Skip to content

feat(coord): a lease over PutObjectIf where every guarded action re-asserts the CAS (#283) - #381

Merged
scttfrdmn merged 5 commits into
mainfrom
feat/coord-lease-283
Aug 8, 2026
Merged

scttfrdmn merged 5 commits into
mainfrom
feat/coord-lease-283

Conversation

@scttfrdmn

Copy link
Copy Markdown
Owner

Closes #283. Second in the CAS series after #282, which supplied Backend.PutObjectIf.

New package internal/coord: mutual exclusion between ObjectFS nodes with the object store as the arbiter.

The re-assert rule is the API's shape, not a comment

There is no exported method on Lease that writes. Acting under a lease goes through Lease.Do, which re-asserts before invoking the action and hands it a Guard whose Put, PutIf, and Delete each re-assert again immediately before the write they perform. #283 asked for a shape where "the unguarded form is unrepresentable over one where it is merely discouraged by a comment" — that is what the absence of an exported write method buys.

Quoting the design doc's §2, which #283 quotes in turn:

A CAS design fails closed only if every guarded action itself re-asserts the CAS. That is a design obligation, not a property you get for free.

What survives is a residual window of one round trip rather than one lease period, stated plainly in the package doc rather than elided: between a successful re-assert and the write it guards, S3 cannot reject the write on the strength of the lease, because a conditional write cannot span two keys. Guard.PutIf exists for callers whose correctness needs zero.

Two deliberate deviations from the issue's proposed mechanism

Both are documented in the package doc, and both are stronger than what was asked:

  1. CAS-2: A lease over PutObjectIf, where every guarded action re-asserts the CAS #283 proposes comparing expiry against S3's Last-Modified/Date. This compares no absolute clock at all. Takeover is decided by observing the lease object's ETag unchanged across a full Period, measured as a duration on one observer's monotonic clock. Durations on one clock are immune to skew between clocks, which timestamp comparisons are not — including comparisons against S3's own view, since the local side of that comparison is still a local clock.

  2. CAS-2: A lease over PutObjectIf, where every guarded action re-asserts the CAS #283 says "Release — conditional delete on the held ETag." There is no DeleteObjectIf on types.Backend. Release therefore writes a record marked (released) conditional on the held ETag; an unconditional delete by a holder that had since lost the lease would remove the current holder's record and hand the lease to whoever raced next. The cost is one observation period of takeover delay for the next contender, which is the cheaper failure.

Why every write carries a nonce

Verified by execution, not assumed: S3's ETag is the MD5 of the body. A lease record rewritten with identical fields keeps its ETag, so a renewal would not move it — and a live holder would become indistinguishable from a stopped one, which is the exact confusion the takeover rule exists to resolve. Renewals must move the ETag or the mechanism silently inverts.

Chasing a one-in-sixty flake found a defect in the lease itself

Renew reads the held ETag, asserts it, and stores the new one, and those three steps were not atomic. Two renewals by the same holder both read the same ETag and both asserted it. One won; the other was handed ErrPreconditionFailed by its own holder's write, could not distinguish that from a takeover, and returned ErrLost and dropped the claim. Every guarded action then failed closed on a lease the node still genuinely held, reporting that another holder had taken it — which was false.

This required no contention and no unusual caller: Do's renewal ticker and every Guard method's re-assert both call Renew, so a holder following this package's only supported pattern defeated itself. Reproduced 100% of the time with two goroutines. Fixed by serializing the claim's whole read-modify-write across its round trip, and now covered by TestOneHoldersConcurrentRenewalsDoNotDefeatEachOther, which asserts the lease is still usable afterwards rather than only that the renewals returned nil.

The flake that led there was separately a defect in a test's model, fixed rather than tolerated: every steal performed inside a Do action races that action's renewal ticker for the lease object's ETag, so the steal's own precondition could fail through no fault of the code under test. Retrying against a fresh ETag is also what the contender being simulated would do, so the stable version is the more faithful one.

Mutation verification

#283 requires it, on the grounds that the re-assert is "the property most likely to be quietly regressed later." Each mutation was applied to lease.go, run, and reverted; 0 markers remain.

mutation failing test
Guard.Put re-assert removed TestGuardedWriteFailsWhenTheLeaseIsStolenMidAction
Guard.Delete re-assert removed TestGuardedDeleteAndPutIfAlsoReassert/Delete
Guard.PutIf re-assert removed TestGuardedDeleteAndPutIfAlsoReassert/PutIf
Guard.Put renews then does not write TestGuardedWriteFailsWhenTheLeaseIsStolenMidAction, TestGuardedWritesReachTheStoreWhileTheLeaseIsHeld
Guard.Delete renews then does not delete TestGuardedWritesReachTheStoreWhileTheLeaseIsHeld
Guard.PutIf drops the precondition TestGuardedWritesReachTheStoreWhileTheLeaseIsHeld
constant nonce TestEveryWriteMovesTheETag
takeover observation window removed TestAcquisitionIsBounded, TestAbandonedLeaseIsTakenOverOnlyAfterAFullPeriod
Do records the renewal failure but does not cancel TestDoCancelsTheActionWhenTheLeaseIsLost

Mutation found two defects in the tests, not the code. Stealing the lease before Do meant Do's own opening Renew rejected the action and the method under test was never reached, so deleting its re-assert changed nothing — the steal had to move inside the action. And the nonce test passed with the nonce replaced by a constant, because the record's nanosecond Acquired/Renewed timestamps varied the body on their own; pinning the clock is what makes it a test of the nonce. Those timestamps are documented as being for operators reading the object, so ETag movement must not depend on them.

Coverage told the same story a third time. At 87.4%, Guard.PutIf and Guard.Delete sat at 66.7% each — covered only on the path where they refuse — so either could have had its write deleted outright while every test still passed, because the rest of the suite asserts that a stale holder's writes do not land. TestGuardedWritesReachTheStoreWhileTheLeaseIsHeld closes that, and the .coverage-floors note records why the number moved.

Cost, per §2's note

AWS bills failed conditional requests at the normal rate, so N contenders on one key is O(N) requests. Acquisition is bounded by MaxAttempts with ±20% jitter — never an unbounded spin — and Lease takes a key per resource. The package doc states that callers must not funnel unrelated resources through one global lock key.

Refusing to start

A store that accepts a conditional header and ignores it is indistinguishable from one that honors it, from every angle except the outcome of a race. New asks types.CapabilityReporter and refuses to construct a lease when the answer is no or when there is no answer to be had. Running unguarded is not offered as a fallback.

Acceptance criteria

  • Lease type with acquire / renew / release over PutObjectIf
  • Guarded actions re-assert the CAS; the unguarded form is not expressible
  • Bounded, jittered retry; per-resource keys, no global lock key
  • Documented clock assumption — no absolute clock is compared at all
  • ErrNotSupported from the probe ⇒ refuse to start, never run unguarded
  • Exactly-one-holder test under contention, with -race (8 contenders, CAS counter a second holder would trip)
  • Partitioned-holder test: a lost lease blocks the guarded action
  • Mutation-verified against removal of the re-assert
  • Package doc stating the liveness limitation plainly — a lease is a timeout, not a guarantee

Verification

  • go build ./..., go vet ./... — clean
  • go test -race ./... — exit 0, all packages
  • make lint — 0 issues
  • ./scripts/coverage-gate.sh — 37 packages at or above their floor; internal/coord 89.1% against a new floor of 88
  • go test -race -count=5 ./internal/coord/ × 20 (100 runs) — 0 failures, against 1 in 60 before the concurrent-renewal fix

Also fixes a broken godoc link in pkg/types/conditional.go left by #282: [ErrNotFound] names no symbol.

Next in the series: #284 (remove the executeStrongConsistency fan-out), then #285.

…sserts the CAS (#283)

Mutual exclusion between nodes with the object store as the arbiter. The shape of the
API is the substance: there is no exported method on Lease that writes. Acting under a
lease goes through Lease.Do, which re-asserts before invoking the action and hands it a
Guard whose Put, PutIf, and Delete each re-assert again immediately before their write.

That is the property the design doc names as the whole difference between this and a
lock that lies: a CAS design fails closed only if every guarded action itself re-asserts
the CAS. A node that has lost its network keeps believing it holds the lease — Raft's
partitioned leader has the same blind spot — and what decides the outcome is whether its
next write is refused. An action guarded by "I checked my lease a moment ago" is not
guarded, so it is not expressible through this type.

What survives is a residual window of one round trip rather than one lease period, stated
in the package doc rather than elided: between a re-assert and the write it guards, S3
cannot reject the write on the strength of the lease, because a conditional write cannot
span two keys. Guard.PutIf is there for callers who need zero.

Takeover never compares two clocks. Skewed clocks disagreeing about expiry is how two
holders arise, so an abandoned lease is claimed only after its ETag has been observed
unchanged across a full period, measured as a duration on one observer's monotonic clock.
This is why each record carries a fresh nonce, and the reason is verified rather than
precautionary: S3's ETag is the MD5 of the body, so a renewal rewriting identical fields
leaves it unchanged and a live holder becomes indistinguishable from a stopped one — the
exact confusion the takeover rule exists to resolve.

Release writes a released-marked record rather than deleting, because there is no
DeleteObjectIf: an unconditional delete by a holder that has since lost the lease would
remove the current holder's record. Acquisition is bounded and jittered and keys are
per-resource, because AWS bills failed conditional requests at the normal rate. New
refuses an endpoint that does not report ConditionalWrite, and one that cannot answer at
all — a store that accepts a conditional header and ignores it is indistinguishable from
one that honors it, from every angle except the outcome of a race.

Chasing a one-in-sixty flake found a defect in the lease itself. Renew reads the held
ETag, asserts it, and stores the new one, and those steps were not atomic — so two
renewals by the same holder both read the same ETag and both asserted it. One won; the
other was handed ErrPreconditionFailed by its own holder's write, could not tell that
from a takeover, and dropped the claim. Every guarded action then failed closed on a
lease the node still genuinely held, reporting a takeover that had not happened. This
needed no contention: Do's renewal ticker and every Guard method's re-assert both call
Renew, so a holder following the only supported pattern defeated itself. Reproduced 100%
of the time with two goroutines; fixed by serializing the claim's whole read-modify-write
across its round trip.

Mutation-verified, and it found two defects in the tests rather than in the code. Removing
the re-assert from each Guard method fails a named test; so does replacing the nonce with
a constant, deleting the observation window, and deleting any Guard method's write
outright. Two of those only failed after the tests were fixed: stealing the lease before
Do meant Do's own opening Renew rejected the action and the method under test was never
reached, and the nonce test passed with a constant nonce because the record's nanosecond
timestamps varied the body on their own. Coverage told the same story a third time — at
87.4% Guard.PutIf and Guard.Delete were covered only where they refuse, so either could
have had its write deleted while every test still passed.

Closes #283.
…tted (#283)

FuzzNewConfig asserts the one property that makes a Config safe to hold a lease with:
New either refuses it, or produces a lease whose renewal interval leaves genuine margin
before its period. A RenewInterval at or past Period means the lease becomes takeable
before its holder would ever renew — two simultaneous holders arrived at through
configuration rather than through a race.

It found one in 0.37 seconds. Period=2ns makes RenewInterval default to Period/4 = 0 by
integer division, which passes the margin check because 0 genuinely is shorter than 2ns,
and then panics: time.NewTicker(0) is "non-positive interval for NewTicker", raised inside
Do's renewal goroutine where no caller can recover it. In a mount that is the process and
every open file descriptor with it.

Period now has a MinPeriod floor. It is set at where the arithmetic degenerates rather
than at a useful deployment minimum: a real lower bound is orders of magnitude higher,
but encoding that here would reject the short periods this package's own takeover tests
depend on, trading a real guard for slower tests. validate also rejects a non-positive
RenewInterval outright, which is unreachable through withDefaults now and checked anyway
because it is the value handed to NewTicker. Each guard alone suffices — verified by
mutating them out one at a time; the test fails only with both gone.

The reproducer the fuzzer minimized is committed as corpus, and the rejection is tabled in
TestNewRejectsUnusableConfigs as well, so it is not covered only by fuzzing. The target is
in the CI matrix, and the job's header comment is corrected: four of ten targets have now
found a real defect, not three of eight.

Verified through the CI script itself — .github/scripts/fuzz-smoke.sh ./internal/coord
FuzzNewConfig 60 — at 3,001,445 executions clean.

Refs #283.
@scttfrdmn

Copy link
Copy Markdown
Owner Author

Pushed b3fbb4d: a fuzz target for Config, which found a process-killing panic in 0.37 seconds — before it was committed.

FuzzNewConfig asserts the property that makes a Config safe to hold a lease with: New either refuses it, or produces a lease whose renewal interval leaves genuine margin before its period. A RenewInterval at or past Period means the lease becomes takeable before its holder would ever renew — two simultaneous holders arrived at through configuration rather than through a race.

What it found. Period: 2ns makes RenewInterval default to Period/4 = 0 by integer division. That passes the margin check, because 0 genuinely is shorter than 2ns. Then Do hands it to time.NewTicker:

panic: non-positive interval for NewTicker
time.NewTicker(0x0)
github.com/scttfrdmn/objectfs/internal/coord.(*Lease).Do.func1()
	internal/coord/lease.go:516

Raised inside Do's renewal goroutine, where no caller can recover it. In a mount that is the process and every open file descriptor with it.

Fix. Period now has a MinPeriod floor, set at where the arithmetic degenerates rather than at a useful deployment minimum — a real lower bound is orders of magnitude higher, but encoding that here would reject the short periods this package's own takeover tests depend on, trading a real guard for slower tests. validate also rejects a non-positive RenewInterval outright: unreachable through withDefaults now, and checked anyway because it is the value handed to NewTicker. Mutating the two guards out one at a time confirms each alone suffices; the test fails only with both gone.

The reproducer the fuzzer minimized is committed as corpus, and the rejection is tabled in TestNewRejectsUnusableConfigs too, so it is not fuzz-only. The target is in the CI matrix, and that job's header comment is corrected — four of ten targets have now found a real defect, not three of eight.

Verified through the CI script itself: .github/scripts/fuzz-smoke.sh ./internal/coord FuzzNewConfig 60 → 3,001,445 executions clean.

Re-verified locally at this commit: go build, go vet, go test -race ./... (exit 0), make lint (0 issues), coverage gate (37 packages at or above their floor; internal/coord 88.6% against a floor of 88).

…im (#283)

Renew classifies three failures. A precondition failure means the lease moved;
a 404 means the record is gone; both drop the claim. A 500 means neither — it
says S3 could not be reached, and the holder's claim is exactly as valid as it
was a moment before. That third arm was the only one with no test.

It is the fail-open direction, which is why it is worth reaching. Dropping the
claim on a transient error would hand the resource to the next contender on
every blip, and would do it while the original holder may still be mid-action:
two nodes acting on one resource is the failure this package exists to prevent,
and arriving there through a retryable error would be a bitter way to get it.

The test goes through testaws.Fault rather than a backend double on purpose. A
double returning a canned error exercises the errors.Is arms and proves nothing
about which errors S3 produces; the injector puts a real 500 through the SDK,
the retry policy, the circuit breaker, and the error translator, so the
classification is tested against the shape of error that will actually arrive.
It also asserts the claim is still *assertable* after the store recovers, not
only that Held reports true — a cleared or replaced local ETag would fail the
next precondition while still looking held, which is how this could be wrong in
a way the obvious assertion misses.

Verified by mutation: making the arm treat any failure as a lost lease fails the
test on both the sentinel and Held. Coverage 88.6% -> 89.2%, Renew 93.8%, floor
raised to 89.

The .coverage-floors note this replaces was wrong rather than describing a real
gap. It said the branch needed "a backend double that fails a specific call,
which the endpoint does not currently offer" — testaws.InjectFault had done
exactly that for weeks. Worth recording as a reason to check the harness before
writing down that something is unreachable.
…ocess offline

`ErrCodeConditionalConflict` was missing from `IsServiceFailure`'s non-failure set, so
S3's 409 ConditionalRequestConflict counted against the `s3-writes` health component.
ErrorThreshold is 3. Ten conflicts on one key therefore drove `s3-writes` to unavailable
and the health gate then refused *every* write in the process — including writes to
unrelated keys by unrelated callers — under exactly the contention conditional writes
exist to arbitrate.

A conflict is the mechanism working. It means two well-formed requests collided and the
service did the work of noticing: evidence S3 is healthy, not evidence it is not. The
precondition-failure half of that reasoning was already applied in #282; only the conflict
half was missed, and it is the half that matters more, because a conflict is what a *busy*
key produces and so arrives in bursts by design.

Retryable and not-a-service-failure are separate questions and this code genuinely answers
them differently: `ErrCodeConditionalConflict` is in `retry.DefaultConfig`'s retryable set,
because repeating the write may well succeed, while `ErrCodePreconditionFailed` is not.
Being worth retrying is not evidence the service is unwell.

Found by `TestAConflictStormDoesNotDegradeWritesOrTripTheBreaker` rather than by review,
and only once the emulator could produce a 409 at all — the arm shipped untested because
nothing available could make it. That is the second defect in this series found by a test
written against a newly-available capability rather than by reading the code.

The enabling harness addition is `testaws.SeedConditionalConflict` /
`ClearConditionalConflicts`, driving substrate v0.93.0's `POST /v1/s3/conditional-conflict`
(scttfrdmn/substrate#540). It is not a `Fault` on purpose: a fault short-circuits in front
of the emulator and would answer 409 to a write whose precondition never held, a state S3
does not produce. A seeded conflict is consumed after the preconditions pass, so a genuine
412 or 404 still reports as itself and does not spend the budget, and an unconditional write
is unaffected — which is what makes the retryable/not-retryable distinction testable rather
than assumed. The control-plane request goes to the emulator directly rather than through
the recording proxy, because it is not S3 traffic and should not pollute the request log
tests assert against.

Tests:

- `TestConditionalConflictIsDistinctFromAPreconditionFailureAndIsRetried` — one request, the
  `ErrConditionalConflict` sentinel, *not* `ErrPreconditionFailed`, then the caller's own
  retry succeeding. `PutObjectIf` sits outside `b.retryer` on purpose, because a CAS caller
  must re-read state and recompute bytes before retrying; the retry succeeding is the
  substantive difference from a precondition failure, and asserting the error alone would
  not show it.
- `TestAConflictStormDoesNotDegradeWritesOrTripTheBreaker` — ten conflicts store nothing,
  the classification is asserted directly, and a final unconditional write detects a
  degraded `s3-writes` at the health gate.
- `TestSeedConditionalConflictOnlyAffectsConditionalWrites` — the seed's own regression
  test, pinning that it fires only where a real conflict would.

Mutation-verified in three directions: removing the non-failure entry, removing each seed
call, and folding the 409 arm into the 412 arm each break a named test.

Floors: `internal/testaws` 61 → 64. `internal/storage/s3` (83.5%) and `pkg/errors` (48.3%)
were already above theirs.
@scttfrdmn
scttfrdmn merged commit 4ee5c46 into main Aug 8, 2026
34 checks passed
@scttfrdmn
scttfrdmn deleted the feat/coord-lease-283 branch August 8, 2026 09:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

CAS-2: A lease over PutObjectIf, where every guarded action re-asserts the CAS

1 participant