Repository navigation
Expand file tree
/
Copy pathgc.rs
More file actions
7613 lines (7228 loc) · 285 KB
/
Copy pathgc.rs
File metadata and controls
7613 lines (7228 loc) · 285 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
//! Manifest-aware garbage collection for immutable WAL and segment objects.
//!
//! Zeppelin never deletes an object merely because an S3/MinIO listing does
//! not match one in-memory view. The live
//! [`Manifest`][crate::wal::manifest::Manifest] is authoritative, every
//! retained manifest-history generation is an additional live root, and
//! uploads recorded by the active compaction lease are temporarily protected.
//! This module derives the exact union of those references, records known-shape
//! objects outside that union in a persisted
//! [`GcCandidate`][crate::compaction::gc::GcCandidate] ledger, and
//! revalidates the union before a later sweep physically deletes anything.
//!
//! [`run_gc_cycle`][crate::compaction::gc::run_gc_cycle] is called by the
//! background compaction loop before it considers new compaction work.
//! [`drain_pending_deletes`][crate::compaction::gc::drain_pending_deletes]
//! handles objects that an already-published manifest explicitly scheduled for
//! removal. The helper
//! [`reachable_keys`][crate::compaction::gc::reachable_keys] is also used by
//! namespace clone/restore and storage oracles that need the same artifact
//! vocabulary as GC.
//!
//! This file talks to object storage only through
//! [`ZeppelinStore`][crate::storage::ZeppelinStore]. It does not mutate query
//! caches or make a candidate ledger authoritative. A configured time horizon
//! protects readers that may still use a cached older manifest; the cache
//! itself remains disposable and is not consulted during deletion. There is no
//! dry-run mode: reports such as
//! [`GcCycleReport`][crate::compaction::gc::GcCycleReport] describe work already
//! attempted in the current cycle.
//!
//! ## Reading map
//!
//! 1. Start with [`reachable_keys`][crate::compaction::gc::reachable_keys] and
//! [`reachable_keys_with_staging`][crate::compaction::gc::reachable_keys_with_staging]
//! to see how a manifest becomes an exact object-key set.
//! 2. Read [`CompactionStaging`][crate::compaction::gc::CompactionStaging] and
//! [`active_staged_keys`][crate::compaction::gc::active_staged_keys] for the
//! upload-before-manifest safety bridge.
//! 3. Read [`GcCandidate`][crate::compaction::gc::GcCandidate] and
//! [`mark_gc_candidates`][crate::compaction::gc::mark_gc_candidates] for the
//! persisted mark pass.
//! 4. Read
//! [`drain_pending_deletes`][crate::compaction::gc::drain_pending_deletes]
//! for manifest-owned deferred deletion.
//! 5. Finish with [`run_gc_cycle`][crate::compaction::gc::run_gc_cycle] for
//! history pruning, mark persistence, fresh revalidation, and the batched
//! sweep.
//!
//! ## Authority and deletion flow
//!
//! ```text
//! live manifest on S3 -----------+
//! retained manifest history ----+---- exact reachable union
//! active-lease staged uploads ---+ |
//! | subtract from namespace LIST
//! v
//! persist candidate ledger (mark)
//! |
//! wait for configured time horizon
//! |
//! re-read manifest + history + active staging
//! | reachable/failure | still unreachable
//! v v
//! keep candidate DELETE immutable object
//! ```
//!
//! History pruning precedes artifact deletion. A generation protected by the
//! count window, PITR window, or a named snapshot therefore continues to pin
//! every object it references. Deletes use deterministic batches of at most
//! 1,000 keys and are not transactional across batches: a later failure can
//! follow earlier successful batches. Candidate and `pending_deletes` state
//! retain every member of an uncertain batch, and absence is an idempotent
//! completion.
//!
//! ## Invariants
//!
//! - The manifest-derived union, not LIST output or the candidate ledger,
//! decides reachability.
//! - Retained history and active compaction staging are live roots.
//! - Only recognized immutable artifact key shapes may enter the LIST-derived
//! candidate sweep; unfamiliar listed keys fail closed and remain in object
//! storage. Explicit manifest `pending_deletes` use their separate drain
//! contract.
//! - A candidate must survive the wall-clock horizon and a fresh reachability
//! check. Its embedded ULID must also be old enough.
//! - An object shared by carried clusters is collectible only after its last
//! manifest reference disappears.
//! - GC never edits immutable WAL or segment objects in place.
//!
//! ## Rust concepts used here
//!
//! [`BTreeSet`][std::collections::BTreeSet] represents mathematical key unions
//! and differences while
//! deduplicating shared artifacts and keeping reports deterministic. This is
//! closest to Java's `TreeSet`; in C it would require an explicitly owned set
//! implementation and cleanup discipline. Borrowed `&Manifest` and `&str`
//! parameters cannot be retained after a call, while returned sets and reports
//! are owned values. Async store calls borrow the shared
//! [`ZeppelinStore`][crate::storage::ZeppelinStore] gateway across `.await`; no
//! mutex guard or raw backend pointer is exposed. Rust enums make each
//! delete/skip outcome explicit and exhaustive instead of relying on integer
//! status codes as C code often would.
use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;
use bytes::Bytes;
use chrono::{DateTime, Utc};
use futures::future::BoxFuture;
use futures::{FutureExt, StreamExt};
use serde::{Deserialize, Serialize};
use tracing::{debug, info, warn};
use ulid::Ulid;
use crate::config::GcConfig;
use crate::error::{Result, ZeppelinError};
use crate::fts::global_index::global_fts_key;
use crate::fts::inverted_index::fts_index_key;
use crate::index::bitmap::bitmap_key;
use crate::index::hierarchical::tree_meta_key;
use crate::index::ivf_flat::build::{attrs_key, centroids_key, cluster_key};
use crate::index::quantization::pq::{pq_cluster_key, pq_codebook_key};
use crate::index::quantization::sq::{sq_calibration_key, sq_cluster_key};
use crate::index::quantization::QuantizationType;
use crate::namespace::branching::{ArtifactOrigin, BranchError};
use crate::namespace::manager::{NamespaceIncarnationId, NamespaceMetadata};
use crate::namespace::{BranchId, BranchRoot, ManifestDigest, ManifestGeneration};
use crate::security::{NamespaceId, PreservationService};
use crate::storage::capabilities::canonical_etag;
use crate::storage::store::DELETE_MANY_MAX_KEYS;
use crate::storage::{
ListedObject, NamespaceObjectFamily, NamespaceObjectKey, StorageVersion, ZeppelinStore,
};
use crate::wal::fragment::WalFragment;
use crate::wal::input_fragment::EncoderInputWalFragment;
use crate::wal::late_section::LateStateSection;
use crate::wal::manifest::{
Manifest, ManifestHistoryObservation, ManifestHistoryPruneResult, ManifestHistoryRetention,
ManifestVersion, NamedSnapshot, NamedSnapshotObservation,
};
use crate::wal::Lease;
/// Persisted JSON wrapper version written for new candidate ledgers.
pub(crate) const GC_CANDIDATE_STORE_VERSION: u32 = 1;
/// Maximum fresh-read/CAS attempts made while pruning `pending_deletes`.
const GC_MANIFEST_CAS_RETRIES: usize = 10;
/// Maximum number of reads polled concurrently within one variable-size GC batch.
const GC_READ_BATCH_CONCURRENCY: usize = 32;
/// Object-store key proven to belong to the namespace whose GC cycle may delete it.
///
/// Reachability may legitimately contain foreign physical keys. Destructive GC
/// paths must cross this classifier before calling `delete_many`, so a borrowed
/// source artifact can never become a target-owned deletion candidate by
/// accident.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
struct TargetOwnedDeletionKey {
target: NamespaceId,
key: String,
}
impl TargetOwnedDeletionKey {
fn classify(namespace: &str, key: String) -> Result<Self> {
let target = NamespaceId::new(namespace.to_string())?;
NamespaceObjectKey::classify(target.as_str(), key.clone()).map_err(|error| {
ZeppelinError::Serialization(format!(
"GC target {} cannot delete unowned key {key}: {error}",
target.as_str()
))
})?;
Ok(Self { target, key })
}
fn as_str(&self) -> &str {
&self.key
}
}
/// Exercise the same ownership classifier used by every destructive GC path.
#[cfg(feature = "branching-test-support")]
pub(crate) fn classify_target_owned_deletion_key_for_test_support(
namespace: &str,
key: String,
) -> Result<String> {
TargetOwnedDeletionKey::classify(namespace, key).map(|owned| owned.key)
}
async fn delete_target_owned_many(
store: &ZeppelinStore,
keys: &[TargetOwnedDeletionKey],
) -> Result<usize> {
debug_assert!(keys
.first()
.is_none_or(|first| keys.iter().all(|key| key.target == first.target)));
store
.delete_many(keys.iter().map(|key| key.key.clone()).collect())
.await
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum GcReadMode {
Sequential,
WarmBounded,
}
impl GcReadMode {
fn is_bounded(self) -> bool {
self == Self::WarmBounded
}
}
/// Process-local discriminator for one lifetime of a namespace name.
///
/// Namespace names can be deleted and recreated. A GC history memo therefore
/// belongs to the name and its authoritative per-create identity. Legacy
/// metadata without that identity falls back to its creation timestamp.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct GcNamespaceIncarnation {
name: String,
created_at: DateTime<Utc>,
incarnation_id: Option<NamespaceIncarnationId>,
}
impl GcNamespaceIncarnation {
/// Creates one process-local namespace incarnation identity.
#[must_use]
pub fn new(name: String, created_at: DateTime<Utc>) -> Self {
assert!(!name.is_empty(), "GC namespace incarnation cannot be empty");
Self {
name,
created_at,
incarnation_id: None,
}
}
/// Captures the lifecycle identity carried by an authoritative metadata GET.
#[must_use]
pub fn from_metadata(metadata: &NamespaceMetadata) -> Self {
assert!(
!metadata.name.is_empty(),
"GC namespace incarnation cannot be empty"
);
Self {
name: metadata.name.clone(),
created_at: metadata.created_at,
incarnation_id: metadata.incarnation_id.clone(),
}
}
#[cfg(test)]
pub(crate) fn with_incarnation_id(
name: String,
created_at: DateTime<Utc>,
incarnation_id: NamespaceIncarnationId,
) -> Self {
Self {
name,
created_at,
incarnation_id: Some(incarnation_id),
}
}
/// Returns the namespace name used for object-store keys.
#[must_use]
pub fn name(&self) -> &str {
&self.name
}
}
/// Stateful background GC entrypoint with a disposable validated history memo.
///
/// The runner owns no authority: every cycle freshly lists history metadata and
/// reuses a decoded body only when the exact key and nonempty S3 ETag match the
/// prior completed cycle. One-shot callers continue to use [`run_gc_cycle`] or
/// [`run_gc_cycle_at`] and therefore never retain process state.
pub struct GcRunner {
store: ZeppelinStore,
gc: GcConfig,
preservation: Option<Arc<PreservationService>>,
namespaces: BTreeMap<String, NamespaceGcMemo>,
}
#[derive(Debug, Clone)]
struct NamespaceGcMemo {
incarnation: GcNamespaceIncarnation,
history: BTreeMap<String, CachedHistory>,
inventory: Option<InventoryFingerprint>,
live_root_identity: LiveRootIdentity,
next_due_at: Option<DateTime<Utc>>,
last_now: DateTime<Utc>,
last_cycle_complete: bool,
candidate_phase_due: bool,
config: GcConfigFingerprint,
}
/// One validated recursive observation of every object below a namespace.
///
/// This is disposable routing state, never storage authority by itself. Root
/// bodies still have to be read and paired with their LIST-observed identity
/// before they can authorize a physical delete.
#[derive(Debug, Clone)]
struct NamespaceInventory {
objects: BTreeMap<String, ListedObject>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct InventoryFingerprint(BTreeMap<String, InventoryObjectFingerprint>);
/// Per-object identity inside an [`InventoryFingerprint`].
///
/// Holds the canonical ETag rather than the whole [`StorageVersion`]: memoized
/// inventories mix LIST-derived entries with PUT/GET-derived upserts (the
/// candidate ledger after a durable mark), and only the ETag is comparable
/// across those observation kinds — GCS carries its generation exclusively on
/// PUT/GET, so whole-token equality would report every idle cycle as changed
/// there. An object without an ETag yields no fingerprint (fail-closed).
#[derive(Debug, Clone, PartialEq, Eq)]
struct InventoryObjectFingerprint {
size: u64,
etag: String,
}
impl InventoryObjectFingerprint {
fn from_listed(object: &ListedObject) -> Option<Self> {
let etag = object.version.as_ref().and_then(StorageVersion::etag)?;
Some(Self {
size: object.size,
etag: canonical_etag(etag).to_string(),
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct GcConfigFingerprint {
horizon_secs: u64,
compaction_upload_window_secs: u64,
skew_slop_secs: u64,
allow_unsafe_short_horizon: bool,
manifest_history_keep_count: usize,
pitr_retention_secs: u64,
}
#[derive(Debug, Clone)]
struct CachedHistory {
storage_version: StorageVersion,
manifest: Manifest,
stored_bytes: Bytes,
reachable_keys: BTreeSet<String>,
}
#[derive(Debug)]
struct HistorySnapshot {
entries: Vec<(
ManifestHistoryObservation,
Manifest,
Bytes,
BTreeSet<String>,
)>,
cacheable: BTreeMap<String, CachedHistory>,
}
/// Exact authoritative live-manifest identity that supplied branch roots.
///
/// Root retention decisions are useful only while this complete observation
/// remains current. The ETag binds the stored bytes, while generation,
/// incarnation, and the root map make the safety-relevant state explicit for
/// review and memo invalidation.
#[derive(Debug, Clone, PartialEq, Eq)]
struct LiveRootIdentity {
storage_etag: String,
manifest_generation: u64,
namespace_incarnation: Option<uuid::Uuid>,
branch_roots: BTreeMap<BranchId, BranchRoot>,
}
/// One live-root observation plus the manifest used to validate rooted history.
///
/// The version is retained alongside the manifest so later phases of the same
/// cycle can reuse this authoritative read instead of issuing an identical GET.
/// [`LiveRootIdentity::matches_inventory`] decides when that reuse is sound.
#[derive(Debug, Clone)]
struct LiveRootObservation {
identity: LiveRootIdentity,
manifest: Manifest,
version: Box<ManifestVersion>,
rooted_generations: BTreeMap<ManifestGeneration, ManifestDigest>,
}
struct MemoizedHistoryPruneResult {
result: ManifestHistoryPruneResult,
retained_reachable_keys: BTreeSet<String>,
retained_history_observations: Vec<ManifestHistoryObservation>,
snapshot_observations: Vec<NamedSnapshotObservation>,
}
struct GcCycleOutcome {
report: GcCycleReport,
completed: Option<CompletedGcState>,
candidate_phase_due: bool,
}
struct CompletedGcState {
history: BTreeMap<String, CachedHistory>,
inventory: Option<InventoryFingerprint>,
live_root_identity: LiveRootIdentity,
next_due_at: Option<DateTime<Utc>>,
}
impl GcCycleOutcome {
fn incomplete(report: GcCycleReport) -> Self {
Self {
report,
completed: None,
candidate_phase_due: false,
}
}
fn incomplete_with_candidate_phase(report: GcCycleReport) -> Self {
Self {
report,
completed: None,
candidate_phase_due: true,
}
}
fn complete(report: GcCycleReport, completed: CompletedGcState) -> Self {
Self {
report,
completed: Some(completed),
candidate_phase_due: false,
}
}
}
impl LiveRootObservation {
fn from_authority(
namespace: &str,
manifest: Manifest,
version: ManifestVersion,
) -> Result<Self> {
let storage_etag = version
.require_etag(namespace, "GC live branch-root observation")?
.to_string();
let rooted_generations = manifest.rooted_generations()?;
let identity = LiveRootIdentity {
storage_etag,
manifest_generation: manifest.version(),
namespace_incarnation: manifest.namespace_incarnation(),
branch_roots: manifest.branch_roots().clone(),
};
Ok(Self {
identity,
manifest,
version: Box::new(version),
rooted_generations,
})
}
}
impl LiveRootIdentity {
fn matches_inventory(&self, namespace: &str, inventory: &NamespaceInventory) -> bool {
inventory
.object(&Manifest::object_store_key(namespace))
.and_then(|object| object.version.as_ref())
.and_then(StorageVersion::etag)
.map(canonical_etag)
== Some(canonical_etag(&self.storage_etag))
}
}
async fn load_live_root_observation(
store: &ZeppelinStore,
namespace: &str,
inventory: Option<&NamespaceInventory>,
) -> Result<Option<LiveRootObservation>> {
let observed = match inventory {
Some(inventory) => {
read_versioned_manifest_from_inventory(store, namespace, inventory).await?
}
None => Manifest::read_versioned(store, namespace).await?,
};
observed
.map(|(manifest, version)| {
LiveRootObservation::from_authority(namespace, manifest, version)
})
.transpose()
}
async fn revalidate_live_root_observation(
store: &ZeppelinStore,
namespace: &str,
expected: &LiveRootObservation,
) -> Result<()> {
let Some((manifest, version)) = Manifest::read_versioned(store, namespace).await? else {
return Err(ZeppelinError::Serialization(format!(
"namespace {namespace} live manifest disappeared during GC root observation"
)));
};
let actual = LiveRootObservation::from_authority(namespace, manifest, version)?;
if actual.identity != expected.identity {
return Err(ZeppelinError::ManifestConflict {
namespace: namespace.to_string(),
});
}
Ok(())
}
impl InventoryFingerprint {
fn from_listed<'a>(objects: impl IntoIterator<Item = &'a ListedObject>) -> Option<Self> {
let mut entries = BTreeMap::new();
for object in objects {
let fingerprint = InventoryObjectFingerprint::from_listed(object)?;
if entries.insert(object.key.clone(), fingerprint).is_some() {
return None;
}
}
Some(Self(entries))
}
fn matches_listed_prefix<'a>(
&self,
prefix: &str,
listed: impl IntoIterator<Item = &'a ListedObject>,
) -> bool {
let mut expected = BTreeMap::new();
for object in listed {
let Some(fingerprint) = InventoryObjectFingerprint::from_listed(object) else {
return false;
};
if !object.key.starts_with(prefix)
|| expected.insert(object.key.clone(), fingerprint).is_some()
{
return false;
}
}
let actual = self
.0
.iter()
.filter(|(key, _)| key.starts_with(prefix))
.map(|(key, value)| (key.clone(), value.clone()))
.collect::<BTreeMap<_, _>>();
actual == expected
}
}
fn malformed_control_key(
family: &'static str,
key: impl Into<String>,
reason: impl Into<String>,
) -> ZeppelinError {
ZeppelinError::MalformedControlKey {
family,
key: key.into(),
reason: reason.into(),
}
}
fn listed_object_identity_matches(before: &ListedObject, after: &ListedObject) -> bool {
// One side of this comparison may be PUT/GET-derived (e.g. the candidate
// ledger identity recorded after a durable mark) while the other is
// LIST-derived. Only the ETag is comparable across those observation
// kinds — GCS carries its generation exclusively on PUT/GET, so full
// `StorageVersion` equality would declare every cross-kind pair changed
// and permanently skip the sweep there. Compare canonical ETags; either
// side lacking one means "cannot validate" and stays fail-closed.
before.size == after.size
&& before
.version
.as_ref()
.and_then(StorageVersion::etag)
.zip(after.version.as_ref().and_then(StorageVersion::etag))
.is_some_and(|(before, after)| canonical_etag(before) == canonical_etag(after))
}
fn listed_object_horizon_satisfied(
object: &ListedObject,
now: DateTime<Utc>,
horizon_secs: u64,
) -> bool {
if horizon_secs == 0 {
return true;
}
let Ok(horizon_secs) = i64::try_from(horizon_secs) else {
return false;
};
object
.last_modified
.checked_add_signed(chrono::Duration::seconds(horizon_secs))
.is_some_and(|deadline| now >= deadline)
}
impl NamespaceInventory {
fn from_listed(namespace: &str, listed: Vec<ListedObject>) -> Result<Self> {
let history_prefix = Manifest::history_prefix(namespace);
let snapshot_prefix = NamedSnapshot::prefix(namespace);
let staging_prefix = NamespaceObjectFamily::Staging.namespace_prefix(namespace);
let gc_prefix = format!(
"{namespace}/{}",
NamespaceObjectFamily::Gc.relative_root_prefix()
);
let candidate_key = gc_candidate_store_key(namespace);
let mut objects = BTreeMap::new();
let mut history_objects = Vec::new();
let mut snapshot_objects = Vec::new();
for object in listed {
NamespaceObjectKey::classify(namespace, object.key.clone())?;
if object.key.starts_with(&history_prefix) {
history_objects.push(object.clone());
} else if object.key.starts_with(&snapshot_prefix) {
snapshot_objects.push(object.clone());
} else if let Some(suffix) = object.key.strip_prefix(&staging_prefix) {
let Some(token) = suffix.strip_suffix(".json") else {
return Err(malformed_control_key(
"staging",
object.key,
"key must end with .json",
));
};
let token = token.parse::<u64>().map_err(|_| {
malformed_control_key(
"staging",
object.key.clone(),
"key must contain a decimal fencing token",
)
})?;
if staging_key(namespace, token) != object.key {
return Err(malformed_control_key(
"staging",
object.key,
"key is not canonical",
));
}
} else if object.key.starts_with(&gc_prefix) && object.key != candidate_key {
return Err(malformed_control_key(
"gc",
object.key,
"unrecognized reserved key",
));
}
let duplicate_key = object.key.clone();
if objects.insert(object.key.clone(), object).is_some() {
return Err(malformed_control_key(
"namespace-inventory",
duplicate_key,
"duplicate key",
));
}
}
// Delegate reserved-key grammar to the modules that own it. These
// parsers validate the full batch before any retention DELETE begins.
Manifest::history_observations_from_listed(namespace, history_objects)?;
NamedSnapshot::validate_listed_objects(namespace, snapshot_objects)?;
Ok(Self { objects })
}
fn fingerprint(&self) -> Option<InventoryFingerprint> {
InventoryFingerprint::from_listed(self.objects.values())
}
fn all_objects(&self) -> Vec<ListedObject> {
self.objects.values().cloned().collect()
}
fn all_keys(&self) -> BTreeSet<String> {
self.objects.keys().cloned().collect()
}
fn object(&self, key: &str) -> Option<&ListedObject> {
self.objects.get(key)
}
fn history_observations(&self, namespace: &str) -> Result<Vec<ManifestHistoryObservation>> {
let prefix = Manifest::history_prefix(namespace);
Manifest::history_observations_from_listed(
namespace,
self.objects
.range(prefix.clone()..)
.take_while(|(key, _)| key.starts_with(&prefix))
.map(|(_, object)| object.clone())
.collect(),
)
}
fn snapshot_objects(&self, namespace: &str) -> Result<Vec<ListedObject>> {
let prefix = NamedSnapshot::prefix(namespace);
NamedSnapshot::validate_listed_objects(
namespace,
self.objects
.range(prefix.clone()..)
.take_while(|(key, _)| key.starts_with(&prefix))
.map(|(_, object)| object.clone())
.collect(),
)
}
fn staging_objects(&self, namespace: &str) -> Vec<ListedObject> {
let prefix = NamespaceObjectFamily::Staging.namespace_prefix(namespace);
self.objects
.range(prefix.clone()..)
.take_while(|(key, _)| key.starts_with(&prefix))
.map(|(_, object)| object.clone())
.collect()
}
fn remove(&mut self, key: &str) {
self.objects.remove(key);
}
fn upsert(&mut self, key: String, size: u64, version: Option<StorageVersion>) {
self.objects.insert(
key.clone(),
ListedObject {
key,
size,
last_modified: Utc::now(),
version,
},
);
}
fn matches_listed_prefix<'a>(
&self,
prefix: &str,
listed: impl IntoIterator<Item = &'a ListedObject>,
) -> bool {
self.fingerprint()
.is_some_and(|fingerprint| fingerprint.matches_listed_prefix(prefix, listed))
}
}
impl From<&GcConfig> for GcConfigFingerprint {
fn from(gc: &GcConfig) -> Self {
let GcConfig {
horizon_secs,
compaction_upload_window_secs,
skew_slop_secs,
allow_unsafe_short_horizon,
manifest_history_keep_count,
pitr_retention_secs,
} = gc;
Self {
horizon_secs: *horizon_secs,
compaction_upload_window_secs: *compaction_upload_window_secs,
skew_slop_secs: *skew_slop_secs,
allow_unsafe_short_horizon: *allow_unsafe_short_horizon,
manifest_history_keep_count: *manifest_history_keep_count,
pitr_retention_secs: *pitr_retention_secs,
}
}
}
/// Lease-scoped record of compaction uploads not yet committed to a manifest.
///
/// The record is a temporary GC root, not a visibility mechanism: queries do
/// not read its keys. A staging object is useful only while its fencing token
/// matches the unexpired namespace lease observed by [`active_staged_keys`].
///
/// The type is encoded as self-describing JSON so its named fields can evolve
/// without depending on a positional binary layout.
///
/// # Examples
///
/// During lease token 17, a compactor can record the centroid and cluster keys
/// it uploaded. The record protects those keys from GC but does not make the
/// unfinished segment query-visible.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct CompactionStaging {
/// Fencing token of the lease holder that owns these in-flight uploads.
pub fencing_token: u64,
/// Exact object keys uploaded by compaction but not yet manifest-visible.
#[serde(default)]
pub keys: BTreeSet<String>,
}
struct ActiveStagingObservation {
keys: BTreeSet<String>,
lease_expires_at: Option<DateTime<Utc>>,
}
/// Builds the object key for one lease holder's compaction staging record.
///
/// # Parameters
///
/// - `namespace`: Namespace that owns the compaction and lease.
/// - `fencing_token`: Monotonic token assigned to that lease acquisition.
///
/// # Returns
///
/// An owned key under `<namespace>/_staging/`, ending in `.json`.
///
/// # Examples
///
/// Namespace `catalog` with fencing token `17` maps to
/// `catalog/_staging/17.json`.
#[must_use]
pub fn staging_key(namespace: &str, fencing_token: u64) -> String {
format!(
"{}{fencing_token}.json",
NamespaceObjectFamily::Staging.namespace_prefix(namespace)
)
}
fn local_artifact_origin_for_gc(
namespace: &str,
manifest: &Manifest,
) -> Result<Option<ArtifactOrigin>> {
let has_explicit_origins = !manifest.artifact_origins.is_empty()
|| manifest
.fragments
.iter()
.any(|fragment| fragment.artifact_origin.is_some())
|| manifest
.segments
.iter()
.any(|segment| segment.artifact_origin.is_some())
|| manifest
.input_fragments
.iter()
.any(|fragment| fragment.artifact_origin.is_some())
|| manifest
.late_state
.as_ref()
.is_some_and(|reference| reference.artifact_origin.is_some());
let Some(incarnation) = manifest.namespace_incarnation() else {
if has_explicit_origins {
return Err(ZeppelinError::Serialization(format!(
"manifest for namespace {namespace} has artifact origins but no local incarnation"
)));
}
return Ok(None);
};
Ok(Some(ArtifactOrigin {
namespace: NamespaceId::new(namespace.to_string())?,
incarnation: NamespaceIncarnationId::from_uuid(incarnation),
}))
}
/// Derives every immutable artifact key referenced by one manifest.
///
/// This pure function expands WAL fragments, segment metadata, cluster data,
/// attribute sidecars, bitmap/FTS indexes, quantization artifacts, and
/// `pending_deletes`. Pending-delete keys remain protected until the drain path
/// confirms their deletion and conditionally removes them from the manifest.
/// The returned set does not include the manifest object, history objects, GC
/// ledgers, leases, or staging records themselves; their key families are not
/// sweepable artifact shapes.
///
/// # Parameters
///
/// - `namespace`: Namespace prefix used by deterministic artifact-key helpers.
/// - `manifest`: Borrowed manifest snapshot whose references should be expanded.
///
/// # Returns
///
/// A lexicographically ordered, duplicate-free owned set of exact object keys.
/// Shared carried-cluster objects appear once.
///
/// # Errors
///
/// Returns an artifact-origin integrity error when an indexed reference cannot
/// be resolved or an explicit stored key falls outside its declared physical
/// origin. Legacy local-only manifests remain namespace-routed.
///
/// # Consistency
///
/// The result describes the supplied snapshot, not necessarily the current
/// manifest by the time the caller uses it. Delete callers must obtain a fresh
/// authoritative snapshot immediately before deciding.
///
/// # Performance
///
/// Performs no object-store I/O. Work and memory are proportional to fragments,
/// segments, clusters, and enabled sidecar families in the manifest, with
/// `BTreeSet` insertion costing `O(log n)` per distinct key.
///
/// # Examples
///
/// A two-cluster scalar-quantized segment contributes its tree or centroid
/// metadata, two cluster and attribute objects, two scalar-code objects, and
/// one calibration object. If both clusters reuse one carried object, that key
/// remains present only once.
///
/// # Rust Notes for Java/C Engineers
///
/// `&Manifest` is a temporary shared borrow, similar to a read-only Java
/// reference or `const Manifest *` in C, but Rust also guarantees it is non-null
/// and valid for the call. The returned [`BTreeSet`] owns cloned key strings and
/// therefore remains valid after the manifest borrow ends.
pub fn reachable_keys(namespace: &str, manifest: &Manifest) -> Result<BTreeSet<String>> {
reachable_keys_with_staging(namespace, manifest, &BTreeSet::new())
}
/// Expand root-manifest artifacts plus a checked, decoded late-state section.
///
/// Version-2 sections carry source inventory outside the root manifest, so
/// destructive callers must load the selected section and use this function.
pub fn reachable_keys_with_late_state(
namespace: &str,
manifest: &Manifest,
late_state: Option<&LateStateSection>,
) -> Result<BTreeSet<String>> {
reachable_keys_with_staging_and_late_state(namespace, manifest, &BTreeSet::new(), late_state)
}
fn reachable_keys_with_staging_and_late_state(
namespace: &str,
manifest: &Manifest,
staging: &BTreeSet<String>,
late_state: Option<&LateStateSection>,
) -> Result<BTreeSet<String>> {
let mut keys = reachable_keys_with_staging(namespace, manifest, staging)?;
match (manifest.late_state.as_ref(), late_state) {
(None, None) => {}
(None, Some(_)) => {
return Err(ZeppelinError::Serialization(
"late-state section supplied without a manifest reference".to_string(),
));
}
(Some(reference), None) if reference.format_version >= 2 => {
return Err(ZeppelinError::Serialization(
"version-2 late-state reachability requires the decoded section".to_string(),
));
}
(Some(_), None) => {}
(Some(reference), Some(section)) => {
let section_origin = manifest.late_section_origin(reference)?;
section.validate_for_origin(§ion_origin)?;
for artifact in section.resolved_artifacts(§ion_origin)? {
let owned = NamespaceObjectKey::classify(
artifact.origin.namespace.as_str(),
&artifact.key,
)?;
if owned.family() != artifact.family {
return Err(ZeppelinError::Validation(format!(
"late-state key is outside its registered {:?} family: {}",
artifact.family, artifact.key
)));
}
keys.insert(artifact.key);
}
}
}
Ok(keys)
}
async fn reachable_keys_with_loaded_late_state(
store: &ZeppelinStore,
namespace: &str,
manifest: &Manifest,
staging: &BTreeSet<String>,
) -> Result<BTreeSet<String>> {
let late_state = manifest.load_late_state(store).await?;
reachable_keys_with_staging_and_late_state(namespace, manifest, staging, late_state.as_ref())
}
/// Unions one manifest's references with caller-validated staged uploads.
///
/// The caller is responsible for supplying only keys belonging to the active,
/// unexpired lease; [`active_staged_keys`] performs that validation for normal
/// GC use. Staged keys are protected from deletion but do not become visible to
/// query readers.
///
/// # Parameters
///
/// - `namespace`: Namespace prefix for manifest-derived artifact keys.
/// - `manifest`: Borrowed manifest snapshot to expand.
/// - `staging`: Borrowed exact keys currently protected by compaction staging.
///
/// # Returns
///
/// An owned, ordered union containing manifest and staged keys exactly once.
///
/// # Errors
///
/// Returns an artifact-origin integrity error rather than deriving any
/// unresolved immutable key from the logical namespace.
///
/// # Consistency
///
/// This is a snapshot calculation. Sweep code re-reads both authoritative
/// manifest state and active staging rather than trusting an earlier union.
///
/// # Examples
///
/// If the manifest references segment A while the active compactor has
/// uploaded two objects for segment B, the result protects A and both B objects;
/// only A is query-visible.
pub fn reachable_keys_with_staging(
namespace: &str,
manifest: &Manifest,
staging: &BTreeSet<String>,
) -> Result<BTreeSet<String>> {
let mut keys = BTreeSet::new();
let local_origin = local_artifact_origin_for_gc(namespace, manifest)?;