reddb-io-server 1.10.0

RedDB server-side engine: storage, runtime, replication, MCP, AI, and the gRPC/HTTP/RedWire/PG-wire dispatchers. Re-exported by the umbrella `reddb` crate.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
//! Serverless writer lease (PLAN.md Phase 5 / W6).
//!
//! Multiple RedDB instances can attach to the same remote-backed
//! database key. To prevent two of them from concurrently mutating the
//! same remote artifacts (snapshots, WAL segments, head manifest),
//! exactly one of them must hold a *writer lease*. Other instances may
//! still attach as read-only replicas without acquiring a lease.
//!
//! ## Wire format
//!
//! The lease is serialized as JSON under
//! `leases/{database_key}.lease.json` on the remote backend:
//!
//! ```json
//! {
//!   "database_key": "main",
//!   "holder_id": "instance-uuid",
//!   "term": 3,
//!   "generation": 7,
//!   "acquired_at_ms": 1730000000000,
//!   "expires_at_ms":  1730000060000
//! }
//! ```
//!
//! - `generation` increments every time a different holder acquires
//!   the key. The holder stamps its uploads with the generation so a
//!   stale writer (whose lease was poached because it expired) can be
//!   detected during reclaim by reading the current lease and
//!   comparing.
//! - `term` is the replication term the holder acquired under (issue
//!   #835, ADR 0030). A contender on a term *behind* the published
//!   lease's term is a deposed primary and is fenced
//!   (`LeaseError::Fenced`) — even if the lease has expired and would
//!   otherwise be poachable. Legacy lease objects without a `term`
//!   field decode as `DEFAULT_REPLICATION_TERM`.
//! - `expires_at_ms` is wall-clock millis since UNIX epoch. A holder
//!   refreshes it periodically; a contender treats anything past it as
//!   poachable.
//!
//! ## Atomicity contract
//!
//! Lease mutation requires backend-side compare-and-swap. Backends
//! advertise this through `RemoteBackend::supports_conditional_writes`
//! and implement object version tokens + conditional writes/deletes.
//! A backend that cannot enforce `IfAbsent` / `IfVersion` fails
//! closed before the instance is allowed to write. This keeps
//! serverless fencing out of "last writer wins" territory.

use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;

use crate::serde_json::{self, Value as JsonValue};
use crate::storage::backend::{
    AtomicRemoteBackend, BackendError, BackendObjectVersion, ConditionalDelete, ConditionalPut,
};
use serde_json::Map;

/// Per-process monotonic counter that disambiguates lease temp files
/// when multiple threads sample `now_unix_nanos()` within the same
/// nanosecond (observed on virtualised CI runners with coarse
/// clocks). Without this, two writers could share the same temp path,
/// and the CAS holder would publish the *other* writer's bytes,
/// producing a spurious `LostRace` for the apparent winner.
static LEASE_TEMP_COUNTER: AtomicU64 = AtomicU64::new(0);

fn lease_temp_path(kind: &str) -> std::path::PathBuf {
    let unique = LEASE_TEMP_COUNTER.fetch_add(1, Ordering::Relaxed);
    std::env::temp_dir().join(format!(
        "reddb-lease-{kind}-{}-{}-{unique}.json",
        std::process::id(),
        crate::utils::now_unix_nanos()
    ))
}

/// One snapshot of who owns the writer lease for a database key.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WriterLease {
    pub database_key: String,
    pub holder_id: String,
    /// Replication term the holder acquired the lease under (issue #835,
    /// ADR 0030). Tying the lease to the term is what makes a deposed
    /// primary fail closed: once a new primary acquires the lease at a
    /// higher term, the old holder's term is behind and every term-gated
    /// op it attempts is fenced. Defaults to
    /// [`DEFAULT_REPLICATION_TERM`](crate::replication::DEFAULT_REPLICATION_TERM)
    /// when read from a legacy (pre-#835) lease object that did not carry
    /// a term, so older lease files stay readable.
    pub term: u64,
    pub generation: u64,
    pub acquired_at_ms: u64,
    pub expires_at_ms: u64,
}

impl WriterLease {
    pub fn is_expired(&self, now_ms: u64) -> bool {
        self.expires_at_ms <= now_ms
    }

