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

feat(ha): leader-elected cron and cluster-safe locks for multi-node operation #110

Merged
pat-s merged 12 commits from feat/ha-leader-election into v16.0/forgejo-codefloe 2026-09-14 09:40:35 +00:00
Owner

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 in contrib/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 NX lock 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_lease table with atomic acquire, renew and release and a fencing token (codefloe migration v13).
  • services/codefloe/ha: elector goroutine, per-term leader context, Hold for named leases, Prometheus gauges gitea_codefloe_ha_is_leader{node} and gitea_codefloe_ha_lease_age_seconds.
  • Cron gate: gocron keeps running everywhere, but scheduled runs execute on the leader only, are bound to the leadership context, and take a per-task lease so manual runs on other nodes cannot overlap. Run-at-start tasks fire on first election.
  • codefloe_cron_status table so the cron monitor and dashboard show the same last-run data on every node, plus a leader line on both pages.
  • Schema migrations are serialised across nodes with a schema-migration lease.
  • The Actions scheduler creates the run and advances the spec in one transaction, closing a duplicate-run window on failover.
  • The in-process pull, wiki, repository-transfer and package upload pools become lease-backed when HA is enabled (ha.NewPool), and stay process-local otherwise.
  • MinIO storage init tolerates BucketAlreadyOwnedByYou when two nodes create the bucket at once.
  • contrib/ha: two-node docker compose harness, nginx round-robin, and failover-test.sh.

Verified

Two local nodes against PostgreSQL, Valkey, MinIO and Meilisearch containers:

  • exactly one leader; run-at-start tasks ran once, on the leader only; the concurrent first start was serialised by the migration lease;
  • graceful stop of the leader: failover in 2 s; SIGKILL of the leader: failover in 13 s (TTL 15 s);
  • the follower's admin cron page and /api/v1/admin/cron show the cluster-wide status and the current leader.

With ENABLED = false (the default) behaviour is unchanged.

Not included

  • A forgejo codefloe ha resign CLI command and runbooks (rollout step 5 of the design).
  • Infrastructure choices for codefloe.com: NFS vs CephFS for the git root, Redis Sentinel, one shared SSH host key.

These are written down in contrib/ha/README.md under "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:

  • Elector: store calls are bounded to one renew interval and a per-term watchdog resigns at last renew + TTL - renew even if a call hangs; the margin comparison is now inclusive. Tests cover a hanging store and the margin timing.
  • Hold returns a Held with a Lost channel; 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.
  • The lease-backed pool serialises goroutines of one node per key locally before touching the cluster lease, so a lost-and-reacquired lease can no longer be released by the wrong goroutine, and only one goroutine per node polls.
  • The migration lease is renewed while migrations run; a waiting node waits up to six hours.
  • Scheduled runs are identified by the scheduler's own doer value, so POST /api/v1/admin/cron/{task} on a follower runs the task instead of being cancelled at once.
  • A failure to advance an Actions schedule spec aborts the pass, as upstream did, instead of disabling the workflow.
  • A failed lease-row insert is only ignored when the row turns out to exist.
  • A skip recorded locally is no longer hidden by the cluster-wide status on the cron page.

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:

  • stamps the last successful renew with the call's start time in both the elector and Hold, which is the base of the server-side expiry, and makes Hold give up while one more bounded attempt still fits before expiry;
  • makes the deadline resign attempt a bounded release so followers need not wait for expiry, and makes the watchdog end only the term it was started for;
  • hashes pool keys that would not fit the lease name column;
  • classifies only workflow errors as reasons to disable a scheduled workflow, so any transaction failure aborts the pass;
  • reads the task's last-run time under its lock, and tolerates a concurrent first-start table creation.

Changes after the third review

