reddb-io-server 1.45.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
//! Writer-lease boot path with optional serverless snapshot hydration.
//!
//! Boot-time entrypoint that opts the runtime into lease-fenced
//! writes when:
//!   * `RED_LEASE_REQUIRED=true` (or `1`) is set, and
//!   * a remote backend is configured (S3, FS, HTTP, …).
//!
//! All transitions (acquire / refresh / lost / release) are
//! delegated to `LeaseLifecycle`; this module only owns env-var
//! parsing, lifecycle construction, and the refresh thread.
//!
//! The refresh thread uses `LeaseTimerWheel` instead of a fixed
//! `thread::sleep(ttl_ms / 3)` polling loop. The wheel wakes the
//! thread exactly when the next refresh is due and reschedules after
//! each successful refresh, so idle leases cost zero CPU.
//!
//! Env knobs:
//!   * `RED_LEASE_REQUIRED` — `true` / `1` to enable. Default off.
//!   * `RED_LEASE_TTL_SECS` — lease TTL in seconds. Default 60.
//!   * `RED_LEASE_HOLDER_ID` — explicit holder id. Default
//!     `<hostname>-<pid>`.
//!   * `RED_LEASE_PREFIX` — backend prefix for the lease object key.
//!     Default `leases/`.

use std::sync::Arc;
use std::thread;
use std::time::Instant;

use crate::api::{RedDBError, RedDBResult};
use crate::replication::lease::LeaseStore;
use crate::runtime::lease_lifecycle::{ClaimHook, LeaseLifecycle, MarkDraining};
use crate::runtime::lease_timer_wheel::LeaseTimerWheel;
use crate::runtime::serverless_snapshot_publication::SnapshotPublicationStore;
use crate::runtime::serverless_wal_archive::{
    archive_enabled, restore_generation, RestoredStream, ServerlessArchiveConfig,
    ServerlessWalArchive,
};
use crate::runtime::RedDBRuntime;
use crate::storage::unified::store::WalArchiveTap;

pub struct LeaseBootPlan {
    store: Arc<LeaseStore>,
    backend: Arc<dyn crate::storage::backend::AtomicRemoteBackend>,
    snapshot_publication: Option<Arc<SnapshotPublicationStore>>,
    /// Generation restored before the runtime opened (generation heads).
    restored: Option<RestoredStream>,
    holder_id: String,
    database_key: String,
    ttl_ms: u64,
    initial_snapshot_required: bool,
}

