feat(wait): a run's end, for the background beside a detached run
All checks were successful
Flatpak / check (push) Has been skipped
Flatpak / publish (push) Successful in 6m6s

A run launched detached, as the prepush skill says, tells the session
nothing when it ends: a round finished unread for hours.

`crafter-review wait --artifact <artifact> --hash <hash>`, the two
values of the run line, follows the hash's run lock. A full run holds it
until it ends; taking it, the run now clears the last run's identity
there, and it names itself with its run number once it has one. When a
run the wait has seen hold or take the lock lets it go, the wait reads
the identity - under its own instant shared hold, so never a rewrite in
flight - prints the summary of the final dump of the run the identity
names and exits with the code its verdict maps to, as run's does: 2 when
there is no final dump or no run number, 3 with the message of a
preflight check that stopped the run after it took the lock, which the
run adds to the identity. A wait that sees no run within --appear (120 s
by default) exits 3. Every probe of the lock, a test or dry run's too,
takes it shared for an instant, and the run lock is tried for 200 ms
before another driver counts as its holder. A wait only reads: one that
is stopped is started again and the run goes on.

freeze prints the wait line before the run line, and the skill and the
process start the wait in the background, then launch the run detached.
Released as 1.2.0.
This commit is contained in:
Jorijn van der Graaf 2026-11-02 20:34:01 +01:00
commit 4318c7d8f2
Signed by: jorijnvdgraaf
GPG key ID: 2937E59CDCC1BCFB
15 changed files with 607 additions and 33 deletions

View file

