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

feat(quota): let an external CI ask whether it may start work #104

Merged
pat-s merged 1 commit from feat/quota-ci-preflight-check into v16.0/forgejo-codefloe 2026-08-29 19:19:22 +00:00
Owner

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

GET /api/v1/quota/ci/check?repo=owner/name&class=linux
{
  "allowed": true,
  "remaining_seconds": 44100,
  "reason": ""
}

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.

source is the authenticated reporter, never a query parameter, so a reporter can only ask about its own budget. A ?source=actions in the request buys nothing; there is a test for that.

allowed is the field to branch on. reason is 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.

class is validated against the same shape the ledger stores but does not change the answer yet: per-class subjects such as time:ci:class:macos are 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.RemainingFor is new in models/quota/group_codefloe.go. It walks the same rules, in the same order and with the same precedence, as Evaluate: 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 Evaluate rather 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. TestCodefloeRemainingForAgreesWithEvaluate asserts the two agree across every combination of group shape, subject and spend.

-1 means 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 it
  • models/quota/group_codefloe_test.go — unlimited, spent, the strictest rule binding, the most generous group winning, the default fallback, and agreement with Evaluate
  • services/codefloe/quota_ci/enforce.go — Decision gains Remaining, filled in wherever a decision is taken
  • services/codefloe/quota_ci/check.go — new: class validation, repository resolution, evaluation, and the refusal prose
  • services/codefloe/quota_ci/check_test.go — new: the two shapes of refusal reason
  • services/codefloe/quota_ci/enforce_test.go — remaining on permission, on refusal, and with the feature off
  • modules/structs/codefloe_quota_ci.go — QuotaCICheck
  • routers/api/v1/codefloe/quota_ci.go — the handler
  • routers/api/v1/codefloe/quota_ci_reporter.go — one route added to the reporter stack
  • routers/api/v1/swagger/codefloe_quota_ci.go, templates/swagger/v1_json.tmpl — the response definition and the regenerated spec
  • tests/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 case

Behaviour change

Nothing changes for an instance that has not turned the ledger on: the route is mounted only when [quota.ci] ENABLED is 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.

  • Call the check endpoint before scheduling a pipeline, and refuse to start when it answers no
  • Surface the refusal as a commit status on the Forgejo repository, carrying reason, so the user sees why nothing ran instead of finding a silently missing pipeline
  • Fail open on transport errors, and log loudly

Failing 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/... passes
  • The full quota integration suite (TestAPIQuotaCI*, TestActionsQuotaCI*, TestQuota*, TestAPIQuota*) passes on sqlite
  • golangci-lint is clean on every package touched, and make swagger-check passes
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 ``` GET /api/v1/quota/ci/check?repo=owner/name&class=linux ``` ```json { "allowed": true, "remaining_seconds": 44100, "reason": "" } ``` 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. `source` is the authenticated reporter, never a query parameter, so a reporter can only ask about its own budget. A `?source=actions` in the request buys nothing; there is a test for that. `allowed` is the field to branch on. `reason` is 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. `class` is validated against the same shape the ledger stores but does not change the answer yet: per-class subjects such as `time:ci:class:macos` are 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.RemainingFor` is new in `models/quota/group_codefloe.go`. It walks the same rules, in the same order and with the same precedence, as `Evaluate`: 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 `Evaluate` rather 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. `TestCodefloeRemainingForAgreesWithEvaluate` asserts the two agree across every combination of group shape, subject and spend. `-1` means 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 it - `models/quota/group_codefloe_test.go` — unlimited, spent, the strictest rule binding, the most generous group winning, the default fallback, and agreement with `Evaluate` - `services/codefloe/quota_ci/enforce.go` — `Decision` gains `Remaining`, filled in wherever a decision is taken - `services/codefloe/quota_ci/check.go` — new: class validation, repository resolution, evaluation, and the refusal prose - `services/codefloe/quota_ci/check_test.go` — new: the two shapes of refusal reason - `services/codefloe/quota_ci/enforce_test.go` — remaining on permission, on refusal, and with the feature off - `modules/structs/codefloe_quota_ci.go` — `QuotaCICheck` - `routers/api/v1/codefloe/quota_ci.go` — the handler - `routers/api/v1/codefloe/quota_ci_reporter.go` — one route added to the reporter stack - `routers/api/v1/swagger/codefloe_quota_ci.go`, `templates/swagger/v1_json.tmpl` — the response definition and the regenerated spec - `tests/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 case ## Behaviour change Nothing changes for an instance that has not turned the ledger on: the route is mounted only when `[quota.ci] ENABLED` is 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. - Call the check endpoint before scheduling a pipeline, and refuse to start when it answers no - Surface the refusal as a commit status on the Forgejo repository, carrying `reason`, so the user sees why nothing ran instead of finding a silently missing pipeline - Fail open on transport errors, and log loudly Failing 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/...` passes - The full quota integration suite (`TestAPIQuotaCI*`, `TestActionsQuotaCI*`, `TestQuota*`, `TestAPIQuota*`) passes on sqlite - `golangci-lint` is clean on every package touched, and `make swagger-check` passes
Author
Owner

