local-ci 0.20.0

Run the GitHub Actions jobs a branch would trigger, locally, in an isolated worktree, and print a short report
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
//! Read scheduling facts from a fixed Git commit, never from the checkout.
use super::{
    scheduling, EvaluationBinding, EvaluationSource, VerifiedEvaluationSource, MAX_SOURCE_BYTES,
    MAX_WORKFLOWS, VERSION,
};
use crate::{context::ExecContext, frozen::FrozenPlan};
use anyhow::{bail, ensure, Context, Result};
use sha2::{Digest, Sha256};
use std::{
    io::{Read, Write},
    os::fd::AsRawFd,
    os::unix::process::CommandExt,
    path::Path,
    process::{Child, Stdio},
    time::{Duration, Instant},
};

const MAX_PATH: usize = 4096;
const MAX_LIST_BYTES: usize = MAX_WORKFLOWS * (MAX_PATH + 1);
const MAX_STDERR: usize = 64 * 1024;
const REQUEST_TIME: Duration = Duration::from_secs(30);
const COMMAND_TIME: Duration = Duration::from_secs(5);

/// Recompute omitted scheduling facts from the plan's full, immutable Git
/// commit. Requires Git's `--no-lazy-fetch` option; older versions fail closed.
/// Reads at most 4MiB of workflow contents and 4096 regular workflow entries.
/// Git's object database and executable are the host's trusted Git boundary;
/// this is not a repository-wide object-database integrity scan.
/// No checkout, filter, fetch, credential prompt or worker execution is used.
pub fn git_evaluation_source(
    ctx: &ExecContext,
    repository: &Path,
    plan: &FrozenPlan,
) -> Result<VerifiedEvaluationSource> {
    plan.verify()?;
    plan.require_git_source()?;
    ensure!(
        plan.workflows.len() <= MAX_WORKFLOWS,
        "too many evaluation workflows"
    );
    let commit = plan
        .source
        .execution_commit
        .as_deref()
        .context("missing execution commit")?;
    ensure!(
        oid(commit),
        "evaluation source requires a full lowercase commit object ID"
    );
    ensure!(
        plan.source.source_id == format!("commit:{commit}"),
        "Git source identity mismatch"
    );
    let mut reader = GitWorkflowReader::new(ctx, repository, commit)?;
    let mut workflows = Vec::new();
    for frozen in &plan.workflows {
        let bytes = reader.read(&frozen.file)?;
        workflows.push(scheduling(
            frozen,
            &bytes,
            format!("{:x}", Sha256::digest(&bytes)),
        )?);
    }
    let record = EvaluationSource {
        schema_version: VERSION,
        plan_digest: plan.digest.clone(),
        source_id: plan.source.source_id.clone(),
        binding: EvaluationBinding::Git {
            execution_commit: commit.into(),
        },
        workflows,
    };
    ensure!(
        serde_json::to_vec(&record)?.len() <= MAX_SOURCE_BYTES,
        "evaluation source exceeds byte bound"
    );
    reader.finish()?;
    Ok(VerifiedEvaluationSource(record))
}