@ -21,6 +21,7 @@ import :Seats;
import :SeatPool;
import :OpenCode;
import :Run;
import :State;
import std;
namespace fs = std::filesystem;
@ -29,7 +30,7 @@ namespace Crafter::Review {
namespace {
constexpr std::string_view Usage =
R"(usage: crafter-review [--config FILE] {run,freeze,slots,config} ...
crafter-review {seats,inventory,sql,totp,init,doc,browser,stop} ...
crafter-review {seats,inventory,sql,totp,init,doc,browser,stop,wait} ...
crafter-review --version
The pre-push review pipeline: adversarial lenses, one claude process per
@ -714,6 +715,148 @@ inventory unit, against a frozen commit range.)";
return 0;
}
// ---- wait: a run's end, for the background beside a detached run ---------------
constexpr std::array<OptionSpec, 3> WaitOptions = {{
{"--artifact", true, "ARTIFACT", "the artifact the run reviews, as the run line names it", Kind::String, {}, true},
{"--hash", true, "HASH", "the artifact hash, as the run line names it (its first 8 characters decide)", Kind::String, {}, true},
{"--appear", true, "SECONDS", "how long to wait for a run of the hash to take its run lock (default 120)", Kind::Float},
}};
// The dump of the run a lock identity names.
fs::path DumpOf(const fs::path& gateDir, std::string_view kind, std::string_view h8, const Json& info) {
return gateDir / std::format("{}-{}-run-{}.json", kind, h8, Dyn::Str(Dyn::Get(info, "run_n")));
}
// That run's final dump: null while it has none (live, or killed).
Json FinalDump(const fs::path& gateDir, std::string_view kind, std::string_view h8, const Json& info) {
if (!Dyn::Truthy(Dyn::Get(info, "run_n"))) return nullptr;
Json dump;
try {
dump = Dyn::LoadJsonFile(DumpOf(gateDir, kind, h8, info));
} catch (const std::exception&) {
return nullptr;
}
const std::string overall = dump.is_object() ? Dyn::StrOr(Dyn::Get(dump, "overall"), "") : "";
return overall.empty() || overall.starts_with("IN PROGRESS") ? Json(nullptr) : dump;
}
// A run's end, as its run lock's identity and its dump record it: the
// summary `run` printed at its end and the run's exit code; 3 with the
// message of a preflight check that stopped it, 2 when it left no final
// dump.
std::int32_t ReportRun(const fs::path& gateDir, std::string_view kind, std::string_view h8, const Json& info) {
if (Dyn::Get(info, "preflight").is_string()) {
std::println("preflight: {}", Dyn::Str(info.at("preflight")));
return 3;
}
if (!Dyn::Truthy(Dyn::Get(info, "run_n"))) {
std::println("wait: a run of {} took its run lock and ended before it named itself (killed or crashed)", h8);
return 2;
}
const Json dump = FinalDump(gateDir, kind, h8, info);
if (dump.is_null()) {
std::println("wait: run {} of {} ended without its final dump (killed or crashed); its log is {}", Dyn::Str(Dyn::Get(info, "run_n")), h8,
(fs::path(Dyn::StrOr(Dyn::Get(info, "scratch"), "")) / "log.txt").string());
return 2;
}
const std::string overall = Dyn::Str(dump.at("overall"));
std::string summary;
try {
summary = State::Summary(dump);
} catch (const std::exception&) {
summary = std::format("overall: {}\ndump: {}", overall, DumpOf(gateDir, kind, h8, info).string());
}
std::println("{}", summary);
if (overall == "SEND-READY") return 0;
return overall == "FIX FIRST" ? 1 : 2;
}
std::int32_t WaitCommand(std::span<const std::string_view> args) {
constexpr std::string_view Prog = "crafter-review wait";
const Parsed parsed = ParseOptions(args, WaitOptions);
if (parsed.help) {
std::print("{}", Help(Prog,
"once a run of an artifact hash that it has seen hold or take the run lock lets it go, print the summary of the final dump of the run "
"the lock names and exit with the code its verdict maps to (2 without a final dump, 3 with the message of a preflight check that stopped "
"it after it took the lock, or when it sees no run) - in the background, started before a detached `run`; a wait that is stopped "
"changes nothing: run it again",
WaitOptions));
return 0;
}
if (!parsed.error.empty()) return UsageError(UsageLine(Prog, WaitOptions), Prog, parsed.error);
const fs::path artifact = parsed.Value("artifact").value_or("");
const std::string h8 = parsed.Value("hash").value_or("").substr(0, 8);
double appear = 120;
if (const std::optional<std::string> given = parsed.Value("appear")) {
appear = Dyn::ParseFloat(*given).value_or(-1);
if (!std::isfinite(appear) || appear < 0) return UsageError(UsageLine(Prog, WaitOptions), Prog, std::format("argument --appear: invalid seconds: {}", Dyn::Repr(*given)));
}
// The gate-state dir as `run` takes it: a reply's beside its file.
const fs::path gateDir = (fs::is_regular_file(artifact) ? artifact.parent_path() : artifact) / "gate-state";
// The hash's run lock, of whichever kind's is there: a full run
// takes it before anything slow, clears the last run's identity
// from it and names itself there once it has its run number; the
// kernel releases it when the run's driver ends.
auto lockOf = [&]() -> std::optional<std::pair<std::string, fs::path>> {
for (const std::string_view kind : Plan::Kinds) {
const fs::path path = State::LockPath(gateDir, kind, h8);
if (fs::exists(path)) return std::pair(std::string(kind), path);
}
return std::nullopt;
};
auto same = [](const Json& l, const Json& r) {
return Dyn::Get(l, "pid") == Dyn::Get(r, "pid") && Dyn::Get(l, "since") == Dyn::Get(r, "since") && Dyn::Get(l, "run_n") == Dyn::Get(r, "run_n");
};
// The run to wait for: one a poll sees holding the lock, or one that
// names itself there - or clears the last run's identity from it -
// after the wait began (it can take and leave the lock between two
// polls). It has ended once nobody holds the lock: the identity,
// read only then, under the probe's own hold, is its - never a
// rewrite in flight, never a new holder's first instant.
std::optional<std::pair<std::string, fs::path>> lock = lockOf();
const std::optional<State::LockState> first = lock ? State::ProbeRunLock(lock->second) : std::nullopt;
bool heldSeen = first && first->held;
const Json start = first && !first->held ? first->info : Json::object();
// An identity a run wrote there since the wait began: a new one, or
// the last one cleared.
auto changed = [&](const Json& info) {
if (Dyn::Truthy(Dyn::Get(info, "pid"))) return !same(info, start);
return Dyn::Truthy(Dyn::Get(start, "pid"));
};
const double deadline = Platform::Now() + appear;
constexpr auto Poll = std::chrono::seconds(2);
while (true) {
if (!lock) lock = lockOf();
if (const std::optional<State::LockState> now = lock ? State::ProbeRunLock(lock->second) : std::nullopt) {
if (now->held) {
heldSeen = true;
} else if (heldSeen || changed(now->info)) {
return ReportRun(gateDir, lock->first, h8, now->info);
}
}
if (!heldSeen && Platform::Now() > deadline) {
// The run the lock names ended before the wait began.
std::string late;
if (lock && Dyn::Truthy(Dyn::Get(start, "run_n"))) {
const std::string n = Dyn::Str(start.at("run_n"));
const fs::path dump = DumpOf(gateDir, lock->first, h8, start);
if (Dyn::Get(start, "preflight").is_string()) {
late = std::format("; the lock names run {}, which a preflight check stopped before this wait began: {}", n, Dyn::Str(start.at("preflight")));
} else if (fs::exists(dump)) {
late = std::format("; the lock names run {}, which ended before this wait began: {}", n, dump.string());
} else {
late = std::format("; the lock names run {}, which ended before this wait began without a dump: its log is {}", n,
(fs::path(Dyn::StrOr(Dyn::Get(start, "scratch"), "")) / "log.txt").string());
}
}
std::println(std::cerr, "wait: no full run of {} seen at its run lock in {} within {} s - a run that stops at its preflight before it takes the lock never shows: its own output says why{}",
h8, gateDir.string(), std::format("{:g}", appear), late);
return 3;
}
std::this_thread::sleep_for(Poll);
}
}
// ---- doc: the texts the Flatpak ships -------------------------------------------------
constexpr std::array<std::string_view, 3> DocNames = {"prepush", "manifest", "config"};
constexpr std::array<OptionSpec, 1> DocOptions = {{
@ -1046,6 +1189,7 @@ inventory unit, against a frozen commit range.)";
if (command == "slots") return SlotsCommand(after, configPath);
if (command == "seats") return SeatsCommand(after);
if (command == "stop") return StopCommand(after);
if (command == "wait") return WaitCommand(after);
if (command == "doc") return DocCommand(after);
if (command == "browser") return BrowserCommand(after);
if (command == "init") return InitCommand(after);

View file

@ -422,6 +422,10 @@ namespace Crafter::Review::Freeze {
Dyn::Str(Dyn::At(report, "base")), trees, Dyn::JoinPath(Dyn::JoinPath(outRel, "gate-state"), "dispositions.json"), Dyn::Str(Dyn::At(report, "date")));
}
std::string WaitLine(const Json& report, std::string_view outRel) {
return std::format("{} wait --artifact {} --hash {}", Invocation(), outRel, Dyn::Slice(Dyn::Str(Dyn::At(report, "hash")), 0, 8));
}
std::string TreeOf(const Json& record, const fs::path& cwd) {
const Json& worktree = Dyn::Get(record, "worktree");
if (Dyn::Truthy(worktree)) return Dyn::Str(worktree);
@ -492,7 +496,8 @@ namespace Crafter::Review::Freeze {
std::println("hash: {}", report.at("hash").get<std::string>());
const std::string line = RunLine(report, rel, TreeOf(report, cwd));
std::ofstream(fs::path(report.at("out").get<std::string>()) / "run-line.txt", std::ios::binary) << line << "\n";
std::println("run (from the repository root, in a detached background shell; also in {}):\n {}", Dyn::JoinPath(rel, "run-line.txt"), line);
std::println("first the wait, in the background:\n {}", WaitLine(report, rel));
std::println("then the run, from the repository root, detached - `setsid nohup <it> > <log> 2>&1 < /dev/null &` (also in {}):\n {}", Dyn::JoinPath(rel, "run-line.txt"), line);
return 0;
}
}