/// Observe the exact snapshot head before runtime hydration. The later lease
/// claim CASes that observed version; publication racing with boot therefore
/// aborts this boot instead of letting it serve a stale local snapshot.
pub fn prepare_lease_loop_if_required(
    options: &mut crate::api::RedDBOptions,
) -> RedDBResult<Option<LeaseBootPlan>> {
    if !lease_required() {
        return Ok(None);
    }
    if options.read_only {
        return Err(RedDBError::InvalidOperation(
            "serverless writer leases require a writable local cache".into(),
        ));
    }
    let backend = options.remote_backend_atomic.clone().ok_or_else(|| {
        RedDBError::Internal(
            "RED_LEASE_REQUIRED=true but the configured backend does not support atomic CAS — \
             use s3, fs, or http with RED_HTTP_CONDITIONAL_WRITES=true"
                .to_string(),
        )
    })?;
    let database_key = options
        .remote_key
        .clone()
        .filter(|key| !key.is_empty())
        .filter(|_| options.remote_backend.is_some())
        .ok_or_else(|| {
            RedDBError::InvalidOperation(
                "serverless writer leases require a remote backend and database key".into(),
            )
        })?;
    let prefix = std::env::var("RED_LEASE_PREFIX")
        .ok()
        .filter(|value| !value.trim().is_empty())
        .unwrap_or_else(|| "leases/".to_string());
    // A primary/replica or cluster lease fences ownership of its local store.
    // Only snapshot-backed profiles may replace that store from a remote head.
    let snapshot_publication = match options.storage_profile.deploy_profile {
        crate::storage::DeployProfile::Embedded | crate::storage::DeployProfile::Serverless => {
            Some(Arc::new(SnapshotPublicationStore::new(
                backend.clone(),
                database_key.clone(),
            )))
        }
        crate::storage::DeployProfile::PrimaryReplica | crate::storage::DeployProfile::Cluster => {
            None
        }
    };
    if snapshot_publication.is_some() {
        verify_conditional_writes(
            backend.as_ref(),
            &format!("{prefix}{database_key}.cas-probe"),
        )?;
    }
    options.remote_bootstrap_key = snapshot_publication
        .as_ref()
        .map(|publication| publication.observe_for_boot())
        .transpose()
        .map_err(|err| RedDBError::Internal(err.to_string()))?
        .flatten();
    let generation_head = snapshot_publication
        .as_ref()
        .and_then(|publication| publication.observed_head())
        .filter(|head| head.generation.is_some());
    let mut restored = None;
    if let Some(head) = generation_head {
        if !archive_enabled() {
            return Err(RedDBError::InvalidOperation(
                "the serverless head points at a physical generation; \
                 RED_SERVERLESS_WAL_ARCHIVE=false cannot hydrate it"
                    .into(),
            ));
        }
        // Rebuild the generation and its archived WAL in an isolated cache;
        // normal crash recovery replays the WAL when the runtime opens it.
        let cache = crate::api::RedDBOptions::temporary();
        let dir = cache
            .data_path
            .as_deref()
            .and_then(std::path::Path::parent)
            .ok_or_else(|| RedDBError::Internal("temporary cache has no directory".into()))?
            .to_path_buf();
        let stream = restore_generation(backend.as_ref(), &head, &dir).map_err(|err| {
            RedDBError::Internal(format!("serverless generation restore failed: {err}"))
        })?;
        tracing::info!(
            target: "reddb::serverless::archive",
            generation_wal_lsn = stream.generation_wal_lsn,
            restored_lsn = stream.last_lsn,
            segments = stream.segments_replayed,
            frames = stream.frames_replayed,
            bytes = stream.bytes_downloaded,
            duration_ms = stream.duration.as_millis() as u64,
            "serverless generation restored"
        );
        options.data_path = Some(stream.data_path.clone());
        options.metadata.insert(
            crate::api::EPHEMERAL_RUNTIME_METADATA_KEY.into(),
            "true".into(),
        );
        options.remote_bootstrap_key = None;
        restored = Some(stream);
    } else if options.remote_bootstrap_key.is_some()
        && options.storage_profile.deploy_profile != crate::storage::DeployProfile::Embedded
    {
        // Operational caches have WAL and metadata siblings. Hydrate into an
        // isolated boot directory so an old local WAL cannot replay over the
        // authoritative snapshot. Reuse the existing ephemeral cleanup owner.
        let cache = crate::api::RedDBOptions::in_memory();
        options.data_path = cache.data_path;
        options.metadata.insert(
            crate::api::EPHEMERAL_RUNTIME_METADATA_KEY.into(),
            "true".into(),
        );
    }
    let initial_snapshot_required = snapshot_publication.is_some()
        && options.remote_bootstrap_key.is_none()
        && restored.is_none();
    Ok(Some(LeaseBootPlan {
        store: Arc::new(LeaseStore::new(backend.clone()).with_prefix(prefix)),
        backend,
        snapshot_publication,
        restored,
        holder_id: lease_holder_id(),
        database_key,
        ttl_ms: lease_ttl_secs() * 1000,
        initial_snapshot_required,
    }))
}

/// Try to start the writer-lease lifecycle if the operator opted in.
/// Returns `Ok(())` when:
///   * `RED_LEASE_REQUIRED` is unset / false, or
///   * the lease was acquired and the refresh thread is running.
///
/// Returns `Err` when the operator asked for a lease and we couldn't
/// get one — the caller should refuse to serve in that case.
pub fn start_lease_loop_if_required(runtime: &RedDBRuntime) -> RedDBResult<()> {
    let mut options = runtime.db().options().clone();
    let plan = prepare_lease_loop_if_required(&mut options)?;
    if options.remote_bootstrap_key.is_some()
        || plan.as_ref().is_some_and(|plan| plan.restored.is_some())
    {
        return Err(RedDBError::InvalidOperation(
            "serverless snapshot head must be observed before runtime hydration; use the prepared lease boot path"
                .to_string(),
        ));
    }
    start_prepared_lease_loop(runtime, plan)
}

