CI & release: enforce executable regression checks, PR gates, Windows unit tests, and Mac release gate (#1128)

* CI & release: enforce executable regression checks, PR gates, Windows unit tests, and Mac release gate

* Compose: keep empty environment variables distinct instead of gluing onto preceding entry
This commit is contained in:
Precious Okwu authored and GitHub committed 2026-12-02 02:41:04 +01:00
1 parent 5c29328c44
commit 3db7378e5b
15 files changed
+2160 -149

No files matched your search

+595
View File
@@ -0,0 +1,595 @@
#!/usr/bin/env python3
"""Mechanical pull request gates for Kiri's test and regression invariants.
1. No silent `KIRI_TEST_*` early-return skips in Rust unit tests:
Scans `crates/` and `xtask/` for non-`#[ignore]` `#[test]` functions (and
`#[cfg(test)]` helpers) that read a `KIRI_TEST_*` environment variable not
spawned by `.env(...)` in the same file and return early instead of running
or failing. Child-process re-entry helpers that spawn `current_exe()` with
`.env(...)` in the same file are permitted.
2. Closing issue keywords require a regression entry:
When `--base` and `--head` (or `PR_TITLE` / `PR_BODY`) are given, every
same-repo `#N` matched by GitHub's closing keywords (`fix`, `fixes`, `fixed`,
`close`, `closes`, `closed`, `resolve`, `resolves`, `resolved`) in commit
messages in `base..head`, `PR_TITLE`, or `PR_BODY` must appear in the second
column of `tests/regressions.tsv`, unless `--skip-issue-check` is set (from
the `no-regression-needed` pull request label).
Standard library only.
python3 scripts/ci/check-pr-gates.py [--base HEAD^1 --head HEAD] [--skip-issue-check]
"""
import argparse
import os
import pathlib
import re
import subprocess
import sys
REPO = pathlib.Path(__file__).resolve().parent.parent.parent
IDENT = re.compile(r"[^\W\d]\w*")
RAW_STR = re.compile(r'(?:b|c)?r(#*)"')
NUMBER = re.compile(r"\d[\w]*(?:\.\d[\w]*)?")
CLOSING_ISSUE = re.compile(
r"(?<![A-Za-z0-9_/-])(?:fix(?:es|ed)?|clos(?:es|ed)?|resolv(?:es|ed)?):?\s+#([0-9]+)\b",
re.IGNORECASE,
)
HTML_COMMENT = re.compile(r"<!--.*?-->", re.DOTALL)
# KIRI_TEST_REGISTRY selects the container image mirror rather than gating execution.
NON_SKIP_ENVS = frozenset({"KIRI_TEST_REGISTRY"})
class Tok:
__slots__ = ("kind", "text", "line")
def __init__(self, kind, text, line):
self.kind, self.text, self.line = kind, text, line
def tokenize_rust(src):
toks = []
i, n, line = 0, len(src), 1
while i < n:
c = src[i]
if c == "\n":
line += 1
i += 1
elif c.isspace():
i += 1
elif src.startswith("//", i):
j = src.find("\n", i)
i = n if j < 0 else j
elif src.startswith("/*", i):
depth, j, start = 0, i, line
while j < n:
if src.startswith("/*", j):
depth += 1
j += 2
elif src.startswith("*/", j):
depth -= 1
j += 2
if depth == 0:
break
else:
if src[j] == "\n":
line += 1
j += 1
if depth != 0:
raise ValueError(f"unclosed block comment from line {start}")
i = j
elif (m := RAW_STR.match(src, i)) is not None:
close = '"' + m.group(1)
j = src.find(close, m.end())
if j < 0:
raise ValueError(f"unclosed raw string from line {line}")
text = src[i : j + len(close)]
toks.append(Tok("str", text, line))
line += text.count("\n")
i = j + len(close)
elif c == '"' or (c in "bc" and src.startswith('"', i + 1)):
j = i + (1 if c == '"' else 2)
while j < n and src[j] != '"':
j += 2 if src[j] == "\\" else 1
if j >= n:
raise ValueError(f"unclosed string from line {line}")
text = src[i : j + 1]
toks.append(Tok("str", text, line))
line += text.count("\n")
i = j + 1
elif c == "'" or (c == "b" and src.startswith("'", i + 1)):
q = i if c == "'" else i + 1
if src.startswith("\\", q + 1):
j = src.find("'", q + 3)
if j < 0 or "\n" in src[q:j]:
raise ValueError(f"unclosed char literal on line {line}")
toks.append(Tok("char", src[i : j + 1], line))
i = j + 1
elif q + 2 < n and src[q + 2] == "'" and src[q + 1] != "\n":
toks.append(Tok("char", src[i : q + 3], line))
i = q + 3
elif c == "'" and (m := IDENT.match(src, q + 1)) is not None:
toks.append(Tok("life", src[i : m.end()], line))
i = m.end()
else:
toks.append(Tok("punct", c, line))
i += 1
elif c == "r" and src.startswith("#", i + 1) and (m := IDENT.match(src, i + 2)) is not None:
toks.append(Tok("ident", src[i + 2 : m.end()], line))
i = m.end()
elif (m := IDENT.match(src, i)) is not None:
toks.append(Tok("ident", m.group(), line))
i = m.end()
elif c.isdigit():
m = NUMBER.match(src, i)
toks.append(Tok("num", m.group(), line))
i = m.end()
else:
toks.append(Tok("punct", c, line))
i += 1
return toks
def match_brackets(toks):
opens, closes = "([{", ")]}"
pairs, stack = {}, []
for idx, t in enumerate(toks):
if t.kind != "punct":
continue
if t.text in opens:
stack.append(idx)
elif t.text in closes:
if not stack or opens.index(toks[stack[-1]].text) != closes.index(t.text):
raise ValueError(f"unbalanced {t.text!r} on line {t.line}")
o = stack.pop()
pairs[o], pairs[idx] = idx, o
if stack:
raise ValueError(f"unclosed {toks[stack[-1]].text!r} from line {toks[stack[-1]].line}")
return pairs
def str_value(tok):
t = tok.text
m = RAW_STR.match(t)
if m:
return t[m.end() : len(t) - 1 - len(m.group(1))]
if t[0] in "bc":
t = t[1:]
return t[1:-1].replace("\\\\", "\\").replace('\\"', '"')
def _attr_is_test(tokens):
if not tokens:
return False
if len(tokens) == 1 and tokens[0].kind == "ident" and tokens[0].text == "test":
return True
if tokens[-1].kind == "ident" and tokens[-1].text == "test":
if all(t.kind == "ident" or t.text == ":" for t in tokens[:-1]):
return True
if tokens[0].kind == "ident" and tokens[0].text == "cfg_attr":
return any(t.kind == "ident" and t.text == "test" for t in tokens[1:])
return False
def _attr_is_ignore(tokens):
if not tokens:
return False
if tokens[0].kind == "ident" and tokens[0].text == "ignore":
return True
if tokens[0].kind == "ident" and tokens[0].text == "cfg_attr":
return any(t.kind == "ident" and t.text == "ignore" for t in tokens[1:])
return False
def _attr_mentions_cfg_test(tokens):
if len(tokens) >= 4 and tokens[0].kind == "ident" and tokens[0].text == "cfg":
return any(t.kind == "ident" and t.text == "test" for t in tokens[1:])
return False
def _collect_consts(toks, lo, hi):
"""Finds `const NAME: ... = "KIRI_TEST_...";` bindings inside `toks[lo:hi]`."""
consts = {}
i = lo
while i + 5 < hi:
if toks[i].kind == "ident" and toks[i].text == "const" and toks[i + 1].kind == "ident":
name = toks[i + 1].text
j = i + 2
while j < hi and toks[j].text != ";" and toks[j].text != "=":
j += 1
if j + 1 < hi and toks[j].text == "=" and toks[j + 1].kind == "str":
val = str_value(toks[j + 1])
if val.startswith("KIRI_TEST_"):
consts[name] = val
i += 1
return consts
def _resolve_env_arg(toks, arg_lo, arg_hi, consts):
if arg_lo >= arg_hi:
return None
# Direct string literal: "KIRI_TEST_..." or &str reference
for k in range(arg_lo, min(arg_lo + 3, arg_hi)):
if toks[k].kind == "str":
val = str_value(toks[k])
return val if val.startswith("KIRI_TEST_") and val not in NON_SKIP_ENVS else None
if toks[k].kind == "ident" and toks[k].text in consts:
val = consts[toks[k].text]
return val if val not in NON_SKIP_ENVS else None
return None
def _collect_spawned_envs(toks, pairs, lo, hi, consts):
"""Finds `KIRI_TEST_*` names passed to `.env(NAME, ...)` in `toks[lo:hi]`."""
spawned = set()
i = lo
while i + 3 < hi:
if (
toks[i].text == "."
and toks[i + 1].kind == "ident"
and toks[i + 1].text == "env"
and toks[i + 2].text == "("
and (i + 2) in pairs
):
close = pairs[i + 2]
comma = next((k for k in range(i + 3, close) if toks[k].text == ","), close)
val = _resolve_env_arg(toks, i + 3, comma, consts)
if val:
spawned.add(val)
i += 1
return spawned
def _collect_env_reads(toks, pairs, lo, hi, consts):
"""Finds `(env_name, line)` read via `var`, `var_os`, or `option_env!` in `toks[lo:hi]`."""
reads = []
i = lo
while i + 2 < hi:
# var(...) / var_os(...)
if (
toks[i].kind == "ident"
and toks[i].text in ("var", "var_os")
and toks[i + 1].text == "("
and (i + 1) in pairs
):
# Exclude method calls like `foo.var(...)` (unless `::var(...)` or bare `var(...)`).
if i == lo or toks[i - 1].text != ".":
close = pairs[i + 1]
val = _resolve_env_arg(toks, i + 2, close, consts)
if val:
reads.append((val, toks[i].line))
# option_env!("KIRI_TEST_...")
elif (
i + 3 < hi
and toks[i].kind == "ident"
and toks[i].text == "option_env"
and toks[i + 1].text == "!"
and toks[i + 2].text in "([{"
and (i + 2) in pairs
):
close = pairs[i + 2]
val = _resolve_env_arg(toks, i + 3, close, consts)
if val:
reads.append((val, toks[i].line))
i += 1
return reads
def scan_rust_file(text, rel_path):
"""Scans one Rust source file for silent `KIRI_TEST_*` skips in unit tests."""
try:
toks = tokenize_rust(text)
pairs = match_brackets(toks)
except ValueError as exc:
return [f"{rel_path}: cannot tokenise Rust source: {exc}"]
file_consts = _collect_consts(toks, 0, len(toks))
functions = [] # (fn_name, fn_line, is_test, is_ignored, in_cfg_test, body_lo, body_hi, consts)
def walk(lo, hi, in_cfg_test, scope_consts):
local_consts = dict(scope_consts)
local_consts.update(_collect_consts(toks, lo, hi))
i = lo
# Inner `#![cfg(test)]` attribute at module/file top.
while (
i + 2 < hi
and toks[i].text == "#"
and toks[i + 1].text == "!"
and toks[i + 2].text == "["
and (i + 2) in pairs
):
close = pairs[i + 2]
if _attr_mentions_cfg_test(toks[i + 3 : close]):
in_cfg_test = True
i = close + 1
while i < hi:
attrs = []
while (
i + 1 < hi
and toks[i].text == "#"
and toks[i + 1].text == "["
and (i + 1) in pairs
):
close = pairs[i + 1]
attrs.append(toks[i + 2 : close])
i = close + 1
if i >= hi:
break
j = i
if j < hi and toks[j].kind == "ident" and toks[j].text == "pub":
j += 1
if j < hi and toks[j].text == "(" and j in pairs:
j = pairs[j] + 1
while j < hi and toks[j].kind == "ident" and toks[j].text in ("async", "unsafe", "const", "extern"):
j += 1
if j < hi and toks[j].kind == "str":
j += 1
item_cfg_test = in_cfg_test or any(_attr_mentions_cfg_test(a) for a in attrs)
if j + 1 < hi and toks[j].kind == "ident" and toks[j].text == "mod" and toks[j + 1].kind == "ident":
if j + 2 < hi and toks[j + 2].text == "{" and (j + 2) in pairs:
close = pairs[j + 2]
walk(j + 3, close, item_cfg_test, local_consts)
i = close + 1
continue
if j + 1 < hi and toks[j].kind == "ident" and toks[j].text == "fn" and toks[j + 1].kind == "ident":
fn_name = toks[j + 1].text
fn_line = toks[j].line
# Find the function body `{ ... }` or `;` (for trait declarations).
k = j + 2
body_open = None
while k < hi:
if toks[k].text == ";" and body_open is None:
i = k + 1
break
if toks[k].text in "([" and k in pairs:
k = pairs[k] + 1
continue
if toks[k].text == "{" and k in pairs:
# Might be inside a `where` bound only if rare; first top-level `{` is the fn body.
body_open = k
break
k += 1
if body_open is not None:
body_close = pairs[body_open]
fn_consts = dict(local_consts)
fn_consts.update(_collect_consts(toks, body_open + 1, body_close))
is_test = any(_attr_is_test(a) for a in attrs)
is_ignored = any(_attr_is_ignore(a) for a in attrs)
functions.append(
(
fn_name,
fn_line,
is_test,
is_ignored,
item_cfg_test,
body_open + 1,
body_close,
fn_consts,
)
)
# Also walk nested items inside the function body.
walk(body_open + 1, body_close, item_cfg_test, fn_consts)
i = body_close + 1
continue
if toks[i].text in "([{" and i in pairs:
i = pairs[i] + 1
else:
i += 1
walk(0, len(toks), False, file_consts)
# Collect KIRI_TEST_* variables spawned via `.env(...)` in non-ignored functions.
spawned = set()
for _name, _line, _is_test, is_ignored, _in_cfg_test, b_lo, b_hi, fn_consts in functions:
if not is_ignored:
spawned |= _collect_spawned_envs(toks, pairs, b_lo, b_hi, fn_consts)
# Map cfg(test) helper functions that read unspawned KIRI_TEST_* variables.
helper_unspawned = {}
for fn_name, _fn_line, is_test, is_ignored, in_cfg_test, b_lo, b_hi, fn_consts in functions:
if is_ignored or is_test or not in_cfg_test:
continue
reads = [(v, ln) for v, ln in _collect_env_reads(toks, pairs, b_lo, b_hi, fn_consts) if v not in spawned]
if reads:
helper_unspawned[fn_name] = reads
errors = []
seen = set()
for fn_name, fn_line, is_test, is_ignored, in_cfg_test, b_lo, b_hi, fn_consts in functions:
if is_ignored:
continue
body_toks = toks[b_lo:b_hi]
has_return = any(t.kind == "ident" and t.text == "return" for t in body_toks)
has_soft_probe = any(
t.kind == "ident" and t.text in ("ok", "is_err", "is_none", "unwrap_or", "unwrap_or_default", "unwrap_or_else")
for t in body_toks
)
if is_test:
for env_name, read_line in _collect_env_reads(toks, pairs, b_lo, b_hi, fn_consts):
if env_name not in spawned and (has_return or has_soft_probe):
key = (rel_path, read_line, env_name)
if key not in seen:
seen.add(key)
errors.append(
f"{rel_path}:{read_line}: #[test] fn {fn_name} (line {fn_line}) reads {env_name} "
"and can return without running; remove the KIRI_TEST_* gate so the test always "
"executes, or mark manual-only tests #[ignore]"
)
if has_return and helper_unspawned:
called = {
body_toks[idx].text
for idx in range(len(body_toks) - 1)
if body_toks[idx].kind == "ident"
and body_toks[idx + 1].text == "("
and body_toks[idx].text in helper_unspawned
}
for helper in sorted(called):
for env_name, read_line in helper_unspawned[helper]:
key = (rel_path, read_line, env_name)
if key not in seen:
seen.add(key)
errors.append(
f"{rel_path}:{read_line}: test helper fn {helper} (called by #[test] fn "
f"{fn_name} at line {fn_line}) reads {env_name} for an early-return skip; "
"remove the KIRI_TEST_* gate or mark manual-only tests #[ignore]"
)
elif in_cfg_test and has_return:
for env_name, read_line in _collect_env_reads(toks, pairs, b_lo, b_hi, fn_consts):
if env_name not in spawned:
key = (rel_path, read_line, env_name)
if key not in seen:
seen.add(key)
errors.append(
f"{rel_path}:{read_line}: test helper fn {fn_name} (line {fn_line}) reads "
f"{env_name} and returns early; silent KIRI_TEST_* skips are banned"
)
return errors
def check_silent_test_skips(repo=REPO):
repo = pathlib.Path(repo)
errors = []
for sub in ("crates", "xtask"):
base = repo / sub
if not base.is_dir():
continue
for rs_path in sorted(base.rglob("*.rs")):
rel = rs_path.relative_to(repo).as_posix()
errors.extend(scan_rust_file(rs_path.read_text(encoding="utf-8"), rel))
return errors
def extract_closing_issues(text):
"""Returns ordered unique list of `#N` strings matched by GitHub closing keywords."""
if not text:
return []
cleaned = HTML_COMMENT.sub(" ", text)
seen = set()
out = []
for m in CLOSING_ISSUE.finditer(cleaned):
issue = f"#{int(m.group(1))}"
if issue not in seen:
seen.add(issue)
out.append(issue)
return out
def regressions_issues(table_path):
issues = set()
for line in pathlib.Path(table_path).read_text(encoding="utf-8").splitlines():
if not line.strip() or line.startswith("#"):
continue
cols = line.split("\t")
if len(cols) == 3 and re.fullmatch(r"#[0-9]+", cols[1]) and cols[2].strip():
issues.add(cols[1])
return issues
def check_closing_issues(repo=REPO, commit_messages=(), pr_title="", pr_body="", table_path=None):
repo = pathlib.Path(repo)
table = pathlib.Path(table_path) if table_path is not None else repo / "tests/regressions.tsv"
covered = regressions_issues(table)
sources = []
for msg in commit_messages:
for issue in extract_closing_issues(msg):
sources.append((issue, "commit message"))
for issue in extract_closing_issues(pr_title):
sources.append((issue, "PR title"))
for issue in extract_closing_issues(pr_body):
sources.append((issue, "PR description"))
by_issue = {}
order = []
for issue, where in sources:
if issue not in by_issue:
by_issue[issue] = []
order.append(issue)
if where not in by_issue[issue]:
by_issue[issue].append(where)
errors = []
for issue in order:
if issue not in covered:
places = ", ".join(by_issue[issue])
errors.append(
f"tests/regressions.tsv: missing regression check for {issue} (referenced in {places}). "
f"Add an executable check for {issue} to tests/regressions.tsv, or add the pull request "
"label no-regression-needed if no regression test applies."
)
return errors
def git_commit_messages(repo, base, head):
out = subprocess.run(
["git", "log", "--format=%B%x00", f"{base}..{head}"],
cwd=repo,
check=True,
capture_output=True,
text=True,
).stdout
return [chunk for chunk in out.split("\x00") if chunk.strip()]
def write_summary(errors):
summary_path = os.environ.get("GITHUB_STEP_SUMMARY")
if not summary_path or not errors:
return
lines = ["### Pull request gate failures", ""]
lines.extend(f"- {err}" for err in errors)
lines.append("")
with open(summary_path, "a", encoding="utf-8") as f:
f.write("\n".join(lines))
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--repo", type=pathlib.Path, default=REPO)
parser.add_argument("--base", default=None, help="Base git revision (for example HEAD^1)")
parser.add_argument("--head", default=None, help="Head git revision (for example HEAD)")
parser.add_argument("--pr-title", default=None, help="Pull request title (defaults to $PR_TITLE)")
parser.add_argument("--pr-body", default=None, help="Pull request body (defaults to $PR_BODY)")
parser.add_argument(
"--skip-issue-check",
action="store_true",
help="Skip the Fixes/Closes/Resolves #N -> tests/regressions.tsv check (label no-regression-needed)",
)
args = parser.parse_args(argv)
if (args.base is None) != (args.head is None):
parser.error("--base and --head must be given together")
errors = check_silent_test_skips(args.repo)
pr_title = args.pr_title if args.pr_title is not None else os.environ.get("PR_TITLE", "")
pr_body = args.pr_body if args.pr_body is not None else os.environ.get("PR_BODY", "")
if not args.skip_issue_check and (args.base is not None or pr_title or pr_body):
commits = git_commit_messages(args.repo, args.base, args.head) if args.base is not None else ()
errors.extend(
check_closing_issues(
args.repo,
commit_messages=commits,
pr_title=pr_title,
pr_body=pr_body,
)
)
for err in errors:
print(err)
write_summary(errors)
if errors:
print(f"check-pr-gates: {len(errors)} problem(s) found")
return 1
print("check-pr-gates: all checks passed")
return 0
if __name__ == "__main__":
sys.exit(main())
+300
View File
@@ -0,0 +1,300 @@
#!/usr/bin/env python3
"""Unit tests for scripts/ci/check-pr-gates.py and tests/lib/check-regressions.py.
python3 -m unittest discover -s scripts/ci -p 'test_check_pr_gates.py'
"""
import importlib.util
import os
import pathlib
import subprocess
import tempfile
import unittest
HERE = pathlib.Path(__file__).resolve().parent
REPO = HERE.parent.parent
_gates_spec = importlib.util.spec_from_file_location("check_pr_gates", HERE / "check-pr-gates.py")
gates = importlib.util.module_from_spec(_gates_spec)
_gates_spec.loader.exec_module(gates)
_reg_spec = importlib.util.spec_from_file_location("check_regressions", REPO / "tests/lib/check-regressions.py")
reg = importlib.util.module_from_spec(_reg_spec)
_reg_spec.loader.exec_module(reg)
class SilentSkipGateTests(unittest.TestCase):
def test_flags_let_else_early_return_in_unit_test(self):
src = """
#[cfg(test)]
mod tests {
#[test]
fn grows_when_configured() {
let Ok(dev) = std::env::var("KIRI_TEST_EXT4_DEV") else {
return;
};
assert!(!dev.is_empty());
}
}
"""
errs = gates.scan_rust_file(src, "crates/kiri-init/src/linux/disk.rs")
self.assertEqual(len(errs), 1)
self.assertIn("KIRI_TEST_EXT4_DEV", errs[0])
self.assertIn("grows_when_configured", errs[0])
def test_flags_const_alias_and_helper_wrapped_skip(self):
src = """
#[cfg(test)]
mod tests {
const OPT_IN: &str = "KIRI_TEST_NEED_LOOP";
fn loop_dev() -> Option<String> {
std::env::var(OPT_IN).ok()
}
#[test]
fn mounts_loop() {
let Some(d) = loop_dev() else { return };
assert!(!d.is_empty());
}
}
"""
errs = gates.scan_rust_file(src, "crates/kiri/src/loop_test.rs")
self.assertEqual(len(errs), 1)
self.assertIn("KIRI_TEST_NEED_LOOP", errs[0])
def test_allows_child_process_reentry_in_same_file(self):
src = """
#[cfg(test)]
mod tests {
const CHILD: &str = "KIRI_TEST_UMASK_CHILD";
#[test]
fn runs_isolated_child() {
if std::env::var_os(CHILD).is_some() {
return;
}
let status = std::process::Command::new(std::env::current_exe().unwrap())
.env(CHILD, "1")
.status()
.unwrap();
assert!(status.success());
}
}
"""
self.assertEqual(gates.scan_rust_file(src, "crates/kiri/src/umask.rs"), [])
def test_allows_split_parent_and_child_tests_in_same_file(self):
src = """
#[cfg(test)]
mod kill_points {
const CHILD: &str = "KIRI_TEST_STORE_CHILD";
fn in_child() {
let _ = std::process::Command::new("exe").env(CHILD, "/tmp/x").status();
}
#[test]
fn child_entry() {
let Some(_root) = std::env::var_os(CHILD) else { return };
}
#[test]
fn parent_driver() {
if std::env::var_os(CHILD).is_some() { return; }
in_child();
}
}
"""
self.assertEqual(gates.scan_rust_file(src, "crates/kiri-image/src/store.rs"), [])
def test_ignored_test_allowed_and_cannot_excuse_unignored_skip(self):
src = """
#[cfg(test)]
mod tests {
#[test]
#[ignore = "manual stress test"]
fn manual_only() {
let Some(_) = std::env::var_os("KIRI_TEST_MANUAL") else { return };
let _ = std::process::Command::new("exe").env("KIRI_TEST_SNEAKY", "1");
}
#[test]
fn unignored_sneaky_skip() {
let Some(_) = std::env::var_os("KIRI_TEST_SNEAKY") else { return };
}
}
"""
errs = gates.scan_rust_file(src, "crates/kiri/src/sneaky.rs")
self.assertEqual(len(errs), 1)
self.assertIn("KIRI_TEST_SNEAKY", errs[0])
def test_comments_and_plain_strings_do_not_trigger(self):
src = """
#[cfg(test)]
mod tests {
// std::env::var("KIRI_TEST_COMMENT") else { return; }
/* std::env::var("KIRI_TEST_BLOCK") */
#[test]
fn plain_assertion() {
let msg = "KIRI_TEST_LITERAL_ONLY";
if msg.is_empty() {
return;
}
assert_eq!(msg.len(), 22);
}
}
"""
self.assertEqual(gates.scan_rust_file(src, "crates/kiri/src/clean.rs"), [])
class ClosingIssuesGateTests(unittest.TestCase):
def test_extracts_github_closing_keywords_only(self):
text = (
"Fixes #101, closes: #202 and RESOLVED #303.\n"
"Also (fix #404). External: Fixes docker/cli#999, prefix #888, unfixed #777.\n"
"<!-- Fixes #666 in template comment -->"
)
self.assertEqual(gates.extract_closing_issues(text), ["#101", "#202", "#303", "#404"])
def test_enforces_regressions_tsv_coverage_and_skip_flag(self):
with tempfile.TemporaryDirectory() as tmp:
root = pathlib.Path(tmp)
(root / "tests").mkdir()
(root / "crates/demo/src").mkdir(parents=True)
(root / "tests/regressions.tsv").write_text(
"# header\ncrates/demo/src/lib.rs::guards_101\t#101\twhat broke\n",
encoding="utf-8",
)
(root / "crates/demo/src/lib.rs").write_text(
"#[test]\nfn guards_101() { assert_eq!(1, 1); }\n",
encoding="utf-8",
)
subprocess.run(["git", "init", "-q"], cwd=root, check=True)
subprocess.run(["git", "config", "user.email", "ci@example.com"], cwd=root, check=True)
subprocess.run(["git", "config", "user.name", "CI"], cwd=root, check=True)
subprocess.run(["git", "add", "."], cwd=root, check=True)
subprocess.run(["git", "commit", "-q", "-m", "Initial commit"], cwd=root, check=True)
(root / "crates/demo/src/lib.rs").write_text(
"#[test]\nfn guards_101() { assert_eq!(2, 2); }\n",
encoding="utf-8",
)
subprocess.run(["git", "add", "."], cwd=root, check=True)
subprocess.run(["git", "commit", "-q", "-m", "Engine: fix #101 and closes #202"], cwd=root, check=True)
# Missing #202 in commit message and #303 in PR body -> fails.
rc = gates.main(
[
"--repo",
str(root),
"--base",
"HEAD^1",
"--head",
"HEAD",
"--pr-title",
"Engine: repair",
"--pr-body",
"Resolves #303",
]
)
self.assertEqual(rc, 1)
# With --skip-issue-check (no-regression-needed label) -> passes.
rc_skip = gates.main(
[
"--repo",
str(root),
"--base",
"HEAD^1",
"--head",
"HEAD",
"--pr-body",
"Resolves #303",
"--skip-issue-check",
]
)
self.assertEqual(rc_skip, 0)
# Once #202 and #303 are recorded in tests/regressions.tsv -> passes without skip flag.
(root / "tests/regressions.tsv").write_text(
"# header\n"
"crates/demo/src/lib.rs::guards_101\t#101\tfirst\n"
"crates/demo/src/lib.rs::guards_202\t#202\tsecond\n"
"crates/demo/src/lib.rs::guards_303\t#303\tthird\n",
encoding="utf-8",
)
rc_ok = gates.main(
[
"--repo",
str(root),
"--base",
"HEAD^1",
"--head",
"HEAD",
"--pr-body",
"Resolves #303",
]
)
self.assertEqual(rc_ok, 0)
class CheckRegressionsTableTests(unittest.TestCase):
def test_real_repository_regressions_table_is_clean(self):
rows, errors = reg.check_table(REPO)
self.assertGreater(rows, 400)
self.assertEqual(errors, [])
def test_rejects_unexecuted_and_bare_paths_and_accepts_valid_targets(self):
with tempfile.TemporaryDirectory() as tmp:
root = pathlib.Path(tmp)
for d in ("tests/ui", "scripts", "crates/kiri/src", "guest/kernel/patches"):
(root / d).mkdir(parents=True)
(root / "scripts/ui-test.py").write_text("# runner\n", encoding="utf-8")
(root / "tests/e2e.sh").write_text('#!/bin/bash\nt valid-shell-check "ok"\n', encoding="utf-8")
(root / "tests/disk-grow.py").write_text("print('standalone')\n", encoding="utf-8")
(root / "tests/ui/fixture.js").write_text("// helper\n", encoding="utf-8")
(root / "tests/ui/good.js").write_text('report(["PASS ok"]);\n', encoding="utf-8")
(root / "tests/ui/noreport.js").write_text("console.log('nothing');\n", encoding="utf-8")
(root / "guest/kernel/patches/0001-fix.patch").write_text("diff --git a/x b/x\n", encoding="utf-8")
(root / "crates/kiri/src/lib.rs").write_text(
"""
// #[test]
// fn commented_out() {}
#[test]
fn real_unit_test() {}
#[test]
#[ignore = "manual"]
fn ignored_unit_test() {}
""",
encoding="utf-8",
)
table = root / "tests/regressions.tsv"
table.write_text(
"\n".join(
[
"valid-shell-check\t#1\tshell check",
"tests/ui/good.js\t#2\tui check",
"crates/kiri/src/lib.rs::real_unit_test\t#3\trust check",
"guest/kernel/patches/0001-fix.patch\t#4\tkernel patch",
"crates/kiri/src/lib.rs\t#5\tbare rust file",
"tests/disk-grow.py\t#6\tstandalone python script",
"crates/kiri/src/lib.rs::missing_fn\t#7\tmissing fn",
"crates/kiri/src/lib.rs::ignored_unit_test\t#8\tignored fn",
"crates/kiri/src/lib.rs::commented_out\t#9\tcommented fn",
"tests/ui/fixture.js\t#10\tfixture not a test",
"tests/ui/noreport.js\t#11\tui without report",
"valid-shell-check\t#12\tduplicate check",
]
)
+ "\n",
encoding="utf-8",
)
rows, errors = reg.check_table(root, table)
self.assertEqual(rows, 12)
joined = "\n".join(errors)
self.assertEqual(len(errors), 8, joined)
self.assertIn("bare Rust file crates/kiri/src/lib.rs is not allowed", joined)
self.assertIn("tests/disk-grow.py is not an executed CI check", joined)
self.assertIn("no #[test] fn missing_fn", joined)
self.assertIn("ignored_unit_test in crates/kiri/src/lib.rs is marked #[ignore]", joined)
self.assertIn("no #[test] fn commented_out", joined)
self.assertIn("tests/ui/fixture.js is not discovered by scripts/ui-test.py", joined)
self.assertIn("tests/ui/noreport.js never calls report()", joined)
self.assertIn("valid-shell-check is listed twice", joined)
if __name__ == "__main__":
unittest.main()
+236
View File
@@ -0,0 +1,236 @@
#!/usr/bin/env python3
"""Unit tests for scripts/release-gate-mac.py."""
import importlib.util
import json
from pathlib import Path
import stat
import struct
import subprocess
import tempfile
import unittest
REPO = Path(__file__).resolve().parents[2]
def _load_module():
path = REPO / "scripts/release-gate-mac.py"
spec = importlib.util.spec_from_file_location("release_gate_mac", path)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
return mod
GATE = _load_module()
def _make_cpio(entries: list[tuple[str, int, bytes]], *, include_trailer: bool = True) -> bytes:
buf = bytearray()
ino = 0
def add(name: str, mode: int, payload: bytes) -> None:
nonlocal ino
ino += 1
name_bytes = name.encode("utf-8") + b"\x00"
fields = [
ino,
mode,
0,
0,
1,
0,
len(payload),
0,
0,
0,
0,
len(name_bytes),
0,
]
buf.extend(b"070701")
for val in fields:
buf.extend(f"{val:08x}".encode("ascii"))
buf.extend(name_bytes)
while len(buf) % 4:
buf.append(0)
buf.extend(payload)
while len(buf) % 4:
buf.append(0)
for name, mode, payload in entries:
add(name, mode, payload)
if include_trailer:
ino = -1
add("TRAILER!!!", 0, b"")
return bytes(buf)
def _write_ext4_image(path: Path, *, size: int, magic: int = 0xEF53, compat: int = 0x003C) -> None:
with path.open("wb") as fh:
fh.truncate(size)
sb = bytearray(1024)
struct.pack_into("<H", sb, 0x38, magic)
struct.pack_into("<I", sb, 0x5C, compat)
fh.seek(1024)
fh.write(sb)
class ReleaseGateMacTests(unittest.TestCase):
def test_initramfs_accepts_required_regular_files_and_symlinks(self):
with tempfile.TemporaryDirectory() as tmp:
cpio = Path(tmp) / "initramfs.cpio"
cpio.write_bytes(
_make_cpio([
("./init", stat.S_IFREG | 0o755, b"\x7fELF-kiri-init"),
("sbin/e2fsck", stat.S_IFREG | 0o755, b"\x7fELF-e2fsck"),
("sbin/resize2fs", stat.S_IFLNK | 0o777, b"e2fsck"),
])
)
GATE.verify_initramfs(cpio)
def test_initramfs_rejects_missing_or_empty_tools(self):
with tempfile.TemporaryDirectory() as tmp:
cpio = Path(tmp) / "initramfs.cpio"
# Missing sbin/resize2fs.
cpio.write_bytes(
_make_cpio([
("init", stat.S_IFREG | 0o755, b"init"),
("sbin/e2fsck", stat.S_IFREG | 0o755, b"fsck"),
])
)
with self.assertRaisesRegex(GATE.GateError, "sbin/resize2fs"):
GATE.verify_initramfs(cpio)
# Empty sbin/e2fsck stub.
cpio.write_bytes(
_make_cpio([
("init", stat.S_IFREG | 0o755, b"init"),
("sbin/e2fsck", stat.S_IFREG | 0o755, b""),
("sbin/resize2fs", stat.S_IFREG | 0o755, b"resize"),
])
)
with self.assertRaisesRegex(GATE.GateError, "empty"):
GATE.verify_initramfs(cpio)
# Directory instead of executable binary.
cpio.write_bytes(
_make_cpio([
("init", stat.S_IFREG | 0o755, b"init"),
("sbin/e2fsck", stat.S_IFDIR | 0o755, b""),
("sbin/resize2fs", stat.S_IFREG | 0o755, b"resize"),
])
)
with self.assertRaisesRegex(GATE.GateError, "not a regular file"):
GATE.verify_initramfs(cpio)
# Truncated archive without TRAILER!!!
cpio.write_bytes(
_make_cpio(
[
("init", stat.S_IFREG | 0o755, b"init"),
("sbin/e2fsck", stat.S_IFREG | 0o755, b"fsck"),
("sbin/resize2fs", stat.S_IFREG | 0o755, b"resize"),
],
include_trailer=False,
)
)
with self.assertRaisesRegex(GATE.GateError, "TRAILER"):
GATE.verify_initramfs(cpio)
def test_ext4_superblock_checks_magic_size_and_sparse_super2(self):
with tempfile.TemporaryDirectory() as tmp:
img = Path(tmp) / "data.img"
_write_ext4_image(img, size=64 << 20, magic=0xEF53, compat=0x003C)
GATE.verify_ext4_superblock(img, expected_size=64 << 20)
# Wrong size fails.
with self.assertRaisesRegex(GATE.GateError, "expected"):
GATE.verify_ext4_superblock(img, expected_size=64 << 30)
# Bad magic fails.
_write_ext4_image(img, size=64 << 20, magic=0x1234, compat=0x003C)
with self.assertRaisesRegex(GATE.GateError, "magic"):
GATE.verify_ext4_superblock(img, expected_size=64 << 20)
# sparse_super2 (0x0200) set fails.
_write_ext4_image(img, size=64 << 20, magic=0xEF53, compat=0x003C | 0x0200)
with self.assertRaisesRegex(GATE.GateError, "sparse_super2"):
GATE.verify_ext4_superblock(img, expected_size=64 << 20)
def test_unpack_and_verify_guest_stages_complete_bundle(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
app = root / "Kiri.app"
macos = app / "Contents/MacOS"
guest = app / "Contents/Resources/guest"
macos.mkdir(parents=True)
guest.mkdir(parents=True)
exe = macos / "kiri"
exe.write_bytes(b"#!/bin/sh\nexit 0\n")
exe.chmod(0o755)
(guest / "Image").write_bytes(b"kernel-image")
(guest / "initramfs.cpio").write_bytes(
_make_cpio([
("init", stat.S_IFREG | 0o755, b"init"),
("sbin/e2fsck", stat.S_IFREG | 0o755, b"fsck"),
("sbin/resize2fs", stat.S_IFREG | 0o755, b"resize"),
])
)
raw_dir = root / "raw"
raw_dir.mkdir()
_write_ext4_image(raw_dir / "data.img", size=64 << 30, magic=0xEF53, compat=0x003C)
subprocess.run(
["tar", "-cSzf", str(guest / "data.img.tgz"), "-C", str(raw_dir), "data.img"],
check=True,
)
staged = root / "staged"
GATE.unpack_and_verify_guest(app, staged)
self.assertTrue((staged / "Image").is_file())
self.assertTrue((staged / "initramfs.cpio").is_file())
self.assertEqual((staged / "data.img").stat().st_size, 64 << 30)
def test_bundle_sha256_and_receipt_are_deterministic(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
app = root / "Kiri.app"
(app / "Contents/MacOS").mkdir(parents=True)
exe = app / "Contents/MacOS/kiri"
exe.write_bytes(b"binary-v1")
exe.chmod(0o755)
(app / "Contents/Info.plist").write_text("<plist/>", encoding="utf-8")
digest_a = GATE.bundle_sha256(app)
digest_b = GATE.bundle_sha256(app)
self.assertEqual(digest_a, digest_b)
exe.chmod(0o644)
self.assertNotEqual(digest_a, GATE.bundle_sha256(app))
exe.chmod(0o755)
self.assertEqual(digest_a, GATE.bundle_sha256(app))
exe.write_bytes(b"binary-v2")
digest_c = GATE.bundle_sha256(app)
self.assertNotEqual(digest_a, digest_c)
receipt_file = root / "receipt.json"
written = GATE.write_receipt(
receipt_file,
app,
["guest_assets_present", "packaged_vm_disk_grow"],
head="a" * 40,
app_digest=digest_c,
timestamp="2026-12-02T00:00:00Z",
)
loaded = json.loads(receipt_file.read_text(encoding="utf-8"))
self.assertEqual(loaded, written)
self.assertEqual(loaded["git_head"], "a" * 40)
self.assertEqual(loaded["app_sha256"], digest_c)
self.assertEqual(loaded["timestamp"], "2026-12-02T00:00:00Z")
self.assertEqual(loaded["checks_passed"], ["guest_assets_present", "packaged_vm_disk_grow"])
if __name__ == "__main__":
unittest.main()
+14
View File
@@ -404,6 +404,20 @@ class NotRust(unittest.TestCase):
out, res = run({"README.md": "x\n"})
self.assertFalse(res["scripts"] or res["suites_changed"])
def test_regression_targets_and_gate_scripts_start_scripts_job(self):
out, res = run(edit("crates/kiri/src/shared.rs", "let a = 1;", "let a = 10;"))
self.assertTrue(res["scripts"])
out, res = run({"tests/ui/new-check.js": 'report(["PASS ok"]);\n'})
self.assertTrue(res["scripts"])
self.assertFalse(res["suites_changed"])
out, res = run({"guest/kernel/patches/0012-fix.patch": "diff\n"})
self.assertTrue(res["scripts"])
self.assertEqual({s for s in ts.SYSTEMS if res[s]}, set())
for gate_script in ("scripts/ci/check-pr-gates.py", "scripts/release-gate-mac.py"):
out, res = run({gate_script: "#!/usr/bin/env python3\n"})
self.assertTrue(res["scripts"], gate_script)
self.assertEqual({s for s in ts.SYSTEMS if res[s]}, set(), gate_script)
if __name__ == "__main__":
unittest.main()
+13 -7
View File
@@ -6,10 +6,10 @@
prints, on stdout:
linux=true|false unit: the workspace's unit tests on Linux
windows=true|false windows-build: the Windows app and CLI compile
windows=true|false windows-build: the build and unit tests on Windows
mac=true|false mac-build: the build and unit tests on a Mac
scripts=true|false scripts: the suites' and scripts' own checks
suites_changed=true|false the suites changed (the label run-tests runs them)
scripts=true|false scripts: the suites', scripts' and regression gates' checks
suites_changed=true|false the suites changed (runs e2e-linux on same-repo PRs, or with run-tests)
and, on stderr and in $GITHUB_STEP_SUMMARY when it is set, every changed file
with the jobs it starts and why.
@@ -71,7 +71,7 @@ TARGET = {
# The crates each job builds, as the workflow's commands build them:
# unit cargo test --workspace --exclude kiri-init; cargo test -p kiri-init
# mac-build cargo test --workspace --exclude kiri-init
# windows-build cargo check --target x86_64-pc-windows-msvc -p kiri-win -p kiri
# windows-build cargo test --target x86_64-pc-windows-msvc -p kiri-win -p kiri
# with the path dependencies each needs on that system. Change this with them.
JOBS = {
"linux": {"workspace": True, "exclude": ()},
@@ -88,8 +88,10 @@ PATHS = [
(("guest/kernel/*",), NONE, "Kiri's kernel: a runner runs its own kernel and can't start Kiri's VM"),
(("tests/*", "bench/*"), NONE, "the suites: the label run-tests runs them"),
((".github/workflows/codeql.yml", ".github/workflows/perf.yml", ".github/workflows/ui-tests.yml", "scripts/perf*", "scripts/ui-*",
"scripts/i18n-check.py", "scripts/dmg-*", "scripts/ci/tests-scope.py", "scripts/ci/test_tests_scope.py", "scripts/ci/tests-scope-replay.py",
"scripts/ci/page-scan.py", "scripts/ci/test_page_scan.py"), NONE, "another workflow's or job's own file"),
"scripts/i18n-check.py", "scripts/dmg-*", "scripts/release-gate-mac.py",
"scripts/ci/tests-scope.py", "scripts/ci/test_tests_scope.py", "scripts/ci/tests-scope-replay.py",
"scripts/ci/page-scan.py", "scripts/ci/test_page_scan.py",
"scripts/ci/check-pr-gates.py", "scripts/ci/test_check_pr_gates.py", "scripts/ci/test_release_gate_mac.py"), NONE, "another workflow's or job's own file"),
(("crates/kiri/kiri.entitlements", "xtask/dev-icon.swift"), frozenset({"mac"}), "the Mac app's packaging"),
(("contrib/windows/*", "installer/windows/*"), frozenset({"windows"}), "the Windows app's packaging"),
(("contrib/linux/*", "contrib/wsl/*", "packaging/linux/*", "scripts/kiri-linux.sh", "scripts/windows-engine.sh", "scripts/ci/linux-*"),
@@ -98,9 +100,13 @@ PATHS = [
def scripts_job(path):
"""The `scripts` job: the suites' and scripts' shell and Python files."""
"""The `scripts` job: the suites, scripts, and files regressions.tsv names."""
if path.startswith(("tests/", "scripts/")) and path.endswith((".sh", ".py")):
return True
if path.endswith(".rs") and path.startswith(("crates/", "xtask/")):
return True
if path.startswith(("tests/ui/", "guest/kernel/patches/")):
return True
return path == "tests/regressions.tsv" or path.startswith("tests/lib/")
+426
View File
@@ -0,0 +1,426 @@
#!/usr/bin/env python3
"""Hardware release gate for a packaged macOS Kiri.app bundle.
Runs on an Apple Silicon Mac before a release is notarised or published:
python3 scripts/release-gate-mac.py target/Kiri.app [--receipt target/release-gate-receipt.json]
Checks:
1. Contents/MacOS/kiri and Contents/Resources/guest/{Image,initramfs.cpio,data.img.tgz}
exist, initramfs.cpio contains init, sbin/e2fsck, and sbin/resize2fs, and
data.img.tgz unpacks to a 64 GiB sparse ext4 image without sparse_super2.
2. `codesign --verify --deep --strict` passes on Kiri.app and Contents/MacOS/kiri
carries `com.apple.security.virtualization`.
3. `tests/disk-grow.py` passes against the packaged binary and unpacked guest
assets inside an isolated `/tmp` sandbox without touching `~/.kiri`.
4. Writes an atomic JSON pass receipt (`git_head`, `app_sha256`, `timestamp`,
`checks_passed`).
"""
import argparse
from datetime import datetime, timezone
import hashlib
import json
import os
from pathlib import Path
import platform
import plistlib
import posixpath
import shutil
import stat
import struct
import subprocess
import sys
import tempfile
EXT4_SUPERBLOCK_OFFSET = 1024
EXT4_SUPERBLOCK_SIZE = 1024
EXT4_SUPER_MAGIC = 0xEF53
EXT2_FEATURE_COMPAT_SPARSE_SUPER2 = 0x0200
EXPECTED_TEMPLATE_BYTES = 64 << 30
REQUIRED_GUEST_FILES = ("Image", "initramfs.cpio", "data.img.tgz")
REQUIRED_INITRAMFS_TOOLS = ("init", "sbin/e2fsck", "sbin/resize2fs")
class GateError(RuntimeError):
"""Raised when any release gate check fails."""
def _normalise_cpio_name(raw_name: str) -> str:
name = raw_name.replace("\\", "/")
while name.startswith("./"):
name = name[2:]
name = name.lstrip("/")
return posixpath.normpath(name) if name else ""
def parse_cpio_newc(data: bytes) -> dict[str, tuple[int, int, bytes]]:
"""Parse an uncompressed newc (070701/070702) initramfs archive.
Returns a mapping of normalised archive path to (mode, filesize, payload).
"""
entries: dict[str, tuple[int, int, bytes]] = {}
offset = 0
total = len(data)
saw_trailer = False
while offset < total:
# Concatenated cpio archives may be padded with NUL bytes between segments.
while offset < total and data[offset] == 0:
offset += 1
if offset >= total:
break
if offset + 110 > total:
raise GateError(f"truncated cpio header at byte {offset}")
magic = data[offset : offset + 6]
if magic not in (b"070701", b"070702"):
raise GateError(f"unsupported initramfs header magic {magic!r} at byte {offset} (expected uncompressed newc)")
try:
mode = int(data[offset + 14 : offset + 22].decode("ascii"), 16)
filesize = int(data[offset + 54 : offset + 62].decode("ascii"), 16)
namesize = int(data[offset + 94 : offset + 102].decode("ascii"), 16)
except (UnicodeDecodeError, ValueError) as exc:
raise GateError(f"malformed cpio hex header at byte {offset}: {exc}") from exc
if namesize < 1:
raise GateError(f"invalid cpio namesize {namesize} at byte {offset}")
name_start = offset + 110
name_end = name_start + namesize
if name_end > total:
raise GateError(f"truncated cpio entry name at byte {offset}")
name_bytes = data[name_start:name_end]
if not name_bytes.endswith(b"\x00"):
raise GateError(f"cpio entry name at byte {offset} is missing NUL terminator")
raw_name = name_bytes[:-1].decode("utf-8", errors="replace")
data_start = (name_end + 3) & ~3
data_end = data_start + filesize
if data_end > total:
raise GateError(f"truncated cpio payload for {raw_name!r} at byte {offset}")
payload = data[data_start:data_end]
offset = (data_end + 3) & ~3
if raw_name == "TRAILER!!!":
saw_trailer = True
continue
norm = _normalise_cpio_name(raw_name)
if norm and norm != ".":
entries[norm] = (mode, filesize, payload)
if not saw_trailer:
raise GateError("initramfs.cpio is missing TRAILER!!! sentinel")
return entries
def _resolve_cpio_entry(
entries: dict[str, tuple[int, int, bytes]],
path: str,
depth: int = 0,
) -> tuple[int, int]:
if depth > 16:
raise GateError(f"initramfs symlink loop while resolving {path!r}")
if path not in entries:
raise GateError(f"initramfs.cpio is missing required entry {path!r}")
mode, filesize, payload = entries[path]
kind = stat.S_IFMT(mode)
if kind == stat.S_IFLNK:
target_raw = payload.decode("utf-8", errors="replace").rstrip("\x00")
if not target_raw:
raise GateError(f"initramfs symlink {path!r} has an empty target")
if target_raw.startswith("/"):
resolved = _normalise_cpio_name(target_raw)
else:
parent = posixpath.dirname(path)
resolved = _normalise_cpio_name(posixpath.join(parent, target_raw))
return _resolve_cpio_entry(entries, resolved, depth + 1)
if kind != stat.S_IFREG:
raise GateError(f"initramfs entry {path!r} is not a regular file (mode 0o{mode:o})")
if filesize <= 0:
raise GateError(f"initramfs entry {path!r} is empty (0 bytes)")
return mode, filesize
def verify_initramfs(
cpio_path: Path,
required: tuple[str, ...] = REQUIRED_INITRAMFS_TOOLS,
) -> None:
if not cpio_path.is_file():
raise GateError(f"missing initramfs archive: {cpio_path}")
entries = parse_cpio_newc(cpio_path.read_bytes())
for item in required:
_resolve_cpio_entry(entries, item)
def verify_ext4_superblock(
img_path: Path,
expected_size: int | None = EXPECTED_TEMPLATE_BYTES,
) -> None:
if not img_path.is_file():
raise GateError(f"missing unpacked disk image: {img_path}")
info = img_path.stat()
if expected_size is not None and info.st_size != expected_size:
raise GateError(
f"{img_path}: expected {expected_size} bytes ({expected_size >> 30} GiB), got {info.st_size}"
)
if info.st_size < EXT4_SUPERBLOCK_OFFSET + EXT4_SUPERBLOCK_SIZE:
raise GateError(f"{img_path}: file too small ({info.st_size} bytes) to hold an ext4 superblock")
with img_path.open("rb") as fh:
fh.seek(EXT4_SUPERBLOCK_OFFSET)
sb = fh.read(EXT4_SUPERBLOCK_SIZE)
if len(sb) != EXT4_SUPERBLOCK_SIZE:
raise GateError(f"{img_path}: short read of ext4 superblock")
magic = struct.unpack_from("<H", sb, 0x38)[0]
if magic != EXT4_SUPER_MAGIC:
raise GateError(
f"{img_path}: invalid ext4 superblock magic 0x{magic:04x} (expected 0x{EXT4_SUPER_MAGIC:04x})"
)
compat = struct.unpack_from("<I", sb, 0x5C)[0]
if compat & EXT2_FEATURE_COMPAT_SPARSE_SUPER2:
raise GateError(
f"{img_path}: ext4 compatible feature sparse_super2 (0x{EXT2_FEATURE_COMPAT_SPARSE_SUPER2:04x}) "
f"is set in s_feature_compat=0x{compat:08x}"
)
def unpack_and_verify_guest(app_path: Path, guest_stage_dir: Path) -> None:
exe = app_path / "Contents/MacOS/kiri"
if not exe.is_file() or not os.access(exe, os.X_OK):
raise GateError(f"missing or non-executable host binary: {exe}")
guest_dir = app_path / "Contents/Resources/guest"
for name in REQUIRED_GUEST_FILES:
asset = guest_dir / name
if not asset.is_file():
raise GateError(f"missing packaged guest asset: {asset}")
if asset.stat().st_size <= 0:
raise GateError(f"packaged guest asset is empty: {asset}")
verify_initramfs(guest_dir / "initramfs.cpio")
guest_stage_dir.mkdir(parents=True, exist_ok=True)
proc = subprocess.run(
["tar", "-xzf", str(guest_dir / "data.img.tgz"), "-C", str(guest_stage_dir)],
capture_output=True,
text=True,
)
if proc.returncode != 0:
detail = (proc.stderr or proc.stdout).strip()
raise GateError(f"failed to unpack {guest_dir / 'data.img.tgz'}: {detail}")
data_img = guest_stage_dir / "data.img"
verify_ext4_superblock(data_img)
img_stat = data_img.stat()
if hasattr(img_stat, "st_blocks") and img_stat.st_blocks * 512 >= img_stat.st_size // 4:
raise GateError(f"{data_img}: unpacked template is not sparse ({img_stat.st_blocks * 512} bytes allocated)")
for name in ("Image", "initramfs.cpio"):
shutil.copyfile(guest_dir / name, guest_stage_dir / name)
def verify_codesign(app_path: Path) -> None:
verify = subprocess.run(
["codesign", "--verify", "--deep", "--strict", str(app_path)],
capture_output=True,
text=True,
)
if verify.returncode != 0:
detail = (verify.stderr or verify.stdout).strip()
raise GateError(f"codesign verification failed for {app_path}: {detail}")
exe = app_path / "Contents/MacOS/kiri"
ent = subprocess.run(
["codesign", "-d", "--entitlements", ":-", str(exe)],
capture_output=True,
)
if ent.returncode != 0:
detail = ent.stderr.decode("utf-8", errors="replace").strip()
raise GateError(f"could not read entitlements from {exe}: {detail}")
try:
plist = plistlib.loads(ent.stdout) if ent.stdout.strip() else {}
except Exception as exc:
raise GateError(f"malformed entitlements plist on {exe}: {exc}") from exc
if plist.get("com.apple.security.virtualization") is not True:
raise GateError(f"{exe} is missing com.apple.security.virtualization entitlement")
def bundle_sha256(app_path: Path) -> str:
"""Compute a deterministic SHA-256 digest across all files in an .app bundle."""
if not app_path.is_dir():
raise GateError(f"app bundle directory does not exist: {app_path}")
outer = hashlib.sha256()
entries: list[tuple[str, Path]] = []
for root, dirs, files in os.walk(app_path, followlinks=False):
dirs.sort()
files.sort()
root_path = Path(root)
for name in dirs:
candidate = root_path / name
if candidate.is_symlink():
rel = candidate.relative_to(app_path).as_posix()
entries.append((rel, candidate))
for name in files:
candidate = root_path / name
rel = candidate.relative_to(app_path).as_posix()
entries.append((rel, candidate))
entries.sort(key=lambda item: item[0])
for rel, full in entries:
st = full.lstat()
kind = stat.S_IFMT(st.st_mode)
if kind == stat.S_IFLNK:
target = os.readlink(full)
outer.update(f"L\0{rel}\0{target}\n".encode("utf-8"))
elif kind == stat.S_IFREG:
file_hash = hashlib.sha256()
with full.open("rb") as fh:
while chunk := fh.read(1 << 20):
file_hash.update(chunk)
exec_bit = 1 if (st.st_mode & stat.S_IXUSR) else 0
outer.update(f"F\0{rel}\0{exec_bit}\0{file_hash.hexdigest()}\n".encode("utf-8"))
else:
raise GateError(f"unexpected special file in bundle: {full}")
return outer.hexdigest()
def git_head(repo_root: Path) -> str:
proc = subprocess.run(
["git", "-C", str(repo_root), "rev-parse", "HEAD"],
capture_output=True,
text=True,
)
if proc.returncode != 0:
detail = (proc.stderr or proc.stdout).strip()
raise GateError(f"could not read git HEAD in {repo_root}: {detail}")
head = proc.stdout.strip()
if len(head) != 40 or any(ch not in "0123456789abcdef" for ch in head):
raise GateError(f"unexpected git HEAD output: {head!r}")
return head
def run_disk_grow_gate(
repo_root: Path,
app_path: Path,
guest_stage_dir: Path,
sandbox_dir: Path,
) -> None:
home_dir = sandbox_dir / "home"
docker_cfg = sandbox_dir / "docker-config"
home_dir.mkdir(parents=True, exist_ok=True)
docker_cfg.mkdir(parents=True, exist_ok=True)
env = os.environ.copy()
env["HOME"] = str(home_dir)
env["DOCKER_CONFIG"] = str(docker_cfg)
bundled_bin = app_path / "Contents/Resources/bin"
if bundled_bin.is_dir():
env["PATH"] = f"{bundled_bin}{os.pathsep}{env.get('PATH', '')}"
script = repo_root / "tests/disk-grow.py"
exe = app_path / "Contents/MacOS/kiri"
proc = subprocess.run(
[sys.executable, str(script), str(exe), "--guest-dir", str(guest_stage_dir)],
cwd=str(repo_root),
env=env,
)
if proc.returncode != 0:
raise GateError(f"tests/disk-grow.py failed with exit code {proc.returncode}")
def write_receipt(
receipt_path: Path,
app_path: Path,
checks_passed: list[str],
*,
head: str,
app_digest: str,
timestamp: str | None = None,
) -> dict[str, object]:
if timestamp is None:
timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
payload: dict[str, object] = {
"git_head": head,
"app_path": str(app_path),
"app_sha256": app_digest,
"timestamp": timestamp,
"checks_passed": list(checks_passed),
}
receipt_path.parent.mkdir(parents=True, exist_ok=True)
tmp_path = receipt_path.with_name(f".{receipt_path.name}.{os.getpid()}.tmp")
tmp_path.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
os.replace(tmp_path, receipt_path)
return payload
def run_gate(repo_root: Path, app_path: Path, receipt_path: Path) -> dict[str, object]:
if platform.system() != "Darwin" or platform.machine() != "arm64":
raise GateError(
f"release-gate-mac.py must run on Apple Silicon macOS (got {platform.system()} {platform.machine()})"
)
app_resolved = app_path.resolve()
if not app_resolved.is_dir() or app_resolved.suffix != ".app":
raise GateError(f"expected a .app bundle directory, got: {app_path}")
if app_resolved == Path("/Applications/Kiri.app"):
raise GateError("refusing to run release gate against installed /Applications/Kiri.app; pass a built bundle")
head = git_head(repo_root)
checks_passed: list[str] = []
with tempfile.TemporaryDirectory(prefix="kiri-release-gate-", dir="/tmp") as tmp:
sandbox = Path(tmp).resolve()
guest_stage = sandbox / "guest"
print(f"==> [1/4] Checking guest assets and ext4 template in {app_resolved}", flush=True)
unpack_and_verify_guest(app_resolved, guest_stage)
checks_passed.extend([
"guest_assets_present",
"initramfs_tools_present",
"ext4_superblock_valid_no_sparse_super2",
])
print(f"==> [2/4] Verifying code signature and entitlements on {app_resolved}", flush=True)
verify_codesign(app_resolved)
checks_passed.append("codesign_deep_strict_and_virtualization_entitlement")
print("==> [3/4] Running packaged VM disk-growth test in isolated /tmp sandbox", flush=True)
run_disk_grow_gate(repo_root, app_resolved, guest_stage, sandbox)
checks_passed.append("packaged_vm_disk_grow")
print("==> [4/4] Writing release gate receipt", flush=True)
digest = bundle_sha256(app_resolved)
receipt = write_receipt(
receipt_path.resolve(),
app_resolved,
checks_passed,
head=head,
app_digest=digest,
)
print(f"PASS release gate receipt written to {receipt_path.resolve()}", flush=True)
return receipt
def main(argv: list[str] | None = None) -> int:
repo_root = Path(__file__).resolve().parent.parent
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("app", type=Path, help="Path to the built Kiri.app bundle (for example target/Kiri.app)")
parser.add_argument(
"--receipt",
type=Path,
default=None,
help="Output path for the JSON pass receipt (default: <app-parent>/release-gate-receipt.json)",
)
args = parser.parse_args(argv)
receipt_path = args.receipt if args.receipt is not None else args.app.resolve().parent / "release-gate-receipt.json"
try:
run_gate(repo_root, args.app, receipt_path)
except GateError as exc:
print(f"FAIL release gate: {exc}", file=sys.stderr)
return 1
return 0
if __name__ == "__main__":
sys.exit(main())