Rebased onto v16.0/forgejo-codefloe and 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_INTERVAL is reset to a third of LEASE_TTL unless 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 = 15s with the default RENEW_INTERVAL = 10s was enough to flap leadership forever.
  • The migration lease is now held until db.InitEngineWithMigration returns, because SyncAllTables and the registered init functions run after the migration function and issue DDL of their own.
  • Lease statements go through the new 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 schedule spec advance is a compare-and-set on the next run time, so two nodes that both believe they are the leader cannot each create a run.
    The transaction around CreateScheduleTask stays: committing the advance first would trade a duplicate run for a lost one.
  • Cron status is persisted only when HA is enabled, so a default install behaves exactly as before.
  • makeBucketIfMissing also accepts BucketAlreadyExists from S3 gateways that answer that for a bucket the caller owns, once BucketExists confirms it.
  • failover-test.sh no longer aborts on pipefail when a node is unreachable, which is the normal state right after the leader is stopped.
  • The HA migration has a test, as v8 through v11 do.
  • actions_model.UpdateScheduleSpec lost its last caller to the compare-and-set and is recorded in .deadcode-out.
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 in `contrib/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 NX` lock 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_lease` table with atomic acquire, renew and release and a fencing token (codefloe migration v13). - `services/codefloe/ha`: elector goroutine, per-term leader context, `Hold` for named leases, Prometheus gauges `gitea_codefloe_ha_is_leader{node}` and `gitea_codefloe_ha_lease_age_seconds`. - Cron gate: gocron keeps running everywhere, but scheduled runs execute on the leader only, are bound to the leadership context, and take a per-task lease so manual runs on other nodes cannot overlap. Run-at-start tasks fire on first election. - `codefloe_cron_status` table so the cron monitor and dashboard show the same last-run data on every node, plus a leader line on both pages. - Schema migrations are serialised across nodes with a `schema-migration` lease. - The Actions scheduler creates the run and advances the spec in one transaction, closing a duplicate-run window on failover. - The in-process pull, wiki, repository-transfer and package upload pools become lease-backed when HA is enabled (`ha.NewPool`), and stay process-local otherwise. - MinIO storage init tolerates `BucketAlreadyOwnedByYou` when two nodes create the bucket at once. - `contrib/ha`: two-node docker compose harness, nginx round-robin, and `failover-test.sh`. ## Verified Two local nodes against PostgreSQL, Valkey, MinIO and Meilisearch containers: - exactly one leader; run-at-start tasks ran once, on the leader only; the concurrent first start was serialised by the migration lease; - graceful stop of the leader: failover in 2 s; SIGKILL of the leader: failover in 13 s (TTL 15 s); - the follower's admin cron page and `/api/v1/admin/cron` show the cluster-wide status and the current leader. With `ENABLED = false` (the default) behaviour is unchanged. ## Not included - A `forgejo codefloe ha resign` CLI command and runbooks (rollout step 5 of the design). - Infrastructure choices for codefloe.com: NFS vs CephFS for the git root, Redis Sentinel, one shared SSH host key. These are written down in `contrib/ha/README.md` under "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: - Elector: store calls are bounded to one renew interval and a per-term watchdog resigns at `last renew + TTL - renew` even if a call hangs; the margin comparison is now inclusive. Tests cover a hanging store and the margin timing. - `Hold` returns a `Held` with a `Lost` channel; 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. - The lease-backed pool serialises goroutines of one node per key locally before touching the cluster lease, so a lost-and-reacquired lease can no longer be released by the wrong goroutine, and only one goroutine per node polls. - The migration lease is renewed while migrations run; a waiting node waits up to six hours. - Scheduled runs are identified by the scheduler's own doer value, so `POST /api/v1/admin/cron/{task}` on a follower runs the task instead of being cancelled at once. - A failure to advance an Actions schedule spec aborts the pass, as upstream did, instead of disabling the workflow. - A failed lease-row insert is only ignored when the row turns out to exist. - A skip recorded locally is no longer hidden by the cluster-wide status on the cron page. 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: - stamps the last successful renew with the call's start time in both the elector and `Hold`, which is the base of the server-side expiry, and makes `Hold` give up while one more bounded attempt still fits before expiry; - makes the deadline resign attempt a bounded release so followers need not wait for expiry, and makes the watchdog end only the term it was started for; - hashes pool keys that would not fit the lease name column; - classifies only workflow errors as reasons to disable a scheduled workflow, so any transaction failure aborts the pass; - reads the task's last-run time under its lock, and tolerates a concurrent first-start table creation. ## Changes after the third review Rebased onto `v16.0/forgejo-codefloe` and 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_INTERVAL` is reset to a third of `LEASE_TTL` unless 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 = 15s` with the default `RENEW_INTERVAL = 10s` was enough to flap leadership forever. - The migration lease is now held until `db.InitEngineWithMigration` returns, because `SyncAllTables` and the registered init functions run after the migration function and issue DDL of their own. - Lease statements go through the new `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 schedule spec advance is a compare-and-set on the next run time, so two nodes that both believe they are the leader cannot each create a run. The transaction around `CreateScheduleTask` stays: committing the advance first would trade a duplicate run for a lost one. - Cron status is persisted only when HA is enabled, so a default install behaves exactly as before. - `makeBucketIfMissing` also accepts `BucketAlreadyExists` from S3 gateways that answer that for a bucket the caller owns, once `BucketExists` confirms it. - `failover-test.sh` no longer aborts on `pipefail` when a node is unreachable, which is the normal state right after the leader is stopped. - The HA migration has a test, as v8 through v11 do. - `actions_model.UpdateScheduleSpec` lost its last caller to the compare-and-set and is recorded in `.deadcode-out`.
feat(ha): leader-elected cron and cluster-safe locks for multi-node operation
All checks were successful
testing / test-e2e (pull_request) Successful in 27m56s
testing / test-mysql (pull_request) Successful in 31m24s
issue-labels / backporting (pull_request_target) Has been skipped
milestone / set (pull_request_target) Has been skipped
testing / test-pgsql (pull_request) Successful in 46m59s
testing / frontend-checks (pull_request) Successful in 2m2s
testing / backend-checks (pull_request) Successful in 8m12s
testing / test-unit (pull_request) Successful in 9m52s
testing / test-remote-cacher (valkey) (pull_request) Successful in 1m57s
testing / test-remote-cacher (redis) (pull_request) Successful in 2m0s
testing / test-remote-cacher (garnet) (pull_request) Successful in 1m59s
testing / test-sqlite (pull_request) Successful in 46m55s
74730b4dbd
Add multi-node (HA) operation behind [codefloe.ha] ENABLED:

- elect one leader through a codefloe_lease row with a fencing token,
  renewed by an elector goroutine on every node
- run scheduled cron tasks on the leader only, bound to the leadership
  context, and guard each run with a per-task lease
- persist cron run status in codefloe_cron_status so every node's admin
  pages show the same data, and show the current leader there
- serialise schema migrations across nodes with a lease
- create an Actions scheduled run and advance its spec atomically
- back the pull, wiki, repository transfer and package upload pools with
  leases when HA is enabled
- refuse to start with node-local cache, sessions, queues, storage,
  indexers or SQLite when HA is enabled
- export gitea_codefloe_ha_is_leader and gitea_codefloe_ha_lease_age_seconds
- tolerate a MinIO bucket created concurrently by another node
- add contrib/ha with a two-node compose harness and a failover test

SetElectorForTest is recorded in .deadcode-out because only tests in
other packages call it.
pat-s force-pushed feat/ha-leader-election from 74730b4dbd
All checks were successful
testing / test-e2e (pull_request) Successful in 27m56s
testing / test-mysql (pull_request) Successful in 31m24s
issue-labels / backporting (pull_request_target) Has been skipped
milestone / set (pull_request_target) Has been skipped
testing / test-pgsql (pull_request) Successful in 46m59s
testing / frontend-checks (pull_request) Successful in 2m2s
testing / backend-checks (pull_request) Successful in 8m12s
testing / test-unit (pull_request) Successful in 9m52s
testing / test-remote-cacher (valkey) (pull_request) Successful in 1m57s
testing / test-remote-cacher (redis) (pull_request) Successful in 2m0s
testing / test-remote-cacher (garnet) (pull_request) Successful in 1m59s
testing / test-sqlite (pull_request) Successful in 46m55s
to bb206c269e
Some checks failed
testing / frontend-checks (pull_request) Successful in 59s
testing / backend-checks (pull_request) Successful in 6m20s
testing / test-remote-cacher (redis) (pull_request) Has been cancelled
testing / test-remote-cacher (valkey) (pull_request) Has been cancelled
testing / test-remote-cacher (garnet) (pull_request) Has been cancelled
testing / test-sqlite (pull_request) Has been cancelled
testing / test-pgsql (pull_request) Has been cancelled
testing / test-e2e (pull_request) Has been cancelled
testing / test-mysql (pull_request) Has been cancelled
testing / test-unit (pull_request) Has been cancelled
2026-09-06 16:34:09 +00:00
Compare
pat-s force-pushed feat/ha-leader-election from bb206c269e
Some checks failed
testing / frontend-checks (pull_request) Successful in 59s
testing / backend-checks (pull_request) Successful in 6m20s
testing / test-remote-cacher (redis) (pull_request) Has been cancelled
testing / test-remote-cacher (valkey) (pull_request) Has been cancelled
testing / test-remote-cacher (garnet) (pull_request) Has been cancelled
testing / test-sqlite (pull_request) Has been cancelled
testing / test-pgsql (pull_request) Has been cancelled
testing / test-e2e (pull_request) Has been cancelled
testing / test-mysql (pull_request) Has been cancelled
testing / test-unit (pull_request) Has been cancelled
to 679ca0572a
All checks were successful
testing / test-remote-cacher (valkey) (pull_request) Successful in 1m22s
testing / test-mysql (pull_request) Successful in 29m49s
testing / frontend-checks (pull_request) Successful in 1m13s
testing / backend-checks (pull_request) Successful in 6m21s
testing / test-unit (pull_request) Successful in 9m29s
testing / test-remote-cacher (redis) (pull_request) Successful in 1m23s
testing / test-remote-cacher (garnet) (pull_request) Successful in 1m23s
testing / test-e2e (pull_request) Successful in 24m50s
testing / test-sqlite (pull_request) Successful in 39m11s
testing / test-pgsql (pull_request) Successful in 41m14s
2026-09-06 16:46:31 +00:00
Compare
.deadcode-out Outdated
@ -273,6 +273,9 @@ forgejo.org/routers/web/org
forgejo.org/services/auth
RegisterInternalIssuerForTesting
forgejo.org/services/codefloe/ha
SetElectorForTest
Author
Owner

