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

feat: per-owner egress quota counter #142

Merged
pat-s merged 23 commits from feat/egress-quota into v16.0/forgejo-codefloe 2026-09-19 17:49:57 +00:00
Owner

Adds a per-owner monthly egress (bytes-served) counter to Forgejo, surfaced through the existing quota UI and fed by an external aggregator.

Paired with codefloe/infrastructure-as-code PR (linked below), which does the measuring and the enforcing.
This fork change is display and bookkeeping only.

The load-bearing property

Forgejo must never reject a write because of egress.
Enforcement happens at HAProxy, which denies reads.
An egress budget should stop someone downloading, not stop them pushing a fix.

That is enforced structurally rather than by a flag:

  • the subject is egress:all, not size:egress:all, so it is outside the size: family;
  • it has no entry in subjectToParent, so no route ever evaluates it;
  • it sits outside the LimitSubjectFirst..LimitSubjectLast range, so it is invisible to every present and future generic subject iteration.

That last point also means no upstream test needed modifying: git diff against the base shows no pre-existing test file touched anywhere on this branch.

A rule that lists egress:all alongside a size: subject is rejected with 422 at both create and edit, because Rule.Sum adds every listed subject and would otherwise conflate downloads with storage on the write path.

What it adds

user_egress_usage, keyed (user_id, period) with period as a UTC YYYY-MM calendar month, plus a (period, bytes) index for the two scanning queries.
Accumulation is a single atomic conditional UPDATE ... SET bytes = bytes + ? guarded on last_run_id <>, so it is correct regardless of the driver's isolation level, with a bounded retry on duplicate key.

Idempotency per run id is the contract the external aggregator relies on: it commits its journal cursor only after this API accepts the deltas, so a crash replays a run rather than losing an hour.

POST /api/v1/admin/egress/usage takes a run's deltas, pre-aggregated per owner so a repeated owner cannot silently drop bytes, validating the whole report before the first write.
An owner that no longer resolves is skipped rather than failing the batch, since accounts can be renamed or deleted between a request being served and the run being aggregated.

GET /api/v1/admin/egress/over-quota returns who is over, deferring to GroupList.Evaluate so the upstream OR-across-groups semantics hold.
That matters concretely: exemptions work by putting an account in a custom-quota-<user> group with an unlimited rule while it stays in the finite default group, so an AND reading would have blocked crowci and crow-plugins despite their explicit exemptions and taken CI's own package pulls down.

A new admin page lists the top consumers for the period, which is what you will actually use to choose the eventual limit.
It keeps rows for deleted users, since the page attributes cost rather than deciding who to block.

Fails open

The egress read in GetUsedForUser logs and leaves the value at zero rather than propagating.
That function is on the write-enforcement path for pushes, LFS, packages, artifacts and mirrors, so a missing table (a node where the migration has not run) would otherwise refuse every write on that node.
A display-only counter must degrade to zero, never block.

Rebase surface

Built on v16.0/forgejo-codefloe, and deliberately shaped to keep the fork's conflict surface small.

Eight upstream files are touched, all of them unavoidable registration points: models/quota/quota.go and routers/api/v1/admin/quota_rule.go (one guard each), models/quota/used.go, the locale file (keys appended at the end of [admin] so no existing group is split), routers/api/v1/api.go, routers/web/web.go, templates/admin/navbar.tmpl, and regenerated swagger.
No upstream test is modified.

Everything fork-specific lives in fork-owned files, following the conventions this fork already established:

  • the migration is models/codefloe_migrations/v15.go, in the fork's own sequence with its own version table, not in upstream's forgejo_migrations. A fork-invented id in the upstream sequence makes the database log.Fatal under a stock Forgejo binary, which breaks the interchangeability the fork maintains deliberately;
  • the subject is declared in models/quota/limit_subject_codefloe.go at 1006, continuing the existing 1000 + iota allocation alongside the CI subjects, so it cannot collide with a future upstream subject and silently reinterpret stored rules.

As a result models/quota/limit_subject.go, errors.go, group.go and routers/web/shared/storage_overview.go are byte-identical to the base.

Known gaps

The migration has not been exercised through the real DB-backed migration runner; those tests need a live Postgres or MySQL host.
Verify on a dev instance before merging.

The concurrency test cannot exhibit the cross-connection race, because SQLite serialises writers.
The atomic UPDATE is correct by construction, but that is not empirical proof on Postgres.

make lint-go could not run locally (golangci-lint cannot import internal/goarch under Go 1.27.1) and needs to pass in CI.

Neither the quota settings row nor the admin page has been confirmed in a browser.

LimitSubjects.Validate() currently runs only in the admin API, so a direct CreateRule call could still create a mixed rule.
Impossible today, since the admin API is the only caller, but worth closing in a follow-up.

Adds a per-owner monthly egress (bytes-served) counter to Forgejo, surfaced through the existing quota UI and fed by an external aggregator. Paired with codefloe/infrastructure-as-code PR (linked below), which does the measuring and the enforcing. This fork change is display and bookkeeping only. ## The load-bearing property **Forgejo must never reject a write because of egress.** Enforcement happens at HAProxy, which denies reads. An egress budget should stop someone downloading, not stop them pushing a fix. That is enforced structurally rather than by a flag: - the subject is `egress:all`, not `size:egress:all`, so it is outside the `size:` family; - it has no entry in `subjectToParent`, so no route ever evaluates it; - it sits **outside** the `LimitSubjectFirst..LimitSubjectLast` range, so it is invisible to every present and future generic subject iteration. That last point also means no upstream test needed modifying: `git diff` against the base shows no pre-existing test file touched anywhere on this branch. A rule that lists `egress:all` alongside a `size:` subject is rejected with 422 at both create and edit, because `Rule.Sum` adds every listed subject and would otherwise conflate downloads with storage on the write path. ## What it adds `user_egress_usage`, keyed `(user_id, period)` with `period` as a UTC `YYYY-MM` calendar month, plus a `(period, bytes)` index for the two scanning queries. Accumulation is a single atomic conditional `UPDATE ... SET bytes = bytes + ?` guarded on `last_run_id <>`, so it is correct regardless of the driver's isolation level, with a bounded retry on duplicate key. Idempotency per run id is the contract the external aggregator relies on: it commits its journal cursor only after this API accepts the deltas, so a crash replays a run rather than losing an hour. `POST /api/v1/admin/egress/usage` takes a run's deltas, pre-aggregated per owner so a repeated owner cannot silently drop bytes, validating the whole report before the first write. An owner that no longer resolves is skipped rather than failing the batch, since accounts can be renamed or deleted between a request being served and the run being aggregated. `GET /api/v1/admin/egress/over-quota` returns who is over, deferring to `GroupList.Evaluate` so the upstream OR-across-groups semantics hold. That matters concretely: exemptions work by putting an account in a `custom-quota-<user>` group with an unlimited rule while it stays in the finite default group, so an AND reading would have blocked `crowci` and `crow-plugins` despite their explicit exemptions and taken CI's own package pulls down. A new admin page lists the top consumers for the period, which is what you will actually use to choose the eventual limit. It keeps rows for deleted users, since the page attributes cost rather than deciding who to block. ## Fails open The egress read in `GetUsedForUser` logs and leaves the value at zero rather than propagating. That function is on the write-enforcement path for pushes, LFS, packages, artifacts and mirrors, so a missing table (a node where the migration has not run) would otherwise refuse every write on that node. A display-only counter must degrade to zero, never block. ## Rebase surface Built on `v16.0/forgejo-codefloe`, and deliberately shaped to keep the fork's conflict surface small. Eight upstream files are touched, all of them unavoidable registration points: `models/quota/quota.go` and `routers/api/v1/admin/quota_rule.go` (one guard each), `models/quota/used.go`, the locale file (keys appended at the end of `[admin]` so no existing group is split), `routers/api/v1/api.go`, `routers/web/web.go`, `templates/admin/navbar.tmpl`, and regenerated swagger. No upstream test is modified. Everything fork-specific lives in fork-owned files, following the conventions this fork already established: - the migration is `models/codefloe_migrations/v15.go`, in the fork's own sequence with its own version table, not in upstream's `forgejo_migrations`. A fork-invented id in the upstream sequence makes the database `log.Fatal` under a stock Forgejo binary, which breaks the interchangeability the fork maintains deliberately; - the subject is declared in `models/quota/limit_subject_codefloe.go` at 1006, continuing the existing `1000 + iota` allocation alongside the CI subjects, so it cannot collide with a future upstream subject and silently reinterpret stored rules. As a result `models/quota/limit_subject.go`, `errors.go`, `group.go` and `routers/web/shared/storage_overview.go` are byte-identical to the base. ## Known gaps The migration has not been exercised through the real DB-backed migration runner; those tests need a live Postgres or MySQL host. **Verify on a dev instance before merging.** The concurrency test cannot exhibit the cross-connection race, because SQLite serialises writers. The atomic UPDATE is correct by construction, but that is not empirical proof on Postgres. `make lint-go` could not run locally (golangci-lint cannot import `internal/goarch` under Go 1.27.1) and needs to pass in CI. Neither the quota settings row nor the admin page has been confirmed in a browser. `LimitSubjects.Validate()` currently runs only in the admin API, so a direct `CreateRule` call could still create a mixed rule. Impossible today, since the admin API is the only caller, but worth closing in a follow-up.
Eliminate the read-then-write in AddEgress, which allowed two
concurrent calls for the same (userID, period) to read the same
existing.Bytes and both write, losing one increment. Replace it with
a single atomic conditional UPDATE (bytes = bytes + ?, guarded by
last_run_id <> ?), which is correct independent of driver isolation
level. Fall back to INSERT when no row exists yet, and retry the
conditional UPDATE once if the INSERT loses a race on the primary
key.
Register LimitSubjectEgressAll as a top-level quota subject, deliberately
outside the size: family and absent from subjectToParent, so no route can
ever evaluate it and a download-budget overage can never reject a write.
Wire Used.Egress from GetEgressForUser and add the PrettySubject label so
the existing quota overview UI renders it without any template change.