Review

The core logic is sound.
A 3,783-case property probe over rule/group/usage combinations found no disagreement between RemainingFor and Evaluate, 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

  1. reason can name builtin-default-rule (services/codefloe/quota_ci/check.go:74).
    When the instance default refuses (owner in no seconds-limiting group), EvaluateWithRule returns the synthetic rule from defaultRuleFor, so the message tells the user that quota rule builtin-default-rule is 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, user2 in no group, 600s reported this period, GET /quota/ci/check?repo=user2/repo1.

  2. util.SecToTime(0) renders as an empty string (check.go:75).
    formatTime only prints values >= 1, so a zero-limit rule (the deny-all rule the PR's own tests build via quotaCIRule(t, user2, 0)) with nothing spent produces the CI time quota "ci-enforcement" is used up: spent of this period.
    Same for Used == 0 with any limit.

  3. "Overshoot is bounded by one unit of work per reporter" is not true (check.go:24, swagger description, release-notes/104.md).
    InFlightSeconds only counts action_task rows, 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 loadCodefloeTime includes for external sources.

  4. repositoryFor ignores repo redirects (services/codefloe/quota_ci/ingest.go:133, pre-existing from #103 but now shared by Check).
    GetRepositoryByOwnerAndName does not consult repo_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

  1. Class validation is copied verbatim from ingest.go:72-78 and 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 both recordFrom and Check.
    The shared 422 message also omits two rules IsValidQuotaCIName enforces: max 40 chars and no leading -/_, so class=-macos is told it must be "lowercase alphanumeric with dashes or underscores", which it already is.

  2. refusalReason is a third copy of the Actions warning prose (check.go:68).
    services/actions/codefloe_quota_ci.go already maps the same Decision to actions.workflow.ci_quota_warning / ci_quota_not_granted_warning.
    The struct doc says reason is "never to be parsed", yet api_quota_ci_check_test.go:103 and :176 grep 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) plus rule, used_seconds, limit_seconds alongside the prose.

  3. RemainingFor is a third hand-mirrored precedence walk (models/quota/group_codefloe.go:157).
    decide() now runs EvaluateWithRule and then RemainingFor over 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) with Evaluate / EvaluateWithRule / RemainingFor as 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.Evaluate on merge) has to be mirrored by hand.

  4. Doc contract vs. sentinel (enforce.go:34, group_codefloe.go:150).
    Both docs say Remaining is "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 allowed var comment ("whenever nothing stands in the way") is also stale now that decide() no longer returns it.

  5. 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/asking in isolation fails.
    Separately, quotaCIRule and quotaCISubjectRule in actions_quota_ci_test.go differ only in the subject constant; quotaCIRule can delegate.