    /// Is this lease fenced by `current_term`? A holder whose lease was
    /// stamped under a term *behind* the cluster's current term is a
    /// stale writer from a superseded timeline (issue #835) — it must
    /// fail closed rather than keep mutating the new timeline.
    pub fn fenced_by_term(&self, current_term: u64) -> bool {
        self.term < current_term
    }

    /// The monotonic fencing token `(term, generation)`. Both components
    /// advance forward across a legitimate handover (a new primary wins a
    /// higher term *and* takes a fresh lease generation), so a stale
    /// holder is ordered strictly behind on both axes (ADR 0030).
    pub fn fencing_token(&self) -> (u64, u64) {
        (self.term, self.generation)
    }

    fn to_json(&self) -> JsonValue {
        let mut object = Map::new();
        object.insert(
            "database_key".to_string(),
            JsonValue::String(self.database_key.clone()),
        );
        object.insert(
            "holder_id".to_string(),
            JsonValue::String(self.holder_id.clone()),
        );
        object.insert("term".to_string(), JsonValue::Number(self.term as f64));
        object.insert(
            "generation".to_string(),
            JsonValue::Number(self.generation as f64),
        );
        object.insert(
            "acquired_at_ms".to_string(),
            JsonValue::Number(self.acquired_at_ms as f64),
        );
        object.insert(
            "expires_at_ms".to_string(),
            JsonValue::Number(self.expires_at_ms as f64),
        );
        JsonValue::Object(object)
    }

    fn from_json(value: &JsonValue) -> Result<Self, LeaseError> {
        let obj = value
            .as_object()
            .ok_or_else(|| LeaseError::InvalidFormat("lease json is not an object".into()))?;
        Ok(Self {
            database_key: obj
                .get("database_key")
                .and_then(JsonValue::as_str)
                .ok_or_else(|| LeaseError::InvalidFormat("missing database_key".into()))?
                .to_string(),
            holder_id: obj
                .get("holder_id")
                .and_then(JsonValue::as_str)
                .ok_or_else(|| LeaseError::InvalidFormat("missing holder_id".into()))?
                .to_string(),
            // Legacy lease objects (pre-#835) carry no term — default to the
            // base replication term so they stay readable and act as "never
            // fenced" until a termed primary re-stamps them.
            term: obj
                .get("term")
                .and_then(JsonValue::as_u64)
                .unwrap_or(crate::replication::DEFAULT_REPLICATION_TERM),
            generation: obj
                .get("generation")
                .and_then(JsonValue::as_u64)
                .ok_or_else(|| LeaseError::InvalidFormat("missing generation".into()))?,
            acquired_at_ms: obj
                .get("acquired_at_ms")
                .and_then(JsonValue::as_u64)
                .ok_or_else(|| LeaseError::InvalidFormat("missing acquired_at_ms".into()))?,
            expires_at_ms: obj
                .get("expires_at_ms")
                .and_then(JsonValue::as_u64)
                .ok_or_else(|| LeaseError::InvalidFormat("missing expires_at_ms".into()))?,
        })
    }
}

#[derive(Debug)]
pub enum LeaseError {
    Backend(BackendError),
    /// A different holder owns a non-expired lease.
    Held {
        current: WriterLease,
        now_ms: u64,
    },
    /// We uploaded a fresh lease but a re-read shows a different holder
    /// or generation, so we lost a concurrent acquire race.
    LostRace {
        attempted_holder: String,
        observed: WriterLease,
    },
    InvalidFormat(String),
    /// The release/refresh target no longer matches what's on the
    /// backend (lease was already poached or removed).
    Stale {
        attempted_holder: String,
        attempted_generation: u64,
        observed: Option<WriterLease>,
    },
    /// A holder on a term *behind* the current term tried to take or keep
    /// the lease (issue #835). The deposed primary is fenced: a newer term
    /// already owns the timeline, so the stale holder fails closed rather
    /// than mutate it.
    Fenced {
        attempted_holder: String,
        attempted_term: u64,
        current_term: u64,
    },
}

