pipedash-core 0.8.0

Framework-agnostic core library for Pipedash
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
use std::sync::{
    Arc,
    Weak,
};
use std::time::Duration;

use chrono::{
    DateTime,
    Utc,
};
use tokio::time::{
    sleep,
    sleep_until,
    timeout,
    Instant,
};

use super::{
    failed_outcome,
    PipelineService,
    FETCH_TIMEOUT_MESSAGE,
};
use crate::application::fetch_scheduler::{
    FetchClaim,
    FetchResult,
    ForcedClaim,
    Generation,
};
use crate::application::{
    ClaimKind,
    HealthInput,
    Outcome,
};
use crate::domain::{
    DomainError,
    DomainResult,
    FailureKind,
    Pipeline,
    PipelineRun,
    PipelineStatus,
};

const RUN_WATCH_INTERVAL: Duration = Duration::from_secs(10);

#[derive(Debug)]
pub struct WatchedRun {
    pub pipeline: Pipeline,
    pub provider_name: String,
    pub run: PipelineRun,
    pub observed_at: DateTime<Utc>,
}

pub struct RunWatch {
    service: Weak<PipelineService>,
    pipeline_id: String,
    provider_id: i64,
    generation: Generation,
    run_number: i64,
    next_attempt: Instant,
    finished: bool,
}

struct RunAttempt(Option<FetchClaim>);

impl Drop for RunAttempt {
    fn drop(&mut self) {
        if let Some(claim) = self.0.take() {
            claim.release();
        }
    }
}

impl PipelineService {
    pub async fn watch_run(
        self: &Arc<Self>, pipeline_id: String, run_number: i64,
    ) -> DomainResult<RunWatch> {
        if run_number <= 0 {
            return Err(DomainError::InvalidConfig(
                "Choose a positive run number".to_string(),
            ));
        }
        let pipeline = self
            .repository
            .get_cached_pipelines(None)
            .await?
            .into_iter()
            .find(|pipeline| pipeline.id == pipeline_id)
            .ok_or_else(|| DomainError::PipelineNotFound(pipeline_id.clone()))?;
        let lease = self.provider_service.acquire(pipeline.provider_id).await?;
        Ok(RunWatch {
            service: Arc::downgrade(self),
            pipeline_id,
            provider_id: pipeline.provider_id,
            generation: lease.generation,
            run_number,
            next_attempt: Instant::now(),
            finished: false,
        })
    }
}

impl RunWatch {
    pub fn provider_id(&self) -> i64 {
        self.provider_id
    }

    pub async fn next(&mut self) -> Option<DomainResult<WatchedRun>> {
        if self.finished {
            return None;
        }
        sleep_until(self.next_attempt).await;
        let result = match self.service.upgrade() {
            Some(service) => timeout(PipelineService::REFRESH_DEADLINE, self.observe(&service))
                .await
                .unwrap_or_else(|_| Err(DomainError::Timeout(FETCH_TIMEOUT_MESSAGE.to_string()))),
            None => Err(superseded()),
        };
        self.finished = match &result {
            Ok(observed) => !matches!(
                observed.run.status,
                PipelineStatus::Pending | PipelineStatus::Running
            ),
            Err(_) => true,
        };
        self.next_attempt = Instant::now() + RUN_WATCH_INTERVAL;
        Some(result)
    }

