codefloe/forgejo-codefloe
Watch
4
12
Fork
You've already forked forgejo-codefloe
0

feat(quota): enforce CI build minutes for Forgejo Actions #102

Merged
pat-s merged 1 commit from feat/ci-quota-enforcement into v16.0/forgejo-codefloe 2026-08-29 10:11:55 +00:00
Owner

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.Evaluate answers 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 existing GroupList.Evaluate, so a limit of -1 is unlimited and the most permissive group still wins.
When no rule applies it falls back to [quota.ci.default] TOTAL.
With [quota] ENABLED or [quota.ci] ENABLED off 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

WarningCodeCIQuotaExceeded lives in models/actions/pre_execution_warnings_codefloe.go at offset 1000, well clear of upstream's enum, the way the time: limit subjects do.
The only edit to the upstream file is one case arm 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.Evaluate denies 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:all rule 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, not models/codefloe/quota_ci as the issue suggested.
It has to reuse quota.Rule and quota.Group, and models/quota already imports models/codefloe/quota_ci for the ledger, so putting it there would be an import cycle.

models/quota/group.go needed 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.go gained GetUsedTimeForUser.
GetUsedForUser runs 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 PickTask backstop 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

  • I added test coverage for Go changes...
    • in their respective *_test.go for unit tests.
    • in the tests/integration directory if it involves interactions with a live Forgejo server.
  • I ran...
    • make pr-go before 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-go runs clean here against the toolchain pinned in go.mod.

Documentation

  • I created a pull request to the documentation to explain to Forgejo users how to use this change.
  • I did not document these changes and I do not expect someone else to do it. [quota.ci] ENABLED is documented by its comments in custom/conf/app.example.ini and modules/setting/codefloe_quota_ci.go, both updated to say that it now enforces as well as records.

Release notes

  • This change will be noticed by a Forgejo user or admin (feature, bug fix, performance, etc.). I suggest to include a release note for this change.
  • This change is not visible to a Forgejo user or admin (refactor, dependency upgrade, etc.). I think there is no need to add a release note for this change.
