Files
aevolution/docs/adr/0060-fenced-region-ownership.md
T
dingoandClaude Opus 5.5 a2c4543df2 Complete M7.4b lineage checkpoint profile; M7.4 done
ADR-0062 adds a canonical LineageArchive codec (parents before children,
organisms by id, FNV) that decodes by replaying admit/record_birth/
record_death and requires byte-identical re-encoding; it never overwrites
an existing archive. LineageRegion binds the environmental producer and
consumer accounts to archived organisms with identity high-waters,
enforces closure (lifecycle vs deaths, exact living set, tick bounds)
and records deaths in the tick that causes them.

Checkpoint profile 2 (environmental-lineage-v1, history profile 1)
publishes that container; schema v4 admits it with a 4,268,144-byte cap
and requires each commit to keep its predecessor's profile, RNG, history
and durability declarations. Linux adds provision/publish/recover for
the profile on the shared publication path.

Qualification found WSL2 stepping CLOCK_REALTIME back ~0.5 s every ~32 s,
which made two 1 s-lease tests flaky under ASan. Tests now wait on
database-time expiry; ADR-0060 records the slewed-clock requirement.

Validated: Windows CTest 57/57; Linux GCC Debug/Release, clang-tidy and
ASan/UBSan CTest 57/57 each; PostgreSQL suites 2x Release, 2x analysis,
5x ASan; SQL and C++ mutations each caught. No Docker/Gitea CI, remote
store, process kill or deployment.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 16:43:10 -04:00

120 lines
7.3 KiB
Markdown

