Skip to main content

engenho_controllers/
tiered_reconciler.rs

1//! `TieredCacheReconciler` — proactive promotion across cache tiers.
2//!
3//! Complement to `TieredCache`'s on-read promotion: this controller
4//! sweeps lower-tier entries that haven't yet reached upper tiers
5//! + fans them out. Useful when the operator's `PromotionPolicy` is
6//! Lazy or `SampleRate` (which deliberately skip on-read promotion).
7//!
8//! ## Reconcile rule
9//!
10//! For a configured set of (`drv_hash`, `output_name`) of interest:
11//!   1. Walk all tiers via separate handles (NOT through the
12//!      tiered facade — we need per-tier visibility).
13//!   2. For each item present in tier `i` but absent in tier `j<i`,
14//!      copy the bytes from `i` → `j`.
15//!   3. Report per-tier promotion counts via `ReconcileReport`.
16//!
17//! ## Configuring "items of interest"
18//!
19//! The controller doesn't sweep the whole drv-space (that's
20//! O(cluster-wide). Instead it consults a [`PromotionScope`]
21//! trait that yields drv hashes worth promoting (e.g. from a
22//! `DerivationCR` list, from a watched-cache subscription, from
23//! a static config of "always-cache-locally" pins).
24
25use std::sync::Arc;
26
27use async_trait::async_trait;
28use engenho_substrate::{DerivationCacheBackend, DrvHash};
29
30use crate::controller::{Controller, ReconcileOutcome, ReconcileReport};
31use crate::effect::Effect;
32use crate::error::ControllerError;
33
34/// Source of "items of interest" for proactive promotion.
35#[async_trait]
36pub trait PromotionScope: Send + Sync {
37    /// Drv hashes the controller should keep promoted to high tiers.
38    /// Returning an empty Vec is fine (controller is a no-op).
39    ///
40    /// # Errors
41    /// Implementations may surface I/O or backend errors.
42    async fn drv_hashes_of_interest(&self) -> Result<Vec<DrvHash>, ControllerError>;
43}
44
45/// Static scope — fixed list of pins.
46pub struct StaticPromotionScope {
47    pins: Vec<DrvHash>,
48}
49
50impl StaticPromotionScope {
51    /// New scope from a list of drv hashes.
52    #[must_use]
53    pub fn new(pins: Vec<DrvHash>) -> Self {
54        Self { pins }
55    }
56}
57
58#[async_trait]
59impl PromotionScope for StaticPromotionScope {
60    async fn drv_hashes_of_interest(&self) -> Result<Vec<DrvHash>, ControllerError> {
61        Ok(self.pins.clone())
62    }
63}
64
65/// Reconciler controller.
66pub struct TieredCacheReconciler {
67    /// Tiers ordered fastest-to-slowest (same convention as `TieredCache`).
68    tiers: Vec<Arc<dyn DerivationCacheBackend>>,
69    scope: Arc<dyn PromotionScope>,
70}
71
72impl TieredCacheReconciler {
73    /// New reconciler.
74    #[must_use]
75    pub fn new(
76        tiers: Vec<Arc<dyn DerivationCacheBackend>>,
77        scope: Arc<dyn PromotionScope>,
78    ) -> Self {
79        Self { tiers, scope }
80    }
81
82    /// Tier count.
83    #[must_use]
84    pub fn tier_count(&self) -> usize {
85        self.tiers.len()
86    }
87}
88
89#[async_trait]
90impl Controller for TieredCacheReconciler {
91    fn name(&self) -> &'static str {
92        "tiered-cache-reconciler"
93    }
94
95    async fn tick(&self) -> Result<ReconcileOutcome, ControllerError> {
96        let mut report = ReconcileReport::default();
97        if self.tiers.len() < 2 {
98            // No promotion possible with < 2 tiers.
99            return Ok(report.into());
100        }
101        let pins = self.scope.drv_hashes_of_interest().await?;
102        report.objects_examined = pins.len();
103
104        for hash in &pins {
105            // Find the highest tier index that holds this drv.
106            // (highest = LARGEST idx = slowest tier; we promote
107            // toward idx 0 = fastest.)
108            let mut authoritative_idx: Option<usize> = None;
109            for (idx, tier) in self.tiers.iter().enumerate().rev() {
110                let exists = tier
111                    .get_drv(hash)
112                    .await
113                    .map_err(|e| ControllerError::Internal(e.to_string()))?
114                    .is_some();
115                if exists {
116                    authoritative_idx = Some(idx);
117                    break;
118                }
119            }
120            // If found, walk down to all faster tiers + promote where missing.
121            if let Some(src_idx) = authoritative_idx {
122                let drv = self.tiers[src_idx]
123                    .get_drv(hash)
124                    .await
125                    .map_err(|e| ControllerError::Internal(e.to_string()))?
126                    .expect("just verified existence");
127                // Also fetch realisations to promote them.
128                let realisations = self.tiers[src_idx]
129                    .list_realisations(hash)
130                    .await
131                    .map_err(|e| ControllerError::Internal(e.to_string()))?;
132
133                for dst_idx in 0..src_idx {
134                    // Promote drv if missing.
135                    let exists = self.tiers[dst_idx]
136                        .get_drv(hash)
137                        .await
138                        .map_err(|e| ControllerError::Internal(e.to_string()))?
139                        .is_some();
140                    if !exists {
141                        let applied = Effect::applied(self.tiers[dst_idx].put_drv(&drv).await)
142                            .map_err(|e| ControllerError::Internal(e.to_string()))?;
143                        report.record(applied);
144                    }
145                    // Promote realisations (idempotent — backend dedupes by output_name).
146                    for r in &realisations {
147                        self.tiers[dst_idx]
148                            .put_realisation(r)
149                            .await
150                            .map_err(|e| ControllerError::Internal(e.to_string()))?;
151                    }
152                }
153            }
154        }
155        Ok(report.into())
156    }
157}
158
159#[cfg(test)]
160mod tests {
161    use super::*;
162    use engenho_substrate::{Drv, MemoryDerivationCache, OutputPath, Realisation};
163
164    fn arc_mem() -> Arc<dyn DerivationCacheBackend> {
165        Arc::new(MemoryDerivationCache::new())
166    }
167
168    fn sample_drv(tag: &[u8]) -> Drv {
169        Drv::synthetic(DrvHash::from_bytes(tag), "x86_64-linux")
170    }
171
172    #[tokio::test]
173    async fn empty_scope_no_changes() {
174        let r = TieredCacheReconciler::new(
175            vec![arc_mem(), arc_mem()],
176            Arc::new(StaticPromotionScope::new(vec![])),
177        );
178        let report = r.tick().await.unwrap();
179        assert_eq!(report.objects_changed, 0);
180    }
181
182    #[tokio::test]
183    async fn single_tier_no_promotion() {
184        let only = arc_mem();
185        only.put_drv(&sample_drv(b"x")).await.unwrap();
186        let r = TieredCacheReconciler::new(
187            vec![only],
188            Arc::new(StaticPromotionScope::new(vec![DrvHash::from_bytes(b"x")])),
189        );
190        let report = r.tick().await.unwrap();
191        assert_eq!(report.objects_changed, 0);
192    }
193
194    #[tokio::test]
195    async fn promotes_drv_from_slow_to_fast_tier() {
196        let l0 = arc_mem();
197        let l1 = arc_mem();
198        let drv = sample_drv(b"promote-me");
199        // Only in L1.
200        l1.put_drv(&drv).await.unwrap();
201        let r = TieredCacheReconciler::new(
202            vec![l0.clone(), l1.clone()],
203            Arc::new(StaticPromotionScope::new(vec![drv.drv_hash.clone()])),
204        );
205        let report = r.tick().await.unwrap();
206        assert_eq!(report.objects_changed, 1);
207        // L0 now has the drv too.
208        assert!(l0.get_drv(&drv.drv_hash).await.unwrap().is_some());
209    }
210
211    #[tokio::test]
212    async fn idempotent_when_already_present_everywhere() {
213        let l0 = arc_mem();
214        let l1 = arc_mem();
215        let drv = sample_drv(b"x");
216        l0.put_drv(&drv).await.unwrap();
217        l1.put_drv(&drv).await.unwrap();
218        let r = TieredCacheReconciler::new(
219            vec![l0, l1],
220            Arc::new(StaticPromotionScope::new(vec![drv.drv_hash])),
221        );
222        let report = r.tick().await.unwrap();
223        assert_eq!(report.objects_changed, 0);
224    }
225
226    #[tokio::test]
227    async fn promotes_realisations_alongside_drvs() {
228        let l0 = arc_mem();
229        let l1 = arc_mem();
230        let drv = sample_drv(b"d");
231        l1.put_drv(&drv).await.unwrap();
232        l1.put_realisation(&Realisation {
233            drv_hash: drv.drv_hash.clone(),
234            output_name: "out".into(),
235            output_path: OutputPath::new("/nix/store/a"),
236            nar_hash: None,
237        })
238        .await
239        .unwrap();
240        let r = TieredCacheReconciler::new(
241            vec![l0.clone(), l1.clone()],
242            Arc::new(StaticPromotionScope::new(vec![drv.drv_hash.clone()])),
243        );
244        let _ = r.tick().await.unwrap();
245        let l0_rs = l0.list_realisations(&drv.drv_hash).await.unwrap();
246        assert_eq!(l0_rs.len(), 1);
247        assert_eq!(l0_rs[0].output_name, "out");
248    }
249
250    #[tokio::test]
251    async fn three_tier_promotion_walks_down_from_authoritative() {
252        let l0 = arc_mem();
253        let l1 = arc_mem();
254        let l2 = arc_mem();
255        let drv = sample_drv(b"three-tier");
256        // Only in L2 (slowest).
257        l2.put_drv(&drv).await.unwrap();
258        let r = TieredCacheReconciler::new(
259            vec![l0.clone(), l1.clone(), l2.clone()],
260            Arc::new(StaticPromotionScope::new(vec![drv.drv_hash.clone()])),
261        );
262        let report = r.tick().await.unwrap();
263        // Both L0 and L1 promoted = 2 changes.
264        assert_eq!(report.objects_changed, 2);
265        assert!(l0.get_drv(&drv.drv_hash).await.unwrap().is_some());
266        assert!(l1.get_drv(&drv.drv_hash).await.unwrap().is_some());
267    }
268
269    #[tokio::test]
270    async fn missing_drv_in_any_tier_silently_skipped() {
271        let l0 = arc_mem();
272        let l1 = arc_mem();
273        // Nothing in either tier.
274        let r = TieredCacheReconciler::new(
275            vec![l0.clone(), l1.clone()],
276            Arc::new(StaticPromotionScope::new(vec![DrvHash::from_bytes(
277                b"void",
278            )])),
279        );
280        let report = r.tick().await.unwrap();
281        assert_eq!(report.objects_changed, 0);
282        assert!(
283            l0.get_drv(&DrvHash::from_bytes(b"void"))
284                .await
285                .unwrap()
286                .is_none()
287        );
288    }
289
290    #[tokio::test]
291    async fn tier_count_helper() {
292        let r = TieredCacheReconciler::new(
293            vec![arc_mem(), arc_mem(), arc_mem()],
294            Arc::new(StaticPromotionScope::new(vec![])),
295        );
296        assert_eq!(r.tier_count(), 3);
297    }
298
299    #[tokio::test]
300    async fn controller_name_is_stable() {
301        let r = TieredCacheReconciler::new(
302            vec![arc_mem()],
303            Arc::new(StaticPromotionScope::new(vec![])),
304        );
305        assert_eq!(r.name(), "tiered-cache-reconciler");
306    }
307}