/// Shared exact-byte workflow IO for planning and verified scheduling facts.
/// This owns one aggregate budget, not a new allowance for each workflow.
pub(crate) struct GitWorkflowReader<'a> {
    ctx: &'a ExecContext,
    repository: &'a Path,
    commit: &'a str,
    started: Instant,
    remaining: usize,
    count: usize,
    listing_remaining: usize,
    listed: usize,
}
impl<'a> GitWorkflowReader<'a> {
    pub(crate) fn new(ctx: &'a ExecContext, repository: &'a Path, commit: &'a str) -> Result<Self> {
        ensure!(
            oid(commit),
            "workflow reader requires a full lowercase commit object ID"
        );
        let started = Instant::now();
        let format = command(
            ctx,
            repository,
            &["rev-parse", "--show-object-format"],
            16,
            started,
        )?;
        ensure!(
            matches!(
                (format.as_slice(), commit.len()),
                (b"sha1\n", 40) | (b"sha256\n", 64)
            ),
            "Git object format/commit mismatch"
        );
        ensure!(
            command(ctx, repository, &["cat-file", "-t", commit], 16, started)? == b"commit\n",
            "execution object is not a commit"
        );
        Ok(Self {
            ctx,
            repository,
            commit,
            started,
            remaining: MAX_SOURCE_BYTES,
            count: 0,
            listing_remaining: MAX_LIST_BYTES,
            listed: 0,
        })
    }
    /// NUL-terminated literal paths, with one metadata budget for all dirs.
    /// Decode strictly: lossy decoding could map a non-UTF8 entry to a different
    /// existing workflow whose name actually contains the replacement character.
    pub(crate) fn paths(&mut self, directory: &str) -> Result<String> {
        ensure!(
            directory.len() <= MAX_PATH && !directory.contains('\0'),
            "invalid Git workflow listing directory"
        );
        let bytes = command(
            self.ctx,
            self.repository,
            &[
                "ls-tree",
                "--name-only",
                "-z",
                self.commit,
                "--",
                &format!("{directory}/"),
            ],
            self.listing_remaining,
            self.started,
        )?;
        self.listing_remaining -= bytes.len();
        let text = String::from_utf8(bytes).context("Git workflow paths must be UTF-8")?;
        ensure!(
            text.is_empty() || text.ends_with('\0'),
            "unterminated Git workflow listing"
        );
        for path in text.split('\0').filter(|p| !p.is_empty()) {
            ensure!(
                path.len() <= MAX_PATH,
                "Git workflow listing path exceeds byte bound"
            );
            ensure!(
                self.listed < MAX_WORKFLOWS,
                "too many Git workflow listing entries"
            );
            self.listed += 1;
        }
        self.finish()?;
        Ok(text)
    }
    pub(crate) fn read(&mut self, path: &str) -> Result<Vec<u8>> {
        ensure!(self.count < MAX_WORKFLOWS, "too many evaluation workflows");
        self.count += 1;
        ensure!(
            !path.is_empty()
                && path.len() <= MAX_PATH
                && !path.bytes().any(|b| b == 0)
                && path.split('/').all(|c| !matches!(c, "" | "." | "..")),
            "noncanonical evaluation workflow path"
        );
        let entry = command(
            self.ctx,
            self.repository,
            &[
                "ls-tree",
                "-l",
                "-z",
                "--full-tree",
                self.commit,
                "--",
                path,
            ],
            MAX_PATH + 256,
            self.started,
        )?;
        let (blob, size) = tree_entry(&entry, path, self.commit.len())?;
        ensure!(
            size <= self.remaining,
            "evaluation workflow exceeds byte bound"
        );
        let bytes = command(
            self.ctx,
            self.repository,
            &["cat-file", "blob", blob],
            self.remaining,
            self.started,
        )?;
        ensure!(bytes.len() == size, "evaluation blob size mismatch");
        let object_id = command_input(
            self.ctx,
            self.repository,
            &["hash-object", "--no-filters", "--stdin"],
            128,
            self.started,
            Some(&bytes),
        )?;
        ensure!(
            object_id.strip_suffix(b"\n") == Some(blob.as_bytes()),
            "Git blob content/object ID mismatch"
        );
        self.remaining -= bytes.len();
        self.finish()?;
        Ok(bytes)
    }
    pub(crate) fn finish(&self) -> Result<()> {
        ensure!(!self.ctx.cancel.is_cancelled(), "Git evaluation cancelled");
        ensure!(
            self.started.elapsed() < REQUEST_TIME,
            "Git evaluation request deadline exceeded"
        );
        Ok(())
    }
}

/// Decoding is never verification: recompute from the same repository and
/// frozen plan before accepting a transported scheduling record.
pub fn verify_git_evaluation_source(
    ctx: &ExecContext,
    repository: &Path,
    plan: &FrozenPlan,
    record: &EvaluationSource,
) -> Result<VerifiedEvaluationSource> {
    let verified = git_evaluation_source(ctx, repository, plan)?;
    ensure!(
        verified.record() == record,
        "evaluation source provenance mismatch"
    );
    Ok(verified)
}