View file

@ -2466,6 +2466,8 @@ namespace Crafter::Review::Run {
} catch (const Preflight& e) {
std::println(std::cerr, "preflight: {}", e.what());
code = 3;
// Once the run lock names this run, `wait` reads the stop there.
if (run.runLock) run.runLock->AddInfo("preflight", e.what());
}
watcher.request_stop();
watcher.join();

View file

@ -155,12 +155,25 @@ namespace Crafter::Review::State {
const fs::path path = LockPath(gateDir, mode, hash8);
fd = open(path.c_str(), O_RDWR | O_CREAT | O_CLOEXEC, 0644);
if (fd < 0) throw std::runtime_error(std::format("{}: {}", Dyn::ErrnoText(errno), Dyn::Repr(std::string_view(path.string()))));
if (flock(fd, LOCK_EX | LOCK_NB) != 0) {
bool locked = flock(fd, LOCK_EX | LOCK_NB) == 0;
for (std::int32_t attempt = 0; !locked && attempt < 20; ++attempt) {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
locked = flock(fd, LOCK_EX | LOCK_NB) == 0;
}
if (!locked) {
const Json info = ReadLockInfo(path);
close(fd);
fd = -1;
throw RunLocked(Describe(info));
}
// The last run's identity is not this run's: until it names itself,
// the holder reads as one that has just started.
if (ftruncate(fd, 0) != 0) {
const std::int32_t failure = errno;
close(fd);
fd = -1;
throw std::runtime_error(std::format("{}: {}", Dyn::ErrnoText(failure), Dyn::Repr(std::string_view(path.string()))));
}
}
RunLock::~RunLock() {
@ -168,6 +181,7 @@ namespace Crafter::Review::State {
}
void RunLock::WriteInfo(const Json& info) {
written = info;
const std::string text = DumpSpaced(info);
if (lseek(fd, 0, SEEK_SET) < 0 || ftruncate(fd, 0) != 0) return;
std::size_t written = 0;
@ -181,18 +195,34 @@ namespace Crafter::Review::State {
}
}
std::optional<Json> LockHolder(const fs::path& gateDir, std::string_view mode, std::string_view hash8) {
const fs::path path = LockPath(gateDir, mode, hash8);
void RunLock::AddInfo(std::string_view key, const Json& value) {
if (!written.is_object()) return;
Json info = written;
info[std::string(key)] = value;
WriteInfo(info);
}
std::optional<LockState> ProbeRunLock(const fs::path& path) {
const std::int32_t handle = open(path.c_str(), O_RDONLY | O_CLOEXEC);
if (handle < 0) return std::nullopt;
std::optional<Json> holder;
if (flock(handle, LOCK_EX | LOCK_NB) == 0) {
// Shared, for an instant: two probers never see each other, and a
// starting run tries its exclusive lock for 200 ms (RunLock).
LockState state;
if (flock(handle, LOCK_SH | LOCK_NB) == 0) {
state.info = ReadLockInfo(path);
flock(handle, LOCK_UN);
} else {
holder = ReadLockInfo(path);
state.held = true;
state.info = ReadLockInfo(path);
}
close(handle);
return holder;
return state;
}
std::optional<Json> LockHolder(const fs::path& gateDir, std::string_view mode, std::string_view hash8) {
const std::optional<LockState> state = ProbeRunLock(LockPath(gateDir, mode, hash8));
if (!state || !state->held) return std::nullopt;
return state->info;
}
std::int64_t NextRunNumber(const fs::path& gateDir, std::string_view mode, std::string_view hash8) {