runnerd-core 0.1.3

Config, domain logic and API types shared by runnerd and its clients
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
//! A repository served by two pools (ADR 0058): a light job starts in the light pool while a heavy one waits, the
//! light pool reserves only what its own jobs predict, and a job no pool's labels match says so.

use std::time::SystemTime;

use super::*;
use crate::api::HoldCause;
use crate::scheduler::Hold;
use crate::store::{RunnerRecord, SampleRecord};
use crate::time;

const G: u64 = 1 << 30;
const M: u64 = 1 << 20;

/// o/r in `app` (4G) for `[self-hosted, app]` jobs, and in `light` (1G) for `r-light` jobs.
fn pools() -> String {
    format!(
        "{CONFIG}
[profiles.light]
image_stage = \"app\"
cpus = 1
memory = \"1G\"
slots = 2

[[repositories]]
name = \"o/r\"
profile = \"light\"
labels = [\"r-light\"]
warm = 0
"
    )
}

/// A job of o/r asking only for `r-light`.
fn light(id: u64) -> QueuedJob {
    QueuedJob {
        name: "lint".to_owned(),
        labels: vec!["r-light".to_owned()],
        ..job(id)
    }
}

/// The runner of each slot that has one, as `(profile, labels it registered with, what it reserves)`.
fn runners(
    engine: &mut Engine<FakeGithub, FakeDocker>,
    handle: &Handle,
    docker: &FakeDocker,
) -> Vec<Started> {
    engine.publish();
    let containers = docker.0.lock().unwrap().containers.clone();
    handle
        .status
        .borrow()
        .profiles
        .iter()
        .flat_map(|profile| {
            profile.slots.iter().filter_map(|slot| {
                let runner = slot.runner.as_ref()?;
                let labels = containers
                    .iter()
                    .find(|container| container.name == runner.name)
                    .and_then(|container| container.labels.get("runnerd.labels").cloned())
                    .unwrap_or_default();
                Some(Started {
                    profile: profile.name.clone(),
                    labels,
                    reserved: runner.reserved,
                })
            })
        })
        .collect()
}

/// A started runner as `runners` sees it.
#[derive(Debug, PartialEq)]
struct Started {
    profile: String,
    labels: String,
    reserved: u64,
}

#[tokio::test]
async fn a_light_job_starts_in_the_light_pool_while_a_heavy_one_waits_for_memory() {
    let (github, docker, dir) = (
        FakeGithub::default(),
        FakeDocker::default(),
        TestDir::new("engine"),
    );
    let (mut engine, handle) = engine_with(&github, &docker, &dir, &pools());
    // Room for a light runner, not for a heavy one.
    engine.memory_max = Some(3 * G);
    engine.recover().await.unwrap();
    github.0.lock().unwrap().queued = vec![job(1), light(2)];
    engine.tick(Shutdown::No).await;
    assert_eq!(
        runners(&mut engine, &handle, &docker),
        [Started {
            profile: "light".to_owned(),
            labels: "r-light".to_owned(),
            reserved: G,
        }]
    );
    let status = handle.status.borrow().clone();
    let heavy = &status.queued[0];
    assert_eq!(heavy.profile.as_deref(), Some("app"));
    assert!(
        matches!(heavy.waiting, Some(api::Waiting::Memory { needs, .. }) if needs == 4 * G),
        "the heavy job waits for 4G: {:?}",
        heavy.waiting
    );
    let pools: Vec<(&str, usize)> = status.repositories[0]
        .pools
        .iter()
        .map(|pool| (pool.profile.as_str(), pool.queued_jobs))
        .collect();
    // The light job stays listed until its runner takes it.
    assert_eq!(pools, [("app", 1), ("light", 1)]);
}

/// Ten finished `name` jobs of o/r in `profile`, asking for `labels`, from ID `first`, that peaked at `peak`.
async fn ran_in(store: &Store, profile: &str, labels: &[&str], name: &str, first: u64, peak: u64) {
    let at = time::now_ms() - 3600 * 1000;
    for id in first..first + 10 {
        let runner = format!("earlier-{id}");
        store.queued(
            "o/r",
            &QueuedJob {
                created_at: at,
                name: name.to_owned(),
                labels: labels.iter().map(|label| (*label).to_owned()).collect(),
                ..job(id)
            },
            time::now_ms(),
        );
        store.runner_started(RunnerRecord {
            purpose: None,
            name: runner.clone(),
            repository: "o/r".to_owned(),
            profile: profile.to_owned(),
            slot: 1,
            container: format!("c-{id}"),
            started_at: at,
            memory_cap: None,
            cpu_cap: None,
            admission: None,
        });
        store.claimed(id, 1, &runner, at + 1000);
        store.samples(vec![SampleRecord {
            runner: runner.clone(),
            at: at + 2000,
            cpu: 0,
            cpu_usage: 0,
            memory: peak,
            network_received: 0,
            network_sent: 0,
            cpu_held: crate::observe::metrics::CpuHeld::default(),
            written: None,
            dirty: None,
            events: crate::observe::metrics::Events::default(),
        }]);
        store.lost(id, at + 60_000);
        store.runner_removed(&runner, at + 60_000);
    }
    store.flush().await;
}

#[tokio::test]
async fn the_light_pool_reserves_only_what_its_own_queued_jobs_predict() {
    let (github, docker, dir) = (
        FakeGithub::default(),
        FakeDocker::default(),
        TestDir::new("engine"),
    );
    let config = pools().replace("admission = \"caps\"", "admission = \"measured\"");
    let (mut engine, handle) = engine_with(&github, &docker, &dir, &config);
    engine.memory_max = Some(10 * G);
    ran_in(
        &handle.store,
        "app",
        &["self-hosted", "app"],
        "build",
        1000,
        3 * G,
    )
    .await;
    // The same job name in both pools: each pool's runs predict only its own.
    ran_in(&handle.store, "light", &["r-light"], "build", 2000, 200 * M).await;
    engine.recover().await.unwrap();
    handle.store.host_sample(api::HostSample {
        at: time::now_ms() / 1000,
        cpu: 0,
        memory: 2 * G,
    });
    let light_build = QueuedJob {
        name: "build".to_owned(),
        ..light(2)
    };
    github.0.lock().unwrap().queued = vec![job(1), light_build];
    engine.tick(Shutdown::No).await;
    let started = runners(&mut engine, &handle, &docker);
    let reserved = |profile: &str| {
        started
            .iter()
            .find(|runner| runner.profile == profile)
            .map(|runner| runner.reserved)
    };
    // Each its own job's peak and a margin: the light runner does not reserve for the build its pool cannot take.
    let (app, light) = (reserved("app").unwrap(), reserved("light").unwrap());
    assert!(
        app > 3 * G,
        "the build's runner reserves past its 3G peak: {app}"
    );
    assert!(
        light < 512 * M,
        "the light build's runner reserves for 200M, not the heavy build's 3G: {light}"
    );
}

#[tokio::test]
async fn a_job_whose_labels_no_pool_has_says_so_and_starts_nothing() {
    let (github, docker, dir) = (
        FakeGithub::default(),
        FakeDocker::default(),
        TestDir::new("engine"),
    );
    let (mut engine, handle) = engine_with(&github, &docker, &dir, &pools());
    engine.recover().await.unwrap();
    let mislabelled = QueuedJob {
        labels: vec!["r-lite".to_owned()],
        ..job(1)
    };
    // GitHub runs this one on its own runners: no pool is meant for it.
    let hosted = QueuedJob {
        labels: vec!["ubuntu-latest".to_owned()],
        ..job(2)
    };
    github.0.lock().unwrap().queued = vec![mislabelled, hosted];
    engine.tick(Shutdown::No).await;
    assert_eq!(registered(&github.calls()), Vec::<&String>::new());
    engine.publish();
    let status = handle.status.borrow().clone();
    let waiting = status.queued[0].waiting.clone().unwrap();
    assert_eq!(
        waiting,
        api::Waiting::NoPool {
            labels: vec!["r-lite".to_owned()]
        }
    );
    assert_eq!(waiting.kind(), api::WaitKind::Act);
    assert_eq!(
        waiting.reason(&status.queued[0], &status, 0),
        "No profile serves the label r-lite"
    );
    assert_eq!(
        status.queued.len(),
        1,
        "the GitHub-hosted job is not listed"
    );
    assert_eq!(status.repositories[0].queued_jobs, 1);
}

#[tokio::test]
async fn pausing_a_repository_pauses_every_pool_of_it() {
    let (github, docker, dir) = (
        FakeGithub::default(),
        FakeDocker::default(),
        TestDir::new("engine"),
    );
    let (mut engine, handle) = engine_with(&github, &docker, &dir, &pools());
    engine.recover().await.unwrap();
    engine.pause(&one("o/r"), RunningJobs::Keep).await.unwrap();
    github.0.lock().unwrap().queued = vec![job(1), light(2)];
    engine.tick(Shutdown::No).await;
    assert_eq!(registered(&github.calls()), Vec::<&String>::new());
    engine.publish();
    let status = handle.status.borrow().clone();
    assert_eq!(status.repositories.len(), 1, "one row for the repository");
    assert!(
        status
            .queued
            .iter()
            .all(|job| job.waiting == Some(api::Waiting::Paused)),
        "both jobs wait for the resume: {:?}",
        status.queued
    );
}

#[tokio::test]
async fn a_pool_whose_runners_fail_holds_back_only_itself() {
    let (github, docker, dir) = (
        FakeGithub::default(),
        FakeDocker::default(),
        TestDir::new("engine"),
    );
    // The light pool's image is missing, so its runners cannot start.
    let config = pools().replacen(
        "image_stage = \"app\"\ncpus = 1",
        "image_stage = \"lite\"\ncpus = 1",
        1,
    );
    docker.0.lock().unwrap().missing_images = BTreeSet::from(["runnerd-runner:lite".to_owned()]);
    let (mut engine, handle) = engine_with(&github, &docker, &dir, &config);
    engine.recover().await.unwrap();
    github.0.lock().unwrap().queued = vec![light(1)];
    engine.tick(Shutdown::No).await;
    // A heavy job queued after the light pool's failure still gets its runner.
    github.0.lock().unwrap().queued = vec![light(1), job(2)];
    engine.tick(Shutdown::No).await;
    let started = runners(&mut engine, &handle, &docker);
    assert_eq!(
        started
            .iter()
            .map(|runner| runner.profile.as_str())
            .collect::<Vec<_>>(),
        ["app"]
    );
    let status = handle.status.borrow().clone();
    assert!(
        matches!(status.queued[0].waiting, Some(api::Waiting::Backoff { .. })),
        "the light job waits for its pool's backoff: {:?}",
        status.queued[0].waiting
    );
}

#[tokio::test]
async fn a_reload_that_leaves_a_pools_runners_alone_keeps_its_hold_and_streaks() {
    // Catches a reload forgetting what failed: auto sizing changes a pool's slots now and then, and a broken pool
    // would start again at each one and announce a new first failure.
    let (github, docker, dir) = (
        FakeGithub::default(),
        FakeDocker::default(),
        TestDir::new("engine"),
    );
    let (mut engine, _handle) = engine_with(&github, &docker, &dir, &pools());
    engine.recover().await.unwrap();
    let until = SystemTime::now() + Duration::from_secs(300);
    let cause = HoldCause::NoJob;
    engine.set_streaks("o/r", "light", 2, 1);
    engine.set_held("o/r", "light", Hold { until, cause });

    let more_slots = pools().replacen(
        "memory = \"1G\"\nslots = 2",
        "memory = \"1G\"\nslots = 3",
        1,
    );
    engine.reload(Config::parse(&more_slots).unwrap(), None, None);

    let facts = engine.pool_hold("o/r", "light").unwrap();
    assert_eq!(
        (facts.failures, facts.idle_exits),
        (2, 1),
        "both streaks stay"
    );
    assert_eq!(
        facts.held.map(|held| (held.until, held.cause)),
        Some((until, cause)),
        "the hold stays as it was"
    );
}

#[tokio::test]
async fn a_start_that_failed_and_left_its_container_holds_its_pool() {
    // Catches a pool retrying at once when Docker kept the container of a start that failed: the slot's runner goes
    // when its removal is confirmed, and the next start would fail the same way, with no backoff.
    let (github, docker, dir) = (
        FakeGithub::default(),
        FakeDocker::default(),
        TestDir::new("engine"),
    );
    let (mut engine, _handle) = engine_with(&github, &docker, &dir, CONFIG);
    engine.recover().await.unwrap();
    github.0.lock().unwrap().queued = vec![job(1)];
    docker
        .0
        .lock()
        .unwrap()
        .late_failures
        .push_back(LateFailure {
            takes_job: false,
            cleanup_fails: true,
        });

    engine.tick(Shutdown::No).await;

    let facts = engine.pool_hold("o/r", "app").unwrap();
    assert_eq!(facts.failures, 1, "it counts as a failed start");
    assert_eq!(
        facts.held.map(|held| held.cause),
        Some(HoldCause::Start),
        "the pool is held for the start"
    );
}

#[tokio::test]
async fn a_reload_that_changes_a_held_pools_runners_lets_it_start_again_at_once() {
    // Catches a backoff outliving the reload that fixed its cause: the owner fixes the light pool's image, and its job
    // still waits out the hold. A reload that leaves its runners as they were, such as auto sizing's slots, keeps it.
    let (github, docker, dir) = (
        FakeGithub::default(),
        FakeDocker::default(),
        TestDir::new("engine"),
    );
    let broken = pools().replacen(
        "image_stage = \"app\"\ncpus = 1",
        "image_stage = \"lite\"\ncpus = 1",
        1,
    );
    docker.0.lock().unwrap().missing_images = BTreeSet::from(["runnerd-runner:lite".to_owned()]);
    let (mut engine, handle) = engine_with(&github, &docker, &dir, &broken);
    engine.recover().await.unwrap();
    github.0.lock().unwrap().queued = vec![light(1)];
    engine.tick(Shutdown::No).await;
    let backing_off = |engine: &mut Engine<FakeGithub, FakeDocker>, handle: &Handle| {
        engine.publish();
        matches!(
            handle.status.borrow().queued[0].waiting,
            Some(api::Waiting::Backoff { .. })
        )
    };
    assert!(
        backing_off(&mut engine, &handle),
        "the light pool backs off"
    );
    let more_slots = broken.replacen(
        "memory = \"1G\"\nslots = 2",
        "memory = \"1G\"\nslots = 3",
        1,
    );
    engine.reload(Config::parse(&more_slots).unwrap(), None, None);
    engine.tick(Shutdown::No).await;
    assert!(
        backing_off(&mut engine, &handle),
        "more slots leave the light pool backing off"
    );
    engine.reload(Config::parse(&pools()).unwrap(), None, None);
    engine.tick(Shutdown::No).await;
    assert!(
        !backing_off(&mut engine, &handle),
        "the fixed image ends the light pool's backoff"
    );
    let profiles: Vec<String> = runners(&mut engine, &handle, &docker)
        .into_iter()
        .map(|runner| runner.profile)
        .collect();
    assert_eq!(profiles, ["light"], "the light job's runner starts");
}

#[tokio::test]
async fn a_repository_names_its_first_pool_for_0_0_19_clients_and_a_later_reason_reads_plainly() {
    let (github, docker, dir) = (
        FakeGithub::default(),
        FakeDocker::default(),
        TestDir::new("engine"),
    );
    let (mut engine, handle) = engine_with(&github, &docker, &dir, &pools());
    engine.recover().await.unwrap();
    engine.publish();
    let repository = handle.status.borrow().repositories[0].clone();
    assert_eq!(repository.first_profile(), "app");
    // A reason added after this client still lets it read the job, said plainly.
    let later: api::QueuedJob = serde_json::from_value(serde_json::json!({
        "id": 1,
        "repository": "o/r",
        "run_id": 1,
        "run_attempt": 1,
        "name": "build",
        "queued_at": 0,
        "waiting": { "kind": "some-later-reason", "detail": 3 },
    }))
    .unwrap();
    let reason = later.waiting.clone().unwrap();
    assert_eq!(reason, api::Waiting::Unknown);
    assert_eq!(reason.kind(), api::WaitKind::Other);
    assert_eq!(
        reason.reason(&later, &handle.status.borrow(), 0),
        "Waits for a reason this client does not know yet"
    );
}