fn oid(value: &str) -> bool {
    matches!(value.len(), 40 | 64)
        && value
            .bytes()
            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
}

fn tree_entry<'a>(bytes: &'a [u8], path: &str, oid_len: usize) -> Result<(&'a str, usize)> {
    let line = bytes.strip_suffix(&[0]).context("missing Git tree entry")?;
    ensure!(!line.contains(&0), "multiple Git tree entries");
    let tab = line
        .iter()
        .position(|b| *b == b'\t')
        .context("invalid Git tree entry")?;
    ensure!(
        &line[tab + 1..] == path.as_bytes(),
        "Git tree path mismatch"
    );
    let fields: Vec<_> = std::str::from_utf8(&line[..tab])?
        .split_ascii_whitespace()
        .collect();
    ensure!(
        fields.len() == 4 && matches!(fields[0], "100644" | "100755") && fields[1] == "blob",
        "evaluation workflow is not a regular Git blob"
    );
    ensure!(
        oid(fields[2]) && fields[2].len() == oid_len,
        "invalid Git blob object ID"
    );
    Ok((
        fields[2],
        fields[3].parse().context("invalid Git blob size")?,
    ))
}

// The unreaped leader pins the group identity on every return path. Signal
// descendants before wait, including after the leader exits but holds no pipes.
// Cancellation is polled here rather than registering a reaped PID in ctx.
struct OwnedGroup(Child);
impl Drop for OwnedGroup {
    fn drop(&mut self) {
        let pid = self.0.id() as i32;
        if pid > 1 {
            // SAFETY: process_group(0) created this group and leader is unreaped.
            unsafe {
                libc::killpg(pid, libc::SIGKILL);
            }
        }
        let _ = self.0.wait();
    }
}

fn command(
    ctx: &ExecContext,
    repository: &Path,
    args: &[&str],
    max: usize,
    request_started: Instant,
) -> Result<Vec<u8>> {
    command_input(ctx, repository, args, max, request_started, None)
}