## Review The core logic is sound. A 3,783-case property probe over rule/group/usage combinations found no disagreement between `RemainingFor` and `Evaluate`, 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 1. **`reason` can name `builtin-default-rule`** (`services/codefloe/quota_ci/check.go:74`). When the instance default refuses (owner in no seconds-limiting group), `EvaluateWithRule` returns the synthetic rule from `defaultRuleFor`, so the message tells the user that quota rule `builtin-default-rule` is 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`, `user2` in no group, 600s reported this period, `GET /quota/ci/check?repo=user2/repo1`. 2. **`util.SecToTime(0)` renders as an empty string** (`check.go:75`). `formatTime` only prints values `>= 1`, so a zero-limit rule (the deny-all rule the PR's own tests build via `quotaCIRule(t, user2, 0)`) with nothing spent produces `the CI time quota "ci-enforcement" is used up: spent of this period`. Same for `Used == 0` with any limit. 3. **"Overshoot is bounded by one unit of work per reporter" is not true** (`check.go:24`, swagger description, `release-notes/104.md`). `InFlightSeconds` only counts `action_task` rows, 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 `loadCodefloeTime` includes for external sources. 4. **`repositoryFor` ignores repo redirects** (`services/codefloe/quota_ci/ingest.go:133`, pre-existing from #103 but now shared by `Check`). `GetRepositoryByOwnerAndName` does not consult `repo_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 5. **Class validation is copied verbatim from `ingest.go:72-78` and 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 both `recordFrom` and `Check`. The shared 422 message also omits two rules `IsValidQuotaCIName` enforces: max 40 chars and no leading `-`/`_`, so `class=-macos` is told it must be "lowercase alphanumeric with dashes or underscores", which it already is. 6. **`refusalReason` is a third copy of the Actions warning prose** (`check.go:68`). `services/actions/codefloe_quota_ci.go` already maps the same `Decision` to `actions.workflow.ci_quota_warning` / `ci_quota_not_granted_warning`. The struct doc says `reason` is "never to be parsed", yet `api_quota_ci_check_test.go:103` and `:176` grep 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`) plus `rule`, `used_seconds`, `limit_seconds` alongside the prose. 7. **`RemainingFor` is a third hand-mirrored precedence walk** (`models/quota/group_codefloe.go:157`). `decide()` now runs `EvaluateWithRule` and then `RemainingFor` over 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)` with `Evaluate` / `EvaluateWithRule` / `RemainingFor` as 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.Evaluate` on merge) has to be mirrored by hand. 8. **Doc contract vs. sentinel** (`enforce.go:34`, `group_codefloe.go:150`). Both docs say `Remaining` is "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 `allowed` var comment ("whenever nothing stands in the way") is also stale now that `decide()` no longer returns it. 9. **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/asking` in isolation fails. Separately, `quotaCIRule` and `quotaCISubjectRule` in `actions_quota_ci_test.go` differ only in the subject constant; `quotaCIRule` can delegate.
pat-s force-pushed feat/quota-ci-preflight-check from fe76cac8ba
Some checks failed
testing / frontend-checks (pull_request) Successful in 1m4s
testing / backend-checks (pull_request) Successful in 6m3s
testing / test-unit (pull_request) Successful in 11m1s
testing / test-remote-cacher (valkey) (pull_request) Successful in 1m43s
testing / test-e2e (pull_request) Successful in 28m15s
testing / test-remote-cacher (redis) (pull_request) Successful in 1m41s
testing / test-remote-cacher (garnet) (pull_request) Successful in 2m7s
testing / test-sqlite (pull_request) Has been cancelled
testing / test-mysql (pull_request) Has been cancelled
testing / test-pgsql (pull_request) Has been cancelled
to ce8712a8c3
All checks were successful
testing / test-unit (pull_request) Successful in 5m39s
testing / backend-checks (pull_request) Successful in 5m26s
testing / frontend-checks (pull_request) Successful in 1m6s
testing / test-remote-cacher (redis) (pull_request) Successful in 1m28s
testing / test-remote-cacher (garnet) (pull_request) Successful in 1m48s
testing / test-remote-cacher (valkey) (pull_request) Successful in 1m49s
testing / test-pgsql (pull_request) Successful in 47m36s
testing / test-e2e (pull_request) Successful in 22m28s
testing / test-mysql (pull_request) Successful in 25m13s
testing / test-sqlite (pull_request) Successful in 47m31s
issue-labels / backporting (pull_request_target) Has been skipped
milestone / set (pull_request_target) Has been skipped
2026-08-29 14:34:08 +00:00
Compare
Author
Owner

All nine addressed. Verified each claim against the code first; findings 1-4 all reproduce.

Should fix

1. reason naming builtin-default-rule — the three ways CI work can be refused are now told apart on Decision as a Reason: exceeded, default_exceeded, not_granted. On default_exceeded the rule is not named at all, and the prose names [quota.ci.default] TOTAL and the time:ci:all rule that would override it.

This defect was not only in the API: services/actions/codefloe_quota_ci.go builds its warning from the same Decision, so a run cancelled against the instance default was blaming builtin-default-rule in the run banner too. Fixed there as well, with WarningCodeCIQuotaDefaultExceeded and actions.workflow.ci_quota_default_warning. That is one more identifier on the fork's existing case arm in pre_execution_warnings.go and no other upstream edit.

2. util.SecToTime(0) rendering empty — confirmed: formatTime only prints values >= 1, so everything below one second renders as nothing. Added HumanSeconds, which spells out 0 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, in TestQuotaCIRefusalReasonAlwaysReadsAsASentence and an integration subtest against a real limit = 0 rule.

3. The overshoot bound — you are right, and InFlightSeconds reading only action_task is 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: NewRedirect is written on both rename and transfer, so either one silently exempted the pipeline. repositoryFor now falls back to repo_model.GetRedirect under 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. TestAPIQuotaCICheckFollowsARename renames user2/repo1 and 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 both recordFrom and Check. The message now states all three rules, including the 40-character bound (maxQuotaCINameLength exported as setting.MaxQuotaCINameLength) and the leading -/_. Tested against Linux, linux/x86, -macos and a 41-character name.

6. Prose as a contract — added reason_code plus rule, used_seconds and limit_seconds, so a Crow plugin branches on the code and only displays the prose. The integration tests now assert on reason_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 Decision and drives both.

