rings-node 1.0.0-pre.5

Rings is a browser-native, structured peer-to-peer network: browser tabs and native daemons find each other by DID and talk over WebRTC, routed by a Chord DHT.
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
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
//! Runtime adapter for the pure `rings-measure` state relation.

use std::convert::Infallible;
use std::num::NonZeroU64;
use std::num::NonZeroUsize;
use std::sync::Arc;
use std::sync::Mutex;
use std::time::Duration;

use async_trait::async_trait;
use futures::channel::mpsc;
use futures::channel::oneshot;
use futures::lock::Mutex as AsyncMutex;
use futures::FutureExt;
use futures::StreamExt;
use rings_core::dht::Did;
use rings_core::measure;
use rings_core::measure::Measure;
use rings_core::measure::PeerMeasurement;
use rings_core::measure::PeerMeasurementPage;
use rings_core::measure::PeerQuality;
use rings_core::measure::PeerQualityThresholds;
use rings_core::storage::KvStorageInterface;
use rings_core::utils::SharedClock;
use rings_core::utils::SystemClock;
use rings_measure::ApplyOutcome;
use rings_measure::Authentication;
use rings_measure::CreditPolicy;
use rings_measure::EvidenceAdmissionReport;
use rings_measure::EvidenceCounters;
use rings_measure::EvidenceDigest;
use rings_measure::EvidenceError;
use rings_measure::EvidenceLimits;
use rings_measure::EvidencePage;
use rings_measure::EvidenceReplayMarker;
use rings_measure::EvidenceSnapshot;
use rings_measure::MeasureError;
use rings_measure::MeasurementBatch;
use rings_measure::MeasurementEvent;
use rings_measure::MeasurementLedger;
use rings_measure::MeasurementSnapshot;
use rings_measure::ProvisionalEvidenceRecord;
use rings_measure::ProvisionalEvidenceStore;
use rings_measure::ReliabilityPolicy;
use rings_measure::UnixTime;
use rings_runtime::sleep;
use rings_runtime::Abandoned;
use rings_runtime::RuntimeUnavailable;
use rings_runtime::Spawner;
use rings_runtime::TaskSet;
use rings_runtime::TimerError;

// Legacy `PeriodicMeasure/counters/...` values intentionally remain unread:
// a bare count proves neither byte-credit direction nor a live epoch timestamp.
const SNAPSHOT_KEY: &str = "MeasurementLedger";
const EVIDENCE_SNAPSHOT_KEY: &str = "ProvisionalEvidence";
const PERSISTENCE_WAKE_CAPACITY: usize = 1;
const PERSISTENCE_SHUTDOWN_ATTEMPTS: usize = 3;
const PRUNE_INTERVAL_SECONDS: u64 = 60 * 60;
#[cfg(test)]
const PERSISTENCE_MIN_INTERVAL: Duration = Duration::from_millis(50);
// Measurement-ledger mutations are coalesced over this interval. Provisional
// evidence admission uses the same serialization lock but commits separately
// before returning success.
#[cfg(not(test))]
const PERSISTENCE_MIN_INTERVAL: Duration = Duration::from_secs(60);
// One window for tests and production. Controlled-clock unit tests advance the clock by
// `RELIABILITY_WINDOW` to drive epoch rollover deterministically, so they need no shorter
// window. A sub-second test window instead broke wall-clock integration tests: reliability
// evidence is windowed (reset when a fresh observation lands in a later epoch) while credit
// is cumulative, so under live keepalive traffic an epoch boundary between a send and a
// later read could reset `evidence.sent` to 0 even though credit had grown — a flaky
// `evidence.sent >= 1`. A production-sized window is never crossed within a test.
#[allow(
    clippy::unwrap_used,
    reason = "the non-zero integer literal is validated during const evaluation"
)]
const RELIABILITY_WINDOW: NonZeroU64 = NonZeroU64::new(3_600).unwrap();

/// Shared peer-quality thresholds used by measurement and route selection.
pub(crate) const fn peer_quality_thresholds() -> PeerQualityThresholds {
    PeerQualityThresholds::new(
        crate::consts::CONNECT_FAILED_LIMIT,
        crate::consts::MSG_SEND_FAILED_LIMIT,
        crate::consts::MSG_RECV_FAILED_LIMIT,
    )
}

const fn reliability_policy() -> ReliabilityPolicy {
    ReliabilityPolicy::from_nonzero_window(RELIABILITY_WINDOW, 1, peer_quality_thresholds())
}

/// Storage used for one versioned complete measurement snapshot.
pub type MeasureStorage =
    Box<rings_runtime::maybe_send_sync!(dyn KvStorageInterface<MeasurementSnapshot<Did>>)>;