why is this deadcode?

why is this deadcode?
pat-s marked this conversation as resolved
@ -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 dev
RUN_MODE = prod
RUN_USER = git
WORK_PATH = /data/gitea
[codefloe.ha]
Author
Owner

should be named [high_availability]

should be named [high_availability]
pat-s marked this conversation as resolved
@ -0,0 +36,10 @@
ports:
- "5433:5432"
healthcheck:
test: ["CMD-SHELL", "pg_isready -U forgejo"]
interval: 2s
timeout: 2s
retries: 30
valkey:
image: valkey/valkey:8-alpine
Author
Owner

use latest

use latest
pat-s marked this conversation as resolved
@ -0,0 +53,10 @@
command: server /data --console-address :9001
environment:
MINIO_ROOT_USER: forgejo
MINIO_ROOT_PASSWORD: forgejo123
ports:
- "9000:9000"
- "9001:9001"
meilisearch:
image: getmeili/meilisearch:v1.12
Author
Owner

use latest

use latest
pat-s marked this conversation as resolved
@ -2059,6 +2059,24 @@ LEVEL = Info
;; Empty means server's location setting
;DEFAULT_UI_LOCATION =
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;[codefloe.ha]
Author
Owner

[high_availability]

[high_availability]
pat-s marked this conversation as resolved
pat-s force-pushed feat/ha-leader-election from 679ca0572a
All checks were successful
testing / test-remote-cacher (valkey) (pull_request) Successful in 1m22s
testing / test-mysql (pull_request) Successful in 29m49s
testing / frontend-checks (pull_request) Successful in 1m13s
testing / backend-checks (pull_request) Successful in 6m21s
testing / test-unit (pull_request) Successful in 9m29s
testing / test-remote-cacher (redis) (pull_request) Successful in 1m23s
testing / test-remote-cacher (garnet) (pull_request) Successful in 1m23s
testing / test-e2e (pull_request) Successful in 24m50s
testing / test-sqlite (pull_request) Successful in 39m11s
testing / test-pgsql (pull_request) Successful in 41m14s
to 233e91c3f2
All checks were successful
testing / frontend-checks (pull_request) Successful in 1m2s
testing / backend-checks (pull_request) Successful in 5m26s
testing / test-unit (pull_request) Successful in 7m12s
testing / test-e2e (pull_request) Successful in 34m1s
testing / test-remote-cacher (valkey) (pull_request) Successful in 1m11s
testing / test-remote-cacher (redis) (pull_request) Successful in 1m37s
testing / test-remote-cacher (garnet) (pull_request) Successful in 1m12s
testing / test-mysql (pull_request) Successful in 36m29s
testing / test-pgsql (pull_request) Successful in 57m29s
testing / test-sqlite (pull_request) Successful in 53m24s
2026-09-07 06:02:09 +00:00
Compare
Author
Owner

Addressed the review: the section is now [high_availability] (code, tests, example config, harness), and the Valkey and Meilisearch images use latest.

On the .deadcode-out entry: SetElectorForTest is not dead, it is called from the tests in services/cron to swap in a fake leader. make lint-go runs deadcode with the forgejo.org main 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 reason RegisterInternalIssuerForTesting and GetPrivateContext sit right above it in the file.