7. The third precedence walk — collapsed. GroupList.Assess returns {Allowed, Remaining, Rule, FromDefault} from one walk, and EvaluateWithRule and RemainingFor are 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. Rewriting Evaluate to 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: Remaining is zero exactly when the subject is refused, and otherwise positive or RemainingUnlimited. The stale allowed comment 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 running asking, an_owner_over, what_is_left, the_instance-wide and a_deny-all individually with -test.run; all pass alone. "asking reserves nothing" now reads the ledger before and after rather than hard-coding a total. quotaCIRule delegates to quotaCISubjectRule.

Verification

  • go test -p 1 ./models/quota/... ./models/actions/... ./models/codefloe/... ./services/codefloe/... ./services/actions/... ./modules/setting/... ./modules/structs/... ./routers/... passes
  • TestAPIQuotaCI*, TestActionsQuotaCI*, TestQuota*, TestAPIQuota* pass on sqlite
  • golangci-lint over models/ services/ routers/ modules/setting/ modules/structs/ tests/integration/ reports only 11 pre-existing slicesbackward findings, none in a file this branch touches
  • make swagger-check passes
All nine addressed. Verified each claim against the code first; findings 1-4 all reproduce. ### Should fix **1. `reason` naming `builtin-default-rule`** — the three ways CI work can be refused are now told apart on `Decision` as a `Reason`: `exceeded`, `default_exceeded`, `not_granted`. On `default_exceeded` the rule is not named at all, and the prose names `[quota.ci.default] TOTAL` and the `time:ci:all` rule that would override it. This defect was not only in the API: `services/actions/codefloe_quota_ci.go` builds its warning from the same `Decision`, so a run cancelled against the instance default was blaming `builtin-default-rule` in the run banner too. Fixed there as well, with `WarningCodeCIQuotaDefaultExceeded` and `actions.workflow.ci_quota_default_warning`. That is one more identifier on the fork's existing case arm in `pre_execution_warnings.go` and no other upstream edit. **2. `util.SecToTime(0)` rendering empty** — confirmed: `formatTime` only prints values `>= 1`, so everything below one second renders as nothing. Added `HumanSeconds`, which spells out `0 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, in `TestQuotaCIRefusalReasonAlwaysReadsAsASentence` and an integration subtest against a real `limit = 0` rule. **3. The overshoot bound** — you are right, and `InFlightSeconds` reading only `action_task` is 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: `NewRedirect` is written on both rename *and* transfer, so either one silently exempted the pipeline. `repositoryFor` now falls back to `repo_model.GetRedirect` under 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. `TestAPIQuotaCICheckFollowsARename` renames `user2/repo1` and 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 both `recordFrom` and `Check`. The message now states all three rules, including the 40-character bound (`maxQuotaCINameLength` exported as `setting.MaxQuotaCINameLength`) and the leading `-`/`_`. Tested against `Linux`, `linux/x86`, `-macos` and a 41-character name. **6. Prose as a contract** — added `reason_code` plus `rule`, `used_seconds` and `limit_seconds`, so a Crow plugin branches on the code and only *displays* the prose. The integration tests now assert on `reason_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 `Decision` and drives both. **7. The third precedence walk** — collapsed. `GroupList.Assess` returns `{Allowed, Remaining, Rule, FromDefault}` from one walk, and `EvaluateWithRule` and `RemainingFor` are 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. Rewriting `Evaluate` to 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: `Remaining` is zero exactly when the subject is refused, and otherwise positive or `RemainingUnlimited`. The stale `allowed` comment 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 running `asking`, `an_owner_over`, `what_is_left`, `the_instance-wide` and `a_deny-all` individually with `-test.run`; all pass alone. "asking reserves nothing" now reads the ledger before and after rather than hard-coding a total. `quotaCIRule` delegates to `quotaCISubjectRule`. ### Verification - `go test -p 1 ./models/quota/... ./models/actions/... ./models/codefloe/... ./services/codefloe/... ./services/actions/... ./modules/setting/... ./modules/structs/... ./routers/...` passes - `TestAPIQuotaCI*`, `TestActionsQuotaCI*`, `TestQuota*`, `TestAPIQuota*` pass on sqlite - `golangci-lint` over `models/ services/ routers/ modules/setting/ modules/structs/ tests/integration/` reports only 11 pre-existing `slicesbackward` findings, none in a file this branch touches - `make swagger-check` passes
pat-s merged commit de174ec6ba into v16.0/forgejo-codefloe 2026-08-29 19:19:22 +00:00
pat-s deleted branch feat/quota-ci-preflight-check 2026-08-29 19:19:22 +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!104
No description provided.