feat: per-owner egress quota counter #142
No reviewers
Labels
No milestone
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
codefloe/forgejo-codefloe!142
Loading…
Reference in a new issue
No description provided.
Delete branch "feat/egress-quota"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
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:
egress:all, notsize:egress:all, so it is outside thesize:family;subjectToParent, so no route ever evaluates it;LimitSubjectFirst..LimitSubjectLastrange, so it is invisible to every present and future generic subject iteration.That last point also means no upstream test needed modifying:
git diffagainst the base shows no pre-existing test file touched anywhere on this branch.A rule that lists
egress:allalongside asize:subject is rejected with 422 at both create and edit, becauseRule.Sumadds every listed subject and would otherwise conflate downloads with storage on the write path.What it adds
user_egress_usage, keyed(user_id, period)withperiodas a UTCYYYY-MMcalendar month, plus a(period, bytes)index for the two scanning queries.Accumulation is a single atomic conditional
UPDATE ... SET bytes = bytes + ?guarded onlast_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/usagetakes 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-quotareturns who is over, deferring toGroupList.Evaluateso 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 blockedcrowciandcrow-pluginsdespite 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
GetUsedForUserlogs 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.goandrouters/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:
models/codefloe_migrations/v15.go, in the fork's own sequence with its own version table, not in upstream'sforgejo_migrations. A fork-invented id in the upstream sequence makes the databaselog.Fatalunder a stock Forgejo binary, which breaks the interchangeability the fork maintains deliberately;models/quota/limit_subject_codefloe.goat 1006, continuing the existing1000 + iotaallocation 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.goandrouters/web/shared/storage_overview.goare 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-gocould not run locally (golangci-lint cannot importinternal/goarchunder 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 directCreateRulecall could still create a mixed rule.Impossible today, since the admin API is the only caller, but worth closing in a follow-up.
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.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.We also need a README entry.
@ -0,0 +1,215 @@// Copyright 2026 The Codefloe Authors. All rights reserved.all new codefloe files should start with
codefloe_@ -0,0 +1,32 @@// Copyright 2026 The Codefloe Authors. All rights reserved.all new codefloe files should start with codefloe_
@ -0,0 +1,142 @@// Copyright 2026 The Codefloe Authors. All rights reserved.all new codefloe files should start with codefloe_
@ -0,0 +1,33 @@{{template "admin/layout_head" (dict "ctxData" . "pageClass" "admin egress")}}all new codefloe files should start with codefloe_
Both addressed, in
e126ee3(renames) andc6dafda(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 acrossmodels/quota,modules/structs,routers/api/v1/{admin,swagger},routers/web/admin,templates/adminandtests/integration.One deliberate exception, please overrule me if you disagree:
models/codefloe_migrations/v15.goandv15_test.goare left unprefixed. Every existing file in that directory is a barevN.go/vN_test.gobecause the directory itself already carries the marker, socodefloe_v15.gowould 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.tmplis referenced by string from the handler, so renaming the file without updatingtplEgressyields a page that compiles and vets cleanly and only 500s at render time. It is nowadmin/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 changesrow 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,deadcodeand themodels/quotasuite all pass.make lint-gocannot 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.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:allis absent fromsubjectToUnit, so itsUnit()isLimitUnitBytes.relevantTo/groupLimitsUnittherefore keep an egress-only group for everysize:*evaluation, no rule matches, andGroupList.Evaluatereturns false.Verified with a test on the branch: a group
{egress:all, 1 TiB}mapped to fixture user 2 withDEFAULT_GROUPSempty makesEvaluateForUserreturnallow=falseforsize:repos:all,size:all,size:git:lfsandsize:assets:packages:allat 0 egress bytes, so pre-receive, LFS, package and mirror writes are refused.The same setup with a
time:ci:allrule 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()rejectsize:all+egress:all, soLimitSubjects.Validatebecomes 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.WithTxafter the INSERT failed.On PostgreSQL the transaction is already aborted, so the retry fails with SQLSTATE 25P02 and
AddEgressreturns an error instead of the documented no-op.Two concurrent
POST /admin/egress/usagecalls on a fresh(user_id, period)produce a 500 and the aggregator replays the run.models/unittesthardcodes sqlite3 with_txlock=immediate, so the tests cannot exercise this.Precedent for the right shape is
postgresGetNextResourceIndexinmodels/db/index.go: a per-dialectINSERT ... ON CONFLICT DO UPDATEthat needs no transaction and no driver error matching.3. Unconditional
go-sqlite3import breaksCGO_ENABLED=0builds (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 withundefined: 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)EvaluateForUserpasses rawused.EgresstoGroupList.Evaluate(Sum < Limit),isOverEgressQuotafeedsbytes-1, and the settings page usesRule.Acceptable(Sum <= Limit).With limit 100 and usage 100:
/user/quota/check?subject=egress:allreports over quota,/admin/egress/over-quotaomits 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 sametoLimitSubjectsthat now returnsErrRuleMixesEgressWithSize, but its error mapping only knowsIsErrParseLimitSubjectUnrecognizedandIsErrMixedLimitUnits.POST /admin/quota/groupswithsubjects: ["size:all", "egress:all"]falls through toctx.Error(500, ...), whilePOST /admin/quota/rulesreturns 422 for the same input.There is also no
IsErrRuleMixesEgressWithSizepredicate 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 buildsUsed{Size: ...}withEgressleft at 0.A group with
size:all = -1andegress:all = 100 GiBnow setscapped = truefor every owner, switching from the purge-all branch to per-key bookkeeping, andDecideForRuleevaluates 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
LimitSubjectEgressAllthere or give egress its own unit (finding 1).7.
/admin/egressroutes ignore[quota] ENABLED(routers/api/v1/api.go:1402)The routes are registered outside the
if setting.Quota.Enabledblock andListOverEgressQuotanever 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/checksays fine,StorageOverview404s 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)toQuotaInfoUsedstill maps onlyUsed.Size, soGET /user/quota,/orgs/{org}/quotaand/admin/users/{u}/quotalist theegress:allrule and limit but no consumption.The only signal is the boolean from
/user/quota/check.The fork's
time:ci:*precedent added a dedicatedapi.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
AddEgressandPostEgressUsageclaim 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
INqueries in the over-quota lookup (models/quota/codefloe_egress_overquota.go:196)getGroupsForUserspasses every active owner id of the month as oneIn("mapped_id", userIDs)andGetUsersByIDsis likewise unchunked, bounded only by the bind-parameter ceiling.The codebase already has
db.GetByFieldIn/db.GetByIDswithDefaultMaxInSize = 500, and the fork already has a bulk group resolver inservices/codefloe/quota_storage/sweep.go(loadGroupIndex) that this function re-implements.Promoting
loadGroupIndexto an exportedmodels/quota.GetGroupsForUsersremoves the third copy and the bound at once.Lower severity, also confirmed
run_idlength is not validated against theVARCHAR(64)column; the paired aggregator sends 36-char UUIDs today.GetUsedForUserperforms an extrauser_egress_usageread on every write-path call; it could sit behind the existingsubject == LimitSubjectEgressAllgate.PostEgressUsagedoes oneGetUserByNameand one transaction per owner; wrapping the loop in a singledb.WithTxis a drop-in sinceWithTxjoins an outer transaction."2006-01"literal; a cron task with a setting likecleanup_quota_ci_recordsmatches the fork's existing pattern.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)sizeQuotaGroupskeepsegress:allrules because they report the bytes unit.For an owner whose only group is an egress group, the storage overview therefore does not synthesise the
Defaultsize:allrow 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] TOTALfallback 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:50filters 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
liveUserEgressUsageShaperather thanquota.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/quotadoes not depend oncodefloe_migrations, so the test canx.Sync(new(quota.EgressUsage))directly.Cleanups
ErrRuleMixesEgressWithSizeis a fieldless struct with noIsErrhelper, matching neither theerrors.gopattern nor the sentinel idiom; if the unit change is out of scope, make it a sentinel checked witherrors.Is(see finding 5).PostEgressUsagekeeps an ordered slice and a pointer map to aggregate deltas; amap[int64]int64with+=does the same job, andslices.Sorted(maps.Keys(...))gives deterministic order if wanted.TopEgressConsumersandListOverEgressQuotacopy the same id-collection,GetUsersByIDsand name-map block; oneegressOwnerNameshelper keeps the deleted-user contract in one place.codefloe_egress_overquota_test.gorepeat the same five-line group/rule/mapping setup; a smallegressGroup(t, ctx, name, limit, userIDs...)helper would make each test's intent visible.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 undermodels/codefloe/<pkg>with acodefloe_migrationsSync, and only the subject/Used glue sits inmodels/quota/*_codefloe.go.This PR places the table,
AddEgress,PruneEgressBefore,TopEgressConsumers,ListOverEgressQuotaand the driver-specific error handling inside the upstream package, which every release rebase touches.Moving them to
models/codefloe/quota_egressmatchesquota_ciand keeps the new driver imports out of upstream code.Egress read on every write path (
models/quota/used.go:295)GetUsedForUsernow queriesuser_egress_usageon every pre-receive, LFS, package, artifact and mirror check, and logs an error on each push if the table is broken.Only
StorageOverviewand theegress:allbranch ofEvaluateForUserever read the value.The fork already has the pattern for this:
used_codefloe.gogatesloadCodefloeTimeand offersGetUsedTimeForUserfor the enforcement path.Mirror it with a
GetUsedEgressForUser, call it only forLimitSubjectEgressAll, 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.Acceptablesemantics; thebytes-1shim instead feeds the pre-write gate and relies on thebytes > 0WHERE clause to stay correct.There is no OR-across-groups
Acceptablehelper today.Adding
GroupList.Acceptable(used, subject)ingroup_codefloe.goand using it here and inquota_ci/info.gogives the tick, the deny list and the API check one comparison (see finding 4).Note
Assessalso returnsAllowed=false, Rule=nilfor a user with no egress rule today, another symptom of finding 1 that the own-unit fix resolves.Addendum 3
Last batch, all reuse items.
models/quota/codefloe_egress.go:59):quota_cialready hasPeriodFor,CurrentPeriod,PeriodShiftbuilt ontimeutil.TimeStampNow()so tests can pin the clock. The egress code readstime.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 thequota_cihelpers so both ledgers share one clock.HasEgressRuleduplicatescappingGroups(models/quota/codefloe_egress_overquota.go:142):GroupList.cappingGroups(subject)ingroup_codefloe.goalready does the same subject-membership walk. A one-line wrapper or an exportedHasRuleForavoids two copies of the matching logic. Moot if egress gets its own unit, since both pre-checks can then be deleted.tests/integration/codefloe_api_admin_egress_test.go:118): the inline setup repeatsquotaCISubjectRulefromactions_quota_ci_test.gowithout 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.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 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.Ownercarriesbinding:"Required", andgo-chi/bindingvalidateFieldrecurses into slices of structs, so a report with one delta whose owner is empty fails with 422 "Owner: Required" beforePostEgressUsageruns.The handler's own
IsErrUserNotExistbranch 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
Ownerand 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)GetGroupsForUsermatches mapping and default group names through SQL, so a case-insensitive MySQL collation matchesDefaultagainstdefault.getGroupsForUsersresolves 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 suppliesperiodverbatim 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
periodequals the current or previous UTC month, or document that the aggregator must use UTC.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)TestGetUsedForUserFailsOpenWhenEgressUnreadableproves the swallow-and-log behaviour on SQLite only.On Postgres a failed SELECT aborts the enclosing transaction, so when
GetUsedForUseris called with a ctx already insidedb.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.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:allnow hasLimitUnitEgress.relevantTosets egress-only groups aside for size subjects,defaultRuleForreturns nil for the unit,RulesForUnitno 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,ErrRuleMixesEgressWithSizeand bothHasEgressRulepre-checks are gone; the existing unit check refuses the mix and already maps to 422 on group creation.Boundary (finding 4): new
GroupList.Acceptablewith the settings page's comparison and Evaluate's precedence.EvaluateForUserforegress:alland the over-quota list both use it; thebytes-1shim is gone.Postgres retry and driver imports (findings 2, 3): the duplicate-key branch and the sqlite3, mysql and pgx imports are removed.
Addis now update-then-insert likequota_ci.addSeconds; a lost first-row race returns an error and the aggregator's retry applies it.CGO_ENABLED=0 go build .passes again andgo-licenses.jsonis back to base.Quota disabled (finding 7):
OverQuotareturns an empty list while[quota] ENABLEDis off, with a unit and an integration test.API usage (finding 8):
QuotaUsed.egressis set from the ledger in/user/quota,/orgs/{org}/quotaand/admin/users/{u}/quota; swagger regenerated.Write path (Addendum 2, 5):
GetUsedForUserno longer touches the table;Used.LoadEgressis 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 inservices/codefloe/quota_egress,GetGroupsForUsersinmodels/quota/group_codefloe.gowithslices.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 onedb.WithTx.Retention moved to the
cleanup_quota_egress_usagecron task with[quota.egress] RETENTION_PERIODS(default 24), documented inapp.example.ini.Clock and periods (Addendum 3):
PeriodFor,CurrentPeriodandPeriodShiftreadtimeutil.TimeStampNow(), so tests pin the clock.Tests: v15 migration test syncs
quota_egress.Usageitself; the 50-goroutine test is replaced by deterministic cases; the integration test usesquotaCISubjectRulewith its cleanup; new tests cover the unit,Acceptable,GetGroupsForUsers, the boundary throughEvaluateForUser, the disabled case, the group-create 422 and the egress field in/user/quota.Left as is
The contract (a run is retried until acknowledged before the next is sent) is now stated on
Addand the struct, andTestAddRemembersOnlyTheLastRunpins the behaviour, rather than adding a per-run table.EgressUsageReport.Periodrather than validated, so a delayed replay for a previous month is still accepted.GetGroupsForUsersresolves names in Go like the storage sweep does; Forgejo's self-check already warns about case-insensitive collations.loadGroupIndex, since it needs every mapping rather than a list of ids.Verified locally:
make lint-goon 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 againsttests/sqlite.ini.