diff --git a/.abcd/development/brief/04-surfaces/35-drain.md b/.abcd/development/brief/04-surfaces/35-drain.md index c760ba9cf9..6c5517705f 100644 --- a/.abcd/development/brief/04-surfaces/35-drain.md +++ b/.abcd/development/brief/04-surfaces/35-drain.md @@ -666,7 +666,28 @@ merge would not), any value of the default branch's `mergeOptions` in any of the drive cannot read one as git does; `merge.verifySignatures` stays git's to apply), and a lane in progress in any run of the checkout (one parked on its pull request, handed back, held or discarded aside) each decline it with nothing run, and a refusal git makes in the gap is declined the same way; a declined fast-forward is one -line, said once while its reason stands, and never ends the start. A fast-forward that +line, said once while its reason stands, and never ends the start. A run's lane in +progress declines it only while the run is held (`ffabandoned.go`, iss-2612022203551074): +its control record names a driver, or a process that recorded an agent's launch, that +the process table reads as alive (a table or a control record that cannot be read +counts as held), or the run last moved (its state's date, its driver's claim, a launch, +its stop) within `lease.Max`, a day, the longest lease a run's reservation takes, since +the state does not record the term its own took. A run held by none of those is let go +only where the checkout is behind the tip and the rest of the judgement found nothing in +the way, immediately before the merge and after the comparison of what the drive holds: +a start declined for any other reason lets nothing go. It is said on one line naming the +run, why, and the discard of each of its lanes in progress that ends it for good; its +worktree, branch and lane are left as they are. Of each hold the run records, only one +this copy's view reads as this copy's, inside its lease and claimed or renewed no later +than the run last moved is released, fenced on the commit the view showed; a hold past +its lease pushes nothing ("its hold had lapsed"), which for a run idle a day is every +hold of its own, and one claimed or renewed after the run last moved is left standing. +A release is written to the run's record as a plain release, and the let-go as its own +mark (`ff_let_go`), both with the run's date left alone, so no later start takes the run +up, the run still reads as idle, and a later start names it no more, counting such runs +on one line. Each run that holds it is named on a line of its own with the act that +frees it, and the hooks' refusal names the same in its remedy in place of a bare +"settle that". A fast-forward that moved says so on one line, and the drive reads its hold again and proves the checkout's in-tree hooks against the same answer, so a pull request merged between two asks cannot refuse a start that has just caught up. Where the fast-forward was declined and the diff --git a/.abcd/work/decisions/dcn-2612022239100187-a-drive-s-start-reads-a-run-with-a-lane.md b/.abcd/work/decisions/dcn-2612022239100187-a-drive-s-start-reads-a-run-with-a-lane.md new file mode 100644 index 0000000000..f734ceed07 --- /dev/null +++ b/.abcd/work/decisions/dcn-2612022239100187-a-drive-s-start-reads-a-run-with-a-lane.md @@ -0,0 +1,6 @@ +--- +id: dcn-2612022239100187 +slug: a-drive-s-start-reads-a-run-with-a-lane +date: 2026-12-02 +--- +2026-12-02 — A drive's start reads a run with a lane in progress as abandoned for its fast-forward when no driver or agent launch its control record names is alive and the run has not moved within lease.Max, a day: the state does not record the term its own reservation took, so the longest lease a run can hold bounds it, and movement is the latest of the state's date, the driver's claim, a launch and the stop's dates (iss-2612022203551074). diff --git a/.abcd/work/decisions/dcn-2612022239193741-an-abandoned-run-the-start-lets-go-for.md b/.abcd/work/decisions/dcn-2612022239193741-an-abandoned-run-the-start-lets-go-for.md new file mode 100644 index 0000000000..d95a52d893 --- /dev/null +++ b/.abcd/work/decisions/dcn-2612022239193741-an-abandoned-run-the-start-lets-go-for.md @@ -0,0 +1,6 @@ +--- +id: dcn-2612022239193741 +slug: an-abandoned-run-the-start-lets-go-for +date: 2026-12-02 +--- +2026-12-02 — An abandoned run the start lets go for its fast-forward has any reservation it still records released through the drive's own release path (releaseHolds, shared with releaseRun), but written to its record as a plain release with its date left alone, not as the drive's let-go: a drive_released line would make a later start take a month-old run up and step it, and a new date would make it read as moved within its lease (iss-2612022203551074). diff --git a/.abcd/work/decisions/dcn-2612022239209278-a-run-a-process-table-that-cannot-be.md b/.abcd/work/decisions/dcn-2612022239209278-a-run-a-process-table-that-cannot-be.md new file mode 100644 index 0000000000..4ee07d98f5 --- /dev/null +++ b/.abcd/work/decisions/dcn-2612022239209278-a-run-a-process-table-that-cannot-be.md @@ -0,0 +1,6 @@ +--- +id: dcn-2612022239209278 +slug: a-run-a-process-table-that-cannot-be +date: 2026-12-02 +--- +2026-12-02 — A run a process table that cannot be read leaves unjudged holds the drive's fast-forward back, as a run whose control record cannot be read does: a checkout moved under a live session costs more than one left behind for a start; and each run that holds it is said on a line of its own with the act that frees it, which the hooks' refusal carries in place of a bare settle that (iss-2612022203551074). diff --git a/.abcd/work/decisions/dcn-2612030123330618-a-drive-start-lets-a-run-go-for-its.md b/.abcd/work/decisions/dcn-2612030123330618-a-drive-start-lets-a-run-go-for-its.md new file mode 100644 index 0000000000..9ae48f0326 --- /dev/null +++ b/.abcd/work/decisions/dcn-2612030123330618-a-drive-start-lets-a-run-go-for-its.md @@ -0,0 +1,6 @@ +--- +id: dcn-2612030123330618 +slug: a-drive-start-lets-a-run-go-for-its +date: 2026-12-03 +--- +2026-12-03 — A drive start lets a run go for its fast-forward only once the rest of the judgement found nothing in the way and the comparison of what the drive holds has passed, immediately before the merge, so a start declined for another reason lets nothing go; a control record that cannot be read, the checkout not opened included, holds the fast-forward rather than reading as no driver (iss-2612022203551074). diff --git a/.abcd/work/decisions/dcn-2612030123330721-refining-dcn-2612022239193741-a-drive.md b/.abcd/work/decisions/dcn-2612030123330721-refining-dcn-2612022239193741-a-drive.md new file mode 100644 index 0000000000..cbad775724 --- /dev/null +++ b/.abcd/work/decisions/dcn-2612030123330721-refining-dcn-2612022239193741-a-drive.md @@ -0,0 +1,6 @@ +--- +id: dcn-2612030123330721 +slug: refining-dcn-2612022239193741-a-drive +date: 2026-12-03 +--- +2026-12-03 — Refining dcn-2612022239193741: a drive start's let-go for its fast-forward pushes nothing for a hold past its lease, which blocks no one and for a run idle a day is every hold of its own, and leaves standing a hold claimed or renewed after the run last moved; only a hold this copy's view reads as this copy's, inside its lease and claimed no later than the run's last movement is released, fenced on the commit the view showed (iss-2612022203551074). diff --git a/.abcd/work/decisions/dcn-2612030123345605-a-run-a-drive-start-let-go-for-its.md b/.abcd/work/decisions/dcn-2612030123345605-a-run-a-drive-start-let-go-for-its.md new file mode 100644 index 0000000000..5ac0f989da --- /dev/null +++ b/.abcd/work/decisions/dcn-2612030123345605-a-run-a-drive-start-let-go-for-its.md @@ -0,0 +1,6 @@ +--- +id: dcn-2612030123345605 +slug: a-run-a-drive-start-let-go-for-its +date: 2026-12-03 +--- +2026-12-03 — A run a drive start let go for its fast-forward carries an ff_let_go mark in its record, written with its date left alone, so a later start names it no more and counts such runs on one line; the first line names `abcd implement step --run --discard ` for each lane in progress as the act that ends the run for good, since the sweep keeps the worktrees of a run not complete (iss-2612022203551074). diff --git a/.abcd/work/decisions/dcn-2612031056281133-a-drive-s-fast-forward-that-lets-a-run.md b/.abcd/work/decisions/dcn-2612031056281133-a-drive-s-fast-forward-that-lets-a-run.md new file mode 100644 index 0000000000..7432c55284 --- /dev/null +++ b/.abcd/work/decisions/dcn-2612031056281133-a-drive-s-fast-forward-that-lets-a-run.md @@ -0,0 +1,6 @@ +--- +id: dcn-2612031056281133 +slug: a-drive-s-fast-forward-that-lets-a-run +date: 2026-12-03 +--- +2026-12-03 — A drive's fast-forward that lets a run go, at its start or between lanes, frees the checkout from that run and decides nothing about whether the run is worked again, which turns on whose the run is: a run the drain lists is the drive's own work and is taken up again as its lane comes to hand, reserved again with a live driver; a run a stop's mark stands on is taken over by a drive's start once the person's stop is lifted, as the stop's rule says; any other run stays let go, taken up by no drive and renewed, logged on or re-dated by nothing, until a person steps it or takes it over. Grounds: the let-go judges only that nothing holds the checkout back; whether the work goes on is the drain's call for its own lanes and the person's for the rest, and a lifted stop is the person's recorded request to resume. The let-go mark is saved before any hold is left to lapse, and a mark that cannot be saved leaves every hold as it was. Reverse: gate takeEarlier and the drain's take-up on the let-go mark for every run (iss-2612022203551074). diff --git a/.abcd/work/issues/open/iss-2612022151029279-dependency-bumps-cannot-merge-on-their.md b/.abcd/work/issues/open/iss-2612022151029279-dependency-bumps-cannot-merge-on-their.md new file mode 100644 index 0000000000..f800303cea --- /dev/null +++ b/.abcd/work/issues/open/iss-2612022151029279-dependency-bumps-cannot-merge-on-their.md @@ -0,0 +1,15 @@ +--- +schema_version: 1 +id: "iss-2612022151029279" +slug: "dependency-bumps-cannot-merge-on-their" +severity: "minor" +category: "observation" +source: "user-observation" +found_during: "manual-capture" +origin: researcher-authored +production_mode: hand-written +found_at: ".github/workflows/dependency-reauthor.yml" +remedy: "list the unset re-author App and its two secrets as a gap in abcd ahoy, with the exact creation steps, and post the workflow's refusal reason as one comment on the bump's pull request" +--- + +Dependency bumps cannot merge on their own: the attribution gate refuses a bot author, and the re-author workflow refuses every bump because the GitHub App it signs with was never created and its two Dependabot secrets (DEPENDENCY_REAUTHOR_APP_ID, DEPENDENCY_REAUTHOR_APP_KEY) are unset. Nothing told the person: three bumps sat for two days failing two checks, and the person asked for them to be auto-merged without knowing a setup step of theirs was missing. The fix is to name the missing App as a gap where the person looks (abcd ahoy and the update news offer), with the steps to create it and set both secrets, and to have the workflow's refusal say the same on the pull request. diff --git a/.abcd/work/issues/open/iss-2612022153543895-a-bare-abcd-drain-prints-one-ledger-line.md b/.abcd/work/issues/open/iss-2612022153543895-a-bare-abcd-drain-prints-one-ledger-line.md new file mode 100644 index 0000000000..4ae2773708 --- /dev/null +++ b/.abcd/work/issues/open/iss-2612022153543895-a-bare-abcd-drain-prints-one-ledger-line.md @@ -0,0 +1,15 @@ +--- +schema_version: 1 +id: "iss-2612022153543895" +slug: "a-bare-abcd-drain-prints-one-ledger-line" +severity: "minor" +category: "ux" +source: "user-observation" +found_during: "manual-capture" +origin: researcher-authored +production_mode: hand-written +found_at: "internal/surface/cli/drain.go" +remedy: "while the bare drain reads its state, show one line with a moving indicator, such as 'Assessing the current state…' with a spinner, on a terminal only (a plain line once when output is not a terminal, nothing under --json); once the state is shown, say that the bare form starts nothing and name abcd drain --drive; then find and remove the thirty seconds of system time from the status path" +--- + +A bare abcd drain prints one ledger line and then nothing for about thirty seconds (8 s user, 23 s system on this machine, v0.18.0) before it shows the drain's state, so the person took it for a hang and stopped it with two Ctrl-C. The bare form only reports state and starts nothing, which the screen does not say either. The wait has no line saying what it is doing, and the time itself (mostly system time) suggests a walk or a repeated git read that a status view should not need. diff --git a/.abcd/work/issues/open/iss-2612022156157064-the-embargo-publish-plan-is-a-plain-dump.md b/.abcd/work/issues/open/iss-2612022156157064-the-embargo-publish-plan-is-a-plain-dump.md new file mode 100644 index 0000000000..6b2eabc0b6 --- /dev/null +++ b/.abcd/work/issues/open/iss-2612022156157064-the-embargo-publish-plan-is-a-plain-dump.md @@ -0,0 +1,15 @@ +--- +schema_version: 1 +id: "iss-2612022156157064" +slug: "the-embargo-publish-plan-is-a-plain-dump" +severity: "minor" +category: "ux" +source: "user-observation" +found_during: "manual-capture" +origin: researcher-authored +production_mode: hand-written +found_at: "internal/surface/cli/embargo.go" +remedy: "render embargo publish as a summary block (to publish, held back by reason, next step), group the left-out advisories under one heading per reason with the action stated once, colour the groups only on a colour-capable terminal honouring NO_COLOR, and set the approve command apart on its own line; leave --json unchanged" +--- + +The embargo publish plan is a plain dump the person found hard to read: twenty lines of the same shape, each advisory carrying its id, record id, a twelve-character fix sha, a parenthetical about the store and an affected-range line, with the advisories that will be published and the ones left out in one undifferentiated list, the reasons for leaving one out repeated in full on every line, and the approve command buried at the end after a 64-character digest. A person deciding whether to publish needs a summary first: how many go public, how many are held back and why, grouped by reason (not yet fixed; description names another embargoed advisory, with which one and what to do), then the approve command, set apart. Colour should mark the three groups on a terminal, with the plain text unchanged when output is not a terminal or NO_COLOR is set. diff --git a/.abcd/work/issues/resolved/iss-2612022203551074-a-drive-cannot-start-in-a-main-checkout.md b/.abcd/work/issues/resolved/iss-2612022203551074-a-drive-cannot-start-in-a-main-checkout.md new file mode 100644 index 0000000000..ad9c07e59e --- /dev/null +++ b/.abcd/work/issues/resolved/iss-2612022203551074-a-drive-cannot-start-in-a-main-checkout.md @@ -0,0 +1,19 @@ +--- +schema_version: 1 +id: "iss-2612022203551074" +slug: "a-drive-cannot-start-in-a-main-checkout" +severity: "major" +category: "bug" +source: "user-observation" +found_during: "manual-capture" +origin: researcher-authored +production_mode: hand-written +found_at: "internal/core/implement/loop" +remedy: "treat a run with no live driver and no heartbeat within its lease as abandoned for the fast-forward check (say so and let it go, as the drive's start already lets go a run no drain lists), name the command that frees each run that really is held, and add the two-case start test described here to the drive's start tests" +resolution: "A drive's start lets go, for its fast-forward, a run with no live driver or agent that has not moved within a day, saying so on one line and releasing any reservation it still records, and names, for each run that still holds the fast-forward, the act that frees it" +impact: fix +resolved_by: + commit: "61800576c" +--- + +A drive cannot start in a main checkout that is behind origin and holds old run state, and nothing in its refusal says how to get past it. On 2 December (v0.18.0) the person typed abcd drain --drive in the main checkout, which was 1130 commits behind origin/main. The drive rightly refused to run with hooks that differ from origin's tip, but it also declined to fast-forward because it counted eight runs as having a lane in progress. Those runs date from 23 October to 21 November, no driver has touched them for weeks, and the drain's own state lists every lane as done or handed back. The remedy says to settle that and names no command, so the person is stuck: the only route is a hand pull, after which the drive may try to take up the month-old runs. Test that would have caught it: a drive start in a fixture checkout behind its origin with a stale run state (a lane marked in progress, no live driver, last heartbeat days old, worktree clean) must either let the dead run go with a stated reason and fast-forward, or refuse naming the exact command that frees each run; a second case with a live driver must still hold off the fast-forward. diff --git a/commands/drain.md b/commands/drain.md index d85d9f9574..9a07144b14 100644 --- a/commands/drain.md +++ b/commands/drain.md @@ -122,10 +122,52 @@ of this checkout (one parked on its pull request, handed back, held or discarded aside) each decline it, with nothing in the checkout changed and one line, said once while the reason stands: "this checkout is `` commits behind origin/`` and was not -fast-forwarded: ``". A declined fast-forward does not stop the start, +fast-forwarded: ``". A run whose lane is in progress holds the +fast-forward back only while something holds the run: a live driver, a +live process that recorded one of its agents' launches, or a movement of its +state within a day, the longest lease a run's reservation takes. In a +checkout behind the tip, once nothing else declines the fast-forward, a run +with none of those, a drive killed weeks ago among them, is let go for it, +on one line naming the run and why ("``, run ``, has no live +driver and has not moved since ``, ... so the fast-forward lets it +go"). The line names the act that ends the run for good, `abcd implement +step --run --discard ` for each lane in progress, and says what +became of each reservation the run records: a hold idle that long has +lapsed and blocks no one ("its hold had lapsed"), so nothing is pushed, +and this copy leaves it to lapse; a hold claimed or renewed after the run +last moved, a hand reservation or the run stepped again, is left standing; +only a hold of this copy's still inside its lease and older than the run's +last movement is released; a hold is left to lapse only once the run's +record marks the let-go, and where that mark cannot be written the line +says so, nothing is left to lapse, and only a release already made stands. +The let-go frees the checkout and decides nothing more: the line ends by +saying what becomes of the run, which turns on whose it is, and promises a +take-up only where a drive takes the run up. Where the drain's state +cannot be read, the line says this drive takes nothing up. A drain that +has ended, an outage or a cap having stopped it, hands nothing out, so a +lane it still lists counts as unlisted. A run whose +lane the drain has in progress and that carries no stop's mark is the +drive's own work: the drive takes it up again as the lane comes to hand, +reserving it again, or, where the drive passed the lane over, the next +drive does. An issue's run a stop's mark stands on, whose lane the drain +has in progress or halted or does not list, is taken over by a drive as +soon as no stop of the person's holds over it, as below, whether or not +this drive passed it over. Any other run, a lane the drain lists as taken +over or handed back, a halted lane with no mark and an intent's build +among them, stays let go: until a person steps it (`abcd implement step +--run `) or takes it over (`abcd implement resume --take `), no +drive takes it up, and no renewal in this copy, a drive's, an `abcd implement status` +call's or a load-gate waiter's, revives a hold of it, logs on it or dates +it as moved, whoever holds its issue now. The run's worktree, branch and +lane are left as they are, and a later drive, at its start or between +lanes, names a run already let go no more, counting such runs on one +line. A run that does hold it is named on a +line of its own with the act that frees it: the driver ending, that process +ending, or the time after which a drive lets it go. A declined fast-forward does not stop the start, except where the checkout's in-tree hooks then differ from the tip's: the start refuses as before, its remedy naming what blocked the fast-forward -before `git pull --ff-only`. The fast-forward reads and runs with your own +before `git pull --ff-only`, and, for each run that holds it, that run and +the act that frees it. The fast-forward reads and runs with your own git configuration, as your own pull does: your home, your global and system files and the repository's, not the narrowed set the drive gives its lanes. The merge runs with the repository's hooks off, so no `post-merge` hook runs, @@ -146,7 +188,9 @@ asks `origin` for its default branch's tip again and fast-forwards this checkout to it under the same rules and with the same lines, whether or not it looks for a new release there, and before it does. A lane in progress in any run of the checkout (one set aside, one passed over, another session's) -declines it. A tip this repository does not hold yet is fetched first; a lost +declines it while something holds its run, judged as at the start: a run +nothing holds is let go there as at the start, on the same line, and one +the drive let go already is named no more. A tip this repository does not hold yet is fetched first; a lost network makes no fast-forward and says nothing, and the next boundary asks again. A declined fast-forward never ends the drive and never holds a lane. After a @@ -549,7 +593,7 @@ The person's own `abcd implement stop` ends a drive too, at its next move, and a within about a minute, a wait on a limit or an outage included. The drive then says what holds it. A preflight queued at the load gate or running ends at the next look too, and a probe does not start. While that stop stands, a new drive names the run it halted and ends, saying what -holds it; once the person lifts the stop, a drive's next start takes the run over where it may, reserving it again, with no take-over typed. A take-over made from a plain terminal records as the run's driver the nearest process above it that is not a shell or abcd; a terminal multiplexer, or a terminal program shared by several windows, is that one process for all of its panes and windows. A drive whose own nearest such process is the recorded driver takes the run from it, with a line in the run's record saying so, only when the recorded driver names no session, no process on the way up from the drive holds a session marker, every session marker could be read, and only shells run beneath that process besides the drive, the processes the drive runs under and the ones it started. Otherwise it does not take the run. Where another process runs beneath the recorded driver, a session marker could not be read, or the process table could not be read, it says which, naming the process or the number of files, with the act that frees the run; in every other case it gives the plain reason that the run is driven by that process. A lane it has in hand waits on that driver and looks again later, and once it has waited as long as `pace.stuck_minutes` it is set aside while the drive goes on with its other lanes. A run a stop's mark stands on, or one a drive's end let go that no drain lists, is judged by the same rule at the drive's start or as its lane comes to hand, and one it may not take is named, with the act worded for a drive's next start, and passed over; a later start judges it again. A drive whose output is piped to another program, or a long-lived helper under the same terminal, is such another process and keeps the run from the drive while it runs. A drive started through a program that stays as its parent, such as one that keeps the machine awake or a recorder, is not under the terminal by this rule and does not take the run. The rule cannot tell a terminal from a host that left no marker and has no other process beneath it: an agent a host runs inside its own process is not in the process table. Nor does it see a step whose shell ended after it claimed, which the process table no longer shows beneath the terminal. A lane parked on its pull request that a signal halted is taken over at a drive's start the same way, and the drive's end names `abcd drain --drive` for it. A stop and a drive's stop on a run whose state changed are two things: while both +holds it; once the person lifts the stop, a drive's next start takes the run over where it may, reserving it again, with no take-over typed. A take-over made from a plain terminal records as the run's driver the nearest process above it that is not a shell or abcd; a terminal multiplexer, or a terminal program shared by several windows, is that one process for all of its panes and windows. A drive whose own nearest such process is the recorded driver takes the run from it, with a line in the run's record saying so, only when the recorded driver names no session, no process on the way up from the drive holds a session marker, every session marker could be read, and only shells run beneath that process besides the drive, the processes the drive runs under and the ones it started. Otherwise it does not take the run. Where another process runs beneath the recorded driver, a session marker could not be read, or the process table could not be read, it says which, naming the process or the number of files, with the act that frees the run; in every other case it gives the plain reason that the run is driven by that process. A lane it has in hand waits on that driver and looks again later, and once it has waited as long as `pace.stuck_minutes` it is set aside while the drive goes on with its other lanes. A run a stop's mark stands on, or one a drive's end let go that no drain lists and no drive's fast-forward has let go since, is judged by the same rule at the drive's start or as its lane comes to hand, and one it may not take is named, with the act worded for a drive's next start, and passed over; a later start judges it again. A drive whose output is piped to another program, or a long-lived helper under the same terminal, is such another process and keeps the run from the drive while it runs. A drive started through a program that stays as its parent, such as one that keeps the machine awake or a recorder, is not under the terminal by this rule and does not take the run. The rule cannot tell a terminal from a host that left no marker and has no other process beneath it: an agent a host runs inside its own process is not in the process table. Nor does it see a step whose shell ended after it claimed, which the process table no longer shows beneath the terminal. A lane parked on its pull request that a signal halted is taken over at a drive's start the same way, and the drive's end names `abcd drain --drive` for it. A stop and a drive's stop on a run whose state changed are two things: while both stand the run is not settled, its work is not saved aside and its reservation lapses with its lease unless a load-gate waiter in this copy renews it. Lifting the stop leaves the other, and removing the other leaves the stop. diff --git a/internal/core/implement/loop/checkoutff.go b/internal/core/implement/loop/checkoutff.go index 387ad20de8..8daf793eb8 100644 --- a/internal/core/implement/loop/checkoutff.go +++ b/internal/core/implement/loop/checkoutff.go @@ -1056,19 +1056,20 @@ func ffWords(root, s string) string { return s } -// ffLanesInProgress names the run of each lane in progress in the checkout, -// read from the runs' state on disk (Runs), for judgeCheckoutFF: a lane at a -// stage with a body (worktree to land) in any run, one the drive set aside or -// passed over, or another session's, included. A lane parked on its pull -// request (parkedAtLand) does not count, nor does a run a newer run of its -// issue followed (superseded), nor a lane handed back, held or discarded, -// which runs nothing until a person acts. -func ffLanesInProgress(repoRoot string) ([]string, error) { +// ffRunsInProgress is the run of each lane in progress in the checkout, read +// whole from the runs' state on disk (Runs), for judgeFFRuns to judge which of +// them hold a drive's fast-forward back: a lane at a stage with a body +// (worktree to land) in any run, one the drive set aside or passed over, or +// another session's, included. A lane parked on its pull request +// (parkedAtLand) does not count, nor does a run a newer run of its issue +// followed (superseded), nor a lane handed back, held or discarded, which +// runs nothing until a person acts. +func ffRunsInProgress(repoRoot string) ([]State, error) { runs, err := Runs(repoRoot) if err != nil { return nil, err } - var out []string + var out []State for i, run := range runs { if superseded(runs, i) || parkedAtLand(run) >= 0 { continue @@ -1080,7 +1081,7 @@ func ffLanesInProgress(repoRoot string) ([]string, error) { } return false }) { - out = append(out, run.RunID) + out = append(out, run) } } return out, nil diff --git a/internal/core/implement/loop/checkoutff_lanes_test.go b/internal/core/implement/loop/checkoutff_lanes_test.go index f4152c7ac7..52c132ecea 100644 --- a/internal/core/implement/loop/checkoutff_lanes_test.go +++ b/internal/core/implement/loop/checkoutff_lanes_test.go @@ -1,7 +1,7 @@ package loop // checkoutff_lanes_test.go holds which lanes, read from the runs' state on -// disk, decline a drive's fast-forward of its checkout (ffLanesInProgress; +// disk, decline a drive's fast-forward of its checkout (ffRunsInProgress; // dcn-2611282233438843). import ( @@ -80,10 +80,14 @@ func TestTheLanesInProgressAreTheOnesThatRunSomething(t *testing.T) { } ids = append(ids, st.RunID) } - got, err := ffLanesInProgress(repo.Root()) + runs, err := ffRunsInProgress(repo.Root()) if err != nil { t.Fatal(err) } + var got []string + for _, run := range runs { + got = append(got, run.RunID) + } if tc.named && !slices.Equal(got, ids[:1]) { t.Fatalf("the lane names its run %s: %q", ids[0], got) } diff --git a/internal/core/implement/loop/drain_lease.go b/internal/core/implement/loop/drain_lease.go index 4a65bc7592..5e1615a9b9 100644 --- a/internal/core/implement/loop/drain_lease.go +++ b/internal/core/implement/loop/drain_lease.go @@ -137,10 +137,11 @@ func renewParkedDue(repoRoot string, now time.Time, passed []string) []string { // renewable reports whether the drain's move renews run's reservation: it // holds one, the lead's or, in a run with members, any member's (holdsAny), -// and its lane is in progress and not parked at land. +// and its lane is in progress and not parked at land, and no drive has let it +// go for its fast-forward with nothing moving it since (ffLetGoStands). func renewable(run State) bool { outcome, _, _ := laneOutcome(run) - return run.holdsAny() && outcome == DrainLaneInProgress && parkedAtLand(run) < 0 + return run.holdsAny() && outcome == DrainLaneInProgress && parkedAtLand(run) < 0 && !ffLetGoStands(run) } // parkedDue reports whether a parked run's reservation is due for a renewal, diff --git a/internal/core/implement/loop/ffabandoned.go b/internal/core/implement/loop/ffabandoned.go new file mode 100644 index 0000000000..716fc03b7d --- /dev/null +++ b/internal/core/implement/loop/ffabandoned.go @@ -0,0 +1,234 @@ +package loop + +// ffabandoned.go is which runs with a lane in progress hold a drive's +// fast-forward of its checkout back (iss-2612022203551074). A lane in +// progress declines the fast-forward (ffRunsInProgress), but a run whose +// driver is gone and whose state has not moved within the longest lease a run +// can take is no one's work: the reservation system already reads a hold idle +// that long as lapsed, so such a run is let go for the fast-forward, said on +// one line naming it and why, and only the runs something still holds keep +// the checkout where it is, each named with the act that frees it. Letting a +// run go here touches no worktree, branch or lane of it: the sweep keeps the +// worktrees of a run not complete, so the line names the discard of each of +// its lanes in progress, which ends it for good (ffEndsFor). + +import ( + "fmt" + "os" + "strings" + "time" + + "github.com/intentdriven/abcd/internal/core/claim" + + "github.com/intentdriven/abcd/internal/core/lease" + "github.com/intentdriven/abcd/internal/core/sessionname" + "github.com/intentdriven/abcd/internal/fsutil" + "github.com/intentdriven/abcd/internal/gitutil" + "github.com/intentdriven/abcd/internal/termsafe" +) + +// ffRunLease is how long a run may stand still, with no live driver, and +// still hold the fast-forward back: lease.Max, the longest lease a run's +// reservation takes (the land fence's), since the run's state does not +// record the term its own reservation took, and a run still within any +// lease it could hold is read as held. +const ffRunLease = lease.Max + +// ffRun is one run with a lane in progress, judged for the fast-forward: +// gone where it is let go, and why, the reason it is let go or, for a run +// that holds the fast-forward back, what holds it and the act that frees it. +// moved is when a run let go last moved (ffLastMoved), which bounds the holds +// its let-go may release (ffHoldFor). +type ffRun struct { + run State + gone bool + why string + moved time.Time + // stop is whether a stop's mark stands on a run let go, which a drive + // takes over, for an issue's run it still hands out, as soon as no stop + // of the person's holds over it (ffWhoseNext). + stop bool +} + +// judgeFFRuns judges each of runs, all with a lane in progress, as of now. +// The process table is read once, and only where a run names a driver or an +// agent's launch. +func judgeFFRuns(repoRoot string, runs []State, now time.Time) []ffRun { + var ( + tab sessionname.Table + tabErr error + read bool + ) + procs := func() (sessionname.Table, error) { + if !read { + tab, tabErr = readProcs() + read = true + } + return tab, tabErr + } + out := make([]ffRun, 0, len(runs)) + for _, run := range runs { + out = append(out, judgeFFRun(repoRoot, run, now, procs)) + } + return out +} + +// judgeFFRun judges run: held while its control record cannot be read, while +// the driver it names, or the process that recorded an agent's launch, is +// alive or cannot be judged +// because the process table cannot be read, and while it last moved within +// ffRunLease of now (a movement dated ahead of now included); let go +// otherwise. +func judgeFFRun(repoRoot string, run State, now time.Time, procs func() (sessionname.Table, error)) ffRun { + id := termsafe.Sanitize(run.RunID) + held := func(format string, a ...any) ffRun { + return ffRun{run: run, why: termsafe.Sanitize(fsutil.RedactHome(fmt.Sprintf(format, a...)))} + } + c, err := ffControl(repoRoot, run.RunID) + if err != nil { + return held("run %s: its control record cannot be read, so whether a driver holds it cannot be told (%s); `abcd implement status --run %s` names what is wrong with it", id, refusalReason(err), id) + } + if c.Driver != nil || len(c.Launches) > 0 { + tab, err := procs() + if err != nil { + return held("run %s: the process table cannot be read, so whether its driver or an agent of it lives cannot be told; start the drive again once it can be read", id) + } + if d := c.Driver; d != nil && tab.Alive(d.host()) { + return held("run %s is driven by %s, alive since it took the run at %s: the fast-forward waits until that driver ends, and once that driver ends a drive lets the run go if it has not moved within a day", + id, driverName(*d), stamp(d.At)) + } + for _, l := range c.Launches { + if l.PID != 0 && tab.Alive(l.host()) { + return held("run %s: the process that recorded an agent's launch at %s, process %d, is alive: the fast-forward waits until that process ends", id, stamp(l.At), l.PID) + } + } + } + moved := ffLastMoved(run, c) + if now.Sub(moved) < ffRunLease { + return held("run %s has no live driver but last moved at %s, within the day a run's lease can hold: a drive lets it go once %s passes with no movement, or its driver steps it on to its pull request (`abcd implement step --run %s`)", + id, stamp(moved), stamp(moved.Add(ffRunLease)), id) + } + return ffRun{run: run, gone: true, moved: moved, stop: c.Stop != nil, why: termsafe.Sanitize(fmt.Sprintf("%s, run %s, has no live driver and has not moved since %s, past the day a run's lease can hold, so the fast-forward lets it go; its worktree, branch and lane are left as they are, and %s ends it for good", + run.Key, id, stamp(moved), ffEndsFor(run)))} +} + +// ffEndsFor is the act that ends run for good: the discard of each of its +// lanes in progress (`abcd implement step --run --discard `, which +// removes the lane's worktree and branch), the commands joined with "then". A +// lane id read from the state file is put in a command only when it is one +// the loop gives (ValidLaneID); any other is said plainly, with no command. +func ffEndsFor(run State) string { + var acts []string + odd := 0 + for _, l := range run.Lanes { + switch l.Stage { + case StageWorktree, StageBrief, StageImplement, StageValidate, StageLand: + if !ValidLaneID(l.ID) { + odd++ + continue + } + acts = append(acts, "`abcd implement step --run "+run.RunID+" --discard "+l.ID+"`") + } + } + if odd > 0 { + acts = append(acts, fmt.Sprintf("a look at the state by hand for %d %s whose id is not one the loop gives, so no command is named for %s", + odd, plural(odd, "lane", "lanes"), plural(odd, "it", "them"))) + } + return strings.Join(acts, " then ") +} + +// ffLastMoved is when run last moved: the latest of its state's own date, its +// driver's claim, each agent's launch and its stop's dates. +func ffLastMoved(run State, c control) time.Time { + moved := run.UpdatedAt + later := func(t time.Time) { + if t.After(moved) { + moved = t + } + } + if c.Driver != nil { + later(c.Driver.At) + } + for _, l := range c.Launches { + later(l.At) + } + if s := c.Stop; s != nil { + later(s.SetAt) + later(s.NotedAt) + if s.HaltedAt != nil { + later(*s.HaltedAt) + } + } + return moved +} + +// ffHold is what declined the start's fast-forward, for the hooks' refusal to +// name before the pull (behindRemedy): clause, "" where nothing declined it, +// and, where runs held it, the act that frees each (judgeFFRun). +type ffHold struct { + clause string + frees []string +} + +// ffMayBeBehind reports whether the checkout at root may be behind tip, so the +// runs are judged (and any let go) only for a fast-forward that may be made: +// false only where HEAD reads cleanly as tip or as a commit holding it, and +// true on any read that fails, which judgeCheckoutFF then reads for itself. +func ffMayBeBehind(root, tip string) bool { + head, err := gitutil.RunCappedAsStored(root, ffSmallRead, ffArgv(ffHead)...) + if err != nil { + return true + } + if head == tip { + return false + } + held, err := ffHoldsCommit(root, tip) + if err != nil || !held { + return true + } + ahead, err := ffIsAncestor(root, tip, head) + return err != nil || !ahead +} + +// ffControl reads the control record of runID for judgeFFRun. Unlike +// runControl, which answers an empty record where the checkout cannot be +// opened or the id is not a run's, every such read is an error here, so a +// run whose control record cannot be read is held rather than read as naming +// no driver. +func ffControl(repoRoot, runID string) (control, error) { + if !ValidRunID(runID) { + return control{}, fmt.Errorf("%q is not a run's id", runID) + } + root, err := os.OpenRoot(repoRoot) + if err != nil { + return control{}, fmt.Errorf("opening the checkout to read the run's control record: %w", err) + } + defer root.Close() + return readControl(root, runID) +} + +// ffHoldFor says what letting a run go does with its hold on one issue, as +// this checkout's view of origin shows it (r, found), where the run last +// moved at moved: release it only where it can still be the run's own and +// still blocks someone, that is this copy's, inside its lease, and claimed or +// renewed no later than moved; otherwise why it is left, which pushes +// nothing. A hold past its lease blocks no one; one claimed or renewed after +// the run last moved is a later hold, a hand reservation or the run stepped +// again, and is left standing. +func ffHoldFor(r claim.Reservation, found bool, moved time.Time) (bool, string) { + switch { + case !found: + return false, "no reservation of it stands on origin as this checkout last fetched it, so nothing is pushed" + case r.State == claim.StateReleased: + return false, "its reservation is already released, so nothing is pushed" + case r.State == claim.StateExpired: + return false, fmt.Sprintf("its hold had lapsed at %s and blocks no one, so nothing is pushed", stamp(r.EffectiveExpiry)) + case r.State != claim.StateLive: + return false, "its reservation cannot be read, so it is left as it stands and nothing is pushed" + case r.Copy != claim.CopyThis: + return false, "its reservation is not this copy's, so it is left as it stands and nothing is pushed" + case r.ClaimedAt.After(moved): + return false, fmt.Sprintf("its reservation was claimed or renewed at %s, after the run last moved, so it is a later hold and is left standing", stamp(r.ClaimedAt)) + } + return true, "" +} diff --git a/internal/core/implement/loop/remoteid.go b/internal/core/implement/loop/remoteid.go index 7c1d8021b7..aca12d677d 100644 --- a/internal/core/implement/loop/remoteid.go +++ b/internal/core/implement/loop/remoteid.go @@ -1200,7 +1200,7 @@ func askStartTip(repoRoot string, id *remoteIdentity, g *outageGate) (startTip, // hooks directory outside the checkout, or no origin, has nothing to be // compared with, and passes. It reads and refuses only, and a person's own // git runs the hooks as before. -func proveCheckoutHooks(repoRoot string, id *remoteIdentity, st startTip, blocked string) error { +func proveCheckoutHooks(repoRoot string, id *remoteIdentity, st startTip, blocked ffHold) error { rels, err := checkoutHooksRels(repoRoot, id) if err != nil || len(rels) == 0 || !st.origin { return err @@ -1272,10 +1272,11 @@ const startOutageLane = "drive-start" // files in the hooks directory git does not track; a checkout behind the tip, // whose hooks are its own commit's; or files that differ from the tip's. Each // file is named through the refusal redactor; no value read from the -// settings is placed in a command to paste. blocked, when it is not "", is -// what declined the start's fast-forward of a checkout behind the tip, and -// the remedy names it before the pull. -func startHooksRefusal(repoRoot, rel, tip, dir, salt, blocked string, err error) error { +// settings is placed in a command to paste. blocked, when its clause is not +// "", is what declined the start's fast-forward of a checkout behind the tip, +// and the remedy names it, with the act that frees each run holding it, +// before the pull. +func startHooksRefusal(repoRoot, rel, tip, dir, salt string, blocked ffHold, err error) error { shown := nameChanges(repoRoot, []string{rel})[0] named := nameChanges(repoRoot, []string{fsutil.RedactHome(err.Error())})[0] var pe *proofError @@ -1301,13 +1302,17 @@ func startHooksRefusal(repoRoot, rel, tip, dir, salt, blocked string, err error) // behindRemedy is the remedy for a checkout behind origin's tip whose hooks // are its own commit's: what blocked the start's fast-forward, when one was -// declined, then the pull. -func behindRemedy(blocked string) string { +// declined, with the act that frees each run holding it where runs did, then +// the pull. +func behindRemedy(blocked ffHold) string { pull := "bring the checkout up to " + Remote + "'s tip (`git pull --ff-only`), then start the drive again; nothing was made" - if blocked == "" { + switch { + case blocked.clause == "": return pull + case len(blocked.frees) > 0: + return "the drive did not fast-forward the checkout, since " + blocked.clause + ": " + strings.Join(blocked.frees, "; ") + "; once each is free, or instead, " + pull } - return "the drive did not fast-forward the checkout, since " + blocked + "; settle that, then " + pull + return "the drive did not fast-forward the checkout, since " + blocked.clause + "; settle that, then " + pull } // untracked says whether git tracks none of paths, each under repoRoot. @@ -2034,7 +2039,7 @@ var boundaryHold = func(repoRoot string, was *remoteIdentity, st startTip, from if len(names) > 0 { return nil, heldChangedRefusal(names) } - if err := proveCheckoutHooks(repoRoot, now, st, ""); err != nil { + if err := proveCheckoutHooks(repoRoot, now, st, ffHold{}); err != nil { return nil, err } return now, nil diff --git a/internal/core/implement/loop/renewruns.go b/internal/core/implement/loop/renewruns.go index fa5c7ec924..1157b19df4 100644 --- a/internal/core/implement/loop/renewruns.go +++ b/internal/core/implement/loop/renewruns.go @@ -249,8 +249,10 @@ func renewalRuns(root, runID string) ([]State, []RunRenewal) { // (drain_finish.go), as the drain's own renewal leaves it (renewable). A lane // handed back that still owes its arming's withdrawal is renewed: its // reservation is kept until the forge reports no arming (handedBackIssue). +// Nor is a run a drive let go for its fast-forward, unmoved since +// (ffLetGoStands): no renewal revives its hold, re-dates it or logs on it. func renewsWhereItWaits(st State) bool { - if !st.holdsAny() || st.Complete() || parkedAtLand(st) >= 0 { + if !st.holdsAny() || st.Complete() || parkedAtLand(st) >= 0 || ffLetGoStands(st) { return false } return !handedBackIssue(st) diff --git a/internal/core/implement/loop/terminal.go b/internal/core/implement/loop/terminal.go index 318dfe51e9..29993efcb7 100644 --- a/internal/core/implement/loop/terminal.go +++ b/internal/core/implement/loop/terminal.go @@ -161,6 +161,24 @@ const TerminalResumeCommand = "abcd drain --drive" // go as it ended, which the drive that takes the lane up reserves again. const StageDriveReleased = "drive_released" +// StageFFLetGo is the run record's stage for a drive letting the run go for +// its fast-forward, at its start or between lanes (letGoForFF): while it is the +// run's last entry (ffLetGoStands), no later drive names the run again. +const StageFFLetGo = "ff_let_go" + +// ffLetGoStands reports whether st's last record entry is a drive's let-go +// for its fast-forward (StageFFLetGo), so nothing has moved the run since a +// drive said it was no one's work: the one sign every path honours. No +// drive's start takes such a run up or over (takeEarlier, letGoUnlisted), no +// take-up works a hold of it again (keptToLapse, takeUp), and no renewal of a +// run renews, re-dates or logs on it (renewsWhereItWaits, renewable), so it +// never reads as moved and holds no later fast-forward back. A step, the +// person's own act, appends an entry and ends it. +func ffLetGoStands(st State) bool { + n := len(st.Record) + return n > 0 && st.Record[n-1].Stage == StageFFLetGo +} + // StageReleasedOver is the run record's stage for the record a drive's release let go // of: its note is that record's blob on origin's default branch and nothing else, so // the take-up can tell what the issue asks now from what the lane was working to. @@ -394,6 +412,12 @@ type terminal struct { // said once while its reason stands; a fast-forward that moved, or a // checkout found level, clears it. ffNoted string + // ffLetGo are the runs this drive let go for its fast-forward (letGoForFF), so each + // is said once. + ffLetGo []string + // ffEarlierSaid is set once the line counting the runs an earlier drive let go + // for the fast-forward is said. + ffEarlierSaid bool // laneInHand is the run the lane counts below are of. laneInHand string // startedAgent says this step started an agent, which is movement of a kind. @@ -1721,7 +1745,8 @@ func (t *terminal) startHold() (*remoteIdentity, error) { return nil, err } st, err := askStartTip(t.repoRoot, id, g) - blocked, moved, from := "", "", "" + var blocked ffHold + moved, from := "", "" if err == nil { id, blocked, from, err = t.startFastForward(id, st) if from != "" { @@ -1768,8 +1793,13 @@ func movedRefusal(repoRoot, moved string, err error) error { // startFastForward is the start's fast-forward of the checkout to the tip // origin answered its one ask with (st; checkoutff.go). Where st holds no // tip, nothing is run, and why one was not taken is said. A lane in progress -// in any run of the checkout (ffLanesInProgress) declines it, and so does -// runs' state that cannot be read. The start has registered no check with +// in any run of the checkout (ffRunsInProgress) declines it while its run is +// held (judgeFFRuns), each such run said on a line of its own with the act +// that frees it. A run nothing holds is let go for it (letGoForFF), but only +// once the judgement found nothing else in the way and the comparison of what +// the drive holds has passed, immediately before the merge: a start declined +// for any other reason lets nothing go and says nothing of it. Runs' state +// that cannot be read declines it too. The start has registered no check with // gitutil yet, so the comparison of what the drive holds with the reading // the start has just made (heldBeforeGit) is asked immediately before the // merge, and a difference refuses the start with nothing run. A merge that @@ -1783,37 +1813,39 @@ func movedRefusal(repoRoot, moved string, err error) error { // refusal after the move, the hold read again included, says so // (movedRefusal), and the runs parked on their pull requests are brought up // to the move (rebaseParked). -func (t *terminal) startFastForward(id *remoteIdentity, st startTip) (*remoteIdentity, string, string, error) { +func (t *terminal) startFastForward(id *remoteIdentity, st startTip) (*remoteIdentity, ffHold, string, error) { if st.tip == "" { if st.why != "" { t.sayFF(st.why, "this checkout was not fast-forwarded: "+st.why) } - return id, "", "", nil + return id, ffHold{}, "", nil } - lanes, err := ffLanesInProgress(t.repoRoot) - if err != nil { - why := "the runs in this checkout could not be read, so whether a lane is in progress is not known: " + nameChanges(t.repoRoot, []string{err.Error()})[0] + runs, why := t.ffRunsFor(st.tip) + if why != "" { t.sayFF(why, "this checkout was not fast-forwarded: "+why) - return id, why, "", nil + return id, ffHold{clause: why}, "", nil } - j, err := judgeCheckoutFF(t.repoRoot, st.branch, st.tip, lanes) + j, err := judgeCheckoutFF(t.repoRoot, st.branch, st.tip, runs.lanes) if err != nil { why := "what stands in it could not be read: " + nameChanges(t.repoRoot, []string{err.Error()})[0] t.sayFF(why, "this checkout was not fast-forwarded: "+why) - return id, why, "", nil + return id, ffHold{clause: why}, "", nil } var held error res, err := actCheckoutFF(j, func() error { - held = heldBeforeGit(t.repoRoot, id) - return held + if held = heldBeforeGit(t.repoRoot, id); held != nil { + return held + } + t.letGoAllForFF(runs.gone) + return nil }) if held != nil { if r, ok := AsRefusal(held); ok { named := *r named.Reason = "the drive cannot start: before it fast-forwarded the checkout, " + r.Reason - return nil, "", "", &named + return nil, ffHold{}, "", &named } - return nil, "", "", held + return nil, ffHold{}, "", held } if err != nil { named := nameChanges(t.repoRoot, []string{err.Error()})[0] @@ -1821,7 +1853,7 @@ func (t *terminal) startFastForward(id *remoteIdentity, st startTip) (*remoteIde if errors.As(err, &stopped) && len(stopped.Paths) > 0 { named += " (" + termsafe.Sanitize(strings.Join(nameChanges(t.repoRoot, stopped.Paths), ", ")) + ")" } - return nil, "", "", refuse(StageDrain, "", "", + return nil, ffHold{}, "", refuse(StageDrain, "", "", "the drive cannot start: its fast-forward of the checkout to "+Remote+"'s tip "+st.tip[:12]+" did not finish: "+named, "look at the checkout as git leaves it (`git status`) and settle it, then start the drive again; nothing else was made") } @@ -1831,15 +1863,87 @@ func (t *terminal) startFastForward(id *remoteIdentity, st startTip) (*remoteIde t.say("%s", ffMovedLine(res)) now, err := readRemoteIdentity(t.repoRoot) if err != nil { - return nil, "", res.From, err + return nil, ffHold{}, res.From, err } - return now, "", res.From, nil + return now, ffHold{}, res.From, nil case ffDeclined: - t.sayFF(string(res.Kind)+"\x00"+res.Sentence+"\x00"+strings.Join(res.Paths, "\x00"), ffDeclinedLine(t.repoRoot, st.branch, res)) - return id, ffBlocked(t.repoRoot, res), "", nil + return id, t.sayFFDeclined(st.branch, res, runs.frees), "", nil } t.ffNoted = "" - return id, "", "", nil + return id, ffHold{}, "", nil +} + +// ffRuns is what the runs with a lane in progress in the checkout make of a +// fast-forward, judged alike at the start and at each boundary (ffRunsFor): +// lanes names the run of each lane something still holds, for +// judgeCheckoutFF; frees is the act that frees each, for the decline to name +// (sayFFDeclined); gone is each run nothing holds, let go just before the +// merge (letGoAllForFF) and never listed in lanes. +type ffRuns struct { + lanes, frees []string + gone []ffRun +} + +// ffRunsFor judges the runs with a lane in progress in the checkout +// (ffRunsInProgress, judgeFFRuns) for a fast-forward to tip, or none where the +// checkout cannot be behind tip (ffMayBeBehind), so no run is let go for a +// fast-forward that will not be made. why is "" where the runs could be read, +// and otherwise why it is not known whether a lane is in progress, which +// declines the fast-forward. +func (t *terminal) ffRunsFor(tip string) (ffRuns, string) { + runs, err := ffRunsInProgress(t.repoRoot) + if err != nil { + return ffRuns{}, "the runs in this checkout could not be read, so whether a lane is in progress is not known: " + nameChanges(t.repoRoot, []string{err.Error()})[0] + } + if !ffMayBeBehind(t.repoRoot, tip) { + return ffRuns{}, "" + } + var out ffRuns + for _, r := range judgeFFRuns(t.repoRoot, runs, t.now()) { + if r.gone { + out.gone = append(out.gone, r) + continue + } + out.lanes = append(out.lanes, r.run.RunID) + out.frees = append(out.frees, r.why) + } + return out, "" +} + +// letGoAllForFF lets go each of gone for the fast-forward about to be made +// (letGoForFF), and says once in a drive, on one line, how many an earlier +// drive had let go already. Its caller has judged the fast-forward clear, and +// the comparison of what the drive holds has passed: at the start +// immediately before (heldBeforeGit), and at a boundary at the top of the +// pass, with the ask of origin between, the merge itself then compared +// through the check the drive registered with gitutil. +func (t *terminal) letGoAllForFF(gone []ffRun) { + earlier := 0 + for _, r := range gone { + if t.letGoForFF(r) { + earlier++ + } + } + if earlier > 0 && !t.ffEarlierSaid { + t.ffEarlierSaid = true + t.say("%d %s an earlier drive let go %s let go for the fast-forward; `abcd implement status` lists %s", earlier, plural(earlier, "run", "runs"), plural(earlier, "stays", "stay"), plural(earlier, "it", "them")) + } +} + +// sayFFDeclined says res, a declined fast-forward of the checkout to branch's +// tip, once while its reason stands (sayFF), the start's and a boundary's +// alike under one key: a lane in progress is followed by frees, the act that +// frees each run holding it, one to a line. It returns what declined it, for +// the hooks' refusal at the start to name (behindRemedy). +func (t *terminal) sayFFDeclined(branch string, res ffResult, frees []string) ffHold { + hold := ffHold{clause: ffBlocked(t.repoRoot, res)} + lines := []string{ffDeclinedLine(t.repoRoot, branch, res)} + if res.Kind == ffLaneInProgress { + hold.frees = frees + lines = append(lines, frees...) + } + t.sayFF(string(res.Kind)+"\x00"+res.Sentence+"\x00"+strings.Join(res.Paths, "\x00")+"\x00"+strings.Join(hold.frees, "\x00"), lines...) + return hold } // holdCheck is the check the drive registers with gitutil @@ -1864,7 +1968,11 @@ func (t *terminal) setHold(id *remoteIdentity) { // origin for its default branch's tip once (boundaryTip) and fast-forwards // the checkout to that answer as the start does (checkoutff.go), never to a // ref in the repository; a lane in progress in any run of the checkout, one -// set aside, passed over or another session's, declines it. The merge runs +// set aside, passed over or another session's, declines it while its run is +// held, judged as the start judges it (ffRunsFor): a run nothing holds is let +// go just before the merge (letGoAllForFF), one the start let go already +// named no more, and only once the judgement found nothing else in the way +// (iss-2612022203551074). The merge runs // through the gitutil runner that asks the drive's check first, so the hold // is compared immediately before it, and a difference there ends the drive. // A lost network, a tip the repository still does not hold once fetched, or @@ -1880,19 +1988,21 @@ func (t *terminal) boundaryFastForward(ctx context.Context) (string, error) { if err != nil || st.tip == "" { return "", err } - lanes, err := ffLanesInProgress(t.repoRoot) - if err != nil { - why := "the runs in this checkout could not be read, so whether a lane is in progress is not known: " + nameChanges(t.repoRoot, []string{err.Error()})[0] + runs, why := t.ffRunsFor(st.tip) + if why != "" { t.sayFF(why, "this checkout was not fast-forwarded: "+why) return "", nil } - j, err := judgeCheckoutFF(t.repoRoot, st.branch, st.tip, lanes) + j, err := judgeCheckoutFF(t.repoRoot, st.branch, st.tip, runs.lanes) if err != nil { why := "what stands in it could not be read: " + nameChanges(t.repoRoot, []string{err.Error()})[0] t.sayFF(why, "this checkout was not fast-forwarded: "+why) return "", nil } - res, err := actCheckoutFF(j, nil) + res, err := actCheckoutFF(j, func() error { + t.letGoAllForFF(runs.gone) + return nil + }) if err != nil { if gitNotRun(err) { if r, ok := heldStopOf(err); ok { @@ -1923,7 +2033,7 @@ func (t *terminal) boundaryFastForward(ctx context.Context) (string, error) { } return "", nil case ffDeclined: - t.sayFF(string(res.Kind)+"\x00"+res.Sentence+"\x00"+strings.Join(res.Paths, "\x00"), ffDeclinedLine(t.repoRoot, st.branch, res)) + t.sayFFDeclined(st.branch, res, runs.frees) return "", nil } t.ffNoted = "" @@ -2037,14 +2147,169 @@ func boundaryMovedRefusal(repoRoot, moved string, err error) error { return &named } -// sayFF says line, why the checkout was not fast-forwarded, unless the -// reason key is the one last said. -func (t *terminal) sayFF(key, line string) { +// sayFF says lines, why the checkout was not fast-forwarded, each on its own, +// unless the reason key is the one last said. +func (t *terminal) sayFF(key string, lines ...string) { if key == t.ffNoted { return } t.ffNoted = key + for _, line := range lines { + t.say("%s", line) + } +} + +// letGoForFF says, once in a drive, that its fast-forward lets go r, a run no +// live driver holds that has not moved within a run's lease (judgeFFRun), on +// one line with what became of each reservation the run still records. Its +// caller has judged the fast-forward clear and compared what the drive holds +// (heldBeforeGit) just before. A hold is released only where ffHoldFor finds +// it can still be the run's own and still blocks someone: this copy's, inside +// its lease, and claimed or renewed no later than the run last moved; it is +// released fenced on the commit the view showed (releaseReservationAt), so a +// hold claimed again since is left as it stands. A hold past its lease blocks +// no one and pushes nothing, and one claimed or renewed after the run last +// moved is someone's later work and is left standing. A hold that can still be +// the run's own and is not released, one that had lapsed or whose release +// failed, is left to lapse (ffLeaveToLapse), so a load-gate waiter's renewal +// does not revive it; the mark below keeps every renewal of the run off it. A +// release is written to +// the run's record as a plain release and leaves the run's date alone +// (recordReleases): the drive's own let-go mark would have a later start take +// the run up and step it (letGoUnlisted), and a new date would read as +// movement within its lease. Nothing of the run's worktree, branch or lane is +// touched; the line names the discard that ends the run for good (ffEndsFor). +// The let-go is marked on the run's record (StageFFLetGo), its date again +// left alone, so a later drive that lets the run go again names it no more +// while that mark is the run's last entry (ffLetGoStands): it reports true, for +// the caller to count such runs on one line. The mark, not the lapse note, is +// what keeps every take-up and renewal off the run. +func (t *terminal) letGoForFF(r ffRun) bool { + if slices.Contains(t.ffLetGo, r.run.RunID) { + return false + } + t.ffLetGo = append(t.ffLetGo, r.run.RunID) + if ffLetGoStands(r.run) { + return true + } + type held struct { + issue, clause string + lapse *claim.Reservation + } + line := r.why + var gone []letGone + var holds []held + if run := r.run; run.holdsAny() && !letItsReservationGo(run) && !letGoByDrive(run) { + now := t.now() + snap, err := claim.View(t.repoRoot, now) + if err != nil { + line += "; its reservations could not be read, so nothing is pushed: " + err.Error() + } else { + for _, issue := range run.reservedIssues() { + h, found := snap.Lookup(issue) + release, why := ffHoldFor(h, found, r.moved) + hd := held{issue: issue, clause: why} + if release { + clause, failed := releaseReservationAt(t.repoRoot, issue, h.Commit, "", now) + gone = append(gone, letGone{id: issue, clause: clause, failed: failed}) + hd.clause, release = clause, !failed + } + if !release && ffMayLapse(h, found, r.moved) { + hd.lapse = &h + } + holds = append(holds, hd) + } + } + } + // The mark is saved before any hold is left to lapse, so a run never + // carries a note without the mark that keeps every take-up off it. + saved := t.recordReleases(r.run.RunID, gone, t.now(), false) + for _, hd := range holds { + if hd.lapse != nil && saved == nil { + hd.clause += t.ffLeaveToLapse(hd.issue, *hd.lapse) + } + line += "; " + hd.issue + ": " + hd.clause + } + if saved != nil { + line += "; the let-go could not be written to the run's record, so nothing marks the run let go and no hold of it is left to lapse" + if slices.ContainsFunc(gone, func(g letGone) bool { return !g.failed }) { + line += ", though each release named above has reached origin" + } + line += ": " + termsafe.Sanitize(fsutil.RedactHome(saved.Error())) + } else { + line += "; " + t.ffWhoseNext(r) + } t.say("%s", line) + return false +} + +// ffWhoseNext is what becomes of r, a run let go for the fast-forward, after +// the let-go, by whose the run is (dcn-2612031056281133): the let-go frees the +// checkout and no more, and the line promises a take-up only where a drive's +// own path takes the run up. Where the drain's state cannot be read, the +// start's take-up (takeEarlier) takes nothing and the first move refuses on +// the same read, so this drive takes nothing up. An ended drain (readDrain's +// live false, a drain an outage or a cap stopped) hands nothing out, since the +// first move begins a new drain with no lanes, so its lanes, like a missing +// state's, are read as unlisted. A run whose lane the live drain lists as +// anything but in progress or halted (taken over, handed back) is +// skipped by takeEarlier and not handed out, whatever mark it carries. An +// issue's run carrying a stop's mark, unlisted or whose lane is in progress or +// halted, is taken over as soon as no stop of the person's holds over it, at a +// start (stopOver, readmitHalted) or as its lane comes to hand (takeUp), by +// this drive or the next, whether or not this drive passed it over. An +// unmarked lane in progress is taken up as it comes to hand: by this drive, or, +// where this drive passed it over (a list it keeps in memory alone), by the +// next. Any other run, an unmarked unlisted run, an unmarked halted lane and +// an intent's build among them, stays let go, taken up by no drive and renewed +// by nothing, until a person steps it or takes it over. +func (t *terminal) ffWhoseNext(r ffRun) string { + id := termsafe.Sanitize(r.run.RunID) + acts := "a person steps it (`abcd implement step --run " + id + "`) or takes it over (`abcd implement resume --take " + id + "`)" + st, live, err := readDrain(t.repoRoot) + if err != nil { + return "the drain's state could not be read, so this drive takes nothing up; once it can be read a drive judges the run again, or " + acts + } + outcome, listed := "", false + if i := slices.IndexFunc(st.Lanes, func(l DrainLane) bool { return l.RunID == r.run.RunID }); i >= 0 { + outcome, listed = st.Lanes[i].Outcome, live + } + switch { + case listed && outcome != DrainLaneInProgress && outcome != DrainLaneHalted: + case r.stop && r.run.Issue() != "": + return "it carries a stop's mark, so a drive takes it over as soon as no stop of the person's holds over it" + case listed && outcome == DrainLaneInProgress && t.passedLane(r.run.RunID): + return "this drive passed its lane over, so the next drive takes it up again as the lane comes to hand" + case listed && outcome == DrainLaneInProgress: + return "the drain has its lane in progress, so this drive takes it up again as the lane comes to hand" + } + return "no drive takes it up again until " + acts +} + +// ffMayLapse reports whether h, the hold on an issue of a run let go for the +// fast-forward that was not released, can still be the run's own and so is +// left to lapse (ffLeaveToLapse): this copy's, live or lapsed, and claimed or +// renewed no later than the run last moved (moved). +func ffMayLapse(h claim.Reservation, found bool, moved time.Time) bool { + return found && h.Copy == claim.CopyThis && (h.State == claim.StateLive || h.State == claim.StateExpired) && !h.ClaimedAt.After(moved) +} + +// ffLeaveToLapse leaves h, the hold on issue of a run let go for the +// fast-forward, to lapse at its lease (claim.LeaveToLapse), as a lane set +// aside leaves its hold (leaveToLapse), where ffMayLapse finds h can still be +// the run's own, and only once the run's let-go mark is saved. The renewals that read the run, the drive's own, an +// `abcd implement status` call's and the drain's, are kept off it by its let-go +// mark (ffLetGoStands); the note keeps off a load-gate waiter's renewal of this +// copy's own reservations (claim.RenewDue), which reads no run, so no hold of +// no one's work is revived on origin. It is never the sign to take the run up: +// while the mark stands, keptToLapse reads no note on the run. Any reservation +// pushed for issue since ends the note with nothing to undo. It returns the +// clause the let-go line takes. +func (t *terminal) ffLeaveToLapse(issue string, h claim.Reservation) string { + if err := claim.LeaveToLapse(t.repoRoot, issue, h.Commit); err != nil { + return ", and it could not be left to lapse, so a renewal in this copy may revive it: " + termsafe.Sanitize(fsutil.RedactHome(err.Error())) + } + return ", and this copy leaves it to lapse, so no renewal here revives it" } // boundaryHeld reports whether a due boundary waits: for a skip the run gave and the next @@ -3201,8 +3466,10 @@ func (t *terminal) takeUp(ctx context.Context, runID string) (bool, string) { // A hold a drive left to lapse, a lane it set aside or the kept hold of a stop that // could not be applied, is worked again from here (resumeKept); so is a lane set aside // and now tried again whose tip is no longer the one left to lapse, a peer's push - // among them, so it is reserved again or dropped before it is stepped. - if _, again := t.retried[run.RunID]; again || t.keptToLapse(run) { + // among them, so it is reserved again or dropped before it is stepped. A run a + // drive let go for its fast-forward is not worked again from here while that + // let-go stands (ffLetGoStands). + if _, again := t.retried[run.RunID]; (again && !ffLetGoStands(run)) || t.keptToLapse(run) { return t.resumeKept(ctx, run) } if !letGoByDrive(run) { @@ -3531,6 +3798,10 @@ func (t *terminal) takeEarlier(ctx context.Context) (string, error) { case t.pastBound(): return TerminalUntil, nil } + // A run a drive let go for its fast-forward is judged here by whose it + // is (ffWhoseNext): one the drain lists is the drain's, and one a stop's + // mark stands on is taken over as any such run; only a run no drain lists + // and no mark stands on stays let go (letGoUnlisted). if run.Complete() || driveStopped(run.RunID) || t.passedLane(run.RunID) { continue } @@ -3624,9 +3895,11 @@ func (t *terminal) takeEarlier(ctx context.Context) (string, error) { // lane of the drain lists: the drain's own lanes are taken up as they come to hand // (takeUp), a parked run keeps its holds, an intent's build is the person's, and a run // whose lane was handed back or dropped since (a take-up that backed off) has nothing to -// take up. A run reserved with no such sign, one a kill left, is not one a start takes. +// take up. A run reserved with no such sign, one a kill left, is not one a start takes, +// nor is one a drive let go for its fast-forward and nothing has moved since +// (ffLetGoStands), whatever other sign it carries. func (t *terminal) letGoUnlisted(run State, listed func(string) (string, bool)) bool { - if run.Issue() == "" || parkedAtLand(run) >= 0 || !(letGoByDrive(run) || t.keptToLapse(run)) { + if run.Issue() == "" || parkedAtLand(run) >= 0 || ffLetGoStands(run) || !(letGoByDrive(run) || t.keptToLapse(run)) { return false } if outcome, _, _ := laneOutcome(run); outcome != DrainLaneInProgress { @@ -4127,10 +4400,12 @@ func (t *terminal) leaveToLapse(runID string) (bool, []SetAsideHold) { // keptToLapse reports whether a hold of run is one a drive left to lapse at its tip // (leaveToLapse): a lane it set aside, or the kept hold of a stop that could not be -// applied. A view that cannot be read is no such sign. +// applied. A view that cannot be read is no such sign, and neither is the note a +// drive's fast-forward left on a run it let go (ffLeaveToLapse): while that let-go +// stands (ffLetGoStands), the run is no one's to take up. func (t *terminal) keptToLapse(run State) bool { ids := run.reservedIssues() - if len(ids) == 0 { + if len(ids) == 0 || ffLetGoStands(run) { return false } snap, err := claim.View(t.repoRoot, t.now()) @@ -4587,22 +4862,48 @@ func (t *terminal) letGo() { // records the let-go on the run, so a later start takes it up (letGoUnlisted). Lines go in // the run's record alone: its file keeps the version it states. func (t *terminal) releaseRun(run State, now time.Time) { - type letGone struct { - id, clause string - failed bool - } var gone []letGone for _, id := range run.reservedIssues() { clause, failed := releaseReservation(t.repoRoot, id, "", now) t.say("%s: %s", id, clause) gone = append(gone, letGone{id: id, clause: clause, failed: failed}) } - _ = mutateReservation(t.repoRoot, run.RunID, func(st *State) (bool, error) { + _ = t.recordReleases(run.RunID, gone, now, true) +} + +// letGone is what releasing one issue a run holds came to. +type letGone struct { + id, clause string + failed bool +} + +// recordReleases records each release of gone in the record of the run runID +// alone, its file keeping the version it states. A drive's let-go (drive) +// writes the drive's mark, which a later start takes the run up from, beside +// the note of the record it released over, and dates the save even with +// nothing released; a fast-forward's let-go writes a plain release line for +// each, failed or not, then its own mark (StageFFLetGo), and leaves the run's +// date as it was. It returns the save's error, which a fast-forward's let-go +// says and writes no lapse note after. +func (t *terminal) recordReleases(runID string, gone []letGone, now time.Time, drive bool) error { + return mutateReservation(t.repoRoot, runID, func(st *State) (bool, error) { for _, g := range gone { + if !drive { + stage := StageReservationReleased + if g.failed { + stage = StageReservationReleaseFailed + } + st.Record = append(st.Record, Entry{At: now, Stage: stage, Note: g.clause, Issue: st.issueOn(g.id)}) + continue + } noteRecordReleasedFor(t.repoRoot, st, g.id, g.failed, now) st.Record = append(st.Record, Entry{At: now, Stage: StageDriveReleased, Note: g.clause, Issue: st.issueOn(g.id)}) } - st.UpdatedAt = now + if drive { + st.UpdatedAt = now + return true, nil + } + st.Record = append(st.Record, Entry{At: now, Stage: StageFFLetGo}) return true, nil }) } diff --git a/internal/core/implement/loop/terminal_ff_abandoned_test.go b/internal/core/implement/loop/terminal_ff_abandoned_test.go new file mode 100644 index 0000000000..ac080a5e2d --- /dev/null +++ b/internal/core/implement/loop/terminal_ff_abandoned_test.go @@ -0,0 +1,316 @@ +package loop + +// terminal_ff_abandoned_test.go holds which runs with a lane in progress hold +// a drive's start back from fast-forwarding its checkout +// (iss-2612022203551074): a run no live driver holds that has not moved +// within the longest lease a run can take is let go for the fast-forward, +// said on one line naming it and why, and the checkout is brought up to +// origin's tip; a run a live driver holds still holds it back, and the start's +// refusal names, for that run, the act that frees it. Watched failing: before +// the change, the month-old run held the fast-forward back like any other, +// and the refusal said only to settle it. + +import ( + "os" + "path/filepath" + "slices" + "strings" + "testing" + "time" + + "github.com/intentdriven/abcd/internal/core/claim" + + "github.com/intentdriven/abcd/internal/core/sessionname" + "github.com/intentdriven/abcd/internal/gittest" +) + +// staleLane writes an issue's run into repo with its lane at the implement +// stage and its state last written days ago, as a drive killed weeks back +// leaves it; driver, when not nil, is the driver its control record names, +// which claimed the run as long ago. It returns the run's id. +func staleLane(t *testing.T, repo *gittest.Repo, driver *LiveDriver) string { + t.Helper() + start, err := Start(repo.Root(), "itd-10", Options{noReserve: true}) + if err != nil { + t.Fatal(err) + } + st, err := ReadState(repo.Root(), start.RunID) + if err != nil { + t.Fatal(err) + } + root, err := os.OpenRoot(repo.Root()) + if err != nil { + t.Fatal(err) + } + defer root.Close() + days := time.Now().UTC().Add(-72 * time.Hour) + st.Key = "iss-2612020000000001" + st.Lanes = []Lane{{ID: "lane-1", Stage: StageImplement}} + st.Pending = nil + st.UpdatedAt = days + if err := writeState(root, st); err != nil { + t.Fatal(err) + } + c, err := readControl(root, start.RunID) + if err != nil { + t.Fatal(err) + } + c.Driver = driver + if driver != nil { + c.Driver.At = days + } + if err := writeControl(root, start.RunID, c); err != nil { + t.Fatal(err) + } + return start.RunID +} + +// procsAre has every read of the process table answer tab. +func procsAre(t *testing.T, tab sessionname.Table) { + t.Helper() + was := readProcs + readProcs = func() (sessionname.Table, error) { return tab, nil } + t.Cleanup(func() { readProcs = was }) +} + +// TestAStartLetsGoARunNoDriverHasMovedForDays: a run whose recorded driver is +// gone and whose state has not moved for days does not hold the start's +// fast-forward back: the start says on one line that it lets the run go and +// why, and brings the checkout up to origin's tip, leaving the run's lane as +// it stands for the sweep. +func TestAStartLetsGoARunNoDriverHasMovedForDays(t *testing.T) { + repo, merged := behindCheckout(t) + tab := terminalProcs(time.Now()) + procsAre(t, tab) + runID := staleLane(t, repo, &LiveDriver{PID: 4242, StartUnix: time.Now().Add(-100 * time.Hour).Unix()}) + tm, err, said := startSaying(t, repo) + if err != nil || tm.o.Options.remote == nil { + t.Fatalf("the drive lets the dead run go and starts: %v\n%s", err, strings.Join(*said, "\n")) + } + headIs(t, repo, merged, "the checkout is fast-forwarded to origin's tip") + var gone []string + for _, l := range *said { + if strings.Contains(l, "run "+runID) && strings.Contains(l, "lets it go") { + gone = append(gone, l) + } + } + if len(gone) != 1 || !strings.Contains(gone[0], "no live driver") || !strings.Contains(gone[0], "has not moved since") { + t.Fatalf("one line names the run let go and why: %q", *said) + } + st, err := ReadState(repo.Root(), runID) + if err != nil || len(st.Lanes) != 1 || st.Lanes[0].Stage != StageImplement { + t.Fatalf("the run's lane is left as it stands: %+v %v", st.Lanes, err) + } +} + +// TestAStartIsHeldByARunALiveDriverHolds: the same run, with its driver alive, +// still holds the fast-forward back, however long ago it last moved, and the +// refusal names the run, its driver and the act that frees it, never a bare +// "settle that". +func TestAStartIsHeldByARunALiveDriverHolds(t *testing.T) { + repo, _ := behindCheckout(t) + first := repo.Git("rev-parse", "HEAD") + tab := terminalProcs(time.Now()) + procsAre(t, tab) + h, ok := procOf(tab, otherDrive) + if !ok { + t.Fatal("the other tab's drive is in the stand-in table") + } + runID := staleLane(t, repo, &LiveDriver{PID: h.PID, StartUnix: h.StartUnix, SlackMS: h.Slack.Milliseconds()}) + tm, err, said := startSaying(t, repo) + r := startRefused(t, tm, err, "the checkout is behind origin's tip") + headIs(t, repo, first, "no fast-forward is made under a run a live driver holds") + if strings.Contains(r.Remedy, "settle that") { + t.Fatalf("the remedy names the act that frees the run, not a bare settle: %+v", r) + } + free := "run " + runID + " is driven by process 5220" + at, pull := strings.Index(r.Remedy, free), strings.Index(r.Remedy, "git pull --ff-only") + if at < 0 || pull < 0 || at > pull || !strings.Contains(r.Remedy, "once that driver ends") { + t.Fatalf("the remedy names the run, its driver and what frees it before `git pull --ff-only`: %+v", r) + } + if strings.Contains(strings.Join(*said, "\n"), "lets it go") { + t.Fatalf("a run a live driver holds is not let go: %q", *said) + } +} + +// staleIssue is the issue staleLane's run is for. +const staleIssue = "iss-2612020000000001" + +// reserveStale reserves staleIssue from repo's copy as at claimed, and marks +// runID's state as holding it from then. +func reserveStale(t *testing.T, repo *gittest.Repo, runID string, claimed time.Time) { + t.Helper() + asPat(t, repo) + if _, err := claim.Reserve(repo.Root(), claim.Request{Record: staleIssue, Footprint: []string{".githooks"}}, + claim.Options{Now: func() time.Time { return claimed }}); err != nil { + t.Fatal(err) + } + if _, err := claim.Fetch(repo.Root(), claim.Options{}); err != nil { + t.Fatal(err) + } + root, err := os.OpenRoot(repo.Root()) + if err != nil { + t.Fatal(err) + } + defer root.Close() + st, err := ReadState(repo.Root(), runID) + if err != nil { + t.Fatal(err) + } + at := claimed.UTC() + st.ReservedAt = &at + if err := writeState(root, st); err != nil { + t.Fatal(err) + } +} + +// reservationRefs is every reservation ref origin holds, with its commit. +func reservationRefs(t *testing.T, repo *gittest.Repo) string { + t.Helper() + return repo.Git("ls-remote", originOf(repo)) +} + +// stagesOf are the stages of runID's record. +func stagesOf(t *testing.T, repo *gittest.Repo, runID string) ([]string, State) { + t.Helper() + st, err := ReadState(repo.Root(), runID) + if err != nil { + t.Fatal(err) + } + var out []string + for _, e := range st.Record { + out = append(out, e.Stage) + } + return out, st +} + +// TestAStartDeclinedForAnotherReasonLetsNothingGo: a stale run that would be +// let go is not, where something else in the checkout declines the +// fast-forward: nothing is said of it and nothing is written to its record. +func TestAStartDeclinedForAnotherReasonLetsNothingGo(t *testing.T) { + repo, first, _ := behindWithNotes(t) + runID := staleLane(t, repo, nil) + repo.Write("notes/a.md", "mine\n") + tm, err, said := startSaying(t, repo) + startRefused(t, tm, err, "the checkout is behind origin's tip") + headIs(t, repo, first, "nothing moved") + if strings.Contains(strings.Join(*said, "\n"), "lets it go") { + t.Fatalf("a start declined for a dirty path lets no run go: %q", *said) + } + if stages, _ := stagesOf(t, repo, runID); slices.Contains(stages, StageFFLetGo) { + t.Fatalf("nothing is written to the run: %q", stages) + } +} + +// TestAnUnreadableControlRecordHoldsTheFastForward: a run whose control record +// cannot be read, its checkout not even opened, is held, never read as naming +// no driver, however long ago it moved. +func TestAnUnreadableControlRecordHoldsTheFastForward(t *testing.T) { + run := State{RunID: "run-2612020000000001", Key: staleIssue, UpdatedAt: time.Now().Add(-72 * time.Hour), + Lanes: []Lane{{ID: "lane-1", Stage: StageImplement}}} + got := judgeFFRun(filepath.Join(t.TempDir(), "gone"), run, time.Now(), readProcs) + if got.gone || !strings.Contains(got.why, "control record cannot be read") { + t.Fatalf("an unreadable control record holds: %+v", got) + } +} + +// TestAStartLetsGoAReservedStaleRunWithoutAPushAndOnce: a stale run whose +// hold had lapsed is let go with nothing pushed, the line saying so and +// naming the discard that ends it; the save keeps the run's date and writes no +// drive's mark, so no later start takes it up; and a later start behind +// origin again names it no more, counting it on one line. +func TestAStartLetsGoAReservedStaleRunWithoutAPushAndOnce(t *testing.T) { + repo, merged := behindCheckout(t) + bare := originOf(repo) + runID := staleLane(t, repo, nil) + reserveStale(t, repo, runID, time.Now().Add(-73*time.Hour)) + _, before := stagesOf(t, repo, runID) + refs := reservationRefs(t, repo) + tm, err, said := startSaying(t, repo) + if err != nil || tm.o.Options.remote == nil { + t.Fatalf("the drive lets the run go and starts: %v\n%s", err, strings.Join(*said, "\n")) + } + headIs(t, repo, merged, "the checkout is fast-forwarded") + lines := strings.Join(*said, "\n") + if !strings.Contains(lines, staleIssue+": its hold had lapsed") || !strings.Contains(lines, "`abcd implement step --run "+runID+" --discard lane-1`") { + t.Fatalf("the line says the hold had lapsed and names the discard: %q", *said) + } + if got := reservationRefs(t, repo); got != refs { + t.Fatalf("nothing is pushed for a lapsed hold:\n%s\nthen\n%s", refs, got) + } + stages, after := stagesOf(t, repo, runID) + if !after.UpdatedAt.Equal(before.UpdatedAt) || slices.Contains(stages, StageDriveReleased) || !slices.Contains(stages, StageFFLetGo) { + t.Fatalf("the save keeps the date, writes the let-go mark and no drive's mark: %v then %v, %q", before.UpdatedAt, after.UpdatedAt, stages) + } + peerPushes(t, repo, bare) + tm, err, said = startSaying(t, repo) + if err != nil || tm.o.Options.remote == nil { + t.Fatalf("the second start starts: %v\n%s", err, strings.Join(*said, "\n")) + } + lines = strings.Join(*said, "\n") + if strings.Contains(lines, "run "+runID) || !strings.Contains(lines, "1 run an earlier drive let go stays let go") { + t.Fatalf("a later start names the run no more and counts it: %q", *said) + } +} + +// TestALetGoReleasesOnlyAHoldThatCanBeTheRuns: the let-go releases, fenced, a +// hold of this copy's still inside its lease and claimed before the run last +// moved, as a plain release with the run's date kept; it leaves standing a +// hold claimed after the run last moved, and pushes nothing for one that had +// lapsed. +func TestALetGoReleasesOnlyAHoldThatCanBeTheRuns(t *testing.T) { + now := time.Now() + cases := []struct { + name string + claimed, moved time.Time + state, says string + }{ + {name: "live, claimed before the run moved", claimed: now.Add(-time.Minute), moved: now, state: claim.StateReleased, says: staleIssue + ": "}, + {name: "claimed after the run moved", claimed: now.Add(-time.Minute), moved: now.Add(-time.Hour), state: claim.StateLive, says: "after the run last moved"}, + {name: "lapsed", claimed: now.Add(-30 * time.Hour), moved: now.Add(-29 * time.Hour), state: claim.StateExpired, says: "its hold had lapsed"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + repo, _, _ := hookedOrigin(t) + runID := staleLane(t, repo, nil) + reserveStale(t, repo, runID, tc.claimed) + _, before := stagesOf(t, repo, runID) + refs := reservationRefs(t, repo) + var said []string + tm := newTerminal(repo.Root(), TerminalOptions{Stages: DefaultStages(), Say: func(s string) { said = append(said, s) }}) + tm.letGoForFF(ffRun{run: before, gone: true, why: "let go", moved: tc.moved}) + if len(said) != 1 || !strings.Contains(said[0], tc.says) { + t.Fatalf("one line says what became of the hold, %q: %q", tc.says, said) + } + if r := reservationOfRoot(t, repo.Root(), staleIssue, time.Now()); r.State != tc.state { + t.Fatalf("the hold is %s, want %s", r.State, tc.state) + } + stages, after := stagesOf(t, repo, runID) + released := slices.Contains(stages, StageReservationReleased) + if released != (tc.state == claim.StateReleased) || slices.Contains(stages, StageDriveReleased) || !after.UpdatedAt.Equal(before.UpdatedAt) { + t.Fatalf("a plain release line only for a release, no drive's mark, the date kept: %q, %v then %v", stages, before.UpdatedAt, after.UpdatedAt) + } + if tc.state != claim.StateReleased && reservationRefs(t, repo) != refs { + t.Fatal("nothing is pushed for a hold left as it stands") + } + }) + } +} + +// TestTheLetGoNamesADiscardOnlyForALaneIdItCanHoldTo: a lane id hand-edited +// into the state with shell words is never put in a command to paste; the +// line says plainly that the lane's id is not one the loop gives, and a valid +// lane beside it is still named with its discard. +func TestTheLetGoNamesADiscardOnlyForALaneIdItCanHoldTo(t *testing.T) { + run := State{RunID: "run-2612020000000001", Lanes: []Lane{ + {ID: "lane-1; rm -rf ~", Stage: StageImplement}, + {ID: "lane-2", Stage: StageImplement}, + }} + got := ffEndsFor(run) + if strings.Contains(got, "rm -rf") || strings.Contains(got, "--discard lane-1") { + t.Fatalf("no command carries the hand-edited lane id: %q", got) + } + if !strings.Contains(got, "`abcd implement step --run run-2612020000000001 --discard lane-2`") || !strings.Contains(got, "not one the loop gives") { + t.Fatalf("the valid lane is named with its discard and the other said plainly: %q", got) + } +} diff --git a/internal/core/implement/loop/terminal_ff_boundary_test.go b/internal/core/implement/loop/terminal_ff_boundary_test.go index 5baf884b25..ab4d6a97ee 100644 --- a/internal/core/implement/loop/terminal_ff_boundary_test.go +++ b/internal/core/implement/loop/terminal_ff_boundary_test.go @@ -20,10 +20,13 @@ import ( "path" "path/filepath" "slices" + "strconv" "strings" "testing" "time" + "github.com/intentdriven/abcd/internal/core/capture" + "github.com/intentdriven/abcd/internal/core/claim" "github.com/intentdriven/abcd/internal/gittest" "github.com/intentdriven/abcd/internal/gitutil" ) @@ -469,6 +472,480 @@ func TestALaneParkedOnItsPullRequestDoesNotHoldTheBoundaryBack(t *testing.T) { }) } +// TestARunNoDriverHasMovedForDaysDoesNotHoldTheBoundaryBack +// (iss-2612022203551074): a run whose driver is gone and whose state has not +// moved for days is judged at a boundary as the start judges it. One the +// start let go stays let go and is named no more, and one first met at a +// boundary is let go there on one line; either way the boundary brings the +// checkout up to origin's new tip. A reserved run let go stays no one's work: +// the start's take-up of what an interrupt left neither reserves it again nor +// steps it, and the drive's own renewal, made at its waits and agent calls, +// neither revives a hold of it nor dates it as moved, whether its hold had +// lapsed in this copy, is now another copy's, or is one of members of which +// one is released. Watched failing: the boundary listed every lane in +// progress, so the run the start had just let go declined each boundary's +// fast-forward; then the renewal revived the lapsed hold and dated the run +// now; then the start's take-up read the lapse note as a hold to work again, +// reserving and stepping the run, and the renewal still logged a hold found +// another copy's, or revived a lead beside a released member, dating the run. +func TestARunNoDriverHasMovedForDaysDoesNotHoldTheBoundaryBack(t *testing.T) { + const member = "iss-2612020000000002" + for _, tc := range []struct { + name string + atStart bool + // hold is the reservation the run records: "" for none, "lapsed" for + // this copy's lapsed hold, "another copy's" for that hold taken since + // by another copy, "member released" for a lapsed lead beside a + // released member. + hold string + }{ + {name: "let go at the start", atStart: true}, + {name: "first met at a boundary"}, + {name: "reserved, let go at the start and renewed", atStart: true, hold: "lapsed"}, + {name: "reserved, its hold now another copy's", atStart: true, hold: "another copy's"}, + {name: "reserved with members, one released", atStart: true, hold: "member released"}, + } { + t.Run(tc.name, func(t *testing.T) { + repo, bare, _ := hookedOrigin(t) + procsAre(t, terminalProcs(time.Now())) + dead := &LiveDriver{PID: 4242, StartUnix: time.Now().Add(-100 * time.Hour).Unix()} + if !tc.atStart { + tm, said := boundaryTerminal(t, repo) + ffAtBoundary(t, tm, said, repo, bare, staleLane(t, repo, dead)) + return + } + // The checkout starts behind origin, so the start judges the + // runs and lets the dead one go as it fast-forwards. + tip := peerPushes(t, repo, bare) + runID := staleLane(t, repo, dead) + claimed := time.Now().Add(-73 * time.Hour) + switch tc.hold { + case "lapsed": + reserveStale(t, repo, runID, claimed) + case "another copy's": + reserveStale(t, repo, runID, claimed) + q := otherCopy(t, bare, quinnEmail) + if _, err := claim.Reserve(q, claim.Request{Record: staleIssue, Footprint: []string{"AGENTS.md"}}, as(t, q, claim.Options{})); err != nil { + t.Fatalf("another copy reserves the lapsed issue: %v", err) + } + if _, err := claim.Fetch(repo.Root(), claim.Options{}); err != nil { + t.Fatal(err) + } + case "member released": + reserveStale(t, repo, runID, claimed) + releasedMember(t, repo, runID, member, claimed) + } + tm, said := boundaryTerminal(t, repo) + headIs(t, repo, tip, "the start fast-forwards past the dead run") + if tc.hold != "" { + takesNothingUp(t, tm, repo, runID, tc.hold == "lapsed") + // The drive's first wait renews what it holds. + tm.renewHeld() + } + ffAtBoundary(t, tm, said, repo, bare, runID) + }) + } +} + +// TestADrainsLaneLetGoAtTheStartIsTakenUpByThatDrive: the fast-forward's +// let-go frees the checkout and no more, so a run whose lane the drain lists +// is the drive's own work: the let-go line says the drive takes it up again, +// the start's take-up of what an interrupt left leaves it to the drain, and +// the drive's own step of the lane reserves it once and steps it once. +// Watched failing: the line said nothing of whose the run was. +func TestADrainsLaneLetGoAtTheStartIsTakenUpByThatDrive(t *testing.T) { + repo, bare, _ := hookedOrigin(t) + procsAre(t, terminalProcs(time.Now())) + peerPushes(t, repo, bare) + runID := staleLane(t, repo, &LiveDriver{PID: 4242, StartUnix: time.Now().Add(-100 * time.Hour).Unix()}) + reserveStale(t, repo, runID, time.Now().Add(-73*time.Hour)) + opened := time.Now().Add(-73 * time.Hour).UTC() + if err := writeDrain(repo.Root(), DrainState{SchemaVersion: DrainSchemaVersion, StartedAt: opened, UpdatedAt: opened, + Lanes: []DrainLane{{Issue: staleIssue, RunID: runID, OpenedAt: opened, Outcome: DrainLaneInProgress}}}); err != nil { + t.Fatal(err) + } + tm, said := boundaryTerminal(t, repo) + if !slices.ContainsFunc(*said, func(l string) bool { + return strings.Contains(l, "run "+runID) && strings.Contains(l, "the drain has its lane in progress, so this drive takes it up again") + }) { + t.Fatalf("the let-go line says the drive takes the drain's lane up again: %q", *said) + } + ref := claim.RefPrefix + staleIssue + before := gitIn(t, bare, "rev-list", "--count", ref) + ctx, steps := stubStages(t, tm) + if ended, err := tm.takeEarlier(ctx); err != nil || ended != "" || *steps != 0 { + t.Fatalf("the start leaves the drain's lane to the drain: %q %v, %d steps", ended, err, *steps) + } + if _, err := tm.driveLane(ctx, runID); err != nil { + t.Fatalf("the drive takes its lane up: %v\n%s", err, strings.Join(*said, "\n")) + } + after := gitIn(t, bare, "rev-list", "--count", ref) + if *steps != 1 { + t.Fatalf("the lane is stepped once, not %d times:\n%s", *steps, strings.Join(*said, "\n")) + } + if b, err := strconv.Atoi(before); err != nil || after != strconv.Itoa(b+1) { + t.Fatalf("the take-up reserves the run once: %s reservation commits then %s", before, after) + } +} + +// TestATakenOverDrainLaneLetGoStaysLetGo: a run whose lane the drain lists +// but no longer has in progress, one a person took over, is not handed out by +// the drain again, so its let-go line names the person's acts, as for a run +// no drain lists, and the start's take-up of what an interrupt left leaves it +// as it stands. Watched failing: the line said the drive takes it up again. +func TestATakenOverDrainLaneLetGoStaysLetGo(t *testing.T) { + repo, bare, _ := hookedOrigin(t) + procsAre(t, terminalProcs(time.Now())) + peerPushes(t, repo, bare) + runID := staleLane(t, repo, &LiveDriver{PID: 4242, StartUnix: time.Now().Add(-100 * time.Hour).Unix()}) + reserveStale(t, repo, runID, time.Now().Add(-73*time.Hour)) + opened := time.Now().Add(-73 * time.Hour).UTC() + if err := writeDrain(repo.Root(), DrainState{SchemaVersion: DrainSchemaVersion, StartedAt: opened, UpdatedAt: opened, + Lanes: []DrainLane{{Issue: staleIssue, RunID: runID, OpenedAt: opened, Outcome: DrainLaneTakenOver}}}); err != nil { + t.Fatal(err) + } + tm, said := boundaryTerminal(t, repo) + if !slices.ContainsFunc(*said, func(l string) bool { + return strings.Contains(l, "run "+runID) && strings.Contains(l, "no drive takes it up again until a person steps it") + }) { + t.Fatalf("the let-go line names the person's acts for a lane the drain no longer has in progress: %q", *said) + } + takesNothingUp(t, tm, repo, runID, true) +} + +// TestTheLetGoLinePromisesOnlyWhatTheDrivesPathsDo (dcn-2612031056281133): +// the sentence that ends a let-go line (ffWhoseNext), over every input it +// reads: the drain's state (readDrain: its read error, whether the file +// stands, whether the drain is live, and its lanes) live and listing the +// run's lane, live and not listing it, ended (stopped) and listing it, +// absent, or unreadable; the lane's outcome; whether this drive passed the lane over; whether a +// stop's mark stands on the run, with the person's stop still set or lifted; +// and whether the run is an issue's or an intent's. Each row names what the +// drive's own paths do with that same input, and the sentence must say that +// and no more: +// - an unreadable drain: the start's take-up (takeEarlier) takes nothing +// and the first move refuses on the same read, so this drive takes +// nothing up; +// - an ended drain hands nothing out: the first move begins a new drain +// with no lanes, so a lane the ended drain lists is read as unlisted, +// which the next start takes up only where a stop's mark stands; +// - a lane listed as anything but in progress or halted: takeEarlier skips +// it as the drain's and the drain hands out only lanes in progress, so it +// waits on a person, whatever its mark; +// - an issue's run with a stop's mark, unlisted or whose lane is halted or +// in progress: takeEarlier takes it over (stopOver, mayTake, TakeRun), or +// readmits a halted lane, or the hand-out's take-up (takeUp) takes it +// over, once no stop of the person's holds over it, in this drive or the +// next, whether this drive passed it over or not; +// - an unmarked lane in progress: handed out and taken up by this drive, or, +// where this drive passed it over (an in-memory list), by the next; +// - any other run (unmarked and unlisted, an unmarked halted lane, an +// intent's build): no path takes it up while the let-go mark stands. +// +// The drain opens lanes for issues only, so no row lists an intent's run. +// Watched failing: a marked lane this drive passed over was told it waits on +// a person, an unmarked one that no drive takes it up, and a marked run under +// an unreadable drain that a drive takes it over. +func TestTheLetGoLinePromisesOnlyWhatTheDrivesPathsDo(t *testing.T) { + const ( + unknown = "the drain's state could not be read, so this drive takes nothing up" + stopped = "it carries a stop's mark, so a drive takes it over as soon as no stop of the person's holds over it" + drain = "the drain has its lane in progress, so this drive takes it up again as the lane comes to hand" + next = "this drive passed its lane over, so the next drive takes it up again as the lane comes to hand" + person = "no drive takes it up again until a person steps it" + ) + type row struct { + drain string // "listed", "ended", "unlisted", "absent" or "unreadable" + outcome string + passed bool + stop string // "set", "lifted" or "none" + intent bool + want string + } + var rows []row + for _, stop := range []string{"set", "lifted", "none"} { + marked := stop != "none" + for _, intent := range []bool{false, true} { + rows = append(rows, row{drain: "unreadable", stop: stop, intent: intent, want: unknown}) + want := person + if marked && !intent { + want = stopped + } + rows = append(rows, row{drain: "unlisted", stop: stop, intent: intent, want: want}, + row{drain: "absent", stop: stop, intent: intent, want: want}) + } + for _, passed := range []bool{false, true} { + for _, outcome := range []string{DrainLaneInProgress, DrainLaneHalted, DrainLaneTakenOver, DrainLaneHandedBack} { + want := person + if marked { + want = stopped + } + rows = append(rows, row{drain: "ended", outcome: outcome, passed: passed, stop: stop, want: want}) + } + } + for _, passed := range []bool{false, true} { + for _, outcome := range []string{DrainLaneInProgress, DrainLaneHalted, DrainLaneTakenOver, DrainLaneHandedBack} { + want := person + switch { + case outcome != DrainLaneInProgress && outcome != DrainLaneHalted: + case marked: + want = stopped + case outcome == DrainLaneInProgress && passed: + want = next + case outcome == DrainLaneInProgress: + want = drain + } + rows = append(rows, row{drain: "listed", outcome: outcome, passed: passed, stop: stop, want: want}) + } + } + } + const runID = "run-2612030000000001" + for _, r := range rows { + name := fmt.Sprintf("%s/%s/passed=%v/stop=%s/intent=%v", r.drain, r.outcome, r.passed, r.stop, r.intent) + t.Run(name, func(t *testing.T) { + repo := gittest.NewRepo(t) + rel := filepath.Join(repo.Root(), filepath.FromSlash(DrainStateRel)) + if err := os.MkdirAll(filepath.Dir(rel), 0o755); err != nil { + t.Fatal(err) + } + switch r.drain { + case "unreadable": + if err := os.WriteFile(rel, []byte("{not the drain's state"), 0o644); err != nil { + t.Fatal(err) + } + case "listed", "ended", "unlisted": + now := time.Now().UTC() + st := DrainState{SchemaVersion: DrainSchemaVersion, StartedAt: now, UpdatedAt: now, + Lanes: []DrainLane{{Issue: staleIssue, RunID: runID, OpenedAt: now, Outcome: r.outcome}}} + switch r.drain { + case "ended": + st.Stopped, st.EndedAt = "outage", &now + case "unlisted": + st.Lanes = []DrainLane{{Issue: "iss-2612020000000009", RunID: "run-2612030000000009", OpenedAt: now, Outcome: DrainLaneInProgress}} + } + if err := writeDrain(repo.Root(), st); err != nil { + t.Fatal(err) + } + } + tm := newTerminal(repo.Root(), TerminalOptions{Stages: DefaultStages()}) + if r.passed { + tm.o.Drain.PassedLanes = []string{runID} + } + key := staleIssue + if r.intent { + key = "itd-10" + } + got := tm.ffWhoseNext(ffRun{run: State{RunID: runID, Key: key}, gone: true, stop: r.stop != "none"}) + if !strings.HasPrefix(got, r.want) { + t.Fatalf("the let-go line ends %q; want it to begin %q", got, r.want) + } + }) + } +} + +// TestAStopMarkedRunLetGoAtTheStartIsTakenOver: a run a person's stop halted +// days ago, the stop since lifted, is let go for the fast-forward and then +// taken over by the same start, as the stop's own rule says: the let-go line +// says so, and the take-over is said. Watched failing: the start passed over +// every run it had let go, so the lifted stop's run stayed halted. +func TestAStopMarkedRunLetGoAtTheStartIsTakenOver(t *testing.T) { + repo, bare, _ := hookedOrigin(t) + procsAre(t, terminalProcs(time.Now())) + asPat(t, repo) + // The run's issue is open in the ledger, so the take-over can reserve it. + if _, err := capture.Capture(capture.CaptureRequest{RepoRoot: repo.Root(), Text: "The page misses a flag (" + staleIssue + ")", + Severity: capture.SeverityMinor, Category: capture.Category("tech-debt"), Source: "manual-test", Slug: "flag", + FoundDuring: "the loop's tests", FoundAt: "AGENTS.md", ForceID: staleIssue, Remedy: "Name the flag on the page."}); err != nil { + t.Fatal(err) + } + repo.Commit("file " + staleIssue) + repo.Git("push", "-q", "origin", "main") + peerPushes(t, repo, bare) + runID := staleLane(t, repo, nil) + days := time.Now().Add(-72 * time.Hour).UTC() + root, err := os.OpenRoot(repo.Root()) + if err != nil { + t.Fatal(err) + } + c, err := readControl(root, runID) + if err != nil { + t.Fatal(err) + } + c.Stop = &RunStop{SetBy: "Pat Example", SetAt: days, NotedAt: days, HaltedAt: &days, Released: "released", FromFile: true} + if err := writeControl(root, runID, c); err != nil { + t.Fatal(err) + } + root.Close() + tm, said := boundaryTerminal(t, repo) + tm.o.Options.stopHome = t.TempDir() + ctx, _ := stubStages(t, tm) + if _, err := tm.takeEarlier(ctx); err != nil { + t.Fatal(err) + } + if !slices.Contains(*said, "took over "+staleIssue+", run "+runID+": its reservation is held again") { + t.Fatalf("the start takes the lifted stop's run over:\n%s", strings.Join(*said, "\n")) + } + if !slices.ContainsFunc(*said, func(l string) bool { + return strings.Contains(l, "run "+runID) && strings.Contains(l, "it carries a stop's mark, so a drive takes it over") + }) { + t.Fatalf("the let-go line says a drive's start takes the run over: %q", *said) + } +} + +// TestAFailedLetGoSaveLeavesNoLapseNote: where the run's let-go mark cannot be +// saved, no hold of the run is left to lapse, so the run carries no note +// without the mark that keeps every take-up off it, and the line says the +// let-go was not written. Watched failing: the note was written before the +// mark, and the mark's failed save was dropped in silence. +func TestAFailedLetGoSaveLeavesNoLapseNote(t *testing.T) { + repo, bare, _ := hookedOrigin(t) + procsAre(t, terminalProcs(time.Now())) + peerPushes(t, repo, bare) + runID := staleLane(t, repo, &LiveDriver{PID: 4242, StartUnix: time.Now().Add(-100 * time.Hour).Unix()}) + reserveStale(t, repo, runID, time.Now().Add(-73*time.Hour)) + dir := filepath.Join(repo.Root(), RunRelDir, runID) + if err := os.Chmod(dir, 0o555); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = os.Chmod(dir, 0o755) }) + _, said := boundaryTerminal(t, repo) + if err := os.Chmod(dir, 0o755); err != nil { + t.Fatal(err) + } + snap, err := claim.View(repo.Root(), time.Now()) + if err != nil { + t.Fatal(err) + } + if h, ok := snap.Lookup(staleIssue); !ok || claim.LeftToLapse(repo.Root(), staleIssue, h.Commit) { + t.Fatalf("no lapse note stands without the mark: %+v %v", h, ok) + } + if !slices.ContainsFunc(*said, func(l string) bool { + return strings.Contains(l, "run "+runID) && strings.Contains(l, "the let-go could not be written to the run's record") + }) { + t.Fatalf("the line says the let-go was not written: %q", *said) + } + if stages, _ := stagesOf(t, repo, runID); slices.Contains(stages, StageFFLetGo) { + t.Fatalf("no mark was written: %q", stages) + } +} + +// stubStages has every stage of tm count its call and end the returned +// context, so a step of a lane stops after one stage; it returns that context +// and the count. +func stubStages(t *testing.T, tm *terminal) (context.Context, *int) { + t.Helper() + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + n := 0 + for i := range tm.o.Stages { + tm.o.Stages[i].Run = func(c Context, l *Lane) (Outcome, error) { + n++ + cancel() + return Outcome{}, errors.New("a stage ran") + } + } + return ctx, &n +} + +// releasedMember adds member to runID's run as a member reserved at claimed, +// its reservation released on origin a minute later and fetched here. +func releasedMember(t *testing.T, repo *gittest.Repo, runID, member string, claimed time.Time) { + t.Helper() + for i, req := range []claim.Request{{Record: member, Footprint: []string{"notes"}}, {Record: member, Release: true}} { + at := claimed.Add(time.Duration(i) * time.Minute) + if _, err := claim.Reserve(repo.Root(), req, claim.Options{Now: func() time.Time { return at }}); err != nil { + t.Fatal(err) + } + } + if _, err := claim.Fetch(repo.Root(), claim.Options{}); err != nil { + t.Fatal(err) + } + root, err := os.OpenRoot(repo.Root()) + if err != nil { + t.Fatal(err) + } + defer root.Close() + st, err := ReadState(repo.Root(), runID) + if err != nil { + t.Fatal(err) + } + at := claimed.UTC() + st.Bundle = append(st.Bundle, Member{Issue: member, Footprint: []string{"notes"}, ReservedAt: &at}) + if err := writeState(root, st); err != nil { + t.Fatal(err) + } +} + +// takesNothingUp runs the start's take-up of what an interrupt left +// (takeEarlier) once the start has let runID go, and fails the test unless no +// reservation on origin moved, nothing was written to the run, no stage of it +// ran, and, where noted, the note leaving its hold to lapse still stands. +func takesNothingUp(t *testing.T, tm *terminal, repo *gittest.Repo, runID string, noted bool) { + t.Helper() + refs := reservationRefs(t, repo) + before, _ := stagesOf(t, repo, runID) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + ran := false + stub := func(c Context, l *Lane) (Outcome, error) { + ran = true + cancel() + return Outcome{}, errors.New("a stage of the run let go ran") + } + for i := range tm.o.Stages { + tm.o.Stages[i].Run = stub + } + if ended, err := tm.takeEarlier(ctx); err != nil || ended != "" { + t.Fatalf("the take-up goes on: %q %v", ended, err) + } + if got := reservationRefs(t, repo); got != refs { + t.Fatalf("no reservation is pushed for the run let go:\n%s\nthen\n%s", refs, got) + } + if after, _ := stagesOf(t, repo, runID); ran || !slices.Equal(after, before) { + t.Fatalf("the run let go is neither stepped nor written: ran %v, %q then %q", ran, before, after) + } + if !noted { + return + } + snap, err := claim.View(repo.Root(), time.Now()) + if err != nil { + t.Fatal(err) + } + if h, ok := snap.Lookup(staleIssue); !ok || !claim.LeftToLapse(repo.Root(), staleIssue, h.Commit) { + t.Fatalf("the note leaving the hold to lapse still stands: %+v %v", h, ok) + } +} + +// ffAtBoundary has origin move, runs two boundaries, and fails the test unless +// the checkout came up to origin's tip, no decline was said, and runID was +// said let go on exactly one line. +func ffAtBoundary(t *testing.T, tm *terminal, said *[]string, repo *gittest.Repo, bare, runID string) { + t.Helper() + tip := peerPushes(t, repo, bare) + for range 2 { + if ended, err := tm.boundaryFastForward(context.Background()); err != nil || ended != "" { + t.Fatalf("the boundary goes on: %q %v\n%s", ended, err, strings.Join(*said, "\n")) + } + } + headIs(t, repo, tip, "a run no driver has moved for days does not hold the boundary back") + lines := strings.Join(*said, "\n") + if strings.Contains(lines, "was not fast-forwarded") || strings.Contains(lines, "is in progress") { + t.Fatalf("no decline is said over the run let go: %q", *said) + } + n := 0 + for _, l := range *said { + if strings.Contains(l, "run "+runID) && strings.Contains(l, "lets it go") { + n++ + } + } + if n != 1 { + t.Fatalf("the run is said let go on one line, not %d: %q", n, *said) + } + if !slices.Contains(*said, movedLine(tip, 1)) { + t.Fatalf("the boundary's fast-forward is said: %q", *said) + } +} + // TestALaneSetAsideDeclinesTheBoundaryFastForward: a lane the drive set aside // is a lane in progress, so once origin moves the boundaries after it decline // the fast-forward, said once, naming its run, while the other lanes land.