feat(quota): let an external CI ask whether it may start work #104
No reviewers
Labels
No milestone
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
codefloe/forgejo-codefloe!104
Loading…
Reference in a new issue
No description provided.
Delete branch "feat/quota-ci-preflight-check"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Implements #98, phase 3b of the CI build minutes quota work, on top of #102 (the evaluator) and #103 (the reporter identity and the ingest endpoint).
Phase 3a made an external CI system's minutes visible. This makes them enforceable, by letting that system ask before it starts rather than only reporting after it finishes.
This is the Forgejo half. The Crow CI side is tracked in the Crow repository and is listed at the bottom so the two stay in step.
What changed
The endpoint
It sits on the reporter route stack the usage endpoint already uses, so it authenticates with the same credential and a user token is refused exactly as it is there.
sourceis the authenticated reporter, never a query parameter, so a reporter can only ask about its own budget. A?source=actionsin the request buys nothing; there is a test for that.allowedis the field to branch on.reasonis prose meant to be shown to whoever triggered the work, and is not to be parsed. It names the rule that refused, or, when the owner has no CI allowance at all rather than a spent one, the rule an administrator would have to add, since that is a configuration to fix rather than something to wait out.classis validated against the same shape the ledger stores but does not change the answer yet: per-class subjects such astime:ci:class:macosare a later phase. Validating it now means a reporter learns its class name is unusable while it is asking permission, rather than when the minutes it already spent are refused by the usage endpoint.Remaining is answered by the model, not the caller
A verdict cannot answer "how much is left", so
GroupList.RemainingForis new inmodels/quota/group_codefloe.go. It walks the same rules, in the same order and with the same precedence, asEvaluate: the strictest matching rule in a group binds, the most generous group wins, and an owner no group of theirs limits falls back to the instance default for the subject's unit.The point of putting it beside
Evaluaterather than working it out in the service is that the number and the yes-or-no cannot drift. A caller told to go ahead with nothing left to spend, or refused while holding a budget, is a contradiction an external CI cannot act on.TestCodefloeRemainingForAgreesWithEvaluateasserts the two agree across every combination of group shape, subject and spend.-1means unlimited, so a caller counts down a real number or knows there is nothing to count.No reservation
Answering the check reserves, holds and decrements nothing, which the tests assert against the ledger.
An external system can therefore be told yes, start a job, and run past the limit before it finishes. That is accepted. The overshoot is bounded by one job per reporter, and the alternative is a reservation protocol that has to survive every way a remote system can die: crashed schedulers holding reservations forever, jobs that never report completion, and a lease expiry to clean up after both. The in-flight estimate from #100 already makes the same choice for Forgejo Actions.
Files
models/quota/group_codefloe.go—RemainingFor, with the per-rule, per-group and instance-default helpers behind itmodels/quota/group_codefloe_test.go— unlimited, spent, the strictest rule binding, the most generous group winning, the default fallback, and agreement withEvaluateservices/codefloe/quota_ci/enforce.go—DecisiongainsRemaining, filled in wherever a decision is takenservices/codefloe/quota_ci/check.go— new: class validation, repository resolution, evaluation, and the refusal proseservices/codefloe/quota_ci/check_test.go— new: the two shapes of refusal reasonservices/codefloe/quota_ci/enforce_test.go— remaining on permission, on refusal, and with the feature offmodules/structs/codefloe_quota_ci.go—QuotaCICheckrouters/api/v1/codefloe/quota_ci.go— the handlerrouters/api/v1/codefloe/quota_ci_reporter.go— one route added to the reporter stackrouters/api/v1/swagger/codefloe_quota_ci.go,templates/swagger/v1_json.tmpl— the response definition and the regenerated spectests/integration/api_quota_ci_check_test.go— new: permission and refusal against a real rule, headroom shrinking as usage is reported, the answer being the owner's rather than the repository's, per-source attribution, every reporter drawing on one external allowance, the instance default, unknown repositories, unusable classes, that asking bills nothing, that an unauthenticated caller, an unknown token, a user token and a query-string token are all refused, and the disabled-feature caseBehaviour change
Nothing changes for an instance that has not turned the ledger on: the route is mounted only when
[quota.ci] ENABLEDis set, and without a matching reporter token every request to it is a 401.Once it is on, an existing reporter that never calls the check is unaffected: its usage is still ingested and still counted.
Crow CI side
Tracked in the Crow repository, listed here so the two halves stay in step.
reason, so the user sees why nothing ran instead of finding a silently missing pipelineFailing open is deliberate, and this side is built for it: with the feature off the route is not mounted, so a caller already has to treat a non-200 as permission. A Forgejo outage must not stop every pipeline on the instance, and the ingest path still bills the minutes afterwards, so an owner cannot use an outage to run free work indefinitely.
Testing
go test ./models/quota/... ./services/codefloe/... ./services/actions/... ./modules/setting/... ./routers/api/v1/...passesTestAPIQuotaCI*,TestActionsQuotaCI*,TestQuota*,TestAPIQuota*) passes on sqlitegolangci-lintis clean on every package touched, andmake swagger-checkpassesReview
The core logic is sound.
A 3,783-case property probe over rule/group/usage combinations found no disagreement between
RemainingForandEvaluate, the reporter router and auth wiring are correct, and the disabled-feature path behaves as documented.What should change before merge is the user-facing prose and one documented guarantee.
Should fix
reasoncan namebuiltin-default-rule(services/codefloe/quota_ci/check.go:74).When the instance default refuses (owner in no seconds-limiting group),
EvaluateWithRulereturns the synthetic rule fromdefaultRuleFor, so the message tells the user that quota rulebuiltin-default-ruleis used up.No such rule exists in any quota group; the fix an admin needs is
[quota.ci.default] TOTAL.Repro:
QuotaCI.Default.Total=600,user2in no group, 600s reported this period,GET /quota/ci/check?repo=user2/repo1.util.SecToTime(0)renders as an empty string (check.go:75).formatTimeonly prints values>= 1, so a zero-limit rule (the deny-all rule the PR's own tests build viaquotaCIRule(t, user2, 0)) with nothing spent producesthe CI time quota "ci-enforcement" is used up: spent of this period.Same for
Used == 0with any limit."Overshoot is bounded by one unit of work per reporter" is not true (
check.go:24, swagger description,release-notes/104.md).InFlightSecondsonly countsaction_taskrows, so nothing moves the ledger between an external check and its usage report.A scheduler that checks a 20-job matrix in one burst with 60s left gets 20 permits, each seeing
remaining_seconds=60.Either state the real bound (permits granted before the first report lands) or give reporters an in-flight signal, e.g. an optional "started" report that
loadCodefloeTimeincludes for external sources.repositoryForignores repo redirects (services/codefloe/quota_ci/ingest.go:133, pre-existing from #103 but now shared byCheck).GetRepositoryByOwnerAndNamedoes not consultrepo_model.Redirect.Under the documented "non-200 means start the work" contract, a CI still configured with the old name gets a 404 from
/check(starts anyway) and a 404 from/usage(minutes never booked), so a rename silently exempts that pipeline from quota.Worth tidying
Class validation is copied verbatim from
ingest.go:72-78and the result is discarded (check.go:39-44).The stated purpose (agree with what ingest will accept) is exactly what duplication cannot guarantee.
Extract one
normalizeClass(string) (string, error)used by bothrecordFromandCheck.The shared 422 message also omits two rules
IsValidQuotaCINameenforces: max 40 chars and no leading-/_, soclass=-macosis told it must be "lowercase alphanumeric with dashes or underscores", which it already is.refusalReasonis a third copy of the Actions warning prose (check.go:68).services/actions/codefloe_quota_ci.goalready maps the sameDecisiontoactions.workflow.ci_quota_warning/ci_quota_not_granted_warning.The struct doc says
reasonis "never to be parsed", yetapi_quota_ci_check_test.go:103and:176grep it, which is what a Crow plugin will also do to tell exhausted from not-granted.Consider a shared explain helper, and/or a structured
reason_code(exceeded|not_granted) plusrule,used_seconds,limit_secondsalongside the prose.RemainingForis a third hand-mirrored precedence walk (models/quota/group_codefloe.go:157).decide()now runsEvaluateWithRuleand thenRemainingForover the same groups, including on the Actions pick-task path, and the "number and verdict agree" property is held only by a six-fixture table test.One
evaluate(used, subject) (allowed bool, rule *Rule, remaining int64)withEvaluate/EvaluateWithRule/RemainingForas projections would remove ~90 lines of shadow logic and the double walk.Not a live bug today, but the next precedence change (per-class subjects, an upstream change to
Group.Evaluateon merge) has to be mirrored by hand.Doc contract vs. sentinel (
enforce.go:34,group_codefloe.go:150).Both docs say
Remainingis "above zero exactly when Evaluate passes", but the unlimited path returns-1, and the agreement test asserts!= 0, so the documented contract is untested and false.The
allowedvar comment ("whenever nothing stands in the way") is also stale now thatdecide()no longer returns it.Order-coupled subtests (
tests/integration/api_quota_ci_check_test.go:85)."what is left goes down" relies on the earlier 600 headroom, "over their quota" on the prior 500 spend, and "asking reserves nothing" hard-codes 700 as their sum, so
-run TestAPIQuotaCICheck/askingin isolation fails.Separately,
quotaCIRuleandquotaCISubjectRuleinactions_quota_ci_test.godiffer only in the subject constant;quotaCIRulecan delegate.fe76cac8bace8712a8c3All nine addressed. Verified each claim against the code first; findings 1-4 all reproduce.
Should fix
1.
reasonnamingbuiltin-default-rule— the three ways CI work can be refused are now told apart onDecisionas aReason:exceeded,default_exceeded,not_granted. Ondefault_exceededthe rule is not named at all, and the prose names[quota.ci.default] TOTALand thetime:ci:allrule that would override it.This defect was not only in the API:
services/actions/codefloe_quota_ci.gobuilds its warning from the sameDecision, so a run cancelled against the instance default was blamingbuiltin-default-rulein the run banner too. Fixed there as well, withWarningCodeCIQuotaDefaultExceededandactions.workflow.ci_quota_default_warning. That is one more identifier on the fork's existing case arm inpre_execution_warnings.goand no other upstream edit.2.
util.SecToTime(0)rendering empty — confirmed:formatTimeonly prints values>= 1, so everything below one second renders as nothing. AddedHumanSeconds, which spells out0 seconds. Exported, because the run view renders the same numbers through the translation and the two should not disagree; both paths now use it. Covered at the numbers a deny-all rule actually produces, inTestQuotaCIRefusalReasonAlwaysReadsAsASentenceand an integration subtest against a reallimit = 0rule.3. The overshoot bound — you are right, and
InFlightSecondsreading onlyaction_taskis exactly why. Reworded rather than adding an in-flight signal: the issue scopes reservation out, and an external in-flight report is a contract change that belongs with the per-class work. The doc, the swagger description and the release note now state the real bound: nothing moves the ledger until the work is reported, so a scheduler asking about twenty jobs in one burst gets twenty permits each seeing the same budget, and the owner can end the period that far over.4. Repo redirects — confirmed, and worse than a 404:
NewRedirectis written on both rename and transfer, so either one silently exempted the pipeline.repositoryFornow falls back torepo_model.GetRedirectunder the named owner, which covers both cases (a rename records the old name under the same owner, a transfer the unchanged name under the old one). The repository is re-read by ID rather than assumed to still belong to the owner named, so after a transfer the minutes go to whoever holds it now. Real not-found still returns the original error, so an unknown repository still reads as one. Both endpoints get this, since they share the resolver.TestAPIQuotaCICheckFollowsARenamerenamesuser2/repo1and asserts the old name still resolves for the check and still bills on the usage endpoint.Deliberately not using
redirect.LookupRepoRedirect: it takes a doer and does a permission check, and a reporter is not a user.Worth tidying
5. Class validation — extracted
normalizeClass, used by bothrecordFromandCheck. The message now states all three rules, including the 40-character bound (maxQuotaCINameLengthexported assetting.MaxQuotaCINameLength) and the leading-/_. Tested againstLinux,linux/x86,-macosand a 41-character name.6. Prose as a contract — added
reason_codeplusrule,used_secondsandlimit_seconds, so a Crow plugin branches on the code and only displays the prose. The integration tests now assert onreason_code, and only check the prose where the prose itself is the thing under test (that it does not name the built-in rule, that it never has a gap where a duration should be).Not sharing a single explain helper with the Actions path: one produces plain JSON prose, the other a translated HTML fragment with escaped arguments. What was worth sharing is the classification, and that now lives on
Decisionand drives both.7. The third precedence walk — collapsed.
GroupList.Assessreturns{Allowed, Remaining, Rule, FromDefault}from one walk, andEvaluateWithRuleandRemainingForare one-line projections of it.decide()calls it once, so the pick-task path no longer walks twice.The verdict is still
Evaluate's rather than recomputed, which keeps the upstream diff where it is. RewritingEvaluateto delegate would replace an upstream function body and make the merge surface worse, not better.8. Doc vs. sentinel — the contract is now stated as it is tested:
Remainingis zero exactly when the subject is refused, and otherwise positive orRemainingUnlimited. The staleallowedcomment now says what it is: the answer given while the feature is off.9. Order-coupled subtests — each subtest now sizes its own rule against
ciTimeSpent, what the ledger actually holds, instead of what the subtests before it happened to book. Verified by runningasking,an_owner_over,what_is_left,the_instance-wideanda_deny-allindividually with-test.run; all pass alone. "asking reserves nothing" now reads the ledger before and after rather than hard-coding a total.quotaCIRuledelegates toquotaCISubjectRule.Verification
go test -p 1 ./models/quota/... ./models/actions/... ./models/codefloe/... ./services/codefloe/... ./services/actions/... ./modules/setting/... ./modules/structs/... ./routers/...passesTestAPIQuotaCI*,TestActionsQuotaCI*,TestQuota*,TestAPIQuota*pass on sqlitegolangci-lintovermodels/ services/ routers/ modules/setting/ modules/structs/ tests/integration/reports only 11 pre-existingslicesbackwardfindings, none in a file this branch touchesmake swagger-checkpasses