/// Storage used for the separate provisional-receipt evidence snapshot.
pub type EvidenceStorage =
    Box<rings_runtime::maybe_send_sync!(dyn KvStorageInterface<EvidenceSnapshot<Did>>)>;

/// Evidence backend used when a provider did not configure durable receipt storage.
///
/// Reads expose an empty initial state so measurement-only runtimes can start, but every write
/// fails. Consequently the admission adapter rolls back and never returns `Admitted` under a
/// process-local store that cannot refine the crash-recovery model.
pub(crate) struct UnavailableEvidenceStorage;

#[cfg_attr(all(feature = "browser", target_family = "wasm"), async_trait(?Send))]
#[cfg_attr(not(all(feature = "browser", target_family = "wasm")), async_trait)]
impl KvStorageInterface<EvidenceSnapshot<Did>> for UnavailableEvidenceStorage {
    async fn get(&self, _key: &str) -> rings_core::error::Result<Option<EvidenceSnapshot<Did>>> {
        Ok(None)
    }

    async fn put(
        &self,
        _key: &str,
        value: &EvidenceSnapshot<Did>,
    ) -> rings_core::error::Result<()> {
        if value.records.is_empty()
            && value.replay_markers.is_empty()
            && value.replay_floor == 0
            && value.counters == EvidenceCounters::default()
        {
            return Ok(());
        }
        Err(EvidenceError::StorageUnavailable.into())
    }

    async fn get_all(&self) -> rings_core::error::Result<Vec<(String, EvidenceSnapshot<Did>)>> {
        Ok(Vec::new())
    }

    async fn remove(&self, _key: &str) -> rings_core::error::Result<()> {
        Ok(())
    }

    async fn clear(&self) -> rings_core::error::Result<()> {
        Ok(())
    }

    async fn count(&self) -> rings_core::error::Result<u32> {
        Ok(0)
    }
}

/// Runtime identity that owns one persisted provisional-evidence collection.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct EvidenceCollectorIdentity {
    network_id: u32,
    provider_account: Did,
}

impl EvidenceCollectorIdentity {
    /// Bind persisted evidence to one overlay and the local provider account.
    pub const fn new(network_id: u32, provider_account: Did) -> Self {
        Self {
            network_id,
            provider_account,
        }
    }
}

type SharedMeasureStorage =
    Arc<rings_runtime::maybe_send_sync!(dyn KvStorageInterface<MeasurementSnapshot<Did>>)>;

type SharedEvidenceStorage =
    Arc<rings_runtime::maybe_send_sync!(dyn KvStorageInterface<EvidenceSnapshot<Did>>)>;

