Repository navigation
feat(coord): a lease over PutObjectIf where every guarded action re-asserts the CAS (#283) - #381
Conversation
…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.
|
Pushed
What it found. Raised inside Fix. The reproducer the fuzzer minimized is committed as corpus, and the rejection is tabled in Verified through the CI script itself: Re-verified locally at this commit: |
…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.
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
Leasethat writes. Acting under a lease goes throughLease.Do, which re-asserts before invoking the action and hands it aGuardwhosePut,PutIf, andDeleteeach 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:
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.PutIfexists 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:
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 fullPeriod, 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.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
DeleteObjectIfontypes.Backend.Releasetherefore 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
Renewreads 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 handedErrPreconditionFailedby its own holder's write, could not distinguish that from a takeover, and returnedErrLostand 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 everyGuardmethod's re-assert both callRenew, 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 byTestOneHoldersConcurrentRenewalsDoNotDefeatEachOther, 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
Doaction 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.Guard.Putre-assert removedTestGuardedWriteFailsWhenTheLeaseIsStolenMidActionGuard.Deletere-assert removedTestGuardedDeleteAndPutIfAlsoReassert/DeleteGuard.PutIfre-assert removedTestGuardedDeleteAndPutIfAlsoReassert/PutIfGuard.Putrenews then does not writeTestGuardedWriteFailsWhenTheLeaseIsStolenMidAction,TestGuardedWritesReachTheStoreWhileTheLeaseIsHeldGuard.Deleterenews then does not deleteTestGuardedWritesReachTheStoreWhileTheLeaseIsHeldGuard.PutIfdrops the preconditionTestGuardedWritesReachTheStoreWhileTheLeaseIsHeldTestEveryWriteMovesTheETagTestAcquisitionIsBounded,TestAbandonedLeaseIsTakenOverOnlyAfterAFullPeriodDorecords the renewal failure but does not cancelTestDoCancelsTheActionWhenTheLeaseIsLostMutation found two defects in the tests, not the code. Stealing the lease before
DomeantDo's own openingRenewrejected 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 nanosecondAcquired/Renewedtimestamps 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.PutIfandGuard.Deletesat 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.TestGuardedWritesReachTheStoreWhileTheLeaseIsHeldcloses that, and the.coverage-floorsnote 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
MaxAttemptswith ±20% jitter — never an unbounded spin — andLeasetakes 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.
Newaskstypes.CapabilityReporterand 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
PutObjectIfErrNotSupportedfrom the probe ⇒ refuse to start, never run unguarded-race(8 contenders, CAS counter a second holder would trip)Verification
go build ./...,go vet ./...— cleango test -race ./...— exit 0, all packagesmake lint— 0 issues./scripts/coverage-gate.sh— 37 packages at or above their floor;internal/coord89.1% against a new floor of 88go test -race -count=5 ./internal/coord/× 20 (100 runs) — 0 failures, against 1 in 60 before the concurrent-renewal fixAlso fixes a broken godoc link in
pkg/types/conditional.goleft by #282:[ErrNotFound]names no symbol.Next in the series: #284 (remove the
executeStrongConsistencyfan-out), then #285.