# ADR-0060: Fenced region ownership
## Status
Accepted for M7.3, 2026-09-28. Implements the lease/fence portion of ADR-0058 on
the ADR-0059 adapter. No region host, director, gateway or deployment exists yet.
## Context
ADR-0058 requires that PostgreSQL arbitrate acquire/renew/commit/release under one
lease-row lock using database time, that commits compare the expected predecessor,
and that workers cannot bypass the guard. Schema v1 has only a lease table and no
runtime grants. REGION_DURABILITY.md deferred selecting lease duration, renewal
cadence, local safety margin and store deadlines to this gate.
## Decision
Schema v2 (`migrations/0002_region_fencing.sql`) adds `region_heads` and owner-owned
functions. Every mutating function is SECURITY DEFINER with `search_path` pinned to
`pg_catalog, pg_temp`. The runtime group role gets schema USAGE and EXECUTE on
acquire, renew, release, load_region_head and advance_region_head only. It has no
table privileges. Provisioning (genesis) and the internal lease check stay owner-only.
- Acquire locks the row, reads `clock_timestamp()` after the lock and succeeds only if
the row is released or expired. It then increments the u64 epoch and stores a
database-generated holder UUID. Epoch overflow fails closed. The holder is a
per-acquisition token, not a Pod identity.
- Renew, release and advance all go through the same row lock and require the exact
holder and epoch, with expiry in database time after the lock wait. Renewal never
revives an expired lease. Release keeps the epoch, so it is never reused.
- The advance function checks the lease, then locks the head. It requires the
expected sequence, commit ID and digest, a 1..64 tick delta and no sequence wrap.
M7.4/M7.5 publication wraps this kernel in the same transaction as the manifest,
decisions and outbox. Runtime EXECUTE on the bare kernel must then be revoked.
- Rejections use custom SQLSTATEs EVL01..EVL05 (busy, fenced, head mismatch, not
provisioned, exhausted) and 22023 for invalid arguments. A rejection aborts any
enclosing transaction. Clients never send timestamps.
- The migration requires an operator-created runtime role. Every migrate run audits
the effective privileges of that role and all its members. It rejects privileged
attributes, any membership outside the group (including predefined roles such as
pg_write_all_data), table or CREATE rights, and EXECUTE beyond the five
functions. This addresses a review finding: an attribute-only check let an
inherited pg_write_all_data bypass fencing. History admission is an exact prefix: clean→v1→v2,
v1→v2, or a v2 no-op. Anything else fails closed.
Host side: the portable `LeaseAuthority` sets its local deadline to request-send time
plus the granted duration minus the safety margin. Database expiry is set no earlier
than that send, so the holder stops before a successor can acquire. An ambiguous
renewal keeps the earlier of the old deadline and the one the attempt could have
set. A reply received after the local deadline fences. Fencing is sticky until a
strictly newer epoch is acquired, which is followed by recovery. `LeaseClock` uses
Linux CLOCK_BOOTTIME so that suspend time still counts.
Selected timings (`LeasePolicy` defaults; the database admits 1..60 s leases):
| Setting | Value | Reason |
|---|---|---|
| Lease duration | 20 s | Bounds orphaned-lease unavailability and leaves 40 s of the proposed 60 s recovery target for load and verification |
| Renewal interval | 5 s | Two full attempts (interval + timeout) fit in the 18 s usable window |
| Safety margin | 2 s | ≥10% of duration, covering clock-rate disagreement and check-to-effect delay |
| Renewal deadline | 2 s | About three orders of magnitude above the measured local p99 (about 1 ms); drop the connection and treat the outcome as unknown |
| Commit deadline | 5 s | Below the 10 s server statement timeout; begin only if it ends before local fencing |
`valid(LeasePolicy)` enforces these relations, not the specific numbers. Remote
TLS latency and clock-rate behavior must be measured in the target environment
before World0. These values are not a player SLA.
The world director is deliberately not implemented. Its output would be an
assignment hint with no authority, and the database decides ownership anyway.
Adding one now would be a placeholder service. It belongs with the host (M7.6)
or later operations work.
## Alternatives Considered
Kubernetes Leases or broker locks are not in the commit transaction. Client-supplied
holder IDs allow lost-acquire adoption but need uniqueness guarantees and let any
runtime guess tokens; DB tokens cost at most one lease period after an unknown
acquire. Transaction-start `now()` lets a writer queued on the lock commit after
expiry. Row-level security on direct table writes widens the attack surface compared
with no table grants. Status-row returns instead of SQLSTATEs would not abort a
future enclosing publication transaction.
## Benefits
One lock serializes every ownership and head transition. The runtime login cannot
write tables, create objects or call provisioning. Stale, paused, queued and
partitioned writers are rejected by the database. The local fence has an explicit
bound instead of trusting liveness.
## Costs
Each renewal or commit takes a row lock. After a worker crash or an unknown acquire,
the region stays unavailable for up to one lease period. The runtime role must be
pre-created by an operator. This adds a second migration and a chain of prefix checksums.
## Risks
Grants made after the last migrate run are not audited until it runs again, so
operators must rerun it after role changes.
Database time is the server's wall clock (`clock_timestamp()`), so steps count.
M7.4b measured WSL2 stepping it back about 0.5 s every ~32 s: 3.66 s over 240 s,
roughly a 1.5% rate difference from CLOCK_MONOTONIC.
- Backward steps only lengthen leases in database time. Exclusivity holds, and a
holder's monotonic deadline still fences it early.
- Forward steps shorten leases. A successor can then acquire while the old holder
still believes it has authority. Commits are still rejected, but provisional
output could overlap.
Database hosts therefore need slewed, not stepped, time. A forward step larger
than the safety margin is outside the declared failure model. Tests wait on
database-time expiry instead of assuming a local sleep equals database time. A frozen VM/hypervisor can stop all
guest clocks. Database commits stay fenced, but
provisional output could then be late. Gateways still need bounded-validity
registration (ADR-0058). The bare head kernel accepts any 32-byte digest until M7.4
binds it to verified payloads, so v2 must not host real world state. Custom
SQLSTATEs are project conventions; they are not PostgreSQL-reserved.
## Consequences
Done in M7.4a (ADR-0061): schema v3 drops the bare kernel and publishes through a
manifest-parsing function under the same lock order.
The M7.4 migration must add the manifest/payload publication function that calls
the kernel, and revoke runtime EXECUTE on `advance_region_head`. M7.5 adds
commit-ID resolution. Until then, "head equals my commit ID" is only the primitive
reconciliation used in tests. M7.6 hosts must drive `LeaseAuthority`, stop admission,
simulation and output when fenced, and recover after any new acquisition. Timing
changes require updated measurements and this ADR's table.