Implements [#94](https://codefloe.com/codefloe/forgejo-codefloe/issues/94), phase 2 of the CI build minutes quota work, on top of [#100](https://codefloe.com/codefloe/forgejo-codefloe/pulls/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.Evaluate` answers 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 existing `GroupList.Evaluate`, so a limit of `-1` is unlimited and the most permissive group still wins. When no rule applies it falls back to `[quota.ci.default] TOTAL`. With `[quota] ENABLED` or `[quota.ci] ENABLED` off 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 `WarningCodeCIQuotaExceeded` lives in `models/actions/pre_execution_warnings_codefloe.go` at offset 1000, well clear of upstream's enum, the way the `time:` limit subjects do. The only edit to the upstream file is one `case` arm 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.Evaluate` denies 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:all` rule 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`, not `models/codefloe/quota_ci` as the issue suggested. It has to reuse `quota.Rule` and `quota.Group`, and `models/quota` already imports `models/codefloe/quota_ci` for the ledger, so putting it there would be an import cycle. `models/quota/group.go` needed 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.go` gained `GetUsedTimeForUser`. `GetUsedForUser` runs 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 `PickTask` backstop 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 - I added test coverage for Go changes... - [x] in their respective `*_test.go` for unit tests. - [x] in the `tests/integration` directory if it involves interactions with a live Forgejo server. - I ran... - [x] `make pr-go` before 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-go` runs clean here against the toolchain pinned in `go.mod`. ### Documentation - [ ] I created a pull request to the documentation to explain to Forgejo users how to use this change. - [x] I did not document these changes and I do not expect someone else to do it. `[quota.ci] ENABLED` is documented by its comments in `custom/conf/app.example.ini` and `modules/setting/codefloe_quota_ci.go`, both updated to say that it now enforces as well as records. ### Release notes - [x] This change will be noticed by a Forgejo user or admin (feature, bug fix, performance, etc.). I suggest to include a release note for this change. - [ ] This change is not visible to a Forgejo user or admin (refactor, dependency upgrade, etc.). I think there is no need to add a release note for this change.
pat-s force-pushed feat/ci-quota-enforcement from 470f623c51
Some checks failed
testing / backend-checks (pull_request) Has been cancelled
testing / test-unit (pull_request) Has been cancelled
testing / test-e2e (pull_request) Has been cancelled
testing / test-remote-cacher (redis) (pull_request) Has been cancelled
testing / test-remote-cacher (valkey) (pull_request) Has been cancelled
testing / test-remote-cacher (garnet) (pull_request) Has been cancelled
testing / test-mysql (pull_request) Has been cancelled
testing / test-pgsql (pull_request) Has been cancelled
testing / test-sqlite (pull_request) Has been cancelled
testing / frontend-checks (pull_request) Has been cancelled
to 4263dcc82b
Some checks failed
testing / frontend-checks (pull_request) Successful in 1m6s
testing / test-remote-cacher (redis) (pull_request) Has been cancelled
testing / test-remote-cacher (valkey) (pull_request) Has been cancelled
testing / backend-checks (pull_request) Successful in 6m0s
testing / test-unit (pull_request) Has been cancelled
testing / test-pgsql (pull_request) Has been cancelled
testing / test-e2e (pull_request) Has been cancelled
testing / test-mysql (pull_request) Has been cancelled
testing / test-remote-cacher (garnet) (pull_request) Has been cancelled
testing / test-sqlite (pull_request) Has been cancelled
2026-08-28 18:58:25 +00:00
Compare
@ -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.
Author
Owner

remove that - and also 100.md

remove that - and also 100.md
pat-s marked this conversation as resolved
pat-s force-pushed feat/ci-quota-enforcement from 4263dcc82b
Some checks failed
testing / frontend-checks (pull_request) Successful in 1m6s
testing / test-remote-cacher (redis) (pull_request) Has been cancelled
testing / test-remote-cacher (valkey) (pull_request) Has been cancelled
testing / backend-checks (pull_request) Successful in 6m0s
testing / test-unit (pull_request) Has been cancelled
testing / test-pgsql (pull_request) Has been cancelled
testing / test-e2e (pull_request) Has been cancelled
testing / test-mysql (pull_request) Has been cancelled
testing / test-remote-cacher (garnet) (pull_request) Has been cancelled
testing / test-sqlite (pull_request) Has been cancelled
to 46b95785c6
All checks were successful
testing / backend-checks (pull_request) Successful in 5m4s
testing / frontend-checks (pull_request) Successful in 1m1s
testing / test-unit (pull_request) Successful in 5m31s
testing / test-remote-cacher (garnet) (pull_request) Successful in 1m48s
testing / test-mysql (pull_request) Successful in 25m5s
testing / test-remote-cacher (redis) (pull_request) Successful in 1m27s
testing / test-remote-cacher (valkey) (pull_request) Successful in 1m45s
testing / test-e2e (pull_request) Successful in 22m23s
testing / test-sqlite (pull_request) Successful in 46m24s
testing / test-pgsql (pull_request) Successful in 47m26s
2026-08-28 19:10:36 +00:00
Compare
Author
Owner

Review

Verified against the branch head; findings ranked by severity, refuted candidates at the end.

Bugs

1. Quota refusal in PickTask stalls the runner queue
services/actions/codefloe_quota_ci.go:124, services/actions/task.go:61
cancelPickedRunOverQuota returns ErrNoMatchingJobFound without calling IncreaseTaskVersion.
FetchTask (routers/api/actions/runner/runner.go:184-219) then replies Task=nil, TasksVersion=latestVersion; the runner stores that and skips PickTask on every following poll until something else bumps the version.
Cancelling a job does not bump it (models/actions/run_job.go:230 only 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 inside PickTask after a refusal instead of returning "no task".

2. Over-quota run with every job skipped stays Waiting forever
services/actions/notifier.go:899
The early return cancelUnstartedJobs(ctx, run) skips ComputeExistingRunStatus/UpdateRun.
Jobs already Skipped by server-side if evaluation are IsDone(), so cancelUnstartedJobs touches nothing and no UpdateRunJob recomputes the run status.
The run is inserted as Waiting and never reaches a terminal state (counted as active by concurrency/cancel-previous queries; ActionRunNowDone never fires).
Keep the status recomputation after the cancel; only checkJobsOfRun needs to be skipped.

3. GroupList.Evaluate and the CI evaluator disagree on time subjects
models/quota/group_codefloe.go:44, services/codefloe/quota_ci/enforce.go:95-138
evaluateDefaultForUnit returns true for any non-byte subject, so EvaluateForUser(…, time:ci:all) (reachable via GET /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, while InsertRun/PickTask cancel their runs.
The real seconds default lives in a parallel copy: defaultGroups duplicates EvaluateDefault, applicableGroups duplicates relevantTo.
Fix at the model: build the seconds default from setting.QuotaCI.Default.Total in evaluateDefaultForUnit; then decide() reduces to groups.Evaluate plus 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:211
Upstream: an owner in a group whose rules match nothing is denied.
Now relevantTo drops 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:87
Rerun 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 Cancelled while a task is still executing
services/actions/codefloe_quota_ci.go:98
In the PickTask path, cancelling the blocked/waiting siblings of a running job recomputes the run via AggregateJobStatus, where hasCancelled beats hasRunning (models/actions/run_job.go:274), stamping Stopped while 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

  • Two runners picking two jobs of the same run concurrently both pass the slices.Contains dedup and append the warning twice (codefloe_quota_ci.go:117).
  • After cancelUnstartedJobs, the caller's run has a stale Version; consistencyCheckRun → FailRunPreExecutionError on that same object would hit ErrActionRunOutOfDate.
  • cancelUnstartedJobs re-implements killRun (services/actions/run.go:17) minus clearing NeedApproval; a cancelled approval-gated run keeps its approve button.

Efficiency

  • task.go:61: the check runs after CreateTaskForRunner has 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+1 LoadRules) runs once per workflow file per push inside the insert transaction; evaluating once per owner per notify would do.

Simplification / dead code

  • enforce.go:84 return Decision{} is unreachable and encodes "refused by nothing".
  • codefloe_quota_ci.go:65 ciQuotaLimit's "unlimited" branch is dead by its own comment; util.SecToTime inline suffices.
  • pre_execution_warnings_codefloe.go:31 default arm is unreachable (upstream's switch only dispatches the one code).
  • group_codefloe.go:18 nil guard is unreachable; the caller already handles nil.

Checked and not an issue

  • Duplicate commit statuses from CreateCommitStatus inside the tx and again after commit: createCommitStatus skips when state and description are unchanged (services/actions/commit_status.go:115).
  • Stale Version breaking the parse-error path: the placeholder job is inserted as StatusFailure, 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.

## Review Verified against the branch head; findings ranked by severity, refuted candidates at the end. ### Bugs **1. Quota refusal in `PickTask` stalls the runner queue** `services/actions/codefloe_quota_ci.go:124`, `services/actions/task.go:61` `cancelPickedRunOverQuota` returns `ErrNoMatchingJobFound` without calling `IncreaseTaskVersion`. `FetchTask` (`routers/api/actions/runner/runner.go:184-219`) then replies `Task=nil, TasksVersion=latestVersion`; the runner stores that and skips `PickTask` on every following poll until something else bumps the version. Cancelling a job does not bump it (`models/actions/run_job.go:230` only 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 inside `PickTask` after a refusal instead of returning "no task". **2. Over-quota run with every job skipped stays `Waiting` forever** `services/actions/notifier.go:899` The early `return cancelUnstartedJobs(ctx, run)` skips `ComputeExistingRunStatus`/`UpdateRun`. Jobs already `Skipped` by server-side `if` evaluation are `IsDone()`, so `cancelUnstartedJobs` touches nothing and no `UpdateRunJob` recomputes the run status. The run is inserted as `Waiting` and never reaches a terminal state (counted as active by concurrency/cancel-previous queries; `ActionRunNowDone` never fires). Keep the status recomputation after the cancel; only `checkJobsOfRun` needs to be skipped. **3. `GroupList.Evaluate` and the CI evaluator disagree on time subjects** `models/quota/group_codefloe.go:44`, `services/codefloe/quota_ci/enforce.go:95-138` `evaluateDefaultForUnit` returns `true` for any non-byte subject, so `EvaluateForUser(…, time:ci:all)` (reachable via `GET /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, while `InsertRun`/`PickTask` cancel their runs. The real seconds default lives in a parallel copy: `defaultGroups` duplicates `EvaluateDefault`, `applicableGroups` duplicates `relevantTo`. Fix at the model: build the seconds default from `setting.QuotaCI.Default.Total` in `evaluateDefaultForUnit`; then `decide()` reduces to `groups.Evaluate` plus 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:211` Upstream: an owner in a group whose rules match nothing is denied. Now `relevantTo` drops 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:87` Rerun 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 `Cancelled` while a task is still executing** `services/actions/codefloe_quota_ci.go:98` In the `PickTask` path, cancelling the blocked/waiting siblings of a running job recomputes the run via `AggregateJobStatus`, where `hasCancelled` beats `hasRunning` (`models/actions/run_job.go:274`), stamping `Stopped` while 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** - Two runners picking two jobs of the same run concurrently both pass the `slices.Contains` dedup and append the warning twice (`codefloe_quota_ci.go:117`). - After `cancelUnstartedJobs`, the caller's `run` has a stale `Version`; `consistencyCheckRun` → `FailRunPreExecutionError` on that same object would hit `ErrActionRunOutOfDate`. - `cancelUnstartedJobs` re-implements `killRun` (`services/actions/run.go:17`) minus clearing `NeedApproval`; a cancelled approval-gated run keeps its approve button. ### Efficiency - `task.go:61`: the check runs after `CreateTaskForRunner` has 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+1 `LoadRules`) runs once per workflow file per push inside the insert transaction; evaluating once per owner per notify would do. ### Simplification / dead code - `enforce.go:84` `return Decision{}` is unreachable and encodes "refused by nothing". - `codefloe_quota_ci.go:65` `ciQuotaLimit`'s `"unlimited"` branch is dead by its own comment; `util.SecToTime` inline suffices. - `pre_execution_warnings_codefloe.go:31` default arm is unreachable (upstream's switch only dispatches the one code). - `group_codefloe.go:18` nil guard is unreachable; the caller already handles nil. ### Checked and not an issue - Duplicate commit statuses from `CreateCommitStatus` inside the tx and again after commit: `createCommitStatus` skips when state and description are unchanged (`services/actions/commit_status.go:115`). - Stale `Version` breaking the parse-error path: the placeholder job is inserted as `StatusFailure`, 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.
pat-s force-pushed feat/ci-quota-enforcement from 46b95785c6
All checks were successful
testing / backend-checks (pull_request) Successful in 5m4s
testing / frontend-checks (pull_request) Successful in 1m1s
testing / test-unit (pull_request) Successful in 5m31s
testing / test-remote-cacher (garnet) (pull_request) Successful in 1m48s
testing / test-mysql (pull_request) Successful in 25m5s
testing / test-remote-cacher (redis) (pull_request) Successful in 1m27s
testing / test-remote-cacher (valkey) (pull_request) Successful in 1m45s
testing / test-e2e (pull_request) Successful in 22m23s
testing / test-sqlite (pull_request) Successful in 46m24s
testing / test-pgsql (pull_request) Successful in 47m26s
to acf83d1813
Some checks failed
testing / frontend-checks (pull_request) Successful in 1m23s
testing / backend-checks (pull_request) Successful in 5m42s
testing / test-unit (pull_request) Successful in 5m29s
testing / test-remote-cacher (garnet) (pull_request) Successful in 1m49s
testing / test-remote-cacher (valkey) (pull_request) Successful in 1m55s
testing / test-remote-cacher (redis) (pull_request) Successful in 1m29s
testing / test-mysql (pull_request) Successful in 25m19s
testing / test-e2e (pull_request) Successful in 22m35s
testing / test-pgsql (pull_request) Has been cancelled
testing / test-sqlite (pull_request) Has been cancelled
2026-08-29 08:45:45 +00:00
Compare
Author
Owner

All seven findings were real. Reworked in acf83d1; verification notes below.

Bugs

1. Runner queue stall. Confirmed: run_job.go:230 only bumps the task version on transitions to Waiting, so cancelling never bumps it, and FetchTask hands the runner a version it then never gets past.

Fixed on both axes you suggested. PickTask now 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. cancelPickedRunOverQuota also calls IncreaseTaskVersion, so other runners learn the queue moved.

You were right that the test masked this. It no longer resets lastTasksVersion before asserting; it reads the version from the model either side of the refusal. Removing the IncreaseTaskVersion call 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-Version hazard you list under #7, since the caller's copy is never written back. TestActionsQuotaCISkippedRunStillSettles covers 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. defaultRuleFor gives each unit its own default, evaluateDefaultForUnit uses it, and decide() is now three lines over a new GroupList.EvaluateWithRule. applicableGroups and defaultGroups are gone. A table test asserts decide() and GroupList.Evaluate agree 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:external no 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, with WarningCodeCIQuotaNotGranted and its own string. Reporting "quota builtin-default-rule is used up (0 seconds of unlimited)" would have been worse than the original inconsistency. Documented in app.example.ini and 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. groupLimitsUnit now 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. TestCodefloeEmptyGroupStillDenies pins both subjects.

5. Warning survives a rerun. Confirmed at rerun.go:87. RerunAllJobs now 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 UpdateRunJobWithoutNotification when 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 reordering AggregateJobStatus for 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. NeedApproval is cleared, matching killRun.

Efficiency

notifier.go: taken, in the sense that the evaluator no longer calls GetUsedForUser. Per-notify caching I left alone — it needs plumbing through InsertRun'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 inside CreateTaskForRunner; 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{} and applicableGroups are gone with the rewrite, ciQuotaLimit is gone, the warning translator no longer has a default arm. The nil guard in relevantTo stayed and is now genuinely reachable, since EvaluateWithRule calls it after Evaluate has returned.

Verification

make lint-go clean, fmt-check/tidy-check/swagger-check/lint-swagger/swagger-validate/lint-editorconfig/lint-locale pass, full ./models/... ./services/... unit suite and the whole TestAction* and TestQuota* 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.

All seven findings were real. Reworked in `acf83d1`; verification notes below. ## Bugs **1. Runner queue stall.** Confirmed: `run_job.go:230` only bumps the task version on transitions *to* Waiting, so cancelling never bumps it, and `FetchTask` hands the runner a version it then never gets past. Fixed on both axes you suggested. `PickTask` now 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. `cancelPickedRunOverQuota` also calls `IncreaseTaskVersion`, so other runners learn the queue moved. You were right that the test masked this. It no longer resets `lastTasksVersion` before asserting; it reads the version from the model either side of the refusal. Removing the `IncreaseTaskVersion` call 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-`Version` hazard you list under #7, since the caller's copy is never written back. `TestActionsQuotaCISkippedRunStillSettles` covers 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. `defaultRuleFor` gives each unit its own default, `evaluateDefaultForUnit` uses it, and `decide()` is now three lines over a new `GroupList.EvaluateWithRule`. `applicableGroups` and `defaultGroups` are gone. A table test asserts `decide()` and `GroupList.Evaluate` agree 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:external` no 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, with `WarningCodeCIQuotaNotGranted` and its own string. Reporting "quota builtin-default-rule is used up (0 seconds of unlimited)" would have been worse than the original inconsistency. Documented in `app.example.ini` and 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. `groupLimitsUnit` now 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. `TestCodefloeEmptyGroupStillDenies` pins both subjects. **5. Warning survives a rerun.** Confirmed at `rerun.go:87`. `RerunAllJobs` now 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 `UpdateRunJobWithoutNotification` when 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 reordering `AggregateJobStatus` for 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. `NeedApproval` is cleared, matching `killRun`. ## Efficiency `notifier.go`: taken, in the sense that the evaluator no longer calls `GetUsedForUser`. Per-notify caching I left alone — it needs plumbing through `InsertRun`'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 inside `CreateTaskForRunner`; 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{}` and `applicableGroups` are gone with the rewrite, `ciQuotaLimit` is gone, the warning translator no longer has a default arm. The nil guard in `relevantTo` stayed and is now genuinely reachable, since `EvaluateWithRule` calls it after `Evaluate` has returned. ## Verification `make lint-go` clean, `fmt-check`/`tidy-check`/`swagger-check`/`lint-swagger`/`swagger-validate`/`lint-editorconfig`/`lint-locale` pass, full `./models/... ./services/...` unit suite and the whole `TestAction*` and `TestQuota*` 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.
Author
Owner

Re-review of acf83d1

Verified against the new head.
Unit tests (models/quota, models/actions, services/codefloe/quota_ci) and the full TestActionsQuotaCI* 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 ActionRunNowDone

services/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:

  • cancelUnstartedJobQuietly calls UpdateRunJobWithoutNotification, which itself runs ComputeRunStatus and writes the run (models/actions/run_job.go:244-250). With hasCancelled beating hasRunning, the run is written as Cancelled with Stopped = now at cancel time. settleRunStatus(quietly=true) afterwards is a no-op, since no column changes.
  • When the running job finishes, UpdateRunJob (services/actions/notifier.go:944-958) loads priorRun, which is already Cancelled, so sendActionRunNowDoneNotificationIfNeeded sees priorRun.Status.IsDone() and does nothing.

Net effect: the done-notification (webhooks, notifications) never fires for any run cancelled while a job was executing, and Stopped excludes the running job's remaining time.
The previous revision fired it early; this one fires it never.
TestActionsQuotaCICancelsQueuedWorkButNotRunningWork finishes 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 through UpdateRunJobWithoutNotification, and skip settleRunStatus in that case.
The run then stays Running, and the last job's completion transitions it Running → Cancelled through the normal UpdateRunJob path, with a correct Stopped and a single notification.
Add an assertion after quotaCIFinishTask that the run is Cancelled with Stopped at or after the finish time, and ideally a notifier mock asserting ActionRunNowDone fired exactly once.

Minor

  • services/actions/rerun.go:131: RerunJob (single-job rerun) does not clear the warning; only RerunAllJobs does. After a quota cancel every job is Cancelled, so "re-run this job" on one of them is a realistic path and still shows the stale banner.
  • The stale-Version note is only closed inside the cancel path. notifier_helper.go:491 still passes the caller's run to consistencyCheckRun, whose FailRunPreExecutionError would hit ErrActionRunOutOfDate on an over-quota push whose workflow also has an unknown needs. Outcome is a logged error rather than a broken run, so low.

Verified as fixed

  • #1: retry loop bounded at 10, IncreaseTaskVersion in cancelPickedRunOverQuota, test asserts the version moved.
  • #2: settleRunStatus re-reads the run; the all-skipped test fails without it.
  • #3: EvaluateWithRule and defaultRuleFor make decide() and GroupList.Evaluate share one code path; the "not granted" split is the correct consequence and the message reads right.
  • #4: groupLimitsUnit keeps empty and unreadable groups.
  • #5 (all-jobs rerun), #7 (NeedApproval cleared, ErrActionRunOutOfDate tolerated), and the dead-code removals.

Summary: one blocking regression (lost completion notification and wrong Stopped when a job is in flight), two minors; everything else in the rework checks out.

## Re-review of `acf83d1` Verified against the new head. Unit tests (`models/quota`, `models/actions`, `services/codefloe/quota_ci`) and the full `TestActionsQuotaCI*` 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 `ActionRunNowDone` `services/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: - `cancelUnstartedJobQuietly` calls `UpdateRunJobWithoutNotification`, which itself runs `ComputeRunStatus` and writes the run (`models/actions/run_job.go:244-250`). With `hasCancelled` beating `hasRunning`, the run is written as `Cancelled` with `Stopped = now` at cancel time. `settleRunStatus(quietly=true)` afterwards is a no-op, since no column changes. - When the running job finishes, `UpdateRunJob` (`services/actions/notifier.go:944-958`) loads `priorRun`, which is already `Cancelled`, so `sendActionRunNowDoneNotificationIfNeeded` sees `priorRun.Status.IsDone()` and does nothing. Net effect: the done-notification (webhooks, notifications) never fires for any run cancelled while a job was executing, and `Stopped` excludes the running job's remaining time. The previous revision fired it early; this one fires it never. `TestActionsQuotaCICancelsQueuedWorkButNotRunningWork` finishes 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 through `UpdateRunJobWithoutNotification`, and skip `settleRunStatus` in that case. The run then stays `Running`, and the last job's completion transitions it `Running → Cancelled` through the normal `UpdateRunJob` path, with a correct `Stopped` and a single notification. Add an assertion after `quotaCIFinishTask` that the run is `Cancelled` with `Stopped` at or after the finish time, and ideally a notifier mock asserting `ActionRunNowDone` fired exactly once. ### Minor - `services/actions/rerun.go:131`: `RerunJob` (single-job rerun) does not clear the warning; only `RerunAllJobs` does. After a quota cancel every job is `Cancelled`, so "re-run this job" on one of them is a realistic path and still shows the stale banner. - The stale-`Version` note is only closed inside the cancel path. `notifier_helper.go:491` still passes the caller's `run` to `consistencyCheckRun`, whose `FailRunPreExecutionError` would hit `ErrActionRunOutOfDate` on an over-quota push whose workflow also has an unknown `needs`. Outcome is a logged error rather than a broken run, so low. ### Verified as fixed - #1: retry loop bounded at 10, `IncreaseTaskVersion` in `cancelPickedRunOverQuota`, test asserts the version moved. - #2: `settleRunStatus` re-reads the run; the all-skipped test fails without it. - #3: `EvaluateWithRule` and `defaultRuleFor` make `decide()` and `GroupList.Evaluate` share one code path; the "not granted" split is the correct consequence and the message reads right. - #4: `groupLimitsUnit` keeps empty and unreadable groups. - #5 (all-jobs rerun), #7 (`NeedApproval` cleared, `ErrActionRunOutOfDate` tolerated), and the dead-code removals. **Summary:** one blocking regression (lost completion notification and wrong `Stopped` when a job is in flight), two minors; everything else in the rework checks out.
pat-s force-pushed feat/ci-quota-enforcement from acf83d1813
Some checks failed
testing / frontend-checks (pull_request) Successful in 1m23s
testing / backend-checks (pull_request) Successful in 5m42s
testing / test-unit (pull_request) Successful in 5m29s
testing / test-remote-cacher (garnet) (pull_request) Successful in 1m49s
testing / test-remote-cacher (valkey) (pull_request) Successful in 1m55s
testing / test-remote-cacher (redis) (pull_request) Successful in 1m29s
testing / test-mysql (pull_request) Successful in 25m19s
testing / test-e2e (pull_request) Successful in 22m35s
testing / test-pgsql (pull_request) Has been cancelled
testing / test-sqlite (pull_request) Has been cancelled
to cd459d9493
All checks were successful
testing / frontend-checks (pull_request) Successful in 1m2s
testing / backend-checks (pull_request) Successful in 5m26s
testing / test-remote-cacher (redis) (pull_request) Successful in 2m46s
testing / test-remote-cacher (valkey) (pull_request) Successful in 2m47s
testing / test-remote-cacher (garnet) (pull_request) Successful in 2m46s
testing / test-unit (pull_request) Successful in 10m40s
testing / test-mysql (pull_request) Successful in 30m17s
testing / test-e2e (pull_request) Successful in 26m2s
testing / test-sqlite (pull_request) Successful in 39m27s
testing / test-pgsql (pull_request) Successful in 42m30s
issue-labels / backporting (pull_request_target) Has been skipped
milestone / set (pull_request_target) Has been skipped
2026-08-29 09:21:02 +00:00
Compare
Author
Owner

The regression is real and my comment described behaviour the code did not have. Fixed in cd459d9.

The lost notification

Both halves verified. UpdateRunJobWithoutNotification recomputes and writes the run itself (run_job.go:244-250), so my "quiet" cancel still stamped Cancelled with Stopped = now, and sendActionRunNowDoneNotificationIfNeeded (notifier.go:839) requires !priorRun.Status.IsDone(), so the real completion then fired nothing. Fires early became fires never, with a Stopped that excluded the running job.

Taken as suggested: while a task is in flight the run is not touched at all. cancelUnstartedJobRowOnly writes the job row directly with db.GetEngine(ctx).ID(job.ID).Cols("status", "stopped").Update(job) — ActionRunJob has no version column, so this is what UpdateRunJobWithoutNotification does minus the run recompute — and settleRunStatus is skipped entirely in that case. The run stays Running until the last job reports in and moves it Running → Cancelled through the ordinary path, with one notification and a Stopped that includes the work.

Three assertions now pin it, after the cancel and after the finish:

  • the run is not done while a task is in flight
  • no completion notification has fired at that point
  • exactly one fires afterwards, as Cancelled, via a notify_service.Notifier mock

Reverting cancelUnstartedJobRowOnly to the old call fails two of them, so they hold the behaviour rather than describe it.

I did not take the Stopped timestamp assertion. The test fabricates a stop time five minutes ahead so the billed duration is non-zero, while the run stamps Stopped from the clock when it settles, so the two are not comparable. Asserting only that it is set, with a comment saying why.

Minors

RerunJob now clears the warning as well, on job.Run before its UpdateRun. You are right that it is the realistic path: after a quota cancel every job is Cancelled, so "re-run this job" is what a user reaches for.

The stale Version is now closed generally rather than only inside the cancel path. settleRunStatus copies status, started, stopped and version from the freshly loaded run back onto the caller's, so the object InsertRun hands to consistencyCheckRun is current and FailRunPreExecutionError on the unknown-needs path no longer hits ErrActionRunOutOfDate.

Verification

make lint-go clean, fmt-check/tidy-check/swagger-check/lint-editorconfig/lint-locale pass, full ./models/... ./services/... unit suite green, and TestAction*, TestQuota*, TestAPIQuota*, TestRerun* all pass on sqlite.

The regression is real and my comment described behaviour the code did not have. Fixed in `cd459d9`. ## The lost notification Both halves verified. `UpdateRunJobWithoutNotification` recomputes and writes the run itself (`run_job.go:244-250`), so my "quiet" cancel still stamped `Cancelled` with `Stopped = now`, and `sendActionRunNowDoneNotificationIfNeeded` (`notifier.go:839`) requires `!priorRun.Status.IsDone()`, so the real completion then fired nothing. Fires early became fires never, with a `Stopped` that excluded the running job. Taken as suggested: while a task is in flight the run is not touched at all. `cancelUnstartedJobRowOnly` writes the job row directly with `db.GetEngine(ctx).ID(job.ID).Cols("status", "stopped").Update(job)` — `ActionRunJob` has no version column, so this is what `UpdateRunJobWithoutNotification` does minus the run recompute — and `settleRunStatus` is skipped entirely in that case. The run stays `Running` until the last job reports in and moves it `Running → Cancelled` through the ordinary path, with one notification and a `Stopped` that includes the work. Three assertions now pin it, after the cancel and after the finish: - the run is not done while a task is in flight - no completion notification has fired at that point - exactly one fires afterwards, as `Cancelled`, via a `notify_service.Notifier` mock Reverting `cancelUnstartedJobRowOnly` to the old call fails two of them, so they hold the behaviour rather than describe it. I did not take the `Stopped` timestamp assertion. The test fabricates a stop time five minutes ahead so the billed duration is non-zero, while the run stamps `Stopped` from the clock when it settles, so the two are not comparable. Asserting only that it is set, with a comment saying why. ## Minors `RerunJob` now clears the warning as well, on `job.Run` before its `UpdateRun`. You are right that it is the realistic path: after a quota cancel every job is `Cancelled`, so "re-run this job" is what a user reaches for. The stale `Version` is now closed generally rather than only inside the cancel path. `settleRunStatus` copies status, started, stopped and version from the freshly loaded run back onto the caller's, so the object `InsertRun` hands to `consistencyCheckRun` is current and `FailRunPreExecutionError` on the unknown-`needs` path no longer hits `ErrActionRunOutOfDate`. ## Verification `make lint-go` clean, `fmt-check`/`tidy-check`/`swagger-check`/`lint-editorconfig`/`lint-locale` pass, full `./models/... ./services/...` unit suite green, and `TestAction*`, `TestQuota*`, `TestAPIQuota*`, `TestRerun*` all pass on sqlite.
pat-s merged commit 0d1c4fe97f into v16.0/forgejo-codefloe 2026-08-29 10:11:55 +00:00
pat-s deleted branch feat/ci-quota-enforcement 2026-08-29 10:11:55 +00:00
Sign in to join this conversation.
No reviewers
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
codefloe/forgejo-codefloe!102
No description provided.