pub fn start_prepared_lease_loop(
    runtime: &RedDBRuntime,
    plan: Option<LeaseBootPlan>,
) -> RedDBResult<()> {
    let Some(plan) = plan else {
        return Ok(());
    };
    // Paged stores publish physical generations plus the archived WAL. A
    // restored generation head always continues in that mode.
    if plan.snapshot_publication.is_some()
        && (plan.restored.is_some() || (archive_enabled() && runtime.db().is_paged()))
    {
        return start_generation_lease_loop(runtime, plan);
    }
    // Existing heads are claimed without re-uploading or re-checkpointing the
    // hydrated database. Only migration to the first head needs a payload.
    let local_snapshot = if plan.initial_snapshot_required {
        Some(runtime.capture_serverless_snapshot()?)
    } else {
        None
    };
    let runtime_for_drain = Arc::downgrade(&runtime.inner);
    let mark_draining: MarkDraining = Arc::new(move || {
        if let Some(inner) = runtime_for_drain.upgrade() {
            inner.lifecycle.mark_draining();
        }
    });
    let term = runtime.current_replication_term();
    let current_term = Arc::new(move || term);
    let mut lifecycle = LeaseLifecycle::new(
        plan.store,
        runtime.write_gate_arc(),
        runtime.audit_log_arc(),
        mark_draining,
        current_term,
        plan.holder_id,
        plan.database_key,
        plan.ttl_ms,
    );
    if let Some(publication) = plan.snapshot_publication {
        let database = runtime.db();
        let snapshot_path = local_snapshot
            .as_ref()
            .map(|snapshot| snapshot.path())
            .or_else(|| database.path())
            .ok_or_else(|| {
                RedDBError::InvalidOperation(
                    "serverless boot requires a persistent local cache".into(),
                )
            })?;
        lifecycle = lifecycle.with_snapshot_publication(publication, snapshot_path);
    }
    let lifecycle = Arc::new(lifecycle);
    lifecycle.try_acquire()?;

    // Stash the lifecycle on the runtime so admin handlers and the
    // refresh thread share one instance. The OnceLock guarantees
    // idempotency — re-entering the boot path (tests, double-init)
    // returns Err and we drop the duplicate.
    let lifecycle_for_runtime = Arc::clone(&lifecycle);
    let _ = runtime.set_lease_lifecycle(lifecycle_for_runtime);

    spawn_refresh_thread(runtime.clone(), lifecycle);
    Ok(())
}

/// Generation mode: attach the WAL archive tap before any write is admitted,
/// publish the first generation when the head has none, claim the head with
/// this boot's stream epoch, then start the archive and refresh loops.
fn start_generation_lease_loop(runtime: &RedDBRuntime, plan: LeaseBootPlan) -> RedDBResult<()> {
    let publication = plan
        .snapshot_publication
        .clone()
        .ok_or_else(|| RedDBError::Internal("generation mode needs a publication store".into()))?;
    let epoch = publication
        .next_claim_epoch()
        .map_err(|err| RedDBError::Internal(err.to_string()))?;
    let (start_lsn, prev_sha) = plan
        .restored
        .as_ref()
        .map(|restored| (restored.last_lsn + 1, restored.last_sha256))
        .unwrap_or((1, None));
    let config = ServerlessArchiveConfig::from_env();
    let tap = Arc::new(WalArchiveTap::new(
        epoch,
        start_lsn,
        prev_sha,
        config.max_segment_bytes,
    ));
    runtime
        .db()
        .store()
        .attach_wal_archive_tap(Arc::clone(&tap))
        .map_err(|err| RedDBError::Internal(format!("attach WAL archive: {err}")))?;
    let archive = Arc::new(ServerlessWalArchive::new(
        Arc::clone(&plan.backend),
        Arc::clone(&publication),
        tap,
        epoch,
        config,
        plan.restored.as_ref(),
    ));
    // A head without a generation (first boot, or a single-file head being
    // migrated) gets one before the claim. It is uploaded before the lease
    // is taken so no object-store transfer runs under the lease lock.
    let initial = if plan.restored.is_none() {
        Some(
            archive
                .stage_and_upload_generation(runtime, epoch, false)?
                .0,
        )
    } else {
        None
    };
    // The restore listed the previous writer's segments before this node
    // held the lease. A writer that flushed more WAL and then released the
    // lease (graceful sleep whose final generation failed) would have those
    // segments ignored forever once this claim starts the stream at
    // `start_lsn`. Re-list under the lease and refuse to claim over them;
    // the next boot restores them.
    let previous_epoch = plan
        .restored
        .as_ref()
        .and_then(|_| publication.observed_head())
        .and_then(|head| head.generation)
        .and_then(|generation| generation.wal_epochs.last().map(|claim| claim.epoch));
    let claim_backend = Arc::clone(&plan.backend);
    let claim_database = plan.database_key.clone();
    let claim_publication = Arc::clone(&publication);
    let claim: ClaimHook = Arc::new(move |lease| {
        if let Some(epoch) = previous_epoch {
            let prefix = reddb_file::serverless_wal_epoch_prefix(&claim_database, epoch);
            let late = claim_backend
                .list(&prefix)
                .map_err(|err| format!("re-list {prefix} before claiming: {err}"))?
                .into_iter()
                .filter_map(|key| reddb_file::parse_serverless_wal_segment_key(&key))
                .filter(|(segment_epoch, _, last)| *segment_epoch == epoch && *last >= start_lsn)
                .map(|(_, _, last)| last)
                .max();
            if let Some(last) = late {
                return Err(format!(
                    "the previous writer archived WAL through stream LSN {last} after this boot \
                     restored through {}; restart to restore it",
                    start_lsn.saturating_sub(1)
                ));
            }
        }
        claim_publication
            .claim_generation_stream(lease, start_lsn, initial.as_ref())
            .map(|_| ())
            .map_err(|err| err.to_string())
    });
    let runtime_for_drain = Arc::downgrade(&runtime.inner);
    let mark_draining: MarkDraining = Arc::new(move || {
        if let Some(inner) = runtime_for_drain.upgrade() {
            inner.lifecycle.mark_draining();
        }
    });
    let term = runtime.current_replication_term();
    let lifecycle = Arc::new(
        LeaseLifecycle::new(
            plan.store,
            runtime.write_gate_arc(),
            runtime.audit_log_arc(),
            mark_draining,
            Arc::new(move || term),
            plan.holder_id,
            plan.database_key,
            plan.ttl_ms,
        )
        .with_claim_hook(claim),
    );
    lifecycle.try_acquire()?;
    archive.attach_lease(Arc::clone(&lifecycle));
    let _ = runtime.set_lease_lifecycle(Arc::clone(&lifecycle));
    runtime.set_serverless_wal_archive(Arc::clone(&archive));
    archive.spawn(runtime.clone());
    spawn_refresh_thread(runtime.clone(), lifecycle);
    Ok(())
}

