feat(quota): enforce CI build minutes for Forgejo Actions #102
No reviewers
Labels
No milestone
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
codefloe/forgejo-codefloe!102
Loading…
Reference in a new issue
No description provided.
Delete branch "feat/ci-quota-enforcement"
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 #94, phase 2 of the CI build minutes quota work, on top of #100.
Phase 1 made CI minutes countable. This phase makes them matter.
The rule is that work which has not started can be refused, and work that is already executing is never interrupted.
A job no runner has taken has consumed nothing, so cancelling it costs the owner a retry.
A job mid-execution has already spent its minutes, and killing it wastes them and throws the result away.
What changed
Evaluator
services/codefloe/quota_ci.Evaluateanswers whether an owner may start CI work booked to a source.It loads the owner's groups with
quota.GetGroupsForUser, keeps the rules counted in seconds that apply to the subject, and evaluates them with the existingGroupList.Evaluate, so a limit of-1is unlimited and the most permissive group still wins.When no rule applies it falls back to
[quota.ci.default] TOTAL.With
[quota] ENABLEDor[quota.ci] ENABLEDoff it returns immediately, before touching the database.The refusal carries the rule that caused it, its limit and the usage compared against it, because a run that vanishes without a reason is worse than no quota at all.
Enforcement points
At run creation, in
InsertRun.An owner over quota still gets the run; it is inserted and then immediately cancelled, carrying a new pre-execution warning.
Creating and cancelling is better than refusing to create: a run that never appears leaves the user with a push that silently did nothing.
As a backstop, in
PickTask.An owner can cross the limit while jobs are already queued, and those must not slip through when a runner asks for work.
The pick unwinds its transaction so the job is not left half-assigned, the run's unstarted jobs are cancelled with the same warning, and the runner is told there is no task for it, which is what it is told when no job matches it anyway.
Surfacing the reason
WarningCodeCIQuotaExceededlives inmodels/actions/pre_execution_warnings_codefloe.goat offset 1000, well clear of upstream's enum, the way thetime:limit subjects do.The only edit to the upstream file is one
casearm delegating to the fork's translator.The run view already renders warnings, so the user gets a sentence naming the quota, how much they have used and what their limit is.
A trap the new subjects had set
GroupList.Evaluatedenies any subject that no group in the list has a rule for.That was safe while every rule was about stored bytes. It is not safe now: putting a user in a quota group that holds a single
time:ci:allrule stopped that user from pushing at all, because nothing in their group mentioned bytes.The integration tests found this immediately, since a CI-minutes group is exactly what an administrator would create to use this feature.
Groups are now consulted only about units they actually limit, and a subject that no group limits falls back to the default for its unit.
The reverse case is fixed too: a group of only
size:rules no longer denies CI time.Notes for the reviewer
Three deviations from the issue worth a look.
The evaluator is in
services/codefloe/quota_ci, notmodels/codefloe/quota_cias the issue suggested.It has to reuse
quota.Ruleandquota.Group, andmodels/quotaalready importsmodels/codefloe/quota_cifor the ledger, so putting it there would be an import cycle.models/quota/group.goneeded a small edit for the unit fix described above, which the issue did not anticipate.It is seven lines, and everything it calls lives in
models/quota/group_codefloe.go.models/quota/used_codefloe.gogainedGetUsedTimeForUser.GetUsedForUserruns eight aggregate queries over every repository, attachment, artifact and package an owner has, which is far too much to do each time a runner asks whether it may start a job.Rules counted in seconds never read the size half of
Used, so the evaluator loads only the time half.The
PickTaskbackstop cancels the run the refused job belongs to, not every queued run the owner has.Other queued runs are cancelled the same way the next time a runner asks for them.
Checklist
Tests for Go changes
*_test.gofor unit tests.tests/integrationdirectory if it involves interactions with a live Forgejo server.make pr-gobefore pushing.Unit tests cover the evaluator (unlimited, the default fallback, the disabled switch, per-source subjects, rules in the wrong unit), the group unit fix, and rendering the new warning.
Integration tests cover the three lifecycle cases from the issue: a push over quota lands as a cancelled run with the reason, a job already running when the limit is crossed is left alone, finishes normally and is billed, and a queued job is cancelled when a runner asks for it.
An unlimited rule and the feature switched off are covered too.
make lint-goruns clean here against the toolchain pinned ingo.mod.Documentation
[quota.ci] ENABLEDis documented by its comments incustom/conf/app.example.iniandmodules/setting/codefloe_quota_ci.go, both updated to say that it now enforces as well as records.Release notes
470f623c514263dcc82b@ -0,0 +1 @@feat(quota): CI build minutes are now enforced for Forgejo Actions. When `[quota.ci].ENABLED` is on and an owner is over a `time:` quota rule, a new run is created and immediately cancelled carrying a warning that names the quota, and a job still queued when the limit is crossed is cancelled the next time a runner asks for it. Work that is already executing is never interrupted: those minutes are spent either way. An owner in no quota group with a `time:` rule is held to `[quota.ci.default].TOTAL`, which is unlimited by default. A quota group whose rules are all about CI time no longer denies storage operations, and one whose rules are all about stored bytes no longer denies CI time.remove that - and also 100.md
4263dcc82b46b95785c6Review
Verified against the branch head; findings ranked by severity, refuted candidates at the end.
Bugs
1. Quota refusal in
PickTaskstalls the runner queueservices/actions/codefloe_quota_ci.go:124,services/actions/task.go:61cancelPickedRunOverQuotareturnsErrNoMatchingJobFoundwithout callingIncreaseTaskVersion.FetchTask(routers/api/actions/runner/runner.go:184-219) then repliesTask=nil, TasksVersion=latestVersion; the runner stores that and skipsPickTaskon every following poll until something else bumps the version.Cancelling a job does not bump it (
models/actions/run_job.go:230only bumps on a transition to Waiting).Effect: after one over-quota pick, jobs of under-quota owners queued behind it, and the over-quota owner's remaining runs, sit until an unrelated run is inserted.
The integration test masks this by forcing
runner.lastTasksVersion = 0(tests/integration/actions_quota_ci_test.go:169).Even with a version bump, each poll drains at most one run and returns no task, so N queued runs cost N polls of starvation.
Suggested fix: bump the version in
cancelPickedRunOverQuota, and preferably retry the pick insidePickTaskafter a refusal instead of returning "no task".2. Over-quota run with every job skipped stays
Waitingforeverservices/actions/notifier.go:899The early
return cancelUnstartedJobs(ctx, run)skipsComputeExistingRunStatus/UpdateRun.Jobs already
Skippedby server-sideifevaluation areIsDone(), socancelUnstartedJobstouches nothing and noUpdateRunJobrecomputes the run status.The run is inserted as
Waitingand never reaches a terminal state (counted as active by concurrency/cancel-previous queries;ActionRunNowDonenever fires).Keep the status recomputation after the cancel; only
checkJobsOfRunneeds to be skipped.3.
GroupList.Evaluateand the CI evaluator disagree on time subjectsmodels/quota/group_codefloe.go:44,services/codefloe/quota_ci/enforce.go:95-138evaluateDefaultForUnitreturnstruefor any non-byte subject, soEvaluateForUser(…, time:ci:all)(reachable viaGET /user/quota/check?subject=time:ci:all,routers/api/v1/shared/quota.go:41) says "allowed" for an owner whose[quota.ci.default]is exhausted, whileInsertRun/PickTaskcancel their runs.The real seconds default lives in a parallel copy:
defaultGroupsduplicatesEvaluateDefault,applicableGroupsduplicatesrelevantTo.Fix at the model: build the seconds default from
setting.QuotaCI.Default.TotalinevaluateDefaultForUnit; thendecide()reduces togroups.Evaluateplus the refusing-rule lookup and both copies go away.4. Storage semantics change for groups with no usable rule (behaviour change, possibly intentional)
models/quota/group.go:211Upstream: an owner in a group whose rules match nothing is denied.
Now
relevantTodrops a group with zero rules (or only mixed-unit rules) and falls through to the instance default, which is unlimited by default.An admin using an empty group as a deny-all placeholder silently loses that.
This applies to every upstream byte-subject caller, is not covered by tests, and is not mentioned in the release note.
5. Quota warning survives a successful rerun
services/actions/codefloe_quota_ci.go:46,services/actions/rerun.go:87Rerun resets job status but keeps
PreExecutionWarningCodes, so a run cancelled over quota and rerun after the limit was raised still shows "This run was cancelled before it started…".Conversely the dedup keeps the first used/limit numbers if it is refused again.
6. Run flips to
Cancelledwhile a task is still executingservices/actions/codefloe_quota_ci.go:98In the
PickTaskpath, cancelling the blocked/waiting siblings of a running job recomputes the run viaAggregateJobStatus, wherehasCancelledbeatshasRunning(models/actions/run_job.go:274), stampingStoppedwhile job A is still running.The test only asserts job statuses, not
run.Status.Worth deciding whether this is acceptable given the "leave running work alone" design.
7. Minor
slices.Containsdedup and append the warning twice (codefloe_quota_ci.go:117).cancelUnstartedJobs, the caller'srunhas a staleVersion;consistencyCheckRun→FailRunPreExecutionErroron that same object would hitErrActionRunOutOfDate.cancelUnstartedJobsre-implementskillRun(services/actions/run.go:17) minus clearingNeedApproval; a cancelled approval-gated run keeps its approve button.Efficiency
task.go:61: the check runs afterCreateTaskForRunnerhas inserted the task, steps and updated the job, then rolls it all back. Checking the owner before materialising the task avoids a write plus rollback per refused poll.notifier.go:884: the ledger scan plus groups load (N+1LoadRules) runs once per workflow file per push inside the insert transaction; evaluating once per owner per notify would do.Simplification / dead code
enforce.go:84return Decision{}is unreachable and encodes "refused by nothing".codefloe_quota_ci.go:65ciQuotaLimit's"unlimited"branch is dead by its own comment;util.SecToTimeinline suffices.pre_execution_warnings_codefloe.go:31default arm is unreachable (upstream's switch only dispatches the one code).group_codefloe.go:18nil guard is unreachable; the caller already handles nil.Checked and not an issue
CreateCommitStatusinside the tx and again after commit:createCommitStatusskips when state and description are unchanged (services/actions/commit_status.go:115).Versionbreaking the parse-error path: the placeholder job is inserted asStatusFailure, nothing is cancelled, no version bump.Summary: the enforcement logic and tests are solid for the happy paths, but #1 is a real stall for shared runners and #2 leaves runs stuck; both should be fixed before merge. #3 and #4 are semantic gaps between the two evaluators that a model-level fix would close and would also delete the duplicated group/default code.
46b95785c6acf83d1813All seven findings were real. Reworked in
acf83d1; verification notes below.Bugs
1. Runner queue stall. Confirmed:
run_job.go:230only bumps the task version on transitions to Waiting, so cancelling never bumps it, andFetchTaskhands the runner a version it then never gets past.Fixed on both axes you suggested.
PickTasknow cancels a refused run and retries the pick in the same request, bounded at 10 refusals, because the selection keeps offering the same job until it leaves the queue — returning early would be the head-of-line block.cancelPickedRunOverQuotaalso callsIncreaseTaskVersion, so other runners learn the queue moved.You were right that the test masked this. It no longer resets
lastTasksVersionbefore asserting; it reads the version from the model either side of the refusal. Removing theIncreaseTaskVersioncall fails that assertion, so it has teeth.2. All-skipped run stuck at Waiting. Confirmed. The cancel path now ends in
settleRunStatus, which recomputes from a freshly loaded run — that also closes the stale-Versionhazard you list under #7, since the caller's copy is never written back.TestActionsQuotaCISkippedRunStillSettlescovers it and fails without the fix.3. The two evaluators disagreed. Confirmed reachable via
GET /user/quota/check?subject=time:ci:all.Fixed at the model as you suggested.
defaultRuleForgives each unit its own default,evaluateDefaultForUnituses it, anddecide()is now three lines over a newGroupList.EvaluateWithRule.applicableGroupsanddefaultGroupsare gone. A table test assertsdecide()andGroupList.Evaluateagree across usages and group shapes.One thing fell out of this worth flagging: with the duplication gone, CI time inherits upstream's rule that a group grants what its rules mention. A group carrying only
time:ci:externalno longer implicitly grants Actions. I kept that rather than special-casing seconds — consistency between the two paths was the bug — but it made the refusal message wrong, so refusals now distinguish an exhausted allowance from an absent one, withWarningCodeCIQuotaNotGrantedand its own string. Reporting "quota builtin-default-rule is used up (0 seconds of unlimited)" would have been worse than the original inconsistency. Documented inapp.example.iniand the release note.4. Empty groups as deny-all. Not intentional, and worse than the mixed-unit case you describe: an empty group has no rule in any unit, so it was dropped and became allow-all.
groupLimitsUnitnow keeps a group that has no rules, and keeps one whose rules are unreadable, setting aside only groups whose every rule is a valid limit on another unit.TestCodefloeEmptyGroupStillDeniespins both subjects.5. Warning survives a rerun. Confirmed at
rerun.go:87.RerunAllJobsnow clears the CI quota warning and adds the two columns. Only that warning is cleared — the permissions warning isn't recomputed on rerun, so dropping all of them would lose it.6. Run flips to Cancelled with a task running. Confirmed, and the consequence is worse than display: reaching a done status fires
ActionRunNowDone, so completion webhooks fire while a job is still executing and the real completion is then silent.Cancelling immediately, since deferring head-of-line blocks the runner. Queued siblings are cancelled through
UpdateRunJobWithoutNotificationwhen a task is still in flight, so no completion notification fires; the run is settled again when that last job reports in. The run still reads Cancelled during that window, which I did not fix, since the alternative is reorderingAggregateJobStatusfor every run in the instance.7. Minors. The concurrent-append race actually surfaces as
ErrActionRunOutOfDate, not a doubled warning, because of the optimistic version column — the loser is now tolerated, since it is looking at a run another request already explained.NeedApprovalis cleared, matchingkillRun.Efficiency
notifier.go: taken, in the sense that the evaluator no longer callsGetUsedForUser. Per-notify caching I left alone — it needs plumbing throughInsertRun's signature for a saving only visible on a push touching many workflow files.task.go: not taken. The owner is only known once a job is selected, which happens insideCreateTaskForRunner; an instance-wide runner can be offered any owner's job. Checking earlier means either restructuring that upstream function or pre-computing over-quota owners on every poll. The write plus rollback is bounded by the retry limit and only happens when someone is over quota.Simplification
All four taken: the unreachable
return Decision{}andapplicableGroupsare gone with the rewrite,ciQuotaLimitis gone, the warning translator no longer has a default arm. The nil guard inrelevantTostayed and is now genuinely reachable, sinceEvaluateWithRulecalls it afterEvaluatehas returned.Verification
make lint-goclean,fmt-check/tidy-check/swagger-check/lint-swagger/swagger-validate/lint-editorconfig/lint-localepass, full./models/... ./services/...unit suite and the wholeTestAction*andTestQuota*integration suites pass. Seven integration tests now, four new unit tests. The two blocking fixes were mutation-checked: each fails when its fix is removed.Re-review of
acf83d1Verified against the new head.
Unit tests (
models/quota,models/actions,services/codefloe/quota_ci) and the fullTestActionsQuotaCI*integration suite pass locally on sqlite.Most of the fixes hold up; one of them introduces a new bug.
New bug: the in-flight cancel path drops
ActionRunNowDoneservices/actions/codefloe_quota_ci.go:149-166(cancelUnstartedJobQuietly,settleRunStatus)The comment says the completion notification is "held back" and the run "is settled again when that last job reports in".
Neither happens:
cancelUnstartedJobQuietlycallsUpdateRunJobWithoutNotification, which itself runsComputeRunStatusand writes the run (models/actions/run_job.go:244-250). WithhasCancelledbeatinghasRunning, the run is written asCancelledwithStopped = nowat cancel time.settleRunStatus(quietly=true)afterwards is a no-op, since no column changes.UpdateRunJob(services/actions/notifier.go:944-958) loadspriorRun, which is alreadyCancelled, sosendActionRunNowDoneNotificationIfNeededseespriorRun.Status.IsDone()and does nothing.Net effect: the done-notification (webhooks, notifications) never fires for any run cancelled while a job was executing, and
Stoppedexcludes the running job's remaining time.The previous revision fired it early; this one fires it never.
TestActionsQuotaCICancelsQueuedWorkButNotRunningWorkfinishes the running task but asserts only the task status and the billed seconds, not the run status or the notification, so it passes.Suggested fix: while a task is in flight, do not write a done status to the run at all.
Update the queued jobs' rows directly (
db.GetEngine(ctx).ID(job.ID).Cols("status", "stopped").Update(job)) instead of going throughUpdateRunJobWithoutNotification, and skipsettleRunStatusin that case.The run then stays
Running, and the last job's completion transitions itRunning → Cancelledthrough the normalUpdateRunJobpath, with a correctStoppedand a single notification.Add an assertion after
quotaCIFinishTaskthat the run isCancelledwithStoppedat or after the finish time, and ideally a notifier mock assertingActionRunNowDonefired exactly once.Minor
services/actions/rerun.go:131:RerunJob(single-job rerun) does not clear the warning; onlyRerunAllJobsdoes. After a quota cancel every job isCancelled, so "re-run this job" on one of them is a realistic path and still shows the stale banner.Versionnote is only closed inside the cancel path.notifier_helper.go:491still passes the caller'sruntoconsistencyCheckRun, whoseFailRunPreExecutionErrorwould hitErrActionRunOutOfDateon an over-quota push whose workflow also has an unknownneeds. Outcome is a logged error rather than a broken run, so low.Verified as fixed
IncreaseTaskVersionincancelPickedRunOverQuota, test asserts the version moved.settleRunStatusre-reads the run; the all-skipped test fails without it.EvaluateWithRuleanddefaultRuleFormakedecide()andGroupList.Evaluateshare one code path; the "not granted" split is the correct consequence and the message reads right.groupLimitsUnitkeeps empty and unreadable groups.NeedApprovalcleared,ErrActionRunOutOfDatetolerated), and the dead-code removals.Summary: one blocking regression (lost completion notification and wrong
Stoppedwhen a job is in flight), two minors; everything else in the rework checks out.acf83d1813cd459d9493The regression is real and my comment described behaviour the code did not have. Fixed in
cd459d9.The lost notification
Both halves verified.
UpdateRunJobWithoutNotificationrecomputes and writes the run itself (run_job.go:244-250), so my "quiet" cancel still stampedCancelledwithStopped = now, andsendActionRunNowDoneNotificationIfNeeded(notifier.go:839) requires!priorRun.Status.IsDone(), so the real completion then fired nothing. Fires early became fires never, with aStoppedthat excluded the running job.Taken as suggested: while a task is in flight the run is not touched at all.
cancelUnstartedJobRowOnlywrites the job row directly withdb.GetEngine(ctx).ID(job.ID).Cols("status", "stopped").Update(job)—ActionRunJobhas no version column, so this is whatUpdateRunJobWithoutNotificationdoes minus the run recompute — andsettleRunStatusis skipped entirely in that case. The run staysRunninguntil the last job reports in and moves itRunning → Cancelledthrough the ordinary path, with one notification and aStoppedthat includes the work.Three assertions now pin it, after the cancel and after the finish:
Cancelled, via anotify_service.NotifiermockReverting
cancelUnstartedJobRowOnlyto the old call fails two of them, so they hold the behaviour rather than describe it.I did not take the
Stoppedtimestamp assertion. The test fabricates a stop time five minutes ahead so the billed duration is non-zero, while the run stampsStoppedfrom the clock when it settles, so the two are not comparable. Asserting only that it is set, with a comment saying why.Minors
RerunJobnow clears the warning as well, onjob.Runbefore itsUpdateRun. You are right that it is the realistic path: after a quota cancel every job isCancelled, so "re-run this job" is what a user reaches for.The stale
Versionis now closed generally rather than only inside the cancel path.settleRunStatuscopies status, started, stopped and version from the freshly loaded run back onto the caller's, so the objectInsertRunhands toconsistencyCheckRunis current andFailRunPreExecutionErroron the unknown-needspath no longer hitsErrActionRunOutOfDate.Verification
make lint-goclean,fmt-check/tidy-check/swagger-check/lint-editorconfig/lint-localepass, full./models/... ./services/...unit suite green, andTestAction*,TestQuota*,TestAPIQuota*,TestRerun*all pass on sqlite.