orch-cli 0.118.0

Orch, the agent orchestration engine: runs coding agents on tasks and cron jobs
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
//! Leader work that needs a checkout: a PR rebase, the shipcheck run before a review and `bash`
//! jobs. A leader that does not host the repo hands it to a host, see `docs/content/docs/cluster.md`

use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::{Arc, LazyLock};

use async_trait::async_trait;
use chrono::{DateTime, Utc};
use dashmap::DashSet;
use serde::{Deserialize, Serialize};

use crate::engine::review::auto_merge::{self, WorktreeRebaseOutcome};
use crate::engine::review::shipcheck::{self, Prerun};
use crate::engine::subscribers::review as review_subscriber;
use crate::engine::tasks::jobs::{self, Job};
use crate::engine::tick::assign;
use crate::store::cluster::Node;
use crate::store::cluster::registry::{self, Entry};
use crate::store::{TaskStore, opt_store_get_task};

/// Rows are replicated kv rows `chore:<repo>#<kind>#<subject>`
const PREFIX: &str = "chore:";

/// A row nobody collected after this long is dropped, its task or job has moved on
const STALE_AFTER: chrono::Duration = chrono::Duration::hours(24);

/// The work the leader hands to a node that hosts the project
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub(crate) enum Request {
    /// Rebase the PR branch onto its base in the task worktree and force push it. `carry` moves
    /// the approval to the rebased head
    Rebase {
        task_id: String,
        pr_number: u64,
        #[serde(default)]
        carry: bool,
    },
    /// Start `shipcheck run` on the PR head in the task worktree, or report its result
    Shipcheck { task_id: String },
    /// Run a `bash` job in the project directory
    Bash { job: Box<Job> },
}

impl Request {
    fn key(&self, repo: &str) -> String {
        let (kind, subject) = match self {
            Self::Rebase { task_id, .. } => ("rebase", task_id.as_str()),
            Self::Shipcheck { task_id } => ("shipcheck", task_id.as_str()),
            Self::Bash { job } => ("bash", job.id.as_str()),
        };
        format!("{PREFIX}{repo}#{kind}#{subject}")
    }
}

/// The key of a `bash` job's row, for a poll before the job is due
pub(crate) fn bash_key(repo: &str, job_id: &str) -> String {
    format!("{PREFIX}{repo}#bash#{job_id}")
}