fn command_input(
    ctx: &ExecContext,
    repository: &Path,
    args: &[&str],
    max: usize,
    request_started: Instant,
    input: Option<&[u8]>,
) -> Result<Vec<u8>> {
    ensure!(!ctx.cancel.is_cancelled(), "Git evaluation cancelled");
    let remaining = REQUEST_TIME
        .checked_sub(request_started.elapsed())
        .context("Git evaluation request deadline exceeded")?;
    let timeout = remaining.min(COMMAND_TIME);
    let mut cmd = ctx.command("git");
    for name in [
        "GIT_DIR",
        "GIT_WORK_TREE",
        "GIT_COMMON_DIR",
        "GIT_OBJECT_DIRECTORY",
        "GIT_ALTERNATE_OBJECT_DIRECTORIES",
        "GIT_INDEX_FILE",
        "GIT_CONFIG",
        "GIT_CONFIG_COUNT",
        "GIT_CONFIG_PARAMETERS",
        "GIT_EXEC_PATH",
    ] {
        cmd.env_remove(name);
    }
    cmd.args([
        "--no-replace-objects",
        "--no-lazy-fetch",
        "--literal-pathspecs",
        "-C",
    ])
    .arg(repository)
    .args([
        "-c",
        "core.fsmonitor=false",
        "-c",
        "gc.auto=0",
        "-c",
        "maintenance.auto=false",
    ])
    .args(args)
    .env("GIT_CONFIG_NOSYSTEM", "1")
    .env("GIT_CONFIG_GLOBAL", "/dev/null")
    .env("GIT_TERMINAL_PROMPT", "0")
    .env("GIT_ALLOW_PROTOCOL", "")
    .env("GIT_OPTIONAL_LOCKS", "0")
    .stdin(if input.is_some() {
        Stdio::piped()
    } else {
        Stdio::null()
    })
    .stdout(Stdio::piped())
    .stderr(Stdio::piped())
    .process_group(0);
    let started = Instant::now();
    let mut child = OwnedGroup(cmd.spawn().context("start Git evaluation command")?);
    #[cfg(test)]
    tests::observe_spawn(&child.0);
    let mut stdout = child.0.stdout.take().context("missing Git stdout")?;
    let mut stderr = child.0.stderr.take().context("missing Git stderr")?;
    let mut stdin = child.0.stdin.take();
    let mut input_offset = 0;
    for fd in [
        Some(stdout.as_raw_fd()),
        Some(stderr.as_raw_fd()),
        stdin.as_ref().map(AsRawFd::as_raw_fd),
    ]
    .into_iter()
    .flatten()
    {
        // SAFETY: the owned descriptors are pipe read ends.
        unsafe {
            let flags = libc::fcntl(fd, libc::F_GETFL);
            if flags < 0 || libc::fcntl(fd, libc::F_SETFL, flags | libc::O_NONBLOCK) < 0 {
                return Err(std::io::Error::last_os_error()).context("nonblocking Git pipe");
            }
        }
    }
    let mut output = Vec::new();
    let mut errors = Vec::new();
    let mut eof = [false; 2];
    loop {
        ensure!(!ctx.cancel.is_cancelled(), "Git evaluation cancelled");
        ensure!(
            started.elapsed() < timeout,
            "Git evaluation command deadline exceeded"
        );
        if let Some(pipe) = &mut stdin {
            let input = input.context("missing Git input")?;
            if input_offset < input.len() {
                let end = input.len().min(input_offset + 65536);
                match pipe.write(&input[input_offset..end]) {
                    Ok(0) => bail!("Git evaluation input closed"),
                    Ok(n) => input_offset += n,
                    Err(e)
                        if matches!(
                            e.kind(),
                            std::io::ErrorKind::WouldBlock | std::io::ErrorKind::Interrupted
                        ) => {}
                    Err(e) => return Err(e).context("write Git evaluation input"),
                }
            }
            if input_offset == input.len() {
                stdin.take();
            }
        }
        for (index, (pipe, bytes, limit)) in [
            (&mut stdout as &mut dyn Read, &mut output, max),
            (&mut stderr as &mut dyn Read, &mut errors, MAX_STDERR),
        ]
        .into_iter()
        .enumerate()
        {
            let mut buffer = [0; 65536];
            match pipe.read(&mut buffer) {
                Ok(0) => eof[index] = true,
                Ok(n) => {
                    ensure!(
                        bytes.len().checked_add(n).is_some_and(|n| n <= limit),
                        "Git evaluation output limit exceeded"
                    );
                    bytes.extend_from_slice(&buffer[..n]);
                }
                Err(e)
                    if matches!(
                        e.kind(),
                        std::io::ErrorKind::WouldBlock | std::io::ErrorKind::Interrupted
                    ) => {}
                Err(e) => return Err(e).context("read Git evaluation output"),
            }
        }
        let mut status: libc::siginfo_t = unsafe { std::mem::zeroed() };
        // SAFETY: inspect only our owned leader, leaving its PID pinned for Drop.
        let rc = unsafe {
            libc::waitid(
                libc::P_PID,
                child.0.id(),
                &mut status,
                libc::WEXITED | libc::WNOHANG | libc::WNOWAIT,
            )
        };
        if rc != 0 {
            return Err(std::io::Error::last_os_error()).context("inspect Git evaluation child");
        }
        if unsafe { status.si_pid() } != 0 && eof.iter().all(|v| *v) {
            if status.si_code != libc::CLD_EXITED || unsafe { status.si_status() } != 0 {
                bail!("Git evaluation command failed (requires Git --no-lazy-fetch support and local objects)");
            }
            ensure!(
                input.is_none_or(|bytes| input_offset == bytes.len()),
                "Git evaluation input incomplete"
            );
            return Ok(output);
        }
        std::thread::sleep(Duration::from_millis(2));
    }
}

#[cfg(test)]
mod tests;