fn spawn_refresh_thread(runtime: RedDBRuntime, lifecycle: Arc<LeaseLifecycle>) {
    // Timer wheel replaces thread::sleep(interval) — wakes exactly when the
    // next refresh is due. Zero CPU during the idle window.
    let wheel = Arc::new(LeaseTimerWheel::new(1));
    wheel.schedule(
        "lease-refresh".to_string(),
        Instant::now() + lifecycle.refresh_delay(),
    );

    let wheel_for_handler = Arc::clone(&wheel);
    let _ = thread::Builder::new()
        .name("reddb-lease-refresh".into())
        .spawn(move || {
            wheel.run_until_shutdown(move |_id| {
                // Keep the lease through drain and final publication. Shutdown
                // releases it only after the last snapshot; a lease-loss path
                // terminates below when refresh fails.
                let phase = runtime.lifecycle().phase();
                if phase == crate::runtime::lifecycle::Phase::Stopped {
                    let _ = lifecycle.release();
                    return false;
                }

                if lifecycle.refresh().is_err() {
                    return false;
                }

                // Reschedule the next refresh.
                wheel_for_handler.schedule(
                    "lease-refresh".to_string(),
                    Instant::now() + lifecycle.refresh_delay(),
                );
                true
            });
        });
}

/// Boot self-test for lease mode: the backend must refuse a PUT whose
/// `If-Match` names a superseded version, and a create-only PUT on an
/// existing key. A backend that silently ignores the precondition (OCI's
/// S3-compatible API does) lets every writer win and cannot fence a lease,
/// so startup fails instead of running unfenced.
pub fn verify_conditional_writes(
    backend: &dyn crate::storage::backend::AtomicRemoteBackend,
    probe_key: &str,
) -> RedDBResult<()> {
    // Transport hiccups are retried; a backend that accepts a stale
    // precondition fails at once. The sentinel is removed either way.
    let mut result = probe_conditional_writes(backend, probe_key);
    for attempt in 1..=2u64 {
        match &result {
            Err(RedDBError::Internal(_)) => {
                std::thread::sleep(std::time::Duration::from_millis(250 * attempt));
                result = probe_conditional_writes(backend, probe_key);
            }
            _ => break,
        }
    }
    let _ = backend.delete(probe_key);
    result
}