/// Failure while loading or explicitly flushing the runtime measurement adapter.
#[derive(Debug, thiserror::Error)]
pub enum MeasureRuntimeError {
    /// The configured key-value backend failed.
    #[error("measurement storage failed: {0}")]
    Storage(#[from] rings_core::error::Error),
    /// Persisted or live state violated the pure measurement model.
    #[error("measurement model failed: {0}")]
    Model(#[from] MeasureError),
    /// Persisted or live provisional evidence violated its bounded model.
    #[error("provisional evidence model failed: {0}")]
    Evidence(#[from] EvidenceError),
    /// A bounded explicit flush did not complete before its deadline.
    #[error("measurement persistence flush timed out")]
    FlushTimeout,
    /// The runtime stopped the owned flush task before it returned a result.
    #[error("measurement persistence flush task stopped")]
    FlushTaskStopped,
    /// The browser could not schedule a measurement timer.
    #[error("measurement timer failed: {0}")]
    Timer(#[from] TimerError),
    /// Native construction was attempted without a live Tokio runtime.
    #[error("measurement persistence requires a live runtime: {0}")]
    RuntimeUnavailable(#[from] RuntimeUnavailable),
}

/// Pure-ledger runtime adapter with durable evidence admission and coalesced measurement snapshots.
///
/// Measurement callbacks update in-memory state and replace the pending full
/// snapshot. Receipt admission commits its evidence snapshot before success.
/// One runtime lock serializes both write paths. The algorithm, time projection,
/// pruning, and snapshot schemas remain in `rings-measure`.
pub struct PeriodicMeasure {
    state: Arc<MeasureState>,
    persistence_wake: mpsc::Sender<()>,
    /// Resolves once the state, with its stores, is dropped (see `MeasureState::_released`).
    released: oneshot::Receiver<Infallible>,
}

struct MeasureState {
    storage: SharedMeasureStorage,
    evidence_storage: SharedEvidenceStorage,
    /// Synchronous in-memory ledger and evidence state (`Law (Lock order): persistence_lock ≺ runtime`,
    /// `runtime` is a leaf never held across `.await`).
    runtime: Mutex<RuntimeLedger>,
    /// Serializes durable snapshot writes (`Law (Lock order): persistence_lock ≺ runtime`).
    persistence_lock: AsyncMutex<()>,
    clock: Arc<dyn MeasureClock>,
    /// The executor captured at construction, which owns persistence and flush work.
    spawner: Spawner,
    /// The measurement's own tasks, its persistence worker and flushes, spawned on `spawner`.
    /// Not the node's tasks: they run until the measurement's owner drops it, after the node's
    /// tasks have drained, and a close awaits them through its stores' release (#1085).
    tasks: TaskSet,
    /// Never sent on, only dropped: fields drop in declaration order, so this one drops after
    /// both stores, and its receiver's `Canceled` is the event that the stores are released.
    _released: oneshot::Sender<Infallible>,
}

impl MeasureState {
    /// Serialize clock sampling with the ledger transition it timestamps.
    fn runtime_at_now(&self) -> (std::sync::MutexGuard<'_, RuntimeLedger>, UnixTime) {
        let runtime = lock_or_recover(&self.runtime);
        let now = self.clock.now();
        (runtime, now)
    }
}

struct RuntimeLedger {
    ledger: MeasurementLedger<Did>,
    evidence: ProvisionalEvidenceStore<Did>,
    /// Last durable view while an admission write is in flight, so read-only evidence queries
    /// need only the synchronous `runtime` lock without observing uncommitted state.
    committed_evidence_override: Option<ProvisionalEvidenceStore<Did>>,
    dirty: bool,
    persisting: bool,
    mutated_while_persisting: bool,
    last_clock: UnixTime,
    next_prune_at: UnixTime,
}

impl RuntimeLedger {
    fn committed_evidence(&self) -> &ProvisionalEvidenceStore<Did> {
        self.committed_evidence_override
            .as_ref()
            .unwrap_or(&self.evidence)
    }
}

// Boundary: the adapter supplies wall-clock seconds to the pure state relation.
trait MeasureClock: Send + Sync {
    fn now(&self) -> UnixTime;
}

struct SharedMeasureClock(SharedClock);

impl MeasureClock for SharedMeasureClock {
    fn now(&self) -> UnixTime {
        let seconds = u64::try_from(self.0.now_ms() / 1_000).unwrap_or(u64::MAX);
        UnixTime::from_secs(seconds)
    }
}

impl PeriodicMeasure {
    /// Load the complete ledger once and start the coalescing persistence task.
    ///
    /// On native targets this captures the active Tokio runtime handle. The
    /// constructor returns `MeasureRuntimeError::RuntimeUnavailable` instead
    /// of panicking when called outside a live runtime.
    /// Provisional receipt admission is disabled; use [`Self::new_with_evidence_storage`]
    /// when successful receipt admission must survive process restart.
    pub async fn new(storage: MeasureStorage) -> Result<Self, MeasureRuntimeError> {
        Self::new_with_clock_and_evidence(
            storage,
            Box::new(UnavailableEvidenceStorage),
            None,
            Arc::new(SharedMeasureClock(Arc::new(SystemClock))),
        )
        .await
    }

    /// Load snapshots and bind restored evidence to this local collector.
    ///
    /// Pre: `evidence_storage` preserves a successful `put` across process restart. A volatile
    /// test backend is valid for bounded tests, but does not satisfy the crash-recovery claim.
    pub async fn new_with_evidence_storage(
        storage: MeasureStorage,
        evidence_storage: EvidenceStorage,
        collector: EvidenceCollectorIdentity,
    ) -> Result<Self, MeasureRuntimeError> {
        Self::new_with_evidence_storage_and_clock(
            storage,
            evidence_storage,
            collector,
            Arc::new(SystemClock),
        )
        .await
    }

    /// [`Self::new_with_evidence_storage`] reading epoch timestamps from `clock`.
    pub async fn new_with_evidence_storage_and_clock(
        storage: MeasureStorage,
        evidence_storage: EvidenceStorage,
        collector: EvidenceCollectorIdentity,
        clock: SharedClock,
    ) -> Result<Self, MeasureRuntimeError> {
        Self::new_with_clock_and_evidence(
            storage,
            evidence_storage,
            Some(collector),
            Arc::new(SharedMeasureClock(clock)),
        )
        .await
    }

    #[cfg(all(test, feature = "node"))]
    async fn new_with_clock(
        storage: MeasureStorage,
        clock: Arc<dyn MeasureClock>,
    ) -> Result<Self, MeasureRuntimeError> {
        Self::new_with_clock_and_evidence(
            storage,
            Box::new(rings_core::storage::MemStorage::new()),
            None,
            clock,
        )
        .await
    }

    async fn new_with_clock_and_evidence(
        storage: MeasureStorage,
        evidence_storage: EvidenceStorage,
        collector: Option<EvidenceCollectorIdentity>,
        clock: Arc<dyn MeasureClock>,
    ) -> Result<Self, MeasureRuntimeError> {
        let spawner = Spawner::current()?;
        let storage = SharedMeasureStorage::from(storage);
        let evidence_storage = SharedEvidenceStorage::from(evidence_storage);
        let mut ledger = match storage.get(SNAPSHOT_KEY).await? {
            Some(snapshot) => MeasurementLedger::from_snapshot(snapshot)?,
            None => MeasurementLedger::new(),
        };
        let now = clock.now();
        let (evidence, evidence_load) = match evidence_storage.get(EVIDENCE_SNAPSHOT_KEY).await? {
            Some(snapshot) => ProvisionalEvidenceStore::from_snapshot_with_validator(
                snapshot,
                EvidenceLimits::default(),
                |record| {
                    collector.is_some_and(|identity| valid_persisted_evidence(record, identity))
                },
                |marker| {
                    collector
                        .is_some_and(|identity| valid_persisted_replay_marker(marker, identity))
                },
            )?,
            None => (
                ProvisionalEvidenceStore::new(EvidenceLimits::default()),
                rings_measure::EvidenceLoadReport::default(),
            ),
        };
        if evidence_load.rejected_records() > 0
            || evidence_load.evicted_records() > 0
            || evidence_load.rejected_replay_markers() > 0
        {
            tracing::warn!(
                rejected_records = evidence_load.rejected_records(),
                evicted_records = evidence_load.evicted_records(),
                rejected_replay_markers = evidence_load.rejected_replay_markers(),
                "reconciled provisional evidence during startup"
            );
        }
        let reconciliation = ledger.reconcile_runtime(now, reliability_policy());
        if reconciliation.is_adjusted() {
            tracing::warn!(
                clock_adjusted_records = reconciliation.clock_adjusted_records(),
                reliability_reset_records = reconciliation.reliability_reset_records(),
                "reconciled measurement state during startup"
            );
        }
        let pruning = ledger.prune(now, CreditPolicy::amule());
        log_prune_failures(&pruning);
        let dirty = reconciliation.is_adjusted()
            || pruning.removed_count() > 0
            || evidence_load.rejected_records() > 0
            || evidence_load.evicted_records() > 0
            || evidence_load.rejected_replay_markers() > 0;
        let next_prune_at = next_prune_time(&ledger, now);
        let (released_signal, released) = oneshot::channel();
        let state = Arc::new(MeasureState {
            storage,
            evidence_storage,
            runtime: Mutex::new(RuntimeLedger {
                ledger,
                evidence,
                committed_evidence_override: None,
                dirty,
                persisting: false,
                mutated_while_persisting: false,
                last_clock: now,
                next_prune_at,
            }),
            persistence_lock: AsyncMutex::new(()),
            clock,
            spawner,
            tasks: TaskSet::new(),
            _released: released_signal,
        });
        let (mut persistence_wake, receiver) = mpsc::channel(PERSISTENCE_WAKE_CAPACITY);
        drop(state.tasks.spawn_with(
            &state.spawner,
            run_persistence_worker(state.clone(), receiver),
        ));
        if dirty {
            let _ = persistence_wake.try_send(());
        }
        Ok(Self {
            state,
            persistence_wake,
            released,
        })
    }

    /// Stop this measurement and wait until it has released its stores.
    ///
    /// The persistence worker sees its wake channel close, persists the pending snapshot as on
    /// a drop, and exits; a flush still running ends first.
    ///
    /// Post: no task of this measurement holds either store, so their directories can be opened
    /// again in this process (one open store per directory, #1039). A plain drop releases them
    /// too, but only once a later poll of the worker has written the final snapshot, so an open
    /// right after a drop can find the directory still held (#1083). A storage operation whose
    /// wait was abandoned (a timed-out [`Self::flush_with_timeout`]) holds its store until it
    /// ends.
    pub async fn close(self) {
        let Self {
            state,
            persistence_wake,
            released,
        } = self;
        drop(persistence_wake);
        drop(state);
        // The sender is never sent on: `Canceled` is the release.
        let _ = released.await;
    }

    /// Persist a snapshot containing every update visible when this method starts.
    ///
    /// On native targets, the Tokio runtime captured by [`Self::new`] must
    /// remain alive until the returned future completes.
    pub async fn flush(&self) -> Result<(), MeasureRuntimeError> {
        self.start_flush().await
    }

    /// Persist all applied updates unless the supplied deadline expires first.
    ///
    /// On native targets, the Tokio runtime captured by [`Self::new`] must
    /// remain alive until the returned future completes or reaches `timeout`.
    pub async fn flush_with_timeout(&self, timeout: Duration) -> Result<(), MeasureRuntimeError> {
        let flush = self.start_flush().fuse();
        let deadline = measurement_delay(timeout).fuse();
        futures::pin_mut!(flush, deadline);
        futures::select! {
            result = flush => result,
            deadline = deadline => match deadline {
                Ok(()) => Err(MeasureRuntimeError::FlushTimeout),
                Err(error) => Err(error),
            },
        }
    }

    /// Start a flush on the captured executor now; the flush outlives a caller that stops
    /// waiting for it (a timed-out [`Self::flush_with_timeout`]).
    fn start_flush(&self) -> impl std::future::Future<Output = Result<(), MeasureRuntimeError>> {
        let state = Arc::clone(&self.state);
        let flush =
            self.state.tasks.spawn_with(
                &self.state.spawner,
                async move { flush_state(&state).await },
            );
        async move {
            match flush.await {
                Ok(result) => result,
                Err(Abandoned) => Err(MeasureRuntimeError::FlushTaskStopped),
            }
        }
    }

    fn wake_persistence(&self) {
        let mut sender = self.persistence_wake.clone();
        match sender.try_send(()) {
            Ok(()) => {}
            Err(error) if error.is_full() => {}
            Err(error) => tracing::error!(%error, "measurement persistence worker stopped"),
        }
    }
}

async fn flush_state(state: &MeasureState) -> Result<(), MeasureRuntimeError> {
    // Law (Lock order): persistence_lock ≺ runtime; `runtime` is released before storage I/O.
    let _guard = rings_core::utils::SlowLockGuard::acquire(
        "PeriodicMeasure::persistence_lock",
        state.persistence_lock.lock(),
    )
    .await;
    let (snapshot, evidence_snapshot) = {
        let mut runtime = lock_or_recover(&state.runtime);
        prepare_snapshots(&mut runtime)
    };
    let result = match state.storage.put(SNAPSHOT_KEY, &snapshot).await {
        Ok(()) => {
            state
                .evidence_storage
                .put(EVIDENCE_SNAPSHOT_KEY, &evidence_snapshot)
                .await
        }
        Err(error) => Err(error),
    };
    finish_persist(&mut lock_or_recover(&state.runtime), result.is_ok());
    result.map_err(MeasureRuntimeError::from)
}

/// Wait on the shared runtime timer, reporting failure as a measurement runtime error.
async fn measurement_delay(duration: Duration) -> Result<(), MeasureRuntimeError> {
    Ok(sleep(duration).await?)
}

fn next_prune_time(ledger: &MeasurementLedger<Did>, now: UnixTime) -> UnixTime {
    ledger
        .next_retention_boundary(CreditPolicy::amule())
        .unwrap_or_else(|| {
            UnixTime::from_secs(now.as_secs().saturating_add(PRUNE_INTERVAL_SECONDS))
        })
}

fn reconcile_runtime_clock(
    runtime: &mut RuntimeLedger,
    now: UnixTime,
) -> Result<bool, MeasureError> {
    if now >= runtime.last_clock {
        runtime.last_clock = now;
        return Ok(false);
    }
    runtime.last_clock = now;
    let reconciliation = runtime.ledger.reconcile_runtime(now, reliability_policy());
    runtime.next_prune_at = next_prune_time(&runtime.ledger, now);
    if !reconciliation.is_adjusted() {
        return Ok(false);
    }
    mark_runtime_dirty(runtime);
    tracing::warn!(
        clock_adjusted_records = reconciliation.clock_adjusted_records(),
        reliability_reset_records = reconciliation.reliability_reset_records(),
        "reconciled measurement state after wall-clock regression"
    );
    Ok(true)
}

fn maintain_runtime(runtime: &mut RuntimeLedger, now: UnixTime) -> Result<bool, MeasureError> {
    let mut persistence_required = reconcile_runtime_clock(runtime, now)?;
    if now < runtime.next_prune_at {
        return Ok(persistence_required);
    }

    let pruning = runtime.ledger.prune(now, CreditPolicy::amule());
    log_prune_failures(&pruning);
    runtime.next_prune_at = next_prune_time(&runtime.ledger, now);
    if pruning.removed_count() > 0 {
        mark_runtime_dirty(runtime);
        persistence_required = true;
    }
    Ok(persistence_required)
}

fn mark_runtime_dirty(runtime: &mut RuntimeLedger) {
    runtime.dirty = true;
    if runtime.persisting {
        runtime.mutated_while_persisting = true;
    }
}

fn prepare_snapshots(
    runtime: &mut RuntimeLedger,
) -> (MeasurementSnapshot<Did>, EvidenceSnapshot<Did>) {
    runtime.persisting = true;
    runtime.mutated_while_persisting = false;
    (runtime.ledger.snapshot(), runtime.evidence.snapshot())
}

fn valid_persisted_evidence(
    record: &ProvisionalEvidenceRecord<Did>,
    collector: EvidenceCollectorIdentity,
) -> bool {
    let Ok(receipt) = rings_core::message::ProvisionalServiceReceipt::from_canonical_bytes(
        record.canonical_receipt(),
    ) else {
        return false;
    };
    let claim = &receipt.claim;
    let observed_at_ms = u128::from(record.observed_at().as_secs()) * 1_000;
    let observed_slot =
        rings_core::message::ProvisionalEpoch::from_unix_seconds(record.observed_at().as_secs())
            .slot;
    receipt
        .verify_live_at(collector.network_id, observed_at_ms)
        .is_ok()
        && claim.network_id == collector.network_id
        && claim.provider_account == collector.provider_account
        && claim.network_id == record.freshness().network_id()
        && claim.provider_account == *record.pair().provider()
        && claim.beneficiary_account == *record.pair().beneficiary()
        && claim.beneficiary_account == *record.freshness().beneficiary()
        && claim.epoch.slot == record.freshness().epoch_slot()
        && claim.nonce == record.freshness().nonce()
        && record.replay_floor() == observed_slot.saturating_sub(1)
        && receipt
            .digest()
            .is_ok_and(|digest| digest.into_bytes() == record.digest().into_bytes())
}

fn valid_persisted_replay_marker(
    marker: &EvidenceReplayMarker<Did>,
    collector: EvidenceCollectorIdentity,
) -> bool {
    marker.freshness().network_id() == collector.network_id
        && *marker.pair().provider() == collector.provider_account
        && marker.pair().beneficiary() == marker.freshness().beneficiary()
}

fn finish_persist(runtime: &mut RuntimeLedger, succeeded: bool) {
    runtime.persisting = false;
    if succeeded {
        runtime.committed_evidence_override = None;
    }
    if succeeded && !runtime.mutated_while_persisting {
        runtime.dirty = false;
    }
    runtime.mutated_while_persisting = false;
}

fn log_prune_failures(report: &rings_measure::PruneReport<Did>) {
    for failure in report.failures() {
        tracing::warn!(
            peer = %failure.peer(),
            error = %failure.error(),
            "retained peer measurement that could not be pruned"
        );
    }
}

fn lock_or_recover<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
    mutex
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
}

async fn run_persistence_worker(state: Arc<MeasureState>, mut receiver: mpsc::Receiver<()>) {
    let mut retrying = false;
    loop {
        let should_attempt = if retrying {
            wait_for_retry_or_close(&mut receiver).await
        } else {
            match receiver.next().await {
                Some(()) => wait_for_debounce_or_close(&mut receiver).await,
                None => false,
            }
        };
        if !should_attempt {
            break;
        }
        retrying = match persist_pending_once(&state).await {
            Ok(()) => false,
            Err(error) => {
                tracing::error!(%error, "failed to persist measurement snapshot; retrying");
                true
            }
        };
    }
    persist_final_with_retries(&state).await;
}

async fn wait_for_debounce_or_close(receiver: &mut mpsc::Receiver<()>) -> bool {
    wait_for_debounce_or_close_with_delay(receiver, measurement_delay(PERSISTENCE_MIN_INTERVAL))
        .await
}

async fn wait_for_debounce_or_close_with_delay(
    receiver: &mut mpsc::Receiver<()>,
    delay: impl std::future::Future<Output = Result<(), MeasureRuntimeError>>,
) -> bool {
    let delay = delay.fuse();
    futures::pin_mut!(delay);
    loop {
        let signal = receiver.next().fuse();
        futures::pin_mut!(signal);
        futures::select! {
            result = delay => {
                log_persistence_delay_error(result);
                return true;
            }
            signal = signal => match signal {
                Some(()) => {}
                None => return false,
            }
        }
    }
}

async fn wait_for_retry_or_close(receiver: &mut mpsc::Receiver<()>) -> bool {
    wait_for_retry_or_close_with_delay(receiver, measurement_delay(PERSISTENCE_MIN_INTERVAL)).await
}

async fn wait_for_retry_or_close_with_delay(
    receiver: &mut mpsc::Receiver<()>,
    delay: impl std::future::Future<Output = Result<(), MeasureRuntimeError>>,
) -> bool {
    let delay = delay.fuse();
    futures::pin_mut!(delay);
    let mut wake_observed = false;
    loop {
        let signal = receiver.next().fuse();
        futures::pin_mut!(signal);
        futures::select! {
            result = delay => {
                match result {
                    Ok(()) => return true,
                    Err(error) => {
                        tracing::error!(%error, "failed to schedule measurement persistence retry");
                        if wake_observed {
                            return true;
                        }
                        // A broken browser timer cannot provide bounded autonomous retry. Wait for
                        // a later semantic mutation instead of spinning the JS microtask queue.
                        return receiver.next().await.is_some();
                    }
                }
            }
            signal = signal => match signal {
                Some(()) => wake_observed = true,
                None => return false,
            }
        }
    }
}

async fn persist_final_with_retries(state: &MeasureState) {
    // Shutdown retries are deliberately back-to-back: this path must remain
    // bounded and can recover immediate backend races, but must not add another
    // timer dependency while the owning runtime is stopping.
    for attempt in 1..=PERSISTENCE_SHUTDOWN_ATTEMPTS {
        match persist_pending_once(state).await {
            Ok(()) => return,
            Err(error) => {
                tracing::error!(
                    %error,
                    attempt,
                    max_attempts = PERSISTENCE_SHUTDOWN_ATTEMPTS,
                    "failed to persist final measurement snapshot"
                );
            }
        }
    }
}

fn log_persistence_delay_error(result: Result<(), MeasureRuntimeError>) {
    if let Err(error) = result {
        tracing::error!(%error, "failed to debounce measurement persistence");
    }
}

async fn persist_pending_once(state: &MeasureState) -> Result<(), MeasureRuntimeError> {
    // Law (Lock order): persistence_lock ≺ runtime; `runtime` is released before storage I/O.
    let _guard = rings_core::utils::SlowLockGuard::acquire(
        "PeriodicMeasure::persistence_lock",
        state.persistence_lock.lock(),
    )
    .await;
    let (snapshot, evidence_snapshot) = {
        let mut runtime = lock_or_recover(&state.runtime);
        if !runtime.dirty {
            return Ok(());
        }
        prepare_snapshots(&mut runtime)
    };
    let result = match state.storage.put(SNAPSHOT_KEY, &snapshot).await {
        Ok(()) => {
            state
                .evidence_storage
                .put(EVIDENCE_SNAPSHOT_KEY, &evidence_snapshot)
                .await
        }
        Err(error) => Err(error),
    };
    finish_persist(&mut lock_or_recover(&state.runtime), result.is_ok());
    result.map_err(MeasureRuntimeError::from)
}

#[cfg_attr(feature = "node", async_trait)]
#[cfg_attr(all(feature = "browser", target_family = "wasm"), async_trait(?Send))]
impl Measure for PeriodicMeasure {
    async fn record(
        &self,
        did: Did,
        authentication: Authentication,
        event: MeasurementEvent,
    ) -> Result<ApplyOutcome, MeasureError> {
        self.record_batch(did, authentication, MeasurementBatch::single(event))
            .await
    }

    async fn record_batch(
        &self,
        did: Did,
        authentication: Authentication,
        batch: MeasurementBatch,
    ) -> Result<ApplyOutcome, MeasureError> {
        let (outcome, persistence_required) = {
            let (mut runtime, now) = self.state.runtime_at_now();
            let persistence_required = maintain_runtime(&mut runtime, now)?;
            let outcome = runtime
                .ledger
                .apply_batch(did, authentication, batch, now, reliability_policy())
                .map(|report| {
                    if let Some(evicted_peer) = report.evicted_peer() {
                        tracing::warn!(
                            ?evicted_peer,
                            replacement_peer = ?did,
                            "measurement ledger evicted its stalest authenticated peer"
                        );
                    }
                    report.outcome()
                });
            let applied = matches!(outcome, Ok(ApplyOutcome::Applied));
            if applied {
                mark_runtime_dirty(&mut runtime);
            }
            (outcome, persistence_required || applied)
        };
        if persistence_required {
            self.wake_persistence();
        }
        outcome
    }

    async fn peer_measurement(&self, did: Did) -> Result<Option<PeerMeasurement>, MeasureError> {
        let (projected, reconciled) = {
            let (mut runtime, now) = self.state.runtime_at_now();
            let reconciled = maintain_runtime(&mut runtime, now)?;
            let projected =
                runtime
                    .ledger
                    .measurement(&did, now, CreditPolicy::amule(), reliability_policy());
            (projected, reconciled)
        };
        if reconciled {
            self.wake_persistence();
        }
        Ok(projected?.map(PeerMeasurement::from_projected))
    }

    async fn peer_measurements(&self) -> Result<Vec<PeerMeasurement>, MeasureError> {
        let (projection, reconciled) = {
            let (mut runtime, now) = self.state.runtime_at_now();
            let reconciled = maintain_runtime(&mut runtime, now)?;
            let projection =
                runtime
                    .ledger
                    .measurements(now, CreditPolicy::amule(), reliability_policy());
            (projection, reconciled)
        };
        if reconciled {
            self.wake_persistence();
        }
        let (measurements, failures) = projection.into_parts();
        for failure in failures {
            tracing::warn!(
                peer = %failure.peer(),
                error = %failure.error(),
                "omitted invalid peer from measurement projection"
            );
        }
        Ok(measurements
            .into_iter()
            .map(PeerMeasurement::from_projected)
            .collect())
    }

    async fn peer_measurements_page(
        &self,
        after: Option<Did>,
        limit: NonZeroUsize,
    ) -> Result<PeerMeasurementPage, MeasureError> {
        let (page, reconciled) = {
            let (mut runtime, now) = self.state.runtime_at_now();
            let reconciled = maintain_runtime(&mut runtime, now)?;
            let page = runtime.ledger.measurements_page(
                after.as_ref(),
                limit,
                now,
                CreditPolicy::amule(),
                reliability_policy(),
            );
            (page, reconciled)
        };
        if reconciled {
            self.wake_persistence();
        }
        let (measurements, failures, next_cursor) = page.into_parts();
        for failure in failures {
            tracing::warn!(
                peer = %failure.peer(),
                error = %failure.error(),
                "omitted invalid peer from bounded measurement projection"
            );
        }
        Ok(PeerMeasurementPage {
            measurements: measurements
                .into_iter()
                .map(PeerMeasurement::from_projected)
                .collect(),
            next_cursor,
        })
    }

    async fn admit_provisional_evidence(
        &self,
        record: ProvisionalEvidenceRecord<Did>,
    ) -> Result<EvidenceAdmissionReport<Did>, EvidenceError> {
        // The evidence-storage put below is the successful operation's linearization point.
        // Law (Lock order): persistence_lock ≺ runtime. While the durable write is in flight,
        // `committed_evidence_override` preserves the pre-admission view for read-only queries so
        // they never block behind storage I/O and never observe an uncommitted admission.
        let _persistence_guard = rings_core::utils::SlowLockGuard::acquire(
            "PeriodicMeasure::persistence_lock",
            self.state.persistence_lock.lock(),
        )
        .await;
        let (rollback_before, previous_override, result, snapshot) = {
            let mut runtime = lock_or_recover(&self.state.runtime);
            let rollback_before = runtime.evidence.clone();
            let previous_override = runtime.committed_evidence_override.clone();
            if runtime.committed_evidence_override.is_none() {
                runtime.committed_evidence_override = Some(rollback_before.clone());
            }
            let result = runtime.evidence.admit(record);
            mark_runtime_dirty(&mut runtime);
            let snapshot = runtime.evidence.snapshot();
            (rollback_before, previous_override, result, snapshot)
        };
        self.wake_persistence();
        if let Err(error) = self
            .state
            .evidence_storage
            .put(EVIDENCE_SNAPSHOT_KEY, &snapshot)
            .await
        {
            tracing::error!(%error, "failed to commit provisional evidence admission");
            let mut runtime = lock_or_recover(&self.state.runtime);
            runtime.evidence = rollback_before;
            runtime.committed_evidence_override = previous_override;
            return Err(EvidenceError::PersistenceUnavailable);
        }
        lock_or_recover(&self.state.runtime).committed_evidence_override = None;
        result
    }

    async fn provisional_evidence_page(
        &self,
        after: Option<EvidenceDigest>,
        limit: NonZeroUsize,
    ) -> Result<EvidencePage<Did>, EvidenceError> {
        // Leaf read (`runtime` only, `Law (Lock order): persistence_lock ≺ runtime`).
        Ok(lock_or_recover(&self.state.runtime)
            .committed_evidence()
            .page(after, limit))
    }

    async fn provisional_evidence_counters(&self) -> EvidenceCounters {
        // Leaf read (`runtime` only, `Law (Lock order): persistence_lock ≺ runtime`).
        lock_or_recover(&self.state.runtime)
            .committed_evidence()
            .counters()
    }
}

#[cfg_attr(feature = "node", async_trait)]
#[cfg_attr(all(feature = "browser", target_family = "wasm"), async_trait(?Send))]
impl measure::BehaviourJudgement for PeriodicMeasure {
    async fn quality(&self, did: Did) -> PeerQuality {
        match self.peer_measurement(did).await {
            Ok(Some(measurement)) => measurement.quality,
            Ok(None) => PeerQuality::Unknown,
            Err(error) => {
                tracing::error!(peer = %did, %error, "failed to project peer reliability");
                PeerQuality::Unknown
            }
        }
    }
}

#[cfg(test)]
#[cfg(feature = "node")]
#[allow(clippy::panic)]
mod authentication_tests;
#[cfg(test)]
#[cfg(feature = "node")]
#[allow(clippy::panic)]
mod evidence_tests;
#[cfg(test)]
#[cfg(feature = "node")]
#[allow(clippy::panic)]
mod tests;
#[cfg(test)]
#[cfg(feature = "node")]
#[allow(clippy::panic)]
mod worker_tests;