    async fn observe(&self, service: &PipelineService) -> DomainResult<WatchedRun> {
        loop {
            let lease = service.provider_service.acquire(self.provider_id).await?;
            if lease.generation != self.generation {
                return Err(superseded());
            }
            if let Some(until) = service.scheduler.paused_until(self.provider_id, Utc::now()) {
                return Err(rate_limited((until - Utc::now()).to_std().ok()));
            }
            let claim = match service.scheduler.claim_forced(
                self.provider_id,
                self.generation,
                Instant::now(),
            ) {
                ForcedClaim::Claimed(claim) => claim,
                ForcedClaim::Joined(handle) => {
                    drop(lease);
                    handle.wait().await;
                    continue;
                }
                ForcedClaim::Recent(Outcome::Failed {
                    kind: FailureKind::RateLimited,
                    ..
                }) => {
                    let retry_after = service
                        .scheduler
                        .forced_retry_in(self.provider_id, self.generation, Instant::now())
                        .ok_or_else(superseded)?;
                    return Err(rate_limited(Some(retry_after)));
                }
                ForcedClaim::Recent(_) => {
                    let wait = service
                        .scheduler
                        .forced_retry_in(self.provider_id, self.generation, Instant::now())
                        .ok_or_else(superseded)?;
                    drop(lease);
                    sleep(wait).await;
                    continue;
                }
                ForcedClaim::Refused => return Err(superseded()),
            };
            let mut attempt = RunAttempt(Some(claim));
            let permit = service
                .acquire_permit(ClaimKind::Forced)
                .await
                .ok_or_else(superseded)?;
            if service
                .provider_service
                .commit(&lease, || async {})
                .await
                .is_none()
            {
                return Err(superseded());
            }
            if let Some(until) = service.provider_service.check_quota(&lease).await {
                return Err(rate_limited((until - Utc::now()).to_std().ok()));
            }
            let pipeline = service
                .repository
                .get_cached_pipelines(Some(self.provider_id))
                .await?
                .into_iter()
                .find(|pipeline| {
                    pipeline.id == self.pipeline_id && pipeline.provider_id == self.provider_id
                })
                .ok_or_else(|| DomainError::PipelineNotFound(self.pipeline_id.clone()))?;
            if service
                .provider_service
                .commit(&lease, || async {})
                .await
                .is_none()
            {
                return Err(superseded());
            }
            let fetched = service
                .fetch_run_details_from(lease.provider.as_ref(), &pipeline, self.run_number)
                .await;
            drop(permit);
            return service
                .provider_service
                .commit(&lease, || async {
                    let run = match fetched {
                        Ok(run) => run,
                        Err(error) => {
                            if let Some(view) = attempt.0.take().and_then(|claim| {
                                claim.complete(
                                    Instant::now(),
                                    failed_outcome(&error),
                                    FetchResult::Cancelled,
                                )
                            }) {
                                service.health.send(HealthInput::FetchOutcome {
                                    provider_id: self.provider_id,
                                    generation: self.generation,
                                    view,
                                    kind: Some(error.failure_kind()),
                                });
                                service.provider_service.emit_status(self.provider_id).await;
                            }
                            return Err(error);
                        }
                    };
                    let pipeline = service
                        .repository
                        .get_cached_pipelines(Some(self.provider_id))
                        .await?
                        .into_iter()
                        .find(|pipeline| {
                            pipeline.id == self.pipeline_id
                                && pipeline.provider_id == self.provider_id
                        })
                        .ok_or_else(|| DomainError::PipelineNotFound(self.pipeline_id.clone()))?;
                    let config = service.repository.get_provider(self.provider_id).await?;
                    if run.pipeline_id != self.pipeline_id
                        || run.run_number != self.run_number
                        || config.id != Some(self.provider_id)
                        || config.provider_type != pipeline.provider_type
                    {
                        return Err(DomainError::InvalidConfig(
                            "The provider returned a different pipeline or build run".to_string(),
                        ));
                    }
                    Ok(WatchedRun {
                        pipeline,
                        provider_name: config.display_name().to_string(),
                        run,
                        observed_at: Utc::now(),
                    })
                })
                .await
                .ok_or_else(superseded)?;
        }
    }
}

fn superseded() -> DomainError {
    DomainError::ConcurrentModification(
        "The watched provider or application session changed".to_string(),
    )
}

fn rate_limited(retry_after: Option<Duration>) -> DomainError {
    DomainError::RateLimited {
        message: "Provider API quota or rate-limit cooldown is active".to_string(),
        retry_after,
    }
}

#[cfg(test)]
mod tests {
    use std::future::Future;
    use std::sync::atomic::Ordering;