Addressed the review: the section is now `[high_availability]` (code, tests, example config, harness), and the Valkey and Meilisearch images use `latest`. On the `.deadcode-out` entry: `SetElectorForTest` is not dead, it is called from the tests in `services/cron` to swap in a fake leader. `make lint-go` runs deadcode with the `forgejo.org` main 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 reason `RegisterInternalIssuerForTesting` and `GetPrivateContext` sit right above it in the file.
pat-s force-pushed feat/ha-leader-election from 233e91c3f2
All checks were successful
testing / frontend-checks (pull_request) Successful in 1m2s
testing / backend-checks (pull_request) Successful in 5m26s
testing / test-unit (pull_request) Successful in 7m12s
testing / test-e2e (pull_request) Successful in 34m1s
testing / test-remote-cacher (valkey) (pull_request) Successful in 1m11s
testing / test-remote-cacher (redis) (pull_request) Successful in 1m37s
testing / test-remote-cacher (garnet) (pull_request) Successful in 1m12s
testing / test-mysql (pull_request) Successful in 36m29s
testing / test-pgsql (pull_request) Successful in 57m29s
testing / test-sqlite (pull_request) Successful in 53m24s
to 37bb014bab
All checks were successful
testing / frontend-checks (pull_request) Successful in 1m24s
testing / test-remote-cacher (redis) (pull_request) Successful in 1m40s
testing / backend-checks (pull_request) Successful in 6m34s
testing / test-unit (pull_request) Successful in 9m44s
testing / test-remote-cacher (valkey) (pull_request) Successful in 1m39s
testing / test-remote-cacher (garnet) (pull_request) Successful in 1m40s
testing / test-e2e (pull_request) Successful in 34m27s
testing / test-mysql (pull_request) Successful in 36m34s
testing / test-pgsql (pull_request) Successful in 46m46s
testing / test-sqlite (pull_request) Successful in 45m48s
2026-09-07 07:20:47 +00:00
Compare
pat-s force-pushed feat/ha-leader-election from 37bb014bab
All checks were successful
testing / frontend-checks (pull_request) Successful in 1m24s
testing / test-remote-cacher (redis) (pull_request) Successful in 1m40s
testing / backend-checks (pull_request) Successful in 6m34s
testing / test-unit (pull_request) Successful in 9m44s
testing / test-remote-cacher (valkey) (pull_request) Successful in 1m39s
testing / test-remote-cacher (garnet) (pull_request) Successful in 1m40s
testing / test-e2e (pull_request) Successful in 34m27s
testing / test-mysql (pull_request) Successful in 36m34s
testing / test-pgsql (pull_request) Successful in 46m46s
testing / test-sqlite (pull_request) Successful in 45m48s
to 33b4799198
All checks were successful
testing / test-remote-cacher (garnet) (pull_request) Successful in 2m16s
testing / frontend-checks (pull_request) Successful in 1m41s
testing / backend-checks (pull_request) Successful in 8m0s
testing / test-unit (pull_request) Successful in 9m41s
testing / test-remote-cacher (valkey) (pull_request) Successful in 2m16s
testing / test-remote-cacher (redis) (pull_request) Successful in 2m17s
testing / test-e2e (pull_request) Successful in 27m9s
testing / test-mysql (pull_request) Successful in 31m27s
testing / test-sqlite (pull_request) Successful in 48m16s
testing / test-pgsql (pull_request) Successful in 51m48s
2026-09-13 17:00:19 +00:00
Compare
Author
Owner

Rebased onto v16.0/forgejo-codefloe

The 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, #111 added to the database-consistency row, the reworded CI-quota row) and the HA row was re-inserted with status Pending instead of the old 2026-09-06, matching how #123 and #120 are listed.

go build ./... passes.
Tests pass for services/codefloe/ha, modules/codefloe/lock, modules/setting, services/cron, models/codefloe and services/actions.
models/codefloe_migrations fails, but it fails the same way on v8_test.go and v11_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 v12 migration lives in v11.go, so CreateHATables correctly became v12 -> v13.

Review of the rebased revision

1. Leadership flaps forever on a healthy database

modules/setting/codefloe_ha.go:42

