A crashed merge no longer blocks every other merge, and a one-call count of PRs waiting to merge (GST-3549) (#4712)

When `gstack-ship-queue land --pin` dies in the middle of a merge, the
next merge now takes over its lock by itself (the process has exited,
its machine restarted, or 90 minutes passed) and logs it; a merge that
is still running is never interrupted.

New `gstack-ship-queue count` says how many finished PRs are waiting to
merge, and the docs now say how to drain that queue and how to time a
revert drill.

Nothing to do: the next `land --pin` uses the new lock on its own.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
Review-Finding: p1/specialist-batched#1 reader=security
Review-Finding: p1/specialist-batched#2 reader=testing
Review-Finding: p1/red-team#2 reader=red-team
Review-Finding: p1/red-team#3 reader=red-team
Review-Finding: p2/outside-voice#1 reader=outside-voice
Review-Finding: p2/outside-voice#3 reader=outside-voice
Review-Finding: p2/outside-voice#4 reader=outside-voice
Review-Finding: p2/red-team#1 reader=red-team
Review-Finding: p2/adversarial-native#1 reader=adversarial-native
Review-Finding: p2/outside-voice#5 reader=outside-voice
Review-Finding: p2/outside-voice#6 reader=outside-voice
Review-Finding: p2/specialist-batched#2 reader=testing
This commit is contained in:
Garry Tanandcapy-ai[bot] authored and GitHub committed 2026-11-22 18:37:39 +00:00
1 parent d3aed00dbe
commit 2ab2aad705
13 files changed
+696 -22

No files matched your search

+6
View File
@@ -19,6 +19,7 @@
* gstack-ship-queue land --pr <n> [--dry-run] [--no-wait] [--break-lock [--break-train-lock]] (the merge step; lib/ship-queue-land.ts)
* gstack-ship-queue land --pr <n> --repair (after QUEUE_LAND_DRIFT: open the outside merge's release PR)
* gstack-ship-queue land --census
* gstack-ship-queue count [--authors <login,...>] (R119: finished PRs waiting to land, one gh call; lib/ship-queue-count.ts)
* gstack-ship-queue train build|status|verdict|bisect|rebuild|watch|prune ... (merge trains; train --help)
* gstack-ship-queue wave plan|build|status|settle ... (wave PRs: 3-6 same-area PRs in one train slot; wave --help)
*
@@ -86,6 +87,10 @@ const HELP = `gstack-ship-queue — the shared merge queue's protocol steps (doc
land --pr <n> --repair after QUEUE_LAND_DRIFT: open the PR that gives the merge outside land its own
release; /ship and land it, which releases the lock
land --census what land would do with every open PR (read-only)
count [--authors <login,...>] finished PRs waiting to land, from one gh call: QUEUE_COUNT (count, how many waited 24h
or more, the oldest wait), a FINISHED line each, and DRAIN when more than 6 wait or one
has waited 24h (docs/captain.md#drain-the-queue); finished = by an author (default
garrytan,capy-ai,garrytan-agents), on the base, not a draft or conflicting, green at its head
train build|status|verdict|bisect|rebuild|watch|prune ...
merge trains, when the base policy declares a train block (train --help;
docs/ship-policy.md#run-a-merge-train); ready then takes --screen|--no-screen
@@ -217,6 +222,7 @@ async function main(argv: string[]): Promise<number> {
if (loaded && !('message' in loaded) && loaded.policy.merge === 'direct') return finish(`train ${args[0]}`, { ok: false, lines: [], run: 'none', failure: { code: 'QUEUE_NOT_READY', message: 'the base policy sets merge: direct, so trains are off', fix: 'land each READY PR with gstack-ship-queue land --pr <n> --pin <sha> (docs/ship-policy.md#land-direct)' } });
return train.trainMain(ctx, args);
}
if (cmd === 'count') return finish('count', (await import('../lib/ship-queue-count')).queueCount(ctx, { authors: flag(args, '--authors')?.split(',').map(s => s.trim()).filter(Boolean) }));
if (cmd === 'wave') return (await import('../crew/lib/ship-queue-wave')).waveMain(ctx, args);
if (cmd === 'verify' && flag(args, '--post-merge') !== undefined) return (await import('../crew/lib/ship-queue-train-cli')).postMergeMain(ctx, args);
if (cmd === 'land') {
+1
View File
@@ -17,3 +17,4 @@ Your crew's CREW.md and recorded approvals decide who may merge, update a base,
13. **The owner's model preference.** `gstack-models resolve --role agent` picks agent models, except cross-family voices and eval subjects. [docs/model-policy.md: Your model preference]
14. **Finish before starting.** No new fix thread in a repo while more than 10 finished PRs (green, reviewed, waiting only to merge) sit in its queue: merge or close them first. Severe hotfixes are exempt: security, data loss, red main, a broken install. [crew/docs/captain.md: New threads join the crew]
15. **Subagents earn their context.** Start one only for parallel work you can throw away, a fresh-eyes review or another model family, never for a step of your own procedure; name the compact result it returns. [crew/docs/captain.md: Lane context]
16. **Drain the queue.** Captains run `gstack-ship-queue count` every sweep and standing wake; a `DRAIN:` line means drain that turn: low-risk PRs land alone, risky ones in bundles of 3 to 6, idle owners get their next step. [crew/docs/captain.md: Drain the queue]
+1
View File
@@ -0,0 +1 @@
**A crashed `gstack-ship-queue land --pin` no longer blocks every other merge.** Its lock now records the process holding it and expires 90 minutes after its last step, so the next land takes over a lock whose land has exited, whose machine restarted, or that expired, and logs the takeover; a land that is still running is never interrupted. New `gstack-ship-queue count` prints how many finished PRs are waiting to merge, from one gh call, with a DRAIN line when more than 6 wait or one has waited a day. docs/ship-policy.md#land-lock, docs/ship-policy.md#revert-drill, crew/docs/captain.md#drain-the-queue
+49 -1
View File
@@ -555,6 +555,54 @@ the same product diff; any other rebase is a full /ship
([ship-policy.md](../../docs/ship-policy.md#receipt-carry)). A controller never asks a lane to
rebase a reviewed branch.
## Drain the queue
A finished PR that sits unmerged goes stale: main moves under it, conflicts appear, and
its lane sits idle. On 2026-11-22 gbrain had 22 waiting and gstack 21, gstack's held for
hours by a stale land lock. The repository owner's ruling that day: fix it now, and put a
standing process in place so it never builds up again, in this project and in every other
crew. So every Captain that lands PRs counts its queue at every wake and drains it before it
piles up.
**Count at every sweep and standing wake.** Run `gstack-ship-queue count` in each repository
you land, from its checkout. It makes one gh call and prints one `QUEUE_COUNT:` line (how
many PRs are finished, how many have waited 24 hours or more, and the oldest wait), then a
`FINISHED:` line per PR, oldest first. A PR is finished when one of ours opened it
(garrytan, capy-ai or garrytan-agents; `--authors a,b` for another repo's), it targets the
base, it isn't a draft, GitHub doesn't report it conflicting, and the checks on its newest
commit are green. Its wait counts from that commit.
**A `DRAIN:` line means drain this turn.** count prints it when more than 6 PRs are
finished, or when one has waited 24 hours or more. Drain before you start anything new:
1. Land every PR that has a verified READY ([direct land](#direct-land-merge-direct)).
2. Sort the rest into the two lanes below.
3. Send each idle owner its next step in one line: /ship at the head, `ready`, merge main
and resolve, or "goes in bundle N". A PR whose thread is gone gets a new owner
([no orphaned work](#no-orphaned-work)).
**Lane 1: a low-risk PR lands alone, on its own green head.** No re-merge and no re-test
when main moves, once the repository has passed one timed
[revert drill](../../docs/ship-policy.md#revert-drill). If main then goes red, revert the
culprit within 30 minutes. Low-risk means it touches none of: migrations, dependencies, CI,
security, user data, money, or a default that flips. Until its drill passes, a repository
keeps re-testing a stale base (`land.merged_checks`, `land.merged_ci`).
**Lane 2: risky PRs land in a bundle of 3 to 6.** Pick PRs from one area. One integrator
lane merges their branches into one bundle branch from main and opens one PR naming each
one; that PR gets one /ship (one review), one full CI and one landing. A PR whose part fails
drops out and goes back to its owner, and the rest land. Close each bundled PR as landed in
the bundle. A bundle lives only until it lands: never a standing merge branch, which one bad
PR poisons.
**A cheap-tier green is never landing evidence.** Land only when every required check
passes at the exact head (CREW.md `REQUIRED_CHECKS`), the same as any land.
**A stale land lock no longer stops the queue.** `land --pin` takes over a lock whose land
has exited or expired, and logs it
([the land lock can't go stale](../../docs/ship-policy.md#land-lock)). A
`QUEUE_LAND_LOCKED` that says a land is still running means wait for it.
## Direct land (`merge: direct`)
When the base policy sets `"merge": "direct"`, there are no trains, slot calls or stamp
@@ -596,7 +644,7 @@ What to do with each refusal (nothing was merged unless the code says so):
| `QUEUE_LAND_CHECKS` | Captain, then lane | pending: `gstack-pr-wait <n> --until green` and rerun; red: back to the lane (rule 16 rerun for a flaky case); missing: dispatch the workflow on the branch |
| `QUEUE_LAND_MERGED_CHECKS` | Captain, then lane | the message says the checks changed files land's git or gh calls read: hold, nothing goes back to the lane yet; restore each named path from a trusted copy, release the lock with `land --pr <n> --pin <sha>` (no `--allow-repo-commands`), and find out why the checks wrote there. Otherwise a `land.merged_checks` command failed, or the `land.merged_ci` run was red, on the pin merged onto main: one rerun of land for a flaky case (rule 16), else back to the lane, which merges main (rule 19), fixes it, /ship, `ready`, new READY ([troubleshooting](../../docs/troubleshooting.md#queue-land-merged-checks)) |
| `QUEUE_LAND_NOT_CLEAN` | lane, or Captain | `CONFLICTING`, or the pin conflicts with main's tip on a stale base: the lane merges main (rule 19), /ship, `ready`; `UNKNOWN`: rerun in a minute |
| `QUEUE_TRAIN_FROZEN` / `QUEUE_LAND_LOCKED` | Captain | finish the repair or the holder first |
| `QUEUE_TRAIN_FROZEN` / `QUEUE_LAND_LOCKED` | Captain | finish the repair or the holder first. land takes over a lock whose land exited or expired by itself; a lock it refuses says why: a land still running (wait, or stop the process it names if stuck), another machine's land (rerun after the expiry it prints, or `--break-lock` once you know that land stopped), or a deliberate hold (release it as the `LOCK:` line says) |
| `QUEUE_TRAIN_UNTRUSTED` | Captain | a fork head; rewrite on a crew branch |
| `QUEUE_LAND_UNVERIFIED` | Captain | merged, but main isn't the pin on its parent, or main moved after land's check and `land.merged_checks` failed or is absent on the landed tree: revert the stray change or fix forward, report it |
| `RELEASE_STAMP_INVALID` | Captain | the `release/<version>` head is more than its stamp: close it, `gstack-release-stamp open` again |
+161 -12
View File
@@ -8,13 +8,38 @@
* the same owner kind, identity and journal; anything else is a takeover the caller allows (a drift repair, a
* train's next slot, the admitted repair train) or a --break-lock under the staleness, mid-push, drift, freeze
* and live-train rules.
*
* A direct land (`land --pin`) holds the lock only while its process runs, so its lock is process-scoped
* (AcquireOptions.processScoped): every write records the process (boot id, pid namespace, pid, process group,
* start time and a random mark) and an expiry, and the run keeps a mark file under the state root until it
* releases. A later land judges such a lock before anything else: a process of the holder's group started at or
* after the holder still running on this machine means it runs, and it is never taken over, --break-lock included;
* a group with no such process, or a mark file this machine kept for a lock written before its last boot, means the
* holder is gone, and an expired lock whose holder is not running is stale. A gone or stale lock is taken over
* without --break-lock and the takeover is logged (LOCK_TAKEOVER, and took_over in the new lock). A mark file that
* records a deliberate hold (land.merged_checks were running, or changed the checkout) keeps the lock refused on
* this machine; the hold lives in this machine's state root, so another machine still takes it over once it
* expires (its checkout was never touched). A mark proves a restart only for this machine and a different boot.
* Anything else refuses
* with the expiry and the fix. A takeover writes under the exact lease on the sha it judged, and a retry adopts only
* a lock carrying this run's own mark, so a stalled takeover or a late release never replaces a newer owner's lock.
*/
import * as crypto from 'node:crypto';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import { resolveStateRoot } from '../../lib/state-root';
import { git, type QueueFailure } from './ship-queue-gate';
export const LAND_LOCK_REF = 'refs/notes/gstack-land';
export const PUSH_STALE_MS = 10 * 60_000;
/** A direct land's bound: merged checks (about 15 minutes), land.merged_ci (CI_TIMEOUT_MS, 45) and the merge with its tree check, with room to spare. */
export const DIRECT_LOCK_TTL_MS = 90 * 60_000;
export type LandLockPhase = 'stamping' | 'pushing' | 'waiting' | 'merging' | 'drift' | 'between' | 'freeze';
export interface LandLock { pr: string; holder: string; started_at: string; phase: LandLockPhase; journal: string; phase_at?: string; repair_pr?: string; drift_of?: string; train?: string; slot?: number }
/** The process holding a process-scoped lock; start is the kernel's start time in clock ticks since boot. */
export interface LockProcess { boot: string; pidns: string; pid: number; pgid: number; start: number; mark: string }
export interface LockTakeover { pr: string; holder: string; sha: string; why: string; at: string }
export interface LandLock { pr: string; holder: string; started_at: string; phase: LandLockPhase; journal: string; phase_at?: string; repair_pr?: string; drift_of?: string; train?: string; slot?: number; proc?: LockProcess; expires_at?: string; took_over?: LockTakeover }
export type LockOwner = { pr: string; train?: undefined; slot?: undefined } | { pr: string; train: string; slot: number };
export type LockRead = { state: 'absent'; sha: '' } | { state: 'released'; sha: string } | { state: 'held'; sha: string; lock: LandLock } | { state: 'unreadable'; sha: string; detail: string };
type Released = { released: true; by: string; at: string };
@@ -26,6 +51,90 @@ export const lockLabel = (lock: LandLock): string => (lock.train ? `train ${lock
export const ownsLock = (lock: LandLock, owner: LockOwner, journal: string): boolean =>
lock.pr === owner.pr && (lock.train ?? null) === (owner.train ?? null) && (lock.slot ?? null) === (owner.slot ?? null) && lock.journal === journal;
/** state, process group and start time (clock ticks since boot) from /proc/<pid>/stat; null off Linux or once the process is gone. */
function procStat(pid: number | 'self'): { state: string; ppid: number; pgrp: number; start: number } | null {
try {
const stat = fs.readFileSync(`/proc/${pid}/stat`, 'utf8');
const f = stat.slice(stat.lastIndexOf(')') + 2).split(' ');
return { state: f[0]!, ppid: Number(f[1]), pgrp: Number(f[2]), start: Number(f[19]) };
} catch { return null; }
}
/** This process as a lock records it, with a fresh mark; null where /proc cannot say (then only the expiry applies). */
export function thisProcess(): LockProcess | null {
try {
const self = procStat('self');
if (!self || !Number.isInteger(self.pgrp) || !Number.isInteger(self.start)) return null;
return { boot: fs.readFileSync('/proc/sys/kernel/random/boot_id', 'utf8').trim(), pidns: fs.readlinkSync('/proc/self/ns/pid'), pid: process.pid, pgid: self.pgrp, start: self.start, mark: crypto.randomUUID() };
} catch { return null; }
}
/**
* A live process of the holder's group that started at or after the holder (the holder, or a child it started,
* even one orphaned when the holder died); 0 when there is none. Older members are the shell that ran the holder.
* When this run shares the holder's group (a rerun in the same script), this run, its ancestors and its siblings
* (a `| tee` beside it) are never counted, except the holder itself. A group reused after its last member exited reads as running: a refusal, never a theft.
*/
function groupRunning(p: LockProcess): number {
let entries: string[];
try { entries = fs.readdirSync('/proc'); } catch { return p.pid; }
const mine = new Set<number>();
for (let at = process.pid; at > 1 && !mine.has(at);) { mine.add(at); at = procStat(at)?.ppid ?? 0; }
const self = procStat('self');
const parent = self?.pgrp === p.pgid ? self.ppid : 0;
for (const name of entries) {
const pid = Number(name);
if (!Number.isInteger(pid) || pid <= 0) continue;
const s = procStat(pid);
if (!s || s.pgrp !== p.pgid || s.start < p.start || s.state === 'Z' || s.state === 'X') continue;
const holder = pid === p.pid && s.start === p.start;
if (!holder && parent && (mine.has(pid) || (parent > 1 && s.ppid === parent))) continue;
return pid;
}
return 0;
}
/** This machine as a mark file records it, so a mark read through a shared state root never proves another machine's restart. */
function thisMachine(): string {
let id = '';
try { id = fs.readFileSync('/etc/machine-id', 'utf8').trim(); } catch { /* none */ }
return `${os.hostname()}/${id}`;
}
export const lockMarkDir = (env: NodeJS.ProcessEnv = process.env) => path.join(resolveStateRoot(env), 'ship-queue', 'land-owners');
const markFile = (dir: string, mark: string) => path.join(dir, `${mark.replace(/[^A-Za-z0-9-]/g, '')}.json`);
function readMark(dir: string, mark: string): { hold?: string; machine?: string; boot?: string } | null {
try { return JSON.parse(fs.readFileSync(markFile(dir, mark), 'utf8')); } catch { return null; }
}
function writeMark(dir: string, mark: string, value: object): boolean {
const file = markFile(dir, mark);
try {
fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(`${file}.${process.pid}.tmp`, JSON.stringify(value) + '\n');
fs.renameSync(`${file}.${process.pid}.tmp`, file);
return true;
} catch { return false; }
}
const dropMark = (dir: string, mark: string) => { try { fs.rmSync(markFile(dir, mark), { force: true }); } catch { /* already gone */ } };
/** Whether a lock is held only while its land runs: one a process-scoped run wrote, or a direct land's from before process records. */
export const processScopedLock = (lock: LandLock): boolean => !!(lock.expires_at || lock.proc) || (!lock.train && lock.journal?.startsWith('land-pin:'));
export const lockExpiry = (lock: LandLock): number => Date.parse(lock.expires_at ?? '') || Date.parse(lock.phase_at ?? lock.started_at) + DIRECT_LOCK_TTL_MS;
export type OwnerVerdict = { state: 'running'; pid: number; why: string } | { state: 'gone' | 'held' | 'unknown'; why: string };
/** What this machine can prove about a process-scoped lock's holder. */
export function judgeOwner(lock: LandLock, self: LockProcess | null, marks: string): OwnerVerdict {
const p = lock.proc;
const mark = p?.mark ? readMark(marks, p.mark) : null;
const here = !!(p && self && p.boot === self.boot && p.pidns === self.pidns);
const pid = here ? groupRunning(p!) : 0;
if (pid) return { state: 'running', pid, why: `process ${pid} of its land (process group ${p!.pgid}) is still running on this machine` };
if (mark?.hold && mark.machine === thisMachine()) return { state: 'held', why: `its land left it held on purpose: ${mark.hold}` };
if (here) return { state: 'gone', why: `its land (process ${p!.pid}) and every process it started have exited` };
if (p && self && mark && mark.machine === thisMachine() && mark.boot === p.boot && p.boot !== self.boot) return { state: 'gone', why: 'this machine wrote it before it last restarted, so its land is gone' };
return { state: 'unknown', why: p ? 'its land ran on another machine, so this one cannot check whether it still runs' : 'it records no land process (an older gstack wrote it), so no machine can check it' };
}
/** The sha origin's lock ref holds: '' when origin has none, null when origin cannot be read. */
function originSha(root: string, remote: string): string | null {
const listed = git(root, ['ls-remote', remote, LAND_LOCK_REF]);
@@ -55,7 +164,7 @@ export function readLock(root: string, remote = 'origin'): LockRead {
export function writeLock(root: string, expected: string, value: LandLock | Released, remote = 'origin'): { ok: boolean; sha: string; origin?: string | null } {
const blob = git(root, ['hash-object', '-w', '--stdin'], undefined, JSON.stringify(value, null, 2) + '\n').out;
const tree = git(root, ['mktree'], undefined, `100644 blob ${blob}\tlock.json\n`).out;
const message = 'released' in value ? `land lock released by ${value.by}` : `land lock ${value.train ? `train ${value.train} slot ${value.slot} ` : ''}#${value.pr} ${value.phase}`;
const message = 'released' in value ? `land lock released by ${value.by}` : `land lock ${value.train ? `train ${value.train} slot ${value.slot} ` : ''}#${value.pr} ${value.phase}${value.took_over ? ` (took over #${value.took_over.pr}: ${value.took_over.why})` : ''}`;
const commit = git(root, ['commit-tree', tree, ...(expected ? ['-p', expected] : []), '-m', message]).out;
if (![blob, tree, commit].every(isSha)) return { ok: false, sha: '', origin: expected };
const push = git(root, ['push', '-q', `--force-with-lease=${LAND_LOCK_REF}:${expected}`, remote, `${commit}:${LAND_LOCK_REF}`]);
@@ -73,6 +182,8 @@ export interface HeldLandLock {
/** Move to a phase under the exact lease; a failure is another lander's lock (QUEUE_LAND_LOCKED) or a refused push (QUEUE_NOT_READY). */
set(phase: LandLockPhase, extra?: Partial<LandLock>): QueueFailure | null;
release(): boolean;
/** Mark a process-scoped lock as held on purpose (no git call): if this process stops while a reason is set, later lands here refuse it with that reason; null clears it. False when the mark could not be written. */
hold(reason: string | null): boolean;
}
export interface AcquireOptions {
root: string; remote?: string; holder: string; owner: LockOwner; journal: string; now: () => Date;
@@ -85,6 +196,10 @@ export interface AcquireOptions {
liveTrain?: (nonce: string) => boolean;
/** Fields every write of this run carries (land's drift_of), given this owner's own lock when resumed. */
extra?: (own: LandLock | null) => Partial<LandLock>;
/** The lock lives only as long as this process (land --pin): each write records the process and expires ttlMs later. proc and marks are for tests. */
processScoped?: { ttlMs: number; proc?: LockProcess | null; marks?: string };
/** This run may replace a lock held on purpose by its own PR's earlier run (land --pin without --allow-repo-commands, the documented release). */
releasesHold?: boolean;
}
/** Why --break-lock may not break a foreign lock, or null when it may. */
@@ -98,6 +213,12 @@ function unbreakable(lock: LandLock, o: AcquireOptions, age: number): QueueFailu
return null;
}
/** The fix a refusal of a process-scoped lock names: the expiry and --break-lock, or how a deliberate hold is released. */
function scopedFix(lock: LandLock, state: OwnerVerdict['state'], expiry: number, now: number, tampered = false): string {
if (state === 'held') return `make sure nothing that land started still runs and restore any path of the checkout's git directory it changed from a trusted copy, then release it: gstack-ship-queue land --pr ${lock.pr} --pin ${lock.journal.replace(/^land-pin:/, '')} (without --allow-repo-commands)${tampered ? '' : ', or pass --break-lock'}`;
return `the lock expires at ${new Date(expiry).toISOString()} (in ${Math.max(1, Math.ceil((expiry - now) / 60_000))} min), and the first land after that takes it over; to take it sooner, make sure the land that holds it has stopped, then rerun with --break-lock`;
}
/**
* Take the land lock for `owner`: resume this owner's own lock, take over one the caller allows, or (with
* --break-lock, which always names the holder) break a foreign one the rules permit; then write the first
@@ -110,15 +231,28 @@ export function acquireLandLock(o: AcquireOptions): { held: HeldLandLock; lines:
let sha = read.sha;
let current: LandLock | null = read.state === 'held' ? read.lock : null;
const own = current && ownsLock(current, o.owner, o.journal) ? current : null;
const scoped = o.processScoped;
const proc = scoped ? (scoped.proc === undefined ? thisProcess() : scoped.proc) : null;
const marks = scoped?.marks ?? lockMarkDir();
const previousMark = current?.proc?.mark;
let tookOver: LockTakeover | undefined;
if (read.state === 'unreadable') {
if (!o.breakLock) return { failure: { code: 'QUEUE_LAND_LOCKED', message: `the land lock at ${read.sha.slice(0, 12)} cannot be read (${read.detail}); --break-lock replaces it` }, lines };
lines.push(`LOCK: broke an unreadable lock at ${read.sha.slice(0, 12)} (${read.detail})`);
} else if (current && !own) {
const allowed = o.takeover?.(current) ?? null;
if (allowed) lines.push(allowed);
else {
} else if (current) {
const verdict = processScopedLock(current) ? judgeOwner(current, proc ?? thisProcess(), marks) : null;
if (verdict?.state === 'running') return { failure: { code: 'QUEUE_LAND_LOCKED', message: `${lockLabel(current)}'s land is still running: ${verdict.why}; a running land's lock is never taken over, --break-lock included`, fix: `wait for it to finish, then rerun land; if it is stuck, stop process ${verdict.pid} and rerun land, which then takes the lock over` }, lines };
const expiry = verdict ? lockExpiry(current) : NaN;
if (verdict?.state === 'held' && (own || current.pr === o.owner.pr) && !o.releasesHold && !o.breakLock) return { failure: { code: 'QUEUE_LAND_LOCKED', message: `#${current.pr}'s earlier land left the lock held on purpose: ${verdict.why.replace(/^its land left it held on purpose: /, '')}`, fix: scopedFix(current, 'held', expiry, o.now().getTime(), /changed this checkout/.test(verdict.why)) }, lines };
const allowed = own ? null : o.takeover?.(current) ?? null;
if (own) { /* this owner's own lock: resumed below */ } else if (allowed) lines.push(allowed);
else if (verdict && !o.breakLock && (verdict.state === 'gone' || (verdict.state === 'unknown' && o.now().getTime() >= expiry))) {
const why = verdict.state === 'gone' ? verdict.why : `it expired at ${new Date(expiry).toISOString()}, and ${verdict.why}`;
tookOver = { pr: current.pr, holder: current.holder, sha: read.sha, why, at: o.now().toISOString() };
lines.push(`LOCK_TAKEOVER: ${lockLabel(current)}'s land lock (holder ${current.holder}, phase ${current.phase}, since ${current.phase_at ?? current.started_at}): ${why}`);
} else {
const age = o.now().getTime() - Date.parse(current.phase_at ?? current.started_at);
if (!o.breakLock) return { failure: { code: 'QUEUE_LAND_LOCKED', message: `${lockLabel(current)} holds the land lock (${current.holder}, phase ${current.phase}, since ${current.started_at})` }, lines };
if (!o.breakLock) return { failure: { code: 'QUEUE_LAND_LOCKED', message: `${lockLabel(current)} holds the land lock (${current.holder}, phase ${current.phase}, since ${current.started_at})${verdict ? `; ${verdict.why}` : ''}`, ...(verdict ? { fix: scopedFix(current, verdict.state, expiry, o.now().getTime(), /changed this checkout/.test(verdict.why)) } : {}) }, lines };
lines.push(`LOCK_HOLDER: ${lockLabel(current)} holder=${current.holder} phase=${current.phase} since=${current.started_at}`);
const refusal = unbreakable(current, o, age);
if (refusal) return { failure: refusal, lines };
@@ -131,12 +265,16 @@ export function acquireLandLock(o: AcquireOptions): { held: HeldLandLock; lines:
const w = writeLock(o.root, sha, value, remote);
if (w.ok || w.origin === sha) return w;
const seen = readLock(o.root, remote);
if (seen.state !== 'held' || seen.sha === sha || !ownsLock(seen.lock, o.owner, o.journal) || seen.lock.holder !== o.holder) return w;
if (seen.state !== 'held' || seen.sha === sha || !ownsLock(seen.lock, o.owner, o.journal) || seen.lock.holder !== o.holder || seen.lock.proc?.mark !== proc?.mark) return w;
sha = seen.sha;
return writeLock(o.root, sha, value, remote);
};
const set = (phase: LandLockPhase, extra: Partial<LandLock> = {}): QueueFailure | null => {
const next: LandLock = { pr: o.owner.pr, ...(o.owner.train ? { train: o.owner.train, slot: o.owner.slot } : {}), holder: o.holder, started_at: startedAt, phase, journal: o.journal, phase_at: o.now().toISOString(), ...always, ...extra };
const at = o.now();
const next: LandLock = {
pr: o.owner.pr, ...(o.owner.train ? { train: o.owner.train, slot: o.owner.slot } : {}), holder: o.holder, started_at: startedAt, phase, journal: o.journal, phase_at: at.toISOString(),
...(proc ? { proc } : {}), ...(scoped ? { expires_at: new Date(at.getTime() + scoped.ttlMs).toISOString() } : {}), ...always, ...extra,
};
const w = write(next);
if (!w.ok) {
if (w.origin === null) return { code: 'QUEUE_NOT_READY', message: `the land lock push to ${remote} failed and ${remote}'s lock could not be read, so this run cannot tell whether the push landed`, fix: 'rerun the same command once origin answers; it resumes this run\'s own lock' };
@@ -147,13 +285,24 @@ export function acquireLandLock(o: AcquireOptions): { held: HeldLandLock; lines:
sha = w.sha; current = next;
return null;
};
const failed = set(o.phase(own));
if (failed) return { failure: failed, lines };
const markOf = (hold: string | null) => ({ pr: o.owner.pr, journal: o.journal, machine: thisMachine(), boot: proc!.boot, at: o.now().toISOString(), ...(hold ? { hold } : {}) });
if (proc) writeMark(marks, proc.mark, markOf(null));
const failed = set(o.phase(own), tookOver ? { took_over: tookOver } : {});
if (failed) {
if (proc) dropMark(marks, proc.mark);
return { failure: failed, lines };
}
if (previousMark) dropMark(marks, previousMark);
const held: HeldLandLock = {
get lock() { return current!; },
resumed: own,
set,
release: () => write({ released: true, by: o.holder, at: o.now().toISOString() }).ok,
release: () => {
const ok = write({ released: true, by: o.holder, at: o.now().toISOString() }).ok;
if (ok && proc) dropMark(marks, proc.mark);
return ok;
},
hold: reason => !proc || writeMark(marks, proc.mark, markOf(reason)),
};
return { held, lines };
}
+227 -1
View File
@@ -10,7 +10,10 @@ import { afterEach, describe, expect, test } from 'bun:test';
import * as fs from 'node:fs';
import * as path from 'node:path';
import { EXIT } from '../../lib/headless-artifacts';
import { acquireLandLock, LAND_LOCK_REF, readLock, writeLock, type LandLock, type LockOwner } from '../lib/ship-queue-land-lock';
import { spawn, spawnSync } from 'node:child_process';
import * as os from 'node:os';
import { acquireLandLock, DIRECT_LOCK_TTL_MS, judgeOwner, LAND_LOCK_REF, readLock, thisProcess, writeLock, type LandLock, type LockOwner, type LockProcess } from '../lib/ship-queue-land-lock';
import { bunIsolationArgs } from '../../lib/bun-isolation';
import { BASE_POLICY, cleanup, makeFixtureRepo, type FixtureRepo } from '../../test/helpers/restamp-fixture';
import { flakyGit } from '../../test/helpers/flaky-git';
import { coordinatorClone } from '../../test/helpers/ship-queue-fixture';
@@ -214,6 +217,229 @@ describe('the lock module', () => {
}, 60_000);
});
/** A real process as a lock records it: its group and kernel start time, with this machine's boot id and pid namespace. */
function procOf(pid: number, self: LockProcess, boot = self.boot): LockProcess {
const stat = fs.readFileSync(`/proc/${pid}/stat`, 'utf8');
const f = stat.slice(stat.lastIndexOf(')') + 2).split(' ');
return { boot, pidns: self.pidns, pid, pgid: Number(f[2]), start: Number(f[19]), mark: `mark-${pid}-${Date.now()}` };
}
/** A detached shell running script; resolves once /proc shows it leading its own process group. */
async function group(script: string) {
const child = spawn('sh', ['-c', script], { detached: true, stdio: 'ignore' });
const exited = new Promise<void>(resolve => child.on('exit', () => resolve()));
const leads = () => { try { const s = fs.readFileSync(`/proc/${child.pid}/stat`, 'utf8'); return Number(s.slice(s.lastIndexOf(')') + 2).split(' ')[2]) === child.pid; } catch { return false; } };
while (!leads()) await Bun.sleep(5);
return { pid: child.pid!, exited, kill: () => { try { process.kill(-child.pid!, 'SIGKILL'); } catch { /* gone */ } } };
}
describe.skipIf(process.platform !== 'linux')('a direct land\'s lock cannot go stale (process-scoped locks)', () => {
const pin = (n: string) => `land-pin:${n.repeat(40)}`;
const marksDirs: string[] = [];
afterEach(() => { while (marksDirs.length) fs.rmSync(marksDirs.pop()!, { recursive: true, force: true }); });
const newMarks = () => { const d = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-land-marks-')); marksDirs.push(d); return d; };
const takeDirect = (root: string, pr: string, o: { proc: LockProcess | null; marks: string; now?: () => Date; breakLock?: boolean; journal?: string; releasesHold?: boolean }) => acquireLandLock({
root, holder: `cox.local:${o.proc?.pid ?? 1}`, owner: { pr }, journal: o.journal ?? pin(pr.slice(-1)), now: o.now ?? at(0), phase: () => 'merging', breakLock: o.breakLock, releasesHold: o.releasesHold,
processScoped: { ttlMs: DIRECT_LOCK_TTL_MS, proc: o.proc, marks: o.marks },
});
test('a lock whose land process has exited is taken over without --break-lock, and the takeover is logged in the output and in the new lock', async () => {
const self = thisProcess()!;
const repo = bareRepo();
const marks = newMarks();
const dead = await group('sleep 30');
const proc = procOf(dead.pid, self);
dead.kill();
await dead.exited;
withRepoEnv(repo, () => {
expect(failureOf(takeDirect(repo.work, '4670', { proc, marks }))).toBeNull();
expect(readLock(repo.work)).toMatchObject({ state: 'held', lock: { pr: '4670', proc: { pid: dead.pid }, expires_at: new Date(T0 + DIRECT_LOCK_TTL_MS).toISOString() } });
const judged = readLock(repo.work).sha;
const next = takeDirect(repo.work, '4671', { proc: { ...self, mark: 'next' }, marks, now: at(1) });
expect(failureOf(next)).toBeNull();
expect(next.lines.join('\n')).toMatch(new RegExp(`^LOCK_TAKEOVER: #4670's land lock \\(holder cox.local:${dead.pid}, phase merging, since .*\\): its land \\(process ${dead.pid}\\) and every process it started have exited$`, 'm'));
const now = readLock(repo.work);
expect(now).toMatchObject({ state: 'held', lock: { pr: '4671', took_over: { pr: '4670', sha: judged, holder: `cox.local:${dead.pid}` } } });
expect(repo.git('log', '-1', '--format=%s', LAND_LOCK_REF)).toContain('(took over #4670: its land');
});
}, 60_000);
test('a lock whose land is still running is refused, --break-lock included, even when the land\'s first process exited and left a child running', async () => {
const self = thisProcess()!;
const repo = bareRepo();
const marks = newMarks();
const live = await group('sleep 60');
const parent = await group('sleep 60 & sleep 0.5; exit 0');
try {
const parentProc = procOf(parent.pid, self);
await parent.exited;
withRepoEnv(repo, () => {
expect(failureOf(takeDirect(repo.work, '4670', { proc: procOf(live.pid, self), marks }))).toBeNull();
for (const breakLock of [false, true]) {
const refused = failureOf(takeDirect(repo.work, '4671', { proc: { ...self, mark: 'b' }, marks, now: at(500), breakLock }));
expect(refused).toMatchObject({ code: 'QUEUE_LAND_LOCKED' });
expect(refused!.message).toContain(`#4670's land is still running: process ${live.pid} of its land`);
expect(refused!.fix).toContain(`stop process ${live.pid}`);
}
live.kill();
writeLock(repo.work, readLock(repo.work).sha, { released: true, by: 'test', at: new Date(T0).toISOString() });
expect(failureOf(takeDirect(repo.work, '4672', { proc: parentProc, marks }))).toBeNull();
const orphaned = failureOf(takeDirect(repo.work, '4673', { proc: { ...self, mark: 'c' }, marks, now: at(1) }));
expect(orphaned!.message).toMatch(/#4672's land is still running: process \d+ of its land/);
expect(orphaned!.message).not.toContain(`process ${parent.pid} of`);
});
} finally { live.kill(); parent.kill(); }
}, 60_000);
test('a lock from another machine is refused until it expires, naming the expiry and the fix, then taken over; one this machine wrote before it restarted is taken over at once', () => {
const self = thisProcess()!;
const repo = bareRepo();
const marks = newMarks();
withRepoEnv(repo, () => {
const elsewhere: LockProcess = { ...self, boot: 'another-boot', pid: 1640, pgid: 1640, start: 1, mark: 'elsewhere' };
expect(failureOf(takeDirect(repo.work, '4670', { proc: elsewhere, marks: newMarks() }))).toBeNull();
const early = failureOf(takeDirect(repo.work, '4671', { proc: { ...self, mark: 'x' }, marks, now: at(89) }));
expect(early).toMatchObject({ code: 'QUEUE_LAND_LOCKED' });
expect(early!.message).toContain('its land ran on another machine, so this one cannot check whether it still runs');
expect(early!.fix).toContain(`the lock expires at ${new Date(T0 + DIRECT_LOCK_TTL_MS).toISOString()} (in 1 min)`);
expect(early!.fix).toContain('--break-lock');
const expired = takeDirect(repo.work, '4671', { proc: { ...self, mark: 'y' }, marks, now: at(90) });
expect(failureOf(expired)).toBeNull();
expect(expired.lines.join('\n')).toContain(`LOCK_TAKEOVER: #4670's land lock (holder cox.local:1640, phase merging, since ${new Date(T0).toISOString()}): it expired at ${new Date(T0 + DIRECT_LOCK_TTL_MS).toISOString()}`);
const before: LockProcess = { ...self, boot: 'before-restart', pid: 1639, pgid: 1639, start: 1, mark: 'restarted' };
writeLock(repo.work, readLock(repo.work).sha, { released: true, by: 'test', at: new Date(T0).toISOString() });
expect(failureOf(takeDirect(repo.work, '4672', { proc: before, marks }))).toBeNull();
expect(fs.existsSync(path.join(marks, 'restarted.json'))).toBe(true);
const rebooted = takeDirect(repo.work, '4673', { proc: { ...self, mark: 'z' }, marks, now: at(1) });
expect(failureOf(rebooted)).toBeNull();
expect(rebooted.lines.join('\n')).toContain('this machine wrote it before it last restarted, so its land is gone');
expect(fs.existsSync(path.join(marks, 'restarted.json'))).toBe(false);
});
}, 60_000);
test('a lock from an older gstack (no process, no expiry) expires 90 minutes after its last phase; a deliberate hold refuses even after it expires', () => {
const self = thisProcess()!;
const repo = bareRepo();
const marks = newMarks();
withRepoEnv(repo, () => {
const old: LandLock = { pr: '4670', holder: 'cox.local:74326', started_at: new Date(T0).toISOString(), phase_at: new Date(T0).toISOString(), phase: 'merging', journal: pin('4') };
writeLock(repo.work, readLock(repo.work).sha, old);
expect(failureOf(takeDirect(repo.work, '4671', { proc: { ...self, mark: 'p' }, marks, now: at(30) }))!.message).toContain('it records no land process (an older gstack wrote it)');
expect(failureOf(takeDirect(repo.work, '4671', { proc: { ...self, mark: 'q' }, marks, now: at(91) }))).toBeNull();
const holder: LockProcess = { ...self, boot: 'held-boot', pid: 77, pgid: 77, start: 1, mark: 'held' };
writeLock(repo.work, readLock(repo.work).sha, { released: true, by: 'test', at: new Date(T0).toISOString() });
const tampered = takeDirect(repo.work, '4672', { proc: holder, marks });
if (!('held' in tampered)) throw new Error('lock not taken');
tampered.held.hold('land.merged_checks changed this checkout\'s git directory while landing #4672');
const refused = failureOf(takeDirect(repo.work, '4673', { proc: { ...self, mark: 'r' }, marks, now: at(500) }));
expect(refused!.message).toContain('its land left it held on purpose: land.merged_checks changed');
expect(refused!.fix).toContain(`gstack-ship-queue land --pr 4672 --pin ${'2'.repeat(40)}`);
});
}, 60_000);
test('a hold set while land.merged_checks run keeps a dead land\'s lock refused; cleared, the lock is taken over', async () => {
const self = thisProcess()!;
const repo = bareRepo();
const marks = newMarks();
const dead = await group('sleep 30');
const proc = procOf(dead.pid, self);
dead.kill();
await dead.exited;
withRepoEnv(repo, () => {
const got = takeDirect(repo.work, '4670', { proc, marks });
if (!('held' in got)) throw new Error('lock not taken');
expect(got.held.hold('land.merged_checks were running when it stopped')).toBe(true);
const refused = failureOf(takeDirect(repo.work, '4671', { proc: { ...self, mark: 'h1' }, marks, now: at(1) }));
expect(refused!.message).toContain('its land left it held on purpose: land.merged_checks were running when it stopped');
expect(refused!.fix).toContain('or pass --break-lock');
const retry = failureOf(takeDirect(repo.work, '4670', { proc: { ...self, mark: 'h0' }, marks, now: at(1) }));
expect(retry!.message).toBe("#4670's earlier land left the lock held on purpose: land.merged_checks were running when it stopped");
expect(failureOf(takeDirect(repo.work, '4670', { proc: { ...self, mark: 'h0' }, marks, now: at(1), releasesHold: true }))).toBeNull();
writeLock(repo.work, readLock(repo.work).sha, { released: true, by: 'test', at: new Date(T0).toISOString() });
const again = takeDirect(repo.work, '4672', { proc, marks });
if (!('held' in again)) throw new Error('lock not taken');
expect(again.held.hold('land.merged_checks were running when it stopped')).toBe(true);
expect(again.held.hold(null)).toBe(true);
expect(failureOf(takeDirect(repo.work, '4671', { proc: { ...self, mark: 'h2' }, marks, now: at(1) }))).toBeNull();
const unwritable = path.join(marks, 'not-a-dir');
fs.writeFileSync(unwritable, '');
writeLock(repo.work, readLock(repo.work).sha, { released: true, by: 'test', at: new Date(T0).toISOString() });
const blind = takeDirect(repo.work, '4673', { proc: { ...self, mark: 'h3' }, marks: unwritable });
if (!('held' in blind)) throw new Error('lock not taken');
expect(blind.held.hold('land.merged_checks were running when it stopped')).toBe(false);
});
}, 60_000);
test('a mark file proves a restart only for this machine and a different boot: another pid namespace or another machine\'s mark is unknown', () => {
const self = thisProcess()!;
const marks = newMarks();
const lock = (proc: LockProcess): LandLock => ({ pr: '4670', holder: 'cox.local:9', started_at: new Date(T0).toISOString(), phase: 'merging', journal: pin('4'), proc });
const otherNs: LockProcess = { ...self, pidns: 'pid:[1]', pid: 9, pgid: 9, start: 1, mark: 'ns' };
const machine = `${os.hostname()}/${(() => { try { return fs.readFileSync('/etc/machine-id', 'utf8').trim(); } catch { return ''; } })()}`;
fs.writeFileSync(path.join(marks, 'ns.json'), JSON.stringify({ machine, boot: self.boot }));
expect(judgeOwner(lock(otherNs), self, marks).state).toBe('unknown');
const heldElsewhere: LockProcess = { ...self, boot: 'their-boot', pid: 9, pgid: 9, start: 1, mark: 'held-elsewhere' };
fs.writeFileSync(path.join(marks, 'held-elsewhere.json'), JSON.stringify({ machine: 'another-host/another-id', boot: 'their-boot', hold: 'land.merged_checks were running when it stopped' }));
expect(judgeOwner(lock(heldElsewhere), self, marks).state).toBe('unknown');
const otherMachine: LockProcess = { ...self, boot: 'their-boot', pid: 9, pgid: 9, start: 1, mark: 'theirs' };
fs.writeFileSync(path.join(marks, 'theirs.json'), JSON.stringify({ machine: 'another-host/another-id', boot: 'their-boot' }));
expect(judgeOwner(lock(otherMachine), self, marks).state).toBe('unknown');
});
test('a rerun in the dead holder\'s own process group is not refused because of its own siblings (a | cat beside it)', () => {
const dir = newMarks();
const judge = path.join(dir, 'judge.ts');
fs.writeFileSync(judge, `import * as fs from 'node:fs';
import { judgeOwner, thisProcess } from ${JSON.stringify(path.resolve(import.meta.dir, '../lib/ship-queue-land-lock.ts'))};
const self = thisProcess()!;
const stat = fs.readFileSync(process.argv[2]!, 'utf8');
const f = stat.slice(stat.lastIndexOf(')') + 2).split(' ');
const proc = { ...self, pid: Number(stat.split(' ')[0]), pgid: Number(f[2]), start: Number(f[19]), mark: 'none' };
console.log(judgeOwner({ pr: '1', holder: 'h', started_at: '', phase: 'merging', journal: 'land-pin:1', proc }, self, process.argv[3]!).state);
`);
const bun = [process.execPath, ...bunIsolationArgs()].map(a => `'${a}'`).join(' ');
const script = `sleep 0.5 & cat /proc/$!/stat > '${dir}/holder.stat'; wait; ${bun} '${judge}' '${dir}/holder.stat' '${dir}' | cat`;
const r = spawnSync('setsid', ['sh', '-c', script], { encoding: 'utf8', timeout: 30_000 });
expect(r.stdout.trim(), r.stderr).toBe('gone');
}, 60_000);
test('a stalled takeover never replaces a newer owner\'s lock, and a taken-over land can neither move nor release the lock it lost', async () => {
const self = thisProcess()!;
const repo = bareRepo();
const other = coordinatorClone(repo);
const marks = newMarks();
const dead = await group('sleep 30');
const deadProc = procOf(dead.pid, self);
dead.kill();
await dead.exited;
withRepoEnv(repo, () => {
const lost = takeDirect(repo.work, '4670', { proc: deadProc, marks });
if (!('held' in lost)) throw new Error('lock not taken');
let fresh = '';
const stalled = takeDirect(repo.work, '4671', {
proc: { ...self, mark: 'stalled' }, marks,
now: () => {
if (!fresh) {
const seen = readLock(other);
const w = writeLock(other, seen.sha, { pr: '4672', holder: 'fresh:1', started_at: new Date(T0).toISOString(), phase: 'merging', journal: pin('7'), proc: { ...self, mark: 'fresh' }, expires_at: new Date(T0 + DIRECT_LOCK_TTL_MS).toISOString() });
expect(w.ok).toBe(true);
fresh = w.sha;
}
return new Date(T0 + 60_000);
},
});
expect(failureOf(stalled)).toMatchObject({ code: 'QUEUE_LAND_LOCKED', message: 'the land lock moved under this run (another lander took it)' });
expect(repo.git('--git-dir', repo.origin, 'rev-parse', LAND_LOCK_REF)).toBe(fresh);
expect(lost.held.set('merging')).toMatchObject({ code: 'QUEUE_LAND_LOCKED' });
expect(lost.held.release()).toBe(false);
expect(readLock(repo.work)).toMatchObject({ state: 'held', lock: { pr: '4672', holder: 'fresh:1' } });
});
}, 60_000);
});
const POLICY = { ...TRAIN_POLICY, release_tool: null, release_outputs: [], changelog_fragments: { dir: 'changelog.d' }, min_gstack_version: '1.91.336.0' };
function stampedTrain(prs = ['1', '2']) {
const fx = trainFixture(POLICY, 'gstack-land-lock-'); fixtures.push(fx); wrapLand(fx);
+58 -1
View File
@@ -2998,7 +2998,7 @@ release-file rows):
| VERSION, the `package.json` version, the CHANGELOG and `.gstack/version-path` are unchanged since the merge base | [`QUEUE_LAND_STAMPED`](troubleshooting.md#queue-land-stamped) |
| every check at the pin is green with none pending, and each `changelog_fragments.required_checks` entry passed there | [`QUEUE_LAND_CHECKS`](troubleshooting.md#queue-land-checks) |
| GitHub reports the PR `MERGEABLE` and `CLEAN` | [`QUEUE_LAND_NOT_CLEAN`](troubleshooting.md#queue-land-not-clean) |
| land takes the land lock (`land-pin:<pin>` journal, phase `merging`) and re-fetches `origin/main`; it takes over a lock an earlier `land --pin` run of the same PR left, and `--break-lock` breaks another lander's stale lock under the usual rules | `QUEUE_LAND_LOCKED`, `QUEUE_NOT_READY` |
| land takes the land lock (`land-pin:<pin>` journal, phase `merging`) and re-fetches `origin/main`; it takes over a lock an earlier `land --pin` run of the same PR left, and another lander's lock whose land exited or expired ([the land lock can't go stale](#land-lock)); `--break-lock` breaks a stale lock of unknown state under the usual rules, never a running land's | `QUEUE_LAND_LOCKED`, `QUEUE_NOT_READY` |
| when the base moved past the pin's merge base and the base policy lists `land.merged_checks`: `--allow-repo-commands` was passed, the pin merges onto the tip without a conflict, and every command passes on that merged tree | [`REPO_COMMANDS_NOT_ALLOWED`](troubleshooting.md#repo-commands-not-allowed), [`QUEUE_LAND_NOT_CLEAN`](troubleshooting.md#queue-land-not-clean), [`QUEUE_LAND_MERGED_CHECKS`](troubleshooting.md#queue-land-merged-checks) |
| when the base moved past the pin's merge base and the base policy sets `land.merged_ci`: the workflow's run on the merged commit is green, and `lib/run-evidence.ts` accepts it under the named run profile with the merged tree as its tested tree | [`QUEUE_LAND_MERGED_CHECKS`](troubleshooting.md#queue-land-merged-checks) (a red run), `QUEUE_NOT_READY` |
@@ -3110,6 +3110,63 @@ in place of the merged checks, and merges nothing; on a PR that already
merged it verifies nothing. Under `merge: direct`, `train build` refuses and
names this command.
<a id="land-lock"></a>
#### The land lock can't go stale
`land --pin` holds `refs/notes/gstack-land` only while it runs. When that run dies
(its machine restarts, or the shell that started it is killed), nothing releases the
lock, and every other land refuses with `QUEUE_LAND_LOCKED`. On 2026-11-22 that kept
about 15 green gstack PRs waiting for hours behind #4670. So each lock a direct land
writes records the process holding it (boot id, pid namespace, pid, process group,
start time and a random mark) and an `expires_at` 90 minutes after its last phase,
which is longer than any normal land (`land.merged_checks`, up to 45 minutes of
`land.merged_ci`, then the merge). The run also keeps a mark file under
`$GSTACK_STATE_ROOT/ship-queue/land-owners/` until it releases. The next land judges
the lock before anything else:
| The holder is | How land knows | What land does |
|---|---|---|
| running | a process in the holder's process group that started at or after it is alive on this machine (the holder, or a child it started, even one orphaned when the holder died; never the judging run itself, its ancestors or its siblings) | refuses, even with `--break-lock`, naming the process to stop if it is stuck |
| gone | that group has no such process left, or a mark file written by this same machine (hostname and machine id) under an earlier boot id shows it wrote the lock before it last restarted | takes it over, no flag needed |
| unknown, expired | it ran on another machine, or an older gstack wrote it without a process, and `expires_at` (or its last phase plus 90 minutes) has passed | takes it over, no flag needed |
| unknown, not expired | as above, before the expiry | refuses with the expiry time and the fix: rerun after it, or pass `--break-lock` once you know that land stopped (the usual `--break-lock` rules apply) |
| held on purpose | its mark file here records a hold: `land.merged_checks` were running when it stopped (they run in their own process group, so a check may still run and the git directory was never compared), or they changed the checkout's git directory | refuses on this machine even after the expiry, that PR's own rerun with `--allow-repo-commands` included; make sure nothing it started still runs and the git directory is intact, then release it with that PR's own `land --pr <n> --pin <sha>` without `--allow-repo-commands` (or `--break-lock` when no check changed the git directory) |
Every takeover prints `LOCK_TAKEOVER: <lock> (holder, phase, since): <why>` and writes
`took_over` (the PR, the holder, the lock commit it replaced, why and when) into the
new lock, whose commit subject ends `(took over #<n>: <why>)`, so
`git log refs/notes/gstack-land` is the takeover log. The takeover is written under an
exact lease on the lock commit it judged: if another lander moved the lock meanwhile,
the takeover fails instead of replacing the newer lock, and a land whose lock was taken
over can no longer move or release it, because a retry adopts only a lock that carries
its own mark (two machines can share a hostname and a pid). A hold lives in the
holding machine's state root and names that machine, so another machine, whose
checkout the checks never touched, still takes the lock over once it expires. A land
that cannot write the hold before its checks start runs no check and merges nothing. Telling whether a holder
runs needs Linux's `/proc`; elsewhere only the expiry applies. Locks from the
stamp-at-merge `land` and from `train land` keep the rules in
[the per-PR merge step](#gstack-ship-queue-land-the-per-pr-merge-step).
<a id="revert-drill"></a>
#### The revert drill: proof a repository can undo a bad land fast
A low-risk PR may land on its own green head without being re-tested when main moves
([the drain lanes](../crew/docs/captain.md#drain-the-queue)) only in a repository that
has shown it can undo a bad land quickly: if main goes red, its culprit is reverted
within 30 minutes. The drill proves that once, with a clock:
1. Open a harmless one-line docs PR (a sentence nothing depends on), /ship it, and land
it the normal way: `gstack-ship-queue land --pr <n> --pin <head>`.
2. Make its revert on a fresh branch from main (`git revert --no-edit <merge sha>`),
open the PR, /ship it and send it READY. Start the clock at that READY.
3. Land the revert with `land --pin`, then wait for main's push checks at its merge
commit with `gstack-ship-queue verify --post-merge <merge sha>` until it prints
`POST_MERGE: green`. Stop the clock.
4. Report both PRs, both merge commits, the READY time, the green time and the minutes
between to the Captain, which records the drill in its notes. Under 30 minutes opens
the low-risk lane. Over 30 minutes, the repository keeps re-testing every land until
the slow step is fixed and a new drill passes.
<a id="direct-freeze"></a>
#### The freeze under `merge: direct`: `land --pin --repair`
+9
View File
@@ -6404,6 +6404,15 @@ released by the verify that clears the freeze
next `land` or `train land` takes the lock over once the freeze record it fetches
shows the freeze cleared after the lock was written; `--break-lock` never does.
Under `merge: direct`, `land --pin` takes over by itself a lock whose land has
exited or whose 90-minute expiry has passed, and prints `LOCK_TAKEOVER:`. When it
still refuses, the message says why: a land that is still running (wait, or stop
the process it names if it is stuck; `--break-lock` is refused), another
machine's land that has not expired yet (rerun after the expiry it prints, or pass
`--break-lock` once you know that land stopped), or a deliberate hold (release it
as the `LOCK:` line says). See
[the land lock can't go stale](ship-policy.md#land-lock).
A lock push that GitHub applied but answered with an error (an HTTP 502) is
checked against origin's ref and counts as written, so a rerun resumes this
run's own lock without `--break-lock`.
+64
View File
@@ -0,0 +1,64 @@
/**
* `gstack-ship-queue count` (R119): how many of this repository's PRs are finished and waiting to land, cheap enough
* to run at every Captain wake. One gh call (one GraphQL query) reads the oldest 100 open PRs with each one's newest
* commit. A PR is finished when one of the authors opened it (garrytan, capy-ai and garrytan-agents unless --authors
* says otherwise), it targets the base, it is not a draft, GitHub does not report it conflicting, and the check
* rollup on its newest commit is SUCCESS. Its wait runs from that commit's date. More than DRAIN_COUNT finished,
* or one that has waited DRAIN_HOURS or more, prints a DRAIN line: the Captain starts a drain that same turn
* (docs/captain.md#drain-the-queue).
*/
import type { QueueContext, StepOutput } from './ship-queue';
export const DRAIN_COUNT = 6;
export const DRAIN_HOURS = 24;
export const DEFAULT_AUTHORS = ['garrytan', 'capy-ai', 'garrytan-agents'];
const SHOWN = 10;
export const COUNT_QUERY = 'query($owner:String!,$name:String!){repository(owner:$owner,name:$name){pullRequests(states:OPEN,first:100,orderBy:{field:CREATED_AT,direction:ASC}){totalCount nodes{number title isDraft mergeable baseRefName author{login} commits(last:1){nodes{commit{committedDate statusCheckRollup{state}}}}}}}}';
interface PrNode {
number: number; title: string; isDraft: boolean; mergeable: string; baseRefName: string; author: { login: string } | null;
commits: { nodes: Array<{ commit: { committedDate: string; statusCheckRollup: { state: string } | null } }> };
}
export interface FinishedPr { pr: number; title: string; hours: number }
/** A bot's login reads as `capy-ai`, `capy-ai[bot]` or `app/capy-ai` depending on the API; compare the bare name. */
const bare = (login: string) => login.toLowerCase().replace(/^app\//, '').replace(/\[bot\]$/, '');
/** The finished PRs among nodes, oldest wait first. */
export function finishedPrs(nodes: PrNode[], o: { base: string; authors: string[]; now: Date }): FinishedPr[] {
const authors = new Set(o.authors.map(bare));
const out: FinishedPr[] = [];
for (const n of nodes) {
const head = n.commits?.nodes?.[0]?.commit;
if (!head || n.isDraft || n.mergeable === 'CONFLICTING' || n.baseRefName !== o.base || !authors.has(bare(n.author?.login ?? ''))) continue;
if (head.statusCheckRollup?.state !== 'SUCCESS') continue;
const since = Date.parse(head.committedDate);
if (Number.isNaN(since)) continue;
out.push({ pr: n.number, title: n.title, hours: Math.max(0, Math.floor((o.now.getTime() - since) / 3_600_000)) });
}
return out.sort((a, b) => b.hours - a.hours || a.pr - b.pr);
}
export function queueCount(ctx: QueueContext, o: { authors?: string[]; now?: Date } = {}): StepOutput {
const authors = o.authors?.length ? o.authors : DEFAULT_AUTHORS;
const r = ctx.gh(['api', 'graphql', '-F', 'owner={owner}', '-F', 'name={repo}', '-f', `query=${COUNT_QUERY}`]);
let page: { totalCount: number; nodes: PrNode[] } | undefined;
try { page = JSON.parse(r.out)?.data?.repository?.pullRequests; } catch { /* reported below */ }
if (!r.ok || !page || !Array.isArray(page.nodes)) {
return { ok: false, lines: [], run: 'none', failure: { code: 'QUEUE_NOT_READY', message: `gh could not list the open PRs: ${(r.err || r.out).trim().split('\n')[0]?.slice(0, 200) || 'no data'}`, fix: 'check gh auth status and that this checkout\'s origin is the GitHub repository, then rerun count' } };
}
const finished = finishedPrs(page.nodes, { base: ctx.base, authors, now: o.now ?? new Date() });
const old = finished.filter(f => f.hours >= DRAIN_HOURS);
const oldest = finished[0];
const lines = [`QUEUE_COUNT: finished=${finished.length} waited_${DRAIN_HOURS}h=${old.length} oldest=${oldest ? `${oldest.hours}h #${oldest.pr}` : 'none'} open=${page.totalCount} base=${ctx.base} authors=${authors.join(',')}`];
if (page.totalCount > page.nodes.length) lines.push(`QUEUE_COUNT_PARTIAL: counted the oldest ${page.nodes.length} of ${page.totalCount} open PRs`);
for (const f of finished.slice(0, SHOWN)) lines.push(`FINISHED: #${f.pr} ${f.hours}h ${f.title}`);
if (finished.length > SHOWN) lines.push(`FINISHED: and ${finished.length - SHOWN} more`);
const why = [
...(finished.length > DRAIN_COUNT ? [`${finished.length} finished PRs are waiting (more than ${DRAIN_COUNT})`] : []),
...(old.length ? [`${old.length} ${old.length === 1 ? 'has' : 'have'} waited ${DRAIN_HOURS}h or more (oldest #${oldest!.pr}, ${oldest!.hours}h)`] : []),
];
if (why.length) lines.push(`DRAIN: ${why.join(' and ')}; start a drain this turn: land them, bundle them, or send each idle owner its next step (docs/captain.md#drain-the-queue)`);
return { ok: true, lines, run: 'none' };
}
+14 -5
View File
@@ -26,7 +26,7 @@ import { versionAtRef } from './restamp';
import type { ShipPolicy } from './ship-policy';
import { ciAtHead, loadBasePolicy, type QueueContext, type StepOutput } from './ship-queue';
import { git, queueHooksOff, type QueueFailure } from '../crew/lib/ship-queue-gate';
import { acquireLandLock, lockLabel, ownsLock, readLock, type HeldLandLock, type LandLock } from '../crew/lib/ship-queue-land-lock';
import { acquireLandLock, DIRECT_LOCK_TTL_MS, lockLabel, ownsLock, readLock, type HeldLandLock, type LandLock } from '../crew/lib/ship-queue-land-lock';
import * as os from 'node:os';
import { activeFreeze, loadReady, persist, rebuildFromNotes, repoIdentity, type FreezeRecord } from '../crew/lib/ship-queue-train-record';
import { bindShippedReceipt } from './ship-receipt-depth';
@@ -75,6 +75,8 @@ export function verifyPin(ctx: QueueContext, o: { pr: string; pin: string; accep
}
const isSha = (s: string | undefined) => /^[0-9a-f]{40,64}$/.test(s ?? '');
/** The hold a direct land sets while land.merged_checks run detached, outside its process group: a land that stops there needs a person. */
const CHECKS_HOLD = 'land.merged_checks were running when it stopped, so a check may still run and the checkout\'s git directory was never compared';
function view(ctx: QueueContext, pr: string): DirectPr | QueueFailure {
const r = ctx.gh(['pr', 'view', pr, '--json', 'state,baseRefName,headRefName,headRefOid,isCrossRepository,body,title,mergeable,mergeStateStatus,mergeCommit']);
@@ -122,7 +124,7 @@ function havePin(root: string, pr: string, pin: string, branch?: string): boolea
}
/** The merge commit's tree is the pin merged onto the merge commit's first parent: GitHub merged exactly the pin. A read that fails is "cannot verify", never a mismatch. */
function verifyMerge(ctx: QueueContext, root: string, pr: string, pin: string, merge: string, lines: string[], run: string, now: Date, stamped?: string | 'pin-parent', merged: { checks: string[]; on?: string; allow?: boolean } = { checks: [] }): StepOutput {
function verifyMerge(ctx: QueueContext, root: string, pr: string, pin: string, merge: string, lines: string[], run: string, now: Date, stamped?: string | 'pin-parent', merged: { checks: string[]; on?: string; allow?: boolean; hold?: (reason: string | null) => boolean } = { checks: [] }): StepOutput {
const cannot = (why: string): StepOutput => ({ ok: false, run, lines, failure: { code: 'QUEUE_NOT_READY', message: `#${pr} merged as ${merge.slice(0, 12)}, but land cannot verify it: ${why}`, fix: `fix the read named, then rerun gstack-ship-queue land --pr ${pr} --pin ${pin}; it goes straight to the tree check` } });
if (!git(root, ['fetch', '-q', 'origin', ctx.base]).ok) return cannot(`git fetch origin ${ctx.base} failed`);
if (!havePin(root, pr, pin)) return cannot(`the pin ${pin.slice(0, 12)} is not in this clone and refs/pull/${pr}/head did not fetch it`);
@@ -137,7 +139,9 @@ function verifyMerge(ctx: QueueContext, root: string, pr: string, pin: string, m
else if (!merged.checks.length) return unverified('the base policy lists no land.merged_checks to run on it');
else if (!merged.allow) return { ok: false, run, lines, failure: { code: 'REPO_COMMANDS_NOT_ALLOWED', message: `${onto}, so land must run land.merged_checks on the tree that landed; they are repo commands, so nothing ran`, fix: `rerun gstack-ship-queue land --pr ${pr} --pin ${pin} --allow-repo-commands` } };
else {
if (merged.hold && !merged.hold(CHECKS_HOLD)) return cannot('it could not record under the state root that land.merged_checks are about to run (make $GSTACK_STATE_ROOT/ship-queue/land-owners writable)');
const mc = runMergedChecks(root, parent, pin, merged.checks);
if (!changedCheckouts.has(root)) merged.hold?.(null);
if (!mc.ok) return mc.setup ? cannot(mc.detail) : unverified(`land.merged_checks did not pass on it: ${mc.detail}`);
lines.push(`MERGED_CHECKS: pass tree=${mc.tree} base=${parent} (after the merge, on the base GitHub merged onto)`);
}
@@ -176,7 +180,7 @@ export function landDirect(ctx: QueueContext, o: DirectOptions): StepOutput {
const journal = `land-pin:${o.pin}`;
const unlock = `LOCK: warn land.merged_checks changed the checkout's git directory, so land pushed no lock release and the land lock stays held; once every path it names is restored from a trusted copy, release the lock without running the checks: gstack-ship-queue land --pr ${o.pr} --pin ${o.pin} (without --allow-repo-commands)`;
const takeLock = () => acquireLandLock({
root, remote, holder: `${os.hostname()}:${process.pid}`, owner: { pr: o.pr }, journal, now, phase: () => 'merging', breakLock: o.breakLock,
root, remote, holder: `${os.hostname()}:${process.pid}`, owner: { pr: o.pr }, journal, now, phase: () => 'merging', breakLock: o.breakLock, processScoped: { ttlMs: DIRECT_LOCK_TTL_MS }, releasesHold: !o.allowRepoCommands,
takeover: (held: LandLock) => !held.train && held.pr === o.pr && held.journal.startsWith('land-pin:') ? `LOCK: taking over #${o.pr}'s land lock that an earlier land --pin run left (${held.journal}, since ${held.started_at})` : null,
});
if (info.state === 'MERGED' && info.headRefOid === o.pin && isSha(info.mergeCommit?.oid)) {
@@ -272,7 +276,9 @@ export function landDirect(ctx: QueueContext, o: DirectOptions): StepOutput {
if (ci) lines.push(`DRY-RUN: land.merged_ci not dispatched; a real land runs ${ci.workflow} on the pin merged onto ${tip.slice(0, 12)} and waits for it`);
} else if (checks.length && !o.allowRepoCommands) return fail(lines, { code: 'REPO_COMMANDS_NOT_ALLOWED', message: `${moved}, so land must run land.merged_checks on the pin merged onto it; they are repo commands (the merged tree's package.json decides what they run), so nothing ran and nothing merged`, fix: `rerun gstack-ship-queue land --pr ${o.pr} --pin ${o.pin} --allow-repo-commands` });
else {
if (checks.length && held && !held.hold(CHECKS_HOLD)) return fail(lines, { code: 'QUEUE_NOT_READY', message: `${moved}, and land could not record under the state root that land.merged_checks are about to run, so a land that stopped during them would look gone; nothing ran and nothing merged`, fix: 'make $GSTACK_STATE_ROOT/ship-queue/land-owners writable (or free disk space), then rerun land' });
const built = checks.length ? runMergedChecks(root, tip, o.pin, checks) : mergedCommit(root, tip, o.pin);
if (checks.length && !changedCheckouts.has(root)) held?.hold(null);
if (!built.ok) return refuse(built);
if (checks.length) lines.push(`MERGED_CHECKS: pass tree=${built.tree} base=${tip} pin=${o.pin.slice(0, 12)} checks: ${checks.join('; ')}`);
if (ci) {
@@ -311,11 +317,14 @@ export function landDirect(ctx: QueueContext, o: DirectOptions): StepOutput {
}
if (!isSha(merge) && m.ok) return fail(lines, { code: 'QUEUE_NOT_READY', message: `gh pr merge accepted #${o.pr}, but GitHub does not show it merged yet; nothing is verified`, fix: `rerun gstack-ship-queue land --pr ${o.pr} --pin ${o.pin} in a minute; once GitHub shows the merge it goes straight to the tree check` });
if (!isSha(merge)) return fail(lines, { code: 'QUEUE_NOT_READY', message: `gh pr merge refused: ${(m.err ?? m.out).trim().slice(0, 200) || 'the PR is not merged'}`, fix: `read the refusal; rerun land --pr ${o.pr} --pin ${o.pin} once it is fixed` });
return verifyMerge(ctx, root, o.pr, o.pin, merge!, lines, run, now(), release ? mergeBase : undefined, { checks, on: tip, allow: o.allowRepoCommands });
return verifyMerge(ctx, root, o.pr, o.pin, merge!, lines, run, now(), release ? mergeBase : undefined, { checks, on: tip, allow: o.allowRepoCommands, hold: held && (reason => held!.hold(reason)) });
};
let out: StepOutput;
let released = true;
try { out = locked(); } finally { if (held) released = !changedCheckouts.has(root) && held.release(); }
try { out = locked(); } finally {
if (held && changedCheckouts.has(root)) held.hold(`land.merged_checks changed this checkout's git directory while landing #${o.pr}`);
if (held) released = !changedCheckouts.has(root) && held.release();
}
if (changedCheckouts.has(root)) return { ...out, lines: [...out.lines, unlock] };
return released ? out : { ...out, lines: [...out.lines, `LOCK: warn the land lock release push failed, so the lock stays held; rerun gstack-ship-queue land --pr ${o.pr} --pin ${o.pin} to resume and release it`] };
}
+3 -1
View File
@@ -694,7 +694,9 @@ describe('capy skill: factory.md, the auto-loaded "how we work" page', () => {
// R105 and R109, each the owner's standing rule).
// 5,050 for point 7's two clauses that a green fake or dry run isn't done and that a check must see the change and count
// what its name says (the second batch of crew rules, G4 and G10, each reached by three crews on their own).
expect(Buffer.byteLength(text)).toBeLessThanOrEqual(5050);
// 5,300 for point 16's queue drain (R119, Garry's rule of 2026-11-22: every Captain that lands PRs runs a standing process
// that stops finished PRs piling up; the procedure is crew/docs/captain.md's Drain the queue).
expect(Buffer.byteLength(text)).toBeLessThanOrEqual(5300);
expect(text).toMatch(/^# How we work/);
expect(citationProblems(text)).toEqual([]);
});
+84
View File
@@ -0,0 +1,84 @@
/**
* gstack-ship-queue count (lib/ship-queue-count.ts, R119): the finished-PR count a Captain reads at every wake, from
* one gh call. Fixtures stand in for that call's GraphQL page.
*/
import { describe, expect, test } from 'bun:test';
import { COUNT_QUERY, queueCount } from '../lib/ship-queue-count';
import type { QueueContext } from '../lib/ship-queue';
const NOW = new Date('2026-11-22T16:00:00Z');
const hoursAgo = (h: number) => new Date(NOW.getTime() - h * 3_600_000).toISOString();
type Over = Partial<{ isDraft: boolean; mergeable: string; baseRefName: string; login: string | null; rollup: string | null; committed: string }>;
const pr = (number: number, hours: number, o: Over = {}) => ({
number, title: `Change ${number}`, isDraft: o.isDraft ?? false, mergeable: o.mergeable ?? 'MERGEABLE', baseRefName: o.baseRefName ?? 'main',
author: o.login === null ? null : { login: o.login ?? 'garrytan' },
commits: { nodes: [{ commit: { committedDate: o.committed ?? hoursAgo(hours), statusCheckRollup: o.rollup === null ? null : { state: o.rollup ?? 'SUCCESS' } } }] },
});
function run(nodes: unknown[], o: { totalCount?: number; authors?: string[]; fail?: string } = {}) {
const calls: string[][] = [];
const ctx: QueueContext = {
repoRoot: '/nonexistent', base: 'main',
gh: args => { calls.push(args); return o.fail ? { ok: false, out: '', err: o.fail } : { ok: true, out: JSON.stringify({ data: { repository: { pullRequests: { totalCount: o.totalCount ?? nodes.length, nodes } } } }), err: '' }; },
};
return { out: queueCount(ctx, { now: NOW, authors: o.authors }), calls };
}
describe('gstack-ship-queue count', () => {
test('makes exactly one gh call and counts only finished PRs: our authors, on the base, not draft, not conflicting, green at the head', () => {
const { out, calls } = run([
pr(1, 3),
pr(2, 5, { login: 'capy-ai' }),
pr(3, 1, { login: 'app/garrytan-agents' }),
pr(4, 2, { login: 'capy-ai[bot]', mergeable: 'UNKNOWN' }),
pr(10, 9, { isDraft: true }),
pr(11, 9, { mergeable: 'CONFLICTING' }),
pr(12, 9, { login: 'dependabot' }),
pr(13, 9, { login: null }),
pr(14, 9, { baseRefName: 'release' }),
pr(15, 9, { rollup: 'PENDING' }),
pr(16, 9, { rollup: 'FAILURE' }),
pr(17, 9, { rollup: null }),
]);
expect(calls).toEqual([['api', 'graphql', '-F', 'owner={owner}', '-F', 'name={repo}', '-f', `query=${COUNT_QUERY}`]]);
expect(out.ok).toBe(true);
expect(out.lines).toEqual([
'QUEUE_COUNT: finished=4 waited_24h=0 oldest=5h #2 open=12 base=main authors=garrytan,capy-ai,garrytan-agents',
'FINISHED: #2 5h Change 2',
'FINISHED: #1 3h Change 1',
'FINISHED: #4 2h Change 4',
'FINISHED: #3 1h Change 3',
]);
});
test('more than 6 finished PRs prints DRAIN; exactly 6, none a day old, does not', () => {
const six = [1, 2, 3, 4, 5, 6].map(n => pr(n, n));
expect(run(six).out.lines.some(l => l.startsWith('DRAIN:'))).toBe(false);
const seven = run([...six, pr(7, 7)]).out.lines;
expect(seven[0]).toBe('QUEUE_COUNT: finished=7 waited_24h=0 oldest=7h #7 open=7 base=main authors=garrytan,capy-ai,garrytan-agents');
expect(seven.at(-1)).toBe('DRAIN: 7 finished PRs are waiting (more than 6); start a drain this turn: land them, bundle them, or send each idle owner its next step (docs/captain.md#drain-the-queue)');
});
test('one PR waiting 24 hours since its last commit prints DRAIN on its own; 23 hours does not', () => {
expect(run([pr(1, 23.9)]).out.lines.some(l => l.startsWith('DRAIN:'))).toBe(false);
const lines = run([pr(1, 2), pr(4670, 31)]).out.lines;
expect(lines[0]).toBe('QUEUE_COUNT: finished=2 waited_24h=1 oldest=31h #4670 open=2 base=main authors=garrytan,capy-ai,garrytan-agents');
expect(lines.at(-1)).toMatch(/^DRAIN: 1 has waited 24h or more \(oldest #4670, 31h\); start a drain this turn/);
});
test('both bounds name both reasons; past 10 finished the list folds; over 100 open PRs says the count is partial', () => {
const many = Array.from({ length: 12 }, (_, i) => pr(i + 1, 30 + i));
const lines = run(many, { totalCount: 140 }).out.lines;
expect(lines[1]).toBe('QUEUE_COUNT_PARTIAL: counted the oldest 12 of 140 open PRs');
expect(lines.filter(l => l.startsWith('FINISHED: #'))).toHaveLength(10);
expect(lines).toContain('FINISHED: and 2 more');
expect(lines.at(-1)).toMatch(/^DRAIN: 12 finished PRs are waiting \(more than 6\) and 12 have waited 24h or more \(oldest #12, 41h\); /);
});
test('--authors replaces the default list, and a failed gh call refuses with the fix instead of printing a zero count', () => {
expect(run([pr(1, 2), pr(2, 2, { login: 'someone' })], { authors: ['someone'] }).out.lines[0]).toBe('QUEUE_COUNT: finished=1 waited_24h=0 oldest=2h #2 open=2 base=main authors=someone');
const failed = run([], { fail: 'HTTP 401: Bad credentials' }).out;
expect(failed.ok).toBe(false);
expect(failed.lines).toEqual([]);
expect(failed.failure).toMatchObject({ code: 'QUEUE_NOT_READY', message: 'gh could not list the open PRs: HTTP 401: Bad credentials' });
});
});
+19 -1
View File
@@ -21,7 +21,7 @@ import { bumpVersion } from '../crew/lib/version-gate-train';
import { openRelease } from '../lib/release-stamp';
import type { MergedRun } from '../lib/land-merged-checks';
import { bunIsolationArgs } from '../lib/bun-isolation';
import { readLock, writeLock } from '../crew/lib/ship-queue-land-lock';
import { readLock, thisProcess, writeLock, LAND_LOCK_REF } from '../crew/lib/ship-queue-land-lock';
import { flakyGit } from './helpers/flaky-git';
import { runBackstop } from '../crew/scripts/train-backstop';
import { readTrainNotes } from '../crew/scripts/release-cut';
@@ -551,6 +551,24 @@ describe('land --pin: direct merge at the PR\'s own green head', () => {
expect(dry.out).toContain('DRY-RUN: nothing verified');
}, 120_000);
test.skipIf(process.platform !== 'linux')('the land lock: another PR\'s lock whose land process has exited is taken over without --break-lock, logged, and the land merges; the lock it writes names its process and expiry', () => {
const fx = setup();
const self = thisProcess()!;
const exited = spawnSync('setsid', ['sh', '-c', 'cat /proc/$$/stat'], { encoding: 'utf8', timeout: 10_000 });
const f = exited.stdout.slice(exited.stdout.lastIndexOf(')') + 2).split(' ');
const pid = Number(exited.stdout.split(' ')[0]);
const at = new Date().toISOString();
expect(writeLock(fx.repo.work, readLock(fx.repo.work).sha, { pr: '90', holder: `gone:${pid}`, started_at: at, phase_at: at, phase: 'merging', journal: 'land-pin:' + '1'.repeat(40), proc: { ...self, pid, pgid: Number(f[2]), start: Number(f[19]), mark: 'gone' } }).ok).toBe(true);
const pin = openPr(fx, '89');
const r = land(fx, '89', pin);
expect(r.status, r.err).toBe(EXIT.ok);
expect(r.out).toContain(`LOCK_TAKEOVER: #90's land lock (holder gone:${pid}, phase merging, since ${at}): its land (process ${pid}) and every process it started have exited`);
expect(fx.read().prs['89'].state).toBe('MERGED');
expect(readLock(fx.repo.work).state).toBe('released');
const took = fx.repo.git('log', '--format=%H %s', LAND_LOCK_REF).split('\n').find(l => l.includes('(took over #90'))!.split(' ')[0]!;
expect(JSON.parse(fx.repo.git('show', `${took}:lock.json`))).toMatchObject({ pr: '89', proc: { boot: self.boot }, took_over: { pr: '90', holder: `gone:${pid}` }, expires_at: expect.any(String) });
}, 120_000);
describe('GST-1344: a lock push GitHub applied but answered with an HTTP 502', () => {
const lockAt = (fx: Fx) => JSON.parse(fx.repo.git('--git-dir', fx.repo.origin, 'show', 'refs/notes/gstack-land:lock.json'));
const flaky = (fx: Fx) => { const g = flakyGit(fx.repo.root); return { g, run: (pr: string, pin: string, extra: string[] = []) => runBin(fx.repo, 'gstack-ship-queue', ['land', '--pr', pr, '--pin', pin, '--base', 'main', ...extra], { ...fx.env, ...g.env, PATH: `${g.dir}:${fx.env.PATH}` }) }; };