feat(ha): leader-elected cron and cluster-safe locks for multi-node operation #110
No reviewers
Labels
No milestone
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
codefloe/forgejo-codefloe!110
Loading…
Reference in a new issue
No description provided.
Delete branch "feat/ha-leader-election"
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 multi-node (HA) operation to the fork: one node is elected leader through a database lease and only the leader runs cron, while every node serves requests and works queues.
Design:
docs/superpowers/specs/2026-09-06-forgejo-ha-design.md(local, gitignored) summarised incontrib/ha/README.md.Why a database lease
HA Forgejo already requires an HA PostgreSQL, so the lease lives there instead of adding etcd or embedding Raft (which needs a three-node quorum and stateful web nodes).
A Redis
SET NXlock was rejected because asynchronous replication can forget the key on failover.The pattern is the one Kubernetes controllers use: holder, expiry, fencing token, renew loop.
Components
[high_availability]settings (ENABLED,NODE_ID,LEASE_TTL,RENEW_INTERVAL) with a startup preflight that refuses node-local cache, sessions, queues, storage, indexers or SQLite.codefloe_leasetable with atomic acquire, renew and release and a fencing token (codefloe migration v13).services/codefloe/ha: elector goroutine, per-term leader context,Holdfor named leases, Prometheus gaugesgitea_codefloe_ha_is_leader{node}andgitea_codefloe_ha_lease_age_seconds.codefloe_cron_statustable so the cron monitor and dashboard show the same last-run data on every node, plus a leader line on both pages.schema-migrationlease.ha.NewPool), and stay process-local otherwise.BucketAlreadyOwnedByYouwhen two nodes create the bucket at once.contrib/ha: two-node docker compose harness, nginx round-robin, andfailover-test.sh.Verified
Two local nodes against PostgreSQL, Valkey, MinIO and Meilisearch containers:
/api/v1/admin/cronshow the cluster-wide status and the current leader.With
ENABLED = false(the default) behaviour is unchanged.Not included
forgejo codefloe ha resignCLI command and runbooks (rollout step 5 of the design).These are written down in
contrib/ha/README.mdunder "Before a production rollout", so they are not lost when this merges.Changes after independent review
An independent review of the first revision found that a hung database could keep a leader alive past its lease, that the resign margin was off by one tick, and that lost leases were silent. This revision fixes:
last renew + TTL - reneweven if a call hangs; the margin comparison is now inclusive. Tests cover a hanging store and the margin timing.Holdreturns aHeldwith aLostchannel; cron binds every run's context to it, and the lease-backed pools log at error level when a lease is lost. A renew that keeps erroring for a full TTL counts as lost.POST /api/v1/admin/cron/{task}on a follower runs the task instead of being cancelled at once.A second independent review confirmed those fixes and found that both margins were measured from the return of the store call rather than its start, and that an over-long package key could hang a request. This revision also:
Hold, which is the base of the server-side expiry, and makesHoldgive up while one more bounded attempt still fits before expiry;Changes after the third review
Rebased onto
v16.0/forgejo-codefloeand reviewed again.The review found that the configuration validation did not actually protect the elector's own deadline, that the migration lease was released before the schema work was over, and that the fencing-token read-back could be served by a replica.
Each fix is its own commit on top of the feature commit:
RENEW_INTERVALis reset to a third ofLEASE_TTLunless it is strictly below half of it.A term is given up at
lastRenewOK + LEASE_TTL - RENEW_INTERVAL, so a longer interval leaves no renewal attempt before that deadline and every term ends against a healthy database.LEASE_TTL = 15swith the defaultRENEW_INTERVAL = 10swas enough to flap leadership forever.db.InitEngineWithMigrationreturns, becauseSyncAllTablesand the registered init functions run after the migration function and issue DDL of their own.db.PrimaryEngine, which binds to the primary whatever engine the context carries and keeps the transaction's own session inside a transaction.The acquisition also fails instead of reporting success when the row cannot be read back, which previously handed out token 0, the value that means "not the leader".
The transaction around
CreateScheduleTaskstays: committing the advance first would trade a duplicate run for a lost one.makeBucketIfMissingalso acceptsBucketAlreadyExistsfrom S3 gateways that answer that for a bucket the caller owns, onceBucketExistsconfirms it.failover-test.shno longer aborts onpipefailwhen a node is unreachable, which is the normal state right after the leader is stopped.actions_model.UpdateScheduleSpeclost its last caller to the compare-and-set and is recorded in.deadcode-out.74730b4dbdbb206c269ebb206c269e679ca0572a@ -273,6 +273,9 @@ forgejo.org/routers/web/orgforgejo.org/services/authRegisterInternalIssuerForTestingforgejo.org/services/codefloe/haSetElectorForTestwhy is this deadcode?
@ -0,0 +1,80 @@; Two-node development configuration for contrib/ha/docker-compose.yml.; Every value here is a development default; do not reuse the secrets.APP_NAME = Forgejo HA devRUN_MODE = prodRUN_USER = gitWORK_PATH = /data/gitea[codefloe.ha]should be named [high_availability]
@ -0,0 +36,10 @@ports:- "5433:5432"healthcheck:test: ["CMD-SHELL", "pg_isready -U forgejo"]interval: 2stimeout: 2sretries: 30valkey:image: valkey/valkey:8-alpineuse latest
@ -0,0 +53,10 @@command: server /data --console-address :9001environment:MINIO_ROOT_USER: forgejoMINIO_ROOT_PASSWORD: forgejo123ports:- "9000:9000"- "9001:9001"meilisearch:image: getmeili/meilisearch:v1.12use latest
@ -2059,6 +2059,24 @@ LEVEL = Info;; Empty means server's location setting;DEFAULT_UI_LOCATION =;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;[codefloe.ha][high_availability]
679ca0572a233e91c3f2Addressed the review: the section is now
[high_availability](code, tests, example config, harness), and the Valkey and Meilisearch images uselatest.On the
.deadcode-outentry:SetElectorForTestis not dead, it is called from the tests inservices/cronto swap in a fake leader.make lint-goruns deadcode with theforgejo.orgmain package as the only root (plus its own tests), so a helper whose only callers are another package's tests is reported and has to be recorded in the baseline. That is the same reasonRegisterInternalIssuerForTestingandGetPrivateContextsit right above it in the file.233e91c3f237bb014bab37bb014bab33b4799198Rebased onto
v16.0/forgejo-codefloeThe branch was 27 commits behind and is now rebased onto
e7910b4d73, still a single commit (33b4799198).The only conflict was in
README.md: main's newer rows won (announcements, request budgets, page search,#111added to the database-consistency row, the reworded CI-quota row) and the HA row was re-inserted with statusPendinginstead of the old2026-09-06, matching how#123and#120are listed.go build ./...passes.Tests pass for
services/codefloe/ha,modules/codefloe/lock,modules/setting,services/cron,models/codefloeandservices/actions.models/codefloe_migrationsfails, but it fails the same way onv8_test.goandv11_test.go, with "no database host defined", so that is the pre-existing clean-checkout problem rather than this branch.There is no migration collision: main's
v12migration lives inv11.go, soCreateHATablescorrectly becamev12 -> v13.Review of the rebased revision
1. Leadership flaps forever on a healthy database
modules/setting/codefloe_ha.go:42loadHAFromonly clampsRENEW_INTERVALwhen it is greater than or equal toLEASE_TTL, butElector.deadline()islastRenewOK + (ttl - renew).As soon as
renew >= ttl/2, that deadline falls before the first renew tick, so the watchdog ends the term atttl - renewno matter how fast the database answers, and the node then re-acquires and is killed again.LEASE_TTL = 15swith the defaultRENEW_INTERVAL = 10sis enough to trigger it.The fix is to clamp to
ttl/3when2*renew >= ttl.The shipped defaults (30s/10s) and the
contrib/haharness (15s/5s) both stay on the safe side of the boundary, which is why the local two-node run never showed this.2. The migration lease is released before the schema work is finished
routers/common/db_codefloe.go:83The lease is released by a
deferaroundmigrateWithSetting, butdb.InitEngineWithMigrationrunsSyncAllTables()and the registeredinitFuncsaftermigrateFuncreturns.Two nodes booting together therefore still issue concurrent DDL there, which is the race the lease was added to prevent.
The fork's own migrations are fine, because
codefloe_migrations.Migrateis called from insidegitea_migrations.Migrateand so runs under the lease.3. A lease can be acquired with fencing token 0
models/codefloe/lease.go:65The
hasreturn ofe.Get(l)is discarded, so a read-back that finds no row returns(0, true, nil).That reports a successful acquisition with the value
Elector.Token()uses to mean "follower", and every subsequentRenewandReleasethen fails itstoken = ?predicate.The read-back can genuinely miss, because
primaryContextis a no-op whenever the context already carries an engine:db.GetEnginechecksgetEngine(ctx)before it looks atIsPinnedToPrimary.The elector itself is safe, since graceful's shutdown context carries no engine.
ha.Holdthroughlock.NewLeasePoolis not, because the merge, wiki, transfer and package-upload paths pass request contexts that do carry one.The worst case there is a
Releasewith token 0 that fails to clear the row, leaving that repository's pool blocked until the 30 s TTL expires.4. Git work now runs inside a database transaction
services/actions/schedule_tasks_codefloe.go:26The new
db.WithTxspansCreateScheduleTask, which callslazyRepoExpandLocalReusableWorkflowand reads blobs out of the repository to resolveuses: ./...references.Upstream ran that outside any transaction.
An alternative that keeps the atomicity guarantee without holding a transaction open across git work: advance the spec first with a conditional
UPDATE ... WHERE next = <old next>, and create the run only when that statement affected a row.5. Cron status is written in single-node mode as well
services/cron/tasks_codefloe.go:108codefloeRecordRunandcodefloeRecordResultare not gated onha.Enabled(), whilecodefloeMergeCronStatusreturns early when HA is off.A single-node install therefore writes a
codefloe_cron_statusrow on every cron run that nothing ever reads back.The PR description calls this out as intended, so this is a question rather than a defect.
6. The failover test aborts instead of reporting an unreachable node
contrib/ha/failover-test.sh:22is_leaderis documented to print empty when a node is unreachable, but underset -euo pipefailthe failingcurlaborts the script ata="$(is_leader a)"without printing anything.Appending
|| trueto the pipeline restores the documented behaviour.7. Smaller points
The commit message still reads "Add multi-node (HA) operation behind [codefloe.ha] ENABLED", which is stale after the rename to
[high_availability]and becomes the squash-merge message.modules/storage/minio_codefloe.go:20tolerates onlyBucketAlreadyOwnedByYou, not theBucketAlreadyExiststhat some S3-compatible gateways return for a bucket you already own.The new migration has no
v12_test.go, unlike v8 through v11.Checked and found correct
The
Lease.IsHeld()nil guard, soGetStatuswith a missing row is safe.leaseNamehashing and the 100-character bound.Balanced
CheckInandCheckOutat every pool call site, including the double-CheckOutpath inleasePool.The
scheduledDoerpointer identity that decides which runs are bound to leadership.The new
admin.monitor.ha.*locale keys againstFormatMessage's argument order.setHADatacovering both templates that read.CodefloeHA; no other handler rendersadmin/dashboardoradmin/cron.All seven findings are addressed, one commit each on top of
33b4799198.539584b58cRENEW_INTERVALis reset toLEASE_TTL/3unless it is strictly below half the TTL, so a renewal is always attempted before the elector's own deadline87e6e32ddcdb.InitEngineWithMigrationreturns, coveringSyncAllTablesand the init functions34b007ec64db.PrimaryEngine, and an acquisition whose row cannot be read back fails instead of handing out token 056da6a6715c12aeb7aaac050057da3failover-test.shsurvives an unreachable node underpipefail0460b90021makeBucketIfMissingalso acceptsBucketAlreadyExistsonceBucketExistsconfirms the bucket11f1b5e8cd8da190deddactions_model.UpdateScheduleSpeclost its last caller and is recorded in.deadcode-outTwo of the items deserve a note rather than a silent change.
The transaction around
CreateScheduleTaskstays where it is.Holding it across the lazy git read that resolves
uses: ./...is the cost of the guarantee; committing the advance first would turn the duplicate run this closes into a lost run, which is the worse outcome for a scheduled build.What the commit does add is the compare-and-set, so two nodes that both believe they are the leader, which a lease handover under clock skew can produce, cannot each create a run and each move the spec on.
db.PrimaryEngineis new API inmodels/db, inengine_codefloe.go.db.GetEnginecannot serve a read-back of a value just written, because it returns whatever engine the context already carries before it looks at the primary pin, and fordb.DefaultContextor a request context that engine is the group.db.PrimaryEnginebinds to the primary regardless, and returns the transaction's own session inside a transaction so the statement cannot escape it.models/db/engine_codefloe_test.gocovers all three cases against the existing lagging-replica harness.One thing I could not fix without rewriting the feature commit: its message still says
[codefloe.ha] ENABLED, which is stale since the rename to[high_availability].Nothing in the tree says that any more, only the commit message, so it is worth correcting in the squash message at merge time.
Verified:
go build ./...,make lint-go,make lint-go-vetandmake lint-editorconfigpass.Tests pass for
models/db,models/codefloe,models/codefloe_migrations(withGITEA_CONF=tests/sqlite.ini, which the individual-migration make target uses),modules/setting,modules/storage,modules/codefloe/lock,services/codefloe/ha,services/cron,services/actionsandrouters/common.8da190deddb9b2fc287c