impl std::fmt::Display for LeaseError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Backend(err) => write!(f, "lease backend error: {err}"),
            Self::Held { current, now_ms } => {
                write!(
                    f,
                    "lease for '{}' held by '{}' (gen {}, expires in {} ms)",
                    current.database_key,
                    current.holder_id,
                    current.generation,
                    current.expires_at_ms.saturating_sub(*now_ms)
                )
            }
            Self::LostRace {
                attempted_holder,
                observed,
            } => write!(
                f,
                "lost lease acquire race: '{}' tried to take '{}' but '{}' (gen {}) won",
                attempted_holder, observed.database_key, observed.holder_id, observed.generation
            ),
            Self::InvalidFormat(msg) => write!(f, "invalid lease format: {msg}"),
            Self::Stale {
                attempted_holder,
                attempted_generation,
                observed,
            } => match observed {
                Some(o) => write!(
                    f,
                    "stale lease op: '{}' (gen {}) tried to act, but current is '{}' (gen {})",
                    attempted_holder, attempted_generation, o.holder_id, o.generation
                ),
                None => write!(
                    f,
                    "stale lease op: '{}' (gen {}) tried to act, but no lease present",
                    attempted_holder, attempted_generation
                ),
            },
            Self::Fenced {
                attempted_holder,
                attempted_term,
                current_term,
            } => write!(
                f,
                "fenced lease op: '{attempted_holder}' on stale term {attempted_term} \
                 is behind current term {current_term}"
            ),
        }
    }
}

impl std::error::Error for LeaseError {}

impl From<BackendError> for LeaseError {
    fn from(value: BackendError) -> Self {
        Self::Backend(value)
    }
}

struct VersionedLease {
    lease: WriterLease,
    version: BackendObjectVersion,
}

/// Wraps an `AtomicRemoteBackend` with lease primitives. The lease
/// object is stored under a deterministic key derived from
/// `database_key`; the store reads/writes that one key.
///
/// The trait bound `AtomicRemoteBackend` is the type-system version
/// of "this backend can enforce CAS" — backends that cannot
/// (Turso, D1, plain HTTP without ETag) deliberately do not
/// implement the trait, so wiring them into a `LeaseStore` becomes
/// a compile error rather than a runtime fail-closed.
pub struct LeaseStore {
    backend: Arc<dyn AtomicRemoteBackend>,
    prefix: String,
}

impl LeaseStore {
    pub fn new(backend: Arc<dyn AtomicRemoteBackend>) -> Self {
        Self {
            backend,
            prefix: "leases/".to_string(),
        }
    }

    pub fn with_prefix(mut self, prefix: impl Into<String>) -> Self {
        let p = prefix.into();
        self.prefix = if p.ends_with('/') { p } else { format!("{p}/") };
        self
    }

    fn key_for(&self, database_key: &str) -> String {
        format!("{}{}.lease.json", self.prefix, database_key)
    }

    /// Read whatever lease object is currently published. `None` means
    /// no lease has ever been written for this key.
    pub fn current(&self, database_key: &str) -> Result<Option<WriterLease>, LeaseError> {
        self.read_lease(database_key)
    }

    fn read_lease(&self, database_key: &str) -> Result<Option<WriterLease>, LeaseError> {
        let key = self.key_for(database_key);
        let temp = lease_temp_path("read");
        let downloaded = self.backend.download(&key, &temp)?;
        if !downloaded {
            return Ok(None);
        }
        let bytes = std::fs::read(&temp)
            .map_err(|err| LeaseError::Backend(BackendError::Transport(err.to_string())))?;
        let _ = std::fs::remove_file(&temp);
        let json: JsonValue = serde_json::from_slice(&bytes)
            .map_err(|err| LeaseError::InvalidFormat(format!("lease json parse: {err}")))?;
        WriterLease::from_json(&json).map(Some)
    }