loadHAFrom only clamps RENEW_INTERVAL when it is greater than or equal to LEASE_TTL, but Elector.deadline() is lastRenewOK + (ttl - renew).
As soon as renew >= ttl/2, that deadline falls before the first renew tick, so the watchdog ends the term at ttl - renew no matter how fast the database answers, and the node then re-acquires and is killed again.
LEASE_TTL = 15s with the default RENEW_INTERVAL = 10s is enough to trigger it.
The fix is to clamp to ttl/3 when 2*renew >= ttl.
The shipped defaults (30s/10s) and the contrib/ha harness (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:83

The lease is released by a defer around migrateWithSetting, but db.InitEngineWithMigration runs SyncAllTables() and the registered initFuncs after migrateFunc returns.
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.Migrate is called from inside gitea_migrations.Migrate and so runs under the lease.

3. A lease can be acquired with fencing token 0

models/codefloe/lease.go:65

The has return of e.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 subsequent Renew and Release then fails its token = ? predicate.
The read-back can genuinely miss, because primaryContext is a no-op whenever the context already carries an engine: db.GetEngine checks getEngine(ctx) before it looks at IsPinnedToPrimary.
The elector itself is safe, since graceful's shutdown context carries no engine.
ha.Hold through lock.NewLeasePool is not, because the merge, wiki, transfer and package-upload paths pass request contexts that do carry one.
The worst case there is a Release with 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:26

The new db.WithTx spans CreateScheduleTask, which calls lazyRepoExpandLocalReusableWorkflow and reads blobs out of the repository to resolve uses: ./... 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:108

codefloeRecordRun and codefloeRecordResult are not gated on ha.Enabled(), while codefloeMergeCronStatus returns early when HA is off.
A single-node install therefore writes a codefloe_cron_status row 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:22

is_leader is documented to print empty when a node is unreachable, but under set -euo pipefail the failing curl aborts the script at a="$(is_leader a)" without printing anything.
Appending || true to 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:20 tolerates only BucketAlreadyOwnedByYou, not the BucketAlreadyExists that 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, so GetStatus with a missing row is safe.
leaseName hashing and the 100-character bound.
Balanced CheckIn and CheckOut at every pool call site, including the double-CheckOut path in leasePool.
The scheduledDoer pointer identity that decides which runs are bound to leadership.
The new admin.monitor.ha.* locale keys against FormatMessage's argument order.
setHAData covering both templates that read .CodefloeHA; no other handler renders admin/dashboard or admin/cron.

## Rebased onto `v16.0/forgejo-codefloe` The 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, `#111` added to the database-consistency row, the reworded CI-quota row) and the HA row was re-inserted with status `Pending` instead of the old `2026-09-06`, matching how `#123` and `#120` are listed. `go build ./...` passes. Tests pass for `services/codefloe/ha`, `modules/codefloe/lock`, `modules/setting`, `services/cron`, `models/codefloe` and `services/actions`. `models/codefloe_migrations` fails, but it fails the same way on `v8_test.go` and `v11_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 `v12` migration lives in `v11.go`, so `CreateHATables` correctly became `v12 -> v13`. ## Review of the rebased revision ### 1. Leadership flaps forever on a healthy database `modules/setting/codefloe_ha.go:42` `loadHAFrom` only clamps `RENEW_INTERVAL` when it is greater than or equal to `LEASE_TTL`, but `Elector.deadline()` is `lastRenewOK + (ttl - renew)`. As soon as `renew >= ttl/2`, that deadline falls before the first renew tick, so the watchdog ends the term at `ttl - renew` no matter how fast the database answers, and the node then re-acquires and is killed again. `LEASE_TTL = 15s` with the default `RENEW_INTERVAL = 10s` is enough to trigger it. The fix is to clamp to `ttl/3` when `2*renew >= ttl`. The shipped defaults (30s/10s) and the `contrib/ha` harness (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:83` The lease is released by a `defer` around `migrateWithSetting`, but `db.InitEngineWithMigration` runs `SyncAllTables()` and the registered `initFuncs` after `migrateFunc` returns. 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.Migrate` is called from inside `gitea_migrations.Migrate` and so runs under the lease. ### 3. A lease can be acquired with fencing token 0 `models/codefloe/lease.go:65` The `has` return of `e.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 subsequent `Renew` and `Release` then fails its `token = ?` predicate. The read-back can genuinely miss, because `primaryContext` is a no-op whenever the context already carries an engine: `db.GetEngine` checks `getEngine(ctx)` before it looks at `IsPinnedToPrimary`. The elector itself is safe, since graceful's shutdown context carries no engine. `ha.Hold` through `lock.NewLeasePool` is not, because the merge, wiki, transfer and package-upload paths pass request contexts that do carry one. The worst case there is a `Release` with 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:26` The new `db.WithTx` spans `CreateScheduleTask`, which calls `lazyRepoExpandLocalReusableWorkflow` and reads blobs out of the repository to resolve `uses: ./...` 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:108` `codefloeRecordRun` and `codefloeRecordResult` are not gated on `ha.Enabled()`, while `codefloeMergeCronStatus` returns early when HA is off. A single-node install therefore writes a `codefloe_cron_status` row 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:22` `is_leader` is documented to print empty when a node is unreachable, but under `set -euo pipefail` the failing `curl` aborts the script at `a="$(is_leader a)"` without printing anything. Appending `|| true` to 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:20` tolerates only `BucketAlreadyOwnedByYou`, not the `BucketAlreadyExists` that 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, so `GetStatus` with a missing row is safe. `leaseName` hashing and the 100-character bound. Balanced `CheckIn` and `CheckOut` at every pool call site, including the double-`CheckOut` path in `leasePool`. The `scheduledDoer` pointer identity that decides which runs are bound to leadership. The new `admin.monitor.ha.*` locale keys against `FormatMessage`'s argument order. `setHAData` covering both templates that read `.CodefloeHA`; no other handler renders `admin/dashboard` or `admin/cron`.
Author
Owner

All seven findings are addressed, one commit each on top of 33b4799198.

Commit Finding
539584b58c RENEW_INTERVAL is reset to LEASE_TTL/3 unless it is strictly below half the TTL, so a renewal is always attempted before the elector's own deadline
87e6e32ddc the migration lease is held until db.InitEngineWithMigration returns, covering SyncAllTables and the init functions
34b007ec64 lease statements run on the primary through the new db.PrimaryEngine, and an acquisition whose row cannot be read back fails instead of handing out token 0
56da6a6715 the schedule spec advance is a compare-and-set on the next run time
c12aeb7aaa cron status is persisted only when HA is enabled
c050057da3 failover-test.sh survives an unreachable node under pipefail
0460b90021 makeBucketIfMissing also accepts BucketAlreadyExists once BucketExists confirms the bucket
11f1b5e8cd the HA migration has a test, as v8 through v11 do
8da190dedd actions_model.UpdateScheduleSpec lost its last caller and is recorded in .deadcode-out

Two of the items deserve a note rather than a silent change.

The transaction around CreateScheduleTask stays 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.PrimaryEngine is new API in models/db, in engine_codefloe.go.
db.GetEngine cannot 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 for db.DefaultContext or a request context that engine is the group.
db.PrimaryEngine binds 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.go covers 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-vet and make lint-editorconfig pass.
Tests pass for models/db, models/codefloe, models/codefloe_migrations (with GITEA_CONF=tests/sqlite.ini, which the individual-migration make target uses), modules/setting, modules/storage, modules/codefloe/lock, services/codefloe/ha, services/cron, services/actions and routers/common.

All seven findings are addressed, one commit each on top of `33b4799198`. | Commit | Finding | | --- | --- | | `539584b58c` | `RENEW_INTERVAL` is reset to `LEASE_TTL/3` unless it is strictly below half the TTL, so a renewal is always attempted before the elector's own deadline | | `87e6e32ddc` | the migration lease is held until `db.InitEngineWithMigration` returns, covering `SyncAllTables` and the init functions | | `34b007ec64` | lease statements run on the primary through the new `db.PrimaryEngine`, and an acquisition whose row cannot be read back fails instead of handing out token 0 | | `56da6a6715` | the schedule spec advance is a compare-and-set on the next run time | | `c12aeb7aaa` | cron status is persisted only when HA is enabled | | `c050057da3` | `failover-test.sh` survives an unreachable node under `pipefail` | | `0460b90021` | `makeBucketIfMissing` also accepts `BucketAlreadyExists` once `BucketExists` confirms the bucket | | `11f1b5e8cd` | the HA migration has a test, as v8 through v11 do | | `8da190dedd` | `actions_model.UpdateScheduleSpec` lost its last caller and is recorded in `.deadcode-out` | Two of the items deserve a note rather than a silent change. The transaction around `CreateScheduleTask` stays 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.PrimaryEngine` is new API in `models/db`, in `engine_codefloe.go`. `db.GetEngine` cannot 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 for `db.DefaultContext` or a request context that engine is the group. `db.PrimaryEngine` binds 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.go` covers 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-vet` and `make lint-editorconfig` pass. Tests pass for `models/db`, `models/codefloe`, `models/codefloe_migrations` (with `GITEA_CONF=tests/sqlite.ini`, which the individual-migration make target uses), `modules/setting`, `modules/storage`, `modules/codefloe/lock`, `services/codefloe/ha`, `services/cron`, `services/actions` and `routers/common`.
pat-s force-pushed feat/ha-leader-election from 8da190dedd
Some checks failed
testing / backend-checks (pull_request) Successful in 8m57s
testing / frontend-checks (pull_request) Successful in 1m19s
testing / test-unit (pull_request) Successful in 6m21s
testing / test-remote-cacher (garnet) (pull_request) Has been cancelled
testing / test-remote-cacher (redis) (pull_request) Successful in 1m43s
testing / test-mysql (pull_request) Has been cancelled
testing / test-sqlite (pull_request) Has been cancelled
testing / test-e2e (pull_request) Has been cancelled
testing / test-pgsql (pull_request) Has been cancelled
testing / test-remote-cacher (valkey) (pull_request) Has been cancelled
to b9b2fc287c
All checks were successful
testing / frontend-checks (pull_request) Successful in 1m0s
testing / backend-checks (pull_request) Successful in 5m29s
testing / test-remote-cacher (redis) (pull_request) Successful in 2m5s
testing / test-remote-cacher (garnet) (pull_request) Successful in 1m55s
testing / test-unit (pull_request) Successful in 10m23s
testing / test-remote-cacher (valkey) (pull_request) Successful in 1m57s
testing / test-e2e (pull_request) Successful in 40m22s
testing / test-sqlite (pull_request) Successful in 56m5s
testing / test-pgsql (pull_request) Successful in 1h0m6s
testing / test-mysql (pull_request) Successful in 22m23s
2026-09-13 18:25:26 +00:00
Compare
docs(ha): describe the design and the open rollout decisions
Some checks failed
testing / frontend-checks (pull_request) Successful in 1m20s
testing / test-unit (pull_request) Has been cancelled
testing / test-e2e (pull_request) Has been cancelled
testing / test-remote-cacher (redis) (pull_request) Has been cancelled
testing / test-remote-cacher (valkey) (pull_request) Has been cancelled
testing / test-remote-cacher (garnet) (pull_request) Has been cancelled
testing / test-mysql (pull_request) Has been cancelled
testing / test-pgsql (pull_request) Has been cancelled
testing / test-sqlite (pull_request) Has been cancelled
testing / backend-checks (pull_request) Has been cancelled
653279642f
Three files pointed at docs/superpowers/specs/2026-09-06-forgejo-ha-design.md,
which is gitignored and so does not exist for anyone reading the merged
code. Summarise that design in contrib/ha/README.md and point at it
instead.

Also write down what a production rollout still needs and this
repository does not decide: the shared git root (NFS vs CephFS), Redis
high availability, one SSH host key across nodes, a way to step a node
down on purpose, and runbooks. The docs/ directory was removed in #121
and is gitignored, so the HA harness README is the tracked home for
this.
docs(ha): correct where a resign command would live
All checks were successful
testing / frontend-checks (pull_request) Successful in 1m45s
testing / backend-checks (pull_request) Successful in 9m27s
testing / test-remote-cacher (redis) (pull_request) Successful in 1m43s
testing / test-unit (pull_request) Successful in 11m50s
testing / test-e2e (pull_request) Successful in 28m52s
testing / test-mysql (pull_request) Successful in 34m9s
testing / test-remote-cacher (valkey) (pull_request) Successful in 1m43s
testing / test-remote-cacher (garnet) (pull_request) Successful in 1m42s
testing / test-pgsql (pull_request) Successful in 51m41s
testing / test-sqlite (pull_request) Successful in 48m37s
issue-labels / backporting (pull_request_target) Has been skipped
milestone / set (pull_request_target) Has been skipped
a799294522
Stopping a node already hands leadership over within a renew interval,
so a resign command is a convenience rather than a gap: it only matters
when a node should give up cron while still serving requests.

Name it under `forgejo manager`, not `forgejo codefloe ha`. The command
has to reach the running process that holds the lease, which is what
every manager subcommand does, and the fork keeps codefloe out of
user-facing names, as the [high_availability] section already does.
pat-s merged commit 58265447a9 into v16.0/forgejo-codefloe 2026-09-14 09:40:35 +00:00
pat-s deleted branch feat/ha-leader-election 2026-09-14 09:40:35 +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!110
No description provided.