Skip to main content

flint_lean/
lease.rs

1//! The subtree lease, held for ONE BARRIER's commit section (design
2//! 2026-09-13, `docs/plans/flint-lean-writer-lease-and-gated-assessment.md`
3//! §4), with a FIFO ticket so W writers wait at most W barriers.
4//!
5//! What the cell arbitrates is who may INSTALL a manifest. Nothing
6//! else: checkout, sync, status and the uploads of a barrier hold
7//! nothing, because every one of those is guarded by the object's own
8//! etag (`If-Match`) and installs no citation. Between barriers nobody
9//! holds the cell, so a second writer on the same workspace is Ready in
10//! checkout time and publishes every floor — the life-long lease this
11//! replaces made it wait the first writer's LIFETIME in
12//! ContainerCreating (`verbs.rs` used to call it "a DEADLOCK dressed as
13//! mutual exclusion", and had already taken checkout out of it).
14//!
15//! Deliberately NOT `tier::epoch::claim`: that path (a) runs the
16//! bucket-wide MPU takeover sweep, which a project-scoped proxy denies
17//! (the sweep is an operator-side job in lean — plan §2.4), and (b)
18//! gates self-recognition on the hub's state-directory occupancy lock.
19//! Lean's self-recognition token is the PERSISTED INCARNATION ID: it is
20//! emptyDir-scoped, so only the same pod's restarted container inherits
21//! it — which is exactly the one case where immediate self-supersede is
22//! safe. A replacement pod gets a fresh id and must wait out the quiet
23//! polls; that observation ({last_token, quiet_polls}) persists so a
24//! container restart RESUMES it instead of resetting the clock.
25//!
26//! The claim step is one read plus at most one CAS. Its verdicts:
27//!
28//! - a FRESH cell: acquire.
29//! - a cell that names THIS incarnation at THIS epoch: our own acquire
30//!   whose response was lost — adopt it.
31//! - a RELEASED cell reserved for nobody, or for us: acquire (a clean
32//!   handoff; no manifest rotation).
33//! - a RELEASED cell reserved for someone else: queue up once, and wait
34//!   — unless the reservation has stood unclaimed across
35//!   `HANDOFF_QUIET_POLLS` spaced observations (the reserved holder
36//!   died), in which case take it.
37//! - a cell HELD by someone else (or by us at an epoch we never
38//!   recorded: an orphaned acquire): queue up once, and wait — unless it
39//!   has stood still across `QUIET_POLLS` spaced observations (the
40//!   holder died inside its commit section), in which case DEPOSE it and
41//!   rotate the manifest, exactly the straggler fence there always was.
42//!
43//! An observation is "spaced" when at least `QUIET_SPACING_SECS` passed
44//! since the previous counted one. The wait loop polls faster than
45//! that (`CLAIM_POLL_SECS`), so a release is seen within a second, but
46//! deadness is still judged over a minute of a token that does not move.
47//! A waiter's own enqueue moves the token; the holder's next renew or
48//! handoff 412s, re-reads, and adopts the longer queue (`renew`,
49//! `release`).
50
51use std::sync::Arc;
52use std::time::{Duration, Instant};
53
54use flint_store::{EpochLease, EpochState, ObjectStore, StoreError};
55
56use super::state::Incarnation;
57use super::{manifest, LeanError, LeanResult, Syncer};
58
59/// Spaced quiet observations before a HELD cell's holder is judged dead
60/// and deposed (6 x 10 s: the takeover threshold the drills were run at).
61pub const QUIET_POLLS: u32 = 6;
62/// Spaced quiet observations before a RELEASED cell's reservation is
63/// judged abandoned (the reserved waiter died before claiming).
64pub const HANDOFF_QUIET_POLLS: u32 = 2;
65/// Minimum spacing between two observations that COUNT toward either
66/// threshold. Polls in between only look for a release or a handoff.
67pub const QUIET_SPACING_SECS: u64 = 10;
68/// The wait loop's poll cadence: one GET of a few-hundred-byte cell.
69pub const CLAIM_POLL_SECS: u64 = 1;
70/// The poll cadence of the waiter at the HEAD of the queue: it is the one
71/// the holder's handoff reserves the cell for, and every millisecond it
72/// takes to notice is a millisecond the cell stands idle with the rest of
73/// the queue behind it. In the writers drill (6 writers, 1 s polls) the
74/// cell sat released a median 614 ms before the next holder claimed it,
75/// on top of a 973 ms hold. Deadness is judged on `QUIET_SPACING_SECS`,
76/// not on this, so the thresholds do not move.
77pub const CLAIM_POLL_HEAD_MS: u64 = 200;
78/// Longest a barrier waits for the cell before failing (and being
79/// retried at the next floor). Comfortably past the deposal threshold
80/// plus the spacing it needs, so a dead holder is always deposed within
81/// one wait; a LIVE holder that never releases is a bug, and the
82/// deadline is what keeps it from being a hang.
83pub const CLAIM_DEADLINE_SECS: u64 = 150;
84
85pub enum ClaimOutcome {
86    /// Fresh, released-for-us, deposed, or adopted: held.
87    Claimed(EpochLease),
88    /// Not ours yet. `quiet_polls` is the spaced-observation count
89    /// against the current verdict's threshold; `behind` names the
90    /// holder or the reserved waiter we are waiting on; `next` says this
91    /// waiter heads the queue behind a held cell, so the holder's handoff
92    /// will name it.
93    Waiting { quiet_polls: u32, behind: Option<String>, next: bool },
94}
95
96/// Say so, loudly, if another product also writes this prefix.
97///
98/// Detection, deliberately NOT enforcement — see the forge twin. A
99/// lean workspace and a forge repository on one prefix arbitrate on
100/// different cells and will never fence each other, so without this
101/// nothing anywhere reports the condition.
102///
103/// Note what is NOT a finding: forge's legible export IS a lean
104/// workspace, published by forge rather than by an agent's syncer, so
105/// a syncer reading an export prefix finds only its own kind of cell.
106/// And an export nested under a repository's prefix puts this cell at
107/// `<prefix>/inner/.flint/lean/epoch`, which is not the key forge
108/// probes — the exact-key probe is what keeps that from reading as a
109/// collision.
110pub async fn warn_if_prefix_is_shared(sc: &Syncer) {
111    // A published mirror does not probe. Two reasons, and the second is
112    // the load-bearing one:
113    //
114    // Forge spawns a barrier per export, so this would be a recurring
115    // read for a condition that cannot change between two barriers of
116    // the same publisher. And forge echoes only the child lines
117    // containing "barrier" (export.rs:389), so a warning raised here
118    // would be read by nobody — a check whose output is discarded is
119    // worse than no check, because it looks like coverage.
120    //
121    // The prefix is still probed, ONCE, by the publisher at startup:
122    // see `warn_if_export_prefix_is_shared` in forge's twin. Moved, not
123    // dropped — an export prefix is a prefix two products both write
124    // legitimately, which makes it likelier than most to have a third
125    // pointed at it.
126    if sc.cfg.sole_writer {
127        return;
128    }
129    let found = flint_store::layout::neighbours(
130        sc.store.as_ref(),
131        &sc.cfg.prefix,
132        flint_store::layout::Writer::LeanWorkspace,
133    )
134    .await
135    .unwrap_or_default();
136    for f in found {
137        eprintln!("flint-sync: {}", f.report());
138    }
139}
140
141/// This pod's identity, minted once and persisted in the state
142/// directory (emptyDir-scoped: a restarted container inherits it, a
143/// replacement pod does not).
144pub fn incarnation(sc: &Syncer) -> LeanResult<Incarnation> {
145    match sc.state.load_incarnation()? {
146        Some(i) => Ok(i),
147        None => {
148            let i = Incarnation {
149                holder_id: format!("lean-{}", uuid::Uuid::new_v4()),
150                epoch: 0,
151                last_token: None,
152                quiet_polls: 0,
153            };
154            sc.state.save_incarnation(&i)?;
155            Ok(i)
156        }
157    }
158}
159
160/// One claim step. The caller loops on `Waiting` at its poll cadence;
161/// each call performs one read and at most one CAS (an acquire, or an
162/// enqueue). `count` says whether this observation is spaced far
163/// enough from the last counted one to advance the quiet thresholds —
164/// the loop decides that from its own clock, so the judgement of
165/// deadness stays tied to wall time however fast the loop polls.
166pub async fn claim_step(sc: &mut Syncer, count: bool) -> LeanResult<ClaimOutcome> {
167    let store: &Arc<dyn ObjectStore> = &sc.store;
168    let key = sc.cfg.epoch_key();
169    let mut inc = incarnation(sc)?;
170
171    let observed = store.epoch_read(&key).await?;
172    let Some(state) = observed else {
173        return match store.epoch_acquire(&key, &inc.holder_id, None).await {
174            Ok(lease) => {
175                inc.epoch = lease.epoch;
176                inc.last_token = None;
177                inc.quiet_polls = 0;
178                sc.state.save_incarnation(&inc)?;
179                sc.lease = Some(lease.clone());
180                sc.trace("claim", serde_json::json!({"verdict": "claimed", "how": "fresh", "epoch": lease.epoch}));
181                Ok(ClaimOutcome::Claimed(lease))
182            }
183            Err(StoreError::PreconditionFailed(_)) | Err(StoreError::Conflict(_)) => {
184                Ok(ClaimOutcome::Waiting { quiet_polls: 0, behind: None, next: false })
185            }
186            Err(e) => Err(e.into()),
187        };
188    };
189
190    // Self-recognition needs the EPOCH too (review 2026-09-12, lease-3 /
191    // audit #7): a cell naming this holder at an epoch this incarnation
192    // never recorded is our own acquire whose response was lost, or
193    // whose rotation failed after it landed — the straggler it deposed
194    // may still be mid-barrier, so that path takes the takeover
195    // rotation like any other.
196    let same_holder = state.holder_id == inc.holder_id;
197    let ours = same_holder && state.epoch == inc.epoch && !state.released;
198    let quiet = inc.last_token.as_deref() == Some(state.token.as_str());
199    let counted_quiet = if count {
200        if quiet {
201            inc.quiet_polls + 1
202        } else {
203            0
204        }
205    } else {
206        inc.quiet_polls
207    };
208
209    if ours {
210        // Our own acquire whose response was lost, or a cell a previous
211        // container of this pod is still named on at the epoch we
212        // recorded: adopt it IN PLACE — token and queue as they stand,
213        // no write. (Re-acquiring would move the epoch for nothing and
214        // make every reader of the cell count a barrier that never ran.)
215        let lease = EpochLease {
216            holder_id: state.holder_id,
217            epoch: state.epoch,
218            token: state.token,
219            waiters: state.waiters,
220        };
221        inc.last_token = None;
222        inc.quiet_polls = 0;
223        sc.state.save_incarnation(&inc)?;
224        sc.lease = Some(lease.clone());
225        sc.trace("claim", serde_json::json!({"verdict": "claimed", "how": "adopted-own", "epoch": lease.epoch}));
226        return Ok(ClaimOutcome::Claimed(lease));
227    }
228
229    // The verdict. `take` = acquire now; `rotate` = the acquire is a
230    // deposal of a possibly-live straggler and must fence it.
231    let (take, rotate, behind) = if same_holder && !state.released {
232        // Orphaned own: our acquire landed and its response was lost, or
233        // its rotation failed after it landed. The straggler it deposed
234        // may still be mid-commit, so this takes the rotation too.
235        (true, true, None)
236    } else if state.released {
237        match state.handoff.as_deref() {
238            None => (true, false, None),
239            Some(h) if h == inc.holder_id => (true, false, None),
240            Some(h) => (counted_quiet >= HANDOFF_QUIET_POLLS, false, Some(h.to_string())),
241        }
242    } else {
243        // Held by someone else, or by us at an epoch we never recorded.
244        (counted_quiet >= QUIET_POLLS, true, Some(state.holder_id.clone()))
245    };
246
247    if take {
248        // Rotation is needed ONLY for the unreleased-foreign takeover (a
249        // possibly-live straggler mid-commit). A released cell is a
250        // clean handoff — the holder's barrier completed before its
251        // release — and self-recognition means the previous container's
252        // process (and any in-flight write of its) died with it.
253        // Rotating on those paths is pure manifest churn: at 100k+
254        // entries it is a multi-MB GET+PUT per claim, it double-bumps
255        // seq, and it defeats the no-change barrier's early exit
256        // (measured on the 0b rig). Under the per-barrier lease that
257        // would be every boundary.
258        let prior = serde_json::json!({"holder": state.holder_id, "epoch": state.epoch, "released": state.released,
259            "handoff": state.handoff, "waiters": state.waiters});
260        let how = if rotate && same_holder {
261            "orphaned-own"
262        } else if rotate {
263            "deposed"
264        } else if state.handoff.as_deref().map(|h| h != inc.holder_id).unwrap_or(false) {
265            "skipped-handoff"
266        } else {
267            "released"
268        };
269        return match store.epoch_acquire(&key, &inc.holder_id, Some(&state)).await {
270            Ok(lease) => {
271                if rotate {
272                    manifest::rotate_for_takeover(store.as_ref(), &sc.cfg, lease.epoch).await?;
273                }
274                inc.epoch = lease.epoch;
275                inc.last_token = None;
276                inc.quiet_polls = 0;
277                sc.state.save_incarnation(&inc)?;
278                sc.lease = Some(lease.clone());
279                sc.trace("claim", serde_json::json!({"verdict": "claimed", "how": how, "epoch": lease.epoch, "prior": prior}));
280                Ok(ClaimOutcome::Claimed(lease))
281            }
282            Err(StoreError::PreconditionFailed(_)) | Err(StoreError::Conflict(_)) => {
283                // Lost the race (a rival acquire, or an enqueue moved the
284                // token); restart the observation.
285                inc.last_token = None;
286                inc.quiet_polls = 0;
287                sc.state.save_incarnation(&inc)?;
288                Ok(ClaimOutcome::Waiting { quiet_polls: 0, behind, next: false })
289            }
290            Err(e) => Err(e.into()),
291        };
292    }
293
294    // Not ours yet: make sure we are in the queue, ONCE. The enqueue
295    // moves the token, so the observation restarts from the token we
296    // wrote — our own append must not read as the holder's renewal,
297    // and it must not reset a count that a rival's append did not.
298    let token = if state.waiters.iter().any(|w| w == &inc.holder_id) {
299        state.token.clone()
300    } else {
301        match store.epoch_enqueue(&key, &state, &inc.holder_id).await {
302            Ok(after) => after.token,
303            Err(StoreError::PreconditionFailed(_)) | Err(StoreError::Conflict(_)) => {
304                // Somebody else moved the cell first; observe again.
305                state.token.clone()
306            }
307            Err(e) => return Err(e.into()),
308        }
309    };
310    if count {
311        inc.quiet_polls = counted_quiet;
312        inc.last_token = Some(token);
313        sc.state.save_incarnation(&inc)?;
314    }
315    // First in the queue behind a HELD cell (our enqueue appended us to
316    // whatever `state.waiters` held, or we were already in it).
317    let next = !state.released
318        && state.waiters.iter().find(|w| **w != state.holder_id).map(|w| w == &inc.holder_id).unwrap_or(true);
319    Ok(ClaimOutcome::Waiting { quiet_polls: counted_quiet, behind, next })
320}
321
322/// The wait loop: claim the cell for a commit section, or give up
323/// after `CLAIM_DEADLINE_SECS` so a holder that never releases turns
324/// into a failed (and retried) barrier rather than a hang.
325pub async fn claim(sc: &mut Syncer) -> LeanResult<EpochLease> {
326    let started = Instant::now();
327    let mut last_counted: Option<Instant> = None;
328    let mut reported: Option<String> = None;
329    let spacing = Duration::from_secs(sc.cfg.claim_quiet_spacing_secs);
330    let deadline = Duration::from_secs(sc.cfg.claim_deadline_secs);
331    let poll = Duration::from_secs(sc.cfg.claim_poll_secs);
332    let head_poll = Duration::from_millis(sc.cfg.claim_poll_head_ms).min(poll);
333    loop {
334        let count = last_counted.map(|t| t.elapsed() >= spacing).unwrap_or(true);
335        match claim_step(sc, count).await? {
336            ClaimOutcome::Claimed(lease) => return Ok(lease),
337            ClaimOutcome::Waiting { quiet_polls, behind, next } => {
338                if count {
339                    last_counted = Some(Instant::now());
340                    sc.trace("claim", serde_json::json!({"verdict": "waiting", "behind": behind, "quiet_polls": quiet_polls,
341                        "waited_ms": started.elapsed().as_millis() as u64}));
342                    // Once per spaced observation, not once per second.
343                    let line = format!(
344                        "flint-sync: waiting for the publish fence behind {} (quiet {quiet_polls})",
345                        behind.as_deref().unwrap_or("a rival claim")
346                    );
347                    if reported.as_deref() != Some(line.as_str()) {
348                        eprintln!("{line}");
349                        reported = Some(line);
350                    }
351                }
352                if started.elapsed() >= deadline {
353                    sc.trace("claim", serde_json::json!({"verdict": "deadline", "behind": behind,
354                        "waited_ms": started.elapsed().as_millis() as u64}));
355                    return Err(LeanError::State(format!(
356                        "could not acquire the publish fence within {}s \
357                         (behind {}); this barrier is abandoned and retried at the next floor — \
358                         its uploads are durable and the next barrier adopts them",
359                        deadline.as_secs(),
360                        behind.as_deref().unwrap_or("a rival claim")
361                    )));
362                }
363                tokio::time::sleep(if next { head_poll } else { poll }).await;
364            }
365        }
366    }
367}
368
369/// What this syncer is OBSERVED to be doing, for the cell's echo
370/// (boundary-verbs plan §2.6). Computed from local files only — the
371/// same store-free discipline as `write_gauges`, and for the same
372/// reason: this rides writes that already happen, so it must not add a
373/// request to the one tick every idle workspace in the fleet pays (leg
374/// B8's oracle counts them).
375fn observed_echo(sc: &Syncer) -> Option<String> {
376    let g = sc.load_gauges().ok()?;
377    let (seq, unix) = g.last_boundary.as_ref().map(|b| (b.seq, b.unix)).unwrap_or((0, 0));
378    // The pre-flight verdict lives in the marker the AGENT reads; the
379    // operator has no other way to see it, so it rides the echo.
380    let caps: Option<super::control::Capabilities> =
381        std::fs::read(sc.cfg.control_dir().join(super::control::CAPABILITIES))
382            .ok()
383            .and_then(|b| serde_json::from_slice(&b).ok());
384    serde_json::to_string(&flint_store::LeaseEcho {
385        syncer_version: super::SYNCER_VERSION.to_string(),
386        protocol: super::SENTINEL_PROTOCOL,
387        last_cited_seq: seq,
388        last_cited_unix: unix,
389        sentinel_verbs_active: caps.map(|c| !c.verbs.is_empty()).unwrap_or(false),
390        metrics_bound: sc.load_metrics_posture().filter(|m| m.enabled).map(|m| m.bound),
391    })
392    .ok()
393}
394
395/// Re-read the cell after a 412 and, if it still names this holder at
396/// this epoch unreleased, hand back its current token and queue: the
397/// only things that move OUR cell's token are our own writes whose
398/// response was lost and the waiters' enqueues, and neither is a
399/// takeover. Anything else is the fence.
400async fn still_ours(sc: &Syncer, key: &str, lease: &EpochLease) -> Option<EpochLease> {
401    match sc.store.epoch_read(key).await {
402        Ok(Some(state))
403            if state.holder_id == lease.holder_id && state.epoch == lease.epoch && !state.released =>
404        {
405            Some(EpochLease {
406                holder_id: state.holder_id,
407                epoch: state.epoch,
408                token: state.token,
409                waiters: state.waiters,
410            })
411        }
412        _ => None,
413    }
414}
415
416/// Renew the held lease inside a commit section; a 412 that is not our
417/// own moved token means deposed — the caller must abandon the barrier
418/// (self-fence).
419///
420/// The renewal also carries the observed-state echo (§2.6).
421pub async fn renew(sc: &mut Syncer) -> LeanResult<()> {
422    let key = sc.cfg.epoch_key();
423    let lease = sc
424        .lease
425        .clone()
426        .ok_or_else(|| LeanError::State("renew without a lease".into()))?;
427    let echo = observed_echo(sc);
428    match sc.store.epoch_renew(&key, &lease, echo.as_deref()).await {
429        Ok(l) => {
430            sc.lease = Some(l);
431            // The renewal is a probe of our own credentials, so it is
432            // also a place a pause can be observed to have ENDED.
433            // Best-effort: a gauge that failed to write must not fail a
434            // renewal that succeeded.
435            let _ = sc.clear_auth_pause();
436            Ok(())
437        }
438        Err(StoreError::PreconditionFailed(e)) => {
439            // A 412 is not yet a deposal. The renew CAS is If-Match on
440            // OUR token, and three things move that token: a
441            // successor's acquire, a waiter's enqueue, or our own
442            // previous write whose RESPONSE was lost. Only the first is
443            // a takeover, and treating the others as one made a live
444            // holder fence itself (audit 2026-09-03, finding 2). One
445            // read tells the cases apart.
446            match still_ours(sc, &key, &lease).await {
447                Some(adopted) => {
448                    eprintln!(
449                        "flint-sync: renew 412 on a cell that is still ours (epoch {}, {} queued): \
450                         adopting its token, not fencing",
451                        adopted.epoch,
452                        adopted.waiters.len()
453                    );
454                    // Review 2026-09-12, lease-2: the adoption alone
455                    // writes nothing, so the token would stand still
456                    // for a whole takeover threshold and a waiter could
457                    // count a live holder dead. One renew moves it; if
458                    // that write fails the adopted token stands and the
459                    // next tick tries again.
460                    sc.lease = Some(
461                        sc.store
462                            .epoch_renew(&key, &adopted, echo.as_deref())
463                            .await
464                            .unwrap_or(adopted),
465                    );
466                    let _ = sc.clear_auth_pause();
467                    Ok(())
468                }
469                None => {
470                    sc.lease = None;
471                    Err(LeanError::Fenced(format!("deposed at renew: {e}")))
472                }
473            }
474        }
475        // 401/403 is not contention and not a bucket fault; retrying
476        // cannot fix it. Record when the pause began while we still can:
477        // nothing we write to the STORE can carry this, because the
478        // request that would carry it is the one being refused (design
479        // §6.3).
480        Err(e @ StoreError::Auth(_)) => {
481            let _ = sc.note_auth_pause();
482            Err(e.into())
483        }
484        Err(e) => Err(e.into()),
485    }
486}
487
488/// The claim precondition (audit 2026-09-03, finding 5). With a project
489/// id stamped (`FLINT_SYNC_PROJECT_ID`), refuse to run over a prefix
490/// whose claim cell names ANOTHER project. The operator's refuse-foreign
491/// was advisory on the data plane: a CR the operator had not yet judged
492/// resolved to its spec, and the syncer checked out and republished over
493/// the foreign project's manifest. The cell is durable in the bucket, so
494/// the data plane can read it — one GET before the first claim step.
495/// Absent cell ⇒ a fresh prefix, claimable; unstamped ⇒ no check (the
496/// pre-operator posture, which the drill runs). A foreign claim is
497/// `LeanError::Refused`: the process exits `EXIT_REFUSED`, which the
498/// delivery treats as final (tear down, name the reason) rather than
499/// as one more crash to restart.
500pub async fn verify_claim(sc: &Syncer) -> LeanResult<()> {
501    let Some(mine) = sc.cfg.project_id.as_deref() else { return Ok(()) };
502    let key = sc.cfg.claim_key();
503    match sc.store.get_whole(&key, None).await {
504        Ok((_, body)) => {
505            let doc: serde_json::Value = serde_json::from_slice(&body)
506                .map_err(|e| LeanError::State(format!("claim cell {key} is unparseable: {e}")))?;
507            match doc.get("project_id").and_then(|v| v.as_str()) {
508                Some(p) if p == mine => Ok(()),
509                Some(p) => Err(LeanError::Refused(format!(
510                    "prefix {} is claimed by project {p:?}; this workspace is project {mine:?} — \
511                     refusing to check out or publish over another project's data (delete the \
512                     standing claim explicitly if this reuse is intended)",
513                    sc.cfg.prefix
514                ))),
515                None => Err(LeanError::State(format!("claim cell {key} names no project_id"))),
516            }
517        }
518        Err(StoreError::NotFound(_)) => Ok(()),
519        Err(e) => Err(e.into()),
520    }
521}
522
523/// Release at the end of a commit section: the cell is handed to the
524/// queue head and keeps this barrier's echo.
525///
526/// Every waiter's enqueue moves the token, so under contention the handoff
527/// can 412 several times in a row, and S3 answers a conditional write that
528/// races another with 409 ConditionalRequestConflict. Each is re-read: while
529/// the cell still names this holder at this epoch, unreleased, the handoff
530/// is retried on the adopted token. Only a cell that is no longer ours ends
531/// the attempt quietly. Returning with the cell still held — what a second
532/// 412 or a 409 used to do — leaves nobody to release it: the queue waits
533/// out the deposal threshold and the takeover rotates the manifest (the
534/// contention drill, 2026-09-14).
535pub async fn release(sc: &mut Syncer) -> LeanResult<()> {
536    let key = sc.cfg.epoch_key();
537    let Some(lease) = sc.lease.take() else { return Ok(()) };
538    let echo = observed_echo(sc);
539    sc.trace("release", serde_json::json!({"epoch": lease.epoch, "waiters_at_claim": lease.waiters}));
540    // `release` above is stamped before the request, `handed_off` after it
541    // lands: the gap between one holder's release and the next claim is
542    // the handoff's own latency plus the reserved waiter's poll delay.
543    let mut current = lease;
544    for attempt in 0..RELEASE_ATTEMPTS {
545        match sc.store.epoch_handoff(&key, &current, echo.as_deref()).await {
546            Ok(()) => {
547                sc.trace("handed_off", serde_json::json!({"epoch": current.epoch, "retried": attempt > 0, "attempts": attempt + 1}));
548                return Ok(());
549            }
550            Err(StoreError::PreconditionFailed(_)) | Err(StoreError::Conflict(_)) => {
551                if attempt > 0 {
552                    // Waiters enqueue in bursts; step out of the burst.
553                    tokio::time::sleep(Duration::from_millis(20 * attempt as u64)).await;
554                }
555                match sc.store.epoch_read(&key).await {
556                    Ok(Some(state))
557                        if state.holder_id == current.holder_id
558                            && state.epoch == current.epoch
559                            && !state.released =>
560                    {
561                        current = EpochLease {
562                            holder_id: state.holder_id,
563                            epoch: state.epoch,
564                            token: state.token,
565                            waiters: state.waiters,
566                        };
567                    }
568                    // Released, rotated or taken: the cell is the successor's.
569                    Ok(_) => return Ok(()),
570                    Err(e) if attempt + 1 < RELEASE_ATTEMPTS => {
571                        eprintln!("flint-sync: re-reading the publish fence for its handoff: {e}; retrying");
572                    }
573                    Err(e) => return Err(e.into()),
574                }
575            }
576            Err(e) => return Err(e.into()),
577        }
578    }
579    Err(LeanError::State(format!(
580        "the publish fence handoff lost {RELEASE_ATTEMPTS} races to the queue; the cell stays ours \
581         until this writer's next claim adopts it, or a waiter deposes it"
582    )))
583}
584
585/// Handoff attempts before a release gives up (each lost to a waiter's
586/// enqueue or a racing conditional write, re-read between them).
587pub const RELEASE_ATTEMPTS: u32 = 8;
588
589/// A restarted container that finds the cell HELD by its own
590/// incarnation releases it: it holds nothing in memory, the intent
591/// journal replays whatever the previous container left, and a cell
592/// left held would cost every other writer a 60 s deposal wait.
593pub async fn release_stale_own(sc: &mut Syncer) -> LeanResult<()> {
594    let key = sc.cfg.epoch_key();
595    let inc = incarnation(sc)?;
596    if let Some(state) = sc.store.epoch_read(&key).await? {
597        if state.holder_id == inc.holder_id && !state.released {
598            eprintln!(
599                "flint-sync: the publish fence was left held by a previous container of this pod \
600                 (epoch {}); releasing it",
601                state.epoch
602            );
603            sc.lease = Some(EpochLease {
604                holder_id: state.holder_id,
605                epoch: state.epoch,
606                token: state.token,
607                waiters: state.waiters,
608            });
609            return release(sc).await;
610        }
611    }
612    Ok(())
613}
614
615// An observed cell, re-exported for the callers that fence on one.
616pub type Observed = EpochState;