    fn current_versioned(&self, database_key: &str) -> Result<Option<VersionedLease>, LeaseError> {
        let key = self.key_for(database_key);
        let before = match self.backend.object_version(&key)? {
            Some(version) => version,
            None => return Ok(None),
        };
        let temp = lease_temp_path("read");
        let downloaded = self.backend.download(&key, &temp)?;
        if !downloaded {
            return Ok(None);
        }
        let after = self.backend.object_version(&key)?;
        if after.as_ref() != Some(&before) {
            let _ = std::fs::remove_file(&temp);
            return Err(LeaseError::Backend(BackendError::PreconditionFailed(
                "lease object changed while being read".to_string(),
            )));
        }
        let bytes = std::fs::read(&temp)
            .map_err(|err| LeaseError::Backend(BackendError::Transport(err.to_string())))?;
        let _ = std::fs::remove_file(&temp);
        let json: JsonValue = serde_json::from_slice(&bytes)
            .map_err(|err| LeaseError::InvalidFormat(format!("lease json parse: {err}")))?;
        Ok(Some(VersionedLease {
            lease: WriterLease::from_json(&json)?,
            version: before,
        }))
    }

    /// Try to acquire the lease for `database_key` on behalf of
    /// `holder_id`, valid for `ttl_ms`. Returns the `WriterLease` we
    /// own on success. Errors:
    /// - `LeaseError::Held` if a different holder owns a non-expired
    ///   lease.
    /// - `LeaseError::LostRace` if a concurrent contender beat us.
    ///
    /// Acquires under the base replication term; use
    /// [`LeaseStore::try_acquire_for_term`] to stamp a specific term and
    /// fence stale-term contenders (issue #835).
    pub fn try_acquire(
        &self,
        database_key: &str,
        holder_id: &str,
        ttl_ms: u64,
    ) -> Result<WriterLease, LeaseError> {
        self.try_acquire_for_term(
            database_key,
            holder_id,
            ttl_ms,
            crate::replication::DEFAULT_REPLICATION_TERM,
        )
    }

    /// Like [`LeaseStore::try_acquire`] but stamps `term` onto the lease
    /// and **fences** any contender whose `term` is behind the published
    /// lease's term (issue #835, ADR 0030).
    ///
    /// The term tie is what makes a deposed primary fail closed: a new
    /// primary that won a higher term takes the lease under that term, so
    /// a returning ex-primary on the old term sees a published lease whose
    /// term is *ahead* of its own and is refused with `LeaseError::Fenced`
    /// — even when the lease has since expired and would otherwise be
    /// poachable. A stale holder can never re-take the writer slot until
    /// it adopts the new term.
    pub fn try_acquire_for_term(
        &self,
        database_key: &str,
        holder_id: &str,
        ttl_ms: u64,
        term: u64,
    ) -> Result<WriterLease, LeaseError> {
        let now_ms = crate::utils::now_unix_millis();

        let current = self.current_versioned(database_key)?;
        // Term fence first — a contender behind the published term is a
        // deposed writer and fails closed regardless of expiry or holder.
        if let Some(c) = &current {
            if term < c.lease.term {
                return Err(LeaseError::Fenced {
                    attempted_holder: holder_id.to_string(),
                    attempted_term: term,
                    current_term: c.lease.term,
                });
            }
        }
        // If a healthy lease exists held by someone else, refuse
        // immediately. Two cases collapse: either the current holder
        // is us (refresh) or it's somebody else with time left.
        let next_generation = match &current {
            Some(c) if !c.lease.is_expired(now_ms) && c.lease.holder_id != holder_id => {
                return Err(LeaseError::Held {
                    current: c.lease.clone(),
                    now_ms,
                });
            }
            Some(c) => c.lease.generation.saturating_add(1),
            None => 1,
        };

        let new_lease = WriterLease {
            database_key: database_key.to_string(),
            holder_id: holder_id.to_string(),
            term,
            generation: next_generation,
            acquired_at_ms: now_ms,
            expires_at_ms: now_ms.saturating_add(ttl_ms),
        };
        let condition = match current {
            Some(c) => ConditionalPut::IfVersion(c.version),
            None => ConditionalPut::IfAbsent,
        };
        if let Err(err) = self.publish_conditional(&new_lease, condition) {
            if matches!(
                err,
                LeaseError::Backend(BackendError::PreconditionFailed(_))
            ) {
                return self.acquire_race_error(database_key, holder_id, now_ms);
            }
            return Err(err);
        }

        // Re-read and verify nobody else won the same gap.
        match self.current(database_key)? {
            Some(observed)
                if observed.holder_id == holder_id
                    && observed.generation == new_lease.generation =>
            {
                Ok(new_lease)
            }
            Some(observed) => Err(LeaseError::LostRace {
                attempted_holder: holder_id.to_string(),
                observed,
            }),
            None => Err(LeaseError::LostRace {
                attempted_holder: holder_id.to_string(),
                observed: WriterLease {
                    database_key: database_key.to_string(),
                    holder_id: "<missing>".to_string(),
                    term: 0,
                    generation: 0,
                    acquired_at_ms: 0,
                    expires_at_ms: 0,
                },
            }),
        }
    }