    use futures::poll;
    use pipedash_plugin_api::RateLimit;

    use super::*;
    use crate::application::test_support::{
        pipeline,
        stub_run,
        Gate,
        Harness,
        StubProvider,
    };
    use crate::domain::{
        FailureKind,
        RefreshState,
    };

    async fn selected(h: &Harness, gate: Option<&Arc<Gate>>) -> (i64, Arc<StubProvider>, RunWatch) {
        let (id, stub) = h
            .add_stub(|id| {
                let mut stub = StubProvider::new(id);
                if let Some(gate) = gate {
                    stub = stub.run_gated(gate);
                }
                let mut run = stub_run(&pipeline(id, "web", PipelineStatus::Running).id, 7, 0);
                run.status = PipelineStatus::Running;
                stub.with_runs(vec![run])
            })
            .await;
        let mut cached = pipeline(id, "web", PipelineStatus::Running);
        cached.provider_type = "argocd".to_string();
        let pipeline_id = cached.id.clone();
        h.repository
            .update_pipelines_cache(id, &[cached])
            .await
            .unwrap();
        let watch = h.pipeline_service.watch_run(pipeline_id, 7).await.unwrap();
        (id, stub, watch)
    }

    fn run_calls(stub: &StubProvider) -> usize {
        stub.run_fetches.load(Ordering::SeqCst)
    }

    async fn wait_for_claim(h: &Harness, id: i64, pending: &mut (impl Future + Unpin)) {
        timeout(Duration::from_secs(10), async {
            while !h.scheduler.view(id, Instant::now()).unwrap().in_flight {
                assert!(poll!(&mut *pending).is_pending());
                tokio::task::yield_now().await;
            }
        })
        .await
        .expect("watch did not reach scheduler admission");
    }

    #[tokio::test]
    async fn active_quota_cooldown_makes_no_run_request() {
        let h = Harness::new().await;
        let (id, stub, mut watch) = selected(&h, None).await;
        h.scheduler.set_quota_pause(
            id,
            watch.generation,
            Some(Utc::now() + chrono::Duration::minutes(10)),
            Instant::now(),
            Utc::now(),
        );

        let result = timeout(Duration::from_secs(1), watch.next()).await.unwrap();
        assert!(matches!(result, Some(Err(DomainError::RateLimited { .. }))));
        assert!(watch.next().await.is_none());
        assert_eq!(run_calls(&stub), 0);
        assert_eq!(stub.fetch_count(), 0);
        assert!(!h.scheduler.view(id, Instant::now()).unwrap().in_flight);
    }

    #[tokio::test]
    async fn exhausted_provider_quota_prevents_run_request() {
        let h = Harness::new().await;
        let (id, stub, mut watch) = selected(&h, None).await;
        *stub.rate_limit.lock().unwrap() = Some(RateLimit {
            limit: 5000,
            remaining: 0,
            reset_at: Utc::now() + chrono::Duration::minutes(10),
        });

        assert!(matches!(
            watch.next().await,
            Some(Err(DomainError::RateLimited { .. }))
        ));
        assert!(watch.next().await.is_none());
        assert_eq!(run_calls(&stub), 0);
        assert!(h.scheduler.paused_until(id, Utc::now()).is_some());
        assert!(!h.scheduler.view(id, Instant::now()).unwrap().in_flight);
    }

    #[tokio::test]
    async fn run_rate_limit_blocks_another_watch_and_provider_refresh() {
        let h = Harness::new().await;
        let (id, stub, mut watch) = selected(&h, None).await;
        *stub.run_response.lock().unwrap() = Some(Err(DomainError::RateLimited {
            message: "slow down".to_string(),
            retry_after: Some(Duration::from_secs(120)),
        }));

        assert!(matches!(
            watch.next().await,
            Some(Err(DomainError::RateLimited { .. }))
        ));
        assert!(watch.next().await.is_none());
        let mut other = h
            .pipeline_service
            .watch_run(watch.pipeline_id.clone(), 7)
            .await
            .unwrap();
        let result = timeout(Duration::from_secs(1), other.next()).await.unwrap();
        assert!(matches!(result, Some(Err(DomainError::RateLimited { .. }))));
        let refreshed = h.pipeline_service.refresh_provider(id).await;
        assert_eq!(refreshed.state, RefreshState::Recent);
        assert_eq!(refreshed.kind, Some(FailureKind::RateLimited));
        assert_eq!(run_calls(&stub), 1);
        assert_eq!(stub.fetch_count(), 0);
    }