/// What the node that ran the work reports back
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub(crate) enum Outcome {
    Rebase {
        outcome: WorktreeRebaseOutcome,
    },
    /// `ready` is false while a run of the head is still going
    Shipcheck {
        ready: bool,
    },
    /// The node has no worktree with shipcheck for the task
    NoShipcheck,
    /// `done`, `failed` or `timeout`, as `job_state.last_task_status` holds it
    Bash {
        status: String,
    },
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct Row {
    node: String,
    term: u64,
    request: Request,
    #[serde(default)]
    outcome: Option<Outcome>,
    created: String,
}

impl Row {
    fn stale_at(&self, now: DateTime<Utc>) -> bool {
        DateTime::parse_from_rfc3339(&self.created)
            .is_ok_and(|at| now.signed_duration_since(at) > STALE_AFTER)
    }
}

/// Where the work for a repo runs
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Where {
    /// One machine, or this node hosts the repo: run it here as before
    Here,
    /// The node that runs it
    Node(String),
    /// No online node hosts the repo
    Waiting,
}

/// A row as the leader finds it
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Poll {
    Absent,
    /// The node still runs it
    Pending(String),
    /// The node that held it is offline, so another one may take it
    Orphaned,
    /// The outcome. Reading it deleted the row
    Done(Outcome),
}

/// What the leader does next
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Ask {
    Here,
    Pending(String),
    Waiting,
    Done(Outcome),
}

/// The note on a task or job whose work waits for a host
pub(crate) fn waiting_note(repo: &str) -> String {
    format!("{}{repo}", assign::WAITING_PREFIX)
}

fn hosts(entry: &Entry, repo: &str, now: DateTime<Utc>) -> bool {
    !entry.witness && entry.online_at(now) && entry.hosts(repo)
}

/**
 * Pick the node for work on `repo`. This node when it hosts the repo, or when it has no registry
 * entry yet, so a start before the first heartbeat behaves as before. Otherwise the online host
 * with the lowest name, so every leader picks the same one
 **/
pub(crate) fn choose(entries: &[Entry], me: &str, repo: &str, now: DateTime<Utc>) -> Where {
    match entries.iter().find(|e| e.node == me) {
        None => return Where::Here,
        Some(mine) if mine.hosts(repo) => return Where::Here,
        Some(_) => {}
    }

    entries
        .iter()
        .filter(|e| hosts(e, repo, now))
        .map(|e| e.node.clone())
        .min()
        .map_or(Where::Waiting, Where::Node)
}

/// Where the work for `repo` runs. Always `Here` on one machine
pub(crate) async fn place(store: &TaskStore, repo: &str) -> Where {
    let Some(node) = store.node() else {
        return Where::Here;
    };
    match registry::read(store).await {
        Ok(entries) => choose(&entries, node.name(), repo, Utc::now()),
        Err(e) => {
            tracing::warn!(repo, err = %e, "cannot read the node registry, the work waits");
            Where::Waiting
        }
    }
}

/// Hand `request` to `node`
pub(crate) async fn assign(
    store: &TaskStore,
    repo: &str,
    node: &str,
    request: Request,
) -> anyhow::Result<()> {
    let row = Row {
        node: node.to_string(),
        term: store.node().map_or(0, Node::term),
        request,
        outcome: None,
        created: Utc::now().to_rfc3339(),
    };
    let key = row.request.key(repo);
    tracing::info!(key, node, "handing work that needs a checkout to a node");
    store.kv_set(&key, &serde_json::to_string(&row)?).await
}

/// Read the row under `key`. A finished row is deleted, so its outcome is used once
pub(crate) async fn poll(store: &TaskStore, key: &str) -> Poll {
    let row = match store.kv_get(key).await {
        Ok(Some(value)) => match serde_json::from_str::<Row>(&value) {
            Ok(row) => row,
            Err(e) => {
                tracing::warn!(key, err = %e, "dropping a work row that does not parse");
                let _ = store.kv_delete(key).await;
                return Poll::Absent;
            }
        },
        Ok(None) => return Poll::Absent,
        Err(e) => {
            tracing::warn!(key, err = %e, "cannot read a work row");
            return Poll::Absent;
        }
    };
    if let Some(outcome) = row.outcome {
        if let Err(e) = store.kv_delete(key).await {
            tracing::warn!(key, err = %e, "failed to delete a finished work row");
        }
        return Poll::Done(outcome);
    }

    let now = Utc::now();
    let online = registry::read(store)
        .await
        .unwrap_or_default()
        .iter()
        .any(|e| e.node == row.node && e.online_at(now));
    if online {
        Poll::Pending(row.node)
    } else {
        Poll::Orphaned
    }
}

/**
 * Ask for `request` on `repo`. `Here` means run it in this process as before. Otherwise the
 * outcome when a node finished it, or the node that still runs it, or a wait for a host. A row
 * whose node went offline goes to another host. A wait writes nothing, so the next pass asks again
 **/
pub(crate) async fn ask(store: &TaskStore, repo: &str, request: Request) -> Ask {
    let Some(node) = store.node() else {
        return Ask::Here;
    };
    let key = request.key(repo);
    let orphaned = match poll(store, &key).await {
        Poll::Done(outcome) => return Ask::Done(outcome),
        Poll::Pending(node) => return Ask::Pending(node),
        Poll::Orphaned => true,
        Poll::Absent => false,
    };
    match place(store, repo).await {
        Where::Here => {
            if orphaned {
                let _ = store.kv_delete(&key).await;
            }
            Ask::Here
        }
        Where::Waiting => Ask::Waiting,
        Where::Node(chosen) if chosen == node.name() => Ask::Here,
        Where::Node(chosen) => {
            if orphaned {
                tracing::warn!(key, node = %chosen, "the node holding the work is offline, moving it");
            }
            if let Err(e) = assign(store, repo, &chosen, request).await {
                tracing::warn!(key, err = %e, "failed to hand the work to a node, next pass tries again");
            }
            Ask::Pending(chosen)
        }
    }
}

/// Runs the work a row asks for on the node that holds it
#[async_trait]
pub(crate) trait Execute: Send + Sync {
    async fn execute(&self, store: &Arc<TaskStore>, repo: &str, request: &Request) -> Outcome;
}

/// The real work, in the checkouts this node hosts
pub(crate) struct Checkout {
    /// Each hosted repo and its project directory
    pub(crate) dirs: HashMap<String, PathBuf>,
}

#[async_trait]
impl Execute for Checkout {
    async fn execute(&self, store: &Arc<TaskStore>, repo: &str, request: &Request) -> Outcome {
        match request {
            Request::Rebase {
                task_id,
                pr_number,
                carry,
            } => Outcome::Rebase {
                outcome: auto_merge::rebase_here(store, repo, task_id, *pr_number, *carry).await,
            },
            Request::Shipcheck { task_id } => {
                let worktree = opt_store_get_task(&Some(Arc::clone(store)), repo, task_id)
                    .await
                    .map(|t| PathBuf::from(t.worktree))
                    .filter(|p| !p.as_os_str().is_empty() && p.exists());
                match review_subscriber::local_ci_worktree(repo, worktree).await {
                    Some(wt) => Outcome::Shipcheck {
                        ready: shipcheck::prerun(&wt).await == Prerun::Ready,
                    },
                    None => Outcome::NoShipcheck,
                }
            }
            Request::Bash { job } => {
                let Some(dir) = self.dirs.get(repo) else {
                    tracing::warn!(
                        repo,
                        job_id = job.id,
                        "no checkout of the repo here for a bash job"
                    );
                    return Outcome::Bash {
                        status: "failed".to_string(),
                    };
                };
                Outcome::Bash {
                    status: jobs::run_bash_job(job, dir).await,
                }
            }
        }
    }
}

/// Rows this process runs, keyed by node and row key
static RUNNING: LazyLock<DashSet<String>> = LazyLock::new(DashSet::new);

/// Releases the in-process claim on a row when its run ends
struct Claim(String);

impl Drop for Claim {
    fn drop(&mut self) {
        RUNNING.remove(&self.0);
    }
}

/**
 * Start every row assigned to this node that has no outcome and does not run here yet, each in its
 * own task. The outcome is written only while the row is still this node's. The leader also drops
 * rows nobody collected. Does nothing on one machine
 **/
pub(crate) async fn run_assigned(store: &Arc<TaskStore>, exec: &Arc<dyn Execute>) {
    let Some(node) = store.node() else {
        return;
    };
    let me = node.name().to_string();
    let rows = match store.kv_list_prefix(PREFIX).await {
        Ok(rows) => rows,
        Err(e) => {
            tracing::warn!(err = %e, "failed to list work rows");
            return;
        }
    };
    let now = Utc::now();
    for (key, value) in rows {
        let Ok(row) = serde_json::from_str::<Row>(&value) else {
            continue;
        };
        if store.is_leader() && row.stale_at(now) {
            tracing::info!(key, node = %row.node, "dropping a work row nobody collected");
            let _ = store.kv_delete(&key).await;
            continue;
        }

        if row.node != me || row.outcome.is_some() {
            continue;
        }

        let Some(repo) = key
            .strip_prefix(PREFIX)
            .and_then(|rest| rest.split('#').next())
            .map(str::to_string)
        else {
            continue;
        };
        let claim_key = format!("{me}|{key}");
        if !RUNNING.insert(claim_key.clone()) {
            continue;
        }

        let claim = Claim(claim_key);
        let store = Arc::clone(store);
        let exec = Arc::clone(exec);
        let me = me.clone();
        tokio::spawn(async move {
            let _claim = claim;
            tracing::info!(key, "running work the leader handed to this node");
            let outcome = exec.execute(&store, &repo, &row.request).await;
            finish(&store, &key, &me, outcome).await;
        });
    }
}

/// Write the outcome, unless the row went to another node or was dropped meanwhile
async fn finish(store: &TaskStore, key: &str, me: &str, outcome: Outcome) {
    let row = match store.kv_get(key).await {
        Ok(Some(value)) => serde_json::from_str::<Row>(&value).ok(),
        _ => None,
    };
    let Some(mut row) = row.filter(|r| r.node == me && r.outcome.is_none()) else {
        tracing::info!(key, "the work row moved on, dropping its outcome");
        return;
    };
    tracing::info!(key, ?outcome, "work done, reporting the outcome");
    row.outcome = Some(outcome);
    match serde_json::to_string(&row) {
        Ok(value) => {
            if let Err(e) = store.kv_set(key, &value).await {
                tracing::warn!(key, err = %e, "failed to report the outcome of the work");
            }
        }
        Err(e) => tracing::warn!(key, err = %e, "failed to encode the outcome of the work"),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn entry(node: &str, projects: &[&str], seen: DateTime<Utc>) -> Entry {
        Entry {
            node: node.into(),
            projects: projects.iter().map(ToString::to_string).collect(),
            agents: vec![],
            max_parallel: 1,
            version: None,
            witness: false,
            seen: seen.to_rfc3339(),
        }
    }

    #[test]
    fn a_node_that_hosts_the_repo_or_has_no_entry_runs_the_work_itself() {
        let now = Utc::now();
        let entries = [entry("a", &["o/r"], now), entry("b", &["o/r"], now)];
        assert_eq!(choose(&entries, "a", "o/r", now), Where::Here);
        assert_eq!(choose(&entries, "new", "o/r", now), Where::Here);
    }

    #[test]
    fn a_leader_without_the_repo_picks_the_online_host_with_the_lowest_name() {
        let now = Utc::now();
        let mut witness = entry("a-witness", &["o/r"], now);
        witness.witness = true;
        let entries = [
            entry("lead", &[], now),
            entry("c", &["o/r"], now),
            entry("b", &["o/r"], now),
            entry("a-offline", &["o/r"], now - chrono::Duration::minutes(10)),
            witness,
        ];
        assert_eq!(
            choose(&entries, "lead", "o/r", now),
            Where::Node("b".into())
        );
        assert_eq!(choose(&entries, "lead", "o/other", now), Where::Waiting);
    }

    #[test]
    fn a_row_survives_a_round_trip_and_ages_out() {
        let row = Row {
            node: "b".into(),
            term: 3,
            request: Request::Rebase {
                task_id: "7".into(),
                pr_number: 9,
                carry: true,
            },
            outcome: Some(Outcome::Rebase {
                outcome: WorktreeRebaseOutcome::RebaseConflict("x".into()),
            }),
            created: (Utc::now() - chrono::Duration::hours(25)).to_rfc3339(),
        };
        let back: Row = serde_json::from_str(&serde_json::to_string(&row).unwrap()).unwrap();
        assert_eq!(back.outcome, row.outcome);
        assert_eq!(back.request.key("o/r"), "chore:o/r#rebase#7");
        assert!(back.stale_at(Utc::now()));
    }
}