    fn acquire_race_error(
        &self,
        database_key: &str,
        holder_id: &str,
        now_ms: u64,
    ) -> Result<WriterLease, LeaseError> {
        match self.current(database_key)? {
            Some(observed) if !observed.is_expired(now_ms) && observed.holder_id != holder_id => {
                Err(LeaseError::Held {
                    current: observed,
                    now_ms,
                })
            }
            Some(observed) => Err(LeaseError::LostRace {
                attempted_holder: holder_id.to_string(),
                observed,
            }),
            None => Err(LeaseError::LostRace {
                attempted_holder: holder_id.to_string(),
                observed: WriterLease {
                    database_key: database_key.to_string(),
                    holder_id: "<missing>".to_string(),
                    term: 0,
                    generation: 0,
                    acquired_at_ms: 0,
                    expires_at_ms: 0,
                },
            }),
        }
    }

    /// Refresh `lease.expires_at_ms` to `now + ttl_ms`. Fails with
    /// `Stale` if the holder/generation no longer matches what's
    /// currently published. The returned lease is the new
    /// in-effect record.
    pub fn refresh(&self, lease: &WriterLease, ttl_ms: u64) -> Result<WriterLease, LeaseError> {
        let now_ms = crate::utils::now_unix_millis();
        let observed = self.current_versioned(&lease.database_key)?;
        match observed {
            Some(o)
                if o.lease.holder_id == lease.holder_id
                    && o.lease.generation == lease.generation =>
            {
                let mut next = lease.clone();
                next.expires_at_ms = now_ms.saturating_add(ttl_ms);
                if let Err(err) =
                    self.publish_conditional(&next, ConditionalPut::IfVersion(o.version))
                {
                    if matches!(
                        err,
                        LeaseError::Backend(BackendError::PreconditionFailed(_))
                    ) {
                        return Err(LeaseError::Stale {
                            attempted_holder: lease.holder_id.clone(),
                            attempted_generation: lease.generation,
                            observed: self.current(&lease.database_key)?,
                        });
                    }
                    return Err(err);
                }
                Ok(next)
            }
            other => Err(LeaseError::Stale {
                attempted_holder: lease.holder_id.clone(),
                attempted_generation: lease.generation,
                observed: other.map(|v| v.lease),
            }),
        }
    }

    /// Refresh the lease, but **fail closed** if the holder's term has
    /// fallen behind `current_term` (issue #835). This is the keep-alive
    /// counterpart to the acquire fence: a primary that was deposed while
    /// holding a live lease cannot keep extending it once the cluster has
    /// moved to a newer term — its next refresh is fenced before it ever
    /// touches the backend, so it stops mutating and drains.
    ///
    /// When the holder's own term still matches or leads `current_term`,
    /// this is exactly [`LeaseStore::refresh`].
    pub fn refresh_for_term(
        &self,
        lease: &WriterLease,
        ttl_ms: u64,
        current_term: u64,
    ) -> Result<WriterLease, LeaseError> {
        if lease.fenced_by_term(current_term) {
            return Err(LeaseError::Fenced {
                attempted_holder: lease.holder_id.clone(),
                attempted_term: lease.term,
                current_term,
            });
        }
        self.refresh(lease, ttl_ms)
    }