    #[tokio::test]
    async fn provider_refresh_rate_limit_blocks_run_requests() {
        let h = Harness::new().await;
        let (id, stub, mut watch) = selected(&h, None).await;
        *stub.pipelines.lock().unwrap() = Err(DomainError::RateLimited {
            message: "slow down".to_string(),
            retry_after: Some(Duration::from_secs(120)),
        });
        h.fetch_directly(id).await;

        assert!(matches!(
            watch.next().await,
            Some(Err(DomainError::RateLimited { .. }))
        ));
        assert_eq!(run_calls(&stub), 0);
        assert_eq!(stub.fetch_count(), 1);
    }

    #[tokio::test]
    async fn selected_run_does_not_drift_and_terminal_state_stops_fetching() {
        let h = Harness::new().await;
        let (id, stub, mut watch) = selected(&h, None).await;
        let before = h.scheduler.view(id, Instant::now()).unwrap();
        assert_eq!(watch.next().await.unwrap().unwrap().run.run_number, 7);
        let mut next_run = stub_run(&watch.pipeline_id, 8, 0);
        next_run.status = PipelineStatus::Running;
        *stub.runs.lock().unwrap() = vec![next_run, stub_run(&watch.pipeline_id, 7, 30)];
        let mut next = Box::pin(watch.next());
        assert!(poll!(&mut next).is_pending());
        assert_eq!(run_calls(&stub), 1);
        drop(next);
        watch.next_attempt = Instant::now();

        let observed = watch.next().await.unwrap().unwrap();
        assert_eq!(observed.run.run_number, 7);
        assert_eq!(observed.run.status, PipelineStatus::Success);
        assert!(watch.next().await.is_none());
        assert_eq!(run_calls(&stub), 2);
        assert_eq!(stub.fetch_count(), 0);
        let after = h.scheduler.view(id, Instant::now()).unwrap();
        assert_eq!(before.failures, after.failures);
        assert_eq!(before.last_failure, after.last_failure);
        assert_eq!(h.bus.count("pipelines-updated"), 0);
    }

    #[tokio::test]
    async fn mismatched_provider_run_identity_is_rejected() {
        let h = Harness::new().await;
        let (_, stub, mut watch) = selected(&h, None).await;
        *stub.run_response.lock().unwrap() = Some(Ok(stub_run(&watch.pipeline_id, 8, 0)));
        assert!(matches!(
            watch.next().await,
            Some(Err(DomainError::InvalidConfig(_)))
        ));
        let mut other = h
            .pipeline_service
            .watch_run(watch.pipeline_id.clone(), 7)
            .await
            .unwrap();
        *stub.run_response.lock().unwrap() = Some(Ok(stub_run("another-pipeline", 7, 0)));
        assert!(matches!(
            other.next().await,
            Some(Err(DomainError::InvalidConfig(_)))
        ));
        assert_eq!(run_calls(&stub), 2);
    }

    #[tokio::test]
    async fn cancelling_in_flight_run_releases_provider_lease_claim_and_permit() {
        let h = Harness::new().await;
        let gate = Gate::new();
        let (id, stub, mut watch) = selected(&h, Some(&gate)).await;
        let leases = Arc::strong_count(&stub);
        let pending = tokio::spawn(async move { watch.next().await });
        gate.arrived().await;
        assert!(Arc::strong_count(&stub) > leases);
        assert!(h.scheduler.view(id, Instant::now()).unwrap().in_flight);
        assert_eq!(h.pipeline_service.fetch_permits.available_permits(), 9);

        pending.abort();
        assert!(pending.await.unwrap_err().is_cancelled());
        assert_eq!(Arc::strong_count(&stub), leases);
        assert!(!h.scheduler.view(id, Instant::now()).unwrap().in_flight);
        assert_eq!(h.pipeline_service.fetch_permits.available_permits(), 10);
        gate.open();
        assert_eq!(run_calls(&stub), 1);
    }