fn probe_conditional_writes(
    backend: &dyn crate::storage::backend::AtomicRemoteBackend,
    probe_key: &str,
) -> RedDBResult<()> {
    use crate::storage::backend::{BackendError, ConditionalPut};
    let internal = |err: BackendError| {
        RedDBError::Internal(format!("conditional-write self-test on {probe_key}: {err}"))
    };
    let probe = reddb_file::ServerlessWriterLeaseTempFile::new("cas-probe");
    let write = |tag: &str| {
        probe
            .write_bytes(format!("{tag}-{}", crate::utils::now_unix_nanos()).as_bytes())
            .map_err(|err| RedDBError::Internal(err.to_string()))
    };
    // A concurrent boot may advance the sentinel between our reads; retry.
    for _ in 0..3 {
        write("base")?;
        let base =
            match backend.upload_conditional(probe.path(), probe_key, ConditionalPut::IfAbsent) {
                Ok(version) => version,
                Err(BackendError::PreconditionFailed(_)) => {
                    match backend.object_version(probe_key).map_err(internal)? {
                        Some(version) => version,
                        None => continue,
                    }
                }
                Err(err) => return Err(internal(err)),
            };
        write("next")?;
        match backend.upload_conditional(
            probe.path(),
            probe_key,
            ConditionalPut::IfVersion(base.clone()),
        ) {
            Ok(_) => {}
            Err(BackendError::PreconditionFailed(_)) => continue,
            Err(err) => return Err(internal(err)),
        }
        write("stale")?;
        let stale =
            backend.upload_conditional(probe.path(), probe_key, ConditionalPut::IfVersion(base));
        let duplicate =
            backend.upload_conditional(probe.path(), probe_key, ConditionalPut::IfAbsent);
        let refused = |result: &Result<_, BackendError>| {
            matches!(result, Err(BackendError::PreconditionFailed(_)))
        };
        if refused(&stale) && refused(&duplicate) {
            return Ok(());
        }
        if stale.is_ok() || duplicate.is_ok() {
            return Err(RedDBError::InvalidOperation(format!(
                "RED_LEASE_REQUIRED=true but the remote backend accepted a write whose \
                 precondition no longer held ({probe_key}); it does not enforce If-Match / \
                 If-None-Match and cannot fence a writer lease"
            )));
        }
        // Both failed and at least one failure was not a 412.
        return Err([stale.err(), duplicate.err()]
            .into_iter()
            .flatten()
            .find(|err| !matches!(err, BackendError::PreconditionFailed(_)))
            .map_or_else(
                || {
                    RedDBError::Internal(format!(
                        "conditional-write self-test on {probe_key} failed"
                    ))
                },
                internal,
            ));
    }
    Err(RedDBError::Internal(format!(
        "conditional-write self-test on {probe_key} kept racing another boot"
    )))
}

fn lease_required() -> bool {
    std::env::var("RED_LEASE_REQUIRED")
        .ok()
        .map(|v| {
            let t = v.trim();
            t.eq_ignore_ascii_case("true") || t == "1" || t.eq_ignore_ascii_case("yes")
        })
        .unwrap_or(false)
}

fn lease_ttl_secs() -> u64 {
    std::env::var("RED_LEASE_TTL_SECS")
        .ok()
        .and_then(|s| s.trim().parse::<u64>().ok())
        .filter(|v| *v > 0)
        .unwrap_or(60)
}

fn lease_holder_id() -> String {
    if let Some(explicit) = crate::utils::env_with_file_fallback("RED_LEASE_HOLDER_ID") {
        return explicit;
    }
    let host = std::env::var("HOSTNAME")
        .or_else(|_| std::env::var("HOST"))
        .unwrap_or_else(|_| "unknown-host".to_string());
    format!("{}-{}", host, std::process::id())
}

#[cfg(test)]
mod tests {
    use super::*;

    use crate::storage::backend::{AtomicRemoteBackend as _, RemoteBackend as _};

    /// An S3-compatible API that accepts every conditional write (as OCI's
    /// does) must fail the boot self-test.
    struct IgnoresPreconditions(crate::storage::backend::LocalBackend);