    /// Release the lease. Only succeeds when the published lease
    /// matches `lease.holder_id + lease.generation`. A stolen or
    /// already-replaced lease returns `Stale`.
    pub fn release(&self, lease: &WriterLease) -> Result<(), LeaseError> {
        let observed = self.current_versioned(&lease.database_key)?;
        match observed {
            Some(o)
                if o.lease.holder_id == lease.holder_id
                    && o.lease.generation == lease.generation =>
            {
                let key = self.key_for(&lease.database_key);
                if let Err(err) = self
                    .backend
                    .delete_conditional(&key, ConditionalDelete::IfVersion(o.version))
                {
                    if matches!(err, BackendError::PreconditionFailed(_)) {
                        return Err(LeaseError::Stale {
                            attempted_holder: lease.holder_id.clone(),
                            attempted_generation: lease.generation,
                            observed: self.current(&lease.database_key)?,
                        });
                    }
                    return Err(err.into());
                }
                Ok(())
            }
            other => Err(LeaseError::Stale {
                attempted_holder: lease.holder_id.clone(),
                attempted_generation: lease.generation,
                observed: other.map(|v| v.lease),
            }),
        }
    }

    fn publish_conditional(
        &self,
        lease: &WriterLease,
        condition: ConditionalPut,
    ) -> Result<BackendObjectVersion, LeaseError> {
        let key = self.key_for(&lease.database_key);
        let json = lease.to_json();
        let bytes = serde_json::to_vec(&json).map_err(|err| {
            LeaseError::Backend(BackendError::Internal(format!("serialize lease: {err}")))
        })?;
        let temp = lease_temp_path("write");
        std::fs::write(&temp, &bytes)
            .map_err(|err| LeaseError::Backend(BackendError::Transport(err.to_string())))?;
        let res = self.backend.upload_conditional(&temp, &key, condition);
        let _ = std::fs::remove_file(&temp);
        Ok(res?)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::storage::backend::LocalBackend;
    use std::path::Path;

    fn store() -> LeaseStore {
        LeaseStore::new(Arc::new(LocalBackend)).with_prefix(format!(
            "{}/leases-test-{}",
            std::env::temp_dir().to_string_lossy(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ))
    }

    #[test]
    fn first_acquire_assigns_generation_one() {
        let s = store();
        let lease = s.try_acquire("db", "writer-a", 60_000).unwrap();
        assert_eq!(lease.generation, 1);
        assert_eq!(lease.holder_id, "writer-a");
    }

    #[test]
    fn second_holder_rejected_while_first_alive() {
        let s = store();
        let _ = s.try_acquire("db", "writer-a", 60_000).unwrap();
        let err = s.try_acquire("db", "writer-b", 60_000).unwrap_err();
        match err {
            LeaseError::Held { current, .. } => {
                assert_eq!(current.holder_id, "writer-a");
                assert_eq!(current.generation, 1);
            }
            other => panic!("expected Held, got {other:?}"),
        }
    }

    #[test]
    fn expired_lease_is_poachable() {
        let s = store();
        let _ = s.try_acquire("db", "writer-a", 1).unwrap();
        std::thread::sleep(std::time::Duration::from_millis(10));
        let lease = s.try_acquire("db", "writer-b", 60_000).unwrap();
        assert_eq!(lease.holder_id, "writer-b");
        assert_eq!(
            lease.generation, 2,
            "generation must increment when poaching"
        );
    }

    #[test]
    fn release_clears_so_anyone_can_take_again() {
        let s = store();
        let lease = s.try_acquire("db", "writer-a", 60_000).unwrap();
        s.release(&lease).unwrap();
        // After release the slot is empty — generation resets to 1
        // because the previous record is gone.
        let next = s.try_acquire("db", "writer-b", 60_000).unwrap();
        assert_eq!(next.holder_id, "writer-b");
        assert_eq!(next.generation, 1);
    }

    #[test]
    fn refresh_extends_expiration_for_same_holder() {
        let s = store();
        let lease = s.try_acquire("db", "writer-a", 1_000).unwrap();
        std::thread::sleep(std::time::Duration::from_millis(20));
        let refreshed = s.refresh(&lease, 60_000).unwrap();
        assert_eq!(refreshed.generation, lease.generation);
        assert!(refreshed.expires_at_ms > lease.expires_at_ms);
    }

    #[test]
    fn refresh_fails_when_someone_else_owns() {
        let s = store();
        let lease = s.try_acquire("db", "writer-a", 1).unwrap();
        std::thread::sleep(std::time::Duration::from_millis(10));
        let _ = s.try_acquire("db", "writer-b", 60_000).unwrap();
        let err = s.refresh(&lease, 60_000).unwrap_err();
        assert!(matches!(err, LeaseError::Stale { .. }));
    }

    #[test]
    fn acquire_stamps_term_onto_lease() {
        let s = store();
        let lease = s.try_acquire_for_term("db", "writer-a", 60_000, 7).unwrap();
        assert_eq!(lease.term, 7);
        assert_eq!(lease.fencing_token(), (7, 1));
    }

    #[test]
    fn legacy_lease_defaults_to_base_term() {
        // A lease acquired through the term-agnostic API carries the base
        // replication term, so it is never fenced until a termed primary
        // re-stamps it.
        let s = store();
        let lease = s.try_acquire("db", "writer-a", 60_000).unwrap();
        assert_eq!(lease.term, crate::replication::DEFAULT_REPLICATION_TERM);
        assert!(!lease.fenced_by_term(crate::replication::DEFAULT_REPLICATION_TERM));
    }

    #[test]
    fn stale_term_contender_is_fenced_even_when_lease_expired() {
        // New primary holds the lease at term 5. The lease then expires,
        // but a returning ex-primary on the old term 4 still cannot poach
        // it — the term fence refuses before expiry is even consulted.
        let s = store();
        let _new_primary = s.try_acquire_for_term("db", "new-primary", 1, 5).unwrap();
        std::thread::sleep(std::time::Duration::from_millis(10));
        let err = s
            .try_acquire_for_term("db", "ex-primary", 60_000, 4)
            .unwrap_err();
        match err {
            LeaseError::Fenced {
                attempted_term,
                current_term,
                ..
            } => {
                assert_eq!(attempted_term, 4);
                assert_eq!(current_term, 5);
            }
            other => panic!("expected Fenced, got {other:?}"),
        }
    }

    #[test]
    fn same_or_higher_term_contender_may_poach_expired_lease() {
        // The fence only bites a *behind* term. A contender at the same or
        // a higher term takes an expired lease normally, and the generation
        // advances with the handover.
        let s = store();
        let _ = s.try_acquire_for_term("db", "old", 1, 5).unwrap();
        std::thread::sleep(std::time::Duration::from_millis(10));
        let lease = s.try_acquire_for_term("db", "new", 60_000, 6).unwrap();
        assert_eq!(lease.holder_id, "new");
        assert_eq!(lease.term, 6);
        assert_eq!(lease.generation, 2, "poaching advances the generation");
    }

    #[test]
    fn refresh_for_term_fails_closed_once_term_advances() {
        // A primary holds a live lease at term 4, then the cluster moves to
        // term 5 underneath it. Its keep-alive refresh is fenced before it
        // touches the backend — the deposed holder stops mutating.
        let s = store();
        let lease = s.try_acquire_for_term("db", "deposed", 60_000, 4).unwrap();
        let err = s.refresh_for_term(&lease, 60_000, 5).unwrap_err();
        match err {
            LeaseError::Fenced {
                attempted_holder,
                attempted_term,
                current_term,
            } => {
                assert_eq!(attempted_holder, "deposed");
                assert_eq!(attempted_term, 4);
                assert_eq!(current_term, 5);
            }
            other => panic!("expected Fenced, got {other:?}"),
        }
    }

    #[test]
    fn refresh_for_term_succeeds_while_term_holds() {
        let s = store();
        let lease = s.try_acquire_for_term("db", "primary", 1_000, 5).unwrap();
        std::thread::sleep(std::time::Duration::from_millis(20));
        let refreshed = s.refresh_for_term(&lease, 60_000, 5).unwrap();
        assert_eq!(refreshed.term, 5);
        assert!(refreshed.expires_at_ms > lease.expires_at_ms);
    }

    // The legacy `acquire_fails_closed_without_backend_conditional_writes`
    // test was deleted with the trait split: `LeaseStore::new` now requires
    // `Arc<dyn AtomicRemoteBackend>`, so a non-CAS backend cannot even be
    // wired into the constructor — the test is enforced at compile time
    // (see tests/lease_atomic_http_opt_in.rs for the runtime-config branch).
}