    #[tokio::test]
    async fn blocked_watch_uses_common_fetch_permits_and_cancels_without_a_request() {
        let h = Harness::new().await;
        let (id, stub, mut watch) = selected(&h, None).await;
        let permits = h
            .pipeline_service
            .fetch_permits
            .clone()
            .acquire_many_owned(10)
            .await
            .unwrap();
        let mut pending = Box::pin(watch.next());
        wait_for_claim(&h, id, &mut pending).await;
        assert_eq!(run_calls(&stub), 0);

        drop(pending);
        assert!(!h.scheduler.view(id, Instant::now()).unwrap().in_flight);
        drop(permits);
        assert_eq!(watch.next().await.unwrap().unwrap().run.run_number, 7);
        assert_eq!(run_calls(&stub), 1);
    }

    #[tokio::test]
    async fn replacing_credentials_rejects_an_in_flight_result() {
        let h = Harness::new().await;
        let gate = Gate::new();
        let (id, old, mut watch) = selected(&h, Some(&gate)).await;
        let replacement = h.stubs.queue(StubProvider::new(id));
        let pending = tokio::spawn(async move { watch.next().await });
        gate.arrived().await;
        let mut config = h.config("replacement", 30);
        config.id = Some(id);
        config.token = "new-token".to_string();
        h.provider_service
            .update_provider(id, config)
            .await
            .unwrap();
        gate.open();

        assert!(matches!(
            pending.await.unwrap(),
            Some(Err(DomainError::ConcurrentModification(_)))
        ));
        assert_eq!(run_calls(&old), 1);
        assert_eq!(run_calls(&replacement), 0);
        assert_eq!(replacement.fetch_count(), 0);
    }

    #[tokio::test]
    async fn replacing_credentials_before_next_makes_no_old_run_request() {
        let h = Harness::new().await;
        let (id, old, mut watch) = selected(&h, None).await;
        let replacement = h.stubs.queue(StubProvider::new(id));
        let mut config = h.config("replacement", 30);
        config.id = Some(id);
        h.provider_service
            .update_provider(id, config)
            .await
            .unwrap();

        assert!(matches!(
            watch.next().await,
            Some(Err(DomainError::ConcurrentModification(_)))
        ));
        assert_eq!(run_calls(&old), 0);
        assert_eq!(run_calls(&replacement), 0);
    }

    #[tokio::test]
    async fn replaced_credentials_are_not_used_after_waiting_for_a_fetch_permit() {
        let h = Harness::new().await;
        let (id, old, mut watch) = selected(&h, None).await;
        let permits = h
            .pipeline_service
            .fetch_permits
            .clone()
            .acquire_many_owned(10)
            .await
            .unwrap();
        let mut pending = Box::pin(watch.next());
        wait_for_claim(&h, id, &mut pending).await;
        let replacement = h.stubs.queue(StubProvider::new(id));
        let mut config = h.config("replacement", 30);
        config.id = Some(id);
        h.provider_service
            .update_provider(id, config)
            .await
            .unwrap();
        drop(permits);

        assert!(matches!(
            pending.await,
            Some(Err(DomainError::ConcurrentModification(_)))
        ));
        assert_eq!(run_calls(&old), 0);
        assert_eq!(run_calls(&replacement), 0);
    }