    impl crate::storage::backend::RemoteBackend for IgnoresPreconditions {
        fn name(&self) -> &str {
            "ignores-preconditions"
        }
        fn download(
            &self,
            key: &str,
            path: &std::path::Path,
        ) -> Result<bool, crate::storage::backend::BackendError> {
            self.0.download(key, path)
        }
        fn upload(
            &self,
            path: &std::path::Path,
            key: &str,
        ) -> Result<(), crate::storage::backend::BackendError> {
            self.0.upload(path, key)
        }
        fn exists(&self, key: &str) -> Result<bool, crate::storage::backend::BackendError> {
            self.0.exists(key)
        }
        fn delete(&self, key: &str) -> Result<(), crate::storage::backend::BackendError> {
            self.0.delete(key)
        }
        fn list(&self, prefix: &str) -> Result<Vec<String>, crate::storage::backend::BackendError> {
            self.0.list(prefix)
        }
    }

    impl crate::storage::backend::AtomicRemoteBackend for IgnoresPreconditions {
        fn object_version(
            &self,
            key: &str,
        ) -> Result<
            Option<crate::storage::backend::BackendObjectVersion>,
            crate::storage::backend::BackendError,
        > {
            self.0.object_version(key)
        }
        fn upload_conditional(
            &self,
            path: &std::path::Path,
            key: &str,
            _condition: crate::storage::backend::ConditionalPut,
        ) -> Result<
            crate::storage::backend::BackendObjectVersion,
            crate::storage::backend::BackendError,
        > {
            self.0.upload(path, key)?;
            Ok(self.0.object_version(key)?.expect("object just written"))
        }
        fn delete_conditional(
            &self,
            key: &str,
            _condition: crate::storage::backend::ConditionalDelete,
        ) -> Result<(), crate::storage::backend::BackendError> {
            self.0.delete(key)
        }
    }

    #[test]
    fn conditional_write_self_test_accepts_cas_and_rejects_ignored_preconditions() {
        let root = tempfile::tempdir().unwrap();
        let key = root.path().join("leases/db.cas-probe");
        let key = key.to_string_lossy();
        verify_conditional_writes(&crate::storage::backend::LocalBackend, &key)
            .expect("a CAS backend passes, on first boot and again later");
        verify_conditional_writes(&crate::storage::backend::LocalBackend, &key)
            .expect("an existing sentinel is reused");
        let ignoring = IgnoresPreconditions(crate::storage::backend::LocalBackend);
        let err = verify_conditional_writes(&ignoring, &key).expect_err("must refuse");
        assert!(err.to_string().contains("cannot fence"), "{err}");
    }

    #[test]
    fn lease_required_parses_truthy_values() {
        unsafe {
            std::env::set_var("RED_LEASE_REQUIRED", "true");
        }
        assert!(lease_required());
        unsafe {
            std::env::set_var("RED_LEASE_REQUIRED", "1");
        }
        assert!(lease_required());
        unsafe {
            std::env::set_var("RED_LEASE_REQUIRED", "yes");
        }
        assert!(lease_required());
        unsafe {
            std::env::set_var("RED_LEASE_REQUIRED", "false");
        }
        assert!(!lease_required());
        unsafe {
            std::env::remove_var("RED_LEASE_REQUIRED");
        }
        assert!(!lease_required());
    }

    #[test]
    fn ttl_defaults_to_60_when_unset() {
        unsafe {
            std::env::remove_var("RED_LEASE_TTL_SECS");
        }
        assert_eq!(lease_ttl_secs(), 60);
    }

    #[test]
    fn ttl_rejects_zero_and_negative() {
        unsafe {
            std::env::set_var("RED_LEASE_TTL_SECS", "0");
        }
        assert_eq!(lease_ttl_secs(), 60);
        unsafe {
            std::env::set_var("RED_LEASE_TTL_SECS", "abc");
        }
        assert_eq!(lease_ttl_secs(), 60);
        unsafe {
            std::env::set_var("RED_LEASE_TTL_SECS", "30");
        }
        assert_eq!(lease_ttl_secs(), 30);
        unsafe {
            std::env::remove_var("RED_LEASE_TTL_SECS");
        }
    }

    #[test]
    fn holder_id_falls_back_when_no_env() {
        unsafe {
            std::env::remove_var("RED_LEASE_HOLDER_ID");
        }
        let id = lease_holder_id();
        assert!(id.contains('-'));
        assert!(!id.is_empty());
    }

    #[test]
    fn holder_id_uses_explicit_when_set() {
        unsafe {
            std::env::set_var("RED_LEASE_HOLDER_ID", "explicit-writer-1");
        }
        assert_eq!(lease_holder_id(), "explicit-writer-1");
        unsafe {
            std::env::remove_var("RED_LEASE_HOLDER_ID");
        }
    }
}