Also adjust TestQuotaDefaultGroup's full-range subject loop: it assumed
every LimitSubject rolls up into size:all, which is no longer true for
the intentionally orphaned egress:all.
Add POST /api/v1/admin/egress/usage so the external hourly aggregator
can post per-owner byte deltas for a period. The handler passes each
delta's run_id straight through to quota.AddEgress, which already
guarantees idempotent replay. Unknown owners are skipped rather than
failing the batch, since an owner can be renamed or deleted between a
request being served and the run being aggregated. Retention pruning
runs on every call but a pruning failure is logged and non-fatal, so
it cannot cause the aggregator to replay an hour it already applied.
Add GET /api/v1/admin/egress/over-quota, the read side the hourly
external aggregator polls to build the HAProxy deny map. The list is
derived from the same primitives (Rule.Acceptable per matching rule of
the user's quota groups) that render the settings page's egress row,
so the number a user sees and the reason they get blocked can never
disagree.

GroupList.Evaluate/EvaluateDefault were deliberately not reused: they
collapse "no rule matches this subject" into "denied", which is
correct for gating a write but would incorrectly flag every user
without an explicit egress rule as over quota, since egress:all is
intentionally excluded from subjectToParent.
isOverEgressQuota previously AND-ed across groups and rules by
returning true on the first Rule.Acceptable failure anywhere in the
user's groups. That inverts the exemption pattern this deployment
relies on: a per-user unlimited egress:all rule lives in a separate
custom-quota-<user> group alongside a finite default group, and
GroupList.Evaluate is OR-across-groups (first matching, allowing
group wins). Under the old AND logic, crowci/crow-plugins would stay
on the over-quota list and get blocked by HAProxy the moment
enforcement switched on.

Fix: keep the existing guard that skips users with no egress:all rule
at all (GroupList.Evaluate collapses that case into "denied", which
is wrong here), but hand the actual allow/deny verdict to
GroupList.Evaluate itself instead of re-implementing the comparison.
Rule.Sum adds up used.CalculateFor(subject) over every subject in a rule,
while Rule.Evaluate only checks membership for the subject being tested. A
rule such as {limit: 10GiB, subjects: ["size:all", "egress:all"]} was
therefore matched by a git push evaluating size:all and compared against a
sum that included the month's download bytes, so an owner with 2 GiB of
repositories and 9 GiB of downloads was told "quota exceeded" on push. The
counter is display-only: Forgejo must never reject a write because of it.

This change will:

- Restore LimitSubjectLast to LimitSubjectSizeWiki and declare
  LimitSubjectEgressAll after it, outside the
  LimitSubjectFirst..LimitSubjectLast range. Together with its absence from
  subjectToParent, that makes the display-only property structural: every
  present and future enforcement walk over the range skips egress without
  having to know it exists. It stays parseable through limitSubjectRepr.
- Revert the skip added to the upstream test
  models/quota/quota_group_test.go, which is now byte-identical to the base
  branch again: with egress outside the range its loop no longer sees it.
- Reject a rule listing egress:all together with any other subject, in
  LimitSubjects.Validate, applied at rule creation and rule edit in the
  admin API (422). EditQuotaRule reuses toLimitSubjects rather than
  repeating the parse loop, so the check cannot be bypassed by editing.
- Cover egress alone, egress mixed with size, size-only rules, and the
  range invariant itself.
GetUsedForUser is on the write-enforcement path for pushes
(routers/private/hook_pre_receive.go), LFS uploads
(services/lfs/server.go), package uploads (routers/api/packages/api.go),
artifacts and mirrors, all of which turn an error into a deny or a 500.
Propagating an error from the egress read meant an unapplied migration, or
an unreadable or damaged user_egress_usage table, failed every write on the
node.

This change will make that one read fail open: log at error level and leave
Used.Egress at zero instead of propagating, with a comment explaining why it
deliberately swallows its error while every other read here, all of which
back enforced size limits, must propagate. A display-only counter degrades
to zero, never blocks a write.
GET /user/quota/check?subject=egress:all went through EvaluateForUser to
GroupList.Evaluate, which for a non-matching subject falls through to
EvaluateDefault, whose builtin rule only names size:all, and denies. On an
instance with no egress rule configured that API reported every user as over
quota while /admin/egress/over-quota correctly reported nobody, because the
pre-check for "is there an egress rule at all" existed only inside
ListOverEgressQuota.

This change will:

- Export that pre-check as HasEgressRule and apply it in EvaluateForUser as
  well, so the two endpoints cannot disagree.
- Make the over-quota verdict agree with the settings page. The page renders
  its green tick from Rule.Acceptable ("Sum <= Limit") while Rule.Evaluate
  allows on "Sum < Limit", so at exactly bytes == limit the page showed a
  tick while HAProxy blocked the owner. Since bytes are integers, evaluating
  bytes-1 is identical to "bytes <= limit" and keeps upstream's
  OR-across-groups semantics unforked.
- Resolve group membership and owner names in a fixed number of queries
  instead of a GetGroupsForUser (plus a LoadRules per group) and a
  GetUserByID per usage row, which was roughly 6,000 queries for 2,000
  owners on an hourly endpoint. getGroupsForUsers loads groups, their rules
  and the user mappings once each and keeps GetGroupsForUser's semantics,
  including the DefaultGroups fallback; names are resolved with
  GetUsersByIDs for the over-quota owners only. Behaviour is unchanged and
  all nine existing tests pass unmodified.
- Add tests at the exact boundary and for both endpoints agreeing with and
  without a configured egress rule.
Two problems in the same loop. A report listing the same owner twice hit
AddEgress twice with the same run id, so the second delta took the replay
branch and was discarded with no error and no log. And a negative Bytes was
rejected with 422 only once the walk reached it, leaving the earlier deltas
committed under that run id, so the aggregator's retry hit the replay guard
and the run was wedged for good.

This change will validate the whole report and pre-aggregate its deltas by
owner id before the first write, so a report is either applied in full or
not at all, and each owner is written exactly once per run with the summed
bytes. Keying on the resolved user id rather than the name in the payload
also folds together two lines naming the same account differently.

The period check now calls quota.ValidatePeriod so the handler and the model
cannot drift apart.
Two fixes to user_egress_usage.

The period regex guarded only the HTTP handler, so quota.AddEgress accepted
any string. A row filed under a bad period is invisible to every reader,
which queries the period CurrentPeriod computed, and PruneEgressBefore
compares period strings lexicographically, so a value such as "abcd-ef"
sorts above every real period and would never be pruned: one bad call leaks
a row forever. ValidatePeriod now lives in the model and AddEgress applies
it at the only write entry point.

The composite primary key is (user_id, period), so user_id leads and no
lookup by period alone can use it, yet ListOverEgressQuota, TopEgressConsumers
and PruneEgressBefore all filter or sort on period alone and scanned a table
that grows to owners times 24 months. Add an index on (period, bytes), in
both the model struct tags and the migration: the period prefix serves all
three queries, "bytes > 0" is satisfied from the index, and
TopEgressConsumers' ORDER BY bytes DESC becomes an index-ordered range scan
of one period rather than a sort.

Also covers the fail-open behaviour of GetUsedForUser when the table cannot
be read at all.
The six egress.* keys were inserted mid-block, splitting the existing
pages.* group in two and putting fork-only lines in the middle of a section
upstream edits regularly. Moving them to the end of [admin] keeps every
fork-added line in one contiguous block and shrinks the rebase conflict
surface. No key or value changes; lint-locale passes.
A fork-only table registered in upstream's forgejo_migrations sequence
leaves the database claiming a forgejo_version a stock Forgejo binary
does not know, and that binary log.Fatals on start. Create
user_egress_usage from the fork's own codefloe_migrations sequence
(v15 -> v16) instead, where every other fork table already lives.

The test drives Migrate itself from version 15 rather than only calling
the migration function, so a migration that is written but never
registered fails here.
fix(quota): allocate the egress subject in the fork's own range
Some checks failed
testing / test-pgsql (pull_request) Has been skipped
testing / test-sqlite (pull_request) Has been skipped
testing / test-e2e (pull_request) Has been skipped
issue-labels / backporting (pull_request_target) Has been skipped
milestone / set (pull_request_target) Has been skipped
testing / backend-checks (pull_request) Failing after 4m35s
testing / frontend-checks (pull_request) Successful in 1m35s
testing / test-mysql (pull_request) Has been skipped
testing / test-unit (pull_request) Has been skipped
testing / test-remote-cacher (redis) (pull_request) Has been skipped
testing / test-remote-cacher (garnet) (pull_request) Has been skipped
testing / test-remote-cacher (valkey) (pull_request) Has been skipped
36aec80e5a
LimitSubjectEgressAll was LimitSubjectLast + 1, which is 13 and sits
inside upstream's own allocation: an upstream release defining a
thirteenth subject would silently turn every stored egress rule into
that subject. Declare it in models/quota/limit_subject_codefloe.go, in
the fork's 1000+ sequence next to the CI subjects, and register its
repr there too.

Move LimitSubjects.Validate, ErrRuleMixesEgressWithSize and
ErrInvalidEgressPeriod into fork files as well, and render egress:all
through prettyCodefloeSubject. models/quota/limit_subject.go,
models/quota/errors.go and routers/web/shared/storage_overview.go are
now untouched relative to upstream, which removes the branch's three
most conflict-prone hunks.
fix(tests): satisfy testifylint in the egress tests
Some checks failed
testing / backend-checks (pull_request) Failing after 3m50s
testing / frontend-checks (pull_request) Successful in 1m11s
testing / test-pgsql (pull_request) Has been skipped
testing / test-unit (pull_request) Has been skipped
testing / test-e2e (pull_request) Has been skipped
testing / test-mysql (pull_request) Has been skipped
testing / test-sqlite (pull_request) Has been skipped
testing / test-remote-cacher (redis) (pull_request) Has been skipped
testing / test-remote-cacher (garnet) (pull_request) Has been skipped
testing / test-remote-cacher (valkey) (pull_request) Has been skipped
956356891d
Use require for error assertions and Equal where the types already match,
as testifylint requires. golangci-lint cannot run locally (Go 1.27.1 emits
export data version 4, above the vendored linter's maximum of 2), so these
were applied from CI's report and verified by the test suite.
deadcode flagged IsErrInvalidEgressPeriod and IsErrRuleMixesEgressWithSize
as dead: both call sites in the admin API already map every error from
toLimitSubjects to 422, so nothing needed to discriminate the type. The
tests now assert on the error type directly with ErrorAs. The error types
themselves stay, since they are returned and their messages are used.
fix(swagger): register EgressUsageReport as a parameter body
Some checks failed
testing / test-unit (pull_request) Has been skipped
testing / test-e2e (pull_request) Has been skipped
testing / test-mysql (pull_request) Has been skipped
testing / frontend-checks (pull_request) Successful in 1m2s
testing / backend-checks (pull_request) Failing after 3m55s
testing / test-remote-cacher (valkey) (pull_request) Has been skipped
testing / test-sqlite (pull_request) Has been skipped
testing / test-pgsql (pull_request) Has been skipped
testing / test-remote-cacher (garnet) (pull_request) Has been skipped
testing / test-remote-cacher (redis) (pull_request) Has been skipped
b2a4c888d3
go-swagger only emits a definition for a struct reachable from a declared
response or parameter body, so the handler's $ref to
#/definitions/EgressUsageReport resolved to nothing and both lint-swagger
and swagger-validate failed. Declaring it in swaggerParameterBodies, the
same way CreateQuotaRuleOptions is, emits the definition.
fix(tests): use require for the in-loop egress period assertion
All checks were successful
testing / backend-checks (pull_request) Successful in 6m15s
testing / frontend-checks (pull_request) Successful in 1m2s
testing / test-unit (pull_request) Successful in 10m32s
testing / test-remote-cacher (garnet) (pull_request) Successful in 3m2s
testing / test-remote-cacher (valkey) (pull_request) Successful in 3m2s
testing / test-remote-cacher (redis) (pull_request) Successful in 3m2s
testing / test-mysql (pull_request) Successful in 31m21s
testing / test-e2e (pull_request) Successful in 28m52s
testing / test-sqlite (pull_request) Successful in 46m42s
testing / test-pgsql (pull_request) Successful in 49m44s
6dcf34e0fb
testifylint's require-error flags an error assertion that is not in
terminal position, which the ErrorAs inside the bad-period loop is. The
identical call at the end of TestLimitSubjectsValidateRejectsEgressMixedWithSize
is terminal and is correctly left as assert.
pat-s left a comment

We also need a README entry.

We also need a README entry.
@ -0,0 +1,215 @@
// Copyright 2026 The Codefloe Authors. All rights reserved.
Author
Owner

all new codefloe files should start with codefloe_

all new codefloe files should start with `codefloe_`
pat-s marked this conversation as resolved
@ -0,0 +1,32 @@
// Copyright 2026 The Codefloe Authors. All rights reserved.
Author
Owner

all new codefloe files should start with codefloe_

all new codefloe files should start with codefloe_
pat-s marked this conversation as resolved
@ -0,0 +1,142 @@
// Copyright 2026 The Codefloe Authors. All rights reserved.
Author
Owner

all new codefloe files should start with codefloe_

all new codefloe files should start with codefloe_
pat-s marked this conversation as resolved
@ -0,0 +1,33 @@
{{template "admin/layout_head" (dict "ctxData" . "pageClass" "admin egress")}}
Author
Owner

all new codefloe files should start with codefloe_

all new codefloe files should start with codefloe_
pat-s marked this conversation as resolved
Rename every file this branch added under the egress quota feature to
carry the codefloe_ prefix, per review on PR #142, and update the
tplEgress template-name string and a stale doc-comment path that
referenced the old file name.
docs(readme): document the egress quota feature
All checks were successful
testing / frontend-checks (pull_request) Successful in 1m7s
testing / backend-checks (pull_request) Successful in 9m40s
testing / test-remote-cacher (redis) (pull_request) Successful in 1m48s
testing / test-remote-cacher (garnet) (pull_request) Successful in 1m52s
testing / test-unit (pull_request) Successful in 7m59s
testing / test-remote-cacher (valkey) (pull_request) Successful in 2m15s
testing / test-mysql (pull_request) Successful in 31m39s
testing / test-e2e (pull_request) Successful in 34m5s
testing / test-sqlite (pull_request) Successful in 56m51s
testing / test-pgsql (pull_request) Successful in 59m52s
c6dafdad22
Add a Custom changes row for the fork-owned egress-usage tracking,
display-only quota UI integration, admin top-consumers page, and the
aggregator reporting/over-quota API added in PR #142.
Author
Owner

Both addressed, in e126ee3 (renames) and c6dafda (README).

codefloe_ prefix. Applied to every new file the branch adds, not only the four you marked, since it reads as a general convention rather than four individual nits. That is 13 files across models/quota, modules/structs, routers/api/v1/{admin,swagger}, routers/web/admin, templates/admin and tests/integration.

One deliberate exception, please overrule me if you disagree: models/codefloe_migrations/v15.go and v15_test.go are left unprefixed. Every existing file in that directory is a bare vN.go / vN_test.go because the directory itself already carries the marker, so codefloe_v15.go would be the odd one out in its own package. Happy to rename if you would rather the rule be literal everywhere.

Worth flagging one thing this touched, because it is the kind of break that ships silently: templates/admin/egress.tmpl is referenced by string from the handler, so renaming the file without updating tplEgress yields a page that compiles and vets cleanly and only 500s at render time. It is now admin/codefloe_egress, verified by a temporary integration test that GETs the admin page and asserts 200 (removed again afterwards, since the repo has no permanent template-render test to hang it on).

README. Added a Custom changes row at the top, Added: Pending, matching the existing rows' voice: what is measured, that it is display-only inside Forgejo with enforcement at the edge proxy, the top-consumers admin page, and the two admin API endpoints the external aggregator uses.

Full check run after the renames: fmt-check, tidy-check, swagger-check, lint-swagger, swagger-validate, deadcode and the models/quota suite all pass. make lint-go cannot run in my environment (Go 1.27.1 emits export data version 4, above golangci-lint's supported maximum of 2), so CI remains the only check on that one; it was green on the previous head and nothing in these two commits touches a testify assertion.

Both addressed, in `e126ee3` (renames) and `c6dafda` (README). **`codefloe_` prefix.** Applied to every new file the branch adds, not only the four you marked, since it reads as a general convention rather than four individual nits. That is 13 files across `models/quota`, `modules/structs`, `routers/api/v1/{admin,swagger}`, `routers/web/admin`, `templates/admin` and `tests/integration`. One deliberate exception, please overrule me if you disagree: `models/codefloe_migrations/v15.go` and `v15_test.go` are left unprefixed. Every existing file in that directory is a bare `vN.go` / `vN_test.go` because the directory itself already carries the marker, so `codefloe_v15.go` would be the odd one out in its own package. Happy to rename if you would rather the rule be literal everywhere. Worth flagging one thing this touched, because it is the kind of break that ships silently: `templates/admin/egress.tmpl` is referenced by string from the handler, so renaming the file without updating `tplEgress` yields a page that compiles and vets cleanly and only 500s at render time. It is now `admin/codefloe_egress`, verified by a temporary integration test that GETs the admin page and asserts 200 (removed again afterwards, since the repo has no permanent template-render test to hang it on). **README.** Added a `Custom changes` row at the top, `Added: Pending`, matching the existing rows' voice: what is measured, that it is display-only inside Forgejo with enforcement at the edge proxy, the top-consumers admin page, and the two admin API endpoints the external aggregator uses. Full check run after the renames: `fmt-check`, `tidy-check`, `swagger-check`, `lint-swagger`, `swagger-validate`, `deadcode` and the `models/quota` suite all pass. `make lint-go` cannot run in my environment (Go 1.27.1 emits export data version 4, above golangci-lint's supported maximum of 2), so CI remains the only check on that one; it was green on the previous head and nothing in these two commits touches a testify assertion.
Author
Owner

Review findings

Ten verified findings, most severe first.
Three are blocking, the rest are correctness gaps worth closing before merge.

Blocking

1. Egress-only groups deny every write (models/quota/limit_subject_codefloe.go:105)
egress:all is absent from subjectToUnit, so its Unit() is LimitUnitBytes.
relevantTo / groupLimitsUnit therefore keep an egress-only group for every size:* evaluation, no rule matches, and GroupList.Evaluate returns false.
Verified with a test on the branch: a group {egress:all, 1 TiB} mapped to fixture user 2 with DEFAULT_GROUPS empty makes EvaluateForUser return allow=false for size:repos:all, size:all, size:git:lfs and size:assets:packages:all at 0 egress bytes, so pre-receive, LFS, package and mirror writes are refused.
The same setup with a time:ci:all rule allows, because seconds-unit groups are filtered out.
Suggested fix: give egress its own LimitUnit (admitted in the storage overview unit filter).
That also makes Unit() reject size:all + egress:all, so LimitSubjects.Validate becomes unnecessary, and it keeps egress out of the storage sweep (finding 6).

2. Duplicate-key retry runs inside an aborted Postgres transaction (models/quota/codefloe_egress.go:140)
The recovery path re-issues the conditional UPDATE inside the same db.WithTx after the INSERT failed.
On PostgreSQL the transaction is already aborted, so the retry fails with SQLSTATE 25P02 and AddEgress returns an error instead of the documented no-op.
Two concurrent POST /admin/egress/usage calls on a fresh (user_id, period) produce a 500 and the aggregator replays the run.
models/unittest hardcodes sqlite3 with _txlock=immediate, so the tests cannot exercise this.
Precedent for the right shape is postgresGetNextResourceIndex in models/db/index.go: a per-dialect INSERT ... ON CONFLICT DO UPDATE that needs no transaction and no driver error matching.

3. Unconditional go-sqlite3 import breaks CGO_ENABLED=0 builds (models/quota/codefloe_egress.go:18)
The import exists only for isDuplicateKeyError.
Verified: CGO_ENABLED=0 go build . succeeds on base and fails on the PR with undefined: sqlite3.Error / undefined: sqlite3.ErrConstraint.
Every non-sqlite-tag build now also compiles the SQLite amalgamation.
Upstream only imports the driver behind //go:build sqlite.
The mysql and pgconn imports are pre-existing deps of models/db; only sqlite3 is new.
The upsert from finding 2 removes all three imports.

Correctness gaps

4. Three surfaces disagree at bytes == limit (models/quota/quota.go:49)
EvaluateForUser passes raw used.Egress to GroupList.Evaluate (Sum < Limit), isOverEgressQuota feeds bytes-1, and the settings page uses Rule.Acceptable (Sum <= Limit).
With limit 100 and usage 100: /user/quota/check?subject=egress:all reports over quota, /admin/egress/over-quota omits the owner so HAProxy does not block, and the settings page renders a green tick.
No test covers the exact boundary.
Put the boundary in one helper and route all three through it.

5. Mixed egress/size rule returns 500 from group create (routers/api/v1/admin/quota_group.go:121)
CreateQuotaGroup's inline-rule path calls the same toLimitSubjects that now returns ErrRuleMixesEgressWithSize, but its error mapping only knows IsErrParseLimitSubjectUnrecognized and IsErrMixedLimitUnits.
POST /admin/quota/groups with subjects: ["size:all", "egress:all"] falls through to ctx.Error(500, ...), while POST /admin/quota/rules returns 422 for the same input.
There is also no IsErrRuleMixesEgressWithSize predicate anywhere; add one and a 422 branch.

6. The low-storage sweep from #138 now picks up egress rules (services/codefloe/quota_storage/sweep.go:197)
The sweep selects rules via RulesForUnit(groups, LimitUnitBytes) and builds Used{Size: ...} with Egress left at 0.
A group with size:all = -1 and egress:all = 100 GiB now sets capped = true for every owner, switching from the purge-all branch to per-key bookkeeping, and DecideForRule evaluates egress at a permanent 0%.
An owner at 95% egress never receives a threshold mail even though the settings page shows 95% for the same rule.
Either exclude LimitSubjectEgressAll there or give egress its own unit (finding 1).

7. /admin/egress routes ignore [quota] ENABLED (routers/api/v1/api.go:1402)
The routes are registered outside the if setting.Quota.Enabled block and ListOverEgressQuota never checks the flag.
With quota disabled during an incident, the over-quota list still names owners, the hourly aggregator keeps them in the deny map and downloads stay blocked, while /user/quota/check says fine, StorageOverview 404s and /admin/quota/* is unregistered so the admin cannot edit the blocking rule.
Return an empty list or gate the route when quota is disabled.

8. The API exposes no egress usage (services/convert/quota.go:34)
toQuotaInfoUsed still maps only Used.Size, so GET /user/quota, /orgs/{org}/quota and /admin/users/{u}/quota list the egress:all rule and limit but no consumption.
The only signal is the boolean from /user/quota/check.
The fork's time:ci:* precedent added a dedicated api.QuotaCIUsed; egress needs an equivalent field or endpoint plus the converter line.

9. Replay guard remembers only the most recent run id (models/quota/codefloe_egress.go:153)
last_run_id <> ? holds one slot per (user, period), so a replay of run N after run N+1 has been applied double-counts N's bytes.
The comments on AddEgress and PostEgressUsage claim idempotency per (owner, period, run id).
The sequential partial-failure retry is safe, but the interleaved A,B,A sequence is neither excluded by a documented precondition nor covered by the tests.
Either document the single-slot contract explicitly or key idempotency on a per-run table.

10. Unchunked IN queries in the over-quota lookup (models/quota/codefloe_egress_overquota.go:196)
getGroupsForUsers passes every active owner id of the month as one In("mapped_id", userIDs) and GetUsersByIDs is likewise unchunked, bounded only by the bind-parameter ceiling.
The codebase already has db.GetByFieldIn / db.GetByIDs with DefaultMaxInSize = 500, and the fork already has a bulk group resolver in services/codefloe/quota_storage/sweep.go (loadGroupIndex) that this function re-implements.
Promoting loadGroupIndex to an exported models/quota.GetGroupsForUsers removes the third copy and the bound at once.

Lower severity, also confirmed

  • run_id length is not validated against the VARCHAR(64) column; the paired aggregator sends 36-char UUIDs today.
  • GetUsedForUser performs an extra user_egress_usage read on every write-path call; it could sit behind the existing subject == LimitSubjectEgressAll gate.
  • PostEgressUsage does one GetUserByName and one transaction per owner; wrapping the loop in a single db.WithTx is a drop-in since WithTx joins an outer transaction.
  • Retention pruning runs inline in the handler with a duplicated "2006-01" literal; a cron task with a setting like cleanup_quota_ci_records matches the fork's existing pattern.
## Review findings Ten verified findings, most severe first. Three are blocking, the rest are correctness gaps worth closing before merge. ### Blocking **1. Egress-only groups deny every write** (`models/quota/limit_subject_codefloe.go:105`) `egress:all` is absent from `subjectToUnit`, so its `Unit()` is `LimitUnitBytes`. `relevantTo` / `groupLimitsUnit` therefore keep an egress-only group for every `size:*` evaluation, no rule matches, and `GroupList.Evaluate` returns false. Verified with a test on the branch: a group `{egress:all, 1 TiB}` mapped to fixture user 2 with `DEFAULT_GROUPS` empty makes `EvaluateForUser` return `allow=false` for `size:repos:all`, `size:all`, `size:git:lfs` and `size:assets:packages:all` at 0 egress bytes, so pre-receive, LFS, package and mirror writes are refused. The same setup with a `time:ci:all` rule allows, because seconds-unit groups are filtered out. Suggested fix: give egress its own `LimitUnit` (admitted in the storage overview unit filter). That also makes `Unit()` reject `size:all` + `egress:all`, so `LimitSubjects.Validate` becomes unnecessary, and it keeps egress out of the storage sweep (finding 6). **2. Duplicate-key retry runs inside an aborted Postgres transaction** (`models/quota/codefloe_egress.go:140`) The recovery path re-issues the conditional UPDATE inside the same `db.WithTx` after the INSERT failed. On PostgreSQL the transaction is already aborted, so the retry fails with SQLSTATE 25P02 and `AddEgress` returns an error instead of the documented no-op. Two concurrent `POST /admin/egress/usage` calls on a fresh `(user_id, period)` produce a 500 and the aggregator replays the run. `models/unittest` hardcodes sqlite3 with `_txlock=immediate`, so the tests cannot exercise this. Precedent for the right shape is `postgresGetNextResourceIndex` in `models/db/index.go`: a per-dialect `INSERT ... ON CONFLICT DO UPDATE` that needs no transaction and no driver error matching. **3. Unconditional `go-sqlite3` import breaks `CGO_ENABLED=0` builds** (`models/quota/codefloe_egress.go:18`) The import exists only for `isDuplicateKeyError`. Verified: `CGO_ENABLED=0 go build .` succeeds on base and fails on the PR with `undefined: sqlite3.Error` / `undefined: sqlite3.ErrConstraint`. Every non-sqlite-tag build now also compiles the SQLite amalgamation. Upstream only imports the driver behind `//go:build sqlite`. The mysql and pgconn imports are pre-existing deps of `models/db`; only sqlite3 is new. The upsert from finding 2 removes all three imports. ### Correctness gaps **4. Three surfaces disagree at `bytes == limit`** (`models/quota/quota.go:49`) `EvaluateForUser` passes raw `used.Egress` to `GroupList.Evaluate` (`Sum < Limit`), `isOverEgressQuota` feeds `bytes-1`, and the settings page uses `Rule.Acceptable` (`Sum <= Limit`). With limit 100 and usage 100: `/user/quota/check?subject=egress:all` reports over quota, `/admin/egress/over-quota` omits the owner so HAProxy does not block, and the settings page renders a green tick. No test covers the exact boundary. Put the boundary in one helper and route all three through it. **5. Mixed egress/size rule returns 500 from group create** (`routers/api/v1/admin/quota_group.go:121`) `CreateQuotaGroup`'s inline-rule path calls the same `toLimitSubjects` that now returns `ErrRuleMixesEgressWithSize`, but its error mapping only knows `IsErrParseLimitSubjectUnrecognized` and `IsErrMixedLimitUnits`. `POST /admin/quota/groups` with `subjects: ["size:all", "egress:all"]` falls through to `ctx.Error(500, ...)`, while `POST /admin/quota/rules` returns 422 for the same input. There is also no `IsErrRuleMixesEgressWithSize` predicate anywhere; add one and a 422 branch. **6. The low-storage sweep from #138 now picks up egress rules** (`services/codefloe/quota_storage/sweep.go:197`) The sweep selects rules via `RulesForUnit(groups, LimitUnitBytes)` and builds `Used{Size: ...}` with `Egress` left at 0. A group with `size:all = -1` and `egress:all = 100 GiB` now sets `capped = true` for every owner, switching from the purge-all branch to per-key bookkeeping, and `DecideForRule` evaluates egress at a permanent 0%. An owner at 95% egress never receives a threshold mail even though the settings page shows 95% for the same rule. Either exclude `LimitSubjectEgressAll` there or give egress its own unit (finding 1). **7. `/admin/egress` routes ignore `[quota] ENABLED`** (`routers/api/v1/api.go:1402`) The routes are registered outside the `if setting.Quota.Enabled` block and `ListOverEgressQuota` never checks the flag. With quota disabled during an incident, the over-quota list still names owners, the hourly aggregator keeps them in the deny map and downloads stay blocked, while `/user/quota/check` says fine, `StorageOverview` 404s and `/admin/quota/*` is unregistered so the admin cannot edit the blocking rule. Return an empty list or gate the route when quota is disabled. **8. The API exposes no egress usage** (`services/convert/quota.go:34`) `toQuotaInfoUsed` still maps only `Used.Size`, so `GET /user/quota`, `/orgs/{org}/quota` and `/admin/users/{u}/quota` list the `egress:all` rule and limit but no consumption. The only signal is the boolean from `/user/quota/check`. The fork's `time:ci:*` precedent added a dedicated `api.QuotaCIUsed`; egress needs an equivalent field or endpoint plus the converter line. **9. Replay guard remembers only the most recent run id** (`models/quota/codefloe_egress.go:153`) `last_run_id <> ?` holds one slot per `(user, period)`, so a replay of run N after run N+1 has been applied double-counts N's bytes. The comments on `AddEgress` and `PostEgressUsage` claim idempotency per `(owner, period, run id)`. The sequential partial-failure retry is safe, but the interleaved A,B,A sequence is neither excluded by a documented precondition nor covered by the tests. Either document the single-slot contract explicitly or key idempotency on a per-run table. **10. Unchunked `IN` queries in the over-quota lookup** (`models/quota/codefloe_egress_overquota.go:196`) `getGroupsForUsers` passes every active owner id of the month as one `In("mapped_id", userIDs)` and `GetUsersByIDs` is likewise unchunked, bounded only by the bind-parameter ceiling. The codebase already has `db.GetByFieldIn` / `db.GetByIDs` with `DefaultMaxInSize = 500`, and the fork already has a bulk group resolver in `services/codefloe/quota_storage/sweep.go` (`loadGroupIndex`) that this function re-implements. Promoting `loadGroupIndex` to an exported `models/quota.GetGroupsForUsers` removes the third copy and the bound at once. ### Lower severity, also confirmed - `run_id` length is not validated against the `VARCHAR(64)` column; the paired aggregator sends 36-char UUIDs today. - `GetUsedForUser` performs an extra `user_egress_usage` read on every write-path call; it could sit behind the existing `subject == LimitSubjectEgressAll` gate. - `PostEgressUsage` does one `GetUserByName` and one transaction per owner; wrapping the loop in a single `db.WithTx` is a drop-in since `WithTx` joins an outer transaction. - Retention pruning runs inline in the handler with a duplicated `"2006-01"` literal; a cron task with a setting like `cleanup_quota_ci_records` matches the fork's existing pattern.
Author
Owner

Addendum

Two further consequences of finding 1 (egress sharing LimitUnitBytes), plus a few cleanups.

1a. The storage card hides the missing size rule (routers/web/shared/codefloe_quota_ci.go:44)
sizeQuotaGroups keeps egress:all rules because they report the bytes unit.
For an owner whose only group is an egress group, the storage overview therefore does not synthesise the Default size:all row and shows a single green egress bar, while every push, LFS and package upload is rejected with "quota exceeded".
The page and the enforcement disagree in the direction that hides the cause from the user.

6a. The sweep also drops the default storage fallback (services/codefloe/quota_storage/sweep.go:197)
RulesForUnit(groups, LimitUnitBytes, storageDefaultRule()) returns the egress rule, so the [quota.default] TOTAL fallback is no longer applied.
An owner in an egress-only group can fill storage well past the instance default and never receive a threshold mail.

Both go away if egress gets its own LimitUnit.
quota_notify/rules.go:50 filters on the bytes unit as well and needs the same adjustment.

Test does not guard what it claims (models/codefloe_migrations/v15_test.go)
The test syncs a hand-written liveUserEgressUsageShape rather than quota.EgressUsage, so editing the model without editing the copy passes silently, contrary to the comment "changing EgressUsage without touching v15 has to fail here".
models/quota does not depend on codefloe_migrations, so the test can x.Sync(new(quota.EgressUsage)) directly.

Cleanups

  • ErrRuleMixesEgressWithSize is a fieldless struct with no IsErr helper, matching neither the errors.go pattern nor the sentinel idiom; if the unit change is out of scope, make it a sentinel checked with errors.Is (see finding 5).
  • PostEgressUsage keeps an ordered slice and a pointer map to aggregate deltas; a map[int64]int64 with += does the same job, and slices.Sorted(maps.Keys(...)) gives deterministic order if wanted.
  • TopEgressConsumers and ListOverEgressQuota copy the same id-collection, GetUsersByIDs and name-map block; one egressOwnerNames helper keeps the deleted-user contract in one place.
  • Nine tests in codefloe_egress_overquota_test.go repeat the same five-line group/rule/mapping setup; a small egressGroup(t, ctx, name, limit, userIDs...) helper would make each test's intent visible.
## Addendum Two further consequences of finding 1 (egress sharing `LimitUnitBytes`), plus a few cleanups. **1a. The storage card hides the missing size rule** (`routers/web/shared/codefloe_quota_ci.go:44`) `sizeQuotaGroups` keeps `egress:all` rules because they report the bytes unit. For an owner whose only group is an egress group, the storage overview therefore does not synthesise the `Default` `size:all` row and shows a single green egress bar, while every push, LFS and package upload is rejected with "quota exceeded". The page and the enforcement disagree in the direction that hides the cause from the user. **6a. The sweep also drops the default storage fallback** (`services/codefloe/quota_storage/sweep.go:197`) `RulesForUnit(groups, LimitUnitBytes, storageDefaultRule())` returns the egress rule, so the `[quota.default] TOTAL` fallback is no longer applied. An owner in an egress-only group can fill storage well past the instance default and never receive a threshold mail. Both go away if egress gets its own `LimitUnit`. `quota_notify/rules.go:50` filters on the bytes unit as well and needs the same adjustment. **Test does not guard what it claims** (`models/codefloe_migrations/v15_test.go`) The test syncs a hand-written `liveUserEgressUsageShape` rather than `quota.EgressUsage`, so editing the model without editing the copy passes silently, contrary to the comment "changing EgressUsage without touching v15 has to fail here". `models/quota` does not depend on `codefloe_migrations`, so the test can `x.Sync(new(quota.EgressUsage))` directly. **Cleanups** - `ErrRuleMixesEgressWithSize` is a fieldless struct with no `IsErr` helper, matching neither the `errors.go` pattern nor the sentinel idiom; if the unit change is out of scope, make it a sentinel checked with `errors.Is` (see finding 5). - `PostEgressUsage` keeps an ordered slice and a pointer map to aggregate deltas; a `map[int64]int64` with `+=` does the same job, and `slices.Sorted(maps.Keys(...))` gives deterministic order if wanted. - `TopEgressConsumers` and `ListOverEgressQuota` copy the same id-collection, `GetUsersByIDs` and name-map block; one `egressOwnerNames` helper keeps the deleted-user contract in one place. - Nine tests in `codefloe_egress_overquota_test.go` repeat the same five-line group/rule/mapping setup; a small `egressGroup(t, ctx, name, limit, userIDs...)` helper would make each test's intent visible.
Author
Owner

Addendum 2

Three structural points from the last pass.

Fork table and DAO live in upstream's models/quota (models/quota/codefloe_egress.go:53)
Every other fork table (quota_ci_usage, quota_ci_record, quota_storage_level, lease, cron_status) registers under models/codefloe/<pkg> with a codefloe_migrations Sync, and only the subject/Used glue sits in models/quota/*_codefloe.go.
This PR places the table, AddEgress, PruneEgressBefore, TopEgressConsumers, ListOverEgressQuota and the driver-specific error handling inside the upstream package, which every release rebase touches.
Moving them to models/codefloe/quota_egress matches quota_ci and keeps the new driver imports out of upstream code.

Egress read on every write path (models/quota/used.go:295)
GetUsedForUser now queries user_egress_usage on every pre-receive, LFS, package, artifact and mirror check, and logs an error on each push if the table is broken.
Only StorageOverview and the egress:all branch of EvaluateForUser ever read the value.
The fork already has the pattern for this: used_codefloe.go gates loadCodefloeTime and offers GetUsedTimeForUser for the enforcement path.
Mirror it with a GetUsedEgressForUser, call it only for LimitSubjectEgressAll, and have the overview load it explicitly; the fail-open branch and its justification then disappear.

Boundary fix at the right altitude (models/quota/codefloe_egress_overquota.go:128)
Egress is a state question ("is what I have within limit?"), which is Rule.Acceptable semantics; the bytes-1 shim instead feeds the pre-write gate and relies on the bytes > 0 WHERE clause to stay correct.
There is no OR-across-groups Acceptable helper today.
Adding GroupList.Acceptable(used, subject) in group_codefloe.go and using it here and in quota_ci/info.go gives the tick, the deny list and the API check one comparison (see finding 4).
Note Assess also returns Allowed=false, Rule=nil for a user with no egress rule today, another symptom of finding 1 that the own-unit fix resolves.

## Addendum 2 Three structural points from the last pass. **Fork table and DAO live in upstream's `models/quota`** (`models/quota/codefloe_egress.go:53`) Every other fork table (`quota_ci_usage`, `quota_ci_record`, `quota_storage_level`, `lease`, `cron_status`) registers under `models/codefloe/<pkg>` with a `codefloe_migrations` Sync, and only the subject/Used glue sits in `models/quota/*_codefloe.go`. This PR places the table, `AddEgress`, `PruneEgressBefore`, `TopEgressConsumers`, `ListOverEgressQuota` and the driver-specific error handling inside the upstream package, which every release rebase touches. Moving them to `models/codefloe/quota_egress` matches `quota_ci` and keeps the new driver imports out of upstream code. **Egress read on every write path** (`models/quota/used.go:295`) `GetUsedForUser` now queries `user_egress_usage` on every pre-receive, LFS, package, artifact and mirror check, and logs an error on each push if the table is broken. Only `StorageOverview` and the `egress:all` branch of `EvaluateForUser` ever read the value. The fork already has the pattern for this: `used_codefloe.go` gates `loadCodefloeTime` and offers `GetUsedTimeForUser` for the enforcement path. Mirror it with a `GetUsedEgressForUser`, call it only for `LimitSubjectEgressAll`, and have the overview load it explicitly; the fail-open branch and its justification then disappear. **Boundary fix at the right altitude** (`models/quota/codefloe_egress_overquota.go:128`) Egress is a state question ("is what I have within limit?"), which is `Rule.Acceptable` semantics; the `bytes-1` shim instead feeds the pre-write gate and relies on the `bytes > 0` WHERE clause to stay correct. There is no OR-across-groups `Acceptable` helper today. Adding `GroupList.Acceptable(used, subject)` in `group_codefloe.go` and using it here and in `quota_ci/info.go` gives the tick, the deny list and the API check one comparison (see finding 4). Note `Assess` also returns `Allowed=false, Rule=nil` for a user with no egress rule today, another symptom of finding 1 that the own-unit fix resolves.
Author
Owner

Addendum 3

Last batch, all reuse items.

  • Second month-period convention (models/quota/codefloe_egress.go:59): quota_ci already has PeriodFor, CurrentPeriod, PeriodShift built on timeutil.TimeStampNow() so tests can pin the clock. The egress code reads time.Now() directly here and in the prune call, which is why the integration tests have to compute the period at runtime. Derive the egress period and the prune cutoff from the quota_ci helpers so both ledgers share one clock.
  • HasEgressRule duplicates cappingGroups (models/quota/codefloe_egress_overquota.go:142): GroupList.cappingGroups(subject) in group_codefloe.go already does the same subject-membership walk. A one-line wrapper or an exported HasRuleFor avoids two copies of the matching logic. Moot if egress gets its own unit, since both pre-checks can then be deleted.
  • Integration test leaks its group and rule (tests/integration/codefloe_api_admin_egress_test.go:118): the inline setup repeats quotaCISubjectRule from actions_quota_ci_test.go without its cleanup, so the group and rule persist into later tests in the package. defer quotaCISubjectRule(t, user2, 100, quota.LimitSubjectEgressAll)() is a drop-in.
  • The 50-goroutine race test cannot exhibit the race (models/quota/codefloe_egress_test.go:89): SQLite serialises the writers, as the comment admits, so it would pass against a broken implementation. Three deterministic calls (same run id twice, existing row with new run id, empty period) cover both branches; keep a small goroutine count only as a deadlock smoke test.
## Addendum 3 Last batch, all reuse items. - **Second month-period convention** (`models/quota/codefloe_egress.go:59`): `quota_ci` already has `PeriodFor`, `CurrentPeriod`, `PeriodShift` built on `timeutil.TimeStampNow()` so tests can pin the clock. The egress code reads `time.Now()` directly here and in the prune call, which is why the integration tests have to compute the period at runtime. Derive the egress period and the prune cutoff from the `quota_ci` helpers so both ledgers share one clock. - **`HasEgressRule` duplicates `cappingGroups`** (`models/quota/codefloe_egress_overquota.go:142`): `GroupList.cappingGroups(subject)` in `group_codefloe.go` already does the same subject-membership walk. A one-line wrapper or an exported `HasRuleFor` avoids two copies of the matching logic. Moot if egress gets its own unit, since both pre-checks can then be deleted. - **Integration test leaks its group and rule** (`tests/integration/codefloe_api_admin_egress_test.go:118`): the inline setup repeats `quotaCISubjectRule` from `actions_quota_ci_test.go` without its cleanup, so the group and rule persist into later tests in the package. `defer quotaCISubjectRule(t, user2, 100, quota.LimitSubjectEgressAll)()` is a drop-in. - **The 50-goroutine race test cannot exhibit the race** (`models/quota/codefloe_egress_test.go:89`): SQLite serialises the writers, as the comment admits, so it would pass against a broken implementation. Three deterministic calls (same run id twice, existing row with new run id, empty period) cover both branches; keep a small goroutine count only as a deadlock smoke test.
Author
Owner

Addendum 4

One confirmed wedge and two plausible consistency gaps from a cross-file trace.

An empty owner rejects the whole run (modules/structs/codefloe_egress.go:9, routers/api/v1/api.go:1403)
EgressDelta.Owner carries binding:"Required", and go-chi/binding validateField recurses into slices of structs, so a report with one delta whose owner is empty fails with 422 "Owner: Required" before PostEgressUsage runs.
The handler's own IsErrUserNotExist branch shows unknown owners are meant to be skipped, but binding fires first.
If the aggregator ever emits an unattributed row, nothing from that run is applied and the aggregator replays the same 422 until someone intervenes.
Drop the tag on Owner and let the handler skip empty names alongside unknown ones, or make the aggregator contract explicit that it never sends them.

Group names resolved by Go map versus SQL collation (models/quota/codefloe_egress_overquota.go:203, plausible)
GetGroupsForUser matches mapping and default group names through SQL, so a case-insensitive MySQL collation matches Default against default.
getGroupsForUsers resolves the same names with byte-exact map lookups, so on such a collation the two disagree: the user check reports over quota while the deny list omits the owner.
Reusing the existing per-user resolver, or the sweep's loadGroupIndex (see finding 10), removes the second code path.

Period boundary depends on the aggregator's clock (models/quota/used.go:296, plausible)
Forgejo reads egress for CurrentPeriod() in UTC while the aggregator supplies period verbatim and nothing rejects a non-current value.
If the aggregator computes the month in local time, the two disagree for a window around each month boundary, during which the over-quota list is empty and the settings page shows zero.
Either validate that period equals the current or previous UTC month, or document that the aggregator must use UTC.

## Addendum 4 One confirmed wedge and two plausible consistency gaps from a cross-file trace. **An empty owner rejects the whole run** (`modules/structs/codefloe_egress.go:9`, `routers/api/v1/api.go:1403`) `EgressDelta.Owner` carries `binding:"Required"`, and `go-chi/binding` `validateField` recurses into slices of structs, so a report with one delta whose owner is empty fails with 422 "Owner: Required" before `PostEgressUsage` runs. The handler's own `IsErrUserNotExist` branch shows unknown owners are meant to be skipped, but binding fires first. If the aggregator ever emits an unattributed row, nothing from that run is applied and the aggregator replays the same 422 until someone intervenes. Drop the tag on `Owner` and let the handler skip empty names alongside unknown ones, or make the aggregator contract explicit that it never sends them. **Group names resolved by Go map versus SQL collation** (`models/quota/codefloe_egress_overquota.go:203`, plausible) `GetGroupsForUser` matches mapping and default group names through SQL, so a case-insensitive MySQL collation matches `Default` against `default`. `getGroupsForUsers` resolves the same names with byte-exact map lookups, so on such a collation the two disagree: the user check reports over quota while the deny list omits the owner. Reusing the existing per-user resolver, or the sweep's `loadGroupIndex` (see finding 10), removes the second code path. **Period boundary depends on the aggregator's clock** (`models/quota/used.go:296`, plausible) Forgejo reads egress for `CurrentPeriod()` in UTC while the aggregator supplies `period` verbatim and nothing rejects a non-current value. If the aggregator computes the month in local time, the two disagree for a window around each month boundary, during which the over-quota list is empty and the settings page shows zero. Either validate that `period` equals the current or previous UTC month, or document that the aggregator must use UTC.
Author
Owner

Addendum 5

One last point on the fail-open read, which reinforces the recommendation in Addendum 2.

Fail-open is not fail-open on PostgreSQL inside a transaction (models/quota/used.go:296)
TestGetUsedForUserFailsOpenWhenEgressUnreadable proves the swallow-and-log behaviour on SQLite only.
On Postgres a failed SELECT aborts the enclosing transaction, so when GetUsedForUser is called with a ctx already inside db.WithTx, the error is logged here but the caller's next statement fails with SQLSTATE 25P02.
Current callers are not in a transaction today, so this only bites a future wrapped caller, but the comment promises a property the code cannot deliver on the production database.
Moving the egress load off the shared path (GetUsedEgressForUser, loaded only where consumed) removes the branch and the promise together.

## Addendum 5 One last point on the fail-open read, which reinforces the recommendation in Addendum 2. **Fail-open is not fail-open on PostgreSQL inside a transaction** (`models/quota/used.go:296`) `TestGetUsedForUserFailsOpenWhenEgressUnreadable` proves the swallow-and-log behaviour on SQLite only. On Postgres a failed SELECT aborts the enclosing transaction, so when `GetUsedForUser` is called with a ctx already inside `db.WithTx`, the error is logged here but the caller's next statement fails with SQLSTATE 25P02. Current callers are not in a transaction today, so this only bites a future wrapped caller, but the comment promises a property the code cannot deliver on the production database. Moving the egress load off the shared path (`GetUsedEgressForUser`, loaded only where consumed) removes the branch and the promise together.
fix(quota): address review findings on the egress quota
Some checks failed
testing / frontend-checks (pull_request) Successful in 1m7s
testing / test-remote-cacher (garnet) (pull_request) Successful in 1m16s
testing / test-remote-cacher (redis) (pull_request) Successful in 1m34s
testing / backend-checks (pull_request) Successful in 5m52s
testing / test-unit (pull_request) Successful in 5m59s
testing / test-remote-cacher (valkey) (pull_request) Successful in 1m3s
testing / test-e2e (pull_request) Successful in 25m9s
testing / test-mysql (pull_request) Failing after 26m35s
testing / test-sqlite (pull_request) Has been cancelled
testing / test-pgsql (pull_request) Has been cancelled
0ecc86ae5e
Give egress:all a limit unit of its own so that the mechanism the fork
already has for CI time keeps it apart from stored bytes everywhere:
a group holding only an egress rule no longer denies every write, the
mixed-subject check collapses into LimitSubjects.Unit and answers 422
on every rule-authoring path, the storage sweep and the storage card
select rules by unit, and an owner with no egress rule has no egress
limit without a pre-check.

- Add GroupList.Acceptable, the state comparison the settings page
  renders, and answer egress:all with it in EvaluateForUser and in the
  over-quota list, so the three surfaces agree at bytes == limit.
- Move the ledger to models/codefloe/quota_egress and the over-quota
  decision to services/codefloe/quota_egress, matching the other fork
  tables and keeping the driver imports out of models/quota.
- Drop the duplicate-key retry and the go-sqlite3, mysql and pgx
  imports; the update-then-insert shape of the other ledgers is enough
  because a lost insert race self-heals on the aggregator's retry.
- Load egress on request through Used.LoadEgress instead of inside
  GetUsedForUser, which runs on every write path.
- Return an empty over-quota list while [quota] ENABLED is off,
  matching EvaluateForUser.
- Expose egress usage in the quota API's used block.
- Read the clock through timeutil, bound the run id to the column
  width, skip empty owners instead of rejecting the run, resolve
  owners in one batched lookup, and write a report in one transaction.
- Replace the inline prune with the cleanup_quota_egress_usage cron
  task and a [quota.egress] RETENTION_PERIODS setting.
- Add GetGroupsForUsers with bounded IN lists, and sync the live model
  in the v15 migration test instead of a copy of its shape.
Author
Owner

Review findings addressed

Pushed as one commit, 0ecc86ae5e, on top of the branch.

Root cause, egress shares the bytes unit (findings 1, 1a, 5, 6, 6a, Addendum 2):
egress:all now has LimitUnitEgress.
relevantTo sets egress-only groups aside for size subjects, defaultRuleFor returns nil for the unit, RulesForUnit no longer picks egress rules into the storage sweep, and the storage card keeps egress rules but adds the storage default whenever nothing limits stored bytes.
LimitSubjects.Validate, ErrRuleMixesEgressWithSize and both HasEgressRule pre-checks are gone; the existing unit check refuses the mix and already maps to 422 on group creation.

Boundary (finding 4): new GroupList.Acceptable with the settings page's comparison and Evaluate's precedence.
EvaluateForUser for egress:all and the over-quota list both use it; the bytes-1 shim is gone.

Postgres retry and driver imports (findings 2, 3): the duplicate-key branch and the sqlite3, mysql and pgx imports are removed.
Add is now update-then-insert like quota_ci.addSeconds; a lost first-row race returns an error and the aggregator's retry applies it.
CGO_ENABLED=0 go build . passes again and go-licenses.json is back to base.

Quota disabled (finding 7): OverQuota returns an empty list while [quota] ENABLED is off, with a unit and an integration test.

API usage (finding 8): QuotaUsed.egress is set from the ledger in /user/quota, /orgs/{org}/quota and /admin/users/{u}/quota; swagger regenerated.

Write path (Addendum 2, 5): GetUsedForUser no longer touches the table; Used.LoadEgress is called by the storage overview, the quota API and the egress check only, and errors propagate.

Placement (Addendum 2): ledger in models/codefloe/quota_egress, decision in services/codefloe/quota_egress, GetGroupsForUsers in models/quota/group_codefloe.go with slices.Chunk(…, db.DefaultMaxInSize) (finding 10).

Ingestion handler: run id bounded to the column width with a 422, empty owners skipped instead of failing the run (Addendum 4), owners resolved in one batched lookup, deltas summed in a map[int64]int64, and the report written in one db.WithTx.
Retention moved to the cleanup_quota_egress_usage cron task with [quota.egress] RETENTION_PERIODS (default 24), documented in app.example.ini.

Clock and periods (Addendum 3): PeriodFor, CurrentPeriod and PeriodShift read timeutil.TimeStampNow(), so tests pin the clock.

Tests: v15 migration test syncs quota_egress.Usage itself; the 50-goroutine test is replaced by deterministic cases; the integration test uses quotaCISubjectRule with its cleanup; new tests cover the unit, Acceptable, GetGroupsForUsers, the boundary through EvaluateForUser, the disabled case, the group-create 422 and the egress field in /user/quota.

Left as is

  • Replay guard still remembers one run id per owner and month.
    The contract (a run is retried until acknowledged before the next is sent) is now stated on Add and the struct, and TestAddRemembersOnlyTheLastRun pins the behaviour, rather than adding a per-run table.
  • Period boundary is documented on EgressUsageReport.Period rather than validated, so a delayed replay for a previous month is still accepted.
  • Collation (Addendum 4, plausible): GetGroupsForUsers resolves names in Go like the storage sweep does; Forgejo's self-check already warns about case-insensitive collations.
  • The storage sweep keeps its own loadGroupIndex, since it needs every mapping rather than a list of ids.

Verified locally: make lint-go on the pinned toolchain, make swagger-check, unit tests for every touched package, the egress and quota integration tests on SQLite, and the codefloe migration tests against tests/sqlite.ini.

## Review findings addressed Pushed as one commit, 0ecc86ae5e, on top of the branch. **Root cause, egress shares the bytes unit (findings 1, 1a, 5, 6, 6a, Addendum 2):** `egress:all` now has `LimitUnitEgress`. `relevantTo` sets egress-only groups aside for size subjects, `defaultRuleFor` returns nil for the unit, `RulesForUnit` no longer picks egress rules into the storage sweep, and the storage card keeps egress rules but adds the storage default whenever nothing limits stored bytes. `LimitSubjects.Validate`, `ErrRuleMixesEgressWithSize` and both `HasEgressRule` pre-checks are gone; the existing unit check refuses the mix and already maps to 422 on group creation. **Boundary (finding 4):** new `GroupList.Acceptable` with the settings page's comparison and Evaluate's precedence. `EvaluateForUser` for `egress:all` and the over-quota list both use it; the `bytes-1` shim is gone. **Postgres retry and driver imports (findings 2, 3):** the duplicate-key branch and the sqlite3, mysql and pgx imports are removed. `Add` is now update-then-insert like `quota_ci.addSeconds`; a lost first-row race returns an error and the aggregator's retry applies it. `CGO_ENABLED=0 go build .` passes again and `go-licenses.json` is back to base. **Quota disabled (finding 7):** `OverQuota` returns an empty list while `[quota] ENABLED` is off, with a unit and an integration test. **API usage (finding 8):** `QuotaUsed.egress` is set from the ledger in `/user/quota`, `/orgs/{org}/quota` and `/admin/users/{u}/quota`; swagger regenerated. **Write path (Addendum 2, 5):** `GetUsedForUser` no longer touches the table; `Used.LoadEgress` is called by the storage overview, the quota API and the egress check only, and errors propagate. **Placement (Addendum 2):** ledger in `models/codefloe/quota_egress`, decision in `services/codefloe/quota_egress`, `GetGroupsForUsers` in `models/quota/group_codefloe.go` with `slices.Chunk(…, db.DefaultMaxInSize)` (finding 10). **Ingestion handler:** run id bounded to the column width with a 422, empty owners skipped instead of failing the run (Addendum 4), owners resolved in one batched lookup, deltas summed in a `map[int64]int64`, and the report written in one `db.WithTx`. Retention moved to the `cleanup_quota_egress_usage` cron task with `[quota.egress] RETENTION_PERIODS` (default 24), documented in `app.example.ini`. **Clock and periods (Addendum 3):** `PeriodFor`, `CurrentPeriod` and `PeriodShift` read `timeutil.TimeStampNow()`, so tests pin the clock. **Tests:** v15 migration test syncs `quota_egress.Usage` itself; the 50-goroutine test is replaced by deterministic cases; the integration test uses `quotaCISubjectRule` with its cleanup; new tests cover the unit, `Acceptable`, `GetGroupsForUsers`, the boundary through `EvaluateForUser`, the disabled case, the group-create 422 and the egress field in `/user/quota`. ## Left as is - **Replay guard** still remembers one run id per owner and month. The contract (a run is retried until acknowledged before the next is sent) is now stated on `Add` and the struct, and `TestAddRemembersOnlyTheLastRun` pins the behaviour, rather than adding a per-run table. - **Period boundary** is documented on `EgressUsageReport.Period` rather than validated, so a delayed replay for a previous month is still accepted. - **Collation** (Addendum 4, plausible): `GetGroupsForUsers` resolves names in Go like the storage sweep does; Forgejo's self-check already warns about case-insensitive collations. - The storage sweep keeps its own `loadGroupIndex`, since it needs every mapping rather than a list of ids. Verified locally: `make lint-go` on the pinned toolchain, `make swagger-check`, unit tests for every touched package, the egress and quota integration tests on SQLite, and the codefloe migration tests against `tests/sqlite.ini`.
test(cron): count the egress cleanup task in the admin cron list
All checks were successful
testing / backend-checks (pull_request) Successful in 5m39s
testing / test-remote-cacher (valkey) (pull_request) Successful in 48s
testing / test-remote-cacher (garnet) (pull_request) Successful in 1m1s
testing / frontend-checks (pull_request) Successful in 1m7s
testing / test-unit (pull_request) Successful in 6m6s
testing / test-remote-cacher (redis) (pull_request) Successful in 1m33s
testing / test-e2e (pull_request) Successful in 33m22s
testing / test-mysql (pull_request) Successful in 36m12s
testing / test-sqlite (pull_request) Successful in 46m55s
testing / test-pgsql (pull_request) Successful in 47m41s
issue-labels / backporting (pull_request_target) Has been skipped
milestone / set (pull_request_target) Has been skipped
de83bd6e79
Registering cleanup_quota_egress_usage adds a row to GET /admin/cron,
which TestAPICron pins to an exact number, as #138 did for its task.
pat-s merged commit 156a172677 into v16.0/forgejo-codefloe 2026-09-19 17:49:57 +00:00
pat-s deleted branch feat/egress-quota 2026-09-19 17:49:58 +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!142
No description provided.