    #[tokio::test]
    async fn waiting_for_a_fetch_permit_ends_at_the_core_deadline() {
        let h = Harness::new().await;
        let (id, stub, mut watch) = selected(&h, None).await;
        let permits = h
            .pipeline_service
            .fetch_permits
            .clone()
            .acquire_many_owned(10)
            .await
            .unwrap();
        let mut pending = Box::pin(watch.next());
        wait_for_claim(&h, id, &mut pending).await;
        tokio::time::pause();
        tokio::time::advance(PipelineService::REFRESH_DEADLINE + Duration::from_secs(1)).await;

        assert!(matches!(pending.await, Some(Err(DomainError::Timeout(_)))));
        assert!(watch.next().await.is_none());
        assert_eq!(run_calls(&stub), 0);
        assert!(!h.scheduler.view(id, Instant::now()).unwrap().in_flight);
        drop(permits);
        assert_eq!(h.pipeline_service.fetch_permits.available_permits(), 10);
    }

    async fn cached_flux_run(
        h: &Harness, status: PipelineStatus, uid: &str, source: &str,
    ) -> (Arc<StubProvider>, RunWatch) {
        let (id, stub) = h.add_stub(StubProvider::new).await;
        let mut config = h.config("Flux", 30);
        config.id = Some(id);
        config.provider_type = "fluxcd".to_string();
        h.repository.update_provider(id, &config).await.unwrap();
        let mut cached = pipeline(id, "web", PipelineStatus::Running);
        cached.id = format!("fluxcd__{id}__HelmRelease__apps__web");
        cached.provider_type = "fluxcd".to_string();
        cached
            .metadata
            .insert("uid".to_string(), serde_json::json!("resource-1"));
        let pipeline_id = cached.id.clone();
        h.repository
            .update_pipelines_cache(id, &[cached])
            .await
            .unwrap();
        let mut run = stub_run(&pipeline_id, 7, 30);
        run.status = status;
        run.metadata
            .insert("uid".to_string(), serde_json::json!(uid));
        run.metadata
            .insert("record_source".to_string(), serde_json::json!(source));
        h.repository
            .cache_run_history(&pipeline_id, &[run])
            .await
            .unwrap();
        *stub.run_response.lock().unwrap() = Some(Err(DomainError::PipelineNotFound(
            "remote execution missing".to_string(),
        )));
        let watch = h.pipeline_service.watch_run(pipeline_id, 7).await.unwrap();
        (stub, watch)
    }

    #[tokio::test]
    async fn missing_flux_execution_uses_the_same_archived_terminal_fallback() {
        let h = Harness::new().await;
        let (stub, mut watch) =
            cached_flux_run(&h, PipelineStatus::Success, "resource-1", "status.history").await;
        let details = h
            .pipeline_service
            .fetch_run_details(&watch.pipeline_id, 7)
            .await
            .unwrap();
        assert_eq!(details.metadata["archived"], serde_json::json!(true));

        let observed = watch.next().await.unwrap().unwrap();
        assert_eq!(observed.run.run_number, 7);
        assert_eq!(observed.run.status, PipelineStatus::Success);
        assert_eq!(observed.run.metadata["archived"], serde_json::json!(true));
        assert!(watch.next().await.is_none());
        assert_eq!(run_calls(&stub), 2);
        assert_eq!(stub.fetch_count(), 0);
    }

    #[tokio::test]
    async fn unarchivable_flux_cache_keeps_the_remote_lookup_error() {
        for (status, uid, source) in [
            (PipelineStatus::Running, "resource-1", "status.history"),
            (PipelineStatus::Pending, "resource-1", "status.history"),
            (PipelineStatus::Success, "resource-2", "status.history"),
            (PipelineStatus::Success, "resource-1", "current_snapshot"),
        ] {
            let h = Harness::new().await;
            let (stub, mut watch) = cached_flux_run(&h, status, uid, source).await;

            assert!(matches!(
                watch.next().await,
                Some(Err(DomainError::PipelineNotFound(message)))
                    if message == "remote execution missing"
            ));
            assert!(watch.next().await.is_none());
            assert_eq!(run_calls(&stub), 1);
            assert_eq!(stub.fetch_count(), 0);
        }
    }
}