-
Notifications
You must be signed in to change notification settings - Fork 220
Expand file tree
/
Copy pathfixed.rs
More file actions
4281 lines (3743 loc) · 167 KB
/
fixed.rs
File metadata and controls
4281 lines (3743 loc) · 167 KB
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
//! An append-only log for storing fixed length _items_ on disk.
//!
//! In addition to replay, stored items can be fetched directly by their `position` in the journal,
//! where position is defined as the item's order of insertion starting from 0, unaffected by
//! pruning.
//!
//! _See [super::variable] for a journal that supports variable length items._
//!
//! # Format
//!
//! Data stored in a `fixed::Journal` is persisted in one of many Blobs. Each `Blob` contains a
//! configurable maximum of `items_per_blob`, with page-level data integrity provided by a buffer
//! pool.
//!
//! ```text
//! +--------+----- --+--- -+----------+
//! | item_0 | item_1 | ... | item_n-1 |
//! +--------+-----------+--------+----0
//!
//! n = config.items_per_blob
//! ```
//!
//! The most recent blob may not necessarily be full, in which case it will contain fewer than the
//! maximum number of items.
//!
//! Data fetched from disk is always checked for integrity before being returned. If the data is
//! found to be invalid, an error is returned instead.
//!
//! # Open Blobs
//!
//! All `Blobs` in a given `partition` are kept open during the lifetime of `Journal`. You can limit
//! the number of open blobs by using a higher number of `items_per_blob` and/or pruning old items.
//!
//! # Partition
//!
//! Blobs are stored in the legacy partition (`cfg.partition`) if it already contains data;
//! otherwise they are stored in `{cfg.partition}-blobs`.
//!
//! Metadata is stored in `{cfg.partition}-metadata`.
//!
//! # Metadata
//!
//! Metadata consists of two optional keys:
//! - PRUNING_BOUNDARY_KEY: Stores the pruning boundary as a u64 when it's mid-section (not a
//! multiple of items_per_blob). Absent from legacy journals or when the boundary is
//! section-aligned, since it can be derived from the oldest blob.
//! - RECOVERY_WATERMARK_KEY: Stores the last logical size at which the fixed journal's entries and
//! metadata were synced as a coherent recovery checkpoint for external consumers. Fixed-journal
//! recovery does not use this value to decide whether short blobs are corrupt. Absent on journals
//! created before this key was added; those journals recover from the newest retained blob using
//! the old rollover-sync invariant, then write the key before accepting new appends.
//!
//! RECOVERY_WATERMARK_KEY is mainly useful when this journal is used as an index for a layered
//! journal, such as the variable journal's offsets. Standalone fixed journals do not need it to
//! recover their own size; they recover from retained blob lengths.
//!
//! # Recovery
//!
//! Recovery derives fixed-journal size from retained blob lengths:
//! - Once RECOVERY_WATERMARK_KEY exists, recovery walks retained blob lengths from oldest to
//! newest. A short newest section is the natural tail; a short earlier section is treated as the
//! end of the contiguous prefix, and newer sections are truncated. After size recovery, the
//! watermark is preserved if it is still within the recovered size and lowered otherwise.
//! - Legacy journals without RECOVERY_WATERMARK_KEY rely on the old rule that section rollover
//! synced the previous section. Valid legacy journals recover from the newest retained blob once,
//! then persist the watermark before returning from `init`.
//!
//! The recovery watermark is therefore an external recovery checkpoint, not a complete record of
//! every item that may have become durable through `commit` or storage behavior.
//!
//! # Consistency
//!
//! Data written to `Journal` may not be immediately persisted to `Storage`. It is up to the caller
//! to determine when to force pending data to be durably written using `commit` or `sync`. When
//! calling `close`, all pending data is automatically synced and any open blobs are closed.
//!
//! # Pruning
//!
//! The `prune` method allows the `Journal` to prune blobs consisting entirely of items prior to a
//! given point in history.
//!
//! # Replay
//!
//! The `replay` method supports fast reading of all unpruned items into memory.
#[cfg(test)]
use super::Reader as _;
use crate::{
journal::{
contiguous::{metrics::FixedMetrics as Metrics, Many, Mutable},
segmented::fixed::{Config as SegmentedConfig, Journal as SegmentedJournal},
Error,
},
metadata::{Config as MetadataConfig, Metadata},
Context, Persistable,
};
use commonware_codec::CodecFixedShared;
use commonware_runtime::buffer::paged::CacheRef;
use commonware_utils::sync::{AsyncMutex, AsyncRwLock, AsyncRwLockReadGuard};
use futures::{stream::Stream, StreamExt};
use std::num::{NonZeroU64, NonZeroUsize};
use tracing::warn;
/// Metadata key for storing the pruning boundary.
const PRUNING_BOUNDARY_KEY: u64 = 1;
/// Metadata key for storing the recovery watermark.
const RECOVERY_WATERMARK_KEY: u64 = 2;
/// Return the first retained logical position in `section`.
#[inline]
const fn first_in_section(pruning_boundary: u64, section: u64, items_per_blob: u64) -> u64 {
let start = section * items_per_blob;
if pruning_boundary > start {
pruning_boundary
} else {
start
}
}
/// Maximum number of items a section's blob can physically hold. This is `items_per_blob` unless
/// the pruning boundary falls mid-section (from `init_at_size`), in which case the skipped prefix
/// reduces the capacity.
#[inline]
const fn section_capacity(pruning_boundary: u64, section: u64, items_per_blob: u64) -> u64 {
let start = section * items_per_blob;
items_per_blob - (first_in_section(pruning_boundary, section, items_per_blob) - start)
}
/// Configuration for `Journal` storage.
#[derive(Clone)]
pub struct Config {
/// Prefix for the journal partitions.
///
/// Blobs are stored in `partition` (legacy) if it contains data, otherwise in
/// `{partition}-blobs`. Metadata is stored in `{partition}-metadata`.
pub partition: String,
/// The maximum number of journal items to store in each blob.
///
/// Retained non-tail blobs are expected to be full relative to their logical capacity. A
/// mid-section oldest blob may physically hold fewer than this many items, and the newest blob
/// may contain fewer items.
pub items_per_blob: NonZeroU64,
/// The page cache to use for caching data.
pub page_cache: CacheRef,
/// The size of the write buffer to use for each blob.
pub write_buffer: NonZeroUsize,
}
/// Inner state protected by a single RwLock.
struct Inner<E: Context, A: CodecFixedShared> {
/// The underlying segmented journal.
journal: SegmentedJournal<E, A>,
/// Total number of items appended (not affected by pruning).
size: u64,
/// Stores the recovery watermark and, when the pruning boundary is mid-section, the exact
/// pruning boundary. Otherwise, the pruning-boundary entry is omitted.
///
/// Metadata that advances the pruning boundary or recovery watermark is persisted only after
/// the blob state it describes is durable. A lower recovery watermark is always safe to persist
/// because it only expands the suffix external consumers may replay. If pruning metadata
/// disagrees with the oldest blob during recovery, the blob state wins.
// TODO(#2939): Remove metadata
metadata: Metadata<E, u64, Vec<u8>>,
/// The position before which all items have been pruned.
pruning_boundary: u64,
/// The earliest section modified since the last successful `commit()` or `sync()`.
dirty_from_section: Option<u64>,
}
/// A deferred blob truncation to apply after metadata is persisted during init.
struct RecoveryRepair {
section: u64,
byte_offset: u64,
}
impl<E: Context, A: CodecFixedShared> Inner<E, A> {
/// Read the item at position `pos` in the journal.
///
/// # Errors
///
/// - [Error::ItemPruned] if the item at position `pos` is pruned.
/// - [Error::ItemOutOfRange] if the item at position `pos` does not exist.
async fn read(&self, pos: u64, items_per_blob: u64) -> Result<A, Error> {
if pos >= self.size {
return Err(Error::ItemOutOfRange(pos));
}
if pos < self.pruning_boundary {
return Err(Error::ItemPruned(pos));
}
let section = pos / items_per_blob;
let pos_in_section = pos - first_in_section(self.pruning_boundary, section, items_per_blob);
self.journal
.get(section, pos_in_section)
.await
.map_err(|e| {
// Since we check bounds above, any failure here is unexpected.
match e {
Error::SectionOutOfRange(e)
| Error::AlreadyPrunedToSection(e)
| Error::ItemOutOfRange(e) => {
Error::Corruption(format!("section/item should be found, but got: {e}"))
}
other => other,
}
})
}
/// Read an item if it can be done synchronously (e.g. without I/O), returning `None` otherwise.
fn try_read_sync(&self, pos: u64, items_per_blob: u64) -> Option<A> {
let mut buf = vec![0u8; SegmentedJournal::<E, A>::CHUNK_SIZE];
self.try_read_sync_into(pos, items_per_blob, &mut buf)
}
/// Read an item synchronously using caller-provided buffer.
fn try_read_sync_into(&self, pos: u64, items_per_blob: u64, buf: &mut [u8]) -> Option<A> {
if pos >= self.size || pos < self.pruning_boundary {
return None;
}
let section = pos / items_per_blob;
let pos_in_section = pos - first_in_section(self.pruning_boundary, section, items_per_blob);
self.journal.try_get_sync_into(section, pos_in_section, buf)
}
}
/// Implementation of `Journal` storage.
///
/// This is implemented as a wrapper around [SegmentedJournal] that provides position-based access
/// where positions are automatically mapped to (section, position_in_section) pairs.
///
/// # Repair
///
/// Like
/// [sqlite](https://github.com/sqlite/sqlite/blob/8658a8df59f00ec8fcfea336a2a6a4b5ef79d2ee/src/wal.c#L1504-L1505)
/// and
/// [rocksdb](https://github.com/facebook/rocksdb/blob/0c533e61bc6d89fdf1295e8e0bcee4edb3aef401/include/rocksdb/options.h#L441-L445),
/// the first invalid data read will be considered the new end of the journal (and the
/// underlying blob will be truncated to the last valid item). Repair is performed
/// by the underlying [SegmentedJournal] during init.
pub struct Journal<E: Context, A: CodecFixedShared> {
/// Inner state with segmented journal and size.
inner: AsyncRwLock<Inner<E, A>>,
/// Serializes writers with `commit()` and `sync()` so a plain rwlock is sufficient.
op_lock: AsyncMutex<()>,
/// The maximum number of items per blob (section).
items_per_blob: u64,
/// Metrics for monitoring journal state and activity.
metrics: Metrics<E>,
}
/// A reader guard that holds a consistent snapshot of the journal's bounds.
pub struct Reader<'a, E: Context, A: CodecFixedShared> {
guard: AsyncRwLockReadGuard<'a, Inner<E, A>>,
items_per_blob: u64,
metrics: &'a Metrics<E>,
}
impl<E: Context, A: CodecFixedShared> super::Reader for Reader<'_, E, A> {
type Item = A;
fn bounds(&self) -> std::ops::Range<u64> {
self.guard.pruning_boundary..self.guard.size
}
async fn read(&self, pos: u64) -> Result<A, Error> {
let _timer = self.metrics.read_timer();
self.metrics.read_calls.inc();
let result = match self.guard.read(pos, self.items_per_blob).await {
Ok(item) => {
self.metrics.items_read.inc();
Ok(item)
}
Err(error) => Err(error),
};
result
}
async fn read_many(&self, positions: &[u64]) -> Result<Vec<A>, Error> {
if positions.is_empty() {
return Ok(Vec::new());
}
let _timer = self.metrics.read_many_timer();
self.metrics.read_many_calls.inc();
assert!(
positions.windows(2).all(|w| w[0] < w[1]),
"positions must be strictly increasing"
);
// Validate all positions.
for &pos in positions {
if pos >= self.guard.size {
return Err(Error::ItemOutOfRange(pos));
}
if pos < self.guard.pruning_boundary {
return Err(Error::ItemPruned(pos));
}
}
let items_per_blob = self.items_per_blob;
let pruning_boundary = self.guard.pruning_boundary;
let chunk_size = SegmentedJournal::<E, A>::CHUNK_SIZE;
// Phase 1: Drain page-cache hits synchronously.
let mut result: Vec<Option<A>> = Vec::with_capacity(positions.len());
let mut miss_indices: Vec<usize> = Vec::new();
let mut miss_positions: Vec<u64> = Vec::new();
let mut sync_buf = vec![0u8; chunk_size];
for (i, &pos) in positions.iter().enumerate() {
if let Some(item) = self
.guard
.try_read_sync_into(pos, items_per_blob, &mut sync_buf)
{
result.push(Some(item));
} else {
result.push(None);
miss_indices.push(i);
miss_positions.push(pos);
}
}
if miss_positions.is_empty() {
self.metrics.record_cache_hits(positions.len() as u64);
self.metrics.items_read.inc_by(positions.len() as u64);
return Ok(result.into_iter().map(|r| r.unwrap()).collect());
}
self.metrics
.record_cache_hits((positions.len() - miss_positions.len()) as u64);
self.metrics
.record_cache_misses(miss_positions.len() as u64);
// Phase 2: Read cache misses grouped by section (sequential).
let mut reusable_buf = vec![0u8; miss_positions.len() * chunk_size];
let mut disk_offset = 0;
let mut group_start = 0;
while group_start < miss_positions.len() {
let section = miss_positions[group_start] / items_per_blob;
let mut group_end = group_start + 1;
while group_end < miss_positions.len()
&& miss_positions[group_end] / items_per_blob == section
{
group_end += 1;
}
let group_len = group_end - group_start;
let first_position = first_in_section(pruning_boundary, section, items_per_blob);
let section_positions: Vec<u64> = miss_positions[group_start..group_end]
.iter()
.map(|&pos| pos - first_position)
.collect();
let buf = &mut reusable_buf[..group_len * chunk_size];
let items = self
.guard
.journal
.get_many(section, §ion_positions, buf)
.await
.map_err(|e| match e {
Error::SectionOutOfRange(e)
| Error::AlreadyPrunedToSection(e)
| Error::ItemOutOfRange(e) => {
Error::Corruption(format!("section/item should be found, but got: {e}"))
}
other => other,
})?;
for (item, &miss_idx) in items.into_iter().zip(&miss_indices[disk_offset..]) {
result[miss_idx] = Some(item);
}
disk_offset += group_len;
group_start = group_end;
}
self.metrics.items_read.inc_by(positions.len() as u64);
Ok(result.into_iter().map(|r| r.unwrap()).collect())
}
fn try_read_sync(&self, pos: u64) -> Option<A> {
self.guard
.try_read_sync(pos, self.items_per_blob)
.map_or_else(
|| {
self.metrics.record_cache_misses(1);
None
},
|item| {
self.metrics.record_cache_hits(1);
self.metrics.try_read_sync_hits.inc();
self.metrics.items_read.inc();
Some(item)
},
)
}
async fn replay(
&self,
buffer: NonZeroUsize,
start_pos: u64,
) -> Result<impl Stream<Item = Result<(u64, A), Error>> + Send, Error> {
let items_per_blob = self.items_per_blob;
let pruning_boundary = self.guard.pruning_boundary;
// Validate bounds.
if start_pos > self.guard.size {
return Err(Error::ItemOutOfRange(start_pos));
}
if start_pos < pruning_boundary {
return Err(Error::ItemPruned(start_pos));
}
let start_section = start_pos / items_per_blob;
let start_pos_in_section =
start_pos - first_in_section(pruning_boundary, start_section, items_per_blob);
// Check all middle sections (not oldest, not tail) in range are complete.
let journal = &self.guard.journal;
if let (Some(oldest), Some(newest)) = (journal.oldest_section(), journal.newest_section()) {
let first_to_check = start_section.max(oldest + 1);
for section in first_to_check..newest {
let len = journal.section_len(section).await?;
if len < items_per_blob {
return Err(Error::Corruption(format!(
"section {section} incomplete: expected {items_per_blob} items, got {len}"
)));
}
}
}
let inner_stream = journal
.replay(start_section, start_pos_in_section, buffer)
.await?;
// Transform (section, pos_in_section, item) to (global_pos, item).
let stream = inner_stream.map(move |result| {
result.map(|(section, pos_in_section, item)| {
let global_pos =
first_in_section(pruning_boundary, section, items_per_blob) + pos_in_section;
(global_pos, item)
})
});
Ok(stream)
}
}
impl<E: Context, A: CodecFixedShared> Journal<E, A> {
/// Size of each entry in bytes.
pub const CHUNK_SIZE: usize = SegmentedJournal::<E, A>::CHUNK_SIZE;
/// Size of each entry in bytes (as u64).
pub const CHUNK_SIZE_U64: u64 = Self::CHUNK_SIZE as u64;
/// Mark all sections from `section` onward as dirty.
fn mark_dirty_from(inner: &mut Inner<E, A>, section: u64) {
inner.dirty_from_section = Some(
inner
.dirty_from_section
.map_or(section, |existing| existing.min(section)),
);
}
/// Parse an optional u64 value from metadata.
fn parse_metadata_u64(
metadata: &Metadata<E, u64, Vec<u8>>,
key: u64,
label: &'static str,
) -> Result<Option<u64>, Error> {
match metadata.get(&key) {
Some(bytes) => Ok(Some(u64::from_be_bytes(
bytes
.as_slice()
.try_into()
.map_err(|_| Error::Corruption(format!("invalid {label} metadata")))?,
))),
None => Ok(None),
}
}
/// Update pruning-boundary and recovery-watermark entries in metadata's in-memory state.
///
/// Call `inner.metadata.sync()` separately to persist the updated entries.
fn update_metadata_entries(
inner: &mut Inner<E, A>,
items_per_blob: u64,
pruning_boundary: u64,
recovery_watermark: u64,
) -> Result<(), Error> {
let current_pruning =
Self::parse_metadata_u64(&inner.metadata, PRUNING_BOUNDARY_KEY, "pruning_boundary")?;
if !pruning_boundary.is_multiple_of(items_per_blob) {
if current_pruning != Some(pruning_boundary) {
inner.metadata.put(
PRUNING_BOUNDARY_KEY,
pruning_boundary.to_be_bytes().to_vec(),
);
}
} else if current_pruning.is_some() {
inner.metadata.remove(&PRUNING_BOUNDARY_KEY);
}
let current_watermark = Self::parse_metadata_u64(
&inner.metadata,
RECOVERY_WATERMARK_KEY,
"recovery_watermark",
)?;
if current_watermark != Some(recovery_watermark) {
inner.metadata.put(
RECOVERY_WATERMARK_KEY,
recovery_watermark.to_be_bytes().to_vec(),
);
}
Ok(())
}
/// Update and persist pruning-boundary and recovery-watermark metadata entries.
async fn persist_metadata_entries(
inner: &mut Inner<E, A>,
items_per_blob: u64,
pruning_boundary: u64,
recovery_watermark: u64,
) -> Result<(), Error> {
Self::update_metadata_entries(inner, items_per_blob, pruning_boundary, recovery_watermark)?;
inner.metadata.sync().await?;
Ok(())
}
/// Stage a recovery watermark no greater than `limit`.
///
/// This is used before blob state moves backward so external consumers never see a persisted
/// recovery checkpoint beyond the rewind/clear target.
fn lower_recovery_watermark(inner: &mut Inner<E, A>, limit: u64) -> Result<bool, Error> {
let current_watermark = Self::parse_metadata_u64(
&inner.metadata,
RECOVERY_WATERMARK_KEY,
"recovery_watermark",
)?;
let Some(current) = current_watermark else {
return Ok(false);
};
if current <= limit {
return Ok(false);
}
inner
.metadata
.put(RECOVERY_WATERMARK_KEY, limit.to_be_bytes().to_vec());
Ok(true)
}
/// Stage a recovery-watermark entry no greater than `limit` in raw metadata.
///
/// This is used by `init_at_size` before it clears existing blobs, before an `Inner` exists.
#[commonware_macros::stability(ALPHA)]
fn update_metadata_watermark_before_clear(
metadata: &mut Metadata<E, u64, Vec<u8>>,
limit: u64,
) -> Result<bool, Error> {
let Some(current_watermark) =
Self::parse_metadata_u64(metadata, RECOVERY_WATERMARK_KEY, "recovery_watermark")?
else {
return Ok(false);
};
if current_watermark <= limit {
return Ok(false);
}
metadata.put(RECOVERY_WATERMARK_KEY, limit.to_be_bytes().to_vec());
Ok(true)
}
/// Scan a partition and return blob names, treating a missing partition as empty.
async fn scan_partition(context: &E, partition: &str) -> Result<Vec<Vec<u8>>, Error> {
match context.scan(partition).await {
Ok(blobs) => Ok(blobs),
Err(commonware_runtime::Error::PartitionMissing(_)) => Ok(Vec::new()),
Err(err) => Err(Error::Runtime(err)),
}
}
/// Select the blobs partition using legacy-first compatibility rules.
///
/// If both legacy and new blobs partitions contain data, returns corruption.
/// If neither contains data, defaults to the new blobs partition.
// TODO(#2941): Remove legacy partition support
async fn select_blob_partition(context: &E, cfg: &Config) -> Result<String, Error> {
let legacy_partition = cfg.partition.as_str();
let new_partition = format!("{}-blobs", cfg.partition);
let legacy_blobs = Self::scan_partition(context, legacy_partition).await?;
let new_blobs = Self::scan_partition(context, &new_partition).await?;
if !legacy_blobs.is_empty() && !new_blobs.is_empty() {
return Err(Error::Corruption(format!(
"both legacy and blobs partitions contain data: legacy={} blobs={}",
legacy_partition, new_partition
)));
}
if !legacy_blobs.is_empty() {
Ok(legacy_partition.into())
} else {
Ok(new_partition)
}
}
/// Initialize a new `Journal` instance.
///
/// All backing blobs are opened but not read during initialization. The `replay` method can be
/// used to iterate over all items in the `Journal`.
pub async fn init(context: E, cfg: Config) -> Result<Self, Error> {
let items_per_blob = cfg.items_per_blob.get();
let blob_partition = Self::select_blob_partition(&context, &cfg).await?;
let segmented_cfg = SegmentedConfig {
partition: blob_partition,
page_cache: cfg.page_cache,
write_buffer: cfg.write_buffer,
};
let mut journal = SegmentedJournal::init(context.child("blobs"), segmented_cfg).await?;
let meta_cfg = MetadataConfig {
partition: format!("{}-metadata", cfg.partition),
codec_config: ((0..).into(), ()),
};
let metadata = Metadata::<_, u64, Vec<u8>>::init(context.child("meta"), meta_cfg).await?;
let meta_pruning_boundary =
Self::parse_metadata_u64(&metadata, PRUNING_BOUNDARY_KEY, "pruning_boundary")?;
let meta_recovery_watermark =
Self::parse_metadata_u64(&metadata, RECOVERY_WATERMARK_KEY, "recovery_watermark")?;
let (pruning_boundary, size, recovery_watermark, repair) = Self::recover_bounds(
&mut journal,
items_per_blob,
meta_pruning_boundary,
meta_recovery_watermark,
)
.await?;
let mut inner = Inner {
journal,
size,
metadata,
pruning_boundary,
dirty_from_section: None,
};
// Persist any lowered checkpoint before applying blob repairs that move recovered state
// backward.
Self::persist_metadata_entries(
&mut inner,
items_per_blob,
pruning_boundary,
recovery_watermark,
)
.await?;
if let Some(repair) = repair {
inner
.journal
.rewind(repair.section, repair.byte_offset)
.await?;
inner.journal.sync(repair.section).await?;
}
let tail_section = size / items_per_blob;
inner.journal.ensure_section_exists(tail_section).await?;
let metrics = Metrics::new(context);
metrics.update(size, pruning_boundary, items_per_blob);
Ok(Self {
inner: AsyncRwLock::new(inner),
op_lock: AsyncMutex::new(()),
items_per_blob,
metrics,
})
}
/// Recover `(pruning_boundary, size, recovery_watermark, repair)` from metadata and blob state.
async fn recover_bounds(
inner: &mut SegmentedJournal<E, A>,
items_per_blob: u64,
meta_pruning_boundary: Option<u64>,
meta_recovery_watermark: Option<u64>,
) -> Result<(u64, u64, u64, Option<RecoveryRepair>), Error> {
let blob_boundary = inner.oldest_section().map_or(0, |o| o * items_per_blob);
// Determine the pruning boundary from metadata and blob state.
//
// PRUNING_BOUNDARY_KEY is only stored when the boundary falls mid-section. If present and
// it refers to the current oldest section, use it. If it refers to a different section
// (crash left stale metadata), fall back to the section-aligned blob boundary. Absence of
// the key just means the boundary is section-aligned.
//
// Staleness detection is one-sided: we can only tell metadata is stale when it names a
// section that no longer exists. If it names the current oldest section, we trust it. This
// is safe because prune persists metadata after blob state, so a crash before the metadata
// update means the newer boundary was never fully committed.
let mut pruning_metadata_stale = false;
let pruning_boundary = match meta_pruning_boundary {
Some(meta_pruning_boundary)
if !meta_pruning_boundary.is_multiple_of(items_per_blob) =>
{
let meta_oldest_section = meta_pruning_boundary / items_per_blob;
match inner.oldest_section() {
None => {
warn!(
meta_oldest_section,
"crash repair: no blobs exist, ignoring stale pruning metadata"
);
pruning_metadata_stale = true;
blob_boundary
}
Some(oldest_section) if meta_oldest_section < oldest_section => {
warn!(
meta_oldest_section,
oldest_section,
"crash repair: pruning metadata stale, computing from blobs"
);
pruning_metadata_stale = true;
blob_boundary
}
Some(oldest_section) if meta_oldest_section > oldest_section => {
warn!(
meta_oldest_section,
oldest_section,
"crash repair: pruning metadata ahead of blobs, computing from blobs"
);
pruning_metadata_stale = true;
blob_boundary
}
Some(_) => meta_pruning_boundary,
}
}
_ => blob_boundary,
};
// Check oldest section for over-capacity corruption before recovery mode dispatch.
Self::validate_oldest_section(inner, items_per_blob, pruning_boundary).await?;
// Perform any recovery if needed, computing journal size and recovery watermark.
let (size, repair) = match meta_recovery_watermark {
Some(_) => {
Self::recover_by_walking_lengths(inner, items_per_blob, pruning_boundary).await?
}
None if !pruning_metadata_stale => {
// No stale pruning metadata and no recovery watermark implies a legacy format.
Self::recover_legacy_size(inner, items_per_blob, pruning_boundary).await?
}
None => {
// Pruning metadata was stale, and there is no recovery watermark to preserve.
Self::recover_by_walking_lengths(inner, items_per_blob, pruning_boundary).await?
}
};
let recovery_watermark = meta_recovery_watermark.unwrap_or(size).min(size);
Ok((pruning_boundary, size, recovery_watermark, repair))
}
/// Check that the oldest section does not exceed its logical capacity.
async fn validate_oldest_section(
inner: &SegmentedJournal<E, A>,
items_per_blob: u64,
pruning_boundary: u64,
) -> Result<(), Error> {
let Some(oldest) = inner.oldest_section() else {
return Ok(());
};
let oldest_len = inner.section_len(oldest).await?;
let expected = section_capacity(pruning_boundary, oldest, items_per_blob);
if oldest_len > expected {
return Err(Error::Corruption(format!(
"oldest section {oldest} has too many items: expected at most {expected}, got {oldest_len}"
)));
}
Ok(())
}
async fn section_len_within_capacity(
inner: &SegmentedJournal<E, A>,
items_per_blob: u64,
pruning_boundary: u64,
section: u64,
) -> Result<(u64, u64), Error> {
let len = inner.section_len(section).await?;
let capacity = section_capacity(pruning_boundary, section, items_per_blob);
if len > capacity {
return Err(Error::Corruption(format!(
"section {section} has too many items: expected at most {capacity}, got {len}"
)));
}
Ok((len, capacity))
}
/// Recover a legacy journal that has no RECOVERY_WATERMARK_KEY.
///
/// Before the watermark key existed, writers synced each section before rolling over to the
/// next one. That lets valid legacy journals recover from the newest retained blob without
/// walking all retained sections. If the oldest non-tail section is already short, the legacy
/// invariant is violated and recovery keeps only the contiguous prefix.
async fn recover_legacy_size(
inner: &mut SegmentedJournal<E, A>,
items_per_blob: u64,
pruning_boundary: u64,
) -> Result<(u64, Option<RecoveryRepair>), Error> {
let Some(newest) = inner.newest_section() else {
return Ok((pruning_boundary, None));
};
let Some(oldest) = inner.oldest_section() else {
return Ok((pruning_boundary, None));
};
let (oldest_len, oldest_capacity) =
Self::section_len_within_capacity(inner, items_per_blob, pruning_boundary, oldest)
.await?;
if oldest != newest && oldest_len < oldest_capacity {
// This cannot be a valid legacy state under the old rollover-sync rule, but walking
// lengths still recovers the contiguous prefix without trusting the stale size.
return Self::recover_by_walking_lengths(inner, items_per_blob, pruning_boundary).await;
}
let (tail_len, _) =
Self::section_len_within_capacity(inner, items_per_blob, pruning_boundary, newest)
.await?;
let size = first_in_section(pruning_boundary, newest, items_per_blob) + tail_len;
Ok((size, None))
}
/// Recover by walking section lengths until the first short non-tail section.
///
/// This is the normal current-format crash-repair path. Legacy recovery uses it only when the
/// old rollover invariant is already violated or pruning metadata was stale.
async fn recover_by_walking_lengths(
inner: &mut SegmentedJournal<E, A>,
items_per_blob: u64,
pruning_boundary: u64,
) -> Result<(u64, Option<RecoveryRepair>), Error> {
let oldest = inner.oldest_section();
let newest = inner.newest_section();
let (Some(oldest), Some(newest)) = (oldest, newest) else {
return Ok((pruning_boundary, None));
};
// The oldest section's capacity was already checked before recovery mode dispatch.
let oldest_len = inner.section_len(oldest).await?;
let expected_oldest = section_capacity(pruning_boundary, oldest, items_per_blob);
let mut size = pruning_boundary + oldest_len;
if oldest == newest {
return Ok((size, None));
}
if oldest_len < expected_oldest {
return Ok((
size,
Some(RecoveryRepair {
section: oldest,
byte_offset: oldest_len * Self::CHUNK_SIZE_U64,
}),
));
}
for section in oldest + 1..=newest {
let (len, capacity) =
Self::section_len_within_capacity(inner, items_per_blob, pruning_boundary, section)
.await?;
size += len;
if len < capacity {
if section == newest {
return Ok((size, None));
}
return Ok((
size,
Some(RecoveryRepair {
section,
byte_offset: len * Self::CHUNK_SIZE_U64,
}),
));
}
}
Ok((size, None))
}
/// Initialize a new `Journal` instance in a pruned state at a given size.
///
/// This is used for state sync to create a journal that appears to have had `size` items
/// appended and then pruned up to that point.
///
/// # Arguments
/// * `context` - The storage context
/// * `cfg` - Configuration for the journal
/// * `size` - The number of operations that have been "pruned"
///
/// # Behavior
/// - Clears any existing data in the partition
/// - Creates an empty tail blob where the next append (at position `size`) will go
/// - `bounds().is_empty()` returns `true` (fully pruned state)
/// - The next `append()` will write to position `size`
///
/// # Post-conditions
/// - `bounds().end` returns `size`
/// - `bounds().is_empty()` returns `true`
/// - `bounds.start` equals `size` (no data exists)
///
/// # Crash Safety
/// If a crash occurs during this operation, `init()` will recover to a consistent state
/// (though possibly different from the intended `size`).
#[commonware_macros::stability(ALPHA)]
pub async fn init_at_size(context: E, cfg: Config, size: u64) -> Result<Self, Error> {
let items_per_blob = cfg.items_per_blob.get();
let tail_section = size / items_per_blob;
let blob_partition = Self::select_blob_partition(&context, &cfg).await?;
let segmented_cfg = SegmentedConfig {
partition: blob_partition,
page_cache: cfg.page_cache,
write_buffer: cfg.write_buffer,
};
let meta_cfg = MetadataConfig {
partition: format!("{}-metadata", cfg.partition),
codec_config: ((0..).into(), ()),
};
let mut metadata =
Metadata::<_, u64, Vec<u8>>::init(context.child("meta"), meta_cfg).await?;
let mut journal = SegmentedJournal::init(context.child("blobs"), segmented_cfg).await?;
if Self::update_metadata_watermark_before_clear(&mut metadata, size)? {
metadata.sync().await?;
}
journal.clear().await?;
journal.ensure_section_exists(tail_section).await?;
let mut inner = Inner {
journal,
size,
metadata,
pruning_boundary: size,
dirty_from_section: None,
};
Self::persist_metadata_entries(&mut inner, items_per_blob, size, size).await?;
let metrics = Metrics::new(context);
metrics.update(size, size, items_per_blob);
Ok(Self {
inner: AsyncRwLock::new(inner),
op_lock: AsyncMutex::new(()),
items_per_blob,
metrics,
})
}
/// Convert a global position to (section, position_in_section).
#[inline]
const fn position_to_section(&self, position: u64) -> (u64, u64) {
let section = position / self.items_per_blob;
let pos_in_section = position % self.items_per_blob;
(section, pos_in_section)
}
/// Fsync dirty sections under the read lock, allowing concurrent reads.
async fn fsync_dirty_sections(&self) -> Result<(), Error> {
let inner = self.inner.read().await;
if let Some(start_section) = inner.dirty_from_section {
let tail_section = inner.size / self.items_per_blob;
let start_section = inner
.journal
.oldest_section()
.map(|oldest| start_section.max(oldest))
// With no retained blobs, any earlier dirty section was cleared or pruned.
// Syncing the tail section is harmless when it does not exist.
.unwrap_or(tail_section);
for section in start_section..=tail_section {
inner.journal.sync(section).await?;
}
}
Ok(())
}