diff --git a/tests/conftest.py b/tests/conftest.py index 5c4e3d18..551ae334 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -534,6 +534,15 @@ def pytest_configure(config): raise pytest.UsageError(refusal) if not config.pluginmanager.has_plugin(pgcluster.PLUGIN_NAME): config.pluginmanager.register(pgcluster, pgcluster.PLUGIN_NAME) + # SHORT TRACEBACKS UNLESS ASKED (#165, lane 3's ruling 6949488277 on lane + # 2's pre-review RV9-38 of P09, B1): pytest's default `auto` prints a long + # entry's frame arguments, a helper's raw stream or a statement's password + # among them, in the terminal and in --junitxml. `short` prints none. An + # explicit `--tb` other than `auto` stays as given; `--tb=auto` cannot be + # told from the default, so it becomes short too. `--tb=long`, + # `--fulltrace` (which forces long) and `--showlocals` are not secret-safe. + if config.getoption("tbstyle", "auto") == "auto": + config.option.tbstyle = "short" def pytest_report_header(config): diff --git a/tests/fixtures/lanes-edit-v1.1.0/SHA256SUMS b/tests/fixtures/lanes-edit-v1.1.0/SHA256SUMS new file mode 100644 index 00000000..1fa16287 --- /dev/null +++ b/tests/fixtures/lanes-edit-v1.1.0/SHA256SUMS @@ -0,0 +1 @@ +b68d0cbac35ac3bbac9e70790cafe63538821be582ca28cec0f7ec0f5c4745d2 lanes-edit.sh diff --git a/tests/fixtures/lanes-edit-v1.1.0/lanes-edit.sh b/tests/fixtures/lanes-edit-v1.1.0/lanes-edit.sh new file mode 100644 index 00000000..d28ed8f2 --- /dev/null +++ b/tests/fixtures/lanes-edit-v1.1.0/lanes-edit.sh @@ -0,0 +1,18977 @@ +#!/usr/bin/env bash +# +# lanes-edit.sh — the sanctioned writer for the estate lane registry (LANES.md). +# +# Protocol: ~/.agents/protocols/lane-collision-protocol.md, Rule 9 (registry in +# git) and Rule 10 (workstation designation), Amendment 3, 2026-09-09 — moved +# to the person's workspace repository by Amendment 5, 2026-09-10. +# +# WHERE THE REGISTER LIVES (Amendment 5, 2026-09-10; Amendment 9(a), 2026-09-13) +# `lanes/LANES.md` on `main` of THE PERSON'S OWN workspace repository — the +# `/-wip` that `$AGENT_PROTOCOL_ROOT/workspace.yaml` names, which +# is `opensoft/brett-wip` for the person this file was written for and +# `opensoft/scott-wip` for the next one. This file names no repository of its +# own: Amendment 5's second-person clause put a second person's register in a +# second repository, and Amendment 9 is what made that reachable. Direct commits to +# `main` are the norm THERE by design: the repository is excluded from the +# organisation's PR-only ruleset precisely so that a per-edit registry +# commit can land, which is what Rule 9 requires and what the orphan +# `lanes` branch of `opensoft/xFactory` used to be for. That branch is +# RETIRED, and its history came across whole with this file. +# +# Every path a lane already uses keeps resolving: +# `~/projects/xFactory/LANES.md` and `~/projects/xFactory/lanes-edit.sh` +# are symlinks into the checkout, placed by `link-estates`. +# This script never spells the checkout's own path, and since Amendment 9(a) +# it no longer derives it from its own location either: it reads +# `repository:` and `path:` from `$AGENT_PROTOCOL_ROOT/workspace.yaml`, the +# same pointer file `resume` and `status` already read. This file is an +# installed command in `~/.local/bin` with no register anywhere near it, so +# its own directory is evidence about the command and not about a person's +# data. Failing to find the workspace is a refusal naming +# `openRepoTools wip init`, never a guess. +# +# WHY THIS EXISTS +# LANES.md is edited by many concurrent lanes on more than one workstation. +# On 2026-09-08T23:46Z a whole-file write from one session dropped two other +# lanes' rows and a day of Rule 6 LANDED lines, and there was no history to +# recover from. Every write now goes through this script (or an equivalent +# single-line in-place edit followed by commit + pull --rebase + push), so the +# registry has a history and a lost row is one `git show` away. +# +# HAZARD — `sed -i` REPLACES A SYMLINK WITH A REGULAR FILE. +# ~/projects/xFactory/LANES.md is a SYMLINK into this worktree. Plain +# `sed -i` unlinks it and writes a new regular file, silently detaching the +# registry from git. Use this helper, or `sed -i --follow-symlinks`, or +# `cat tmp > LANES.md` (a redirect follows the symlink). `>>` appends, +# `cat`, `cut`, `head`, `tail`, `grep`, `python open(...,'a')` are all safe. +# +# USAGE +# lanes-edit.sh [--no-sweep|--sweep] verify-row +# lanes-edit.sh [--no-sweep|--sweep] set-row-state " · " +# lanes-edit.sh [--no-sweep|--sweep] replace-in-row "" "" [""] +# lanes-edit.sh [--no-sweep|--sweep] append-session-id "" "" [""] +# (the anchor is matched INSIDE THE +# SESSION CELL and nowhere else, and the +# text is appended at the END of it) +# lanes-edit.sh [--no-sweep|--sweep] append-line "" # LANDING/LANDED lines +# (attribution: $LANES_LANE, else the +# "lane " the text itself names) +# lanes-edit.sh [--no-sweep|--sweep] add-row "" +# lanes-edit.sh commit "" # commit a hand edit; with +# nothing staged, publish the stranded +# register and handoff commits (#194) +# lanes-edit.sh migrate-state-cells [--yes] # Amendment 13(e), once +# lanes-edit.sh retire-rows … [--reason ""] [--writer ] +# lanes-edit.sh archive-rows [--yes] # Amendment 19(d) +# +# AMENDMENT 19 — A CLOSED OR DORMANT LANE LEAVES THE LISTING +# lanes-edit.sh lanes [--closed] # CLOSED and DORMANT rows too +# lane-end --retire-dormant [--reason ""] [--yes] +# lanes-edit.sh archive-rows [--yes] +# +# CLOSED is a lane whose object log's last lane-kind line is `ENDED` or +# `RETIRED`; DORMANT is a ROW WITH NO OBJECT LOG and no live session here — +# the rows that predate Amendment 7 and that no `lane-end` can close, because +# it wants a live session or a log to write into. `lanes` lists neither by +# default; `--closed` adds them, and the NEXT FREE POSITION is computed over +# every row of the repository — the hidden ones and the archive included — so +# a retired `-` is never reissued. +# +# `lane-end --retire-dormant ` is a DRY RUN that names every dormant row +# of that repository with its start, its workstation and its state cell's +# head, and FLAGS the cells that say the work was unpushed, lost, a loss or +# owed, or that still say LIVE. With `--yes` it is ONE commit — `retire-rows` +# below it — creating each lane's log with a single `RETIRED` line that +# carries the row's own last words, and setting the row's state to +# `RETIRED · · ; was: `. +# +# AMENDMENT 13 — THE ROW IS CURRENT STATE; THE LOG IS HISTORY +# lanes-edit.sh set-row-state " · " +# lanes-edit.sh log NOTED lane: "" +# lanes-edit.sh log RULED lane: [→ ] "" +# lanes-edit.sh history [--since ] [--index] +# lanes-edit.sh history --all | --repo [--since ] [--index] +# lanes-edit.sh migrate-state-cells [--yes] +# +# The `state` column holds ONE PHRASE — ` · · ` — and +# every write REPLACES it. `set-row-state` stamps the UTC itself; the STATE is +# one of LIVE, PAUSED, LANDING #, LANDED, ENDED, RETIRED, HANDED OFF (Rule +# 6's reading of the cell is unchanged and is now the whole of what the cell +# says at that moment), and the line is at most 240 characters (ratified +# decision O1) carrying neither a `|` nor a second ` · `. +# +# `append-row-status` is RETIRED and refuses, naming these. It appended and +# never replaced, which is how the column that says where a lane IS came to +# hold 96,228 characters in one row and 7,016 in another after ONE day — a +# diary in a table nobody can read in the table. +# +# THE NARRATIVE GOES TO THE LANE'S OWN LOG, under two Amendment 7 verbs that +# are lane-kind lines and NOT transitions: `NOTED` is a status note and +# `RULED` a ruling recorded verbatim, with the object it bears on as its +# payload where there is one. Neither ever changes a lane's state on any +# object or on itself — `who`, `lane-end`, `lanes` and `swapped` skip them +# exactly as they skip `STARTED` and `RESUMED` — and `history` prints them in +# file order, which is the diary the cell used to be. +# +# `migrate-state-cells` is clause (e)'s ONE act, on Brett Heap's word: a DRY +# RUN by default, and with `--yes` one commit carrying the archive +# `lanes/archive/LANES-pre-amendment-13-.md`, every lane's log and the +# register. It REFUSES when no cell holds a ` · ` entry, so a second run is a +# no-op that says so. +# +# AMENDMENT 14 — THE DERIVED INDEX (`lanes-index`), WHICH NOTHING HERE ACTS ON +# lanes-edit.sh lanes … --index # the listing, out of the index +# lanes-edit.sh history … --index # the diary, out of the index +# lanes-edit.sh worktrees … --index # the inventory, out of its table (#161) +# +# The register's truth stays where it is. `lanes-index` (placed by +# `openRepoTools --install`) keeps a DERIVED copy — SQLite, or QA Postgres +# where this workstation is configured for it — written BEHIND the sources: +# after every write whose push LANDED, and after the mutex is released, this +# file starts one DETACHED `lanes-index sync` (stdin closed, never waited, +# its status never read; skipped where `lanes-index` is not on PATH or +# `LANES_INDEX=off`). No act reads the index or waits on it. `--index` is the +# only way a read consults it, typed per invocation, and it says on stderr +# which it read: `read: index () at register@; commits +# behind`, or `read: sources (index )` and the sources answer. +# +# THE INVENTORY HAS A TABLE TOO (opensoft/openRepoTools#161): `worktrees`, +# under the source `inventory:`, copied from `worktrees --all` +# by `lanes-index sync --source inventory` — which every inventory write +# (`set-lane-state`, `set-lane-tree`, the lifecycle follow, a rename's move +# of the control root) nudges exactly as a landed push nudges the register's. +# No act reads it: `lane-reconcile`, `lane-start` and `lane-end` read the +# sidecars and the disk. With `--index` the stderr line is `read: index +# () at inventory: synced `, followed by `(last error: +# )`, the last error `status` shows for that source: one a sync or a +# reconcile on this workstation refused or failed with, a `--dry-run` +# included, until a sync or a reconcile that is not a dry run succeeds. +# +# AMENDMENT 7 — the per-lane object log (`lanes/log/.md`) +# lanes-edit.sh log [→|← ] [""] [--text ""] +# lanes-edit.sh claim [--force] [--no-github] [--home owner/repo] +# lanes-edit.sh release [""] [--no-github] [--home owner/repo] +# lanes-edit.sh who | --lane | --landing owner/repo +# +# AMENDMENT 8 — swap and restart, the READ side (both read-only, never write) +# lanes-edit.sh swapped [] +# lanes-edit.sh session-start # the SessionStart hook; JSON on stdin +# +# AMENDMENT 12 — the name guard and the lock (the blocking hook) +# lanes-edit.sh guard # the UserPromptSubmit hook; JSON on stdin +# +# `guard` is the ONLY verb here that refuses a person's work. It reads the +# hook's JSON, takes the WINDOW from tmux, the SESSION's own name from the +# live record and the ROW from `origin/`, and where the three are not +# one name it REFUSES THE PROMPT (exit 2) with the triple and the one command +# that cures it. THE LOCK types `/rename ` into this pane for the TWO +# drifts that are not decisions — a name differing from the row's only by +# CASE, which is the same lane under Amendment 15, and a name that is a +# FORMER name of the row's lane, which is the same lane under Amendment +# 16(e) and is what a rename run from another window leaves behind. EVERY +# OTHER READABLE MISMATCH IS AN OFFER OF THREE CHOICES, answered `1` (allow +# this lane for this transcript), `2` (adjust the lane to the session) or `3` +# (adjust the session to the lane, which types the `/rename`) at the next +# prompt; an answer to a question the state has moved past is dropped rather +# than acted on, and the unreadable, ambiguous, duplicate and superseded still +# refuse outright. It is silent and cheap where the three agree, silent +# outside `$PROJECTS_ROOT` and silent for a subagent's prompt. +# +# AMENDMENT 16 — a lane is renamed by ONE WORD, in ONE COMMIT, and its old name +# resolves for ever +# lanes-edit.sh rename-lane [""] [--verbatim] [--no-github] +# +# `lane-rename ` on PATH is the word; this is its write. ONE +# commit, refused or whole, and its four moves are the amendment's clauses +# (b)–(e): the row's key cell becomes `` `` `` with `*(ex ``, +# renamed )*` beside it; `lanes/log/.md` is renamed to +# `lanes/log/.md` and gains a `RENAMED` line; the handoff the row names +# is renamed to the same date with `lane-` and gains a Rule 3 stamp, +# with the row's handoff column following; and `lanes/aliases.tsv` gains +# ` `. +# +# THE ALIAS TABLE IS WHAT MAKES THE OLD NAME KEEP WORKING (clause (e)). +# `canon_lane` — Amendment 15's resolver, which every `` argument and +# every `$LANES_LANE` already passes through — resolves a name with NO ROW +# through that table, case-insensitively, chains to their end, before it +# answers. So an old name in a line, a window, a session record or a person's +# typing lands on the current row, in every reader at once, rather than in a +# list of readers somebody has to keep complete. A ROW WINS OVER AN ALIAS: +# a name that is a lane today IS that lane, which is also what makes a rename +# back again readable. +# +# `RENAMED` is a LANE-KIND verb that changes no object's state. Every +# last-line state reader here enumerates the five verbs that DO +# (`STARTED PAUSED RESUMED ENDED RETIRED`), so the new verb is outside that +# rule by construction and no reader had to be taught to skip it. +# +# AMENDMENT 18 — ONE BINDING PER LANE +# lanes-edit.sh binding # where this lane is bound +# lanes-edit.sh request-handoff [--wait ] [--session ] +# lanes-edit.sh request-handoff --force "" +# +# A lane's BINDING is the `host`, `container` and `window` of its last +# `STARTED`/`RESUMED` with no `PAUSED`/`ENDED`/`RETIRED` after it, and those +# three sub-fields are written by `write_event` beside Amendment 11(c)'s +# `dir`/`profile`/`window` — read from `LANES_HOST`/`LANES_OS`/ +# `LANES_CONTAINER`, which the launcher exports, with clause (a)'s fallbacks. +# **Liveness is pronounced only from inside the binding's own host and +# container**: from anywhere else it is UNKNOWN and never dead, whatever +# `kill -0` of a pid in another namespace would say. The ONE exception is a +# window that is gone from a tmux server the two share, which is dead and is +# today's takeover path. A second place ASKS — `request-handoff` writes the +# line and pushes it, types `/handoff --exit requested by …` into the bound +# pane where that pane is here, and waits; an empty wait refuses with the +# facts and names `--force`, which is a second invocation that releases the +# binding on the bound session's behalf in the requester's own session field. +# The prompt guard answers both from the bound side (clauses (d) and (e)). +# +# AMENDMENT 18(h) — one live process per transcript +# lanes-edit.sh transcript-holders # every live process carrying it +# +# A transcript is held by ONE live process; the harness can fork one or resume +# one twice. This read is what `lane-start` asks before it binds or resumes an +# id, what `lane-end --retire ` proves a duplicate with, and what +# `guard` refuses a prompt on. It sweeps EVERY profile's `sessions/`, because a +# duplicate's record sits in another profile's — measured four times on +# 2026-09-14. +# +# A SWAP is a planned stop — a usage reset, a profile switch — and a RESTART +# is the launch that follows it. The RECORD a swap leaves is not a new file: +# it is the lane's own `PAUSED` line, payload +# `swap; window :; workstation `. A lane is SWAPPED +# on a workstation when that PAUSED is its LAST lane-kind line — no later +# RESUMED, STARTED, ENDED or RETIRED — and `swapped` lists those lanes, which +# is how a restart finds its lane once the new tmux session has lost the +# window name. `session-start` is the whole output of the SessionStart hook: +# it resolves the lane from the tmux window name, else from the session id in +# the hook's JSON, prints ONE block, and ALWAYS exits 0 — a hook that fails +# is a hook that breaks the session it was meant to orient. +# +# AMENDMENT 17 — the handoff is the swap, and the record names the agent +# lanes-edit.sh lane-agent # the last record's `agent ` +# lanes-edit.sh lane-transcript # its `transcript ` +# lanes-edit.sh lane-last # its LAST lane-kind line, as +# # +# lanes-edit.sh workspace-root # the workspace repository's path +# lanes-edit.sh log PAUSED … --utc # date a LATE record by its own field +# +# Clause (b) gives the `PAUSED` payload two sub-fields beside Amendment +# 11(c)'s `window`, `dir` and `profile`: `agent ` — `claude`, `codex`, +# or the launcher's name for whatever wrote the line, a manifest key (letters, +# digits, `.`, `_`, `-`) — and `transcript `, the agent's own +# resumable id where it has one. THE WRITER VALIDATES BOTH (`pause_subfields_check`, +# called from `write_event`) because the log is append-only: a malformed +# sub-field there is malformed for ever, and `lane-start --agent` launches on +# what it reads. `swapped` prints them as its sixth and seventh fields, after +# the five it already had, and a record written before this amendment carries +# neither — which is EMPTY in that output and 8 from the two reads, never a +# guess (Amendment 7(i)'s cutover rule). +# +# `--utc ` IS FOR THE LATE RECORD AND NOTHING ELSE (adoption act 7): the +# `PAUSED` a swap never left, written after the fact and dated by the moment +# the old session ENDED rather than by the clock of the shell writing it. It +# changes which instant the line NAMES and never where the line goes: the log +# is append-only and FILE ORDER is what every state read means by "last", so +# `lane-handoff --late` refuses to write one that would land after the +# relaunch's `RESUMED` — a lane that is running must never read as paused. +# +# `--home owner/repo` is an option of all FIVE of `claim`, `release`, `who`, +# `log` and `lane-end`, for a lane whose log has no STARTED line. All five +# resolve it AFTER the fetch (R30), because the STARTED line that refuses it +# may be a peer's and live only on `origin/`. +# +# An object is `owner/repo#`, `owner/repo:openspec/changes/`, `#` +# for the lane's OWN home repo, or `lane:` for the lane-kind lines. +# `lanes/repos.tsv` (`aliasowner/repo`) resolves an omitted owner and +# the register's legacy spellings; an unknown alias is refused, never guessed. +# A LANE'S HOME GOES THROUGH THE SAME TABLE (R20, Addendum 5) — `lane-start` +# resolves it before writing STARTED, and every comparison of an object's +# repository against a home resolves BOTH sides. A home is inherited by every +# `#` that lane writes, so a legacy org spelling there gave one GitHub +# issue two object keys and two lanes held it with no collision detected. +# +# STATE IS PER LANE: a lane's state on an object is its own LAST line naming +# it, and it HOLDS the object while that verb is open. Open is +# {CLAIMED, TAKEOVER, OPENED, LANDING, WITHDRAWN}; closed — and it closes +# only the writing lane's hold — is {RELEASED, CLAIM-LOST, CLOSED, LANDED}. +# +# THAT APPLIES TO A TAKEOVER TOO (R18, Addendum 5): lane B's TAKEOVER on an +# object supersedes lane A's CLAIMED only while the TAKEOVER is B's OWN LAST +# LINE on it. Once B writes RELEASED, CLOSED or LANDED there, A's later +# CLAIMED holds normally. A TAKEOVER is never removed from an append-only +# log, so treating one as superseding for ever made a legitimate re-claim +# invisible: `who` called a held object FREE and `claim` did not refuse the +# next lane. Known and deliberate: two lanes each ending on a TAKEOVER of one +# object are BOTH reported as holders — a visible conflict, and not reachable +# through the helpers, since `claim --force` takes over a stale CLAIMED only. +# +# AND "LAST" IS THE LAST LINE IN THE FILE (R14, Addendum 4). A lane's log is +# append-only and single-writer, so the ORDER OF ITS LINES is the order of +# that lane's writes. No state read here — `lane_objects`, `superseded_by`, +# PER_LANE_AWK, `who` in any mode, `lane-end`'s refusal, `claim`'s pre-check +# and its rescan — selects or orders lines by their UTC field. The UTC stays +# on every line as INFORMATION, and is compared only where a DURATION is the +# rule: Rule 1's four-hour staleness and Rule 6's thirty minutes, where a few +# seconds are immaterial. On 2026-09-11 this workstation's realtime clock was +# observed jumping ±25s in bursts and a log commit landed whose content +# carried a UTC 26s after its own committer date; a max-UTC read made that +# lane's newest line invisible. Two workstations never share a clock either. +# +# `claim` is Rule 1 as one act, and THE RACE IS DECIDED BY WHICH CLAIMED +# LANDS ON `main` FIRST, never by comparing timestamps: fetch, pre-check +# against `origin/main`, append, commit, push; on a rebase, rescan, and if +# another lane's claim is already there, write `CLAIM-LOST` and stop. Git's +# push serialization is the arbiter between workstations; the `mkdir` mutex +# below only serializes this one. +# +# EVERY STATE READ IS OF `origin/`, AFTER A FETCH — never of the +# working tree. What has LANDED is what other lanes can see; a working tree +# can be behind by a peer's whole day. `who`, the pre-check, staleness, the +# superseded filter, the crossing warning, `lane-end`'s refusal and +# `lane-start`'s home lookup all read the same source, so they cannot +# disagree with each other either. +# +# THE REGISTER'S ROWS ARE READ THE SAME WAY (R19, Addendum 5). The session +# cell, the handoff path and the workstation column come from +# `git show origin/:lanes/LANES.md`; nothing in `who` reads the +# working tree. THE ONE EXCEPTION IS THE `live-holder` SUBCOMMAND, and only +# its id SET (R25, Addendum 6): it is the published row's union this +# checkout's, because a session stamps its uuid on the row with +# `replace-in-row` and that write is a LOCAL COMMIT until its push lands — +# read from `origin` alone the rename gate would not see the uuid of the very +# session it is being asked to rename over, would answer 8, and `lane-start` +# would take the name. That is what mints ` (2)` (AGENTS.md rule 7). +# Liveness fails closed, so an id `origin` has not seen is a reason to refuse +# a rename, never to allow one, and nothing that PRINTS uses the union. +# +# A LANDED CLOSES THE LANDING IT ANSWERS (R17, Addendum 5): `who --landing` +# pairs them by (lane, PR) in FILE ORDER and keys the result on +# (lane, repository, PR). Most of the register's LANDED lines carry no +# `into main` clause, and keying those on the repository they name +# reported 232 phantom merge holds where one was real. +# +# openRepoTools#91 — THE CRASH-CONSISTENT LANE LIFECYCLE AND THE INVENTORY +# lanes-edit.sh lane-state +# lanes-edit.sh set-lane-state \ +# [--expect ] [--expect-generation ] \ +# [--expect-operation ] [--operation ] \ +# [--owner ] [--agent ] [--profile ] \ +# [--kind ] +# lanes-edit.sh lane-trees +# lanes-edit.sh set-lane-tree [--checkout ] \ +# [--branch ] [--head ] [--upstream ] \ +# [--dirty ] [--unpushed ] [--writer ] \ +# [--generation ] [--operation ] +# lanes-edit.sh lane-tree-now +# lanes-edit.sh project-legs # an assembly's legs, by path (T018) +# lanes-edit.sh lane-reconcile +# lanes-edit.sh worktrees [ | --all] [--index] [--fetch] +# lanes-edit.sh pathspec-check ... # opensoft/openRepoTools#162 +# +# A lane is RUNNING, SWAPPING, SWAPPED or CLOSED, and WHICH OF THOSE IT IS +# WITH NO LIVE HOLDER is what says where its session stopped: `RUNNING` with +# no holder is an UNGRACEFUL STOP (nothing was handed off) and `SWAPPING` +# with no holder is an INTERRUPTED SWAP (the handoff began and did not +# finish). Every transition carries a monotonic `generation` and a unique +# `operation`, and `--expect*` is the compare-and-swap that refuses a stale +# finalizer with exit 7 rather than letting it overwrite a newer owner. +# +# NO LANE-KIND VERB IS ADDED TO THE APPEND-ONLY LOG BY THIS CHANGE. Amendment +# 7's five state verbs stand and every reader of them is untouched (Amendment +# 18(g) has since added a sixth lane-kind verb, `HANDOFF-REQUESTED`, which +# changes no state; this adds none). This is a SNAPSHOT beside that +# history, local to the workstation, replaced atomically, and never committed +# — see the section above the dispatcher for where it lives and why it is +# neither in the register nor inside a git worktree. +# +# `set-lane-tree` records ONE worktree of the lane — its path, checkout, +# branch, head, upstream, dirty and unpushed counts and writer — as an +# OBSERVATION; `lane-reconcile` recomputes every one of them and REPORTS the +# difference. It resets nothing, deletes nothing and creates nothing: a +# missing tree's only rebuild is the estate's own `resume `, and a +# missing tree that last held uncommitted work is reported as possible loss, +# because no metadata reconstructs a file's contents. +# +# `lane-tree-now` IS THAT OBSERVATION ON ITS OWN, and it is here so that the +# handoff's WRITERS section, the sidecar it files and the reconciliation that +# recomputes against it are one implementation with one error handling. A git +# read that FAILED is never converted into a clean-looking value by any of the +# three: `unknown`, `none` and `0` are answers, and the reads that could not +# be made are said instead (R22, Amendment 7(d)). +# +# THE TWO WRITERS REFUSE A SIDECAR THEY CANNOT READ. A snapshot or a tree +# record carrying a schema this helper does not write is never replaced — a +# reader that fails closed and a writer that walks past it protect nothing — +# and neither is one of THIS schema that is not a whole record: a key its +# writer writes missing or out of shape, or an id that is not its file's +# (#115). `set-lane-tree`'s `--generation`/`--operation` are COMPARED with +# the lane's own snapshot under the mutex before the record is filed, so a +# poll from an operation a recovery has superseded, or from one already +# finalized (`SWAPPED`, #114), cannot be filed over the current one. +# +# THE SEAM — A MANAGED-OWNED LANE IS NOT THIS TOOLING'S (Brett Heap's ruling of +# 2026-10-04, verbatim: "managed ledger owns enrolled lanes; #97 owns legacy — +# rework both") +# lanes-edit.sh managed-projection +# +# 0 with the owner on stdout where the lane's register row carries a valid +# managed-owner marker, 8 where it carries none (a LEGACY lane, which is +# every lane today), 1 where it carries managed-owner vocabulary that does +# not parse as a marker, where only THIS checkout's row carries the +# vocabulary (#157 item 4a), or the register could not be read (ownership +# UNKNOWN), 64 usage. Every legacy act that would write for a lane asks this +# first and refuses a managed lane with 2 and an unknown one with 1, before +# a byte is written: the lane-kind lines `log` writes (STARTED, RESUMED, +# ENDED, RETIRED), `set-lane-state`, `set-lane-tree`, `retire-rows`, +# `set-row-state`, `replace-in-row` and `rename-lane`, the entry of +# `lane-start` and `lane-handoff`, and `lane-end` before its first act on +# each of its paths. `lane-reconcile` pronounces +# nothing on a managed lane (`VERDICT managed-owned`), and no legacy writer +# may write the marker's vocabulary into a row at all. +# +# EXIT CODES — every subcommand, one table, no two meanings on one number +# 0 done (and #194's publish whose queue `pull --rebase` emptied) +# 1 environment (no register, no writer) +# 2 refusal: bad arguments, the object is held, an unknown alias, a +# checkout that cannot be rebased, — Amendment 15 — a register holding +# two rows whose lane names differ only by case, which every writer and +# `canon-lane` refuse until 15(d)'s merge, or AMENDMENT 12's BLOCKED +# PROMPT, or — opensoft/openRepoTools#162 — a commit whose pathspec +# would stage bytecode, a cache or a virtual environment +# (`commit_push`, `pathspec-check`), or — #194 — `commit` refusing to +# publish local commits that are not register or handoff writes, from a +# checkout whose HEAD is off the branch, or that it cannot read +# (`cp_publish_fence`), and pushes none of them. EIGHT MEANINGS ON ONE NUMBER, and they +# stay readable only because of where each can occur: bad arguments to a +# subcommand that predates Amendment 11; `register-row`'s "not lane-shaped"; +# AN UNKNOWN SUBCOMMAND (the `*)` arm below), which is how a caller detects +# a helper predating the amendment that added the read it asked for; and +# Amendment 11's container refusal. The last is on WRITERS ONLY (the +# dispatcher guard), so no READ can return it and clause (h)'s +# fall-to-the-next-rung rule is unaffected by it. +# THE SIXTH IS NOT THIS FILE'S NUMBER AT ALL: 2 is what a `UserPromptSubmit` +# hook must exit to BLOCK a prompt (code.claude.com/docs/en/hooks), so +# `guard` spends the one number the harness reads, and every refusal it +# makes — a mismatch, an unreadable read, a pending offer's question and +# its answer — is that 2. `guard` never exits anything else but 0. +# 64 usage — a caller's bad arguments to one of the reads Amendment 11 added +# (`window-lane`, `lane-dir`, `lane-profile`, `last-session`, `forks`, +# `duplicate-holder` (issue #39), `workstation`, `fetch-age`, `lanes`, +# `session-lane`, and `swapped`, which +# took it first), to Amendment 13's `history`, and to Amendment 15's +# `canon-lane`, which takes the same +# contract because its four callers sit in front of a launch as those do. IT WAS IN NO TABLE AT ALL until this round (F-X16), while +# being the code the contract gives every one of those reads. +# +# 66 EX_NOINPUT — AMENDMENT 16(e)'s ALIAS TABLE COULD NOT BE READ, and +# `canon-lane` is the one verb that spends it. `lanes/aliases.tsv` is what +# makes a renamed lane's OLD name resolve, so a table nobody can read is +# not an estate with no renames: a former name would read as a lane nobody +# has, and `lane-start` would append a SECOND row for one that has been +# running all day. It is a number of its own because 2 already carries two +# meanings to `lane-start`, `lane-end`, `lane` and `lane-handoff` — 15(d)'s +# two-rows refusal, told by its words, and the unknown-subcommand 2 of an +# older helper, which they carry on past — and a third meaning there is the +# fail-open this refusal exists to close. +# +# WHY A SECOND USAGE CODE RATHER THAN 2. A read in front of a launch has to +# tell "you called me wrong" from "this helper has never heard of you" — +# and the second of those IS a 2, emitted by the `*)` arm, on every +# workstation until adoption act 3's install reaches it. One number cannot +# carry both without the caller guessing, so the newer reads spend a number +# of their own and the older half of this file keeps 2 where it always was. +# Clause (h)'s table is the contract for which read uses which. +# 3 the edit is never a permanent loss, but this attempt cannot confirm +# whether it also reached origin. THREE CAUSES (Copilot round 3 on #50, +# 5203261904, naming the other two this row used to leave out): a +# rebase conflict this attempt could not resolve — not pushed BY THIS +# ATTEMPT; a later write from this checkout may already carry it to +# origin, so LOOK by CONTENT before you retry (round 4, 5203455553: +# SHA ancestry alone misses a peer's rebase of it, which changes the +# hash but not the patch); `git_timeout_die`'s network timeout on a +# push OR a pull, where a hung one often already landed; or six +# attempts exhausted because a peer's own uncommitted file blocks +# every rebase. +# 4 the mutex could not be taken within 60s +# 5 an edit moved more than one line and was refused — or, Amendment 15, a +# lane's object log could not be renamed to the row's own spelling — or, +# #120 item 1, a register rewrite (`replace_line`, `delete_lines`) whose +# copy, write or result could not be proved; where the write had cut the +# register short its earlier bytes are put back first, and the refusal +# says which of the two the register holds +# 6 git add / commit / push failed +# 7 ANOTHER ACT GOT THERE FIRST, and this one wrote nothing. `claim`: +# CLAIM-LOST, another lane's claim landed on main first. +# `set-lane-state`: the lifecycle fence did not match — the state, the +# generation or the operation id moved under this process — so a stale +# finalizer cannot overwrite a newer owner (openRepoTools#91). +# `set-lane-tree`: the `--generation`/`--operation` this observation was +# taken under is no longer the lane's — or the lane is `SWAPPED` and the +# operation it names is finished (#114) — so a superseded poll cannot be +# filed over the current inventory. ONE MEANING ON THE NUMBER, in three +# places: you lost the race. +# 8 no record — `who` found nothing; `lane-objects` has no log file for the +# lane; `live-holder` READ this workstation's session records and none of +# them holds it; `swapped` found no lane swapped on the workstation; +# `history` READ the lane's log and it carries no `NOTED` or `RULED` line; +# `window-session` found no live session in the window. A read that could +# not be performed is never 8 (R22). `session-start` never exits 8, or +# anything but 0: it is a hook. `guard` never exits 8 either — it is a hook +# too, and a BLOCKING one, so its two codes are 0 and 2 (see 2 above). +# 9 CLAIM-LOST — issue #30's own dead-lane verdict could not be +# reconfirmed before this takeover's push landed: the source lane's own +# log moved past its terminal line, a live session on this workstation +# now backs it up, or that could not be read at all (`claim` only, +# `--force` over a dead lane's hold). NEVER coerced to 7: that code +# means a RIVAL's claim landed first, and this is the same lane the +# takeover was granted over, alive again rather than beaten to main. +# 10 THE RECORD IS THERE AND COULD NOT BE READ, which is the other half of 8 +# and never 8 itself (Copilot round 6 on openRepoTools#97). `lane-state` +# spends it for a lifecycle snapshot that EXISTS at the control root and +# cannot be opened — a permission, an I/O error, a name whose bytes are +# gone. 8 says *this lane has no snapshot*, which a launcher answers by +# going on; 10 says *this lane may be mid-crash and nobody could look*, +# which it answers by reading the lane by hand. One number could not carry +# both, and the one that was carrying both was 8 (R22, Amendment 7(d)). +# IT WAS 9 until main's #61 landed with 9 as `claim --force`'s abandoned +# takeover; each PR had taken 9 as unused, and the later one moved. +# `lane-trees` spends it for an inventory directory that EXISTS and +# cannot be listed, which is never "this lane recorded no tree" (#157 +# item 4e). And `lane-state` spends it for a snapshot of this schema that +# opens and is not a WHOLE record — cut short, or a key missing or out of +# shape (#115): nothing can be read out of it as a snapshot, so it is +# the same answer, and the message says which of the two it is. +# +# --no-sweep (DEFAULT, added 2026-09-09 after 0d84d34/a1f2438 swept another +# lane's uncommitted hand edit into an unrelated commit): every mutating +# subcommand checks, before making its own edit, whether LANES.md is +# already dirty. If it is, that content is someone else's — never this +# invocation's — so it is committed FIRST, on its own, as +# `LANES(pre-existing@): capture an uncommitted registry edit +# (row )`, before this invocation's own edit is made and committed. +# A WARNING (with `git diff --stat` and the first 200 chars of every +# changed line) always prints first. This never fails the call — the +# write still goes through. Amendment 7's `log`, `claim` and `release` take +# the same capture for the REGISTER between the two halves of their +# dirty-checkout guard, which is why a peer's half-written `lanes/LANES.md` +# does not refuse them (Addendum 3, R11); any OTHER modified tracked file +# still does, and is refused before the capture rather than after it. +# --sweep — the old behaviour: leave the pre-existing content staged so it +# lands inside this invocation's own commit. Still warns exactly as above, +# and appends " + sweeps uncommitted edit to row " to the commit +# subject, so the sweep is never silent. +# `commit` has no edit of its own to separate from a pre-existing one — its +# job IS to wrap whatever is already dirty. It instead warns and appends +# the same " + sweeps uncommitted edit to row " note when the dirty +# content touches a row other than the caller's own $LANES_LANE. +# +# ENVIRONMENT +# LANES_FILE registry path (default: /LANES.md) +# LANES_DIR dir holding it (default: /lanes) +# LANES_REPO checkout root (default: the `path:` in +# $AGENT_PROTOCOL_ROOT/workspace.yaml, +# checked to be a checkout of the +# `repository:` beside it — Amendment +# 9(a); never a literal path) +# LANES_WORKSPACE_ROOT that `path:`, overridden (the test seam; nothing else +# sets it) +# AGENT_PROTOCOL_ROOT dir holding workspace.yaml (default: ~/.agents) +# LANES_PATH pathspec of the register RELATIVE to LANES_REPO +# (default: `lanes/LANES.md`, derived +# with `git rev-parse --show-prefix`) +# LANES_BRANCH branch to commit on (default: main) +# LANES_LANE lane name for the commit subject when no lane argument +# LANES_WORKSTATION workstation name (the launcher exports it; else +# `hostname -s` outside a container, +# and inside one WITH NO VALUE every +# WRITER refuses — Amendment 11, +# decision 8(d), R-A11-14) +# LANES_HOST the MACHINE's short hostname as it reads OUTSIDE any +# container (Amendment 18(a); the launcher exports it). +# Fallback: `hostname -s` outside a container, and inside +# one the Rule 10 workstation name +# LANES_OS linux | macos | wsl | windows — the HOST's, as the person +# means it. Fallback: the kernel probe (Darwin -> macos, +# /proc/version naming microsoft -> wsl, linuxkit -> macos, +# any other Linux -> linux). `windows` is a launcher's word +# only: this file is bash and runs in WSL2 there +# LANES_CONTAINER the bench's name (`py-bench`, …). Fallback: inside a +# container, that container's own `hostname` — read LIVE at +# every write, never cached; outside one, `none` +# LANES_POLL_SECONDS the interval `request-handoff`'s wait polls the published +# log at (default 15). The test seam, and only that +# LANES_IN_CONTAINER 1|0 force the container probe (test seam) +# LANES_NO_GIT=1 edit only, no commit/push (used by the test harness) +# LANES_LOG_DIR the object logs (default: /log) +# LANES_REPOS_TSV the per-wip alias OVERRIDE (default: /repos.tsv) +# LANES_REPOS_TSV_SHIPPED the organisation's alias table shipped by +# openRepoTools (default: beside this command) +# LANES_ALIASES_TSV Amendment 16(e)'s LANE alias table, ` +# ` (default: /aliases.tsv) +# LANES_ALIASES_PATH its pathspec relative to LANES_REPO +# (default: `lanes/aliases.tsv`) +# LANES_SESSION this session's TRANSCRIPT uuid, for the event lines +# (default: the last uuid in the lane's row — Amendment 6(b)) +# LANES_LANE_DIR the lane's checkout, for project.yaml leg detection +# (default: $PROJECTS_ROOT/) +# LANES_NO_GITHUB=1 skip every `gh` call (tests, offline); same as --no-github +# LANES_NO_FETCH=1 skip the `git fetch` a read does first (offline; tests). +# It does NOT change WHAT is read: every state read is of +# `origin/`, which without the fetch is simply the +# ref as it already stands here. +# LANES_STALE_HOURS Rule 1's stale threshold, reused (default: 4) +# LANES_DEBUG non-empty: a refusal also prints its exit code +# LANES_INDEX=off no `lanes-index sync` after a write, and `--index` reads +# the sources (Amendment 14). It never turns a read ON: +# only a typed `--index` does +# +# Dependencies: bash, git, coreutils. No sed/awk substitution on the payload — +# every edit is computed with bash string operations, so `/`, `&`, `\` and `|` +# in the text are literal. + +set -u + +# Parse the global flags before probing paths, git or workstation identity. +# A profile-only prompt must not depend on any of that lane infrastructure. +SWEEP_MODE="no-sweep" +while [ $# -gt 0 ]; do + case "${1-}" in + --no-sweep) SWEEP_MODE="no-sweep"; shift ;; + --sweep) SWEEP_MODE="sweep"; shift ;; + --no-github) LANES_NO_GITHUB=1; shift ;; + *) break ;; + esac +done + +if [ "${1-}" = guard ] && [ "${CLAUDE_NO_LANE:-}" = 1 ]; then + if [ "$#" -ne 1 ]; then + printf '%s\n' "lanes-edit: usage: guard (the UserPromptSubmit hook; the hook's JSON on stdin)" >&2 + exit 2 + fi + exit 0 +fi + +SELF="$0" +if command -v readlink >/dev/null 2>&1; then + RESOLVED="$(readlink -f "$SELF" 2>/dev/null || printf '%s' "$SELF")" +else + RESOLVED="$SELF" +fi +SCRIPT_DIR="$(cd -- "$(dirname -- "$RESOLVED")" && pwd)" + +# --- THE WORKSPACE REPOSITORY (lane-collision-protocol Amendment 9(a)) ------- +# +# The person's data — the register `lanes/LANES.md`, the object logs +# `lanes/log/`, the handoffs, the manifests `park` writes, and a +# `lanes/repos.tsv` override — is found through +# `$AGENT_PROTOCOL_ROOT/workspace.yaml`, and NEVER from this file's own +# location. `resume:466` and `status:1673` already read that same file under +# that same name, and Amendment 9(a) mints no second one: a second way to find +# it is a second answer. +# +# Deriving it from here stopped being POSSIBLE the moment this became an +# installed regular file in `~/.local/bin` with no register anywhere near it, +# and it stopped being WANTED for a subtler reason: a file's location on disk +# is evidence about the file, not about a person's data. +# +# THESE FOUR FUNCTIONS ARE A DELIBERATE COPY, byte for byte, across +# `lanes-edit.sh`, `lane-start`, `lane-end` and `link-estates` — the same trade +# openRepoTools already makes for its own fetch shim (`openRepoTools:93-100`). +# A shared `lanes-common.sh` would be a TENTH file for `--install` to place and +# a broken helper the first time somebody copied only some of them. Each of +# these is one file a person has on PATH. +# +# FAILING TO FIND IT IS A REFUSAL, NEVER A GUESS. No file, no `path:`, no +# `repository:`, or a `path:` that is not the root of a checkout of the +# `repository:` named beside it → the caller refuses, exit 1 — the code +# `lanes-edit.sh` has always used for *registry not found* — with the fix +# named: `openRepoTools wip init`. Nothing here ever creates that file, writes +# a register, or falls back to a path derived from its own location. THE +# CHECKOUT TEST IS NEW: nothing validated it before this, so a `path:` pointing +# at some other repository used to be accepted and now is not. +# +# `LANES_WORKSPACE_ROOT` is the test seam and the only override — the seam +# `lane-start` already spelled for handoff resolution, widened to the whole +# question so `test_lane_helpers.sh` can point every helper at one sandbox. +# --- BEGIN shared workspace resolver (Amendment 9(a)) ---------------------- +# BYTE-IDENTICAL IN ALL FOUR LANE HELPERS, and held there by +# `tests/test_repo_hygiene.py`. The estate commands carry the same discipline +# for their own estate resolver and for the same reason its guard gives: a +# drifted copy is TWO ANSWERS to one question, and "where is this person's +# workspace" is exactly the question Amendment 9(a) exists to give one answer +# to. Edit it in one file and the test names the other three. +LANES_WS_WHY="" + +lanes_ws_yaml() { printf '%s\n' "${AGENT_PROTOCOL_ROOT:-$HOME/.agents}/workspace.yaml"; } + +# `key: value` at the TOP LEVEL only, first occurrence, with an inline `#` +# comment and surrounding quotes stripped and a leading `~` expanded against +# $HOME (nothing expands a bare `~` inside a file). The anchored `^key:` never +# reaches into the INDENTED `orgs:` map, which Amendment 9(a) puts out of +# scope: these helpers read `repository:` and `path:` and nothing else, because +# one register in the first workspace repository is the whole rule — the +# register never follows that map. Two lines of sed, because a YAML parser is +# not a dependency any of these files will take for one scalar. +lanes_ws_field() { + local v + v="$(sed -n -e "s/^$1:[[:space:]]*//p" "$2" 2>/dev/null | head -n 1 | + sed -e 's/[[:space:]]*#.*$//' -e 's/[[:space:]]*$//')" + v="${v%\"}"; v="${v#\"}" + v="${v%\'}"; v="${v#\'}" + case "$v" in + '~') v="$HOME" ;; + '~/'*) v="$HOME/${v#'~/'}" ;; + esac + printf '%s\n' "$v" +} + +# THE WORKSTATION'S NAME IS READ, NEVER INVENTED — AND NEVER `hostname` INSIDE A +# CONTAINER (lane-collision-protocol Amendment 11, ratified decision 8(d), as +# corrected by A11 Addendum 3's `R-A11-14`). +# +# WHAT WENT WRONG. `opensoft/brett-wip` `origin/main` carries SIX lines in +# `lanes/log/openRepoProject-1.md` whose workstation is a container id — five +# `@0e7d1a79a07e`, one `@55cceb3e5bc9` — in an append-only file, written by every +# writer inside that container and not only by Evidence 6's fork. A row on a +# workstation that does not exist is a row no reader can match, no crossing can +# detect and no `swapped ` can answer for; and the log is never rewritten, so +# each one is wrong for ever. +# +# WHO OWNS THE VALUE. `R-A11-14`: the **workBenches launcher**, which runs on the +# host and exports `LANES_WORKSTATION=` into every +# session AND every container it starts, beside the `CLAUDE_PROFILE_NAME` it +# already exports. These helpers READ it. They do not write it, they do not +# derive it from a second file, and THEY NEVER SUBSTITUTE A PLACEHOLDER: an +# `@unknown-workstation` is the same defect one field along from the `unknown` +# clause (e) refuses in the session field, and the rejected alternative — a +# `workstation:` key in `workspace.yaml` — is a SECOND PLACE FOR THE TRUTH TO BE +# WRONG beside the variable the launcher already sets. +# +# THE THREE ANSWERS, as ``: +# +# seam `$LANES_WORKSTATION` is set. This is the ordinary case +# wherever the launcher started the session. +# hostname no seam, and this is NOT a container: `hostname -s`, which +# is what the seam has defaulted to since Amendment 6 and +# what every row written before this rung was written by. +# container-unset no seam, and this IS a container. The NAME still answers, +# because a read in front of every launch may not refuse — +# it will simply match nothing, which is the honest answer — +# but every WRITER refuses, exit 2, naming the variable and +# the launcher that sets it. +# +# IT ANSWERS AS A PAIR, AND THAT IS NOT A STYLE CHOICE. A caller reads the name +# with `$(lanes_workstation)`, which is a COMMAND SUBSTITUTION and therefore a +# subshell: a global the function set there dies with it. The source is on the +# same line as the name, which is the only way out of a subshell there is. +# +# $LANES_IN_CONTAINER 1 or 0, forcing the probe. THE TEST SEAM, and nothing +# else sets it: the suite must be able to exercise both +# halves of this rule on one host, and the host it runs +# on is a container exactly when it is. +lanes_in_container() { + case "${LANES_IN_CONTAINER:-}" in + 1) return 0 ;; + 0) return 1 ;; + esac + [ -e /.dockerenv ] || [ -e /run/.containerenv ] +} + +lanes_workstation_pair() { + local v + if [ -n "${LANES_WORKSTATION:-}" ]; then + printf '%s\t%s\n' "$LANES_WORKSTATION" seam + return 0 + fi + v="$(hostname -s 2>/dev/null || hostname 2>/dev/null || printf 'unknown')" + if lanes_in_container; then + printf '%s\t%s\n' "$v" container-unset + else + printf '%s\t%s\n' "$v" hostname + fi +} + +# THE NAME ALONE, which is what every writer of the workstation column wants. +lanes_workstation() { lanes_workstation_pair | cut -f1; } + +# The ONE SENTENCE a writer refuses with, in one place, so the three writers +# cannot word it three ways. Empty on every other source, so +# `[ -n "$(lanes_workstation_why "$src")" ]` is the whole of the test. +lanes_workstation_why() { # + [ "${1:-}" = container-unset ] || return 0 + printf '%s\n' "this is a container and \$LANES_WORKSTATION is not set, so there is no workstation name to write. This host's own \`hostname\` is the CONTAINER'S id, not a workstation, and a row on a workstation that does not exist is a row no reader can match — in a log nothing ever rewrites (Amendment 11, decision 8(d); R-A11-14). The value is the workBenches launcher's to export into every session and container it starts. Set it for this one and re-run: export LANES_WORKSTATION=" +} + +# One of the spellings `git remote get-url origin` prints for one GitHub +# repository, reduced to a bare lowercased `/` so it can be +# compared against workspace.yaml's own `/`. A URL that is not +# GitHub's is compared as it stands, lowercased — which is what lets a sandbox +# name a bare local origin and still be checked. +lanes_ws_norm() { + local u="${1%.git}" + case "$u" in + https://github.com/*) u="${u#https://github.com/}" ;; + ssh://git@github.com/*) u="${u#ssh://git@github.com/}" ;; + git@github.com:*) u="${u#git@github.com:}" ;; + esac + printf '%s' "$u" | tr '[:upper:]' '[:lower:]' +} + +# Do these two name one repository? Equal after normalisation, OR the origin's +# path ENDS in the `/` the pointer file spells — which is how a +# GitHub Enterprise host, an ssh alias and a local bare mirror laid out by +# owner and name all say the same thing as `https://github.com//`. +# The pointer file spells `/` because that is what a person types; +# `git remote get-url` spells a URL because that is what git stores. +lanes_ws_same_repo() { + local a b + a="$(lanes_ws_norm "$1")" + b="$(lanes_ws_norm "$2")" + [ -n "$a" ] && [ -n "$b" ] || return 1 + [ "$a" = "$b" ] && return 0 + case "$a" in */"$b") return 0 ;; esac + return 1 +} + +# Prints the workspace checkout's real root, or returns 1 having set +# $LANES_WS_WHY to the one sentence that says which of the five ways it failed. +# ROOT-NESS IS ITS OWN CHECK: `rev-parse --is-inside-work-tree` and +# `remote get-url origin` both succeed from any SUBDIRECTORY of a work tree, so +# a `path:` naming a subdirectory would otherwise be accepted and resolve +# `/lanes/LANES.md` inside the wrong directory. +lanes_workspace_root() { + local yaml repo path origin toplevel real + LANES_WS_WHY="" + if [ -n "${LANES_WORKSPACE_ROOT:-}" ]; then + printf '%s\n' "$LANES_WORKSPACE_ROOT" + return 0 + fi + yaml="$(lanes_ws_yaml)" + if [ ! -r "$yaml" ]; then + LANES_WS_WHY="there is no $yaml" + return 1 + fi + repo="$(lanes_ws_field repository "$yaml")" + path="$(lanes_ws_field path "$yaml")" + if [ -z "$repo" ]; then + LANES_WS_WHY="$yaml names no \`repository:\`" + return 1 + fi + if [ -z "$path" ]; then + LANES_WS_WHY="$yaml names no \`path:\`" + return 1 + fi + if ! git -C "$path" rev-parse --is-inside-work-tree >/dev/null 2>&1; then + LANES_WS_WHY="$yaml names path: $path, which is not a git checkout" + return 1 + fi + origin="$(git -C "$path" remote get-url origin 2>/dev/null || :)" + if ! lanes_ws_same_repo "$origin" "$repo"; then + LANES_WS_WHY="$yaml names repository: $repo, but $path is a checkout of ${origin:-no origin at all}" + return 1 + fi + toplevel="$(git -C "$path" rev-parse --show-toplevel 2>/dev/null || :)" + real="$(cd -- "$path" 2>/dev/null && pwd -P)" || real="" + if [ -z "$real" ] || [ "$toplevel" != "$real" ]; then + LANES_WS_WHY="$yaml names path: $path, which is not the ROOT of that checkout (${toplevel:-unknown} is)" + return 1 + fi + printf '%s\n' "$real" +} + +# The refusal's body, so all four helpers say the same thing in the same words. +# +# THE REASON IS RE-DERIVED HERE, IN THE PARENT SHELL, and that is the whole +# point of this line. Every caller reaches the resolver through a command +# substitution — `LANES_WS_ROOT="$(lanes_workspace_root || :)"` — which runs it +# in a SUBSHELL, so the $LANES_WS_WHY it set died with that subshell and the +# parent still holds the empty string it started with. Six distinct diagnoses +# were being computed and all six were being thrown away; every one of the +# refusals Amendment 9(a) enumerates printed the same "no reason recorded". +# The resolver is read-only and cheap — two `sed`s and three `git` reads — and +# it is reached on the refusal path only, so running it again HERE is the one +# place its answer survives to be printed. +lanes_workspace_why() { + [ -n "$LANES_WS_WHY" ] || lanes_workspace_root >/dev/null 2>&1 || : + printf '%s' "the workspace repository could not be found — ${LANES_WS_WHY:-no reason recorded}. + Amendment 9(a): every lane helper reads \`repository:\` and \`path:\` from + $(lanes_ws_yaml), never from its own location. One command writes that + file, creates or clones the repository and places the symlinks: + openRepoTools wip init" +} +# --- END shared workspace resolver ------------------------------------------ + +# ======================= AMENDMENT 18(a) — WHERE THE LANE IS ================ +# +# **A LANE HAS ONE BINDING, AND THE RECORD SAYS WHERE IT IS.** Ratified +# 2026-09-14T13:15:18Z as revision 4; `brettheap/new-workstation#34`/#35, +# opensoft/openRepoTools#38. Clause (a) gives the lane-kind payload three +# sub-fields beside Amendment 11(c)'s `window`, `dir` and `profile`: +# +# host the MACHINE's short hostname as it reads OUTSIDE any +# container. The launcher exports it (`LANES_HOST`); a +# writer outside a container reads `hostname -s`; a writer +# INSIDE one with no export writes the Rule 10 workstation +# name, because in this estate a workstation is one host and +# a container's own `hostname` is its id. +# os +# the HOST's operating system as the person means it. The +# launcher exports it (`LANES_OS`); with no export the +# kernel is probed: `Darwin` -> macos; `Linux` whose +# `/proc/version` names `microsoft` -> wsl; one naming +# `linuxkit` -> macos (Docker Desktop's VM); any other +# `Linux` -> linux. `windows` is written ONLY by a launcher +# on the Windows host itself — this toolset is bash and runs +# in WSL2 there, so its own probe never says it. +# container +# the bench's name as the launcher exports it +# (`LANES_CONTAINER`: `py-bench`, `cloud-bench`, …); inside +# a container with no export, THAT CONTAINER'S OWN +# `hostname`, which for Docker's default is its id — a true +# name of that container and the one thing that tells two +# unnamed containers apart; outside every container, `none`. +# +# WHY THE RULE EXISTS AT ALL, in the amendment's own words: *"a pid does not +# cross a pid namespace, and the tooling pretends it does."* Two bench +# containers on one host share the profile directory, so pyBench can read a +# session record cloudBench wrote and then `kill -0` a pid in cloudBench's +# namespace — which is either nothing or some other process. A lane live and +# writing in cloudBench reads NOT LIVE from pyBench, and `lane-start` there took +# the name. The three facts are what let a reader say UNKNOWN instead. +# +# READ LIVE, EVERY TIME, AND NEVER CACHED — MEASURED 2026-09-15T12:17Z. This +# bench container was recreated with a new hostname (`cb999b9fd177`) and its +# `~/.local/bin` was wiped with it. A container's `hostname` names THIS +# container for as long as it exists and names nothing afterwards, so it is +# asked at the moment a line is written and is never carried in a variable +# across a run, let alone read back out of a record as though it were the +# workstation's name. A binding written by a container that has since been +# recreated therefore does NOT match this one — which is correct, because its +# pid namespace went with it — and the window-gone exception in clause (b) is +# what makes such a binding readable as dead rather than stranding the lane. +# +# EACH ANSWERS AS A PAIR, ``, for the reason +# `lanes_workstation_pair` states: a caller reads the value with `$( … )`, which +# is a subshell, so a global the function set there dies with it. The source is +# what `workstation` prints in its two new columns. +# +# NOT IN THE SHARED RESOLVER BLOCK ABOVE, deliberately. That block is +# byte-identical in four files and `tests/test_repo_hygiene.py` holds it there; +# these three are read by the WRITER and by the reads built on it, all of which +# are in this file, so a fourth copy would be three more places for one answer +# to be given differently. + +# `hostname -s` where there is one, else `hostname`, else empty. BSD and GNU +# both take `-s`; a busybox one may not, and an empty answer is honest. +lanes_host_probe() { + hostname -s 2>/dev/null || hostname 2>/dev/null || printf '' +} + +lanes_host_pair() { + if [ -n "${LANES_HOST:-}" ]; then + printf '%s\t%s\n' "$LANES_HOST" seam + return 0 + fi + if lanes_in_container; then + # INSIDE A CONTAINER `hostname` IS THE CONTAINER'S ID AND NOT THE HOST'S + # (Amendment 11 decision 8(d), R-A11-14, one field along): the Rule 10 + # workstation name is the host in this estate, so it is what is written. + printf '%s\t%s\n' "$WS" workstation + return 0 + fi + printf '%s\t%s\n' "$(lanes_host_probe)" hostname +} + +# THE KERNEL, PROBED — and `windows` is not one of its answers, which is the +# clause's own sentence and not an omission. +lanes_os_pair() { + if [ -n "${LANES_OS:-}" ]; then + printf '%s\t%s\n' "$LANES_OS" seam + return 0 + fi + lop_u="$(uname -s 2>/dev/null || printf '')" + case "$lop_u" in + Darwin) printf '%s\t%s\n' macos kernel; return 0 ;; + Linux) : ;; + *) printf '%s\t%s\n' linux kernel; return 0 ;; + esac + # `/proc/version` IS ABSENT ON A BSD USERLAND AND THAT IS NOT AN ERROR (#52's + # fixture lesson): the read is guarded, and a Linux kernel naming neither + # string is plain `linux`. + lop_v="" + [ -r /proc/version ] && lop_v="$(cat /proc/version 2>/dev/null || printf '')" + case "$lop_v" in + *microsoft*|*Microsoft*|*WSL*) printf '%s\t%s\n' wsl kernel ;; + *linuxkit*|*Linuxkit*) printf '%s\t%s\n' macos kernel ;; + *) printf '%s\t%s\n' linux kernel ;; + esac +} + +lanes_container_pair() { + if [ -n "${LANES_CONTAINER:-}" ]; then + printf '%s\t%s\n' "$LANES_CONTAINER" seam + return 0 + fi + if lanes_in_container; then + printf '%s\t%s\n' "$(lanes_host_probe)" hostname + return 0 + fi + printf '%s\t%s\n' none outside +} + +# THE ONE FENCE ALL THREE VALUES PASS, and it is Amendment 7(b)'s grammar +# rather than a taste: a sub-field's refs are separated by SPACES and its +# siblings by `; `, the line's fields by `, ` and its free text by ` — `, and +# the log is APPEND-ONLY. A hostname carrying any of those is a line no parser +# can read, for ever. A value that fails is DROPPED with a note (the sub-field, +# never the line — `R-A11-11`'s posture for the swap record, one field along): +# a binding that loses its `container` still says which host it is on, while a +# lane-kind line that was never written loses the lane. +lanes_binding_value_ok() { # + case "${1-}" in + '') return 1 ;; + *[!A-Za-z0-9._:-]*) return 1 ;; + esac + return 0 +} + +# The register is no longer the whole of its own worktree: since Amendment 5 +# it is one file, `lanes/LANES.md`, inside the workspace repository. So every +# git call needs the checkout ROOT and a pathspec RELATIVE to it. Amendment +# 9(a) says where the root comes from; `--show-prefix` still derives the +# pathspec, because `LANES_DIR` may be pointed anywhere by a caller and the +# pathspec must follow it. +# +# RESOLVED HERE, REFUSED LATER. An empty answer is carried rather than fatal, +# so `--help`, the usage and `session-start` — a hook that must exit 0 on a +# machine with no register at all — still run. The refusal is the +# `registry not found` guard below, which is exit 1: the code this script has +# always used for it and the code Amendment 9(a) quotes. +LANES_WS_ROOT="" +if [ -z "${LANES_REPO:-}" ] || { [ -z "${LANES_DIR:-}" ] && [ -z "${LANES_FILE:-}" ]; }; then + LANES_WS_ROOT="$(lanes_workspace_root || :)" +fi +: "${LANES_REPO:=$LANES_WS_ROOT}" +if [ -z "${LANES_DIR:-}" ]; then + if [ -n "${LANES_FILE:-}" ]; then + LANES_DIR="$(dirname -- "$LANES_FILE")" + else + LANES_DIR="${LANES_WS_ROOT:+$LANES_WS_ROOT/lanes}" + fi +fi +LANES_FILE="${LANES_FILE:-$LANES_DIR/LANES.md}" +WS_PAIR="$(lanes_workstation_pair)" +WS="${WS_PAIR%% *}" +WS_SOURCE="${WS_PAIR##* }" +# AMENDMENT 18(a) — THE THREE FACTS BENEATH THE WORKSTATION'S NAME, probed here +# for the READS and probed AGAIN by the writer for every line it appends, and +# always AFTER `WS`, because the `host` fallback inside a container IS the +# workstation's name. Every one of them is a live read of this process's own +# environment and kernel: nothing here is ever taken from a record. +LANES_HOST_NAME=""; LANES_HOST_SOURCE="" +LANES_OS_NAME=""; LANES_OS_SOURCE="" +LANES_CONTAINER_NAME=""; LANES_CONTAINER_SOURCE="" +# ONE FUNCTION PROBES ALL THREE, AND THE WRITER CALLS IT AGAIN AT THE WRITE +# (Copilot round 3 on opensoft/openRepoTools#83). A process-start snapshot is +# what every reader wants — the values cannot change under a short read — but +# the sentence this file makes about them is *"read live at every write and +# never cached"*, and a `request-handoff` can sit in a five-minute wait between +# its start and a later act. The probe is two forks; making the words true costs +# nothing and leaves nothing for a reader to have to reason about. +lanes_binding_probe() { + HOST_PAIR="$(lanes_host_pair)" + LANES_HOST_NAME="${HOST_PAIR%% *}" + LANES_HOST_SOURCE="${HOST_PAIR##* }" + OS_PAIR="$(lanes_os_pair)" + LANES_OS_NAME="${OS_PAIR%% *}" + LANES_OS_SOURCE="${OS_PAIR##* }" + CONTAINER_PAIR="$(lanes_container_pair)" + LANES_CONTAINER_NAME="${CONTAINER_PAIR%% *}" + LANES_CONTAINER_SOURCE="${CONTAINER_PAIR##* }" + # The lower-cased cache the locality rule reads is derived from them, so it + # is dropped here rather than left saying what the probe used to say. + LANES_HOST_LC=""; LANES_WS_LC=""; LANES_CONTAINER_LC="" + return 0 +} +lanes_binding_probe +NO_GIT="${LANES_NO_GIT:-0}" +LOCK="$LANES_DIR/.lanes-edit.lock" +# AMENDMENT 14 — TWO VALUES ONLY THIS PROCESS SETS, AND NEVER THE ENVIRONMENT. +# The index is consulted behind a flag typed for the invocation, "never by +# default, environment or configuration" (clause (b)), and the nudge follows a +# push THIS process made (clause (d)). Both are assigned here unconditionally, +# so an exported variable of either name changes nothing. +LANES_IDX_DIR="" +LANES_INDEX_NUDGE=0 +# AND THE INVENTORY'S OWN TWO (opensoft/openRepoTools#161), for the same reason: +# the `worktrees` table's export directory, set only by `index_open worktrees`, +# and the nudge an inventory write leaves for `cleanup` - set only by a write +# of a lifecycle snapshot or a tree record that this process made. +LANES_WT_IDX_DIR="" +LANES_INDEX_NUDGE_INV=0 +LOCK_HELD=0 +LANES_PATH="${LANES_PATH:-$(git -C "${LANES_DIR:-.}" rev-parse --show-prefix 2>/dev/null || :)${LANES_FILE##*/}}" + +# The pathspecs the current invocation is writing. Every subcommand that +# predates Amendment 7 writes exactly one, the register; a LANDING or LANDED +# writes two. CP_AFTER_REBASE is a function commit_push calls after each +# `pull --rebase`, before it pushes — `claim` uses it to notice that another +# lane's claim landed first. +CP_PATHS=("$LANES_PATH") +CP_AFTER_REBASE="" +# Set by `commit` alone, and never taken from the environment: with nothing +# staged, commit_push publishes the local commits ahead of origin for that one +# write and for no other (#194). +CP_PUBLISH_AHEAD=0 +# A publish's push sends the commit its fence read, `:refs/heads/`; +# empty, every push sends the branch as it stands, as it always has (#194). +CP_PUSH_SPEC="" +CP_FENCE_TIP="" +CP_FENCE_AHEAD=0 + +# die "" [] — the MESSAGE is $1 alone. It used to be "$*", +# which joined the exit code on to the end of every refusal that passed one: +# `… is not a stale claim. 2`. The code is the caller's business and the +# process's, not the reader's; LANES_DEBUG=1 prints it for whoever is debugging +# the codes themselves. +die() { + printf 'lanes-edit: %s\n' "${1-}" >&2 + [ -n "${LANES_DEBUG:-}" ] && printf 'lanes-edit: (exit %s)\n' "${2:-1}" >&2 + exit "${2:-1}" +} +note() { printf 'lanes-edit: %s\n' "$*" >&2; } + +# AMENDMENT 8, ruling (h): THE LOCK NAMES ITS HOLDER, so a lock nobody holds can +# be told from a lock somebody does. The directory alone could only be aged out, +# and ten minutes of every lane on the workstation blocked is not a recovery. +release_lock() { + rm -f -- "$LOCK/pid" 2>/dev/null || : + rmdir -- "$LOCK" 2>/dev/null || : + LOCK_HELD=0 + return 0 +} + +# ====================================================== AMENDMENT 16 ======= +# +# THE RENAME'S UNDO, AND WHY IT IS A TRAP AND NOT A LINE BEFORE EACH `die`. +# +# `rename-lane` is ONE COMMIT, REFUSED OR WHOLE, and its refusals all happen +# before the first byte — but the four MOVES themselves can still fail on a +# filesystem: a `mv` across a mount, a handoff this user may not write, a disk +# that fills between the log and the alias table. Copilot round 1 on +# openRepoTools#81 named the state that left: *"the log has already been moved +# and its `RENAMED` line appended, and this `die` exits without rolling either +# change back"* — a half-renamed checkout, which is exactly what the contract +# says cannot happen and what no re-run can finish. +# +# So the writes are made against a SNAPSHOT taken before the first of them, and +# every exit path between the first write and the commit restores it. It hangs +# off `cleanup`, not off each `die`, for the reason `replace_line` makes +# unavoidable: that function dies inside itself when its own proof fails, and a +# caller cannot put a line after it. `cleanup` runs on EXIT and on the two +# signals, so one hook covers every way out, the shell's included. +# +# THE REGISTER IS NOT IN IT. `replace_line` builds the new file in a temporary +# directory and proves it — one line added, one removed, the same line count — +# BEFORE it writes a byte of `LANES.md`, so the register is never half-written +# and there is nothing there to restore. +RL_ACTIVE=0; RL_SNAP=""; RL_HEAD_BEFORE="" +RL_LOG_OLD=""; RL_LOG_NEW=""; RL_H_OLD=""; RL_H_NEW="" +RL_ALIAS=""; RL_ALIAS_EXISTED=0; RL_REG="" +RL_PATHS_FOR_UNDO=() +rename_undo() { + [ "$RL_ACTIVE" = 1 ] || return 0 + RL_ACTIVE=0 + # A COMMIT THAT EXISTS IS NOT UNDONE. The undo is armed through `commit_push` + # because that function can die before it commits anything; once it HAS + # committed, the four moves are in that commit and restoring the working tree + # would be an inverse change nobody asked for, on top of a commit whose own + # recovery `commit_push` prints. HEAD is the whole test. + if [ -n "$RL_HEAD_BEFORE" ]; then + ru_head="$(git -C "$LANES_REPO" rev-parse HEAD 2>/dev/null || printf '')" + if [ -n "$ru_head" ] && [ "$ru_head" != "$RL_HEAD_BEFORE" ]; then + note "the rename is COMMITTED as $ru_head and is not rolled back; what follows is about getting that commit to origin, and the four files are whole." + return 0 + fi + fi + [ -n "$RL_LOG_NEW" ] && [ -f "$RL_LOG_NEW" ] && rm -f -- "$RL_LOG_NEW" + [ -n "$RL_LOG_OLD" ] && [ -n "$RL_SNAP" ] && [ -f "$RL_SNAP/log" ] && cat -- "$RL_SNAP/log" > "$RL_LOG_OLD" + if [ -n "$RL_H_NEW" ] && [ "$RL_H_NEW" != "$RL_H_OLD" ] && [ -f "$RL_H_NEW" ]; then rm -f -- "$RL_H_NEW"; fi + [ -n "$RL_H_OLD" ] && [ -n "$RL_SNAP" ] && [ -f "$RL_SNAP/handoff" ] && cat -- "$RL_SNAP/handoff" > "$RL_H_OLD" + if [ -n "$RL_ALIAS" ]; then + if [ "$RL_ALIAS_EXISTED" = 1 ]; then + [ -n "$RL_SNAP" ] && [ -f "$RL_SNAP/aliases" ] && cat -- "$RL_SNAP/aliases" > "$RL_ALIAS" + else + rm -f -- "$RL_ALIAS" + fi + fi + # THE REGISTER LAST, and with the `cat >` every writer here uses for it: the + # register reached through `~/projects//LANES.md` is a SYMLINK, and a + # redirect follows it where `mv` or `cp` would replace it with a regular file + # and detach the register from git — the hazard this file's own header opens + # with. + [ -n "$RL_REG" ] && [ -n "$RL_SNAP" ] && [ -f "$RL_SNAP/register" ] && cat -- "$RL_SNAP/register" > "$RL_REG" + # AND THE INDEX WITH IT, because `commit_push` STAGES before it commits: a + # `git add` that succeeded and a `git commit` that did not leaves the four + # paths staged, so restoring only the working tree would leave the rename in + # the index for the next writer to commit by accident. + # THE PATHSPECS STAY AN ARRAY (Copilot round 8 on openRepoTools#81). Flattened + # into one string and expanded unquoted, a handoff under `handoffs/team + # notes/…` — a path this estate supports, and the one every other line here + # quotes — became `handoffs/team` and `notes/…`, two pathspecs that match + # nothing. AND `git reset` SAYS NOTHING ABOUT ONE IT CANNOT MATCH: measured, + # it resets the paths it does match, leaves that file staged and exits 0, so + # the `|| :` above was never reached and no line of output said so. The + # rename then stayed in the index for the next writer to commit by accident, + # which is the half-transaction this whole snapshot exists to prevent. + if [ -n "$RL_REG" ] && [ "$NO_GIT" != 1 ] && [ "${#RL_PATHS_FOR_UNDO[@]}" -gt 0 ]; then + git -C "$LANES_REPO" reset -q HEAD -- "${RL_PATHS_FOR_UNDO[@]}" 2>/dev/null || : + fi + note "the rename was rolled back: the object log, the handoff and ${LANES_ALIASES_PATH:-lanes/aliases.tsv} are as they were, and nothing was committed. A rename is ONE commit, refused or whole (Amendment 16)." + return 0 +} + +# `cleanup`'S TEMPORARIES START EMPTY, so none of them is a path the CALLER +# chose. It runs on every exit and removes each one by name, and a variable +# exported into the environment used to arrive here already set: `rl_htmp` +# made a read-only `canon-lane` delete the file it named, and `TMPD` made it +# `rm -rf` the directory (the reviews of #212 and #213; `pbh_tmp` and `TMPD` +# had the hole before `rl_htmp` joined them). `SE_CACHE_FILE` is assigned only +# at the state-event cache below, so a signal before that line removed what it +# inherited. Every other path `cleanup`, `rename_undo` and `release_lock` +# remove is set above, before the trap: `RL_*`, `LANES_IDX_DIR`, +# `LANES_WT_IDX_DIR`, `LOCK` and `LOCK_HELD`. +TMPD=""; pbh_tmp=""; rl_htmp=""; SE_CACHE_FILE="" +cleanup() { + [ -z "${pbh_tmp:-}" ] || rm -f -- "$pbh_tmp" + [ -z "${rl_htmp:-}" ] || rm -f -- "$rl_htmp" # rename-lane's stamp before its replace (#158) + rename_undo + if [ "$LOCK_HELD" = 1 ]; then release_lock; fi + [ -n "${RL_SNAP:-}" ] && [ -d "${RL_SNAP:-}" ] && rm -rf -- "$RL_SNAP" + [ -n "${TMPD:-}" ] && [ -d "${TMPD:-}" ] && rm -rf -- "$TMPD" + [ -n "${SE_CACHE_FILE:-}" ] && rm -f -- "$SE_CACHE_FILE" "$SE_CACHE_FILE".* 2>/dev/null + [ -n "${LANES_IDX_DIR:-}" ] && [ -d "${LANES_IDX_DIR:-}" ] && rm -rf -- "$LANES_IDX_DIR" + [ -n "${LANES_WT_IDX_DIR:-}" ] && [ -d "${LANES_WT_IDX_DIR:-}" ] && rm -rf -- "$LANES_WT_IDX_DIR" + # AMENDMENT 14(d) — THE NUDGE IS THE LAST THING THIS PROCESS DOES: after the + # lock is released at the top of this function, and only where `commit_push` recorded a push + # that landed - or, opensoft/openRepoTools#161, where an inventory writer + # recorded a snapshot or a tree record it had just replaced. Tested here rather + # than inside the function, because `cleanup` also runs for a process that died + # before `index_nudge` was ever defined. + if [ "${LANES_INDEX_NUDGE:-0}" = 1 ] || [ "${LANES_INDEX_NUDGE_INV:-0}" = 1 ]; then index_nudge; fi + return 0 +} +# AND A SIGNAL ACTUALLY STOPS IT (Amendment 8, ruling (h)). `trap cleanup EXIT +# INT TERM` ran the handler and then CARRIED ON, because a trap that returns +# resumes the command after the one that was interrupted — so a `kill` of a +# writer stuck in `acquire_lock`'s 60-second wait released the lock and then +# went on waiting for it, and a `kill` of one mid-write released the lock while +# it still had the register open. Measured: SIGTERM at 8s, the process still +# running at 56s. The handler now re-raises with the default disposition, which +# is the only way a shell reports "killed by that signal" and the only way the +# process actually stops. +trap cleanup EXIT +trap 'cleanup; trap - INT; kill -INT $$' INT +trap 'cleanup; trap - TERM; kill -TERM $$' TERM + +# A LOCK WHOSE HOLDER IS DEAD IS STALE THE INSTANT ITS PID IS GONE — not ten +# minutes later. A helper killed at a usage reset, or an ssh that took the +# process down with it, leaves a directory no living process will ever remove, +# and until Amendment 8(h) every writer on the workstation waited out the full +# age-out behind it. A lock with NO pid file is from an older version of this +# script and keeps the age test, which is the only thing that could be said +# about it. +lock_steal_if_dead() { + [ -d "$LOCK" ] || return 0 + lsd_pid="$(cat -- "$LOCK/pid" 2>/dev/null || :)" + case "$lsd_pid" in ''|*[!0-9]*) return 0 ;; esac + [ "$lsd_pid" = "$$" ] && return 0 + kill -0 "$lsd_pid" 2>/dev/null && return 0 + note "taking over $LOCK: its holder (pid $lsd_pid) is gone" + rm -f -- "$LOCK/pid" 2>/dev/null || : + rmdir -- "$LOCK" 2>/dev/null || : + return 0 +} + +# THE MUTEX, TAKEN WITHOUT DYING FOR IT — 0 taken, 1 not taken, and no exit +# either way. `acquire_lock` below is this with the refusal on the end, so the +# `mkdir` mutex, the pid test and the age-out are written ONCE and every taker +# of the lock obeys the same three. +# +# THE NON-FATAL FORM IS WHAT THE LIFECYCLE FOLLOW-UP TAKES (openRepoTools#91). +# It runs at the foot of `write_event`, AFTER the event line has landed and been +# committed, and a `die` there would abort a caller whose write is already on +# disk — so the snapshot that could not be taken under the mutex is left alone +# and SAID, exactly as a snapshot that could not be written is. +lock_try() { # [] + lt_max="${1:-60}" + lock_steal_if_dead + # Stale lock (>10 min) is removed: a helper run never takes that long. The + # age test is now the FALLBACK — the pid test above is the real one. + if [ -d "$LOCK" ]; then + if [ -z "$(find "$LOCK" -maxdepth 0 -mmin -10 2>/dev/null)" ]; then + note "removing stale lock $LOCK" + rm -f -- "$LOCK/pid" 2>/dev/null || : + rmdir -- "$LOCK" 2>/dev/null || : + fi + fi + lt_i=0 + while [ "$lt_i" -lt "$lt_max" ]; do + if mkdir -- "$LOCK" 2>/dev/null; then + LOCK_HELD=1 + printf '%s\n' "$$" > "$LOCK/pid" 2>/dev/null || : + return 0 + fi + lock_steal_if_dead # it may have died while we were waiting + lt_i=$((lt_i + 1)) + sleep 1 + done + return 1 +} + +acquire_lock() { + lock_try 60 && return 0 + die "could not acquire $LOCK after 60s — another lanes-edit run is active (holder pid $(cat -- "$LOCK/pid" 2>/dev/null || printf 'unrecorded'))" 4 +} + +# ---------------------------------------------------------------- row lookup + +# AMENDMENT 15 — A LANE NAME IS ONE NAME UNDER ANY CASE, AND THE ROW'S SPELLING +# IS THE ONE IT CARRIES (ratified 2026-09-14T00:07:18Z). +# +# Every spelling the WORKING TREE's register carries for a name, compared +# case-insensitively, one per line. This is the set `row_line` counts and the +# set every refusal below NAMES: at 2026-09-13T23:51:56Z a `lane-start +# openxfactory 2` typed in lowercase for the lane `openXfactory-2` found NO row +# here — the row key was the one exact comparison left in this file — and +# appended a SECOND row for a lane that had run since 2026-09-02, while its +# object log went on into the one file both spellings had always shared. +rows_named_ci_local() { # + awk -v want="$1" ' + substr($0,1,1) == "|" { + p1 = index($0, "`"); if (p1 == 0) next + rest = substr($0, p1 + 1); p2 = index(rest, "`"); if (p2 == 0) next + t = substr(rest, 1, p2 - 1) + if (tolower(t) == tolower(want)) print t + }' "$LANES_FILE" +} + +# Prints the 1-based line number of the row whose FIRST backticked token is the +# lane name, COMPARED CASE-INSENSITIVELY (Amendment 15). Exactly one match is +# required — and where there are two, that is the amendment's own refusal and +# not a puzzle about which row to edit: 15(d) says the two are merged into one, +# by hand, in a commit that names both spellings. +# +# THE LINE IT RETURNS IS STILL THE EXACT LINE. What changed is how the line is +# FOUND; every editor above still rewrites that one line byte for byte, so a row +# spelled `openXfactory-2` keeps its spelling when a caller typed the lowercase +# form. Which spelling gets WRITTEN into new text is `canon_lane`'s answer, one +# function along. +row_line() { + lane="$1" + hits="$( + awk -v lane="$lane" ' + substr($0,1,1) == "|" { + p1 = index($0, "`") + if (p1 == 0) next + rest = substr($0, p1 + 1) + p2 = index(rest, "`") + if (p2 == 0) next + if (tolower(substr(rest, 1, p2 - 1)) == tolower(lane)) print NR + }' "$LANES_FILE" + )" + n="$(printf '%s' "$hits" | grep -c . || :)" + if [ "$n" != 1 ]; then + # NOTE: row_line runs inside $( ), so it must RETURN, not exit — an `exit` + # here would only leave the command substitution's subshell and the caller + # would carry on with an empty line number. + note "expected exactly 1 row for lane '$lane', found $n${hits:+ (lines: $(printf '%s' "$hits" | tr '\n' ' '))}" + if [ "$n" -gt 1 ]; then + note "those rows are spelled $(rows_named_ci_local "$lane" | tr '\n' ' ')— a lane name is ONE name under any case (Amendment 15), so merge them into one row (Amendment 15(d)): append the newer row's session id(s) to the older row's session cell, in order, and remove the newer row in the SAME commit" + fi + return 2 + fi + printf '%s' "$hits" +} + +count_occurrences() { # $1=haystack $2=needle + hay="$1"; needle="$2"; c=0 + if [ -z "$needle" ]; then note "empty search string"; return 2; fi + while :; do + case "$hay" in + *"$needle"*) c=$((c + 1)); hay="${hay#*"$needle"}" ;; + *) break ;; + esac + done + printf '%s' "$c" +} + +# A row split into HEAD (everything up to and including the SECOND `|`), the +# SESSION CELL, and TAIL (from the THIRD `|` on) — the three pieces +# `append-session-id` needs, and the only safe way to reach cell 3 of a row +# whose LATER cells may contain a literal `|` (the live register has two such +# rows). It splits from the LEFT for that reason, never from NF. The three +# pieces are asserted to reassemble into the row before anything is written. +RSC_HEAD=""; RSC_CELL=""; RSC_TAIL="" +row_split_session_cell() { # + rsc_row="$1"; RSC_HEAD=""; RSC_CELL=""; RSC_TAIL="" + case "$rsc_row" in *"|"*) : ;; *) return 1 ;; esac + rsc_rest="${rsc_row#*|}" # after the 1st | + case "$rsc_rest" in *"|"*) : ;; *) return 1 ;; esac + rsc_rest2="${rsc_rest#*|}" # after the 2nd | + case "$rsc_rest2" in *"|"*) : ;; *) return 1 ;; esac + RSC_CELL="${rsc_rest2%%|*}" + RSC_TAIL="|${rsc_rest2#*|}" + RSC_HEAD="${rsc_row%%|*}|${rsc_rest%%|*}|" + [ "$RSC_HEAD$RSC_CELL$RSC_TAIL" = "$rsc_row" ] || return 1 + return 0 +} +rstrip_spaces() { s="$1"; while [ "${s% }" != "$s" ]; do s="${s% }"; done; printf '%s' "$s"; } + +# --------------------------------------------- AMENDMENT 13: THE ROW IS STATE +# +# **THE ROW IS THE LANE'S CURRENT STATE, ONE LINE A PERSON CAN READ; ITS HISTORY +# IS THE LANE'S OWN LOG** — lane-collision-protocol Amendment 13, in force +# 2026-09-13T21:08:36Z. Clause (a): the `state` column holds ONE PHRASE, +# ` · · `, and every write REPLACES it. `set-row-state` +# is the writer; `append-row-status` is RETIRED, so the cell can never grow into +# a diary again. Measured on the day the amendment was drafted: the register was +# 1,141,283 bytes over 46 rows, its longest row 96,228 characters, and this +# lane's own cell 7,016 characters after ONE day of appending. +# +# WHERE THE CELL IS: SPLIT THE ROW ON ` | `, AND SIX SEPARATORS ARE THE PROOF. +# A seven-column row has exactly six of them, and then the two readings of the +# row — count six from the left, take the last cell from the right — are the +# same text. A row with MORE has a ` | ` inside one of its cells, and nothing +# here can tell WHICH cell it is in: the two readings disagree, and one of them +# writes the new state over the row's handoff path. So more than six is a +# REFUSAL naming the row, never a choice between them. +# +# MEASURED ON THE LIVE REGISTER, 2026-09-15 (1,335,595 bytes, 52 rows): 50 of +# them carry exactly six separators and split cleanly. `openXfactory-2` carries +# seven — one of them is inside its `objects owned` cell, so the two readings +# disagree about the HANDOFF PATH — and `openxfactory-4` eight, both inside its +# state cell. Those two are refused by name, and the fix is a person's: escape +# the pipe as `\|`, which is how a Markdown table carries a literal one, in a +# hand edit wrapped by `lanes-edit.sh commit`. A BARE `|` THAT IS NOT SPELLED +# ` | ` IS HARMLESS and stays inside whichever cell holds it: the state cells of +# `openRepoProject-1` and `openRepoTools-3` carry nineteen and four of them +# (`'| true'`, a quoted shell fragment), and both of those rows split exactly. +# +# It splits from the LEFT for the reason `row_split_session_cell` does — the +# cells that may carry a stray separator are the free-text ones at the end — and +# the three pieces are asserted to reassemble into the row before anything is +# written. +RSS_HEAD=""; RSS_CELL=""; RSS_TAIL="" +row_split_state_cell() { # — 0 with the pieces · 1 not a row · 2 ambiguous + rss_row="$1"; RSS_HEAD=""; RSS_CELL=""; RSS_TAIL="" + case "$rss_row" in "|"*) : ;; *) return 1 ;; esac + rss_body="$(rstrip_spaces "$rss_row")" + case "$rss_body" in *"|") : ;; *) return 1 ;; esac + # `${row:N}` AND NEVER `${row#"$body"}`. Removing a literal prefix walks every + # prefix length in turn, so a 90,751-character row cost ELEVEN SECONDS in that + # one expansion — measured 2026-09-15 against the live register's longest row, + # and it is the whole of what made a dry run of the migration take a minute + # and a half. A substring by offset is linear, and both `${#s}` and `${s:n}` + # count CHARACTERS, so the two agree on a row full of `·`, `—` and `→`. + rss_pad="${rss_row:${#rss_body}}" # the row's own trailing spaces, kept + rss_inner="${rss_body%|}" # everything before the closing pipe + rss_n="$(count_occurrences "$rss_inner" " | ")" || return 1 + [ "$rss_n" = 6 ] || return 2 + rss_rest="$rss_inner"; rss_head=""; rss_i=0 + while [ "$rss_i" -lt 6 ]; do + rss_one="${rss_rest%% | *}" + rss_head="$rss_head$rss_one | " + rss_rest="${rss_rest:$(( ${#rss_one} + 3 ))}" # 3 = the separator + rss_i=$((rss_i + 1)) + done + RSS_HEAD="$rss_head"; RSS_CELL="$rss_rest"; RSS_TAIL="|$rss_pad" + [ "$RSS_HEAD$RSS_CELL$RSS_TAIL" = "$rss_row" ] || { RSS_HEAD=""; RSS_CELL=""; RSS_TAIL=""; return 1; } + return 0 +} + +# How many ` | ` a row carries, for the refusal above to be able to say so. +row_sep_count() { # + count_occurrences "$(rstrip_spaces "$1")" " | " 2>/dev/null || printf '?' +} + +# Clause (a)'s seven states, and O1's cap on the one line beside them. +ROW_STATES='LIVE, PAUSED, LANDING #, LANDED, ENDED, RETIRED, HANDED OFF' +ROW_STATE_CAP=240 +ROW_STATE=""; ROW_STATE_LINE="" +state_word_is_valid() { # + case "${1-}" in + LIVE|PAUSED|LANDED|ENDED|RETIRED|'HANDED OFF') return 0 ;; + 'LANDING #'*) + # Rule 6's reading of the cell is unchanged by Amendment 13 and is now the + # whole of what the cell says at that moment, so the number is checked: + # `LANDING #` with nothing after it is a merge hold no lane can pair with + # a PR. + case "${1#LANDING #}" in + '' | *[!0-9]*) return 1 ;; + *) return 0 ;; + esac ;; + esac + return 1 +} + +# ` · ` → ROW_STATE and ROW_STATE_LINE, or a refusal. Every +# test is made BEFORE the lock and before the row is touched, so a refusal +# leaves the register exactly as it found it. +row_state_check() { # " · " + rst_in="${1-}"; ROW_STATE=""; ROW_STATE_LINE="" + case "$rst_in" in + *' · '*) : ;; + *) die "the phrase is ' · ' and this carries no ' · ' separator: '$rst_in'. The STATE is one of $ROW_STATES; the line says what the last act was, in at most $ROW_STATE_CAP characters. The narrative goes to the lane's own log — \`log NOTED\` / \`log RULED\` (Amendment 13(b))." 2 ;; + esac + ROW_STATE="${rst_in%% · *}" + ROW_STATE_LINE="${rst_in#* · }" + state_word_is_valid "$ROW_STATE" || + die "'$ROW_STATE' is not one of Amendment 13(a)'s states ($ROW_STATES). The cell is the lane's CURRENT STATE and nothing else, so an eighth word is a state no reader of Rule 6 or of the listing knows." 2 + [ -n "$ROW_STATE_LINE" ] || + die "the phrase is ' · ' and the line is empty: say what the last act was. A state with no line is a cell a person cannot read anything out of." 2 + case "$ROW_STATE_LINE" in + *' · '*) die "the line may not contain ' · ': that separator is what divides the cell's three parts — ' · · ' — and a second one inside the line reads back as a fourth part. Use a semicolon: '$ROW_STATE_LINE'" 2 ;; + *'|'*) die "the line may not contain '|': it would forge a cell boundary in the row, which is the one edit no reader of the register could recover from. Got: '$ROW_STATE_LINE'" 2 ;; + esac + if [ "${ROW_STATE_LINE//[$'\n\r']/}" != "$ROW_STATE_LINE" ]; then + die "the line is ONE line: a newline in it would split the row in two and every row after it would be read as a lane" 2 + fi + # THE MARKER'S VOCABULARY IS NOT A LEGACY WRITER'S TO WRITE (ruling + # 2026-10-04). The projection reader matches it anywhere in a row, so a + # phrase carrying it would make this lane read as managed, or as UNKNOWN. + if managed_projection_hint "$rst_in"; then + die "the phrase carries managed-owner vocabulary ('managed owner', 'managed binding', 'mode=managed' or 'managed:'), and only the managed ledger's own writer writes a managed-owner marker, and a legacy writer that wrote its vocabulary into a row would forge that lane's ownership (ruling 2026-10-04: \"managed ledger owns enrolled lanes; #97 owns legacy\"). Reword it: '$rst_in'" 2 + fi + # ${#s} COUNTS CHARACTERS and the cap is O1's 240 of them — these lines are + # full of `·`, `—` and `→`, so a byte count would refuse a line that is inside + # the cap and accept one that is not. + [ "${#ROW_STATE_LINE}" -le "$ROW_STATE_CAP" ] || + die "the line is ${#ROW_STATE_LINE} characters and the cap is $ROW_STATE_CAP (Amendment 13, ratified decision O1). Shorten it, and put what will not fit in the lane's own log, which is where the history lives: LANES_LANE= lanes-edit.sh log NOTED lane: \"\"" 2 + return 0 +} + +# Prints the row's OWN spelling of a lane name that matches $1 ignoring case, +# when exactly one row does. Attribution only — never used to pick the line an +# edit rewrites, which stays exact-match. Rule 10's wire form is lowercase +# (`Lane: openxfactory-2`) while the row's token may be camel (`openXfactory-2`), +# so an exact lookup alone loses the author of a Rule 6 line. +row_lane_ci() { + awk -v want="$1" ' + substr($0,1,1) == "|" { + p1 = index($0, "`"); if (p1 == 0) next + rest = substr($0, p1 + 1); p2 = index(rest, "`"); if (p2 == 0) next + t = substr(rest, 1, p2 - 1) + if (tolower(t) == tolower(want)) { n++; hit = t } + } + END { if (n == 1) print hit }' "$LANES_FILE" +} + +# A Rule 6 line names its own lane in its text — "LANDING — lane , …", +# "LANDED — lane (), …". `append-line` takes no lane argument, +# so with LANES_LANE unset it used to commit as LANES(unknown@) and the +# line's author was lost from the log (this predates Amendment 5: the same +# `${LANES_LANE:-unknown}` is in the pre-move script). Read the name out of +# the text instead, and fall back to unknown only when there is nothing to +# read. Anything outside [A-Za-z0-9._-] is rejected rather than sanitised, +# and the caller checks the candidate against the register's own rows before +# trusting it — "…names no lane at all" must not be attributed to a lane +# called "at". +lane_from_text() { + t="$1"; l="" + case "$t" in + *"lane "*) + l="${t#*lane }" + l="${l%%[ ,;:)]*}" + l="${l//\`/}" + ;; + esac + case "$l" in + "" | *[!A-Za-z0-9._-]*) printf '' ;; + *) printf '%s' "$l" ;; + esac +} + +# --------------------------------------------------------------- file writes + +# THE REGISTER IS REWRITTEN IN TWO PLACES, `replace_line` AND `delete_lines`, +# AND BOTH PROVE WHAT THEY COPIED AND WHAT LANDED (opensoft/openRepoTools#120 +# item 1, Copilot round 5 on #93). The appends below them prove their result +# with `cmp`; the rewrites proved only the file they built, and two steps of +# theirs were never checked at all: +# +# * THE COPY. Every proof of a rewrite (the line count, `numstat`, the no-op) +# is made against `$pre`, a `cat` of the register into a temporary file, and +# that `cat` had no status. A copy that came out short (a full temporary +# filesystem, a read that failed part-way) made a SHORT register look like a +# one-line edit of itself: every proof passed and the short copy was written +# back as the register and committed. Measured at 5e88a2c with the copy cut +# at half its lines: a 156,611-byte register rewritten as 78,306, exit 0. +# * THE WRITE. `cat -- > LANES.md` had its status read and not its +# result, and `>` TRUNCATES before `cat` writes a byte. A write that failed +# part-way left a half register behind a refusal that called it UNCHANGED, +# and one that came out short and said nothing was a half register +# committed. Even an uncommitted half register is one write from being +# published: the next writer in this checkout commits a dirty register as a +# peer's pre-existing edit (`handle_preexisting`). +# +# So the copy is compared with the register and the result with what was built. +# Where the result is not what was built, the copy's bytes are put back and +# proved before the refusal (5) says which of the two the register now holds. +# Both still write through `cat` and a redirection, which FOLLOW a symlinked +# register; a rename beside it would replace the link with a file. +# +# A REFUSAL SAYS WHAT IS ALREADY ON DISK (the review of #263, S2). The sweeps +# write their logs, their archive and their earlier rows before a row's +# rewrite, so a refusal that said "Nothing was written" was false there: `git +# status` showed those files, and a re-run read them back. What holds is that +# THIS ACT has committed nothing — not "nothing has been committed": a peer's +# uncommitted register edit found first is captured as a commit of its own +# (`handle_preexisting`) before the act's edit, and the one caller that HAS +# committed when it rewrites (add-row's after-rebase take-back) says so through +# `REG_COMMITTED_HERE` (the delta review of #263). Each sweep names its local +# writes with `reg_wrote`, which the refusals list. AND WHERE THE REGISTER MAY +# BE TRUNCATED the copy is KEPT (S2's NIT 6): it is the only exact copy of the +# register as it was, uncommitted edits included, and the exit trap removes +# `$TMPD`. So it is copied into the checkout's own git directory — mode 0600, +# under a name nothing else holds, proved byte for byte — where a restart that +# empties the temporary directory leaves it; only where that cannot be done is +# it renamed beside `$TMPD` instead (a rename needs no free space). +REG_WRITTEN_HERE="" +REG_COMMITTED_HERE="" +DL_SAYS_UNCHANGED="" +DL_SAYS_AFTER_WRITE="" +reg_wrote() { # + REG_WRITTEN_HERE="$REG_WRITTEN_HERE, $1" +} +reg_committed() { # — what this act has committed, as a refusal says it + printf '%s' "${REG_COMMITTED_HERE:-this act has committed nothing}" +} +reg_written_here() { # — the sentence a refusal ends with, or nothing + [ -n "$REG_WRITTEN_HERE" ] || return 0 + printf ' This act has already written, in this checkout and NOT committed: %s. `git -C %s status` shows them; commit or undo them before re-running.' \ + "${REG_WRITTEN_HERE#, }" "$LANES_REPO" +} +register_copy() { # + cat -- "$LANES_FILE" > "$1" && cmp -s -- "$LANES_FILE" "$1" || + die "the register at $LANES_FILE could not be copied whole to $1, and every proof of this edit is made against that copy: a short one would make a short register look like a one-line edit of itself. The register is as it was and $(reg_committed): $2.$(reg_written_here)" 5 +} +register_rewrite() { # + cat -- "$2" > "$LANES_FILE" && cmp -s -- "$LANES_FILE" "$2" && return 0 + if cmp -s -- "$LANES_FILE" "$1"; then + die "could not write the rewritten register $LANES_FILE: the write did not reach it, and it is byte for byte as it was before this edit. $3$(reg_written_here)" 5 + fi + if cat -- "$1" > "$LANES_FILE" && cmp -s -- "$LANES_FILE" "$1"; then + die "the rewritten register $LANES_FILE did not land as it was written: the write cut it short, and its earlier bytes have been put back and proved. $3$(reg_written_here)" 5 + fi + rgw_keep=""; rgw_where="" + rgw_git="$(git -C "$LANES_REPO" rev-parse --absolute-git-dir 2>/dev/null)" || rgw_git="" + if [ -n "$rgw_git" ] && [ -d "$rgw_git" ]; then + rgw_to="$rgw_git/lanes-edit-register-before-edit.$(date -u +%Y%m%dT%H%M%SZ).$$" + if [ ! -e "$rgw_to" ] && [ ! -L "$rgw_to" ]; then + if ( umask 077 && set -C && cat -- "$1" > "$rgw_to" ) 2>/dev/null && cmp -s -- "$1" "$rgw_to"; then + rgw_keep="$rgw_to" + else + rm -f -- "$rgw_to" 2>/dev/null || : + fi + fi + fi + if [ -z "$rgw_keep" ]; then + rgw_to="${1%/*}.register-before-edit" + if [ ! -e "$rgw_to" ] && [ ! -L "$rgw_to" ] && chmod 600 -- "$1" 2>/dev/null && mv -- "$1" "$rgw_to" 2>/dev/null; then + rgw_keep="$rgw_to" + rgw_where=" That is the temporary directory, because the checkout's git directory could not take the copy: a restart that empties it loses them, so restore them first." + fi + fi + if [ -n "$rgw_keep" ]; then + rgw_copy="Its exact bytes from before this edit, with any uncommitted edit they held, are kept in $rgw_keep (mode 0600; \`cat -- $rgw_keep > $LANES_FILE\` puts them back, and \`git -C $LANES_REPO diff -- $LANES_PATH\` shows what it lost meanwhile); \`git checkout\` would bring back only its last commit and drop any uncommitted edit.$rgw_where" + else + rgw_copy="Its bytes from before this edit could not be kept either: \`git -C $LANES_REPO diff -- $LANES_PATH\` shows what it lost, and \`git -C $LANES_REPO checkout -- $LANES_PATH\` brings back its last commit, dropping any uncommitted edit it held." + fi + die "could not write the rewritten register $LANES_FILE, and the bytes it had before this edit could not be put back either: IT MAY NOW BE TRUNCATED. Restore it before any other write in $LANES_REPO, because the next one would commit it as a pre-existing edit. $rgw_copy $3$(reg_written_here)" 5 +} + +# Replace line N with $2, leaving every other byte untouched. Verified with +# `git diff --no-index --numstat` (must be exactly 1 added / 1 deleted). +replace_line() { + n="$1"; newline="$2" + # 1 where the line was already exactly what was asked for and nothing was + # written. A caller that prints what it did reads this rather than announcing + # a replacement that did not happen. + REPLACE_LINE_NOOP=0 + TMPD="$(mktemp -d)" + pre="$TMPD/pre"; out="$TMPD/out" + register_copy "$pre" "its line $n is as it was and this edit is not made" + before="$(wc -l < "$pre" | tr -d ' ')" + { + [ "$n" -gt 1 ] && head -n "$((n - 1))" -- "$pre" + printf '%s\n' "$newline" + tail -n "+$((n + 1))" -- "$pre" + } > "$out" + after="$(wc -l < "$out" | tr -d ' ')" + [ "$before" = "$after" ] || die "line count changed ($before -> $after); refusing" 5 + # A LINE THAT IS ALREADY EXACTLY WHAT WAS ASKED FOR IS A WRITE THAT IS DONE, + # AND NOT A PROOF THAT FAILED (measured 2026-09-16, `lanes-edit.sh`). The + # `numstat` below proves this edit touched ONE line by demanding `1 1` from + # `git diff --no-index` — and an edit that changes nothing produces NO OUTPUT + # AT ALL, so `$stat` came back empty, the equality was false, and the act + # died 5 with `numstat: none`. The guard read "nothing changed" as "more than + # one line changed", which are opposite facts. + # + # IT IS REACHED BY ORDINARY USE AND NOT BY A CONTRIVANCE. `set-row-state` + # writes ` · $(utc_now) · ` and `utc_now` is seconds, so two + # stamps of the SAME state phrase inside one second are byte-identical — two + # `lane-start --no-launch` runs of one lane in one window, which is exactly + # what `tests/test_lane_helpers.sh`'s Amendment 15 `--confirm` case does, and + # what made it fail about one run in two with `expected [0], got [5]`. On a + # workstation it is a lane stamped twice in a second being told its write was + # refused, when the register already says precisely what the caller asked for. + # + # THE CALLERS ARE SAFE WITH IT: nothing is written, so `commit_push` finds + # nothing staged and says so on its own line, and every one of the four + # callers (`set-row-state`, `append-session-id`, `replace-in-row` and + # `migrate-state-cells`) wanted the file to SAY something rather than to + # differ from what it said. Nor does it push: a write with nothing staged + # publishes nothing, whatever this shared checkout has queued ahead of + # origin; only `commit` does that, and only what its path filter passes (#194). + if cmp -s -- "$pre" "$out"; then + REPLACE_LINE_NOOP=1 + note "line $n of $LANES_FILE is already exactly what this write asked for — nothing rewritten, and nothing to commit" + return 0 + fi + stat="$(git --no-pager diff --no-index --numstat -- "$pre" "$out" 2>/dev/null | head -n1 | cut -f1,2)" + [ "$stat" = "$(printf '1\t1')" ] || die "edit touched more than one line (numstat: ${stat:-none}); refusing" 5 + # THE WRITE IS CHECKED (Copilot round 3 on openRepoTools#81). `cat > file` + # here is the last act of every row edit in this file — `append-row-status`, + # `replace-in-row`, `append-session-id` and Amendment 16's `rename-lane` — + # and unchecked it returns 0 having written NOTHING when `LANES.md` is not + # writable: the two proofs above pass (they are made against a temporary + # file), the note says the line was rewritten, and the caller commits whatever + # else it changed. For a rename that is the alias landing while the row it + # points at never moves. AND ITS RESULT IS PROVED, not only its status, with + # the register put back where the write cut it short (#120 item 1, above). + register_rewrite "$pre" "$out" "Its line $n is not rewritten, and $(reg_committed)." + note "line $n rewritten in $LANES_FILE" +} + +# LINES REMOVED AND NOTHING ELSE TOUCHED — `replace_line`'s proof, for the one +# act that takes rows OUT of the register (Amendment 19(d): `archive-rows` +# MOVES a repository's RETIRED rows to `lanes/archive/LANES-retired.md`). The +# rows are appended to the archive FIRST and removed here second, so a refusal +# between the two leaves the register whole and the archive holding a copy — +# never the other way round, which would be the one order that loses a row. +# +# THE NUMBERS ARE THE PROOF: exactly N fewer lines, and `git diff --numstat` +# showing N deleted and ZERO added. A deletion that also rewrote a line would +# pass a line count and fail this. +delete_lines() { # + dl_list="$1" + dl_n="$(printf '%s\n' "$dl_list" | grep -c . || :)" + [ "$dl_n" -gt 0 ] || return 0 + TMPD="$(mktemp -d)" + dl_pre="$TMPD/pre"; dl_out="$TMPD/out" + # WHAT A REFUSAL HERE SAYS ABOUT THE ROWS IS THE CALLER'S (the delta review of + # #263, NIT). archive-rows' sentences are the default: its rows are already in + # the archive. add-row's take-back passes its own, because there the row is + # add-row's committed one and no archive is involved. + dl_unchanged="${DL_SAYS_UNCHANGED:-no row was removed, the rows are in $LANES_ARCH_PATH, and the register is whole}" + dl_after_write="${DL_SAYS_AFTER_WRITE:-The archive may have been appended locally, but $(reg_committed); resolve that partial move before retrying.}" + register_copy "$dl_pre" "$dl_unchanged" + # AND EVERY LATER REFUSAL HERE SAYS IT AS WELL (delta review 4 of #263, N1 + # and S4's N2). The pass, the line count and `numstat` below refused with no + # word of what the act had committed: add-row's take-back, which HAS committed + # its row, died saying only "the removal added or rewrote lines" or "that row + # is still in it and in that commit", with no row and no commit named, and the + # next write published the row. Each now ends as `register_copy`'s refusal + # does: the register as it was, what this act has committed, the caller's + # sentence, and what the act has already written in this checkout. + dl_as_was="The register is as it was and $(reg_committed): $dl_unchanged.$(reg_written_here)" + dl_before="$(wc -l < "$dl_pre" | tr -d ' ')" + # `awk -v` CARRIES ONE LINE, AND THIS LIST IS MANY — the finding `who_landing` + # took in round 5 of A9 Addendum 4 (R-A9-11), re-made here and answered by + # `tests-macos` at `758a536` with six red lines and nothing saying why. A + # `-v name=value` is processed as if it were a STRING LITERAL, and a string + # literal cannot span lines: macOS's awk (one-true-awk) refuses it outright — + # `awk: newline in string … at source line 1`, exit 2, NO OUTPUT AT ALL — + # while gawk and mawk accept it silently, so no Linux job and no workstation + # here can see it. What it cost is exactly what it cost there: an empty + # `$dl_out`, a line count that fails its own proof, and `archive-rows --yes` + # dying 5 with the rows already in the archive and the register untouched. + # `ENVIRON` has no such restriction and is POSIX awk, so the list goes through + # the environment of this one command, which is the spelling `who_landing` + # settled on. Asserted on every platform by a shim that IS the one-true-awk + # rule (`tests/test_lane_helpers.sh`, the `repo19d` case). + # + # AND THE PASS IS READ WITH ITS OWN STATUS. An awk that failed writes an empty + # file, and an empty file is not "no rows matched" (Amendment 7(d)) — it is a + # read that failed, and it must say so rather than arrive at the line-count + # proof as a wrong number, which is the shape the macOS job had to be + # reverse-engineered from. + if ! LANES_DROP_LINES="$dl_list" awk ' + BEGIN { k = split(ENVIRON["LANES_DROP_LINES"], a, "\n") + for (i = 1; i <= k; i++) if (a[i] != "") drop[a[i] + 0] = 1 } + !(NR in drop)' "$dl_pre" > "$dl_out"; then + die "the pass that removes $dl_n row(s) from $LANES_FILE failed, so what the register would become is not known — and that is not an empty register (Amendment 7(d)). $dl_as_was" 5 + fi + dl_after="$(wc -l < "$dl_out" | tr -d ' ')" + [ "$dl_after" -eq "$((dl_before - dl_n))" ] || + die "removing $dl_n row(s) changed the line count by $((dl_before - dl_after)); refusing. $dl_as_was" 5 + # AND IT COUNTS LINES WHATEVER THE REGISTER'S SIZE (delta review 4 of #263, + # S4). Under a `core.bigFileThreshold` below the register's size git classes + # both copies as binary, and `numstat` prints a `-` for each count, which + # `--text` does not change: add-row's take-back refused there, and its row + # stayed committed for the next write to publish. A `-c` on the command line + # outranks every config file and `GIT_CONFIG_*` in the environment (measured + # on git 2.43). An attribute or a NUL byte that classes the copies as binary + # still makes this proof refuse, in the words above. + dl_stat="$(git --no-pager -c core.bigFileThreshold=2g diff --no-index --numstat -- "$dl_pre" "$dl_out" 2>/dev/null | head -n1 | cut -f1,2)" + [ "$dl_stat" = "$(printf '0\t%s' "$dl_n")" ] || + die "the removal added or rewrote lines (numstat: ${dl_stat:-none}); refusing. $dl_as_was" 5 + # The redirection follows the register symlink, but its status is still a + # write fence. An unwritable target must not let archive-rows commit the + # appended archive while the source rows remain in the register. And its + # RESULT is the fence as well, with the register put back where the write cut + # it short (#120 item 1, above `replace_line`). + register_rewrite "$dl_pre" "$dl_out" "$dl_after_write" + note "$dl_n row(s) removed from $LANES_FILE" +} + +# $2 is the file to append to, defaulting to the register. Amendment 7's +# per-lane object logs are appended with exactly the same proof — one line +# more, not one existing byte different. +append_text_line() { + newline="$1"; target="${2:-$LANES_FILE}" + # ONE LINE IS REFUSED A NEWLINE BEFORE IT IS WRITTEN, NOT PROVED ONE AFTER + # (opensoft/openRepoTools#85). The proofs below are made AFTER the `>>`, so a + # text carrying a newline was appended whole — two physical lines where one + # was meant — and only then refused: `append changed line count by 2`, exit + # 5, the file left modified and uncommitted. What came next was worse than + # the refusal. A dirty object log is refused by every later writer in that + # checkout; a dirty REGISTER is committed by the next one, as a peer's + # `pre-existing` edit (`handle_preexisting`) — measured in `lane-handoff`'s own + # flow, where the row flip right after the refused PAUSED line committed the + # two lines. A carriage return is refused with it: `wc -l` does not count one, so it + # passed the proof and put a line no reader splits the same way into a file + # nothing rewrites. `write_event` has refused both since R21; this is the + # same gate in the one function every append goes through, which is the + # reason this file gives for putting the container guard at the dispatcher: + # *"nine copies of one rule is how eight of them would come to disagree"*. + # FIRST, before the `mktemp` and the copy, so a refusal touches nothing. + if [ "${newline//[$'\n\r']/}" != "$newline" ]; then + die "an appended line is ONE line, and this text carries a newline or a carriage return: appended, it would put several lines into $target where one was meant, and the proof that only one was added fails after the write, not before it. Nothing was written. Spell the break '; ' and re-run." 2 + fi + TMPD="$(mktemp -d)" + pre="$TMPD/pre" + cat -- "$target" > "$pre" + # `| tr -d ' '`, THE SPELLING `park:564` AND `status:746` ALREADY USE — and + # the one function that did not use it was the macOS job's LARGEST SINGLE + # CAUSE (A9 Addendum 4, R-A9-11). BSD `wc` right-aligns every count in a + # fixed-width field, so `wc -l < f` answers `" 5"` on macOS where GNU + # answers `"5"`, while `$((before_lines + 1))` is arithmetic and is never + # padded. `[ " 5" = "5" ]` is FALSE — so on BSD this refused EVERY + # append it was ever asked to make, and refused it HAVING ALREADY APPENDED: + # the `>>` on the line between them had run, so the `die` left the file + # modified and uncommitted, and then every later `lanes-edit.sh` in that + # checkout refused as well (`unstaged tracked change — so the race cannot be + # run safely here`, 48 times in the macOS transcript at `9000e86`). The + # message it died with read `append changed line count by 1`: the very + # equality the test above it had just denied, which is what a comparison of + # a padded string against an unpadded one looks like from the outside. + # Measured: transcript line 454 of the macOS job at `9000e86`. And + # reproduced on Linux under NOTHING BUT a `wc` that pads — the rest of the + # tree exactly as `d3d59b5` shipped it — for **575 passed, 423 failed** + # against that runner's own 560 / 438. Fifteen assertions apart, which is + # about what the second defect (a liveness `sleep` too short for a 900 s + # run, `tests/test_lane_helpers.sh:446`) has left to contribute once this + # one has already taken the checkout down with it. + before_lines="$(wc -l < "$pre" | tr -d ' ')" + printf '%s\n' "$newline" >> "$target" # >> FOLLOWS the symlink + after_lines="$(wc -l < "$target" | tr -d ' ')" + # `-eq`, not `=`: these are NUMBERS, and saying so is what makes a second + # padded spelling arriving from anywhere unable to resurrect the defect. + [ "$after_lines" -eq "$((before_lines + 1))" ] || die "append changed line count by $((after_lines - before_lines)); inspect $target" 5 + # THE WHOLE FILE REBUILT, and no `cmp -n`: the `-n ` that reads + # "compare at most this many bytes" is GNU's, and BSD `cmp`'s trailing + # numbers are SKIPS, not a limit — so where GNU compared a prefix, BSD + # answers `illegal option -- n`, exits 2, and this proof becomes a REFUSAL + # of a write that was perfectly correct, dying 5 with the log line already + # on disk and uncommitted. What the file must now be is exactly its old + # bytes followed by the one new line, so that is what is built and compared: + # `cat`, `printf` and cmp's `-` operand are POSIX, no byte count is needed + # (`head -c 0` is an ERROR on BSD, which is what the first append to an + # empty log would have hit), and the claim is STRONGER than the old one — + # not merely that no existing byte moved, but that the line appended is the + # line that was asked for. + { cat -- "$pre"; printf '%s\n' "$newline"; } | cmp -s -- "$target" - || + die "append rewrote existing bytes; inspect $target" 5 + note "1 line appended to $target" +} + +# ------------------------------------------------------------------ git side + +LANES_BRANCH="${LANES_BRANCH:-main}" + +# Bounded like every other network call (Amendment 8(h)). A timeout here is not +# fatal: the callers already degrade to "no remote branch", which costs a fetch +# that would have hung anyway. +remote_has_branch() { + git_net -C "$LANES_REPO" ls-remote --exit-code --heads origin "$LANES_BRANCH" >/dev/null 2>&1 || { + [ "$GIT_TIMED_OUT" = 1 ] && note "ls-remote timed out after ${GIT_TIMEOUT}s — treating origin/$LANES_BRANCH as unreachable" + return 1 + } + return 0 +} + +# Unstaged changes to TRACKED files OTHER than the register. New in Amendment +# 5 and unavoidable: the register shares its checkout with handoffs/ and +# workspaces/, which other lanes write. `git pull --rebase` refuses outright +# on ANY unstaged tracked change, so without this the refusal would surface as +# a bogus "REBASE CONFLICT" and the writer would be sent to a recovery that +# does not apply. Prints the offending paths, one per line. +dirty_elsewhere() { + git -C "$LANES_REPO" --no-pager diff --name-only 2>/dev/null \ + | grep -v -x -F -- "$(printf '%s\n' "${CP_PATHS[@]}")" || : +} + +# Every TRACKED file in this checkout that differs from HEAD — staged or not, +# and whatever pathspec the caller happens to be writing. That is exactly the +# set `git pull --rebase` refuses on. `git status --porcelain` reports the same +# thing, with rename records and path quoting to parse first; these two +# plumbing reads answer the same question unambiguously, and neither reports an +# untracked file, which does not block a rebase. +tracked_dirty() { + { git -C "$LANES_REPO" --no-pager diff --name-only 2>/dev/null + git -C "$LANES_REPO" --no-pager diff --name-only --cached 2>/dev/null + } | LC_ALL=C sort -u +} + +# AMENDMENT 7 — `log`, `claim` and `release` REFUSE a checkout that cannot be +# rebased. $1 names the act; every remaining argument is a pathspec THIS write +# is about to append to and is therefore exempt. +# +# `lanes/LANES.md` is the one exemption that is not a pathspec of the write: +# it is CAPTURED rather than refused, by capture_register_edit below, and the +# guard is then re-run against the checkout that capture left behind. See +# there for why (Addendum 3, R11). +# +# The guard is computed over the WHOLE checkout, and from the same set the +# write will use, because the first version of it was not: `claim` measured +# "dirty elsewhere" against (log + LANES.md) while a CLAIMED writes the log +# alone, so a dirty `lanes/LANES.md` — the one dirty file this repository +# actually has, at ~500 register commits a day — passed the guard and then took +# commit_push's Amendment 5(d) branch, which skips `pull --rebase` and with it +# the rescan that decides the race. Two lanes ended up holding one object with +# no CLAIM-LOST. The guard and the write must never disagree about what this +# invocation is writing. +refuse_dirty_checkout() { + rd_what="$1"; shift + [ "$NO_GIT" = 1 ] && return 0 + git -C "$LANES_REPO" rev-parse --git-dir >/dev/null 2>&1 || return 0 + if [ "$#" -gt 0 ]; then + rd_others="$(tracked_dirty | grep -v -x -F -- "$(printf '%s\n' "$@")" || :)" + else + rd_others="$(tracked_dirty)" + fi + [ -n "$rd_others" ] || return 0 + note "this checkout has uncommitted changes to tracked files that are not this $rd_what's:" + printf ' %s\n' $rd_others >&2 + case "$rd_what" in + claim) note "a claim is decided by which CLAIMED lands on main first, and 'pull --rebase' refuses on any" + note "unstaged tracked change — so the race cannot be run safely here." ;; + *) note "an object-log write is ordered against other lanes by landing on main, and 'pull --rebase'" + note "refuses on any unstaged tracked change — so this write cannot be ordered safely here." ;; + esac + note "RECOVERY — whoever wrote those files commits them:" + note " lanes/LANES.md LANES_LANE= lanes-edit.sh commit \"\"" + note " anything else git -C $LANES_REPO commit -m \"handoff(@): \" -- " + note "then re-run the refused $rd_what: its own push publishes their commits with it (#194)." + die "refusing to $rd_what on a checkout that cannot be rebased" 2 +} + +# ------------------------------------------- AMENDMENT 8, ruling (h): THE +# WRITER NEVER BLOCKS THE ESTATE. +# +# On 2026-09-12 at about 01:44Z an ssh `git-receive-pack` hung for five minutes +# AFTER its push had already landed, and `lanes-edit.sh append-row-status` sat +# inside it holding the mutex for the whole five minutes. Every lane on Eagle +# that wanted to write a row waited behind a lock whose holder was blocked on a +# socket, and the estate only moved again when the ssh was killed by hand. +# +# So every git call that touches the NETWORK — push, pull, fetch, ls-remote — +# runs under a timeout, and a timeout is not a failure to retry: it is a +# refusal to hold the mutex any longer. The helper aborts any rebase it started, +# releases the lock, prints how to find out whether the push landed anyway, and +# exits 3 with the edit safe in a local commit. +# +# `LANES_GIT_TIMEOUT` is the budget in seconds (default 60; 0 disables the +# bound). `LANES_GIT` is the binary, so a test can hand these calls — and ONLY +# these calls — a git that hangs, without shadowing git for the rest of the +# script. +GIT_TIMEOUT="${LANES_GIT_TIMEOUT:-60}" +GIT_BIN="${LANES_GIT:-git}" +GIT_TIMED_OUT=0 +git_net() { + GIT_TIMED_OUT=0 + gn_rc=0 + case "$GIT_TIMEOUT" in + ''|0|*[!0-9]*) "$GIT_BIN" "$@" || gn_rc=$? ;; + *) + if command -v timeout >/dev/null 2>&1; then + timeout -k 5 "$GIT_TIMEOUT" "$GIT_BIN" "$@" || gn_rc=$? + case "$gn_rc" in 124|137) GIT_TIMED_OUT=1 ;; esac + else + "$GIT_BIN" "$@" || gn_rc=$? + fi ;; + esac + return "$gn_rc" +} + +# What a timed-out network call does. NEVER a retry: the point is to stop +# holding the lock, and a second call to the same hung endpoint holds it twice +# as long. +git_timeout_die() { # + note "TIMED OUT after ${GIT_TIMEOUT}s: $1" + note " Amendment 8(h): the writer does not hold the estate's mutex on a hung" + note " network call. The lock is being released now, before this exits." + "$GIT_BIN" -C "$LANES_REPO" rebase --abort 2>/dev/null || : + note " YOUR EDIT IS SAFE — it is already a local commit:" + "$GIT_BIN" -C "$LANES_REPO" --no-pager log --oneline "origin/$LANES_BRANCH..HEAD" 2>/dev/null | head -n 5 >&2 || : + note " RECOVERY — a hung push often means it LANDED and the connection did not close," + note " so look before you push again:" + note " git -C $LANES_REPO fetch origin $LANES_BRANCH && git -C $LANES_REPO log --oneline origin/$LANES_BRANCH -3" + note " git -C $LANES_REPO push origin $LANES_BRANCH # only if it is not there" + release_lock + die "timed out after ${GIT_TIMEOUT}s on '$1' — the mutex is released and your commit is local; nothing was lost." 3 +} + +# BYTECODE NEVER RIDES A WORKSPACE COMMIT (opensoft/openRepoTools#162, cause +# 19: a handoff's attachments were committed with a whole virtualenv's +# `__pycache__` inside them, and the workspace repository carries them for +# ever). What `git add` WOULD stage for a pathspec is asked of git itself +# (`add --dry-run`, which honours `.gitignore` exactly as the real add does), +# and every path in that answer with a cache, bytecode or environment +# component is printed. Empty means the pathspec is clean. +# ONE PER LINE AND READ WITH `read`, never word-split: `*.pyc` unquoted is a +# glob, and the shell would expand it against whatever directory this runs in. +BYTECODE_IGNORES='__pycache__/ +*.pyc +*.pyo +.pytest_cache/ +.mypy_cache/ +.ruff_cache/ +node_modules/ +.venv/ +venv/ +site-packages/' +bytecode_in_pathspec() { # ... 0 read (the paths printed) · 3 a read FAILED + bip_repo="${1-}"; shift || : + [ "$#" -gt 0 ] || return 0 + # WHAT THE ADD WOULD STAGE, AND WHAT IS STAGED ALREADY: `add --dry-run` says + # nothing of a path the index already holds at these bytes, and the commit + # takes it all the same. A staged DELETION of bytecode is a cleanup and is + # let through (`--diff-filter=d`). + # + # A READ THAT FAILED IS NO "CLEAN" (#170 G13): a malformed magic pathspec, or + # an index git cannot read, made both reads exit 128 with their stderr thrown + # away and printed nothing, and the check passed. Each status is kept now. + # `add --dry-run`'s 1 is the one answer that is not a failure: it means some + # NAMED path is ignored, which the add would not stage. + # + # BOTH READS IN THE C LOCALE AND UNQUOTED (#170 E1, E2): the `add ''` + # lines are parsed, and a translated git words them otherwise; and `diff + # --name-only` C-quotes a path that is not ASCII (`"caf\303\251.pyc"`), whose + # closing quote hid the `.pyc` - so a staged non-ASCII bytecode file passed. + # `core.quotePath=false` leaves such a path as its bytes; one git still + # quotes (a control character, a `"` or a `\`) has its quotes taken off + # before it is judged. + bip_add=""; bip_rc=0 + bip_add="$(LC_ALL=C git -C "$bip_repo" -c core.quotePath=false add --dry-run --ignore-missing -- "$@" 2>/dev/null)" || bip_rc=$? + [ "$bip_rc" -le 1 ] || return 3 + bip_staged="" + bip_staged="$(LC_ALL=C git -C "$bip_repo" -c core.quotePath=false diff --cached --name-only --diff-filter=d -- "$@" 2>/dev/null)" || return 3 + { + printf '%s\n' "$bip_add" | LC_ALL=C sed -n "s/^add '\(.*\)'\$/\1/p" + printf '%s\n' "$bip_staged" + } | + LC_ALL=C awk '{ if ($0 ~ /^".*"$/) $0 = substr($0, 2, length($0) - 2) } + !seen[$0]++ { + n = split($0, part, "/"); hit = 0 + for (i = 1; i <= n; i++) + if (part[i] == "__pycache__" || part[i] == ".pytest_cache" || + part[i] == ".mypy_cache" || part[i] == ".ruff_cache" || + part[i] == "node_modules" || part[i] == ".venv" || + part[i] == "venv" || part[i] == "site-packages") hit = 1 + if ($0 ~ /\.py[co]$/) hit = 1 + if (hit) print }' +} + +# The refusal's words, and the OFFER beside them: the ignore lines the +# workspace's own `.gitignore` lacks, with the one command that adds them. +# `openRepoTools wip init` seeds them into a new workspace; an older one is +# offered them here, where they are missing. +bytecode_refusal_text() { # + brt_n="$(printf '%s\n' "${1-}" | awk 'NF { n++ } END { print n + 0 }')" + brt_missing="" + while IFS= read -r brt_l; do + [ -n "$brt_l" ] || continue + command grep -Fqx -- "$brt_l" "$LANES_REPO/.gitignore" 2>/dev/null || + brt_missing="$brt_missing '$brt_l'" + done <> %s\n' \ + "$brt_missing" "$brt_missing" "$brt_target" + fi + printf 'Nothing was staged or committed. Unstage or delete those paths, then re-run.' +} + +# #194, AS #214's ADVERSARIAL CHECK HARDENED IT — WHAT `commit` MAY PUBLISH +# WITH NOTHING STAGED, read from the objects the push will send and nothing +# else. Three ordinary checkout states got a deletion past the first fence, +# which read `git log --name-status origin/..HEAD`: +# +# * A MERGE's own changes: `log` prints no diff for a merge, so a deletion +# made while resolving one passed unread. A merge or root commit refuses. +# * HEAD ON ANOTHER BRANCH: the fence read HEAD and the push sent +# `refs/heads/`. The range is the branch, and HEAD must be it, because +# `pull --rebase` moves HEAD and the push moves the branch. +# * A LOCAL BRANCH NAMED `origin/`, which shadows the tracking ref. Both +# ends of the range are spelled in full. +# +# The reads are plumbing (`rev-list`, `diff-tree --raw`), which no `color.*` or +# `diff.ignoreSubmodules` reshapes, under `--no-replace-objects`, so a replace +# ref cannot show the fence one commit while the push sends another. A change +# passes only as an ADDED or MODIFIED REGULAR FILE under the register's own +# directory (`$LANES_PREFIX`, derived, as every path of the register's is) or +# `handoffs/`, and never as bytecode, a cache or an environment (#162's list). +# A deletion, a type change, a symlink or a gitlink refuses, and so does a path +# anywhere else. IT IS A PATH AND KIND FILTER: it vouches for where a change +# lands and what it is, never for whose it is (it reads no subject, author or +# trailer), so another lane's register write passes it. That includes lane +# tooling's own lane rename, +# which deletes a log to re-add it: a deletion is the one change origin cannot +# get back, and the fence keeps one rule for it. A read or a classification +# that fails refuses too (2), because it proves nothing. +# +# Two guards have a test each (lane openRepoShape-2's SHOULD 4). `--no-renames` +# reads a rename as the deletion it is: read as an `R` line, the refusal would +# name a rename and not the path origin loses. And the register's directories +# are matched with their trailing `/`, so `lanes-archive/` beside `lanes/` is +# not inside it. +# +# It leaves CP_FENCE_TIP at the commit it read and CP_FENCE_AHEAD at how many +# it read, and the publish pushes exactly that commit (`:refs/heads/`). +# A commit another lane makes in this shared checkout between the read and the +# push stays local. +cp_publish_fence() { + cpf_ref="refs/heads/$LANES_BRANCH" + cpf_head="$(git -C "$LANES_REPO" symbolic-ref -q HEAD 2>/dev/null || :)" + [ "$cpf_head" = "$cpf_ref" ] || die "refusing to publish: HEAD is ${cpf_head:-detached}, not $cpf_ref, and the push sends $cpf_ref while \`pull --rebase\` moves HEAD, so what would be published is not what HEAD shows, and nothing was pushed (#194). Whoever moved this shared checkout off $LANES_BRANCH puts it back; never reset or check out over their work." 2 + cpf_rc=0 + cpf_base="$(git --no-replace-objects -C "$LANES_REPO" rev-parse -q --verify "refs/remotes/origin/$LANES_BRANCH^{commit}")" || cpf_rc=$? + cpf_tip="$(git --no-replace-objects -C "$LANES_REPO" rev-parse -q --verify "$cpf_ref^{commit}")" || cpf_rc=$? + cpf_revs="$(git --no-replace-objects -C "$LANES_REPO" rev-list --parents "$cpf_base..$cpf_tip")" || cpf_rc=$? + cpf_odd="$(printf '%s\n' "$cpf_revs" | awk 'NF > 0 && NF != 2 { printf " %s %s\n", substr($1, 1, 12), (NF > 2 ? "is a merge commit" : "is a root commit") }')" || cpf_rc=$? + cpf_pairs="$(printf '%s\n' "$cpf_revs" | awk 'NF == 2')" || cpf_rc=$? + # `diff-tree --stdin` SKIPS A COMMIT IT CANNOT READ and still exits 0, and + # prints no header for an empty diff unless told `--always`: so every commit + # handed to it must come back as a header, or the read refuses. + cpf_raw=""; cpf_n=0 + if [ -n "$cpf_pairs" ]; then + cpf_n="$(printf '%s\n' "$cpf_pairs" | awk 'END { print NR }')" || cpf_rc=$? + cpf_raw="$(printf '%s\n' "$cpf_pairs" | git --no-replace-objects -C "$LANES_REPO" -c core.quotePath=false diff-tree --stdin --always -r --no-renames --raw --ignore-submodules=none)" || cpf_rc=$? + fi + cpf_reg="${LANES_PREFIX:+${LANES_PREFIX%/}/}"; cpf_logp="${LANES_LOG_PREFIX:+${LANES_LOG_PREFIX%/}/}" + cpf_bad="$(printf '%s\n' "$cpf_raw" | awk -F '\t' -v want="$cpf_n" -v reg="$cpf_reg" -v logp="$cpf_logp" \ + -v reg_path="$LANES_PATH" -v alias_path="$LANES_ALIASES_PATH" ' + function inside(p) { + return (reg != "" && index(p, reg) == 1) || (logp != "" && index(p, logp) == 1) || + index(p, "handoffs/") == 1 || p == reg_path || p == alias_path + } + function bytecode(p, n, part, i) { + if (p ~ /\.py[co]$/) return 1 + n = split(p, part, "/") + for (i = 1; i <= n; i++) + if (part[i] == "__pycache__" || part[i] == ".pytest_cache" || part[i] == ".mypy_cache" || + part[i] == ".ruff_cache" || part[i] == "node_modules" || part[i] == ".venv" || + part[i] == "venv" || part[i] == "site-packages") return 1 + return 0 + } + NF == 0 { next } + NF == 1 && $1 ~ /^[0-9a-f]+$/ { c = substr($1, 1, 12); seen++; next } + { split($1, f, " "); st = f[5]; mode = f[2] + if (!(NF == 2 && (st == "A" || st == "M") && (mode == "100644" || mode == "100755") && inside($2) && !bytecode($2))) + printf " %s %s %s %s\n", c, st, mode, $2 } + END { if (seen != want) exit 3 }')" || cpf_rc=$? + [ "$cpf_rc" = 0 ] || die "git could not read, or this helper could not classify, the local commits on $cpf_ref ahead of refs/remotes/origin/$LANES_BRANCH, so whether they are \`commit\`'s to publish is unknown; nothing was pushed (#194)" 2 + if [ -n "$cpf_odd$cpf_bad" ]; then + note "of the local commits on $cpf_ref ahead of origin/$LANES_BRANCH, these are not register or handoff writes (a merge or root commit, or a change that is not an added or modified regular file under ${LANES_PREFIX:-the register directory} or handoffs/):" + [ -z "$cpf_odd" ] || printf '%s\n' "$cpf_odd" >&2 + [ -z "$cpf_bad" ] || printf '%s\n' "$cpf_bad" >&2 + die "refusing to publish: \`commit\` pushes only register and handoff writes (#194), so nothing was pushed. A lane rename (Amendment 16) deletes and re-adds its log and is refused here too; the next register write from this checkout carries it. Anything else, whoever queued it publishes it; never reset it away. Read them: git -C $LANES_REPO log --stat refs/remotes/origin/$LANES_BRANCH..$cpf_ref" 2 + fi + CP_FENCE_TIP="$cpf_tip" + CP_FENCE_AHEAD="$cpf_n" +} + +# The publish's CP_AFTER_REBASE: `pull --rebase` has rewritten the queue onto +# what origin holds now, and may have taken in a commit made since the first +# read, so the fence reads it again and the push is pinned to what it read. +# THE PULL CAN EMPTY THE QUEUE (lane openRepoShape-2, #214 6243280936): origin +# may hold every queued commit already, by content under other shas, because +# another workstation made the same edit or a peer's write carried it. The +# rebase drops each one, and a push would send origin its own tip and print +# "pushed". So the publish ends here, exit 0, as the no-op it now is, and it +# says so. Only `commit` installs this hook, and this commit_push is its last +# act, so the exit is that return. +cp_publish_refence() { + cp_publish_fence + if [ "$CP_FENCE_AHEAD" = 0 ]; then + note "origin/${LANES_BRANCH} already holds every commit this publish listed: \`pull --rebase\` found each one there by content and dropped it, so none is left to push and no push was sent (#194)" + exit 0 + fi + CP_PUSH_SPEC="$CP_FENCE_TIP:refs/heads/$LANES_BRANCH" +} + +# commit_push "" [...] — the pathspecs default to the +# register alone, which is every caller that predates Amendment 7. A LANDING +# or LANDED writes TWO (the register and the lane's log) so that both halves +# of one act land in one commit and no reader ever sees half of it. +# AMENDMENT 15 — A CASE-ONLY RENAME IS STAGED IN THE INDEX AND COMMITTED FROM +# IT, because a PATH-LIMITED commit cannot record one at all on a +# case-INSENSITIVE filesystem — which is what this repository's macOS job runs +# on. `ensure_log` renames a lane's log to the register row's spelling and +# hands the OLD path in beside the new one. Three things are true there, and +# together they leave exactly one way through: +# +# * `git add -- ` under git's own `core.ignorecase=true` matches +# both pathspecs to the ONE index entry and stages a MODIFICATION under the +# old name, so the rename never reaches the commit. Measured on the macOS +# job of openRepoTools#41 at `48f2111`: fifteen red assertions, the first +# of them *"the rename landed in the WRITE's own commit"*, whose +# `git log -- ` came back EMPTY. +# * The same `add` under `core.ignorecase=false` is no better, and is worse: +# the OPERATING SYSTEM still resolves `lanes/log/repocase-1.md` to the file +# now named `repoCase-1.md`, so git stages the old entry as MODIFIED and +# the new path as a SECOND entry. One file on disk, two paths in the tree — +# and every checkout after it reports the one it cannot materialise as +# deleted, so the writes behind it are refused (2) for a dirty checkout +# they did not make. Measured at `e35f2a8` and `928908a`: eleven red +# assertions, all of them behind `lanes/log/repocase-1.md` reported dirty. +# * `git commit -- ` is `--only`: it builds the tree from HEAD and the +# WORKING TREE of those paths, disregarding what is staged. So an index +# that holds the rename exactly is thrown away by the commit anyway, and +# the old path — which the OS still resolves — comes back in the tree. +# +# So the old entry is dropped from the INDEX by its exact path, where no +# filesystem is consulted at all; the NEW path alone is added; and the commit +# is made from the index rather than from a pathspec. +# `update-index --force-remove` is the one git verb that removes an entry +# without asking the filesystem whether the file is still there, and it is a +# no-op on a path the index does not hold — so a log that was never committed +# renames just as quietly. The index commit is FAIL-CLOSED: anything staged +# that is not one of this write's own pathspecs refuses (6) instead of riding +# along, which is the guarantee the `--only` pathspec was there to give. +# +# `-c core.ignorecase=false` stays on every call that takes `CP_PATHS`, because +# a pathspec that means one thing to `add` and another to `diff` is the same +# defect one line along: with the old entry already gone it is what makes `add` +# record the new path in the spelling the code computed rather than the one the +# index used to hold. It narrows nothing else — these paths are this file's own, +# `lanes/LANES.md` and `lanes/log/.md`, spelled by the code that computes +# them. +CP_EXACT="core.ignorecase=false" +commit_push() { + msg="$1"; shift || : + if [ "$#" -gt 0 ]; then CP_PATHS=("$@"); else CP_PATHS=("$LANES_PATH"); fi + [ "$NO_GIT" = 1 ] && { note "LANES_NO_GIT=1 — not committing"; return 0; } + # THE OLD PATH IS A PATHSPEC FOR THE DIFFS AND NEVER FOR THE `add`: after the + # index entry is force-removed it matches neither the index nor a directory + # read that compares exactly, and `git add` FAILS on a pathspec that matches + # nothing at all. + cp_ren="${LOG_RENAMED_FROM:-}" + cp_add=(); cp_add_n=0 + for cp_p in ${CP_PATHS[@]+"${CP_PATHS[@]}"}; do + if [ -n "$cp_ren" ] && [ "$cp_p" = "$cp_ren" ]; then continue; fi + cp_add+=("$cp_p"); cp_add_n=$((cp_add_n + 1)) + done + if [ -n "$cp_ren" ]; then + git -C "$LANES_REPO" -c "$CP_EXACT" update-index --force-remove -- "$cp_ren" \ + || die "git update-index --force-remove $cp_ren failed — the log is already renamed on disk and git still holds the old path, so nothing was committed. Re-run; if it refuses again, \`git -C $LANES_REPO rm --cached -- $cp_ren\` is the same act by hand." 6 + fi + if [ "$cp_add_n" -gt 0 ]; then + cp_brc=0 + cp_byte="$(bytecode_in_pathspec "$LANES_REPO" ${cp_add[@]+"${cp_add[@]}"})" || cp_brc=$? + [ "$cp_brc" = 0 ] || die "git could not read what this commit would stage (a pathspec it cannot parse, or an index it cannot read), so whether it carries bytecode is unknown; nothing was staged or committed (opensoft/openRepoTools#170 G13)" 2 + [ -z "$cp_byte" ] || die "$(bytecode_refusal_text "$cp_byte")" 2 + git -C "$LANES_REPO" -c "$CP_EXACT" add -- ${cp_add[@]+"${cp_add[@]}"} || die "git add failed" 6 + fi + # #194 — NOTHING STAGED IS NOT NOTHING TO PUBLISH, FOR `commit` ALONE. A + # write the push loop below could not get out (a peer's uncommitted file + # blocking the rebase, six rejected pushes) leaves its edit as a LOCAL commit, + # and the RECOVERY printed for it is to re-run `commit` once the way is clear. + # Returning here sent that re-run home with exit 0 and the commit still local. + # So `commit`, the one caller that sets CP_PUBLISH_AHEAD, still takes the push + # loop (its lock, the dirty-elsewhere guard, the retries) whenever the branch + # holds commits `origin/$LANES_BRANCH` does not, as of the last fetch; no such + # ref reads as none. Every other write with nothing to stage stays the no-op it + # always was and reaches no network: a repeated `set-row-state` must not turn + # into a push of whatever this SHARED checkout has queued (the #214 review + # measured exactly that deleting `scripts/link-estates` on origin). + # + # AND `commit` PUBLISHES ONLY REGISTER AND HANDOFF WRITES, and only what it read: + # `cp_publish_fence` (above) reads the queue on the branch the push sends and + # refuses the whole publish (2) for anything that is not a register or + # handoff write. The push is pinned to the commit the fence read, and every + # `pull --rebase` reads it again (CP_AFTER_REBASE) and re-pins it. + cp_publish=0 + if git -C "$LANES_REPO" -c "$CP_EXACT" diff --cached --quiet -- "${CP_PATHS[@]}"; then + cp_ahead="$(git --no-replace-objects -C "$LANES_REPO" --no-pager log --oneline "refs/remotes/origin/$LANES_BRANCH..refs/heads/$LANES_BRANCH" 2>/dev/null || :)" + if [ -z "$cp_ahead" ]; then + note "nothing staged for ${CP_PATHS[*]} — no commit made" + return 0 + fi + cp_n="$(printf '%s\n' "$cp_ahead" | awk 'END { print NR }')" + if [ "$CP_PUBLISH_AHEAD" != 1 ]; then + note "nothing staged for ${CP_PATHS[*]} — no commit made; the $cp_n local commit(s) ahead of origin/$LANES_BRANCH stay local. \`lanes-edit.sh commit\` would publish all of them, so read \`git -C $LANES_REPO cherry -v origin/$LANES_BRANCH HEAD\` first: another lane's commits are its own to publish" + return 0 + fi + cp_publish_fence + note "nothing staged for ${CP_PATHS[*]} — no commit made; pushing the $cp_n local commit(s) origin/$LANES_BRANCH does not have, up to ${CP_FENCE_TIP:0:12}:" + printf '%s\n' "$cp_ahead" | head -n 10 >&2 || : + [ "$cp_n" -le 10 ] || note " … and $((cp_n - 10)) more" + CP_PUSH_SPEC="$CP_FENCE_TIP:refs/heads/$LANES_BRANCH" + CP_AFTER_REBASE=cp_publish_refence + cp_publish=1 + fi + if [ "$cp_publish" = 1 ]; then + : # nothing of this write's own to commit: straight on to the push + elif [ -n "$cp_ren" ]; then + cp_staged="$(git -C "$LANES_REPO" -c "$CP_EXACT" diff --cached --name-only)" + cp_extra="" + while IFS= read -r cp_s; do + [ -n "$cp_s" ] || continue + cp_known=0 + for cp_p in ${CP_PATHS[@]+"${CP_PATHS[@]}"}; do + if [ "$cp_s" = "$cp_p" ]; then cp_known=1; fi + done + if [ "$cp_known" = 0 ]; then cp_extra="$cp_extra $cp_s"; fi + done <&2 + note "skipping 'pull --rebase' (it refuses on any unstaged tracked change) and pushing straight out" + if git_net -C "$LANES_REPO" push -q origin "${CP_PUSH_SPEC:-$LANES_BRANCH}"; then + LANES_INDEX_NUDGE=1 + note "pushed origin/$LANES_BRANCH (attempt $attempt, no pull — see the warning above)" + return 0 + fi + [ "$GIT_TIMED_OUT" = 1 ] && git_timeout_die "git push origin $LANES_BRANCH" + note "push rejected and the pull is blocked by the files above (attempt $attempt)" + if [ "$attempt" -ge 6 ]; then + note "RECOVERY: their author commits those files (a handoff: handoff(@): )," + note " then re-run: LANES_LANE= lanes-edit.sh commit \"\" — your edit is already" + note " a local commit here. If $LANES_PATH is clean, that re-run makes no commit of its own and" + note " pushes the local commits this lists (#194), refusing (2) and pushing nothing unless every one" + note " is a register or handoff write: git -C $LANES_REPO log --oneline origin/$LANES_BRANCH..HEAD" + die "could not push origin/$LANES_BRANCH: behind the remote, and a peer's uncommitted file blocks the rebase. Nothing was lost — your commit is local." 3 + fi + elif git_net -C "$LANES_REPO" pull --rebase -q origin "$LANES_BRANCH"; then + # The rebase has just put this invocation's commit on top of whatever + # landed first. `claim` hooks in HERE, because that is the moment the + # race is decided: if a peer's claim is on this history, theirs landed. + if [ -n "${CP_AFTER_REBASE:-}" ]; then + "$CP_AFTER_REBASE" || return $? + fi + if git_net -C "$LANES_REPO" push -q origin "${CP_PUSH_SPEC:-$LANES_BRANCH}"; then + LANES_INDEX_NUDGE=1 + note "pushed origin/$LANES_BRANCH (attempt $attempt)" + return 0 + fi + [ "$GIT_TIMED_OUT" = 1 ] && git_timeout_die "git push origin $LANES_BRANCH" + note "push raced (attempt $attempt) — retrying" + else + # A TIMED-OUT PULL IS NOT A CONFLICT. Read as one it would send the writer + # to a recovery that does not apply, and `rebase --abort` would be the + # only true line in it. + [ "$GIT_TIMED_OUT" = 1 ] && git_timeout_die "git pull --rebase origin $LANES_BRANCH" + note "REBASE CONFLICT on origin/$LANES_BRANCH — conflicting lines follow:" + for cp in "${CP_PATHS[@]}"; do + grep -n -e '^<<<<<<<' -e '^=======' -e '^>>>>>>>' -- "$LANES_REPO/$cp" 2>/dev/null | head -n 40 >&2 || : + grep -n -A2 -e '^<<<<<<<' -- "$LANES_REPO/$cp" 2>/dev/null | head -n 40 >&2 || : + done + git -C "$LANES_REPO" rebase --abort 2>/dev/null || : + cp_sha="$(git -C "$LANES_REPO" rev-parse HEAD 2>/dev/null)" + note "rebase ABORTED — the worktree is clean and NOT mid-rebase. Your edit is safe in these local commits:" + git -C "$LANES_REPO" --no-pager log --oneline "origin/$LANES_BRANCH..HEAD" 2>/dev/null | head -n 10 >&2 || : + # #32 — AN ABORTED PULL IS NOT PROOF THIS COMMIT NEVER REACHED ORIGIN + # (the same rule RV-B3 took for the handoff stamp's own push, in + # lane-start). This checkout is shared with every lane on the + # workstation, so the very next write out of it pulls this dangling + # commit onto its own and pushes both together — three of the four + # "rebase conflict … nothing was pushed" lines seen on Eagle in one + # hour named a commit that was ALREADY on origin by the time anyone + # read them. LOOK before you reset or redo anything — by ANCESTRY + # (Copilot round 2 on #50, 5203033893): a log capped at a few entries + # can bury this commit below the window while it stays an ancestor, the + # moment four or more later writes land ahead of it. + # ROUND 3 (Copilot 5203261904): `fetch && merge-base ... && echo A || + # echo B` is left-associative — a FAILED fetch also falls to the `||` + # and prints the SAME "not-there" a genuine non-ancestor does, so a + # stale or unreachable origin would silently wave the reset/redo path + # through. Fetch is now its own line, checked before anything else. + # ROUND 4 (Copilot 5203455553): SHA ancestry is the wrong test — the + # very write this whole recovery exists to catch (a peer's own + # `commit_push` pulling THIS dangling commit and rebasing it onto a + # newer base, per the very next branch above) gives it a NEW sha, so + # `merge-base --is-ancestor $cp_sha …` answers "not-there" even once + # the CONTENT is published. `git cherry` compares by PATCH, not by + # sha, so a rebase that only replays the same change (no real + # conflict) is still found. Measured against a real bare repo: a + # commit rebased by a peer this way answers `not-there` under + # `merge-base --is-ancestor` and `-` (found, equivalent) under + # `git cherry` — verified for the genuinely-absent case too (`+`) and + # the plain same-sha case (no output at all, which the `-c '^+'` + # count below also reads as zero, i.e. already there). + note "RECOVERY (in that order):" + note " git -C $LANES_REPO fetch origin $LANES_BRANCH || echo FETCH-FAILED # if that printed FETCH-FAILED, STOP and retry — a stale or unreachable origin proves nothing either way" + note " git -C $LANES_REPO cherry origin/$LANES_BRANCH $cp_sha | grep -c '^+' # BY CONTENT, not by sha: a peer's rebase changes the hash but git cherry still finds the same patch" + note " if that printed 0, STOP — reset or redo now would write it a second time." + note " git -C $LANES_REPO rev-parse HEAD # if this is not $cp_sha, STOP: the checkout moved after this abort, and the lines below no longer describe it" + note " git -C $LANES_REPO cherry -v origin/$LANES_BRANCH HEAD # WHOSE: one '+' line per local commit origin lacks, which is what the reset below drops" + note " if any '+' line is not your own write, STOP and take it to the lane its subject names; a LANES(concurrent@…) or" + note " LANES(pre-existing@…) capture names no lane, so it is NOT yours. Never reset, stash or overwrite a peer's work:" + note " the reset below drops EVERY '+' commit in this checkout, theirs with yours, and origin holds no copy of any of them (#194)." + note " git -C $LANES_REPO diff origin/$LANES_BRANCH..HEAD -- ${CP_PATHS[*]} # only if it is not there: read back exactly what you wrote" + note " git -C $LANES_REPO reset --hard origin/$LANES_BRANCH # only if every '+' line is yours: drop the local commits (NOTE: also drops any" + note " # uncommitted peer edit in this checkout)" + note " then re-read LANES.md and redo the edit with lanes-edit.sh, on top of the peer's version." + die "rebase conflict on origin/$LANES_BRANCH — not pushed by this attempt; a later write from this checkout may already carry it, so look before you retry." 3 + fi + attempt=$((attempt + 1)) + sleep 3 + done + die "could not push origin/$LANES_BRANCH after 6 attempts; your commit is local — retry later" 6 +} + +# ====================================================== AMENDMENT 14 ======= +# +# THE DERIVED INDEX (lane-collision-protocol Amendment 14, ratified by Brett +# Heap 2026-10-05, verbatim "ratify 48"). The register's truth stays where it +# is; `lanes-index` keeps a DERIVED copy of it — SQLite on local disk, or QA +# Postgres where a workstation is configured for it — written behind the +# sources, read only by tooling that decides nothing, and never a gate. +# +# THIS FILE TOUCHES IT IN EXACTLY TWO PLACES, AND NEITHER IS ON AN ACT'S PATH. +# +# THE NUDGE (clause (d)). After a push has LANDED and the mutex is released — +# `cleanup`, on the way out, once `commit_push` has recorded a push that went +# through — ONE DETACHED `lanes-index sync`: stdin closed, stdout and stderr +# on /dev/null, descriptors 3 to 9 closed, started from a subshell that +# exits at once so this process never has a child to wait for, and its +# status never read. It carries no data: the indexer reads `origin/` +# as the push left it, never takes this file's mutex, and a slow, failing or +# absent indexer delays and fails nothing here. `LANES_INDEX=off` skips it, +# and so does a workstation with no `lanes-index` ON PATH — PATH alone, not +# the file beside this one, because a sibling in a clone is not an +# installation and the suite runs this file thousands of times from one: the +# absent case is one `command -v` and prints nothing. +# +# THE READ FLAG (clause (b)). `lanes ... --index` and `history ... --index`, +# and only when TYPED: `index_open` asks `lanes-index export` for the index's +# image of the register, and the eight PUBLISHED-READ primitives — the +# register, the archive, the alias table, the log list, a log's events, the +# events of them all — answer out of that image instead of `origin/`. +# Everything else the read does is unchanged, the LOCAL reads included (this +# checkout's own register and log files, this workstation's session records, +# tmux), which is what makes its answer byte-identical to the source read's +# where the index is current. Anything else — the indexer absent, the store +# missing, unreachable, wiped or of another schema, a configuration it +# refuses — is said in ONE line and the source read runs as it always did. +# +# NOTHING ELSE READS IT. No act, no hook, no guard, no writer and none of the +# reads an act makes for itself (`who`, `binding`, `live-holder`, `next-free`, +# `managed-projection`, `lane-reconcile`) has a path to `LANES_IDX_DIR`: it is +# assigned empty at start-up whatever the environment says, and set only by +# `index_open`, which only the two read arms call. +# +# THE INVENTORY'S NUDGE IS THE SAME ONE (opensoft/openRepoTools#161). The #97 +# inventory writers — `set-lane-state`, `set-lane-tree`, the lifecycle follow +# `write_event` makes after a `STARTED`/`RESUMED`/`ENDED`/`RETIRED`, and the +# rename that moves a lane's control root — write no commit and push nothing, +# so they leave `LANES_INDEX_NUDGE_INV` instead, and the same detached fork is +# made with `--source inventory`: the indexer reads this workstation's +# sidecars as they now stand, through this file's own `worktrees` read. A write +# that did both (a `STARTED` that landed and moved the snapshot) makes both +# forks; `lanes-index` runs one sync at a time per workstation, and a second +# that finds the lock held leaves the holder a mark naming its source. +index_nudge() { + in_reg="${LANES_INDEX_NUDGE:-0}"; in_inv="${LANES_INDEX_NUDGE_INV:-0}" + LANES_INDEX_NUDGE=0; LANES_INDEX_NUDGE_INV=0 + [ "${LANES_INDEX:-}" = off ] && return 0 + in_bin="$(command -v lanes-index 2>/dev/null || :)" + [ -n "$in_bin" ] || return 0 + if [ "$in_reg" = 1 ]; then + ( "$in_bin" sync /dev/null 2>&1 3>&- 4>&- 5>&- 6>&- 7>&- 8>&- 9>&- & ) >/dev/null 2>&1 + fi + if [ "$in_inv" = 1 ]; then + ( "$in_bin" sync --source inventory /dev/null 2>&1 3>&- 4>&- 5>&- 6>&- 7>&- 8>&- 9>&- & ) >/dev/null 2>&1 + fi + return 0 +} + +# THE READ FLAG'S ONE DOOR. 0 with `LANES_IDX_DIR` set and `read: index (...)` +# said; 1 with `read: sources (index )` said and NOTHING set, so the caller +# runs the source read exactly as it would have without the flag — and exits as +# that read would. Both lines go to stderr: stdout is the read's own, and a +# person diffing the two answers diffs the answer. +# +# THE LAG IS SAID, NEVER REFUSED (clause (b)): `` is how many commits this +# checkout's `origin/` carries past the indexed one, and `unknown` where +# that commit is not here to count from. +# +# `index_open worktrees` IS THE SAME DOOR FOR THE `worktrees` TABLE +# (opensoft/openRepoTools#161): `export --worktrees` writes every +# `inventory:` source the store holds, `LANES_WT_IDX_DIR` is set +# and `LANES_IDX_DIR` is NOT — so not one published read of the register is +# answered out of the index by it — and the line names each source with the +# time it was synced, because an inventory has no commit to count a lag in. +index_open() { # [worktrees] + io_kind="${1-register}" + LANES_IDX_DIR="" + LANES_WT_IDX_DIR="" + if [ "${LANES_INDEX:-}" = off ]; then + printf 'read: sources (index off: LANES_INDEX=off)\n' >&2 + return 1 + fi + io_bin="" + if [ -x "$SCRIPT_DIR/lanes-index" ]; then io_bin="$SCRIPT_DIR/lanes-index" + else io_bin="$(command -v lanes-index 2>/dev/null || :)" + fi + if [ -z "$io_bin" ]; then + printf 'read: sources (index missing: no lanes-index beside %s or on PATH)\n' "$SCRIPT_DIR/lanes-edit.sh" >&2 + return 1 + fi + io_dir="$(mktemp -d "${TMPDIR:-/tmp}/lanes-index-read.XXXXXX" 2>/dev/null || printf '')" + if [ -z "$io_dir" ]; then + printf 'read: sources (index unread: no temporary directory could be made)\n' >&2 + return 1 + fi + io_rc=0 + io_xa="" + [ "$io_kind" = worktrees ] && io_xa=--worktrees + if command -v timeout >/dev/null 2>&1; then + timeout -k 2 30 "$io_bin" export --out "$io_dir" ${io_xa:+"$io_xa"} /dev/null 2>"$io_dir/.stderr" || io_rc=$? + else + "$io_bin" export --out "$io_dir" ${io_xa:+"$io_xa"} /dev/null 2>"$io_dir/.stderr" || io_rc=$? + fi + if [ "$io_rc" != 0 ] || [ ! -f "$io_dir/meta" ]; then + io_why="" + [ -f "$io_dir/why" ] && io_why="$(head -n 1 -- "$io_dir/why" 2>/dev/null || :)" + case "$io_rc" in 124|137) io_why="unreachable: lanes-index export did not answer within 30 s" ;; esac + if [ -z "$io_why" ]; then + io_why="unread: lanes-index export exited $io_rc" + io_err="$(head -n 1 -- "$io_dir/.stderr" 2>/dev/null || :)" + [ -z "$io_err" ] || io_why="$io_why: $io_err" + fi + rm -rf -- "$io_dir" + printf 'read: sources (index %s)\n' "$io_why" >&2 + return 1 + fi + io_store="$(sed -n -e 's/^store=//p' "$io_dir/meta" | head -n 1)" + if [ "$io_kind" = worktrees ]; then + # A FIFTH FIELD IS THE LAST ERROR this workstation's own record of the + # source carries (N2 of the review of #289): a sync that refused a listing + # that was not whole left the table as it was, and `synced` alone did not + # say that a later sync had failed, or why. It is named as `status` names + # it, because a refused `reconcile`, a `--dry-run` included, records one + # too (review r2 of #289, NIT-1). + io_at="$(awk -F'\t' '$1 == "inventory" { printf "%s%s synced %s%s", (n++ ? "; " : ""), $2, $3, ($5 != "" ? " (last error: " $5 ")" : "") }' "$io_dir/meta")" + LANES_WT_IDX_DIR="$io_dir" + printf 'read: index (%s) at %s\n' "${io_store:-unknown}" "${io_at:-no inventory source}" >&2 + return 0 + fi + io_sha="$(sed -n -e 's/^sha=//p' "$io_dir/meta" | head -n 1)" + io_behind=unknown + if [ -n "$io_sha" ] && have_remote_ref; then + io_n="$(git -C "$LANES_REPO" rev-list --count "$io_sha..origin/$LANES_BRANCH" 2>/dev/null || :)" + case "$io_n" in ''|*[!0-9]*) : ;; *) io_behind="$io_n" ;; esac + fi + LANES_IDX_DIR="$io_dir" + # WHAT WAS READ BEFORE THE FLAG WAS HONOURED IS NOT WHAT IS READ AFTER IT: + # every published-read cache this process may already hold is dropped. + LANES_REGISTER_CACHE="" + [ -n "${SE_CACHE_FILE:-}" ] && rm -f -- "$SE_CACHE_FILE.register" + lane_alias_flush + state_events_flush + printf 'read: index (%s) at register@%s; %s commits behind\n' "${io_store:-unknown}" "${io_sha:0:12}" "$io_behind" >&2 + return 0 +} + +# Prints, to stdout, a comma-joined, de-duplicated list of the lane(s) whose +# row changed in the CURRENT unstaged diff of LANES.md — identified by the +# first backtick token on each changed (+/-) line — or "append" for a +# changed line that is not a `| ... |` row (e.g. a Rule 6 LANDING/LANDED +# line, which names no row of its own). +identify_changed_lanes() { + git -C "$LANES_REPO" --no-pager diff -- "${CP_PATHS[@]}" 2>/dev/null | awk ' + /^[+-][^+-]/ { + line = substr($0, 2) + lane = "append" + if (substr(line, 1, 1) == "|") { + p1 = index(line, "`") + if (p1 > 0) { + rest = substr(line, p1 + 1) + p2 = index(rest, "`") + if (p2 > 0) lane = substr(rest, 1, p2 - 1) + } + } + if (!(lane in seen)) { seen[lane] = 1; order[++n] = lane } + } + END { for (i = 1; i <= n; i++) printf "%s%s", (i > 1 ? "," : ""), order[i] } + ' +} + +# Prints the standard WARNING block (diff --stat + first 200 chars of every +# changed line) to stderr. Takes no action beyond warning. +warn_dirty() { + git -C "$LANES_REPO" --no-pager diff --stat -- "${CP_PATHS[@]}" >&2 + git -C "$LANES_REPO" --no-pager diff -- "${CP_PATHS[@]}" 2>/dev/null | awk '/^[+-][^+-]/ {print substr($0,1,200)}' >&2 +} + +# Called by every mutating subcommand BEFORE it makes its own edit. If +# LANES.md is already dirty at that point, that content is someone else's — +# a peer's hand edit, or a helper run interrupted before it could push — +# never this invocation's. Always warns. In the default --no-sweep mode it +# commits that content now, as its own attributed commit, so it can never +# land combined with this invocation's edit (the 0d84d34 / a1f2438 +# incidents: another lane's row edit landed inside an unrelated commit with +# no trace of whose it was). In --sweep mode it leaves the content staged +# for this invocation's own commit and sets PRE_DIRTY_LANES so the caller +# can annotate its commit subject. +# +# Sets PRE_DIRTY_LANES to the affected lane list in --sweep mode; empty +# otherwise (nothing left to annotate — it was already committed separately). +handle_preexisting() { + PRE_DIRTY_LANES="" + if [ "$#" -gt 0 ]; then CP_PATHS=("$@"); else CP_PATHS=("$LANES_PATH"); fi + [ "$NO_GIT" = 1 ] && return 0 + git -C "$LANES_REPO" diff --quiet -- "${CP_PATHS[@]}" 2>/dev/null && return 0 + lanes="$(identify_changed_lanes)"; lanes="${lanes:-unknown}" + note "WARNING: LANES.md already has uncommitted changes before this edit (row: $lanes) — not this invocation's" + warn_dirty + if [ "$SWEEP_MODE" = "sweep" ]; then + PRE_DIRTY_LANES="$lanes" + note "SWEEP_MODE=sweep — leaving it staged; it will land inside this invocation's own commit, annotated" + else + git -C "$LANES_REPO" add -- "${CP_PATHS[@]}" + git -C "$LANES_REPO" commit -q -m "LANES(pre-existing@$WS): capture an uncommitted registry edit (row $lanes)" -- "${CP_PATHS[@]}" || : + note "captured pre-existing edit (row $lanes) as its own commit" + fi + return 0 +} + +# R11 (Addendum 3, 2026-09-11) — a peer's uncommitted REGISTER edit is +# CAPTURED, not refused. `lanes/LANES.md` is dirty in this shared checkout for +# much of the day — the register takes ~500 commits a day and a half-written +# row is what one of them looks like a second before it lands — so refusing +# every `claim`, `log` and `release` on it would push lanes to stop using the +# tool, and the pre-existing capture already exists precisely to make that +# state safe to rebase over. So: capture FIRST, exactly as every register +# write has done since --no-sweep (the warning included), and let the guard +# re-test the checkout afterwards. +# +# Only when the register is NOT one of this write's own pathspecs: a LANDING +# or a LANDED commits it itself, and the ordinary handle_preexisting call +# covers it there, --sweep included. There is nothing to sweep a register edit +# INTO when this commit does not touch the register, so this capture is always +# its own commit whatever --sweep says. +# +# It is reached only AFTER write_event's first guard, so it never commits on +# behalf of a write that is about to refuse: a checkout dirty in anything ELSE +# is refused before the lock and before this runs, and a refusal that had +# already committed a peer's register edit would be a refusal that wrote. +capture_register_edit() { + case " $* " in *" $LANES_PATH "*) return 0 ;; esac + cre_mode="$SWEEP_MODE" + SWEEP_MODE="no-sweep" + handle_preexisting "$LANES_PATH" + SWEEP_MODE="$cre_mode" + return 0 +} + +# ======================================================== Amendment 7 ====== +# +# THE PER-LANE OBJECT LOG. +# +# lanes/log/.md — one file per lane, append-only, line 1 a header, +# every other line an EVENT. This helper is the only writer, for the same +# reason it is the register's only writer. One file per lane is also what +# makes two workstations safe: two lanes writing at once touch two files. +# +# — lane , session @, , [ → ][ — ] +# +# The verb is ONE token. The first four fields are separated by `, `. The +# OBJECT token contains no space and no comma; everything after it up to +# ` — ` is payload, whose sub-fields are separated by `; ` and whose refs +# are space-separated. +# +# STATE IS PER LANE. A lane's state on an object is that lane's LAST line +# naming it — the last such line IN THE FILE, never the largest UTC (R14); +# the lane HOLDS the object when that verb is in the OPEN set; the object is +# HELD when any lane holds it. There is no index file: a read fetches and +# greps, because 45 lanes' logs together are smaller than one of the +# register's rows. +# +# LANES.md is unchanged. Its rows stay its rows and its Rule 6 LANDING / +# LANDED lines stay where every lane already reads them as the merge hold — +# which is why `who --landing` reads THOSE and not the logs. A LANDING or +# LANDED writes both files in one commit, with two pathspecs. + +LANES_PREFIX="${LANES_PREFIX:-$(git -C "${LANES_DIR:-.}" rev-parse --show-prefix 2>/dev/null || :)}" +LANES_LOG_DIR="${LANES_LOG_DIR:-$LANES_DIR/log}" +LANES_LOG_PREFIX="${LANES_LOG_PREFIX:-${LANES_PREFIX}log/}" + +# THE ALIAS TABLE IS TWO LAYERS, in this order (Amendment 9(b), ruling 3): the +# per-wip OVERRIDE in the person's own workspace repository, then the +# organisation's table shipped by openRepoTools and installed beside this +# command. An override row replaces the shipped row for the same alias and adds +# rows the shipped table does not carry; an alias in NEITHER layer is still a +# refusal naming the fix, spell it `owner/repo` (Amendment 7(a), unchanged). +# +# The shipped copy sits BESIDE this file because `--install` places from one +# list into one directory at one mode — the alternative was a second +# destination and a second mode in two repositories, which is why the table +# carries an executable bit it has no use for. +LANES_REPOS_TSV="${LANES_REPOS_TSV:-${LANES_DIR:+$LANES_DIR/repos.tsv}}" +if [ -z "${LANES_REPOS_TSV_SHIPPED:-}" ]; then + if [ -n "${OPENREPOTOOLS_BIN_DIR:-}" ] && [ -f "$OPENREPOTOOLS_BIN_DIR/repos.tsv" ]; then + LANES_REPOS_TSV_SHIPPED="$OPENREPOTOOLS_BIN_DIR/repos.tsv" + else + LANES_REPOS_TSV_SHIPPED="$SCRIPT_DIR/repos.tsv" + fi +fi + +# AMENDMENT 16(e) — THE LANE ALIAS TABLE, `lanes/aliases.tsv`, one layer and +# not two. `repos.tsv` above has a shipped layer because a repository alias is +# an ORGANISATION's fact; a lane rename is one person's register moving, so the +# table lives beside the register it describes and openRepoTools ships none. +# ` `, one line per rename, appended by `rename-lane` and by +# nothing else — and read case-insensitively by `canon_lane`, which is the one +# seat every `` argument in this file already passes through. +LANES_ALIASES_TSV="${LANES_ALIASES_TSV:-${LANES_DIR:+$LANES_DIR/aliases.tsv}}" +LANES_ALIASES_PATH="${LANES_ALIASES_PATH:-${LANES_PREFIX}aliases.tsv}" +PROJECTS_ROOT="${PROJECTS_ROOT:-$HOME/projects}" +NO_GITHUB="${LANES_NO_GITHUB:-0}" +STALE_HOURS="${LANES_STALE_HOURS:-4}" # Rule 1's threshold, reused + +# The field separator for every machine-read line below. NOT a tab: a tab is +# IFS WHITESPACE, so bash's `read` collapses runs of them and one empty field +# (an event with no payload) shifts every field after it one to the left. +# \037 — US, "unit separator" — is not whitespace, so empty fields survive it. +US="$(printf '\037')" +# THE ROW SEPARATOR FOR THE IN-SHELL LOOKUP TABLES (A11 Addendum 4 ruling 12). +# GS, one below US, and for the same reason US was chosen over a tab: it is not +# IFS whitespace, so an empty field does not shift every field after it. +GS="$(printf '\036')" + +# ONE LINE OUT OF A TABLE THIS SHELL IS ALREADY HOLDING, WITHOUT A PROCESS. +# The listing's three tables — the published register's index, this checkout's, +# and one line of facts per lane — are a few dozen lines each and were read with +# `printf | awk` PER LANE, which is six processes a lane to look up strings that +# are already in memory. Fenced with `$GS` and keyed on the lane name +# lower-cased, the whole lookup is one parameter expansion. +# +# IT ASSIGNS A GLOBAL AND RETURNS, rather than printing: a function whose answer +# is taken with `$( … )` forks, which is the cost this exists to avoid. +# +# AND THE EXPANSION IS `%%key*`, NEVER `#*key` — THE SAME FIRST MATCH, IN +# LINEAR TIME (opensoft/openRepoTools#107). Bash removes a shortest prefix by +# trying the whole pattern against EVERY prefix of the string in turn, and a +# pattern that opens with `*` costs a scan of that prefix each time: `#*key` is +# QUADRATIC in the table. A longest suffix is found by trying the pattern only +# where its FIRST character matches, and here that is `$GS`, which occurs once +# per line — so `%%key*` touches each byte about once. Both name the FIRST +# occurrence of `$GS$US`: `#*key` is everything up to and including it, +# `%%key*` everything before it. Measured on the suite's own fixture register +# (194 rows, 162 object logs): the per-lane loop of one `lanes --prefix` read +# was 56.6 s of its 58.1 s, about 75 ms per lookup, three or more lookups per +# lane — which is what put `lane`'s pick past the pty driver's 60-second bound. +# The offset is in CHARACTERS on both sides of the `+` (`${#…}` and `${1:…}` +# count the same way in any one locale), so a multibyte table cuts where the +# old expansion cut. +LOOKUP_OUT="" +table_lookup() { # + local tl_key tl_head tl_rest + LOOKUP_OUT="" + tl_key="$GS$2$US" + tl_head="${1%%"$tl_key"*}" + [ "$tl_head" = "$1" ] && return 1 + tl_rest="${1:$(( ${#tl_head} + ${#tl_key} ))}" + LOOKUP_OUT="${tl_rest%%"$GS"*}" + return 0 +} + +utc_now() { date -u +%Y-%m-%dT%H:%M:%SZ; } + +# ---------------------------------------------------------------- the verbs +# +# A lane HOLDS an object while its own last line on it is OPEN. WITHDRAWN is +# open on purpose: withdrawing a landing leaves the PR held by the lane that +# withdrew it. The CLOSED set closes only the WRITING lane's hold — another +# lane's claim on the same object is untouched by it. +is_open_verb() { case "$1" in CLAIMED|TAKEOVER|OPENED|LANDING|WITHDRAWN) return 0 ;; esac; return 1; } +is_closed_verb() { case "$1" in RELEASED|CLAIM-LOST|CLOSED|LANDED) return 0 ;; esac; return 1; } +# AND `HANDOFF-REQUESTED` IS A LANE-KIND VERB THAT CHANGES NO STATE (Amendment +# 18(g)): *"this adds one lane-kind verb, `HANDOFF-REQUESTED`, which changes no +# object's state and which every last-line reader skips."* It is lane-kind +# because its object is `lane:` — which is what `is_lane_verb` is asked +# here, and the only thing it is asked (its one caller is the `log` arm's +# object check) — and it is in NEITHER state set, so it opens nothing and closes +# nothing. Every reader that decides a lane's STATE enumerates the five state +# verbs by name (`lane_row_facts`, `lane_payload_field`, `lane_binding_utc`, +# `lane-last`, `swapped_candidates`), so none of them sees it, and +# `lane_binding_scan` is the one read that does: to it a request is a fact ABOUT +# a binding and never a release of one. +is_lane_verb() { case "$1" in STARTED|PAUSED|RESUMED|ENDED|RETIRED|HANDOFF-REQUESTED) return 0 ;; esac; return 1; } +# AMENDMENT 13(b) — THE TWO NARRATIVE VERBS, AND THEY ARE OUTSIDE EVERY STATE +# THERE IS. `NOTED` is a status note and `RULED` a ruling recorded verbatim; +# both are lane-kind lines whose object is the lane itself, and NEITHER IS A +# TRANSITION OF ANYTHING. So they are their own set rather than members of +# `is_lane_verb`: every reader that computes a lane's state by the per-lane +# last-line rule takes the five lane verbs by name, and a sixth and seventh +# inside that predicate would have made the narrative move the lane — a `NOTED` +# after a swap's `PAUSED` would have made a paused lane read as neither paused +# nor running, which is the one thing `swapped` and `restart` are built on. +# The one reader that took the LAST lane-kind line whatever it was is +# `swapped_candidates`, and it skips these by name for exactly that reason. +# +# AMENDMENT 16 PUTS `RENAMED` HERE, AND THE SET IS WHAT IT WAS RATHER THAN WHAT +# IT IS CALLED: a LANE-KIND LINE THAT IS NOT A TRANSITION. Clause (c) says the +# rename's line "changes no object's state, every last-line reader skips it", +# which is Amendment 13(b)'s sentence about its own two in different words — and +# `swapped_candidates` is the proof that `is_lane_verb` is the wrong home: it +# takes a lane's last lane-kind line WHATEVER its verb is, so a `RENAMED` there +# would make a swapped lane read as neither paused nor running and `restart` +# would not find it. One predicate, three verbs, one property. +# +# `HANDOFF-REQUESTED` IS INSIDE `is_lane_verb` AND THESE THREE ARE NOT, and the +# difference is the object rather than the state: that predicate's ONE caller is +# the `log` arm's check that a lane verb's object is `lane:`, which the +# request needs and which Amendment 13 gives its two by their own arm, as +# Amendment 16 gives `RENAMED` by its. None of the four moves a lane, and none +# of the four is seen by a state reader. +is_note_verb() { case "$1" in NOTED|RULED|RENAMED) return 0 ;; esac; return 1; } +valid_verb() { + is_open_verb "$1" || is_closed_verb "$1" || is_lane_verb "$1" || is_note_verb "$1" +} +VERB_LIST="CLAIMED RELEASED TAKEOVER CLOSED | OPENED LANDING LANDED WITHDRAWN | STARTED PAUSED RESUMED ENDED RETIRED HANDOFF-REQUESTED | CLAIM-LOST | NOTED RULED RENAMED" + +check_lane_name() { + case "${1-}" in + "" | *[!A-Za-z0-9._-]* | .* | -*) + die "'${1-}' is not a lane name (letters, digits, . _ -, not opening with . or -)" 2 ;; + esac +} + +log_file_for() { printf '%s/%s.md\n' "$LANES_LOG_DIR" "$1"; } +log_path_for() { printf '%s%s.md\n' "$LANES_LOG_PREFIX" "$1"; } + +# AMENDMENT 15 — THE LOG FILE IS `lanes/log/.md`, AND A FILE OF +# ANOTHER CASE IS STILL THIS LANE'S LOG. +# +# The log's file name was lowercased from the start, which is exactly why the +# 2026-09-13 incident produced TWO ROWS AND ONE LOG: `openXfactory-2` and +# `openxfactory-2` had always shared `lanes/log/openxfactory-2.md`. The real +# register still carries `lanes/log/openxfactory-4.md` beside the row +# `openxfactory-4` — the same spelling, nothing to do — and the historical +# mismatch is the shape these two functions exist for. READERS find the file +# whatever its case; the first WRITE renames it to the canonical spelling, once, +# inside its own commit (`ensure_log` below). +# +# `ls` and one `awk`, not a `$(lc …)` per file: `lanes/log/` carries a file per +# lane of the estate and this is asked on the path a person is waiting on. +# +# AND THE `--` STAYS (Copilot round 3 on openRepoTools#41, DECLINED with a +# measurement). It was read as a macOS defect — *"BSD `ls` rejects `--`, and the +# suppressed error makes every case-insensitive log scan empty"* — which would +# mean no first write ever renames anything on the one platform this amendment's +# rename exists for. BSD `ls` ends its options at `--` through `getopt(3)`, as +# every POSIX utility does, and `tests-macos` has been GREEN on the two +# assertions that can only pass if this scan finds a file of another case there: +# the rename recorded inside the write's own commit, and `lane-start`'s own +# `repo repocase → repoCase` out of the twin scan at `lane-start:677`. The suite +# asserts the parse itself as well, on every platform. Dropping `--` would hand +# a directory whose name begins with `-` back to `ls` as flags and change +# nothing else. +# +# AND IT RETURNS 1 WHERE THE DIRECTORY IS THERE AND COULD NOT BE LISTED (#138 +# item 9). It was `ls … 2>/dev/null | awk`, whose status is the awk's, so an +# unreadable directory answered "no log of any case" — which `retire_rows`' scan +# took as a lane with no log, and its write loop then failed on that directory +# after the scan had passed. A missing directory is still no log, and 0. +log_files_named_ci() { # — every existing log file for it, whatever its case + lfn_ls="" + if [ -e "$LANES_LOG_DIR" ]; then + lfn_ls="$(ls -- "$LANES_LOG_DIR" 2>/dev/null)" || return 1 + fi + printf '%s\n' "$lfn_ls" | awk -v want="$1" -v d="$LANES_LOG_DIR" ' + BEGIN { w = tolower(want) ".md" } + tolower($0) == w { print d "/" $0 }' +} + +# The PUBLISHED path of a lane's log, found the same way — the canonical path +# where `origin/` has no file of another case, so a lane with no log at +# all still reads as the pre-cutover 8 rather than as a failure. +# +# TWO PATHS DIFFERING ONLY BY CASE ARE A REFUSAL AND NOT A CHOICE (Copilot round +# 4 on openRepoTools#41). The `exit` after the first match read a tree holding +# BOTH `lanes/log/repocase-1.md` and `lanes/log/repoCase-1.md` as though it held +# one, and every reader behind it — `lane_log_events`, `lane_log_exists`, +# `last-session`, the listing's per-lane facts — then consumed whichever `ls-tree` +# happened to name first and DROPPED the other file's lines without saying so. +# That is two logs for one lane, the state 15(d)'s hand merge exists for, and an +# append-only history half of which is invisible is worse than a refusal. Counted +# and REFUSED (2) naming both, in `canon_lane`'s own shape — it RETURNS rather +# than exits, because every caller takes it with `$( )`. +# +# AND THE WORKING TREE ANSWERS WHERE `origin` HAS NOTHING. The fallback was the +# canonical path outright, which is a path that need not exist: a lane whose log +# is still spelled the old way and has never been pushed has ONE file on disk and +# this named another. `claim`'s dirty-checkout exemption is computed from it, so +# the lane's own uncommitted log read as an unrelated dirty file and the claim was +# refused for it. The same case-insensitive scan every other reader uses answers +# that half (Copilot round 4). +log_path_ci() { # — 0 with the ONE path, 2 where two differ only by case + lpc_exact="$(log_path_for "$1")" + # AMENDMENT 14 — UNDER `--index` THE INDEX'S LOG LIST STANDS IN FOR + # `origin`'s tree, and nothing else in this function changes. + if [ -n "$LANES_IDX_DIR" ] || have_remote_ref; then + if [ -n "$LANES_IDX_DIR" ]; then + lpc_hits="$(awk -v want="$lpc_exact" 'BEGIN { w = tolower(want) } tolower($0) == w' "$LANES_IDX_DIR/logs" 2>/dev/null)" + else + lpc_hits="$(git -C "$LANES_REPO" ls-tree --name-only "origin/$LANES_BRANCH" -- "$LANES_LOG_PREFIX" 2>/dev/null \ + | awk -v want="$lpc_exact" 'BEGIN { w = tolower(want) } tolower($0) == w')" + fi + lpc_n="$(printf '%s' "$lpc_hits" | grep -c . || :)" + if [ "$lpc_n" -gt 1 ]; then + note "lane $1 has $lpc_n object logs on origin/$LANES_BRANCH whose names differ only by case: $(printf '%s\n' "$lpc_hits" | tr '\n' ' ')" + note "one lane is ONE lane under any case and its log is ONE file (Amendment 15), so no read of it is unambiguous and nothing here picks one of them. Merge them by hand into $lpc_exact, oldest lines first, remove the others in the same commit (Amendment 15(d)), and re-run." + return 2 + fi + [ "$lpc_n" = 1 ] && { printf '%s\n' "$lpc_hits"; return 0; } + fi + lpc_loc="$(log_files_named_ci "$1")" + lpc_ln="$(printf '%s' "$lpc_loc" | grep -c . || :)" + if [ "$lpc_ln" -gt 1 ]; then + note "lane $1 has $lpc_ln object logs in this checkout whose names differ only by case: $(printf '%s\n' "$lpc_loc" | tr '\n' ' ')" + note "one lane is ONE lane under any case and its log is ONE file (Amendment 15), so no read of it is unambiguous and nothing here picks one of them. Merge them by hand into $(log_file_for "$1"), oldest lines first, remove the others in the same commit (Amendment 15(d)), and re-run." + return 2 + fi + [ "$lpc_ln" = 1 ] && { printf '%s\n' "${LANES_LOG_PREFIX}${lpc_loc##*/}"; return 0; } + printf '%s\n' "$lpc_exact" +} + +# The repo-relative path `ensure_log` renamed a log AWAY from, for the ONE +# caller that has to put it in the same commit as the write. Empty on every +# other run, and reset by every `ensure_log`, so "renamed" is never sticky. +LOG_RENAMED_FROM="" + +ensure_log() { + lane="$1"; lf="$(log_file_for "$lane")" + LOG_RENAMED_FROM="" + [ -d "$LANES_LOG_DIR" ] || mkdir -p -- "$LANES_LOG_DIR" + el_hits="$(log_files_named_ci "$lane")" + el_n="$(printf '%s' "$el_hits" | grep -c . || :)" + if [ "$el_n" -gt 1 ]; then + die "lane $lane has $el_n object logs whose names differ only by case: $(printf '%s\n' "$el_hits" | tr '\n' ' ')— one lane is ONE lane under any case and its log is ONE file (Amendment 15). Merge them by hand into $lf, oldest lines first, remove the others in the same commit, and re-run. Nothing was written." 2 + fi + # A LOG THIS CHECKOUT HAS NOT PULLED IS STILL THIS LANE-S LOG, AND CREATING + # THE CANONICAL FILE BESIDE IT IS THE SPLIT THIS FUNCTION EXISTS TO PREVENT. + # `log_files_named_ci` reads the WORKING TREE, while every state reader here + # deliberately answers out of `origin/` (R19): on a checkout that is + # behind, a published `lanes/log/repocase-1.md` is invisible to the scan + # above, this write would create `repoCase-1.md`, and `commit_push`-s own + # rebase would then land BOTH. The refusal below is fail-closed and its cure + # is one command, where the cure for two published files is 15(d)-s hand + # merge (Copilot round 1 on openRepoTools#41). + # + # AND THE GUARD IS NOT ONLY FOR A CHECKOUT WITH NO FILE AT ALL (Copilot round 4 + # on openRepoTools#41). It ran under `el_n = 0`, so the state a rename leaves + # when its COMMIT does not land — the canonical file here, the old-cased path + # still in the remote tree — walked straight past it, and the next write staged + # the canonical path alone and left the published one where it was: two files + # for one lane again, by the path this function exists to close. The test is + # therefore on the PATHS and not on the count: a published path that is neither + # the canonical one NOR the one this checkout is about to rename FROM is a + # refusal, which leaves the ordinary rename (local and published agree on the + # old spelling) exactly as it was. + el_from="" + [ "$el_n" = 1 ] && el_from="$el_hits" + if have_remote_ref; then + el_pub="$(log_path_ci "$lane")" || die "lane $lane's object log is published twice (above) and nothing is written under a name that means two files. Merge them by hand (Amendment 15(d)) and re-run. Nothing was written." 2 + if [ "$el_pub" != "$(log_path_for "$lane")" ] && [ "${el_from##*/}" != "${el_pub##*/}" ]; then + el_here="and this checkout does not have it" + [ -n "$el_from" ] && el_here="while this checkout has ${LANES_LOG_PREFIX}${el_from##*/} instead — a case-only rename whose commit never landed" + die "lane ${lane}'s object log is published as $el_pub $el_here: the row spells the lane $lane, so the log is $(log_path_for "$lane") (Amendment 15), and writing one here now would leave TWO files for one lane. Pull first — \`git -C $LANES_REPO pull --rebase\` — and re-run; the rename then happens once, inside this write's own commit. Nothing was written." 2 + fi + fi + if [ -n "$el_from" ] && [ "$el_from" != "$lf" ]; then + # THE RENAME IS ONE ACT AND IT HAPPENS ONCE: after it the canonical name is + # the only one `log_files_named_ci` can find, so the next write takes the + # branch above and does nothing. THROUGH A TEMPORARY NAME, because on a + # case-INSENSITIVE filesystem — macOS, which this repository's CI runs — the + # two names are one file and `mv a A` answers "identical" rather than + # renaming; two `mv`s do the same job on both kinds of filesystem, and + # neither is `git mv`, whose own case-only rename is the thing that differs + # between platforms. The caller puts the old path in this write's pathspecs + # and `commit_push` drops its INDEX entry by that exact path before staging + # the new one, then commits the index rather than the pathspecs — the one + # sequence that records the rename on a case-insensitive filesystem as well + # as on this one, argued in full above `CP_EXACT`. + el_tmp="$lf.amendment15.$$" + # THE REFUSAL SAYS WHERE THE FILE IS, and the two halves fail differently: + # the first `mv` failing leaves the log exactly where it was, while the + # SECOND failing leaves it at `$el_tmp` — a name no reader of this + # directory looks for. A refusal that told a person to "move it by hand" + # without saying which path to move is a refusal they cannot act on, and + # this one costs a lane its whole history if it is acted on wrongly. + if ! mv -- "$el_from" "$el_tmp" 2>/dev/null; then + die "could not rename $el_from to $lf (Amendment 15: the register row's spelling names the lane's log). Nothing was written and the log is untouched at $el_from; rename it by hand and re-run." 5 + fi + if ! mv -- "$el_tmp" "$lf" 2>/dev/null; then + die "could not rename $el_tmp to $lf (Amendment 15: the register row's spelling names the lane's log). Nothing was written, and THIS LANE'S LOG IS NOW AT $el_tmp — rename it to $lf by hand, or back to $el_from, and re-run. It is not lost and no reader looks for it under that name." 5 + fi + LOG_RENAMED_FROM="${LANES_LOG_PREFIX}${el_from##*/}" + note "$el_from → $lf: the register row spells this lane $lane, and the row's spelling names its log (Amendment 15)" + fi + if [ ! -f "$lf" ]; then + printf '# lane %s — object log (lane-collision-protocol Amendment 7)\n' "$lane" > "$lf" + note "created $lf" + fi +} + +# ------------------------------------------------------- the alias table +# +# `lanes/repos.tsv`, `aliasowner/repo`. Consulted when the owner is +# omitted, and when a spelling the register really uses is not the canonical +# nameWithOwner (all four spellings of codexFactory resolve to +# `codeXfactory/codexFactory`, which is the redirect GitHub answers with). +# Matching is case-insensitive: the register spells one repo `OpsxFactory`, +# `opsXfactory` and `opsxfactory` in the same week. +alias_lookup() { + al_k="$1" + for al_tsv in "${LANES_REPOS_TSV:-}" "${LANES_REPOS_TSV_SHIPPED:-}"; do + [ -n "$al_tsv" ] && [ -f "$al_tsv" ] || continue + awk -F'\t' -v k="$al_k" ' + BEGIN { kl = tolower(k) } + /^[ \t]*#/ { next } + NF >= 2 { if (tolower($1) == kl) { print $2; found = 1; exit } } + END { exit(found ? 0 : 1) }' "$al_tsv" && return 0 + done + return 1 +} + +# canon_object [] — prints the canonical object key. +# THE KINDS IN SCOPE, and no others (a later amendment may add keys): +# owner/repo#n an issue or a PR +# owner/repo:openspec/changes/ an OpenSpec change directory +# #n the lane's OWN home repo +# lane: a lane, for the lane-kind lines only +# Human acts, realization groups, contract cuts, file surfaces and Amendment +# 1's substrates stay where they are today — comments on their governing +# records — and are an explicit non-goal here. +canon_object() { + co_raw="$1"; co_home="${2-}"; co_repo=""; co_rest=""; co_owner=""; co_hc="" + case "$co_raw" in + lane:*) + case "${co_raw#lane:}" in + "" | *[!A-Za-z0-9._-]*) note "'$co_raw' is not a lane object: lane:"; return 2 ;; + esac + # AMENDMENT 15 — A LANE OBJECT CARRIES THE ROW'S SPELLING TOO. `lane:` + # is the object of every lane-kind line (7(b)), so a `log PAUSED + # lane:openxfactory-2` on the lane `openXfactory-2` would write a key that + # does not match the lane's own earlier lines — in a file nothing rewrites, + # and against which `who lane:` is then asked. Canonicalised here, so + # the writers and the reader ask the same question of it. + co_cl="$(canon_lane "${co_raw#lane:}")" || return 2 + printf 'lane:%s\n' "$co_cl"; return 0 ;; + '#'*) + case "${co_raw#\#}" in + "" | *[!0-9]*) note "'$co_raw' is not an object key: after '#' comes the issue or PR number"; return 2 ;; + esac + if [ -z "$co_home" ]; then + note "'$co_raw' is shorthand for this lane's home repo, and no home is on record for it." + note " Spell it owner/repo$co_raw, or pass --home owner/repo (a pre-cutover lane has no STARTED line)." + return 2 + fi + if ! valid_nwo "$co_home"; then + note "'$co_home' is not a repository, so '$co_raw' cannot be expanded against it." + note " A home is owner/repo. This one came from the lane's STARTED line or from --home." + return 2 + fi + # R20 — THE HOME GOES THROUGH THE ALIAS TABLE TOO, on the way into a key. + # `home_of_lane` and `resolve_home` both resolve already; this is the last + # gate, so no caller can reach a key by a path that skipped it. A checkout + # whose origin still spells `opensoft/codexFactory` wrote `#5` as a key + # nothing could reconcile with `codeXfactory/codexFactory#5`, and two lanes + # held one issue with no collision detected. + co_hc="$(alias_lookup "$co_home" 2>/dev/null || :)" + [ -n "$co_hc" ] && co_home="$co_hc" + printf '%s%s\n' "$co_home" "$co_raw"; return 0 ;; + *:openspec/changes/*) + co_repo="${co_raw%%:openspec/changes/*}" + co_rest=":openspec/changes/${co_raw#*:openspec/changes/}" + case "${co_rest#:openspec/changes/}" in + "" | *[!A-Za-z0-9._-]*) note "'$co_raw' is not an object key: an OpenSpec change is owner/repo:openspec/changes/"; return 2 ;; + esac ;; + *'#'*) + co_repo="${co_raw%%#*}" + co_rest="#${co_raw#*#}" + case "${co_rest#\#}" in + "" | *[!0-9]*) note "'$co_raw' is not an object key: after '#' comes the issue or PR number"; return 2 ;; + esac ;; + *) + note "'$co_raw' is not an object key. In scope: owner/repo#, owner/repo:openspec/changes/, # for this lane's home repo, lane:." + return 2 ;; + esac + [ -n "$co_repo" ] || { note "'$co_raw' names no repository"; return 2; } + co_owner="$(alias_lookup "$co_repo" 2>/dev/null || :)" + if [ -z "$co_owner" ]; then + case "$co_repo" in + */*) co_owner="$co_repo" ;; # a spelled owner/repo is always accepted + *) + note "unknown repo alias '$co_repo' — spell it owner/repo (the canonical GitHub nameWithOwner), or add it to ${LANES_LOG_PREFIX%log/}repos.tsv" + return 2 ;; + esac + fi + case "$co_owner" in + */*/*|*/) note "the alias table maps '$co_repo' to '$co_owner', which is not owner/repo"; return 2 ;; + */*) : ;; + *) note "the alias table maps '$co_repo' to '$co_owner', which is not owner/repo"; return 2 ;; + esac + case "$co_owner" in *[!A-Za-z0-9./_-]*) note "'$co_owner' is not a usable owner/repo"; return 2 ;; esac + printf '%s%s\n' "$co_owner" "$co_rest" +} + +# owner/repo, and nothing else: exactly one slash, and only the characters +# GitHub allows in either half. `--home 'not a repo'` used to go straight into +# an object key, and the helper wrote `not a repo#42` — a line its OWN parser +# cannot read back, in a log nothing ever rewrites. +valid_nwo() { [[ "${1-}" =~ ^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$ ]]; } + +# A TRANSCRIPT UUID, and nothing else — the shape `claude --resume` takes +# exactly and the one every event line's `session` field carries (Amendment +# 7(b), Definitions sense 1). Not a PR-footer `session_01…`, not a session +# NAME, and not the literal `unknown`: `write_event` refuses all three. +valid_uuid() { [[ "${1-}" =~ ^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$ ]]; } + +# The home repo for this invocation. `--home` is for a PRE-CUTOVER lane — one +# whose log has no STARTED line — and is REFUSED where the log already answers +# the question, so the flag and the log can never disagree. It is resolved +# through the alias table and then validated, like any other spelling. +# +# R30 (Addendum 7) — AND EVERY CALLER ASKS AFTER THE FETCH. The STARTED line it +# reads is `origin/`'s, like every other state read, so a home a peer +# recorded is invisible here until `log_sync` has run: asked before it, `--home` +# was ACCEPTED on a lane whose own log already answers the question — the one +# refusal this flag has — and the object key it then built was the second +# spelling of an issue another lane was already holding. `who` and `lane-end`'s +# `resolve-home` preflight fetched first already; `log`, `claim` and `release` +# now do too, so the preflight and the write can still never disagree. +# +# Called as `home="$(resolve_home "$lane" "$override")" || exit $?` — a `die` +# in here runs inside the command substitution, so the caller must pass the +# code on rather than carry on with an empty home. +resolve_home() { + rh_lane="${1-}"; rh_over="${2-}"; rh_log="" + [ -n "$rh_lane" ] && rh_log="$(home_of_lane "$rh_lane" 2>/dev/null || :)" + if [ -n "$rh_over" ]; then + if [ -n "$rh_log" ]; then + note "lane $rh_lane's own log already records its home: $rh_log (from its STARTED line)." + die "--home is for a pre-cutover lane, one whose log has no STARTED line. Drop it, or correct the lane's home by appending a new STARTED line through lane-start." 2 + fi + rh_res="$(alias_lookup "$rh_over" 2>/dev/null || :)"; rh_over="${rh_res:-$rh_over}" + valid_nwo "$rh_over" || die "--home takes owner/repo (the canonical GitHub nameWithOwner), or an alias in ${LANES_LOG_PREFIX%log/}repos.tsv: '${2-}' is neither" 2 + printf '%s\n' "$rh_over" + return 0 + fi + printf '%s\n' "$rh_log" +} + +is_lane_object() { case "$1" in lane:*) return 0 ;; esac; return 1; } +object_repo() { case "$1" in lane:*) printf '\n' ;; *:openspec/changes/*) printf '%s\n' "${1%%:openspec/changes/*}" ;; *) printf '%s\n' "${1%%#*}" ;; esac; } +object_number() { case "$1" in lane:*|*:openspec/changes/*) printf '\n' ;; *'#'*) printf '%s\n' "${1##*#}" ;; *) printf '\n' ;; esac; } +object_slug() { case "$1" in *:openspec/changes/*) printf '%s\n' "${1##*/}" ;; *'#'*) printf '%s\n' "${1##*#}" ;; *) printf '%s\n' "$1" ;; esac; } + +# ------------------------------------------------------- reading the logs +# +# One parser, used by everything. It prints US-separated fields, UTC first: +# utc lane verb uuid ws object ref payload text file line +# +# The last two are the line's ADDRESS — the file it was read from and its +# number IN THAT FILE (FNR, so it is the number the reader sees in the log and +# the number an `unreadable:` report names). That address is what every state +# read orders by (R14): the log is append-only, so a line further down the file +# is a line written later, whatever the two lines' UTC fields say. +# `match()` is used for every multi-byte separator: RSTART and RLENGTH are in +# the same units as each other whatever the locale, and a hard-coded byte +# offset for " — " is not. +# AMENDMENT 16(e) — A LINE'S LANE IS THE LANE OF THE FILE IT IS IN, and that is +# the whole of the rule. +# +# Clause (c) is explicit that a rename rewrites none of the lines above it: +# *"the lines above it — which still say `lane ` — are never rewritten"*. +# So after a rename a lane's log holds its whole history under two names, in one +# file, about one lane — the exact shape Amendment 15 met when one lane's log +# spelled it two ways, and the exact failure: `lane_objects`, `superseded_by`, +# `holders_of`, `lane_row_facts` and `first_landed_of` all key on this field, so +# read byte for byte HALF A RENAMED LANE'S HOLDS BECOME INVISIBLE — `who --lane` +# calls a held object free and `lane-end` ends a lane that holds one. +# +# THE FIRST ANSWER WAS AN ALIAS LOOKUP IN THIS PARSE, AND IT WAS THE WRONG ONE +# (Copilot round 1 on openRepoTools#81). A rename FREES the old name — no row +# carries it, so `lane_next_free` hands the position out and a NEW lane can be +# called it — and from that moment the field `lane ` is ambiguous: it is +# the renamed lane's history in one file and the new lane's present in another. +# No amount of resolving a NAME tells those apart, because the name is the same. +# +# THE FILE DOES. Amendment 7's first sentence is one file per lane, single +# writer, and Amendment 15 makes its name the row's own spelling — so +# `lanes/log/.md` IS the statement of which lane every line in it belongs +# to, it MOVES with the rename (clause (c)), and it needs no table to read. The +# field stays on the line as the spelling somebody typed; the FILE is what the +# readers are keyed on. That also settles, with nothing added, the two spellings +# of one lane Amendment 15 had to reason about line by line. +LOG_AWK=' +function trim(s) { sub(/^[ \t]+/, "", s); sub(/[ \t]+$/, "", s); return s } +# The lane a FILE belongs to: its base name without `.md`. `FN` is the +# repo-relative path `remote_log_events` hands in; `FILENAME` is awk-s own for a +# file read from disk. Computed once per file rather than per line. +function filelane( f, n, parts) { + f = (FN != "" ? FN : FILENAME) + if (f == "") return "" + n = split(f, parts, "/") + f = parts[n] + sub(/\.[Mm][Dd]$/, "", f) + return f +} +# A LINE IS NEVER DROPPED SILENTLY. This log is append-only and nothing in it +# is ever rewritten, so a line no parser can read is a hold no tool will +# mention again — `who` would call the object free, and it is not. +function bad(why, f) { + f = (FN != "" ? FN : FILENAME) + printf "unreadable: %s:%d (%s)\n", f, FNR, why > "/dev/stderr" + nbad++ +} +FNR == 1 { FL = "" } +{ + line = $0 + if (line ~ /^[ \t]*#/ || line ~ /^[ \t]*$/) next + if (match(line, / — /) == 0) { bad("no \" — \" after the verb"); next } + verb = trim(substr(line, 1, RSTART - 1)) + rest = substr(line, RSTART + RLENGTH) + if (index(verb, " ") > 0) { bad("the verb is one token: \"" verb "\""); next } + if (substr(rest, 1, 5) != "lane ") { bad("no \"lane \" field"); next } + rest = substr(rest, 6) + q = index(rest, ","); if (q == 0) { bad("no \",\" after the lane"); next } + lane = trim(substr(rest, 1, q - 1)); rest = trim(substr(rest, q + 1)) + if (substr(rest, 1, 8) != "session ") { bad("no \"session @\" field"); next } + rest = substr(rest, 9) + q = index(rest, ","); if (q == 0) { bad("no \",\" after the session"); next } + sess = trim(substr(rest, 1, q - 1)); rest = trim(substr(rest, q + 1)) + a = index(sess, "@") + uuid = (a ? substr(sess, 1, a - 1) : sess) + ws = (a ? substr(sess, a + 1) : "") + # The UTC is matched by SHAPE. Taking it up to the next comma would be + # wrong for any line whose object is followed by nothing at all. The + # seconds are optional: the register carries `…T20:31Z` lines from before + # this helper existed, and refusing to read one loses a hold. + if (match(rest, /^[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9](:[0-9][0-9])?Z/) == 0) { bad("no YYYY-MM-DDTHH:MM[:SS]Z"); next } + utc = substr(rest, RSTART, RLENGTH) + rest = substr(rest, RSTART + RLENGTH) + if (substr(rest, 1, 1) != ",") { bad("no \",\" and object after the UTC"); next } + rest = trim(substr(rest, 2)) + # The object token contains no space and no comma, so it ends at the first + # space — which is what makes the payload unambiguous however it is spelled. + sp = index(rest, " ") + if (sp == 0) { obj = rest; rest = "" } + else { obj = substr(rest, 1, sp - 1); rest = substr(rest, sp + 1) } + ref = ""; payload = ""; txt = "" + # Every test below is a REGEX, never a substr() width: RSTART and RLENGTH + # are in whatever unit the locale counts in, and they agree with each other. + # A hard-coded 4 for "— " does not, and gawk counts characters. + if (rest != "") { + if (match(rest, /^— /)) { txt = trim(substr(rest, RSTART + RLENGTH)) } + else { + if (match(rest, / — /)) { txt = trim(substr(rest, RSTART + RLENGTH)); rest = trim(substr(rest, 1, RSTART - 1)) } + if (match(rest, /^→ /)) { ref = "→"; payload = trim(substr(rest, RSTART + RLENGTH)) } + else if (match(rest, /^← /)) { ref = "←"; payload = trim(substr(rest, RSTART + RLENGTH)) } + else { payload = trim(rest) } + } + } + if (FL == "") FL = filelane() + if (FL != "") { + # THE LANE-KIND OBJECT IS THE WRITING LANE AND NOTHING ELSE (Amendment + # 7(b)), so it follows the same rule: `lane:` in a renamed lane-s own + # log is that lane under the name it had, and `who lane:` asks + # `canon_object` -> `canon_lane` of the name it was given, which lands on + # the same answer from the other side. + lane = FL + if (substr(obj, 1, 5) == "lane:") obj = "lane:" FL + } + printf "%s%c%s%c%s%c%s%c%s%c%s%c%s%c%s%c%s%c%s%c%d\n", utc, 31, lane, 31, verb, 31, uuid, 31, ws, 31, obj, 31, ref, 31, payload, 31, txt, 31, (FN != "" ? FN : FILENAME), 31, FNR +} +END { if (nbad > 0) printf "%d unreadable line(s) above — an append-only log is never rewritten, so a line no parser reads is a hold no tool will mention again\n", nbad > "/dev/stderr" }' + +parse_log_stream() { awk -v FN="${1:-}" "$LOG_AWK"; } + +log_files() { + for le_f in "$LANES_LOG_DIR"/*.md; do + [ -e "$le_f" ] || continue + case "${le_f##*/}" in README.md) continue ;; esac + printf '%s\n' "$le_f" + done +} + +log_events() { + le_files=() + if [ "$#" -gt 0 ]; then + le_files=("$@") + else + while IFS= read -r le_f; do [ -n "$le_f" ] && le_files+=("$le_f"); done <` to read from at all? Outside a repository, and +# under the LANES_NO_GIT=1 harness, there is not, and the working tree is all +# there is. +have_remote_ref() { + [ "$NO_GIT" = 1 ] && return 1 + git -C "$LANES_REPO" rev-parse --verify -q "origin/$LANES_BRANCH" >/dev/null 2>&1 +} + +# The same events, read from `origin/` instead of the working tree. +# EVERY state read goes through state_events() below, which reads THIS: what +# has LANDED is what other lanes can see, and a working tree can be anything — +# behind by a peer's whole day, or carrying a line that never lands. +remote_log_events() { + # AMENDMENT 14 — under `--index`, the index's events of every log, in the + # order and the grammar this function prints them in, and the warnings + # `LOG_AWK` would have printed for the lines it could not read. + if [ -n "$LANES_IDX_DIR" ]; then + cat -- "$LANES_IDX_DIR/warn" >&2 2>/dev/null || : + cat -- "$LANES_IDX_DIR/events" + return 0 + fi + [ "$NO_GIT" = 1 ] && { log_events; return 0; } + git -C "$LANES_REPO" rev-parse --verify -q "origin/$LANES_BRANCH" >/dev/null 2>&1 || { log_events; return 0; } + # A LOG THE TREE NAMES AND `show` CANNOT READ IS SAID, by path (#138 item + # 11). The parser's status is the pipeline's, so the failure left no trace: + # the lane simply had no lines, which the listing reads as DORMANT. The line + # reaches the person through `state_events`' warnings, and `lanes_rows` reads + # it back out of that file by its fixed prefix. + # AND A LIST OF THE LOGS THAT COULD NOT BE MADE IS SAID THE SAME WAY (the + # review of #289, SHOULD-1(a)). Piped straight into the loop, a failed + # `ls-tree` was no logs at all: every lane lost its events - its `dir` among + # them - in silence. `worktree_rows` reads this line back out of the same + # warnings, and because the events are built once per process, it speaks for + # the very read every lane's `dir` came from. + rl_list="" + if ! rl_list="$(git -C "$LANES_REPO" ls-tree --name-only "origin/$LANES_BRANCH" -- "$LANES_LOG_PREFIX" 2>/dev/null)"; then + note "unlisted logs: $LANES_LOG_PREFIX on origin/$LANES_BRANCH — git could not list them, so no log's lines are in this read" + return 0 + fi + printf '%s\n' "$rl_list" \ + | while IFS= read -r rf; do + [ -n "$rf" ] || continue + case "${rf##*/}" in README.md) continue ;; esac + git -C "$LANES_REPO" show "origin/$LANES_BRANCH:$rf" 2>/dev/null | parse_log_stream "$rf" + [ "${PIPESTATUS[0]}" = 0 ] || note "unreadable log: $rf — git could not read it, so none of its lines are in this read" + done +} + +# THE SOURCE OF EVERY STATE READ. Cached for the life of one invocation, +# because `who` on a held object asks for it eight or nine times (the state +# scan, the superseded filter once per holder, staleness twice, the crossing +# check) and reading it is 45 `git show`s. Any write flushes it: `claim` +# rescans after its rebase, and the ref has moved by then. +SE_CACHE_FILE="$(mktemp "${TMPDIR:-/tmp}/lanes-edit-events.XXXXXX" 2>/dev/null || printf '')" +# THE BUILD'S WARNINGS OUTLIVE THE BUILD, AND THAT IS NOT A CONVENIENCE. +# `LOG_AWK` writes `unreadable: :` and its count to stderr WHILE the +# stream is parsed — so they were emitted by whichever caller happened to build +# the cache first, and lost entirely when that caller was a command substitution +# with `2>/dev/null`. That was always true and never mattered, because the +# first builder in `who` was a call whose stderr reached the person. Ruling 12's +# one-pass listing moved the first build into exactly such a substitution — the +# `lr_facts` render — and the whole warning vanished from `who --lane`, caught +# by the two assertions that exist for it. +# +# So the build's stderr is CAPTURED beside the cache and replayed once per +# shell. `SE_WARNED` is deliberately a plain variable: a subshell that replays +# into `/dev/null` sets it only in ITSELF, so the parent still warns at its own +# first call — which is the call whose stderr a person is reading. An +# append-only log is never rewritten, so a line no parser reads is a hold no +# tool will mention again: this warning is the only notice there is. +SE_WARN_FILE="${SE_CACHE_FILE:+$SE_CACHE_FILE.warn}" +SE_WARNED=0 +state_events_warn() { + [ "$SE_WARNED" = 1 ] && return 0 + [ -n "$SE_WARN_FILE" ] && [ -s "$SE_WARN_FILE" ] || return 0 + SE_WARNED=1 + cat -- "$SE_WARN_FILE" >&2 + return 0 +} +state_events() { + if [ -z "$SE_CACHE_FILE" ]; then remote_log_events; return 0; fi + if [ ! -s "$SE_CACHE_FILE" ]; then + # BUILT ATOMICALLY, because `claim` asks for this from both ends of one + # pipeline: `state_events | lane_states_on | holders_of`, and holders_of + # calls superseded_by, which asks again while the first read is still + # writing. A half-written cache read as a whole one loses lines, and a + # lost line is a hold that has vanished. Write to a per-subshell name and + # rename: a reader then sees either the empty file (and builds its own) or + # the finished one, never half of it. + se_t="$SE_CACHE_FILE.${BASHPID:-$$}" + remote_log_events > "$se_t" 2> "$se_t.warn" + mv -f -- "$se_t.warn" "$SE_WARN_FILE" 2>/dev/null || rm -f -- "$se_t.warn" + mv -f -- "$se_t" "$SE_CACHE_FILE" 2>/dev/null || { state_events_warn; cat -- "$se_t"; rm -f -- "$se_t"; return 0; } + fi + state_events_warn + cat -- "$SE_CACHE_FILE" +} +state_events_flush() { + [ -n "$SE_CACHE_FILE" ] && : > "$SE_CACHE_FILE" + # The warnings belong to the stream that was parsed; a flush means it is + # parsed again, so they are said again. + [ -n "$SE_WARN_FILE" ] && : > "$SE_WARN_FILE" + SE_WARNED=0 + return 0 +} + +# One lane's own events, and whether that lane has a log at all — from +# `origin/` for the same reason. A lane whose log exists only in this +# working tree has not published anything, and a lane whose log exists only on +# `origin` is a lane this checkout has not pulled: the second is the case that +# matters and the one that used to read as "pre-cutover". +# +# AMENDMENT 15 — AND THE FILE IS FOUND WHATEVER ITS CASE. A lane whose log was +# written under another spelling has not lost its history the moment its row's +# spelling becomes canonical; the first write renames the file, and until then +# every reader finds it. +# +# BOTH HALVES ASK `log_path_ci`, AND A `head -n1` IS NOT AN ANSWER (Copilot round +# 4 on openRepoTools#41). The working-tree branch took the first of the +# case-insensitive matches exactly as the published lookup did, so two local +# files made a read-only caller decide a lane's resume, its profile and its state +# out of half its history — silently, while the WRITER treats that same state as +# ambiguous and refuses. One resolver now answers both, and its 2 is carried: +# `lane_log_exists` spends it rather than 1, so "there are two logs" is never +# read as "there is no log". +lane_log_events() { + ll_rel="$(log_path_ci "$1")" || return 2 + if [ -n "$LANES_IDX_DIR" ]; then + # A LOG THE INDEX DOES NOT HOLD IS A LOG `origin` DID NOT HOLD at the + # indexed commit: no lines, exactly as a `git show` of a missing path. + command grep -Fqx -- "$ll_rel" "$LANES_IDX_DIR/logs" 2>/dev/null || return 0 + awk -F"$US" -v p="$ll_rel" '$10 == p' "$LANES_IDX_DIR/events" + # THAT LOG'S WARNINGS AND THE COUNT THAT CLOSES THEM (opensoft/openRepoTools#166 + # item 3): the source read runs LOG_AWK over this one file, whose END says + # how many lines it could not read. The export writes that line after each + # log's own warnings, so it is the line straight after this log's last one. + awk -v p="unreadable: $ll_rel:" ' + index($0, p) == 1 { print; mine = 1; next } + mine && /^[0-9]+ unreadable line[(]s[)] above/ { print } + { mine = 0 }' "$LANES_IDX_DIR/warn" >&2 2>/dev/null || : + return 0 + elif have_remote_ref; then + git -C "$LANES_REPO" show "origin/$LANES_BRANCH:$ll_rel" 2>/dev/null | parse_log_stream "$ll_rel" + else + ll_f="$LANES_LOG_DIR/${ll_rel##*/}" + [ -f "$ll_f" ] || return 0 + log_events "$ll_f" + fi +} +lane_log_exists() { + lle_rel="$(log_path_ci "$1")" || return 2 + if [ -n "$LANES_IDX_DIR" ]; then + command grep -Fqx -- "$lle_rel" "$LANES_IDX_DIR/logs" 2>/dev/null + elif have_remote_ref; then + git -C "$LANES_REPO" cat-file -e "origin/$LANES_BRANCH:$lle_rel" 2>/dev/null + else + [ -f "$LANES_LOG_DIR/${lle_rel##*/}" ] + fi +} + +# The register, read the same way — `who --landing` is a state read about a +# merge hold other lanes are holding their merges for, so it must see what +# landed rather than what this checkout happens to have pulled. +# CACHED FOR THE LIFE OF ONE PROCESS, and Amendment 11's listing is the reason. +# The published register is a 1 MB file and this is a `git show` of it; every +# `row_of_lane`, `lane_named_ci`, `lane_of_session` and `lane_workstation` call +# makes one. A single lane's act makes a handful and nobody noticed — but +# `lanes` asks about EVERY lane in the register, so the same megabyte was being +# re-rendered dozens of times for one listing a person is waiting on. +# +# IT IS SAFE BECAUSE NOTHING INSIDE ONE INVOCATION MOVES IT. `origin/` +# is advanced by `log_sync`, which every subcommand runs BEFORE it reads, and by +# `commit_push`, which runs AFTER the last read of a write path — so the ref a +# process reads is fixed for as long as that process reads it. The one act that +# would break that assumption is a second `log_sync` mid-read, and there is +# none; `log_sync` clears this cache anyway, so a caller that adds one gets the +# fresh answer rather than a stale one. +# AND IN A FILE AS WELL AS A VARIABLE (A11 Addendum 4 ruling 12). The variable +# serves one shell; every caller of `row_of_lane`, `lane_workstation` and +# `session_ids_of_lane` reaches it through `$( … )`, which is a SUBSHELL, so the +# variable cache was rebuilt — a `git show` of 1.1 MB — by all four of the +# per-lane reads the listing makes, for every lane. The file survives the +# subshell that wrote it, so the megabyte is rendered once per process. +# +# AND THE READ SAYS WHETHER IT HAPPENED (opensoft/openRepoTools#67). +# `register_text_checked` is the read itself: 0 with the register on stdout, and +# 1 where the published `git show` or the working tree's `cat` FAILED — what it +# prints then is whatever that read printed, so `register_text` renders a failed +# read exactly as it always did, and it is not an answer. `register_text` is the +# same read with the status thrown away, as it always was, because its callers +# are pipelines whose `awk` answers for them and rewriting all of them is not +# this change. The three callers for which an empty register is a VERDICT ask +# the checked read through `session_ids_checked` below. +# +# A FAILED READ IS NEVER CACHED, in the variable or in the file. It used to be: +# the empty render went into both, so the first caller to meet a failed read — +# `canon_lane`, which `claim` and `duplicate-holder` both run first — left every +# later read in the process an empty register with no failure left to report, +# and a checked read behind it would have been reading that cache instead of the +# register. The next read asks again, and gets the same failure or the register. +LANES_REGISTER_CACHE="" +register_text_checked() { + # AMENDMENT 14 — under `--index`, the register's rows and its Rule 6 and + # Amendment 10 lines as the index holds them, in register order. Not cached: + # it is one local file, and the cache below belongs to the published read. + if [ -n "$LANES_IDX_DIR" ]; then cat -- "$LANES_IDX_DIR/register"; return; fi + if [ -n "$LANES_REGISTER_CACHE" ]; then printf '%s\n' "$LANES_REGISTER_CACHE"; return 0; fi + rt_c="${SE_CACHE_FILE:+$SE_CACHE_FILE.register}" + if [ -n "$rt_c" ] && [ -s "$rt_c" ]; then cat -- "$rt_c"; return; fi + rt_txt=""; rt_rc=0 + # WHETHER THE REGISTER IS PUBLISHED IS `register_published`'s answer, the + # tree's (#138 item 18, the review of #230): asked with `cat-file -e`, a + # missing or corrupt blob was "not published" and this checkout's copy was + # read in its place — an answer, where #67's rule above makes it a 1. + rt_prc=0; register_published || rt_prc=$? + case "$rt_prc" in + 0) rt_txt="$(git -C "$LANES_REPO" show "origin/$LANES_BRANCH:$LANES_PATH" 2>/dev/null)" || rt_rc=$? ;; + 8) rt_txt="$(cat -- "$LANES_FILE")" || rt_rc=$? ;; + *) rt_rc=1 ;; + esac + if [ "$rt_rc" != 0 ]; then + printf '%s\n' "$rt_txt" + return 1 + fi + LANES_REGISTER_CACHE="$rt_txt" + if [ -n "$rt_c" ]; then + printf '%s\n' "$LANES_REGISTER_CACHE" > "$rt_c.${BASHPID:-$$}" 2>/dev/null && + mv -f -- "$rt_c.${BASHPID:-$$}" "$rt_c" 2>/dev/null || + rm -f -- "$rt_c.${BASHPID:-$$}" + fi + printf '%s\n' "$LANES_REGISTER_CACHE" +} +register_text() { register_text_checked || :; } + +# IS THE REGISTER PUBLISHED? 0 yes, 8 no (or there is no `origin/`), 1 +# the tree could not be listed. THE TREE ANSWERS AND NEVER THE BLOB (#138 item +# 18, the review of #230): `cat-file -e` fails for a blob that is missing or +# corrupt exactly as for a path origin does not have, so a register origin has +# and git could not read was "not published", and `register_text` answered with +# this checkout's copy — the seam, `next-free` and `add-row` all read that as +# the published register. `retire_rows` asks a lane's log the same way (item 17). +# THE PATH IS AN ARGUMENT, the register's by default: `archive_text` asks it of +# the archive, which had the same `cat-file -e` and the same fallback. +register_published() { # [] + have_remote_ref || return 8 + rp_tree="" + rp_tree="$(git -C "$LANES_REPO" ls-tree --name-only "origin/$LANES_BRANCH" -- "${1:-$LANES_PATH}" 2>/dev/null)" || return 1 + [ -n "$rp_tree" ] || return 8 + return 0 +} + +# ------------------------- AMENDMENT 19(d): THE ARCHIVE IS PART OF THE READ +# +# `archive-rows ` moves a repository's RETIRED rows out of the register +# and into `lanes/archive/LANES-retired.md`, and the amendment is explicit about +# who follows them: *"every reader of the next free position and `lanes +# --closed` read the archive too"*. So the archive is read exactly as the +# register is — `origin/` first (R19), this checkout second — and its +# ABSENCE IS SILENCE: a register nobody has archived from has no such file, and +# that is the ordinary case rather than an error. +# +# It is NOT cached the way `register_text` is: this file is the small one (the +# rows nobody reads day to day), and a write that rescans it after its rebase +# (`add-row`'s `retired_identity_hits`) must read it as it now stands, which a +# cache kept for the process would not. ONE LISTING PINS IT, and only for its +# own reads: `worktree_rows` reads the archive once, and where that read +# succeeded, `PIN_ARCHIVE` hands its text to every read of the listing it then +# makes - so the archive the listing names lanes from IS the one it checked (the +# review of opensoft/openRepoTools#289, SHOULD-1(b): a read that failed only +# after the check left the archive's lanes out of a listing taken as whole). +LANES_ARCH_NAME="LANES-retired.md" +LANES_ARCH_PATH="${LANES_ARCH_PATH:-${LANES_PREFIX}archive/$LANES_ARCH_NAME}" +LANES_ARCH_FILE="${LANES_ARCH_FILE:-$LANES_DIR/archive/$LANES_ARCH_NAME}" +PIN_ARCHIVE=0 +PIN_ARCHIVE_TEXT="" +archive_text() { + if [ "$PIN_ARCHIVE" = 1 ]; then printf '%s' "$PIN_ARCHIVE_TEXT"; return 0; fi + # AMENDMENT 14 — under `--index`, the archive's rows where the indexed commit + # carried an archive; where it carried none, the same local fallback below. + if [ -n "$LANES_IDX_DIR" ] && [ -f "$LANES_IDX_DIR/archive" ]; then cat -- "$LANES_IDX_DIR/archive"; return 0; fi + # A published archive that cannot be rendered cannot be replaced with a + # possibly stale local copy: that copy may omit a retired position. WHETHER + # IT IS PUBLISHED IS THE TREE'S ANSWER (the re-review of #230): asked with + # `cat-file -e`, an archive blob git could not read was "not published", the + # local copy answered, and a retired position was offered and reissued. + if [ -z "$LANES_IDX_DIR" ]; then + at_prc=0; register_published "$LANES_ARCH_PATH" || at_prc=$? + case "$at_prc" in + 0) if git -C "$LANES_REPO" show "origin/$LANES_BRANCH:$LANES_ARCH_PATH" 2>/dev/null; then return 0; fi + note "the published $LANES_ARCH_PATH exists but could not be read — a local copy cannot prove it contains every published retired position" + return 1 ;; + 8) : ;; + *) note "the tree of origin/$LANES_BRANCH could not be listed, so whether $LANES_ARCH_PATH is published is not known — and a local copy cannot stand in for it" + return 1 ;; + esac + fi + # AND THE LOCAL COPY IS THE SAME RULE ONE RUNG DOWN: a file that is THERE and + # will not open is a read that FAILED, and its rows hold positions. Saying + # nothing here would put a retired `-` back on offer. + archive_local_text +} + +# THIS CHECKOUT'S ARCHIVE: its text, nothing where there is none, and 1 where +# the path is THERE AND IS NOT A REGULAR FILE (#138 item 7) as well as where it +# will not open. Asked with `-f` alone, a directory, a FIFO or a broken symlink +# read as no archive and its retired positions came back on offer; `cat` on the +# FIFO would have blocked besides. `archive_text`'s last rung and +# `retired_identity_hits`' second read are both this. +archive_local_text() { + if [ -f "$LANES_ARCH_FILE" ]; then + cat -- "$LANES_ARCH_FILE" 2>/dev/null || return 1 + elif [ -e "$LANES_ARCH_FILE" ] || [ -L "$LANES_ARCH_FILE" ]; then + note "$LANES_ARCH_PATH is there and is not a regular file, so the retired positions it should hold cannot be read" + return 1 + fi + return 0 +} + +# A retired name OR its numeric position is unavailable, even when a recut +# suffix changes the spelling. Inspect both published and unpushed archives. +# +# A LINE THE SCAN CANNOT TAKE APART IS A REFUSAL, NOT A NON-ROW (#122, Copilot +# round 6 on #93). The scan skipped every `|` line with no backticked token, and +# took the first backtick ANYWHERE in a line as its lane, so a retired row whose +# lane cell a hand edit or a bad merge had mangled — `| repoX-4 | harness `` +# | …` — dropped out of the answer and add-row reissued its position: 19(b)'s +# guarantee failing open. Every `|` line of the archive is now one of three: +# +# * THE RULE: `|`, `-`, `:` and blanks only, with at least one dash; +# * THE HEADER: its first cell is the word `lane`, as in the header +# `archive_rows` writes. It is NOT found as "the line above the rule": the +# live register carried two rows between its header and its rule on +# 2026-10-19, so a hand edit can part the two, and refusing a header for it +# would make add-row refuse on the path that creates every lane. Nor is it +# found by counting ` | `: the header carries six, exactly as a row does; +# * A ROW: its first backticked token lies wholly inside its FIRST cell. That +# is the token every reader here takes as the lane, `*(unnamed)* ``` +# included (three live rows are spelled that way). +# +# Any other `|` line is printed with its line number, and this returns 3: a row +# nobody can read may be the very lane being added. AND THE SCAN'S OWN STATUS +# IS READ. The scan's status used to be that of the `sort -u` behind it, so an +# awk that FAILED read as "no archived row matched". +# +# EACH LINE NUMBER NAMES ITS COPY (the review of #263, NIT 4). Both copies are +# scanned, and where the published archive and this checkout's differ, one bad +# line had two numbers and no word on which file either was in. +RETIRED_ROWS_AWK=' + function key(n, h, p) { + p = n; sub(/^.*-/, "", p); sub(/[A-Za-z]$/, "", p) + h = n; sub(/-[^-]*$/, "", h) + if (h == n || p !~ /^[0-9]+$/) return "" + return tolower(h) "-" (p + 0) + } + BEGIN { wk = key(want) } + substr($0, 1, 1) == "|" { + if ($0 ~ /^[|][-:| \t]*$/ && index($0, "-")) next + c = substr($0, 2); s = index(c, " | "); if (s) c = substr(c, 1, s - 1) + h = c; sub(/^[ \t]+/, "", h); sub(/[ \t|]+$/, "", h) + if (tolower(h) == "lane") next + p1 = index(c, "`"); p2 = p1 ? index(substr(c, p1 + 1), "`") : 0 + if (!p1 || p2 < 2) { printf "M%s%d%s%s\n", sep, NR, sep, $0; next } + t = substr(c, p1 + 1, p2 - 1) + if (tolower(t) == tolower(want) || (wk != "" && key(t) == wk)) printf "H%s%s\n", sep, t + }' +retired_identity_hits() { # ; stdout: matching retired spellings · 1 not read · 3 a line not a row + ri_lane="$1" + ri_pub="$(archive_text 2>/dev/null)" || return 1 + ri_local="" + ri_local="$(archive_local_text 2>/dev/null)" || return 1 + ri_scan="" + ri_scan="$(printf '%s\n' "$ri_pub" | awk -v want="$ri_lane" -v sep="$US" "$RETIRED_ROWS_AWK")" || return 1 + ri_scan2="" + ri_scan2="$(printf '%s\n' "$ri_local" | awk -v want="$ri_lane" -v sep="$US" "$RETIRED_ROWS_AWK")" || return 1 + # WHICH COPY `archive_text` ANSWERED WITH: the index's under `--index`, else + # origin's where the tree publishes one, else this checkout's (its own rungs, + # read the same way; a read that failed has already returned 1 above). + ri_from="this checkout" + if [ -n "$LANES_IDX_DIR" ]; then + [ -f "$LANES_IDX_DIR/archive" ] && ri_from="the index" + elif register_published "$LANES_ARCH_PATH" >/dev/null 2>&1; then + ri_from="origin/$LANES_BRANCH" + fi + ri_bad="" + ri_bad="$( { printf '%s\n' "$ri_scan" | awk -v sep="$US" -v w="$ri_from" 'substr($0, 1, 2) == "M" sep { print w sep substr($0, 3) }' + printf '%s\n' "$ri_scan2" | awk -v sep="$US" -v w="this checkout" 'substr($0, 1, 2) == "M" sep { print w sep substr($0, 3) }'; } | + awk -F"$US" '{ k = $2 FS $3 + if (!(k in w)) { o[++n] = k; w[k] = $1 } else if (w[k] != $1) w[k] = w[k] " and " $1 } + END { for (i = 1; i <= n; i++) { split(o[i], p, FS); print "line " p[1] " (" w[o[i]] "): " p[2] } }')" || return 1 + if [ -n "$ri_bad" ]; then + note "$LANES_ARCH_PATH carries a table line that is neither its header, its rule, nor a row whose first cell holds its lane in backticks (each named with the copy it is in):" + printf '%s\n' "$ri_bad" | sed -e 's/^/lanes-edit: /' >&2 + return 3 + fi + ri_hits="" + ri_hits="$(printf '%s\n%s\n' "$ri_scan" "$ri_scan2" | + awk -v sep="$US" 'substr($0, 1, 2) == "H" sep { print substr($0, 3) }')" || return 1 + [ -z "$ri_hits" ] || printf '%s\n' "$ri_hits" | LC_ALL=C sort -u +} + +# EVERY REFUSAL HERE TAKES ITS ROW BACK, not only the retired match (the review +# of #263, M1). This runs after `pull --rebase`, so the add-row is already a +# local commit on top of the peer's archive. A refusal that only returned left +# that commit at HEAD, and the next unrelated write from this checkout pushed +# it: measured, a peer's archive line this scan could not take apart during +# add-row's pull gave exit 1, then `set-row-state` published the row it had +# refused. A read that failed and a line that is not a row are refusals of the +# same row as a retired match is, so all three run the same compensation. +add_row_retirement_rescan() { + ar_rebased_rc=0 + ar_rebased_hits="$(retired_identity_hits "$ADD_ROW_LANE")" || ar_rebased_rc=$? + if [ "$ar_rebased_rc" != 0 ]; then + ar_why="the archive could not be read after rebase, or it carries a line that is not a row (above), so whether lane $ADD_ROW_LANE was retired meanwhile is not known" + ar_subject="cancel add-row whose retirement could not be checked after rebase" + ar_back=1 + elif [ -n "$ar_rebased_hits" ]; then + ar_why="lane $ADD_ROW_LANE was retired by a peer before this add-row could push (archive: $(printf '%s' "$ar_rebased_hits" | tr '\n' ' '))" + ar_subject="cancel add-row rejected by peer retirement" + ar_back=2 + else + return 0 + fi + # Leaving the rejected add-row at HEAD would let the next unrelated registry + # write push it. Remove ONLY this invocation's exact appended line and commit + # that compensation locally; any swept pre-existing edit stays intact. + # + # AND ONLY A ROW THIS CHECKOUT STILL ADDS IS ITS OWN TO TAKE BACK (the delta + # review of #263, D1). A peer that published the byte-identical row first + # makes `pull --rebase` DROP this add-row's commit as already upstream, and + # the one copy left in the register is then the peer's: the exact-line grep + # found it and deleted it, and the next write published that deletion + # (measured: the peer's row gone from origin). So the copy taken back is the + # one this checkout's register adds over origin/$LANES_BRANCH's, read from + # their diff by content — which is what a surviving add-row commit is, under + # whatever sha the rebase gave it, and whatever local commits sit beside it. + # None added: nothing of this add-row's is left, and nothing is taken back. + # One: that line, wherever an identical peer copy sits. More than one, or a + # diff that cannot be read: not this act's to guess, and said so. + # "origin already has the row" would be wrong the other way: an add-row + # commit that SURVIVED beside a peer's identical row at another place would + # be kept, and published by the next write as a second copy. + # + # AND THE LINE IS COUNTED WHATEVER CONTEXT THE DIFF CARRIES (the delta review + # of #263, S3). `-U0` does not hold on its own: a `GIT_DIFF_OPTS=-u3` in the + # environment overrides it outright, and a user's `diff.interHunkContext` + # fuses two nearby changes into one hunk with the lines between them as + # context. The parse counted only `+` lines, so a hunk carrying context put + # the row at the wrong line, the line check refused, nothing was taken back, + # and the next ordinary write published the row add-row had refused (M1 + # again; measured with each of the two). So both: this one diff runs with + # `GIT_DIFF_OPTS` unset and `diff.interHunkContext=0` (a `-c` on the command + # line outranks every config file and `GIT_CONFIG_*` in the environment), and + # the parse advances its new-file line on every line of a hunk but a removed + # one (`-`) or git's "\ No newline" note, so whatever context still arrives + # is counted where it stands. The `unset` is inside the command + # substitution's own subshell, and so touches nothing after it. + # + # AND IT IS READ AS TEXT (delta review 4 of #263, S4). Where git classes the + # register as binary, the diff is one line, "Binary files … differ", with no + # hunk to read: a `binary` or `-diff` attribute, published or local, a diff + # driver with `binary=true`, `core.attributesFile`, `GIT_ATTR_SOURCE`, + # `attr.tree`, a NUL byte in its first 8000 bytes, or a `core.bigFileThreshold` + # below its size (the live register is over 2 MB). add-row then said this + # checkout added no copy of the row, kept its commit, and the next write + # published the row (measured with each). `--text` gives the hunks whatever + # classes the register. + ar_diff="$(unset GIT_DIFF_OPTS; git --no-replace-objects --no-pager -C "$LANES_REPO" -c "$CP_EXACT" -c diff.interHunkContext=0 diff --no-color --no-ext-diff --no-textconv --text -U0 "refs/remotes/origin/$LANES_BRANCH" -- "$LANES_PATH" 2>/dev/null)" || { + note "$ar_why; and this checkout's register could not be compared with origin/$LANES_BRANCH's, so whether a copy of the rejected row here is this add-row's or a peer's is not known. Nothing was taken back: read \`git -C $LANES_REPO log -p origin/$LANES_BRANCH..HEAD -- $LANES_PATH\` and remove this add-row's row before any later push" + return 1 + } + ar_lines="$(printf '%s\n' "$ar_diff" | AR_ROW="$ADD_ROW_TEXT" LC_ALL=C awk ' + /^@@ / { h = $0; sub(/^@@ -[0-9,]+ [+]/, "", h); sub(/[ ,].*$/, "", h); n = h + 0; inh = 1; next } + !inh { next } + { c = substr($0, 1, 1) } + c == "-" || c == "\\" { next } + c == "+" && substr($0, 2) == ENVIRON["AR_ROW"] { print n } + { n++ } + ')" || { + note "$ar_why; and the diff of this checkout's register against origin/$LANES_BRANCH's could not be read, so nothing was taken back: remove this add-row's row before any later push" + return 1 + } + case "$ar_lines" in + '') + if git --no-replace-objects --no-pager -C "$LANES_REPO" show "refs/remotes/origin/$LANES_BRANCH:$LANES_PATH" 2>/dev/null | command grep -qFx -- "$ADD_ROW_TEXT"; then + note "$ar_why. origin/$LANES_BRANCH already carries this exact row, published by a peer, and the rebase dropped this add-row's commit as already upstream: this checkout adds no copy of it, so there is nothing of this add-row's to take back and the peer's row is left as it is." + else + note "$ar_why. This checkout's register carries no copy of the row that origin/$LANES_BRANCH's does not, so there is nothing of this add-row's to take back." + fi + return "$ar_back" ;; + *$'\n'*) + note "$ar_why; and this checkout's register adds more than one exact copy of the rejected row over origin/$LANES_BRANCH's, so which is this add-row's is not known and none was taken back: the local add-row commit must be repaired before any later push" + return 1 ;; + esac + ar_line="$ar_lines" + [ "$(sed -n "${ar_line}p" "$LANES_FILE" 2>/dev/null)" = "$ADD_ROW_TEXT" ] || { + note "$ar_why; and line $ar_line of $LANES_FILE, where the diff puts the rejected row, does not hold it exactly, so nothing was taken back: the local add-row commit must be repaired before any later push" + return 1 + } + # A REFUSAL OF THE TAKE-BACK ITSELF SAYS ADD-ROW'S TRUTH (the delta review of + # #263, NIT): `delete_lines`' own sentences are archive-rows' — "the rows are + # in the archive", "the archive may have been appended" — and false here. + REG_COMMITTED_HERE="this act HAS committed its row for lane $ADD_ROW_LANE, locally and unpushed" + DL_SAYS_UNCHANGED="no row was removed, so that row is still in it and in that commit. Remove it from $LANES_PATH and commit that before any other write in $LANES_REPO, because the next one would publish it" + DL_SAYS_AFTER_WRITE="Its row for lane $ADD_ROW_LANE was not taken back, and this act HAS committed it, locally and unpushed: with the register whole, remove that row from $LANES_PATH and commit that before any other write in $LANES_REPO, because the next one would publish it." + delete_lines "$ar_line" + REG_COMMITTED_HERE=""; DL_SAYS_UNCHANGED=""; DL_SAYS_AFTER_WRITE="" + # A REMOVAL THAT CANNOT BE COMMITTED SAYS SO (delta review 4 of #263, N3). + # These returned in silence: the removal was left written or staged under + # add-row's commit, and the next write's own commit carried it, under its + # own caption, with no one told. + ar_msg="LANES($ADD_ROW_LANE@$WS): $ar_subject" + ar_fix="add-row's commit still holds the row. Commit the removal before any other write in $LANES_REPO, so that write does not carry it under its own caption: \`git -C $LANES_REPO commit -m '$ar_msg' -- $LANES_PATH\`" + git -C "$LANES_REPO" -c "$CP_EXACT" add -- "$LANES_PATH" || { + note "$ar_why; the rejected row was removed from $LANES_FILE, but staging that removal failed, so it is only in the working tree, and $ar_fix" + return 1 + } + git -C "$LANES_REPO" -c "$CP_EXACT" commit -q -m "$ar_msg" -- "$LANES_PATH" || { + note "$ar_why; the rejected row was removed from $LANES_FILE and that removal is staged, but its compensating commit failed, so $ar_fix" + return 1 + } + note "$ar_why; the rejected row was removed in a compensating LOCAL commit, so no later write publishes it. Neither commit was pushed." + return "$ar_back" +} + +# Each lane's LAST line on , as +# utc lane verb uuid ws object ref payload text file line +# +# R14 — "LAST" IS THE LAST LINE IN THE FILE, and never the largest UTC. One +# lane's log is append-only and single-writer, so its line order IS that lane's +# write order; a clock is not. It was a max-UTC read here that made a LANDED +# invisible behind the LANDING it closed, on the day this workstation's clock +# was jumping ±25s. `pos()` is the line's address — its file and its line +# number, zero-padded so that one string comparison orders both. +# AMENDMENT 15 — KEYED ON THE LANE LOWER-CASED. The key decides how many rows +# come out of here, and the ROW is the whole line, so the spelling a reader sees +# is still the one the winning line carried. Keyed on the raw `$2`, a lane whose +# log spells it two ways emitted TWO rows for ONE lane — and `claim`-s rival +# test, which excludes its OWN row from this set, then met its own earlier +# CLAIMED as a stranger and refused the lane its own object (Copilot round 1 on +# openRepoTools#41). +PER_LANE_AWK=' +function pos(pf, pn) { return pf "\034" sprintf("%09d", pn) } +BEGIN { FS = sep } +$6 == o { k = tolower($2); p = pos($10, $11); if (!(k in u) || p >= u[k]) { u[k] = p; L[k] = $0 } } +END { for (l in u) print L[l] }' + +# Ordered by LANE NAME, deliberately. These rows are one line per lane, so +# nothing about their order is a fact about the object: which lane got there +# first is LANDING ORDER ON `main` (F13), which `first_landed_of` reads out of +# git history. This sort used to be on the UTC field, and sorting a set of +# lanes by their clocks is exactly the comparison R14 removes. +lane_states_on() { # [events-producer-output on stdin] + awk -v sep="$US" -v o="$1" "$PER_LANE_AWK" | LC_ALL=C sort -t"$US" -k2,2 +} + +# The lanes that HOLD — those whose own last line on it is open. +# Prints lane verb utc file line: the last two are the ADDRESS of that +# lane's own last line, which is what a staleness test needs in order to ask +# "has this lane written anything BELOW it in its own log" without a clock. +holders_of() { + hf_obj="$1" + while IFS="$US" read -r h_utc h_lane h_verb h_uuid h_ws h_o h_ref h_pay h_txt h_file h_line; do + [ -n "${h_verb:-}" ] || continue + is_open_verb "$h_verb" || continue + # A CLAIMED that another lane has since taken over is not a hold. + [ -z "$(superseded_by "$hf_obj" "$h_lane" "$h_verb")" ] || continue + printf '%s%s%s%s%s%s%s%s%s\n' "$h_lane" "$US" "$h_verb" "$US" "$h_utc" "$US" "$h_file" "$US" "$h_line" + done +} + +# A LANE NAME IS NOT A REGULAR EXPRESSION (Copilot round 4 on openRepoTools#41). +# Every filter of these US-delimited holder rows was `grep "^$lane$US"`, which +# hands a name straight to a matcher: `check_lane_name` admits `.`, so excluding +# `repo.a-1` also excludes the REAL rival `repoXa-1`, and `first_landed_of`'s +# `grep -q` could match a lane that is not in the set at all. A claim decided by +# that filter is a claim whose winner is whichever name happened to be a pattern +# — in a race whose whole point is that the arbiter is exact. +# +# So the comparison is `awk` on FIELD ONE, `tolower` on both sides, with no +# pattern anywhere: literal, case-insensitive (Amendment 15) and blind to `.`, +# `*`, `[` and `^`. `-v` carries one line, which a lane name is. +rows_not_named() { # — every row whose first field is NOT it + awk -v sep="$US" -v want="$1" 'BEGIN { FS = sep; w = tolower(want) } tolower($1) != w' +} +rows_named() { # — every row whose first field IS it + awk -v sep="$US" -v want="$1" 'BEGIN { FS = sep; w = tolower(want) } tolower($1) == w' +} + +# Every object this lane's OWN log mentions, with the lane's last verb on it. +# `lane-end`'s refusal and `who --lane` both read exactly this. +# Every object this lane's OWN log mentions, with the lane's last verb on it, +# plus — read from EVERY lane's log — whether another lane has since taken the +# object over. A lane closes only its own hold, so after someone else's +# TAKEOVER this lane's last line is still its CLAIMED; without the fifth field +# `lane-end` would refuse for ever and never say why. +# utc verb object ref+payload superseded-by(lane@utc, or empty) +lane_objects() { + # 8, not 1: "no log file" is an ANSWER. TWO LOGS IS NOT THAT ANSWER, and 2 is + # carried through rather than flattened into it (Copilot round 4): `who --lane` + # and `lane-end`'s refusal would otherwise report a lane whose history is split + # across two files as a pre-cutover lane with no log at all. + lo_ex=0 + lane_log_exists "$1" || lo_ex=$? + case "$lo_ex" in + 0) : ;; + 2) return 2 ;; + *) return 8 ;; + esac + # AMENDMENT 15 — THE LANE FIELD OF A LOG LINE IS MATCHED CASE-INSENSITIVELY, + # and the caller has already resolved `$1` to the row's spelling. The line's + # own spelling is whatever was TYPED on the day it was appended, and an + # append-only log is never rewritten: `lanes/log/openxfactory-2.md` carries + # `lane openXfactory-2` lines from 2026-09-02 and `lane openxfactory-2` lines + # from the 23:51:56Z incident, in one file, about one lane. Read byte for + # byte, half of that lane's claims are invisible to `who --lane` and to + # `lane-end`'s refusal — which is the amendment's own sentence, that a lane + # name is compared case-insensitively wherever a name is looked up, and the + # OBJECT LOG is one of the places it lists. + # + # `mel` IS COMPUTED ONCE IN `BEGIN`, not per line: this stream is every line + # of every lane's log on the estate. + state_events | awk -v sep="$US" -v me="$1" ' + function pos(pf, pn) { return pf "\034" sprintf("%09d", pn) } + BEGIN { FS = sep; mel = tolower(me) } + $6 ~ /^lane:/ { next } + tolower($2) == mel { + if (!($6 in ord)) { ord[$6] = ++n; byn[n] = $6 } + p = pos($10, $11) + if (!($6 in mp) || p >= mp[$6]) { mp[$6] = p; utc[$6] = $1; verb[$6] = $3; ref[$6] = $7; pay[$6] = $8 } + } + # EVERY OTHER LANE, ITS OWN LAST LINE on each object, by the same file-order + # rule this lane is read by (R14). The verb is kept, not only the TAKEOVERs, + # because what decides supersession is whether a TAKEOVER is still the last + # word of the lane that wrote it — see the END block. + # KEYED ON THE OTHER LANE LOWER-CASED TOO, and its SPELLING carried beside + # the key (Amendment 15): two spellings of one taker would otherwise be two + # takers, and the one whose last line is a stale CLAIMED could hide the + # other-s TAKEOVER. `on[]` keeps the spelling of the line that won the + # position test, so what is PRINTED is still a name somebody wrote. + # `ot[]` is the lane a TAKEOVER names as `← lane:`, lower-cased, and + # empty for any other line: the link a chain is followed by (#74, below). + tolower($2) != mel { + q = pos($10, $11); okey = $6 SUBSEP tolower($2) + if (!(okey in op) || q >= op[okey]) { op[okey] = q; ov[okey] = $3; ou[okey] = $1; on[okey] = $2 + ot[okey] = ($3 == "TAKEOVER" && $7 == "←" && substr($8, 1, 5) == "lane:") ? tolower(substr($8, 6)) : "" } + } + # SUPERSEDED, WITHOUT ORDERING TWO FILES AGAINST EACH OTHER (R14), AND ONLY + # WHILE THE TAKEOVER STILL STANDS (R18): another lane has a TAKEOVER on the + # object AS ITS OWN LAST LINE, and this lane has written nothing on it since + # — the last line here is still the open verb that TAKEOVER took. A + # TAKEOVER is never removed from an append-only log, so testing for one + # ANYWHERE in the file of the taker kept superseding these claims for ever: + # after that lane released the object and this one legitimately re-claimed + # it, `who` called the object FREE and a third lane was not refused. + # STALE UNTIL PR #61 (Copilot round 11): this paragraph itself said "a + # TAKEOVER displaces a CLAIMED and nothing else", singular, after the + # dead-lane exception of issue #30 had already widened what the awk + # fragment above tests. A TAKEOVER displaces CLAIMED (the ordinary + # stale-claim shape of decision 8(e)) or, per that dead-lane exception, a + # TAKEOVER, OPENED, LANDING or WITHDRAWN left by another lane (`claim + # --force` refuses every other verb) — that full set is the whole of the + # test; any later line of this lane is it speaking after the fact and is + # reported as it stands. The two lines sit in two different lanes, whose + # files share no clock, and this asks for none. + # A CHAIN IS FOLLOWED TO ITS LAST LINK (opensoft/openRepoTools#74), by the + # rule `superseded_by` below argues: when this lane-s own last line is a + # TAKEOVER, only another lane-s standing TAKEOVER that NAMES this lane + # (`← lane:`) displaces it, and not one this lane-s own + # TAKEOVER names back; any other open verb is displaced by any standing + # TAKEOVER, and the taker NAMED is one no other standing TAKEOVER names + # wherever there is one. Without it the true holder at the end of a chain + # was told here that it had been "taken over" by the lane it took the + # object from, and `lane-end` handed it the release that frees the object. + END { for (kk in ov) if (ov[kk] == "TAKEOVER" && ot[kk] != "") { + split(kk, aa, SUBSEP); if (ot[kk] != aa[2]) nmd[aa[1], ot[kk]] = 1 } + for (kk in ov) if (ov[kk] == "TAKEOVER") { + split(kk, aa, SUBSEP); oo = aa[1]; ll = aa[2] + if (!(oo in verb)) continue + if (verb[oo] == "TAKEOVER") { + mt = (ref[oo] == "←" && substr(pay[oo], 1, 5) == "lane:") ? tolower(substr(pay[oo], 6)) : "" + if (ot[kk] != mel || mt == ll) continue + r = 1 + } else r = (((oo, ll) in nmd) ? 0 : 1) + if (!(oo in tp) || r > tr[oo] || (r == tr[oo] && op[kk] >= tp[oo])) { tp[oo] = op[kk]; tr[oo] = r; tlane[oo] = on[kk]; tutc[oo] = ou[kk] } } + for (i = 1; i <= n; i++) { o = byn[i] + supv = ((o in tlane) && (verb[o] == "CLAIMED" || verb[o] == "TAKEOVER" || verb[o] == "OPENED" || verb[o] == "LANDING" || verb[o] == "WITHDRAWN")) + sup = supv ? tlane[o] "@" tutc[o] : "" + printf "%s%c%s%c%s%c%s%c%s\n", utc[o], 31, verb[o], 31, o, 31, (ref[o] ? ref[o] " " pay[o] : ""), 31, sup } }' +} + +# The lane and UTC of a TAKEOVER on that is STILL THAT LANE'S OWN LAST +# LINE on it — printed only when $3, our own last verb on the object, is one of +# the OPEN VERBS a takeover can displace: CLAIMED (decision 8(e)'s ordinary +# stale-claim shape), or TAKEOVER, OPENED, LANDING or WITHDRAWN (issue #30's +# dead-lane exception, `superseded_by`'s own case below). Empty when there is +# none. STALE UNTIL PR #61 (Copilot round 8): this line said "the CLAIMED a +# takeover displaces", singular, after the awk fragment just above it had +# already grown the full set — the code was never wrong, only this prose. +# +# R18 — "ITS OWN LAST LINE" IS THE WHOLE OF THE BOUND. Per-lane last-line +# semantics apply to the taker too: once the taker writes RELEASED, CLOSED or +# LANDED on the object, its TAKEOVER supersedes nothing and a later CLAIMED by +# the dispossessed lane holds. Matching any TAKEOVER anywhere in the taker's +# append-only file made a legitimate re-claim invisible for ever: `who` called +# a held object FREE, `claim` did not refuse the next lane — the single outcome +# Rule 1 exists to prevent — and `who --lane` and `lane-end` disagreed about the +# same object. +# +# NO TIMESTAMP IS COMPARED (R14): the two lines are in two lanes' files and +# there is no shared clock to order them by, so the question asked is the one +# file order can answer — is our own last line still the claim, and is a +# TAKEOVER still theirs. The UTC printed beside the lane is information for the +# reader, never a key. +# +# A CHAIN OF TAKEOVERS RESOLVES TO ITS LAST LINK (opensoft/openRepoTools#74). +# Issue #30's dead-lane exception lets a TAKEOVER displace an earlier TAKEOVER +# — A claims, B takes over from A, C takes over from B once B is dead — and +# every link that displaces a TAKEOVER names the lane it displaced as +# `← lane:`: `claim --force` writes that payload for every hold that is not +# a CLAIMED, and only a CLAIMED is ever taken with a comment URL instead. The +# test used to be "does SOME other lane's last line here read TAKEOVER", and it +# read B's TAKEOVER — itself displaced by C — as proof that C was displaced +# too: `who` reported ZERO holders of an object C held. So the question is now +# asked by what our own last line is: +# * a TAKEOVER is displaced ONLY by another lane's standing TAKEOVER that +# NAMES our lane. B is displaced by C, which names it; C by nothing, since +# no standing TAKEOVER names C. One lane holds the object: the last link. +# * any other open verb is displaced by any standing TAKEOVER, as it always +# was, and the taker NAMED is one that no other standing TAKEOVER names — +# the lane that holds the object now — wherever there is one. A's line +# says C, not B. Where every taker is named, the file-ordered position +# picks which one is named; A is displaced either way. +# Two lanes that each end on a TAKEOVER and do not name each other — two takers +# of one stale claim — are therefore BOTH holders, the visible conflict the +# README's "Known, deliberate" paragraph has always described; since PR #61 +# (issue #30) widened the gate, the old test had them displace each other and +# `who` called the object FREE. Two TAKEOVERs that name EACH OTHER (a lane revived and took back +# what had been taken from it) are both holders too: no file order says which +# was written last, and a conflict `who` shows is one a person can resolve. +superseded_by() { # + # ANY OPEN VERB, NOT ONLY CLAIMED (Copilot round 7, PR #61, issue #30): a + # dead lane's TAKEOVER — decision 8(e)'s stale-CLAIMED case is still the + # common one, but opensoft/openRepoTools#30 added a dead-lane TAKEOVER that + # displaces an OPENED, LANDING, WITHDRAWN or an earlier TAKEOVER too, exactly + # the verbs `is_open_verb` already lists. Gating this early return on + # `= CLAIMED` alone left every one of those un-superseded: `holders_of` + # counted the dead lane's own OPENED as a live hold beside the taker's + # TAKEOVER, and `who` reported two holders of one object — the very + # collision #30 exists to end. + case "${3-}" in + CLAIMED|TAKEOVER|OPENED|LANDING|WITHDRAWN) : ;; + *) return 0 ;; + esac + # AMENDMENT 15 — `tolower` ON BOTH SIDES, exactly as `lane_objects` above + # reads the same stream: the lane field of a log line carries the spelling + # that was typed on the day, and one lane's two spellings are one lane. The + # NAME is still the one the winning line carried, because this is printed. + # OUR OWN LAST LINE IS READ HERE TOO, not only the other lanes': the TAKEOVER + # it may be is what names the lane a chain was taken from (#74, above). `t[]` + # is the lane each last line names as `← lane:`, lower-cased, or empty; + # a TAKEOVER naming its own lane names nobody. + state_events | awk -v sep="$US" -v o="$1" -v me="$2" -v mv="$3" ' + function pos(pf, pn) { return pf "\034" sprintf("%09d", pn) } + BEGIN { FS = sep; mel = tolower(me) } + $6 == o { p = pos($10, $11); ll = tolower($2) + if (!(ll in q) || p >= q[ll]) { q[ll] = p; v[ll] = $3; u[ll] = $1; nm[ll] = $2 + t[ll] = ($3 == "TAKEOVER" && $7 == "←" && substr($8, 1, 5) == "lane:") ? tolower(substr($8, 6)) : "" } } + END { for (l in q) if (v[l] == "TAKEOVER" && t[l] != "" && t[l] != l) named[t[l]] = 1 + for (l in q) { + if (l == mel || v[l] != "TAKEOVER") continue + if (mv == "TAKEOVER") { + if (t[l] != mel || t[mel] == l) continue + r = 1 + } else r = ((l in named) ? 0 : 1) + if (!seen || r > br || (r == br && q[l] >= b)) { seen = 1; br = r; b = q[l]; bl = nm[l]; bu = u[l] } } + if (seen) print bl "@" bu }' +} + +# A lane's HOME repo, from the payload of its own STARTED (or RESUMED) line. +# `-` is a label, not a scope: this is the only thing that says where +# a lane actually lives. +# R20 — and the answer is CANONICAL. A STARTED line records whatever spelling +# that checkout's `origin` had on the day, and the register's own history proves +# those drift (`opensoft/codexFactory` is today `codeXfactory/codexFactory`). +# Every comparison of an object's repository against a home — canon_object's +# `#n`, cross_repo_warn, same_project, who's CROSS-REPO note — resolves BOTH +# sides, and resolving here is what makes that true of all of them at once. +home_of_lane() { + lane_log_exists "$1" || return 1 + hol_h="$(lane_log_events "$1" | awk -v sep="$US" ' + BEGIN { FS = sep } + $3 == "STARTED" || $3 == "RESUMED" { + if (match($8, /home [^ ;]+/)) h = substr($8, RSTART + 5, RLENGTH - 5) + } + END { if (h != "" && h != "unknown") print h; else exit 1 }')" || return 1 + [ -n "$hol_h" ] || return 1 + hol_c="$(alias_lookup "$hol_h" 2>/dev/null || :)" + printf '%s\n' "${hol_c:-$hol_h}" +} + +# `PIN_LOGS` IS THE ONE LISTING'S OWN LIST OF THE PUBLISHED LOGS, exactly as +# `PIN_ARCHIVE` is its archive: `worktree_rows` lists them once, and where that +# succeeded the listing names its lanes from that list and not from a second +# `ls-tree` that could fail after it (the review of #289, SHOULD-1(b)). +PIN_LOGS=0 +PIN_LOGS_TEXT="" +known_lanes() { + if [ -n "$LANES_IDX_DIR" ]; then + while IFS= read -r kl_f; do + [ -n "$kl_f" ] || continue + kl_n="${kl_f##*/}" + case "$kl_n" in README.md) continue ;; esac + printf '%s\n' "${kl_n%.md}" + done < "$LANES_IDX_DIR/logs" + return 0 + fi + if [ "$PIN_LOGS" = 1 ] || have_remote_ref; then + { if [ "$PIN_LOGS" = 1 ]; then printf '%s' "$PIN_LOGS_TEXT" + else git -C "$LANES_REPO" ls-tree --name-only "origin/$LANES_BRANCH" -- "$LANES_LOG_PREFIX" 2>/dev/null + fi; } \ + | while IFS= read -r kl_f; do + [ -n "$kl_f" ] || continue + kl_n="${kl_f##*/}" + case "$kl_n" in README.md) continue ;; esac + printf '%s\n' "${kl_n%.md}" + done + return 0 + fi + while IFS= read -r kl_f; do + [ -n "$kl_f" ] || continue + kl_n="${kl_f##*/}"; printf '%s\n' "${kl_n%.md}" + done <` IS GNU-ONLY, AND THIS FUNCTION IS WHAT STALENESS IS MADE +# OF (A9 Addendum 4, R-A9-11). BSD `date` — macOS's — answers `illegal option +# -- d`, and `2>/dev/null || printf ''` turned that refusal into an EMPTY +# ANSWER rather than an error: `age_of` printed `age unknown` beside every row, +# `older_than_minutes` and `older_than_threshold` returned false for every +# stamp, and the whole of `who`'s idle and stale reporting was silently off on +# a platform this repository's own CI runs. BSD spells the same question +# `-j -f `, so both are asked, GNU first because it is what +# every lane workstation runs. TWO FORMATS, because this estate writes two: +# `utc_now`, `lane-end`'s RELEASED and every log line carry SECONDS, and a +# row's `Started` cell carries MINUTES. GNU reads either from one call; BSD +# must be told which, so it is asked twice. A stamp none of the three can read +# is still the empty string every caller here already tests for. +epoch_of() { + date -u -d "$1" +%s 2>/dev/null || + date -u -j -f '%Y-%m-%dT%H:%M:%SZ' "$1" +%s 2>/dev/null || + date -u -j -f '%Y-%m-%dT%H:%MZ' "$1" +%s 2>/dev/null || + printf '' +} + +# `age_of []`. A CALLER WITH MANY STAMPS PASSES `now` +# ONCE (A11 Addendum 4 ruling 12): `date -u +%s` is a process, and asking the +# clock again for every row of a listing both costs one and lets the rows +# disagree about when "now" was. +age_of() { + ao_t="$(epoch_of "$1")" + if [ -z "$ao_t" ]; then printf 'age unknown'; return 0; fi + ao_now="${2-}"; [ -n "$ao_now" ] || ao_now="$(date -u +%s)" + ao_d=$(( ao_now - ao_t )); [ "$ao_d" -lt 0 ] && ao_d=0 + printf '%dh %02dm' "$((ao_d / 3600))" "$(((ao_d % 3600) / 60))" +} + +lc() { printf '%s' "${1-}" | tr 'A-Z' 'a-z'; } + +# `lc`'s ANSWER WITHOUT A PROCESS, for a loop that asks it of EVERY lane in the +# estate (opensoft/openRepoTools#107). `$(lc …)` is a subshell and a `tr`, and +# the listing's `--prefix` and `--repo` filters made two of them per lane per +# filter: measured on the suite's fixture register (194 rows, 162 logs), 3.2 s +# of one `lanes --prefix` read, for lanes it then filtered out. The mapping is +# `tr 'A-Z' 'a-z'`'s — the twenty-six ASCII capitals and nothing else — spelled +# as twenty-six literal substitutions, so no locale's idea of a range or of a +# case can widen it. It ASSIGNS `LOWER_OUT` and returns, for `table_lookup`'s +# reason: a function read through `$( … )` is the fork this exists to remove. +LOWER_OUT="" +lower_into() { # + LOWER_OUT="${1-}" + case "$LOWER_OUT" in *[ABCDEFGHIJKLMNOPQRSTUVWXYZ]*) : ;; *) return 0 ;; esac + LOWER_OUT="${LOWER_OUT//A/a}"; LOWER_OUT="${LOWER_OUT//B/b}"; LOWER_OUT="${LOWER_OUT//C/c}" + LOWER_OUT="${LOWER_OUT//D/d}"; LOWER_OUT="${LOWER_OUT//E/e}"; LOWER_OUT="${LOWER_OUT//F/f}" + LOWER_OUT="${LOWER_OUT//G/g}"; LOWER_OUT="${LOWER_OUT//H/h}"; LOWER_OUT="${LOWER_OUT//I/i}" + LOWER_OUT="${LOWER_OUT//J/j}"; LOWER_OUT="${LOWER_OUT//K/k}"; LOWER_OUT="${LOWER_OUT//L/l}" + LOWER_OUT="${LOWER_OUT//M/m}"; LOWER_OUT="${LOWER_OUT//N/n}"; LOWER_OUT="${LOWER_OUT//O/o}" + LOWER_OUT="${LOWER_OUT//P/p}"; LOWER_OUT="${LOWER_OUT//Q/q}"; LOWER_OUT="${LOWER_OUT//R/r}" + LOWER_OUT="${LOWER_OUT//S/s}"; LOWER_OUT="${LOWER_OUT//T/t}"; LOWER_OUT="${LOWER_OUT//U/u}" + LOWER_OUT="${LOWER_OUT//V/v}"; LOWER_OUT="${LOWER_OUT//W/w}"; LOWER_OUT="${LOWER_OUT//X/x}" + LOWER_OUT="${LOWER_OUT//Y/y}"; LOWER_OUT="${LOWER_OUT//Z/z}" + return 0 +} + +older_than_minutes() { # + om_t="$(epoch_of "$1")"; [ -n "$om_t" ] || return 1 + [ "$(( $(date -u +%s) - om_t ))" -gt "$(( $2 * 60 ))" ] +} + +older_than_threshold() { + st_t="$(epoch_of "$1")"; [ -n "$st_t" ] || return 1 + [ "$(( $(date -u +%s) - st_t ))" -gt "$((STALE_HOURS * 3600))" ] +} + +# An object is treated as a PR once some lane has written OPENED on it. That +# is the only offline evidence there is, and it is exactly the evidence Rule 1 +# cares about: a claim followed by a PR is not abandoned. +object_is_pr() { + op_o="$1" + state_events | awk -v sep="$US" -v o="$op_o" 'BEGIN{FS=sep} $6 == o && $3 == "OPENED" { f = 1 } END { exit(f ? 0 : 1) }' +} + +# Rule 1's staleness, made checkable. A lane's CLAIMED on an ISSUE is stale +# when it is older than four hours AND that lane has written no later OPENED +# whose `←` payload names the issue. A PR is never stale by this rule — Rule 6 +# governs PRs, with its own thirty minutes. +# "LATER" IS FURTHER DOWN THE SAME FILE (R14). The four hours above is a +# DURATION and stays on the clock, where ±25s is immaterial; this is an ORDER +# between two lines of one append-only log, and it is read off the log. +claim_is_stale() { # + cs_lane="$1"; cs_obj="$2"; cs_utc="$3"; cs_file="${4-}"; cs_line="${5-0}" + older_than_threshold "$cs_utc" || return 1 + object_is_pr "$cs_obj" && return 1 + state_events | awk -v sep="$US" -v l="$cs_lane" -v o="$cs_obj" -v f="$cs_file" -v ln="$cs_line" ' + BEGIN { FS = sep } + tolower($2) == tolower(l) && $3 == "OPENED" && $10 == f && ($11 + 0) > (ln + 0) { + # the `←` payload is space-separated issue keys + n = split($8, a, " ") + for (i = 1; i <= n; i++) if (a[i] == o) { found = 1 } + } + END { exit(found ? 1 : 0) }' +} + +# ------------------------------------------- issue #30: A DEAD LANE'S HOLD +# +# `claim_is_stale` answers Rule 1's own question — is THIS CLAIM old — and on +# purpose it refuses for anything that is not a CLAIMED issue: Rule 6 governs a +# PR's own thirty minutes, and an OPENED, LANDING or WITHDRAWN was never a +# claim to begin with. Neither test answers a DIFFERENT question Rule 1 never +# had a word for: the LANE holding the object is not coming back at all, +# whatever verb its last line on the object used. Measured 2026-09-13 +# (opensoft/openRepoTools#30): lane openRepoProject-1 went silent and was +# retired (`lane-end --retire`, Amendment 6(d)), leaving an OPENED PR and two +# CLAIMED issues behind — `claim --force` refused all three, the verb-check +# refusing the PR and the four-hour clock refusing the issues (a CLAIMED lane +# that later OPENED a PR naming it is deliberately never stale by Rule 1's own +# test, which is exactly backwards for a lane that is dead). The workaround +# was a `release` on the dead lane's behalf, by hand, object by object. +# +# DEAD, HERE, MEANS THE REGISTER SAYS SO, FIRST: the holder's own object log's +# last LANE-KIND line (Amendment 7(b)'s STARTED/PAUSED/RESUMED/ENDED/RETIRED — +# `lane_row_facts`' own "last lane-kind line wins in file order" rule, R14, +# read for one lane rather than for a whole listing) is ENDED or RETIRED. +# PAUSED IS DELIBERATELY NOT DEAD — a swap is a planned, expected stop +# (Amendment 8) and stealing a swapped lane's claims would be exactly the +# collision this protocol exists to prevent — and neither is a log with no +# lane-kind line yet, which cannot hold an object through this path at all +# (`state_events` reads nothing for it either). +# +# AND CONFIRMED, NEVER ASSUMED, SECOND: a register that says RETIRED is not +# proof by itself that nothing is still running under that name — Amendment +# 6(d)'s retire act writes no signal and kills no process, and +# opensoft/openRepoTools#39 is exactly a register saying one thing while a +# duplicate process says another. So the verdict is checked against +# `live_holder` — the ONE liveness implementation this file has, over the same +# published-union-local id set `lanes-edit.sh live-holder` already builds, and +# never a new one — and a lane a live record on THIS workstation still holds is +# refused exactly as an untaken CLAIMED is: "refuse where the holder is live" +# is not a special case here, it is this same rule. A `live_holder` read that +# FAILS is not "confirmed live" (fail closed for the log half, as every other +# reader of this stream does) — but nor is it "confirmed dead": a RETIRED +# verdict this workstation simply cannot check against any records at all is +# HELD BACK exactly as a live one is, because issue #30's fix must never be +# LESS safe than the check it sits beside. STALE UNTIL PR #61 (Copilot round +# 11): this paragraph used to say such a read "is not held back either", +# which described the opposite of the fail-closed rule the code below it +# already enforced — only an ACTUAL, CONFIRMED-EMPTY read (`live_holder` exit +# 8, never a bare rc 0 check) allows the takeover that every other outcome, +# read failures included, withholds. +# +# 0 dead-and-confirmed (`HOLDER_DEAD_VERB` names the verdict), 1 not — refuse +# as before. (This is `holder_is_dead`'s OWN return code, a different space +# from the three `live_holder` answers just above it.) +# +# A LINE WHOSE PAYLOAD OPENS `fork ` IS NEVER THE LANE'S OWN VERB (Copilot +# round 8, PR #61) — the same exclusion `lane_row_facts` already makes (above, +# "A FORK-S RETIRED IS NOT THE LANE-S OWN LAST VERB") and for the identical +# reason: the first build of ruling 8's retire act appended `RETIRED … lane: +# -> fork ; pid ; kind ` to the LANE's own log for a FORK it +# retired, and nothing writes one any more but these logs are append-only, so +# one written under that build is still there. Read as this lane's own last +# line, it says the LANE was retired — backwards for a lane that may be alive +# beside the fork it disowned, and exactly the state a PAUSED (swapped) lane +# would be in if a stray line like this landed after its own last STARTED or +# RESUMED: `claim --force` would read it as ENDED and take over holds a +# planned, expected stop was never meant to surrender — the very collision +# Amendment 8 exists to prevent. +# +# A LOG THAT YIELDED NO LANE-KIND VERDICT AT ALL IS ITS OWN ANSWER TOO +# (Copilot on 05d7889, PR #61). The read used to be one pipeline whose status +# was `awk`'s, so a log `lane_log_events` could not read — two files differing +# only by case on origin, a `git show` that failed, a log no longer there — +# came back as an EMPTY verdict with status 0 and set neither marker below: +# `claim_rescan_hook` then told the operator the log had "moved past the +# terminal line", which nobody had read. `HOLDER_NO_VERDICT` is that case, +# named: the read failed, or it produced no STARTED/PAUSED/RESUMED/ENDED/ +# RETIRED line to judge. It is still `return 1` — fail closed — and only the +# words a caller prints change. +# +# AND THE CONFIRMATION IS PRONOUNCED ONLY FROM INSIDE THE LANE'S LAST BINDING +# (Copilot on 8ce6c9d, PR #61, against Amendment 18(b) as #83 landed it): +# *"Liveness is pronounced only from INSIDE the binding's own `host` and +# `container`, where the pid namespace is the record's: from anywhere else a +# binding is UNKNOWN, never dead."* `live_holder` answering 8 says no session +# record on THIS workstation holds the lane — which proves nothing about a lane +# whose last `STARTED`/`RESUMED` was written on another host or in another +# container, so a terminal log there plus an empty read here would have handed +# its open holds to `--force` on a fact nobody could establish. The binding is +# read off the last such line before the terminal one, with clause (a)'s +# cutover rule (no `host`/`container`/`os` at all is a line from before it, +# matched on the line's own workstation), and judged by `binding_is_here` — +# the one locality rule this file has. Not here, the one exception clause (b) +# carves out still applies: a shared tmux server on which the binding's window +# is GONE is a dead binding (`binding_window_state`) — and then the local +# `live_holder` read below still has to come back empty, because a dead pane +# is not proof that nothing on this workstation still carries the lane +# (Copilot on a52abc6). Anything else is +# `HOLDER_BOUND_ELSEWHERE` (the binding's `host/container`), and refused like +# every other verdict this workstation could not establish. A log with no +# binding line at all keeps the local read, which is all there is to ask. +# +# AND THE IDS THE LOCAL READ IS ASKED ABOUT MUST HAVE BEEN READ +# (opensoft/openRepoTools#67). They are the row's, published-union-local, and +# an unreadable register used to yield the same EMPTY set as a lane with no +# row — which `live_holder` answers 8, so a terminal log on a register nobody +# could read was "confirmed dead" and its holds went to `--force`, even with a +# live session on this workstation still carrying the lane's id. That is +# `HOLDER_REGISTER_UNREADABLE` now, with `HOLDER_TERMINAL_UNKNOWN` beside it so +# every reader that already refuses a liveness read that failed refuses this one +# too; `claim` names it in its own words. +HOLDER_DEAD_VERB="" +HOLDER_LIVE_TERMINAL="" +HOLDER_TERMINAL_UNKNOWN="" +HOLDER_NO_VERDICT="" +HOLDER_BOUND_ELSEWHERE="" +HOLDER_REGISTER_UNREADABLE="" +HOLDER_DEAD_WHY="" +HOLDER_TERMINAL_SEEN="" +holder_is_dead() { # + hid_l="${1-}"; [ -n "$hid_l" ] || return 1 + HOLDER_DEAD_VERB="" + HOLDER_LIVE_TERMINAL="" + HOLDER_TERMINAL_UNKNOWN="" + HOLDER_NO_VERDICT="" + HOLDER_BOUND_ELSEWHERE="" + HOLDER_REGISTER_UNREADABLE="" + HOLDER_DEAD_WHY="no live session on this workstation" + HOLDER_TERMINAL_SEEN="" + hid_rc=0 + hid_ev="$(lane_log_events "$hid_l" 2>/dev/null)" || hid_rc=$? + if [ "$hid_rc" != 0 ]; then + HOLDER_NO_VERDICT=1 + return 1 + fi + hid_verb="$(printf '%s\n' "$hid_ev" | awk -F"$US" ' + ($3=="STARTED"||$3=="PAUSED"||$3=="RESUMED"||$3=="ENDED"||$3=="RETIRED") && substr($8,1,5)!="fork " { v=$3 } + END { print v }')" + case "$hid_verb" in + ENDED|RETIRED) : ;; + "") HOLDER_NO_VERDICT=1; return 1 ;; + *) return 1 ;; + esac + HOLDER_TERMINAL_SEEN="$hid_verb" + # AMENDMENT 18(b) — the last binding, and whether this place may pronounce + # on it (the paragraph above `HOLDER_DEAD_VERB`). + hid_bind="$(printf '%s\n' "$hid_ev" | awk -F"$US" ' + ($3=="STARTED"||$3=="RESUMED") && substr($8,1,5)!="fork " { ws=$5; pay=$8; seen=1 } + END { if (seen) printf "%s%c%s\n", ws, 31, pay }')" + if [ -n "$hid_bind" ]; then + hid_bws="${hid_bind%%"$US"*}"; hid_bpay="${hid_bind#*"$US"}" + hid_bhost="$(payload_subfield "$hid_bpay" host)" + hid_bcont="$(payload_subfield "$hid_bpay" container)" + hid_bos="$(payload_subfield "$hid_bpay" os)" + hid_bwin="$(payload_subfield "$hid_bpay" window all)" + hid_blegacy="" + [ -n "$hid_bhost$hid_bcont$hid_bos" ] || hid_blegacy=legacy + [ -n "$hid_bhost" ] || hid_bhost="$hid_bws" + [ -n "$hid_bcont" ] || hid_bcont=none + if ! binding_is_here "$hid_bhost" "$hid_bcont" "$hid_blegacy"; then + # THE WINDOW-GONE EXCEPTION ADMITS THE BINDING TO THE LOCAL READ BELOW, + # IT DOES NOT REPLACE IT (Copilot on a52abc6, PR #61): a pane gone from + # the shared tmux server says the BINDING is dead, not that nothing on + # this workstation still carries the lane — an orphaned background + # duplicate outlives its pane. So `live_holder` is still asked, and only + # its confirmed-empty 8 lets this answer dead; live or unreadable stays + # a refusal exactly as it is for a binding that is here. + if [ "$(binding_window_state "$hid_bhost" "$hid_bwin" "$hid_blegacy")" != gone ]; then + HOLDER_BOUND_ELSEWHERE="${hid_bhost:-unknown}/${hid_bcont}" + return 1 + fi + HOLDER_DEAD_WHY="its binding's window is gone from this host's tmux, Amendment 18(b), and no live session on this workstation" + fi + fi + # 8 IS AN ANSWER AND 1 IS NOT (#67, the paragraph above `HOLDER_DEAD_VERB`): + # a lane the register gives no transcript uuid goes on to `live_holder` with + # an empty set exactly as before; a register that could not be read stops here. + hid_ids=""; hid_irc=0 + hid_ids="$(session_ids_checked "$hid_l")" || hid_irc=$? + case "$hid_irc" in + 0|8) : ;; + *) HOLDER_REGISTER_UNREADABLE=1; HOLDER_TERMINAL_UNKNOWN="$hid_verb"; return 1 ;; + esac + # THREE ANSWERS, NEVER TWO CONFLATED (Copilot round 1, opensoft/openRepoTools#61): + # `live_holder` is 0 live, 8 read-and-confirmed-nothing, or any other code a + # records tree this workstation could not read at all — and THAT is not + # "confirmed dead" either, it is "not established", exactly as every other + # caller of this one liveness implementation already treats it. Only 8 may + # pass; 0 and every failure both refuse. + live_holder "$hid_l" "$hid_ids" >/dev/null 2>&1; hid_lrc=$? + [ "$hid_lrc" = 8 ] || { + # A CONFIRMED-LIVE TERMINAL LOG IS ITS OWN VERDICT, NOT "NOT ESTABLISHED" + # (Copilot round 13, PR #61): this function's OWN return value stays + # fail-closed exactly as above — only 8 ever lets it answer dead — but a + # caller that reads false here and falls back to Rule 1's ORDINARY + # stale-claim test has no way to tell "this log never terminated" apart + # from "this log terminated and a real session still answers for it", + # and the second is refused on liveness alone wherever else this file + # meets it (`repoK-3`'s own case, `lane-start`'s own refusal). Recorded + # here, for `hid_lrc = 0` (genuinely confirmed live). + # + # AND AN UNREADABLE RECORDS TREE IS NEITHER (Copilot's own "closer look" + # on c82577e, PR #61): `hid_lrc` outside {0, 8} means this workstation + # could not read whether a live session backs the lane up at all — the + # exact reading every OTHER caller of `live_holder` already refuses on + # (the comment three lines up), and silently letting `claim_is_stale` + # answer instead would treat "I could not check" as "checked and clear" + # for the one shape (a terminal log) this file already distrusts enough + # to check in the first place. Recorded so the caller can refuse in + # these words rather than in the confirmed-live ones, which would + # misstate why. + if [ "$hid_lrc" = 0 ]; then + HOLDER_LIVE_TERMINAL="$hid_verb" + else + HOLDER_TERMINAL_UNKNOWN="$hid_verb" + fi + return 1 + } + HOLDER_DEAD_VERB="$hid_verb" + return 0 +} + +# ------------------------------------------------------------- liveness +# +# ONE implementation, here, because `lane-start` and `who` must agree about +# what "live" means — `lane-start` asks for it with the `live-holder` +# subcommand rather than keeping a second copy that can drift. +# +# LIVE iff a session record ON THIS WORKSTATION carries one of the row's +# transcript uuids, its `status` is not one of {ended, exited, dead, stopped}, +# its pid is alive, and `/proc//stat` field 22 still equals the +# `procStart` the record wrote down. + +# Every session record on this workstation, one path per line. +# +# R22 — AND IT SAYS WHETHER IT COULD READ THEM. Returns 0 when every records +# tree that EXISTS was listed without error, and 1 when one existed and could +# not be — a permissions or IO fault, which is not the same answer as "no record +# holds this lane" and must never be reported as one. A tree that is simply +# absent is not a failure: a workstation may have only one of the two. +SESSION_FILES_ERR="" +session_files() { + sf_rc=0; sf_d=""; sf_err="" + SESSION_FILES_ERR="" + sf_err="$(mktemp "${TMPDIR:-/tmp}/lanes-edit-sf.XXXXXX" 2>/dev/null || printf '')" + if [ -z "$sf_err" ]; then + SESSION_FILES_ERR="could not create a temporary file under ${TMPDIR:-/tmp}" + return 1 + fi + # Team profiles sit two levels down (profiles////sessions/), + # so that one is a -path find and not a one-level glob. + for sf_d in "$HOME/.claude-profiles/profiles" "$HOME/.claude/sessions"; do + [ -e "$sf_d" ] || continue + case "$sf_d" in + */sessions) find "$sf_d" -maxdepth 1 -name '*.json' -type f 2>>"$sf_err" || sf_rc=1 ;; + *) find "$sf_d" -path '*/sessions/*.json' -type f 2>>"$sf_err" || sf_rc=1 ;; + esac + done + if [ -s "$sf_err" ]; then + SESSION_FILES_ERR="$(LC_ALL=C tr '\n' ';' < "$sf_err" | LC_ALL=C cut -c1-300)" + sf_rc=1 + fi + rm -f -- "$sf_err" + return "$sf_rc" +} + +jstr() { printf '%s' "$1" | grep -o "\"$2\":\"[^\"]*\"" | head -n1 | sed 's/^.*":"//; s/"$//'; } +jnum() { printf '%s' "$1" | grep -o "\"$2\":[0-9][0-9]*" | head -n1 | sed 's/^.*://'; } + +# ------------------------------------------------- A11 Addendum 4 ruling 12: +# ONE PASS OVER THE SESSION RECORDS, FOR THE WHOLE PROCESS +# +# *"Decision 6's `lanes` gets a stated bar — it answers in about a second on +# this estate — and the per-lane fan-out is what changes to meet it."* +# +# WHERE THE TIME WENT, measured on a copy of the live register (46 rows, 15 +# logs) before any of this was written: `lanes` took 14 m 30 s wall and ~23 +# CPU-minutes. Not the register, and not the logs — a `git show` of the 1.1 MB +# register is 11 ms and the fifteen logs are one cached pass. It was THIS: 564 +# session records on this workstation, each read with `cat` and then four or +# five `jstr`/`jnum` calls that are FOUR PROCESSES EACH (`printf | grep | head | +# sed`) — about twenty processes per record, eleven thousand per scan — and both +# scans were rebuilt FOR EVERY LANE, because `live_session_ids` and `fork_map` +# cached into a VARIABLE and every caller invoked them inside `$( … )`, which is +# a subshell whose variables die with it. +# +# So: the parse becomes ONE awk over every record file, and the caches become +# FILES, which a subshell's build leaves behind for its parent. +# +# `jstr` and `jnum` ARE REPRODUCED HERE RATHER THAN CALLED, and the reproduction +# is exact: `jstr` is the first `"key":"…"` whose value holds no `"`, `jnum` the +# first `"key":` followed immediately by a digit. Both are `grep -o … | head -n1` +# on the whole blob, so both take the FIRST occurrence and neither is anchored. +# A record is read the same way by either path, and `record_is_live` still makes +# the liveness decision in shell, on the fields this hands it. +SESSION_RECORD_AWK=' +function jstr(s, k, r, i, v) { + r = "\"" k "\":\"" + i = index(s, r); if (i == 0) return "" + v = substr(s, i + length(r)) + i = index(v, "\""); if (i == 0) return "" + return substr(v, 1, i - 1) +} +function jnum(s, k, r, i, v, rest) { + r = "\"" k "\":" + rest = s + while ((i = index(rest, r)) > 0) { + v = substr(rest, i + length(r)) + if (v ~ /^[0-9]/) { match(v, /^[0-9]+/); return substr(v, 1, RLENGTH) } + rest = substr(rest, i + length(r)) + } + return "" +} +function emit( ) { + if (f == "") return + printf "%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s\n", f, sep, + jstr(blob, "sessionId"), sep, jstr(blob, "tmux"), sep, jstr(blob, "name"), sep, + jnum(blob, "pid"), sep, jstr(blob, "kind"), sep, jstr(blob, "cwd"), sep, + jstr(blob, "status"), sep, jstr(blob, "procStart") +} +FNR == 1 { emit(); f = FILENAME; blob = "" } +{ blob = blob $0 } +END { emit() }' + +# A PER-PROCESS FILE CACHE. `$( … )` is a subshell, so a variable set by a +# builder called inside one is gone the moment it answers; a file is not. +# Named beside the events cache so `cleanup`'s `rm -f -- "$SE_CACHE_FILE".*` +# already takes them, and cleared by `log_sync` with everything else it moves. +# +# SPELLED AS A PARAMETER EXPANSION AND NOT A FUNCTION, because a function called +# as `$(cache_path register)` is a FORK — and this is reached on the per-lane +# path the ruling exists to take the forks out of. `${SE_CACHE_FILE:+…}` is the +# shell's own, costs nothing, and yields the empty string where there is no +# cache file at all, which is the one case every caller already tests for. + +# Every session record on this workstation, parsed once: +# +session_records() { + sr_c="${SE_CACHE_FILE:+$SE_CACHE_FILE.records}" + if [ -n "$sr_c" ] && [ -f "$sr_c" ]; then cat -- "$sr_c"; return 0; fi + # AND A TREE THAT COULD NOT BE READ IS NOT A WORKSTATION WITH NO SESSIONS + # (#26, the review of `37632b1`, `lanes-edit.sh:2008`). `session_files` sets + # `SESSION_FILES_ERR` and returns 1 for exactly that case — the three callers + # that read it DIRECTLY refuse on it, and say so where they do — and this one + # read it through `|| :` inside a `$( )`, which discards the status and the + # message with the subshell. The empty answer was then CACHED for the life of + # the process, so every consumer after it was told the same untrue thing. The + # status decides here and NOTHING IS WRITTEN to the cache on it: a cache of a + # failure is a failure nobody can see. + sr_files=""; sr_frc=0 + sr_files="$(session_files 2>/dev/null)" || sr_frc=$? + [ "$sr_frc" = 0 ] || return 1 + sr_t="" + [ -n "$sr_c" ] && sr_t="$sr_c.${BASHPID:-$$}" + if [ -z "$sr_files" ]; then + [ -n "$sr_t" ] && { : > "$sr_t"; mv -f -- "$sr_t" "$sr_c" 2>/dev/null || rm -f -- "$sr_t"; } + return 0 + fi + # One awk, however many files — `awk` takes them all on its command line and + # `FILENAME` keeps each record attributable. The same shape `log_events` uses + # for the lane logs, for the same reason. + sr_arr=() + while IFS= read -r sr_f; do [ -n "$sr_f" ] && sr_arr+=("$sr_f"); done < "$sr_t"; mv -f -- "$sr_t" "$sr_c" 2>/dev/null || rm -f -- "$sr_t"; } + return 0 + fi + if [ -n "$sr_t" ]; then + awk -v sep="$US" "$SESSION_RECORD_AWK" "${sr_arr[@]}" > "$sr_t" 2>/dev/null + mv -f -- "$sr_t" "$sr_c" 2>/dev/null || { cat -- "$sr_t"; rm -f -- "$sr_t"; return 0; } + cat -- "$sr_c" + else + awk -v sep="$US" "$SESSION_RECORD_AWK" "${sr_arr[@]}" 2>/dev/null + fi + return 0 +} + +pid_alive() { + local pid="$1" want="$2" statline rest + [ -n "$pid" ] || return 1 + kill -0 "$pid" 2>/dev/null || return 1 + [ -n "$want" ] || return 0 + [ -r "/proc/$pid/stat" ] || return 0 + # `read` AND NOT `$(cat …)`, WHICH IS A FORK PER RECORD (A11 Addendum 4 + # ruling 12). This runs once for every session record on the workstation — + # 564 of them here — and `lanes` asked about every record for every lane, so + # this one substitution was ~26,000 processes for one listing. A builtin read + # of a one-line file is the same answer. + statline="" + read -r statline < "/proc/$pid/stat" 2>/dev/null || statline="" + rest="${statline##*) }" + # shellcheck disable=SC2086 + set -- $rest + [ "$#" -ge 20 ] || return 0 + [ "${20}" = "$want" ] +} + +# A session record's `name` is EVIDENCE ABOUT ANOTHER LANE only when a person +# or a `--name` set it. The values real records carry on this estate are: +# +# derived the harness named the window after its working directory +# auto the harness named it without being told to +# user a person typed `/rename`, or `--name` was passed +# peer another session in the mesh set it +# +# EXPLICIT is {user, peer} — the two a person or `--name` produces. A record +# with any other value, or with none at all, says nothing either way about +# which lane it is, and is therefore NOT read as a denial. +# +# This is a fix, not a preference. On 2026-09-11 the orchestrator's own record +# read `name: openrepoproject-63, nameSource: derived` while it held lane +# openRepoProject-1 — pid alive, procStart matching, status busy — and the old +# filter skipped it on the name alone, so a dry run reported "no live session +# holds openRepoProject-1" and a second window would not have been refused. +# 274 of this estate's 341 records carry `derived`. +EXPLICIT_NAME_SOURCES="user peer" +name_is_explicit() { + case " $EXPLICIT_NAME_SOURCES " in *" ${1:-} "*) return 0 ;; esac + return 1 +} + +# The three tests every record answers, wherever it was found: a status that is +# not one of {ended, exited, dead, stopped}, a pid that is alive, and a +# `/proc//stat` field 22 still equal to the `procStart` the record wrote +# down — so a recycled pid cannot hold a name. `live_holder` adds the two that +# are about a LANE (the row's ids, and the nameSource rule); `window_session` +# adds the one that is about a WINDOW. One copy of the three, because two would +# drift and this is the check that decides whether a name may be taken. +record_is_live() { # + record_fields_are_live "$(jstr "$1" status)" "$(jnum "$1" pid)" "$(jstr "$1" procStart)" +} +# THE SAME THREE TESTS, ON FIELDS ALREADY IN HAND (ruling 12). `session_records` +# parses every record once; re-serialising its fields back into a blob so this +# could re-parse them would be the fork storm the one pass exists to remove. +# ONE copy of the three tests, because two would drift and this is the check +# that decides whether a name may be taken. +record_fields_are_live() { # + case "${1-}" in ended|exited|dead|stopped) return 1 ;; esac + pid_alive "${2-}" "${3-}" +} + +# ------------------------------------- AMENDMENT 8, ruling (g): WHOSE session +# +# Three facts about this estate's records, every one of them observed on +# 2026-09-12 while `lane-start` was refusing the very window that held the lane: +# +# 1. THE HARNESS EXPORTS `CLAUDE_CODE_SESSION_ID` into every shell a session +# runs — so a `lane-start` that a session runs already knows its own +# transcript id without asking the filesystem anything. That is the +# cheapest and the most certain test there is, and it comes first. +# 2. ONE SESSION WRITES MORE THAN ONE RECORD. Beside the interactive process +# in the pane the harness runs a companion: `kind: bg`, no `tmux`, no +# `nameSource`, its own pid, and THE SAME `sessionId`. Records that share a +# `sessionId` are one session, not a queue of rival holders, and there is +# no contest between them to win. +# 3. A RECORD MAY CARRY NO `tmux` AT ALL. The pane's interactive record +# usually has one, the companion never does, and the harness has been seen +# to write none for a process plainly in a window. "No target" is not "no +# window": it is a missing observation, and the process tree holds the +# answer the record failed to write down. +# +# What those three produced: `live_holder` returned the COMPANION — its +# `sessionId` matched the row, its pid was alive, and carrying no `nameSource` +# it survived the name test — reported its target as `none`, and `lane-start` +# read "not this window" and refused the session that was running the command: +# +# lane openRepoProject-1 is live in session c5701b54… (tmux none); +# take openRepoProject-2 or resume that window +# +# The orphaned idle holder from the PREVIOUS profile was a real find and was +# correctly retired under Amendment 6(d); this one was the same shape read +# wrongly. The difference between them is not recency and never was — it is +# whether the process is in THIS pane's tree. + +# A `kind: bg` record is a COMPANION: never a holder, never a rival, skipped by +# every read that asks who holds a lane or what is in a window. Only +# `interactive` records hold a lane; a record from a harness too old to say +# carries no `kind` at all and is read as interactive, because that is the only +# thing those harnesses ever wrote. +record_is_session() { # + record_fields_are_session "$(jstr "$1" kind)" +} +record_fields_are_session() { # + case "${1-}" in + ''|interactive) return 0 ;; + *) return 1 ;; + esac +} + +# THIS shell's own window and pane, asked of tmux and never guessed. Both are +# empty outside tmux, and an empty answer makes every test below fail SHUT — so +# a caller with no tmux behaves exactly as it did before Amendment 8. Cached +# because `who` asks about every lane in the register and this is two forks. +LANES_HERE_CTX=0 +LANES_THIS_WINDOW="" +LANES_PANE_PID="" +here_context() { + [ "$LANES_HERE_CTX" = 1 ] && return 0 + LANES_HERE_CTX=1 + [ -n "${TMUX:-}" ] || return 0 + command -v tmux >/dev/null 2>&1 || return 0 + LANES_THIS_WINDOW="$(tmux display-message -p '#{session_name}:#{window_id}' 2>/dev/null || :)" + LANES_PANE_PID="$(tmux display-message -p '#{pane_pid}' 2>/dev/null || :)" + case "$LANES_PANE_PID" in *[!0-9]*) LANES_PANE_PID="" ;; esac + return 0 +} + +# pid_under — is the ancestor itself, or below it? +# +# `/proc//stat` is ` () …`, and a comm may hold +# spaces and brackets, so the parse starts after the LAST `) ` — the same cut +# `pid_alive` makes for field 22. The walk stops at pid 1, at an entry it cannot +# read (a process it cannot see is not in this pane), and at 64 steps, so a +# /proc that lies about parentage cannot spin it. +pid_under() { # + pu_p="${1-}"; pu_anc="${2-}"; pu_i=0 + [ -n "$pu_p" ] && [ -n "$pu_anc" ] || return 1 + case "$pu_anc" in *[!0-9]*) return 1 ;; esac + while [ "$pu_i" -lt 64 ]; do + case "$pu_p" in ''|*[!0-9]*) return 1 ;; esac + [ "$pu_p" = "$pu_anc" ] && return 0 + [ "$pu_p" -gt 1 ] 2>/dev/null || return 1 + [ -r "/proc/$pu_p/stat" ] || return 1 + pu_rest="$(cat "/proc/$pu_p/stat" 2>/dev/null || :)" + [ -n "$pu_rest" ] || return 1 + pu_rest="${pu_rest##*) }" + pu_p="$(printf '%s' "$pu_rest" | cut -d' ' -f2)" + pu_i=$((pu_i + 1)) + done + return 1 +} + +# record_is_here — is this record THIS window's own session? The ruling's +# order, cheapest and most certain first: +# 1. its `sessionId` is the one the harness exported into this very shell; +# 2. its `tmux` target names this window — the FAST PATH, and only a fast +# path: a record without one is not thereby somewhere else; +# 3. its pid is this pane's process, or below it. +record_is_here() { # + here_context + rih_sid="$(jstr "$1" sessionId)" + if [ -n "${CLAUDE_CODE_SESSION_ID:-}" ] && [ -n "$rih_sid" ] \ + && [ "$rih_sid" = "$CLAUDE_CODE_SESSION_ID" ]; then return 0; fi + rih_t="$(jstr "$1" tmux)" + if [ -n "$rih_t" ] && [ -n "$LANES_THIS_WINDOW" ] \ + && [ "${rih_t%.*}" = "$LANES_THIS_WINDOW" ]; then return 0; fi + pid_under "$(jnum "$1" pid)" "$LANES_PANE_PID" +} + +# live_holder [] +# +# R22 — IT FAILS CLOSED AT THE SOURCE. Three answers, and they are distinct: +# 0 a live record holds the lane (the row is printed) +# 8 the records were READ, and none of them does +# 1 the records could not be read — a permissions or IO fault +# +# AND ON 0 IT SAYS WHOSE (Amendment 8, ruling (g)). The fifth field is the +# verdict — `here`, `elsewhere` or `orphan` — because the caller that has to act +# on it cannot work it out from the `tmux` column: a record with no target is +# not a record in no window, and `lane-start` refusing on that string is what +# refused this lane its own window. `here` beats `elsewhere` beats `orphan`, and +# a record with no target whose SESSION also wrote a windowed record is that +# same session seen twice, not a second holder — it is dropped, never ranked. +# `lane-start` renames a window on 8 and REFUSES on anything else, so collapsing +# a failed read into 8 is exactly how a running lane loses its address: the +# rename mints ` (2)` (AGENTS.md rule 7). The first version returned 1 for +# both, which is the same fault one layer up; hardening the CALLER left this +# source with no way to say "I could not read". +live_holder() { + local lane="$1" ids="${2-}" all="${3-}" pats=() f blob pid name status target sid base src + local lh_files lh_match lh_err kindv verdict c c_sid c_tgt c_name c_pid c_v + local lh_bg="" lh_windowed="" lh_here="" lh_here_tgt="" lh_else="" lh_orph="" lh_bres="" + local cands=() + SESSION_FILES_ERR="" + [ -n "$ids" ] || ids="$(session_ids_of_lane "$lane" 2>/dev/null || :)" + # A row with no transcript uuid in it is an ANSWER: nothing recorded can be + # live. It is not a failed read. + [ -n "$ids" ] || return 8 + for sid in $ids; do pats+=(-e "\"sessionId\":\"$sid\""); done + [ "${#pats[@]}" -gt 0 ] || return 8 + lh_files="$(mktemp "${TMPDIR:-/tmp}/lanes-edit-lf.XXXXXX" 2>/dev/null || printf '')" + lh_match="$(mktemp "${TMPDIR:-/tmp}/lanes-edit-lm.XXXXXX" 2>/dev/null || printf '')" + lh_err="$(mktemp "${TMPDIR:-/tmp}/lanes-edit-le.XXXXXX" 2>/dev/null || printf '')" + if [ -z "$lh_files" ] || [ -z "$lh_match" ] || [ -z "$lh_err" ]; then + rm -f -- "$lh_files" "$lh_match" "$lh_err" 2>/dev/null || : + SESSION_FILES_ERR="could not create a temporary file under ${TMPDIR:-/tmp}" + return 1 + fi + # NOT `$( )`: session_files sets SESSION_FILES_ERR, and a subshell would keep + # the reason for the failure to itself. + if ! session_files > "$lh_files"; then + rm -f -- "$lh_files" "$lh_match" "$lh_err" + return 1 + fi + if [ ! -s "$lh_files" ]; then + rm -f -- "$lh_files" "$lh_match" "$lh_err" + return 8 # this workstation keeps no records at all + fi + # `xargs -r` IS GNU-ONLY and was dead weight: the `[ ! -s ]` guard above + # returns before this line when there is no record to search at all, which + # is the only thing `-r` would have caught (A9 Addendum 4, R-A9-11). The + # `tr`s read arbitrary bytes — a path, and grep's own words about it — so + # they read them as bytes: BSD `tr` answers `Illegal byte sequence` for a + # multibyte character in a UTF-8 locale and prints NOTHING, which would turn + # a record that cannot be read into a reason nobody can read either. + LC_ALL=C tr '\n' '\0' < "$lh_files" | xargs -0 grep -l -F "${pats[@]}" > "$lh_match" 2>"$lh_err" || : + if [ -s "$lh_err" ]; then # a record that exists and cannot be read + SESSION_FILES_ERR="$(LC_ALL=C tr '\n' ';' < "$lh_err" | LC_ALL=C cut -c1-300)" + rm -f -- "$lh_files" "$lh_match" "$lh_err" + return 1 + fi + rm -f -- "$lh_files" "$lh_err" + # PASS 1 — every live record the row's ids match, classified. Not the first + # one found: the first one found is a directory order, and on 2026-09-12 the + # directory order put the companion in front of the session at the keyboard. + while IFS= read -r f; do + [ -n "$f" ] || continue + blob="$(cat -- "$f" 2>/dev/null || :)" + [ -n "$blob" ] || continue + record_is_live "$blob" || continue + sid="$(jstr "$blob" sessionId)" + pid="$(jnum "$blob" pid)" + name="$(jstr "$blob" name)" + src="$(jstr "$blob" nameSource)" + target="$(jstr "$blob" tmux)" + # A COMPANION IS NOT A HOLDER. It is reported, on stderr, so that a person + # who is looking at a `(tmux none)` record can see why it was not obeyed. + if ! record_is_session "$blob"; then + kindv="$(jstr "$blob" kind)" + lh_bg="${lh_bg}${lh_bg:+, }pid ${pid:-unknown} (kind ${kindv:-none}, session ${sid:-unknown})" + continue + fi + base="${name% (*)}" + # `tr`, not `${x,,}`: openRepoTools' CI parses every shipped bash file with + # macOS' /bin/bash 3.2, where `${x,,}` is a SYNTAX error and not a portable + # lowercase (.github/workflows/tests.yml — that job names this very + # construction as its example). Amendment 9's adoption act 3, obligation 4. + base_lc="$(printf '%s' "$base" | tr '[:upper:]' '[:lower:]')" + lane_lc="$(printf '%s' "$lane" | tr '[:upper:]' '[:lower:]')" + if [ -n "$base" ] && [ "$base_lc" != "$lane_lc" ] && name_is_explicit "$src"; then + # AMENDMENT 16(e) — A NAME THIS LANE USED TO HAVE IS THIS LANE. The skip + # above is Amendment 8's: a session a PERSON named for ANOTHER lane is not + # this one's holder. After a rename the lane's own session still carries + # its FORMER name — the `/rename` is what clause (f) is for and it lands at + # the lane's next prompt, not before — and read byte for byte that record + # is "another lane's", so the lane's own live session stopped being its + # holder the instant the row moved. That would refuse the rename's own + # window its `/rename`, and tell `who` the lane is NOT LIVE while it is. + # Resolved through the same seat every other name goes through; anything + # that resolves elsewhere is still skipped, which is Amendment 8's rule + # unchanged. + # AND THE RESOLVER'S OWN STATUS IS KEPT (Copilot round 4). Piped into + # `grep | head || :` it was thrown away, so an unreadable alias table + # answered EMPTY here, the record was skipped, and `live_holder` returned + # 8 — "no live session holds it" — about a lane that is running. That is + # the read `lane-start` renames a window over. + lh_brc=0 + lh_bres="$(rows_named_ci_alias "$base" 2>/dev/null)" || lh_brc=$? + if [ "$lh_brc" != 0 ]; then + SESSION_FILES_ERR="${LANES_ALIASES_PATH:-lanes/aliases.tsv} could not be read ($(lane_alias_err)), so whether the session named '$base' carries a FORMER name of lane $lane could not be established (Amendment 16(e))" + rm -f -- "$lh_match" + return 1 + fi + lh_bres="$(printf '%s\n' "$lh_bres" | grep . | head -n1 || :)" + if [ -z "$lh_bres" ] || [ "$(lc "$lh_bres")" != "$lane_lc" ]; then continue; fi + fi + if record_is_here "$blob"; then verdict=here + elif [ -n "$target" ]; then verdict=elsewhere + else verdict=orphan + fi + [ -n "$target" ] && lh_windowed="${lh_windowed}${sid} +" + cands+=("$(printf '%s%s%s%s%s%s%s%s%s' "$sid" "$US" "${target:-none}" "$US" "${name:-none}" "$US" "${pid:-unknown}" "$US" "$verdict")") + done < "$lh_match" + rm -f -- "$lh_match" + [ -n "$lh_bg" ] && note "lane $lane: companion records, which are never holders: $lh_bg" + + # The restart observer needs every process, while live-holder keeps its + # existing preferred-record contract. Multiple witnesses of one PID are + # one holder; two PIDs sharing a transcript are still two holders. + if [ "$all" = all ]; then + [ "${#cands[@]}" -gt 0 ] || return 8 + printf '%s\n' "${cands[@]}" | awk -F'\037' '!seen[$1 FS $4]++' + return 0 + fi + + # PASS 2 — the pick. `here` first, and among two records of one session the + # WINDOWED one is the better witness of it; then a genuine rival in another + # window; then an orphan, and only one whose session wrote no windowed record + # at all, because the other kind is this same session seen twice. + for c in ${cands[@]+"${cands[@]}"}; do + IFS="$US" read -r c_sid c_tgt c_name c_pid c_v <<<"$c" + case "$c_v" in + here) + if [ -z "$lh_here" ] || { [ "$lh_here_tgt" = none ] && [ "$c_tgt" != none ]; }; then + lh_here="$c"; lh_here_tgt="$c_tgt" + fi ;; + elsewhere) [ -n "$lh_else" ] || lh_else="$c" ;; + orphan) + printf '%s' "$lh_windowed" | grep -qx -F -- "$c_sid" && continue + [ -n "$lh_orph" ] || lh_orph="$c" ;; + esac + done + if [ -n "$lh_here" ]; then printf '%s\n' "$lh_here"; return 0 + elif [ -n "$lh_else" ]; then printf '%s\n' "$lh_else"; return 0 + elif [ -n "$lh_orph" ]; then printf '%s\n' "$lh_orph"; return 0 + fi + return 8 +} + +# -------------------------------- AMENDMENT 8(f), R-A8-6: the ORPHANED HOLDERS +# +# A row's session cell is a HISTORY, and its EARLIER ids are history rather than +# alternatives — but a live process can still be holding one, which is Amendment +# 6(d)'s orphan and, on this lane, the reason the `/resume` picker offered two +# transcripts of which neither was the lane. `live_holder` answers about the +# lane's holder, one record, picked; this answers about ALL the earlier ids, and +# it answers to be READ. +# +# IT NAMES THEM AND DOES NOTHING ELSE. Retiring is `kill `, printed by the +# caller and run by a person: ending somebody's process is not a boundary +# script's act — an idle background session is exactly the shape of thing that +# turns out to be somebody's long-running job — and clause (f) rules it the +# operator's, for the same reason clause (a)'s step 3 pushes nobody's work for +# them. +# +# IDLE means a LIVE record (Amendment 6's three tests: a status that is not +# ended, a pid that is alive, a `procStart` that still matches) which is NOT a +# session in a window: a `kind: bg` companion, or a record carrying no `tmux` +# target at all. A live INTERACTIVE record with a window is not an orphan, it is +# a rival, and `live_holder` is the read that answers about those. +# +# One line per record, ``. +# Exit 0 with rows, 8 with none, 1 where the records could not be read. +idle_holders() { # + ih_lane="${1-}"; ih_ids=""; ih_last=""; ih_earlier=""; ih_out="" + ih_files=""; ih_match=""; ih_err=""; ih_f=""; ih_blob="" + ih_sid=""; ih_pid=""; ih_kind=""; ih_tgt="" + SESSION_FILES_ERR="" + [ -n "$ih_lane" ] || return 8 + ih_ids="$(session_ids_of_lane "$ih_lane" 2>/dev/null || :)" + [ -n "$ih_ids" ] || return 8 + ih_last="$(printf '%s\n' "$ih_ids" | tail -n1)" + ih_earlier="$(printf '%s\n' "$ih_ids" | grep -vx -F -- "$ih_last" || :)" + [ -n "$ih_earlier" ] || return 8 + ih_files="$(mktemp "${TMPDIR:-/tmp}/lanes-edit-if.XXXXXX" 2>/dev/null || printf '')" + ih_match="$(mktemp "${TMPDIR:-/tmp}/lanes-edit-im.XXXXXX" 2>/dev/null || printf '')" + ih_err="$(mktemp "${TMPDIR:-/tmp}/lanes-edit-ie.XXXXXX" 2>/dev/null || printf '')" + if [ -z "$ih_files" ] || [ -z "$ih_match" ] || [ -z "$ih_err" ]; then + rm -f -- "$ih_files" "$ih_match" "$ih_err" 2>/dev/null || : + SESSION_FILES_ERR="could not create a temporary file under ${TMPDIR:-/tmp}" + return 1 + fi + if ! session_files > "$ih_files"; then + rm -f -- "$ih_files" "$ih_match" "$ih_err" + return 1 + fi + if [ ! -s "$ih_files" ]; then + rm -f -- "$ih_files" "$ih_match" "$ih_err" + return 8 + fi + ih_pats=() + for ih_sid in $ih_earlier; do ih_pats+=(-e "\"sessionId\":\"$ih_sid\""); done + # `xargs -r` and the locale, for the reason `live_holder` gives above. + LC_ALL=C tr '\n' '\0' < "$ih_files" | xargs -0 grep -l -F "${ih_pats[@]}" > "$ih_match" 2>"$ih_err" || : + if [ -s "$ih_err" ]; then + SESSION_FILES_ERR="$(LC_ALL=C tr '\n' ';' < "$ih_err" | LC_ALL=C cut -c1-300)" + rm -f -- "$ih_files" "$ih_match" "$ih_err" + return 1 + fi + rm -f -- "$ih_files" "$ih_err" + while IFS= read -r ih_f; do + [ -n "$ih_f" ] || continue + ih_blob="$(cat -- "$ih_f" 2>/dev/null || :)" + [ -n "$ih_blob" ] || continue + record_is_live "$ih_blob" || continue + ih_sid="$(jstr "$ih_blob" sessionId)" + ih_tgt="$(jstr "$ih_blob" tmux)" + ih_kind="$(jstr "$ih_blob" kind)" + # a session IN a window is not an orphan — it is a rival, and live_holder's + # question, not this one's. + if record_is_session "$ih_blob" && [ -n "$ih_tgt" ]; then continue; fi + ih_pid="$(jnum "$ih_blob" pid)" + ih_out="${ih_out}${ih_sid}\t${ih_pid:-unknown}\t${ih_kind:-none}\t$(record_profile "$ih_f") +" + done < "$ih_match" + rm -f -- "$ih_match" + [ -n "$ih_out" ] || return 8 + printf '%b' "$ih_out" + return 0 +} + +# ---------------------------------------------- the session in a tmux WINDOW +# +# AMENDMENT 8. `live_holder` asks "is any session this ROW names alive"; this +# asks "which live session is in THIS WINDOW", and the two answers differ in +# exactly the case Amendment 8 exists for. The harness mints a new transcript +# uuid without anybody acting — a `/clear` does it (Amendment 6, fact 4), and so +# did the 2026-09-12 usage reset that carried this lane's conversation into +# `4a91f1dc…` while its row still ended on `09dd34d1…`. That id is in no row, so +# `live_holder` cannot see it and answers 8, "this lane is parked", about the +# conversation sitting in the window it was asked about. Keyed on the WINDOW +# instead, the record is found, and `lane-start` appends its uuid to the cell +# before it stamps — which is what makes the next resume land in the right +# conversation. + +# The profile a record belongs to, read off its own path — never guessed from +# the environment, because the process asking may be in another profile: +# ~/.claude-profiles/profiles////sessions/.json +# ~/.claude/sessions/.json -> default +record_profile() { + rpf_d="${1%/*}"; rpf_d="${rpf_d%/sessions}"; rpf_n="${rpf_d##*/}" + case "$rpf_n" in .claude|claude|"") printf 'default\n' ;; *) printf '%s\n' "$rpf_n" ;; esac +} + +# window_session — the LIVE record whose own `tmux` field names +# that window. The target is `:`, which is what +# `tmux display-message -p '#{session_name}:#{window_id}'` prints and what the +# record's `tmux` field carries before its `.%` suffix. +# +# NO NAME TEST. `live_holder`'s fifth test skips a record explicitly named for +# another lane, because there the question is "does this record hold that lane". +# Here the question is "what is running in this window", and a window holds one +# interactive session whatever it is called: the record's name is REPORTED, so +# the caller can put it in front of a person, and decides nothing. +# +# R22 — three answers, never two of them conflated: 0 with the record, 8 when +# the records were READ and none is in that window, 1 when they could not be +# read at all. +# WHERE SEVERAL LIVE RECORDS NAME ONE WINDOW, IDENTITY DECIDES — NOT RECENCY +# (Amendment 8, ruling (g); this replaces the first version's "the most recently +# updated one wins", which was wrong in the case it was written for). +# +# tier 3 its `sessionId` is `$CLAUDE_CODE_SESSION_ID`, which the harness +# exported into this very shell — when the window asked about is this +# one. Nothing beats a session naming itself. +# tier 2 its pid is this pane's process or below it — again only for this +# window. This is what lets a record with NO `tmux` be found: the +# harness does not always write the target down, and a record without +# one is not thereby in no window. +# tier 1 its `tmux` field names the window. The fast path, and the only test +# available for a window that is not this one. +# +# `updatedAt` breaks a tie WITHIN a tier and nowhere else, so the answer never +# depends on directory order. It cannot be the rule itself: it is a LIVENESS +# HEARTBEAT, and the idle companion beside a working session heartbeats later +# than the session does — in the 2026-09-12 records the companion's `updatedAt` +# was 1789235975177 against the interactive record's 1789235958137, so "the +# newest wins" picks precisely the record that is not in the window. Two records +# of ONE session are not a contest to win at all: the windowed one represents +# the session, and `record_is_session` has already dropped the companion. +window_session() { + local target="$1" f blob sid tmuxv name pid upd best_upd best_out wsn_files + local tier best_tier ws_is_self ws_pane + SESSION_FILES_ERR="" + [ -n "$target" ] || return 8 + # Tiers 2 and 3 are about THIS pane, so they apply only when the window asked + # about is the one this process is in. Asked about somebody else's window, + # this read is exactly the `tmux`-field match it always was. + here_context + ws_is_self=0; ws_pane="" + if [ -n "$LANES_THIS_WINDOW" ] && [ "$LANES_THIS_WINDOW" = "$target" ]; then + ws_is_self=1; ws_pane="$LANES_PANE_PID" + fi + wsn_files="$(mktemp "${TMPDIR:-/tmp}/lanes-edit-ws.XXXXXX" 2>/dev/null || printf '')" + if [ -z "$wsn_files" ]; then + SESSION_FILES_ERR="could not create a temporary file under ${TMPDIR:-/tmp}" + return 1 + fi + # NOT `$( )`: session_files sets SESSION_FILES_ERR, and a subshell would keep + # the reason for the failure to itself. + if ! session_files > "$wsn_files"; then rm -f -- "$wsn_files"; return 1; fi + best_upd=-1; best_tier=0; best_out="" + while IFS= read -r f; do + [ -n "$f" ] || continue + blob="$(cat -- "$f" 2>/dev/null || :)" + [ -n "$blob" ] || continue + record_is_live "$blob" || continue + # A COMPANION IS NOT WHAT IS IN A WINDOW. `kind: bg` carries the interactive + # record's own `sessionId`, so admitting it here would let the SAME uuid be + # found by the wrong process — and would re-open the bug the moment a + # harness starts writing a target on to companions. + record_is_session "$blob" || continue + sid="$(jstr "$blob" sessionId)" + tmuxv="$(jstr "$blob" tmux)" + tier=0 + if [ "$ws_is_self" = 1 ] && [ -n "${CLAUDE_CODE_SESSION_ID:-}" ] \ + && [ -n "$sid" ] && [ "$sid" = "$CLAUDE_CODE_SESSION_ID" ]; then + tier=3 + elif [ -n "$ws_pane" ] && pid_under "$(jnum "$blob" pid)" "$ws_pane"; then + tier=2 + elif [ -n "$tmuxv" ] && [ "${tmuxv%.*}" = "$target" ]; then + tier=1 + else + continue + fi + upd="$(jnum "$blob" updatedAt)" + case "$upd" in ''|*[!0-9]*) upd=0 ;; esac + if [ "$tier" -lt "$best_tier" ]; then continue; fi + if [ "$tier" = "$best_tier" ] && [ "$upd" -le "$best_upd" ]; then continue; fi + best_tier="$tier"; best_upd="$upd" + name="$(jstr "$blob" name)" + pid="$(jnum "$blob" pid)" + best_out="$(printf '%s%s%s%s%s%s%s%s%s' "$sid" "$US" "${tmuxv:-$target}" "$US" "${name:-none}" "$US" "${pid:-unknown}" "$US" "$(record_profile "$f")")" + done < "$wsn_files" + rm -f -- "$wsn_files" + [ -n "$best_out" ] || return 8 + printf '%s\n' "$best_out" + return 0 +} + +# ------------------------------------------------------------ the row, read +# +# R19 — FROM `origin/`, LIKE EVERY OTHER STATE READ. These four reads +# (the row itself, its session cell, its handoff path and its workstation +# column) were the last ones taking the WORKING TREE, and `print_holder_detail` +# is built entirely out of them — so `who` routinely answered with a current log +# and a stale row: a holder recorded on the other workstation read `NOT LIVE` +# because a peer's UNCOMMITTED edit to column 3 said `Eagle`, and a row that +# exists only on `origin/main` was not seen at all, losing the resume uuid and +# the handoff path, which are the two things `who` exists to hand over. Nothing +# in `who` reads the working tree now. + +# AMENDMENT 15 — `tolower` ON BOTH SIDES, like every other lookup of a lane +# name in this file. A caller reaches these two through `canon_lane`, so the +# name arriving here is already the ROW's own spelling; the comparison is +# case-insensitive anyway, because a caller that did not canonicalise must not +# silently read "this lane has no row" about a lane that has one. +ROW_AWK=' + substr($0,1,1) == "|" { + p1 = index($0, "`"); if (p1 == 0) next + rest = substr($0, p1 + 1); p2 = index(rest, "`"); if (p2 == 0) next + if (tolower(substr(rest, 1, p2 - 1)) == tolower(lane)) print + }' +row_of_lane() { register_text | awk -v lane="$1" "$ROW_AWK"; } +# The same row as THIS CHECKOUT has it. One caller: the `live-holder` +# subcommand, which unions these ids with the published ones because liveness +# fails CLOSED — an id this checkout knows and `origin/main` does not yet is one +# more reason to refuse a rename, never a reason to allow one (AGENTS.md rule 7). +row_of_lane_local() { awk -v lane="$1" "$ROW_AWK" "$LANES_FILE"; } +row_cell() { printf '%s\n' "$1" | awk -F'|' -v i="$2" '{print $i}'; } + +# ====================================================== AMENDMENT 15 ======= +# +# THE RESOLVER. **A lane name is compared CASE-INSENSITIVELY wherever a name is +# looked up, and the spelling the register row carries is canonical** — it is +# what the window is named, what the session is named, what the log file is +# called, and what every line and stamp writes. A name typed in another case +# RESOLVES to it and is never written as typed. +# +# Every spelling the PUBLISHED register carries for a name, from +# `origin/` like every other state read (R19). `lane_named_ci` below is +# the same question asked for one answer and no refusal — it is the hook's read +# and the hook never refuses — so the two are one parse in two shapes rather +# than two rules. +# +# AND A THIRD SHAPE SINCE AMENDMENT 12: the prompt guard asks this one because +# it COUNTS. `canon_lane` below answers a caller that wants a name back and +# refuses two with `note` + 2 in this file's own voice; the guard has to print +# its triple FIRST and then say what is wrong, in its own shape, so it takes the +# spellings from here and makes the refusal itself. One parse, three readings, +# and no second rule about what a lane name is. +# +# AND IT RETURNS 1 WHERE THE PUBLISHED REGISTER COULD NOT BE READ (#138 item +# 18): the pipeline's status is the awk's, so a failed read was "no such row". +# It reads `register_text_checked` (#67), whose status `register_text` drops, +# and keeps both statuses; every caller that does not check them is unchanged. +rows_named_ci() { # + register_text_checked | awk -v want="$1" ' + substr($0,1,1) == "|" { + p1 = index($0, "`"); if (p1 == 0) next + rest = substr($0, p1 + 1); p2 = index(rest, "`"); if (p2 == 0) next + t = substr(rest, 1, p2 - 1) + if (tolower(t) == tolower(want)) print t + }' + [ "${PIPESTATUS[0]}${PIPESTATUS[1]}" = 00 ] +} + +# ====================================================== AMENDMENT 16 ======= +# +# THE LANE ALIAS TABLE — `lanes/aliases.tsv`, ` ` — AND THE +# ONE SEAT EVERY READER SHARES. +# +# Clause (e): *"Every reader that takes a lane name — `who`, `lanes`, +# `live-holder`, `history`, Rule 6 attribution, `lane-start`'s row lookup, the +# `SessionStart` block and Amendment 12's guard — resolves through it, +# case-insensitively (Amendment 15), before it reads."* THAT LIST IS NOT BUILT +# AS A LIST. Amendment 15 already put `canon_lane` in front of every one of +# those reads — each subcommand arm below spells +# `lane="$(canon_lane "$lane")" || exit 2`, and `lane-start`, `lane-end`, `lane` +# and `lane-handoff` each call the `canon-lane` subcommand — so the resolution +# is hooked THERE, once, and the guard's own two lookups take the same function +# one layer down. A list of readers is a list somebody has to keep complete. +# +# READ FROM `origin/` LIKE THE REGISTER (R19), falling back to this +# checkout's own file — `register_text`'s exact shape, for its exact reason: +# `rename-lane` lands the row and this table in ONE commit, so a reader taking +# one from the working tree and the other from `origin` could see an alias whose +# row has not arrived here, or a row whose alias has not. +LANES_ALIAS_CACHE="" +LANES_ALIAS_ERR="" +# THE REASON IS WRITTEN WHERE THE PARENT CAN READ IT, and that is not a +# nicety: every caller of `lane_alias_text` reaches it through a COMMAND +# SUBSTITUTION — `lane_alias_hop`, `lane_alias_target` and `lane_alias_keys` +# are all taken with `$( )`, and `rows_named_ci_alias` is taken with one by +# `canon_lane` — so a variable set here dies with the subshell, and every +# refusal below printed `(unknown error)`: fail-closed, and silent about what +# to fix. It goes in a file beside the events cache, which `cleanup` already +# sweeps (`rm -f -- "$SE_CACHE_FILE".*`), exactly as `SE_WARN_FILE` carries a +# warning raised inside the same kind of substitution. The variable is kept as +# the answer for a process that has no temporary file at all — `mktemp` can +# fail, and `SE_CACHE_FILE` is empty when it does. +lane_alias_fail() { # + LANES_ALIAS_ERR="${1-}" + laf_f="${SE_CACHE_FILE:+$SE_CACHE_FILE.aliaserr}" + [ -n "$laf_f" ] && printf '%s' "${1-}" > "$laf_f" 2>/dev/null + return 0 +} +# AND IT IS NOT ITS OWN FALLBACK. The file is the reason THIS process last +# failed with; the variable is the reason THIS SHELL last failed with; and +# where there is neither, the sentence still has to read as English, so the +# words are spelled out here rather than left to a caller's `${x:-…}`. +lane_alias_err() { + lae_f="${SE_CACHE_FILE:+$SE_CACHE_FILE.aliaserr}" + if [ -n "$lae_f" ] && [ -s "$lae_f" ]; then cat -- "$lae_f"; return 0; fi + printf '%s' "${LANES_ALIAS_ERR:-unknown error}" + return 0 +} +# A READ THAT FAILED IS NOT AN EMPTY TABLE (Copilot round 1 on openRepoTools#81). +# `cat … 2>/dev/null || :` made a permission or IO fault on `lanes/aliases.tsv` +# indistinguishable from an estate that has never renamed a lane — and the two +# have opposite consequences: the second means a name resolves to itself, while +# the first means a name whose row moved resolves to NOTHING, so a reader misses +# that lane's whole history and `rename-lane` validates its cycle test against a +# table it could not read. Clause (e) promises the old name resolves FOR EVER, so +# this fails CLOSED: 5, with the reason in `LANES_ALIAS_ERR`, which the writer +# turns into a refusal and every reader says out loud. +lane_alias_text() { + if [ -n "$LANES_ALIAS_CACHE" ]; then printf '%s\n' "$LANES_ALIAS_CACHE"; return 0; fi + lat_c="${SE_CACHE_FILE:+$SE_CACHE_FILE.aliases}" + # THE CACHE'S OWN READ IS CHECKED (Copilot round 5 on openRepoTools#81). The + # `return 0` under an unchecked `cat` was the fail-closed rule with a hole in + # it: a cache this process wrote and cannot now read would answer EMPTY with + # status 0, and a former lane name would resolve as new — which is the one + # outcome every other branch of this function exists to refuse. + if [ -n "$lat_c" ] && [ -s "$lat_c" ]; then + cat -- "$lat_c" || { + lane_alias_fail "the cached copy at $lat_c could not be read" + return 5 + } + return 0 + fi + # A FRESH READ BEGINS HERE, so the reason the LAST one failed with goes: the + # file outlives the subshell that wrote it on purpose, and an answer kept + # past the read it belongs to is the stale kind of honesty. + lat_t=""; LANES_ALIAS_ERR="" + lat_e="${SE_CACHE_FILE:+$SE_CACHE_FILE.aliaserr}" + [ -n "$lat_e" ] && rm -f -- "$lat_e" + # AMENDMENT 14 — under `--index`, the table as the indexed commit carried it; + # where it carried none, the same local fallbacks below. + if [ -n "$LANES_IDX_DIR" ] && [ -f "$LANES_IDX_DIR/aliases" ]; then + lat_t="$(cat -- "$LANES_IDX_DIR/aliases" 2>/dev/null)" || { + lane_alias_fail "the index's copy at $LANES_IDX_DIR/aliases could not be read" + return 5 + } + elif [ -z "$LANES_IDX_DIR" ] && have_remote_ref && git -C "$LANES_REPO" cat-file -e "origin/$LANES_BRANCH:$LANES_ALIASES_PATH" 2>/dev/null; then + lat_t="$(git -C "$LANES_REPO" show "origin/$LANES_BRANCH:$LANES_ALIASES_PATH" 2>/dev/null)" || { + lane_alias_fail "git show origin/$LANES_BRANCH:$LANES_ALIASES_PATH failed, and the object is there" + return 5 + } + elif [ -n "${LANES_ALIASES_TSV:-}" ] && [ -f "$LANES_ALIASES_TSV" ]; then + lat_t="$(cat -- "$LANES_ALIASES_TSV" 2>/dev/null)" || { + lane_alias_fail "$LANES_ALIASES_TSV is there and could not be read" + return 5 + } + elif [ -n "${LANES_ALIASES_TSV:-}" ] \ + && { [ -e "$LANES_ALIASES_TSV" ] || [ -L "$LANES_ALIASES_TSV" ]; }; then + # SOMETHING IS THERE AND IT IS NOT A TABLE (Copilot round 8 on + # openRepoTools#81). A directory, a FIFO, a socket or a DANGLING symlink at + # this path makes `-f` false, and the branch was simply skipped: the empty + # answer below was cached and handed back with status 0, so a former lane + # name read as NEW — and `lane-start` then appends a SECOND row for a lane + # that has been running all day, which is Amendment 15(a)'s duplicate + # arrived at through a READ. `-L` is asked beside `-e` because `-e` is FALSE + # on a dangling link, the same pair the handoff's destination test uses. + # + # AND THE READER'S RULE IS NARROWER THAN THE WRITER'S, deliberately. The + # writer refuses a LIVE symlink to a regular file as well, because it + # appends in place and a redirect follows one into whatever is at the far + # end; a reader that follows the same link gets the table's own bytes and is + # right to, so `-f` above answers it and says nothing. What is refused here + # is only what cannot be READ — which is why the two say different words. + if [ -L "$LANES_ALIASES_TSV" ]; then + lane_alias_fail "$LANES_ALIASES_TSV is a symlink whose target is not a regular file" + else + lane_alias_fail "$LANES_ALIASES_TSV exists and is not a regular file" + fi + return 5 + fi + # AND THE EMPTY ANSWER IS CACHED TOO, as one comment line in the table's own + # grammar. An estate that has never renamed a lane is the ordinary case, and + # without this the `cat-file -e` above would run again for every `canon_lane` + # of every command — which is the cost `table_lookup` one screen up exists to + # avoid, made per process instead of per lane. + LANES_ALIAS_CACHE="${lat_t:-# no lane aliases}" + if [ -n "$lat_c" ]; then + printf '%s\n' "$LANES_ALIAS_CACHE" > "$lat_c.${BASHPID:-$$}" 2>/dev/null && + mv -f -- "$lat_c.${BASHPID:-$$}" "$lat_c" 2>/dev/null || + rm -f -- "$lat_c.${BASHPID:-$$}" + fi + printf '%s\n' "$LANES_ALIAS_CACHE" +} + +# BOTH COPIES OF IT, and the flag that says the awk file has been asked for: +# the variable this shell holds, the file every subshell reads, and the path +# `LOG_AWK` was handed (ruling 12's rule for the register cache, which this one +# is a twin of). Called by `log_sync`, because a fetch moves the ref this is +# read from, and by `rename-lane` after its own commit, because the alias it +# just wrote is the one the comments below it are computed with. +lane_alias_flush() { + LANES_ALIAS_CACHE="" + LANES_ALIAS_ERR="" + laf_e="${SE_CACHE_FILE:+$SE_CACHE_FILE.aliaserr}" + [ -n "$laf_e" ] && rm -f -- "$laf_e" + laf_c="${SE_CACHE_FILE:+$SE_CACHE_FILE.aliases}" + [ -n "$laf_c" ] && rm -f -- "$laf_c" + return 0 +} + +# lane_alias_target [] — the END of that name's alias chain. +# 0 + the name the table names it (a chain `a→b`, `b→c` answers `c`) +# 1 + nothing the table does not name it +# 3 + nothing the table holds a CYCLE through it +# 4 + nothing the chain VISITS — `rename-lane`'s cycle test, +# which asks of the table as it WILL be: adding ` → +# ` closes a cycle exactly when the chain from `` +# reaches ``, and reaching it ANYWHERE counts, not only +# at the end (a chain `new → old → x` ends at `x` and still +# closes, because the new row is appended last and wins the +# key `old`). +# 5 + nothing the table could not be READ (fail closed; `LANES_ALIAS_ERR`) +# +# Case-insensitive on both sides (Amendment 15). THE LAST ROW FOR A KEY WINS: +# the file is append-ordered, and a name renamed away, minted again and renamed +# again has two rows of which the later is the answer a reader today needs. +# +# THE WALK IS BOUNDED BY THE TABLE AND NOT BY A NUMBER (Copilot round 1 on +# openRepoTools#81). It was `for (i = 0; i < 32; i++)`, which is a CAP on a +# valid chain as well as on a cycle: an estate that renamed one lane thirty-three +# times would have its earliest names resolve to an INTERMEDIATE one, which has +# no row, so `canon_lane` would answer a name nothing carries and clause (e)'s +# "for ever" would quietly end at hop 32. The `seen` set is what guarantees +# termination — every hop consumes one key of a finite map — so the bound is the +# number of keys plus one, which no honest chain can exceed and no cycle can +# reach without closing first. +lane_alias_target() { # [] + lat_out="$(lane_alias_text)" || return 5 + printf '%s\n' "$lat_out" | awk -F'\t' -v want="$1" -v stop="${2-}" ' + /^[ \t]*#/ { next } + NF >= 2 { + k = $1; v = $2 + gsub(/^[ \t]+|[ \t]+$/, "", k); gsub(/^[ \t]+|[ \t]+$/, "", v) + if (k == "" || v == "") next + if (!(tolower(k) in map)) nmap++ + map[tolower(k)] = v + } + END { + cur = want; ls = tolower(stop) + for (i = 0; i <= nmap; i++) { + lk = tolower(cur) + if (stop != "" && lk == ls) { hit = 1; break } + if (lk in seen) { cyc = 1; break } + if (!(lk in map)) break + seen[lk] = 1; cur = map[lk]; hops++ + } + if (hit) exit 4 + if (cyc) exit 3 + if (hops > 0) { print cur; exit 0 } + exit 1 + }' +} + +# ONE HOP, and the reason it exists apart from the walk above: "a ROW WINS OVER +# AN ALIAS" has to be asked at EVERY hop and not only at the start (Copilot round +# 1). After `A → B`, a lane legitimately minted under the name `A` again — the +# position `A` freed is one `lane_next_free` will hand out — makes `A` both a row +# and an alias key, and a chain `C → A` must then stop AT `A`, which is a lane, +# rather than carry on to `B`, which is a different one. Walking hop by hop in +# the shell is what lets the row test sit between the hops; the chains this +# estate writes are one or two long, and `register_text` is cached, so the cost +# is an awk per hop over a table of a few lines. +# 0 + the next name · 1 + nothing · 5 the table could not be read +lane_alias_hop() { # + lah_out="$(lane_alias_text)" || return 5 + printf '%s\n' "$lah_out" | awk -F'\t' -v want="$1" ' + /^[ \t]*#/ { next } + NF >= 2 { + k = $1; v = $2 + gsub(/^[ \t]+|[ \t]+$/, "", k); gsub(/^[ \t]+|[ \t]+$/, "", v) + if (k == "" || v == "") next + map[tolower(k)] = v + } + END { if (tolower(want) in map) { print map[tolower(want)]; exit 0 } exit 1 }' +} + +# lane_alias_keys — every key of the table, one per line, as written. The one +# caller is `rename-lane`, which refuses a `` that is already a key +# (Copilot round 1): a row under a former name TAKES PRECEDENCE over the alias, +# so minting one deliberately would end that former name's resolution — the one +# thing clause (e) promises never happens. +lane_alias_keys() { + lak_out="$(lane_alias_text)" || return 5 + printf '%s\n' "$lak_out" | awk -F'\t' ' + /^[ \t]*#/ { next } + NF >= 2 { k = $1; gsub(/^[ \t]+|[ \t]+$/, "", k); if (k != "") print k }' +} + +# Every ROW SPELLING that answers for : its own rows, and where it has +# none, the rows of the first name along its alias chain that HAS one. Used by +# `canon_lane` below and by the guard's window and session lookups, which are +# the two seats that read a row from a name without going through `canon_lane`. +# +# A ROW WINS OVER AN ALIAS, AT EVERY HOP AND NOT ONLY AT THE START (Copilot +# round 1 on openRepoTools#81). A name that is a lane today IS that lane — which +# is what makes renaming a lane BACK to a name readable — and the chain has to +# be walked with that test BETWEEN the hops, because an alias key can become a +# row again: `A → B` frees the name `A`, `lane_next_free` hands that position +# out, and a later `C → A` must then answer `A`, the lane, rather than running +# on to `B`, which is a different one. Taking only the END of the chain answered +# `B` and lost `C`'s own lane. +# +# The loop is bounded by a `seen` list rather than by a number, for +# `lane_alias_target`'s reason: every hop consumes one key of a finite table. +# 0 + the row spellings (possibly none) · 5 the alias table could not be READ +# +# AND THE 5 IS CARRIED, NOT SWALLOWED (Copilot round 3 on openRepoTools#81). It +# was `|| return 0`, which hands a caller an EMPTY answer — "no row under this +# name" — for a table nobody could read. Every caller then falls to its own +# not-a-lane branch: `canon_lane` answers the typed spelling, so `lane-start` +# reads a renamed lane as new and appends a SECOND row; the guard falls to +# `lane_shaped` and sends a running session to bind a row it already has. That +# is the fail-OPEN direction on the one promise clause (e) makes, so the status +# is propagated and each caller decides what to do with it. +rows_named_ci_alias() { # + rna_hits="$(rows_named_ci "$1" 2>/dev/null || :)" + if [ -n "$rna_hits" ]; then printf '%s\n' "$rna_hits"; return 0; fi + rna_cur="$1"; rna_seen="$US$(lc "$1")$US" + while :; do + rna_rc=0 + rna_next="$(lane_alias_hop "$rna_cur" 2>/dev/null)" || rna_rc=$? + [ "$rna_rc" = 5 ] && return 5 + [ "$rna_rc" = 0 ] && [ -n "$rna_next" ] || return 0 + case "$rna_seen" in *"$US$(lc "$rna_next")$US"*) return 0 ;; esac + rna_seen="$rna_seen$(lc "$rna_next")$US" + rna_hits="$(rows_named_ci "$rna_next" 2>/dev/null || :)" + if [ -n "$rna_hits" ]; then printf '%s\n' "$rna_hits"; return 0; fi + rna_cur="$rna_next" + done +} + +# canon_lane — the name every `` argument and `$LANES_LANE` is +# read through BEFORE anything is read or written under it. +# +# exactly one row matches, ignoring case its OWN spelling +# no row matches the typed spelling, unchanged — +# which is what `add-row` needs, and +# what makes a brand-new lane's +# first act possible at all +# two or more REFUSE (2), naming them all +# +# IT RETURNS AND NEVER EXITS, for `row_line`'s reason: every caller takes it +# with `$( )`, and an `exit` there would leave only the substitution's subshell +# while the caller carried on with an empty lane name. The callers spell it +# `lane="$(canon_lane "$lane")" || exit 2`. +# +# THE REFUSAL IS THE AMENDMENT'S OWN AND IT BELONGS TO EVERY WRITER, not only +# to `lane-start`, which has refused two rows for one name since Amendment 5: +# clause (b) says *"where the register already holds two rows that differ only +# by case, every writer REFUSES, naming both, until they are merged"*. Merging +# them is 15(d)'s act and a person's — the newer row's session id(s) appended to +# the older row's cell, in order, and the newer row removed in the same commit — +# because a tool that merged two rows of history on its own would be choosing +# which lane's record survives. +# +# AMENDMENT 16(e) — AND A NAME WITH NO ROW IS ASKED OF THE ALIAS TABLE BEFORE +# the typed spelling is handed back. This is clause (e)'s whole implementation +# and it is one function deep: a renamed lane's OLD name, from a line, a window, +# a session record or a person's typing, lands on the row it is now. The order +# is row first and alias second — a name that is a lane today is that lane — and +# the resolution SAYS SO on stderr, because every act under an old name is an +# act on a lane the caller did not name. +canon_lane() { # + cl_want="${1-}" + [ -n "$cl_want" ] || return 0 + cl_rc=0 + cl_hits="$(rows_named_ci_alias "$cl_want" 2>/dev/null)" || cl_rc=$? + # AN ALIAS TABLE THAT CANNOT BE READ IS A REFUSAL HERE TOO (Copilot round 3 + # on openRepoTools#81). This function's answer is what `lane-start` decides + # "is this lane new" by and what `register-row` reports, so carrying on with + # the typed spelling is not a read-only shrug: with a row under `` and an + # unreadable table, `lane-start ` reads the former name as absent + # and appends a SECOND row — the duplicate Amendment 15(a) exists to refuse. + # R22's rule governs: a read that could not be performed is never an answer. + if [ "$cl_rc" = 5 ]; then + note "${LANES_ALIASES_PATH:-lanes/aliases.tsv} COULD NOT BE READ ($(lane_alias_err)), so whether '$cl_want' is a FORMER name of some lane is NOT established — which is not the same as it not being one (Amendment 16(e))." + note "Nothing is read or written under a name this register cannot resolve: a rename's alias would be invisible, and a lane that has one would read as new. Fix the read — the table is ${LANES_ALIASES_TSV:-} here and ${LANES_ALIASES_PATH:-lanes/aliases.tsv} on origin/$LANES_BRANCH — and re-run." + # 66 AND NOT 2, BECAUSE 2 ALREADY MEANS SOMETHING TO FOUR CALLERS (Copilot + # round 4). `lane-start`, `lane-end`, `lane` and `lane-handoff` each read + # `canon-lane`'s 2 as EITHER Amendment 15(d)'s two-rows refusal — told by + # the words in its message — or the unknown-subcommand 2 of a helper that + # predates Amendment 15, which they carry on past with the name as typed. + # A third meaning on that number lands in the second branch, which is the + # fail-OPEN this refusal exists to close. 66 is EX_NOINPUT: an input file + # that did not exist or could not be read, which is exactly what happened, + # and a code none of the four recognises makes `lane` and `lane-handoff` + # refuse where they stand — the other two are taught it in this same commit. + return 66 + fi + cl_n="$(printf '%s' "$cl_hits" | grep -c . || :)" + if [ "$cl_n" -gt 1 ]; then + note "the register has $cl_n rows whose lane names differ only by case for '$cl_want': $(printf '%s' "$cl_hits" | tr '\n' ' ')" + note "a lane name is ONE name under any case (Amendment 15), so no read and no write under it is unambiguous. Merge them into one row (Amendment 15(d)): append the newer row's session id(s) to the older row's session cell, in order, remove the newer row in the SAME commit, and name both spellings in the commit message." + return 2 + fi + cl_out="$cl_want" + if [ "$cl_n" = 1 ]; then + cl_out="$cl_hits" + else + # NO ROW UNDER EITHER NAME. The alias still answers where the table names + # it — a lane whose row has since been archived keeps its log, and reading + # that log under the old name is the whole point of the table. + cl_al=""; cl_arc=0 + cl_al="$(lane_alias_target "$cl_want" 2>/dev/null)" || cl_arc=$? + if [ "$cl_arc" = 3 ]; then + note "${LANES_ALIASES_PATH:-lanes/aliases.tsv} resolves '$cl_want' in a CYCLE, so it names no lane at all: a rename chain that returns to its own start has no end to resolve to. \`rename-lane\` refuses to write one, so this table was edited by hand — take the offending row out of it. Carrying on with '$cl_want' exactly as typed." + elif [ "$cl_arc" = 5 ]; then + # UNREACHABLE BY THE PATH ABOVE, which already refused a 5 — kept because + # this arm is the second reader of the same table and a silent + # disagreement between two readers of one file is worth a line of code. + note "${LANES_ALIASES_PATH:-lanes/aliases.tsv} could not be read ($(lane_alias_err))." + return 66 + elif [ -n "$cl_al" ]; then + cl_out="$cl_al" + fi + fi + if [ "$(lc "$cl_out")" != "$(lc "$cl_want")" ]; then + note "'$cl_want' is a FORMER name of lane $cl_out (${LANES_ALIASES_PATH:-lanes/aliases.tsv}, Amendment 16(e)) — reading and writing $cl_out." + fi + printf '%s' "$cl_out" + return 0 +} + +uuids_in_cell() { grep -oiE '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}' | tr 'A-F' 'a-f' || :; } + +session_ids_of_lane() { + si_row="$(row_of_lane "$1")" + [ -n "$si_row" ] || return 1 + row_cell "$si_row" 3 | uuids_in_cell +} +session_ids_local_of_lane() { + sl_row="$(row_of_lane_local "$1")" + [ -n "$sl_row" ] || return 1 + row_cell "$sl_row" 3 | uuids_in_cell +} +# THE SAME UNION, AND IT SAYS WHETHER IT COULD READ IT (opensoft/openRepoTools#67). +# The pair above answer 1 for "this lane has no row" AND for "the register could +# not be read" — `row_of_lane` is `register_text | awk`, and `awk` answers 0 +# over an empty render — so a caller that unions them with `|| :` holds an +# EMPTY id set either way. For most of them that is harmless. For the three +# that take an empty set as a VERDICT it is fail-open: `holder_is_dead` hands it +# to `live_holder`, whose 8 then calls a lane dead that nobody could check, +# `duplicate_holder_pids` answers "no duplicate" without looking, and +# `lane_reconcile` pronounces a crash on that same 8 (#113 item 1). Those three +# ask this read instead, and the pair keep their contract for everyone else. +# +# 0 the published-union-local ids, one per line, published first, deduped +# 8 BOTH copies were read and neither gives this lane a transcript uuid: no +# row, or a row whose session cell holds none — an answer either way, the +# same one `live_holder` already gives an empty cell +# 1 the published register (or, with none published, the working tree's) or +# the working tree's own copy could not be read: NOT an empty set +session_ids_checked() { # + sc_pub=""; sc_loc="" + sc_pub="$(register_text_checked 2>/dev/null)" || return 1 + sc_loc="$(row_of_lane_local "$1" 2>/dev/null)" || return 1 + sc_ids="$(row_cell "$(printf '%s\n' "$sc_pub" | awk -v lane="$1" "$ROW_AWK") +$sc_loc" 3 | uuids_in_cell | awk 'NF && !seen[$0]++')" + [ -n "$sc_ids" ] || return 8 + printf '%s\n' "$sc_ids" +} +last_session_id_of_lane() { session_ids_of_lane "$1" 2>/dev/null | tail -n1; } +# The handoff path is the row's SIXTH column — awk field 7, because $1 is the +# empty string before the leading pipe. Counting back from NF was wrong for any +# row with a literal `|` inside a cell, and the live register has two: of 45 +# rows, 43 split into 9 fields, one into 10 and one into 11, and for the last +# of those NF-2 is the tail of the state cell (` re-cut `) rather than the +# handoff. `lane_workstation` below counts from the left for the same reason. +handoff_of_lane() { + hl_row="$(row_of_lane "$1")" + [ -n "$hl_row" ] || return 1 + row_cell "$hl_row" 7 | sed 's/^ *//; s/ *$//' +} + +short_ws() { printf '%s' "${1%%.*}" | tr 'A-Z' 'a-z'; } + +# Column 3 of the row is ` / / `. A lane recorded on +# ANOTHER workstation cannot be liveness-checked from here at all: the session +# records are local files. Saying NOT LIVE about it would be a claim this +# machine has no way to make. +lane_workstation() { + lw_row="$(row_of_lane "$1")" + [ -n "$lw_row" ] || return 1 + row_cell "$lw_row" 4 | sed 's/^ *//; s/ *$//; s| */.*||' | awk '{print $1}' +} +lane_is_elsewhere() { + lw="$(lane_workstation "$1" 2>/dev/null || :)" + [ -n "$lw" ] || return 1 + [ "$(short_ws "$lw")" != "$(short_ws "$WS")" ] +} + +# The session id an event line carries: what the caller says it is, else the +# lane's current one (Amendment 6(b): the LAST id in the cell), else NOTHING. +# +# R-A11 (e) — IT NO LONGER SUBSTITUTES THE LITERAL `unknown`. It did, and that +# literal is in the append-only log four times already, in two lanes +# (`lanes/log/codeXfactory-1.md` ×3, `lanes/log/openxfactory-4-opendox-extraction.md` +# ×1 on `origin/main`) — written by `log PAUSED` from a swap skill that had the +# uuid in hand and did not pass it, and by `release`. Amendment 7(b) makes that +# field a transcript uuid and ONLY that. Returning empty hands the decision to +# `write_event`, which refuses the write and names the act that supplies the +# uuid; the four lines already written stay exactly where they are (Amendment +# 7(b) forbids editing them, 7(i)'s cutover rule governs). +session_for() { + if [ -n "${LANES_SESSION:-}" ]; then printf '%s\n' "$LANES_SESSION"; return 0; fi + last_session_id_of_lane "$1" 2>/dev/null || : +} + +# ----------------------------------------------------- project.yaml legs +# +# openRepoShape's assembly-root manifest: a top-level `legs:` list of +# `- role: assembly|spec|code` / `repository: owner/repo` / `path:`. Two +# repositories are legs of ONE project when one manifest names them both. +# +# ONLY `legs[].repository` is read, and only as navigation. The manifest says +# of itself that it CONFERS NOTHING — `role:` in particular grants nothing and +# is never read here. +# +# `family.yaml`'s `members:` is deliberately NOT read, though its entries carry +# a `repository:` too. A family is broader than a project — `InkRouter` holds +# `IRRS` and `IRSS`, separate projects with separate lanes — and the ruling +# said legs. Two repos in one family ARE a crossing. +project_legs_file() { + [ -f "$1" ] || return 1 + awk ' + /^[A-Za-z_][A-Za-z0-9_]*:/ { inlegs = ($0 ~ /^legs:/); next } + !inlegs { next } + /^[ \t]*#/ { next } + /^[ \t]+repository:[ \t]*/ { + v = $0 + sub(/^[ \t]+repository:[ \t]*/, "", v) + sub(/[ \t]+$/, "", v) + gsub(/^"|"$/, "", v) + gsub(/^'"'"'|'"'"'$/, "", v) + if (v != "") print v + }' "$1" +} + +# ------------------------------------------- an assembly's legs, by path +# +# opensoft/openRepoTools#186, plan task T018 — WHERE A TRIAD'S LEGS ARE CHECKED +# OUT, for the lane tooling that has to look inside one: `lane-worktrees`' sweep, +# its daily report and its `add`, `lane-handoff`'s writer poll, and +# `lane-reconcile` below. A checkout IS AN ASSEMBLY when its own `project.yaml` +# declares a leg other than itself — the standard's own rule (openRepoShape's +# `templates/assembly-root/project.yaml`: a top-level `legs:` list of `- role:` / +# `repository:` / `path:`, the assembly's own leg at `path: "."`). A checkout +# with no such file, or one naming no leg but itself, is every single +# repository, and every reader asks it nothing more than it did before. +# +# THE READING IS `lane-start`'s RUNG 5, LINE FOR LINE, and never a second +# grammar: rung 5 resolves ONE leg's path for the home it is given, and this +# prints every leg the block declares, as ``. The seven +# lines that decide what a leg is are byte-identical to that reader's, and +# `tests/test_triad_lane_tooling.py` holds them so. As there, ONLY `repository:` +# and `path:` are read, and only as navigation: the manifest CONFERS NOTHING, +# and `role:` is never read. +project_leg_paths_file() { # + [ -f "$1" ] || return 1 + awk ' + /^[A-Za-z_][A-Za-z0-9_]*:/ { inlegs = ($0 ~ /^legs:/); repo = ""; path = ""; next } + !inlegs { next } + /^[ \t]*-[ \t]/ { repo = ""; path = "" } + /^[ \t]+repository:[ \t]*/ { v = $0; sub(/^[ \t]+repository:[ \t]*/, "", v) + sub(/[ \t]+$/, "", v); gsub(/^"|"$/, "", v); gsub(/^'"'"'|'"'"'$/, "", v); repo = v } + /^[ \t]+path:[ \t]*/ { v = $0; sub(/^[ \t]+path:[ \t]*/, "", v) + sub(/[ \t]+$/, "", v); gsub(/^"|"$/, "", v); gsub(/^'"'"'|'"'"'$/, "", v); path = v } + repo != "" && path != "" { print repo "\t" path; repo = ""; path = "" }' "$1" +} + +# THE LEGS OF ONE CHECKOUT, one a line: ``, the last being the declared path +# resolved against the checkout as rung 5 resolves it. The assembly's own `.` +# is left out: it IS the checkout. 0 with legs; 8 with none — no +# `project.yaml`, or one naming no leg but the checkout itself; 1 where the +# manifest is there and could not be read, which is never "no legs" (R22, +# Amendment 7(d)). +assembly_legs() { # + al_dir="${1-}"; al_dir="${al_dir%/}"; al_rows=""; al_out=""; al_tab="$(printf '\t')" + [ -n "$al_dir" ] || return 8 + al_m="$al_dir/project.yaml" + [ -e "$al_m" ] || [ -L "$al_m" ] || return 8 + { [ -f "$al_m" ] && [ -r "$al_m" ]; } || return 1 + al_rows="$(project_leg_paths_file "$al_m")" || return 1 + while IFS="$al_tab" read -r al_repo al_path; do + al_path="${al_path%/}" + case "$al_path" in + ''|.|./.) continue ;; + /*) al_abs="$al_path" ;; + ./*) al_abs="$al_dir/${al_path#./}" ;; + *) al_abs="$al_dir/$al_path" ;; + esac + al_out="$al_out$al_repo$al_tab$al_path$al_tab$al_abs +" + done </dev/null || :)" + printf '%s\n' "${cr_c:-$cr_v}" + done +} + +same_project() { + sp_home="$1"; sp_obj="$2"; sp_f=""; sp_legs="" + SAME_PROJECT_FILE="" + [ -n "$sp_home" ] && [ -n "$sp_obj" ] || return 1 + sp_c="$(alias_lookup "$sp_home" 2>/dev/null || :)"; sp_home="${sp_c:-$sp_home}" + sp_c="$(alias_lookup "$sp_obj" 2>/dev/null || :)"; sp_obj="${sp_c:-$sp_obj}" + [ "$sp_home" = "$sp_obj" ] && return 0 + for sp_f in ${LANES_LANE_DIR:+"$LANES_LANE_DIR/project.yaml"} \ + "$PROJECTS_ROOT"/*/project.yaml \ + "$PROJECTS_ROOT"/*/*/project.yaml; do + [ -f "$sp_f" ] || continue + sp_legs="$(project_legs_file "$sp_f" 2>/dev/null | canon_repo_list || :)" + [ -n "$sp_legs" ] || continue + printf '%s\n' "$sp_legs" | grep -qx -F -- "$sp_home" || continue + printf '%s\n' "$sp_legs" | grep -qx -F -- "$sp_obj" || continue + SAME_PROJECT_FILE="$sp_f" + return 0 + done + return 1 +} + +# Decision 2, ratified by Brett Heap 2026-09-11 ("yes just warn"): a crossing +# WARNS and proceeds. It never refuses — the estate crosses routinely +# (opsXfactory-3 landed 32 distinct PRs into opensoft/Omnigent-Install, every +# one of them foreign to its home), and a refusal here would be a new gate +# nobody asked for. +cross_repo_warn() { + cw_obj_repo="$1"; cw_home="$2"; cw_me="$3"; cw_found=0; cw_lane=""; cw_h=""; cw_id="" + [ -n "$cw_obj_repo" ] || return 0 + if [ -z "$cw_home" ]; then + note "NOTE: lane $cw_me has no home repo on record, so the cross-repo check did not run (pre-cutover lane: pass --home owner/repo)" + return 0 + fi + [ "$cw_obj_repo" = "$cw_home" ] && return 0 + if same_project "$cw_home" "$cw_obj_repo"; then + note "$cw_obj_repo and $cw_home are legs of one project.yaml — not a crossing (${SAME_PROJECT_FILE:-?})" + return 0 + fi + note "WARNING: CROSS-REPO — $cw_obj_repo is not lane $cw_me's home ($cw_home). Proceeding: Amendment 7 warns here, it never refuses." + while IFS= read -r cw_lane; do + [ -n "$cw_lane" ] || continue + [ "$cw_lane" = "$cw_me" ] && continue + # Both sides through the alias table (R20): home_of_lane resolves its + # answer, and the object's repository arrived canonical from canon_object, + # so this comparison is between two canonical spellings. It is still made + # case-insensitively, because the register spells one repository three ways + # in a week and only the TABLE's lookup is case-blind, not its output. + cw_h="$(home_of_lane "$cw_lane" 2>/dev/null || :)" + [ "$(lc "$cw_h")" = "$(lc "$cw_obj_repo")" ] || continue + cw_id="$(last_session_id_of_lane "$cw_lane" 2>/dev/null || :)" + if lane_is_elsewhere "$cw_lane"; then + note " lane homed on $cw_obj_repo, on another workstation ($(lane_workstation "$cw_lane")): @$cw_lane — last transcript uuid ${cw_id:-unknown}" + cw_found=1 + elif live_holder "$cw_lane" >/dev/null 2>&1; then + note " LIVE lane homed on $cw_obj_repo: @$cw_lane — last transcript uuid ${cw_id:-unknown} — claude --resume ${cw_id:-}" + cw_found=1 + fi + done < +# Appends to the lane's log and commits — and for a LANDING or a LANDED +# appends Rule 6's line to LANES.md in the SAME commit, two pathspecs, so the +# register and the log can never disagree about a merge hold. +write_event() { + we_lane="$1"; we_verb="$2"; we_obj="$3"; we_ref="$4"; we_pay="$5"; we_txt="$6"; we_utc="$7"; we_uuid="$8" + # R-A11 (e) — THE `session` FIELD IS A TRANSCRIPT UUID AND ONLY THAT, AND THE + # WRITER ITSELF IS WHERE THAT IS ENFORCED. Amendment 7(b) says so of the + # grammar; nothing checked it, and the literal `unknown` is in the append-only + # log four times already, in two lanes — three from `log PAUSED` (a swap skill + # holding the uuid and not passing it) and one from `release`. The log is + # append-only, so a line written wrong there is wrong for ever and no later + # line can correct it. Refused HERE rather than in the `log` arm because the + # same field is written by `claim` and `release` too, and one of the four came + # from `release`: this is the writer, so this is the gate. + # + # It is the FIRST test in the function, before the lock, before the capture + # and before the log file is created, so a refusal leaves the checkout exactly + # as it found it — and it names the act that supplies the uuid rather than the + # rule it broke, because the caller's next move is that act. + # + # This composes with `R-A8-2` rather than repeating it: `R-A8-2` stopped + # `lane-start` WRITING `unknown` (its title-fallback path defers the line + # instead); this stops the writer ACCEPTING it, from any caller. + if ! valid_uuid "$we_uuid"; then + we_bad="${we_uuid:-}" + case "$we_uuid" in + unknown) we_why="'unknown' is the one value this field must never carry: it is in this append-only log four times already, and no later line can correct any of them" ;; + session_*) we_why="'$we_bad' is a PR-footer id, which is neither resumable nor liveness-checkable (Amendment 6(b))" ;; + *) we_why="'$we_bad' is not a transcript uuid" ;; + esac + die "an event's session field is the TRANSCRIPT UUID and only that (Amendment 7(b)): $we_why. Nothing was written — not the $we_verb line, not the log file, not a commit. Name the session taking the act: LANES_SESSION=\"\$CLAUDE_CODE_SESSION_ID\" LANES_LANE=$we_lane lanes-edit.sh … If lane $we_lane has no transcript uuid recorded at all, the act that gives it one is Amendment 6(c)'s session-cell append: run 'lane-start --no-launch ' in the lane's own window first" 2 + fi + # THE WRITER REFUSES A FIELD THAT WOULD MAKE THE LINE UNREADABLE (R21). + # ` — ` divides a line into its three parts, and the grammar guarantees it + # occurs AT MOST TWICE — once after the verb, once before the free text — so + # that one parser reads every line. A payload or a free text carrying a third + # one breaks that guarantee in a file nothing ever rewrites; so does a + # newline, which `append_text_line` would notice only AFTER writing it. Both + # are refused here, before the lock and before anything is created, rather + # than hoped against. + case "$we_pay$we_txt" in + *" — "*) die "an event's payload and free text may not contain ' — ': that separator is what divides a line's verb from its fields and its fields from its free text, and a third one leaves the line ambiguous to its own parser. Use a semicolon or a colon instead: '$we_pay$we_txt'" 2 ;; + esac + if [ "${we_pay//[$'\n\r']/}" != "$we_pay" ] || [ "${we_txt//[$'\n\r']/}" != "$we_txt" ]; then + die "an event's payload and free text are ONE line: a newline in either would append several lines to an append-only log, and the proof that only one was added would fail after the write, not before it" 2 + fi + # AND A `, ` IN THE PAYLOAD, WHICH IS CLAUSE (c)'S OTHER SEPARATOR AND WAS IN + # NO WRITER AT ALL. ` — ` divides the verb from the fields and the fields from + # the free text; `, ` divides THE FIELDS FROM EACH OTHER — `lane , session + # @, , ` — and the payload is the tail of that fourth + # field, so a `, ` inside it reads back as a fifth field and a sixth that no + # reader knows. `lane-start` fences its `dir`, `window` and `profile` values + # one at a time (`:689-692`, `:728-731`, `:1574-1578`) and the `/lane-swap` + # skill now fences the same two; this is the backstop under all of them, in the + # writer, for the reason this file gives for putting the container guard at the + # dispatcher: *"nine copies of one rule is how eight of them would come to + # disagree"*. + # + # THE PAYLOAD AND NOT THE FREE TEXT. The free text is everything after the + # SECOND ` — `, where a parser has already finished splitting fields, so a + # comma there is ordinary prose and the estate's log is full of it. Refusing it + # would refuse lines this estate legitimately writes. + # + # AND NOT THE `"` EITHER, WHICH IS WHY THIS GUARD IS NARROWER THAN THE ONES + # ABOVE IT. Clause (c)'s own rule for a path containing a space is to WRITE IT + # QUOTED — `dir "/checkouts/b/my projects/x"`, which is what makes it one ref + # under 7(b)'s own grammar. (The amendment spells that example under a home + # directory; it is spelled with a neutral root here because + # `test_no_committed_file_names_a_host_absolute_path` refuses a `/home//` + # path in any tracked file, and a rule that holds for a real path holds for an + # example of one.) One ref under + # 7(b) — so `quote_subfield` puts a `"` into the payload deliberately and a `"` + # refusal here would refuse the very shape the clause mandates. The `"` belongs + # in the per-VALUE fences, where it is, and not in the whole-payload one. + # + # MEASURED BEFORE IT WAS WRITTEN, against every line this estate has: 111 + # payloads in `opensoft/brett-wip`'s 15 lane logs carry `, ` 0 times and `"` 0 + # times, while 76 carry `; ` — the sub-field separator, which this guard must + # therefore never touch. + case "$we_pay" in + *", "*) die "an event's payload may not contain ', ': that separator is what divides an event line's four fields from each other — 'lane , session @, , ' — and the payload is the tail of the fourth, so a ', ' inside it reads back as fields the log's own parser cannot account for. The log is append-only and no later line can correct it. Use a semicolon, which is the sub-field separator: '$we_pay'" 2 ;; + esac + # AND IT REFUSES A FREE TEXT THAT BEGINS WITH AN ARROW (R26, Addendum 6). + # `→` and `←` introduce the PAYLOAD, and the payload is its own argument. + # Quoted into the free-text slot — `log LANDED "→ "`, the shape a + # reader reaches for because that is how the finished line looks — it is + # written AFTER the ` — `, where the parser reads it as prose: the event + # carries no payload, `rule6_line` renders the register's Rule 6 line without + # `→ `, and the merge sha is lost in two files that are never rewritten. + # Nothing legitimate starts a sentence with an arrow, so the trap is closed + # here rather than left to be noticed afterwards. + case "$we_txt" in + '→'*|'←'*) + we_hint="LANES_LANE=$we_lane lanes-edit.sh log $we_verb $we_obj → " + case "$we_verb" in + RELEASED) we_hint="LANES_LANE=$we_lane lanes-edit.sh release $we_obj \"\" — a release takes a reason, not a payload" ;; + CLAIMED|TAKEOVER|CLAIM-LOST) we_hint="LANES_LANE=$we_lane lanes-edit.sh claim $we_obj" ;; + esac + die "an event's free text may not begin with '→' or '←': those arrows introduce the PAYLOAD, which is its own argument and comes BEFORE the free text. Quoted into the text slot it is written after the ' — ', where no reader and no parser looks for it — a LANDED that way loses its merge sha from both the log and the register's Rule 6 line, in two files nothing rewrites. Write it positionally, e.g. 'lanes-edit.sh log LANDED → '; for this call: $we_hint" 2 ;; + esac + # AMENDMENT 17(b) — the two sub-fields, checked in the writer for the same + # reason the session field is: from any caller, before the lock, before the + # log file is created, and on a log no later line can correct. + pause_subfields_check "$we_pay" + # AMENDMENT 18(a) — the binding's three sub-fields, checked where a caller + # wrote them and APPENDED where it did not, for the three verbs clause (a) + # names. The append is the LAST thing done to the payload, after every + # separator guard above has passed on what the caller gave: the writer's own + # values are fenced by `lanes_binding_value_ok` before they go in, so the + # guards cannot be re-run on them and do not need to be. + binding_subfields_check "$we_pay" + case "$we_verb" in + STARTED|RESUMED|PAUSED) + we_pay="$(binding_subfields_add "$we_pay")" + # A PAYLOAD THIS APPEND CREATED GETS THE ARROW THAT INTRODUCES ONE. A + # lane-kind line written with no payload at all — `log STARTED lane:X`, + # which this estate's older lines and several of its callers spell — now + # has one, and Amendment 7(b) introduces a payload with `→`. Without it + # the line would carry its sub-fields bare after the object: readable by + # `LOG_AWK`, which takes an unarrowed tail as the payload, and unlike + # every other lane-kind line in the estate. + [ -n "$we_ref" ] || [ -z "$we_pay" ] || we_ref='→' ;; + esac + we_line="$(event_line "$we_verb" "$we_lane" "$we_uuid" "$we_utc" "$we_obj" "$we_ref" "$we_pay" "$we_txt")" + we_paths=("$(log_path_for "$we_lane")") + we_r6="" + case "$we_verb" in + LANDING|LANDED) we_r6="$(rule6_line "$we_verb" "$we_lane" "$we_uuid" "$we_utc" "$we_obj" "$we_pay" 2>/dev/null || :)" ;; + esac + [ -n "$we_r6" ] && we_paths+=("$LANES_PATH") + # THE EXEMPTION IS THE PATH THE LOG IS ACTUALLY AT, WHICH NEED NOT BE THE + # CANONICAL ONE YET (Amendment 15; Copilot round 4 on openRepoTools#41). + # `$we_lane` is the ROW's spelling by the time it reaches here, while the file + # may still carry the spelling it was written under until THIS write renames + # it — so a lane with uncommitted lines in its own old-cased log met the test + # that exists to refuse somebody ELSE's uncommitted work, and could not write + # at all. Only the two exemptions take it: `we_paths` is what the capture and + # the commit are given and stays exactly what it was, with the old path joining + # it below as `LOG_RENAMED_FROM` once the rename has actually happened. + we_lp="$(log_path_ci "$we_lane")" || die "lane $we_lane's object log is published twice (above), and one lane is ONE lane under any case: its log is ONE file (Amendment 15). Merge them by hand (Amendment 15(d)) and re-run. Nothing was written." 2 + # R11 — the register is EXEMPT from this first test, because it is captured + # below rather than refused. Everything ELSE this checkout has dirty is + # refused HERE: before the lock, before the capture and before anything is + # created, so that a refusal leaves the checkout exactly as it found it. + refuse_dirty_checkout "write $we_verb" "${we_paths[@]}" "$we_lp" "$LANES_PATH" + # THE LIFECYCLE SNAPSHOT AS IT STANDS BEFORE THIS LINE EXISTS (openRepoTools#91, + # Copilot round 5 on #97). It is read HERE — before the lock, before the append + # and before the commit — because it is the pre-image the follow-up at the foot + # of this function compares against: a `RUNNING` written out of an event that + # landed an hour ago must not overwrite a `SWAPPING` that began since, and the + # only evidence of which came first is what the snapshot said when this write + # started. Only the four verbs that move the lifecycle pay for the read. + we_pre=""; we_seam="" + # THE SEAM, BEFORE THE LOCK AND BEFORE A BYTE (ruling 2026-10-04): EVERY + # lane-kind line — the four that move a lifecycle, a swap's `PAUSED`, and + # Amendment 18(g)'s `HANDOFF-REQUESTED` (Copilot round 3 on #97) — is a legacy + # act on the lane itself, and a managed-owned lane, or one whose ownership + # could not be read, refuses it here. Object-kind lines (a claim, a release) + # are about the object a lane holds and are not the lane's ownership. + is_lane_verb "$we_verb" && managed_seam_refuse "$we_lane" "a $we_verb line in its object log" + case "$we_verb" in + STARTED|RESUMED|ENDED|RETIRED) + # Past the seam the lane is legacy, and that verdict is what the lifecycle + # follow-up at this function's foot is handed. `PAUSED` and + # `HANDOFF-REQUESTED` move no lifecycle and are handed nothing. + we_seam=8 + we_pre="$(lane_state_preimage "$we_lane" "$we_pay")" ;; + esac + acquire_lock + capture_register_edit "${we_paths[@]}" + handle_preexisting "${we_paths[@]}" + # AMENDMENT 15 — `ensure_log` IS BELOW THE CAPTURE AND NOT ABOVE IT, and the + # order is load-bearing rather than tidy. It may now RENAME the lane's log to + # the row's own spelling, and the amendment says that rename lands "in that + # same commit" as the write — while `handle_preexisting` exists to commit + # whatever it finds dirty in this write's pathspecs FIRST, as somebody else's + # content. Run above it, the rename was exactly what that capture would + # commit: the one act of this write, taken out of it and attributed to a peer. + # Below it, the checkout is clean when the rename happens and the rename is + # this write's own. The old path joins the pathspecs so the deletion is + # committed beside the append. + ensure_log "$we_lane" + [ -n "$LOG_RENAMED_FROM" ] && we_paths+=("$LOG_RENAMED_FROM") + # THEN re-test, against the checkout the capture left behind. The capture is + # not assumed to have worked — handle_preexisting swallows a failed commit by + # design, it never fails the call — and a register still dirty at this point + # would send commit_push down Amendment 5(d)'s skip-the-pull branch, which is + # the branch that disables the rescan deciding a race. + refuse_dirty_checkout "write $we_verb" "${we_paths[@]}" "$we_lp" + append_text_line "$we_line" "$(log_file_for "$we_lane")" + if [ -n "$we_r6" ]; then + append_text_line "$we_r6" "$LANES_FILE" + note "Rule 6 line also appended to $LANES_FILE (one commit, ${#we_paths[@]} pathspecs)" + fi + we_msg="LOG($we_lane@$WS): $we_verb $we_obj" + [ -n "$PRE_DIRTY_LANES" ] && we_msg="$we_msg + sweeps uncommitted edit to row $PRE_DIRTY_LANES" + commit_push "$we_msg" "${we_paths[@]}" + we_rc=$? + state_events_flush + release_lock + # THE LIFECYCLE SNAPSHOT FOLLOWS THE LINE THAT WAS WRITTEN (openRepoTools#91), + # and it is here — in the writer, after the lock — for the reason + # `pause_subfields_check` is here: from ANY caller, over one implementation, + # rather than in each of the commands that write a lane-kind line. A + # `STARTED` or a `RESUMED` is the confirming act of a new owner and takes the + # lane to `RUNNING`; an `ENDED` or a `RETIRED` takes it to `CLOSED`; a + # `PAUSED` moves nothing, because the two-phase transition around it is + # `lane-handoff`'s and lands `SWAPPED` only once every mandatory write has. + # AFTER `release_lock`, because `acquire_lock` is a `mkdir` mutex and not a + # reentrant one — and the follow-up takes that same mutex for itself, around + # the read of the pre-image and the replacement of the snapshot together. It + # never fails the event and it is silent for a lane with no control root, which + # is every lane that has not started under Amendment 11(c) — the cutover rule + # of Amendment 7(i), not a failure. + lane_state_follow "$we_lane" "$we_verb" "$we_pay" "$we_uuid" "$we_pre" "$we_seam" + return "$we_rc" +} + +# A read fetches first — there is no index, so "current" means "after a fetch". +# +# AND WHERE IT DID NOT FETCH IT RECORDS WHY, so the one caller with a freshness +# line can correct it (#26, the fail-closed family one layer out, `lanes:411`). +# FOUR of the five ways out of here never reach the fetch at all — +# `LANES_NO_GIT=1`, `LANES_NO_FETCH=1`, a `$LANES_REPO` that is not a checkout, +# and an `origin/$LANES_BRANCH` `ls-remote` could not confirm, THE TIMEOUT AMONG +# THEM — and every one of them answered 0 in silence. `lanes --fetch` reads this +# file's stderr for one phrase and prints *"as of a fetch just now"* when it does +# not find it, so all four printed that sentence over a fetch that never ran. +# `43b6320` closed the LOUD path, where the fetch was attempted and failed; this +# is the quiet one. +# +# IT IS RECORDED HERE AND SAID IN THE `lanes` ARM, not printed here, because +# EVERY subcommand in this file runs this function and only the one with a +# `--fetch` flag has a freshness line to be wrong. A note on every path would put +# a paragraph in front of every launch on the workstation to fix a sentence that +# is printed in one place. +LOG_SYNC_FETCH="" # yes · fell-back · else WHY this run did not fetch +log_sync() { + # THE CACHE ABOVE IS THE REF AS IT STOOD; a fetch moves the ref, so it is + # dropped here rather than read past. Both copies of it: the variable this + # shell holds and the file every subshell reads (ruling 12). + LANES_REGISTER_CACHE="" + ls_rc="${SE_CACHE_FILE:+$SE_CACHE_FILE.register}"; [ -n "$ls_rc" ] && rm -f -- "$ls_rc" + # AND AMENDMENT 16's ALIAS TABLE, for the same reason and in the same breath: + # it is read from `origin/` beside the register and a fetch moves that + # ref. A rename lands both files in ONE commit, so a cache that kept one and + # dropped the other is exactly the disagreement the single commit prevents. + lane_alias_flush + LOG_SYNC_FETCH="" + [ "$NO_GIT" = 1 ] && { LOG_SYNC_FETCH="LANES_NO_GIT=1 is set, so nothing in this run touches git"; return 0; } + [ "${LANES_NO_FETCH:-0}" = 1 ] && { LOG_SYNC_FETCH="LANES_NO_FETCH=1 is set in this environment"; note "LANES_NO_FETCH=1 — not fetching; reading origin/$LANES_BRANCH as the ref already stands here"; return 0; } + git -C "$LANES_REPO" rev-parse --git-dir >/dev/null 2>&1 || { LOG_SYNC_FETCH="$LANES_REPO is not a git checkout"; return 0; } + if ! remote_has_branch; then + LOG_SYNC_FETCH="origin/$LANES_BRANCH could not be reached" + [ "$GIT_TIMED_OUT" = 1 ] && LOG_SYNC_FETCH="$LOG_SYNC_FETCH — ls-remote timed out after ${GIT_TIMEOUT}s" + return 0 + fi + if git_net -C "$LANES_REPO" fetch -q origin "$LANES_BRANCH" 2>/dev/null; then + LOG_SYNC_FETCH=yes + else + LOG_SYNC_FETCH=fell-back + note "fetch $([ "$GIT_TIMED_OUT" = 1 ] && printf 'timed out after %ss' "$GIT_TIMEOUT" || printf 'failed') — reading the logs as they stand locally" + fi + return 0 +} + +# ------------------------------------------------------------------- who +# +# Exit 0 found, 8 no record. + +print_holder_detail() { + ph_lane="$1"; ph_obj="$2"; ph_rc=0 + ph_home="$(home_of_lane "$ph_lane" 2>/dev/null || :)" + printf ' home %s\n' "${ph_home:-unknown (pre-cutover lane: no STARTED line)}" + ph_rowid="$(last_session_id_of_lane "$ph_lane" 2>/dev/null || :)" + if lane_is_elsewhere "$ph_lane"; then + # Session records are local files. This machine cannot see another + # workstation's, so it must not say NOT LIVE about one. + printf ' holder lane %s — UNKNOWN (records are local to %s; ask @%s or read its handoff)\n' \ + "$ph_lane" "$(lane_workstation "$ph_lane")" "$ph_lane" + else + # 0 / 8 / anything else, and never two of them conflated (R22): a read this + # workstation could not perform is UNKNOWN, exactly as another workstation's + # records are. NOT LIVE is a claim, and it is the claim that sends a reader + # to `claim --force` against a lane that is running. + ph_h="$(live_holder "$ph_lane" 2>/dev/null)"; ph_rc=$? + case "$ph_rc" in + 0) + IFS="$US" read -r ph_hid ph_target ph_hname ph_hpid ph_where <`, printed with the session and profile beside it so a person can + # check first, and run by that person (clause (f)). + # + # Silent where there are none, where the lane is on another workstation (its + # records are not local and this machine must not claim about them), and where + # the read itself failed — an unreadable record is not an assertion that a + # holder is absent, and `who`'s own `UNKNOWN` line has already said so. + if ! lane_is_elsewhere "$ph_lane"; then + ph_idle="$(idle_holders "$ph_lane" 2>/dev/null)" + # NOT a pipe: `printf ... | while read; do …; done` runs the loop on the + # STRIPPED command substitution with no trailing newline, so `read` hits + # EOF on the (only) line before it ever completes one, returns failure, + # and the loop body never runs at all — the one-holder case is exactly + # the common case, and a pipe here would print nothing, ever. A here-string + # always terminates the last line, which is why `lane-start`'s own reader + # of this same helper (above) uses one instead of a pipe. + if [ -n "$ph_idle" ]; then + while IFS="$(printf '\t')" read -r ph_isid ph_ipid ph_ikind ph_iprof; do + [ -n "$ph_isid" ] || continue + printf ' idle lane %s — an EARLIER session id of this row is still held: session %s, pid %s (kind %s, profile %s). History, not an alternative — retire it: kill %s\n' \ + "$ph_lane" "$ph_isid" "$ph_ipid" "${ph_ikind:-none}" "${ph_iprof:-unknown}" "$ph_ipid" + done <<<"$ph_idle" + fi + fi + printf ' address @%s · claude --resume %s\n' "$ph_lane" "${ph_rowid:-}" + ph_ho="$(handoff_of_lane "$ph_lane" 2>/dev/null || :)" + [ -n "$ph_ho" ] && printf ' handoff %s\n' "$ph_ho" + printf ' log %s\n' "$(log_path_for "$ph_lane")" + ph_objrepo="$(object_repo "$ph_obj")" + if [ -n "$ph_home" ] && [ -n "$ph_objrepo" ] && [ "$ph_objrepo" != "$ph_home" ] && ! same_project "$ph_home" "$ph_objrepo"; then + printf ' CROSS-REPO %s is not lane %s'"'"'s home (%s)\n' "$ph_objrepo" "$ph_lane" "$ph_home" + fi +} + +who_object() { + wo_obj="$1" + wo_states="$(state_events | lane_states_on "$wo_obj")" + if [ -z "$wo_states" ]; then + printf 'no record of %s in any lane log\n' "$wo_obj" + printf ' (a lane with no log file is pre-cutover: see its row'"'"'s state cell in LANES.md)\n' + return 8 + fi + printf 'object %s\n' "$wo_obj" + wo_held=0 + while IFS="$US" read -r s_utc s_lane s_verb s_uuid s_ws s_o s_ref s_pay s_txt s_file s_line; do + [ -n "${s_verb:-}" ] || continue + wo_sup="$(superseded_by "$wo_obj" "$s_lane" "$s_verb")" + if [ -n "$wo_sup" ]; then + printf 'super. lane %-22s %-9s %s (%s ago) — superseded by TAKEOVER (lane:%s) at %s\n' \ + "$s_lane" "$s_verb" "$s_utc" "$(age_of "$s_utc")" "${wo_sup%@*}" "${wo_sup#*@}" + printf ' this lane no longer holds it; it closes its own line with: lanes-edit.sh release %s "taken over by %s"\n' "$wo_obj" "${wo_sup%@*}" + elif is_open_verb "$s_verb"; then + printf 'HOLDS lane %-22s %-9s %s (%s ago)%s\n' "$s_lane" "$s_verb" "$s_utc" "$(age_of "$s_utc")" "${s_pay:+ ${s_ref:-} $s_pay}" + wo_held=1 + else + printf 'closed lane %-22s %-9s %s (%s ago)%s\n' "$s_lane" "$s_verb" "$s_utc" "$(age_of "$s_utc")" "${s_pay:+ ${s_ref:-} $s_pay}" + fi + # A line written with --no-github is not yet a Rule 1 claim: the comment a + # person outside this estate reads does not exist. + case "${s_txt:-}" in + no-github|'no-github;'*) printf ' local only — no GitHub claim comment\n' ;; + "") : ;; + *) printf ' %s\n' "$s_txt" ;; + esac + done </dev/null)" || wl_fkrc=$? + case "$wl_fkrc" in + 0 | 8) : ;; + *) printf 'UNKNOWN this workstation'"'"'s session records could not be read, so whether a live FORK of lane %s'"'"'s transcript is running is NOT established — which is not the same as none. See: lanes-edit.sh forks %s\n' "$wl_lane" "$wl_lane" ;; + esac + if [ -n "$wl_fk" ]; then + while IFS="$(printf '\t')" read -r wl_fid wl_fpid wl_fkind wl_fcwd; do + [ -n "${wl_fid:-}" ] || continue + printf 'DEFECT %s is a live FORK of this lane'"'"'s transcript (pid %s, %s, cwd %s) — never a holder, and it must not write the register. Retire it: lane-end %s --retire %s\n' \ + "$wl_fid" "$wl_fpid" "${wl_fkind:-interactive}" "${wl_fcwd:-unknown}" "$wl_lane" "$wl_fpid" + done < main` clause +# at all — 284 of 308 on the day this was measured — so keying a LANDED on the +# repository it names keyed 284 of them on the empty string, where they could +# never close the repository-qualified LANDING they belonged to: `who --landing` +# reported 201 phantom merge holds across five repositories, every one of them +# landed long ago, on a register whose genuinely open count was one. So the +# PAIRING is by (lane, PR) — the LANDED closes the most recent LANDING of that +# lane and PR that is still unmatched, and the pair’s repository is the +# LANDING’s — while the RESULT still keys on (lane, repository, PR), which is +# what keeps a LANDED on one repository from closing a LANDING on another. +# AND A LANDED THAT NAMES A REPOSITORY PREFERS A LANDING ON THAT REPOSITORY +# (R24, Addendum 6). Only a LANDED with NO `into main` clause takes the +# most recent unmatched LANDING regardless — it has said nothing about where it +# landed, so the LANDING is the only thing that can say. One that DOES name a +# repository takes the most recent unmatched LANDING naming the same one, and +# is reported as an `unpaired LANDED` — closing nothing — only when there is no +# such LANDING at all. Without the preference, a lane with two LANDINGs open on +# ONE PR number in two repositories that lands the EARLIER one, naming its +# repository, was unpaired and both holds stayed open until the second landed. +# The answer is identical everywhere else, including the (lane, repository, PR) +# result key: a LANDED on one repository still closes no LANDING on another. +# +# The repository is lower-cased IN THE KEY ONLY: the register spells one +# repository four ways in a week, and a LANDED spelled `OpsxFactory` must still +# close a LANDING spelled `opsXfactory`. +# +# AND BOTH SIDES GO THROUGH `lanes/repos.tsv` FIRST (R29, Addendum 7). Case is +# only half of it: the register writes `OpsxFactory` and `opensoft/OpsxFactory` +# for ONE repository — 23 Rule 6 lines against 70 at `8f9c04d` — and +# `codexFactory`, `codeXfactory/codexFactory` and `opensoft/codexFactory` for +# another. Compared literally, a LANDED spelled one way does not close the +# LANDING spelled the other: it reads as an `unpaired LANDED`, the hold stays +# open, and over-reporting a merge hold is the direction that stalls other +# lanes' merges. So every `into main` is resolved AS IT IS PARSED, which +# makes the pairing, R24's preference and the (lane, repository, PR) result key +# agree by construction — the key's repository is the canonical spelling, and +# an alias the table does not know keeps its own, case-blind like every other. +# +# WHAT THAT IS WORTH TODAY, measured read-only over `origin/main` at `6fa966b`: +# the VERDICT does not move — 1 open LANDING (lane browser-ui-repair's PR #401, +# genuinely in flight) and 0 unpaired LANDED, before this change and after it. +# No (lane, PR) pair in the register mixes its spellings YET, so this is a +# guard and not a repair, and it is worth saying so rather than claiming a hold +# it did not clear. What it does move there is the KEY: 17 result-key spellings +# collapse to the 11 repositories they name, and two LANDINGs a retry spelled +# two ways are one hold instead of two. +# +# The table is handed in through the ENVIRONMENT, as `LANES_RULE6_ALIASES`, +# one `\037` per line — because awk cannot read +# `repos.tsv` for itself here (this program's stdin is the register) and +# because `awk -v`, which is where it used to go, carries ONE LINE: see +# `who_landing` for what a many-line `-v` does on macOS's awk. +# +# BOTH LAYERS, SHIPPED FIRST (Amendment 9(b)). This is the second reader of the +# table — `alias_lookup` is the other — and it layers them the same way by +# reading the shipped file before the override, so the LAST assignment to an +# alias wins and an override row REPLACES the shipped row for that alias while +# adding rows the shipped table does not carry. One map, emitted in the order +# the aliases were first seen, so the output is stable. +rule6_aliases() { + r6_files=() + for r6_tsv in "${LANES_REPOS_TSV_SHIPPED:-}" "${LANES_REPOS_TSV:-}"; do + [ -n "$r6_tsv" ] && [ -f "$r6_tsv" ] || continue + r6_files+=("$r6_tsv") + done + [ "${#r6_files[@]}" -gt 0 ] || return 0 + awk -F'\t' ' + /^[ \t]*#/ { next } + NF >= 2 { + a = $1; b = $2 + gsub(/^[ \t]+|[ \t]+$/, "", a); gsub(/^[ \t]+|[ \t]+$/, "", b) + if (a != "" && b != "") { + k = tolower(a) + if (!(k in seen)) { seen[k] = 1; ord[++n] = k } + m[k] = b + } + } + END { for (i = 1; i <= n; i++) printf "%s\037%s\n", ord[i], m[ord[i]] }' "${r6_files[@]}" +} + +RULE6_AWK=' +function trim(s) { sub(/^[ \t]+/, "", s); sub(/[ \t]+$/, "", s); return s } +function canon(r, l) { l = tolower(r); return (l in A) ? A[l] : r } +BEGIN { + na = split(ENVIRON["LANES_RULE6_ALIASES"], ar, "\n") + for (ai = 1; ai <= na; ai++) { ap = index(ar[ai], "\037") + if (ap > 1) A[substr(ar[ai], 1, ap - 1)] = substr(ar[ai], ap + 1) } +} +/^(LANDING|LANDED) — / { + line = $0 + verb = substr(line, 1, index(line, " ") - 1) + lane = ""; pr = ""; repo = ""; utc = "" + if (match(line, /lane [A-Za-z0-9._-]+/)) lane = substr(line, RSTART + 5, RLENGTH - 5) + if (match(line, /PR #[0-9]+/)) pr = substr(line, RSTART + 4, RLENGTH - 4) + if (match(line, /into [A-Za-z0-9\/._-]+ main/)) repo = canon(substr(line, RSTART + 5, RLENGTH - 10)) + if (match(line, /[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9](:[0-9][0-9])?Z/)) utc = substr(line, RSTART, RLENGTH) + if (lane == "" || pr == "") next + g = lane "\037" pr + if (verb == "LANDING") { + k = g "\037" tolower(repo) + if (!(k in ST)) { gk[g, ++gn[g]] = k } + ST[k] = "LANDING"; U[k] = utc; L[k] = lane; P[k] = pr; R[k] = repo; O[k] = NR + next + } + best = ""; bord = -1; bestr = ""; bordr = -1 + for (i = 1; i <= gn[g]; i++) { kk = gk[g, i] + if (ST[kk] != "LANDING") continue + if (O[kk] > bord) { bord = O[kk]; best = kk } + if (repo != "" && tolower(repo) == tolower(R[kk]) && O[kk] > bordr) { bordr = O[kk]; bestr = kk } } + if (bestr != "") best = bestr # R24: a LANDED that NAMES a repository + if (best == "") next + if (repo != "" && tolower(repo) != tolower(R[best])) { + printf "UNPAIRED%c%s%c%s%c%s%c%s%c%s\n", 31, lane, 31, pr, 31, utc, 31, repo, 31, R[best] + next + } + ST[best] = "LANDED"; U[best] = utc; O[best] = NR +} +END { for (k in ST) printf "%s%c%s%c%s%c%s%c%s%c\n", ST[k], 31, L[k], 31, P[k], 31, U[k], 31, R[k], 31 }' + +# Rule 6's window, in minutes. A LANDING past it with no LANDED is still a +# line somebody wrote and is still listed — but it is marked, because reporting +# a 253-day-old LANDING as a live merge hold with nothing to say it is not one +# is how the estate ends up holding its merges for a lane that stopped. +LANDING_MINUTES="${LANES_LANDING_MINUTES:-30}" + +# The lane logs are SECONDARY here and are reported after the register: every +# lane writes its Rule 6 line into LANES.md, pre- and post-cutover alike, and +# that is what decides the hold. A lane's own LANDING/LANDED is evidence +# beside it, never instead of it. +who_landing_logs() { + wll_repo="$1"; wll_rows="" + wll_rows="$(state_events | awk -v sep="$US" -v repo="$wll_repo" ' + function pos(pf, pn) { return pf "\034" sprintf("%09d", pn) } + BEGIN { FS = sep } + $6 ~ /^lane:/ { next } + { + o = $6; r = o; sub(/#.*$/, "", r); sub(/:openspec\/changes\/.*$/, "", r) + if (tolower(r) != tolower(repo)) next + # The LAST line this lane wrote on the object, in FILE ORDER (R14). + # A LANDED is often written in the same second as the LANDING it closes, + # and on a workstation whose clock steps back it is stamped before it. + k = $2 sep o + p = pos($10, $11) + if (!(k in P) || p >= P[k]) { P[k] = p; u[k] = $1; V[k] = $3; L[k] = $2; O[k] = o } + } + END { for (k in P) if (V[k] == "LANDING" || V[k] == "LANDED") + printf "%s%c%s%c%s%c%s\n", V[k], 31, L[k], 31, O[k], 31, u[k] }' \ + | LC_ALL=C sort -t"$US" -k3,3 -k2,2)" + [ -n "$wll_rows" ] || return 0 + printf 'from lane logs (secondary):\n' + while IFS="$US" read -r wl_verb wl_lane wl_obj wl_utc; do + [ -n "${wl_verb:-}" ] || continue + printf ' %-8s %s lane %s, %s (%s ago)\n' "$wl_verb" "$wl_obj" "$wl_lane" "$wl_utc" "$(age_of "$wl_utc")" + done </dev/null || :)"; wd_c="${wd_c:-$wd_r}" + [ "$(lc "$wd_c")" = "$(lc "$wd_repo")" ] || continue + wd_stale="" + older_than_minutes "$wd_utc" "$LANDING_MINUTES" && wd_stale=" STALE (Rule 6: >${LANDING_MINUTES} min)" + printf 'LANDING %s#%s lane %s, %s (%s ago)%s\n' "$wd_repo" "$wd_pr" "$wd_lane" "$wd_utc" "$(age_of "$wd_utc")" "$wd_stale" + wd_n=$((wd_n + 1)) + done <` must read it as one. 8 is reserved for absence. + [ "$wd_n" = 0 ] && printf 'none open — no LANDING on %s is still open (read from LANES.md'"'"'s Rule 6 lines)\n' "$wd_repo" + # A LANDED that names THIS repository while the LANDING it would close is on + # another closes nothing (R17), and is said so rather than dropped: an + # append-only register is never rewritten, so a line no tool mentions again is + # a line nobody will ever reconcile. + while IFS="$US" read -r wd_verb wd_lane wd_pr wd_utc wd_r wd_other; do + [ "${wd_verb:-}" = UNPAIRED ] || continue + wd_c="$(alias_lookup "${wd_r:-}" 2>/dev/null || :)"; wd_c="${wd_c:-$wd_r}" + [ "$(lc "$wd_c")" = "$(lc "$wd_repo")" ] || continue + printf 'unpaired LANDED %s#%s lane %s, %s — the open LANDING for (lane %s, PR #%s) is on %s, so this closes nothing\n' \ + "$wd_repo" "$wd_pr" "$wd_lane" "$wd_utc" "$wd_lane" "$wd_pr" "${wd_other:-an unnamed repository}" + done <:; workstation `, and a lane is +# SWAPPED on a workstation when that PAUSED is its LAST lane-kind line. +# +# Both reads here are READ-ONLY and neither ever writes. `swapped` is what a +# launcher asks when the tmux window name is gone — a restart opens a NEW +# tmux session, which is precisely why the window name cannot carry the lane +# across one. `session-start` is the SessionStart hook's whole output. + +# The register's own spelling of a lane whose name matches $1 ignoring case, +# read from `origin/` like every other state read (R19). Rule 10's wire +# form is lowercase and a tmux window may carry either, while the row's token is +# camel (`openRepoProject-1`): an exact lookup alone loses the lane. +# +# AMENDMENT 16(e) — AND IT RESOLVES A FORMER NAME, through the same seat every +# other reader takes. Clause (e) names the `SessionStart` block among the +# readers that resolve, and this is the read behind it: a window still carrying +# the name a lane had before its rename would otherwise orient the new session +# to "no lane bound to this window" — which is the one thing that block exists +# not to say — while the lane's row, log and handoff are all a `lane-rename` +# away under another name. +# +# `rows_named_ci_alias` IS THAT SEAT AND THIS IS `head -n1` OF IT, which is +# exactly what the `exit` in the awk above was: one answer and no refusal. The +# hook never refuses, so where two rows differ only by case this still answers +# with the first of them and `canon_lane` — the read every WRITER goes through +# — is where that pair is refused. +# 0 + one spelling (or nothing) · 5 the alias table could not be READ +# The 5 is carried for `rows_named_ci_alias`-s reason: `session_start_block` is +# a hook and may not refuse, but it must not print "no lane bound to this +# window" about a window whose name it could not resolve. +lane_named_ci() { + lnc_rc=0 + lnc_out="$(rows_named_ci_alias "$1" 2>/dev/null)" || lnc_rc=$? + [ "$lnc_rc" = 5 ] && return 5 + printf '%s\n' "$lnc_out" | grep . | head -n1 + return 0 +} + +# The lane whose row's SESSION CELL names — the second resolution the +# hook has, for a window that carries no lane name. ONLY the session cell is +# read: state cells quote other lanes' ids all the time ("RESUMED by ", +# "handed off to "), and one of those is not this session's lane. +lane_of_session() { + los_id="$(lc "${1-}")" + [ -n "$los_id" ] || return 1 + register_text | awk -F'|' -v id="$los_id" ' + substr($0,1,1) != "|" { next } + { + if (index(tolower($3), id) == 0) next + p1 = index($2, "`"); if (p1 == 0) next + rest = substr($2, p1 + 1); p2 = index(rest, "`"); if (p2 == 0) next + print substr(rest, 1, p2 - 1); exit + }' +} + +# ============================================================================ +# AMENDMENT 11 — THE RECORD'S SUB-FIELDS, AND THE READS BUILT ON THEM +# ============================================================================ +# +# Amendment 11 clause (c) gives the lane's `STARTED`/`RESUMED` lines and the +# swap record two new payload sub-fields, `dir ` and `profile `, +# beside Amendment 8(b)'s `window`, which gains a second ref. Clause (h) turns +# the reads of them into subcommands, for the reason Amendment 7(d) already +# gives `live-holder` and `lane-objects`: EACH READ EXISTS SO THAT SEVERAL +# CALLERS SHARE ONE IMPLEMENTATION. `window-lane` has three (the launcher's +# precedence 3, `/restart`'s step 2(c), the `/lane-swap` skill's step 1); +# `session-lane` has two (`/restart`'s step 2(b) and the SessionStart hook); +# `lane-dir` has four. A rule implemented once cannot be implemented three +# ways, which is exactly how the launcher, the skill and `/restart` would come +# to disagree about which lane a window is. + +# ONE PARSER OF A PAYLOAD'S SUB-FIELDS, AND ONE UNQUOTER. +# +# Amendment 7(b)'s grammar: sub-fields are separated by `; `, and SEVERAL REFS +# INSIDE ONE SUB-FIELD ARE SEPARATED BY SPACES — which is what the `window` +# sub-field's `: <@id>` relies on. So an unquoted +# `dir $HOME/my projects/x` (unquoted) parses as two refs and hands back a truncated +# path, and clause (c)'s rule is that the WRITER QUOTES a value containing a +# space and EVERY READER takes a value opening with `"` as running to its +# closing `"`, stripping both. +# +# Two modes, because the grammar has two kinds of value: +# (default) ONE REF — the value up to its first space, or the whole of a +# quoted value. `dir` and `profile` are read this way. +# all EVERY REF — the whole sub-field, which is what `window` is: +# two refs that a caller splits itself. +payload_subfield() { # [all] + awk -v pay="$1" -v want="$2" -v mode="${3-}" ' + BEGIN { + want = want " " + n = split(pay, sf, "; ") + for (i = 1; i <= n; i++) { + if (substr(sf[i], 1, length(want)) != want) continue + v = substr(sf[i], length(want) + 1) + sub(/^[ \t]+/, "", v); sub(/[ \t]+$/, "", v) + if (substr(v, 1, 1) == "\"") { + q = index(substr(v, 2), "\"") + if (q > 0) { print substr(v, 2, q - 1); exit } + } + if (mode != "all") { sub(/ .*$/, "", v) } + print v; exit + } + }' +} + +# ---------------------------------------- AMENDMENT 17(b): THE TWO SUB-FIELDS +# +# `agent ` and `transcript `, VALIDATED BY THE WRITER. Amendment +# 17(b) gives the `PAUSED` payload both; nothing else in this file could check +# them, because a payload is free text to `write_event` — and this log is +# APPEND-ONLY, so a sub-field written wrong is wrong for ever and no later line +# corrects it. The check is the same shape `valid_uuid` gives the session field +# under clause (e): the WRITER is the gate, from any caller. +# +# WHAT EACH ADMITS, and why the pattern is the rule rather than a list: +# agent A MANIFEST KEY — letters, digits, `.`, `_`, `-`. It is what +# `lane-start --agent ` reads back to choose a launcher, so +# a value carrying a space or a `;` is a value that would come +# back as two sub-fields or as an argument nobody meant. The +# pattern is also how this sub-field gets SPEC rev 6 §5's `; ` +# rule without a token of its own — the same argument clause (c)'s +# `profile` takes. +# transcript THE AGENT'S OWN RESUMABLE ID, or the literal `none` — which is +# an ANSWER ("this agent has no resumable id") and not a gap. +# Claude's is a uuid; another agent's is whatever that agent +# prints, so the shape is the same manifest key rather than +# `valid_uuid`, which would refuse every agent but one. +# +# A PAYLOAD CARRYING NEITHER IS VALID AND STAYS VALID. Every record written +# before this amendment carries neither, and Amendment 7(i)'s cutover rule is +# that a reader finding none says so rather than assuming one. The check fires +# only on a sub-field that is THERE. +# THE TWO ARE WRITTEN TOGETHER OR NOT AT ALL, AND AN EMPTY ONE IS NOT AN +# ABSENT ONE (Copilot rounds 1 and 2 on openRepoTools#47). The first shape of +# this gate entered on either sub-field and then accepted each empty result +# independently, which let a HALF record through: `agent codex` with no +# transcript, or `transcript ` with no agent, both of which `lane-start` +# reads one field of and defaults the other — launching Claude on a codex id, +# or codex on none. And a sub-field written EMPTY (`; agent ; …`) parsed +# identically to one that was never there, so a malformed line was indexed as a +# pre-amendment one for ever, in a log nothing rewrites. +# +# PRESENCE IS READ OFF THE SUB-FIELDS, never off the whole line: `dir +# /srv/agent-work` carries the letters and is not the field. +pause_subfields_check() { # + psc_pay="${1-}" + case "$psc_pay" in *agent*|*transcript*) : ;; *) return 0 ;; esac + psc_has_a=0; psc_has_t=0 + psc_rest="$psc_pay" + while : ; do + psc_one="${psc_rest%%; *}" + case "$psc_one" in + agent | 'agent '*) psc_has_a=1 ;; + transcript | 'transcript '*) psc_has_t=1 ;; + esac + case "$psc_rest" in + *'; '*) psc_rest="${psc_rest#*; }" ;; + *) break ;; + esac + done + # A PAYLOAD CARRYING NEITHER IS VALID AND STAYS VALID: every record written + # before this amendment carries neither, and Amendment 7(i)'s cutover rule is + # that a reader finding none says so rather than assuming one. + if [ "$psc_has_a" = 0 ] && [ "$psc_has_t" = 0 ]; then return 0; fi + # EACH FIELD THAT IS THERE IS READ WITH `all`, WHICH IS THE WHOLE SUB-FIELD + # AND NOT ITS FIRST REF. The default mode ends a value at its first space — + # the rule `dir` and `profile` are read by — so `agent not a key` would come + # back as `not`, a perfectly good manifest key, and the check would pass the + # very value it exists to refuse. A gate reads what was written, never what a + # reader would make of it. THE VALUE IS JUDGED BEFORE THE PAIR, so a payload + # that is both malformed and half-written is refused for the malformation, + # which is the thing the writer of it can see in what they typed. + if [ "$psc_has_a" = 1 ]; then + psc_a="$(payload_subfield "$psc_pay" agent all)" + case "$psc_a" in + '') + die "the record's \`agent\` sub-field is THERE and EMPTY, which is not the same as absent: no reader can tell it from a pre-amendment record, so every one of them would default to \`claude\` for ever (Amendment 7(i)'s cutover rule is about a field that was never written, not one written blank). Write the agent, or write neither sub-field. Nothing was written" 2 ;; + *[!A-Za-z0-9._-]*) + die "the record's \`agent\` sub-field is a manifest key — letters, digits, '.', '_', '-' — and '$psc_a' is not one (Amendment 17(b)). Nothing was written: this log is append-only, and \`lane-start --agent\` launches on what it reads back from this field" 2 ;; + esac + fi + if [ "$psc_has_t" = 1 ]; then + psc_t="$(payload_subfield "$psc_pay" transcript all)" + case "$psc_t" in + '') + die "the record's \`transcript\` sub-field is THERE and EMPTY. The word for an agent with no resumable id is \`none\`, which is an ANSWER; blank is a gap no reader can tell from a pre-amendment record. Nothing was written" 2 ;; + *[!A-Za-z0-9._-]*) + die "the record's \`transcript\` sub-field is the agent's own resumable id, or the word 'none' — '$psc_t' is neither (Amendment 17(b)). Nothing was written" 2 ;; + esac + fi + # AND THE PAIR. `lane-start` reads ONE of these fields to choose a launcher + # and the OTHER to choose what it hands that launcher, so a record carrying + # one of them makes it default the other: Claude launched on a codex id, or + # codex launched on none, out of a line nothing rewrites. + if [ "$psc_has_a" != "$psc_has_t" ]; then + psc_only=transcript + [ "$psc_has_a" = 1 ] && psc_only=agent + die "Amendment 17(b)'s two sub-fields are written TOGETHER or not at all, and this payload carries only \`$psc_only\`. A half record is worse than none: \`lane-start\` reads the field that is there and DEFAULTS the one that is not, so it would launch the wrong agent, or the right one on an id that is not its. Write both (\`agent ; transcript \`), or neither. Nothing was written — this log is append-only" 2 + fi + return 0 +} + +# ------------------------- AMENDMENT 18(a): THE BINDING'S THREE SUB-FIELDS +# +# WRITTEN BY THE WRITER, ONCE, FOR EVERY CALLER — the argument this file already +# makes for putting the container refusal at the dispatcher: *"nine copies of one +# rule is how eight of them would come to disagree."* `lane-start` writes +# `STARTED`/`RESUMED`, `lane-handoff` writes `PAUSED`, and clause (e)'s forced +# `PAUSED` is written here; all three go through `write_event`, so the three +# facts are appended HERE and no boundary script carries a copy of the probe. +# +# THE THREE VERBS ARE CLAUSE (a)'s THREE, AND `ENDED`/`RETIRED` ARE NOT AMONG +# THEM. Clause (a) is the RULE and it names `STARTED`, `RESUMED` and `PAUSED`; +# clause (b) reads the binding out of `STARTED`/`RESUMED` alone and a `PAUSED` +# releases it. Amendment 18's Adoption list adds `lane-end`'s two "for the +# record", and they are left out deliberately: Amendment 7(b) says *"`PAUSED`, +# `RESUMED`, `ENDED` and `RETIRED` take no payload"*, Amendment 11 clause (c) +# narrows that for `RESUMED` as **edit 1 of six** and says in the same breath +# that *"`ENDED` and `RETIRED` stay payload-free"*, and `lane-end` already +# refuses to write one for exactly that reason (its own block argues it at +# length: a payload there is a SEVENTH edit to in-force text where the count is +# six and the six are ratified, `R-A11-15`). A verb that RELEASES a binding has +# no binding to describe, so nothing is lost by the omission and a ratified +# count is not quietly broken by it. +# +# APPENDED AND NEVER SUBSTITUTED: a payload that already carries one of the +# three is the caller's own and is left exactly as it is, so a test seam, a +# replay and a future writer that fills them in itself all keep their value. +# They go LAST, after Amendment 11(c)'s and Amendment 17(b)'s, on the same +# cutover argument those took: a reader written before this clause stops at the +# sub-field it knows, and one that finds none says so (Amendment 7(i)). +# +# A VALUE THAT WOULD MAKE THE LINE UNREADABLE COSTS ITS OWN SUB-FIELD AND NEVER +# THE LINE (`R-A11-11`'s posture): the drop is printed, and the binding still +# names whichever of the three it could write. +binding_subfields_add() { # ; prints the payload with the three appended + bsa_pay="${1-}" + bsa_drop="" + # READ LIVE AT THE WRITE, which is what this clause says and what the + # 2026-09-15T12:17Z measurement means: a container's `hostname` names THAT + # container for as long as it exists and names nothing afterwards. The globals + # are a process-start convenience for the reads; the line about to be appended + # to an append-only log takes the probe again. + lanes_binding_probe + for bsa_f in host os container; do + case "$bsa_f" in + host) bsa_v="$LANES_HOST_NAME" ;; + os) bsa_v="$LANES_OS_NAME" ;; + container) bsa_v="$LANES_CONTAINER_NAME" ;; + esac + # Already there: the caller's, untouched. + [ -n "$(payload_subfield "$bsa_pay" "$bsa_f" all)" ] && continue + case "$bsa_pay" in "$bsa_f "*) continue ;; esac + if ! lanes_binding_value_ok "$bsa_v"; then + bsa_drop="$bsa_drop $bsa_f=${bsa_v:-}" + continue + fi + # AND `os` IS ONE OF FOUR WORDS WHEREVER IT COMES FROM (Copilot round 5 on + # openRepoTools#83). `binding_subfields_check` refuses a caller-written `os` + # that is none of them; this path takes the LAUNCHER'S export, which is + # nobody's to validate but this writer's — `LANES_OS=plan9` would otherwise + # be persisted on every binding line as a value the same file refuses when a + # caller supplies it, in a log nothing rewrites. Dropped rather than + # refused, like every other value here: `host` and `container` are what + # clause (b) reads, and a lane-kind line is never lost over a field no + # reader decides anything by. + if [ "$bsa_f" = os ]; then + case "$bsa_v" in + linux|macos|wsl|windows) : ;; + *) bsa_drop="$bsa_drop os=$bsa_v"; continue ;; + esac + fi + bsa_pay="${bsa_pay:+$bsa_pay; }$bsa_f $bsa_v" + done + [ -z "$bsa_drop" ] || note "DROPPED binding sub-field (the line is still written, Amendment 18(a)):$bsa_drop — a value carrying a space, ',', ';', '\"' or ' — ' is a line this log's own parser could never read again, and an \`os\` that is none of linux, macos, wsl, windows is a value this file's own writer refuses when a caller supplies it" + printf '%s' "$bsa_pay" +} + +# AND THE VALUES A CALLER WRITES ITSELF ARE CHECKED, for the reason +# `pause_subfields_check` gives for Amendment 17(b)'s two: a payload is free +# text to `write_event`, this log is append-only, and `binding` launches — and +# refuses — on what it reads back. The check fires only on a sub-field that is +# THERE, so every line written before this clause stays valid (Amendment 7(i)). +binding_subfields_check() { # + bsc_pay="${1-}" + case "$bsc_pay" in *host*|*os*|*container*) : ;; *) return 0 ;; esac + for bsc_f in host os container; do + bsc_has=0 + bsc_rest="$bsc_pay" + while : ; do + bsc_one="${bsc_rest%%; *}" + case "$bsc_one" in "$bsc_f" | "$bsc_f "*) bsc_has=1 ;; esac + case "$bsc_rest" in + *'; '*) bsc_rest="${bsc_rest#*; }" ;; + *) break ;; + esac + done + [ "$bsc_has" = 1 ] || continue + bsc_v="$(payload_subfield "$bsc_pay" "$bsc_f" all)" + case "$bsc_v" in + '') + die "the record's \`$bsc_f\` sub-field is THERE and EMPTY, which is not the same as absent: no reader can tell it from a line written before Amendment 18(a), so every one of them would read this lane's binding as the window on the row's workstation for ever. Write the value, or leave the sub-field out and the writer fills it in. Nothing was written" 2 ;; + *[!A-Za-z0-9._:-]*) + die "the record's \`$bsc_f\` sub-field is one ref of Amendment 7(b)'s grammar — letters, digits, '.', '_', '-', ':' — and '$bsc_v' is not one (Amendment 18(a)). A space there is a SECOND ref and a ';' is a second sub-field, in a log nothing rewrites. Nothing was written" 2 ;; + esac + if [ "$bsc_f" = os ]; then + case "$bsc_v" in + linux|macos|wsl|windows) : ;; + *) die "the record's \`os\` sub-field is one of linux, macos, wsl, windows (Amendment 18(a)) — '$bsc_v' is none of them. The probe writes the first three and only a launcher on the Windows host itself writes the fourth. Nothing was written" 2 ;; + esac + fi + done + return 0 +} + +# The sub-field of the lane's LAST lane-kind line that carries one, IN +# FILE ORDER — which is the order every other state read in this file uses, and +# for the reason `swapped_lanes` states below: a lane's log is append-only and +# single-writer, so a line further down the file is a line written later +# whatever the two UTC fields say. +# +# THE LAST LINE CARRYING ONE, NOT THE LAST LINE. A lane started under Amendment +# 11 and then PAUSED for a reason that is not a swap has a last line with no +# payload at all, and its directory has not stopped being true. Amendment 7(i)'s +# cutover rule is the same shape: a line written before this clause carries +# none, and a reader that finds none SAYS SO rather than assuming one. +# THE SIX FACTS A LISTING ROW NEEDS, FROM ONE PASS OVER ONE LANE'S EVENTS. +# `` on one line. +# It is `payload_subfield`'s two rules and `home_of_lane`'s one, written once in +# awk instead of a dozen forks per lane — and the rules are restated here rather +# than referred to because a reader comparing the two must be able to see both: +# * the LAST lane-kind line that carries a sub-field wins, in FILE ORDER; +# * a value opening with `"` runs to its closing `"`, quotes stripped, and any +# other value ends at its first space — except `window`, which is two +# space-separated refs in ONE sub-field and is taken whole. +lane_row_facts() { # events on stdin, ONE LINE PER LANE + awk -v sep="$US" ' + function field(pay, want, whole, n, i, sf, v, q) { + want = want " " + n = split(pay, sf, "; ") + for (i = 1; i <= n; i++) { + if (substr(sf[i], 1, length(want)) != want) continue + v = substr(sf[i], length(want) + 1) + sub(/^[ \t]+/, "", v); sub(/[ \t]+$/, "", v) + if (substr(v, 1, 1) == "\"") { + q = index(substr(v, 2), "\"") + if (q > 0) return substr(v, 2, q - 1) + } + if (!whole) sub(/ .*$/, "", v) + return v + } + return "" + } + function pos(pf2, pn) { return pf2 "\034" sprintf("%09d", pn) } + BEGIN { FS = sep } + $3 == "STARTED" || $3 == "PAUSED" || $3 == "RESUMED" || $3 == "ENDED" || $3 == "RETIRED" { + # AMENDMENT 15 — KEYED ON THE LANE LOWER-CASED, WITH ITS SPELLING BESIDE + # IT. Every consumer of this table already looks a lane up by its + # lower-cased name (`lanes_rows`-s `table_lookup`, which reads the FIRST + # line with that key), and the key used to be the spelling the LINE + # carried: a log holding both spellings of one lane — which is what + # `lanes/log/openxfactory-2.md` holds — emitted TWO lines under one key, + # and the listing took the first and lost the other-s state, dir, + # profile, window, home and session. `disp` is the first spelling seen, + # for the second column; `lanes_rows` prints the register-s spelling over + # it anyway, and this is what a lane with a log and no row shows as. + l = tolower($2) + if (!(l in seen)) { seen[l] = ++n; byn[n] = l } + if (!(l in disp)) disp[l] = $2 + # A FORK-S RETIRED IS NOT THE LANE-S OWN LAST VERB (decision 8(c): a fork + # is never the lane; A11 Addendum 4 ruling 8). Read as the lane-s own line + # it would say the LANE was retired — the opposite of what happened, since + # the lane may well be live beside the fork it disowned. So a line whose + # payload opens `fork ` is skipped HERE, for the state fields only. + # NOTHING WRITES ONE ANY MORE, and this comment said otherwise (#26, the + # review of `29d3417`). The first build of ruling 8-s act appended + # `RETIRED … lane: -> fork ; pid ; kind `; that line is a + # seventh edit to in-force text and Amendment 7(b) gives `RETIRED` no + # payload, so `lane-end --retire` PROVES the fork and prints 6(d) and + # writes nothing at all (`lane_forks`-s own block argues it in full). The + # skip stays because these logs are APPEND-ONLY and never rewritten: a log + # that took one of those lines while that build was live still carries it. + # + # R14 IS NOT WEAKENED BY THIS. R14 decides WHICH of a lane-s own lines is + # last; this decides which lines are the lane-s own. A line about + # something that is never the lane was never in that set. + if (substr($8, 1, 5) == "fork ") next + # FILE ORDER decides which line is a lane-s LAST (R14), exactly as + # `swapped_candidates` decides it: a lane-s log is append-only and + # single-writer, so a line further down the file is a line written later + # whatever the two UTC fields say. + p = pos($10, $11) + if (!(l in mp) || p >= mp[l]) { mp[l] = p; verb[l] = $3; utc[l] = $1; ws[l] = $5 } + v = field($8, "dir", 0); if (v != "") d[l] = v + v = field($8, "profile", 0); if (v != "") pf[l] = v + v = field($8, "window", 1); if (v != "") w[l] = v + if ($3 == "STARTED" || $3 == "RESUMED") { + v = field($8, "home", 0); if (v != "" && v != "unknown") h[l] = v + # AMENDMENT 18(b) — WHERE THIS BINDING IS, out of the same pass, and + # taken from the BINDING LINE rather than from the last line carrying a + # sub-field: a `PAUSED` releases a binding and its own host is where the + # release was written, not where the lane was. Lower-cased here so the + # comparison one layer up costs no process (`lc` is a printf and a tr, + # and this listing asks it of every lane). + bh[l] = tolower(field($8, "host", 0)); if (bh[l] == "") bh[l] = tolower($5) + bc[l] = tolower(field($8, "container", 0)); if (bc[l] == "") bc[l] = "none" + # A line written before clause (a) carries NONE OF THE THREE, and its + # binding is *"the window on the row-s workstation"* — which has no + # container in it. All three, and not the host alone: this writer drops + # an offending sub-field on its own and keeps the line, so a modern line + # missing only its host is modern and is matched on the container it + # does carry (Copilot round 2). Said here so the reader one layer up + # matches it exactly as `binding` does. + bl[l] = (field($8, "host", 0) == "" && field($8, "container", 0) == "" && \ + field($8, "os", 0) == "" ? "legacy" : "") + } + # Clause (d) rule 3-s second source, out of the same pass: the session + # field of the lane-s last PAUSED or RESUMED, which is the resume target + # where the published cell names none. + if (($3 == "PAUSED" || $3 == "RESUMED") && $4 ~ /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/) sid[l] = tolower($4) + next + } + # THE OBJECTS EACH LANE HOLDS, from the same pass. A lane HOLDS an object + # when its own LAST line on that object carries an OPEN verb — Amendment + # 7(b)-s partition, and the one `lane-end` refuses on. + # + # IT CARRIES NO TAKEN-OVER ANNOTATION, AND THAT IS A DELIBERATE NARROWING. + # `lane_objects` adds one by asking `superseded_by` per object, which is a + # full pass over this stream per object per lane: on the suite-s own + # register that turned a listing into eighteen minutes and counting. A + # listing says WHAT A LANE HOLDS; `who --lane ` is the authority that + # says whether somebody has taken it over, and the listing points at it. + $6 !~ /^lane:/ { + l = tolower($2); k = l "\034" $6 # Amendment 15, as above + p = pos($10, $11) + if (!(k in omp) || p >= omp[k]) { omp[k] = p; overb[k] = $3; oobj[k] = $6; olane[k] = l + if (!(k in okseen)) { okseen[k] = ++okn; okbyn[okn] = k } } + if (!(l in seen)) { seen[l] = ++n; byn[n] = l } + if (!(l in disp)) disp[l] = $2 + } + END { + for (i = 1; i <= okn; i++) { + k = okbyn[i] + if (overb[k] != "CLAIMED" && overb[k] != "TAKEOVER" && overb[k] != "OPENED" && overb[k] != "LANDING" && overb[k] != "WITHDRAWN") continue + l = olane[k] + if (l in have) obj[l] = obj[l] "; " overb[k] " " oobj[k] + else { obj[l] = overb[k] " " oobj[k]; have[l] = 1 } + } + for (i = 1; i <= n; i++) { + l = byn[i] + # KEYED ON THE LANE LOWER-CASED, like the register index beside it and + # for the same reason: the listing joins these two tables on the lane + # name, and this file matches a lane name case-insensitively everywhere + # else (`lane_named_ci`). + printf "%s%c%s%c%s%c%s%c%s%c%s%c%s%c%s%c%s%c%s%c%s%c%s%c%s%c%s\n", l, 31, disp[l], 31, verb[l], 31, utc[l], 31, ws[l], 31, d[l], 31, pf[l], 31, w[l], 31, h[l], 31, sid[l], 31, obj[l], 31, bh[l], 31, bc[l], 31, bl[l] + } + }' +} + +# 0 with the sub-field · 8 the log was read and carries none · 1 THE LOG COULD +# NOT BE READ, which is not the same fact and never was (#26, the fail-closed +# family one layer out, `lanes-edit.sh:3525`). +# +# THE READ WAS INSIDE THE HERE-DOCUMENT THAT FEEDS THE LOOP, and a command +# substitution's status THERE is not carried anywhere — not, as the review had +# it, carried as `awk`'s; it is discarded outright, because a here-document body +# is text and nothing tests it. So a `lane_log_events` that failed arrived as no +# lines at all and left through the `return 8` below, and 8 is the one code every +# caller of this function is entitled to read as *"this lane has not started +# under Amendment 11 yet"* — the pre-cutover answer that sends `restart`, +# `lane-start` and both skills to the rungs beneath a record they never +# established was readable. The read is its own step now and its status decides. +lane_payload_field() { # [all] + lpf_lines=""; lpf_rc=0 + lpf_lines="$(lane_log_events "$1")" || lpf_rc=$? + [ "$lpf_rc" = 0 ] || return 1 + # The scan is over EVERY lane-kind payload, newest last, and the answer is + # the last one that actually carries the sub-field. + lpf_v="" + while IFS= read -r lpf_p; do + [ -n "$lpf_p" ] || continue + lpf_this="$(payload_subfield "$lpf_p" "$2" "${3-}")" + [ -n "$lpf_this" ] && lpf_v="$lpf_this" + done < + [ -n "${1-}" ] || return 1 + command -v tmux >/dev/null 2>&1 || return 1 + tmux display-message -p -t "$1" "$2" 2>/dev/null | head -n1 +} + +# THE LANE BOUND TO A WINDOW OF THE ASKING WORKSTATION (Amendment 11 clause +# (h), `R-A11-8`/RV-T7 for the scoping and `R-A11-8`/RV-T6 for the agreement +# rule). Three callers, ONE implementation: +# +# * the launcher's precedence 3 (clause (b) row 3), +# * `/restart`'s step 2(c) (clause (f)), +# * the `/lane-swap` skill's step 1 (Amendment 8(a) step 1, extended). +# +# TWO RUNGS, first answer wins: +# 1. the window's own NAME, where the register has a row for it. That is +# clause (b)'s precedence 2 read through the same door, so a caller that +# asks this read a ref gets the same answer the launcher would. +# 2. this workstation's swap records, matched on the ref. +# +# SCOPED TO THE ASKING WORKSTATION, IN THE CONTRACT AND NOT ONLY IN `Open`. A +# `:` is a local fact about one machine, and `claude-x:0` +# written on Raven collides with `claude-y:0` on Eagle far more easily than an +# `<@id>` will. `swapped` takes `[]` for exactly that reason and this read +# takes it for the same one: records written by another workstation are NOT +# CONSIDERED. +# +# THE AGREEMENT RULE, AND THIS READ OWNS IT. Existing-now is not enough on its +# own: a record naming `claude-y:0 @97`, met from the window that has since +# taken `claude-y:0` as `@200`, passes the existing-now test on its ref and +# would bind the lane to a stranger's pane with no question — which is the +# failure the liveness fence exists to stop, arriving through the LIVE ref +# instead of the dead one. So: +# +# a record that carries an `<@id>` is matched on its `:` ONLY +# WHERE THE WINDOW NOW HOLDING THAT REF REPORTS THAT SAME ID; a record with +# no id is matched on the ref alone. +# +# It is stated once, here, and not restated in each of the read's three +# callers: three implementations of one rule is how they would come to +# disagree. The launcher PR withdrew its own copy of this clause on the same +# ground. +# +# 0 with the lane, 8 with none, 64 a usage error of its own. +window_lane() { # + wl_ws="$(short_ws "${1:-$WS}")"; wl_ref="${2-}" + [ -n "$wl_ref" ] || return 64 + # A WORKSTATION THAT IS NOT THIS ONE HAS NO WINDOW THIS PROCESS CAN SEE, and + # the read says so rather than pretending. The window's NAME and the liveness + # fence are both facts about the tmux server running HERE: asked about Raven, + # a local `display-message` would answer about an Eagle window that happens to + # share the ref — which is the collision the scoping exists to stop, made by + # the fence itself. So a foreign workstation is answered from its RECORDS + # alone, unfenced, and that is the cross-machine answer Amendment 7's open + # item is about: this process cannot tell whether Raven's window still exists. + wl_local=1 + [ "$wl_ws" = "$(short_ws "$WS")" ] || wl_local=0 + if [ "$wl_local" = 1 ]; then + # RUNG 1 — the window's own name. Read from tmux, so a ref that names no + # window answers nothing here either. + wl_name="$(tmux_window_field "$wl_ref" '#{window_name}' 2>/dev/null || :)" + if [ -n "$wl_name" ]; then + wl_row="$(lane_named_ci "$wl_name" 2>/dev/null || :)" + if [ -n "$wl_row" ]; then printf '%s\n' "$wl_row"; return 0; fi + fi + fi + # RUNG 2 — that workstation's swap records. `swapped_candidates` is the one + # reader of a `PAUSED … swap;` line in this file, so the record's shape is + # parsed once however many reads are built on it. + wl_now_id="" + if [ "$wl_local" = 1 ]; then + wl_now_id="$(tmux_window_field "$wl_ref" '#{window_id}' 2>/dev/null || :)" + [ -n "$wl_now_id" ] || return 8 # the ref names no window HERE, now + fi + # THE FIELD LIST IS `swapped_candidates`' OWN, IN FULL, and it gains Amendment + # 17(b)'s two: `read` puts every field it has no variable for into the LAST + # one, so a short list would have quietly moved the pickaxe key — which is not + # read here — into `wl_p` and the agent into it too. Named in full, the reader + # and the writer of this row cannot drift apart. + while IFS="$US" read -r wl_l wl_u wl_w wl_d wl_p wl_a wl_t wl_key; do + [ -n "${wl_l:-}" ] || continue + [ -n "${wl_w:-}" ] && [ "$wl_w" != unknown ] || continue + # The sub-field's refs: `:` first, `<@id>` second. + wl_rec_ref="${wl_w%% *}" + wl_rec_id="" + case "$wl_w" in *' '@*) wl_rec_id="${wl_w##* }" ;; esac + case "$wl_ref" in + @*) + # Asked by id. The record must carry that id, and the id must resolve — + # which `wl_now_id` has already proved, since tmux answered for it. + [ -n "$wl_rec_id" ] && [ "$wl_rec_id" = "$wl_ref" ] || continue + ;; + *) + # Asked by `:`. The record must name that ref, AND — + # where the record carries an id and this workstation can see the window + # — the window now holding the ref must report that same id. + [ "$wl_rec_ref" = "$wl_ref" ] || continue + if [ "$wl_local" = 1 ] && [ -n "$wl_rec_id" ] && [ "$wl_rec_id" != "$wl_now_id" ]; then continue; fi + ;; + esac + # AMENDMENT 15 — AND THE ANSWER IS THE ROW'S SPELLING, as rung 1's already + # is. `$wl_l` is the lane as its own `PAUSED … swap;` line spells it, which + # is whatever the lane was PAUSED under; this read's three callers hand what + # it prints to `tmux rename-window`, to `--name` and to `lane `, so + # a record written before the row's spelling settled would rename a window + # to the wrong one. A register holding the 15(d) pair keeps the record's own + # spelling rather than refusing: this read is a rung in front of a launch and + # its contract is 0, 8 or 64 — the refusal belongs to the writer it leads to. + wl_can="$(canon_lane "$wl_l" 2>/dev/null || :)" + printf '%s\n' "${wl_can:-$wl_l}" + return 0 + done <` exactly as every other +# state read is. Clause (e) is what makes this source trustworthy, by +# refusing `unknown` in that field: a log that may carry the literal there +# is a log that cannot be read this way, and the two clauses are one act. +# +# A uuid whose transcript is not in the lane's directory IS STILL A UUID, and +# the caller says so rather than resuming a title into a picker. +# +# 0 with the uuid, 8 where neither source names one. +last_session_of() { # + lso_l="${1-}"; [ -n "$lso_l" ] || return 64 + lso_id="$(session_ids_of_lane "$lso_l" 2>/dev/null | tail -n1 || :)" + if [ -n "$lso_id" ]; then printf '%s\n' "$lso_id"; return 0; fi + lso_id="$(lane_log_events "$lso_l" 2>/dev/null | awk -F"$US" ' + ($3 == "PAUSED" || $3 == "RESUMED") && $4 ~ /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/ { id = $4 } + END { if (id != "") print tolower(id) }')" + [ -n "$lso_id" ] || return 8 + printf '%s\n' "$lso_id" +} + +# ------------------------- decision 8(c) and 8(e): A FORK IS NEVER A HOLDER +# +# Evidence 6, 2026-09-13: an abandoned launch of a lane left behind a DAEMON +# FORK of its transcript — `--fork-session`, a NEW session id, `kind: bg`, no +# tmux, a cwd of `/workspace` — which went on orchestrating the same plan, +# relaunched writers on the same three branches, wrote `RESUMED` and `PAUSED` +# lines into the lane's log, and messaged the interactive session claiming to +# be the holder while citing a dead pid. +# +# Amendment 8 ruling (g) already skips a `kind: bg` companion, and that is not +# enough: a fork is a SESSION OF ITS OWN with an id no row carries, so the +# thing that makes it recognisable is neither its kind nor its id but ITS +# TRANSCRIPT'S TITLE. A `--fork-session` copies the parent's `custom-title` +# record, so the fork's transcript says `openRepoProject-1` while its id says +# something the lane's row has never heard of. That pair — THE LANE'S TITLE +# UNDER AN ID THE LANE DOES NOT RECORD — is the defect, and it is what this +# read finds. +# +# IT NAMES THEM AND DOES NOTHING ELSE, exactly as `idle_holders` does and for +# the same reason clause (f) of Amendment 8 gives. THE ACT IT NAMES IS +# `lane-end --retire ` (clause (k) rule (e), A11 Addendum 4 +# ruling 8) and never `kill `: that act is the DOOR to Amendment 6(d), it +# writes nothing and *"neither kills a process"*. So this read goes on naming a +# fork until 6(d) is actually taken on it — the retitle, or the process gone — +# which is what is TRUE; and stopping the process stays a person's act that no +# surface here prints as the one. +# +# One line per fork, ``. +# 0 with rows, 8 with none, 1 where the records could not be read. +# Every LIVE record on this workstation whose transcript carries a custom +# title, as +# `<US><sessionId><US><lc sessionId><US><pid><US><kind><US><cwd>`. +# Built ONCE per process: `who` asks about every lane in the register, and one +# find per record per lane would be a read nobody would run. +# +# CACHED IN A FILE for the reason `live_session_ids` gives, and this one was the +# more expensive of the two: `transcript_title` falls back to a `find` over the +# whole profiles tree, so a rebuild per lane was a filesystem walk per lane. +# +# THE LOWER-CASED TITLE AND ID ARE CARRIED rather than computed by the reader: +# `lc` is `printf | tr`, TWO PROCESSES, and `lane_forks` ran it on every entry of +# this map for every lane it was asked about — fifty lanes times however many +# live records, for two comparisons a `case` can make. +fork_map() { + fm_c="${SE_CACHE_FILE:+$SE_CACHE_FILE.forks}" + if [ -n "$fm_c" ] && [ -f "$fm_c" ]; then cat -- "$fm_c"; return 0; fi + # THE READ IS ITS OWN STEP AND ITS STATUS DECIDES, because the loop below is + # fed by a HERE-DOCUMENT and a here-document body is TEXT: the status of a + # command substitution inside it is discarded outright (#26, the review of + # `37632b1`; the same shape `f368a75` took out of `lane_payload_field`). + fm_recs=""; fm_rc=0 + fm_recs="$(session_records)" || fm_rc=$? + [ "$fm_rc" = 0 ] || return 1 + fm_out="" + while IFS="$US" read -r fm_f fm_sid fm_tmux fm_name fm_pid fm_kind fm_cwd fm_status fm_start; do + [ -n "${fm_sid:-}" ] || continue + record_fields_are_live "$fm_status" "$fm_pid" "$fm_start" || continue + fm_t="$(transcript_title "$fm_sid" "$fm_f" "$fm_cwd")" + [ -n "$fm_t" ] || continue + fm_out="${fm_out}$(lc "$fm_t")${US}${fm_t}${US}${fm_sid}${US}$(lc "$fm_sid")${US}${fm_pid}${US}${fm_kind}${US}${fm_cwd} +" + done <<EOF +$fm_recs +EOF + if [ -n "$fm_c" ]; then + printf '%s' "$fm_out" > "$fm_c.${BASHPID:-$$}" 2>/dev/null && + mv -f -- "$fm_c.${BASHPID:-$$}" "$fm_c" 2>/dev/null || + rm -f -- "$fm_c.${BASHPID:-$$}" + fi + printf '%s' "$fm_out" +} + +# The `customTitle` of a transcript, by its uuid. A `/rename` writes a +# `{"type":"custom-title",…}` record INTO the transcript and the LAST one wins, +# which is the same reading `lane-start`'s own `titled_transcript` makes. +# `<lane> (2)` is the same lane: that suffix is what a rename into a title +# something else still holds mints. +transcript_title() { # <uuid> [<the record's file>] [<the record's cwd>] + tt_id="${1-}"; [ -n "$tt_id" ] || return 1 + tt_f="" + # THE CHEAP CANDIDATES FIRST, AND THE WALK ONLY WHERE THEY MISS. The harness + # keeps one transcript directory per working directory, named by that + # directory with every character that is not a letter or a digit replaced by + # `-`; the record itself carries both the profile directory it was written in + # (`<profile>/sessions/<pid>.json`) and the `cwd`. Two `[ -f ]` tests answer + # for every ordinary session, and the `find` is what catches a transcript the + # harness moved — which is the case Evidence 6's fork was in, its transcript + # under `state/` rather than under the profile. + if [ -n "${3-}" ]; then + tt_slug="$(printf '%s' "$3" | sed 's/[^A-Za-z0-9]/-/g')" + for tt_c in \ + "$(dirname -- "$(dirname -- "${2:-/nonexistent/x}")")/projects/$tt_slug/$tt_id.jsonl" \ + "${CLAUDE_CONFIG_DIR:-$HOME/.claude}/projects/$tt_slug/$tt_id.jsonl"; do + [ -f "$tt_c" ] && { tt_f="$tt_c"; break; } + done + fi + if [ -z "$tt_f" ]; then + for tt_root in "${CLAUDE_PROFILES_HOME:-$HOME/.claude-profiles}" "${CLAUDE_CONFIG_DIR:-$HOME/.claude}"; do + [ -d "$tt_root" ] || continue + tt_f="$(find "$tt_root" -maxdepth 8 -path '*/projects/*' -name "$tt_id.jsonl" -type f 2>/dev/null | head -n1)" + [ -n "$tt_f" ] && break + done + fi + [ -n "$tt_f" ] || return 1 + tt_last="$(grep -e '^{"type":"custom-title"' -- "$tt_f" 2>/dev/null | tail -n1 || :)" + [ -n "$tt_last" ] || return 1 + tt_v="$(printf '%s' "$tt_last" | sed 's/.*"customTitle":"//; s/".*//')" + [ -n "$tt_v" ] || return 1 + printf '%s\n' "${tt_v% (*)}" +} + +# `lane_forks <lane> [<ids fence>]` +# +# THE TWO SETS AS ONE SPACE-FENCED STRING EACH, tested with `case` (A11 +# Addendum 4 ruling 12). The `grep -qx` this replaces was a process per map +# entry per lane, and `lc` on the entry's title was two more; a `case` is the +# shell's own. +# +# AND A CALLER THAT ALREADY HAS THEM PASSES THEM. `lanes` asks this about every +# lane, and computing the row's ids here meant TWO renders of the published +# register plus one of the working tree's, per lane — the very reads the listing +# has already made in one pass. A caller with one lane in hand (`forks`, `who`) +# passes nothing and this computes them, so the read is unchanged for everybody +# else. The fences are `" a b c "`, lower-cased, spaces at both ends. +lane_forks() { # <lane> [<ids fence>] + lf_l="${1-}"; [ -n "$lf_l" ] || return 64 + lf_ll="$(lc "$lf_l")" + if [ "$#" -ge 2 ]; then + lf_ids="$2" + else + lf_ids=" $( { session_ids_of_lane "$lf_l" 2>/dev/null || : + session_ids_local_of_lane "$lf_l" 2>/dev/null || :; } | awk 'NF && !seen[$0]++' | tr '\n' ' ')" + fi + # AND THE MAP IS READ BEFORE THE LOOP, so that a session tree which could not + # be read leaves here as **1** and not as the **8** that means "no fork of it + # is live" (#26, the review of `37632b1`). The `forks` arm has carried the + # refusal for that 1 since it was written — *"That is NOT 'no fork of it is + # live'"* — and it was UNREACHABLE, because the status died in the + # here-document below. A fork is a DEFECT under ratified decision 8(e); the + # one thing worse than reporting one is reporting none without looking. + lf_map=""; lf_mrc=0 + lf_map="$(fork_map)" || lf_mrc=$? + [ "$lf_mrc" = 0 ] || return 1 + lf_out="" + while IFS="$US" read -r lf_tl lf_t lf_sid lf_sidl lf_pid lf_kind lf_cwd; do + [ -n "${lf_tl:-}" ] || continue + [ "$lf_tl" = "$lf_ll" ] || continue + # AN ID THE ROW RECORDS IS THE LANE ITSELF, never a fork of it. + case "$lf_ids" in *" $lf_sid "*) continue ;; esac + # AND THERE IS NO THIRD TEST, BECAUSE RETIRING WRITES NOTHING. The first + # build of ruling 8's act appended `RETIRED … -> fork <sid>` to the lane's + # log and this read filtered on it; that line is a SEVENTH edit to in-force + # text — Amendment 7(b) gives `RETIRED` no payload and A11 clause (c) keeps + # it that way — so it is gone (`lane-end`'s own block argues it in full). + # `lane-end --retire <pid|uuid>` is the DOOR to Amendment 6(d) and performs + # none of it, which is clause (k) rule (e)'s own posture, so a fork stays a + # fork here until the operator's retitle or its process is gone. This read + # keeps saying what is TRUE rather than what has been acknowledged. + lf_out="${lf_out}${lf_sid} ${lf_pid} ${lf_kind:-interactive} ${lf_cwd} +" + done <<EOF +$lf_map +EOF + [ -n "$lf_out" ] || return 8 + printf '%s' "$lf_out" +} + +# ------------------------------------------- issue #39: DUPLICATE HOLDERS +# +# `lane_forks` answers one question — a LIVE session recorded under an id the +# row does NOT carry, wearing the lane's own transcript title — and it answers +# it well: Evidence 6's `--fork-session` daemon had a fresh id nothing had +# heard of. Measured 2026-09-14 (opensoft/openRepoTools#39): a cross-profile +# resume leaves a SECOND kind of stray behind that `lane_forks` cannot see at +# all — a `bg-pty-host` running `claude --session-id <X> --fork-session +# --resume <parent>.jsonl` under a background pty host, where a LATER +# `lane-start --no-launch` went on to bind `<X>` itself as the row's own +# session. Once that happens the fork's id IS an id the row carries, +# `lane_forks`' own exclusion (`case "$lf_ids" in *" $lf_sid "*) continue`) +# fires exactly as designed, and the daemon goes invisible to it — while a +# second live process now holds the one transcript Amendment 18(h) says +# exactly one process may hold. `lane-end --retire <pid>` refused it outright, +# and the retirement was a bare `kill -TERM`, outside every tool this estate +# has. +# +# THE PROCESS TABLE, NOT A SESSION RECORD'S `sessionId` FIELD, because this +# question is not about what a record CLAIMS its id is — the fork's own record +# may say `<X>`, which is exactly the id the row now also carries and exactly +# why `lane_forks` cannot use it — it is about the ARGV a live process was +# actually started with: a `--fork-session` invocation whose `--resume` path +# ends in one of THIS LANE's own transcript ids. Every id the row has ever +# carried is checked, not only the last (Amendment 6(b): a chained cell's +# earlier link is still this lane's transcript). +# +# `pgrep -f` FIRST, THEN `ps -o pid=,ppid=,args= -p` PER CANDIDATE, both forms +# already used elsewhere in this tree for the same reason: GNU and BSD/macOS +# agree on `-f` (match the full argument list) and on `-o field=` (each `=` +# suppresses that field's own header, so the frame needs no trimming) where +# they do not agree on a fixed-column `ps aux`. Scoping the `ps` call to one +# candidate pid at a time, rather than walking the whole table once, is what +# lets the exact form stay `-p <pid>` instead of a table-wide parse this file +# would then own two implementations of. +# +# THE ROW'S OWN LIVE HOLDER IS EXCLUDED, never reported and never touched, +# over the SAME implementation `live-holder` already calls (`live_holder`, +# over the published-union-local id set) — never a new liveness primitive. In +# the ordinary case this exclusion never fires: a lane's real interactive +# session is never started WITH `--fork-session` in its own argv, so nothing +# this read finds can coincide with it. It stays in because a fence that is +# usually a no-op is exactly what a fence should be, and `lane-end` asks the +# same question again, in words, before it sends a single signal. +# +# One line per surviving match: `<parent pid><US><child pids, or empty><US> +# <the matched uuid>` — `$US`, never a TAB. A CONFIRMED CHILD OF THE CI RUN ON +# PR #61: with a real, honest, DOCUMENTED-empty child slot (the line just +# above — "the child slot stays empty" is not a race-only rarity, it is this +# read's ordinary answer for a parent with no confirmable fork-session child), +# a bare TAB is one of bash `read`'s own IFS-WHITESPACE characters, so +# `IFS=$'\t' read -r a b c` on `"<parent>\t\t<uuid>"` — TWO adjacent tabs +# either side of the empty middle field — COLLAPSES them into ONE delimiter +# exactly as it collapses repeated spaces, silently shifting the uuid into +# `b` and leaving `c` empty. Measured: `tests-no-submodule` on e4f9054, +# `test_the_lane_helper_suite_passes` read the empty child as a parent still +# "STILL ALIVE" (its own argv check comparing against `$dh_uuid_lc=""` could +# match nothing) and the uuid as a pid — `pid <uuid> (child): gone`. `$US` is +# not IFS whitespace, so `read` never merges it with itself; both consumers in +# `lane-end` read this format with `IFS=$'\037'` for the same reason +# `live-holder`'s own multi-field line already does. +# 0 with rows, 8 with none, 1 where `pgrep` is missing, the register or +# this workstation's session records could not be read — a read that failed is +# never "nothing is a duplicate". +duplicate_holder_pids() { # <lane> + dhp_l="${1-}"; [ -n "$dhp_l" ] || return 64 + command -v pgrep >/dev/null 2>&1 || return 1 + command -v ps >/dev/null 2>&1 || return 1 + # THE IDS ARE THE WHOLE SEARCH, SO A REGISTER THAT COULD NOT BE READ IS 1 + # (opensoft/openRepoTools#67). Its empty render used to be the same empty set + # as a lane with no row, and this returned 8 — "no duplicate holder is live" — + # without asking the process table anything at all. + dhp_ids=""; dhp_irc=0 + dhp_ids="$(session_ids_checked "$dhp_l")" || dhp_irc=$? + case "$dhp_irc" in + 0) : ;; + 8) return 8 ;; + *) SESSION_FILES_ERR="the register (origin/$LANES_BRANCH:$LANES_PATH, or $LANES_FILE) could not be read, so lane $dhp_l's session ids are not known and no process could be matched against them" + return 1 ;; + esac + dhp_legit="" + # NOT `$( … )` (Copilot round 2, PR #61): `live_holder` communicates a read + # failure by setting `SESSION_FILES_ERR` in ITS CALLER's shell, exactly as + # `session_files` documents and `window_session` already relies on — a + # command substitution runs in a SUBSHELL, so that assignment would die with + # it and the dispatcher's `${SESSION_FILES_ERR:-unknown error}` would print + # "unknown error" always. The tmp file is what lets this call stay direct + # and still hand the printed record back to the code after it. + dhp_lh_f="$(mktemp "${TMPDIR:-/tmp}/lanes-edit-dhp.XXXXXX" 2>/dev/null || printf '')" + if [ -z "$dhp_lh_f" ]; then + SESSION_FILES_ERR="could not create a temporary file under ${TMPDIR:-/tmp}" + return 1 + fi + live_holder "$dhp_l" "$dhp_ids" > "$dhp_lh_f" 2>/dev/null; dhp_lrc=$? + case "$dhp_lrc" in + 0) dhp_legit="$(awk -F"$US" '{print $4}' "$dhp_lh_f")" ;; + 8) : ;; + *) rm -f -- "$dhp_lh_f"; return 1 ;; + esac + rm -f -- "$dhp_lh_f" + # `pgrep -f` ITSELF, THREE-WAY (Copilot round 2): 1 is its OWN "no process + # matched" — the ordinary, honest 8 — and anything else (2 usage, 3 a fatal + # error reading the process table) is a READ THAT FAILED, never "none is a + # duplicate". + dhp_cand=""; dhp_pgrc=0 + dhp_cand="$(pgrep -f 'fork-session' 2>/dev/null)" || dhp_pgrc=$? + case "$dhp_pgrc" in + 0) : ;; + 1) return 8 ;; + *) return 1 ;; + esac + [ -n "$dhp_cand" ] || return 8 + # AMENDMENT 8 RULING (g)'s COMPANION IS NEVER A DUPLICATE, FROM THIS SURFACE + # EITHER (Copilot on 05d7889, PR #61). `live_holder` above answers the + # INTERACTIVE holder only — it passes over a `kind: bg` record by design — + # so `dhp_legit` fenced the session at the keyboard but not the harness's + # own companion beside it: a `kind: bg` record carrying the SAME id in the + # SAME profile as an interactive record of it, "one session, not a queue of + # rival holders". `lane-end`'s session-record path already refuses that pid + # by name; this process-table path runs FIRST, so a companion whose argv + # carried `--fork-session --resume <this lane's id>.jsonl` would have been + # handed to it as a duplicate and TERMed — one half of the live session that + # IS the lane. The companion set is built here with the very rule + # `lane-end` applies (`transcript_holders`' own `companion` verdict, or a + # `bg` row in a profile that also holds a non-`bg` row of the same id, which + # is how that verdict reads from outside the lane's own window), and a + # candidate that is one — or a wrapper whose child is one — is never a row. + # A records tree `transcript_holders` could not read is a read that FAILED, + # exactly as `live_holder`'s is above: 1, never "no companion". + dhp_comp=" " + dhp_th_f="$(mktemp "${TMPDIR:-/tmp}/lanes-edit-dht.XXXXXX" 2>/dev/null || printf '')" + if [ -z "$dhp_th_f" ]; then + SESSION_FILES_ERR="could not create a temporary file under ${TMPDIR:-/tmp}" + return 1 + fi + for dhp_tid in $dhp_ids; do + transcript_holders "$dhp_tid" > "$dhp_th_f" 2>/dev/null; dhp_thrc=$? + case "$dhp_thrc" in + 0) : ;; + 8) continue ;; + *) rm -f -- "$dhp_th_f"; return 1 ;; + esac + dhp_int_profs=" " + while IFS="$US" read -r dt_pid dt_kind dt_tgt dt_prof dt_where dt_v dt_file; do + [ -n "${dt_pid:-}" ] || continue + [ "$dt_kind" = bg ] && continue + case "$dhp_int_profs" in *" $dt_prof "*) : ;; *) dhp_int_profs="${dhp_int_profs}${dt_prof} " ;; esac + done < "$dhp_th_f" + while IFS="$US" read -r dt_pid dt_kind dt_tgt dt_prof dt_where dt_v dt_file; do + [ -n "${dt_pid:-}" ] || continue + [ "$dt_kind" = bg ] || continue + dt_is_comp=0 + if [ "$dt_v" = companion ]; then + dt_is_comp=1 + else + case "$dhp_int_profs" in *" $dt_prof "*) dt_is_comp=1 ;; esac + fi + [ "$dt_is_comp" = 1 ] && dhp_comp="${dhp_comp}${dt_pid} " + done < "$dhp_th_f" + done + rm -f -- "$dhp_th_f" + # A CANDIDATE'S OWN PARENT, WHEN IT IS ALSO A CANDIDATE, IS NEVER TREATED AS + # A SECOND PARENT (Copilot round 2): `--fork-session`'s argv is inherited by + # the child `claude` process as often as the bg-pty-host wrapper that + # started it, so `pgrep -f` routinely returns BOTH — and reading the child + # on its own turn, with no ppid fence, reported it as a headless parent of + # its own (no child of ITS OWN to find), doubling one duplicate into two + # rows and leaving `--retire <the real parent's pid>` unreachable if the + # child's spurious row was taken instead. + dhp_cand_fence=" $(printf '%s' "$dhp_cand" | tr '\n' ' ') " + dhp_out="" + while IFS= read -r dhp_pid; do + [ -n "$dhp_pid" ] || continue + [ -n "$dhp_legit" ] && [ "$dhp_pid" = "$dhp_legit" ] && continue + case "$dhp_comp" in *" $dhp_pid "*) continue ;; esac + dhp_psrc=0 + dhp_line="$(ps -o pid=,ppid=,args= -p "$dhp_pid" 2>/dev/null)" || dhp_psrc=$? + # A `ps -p` MISS IS NOT A READ FAILURE, but a nonzero status alongside + # OUTPUT would be (Copilot round 5/6, PR #61: "a failed ps lookup is read + # as no candidate") — `ps -p <gone pid>` fails with EMPTY output, which is + # the ordinary, honest "it already exited" race this whole scan expects; + # a command that failed and still printed something is the one case + # this file's fail-closed rule everywhere else applies to. + if [ -z "$dhp_line" ]; then continue; fi + [ "$dhp_psrc" = 0 ] || return 1 + read -r dhp_pid_chk dhp_ppid dhp_args <<DHPLINE +$dhp_line +DHPLINE + # `--fork-session ` WITH ITS OWN TRAILING SPACE (Copilot round 11, PR + # #61): a bare substring also matches `--fork-session-helper` or any + # other flag that merely STARTS WITH this text, which is never the + # process this scan means — the real invocation always has a boundary + # (a space, then `--resume`) right after this flag, so requiring it + # rules the false one out the same way the `--resume ` half already + # rules out `--resume-file` beside it. + case "$dhp_args" in *"--fork-session "*"--resume "*) : ;; *) continue ;; esac + case "$dhp_cand_fence" in *" $dhp_ppid "*) continue ;; esac + dhp_args_lc="$(printf '%s' "$dhp_args" | tr 'A-F' 'a-f')" + # THE ACTUAL `--resume` VALUE, NOT A GLOB THAT CAN SPAN OTHER ARGUMENTS + # (Copilot round 5, PR #61): `*"--resume"*"/$id.jsonl"*` also matches + # `--resume /other.jsonl --label /<id>.jsonl`, since `*` between them + # freely crosses argument boundaries. What was actually resumed is the + # value right after `--resume `, and that is the only thing compared — + # read WHOLE, spaces and all, by `dhp_resume_value` below this function + # (opensoft/openRepoTools#76: cutting it at the first space never matched + # a directory that has one). + dhp_resume_value "$dhp_args_lc"; dhp_resume="$dhp_rv" + for dhp_id in $dhp_ids; do + dhp_id_lc="$(printf '%s' "$dhp_id" | tr 'A-F' 'a-f')" + # AN EXACT PATH COMPONENT, NOT AN ARBITRARY SUBSTRING (Copilot round 4, + # PR #61): a bare substring also matches `other-<id>.jsonl` (no leading + # `/`, so it is not THIS transcript's basename) and `<id>.jsonl.bak` — + # `/<id>.jsonl` must be the resume token's own trailing path component. + dhp_matched=0 + case "$dhp_resume" in */"$dhp_id_lc.jsonl") dhp_matched=1 ;; esac + if [ "$dhp_matched" = 1 ]; then + # THE CHILD, PREFERRING ONE THAT IS ITSELF A `--fork-session` MATCH + # (the real `claude` leaf) over whichever child the process table + # happens to list first. `pgrep -P`'s OWN status, three-way, same as + # the top-level `pgrep -f` above (Copilot round 4): 1 is its own + # "no children", honestly empty; anything else is a read that + # FAILED, and this candidate is skipped rather than reported with a + # child slot that only LOOKS empty on purpose. + dhp_child=""; dhp_kids=""; dhp_kidrc=0 + dhp_kids="$(pgrep -P "$dhp_pid" 2>/dev/null)" || dhp_kidrc=$? + case "$dhp_kidrc" in + 0 | 1) : ;; + *) return 1 ;; + esac + # AN ARBITRARY CHILD IS NEVER GUESSED (Copilot round 6, PR #61): a + # bg-pty-host can have children that are not the `claude` process it + # wraps at all — a shell, a pty helper — and reporting the FIRST one + # `pgrep -P` happens to list, when none of them is itself a + # `--fork-session` candidate, could hand an unrelated process to + # `lane-end --retire`'s TERM. Only a child THIS SAME SCAN also + # confirmed as a fork-session candidate is ever named; otherwise the + # child slot stays empty; the parent is still reported and retirable + # on its own. + # + # EVERY FENCED CANDIDATE MUST PROVE IT RESUMES THIS SAME TRANSCRIPT + # BEFORE IT IS NAMED, and a `ps -p` MISS IS NOT THE SAME VERDICT AS A + # CONFIRMED MISMATCH (Copilot round 8 AND round 9, PR #61: the first + # pass here trusted a SOLE fenced candidate on the fence alone, + # which round 9 found true a wrapper with exactly one child for a + # DIFFERENT transcript could exploit). Both facts are proven in one + # pass, never two: + # * a candidate whose `ps -p` reads and whose `--resume` value + # matches `$dhp_id_lc` exactly is VERIFIED — named, however many + # other candidates there are, and so is EVERY other child that + # verifies (opensoft/openRepoTools#86, below); + # * a candidate whose `ps -p` reads but whose `--resume` does NOT + # match is a CONFIRMED MISMATCH — a different transcript's fork, + # and it is never named, however few other candidates there are; + # * a candidate whose `ps -p` MISSES (empty output — the ordinary + # "already gone by the time this scan asks" race, not a + # confirmed anything) is neither: it is held as a FALLBACK, and + # named only if it is the SOLE fallback with no verified + # candidate elsewhere. This is what keeps `lane-end`'s own race + # case working — a child already unreadable by the time + # discovery runs is still named here, for the pre-kill recheck + # a step later to catch honestly — while a wrapper's one child + # for another transcript, which DOES read, is never mistaken + # for it. + # Two or more unresolved fallbacks are left unnamed rather than + # guessed between; the parent is still reported and retirable on + # its own in every one of these shapes. + # + # EVERY VERIFIED CHILD, NOT THE FIRST (opensoft/openRepoTools#86, + # Copilot on 11bf0f0, PR #61): this loop used to `break` on the first + # child that verified, and the record had one child slot, so a + # wrapper with two children both resuming this transcript had the + # second left out of the report `lane-end --retire` acts on — which + # then TERMed the parent and the one child it was told about, + # reported RETIRED, and left the other still holding the transcript. + # The loop now runs to the end, and the slot carries every verified + # child, space-separated, in the order `pgrep -P` listed them. A + # pid never contains a space and `$US` is the record's only field + # separator, so `lane-end`'s `IFS=$'\037' read` still takes the + # whole list as one field. + dhp_verified=""; dhp_fallback=""; dhp_fallback_n=0 + for dhp_c in $dhp_kids; do + case "$dhp_cand_fence" in *" $dhp_c "*) : ;; *) continue ;; esac + dhp_c_line=""; dhp_c_psrc=0 + dhp_c_line="$(ps -o args= -p "$dhp_c" 2>/dev/null)" || dhp_c_psrc=$? + if [ -z "$dhp_c_line" ]; then + dhp_fallback_n=$((dhp_fallback_n + 1)) + [ -n "$dhp_fallback" ] || dhp_fallback="$dhp_c" + continue + fi + [ "$dhp_c_psrc" = 0 ] || return 1 + dhp_c_args_lc="$(printf '%s' "$dhp_c_line" | tr 'A-F' 'a-f')" + # `--fork-session ` WITH ITS OWN TRAILING SPACE (Copilot round 11, + # PR #61) — same fix, same reason as the parent's own check above. + case "$dhp_c_args_lc" in *"--fork-session "*"--resume "*) : ;; *) continue ;; esac + dhp_resume_value "$dhp_c_args_lc"; dhp_c_resume="$dhp_rv" + case "$dhp_c_resume" in + */"$dhp_id_lc.jsonl") dhp_verified="${dhp_verified}${dhp_verified:+ }${dhp_c}" ;; + esac + done + if [ -n "$dhp_verified" ]; then + dhp_child="$dhp_verified" + elif [ "$dhp_fallback_n" = 1 ]; then + dhp_child="$dhp_fallback" + fi + # A WRAPPER WHOSE CHILD IS THE COMPANION IS THE COMPANION'S OWN HOST + # (Copilot on 05d7889, PR #61, with the companion set above): the + # harness's record may carry the `claude` leaf's pid rather than the + # `bg-pty-host` wrapper's, so EVERY child `pgrep -P` listed is asked + # — named or not — and a match drops the whole pair. Terming the + # wrapper ends the companion with it. + dhp_is_comp_host=0 + for dhp_c in $dhp_kids; do + case "$dhp_comp" in *" $dhp_c "*) dhp_is_comp_host=1; break ;; esac + done + if [ "$dhp_is_comp_host" = 0 ]; then + dhp_out="${dhp_out}${dhp_pid}${US}${dhp_child}${US}${dhp_id} +" + fi + break + fi + done + done <<EOF +$dhp_cand +EOF + [ -n "$dhp_out" ] || return 8 + printf '%s' "$dhp_out" +} + +# THE `--resume` VALUE, READ WHOLE (opensoft/openRepoTools#76), for both of +# `duplicate_holder_pids`' matches above. It sets `dhp_rv` in the caller's own +# shell, never through `$( … )`, which would fork once per candidate, to the +# value after the FIRST `--resume ` in a flattened, already-lowercased argv, +# or to empty where there is no value it can name. +# +# `ps -o args=` JOINS THE ARGV WITH SPACES AND QUOTES NOTHING, so where one +# argument ends is gone from the line this reads. Measured with procps on +# Linux: `--resume "/home/Jane Doe/.claude/projects/p/<id>.jsonl" +# --output-format stream-json` reads back as `--resume /home/Jane +# Doe/.claude/projects/p/<id>.jsonl --output-format stream-json`. The cut this +# replaced, `${v%% *}`, took `/home/jane` from that and matched nothing, so a +# duplicate resumed from a home, profile or project directory with a space in +# it was never found, and `lane-end`'s pre-kill recheck, which made the same +# cut, would have withheld the TERM it is there to send. +# +# THE VALUE ENDS AT THE FIRST `.jsonl` THAT ENDS AN ARGUMENT, one followed by +# a space or by the end of the line, because the transcript path a harness +# resumes ends exactly there. That keeps both of PR #61's earlier guarantees: +# Copilot round 5's `--resume /other.jsonl --label /<id>.jsonl` still reads +# `/other.jsonl` and never this transcript, and round 4's `<id>.jsonl.bak` +# is still not `<id>.jsonl`, because its `.jsonl` ends no argument. +# +# A WORD OPENING WITH `--` INSIDE IT IS A LATER OPTION, NOT A DIRECTORY, and a +# value that holds one is EMPTY. `--resume <a bare session id> --x +# /<id>.jsonl` has no `.jsonl` of its own to stop at, so the first one that +# ends an argument is the later option's, and naming the process from it +# would hand `lane-end --retire` a TERM for something that resumed another +# session. +# +# A VALUE WITH A SPACE IN IT MUST BE ONE ABSOLUTE PATH, starting with `/` and +# holding no ` /`, or it is EMPTY (Brett Heap's ruling of 2026-10-18 on PR +# #205, "Add the condition first (Recommended)"). A value that does not itself +# end in `.jsonl` runs on to the next `.jsonl` that ends an argument, so a +# later plain word ending in `/<id>.jsonl` was read as its tail, where the cut +# at the first space never read it at all. Five shapes did that: a bare +# session id followed by a prompt that names the transcript (`--resume <id> +# read /p/<id>.jsonl and summarise`, and `claude -p … --resume <id> summarise +# /p/<id>.jsonl`), an empty argument before the path (`--resume '' +# /p/<id>.jsonl`, which `ps` prints with two spaces), a `<id>.jsonl.bak` +# followed by a word that names the transcript (`--resume /p/<id>.jsonl.bak +# note /q/<id>.jsonl`), and a shell whose `-c` string resumes `$ID` and then +# tails the transcript. Each of them starts with something other than `/`, or +# reaches the later path through a space and a `/`, and a transcript path does +# neither, whatever spaces its home, profile or project directory holds, save +# a directory whose name ENDS in a space before its `/`, which puts a ` /` +# inside the path, so it is refused (see the known limits below). A value with +# no space in it is untouched by this, and reads as the cut read it. +# +# KNOWN LIMITS, and they are the flattening's rather than this read's. A +# directory whose own name holds `.jsonl ` or ` --`, or ends in a space before +# its `/`, is cut short or refused, which only ever misses. The one shape this +# read can still mistake is narrower now: a value that starts with `/` but +# does not itself end in `.jsonl`, followed by a later word that names +# `<id>.jsonl` and does not begin with `/` (`--resume /p/<id>.jsonl.bak note +# q/<id>.jsonl`, and likewise a word opening `~/`, `$HOME/`, `file:///`, +# `path=/` or `(/`), which reaches it through no ` /`. Linux's +# `/proc/<pid>/cmdline` keeps the argument boundaries and BSD/macOS has +# nothing like it, so one portable reading of `ps`, the same on every +# platform and under the suite's own fake `ps`, is kept over two that could +# disagree. `lane-end` carries the same rule for its pre-kill recheck +# (`dh_resume_value`), and the two must stay the same rule. +dhp_resume_value() { # <flattened argv, lowercased> — sets dhp_rv + dhp_rv="" + case "${1-}" in *"--resume "*) : ;; *) return 0 ;; esac + dhp_rv_rest="${1#*--resume }" + while :; do + case "$dhp_rv_rest" in *.jsonl*) : ;; *) dhp_rv=""; return 0 ;; esac + dhp_rv="${dhp_rv}${dhp_rv_rest%%.jsonl*}.jsonl" + dhp_rv_rest="${dhp_rv_rest#*.jsonl}" + case "$dhp_rv_rest" in "" | " "*) break ;; esac + done + case "$dhp_rv" in *" --"*) dhp_rv="" ;; esac + case "$dhp_rv" in *" "*) + case "$dhp_rv" in /*) : ;; *) dhp_rv="" ;; esac + case "$dhp_rv" in *" /"*) dhp_rv="" ;; esac + esac + return 0 +} + +# ------------------------------- decisions 6 and 7: THE LANE LISTING READ +# +# ONE READ, TWO LISTINGS. Decision 6 ratified the estate-wide `lanes`; decision +# 7 ratified `restart`'s per-repo listing and `/restart`'s. All three are the +# same rows with a different filter, so the filter is an argument here rather +# than three implementations in three commands — the rule clause (h) already +# gives `window-lane` and `session-lane`. +# +# READ-ONLY, out of `origin/<branch>` like every Amendment 7 read, and +# `LANES_NO_FETCH=1` is honoured by the one `log_sync` its caller makes. It +# never writes and never launches anything. +# +# lanes_rows [--repo <owner/repo>] [--dir <path>] [--ws <ws>] [--all] +# +# `--repo` and `--dir` are decision 7's per-repo scope and they are an OR, not +# an AND: "rows whose register `home` is this checkout's `origin`, OR whose +# recorded `dir` is this checkout". That second half is a second use for clause +# (c)'s `dir` and an argument for recording it, because a lane's home +# repository and the checkout it sits in are not the same fact. +# +# Tab-separated, one line per lane, and the COLUMNS ARE THE DATA rather than a +# rendering: `restart` and `lanes` lay them out, and a third caller that wants +# a different shape does not need a fourth read. +# +# <lane> <state> <workstation> <profile> <window> <last uuid> <dir> +# <objects> <age> <restart line> <home> <forks> +# +# THE FIRST TEN ARE CLAUSE (j)'s TEN, IN CLAUSE (j)'s ORDER (A11 Addendum 4 +# ruling 7): *"`lanes` and `restart` each render the subset of clause (j)'s ten +# columns their surface needs while the read carries all ten."* Column 10 — the +# restart line — used to be computed by each renderer, which is two +# implementations of one column; it is the read's now, so the two surfaces +# cannot disagree about which lane may be restarted or about what to type. +# +# `<home>` and `<forks>` are the read's own additions after the ten. +# `<forks>` is decision 8(e): the count of LIVE forks of this lane's transcript +# — a defect to retire, shown by both listings and never counted as a holder. +# +# Newest activity first, by the UTC of the lane's last lane-kind line. That is +# a clock and it decides nothing but the ORDER OF A LISTING, which is the one +# place a clock is allowed to: `swapped` ranks by landing order because a +# launcher BINDS from its first row, and nothing binds from this one. +# Every LIVE session id on this workstation with the window it is in, as +# `<sessionId><US><tmux target><US><name><US><pid>`. ONE pass over the records +# for the whole listing: `live_holder` answers about one lane and re-reads +# every record to do it, which for a 48-row register is 48 scans of the same +# directory. +# +# CACHED IN A FILE AND NOT IN A VARIABLE (A11 Addendum 4 ruling 12). Every +# caller invokes this inside `$( … )`, which is a SUBSHELL — so the variable the +# build set died with the build and the next lane rebuilt it, 564 records at a +# time, 46 times for one listing. A file survives the subshell that wrote it. +live_session_ids() { + lsi_c="${SE_CACHE_FILE:+$SE_CACHE_FILE.live}" + if [ -n "$lsi_c" ] && [ -f "$lsi_c" ]; then cat -- "$lsi_c"; return 0; fi + # ITS OWN STEP, FOR THE HERE-DOCUMENT'S SAKE, exactly as in `fork_map`: a + # session tree that could not be read is not a workstation with nothing live + # on it, and this answer decides the STATE column of every row a listing + # prints (#26, the review of `37632b1`). + lsi_recs=""; lsi_rc=0 + lsi_recs="$(session_records)" || lsi_rc=$? + [ "$lsi_rc" = 0 ] || return 1 + lsi_out="" + while IFS="$US" read -r lsi_f lsi_sid lsi_tmux lsi_name lsi_pid lsi_kind lsi_cwd lsi_status lsi_start; do + [ -n "${lsi_sid:-}" ] || continue + record_fields_are_session "$lsi_kind" || continue + record_fields_are_live "$lsi_status" "$lsi_pid" "$lsi_start" || continue + lsi_out="${lsi_out}${lsi_sid}${US}${lsi_tmux}${US}${lsi_name}${US}${lsi_pid} +" + done <<EOF +$lsi_recs +EOF + if [ -n "$lsi_c" ]; then + printf '%s' "$lsi_out" > "$lsi_c.${BASHPID:-$$}" 2>/dev/null && + mv -f -- "$lsi_c.${BASHPID:-$$}" "$lsi_c" 2>/dev/null || + rm -f -- "$lsi_c.${BASHPID:-$$}" + fi + printf '%s' "$lsi_out" +} + +# Every lane the register has a row for — the union with `known_lanes` is what +# a listing shows, because a lane may have a row and no log (pre-cutover) or a +# log and a row that has been closed. +register_lanes() { + { register_text; archive_text; } | awk ' + substr($0,1,1) == "|" { + p1 = index($0, "`"); if (p1 == 0) next + rest = substr($0, p1 + 1); p2 = index(rest, "`"); if (p2 == 0) next + print substr(rest, 1, p2 - 1) + }' +} + +# ONE PASS OVER THE REGISTER FOR THE WHOLE LISTING (A11 Addendum 4 ruling 12). +# `<lane><US><workstation><US><session ids, lower-cased, space separated>` +# +# The four facts the listing wants from a row — is there a row, whose +# workstation, which ids, which is last — were four separate reads per lane, +# each of them `register_text | awk` and each therefore a render of the +# published 1.1 MB register. This is the same three answers from one pass, and +# the parsing is the SAME parsing: `ROW_AWK`'s first-backticked-token rule for +# the name, `row_cell`'s "field k+1 because $1 is the empty string before the +# leading pipe" for the cells, `lane_workstation`'s strip-at-the-first-slash for +# the workstation, and `uuids_in_cell`'s shape match — restated here in awk +# because a reader comparing the two must be able to see both. +LANES_REGISTER_INDEX_AWK=' + # THE STATE CELL IS THE SEVENTH, AND SIX ` | ` SEPARATORS ARE THE PROOF — + # `row_split_state_cell` in awk, for the same reason the three reads above + # are restated here: this pass already holds the row, and a second read of + # the same megabyte to ask what the cell says would cost the listing what + # ruling 12 spent this function to save. The rule is that files: split from + # the left, six separators or it is not knowable WHICH text is the state + # cell, and then the last piece is it. More than six returns EMPTY rather + # than a guess — the writer refuses that row outright, and a reader that + # picked one of the two readings would be filing a lane by the wrong text. + function cell_state(row, body, rest, i, cnt) { + sub(/[ \t]+$/, "", row) + if (substr(row, 1, 1) != "|") return "" + if (substr(row, length(row), 1) != "|") return "" + body = substr(row, 1, length(row) - 1) + rest = body; cnt = 0 + while (cnt < 6) { + i = index(rest, " | ") + if (i == 0) return "" + rest = substr(rest, i + 3) + cnt++ + } + if (index(rest, " | ") > 0) return "" + return rest + } + function trim(t) { sub(/^[ \t]+/, "", t); sub(/[ \t]+$/, "", t); return t } + substr($0, 1, 1) != "|" { next } + { + p1 = index($0, "`"); if (p1 == 0) next + rest = substr($0, p1 + 1); p2 = index(rest, "`"); if (p2 == 0) next + lane = substr(rest, 1, p2 - 1) + n = split($0, c, "|") + ses = (n >= 3 ? c[3] : "") + ws = (n >= 4 ? c[4] : "") + # COLUMN 4, `started (UTC)`, AS THE ROW SPELLS IT. The live register + # writes that column three ways — `2026-09-02`, `2026-09-04 ~15:30Z` and + # `2026-09-13T17:41Z` — and this carries the text, not an instant: the + # sweep prints it for a person to read, and `mig_started_utc` is the one + # place that turns it into a UTC. + started = (n >= 5 ? trim(c[5]) : "") + gsub(/\t/, " ", started) + sub(/^[ \t]+/, "", ws); sub(/[ \t]+$/, "", ws) + sub(/ *\/.*$/, "", ws) + sub(/[ \t].*$/, "", ws) + # `short_ws` IS `printf | tr`, TWO PROCESSES, and the listing ran it per + # lane to decide the workstation filter. It is one `sub` and a `tolower` + # here, in the pass that already has the value. + wss = tolower(ws); sub(/\..*$/, "", wss) + ids = ""; s2 = tolower(ses) + while (match(s2, /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/)) { + ids = ids substr(s2, RSTART, RLENGTH) " " + s2 = substr(s2, RSTART + RLENGTH) + } + sub(/ $/, "", ids) + # THE STATE CELL: ITS HEAD, AND THE WORDS A SWEEP MUST NOT PASS OVER + # SILENTLY (Amendment 19(b) and (c)). The head is what `lanes --closed` + # shows for a dormant row and what its `RETIRED` line carries as + # `was:`, so the row-s own last words survive the sweep that closes it; + # the flags are read from the WHOLE cell and not from the head, because + # the five words that matter — the work was unpushed, lost, a loss, owed, + # or the cell still says LIVE — sit at the end of cells thousands of + # characters long on the register this was written for. + # CUT BACK TO A SPACE: `substr` counts bytes in some awks and characters + # in others, and a cut mid-character would put half a `—` into a log line + # that is append-only. Dropping the last (possibly torn) word costs a word + # and can never do that. + # + # AND THESE TWO ARE A TABLE OF THEIR OWN (`--cells`), NEVER THE ONE THE + # LISTING SCANS PER LANE — ruling 12 again, measured. `table_lookup` walks + # the whole table for every lane, so a free-text field of up to 280 + # characters per row is paid for N times: on a register of 132 rows one + # `lanes --prefix <repo>` went from 14 s to 42 s with `head` and `flags` + # in this table, which is what put the pick past the 60-second terminal + # case in CI. The four short facts every row needs stay here; the two long + # ones are asked for BELOW THE NARROWING FILTER and only for a row with no + # object log, which is the only row that has anything to say with them + # (Amendment 19(a)). + if (!cells) { + print tolower(lane) sep lane sep ws sep wss sep ids sep started + next + } + cell = cell_state($0) + # An invalid column boundary is NOT an empty state cell. Leave this row + # out of the cells index so the caller keeps it unclassified and visible. + if (cell == "") next + gsub(/\t/, " ", cell) + cell = trim(cell) + head = cell + if (length(head) > 280) { + head = substr(head, 1, 280) + sub(/[^ ]*$/, "", head) + head = trim(head) + if (head == "") head = substr(cell, 1, 200) + head = head " ..." + } + lcell = tolower(cell) + flags = "" + if (lcell ~ /(^|[^a-z])unpushed([^a-z]|$)/) flags = flags "unpushed," + if (lcell ~ /(^|[^a-z])lost([^a-z]|$)/) flags = flags "lost," + if (lcell ~ /(^|[^a-z])loss([^a-z]|$)/) flags = flags "loss," + if (lcell ~ /(^|[^a-z])owe[sd]([^a-z]|$)/) flags = flags "owes," + if (lcell ~ /(^|[^a-z])live([^a-z]|$)/) flags = flags "LIVE," + sub(/,$/, "", flags) + # KEYED ON THE LANE NAME LOWER-CASED, because `lane_named_ci` is the rule + # everywhere else in this file: the register spells one lane three ways in + # a week, and the names this listing joins on come from the LOG files. + # (No apostrophe in this comment: the whole program is a single-quoted + # shell string, and one would end it.) + print tolower(lane) sep head sep flags + }' +# `--local` READS THIS CHECKOUT'S REGISTER instead of the published one, which +# is `session_ids_local_of_lane`'s source and is unioned with the published ids +# for the same fail-closed reason that read gives: an id this checkout knows and +# `origin/main` does not yet is one more reason to refuse, never to allow. +# `--cells` IS THE OTHER HALF OF THE SAME PASS: `<lane>` and the state cell-s +# head and flag words, and nothing else. It is a separate call because it is a +# separate COST — see the awk above — and the listing asks for it only where a +# row has no object log to speak for it. +lanes_register_index() { # [--local] [--cells] + lri_local=0; lri_cells=0 + while [ $# -gt 0 ]; do + case "$1" in + --local) lri_local=1; shift ;; + --cells) lri_cells=1; shift ;; + *) break ;; + esac + done + if [ "$lri_local" = 1 ]; then + { cat -- "$LANES_FILE" 2>/dev/null || : + [ -f "$LANES_ARCH_FILE" ] && { cat -- "$LANES_ARCH_FILE" 2>/dev/null || :; } + } | awk -v sep="$US" -v cells="$lri_cells" "$LANES_REGISTER_INDEX_AWK" 2>/dev/null + else + { register_text; archive_text; } | awk -v sep="$US" -v cells="$lri_cells" "$LANES_REGISTER_INDEX_AWK" + fi +} + +# SCOPE, AFTER A11 Addendum 4 RULING 6 (ratified "a11 addendum 4 yes", ruling 6 +# = NO to the workstation-scoped default): +# +# default EVERY lane the register and the logs know — clause (j) as +# written. It used to be this workstation's, and that was never in +# the contract: `window-lane` is scoped and the contract says so at +# length (`R-A11-8`/RV-T7); this read is not. "List the lanes" on a +# two-workstation estate means both. +# --here this workstation only. The old default, kept as an OPTION. +# --ws <n> a named workstation only, which implies the same narrowing. +# --all no narrowing of any kind: it CLEARS `--repo`, `--dir`, `--prefix` +# and `--here`, so a caller that has narrowed can undo it in one +# word. That is what the settlement means by "`--all` forces the +# every-lane listing". +# +# `--prefix <repo>` is the LABEL fallback and nothing more: a lane whose log +# records NEITHER a home NOR a directory cannot be filed by either, and its +# name's `<repo>-` prefix is the only thing left. Amendment 7 calls that prefix +# a label rather than a fact, so it is used ONLY where the two facts are absent +# — never to override a home that disagrees with it, which is the case +# `openRepoTools#28` says must be SAID rather than filed twice. +lanes_rows() { + lr_repo=""; lr_dir=""; lr_ws="$WS"; lr_here=0; lr_all=0; lr_one=""; lr_prefix="" + lr_closed=0 + while [ $# -gt 0 ]; do + case "$1" in + --repo) lr_repo="${2-}"; shift 2 || return 64 ;; + --dir) lr_dir="${2-}"; shift 2 || return 64 ;; + --prefix) lr_prefix="${2-}"; shift 2 || return 64 ;; + --ws) lr_ws="${2-}"; lr_here=1; shift 2 || return 64 ;; + --lane) lr_one="${2-}"; shift 2 || return 64 ;; + --here) lr_here=1; shift ;; + --all) lr_all=1; shift ;; + # AMENDMENT 19(b) — `--closed` ADDS the CLOSED and the DORMANT rows, and + # it COMBINES with everything rather than replacing it: with `--all` it is + # every repository-s closed lanes, with `--here` this workstation-s. So it + # is deliberately NOT cleared by the `--all` reset below, which exists to + # undo a NARROWING; this flag widens. + --closed) lr_closed=1; shift ;; + *) return 64 ;; + esac + done + # `--all` LAST AND ABSOLUTE, whatever order the flags arrived in — AND THAT + # INCLUDES `--lane`, which this reset used to leave standing (#26, the review + # of `c3ebcfe`). `--lane <name>` is the narrowest selector there is: the block + # below it sets `lr_names` to that one name and clears the other four filters + # for itself, so `lanes --all --lane X` answered about ONE lane under the flag + # that means every lane. The sentence above it has said "absolute" since it was + # written; this is the code catching up with it, and it is the same defect the + # wrapper's own `here_repo` had one file up (`lanes:143`, taken at `2f44da0`). + if [ "$lr_all" = 1 ]; then lr_repo=""; lr_dir=""; lr_prefix=""; lr_here=0; lr_one=""; fi + [ -n "$lr_dir" ] && lr_dir="$(cd -- "$lr_dir" 2>/dev/null && pwd -P || printf '%s' "$lr_dir")" + # ONE LANE, WITHOUT SCANNING THE ESTATE. `lane <name>` needs one row's + # `profile` and nothing else, and building the whole listing for it would walk + # every log, every row and every live session record on the workstation to + # answer a question about one lane. Same rows, same columns, same code. + # EACH NAME CARRIES ITS OWN LOWER-CASED KEY, emitted by the pass that already + # computes it for the de-duplication: the three lookups below join on that key + # and `lc` is two processes (ruling 12). + if [ -n "$lr_one" ]; then + lr_names="$(printf '%s\n' "$lr_one" | awk -v sep="$US" 'NF { print tolower($0) sep $0 }')" + lr_here=0; lr_repo=""; lr_dir=""; lr_prefix="" + else + # THE REGISTER FIRST, AND THAT IS AMENDMENT 15 (it was the logs first). + # The de-duplication has always been on the name LOWER-CASED, so for a lane + # both sources know it is the FIRST source that decides which spelling the + # listing prints — and the amendment says the register row's spelling is the + # canonical one. Read the other way round, a lane whose log file predates + # its row's spelling was listed under the file name, and column 10's + # line that binds the lane offered that spelling back to the reader. + lr_names="$( { register_lanes 2>/dev/null || :; known_lanes 2>/dev/null || :; } | awk -v sep="$US" 'NF && !seen[tolower($0)]++ { print tolower($0) sep $0 }')" + fi + [ -n "$lr_names" ] || return 8 + # ONE PASS OVER EVERY LANE'S EVENTS, NOT ONE READ PER LANE PER FIELD. + # `lanes` asks about every lane the register and the logs know, and this loop + # used to make a `git show` of each lane's log — and then a fork per sub-field + # on top. Measured on the live register: 24 s for a listing that shows ONE + # row, because the cost was the 74 lanes it filtered OUT. `state_events` is + # the stream every other state read in this file is built on, it is already + # cached for the life of the process, and `lane_row_facts` turns it into one + # line per lane carrying the six facts a row needs — `payload_subfield`'s two + # rules and `home_of_lane`'s one, applied in the same awk that parses. + # `--lane` READS ONE LOG, NOT THE ESTATE'S. `lane <name>` asks for one + # lane's profile and nothing else, and `state_events` is a `git show` per log + # file — nine seconds on the live register. The same parser over the same + # grammar either way, so the two answers cannot differ. + if [ -n "$lr_one" ]; then + lr_facts="$(lane_log_events "$lr_one" 2>/dev/null | lane_row_facts)" + else + lr_facts="$(state_events 2>/dev/null | lane_row_facts)" + fi + # AND A PUBLISHED LOG THAT COULD NOT BE READ IS NOT A LANE WITH NO LOG (#138 + # item 11). A lane absent from the facts is DORMANT below, and a log whose + # `git show` failed gave no lines; `remote_log_events` names each such log, + # and those lanes are fenced out of the class here. Without the warnings file + # (no temporary file could be made) no read can be told from a failed one, so + # no row is classed dormant at all. + lr_unread=" "; lr_unread_ok=1; lr_unread_paths="" + if [ -z "$lr_one" ] && [ -z "$LANES_IDX_DIR" ]; then + if [ -n "$SE_WARN_FILE" ]; then + lr_unread_paths="$(sed -n -e 's/^lanes-edit: unreadable log: \(.*\) — git could not read it.*$/\1/p' "$SE_WARN_FILE" 2>/dev/null)" + lr_unread=" $(printf '%s\n' "$lr_unread_paths" | awk 'NF { n = $0; sub(/^.*\//, "", n); sub(/\.md$/, "", n); print tolower(n) }' | tr '\n' ' ')" + else + lr_unread_ok=0 + fi + fi + [ -z "$lr_unread_paths" ] || + note "these published logs could not be read, so no lane of theirs is classed DORMANT: $(printf '%s\n' "$lr_unread_paths" | tr '\n' ' ')" + [ "$lr_unread_ok" = 1 ] || + note "no temporary file could be made for the read's warnings, so whether any published log failed to read is not known, and no row is classed DORMANT here." + # AND A REGISTER THAT COULD NOT BE READ IS SAID, ONCE (the re-review of #230). + # Every row above came out of `register_text`, which drops the status + # `register_text_checked` keeps (#67), and a published register git cannot + # read renders as no text, so those rows simply vanished — and the sweep + # counted none of them. The class is withheld, which `lane-end` refuses on. A + # read that succeeds fills the cache every later read here takes, so the + # check costs one render. + lr_reg_ok=1 + register_text_checked >/dev/null 2>&1 || lr_reg_ok=0 + [ "$lr_reg_ok" = 1 ] || + note "the register ($LANES_PATH, published or this checkout's) could not be read, so its rows are not in this listing, and no row is classed DORMANT here." + # THE REGISTER AND THE LIVE RECORDS, EACH READ ONCE FOR THE WHOLE LISTING + # (ruling 12). Both were per-lane before, and `live_session_ids` was rebuilt + # from 564 session records for every one of them. + # THE THREE TABLES, FENCED FOR AN IN-SHELL LOOKUP (ruling 12). `tr` turns each + # newline into `$GS` once, and `table_lookup` then finds any lane's line with + # one parameter expansion — instead of `printf | awk` per lane per table, + # which for fifty lanes was a hundred and fifty processes spent reading + # strings this shell was already holding. + # AN ARCHIVE THAT CANNOT BE READ IS SAID, NOT SWALLOWED (Copilot round 2 on + # #93). The two pipelines below end in `awk`, whose status is its own, so a + # failed `archive_text` inside them is invisible — and what goes missing is + # the CLOSED rows the archive holds. A listing may not refuse (it sits in + # front of a launch), so it says it, exactly as it says a session-record read + # that failed; the POSITION is the half that must not guess, and + # `lane_next_free` refuses there rather than offering one over a partial read. + if ! archive_text >/dev/null 2>&1; then + note "$LANES_ARCH_PATH exists and could not be read, so the RETIRED rows it holds are not in this listing — and \`next-free\` will refuse a position rather than offer one over a partial read." + fi + lr_index="$GS$(lanes_register_index 2>/dev/null | tr '\n' "$GS" || :)" + # THE CELLS ARE BUILT ON FIRST USE AND NOT BEFORE (see `lanes_register_index + # --cells`): a listing whose every row has an object log never asks for them, + # and the two passes that build them are two `awk`s over a register this + # function has already rendered once. + lr_cells=""; lr_lcells=""; lr_cells_built=0 + lr_local_index="$GS$(lanes_register_index --local 2>/dev/null | tr '\n' "$GS" || :)" + lr_facts_t="$GS$(printf '%s\n' "$lr_facts" | tr '\n' "$GS")" + # THE LIVE SCAN, AND WHAT A LISTING DOES WHEN IT FAILS (#26, the review of + # `37632b1`). NOT a refusal: this listing is the read a person makes IN FRONT + # OF A LAUNCH, and `43b6320`'s rule for the fetch is the rule here — it + # answers, and says what it could not establish. What it must never do is + # print a lane's log verb as its STATE in silence, because a lane that is + # LIVE then shows as IDLE or PAUSED and the row offers the `restart` line that + # would start a second session on it. The collision itself is still refused + # one surface along: `lane-start`'s own `live_holder` reads these same records + # DIRECTLY and exits 1 where they cannot be read. + lr_live_rows=""; lr_live_rc=0 + lr_live_rows="$(live_session_ids 2>/dev/null)" || lr_live_rc=$? + lr_fork_rc=0 + lr_live_fence=" $(printf '%s\n' "$lr_live_rows" | awk -F"$US" 'NF { print tolower($1) }' | tr '\n' ' ')" + lr_ws_short="$(short_ws "$lr_ws")" + lr_now="$(date -u +%s)" + # AMENDMENT 18(b), FOR THE PARTITION — computed ONCE for the whole listing, + # because `lc` is two processes and this is asked of every lane. The row + # carries the BINDING-s host and container (lower-cased by the awk above) and + # this is what they are compared against. + LANES_HOST_LC="$(lc "$LANES_HOST_NAME")" + LANES_WS_LC="$(lc "$WS")" + LANES_CONTAINER_LC="$(lc "$LANES_CONTAINER_NAME")" + # AND THE TWO NARROWING FILTERS' OWN SIDES, for the same reason: `--repo` and + # `--prefix` do not change from one lane to the next, and the loop below asked + # `lc` for both of them again for every lane in the estate (#107). The lane's + # side is per lane and goes through `lower_into`, which is `lc` without a fork. + lr_repo_lc=""; [ -z "$lr_repo" ] || lr_repo_lc="$(lc "$lr_repo")" + lr_prefix_lc=""; [ -z "$lr_prefix" ] || lr_prefix_lc="$(lc "$lr_prefix")" + # ONLY A LANE THE FORK MAP NAMES CAN HAVE A FORK (ruling 12). `lane_forks` + # stays the ONE implementation of what a fork is and what disqualifies one; + # this simply declines to ask it about the forty-five lanes of this estate + # that no live transcript is titled for, each of which cost a subshell, a + # `cat` of the map and a `grep` to be told nothing. + lr_fork_map="" + lr_fork_map="$(fork_map 2>/dev/null)" || lr_fork_rc=$? + lr_fork_titles=" $(printf '%s\n' "$lr_fork_map" | awk -F"$US" 'NF { print $1 }' | tr '\n' ' ')" + # THE LOG FILES THIS CHECKOUT HAS, LOWER-CASED, AS ONE FENCE (Copilot round 4 + # on #93). `state_events` reads the PUBLISHED logs (R19), so a log committed + # here and not yet pushed is not in the facts pass at all — and DORMANT is + # "no object log", which that lane has. The sweep reads the local log for + # exactly this reason since round 3, and the read and the writer may not + # disagree about the amendment's own condition. One `ls` for the whole + # listing, matched with a `case` per lane, and lower-cased because a lane name + # is ONE name under any case (Amendment 15). + # AND A DIRECTORY THAT IS THERE AND CANNOT BE LISTED IS NOT ONE WITH NO LOG IN + # IT (#138 item 4): the fence would be empty and a lane whose only log is here + # classed DORMANT. It is said, and no row is classed dormant over it below. + lr_logfiles=""; lr_logs_rc=0 + if [ -e "$LANES_LOG_DIR" ]; then + lr_logfiles="$(ls -- "$LANES_LOG_DIR" 2>/dev/null)" || lr_logs_rc=1 + fi + lr_logfiles=" $(printf '%s\n' "$lr_logfiles" | awk '{ print tolower($0) }' | tr '\n' ' ')" + [ "$lr_logs_rc" = 0 ] || + note "$LANES_LOG_DIR exists and could not be listed, so whether a row has a log this checkout has and origin has not is not known, and no row is classed DORMANT here. Fix the read and re-run before sweeping." + if [ "$lr_live_rc" != 0 ] || [ "$lr_fork_rc" != 0 ]; then + note "this workstation's session records could not be read, so the STATE column below is the LOG's verb alone: a lane that is live may show as IDLE or PAUSED here, and no fork of any lane is established either way. Fix the read and re-run before acting on a restart line." + fi + lr_out="" + while IFS="$US" read -r lr_ll lr_l; do + [ -n "$lr_l" ] || continue + lr_verb=""; lr_utc=""; lr_w=""; lr_d=""; lr_pf=""; lr_win=""; lr_home=""; lr_logsid=""; lr_obj="" + # DOES THIS LANE HAVE AN OBJECT LOG AT ALL? `lane_row_facts` emits a line + # for every lane whose log carries one of Amendment 7-s five lane verbs, so + # this lookup — which the listing makes anyway — is the answer, and + # Amendment 19(a)-s DORMANT is built on it below. + lr_lanekind=0 + lr_bhost=""; lr_bcont=""; lr_blegacy="" + if table_lookup "$lr_facts_t" "$lr_ll"; then + lr_lanekind=1 + IFS="$US" read -r lr_fl lr_verb lr_utc lr_w lr_d lr_pf lr_win lr_home lr_logsid lr_obj \ + lr_bhost lr_bcont lr_blegacy <<EOF2 +$LOOKUP_OUT +EOF2 + fi + # THE ROW'S THREE FACTS, OUT OF THE ONE PASS: is there a row at all, whose + # workstation it names, and which transcript uuids its session cell carries. + # AND ITS `started` CELL (Amendment 19(b)), which `--closed` prints for a + # CLOSED row as well as a dormant one and which is a date rather than free + # text. Its state cell's HEAD and FLAGS are NOT here — they are the one + # table this loop does not walk per lane, and they are fetched below the + # narrowing filter for the rows that have no log to speak for them. + lr_ixl=""; lr_rw=""; lr_rws=""; lr_ids_sp=""; lr_start=""; lr_was=""; lr_flags="" + if table_lookup "$lr_index" "$lr_ll"; then + IFS="$US" read -r lr_ixl lr_rw lr_rws lr_ids_sp lr_start <<EOF2 +$LOOKUP_OUT +EOF2 + fi + lr_lixl=""; lr_lrw=""; lr_lrws=""; lr_lids_sp=""; lr_lstart=""; lr_lwas=""; lr_lflags="" + if table_lookup "$lr_local_index" "$lr_ll"; then + IFS="$US" read -r lr_lixl lr_lrw lr_lrws lr_lids_sp lr_lstart <<EOF2 +$LOOKUP_OUT +EOF2 + fi + # THE PUBLISHED ROW-S WORDS WIN AND THIS CHECKOUT-S ANSWER ONLY FILLS IN + # (R19): a row this checkout has added and not yet pushed has no published + # text at all, and showing nothing about it would hide the newest row on the + # workstation that made it. + [ -n "$lr_start" ] || lr_start="$lr_lstart" + # THE REGISTER'S OWN WORKSTATION COLUMN WINS where the row has one: it is + # what every other read in this file compares, and a lane may have a row + # here and its last log line from another machine. + [ -n "$lr_rw" ] && lr_w="$lr_rw" + if [ "$lr_here" = 1 ] && [ -n "$lr_w" ]; then + lr_wcmp="$lr_rws"; [ -n "$lr_wcmp" ] || lr_wcmp="$(short_ws "$lr_w")" + [ "$lr_wcmp" = "$lr_ws_short" ] || continue + fi + lr_row="$lr_ixl" + if [ -n "$lr_home" ]; then + lr_hc="$(alias_lookup "$lr_home" 2>/dev/null || :)" + [ -n "$lr_hc" ] && lr_home="$lr_hc" + fi + if [ -n "$lr_repo" ] || [ -n "$lr_dir" ] || [ -n "$lr_prefix" ]; then + lr_keep=0 + if [ -n "$lr_repo" ] && [ -n "$lr_home" ]; then + lower_into "$lr_home" + [ "$LOWER_OUT" = "$lr_repo_lc" ] && lr_keep=1 + fi + [ -n "$lr_dir" ] && [ -n "$lr_d" ] && [ "$lr_d" = "$lr_dir" ] && lr_keep=1 + # THE LABEL, AS A THIRD OR-TERM. Amendment 7 calls a lane name's + # `<repo>-` prefix a LABEL rather than a fact, and the home is what FILES + # a lane — but a listing is asked "which lanes are this repository's", and + # two populations answer that and are missed by home and `dir` alike: + # * a lane with a ROW AND NO LOG, which this estate has, whose home and + # directory are simply not recorded anywhere yet; + # * a lane a person NAMED for this repository whose log records a + # different home — the disagreement `openRepoTools#28` says to SAY + # rather than resolve, and still a position `lane-start <repo> <n>` + # cannot hand out twice. + # It never overrides a home: a lane matched only by its label is LISTED, + # not re-homed. + if [ "$lr_keep" = 0 ] && [ -n "$lr_prefix" ]; then + lower_into "$lr_l" + case "$LOWER_OUT" in "$lr_prefix_lc"-*) lr_keep=1 ;; esac + fi + [ "$lr_keep" = 1 ] || continue + fi + # FAILING THE CELL, THE LANE'S OWN LOG — clause (d) rule 3, out of the same + # one pass rather than a second read of the same stream. + lr_sid="${lr_ids_sp##* }" + [ -n "$lr_sid" ] || lr_sid="$lr_logsid" + # THE STATE. A live record naming one of the lane-s ids beats the log-s + # own last verb, because a lane whose session is running is LIVE whatever + # its last written line says; otherwise the verb answers. + # + # A `case` OVER A SPACE-FENCED STRING, AND NOT A `grep` PER RECORD (ruling + # 12): this ran `printf | grep -qx` once for every live record for every + # lane. The fence is built once above; the lookup of the WINDOW is an awk, + # and it only happens for a lane that is actually live. + # THE IDS OF BOTH ROWS, AND THAT IS FAIL-CLOSED (Copilot round 1 on #93). + # The published cell is R19's source for everything else here, but a lane + # whose `append-session-id` has landed in THIS checkout and not yet been + # pushed has its current transcript in the local row alone — and + # `live_session_ids` can see that very session running. Read from the + # published cell only, such a lane is not LIVE, which under Amendment 19(a) + # makes it DORMANT: hidden from the listing and offered to the sweep while + # somebody is working in it. Both sets are asked, and either one naming a + # live record is LIVE. + lr_state="" + lr_live_win="" + for lr_one_id in $lr_ids_sp $lr_lids_sp; do + case "$lr_live_fence" in + *" $lr_one_id "*) + lr_state=LIVE + lr_live_win="$(printf '%s\n' "$lr_live_rows" | awk -F"$US" -v i="$lr_one_id" 'tolower($1) == i { print $2; exit }')" + break ;; + esac + done + if [ -n "$lr_live_win" ]; then + lr_win="$lr_live_win" + elif [ -n "$lr_win" ]; then + # SPEC rev 4 §15 column 5: the window is marked `gone` where the ref no + # longer resolves. After a tmux server restart that is EVERY recorded + # window on the workstation — measured on Eagle at 15:5xZ on 2026-09-13, + # 0 of 5 — and a column that showed a dead ref as though it were live is + # the column a person would try to attach to. + lr_wref="${lr_win%% *}" + [ -n "$(tmux_window_field "$lr_wref" '#{window_id}' 2>/dev/null || :)" ] || lr_win="$lr_win (gone)" + fi + if [ -z "$lr_state" ]; then + case "$lr_verb" in + PAUSED) lr_state=PAUSED ;; + ENDED) lr_state=ENDED ;; + RETIRED) lr_state=RETIRED ;; + STARTED|RESUMED) lr_state=IDLE ;; + *) lr_state="$([ -n "$lr_row" ] && printf 'NO LOG' || printf 'UNKNOWN')" ;; + esac + fi + # THE STATE CELL-S HEAD AND FLAGS, FOR THE ROWS THEY ARE ABOUT — a row with + # NO OBJECT LOG (Amendment 19(a)). It is the only row whose cell is all the + # listing has: one with a log has the log, and `lanes` prints neither field + # for it. The lookup is HERE, below the narrowing filter, because a row this + # listing is not showing is a row it may not pay for — and it walks a table + # of its own rather than the one above, which every lane in the estate walks + # once (ruling 12: the measurement is in `LANES_REGISTER_INDEX_AWK`). + # + # AND A ROW THE CELLS PASS DID NOT SEE IS NOT A ROW WITH NO CELL. The two + # passes read ONE register text, so every row in the table above is in this + # one; a row in the first and not the second is a read that answered + # differently the second time, and an EMPTY cell read as an answer would + # make `mig_cell_is_phrase` false and class the row DORMANT — hiding a row + # whose cell may say PAUSED and offering it to the sweep, which is the one + # thing 13(a) is in this rule for. `lr_cellrow` carries whether the pass saw + # it, and the class below is not decided without it (Amendment 7(d), the + # same posture round 3 gave the liveness read). It is the PUBLISHED pass + # that carries it, because the published row is the only one the class is + # ever decided on — `lr_row` is `lr_ixl` and a row this checkout alone has + # is in no class either way. + lr_cellrow=0 + if [ "$lr_lanekind" = 0 ] && [ -n "$lr_ixl$lr_lixl" ]; then + if [ "$lr_cells_built" = 0 ]; then + lr_cells="$GS$(lanes_register_index --cells 2>/dev/null | tr '\n' "$GS" || :)" + lr_lcells="$GS$(lanes_register_index --local --cells 2>/dev/null | tr '\n' "$GS" || :)" + lr_cells_built=1 + fi + if table_lookup "$lr_cells" "$lr_ll"; then + lr_cellrow=1 + IFS="$US" read -r lr_was lr_flags <<EOF2 +$LOOKUP_OUT +EOF2 + fi + if table_lookup "$lr_lcells" "$lr_ll"; then + IFS="$US" read -r lr_lwas lr_lflags <<EOF2 +$LOOKUP_OUT +EOF2 + fi + [ -n "$lr_was" ] || lr_was="$lr_lwas" + [ -n "$lr_flags" ] || lr_flags="$lr_lflags" + fi + # ------- AMENDMENT 19(a): THE TWO STATES BELOW PARKED, AND WHO IS IN THEM + # + # CLOSED is a lane whose own log has FINISHED — its last lane-kind line is + # `ENDED` or `RETIRED`, which is exactly what the block above has just put + # in `lr_state`. DORMANT is a row with NO OBJECT LOG and no live session + # here: the fourteen rows of openxFactory that ran before Amendment 7 gave + # every lane a log, that no `lane-end` can close because it wants a live + # session or a log to write into, and that sat at the top of every `lanes` + # while the next free position was read past them. + # + # "NO OBJECT LOG" IS ASKED OF THE FACTS TABLE AND NOT OF THE FILESYSTEM: + # `lr_lanekind` is that lookup, made once at the top of this loop, where a + # `git cat-file` per lane would have the listing pay for the whole estate to + # answer about the rows it is going to hide. + # + # AND THE REGISTER-S OWN CLAIM IS HONOURED (Amendment 13(a): the row says + # where a lane IS, in one line). A cell that is the phrase and whose state + # word is neither `ENDED`, `RETIRED` nor the migration-s `MIGRATED` says the + # lane is somewhere — PAUSED, LANDING, HANDED OFF — and hiding that row + # would hide a lane a person can still pick up, which is the opposite of + # what this amendment is for. It is the one way a row with no log is NOT + # dormant, and `mig_cell_is_phrase` is the same test the migration makes of + # the same cell rather than a second reading of it. + lr_class="" + case "$lr_state" in + ENDED|RETIRED) lr_class=closed ;; + LIVE) : ;; + *) + # AND NEVER OVER A LIVENESS READ THAT FAILED (Copilot round 3 on #93). + # DORMANT is "no object log AND no live session on this workstation"; + # where the session records could not be read, the second half was never + # established, and hiding the row on it would hide a lane somebody may + # be working in. The listing already SAYS the read failed (one screen + # up); this is what it does about it — leaves the class unset, so the + # row stays listed and the sweep is never offered it. + if [ -n "$lr_row" ] && [ "$lr_lanekind" = 0 ] && [ "$lr_live_rc" = 0 ] && + [ "$lr_cellrow" = 1 ] && [ "$lr_logs_rc" = 0 ] && [ "$lr_unread_ok" = 1 ] && + [ "$lr_reg_ok" = 1 ]; then + lr_class=dormant + # A LOG THIS CHECKOUT HAS AND `origin` HAS NOT IS STILL AN OBJECT LOG, + # AND SO IS ONE `origin` HAS AND GIT COULD NOT READ (item 11). + case "$lr_logfiles" in + *" $lr_ll.md "*) lr_class="" ;; + esac + case "$lr_unread" in + *" $lr_ll "*) lr_class="" ;; + esac + if mig_cell_is_phrase "$lr_was"; then + case "${lr_was%% · *}" in + ENDED|RETIRED|MIGRATED) : ;; + *) lr_class="" ;; + esac + fi + fi ;; + esac + # NEITHER IS LISTED BY DEFAULT (clause (b)) and `--closed` adds them back. + # `--lane <name>` IS NEVER FILTERED: it is the narrowest selector there is + # and its caller has NAMED the lane, so a closed lane asked about by name + # answers about itself instead of reading as a lane that does not exist — + # which is what `lane <name>`, `lane-start` and the handoff would all have + # been told by an empty answer. + if [ -n "$lr_class" ] && [ "$lr_closed" = 0 ] && [ -z "$lr_one" ]; then continue; fi + # THE ROW'S OWN STATE, WHERE THE LOG HAS NONE TO GIVE (#89, out of the + # suppressed comments of Copilot's review of #82). Amendment 13(a) makes the + # state cell the lane's CURRENT STATE, and `migrate-state-cells` leaves + # exactly that behind: the phrase in the cell and, in the log, NOTED lines + # and no lane-kind line at all. So the STATE above said `NO LOG` over a cell + # saying `PAUSED`, and the one column the amendment exists to make + # authoritative was the one column this listing did not consult. Where the + # log gave no answer and `mig_cell_is_phrase` proves the cell is the phrase + # — the same test the migration and the class above make of the same cell — + # the STATE is the cell's word with ` (row)` after it. + # + # ` (row)` IS PART OF THE WORD, AND THAT IS THE POINT: the word is SHOWN and + # never bound. A row with no lane-kind line records no directory, no profile + # and no binding, so there is nothing for `lane` to resume — and every + # reader that keys on the log's own `PAUSED` (column 10 below, `lane_groups`, + # the `bind it:` line of `lanes`) passes this word by without a change of + # its own. `lane_groups` files it `rowonly`, and `lane` refuses that group by + # name rather than launching on a word no log wrote. + # + # FOUR WORDS STAY `NO LOG`. `ENDED`, `RETIRED` and the migration's + # `MIGRATED` are the cells of Amendment 19(a)'s DORMANT rows, which 19(b) + # shows as `NO LOG` with that cell's head on a line of its own. And `LIVE` is + # the one case that is NOT symmetric: a cell cannot prove a session is + # running, only a live record can, and the read above has already been + # asked — a row it did not find live whose cell still says `LIVE` is the row + # column 17 flags, and a STATE column saying so would tell a person a lane + # is running that nothing has proved is. + # + # BELOW THE CLASS, ON PURPOSE: the cell is read only for a row with no object + # log and only below the narrowing filter (ruling 12), and the class is the + # LOG's question, decided on the log's answer before this changes the word. + if [ "$lr_state" = 'NO LOG' ] && mig_cell_is_phrase "$lr_was"; then + case "${lr_was%% · *}" in + LIVE | ENDED | RETIRED | MIGRATED) : ;; + *) lr_state="${lr_was%% · *} (row)" ;; + esac + fi + [ -n "$lr_obj" ] || lr_obj="none open" + lr_age="$([ -n "$lr_utc" ] && age_of "$lr_utc" "$lr_now" || printf 'age unknown')" + # THE TWO SETS `lane_forks` WOULD OTHERWISE RE-READ THE REGISTER FOR, handed + # to it out of the one pass this loop already made (ruling 12) — and asked + # at all only where a live transcript carries this lane's title. + lr_fk=0 + case "$lr_fork_titles" in + *" $lr_ll "*) + lr_fk="$(lane_forks "$lr_l" " $lr_ids_sp $lr_lids_sp " 2>/dev/null | grep -c . || :)" + case "$lr_fk" in ''|*[!0-9]*) lr_fk=0 ;; esac ;; + esac + # `none` AND NEVER A DASH, because three of these columns are `none` on + # this estate until adoption act 7 cuts each lane over — `profile`, + # `directory` and the `<@id>` half of `window` all come from records written + # under clause (c), and 0 of the 5 swap records on Eagle carry any of them. + # A word a reader can act on beats a glyph they have to interpret. + # COLUMN 10 — THE LINE THAT BINDS THE LANE — IS THE READ'S AND NOT A + # RENDERER'S (A11 Addendum 4 ruling 7). Clause (j) gives TEN columns in + # order and this carried nine; `lanes` computed the tenth and `restart` + # computed a different tenth, which is two implementations of one column and + # is how they would come to disagree about which lane may be restarted. + # + # THE WORD IS `lane <name>` (Amendment 18 Addendum 2, ratified + # 2026-09-14T16:50:32Z verbatim "ratify"): `restart` is no longer a command + # a person is given, and `lane <name>` is the same act — the launcher's + # path, the lane's own recorded directory and profile, asking nothing — + # plus the pick, the attach and the elsewhere branch. A column naming a word + # that is not on the person's PATH is a column they cannot type. + # + # A PAUSED LANE ONLY (clause (j) column 10, F-X20), and a PAUSED lane whose + # record carries NO `profile` gets the form that works today with the + # profile named as the one token the operator must supply — because a wrong + # profile is a launch into another account and nothing here may guess one, + # while a line that cannot be typed is worse than a column that says + # `none`. Every other state gets `none`: a lane whose last act was its last + # is not a lane a person restarts. + # + # AND A **LIVE** LANE'S ONE ACT IS THE ATTACH, FILLED IN (Amendment 18 + # clause (i), refined on the question Brett Heap asked 2026-09-14T13:47Z — + # verbatim *"how do i start claude with that profile and that lane? do i use + # lane command?"*, about a lane live in a DETACHED tmux session, where the + # listing named the session and no act). A live lane is never started a + # second time: clause (h) is one live process per transcript, and a + # `lane-start` or a `pclaude` on a running lane is exactly the second one. + # So the column carries `tmux switch-client` inside tmux and `tmux attach` + # outside it — the same two acts `lane`'s LIVE HERE branch performs, which + # is why the CHOICE between them is made here, in the read both surfaces + # share, and not in a renderer. + # + # THE TARGET IS `<session>:<@id>` WHERE THE RECORD KNOWS AN ID, and the + # session alone where it does not. Measured on this estate 2026-09-14 (tmux + # 3.4, private socket): `attach -t dst:@2` attached AND made `@2` current in + # ONE act, while `attach -t <session>` lands on whatever that session has + # since made current — another lane, which is the one thing the + # id-AND-session fence exists to stop. A bare session is still what a record + # with no `@id` can offer, and it is offered as that. + lr_restart=none + if [ "$lr_state" = PAUSED ]; then + if [ -z "$lr_pf" ] || [ "$lr_pf" = none ]; then + lr_restart="pclaude --lane $lr_l <profile>" + else + lr_restart="lane $lr_l" + fi + elif [ "$lr_state" = LIVE ]; then + # THE WINDOW COLUMN HAS TWO SHAPES AND BOTH REACH HERE. A LIVE row takes + # it from the live session record, whose `tmux` field is + # `<session>:<@id>.<%pane>`; every other row takes it from the log, whose + # `window` sub-field is Amendment 11(c)'s TWO space-separated refs, + # `<session>:<index> <@id>`. Reading one for the other is how this column + # would offer `tmux attach -t <session>:<index>` — an index another window + # can be given between the read and the act, which is exactly what the + # id-AND-session rule exists to stop. + lr_wref="${lr_win%% *}" + lr_attid="" + case "$lr_win" in *' @'*) lr_attid="${lr_win##* }" ;; esac + if [ -z "$lr_attid" ]; then + lr_wtmp="${lr_wref%%.*}" + case "${lr_wtmp#*:}" in @[0-9]*) lr_attid="${lr_wtmp#*:}" ;; esac + fi + lr_att="${lr_wref%%:*}" + [ -z "$lr_attid" ] || lr_att="$lr_att:$lr_attid" + case "${lr_win:-none}" in + none | *'(gone)'*) : ;; + *) + if [ -n "${TMUX:-}" ]; then lr_restart="tmux switch-client -t $lr_att" + else lr_restart="tmux attach -t $lr_att" + fi ;; + esac + fi + # COLUMN 13 — WHETHER THIS PLACE MAY PRONOUNCE ON THAT BINDING, and it is + # the READ-s answer and not a renderer-s (Copilot round 1 on this PR; the + # rule A11 Addendum 4 ruling 7 gave column 10). `lane-groups` filed an + # `IDLE` row as AVAILABLE on the workstation column alone — and an IDLE row + # is a binding THIS host could not see a live record for, which across a + # container seam is exactly the lane that IS running: two benches on one + # host share the profile directory, so the pick offered another container-s + # live lane and the launch made a second process on it. `here` is Amendment + # 18(b)-s only place liveness may be pronounced from; a pre-clause line is + # matched on the host alone, which is clause (a)-s cutover sentence; and + # `none` is a lane with no binding line at all, which changes nothing about + # how it was filed before this column existed (it was EMPTY until Amendment + # 19-s four columns came after it — see below for why it cannot be now). + # AND ONLY WHERE THERE IS A BINDING TO BE LOCAL TO. The binding fields come + # from the last `STARTED`/`RESUMED` whatever released it since, so a PARKED + # lane still carries the host and container of the place that last ran it — + # and a lane parked in another container is AVAILABLE here, because parking + # IS the handoff (asserted since Amendment 18 Addendum 1). Column 13 means + # *the locality of a binding that stands*, and is `none` where none does. + lr_local="" + case "$lr_verb" in STARTED|RESUMED) : ;; *) lr_bhost="" ;; esac + if [ -n "$lr_bhost" ]; then + lr_local=elsewhere + # THE RULE IS `binding_is_here`-s AND NOT A SECOND COPY OF IT (Copilot + # round 2 on openRepoTools#83 read the two and found them already + # diverging). The `_lc` form is the same function with the two `lc` forks + # taken off the front, because the awk above has lower-cased these values + # already and this is asked of every lane in the listing. + binding_is_here_lc "$lr_bhost" "$lr_bcont" "$lr_blegacy" && lr_local=here + fi + # COLUMNS 14 TO 17 ARE AMENDMENT 19-S, AND THEY GO AFTER AMENDMENT 18(b)-S + # 13 for the reason `swapped_lanes` gives its sixth and seventh: the first + # field before the first tab is the contract every reader of this output + # takes, and each of the others is read by its own index. 14 is the CLASS — + # `closed`, `dormant` or `none` — so that the sweep and the listing + # partition the rows ONE way; 15 the row-s `started` cell, 16 its state + # cell-s head and 17 the flag words found in the whole of that cell. + # + # AND NO COLUMN IS EMPTY, 13 INCLUDED, because three readers take this row + # with `IFS=<tab> read`, and a tab is IFS WHITESPACE: two in a row are ONE + # separator, so an empty 13 would hand 14 to the variable named for 13 and + # every field after it to the one before. A row with no standing binding + # says `none` there, which `lane_groups` files exactly as it filed empty — + # only `elsewhere` changes the group. + lr_out="${lr_out}${lr_utc:-0000}${US}${lr_l} ${lr_state} ${lr_w:-unknown} ${lr_pf:-none} ${lr_win:-none} ${lr_sid:-none} ${lr_d:-none} ${lr_obj:-none} ${lr_age} ${lr_restart} ${lr_home:-none} ${lr_fk} ${lr_local:-none} ${lr_class:-none} ${lr_start:-unknown} ${lr_was:-none} ${lr_flags:-none} +" + done <<EOF +$lr_names +EOF + [ -n "$lr_out" ] || return 8 + printf '%s' "$lr_out" | LC_ALL=C sort -t"$US" -k1,1r | awk -F"$US" 'NF >= 2 { print $2 }' +} + +# --------------------- AMENDMENT 18 ADDENDUM 1: THE PICK'S TWO READS --------- +# +# `lane` (Addendum 1 (i-1), ratified 2026-09-14T14:05:54Z verbatim "ratify the +# addendum") renders THE SAME ROWS `lanes` renders — in three groups, with a +# number in front of each. Neither the grouping nor the next free position is +# that word's own: both are computed HERE, over the rows `lanes_rows` printed, +# because two surfaces computing one answer is how they come to disagree. That +# is the rule clause (h) already gives `window-lane` and `session-lane`, and the +# one A11 Addendum 4 ruling 7 gave column 10 after `lanes` and `restart` had +# each computed a restart line of its own. +# +# ROWS ON STDIN, like `sibling-filter` one screen down: the caller has already +# made the read and paid for it, and a subcommand that read the register a +# second time would double the cost of every pick to answer a question about +# the rows already in its hand. Neither of these two reads the register, the +# logs, the session records or the network at all. + +# THE PARTITION, AND IT IS THE STATE COLUMN'S (clause (i-2)): +# +# available PARKED — a lane nobody holds — or A BINDING THIS HOST PROVES +# DEAD: a lane whose last verb was STARTED or RESUMED, on this +# workstation, with no live session record naming any of its ids. +# `lanes_rows` has already made that proof, and it is the whole +# difference between its `LIVE` and its `IDLE`. +# live LIVE: a live session record on this workstation names one of the +# row's ids. The act is the ATTACH and never a second process. +# elsewhere a binding this host CANNOT prove dead, because the row is +# another workstation's: the session records are local files, so +# saying NOT LIVE about Raven from Eagle would be a claim this +# machine has no way to make. Clause (c)'s handoff question. +# rowonly NOT A PICK: a STATE `lanes_rows` read out of the row's own +# 13(a) cell, `<WORD> (row)`, because the log has no lane-kind +# line to give one (#89). Shown by `lanes`, never numbered by +# `lane`, and refused by name — there is no log to resume from. +# +# CLOSED AND DORMANT LANES LEAVE THE PICK (Amendment 19). A lane whose last act +# was its last is not a lane a person picks, and a pick that offered one would +# be offering to reopen something closed on purpose. `ENDED` and `RETIRED` are +# that set in today's vocabulary and `CLOSED`/`DORMANT` are the words the rows +# take under #42; both are named here, so the pick is right under either and +# the word does not have to move when the read does. They are still ROWS in +# `lanes`, which is the READ — this is a pick. +lane_groups() { # <workstation> ; rows on stdin + awk -F'\t' -v me="$(short_ws "${1:-$WS}")" ' + NF >= 3 { + st = $2 + # THE CLASS FIRST, AND THAT IS AMENDMENT 19 ARRIVING IN COLUMN 14 — 13 is + # Amendment 18(b)-s, which landed first (Copilot round 2 on #93). A DORMANT row-s STATE is `NO LOG`, which is in no list + # below, so the state test alone let one through wherever the rows come + # from a read that does not hide them — `lanes --closed`, and `lane + # <name>`-s own `--lane` read, which is never filtered because its caller + # named the lane. The class is the read-s answer to exactly this question. + cls = (NF >= 14 ? $14 : "") + if (cls == "closed" || cls == "dormant") next + if (st == "ENDED" || st == "RETIRED" || st == "CLOSED" || st == "DORMANT") next + # A STATE READ OUT OF THE ROW-S OWN CELL IS SHOWN AND NEVER PICKED (#89). + # `lanes_rows` prints `<WORD> (row)` for a row whose log has no lane-kind + # line and whose cell is Amendment 13(a)-s phrase, and such a row records + # no directory, no profile and no binding: there is no log to resume it + # from. It is in none of the three groups, so the pick never numbers it, + # and `rowonly` is the group `lane <name>` refuses by name. Asked BEFORE + # the workstation, because a row with no log on this workstation was + # filed AVAILABLE on that column alone. + if (st ~ / \(row\)$/) { print "rowonly" "\t" $0; next } + w = tolower($3); sub(/\..*$/, "", w) + # COLUMN 13 IS THE READ-S OWN ANSWER to *"may this place pronounce on that + # binding"* (Amendment 18(b)), and an `IDLE` row is exactly the row that + # needs it: IDLE means THIS host saw no live record for the lane-s ids, + # and across a container seam that is the lane that IS running — two + # benches on one host share the profile directory, so the pid the record + # names is in the other one-s namespace. Filed on the workstation column + # alone, such a row was offered as AVAILABLE and the launch made a second + # process on a live lane (Copilot round 1 on openRepoTools#83). + # + # AN EMPTY OR `none` COLUMN 13 IS A ROW WITH NO BINDING LINE AT ALL — a lane + # with a row and no log, or a `lanes-edit.sh` predating this column (the + # read says `none` since Amendment 19 put columns after it) — and it is + # filed exactly as it was before the column existed, which is Amendment + # 7(i)-s cutover rule for a field a reader may simply not have. + loc = (NF >= 13 ? $13 : "") + # AND IT IS ASKED BEFORE THE STATE, INCLUDING OF A `LIVE` ROW (Copilot + # round 2 on openRepoTools#83). `LIVE` is a live session record HERE + # naming one of the row-s ids — and a record written in another container + # is readable here while the pid it names is in another namespace, so a + # `kill -0` that answers is answering about some other process. Clause (b) + # gives that binding to the place it is in: from here it is UNKNOWN, the + # act is clause (c)-s request, and the attach stays available to a person + # because `lane`-s elsewhere branch names it wherever that window is live + # on this tmux server. Column 13 is `none` where no binding stands, so a + # PARKED lane of another container is untouched by this and is AVAILABLE, + # because parking IS the handoff. + if (loc == "elsewhere") g = "elsewhere" + else if (st == "LIVE") g = "live" + else if (st == "PAUSED") g = "available" + else if (w == me) g = "available" + else g = "elsewhere" + print g "\t" $0 + }' +} + +# THE NEXT FREE POSITION, over those same rows: clause (i-1)'s `f` answer, and +# the footer `lanes` has printed since Brett Heap's settlement of +# 2026-09-13T20:38:11Z. It is the LOWEST one NO ROW HOLDS and never the highest +# plus one, because handing out 12 while 3 has never been used grows a column +# nobody reads — and `lane-start` refuses a position that is taken, so this is a +# suggestion with a guard behind it and never an assertion. +# +# A POSITION A LANE HAS HELD IS RESERVED, ENDED AND RETIRED ROWS INCLUDED +# (Copilot round 7 on #45, `lanes-edit.sh:4839`, where this paragraph said +# positions "come back as lanes end" and the code has never done that). EVERY +# row on stdin is taken, whatever its state, and that is deliberate: a lane's +# identity is its name, its object log is `lanes/log/<lane>.md` and it is +# APPEND-ONLY, so a second lane at a retired position would write its life into +# the first one's file and every read of that log — who holds what, when it was +# claimed, which session paused it — would answer for two lanes at once. The +# register's row is the same story in one line. Positions are cheap; identities +# are not. +# +# A POSITION IS DIGITS WITH AN OPTIONAL TRAILING LETTER, which is +# `lane-start`'s own rule: `5a` and `5` are one position taken twice, because a +# lane may be re-cut and a re-cut position is not free, and it is the only +# reading under which `openxfactory-4-opendox-extraction` has no position at +# all. The comparison is case-insensitive on both sides, like every other lookup +# of a lane name in this file (Amendment 15). +# EVERY ROW OF THE REGISTER AND OF THE ARCHIVE, AS BARE NAMES — the rows the +# listing HIDES since Amendment 19(b), and the rows `archive-rows` has moved out +# of the register altogether under 19(d). Both are read out of THIS CHECKOUT-s +# files and neither is fetched: the rows on stdin already carry the published +# register (the caller has just rendered it), and this union can only move the +# position UP, which is the direction a position may safely move. `next-free` +# is exempt from the workspace guard, so no workspace at all is silence here. +# THE PUBLISHED ONES, WITH THIS CHECKOUT'S AS THE FALLBACK (Copilot round 1 on +# #93). Reading only the local files missed a row that is on `origin/<branch>` +# and not yet pulled here: hidden from the stdin rows by clause (b) and absent +# from this union, its position came back on offer — which is the one thing +# 19(b) exists to prevent. `register_text` and `archive_text` are the same two +# reads the listing makes, in R19's order. +# +# AND A SOURCE THAT EXISTS AND CANNOT BE READ IS A REFUSAL, not an empty set: a +# position is handed out ONCE, and a read that failed is never an answer +# (Amendment 7(d)). +lane_position_rows() { # 0 with the names · 1 where a source exists and could not be read + [ -n "${LANES_FILE:-}" ] || return 0 + # THE PUBLISHED REGISTER FIRST AND THE WORKING TREE SECOND — `register_text`'s + # own rule, asked for rather than restated (Copilot round 3 on #93). Gated on + # the working-tree FILE existing, this read skipped the published register + # entirely on a checkout that has none, and `next-free` then counted only the + # stdin rows and the archive. + # + # AND AN EMPTY ANSWER WHERE A SOURCE EXISTS IS A READ THAT FAILED (round 2): + # `register_text` ends in a `printf` and answers 0 whatever its `git show` or + # its `cat` did, so the status says nothing; what cannot happen is a source + # with bytes in it rendering as nothing. + # AND ANY PATH THERE IS A SOURCE (#138 item 5). Under `[ -s ]` a zero-byte + # register — what a rewrite that failed leaves — and a broken symlink were + # skipped where origin has no register, and `next-free` counted the stdin + # rows and the archive alone. Counted as a source, either renders empty, and + # the check below refuses it. + if [ -f "$LANES_FILE" ] && [ ! -r "$LANES_FILE" ]; then return 1; fi + lpr_have=0 + if [ -e "$LANES_FILE" ] || [ -L "$LANES_FILE" ]; then lpr_have=1; fi + # AND THE PUBLISHED ONE IS THE TREE'S ANSWER, with `register_text`'s 1 kept + # (#138 item 18, the review of #230): a published register whose blob git + # cannot read is a source that failed, not one that is absent. + lpr_prc=0; register_published || lpr_prc=$? + case "$lpr_prc" in + 0) lpr_have=1 ;; + 8) : ;; + *) return 1 ;; + esac + lpr_reg="" + if [ "$lpr_have" = 1 ]; then + lpr_reg="$(register_text_checked 2>/dev/null)" || return 1 + [ -n "$lpr_reg" ] || return 1 + fi + lpr_arc="" + lpr_arc="$(archive_text 2>/dev/null)" || return 1 + printf '%s\n%s\n' "$lpr_reg" "$lpr_arc" | awk ' + substr($0,1,1) == "|" { + p1 = index($0, "`"); if (p1 == 0) next + r = substr($0, p1 + 1); p2 = index(r, "`"); if (p2 == 0) next + print substr(r, 1, p2 - 1) + }' 2>/dev/null || return 1 + return 0 +} + +lane_next_free() { # <repo> ; rows on stdin + [ -n "${1-}" ] || return 64 + lnf_more="" + if ! lnf_more="$(lane_position_rows)"; then + note "the register or the archive of retired rows exists and could not be read, so the rows this position must avoid are not all known. A position is handed out ONCE and a read that failed is not an answer (Amendment 7(d)), so none is offered." + return 1 + fi + { cat; printf '%s\n' "$lnf_more"; } | awk -F'\t' -v r="$1" ' + BEGIN { rl = tolower(r) } + $1 != "" { + # THE WHOLE NAME BEFORE THE POSITION IS COMPARED, NOT A PREFIX (Copilot + # round 7 on #45, `lanes-edit.sh:4853`). `substr(l, 1, length(rl))` reads + # `repo-foo-1` as a lane of `repo`, so a repository whose name is another + # name plus a hyphen took positions out of its neighbour: `next-free repo` + # would skip 1 because `repo-foo-1` exists, and hand out a number for a + # reason nobody could see in the listing. `head` is everything before the + # LAST hyphen and has to equal the repository exactly. + p = $1; sub(/^.*-/, "", p) + head = $1; sub(/-[^-]*$/, "", head) + if (head == $1) next + if (tolower(head) != rl) next + sub(/[A-Za-z]$/, "", p) + if (p !~ /^[0-9]+$/) next + taken[p + 0] = 1 + } + END { i = 1; while (i in taken) i++; print i }' +} + +# swapped_lanes [<workstation>] — one row per swapped lane, tab-separated: +# <lane> <UTC> <window> <dir> <profile> <agent> <transcript> +# +# THE FIRST FIELD IS THE REGISTER ROW'S SPELLING OF THE LANE (Amendment 15), the +# way `window-lane`'s answer is. The record is read under the lane's LOG FILE +# name, and a log written before Amendment 15 is still `lanes/log/<lower>.md` +# beside a row that spells the lane in mixed case (`lanes/log/openxfactory-4.md` +# and `openXfactory-4`), so the raw name is the wrong one to print. A caller of +# this output hands that field to `tmux rename-window`, to `--name`, to +# `lane <name>` and to a read of the register, and each of them wants the row's +# spelling. The log's own spelling is kept for the two things that read the LOG +# — its path and the pickaxe key — and is never printed. +# +# THE LAST TWO ARE AMENDMENT 17(b)'s, and they are added at the END for the +# reason the fourth and fifth were: the FIRST FIELD BEFORE THE FIRST TAB is the +# contract every reader of this output takes (the launcher, the `handoff` +# skill's step 1, `lane-start`'s directory rung 2 and `restart`'s, each with the +# same comment saying so), and each of the others is read by its own index. A +# record written before an amendment carries its fields EMPTY rather than +# guessed — Amendment 7(i)'s cutover rule, which is what makes a sixth and a +# seventh safe to add at all. +# +# WHICH LINE IS A LANE'S "LAST" IS FILE ORDER (R14), like every other state read +# here: a lane's log is append-only and single-writer, so a line further down +# the file is a line written later whatever the two UTC fields say — and this is +# the read a restart resolves its lane from, so letting a clock decide it would +# be the same fault Amendment 7 removed everywhere else. +# +# THE ROWS ARE ORDERED BY LANDING ORDER ON `origin/<branch>`, MOST RECENTLY +# LANDED FIRST — the position of the commit that ADDED each lane's PAUSED line, +# and never the UTC in it. File order does not reach across two lanes' files, +# and two lanes' UTCs are two clocks: they may be two workstations' (Amendment 7 +# gives them no shared order at all) or one workstation's mid-jump — this one +# was observed stepping ±25 s in bursts, and a log commit landed whose content +# carried a UTC 26 s after its own committer date. Git's push serialization is +# the one order both lanes really share, and it is the same arbiter clause (f) +# already uses to decide a race. The UTC stays in the output as INFORMATION, and +# decides nothing. +# +# The rank is the DAG distance from the tip (`rev-list --count <sha>..origin`), +# not a committer date, so it is history order and not a clock either. Swapped +# lanes are few — one per window a swap paused — so one pickaxe per candidate is +# the cheap read. A candidate whose adding commit cannot be found (no remote ref +# here, or the harness's LANES_NO_GIT=1) ranks last, and those fall back to UTC +# order among themselves: an order that is merely unhelpful, never wrong. +swapped_candidates() { + sw_want="$(short_ws "${1:-$WS}")" + state_events | awk -v sep="$US" -v want="$sw_want" ' + function pos(pf, pn) { return pf "\034" sprintf("%09d", pn) } + BEGIN { FS = sep } + $6 !~ /^lane:/ { next } + # AMENDMENT 13(b) — AND THE TWO NARRATIVE VERBS ARE NOT LANE-KIND STATE. + # AMENDMENT 16 ADDS THE THIRD, and it is the one reader that has to be told + # (Copilot round 6 on openRepoTools#81). `RENAMED` joined `is_note_verb` — + # lane-kind, and not a transition — but this awk names the verbs it skips + # rather than asking the predicate, so a lane whose LAST line was its rename + # stopped reading as PAUSED: `swapped` would not list it and `restart` would + # not find the lane it is meant to bring back. + # This read takes a lane-s LAST lane-kind line whatever its verb is and then + # asks whether it is a `PAUSED` carrying a swap payload; it is the ONE state + # reader in this file that does not name the five verbs it wants. `NOTED` + # and `RULED` are written into exactly the same lines and change nothing + # about where a lane is, so a lane that noted anything after its swap would + # have vanished from `swapped` — and `restart` reads `swapped` to find the + # lane whose window name a new tmux session has lost. Skipped by name, here + # and nowhere else, because every other reader already takes a whitelist. + $3 == "NOTED" || $3 == "RULED" || $3 == "RENAMED" { next } + # AMENDMENT 15 — LOWER-CASED KEY, ORIGINAL SPELLING BESIDE IT. Which line is + # a lane-s LAST is what decides whether that lane is SWAPPED at all, and + # keyed on the raw `$2` a `PAUSED … swap;` under one spelling followed by a + # `RESUMED` under the other left the PAUSED alive as a candidate: `restart` + # would relaunch a lane that is not paused, and `window-lane` would bind a + # window ref the lane has since left (Copilot round 1 on openRepoTools#41). + { k = tolower($2); p = pos($10, $11) + if (!(k in mp) || p >= mp[k]) { + mp[k] = p; verb[k] = $3; utc[k] = $1; pay[k] = $8; uuid[k] = $4; ws[k] = $5; obj[k] = $6; nm[k] = $2 } } + END { + for (l in mp) { + if (verb[l] != "PAUSED") continue + if (substr(pay[l], 1, 5) != "swap;") continue + w = ""; wst = ""; d = ""; pf = ""; ag = ""; tr = "" + n = split(pay[l], sf, "; ") + for (i = 1; i <= n; i++) { + if (substr(sf[i], 1, 7) == "window ") w = substr(sf[i], 8) + if (substr(sf[i], 1, 12) == "workstation ") wst = substr(sf[i], 13) + # AMENDMENT 11 clause (c): two sub-fields added to the three + # A8(b):202 gives this line. + # A `dir` whose path carries a space is written QUOTED, so the quotes + # are stripped here — one unquoter, in the one parser of this line. + if (substr(sf[i], 1, 4) == "dir ") d = substr(sf[i], 5) + if (substr(sf[i], 1, 8) == "profile ") pf = substr(sf[i], 9) + # AMENDMENT 17(b): two more, and a record written before that + # amendment carries neither — which is EMPTY here, never a guess + # (the cutover rule of Amendment 7(i); no apostrophe in this comment, + # because this awk program is single-quoted in the shell). + if (substr(sf[i], 1, 6) == "agent ") ag = substr(sf[i], 7) + if (substr(sf[i], 1, 11) == "transcript ") tr = substr(sf[i], 12) + } + sub(/[ \t]+$/, "", w); sub(/[ \t]+$/, "", wst); sub(/\..*$/, "", wst) + sub(/^[ \t]+/, "", d); sub(/[ \t]+$/, "", d) + sub(/^[ \t]+/, "", pf); sub(/[ \t]+$/, "", pf) + sub(/^[ \t]+/, "", ag); sub(/[ \t]+$/, "", ag) + sub(/^[ \t]+/, "", tr); sub(/[ \t]+$/, "", tr) + if (substr(d, 1, 1) == "\"") { q = index(substr(d, 2), "\""); if (q > 0) d = substr(d, 2, q - 1) } + else { sub(/ .*$/, "", d) } + sub(/ .*$/, "", pf) + sub(/ .*$/, "", ag) + sub(/ .*$/, "", tr) + if (tolower(wst) != want) continue + # The LAST field is the PICKAXE KEY: the head of the line as it was + # written, up to and including its object, which is unique to it and + # which `git log -S` can find without a regex. + # `nm[l]` AND NEVER `l` (Amendment 15, `8345d2f`): the key is the lane + # folded to one case and `nm` is the lane as the event stream spells + # it, which is the base name of the lane LOG FILE (Amendment 16(c) keys + # every line to its file). That is NOT the register row spelling + # wherever the file does not carry it: a log written before Amendment 15 + # is still `lanes/log/openxfactory-4.md` beside the row `openXfactory-4`. + # It stays the spelling of the log itself, for the pickaxe key below and for + # `log_path_for`; the row spelling is for `swapped_lanes` to print as + # the first field, and `window-lane` canonicalises its answer the same + # way. (No apostrophe in this comment: this awk program is single-quoted.) + printf "%s%c%s%c%s%c%s%c%s%c%s%c%s%c%s — lane %s, session %s@%s, %s, %s\n", + nm[l], 31, utc[l], 31, (w == "" ? "unknown" : w), 31, + (d == "" ? "" : d), 31, (pf == "" ? "" : pf), 31, + (ag == "" ? "" : ag), 31, (tr == "" ? "" : tr), 31, + verb[l], nm[l], uuid[l], ws[l], utc[l], obj[l] + } + }' +} + +swapped_lanes() { + sw_rows="$(swapped_candidates "${1:-$WS}")" + [ -n "$sw_rows" ] || return 0 + while IFS="$US" read -r sw_l sw_u sw_w sw_d sw_p sw_a sw_t sw_key; do + [ -n "${sw_l:-}" ] || continue + # THE ROW'S SPELLING FOR THE FIRST FIELD, THE LOG'S FOR THE LOG (see above). + # `canon_lane` refuses a register holding the 15(d) pair and a table of + # former names it cannot read; this read keeps the log's own spelling then, + # for `window-lane`'s reason: it is informational and its contract is rows + # or 8, and the refusal belongs to the writer the lane leads to. + sw_can="$(canon_lane "$sw_l" 2>/dev/null || :)" + sw_rank=999999999 + if have_remote_ref; then + sw_sha="$(git -C "$LANES_REPO" log -1 --format=%H -S"$sw_key" "origin/$LANES_BRANCH" -- "$(log_path_for "$sw_l")" 2>/dev/null || :)" + if [ -n "$sw_sha" ]; then + sw_c="$(git -C "$LANES_REPO" rev-list --count "$sw_sha..origin/$LANES_BRANCH" 2>/dev/null || :)" + case "$sw_c" in ''|*[!0-9]*) : ;; *) sw_rank="$sw_c" ;; esac + fi + fi + printf '%09d%s%s%s%s%s%s%s%s%s%s%s%s%s%s\n' "$sw_rank" "$US" "${sw_can:-$sw_l}" "$US" "$sw_u" "$US" "$sw_w" \ + "$US" "${sw_d:-}" "$US" "${sw_p:-}" "$US" "${sw_a:-}" "$US" "${sw_t:-}" + done <<EOF +$sw_rows +EOF +} + +# The lane's open objects on ONE line, for the hook's block. `who --lane` prints +# a line per object and a heading; a hook has one line's worth of a reader's +# attention, and the objects are what the next act needs to know. +lane_open_summary() { + los_l="$1"; los_out="" + if ! lane_log_exists "$los_l"; then + printf 'no log for %s (pre-cutover lane) — see its row'"'"'s state cell\n' "$los_l" + return 0 + fi + while IFS="$US" read -r lo_utc lo_verb lo_obj lo_ref lo_sup; do + [ -n "${lo_verb:-}" ] || continue + is_open_verb "$lo_verb" || continue + los_out="${los_out}${los_out:+; }$lo_verb $lo_obj${lo_sup:+ (taken over by lane:${lo_sup%@*})}" + done <<EOF +$(lane_objects "$los_l" 2>/dev/null || :) +EOF + printf '%s\n' "${los_out:-none open}" +} + +# HOW OLD THE ANSWER IS (Amendment 8, R-A8-1). The hook never fetches, so every +# line of its block is the checkout as it last stood. `.git/FETCH_HEAD` is +# rewritten by every fetch and by nothing else, so its mtime is when this +# checkout last heard from `origin` — and a block that says "4d ago" is a block +# a reader knows not to trust about another workstation's lane. Never a network +# call and never a failure: an unreadable one answers `unknown`. +fetch_age() { + fa_dir="$(git -C "$LANES_REPO" rev-parse --git-dir 2>/dev/null || :)" + [ -n "$fa_dir" ] || { printf 'unknown\n'; return 0; } + case "$fa_dir" in /*) : ;; *) fa_dir="$LANES_REPO/$fa_dir" ;; esac + [ -f "$fa_dir/FETCH_HEAD" ] || { printf 'never\n'; return 0; } + fa_t="$(stat -c %Y -- "$fa_dir/FETCH_HEAD" 2>/dev/null || stat -f %m -- "$fa_dir/FETCH_HEAD" 2>/dev/null || :)" + case "$fa_t" in ''|*[!0-9]*) printf 'unknown\n'; return 0 ;; esac + fa_s=$(( $(date -u +%s) - fa_t )) + [ "$fa_s" -lt 0 ] && fa_s=0 + if [ "$fa_s" -lt 90 ]; then printf '%ss ago\n' "$fa_s" + elif [ "$fa_s" -lt 5400 ]; then printf '%sm ago\n' "$((fa_s / 60))" + elif [ "$fa_s" -lt 172800 ]; then printf '%sh ago\n' "$((fa_s / 3600))" + else printf '%sd ago\n' "$((fa_s / 86400))" + fi +} + +# The last line of every block the hook prints, whichever branch wrote the rest, +# in the words clause (e) gives it: "every block ends with the line +# `as of <n>m ago (no fetch)`". It is the whole of what makes an unfetched read +# honest — a reader sees how stale the answer is instead of trusting a freshness +# nobody verified. +ssb_tail() { + printf 'as of %s (no fetch)\n' "$(fetch_age)" + return 0 +} + +# `lane-start`'s arguments FOR THIS LANE, filled in (Amendment 8, R-A8-7). The +# block used to print the literal `<repo> <n>` with the lane in hand, so every +# reader translated `openRepoProject-1` into `openRepoProject 1` by hand, on +# every mismatch, for ever. A lane is `<repo>-<position across>` (THE LANE +# RULE), so the split is on the LAST `-` — and ONLY when what follows it is a +# number: a lane named before that rule (`browser-ui-repair`) is started through +# `--dir`, and splitting it would print `browser-ui repair`, which is a command +# that does the wrong thing rather than one that does nothing. +lane_start_args() { + lsa_l="${1-}"; lsa_n="${lsa_l##*-}" + case "$lsa_l" in *-*) : ;; *) printf -- '--dir <path> %s\n' "$lsa_l"; return 0 ;; esac + case "$lsa_n" in ''|*[!0-9]*) printf -- '--dir <path> %s\n' "$lsa_l"; return 0 ;; esac + printf '%s %s\n' "${lsa_l%-*}" "$lsa_n" +} + +# Has Rule 3's stamp for THIS session already been written? (Amendment 8, +# R-A8-7: the block told every resume to "stamp the handoff RESUMED" when +# `lane-start` had just written it — one manufactured decision per resume.) A +# local file read and nothing else: the row's handoff cell, resolved the way the +# row spells it, grepped for this session's own line. It is ASKED rather than +# assumed from the ids matching, because a window started by a bare `claude` +# rather than by `lane-start` has no stamp and does still owe one. +handoff_stamped_by() { # <handoff cell> <session id> + hsb_cell="${1-}"; hsb_id="${2-}"; hsb_f="" + [ -n "$hsb_cell" ] && [ -n "$hsb_id" ] || return 1 + case "$hsb_cell" in + '~/'*) hsb_f="$HOME/${hsb_cell#'~/'}" ;; + /*) hsb_f="$hsb_cell" ;; + *) [ -n "${LANES_REPO:-}" ] && hsb_f="$LANES_REPO/$hsb_cell" ;; + esac + [ -n "$hsb_f" ] && [ -r "$hsb_f" ] || return 1 + grep -qF -e "RESUMED by $hsb_id" -- "$hsb_f" 2>/dev/null +} + +# DOES THE ROW'S NEWEST STAMP NAME A UUID, OR `unknown`? (Amendment 8(e), "the +# first cure carries one condition".) A real `lane-start` is the wrong-lineage +# remedy BECAUSE the cell's last id names a transcript the lane's directory has. +# Where the last launch took clause (d)'s title fallback, that id names a +# transcript this directory does not have — which is why the fallback was +# reached — and the row says so in its own words: the stamp that run wrote +# carries the literal `unknown`. A relaunch would take the same fallback again, +# so the cure there is the recording act instead. +# +# The row is read, never the directory: the hook is handed no lane checkout and +# the working directory confers no lane. `0` when the newest stamp says +# `unknown`, `1` otherwise — including a row with no stamp at all, where a +# relaunch is the ordinary remedy. +row_stamp_is_unknown() { # <lane> + rsu_lane="${1-}"; rsu_n=""; rsu_row=""; rsu_last="" + [ -n "$rsu_lane" ] || return 1 + rsu_n="$(row_line "$rsu_lane" 2>/dev/null)" || return 1 + case "$rsu_n" in ''|*[!0-9]*) return 1 ;; esac + rsu_row="$(sed -n -e "${rsu_n}p" "$LANES_FILE" 2>/dev/null || :)" + [ -n "$rsu_row" ] || return 1 + rsu_last="$(printf '%s' "$rsu_row" | grep -o '[A-Z][A-Z]* by [^ |]*' | tail -n1 || :)" + case "$rsu_last" in *" by unknown") return 0 ;; esac + return 1 +} + +# session_start_block <hook json> <tmux window name> — the whole of what the +# SessionStart hook prints. It NEVER writes and its caller ALWAYS exits 0. +# +# `source` is one of startup, resume, clear, compact, fork. A COMPACT prints +# NOTHING: the same conversation carries on in the same window under the same +# id, and a block there would announce a lane's identity into the middle of a +# session that already has it. Everything else — a fork included, which is a new +# attachment to the lane's conversation — gets the block, and an unknown or +# missing source is treated as a startup rather than dropped. +# +# `cwd` is in the payload and is deliberately NOT read as a lane: THE WORKING +# DIRECTORY CONFERS NO LANE (Amendment 6(a)) — two lanes share one all day, and +# every nested checkout in the xFactory estate shares its parent's. The WINDOW +# and the REGISTER decide, in that order. +session_start_block() { + ssb_json="${1-}"; ssb_win="${2-}" + ssb_id="$(lc "$(jstr "$ssb_json" session_id)")" + ssb_src="$(jstr "$ssb_json" source)" + case "$ssb_src" in compact) return 0 ;; esac + + # AMENDMENT 15 — THE WINDOW NAME, THE SESSION NAME AND THE ROW KEY ARE + # COMPARED CASE-INSENSITIVELY, AND EVERY LINE BELOW PRINTS THE ROW'S OWN + # SPELLING. Both reads already answer with the register's spelling — + # `lane_named_ci` lowercases both sides by name, and `lane_of_session` prints + # the row's token — so `$ssb_lane` is canonical from here down, which is what + # makes `lane_start_args` below hand a reader the commands filled in with the + # spelling their window and their session are about to be named. + # AMENDMENT 12'S GUARD AND LOCK PLUG IN HERE, and since #25 they ARE built — + # `ssb_name_line` immediately below is clause (f), and the lock it types is + # the same `guard_type` the `UserPromptSubmit` guard uses. A session whose + # name differs from `$ssb_lane` only by case is renamed to the ROW's spelling + # like any other drift, which is what makes this line and Amendment 15 one + # rule rather than two. + ssb_lane=""; ssb_alias_unread="" + if [ -n "$ssb_win" ]; then + # AMENDMENT 16(e) — AND A TABLE THIS READ COULD NOT OPEN IS SAID, NOT + # SWALLOWED (Copilot round 3 on openRepoTools#81). This hook never refuses, + # so an unreadable `lanes/aliases.tsv` cannot stop the block — but printing + # "no lane bound to this window" about a window whose name might be a + # FORMER one is the block orienting a session wrongly, which is the one + # thing it exists not to do. It says so instead, and the line below it is + # then read as what it is. + ssb_rc=0 + ssb_lane="$(lane_named_ci "$ssb_win" 2>/dev/null)" || ssb_rc=$? + [ "$ssb_rc" = 5 ] && { ssb_lane=""; ssb_alias_unread=1; } + fi + [ -n "$ssb_lane" ] || [ -z "$ssb_id" ] || ssb_lane="$(lane_of_session "$ssb_id" 2>/dev/null || :)" + [ -n "$ssb_alias_unread" ] && [ -z "$ssb_lane" ] && \ + printf 'WARNING: %s could not be read, so a window named for a lane RENAMED since could not be resolved to it (Amendment 16(e)) — this block may be about to say no lane binds a window that one does\n' "${LANES_ALIASES_PATH:-lanes/aliases.tsv}" + # AMENDMENT 12 CLAUSE (f) AND AMENDMENT 18(h)'s READ — the name line and the + # duplicate line, printed HERE rather than inside each of the three branches + # below, because both are facts about this session and not about which of them + # applies. `|| :` for the reason the whole block has one: this hook never + # fails and always exits 0 (R-A8-1). + # THE SUBSHELL IS THE `|| :` MADE TRUE OF MORE THAN A RETURN — see + # `ssb_name_line`'s own header. It is the one line of this block that reads + # every profile's session records, so it is the one most able to meet + # something this hook may not die on. + ( ssb_name_line "$ssb_id" "$ssb_lane" ) || : + if [ -z "$ssb_lane" ]; then + # THE ONE PLACE THE PLACEHOLDER IS RIGHT: no lane is known here, so there is + # nothing to fill in. It is also the estate's ONE no-lane notice — the + # launcher prints its own on stderr before the launch, and Amendment 8's + # resume-choice table says one of the two goes; this is the one the session + # itself can read. + # THE ONE BRANCH THAT KEEPS ITS PLACEHOLDERS — no lane is known here, so + # there is nothing to fill in. Except where the WINDOW NAME itself parses as + # `<repo>-<n>`: the register has no such row, but the operator's own two + # arguments are right there in the name, and printing them beats printing a + # blank for them to fill. It is also the estate's ONE no-lane notice — + # clause (c) step 4 stands down wherever this hook can speak. + if [ -n "$ssb_win" ] && [ "$(lane_start_args "$ssb_win")" != "--dir <path> $ssb_win" ]; then + printf 'no lane bound to this window — run: lane-start %s\n' "$(lane_start_args "$ssb_win")" + else + printf 'no lane bound to this window — run: lane-start <repo> <n>\n' + fi + ssb_tail + return 0 + fi + + ssb_args="$(lane_start_args "$ssb_lane")" + ssb_cur="$(last_session_id_of_lane "$ssb_lane" 2>/dev/null || :)" + if [ -n "$ssb_id" ] && [ -n "$ssb_cur" ] && [ "$ssb_id" != "$ssb_cur" ]; then + # THE BRANCH IS THE ID'S POSITION IN THE SESSION CELL, NOT ITS PRESENCE. + # The cell is a history written oldest first and the LAST id is the lane + # (Amendment 6(b)), so there are exactly three places an id can be, and + # each is cured by a different act: + # + # * the cell's LAST id — this session IS the lane. Handled below. + # * IN the cell but not last — a SUPERSEDED transcript of this lane. That + # is the 2026-09-11 wrong-lineage resume, caught at the first instant it + # can be caught, and the cure is a real `lane-start`, which resumes the + # id the row ends on. The conversation in this window is not the lane's, + # so the session is exited rather than carried on with. + # * in NO cell — the harness minted a new transcript with nobody acting (a + # /clear, a usage reset, a profile switch), or an operator's title- + # fallback pick landed on a transcript no row carries. The lane is right + # and the row is simply behind, so the cure is the recording act and no + # relaunch: `lane-start --no-launch`, which reads the live record in + # this window and appends that uuid to the cell. + # + # THE TWO CURES ARE NOT INTERCHANGEABLE. A reader who runs `--no-launch` on + # a superseded transcript records the WRONG conversation as the lane's, in + # the cell the next restart resumes from — the failure this block exists to + # catch, performed by its own remedy. + # + # AND NO CURE SENDS A READER BACK THROUGH THE PICKER (clause (f)): where the + # row's newest stamp says `unknown`, the cell's last id names a transcript + # the lane's directory does not have, a relaunch would take the same title + # fallback again, and the recording act is the cure there too. No branch + # names `/resume` or the picker, because neither is a lane surface. + # + # EVERY COMMAND IS PRINTED FILLED IN (F-B6): the hook holds the lane, and a + # reader trying to get back to work should not have to translate + # `openRepoProject-1` into `openRepoProject 1` by hand at that moment. + if printf '%s\n' "$(session_ids_of_lane "$ssb_lane" 2>/dev/null || :)" | grep -qx -F -- "$ssb_id"; then + if row_stamp_is_unknown "$ssb_lane"; then + printf 'WARNING: this is a superseded transcript of lane %s; the live one is %s, which the row records as `unknown` — a relaunch would record nothing either, so run: lane-start --no-launch %s\n' \ + "$ssb_lane" "$ssb_cur" "$ssb_args" + else + printf 'WARNING: this is a superseded transcript of lane %s; the live one is %s; you resumed %s — exit this session and run: lane-start %s\n' \ + "$ssb_lane" "$ssb_cur" "$ssb_id" "$ssb_args" + fi + else + printf 'WARNING: this window is lane %s whose current session is %s; this session %s is in no row — the harness minted a new transcript — run: lane-start --no-launch %s\n' \ + "$ssb_lane" "$ssb_cur" "$ssb_id" "$ssb_args" + fi + ssb_tail + return 0 + fi + + ssb_ho="$(handoff_of_lane "$ssb_lane" 2>/dev/null || :)" + # AMENDMENT 11 CLAUSE (h) — THE BOUND LINE GAINS THE WINDOW, and gains + # nothing else: `session-start` keeps all three of its safety properties, it + # never writes, it never touches the network and it always exits 0 (R-A8-1), + # and this is a field the block has already read out of the lane's own log. + # It is here because the window is what clause (b)'s precedence 3 and clause + # (f)'s step 2(c) bind from, and a reader who cannot see what the record says + # the window is cannot tell a lane that will bind with no question from one + # that will not. + ssb_win="$(lane_payload_field "$ssb_lane" window all 2>/dev/null || :)" + printf 'LANE %s — handoff %s — row session %s%s\n' \ + "$ssb_lane" "${ssb_ho:-none recorded}" "${ssb_cur:-none recorded}" \ + "${ssb_win:+ — window $ssb_win}" + # DECISION 8(e) — A LIVE FORK OF THIS LANE'S TRANSCRIPT IS SHOWN AS A DEFECT + # TO RETIRE. Evidence 6: an abandoned launch left a `--fork-session` daemon + # orchestrating the same plan, relaunching writers on the same branches and + # writing this lane's log under an id no row carries, while telling the + # interactive session it was the holder. A session that starts into a lane + # somebody else's fork is still running needs to know before it acts, and the + # retirement is a person's act (Amendment 8(f)), so the line NAMES and does + # nothing. + ssb_fk=""; ssb_fkrc=0 + ssb_fk="$(lane_forks "$ssb_lane" 2>/dev/null)" || ssb_fkrc=$? + # AND THE SAME HERE, for the same reason: this block is the first thing a + # session that starts into a lane reads, and "no fork" is a fact it acts on. + case "$ssb_fkrc" in + 0 | 8) : ;; + *) printf 'UNKNOWN: this workstation'"'"'s session records could not be read, so whether a live FORK of this lane'"'"'s transcript is running is NOT established — which is not the same as none. See: lanes-edit.sh forks %s\n' "$ssb_lane" ;; + esac + if [ -n "$ssb_fk" ]; then + while IFS='\t' read -r ssb_fid ssb_fpid ssb_fkind ssb_fcwd; do + [ -n "${ssb_fid:-}" ] || continue + printf 'DEFECT: %s is a live FORK of this lane'"'"'s transcript (pid %s, %s, cwd %s) — it is not the holder and must not write the register. Retire it: lane-end %s --retire %s\n' \ + "$ssb_fid" "$ssb_fpid" "${ssb_fkind:-interactive}" "${ssb_fcwd:-unknown}" "$ssb_lane" "$ssb_fpid" + done <<EOF +$ssb_fk +EOF + fi + # THE BLOCK STOPS ASKING FOR A STAMP `lane-start` HAS ALREADY WRITTEN (R-A8-7, + # resume-choice row 9: one manufactured decision per resume). It is DERIVED, + # not assumed from the ids matching — a window started by a bare `claude` + # rather than through the launcher has no stamp and does still owe one — so + # the handoff the ROW names is read and grepped for THIS session's own line. + # Where the row names no handoff at all the line says that instead. + if [ -z "$ssb_ho" ]; then + printf 'the row records no handoff path — there is none to stamp or to follow\n' + elif handoff_stamped_by "$ssb_ho" "$ssb_id"; then + printf 'handoff already stamped by lane-start — follow its top block\n' + else + printf 'stamp the handoff RESUMED (Rule 3) and follow its top block\n' + fi + printf 'open: %s\n' "$(lane_open_summary "$ssb_lane")" + ssb_tail + return 0 +} + +# ============================================================================ +# AMENDMENT 12 — THE NAME GUARD AND THE LOCK, WITH AMENDMENT 18(h)'S ONE READ +# ============================================================================ +# +# **A LANE SESSION WORKS ONLY WHILE THREE NAMES ARE ONE** — the tmux WINDOW it +# runs in, the SESSION's own name, and the register ROW whose session cell ends +# on this transcript — **and otherwise the prompt is REFUSED** (exit 2), with +# the triple as it stands and the ONE command that cures it, filled in. Ratified +# 2026-09-13T18:20:44Z, "Ratify revision 2", with M1 "Type /rename into the +# pane"; `brettheap/new-workstation#22`/#23, opensoft/openRepoTools#25. +# +# WHY THE RULE NEEDED AN ENFORCEMENT. Amendment 2 has said since 2026-09-05 that +# a lane is its window's name and its session's name; nothing refused anything +# for eight days, and between 2026-09-10 and 2026-09-12 this very lane ran as +# `openRepoTools-3`, `-4`, … `-14` — a fresh title per `/resume`, in a window +# still named `claude`, in profiles that changed at every usage reset — and no +# row was ever written. `session_start_block` above says which lane a window is +# and "ALWAYS exits 0"; `window_session` "decides nothing". This is the surface +# that decides. +# +# THE LOCK (clause (h), Brett Heap's D5). Under the projects root the session +# name is not the person's to set freely; it is the lane's. The tooling sets it +# at every launch (`lane-start --name "$LANE"`, clause (c)) and again whenever it +# drifts — by TYPING `/rename <lane>` into the session's own tmux pane, which is +# the only mechanism a running session has (M1, "Type /rename into the pane"): +# the docs name `--name` at launch, `/rename`, and `Ctrl+R` in the picker, and +# nothing else — no hook output field, no environment variable, no settings key. +# A PERSON'S rename to another lane's name is not drift but an INSTRUCTION, and +# it is OFFERED back before it is obeyed: yes moves this window to that lane, no +# renames the session back. +# +# FAIL CLOSED (clause (d)). A mismatch refuses; so does an INDETERMINATE read — +# session records unreadable, tmux not answering, the register unreadable — +# naming the read, because a triple that cannot be verified is not a triple that +# agrees. Profile-only launches carrying exactly `CLAUDE_NO_LANE=1` are exempt +# from this guard. `claude --safe-mode` disables every hook, deliberate and +# visible in the prompt box; a session started that way is not a lane session +# and may not write the register or claim an object. +# +# WHAT IT COSTS, AND THE ONE WAY IT FAILS OPEN. Measured on Eagle 2026-09-14 +# against 329 session records and a 1.3 MB register: the register read is ~2 s +# wall and the `grep -l` over every profile's records ~0.4 s, so a refusal lands +# inside the ratified `timeout 5`. A hook that EXCEEDS its timeout is killed, and +# a killed hook does not exit 2 — so the timeout is the one path on which this +# guard fails open. It is the amendment's own number and is left at it; the +# cheap tests are made first so that the two reads happen only where they decide +# something. +# +# IT NEVER FETCHES. `session-start`'s R-A8-1 argument applies here several times +# over — that hook runs once per session and this one runs at EVERY PROMPT — so +# the row is read from `origin/<branch>` AS THIS CHECKOUT LAST HAD IT (R19, the +# same `register_text` every other state read takes) and the network is never +# opened. "The register not fetchable" (clause (d)) is therefore the READ +# failing, and that refuses. + +# A LANE NAME IS `<repo>-<position>` (THE LANE RULE), and this is the predicate +# for it: `check_lane_name`'s character fence, plus a LAST `-` followed by +# digits. It agrees with `lane_start_args` by construction — that function +# prints `--dir <path> <lane>` for exactly the names this refuses — and the two +# exist separately because one answers a question and the other builds a command +# line. A name the register has a row for is a lane whatever its shape +# (`browser-ui-repair` is one); this asks only whether the two arguments of +# `lane-start` can be read OUT of a name nobody has a row for yet, which is what +# rows 1 and 6 of the table below need. +lane_shaped() { # <name> + lsh_n="${1-}" + case "$lsh_n" in ''|*[!A-Za-z0-9._-]*|.*|-*) return 1 ;; esac + case "$lsh_n" in *-*) : ;; *) return 1 ;; esac + lsh_pos="${lsh_n##*-}" + case "$lsh_pos" in ''|*[!0-9]*) return 1 ;; esac + return 0 +} + +# CLAUSE (e)'s SCOPE, AND IT IS ASKED OF BOTH SPELLINGS OF A PATH. The guard +# applies to every session whose `cwd` is under the projects root and is silent +# elsewhere (D1, "Projects root only"). On a launcher-configured workstation +# `~/projects` is a SYMLINK — every profile's is one link to +# `~/.claude-profiles/state/opensoft/projects` — and the harness reports a `cwd` +# that has already been resolved through it, so a literal prefix test answers +# "outside the projects root" about every estate session there is. Both the +# typed path and its `pwd -P` are compared, and a match on either is inside: +# the direction that errs toward the guard APPLYING is the safe one, because +# the other direction is the guard never firing at all. +under_projects_root() { # <cwd> <projects root> + upr_c="${1-}"; upr_r="${2-}" + [ -n "$upr_c" ] && [ -n "$upr_r" ] || return 1 + case "$upr_c/" in "$upr_r"/*) return 0 ;; esac + upr_cr="$(cd -- "$upr_c" 2>/dev/null && pwd -P)" || upr_cr="" + upr_rr="$(cd -- "$upr_r" 2>/dev/null && pwd -P)" || upr_rr="" + [ -n "$upr_cr" ] && [ -n "$upr_rr" ] || return 1 + case "$upr_cr/" in "$upr_rr"/*) return 0 ;; esac + return 1 +} + +# THE WINDOW A RECORD NAMES, UNDER AMENDMENT 11(h)'s AGREEMENT RULE. A record's +# `tmux` is `<session>:<@id>.<%pane>`, and tmux REUSES window ids once a window +# is gone — measured 2026-09-14, when a stale record's `@1` resolved to a window +# of another session. So the id alone is not the window: the id must resolve +# HERE and the session it resolves in must be the one the record wrote down. +# 0 the window exists and agrees +# 1 the id resolves nowhere here, or resolves in another tmux session — and +# the SERVER answered, so this is a refutation and not a silence +# 2 tmux did not answer at all: its server is down or unreachable from here, +# so the window is UNKNOWN, not gone (openRepoTools#73, item 1) +# 8 there is nothing to test — no target on the record, no `@id` in it, or no +# tmux to ask (a record with no window is not thereby a record nowhere) +# +# THE 2 NEEDS A SECOND QUESTION, AND IT IS ASKED ONLY WHERE THE FIRST CAME BACK +# EMPTY. `tmux_window_field` answers empty for a window this server refuted and +# for a server that never answered, and this function used to call both 1 — +# which `transcript_holders` writes as `(gone)`, and which `lane-end --retire` +# reads as "not the lane's own session". So with tmux installed and its server +# silent, `--retire <the lane's own pid>` was accepted and printed Amendment +# 6(d)'s retitle for the conversation that IS the lane (measured on f87fd5a: +# `/rename repoGD-1 · retired …`, exit 0). `tmux_server_answers` tells the two +# apart, and a window nobody could ask about keeps `(not asked)`'s posture: it +# protects the process in it. +record_window_state() { # <the record's tmux field> + rws_t="${1-}" + [ -n "$rws_t" ] && [ "$rws_t" != none ] || return 8 + rws_ref="${rws_t%.*}" + rws_id="${rws_ref##*:}" + rws_sess="${rws_ref%:*}" + case "$rws_id" in @*) : ;; *) return 8 ;; esac + command -v tmux >/dev/null 2>&1 || return 8 + rws_now="$(tmux_window_field "$rws_id" '#{session_name}' 2>/dev/null || :)" + if [ -z "$rws_now" ]; then + tmux_server_answers || return 2 + return 1 + fi + [ "$rws_now" = "$rws_sess" ] || return 1 + return 0 +} + +# DOES A TMUX SERVER ANSWER HERE AT ALL? Asked UNTARGETED, so it names no window +# and no window's absence can refute it: with no `-t`, tmux answers for the +# client this shell is in, or outside tmux for a session of its own choosing, +# and with no server it prints nothing and exits 1 (`no server running on …`). +# Measured on this estate 2026-10-13 against tmux 3.4 on a private socket: no +# server → empty, exit 1; a server up, asked from outside it → the session's +# name, exit 0; and a TARGETED read of an `@id` that server does not have → +# empty, exit 0 — the very answer a silent server also gives, which is why this +# is a separate question and not a status code read off the first one. +tmux_server_answers() { + command -v tmux >/dev/null 2>&1 || return 1 + [ -n "$(tmux display-message -p '#{session_name}' 2>/dev/null | head -n1)" ] +} + +# ------------------------------------- AMENDMENT 18(h): ONE LIVE PROCESS +# +# *"A transcript (one session id) is held by ONE live process. The harness can +# fork one (`--fork-session`, minting a new id in a background pty host) or +# resume one twice, and the tooling refuses to build on either."* Ratified +# 2026-09-14T13:15:18Z as revision 4 of Amendment 18; +# `brettheap/new-workstation#34`, opensoft/openRepoTools#39. +# +# MEASURED FOUR TIMES ON 2026-09-14, the fourth at 18:14Z: a `bg` record in ONE +# profile's `sessions/` and an interactive record in ANOTHER's, both live, both +# carrying one `sessionId` — which is why this sweeps EVERY profile's directory +# and not the asking session's. On a launcher-configured workstation every +# profile's `projects/` is one shared directory, so a transcript needs no move +# to be resumed under another profile and a duplicate is one `--resume` away. +# +# THREE CALLERS, ONE IMPLEMENTATION, for the reason clause (h) already gives +# `window-lane`: `lane-start` refuses to bind or resume an id another process +# holds, `lane-end --retire <pid>` retires that process, and the prompt guard +# refuses every prompt inside it. A rule implemented three times is a rule three +# surfaces come to disagree about. +# +# IT IS BUILT ON A `grep -l`, NOT ON `session_records`. This runs at every prompt +# under a five-second timeout, and the one-pass parse is a per-process CACHE that +# the first caller pays for in full — 329 records here. The question asked is +# about ONE id the harness has already handed the hook, so the cheap shape is the +# one `live_holder` uses: one grep for the id, then a parse of the one or two +# files that match. Measured at ~0.4 s against those 329. +# +# <pid><US><kind><US><tmux|none><US><profile><US><where><US><verdict><US><file> +# +# `where` is for a person to read — `window <session>:<@id>`, the same with +# ` (gone)` where the agreement rule above refuses it, ` (no answer)` where tmux +# did not answer at all and ` (not asked)` where there was nothing to ask — or +# `bg`. Only `(gone)` is a window this server REFUTED (openRepoTools#73). +# +# THE VERDICT IS THE WHOLE OF THE JUDGEMENT, and it has four values because +# THREE IN-FORCE RULES MEET HERE AND NONE OF THEM MAY BE OVERTURNED BY THIS ONE: +# +# here the record is THIS window's own process — its `tmux` names this +# window, or its pid is this pane's or below it: `record_is_here`'s +# TIERS 2 AND 3, and its tier 1 is left out because it cannot +# discriminate here. That tier asks whether the record's +# `sessionId` is `$CLAUDE_CODE_SESSION_ID`, and every candidate in +# this set carries the very id being tested — so on the asking +# session's own transcript it would answer `here` for the +# duplicate too, which is the one reading this function exists to +# prevent. +# companion not this window's, in the SAME profile's `sessions/` as this +# window's own record of this id, AND NOT A SESSION RECORD. +# AMENDMENT 8, RULING (g) names exactly one such thing: *"Beside +# the interactive process in the pane the harness runs a companion: +# `kind: bg`, no `tmux`, no `nameSource`, its own pid, and THE SAME +# `sessionId` … Records that share a `sessionId` are one session, +# not a queue of rival holders, and there is no contest between +# them to win."* The harness writes a session's own records under +# that session's own `$CLAUDE_CONFIG_DIR`, so same-profile is what +# "the harness's own second record of one session" looks like — +# and the `kind` is what tells that record apart from a SECOND +# INTERACTIVE PROCESS in the same directory, which is one +# transcript resumed twice and is 18(h)'s own case rather than the +# harness's companion. The profile alone read a second `--resume` +# UNDER ONE PROFILE as benign (Copilot round 1 on this PR), and +# that is the cheapest way there is to make two live processes on +# one transcript: no move, no swap, one command. +# THE KIND IS `bg` AND NOTHING ELSE IS READ AS ONE. `not a session +# record` was the first spelling of this test and it was too wide +# by exactly the kinds nobody has ruled on: this suite's own +# interactive fork carries `kind: user` +# (`tests/test_lane_helpers.sh`, Amendment 11 clause (k)), and any +# kind a later harness invents would have arrived here as the +# harness's benign companion (Copilot round 2 on this PR). Ruling +# (g) names ONE shape to pass over, so that shape is what this +# matches; every other live record on this id — known kind or not, +# and a record too old to carry a `kind` at all, which pass 1 +# writes down as `interactive` — is a duplicate, which is the +# closed direction. +# AND WHERE THIS WINDOW CARRIES NO RECORD OF THE TRANSCRIPT, THE +# LANE'S LIVE WINDOW STANDS IN FOR IT (openRepoTools#73, item 2). +# The relation is the HARNESS's, between two records of one +# session, and nothing about it depends on who asks — but it was +# read relative to the ASKING process, so `lane-end --retire` typed +# in a bare shell or in another lane's window found nothing +# `here`, every holder came back `unrelated`, and the companion +# was never called one. The record a session's companion sits +# beside is the interactive record in a window this server +# RESOLVES AND AGREES WITH (rc 0 above) — the record `lane-end` +# already calls "the lane's session" — so a `kind: bg` record in +# that record's profile is `companion` from any window. ONLY ONE +# PROFILE MAY ANSWER: two live windows in two profiles on one +# transcript is 18(h)'s own case with no way to tell which is the +# lane's, and there every row stays `unrelated`, as before. The +# anchor row itself is not this window's and stays `unrelated`. +# duplicate EVERY OTHER live record carrying this id: a session record in +# another window of this same profile, or any record at all in +# ANOTHER profile's `sessions/` beside this window's own. That is +# AMENDMENT 18(h)'s second live process. The MEASURED shape was the +# second one — four times on 2026-09-14, the last at 18:14Z, the +# second record sat in another profile's directory, and 18(h) says +# why, *"on a launcher-configured workstation every profile's +# `projects/` is one shared directory … which is also why a +# duplicate is one `--resume` away"* — but the rule it states is +# one live PROCESS per transcript, not one per profile. +# unrelated THIS WINDOW CARRIES NO RECORD OF THIS TRANSCRIPT AT ALL, so this +# read says nothing about the processes that do — beyond the one +# relation that is not this window's to have, the companion above +# (#73). That is not timidity: `live_holder` answers "is any +# session this row names alive" and Amendment 8(f) rules an +# ORPHAN reported and never refused, while `lane_forks` answers +# about a fork. A rule that counted every live record here would +# overturn both from a read that was not asked about either. ONE +# CALLER TAKES IT AS A BLOCKER ANYWAY AND SAYS SO WHERE IT DOES: +# `lane-start`'s `dup_check`, asked about the ONE id a run is +# about to resume, where an `unrelated` holder is a second live +# process on the very file that run is about to open (Amendment +# 18(h), *"never launches a second resume of it"*). That is a +# narrower question than this verdict answers, so the narrowing +# lives at that call site and not in this table. +# +# 0 with rows, 8 with none, 1 where the records could not be read, 64 no uuid. +transcript_holders() { # <session uuid> + th_id="${1-}"; [ -n "$th_id" ] || return 64 + th_files=""; th_match=""; th_err=""; th_f=""; th_blob="" + th_pid=""; th_kind=""; th_tgt=""; th_where=""; th_verdict=""; th_out="" + # `th_here_prof` AND `th_here` AMONG THEM, and the omission was not cosmetic: + # this file runs under `set -u` (line 292), pass 2's `[ -z "$th_here_prof" ]` + # is reached for the FIRST record that is not this window's, and an unset + # variable there exits the shell with `unbound variable` — a 1 every caller + # reads as "the records could not be read" and refuses on. It cost the suite's + # `the same lane live in THIS window is not a collision`, which asks + # `lane-start` for an exit 0 and got `dup_check`'s fail-closed 1. + th_here=""; th_here_prof=""; th_prof=""; th_wrc=0; th_final="" + # THE LANE'S LIVE WINDOW, for the companion verdict where this window has no + # record of the transcript (#73): the profile of the session record whose + # window this server resolves and agrees with, and whether a SECOND profile + # answered too, which leaves no single one to read it from. + th_live_win=no; th_win_prof=""; th_win_two=no + SESSION_FILES_ERR="" + here_context + th_files="$(mktemp "${TMPDIR:-/tmp}/lanes-edit-tf.XXXXXX" 2>/dev/null || printf '')" + th_match="$(mktemp "${TMPDIR:-/tmp}/lanes-edit-tm.XXXXXX" 2>/dev/null || printf '')" + th_err="$(mktemp "${TMPDIR:-/tmp}/lanes-edit-te.XXXXXX" 2>/dev/null || printf '')" + if [ -z "$th_files" ] || [ -z "$th_match" ] || [ -z "$th_err" ]; then + rm -f -- "$th_files" "$th_match" "$th_err" 2>/dev/null || : + SESSION_FILES_ERR="could not create a temporary file under ${TMPDIR:-/tmp}" + return 1 + fi + # NOT `$( )`: session_files sets SESSION_FILES_ERR, and a subshell would keep + # the reason for the failure to itself. + if ! session_files > "$th_files"; then + rm -f -- "$th_files" "$th_match" "$th_err" + return 1 + fi + if [ ! -s "$th_files" ]; then + rm -f -- "$th_files" "$th_match" "$th_err" + return 8 + fi + # The locale and the NUL separator for the reason `live_holder` states above: + # these are arbitrary bytes and BSD `tr` prints nothing at all for a multibyte + # character in a UTF-8 locale. + LC_ALL=C tr '\n' '\0' < "$th_files" | xargs -0 grep -l -F -e "\"sessionId\":\"$th_id\"" > "$th_match" 2>"$th_err" || : + if [ -s "$th_err" ]; then + SESSION_FILES_ERR="$(LC_ALL=C tr '\n' ';' < "$th_err" | LC_ALL=C cut -c1-300)" + rm -f -- "$th_files" "$th_match" "$th_err" + return 1 + fi + rm -f -- "$th_files" "$th_err" + while IFS= read -r th_f; do + [ -n "$th_f" ] || continue + th_blob="$(cat -- "$th_f" 2>/dev/null || :)" + [ -n "$th_blob" ] || continue + # The id is matched EXACTLY and not by the grep alone: a record naming this + # uuid inside some other field would otherwise be counted as a holder. + [ "$(lc "$(jstr "$th_blob" sessionId)")" = "$(lc "$th_id")" ] || continue + record_is_live "$th_blob" || continue + th_pid="$(jnum "$th_blob" pid)" + th_kind="$(jstr "$th_blob" kind)" + th_tgt="$(jstr "$th_blob" tmux)" + th_where=bg; th_live_win=no + if record_fields_are_session "$th_kind" && [ -n "$th_tgt" ]; then + th_wrc=0 + record_window_state "$th_tgt" || th_wrc=$? + case "$th_wrc" in + 0) th_where="window ${th_tgt%.*}"; th_live_win=yes ;; + 1) th_where="window ${th_tgt%.*} (gone)" ;; + 2) th_where="window ${th_tgt%.*} (no answer)" ;; + *) th_where="window ${th_tgt%.*} (not asked)" ;; + esac + elif record_fields_are_session "$th_kind"; then + th_where="no window" + fi + th_here=no + if [ -n "$th_tgt" ] && [ -n "$LANES_THIS_WINDOW" ] && [ "${th_tgt%.*}" = "$LANES_THIS_WINDOW" ]; then + th_here=yes + elif pid_under "$th_pid" "$LANES_PANE_PID"; then + th_here=yes + fi + th_prof="$(record_profile "$th_f")" + [ "$th_here" = yes ] && [ -z "$th_here_prof" ] && th_here_prof="$th_prof" + if [ "$th_live_win" = yes ]; then + if [ -z "$th_win_prof" ]; then th_win_prof="$th_prof" + elif [ "$th_win_prof" != "$th_prof" ]; then th_win_two=yes + fi + fi + th_out="${th_out}${th_pid:-unknown}${US}${th_kind:-interactive}${US}${th_tgt:-none}${US}${th_prof}${US}${th_where}${US}${th_here}${US}${th_f} +" + done < "$th_match" + rm -f -- "$th_match" + [ -n "$th_out" ] || return 8 + [ "$th_win_two" = yes ] && th_win_prof="" + # PASS 2 — THE VERDICT, WHICH NEEDS THE WHOLE SET AND SO CANNOT BE MADE ABOVE. + th_final="" + while IFS="$US" read -r tv_pid tv_kind tv_tgt tv_prof tv_where tv_here tv_file; do + [ -n "${tv_pid:-}" ] || continue + if [ "$tv_here" = yes ]; then + tv_v=here + elif [ -z "$th_here_prof" ]; then + # NOTHING HERE, SO THE LANE'S LIVE WINDOW ANSWERS FOR THE ONE RELATION + # THAT IS NOT THE ASKER'S (#73): the harness's `bg` companion beside it. + # Everything else stays `unrelated`, which is what every caller already + # reads this state as. + if [ -n "$th_win_prof" ] && [ "$tv_prof" = "$th_win_prof" ] && [ "$tv_kind" = bg ]; then + tv_v=companion + else + tv_v=unrelated + fi + elif [ "$tv_prof" = "$th_here_prof" ] && [ "$tv_kind" = bg ]; then + tv_v=companion + else + tv_v=duplicate + fi + th_final="${th_final}${tv_pid}${US}${tv_kind}${US}${tv_tgt}${US}${tv_prof}${US}${tv_where}${US}${tv_v}${US}${tv_file} +" + done <<EOF +$th_out +EOF + printf '%s' "$th_final" + return 0 +} + +# ===================== AMENDMENT 18(b) — THE BINDING, READ ================== +# +# **A LANE HAS ONE BINDING**: the `host`, `container` and `window` of its last +# lane-kind line that is `STARTED` or `RESUMED` with no `PAUSED`, `ENDED` or +# `RETIRED` after it. A lane whose last lane-kind line is one of those three, or +# that has none, is FREE. Ratified 2026-09-14T13:15:18Z as revision 4. +# +# ONE SCAN ANSWERS FOUR QUESTIONS, because three surfaces ask them of the same +# stream and a second pass is a second answer: the `binding` read (clause (c)'s +# refusal), the prompt guard's clause (d) — *"a `HANDOFF-REQUESTED` newer than +# its own binding and not yet answered"* — its clause (e) — *"a `PAUSED` newer +# than the binding that this session did not write"* — and `request-handoff`'s +# wait, which ends when the release arrives. +# +# IT IS FILE ORDER AND NEVER A CLOCK (R14). A lane's log is append-only and +# single-writer, so a line further down the file is a line written later +# whatever the two UTC fields say — and "newer than the binding" here means +# BELOW it in the file, which is the only order two lines of one lane really +# share. The UTC is carried out as information, for the sentence a person reads. +# +# A FORK'S LINE IS NOT THE LANE'S (decision 8(c), A11 Addendum 4 ruling 8), so a +# payload opening `fork ` is skipped exactly as `lane_row_facts` skips it: a +# `RETIRED` about a fork would read as the LANE being retired, which is the +# opposite of what happened. +# +# A LINE WRITTEN BEFORE AMENDMENT 18(a) CARRIES NONE OF THE THREE SUB-FIELDS AND +# STAYS VALID: its binding is *"the window on the row's workstation, which is +# what they read today"*. So `host` falls back to the line's own `@<ws>` — which +# is the Rule 10 workstation, and is also what a container with no export writes +# into `host` deliberately — and `container` falls back to `none`. Amendment +# 7(i)'s cutover rule, with the fallback the clause itself names. +# +# 1 state bound · requested · released · free +# 2 host 3 container 4 window 5 utc 6 session 7 os +# 8 request utc 9 request session 10 request payload +# 11 release verb 12 release utc 13 release session 14 release payload +# 15 legacy `legacy` where the binding line predates clause (a) +# 16 foreign release verb 17 utc 18 session 19 payload — the release +# ANOTHER session wrote after the session named in argument 2 wrote +# its own last lane-kind line, which is clause (e)-s test and which +# survives a later binding by a third place +# +# 0 with the line, 1 where the LOG COULD NOT BE READ — which is not the same +# fact as "this lane has no binding" and never was (#26, the fail-closed family). +lane_binding_scan() { # <lane> [<this session uuid>] + lbs_lines=""; lbs_rc=0 + lbs_lines="$(lane_log_events "$1")" || lbs_rc=$? + [ "$lbs_rc" = 0 ] || return 1 + printf '%s\n' "$lbs_lines" | awk -v sep="$US" -v me="$(lc "${2-}")" ' + function field(pay, want, whole, n, i, sf, v, q) { + want = want " " + n = split(pay, sf, "; ") + for (i = 1; i <= n; i++) { + if (substr(sf[i], 1, length(want)) != want) continue + v = substr(sf[i], length(want) + 1) + sub(/^[ \t]+/, "", v); sub(/[ \t]+$/, "", v) + if (substr(v, 1, 1) == "\"") { + q = index(substr(v, 2), "\"") + if (q > 0) return substr(v, 2, q - 1) + } + if (!whole) sub(/ .*$/, "", v) + return v + } + return "" + } + BEGIN { FS = sep; state = "free" } + # THIS SESSION-S OWN LAST LANE-KIND LINE, wherever it is, and the release + # another session wrote AFTER it — clause (e), which says EVERY prompt from + # then on and not merely the prompt before the next binding (Copilot round 1 + # on this PR). Tracked beside the binding and never out of it: when a third + # place binds the lane after a forced release, the binding fields below move + # on to that new line while this pair stays exactly where it was, which is + # what makes the refusal persist as the clause says it must. + me != "" && tolower($4) == me && \ + ($3 == "STARTED" || $3 == "RESUMED" || $3 == "PAUSED" || $3 == "ENDED" || $3 == "RETIRED") { me_pos = NR; me_verb = $3 } + me != "" && tolower($4) != me && ($3 == "PAUSED" || $3 == "ENDED" || $3 == "RETIRED") { + if (substr($8, 1, 5) != "fork ") { + f_pos = NR; f_verb = $3; f_utc = $1; f_sess = $4; f_pay = $8 + # A release that NAMES this session is evidence on its own, whether or + # not this session ever wrote a line of its own: clause (e)-s `on behalf + # of <bound uuid>` is written by a place that read the binding, and the + # session it names may have been bound by a `lane-start` whose own + # STARTED was deferred for want of a uuid (Amendment 8(d), R-A8-2). + if (index(tolower($8), "on behalf of " me) > 0) { + ob_pos = NR; ob_verb = $3; ob_utc = $1; ob_sess = $4; ob_pay = $8 + } + } + } + $3 == "STARTED" || $3 == "RESUMED" { + if (substr($8, 1, 5) == "fork ") next + state = "bound"; seen = 1 + b_utc = $1; b_sess = $4; b_ws = $5; b_pay = $8 + r_utc = ""; r_sess = ""; r_pay = "" + x_verb = ""; x_utc = ""; x_sess = ""; x_pay = "" + next + } + $3 == "HANDOFF-REQUESTED" { + if (state != "bound" && state != "requested") next + state = "requested" + r_utc = $1; r_sess = $4; r_pay = $8 + next + } + $3 == "PAUSED" || $3 == "ENDED" || $3 == "RETIRED" { + if (substr($8, 1, 5) == "fork ") next + if (!seen) { state = "free"; next } + state = "released" + x_verb = $3; x_utc = $1; x_sess = $4; x_pay = $8 + r_utc = ""; r_sess = ""; r_pay = "" + next + } + END { + host = field(b_pay, "host", 0); if (host == "") host = b_ws + cont = field(b_pay, "container", 0); if (cont == "") cont = "none" + win = field(b_pay, "window", 1) + os = field(b_pay, "os", 0) + # CLAUSE (a) CUTOVER RULE, CARRIED AS A FIELD OF ITS OWN: *"A line + # written before this amendment carries none of the three and stays + # valid; readers treat its binding as THE WINDOW ON THE ROW-S + # WORKSTATION, which is what they read today."* What they read today has + # no container in it — so a pre-amendment binding must not be filed under + # ANOTHER container merely because the asker is in one, which on an estate + # whose every line predates this clause would refuse every lane start + # inside every bench. The fallback values above are still what the read + # PRINTS (`none` is the answer a reader acts on); this field says which of + # them were read and which were supplied. + # (No apostrophe anywhere in this comment: the whole program is a + # single-quoted shell string, and one would end it — the same rule + # `LANES_REGISTER_INDEX_AWK` states for its own.) + # LEGACY IS ALL THREE ABSENT, NOT `host` ALONE (Copilot round 2 on + # openRepoTools#83). The writer drops an offending sub-field on its own + # and keeps the line — `R-A11-11`-s posture — so a MODERN line can carry a + # container and an os and no host, and calling that one pre-amendment + # would ignore the container it does carry and let another container past + # the fence. All three absent is the only shape that is really a line from + # before this clause; anything less fails CLOSED, matched on host AND + # container like every other modern line. + legacy = (field(b_pay, "host", 0) == "" && field(b_pay, "container", 0) == "" && \ + field(b_pay, "os", 0) == "" ? "legacy" : "") + if (state == "free" || state == "released") { host = ""; cont = ""; win = ""; os = ""; legacy = "" } + # A release by another session counts only where it came AFTER this + # session-s own last line. One that came before it is a lane this session + # has bound or handed off since, and the clause is about being released + # from UNDER a session, not about anything that ever happened to the lane. + # A release by another session counts only where it came AFTER this + # session-s own last line, and only where this session HAS one: a uuid + # that appears nowhere in this log has been released from nothing, and + # every fresh transcript in a lane-s window would otherwise be refused for + # ever by the PAUSED its predecessor wrote. The exception is a release + # that names this session outright, which is evidence with no line of its + # own needed. + if (ob_pos > me_pos) { + f_verb = ob_verb; f_utc = ob_utc; f_sess = ob_sess; f_pay = ob_pay + } else if (me_pos == 0 || f_pos <= me_pos) { + f_verb = ""; f_utc = ""; f_sess = ""; f_pay = "" + } + # AND A SESSION THAT RELEASED THE LANE ITSELF WAS TAKEN FROM NOTHING. + # Clause (e) is about a binding released from UNDER a session that still + # holds it; where this session-s own last lane-kind line is a PAUSED, an + # ENDED or a RETIRED, it gave the lane up, and the next place-s release of + # it is ordinary history. A session in that state that is somehow still + # running is the (b) table-s superseded-transcript row, which says the + # right thing about it and names the right cure. + if (me_verb == "PAUSED" || me_verb == "ENDED" || me_verb == "RETIRED") { + f_verb = ""; f_utc = ""; f_sess = ""; f_pay = "" + } + printf "%s%c%s%c%s%c%s%c%s%c%s%c%s%c%s%c%s%c%s%c%s%c%s%c%s%c%s%c%s%c%s%c%s%c%s%c%s\n", \ + state, 31, host, 31, cont, 31, win, 31, b_utc, 31, b_sess, 31, os, 31, \ + r_utc, 31, r_sess, 31, r_pay, 31, x_verb, 31, x_utc, 31, x_sess, 31, x_pay, 31, legacy, 31, \ + f_verb, 31, f_utc, 31, f_sess, 31, f_pay + }' + return 0 +} + +# IS THAT BINDING THIS PLACE'S? Clause (b): *"Liveness is pronounced only from +# INSIDE the binding's own `host` and `container`, where the pid namespace is +# the record's: from anywhere else a binding is UNKNOWN, never dead, whatever +# `kill -0` says."* So the comparison is made ONCE, here, and every surface that +# refuses on it reads the same answer. +# +# A MODERN RECORD MATCHES ON BOTH, AND ON THE HOST'S OWN NAME (Copilot round 2 +# on openRepoTools#83). The `$WS` fallback below is clause (a)'s CUTOVER +# affordance and nothing else: a line written before this amendment carries no +# `host`, and its binding is *"the window on the row's workstation"* — so the +# workstation's name is all such a line has to be matched on, and the container +# it never carried is not asked for. A line that DOES carry the three is matched +# on what it says: the machine's own hostname AND the container. Allowing `$WS` +# there let a record whose `host` is another machine read as `here` wherever the +# two names happened to coincide — and `lane-start` then skips the fence, which +# is the one refusal this clause exists to make. +# +# CLAUSE (a)'s OWN FALLBACK STILL WORKS THROUGH IT: a writer inside a container +# with no `$LANES_HOST` writes the Rule 10 workstation name into `host`, and a +# reader in that same container computes the same name the same way, so the two +# agree without this function having to guess which of the two names it is +# looking at. +# +# TWO FORMS, ONE RULE. `binding_is_here` takes the record's values as they were +# written; `binding_is_here_lc` takes them already lower-cased, for the listing, +# which asks this of every lane and may not spend two processes a lane on `lc`. +# The rule is in the second and the first is two `lc`s in front of it. +LANES_HOST_LC=""; LANES_WS_LC=""; LANES_CONTAINER_LC="" +# THE HOST HALF ON ITS OWN, because clause (b)'s two rules need different +# halves of it: the pid namespace is the host AND the container, while the tmux +# server one host's launcher mounts into every container it starts is THE HOST. +# Both take the same legacy affordance, and taking it in one place is what stops +# them drifting — which is exactly what the review found when only one of them +# had it (Copilot round 4 on openRepoTools#83). +binding_host_is_here_lc() { # <host, lower-cased> [legacy] + [ -n "$LANES_HOST_LC" ] || LANES_HOST_LC="$(lc "$LANES_HOST_NAME")" + [ -n "$LANES_WS_LC" ] || LANES_WS_LC="$(lc "$WS")" + [ "${1-}" = "$LANES_HOST_LC" ] && return 0 + # THE WORKSTATION NAME IS A PRE-AMENDMENT LINE'S ONLY HANDLE, and nothing + # else's: a line that carries the three says which machine it is on, and + # accepting a second name for this one lets another machine's binding read as + # local wherever the two strings coincide. + [ "${2-}" = legacy ] && [ "${1-}" = "$LANES_WS_LC" ] && return 0 + return 1 +} +binding_is_here_lc() { # <host, lower-cased> <container, lower-cased> [legacy] + binding_host_is_here_lc "${1-}" "${3-}" || return 1 + [ "${3-}" = legacy ] && return 0 + [ -n "$LANES_CONTAINER_LC" ] || LANES_CONTAINER_LC="$(lc "$LANES_CONTAINER_NAME")" + [ "${2-}" = "$LANES_CONTAINER_LC" ] || return 1 + return 0 +} +binding_is_here() { # <host> <container> [legacy] + binding_is_here_lc "$(lc "${1-}")" "$(lc "${2-}")" "${3-}" +} + +# IS THIS THE SAME BINDING AS THE ONE THAT WAS READ? Five fields and not two +# (Copilot round 7 on openRepoTools#83). A binding is `host`, `container` and +# `window` — that is clause (b)'s own definition — and the UTC and session are +# what tell one of them from the next at the same place. Compared on the UTC and +# the session alone, a lane released and REBOUND within the same second by a +# process carrying the same transcript id reads as unchanged, and the act that +# follows the comparison (a forced `PAUSED`, or carrying on into a bind) lands +# on a holder that arrived after the read. The log has a one-second UTC and this +# estate resumes one transcript from several places, so neither field is +# distinguishing on its own. +# +# TEN ARGUMENTS IN TWO GROUPS OF FIVE, in the order `binding` prints them. +binding_identity_same() { # <h1> <c1> <w1> <u1> <s1> <h2> <c2> <w2> <u2> <s2> + [ "${1-}" = "${6-}" ] || return 1 + [ "${2-}" = "${7-}" ] || return 1 + [ "${3-}" = "${8-}" ] || return 1 + [ "${4-}" = "${9-}" ] || return 1 + [ "${5-}" = "${10-}" ] || return 1 + return 0 +} + +# THE ONE EXCEPTION CLAUSE (b) CARVES OUT, AND ITS FENCE. *"Where the asker and +# the binding share a tmux server (the launcher mounts one socket into every +# container it starts on a host) and the binding's window no longer exists +# there, the binding is DEAD — the pane a session must live in is gone."* +# +# THE SHARED SERVER IS THE **HOST**, NOT THE CONTAINER: that is the whole point +# of the exception, because two benches on one machine see one tmux and neither +# can see the other's pids. So the window is asked about wherever the `host` +# matches, container or no container, and never where it does not — a window id +# from another MACHINE resolving here would be a coincidence, and matching it is +# how a lane binds to a stranger's pane. +# +# THE ID *AND* THE SESSION, which is Amendment 11(h)'s agreement rule and the +# 2026-09-14 measurement behind it: tmux reuses window ids once a window is +# gone, and a stale record's `@1` resolved to a window of another session. +# +# live the window is there and its session agrees +# gone the id resolves nowhere here, or resolves in another session +# unknown not this host, no `@id` in the record, or no tmux to ask — and +# UNKNOWN IS NEVER DEAD, which is the clause's own word +binding_window_state() { # <host> <window sub-field> [legacy] + bws_host="${1-}"; bws_win="${2-}" + # THE SHARED SERVER IS THE HOST, AND THE HOST IS MATCHED BY THE ONE RULE + # `binding_is_here` USES (Copilot round 4 on openRepoTools#83). This test + # accepted the Rule 10 workstation name for EVERY record, so a MODERN line + # naming another machine could be judged `gone` here — and `gone` is the one + # answer that makes a binding elsewhere read DEAD and hands `lane-start` and + # `lane` the takeover path. A takeover of another machine's lane, out of a + # name that happened to coincide, is the collision this clause exists to stop, + # reached through its own exception. + binding_host_is_here_lc "$(lc "$bws_host")" "${3-}" || { printf 'unknown\n'; return 0; } + [ -n "$bws_win" ] || { printf 'unknown\n'; return 0; } + # `<session>:<index> <@id>` — two space-separated refs in ONE sub-field + # (Amendment 11(c)). The id is the second; a record that carries only the ref + # cannot be tested by the agreement rule at all. + bws_ref="${bws_win%% *}" + bws_id="${bws_win##* }" + case "$bws_id" in @[0-9]*) : ;; *) printf 'unknown\n'; return 0 ;; esac + command -v tmux >/dev/null 2>&1 || { printf 'unknown\n'; return 0; } + bws_now="$(tmux_window_field "$bws_id" '#{session_name}' 2>/dev/null || :)" + # `gone` IS THE ID RESOLVING NOWHERE, AND NOTHING ELSE (Copilot round 6 on + # openRepoTools#83). An id that resolves in ANOTHER session is two different + # facts wearing one answer: tmux reuses ids, so it may be a stranger's + # window — and `lane <name>` MOVES a live lane's window into the asking + # session (Addendum 1 (i-2)), which leaves the record naming the session it + # came from while the very same window, with the very same id, is alive one + # session along. Answered `gone`, that move would make a RUNNING lane read as + # a dead binding, and `gone` is the one answer that hands `lane-start` and + # `lane` the takeover path: a second process on a lane whose window a person + # had just pulled in front of themselves. + # + # So the two are separated and only the first is DEAD. The second is + # `unknown` — not this place's to pronounce, which is clause (b)'s own posture + # everywhere else — and it costs the takeover path exactly the case where an + # id has been reused, which was never a proof of death either. The RECORD + # going stale under a move is a real gap and it is filed, not papered over + # here: `lane` writes nothing to the register by design (Addendum 1), so + # keeping that field current is an act somebody has to rule on + # (opensoft/openRepoTools#95). + # + # AND AN EMPTY ANSWER IS TWO FACTS, OF WHICH ONLY ONE IS DEAD (Copilot round 9 + # on openRepoTools#83). `bws_now` comes back EMPTY both where the id resolves + # nowhere and where there is NO SERVER TO ASK AT ALL — a container the host's + # socket was never mounted into, a server not started yet, a `$TMUX_TMPDIR` + # that differs, a socket this user cannot read. AND THE STATUS IS NOT THE + # DISCRIMINATOR: measured on tmux 3.4, an id that resolves nowhere on a server + # that IS there answers `0` with an empty stdout, while no server at all + # answers 1 with an empty stdout and `error connecting to … (No such file or + # directory)` on stderr — which `tmux_window_field` sends to `/dev/null` and + # this read discards with `|| :`. `command -v tmux` catches only the + # workstation that has no tmux BINARY, and the two are not the same + # workstation. Read as `gone`, the second one makes + # EVERY binding of every other container on this host read DEAD — the one + # answer that hands `lane-start` and `lane` the takeover path — which is this + # clause's own collision reached through its own exception, on the very estate + # the exception was written for. The contract three lines above already says + # *"no tmux to ask"* is `unknown`; this is the code saying it too. + # + # SO THE SERVER IS ASKED A QUESTION THAT DOES NOT MENTION THE ID, and only a + # server that ANSWERS may pronounce. One extra fork, and only on the read that + # was about to say DEAD. + if [ -z "$bws_now" ]; then + tmux list-windows -a -F '#{window_id}' >/dev/null 2>&1 || { printf 'unknown\n'; return 0; } + printf 'gone\n'; return 0 + fi + [ "$bws_now" = "${bws_ref%%:*}" ] || { printf 'unknown\n'; return 0; } + printf 'live\n' + return 0 +} + +# ============ AMENDMENT 18(c)/(d)/(e) — THE SECOND PLACE ASKS =============== +# +# *"`lane-start <repo> <n>` and `restart <lane>` run from a place that is not the +# binding — a different `host`, `container` or `window` — REFUSE to bind. … A +# `y`, or the flag `--request-handoff` from a caller with no terminal, is THE +# REQUEST, and it is written before anything else is tried … Then, WHERE THE +# BOUND PANE IS ON THIS TMUX SERVER, the requester also types `/handoff --exit +# requested by <uuid>@<host>/<container>` into that pane … The requester then +# WAITS … When one arrives the lane is free and the requester binds as it would +# have."* +# +# THE MECHANISM IS HERE AND THE QUESTION IS AT THE DOOR. `lane-start` and `lane` +# each ASK in their own words — one is a launch that has already been typed, the +# other a pick out of a listing — and both then call THIS, so the line that is +# written, the pane that is typed into, the interval that is polled and the +# refusal that ends an empty wait are one implementation. That is the rule +# clause (h) gives `window-lane` and the one A11 Addendum 4 ruling 7 gave column +# 10 after two surfaces had each computed a restart line of their own. +# +# THE ORDER IS THE CLAUSE'S AND IT IS LOAD-BEARING: the line is written and +# PUSHED FIRST, so that a bound session anywhere can read it from `origin`, and +# only then is the pane typed into — which is an optimisation for the same-host +# case and never the request itself. A request that could not be written is not +# a request, and nothing is typed on the strength of one. +# +# $LANES_POLL_SECONDS the poll interval (default 15) — the one seam, and it +# is the suite's: a case that must watch a wait end +# cannot spend fifteen seconds per poll doing it. + +# THE REQUESTER'S OWN TRANSCRIPT UUID, which the line's `session` field is and +# which Amendment 7(b) admits nothing else into (clause (e), enforced in +# `write_event`). Four sources, first answer wins: the flag, `$LANES_SESSION`, +# the harness's own `$CLAUDE_CODE_SESSION_ID`, and the live record of THIS +# window. A caller with none of them is REFUSED rather than given a placeholder: +# the literal `unknown` is in this estate's append-only log four times already +# and no later line corrects any of them. +requester_uuid() { # [<--session value>] + ru_v="${1-}" + [ -n "$ru_v" ] || ru_v="${LANES_SESSION:-}" + [ -n "$ru_v" ] || ru_v="${CLAUDE_CODE_SESSION_ID:-}" + if [ -z "$ru_v" ]; then + here_context + if [ -n "$LANES_THIS_WINDOW" ]; then + ru_rec="$(window_session "$LANES_THIS_WINDOW" 2>/dev/null || :)" + [ -n "$ru_rec" ] && ru_v="${ru_rec%%"$US"*}" + fi + fi + valid_uuid "$ru_v" || return 8 + printf '%s\n' "$(lc "$ru_v")" +} + +# THIS WINDOW'S OWN `@id`, for the one comparison clause (c) needs before it +# writes anything: a request to hand off the window you are standing in is not a +# request, it is a loop. `here_context` gives `<session>:<@id>`; a record's +# `window` sub-field is `<session>:<index> <@id>`, so the ids are what compare. +binding_is_this_window() { # <window sub-field> + bitw_id="${1##* }" + case "$bitw_id" in @[0-9]*) : ;; *) return 1 ;; esac + here_context + [ -n "$LANES_THIS_WINDOW" ] || return 1 + [ "${LANES_THIS_WINDOW##*:}" = "$bitw_id" ] || return 1 + return 0 +} + +# THE FACTS A PERSON NEEDS TO DECIDE, in one place, so the question `lane-start` +# asks, the question `lane` asks and the refusal that ends an empty wait all +# name the same things (clause (e): *"the binding (`host`, `container`, +# `window`, the line and its `UTC`), the request and its `UTC`, whether the pane +# was reachable and typed into, and the one word that overrides"*). +binding_facts() { # <lane> <host> <container> <window> <utc> <session> <window state> + printf 'lane %s is bound to window %s in container %s on host %s (session %s, last line %s); this tmux server says that window is %s\n' \ + "$1" "${4:-none}" "${3:-none}" "${2:-unknown}" "${6:-unknown}" "${5:-unknown}" "${7:-unknown}" +} + +# The UTC of the lane's last `STARTED` or `RESUMED` — Amendment 18(b)'s BINDING, +# read from the lane's own log out of `origin/<branch>` like every other state +# read. Clause (h) rule 2 compares a record's `nameSince` against it: a rename +# OLDER than the binding is a title this window inherited, not an instruction +# somebody has just given. 0 with the stamp, 8 where the log names none, 1 where +# it could not be read. +lane_binding_utc() { # <lane> + lbu_lines=""; lbu_rc=0 + lbu_lines="$(lane_log_events "$1")" || lbu_rc=$? + [ "$lbu_rc" = 0 ] || return 1 + lbu_v="$(printf '%s\n' "$lbu_lines" | awk -F"$US" '$3 == "STARTED" || $3 == "RESUMED" { v = $1 } END { if (v != "") print v }')" + [ -n "$lbu_v" ] || return 8 + printf '%s\n' "$lbu_v" +} + +# ------------------------------------------------- (h)'s ONE ACT ON A PANE +# +# M1, ratified: *"the guard and the `SessionStart` hook rename by TYPING +# `/rename <lane>` into the session's own tmux pane with `tmux send-keys`: the +# only path that exists, run from inside the pane, only after the prompt has +# been refused and only while the pane's current command is `claude`."* +# +# THE PANE'S CURRENT COMMAND IS ASKED FIRST, and a pane that is running anything +# else is NOT typed into: `/rename openRepoTools-3` typed at a shell is a command +# that does not exist, and typed into an editor it is text somebody did not +# write. +# +# `claude` AND NOTHING ELSE, which is M1's own word — *"only while the pane's +# current command is `claude`"*. This test read `claude|node` for one round, on +# the reasoning that the harness is a node program and this format reports the +# process rather than the wrapper; MEASURED on Eagle 2026-09-14T23:4xZ, across +# the twelve panes tmux had, it is not: eleven lane panes report `claude`, two +# report `bash` (a pane whose session is under a launcher wrapper) and one +# `zsh`, and no pane reports `node` at all. So `node` bought nothing here and +# would have let a stray Node REPL in a pane take `/rename <lane>` as input +# (Copilot round 4 on this PR). A pane this refuses is not a lock that failed: +# the caller prints the line for the person to type, which is the cure — and on +# this estate today the `bash` panes are exactly where they will read it. +# +# 0 typed +# 1 no tmux, or `send-keys` itself refused +# 8 the pane's current command could not be read — fail closed, type nothing +# 9 the pane is running something else +guard_type() { # <pane target> <the line to type> + gt_pane="${1-}"; gt_text="${2-}" + [ -n "$gt_text" ] || return 1 + command -v tmux >/dev/null 2>&1 || return 1 + # THE RECORD'S PANE, ELSE THIS ONE — AND THIS ONE IS THE RIGHT FALLBACK + # BECAUSE OF WHERE THIS CODE RUNS. The pane comes from the live record's + # `tmux` field, and the harness has been seen to write NO `tmux` at all for a + # process plainly in a window (Amendment 8, ruling (g)'s third fact) — a + # record `transcript_holders` and `record_is_here` still place HERE, by the + # pane's own process tree. With an empty target the lock used to print "tmux + # would not take the keys" and type nothing, for a session whose name it could + # have fixed (Copilot round 2 on this PR). Both callers of this function run + # INSIDE the session's own pane — a `UserPromptSubmit` hook and a + # `SessionStart` hook do — so `#{pane_id}` with no `-t` is that session's + # pane, asked of tmux rather than guessed, and M1's condition below is still + # asked of whatever pane this resolves to. + [ -n "$gt_pane" ] || gt_pane="$(tmux display-message -p '#{pane_id}' 2>/dev/null || :)" + [ -n "$gt_pane" ] || return 1 + gt_cmd="$(tmux_window_field "$gt_pane" '#{pane_current_command}' 2>/dev/null || :)" + [ -n "$gt_cmd" ] || return 8 + case "$gt_cmd" in claude) : ;; *) return 9 ;; esac + tmux send-keys -t "$gt_pane" "$gt_text" Enter 2>/dev/null || return 1 + return 0 +} + +# THE PENDING OFFER, held per session id and expiring with the session (clause +# (h) rule 2). It is a file and not a variable because the next prompt is a +# different process: `$CLAUDE_CONFIG_DIR/lanes/offers/<uuid>`, the harness's own +# per-profile configuration directory, which is where a fact about one session +# belongs and is not the register. +guard_offer_file() { # <session uuid> + printf '%s/lanes/offers/%s\n' "${CLAUDE_CONFIG_DIR:-$HOME/.claude}" "${1-}" +} + +# `lane-start`, found the way every word in this toolset finds its siblings: +# beside this file first — `--install` places them in one directory — then on +# PATH. One resolution, so a workstation with two copies never reads one and +# runs the other. `$LANES_LANE_START` is the seam the suite sets. +# +# NAMED AS A SIBLING OF THIS FILE AND NOT OF ANY PARTICULAR WORD, because +# Amendment 18 Addendum 2 (in force 2026-09-14T16:50:32Z) takes `restart` off a +# person's PATH altogether — "i think we can drop restart as a cli command and +# keep it inside a claude session with /restart … lane does all the things a +# user wants" — and opensoft/openRepoTools#43 removes the file. A comment that +# pointed at it for its resolution order would name a file that is going. +guard_lane_start() { + if [ -n "${LANES_LANE_START:-}" ]; then printf '%s\n' "$LANES_LANE_START"; return 0; fi + if [ -x "$SCRIPT_DIR/lane-start" ]; then printf '%s\n' "$SCRIPT_DIR/lane-start"; return 0; fi + command -v lane-start 2>/dev/null || printf '' +} + +# ------------------------------------------------------- the triple, printed +# +# EVERY REFUSAL PRINTS THE THREE NAMES AS THEY STAND, and prints them ONCE +# however many things are wrong. What a person sees is the state and then the +# one command, which is F-B6's rule — filled in, never `<repo> <n>`. +G_WINREF=""; G_WINNAME=""; G_ID=""; G_NAME=""; G_SRC=""; G_PID=""; G_PROF="" +G_ROW=""; G_LANE=""; G_SES_LANE="" +# AMENDMENT 16(f) — the former name this window still carried, and whether the +# guard managed to rename the window to the lane's current one. +G_WIN_WAS=""; G_WIN_FIXED=0 +GUARD_TRIPLE_DONE=0 +GUARD_RENAME_SAID=0 +# SAID ONCE, WHEREVER THE RUN ENDS. The guard's own rename of a window is the +# one act it takes that is not a refusal, so it is announced on the agreeing +# path too — a lock that silently did something is a lock nobody knows about, +# which is the rule `guard_lock_rename` already states for the typing. +guard_window_renamed_note() { + [ -n "$G_WIN_WAS" ] || return 0 + [ "$GUARD_RENAME_SAID" = 0 ] || return 0 + GUARD_RENAME_SAID=1 + if [ "$G_WIN_FIXED" = 1 ]; then + note "THIS WINDOW WAS NAMED '$G_WIN_WAS', WHICH IS A FORMER NAME OF LANE $G_LANE (${LANES_ALIASES_PATH:-lanes/aliases.tsv}, Amendment 16(e)) — so it has been renamed to $G_LANE for you (Amendment 16(f): a rename run from another window leaves this one to fix at its next prompt, and a window's name is one tmux call, not a typed one)." + else + note "THIS WINDOW IS NAMED '$G_WIN_WAS', WHICH IS A FORMER NAME OF LANE $G_LANE (${LANES_ALIASES_PATH:-lanes/aliases.tsv}, Amendment 16(e)), and tmux would not rename it. Rename it yourself: tmux rename-window -t ${G_WINREF:-<this window>} $G_LANE" + fi + return 0 +} +# +# THE HEADING IS AN ARGUMENT BECAUSE ONE CALLER DOES NOT REFUSE. An explicitly +# allowed mismatch (choice 1 below) prints the same three names and then lets +# the prompt through, and a line reading "THE NAME GUARD REFUSES THIS PROMPT" +# over a prompt it has just allowed is the guard lying about its own act. Every +# other caller passes nothing and gets the refusal heading unchanged. +guard_triple() { # [<heading>] + [ "$GUARD_TRIPLE_DONE" = 0 ] || return 0 + GUARD_TRIPLE_DONE=1 + gt_s="${G_ID:-unknown} '${G_NAME:-none}'" + [ -n "$G_SRC" ] && gt_s="$gt_s (nameSource $G_SRC)" + [ -n "$G_PID" ] && gt_s="$gt_s pid $G_PID" + [ -n "$G_PROF" ] && gt_s="$gt_s profile $G_PROF" + gt_w="${G_WINREF:-not in tmux} '${G_WINNAME:-none}'" + [ -n "$G_WIN_WAS" ] && gt_w="$gt_w — a former name of $G_LANE (Amendment 16(e))" + note "${1:-THE NAME GUARD REFUSES THIS PROMPT (lane-collision-protocol Amendment 12). The three names:}" + note " window $gt_w" + note " session $gt_s" + note " row ${G_ROW:-not read}" + guard_window_renamed_note + return 0 +} + +# SAFE-MODE RECOVERY, NAMED WHERE A PERSON COULD BE STUCK (clause (d)). +# Profile-only launches are exempt through `CLAUDE_NO_LANE=1` at dispatch. +# Claude's `--safe-mode` disables every hook and is visible in the prompt box; a +# session started that way is not a lane session and may not write the register +# or claim an object. It is printed by the INDETERMINATE refusals — the reads +# that could not be made — and not by the mismatches, which have a cure of their +# own one line above. +guard_bypass() { + printf '%s' "If this workstation cannot answer at all, \`claude --safe-mode\` runs with every hook off — and a session started that way is NOT a lane session: it may not write the register or claim an object." +} + +# <why> [<the one command, filled in>] — the shape of every row of the (b) +# table: the triple, one sentence saying what is wrong, and one line to type. +guard_refuse() { + guard_triple + note "$1" + [ -n "${2-}" ] && note "run: $2" + return 2 +} + +# ============================== `guard` ============================== +# +# THE (b) TABLE, ONE ROW PER STATE AND ONE CURE EACH, in the amendment's own +# order. Every message prints the register's own spelling of the lane +# (Amendment 15) and every command is filled in — or, for a lane named before +# Rule 4, which leaves its checkout unknown, SAYS it cannot be +# (`guard_refuse_start`, openRepoTools#73). +# +# the window is not a lane, the session name parses as `<repo>-<n>` +# -> `lane-start --no-launch <repo> <n>` THE 2026-09-10 CASE +# the window is not a lane, and neither is the session name +# -> `lane-start <repo> <n>` for the lane this work is — the guard cannot +# name it +# the window is a lane, this uuid is the row's LAST id, the session name is +# not a lane name (untitled, a fallback, `<lane> (N)`, any word that does not +# parse) -> THE LOCK RENAMES IT, and says so +# … the session name is ANOTHER lane's and a PERSON set it after the binding +# -> THE OFFER (D5) +# the window is a lane, this uuid is IN the cell but not last +# -> Amendment 8's cure: exit, `lane-start <repo> <n>` +# the window is a lane, this uuid is in NO row +# -> Amendment 8's cure: `lane-start --no-launch <repo> <n>` +# the window is a lane whose name matches TWO rows, or the register cannot be +# read -> refuse naming the read +# not inside tmux at all -> refuse (D2): a lane runs in a tmux window +# named for it +# +# AND THE AGREEING CASE IS SILENT AND COSTS NOTHING, which is the property that +# makes a hook at every prompt bearable at all. +guard_run() { # <the hook's JSON, on stdin already read> + gr_json="${1-}" + + # ---- (e) SCOPE, and the two exemptions are the cheapest tests there are. + # + # A SUBAGENT IS EXEMPT: subagents do not submit prompts, and the lane that + # runs them has already passed this guard. The hook input carries `agent_id` + # for one and nothing else does. + [ -z "$(jstr "$gr_json" agent_id)" ] || return 0 + # OUTSIDE THE PROJECTS ROOT THE GUARD IS SILENT (D1). A name there is a title + # and nothing more. INPUT THAT NAMES NO `cwd` AT ALL is not "outside": it is a + # read that did not happen, and clause (d) refuses those. + gr_cwd="$(jstr "$gr_json" cwd)" + if [ -z "$gr_cwd" ]; then + guard_refuse "the hook input carried no \`cwd\`, so whether this session is under the projects root — the whole of clause (e)'s scope — could not be read, and an indeterminate read refuses (Amendment 12(d)). $(guard_bypass)" + return 2 + fi + under_projects_root "$gr_cwd" "${PROJECTS_ROOT:-$HOME/projects}" || return 0 + + G_ID="$(lc "$(jstr "$gr_json" session_id)")" + gr_prompt="$(jstr "$gr_json" prompt)" + + # ---- THE WORKSPACE. Every other subcommand dies 1 here (the dispatcher's + # own guard, which this verb is exempt from); this one refuses with 2, + # because 1 does not block a prompt and clause (d) is fail CLOSED: a register + # that cannot be located is not a register that agrees. + if [ -z "$LANES_REPO" ] || [ -z "$LANES_DIR" ] || [ ! -f "$LANES_FILE" ]; then + guard_refuse "the ROW cannot be read, so the triple cannot be verified — and a triple that cannot be verified is not a triple that agrees (Amendment 12(d)). $(lanes_workspace_why) $(guard_bypass)" + return 2 + fi + + # ---- (b)'s LAST ROW: NOT INSIDE TMUX AT ALL (D2, "Refuse"). + here_context + if [ -z "$LANES_THIS_WINDOW" ]; then + if [ -z "${TMUX:-}" ]; then + guard_refuse "this session is not in a tmux window at all, and a lane RUNS in a tmux window named for it (Rule 4, Amendment 2). Open one and start the lane there." "lane-start <repo> <n> (in a tmux window)" + else + guard_refuse "tmux did not answer \`display-message -p '#{session_name}:#{window_id}'\`, so the WINDOW half of the triple could not be read — and an indeterminate read refuses (Amendment 12(d)). $(guard_bypass)" + fi + return 2 + fi + G_WINREF="$LANES_THIS_WINDOW" + G_WINNAME="$(tmux display-message -p '#W' 2>/dev/null || :)" + if [ -z "$G_WINNAME" ]; then + guard_refuse "tmux did not answer \`display-message -p '#W'\` for $G_WINREF, so the WINDOW's name could not be read — and an indeterminate read refuses (Amendment 12(d)). $(guard_bypass)" + return 2 + fi + + # ---- THE LIVE RECORD FOR THIS SESSION, AND AMENDMENT 18(h)'s COUNT, IN ONE + # READ. The hook is handed its own `session_id` by the harness, so the + # question asked is "which live processes carry THIS transcript", which is + # both halves at once and is the cheap shape (`transcript_holders` states the + # measurement). `window_session` asks the other question — "what is live in + # this window" — by parsing every record on the workstation, and at 11.8 s + # against 329 of them on 2026-09-14 it cannot run inside a five-second hook. + # + # NOT `$( )`: `transcript_holders` sets `SESSION_FILES_ERR`, and a subshell + # would keep the reason for the failure to itself. + gr_tmp="$(mktemp "${TMPDIR:-/tmp}/lanes-edit-gd.XXXXXX" 2>/dev/null || printf '')" + if [ -z "$gr_tmp" ]; then + guard_refuse "no temporary file could be made under ${TMPDIR:-/tmp}, so this workstation's session records could not be read (Amendment 12(d)). $(guard_bypass)" + return 2 + fi + gr_rc=0 + transcript_holders "$G_ID" > "$gr_tmp" || gr_rc=$? + if [ "$gr_rc" != 0 ] && [ "$gr_rc" != 8 ]; then + rm -f -- "$gr_tmp" + guard_refuse "this workstation's session records could not be read (${SESSION_FILES_ERR:-unknown error}), so the SESSION's own name could not be read — and an indeterminate read refuses (Amendment 12(d)). $(guard_bypass)" + return 2 + fi + gr_here=""; gr_here_tgt=""; gr_others="" + while IFS="$US" read -r gh_pid gh_kind gh_tgt gh_prof gh_where gh_verdict gh_file; do + [ -n "${gh_pid:-}" ] || continue + # A COMPANION IS NEITHER — not this window's record and not a second + # process — so it is passed over in silence, which is Amendment 8 ruling + # (g)'s own posture. Two records of ONE session in ONE pane are that + # session seen twice, and the WINDOWED one is the better witness of it. + case "$gh_verdict" in + here) + if [ -z "$gr_here" ] || { [ "$gr_here_tgt" = none ] && [ "$gh_tgt" != none ]; }; then + gr_here="$gh_pid$US$gh_kind$US$gh_tgt$US$gh_prof$US$gh_file"; gr_here_tgt="$gh_tgt" + fi ;; + duplicate) + gr_others="${gr_others}${gr_others:+, }pid $gh_pid ($gh_where, kind $gh_kind, profile $gh_prof)" ;; + esac + done < "$gr_tmp" + rm -f -- "$gr_tmp" + if [ -z "$gr_here" ]; then + guard_refuse "no live session record in THIS window ($G_WINREF) carries this session id, so the SESSION's own name could not be read — and an indeterminate read refuses (Amendment 12(d)). The records were read; none of them is this window's. $(guard_bypass)" + return 2 + fi + IFS="$US" read -r G_PID gr_kind gr_tgt G_PROF gr_file <<<"$gr_here" + gr_blob="$(cat -- "$gr_file" 2>/dev/null || :)" + G_NAME="$(jstr "$gr_blob" name)" + G_SRC="$(jstr "$gr_blob" nameSource)" + # THE PANE ONLY FROM A TARGET THAT NAMES THIS WINDOW. `here` is true by the + # record's target OR by the pane's own process tree, and tmux REUSES window + # ids — so a record that is here BY ANCESTRY can carry a target another + # window now answers to, and `/rename` typed into it would land in somebody + # else's pane. M1's gate cannot catch that one: the other pane is running + # `claude` too (Copilot round 3 on this PR). Where the record's target does + # not name this window the pane is left EMPTY, and `guard_type` asks tmux for + # the pane this hook is running in, which is the session's own. + gr_pane="" + if [ -n "$gr_tgt" ] && [ -n "$LANES_THIS_WINDOW" ] && [ "${gr_tgt%.*}" = "$LANES_THIS_WINDOW" ]; then + case "$gr_tgt" in *.%*) gr_pane="${gr_tgt##*.}" ;; esac + fi + + # ---- THE REGISTER'S TEXT, TESTED POSITIVELY, ONCE, BEFORE THE ROW IS READ + # (openRepoTools#60). `register_text` prefers `origin/<branch>` and falls back + # to this checkout's file, and where both come back empty — a file this + # checkout cannot open, with no published copy — it answers EMPTY TEXT AND 0, + # because it ends in a `printf`. Every read below then finds no rows, and the + # table refused by its LAST arm, "whose row does not name this uuid at all", + # with a cure that cannot mend a read that did not happen. A status on + # `rows_named_ci` is not the place: its status is its awk's, which says nothing + # about the text, and it is shared with `canon_lane` and Amendment 15's + # callers. The awk below has one job, and its status IS the answer. + # HERE, AND NOT BESIDE THE WORKSPACE TEST WHERE #60 PROPOSED IT: there neither + # the window nor the session has been read yet, so the triple this refusal + # prints said `not in tmux` about a session that is. Here it names both, and + # `row not read`, which is the one thing that is not known. + # IT COSTS ONE `cat` AND ONE `awk`, ~6 ms on a 1.3 MB register: the text is + # cached beside `$SE_CACHE_FILE` for the life of this process, so this is the + # render the first read below would have made, moved here — `GIT_TRACE` counts + # one `git show` of the register per prompt with this test and without it. It + # is streamed and not captured: `$( )` of the same megabyte measured ~30 ms. + if ! register_text 2>/dev/null | awk 'NF { t = 1 } END { exit !t }'; then + guard_refuse "the register's TEXT could not be read — neither \`origin/$LANES_BRANCH:$LANES_PATH\` nor $LANES_FILE rendered a line — so the ROW cannot be read and the triple cannot be verified. A register that could not be read is not a register with no row for this lane, and an indeterminate read refuses (Amendment 12(d)). $(guard_bypass)" + return 2 + fi + + # ---- THE ROW, from `origin/<branch>` as this checkout last had it (R19), and + # every comparison case-insensitive with the register's spelling printed + # (Amendment 15). + # AMENDMENT 16(e) — BOTH LOOKUPS RESOLVE AN ALIAS. A rename run from another + # window leaves this one named for the lane as it was (clause (f) says so in + # as many words), and read byte for byte that window names no row at all: the + # guard would send a running lane to `lane-start --no-launch` for a row it + # already has, under a name the register no longer carries. `rows_named_ci_alias` + # is `rows_named_ci` with the table behind it, so the row this window's name + # answers for is the row the lane is in today. + # AND A TABLE THIS READ COULD NOT OPEN REFUSES THE PROMPT (Copilot round 3 on + # openRepoTools#81). `|| :` made an unreadable `lanes/aliases.tsv` look like + # "this name is no lane", and the `lane_shaped` fallback below then bound the + # window's own former spelling — sending a running lane to `lane-start + # --no-launch` for a row it already has. Clause (d) is fail CLOSED and this is + # exactly its shape: a triple that cannot be verified is not a triple that + # agrees. + # `gr_warc` AND NOT `gr_arc`, WHICH THIS FUNCTION NOW USES FOR THE ANSWER'S + # STATUS (#87). Both are set before every read of them, so nothing leaked; + # one name for two questions in one function is the kind of thing that only + # stays harmless until somebody moves a block. It pairs with `gr_sarc`, the + # session-name read below. + gr_warc=0 + gr_hits="$(rows_named_ci_alias "$G_WINNAME" 2>/dev/null)" || gr_warc=$? + if [ "$gr_warc" = 5 ]; then + guard_refuse "${LANES_ALIASES_PATH:-lanes/aliases.tsv} could not be read ($(lane_alias_err)), so whether this window's name '$G_WINNAME' is a FORMER name of a lane could not be established — and an indeterminate read refuses (Amendment 12(d), Amendment 16(e)). $(guard_bypass)" + return 2 + fi + gr_n="$(printf '%s' "$gr_hits" | grep -c . || :)" + if [ "$gr_n" -gt 1 ]; then + guard_refuse "the register holds $gr_n rows whose lane names differ only by case for this window's name '$G_WINNAME': $(printf '%s' "$gr_hits" | tr '\n' ' '). A lane name is ONE name under any case (Amendment 15), so no read under it is unambiguous and a register that cannot be read is not a register that agrees (Amendment 12(b))." "merge them into one row (Amendment 15(d)) — append the newer row's session id(s) to the older row's session cell, in order, and remove the newer row in the SAME commit" + return 2 + fi + if [ "$gr_n" = 1 ]; then G_LANE="$gr_hits" + elif lane_shaped "$G_WINNAME"; then G_LANE="$G_WINNAME" + fi + + # ---- AMENDMENT 16(f) — AND THE WINDOW IS RENAMED HERE, not merely reported. + # The two halves of the triple are fixed by different acts for a reason: a + # running session's NAME can only be changed from inside it, which is why + # (h)1's lock TYPES `/rename`, while a WINDOW's name is one tmux call any + # client can make — `lane-start:1849` makes exactly this one. So where this + # window still carries a former name of its lane, the guard renames it and + # says so, rather than refusing a prompt over a difference it can close + # itself. It costs nothing where no lane was ever renamed: `G_WIN_WAS` is set + # only when the alias table answered above. + # + # UNTARGETED, LIKE `lane-start:1849` AND `lane-handoff:517`. This hook runs + # INSIDE the session's own pane, so tmux's current window IS the one being + # named, and a `-t` here would be a second spelling of a window this file + # already has three of (Amendment 11(c)) — one more place for two of them to + # disagree. `rename-window` also turns automatic-rename OFF for the window, + # which is what makes the new name survive the next command that runs in it. + gr_wl="$(lc "$G_WINNAME")" + if [ -n "$G_LANE" ] && [ "$gr_wl" != "$(lc "$G_LANE")" ]; then + G_WIN_WAS="$G_WINNAME" + if tmux rename-window "$G_LANE" 2>/dev/null; then + G_WIN_FIXED=1 + fi + fi + + gr_sarc=0 + gr_snhits="$(rows_named_ci_alias "$G_NAME" 2>/dev/null)" || gr_sarc=$? + if [ "$gr_sarc" = 5 ]; then + guard_refuse "${LANES_ALIASES_PATH:-lanes/aliases.tsv} could not be read ($(lane_alias_err)), so whether this session's name '${G_NAME:-none}' is a FORMER name of a lane could not be established — and an indeterminate read refuses (Amendment 12(d), Amendment 16(e)). $(guard_bypass)" + return 2 + fi + gr_snn="$(printf '%s' "$gr_snhits" | grep -c . || :)" + if [ "$gr_snn" -gt 1 ]; then + guard_refuse "the register holds $gr_snn rows whose lane names differ only by case for this session's name '$G_NAME': $(printf '%s' "$gr_snhits" | tr '\n' ' '). A lane name is ONE name under any case (Amendment 15)." "merge them into one row (Amendment 15(d))" + return 2 + fi + if [ "$gr_snn" = 1 ]; then G_SES_LANE="$gr_snhits" + elif lane_shaped "$G_NAME"; then G_SES_LANE="$G_NAME" + fi + + gr_ids=""; gr_last="" + if [ -n "$G_LANE" ]; then + gr_ids="$(session_ids_of_lane "$G_LANE" 2>/dev/null || :)" + gr_last="$(printf '%s\n' "$gr_ids" | grep . | tail -n1 || :)" + if [ -n "$(row_of_lane "$G_LANE" 2>/dev/null || :)" ]; then + G_ROW="\`$G_LANE\` — last session ${gr_last:-none recorded}" + else + G_ROW="the register has no row for \`$G_LANE\`" + fi + else + G_ROW="this window names no lane, so no row is keyed by it" + fi + + # ---- AMENDMENT 18(h) — ONE LIVE PROCESS PER TRANSCRIPT, ASKED BEFORE THE + # PENDING OFFER IS ANSWERED. Clause (h) refuses *"every prompt in a process + # that shares its session id with another live one"*, and THE ANSWER TO THIS + # GUARD'S OWN QUESTION IS A PROMPT: a `2` consumed here runs `lane-start`, + # writes a register row and appends a uuid to a cell, out of a process that + # may not be writing anything at all — and the offer is held per SESSION ID, + # so the second process answers the first one's question. The offer is KEPT + # while the duplicate stands and is answered at the first prompt after the + # other process is retired (Copilot round 1 on this PR). + if [ -n "$gr_others" ]; then + guard_triple + note "ANOTHER LIVE PROCESS CARRIES THIS SESSION ID ($G_ID): $gr_others." + note "A transcript is held by ONE live process (Amendment 18(h), ratified 2026-09-14): two of them append to one file, each overwriting what the other wrote, and the row records an id that two processes answer for. Measured four times on 2026-09-14, the last at 18:14Z — a harness \`--fork-session\` in a background pty host beside the interactive resume, its record in ANOTHER profile's sessions/ directory." + if [ -n "$G_LANE" ]; then + note "retire the other one — it proves the process is this lane's duplicate and prints Amendment 6(d)'s act for it, and it ends, writes and kills nothing:" + note "run: lane-end $G_LANE --retire <pid>" + else + note "retire the other one: lane-end <lane> --retire <pid>. This window names no lane, so which lane it is is yours to name." + fi + return 2 + fi + + # ---- THE PENDING OFFER, ANSWERED BEFORE THE TABLE BELOW IS CONSULTED + # (clause (h) rule 2). The answer prompt is the person's reply to a question + # this guard asked, it is consumed here and never reaches the model, and the + # triple still disagrees BECAUSE of the rename being answered — so this + # cannot wait behind the table below. It DOES wait behind 18(h)'s count + # above, for the reason stated there. + # + # AND AN `allow` FILE IS NOT A PENDING QUESTION, so it is not answered here: + # it is a STANDING ANSWER to one the person has already settled, and it is + # honoured at the row of the table that states the mismatch it allows — never + # in front of the table, where it would also silence the SUPERSEDED and the + # not-in-any-row refusals, which are states nobody allowed and which the + # amendment keeps closed (the requirement's own words: unreadable, ambiguous, + # duplicate or superseded identity still refuses). + gr_off="$(guard_offer_file "$G_ID")" + gr_mode="" + [ -f "$gr_off" ] && gr_mode="$(sed -n -e 's/^mode=//p' "$gr_off" 2>/dev/null | head -n1)" + if [ -f "$gr_off" ] && [ "$gr_mode" != allow ]; then + # 3 IS "THE OFFER WAS STALE AND HAS BEEN DROPPED", and it is the one answer + # that does not consume the prompt: the table below judges it, which asks + # the question again where the mismatch still stands and refuses where the + # state has become one the amendment keeps closed. + gr_arc=0 + guard_answer "$gr_off" "$gr_prompt" "$gr_pane" || gr_arc=$? + [ "$gr_arc" = 3 ] || return 2 + gr_mode="" + fi + + # ---- AMENDMENT 18 CLAUSES (d) AND (e), THE BOUND SESSION'S TWO ANSWERS. + # Both are reads of THIS lane's own object log, made at this point for the + # reason (h)'s count above is made here: the lane is known, nothing has been + # judged yet, and a refusal here costs the prompt and nothing else. + # + # (d) a `HANDOFF-REQUESTED` newer than this session's binding and not yet + # answered by a `PAUSED` of its own -> refuse this ONE prompt, name who + # asked and from where, and type `/handoff --exit requested by …` into + # this pane ((h)1's mechanism, which `guard_type` already is). *"The + # person at the bound pane sees the refusal and the handoff run; nothing + # they typed is lost, because the refused prompt is theirs to type again + # in the new place."* + # (e) a `PAUSED` newer than the binding that THIS session did not write -> + # refuse EVERY prompt from then on, naming the line and who forced it, + # until the person here hands off or ends the session. *"Two places + # never both write a lane in silence; the worst a `--force` can do is + # make the old place stop, loudly."* + # + # BOTH ARE GATED ON THE BINDING BEING THIS SESSION'S, and the gate has two + # disjuncts because a lane's transcript changes under it: the binding's + # `session` field is this uuid, OR the binding's WINDOW is this window — which + # is the `/clear`, the usage reset and the profile switch, where the harness + # minted a new id and the row has not caught up. Without the second, a request + # aimed at a lane that had been cleared would be answered by nobody; without + # the first, a session in a window that merely carries the name would answer + # for somebody else's binding. + # + # WHAT IT COSTS, MEASURED: `lanes-edit.sh binding openRepoTools-3` against this +# estate's live register is **0.17 s** wall (2026-09-15), because it is one +# `git show` of ONE lane's log and one awk — not the register read the triple +# above already paid for. The guard's own budget is the amendment's `timeout 5`, +# and the two reads it makes before this one measured ~2 s and ~0.4 s. +# +# A READ THAT FAILED IS NOT A LANE WITH NOTHING PENDING — but it is not a + # refusal either, and that is a narrowing this guard makes deliberately. + # Clause (d) is fail-closed about the READS THAT BUILD THE TRIPLE; these two + # decide whether ANOTHER PLACE has asked for the lane, and a log that cannot + # be read there costs at worst a request answered one prompt later, while + # refusing on it would block every prompt of every lane on a workstation whose + # `origin` is briefly unreadable. It is said rather than swallowed. + # + # AND ONLY WHERE THIS WINDOW NAMES A LANE. With no lane there is no log to + # read and no binding to be asked for; the row below this block is the one + # that refuses a window naming none, and it says the right thing about it. + gr_bind=""; gr_bind_rc=0 + [ -n "$G_LANE" ] && { gr_bind="$(lane_binding_scan "$G_LANE" "$G_ID")" || gr_bind_rc=$?; } + if [ -z "$G_LANE" ]; then : + elif [ "$gr_bind_rc" != 0 ]; then + note "lane $G_LANE's object log could not be read, so whether another place has asked for this lane (Amendment 18(d)) or forced it away (18(e)) is NOT known this prompt. The prompt is not refused for it — the three names above agree — but a request would be answered one prompt late." + else + IFS="$US" read -r gb_state gb_host gb_cont gb_win gb_utc gb_sess gb_os gb_rutc gb_rsess gb_rpay \ + gb_xverb gb_xutc gb_xsess gb_xpay gb_legacy gb_fverb gb_futc gb_fsess gb_fpay <<EOF +$gr_bind +EOF + gb_mine=0 + [ -n "$gb_sess" ] && [ "$(lc "$gb_sess")" = "$G_ID" ] && gb_mine=1 + # THE WINDOW DISJUNCT IS A LOCAL TEST AND IS GATED LIKE ONE (Copilot round 4 + # on openRepoTools#83). It exists for the `/clear`, the usage reset and the + # profile switch, where the harness minted a new id and the binding's window + # is still this one — but a tmux `@id` names a window on ONE server and tmux + # reissues them from `@0`, so compared alone it could make THIS session the + # answerer for a binding on another host, or for a stale one whose id has + # since been given to somebody else: the guard would then type `/handoff + # --exit` into this pane and refuse this prompt for a request nobody made of + # it. Three tests, not one: the binding is in this host and container, its + # window RESOLVES here with its own session (Amendment 11(h)'s agreement + # rule, which is what `live` means), and only then is the id compared. + if [ "$gb_mine" = 0 ] && [ -n "$gb_win" ] \ + && binding_is_here "$gb_host" "$gb_cont" "$gb_legacy" \ + && [ "$(binding_window_state "$gb_host" "$gb_win" "$gb_legacy")" = live ] \ + && binding_is_this_window "$gb_win"; then + gb_mine=1 + fi + if [ "$gb_mine" = 1 ] && [ "$gb_state" = requested ]; then + # `by host <h>` IS ONE SUB-FIELD WHOSE NAME IS `by host`, which is how + # clause (c) spells the request's payload — `→ by host <h>; container + # <c>; window <w>; wait <n>s`. Read as `host` it matches nothing, because + # `payload_subfield` anchors on the START of a sub-field and this one + # opens `by `. The clause's spelling is the grammar here, not a typo in + # it, and the reader is what bends. + gb_by="$(payload_subfield "$gb_rpay" "by host")" + gb_bc="$(payload_subfield "$gb_rpay" container)" + gb_bw="$(payload_subfield "$gb_rpay" window all)" + gb_line="/handoff --exit requested by ${gb_rsess:-a session this line does not name}@${gb_by:-unknown}/${gb_bc:-none}" + gb_trc=0 + guard_type "$gr_pane" "$gb_line" || gb_trc=$? + guard_triple + note "A HANDOFF WAS REQUESTED for lane $G_LANE at ${gb_rutc:-an instant this line does not name} by ${gb_rsess:-a session this line does not name} from container ${gb_bc:-none} on host ${gb_by:-unknown}${gb_bw:+, window $gb_bw} — handing off (Amendment 18(d))." + gb_wait="$(payload_subfield "$gb_rpay" wait)" + note "A lane has ONE binding: that place cannot bind this lane until this one releases it, and it is WAITING on this session${gb_wait:+, for $gb_wait}. The handoff writes the PAUSED record, refreshes the handoff file with a fresh Rule 3 top block, and then ENDS this session, because a handoff to another place is a handoff and not a restart (Amendment 17(a) under \`--exit\`)." + case "$gb_trc" in + 0) note " \`$gb_line\` has been typed into this pane — it runs at this prompt's place, and THIS prompt is refused so the handoff goes first. Nothing you typed is lost: type it again in the new place." ;; + 9) note " this pane is running something other than \`claude\`, so nothing was typed into it (Amendment 12's M1 types only into a pane running claude). Run it yourself: $gb_line" ;; + 8) note " this pane's current command could not be read, so nothing was typed into it — fail closed. Run it yourself: $gb_line" ;; + *) note " tmux would not take the keys, so nothing was typed. Run it yourself: $gb_line" ;; + esac + note "If this lane is NOT going anywhere, the answer is still an act and not a silence: tell that place, and they can stop waiting." + return 2 + fi + # CLAUSE (e) IS ASKED OF THIS SESSION-S OWN TRACK, not of the latest + # binding (Copilot round 1 on this PR). Read off the binding, the refusal + # stopped the moment a THIRD place bound the lane — the scan-s `x_*` fields + # move on to the new line — and the clause says the refusal is EVERY prompt + # from then on, until the person here hands off or ends the session. Fields + # 16-19 are that track: the release another session wrote after this one-s + # own last lane-kind line, wherever the lane has been since. + if [ -n "$gb_fverb" ] && [ -n "$gb_fsess" ]; then + guard_triple + note "THIS LANE'S BINDING WAS RELEASED BY SOMEBODY ELSE (Amendment 18(e)). Lane $G_LANE's log carries a \`$gb_fverb\` at ${gb_futc:-an instant this line does not name}, written by session $gb_fsess — not by this one — after this session's own last line:" + note " ${gb_fpay:-(no payload)}" + note "Another place forced the lane away and has bound it, or is binding it now. TWO PLACES NEVER BOTH WRITE A LANE: every prompt in this session is refused from here on, and this is not a state a rename or a relaunch clears." + note "The exits, and both are yours: hand this session off properly, which records what it holds and ends it —" + note " lane-handoff --exit \"released from under me by $gb_fsess\"" + note "— or end the session. To take the lane BACK, do it from a place that can bind it, after this one has stopped." + return 2 + fi + fi + + # ---- (b) ROWS 1 AND 2: THE WINDOW IS NOT A LANE. + if [ -z "$G_LANE" ]; then + if [ -n "$G_SES_LANE" ]; then + guard_refuse_start "this window is named '$G_WINNAME', which is no lane, while the SESSION is named for lane $G_SES_LANE — so nothing binds this conversation to a row, no surface would refuse a second window taking the same lane, and the handoff this session writes is one only this profile can find. THAT IS THE 2026-09-10 CASE, which ran for three days." "$G_SES_LANE" --no-launch + else + guard_refuse "neither this window ('$G_WINNAME') nor this session ('${G_NAME:-none}') names a lane, so the guard cannot name one either: WHICH lane this work is is yours to say, and a guard that guessed would bind a window to a row nobody chose." "lane-start <repo> <n> (for the lane this work is)" + fi + return 2 + fi + + # ---- THE WINDOW IS A LANE. Where the uuid sits in the row's cell decides + # which of the next four rows applies, and the cell is a HISTORY written + # oldest first whose LAST id is the lane (Amendment 6(b)). + if [ -n "$gr_last" ] && [ "$G_ID" = "$gr_last" ]; then + # ---- THE DRIFTS THAT ARE NOT DECISIONS, AND AMENDMENT 16 ADDS THE SECOND. + # openRepoTools#87 left the LOCK exactly one case — a session name differing + # from the row's only by CASE, which is the same lane under Amendment 15 — + # and made every other readable mismatch a three-choice OFFER, because a + # person who renames a session to ANOTHER lane's name is choosing something + # and a guard may not choose for them. A FORMER NAME OF THIS VERY LANE IS + # NOT SUCH A CHOICE: clause (e) makes it resolve to this row for ever, so a + # session still named `repoRen-1` on a lane the register now spells + # `repoRen-7` is this lane under the name it was renamed away from — drift + # left behind by a rename run in ANOTHER window, which is precisely the + # state clause (f) exists to finish. Offering three ways to repair it would + # ask a person to decide what the rename already decided, and two of the + # three answers would be wrong: `1` would make the old name permanent and + # `2` would move the lane BACK to the name it was renamed away from. + # + # `$G_SES_LANE` IS THE TEST BECAUSE IT IS ALREADY THE RESOLVED ANSWER: it is + # `rows_named_ci_alias "$G_NAME"` above, so it is this lane exactly when the + # session's name is this lane's under any case or any former spelling. + if [ "$(lc "$G_NAME")" = "$(lc "$G_LANE")" ] \ + || { [ -n "$G_SES_LANE" ] && [ "$(lc "$G_SES_LANE")" = "$(lc "$G_LANE")" ]; }; then + # THE THREE AGREE. Under Amendment 15 they agree under any case — and the + # ROW's spelling is the one the session carries, so a name that differs + # only by case is renamed to it rather than refused for ever. + # AND AN ALLOWANCE DIES WITH THE MISMATCH IT ALLOWED: the names agreeing + # again is one of the two names having CHANGED, which is the requirement's + # own condition for it no longer applying. Leaving the file would let a + # rename back to the allowed spelling pass silently on a decision the + # person made about a state they have since left. + [ -f "$gr_off" ] && [ "$gr_mode" = allow ] && rm -f -- "$gr_off" + # AMENDMENT 16(f): the window may still have carried a former name a + # moment ago, in which case it has just been renamed and that is said + # here — the one thing this guard does that is not a refusal. + [ "$G_NAME" = "$G_LANE" ] && { guard_window_renamed_note; return 0; } + if [ "$(lc "$G_NAME")" = "$(lc "$G_LANE")" ]; then + guard_lock_rename "$gr_pane" "spells the lane '$G_NAME' where the register's row spells it '$G_LANE', and a lane name is ONE name under any case whose canonical spelling is the row's (Amendment 15)" + else + guard_lock_rename "$gr_pane" "is '$G_NAME', which is a FORMER name of lane $G_LANE (${LANES_ALIASES_PATH:-lanes/aliases.tsv}, Amendment 16(e)) — the same lane under the name it was renamed away from, and not a lane anybody is moving to" + fi + return 2 + fi + # ---- THE MISMATCH, AND THE ONE STATE THAT PASSES THROUGH IT. The + # allowance is honoured HERE and nowhere earlier: this is the row of the + # table it was given for — a readable current lane whose uuid is the row's + # LAST id and whose session name is not the lane's — so a superseded + # transcript, a uuid in no row, an ambiguous register and an unreadable + # read have all been refused above it, allowance or no allowance. + if [ "$gr_mode" = allow ] && guard_allow_active "$gr_off"; then + guard_triple "THE NAME GUARD ALLOWS THIS PROMPT ON AN EXPLICIT CHOICE (lane-collision-protocol Amendment 12). The three names:" + note "WARNING: this lane/session name mismatch was explicitly allowed for this transcript. It will remain allowed only while the lane and session names stay unchanged." + return 0 + fi + # AN ALLOWANCE THAT NO LONGER FITS IS DROPPED RATHER THAN CARRIED: either + # name having changed is exactly what invalidates it, and the person is + # asked again below. + [ "$gr_mode" = allow ] && rm -f -- "$gr_off" + guard_offer "$gr_off" "$gr_pane" + return 2 + fi + + if [ -n "$gr_ids" ] && printf '%s\n' "$gr_ids" | grep -qx -F -- "$G_ID"; then + guard_refuse_start "this is a SUPERSEDED transcript of lane $G_LANE: the row's session cell carries $G_ID but ENDS on $gr_last, so the conversation in this window is not the lane's and renaming it would not make it one. Exit this session and start the lane, which resumes the id the row ends on." "$G_LANE" + return 2 + fi + + guard_refuse_start "this window is lane $G_LANE, whose row ${gr_last:+ends on $gr_last and }does not name $G_ID at all — the harness minted a new transcript with nobody acting (a /clear, a usage reset, a profile switch). The lane is right and the ROW is behind, so the cure is the recording act and no relaunch: it reads the live record in this window and appends that uuid to the cell." "$G_LANE" --no-launch + return 2 +} + +# (h) rule 2's third test: is the rename NEWER than this window's binding? +# Amendment 18(b) makes the binding the lane's last `STARTED`/`RESUMED`, and +# `nameSince` is an epoch in MILLISECONDS (measured on this estate's records, +# 2026-09-14). A rename OLDER than the binding is a title this window inherited +# and not an instruction somebody has just given, so it is drift and the lock +# renames it back. A record with NO `nameSince` — an older harness — cannot be +# told apart either way and is drift too, which is (h)1's default and the +# closed direction. A lane whose log records no binding at all cannot make a +# rename older than one, so there the rename is the instruction. +# AND A LOG THAT COULD NOT BE READ IS A THIRD ANSWER, NOT EITHER OF THE TWO +# (openRepoTools#60). `lane_binding_utc` answers 1 for it — `log_path_ci` +# refuses two logs differing only by case (Amendment 15) — and this test folded +# that 1 into the 8, so the `SessionStart` hook, its one caller since #87 made +# the guard's answer the offer, told a person their rename was newer than a +# binding nobody read. Read as "not newer" it would type over a person's own +# `/rename`, which (h) rule 4 forbids, so the caller is told and names the read. +# 0 newer · 1 not newer, or no `nameSince` · 5 the lane's log could not be read +guard_rename_is_newer() { # <lane> <nameSince, epoch ms> + grn_lane="${1-}"; grn_since="${2-}" + case "$grn_since" in ''|*[!0-9]*) return 1 ;; esac + grn_rc=0 + grn_utc="$(lane_binding_utc "$grn_lane" 2>/dev/null)" || grn_rc=$? + [ "$grn_rc" = 0 ] || [ "$grn_rc" = 8 ] || return 5 + [ -n "$grn_utc" ] || return 0 + grn_e="$(epoch_of "$grn_utc")" + [ -n "$grn_e" ] || return 0 + [ "$grn_since" -gt "$((grn_e * 1000))" ] +} + +# ------------------------------------------------------ (h)1: THE LOCK RENAMES +# +# The guard refuses THIS ONE PROMPT so the rename lands first, types +# `/rename <lane>` into this pane, and says so. M1's conditions are +# `guard_type`'s; every outcome but a successful typing prints the line for the +# person to type themselves, because a lock that silently did nothing is a lock +# nobody knows is broken. +guard_lock_rename() { # <pane> <what is wrong with the name, as a clause> + glr_pane="${1-}"; glr_why="${2-}" + glr_rc=0 + guard_type "$glr_pane" "/rename $G_LANE" || glr_rc=$? + guard_triple + note "the session name $glr_why, and under the projects root the session name is not the person's to set freely — it is the LANE's (Amendment 12(h), THE LOCK)." + case "$glr_rc" in + 0) note "SO IT HAS BEEN RENAMED FOR YOU: \`/rename $G_LANE\` was typed into this pane ($glr_pane), which is the only path a running session's name has (M1). This one prompt is refused so the rename lands first — send it again." ;; + 8) note "the pane's current command could not be read, so NOTHING was typed: a \`/rename\` typed at a shell is a command that does not exist and typed into an editor is text nobody wrote. Type it yourself: /rename $G_LANE" ;; + 9) note "this pane is not running claude, so NOTHING was typed, for the reason above. Type it in the lane's own pane: /rename $G_LANE" ;; + *) note "tmux would not take the keys, so NOTHING was typed. Type it yourself: /rename $G_LANE" ;; + esac + # THE ' (N)' SUFFIX IS NOT READ HERE ANY MORE, and it is not lost. Two names + # reach this lock and NEITHER CAN CARRY ONE: a name differing from the lane's + # only by CASE, which has no room for a suffix, and a FORMER name of this lane + # (Amendment 16(e)), which is a KEY of the alias table — and `repoRen-1 (2)` + # is not that key, so a suffixed former name resolves to nothing and goes to + # the offer with every other wider mismatch. `guard_offer` prints ratified + # decision D4's reading of the suffix, where the state that has one arrives. + return 2 +} + +# F-B6 PRINTS EVERY COMMAND FILLED IN, AND THERE IS ONE LANE NAME THAT CANNOT +# BE. `lane_start_args` answers `<repo> <n>` for a lane named under Rule 4's +# `<repo>-<n>` form and `--dir <path> <lane>` for one named before it — and that +# `<path>` is a PLACEHOLDER, because nothing in the register, the window or this +# session says where such a lane's checkout is. Printing it in a diagnostic is +# honest; RUNNING it is not. `lane-start --no-launch --dir '<path>' legacy-ui` +# refuses on a directory that does not exist, and the offer that ran it would +# ask the same question at every prompt afterwards (Copilot round 1 on this PR). +# So the offer SAYS what it cannot fill in and choice `2` refuses instead of +# running it, with the offer kept so that `1` and `3` still answer it. +guard_args_filled() { # <lane> + gaf_a="$(lane_start_args "$1")" + case "$gaf_a" in *'<path>'*) return 1 ;; esac + return 0 +} + +# AND THE TABLE'S OWN CURES SAY IT TOO (openRepoTools#73, item 3). The offer was +# fixed and the diagnostic beside it was not: rows 1, 5 and 6 of the (b) table +# printed `$(lane_start_args …)` straight, so a lane named before Rule 4 got +# `run: lane-start --no-launch --dir <path> legacy-ui` — a `<path>` placeholder +# in the one line a person is told to type, which F-B6 says is printed filled +# in. Filled in where it can be; where it cannot, the reason is the OFFER's +# sentence, the act is the offer's own line, and the checkout is the person's to +# supply, because nothing this guard can read says which one it is. +guard_refuse_start() { # <why> <lane> [--no-launch] + grs_why="${1-}"; grs_lane="${2-}"; grs_flag="${3-}" + if guard_args_filled "$grs_lane"; then + guard_refuse "$grs_why" "lane-start ${grs_flag:+$grs_flag }$(lane_start_args "$grs_lane")" + return 2 + fi + guard_refuse "$grs_why Lane $grs_lane is named before Rule 4's \`<repo>-<n>\` form, so the command below cannot be filled in here: \`lane-start\` needs that lane's DIRECTORY and nothing in the register, the window or this session says which one it is — the checkout is yours to supply." "lane-start ${grs_flag:+$grs_flag }--dir <that lane's checkout> $grs_lane" + return 2 +} + +# ------------------------------------------------------------ (h)2: THE OFFER +# +# *"if the user does a rename, then we should offer to move to that lane or +# create a new lane if we do not have one as that name"* (D5, verbatim). The +# one thing the guard never does silently is decide, with nobody acting, which +# of two disagreeing LANES a window belongs to. +guard_offer() { # <offer file> <pane> + go_f="${1-}"; go_pane="${2-}" + mkdir -p -- "${go_f%/*}" 2>/dev/null || : + { printf 'mode=name-drift\n' + printf 'from=%s\n' "$G_LANE" + printf 'to=%s\n' "$G_SES_LANE" + printf 'session=%s\n' "$G_NAME" + printf 'uuid=%s\n' "$G_ID" + printf 'utc=%s\n' "$(utc_now)" + printf 'window=%s\n' "$G_WINREF" + printf 'pane=%s\n' "$go_pane" + } > "$go_f" 2>/dev/null || : + guard_triple + note "WARNING: the lane and Claude session names disagree. This prompt is paused until you choose how to repair or explicitly allow this lane." + note "1) explicitly allow this lane for this transcript (future prompts warn but do not block while both names stay unchanged)" + if [ -n "$G_SES_LANE" ]; then + go_row="$(row_of_lane "$G_SES_LANE" 2>/dev/null || :)" + if [ -n "$go_row" ]; then + go_last="$(last_session_id_of_lane "$G_SES_LANE" 2>/dev/null || :)" + note "2) adjust the lane to session $G_SES_LANE (existing lane; last session ${go_last:-none recorded})" + else + note "2) adjust the lane to session $G_SES_LANE (create or move to this lane)" + fi + note "3) adjust the session to lane $G_LANE (types \`/rename $G_LANE\` into this pane)" + else + note "2) adjust the lane to session — unavailable because '${G_NAME:-none}' is not a lane name the tooling can safely derive" + note "3) adjust the session to lane $G_LANE (types \`/rename $G_LANE\` into this pane)" + fi + # RATIFIED DECISION D4, WHERE THE STATE IT READS NOW ARRIVES. A `<lane> (N)` + # title is a mismatch and the SUFFIX IS EVIDENCE about another process, so it + # is said beside the choices rather than left for the person to notice. + go_base="${G_NAME% (*)}" + if [ -n "$go_base" ] && [ "$(lc "$go_base")" = "$(lc "$G_LANE")" ] && [ "$go_base" != "$G_NAME" ]; then + note "AND THE ' (N)' SUFFIX IS EVIDENCE: it is exactly what a rename into a title something else still holds mints, so another holder of '$G_LANE' was live when this session was named (Amendment 6(d), ratified decision D4). Naming them is a read of its own, kept off this hook's path because it costs about three seconds: \`lanes-edit.sh forks $G_LANE\`. Retiring one is \`lane-end $G_LANE --retire <pid>\`, which proves it is a fork, prints Amendment 6(d)'s act filled in, and ends, writes and kills nothing." + fi + note "Reply \`1\`, \`2\` or \`3\`. The answer is the NEXT prompt, it is consumed here and never reaches the model; anything else asks again." + [ -f "$go_f" ] || note "(the offer could not be written to $go_f, so the answer will be read as a fresh prompt and this question asked again — which is the safe direction)" + return 2 +} + +# A choice of 1 is deliberately sticky only for the exact readable identity it +# allowed. A renamed session, a different lane binding, or a new transcript +# must come back through the numbered offer. +guard_allow_active() { # <offer file> + gaa_f="${1-}" + [ "$(sed -n -e 's/^mode=//p' "$gaa_f" 2>/dev/null | head -n1)" = allow ] || return 1 + [ "$(sed -n -e 's/^from=//p' "$gaa_f" 2>/dev/null | head -n1)" = "$G_LANE" ] || return 1 + [ "$(sed -n -e 's/^session=//p' "$gaa_f" 2>/dev/null | head -n1)" = "$G_NAME" ] || return 1 + [ "$(sed -n -e 's/^uuid=//p' "$gaa_f" 2>/dev/null | head -n1)" = "$G_ID" ] || return 1 + return 0 +} + +# ------------ THE UUID IN THE NEW LANE'S CELL, WHICH `lane-start --bind` WRITES +# +# CLAUSE (h) RULE 2 NAMES THE END STATE AND RULE 3 REPEATS IT: after choice 2, +# *"window X, session X, ROW X STAMPED WITH THIS UUID"*. `lane-start --no-launch` +# used to perform every other part of that and NOT this one, by a fence that is +# right and stays: its step 3b VETO 1 — Amendment 11 clause (d) rule 1 — never +# takes a uuid that belongs to ANOTHER ROW, and after a rename this uuid belongs +# to `$ga_from`'s. +# +# MEASURED, AND IT WAS A LOOP AND NOT A BLEMISH. In the suite: choice `2` moved +# the window to `repoGD-2`, whose row then read `STARTED by 7a01ae69…` while this +# session was `aaaa0012-1111…`. The NEXT prompt therefore found a lane window +# whose row did not name this transcript — the last row of the (b) table — and +# refused with `lane-start --no-launch repoGD 2`, which vetoed for the same +# reason and changed nothing. So the guard made that last write itself, after +# `lane-start` returned — by which time `lane-start` had taken the destination +# row's ordinary RESUME path and stamped the row, the lane's log and the handoff +# with the id THE ROW ALREADY HAD, under `--no-launch`, about a conversation +# nobody was in (openRepoTools#70). +# +# THE WRITE IS `lane-start`'s NOW, IN ITS BINDING MODE. `--bind <this uuid>` is +# veto 1 answered by the person's `2` — clause (h) rule 4's limit is that the +# lock never moves a uuid between rows WITHOUT the person's yes, and this is the +# yes — so the cell is extended first and every stamp names THIS uuid, in one +# act, anchored on the PUBLISHED last id as `lane-start` always anchors, and +# where a cell records no uuid on the `none recorded` or `pending — set by the +# session's first act` text such a cell carries instead, which is this guard's +# former anchor rule moved there. +# +# SO THIS IS A READ, AND IT WRITES NOTHING. It says the end state rule 3 names +# is there, or prints the act that puts it there where `lane-start` could not: +# a checkout whose copy of the row is older than the published one, or a cell +# carrying no uuid and neither text. THE OLD WRITE IS NOT KEPT BEHIND IT AS A +# FALLBACK, because it would rescue neither: its anchor is `lane-start`'s, so a +# stale copy of the row refuses it exactly as it refused `lane-start` (whose own +# next write to that same row line has by then met the same difference as a +# rebase conflict), and a cell with neither text has nothing to anchor on. What +# it would add is a second append after a write whose push timed out, read +# against a published ref that never moved — the uuid in the cell twice. +# +# 0 the cell ends on this uuid +# 1 it does not, and the act that fixes it has been printed +guard_bound_check() { # <the lane moved to> + gbc_to="${1-}" + # THE CACHED REGISTER IS THE ONE FROM BEFORE `lane-start` RAN, and this is the + # one place in the file that reads it AFTER a writer has moved it: a row + # `lane-start` has just CREATED is not in it at all, and the answer would then + # be "no uuid" on the one path that most needs the true one. Both copies are + # dropped — the variable this shell holds and the file every subshell reads + # (A11 Addendum 4 ruling 12) — exactly as `log_sync` drops them after a fetch, + # and for the same reason: the ref has moved under them. + LANES_REGISTER_CACHE="" + gbc_rc="${SE_CACHE_FILE:+$SE_CACHE_FILE.register}"; [ -n "$gbc_rc" ] && rm -f -- "$gbc_rc" + gbc_last="$(last_session_id_of_lane "$gbc_to" 2>/dev/null || :)" + if [ "$(lc "$gbc_last")" = "$(lc "$G_ID")" ]; then + note "…and $gbc_to's session cell now ends on $G_ID, written by lane-start's binding mode — which is what the next \`lane-start $gbc_to\` resumes." + return 0 + fi + note "…but $gbc_to's session cell does NOT end on $G_ID (it ends on ${gbc_last:-no transcript uuid at all}; lane-start's own words are above). Stamp it as this session's first act, which is Amendment 6(c)'s own remedy:" + note " LANES_LANE=$gbc_to lanes-edit.sh append-session-id $gbc_to \"<the session cell's last id>\" \"→ harness $G_ID (transcript uuid; profile ${G_PROF:-unknown})\"" + return 1 +} + +# The answer, and it is the whole of clause (h) rule 2's second half. +guard_answer() { # <offer file> <the prompt> <pane> + ga_f="${1-}"; ga_p="${2-}"; ga_pane="${3-}" + ga_mode="$(sed -n -e 's/^mode=//p' "$ga_f" 2>/dev/null | head -n1)" + ga_from="$(sed -n -e 's/^from=//p' "$ga_f" 2>/dev/null | head -n1)" + ga_to="$(sed -n -e 's/^to=//p' "$ga_f" 2>/dev/null | head -n1)" + ga_session="$(sed -n -e 's/^session=//p' "$ga_f" 2>/dev/null | head -n1)" + ga_ans="$(printf '%s' "$ga_p" | tr 'A-Z' 'a-z' | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')" + # THE OFFER IS READABLE WHEN IT NAMES ITS MODE AND THE LANE IT WAS MADE FOR, + # AND `session=` IS NOT PART OF THAT TEST. A session record carrying NO `name` + # at all is the (b) table's own untitled row and it reaches this offer with an + # empty name, so requiring one here made that state's offer UNANSWERABLE: the + # question was asked, the answer was dropped as unreadable, the next prompt + # asked it again, and choice 3 — the one that would have fixed it — could + # never be reached. An empty session name is a FACT about the session, and it + # is printed as `none` wherever this speaks. + if [ "$ga_mode" != name-drift ] || [ -z "$ga_from" ]; then + rm -f -- "$ga_f" + guard_refuse "the pending offer at $ga_f could not be read, so it has been dropped rather than answered on a guess. Send your prompt again and the question will be asked afresh." + return 2 + fi + # AND THE QUESTION BEING ANSWERED MUST STILL BE THE QUESTION THAT WAS ASKED + # (Copilot round 1 on openRepoTools#87). The file is keyed by TRANSCRIPT, and + # a prompt is a later moment: between the offer and its answer the window can + # be renamed to another lane and the session renamed by hand, and every one of + # the three choices then acts on a state nobody was shown — `2` moves to a + # destination derived from a session name that has gone, `3` types `/rename` + # for a lane this window no longer is, and `1` records an allowance for a pair + # that does not exist. So the stored identity is compared with the live one, + # and a stale offer is DROPPED rather than answered: this prompt is not + # consumed, it is judged by the table below, which asks again where the + # mismatch still stands and refuses where the state has become one of the + # unsafe ones. 3 is that status, and `guard_run` is its only caller. + if [ "$ga_from" != "$G_LANE" ] || [ "$ga_session" != "$G_NAME" ]; then + rm -f -- "$ga_f" + note "the pending question was about lane $ga_from and session '${ga_session:-none}', and this window is now lane ${G_LANE:-none} with session '${G_NAME:-none}' — so the offer has been DROPPED rather than answered on a state you were never shown. Nothing was renamed or written. This prompt is judged afresh below." + return 3 + fi + case "$ga_ans" in + 1) + if ! { printf 'mode=allow\n' + printf 'from=%s\n' "$ga_from" + printf 'to=%s\n' "$ga_to" + printf 'session=%s\n' "$ga_session" + printf 'uuid=%s\n' "$G_ID" + printf 'utc=%s\n' "$(utc_now)" + } > "$ga_f" 2>/dev/null; then + guard_refuse "the explicit allow could not be recorded at $ga_f, so the mismatch remains unapproved. Nothing was renamed or written; answer 1 again after the session state is writable." + return 2 + fi + guard_triple + note "ALLOWED: this lane/session name mismatch is explicitly allowed for this transcript. This answer is consumed; send your work again. Future prompts will warn without blocking while the lane remains $ga_from and the session remains '${ga_session:-none}'." + return 2 ;; + 2) + if [ -z "$ga_to" ]; then + guard_refuse "choice 2 is unavailable because the session name '${ga_session:-none}' is not a lane name the tooling can safely derive. Nothing was renamed or written; the offer is kept. Choose 1 or 3." + return 2 + fi + if ! guard_args_filled "$ga_to"; then + guard_refuse "lane $ga_to is named before Rule 4's \`<repo>-<n>\` form, so choice 2 cannot be filled in here: \`lane-start\` needs that lane's DIRECTORY and nothing in the register, the window or this session says which one it is. NOTHING has been renamed, moved or written, and the offer is KEPT." "lane-start --no-launch --dir <that lane's checkout> $ga_to" + return 2 + fi + ga_start="$(guard_lane_start)" + if [ -z "$ga_start" ] || [ ! -x "$ga_start" ]; then + guard_refuse "there is no \`lane-start\` beside this file or on PATH, so this window has NOT moved to $ga_to and NOTHING has been written. The offer is kept: answer \`2\` again once it is installed (\`openRepoTools --install\`)." + return 2 + fi + # THE WINDOW IS RENAMED FIRST, AND THAT ORDER IS LOAD-BEARING. Clause (h) + # rule 2 lists the acts in it — *"window renamed, row created or this uuid + # appended to its cell"* — and `lane-start` will not do the second while the + # first is undone: its step 3b VETO 2 refuses to take the session live in a + # window NAMED FOR ANOTHER LANE (Amendment 11 clause (d) rule 1, veto 2, + # `R-A11-12`), which after choice 2 is exactly what this window is. Without + # the rename the binding mode below REFUSES, because `--bind` answers veto 1 + # and never veto 2 (openRepoTools#70) — and before it existed the lane was + # started and stamped with the person's transcript left OUT of its session + # cell, the one thing the next resume follows. The veto is right and stays: + # what changes is that the person has just said this window is the other + # lane. + if command -v tmux >/dev/null 2>&1; then + tmux rename-window "$ga_to" 2>/dev/null || + note "the window could not be renamed to $ga_to, so lane-start may refuse to take this session as that lane's (its step 3b veto 2)." + fi + ga_rc=0 + # ITS STDOUT IS THE COMMAND IT WOULD HAVE LAUNCHED, and a hook's stdout is + # not what a person reads: everything this act says goes to stderr, where + # the blocking reason is shown. + # UNQUOTED ON PURPOSE: `lane_start_args` prints TWO words, `<repo> <n>` — + # or `--dir <path> <lane>` for a lane named before the `<repo>-<n>` rule. + # AND IN ITS BINDING MODE (openRepoTools#70): `--bind` names THIS + # transcript, so the destination's cell is appended with it and the row's + # stamp, its log line and its handoff's Rule 3 stamp all name it — never + # the id that row would otherwise have resumed, which nobody is in. The + # flag is the guard's alone, so it is in this call and in no command this + # file prints for a person to type. + # shellcheck disable=SC2046 + "$ga_start" --no-launch --bind "$G_ID" $(lane_start_args "$ga_to") >&2 || ga_rc=$? + if [ "$ga_rc" != 0 ]; then + guard_refuse "\`lane-start --no-launch $(lane_start_args "$ga_to")\`, run in its binding mode for this transcript, exited $ga_rc (its own words are above), so this window has NOT moved and $ga_from has NOT been marked MOVED. The offer is KEPT, so answer \`2\` again once that refusal is settled, or choose \`3\` to rename the session back to $ga_from." + return 2 + fi + rm -f -- "$ga_f" + guard_triple + note "MOVED: this window is now lane $ga_to — renamed, and stamped. The prompt that answered the question is consumed; send your work again." + guard_bound_check "$ga_to" || : + if [ -n "$(row_of_lane "$ga_from" 2>/dev/null || :)" ]; then + # AMENDMENT 13(a) — THE STATE IS SET, NOT APPENDED. This window has just + # moved to another lane, so the lane it LEFT is not running in it any + # more: `PAUSED` is where that lane now is, and the line says where it + # went. It used to be an `append-row-status` of `MOVED → <lane>`, which + # left the cell saying two things at once — whatever state it opened with, + # and this. + # THE LINE IS BOUNDED (Copilot round 5 on openRepoTools#82). A lane name is + # bounded in its CHARACTERS by `check_lane_name` and not in its length, and + # this line carried it twice: a long enough name makes `set-row-state` + # refuse the very write that records where the work went — after the window + # has already been renamed and moved. The name is said ONCE, and cut where + # even once does not fit, so the act always records something true. + ga_line="this window moved to lane $ga_to on the person's choice 2 at the guard" + if [ "${#ga_line}" -gt 230 ]; then + ga_line="${ga_line:0:230}" + case "$ga_line" in *' '*) ga_line="${ga_line% *}" ;; esac + ga_line="$ga_line ..." + fi + if "$RESOLVED" set-row-state "$ga_from" "PAUSED · $ga_line" >&2; then + note "…and $ga_from's row now reads PAUSED, naming the move to $ga_to." + else + note "…but $ga_from's row could NOT be marked (its writer's words are above). Run: lanes-edit.sh set-row-state $ga_from \"PAUSED · $ga_line\"" + fi + else + note "…and the register has no row for $ga_from, so there is nothing to mark MOVED there." + fi + return 2 ;; + 3) + ga_trc=0 + guard_type "$ga_pane" "/rename $ga_from" || ga_trc=$? + guard_triple + case "$ga_trc" in + 0) rm -f -- "$ga_f"; note "ADJUSTED SESSION TO LANE $ga_from: \`/rename $ga_from\` was typed into this pane ($ga_pane). The prompt that answered the question is consumed; send your work again." ;; + *) note "the rename could NOT be typed into this pane, so the session is still named '${ga_session:-none}'. NOTHING was written; the offer is kept. Type it yourself: /rename $ga_from" ;; + esac + return 2 ;; + *) + guard_triple + note "that is not an answer to the pending question, so it has been refused rather than acted on: this window is lane $ga_from and this session is named '${ga_session:-none}'." + note "1) allow this lane for this transcript 2) adjust the lane to session ${ga_to:-${ga_session:-none}} 3) adjust the session to lane $ga_from (types \`/rename $ga_from\`)" + # THE SAME SENTENCE THE OFFER ENDS ON, because a question asked again is + # asked in the words it was asked in: a person who is being re-asked has + # just typed something else, and two spellings of one question is how they + # come to believe the second one takes different answers. + note "Reply \`1\`, \`2\` or \`3\`. The answer is the NEXT prompt, it is consumed here and never reaches the model; anything else asks again." + return 2 ;; + esac +} + + +# ------------------------------- CLAUSE (f): THE `SessionStart` BLOCK'S LINE +# +# *"Where the record's name differs from the window's lane it prints +# `session name '<x>' was not the lane '<y>' — renamed` and types the rename +# ((h)1), so the first prompt already finds the three agreeing. It stays +# read-only against the register and non-blocking, as Amendment 8 made it; the +# refusal is the `UserPromptSubmit` hook's."* +# +# AND AMENDMENT 18(h)'s READ BESIDE IT, SAID AND NOT ACTED ON: where another +# live process carries this session id, the block NAMES it and the retire act. +# The guard refuses on that; this hook refuses nothing and never will — a hook +# that fails is a hook that breaks the session it was meant to orient (R-A8-1), +# and typing into its own pane writes nothing anywhere, which is why (h)1 gives +# it that one act and no other. +# +# EVERY PATH RETURNS 0. A read that failed prints nothing rather than guessing: +# the guard is the surface that refuses on an indeterminate read, and doing it +# twice, in the hook that may not, would be the same failure one layer up. +ssb_name_line() { # <session uuid> <lane, or empty> + snl_id="${1-}"; snl_lane="${2-}" + [ -n "$snl_id" ] || return 0 + snl_tmp="$(mktemp "${TMPDIR:-/tmp}/lanes-edit-sn.XXXXXX" 2>/dev/null || printf '')" + [ -n "$snl_tmp" ] || return 0 + snl_rc=0 + # IN A SUBSHELL, AND THAT IS R-A8-1 AND NOT TIDINESS. *"This hook never fails + # and always exits 0"*; `|| snl_rc=$?` catches a RETURN and catches nothing + # else, because a fatal inside a function called in this shell — an unbound + # variable under `set -u`, a `die` on a path nobody expected to reach one — + # exits the shell itself, `|| :` at the call site and all. Measured: with + # `th_here_prof` unset, `lanes-edit.sh session-start` exited 1 and printed no + # block at all, which is precisely the hook breaking the session it was + # written to orient. Nothing here needs state from the call — the rows come + # back through a file — so the subshell costs nothing and bounds it. + ( transcript_holders "$snl_id" ) > "$snl_tmp" 2>/dev/null || snl_rc=$? + if [ "$snl_rc" != 0 ]; then rm -f -- "$snl_tmp"; return 0; fi + snl_file=""; snl_tgt=none; snl_others="" + while IFS="$US" read -r sn_pid sn_kind sn_tgt sn_prof sn_where sn_verdict sn_file; do + [ -n "${sn_pid:-}" ] || continue + # The same three-way reading the guard makes, and for the same reasons. + case "$sn_verdict" in + here) + if [ -z "$snl_file" ] || { [ "$snl_tgt" = none ] && [ "$sn_tgt" != none ]; }; then + snl_file="$sn_file"; snl_tgt="$sn_tgt" + fi ;; + duplicate) + snl_others="${snl_others}${snl_others:+, }pid $sn_pid ($sn_where, kind $sn_kind, profile $sn_prof)" ;; + esac + done < "$snl_tmp" + rm -f -- "$snl_tmp" + if [ -n "$snl_others" ]; then + printf 'DEFECT: another live process carries this session id (%s): %s — a transcript is held by ONE live process (Amendment 18(h)), and two of them append to one file. Retire it: lane-end %s --retire <pid>\n' \ + "$snl_id" "$snl_others" "${snl_lane:-<lane>}" + fi + [ -n "$snl_lane" ] && [ -n "$snl_file" ] || return 0 + snl_blob="$(cat -- "$snl_file" 2>/dev/null || :)" + snl_name="$(jstr "$snl_blob" name)" + [ -n "$snl_name" ] || snl_name=none + [ "$snl_name" = "$snl_lane" ] && return 0 + # THE SAME FENCE AS THE GUARD'S, for the same reason and in the same words: + # a record that is here by ancestry can carry another window's target, and + # this hook types into a pane. `here_context` is asked HERE because the read + # above it runs in a subshell, which is where its answer would otherwise have + # stayed. + # A PERSON'S RENAME TO ANOTHER LANE IS THE GUARD'S TO OFFER, NOT THIS HOOK'S + # TO UNDO. Clause (f) types the rename for (h)1's case — DRIFT, a name that is + # no lane's — while (h) rule 2 makes a record whose `nameSource` is `user`, + # whose name is another lane's, and whose `nameSince` is later than this + # window's binding an INSTRUCTION, answered `1`, `2` or `3` at the next prompt. + # This hook runs on every startup, resume, clear and fork, so typing over such + # a name would erase the person's choice before the guard could put the + # question (Copilot round 4 on this PR): a rename, then a `/clear`, and the + # offer never happens. It is SAID here and left to the prompt that follows. + snl_src="$(jstr "$snl_blob" nameSource)" + snl_since="$(jnum "$snl_blob" nameSince)" + snl_nrc=1 + if [ "${snl_src:-}" = user ] && [ "$(lc "$snl_name")" != "$(lc "$snl_lane")" ] \ + && { [ -n "$(rows_named_ci "$snl_name" 2>/dev/null || :)" ] || lane_shaped "$snl_name"; }; then + snl_nrc=0 + guard_rename_is_newer "$snl_lane" "$snl_since" || snl_nrc=$? + fi + case "$snl_nrc" in + 0) + printf "session name '%s' is a lane name YOU set, newer than this window's binding to '%s' — the name guard offers the move at your next prompt (Amendment 12(h) rule 2); nothing was renamed here\n" \ + "$snl_name" "$snl_lane" + return 0 ;; + # A BINDING NOBODY COULD READ IS NEITHER ANSWER (openRepoTools#60): not + # "newer", which is a claim about a log this hook did not read, and not + # drift, which would type over the person's own rename. The read is named + # and the name left alone; this hook refuses nothing, so that is all it does. + 5) + printf "session name '%s' is a lane name YOU set, and lane %s's object log could not be read, so whether you set it after this window's binding is NOT known — nothing was renamed here, and the name guard puts it to you at your next prompt (Amendment 12(h) rule 4)\n" \ + "$snl_name" "$snl_lane" + return 0 ;; + esac + here_context + snl_pane="" + if [ -n "$snl_tgt" ] && [ "$snl_tgt" != none ] && [ -n "$LANES_THIS_WINDOW" ] \ + && [ "${snl_tgt%.*}" = "$LANES_THIS_WINDOW" ]; then + case "$snl_tgt" in *.%*) snl_pane="${snl_tgt##*.}" ;; esac + fi + snl_trc=0 + guard_type "$snl_pane" "/rename $snl_lane" || snl_trc=$? + if [ "$snl_trc" = 0 ]; then + printf "session name '%s' was not the lane '%s' — renamed\n" "$snl_name" "$snl_lane" + else + printf "session name '%s' is not the lane '%s' — run: /rename %s\n" "$snl_name" "$snl_lane" "$snl_lane" + fi + return 0 +} + +# ----------------------------------------------------------------- GitHub +# +# Rule 1 is one act: the three reads, the local line, and the comment that +# another person reads. The LOG is authoritative for a claim made through +# `claim` — a log line IS a live claim for Rule 1 purposes — and the GitHub +# comment is the copy that a person outside this estate can see. +# --no-github skips every call here, which is what the tests and an offline +# lane run with. + +# THE SIBLING READS NAME THE OBJECT, NOT ITS DIGITS (Amendment 8). Rule 1's +# reads 2 and 3 searched for the bare slug as a SUBSTRING, and a number is a +# substring of almost everything. Measured live on 2026-09-12 against the +# governing repository, `gh pr list --search 15` answered with PR #16 and PR +# #10 — GitHub had matched the digits inside "**15 of the register's 41 rows**" +# — and `ls-remote | grep 15` answered with a branch whose 40-character sha +# merely contains them, all under the heading "existing work on this object". +# A sibling that does not NAME the object is not evidence about it, and evidence +# that is not evidence is how a lane talks itself out of a claim it should make. +# +# TWO READS, TWO TESTS, because the two inputs are not the same kind of text. +# pr `gh pr list`'s rows, which are prose. A number in prose is a +# number; a REFERENCE is `#<n>`, so the hash is required — and its +# LEFT side is not bounded, because the canonical spelling of the +# thing being looked for is `owner/repo#15` and the character before +# the `#` is a letter. A row whose FIRST field is the number itself +# is kept too: that is the PR the object IS. +# branch `ls-remote`'s refs, which are names. `issue-15-fix` names the +# object and carries no hash, so the bare number as a whole token is +# the test — after the leading sha is stripped, so a branch is matched +# by its name and never by the digits of the commit it points at. +# An OpenSpec change directory has a word for a slug and takes the whole-token +# test in both modes. +# +# AND READ 2 FILTERS OVER THE BODY. `gh pr list`'s columns are number, title, +# branch and state; the reference that makes a PR a sibling is almost always in +# its BODY, which is what GitHub's own search matched and what the columns do +# not carry. Filtering the columns alone dropped PR #16 — the PR for this very +# issue, whose body says `brettheap/new-workstation#15` twice — while a filter +# with the hash optional kept #10 instead. So the body is fetched, flattened to +# one line, used for the test, and cut off again before anything is printed: +# under-reporting a sibling is the direction that lets a lane claim what +# somebody is already working on, and it is the one direction Rule 1 cannot +# afford. +ere_quote() { printf '%s' "${1-}" | sed -E 's/[][(){}.^$*+?|\\/]/\\&/g'; } +sibling_filter() { # <object> [pr|branch]; candidate lines on stdin + sfl_slug="$(object_slug "$1")" + sfl_num="$(object_number "$1")" + sfl_mode="${2:-pr}" + if [ -z "$sfl_slug" ]; then cat; return 0; fi + sfl_q="$(ere_quote "$sfl_slug")" + if [ -n "$sfl_num" ] && [ "$sfl_mode" = pr ]; then + # `#<n>` anywhere, or the row's own number column. + awk -v sep="$(printf '\t')" -v n="$sfl_slug" -v re="#$sfl_q([^0-9A-Za-z]|$)" ' + { if ($0 ~ re) { print; next } + split($0, f, sep); if (f[1] == n) print }' + return 0 + fi + sed -E 's/^[0-9a-fA-F]{40}[[:space:]]+//' \ + | grep -E -- "(^|[^0-9A-Za-z])$sfl_q([^0-9A-Za-z]|\$)" || : +} + +gh_reads() { + gr_obj="$1"; gr_repo="$(object_repo "$gr_obj")"; gr_n="$(object_number "$gr_obj")"; gr_slug="$(object_slug "$gr_obj")" + gr_term="${gr_n:+#$gr_n}"; gr_term="${gr_term:-$gr_slug}" + if [ "$NO_GITHUB" = 1 ]; then + printf '1. existing claims on the object: not read (--no-github)\n' + printf '2. gh pr list --state all --search: not read (--no-github)\n' + printf '3. git ls-remote --heads: not read (--no-github)\n' + return 0 + fi + command -v gh >/dev/null 2>&1 || { note "gh is not on PATH — rerun with --no-github, or install it"; return 1; } + printf '1. existing `CLAIMED —` comments on %s:\n' "$gr_obj" + if [ -n "$gr_n" ]; then + gr_c="$( { gh issue view "$gr_n" --repo "$gr_repo" --comments 2>/dev/null || gh pr view "$gr_n" --repo "$gr_repo" --comments 2>/dev/null; } | grep -n -e 'CLAIMED —' -e 'TAKEOVER —' -e 'RELEASED —' || : )" + else + gr_c="" + fi + printf '%s\n' "${gr_c:- none}" + printf '2. `gh pr list --repo %s --state all --search "%s"`, kept where the row or its body names `%s`:\n' "$gr_repo" "$gr_term" "${gr_n:+#}$gr_slug" + # The body is fetched for the TEST and cut off before the print. `--json` + # needs a gh that has it; where it does not, the four columns are filtered on + # their own, which is strictly less recall and never a wrong answer. + gr_raw="$(gh pr list --repo "$gr_repo" --state all --search "$gr_term" --limit 20 \ + --json number,title,headRefName,state,body \ + -q '.[] | [.number, .title, .headRefName, .state, (.body // "" | gsub("[\r\n]+"; " "))] | @tsv' 2>/dev/null || :)" + [ -n "$gr_raw" ] || gr_raw="$(gh pr list --repo "$gr_repo" --state all --search "$gr_term" --limit 20 2>/dev/null || :)" + gr_p="$(printf '%s\n' "$gr_raw" | sibling_filter "$gr_obj" pr | cut -f1-4 || :)" + printf '%s\n' "${gr_p:- none}" + printf '3. `git ls-remote --heads git@github.com:%s` branches naming `%s` as a whole token:\n' "$gr_repo" "$gr_slug" + gr_b="$(git ls-remote --heads "git@github.com:$gr_repo.git" 2>/dev/null | sibling_filter "$gr_obj" branch || :)" + printf '%s\n' "${gr_b:- none}" + return 0 +} + +gh_comment() { + gc_obj="$1"; gc_body="$2"; gc_repo="$(object_repo "$gc_obj")"; gc_n="$(object_number "$gc_obj")" + [ "$NO_GITHUB" = 1 ] && return 1 + [ -n "$gc_n" ] || { note "$gc_obj is a change directory, not an issue or a PR — no GitHub comment to post"; return 1; } + command -v gh >/dev/null 2>&1 || return 1 + gc_url="$(printf '%s' "$gc_body" | gh issue comment "$gc_n" --repo "$gc_repo" --body-file - 2>/dev/null \ + || printf '%s' "$gc_body" | gh pr comment "$gc_n" --repo "$gc_repo" --body-file - 2>/dev/null || :)" + gc_url="$(printf '%s\n' "$gc_url" | grep -o 'https://[^ ]*' | tail -n1 || :)" + [ -n "$gc_url" ] || return 1 + printf '%s\n' "$gc_url" +} + +# The hook `commit_push` calls after every `pull --rebase`, before it pushes. +# If another lane's CLAIMED or TAKEOVER on this object is on the rebased +# history, THEIRS LANDED FIRST and this claim has lost. Git's push +# serialization is the arbiter across workstations; the local `mkdir` mutex +# only serializes one workstation, and never decides a race. +# Of the rival lanes in <holders>, the one whose line on <object> LANDED +# first. Landing order is the arbiter and a timestamp is not: two +# workstations' clocks are not a shared order, which is the whole reason this +# amendment decides the race by which CLAIMED reaches `main` first. The +# pickaxe lists the commits that added a line naming the object, oldest first; +# the first of them that touched a rival's log names the winner. +first_landed_of() { # <object> <holder rows> + fl_obj="$1"; fl_holders="$2" + fl_first="$(printf '%s\n' "$fl_holders" | head -n1 | cut -d"$US" -f1)" + [ "$(printf '%s\n' "$fl_holders" | grep -c .)" -gt 1 ] || { printf '%s\n' "$fl_first"; return 0; } + have_remote_ref || { printf '%s\n' "$fl_first"; return 0; } + while IFS= read -r fl_sha; do + [ -n "$fl_sha" ] || continue + while IFS= read -r fl_f; do + [ -n "$fl_f" ] || continue + fl_lane="${fl_f##*/}"; fl_lane="${fl_lane%.md}" + # THE JOIN IS FILE NAME → HOLDER ROW, AND THE TWO NEED NOT SPELL THE LANE + # ALIKE (Copilot round 4). The file carries the row's canonical spelling + # from the moment the first write renames it (Amendment 15); the holder row + # carries whatever the winning LINE was typed with, which an append-only + # log never rewrites. Byte for byte this join missed the winner and the + # rescan fell back to the sorted-first holder — a CLAIM-LOST naming the + # wrong lane. Literal and case-insensitive, both defects at once. + if [ -n "$(printf '%s\n' "$fl_holders" | rows_named "$fl_lane")" ]; then printf '%s\n' "$fl_lane"; return 0; fi + done <<EOF +$(git -C "$LANES_REPO" show --name-only --format= "$fl_sha" -- "$LANES_LOG_PREFIX" 2>/dev/null) +EOF + done <<EOF +$(git -C "$LANES_REPO" log --reverse --format=%H -S"$fl_obj" "origin/$LANES_BRANCH" -- "$LANES_LOG_PREFIX" 2>/dev/null) +EOF + printf '%s\n' "$fl_first" +} + +claim_rescan_hook() { + CLAIM_WINNER="" + # The pull has just moved `origin/<branch>`, and OUR commit is not on it — + # so everything this read can see landed before ours, which is the whole + # test. Flush the cache first: the ref moved a moment ago. + state_events_flush + # ISSUE #30's OWN RACE (Copilot round 12, PR #61): the dead-lane verdict was + # read ONCE, before this claim's first pull, and nothing about $CLAIM_OBJ has + # to change for that verdict to go stale — a RESUMED line is the LANE's own + # log, never an event on the object the scan below reads, so that scan alone + # can never catch a source lane waking back up. Re-run the SAME check the + # takeover was granted on, on every rebase this loop makes, and abandon + # exactly as a landed rival does the moment it no longer answers dead. A + # stale-claim takeover carries no such verdict to revalidate — `claim_is_stale`'s + # age does not run backwards — so this runs only where `CLAIM_SKIP_DEAD` says + # the skip was issue #30's. + if [ -n "$CLAIM_SKIP_DEAD" ] && [ -n "$CLAIM_SKIP" ] && ! holder_is_dead "$CLAIM_SKIP"; then + # THREE DIFFERENT ANSWERS, NEVER ONE SENTENCE (Copilot's own "closer + # look" on 21b8e82, PR #61): `holder_is_dead` returning false a SECOND + # time is not one fact. `HOLDER_LIVE_TERMINAL` set is a CONFIRMED + # revival; `HOLDER_TERMINAL_UNKNOWN` set is a read that failed — fail- + # closed for ownership, same as the grant itself demanded, but "I could + # not check" is not "it came back", and saying so would misreport a read + # failure as a fact this file never established; NEITHER set means the + # log's own last lane-kind line has moved past ENDED/RETIRED entirely — + # a resume in every sense but the word. Distinguished so the note says + # which actually happened here. + # + # AND A FOURTH, `HOLDER_NO_VERDICT` (Copilot on 05d7889, PR #61): the + # log itself could not be read, or yielded no lane-kind line at all. That + # is not "moved past the terminal line" — nothing was read to move — so + # it takes the could-not-reconfirm words, and `CLAIM_ABANDON_REVIVED` + # carries which kind of abort this was to the note and the CLAIM-LOST + # line `claim` writes after this hook returns, so neither says "alive + # again" about a lane nobody saw come back. + CLAIM_ABANDON_REVIVED=1 + if [ -n "$HOLDER_LIVE_TERMINAL" ]; then + note "lane $CLAIM_SKIP is no longer confirmed dead — its own log ends $HOLDER_LIVE_TERMINAL, but a live session on this workstation now backs it up" + elif [ -n "$HOLDER_TERMINAL_UNKNOWN" ]; then + CLAIM_ABANDON_REVIVED="" + note "lane $CLAIM_SKIP's dead-lane verdict could not be reconfirmed — this workstation could not read whether a live session backs it up before this takeover's push landed. That is NOT 'still dead', so the takeover is abandoned rather than assumed safe" + elif [ -n "$HOLDER_BOUND_ELSEWHERE" ]; then + # AMENDMENT 18(b) (Copilot on 8ce6c9d, PR #61): the log the takeover + # was granted on now names a last binding on another host or container, + # whose liveness this place cannot pronounce — not a revival seen. + CLAIM_ABANDON_REVIVED="" + note "lane $CLAIM_SKIP's dead-lane verdict could not be reconfirmed — its last binding is now on $HOLDER_BOUND_ELSEWHERE (host/container), and from here that binding is UNKNOWN, never dead (Amendment 18(b)). The takeover is abandoned rather than assumed safe" + elif [ -n "$HOLDER_NO_VERDICT" ]; then + CLAIM_ABANDON_REVIVED="" + note "lane $CLAIM_SKIP's dead-lane verdict could not be reconfirmed — its own object log could not be read, or yielded no lane-kind line at all, before this takeover's push landed. That is NOT 'still dead' and NOT 'it resumed' either: nothing was read. The takeover is abandoned rather than assumed safe" + else + note "lane $CLAIM_SKIP is no longer confirmed dead — its own log has moved past the terminal line this takeover was granted on, a resume in every sense but the word" + fi + CLAIM_WINNER="$CLAIM_SKIP" + # A DISTINCT EXIT CODE, NOT A REUSE OF 7 (Copilot's own "closer look" on + # 21b8e82, PR #61): 7 is documented, elsewhere and before this PR + # (`lanes-edit.sh`'s own exit-code table, `docs/README-lanes.md`), as + # CLAIM-LOST — another lane's claim landing on main first — and + # automation reading that code for THIS abort would chase a remote race + # that never happened. 9 is this file's own public code, unused before + # now; the event this writes is still CLAIM-LOST (this attempt did not + # succeed, which is what that verb has always meant), but the PROCESS + # exit is not the SAME claim as a landed rival's. + return 9 + fi + # CASE-INSENSITIVE ON BOTH EXCLUSIONS (Amendment 15), for the reason `claim`-s + # own pre-check carries it: these two remove THIS lane and the lane it is + # taking over from the set of rivals, and the row each removes carries whatever + # spelling the winning line used. Byte for byte, a lane whose earlier CLAIMED + # says `repohold-1` under the row `repoHold-1` loses the race to ITSELF and + # writes a CLAIM-LOST naming itself as the winner — measured, exit 7. + # AND LITERAL, not `grep -iv` (Copilot round 4): a name is not a pattern, and a + # rival removed because a `.` in THIS lane's name matched its spelling is a + # race this read reports as won when it was lost. + crh="$(state_events | lane_states_on "$CLAIM_OBJ" | holders_of "$CLAIM_OBJ" \ + | rows_not_named "$CLAIM_LANE" | { [ -n "$CLAIM_SKIP" ] && rows_not_named "$CLAIM_SKIP" || cat; } || :)" + [ -n "$crh" ] || return 0 + CLAIM_WINNER="$(first_landed_of "$CLAIM_OBJ" "$crh")" + IFS="$US" read -r crh_lane crh_verb crh_utc crh_rest <<EOF +$(printf '%s\n' "$crh" | rows_named "$CLAIM_WINNER" | head -n1) +EOF + note "another lane's claim landed on main before this one: @$CLAIM_WINNER ($crh_verb, $crh_utc)" + return 7 +} + +# The URL of the stale claim a TAKEOVER supersedes — Rule 1's takeover comment +# must name it. Read from GitHub, because that is where the comment is. +gh_stale_claim_url() { + gs_obj="$1"; gs_lane="$2"; gs_repo="$(object_repo "$gs_obj")"; gs_n="$(object_number "$gs_obj")" + [ "$NO_GITHUB" = 1 ] && return 1 + [ -n "$gs_n" ] || return 1 + command -v gh >/dev/null 2>&1 || return 1 + gh issue view "$gs_n" --repo "$gs_repo" --json comments \ + -q '.comments[] | select(.body | test("CLAIMED — lane '"$gs_lane"'")) | .url' 2>/dev/null | tail -n1 +} + +# ------------------------------- AMENDMENT 13(e): THE MIGRATION, ONE ACT ----- +# +# `migrate-state-cells` empties every `state` cell of its diary INTO the lane's +# own log, once, on Brett Heap's word (ratified decision O3: after the writer +# changes are installed on both workstations — a cell must stop growing before +# it is emptied). It is a DRY RUN unless `--yes` is passed, and it REFUSES to +# run at all when no cell holds a ` · ` entry, so a second run is a no-op that +# says so. +# +# NOTHING IS DELETED. The appended narrative exists in git history AND in +# `lanes/archive/LANES-pre-amendment-13-<UTC>.md`, written in this same commit, +# AND in the logs — three times over, which is the posture Amendment 3 took +# after the 2026-09-08 loss. +# +# WHAT A ROW BECOMES. Its cell is split on ` · ` into entries, in cell order +# (the cell grew by appending, so that is oldest first). Each entry becomes one +# line in `lanes/log/<lane>.md`: `RULED` where the entry begins with RULING, +# RULINGS or RATIFIED, else `NOTED`; the entry's own leading timestamp becomes +# the line's UTC field rather than being repeated inside its text, and every +# other character of the entry is carried verbatim — including the ` — ` these +# entries are full of, which the log's parser reads as prose because a +# lane-kind line's free text is introduced by the ` — ` right after its object. +# The cell is then REPLACED by the state derived from the LAST entry's leading +# verb where that verb is one of clause (a)'s, else by `MIGRATED`. +# +# THE FOUR FIELDS THAT ARE NOT IN THE ENTRY come from the row: the UTC of an +# entry that carries none is the row's `started` (a date-only `started` is read +# as midnight UTC that day, and the register's older minute-precision form is +# accepted as Amendment 7(b) already accepts it); the session is the LAST uuid +# of the row's session cell; the workstation is the first `/`-separated part of +# the row's own column. +# +# AND A ROW THAT CANNOT BE MIGRATED IS SKIPPED AND NAMED, never guessed at and +# never half-written. Its cell keeps its history, so a re-run after the row is +# fixed by hand migrates exactly that row. Five reasons, all of them visible in +# the dry run: an ambiguous row (more than six ` | ` separators — see +# `row_split_state_cell`); a row whose session cell holds NO transcript uuid, so +# the line could only name `unknown` in the one field this log must never carry +# it in; two rows whose lane names differ only by case (Amendment 15(d)'s hand +# merge); a lane whose object log is two files, or is published under a +# spelling this checkout does not have; and a name that is not a lane name. +# Measured against the live register on 2026-09-15 (52 rows): 20 rows migrate, +# 1 has no uuid, 2 are ambiguous, and 29 hold no ` · ` entry at all and are +# already one phrase. +# +# THE WORKSTATION IS A TOKEN OR IT IS `unknown`. Twelve of the live register's +# rows carry `<workstation? — owner fills>` in that column, and that placeholder +# holds a ` — `: written into the `session <uuid>@<ws>` field it would put a +# THIRD ` — ` in the line, ahead of the object, and the log's own parser would +# read the verb and the fields out of the wrong halves for ever. So the column +# is read up to its first ` / `, and anything that is not one plain token +# (letters, digits, `.`, `_`, `-`) is recorded as `unknown` — which is inert +# here: no reader computes a lane's state, its window or its workstation from a +# narrative line (Amendment 13(b)). + +# THESE FOUR ASSIGN A GLOBAL AND RETURN, rather than printing — the idiom +# `table_lookup` states one screen up, for the same reason: *"a function whose +# answer is taken with `$( … )` forks, which is the cost this exists to avoid"*. +# They are asked once PER ENTRY, and the live register holds 2,206 entries +# across its twenty diary cells. Measured on a copy of it, 2026-09-15: the +# printing form took 94 seconds of a dry run, five forks an entry; this one +# takes eleven. +MIG_LEAD_UTC="" +MIG_LEAD="" +MIG_TRIM="" + +# Spaces off BOTH ends, forking nothing — `rstrip_spaces` and its mirror in one +# place, for the one caller that runs them thousands of times in a row. +mig_trim() { # <text> — sets MIG_TRIM + MIG_TRIM="${1-}" + while [ "${MIG_TRIM# }" != "$MIG_TRIM" ]; do MIG_TRIM="${MIG_TRIM# }"; done + while [ "${MIG_TRIM% }" != "$MIG_TRIM" ]; do MIG_TRIM="${MIG_TRIM% }"; done +} + +# The entry's own leading timestamp, or empty. Matched at the very start of the +# entry and nowhere else: a UTC in the middle of a sentence is prose. +mig_lead_utc() { # <entry> — sets MIG_LEAD_UTC + MIG_LEAD_UTC="" + case "${1-}" in + [0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9]Z*) MIG_LEAD_UTC="${1:0:20}" ;; + [0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]Z*) MIG_LEAD_UTC="${1:0:17}" ;; + esac +} + +# The row's `started` cell as an instant the log's grammar can read: the UTC it +# already is, else midnight on the date it opens with, else empty — the live +# register spells that column `2026-09-02`, `2026-09-04 ~15:30Z` and +# `2026-09-13T17:41Z` in different rows. +mig_started_utc() { # <the started cell> + mig_trim "${1-}" + mig_lead_utc "$MIG_TRIM" + [ -n "$MIG_LEAD_UTC" ] && { printf '%s' "$MIG_LEAD_UTC"; return 0; } + case "$MIG_TRIM" in + [0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]*) printf '%sT00:00Z' "${MIG_TRIM:0:10}" ;; + esac +} + +# Everything a leading state word or timestamp can hide behind, stripped: the +# register writes `**LIVE**`, `> RULING …` and `` `PAUSED` `` in the same column. +mig_strip_lead() { # <text> — sets MIG_LEAD + MIG_LEAD="${1-}" + while :; do + case "$MIG_LEAD" in + ' '*|'*'*|'_'*|'`'*|'>'*|'#'*) MIG_LEAD="${MIG_LEAD#?}" ;; + *) break ;; + esac + done + mig_lead_utc "$MIG_LEAD" + [ -n "$MIG_LEAD_UTC" ] && { MIG_LEAD="${MIG_LEAD#"$MIG_LEAD_UTC"}"; MIG_LEAD="${MIG_LEAD# }"; } + return 0 +} + +# Clause (e)'s test: does this entry RECORD A RULING? Case-folded, because the +# register spells it `RULING`, `Ruling` and `RULINGS` in the same week. +# A CHARACTER CLASS PER LETTER, which is how a `case` matches without regard to +# case in POSIX shell — and it forks nothing, where the `tr` it replaces forked +# once per entry. `RULINGS` is `RULING*` already. +mig_is_ruling() { # <entry> + mig_strip_lead "${1:0:64}" + case "$MIG_LEAD" in + [Rr][Uu][Ll][Ii][Nn][Gg]* | [Rr][Aa][Tt][Ii][Ff][Ii][Ee][Dd]*) return 0 ;; + esac + return 1 +} + +# The current state the last entry names, or empty. The word must END where the +# state word ends — `LIVELY` is not `LIVE` — and `LANDING #<n>` keeps its number, +# because Rule 6's reading of this cell is unchanged by Amendment 13 and is now +# the whole of what the cell says at that moment. +mig_lead_state() { # <entry> + mig_strip_lead "${1:0:64}" + mls="$MIG_LEAD" + case "$mls" in + 'LANDING #'*) + mls_n="${mls#LANDING #}" + mls_d="" + while :; do + case "$mls_n" in + [0-9]*) mls_d="$mls_d${mls_n:0:1}"; mls_n="${mls_n:1}" ;; + *) break ;; + esac + done + # THE NUMBER ENDS WHERE THE WORD ENDS, exactly as `state_word_is_valid` + # and the five states below bound theirs. Without the test `LANDING #123abc` + # derived the state `LANDING #123` — a merge hold Rule 6 would read, out of + # an entry that names no PR at all (Copilot round 1 on openRepoTools#82). + case "$mls_n" in + '' | [!A-Za-z0-9]*) [ -n "$mls_d" ] && printf 'LANDING #%s' "$mls_d" ;; + esac + return 0 ;; + 'HANDED OFF' | 'HANDED OFF'[!A-Za-z0-9]*) printf 'HANDED OFF'; return 0 ;; + LIVE | LIVE[!A-Za-z0-9]*) printf 'LIVE'; return 0 ;; + PAUSED | PAUSED[!A-Za-z0-9]*) printf 'PAUSED'; return 0 ;; + LANDED | LANDED[!A-Za-z0-9]*) printf 'LANDED'; return 0 ;; + ENDED | ENDED[!A-Za-z0-9]*) printf 'ENDED'; return 0 ;; + RETIRED | RETIRED[!A-Za-z0-9]*) printf 'RETIRED'; return 0 ;; + esac + return 0 +} + +# IS THIS CELL ALREADY CLAUSE (a)'s PHRASE? `<STATE> · <UTC> · <one line>` — +# exactly three parts, the first one of the seven states (or the migration's own +# `MIGRATED`) and the second an instant. +# +# WITHOUT THIS THE MIGRATION READS ITS OWN OUTPUT AS A DIARY. The phrase it +# writes carries two ` · ` of its own, so "the cell holds a ` · ` entry" is true +# of every row the moment it has been migrated, and clause (e)'s refusal — +# *"it REFUSES to run when no cell holds a ` · ` entry, so a second run is a +# no-op that says so"* — could never fire on a register that had just been +# migrated. Measured: the second run re-split every migrated cell into three +# entries and would have appended them to the logs again. +mig_cell_is_phrase() { # <cell> + mcp="${1-}" + case "$mcp" in *' · '*) : ;; *) return 1 ;; esac + mcp_a="${mcp%% · *}"; mcp_r="${mcp#* · }" + case "$mcp_r" in *' · '*) : ;; *) return 1 ;; esac + mcp_b="${mcp_r%% · *}"; mcp_c="${mcp_r#* · }" + case "$mcp_c" in *' · '*) return 1 ;; esac # a fourth part is not the phrase + [ -n "$mcp_c" ] || return 1 + case "$mcp_a" in + MIGRATED) : ;; + *) state_word_is_valid "$mcp_a" || return 1 ;; + esac + mig_lead_utc "$mcp_b" + [ -n "$mcp_b" ] && [ "$MIG_LEAD_UTC" = "$mcp_b" ] || return 1 + return 0 +} + +# The workstation field of a migrated line — see the paragraph above. +mig_row_ws() { # <the workstation column> + mrw="${1%% / *}" + mrw="$(rstrip_spaces "$mrw")" + case "$mrw" in + '' | *[!A-Za-z0-9._-]*) printf 'unknown' ;; + *) printf '%s' "$mrw" ;; + esac +} + +# A BLOCK OF LINES APPENDED WITH THE SAME PROOF `append_text_line` MAKES FOR +# ONE. A lane's whole migrated history is appended in a single act — the alt is +# one call per entry, and on the live register that is hundreds of full copies +# of a log and hundreds of `1 line appended to …` notes for what is one write. +# The proof is the stronger of the two `append_text_line` states: the file +# afterwards must be exactly its old bytes followed by exactly this block. +append_text_block() { # <target> <block, lines separated by newlines> + atb_t="$1"; atb_b="$2" + [ -n "$atb_b" ] || return 0 + ATB_TMPD="$(mktemp -d)" + atb_pre="$ATB_TMPD/pre" + cat -- "$atb_t" > "$atb_pre" + atb_before="$(wc -l < "$atb_pre" | tr -d ' ')" + atb_n="$(printf '%s\n' "$atb_b" | wc -l | tr -d ' ')" + printf '%s\n' "$atb_b" >> "$atb_t" # >> FOLLOWS the symlink + atb_after="$(wc -l < "$atb_t" | tr -d ' ')" + [ "$atb_after" -eq "$((atb_before + atb_n))" ] || + die "append changed line count by $((atb_after - atb_before)) where $atb_n lines were appended; inspect $atb_t" 5 + { cat -- "$atb_pre"; printf '%s\n' "$atb_b"; } | cmp -s -- "$atb_t" - || + die "append rewrote existing bytes; inspect $atb_t" 5 + # AND THE COPY GOES, because it is a whole log and there is one per lane: the + # live register's migration makes twenty of them in a run, and a dry run makes + # them while reporting that nothing was written (Copilot round 1 on + # openRepoTools#82). It is removed HERE, where the proof has just passed, and + # a `die` above leaves it for the same reason every other `mktemp -d` in this + # file leaves one: a refused write is evidence. + rm -rf -- "$ATB_TMPD" + note "$atb_n lines appended to $atb_t" +} + +# The act itself. `<1>` writes; `<0>` is the dry run, which reads exactly the +# same things, reports exactly the same rows, and touches nothing. +migrate_state_cells() { # <1 = the act, 0 = the dry run> + msc_do="${1:-0}" + msc_utc="$(utc_now)" + msc_tmp="$(mktemp -d)" + mkdir -p "$msc_tmp/block" + : > "$msc_tmp/report"; : > "$msc_tmp/skips"; : > "$msc_tmp/cells"; : > "$msc_tmp/targets" + msc_arch_rel="${LANES_PREFIX}archive/LANES-pre-amendment-13-$msc_utc.md" + msc_arch="$LANES_DIR/archive/LANES-pre-amendment-13-$msc_utc.md" + + # THE FETCH FIRST (R30), AND A CHECKOUT THAT IS BEHIND IS REFUSED. This one + # act rewrites every row of the register and appends to every lane's log in a + # single commit; made against a register that is not the published one, each + # of those rewrites is a conflict for `commit_push`'s rebase to resolve, and + # the one it cannot resolve costs the whole migration its atomicity. + log_sync + if [ "$NO_GIT" != 1 ] && have_remote_ref; then + msc_behind="$(git -C "$LANES_REPO" rev-list --count "HEAD..origin/$LANES_BRANCH" 2>/dev/null || printf '')" + case "$msc_behind" in + '' | 0) : ;; + *) die "this checkout is $msc_behind commit(s) behind origin/$LANES_BRANCH. The migration rewrites EVERY row and every lane's log in ONE commit, so it is made against the published register or not at all. Pull first — \`git -C $LANES_REPO pull --rebase\` — and re-run. Nothing was written." 2 ;; + esac + fi + refuse_dirty_checkout "migrate-state-cells" "$LANES_PATH" + + # THE MUTEX COMES BEFORE THE SCAN, NOT BETWEEN THE SCAN AND THE WRITE (Copilot + # round 2 on openRepoTools#82). This act reads every row's LINE NUMBER and its + # cell, and then rewrites those lines BY NUMBER: a peer's `add-row` or + # `replace-in-row` landing in this checkout between the two moves the lines + # under it, and `replace_line` then rewrites the wrong row — its one-line proof + # holds for the line it was given, not for the row a person meant. So the scan + # and the write happen inside ONE hold of the lock. + # + # THE DRY RUN TAKES NO LOCK AT ALL. It writes nothing, so a row that moves + # under it costs a report one line of accuracy and nothing else — and a read + # that holds the estate's one register mutex for the seconds this scan takes + # is a read that blocks every lane's write to say what it would have done. + [ "$msc_do" = 1 ] && acquire_lock + + # TWO ROWS FOR ONE LANE UNDER TWO CASES ARE 15(d)'s HAND MERGE, and both of + # them are skipped rather than migrated into one log under a name that means + # two rows. + msc_dups="$(awk ' + substr($0,1,1) == "|" { + p1 = index($0, "`"); if (p1 == 0) next + r = substr($0, p1 + 1); p2 = index(r, "`"); if (p2 == 0) next + print tolower(substr(r, 1, p2 - 1)) + }' "$LANES_FILE" | LC_ALL=C sort | LC_ALL=C uniq -d)" + + msc_rows=0; msc_ok=0; msc_lines=0; msc_noted=0; msc_ruled=0; msc_skipped=0 + msc_phrase=0; msc_plain=0; msc_before=0; msc_after=0 + + while IFS="$(printf '\t')" read -r msc_n msc_lane; do + [ -n "${msc_n:-}" ] || continue + msc_rows=$((msc_rows + 1)) + msc_why="" + case "$msc_lane" in + '' | *[!A-Za-z0-9._-]* | .* | -*) msc_why="'$msc_lane' is not a lane name (letters, digits, . _ -), so it names no log this writer would create" ;; + esac + if [ -z "$msc_why" ] && [ -n "$msc_dups" ]; then + msc_low="$(lc "$msc_lane")" + while IFS= read -r msc_d; do + [ -n "$msc_d" ] || continue + [ "$msc_d" = "$msc_low" ] && msc_why="the register holds more than one row whose lane name is $msc_lane under some case — one lane is ONE lane (Amendment 15), and the two are merged by hand into one row (15(d)) before either is migrated" + done <<EOF +$msc_dups +EOF + fi + msc_row="$(sed -n -e "${msc_n}p" "$LANES_FILE")" + if [ -z "$msc_why" ]; then + msc_rc=0; row_split_state_cell "$msc_row" || msc_rc=$? + case "$msc_rc" in + 0) : ;; + 2) msc_why="its row carries $(row_sep_count "$msc_row") ' | ' separators where a seven-column row carries 6, so which text is the state cell is not knowable from the row (escape the literal pipe inside a cell as \\| by hand, commit it, and re-run)" ;; + *) msc_why="its row does not open with '|' and end with '|'" ;; + esac + fi + if [ -z "$msc_why" ]; then + mig_trim "$RSS_CELL"; msc_cell="$MIG_TRIM" + msc_head="$RSS_HEAD"; msc_tail="$RSS_TAIL" + # TWO WAYS A CELL HOLDS NO HISTORY, AND THEY ARE NOT THE SAME FACT + # (Copilot round 1 on openRepoTools#82). A cell that is already + # `<STATE> · <UTC> · <one line>` is in clause (a)'s shape and there is + # nothing to do. A cell holding ONE WORD — `ACTIVE`, `LIVE`, the bare + # states this register is full of — has no diary to move either, so this + # act leaves it alone, but it is NOT in the shape: the next + # `set-row-state` on that lane puts it there, and reporting the two as one + # number would say the register was compliant when a third of it is not. + case "$msc_cell" in + *' · '*) : ;; + *) msc_plain=$((msc_plain + 1)); continue ;; + esac + if mig_cell_is_phrase "$msc_cell"; then msc_phrase=$((msc_phrase + 1)); continue; fi + # THE SEAM (Brett Heap's ruling of 2026-10-04; Copilot round 2 on + # openRepoTools#97). This act rewrites a row's state cell and appends to + # its lane's log, so a lane the managed ledger has enrolled is not a row it + # may take — and the historical shorthand `MANAGED OWNER · <token>` holds + # ONE ` · `, so `mig_cell_is_phrase` does not recognise it and, unasked, + # the row was planned as a diary and rewritten to `MIGRATED · …`. + # ONE SUCH ROW REFUSES THE WHOLE MIGRATION, exactly as one refuses the + # whole of Amendment 19's sweep: clause (e) makes this act ONE commit, and + # a register migrated but for its managed rows is not that commit. Asked + # HERE and not at the top of the loop: a row skipped above (15(d)'s + # duplicate pair, a row that is not seven columns, one word, the phrase) is + # never rewritten and has nothing to refuse, and asking first would turn + # today's skips into refusals. Both modes ask, because the dry run reports + # exactly what the act would do. `die` releases the lock the act holds. + # The seam reads this checkout's row as well as the published one, and + # this checkout's row is the one the migration rewrites. + managed_seam_refuse "$msc_lane" "migrate-state-cells (the WHOLE migration, which Amendment 13(e) makes one commit)" + fi + if [ -z "$msc_why" ]; then + # The row's own columns, walked from the LEFT out of the head this split + # already proved reassembles: 3 is `<workstation> / <env> / <user>` and 4 + # is `started (UTC)`. + msc_h="${msc_head#| }" + msc_h="${msc_h#* | }" # past the lane cell + msc_h="${msc_h#* | }" # past the session cell + msc_c3="${msc_h%% | *}" # workstation / env / user + msc_c4="${msc_h#* | }"; msc_c4="${msc_c4%% | *}" # started (UTC) + msc_ws="$(mig_row_ws "$msc_c3")" + msc_started="$(mig_started_utc "$msc_c4")" + [ -n "$msc_started" ] || msc_started="$msc_utc" + msc_uuid="" + if row_split_session_cell "$msc_row"; then + msc_uuid="$(printf '%s\n' "$RSC_CELL" | uuids_in_cell | tail -n1)" + fi + [ -n "$msc_uuid" ] || + msc_why="its session cell holds no transcript uuid, and the session field of an event line is a transcript uuid and only that (Amendment 7(b)) — a migrated line naming 'unknown' there is wrong for ever in an append-only file. Read the cell and set the row by hand instead: lanes-edit.sh set-row-state $msc_lane \"<STATE> · <one line>\"" + fi + if [ -z "$msc_why" ]; then + # The lane's log, found whatever its case, and never created beside one + # this checkout has not pulled (Amendment 15, `ensure_log`'s own guard). + msc_pub=""; msc_prc=0 + msc_pub="$(log_path_ci "$msc_lane")" || msc_prc=$? + if [ "$msc_prc" != 0 ]; then + msc_why="its object log is published twice under names that differ only by case (above) — 15(d)'s hand merge" + else + msc_loc="$(log_files_named_ci "$msc_lane")" + msc_ln="$(printf '%s' "$msc_loc" | grep -c . || :)" + if [ "$msc_ln" -gt 1 ]; then + msc_why="this checkout holds $msc_ln object logs for it whose names differ only by case — 15(d)'s hand merge" + elif [ "$msc_ln" = 1 ]; then + msc_lf="$msc_loc"; msc_rel="${LANES_LOG_PREFIX}${msc_loc##*/}" + if [ "${msc_rel##*/}" != "${msc_pub##*/}" ]; then + msc_why="its object log is published as $msc_pub while this checkout has ${msc_rel##*/} — a case-only rename whose commit never landed. Pull first, or merge them (15(d))" + elif [ "$NO_GIT" != 1 ] && ! git -C "$LANES_REPO" ls-files --error-unmatch -- "$msc_rel" >/dev/null 2>&1; then + # AN UNTRACKED LOG IS SOMEBODY'S UNCOMMITTED WORK, AND THIS ACT WOULD + # COMMIT IT (Copilot round 2 on openRepoTools#82). A log that is + # TRACKED and dirty is already refused for the whole run by + # `refuse_dirty_checkout` above, which exempts the register alone and + # reads staged and unstaged alike; an untracked file is in neither of + # those lists, so appending to it here would put a peer's first lines + # into this migration's one commit under this migration's message. + # The row is skipped and the file named, exactly as the other five + # reasons are, and its cell keeps every character. + msc_why="its object log ${msc_rel} exists here but is NOT TRACKED — somebody's uncommitted work, which this act would commit inside the migration's own commit. Commit it first (\`git -C $LANES_REPO commit -m \"<what it is>\" -- $msc_rel\`) and re-run" + fi + else + msc_rel="$msc_pub"; msc_lf="$LANES_LOG_DIR/${msc_pub##*/}" + fi + fi + fi + if [ -n "$msc_why" ]; then + msc_skipped=$((msc_skipped + 1)) + printf ' %-26s %s\n' "$msc_lane" "$msc_why" >> "$msc_tmp/skips" + continue + fi + + # THE ENTRIES, IN CELL ORDER — which is oldest first, because the cell grew + # by appending. + # + # SPLIT BY `awk`, IN ONE PASS, and not by `${cell#* · }` in a loop. That + # expansion is the shortest-prefix form: bash walks every prefix length in + # turn, so its cost is quadratic in the DISTANCE TO THE MATCH — cheap while + # the entries are short and ruinous for one long entry near the end of a + # 94,341-character cell. Measured on this bash, 2026-09-15: six of those + # expansions over a 95,000-character string with no match at all take 16 + # seconds. One pass of `awk` is linear in the cell whatever the entries look + # like. A register row is ONE LINE, so an entry can hold no newline and a + # line of this stream is exactly an entry. + : > "$msc_tmp/block/$msc_n" + msc_en=0; msc_last="" + while IFS= read -r msc_e; do + mig_trim "$msc_e"; msc_e="$MIG_TRIM" + if [ -n "$msc_e" ]; then + msc_last="$msc_e" + mig_lead_utc "$msc_e"; msc_eutc="$MIG_LEAD_UTC" + msc_text="$msc_e" + if [ -n "$msc_eutc" ]; then + msc_t2="${msc_e#"$msc_eutc"}"; mig_trim "$msc_t2"; msc_t2="$MIG_TRIM" + # AN ENTRY THAT IS NOTHING BUT A TIMESTAMP KEEPS IT AS ITS TEXT: a + # line whose free text is empty is a line with a dangling ` — `, and + # this log is never rewritten. + [ -n "$msc_t2" ] && msc_text="$msc_t2" + else + msc_eutc="$msc_started" + fi + if mig_is_ruling "$msc_e"; then msc_verb=RULED; msc_ruled=$((msc_ruled + 1)) + else msc_verb=NOTED; msc_noted=$((msc_noted + 1)); fi + printf '%s — lane %s, session %s@%s, %s, lane:%s — %s\n' \ + "$msc_verb" "$msc_lane" "$msc_uuid" "$msc_ws" "$msc_eutc" "$msc_lane" "$msc_text" >> "$msc_tmp/block/$msc_n" + msc_en=$((msc_en + 1)); msc_lines=$((msc_lines + 1)) + fi + done <<EOF +$(printf '%s\n' "$msc_cell" | awk '{ gsub(/ · /, "\n"); print }') +EOF + if [ "$msc_en" = 0 ]; then + msc_plain=$((msc_plain + 1)); rm -f -- "$msc_tmp/block/$msc_n"; continue + fi + + # THE CELL IT BECOMES — clause (e): the state the LAST entry's leading verb + # names, where that verb is one of clause (a)'s, else `MIGRATED`. + msc_state="$(mig_lead_state "$msc_last")" + [ -n "$msc_state" ] || msc_state=MIGRATED + # THE CAP IS THE CAP HERE TOO (Copilot round 5 on openRepoTools#82). This + # builds the cell directly rather than through `set-row-state`, so nothing + # else enforces ratified decision O1's 240 characters on the line — and the + # line carries a PATH whose length is the lane's name: `check_lane_name` + # bounds a name's characters and not its length, so a lane named with 216 of + # them would be migrated to a cell the writer itself would refuse. Cut back + # to the last space, for the reason the three commands' `cut_to_line` gives: + # `${s:0:n}` counts bytes wherever the locale is not a UTF-8 one. + msc_line="history in $msc_rel" + if [ "${#msc_line}" -gt 230 ]; then + msc_line="${msc_line:0:230}" + case "$msc_line" in *' '*) msc_line="${msc_line% *}" ;; esac + msc_line="$msc_line ..." + fi + msc_new="$msc_state · $msc_utc · $msc_line" + printf '%s%s%s%s%s%s%s\n' "$msc_n" "$US" "$msc_new" "$US" "$msc_head" "$US" "$msc_tail" >> "$msc_tmp/cells" + printf '%s%s%s%s%s\n' "$msc_n" "$US" "$msc_lf" "$US" "$msc_rel" >> "$msc_tmp/targets" + printf ' %-26s %4s entries %7s chars → %s\n' \ + "$msc_lane" "$msc_en" "${#msc_cell}" "$msc_new" >> "$msc_tmp/report" + msc_ok=$((msc_ok + 1)) + msc_before=$((msc_before + ${#msc_cell})); msc_after=$((msc_after + ${#msc_new})) + done <<EOF +$(awk 'substr($0,1,1) == "|" { + p1 = index($0, "`"); if (p1 == 0) next + r = substr($0, p1 + 1); p2 = index(r, "`"); if (p2 == 0) next + printf "%d\t%s\n", NR, substr(r, 1, p2 - 1) + }' "$LANES_FILE") +EOF + + # ------------------------------------------------------------- the report + printf 'migrate-state-cells — %s (lane-collision-protocol Amendment 13(e))\n' \ + "$( [ "$msc_do" = 1 ] && printf 'THE ACT' || printf 'DRY RUN, nothing is written' )" + printf ' register : %s\n' "$LANES_FILE" + printf ' archive : %s\n' "$msc_arch_rel" + printf ' rows : %s read · %s to migrate · %s already the phrase · %s one word, no history · %s skipped\n' \ + "$msc_rows" "$msc_ok" "$msc_phrase" "$msc_plain" "$msc_skipped" + if [ "$msc_ok" -gt 0 ]; then + printf '\n lane entries cell now → the phrase it becomes\n' + cat -- "$msc_tmp/report" + fi + if [ "$msc_skipped" -gt 0 ]; then + printf '\n SKIPPED — nothing is written for these rows and their cells keep every\n' + printf ' character, so a re-run after each is settled migrates exactly it:\n' + cat -- "$msc_tmp/skips" + fi + if [ "$msc_plain" -gt 0 ]; then + printf '\n %s row(s) hold ONE WORD and no history (`ACTIVE`, `LIVE`, …). This act leaves\n' "$msc_plain" + printf ' them exactly as they are — there is no diary in them to move — and they are NOT\n' + printf ' yet `<STATE> · <UTC> · <one line>`: the next set-row-state on each writes it.\n' + fi + printf '\n log lines: %s (%s NOTED, %s RULED) into %s log(s)\n' "$msc_lines" "$msc_noted" "$msc_ruled" "$msc_ok" + printf ' state cells: %s characters → %s\n' "$msc_before" "$msc_after" + + # THE REFUSAL CLAUSE (e) ASKS FOR, and it is the same answer in both modes: + # a register whose cells hold no ` · ` entry has already been migrated (or + # never needed it), and a second run is a no-op that says so. + if [ "$msc_ok" = 0 ]; then + msc_left="" + [ "$msc_skipped" -gt 0 ] && msc_left=" The $msc_skipped row(s) listed above still hold theirs and are the ones this act cannot take; each is settled by the line beside it, and a re-run then migrates exactly those." + rm -rf -- "$msc_tmp" + die "no cell holds a ' · ' entry this act can migrate: $msc_phrase row(s) are already in Amendment 13(a)'s shape and $msc_plain hold ONE WORD and no history, which this act leaves alone — the next \`set-row-state\` on each of those lanes writes it as the phrase.$msc_left The migration is ONE act and this was not it — nothing was written." 2 + fi + if [ "$msc_do" != 1 ]; then + printf '\n DRY RUN — nothing was written. Make it the one act with: lanes-edit.sh migrate-state-cells --yes\n' + printf ' (Amendment 13(e): one commit carrying the archive, the logs and the register.)\n' + rm -rf -- "$msc_tmp" + return 0 + fi + + # --------------------------------------------------------------- the write + # + # THE LOCK IS ALREADY HELD — it was taken BEFORE the scan, so the line numbers + # rewritten below are the ones this invocation read (Copilot round 2 on + # openRepoTools#82). + # + # AND A PEER'S REGISTER EDIT IS CAPTURED HERE, AFTER EVERY REFUSAL AND SKIP OF + # THE SCAN AND BEFORE THE FIRST BYTE IS WRITTEN (openRepoTools#157 item 4b). + # Captured before the scan, a refusal in it — the seam's, or the "nothing to + # migrate" one — left a `LANES(pre-existing@…)` commit behind: a refusal that + # wrote, which `capture_register_edit` names as the one thing it must never + # be. The capture commits the file's bytes and changes none of them, so what + # the scan read is what is committed, as it was. `retire_rows` and + # `archive_rows` capture at their writes for the same reason. + handle_preexisting "$LANES_PATH" + # + # EVERYTHING BELOW IS ONE COMMIT OR NONE. The archive, the appended logs and + # the rewritten rows are made on disk first and published by the single + # `commit_push` at the end, so a refusal in the middle of them — a log whose + # append could not be proved, a row whose rewrite moved more than one line — + # leaves this checkout DIRTY and the register unpublished, which is what + # `git status` then shows and `git checkout -- lanes` undoes whole. Nothing is + # half-published, because the commit is the only thing that publishes; and a + # re-run on a checkout still holding that half is REFUSED by + # `refuse_dirty_checkout` above rather than made twice. + mkdir -p -- "$LANES_DIR/archive" || die "could not create $LANES_DIR/archive — the archive is written BEFORE anything else changes, so nothing has been" 6 + # A `>` REDIRECT, WHICH FOLLOWS A SYMLINK, and the source read whole first: + # this copy is the file's state before this act and it is one of the three + # places clause (e) keeps it. + cat -- "$LANES_FILE" > "$msc_arch" || die "could not write the archive $msc_arch — nothing else has been touched" 6 + cmp -s -- "$LANES_FILE" "$msc_arch" || die "the archive $msc_arch is not byte for byte the register it was copied from; nothing else has been touched" 5 + note "archive written: $msc_arch_rel" + reg_wrote "$msc_arch_rel (the register as it was)" + + msc_paths=("$LANES_PATH" "$msc_arch_rel") + while IFS="$US" read -r msc_n msc_lf msc_rel; do + [ -n "${msc_n:-}" ] || continue + if [ ! -f "$msc_lf" ]; then + mkdir -p -- "$LANES_LOG_DIR" + msc_base="${msc_lf##*/}" + printf '# lane %s — object log (lane-collision-protocol Amendment 7)\n' "${msc_base%.md}" > "$msc_lf" + note "created $msc_lf" + fi + append_text_block "$msc_lf" "$(cat -- "$msc_tmp/block/$msc_n")" + msc_paths+=("$msc_rel") + done <<EOF +$(cat -- "$msc_tmp/targets") +EOF + [ "${#msc_paths[@]}" -le 2 ] || reg_wrote "$(( ${#msc_paths[@]} - 2 )) lanes' logs under $LANES_LOG_PREFIX (their migrated lines)" + + msc_rows=0 + while IFS="$US" read -r msc_n msc_new msc_head msc_tail; do + [ -n "${msc_n:-}" ] || continue + replace_line "$msc_n" "$msc_head$msc_new $msc_tail" + msc_rows=$((msc_rows + 1)) + [ "$msc_rows" != 1 ] || reg_wrote "$LANES_PATH (the state cells rewritten before this one)" + done <<EOF +$(cat -- "$msc_tmp/cells") +EOF + + msc_msg="LANES(migrate@$WS): Amendment 13(e) — $msc_ok state cells become one phrase; $msc_lines lines ($msc_noted NOTED, $msc_ruled RULED) into the lanes' own logs; pre-migration register archived" + commit_push "$msc_msg" "${msc_paths[@]}" + msc_rc=$? + release_lock + # THE STAGING GOES ON THE WAY OUT, on both paths: this directory holds a block + # of log lines per migrated lane, and on the live register that is 2,206 lines + # (Copilot round 1 on openRepoTools#82). A `die` on the way here keeps it, like + # every other refused write in this file. + rm -rf -- "$msc_tmp" + return "$msc_rc" +} + +# ------------------------------------- the restart intent (openRepoTools#94) +# +# WHY THIS IS A FILE AND NOT AN ENVIRONMENT VARIABLE, measured on Eagle +# 2026-09-15T20:59Z and filed as `opensoft/openRepoTools#94`. `/ctx` respawned +# its own pane with `LANE_START_FRESH=1 … lane openRepoTools-3` and what came +# up was `claude --name openRepoTools-3 --resume <the uuid it had just paused>`. +# `lane-start` was not at fault — its `(( ! fresh ))` gates were in the +# installed copy and are in this tree — and neither was `lane`, which `exec`s. +# The launcher is: `claude-profile` re-creates the child through tmux, and its +# own comment states the rule this estate now has to build around — +# +# "`tmux new-session` hands the command the SERVER's environment, not this +# client's, so a variable the operator exported in their own shell reaches +# the child only if it is written into the command string" +# +# — which is why it threads six values explicitly and why a seventh nobody +# thought to thread is simply GONE. The defect capture's session name, +# `claude-max-001-20260915205926-456327`, is that launcher's own +# `claude-<profile>-<timestamp>-<pid>` pattern, so this is what happened and not +# what might have. An ENVIRONMENT seam cannot cross a boundary another +# repository owns. A FILE can: the intent is written under the lane's own +# control root before the old process is killed, and every launch after it +# reads the same bytes whatever the environment did. +# +# THE CONTROL ROOT follows the same layout as the diagnostic lifecycle from +# openRepoTools#97. The restart helpers have their own namespace: their strict +# validation and private atomic writer must not be replaced by the diagnostic +# helpers. The intent sits beside lane-state.yaml without sharing its authority. + +LANE_RESTART_SCHEMA=1 + +# THE CONTROL ROOT — explicit override, retained intent, then creation rungs. +# 0 with a path, 8 with no rung, 1 for unknown or competing locations. +lane_restart_control_root() { # <lane> [<payload>] [<checkout hint>] + lcr_lane="${1-}"; lcr_pay="${2-}"; lcr_dir=""; lcr_par="" + lcr_record_root=""; lcr_projects_root=""; lcr_existing="" + [ -n "$lcr_lane" ] || return 8 + if [ -n "${LANES_LANE_STATE_ROOT:-}" ]; then + printf '%s/%s\n' "${LANES_LANE_STATE_ROOT%/}" "$lcr_lane" + return 0 + fi + [ -n "$lcr_pay" ] && lcr_dir="$(payload_subfield "$lcr_pay" dir)" + if [ -z "$lcr_dir" ]; then + lcr_dir="$(lane_payload_field "$lcr_lane" dir 2>/dev/null || :)" + fi + case "$lcr_dir" in + /*) lcr_par="${lcr_dir%/*}" ;; + *) lcr_par="" ;; + esac + if [ -n "$lcr_par" ]; then + lcr_record_root="$lcr_par/.lane-state/$lcr_lane" + lane_restart_root_ok "$lcr_record_root" || return 1 + [ -d "$lcr_par" ] || lcr_record_root="" + fi + if [ -n "${PROJECTS_ROOT:-}" ]; then + lcr_projects_root="${PROJECTS_ROOT%/}/.lane-state/$lcr_lane" + lane_restart_root_ok "$lcr_projects_root" || return 1 + [ -d "$PROJECTS_ROOT" ] || lcr_projects_root="" + fi + # PAUSED may first record a nested checkout after reservation. Existing + # intent authority stays at its physical location; validity is the reader's + # gate, never a reason to bypass an occupied path. Unknown ancestry refuses. + # Only directory aliases share an atomic replacement entry; separate leaf + # symlinks/hardlinks would split into two records on the next replacement. + for lcr_candidate in "$lcr_record_root" "$lcr_projects_root"; do + [ -n "$lcr_candidate" ] || continue + lcr_file="$lcr_candidate/restart-intent.yaml" + if [ -e "$lcr_file" ] || [ -L "$lcr_file" ]; then + if [ -n "$lcr_existing" ] && [ "$lcr_candidate" != "$lcr_existing" ] && + [ ! "$lcr_candidate" -ef "$lcr_existing" ]; then + note "lane $lcr_lane has distinct restart-intent locations in $lcr_existing and $lcr_candidate; reconcile these records before continuing. Nothing was written." + return 1 + fi + [ -n "$lcr_existing" ] || lcr_existing="$lcr_candidate" + fi + done + if [ -n "$lcr_existing" ]; then + printf '%s\n' "$lcr_existing" + return 0 + fi + if [ -n "$lcr_record_root" ]; then + printf '%s\n' "$lcr_record_root" + return 0 + fi + if [ -n "$lcr_projects_root" ]; then + printf '%s\n' "$lcr_projects_root" + return 0 + fi + # A checkout hint is a last resort, so reads cannot hide an intent that + # writers/status already placed under the established root rungs. + case "${3-}" in + /*) lcr_par="${3%/*}" + if [ -n "$lcr_par" ] && [ -d "$lcr_par" ]; then + printf '%s/.lane-state/%s\n' "$lcr_par" "$lcr_lane" + return 0 + fi ;; + esac + return 8 +} + +# ONE FIELD OUT OF ONE OF THESE FILES. They are flat `key: value` lines and +# nothing else — no nesting, no lists — so one `awk` reads every one of them +# and a malformed file answers empty rather than half a value. +lane_restart_sidecar_field() { # <file> <key> + [ -r "${1-}" ] || return 1 + awk -v k="${2-}" ' + BEGIN { k = k ": " } + substr($0, 1, length(k)) == k { + v = substr($0, length(k) + 1) + print v; exit }' "$1" +} + +# Diagnostic prose is bounded and flattened; launch identity is never normalized. +lane_restart_sidecar_value() { # <diagnostic value> + printf '%s' "${1-}" | LC_ALL=C tr '[:cntrl:]' ' ' +} + +lane_restart_value_ok() { # exact values must survive flat and tabular readers + # POSIX class matching also works in Bash 3.2; its ANSI-C range did not. + local LC_ALL=C + case "${1-}" in *[[:cntrl:]]*) return 1 ;; esac + return 0 +} + +# THE ATOMIC REPLACE. Written beside the target and renamed over it, so a +# reader never sees half a snapshot and a full disk leaves the old one intact. +lane_restart_sidecar_put() { # <file> ; the whole body on stdin + lsp_f="${1-}"; lsp_d="${lsp_f%/*}" + [ -n "$lsp_f" ] || return 1 + mkdir -p -- "$lsp_d" 2>/dev/null || return 1 + [ ! -d "$lsp_f" ] || return 1 + lsp_t="$(umask 077; mktemp "$lsp_d/.restart-intent.XXXXXX" 2>/dev/null)" || return 1 + [ -n "$lsp_t" ] || return 1 + cat > "$lsp_t" 2>/dev/null || { rm -f -- "$lsp_t" 2>/dev/null; return 1; } + lsp_bad="$(lane_restart_missing "$lsp_t" "$2")" || { rm -f -- "$lsp_t"; return 1; } + [ -z "$lsp_bad" ] || { rm -f -- "$lsp_t"; return 1; } + mv -- "$lsp_t" "$lsp_f" 2>/dev/null || { rm -f -- "$lsp_t" 2>/dev/null; return 1; } + return 0 +} + +# AN OPERATION ID: unique to one transition, and shaped like the manifest key +# every other sub-field of this estate is — letters, digits, `.`, `_`, `-` — so +# that it can be carried in a payload, a filename and a commit subject without +# a quoting rule of its own. There is no `uuidgen` on every workstation this +# runs on, and a timestamp with the pid and two `$RANDOM`s behind it is unique +# among the handfuls of transitions one lane takes in a day. +lane_restart_op_id() { + printf 'op-%s-%s-%s%s\n' "$(date -u +%Y%m%dT%H%M%SZ)" "$$" "$RANDOM" "$RANDOM" +} + +# THE FOUR STATES OF A RESTART, AND NOTHING ELSE IS ONE. +# pending the intent is written and the old process may still be alive; the +# pane has not been replaced, or has been and the supervisor has +# not claimed it yet. +# starting a supervisor has claimed this exact operation and launched. +# failed the launch did not reach readiness; the supervisor is still in +# the pane with the diagnostic and the retry. +# ready readiness was positively confirmed. A `ready` intent is HISTORY +# and authorises no launch, which is what makes an ordinary +# `lane <name>` after a successful `/ctx` an ordinary resume. +lane_restart_word_ok() { # <word> + case "${1-}" in preparing|pending|starting|failed|ready) return 0 ;; esac + return 1 +} + +# THE HANDOFF'S DIGEST. `shasum -a 256` is on macOS, `sha256sum` on Linux, and +# a workstation with neither answers `none` — which is an ANSWER and not a gap: +# the digest then cannot be COMPARED, and every reader below treats a `none` +# digest as *not checked here* rather than as *unchanged*. Never `cksum`: a +# 32-bit checksum is not a change detector for a file a person edits. +lane_handoff_digest() { # <file> + [ -r "${1-}" ] || { printf 'none\n'; return 0; } + if command -v sha256sum >/dev/null 2>&1; then + sha256sum -- "$1" 2>/dev/null | awk '{print $1; exit}' + elif command -v shasum >/dev/null 2>&1; then + shasum -a 256 -- "$1" 2>/dev/null | awk '{print $1; exit}' + else + printf 'none\n' + fi +} + +# THE INTENT, READ. `<key><TAB><value>` lines, which is what every caller here +# parses with one `awk`. 0 with the fields, 8 where the lane has no intent at +# all (the ordinary lane, and not a failure), 1 where the control root could +# not be derived. +# All schema-1 keys are mandatory; prepared_digest is an optional extension. +# One read validates presence and duplicate keys without per-field subprocesses. +lane_restart_missing() { # <file> <canonical lane> + awk -v lane="$2" ' + BEGIN { + n=split("schema lane state generation operation mode agent profile dir pane window handoff digest old_transcript new_transcript attempt workstation created updated reason", keys, " ") + for (i=1;i<=n;i++) allowed[keys[i]]=1 + allowed["prepared_digest"]=1 + } + { + if ($0 ~ /[[:cntrl:]]/ || $0 !~ /^[A-Za-z_]+: /) {bad["record"]=1; next} + k=$0; sub(/:.*/, "", k) + if (!(k in allowed)) {bad["unknown-key"]=1; next} + v=substr($0,length(k)+3) + seen[k]++; values[k]=v; if (v!="") good[k]=1 + } + END { + for (i=1;i<=n;i++) if (seen[keys[i]]!=1 || !good[keys[i]]) bad[keys[i]]=1 + if (values["lane"]!=lane) bad["lane"]=1 + if (values["generation"] !~ /^[0-9]+$/) bad["generation"]=1 + if (values["attempt"] !~ /^[0-9]+$/) bad["attempt"]=1 + n=split("operation mode agent profile old_transcript new_transcript", keys, " ") + for (i=1;i<=n;i++) if (values[keys[i]] !~ /^[A-Za-z0-9._-]+$/) bad[keys[i]]=1 + n=split("dir handoff", keys, " ") + for (i=1;i<=n;i++) if (values[keys[i]]!="none" && values[keys[i]] !~ /^\//) bad[keys[i]]=1 + n=split("digest prepared_digest", keys, " ") + for (i=1;i<=n;i++) if ((seen[keys[i]] && seen[keys[i]]!=1) || + (seen[keys[i]] && values[keys[i]]!="none" && (length(values[keys[i]])!=64 || values[keys[i]] !~ /^[0-9a-fA-F]+$/))) bad[keys[i]]=1 + for (k in bad) {printf "%s%s", sep, k; sep=" "} + } + ' "$1" +} + +lane_restart_root_ok() { # missing directories are allowed; unusable existing ancestors are not + lrro_path="$1" + while [ -n "$lrro_path" ]; do + if [ -e "$lrro_path" ] || [ -L "$lrro_path" ]; then + [ -d "$lrro_path" ] && [ -r "$lrro_path" ] && [ -x "$lrro_path" ] || return 1 + fi + lrro_parent="$(dirname -- "$lrro_path")" || return 1 + [ "$lrro_parent" != "$lrro_path" ] || break + lrro_path="$lrro_parent" + done + return 0 +} + +lane_restart_read() { # <lane> [<resolved checkout hint>] + lrr_lane="${1-}"; lrr_root=""; lrr_rc=0 + lrr_root="$(lane_restart_control_root "$lrr_lane" "" "${2-}")" || lrr_rc=$? + [ "$lrr_rc" = 0 ] || return 1 + lane_restart_root_ok "$lrr_root" || return 1 + lrr_f="$lrr_root/restart-intent.yaml" + [ -e "$lrr_f" ] || [ -L "$lrr_f" ] || return 8 + [ -f "$lrr_f" ] && [ -r "$lrr_f" ] || return 1 + lrr_schema="$(lane_restart_sidecar_field "$lrr_f" schema)" || return 1 + # AN UNKNOWN SCHEMA FAILS CLOSED, exactly as `lane-state` does for the same + # reason: a newer tooling's intent read by an older reader must not be + # reported as a launch this reader knows how to make. + case "$lrr_schema" in + "$LANE_RESTART_SCHEMA") : ;; + *) printf 'state\tUNKNOWN-SCHEMA\n'; printf 'schema\t%s\n' "${lrr_schema:-<none>}" + printf 'file\t%s\n' "$lrr_f"; return 0 ;; + esac + # AN ACTIVE INTENT MISSING A FACT A LAUNCH IS FENCED ON IS NOT A READABLE ONE + # (Copilot round 2 on openRepoTools#121). The schema check above is the whole + # of what this read used to verify, so a `pending` record carrying an + # operation and a mode and nothing else came back with empty values — and + # empty is exactly what every comparison downstream treats as *cannot + # compare*: `pane_agrees` returns agreement on an empty side, the digest check + # skips, and the launch goes ahead with none of the three checks those fields + # exist for. That is a silent launch from a record nobody wrote. + # + # PRESENT AND NOT EMPTY, WHICH IS NOT THE SAME AS *NOT `none`*. `none` IS an + # answer here — a workstation with neither `sha256sum` nor `shasum` records + # `digest: none`, and the writer writes `none` for every empty field on every + # transition — so what is checked is that the KEY IS THERE AT ALL, which is + # true of everything this tooling has ever written and false of a record that + # was truncated or edited by hand. + # + # `failed` ALSO NEEDS THE LAUNCH FACTS: it authorizes a supervised retry. + # Incomplete records remain readable diagnostics, never launch authority. + lrr_state="$(lane_restart_sidecar_field "$lrr_f" state)" || return 1 + if ! lane_restart_word_ok "$lrr_state"; then + printf 'state\tUNKNOWN-STATE\nfile\t%s\n' "$lrr_f" + return 0 + fi + lrr_missing="$(lane_restart_missing "$lrr_f" "$lrr_lane")" || return 1 + if [ -n "$lrr_missing" ]; then + printf 'state\tINCOMPLETE\nintended_state\t%s\nmissing\t%s\nfile\t%s\n' "$lrr_state" "$lrr_missing" "$lrr_f" + return 0 + fi + for lrr_num in generation attempt; do + lrr_value="$(lane_restart_sidecar_field "$lrr_f" "$lrr_num")" || return 1 + case "$lrr_value" in ''|*[!0-9]*) + printf 'state\tINCOMPLETE\nmissing\t%s\nfile\t%s\n' "$lrr_num" "$lrr_f" + return 0 ;; + esac + done + for lrr_k in state generation operation mode lane agent profile dir pane window \ + handoff digest prepared_digest old_transcript new_transcript attempt workstation \ + created updated reason; do + printf '%s\t%s\n' "$lrr_k" "$(lane_restart_sidecar_field "$lrr_f" "$lrr_k")" + done + printf 'file\t%s\n' "$lrr_f" + return 0 +} + +# One field of it, for the callers that want exactly one. +lane_restart_of() { # <lane> <key> + lro_out=""; lro_rc=0 + lro_out="$(lane_restart_read "${1-}")" || lro_rc=$? + [ "$lro_rc" = 0 ] || return "$lro_rc" + printf '%s\n' "$lro_out" | awk -F'\t' -v k="${2-}" '$1 == k { print $2; exit }' +} + +# THE INTENT, WRITTEN — the ONE writer, and every caller reaches it through +# `set-restart-intent`. An empty field is written as `none`, which is an ANSWER +# and not a gap, on the same argument Amendment 17(b) gives its `transcript` +# sub-field. +# +# THERE IS NO CREDENTIAL FIELD AND THERE IS NO PLACE FOR ONE. The fields are a +# lane, a generation, an operation, two transcript ids, an agent, a PROFILE +# NAME (a manifest key, never a token), a directory, a pane, a handoff path, +# its digest, an attempt count and a bounded reason. A caller that had a secret +# in hand would have nowhere here to put it. +lane_restart_put() { # <root> <lane> <state> <gen> <op> <mode> <agent> <profile> <dir> <pane> <window> <handoff> <digest> <old> <new> <attempt> <reason> <created> + lrw_root="$1"; lrw_lane="$2"; lrw_state="$3"; lrw_gen="$4"; lrw_op="$5" + lrw_mode="$6"; lrw_agent="$7"; lrw_prof="$8"; lrw_dir="$9"; shift 9 + lrw_pane="$1"; lrw_win="$2"; lrw_hf="$3"; lrw_dig="$4"; lrw_old="$5" + lrw_new="$6"; lrw_att="$7"; lrw_reason="$8"; lrw_created="$9"; lrw_prepared="${10-}" + for lrw_value in "$lrw_lane" "$lrw_state" "$lrw_gen" "$lrw_op" "$lrw_mode" \ + "$lrw_agent" "$lrw_prof" "$lrw_dir" "$lrw_pane" "$lrw_win" "$lrw_hf" \ + "$lrw_dig" "$lrw_old" "$lrw_new" "$lrw_att" "$lrw_created" "$lrw_prepared" "${WS:-none}"; do + lane_restart_value_ok "$lrw_value" || return 1 + done + # BOUNDED DIAGNOSTICS (design decision 3). A launcher that died printing a + # megabyte of stderr must not turn the lane's own control file into that + # megabyte, and the field is one LINE by construction. + lrw_reason="$(lane_restart_sidecar_value "$lrw_reason")" + if [ "${#lrw_reason}" -gt 400 ]; then + lrw_reason="$(printf '%s' "$lrw_reason" | cut -c1-400)… (truncated)" + fi + { printf 'schema: %s\n' "$LANE_RESTART_SCHEMA" + printf 'lane: %s\n' "$lrw_lane" + printf 'state: %s\n' "$lrw_state" + printf 'generation: %s\n' "${lrw_gen:-0}" + printf 'operation: %s\n' "${lrw_op:-none}" + printf 'mode: %s\n' "${lrw_mode:-fresh-from-handoff}" + printf 'agent: %s\n' "${lrw_agent:-none}" + printf 'profile: %s\n' "${lrw_prof:-none}" + printf 'dir: %s\n' "${lrw_dir:-none}" + printf 'pane: %s\n' "${lrw_pane:-none}" + printf 'window: %s\n' "${lrw_win:-none}" + printf 'handoff: %s\n' "${lrw_hf:-none}" + printf 'digest: %s\n' "${lrw_dig:-none}" + printf 'prepared_digest: %s\n' "${lrw_prepared:-none}" + printf 'old_transcript: %s\n' "${lrw_old:-none}" + printf 'new_transcript: %s\n' "${lrw_new:-none}" + printf 'attempt: %s\n' "${lrw_att:-0}" + printf 'workstation: %s\n' "${WS:-none}" + printf 'created: %s\n' "${lrw_created:-$(utc_now)}" + printf 'updated: %s\n' "$(utc_now)" + printf 'reason: %s\n' "${lrw_reason:-none}" + } | lane_restart_sidecar_put "$lrw_root/restart-intent.yaml" "$lrw_lane" +} + +# ------------------- AMENDMENT 19(c): THE SWEEP, ONE COMMIT OR NONE --------- +# +# `lane-end --retire-dormant <repo>` is the word a person types, the dry run +# they read and the `--yes` they answer with; THIS is the write underneath it. +# It is a verb of its own because the sweep touches many rows and many logs and +# is ONE commit — the shape `migrate-state-cells` has one screen up, for the +# same reason: a half-published sweep is a register whose rows and whose logs +# disagree about which lanes are finished. +# +# WHAT IT WRITES PER LANE, and clause (c) spells it out character by character: +# `lanes/log/<lane>.md` gains ONE line — +# RETIRED — lane <lane>, session <uuid>@<ws>, <UTC>, lane:<lane> +# → retired-dormant by lane <writer>; reason <why>; was: <the cell's head> +# and the row's state cell becomes `RETIRED · <UTC> · <why>; was: <head>`. +# +# THE PAYLOAD ON A `RETIRED` IS THIS AMENDMENT'S OWN. Amendment 7(b) gives +# `RETIRED` no payload and Amendment 11 clause (c) keeps it that way — which is +# why `lane-end`'s fork retire is a DOOR that writes nothing at all. Amendment +# 19 is later, ratified as drafted, and spells this line out in full: the row's +# own last words are carried into the log so that nothing the row said is lost +# when the row stops saying it. That is the whole of the exception, and it is +# this line and no other. +# +# THE CELL IS AMENDMENT 13(a)'s PHRASE, NOT CLAUSE (c)'s LITERAL TEXT. Clause +# (c) writes the cell as `RETIRED <UTC> · <why> · was: <head>` — four parts +# where 13(a)'s cell has three, and a first word of `RETIRED <UTC>`, which is a +# state no reader of Rule 6 or of the listing knows. The phrase that carries the +# same four facts under the grammar every other writer obeys is +# `RETIRED · <UTC> · <why>; was: <head>`, and it goes through `row_state_check` +# — the gate `set-row-state` uses — so the 240-character cap, the `|` and the +# second ` · ` are refused here exactly as they are there. The `|` a legacy cell +# may carry is replaced by `/` in the ROW (it would forge a cell boundary) and +# kept VERBATIM in the log line, which is not a table. +# +# THE THREE REFUSALS ARE CLAUSE (c)'s: a lane a live session holds on this +# workstation, a row whose log already carries a lane-kind line other than +# `ENDED`/`RETIRED` (a parked lane is not dormant), and — in `lane-end`, which +# is the word that finds them — a repository with no dormant row at all. +# ANY ONE OF THEM REFUSES THE WHOLE RUN, before a byte is written: this is one +# commit, so it is one decision. +retire_rows() { # <lane>… [--reason "<why>"] [--writer <lane>] + rr_reason=""; rr_writer="${LANES_LANE:-}"; rr_lanes="" + while [ $# -gt 0 ]; do + case "$1" in + # A FLAG IS NOT A VALUE (Copilot round 1 on #93). `--reason --writer x` + # took `--writer` as the reason and swept with it, and the writer the + # caller named was never read — a malformed line that RAN. A value + # beginning with `-` is refused and the `=` spelling named for the reason + # that legitimately starts with one. + --reason) case "${2-}" in '' | -*) die "--reason needs the words that say why, and '${2-}' is a flag — so the reason was left out. Spell a reason that really begins with a dash as --reason=<why>." 2 ;; esac + rr_reason="$2"; shift 2 ;; + --reason=*) rr_reason="${1#--reason=}"; [ -n "$rr_reason" ] || die "--reason needs the words that say why" 2; shift ;; + --writer) case "${2-}" in '' | -*) die "--writer needs the lane doing the sweeping, and '${2-}' is a flag — so the lane was left out." 2 ;; esac + rr_writer="$2"; shift 2 ;; + --writer=*) rr_writer="${1#--writer=}"; [ -n "$rr_writer" ] || die "--writer needs the lane doing the sweeping" 2; shift ;; + --) shift ;; + -*) die "unknown option '$1' for retire-rows (usage: retire-rows <lane>… [--reason \"<why>\"] [--writer <lane>])" 2 ;; + *) check_lane_name "$1"; rr_lanes="$rr_lanes $1"; shift ;; + esac + done + [ -n "$rr_lanes" ] || + die "usage: retire-rows <lane>… [--reason \"<why>\"] [--writer <lane>] + The lanes are DORMANT rows — a row with no object log and no live session + (Amendment 19(a)). The word that FINDS them, shows the dry run and asks for + the person's --yes is: lane-end --retire-dormant <repo>" 2 + [ -n "$rr_reason" ] || rr_reason="dormant row swept under Amendment 19(c)" + [ -n "$rr_writer" ] || + die "retire-rows needs the lane doing the sweeping: LANES_LANE=<lane> lanes-edit.sh retire-rows … (or --writer <lane>). Every line it writes carries that lane's own transcript uuid in its session field, and a session field that is anything else is wrong for ever in an append-only log (Amendment 7(b))." 2 + check_lane_name "$rr_writer" + # THE REASON IS CHECKED ONCE, HERE, AND NEVER PER ROW. It goes into every cell + # this sweep rewrites, so a `|` or a second ` · ` in it is a refusal of the + # ARGUMENT, named as one — rather than `row_state_check` dying half-way down + # the scan with a message about a cell the caller never wrote. The cap is + # lower than the cell's own, because the row's last words go in beside it. + case "$rr_reason" in + *'|'*) die "--reason may not contain '|': it would forge a cell boundary in every row this sweep rewrites. Got: '$rr_reason'" 2 ;; + *' · '*) die "--reason may not contain ' · ': that separator is what divides the state cell's three parts (Amendment 13(a)), and a second one reads back as a fourth part. Use a semicolon. Got: '$rr_reason'" 2 ;; + esac + if [ "${rr_reason//[$'\n\r']/}" != "$rr_reason" ]; then + die "--reason is ONE line: a newline in it would split a row in two and every row after it would be read as a lane" 2 + fi + if [ "${rr_reason//$US/}" != "$rr_reason" ]; then + die "--reason may not contain the internal field separator: it would corrupt the sweep plan before any row is written" 2 + fi + [ "${#rr_reason}" -le 180 ] || + die "--reason is ${#rr_reason} characters. The cell's whole line is capped at $ROW_STATE_CAP (Amendment 13, ratified decision O1) and the row's OWN last words go in beside it, so a reason longer than 180 leaves nothing of them. Shorten it — the long version belongs in the lane's log." 2 + + # R30 — THE FETCH FIRST, AND A CHECKOUT THAT IS BEHIND IS REFUSED, for the + # reason the migration gives: this act rewrites several rows and appends to + # several logs in ONE commit, and made against a register that is not the + # published one each of those is a conflict for `commit_push`'s rebase. + log_sync + if [ "$NO_GIT" != 1 ] && [ "$LOG_SYNC_FETCH" != yes ]; then + die "retire-rows requires a successful fresh fetch before rewriting several rows; $LOG_SYNC_FETCH. The local origin/$LANES_BRANCH ref may be stale. Nothing was written." 1 + fi + rr_writer="$(canon_lane "$rr_writer")" || exit 2 + # THE WRITER'S TRANSCRIPT IS THIS CHECKOUT'S ROW'S LAST ID, and the published + # row's only where this checkout has none (Copilot round 18 on #93, #138 item + # 8). `session_for` reads `$LANES_SESSION` or the PUBLISHED row, and the + # documented call sets only `LANES_LANE`: a writer whose newest transcript is + # stamped here and not yet pushed signed every append-only RETIRED line with an + # older id. A checkout behind origin is refused below, so this row is never + # the older of the two — the same reason refusal 1 reads both rows' ids. + rr_uuid="${LANES_SESSION:-}" + [ -n "$rr_uuid" ] || rr_uuid="$(session_ids_local_of_lane "$rr_writer" 2>/dev/null | tail -n1)" + [ -n "$rr_uuid" ] || rr_uuid="$(session_for "$rr_writer" 2>/dev/null || :)" + valid_uuid "$rr_uuid" || + die "the sweeping lane $rr_writer has no transcript uuid to write: \$LANES_SESSION is unset and its row's session cell holds none. Amendment 7(b) gives the session field a transcript uuid and ONLY that, and this log is append-only, so nothing is written. Run it from the lane's own session, or pass the id: LANES_SESSION=<uuid> LANES_LANE=$rr_writer lanes-edit.sh retire-rows …" 2 + # All path cleanliness and ref fences run under the same writer lock as the + # scan. A peer can otherwise alter a target log while this act waits. + acquire_lock + if [ "$NO_GIT" != 1 ] && have_remote_ref; then + rr_behind="$(git -C "$LANES_REPO" rev-list --count "HEAD..origin/$LANES_BRANCH" 2>/dev/null || printf '')" + case "$rr_behind" in + '' | 0) : ;; + *) die "this checkout is $rr_behind commit(s) behind origin/$LANES_BRANCH. The sweep is ONE commit over several rows and several logs, so it is made against the published register or not at all. Pull first — \`git -C $LANES_REPO pull --rebase\` — and re-run. Nothing was written." 2 ;; + esac + fi + refuse_dirty_checkout "retire-rows" "$LANES_PATH" + + # THE MUTEX COMES BEFORE THE SCAN, not between the scan and the write: this + # act reads every row's LINE NUMBER and rewrites those lines by number, and a + # peer's `add-row` landing in between moves them under it (the finding + # `migrate-state-cells` took in round 2 of openRepoTools#82). It is held from + # `acquire_lock` above; a peer's register edit is captured at the write, after + # every refusal of the scan (#157 item 4b, `migrate_state_cells`' reason). + + # THE LIVE READ IS FAIL-CLOSED, AND IT IS TAKEN INSIDE THE LOCK (Copilot round + # 2 on #93). `lanes_rows` degrades to the log's verb when this workstation's + # session records cannot be read, because a LISTING may not refuse; a WRITE + # that retired a row out from under the session still writing it is the other + # kind of mistake entirely — and a snapshot taken BEFORE the mutex is a + # snapshot a lane can go live behind: `lane-start` appends its id to the row + # under this same lock, so the scan would read that new id and compare it with + # a fence that predates it. + rr_live=""; rr_live_rc=0 + rr_live="$(live_session_ids 2>/dev/null)" || rr_live_rc=$? + [ "$rr_live_rc" = 0 ] || + die "this workstation's session records could not be read, so whether any of these lanes is LIVE HERE is not known — and clause (c) refuses a lane a live session holds. A read that failed is not 'nothing is live' (Amendment 7(d)). Nothing was written." 1 + rr_fence=" $(printf '%s\n' "$rr_live" | awk -F"$US" 'NF { print tolower($1) }' | tr '\n' ' ')" + + rr_utc="$(utc_now)" + rr_tmp="$(mktemp -d)" + : > "$rr_tmp/plan"; : > "$rr_tmp/report" + rr_n=0; rr_names="" + rr_follow="" + rr_seen="" + for rr_lane in $rr_lanes; do + rr_l="$(canon_lane "$rr_lane")" || exit 2 # Amendment 15 + # THE SEAM (ruling 2026-10-04). The sweep is ONE commit, so one managed or + # unknown lane in it refuses all of it, here in the scan, before any line or + # cell is written; `die` releases the lock this sweep holds. + managed_seam_refuse "$rr_l" "retire-rows (Amendment 19's sweep)" + # A LANE NAMED TWICE IS A REFUSAL AND NOT A SECOND LINE. The log is + # append-only: a duplicate in the argument list would put the same `RETIRED` + # line into it twice, in one commit, and no later line could take it back. + # Compared on the RESOLVED name, so the two spellings of one lane are one + # lane here as they are everywhere else (Amendment 15). + case " $rr_seen " in + *" $rr_l "*) die "lane $rr_l is named twice in this sweep. Its log is append-only, so a second pass over it would write the same RETIRED line again and nothing could take it back. Name each lane once. Nothing was written." 2 ;; + esac + rr_seen="$rr_seen $rr_l" + rr_ln="$(row_line "$rr_l")" || exit 2 # one row, exactly + rr_row="$(sed -n -e "${rr_ln}p" "$LANES_FILE")" + if [ "${rr_row//$US/}" != "$rr_row" ]; then + die "lane $rr_l's row contains the internal sweep-plan field separator, so it cannot be serialized safely. Nothing was written." 2 + fi + rr_rc=0; row_split_state_cell "$rr_row" || rr_rc=$? + case "$rr_rc" in + 0) : ;; + 2) die "lane $rr_l's row (line $rr_ln) carries $(row_sep_count "$rr_row") ' | ' separators where a seven-column row carries 6, so WHICH TEXT IS THE STATE CELL is not knowable from the row — and this act both READS that cell (the words it carries into the log) and REWRITES it. Escape the literal pipe inside that cell as \| by hand, commit it, and re-run. Nothing was written." 2 ;; + *) die "lane $rr_l's row (line $rr_ln) does not open with '|' and end with '|', so it is not a row this writer can take apart. Nothing was written." 2 ;; + esac + mig_trim "$RSS_CELL"; rr_cell="$MIG_TRIM" + rr_head="$rr_cell" + if [ "${#rr_head}" -gt 240 ]; then + # THE CAP IS CLAUSE (c)'s 240, CUT BACK TO A SPACE — `cut_to_line`'s rule + # and the migration's: `${s:0:n}` counts bytes wherever the locale is not + # a UTF-8 one, and these cells are full of `·`, `—` and `→`. + rr_head="${rr_head:0:236}" # 236 + " ..." is the 240 clause (c) gives + case "$rr_head" in *' '*) rr_head="${rr_head% *}" ;; esac + rr_head="$rr_head ..." + fi + + # (c) REFUSAL 1 — a live session here. + # BOTH ROWS' IDS, for the reason `lanes_rows` gives one screen up: an id + # this checkout has committed and not yet pushed is on no published cell, + # and this is the FAIL-CLOSED half of the same question (Copilot round 1 on + # #93). + rr_ids="$(session_ids_of_lane "$rr_l" 2>/dev/null || :) +$(session_ids_local_of_lane "$rr_l" 2>/dev/null || :)" + for rr_id in $rr_ids; do + case "$rr_fence" in + *" $rr_id "*) die "lane $rr_l has a LIVE session on this workstation (transcript $rr_id), so it is not a dormant row: clause (c) refuses a lane a live session holds, and retiring it would take the row out from under the conversation that IS the lane. End it the ordinary way when it is done — lane-end $rr_l. Nothing was written." 2 ;; + esac + done + + # (c) REFUSAL 2 — a log that says the lane is somewhere. + # + # THE PUBLISHED LOG IS PROVED READABLE FIRST (Copilot round 3 on #93). + # `lane_log_events` ends in `git show … | parse_log_stream` and this file + # sets no `pipefail`, so a `git show` that FAILED is masked by the parser + # exiting 0 over empty input — and the lane then reads as having no + # lane-kind line at all, which is the one answer that lets the sweep + # through. The object is asked for by name instead, and then `show` with its + # own status. + # WHETHER THE PATH IS PUBLISHED IS THE TREE'S ANSWER, NOT THE BLOB'S + # (Copilot round 21 on #93, #138 item 17). It was `cat-file -e`, which + # fails for a blob that is missing or corrupt exactly as for a path that is + # not there, so a log the tree names and git cannot read was "no published + # log" and the sweep went on. `ls-tree` reads the tree alone. + rr_pubp="" + rr_pubp="$(log_path_ci "$rr_l")" || + die "lane $rr_l's object log is published twice under names that differ only by case (above) — 15(d)'s hand merge. Nothing was written." 2 + if [ "$NO_GIT" != 1 ] && have_remote_ref; then + rr_intree="" + rr_intree="$(git -C "$LANES_REPO" ls-tree --name-only "origin/$LANES_BRANCH" -- "$rr_pubp" 2>/dev/null)" || + die "the tree of origin/$LANES_BRANCH could not be listed, so whether lane $rr_l has a published object log is not known — and that is NOT 'it has none' (Amendment 7(d)). Nothing was written." 1 + if [ -n "$rr_intree" ]; then + git -C "$LANES_REPO" show "origin/$LANES_BRANCH:$rr_pubp" >/dev/null 2>&1 || + die "lane $rr_l's published object log ($rr_pubp) exists on origin/$LANES_BRANCH and could not be read, so whether it carries a lane-kind line is not known — and that is NOT 'it has none' (Amendment 7(d)). Nothing was written." 1 + fi + fi + rr_ev=""; rr_erc=0 + rr_ev="$(lane_log_events "$rr_l" 2>/dev/null)" || rr_erc=$? + [ "$rr_erc" = 0 ] || + die "lane $rr_l's object log could not be read (exit $rr_erc), so whether it carries a lane-kind line is not known — and that is NOT 'this lane has no log' (Amendment 7(d)). Nothing was written." 1 + # AND THIS CHECKOUT'S OWN COPY OF THAT LOG (Copilot round 2 on #93), for the + # reason the session ids are read from both rows: `lane_log_events` answers + # out of `origin/<branch>` (R19), and a log line committed here and not yet + # pushed is on no origin at all. The `behind` guard above refuses a checkout + # that is behind; one that is AHEAD is legitimate, and there a `STARTED` + # that exists only here would be invisible — the lane reading as dormant + # while its own log says it is running. + # AND THE LOCAL ONE IS READ WITH THE SAME POSTURE (round 3): converted to an + # empty stream with `|| :`, a TRACKED log that exists here and will not open + # read as a lane with no lane-kind line — and the untracked-file guard below + # does not catch a tracked one. + rr_lev="" + rr_lf="$(log_file_for "$rr_l")" + # A LOG PATH THAT IS A SYMLINK, OR THERE AND NOT A REGULAR FILE, IS REFUSED + # BEFORE IT IS READ (Copilot round 18 on #93, #138 item 12). The write + # appends with `>>`, which follows a link: a tracked link here put the + # RETIRED line in whatever file it named, outside the repository, while the + # commit recorded only the link. + if [ -L "$rr_lf" ] || { [ -e "$rr_lf" ] && [ ! -f "$rr_lf" ]; }; then + die "lane $rr_l's object log $(log_path_for "$rr_l") is a symlink, or is there and not a regular file, in this checkout. This sweep appends to it with '>>', which writes through a link to whatever file it names while the commit records only the link. Put the log itself there as a regular file, commit that, and re-run. Nothing was written." 2 + fi + if [ -f "$rr_lf" ]; then + [ -r "$rr_lf" ] || + die "lane $rr_l's object log $rr_lf exists in this checkout and could not be read, so whether it carries a lane-kind line is not known — and that is NOT 'it has none' (Amendment 7(d)). Nothing was written." 1 + rr_lev="$(log_events "$rr_lf" 2>/dev/null)" || + die "lane $rr_l's object log $rr_lf could not be parsed, so whether it carries a lane-kind line is not known (Amendment 7(d)). Nothing was written." 1 + fi + rr_open="$(printf '%s\n%s\n' "$rr_ev" "$rr_lev" | awk -F"$US" '$3 == "STARTED" || $3 == "PAUSED" || $3 == "RESUMED" || $3 == "ENDED" || $3 == "RETIRED" { v = $3 } END { if (v != "") print v }')" + rr_pub_open="$(printf '%s\n' "$rr_ev" | awk -F"$US" '$3 == "STARTED" || $3 == "PAUSED" || $3 == "RESUMED" || $3 == "ENDED" || $3 == "RETIRED" { v = $3 } END { if (v != "") print v }')" + # THE RULE IS CLAUSE (c)'s AND STAYS: a log that CARRIES a lane-kind line is + # refused. THE SENTENCE FOLLOWS THE LAST ONE (#120 item 3, Copilot round 5 on + # #93). A log whose last lane-kind line is ENDED or RETIRED is a lane already + # CLOSED (19(a)), and `lane-end` is not its exit: it is told it is closed, + # already hidden, and — for RETIRED alone, the only cell `archive-rows` + # moves — which act takes the row out of the register. + # + # AND "CLOSED" IS SAID ONLY OF A CLOSING LINE ORIGIN CARRIES (the review of + # #263, S2). An earlier sweep that stopped part-way leaves its RETIRED line + # in this checkout's log and nowhere else; a re-run told the lane it was + # CLOSED, "nothing more is owed", about a row never retired and a line never + # published. That line is still refused, and is named as this checkout's. + case "$rr_open" in + '') : ;; + ENDED | RETIRED) + rr_art=a; [ "$rr_open" != ENDED ] || rr_art=an + [ "$rr_pub_open" = "$rr_open" ] || + die "lane $rr_l's object log in THIS CHECKOUT ends on $rr_art $rr_open line, and origin/$LANES_BRANCH's copy does not: it is a write made here and never published, by an earlier act that stopped part-way or a commit whose push has not landed (\`git -C $LANES_REPO status\` and \`git -C $LANES_REPO log origin/$LANES_BRANCH..HEAD -- $(log_path_for "$rr_l")\` say which). It is refused either way, since a second closing line would be one more line in an append-only log, and the lane is not called CLOSED, since nothing published says so. Publish that line or undo it, then re-run. Nothing was written." 2 + case "$rr_open" in + RETIRED) + die "lane $rr_l's object log ends on a RETIRED line, so the lane is already CLOSED and RETIRED (Amendment 19(a)), not a dormant row: \`lanes\` already hides it (19(b)), and its log is append-only, so it is not retired a second time. Its row leaves the register by \`lanes-edit.sh archive-rows ${rr_l%-*}\` (19(d)), which moves that repository's rows whose state cell says RETIRED. Nothing was written." 2 ;; + *) + die "lane $rr_l's object log ends on an ENDED line, so the lane is already CLOSED (Amendment 19(a)): it was ended, and a closed lane is not a dormant row. \`lanes\` already hides it (19(b)), and its log is append-only, so a RETIRED line after its ENDED would be one more line for a lane that is already finished. Nothing more is owed: its row stays in the register as the record (Rule 9), and \`archive-rows\` is not its exit, since it moves only rows whose state cell says RETIRED. Nothing was written." 2 ;; + esac ;; + *) + die "lane $rr_l's object log carries a $rr_open line as its last lane-kind line, so it is not a dormant row: a running or parked lane is a lane a person can still pick up. End it as itself when its work is done: lane-end $rr_l. Nothing was written." 2 ;; + esac + + # (c) REFUSAL 3 — THE ROW ITSELF SAYING THE LANE IS SOMEWHERE, which is the + # same test the listing makes and is re-proved here rather than trusted + # (Copilot round 1 on #93). Amendment 13(a) makes the state cell the lane's + # CURRENT STATE: a cell that is the phrase and names anything but `ENDED`, + # `RETIRED` or the migration's `MIGRATED` is a row `lanes` does not hide + # either, and the writer and the read must not disagree about which rows are + # dormant — that is the defect clause (h) and A11 Addendum 4 ruling 7 both + # exist to prevent. + # + # A CELL THAT ALREADY SAYS `RETIRED` IS NOT A SECOND RETIREMENT (Copilot + # round 20 on #93). Refused here, it was a row the listing classes DORMANT + # and the preview names — and one refusal stops the whole sweep. The row a + # migration leaves is exactly that: the phrase in the cell, NOTED lines in + # the log. A second retirement is a second RETIRED LINE in an append-only + # log, and refusal 2 just above refuses that, from the log. + if mig_cell_is_phrase "$rr_cell"; then + case "${rr_cell%% · *}" in + ENDED | RETIRED | MIGRATED) : ;; + *) die "lane $rr_l's row says ${rr_cell%% · *}: its state cell is Amendment 13(a)'s phrase — '$rr_cell' — and that cell is the lane's CURRENT STATE, so this is not a dormant row and \`lanes\` does not hide it either. A lane the register says is somewhere is ended as itself (lane-end $rr_l) or its cell is corrected first (set-row-state). Nothing was written." 2 ;; + esac + fi + + # AMENDMENT 15 — the log this write appends to is the row's own spelling, + # and a case-only rename is a write of its own rather than one this sweep + # smuggles into a commit that names something else. Both halves of + # `ensure_log`'s question are asked HERE, in the scan, so the refusal comes + # before any byte is written rather than half-way through the run. + # AND A LOG DIRECTORY THAT CANNOT BE LISTED IS A REFUSAL HERE (#138 item 9), + # not a lane with no log that `ensure_log` then fails on inside the loop. + rr_loc="$(log_files_named_ci "$rr_l")" || + die "the log directory $LANES_LOG_DIR exists and could not be listed, so whether lane $rr_l has a log of any case in this checkout is not known — and that is NOT 'it has none' (Amendment 7(d)). Nothing was written." 1 + rr_ln2="$(printf '%s' "$rr_loc" | grep -c . || :)" + [ "$rr_ln2" -le 1 ] || + die "lane $rr_l has $rr_ln2 object logs in this checkout whose names differ only by case: $(printf '%s\n' "$rr_loc" | tr '\n' ' ')— one lane is ONE lane under any case (Amendment 15) and no read of it is unambiguous. Merge them by hand into $(log_file_for "$rr_l") (15(d)) and re-run. Nothing was written." 2 + if [ "$rr_ln2" = 1 ] && [ "$rr_loc" != "$(log_file_for "$rr_l")" ]; then + die "lane $rr_l's object log is here as ${rr_loc##*/} while the row spells the lane $rr_l, so the first write to it RENAMES the file (Amendment 15) — and this sweep is one commit over several lanes, which is not the commit that rename belongs in. Take it first with a write of that lane's own (\`LANES_LANE=$rr_l lanes-edit.sh log NOTED lane:$rr_l \"<what it was>\"\`), then re-run. Nothing was written." 2 + fi + # AN UNTRACKED LOG IS SOMEBODY'S UNCOMMITTED WORK, AND THIS ACT WOULD + # COMMIT IT — the finding `migrate-state-cells` took in round 2 of + # openRepoTools#82, and this sweep has the same shape. A TRACKED log that is + # dirty is already refused for the whole run by `refuse_dirty_checkout` + # above, which exempts the register alone; an untracked file is in neither + # of its lists, so appending here would put a peer's first lines into this + # sweep's one commit under this sweep's message. (A dormant row usually has + # no log at all — but a migrated one has a log of NOTED lines, and that is + # the file this meets.) + if [ "$rr_ln2" = 1 ] && [ "$NO_GIT" != 1 ] && + ! git -C "$LANES_REPO" ls-files --error-unmatch -- "$(log_path_for "$rr_l")" >/dev/null 2>&1; then + die "lane $rr_l's object log $(log_path_for "$rr_l") exists in this checkout but is NOT TRACKED — somebody's uncommitted work, which this sweep would commit inside its own commit and under its own message. Commit it first (\`git -C $LANES_REPO commit -m \"<what it is>\" -- $(log_path_for "$rr_l")\`) and re-run. Nothing was written." 2 + fi + # THE PUBLISHED PATH IS THE ONE THE READABILITY PROBE ALREADY RESOLVED — + # `log_path_ci` is a `ls-tree` of the whole log directory and this loop runs + # per lane, so asking it twice for one lane is a second read of the same + # tree for the same answer. + # + # AND THE QUESTION IS `ensure_log`'S OWN, NOT A PARAPHRASE OF IT (#120 item + # 2, Copilot round 5 on #93). The scan asked it only where this checkout had + # NO log, and beside that compared a BASENAME with a repo-relative PATH, a + # clause that could never be equal. So the state a case-only rename leaves + # when its commit has not been pushed — the row's spelling here, committed; + # the old spelling still in origin's tree; a checkout merely AHEAD, which the + # `behind` guard rightly lets through — passed the scan, and `ensure_log` + # refused it INSIDE THE WRITE LOOP, after the lanes before it in this one + # commit had had their logs created and appended. It is asked here as + # `ensure_log` asks it, in its words, because it is the same refusal; the + # refusal of a local file of another case above means `rr_from`, where + # there is one, is the row's own spelling. + rr_pub="$rr_pubp" + rr_from="" + [ "$rr_ln2" = 1 ] && rr_from="$rr_loc" + if [ "$rr_pub" != "$(log_path_for "$rr_l")" ] && [ "${rr_from##*/}" != "${rr_pub##*/}" ]; then + rr_here="and this checkout does not have it" + [ -n "$rr_from" ] && rr_here="while this checkout has ${LANES_LOG_PREFIX}${rr_from##*/} instead — a case-only rename whose commit never landed" + die "lane ${rr_l}'s object log is published as $rr_pub $rr_here: the row spells the lane $rr_l, so the log is $(log_path_for "$rr_l") (Amendment 15), and writing one here now would leave TWO files for one lane. Pull first — \`git -C $LANES_REPO pull --rebase\` — and re-run. Nothing was written." 2 + fi + + # THE LINE AND THE CELL, BOTH BUILT AND BOTH CHECKED BEFORE ANYTHING IS + # WRITTEN. `row_state_check` dies on a cap, a `|` or a second ` · `, so it + # is asked HERE — in the scan — and never with the register half-rewritten. + rr_pay="retired-dormant by lane $rr_writer; reason $rr_reason; was: $rr_head" + event_line RETIRED "$rr_l" "$rr_uuid" "$rr_utc" "lane:$rr_l" '→' "$rr_pay" > "$rr_tmp/line.$rr_ln" + rr_wasrow="$(printf '%s' "$rr_head" | tr '|' '/')" + rr_wasrow="${rr_wasrow// · /; }" + rr_line="$rr_reason; was: $rr_wasrow" + if [ "${#rr_line}" -gt "$ROW_STATE_CAP" ]; then + rr_line="${rr_line:0:$((ROW_STATE_CAP - 4))}" + case "$rr_line" in *' '*) rr_line="${rr_line% *}" ;; esac + rr_line="$rr_line ..." + fi + row_state_check "RETIRED · $rr_line" + rr_new="RETIRED · $rr_utc · $ROW_STATE_LINE" + printf '%s%s%s%s%s%s%s%s%s\n' "$rr_ln" "$US" "$rr_l" "$US" "$rr_new" "$US" "$RSS_HEAD" "$US" "$RSS_TAIL" >> "$rr_tmp/plan" + printf ' %-26s %s\n' "$rr_l" "$rr_new" >> "$rr_tmp/report" + rr_names="$rr_names $rr_l" + # THE LIFECYCLE PRE-IMAGE, TAKEN UNDER THE LOCK THIS SWEEP ALREADY HOLDS + # (openRepoTools#91). These `RETIRED` lines are appended by this function + # and never by `write_event`, so the follow-up that moves a lane's snapshot + # to `CLOSED` for every other `RETIRED` would never run for them, and a + # swept lane would keep whatever its snapshot last said. The pre-image is + # what the follow-up compares against, exactly as `write_event` takes it. + rr_follow="$rr_follow$rr_l$US$(lane_state_preimage "$rr_l" "")${US}8 +" + rr_n=$((rr_n + 1)) + done + + # --------------------------------------------------------------- the write + # + # THE LOGS FIRST AND THE ROWS SECOND, and all of it published by the single + # `commit_push` at the end: a refusal in the middle leaves this checkout dirty + # and the register unpublished, which `git status` shows and + # `git checkout -- lanes` undoes whole. Nothing is half-published, because the + # commit is the only thing that publishes. A peer's register edit is + # committed as its own first, as `migrate_state_cells` says at its write. + handle_preexisting "$LANES_PATH" + rr_paths=("$LANES_PATH") + while IFS="$US" read -r rr_ln rr_l rr_new rr_head2 rr_tail; do + [ -n "${rr_ln:-}" ] || continue + ensure_log "$rr_l" + append_text_block "$(log_file_for "$rr_l")" "$(cat -- "$rr_tmp/line.$rr_ln")" + rr_paths+=("$(log_path_for "$rr_l")") + reg_wrote "$(log_path_for "$rr_l") (its RETIRED line)" + done <<EOF +$(cat -- "$rr_tmp/plan") +EOF + while IFS="$US" read -r rr_ln rr_l rr_new rr_head2 rr_tail; do + [ -n "${rr_ln:-}" ] || continue + replace_line "$rr_ln" "$rr_head2$rr_new $rr_tail" + reg_wrote "$LANES_PATH (the row of $rr_l)" + done <<EOF +$(cat -- "$rr_tmp/plan") +EOF + + printf 'retire-rows — %s lane(s) RETIRED (lane-collision-protocol Amendment 19(c))\n' "$rr_n" + printf ' writer : lane %s, session %s@%s\n' "$rr_writer" "$rr_uuid" "$WS" + printf ' reason : %s\n' "$rr_reason" + printf '\n lane the cell it becomes\n' + cat -- "$rr_tmp/report" + rm -rf -- "$rr_tmp" + + rr_msg="LANES(retire-dormant@$WS): Amendment 19(c) — $rr_n dormant row(s) RETIRED by lane $rr_writer;$rr_names; reason $rr_reason" + commit_push "$rr_msg" "${rr_paths[@]}" + rr_crc=$? + release_lock + # AND EACH SWEPT LANE'S SNAPSHOT FOLLOWS ITS LINE, after the lock, for the + # reason `write_event` gives at its own foot: the follow-up takes the mutex + # for itself and never fails the act whose lines have already landed. + while IFS="$US" read -r rr_fl rr_fpre rr_fseam; do + [ -n "${rr_fl:-}" ] || continue + lane_state_follow "$rr_fl" RETIRED "" "$rr_uuid" "$rr_fpre" "$rr_fseam" + done <<RR_FOLLOW +$rr_follow +RR_FOLLOW + return "$rr_crc" +} + +# ------------------- AMENDMENT 19(d): THE ARCHIVE, A SECOND ACT ON A SECOND +# WORD +# +# `archive-rows <repo>` MOVES every `RETIRED` row of `<repo>` out of +# `lanes/LANES.md` and into `lanes/archive/LANES-retired.md`, in ONE commit +# whose message names each lane moved. Rule 9 holds either way — a row is one +# `git show` away — so this is for a register a person wants SHORTER and is +# never a requirement, and nothing reads a row differently for having moved: +# `register_lanes`, `lanes_register_index` and `lane_position_rows` all read +# the archive beside the register, which is the amendment's own sentence +# (*"every reader of the next free position and `lanes --closed` read the +# archive too"*). A retired `<repo>-<n>` is never reissued. +# +# WHICH ROWS: the lane name's head — everything before its LAST hyphen — is the +# repository, compared without regard to case, which is `lane_next_free`'s rule +# for the same question and not a second one; and the state cell names `RETIRED` +# by `mig_lead_state`, the one reader of a cell's leading state word, so a +# legacy cell and Amendment 13's phrase are read by the same code. +archive_rows() { # <repo> <1 = the act, 0 = the dry run> + ar_repo="$1"; ar_do="${2:-0}" + ar_rl="$(lc "$ar_repo")" + log_sync + if [ "$ar_do" = 1 ]; then + if [ "$NO_GIT" != 1 ] && [ "$LOG_SYNC_FETCH" != yes ]; then + die "archive-rows requires a successful fresh fetch before moving rows; $LOG_SYNC_FETCH. The local origin/$LANES_BRANCH ref may be stale. Nothing was written." 1 + fi + if [ "$NO_GIT" != 1 ] && have_remote_ref; then + ar_behind="$(git -C "$LANES_REPO" rev-list --count "HEAD..origin/$LANES_BRANCH" 2>/dev/null || printf '')" + case "$ar_behind" in + '' | 0) : ;; + *) die "this checkout is $ar_behind commit(s) behind origin/$LANES_BRANCH. The move is ONE commit carrying the register and the archive, so it is made against the published register or not at all. Pull first — \`git -C $LANES_REPO pull --rebase\` — and re-run. Nothing was written." 2 ;; + esac + fi + acquire_lock + # The cleanliness fence belongs INSIDE the writer lock. Another writer + # could otherwise create or edit the archive while this act waits for it. + # THE ARCHIVE IS NOT EXEMPT (Copilot round 4 on #93). It was, because this + # act writes it — but `handle_preexisting` captures the REGISTER alone, so a + # tracked edit somebody else left in the archive rode into this commit under + # this act's message. And it is what makes a half-done move safe: if the + # append lands and `delete_lines` or the commit does not, the archive is + # dirty and the next run REFUSES by name instead of appending the same rows + # a second time. + refuse_dirty_checkout "archive-rows" "$LANES_PATH" + # THE SAME RULE FOR THE ARCHIVE ITSELF: an untracked one is a file this act + # did not create, and appending to it would commit somebody else's lines + # inside this move (openRepoTools#82, round 2). An archive this act creates + # is untracked for the seconds between the write and the commit, which is + # why the test is made HERE — before anything is written. + if [ -f "$LANES_ARCH_FILE" ] && [ "$NO_GIT" != 1 ] && + ! git -C "$LANES_REPO" ls-files --error-unmatch -- "$LANES_ARCH_PATH" >/dev/null 2>&1; then + die "$LANES_ARCH_PATH exists in this checkout but is NOT TRACKED — somebody's uncommitted work, which this move would commit inside its own commit. Commit it first (\`git -C $LANES_REPO commit -m \"<what it is>\" -- $LANES_ARCH_PATH\`) and re-run. Nothing was written." 2 + fi + # AN ARCHIVE THAT IS A SYMLINK, OR THERE AND NOT A REGULAR FILE, IS REFUSED + # (Copilot on #93's `afd5481`, #138 item 10). The rows are appended with + # `>>`, which follows a link: a tracked link here put them in whatever file + # it named, outside the repository, while the commit published the link and + # their removal from the register — the rows left the repository entirely. + if [ -L "$LANES_DIR/archive" ] || [ -L "$LANES_ARCH_FILE" ] || + { [ -e "$LANES_ARCH_FILE" ] && [ ! -f "$LANES_ARCH_FILE" ]; }; then + die "$LANES_ARCH_PATH, or its directory, is a symlink — or the archive is there and not a regular file. This move appends the rows with '>>', which writes through a link to whatever file it names while the commit records the link and removes the rows from the register. Put the archive itself there as a regular file, commit it, and re-run. Nothing was written." 2 + fi + # A PUBLISHED ARCHIVE THIS CHECKOUT DOES NOT HAVE IS REFUSED (Copilot on #93's + # `d0310f6`, #138 item 2). Out of a sparse checkout, or marked skip-worktree, + # the file is absent here and in nobody's dirty list, so the move created a + # NEW archive of only its own rows, whose commit would drop every position the + # published one reserves (Amendment 19(b)). Refused rather than seeded from + # origin: git (2.43, measured) will not stage a skip-worktree path, so a seeded + # archive fails at the commit after the rows have left the register here. + if [ "$NO_GIT" != 1 ] && have_remote_ref && [ ! -e "$LANES_ARCH_FILE" ] && [ ! -L "$LANES_ARCH_FILE" ]; then + ar_pubarch="" + ar_pubarch="$(git -C "$LANES_REPO" ls-tree --name-only "origin/$LANES_BRANCH" -- "$LANES_ARCH_PATH" 2>/dev/null)" || + die "the tree of origin/$LANES_BRANCH could not be listed, so whether $LANES_ARCH_PATH is published is not known — and a move that creates one beside a published one drops every position it reserves (Amendment 7(d)). Nothing was written." 1 + [ -z "$ar_pubarch" ] || + die "$LANES_ARCH_PATH is published on origin/$LANES_BRANCH and this checkout does not have it (it is outside a sparse checkout, or marked skip-worktree). A move made here would create a new archive holding only these rows, and its commit would drop every retired position the published one reserves (Amendment 19(b)). Bring it into this checkout — \`git -C $LANES_REPO sparse-checkout add ${LANES_ARCH_PATH%/*}\`, or for a skip-worktree path \`git -C $LANES_REPO update-index --no-skip-worktree $LANES_ARCH_PATH\` and \`git -C $LANES_REPO checkout -- $LANES_ARCH_PATH\` — and re-run. Nothing was written." 2 + fi + fi + + # THE REGISTER IS READ WITH ITS OWN STATUS (Copilot round 4 on #93). Inside + # the here-document below, a failed `awk` — an unreadable register — is + # discarded, the loop gets no rows, and the act reports "no row of <repo> has + # the state RETIRED" about a file it never read. An unreadable source is never + # an empty set (Amendment 7(d)). + ar_scan="" + ar_scan="$(awk 'substr($0,1,1) == "|" { + p1 = index($0, "`"); if (p1 == 0) next + r = substr($0, p1 + 1); p2 = index(r, "`"); if (p2 == 0) next + printf "%d\t%s\n", NR, substr(r, 1, p2 - 1) + }' "$LANES_FILE")" || + die "the register $LANES_FILE could not be read, so which of $ar_repo's rows are RETIRED is not known — and that is not 'none of them are' (Amendment 7(d)). Nothing was written." 1 + + ar_tmp="$(mktemp -d)" + : > "$ar_tmp/rows"; : > "$ar_tmp/nums"; : > "$ar_tmp/names" + ar_n=0 + while IFS="$(printf '\t')" read -r ar_num ar_lane; do + [ -n "${ar_num:-}" ] || continue + case "$(lc "$ar_lane")" in + "$ar_rl"-*) : ;; + *) continue ;; + esac + ar_head="$ar_lane"; ar_head="${ar_head%-*}" + [ "$(lc "$ar_head")" = "$ar_rl" ] || continue + ar_row="$(sed -n -e "${ar_num}p" "$LANES_FILE")" + # A ROW OF THIS REPOSITORY THAT CANNOT BE TAKEN APART IS A REFUSAL, NOT A + # SKIP (Copilot round 1 on #93). This act says it moves EVERY `RETIRED` row + # of `<repo>`; a row whose ` | ` count hides which text is the state cell + # may BE one, and moving the others while saying nothing about it is a + # partial act reported as a whole one. + ar_src=0; row_split_state_cell "$ar_row" || ar_src=$? + if [ "$ar_src" != 0 ]; then + rm -rf -- "$ar_tmp" + die "lane $ar_lane is $ar_repo's and its row (line $ar_num) carries $(row_sep_count "$ar_row") ' | ' separators where a seven-column row carries 6, so whether its state is RETIRED is not knowable from the row — and this act moves EVERY retired row of a repository or none of them. Escape the literal pipe inside that cell as \| by hand, commit it (\`LANES_LANE=$ar_lane lanes-edit.sh commit \"escape a literal pipe in row $ar_lane\"\`), and re-run. Nothing was written." 2 + fi + mig_trim "$RSS_CELL" + [ "$(mig_lead_state "$MIG_TRIM")" = RETIRED ] || continue + # THE SEAM (Copilot round 3 on #97). This act takes a row out of the + # register, and a RETIRED row may carry the managed ledger's marker. One + # managed or unknown row refuses the WHOLE move, as one refuses the whole + # of the sweep, because the move is one commit. Asked in a subshell so this + # function removes its own staging directory before it exits, as each + # refusal above does; `die` there has already said why. + ar_mrc=0 + ( managed_seam_refuse "$ar_lane" "archive-rows $ar_repo (the WHOLE move, which Amendment 19(d) makes one commit)" ) || ar_mrc=$? + if [ "$ar_mrc" != 0 ]; then + rm -rf -- "$ar_tmp" + exit "$ar_mrc" + fi + printf '%s\n' "$ar_row" >> "$ar_tmp/rows" + printf '%s\n' "$ar_num" >> "$ar_tmp/nums" + printf '%s\n' "$ar_lane" >> "$ar_tmp/names" + ar_n=$((ar_n + 1)) + done <<EOF +$ar_scan +EOF + + printf 'archive-rows %s — %s (lane-collision-protocol Amendment 19(d))\n' \ + "$ar_repo" "$( [ "$ar_do" = 1 ] && printf 'THE ACT' || printf 'DRY RUN, nothing is written' )" + printf ' register : %s\n' "$LANES_FILE" + printf ' archive : %s\n' "$LANES_ARCH_PATH" + printf ' rows : %s RETIRED row(s) of %s\n' "$ar_n" "$ar_repo" + if [ "$ar_n" -gt 0 ]; then + printf '\n' + awk '{ print " " $0 }' "$ar_tmp/names" + fi + if [ "$ar_n" = 0 ]; then + rm -rf -- "$ar_tmp" + die "no row of $ar_repo has the state RETIRED, so there is nothing to archive — this act moves finished rows and never anything else. \`lanes --closed --prefix $ar_repo\` shows what that repository's rows say; \`lane-end --retire-dormant $ar_repo\` is what RETIRES its dormant ones. Nothing was written." 2 + fi + if [ "$ar_do" != 1 ]; then + printf '\n DRY RUN — nothing was written. Make it the one act with: lanes-edit.sh archive-rows %s --yes\n' "$ar_repo" + rm -rf -- "$ar_tmp" + return 0 + fi + # A stopped earlier run may have appended to the archive before it removed + # the register rows. Never append those identities a second time, even if + # that partial archive was subsequently committed during recovery. + ar_existing="" + if [ -f "$LANES_ARCH_FILE" ]; then + ar_existing="$(awk -F'`' '/^\|/ && NF >= 3 { print $2 }' "$LANES_ARCH_FILE")" || + die "could not read $LANES_ARCH_FILE to check for already archived lanes. Nothing was written." 1 + fi + while IFS= read -r ar_lane; do + [ -n "$ar_lane" ] || continue + if printf '%s\n' "$ar_existing" | command grep -qixF -- "$ar_lane"; then + die "lane $ar_lane is already in $LANES_ARCH_PATH while still present in the register. Resolve that partial archive move before retrying; nothing was written." 2 + fi + done < "$ar_tmp/names" + + # THE ARCHIVE IS WRITTEN FIRST AND THE ROWS REMOVED SECOND, for the reason + # `delete_lines` gives: a refusal between the two leaves a copy in the archive + # and the register whole, and never a row in neither file. A peer's register + # edit is committed as its own first, after every refusal above (#157 item + # 4b, `migrate_state_cells`' reason). + handle_preexisting "$LANES_PATH" + mkdir -p -- "$LANES_DIR/archive" || + die "could not create $LANES_DIR/archive — the archive is written before anything is removed, so nothing has been" 6 + if [ ! -f "$LANES_ARCH_FILE" ]; then + { + printf '# LANES-retired.md — rows RETIRED out of `lanes/LANES.md`\n\n' + printf 'lane-collision-protocol Amendment 19(d). These lanes are finished. Their\n' + printf 'positions are NEVER REISSUED: every reader of the next free position and\n' + printf '`lanes --closed` read this file beside the register.\n\n' + printf '| lane | session id | workstation / env / user | started (UTC) | objects owned | handoff path | state |\n' + printf '|---|---|---|---|---|---|---|\n' + } > "$LANES_ARCH_FILE" || + die "could not write $LANES_ARCH_FILE — nothing has been removed from the register" 6 + note "created $LANES_ARCH_FILE" + reg_wrote "$LANES_ARCH_PATH (created)" + fi + append_text_block "$LANES_ARCH_FILE" "$(cat -- "$ar_tmp/rows")" + reg_wrote "$LANES_ARCH_PATH ($ar_n row(s) appended)" + delete_lines "$(cat -- "$ar_tmp/nums")" + + ar_msg="LANES(archive@$WS): Amendment 19(d) — $ar_n RETIRED row(s) of $ar_repo moved to $LANES_ARCH_PATH: $(tr '\n' ' ' < "$ar_tmp/names")" + rm -rf -- "$ar_tmp" + commit_push "$ar_msg" "$LANES_PATH" "$LANES_ARCH_PATH" + ar_crc=$? + release_lock + return "$ar_crc" +} + +# ============================================================================ +# THE SEAM: A MANAGED-OWNED LANE IS NOT THIS TOOLING'S +# ============================================================================ +# +# Brett Heap's ruling of 2026-10-04, verbatim: "managed ledger owns enrolled +# lanes; #97 owns legacy — rework both". A lane the managed ledger has enrolled +# carries a MANAGED-OWNER MARKER in its register row's state cell, written by +# that ledger's own writer; every lane without one is a LEGACY lane, and the +# legacy lane tooling in this file — the lifecycle below, the object log's +# lane-kind lines, the sweep, the row writers — answers for legacy lanes only. +# +# THE RULE, which is the ported reader's own ("no malformed marker may be +# downgraded to absence"): +# * a VALID marker is a managed lane: every legacy write refuses it with 2, +# names the owner, and writes nothing; +# * managed-owner vocabulary that does NOT parse — a malformed marker, a row +# that is not seven columns, an empty owner — or a register that could not +# be read is UNKNOWN: refused with 1, and nothing is written; +# * no vocabulary at all is a legacy lane, and everything here runs exactly +# as it did. +# +# PROVENANCE. The block between the two markers below is +# `3c26041:lanes-edit.sh:776-898` — the projection reader of branch +# `001-separate-swap-ctx-handoff` (its T019) — ported VERBATIM: not one byte of +# it differs, so that when that branch's T024 lands, the merge of the two is +# "keep either", and this file's `lane_is_managed_owned` becomes that branch's +# `managed_legacy_check`. The proof is an empty diff: +# diff <(git show 3c26041:lanes-edit.sh | sed -n 776,898p) \ +# <(sed -n '/^# --- BEGIN ported from 3c26041/,/^# --- END ported from 3c26041/p' lanes-edit.sh | sed '1d;$d') +# Its four dependencies — `row_split_state_cell`, `rstrip_spaces`, `lc` and +# `row_of_lane` — are byte-identical in this file and in that one. +# --- BEGIN ported from 3c26041:lanes-edit.sh:776-898 --- +MANAGED_PROJECTION_MODE="" +MANAGED_PROJECTION_DAEMON="" +MANAGED_PROJECTION_GENERATION="" +MANAGED_PROJECTION_LANE="" + +managed_projection_component_valid() { # <path-safe component> + local mpc_value="${1-}" + case "$mpc_value" in + '' | .* | -* | *[!A-Za-z0-9._-]*) return 1 ;; + esac + [ "${#mpc_value}" -le 128 ] || return 1 + return 0 +} + +managed_projection_generation_valid() { # <positive decimal integer> + local mpg_value="${1-}" + case "$mpg_value" in + '' | *[!0-9]* | 0) return 1 ;; + esac + while [ "${mpg_value#0}" != "$mpg_value" ]; do + mpg_value="${mpg_value#0}" + done + [ -n "$mpg_value" ] || return 1 + MANAGED_PROJECTION_GENERATION="$mpg_value" + return 0 +} + +managed_projection_hint() { # <row>; 0 means a managed marker is visible + printf '%s\n' "${1-}" | awk ' + { s = tolower($0) + if (s ~ /managed[ _-](owner|binding)/ || + s ~ /mode[ _-]*=[ _-]*managed/ || + s ~ /managed[ _-]*:/) found = 1 + } + END { exit(found ? 0 : 8) }' +} + +managed_projection_parse_row() { # <row>; 0 valid marker, 8 absent, other unknown + local mppr_row="${1-}" mppr_split mppr_cell mppr_text mppr_line mppr_fields mppr_hint mppr_row_lane + MANAGED_PROJECTION_MODE="" + MANAGED_PROJECTION_DAEMON="" + MANAGED_PROJECTION_GENERATION="" + MANAGED_PROJECTION_LANE="" + mppr_hint=8 + if managed_projection_hint "$mppr_row"; then + mppr_hint=0 + else + mppr_hint=$? + fi + mppr_split=0 + row_split_state_cell "$mppr_row" || mppr_split=$? + case "$mppr_split" in + 0) : ;; + 2) [ "$mppr_hint" = 0 ] && return 1; return 8 ;; + *) [ "$mppr_hint" = 0 ] && return 1; return 8 ;; + esac + # A row without any managed-owner vocabulary is an ordinary legacy row and + # is the confirmed-absent projection result. Once that vocabulary appears, + # however, every table/state delimiter and every owner field is evidence that + # must parse; no malformed marker may be downgraded to absence. The split + # above intentionally runs first so projection writers retain RSS_HEAD and + # RSS_TAIL when replacing an ordinary row. + [ "$mppr_hint" = 0 ] || { [ "$mppr_hint" = 8 ] && return 8; return 1; } + mppr_cell="$(rstrip_spaces "$RSS_CELL")" + case "$mppr_cell" in + 'MANAGED OWNER · '* | 'managed owner · '*) + # Keep the historical shorthand, but never treat an empty owner token + # as a valid durable binding. + mppr_text="${mppr_cell#* · }" + case "$mppr_text" in + '' | *[!A-Za-z0-9._-]*) return 1 ;; + esac + return 0 + ;; + *' · '*) mppr_text="${mppr_cell#* · }" ;; + *) return 1 ;; + esac + case "$mppr_text" in + *' · '*) mppr_line="${mppr_text#* · }" ;; + *) + return 1 ;; + esac + case "$mppr_line" in + managed-owner\ *) : ;; + *) return 1 ;; + esac + mppr_fields="$(printf '%s\n' "$mppr_line" | sed -n \ + 's/^managed-owner mode=\([^[:space:]]*\) daemon=\([^[:space:]]*\) generation=\([^[:space:]]*\) bound-lane=\([^[:space:]]*\)$/\1|\2|\3|\4/p')" + [ -n "$mppr_fields" ] || return 1 + IFS='|' read -r MANAGED_PROJECTION_MODE \ + MANAGED_PROJECTION_DAEMON MANAGED_PROJECTION_GENERATION \ + MANAGED_PROJECTION_LANE <<EOF +$mppr_fields +EOF + [ "$MANAGED_PROJECTION_MODE" = managed ] || return 1 + managed_projection_component_valid "$MANAGED_PROJECTION_DAEMON" || return 1 + managed_projection_generation_valid "$MANAGED_PROJECTION_GENERATION" || return 1 + managed_projection_component_valid "$MANAGED_PROJECTION_LANE" || return 1 + mppr_row_lane="$(printf '%s\n' "$RSS_HEAD" | awk -F'|' '{ cell=$2; sub(/^[[:space:]]+/, "", cell); sub(/[[:space:]]+$/, "", cell); sub(/^`/, "", cell); sub(/`$/, "", cell); print cell }')" + managed_projection_component_valid "$mppr_row_lane" || return 1 + [ "$(lc "$mppr_row_lane")" = "$(lc "$MANAGED_PROJECTION_LANE")" ] || return 1 + return 0 +} + +managed_projection_read() { # <canonical lane>; 0 marker, 8 absent, other unknown + local mpr_lane="${1-}" mpr_row mpr_rc + if mpr_row="$(row_of_lane "$mpr_lane" 2>/dev/null)"; then + : + else + mpr_rc=$? + return "${mpr_rc:-1}" + fi + # `row_of_lane` is an awk pipeline and therefore exits 0 even when it + # printed no row. An empty result is the published register's confirmed + # absence (8), not an unreadable projection; callers need this distinction + # so a new legacy lane remains compatible when the optional helper is absent. + [ -n "$mpr_row" ] || return 8 + managed_projection_parse_row "$mpr_row" +} + +managed_projection_check() { # <canonical lane>; 0 conflict, 8 absent, other unknown + managed_projection_read "${1-}" +} +# --- END ported from 3c26041:lanes-edit.sh:776-898 --- + +# THE ONE READ EVERY CALLER ASKS: 0 with the owner on stdout, 8 a legacy lane, +# 1 UNKNOWN. It wraps `managed_projection_read` and maps every other status of +# it to 1, and it closes the one gap the ported reader leaves open on purpose: +# `row_of_lane` is an awk pipeline over `register_text`, which answers an EMPTY +# register — not a failure — where the published one could not be rendered, so +# the reader would call every lane legacy. An empty register is not a register +# with no managed lane in it, and it is 1 here (Amendment 7(d)). +# THE OWNER is the marker's `daemon=` for the full form and its token for the +# historical `MANAGED OWNER · <token>` shorthand, read from the same state cell +# the reader has just validated. +lane_is_managed_owned() { # <canonical lane> + limo_lane="${1-}"; limo_rc=0 + [ -n "$limo_lane" ] || return 1 + limo_reg="$(register_text)" + [ -n "$limo_reg" ] || return 1 + managed_projection_read "$limo_lane" || limo_rc=$? + case "$limo_rc" in + 0) + if [ -n "$MANAGED_PROJECTION_DAEMON" ]; then + printf '%s\n' "$MANAGED_PROJECTION_DAEMON" + else + limo_cell="$(rstrip_spaces "$RSS_CELL")" + printf '%s\n' "${limo_cell#* · }" + fi + return 0 ;; + 8) return 8 ;; + *) return 1 ;; + esac +} + +# THE REFUSAL, in one place, so every legacy act says the same two sentences. +# Returns 0 for a legacy lane; never returns otherwise. Called BEFORE the act +# writes anything — before its lock where it takes one, and where the lock is +# already held (the sweeps), before its first write — so a refusal changes +# nothing; `die` releases a held lock on the way out. +# +# AND THIS CHECKOUT'S ROW, NOT ONLY THE PUBLISHED ONE (Copilot round 2 and 3 on +# openRepoTools#97). The read above is the published register's (R19), and every +# legacy row writer rewrites the row in THIS checkout: one ahead of origin, or +# holding an edit `handle_preexisting` is about to capture, can carry managed-owner +# vocabulary the published row does not. Two copies that disagree on ownership +# are UNKNOWN, never legacy (Amendment 7(d)). A checkout with no register file +# has no row here to rewrite, and the published read has already answered. +managed_seam_refuse() { # <canonical lane> <the act> + msr_lane="${1-}"; msr_act="${2-this act}"; msr_rc=0; msr_owner="" + msr_owner="$(lane_is_managed_owned "$msr_lane")" || msr_rc=$? + case "$msr_rc" in + 0) die "lane $msr_lane is owned by the managed ledger (owner ${msr_owner:-unnamed}, from the managed-owner marker in its register row), and $msr_act is a legacy lane act: Brett Heap's ruling of 2026-10-04 — \"managed ledger owns enrolled lanes; #97 owns legacy\". Nothing was written. Act on this lane through the managed ledger." 2 ;; + 8) : ;; + *) die "whether the managed ledger owns lane $msr_lane is UNKNOWN: its register row carries managed-owner vocabulary that does not parse as a marker, or the register could not be read — and an ownership nobody could establish is never read as 'legacy' (Amendment 7(d)). $msr_act was refused and nothing was written. Read it: lanes-edit.sh managed-projection $msr_lane" 1 ;; + esac + managed_local_hint "$msr_lane" || + die "whether the managed ledger owns lane $msr_lane is UNKNOWN: its row in this checkout's register file, $LANES_FILE, carries managed-owner vocabulary (or could not be read) where the published register's, origin/$LANES_BRANCH, does not, and a legacy act rewrites THAT file's row — an ownership the two copies disagree on is never read as 'legacy' (Amendment 7(d)). $msr_act was refused and nothing was written. $(managed_local_remedy)" 1 + return 0 +} + +# THIS CHECKOUT'S HALF OF THAT READ, which `managed-projection` asks too +# (opensoft/openRepoTools#157 item 4a): the gates of `lane-start`, `lane-handoff` +# and `lane-end` ask that read, and a gate that passed a marker only this copy +# carries let a launch go on until a later writer refused. 0 where this +# checkout's row carries no managed-owner vocabulary, or there is no register +# file here; 1 where it carries some or could not be read. VOCABULARY ONLY, and +# not the row's shape (item 4d): a row with none cannot be a marker, so it is +# legacy in either copy, and the writer that rewrites it refuses a shape it +# cannot split on its own. +managed_local_hint() { # <canonical lane> + mlh_hint=8; mlh_loc="" + [ -f "$LANES_FILE" ] || return 0 + mlh_loc="$(row_of_lane_local "${1-}" 2>/dev/null)" || mlh_hint=1 + if [ "$mlh_hint" = 8 ] && [ -n "$mlh_loc" ]; then + mlh_hint=0; managed_projection_hint "$mlh_loc" || mlh_hint=$? + fi + [ "$mlh_hint" = 8 ] +} + +# WHAT A PERSON DOES ABOUT IT, in the words both refusals above print. The file +# named is the one `managed_local_hint` READ, which is not always in +# `$LANES_REPO`: a caller that points `LANES_REPO` at a runtime clone and sets +# no `LANES_WORKSPACE_ROOT` reads the published register in that clone and this +# file in workspace.yaml's tree. And the two copies can disagree in either +# direction: a change here that origin has not got, or a change on origin +# (the ledger removing its marker) that this checkout has not pulled. +managed_local_remedy() { + printf 'That file is AHEAD of origin — the row changed there and not pushed, or not committed at all: publish that change or undo it — or BEHIND it — origin has dropped the vocabulary since that checkout last moved: fast-forward it. Which one: git -C %s fetch && git -C %s status --short --branch -- %s' \ + "${LANES_FILE%/*}" "${LANES_FILE%/*}" "${LANES_FILE##*/}" +} + +# ============================================================================ +# THE CRASH-CONSISTENT LANE LIFECYCLE AND THE WORKTREE INVENTORY +# (openspec/changes/add-crash-consistent-lane-worktree-recovery, +# opensoft/openRepoTools#91) +# ============================================================================ +# +# **A LANE IS `RUNNING`, `SWAPPING`, `SWAPPED` OR `CLOSED`, and which of those +# it is, with no live holder, is what says where it stopped.** A session can +# run out of tokens BEFORE the handoff, AFTER it began and before it finished, +# or after it finished — and until this section those three left the same +# evidence: a lane whose last lane-kind line was a `STARTED`/`RESUMED` (which +# is also what a lane that is running looks like) or a `PAUSED` (which is also +# what a clean swap looks like). The two crash kinds had no word. +# +# WHAT IS NEW AND WHAT IS NOT. Nothing about the append-only log changes: its +# five STATE verbs are Amendment 7's and this section adds no lane-kind verb at +# all (Amendment 18(g)'s `HANDOFF-REQUESTED` is the sixth lane-kind verb, and it +# changes no state), so `swapped_candidates`, `lane_row_facts`, +# `lane_payload_field`, `lane-last`, `who` and `lane-end` read exactly what they +# read before. What is added is a +# SNAPSHOT beside that history — one small file per lane, replaced atomically +# under this file's own mutex — carrying the state word, a monotonic +# GENERATION, the OPERATION ID of the transition in flight, and the owner. The +# log stays the provenance; the snapshot is the cheap current-state read that +# an append-only file cannot give a compare-and-swap. +# +# WHERE IT LIVES, AND WHY IT IS NOT IN THE REGISTER AND NOT IN A WORKTREE. +# * NOT IN THE REGISTER. `lanes/LANES.md` is one file shared by every lane on +# every workstation and every write of it is a commit, a pull --rebase and +# a push (Amendment 5). A transition is taken three times per handoff and +# must be able to happen with no network at all. +# * NOT INSIDE A GIT WORKTREE. Orchestration metadata written into a checkout +# dirties it, is committed by accident, and disappears with the very +# directory whose loss it is meant to explain. +# * SO: a LOCAL control root beside the lane's own checkouts, derived in this +# order and never from the caller's current directory — +# 1. `$LANES_LANE_STATE_ROOT/<lane>`, the explicit override and the +# suite's seam; +# 2. `<parent of the lane's recorded `dir`>/.lane-state/<lane>` — the +# same parent the lane's own `.lane-worktrees/<lane>` root sits in, +# and `dir` is Amendment 11(c)'s recorded field, not a guess; +# 3. `$PROJECTS_ROOT/.lane-state/<lane>`, for a lane whose record names +# no directory yet. +# No answer is 8, "this lane has no control root", exactly as `lane-dir` +# answers 8 for a lane that has not started under Amendment 11 — and the +# pre-cutover lane is the ordinary case, not a failure (Amendment 7(i)). +# +# IT IS WRITTEN WHERE `R-A11-14` STOPS THE REGISTER AND THE OBJECT LOG. That +# rule refuses a record FILED UNDER A WORKSTATION where no workstation is +# configured, because such a record is unfindable by every restart of every +# workstation. The snapshot is filed under nothing: it is local to the machine +# that wrote it, it is never committed and it never leaves. So a container with +# no `$LANES_WORKSTATION` still keeps a lifecycle it can recover itself from, +# and these two writers are deliberately NOT in the dispatcher's workstation +# guard above. +# +# THE FENCE. Every transition carries `generation` (monotonic) and +# `operation` (unique to one handoff). `set-lane-state --expect` names the +# state, and optionally the generation and the operation, the caller believes +# it is moving from; the write happens only where all three still match, and +# otherwise NOTHING is written and the exit is 7 — the estate's "another act +# got there first", which is what `claim` already spends it on. That is the +# whole of what stops a `/handoff` that stalled for an hour from marking a lane +# `SWAPPED` after somebody has recovered and resumed it. +# +# WHO WRITES `RUNNING`. The confirming act, and never the SessionStart hook: +# `session-start` NEVER WRITES, never touches the network and ALWAYS EXITS 0 +# (Amendment 8, R-A8-1), which is what makes it safe in front of every session +# on the workstation. The act that actually proves lane, transcript, agent, +# directory and binding is `lane-start` (with or without `--no-launch`), and +# the proof it leaves is its `STARTED`/`RESUMED` line — so the snapshot follows +# THAT line, in `write_event`, from any caller. `ENDED`/`RETIRED` become +# `CLOSED` by the same rule. A `PAUSED` moves nothing: the two-phase transition +# around it belongs to `lane-handoff`, which takes `SWAPPING` before it polls +# anything and `SWAPPED` only after every mandatory write has landed. + +LANE_STATE_SCHEMA=1 + +# The four words, and nothing else is one. +lane_state_word_ok() { # <word> + case "${1-}" in RUNNING|SWAPPING|SWAPPED|CLOSED) return 0 ;; esac + return 1 +} + +# THE CONTROL ROOT — the three rungs above, in order. 0 with the path (which +# need not exist yet), 8 where no rung answers. +lane_control_root() { # <lane> [<a payload that may carry `dir`>] + lcr_lane="${1-}"; lcr_pay="${2-}"; lcr_dir=""; lcr_par="" + [ -n "$lcr_lane" ] || return 8 + if [ -n "${LANES_LANE_STATE_ROOT:-}" ]; then + printf '%s/%s\n' "${LANES_LANE_STATE_ROOT%/}" "$lcr_lane" + return 0 + fi + [ -n "$lcr_pay" ] && lcr_dir="$(payload_subfield "$lcr_pay" dir)" + if [ -z "$lcr_dir" ]; then + lcr_dir="$(lane_payload_field "$lcr_lane" dir 2>/dev/null || :)" + fi + case "$lcr_dir" in + /*) lcr_par="${lcr_dir%/*}" ;; + *) lcr_par="" ;; + esac + if [ -n "$lcr_par" ] && [ -d "$lcr_par" ]; then + printf '%s/.lane-state/%s\n' "$lcr_par" "$lcr_lane" + return 0 + fi + if [ -n "${PROJECTS_ROOT:-}" ] && [ -d "$PROJECTS_ROOT" ]; then + printf '%s/.lane-state/%s\n' "${PROJECTS_ROOT%/}" "$lcr_lane" + return 0 + fi + return 8 +} + +# ONE FIELD OUT OF ONE OF THESE FILES. They are flat `key: value` lines and +# nothing else — no nesting, no lists — so one `awk` reads every one of them +# and a malformed file answers empty rather than half a value. +lane_sidecar_field() { # <file> <key> + [ -r "${1-}" ] || return 1 + awk -v k="${2-}" ' + BEGIN { k = k ": " } + substr($0, 1, length(k)) == k { + v = substr($0, length(k) + 1) + sub(/^[ \t]+/, "", v); sub(/[ \t]+$/, "", v) + print v; exit }' "$1" +} + +# THE SCHEMA EVERY WRITER ASKS ABOUT BEFORE IT REPLACES ANYTHING (Copilot round +# 5 on openRepoTools#97). `lane_state_read` fails closed for a snapshot version +# it does not know — but a READER failing closed protects nobody if the WRITER +# beside it reads the raw fields and renames a file of its own over the top: an +# older helper meeting a `schema: 999` snapshot would then destroy a record it +# could not even read, and no later reader can undo that. So every writer of a +# sidecar in this section asks this first. +# +# ABSENT IS FINE — the first snapshot of a lane destroys nothing — and the +# CURRENT version is fine. Everything else, INCLUDING A FILE THAT EXISTS AND +# CANNOT BE READ, is refused: a schema nobody could read is not a schema this +# helper knows (R22, Amendment 7(d)). +# AND A DANGLING SYMLINK IS NOT ABSENT (Copilot on 64dfd97, PR #97): `-e` is +# false for one, so this guard used to wave every writer through to rename its +# own file over a record `lane_state_read` itself calls present-and-unreadable. +# `[ -L ]` beside `[ -e ]`, exactly as the reader asks it. +# +# AND THE RECORD, NOT ONLY ITS VERSION LINE (opensoft/openRepoTools#115). This +# asked one question, so a file whose first line is `schema: 1` and which holds +# nothing else passed it — a record of the current version that is not valid at +# that version — and both sides took it for one: the readers emitted empty +# fields for it and the writers renamed their own file over it, the act this +# guard exists to refuse. A file cut short is not exotic: `lane_sidecar_put`'s +# `cat` can be, and the rename makes a COMPLETE file atomic, not an incomplete +# one impossible. So a record of the current schema passes only when it is +# WHOLE: every key its writer writes is there and is not empty, the keys a +# reader decides with have their shapes, and a tree record claims the id its +# file name gives it. Both writers have written exactly these keys since #97 +# landed (`lane_state_put`, `lane_tree_put`), so no record a released helper +# wrote fails it. A malformed record of the KNOWN schema takes the refusal an +# unknown schema takes: every writer refuses it (1), the snapshot's reader +# answers 10, and the inventory's names it `<malformed>`. +# +# WHICH KIND OF RECORD IT IS COMES FROM WHERE IT IS FILED — `<root>/lane-state.yaml` +# for the snapshot, `<root>/trees/<id>.yaml` for a tree — and the second argument +# names that place for a file that is not there yet (`lane_sidecar_put`'s +# temporary file). THE SNAPSHOT'S ARM COMES FIRST (review r1 of #252): a `case` +# pattern's `*` matches `/`, so `*/trees/*.yaml` also matches +# `/x/trees/state/<lane>/lane-state.yaml`, and under a control root with any +# directory named `trees` above it every snapshot was asked a tree's keys, +# refused, and never written. A tree's file is never named `lane-state.yaml`: +# its id is `c<cksum>-…` (`tree_id_for`). `LSS_WHY` says why a record failed, in words a caller puts +# in its own message; it is set in the caller's shell, so call this directly +# and never inside `$( )`. The awk reads the id through the ENVIRONMENT, because +# `awk -v` processes escapes in a value. +lane_sidecar_schema_ok() { # <file> [<the path it is filed as>] + LSS_WHY="" + [ -e "${1-}" ] || [ -L "${1-}" ] || return 0 + if [ ! -r "$1" ]; then + LSS_WHY="it is there and could not be read" + return 1 + fi + lss_v="$(lane_sidecar_field "$1" schema 2>/dev/null || :)" + if [ "$lss_v" != "$LANE_STATE_SCHEMA" ]; then + LSS_WHY="it is of a schema this helper does not write (it writes schema $LANE_STATE_SCHEMA)" + return 1 + fi + lss_as="${2:-$1}"; lss_kind=""; lss_id="" + case "$lss_as" in + */lane-state.yaml) lss_kind=snapshot ;; + */trees/*.yaml) lss_kind=tree; lss_id="${lss_as##*/}"; lss_id="${lss_id%.yaml}" ;; + esac + [ -n "$lss_kind" ] || return 0 + lss_rc=0 + LSS_WHY="$(LSS_KIND="$lss_kind" LSS_ID="$lss_id" awk ' + { i = index($0, ": ") + if (i > 1) { k = substr($0, 1, i - 1); v = substr($0, i + 2) + sub(/^[ \t]+/, "", v); sub(/[ \t]+$/, "", v) + if (!(k in val)) val[k] = v } } + END { + kind = ENVIRON["LSS_KIND"] + if (kind == "snapshot") + n = split("lane state generation operation owner agent profile workstation kind updated", req, " ") + else + n = split("lane tree path checkout branch head upstream dirty unpushed writer generation operation observed", req, " ") + miss = "" + for (j = 1; j <= n; j++) + if (!(req[j] in val) || val[req[j]] == "") miss = miss (miss == "" ? "" : ", ") req[j] + if (miss != "") { print "it is not a whole record: it carries no " miss; exit } + if (val["generation"] !~ /^[0-9]+$/) { print "its generation \"" val["generation"] "\" is not a number"; exit } + if (kind == "snapshot") { + if (val["state"] !~ /^(RUNNING|SWAPPING|SWAPPED|CLOSED)$/) { + print "its state \"" val["state"] "\" is none of RUNNING, SWAPPING, SWAPPED and CLOSED"; exit } + } else { + if (val["tree"] != ENVIRON["LSS_ID"]) { + print "it claims to be tree " val["tree"] " and is filed as " ENVIRON["LSS_ID"]; exit } + if (substr(val["path"], 1, 1) != "/") { print "its path \"" val["path"] "\" is not absolute"; exit } + if (val["dirty"] !~ /^[0-9]+$/) { print "its dirty count \"" val["dirty"] "\" is not a number"; exit } + if (val["unpushed"] !~ /^([0-9]+|unknown)$/) { + print "its unpushed count \"" val["unpushed"] "\" is neither a number nor unknown"; exit } + } + }' "$1" 2>/dev/null)" || lss_rc=$? + if [ "$lss_rc" != 0 ]; then + LSS_WHY="it could not be read through (awk exited $lss_rc)" + return 1 + fi + [ -z "$LSS_WHY" ] +} + +# THE SNAPSHOT AS IT STOOD, IN ONE STRING — the pre-image a fenced write +# compares against. `<state>/<generation>/<operation>`, and `none/0/none` for a +# lane that has no snapshot at all, so that "there was nothing here" and "there +# was something here" are two different answers rather than one empty string. +lane_state_fingerprint() { # <file> + [ -e "${1-}" ] || { printf 'none/0/none\n'; return 0; } + printf '%s/%s/%s\n' \ + "$(lane_sidecar_field "$1" state 2>/dev/null || :)" \ + "$(lane_sidecar_field "$1" generation 2>/dev/null || :)" \ + "$(lane_sidecar_field "$1" operation 2>/dev/null || :)" +} + +# A VALUE IS ONE LINE OF `key: value`, so a newline or a leading space in one +# would make the file unreadable by the reader above. Both are flattened here +# rather than refused, because a value this can spoil is a branch name or a +# path and losing the WHOLE record over one is the worse trade. +lane_sidecar_value() { # <value> + lsv="${1-}" + lsv="${lsv//$'\r'/ }" + lsv="${lsv//$'\n'/ }" + printf '%s' "$lsv" +} + +# THE ATOMIC REPLACE. Written beside the target and renamed over it, so a +# reader never sees half a snapshot and a full disk leaves the old one intact. +# +# AND ONLY A WHOLE RECORD IS RENAMED INTO PLACE (opensoft/openRepoTools#115). +# The rename makes a complete file atomic and nothing more: a `cat` whose input +# was cut short — the writer killed between two of its lines — still exits 0, +# and the half record it wrote was renamed over the whole one. The temporary +# file is asked the question every reader and writer of the record asks, under +# the name it is about to take, and a record that fails it is removed instead. +lane_sidecar_put() { # <file> ; the whole body on stdin + lsp_f="${1-}"; lsp_d="${lsp_f%/*}" + [ -n "$lsp_f" ] || return 1 + mkdir -p -- "$lsp_d" 2>/dev/null || return 1 + lsp_t="$lsp_f.tmp.$$" + cat > "$lsp_t" 2>/dev/null || { rm -f -- "$lsp_t" 2>/dev/null; return 1; } + if ! lane_sidecar_schema_ok "$lsp_t" "$lsp_f"; then + rm -f -- "$lsp_t" 2>/dev/null + note "the record for $lsp_f was NOT written: what was about to replace it is not a whole record ($LSS_WHY), and a half record is never renamed over a whole one." + return 1 + fi + mv -- "$lsp_t" "$lsp_f" 2>/dev/null || { rm -f -- "$lsp_t" 2>/dev/null; return 1; } + return 0 +} + +# AN OPERATION ID: unique to one transition, and shaped like the manifest key +# every other sub-field of this estate is — letters, digits, `.`, `_`, `-` — so +# that it can be carried in a payload, a filename and a commit subject without +# a quoting rule of its own. There is no `uuidgen` on every workstation this +# runs on, and a timestamp with the pid and two `$RANDOM`s behind it is unique +# among the handfuls of transitions one lane takes in a day. +lane_op_id() { + printf 'op-%s-%s-%s%s\n' "$(date -u +%Y%m%dT%H%M%SZ)" "$$" "$RANDOM" "$RANDOM" +} + +# THE SNAPSHOT, READ. `<key><TAB><value>` lines, which is what every caller +# here parses with one `awk`. 0 with the fields, 8 where the lane has no +# snapshot at all (the pre-cutover lane, and not a failure), 10 where a snapshot +# IS there and could not be read — or is of this schema and not a whole record +# (#115) — 1 where the control root could not be derived. +# +# THE 10 IS THE POINT OF THIS ROUND (Copilot round 6 on openRepoTools#97, where +# it was 9 — main's #61 has since spent 9 on `claim`, so this one moved). A bare +# `[ -r ] || return 8` answered *this lane has no snapshot* for a file that +# exists and cannot be opened, and `lane_reconcile` maps every non-zero read to +# `NONE` — so a permission or an I/O error came out of the report as `no-state`, +# the verdict that tells a launcher this lane was never migrated and there is +# nothing to recover. That is fail-OPEN on a crash pronouncement, which is the +# whole class this capability exists to close: a read that failed is never an +# answer (R22, Amendment 7(d)), and the two cases are told apart here so that +# every caller above can tell them apart too. +# +# `[ -L ]` BESIDE `[ -e ]`, because a DANGLING SYMLINK is `-e` false: the name +# is there and the bytes are not, which is exactly *present and unreadable* and +# would otherwise fall through to the 8. +# +# THE PAYLOAD IS `lane_control_root`'s, AND OPTIONAL: a caller that already +# holds the lane's `dir` hands it here, and the lane's log is not read again +# to find it (review r2 of #289, SHOULD-A). A caller that names the lane +# alone finds the root exactly as before. +lane_state_read() { # <lane> [<a payload that may carry `dir`>] + lsr_lane="${1-}"; lsr_root=""; lsr_rc=0 + lsr_root="$(lane_control_root "$lsr_lane" "${2-}")" || lsr_rc=$? + [ "$lsr_rc" = 0 ] || return 1 + lsr_f="$lsr_root/lane-state.yaml" + if [ ! -r "$lsr_f" ]; then + if [ -e "$lsr_f" ] || [ -L "$lsr_f" ]; then return 10; fi + return 8 + fi + # AN UNKNOWN SCHEMA FAILS CLOSED (design decision: "conservative fail-closed + # behaviour for unknown versions"), through the ONE test every writer of these + # files takes too. A newer tooling's snapshot read by an older reader must not + # be reported as a lane in a state this reader knows — and must not be + # replaced by one either, which is what `lane_sidecar_schema_ok` is for. + # A RECORD OF THIS SCHEMA THAT IS NOT A WHOLE ONE is 10 (#115): it is there + # and nothing can be read out of it as a snapshot, which is what 10 says. Its + # fields used to come out EMPTY, and an empty state reached the verdict table + # as a word nobody wrote. + if ! lane_sidecar_schema_ok "$lsr_f"; then + lsr_schema="$(lane_sidecar_field "$lsr_f" schema 2>/dev/null || :)" + [ "$lsr_schema" != "$LANE_STATE_SCHEMA" ] || return 10 + printf 'state\tUNKNOWN-SCHEMA\n'; printf 'schema\t%s\n' "${lsr_schema:-<none>}" + printf 'file\t%s\n' "$lsr_f"; return 0 + fi + for lsr_k in state generation operation owner agent profile workstation kind updated lane; do + printf '%s\t%s\n' "$lsr_k" "$(lane_sidecar_field "$lsr_f" "$lsr_k")" + done + printf 'file\t%s\n' "$lsr_f" + return 0 +} + +# One field of it, for the callers that want exactly one. +lane_state_of() { # <lane> <key> + lso_out=""; lso_rc=0 + lso_out="$(lane_state_read "${1-}")" || lso_rc=$? + [ "$lso_rc" = 0 ] || return "$lso_rc" + printf '%s\n' "$lso_out" | awk -F'\t' -v k="${2-}" '$1 == k { print $2; exit }' +} + +# THE SNAPSHOT, WRITTEN — the ONE writer, and every caller reaches it through +# `set-lane-state`. `lsw_*` are its fields; an empty one is written as `none`, +# which is an ANSWER and not a gap, on the same argument Amendment 17(b) gives +# its `transcript` sub-field. +lane_state_put() { # <root> <lane> <state> <gen> <op> <owner> <agent> <profile> <ws> <kind> + lsw_root="$1"; lsw_lane="$2"; lsw_state="$3"; lsw_gen="$4"; lsw_op="$5" + lsw_owner="$6"; lsw_agent="$7"; lsw_prof="$8"; lsw_ws="$9"; shift 9; lsw_kind="${1-}" + { printf 'schema: %s\n' "$LANE_STATE_SCHEMA" + printf 'lane: %s\n' "$(lane_sidecar_value "$lsw_lane")" + printf 'state: %s\n' "$lsw_state" + printf 'generation: %s\n' "$lsw_gen" + printf 'operation: %s\n' "${lsw_op:-none}" + printf 'owner: %s\n' "${lsw_owner:-none}" + printf 'agent: %s\n' "${lsw_agent:-none}" + printf 'profile: %s\n' "${lsw_prof:-none}" + printf 'workstation: %s\n' "${lsw_ws:-none}" + printf 'kind: %s\n' "${lsw_kind:-none}" + printf 'updated: %s\n' "$(utc_now)" + } | lane_sidecar_put "$lsw_root/lane-state.yaml" +} + +# THE SNAPSHOT AS IT STOOD BEFORE THE LINE WAS WRITTEN. `write_event` takes this +# BEFORE it appends anything and hands it to the follow-up below, which is the +# only way that follow-up can tell *I am the newest act on this lane* from *I am +# a delayed act whose lane has moved on since*. A lane with no control root +# answers the same `none/0/none` a lane with no snapshot does: nothing to +# compare, and nothing to overwrite either. +lane_state_preimage() { # <lane> <payload> + lsp_root=""; lsp_prc=0 + lsp_root="$(lane_control_root "${1-}" "${2-}")" || lsp_prc=$? + [ "$lsp_prc" = 0 ] || { printf 'none/0/none\n'; return 0; } + lane_state_fingerprint "$lsp_root/lane-state.yaml" +} + +# THE LINE THAT WAS WRITTEN IS WHAT MOVES THE SNAPSHOT, and this is where the +# two are kept from disagreeing: it is called by `write_event`, from any +# caller, after the log line has landed. It NEVER fails the event: a lane with +# no control root is silent, because a lane that has not started under Amendment +# 11 has no directory to derive one from and that is the ordinary pre-cutover +# case. +# +# IT IS SERIALIZED AND IT IS FENCED (Copilot round 5 on openRepoTools#97). What +# a confirmed `STARTED`/`RESUMED` is entitled to overwrite is the state THIS +# WRITE SAW — advancing the generation over a `SWAPPING` it superseded is the +# whole point of writing it — and what it is never entitled to overwrite is a +# state that arrived AFTER it. The two are the same act read at different +# moments, so they are told apart the only way they can be: the snapshot is read +# under the same mutex `set-lane-state` takes, and compared with the pre-image +# `write_event` took before this event's own line landed. Unequal means another +# act moved the lane while this one was being written — a recovery, a handoff, +# an `ENDED` from elsewhere — and a delayed `RUNNING` or `CLOSED` written over +# it would be exactly the overwrite the generation exists to refuse. Nothing is +# written then, and the lane is NAMED so a person can read it. +# +# THE MUTEX IS TAKEN WITHOUT DYING FOR IT. `write_event` has already released it +# and its line is already committed: a `die` here would abort a caller whose +# work is on disk, so a mutex nobody could take within 20s costs the snapshot +# and says so, never the event. +# +# AND IT WRITES ONLY FOR A LEGACY LANE, ON EVIDENCE IT WAS HANDED (ruling +# 2026-10-04, design decision 21). Three things must all hold before the +# snapshot moves — `RUNNING` for a `STARTED`/`RESUMED`, `CLOSED` for an +# `ENDED`/`RETIRED`: +# * the verb is one of those four; +# * the caller's seam read said 8 — this lane carries no managed-owner +# marker and no vocabulary of one — because a managed lane's lifecycle is +# the managed ledger's and an unknown one is nobody's to write; +# * a pre-image was taken before the line was written and the snapshot still +# matches it under the mutex. +# A missing verdict or a missing pre-image is NOT a pass: it writes nothing, +# because a caller that did not ask is not a caller that was told "legacy". +lane_state_follow() { # <lane> <verb> <payload> <uuid> <pre-image> <seam verdict> + lsf_lane="${1-}"; lsf_verb="${2-}"; lsf_pay="${3-}"; lsf_uuid="${4-}"; lsf_pre="${5-}" + lsf_seam="${6-}" + lsf_new="" + case "$lsf_verb" in + STARTED|RESUMED) lsf_new=RUNNING ;; + ENDED|RETIRED) lsf_new=CLOSED ;; + *) return 0 ;; + esac + [ "$lsf_seam" = 8 ] || return 0 + [ -n "$lsf_pre" ] || return 0 + lsf_root=""; lsf_rc=0 + lsf_root="$(lane_control_root "$lsf_lane" "$lsf_pay")" || lsf_rc=$? + [ "$lsf_rc" = 0 ] || return 0 + lsf_f="$lsf_root/lane-state.yaml" + lsf_own=0 + if [ "$LOCK_HELD" != 1 ]; then + if lock_try 20; then + lsf_own=1 + else + note "the lane lifecycle snapshot for $lsf_lane was NOT moved to $lsf_new: $LOCK is held by another lanes-edit run and this follow-up will not wait behind an event that has already landed. The $lsf_verb line itself is written; the snapshot is one act behind until the next transition, and \`lanes-edit.sh lane-reconcile $lsf_lane\` says what it holds." + return 0 + fi + fi + # A SNAPSHOT THIS HELPER CANNOT READ IS ONE IT MUST NOT REPLACE. + if ! lane_sidecar_schema_ok "$lsf_f"; then + if [ "$lsf_own" = 1 ]; then release_lock; fi + note "the lane lifecycle snapshot at $lsf_f is not a record this helper can read ($LSS_WHY), so the $lsf_verb line landed and NOTHING was written over that file: a record this helper cannot read is one it cannot safely replace. Upgrade this workstation's lanes-edit.sh if a newer tooling wrote it, or read the file by hand." + return 0 + fi + lsf_seen="$(lane_state_fingerprint "$lsf_f")" + if [ "$lsf_seen" != "$lsf_pre" ]; then + if [ "$lsf_own" = 1 ]; then release_lock; fi + note "the lane lifecycle moved under this $lsf_verb: lane $lsf_lane read '$lsf_pre' (state/generation/operation) when this write began and reads '$lsf_seen' now, so the snapshot is LEFT AS IT IS and no $lsf_new was written over it. Another act got there first — a recovery, or a second handoff — and a delayed write is precisely what the generation exists to refuse. The $lsf_verb line itself landed: read the lane with \`lanes-edit.sh lane-reconcile $lsf_lane\` before relaunching anything." + return 0 + fi + lsf_gen="$(lane_sidecar_field "$lsf_f" generation 2>/dev/null || :)" + case "$lsf_gen" in ''|*[!0-9]*) lsf_gen=0 ;; esac + lsf_gen=$((lsf_gen + 1)) + lsf_agent="$(payload_subfield "$lsf_pay" agent)" + lsf_prof="$(payload_subfield "$lsf_pay" profile)" + if lane_state_put "$lsf_root" "$lsf_lane" "$lsf_new" "$lsf_gen" "$(lane_op_id)" \ + "$lsf_uuid" "${lsf_agent:-}" "${lsf_prof:-}" "$WS" ""; then + if [ "$lsf_own" = 1 ]; then release_lock; fi + LANES_INDEX_NUDGE_INV=1 # opensoft/openRepoTools#161: the table follows it + return 0 + fi + if [ "$lsf_own" = 1 ]; then release_lock; fi + note "the lane lifecycle snapshot at $lsf_f could NOT be written (the $lsf_verb line itself landed). Crash recovery for lane $lsf_lane is incomplete until it can be: see \`lanes-edit.sh lane-reconcile $lsf_lane\`" + return 0 +} + +# A RENAMED LANE KEEPS ITS LIFECYCLE (Amendment 16, openRepoTools#91). The +# control root is keyed by the lane's NAME — `<parent>/.lane-state/<lane>` on +# every rung — and `rename-lane` moves the row, the log, the handoff and the +# alias table but knew nothing of this directory, so a renamed lane's snapshot +# and inventory were left under a name every reader now resolves away from, and +# its next reconciliation read `no-state`: the one answer a launcher goes past. +# The directory is MOVED, never copied (two snapshots of one lane would be two +# answers), only after the rename's commit returned 0, and never over anything +# already at the new name, which is reported for a person rather than merged. +# The diagnostic files' `lane:` line keeps the old name until the next write; +# their readers do not key on it. Completed restart history is different: its +# strict reader keys on the lane and its launch facts describe the old name. +# Keep that history at the old root and move only the diagnostic files beside +# it. The new canonical lane has no inherited restart operation. +lane_state_rename() { # <the old name's control root> <new lane> + lsn_old="${1-}"; lsn_new="${2-}" + [ -n "$lsn_old" ] && [ -n "$lsn_new" ] || return 0 + [ -e "$lsn_old" ] || [ -L "$lsn_old" ] || return 0 + lsn_to="${lsn_old%/*}/$lsn_new" + [ "$lsn_to" != "$lsn_old" ] || return 0 + # A RENAME BY CASE ALONE is the same directory on a case-insensitive file + # system (macOS's default), where the target "exists" because it is the + # source; it goes through a temporary name so it lands on every file system. + if [ "$(lc "${lsn_old##*/}")" = "$(lc "$lsn_new")" ]; then + lsn_tmp="$lsn_old.rename.$$" + if mv -- "$lsn_old" "$lsn_tmp" 2>/dev/null && mv -- "$lsn_tmp" "$lsn_to" 2>/dev/null; then + LANES_INDEX_NUDGE_INV=1 + note "the lane lifecycle snapshot and inventory moved with the rename: $lsn_old → $lsn_to" + else + note "the lane lifecycle snapshot and inventory could NOT be moved from $lsn_old to $lsn_to (the rename itself has landed). Move it by hand; until then \`lanes-edit.sh lane-reconcile $lsn_new\` reads no snapshot for this lane." + fi + return 0 + fi + if [ -e "$lsn_to" ] || [ -L "$lsn_to" ]; then + note "the lane lifecycle snapshot and inventory were NOT moved: $lsn_old is the old name's and $lsn_to already exists for the new one, and two records of one lane are not merged here. Read both and keep one by hand; the rename itself has landed." + return 0 + fi + if [ -e "$lsn_old/restart-intent.yaml" ] || [ -L "$lsn_old/restart-intent.yaml" ]; then + # rename-lane has already refused unfinished or unreadable restart records + # under the mutex. Preserve the completed record byte for byte, as before + # the diagnostic lifecycle was added; do not reinterpret it as a new lane. + if ! (umask 077; mkdir -- "$lsn_to") 2>/dev/null; then + note "the diagnostic control root could NOT be made at $lsn_to (the rename itself has landed). Completed restart history remains at $lsn_old." + return 0 + fi + # The inventory moves here as well, even when only part of it does, so the + # worktrees table follows it (opensoft/openRepoTools#161). A sync with + # nothing changed writes nothing. + LANES_INDEX_NUDGE_INV=1 + for lsn_part in lane-state.yaml trees; do + if [ -e "$lsn_old/$lsn_part" ] || [ -L "$lsn_old/$lsn_part" ]; then + if ! mv -- "$lsn_old/$lsn_part" "$lsn_to/$lsn_part" 2>/dev/null; then + note "the diagnostic $lsn_part could NOT be moved to $lsn_to (the rename itself has landed). Read both roots before reconciliation. Completed restart history remains at $lsn_old." + return 0 + fi + fi + done + note "the lane lifecycle snapshot and inventory moved to $lsn_to; completed restart history remains at $lsn_old" + return 0 + fi + if mv -- "$lsn_old" "$lsn_to" 2>/dev/null; then + LANES_INDEX_NUDGE_INV=1 + note "the lane lifecycle snapshot and inventory moved with the rename: $lsn_old → $lsn_to" + else + note "the lane lifecycle snapshot and inventory could NOT be moved from $lsn_old to $lsn_to (the rename itself has landed). Move it by hand; until then \`lanes-edit.sh lane-reconcile $lsn_new\` reads no snapshot for this lane." + fi + return 0 +} + +# ------------------------------------------------- the worktree inventory +# +# A TREE ID IS DERIVED FROM ITS PATH AND FROM NOTHING ELSE, so that a branch +# renamed under a writer does not rename the record of the tree it is on: a +# `cksum` of the WHOLE absolute path, then the path with every character outside +# the manifest-key set folded to `-`, which a reader recognises. The fold alone +# is NOT one name per path (Codex on ec9847e, PR #97): `…/a+b` and `…/a-b` fold +# to the same name, and recording the second would replace the first tree's +# sidecar and lose its last observation without a word. The checksum in front +# of EVERY id is what keeps two paths two records; the fold is for a person. +tree_id_for() { # <absolute worktree path> + tif_p="$(printf '%s' "${1-}" | tr -c 'A-Za-z0-9._-' '-' | tr -s '-')" + while [ "${tif_p#-}" != "$tif_p" ]; do tif_p="${tif_p#-}"; done + while [ "${tif_p%-}" != "$tif_p" ]; do tif_p="${tif_p%-}"; done + tif_c="$(printf '%s' "${1-}" | cksum | awk '{print $1}')" + # AND IT CAN NEVER OUTGROW A FILE NAME. A path deep enough to make this + # longer than the 255 bytes most filesystems take is a tree whose sidecar + # could not be created at all — silently, since the failure would be the + # shell's `>` and not this function's. The tail is what a reader recognises, + # so the head is what is dropped. + if [ "${#tif_p}" -gt 180 ]; then + tif_p="$(printf '%s' "$tif_p" | tail -c 180)" + fi + printf 'c%s-%s\n' "$tif_c" "$tif_p" +} + +# ONE TREE'S SIDECAR. Every field is an OBSERVATION and none of them is truth +# about git: `lane-reconcile` recomputes all of them and reports the +# difference, which is the whole of design decision 6. +lane_tree_put() { # <root> <lane> <path> <checkout> <branch> <head> <upstream> <dirty> <unpushed> <writer> <gen> <op> + ltp_root="$1"; ltp_lane="$2"; ltp_path="$3"; ltp_co="$4"; ltp_branch="$5" + ltp_head="$6"; ltp_up="$7"; ltp_dirty="$8"; ltp_unp="$9"; shift 9 + ltp_writer="${1-}"; ltp_gen="${2-}"; ltp_op="${3-}" + ltp_id="$(tree_id_for "$ltp_path")" + [ -n "$ltp_id" ] || return 1 + { printf 'schema: %s\n' "$LANE_STATE_SCHEMA" + printf 'lane: %s\n' "$(lane_sidecar_value "$ltp_lane")" + printf 'tree: %s\n' "$ltp_id" + printf 'path: %s\n' "$(lane_sidecar_value "$ltp_path")" + printf 'checkout: %s\n' "$(lane_sidecar_value "${ltp_co:-unknown}")" + printf 'branch: %s\n' "$(lane_sidecar_value "${ltp_branch:-unknown}")" + printf 'head: %s\n' "$(lane_sidecar_value "${ltp_head:-unknown}")" + printf 'upstream: %s\n' "$(lane_sidecar_value "${ltp_up:-none}")" + printf 'dirty: %s\n' "${ltp_dirty:-0}" + printf 'unpushed: %s\n' "${ltp_unp:-0}" + printf 'writer: %s\n' "${ltp_writer:-none}" + printf 'generation: %s\n' "${ltp_gen:-0}" + printf 'operation: %s\n' "${ltp_op:-none}" + printf 'observed: %s\n' "$(utc_now)" + } | lane_sidecar_put "$ltp_root/trees/$ltp_id.yaml" +} + +# EVERY RECORDED TREE, ONE PER LINE, US-separated: +# <id><US><path><US><branch><US><head><US><upstream><US><dirty><US><unpushed><US><writer><US><observed><US><checkout><US><generation><US><operation><US><schema> +# 0 with rows, 8 with none, 1 where no control root could be derived, 10 where +# the `trees` directory is there and cannot be listed. +# +# THAT 10 IS NOT AN 8 (#157 item 4e). A directory this process may not read or +# search yields an empty glob, which read as a lane that recorded no tree — the +# unreadable sidecar's rule above, one level up. `worktree_rows` already tells +# the two apart before it asks; `lane-trees` and its callers now can too. +# +# THE LAST THREE ARE NEW AND THEY ARE AT THE END (Copilot round 5 on +# openRepoTools#97): the fence the observation was RECORDED UNDER, and the +# schema the sidecar itself carries. A reader written against the ten fields +# that were here first still reads those ten. The fence is here because it was +# written into the file and read by nothing — so a poll filed by an operation a +# recovery has since superseded looked exactly like the current one. +# +# AND A SIDECAR THIS READER DOES NOT KNOW IS SAID, NEVER PARSED. Until this +# round every `*.yaml` under `trees/` was read field by field whatever it +# claimed to be, which is the fail-closed contract `lane_state_read` keeps for +# the snapshot broken for the inventory beside it: a record written by a newer +# tooling would have been reported as an ordinary observation of a tree, in +# fields this reader was guessing at. Its id, its path and its schema are +# printed — the three a person needs to find it — and every other field is +# EMPTY, which `lane_reconcile` reports as `unknown-schema` rather than +# recomputing against. A record of THIS schema that is not a whole one is the +# same row with the schema `<malformed>` (#115), and `lane_reconcile` reports +# it as `malformed-sidecar`. +# +# An optional payload carrying the lane's `dir` is `lane_control_root`'s, as +# `lane_state_read` takes it (review r2 of #289, SHOULD-A). +lane_trees_list() { # <lane> [<a payload that may carry `dir`>] + ltl_root=""; ltl_rc=0; ltl_n=0 + ltl_root="$(lane_control_root "${1-}" "${2-}")" || ltl_rc=$? + [ "$ltl_rc" = 0 ] || return 1 + [ -d "$ltl_root/trees" ] || return 8 + [ -r "$ltl_root/trees" ] && [ -x "$ltl_root/trees" ] || return 10 + for ltl_f in "$ltl_root"/trees/*.yaml; do + [ -e "$ltl_f" ] || [ -L "$ltl_f" ] || continue + ltl_n=$((ltl_n + 1)) + # A SIDECAR THAT IS THERE AND CANNOT BE READ IS NOT AN ABSENT ONE (Codex on + # ec9847e, PR #97). It was skipped, so a permission or an I/O error — or a + # dangling link — made the only record of a tree's location and its dirty + # state vanish, and a lane whose one sidecar it was read as having no + # inventory at all. It is a row of its own, named by its file and carrying + # no field, which `lane_reconcile` reports as `unreadable-sidecar`. + if [ ! -r "$ltl_f" ]; then + ltl_id="${ltl_f##*/}"; ltl_id="${ltl_id%.yaml}" + printf '%s\n' "$ltl_id$US$US$US$US$US$US$US$US$US$US$US$US<unreadable>" + continue + fi + ltl_s="$(lane_sidecar_field "$ltl_f" schema 2>/dev/null || :)" + ltl_id="$(lane_sidecar_field "$ltl_f" tree 2>/dev/null || :)" + ltl_p="$(lane_sidecar_field "$ltl_f" path 2>/dev/null || :)" + if [ "$ltl_s" != "$LANE_STATE_SCHEMA" ]; then + # The file name is the id where the record cannot be trusted to name it: + # a row with no id at all is one `lane_reconcile` skips, and a sidecar + # nobody can account for is the opposite of what this round is about. + [ -n "$ltl_id" ] || { ltl_id="${ltl_f##*/}"; ltl_id="${ltl_id%.yaml}"; } + printf '%s\n' "$ltl_id$US$ltl_p$US$US$US$US$US$US$US$US$US$US$US${ltl_s:-<none>}" + continue + fi + # AND A RECORD OF THIS SCHEMA THAT IS NOT A WHOLE ONE IS SAID, NEVER READ + # (#115). A truncated `schema: 1` file came out as a row of empty fields — + # an EMPTY ID, which `lane_reconcile` skipped outright, and an empty dirty + # and unpushed, which it read as 0 and 0: a vanished tree that held work + # reported `missing`, clean and published. Its id is its FILE NAME, because + # the one it claims is not to be trusted, the path it records is kept so + # the tree is still named once, and every other field is empty under the + # schema `<malformed>`. + if ! lane_sidecar_schema_ok "$ltl_f"; then + ltl_id="${ltl_f##*/}"; ltl_id="${ltl_id%.yaml}" + printf '%s\n' "$ltl_id$US$ltl_p$US$US$US$US$US$US$US$US$US$US$US<malformed>" + continue + fi + printf '%s\n' "$ltl_id$US$ltl_p\ +$US$(lane_sidecar_field "$ltl_f" branch)\ +$US$(lane_sidecar_field "$ltl_f" head)\ +$US$(lane_sidecar_field "$ltl_f" upstream)\ +$US$(lane_sidecar_field "$ltl_f" dirty)\ +$US$(lane_sidecar_field "$ltl_f" unpushed)\ +$US$(lane_sidecar_field "$ltl_f" writer)\ +$US$(lane_sidecar_field "$ltl_f" observed)\ +$US$(lane_sidecar_field "$ltl_f" checkout)\ +$US$(lane_sidecar_field "$ltl_f" generation)\ +$US$(lane_sidecar_field "$ltl_f" operation)\ +$US$ltl_s" + done + [ "$ltl_n" -gt 0 ] || return 8 + return 0 +} + +# ------------------------------------------------ resume-time reconciliation +# +# IT REPORTS AND IT RESETS NOTHING. AGENTS.md rule 1 is the estate's: *"`park` +# CREATES NOTHING and `resume` RESETS NOTHING"*, and never a `git reset`, a +# `git stash`, a `git checkout -f` or a `worktree add --force` to make the next +# run succeed. So this read runs `git status`, `git log @{u}..`, `git rev-parse` +# and `git worktree list --porcelain` and NOTHING ELSE, names the act a person +# takes, and leaves every tree exactly as it found it — a missing tree included, +# whose rebuild is the estate's own `resume <Name>` and is a person's to run. + +# ONE PATH, ONE SPELLING — the physical one, or the path itself where it cannot +# be resolved (a path that is gone still has to be comparable). +# +# THE REPORT READS THREE SOURCES AND THEY DO NOT AGREE ABOUT SPELLING. A sidecar +# holds the path the poll was given, `git worktree list --porcelain` answers with +# the PHYSICAL path, and the on-disk sweep walks the recorded `dir`. Every estate +# with a `projects` symlink reaches its checkouts through it — and on macOS +# `$TMPDIR` and `$HOME` are under `/var`, which IS a symlink to `/private/var`, +# which is how four cases of this section went red on that runner alone at +# `612ba5c` (`expected [dirty], got [dirty unmanaged]`): every tree was reported +# TWICE, once as the tree it is and once as a tree nobody manages. `612ba5c` +# resolved the lane's OWN checkout for exactly this reason and left the trees +# under it unresolved. `cd -P` is the portable resolver, for the reason +# `lane-start`'s `real_of` gives: `readlink -f` is not in the stock macOS +# userland. +lane_real_path() { # <path> + lrp_p="${1-}" + [ -n "$lrp_p" ] || return 0 + lrp_r="$( CDPATH=''; cd -P -- "$lrp_p" 2>/dev/null && pwd -P )" || lrp_r="" + printf '%s\n' "${lrp_r:-$lrp_p}" +} + +# THE LANE'S TWO WORKTREE ROOTS — the same two `lane-handoff` polls, and they +# are here rather than there so the poll and the reconciliation cannot come to +# disagree about where a lane keeps its writers. Where the lane's checkout is an +# ASSEMBLY (T018) both also read its paired root, `<assembly>/worktrees/ +# <feature>/<each leg's path>`, which is two levels deep and per feature, so it +# is read beside these two (`lane_reconcile`, step 4) rather than as a third. +lane_worktree_roots() { # <lane> <the lane's checkout> + lwr_lane="${1-}"; lwr_dir="${2-}" + [ -n "$lwr_dir" ] || return 0 + printf '%s/.claude/worktrees\n' "$lwr_dir" + printf '%s/.lane-worktrees/%s\n' "${lwr_dir%/*}" "$lwr_lane" + return 0 +} + +# What git says about one tree, NOW — +# `<branch><US><head><US><upstream><US><dirty><US><unpushed>` — and it is the ONE +# implementation of that sentence: `lane-reconcile` recomputes with it, +# `set-lane-tree` records through it and `lane-handoff` polls its writers with +# it, over the `lane-tree-now` arm below, so the WRITERS section a person reads +# and the sidecar a recovery reads can never be two different readings. +# +# 0 the five fields +# 1 there is no directory at that path +# 2 the path is there and git does not answer in it at all +# 3 GIT ANSWERED AND ONE OF THE READS FAILED, and NOTHING is printed +# +# THE 3 IS THE WHOLE POINT OF THIS ROUND (Copilot round 5 on openRepoTools#97). +# Every read below used to end in `|| printf 'unknown'`, `|| printf 'none'` or +# an empty count that became `0` — so a repository whose object store is +# unreadable, whose index is locked or whose HEAD is corrupt produced a RECORD +# THAT LOOKED CLEAN AND PUBLISHED, and a later reconciliation comparing against +# it would call a tree holding work `missing` rather than `possible-loss`. A +# read that failed is never an answer (R22, Amendment 7(d)), so it is no longer +# converted into one: the caller is told the observation could not be made. +# +# TWO THINGS ARE ANSWERS AND NOT FAILURES, and they are named rather than +# guessed. A branch with NO COMMIT YET has `unborn` for a head — HEAD is a +# symbolic ref to a branch that does not exist, which is an ordinary state and +# not a broken repository. And a branch with NO UPSTREAM CONFIGURED has `none`, +# which is exactly the distinction the inventory records an upstream for. A +# branch whose upstream IS configured and whose remote-tracking ref is not here +# — the ordinary state of a branch whose remote was deleted after its merge — is +# the third: the configured spelling is recorded, and the count against a ref +# this checkout does not have is `unknown` rather than the `0` that reads as +# *everything is published*. +lane_tree_now() { # <path> + ltn_p="${1-}" + [ -d "$ltn_p" ] || return 1 + git -C "$ltn_p" rev-parse --git-dir >/dev/null 2>&1 || return 2 + ltn_raw=""; ltn_b=""; ltn_h=""; ltn_u=none; ltn_d=""; ltn_n=0 + ltn_s=""; ltn_up=""; ltn_cfg=""; ltn_rem=""; ltn_crc=0 + # THE BRANCH, AND THE UNBORN ONE `rev-parse` CANNOT ANSWER FOR. A branch with + # no commit yet is HEAD as a symbolic ref to a ref that does not exist, which + # `rev-parse --abbrev-ref` refuses exactly as it refuses a corrupt HEAD — + # `symbolic-ref` is what tells the two apart, and it is asked only where the + # first read failed, so an ordinary tree costs one git process as before. + if ltn_raw="$(git -C "$ltn_p" rev-parse --abbrev-ref HEAD 2>/dev/null)" && [ -n "$ltn_raw" ]; then + : + elif ltn_raw="$(git -C "$ltn_p" symbolic-ref --short -q HEAD 2>/dev/null)" && [ -n "$ltn_raw" ]; then + : + else + return 3 + fi + ltn_b="$ltn_raw"; [ "$ltn_b" = HEAD ] && ltn_b=detached + if ltn_h="$(git -C "$ltn_p" rev-parse --verify --quiet HEAD 2>/dev/null)"; then + [ -n "$ltn_h" ] || return 3 + elif git -C "$ltn_p" symbolic-ref -q HEAD >/dev/null 2>&1; then + ltn_h=unborn + else + return 3 + fi + ltn_s="$(git -C "$ltn_p" status --short 2>/dev/null)" || return 3 + ltn_d="$(printf '%s\n' "$ltn_s" | awk 'NF { n = n + 1 } END { print n + 0 }')" + if ltn_up="$(git -C "$ltn_p" rev-parse --abbrev-ref '@{u}' 2>/dev/null)" && [ -n "$ltn_up" ]; then + ltn_u="$ltn_up" + ltn_n="$(git -C "$ltn_p" rev-list --count '@{u}..HEAD' 2>/dev/null)" || return 3 + case "$ltn_n" in ''|*[!0-9]*) return 3 ;; esac + elif [ "$ltn_b" != detached ]; then + # `git config --get` is 0 for found and 1 for NOT FOUND; anything else is + # the read itself failing, and that is a 3 like any other. + ltn_cfg="$(git -C "$ltn_p" config --get "branch.$ltn_raw.merge" 2>/dev/null)" || ltn_crc=$? + case "$ltn_crc" in 0|1) : ;; *) return 3 ;; esac + if [ -n "$ltn_cfg" ]; then + # AND THE REMOTE BESIDE IT IS ASKED THE SAME WAY (opensoft/openRepoTools + # #113 item 3). It ended in `|| :`, so a read that FAILED became an empty + # remote and `${ltn_rem:-.}` then FABRICATED the local upstream + # `./<merge>`, which was filed as an observation. Only a remote that is + # NOT CONFIGURED (1) keeps the `.` this read has always written for it. + ltn_rrc=0 + ltn_rem="$(git -C "$ltn_p" config --get "branch.$ltn_raw.remote" 2>/dev/null)" || ltn_rrc=$? + case "$ltn_rrc" in 0|1) : ;; *) return 3 ;; esac + ltn_u="${ltn_rem:-.}/${ltn_cfg#refs/heads/}" + ltn_n=unknown + fi + fi + printf '%s%s%s%s%s%s%s%s%s\n' "$ltn_b" "$US" "$ltn_h" "$US" "${ltn_u:-none}" "$US" \ + "${ltn_d:-0}" "$US" "$ltn_n" + return 0 +} + +# NO REPOSITORY AT ALL IS AN ABSENCE, and nothing else is: `lane-worktrees`' +# `no_repository`, the rule #170 G5 settled, so the two readers of one lane's +# checkout cannot disagree about it. A directory with a `.git` of its own IS a +# repository however broken — git answers "not a git repository" for a gitdir +# it cannot read too — and only git's own "not a git repository" for a +# directory with none is the answer "there is nothing registered here". That +# message is read in the C locale, as `lane-worktrees`' `git_env` reads it: a +# translated git would otherwise say it in words this match never finds, and the +# two readers would disagree (review r1 of #252). +lane_no_repository() { # <dir> + lnr_d="${1-}"; lnr_err="" + if [ -e "$lnr_d/.git" ] || [ -L "$lnr_d/.git" ]; then return 1; fi + if lnr_err="$(LC_ALL=C git -C "$lnr_d" rev-parse --git-dir 2>&1 >/dev/null </dev/null)"; then return 1; fi + case "$(printf '%s' "$lnr_err" | tr '[:upper:]' '[:lower:]')" in + *"not a git repository"*) return 0 ;; + esac + return 1 +} + +lane_reconcile() { # <lane> + lrc_lane="${1-}" + # 0. THE SEAM (ruling 2026-10-04): a managed-owned lane's lifecycle is the + # managed ledger's, so this legacy reconciliation reads nothing of it and + # pronounces nothing on it — no crash, no clearance, no closure. A lane whose + # ownership could not be read gets the same silence, as `indeterminate`. + lrc_mrc=0; lrc_mown="" + lrc_mown="$(lane_is_managed_owned "$lrc_lane")" || lrc_mrc=$? + case "$lrc_mrc" in + 0) + printf 'MANAGED%s%s\n' "$US" "${lrc_mown:-unnamed}" + printf 'VERDICT%smanaged-owned%slane %s is owned by the managed ledger (owner %s): its lifecycle and its worktrees are that ledger'"'"'s, and this legacy reconciliation pronounces nothing on them (ruling 2026-10-04: "managed ledger owns enrolled lanes; #97 owns legacy")\n' \ + "$US" "$US" "$lrc_lane" "${lrc_mown:-unnamed}" + return 0 ;; + 8) : ;; + *) + printf 'MANAGED%sunknown\n' "$US" + printf 'VERDICT%sindeterminate%swhether the managed ledger owns lane %s is UNKNOWN — its register row carries managed-owner vocabulary that does not parse, or the register could not be read — so nothing is pronounced on it (Amendment 7(d)). Read it: lanes-edit.sh managed-projection %s\n' \ + "$US" "$US" "$lrc_lane" "$lrc_lane" + return 0 ;; + esac + lrc_root=""; lrc_rc=0 + lrc_root="$(lane_control_root "$lrc_lane")" || lrc_rc=$? + if [ "$lrc_rc" != 0 ]; then + note "lane $lrc_lane has no control root: its record names no directory (Amendment 11(c)) and \$PROJECTS_ROOT is not a directory here, so there is nothing to reconcile against. This is the pre-cutover answer, not a failure — the lane's next start or handoff creates one." + return 8 + fi + + # 1. THE SNAPSHOT. + lrc_state=""; lrc_gen=""; lrc_op=""; lrc_owner=""; lrc_upd="" + lrc_snap=""; lrc_srrc=0 + lrc_snap="$(lane_state_read "$lrc_lane")" || lrc_srrc=$? + if [ "$lrc_srrc" = 0 ]; then + lrc_state="$(printf '%s\n' "$lrc_snap" | awk -F'\t' '$1 == "state" { print $2; exit }')" + lrc_gen="$(printf '%s\n' "$lrc_snap" | awk -F'\t' '$1 == "generation" { print $2; exit }')" + lrc_op="$(printf '%s\n' "$lrc_snap" | awk -F'\t' '$1 == "operation" { print $2; exit }')" + lrc_owner="$(printf '%s\n' "$lrc_snap" | awk -F'\t' '$1 == "owner" { print $2; exit }')" + lrc_upd="$(printf '%s\n' "$lrc_snap" | awk -F'\t' '$1 == "updated" { print $2; exit }')" + elif [ "$lrc_srrc" = 8 ]; then + lrc_state=NONE + else + # A SNAPSHOT THAT IS THERE AND COULD NOT BE READ IS NOT A LANE THAT HAS + # NONE (Copilot round 6 on openRepoTools#97). Every non-zero read used to + # land on `NONE` here, and `NONE` is the verdict `no-state` — *this lane + # never started under this capability, there is nothing to recover* — which + # a launcher answers by going straight on. That is fail-OPEN on a crash + # pronouncement, the one class this capability exists to close. A read + # nobody got is `indeterminate` below, exactly as an unreadable HOLDER is. + lrc_state=UNREADABLE + # AND ONE THAT OPENS AND IS NOT A WHOLE RECORD IS SAID AS SUCH (#115). It + # used to come out as fields that were EMPTY, and its empty state word was + # `unknown-state` by the `*)` arm below — failing safe by accident rather + # than by a check. The 10 is the same; the word says which of the two. + lrc_swhy="" + if [ "$lrc_srrc" = 10 ] && [ -r "$lrc_root/lane-state.yaml" ] \ + && ! lane_sidecar_schema_ok "$lrc_root/lane-state.yaml"; then + lrc_state=MALFORMED; lrc_swhy="$LSS_WHY" + fi + fi + printf 'ROOT%s%s\n' "$US" "$lrc_root" + printf 'STATE%s%s%sgeneration %s%soperation %s%sowner %s%supdated %s\n' \ + "$US" "$lrc_state" "$US" "${lrc_gen:-0}" "$US" "${lrc_op:-none}" "$US" \ + "${lrc_owner:-none}" "$US" "${lrc_upd:-never}" + + # 2. THE HOLDER. `live_holder`'s three answers are the contract every other + # caller here reads: 0 a holder, 8 none, anything else THE RECORDS COULD NOT + # BE READ — which is never "no holder" (R22, Amendment 7(d)). A holder that + # could not be established fails CLOSED: the verdict is `indeterminate` and + # no crash is pronounced on a read nobody got. + # AND THE SAME DISTINCTION ONE READ EARLIER (#113 item 1): the ids the row + # records. Both reads ended in `|| :`, so a register nobody could read came + # out as an EMPTY id set, `live_holder` answered 8 for it — this lane records + # no session, nothing can be live — and a crash was pronounced on a liveness + # question nobody answered. `session_ids_checked` is #67's read of the same + # published-union-local ids, and it tells the two apart: 8, no row or a row + # naming no session, goes on to `live_holder` exactly as before; 1, either + # copy of the register unread, never reaches it. + lrc_ids=""; lrc_irc=0; lrc_hwhy="" + lrc_ids="$(session_ids_checked "$lrc_lane")" || lrc_irc=$? + lrc_hold=""; lrc_hrc=0 + if [ "$lrc_irc" != 0 ] && [ "$lrc_irc" != 8 ]; then + lrc_hrc=1 + lrc_hwhy="lane $lrc_lane's register row could not be read — the published register, or this checkout's copy of it at $LANES_FILE — so which sessions it records is NOT established, and an id set nobody read is never an empty one" + else + lrc_hold="$(live_holder "$lrc_lane" "$lrc_ids" 2>/dev/null)" || lrc_hrc=$? + fi + case "$lrc_hrc" in + 0) printf 'HOLDER%slive%s%s\n' "$US" "$US" "$(printf '%s' "$lrc_hold" | tr "$US" ' ')" ;; + 8) printf 'HOLDER%snone\n' "$US" ;; + *) printf 'HOLDER%sunknown%s%s\n' "$US" "$US" "${lrc_hwhy:-${SESSION_FILES_ERR:-the session records of this workstation could not be read}}" ;; + esac + + # 2b. THE BINDING (Amendment 18(b)): *"Liveness is pronounced only from + # INSIDE the binding's own `host` and `container`, where the pid namespace is + # the record's: from anywhere else a binding is UNKNOWN, never dead."* The + # holder read above is THIS workstation's session records, so it says nothing + # about a lane whose last STARTED/RESUMED was written on another host or in + # another container — and this workstation's snapshot is this workstation's + # alone (design decision 10). Read through the same scan and the same + # locality rule `binding` and `holder_is_dead` use, with clause (b)'s one + # exception: a binding whose window is GONE from a shared tmux server is a + # dead binding, and then the local read above decides, as it does there. + # here the binding is this place's, or the lane's lines predate it + # free no binding is open (released, or never started) + # gone bound elsewhere on this host's tmux, and its window is gone + # elsewhere bound in a place this one cannot pronounce on + # unknown the object log could not be read for it (Amendment 7(d)) + lrc_bwhere=free; lrc_bat="" + lrc_bout=""; lrc_brc=0 + lrc_bout="$(lane_binding_scan "$lrc_lane")" || lrc_brc=$? + if [ "$lrc_brc" != 0 ]; then + lrc_bwhere=unknown + else + IFS="$US" read -r lrc_bst lrc_bhost lrc_bcont lrc_bwin lrc_butc lrc_bsess lrc_bos \ + lrc_brutc lrc_brsess lrc_brpay lrc_bxverb lrc_bxutc lrc_bxsess lrc_bxpay lrc_blegacy \ + lrc_bfverb lrc_bfutc lrc_bfsess lrc_bfpay <<LRC_BIND +$lrc_bout +LRC_BIND + case "$lrc_bst" in + bound|requested) + lrc_bat="${lrc_bhost:-unknown}/${lrc_bcont:-none}" + if binding_is_here "$lrc_bhost" "$lrc_bcont" "$lrc_blegacy"; then + lrc_bwhere=here + elif [ "$(binding_window_state "$lrc_bhost" "$lrc_bwin" "$lrc_blegacy")" = gone ]; then + lrc_bwhere=gone + else + lrc_bwhere=elsewhere + fi ;; + esac + fi + printf 'BINDING%s%s%s%s\n' "$US" "$lrc_bwhere" "$US" "${lrc_bat:-none}" + + # 3. THE TREES — the inventory, recomputed. A stored value is a COMPARISON + # POINT and never current truth. + # THE COORDINATOR DIRECTORY, AND A LOG NOBODY COULD READ IS NOT A LANE WITH + # NONE (Copilot on 64dfd97, PR #97). `lane_payload_field` answers 8 for a log + # that carries no `dir` and 1 for a log that could not be read; collapsed into + # one empty string, the second skipped both sweeps below — the registrations + # `git worktree list` holds and the trees on disk — and a SWAPPED lane with no + # holder then read as resumable over paths nobody inspected. The 1 is kept, + # and the verdict below is `indeterminate` for it. + lrc_dir=""; lrc_drc=0 + lrc_dir="$(lane_payload_field "$lrc_lane" dir 2>/dev/null)" || lrc_drc=$? + [ "$lrc_drc" = 0 ] || lrc_dir="" + lrc_seen=""; lrc_n=0; lrc_recover=0; lrc_dirty=0 + # AN INVENTORY NOBODY COULD LIST IS NOT AN EMPTY ONE (#113, the unreadable + # sidecar's rule one level up). `lane_trees_list` answers 10 for a `trees` + # directory that is there and cannot be listed (#157 item 4e), and this read + # ended in `|| :`, so every tree the lane recorded vanished from the report and + # its verdict could still be `resumable`. `lrc_unread` gathers what the + # inventory and the sweeps below could not read, and the verdict says so. + lrc_unread=""; lrc_tl=""; lrc_tlrc=0 + lrc_tl="$(lane_trees_list "$lrc_lane" 2>/dev/null)" || lrc_tlrc=$? + case "$lrc_tlrc" in + 0|8) : ;; + 10) lrc_unread="its worktree inventory directory $lrc_root/trees is there and could not be listed" ;; + *) lrc_unread="its worktree inventory could not be read (exit $lrc_tlrc)" ;; + esac + while IFS="$US" read -r lrc_id lrc_p lrc_b lrc_h lrc_u lrc_d lrc_np lrc_w lrc_ob lrc_co lrc_tg lrc_to lrc_sch; do + [ -n "${lrc_id:-}" ] || continue + lrc_n=$((lrc_n + 1)) + # BOTH SPELLINGS JOIN THE SEEN SET, because the two sweeps below compare + # against it with git's physical answer and with the recorded `dir`'s own, + # and a tree named under one spelling and skipped under neither is a tree + # reported twice. + [ -n "${lrc_p:-}" ] && lrc_seen="$lrc_seen $lrc_p $(lane_real_path "$lrc_p") " + # A SIDECAR THIS READER DOES NOT KNOW IS REPORTED AND NEVER RECOMPUTED + # AGAINST. `lane_trees_list` empties every field of one, because a value + # read out of a record whose shape this reader is guessing at is worse than + # no value: comparing git's answer to it would print a difference that means + # nothing. It counts as wanting recovery, because a person has to say what + # wrote it. + if [ "${lrc_sch:-}" = "<unreadable>" ]; then + printf 'TREE%s%s%sunreadable-sidecar%s%s%sits sidecar is there and could not be read, so the tree it records — where it is, and whether it held uncommitted or unpublished work — is NOT known, and nothing is assumed about it; read %s/trees/%s.yaml by hand before relaunching a writer\n' \ + "$US" "$lrc_id" "$US" "$US" "<no path read>" "$US" "$lrc_root" "$lrc_id" + lrc_recover=$((lrc_recover + 1)) + continue + fi + # A RECORD OF THIS SCHEMA THAT IS NOT A WHOLE ONE (#115) is reported as the + # unreadable one is: nothing is read out of it, it counts toward recovery, + # and the line says what is missing from it and names the file. + if [ "${lrc_sch:-}" = "<malformed>" ]; then + lrc_mwhy="the record could not be read again to say why" + if lane_sidecar_schema_ok "$lrc_root/trees/$lrc_id.yaml"; then :; else lrc_mwhy="$LSS_WHY"; fi + printf 'TREE%s%s%smalformed-sidecar%s%s%sits sidecar is of this schema and %s, so the tree it records — where it is, and whether it held uncommitted or unpublished work — is NOT known, nothing is assumed about it, and no writer replaces it; read %s/trees/%s.yaml by hand before relaunching a writer\n' \ + "$US" "$lrc_id" "$US" "$US" "${lrc_p:-<no path read>}" "$US" "$lrc_mwhy" "$lrc_root" "$lrc_id" + lrc_recover=$((lrc_recover + 1)) + continue + fi + if [ "${lrc_sch:-}" != "$LANE_STATE_SCHEMA" ]; then + printf 'TREE%s%s%sunknown-schema%s%s%sits sidecar records schema %s and this reader writes %s, so none of its fields is read and nothing is compared against them; the tree itself is untouched\n' \ + "$US" "$lrc_id" "$US" "$US" "${lrc_p:-<no path recorded>}" "$US" "${lrc_sch:-<none>}" "$LANE_STATE_SCHEMA" + lrc_recover=$((lrc_recover + 1)) + continue + fi + lrc_now=""; lrc_nrc=0 + lrc_now="$(lane_tree_now "$lrc_p")" || lrc_nrc=$? + if [ "$lrc_nrc" = 3 ]; then + # GIT ANSWERS THERE AND ONE OF ITS READS FAILED. Nothing is assumed: not + # clean, not dirty, not published. The tree is left exactly as it is and + # the person is sent to it. + printf 'TREE%s%s%sunreadable%s%s%sgit answers in this path and one of the reads an observation is made of failed, so NOTHING is assumed about it — it was branch %s head %s with %s dirty and %s unpushed at %s; read it by hand (git -C %s status) before relaunching a writer onto it\n' \ + "$US" "$lrc_id" "$US" "$US" "$lrc_p" "$US" "$lrc_b" "$lrc_h" "${lrc_d:-0}" "${lrc_np:-0}" "$lrc_ob" "$lrc_p" + lrc_recover=$((lrc_recover + 1)) + continue + fi + if [ "$lrc_nrc" = 1 ]; then + # THE PATH IS GONE. Whether that is a tidy removal or a loss is decided + # by what the sidecar last SAW there, and metadata can reconstruct no + # file's contents: a tree that held uncommitted or unpublished work is + # POSSIBLE LOSS and is never claimed to be rebuildable. + case "${lrc_d:-0}${lrc_np:-0}" in + 00) printf 'TREE%s%s%smissing%s%s%swas branch %s head %s; clean and published at %s; the estate parked record and `resume <Name>` are the only rebuild\n' \ + "$US" "$lrc_id" "$US" "$US" "$lrc_p" "$US" "$lrc_b" "$lrc_h" "$lrc_ob" ;; + *) printf 'TREE%s%s%spossible-loss%s%s%swas branch %s head %s with %s dirty and %s unpushed at %s; NOTHING here can reconstruct uncommitted files — do not recreate this path\n' \ + "$US" "$lrc_id" "$US" "$US" "$lrc_p" "$US" "$lrc_b" "$lrc_h" "$lrc_d" "$lrc_np" "$lrc_ob" ;; + esac + lrc_recover=$((lrc_recover + 1)) + continue + fi + if [ "$lrc_nrc" = 2 ]; then + printf 'TREE%s%s%snot-a-checkout%s%s%sthe path exists and git does not answer in it; it is left exactly as it is\n' \ + "$US" "$lrc_id" "$US" "$US" "$lrc_p" "$US" + lrc_recover=$((lrc_recover + 1)) + continue + fi + lrc_nb="$(printf '%s' "$lrc_now" | awk -F"$US" '{print $1}')" + lrc_nh="$(printf '%s' "$lrc_now" | awk -F"$US" '{print $2}')" + lrc_nu="$(printf '%s' "$lrc_now" | awk -F"$US" '{print $3}')" + lrc_nd="$(printf '%s' "$lrc_now" | awk -F"$US" '{print $4}')" + lrc_nn="$(printf '%s' "$lrc_now" | awk -F"$US" '{print $5}')" + lrc_class=ok + [ "${lrc_nd:-0}" -gt 0 ] && lrc_class=dirty + # `unpushed` IS A COUNT OR IT IS THE WORD `unknown`, and the word is what a + # branch whose configured upstream is not in this checkout answers. It is + # never compared as a number, and it counts as work that may not be + # published rather than as nothing to publish. + case "${lrc_nn:-0}" in + ''|0) : ;; + *[!0-9]*) + if [ "$lrc_class" = dirty ]; then lrc_class=dirty+unpushed-unknown; else lrc_class=unpushed-unknown; fi ;; + *) + if [ "$lrc_class" = dirty ]; then lrc_class=dirty+unpushed; else lrc_class=unpushed; fi ;; + esac + [ "$lrc_class" = ok ] || lrc_dirty=$((lrc_dirty + 1)) + lrc_moved="" + [ "$lrc_nb" = "$lrc_b" ] || lrc_moved="$lrc_moved; branch was $lrc_b and is $lrc_nb" + [ "$lrc_nh" = "$lrc_h" ] || lrc_moved="$lrc_moved; head was $lrc_h and is $lrc_nh" + [ "${lrc_nu:-none}" = "${lrc_u:-none}" ] || lrc_moved="$lrc_moved; upstream was ${lrc_u:-none} and is ${lrc_nu:-none}" + # AND WHICH TRANSITION TOOK THE OBSERVATION, where it is not this lane's + # current one. The pair was written into every sidecar and read by nothing + # until this round, so a poll filed by an operation a recovery has since + # superseded read exactly like the current one. + if [ -n "${lrc_tg:-}" ] && [ "$lrc_tg" != 0 ] && [ "$lrc_tg" != "${lrc_gen:-0}" ]; then + lrc_moved="$lrc_moved; observed under generation $lrc_tg (operation ${lrc_to:-none}) and this lane is at generation ${lrc_gen:-0}" + fi + printf 'TREE%s%s%s%s%s%s%sbranch %s head %s upstream %s %s dirty %s unpushed; observed %s at %s%s\n' \ + "$US" "$lrc_id" "$US" "$lrc_class" "$US" "$lrc_p" "$US" \ + "$lrc_nb" "$lrc_nh" "${lrc_nu:-none}" "${lrc_nd:-0}" "${lrc_nn:-0}" \ + "${lrc_d:-0}/${lrc_np:-0}" "$lrc_ob" "$lrc_moved" + done <<EOF +$lrc_tl +EOF + + # 4. WHAT IS THERE AND IS IN NO SIDECAR — from git's own registrations and + # from the two lane roots on disk. It is REPORTED and never adopted, deleted + # or overwritten: which lane a tree belongs to is a person's to say. + lrc_unmanaged=0 + # A TRIAD (opensoft/openRepoTools#186, plan task T018). WHERE THE LANE'S + # CHECKOUT IS AN ASSEMBLY — its own `project.yaml` declares a leg other than + # itself, read by `assembly_legs`, the one reader every lane tool asks — what + # its LEGS hold is read too: the worktrees git registers in each leg's + # repository, which `git worktree list` in the assembly never names, and the + # paired feature trees `<assembly>/worktrees/<feature>/<each leg's path>`. + # Both are reported exactly as the checkout's own registrations and the lane + # roots are, and adopted, deleted or overwritten no more. A checkout with no + # `project.yaml` is asked nothing, so its report is what it always was; a + # manifest, a leg's registrations or the paired root that could not be read + # leaves paths nobody read, and the verdict below says so. + lrc_legs=""; lrc_lgrc=8; lrc_legwhy=""; lrc_tab="$(printf '\t')" + if [ -n "$lrc_dir" ] && [ -d "$lrc_dir" ] && { [ -e "$lrc_dir/project.yaml" ] || [ -L "$lrc_dir/project.yaml" ]; }; then + lrc_lgrc=0 + lrc_legs="$(assembly_legs "$lrc_dir")" || lrc_lgrc=$? + fi + if [ -n "$lrc_dir" ] && [ -d "$lrc_dir" ]; then + # THE CHECKOUT'S OWN ROW IS NOT AN UNMANAGED TREE, AND git ANSWERS WITH THE + # PHYSICAL PATH. A recorded `dir` reached through a symlink — which is how + # every estate with a `projects` link spells it — would otherwise not match + # the first row of `worktree list` and the lane's own checkout would be + # reported as a tree nobody manages. `cd -P` is the portable resolver here + # for the reason `lane-start`'s `real_of` gives: `readlink -f` is not in the + # stock macOS userland. + lrc_dirp="$(lane_real_path "$lrc_dir")" + # THE REGISTRATIONS ARE A READ, AND ITS STATUS IS KEPT (#113 item 4). It + # ended in `|| :`, so a checkout whose registrations could not be read was + # one with none: every stale registration and every unmanaged tree in it + # was omitted, the verdict could still read `resumable`, and the estate's + # own `resume` then failed on the registration the report never named. A + # directory that is NO repository at all registers nothing, and that alone + # is an absence (`lane_no_repository`, `lane-worktrees`' rule). + lrc_wlo=""; lrc_wlrc=0 + lrc_wlo="$(git -C "$lrc_dir" worktree list --porcelain 2>/dev/null </dev/null)" || lrc_wlrc=$? + if [ "$lrc_wlrc" != 0 ] && lane_no_repository "$lrc_dir"; then lrc_wlrc=0; lrc_wlo=""; fi + if [ "$lrc_wlrc" != 0 ]; then + lrc_unread="${lrc_unread:+$lrc_unread; }the worktree registrations of $lrc_dir could not be read (git worktree list exited $lrc_wlrc)" + fi + while IFS= read -r lrc_wl; do + case "$lrc_wl" in worktree\ *) : ;; *) continue ;; esac + lrc_wp="${lrc_wl#worktree }" + [ "$lrc_wp" = "$lrc_dir" ] && continue + [ -n "$lrc_dirp" ] && [ "$lrc_wp" = "$lrc_dirp" ] && continue + # AND THE SIDECARS ARE ASKED UNDER BOTH SPELLINGS, for the same reason. + lrc_wpr="$(lane_real_path "$lrc_wp")" + case "$lrc_seen" in *" $lrc_wp "*|*" $lrc_wpr "*) continue ;; esac + if [ -d "$lrc_wp" ]; then + printf 'TREE%s%s%sunmanaged%s%s%sgit registers it in %s and no sidecar of this lane names it; it is left exactly as it is\n' \ + "$US" "$(tree_id_for "$lrc_wp")" "$US" "$US" "$lrc_wp" "$US" "$lrc_dir" + else + printf 'TREE%s%s%sstale-registration%s%s%sgit registers it in %s and the directory is gone; `git -C %s worktree prune` is a person'\''s act\n' \ + "$US" "$(tree_id_for "$lrc_wp")" "$US" "$US" "$lrc_wp" "$US" "$lrc_dir" "$lrc_dir" + fi + # NAMED ONCE. The on-disk sweep below walks the same two roots git + # registers these in, so a path reported here joins the seen set — under + # both spellings, because that sweep walks the recorded `dir` and this one + # answered with the physical path — or a reader is told about one tree + # twice under two different reasons. + lrc_seen="$lrc_seen $lrc_wp $lrc_wpr " + lrc_unmanaged=$((lrc_unmanaged + 1)) + done <<EOF +$lrc_wlo +EOF + fi + # T018: EVERY LEG'S REGISTRATIONS, beside the checkout's own. A leg that is + # not checked out here is an empty directory of the assembly's, where git + # answers the ASSEMBLY — it registers nothing of its own, so it is passed + # over. A leg's main worktree is listed FIRST and spelled as its git + # directory under the assembly's `.git/modules/`, so it is skipped by place, + # not by name. + # A LEG WITH A `.git` OF ITS OWN THAT GIT CANNOT READ is no absent leg: it is + # a read that failed, never an absent or a clean one (Amendment 7(d)), and + # passed over it was a leg this reconciliation said nothing of while the + # sweep counted it. So it is the sweep's rule (`probe_leg`: git's toplevel + # there is not the leg, and a `.git` stands in it) and the sweep's word: a + # TREE row `unreadable`, which requires recovery, as the sweep's `leg` row is + # `unreadable` and counted. It is NO `indeterminate`: the sweep counts that + # leg and goes on (exit 3), and a verdict it refuses on would hide the count. + # SO IS A LEG DIRECTORY THIS ACCOUNT CANNOT SEARCH (#255, openRepoShape-2's + # SHOULD on #246): whether a `.git` stands in it cannot be tested, and the + # `.git` test fails there exactly as for a leg that is not checked out, so it + # was passed over in silence. It is the same `unreadable` row, in the words + # of the sweep's `probe_leg` and `lane-handoff`; a leg directory that is not + # there at all is still passed over (`-d`). + if [ "$lrc_lgrc" = 0 ]; then + while IFS="$lrc_tab" read -r lrc_lrepo lrc_ldecl lrc_labs; do + [ -n "$lrc_labs" ] && [ -d "$lrc_labs" ] || continue + lrc_ltop="$(git -C "$lrc_labs" rev-parse --show-toplevel 2>/dev/null </dev/null || :)" + if [ -z "$lrc_ltop" ] || [ "$(lane_real_path "$lrc_ltop")" != "$(lane_real_path "$lrc_labs")" ]; then + if [ -e "$lrc_labs/.git" ] || [ -L "$lrc_labs/.git" ]; then + lrc_lwhat="it has a .git of its own and git could not read it" + elif [ ! -x "$lrc_labs" ]; then + lrc_lwhat="its directory cannot be searched, so whether it has a .git of its own could not be tested, and git could not read it" + else + continue + fi + lrc_lr="$(lane_real_path "$lrc_labs")" + case "$lrc_seen" in *" $lrc_labs "*|*" $lrc_lr "*) continue ;; esac + if [ -n "$lrc_ltop" ]; then + lrc_lerr="git answers $lrc_ltop there" + else + lrc_lerr="$(git -C "$lrc_labs" rev-parse --show-toplevel 2>&1 >/dev/null </dev/null \ + | awk 'NF { sub(/^[ \t]+/, ""); sub(/[ \t]+$/, ""); print; exit }' | tr -d '\037')" + lrc_lerr="${lrc_lerr:-no answer}" + fi + printf 'TREE%s%s%sunreadable%s%s%sthe %s leg of %s/project.yaml%s: git could not be read through it (%s: %s), so NOTHING is assumed about it — not its own state, nor the worktrees it registers, which were not listed; a read that failed is never a clean leg (Amendment 7(d)) — read it by hand (git -C %s status) before relaunching a writer onto a tree of its repository\n' \ + "$US" "$(tree_id_for "$lrc_labs")" "$US" "$US" "$lrc_labs" "$US" "$lrc_ldecl" "$lrc_dir" \ + "${lrc_lrepo:+ ($lrc_lrepo)}" "$lrc_lwhat" "$lrc_lerr" "$lrc_labs" + lrc_seen="$lrc_seen $lrc_labs $lrc_lr " + lrc_recover=$((lrc_recover + 1)) + continue + fi + lrc_lwl=""; lrc_lwrc=0 + lrc_lwl="$(git -C "$lrc_labs" worktree list --porcelain 2>/dev/null </dev/null)" || lrc_lwrc=$? + if [ "$lrc_lwrc" != 0 ]; then + lrc_legwhy="${lrc_legwhy:+$lrc_legwhy; }the worktrees git registers in $lrc_labs, the $lrc_ldecl leg, could not be listed (git worktree list exited $lrc_lwrc)" + continue + fi + lrc_first=1 + while IFS= read -r lrc_wl; do + case "$lrc_wl" in worktree\ *) : ;; *) continue ;; esac + if [ "$lrc_first" = 1 ]; then lrc_first=0; continue; fi + lrc_wp="${lrc_wl#worktree }" + lrc_wpr="$(lane_real_path "$lrc_wp")" + case "$lrc_seen" in *" $lrc_wp "*|*" $lrc_wpr "*) continue ;; esac + if [ -d "$lrc_wp" ]; then + printf 'TREE%s%s%sunmanaged%s%s%sgit registers it in %s, the %s leg of %s/project.yaml (%s), and no sidecar of this lane names it; it is left exactly as it is\n' \ + "$US" "$(tree_id_for "$lrc_wp")" "$US" "$US" "$lrc_wp" "$US" "$lrc_labs" "$lrc_ldecl" "$lrc_dir" "$lrc_lrepo" + else + printf 'TREE%s%s%sstale-registration%s%s%sgit registers it in %s, the %s leg of %s/project.yaml (%s), and the directory is gone; `git -C %s worktree prune` is a person'\''s act\n' \ + "$US" "$(tree_id_for "$lrc_wp")" "$US" "$US" "$lrc_wp" "$US" "$lrc_labs" "$lrc_ldecl" "$lrc_dir" "$lrc_lrepo" "$lrc_labs" + fi + lrc_seen="$lrc_seen $lrc_wp $lrc_wpr " + lrc_unmanaged=$((lrc_unmanaged + 1)) + done <<LRC_LEG_TREES +$lrc_lwl +LRC_LEG_TREES + done <<LRC_LEGS +$lrc_legs +LRC_LEGS + fi + while IFS= read -r lrc_wr; do + [ -n "$lrc_wr" ] || continue + [ -d "$lrc_wr" ] || continue + # A ROOT THAT CANNOT BE LISTED hides every tree in it — the glob comes back + # as itself and reads as an empty root — so it is a read nobody made (#113 + # item 4, the on-disk half of the same sweep). + if [ ! -r "$lrc_wr" ] || [ ! -x "$lrc_wr" ]; then + lrc_unread="${lrc_unread:+$lrc_unread; }the lane's worktree root $lrc_wr could not be listed" + continue + fi + for lrc_c in "$lrc_wr"/*; do + [ -d "$lrc_c" ] || continue + lrc_cr="$(lane_real_path "$lrc_c")" + case "$lrc_seen" in *" $lrc_c "*|*" $lrc_cr "*) continue ;; esac + git -C "$lrc_c" rev-parse --git-dir >/dev/null 2>&1 || continue + printf 'TREE%s%s%sunmanaged%s%s%sit sits under this lane'\''s worktree root and no sidecar names it; it is left exactly as it is\n' \ + "$US" "$(tree_id_for "$lrc_c")" "$US" "$US" "$lrc_c" "$US" + lrc_seen="$lrc_seen $lrc_c $lrc_cr " + lrc_unmanaged=$((lrc_unmanaged + 1)) + done + done <<EOF +$(lane_worktree_roots "$lrc_lane" "$lrc_dir") +EOF + # T018: THE PAIRED ROOT. A feature directory, and each declared leg's path + # under it, that holds a `.git` of its own and that nothing above named — a + # registration lost, or a clone where a worktree belongs. Anything else under + # it is the assembly's own working tree, where git answers too, so a `.git` + # is what makes a checkout here. A directory that cannot be listed is a read + # nobody made, never an empty one. + if [ "$lrc_lgrc" = 0 ] && [ -d "$lrc_dir/worktrees" ]; then + if [ ! -r "$lrc_dir/worktrees" ] || [ ! -x "$lrc_dir/worktrees" ]; then + lrc_legwhy="${lrc_legwhy:+$lrc_legwhy; }the assembly's paired root $lrc_dir/worktrees could not be listed" + else + for lrc_f in "$lrc_dir"/worktrees/*; do + [ -d "$lrc_f" ] && [ ! -L "$lrc_f" ] || continue + if [ ! -r "$lrc_f" ] || [ ! -x "$lrc_f" ]; then + lrc_legwhy="${lrc_legwhy:+$lrc_legwhy; }the assembly's feature directory $lrc_f could not be listed" + continue + fi + # THE FEATURE DIRECTORY ITSELF, then each declared leg's path under + # it — a relative one, as the standard writes them. The directory is + # passed through the ENVIRONMENT: `awk -v` reads escapes in a value, + # so a name holding `\` would come out as another path. + lrc_cands="$lrc_f +$(printf '%s\n' "$lrc_legs" | LRC_F="$lrc_f" awk -F'\t' '$2 != "" && $2 !~ /^\// { p = $2; sub(/^\.\//, "", p); print ENVIRON["LRC_F"] "/" p }')" + while IFS= read -r lrc_c; do + [ -n "$lrc_c" ] && [ -d "$lrc_c" ] && [ ! -L "$lrc_c" ] || continue + lrc_cr="$(lane_real_path "$lrc_c")" + case "$lrc_seen" in *" $lrc_c "*|*" $lrc_cr "*) continue ;; esac + # A LEG'S DIRECTORY THAT CANNOT BE SEARCHED hides whether a `.git` + # stands in it: a read nobody made, never an empty directory. + if [ ! -x "$lrc_c" ]; then + lrc_legwhy="${lrc_legwhy:+$lrc_legwhy; }the assembly's paired tree directory $lrc_c could not be searched" + continue + fi + { [ -e "$lrc_c/.git" ] || [ -L "$lrc_c/.git" ]; } || continue + printf 'TREE%s%s%sunmanaged%s%s%sit sits in the assembly'\''s paired feature trees (%s/worktrees) and no sidecar of this lane names it; it is left exactly as it is\n' \ + "$US" "$(tree_id_for "$lrc_c")" "$US" "$US" "$lrc_c" "$US" "$lrc_dir" + lrc_seen="$lrc_seen $lrc_c $lrc_cr " + lrc_unmanaged=$((lrc_unmanaged + 1)) + done <<LRC_PAIRED +$lrc_cands +LRC_PAIRED + done + fi + fi + + # 5. THE VERDICT — the lifecycle word crossed with the holder, which is the + # whole of what tells the two crash kinds apart. + lrc_v=""; lrc_why="" + if [ "$lrc_hrc" != 0 ] && [ "$lrc_hrc" != 8 ]; then + lrc_v=indeterminate + [ -n "$lrc_hwhy" ] || lrc_hwhy="this workstation's session records could not be read" + lrc_why="$lrc_hwhy, so whether a holder is live is NOT established — which is not the same as none" + else + case "$lrc_state$lrc_hrc" in + RUNNING8) lrc_v=ungraceful-stop; lrc_why="the lane is recorded RUNNING and no verified holder is live: the session stopped before any handoff began, so nothing was polled, refreshed or recorded — inspect every tree below before relaunching a writer" ;; + RUNNING0) lrc_v=running; lrc_why="a verified holder is live and the lane is RUNNING: do not launch a second coordinator or a second writer onto any tree below" ;; + SWAPPING8) lrc_v=interrupted-swap; lrc_why="the lane is recorded SWAPPING and no verified holder is live: operation ${lrc_op:-none} began and did not finish, so the handoff, the row and the record may each be half done — every tree below is preserved for recovery" ;; + SWAPPING0) lrc_v=swap-in-progress; lrc_why="operation ${lrc_op:-none} is running in a live holder: do not compete with it" ;; + SWAPPED8) lrc_v=resumable; lrc_why="the swap completed and no holder is live: the lane may be resumed once the trees below are read" ;; + SWAPPED0) lrc_v=inconsistent; lrc_why="the lane is recorded SWAPPED and a holder is LIVE: a swapped lane has no holder, so one of the two is wrong and neither is overwritten here" ;; + CLOSED8) lrc_v=closed; lrc_why="the lane is closed" ;; + CLOSED0) lrc_v=inconsistent; lrc_why="the lane is recorded CLOSED and a holder is LIVE" ;; + UNREADABLE*) lrc_v=indeterminate; lrc_why="this lane's lifecycle snapshot at $lrc_root/lane-state.yaml IS THERE and could not be read, so where its session stopped is NOT established — which is not the same as a lane that has none, and is no clearance to relaunch anything (R22, Amendment 7(d): a read that failed is never an answer). Read that file by hand; if you know what wrote it, move it aside and this lane's next transition writes a fresh one" ;; + MALFORMED*) lrc_v=indeterminate; lrc_why="this lane's lifecycle snapshot at $lrc_root/lane-state.yaml is of this schema and ${lrc_swhy:-is not a whole record} — truncated, or edited by hand — so where its session stopped is NOT established, and no writer replaces it, exactly as none replaces a schema it does not write (#115). Read that file by hand; if you know what wrote it, move it aside and this lane's next transition writes a fresh one" ;; + NONE*) lrc_v=no-state; lrc_why="this lane has no lifecycle snapshot: it has not started or handed off under this capability, so its crash kind cannot be told from its record (Amendment 7(i)'s cutover rule — nothing is backfilled)" ;; + *) lrc_v=unknown-state; lrc_why="the snapshot holds the state word '$lrc_state', which this reader does not know; nothing is assumed about it" ;; + esac + if [ "$lrc_v" = closed ] && [ "$lrc_dirty" -gt 0 ]; then + lrc_v=closure-inconsistent + lrc_why="the lane is recorded CLOSED and $lrc_dirty tree(s) below are dirty or unpushed: no cleanup is made here" + fi + fi + # AND A LANE BOUND ELSEWHERE IS NEVER PRONOUNCED ON FROM HERE (Amendment + # 18(b), step 2b above). Every verdict this function can reach out of a local + # snapshot and a local holder read — a crash, a clearance, a closure, or + # "nothing to recover" — is a pronouncement on liveness, and from outside the + # binding that is UNKNOWN, never dead. So all of them become `indeterminate`. + case "$lrc_bwhere" in + elsewhere) + lrc_v=indeterminate + lrc_why="lane $lrc_lane is bound on $lrc_bat, and liveness is pronounced only from inside that binding (Amendment 18(b)): from here it is UNKNOWN, never dead, so no crash, no clearance and no closure is pronounced — and this workstation's snapshot is this workstation's alone (design decision 10). Read the lane from that place, or ask it to hand off: lane-start --request-handoff" ;; + unknown) + lrc_v=indeterminate + lrc_why="lane $lrc_lane's object log could not be read, so where it is bound is NOT established — and liveness may be pronounced only from inside the binding (Amendment 18(b)). A read that failed is never an answer (Amendment 7(d))" ;; + esac + # AND NO CLEARANCE OVER PATHS NOBODY READ (#113). The inventory, the + # registrations or a lane root that could not be read leaves trees this + # report never saw — so whatever the snapshot and the holder say, the verdict + # is not one a launcher may go past. + if [ -n "$lrc_unread" ] && [ "$lrc_v" != indeterminate ]; then + lrc_v=indeterminate + lrc_why="not all of lane $lrc_lane's worktrees could be read ($lrc_unread), so trees this report never saw may hold work, and no clearance is pronounced over paths nobody read (R22, Amendment 7(d))" + fi + if [ "$lrc_drc" != 0 ] && [ "$lrc_drc" != 8 ] && [ "$lrc_v" != indeterminate ]; then + lrc_v=indeterminate + lrc_why="lane $lrc_lane's object log could not be read, so its coordinator directory is NOT established and neither the worktrees git registers there nor the trees on disk under its roots were inspected — no clearance is pronounced over paths nobody read (Amendment 7(d))" + fi + # T018: AN ASSEMBLY WHOSE LEGS COULD NOT BE READ is one whose leg + # registrations and paired trees nobody inspected — the same paths-nobody-read + # as an unreadable object log, and the same answer. It is said in the words + # `lane-worktrees`' sweep refuses with (`the legs of the assembly <dir> could + # not be read`), because the sweep reads this verdict FIRST and refuses on + # it: one fact, one spelling, whichever reader a person meets. + if [ "$lrc_lgrc" != 0 ] && [ "$lrc_lgrc" != 8 ] && [ "$lrc_v" != indeterminate ]; then + lrc_v=indeterminate + lrc_why="the legs of the assembly $lrc_dir could not be read (its project.yaml is there and unreadable), so which legs it declares — and the worktrees they register and the paired feature trees under $lrc_dir/worktrees — is NOT established, and no clearance is pronounced over paths nobody read (T018, Amendment 7(d))" + fi + if [ -n "$lrc_legwhy" ] && [ "$lrc_v" != indeterminate ]; then + lrc_v=indeterminate + lrc_why="lane $lrc_lane's checkout $lrc_dir is an assembly and not all of what its legs hold could be read ($lrc_legwhy), so no clearance is pronounced over paths nobody read (T018, Amendment 7(d))" + fi + printf 'TREES%s%s inventoried%s%s dirty or unpushed%s%s require recovery%s%s unmanaged or stale\n' \ + "$US" "$lrc_n" "$US" "$lrc_dirty" "$US" "$lrc_recover" "$US" "$lrc_unmanaged" + printf 'VERDICT%s%s%s%s\n' "$US" "$lrc_v" "$US" "$lrc_why" + return 0 +} + +# ------------------------------------- every inventoried worktree, as rows +# +# opensoft/openRepoTools#161 — THE INVENTORY OF EVERY LANE ON THIS WORKSTATION, +# ONE ROW PER TREE, and the one implementation of that sentence: `lanes +# --worktrees` renders what this prints and `lanes-index sync --source +# inventory` copies it into the derived index's `worktrees` table, so the +# listing a person reads and the table another workstation queries cannot come +# to disagree about what a lane left. US-separated, sixteen fields: +# +# TREE <workstation> <lane> <owner> <path> <branch> <base> <lifecycle> +# <generation> <operation> <writer_live> <last_seen_utc> <last_commit> +# <dirty> <unpushed> <provenance> +# UNREAD <workstation> <lane> <why> +# PARTIAL <workstation> <why> +# +# IT READS WHAT #97 WROTE AND NOTHING THAT IT DID NOT. The lanes are the +# listing's own (`lanes_rows --all --closed`, so a closed or dormant lane's +# leftovers are not hidden), and so is `writer_live` — the listing's LIVE, out +# of this workstation's session records, and EMPTY where those could not be +# read or the lane is bound elsewhere (Amendment 7(d) and 18(b): never "no" on a +# read nobody could make). The trees are `lane_trees_list`'s sidecars and +# NO DIRECTORY IS WALKED for a tree no sidecar names: that is +# `lane-reconcile`'s act, and it is an act. `owner` is `lane_is_managed_owned`'s +# answer — the read `managed-projection` makes — as `legacy`, `managed <owner>` +# or `unknown`, and `lifecycle` is the snapshot's own word for a LEGACY lane +# only: a managed or unknown lane's lifecycle is not this tooling's to +# pronounce on (ruling 2026-10-04), and neither is one whose snapshot is +# missing, unreadable or of another schema, so those are `INDETERMINATE`. +# `generation` and `operation` are the snapshot's; `provenance` is the +# generation the TREE'S OWN record was filed under, which is behind +# `generation` exactly when the observation predates the lane's current +# transition. +# +# EVERY FIELD IS THE LAST OBSERVATION, NEVER RECOMPUTED: `branch`, `dirty`, +# `unpushed` and `last_seen_utc` are what the sidecar says the handoff saw. +# Two git reads are made per tree the inventory names, both of the RECORDED +# head and neither of the working tree: `last_commit` (`<sha> <subject>`) and +# `base`, its merge-base with `origin/main`, else `main`, else `origin/HEAD` +# — in the tree, or in its recorded checkout once the tree is gone. A detached +# head is `detached <sha>`; a record that could not be read is `unreadable +# sidecar`, one of another schema `unknown schema <n>`, and one of this schema +# that is not whole `malformed sidecar` (#115). Each keeps the path the record +# names where it names one, else the record's id (its file name) stands +# there. A kept path is the record's own word, so it may be relative or +# not a tree at all; only a whole record's path is known absolute. A count that is +# `unknown` is empty — an INTEGER column has no word for it. +# +# AND THE LISTING ITSELF IS SAID TO BE WHOLE OR NOT (opensoft/openRepoTools#173 +# item c1, Copilot's fourth review of #171). Its lanes are the names three +# reads give — the register's rows, the archive's rows and the object logs' +# file names — and each lane's trees are found under the control root its +# log's `dir` places. `lanes_rows` is a listing a person reads in front of a +# launch, so it may not refuse: where one of those reads fails it SAYS so on +# stderr (the log listing not even that) and lists what the others gave. Taken +# as whole, that made a lane whose only row is in an archive that could not be +# read a lane with no trees — and `lanes-index sync` removed its rows; with all +# three unread the listing was EMPTY and this said 8, "none", and the sync +# removed every row. So for the whole listing — a named lane is read by its +# name, which no listing gives — each of those reads is asked here too, and a +# failed one is ONE `PARTIAL` line: the rows beside it are every tree this read +# reached, a lane it could not name is NOT a lane with no worktrees (R22, +# Amendment 7(d)), and the indexer writes nothing over it. The register, the +# archive and the list of the logs are asked BEFORE the listing, and a read +# that succeeds is the very text the listing then reads - the register's out of +# its cache, the other two pinned for the listing alone (`PIN_ARCHIVE`, +# `PIN_LOGS`), so no read that fails after the check can thin a listing taken +# as whole (the review of #289, SHOULD-1). The logs themselves are asked AFTER +# it, out of the warnings the events' own read of them left (`state_events`, +# built once per process): a log it could not read, and a list of the logs it +# could not make, which is the read every lane's `dir` comes from - and the +# lane's root, its trees and its snapshot are all found under that one `dir`, +# not under a second read of its log (review r2 of #289, SHOULD-A); where +# those warnings could not be kept, whether a log failed is not known, which +# is said the same way. With no `origin`, the log directory is asked as the +# trees' is below, and its files are still read twice: docs/README-lanes.md +# says what that leaves. An empty listing over a failed read is that line +# alone, and never 8. +# +# The rows are sorted bytewise, which is the order the index's copy is written +# in too: the two reads of one inventory are the same bytes. +# 0 rows, with a PARTIAL line where the listing was not whole · 8 none · +# 1 the lane listing could not be read +worktree_rows() { # [<canonical lane>] + wr_one="${1-}"; wr_out="" + wr_live_ok=1 + live_session_ids >/dev/null 2>&1 || wr_live_ok=0 + wr_partial="" + wr_unlisted="the object logs under origin/$LANES_BRANCH:$LANES_LOG_PREFIX could not be listed" + if [ -z "$wr_one" ]; then + register_text_checked >/dev/null 2>&1 || + wr_partial="the register $LANES_PATH could not be read" + # THE ARCHIVE AND THE LOG LIST ARE PINNED, NOT ONLY ASKED (SHOULD-1(b)): + # each read that succeeds here is the text every read of the listing below + # is handed, as the register's is its cache. `x` keeps the text's last + # newline through the substitution. + wr_pin="" + if wr_pin="$(archive_text 2>/dev/null && printf x)"; then + PIN_ARCHIVE_TEXT="${wr_pin%x}"; PIN_ARCHIVE=1 + else + wr_partial="${wr_partial:+$wr_partial; }the archive $LANES_ARCH_PATH could not be read" + fi + # `known_lanes`' OWN TWO READS, which print what they could and answer 0 + # either way, because the listing unions them with the register. WITH NO + # `origin`, A DIRECTORY THAT IS THERE IS ASKED AS THE TREES' IS BELOW: `ls` + # lists an `r--` one, whose files no glob can then open (N1 of the review). + if have_remote_ref; then + wr_pin="" + if wr_pin="$(git -C "$LANES_REPO" ls-tree --name-only "origin/$LANES_BRANCH" -- "$LANES_LOG_PREFIX" 2>/dev/null && printf x)"; then + PIN_LOGS_TEXT="${wr_pin%x}"; PIN_LOGS=1 + else + wr_partial="${wr_partial:+$wr_partial; }$wr_unlisted" + fi + elif [ -e "$LANES_LOG_DIR" ] || [ -L "$LANES_LOG_DIR" ]; then + if [ ! -d "$LANES_LOG_DIR" ] || [ ! -r "$LANES_LOG_DIR" ] || [ ! -x "$LANES_LOG_DIR" ]; then + wr_partial="${wr_partial:+$wr_partial; }the log directory $LANES_LOG_DIR is there and could not be listed" + fi + fi + fi + wr_lanes=""; wr_lrc=0 + if [ -n "$wr_one" ]; then + wr_lanes="$(lanes_rows --lane "$wr_one" --closed)" || wr_lrc=$? + else + wr_lanes="$(lanes_rows --all --closed)" || wr_lrc=$? + fi + PIN_ARCHIVE=0; PIN_ARCHIVE_TEXT=""; PIN_LOGS=0; PIN_LOGS_TEXT="" + case "$wr_lrc" in + 0) : ;; + 8) [ -n "$wr_partial" ] || return 8 ;; + *) return 1 ;; + esac + if [ -z "$wr_one" ] && [ "$wr_lrc" = 0 ]; then + wr_ulogs=""; wr_urc=0; wr_ulist="" + if [ -n "$SE_WARN_FILE" ] && [ -f "$SE_WARN_FILE" ]; then + wr_ulogs="$(sed -n -e 's/^lanes-edit: unreadable log: \(.*\) — git could not read it.*$/\1/p' "$SE_WARN_FILE" 2>/dev/null)" || wr_urc=1 + # THE EVENTS' OWN LIST OF THE LOGS (SHOULD-1(a)): where it failed, no + # lane has the `dir` its trees are found under. + wr_ulist="$(sed -n -e '/^lanes-edit: unlisted logs: /p' "$SE_WARN_FILE" 2>/dev/null)" || wr_urc=1 + else + wr_urc=1 + fi + if [ "$wr_urc" != 0 ]; then + wr_partial="${wr_partial:+$wr_partial; }whether every object log could be read is not known, because the warnings of their read could not be kept" + else + if [ -n "$wr_ulist" ]; then + case "; $wr_partial; " in + *"; $wr_unlisted; "*) : ;; + *) wr_partial="${wr_partial:+$wr_partial; }$wr_unlisted" ;; + esac + fi + if [ -n "$wr_ulogs" ]; then + wr_partial="${wr_partial:+$wr_partial; }these object logs could not be read: $(printf '%s\n' "$wr_ulogs" | tr '\n' ' ' | sed -e 's/ $//')" + fi + fi + fi + wr_tab="$(printf '\t')" + while IFS="$wr_tab" read -r wr_l wr_st wr_w wr_pf wr_win wr_sid wr_dir wr_obj wr_age wr_restart wr_home wr_fk wr_loc wr_rest; do + [ -n "${wr_l:-}" ] || continue + # ONE CONTROL-ROOT READ FOR A LANE WITH NO TREES, which is nearly every lane + # in the estate: the sidecars are listed only where a `trees` directory is. + # The listing's column 7 IS `lane_payload_field <lane> dir` — the same last + # lane-kind payload carrying `dir`, out of the same published logs, `none` + # where there is none — so it is handed to `lane_control_root` as the + # payload it takes, rather than having each of sixty lanes' logs read a + # second time to find what the listing has just said (measured on Eagle's + # 61 lanes: 7.9 s for the whole read with the second reading, 2.7 s + # without it). `none` is not absolute, so it falls to the same third rung + # an absent `dir` does. + # AND THE SAME PAYLOAD TO THE TWO READS BELOW (review r2 of #289, + # SHOULD-A). `lane_trees_list` and `lane_state_read` worked the root out + # again with no `dir`, reading the lane's log a second and a third time, + # and a `git show` that failed there was thrown away: the root fell to the + # third rung, where no `trees` is, and a lane whose trees this loop had + # just found read as a lane with none. The listing's `dir` is now the root + # of all three, so the read that could fail is not made. + wr_pay="dir ${wr_dir:-none}" + wr_root=""; wr_rrc=0 + wr_root="$(lane_control_root "$wr_l" "$wr_pay" 2>/dev/null)" || wr_rrc=$? + [ "$wr_rrc" = 0 ] || continue + [ -d "$wr_root/trees" ] || continue + # A DIRECTORY THAT IS THERE AND CANNOT BE LISTED IS NOT AN EMPTY ONE, and + # the trees it holds are not trees this lane no longer has (R22). + if [ ! -r "$wr_root/trees" ] || [ ! -x "$wr_root/trees" ]; then + wr_out="${wr_out}UNREAD$US$WS$US$wr_l${US}its trees directory $wr_root/trees is there and could not be listed +" + continue + fi + wr_trees=""; wr_trc=0 + wr_trees="$(lane_trees_list "$wr_l" "$wr_pay" 2>/dev/null)" || wr_trc=$? + # 8 IS A `trees` DIRECTORY WITH NO RECORD IN IT; ANYTHING ELSE, with the + # directory already found above, is a read that did not happen - and its + # rows are not rows this lane no longer has (Copilot round 2 on #171). + case "$wr_trc" in + 0) : ;; + 8) continue ;; + *) + wr_out="${wr_out}UNREAD$US$WS$US$wr_l${US}its trees directory $wr_root/trees is there and lane-trees could not read it (exit $wr_trc) +" + continue ;; + esac + # LIVENESS IS PRONOUNCED ONLY FROM INSIDE THE BINDING (Amendment 18(b)). A + # live record here naming one of the lane's ids is `1` and no such record is + # `0` - but only where this workstation could read its records AND the + # lane's latest binding is not on another host (the listing's column 13). + # Either of those says UNKNOWN, the empty field, and it wins over the + # listing's LIVE too (Copilot round 1 on #171): a still-running local + # session of an older binding says nothing about the writer the lane's + # binding elsewhere has now. + wr_live=0 + [ "$wr_st" = LIVE ] && wr_live=1 + [ "${wr_loc:-none}" = elsewhere ] && wr_live="" + [ "$wr_live_ok" = 1 ] || wr_live="" + wr_own=""; wr_orc=0 + wr_own="$(lane_is_managed_owned "$wr_l" 2>/dev/null)" || wr_orc=$? + wr_own="$(printf '%s\n' "$wr_own" | head -n 1)" + case "$wr_orc" in + 0) if [ -n "$wr_own" ]; then wr_owner="managed $wr_own"; else wr_owner=unknown; fi ;; + 8) wr_owner=legacy ;; + *) wr_owner=unknown ;; + esac + wr_life=INDETERMINATE; wr_gen=""; wr_op="" + wr_snap=""; wr_src=0 + wr_snap="$(lane_state_read "$wr_l" "$wr_pay" 2>/dev/null)" || wr_src=$? + if [ "$wr_src" = 0 ]; then + wr_s="$(printf '%s\n' "$wr_snap" | awk -F'\t' '$1 == "state" { print $2; exit }')" + if [ "$wr_s" != UNKNOWN-SCHEMA ]; then + wr_gen="$(printf '%s\n' "$wr_snap" | awk -F'\t' '$1 == "generation" { print $2; exit }')" + wr_op="$(printf '%s\n' "$wr_snap" | awk -F'\t' '$1 == "operation" { print $2; exit }')" + case "$wr_gen" in ''|*[!0-9]*) wr_gen="" ;; esac + case "$wr_s" in RUNNING|SWAPPING|SWAPPED|CLOSED) wr_life="$wr_s" ;; esac + fi + fi + [ "$wr_owner" = legacy ] || wr_life=INDETERMINATE + while IFS="$US" read -r t_id t_p t_b t_h t_u t_d t_n t_w t_ob t_co t_g t_o t_s; do + [ -n "${t_id:-}" ] || continue + t_base=""; t_last="" + if [ "${t_s:-}" = "<unreadable>" ]; then + t_branch="unreadable sidecar"; [ -n "${t_p:-}" ] || t_p="$t_id" + t_d=""; t_n=""; t_g=""; t_ob="" + elif [ "${t_s:-}" = "<malformed>" ]; then + t_branch="malformed sidecar"; [ -n "${t_p:-}" ] || t_p="$t_id" + t_d=""; t_n=""; t_g=""; t_ob="" + elif [ "${t_s:-}" != "$LANE_STATE_SCHEMA" ]; then + t_branch="unknown schema ${t_s:-<none>}"; [ -n "${t_p:-}" ] || t_p="$t_id" + t_d=""; t_n=""; t_g=""; t_ob="" + else + if [ "$t_b" = detached ]; then t_branch="detached $t_h"; else t_branch="$t_b"; fi + case "$t_h" in + ''|*[!0-9a-f]*) : ;; + *) + if [ "${#t_h}" -eq 40 ]; then + t_gd="" + if [ -d "$t_p" ]; then t_gd="$t_p"; elif [ -d "${t_co:-}" ]; then t_gd="$t_co"; fi + if [ -n "$t_gd" ]; then + t_last="$(git -C "$t_gd" show -s --format='%H %s' "$t_h^{commit}" 2>/dev/null | head -n 1 | tr -d '\037')" + [ -n "$t_last" ] || t_last="$t_h" + for t_ref in refs/remotes/origin/main refs/heads/main refs/remotes/origin/HEAD; do + if git -C "$t_gd" rev-parse --verify -q "$t_ref^{commit}" >/dev/null 2>&1; then + t_base="$(git -C "$t_gd" merge-base "$t_h" "$t_ref" 2>/dev/null || :)" + break + fi + done + else + t_last="$t_h" + fi + fi ;; + esac + case "$t_d" in ''|*[!0-9]*) t_d="" ;; esac + case "$t_n" in ''|*[!0-9]*) t_n="" ;; esac + case "$t_g" in ''|*[!0-9]*) t_g="" ;; esac + fi + wr_out="${wr_out}TREE$US$WS$US$wr_l$US$wr_owner$US$t_p$US$t_branch$US$t_base$US$wr_life$US$wr_gen$US$wr_op$US$wr_live$US$t_ob$US$t_last$US$t_d$US$t_n$US$t_g +" + done <<WR_TREES +$wr_trees +WR_TREES + done <<WR_LANES +$wr_lanes +WR_LANES + [ -z "$wr_partial" ] || wr_out="${wr_out}PARTIAL$US$WS$US$wr_partial +" + [ -n "$wr_out" ] || return 8 + printf '%s' "$wr_out" | LC_ALL=C sort + return 0 +} + +# ---------------------------------------------------------------- subcommands + +cmd="${1-}" +# The usage block is this file's own header: print from line 3 until the first +# line that is not a comment. (It used to be a hard-coded `3,59p`, which went +# stale the moment the header grew — as it did under Amendment 5.) +[ -n "$cmd" ] || { sed -n -e '1,2d' -e '/^#/!q' -e 's/^# \{0,1\}//' -e p "$RESOLVED"; exit 2; } +shift || : +# `session-start` is EXEMPT. It is a hook: it never writes, and it must exit 0 +# even where there is no register to read at all — a hook that dies is a hook +# that breaks the session it was meant to orient. +# EVERY WRITER REFUSES WHERE THIS CONTAINER HAS NO CONFIGURED WORKSTATION +# (Amendment 11, decision 8(d), `R-A11-14`). ONE GUARD AT THE DISPATCHER rather +# than one per writer: `WS` is built into every event line's `session <uuid>@<ws>` +# and into every commit subject this file writes, so a container id reaches the +# append-only log through any of the TEN subcommands listed below (nine until +# Amendment 18 added `request-handoff`), and ten copies of one rule is how nine +# of them would come to disagree. The READS are untouched — a read in +# front of every launch may not refuse, and one that answers nothing for a +# workstation nobody configured is telling the truth. +case "$cmd" in + # `request-handoff` JOINS THE LIST BECAUSE IT WRITES (Amendment 18(c)/(e)). It + # reaches `write_event` directly rather than through `log`, so the dispatcher + # guard is the only place that stops it filing a `HANDOFF-REQUESTED` or a + # forced `PAUSED` under a container id — and one field further along than the + # `session <uuid>@<ws>` this guard has always protected, clause (a)'s own + # `host` falls back to THE RULE 10 WORKSTATION NAME, which in this state is + # that same container id. One guard, every writer, exactly as the paragraph + # below says — and Amendment 13's `set-row-state` and `migrate-state-cells` + # are in it for the same reason. + # AND `rename-lane` JOINS IT FOR THE SAME REASON (Amendment 16). Its four + # moves are one commit and one of them is a `RENAMED` line carrying + # `session <uuid>@<ws>`, so an unconfigured container would put its own id + # into the register, the log AND `lanes/aliases.tsv` in a single write. + # AND AMENDMENT 19-S TWO WRITES, `retire-rows` and `archive-rows`, for the + # same reason: each is ONE commit over several rows and logs, and every + # `RETIRED` line it appends carries `session <uuid>@<ws>`. + replace-in-row|append-session-id|append-line|add-row|set-row-state|migrate-state-cells|retire-rows|archive-rows|commit|log|claim|release|request-handoff|rename-lane) + ws_why="$(lanes_workstation_why "$WS_SOURCE")" + [ -z "$ws_why" ] || die "$ws_why" 2 ;; +esac + +# `guard` JOINS THAT EXEMPTION AND REFUSES FOR ITSELF (Amendment 12(d)). It is +# a hook too, and a blocking one: `die … 1` here would print the workspace +# refusal and let the prompt THROUGH, because only exit 2 blocks a +# `UserPromptSubmit`. So the verb takes the same reads itself and answers them +# with a 2 — fail CLOSED, which is the clause. +case "$cmd" in + # THE TWO FILTERS OF AMENDMENT 18 ADDENDUM 1 READ THEIR ROWS FROM STDIN and + # touch no workspace at all, so a workspace this workstation has not pointed + # at yet is not a reason to refuse them — the same exemption `session-start` + # has had since it was written, and the same one `guard` joined under + # Amendment 12(d), each for its own reason. + # AND THE RETIRED VERB IS EXEMPT TOO (Copilot round 4 on openRepoTools#82, + # suppressed comment `lanes-edit.sh:7525`). `append-row-status` is out of the + # WRITER list above and says so of itself — *"it refuses before the + # workstation guard and before the register is even looked for"* — but this + # second guard caught it all the same: on a machine with no configured + # workspace the caller got the workspace refusal (exit 1) instead of the + # RETIREMENT refusal (exit 2) naming the two acts that replace it. A + # compatibility refusal that only fires where the register is already + # reachable is not one. + # AND `project-legs` (T018) READS ONE `project.yaml` and nothing of the + # workspace, so `lane-worktrees`' daily report can ask it on a + # workstation where no register is configured. + session-start|guard|lane-groups|next-free|append-row-status|project-legs) : ;; + *) + if [ -z "$LANES_REPO" ] || [ -z "$LANES_DIR" ]; then + die "$(lanes_workspace_why)" 1 + fi + [ -f "$LANES_FILE" ] || die "registry not found: $LANES_FILE + $LANES_REPO is the workspace repository $(lanes_ws_yaml) names, and it + carries no lanes/LANES.md. A repository seeded by \`openRepoTools wip init\` + has one; re-run it (it is idempotent) or pull that checkout." 1 + ;; +esac + +case "$cmd" in + verify-row) + lane="${1-}"; [ -n "$lane" ] || die "usage: verify-row <lane>" 2 + lane="$(canon_lane "$lane")" || exit 2 + n="$(row_line "$lane")" || exit 2 + row="$(sed -n -e "${n}p" "$LANES_FILE")" + # Bash substrings, not `cut -c` and `rev`: `${#row}` counts CHARACTERS, + # and a register row is full of `·` `—` `→`, so a byte-counting `cut` + # disagrees with the length printed one field earlier — and BSD `rev` and + # `cut` answer `Illegal byte sequence` on the same row rather than + # disagreeing. The same rule `lane-end:566` states (R-A9-11). + # `${row: -200}` on a row SHORTER than 200 answers the empty string, where + # `rev | cut | rev` answered the whole row — so the short case is asked + # for explicitly rather than left to the expansion. + row_tail="$row"; [ "${#row}" -gt 200 ] && row_tail="${row: -200}" + printf 'lane : %s\nline : %s\nlength : %s chars\nfirst200: %s\nlast200 : %s\n' \ + "$lane" "$n" "${#row}" "${row:0:200}" "$row_tail" + ;; + + # AMENDMENT 13(a) — RETIRED, AND THE REFUSAL IS THE WHOLE OF IT. + # + # This verb appended to the `state` cell and never replaced it, which is how a + # column defined as the lane's CURRENT STATE came to hold a diary: 96,228 + # characters in one row, 7,016 in this lane's own after a single day, in a + # table nobody can read in the table. The cell can never grow again because + # the act that grew it is gone — not because every caller remembered. + # + # IT REFUSES BEFORE THE WORKSTATION GUARD AND BEFORE THE REGISTER IS EVEN + # LOOKED FOR (it is out of the dispatcher's writer list above), so a caller on + # a machine that has neither still learns what to run instead. Two acts + # replace it, and they are two because the cell held two things: the STATE, + # which is one phrase a person reads, and the NARRATIVE, which is history and + # belongs in the lane's own append-only log. + append-row-status) + die "append-row-status is RETIRED (lane-collision-protocol Amendment 13(a), in force 2026-09-13T21:08:36Z). The state cell is ONE PHRASE — '<STATE> · <UTC> · <one line>' — and every write REPLACES it, so that the column that says where a lane IS can never grow into a diary again. + the STATE: LANES_LANE=${1:-<lane>} lanes-edit.sh set-row-state ${1:-<lane>} \"<STATE> · <one line>\" + ($ROW_STATES; the line at most $ROW_STATE_CAP characters) + the NARRATIVE: LANES_LANE=${1:-<lane>} lanes-edit.sh log NOTED lane:${1:-<lane>} \"<what the lane did, found, launched, left>\" + a RULING: LANES_LANE=${1:-<lane>} lanes-edit.sh log RULED lane:${1:-<lane>} [→ <object>] \"<Brett Heap's words, verbatim>\" + read it back: lanes-edit.sh history ${1:-<lane>} [--since <UTC>] +Nothing was written." 2 + ;; + + # AMENDMENT 13(a) — THE ONE WRITER OF THE STATE CELL. It stamps the UTC itself + # and REPLACES the cell, so what the column holds after this call is exactly + # `<STATE> · <UTC> · <one line>` and nothing of what it held before. The + # history is not lost by that: it is in git, and — after `migrate-state-cells` + # — in the lane's own log, which is the file built to hold it. + set-row-state) + lane="${1-}"; phrase="${2-}" + [ -n "$lane" ] && [ -n "$phrase" ] || die "usage: set-row-state <lane> \"<STATE> · <one line>\" (STATE: $ROW_STATES)" 2 + [ "$#" -le 2 ] || die "set-row-state takes TWO arguments: the lane, and the phrase as ONE quoted string — set-row-state <lane> \"<STATE> · <one line>\". Got $# ; the shell has split the phrase, so quote it." 2 + # EVERY TEST OF THE PHRASE IS MADE FIRST — before the resolver, before the + # lock and before the row is read — so a refusal leaves this checkout, the + # mutex and the register exactly as it found them. + row_state_check "$phrase" + # AMENDMENT 15 — the row's own spelling, which is what the commit subject + # and every message below then carry. + lane="$(canon_lane "$lane")" || exit 2 + # THE CELL THIS REPLACES MAY BE THE MANAGED LEDGER'S MARKER (ruling + # 2026-10-04), and replacing it would take the lane out of the ledger's + # hands without the ledger: refused before the lock, nothing written. + managed_seam_refuse "$lane" "set-row-state" + acquire_lock; handle_preexisting + n="$(row_line "$lane")" || exit 2 + row="$(sed -n -e "${n}p" "$LANES_FILE")" + srs_rc=0; row_split_state_cell "$row" || srs_rc=$? + case "$srs_rc" in + 0) : ;; + 2) die "lane $lane's row (line $n) carries $(row_sep_count "$row") ' | ' separators where a seven-column row carries 6, so WHICH TEXT IS THE STATE CELL is not knowable from the row: read from the left this write lands on one cell, read from the right on another, and one of those readings overwrites the row's handoff path. Nothing was written. A Markdown table carries a literal pipe ESCAPED — \`\\|\` — so find the unescaped ' | ' inside a cell of that row, escape it by hand with an allowed tool, commit it (\`LANES_LANE=$lane lanes-edit.sh commit \"escape a literal pipe in row $lane\"\`), and re-run." 2 ;; + *) die "lane $lane's row (line $n) does not open with '|' and end with '|', so it is not a row this writer can take apart. Nothing was written." 2 ;; + esac + srs_new="$ROW_STATE · $(utc_now) · $ROW_STATE_LINE" + srs_was="$(rstrip_spaces "$RSS_CELL")" + replace_line "$n" "$RSS_HEAD$srs_new $RSS_TAIL" + # WHAT IT SAYS IS WHAT HAPPENED, and the two are not the same act. A state + # phrase stamped twice inside one second is byte-identical — `utc_now` is + # seconds — so the row already reads exactly this, nothing is written, and + # "REPLACED" beside `replace_line`'s own "nothing rewritten" would be two + # lines of one output contradicting each other. + if [ "${REPLACE_LINE_NOOP:-0}" = 1 ]; then + note "state cell UNCHANGED: it already reads exactly this ${#srs_new} chars, to the second" + else + note "state cell REPLACED: ${#srs_was} chars → ${#srs_new} chars" + fi + # THE WHOLE LINE IN THE SUBJECT, as `append-row-status` put its whole text + # there: the line is capped at 240 characters by the act above, and a + # subject cut at 72 loses exactly the tail that says what happened. + msg="LANES($lane@$WS): state · $ROW_STATE · $ROW_STATE_LINE" + [ -n "$PRE_DIRTY_LANES" ] && msg="$msg + sweeps uncommitted edit to row $PRE_DIRTY_LANES" + commit_push "$msg" + ;; + + replace-in-row) + lane="${1-}"; old="${2-}"; new="${3-}"; why="${4-}" + [ -n "$lane" ] && [ -n "$old" ] || die "usage: replace-in-row <lane> \"<old>\" \"<new>\" [\"<why>\"]" 2 + lane="$(canon_lane "$lane")" || exit 2 # Amendment 15 + # THE SEAM (ruling 2026-10-04): a managed lane's row is the ledger's, and + # no legacy edit may write the marker's vocabulary into any row. + managed_seam_refuse "$lane" "replace-in-row" + if managed_projection_hint "$new"; then + die "the replacement text carries managed-owner vocabulary ('managed owner', 'managed binding', 'mode=managed' or 'managed:'), and only the managed ledger's own writer writes a managed-owner marker, and a legacy writer that wrote its vocabulary into a row would forge that lane's ownership (ruling 2026-10-04: \"managed ledger owns enrolled lanes; #97 owns legacy\"). Nothing was written." 2 + fi + acquire_lock; handle_preexisting + n="$(row_line "$lane")" || exit 2 + row="$(sed -n -e "${n}p" "$LANES_FILE")" + c="$(count_occurrences "$row" "$old")" || exit 2 + [ "$c" = 1 ] || die "'$old' occurs $c times in lane $lane's row (line $n); exactly 1 required" 2 + # NOT `${row/"$old"/"$new"}` (A9 Addendum 4, R-A9-11). Bash 4.3 and later + # read the quotes there as "this half is a literal, not a pattern"; BASH + # 3.2 KEEPS THE ONES AROUND THE REPLACEMENT AS CHARACTERS, so on macOS + # every `replace-in-row` wrote its new text WRAPPED IN DOUBLE QUOTES. The + # macOS job read `| "RETIRED 2026-09-13T20:39:04Z" · …` where the register + # wanted `| RETIRED 2026-…`, and nothing else noticed: the write succeeded, + # the commit landed, and the row was quietly wrong. (The pattern half is + # unaffected — 3.2 does remove those quotes, which is how the replacement + # got made at all.) Prefix and suffix instead, so `$new` never enters the + # pattern machinery: `%%` leaves the shortest prefix and `#` the text after + # the first match, and `count_occurrences` above has already proved there + # is exactly one. + ri_pre="${row%%"$old"*}"; ri_post="${row#*"$old"}" + replace_line "$n" "$ri_pre$new$ri_post" + msg="LANES($lane@$WS): ${why:-replace-in-row}" + [ -n "$PRE_DIRTY_LANES" ] && msg="$msg + sweeps uncommitted edit to row $PRE_DIRTY_LANES" + commit_push "$msg" + ;; + + # AMENDMENT 8, R-A8-4 — THE UUID APPEND IS CELL-SCOPED. + # + # `replace-in-row` refuses unless its anchor occurs exactly once in the WHOLE + # ROW, and the anchor for a session-cell append is a transcript uuid — which + # the 6(c) stamp writes into the STATE cell again on every launch (`RESUMED by + # <uuid> … launching claude --resume <uuid>` — twice more per launched start). + # Measured against `origin/main` on 2026-09-12, `openRepoProject-1`'s own row + # carries its current uuid THREE times and its previous one three times, so + # the single most load-bearing new act in Amendment 8(d) — recording the + # transcript the harness minted — could not run on the lane the amendment was + # written for. + # + # So the anchor is matched INSIDE THE SESSION CELL and nowhere else, and must + # occur exactly once THERE. `replace-in-row`'s whole-row rule is unchanged and + # is still right for what it is for: a state cell says the same thing in two + # places all the time, and a blind replace there would rewrite the wrong one. + # + # AND THE TEXT IS APPENDED AT THE END OF THE CELL, NOT AT THE ANCHOR. This is + # the second half of the same finding and it is not cosmetic: the cell spells + # its ids `harness `<uuid>`` — inside backticks — so a replace AT a bare-uuid + # anchor writes `harness `<uuid> → harness <new>`` and puts the new id inside + # the old one's code span. The anchor's job is to prove that the cell this + # checkout holds is the published one the caller read (Amendment 6(b): the + # cell is a HISTORY, oldest first, and the last id is the lane's current + # session); the APPEND's job is to add a lineage after all of them. Those are + # two different positions, and conflating them corrupted the cell. + # + # Anything that is not an append — a cell that must really be rewritten — is + # `replace-in-row`'s business, in front of a person. + append-session-id) + lane="${1-}"; old="${2-}"; add="${3-}"; why="${4-}" + [ -n "$lane" ] && [ -n "$old" ] && [ -n "$add" ] \ + || die "usage: append-session-id <lane> \"<anchor in the session cell>\" \"<text to append to the cell>\" [\"<why>\"]" 2 + case "$add" in + *"|"*) die "append-session-id's appended text may not contain '|': it would forge a cell boundary in the row. Got '$add'." 2 ;; + esac + if managed_projection_hint "$add"; then + die "append-session-id's appended text carries managed-owner vocabulary ('managed owner', 'managed binding', 'mode=managed' or 'managed:'), and only the managed ledger's own writer writes it into a row. Nothing was written." 2 + fi + lane="$(canon_lane "$lane")" || exit 2 # Amendment 15 + managed_seam_refuse "$lane" "append-session-id" # Copilot round 3 on #97 + acquire_lock; handle_preexisting + n="$(row_line "$lane")" || exit 2 + row="$(sed -n -e "${n}p" "$LANES_FILE")" + row_split_session_cell "$row" || die "lane $lane's row (line $n) does not have three '|' before its session cell ends; refusing to touch it" 2 + c="$(count_occurrences "$RSC_CELL" "$old")" || exit 2 + if [ "$c" != 1 ]; then + whole="$(count_occurrences "$row" "$old" || printf '?')" + die "'$old' occurs $c time(s) in lane $lane's SESSION CELL (line $n); exactly 1 required there. The row as a whole carries it $whole time(s) — that difference is exactly why this act is cell-scoped and not replace-in-row." 2 + fi + replace_line "$n" "$RSC_HEAD$(rstrip_spaces "$RSC_CELL") $add $RSC_TAIL" + msg="LANES($lane@$WS): ${why:-append-session-id}" + [ -n "$PRE_DIRTY_LANES" ] && msg="$msg + sweeps uncommitted edit to row $PRE_DIRTY_LANES" + commit_push "$msg" + ;; + + append-line) + text="${1-}"; [ -n "$text" ] || die "usage: append-line \"<text>\"" 2 + # ONE LINE, REFUSED A NEWLINE BEFORE THE LOCK (opensoft/openRepoTools#85). + # `append_text_line` refuses it too, and before it writes — but that is + # after `acquire_lock` and `handle_preexisting`, which can COMMIT a peer's + # uncommitted register edit before this act's own write. A refusal that has + # already committed something is a refusal that wrote, so the verb asks + # first, exactly where `write_event` asks for `log`: the checkout is left + # as this command found it. `lane-handoff`'s file-level PAUSED line is the + # caller that met it, with a `why` carrying a newline. + if [ "${text//[$'\n\r']/}" != "$text" ]; then + die "append-line appends ONE line to the register, and this text carries a newline or a carriage return: it would append several, and the proof that only one was added would fail after the write, leaving the register modified and uncommitted. Nothing was written, and the lock was not taken. Spell the break '; ' and re-run." 2 + fi + # NO MARKER BY THE BACK DOOR (Copilot round 3 on #97): `add-row` refuses a + # row in the marker's vocabulary, and this appends any line at all to the + # register — a row-shaped one included. + if managed_projection_hint "$text"; then + die "the line carries managed-owner vocabulary ('managed owner', 'managed binding', 'mode=managed' or 'managed:'), and only the managed ledger's own writer writes it into the register. Nothing was written." 2 + fi + lane_tag="${LANES_LANE:-}" + [ -z "$lane_tag" ] || lane_tag="$(canon_lane "$lane_tag")" || exit 2 + if [ -z "$lane_tag" ]; then + cand="$(lane_from_text "$text")" + # AMENDMENT 15 — `row_lane_ci` ALONE, and the exact branch that used to + # sit above it is the same question asked twice now that `row_line` + # compares case-insensitively too. It answers with the ROW's spelling + # rather than the LINE's, which is what Rule 10's wire form needs: the + # line says `Lane: openxfactory-2` in lowercase and the row's token is + # `openXfactory-2`. It is still the register that decides — a candidate no + # row matches prints nothing, so "…names no lane at all" is never + # attributed to a lane called "at". + # + # AND THE 15(d) PAIR IS A REFUSAL HERE TOO, not an absence. `row_lane_ci` + # answers EMPTY for two rows exactly as it does for none, and an empty + # `lane_tag` is a commit attributed to nobody — a writer carrying on over + # the one register state the amendment says every writer refuses (Copilot + # round 1 on openRepoTools#41). `canon_lane` is asked for its STATUS only; + # which of "no row" and "one row" it is stays `row_lane_ci`-s answer. + # + # AMENDMENT 16(e) — AND THE NAME THE LINE CARRIES MAY BE A FORMER ONE. + # Rule 6 attribution is named in clause (e)'s own list of readers, and a + # line that says `lane <old>` is one lane's line whatever the register + # calls that lane today: `canon_lane` resolves it, and `row_lane_ci` still + # has the last word about whether any row answers at all, which is what + # keeps "…names no lane at all" from being attributed to a lane called + # "at". + if [ -n "$cand" ]; then + cand_c="$(canon_lane "$cand")" || exit 2 + lane_tag="$(row_lane_ci "${cand_c:-$cand}")" + fi + fi + acquire_lock; handle_preexisting + append_text_line "$text" + msg="LANES(${lane_tag:-unknown}@$WS): append line — ${text:0:72}" + [ -n "$PRE_DIRTY_LANES" ] && msg="$msg + sweeps uncommitted edit to row $PRE_DIRTY_LANES" + commit_push "$msg" + ;; + + add-row) + row="${1-}"; [ -n "$row" ] || die "usage: add-row \"<full | row |>\"" 2 + case "$row" in + "| "*) : ;; + *) die "a row must start with '| '" 2 ;; + esac + case "$(rstrip_spaces "$row")" in + *"|") : ;; + *) die "a row must end with '|'" 2 ;; + esac + pipes="$(count_occurrences "$row" "|")" || exit 2 + [ "$pipes" -ge 8 ] || die "a 7-column row needs at least 8 '|' characters, found $pipes" 2 + if managed_projection_hint "$row"; then + die "the new row carries managed-owner vocabulary ('managed owner', 'managed binding', 'mode=managed' or 'managed:'), and only the managed ledger's own writer writes a managed-owner marker, and a legacy writer that wrote its vocabulary into a row would forge that lane's ownership (ruling 2026-10-04: \"managed ledger owns enrolled lanes; #97 owns legacy\"). Nothing was written." 2 + fi + lane_new="$(printf '%s' "$row" | cut -d'`' -f2)" + # AMENDMENT 15(a) — A ROW UNDER ANY CASE IS A ROW, AND THE REFUSAL NAMES IT. + # This is the act the 2026-09-13 incident got past: `lane-start openxfactory + # 2` found no row for `openXfactory-2` and appended a second one for a lane + # that already had one. `row_line`'s exactly-one test cannot be the whole + # gate here, because two rows differing only by case make it fail for the + # OTHER reason and a failed `row_line` used to read as "no row, go ahead". + # + # AND THE PUBLISHED ROWS ARE ASKED TOO — R19, AND R30's FETCH IN FRONT OF IT + # (Copilot round 4 on openRepoTools#41). The scan was of `$LANES_FILE` alone, + # which a fetch does not move: on a checkout that is behind, a row `origin` + # already carries as `repoCase-1` is invisible here, this appends + # `repocase-1`, and `commit_push`'s own rebase then publishes the pair — the + # exact duplicate 15(a) makes this command refuse, arrived at through the one + # file the check never read. BOTH sets are asked and either is the refusal: + # the local scan stays because a row added here and not yet pushed is on no + # `origin` at all, and the published scan is the one the incident needed. + if [ -n "$lane_new" ]; then + log_sync + # AND THE ARCHIVE IS ASKED AS WELL (Amendment 19(b) and (d)). A row + # `archive-rows` has moved into `lanes/archive/LANES-retired.md` is still + # that lane's row: its object log is `lanes/log/<lane>.md` and that file is + # APPEND-ONLY, so a second lane under the same name would write its life + # into the first one's file and every read of that log — who held what, + # when it was claimed, which session paused it — would answer for two + # lanes at once. `next-free` never OFFERS such a position, because it + # counts the archive too; this is what refuses one that is typed by hand, + # which is the whole of "a retired `<repo>-<n>` is never reissued". + # BOTH COPIES OF THE ARCHIVE (Copilot round 1 on #93): `archive_text` + # answers with the PUBLISHED file wherever there is one, so a move + # committed here and not yet pushed was invisible to this check and its + # name came back on offer. The local file is read beside it, exactly as + # the row scan below reads `rows_named_ci_local` beside `rows_named_ci`. + # + # AND A READ THAT FAILED IS A REFUSAL, not an empty archive (round 2): the + # whole point of this check is that a retired identity is never reissued, + # and "I could not read the file that says which ones are retired" is not + # "none of them are" (Amendment 7(d)). NOR IS A LINE IT COULD NOT TAKE + # APART (#122): that row may be this lane's own, so it is the same refusal + # and the same 1, naming the line. + ar_arch_rc=0 + ar_arch="$(retired_identity_hits "$lane_new")" || ar_arch_rc=$? + case "$ar_arch_rc" in + 0) : ;; + 3) die "$LANES_ARCH_PATH carries a line this scan cannot take apart (above), so whether '$lane_new' is a name this estate has RETIRED is not known: a row this scan cannot take apart may be that lane's own, and a retired position is never reissued (Amendment 19(b)). A row that could not be read is not a row that is not there (Amendment 7(d)). Put the lane back in backticks in that row's first cell, or remove the line if it is no row; commit the archive (\`git -C $LANES_REPO commit -m \"<what it was>\" -- $LANES_ARCH_PATH\`), publish it where the line is on origin (\`LANES_LANE=<lane> lanes-edit.sh commit \"<what it was>\"\`), and re-run. Nothing was written." 1 ;; + *) die "$LANES_ARCH_PATH exists and could not be read or scanned, so whether '$lane_new' is a name this estate has RETIRED is not known — and a retired position is never reissued (Amendment 19(b)). A read that failed is not 'it is not retired' (Amendment 7(d)). Fix the read and re-run; nothing was written." 1 ;; + esac + if [ -n "$ar_arch" ]; then + die "lane '$lane_new' is RETIRED: its row is in $LANES_ARCH_PATH, spelled $(printf '%s\n' "$ar_arch" | tr '\n' ' ')— and a retired position is NEVER REISSUED (Amendment 19(b)). That lane's object log is $(log_path_for "$lane_new") and it is append-only, so a second lane under this name would write its life into the first one's file and every read of that log would answer for two lanes at once. Take a free position instead — \`lanes --prefix <repo>\` prints the next one and the line that takes it. Nothing was written." 2 + fi + ar_hits="$(rows_named_ci_local "$lane_new")" + # THE PUBLISHED ROWS ARE READ WITH THEIR STATUS (Copilot round 21 on #93, + # #138 item 18). Through `|| :` a register origin has and git could not + # read was "no row there", and a row this checkout had not pulled was + # appended a second time — and landed, wherever the rebase did not clash. + ar_pub="" + ar_pub="$(rows_named_ci "$lane_new" 2>/dev/null)" || + die "the published register on origin/$LANES_BRANCH could not be read, so whether '$lane_new' already has a row there is not known — and that is NOT 'it has none' (Amendment 7(d)): a row this checkout has not pulled would be added a second time. Fix the read and re-run; nothing was written." 1 + ar_all="$(printf '%s\n%s\n' "$ar_hits" "$ar_pub" | grep -v '^$' | LC_ALL=C sort -u || :)" + ar_n="$(printf '%s' "$ar_all" | grep -c . || :)" + ar_ln="$(printf '%s' "$ar_hits" | grep -c . || :)" + if [ "$ar_n" -gt 0 ]; then + # A LANE THE MANAGED LEDGER OWNS IS SAID TO BE ONE (Copilot round 3 on + # #97) before the duplicate refusal below, which would refuse it anyway + # without naming the owner. A new lane has no row and is never asked. + managed_seam_refuse "$lane_new" "add-row" + ar_more="" + [ "$ar_n" -gt 1 ] && ar_more=" Those $ar_n rows differ only by case and are themselves the refusal: merge them into one row first (Amendment 15(d))." + ar_where="Use set-row-state / replace-in-row on the row that is there." + [ "$ar_ln" = 0 ] && ar_where="That row is on origin/$LANES_BRANCH and this checkout has not pulled it, so adding one here would make two the moment this push rebases. Pull first — \`git -C $LANES_REPO pull --rebase\` — then use set-row-state / replace-in-row on the row that is there." + die "lane '$lane_new' already has a row, spelled $(printf '%s\n' "$ar_all" | tr '\n' ' ')— a lane name is ONE name under any case (Amendment 15(a)), so a row under another case IS that lane's row and this would be a second one. $ar_where$ar_more" 2 + fi + fi + acquire_lock; handle_preexisting + append_text_line "$row" + msg="LANES(${lane_new:-${LANES_LANE:-unknown}}@$WS): add row" + [ -n "$PRE_DIRTY_LANES" ] && msg="$msg + sweeps uncommitted edit to row $PRE_DIRTY_LANES" + ADD_ROW_LANE="$lane_new" + ADD_ROW_TEXT="$row" + CP_AFTER_REBASE=add_row_retirement_rescan + commit_push "$msg" + ar_push_rc=$? + CP_AFTER_REBASE="" + exit "$ar_push_rc" + ;; + + commit) + msg="${1-}"; [ -n "$msg" ] || die "usage: commit \"<message>\"" 2 + # AMENDMENT 15 — `$LANES_LANE` passes through the resolver like every + # `<lane>` argument does: it is the attribution in this commit's subject and + # the name the "touches other rows" test compares against. + [ -z "${LANES_LANE:-}" ] || LANES_LANE="$(canon_lane "$LANES_LANE")" || exit 2 + acquire_lock + # `commit` has no edit of its own to separate from a pre-existing one — + # its whole job is to wrap whatever is already dirty (a hand edit made + # with an allowed tool). The best it can do is warn when that dirty + # content ALSO touches a ROW other than the caller's own $LANES_LANE, + # and say so in the commit subject (0d84d34: a hermes-wallet-exercise + # `commit` call silently absorbed an unrelated openXfactory-2 row edit). + # "append" (a plain line with no row of its own, e.g. this call's own + # Rule 6 LANDING/LANDED line) is excluded from "other" — it is the + # normal, expected shape of exactly what `commit` is for, and flagging + # it would warn on every ordinary use. + if [ "$NO_GIT" != 1 ] && ! git -C "$LANES_REPO" diff --quiet -- "${CP_PATHS[@]}" 2>/dev/null; then + touched="$(identify_changed_lanes)" + other="$(printf '%s\n' "$touched" | tr ',' '\n' | grep -v -x -e "${LANES_LANE:-}" -e '' -e 'append' | paste -sd, - 2>/dev/null || :)" + if [ -n "$other" ]; then + note "WARNING: uncommitted LANES.md changes touch row(s) other than this lane (${LANES_LANE:-unknown}): $other" + warn_dirty + msg="$msg + sweeps uncommitted edit to row $other" + fi + fi + # #194 — the one write that, with nothing to stage, publishes the local + # commits ahead of origin: it is the RECOVERY's re-run. See commit_push. + CP_PUBLISH_AHEAD=1 + commit_push "LANES(${LANES_LANE:-unknown}@$WS): $msg" + ;; + + # AMENDMENT 19(c) — THE SWEEP'S WRITE. `lane-end --retire-dormant <repo>` is + # the word that finds the dormant rows, shows the dry run and takes the + # person's `--yes`; this is the one commit under it, and it re-proves every + # refusal for itself rather than trusting the caller's list. + retire-rows) + retire_rows ${1+"$@"} + ;; + + # AMENDMENT 19(d) — THE ARCHIVE. A DRY RUN unless `--yes` is passed, like the + # migration beside it, and one commit naming each lane moved when it is. + archive-rows) + ar_repo=""; ar_yes=0 + while [ $# -gt 0 ]; do + case "$1" in + --yes) ar_yes=1; shift ;; + --dry-run) ar_yes=0; shift ;; + --) shift ;; + -*) die "unknown option '$1' for archive-rows (usage: archive-rows <repo> [--yes])" 2 ;; + *) [ -z "$ar_repo" ] || die "archive-rows takes ONE repository: archive-rows <repo> [--yes]" 2 + ar_repo="$1"; shift ;; + esac + done + [ -n "$ar_repo" ] || die "usage: archive-rows <repo> [--yes] — without --yes it is a DRY RUN that writes nothing" 2 + archive_rows "$ar_repo" "$ar_yes" + ;; + + # ====================================================== AMENDMENT 16 ======= + # + # `rename-lane <old> <new> ["<why>"] [--verbatim] [--no-github]` — A LANE IS + # RENAMED IN ONE COMMIT, REFUSED OR WHOLE, AND ITS OLD NAME RESOLVES FOR EVER. + # + # Ratified 2026-09-14T09:24:35Z, verbatim *"Ratify as drafted (Recommended)"*, + # on Brett Heap's request of the same day, verbatim *"we need the ability to + # rename a lane"*. `lane-rename <old> <new>` on PATH is the word a person + # types; THIS is its write. The two are one act only because the word also + # renames the tmux window and types `/rename <new>` into the pane — neither of + # which a register writer may do for a session it is not (Amendment 16(f), and + # Amendment 12(h)'s M1 for why the typing is the only path a running session's + # name has). + # + # FOUR MOVES, ONE COMMIT (clauses (b)–(e)): the row's key cell, the object + # log, the handoff, and `lanes/aliases.tsv`. They are one commit because ANY + # TWO OF THEM APART IS A STATE NO READER CAN READ — a row under `<new>` whose + # log is still `<old>.md` is a lane whose history `who --lane` cannot find, and + # an alias without the row it points at is a name that resolves to nothing. So + # every refusal in clause (a) is made BEFORE THE FIRST BYTE IS WRITTEN, and + # each one of them says "Nothing was written": this command moves four files + # and a half-done rename is not something a second run can finish. + # + # AND THE `git mv` OF CLAUSES (c) AND (d) IS A PLAIN `mv` PLUS A PATHSPEC. + # `git mv` is one command and it also STAGES, which is the one thing this file + # never does: `commit_push` commits from its PATHSPECS precisely so that a + # peer's uncommitted work in this shared checkout can never be swept into a + # lane's commit (Amendment 5(d), and the sweep that made `--no-sweep` the + # default). Both paths go in as pathspecs of the one commit and git records + # the rename from the content, as it always does. `ensure_log`'s two-step + # `mv` is not needed either: a case-ONLY rename is refused below, so the two + # names are two files on every filesystem this ships to. + rename-lane) + rl_old=""; rl_new=""; rl_why=""; rl_verbatim=0 + while [ $# -gt 0 ]; do + case "$1" in + --verbatim) rl_verbatim=1; shift ;; + --no-github) NO_GITHUB=1; shift ;; + --why) rl_why="${2-}"; [ -n "$rl_why" ] || die "--why needs a reason" 2; shift 2 ;; + --why=*) rl_why="${1#--why=}"; [ -n "$rl_why" ] || die "--why needs a reason" 2; shift ;; + --) shift ;; + -*) die "unknown option '$1' for rename-lane" 2 ;; + *) + if [ -z "$rl_old" ]; then rl_old="$1" + elif [ -z "$rl_new" ]; then rl_new="$1" + elif [ -z "$rl_why" ]; then rl_why="$1" + else die "rename-lane takes <old> <new> [\"<why>\"] — '$1' is one argument too many" 2 + fi + shift ;; + esac + done + [ -n "$rl_old" ] && [ -n "$rl_new" ] \ + || die "usage: rename-lane <old> <new> [\"<why>\"] [--verbatim] [--no-github]" 2 + check_lane_name "$rl_old" + check_lane_name "$rl_new" + if managed_projection_hint "$rl_new"; then + die "the new name '$rl_new' carries managed-owner vocabulary ('managed-owner' or 'managed-binding'), so the row it is written into would read as a malformed managed-owner marker — ownership UNKNOWN for every act. Choose another name. Nothing was written." 2 + fi + # THE REASON IS FREE TEXT ON AN APPEND-ONLY LINE, so it takes the writer's + # own two rules before anything else is read (`write_event` states both): a + # third ` — ` leaves the line ambiguous to its own parser, and a newline + # appends lines to a file whose proof counts exactly one. + case "$rl_why" in + *" — "*) die "the reason may not contain ' — ': that separator divides an event line's verb from its fields and its fields from its free text, and a third one leaves the line ambiguous to its own parser, in a file nothing ever rewrites. Use a semicolon or a colon: '$rl_why'" 2 ;; + esac + if [ "${rl_why//[$'\n\r']/}" != "$rl_why" ]; then + die "the reason is ONE line: a newline in it would append several lines to an append-only log, and the proof that only one was added would fail after the write rather than before it" 2 + fi + rl_utc="$(utc_now)" + [ -n "$rl_why" ] || rl_why="renamed with lane-rename (lane-collision-protocol Amendment 16)" + + # ---- (a) THE REFUSALS. The fetch first, because every read below is of + # `origin/<branch>` (R19, R30) — a rename computed from a checkout that is + # behind is a rename whose push rebases into two rows. + log_sync + # AND THE OLD NAME GOES THROUGH THE RESOLVER LIKE ANY OTHER, WHICH MAKES + # RENAMING UNDER AN ANCIENT NAME WORK: `canon_lane` answers with the row's + # own spelling, and with clause (e) behind it a name this lane was called + # two renames ago renames the lane it is now. + rl_crc=0 + rl_old="$(canon_lane "$rl_old")" || rl_crc=$? + # ONE CONDITION, ONE CODE (Copilot round 6 on openRepoTools#81). `canon_lane` + # answers 66 for an alias table it could not read so that `canon-lane`'s four + # callers can tell it from a refusal — but a flat `|| exit 2` here made THIS + # writer answer 2 or 1 for the same fault depending on whether the typed name + # happened to have a row of its own, because a name with one never reaches + # the table at all. Translated to this command's own 1, which is what its + # other two alias-read refusals already spend and what the amendment's + # fail-closed rule is about. + case "$rl_crc" in + 0) : ;; + 66) die "${LANES_ALIASES_PATH:-lanes/aliases.tsv} could not be read ($(lane_alias_err)), and a rename whose alias table cannot be read is a rename whose old name may stop resolving — which is the one thing clause (e) promises for ever, so this fails closed. Nothing was written." 1 ;; + *) exit 2 ;; + esac + # THE OLD NAME'S LIFECYCLE CONTROL ROOT, read while the old name still has + # its log (openRepoTools#91; `lane_state_rename` moves it after the commit). + rl_lsr_old="$(lane_control_root "$rl_old" 2>/dev/null)" || rl_lsr_old="" + # THE SEAM (ruling 2026-10-04). A managed lane's marker names its lane as + # `bound-lane=`, so renaming the row under it would turn a valid marker into + # an unparseable one; the rename is the ledger's, and refused before the lock. + managed_seam_refuse "$rl_old" "rename-lane" + + # ---- THE MUTEX IS TAKEN BEFORE THE CHECKS, NOT BETWEEN THEM AND THE WRITE + # (Copilot round 6 on openRepoTools#81). Every refusal below reads a row, a + # log path, the alias table and a handoff, and every one of them is a + # question about what is NOT there — so two renames on one workstation could + # both answer "the target is free", and the second would move its log over + # the first's and rewrite a row it read before the first commit. The lock is + # this workstation's serialiser and it costs nothing to take it early: it is + # not a write, every refusal below still writes nothing, and `cleanup` + # releases it on every path out, the two signals included. + # + # ACROSS WORKSTATIONS the arbiter is the same one Rule 1's claim has: + # whichever commit lands on `main` first. `commit_push`'s rebase brings the + # other's row and log in, and the loser's next attempt meets its own + # refusals — a row under `<new>`, a published log — with nothing written. + acquire_lock + + # Refuse a spelling-only rename before probing both roots: on a + # case-insensitive filesystem they are the same intent, whose stored lane + # carries the canonical spelling rather than the requested new spelling. + if [ "$(lc "$rl_old")" = "$(lc "$rl_new")" ]; then + die "'$rl_old' and '$rl_new' are ONE name under any case (Amendment 15), so this is not a rename at all: it is a change to the row's own SPELLING, which every reader already resolves to and which Amendment 15(d) makes a hand act — the newer row's session id(s) appended to the older row's cell, in one commit. Nothing was written." 2 + fi + + # Rename and restart publication share this mutex. An unfinished operation + # owns its name and canonical inputs, including recovery from failed. + for rl_check in "$rl_old" "$rl_new"; do + rl_root_rc=0 + lane_restart_control_root "$rl_check" >/dev/null || rl_root_rc=$? + [ "$rl_root_rc" != 8 ] || continue # no root any writer could have used + [ "$rl_root_rc" = 0 ] || die "restart control root could not be read. Nothing was written." 1 + rl_restart=""; rl_restart_rc=0 + rl_restart="$(lane_restart_read "$rl_check")" || rl_restart_rc=$? + case "$rl_restart_rc" in + 8) continue ;; + 0) rl_restart_state="$(printf '%s\n' "$rl_restart" | awk -F'\t' '$1=="state" {print $2; exit}')" + [ "$rl_restart_state" = ready ] || die "lane $rl_check has restart intent $rl_restart_state; finish its supervised recovery before renaming. Nothing was written." 2 ;; + *) die "lane $rl_check restart intent could not be read. Nothing was written." 1 ;; + esac + done + + rl_oh="$(rows_named_ci "$rl_old" 2>/dev/null || :)" + rl_on="$(printf '%s' "$rl_oh" | grep -c . || :)" + rl_lh="$(rows_named_ci_local "$rl_old" 2>/dev/null || :)" + rl_ln="$(printf '%s' "$rl_lh" | grep -c . || :)" + if [ "$rl_on" -gt 1 ] || [ "$rl_ln" -gt 1 ]; then + die "the register holds rows whose lane names differ only by case for '$rl_old': $(printf '%s\n%s\n' "$rl_oh" "$rl_lh" | grep -v '^$' | LC_ALL=C sort -u | tr '\n' ' ')— a lane name is ONE name under any case (Amendment 15), so there is no ONE row to rename. Merge them first (Amendment 15(d)): append the newer row's session id(s) to the older row's session cell, in order, and remove the newer row in the SAME commit. Nothing was written." 2 + fi + if [ "$rl_ln" = 0 ]; then + if [ "$rl_on" = 1 ]; then + die "lane $rl_old's row is on origin/$LANES_BRANCH and this checkout has not pulled it, so the row this rename must rewrite is not here — and a rename that appended a second row would be the very duplicate Amendment 15(a) refuses. Pull first — \`git -C $LANES_REPO pull --rebase\` — and re-run. Nothing was written." 2 + fi + die "the register has no row for lane '$rl_old', in any case (Amendment 15(a)) and through no alias (Amendment 16(e)). A rename moves a row that exists; \`lanes --all\` lists the ones that do. Nothing was written." 2 + fi + + # A ROW UNDER `<new>` IN ANY CASE, asked of BOTH the published register and + # this copy of it — `add-row`'s own pair of scans, for its own reason: a row + # `origin` already carries is invisible to a local scan, and this push would + # rebase the two together. + rl_nh="$(printf '%s\n%s\n' "$(rows_named_ci "$rl_new" 2>/dev/null || :)" "$(rows_named_ci_local "$rl_new" 2>/dev/null || :)" | grep -v '^$' | LC_ALL=C sort -u || :)" + if [ -n "$rl_nh" ]; then + die "lane '$rl_new' already has a row, spelled $(printf '%s\n' "$rl_nh" | tr '\n' ' ')— a lane name is ONE name under any case (Amendment 15(a)), so renaming into it would make TWO rows for one name, which is the state every writer in this file refuses until 15(d)'s merge. Nothing was written." 2 + fi + + # `<new>` IS `<repo>-<n>` UNLESS `--verbatim` NAMES IT. Rule 4's form is + # what `lanes --prefix`, the next free position and `lane-start <repo> <n>` + # are all computed from, so a lane renamed out of it loses every one of + # them; Amendment 11's `--dir` lanes are the deliberate exception the flag + # exists for. + if [ "$rl_verbatim" = 0 ] && ! lane_shaped "$rl_new"; then + die "'$rl_new' is not of the form <repo>-<n> (Rule 4), and a lane renamed out of that form loses the next free position, the \`lane-start <repo> <n>\` that takes it and the whole of \`lanes --prefix\`. A lane deliberately named otherwise — Amendment 11's \`--dir\` lanes are the ones there are — is renamed with --verbatim. Nothing was written." 2 + fi + + # A `<new>` THAT IS ALREADY AN ALIAS KEY IS REFUSED (Copilot round 1 on + # openRepoTools#81). A row wins over an alias at every hop — that is what + # makes a name that is a lane today BE that lane — so minting a row under a + # name some other lane was renamed AWAY from would end that lane's old name + # resolving, which is the one thing clause (e) promises never happens. The + # refusal is here, at the one writer that can do it deliberately; a row + # minted under a freed name by `lane-start` is a different act and the + # readers handle it by the row-wins rule itself. + rl_krc=0 + rl_keys="$(lane_alias_keys 2>/dev/null)" || rl_krc=$? + if [ "$rl_krc" = 5 ]; then + die "${LANES_ALIASES_PATH:-lanes/aliases.tsv} could not be read ($(lane_alias_err)), and a rename whose alias table cannot be read is a rename whose old name may stop resolving — which is the one thing clause (e) promises for ever, so this fails closed. Nothing was written." 1 + fi + rl_kmatch="$(printf '%s\n' "$rl_keys" | awk -v w="$rl_new" 'BEGIN { lw = tolower(w) } NF && tolower($0) == lw { print; exit }')" + if [ -n "$rl_kmatch" ]; then + die "'$rl_new' is already a FORMER name in ${LANES_ALIASES_PATH:-lanes/aliases.tsv} (spelled '$rl_kmatch'), and a row under it would take precedence over that alias — which would end a lane's old name resolving, the one thing Amendment 16(e) promises for ever. Pick a name no lane has ever been called. Nothing was written." 2 + fi + + # A CYCLE, ASKED OF THE TABLE AS IT WILL BE (clause (e)). Adding `<old> → + # <new>` closes one exactly when the chain from `<new>` reaches `<old>`, + # anywhere along it — the new row is appended last and wins the key. + rl_arc=0 + lane_alias_target "$rl_new" "$rl_old" >/dev/null 2>&1 || rl_arc=$? + case "$rl_arc" in + 0 | 1) : ;; + 3) die "${LANES_ALIASES_PATH:-lanes/aliases.tsv} already resolves '$rl_new' in a CYCLE, so nothing can be added through it until that row is taken out by hand. \`rename-lane\` writes no cycle, so this table was hand-edited. Nothing was written." 2 ;; + 4) die "renaming $rl_old to $rl_new would close a CYCLE in ${LANES_ALIASES_PATH:-lanes/aliases.tsv}: '$rl_new' already resolves back through '$rl_old', and a chain that returns to its own start has no end for a reader to resolve to (Amendment 16(e)). Nothing was written." 2 ;; + *) die "${LANES_ALIASES_PATH:-lanes/aliases.tsv} could not be read ($(lane_alias_err)), and a rename whose alias table cannot be read is a rename whose old name may stop resolving — which is the one thing clause (e) promises for ever, so this fails closed. Nothing was written." 1 ;; + esac + + # THE SESSION FIELD OF THE `RENAMED` LINE IS A TRANSCRIPT UUID AND ONLY + # THAT (Amendment 7(b), R-A11 (e)) — asked HERE, with the other refusals, + # rather than by `write_event`, because this write does not go through + # `write_event`: its line lands in the same commit as three file moves. + rl_uuid="$(session_for "$rl_old")" + if ! valid_uuid "$rl_uuid"; then + die "an event's session field is the TRANSCRIPT UUID and only that (Amendment 7(b)), and this rename's RENAMED line has none: '${rl_uuid:-<empty>}'. Name the session taking the act: LANES_SESSION=\"\$CLAUDE_CODE_SESSION_ID\" lanes-edit.sh rename-lane $rl_old $rl_new. Nothing was written." 2 + fi + + # A LIVE SESSION HOLDING `<old>` IN ANOTHER WINDOW. + # + # THE WINDOW THIS COMMAND RUNS IN IS EXEMPT, AND IT IS THE ORDINARY CASE: a + # lane renames ITSELF, from its own pane, which is the whole of clause (f). + # `live_holder`'s fifth field is the verdict that tells the two apart — + # `here`, `elsewhere`, `orphan` — and it is the same read `lane-start` + # refuses a name over. The id SET is the published row's union this + # checkout's (R25), for that rule's reason: liveness fails CLOSED here, so + # an id `origin` has not seen yet is one more reason to refuse. + rl_ids="$( { session_ids_of_lane "$rl_old" 2>/dev/null || : + session_ids_local_of_lane "$rl_old" 2>/dev/null || :; } | awk 'NF && !seen[$0]++')" + rl_lhv=""; rl_lhrc=0 + rl_lhv="$(live_holder "$rl_old" "$rl_ids" 2>/dev/null)" || rl_lhrc=$? + case "$rl_lhrc" in + 8) : ;; + 0) + IFS="$US" read -r rl_hsid rl_htgt rl_hname rl_hpid rl_hverdict <<EOF +$rl_lhv +EOF + if [ "${rl_hverdict:-}" != here ]; then + die "a LIVE session holds lane $rl_old and it is not this window's: session $rl_hsid, pid $rl_hpid, named '${rl_hname:-none}', window ${rl_htgt:-none} (${rl_hverdict:-unknown}). Clause (a) refuses that, and clause (f) is why: the session's own NAME is locked to the lane (Amendment 12(h)) and only the session itself can change it, so a rename made from anywhere else leaves a running conversation named for a lane the register no longer has. Run \`lane-rename $rl_old $rl_new\` in THAT window, or hand the lane off first (\`lane-handoff\`) and rename it once it is paused. Nothing was written." 2 + fi ;; + *) die "could not read this workstation's session records for lane $rl_old: ${SESSION_FILES_ERR:-unknown error}. That is NOT 'no live session holds it' — clause (a) refuses on a LIVE holder, so a read that could not be made fails closed (R22). Fix the records or the permissions and re-run. Nothing was written." 1 ;; + esac + + # ---- THE FOUR PATHS, ALL COMPUTED BEFORE ANYTHING MOVES. + rl_log_new_rel="$(log_path_for "$rl_new")" + rl_log_new="$(log_file_for "$rl_new")" + # THE TARGET LOG IS LOOKED FOR UNDER ANY CASE, here and on `origin` + # (Copilot round 1 on openRepoTools#81). The exact-path test missed an + # orphan `lanes/log/<NEW>.md` of another spelling on a case-SENSITIVE + # filesystem — Linux and WSL2, where this estate runs — and a rename into it + # would leave two case-variant histories for one lane, which is the state + # Amendment 15(d) makes a hand merge. `log_files_named_ci` and the published + # `ls-tree` scan are the same two reads every other case question here uses. + rl_nlocal="$(log_files_named_ci "$rl_new")" + if [ -n "$rl_nlocal" ]; then + die "lane '$rl_new' has no row and this checkout already carries $(printf '%s\n' "$rl_nlocal" | tr '\n' ' ')— an object log under that name, in some case. That file is not this rename's to write into, and appending one lane's history to another's is the one thing an append-only log cannot be walked back from. Nothing was written." 2 + fi + if have_remote_ref; then + rl_npub="$(git -C "$LANES_REPO" ls-tree --name-only "origin/$LANES_BRANCH" -- "$LANES_LOG_PREFIX" 2>/dev/null \ + | awk -v want="$rl_log_new_rel" 'BEGIN { w = tolower(want) } tolower($0) == w')" + if [ -n "$rl_npub" ]; then + die "$(printf '%s\n' "$rl_npub" | tr '\n' ' ')is published on origin/$LANES_BRANCH while lane '$rl_new' has no row — renaming into it would merge two lanes' histories into one append-only file. Nothing was written." 2 + fi + fi + rl_lfhits="$(log_files_named_ci "$rl_old")" + rl_lfn="$(printf '%s' "$rl_lfhits" | grep -c . || :)" + if [ "$rl_lfn" -gt 1 ]; then + die "lane $rl_old has $rl_lfn object logs whose names differ only by case: $(printf '%s\n' "$rl_lfhits" | tr '\n' ' ')— one lane is ONE lane under any case and its log is ONE file (Amendment 15). Merge them by hand into $(log_file_for "$rl_old"), oldest lines first, remove the others in the same commit (15(d)), and re-run. Nothing was written." 2 + fi + rl_log_old=""; rl_log_old_rel="" + if [ "$rl_lfn" = 1 ]; then + rl_log_old="$rl_lfhits"; rl_log_old_rel="${LANES_LOG_PREFIX}${rl_log_old##*/}" + # A SYMLINK IS NOT THIS LANE'S LOG (Copilot round 4 on openRepoTools#81). + # `ls` lists one like any other file, `mv` moves the LINK, and + # `append_text_line`'s `>>` then writes the RENAMED line THROUGH it — into + # whatever is at the far end, which may be outside this repository + # altogether, while the commit records only the link. The same rule + # `openRepoTools --install` states for every target it places: `cp` + # follows a symlink, so a symlink is a refusal and not a file. + if [ -L "$rl_log_old" ]; then + die "lane $rl_old's object log at $rl_log_old is a SYMLINK. An append-only log is written in place — the RENAMED line would go through the link into whatever is at the far end, and the commit would record the link — so this rename is not made over one. Replace it with the file itself and re-run. Nothing was written." 2 + fi + # AND A REGULAR FILE, NOT MERELY NOT-A-SYMLINK (Copilot round 5). `ls` + # lists a FIFO like any other name, and the snapshot's `cat` of one BLOCKS + # — for ever, holding this lane's mutex — where a refusal costs a second. + if [ ! -f "$rl_log_old" ]; then + die "lane $rl_old's object log at $rl_log_old is not a regular file. An append-only log is read whole for the rollback copy and appended to in place, and neither can be done to that — a FIFO there would block this write, and its lock, indefinitely. Nothing was written." 2 + fi + # AND GIT MUST ALREADY KNOW IT (Copilot round 6 on openRepoTools#81). + # `refuse_dirty_checkout` reads `tracked_dirty`, which reports no untracked + # file, so a peer's uncommitted `lanes/log/<old>.md` walked past it — and + # this rename would MOVE that file to a path it always stages, committing + # somebody else's lines under its own message. Round 3 kept the old path + # out of the pathspecs when it was untracked, which stopped `git add` + # failing and did nothing about the content. + if [ "$NO_GIT" != 1 ] \ + && ! git -C "$LANES_REPO" ls-files --error-unmatch -- "$rl_log_old_rel" >/dev/null 2>&1; then + die "lane $rl_old's object log at $rl_log_old_rel exists here and git does not track it, so its lines have never been committed by anyone — and this rename would move them to $rl_log_new_rel and commit them under its own message. Whoever wrote them commits them first: \`git -C $LANES_REPO add -- $rl_log_old_rel && git -C $LANES_REPO commit -m \"handoff(<lane>@<workstation>): <what>\"\`. Nothing was written." 2 + fi + fi + if have_remote_ref; then + rl_pub="$(log_path_ci "$rl_old")" || die "lane $rl_old's object log is published twice (above), and one lane is ONE lane under any case: its log is ONE file (Amendment 15). Merge them by hand (15(d)) and re-run. Nothing was written." 2 + if [ "$rl_pub" != "$rl_log_old_rel" ] && git -C "$LANES_REPO" cat-file -e "origin/$LANES_BRANCH:$rl_pub" 2>/dev/null; then + die "lane $rl_old's object log is published as $rl_pub while this checkout has ${rl_log_old_rel:-no log for it at all}: a rename made from here would move one file and leave the other, which is two logs for one lane by the path \`ensure_log\` exists to close. Pull first — \`git -C $LANES_REPO pull --rebase\` — and re-run. Nothing was written." 2 + fi + fi + + # AND THE ALIAS TABLE `origin` CARRIES AND THIS CHECKOUT DOES NOT (Copilot + # round 3 on openRepoTools#81). The READ prefers `origin/<branch>`, while + # the APPEND is to the file on disk — so on a checkout that is behind, this + # would create a fresh table holding ONE mapping, and the commit would + # either drop every alias already published or meet an add/add conflict in + # its own rebase. Every name renamed before today would stop resolving, + # which is the one thing clause (e) promises never happens. The cure is the + # one the row and the log guards above already name. + # AND THE ALIAS TABLE IS A FILE, NOT A LINK (Copilot round 4). The append is + # a `>>`, which follows one: a live link would put this estate's permanent + # alias into an arbitrary target and a dangling one would create it, while + # git staged only the link path. + if [ -L "$LANES_ALIASES_TSV" ]; then + die "$LANES_ALIASES_PATH is a SYMLINK at $LANES_ALIASES_TSV. The alias row is appended in place and a redirect follows a link, so it would be written at the far end while this commit recorded the link — and the alias is the one thing that makes a renamed lane's old name resolve for ever (Amendment 16(e)). Replace it with the file itself and re-run. Nothing was written." 2 + fi + if [ -e "$LANES_ALIASES_TSV" ] && [ ! -f "$LANES_ALIASES_TSV" ]; then + die "$LANES_ALIASES_PATH at $LANES_ALIASES_TSV is not a regular file. The alias row is appended in place and the table is read whole for the rollback copy — a FIFO there would block this write, and its lock, indefinitely. Nothing was written." 2 + fi + # AN EXISTING UNTRACKED TABLE IS SOMEBODY'S HAND EDIT (Copilot round 5 on + # openRepoTools#81). `refuse_dirty_checkout` reads `tracked_dirty`, which + # deliberately omits untracked files — so before this estate's FIRST rename + # an untracked `lanes/aliases.tsv` walked past the guard and its contents + # were appended to and committed inside this lane's rename. The only writer + # of that file is this command, and this command commits what it writes, so + # an untracked one was written by hand or left by a run that died. + if [ "$NO_GIT" != 1 ] && [ -f "$LANES_ALIASES_TSV" ] \ + && ! git -C "$LANES_REPO" ls-files --error-unmatch -- "$LANES_ALIASES_PATH" >/dev/null 2>&1; then + die "$LANES_ALIASES_PATH exists here and git does not track it, so it was written by hand or left behind by a run that died — and appending this rename's alias to it would commit somebody else's lines inside this lane's commit. \`rename-lane\` is the only writer of that file and it commits what it writes. Commit it or remove it, and re-run. Nothing was written." 2 + fi + # AND A TABLE WHOSE LAST BYTE IS NOT A NEWLINE IS REFUSED (Copilot round 5). + # `append_text_line`'s `>>` would put this rename's record on the END of the + # previous line — and its own proof passes, because the bytes it builds to + # compare are concatenated the same way. The TSV parser then never sees the + # new alias at all: the rename would commit and the old name would not + # resolve, which is the one thing clause (e) promises. Refused rather than + # repaired, because appending a newline to a file this command did not write + # is an edit to somebody else's lines. + if [ -f "$LANES_ALIASES_TSV" ] && [ -s "$LANES_ALIASES_TSV" ] \ + && [ "$(tail -c 1 -- "$LANES_ALIASES_TSV" | od -An -c | tr -d ' ')" != '\n' ]; then + die "$LANES_ALIASES_PATH does not end with a newline, so appending this rename's record would join it to the last line and the table's own parser would never see the new alias — the rename would land and '$rl_old' would stop resolving (Amendment 16(e)). Put a newline at its end and re-run. Nothing was written." 2 + fi + if have_remote_ref && [ ! -f "$LANES_ALIASES_TSV" ] \ + && git -C "$LANES_REPO" cat-file -e "origin/$LANES_BRANCH:$LANES_ALIASES_PATH" 2>/dev/null; then + die "$LANES_ALIASES_PATH is published on origin/$LANES_BRANCH and this checkout does not have it, so appending here would write a table holding only this one rename and drop every alias already published — every name renamed before today would stop resolving (Amendment 16(e)). Pull first — \`git -C $LANES_REPO pull --rebase\` — and re-run. Nothing was written." 2 + fi + + # THE ROW, AND ITS TWO CELLS. Read before the lock because nothing between + # here and the write changes a byte of it — `capture_register_edit` and + # `handle_preexisting` commit what is already there, they do not edit it. + rl_n="$(row_line "$rl_old")" || exit 2 + rl_row="$(sed -n -e "${rl_n}p" "$LANES_FILE")" + case "$rl_row" in *"|"*) : ;; *) die "lane $rl_old's row (line $rl_n) has no '|' at all; refusing to touch it. Nothing was written." 2 ;; esac + rl_rest="${rl_row#*|}" + case "$rl_rest" in *"|"*) : ;; *) die "lane $rl_old's row (line $rl_n) has one cell and no second '|'; refusing to touch it. Nothing was written." 2 ;; esac + rl_head="${rl_row%%|*}|" + rl_cell="${rl_rest%%|*}" + rl_tail="|${rl_rest#*|}" + [ "$rl_head$rl_cell$rl_tail" = "$rl_row" ] || die "lane $rl_old's row (line $rl_n) does not reassemble from its first cell; refusing to touch it. Nothing was written." 2 + rl_tok="\`$rl_old\`" + case "$rl_cell" in + *"$rl_tok"*) : ;; + *) die "lane $rl_old's row (line $rl_n) does not spell its lane \`$rl_old\` in its first cell, so there is no key cell to rewrite. Nothing was written." 2 ;; + esac + # (b) THE KEY CELL. Prefix and suffix, never `${cell/"$old"/"$new"}`: BASH + # 3.2 keeps the quotes around the REPLACEMENT half as characters, which is + # what once wrote a whole register cell wrapped in double quotes on the + # macOS job (`replace-in-row` states the measurement). + rl_cpre="${rl_cell%%"$rl_tok"*}" + rl_cpost="${rl_cell#*"$rl_tok"}" + rl_newcell="$(rstrip_spaces "$rl_cpre\`$rl_new\`$rl_cpost") *(ex \`$rl_old\`, renamed $rl_utc)* " + rl_newrow="$rl_head$rl_newcell$rl_tail" + + # (d) THE HANDOFF CELL IS COUNTED FROM THE LEFT — awk field 7, the SIXTH + # cell — and never back from NF: the live register carries rows with a + # literal `|` inside a later cell, and counting back from the end puts the + # handoff two cells out on exactly those rows (`handoff_of_lane` says so at + # length). Six pipes consumed, then the cell, then the rest. + rl_pre=""; rl_rem="$rl_newrow"; rl_i=0 + while [ "$rl_i" -lt 6 ]; do + case "$rl_rem" in *"|"*) : ;; *) break ;; esac + rl_pre="$rl_pre${rl_rem%%|*}|"; rl_rem="${rl_rem#*|}"; rl_i=$((rl_i + 1)) + done + rl_hc=""; rl_hpost=""; rl_hsplit=0 + if [ "$rl_i" = 6 ]; then + case "$rl_rem" in + *"|"*) rl_hc="${rl_rem%%|*}"; rl_hpost="|${rl_rem#*|}"; rl_hsplit=1 ;; + esac + fi + [ "$rl_hsplit" = 1 ] && [ "$rl_pre$rl_hc$rl_hpost" = "$rl_newrow" ] || { + rl_hsplit=0 + note "lane $rl_old's row has fewer than seven '|' before its handoff column, so that column is left exactly as it is (Amendment 16(d) moves the file the row NAMES; this row names none in the place the header puts it)" + } + rl_hcell="" + [ "$rl_hsplit" = 1 ] && rl_hcell="$(printf '%s' "$rl_hc" | sed 's/^ *//; s/ *$//')" + rl_hpath_new="$rl_hcell"; rl_hmove=0 + if [ -n "$rl_hcell" ]; then + rl_hbase="${rl_hcell##*/}" + rl_hdir="${rl_hcell%"$rl_hbase"}" + # `session-handoff-<date>-lane-<old>.md` → the same date with + # `lane-<new>` (clause (d)). ANY OTHER SHAPE IS LEFT WHERE IT IS: a + # handoff not named for its lane has no `lane-<name>` in it to rename, + # and inventing one would move a file the row points at to a path the + # row's own history never named. Matched case-insensitively and cut by + # LENGTH, because `${x%$suffix}` cannot match a suffix of another case. + rl_hsuf="-lane-$rl_old.md" + # BOTH SIDES LOWER-CASED INTO VARIABLES FIRST, and the `case` reads them: + # a command substitution inside a case PATTERN is the shape bash 3.2 — + # the bash the macOS job parses every shipped file with — mis-parses at + # the first `)`, which is the rule `tests/test_repo_hygiene.py` holds for + # every file here. + rl_hb_lc="$(lc "$rl_hbase")" + rl_hs_lc="$(lc "$rl_hsuf")" + case "$rl_hb_lc" in + *"$rl_hs_lc") + rl_hkeep=$(( ${#rl_hbase} - ${#rl_hsuf} )) + if [ "$rl_hkeep" -gt 0 ]; then + rl_hpath_new="$rl_hdir${rl_hbase:0:$rl_hkeep}-lane-$rl_new.md" + rl_hmove=1 + fi ;; + esac + fi + rl_hfile=""; rl_hfile_new=""; rl_h_rel=""; rl_h_rel_new="" + if [ -n "$rl_hcell" ]; then + case "$rl_hcell" in + '~/'*) rl_hfile="$HOME/${rl_hcell#'~/'}"; rl_hfile_new="$HOME/${rl_hpath_new#'~/'}" ;; + /*) rl_hfile="$rl_hcell"; rl_hfile_new="$rl_hpath_new" ;; + *) rl_hfile="${LANES_REPO:+$LANES_REPO/}$rl_hcell"; rl_hfile_new="${LANES_REPO:+$LANES_REPO/}$rl_hpath_new" ;; + esac + # THE CONTAINMENT TEST IS PHYSICAL (Copilot round 5 on openRepoTools#81). + # A string prefix accepts `handoffs/../../outside/x.md` and accepts a path + # whose PARENT is a symlink out of the checkout — both of which resolve + # outside it, so the file would be moved and stamped before git refused + # the pathspec. The directory's own `cd -P` is the resolution + # `lane-start:2941` already makes for this very path, and for the same + # reason it gives: `readlink -f` is not in the stock macOS userland. + # + # THE QUESTION IS PUT TO THE NEAREST ANCESTOR THAT EXISTS, which is the + # rule `openRepoTools --install` already states for its own targets. A row + # names a handoff before anything writes one — `lane-start` puts the path + # in the row at the lane's first launch and `lane-handoff` creates the file + # (and its estate directory) at the first swap — so `cd -P` of the leaf + # directory fails for every lane that has not swapped yet, and taking that + # failure as "outside the workspace" refused the ordinary case. + if [ -n "${LANES_REPO:-}" ]; then + rl_repo_real="$( CDPATH=''; cd -P -- "$LANES_REPO" 2>/dev/null && pwd -P )" || rl_repo_real="$LANES_REPO" + rl_anc="$(dirname -- "$rl_hfile")"; rl_suffix=""; rl_hdir_real=""; rl_walk=0 + while [ "$rl_walk" -lt 64 ]; do + if [ -d "$rl_anc" ]; then + rl_hdir_real="$( CDPATH=''; cd -P -- "$rl_anc" 2>/dev/null && pwd -P )" || rl_hdir_real="" + break + fi + case "$rl_anc" in */*) : ;; *) break ;; esac + rl_suffix="${rl_anc##*/}${rl_suffix:+/$rl_suffix}" + rl_anc="${rl_anc%/*}" + [ -n "$rl_anc" ] || rl_anc=/ + rl_walk=$((rl_walk + 1)) + done + # A `..` AMONG THE COMPONENTS THAT DO NOT EXIST RESOLVES TO NOTHING, so + # it is refused rather than guessed at: the physical answer is only the + # ancestor's, and the suffix is taken literally. + case "/$rl_suffix/" in *"/../"*) rl_hdir_real="" ;; esac + if [ -n "$rl_hdir_real" ]; then + [ -n "$rl_suffix" ] && rl_hdir_real="$rl_hdir_real/$rl_suffix" + case "$rl_hdir_real/" in + "$rl_repo_real"/*) + rl_hreal="$rl_hdir_real/$(basename -- "$rl_hfile")" + rl_h_rel="${rl_hreal#"$rl_repo_real"/}" + rl_h_rel_new="${rl_h_rel%/*}/$(basename -- "$rl_hpath_new")" + case "$rl_h_rel" in */*) : ;; *) rl_h_rel_new="$(basename -- "$rl_hpath_new")" ;; esac ;; + esac + fi + fi + # A HANDOFF OUTSIDE THE WORKSPACE REPOSITORY IS A REFUSAL, NOT A NOTE + # (Copilot round 1 on openRepoTools#81). It used to be moved and stamped + # and then left OUT of the commit, because a git commit cannot carry a + # file outside its own checkout — so "four moves, one commit" was not true + # of that row, and a failure afterwards had nothing to roll the outside + # file back from. The register's handoff column is repo-relative + # everywhere this estate writes it (`handoffs/<estate>/…`, the path + # `lane-start` computes), so a row naming one elsewhere is a hand edit, + # and the exit is to put the file where the row's own convention puts it. + if [ -z "$rl_h_rel" ]; then + die "lane $rl_old's row names the handoff '$rl_hcell', which resolves to $rl_hfile — outside the workspace repository ${LANES_REPO:-<unknown>}. A rename is FOUR MOVES IN ONE COMMIT (Amendment 16), and a commit cannot carry a file outside its own checkout, so this one would be three moves and a note. Move that handoff under $LANES_REPO — \`handoffs/<estate>/session-handoff-<date>-lane-$rl_old.md\` is the path \`lane-start\` computes — point the row's handoff column at it, and re-run. Nothing was written." 2 + fi + # `-L` BESIDE `-e`, because `-e` IS FALSE ON A DANGLING LINK (Copilot + # round 5) — and `mv` would then replace that link, destroying a path this + # rename does not own, exactly as the source-side tests already say. + [ "$rl_hmove" = 1 ] && { [ -e "$rl_hfile_new" ] || [ -L "$rl_hfile_new" ]; } && \ + die "the handoff would move to $rl_hfile_new and something is already there. That path belongs to lane $rl_new's own handoff and is not this rename's to overwrite. Move it aside and re-run. Nothing was written." 2 + fi + # THE HANDOFF IS A PATHSPEC OF THIS COMMIT ONLY WHERE THERE IS A FILE TO + # COMMIT. `git add` FAILS on a pathspec matching nothing at all, and a row + # that names a handoff nobody ever wrote is ordinary — every lane has one + # until its first swap. A row that names one which cannot be READ is a + # different thing and is refused below, with the log already snapshotted. + # AND A PATH THAT EXISTS AND IS NOT A REGULAR FILE IS A REFUSAL, not a + # missing handoff (Copilot round 3 on openRepoTools#81). `-f` alone read a + # directory, a FIFO and a DANGLING SYMLINK as "the row names a handoff + # nobody wrote", so the rename committed the other three and left that path + # where it was. `-e` is false on a dangling link, which is why `-L` is asked + # beside it — the same pair `unplaceable_kind` in `openRepoTools` asks, for + # the same reason: `cat` through a dangling link CREATES the far end. + # A SYMLINK IS TESTED BEFORE `-f`, because `-f` is TRUE through one to a + # regular file (Copilot round 4 on openRepoTools#81) — and Rule 3's stamp is + # written with a redirect, which FOLLOWS it: the stamp would land in the + # link's target, possibly outside this repository, while the commit recorded + # the link and the rollback restored the wrong bytes. + if [ -n "$rl_hcell" ] && [ -L "$rl_hfile" ]; then + die "lane $rl_old's row names the handoff '$rl_hcell' and $rl_hfile is a SYMLINK. Rule 3's stamp is written in place and a redirect follows a link, so the stamp would land at the far end while this commit recorded the link (Amendment 16(d)). Point the row's column at the file itself and re-run. Nothing was written." 2 + fi + if [ -n "$rl_hcell" ] && [ ! -f "$rl_hfile" ] && [ -e "$rl_hfile" ]; then + die "lane $rl_old's row names the handoff '$rl_hcell' and $rl_hfile is not a regular file. A rename moves and STAMPS the handoff the row names (Amendment 16(d)), and neither can be done to that; nor is it the absent handoff an un-swapped lane has, which is passed over. Put a handoff there, or point the row's column at one, and re-run. Nothing was written." 2 + fi + rl_h_touch=0 + [ -n "$rl_h_rel" ] && [ -f "$rl_hfile" ] && rl_h_touch=1 + # AND AN UNTRACKED HANDOFF IS SOMEBODY'S UNCOMMITTED WORK (Copilot round 6). + # It is a pathspec of this commit the moment it exists, and `tracked_dirty` + # never reports it, so another lane's half-written handoff would be stamped + # and committed under this rename's message — which is the one thing + # `--no-sweep` was made the default for. + if [ "$rl_h_touch" = 1 ] && [ "$NO_GIT" != 1 ] \ + && ! git -C "$LANES_REPO" ls-files --error-unmatch -- "$rl_h_rel" >/dev/null 2>&1; then + die "the handoff at $rl_h_rel exists here and git does not track it, so its lines have never been committed by anyone — and this rename would stamp it, move it and commit it under its own message. Whoever wrote it commits it first: \`git -C $LANES_REPO add -- $rl_h_rel && git -C $LANES_REPO commit -m \"handoff(<lane>@<workstation>): <what>\"\`. Nothing was written." 2 + fi + + # ---- NOTHING ABOVE HAS WRITTEN A BYTE. The four moves follow, in one + # commit, in the order the amendment lists them. + rl_paths=("$LANES_PATH" "$rl_log_new_rel" "$LANES_ALIASES_PATH") + # THE OLD LOG IS A PATHSPEC ONLY WHERE GIT KNOWS IT (Copilot round 3 on + # openRepoTools#81). A TRACKED path that has been moved away still matches + # in the index and `git add` stages its deletion; an UNTRACKED one — the log + # an earlier write created and never committed — matches nothing once it is + # gone, and `git add` FAILS on a pathspec that matches nothing at all, + # which would end this write inside `commit_push` with all four moves on + # disk. Nothing in the index refers to it, so there is nothing to stage. + if [ -n "$rl_log_old_rel" ] && [ "$rl_log_old_rel" != "$rl_log_new_rel" ] \ + && { [ "$NO_GIT" = 1 ] || git -C "$LANES_REPO" ls-files --error-unmatch -- "$rl_log_old_rel" >/dev/null 2>&1; }; then + rl_paths+=("$rl_log_old_rel") + fi + if [ "$rl_h_touch" = 1 ]; then + rl_paths+=("$rl_h_rel_new") + [ "$rl_hmove" = 1 ] && rl_paths+=("$rl_h_rel") + fi + # THE ALIAS TABLE IS NOT EXEMPT FROM THE DIRTY-CHECKOUT REFUSAL (Copilot + # round 4 on openRepoTools#81). Every pathspec handed here is exempted, and + # `lanes/aliases.tsv` has ONE writer — this command — so a dirty one is not + # the ordinary mid-write state `lanes/LANES.md` is in half the day and there + # is no capture for it: exempted and uncaptured, a peer's half-finished + # rename would be appended to and swept into this lane's commit. So it is + # left OUT of the exemption list and the generic refusal names it. + rl_exempt=() + for rl_p in ${rl_paths[@]+"${rl_paths[@]}"}; do + [ "$rl_p" = "$LANES_ALIASES_PATH" ] && continue + rl_exempt+=("$rl_p") + done + refuse_dirty_checkout "rename lane $rl_old" ${rl_exempt[@]+"${rl_exempt[@]}"} "$LANES_PATH" + # THE CAPTURE IS GIVEN THE REGISTER AND NOTHING ELSE (Copilot round 3 on + # openRepoTools#81). `handle_preexisting` runs `git add -- <paths>` on the + # branch that captures a peer's uncommitted edit, and most of this write's + # pathspecs DO NOT EXIST YET — the new log, the alias table, the handoff's + # new name — so that `git add` would fail, the capture would not happen, and + # a peer's half-written row would be swept into this rename's commit. The + # register is the only file that can be dirty here at all: every OTHER + # tracked change was refused one line up, which is the same reasoning + # `capture_register_edit` states for its own single pathspec. + handle_preexisting "$LANES_PATH" + + # ---- THE SNAPSHOT, BEFORE THE FIRST BYTE. Every exit path from here to the + # commit restores it (`rename_undo`, hooked into `cleanup`), because the + # four moves are one act and a filesystem can refuse the third of them. + RL_SNAP="$(mktemp -d)" || die "no temporary directory could be made under ${TMPDIR:-/tmp}, and this write is not made without somewhere to put the copy that undoes it. Nothing was written." 1 + [ -n "$rl_log_old" ] && { cat -- "$rl_log_old" > "$RL_SNAP/log" || die "lane $rl_old's object log at $rl_log_old could not be read, so there is no copy to roll back to and this rename is not started. Nothing was written." 5; } + [ "$rl_h_touch" = 1 ] && { cat -- "$rl_hfile" > "$RL_SNAP/handoff" || die "the handoff at $rl_hfile is named by the row and could not be READ, so it can be neither stamped nor rolled back — and a rename that moved it unstamped is three moves and a half (Amendment 16(d)). Fix the permission, or point the row's column at a handoff that is there, and re-run. Nothing was written." 5; } + RL_ALIAS="$LANES_ALIASES_TSV"; RL_ALIAS_EXISTED=0 + if [ -f "$LANES_ALIASES_TSV" ]; then + RL_ALIAS_EXISTED=1 + cat -- "$LANES_ALIASES_TSV" > "$RL_SNAP/aliases" || die "$LANES_ALIASES_PATH is there and could not be read, so there is no copy to roll back to. Nothing was written." 5 + fi + # AND THE REGISTER IS IN THE SNAPSHOT TOO (Copilot round 4 on + # openRepoTools#81). `replace_line` cannot half-write it — it proves the new + # file before it writes a byte — but the row IS written before + # `commit_push`, and `commit_push` can die before it commits anything. The + # undo then put the other three back and left the row renamed: a split + # rename, which is the state this whole mechanism exists to prevent. + RL_REG="$LANES_FILE" + cat -- "$LANES_FILE" > "$RL_SNAP/register" || die "the register at $LANES_FILE could not be read, so there is no copy to roll back to. Nothing was written." 5 + RL_LOG_OLD="$rl_log_old"; RL_LOG_NEW="$rl_log_new" + RL_H_OLD=""; RL_H_NEW="" + RL_PATHS_FOR_UNDO=("${rl_paths[@]}") + RL_ACTIVE=1 + + # (c) THE LOG — moved, then appended to. The lines above the new one still + # say `lane <old>` and are NEVER rewritten (clause (c)): this file is + # append-only and those lines are what happened. `LOG_AWK` resolves the + # field on the way in, so every reader sees one lane. + if [ -n "$rl_log_old" ]; then + mv -- "$rl_log_old" "$rl_log_new" || die "could not rename $rl_log_old to $rl_log_new." 5 + note "$rl_log_old_rel → $rl_log_new_rel" + else + [ -d "$LANES_LOG_DIR" ] || mkdir -p -- "$LANES_LOG_DIR" + printf '# lane %s — object log (lane-collision-protocol Amendment 7)\n' "$rl_new" > "$rl_log_new" + note "created $rl_log_new_rel — lane $rl_old has no object log (a pre-cutover lane, Amendment 7(i)), so this RENAMED is its first line" + fi + rl_line="$(event_line RENAMED "$rl_new" "$rl_uuid" "$rl_utc" "lane:$rl_new" "←" "lane:$rl_old" "$rl_why")" + append_text_line "$rl_line" "$rl_log_new" + + # (d) THE HANDOFF — moved to the same date with `lane-<new>`, and stamped + # under its header block (Rule 3). THE FILE IS SPLICED AND NEVER REWRITTEN + # WHOLE, with the proof `lane-start` makes for its own `RESUMED by` stamp: + # one line in at the ruled position, and taking that line back out again + # gives the file back byte for byte. A handoff is the one document this + # protocol cannot afford to lose, and the act that dropped two lanes' rows + # on 2026-09-08 was a file written whole from what somebody remembered. + rl_hstamp="RENAMED from $rl_old by $rl_uuid (lane $rl_new) at $rl_utc" + rl_hdone=0 + if [ -z "$rl_hcell" ]; then + note "the row names no handoff, so there is none to move or stamp (Amendment 16(d))" + elif [ ! -f "$rl_hfile" ]; then + note "the handoff the row names is not at $rl_hfile, so nothing was moved or stamped and the row's handoff column is left exactly as it is. If it turns up, rename it — $rl_hcell → $rl_hpath_new — and stamp it: $rl_hstamp" + else + if [ "$rl_hmove" = 1 ]; then + RL_H_OLD="$rl_hfile"; RL_H_NEW="$rl_hfile_new" + mv -- "$rl_hfile" "$rl_hfile_new" || die "could not rename $rl_hfile to $rl_hfile_new." 5 + note "$rl_hcell → $rl_hpath_new" + rl_hdone=1 + else + rl_hfile_new="$rl_hfile" + RL_H_OLD="$rl_hfile"; RL_H_NEW="$rl_hfile" + note "the handoff $rl_hcell is not named \`…-lane-$rl_old.md\`, so it has no lane in its name to rename; it is stamped where it is (Amendment 16(d))" + fi + # A STAMP THAT CANNOT BE WRITTEN IS A REFUSAL (Copilot round 1 on + # openRepoTools#81). It used to be a `note`, and the rename went on to + # commit — leaving a handoff MOVED and UNSTAMPED, which is clause (d) done + # by half, in the one document Rule 3 says the next session reads first. + # The redirect is checked for the same reason: this file runs `set -u` and + # not `set -e`, so an unwritable handoff would otherwise reach the + # "stamped" note having written nothing. + rl_hat="$(awk 'NR > 1 && /^[[:space:]]*$/ { print NR; exit }' "$rl_hfile_new" 2>/dev/null || :)" + [ -n "$rl_hat" ] || rl_hat=1 + rl_htmpd="$(mktemp -d)" || die "no temporary directory could be made under ${TMPDIR:-/tmp} for the handoff's Rule 3 stamp." 1 + cat -- "$rl_hfile_new" > "$rl_htmpd/pre" 2>/dev/null || { rm -rf -- "$rl_htmpd"; die "the handoff at $rl_hfile_new could not be read, so Rule 3's stamp cannot be written and this rename is not made without it." 5; } + { head -n "$rl_hat" -- "$rl_htmpd/pre" + printf '%s\n' "$rl_hstamp" + tail -n "+$((rl_hat + 1))" -- "$rl_htmpd/pre" + } > "$rl_htmpd/out" + if [ "$(sed -n -e "$((rl_hat + 1))p" "$rl_htmpd/out")" != "$rl_hstamp" ] || + ! { head -n "$rl_hat" -- "$rl_htmpd/out"; tail -n "+$((rl_hat + 2))" -- "$rl_htmpd/out"; } | cmp -s - "$rl_htmpd/pre" + then + rm -rf -- "$rl_htmpd" + die "the handoff at $rl_hfile_new cannot take Rule 3's stamp without rewriting a byte of it, and a handoff written whole from anything but its own bytes is the act that lost two lanes' rows on 2026-09-08. The line it wants under its header block is: $rl_hstamp" 5 + fi + # AND THE STAMPED COPY REPLACES THE HANDOFF BY RENAME, NEVER THROUGH A + # REDIRECT INTO IT (opensoft/openRepoTools#158). `>` truncated the handoff + # before the first stamped byte was written, so a writer killed inside + # that `cat` — or a machine that lost power there — left a handoff cut + # short, and no undo reached it: `rename_undo` is a trap and SIGKILL runs + # none, so every later read took the short file for the handoff. The + # bytes now go to an exclusive temporary file BESIDE the handoff, in the + # physical directory it resolves to, with its mode (`cp -p` first), and + # `mv -f` replaces it in one rename: a reader sees the handoff whole + # before the stamp or whole after it. These are `publish-handoff`'s + # mechanics, inlined because that verb takes the lock this write already + # holds. The leaf is never a link — refused above, before the first byte + # — so replacing it rather than writing through it is the same file. + # `cleanup` removes the temporary on every handled exit; one a crash + # leaves is `<handoff>.rename.XXXXXX`, which no reader of `*.md` takes + # for a handoff. THIS MAKES THE STAMP ATOMIC, NOT THE RENAME: a crash + # between two of the four moves still leaves them apart. + rl_hpub="$( CDPATH=''; cd -P -- "$(dirname -- "$rl_hfile_new")" && pwd -P )" || { rm -rf -- "$rl_htmpd"; die "the directory of the handoff at $rl_hfile_new could not be resolved, so Rule 3's stamp cannot be published beside it and this rename is not made without it." 5; } + rl_hpub="$rl_hpub/$(basename -- "$rl_hfile_new")" + rl_htmp="$(mktemp "$rl_hpub.rename.XXXXXX")" || { rl_htmp=""; rm -rf -- "$rl_htmpd"; die "no temporary file could be made beside the handoff at $rl_hfile_new, and Rule 3's stamp is not written into a handoff in place. This rename is not made without it." 5; } + if ! cp -p -- "$rl_hpub" "$rl_htmp" || ! cat -- "$rl_htmpd/out" > "$rl_htmp" || ! mv -f -- "$rl_htmp" "$rl_hpub"; then + rm -f -- "$rl_htmp"; rl_htmp=""; rm -rf -- "$rl_htmpd" + die "the handoff at $rl_hfile_new could not be written, so Rule 3's stamp is not there and this rename is not made without it." 5 + fi + rl_htmp="" + rm -rf -- "$rl_htmpd" + note "handoff stamped at line $((rl_hat + 1)) of $rl_hpath_new: $rl_hstamp" + fi + # The row's handoff column follows the file, and only where the file + # actually moved: a column pointed at a path nothing moved to is a column + # that names a file that is not there. + if [ "$rl_hdone" = 1 ] && [ "$rl_hsplit" = 1 ]; then + rl_hc_pre="${rl_hc%%"$rl_hcell"*}"; rl_hc_post="${rl_hc#*"$rl_hcell"}" + rl_newrow="$rl_pre$rl_hc_pre$rl_hpath_new$rl_hc_post$rl_hpost" + fi + + # (e) THE ALIAS TABLE — the one write that makes the old name keep working, + # for ever and in every reader (clause (e)). + if [ ! -f "$LANES_ALIASES_TSV" ]; then + { printf '# lanes/aliases.tsv — lane-collision-protocol Amendment 16(e)\n' + printf '# <old lane>\t<new lane>\t<UTC of the rename>\n' + printf '# Appended by `lanes-edit.sh rename-lane` and by nothing else. Every reader of a\n' + printf '# lane name resolves through it, case-insensitively; a chain resolves to its end,\n' + printf '# stopping at any name that is a ROW again; a cycle is refused at write time; the\n' + printf '# LAST row for a key wins.\n' + } > "$LANES_ALIASES_TSV" || die "$LANES_ALIASES_PATH could not be created, and a rename without its alias row is a lane whose old name stops resolving (Amendment 16(e))." 5 + note "created $LANES_ALIASES_PATH" + fi + append_text_line "$(printf '%s\t%s\t%s' "$rl_old" "$rl_new" "$rl_utc")" "$LANES_ALIASES_TSV" + + # (b) THE ROW, LAST — so that a refusal anywhere above leaves the register + # itself untouched and `row_line` still finds the lane under its old name. + replace_line "$rl_n" "$rl_newrow" + + # EVERY ONE OF THE FOUR IS ON DISK — AND THE UNDO STAYS ARMED THROUGH THE + # COMMIT (Copilot round 3 on openRepoTools#81). It was cleared here, and + # `commit_push` can die on `update-index`, `git add` or `git commit` BEFORE + # any commit exists: the four files would then be left moved and modified + # with nothing to show for them, which is the half-renamed state this whole + # mechanism exists to prevent. + # + # WHAT DECIDES IS WHETHER A COMMIT WAS MADE, not where the failure happened. + # `rename_undo` compares HEAD against the sha taken here: unchanged means no + # commit carries this work and the four are restored; moved means the commit + # exists, the work is IN it, and `commit_push` owns the recovery from there + # — its exit 3 says so in its own words, and undoing a committed rename + # behind its back would be a second, inverse change nobody asked for. + RL_HEAD_BEFORE="$(git -C "$LANES_REPO" rev-parse HEAD 2>/dev/null || printf '')" + rl_msg="LANES($rl_new@$WS): RENAMED lane $rl_old → $rl_new (Amendment 16) — the row, $rl_log_new_rel, the handoff and $LANES_ALIASES_PATH in one commit" + [ -n "$PRE_DIRTY_LANES" ] && rl_msg="$rl_msg + sweeps uncommitted edit to row $PRE_DIRTY_LANES" + commit_push "$rl_msg" "${rl_paths[@]}" + rl_rc=$? + # `commit_push` RETURNED, so either it committed or it had nothing staged; + # every other outcome exits from inside it and is the trap's business. + RL_ACTIVE=0 + state_events_flush + lane_alias_flush + [ "$rl_rc" != 0 ] || lane_state_rename "$rl_lsr_old" "$rl_new" + release_lock + [ "$rl_rc" = 0 ] || exit "$rl_rc" + + rl_sha="$(git -C "$LANES_REPO" rev-parse HEAD 2>/dev/null || printf '')" + note "lane $rl_old is lane $rl_new (${rl_sha:-no sha}); '$rl_old' resolves to it for ever through $LANES_ALIASES_PATH" + + # (g) ONE COMMENT PER OBJECT THE LANE HOLDS — Amendment 7(b)'s partition, + # the same set `lane-end` refuses on and `who --lane` reports. Posted only + # AFTER the commit has landed and citing its sha, exactly as `claim`'s + # comment is, and skipped entirely by `--no-github`. + if [ "$NO_GITHUB" != 1 ]; then + rl_body="$(printf 'Lane %s renamed %s at %s (lane-collision-protocol Amendment 16). Lane: %s (%s)\n\nRecorded in `%s` at `%s`. `%s` resolves `%s` to `%s` for every reader of a lane name, so every earlier comment, line and branch naming the old lane still finds it.\n' \ + "$rl_old" "$rl_new" "$rl_utc" "$(lc "$rl_new")" "$rl_new" \ + "$rl_log_new_rel" "${rl_sha:-unknown}" "${LANES_ALIASES_PATH:-lanes/aliases.tsv}" "$rl_old" "$rl_new")" + rl_posted=0; rl_missed="" + while IFS="$US" read -r rl_outc rl_overb rl_oobj rl_oref rl_osup; do + [ -n "${rl_overb:-}" ] || continue + is_open_verb "$rl_overb" || continue + rl_url="$(gh_comment "$rl_oobj" "$rl_body" 2>/dev/null || :)" + if [ -n "$rl_url" ]; then + note "comment posted on $rl_oobj: $rl_url"; rl_posted=$((rl_posted + 1)) + else + rl_missed="$rl_missed $rl_oobj" + fi + done <<EOF +$(lane_objects "$rl_new" 2>/dev/null || :) +EOF + [ "$rl_posted" = 0 ] && [ -z "$rl_missed" ] && note "lane $rl_new holds nothing open, so there is no object to comment on (Amendment 16(g))" + [ -n "$rl_missed" ] && note "WARNING: the rename comment could not be posted on:$rl_missed. The commit IS the rename and it has landed; post them by hand so that a reader outside this estate can see it." + fi + note "THE WINDOW AND THE SESSION ARE NOT THIS WRITE'S (Amendment 16(f)): in the lane's own window, \`tmux rename-window $rl_new\` and \`/rename $rl_new\` typed into its pane. \`lane-rename\` does both when it is run there; from anywhere else the name guard renames the window at this lane's next prompt and types the \`/rename\` itself." + ;; + + # AMENDMENT 13(e) — THE MIGRATION. A DRY RUN unless `--yes` is passed, and one + # act on Brett Heap's word when it is (ratified decision O3). Everything it + # does is argued above `migrate_state_cells`. + migrate-state-cells) + msc_yes=0 + while [ $# -gt 0 ]; do + case "$1" in + --yes) msc_yes=1; shift ;; + --) shift ;; + *) die "usage: migrate-state-cells [--yes] — without --yes it is a DRY RUN that writes nothing; '$1' is neither" 2 ;; + esac + done + migrate_state_cells "$msc_yes" + ;; + + log) + lane="${LANES_LANE:-}" + [ -n "$lane" ] || die "log needs the lane: LANES_LANE=<lane> lanes-edit.sh log <VERB> <object> …" 2 + check_lane_name "$lane" + verb=""; obj_raw=""; ref=""; payload=""; text=""; home_override=""; utc_override="" + while [ $# -gt 0 ]; do + case "$1" in + --no-github) NO_GITHUB=1; shift ;; + # AMENDMENT 17, adoption act 7 — THE LATE RECORD'S OWN DATE, AND + # NOTHING ELSE USES IT. A `PAUSED` written after the fact for a swap + # that never ran names the moment the OLD SESSION ENDED, not the moment + # the shell writing it ran: `lane-handoff --late --at <UTC>` is the one + # caller, and its own rule is that the line may only be written where it + # is still the lane's last one (this log is append-only and FILE ORDER + # is what every state read means by "last"). The shape is checked here + # because a UTC field this parser cannot read is a line no reader can + # date — and the log is never rewritten. + --utc) utc_override="${2-}"; [ -n "$utc_override" ] || die "--utc needs a UTC instant" 2; shift 2 ;; + --utc=*) utc_override="${1#--utc=}"; [ -n "$utc_override" ] || die "--utc needs a UTC instant" 2; shift ;; + --home) home_override="${2-}"; [ -n "$home_override" ] || die "--home needs owner/repo" 2; shift 2 ;; + --home=*) home_override="${1#--home=}"; [ -n "$home_override" ] || die "--home needs owner/repo" 2; shift ;; + --text) text="${2-}"; shift 2 ;; + --text=*) text="${1#--text=}"; shift ;; + --) shift ;; + '→'|'->') ref="→"; payload="${2-}"; [ -n "$payload" ] || die "'$1' needs a payload after it" 2; shift 2 ;; + '←'|'<-') ref="←"; payload="${2-}"; [ -n "$payload" ] || die "'$1' needs a payload after it" 2; shift 2 ;; + -*) die "unknown option '$1' for log" 2 ;; + *) + if [ -z "$verb" ]; then verb="$1" + elif [ -z "$obj_raw" ]; then obj_raw="$1" + elif [ -z "$text" ]; then text="$1" + else die "log takes <VERB> <object> [→|← <payload>] [\"<free text>\"] — '$1' is one argument too many" 2 + fi + shift ;; + esac + done + [ -n "$verb" ] && [ -n "$obj_raw" ] || die "usage: log <VERB> <object> [→|← <payload>] [\"<free text>\"] ($VERB_LIST)" 2 + valid_verb "$verb" || die "'$verb' is not one of the Amendment 7 verbs ($VERB_LIST)" 2 + # The four verbs that have a subcommand of their own are NOT written by + # hand. `log CLAIMED` skipped the pre-check, the race and the rescan and + # `who` reported the result identically to a real claim; `log TAKEOVER` + # skipped the staleness test that is the only thing making a takeover + # legitimate. Refusing them here costs nothing that is actually needed. + case "$verb" in + CLAIMED) + die "a CLAIMED is not written by hand: it is Rule 1's act, and 'log' skips the pre-check, the race and the rescan. Use: LANES_LANE=$lane lanes-edit.sh claim $obj_raw" 2 ;; + TAKEOVER) + die "a TAKEOVER is not written by hand: it is only legitimate against a claim that is STALE, and that is the test 'log' does not make. Use: LANES_LANE=$lane lanes-edit.sh claim $obj_raw --force" 2 ;; + RELEASED) + die "a RELEASED is not written by hand: 'release' also posts the Rule 1 comment. Use: LANES_LANE=$lane lanes-edit.sh release $obj_raw \"<why>\"" 2 ;; + CLAIM-LOST) + die "a CLAIM-LOST is written by 'claim' when it loses the race for an object, and by nothing else — there is no hand-written form of losing a race" 2 ;; + HANDOFF-REQUESTED) + die "a HANDOFF-REQUESTED is not written by hand: it is clause (c)'s act, and 'log' skips the binding read that says there is anything to request, the pane it types into and the wait that follows. Use: $SELF request-handoff $lane" 2 ;; + # AMENDMENT 16 — AND A `RENAMED` IS NOT WRITTEN BY HAND EITHER, for the + # reason the amendment itself was drafted for: two lanes renamed + # themselves on 2026-09-14 by appending exactly this line and nothing + # else, and *"the lines are honest and they are all there is: the rows + # still carry the old keys, the logs and handoffs the old names"*. The + # line is one of four moves that are one commit, and `log` makes the + # other three of them not at all. + RENAMED) + die "a RENAMED is not written by hand: it is one of the FOUR moves of a rename — the row's key, this log's own name, the handoff and lanes/aliases.tsv — which land in ONE commit, refused or whole (Amendment 16). A line on its own is the 2026-09-14 hand rename this amendment exists to replace: honest, and all there is. Use: lane-rename ${obj_raw#lane:} <new name>" 2 ;; + esac + # R30 — THE FETCH COMES FIRST. `log` had no `log_sync` of its own at all: + # it read the STARTED line that REFUSES `--home` out of an `origin/<branch>` + # nothing here had moved, and the pull inside `commit_push` comes far too + # late to be that read. + log_sync + # AMENDMENT 15 — AFTER THE FETCH AND BEFORE EVERY READ AND WRITE BELOW IT. + # The resolver reads the PUBLISHED register (R19), so it is asked once + # `log_sync` has moved the ref — and what it answers is the lane this line + # is WRITTEN with, the file it is written to, and the commit subject. + lane="$(canon_lane "$lane")" || exit 2 + home="$(resolve_home "$lane" "$home_override")" || exit $? + obj="$(canon_object "$obj_raw" "$home")" || exit 2 + # AMENDMENT 13(b) — THE TWO NARRATIVE VERBS, AND WHAT EACH OF THEM TAKES. + # `NOTED` is a status note about the lane; `RULED` is a ruling recorded + # VERBATIM, with the object it bears on as its payload where there is one. + # Both are lane-kind lines in Amendment 7's own `STARTED`/`RESUMED` form — + # object `lane:<lane>`, one token — and neither is a transition, so no + # reader's state moves because one was written. They are the cell's old + # diary, in the file built to hold it. + if is_note_verb "$verb"; then + is_lane_object "$obj" || + die "'$verb' is a lane-kind line (Amendment 13(b)): its object is the LANE itself, lane:$lane, and not $obj. The object a ruling BEARS ON is its payload: LANES_LANE=$lane lanes-edit.sh log RULED lane:$lane → $obj \"<the words, verbatim>\"" 2 + # AND IT IS THIS LANE, NOT ANOTHER (Copilot round 5 on openRepoTools#82). + # `is_lane_object` reads the `lane:` prefix and nothing more, so + # `LANES_LANE=repoA … log NOTED lane:repoB` wrote a line into repoA's log + # whose object named repoB — a note about a lane in a file that is not its + # log, and `history repoB` would never show it. Clause (b) is explicit + # that these are "lane-kind lines whose object is the lane itself". + # COMPARED CASE-INSENSITIVELY, because `$lane` is already the row's own + # spelling and a caller may have typed another (Amendment 15). + [ "$(lc "${obj#lane:}")" = "$(lc "$lane")" ] || + die "'$verb' is a line about THIS lane, and its object is this lane: lane:$lane, not $obj (Amendment 13(b)). A note is written into the log of the lane it names, so an object naming another lane is a note nobody reading that lane's history would ever see. To say something about another lane, write it in the text; to record a ruling about an OBJECT, that object is the payload: LANES_LANE=$lane lanes-edit.sh log RULED lane:$lane → <object> \"<the words>\"" 2 + if [ -z "$text" ]; then + case "$verb" in + RULED) die "a RULED with no words is not a ruling. The text is the ruling, VERBATIM — it is what Amendment 13(b) put this verb in the log for: LANES_LANE=$lane lanes-edit.sh log RULED lane:$lane${payload:+ → $payload} \"<Brett Heap's words, verbatim>\"" 2 ;; + *) die "a NOTED with no text is a note with nothing in it. The text is what the line is FOR — it is the narrative the state cell used to carry (Amendment 13(a)): LANES_LANE=$lane lanes-edit.sh log NOTED lane:$lane \"<what the lane did, found, launched, left>\"" 2 ;; + esac + fi + case "$verb" in + NOTED) + [ -z "$payload" ] || + die "NOTED takes no payload: it is a note about the lane, and Amendment 13(b) gives it the object and the free text alone. Put it in the text — or, if it is a ruling about an object, write it as one: LANES_LANE=$lane lanes-edit.sh log RULED lane:$lane → $payload \"<the words>\"" 2 ;; + RULED) + if [ -n "$payload" ]; then + # `→` AND NOT `←`, because clause (b) spells the form `lane:<lane>[ → + # <object>]` and the arrow is the only thing that says which way the + # ruling points. AND THE OBJECT IS CANONICALISED like every other + # object this file writes (R20): a ruling recorded against `#29` in a + # lane whose home is `opensoft/openRepoTools` is a ruling about + # `opensoft/openRepoTools#29`, and one recorded against a legacy org + # spelling is a second key for one issue — which is the defect + # Amendment 7(a)'s alias table exists for. + [ "$ref" = '→' ] || + die "RULED's payload is the object the ruling bears on and it is introduced by → (Amendment 13(b)): 'log RULED lane:$lane → <object> \"<the words>\"'. '←' points the other way and means nothing here." 2 + payload="$(canon_object "$payload" "$home")" || exit 2 + fi ;; + esac + elif is_lane_verb "$verb"; then + is_lane_object "$obj" || die "'$verb' is a lane verb: its object is lane:<name>, not $obj" 2 + else + ! is_lane_object "$obj" || die "'$verb' is an object verb: lane:<name> is not one of its objects" 2 + fi + log_utc="$(utc_now)" + if [ -n "$utc_override" ]; then + # `--utc` IS THE LATE `PAUSED`'s SEAM AND HAS NO OTHER CALLER (Amendment + # 17, adoption act 7; Copilot round 2 on openRepoTools#47). The parser + # above takes the option for every verb and only its SHAPE was checked + # here, so a `STARTED` or a `RESUMED` could be dated by hand — and this + # log is append-only with FILE ORDER deciding which line is a lane's + # last, so a hand-dated line changes what every state read reports about + # a lane that is running. The one line that legitimately carries its own + # date is the record a swap never left, and `lane-handoff --late` has its + # own rule for when even that may be written. + [ "$verb" = PAUSED ] || die "--utc dates the LATE PAUSED that a swap never left (Amendment 17, adoption act 7) and nothing else — '$verb' is not one. Every other line is dated by the clock of the act that wrote it, because this log is append-only and a line dated by hand is a line whose order no reader can trust. Write it without --utc." 2 + case "$utc_override" in + [0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9]Z) log_utc="$utc_override" ;; + *) die "--utc takes a UTC instant spelled as this log spells it, YYYY-MM-DDTHH:MM:SSZ — '$utc_override' is not one, and a line nothing can date is a line no reader can order" 2 ;; + esac + fi + write_event "$lane" "$verb" "$obj" "$ref" "$payload" "$text" "$log_utc" "$(session_for "$lane")" + ;; + + claim) + lane="${LANES_LANE:-}" + [ -n "$lane" ] || die "claim needs the lane: LANES_LANE=<lane> lanes-edit.sh claim <object>" 2 + check_lane_name "$lane" + obj_raw=""; force=0; home_override="" + while [ $# -gt 0 ]; do + case "$1" in + --force) force=1; shift ;; + --no-github) NO_GITHUB=1; shift ;; + --home) home_override="${2-}"; [ -n "$home_override" ] || die "--home needs owner/repo" 2; shift 2 ;; + --home=*) home_override="${1#--home=}"; [ -n "$home_override" ] || die "--home needs owner/repo" 2; shift ;; + --) shift ;; + -*) die "unknown option '$1' for claim" 2 ;; + *) [ -z "$obj_raw" ] || die "claim takes exactly one object" 2; obj_raw="$1"; shift ;; + esac + done + [ -n "$obj_raw" ] || die "usage: claim <object> [--force] [--no-github] [--home owner/repo]" 2 + + # THE RACE IS DECIDED BY WHICH CLAIM LANDS ON main FIRST, and a rebase is + # what makes that decidable. Amendment 5(d) SKIPS the rebase when a peer + # has left uncommitted changes to other files in this shared checkout — a + # sensible default for a row edit, and unacceptable for a claim, which + # would then race unprotected. Refuse, and name the files — BEFORE the + # reads and before anything is written, and against exactly the pathspec + # this claim will write (the lane's log; a CLAIMED is not a LANDING). + # The register is exempt HERE and only here: write_event captures a peer's + # uncommitted `lanes/LANES.md` as its own commit and re-tests the checkout + # afterwards (R11), so a claim is not refused for the one file this + # checkout is dirty in most of the day. + # AND THE EXEMPTION IS A PATH, SO ITS AMBIGUITY IS THIS CLAIM'S (Copilot + # round 4): two logs differing only by case are a refusal, not a pathspec. + claim_log="$(log_path_ci "$lane")" || exit 2 + refuse_dirty_checkout claim "$claim_log" "$LANES_PATH" + + # 1. FETCH FIRST OF ALL — then resolve `--home` against the lane's STARTED + # line (R30), canonicalise the object, and pre-check against what has + # actually LANDED on main. Never against a working tree, which can be + # anything, and never against a log this checkout has not pulled: a home + # a peer recorded is on `origin/<branch>` and nowhere else here. + log_sync + lane="$(canon_lane "$lane")" || exit 2 # Amendment 15 + home="$(resolve_home "$lane" "$home_override")" || exit $? + obj="$(canon_object "$obj_raw" "$home")" || exit 2 + ! is_lane_object "$obj" || die "a lane is not a claimable object" 2 + takeover_payload=""; takeover_note=""; takeover_from=""; takeover_reason_phrase=""; takeover_dead="" + # CASE-INSENSITIVE, FOR THE SAME REASON THE KEY ABOVE IS LOWER-CASED + # (Amendment 15). This is the lane REMOVING ITSELF from the holders of the + # object it is about to claim, and the row it removes carries whatever + # spelling the winning line used. Byte for byte, a lane whose own earlier + # CLAIMED says `repohold-1` under the row `repoHold-1` is refused its own + # object. AND LITERAL rather than `grep -iv` (Copilot round 4): `repo.-1` + # excluding the rival `repoX-1` is a claim taken over a hold that is open. + held="$(state_events | lane_states_on "$obj" | holders_of "$obj" | rows_not_named "$lane" || :)" + if [ -n "$held" ]; then + who_object "$obj" || : + IFS="$US" read -r h_lane h_verb h_utc h_file h_line <<EOF +$(printf '%s\n' "$held" | head -n1) +EOF + if [ "$force" = 0 ]; then + die "lane $h_lane holds $obj ($h_verb, $h_utc). Rule 1: the lane stops and reports; it does not author a successor. If that claim is stale (CLAIMED on an issue, older than ${STALE_HOURS}h with no OPENED naming it), take it over with --force." 2 + fi + if [ "$(printf '%s\n' "$held" | grep -c .)" != 1 ]; then + die "--force takes over ONE stale claim, and $obj is held by $(printf '%s\n' "$held" | grep -c .) lanes" 2 + fi + # ISSUE #30 — a holder whose LANE is dead is takeable WHATEVER ITS VERB, + # bypassing both gates below: neither one was ever about the lane being + # gone, and a dead lane's OPENED PR has no CLAIMED to be stale in the + # first place. `holder_is_dead` is checked first and, alone, decides + # this branch; it is refused (as today) below wherever it says no. + if holder_is_dead "$h_lane"; then + takeover_from="$h_lane" + takeover_dead=1 + takeover_note="lane $h_lane is dead (log ends $HOLDER_DEAD_VERB, $HOLDER_DEAD_WHY, issue #30)" + # A DIFFERENT PHRASE FOR THE PUBLIC COMMENT (Copilot round 3, PR #61): + # the formatter below used to say every takeover was "of the stale + # claim" unconditionally, which is simply false for this branch — the + # object may be an OPENED PR that was never a CLAIMED issue to begin + # with, and even a CLAIMED one is takeable here whatever its age. The + # audit comment a person outside this estate reads must not misstate + # why. + takeover_reason_phrase=" (takeover of a dead lane's hold: $takeover_note)" + else + # AMENDMENT 18(b) — A TERMINAL LOG WHOSE LAST BINDING IS ANOTHER PLACE'S + # IS UNKNOWN, NEVER DEAD (Copilot on 8ce6c9d, PR #61), and it is + # refused here, ahead of the verb test and of Rule 1's age-only test, + # for the reason `HOLDER_TERMINAL_UNKNOWN` is below: this workstation + # could not establish that nothing still runs under that name, and the + # log is exactly the shape issue #30 distrusts enough to check. + if [ -n "$HOLDER_BOUND_ELSEWHERE" ]; then + die "--force refused: lane $h_lane's own log ends $HOLDER_TERMINAL_SEEN, but its last binding is on $HOLDER_BOUND_ELSEWHERE (host/container), and liveness is pronounced only from inside a binding's own host and container — from here it is UNKNOWN, never dead (Amendment 18(b)). Run this takeover from that host and container, or have the lane's holds released there. Rule 1: the lane stops and reports; it does not author a successor." 2 + fi + # OPENSOFT/OPENREPOTOOLS#67 — AND A REGISTER THAT COULD NOT BE READ IS + # REFUSED HERE TOO, ahead of the verb test, in its own words: the verb + # refusal below would blame a live session nobody looked for, and the + # `HOLDER_TERMINAL_UNKNOWN` one would put the failure on this + # workstation's session records, when what could not be read was the + # register — the row naming the ids to look for. + if [ -n "$HOLDER_REGISTER_UNREADABLE" ]; then + die "--force refused: lane $h_lane's own log ends $HOLDER_TERMINAL_SEEN, but the register (origin/$LANES_BRANCH:$LANES_PATH, or $LANES_FILE) could not be read, so the session ids lane $h_lane holds are not known and whether a live session on this workstation still backs it up was never checked. That is NOT 'it has no session ids' — an unreadable register never confirms a lane dead (issue #67). Fix the read and re-run. Rule 1: the lane stops and reports; it does not author a successor." 2 + fi + if [ "$h_verb" != CLAIMED ]; then + # NAMES ITS OWN VERB, NOT ONLY THE THREE THAT USED TO BE POSSIBLE + # HERE (Copilot round 8, PR #61): before issue #30, `$h_verb` could + # only be OPENED, LANDING or WITHDRAWN by the time this branch is + # reached (a live lane's own TAKEOVER on an object it still holds + # falls through the `!= CLAIMED` test the same way) — but a dead + # lane's own un-superseded TAKEOVER (an earlier stale-claim takeover + # this lane never followed with a CLOSED/RELEASED/LANDED) reaches + # here too when THIS lane is confirmed alive, and the enumeration + # left it unnamed. + die "--force takes over a stale CLAIMED and nothing else: $obj is $h_verb by lane $h_lane. An open TAKEOVER, OPENED, LANDING or WITHDRAWN is not a stale claim, and lane $h_lane's own log does not end on ENDED or RETIRED either (or a live session on this workstation still holds it)." 2 + fi + # A LIVE TERMINAL HOLDER IS REFUSED HERE, NOT ASKED WHETHER ITS CLAIM + # IS OLD (Copilot round 13, PR #61): `claim_is_stale` answers a claim's + # own AGE and has never known anything about the lane behind it — so a + # CLAIMED left by a lane whose own log says ENDED/RETIRED while a real + # session on this workstation still backs it up would read as an + # ORDINARY stale claim once old enough, and be taken over, which is + # exactly the collision issue #30 exists to stop (repoK-3's own shape, + # reached here only because ITS object happened to be OPENED rather + # than CLAIMED). `HOLDER_LIVE_TERMINAL` is the immediately-preceding + # `holder_is_dead` call's own tri-state answer for this lane; refused + # in these words rather than folded into the stale-claim message + # below, which is not why this one is refused. + if [ -n "$HOLDER_LIVE_TERMINAL" ]; then + die "--force refused: lane $h_lane's own log ends $HOLDER_LIVE_TERMINAL, but a live session on this workstation still backs it up — refused exactly as any other live holder's claim on $obj is. Rule 1: the lane stops and reports; it does not author a successor." 2 + fi + # AND AN UNREADABLE RECORDS TREE IS REFUSED THE SAME WAY, NEVER ASKED + # claim_is_stale's QUESTION INSTEAD (Copilot's own "closer look" on + # c82577e, PR #61): "I could not check whether a live session backs + # this terminal log up" is not "checked and clear" — every OTHER + # caller of `live_holder` already refuses on a read this workstation + # could not make, and a terminal log is exactly the shape this branch + # exists to distrust; falling through to an age-only test here would + # let a workstation with no session records at all force a takeover + # `holder_is_dead` itself never established was safe. + if [ -n "$HOLDER_TERMINAL_UNKNOWN" ]; then + die "--force refused: lane $h_lane's own log ends $HOLDER_TERMINAL_UNKNOWN, and this workstation could not read whether a live session still backs it up. That is NOT 'no live session holds it' — refused for the same reason an unreadable read refuses the dead-lane path (issue #30), never assumed safe. Rule 1: the lane stops and reports; it does not author a successor." 2 + fi + if ! claim_is_stale "$h_lane" "$obj" "$h_utc" "$h_file" "$h_line"; then + die "--force refused: lane $h_lane's claim on $obj is $(age_of "$h_utc") old (threshold ${STALE_HOURS}h), or it is a PR, or that lane has since OPENED a PR naming it. Rule 1 makes a claim takeable only when it is stale, and lane $h_lane's own log does not end on ENDED or RETIRED either (or a live session on this workstation still holds it)." 2 + fi + takeover_from="$h_lane" + takeover_note="stale claim by lane $h_lane, posted $h_utc, no PR after ${STALE_HOURS}h" + takeover_reason_phrase=" (takeover of the stale claim held by lane $takeover_from)" + fi + # THE LOOKUP NAMES A "CLAIMED —" COMMENT, SO IT ONLY ANSWERS FOR ONE + # (Copilot round 12, PR #61): a dead lane's OPENED/LANDING/WITHDRAWN/ + # TAKEOVER hold can carry an EARLIER claimed comment of its own, from + # before that lane progressed past it, and `gh_stale_claim_url` would + # happily hand back that superseded comment's URL — citing a claim that + # is not the hold this TAKEOVER displaces. Only a currently-CLAIMED hold + # is that comment's own hold; every other dead-lane verb takes the lane + # fallback, exactly as `--no-github` already does. + if [ "$NO_GITHUB" = 1 ] || [ "$h_verb" != CLAIMED ]; then + takeover_payload="lane:$h_lane" + else + takeover_payload="$(gh_stale_claim_url "$obj" "$h_lane")" + [ -n "$takeover_payload" ] || takeover_payload="lane:$h_lane" + fi + fi + + # 2. Rule 1's three reads, printed. + reads="$(gh_reads "$obj")" || exit 1 + printf '%s\n' "$reads" + + # 3. decision 2 — a crossing warns and proceeds. + cross_repo_warn "$(object_repo "$obj")" "$home" "$lane" + + # 4. append, commit, push. CP_AFTER_REBASE runs on every rebase inside the + # push loop: if another lane's claim is on the rebased history, theirs + # landed first and this one has lost. + uuid="$(session_for "$lane")" + utc="$(utc_now)" + CLAIM_OBJ="$obj"; CLAIM_LANE="$lane"; CLAIM_SKIP="$takeover_from"; CLAIM_SKIP_DEAD="$takeover_dead" + CLAIM_ABANDON_REVIVED="" + CP_AFTER_REBASE=claim_rescan_hook + # A line written with --no-github is NOT a Rule 1 claim until its GitHub + # comment exists, and it says so on its face rather than in a habit. + ng=""; [ "$NO_GITHUB" = 1 ] && ng="no-github" + if [ -n "$takeover_from" ]; then + write_event "$lane" TAKEOVER "$obj" "←" "$takeover_payload" "${ng:+$ng; }$takeover_note" "$utc" "$uuid" + else + write_event "$lane" CLAIMED "$obj" "" "" "$ng" "$utc" "$uuid" + fi + wrc=$? + CP_AFTER_REBASE="" + CLAIM_SKIP_DEAD="" + + # 5. lost: Rule 1 says the lane STOPS AND REPORTS. The claim is abandoned, + # never queued — Rule 7's queueing is for substrates, which this + # amendment does not touch. TWO CAUSES, TWO EXIT CODES (Copilot's own + # "closer look" on 21b8e82, PR #61): 7 is the documented, pre-existing + # CLAIM-LOST — a rival's claim landed on main first; 9 is issue #30's + # own dead-lane verdict failing to reconfirm before this takeover's + # push landed. Both write the same CLAIM-LOST event (this attempt did + # not succeed, in either cause), but automation reading the PROCESS + # exit must be able to tell them apart, so the exit is never coerced + # to 7 for the second. + if [ "$wrc" = 7 ] || [ "$wrc" = 9 ]; then + # "ALIVE AGAIN" ONLY WHERE IT WAS SEEN (Copilot on 05d7889, PR #61): + # `claim_rescan_hook` sets `CLAIM_ABANDON_REVIVED` for a confirmed + # revival — a live session now backs the lane, or its log moved past + # the terminal line — and leaves it empty where the verdict simply + # could not be reconfirmed (an unreadable log, or an unreadable + # records tree). The exit is 9 either way; only the words differ. + if [ "$wrc" = 9 ] && [ -n "$CLAIM_ABANDON_REVIVED" ]; then + note "TAKEOVER ABANDONED — lane $CLAIM_WINNER is alive again. Rule 1: stop and report; do not author a successor." + write_event "$lane" CLAIM-LOST "$obj" "→" "lane:$CLAIM_WINNER" "abandoned: $CLAIM_WINNER is no longer dead, takeover withdrawn before landing" "$(utc_now)" "$uuid" + elif [ "$wrc" = 9 ]; then + note "TAKEOVER ABANDONED — lane $CLAIM_WINNER's dead-lane verdict could not be reconfirmed before this push landed (above). Rule 1: stop and report; do not author a successor." + write_event "$lane" CLAIM-LOST "$obj" "→" "lane:$CLAIM_WINNER" "abandoned: the dead verdict on $CLAIM_WINNER could not be reconfirmed; takeover withdrawn before landing" "$(utc_now)" "$uuid" + else + note "CLAIM LOST — lane $CLAIM_WINNER's claim on $obj landed on main first. Rule 1: stop and report; do not author a successor." + write_event "$lane" CLAIM-LOST "$obj" "→" "lane:$CLAIM_WINNER" "abandoned: $CLAIM_WINNER landed its claim first" "$(utc_now)" "$uuid" + fi + who_object "$obj" || : + exit "$wrc" + fi + [ "$wrc" = 0 ] || exit "$wrc" + + # 6. the comment, AFTER the push, citing the commit that carries the line. + sha="$(git -C "$LANES_REPO" rev-parse HEAD 2>/dev/null || printf '')" + if [ "$NO_GITHUB" != 1 ]; then + body="$(printf '%s — lane %s, session %s@%s, %s, for %s\n\nLogged in `%s` at `%s`%s.\n\nThe three reads (lane-collision-protocol Rule 1):\n\n```text\n%s\n```\n' \ + "${takeover_from:+TAKEOVER}${takeover_from:-CLAIMED}" "$lane" "$uuid" "$WS" "$utc" "$obj" \ + "$(log_path_for "$lane")" "${sha:-unknown}" "$takeover_reason_phrase" "$reads")" + url="$(gh_comment "$obj" "$body" 2>/dev/null || :)" + if [ -n "$url" ]; then + note "comment posted: $url" + else + note "WARNING: the GitHub comment could not be posted. The log line IS the claim and it has landed; post the comment by hand so that a reader outside this estate can see it." + fi + fi + note "lane $lane now holds $obj (${sha:-no sha})" + ;; + + release) + lane="${LANES_LANE:-}" + [ -n "$lane" ] || die "release needs the lane: LANES_LANE=<lane> lanes-edit.sh release <object>" 2 + check_lane_name "$lane" + obj_raw=""; why=""; home_override="" + while [ $# -gt 0 ]; do + case "$1" in + --no-github) NO_GITHUB=1; shift ;; + --home) home_override="${2-}"; [ -n "$home_override" ] || die "--home needs owner/repo" 2; shift 2 ;; + --home=*) home_override="${1#--home=}"; [ -n "$home_override" ] || die "--home needs owner/repo" 2; shift ;; + --) shift ;; + -*) die "unknown option '$1' for release" 2 ;; + *) + if [ -z "$obj_raw" ]; then obj_raw="$1" + elif [ -z "$why" ]; then why="$1" + else die "release takes <object> [\"<why>\"]" 2 + fi + shift ;; + esac + done + [ -n "$obj_raw" ] || die "usage: release <object> [\"<why>\"] [--no-github] [--home owner/repo]" 2 + log_sync # R30 — the fetch, then --home and the STARTED line + lane="$(canon_lane "$lane")" || exit 2 # Amendment 15 + home="$(resolve_home "$lane" "$home_override")" || exit $? + obj="$(canon_object "$obj_raw" "$home")" || exit 2 + ! is_lane_object "$obj" || die "a lane is not a releasable object" 2 + mine="$(state_events | lane_states_on "$obj" | awk -v sep="$US" -v lane="$lane" 'BEGIN{FS=sep} tolower($2) == tolower(lane)' || :)" + if [ -z "$mine" ]; then + note "NOTE: this lane has no line on $obj — releasing anyway, and the log will show that it did." + else + IFS="$US" read -r m_utc m_lane m_verb m_rest <<EOF +$mine +EOF + is_open_verb "$m_verb" || note "NOTE: this lane's last line on $obj is $m_verb, which is not an open state — releasing anyway." + fi + uuid="$(session_for "$lane")" + utc="$(utc_now)" + write_event "$lane" RELEASED "$obj" "" "" "$why" "$utc" "$uuid" || exit $? + if [ "$NO_GITHUB" != 1 ]; then + url="$(gh_comment "$obj" "$(printf 'RELEASED — lane %s, session %s@%s, %s, for %s%s\n' \ + "$lane" "$uuid" "$WS" "$utc" "$obj" "${why:+ — $why}")" 2>/dev/null || :)" + [ -n "$url" ] && note "release comment posted: $url" + fi + note "lane $lane released $obj" + ;; + + who) + mode="object"; arg=""; home_override="" + while [ $# -gt 0 ]; do + case "$1" in + --lane) mode="lane"; arg="${2-}"; [ -n "$arg" ] || die "--lane needs a lane name" 2; shift 2 ;; + --lane=*) mode="lane"; arg="${1#--lane=}"; [ -n "$arg" ] || die "--lane needs a lane name" 2; shift ;; + --landing) mode="landing"; arg="${2-}"; [ -n "$arg" ] || die "--landing needs owner/repo" 2; shift 2 ;; + --landing=*) mode="landing"; arg="${1#--landing=}"; [ -n "$arg" ] || die "--landing needs owner/repo" 2; shift ;; + --home) home_override="${2-}"; [ -n "$home_override" ] || die "--home needs owner/repo" 2; shift 2 ;; + --home=*) home_override="${1#--home=}"; [ -n "$home_override" ] || die "--home needs owner/repo" 2; shift ;; + --no-fetch) LANES_NO_FETCH=1; shift ;; + --) shift ;; + -*) die "unknown option '$1' for who" 2 ;; + *) [ -z "$arg" ] || die "who takes one argument" 2; arg="$1"; shift ;; + esac + done + [ -n "$arg" ] || die "usage: who <object> | who --lane <lane> | who --landing owner/repo" 2 + log_sync + case "$mode" in + lane) arg="$(canon_lane "$arg")" || exit 2 # Amendment 15 + who_lane "$arg" || exit $? ;; + landing) + wl_repo="$(alias_lookup "$arg" 2>/dev/null || :)"; wl_repo="${wl_repo:-$arg}" + case "$wl_repo" in */*) : ;; *) die "--landing needs owner/repo (or an alias in ${LANES_LOG_PREFIX%log/}repos.tsv); '$arg' is neither" 2 ;; esac + who_landing "$wl_repo" || exit $? ;; + *) + home="$(resolve_home "${LANES_LANE:-}" "$home_override")" || exit $? + obj="$(canon_object "$arg" "$home")" || exit 2 + who_object "$obj" || exit $? ;; + esac + ;; + + # ------------------------------------------- Amendment 8: swap and restart + + # Read-only. Exit 0 with rows, 8 with none — 8 is "no record" here exactly as + # it is everywhere else, so a launcher may gate on it. + # `swapped` EXITS 64 ON A USAGE ERROR OF ITS OWN, never the dispatcher's 2 + # (clause (c); F-B8, F-W4). The launcher gates its whole Amendment 8 degrade + # on this subcommand's 2 meaning ONE thing — "this `lanes-edit.sh` predates + # Amendment 8 and has no `swapped`" — and the dispatcher's unknown-subcommand + # 2 is exactly that. A caller's own bug must not be indistinguishable from an + # old helper at the one place the degrade is decided, so it gets a code of its + # own: 0 rows, 8 none swapped, 64 a bad call, 2 no such subcommand. + swapped) + sw_arg="" + while [ $# -gt 0 ]; do + case "$1" in + --) shift ;; + -*) die "unknown option '$1' for swapped (usage: swapped [<workstation>])" 64 ;; + *) [ -z "$sw_arg" ] || die "swapped takes at most one workstation: swapped [<workstation>]" 64 + sw_arg="$1"; shift ;; + esac + done + log_sync + # SEVEN FIELDS SINCE AMENDMENT 17(b), and the `NF >= 4` gate is unchanged: + # it is the shape test for a row that got as far as carrying a window, not a + # count of the fields a row has. `$7` and `$8` are the agent and its + # transcript, EMPTY for every record written before that amendment. + sw_out="$(swapped_lanes "${sw_arg:-$WS}" \ + | LC_ALL=C sort -t"$US" -k1,1 -k3,3r -k2,2 \ + | awk -v sep="$US" 'BEGIN { FS = sep; OFS = "\t" } NF >= 4 { print $2, $3, $4, $5, $6, $7, $8 }')" + if [ -z "$sw_out" ]; then + note "no lane on ${sw_arg:-$WS} is swapped — no lane's LAST lane-kind line is a PAUSED whose payload begins 'swap;' and names that workstation" + exit 8 + fi + printf '%s\n' "$sw_out" + ;; + + # The SessionStart hook. IT NEVER WRITES, IT NEVER TOUCHES THE NETWORK, AND + # IT ALWAYS EXITS 0 — the three properties that make it safe to put in front + # of every session on this workstation. Its stdin is the hook's JSON; with a + # terminal on stdin nobody piped one, and it is read as empty rather than + # waited for, because a hook that blocks is worse than a hook that says + # nothing. + # + # AMENDMENT 8, R-A8-1 — THERE IS NO `log_sync` HERE, AND THERE MUST NOT BE. + # This branch used to fetch: `log_sync` runs `remote_has_branch` (an + # `ls-remote`) and then a `fetch`, two network round-trips bounded at 60 s + # EACH, in front of every session start on the workstation — writing + # `.git/FETCH_HEAD`, objects and `refs/remotes/origin/main`, and advancing + # `origin/main` under any `lane-start` running at the same time. Amendment 7's + # "a read fetches first" governs STATE decisions (a claim, a refusal, who + # holds what); this is an informational block printed at every session start, + # and it must be fast and offline-safe instead. It reads the checkout AS LAST + # FETCHED and says how old that is, so a reader can tell a current answer from + # a stale one. `git_net` is the only door to the network in this file, and + # nothing on this path opens it. + session-start) + if [ -t 0 ]; then ss_json=""; else ss_json="$(cat 2>/dev/null || :)"; fi + ss_win="" + command -v tmux >/dev/null 2>&1 && ss_win="$(tmux display-message -p '#W' 2>/dev/null || :)" + session_start_block "$ss_json" "$ss_win" || : + exit 0 + ;; + + # AMENDMENT 12 — THE `UserPromptSubmit` HOOK. The ONE surface in this file + # that refuses a person's work, and the only one whose exit code is read by + # the harness rather than by a script: 2 BLOCKS the prompt and its stderr is + # what the person sees (code.claude.com/docs/en/hooks). Every other code lets + # the prompt through, which is why every refusal below is a 2 and why this + # verb is exempt from the dispatcher's `die … 1` above. + # + # AN ARGUMENT IS A USAGE REFUSAL AND NOT A SHRUG: a hook configured with a + # stray word is a hook nobody has checked, and passing the prompt through on + # one is exactly the silence Amendment 12 exists to end. + guard) + [ "$#" -eq 0 ] || die "usage: guard (the UserPromptSubmit hook; the hook's JSON on stdin)" 2 + if [ -t 0 ]; then g_json=""; else g_json="$(cat 2>/dev/null || :)"; fi + # IN A SUBSHELL, AND EVERY CODE BUT 0 IS A 2. This is clause (d) — *"fail + # CLOSED"* — made true of the guard's OWN failures and not only of the + # reads it makes, and it is here because the alternative was measured: + # `transcript_holders` left `th_here_prof` unset, `set -u` (line 292) took + # the whole shell down at the first record that was not this window's, and + # `lanes-edit.sh guard` exited 1. A 1 does not block a `UserPromptSubmit` + # — only 2 does — so the one defect this guard cannot have, a guard that + # lets a prompt through in silence, is exactly what a fatal inside it + # produced. The subshell contains it: `guard_run`'s effects are on the + # filesystem (the offer file, `lane-start`, the register) and on stderr, + # all of which cross it, and the only thing lost is shell state nothing + # reads afterwards. + # + # A `die` reached from one of the reads it makes is caught the same way, + # which is why the arm maps EVERY unexpected code rather than listing the + # ones known today. + g_rc=0 + ( guard_run "$g_json" ) || g_rc=$? + case "$g_rc" in + 0 | 2) exit "$g_rc" ;; + *) note "THE NAME GUARD ITSELF FAILED (exit $g_rc), so the three names were not verified — and a triple that cannot be verified is not a triple that agrees (Amendment 12(d)). This prompt is refused rather than let through, because only a 2 blocks one and a guard that fails open is the silence this amendment exists to end. $(guard_bypass)" + exit 2 ;; + esac + ;; + + # --- internal reads, for lane-start and lane-end ------------------------- + # Not part of the protocol's surface: they exist so that the two boundary + # scripts share ONE implementation of liveness and ONE parser of the log, + # instead of carrying copies that drift apart. + # Both answer with 8 for "there is no such record", the same 8 `who` uses, + # and with anything else ONLY when they failed. `lane-start` and `lane-end` + # treat 0 and 8 as answers and every other code as a refusal, because the + # first version of this returned 1 for both and both scripts read 1 as "no + # holder" / "pre-cutover lane" — a broken helper turned a refusal into a + # silent pass, which is the one thing a boundary act must never do. + # 0 prints `<uuid> <tmux> <name> <pid> <here|elsewhere|orphan>`, US-separated. + # The fifth field is Amendment 8 ruling (g)'s: the caller must not have to + # infer whose session it is from the `tmux` column, because a record with no + # target is not a record in no window, and reading it as one is what refused + # this lane the window it was running in. + # AMENDMENT 8(f), R-A8-6 — the row's EARLIER ids, and who is still holding + # them. Read-only, no fetch of its own (the caller has just made one), and it + # runs nothing: `lane-end <lane> --retire <pid|uuid>` is printed by the caller + # and typed by a person (clause (k) rule (e)). + # 0 with rows, 8 with none, 1 where the records could not be read — the same + # three answers `live-holder` gives, so a caller reads them the same way. + idle-holders) + lane="${1-}"; [ -n "$lane" ] || die "usage: idle-holders <lane>" 2 + lane="$(canon_lane "$lane")" || exit 2 # Amendment 15 + idle_holders "$lane"; ih_rc=$? + case "$ih_rc" in + 0) : ;; + 8) exit 8 ;; + *) die "could not read this workstation's session records for lane $lane: ${SESSION_FILES_ERR:-unknown error}." 1 ;; + esac + ;; + + live-holder|lane-holders) + lane="${1-}"; [ -n "$lane" ] || die "usage: live-holder <lane>" 2 + # A READ FETCHES FIRST, like every other read here. This one did not, and + # "the published row" then meant whatever `origin/<branch>` happened to say + # when this checkout last pulled: a session started from another clone on + # this workstation stamps its uuid on the row, and until something unrelated + # fetched, the rename gate could not see it and answered 8 — a rename into a + # name that is held, which is what mints `<lane> (2)`. The fetch can only + # ADD ids, and an id is only ever a reason to refuse. + log_sync + # The id SET is the published row's union the working tree's (R25): this is + # the boundary read that decides whether a window may take a name, and an id + # only ever adds a reason to refuse. + lane="$(canon_lane "$lane")" || exit 2 # Amendment 15 + lh_ids="$( { session_ids_of_lane "$lane" 2>/dev/null || : + session_ids_local_of_lane "$lane" 2>/dev/null || :; } | awk 'NF && !seen[$0]++')" + # DECISION 8(e) — A `--fork-session` OF THIS LANE'S TRANSCRIPT IS NEVER A + # HOLDER, AND SAYING SO IS PART OF THE ANSWER. `live_holder` already + # answers only about ids the ROW carries, so a fork — which has a new id + # and the lane's title — cannot be returned by it and could pass unseen. + # Amendment 8 ruling (g) skipped a `kind: bg` companion; Evidence 6's fork + # was one AND was orchestrating, so the rule is extended to forks BY ID. + # The note is on stderr, so the 0/8 contract this read's two callers gate + # on is untouched. + lh_fk=""; lh_fkrc=0 + lh_fk="$(lane_forks "$lane" 2>/dev/null)" || lh_fkrc=$? + # ON STDERR, like the DEFECT line below it, so the 0/8 contract this read's + # two callers gate on is untouched — and said at all, because a fork check + # that could not be made is not a lane with no fork (#26, `37632b1`). + case "$lh_fkrc" in + 0 | 8) : ;; + *) note "this workstation's session records could not be read, so whether a live FORK of lane $lane's transcript is running is NOT established — which is not the same as none. See: lanes-edit.sh forks $lane" ;; + esac + if [ -n "$lh_fk" ]; then + while IFS="$(printf '\t')" read -r lh_fid lh_fpid lh_fkind lh_fcwd; do + [ -n "${lh_fid:-}" ] || continue + note "DEFECT: $lh_fid is a live FORK of lane $lane's transcript (pid $lh_fpid, ${lh_fkind:-interactive}, cwd ${lh_fcwd:-unknown}) — it is NOT a holder of this lane and must not write the register. Retire it: lane-end $lane --retire $lh_fpid" + done <<EOF +$lh_fk +EOF + fi + lh_all=""; [ "$cmd" != lane-holders ] || lh_all=all + live_holder "$lane" "$lh_ids" "$lh_all"; lh_rc=$? + case "$lh_rc" in + 0) : ;; + 8) exit 8 ;; + *) die "could not read this workstation's session records for lane $lane: ${SESSION_FILES_ERR:-unknown error}. That is NOT 'no live session holds it' — fix the records or the permissions and re-run." 1 ;; + esac + ;; + + # AMENDMENT 8 — which LIVE session is in a tmux WINDOW, keyed on the window + # and not on a lane's recorded ids. `lane-start` asks it about the window it + # is run in, because the harness mints a new transcript uuid with nobody + # acting and that id is in no row for `live-holder` to find. 0 with + # `<uuid> <tmux> <name> <pid> <profile>` (US-separated), 8 when the records + # were read and no live one is in that window, 1 when they could not be read. + window-session) + wsub="${1-}"; [ -n "$wsub" ] || die "usage: window-session <tmux session>:<window id>" 2 + window_session "$wsub"; wsub_rc=$? + case "$wsub_rc" in + 0) : ;; + 8) exit 8 ;; + *) die "could not read this workstation's session records for window $wsub: ${SESSION_FILES_ERR:-unknown error}. That is NOT 'no live session is in that window'." 1 ;; + esac + ;; + + # ------------------------- AMENDMENT 18(h): ONE LIVE PROCESS PER TRANSCRIPT + # + # THREE CALLERS AND ONE IMPLEMENTATION — `lane-start` before it binds or + # resumes an id, `lane-end --retire <pid>` when the duplicate's id is the + # ROW'S OWN (opensoft/openRepoTools#39), and the prompt `guard`. It answers + # about ONE transcript and says, per live process, where it is and whether it + # is THIS window's: + # + # <pid><TAB-as-US><kind><US><tmux|none><US><profile><US><where><US><here|other><US><record file> + # + # 0 with rows, 8 with none, 1 where the records could not be read, 64 usage. + # The 1 is the fail-closed one: a caller that read it as 8 would bind a + # transcript two processes hold, which is the whole defect. + transcript-holders) + thub="${1-}"; [ -n "$thub" ] || die "usage: transcript-holders <session uuid>" 64 + transcript_holders "$thub"; thub_rc=$? + case "$thub_rc" in + 0) : ;; + 8) exit 8 ;; + 64) die "usage: transcript-holders <session uuid>" 64 ;; + *) die "could not read this workstation's session records for session $thub: ${SESSION_FILES_ERR:-unknown error}. That is NOT 'no other live process carries it', and a caller that read it as one would bind a transcript two processes hold." 1 ;; + esac + ;; + + # ---------------------- AMENDMENT 18(b): THE BINDING, AS A READ + # + # `binding <lane>` — WHERE THIS LANE IS, and whether this place may pronounce + # on it. Eight tab-separated fields; the FIRST FOUR are the contract + # opensoft/openRepoTools#38 act 2 states and the rest are grown at the end, + # this file's rule for a read that gains a field (`swapped_lanes`'s sixth and + # seventh say why): + # + # <host> <container> <window> <utc> <session> <os> <here|elsewhere> <window state> + # + # here / elsewhere whether THIS process is inside the binding's own host + # and container — the only place liveness may be + # pronounced from (clause (b)). From `elsewhere` a + # binding is UNKNOWN and never dead, whatever `kill -0` + # says, because a pid does not cross a pid namespace. + # window state `live`, `gone` or `unknown`. `gone` is clause (b)'s one + # exception and is answered only where the HOST matches, + # because that is what makes the tmux server shared; it + # is the takeover path (opensoft/openRepoTools#30) and + # the one way a binding reads dead from another container. + # + # 0 BOUND · 8 FREE (the last lane-kind line released it, or there is none) · + # 1 the log could not be read, which is never "this lane is free" (Amendment + # 7(d)) · 64 a usage error of its own. + binding) + lane="${1-}"; [ -n "$lane" ] || die "usage: binding <lane>" 64 + [ "$#" -le 1 ] || die "binding takes one lane: binding <lane>" 64 + check_lane_name "$lane" + log_sync + lane="$(canon_lane "$lane")" || exit 2 # Amendment 15 + bd_out=""; bd_rc=0 + bd_out="$(lane_binding_scan "$lane")" || bd_rc=$? + [ "$bd_rc" = 0 ] || die "binding could not read lane $lane's object log (exit $bd_rc). That is NOT 'this lane is free' — a read that failed is never an answer (Amendment 7(d)), and a caller that took it as one would start a second session on a lane another place is holding." 1 + # EVERY FIELD IS NAMED, and the last name is the last field: `read` puts + # what is left into its final variable, so a name short of the emit is a + # variable carrying four more fields glued on by `$US` — and `bd_legacy` + # then reads `legacy` plus four separators, which is not `legacy`, and the + # cutover rule below silently stops firing. Measured by the suite, on + # `lane-start --dry-run repoA11 7`: a pre-amendment binding on this very + # workstation read as another container's. + IFS="$US" read -r bd_state bd_host bd_cont bd_win bd_utc bd_sess bd_os \ + bd_rutc bd_rsess bd_rpay bd_xverb bd_xutc bd_xsess bd_xpay bd_legacy \ + bd_fverb bd_futc bd_fsess bd_fpay <<EOF +$bd_out +EOF + case "$bd_state" in + bound|requested) : ;; + *) exit 8 ;; + esac + bd_where=elsewhere + binding_is_here "$bd_host" "$bd_cont" "$bd_legacy" && bd_where=here + printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' \ + "${bd_host:-unknown}" "${bd_cont:-none}" "${bd_win:-none}" "${bd_utc:-unknown}" \ + "${bd_sess:-unknown}" "${bd_os:-unknown}" "$bd_where" "$(binding_window_state "$bd_host" "$bd_win" "$bd_legacy")" + ;; + + # ------------- AMENDMENT 18(c)/(e): ASK THE BINDING TO HAND OFF, THEN WAIT + # + # request-handoff <lane> [--wait <s>] [--session <uuid>] [--no-wait] + # [--force "<why>"] [--dry-run] + # + # THE WHOLE OF CLAUSE (c)'s MECHANISM, in the order the clause states it: the + # line is written and PUSHED first, so a bound session anywhere reads it from + # `origin`; then — and only where the bound pane is on THIS tmux server — + # `/handoff --exit requested by <uuid>@<host>/<container>` is typed into it + # (Amendment 12's M1, the one mechanism a running session has); then the + # requester WAITS for a `PAUSED`, `ENDED` or `RETIRED` newer than its request. + # + # `--force` IS CLAUSE (e) AND IS A SECOND INVOCATION, NEVER AUTOMATIC: it + # writes the release ON THE BOUND SESSION'S BEHALF, in the REQUESTER'S OWN + # session field — *"so it is not impersonation (the retired-lane release of + # 2026-09-13, opensoft/openRepoTools#30, is the precedent)"* — and asks for + # nothing. It takes a WHY, because the bound session, if it is alive after all, + # is going to read that sentence at its next prompt and refuse every prompt + # from then on. + # + # EXIT CODES, this file's family: 0 THE LANE IS FREE — bind it · 2 the wait + # ended with nothing, or the request was refused · 8 the lane was already free + # · 1 a read failed, which is never "the lane is free" · 64 usage. + request-handoff) + lane="${1-}"; [ -n "$lane" ] || die "usage: request-handoff <lane> [--wait <s>] [--session <uuid>] [--force \"<why>\"] [--dry-run]" 64 + shift + rh_wait=300; rh_sess=""; rh_force=0; rh_dry=0; rh_why="" + while [ $# -gt 0 ]; do + case "$1" in + --wait) rh_wait="${2-}"; [ -n "$rh_wait" ] || die "--wait needs a number of seconds" 64; shift 2 ;; + --wait=*) rh_wait="${1#--wait=}"; [ -n "$rh_wait" ] || die "--wait needs a number of seconds" 64; shift ;; + --no-wait) rh_wait=0; shift ;; + --session) rh_sess="${2-}"; [ -n "$rh_sess" ] || die "--session needs a transcript uuid" 64; shift 2 ;; + --session=*) rh_sess="${1#--session=}"; [ -n "$rh_sess" ] || die "--session needs a transcript uuid" 64; shift ;; + --force) rh_force=1; shift ;; + --dry-run) rh_dry=1; shift ;; + --) shift; while [ $# -gt 0 ]; do rh_why="${rh_why:+$rh_why }$1"; shift; done ;; + -*) die "unknown option '$1' for request-handoff" 64 ;; + *) rh_why="${rh_why:+$rh_why }$1"; shift ;; + esac + done + case "$rh_wait" in ''|*[!0-9]*) die "--wait takes a whole number of seconds; '$rh_wait' is not one" 64 ;; esac + # A WHY BELONGS TO `--force` AND TO NOTHING ELSE, so one given without it is + # REFUSED rather than ignored: a request carries the asker's host, container + # and window and no sentence, and words silently dropped are words a person + # believes they wrote into an append-only log. + if [ -n "$rh_why" ] && [ "$rh_force" = 0 ]; then + die "request-handoff takes no free text: clause (c)'s request line says WHO is asking and from WHERE — \`by host <h>; container <c>; window <w>; wait <n>s\` — and carries no sentence. A why is what \`--force\` writes, because that one is read by the session it takes the lane from: + $SELF request-handoff $lane --force \"$rh_why\"" 64 + fi + check_lane_name "$lane" + log_sync + lane="$(canon_lane "$lane")" || exit 2 # Amendment 15 + # THE SEAM (Copilot round 3 on #97): asking a lane's session to hand off is + # a handoff act on that lane, refused for a managed one before the binding + # is read — so `--dry-run` refuses too, rather than planning an act that + # could not be taken. + managed_seam_refuse "$lane" "request-handoff (Amendment 18(c))" + rh_out=""; rh_rc=0 + rh_out="$(lane_binding_scan "$lane")" || rh_rc=$? + [ "$rh_rc" = 0 ] || die "request-handoff could not read lane $lane's object log (exit $rh_rc). That is NOT 'this lane is free' (Amendment 7(d)), and nothing was written." 1 + IFS="$US" read -r rh_state rh_host rh_cont rh_win rh_utc rh_bsess rh_os \ + rh_rutc rh_rsess rh_rpay rh_xverb rh_xutc rh_xsess rh_xpay rh_legacy \ + rh_fverb rh_futc rh_fsess rh_fpay <<EOF +$rh_out +EOF + case "$rh_state" in + bound|requested) : ;; + *) note "lane $lane is FREE — its last lane-kind line is ${rh_xverb:-none at all}${rh_xutc:+ at $rh_xutc}, so there is no binding to ask and nothing was written. Bind it."; exit 8 ;; + esac + rh_wstate="$(binding_window_state "$rh_host" "$rh_win" "$rh_legacy")" + # WHERE the binding is decides what a reader is TOLD, not whether the + # request is allowed. Clause (c) makes a different `host`, `container` OR + # WINDOW a refusal to bind, so a binding in this very host and container — + # a second window of it — is asked for exactly as another machine's is, and + # the one place a request has nothing to ask is the window it is made from. + rh_here=elsewhere + binding_is_here "$rh_host" "$rh_cont" "$rh_legacy" && rh_here=here + # AND THAT ONE PLACE IS TESTED ONLY WHERE THE BINDING IS LOCAL (Copilot + # round 1 on this PR). A tmux `@id` names a window ON ONE TMUX SERVER and + # tmux reissues them from `@0` when a server is replaced, so `@3` here and + # `@3` on another machine are not one window — and comparing the ids alone + # would refuse a request from a second HOST whose current window happened to + # carry the bound window's number, which is the one refusal that leaves a + # lane unaskable. The identity test is made after locality is proved, never + # instead of it. + if [ "$rh_here" = here ] && binding_is_this_window "$rh_win"; then + die "lane $lane's binding IS this window ($rh_win) on this host and in this container: a handoff request is what a SECOND place makes of the first, and there is nothing here to ask. Nothing was written." 2 + fi + + # ---- CLAUSE (e): `--force`, THE SECOND INVOCATION. + if [ "$rh_force" = 1 ]; then + [ -n "$rh_why" ] || die "--force takes a WHY, and it is not decoration: it is written into the lane's append-only log and it is the sentence the bound session reads at its next prompt, when it refuses every prompt from then on and names who forced it (Amendment 18(e)). Say what happened: + $SELF request-handoff $lane --force \"<why>\"" 2 + rh_uuid="$(requester_uuid "$rh_sess")" || rh_uuid="" + [ -n "$rh_uuid" ] || die "--force writes a \`PAUSED\` in THE REQUESTER'S OWN session field — that is what makes it a release on behalf of the bound session rather than an impersonation of it (Amendment 18(e); the 2026-09-13 retired-lane release, opensoft/openRepoTools#30, is the precedent) — and no transcript uuid is knowable here. Name it: --session <uuid>, or run this from inside the session that wants the lane. Nothing was written." 2 + # THE PERSON TYPED A SENTENCE, NOT A GRAMMAR — so the three separators + # this line is built out of are folded rather than refused: `, ` divides + # an event line's four FIELDS, ` — ` divides the verb from the fields and + # the fields from the free text, and `; ` divides one SUB-FIELD from the + # next. A middle dot is none of them, and it is the separator this + # estate's own register rows already use. + # + # AND THE WHY IS WRITTEN AS A NAMED SUB-FIELD, `why <text>`, which clause + # (e) does not spell and which the log needs. The clause's `; <why the + # person gave>` is a sub-field with no name, and every reader here matches + # a sub-field by the word it OPENS with: a why beginning `host is + # unreachable` would be read as this line's `host`, refused by the + # writer's own check, and the person would be told about a field they did + # not write. Named, it can collide with nothing, the words are still + # exactly the ones they typed, and `why` is a name no reader in this file + # parses. + rh_why_clean="$(printf '%s' "$rh_why" | sed 's/ — / · /g; s/, / · /g; s/; / · /g')" + # THE BINDING IS READ AGAIN IMMEDIATELY BEFORE THE APPEND (Copilot round 1 + # on this PR). This release names the session it acts for — `on behalf of + # <bound uuid>` — out of a scan made before the uuid was resolved and the + # why was checked. If the original holder released in between and a third + # place bound the lane, an unconditional append would release THE NEW + # HOLDER while naming the old one: the one act this clause exists to make + # loud, made silently against somebody who never had a chance to answer. + # The window is not closed by this — an append is not a lock, and nothing + # in the ratified text gives a lane one — but the scan is now the last + # thing before the write rather than the first thing in the run, and a + # binding that moved is a refusal naming what it moved to. + rh_re=""; rh_re_rc=0 + rh_re="$(lane_binding_scan "$lane")" || rh_re_rc=$? + [ "$rh_re_rc" = 0 ] || die "lane $lane's object log could not be re-read immediately before the forced release (exit $rh_re_rc), and a \`PAUSED\` written on an answer nobody got could release a binding that is not the one this run read. Nothing was written." 1 + IFS="$US" read -r rh2_state rh2_host rh2_cont rh2_win rh2_utc rh2_sess rh2_rest <<EOF +$rh_re +EOF + if ! binding_identity_same "$rh_host" "$rh_cont" "$rh_win" "$rh_utc" "$rh_bsess" \ + "$rh2_host" "$rh2_cont" "$rh2_win" "$rh2_utc" "$rh2_sess"; then + die "lane $lane's binding CHANGED while this run was preparing to force it. It was window $rh_win in container $rh_cont on host $rh_host (session ${rh_bsess:-unknown}, $rh_utc); it is now ${rh2_state:-free}${rh2_win:+, window $rh2_win in container ${rh2_cont:-none} on host ${rh2_host:-unknown} (session ${rh2_sess:-unknown}, $rh2_utc)}. Nothing was written: a forced release names the session it acts for, and this one would have named a session that no longer holds the lane while releasing one that does. Read it and decide again: + $SELF binding $lane" 2 + fi + rh_fpay="on behalf of ${rh_bsess:-unknown}; forced by $rh_uuid@$LANES_HOST_NAME/$LANES_CONTAINER_NAME; why $rh_why_clean" + if [ "$rh_dry" = 1 ]; then + note "PLAN: $SELF log PAUSED lane:$lane → \"$rh_fpay\" (as session $rh_uuid)" + note "PLAN: then bind — the lane reads free from that line on" + exit 0 + fi + write_event "$lane" PAUSED "lane:$lane" '→' "$rh_fpay" "forced release" "$(utc_now)" "$rh_uuid" || exit $? + note "FORCED: lane $lane's binding is released on behalf of ${rh_bsess:-the bound session}. $(binding_facts "$lane" "$rh_host" "$rh_cont" "$rh_win" "$rh_utc" "$rh_bsess" "$rh_wstate")" + note "If that session is alive after all it will read this line at its next prompt and refuse EVERY prompt from then on, naming it and naming you, until the person there hands off or ends it (Amendment 18(e)). Two places never both write a lane in silence." + exit 0 + fi + + # ---- CLAUSE (c): THE REQUEST, WRITTEN BEFORE ANYTHING ELSE IS TRIED. + rh_uuid="$(requester_uuid "$rh_sess")" || rh_uuid="" + [ -n "$rh_uuid" ] || die "clause (c)'s request line carries the REQUESTER'S transcript uuid in its session field, and Amendment 7(b) admits nothing else there — not a placeholder, and never the literal 'unknown', which is in this estate's append-only log four times already with no later line able to correct any of them. No uuid is knowable here: this shell has no \$CLAUDE_CODE_SESSION_ID and no live session record names this window. Ask from inside the session that wants the lane, or name it: + $SELF request-handoff $lane --session <uuid> + Nothing was written." 2 + rh_mywin="$(tmux display-message -p '#{session_name}:#{window_index}' 2>/dev/null || :)" + rh_myid="$(tmux display-message -p '#{window_id}' 2>/dev/null || :)" + case "$rh_myid" in @[0-9]*) rh_mywin="$rh_mywin $rh_myid" ;; esac + [ -n "$rh_mywin" ] || rh_mywin=none + rh_pay="by host $LANES_HOST_NAME; container $LANES_CONTAINER_NAME; window $rh_mywin; wait ${rh_wait}s" + rh_type="/handoff --exit requested by $rh_uuid@$LANES_HOST_NAME/$LANES_CONTAINER_NAME" + if [ "$rh_dry" = 1 ]; then + note "PLAN: $(binding_facts "$lane" "$rh_host" "$rh_cont" "$rh_win" "$rh_utc" "$rh_bsess" "$rh_wstate") ($rh_here)" + note "PLAN: $SELF log HANDOFF-REQUESTED lane:$lane → \"$rh_pay\" (as session $rh_uuid), committed and pushed FIRST" + if [ "$rh_wstate" = live ]; then + note "PLAN: tmux send-keys into ${rh_win##* } — $rh_type" + else + note "PLAN: nothing is typed into a pane — this tmux server says the bound window is $rh_wstate, and the request travels through the pushed log alone" + fi + note "PLAN: then poll the published log every ${LANES_POLL_SECONDS:-15}s for ${rh_wait}s for a PAUSED, ENDED or RETIRED newer than the request; an empty wait REFUSES and names --force" + exit 0 + fi + rh_wrote="$(utc_now)" + write_event "$lane" HANDOFF-REQUESTED "lane:$lane" '→' "$rh_pay" "" "$rh_wrote" "$rh_uuid" || exit $? + note "REQUESTED: $(binding_facts "$lane" "$rh_host" "$rh_cont" "$rh_win" "$rh_utc" "$rh_bsess" "$rh_wstate")" + + # ---- AND ONLY NOW THE PANE, WHERE IT IS ON THIS TMUX SERVER (Amendment + # 12's M1). It is an OPTIMISATION of the same-host case and never the + # request: a session that never reads it answers at its hook's next read of + # the pushed line instead. + rh_typed=no + if [ "$rh_wstate" = live ]; then + rh_trc=0 + guard_type "${rh_win##* }" "$rh_type" || rh_trc=$? + case "$rh_trc" in + 0) rh_typed=yes; note "typed into ${rh_win##* }: $rh_type" ;; + 9) note "the bound pane is running something other than \`claude\`, so nothing was typed into it (M1's own condition): the request is in the pushed log and is read at that session's next prompt." ;; + 8) note "the bound pane's current command could not be read, so nothing was typed into it — fail closed (M1). The request is in the pushed log." ;; + *) note "tmux would not take the keys for ${rh_win##* }, so nothing was typed. The request is in the pushed log and is read at that session's next prompt." ;; + esac + else + note "the bound window is $rh_wstate from here, so no pane was typed into: the request travels through the pushed log, which is why it is written first." + fi + + # ---- THE WAIT (clause (c)), AND ITS EMPTY END (clause (e)). + rh_poll="${LANES_POLL_SECONDS:-15}" + case "$rh_poll" in ''|*[!0-9]*|0) rh_poll=15 ;; esac + rh_deadline=$(( $(date -u +%s) + rh_wait )) + [ "$rh_wait" = 0 ] || note "waiting up to ${rh_wait}s for lane $lane to be released (polling the published log every ${rh_poll}s) …" + while : ; do + rh_left=$(( rh_deadline - $(date -u +%s) )) + if [ "$rh_left" -le 0 ]; then break; fi + # THE SLEEP IS BOUNDED BY WHAT IS LEFT OF THE WAIT (Copilot round 1 on + # this PR). `--wait <s>` is an UPPER BOUND a person named, and a fixed + # fifteen-second poll overruns it whenever the two disagree: `--wait 1` + # slept fifteen and then answered. What the poll interval decides is how + # OFTEN the log is asked, never how long the caller is held. + rh_nap="$rh_poll" + [ "$rh_nap" -gt "$rh_left" ] && rh_nap="$rh_left" + sleep "$rh_nap" + log_sync + rh_out=""; rh_rc=0 + rh_out="$(lane_binding_scan "$lane")" || rh_rc=$? + [ "$rh_rc" = 0 ] || { note "the lane's log could not be read on this poll — waiting on"; continue; } + IFS="$US" read -r rh_state2 rh_host2 rh_cont2 rh_win2 rh_utc2 rh_bsess2 rh_os2 rh_rest2 <<EOF +$rh_out +EOF + case "$rh_state2" in + released|free) + note "lane $lane is FREE — the binding was released while this request waited. Bind it." + exit 0 ;; + bound|requested) + if ! binding_identity_same "$rh_host" "$rh_cont" "$rh_win" "$rh_utc" "$rh_bsess" \ + "$rh_host2" "$rh_cont2" "$rh_win2" "$rh_utc2" "$rh_bsess2"; then + die "lane $lane was released and BOUND AGAIN while this request waited — its binding is now window ${rh_win2:-none} in container ${rh_cont2:-none} on host ${rh_host2:-unknown} (session ${rh_bsess2:-unknown}, $rh_utc2). The request this run wrote is answered and the lane is somebody else's: ask again, or take it up with that place." 2 + fi ;; + esac + done + note "THE WAIT ENDED WITH NOTHING. $(binding_facts "$lane" "$rh_host" "$rh_cont" "$rh_win" "$rh_utc" "$rh_bsess" "$rh_wstate")" + note " the request: $rh_wrote → $rh_pay, as session $rh_uuid" + note " the pane: ${rh_typed} (this tmux server says that window is $rh_wstate)" + die "no PAUSED, ENDED or RETIRED newer than that request arrived in ${rh_wait}s, so lane $lane is still bound and NOTHING here has bound it (Amendment 18(e)). A working session is never interrupted — a hook fires at a prompt boundary, and a session inside a long turn answers when that turn ends. Wait longer, or override, which is a SECOND invocation and never automatic: + $SELF request-handoff $lane --wait 900 + $SELF request-handoff $lane --force \"<why you are taking it>\"" 2 + ;; + + # ------------------------------ AMENDMENT 11, clause (h): the new reads + # + # ALL READ-ONLY; all answer out of `origin/<branch>` as every Amendment 7 + # read does; all honour `LANES_NO_FETCH=1`, because each one sits in front of + # a launch and a launcher must not sit on the network to open a terminal; and + # all follow Amendment 7(d)'s fail-closed convention — 0 an answer, 8 NO + # ANSWER, 64 a usage error of their own, and anything else a failed read that + # a caller must not read as "nothing to report". + # + # WITH ONE EXCEPTION, AND IT IS THE ONE EVERY UN-UPGRADED WORKSTATION IS IN: + # a `lanes-edit.sh` that has never heard of one of these exits **2** for an + # unknown subcommand, exactly as a pre-Amendment-8 one did for `swapped`. + # That is A HELPER PREDATING THE AMENDMENT THAT ADDED THE READ — expected and + # silent — and a caller falls to its next rung there rather than refusing. + # The two kinds of 2 are told apart by the helper's own WORDS and not by its + # status: the `*)` arm below says "unknown subcommand" and no other refusal + # here does. + + # ADOPTION ACT 0 SHIPS `session-lane`, AND IT IS BELOW RATHER THAN HERE. + # `opensoft/brett-wip#5` @`3719d97` added it and `openRepoTools#24` — MERGED as +# `d4b5710` on this repository's `main`, which is the sha act 3 is cited by from +# here on rather than a branch name — ported that + # commit into this copy, so this branch carries NO second implementation of it + # (A11 Addendum 3, CF-T11: act 0 ships FOUR items, and that is the fourth). + # `3719d97` IS THE MERGE COMMIT. Act 0 merged 2026-09-13T19:14:37Z, squashed, + # so the draft head `95e7a4c` this comment used to cite is not an ancestor of + # `origin/main` at all (F-X18, A11 Addendum 4 ruling 13). + # `/restart`'s step 2(b) and `lane-start`'s step 3b both call the ported arm. + + # The lane bound to a window OF THE ASKING WORKSTATION. Three callers share + # this one implementation — the launcher's precedence 3, `/restart`'s step + # 2(c), and the `/lane-swap` skill's step 1 — and it owns the `<@id>`-versus- + # ref agreement rule for all three (A11 Addendum 2, `R-A11-8`). + # + # The optional workstation comes FIRST, exactly as `swapped [<ws>]` takes it, + # and is told from the ref by shape: a ref is an `@id` or carries a `:`, and + # a workstation name is neither. + window-lane) + wl_a=""; wl_b="" + while [ $# -gt 0 ]; do + case "$1" in + --) shift ;; + -*) die "unknown option '$1' for window-lane (usage: window-lane [<workstation>] <@id>|<session>:<index>)" 64 ;; + *) if [ -z "$wl_a" ]; then wl_a="$1" + elif [ -z "$wl_b" ]; then wl_b="$1" + else die "window-lane takes at most a workstation and one window ref" 64 + fi + shift ;; + esac + done + if [ -n "$wl_b" ]; then wl_in_ws="$wl_a"; wl_in_ref="$wl_b" + else wl_in_ws="$WS"; wl_in_ref="$wl_a" + fi + [ -n "$wl_in_ref" ] || die "usage: window-lane [<workstation>] <@id>|<session>:<index>" 64 + case "$wl_in_ref" in + @*|*:*) : ;; + *) die "'$wl_in_ref' is neither an <@id> nor a <session>:<index>. A workstation is given FIRST: window-lane [<workstation>] <ref>" 64 ;; + esac + log_sync + window_lane "$wl_in_ws" "$wl_in_ref"; wl_rc=$? + case "$wl_rc" in + 0) : ;; + 8) exit 8 ;; + 64) die "usage: window-lane [<workstation>] <@id>|<session>:<index>" 64 ;; + *) die "window-lane could not read this workstation's records for $wl_in_ref (exit $wl_rc). That is NOT 'no lane is bound to that window'." 1 ;; + esac + ;; + + # The lane's RECORDED DIRECTORY: the `dir ` sub-field of its log's LAST + # lane-kind line carrying one, in file order, unquoted where it was written + # quoted (Amendment 11 clause (c)). Four callers: `lane-start`'s directory + # precedence rung 3, the launcher's `--dir` default, `/restart`'s step 3 and + # `restart`'s own. + # + # 8 IS THE ANSWER FOR EVERY LANE THAT HAS NOT STARTED UNDER THIS AMENDMENT, + # and it is not a failure: adoption act 7 cuts each lane over at its own next + # start, nothing is backfilled (Amendment 7(i)), and the default + # `$PROJECTS_ROOT/<repo>` carries it until then, which is what it has always + # done. + lane-dir) + lane="${1-}"; [ -n "$lane" ] || die "usage: lane-dir <lane>" 64 + [ "$#" -le 1 ] || die "lane-dir takes one lane: lane-dir <lane>" 64 + check_lane_name "$lane" + log_sync + lane="$(canon_lane "$lane")" || exit 2 # Amendment 15 + # THE READER'S STATUS DECIDES, AS IT DOES IN EVERY OTHER ARM OF THIS CLAUSE + # (#26, the fail-closed family one layer out). `window-session`, `last-session`, + # `forks` and `window-lane` all carry this `case`; these two carried + # `|| :` and then read the EMPTINESS of the output, so a log that could not + # be read left here as **8** — the pre-cutover answer, which is the one + # answer every caller of this read treats as *"fall to the next rung"*. + ld_out="$(lane_payload_field "$lane" dir)"; ld_rc=$? + case "$ld_rc" in + 0) : ;; + 8) exit 8 ;; + *) die "lane-dir could not read lane $lane's log (exit $ld_rc). That is NOT 'this lane has no recorded directory', and a caller that read it that way would resolve the directory from the rungs beneath a record it never read (Amendment 7(d))." 1 ;; + esac + [ -n "$ld_out" ] || exit 8 + printf '%s\n' "$ld_out" + ;; + + # THE LANE'S RECORDED PROFILE — `lane-dir`'s sibling, and the same read one + # sub-field along: the `profile ` of its log's LAST lane-kind line carrying + # one, unquoted where it was written quoted. + # + # IT IS AN ADDITION TO SPEC §11's TABLE AND IS NAMED AS ONE. `lane <name>` + # needs exactly two facts about a lane it is not standing in — its directory + # and its profile — and the directory already had a read of its own. Without + # this the profile came out of the `lanes` listing, which must consult + # `state_events` for the held-objects column and so reads EVERY log on the + # workstation: measured at seventeen seconds on the live register, to answer + # one question about one lane, on the path a person types to get back to work. + # One `git show` instead, through the same `lane_payload_field` `lane-dir` + # uses, so the two cannot disagree about which line is a lane's last. + # + # 8 IS THE ANSWER FOR EVERY LANE THAT HAS NOT STARTED UNDER THIS AMENDMENT, + # and `restart` refuses on it rather than guessing: a wrong profile is a + # launch into another account. + lane-profile) + lane="${1-}"; [ -n "$lane" ] || die "usage: lane-profile <lane>" 64 + [ "$#" -le 1 ] || die "lane-profile takes one lane: lane-profile <lane>" 64 + check_lane_name "$lane" + log_sync + lane="$(canon_lane "$lane")" || exit 2 # Amendment 15 + lp_out="$(lane_payload_field "$lane" profile)"; lp_rc=$? + case "$lp_rc" in + 0) : ;; + 8) exit 8 ;; + *) die "lane-profile could not read lane $lane's log (exit $lp_rc). That is NOT 'this lane's record names no profile', and a wrong profile is a launch into another account (Amendment 7(d))." 1 ;; + esac + [ -n "$lp_out" ] || exit 8 + printf '%s\n' "$lp_out" + ;; + + # ------------------------------------------- AMENDMENT 17(b): the two reads + # + # `lane-agent` and `lane-transcript` are `lane-dir`'s siblings, one sub-field + # along and through the same `lane_payload_field`, so the four cannot disagree + # about which line is a lane's last. ONE CALLER EACH TODAY and that is the + # point of the read existing rather than being inlined: `lane-start` reads the + # agent to know WHICH LAUNCHER to use with no `--agent`, and reads the + # transcript to know the id to append to the row's session cell in that + # agent's own spelling (`Codex <id>`), which is the one id a launch of a + # non-Claude agent has in hand. + # + # 8 IS THE ANSWER FOR EVERY RECORD WRITTEN BEFORE THIS AMENDMENT, and it is + # not a failure: Amendment 7(i) cuts each lane over at its own next handoff, + # nothing is backfilled, and `lane-start`'s default of `claude` carries it + # until then — which is what it has always done. + lane-agent) + lane="${1-}"; [ -n "$lane" ] || die "usage: lane-agent <lane>" 64 + [ "$#" -le 1 ] || die "lane-agent takes one lane: lane-agent <lane>" 64 + check_lane_name "$lane" + log_sync + lane="$(canon_lane "$lane")" || exit 2 # Amendment 15: one name under any case + la_out="$(lane_payload_field "$lane" agent)"; la_rc=$? + case "$la_rc" in + 0) : ;; + 8) exit 8 ;; + *) die "lane-agent could not read lane $lane's log (exit $la_rc). That is NOT 'this lane's record names no agent', and a caller that read it that way would launch the default agent over a lane another one paused (Amendment 7(d))." 1 ;; + esac + [ -n "$la_out" ] || exit 8 + printf '%s\n' "$la_out" + ;; + + lane-transcript) + lane="${1-}"; [ -n "$lane" ] || die "usage: lane-transcript <lane>" 64 + [ "$#" -le 1 ] || die "lane-transcript takes one lane: lane-transcript <lane>" 64 + check_lane_name "$lane" + log_sync + lane="$(canon_lane "$lane")" || exit 2 # Amendment 15: one name under any case + lt_out="$(lane_payload_field "$lane" transcript)"; lt_rc=$? + case "$lt_rc" in + 0) : ;; + 8) exit 8 ;; + *) die "lane-transcript could not read lane $lane's log (exit $lt_rc). That is NOT 'this lane's record names no transcript' (Amendment 7(d))." 1 ;; + esac + [ -n "$lt_out" ] || exit 8 + printf '%s\n' "$lt_out" + ;; + + # AMENDMENT 13(b) — THE DIARY THE CELL USED TO BE, IN THE FILE BUILT TO HOLD + # IT. A lane's `NOTED` and `RULED` lines in order — FILE order, which is the + # order that lane wrote them (R14), and never a sort on the UTC field: two + # workstations share no clock and this one has been measured jumping ±25s. + # `--since` is the one filter, and it compares the two instants after padding + # the register's older minute-precision form to seconds, so a line stamped + # `…T20:31Z` is on the right side of a `--since …T20:30:00Z`. + # + # 8 IS "THIS LANE HAS WRITTEN NO NARRATIVE", which a lane that has never taken + # a note and a lane with no log at all both are; a read that could not be made + # is never 8 (R22) and leaves through the die above it. + # AMENDMENT 13's DIARY, and since AMENDMENT 14 ACROSS LANES TOO. + # + # history <lane> one lane's `NOTED` and `RULED` lines, in + # FILE ORDER — the diary the state cell used + # to be. Unchanged. + # history --all every lane's, as ONE timeline: by UTC, and + # by file and line where two share a minute. + # history --repo <owner/repo> the lanes whose HOME is that repository — + # the `home` of their last `STARTED`/`RESUMED`, + # through the alias table, exactly as `lanes + # --repo` files them — on one timeline. + # --since <UTC> with any of the three. + # --index read the DERIVED INDEX instead of the + # published logs (Amendment 14(b)), only when + # typed: stderr says `read: index (<store>) at + # register@<sha12>; <k> commits behind`, or + # `read: sources (index <why>)` and the + # sources answer. Where the index answers it + # does not fetch: it reads no network at all, + # and the lag is said against this checkout. + # + # `history` over two lanes was refused, exit 64, on 2026-10-05 (Amendment 14, + # "Why" 3); `--all` and `--repo` are that question, and they read the + # SOURCES — the same one pass over every published log `who` makes — with or + # without the flag. + history) + lane=""; hi_since=""; hi_all=0; hi_repo=""; hi_index=0 + hi_usage="history <lane> | --all | --repo <owner/repo> [--since <UTC>] [--index]" + while [ $# -gt 0 ]; do + case "$1" in + --since) hi_since="${2-}"; [ -n "$hi_since" ] || die "--since needs a UTC instant" 64; shift 2 ;; + --since=*) hi_since="${1#--since=}"; [ -n "$hi_since" ] || die "--since needs a UTC instant" 64; shift ;; + --all) hi_all=1; shift ;; + --repo) hi_repo="${2-}"; [ -n "$hi_repo" ] || die "--repo needs a repository ($hi_usage)" 64; shift 2 ;; + --repo=*) hi_repo="${1#--repo=}"; [ -n "$hi_repo" ] || die "--repo needs a repository ($hi_usage)" 64; shift ;; + --index) hi_index=1; shift ;; + --) shift ;; + -*) die "unknown option '$1' for history ($hi_usage)" 64 ;; + *) [ -z "$lane" ] || die "history takes ONE lane, or --all, or --repo <owner/repo>: $hi_usage" 64; lane="$1"; shift ;; + esac + done + hi_sel=0 + [ -n "$lane" ] && hi_sel=$((hi_sel + 1)) + [ "$hi_all" = 1 ] && hi_sel=$((hi_sel + 1)) + [ -n "$hi_repo" ] && hi_sel=$((hi_sel + 1)) + [ "$hi_sel" = 1 ] || die "usage: $hi_usage — ONE of a lane, --all or --repo" 64 + [ -z "$lane" ] || check_lane_name "$lane" + case "$hi_since" in + '') : ;; + [0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]Z | [0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9]Z) : ;; + *) die "--since takes a UTC instant spelled as this log spells it, YYYY-MM-DDTHH:MM[:SS]Z — '$hi_since' is not one" 64 ;; + esac + # THE INDEX FIRST, and where it answers there is no fetch: the read is the + # index's, and a network round trip in front of it is the cost the flag is + # for avoiding. Where it does not answer, the source read below is exactly + # the one this arm always made, the fetch included. + if [ "$hi_index" = 1 ] && index_open; then LANES_NO_FETCH=1; fi + log_sync + if [ -n "$lane" ]; then + lane="$(canon_lane "$lane")" || exit 2 # Amendment 15 + hi_lines=""; hi_rc=0 + hi_lines="$(lane_log_events "$lane")" || hi_rc=$? + case "$hi_rc" in + 0) : ;; + 2) exit 2 ;; + *) die "history could not read lane $lane's log (exit $hi_rc). That is NOT 'this lane has written no narrative' — a read that failed is never an answer (Amendment 7(d))." 1 ;; + esac + hi_out="$(printf '%s\n' "$hi_lines" | awk -F"$US" -v since="$hi_since" ' + function pad(u) { return (length(u) == 17) ? substr(u, 1, 16) ":00Z" : u } + $3 == "NOTED" || $3 == "RULED" { + if (since != "" && pad($1) < pad(since)) next + printf "%-20s %-5s %s%s\n", $1, $3, ($8 != "" ? $8 " — " : ""), $9 + }')" + [ -n "$hi_out" ] || exit 8 + printf '%s\n' "$hi_out" + else + hi_ev="$(state_events)" + # `--repo`: THE LANES WHOSE HOME IS IT, keyed as every other table in + # this file is — the log's own lane, lower-cased — and a home compared + # through the alias table on BOTH sides, so `openRepoTools` and + # `opensoft/openRepoTools` are one repository here as they are to + # `lanes --repo`. A lane with no recorded home is in no repository's. + hi_filter=0; hi_keep="" + if [ -n "$hi_repo" ]; then + hi_filter=1 + hi_want="$(alias_lookup "$hi_repo" 2>/dev/null || :)"; [ -n "$hi_want" ] || hi_want="$hi_repo" + lower_into "$hi_want"; hi_want_lc="$LOWER_OUT" + while IFS="$US" read -r hi_l _hi_disp _hi_v _hi_u _hi_w _hi_d _hi_p _hi_win hi_h _hi_rest; do + [ -n "${hi_l:-}" ] && [ -n "${hi_h:-}" ] || continue + hi_hc="$(alias_lookup "$hi_h" 2>/dev/null || :)"; [ -n "$hi_hc" ] || hi_hc="$hi_h" + lower_into "$hi_hc" + [ "$LOWER_OUT" = "$hi_want_lc" ] && hi_keep="$hi_keep $hi_l" + done <<EOF +$(printf '%s\n' "$hi_ev" | lane_row_facts) +EOF + fi + # ONE TIMELINE: the UTC padded as the single-lane read pads it, then the + # file and the line — the log's own order where two lines share a stamp. + # The key is cut away after the sort; the lane is the LOG's (Amendment + # 16(e): a line's lane is the lane of the file it is in). + hi_out="$(printf '%s\n' "$hi_ev" | awk -F"$US" -v since="$hi_since" -v filter="$hi_filter" -v keep="$hi_keep" ' + function pad(u) { return (length(u) == 17) ? substr(u, 1, 16) ":00Z" : u } + BEGIN { n = split(keep, kk, " "); for (i = 1; i <= n; i++) K[kk[i]] = 1 } + $3 == "NOTED" || $3 == "RULED" { + if (since != "" && pad($1) < pad(since)) next + if (filter == 1 && !(tolower($2) in K)) next + printf "%s\034%s\034%09d\037%-20s %-26s %-5s %s%s\n", pad($1), $10, $11, $1, $2, $3, ($8 != "" ? $8 " — " : ""), $9 + }' | LC_ALL=C sort | awk -v s="$US" '{ i = index($0, s); print substr($0, i + 1) }')" + [ -n "$hi_out" ] || exit 8 + printf '%s\n' "$hi_out" + fi + ;; + + # THE LANE'S LAST LANE-KIND LINE, in FILE ORDER — `<verb><TAB><utc><TAB><session><TAB><payload>`. + # One caller: `lane-handoff --late`, which may only write the record a swap + # never left where that line is still a `STARTED` or a `RESUMED` older than + # the instant the late line claims. This log is APPEND-ONLY and file order is + # what every state read means by "last", so a `PAUSED` appended after the + # relaunch's `RESUMED` would make a lane that is RUNNING read as paused — and + # this read is how that is refused instead of written. + # + # IT IS THE LANE'S OWN LINES AND NOT A FORK'S, which is `lane_row_facts`' rule + # one function along (decision 8(c): a fork is never the lane). + lane-last) + lane="${1-}"; [ -n "$lane" ] || die "usage: lane-last <lane>" 64 + [ "$#" -le 1 ] || die "lane-last takes one lane: lane-last <lane>" 64 + check_lane_name "$lane" + log_sync + lane="$(canon_lane "$lane")" || exit 2 # Amendment 15: one name under any case + ll_lines=""; ll_rc=0 + ll_lines="$(lane_log_events "$lane")" || ll_rc=$? + [ "$ll_rc" = 0 ] || die "lane-last could not read lane $lane's log (exit $ll_rc). That is NOT 'this lane has no lane-kind line' (Amendment 7(d))." 1 + ll_out="$(printf '%s\n' "$ll_lines" | awk -F"$US" -v OFS=' ' ' + $3 == "STARTED" || $3 == "PAUSED" || $3 == "RESUMED" || $3 == "ENDED" || $3 == "RETIRED" { + if (substr($8, 1, 5) == "fork ") next + v = $3; u = $1; s = $4; p = $8 + } + END { if (v != "") print v, u, s, p }')" + [ -n "$ll_out" ] || exit 8 + printf '%s\n' "$ll_out" + ;; + + # THE WORKSPACE REPOSITORY'S PATH — the one resolver, printed. Amendment 9(a) + # is explicit that a second way to find one thing is a second answer, and + # `lane-handoff` needs this path to resolve the handoff cell of a row whose + # spelling is repository-relative. Every other reader of it is in this file. + workspace-root) + [ "$#" = 0 ] || die "workspace-root takes no arguments" 64 + wr_out="$(lanes_workspace_root 2>/dev/null || :)" + [ -n "$wr_out" ] || die "$(lanes_workspace_why)" 1 + printf '%s\n' "$wr_out" + ;; + + # The lane's RESUME TARGET, read robustly (Amendment 11 clause (d) rules 3 + # and 4): the last uuid in the published row's session cell WHATEVER SHAPE + # THAT CELL IS IN, and failing that the session field of the lane's last + # `PAUSED` or `RESUMED` line. Never a title, and never an exit — a caller + # that gets 8 has learnt that no uuid is knowable from either source, which + # is the ONLY state in which Amendment 8(d)'s title fallback is reachable. + last-session) + lane="${1-}"; [ -n "$lane" ] || die "usage: last-session <lane>" 64 + [ "$#" -le 1 ] || die "last-session takes one lane: last-session <lane>" 64 + check_lane_name "$lane" + log_sync + lane="$(canon_lane "$lane")" || exit 2 # Amendment 15 + last_session_of "$lane"; ls_rc=$? + case "$ls_rc" in + 0) : ;; + 8) exit 8 ;; + *) die "last-session could not read the register or the log for $lane (exit $ls_rc)" 1 ;; + esac + ;; + + # DECISION 8(c) AND 8(e) — the live FORKS of this lane's transcript, which + # are a defect to retire and never a holder. Evidence 6: an abandoned launch + # left a `--fork-session` daemon orchestrating the same plan and writing this + # lane's log under an id no row carries. It NAMES them and does nothing else: + # the act is `lane-end <lane> --retire <pid|uuid>` (clause (k) rule (e)), + # printed by the caller and typed by a person, for the reason Amendment 8(f) + # gives — and it writes a record rather than killing anything. + # 0 with rows, 8 with none, 1 where the records could not be read. + forks) + lane="${1-}"; [ -n "$lane" ] || die "usage: forks <lane>" 64 + [ "$#" -le 1 ] || die "forks takes one lane: forks <lane>" 64 + check_lane_name "$lane" + log_sync + lane="$(canon_lane "$lane")" || exit 2 # Amendment 15 + lane_forks "$lane"; fk_rc=$? + case "$fk_rc" in + 0) : ;; + 8) exit 8 ;; + 64) die "usage: forks <lane>" 64 ;; + *) die "could not read this workstation's session records for lane $lane: ${SESSION_FILES_ERR:-unknown error}. That is NOT 'no fork of it is live'." 1 ;; + esac + ;; + + # ISSUE #39 — a live `--fork-session` DUPLICATE of this lane's OWN + # transcript, found in the process table rather than in a session record's + # `sessionId` field (which is exactly why `forks` cannot see it once the id + # is bound to the row: `lane-end <lane> --retire <pid>` is the caller, for a + # duplicate `lane_forks` was designed to stay silent about). + # 0 with rows, 8 with none, 1 where `pgrep` is missing, or the register or + # the records could not be read. + duplicate-holder) + lane="${1-}"; [ -n "$lane" ] || die "usage: duplicate-holder <lane>" 64 + [ "$#" -le 1 ] || die "duplicate-holder takes one lane: duplicate-holder <lane>" 64 + check_lane_name "$lane" + log_sync + lane="$(canon_lane "$lane")" || exit 2 # Amendment 15 + duplicate_holder_pids "$lane"; dh_rc=$? + case "$dh_rc" in + 0) : ;; + 8) exit 8 ;; + 64) die "usage: duplicate-holder <lane>" 64 ;; + *) die "could not read the register, this workstation's process table or its session records for lane $lane: ${SESSION_FILES_ERR:-unknown error}. That is NOT 'no duplicate holder is live'." 1 ;; + esac + ;; + + # DECISION 8(d) — THE WORKSTATION'S NAME, AND WHERE IT CAME FROM. One + # implementation, so `restart`, `lanes` and every other caller name the + # workstation the same way the register's own writer does rather than each + # running `hostname` and disagreeing with it. Prints `<name><TAB><source>`, + # where the source is one of the THREE `lanes_workstation_pair` emits — + # `seam`, `hostname` or `container-unset` (`:371-383`) — and on that last one + # the sentence that says what to export goes to stderr, because a read must + # still answer. + # + # THE TWO NAMES THAT WERE HERE DO NOT EXIST. `config` and + # `hostname-in-container` are the vocabulary of the rung `R-A11-14` REMOVED: + # a `workstation:` key in `workspace.yaml`, refused as a second place for the + # truth to be wrong beside the variable the launcher already sets (`:337-339`). + # `lanes:190` matched the second of them and could therefore never print, which + # is how a dead branch went unnoticed (F-X1). SPEC rev 6's §11 row still lists + # all four; that is the text's to correct, and the code's own emitters are the + # authority for this comment. + # Always 0: a workstation name that could refuse would be a refusal in front + # of every launch on this machine. + # THE WORKSTATION'S NAME AND ITS SOURCE — and, since Amendment 18(a), the + # THREE FACTS BENEATH IT and theirs. Eight tab-separated fields: + # + # <workstation> <source> <host> <source> <os> <source> <container> <source> + # + # GROWN AT THE END, which is this file's rule for every read that gains a + # field (`swapped_lanes`'s sixth and seventh say why): the FIRST TWO are the + # contract `lanes`, `lane` and `lane-handoff` already take with `cut -f1` and + # `cut -f2`, and a reader that has never heard of the rest is unaffected by + # them. Each source is one of `seam` (the launcher exported it), `hostname` + # (probed), `workstation` (a container with no export, writing the Rule 10 + # name for its host), `kernel` (the `uname`/`/proc/version` probe) or + # `outside` (no container). The workstation's own refusal sentence is printed + # on stderr exactly as before, and this read still ANSWERS: a read in front of + # every launch may not refuse. + workstation) + [ "$#" -eq 0 ] || die "workstation takes no arguments" 64 + ws_why="$(lanes_workstation_why "$WS_SOURCE")" + [ -n "$ws_why" ] && note "$ws_why" + printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' \ + "$WS" "$WS_SOURCE" \ + "$LANES_HOST_NAME" "$LANES_HOST_SOURCE" \ + "$LANES_OS_NAME" "$LANES_OS_SOURCE" \ + "$LANES_CONTAINER_NAME" "$LANES_CONTAINER_SOURCE" + ;; + + # HOW OLD THE CHECKOUT'S ANSWER IS (`R-A8-1`'s rule, given its own read). + # `.git/FETCH_HEAD` is rewritten by every fetch and by nothing else, so its + # mtime is when this checkout last heard from `origin` — and a listing that + # says "4d ago" is a listing a reader knows not to trust about another + # workstation's lane. Never a network call and never a failure: an unreadable + # one answers `unknown`. Always 0. + fetch-age) + [ "$#" -eq 0 ] || die "fetch-age takes no arguments" 64 + fetch_age + ;; + + # DECISIONS 6 AND 7 — THE LANE LISTING, as data. `lanes` renders the + # estate-wide one and `restart` the per-repo one from these same rows, which + # is why the filter is an argument rather than three implementations. + # 0 with rows, 8 with none, 64 a usage error of its own. + lanes) + lns_args=(); lns_fetch=0; lns_index=0 + while [ $# -gt 0 ]; do + case "$1" in + --repo|--dir|--ws|--lane|--prefix) [ -n "${2-}" ] || die "$1 needs a value (usage: lanes [--repo <owner/repo>] [--dir <path>] [--prefix <repo>] [--ws <workstation>] [--lane <lane>] [--here] [--all] [--closed] [--fetch] [--index])" 64 + lns_args+=("$1" "$2"); shift 2 ;; + --all|--here|--closed) lns_args+=("$1"); shift ;; + --fetch) lns_fetch=1; shift ;; + # AMENDMENT 14(b) — THE DERIVED INDEX, ONLY WHEN TYPED. It replaces the + # PUBLISHED reads of the register and the logs and nothing else; the + # live session records, tmux and this checkout's own files are read + # exactly as they are without it, so the rows are the same rows. + --index) lns_index=1; shift ;; + --) shift ;; + *) die "unknown argument '$1' for lanes (usage: lanes [--repo <owner/repo>] [--dir <path>] [--prefix <repo>] [--ws <workstation>] [--here] [--all] [--closed] [--fetch] [--index])" 64 ;; + esac + done + # THE ONE READ IN THIS FILE WHOSE DEFAULT IS LOCAL (SPEC rev 4 §15). Every + # other read here sits in front of a LAUNCH, where a stale answer binds the + # wrong lane; this one sits in front of a PERSON, who is waiting on it. So + # `LANES_NO_FETCH=1` is its default rather than an override — still honoured + # where it is already set — and `--fetch` is how a caller asks for the + # network. `fetch-age` is the read beside it, so a listing can say how old + # its answer is, exactly as Amendment 8(e)'s hook does under `R-A8-1`. + [ "$lns_fetch" = 1 ] || LANES_NO_FETCH=1 + log_sync + # A FETCH THAT DID NOT HAPPEN IS NOT A FETCH, AND IT IS SAID IN THE ONE + # PHRASE THE CALLER ALREADY READS (#26, `lanes:411`). `log_sync` leaves four + # ways out of itself that never reach the fetch and were silent on all four; + # `lanes --fetch` matches its stderr for *"reading the logs as they stand + # locally"* and prints *"as of a fetch just now"* where it does not find it. + # So the phrase is the helper's, once, and the reason is named beside it. + # + # ONLY UNDER `--fetch`. Without it this read's default is LOCAL by design + # (SPEC rev 4 §15) and the notice would be a line saying it did what it was + # asked — which is why the wrapper renders the fetch path's stderr and not + # the local path's. + if [ "$lns_fetch" = 1 ] && [ "$LOG_SYNC_FETCH" != yes ] && [ "$LOG_SYNC_FETCH" != fell-back ]; then + note "--fetch was asked for and NO FETCH WAS MADE: $LOG_SYNC_FETCH — reading the logs as they stand locally" + fi + # AFTER the fetch, so `<k> commits behind` is counted against the + # `origin/<branch>` this run has just brought up to date where it asked to. + if [ "$lns_index" = 1 ]; then index_open || :; fi + # AMENDMENT 15 — `--lane <name>` IS A `<lane>` ARGUMENT AND GOES THROUGH THE + # RESOLVER. The filter inside `lanes_rows` has always joined on the name + # lower-cased, so the ROWS came back either way; what a typed spelling used + # to do was put itself in column 1 and in column 10's `lane <name>` line. + # `${lns_args[@]+"${lns_args[@]}"}` AND NOT `${#lns_args[@]}` OR AN INDEX: + # this file is parsed under macOS bash 3.2 in CI, where an EMPTY array under + # `set -u` is the expansion this idiom exists for — it is the same one the + # `lanes_rows` call below already uses, and a bare `lanes` with no flags is + # exactly the empty case. The rebuild also stops assuming the value sits at + # `i + 1`; it takes the word AFTER `--lane`, which is what the parser above + # guarantees there is one of. + # `--all` IS ABSOLUTE AND IT CLEARS `--lane` (the reset inside `lanes_rows` + # says so in terms), so a `--lane` it is about to throw away must not be + # resolved — and must not REFUSE. `lanes --all --lane <the 15(d) pair>` is + # the every-lane listing, in either flag order, and exiting 2 on a selector + # this run ignores would hide every lane for a name nothing was asked about + # (Copilot round 1 on openRepoTools#41). + lns_all=0 + for lns_a in ${lns_args[@]+"${lns_args[@]}"}; do + case "$lns_a" in --all) lns_all=1 ;; esac + done + lns_new=(); lns_take=0 + for lns_a in ${lns_args[@]+"${lns_args[@]}"}; do + if [ "$lns_take" = 1 ]; then + lns_take=0 + if [ "$lns_all" = 0 ]; then + lns_one="$(canon_lane "$lns_a")" || exit 2 + else + lns_one="$lns_a" + fi + lns_new+=("$lns_one") + continue + fi + case "$lns_a" in --lane) lns_take=1 ;; esac + lns_new+=("$lns_a") + done + lns_args=(${lns_new[@]+"${lns_new[@]}"}) + lns_out="$(lanes_rows ${lns_args[@]+"${lns_args[@]}"})"; lns_rc=$? + case "$lns_rc" in + 0) : ;; + 8) exit 8 ;; + 64) die "usage: lanes [--repo <owner/repo>] [--dir <path>] [--prefix <repo>] [--ws <workstation>] [--here] [--all] [--closed] [--fetch] [--index]" 64 ;; + *) die "the lane listing could not be read (exit $lns_rc)" 1 ;; + esac + [ -n "$lns_out" ] || exit 8 + printf '%s\n' "$lns_out" + ;; + + # AMENDMENT 18 ADDENDUM 1 — THE PICK'S TWO READS, over the rows the `lanes` + # arm above has just printed. Both take those rows on STDIN and neither reads + # the register: the caller has paid for that read and a second one would + # double the cost of every pick. `lane` is the only caller of the first and + # `lane` and `lanes` are both callers of the second, which is the point — two + # surfaces computing one partition, or one next free position, is how they + # come to disagree. + # 0 with the answer · 64 a usage error of its own. + lane-groups) + [ "$#" -le 1 ] || die "lane-groups takes one optional workstation: lane-groups [<workstation>] (the rows on stdin)" 64 + lane_groups "${1-}" + ;; + + next-free) + [ -n "${1-}" ] || die "usage: next-free <repo> (the rows on stdin)" 64 + [ "$#" -le 1 ] || die "next-free takes one repository: next-free <repo> (the rows on stdin)" 64 + lane_next_free "$1" + ;; + + # AMENDMENT 8 — Rule 1's sibling reads, filtered to lines that NAME the + # object. `gh_reads` pipes both of its searches through this; it is a + # subcommand so that the filter can be held to account directly, and so a + # person can run a search of their own through the same test. + sibling-filter) + sfsub=""; sfsub_mode=pr + while [ $# -gt 0 ]; do + case "$1" in + --branch) sfsub_mode=branch; shift ;; + --pr) sfsub_mode=pr; shift ;; + --) shift ;; + -*) die "unknown option '$1' for sibling-filter" 2 ;; + *) [ -z "$sfsub" ] || die "sibling-filter takes one object" 2; sfsub="$1"; shift ;; + esac + done + [ -n "$sfsub" ] || die "usage: sibling-filter <object> [--branch] (candidate lines on stdin)" 2 + sfsub_home="$(resolve_home "${LANES_LANE:-}" "" 2>/dev/null || :)" + sfsub_obj="$(canon_object "$sfsub" "$sfsub_home")" || exit 2 + sibling_filter "$sfsub_obj" "$sfsub_mode" + ;; + + # R20 — a lane's HOME goes through `repos.tsv` like every other spelling, and + # `lane-start` has no alias table of its own. 0 with the canonical + # nameWithOwner, 8 when the table has no row for it (the caller records the + # spelling it derived, and warns), 2 when the table maps it to something that + # is not owner/repo. + resolve-repo) + rr="${1-}"; [ -n "$rr" ] || die "usage: resolve-repo <owner/repo|alias>" 2 + rr_c="$(alias_lookup "$rr" 2>/dev/null || :)" + [ -n "$rr_c" ] || { printf '%s\n' "$rr"; exit 8; } + valid_nwo "$rr_c" || die "the alias table maps '$rr' to '$rr_c', which is not owner/repo" 2 + printf '%s\n' "$rr_c" + ;; + + lane-objects) + lane="${1-}"; [ -n "$lane" ] || die "usage: lane-objects <lane>" 2 + log_sync + lane="$(canon_lane "$lane")" || exit 2 # Amendment 15 + lane_objects "$lane" || exit $? + ;; + + # The lane's ROW as it has LANDED — fetched, and read from + # `origin/<branch>:lanes/LANES.md` like every other state read (R19). 0 with + # the row, 8 when the published register has none. `lane-end`'s pre-cutover + # fallback and `lane-start`'s "is this lane new" test both used to read the + # working tree, which a fetch does not move: a peer's LANDING appended to the + # state cell, or a peer's whole row, was invisible to both, so `lane-end` + # wrote NOTHING IN FLIGHT over a live merge hold and `lane-start` added a + # SECOND row for a lane that already had one — and two rows is a register no + # helper can edit (`row_line` requires exactly one). + register-row) + lane="${1-}"; [ -n "$lane" ] || die "usage: register-row <lane>" 2 + check_lane_name "$lane" + log_sync + lane="$(canon_lane "$lane")" || exit 2 # Amendment 15 + rr_row="$(row_of_lane "$lane")" + [ -n "$rr_row" ] || exit 8 + printf '%s\n' "$rr_row" + ;; + + # This checkout's row can be ahead of origin after a local transcript stamp. + # The live attach checks both copies; an unreadable local row is not absence. + register-row-local) + lane="${1-}"; [ -n "$lane" ] || die "usage: register-row-local <lane>" 2 + check_lane_name "$lane" + rr_row="$(row_of_lane_local "$lane")" || die "could not read local register row for $lane" 1 + [ -n "$rr_row" ] || exit 8 + case "$rr_row" in *$'\n'*) die "more than one local row names $lane" 2 ;; esac + printf '%s\n' "$rr_row" + ;; + + # 0 with archived spellings, 8 absent, 1 when either archive cannot be read + # or carries a line that is not a row (#122, named above the refusal). + retired-identity) + lane="${1-}"; [ -n "$lane" ] || die "usage: retired-identity <lane>" 2 + check_lane_name "$lane" + log_sync + rr_hits="$(retired_identity_hits "$lane")" || die "could not read the lane archive, or it carries a line that is not a row (above)" 1 + [ -n "$rr_hits" ] || exit 8 + printf '%s\n' "$rr_hits" + ;; + + # R-A11-7 — THE HOOK'S OWN uuid → lane READ, EXPOSED. `lane_of_session` has + # answered "which lane's row's SESSION CELL names this uuid" since Amendment + # 8(e), for a window that carries no lane name; nothing else could reach it. + # `lane-start` step 3b needs the same answer to keep R-A11-1's fence — a live + # session that belongs to ANOTHER row is never taken — so it is one read with + # two callers rather than a second implementation of the same question. + # + # ONLY the session cell is read, exactly as the hook reads it: state cells + # quote other lanes' ids all the time (`RESUMED by <id>`, `handed off to + # <id>`), and one of those is not that session's lane. + # + # Read-only. 0 with the lane, 8 when no row's session cell names it — + # Amendment 7(d)'s fail-closed convention, so a caller can tell *none* from + # *could not read* — and 64 on a usage error of its own. + # + # 64 AND NOT 2 (A11 Addendum 4 ruling 1, ratified "a11 addendum 4 yes"). + # Adoption act 0 wrote this read with a usage `2` (`3719d97:lanes/lanes-edit.sh`) + # and SPEC rev 6 §11 recorded the landed code; clause (h)'s own table said + # `64 usage` for every read in it, and the contract contradicted itself. The + # ruling settles it the other way: *"`session-lane`'s usage code is 64 like + # every other read in clause (h); adoption act 0 item (4), which says 2, is + # the line corrected."* + # + # IT MATTERS BECAUSE `2` HERE ALREADY MEANS SOMETHING ELSE. A helper that has + # never heard of `session-lane` exits 2 from the `*)` arm, and that is what + # every workstation answers until act 3's install reaches it. A caller that + # cannot tell that 2 from a usage 2 cannot tell *"install the helper"* from + # *"fix your call"* — and both of `session-lane`'s callers fail CLOSED on + # anything but 0 or 8, so the distinction is the whole of what they can report. + session-lane) + sl_id="${1-}"; [ -n "$sl_id" ] || die "usage: session-lane <transcript-uuid>" 64 + [ "$#" -le 1 ] || die "session-lane takes one transcript uuid: session-lane <transcript-uuid>" 64 + log_sync + sl_lane="$(lane_of_session "$sl_id")" + [ -n "$sl_lane" ] || exit 8 + printf '%s\n' "$sl_lane" + ;; + + # AMENDMENT 15 — THE RESOLVER, EXPOSED, because `lane-start`, `lane-end`, + # `lanes` and `restart` all take a `<lane>` argument and the amendment gives + # them all the SAME resolver. An implementation of "which row is this name's" + # in each command is how they would come to disagree about it — which is the + # whole reason clause (h) turned `window-lane` and `session-lane` into + # subcommands. + # + # Read-only, out of `origin/<branch>` like every other state read (R19). + # 0 the canonical spelling — the row's own where a row matches ignoring + # case, and the TYPED spelling where none does, because a lane with no + # row is a lane `add-row` is about to create and the typed name is all + # there is. + # 2 the refusal: two or more rows differ only by case (15(d)). It is 2 and + # not 8 because it is a REFUSAL and not an absence — and `lane-start` + # already spends 2 on exactly this fact for two rows of one spelling. + # 64 a usage error of its own, as every read in clause (h)'s table does. + # A caller that meets 2 from a helper predating this amendment is meeting the + # `*)` arm's unknown-subcommand 2, told apart by the helper's own WORDS as + # every other read here is; the four callers fall through to the typed + # spelling there, and each has its own refusal for a register that really does + # hold two such rows. + canon-lane) + cl_in="${1-}"; [ -n "$cl_in" ] || die "usage: canon-lane <lane>" 64 + [ "$#" -le 1 ] || die "canon-lane takes one lane: canon-lane <lane>" 64 + check_lane_name "$cl_in" + log_sync + # THE CODE IS CARRIED, not flattened to 2: 66 is the alias table that could + # not be read and its four callers tell it from 2 by that number alone. + cl_res="$(canon_lane "$cl_in")" || exit $? + printf '%s\n' "$cl_res" + ;; + + # `--home`'s validation, WITHOUT a write — the same `resolve_home` the writers + # call, so a preflight and the write can never disagree. 0 with the canonical + # home, 8 when the lane has none and none was given, 2 when the option is + # refused (the lane's log already records its home) or is not owner/repo. + # `lane-end` forwards `--home` to its own ENDED line, which is written AFTER + # the row has been closed: without this the refusal arrived too late to + # refuse anything, and left a closed row with no ENDED line behind it. + resolve-home) + lane="${1-}"; [ -n "$lane" ] || die "usage: resolve-home <lane> [<owner/repo|alias>]" 2 + check_lane_name "$lane" + log_sync + lane="$(canon_lane "$lane")" || exit 2 # Amendment 15 + rh_out="$(resolve_home "$lane" "${2-}")" || exit $? + [ -n "$rh_out" ] || exit 8 + printf '%s\n' "$rh_out" + ;; + + # ---------- openRepoTools#94: the restart intent the supervisor launches from + # + # BOTH ANSWER OUT OF THE LOCAL CONTROL ROOT. The writer reads the register's + # managed-ownership projection before mutation; neither writes the register, + # the object log or reaches the network. The WRITER is deliberately absent from the + # dispatcher's workstation guard above — `R-A11-14` is about a record FILED + # UNDER A WORKSTATION, and this one is filed under nothing and never leaves + # the machine that wrote it — and it takes the same 64-for-usage contract + # every read Amendment 11 added takes, because it sits in front of a launch + # exactly as those do. + # + # 0 done + # 1 no control root could be derived, or it could not be written + # 2 a refusal of the arguments + # 7 THE FENCE DID NOT MATCH — another act got there first, which is what + # this file already spends 7 on (`claim`'s CLAIM-LOST, `set-lane-state`). + # Nothing was written and the current intent is printed. + # 8 there is no intent for this lane + # 64 a usage error of this subcommand's own + + restart-intent) + lane="${1-}"; [ -n "$lane" ] || die "usage: restart-intent <lane> [--dir <absolute checkout>]" 64 + shift; lri_dir="" + if [ "$#" -gt 0 ]; then + [ "$#" = 2 ] && [ "$1" = --dir ] || die "usage: restart-intent <lane> [--dir <absolute checkout>]" 64 + case "$2" in /*) lri_dir="$2" ;; *) die "--dir takes an absolute checkout" 64 ;; esac + fi + check_lane_name "$lane" + log_sync + lane="$(canon_lane "$lane")" || exit 2 # Amendment 15 + lri_out=""; lri_rc=0 + lri_out="$(lane_restart_read "$lane" "$lri_dir")" || lri_rc=$? + case "$lri_rc" in + 0) : ;; + 8) exit 8 ;; + *) die "lane $lane has no lifecycle control root, so it can carry no restart intent: its record names no directory (Amendment 11(c)) and \$PROJECTS_ROOT is not a directory here. That is NOT 'this lane has no restart in flight' — a read that could not be made is never an answer (Amendment 7(d))." 1 ;; + esac + printf '%s\n' "$lri_out" + ;; + + publish-handoff) + lane="${1-}"; pbh_target="${2-}"; pbh_source="${3-}" + [ "$#" -ge 3 ] || die "usage: publish-handoff <lane> <target> <prepared-file> --expect-digest <sha> [--operation <id> --generation <n> --attempt <n> --state <state> --transcript <id>]" 64 + shift 3; check_lane_name "$lane"; lane="$(canon_lane "$lane")" || exit 2 + pbh_digest=""; pbh_op=""; pbh_gen=""; pbh_attempt=""; pbh_state=""; pbh_sid="" + while [ "$#" -gt 0 ]; do + [ "$#" -ge 2 ] && [ -n "${2-}" ] || die "$1 needs a value" 64 + case "$1" in + --expect-digest) pbh_digest="$2" ;; + --operation) pbh_op="$2" ;; + --generation) pbh_gen="$2" ;; + --attempt) pbh_attempt="$2" ;; + --state) pbh_state="$2" ;; + --transcript) pbh_sid="$2" ;; + *) die "unknown publish-handoff flag $1" 64 ;; + esac + shift 2 + done + [ "${#pbh_digest}" = 64 ] || die "publication requires the complete prior SHA-256" 64 + case "$pbh_digest" in *[!0-9a-fA-F]*) die "publication requires SHA-256" 64 ;; esac + [ -f "$pbh_source" ] && [ -r "$pbh_source" ] && [ -s "$pbh_source" ] || die "the prepared handoff is unreadable or empty" 1 + acquire_lock + managed_seam_refuse "$lane" "publish-handoff" + pbh_links=0 + while [ -L "$pbh_target" ]; do + pbh_links=$((pbh_links+1)); [ "$pbh_links" -lt 40 ] || die "the handoff link chain cannot be resolved" 2 + pbh_link="$(readlink "$pbh_target")" || die "the handoff link could not be read" 1 + case "$pbh_link" in /*) pbh_target="$pbh_link" ;; *) pbh_target="$(dirname -- "$pbh_target")/$pbh_link" ;; esac + done + pbh_parent="$( CDPATH=''; cd -P -- "$(dirname -- "$pbh_target")" && pwd -P )" || die "the handoff parent is missing" 1 + pbh_target="$pbh_parent/$(basename -- "$pbh_target")" + [ -f "$pbh_target" ] && [ -r "$pbh_target" ] || die "the handoff target is unreadable" 1 + pbh_irc=0; pbh_intent="$(lane_restart_read "$lane")" || pbh_irc=$? + case "$pbh_irc" in 0|8) : ;; *) release_lock; die "restart ownership could not be read; no handoff was published" 1 ;; esac + pbh_current="$(printf '%s\n' "$pbh_intent" | awk -F'\t' '$1=="state" {print $2; exit}')" + case "$pbh_current" in UNKNOWN-*|INCOMPLETE) release_lock; die "restart ownership is malformed; no handoff was published" 2 ;; esac + if [ -n "$pbh_op" ]; then + [ -n "$pbh_gen" ] && [ -n "$pbh_attempt" ] && [ -n "$pbh_state" ] && [ -n "$pbh_sid" ] || { release_lock; die "operation publication needs generation, attempt, state and transcript fences" 64; } + pbh_actual="$(printf '%s\n' "$pbh_intent" | awk -F'\t' ' + $1=="operation" {o=$2} $1=="generation" {g=$2} $1=="attempt" {a=$2} $1=="state" {s=$2} $1=="new_transcript" {t=$2} + END {printf "%s|%s|%s|%s|%s",o,g,a,s,t}')" + [ "$pbh_actual" = "$pbh_op|$pbh_gen|$pbh_attempt|$pbh_state|$pbh_sid" ] || { release_lock; die "this handoff publisher lost restart ownership; nothing was published" 7; } + pbh_bound="$(printf '%s\n' "$pbh_intent" | awk -F'\t' '$1=="handoff" {print $2; exit}')" + [ -n "$pbh_bound" ] && [ "$pbh_bound" != none ] && [ "$pbh_bound" -ef "$pbh_target" ] || + { release_lock; die "the publication target is not the operation-bound handoff; nothing was published" 2; } + else + case "$pbh_current" in preparing|pending|starting) release_lock; die "an active restart owns this handoff; nothing was published" 7 ;; esac + fi + [ "$(lane_handoff_digest "$pbh_target")" = "$pbh_digest" ] || { release_lock; die "the handoff changed before publication; nothing was published" 7; } + pbh_tmp="$(mktemp "$pbh_target.resume.XXXXXX")" || { release_lock; die "the publication temporary file could not be made" 1; } + if ! cp -p -- "$pbh_target" "$pbh_tmp" || ! cat -- "$pbh_source" > "$pbh_tmp" || ! mv -f -- "$pbh_tmp" "$pbh_target"; then + rm -f -- "$pbh_tmp"; release_lock; die "the handoff could not be published atomically" 1 + fi + release_lock + printf '%s\n' "$pbh_target" + ;; + + legacy-restart-check) + lane="${1-}"; check_lane_name "$lane" + lane="$(canon_lane "$lane")" || exit 2 + managed_seam_refuse "$lane" "legacy-restart-check" + # Use the managed service's affirmative read when that installation exists. + # Exit 8 means confirmed absence; every unknown/error answer refuses. + lrc_managed="${SELF%/*}/lane-managed" + if [ -e "$lrc_managed" ] || [ -L "$lrc_managed" ]; then + [ -f "$lrc_managed" ] && [ -r "$lrc_managed" ] && [ -x "$lrc_managed" ] || + die "the installed managed ownership reader is unusable. Legacy restart refuses without writing or launching." 1 + lrc_rc=0 + LANES_NO_FETCH=1 "$lrc_managed" legacy-check --lane "$lane" >/dev/null || lrc_rc=$? + case "$lrc_rc" in + 8) exit 0 ;; + 0) die "lane $lane is managed. Legacy /ctx restart refuses; use the managed service. Its JSON ledger is the sole authority." 2 ;; + *) die "managed ownership for lane $lane could not be confirmed. Legacy restart refuses without writing or launching." 1 ;; + esac + fi + # A missing executable cannot mean missing enrollment. Probe only the + # private workspace's Git common directory, never this code checkout. + lrc_common="$(git -C "$LANES_REPO" rev-parse --git-common-dir)" || + die "the workspace Git common directory could not be read. Legacy restart refuses." 1 + case "$lrc_common" in /*) : ;; *) lrc_common="$LANES_REPO/$lrc_common" ;; esac + lrc_root="$lrc_common/openrepotools-managed" + if [ -e "$lrc_root" ] || [ -L "$lrc_root" ]; then + [ -d "$lrc_root" ] && [ -r "$lrc_root" ] && [ -x "$lrc_root" ] && [ ! -L "$lrc_root" ] || + die "managed ownership storage is unreadable or unsafe. Legacy restart refuses." 1 + lrc_key="$(lc "$lane")" + for lrc_host in "$lrc_root"/*; do + [ -e "$lrc_host" ] || [ -L "$lrc_host" ] || continue + [ -d "$lrc_host" ] && [ -r "$lrc_host" ] && [ -x "$lrc_host" ] && [ ! -L "$lrc_host" ] || + die "managed host ownership storage is unreadable or unsafe. Legacy restart refuses." 1 + if [ -e "$lrc_host/$lrc_key" ] || [ -L "$lrc_host/$lrc_key" ]; then + die "lane $lane has managed ownership storage. Legacy /ctx restart refuses; install/use its managed service to read the JSON authority." 2 + fi + done + fi + ;; + + set-restart-intent) + lane="${1-}"; [ -n "$lane" ] || die "usage: set-restart-intent <lane> <preparing|pending|starting|failed|ready> [--expect <STATE[|STATE…]|none>] [--expect-generation <n>] [--expect-operation <id>] [--operation <id>] [--generation <n>] [--mode <word>] [--agent <name>] [--profile <name>] [--dir <path>] [--pane <ref>] [--window <ref>] [--handoff <path>] [--digest <sha|none>] [--old-transcript <id>] [--new-transcript <id>] [--attempt <n>] [--bump-attempt] [--reason <text>]" 64 + shift + sri_state="${1-}"; [ -n "$sri_state" ] || die "set-restart-intent needs the state to move to: preparing, pending, starting, failed or ready" 64 + shift + sri_exp=""; sri_expg=""; sri_expo=""; sri_expa=""; sri_expn=""; sri_op=""; sri_gen=""; sri_mode="" + sri_agent=""; sri_prof=""; sri_dir=""; sri_pane=""; sri_win=""; sri_hf="" + sri_dig=""; sri_prepared=""; sri_old=""; sri_new=""; sri_att=""; sri_bump=0; sri_reason="" + # THE TWO SPELLINGS OF ONE FLAG GIVE ONE ANSWER (#26, the review of + # `c3ebcfe`, and `lane-start` carries the same paragraph at its own + # arguments). `--flag ""` refused an empty value here and `--flag=` took + # one, so the `=` spelling of an empty operation, generation, attempt or + # expectation read as ABSENT — and every rung below the flag then ran on a + # value the operator DID give: an `--expect=` would have fenced on nothing, + # an `--expect-operation=` would have claimed an operation it was not + # entitled to. The six that refuse an empty value refuse it in both + # spellings; the ones below that take `[ "$#" -ge 2 ]` deliberately ACCEPT + # an empty value in both, because `none` is an answer for those fields. + while [ $# -gt 0 ]; do + case "$1" in + --expect) sri_exp="${2-}"; [ -n "$sri_exp" ] || die "--expect needs a state word, 'none', or a '|'-separated set of them" 64; shift 2 ;; + --expect=*) sri_exp="${1#--expect=}"; [ -n "$sri_exp" ] || die "--expect needs a state word, 'none', or a '|'-separated set of them" 64; shift ;; + --expect-generation) sri_expg="${2-}"; [ -n "$sri_expg" ] || die "--expect-generation needs a number" 64; shift 2 ;; + --expect-generation=*) sri_expg="${1#--expect-generation=}"; [ -n "$sri_expg" ] || die "--expect-generation needs a number" 64; shift ;; + --expect-attempt) sri_expa="${2-}"; [ -n "$sri_expa" ] || die "--expect-attempt needs a number" 64; shift 2 ;; + --expect-attempt=*) sri_expa="${1#--expect-attempt=}"; [ -n "$sri_expa" ] || die "--expect-attempt needs a number" 64; shift ;; + --prepared-digest) sri_prepared="${2-}"; [ -n "$sri_prepared" ] || die "--prepared-digest needs a checksum" 64; shift 2 ;; + --prepared-digest=*) sri_prepared="${1#--prepared-digest=}"; [ -n "$sri_prepared" ] || die "--prepared-digest needs a checksum" 64; shift ;; + --expect-new-transcript) sri_expn="${2-}"; [ -n "$sri_expn" ] || die "--expect-new-transcript needs an id or none" 64; shift 2 ;; + --expect-new-transcript=*) sri_expn="${1#--expect-new-transcript=}"; [ -n "$sri_expn" ] || die "--expect-new-transcript needs an id or none" 64; shift ;; + --expect-operation) sri_expo="${2-}"; [ -n "$sri_expo" ] || die "--expect-operation needs an operation id" 64; shift 2 ;; + --expect-operation=*) sri_expo="${1#--expect-operation=}"; [ -n "$sri_expo" ] || die "--expect-operation needs an operation id" 64; shift ;; + --operation) sri_op="${2-}"; [ -n "$sri_op" ] || die "--operation needs an operation id" 64; shift 2 ;; + --operation=*) sri_op="${1#--operation=}"; [ -n "$sri_op" ] || die "--operation needs an operation id" 64; shift ;; + --generation) sri_gen="${2-}"; [ -n "$sri_gen" ] || die "--generation needs a number" 64; shift 2 ;; + --generation=*) sri_gen="${1#--generation=}"; [ -n "$sri_gen" ] || die "--generation needs a number" 64; shift ;; + --mode) sri_mode="${2-}"; [ "$#" -ge 2 ] || die "--mode needs a value" 64; shift 2 ;; + --mode=*) sri_mode="${1#--mode=}"; shift ;; + --agent) sri_agent="${2-}"; [ "$#" -ge 2 ] || die "--agent needs a value" 64; shift 2 ;; + --agent=*) sri_agent="${1#--agent=}"; shift ;; + --profile) sri_prof="${2-}"; [ "$#" -ge 2 ] || die "--profile needs a value" 64; shift 2 ;; + --profile=*) sri_prof="${1#--profile=}"; shift ;; + --dir) sri_dir="${2-}"; [ "$#" -ge 2 ] || die "--dir needs a value" 64; shift 2 ;; + --dir=*) sri_dir="${1#--dir=}"; shift ;; + --pane) sri_pane="${2-}"; [ "$#" -ge 2 ] || die "--pane needs a value" 64; shift 2 ;; + --pane=*) sri_pane="${1#--pane=}"; shift ;; + --window) sri_win="${2-}"; [ "$#" -ge 2 ] || die "--window needs a value" 64; shift 2 ;; + --window=*) sri_win="${1#--window=}"; shift ;; + --handoff) sri_hf="${2-}"; [ "$#" -ge 2 ] || die "--handoff needs a value" 64; shift 2 ;; + --handoff=*) sri_hf="${1#--handoff=}"; shift ;; + --digest) sri_dig="${2-}"; [ "$#" -ge 2 ] || die "--digest needs a value" 64; shift 2 ;; + --digest=*) sri_dig="${1#--digest=}"; shift ;; + --old-transcript) sri_old="${2-}"; [ "$#" -ge 2 ] || die "--old-transcript needs a value" 64; shift 2 ;; + --old-transcript=*) sri_old="${1#--old-transcript=}"; shift ;; + --new-transcript) sri_new="${2-}"; [ "$#" -ge 2 ] || die "--new-transcript needs a value" 64; shift 2 ;; + --new-transcript=*) sri_new="${1#--new-transcript=}"; shift ;; + --attempt) sri_att="${2-}"; [ -n "$sri_att" ] || die "--attempt needs a number" 64; shift 2 ;; + --attempt=*) sri_att="${1#--attempt=}"; [ -n "$sri_att" ] || die "--attempt needs a number" 64; shift ;; + --bump-attempt) sri_bump=1; shift ;; + --reason) sri_reason="${2-}"; [ "$#" -ge 2 ] || die "--reason needs a value" 64; shift 2 ;; + --reason=*) sri_reason="${1#--reason=}"; shift ;; + --) shift ;; + *) die "unknown option '$1' for set-restart-intent" 64 ;; + esac + done + lane_restart_word_ok "$sri_state" || + die "'$sri_state' is not a restart-intent state: preparing, pending, starting, failed and ready are the supported states" 64 + # THE FOUR VALUES THAT ARE KEYS AND NOT PROSE. An operation id, a launch + # mode, an agent and a profile are MANIFEST KEYS everywhere else in this + # estate — letters, digits, `.`, `_`, `-` — and each of them is compared + # for equality by a later reader (`--expect-operation`, the supervisor's + # own fence, `lane-start --agent`). A value carrying a space, a `;` or a + # newline is a value no such comparison can be trusted with, and this file + # is written one `key: value` line at a time. + for sri_k in "operation=$sri_op" "mode=$sri_mode" "agent=$sri_agent" "profile=$sri_prof" \ + "expect-operation=$sri_expo"; do + sri_kv="${sri_k#*=}" + [ -n "$sri_kv" ] || continue + case "$sri_kv" in + *[!A-Za-z0-9._-]*) die "--${sri_k%%=*} takes a manifest key — letters, digits, '.', '_' and '-' — because a later reader compares it for equality and this record is one line per field. Got '$sri_kv'." 64 ;; + esac + done + case "$sri_gen$sri_att$sri_expa" in *[!0-9]*) die "--generation and --attempt take numbers" 64 ;; esac + case "$sri_expg" in + '') : ;; + *[!0-9]*) die "--expect-generation takes a number; '$sri_expg' is not one" 64 ;; + esac + # A DIRECTORY IN THIS RECORD IS ABSOLUTE OR IT IS NOTHING, and the same for + # the handoff: the reader of this file is a DIFFERENT PROCESS IN A + # DIFFERENT DIRECTORY — the supervisor in a respawned pane — and a relative + # path resolved against its cwd is a path to somewhere else. `~` is the + # writing shell's and is never expanded here. + case "$sri_dir" in ''|/*) : ;; *) die "--dir takes an ABSOLUTE path: this record is read by the supervisor in a pane whose working directory is not this one, and a relative path there names a different place. Got '$sri_dir'." 64 ;; esac + case "$sri_hf" in ''|/*) : ;; *) die "--handoff takes an ABSOLUTE path, for the same reason --dir does: the launch that reads it back stands somewhere else. Got '$sri_hf'." 64 ;; esac + for sri_exact in "$sri_dir" "$sri_pane" "$sri_win" "$sri_hf" "$sri_old" "$sri_new" "$sri_dig" "$sri_prepared"; do + lane_restart_value_ok "$sri_exact" || die "restart launch facts cannot contain control characters. Nothing was written." 64 + done + check_lane_name "$lane" + log_sync + lane="$(canon_lane "$lane")" || exit 2 # Amendment 15 + # Select the physical intent under the CAS mutex: a waiting writer must + # see a reservation another writer established before releasing the lock. + acquire_lock + managed_seam_refuse "$lane" "set-restart-intent" + sri_root=""; sri_rrc=0 + sri_root="$(lane_restart_control_root "$lane")" || sri_rrc=$? + [ "$sri_rrc" = 0 ] || { + release_lock + die "lane $lane's restart control root is unavailable, unreadable or ambiguous. Nothing was written. Inspect its recorded directory and projects-root intents, or configure LANES_LANE_STATE_ROOT explicitly." 1 + } + sri_f="$sri_root/restart-intent.yaml" + # A SCHEMA THIS WRITER DOES NOT KNOW IS NOT ITS RECORD TO REPLACE (Copilot + # round 1 on openRepoTools#121). The READ side already fails closed on one — + # it answers `UNKNOWN-SCHEMA` rather than reporting a launch it cannot + # understand — and the WRITE side walked straight past it: the fields it + # knows were copied forward, the ones it does not were dropped, and the file + # came out stamped `schema: 1`. A newer tooling's intent would have been + # silently rewritten as an older one's, which is the read-side protection + # undone by the other half of the same command. This is checked INSIDE the + # lock, with the fence, because the file may be replaced between a read and + # a write, and it refuses with 2 — not 7 — because 7 is *another act got + # there first, re-read and decide* and this is *this copy of the tooling + # must not touch this file at all*. + if [ -e "$sri_f" ] || [ -L "$sri_f" ]; then + if [ ! -f "$sri_f" ] || [ ! -r "$sri_f" ]; then + release_lock + die "lane $lane has an existing unreadable restart intent. Nothing was written: a failed read is not an absent operation." 1 + fi + sri_missing="$(lane_restart_missing "$sri_f" "$lane")" || { release_lock; die "the restart record could not be read. Nothing was written." 1; } + [ -z "$sri_missing" ] || { release_lock; die "the existing restart record is malformed (missing, duplicate or invalid fields: $sri_missing). Nothing was written." 2; } + sri_nows="$(lane_restart_sidecar_field "$sri_f" schema)" || { release_lock; die "the restart schema could not be read. Nothing was written." 1; } + if [ "$sri_nows" != "$LANE_RESTART_SCHEMA" ]; then + release_lock + die "lane $lane's restart intent is schema '$sri_nows' and this \`lanes-edit.sh\` writes schema $LANE_RESTART_SCHEMA. Nothing was written: taking a transition over it would copy forward the fields this version knows, drop the ones it does not, and stamp the file as an older schema — which is a newer tooling's record quietly replaced by an older one. Read it with a helper that knows that schema, or remove $sri_f once you know no restart is in flight." 2 + fi + fi + sri_now=""; sri_nowg=""; sri_nowo=""; sri_nowa=""; sri_nown="" + if [ -r "$sri_f" ]; then + sri_now="$(lane_restart_sidecar_field "$sri_f" state)" + sri_nowg="$(lane_restart_sidecar_field "$sri_f" generation)" + sri_nowo="$(lane_restart_sidecar_field "$sri_f" operation)" + sri_nowa="$(lane_restart_sidecar_field "$sri_f" attempt)" + sri_nown="$(lane_restart_sidecar_field "$sri_f" new_transcript)" + fi + if [ -r "$sri_f" ]; then + lane_restart_word_ok "$sri_now" || { release_lock; die "the existing restart state is malformed. Nothing was written." 2; } + case "$sri_nowg:$sri_nowa" in *[!0-9:]*|:*|*:) release_lock; die "the existing restart generation or attempt is malformed. Nothing was written." 2 ;; esac + fi + sri_fence="" + # `--expect` TAKES A SET, because the states a caller is entitled to write + # over are usually more than one and asking for them in two calls is a + # second read-then-write with a window between. `pending` is created over + # `none|ready|failed` and never over `pending|starting`, which is the + # spec's *an ordinary `/ctx` does not supersede an operation in flight* + # expressed as one argument. + if [ -n "$sri_exp" ]; then + sri_match=0 + sri_rest="$sri_exp" + while [ -n "$sri_rest" ]; do + case "$sri_rest" in + *'|'*) sri_one="${sri_rest%%|*}"; sri_rest="${sri_rest#*|}" ;; + *) sri_one="$sri_rest"; sri_rest="" ;; + esac + [ "$sri_one" = none ] || lane_restart_word_ok "$sri_one" || + { release_lock; die "--expect takes restart-intent states or 'none'; '$sri_one' is neither" 64; } + [ "$sri_one" = "${sri_now:-none}" ] && sri_match=1 + done + [ "$sri_match" = 1 ] || sri_fence="the intent is ${sri_now:-none} and --expect named $sri_exp" + fi + [ -z "$sri_expg" ] || [ "$sri_expg" = "${sri_nowg:-0}" ] || sri_fence="${sri_fence:+$sri_fence; }generation is ${sri_nowg:-0} and --expect-generation named $sri_expg" + [ -z "$sri_expo" ] || [ "$sri_expo" = "${sri_nowo:-none}" ] || sri_fence="${sri_fence:+$sri_fence; }operation is ${sri_nowo:-none} and --expect-operation named $sri_expo" + [ -z "$sri_expa" ] || [ "$sri_expa" = "${sri_nowa:-0}" ] || sri_fence="${sri_fence:+$sri_fence; }attempt is ${sri_nowa:-0} and --expect-attempt named $sri_expa" + [ -z "$sri_expn" ] || [ "$sri_expn" = "${sri_nown:-none}" ] || sri_fence="${sri_fence:+$sri_fence; }prepared transcript is ${sri_nown:-none} and --expect-new-transcript named $sri_expn" + if [ -n "$sri_fence" ]; then + release_lock + printf 'state\t%s\ngeneration\t%s\noperation\t%s\nattempt\t%s\n' \ + "${sri_now:-none}" "${sri_nowg:-0}" "${sri_nowo:-none}" "${sri_nowa:-0}" + die "lane $lane's restart intent did not move to $sri_state: $sri_fence. Another act got there first — a second /ctx, a supervisor that claimed this operation, or a resume that finished it — and nothing was written. Re-read it (lanes-edit.sh restart-intent $lane) before deciding what this process should do; a stale supervisor must never overwrite a newer operation." 7 + fi + case "$sri_nowg" in ''|*[!0-9]*) sri_nowg=0 ;; esac + case "$sri_nowa" in ''|*[!0-9]*) sri_nowa=0 ;; esac + # A TRANSITION THAT DOES NOT NAME A FIELD KEEPS IT, and does not blank it — + # the same rule `set-lane-state` takes, and for the same reason: a + # `starting` written by the supervisor is about the STATE, and blanking the + # handoff digest out of that call would lose the one fact every later + # launch and retry is fenced on. + sri_keep() { # <key> <value the caller gave> + [ -n "${2-}" ] && { printf '%s' "$2"; return 0; } + lane_restart_sidecar_field "$sri_f" "$1" 2>/dev/null || : + } + sri_gen="$(sri_keep generation "$sri_gen")"; [ -n "$sri_gen" ] || sri_gen="$sri_nowg" + sri_op="$(sri_keep operation "$sri_op")"; [ -n "$sri_op" ] || sri_op="$(lane_restart_op_id)" + sri_prepared="$(sri_keep prepared_digest "$sri_prepared")" + sri_mode="$(sri_keep mode "$sri_mode")" + sri_agent="$(sri_keep agent "$sri_agent")" + sri_prof="$(sri_keep profile "$sri_prof")" + sri_dir="$(sri_keep dir "$sri_dir")" + sri_pane="$(sri_keep pane "$sri_pane")" + sri_win="$(sri_keep window "$sri_win")" + sri_hf="$(sri_keep handoff "$sri_hf")" + # …EXCEPT WHERE THE OPERATION ITSELF HAS CHANGED, and then five of these + # fields are not this act's facts at all. `old_transcript`, + # `new_transcript`, `attempt`, `reason` and `created` are scoped to ONE + # operation: the transcript that restart paused, the transcript its launch + # was preparing, how many times THAT launch was tried, why THAT one failed, + # and when THAT intent was made. Carrying them into the next operation is + # how a brand-new `/ctx` comes out reading `attempt 3` and `reason "the + # launcher exited 127"` from a restart that is over — and two of them are + # worse than cosmetic, because the supervisor's readiness predicate is + # built on exactly this pair: + # + # * an inherited `new_transcript` is a uuid THIS launch will never mint, + # so readiness can only run to its deadline and report indeterminate; + # * an inherited `old_transcript` is the wrong uuid to be distinct FROM, + # and that check is the one that catches openRepoTools#94 itself — a + # replacement that came up resuming the transcript this `/ctx` paused. + # Comparing it against some earlier restart's transcript would let the + # measured defect through the very predicate written to catch it. + # + # A caller that names one of the five still wins; this only decides what an + # UNNAMED field falls back to, and `none` is an answer where another + # operation's value is a lie. + sri_newop=0 + [ "$sri_op" = "${sri_nowo:-none}" ] || sri_newop=1 + if [ "$sri_newop" = 1 ]; then sri_prepared=none; fi + if [ "$sri_newop" != 1 ]; then + sri_old="$(sri_keep old_transcript "$sri_old")" + sri_new="$(sri_keep new_transcript "$sri_new")" + sri_reason="$(sri_keep reason "$sri_reason")" + fi + # THE DIGEST IS COMPUTED HERE WHERE THE CALLER NAMED A HANDOFF AND NO + # DIGEST, so that there is ONE implementation of *what this handoff was + # when the intent was made* and a caller cannot accidentally record a + # digest of something else. + if [ -z "$sri_dig" ]; then + case "$sri_hf" in + /*) if [ "$sri_state" = pending ] && [ -r "$sri_hf" ]; then + sri_dig="$(lane_handoff_digest "$sri_hf")" + else + sri_dig="$(lane_restart_sidecar_field "$sri_f" digest 2>/dev/null || :)" + fi ;; + *) sri_dig="$(lane_restart_sidecar_field "$sri_f" digest 2>/dev/null || :)" ;; + esac + fi + # THE ATTEMPT COUNT. `--bump-attempt` is the retry's own act and is the one + # thing that may not be inferred: a supervisor claiming a NEW operation + # starts at 1, and a retry of the SAME one increments. + if [ -n "$sri_att" ]; then + : + elif [ "$sri_bump" = 1 ]; then + sri_att=$((sri_nowa + 1)) + elif [ "$sri_newop" = 1 ]; then + sri_att=0 + else + sri_att="$sri_nowa" + fi + # AND `created` IS THIS OPERATION'S OWN, for the same reason: it is read as + # *when this restart was taken*, and a new operation inheriting the last + # one's timestamp says a `/ctx` happened at a moment it did not. + if [ "$sri_newop" = 1 ]; then + sri_created="" + else + sri_created="$(lane_restart_sidecar_field "$sri_f" created 2>/dev/null || :)" + fi + if lane_restart_put "$sri_root" "$lane" "$sri_state" "$sri_gen" "$sri_op" \ + "$sri_mode" "$sri_agent" "$sri_prof" "$sri_dir" "$sri_pane" "$sri_win" \ + "$sri_hf" "$sri_dig" "$sri_old" "$sri_new" "$sri_att" "$sri_reason" \ + "$sri_created" "$sri_prepared"; then + release_lock + printf 'state\t%s\ngeneration\t%s\noperation\t%s\nattempt\t%s\ndigest\t%s\nfile\t%s\n' \ + "$sri_state" "$sri_gen" "$sri_op" "$sri_att" "${sri_dig:-none}" "$sri_f" + else + release_lock + die "lane $lane's restart intent could not be written under $sri_root (the shell's own error is above). Nothing was changed: the intent is replaced atomically, so the one that was there is the one that is there." 1 + fi + ;; + + # ---------- THE SEAM: is this lane the managed ledger's? (ruling 2026-10-04) + # + # 0 a valid managed-owner marker: the owner is printed + # 8 no marker and no managed-owner vocabulary, in the published row or + # this checkout's: a legacy lane + # 1 vocabulary that does not parse, vocabulary only this checkout's row + # carries (#157 item 4a, as `managed_seam_refuse` reads it), or a + # register that could not be read: ownership UNKNOWN, which a caller + # refuses on exactly as it refuses 0 + # 64 usage + managed-projection) + lane="${1-}"; [ -n "$lane" ] || die "usage: managed-projection <lane>" 64 + [ "$#" -le 1 ] || die "managed-projection takes one lane: managed-projection <lane>" 64 + check_lane_name "$lane" + log_sync + lane="$(canon_lane "$lane")" || exit 2 # Amendment 15 + mpj_out=""; mpj_rc=0 + mpj_out="$(lane_is_managed_owned "$lane")" || mpj_rc=$? + case "$mpj_rc" in + 0) printf '%s\n' "$mpj_out" ;; + 8) + managed_local_hint "$lane" || + die "lane $lane's row in this checkout's register file, $LANES_FILE, carries managed-owner vocabulary (or could not be read) where the published register's, origin/$LANES_BRANCH, does not: the two copies disagree on whether the managed ledger owns it, so that is UNKNOWN, and it is never read as 'legacy' (Amendment 7(d)) — every legacy writer refuses it for the same reason. $(managed_local_remedy)" 1 + exit 8 ;; + *) die "lane $lane's register row carries managed-owner vocabulary that does not parse as a marker, or the register could not be read: whether the managed ledger owns it is UNKNOWN, and that is never read as 'legacy' (Amendment 7(d))." 1 ;; + esac + ;; + + # ---------- openRepoTools#91: the lifecycle, the inventory, the reconcile + # + # ALL FIVE ANSWER OUT OF THE LOCAL CONTROL ROOT and none of them touches the + # register, the object log or the network. The two WRITERS are deliberately + # absent from the dispatcher's workstation guard above (`R-A11-14` is about a + # record FILED UNDER A WORKSTATION; this one is filed under nothing and never + # leaves the machine that wrote it), and they take the same 64-for-usage + # contract every read Amendment 11 added takes, because they sit in front of + # a launch exactly as those do. + # + # 0 done + # 1 no control root could be derived, or it could not be written; or a + # WRITER met a record there it cannot read — of a schema it does not + # write, or of its own and not a whole record (#115) — and replaced + # nothing; or `lane-tree-now` met a git read that failed + # 2 a refusal of the arguments + # 7 THE FENCE DID NOT MATCH — another act got there first, which is what + # this file already spends 7 on (`claim`'s CLAIM-LOST). Nothing was + # written and the current state is printed. `set-lane-tree` spends it + # too where the lane is `SWAPPED`: the operation its fence names is + # finished (#114). + # 8 there is no such record (no snapshot, no tree) + # 10 THE RECORD IS THERE AND COULD NOT BE READ, which is never 8 (Copilot + # round 6 on #97). 8 tells a launcher *this lane was never migrated, go + # on*; 10 tells it *this lane may be mid-crash and nobody could look*. + # (It was 9 until main's #61 spent 9 on `claim`'s abandoned takeover.) + # A snapshot of this schema that is not a whole record is 10 as well + # (#115): nothing can be read out of it as a snapshot. + # 64 a usage error of this subcommand's own — for `set-lane-tree`, a + # partial observation, a `--dirty`/`--unpushed` that is not a count + # (`unknown` is one for `--unpushed`), or a field that is only blanks + + lane-state) + lane="${1-}"; [ -n "$lane" ] || die "usage: lane-state <lane>" 64 + [ "$#" -le 1 ] || die "lane-state takes one lane: lane-state <lane>" 64 + check_lane_name "$lane" + log_sync + lane="$(canon_lane "$lane")" || exit 2 # Amendment 15 + lst_out=""; lst_rc=0 + lst_out="$(lane_state_read "$lane")" || lst_rc=$? + case "$lst_rc" in + 0) : ;; + 8) exit 8 ;; + 10) + # WHICH OF THE TWO 10s (#115): a record that opens and is not a whole + # one of this schema is said as that, for the person who reads it. + lst_f="$(lane_control_root "$lane" 2>/dev/null || printf '<no control root>')/lane-state.yaml" + lst_what="it could not be read" + if [ -r "$lst_f" ] && ! lane_sidecar_schema_ok "$lst_f"; then lst_what="it is of this schema and $LSS_WHY, so nothing can be read out of it as a snapshot"; fi + die "lane $lane HAS a lifecycle snapshot at its control root and $lst_what. That is NOT 'this lane has no snapshot' — 8 says that, and a launcher answers an 8 by going on, which over an unreadable record would be a launch made in ignorance of a crash nobody could look at (R22, Amendment 7(d)). Read it by hand: $lst_f" 10 ;; + *) die "lane $lane has no lifecycle control root: its record names no directory (Amendment 11(c)) and \$PROJECTS_ROOT is not a directory here. That is NOT 'this lane is in no state' — a read that could not be made is never an answer (Amendment 7(d))." 1 ;; + esac + printf '%s\n' "$lst_out" + ;; + + set-lane-state) + lane="${1-}"; [ -n "$lane" ] || die "usage: set-lane-state <lane> <RUNNING|SWAPPING|SWAPPED|CLOSED> [--expect <STATE|none>] [--expect-generation <n>] [--expect-operation <id>] [--operation <id>] [--owner <uuid>] [--agent <name>] [--profile <name>] [--kind <word>]" 64 + shift + sls_state="${1-}"; [ -n "$sls_state" ] || die "set-lane-state needs the state to move to: RUNNING, SWAPPING, SWAPPED or CLOSED" 64 + shift + sls_exp=""; sls_expg=""; sls_expo=""; sls_op=""; sls_owner=""; sls_agent=""; sls_prof=""; sls_kind="" + while [ $# -gt 0 ]; do + case "$1" in + --expect) sls_exp="${2-}"; [ -n "$sls_exp" ] || die "--expect needs a state word, or 'none'" 64; shift 2 ;; + --expect=*) sls_exp="${1#--expect=}"; [ -n "$sls_exp" ] || die "--expect needs a value" 64; shift ;; + --expect-generation) sls_expg="${2-}"; [ -n "$sls_expg" ] || die "--expect-generation needs a number" 64; shift 2 ;; + --expect-generation=*) sls_expg="${1#--expect-generation=}"; [ -n "$sls_expg" ] || die "--expect-generation needs a value" 64; shift ;; + --expect-operation) sls_expo="${2-}"; [ -n "$sls_expo" ] || die "--expect-operation needs an operation id" 64; shift 2 ;; + --expect-operation=*) sls_expo="${1#--expect-operation=}"; [ -n "$sls_expo" ] || die "--expect-operation needs a value" 64; shift ;; + --operation) sls_op="${2-}"; [ -n "$sls_op" ] || die "--operation needs an operation id" 64; shift 2 ;; + --operation=*) sls_op="${1#--operation=}"; [ -n "$sls_op" ] || die "--operation needs a value" 64; shift ;; + --owner) sls_owner="${2-}"; [ "$#" -ge 2 ] && [ -n "$sls_owner" ] || die "--owner needs a value" 64; shift 2 ;; + --owner=*) sls_owner="${1#--owner=}"; [ -n "$sls_owner" ] || die "--owner needs a value" 64; shift ;; + --agent) sls_agent="${2-}"; [ "$#" -ge 2 ] && [ -n "$sls_agent" ] || die "--agent needs a value" 64; shift 2 ;; + --agent=*) sls_agent="${1#--agent=}"; [ -n "$sls_agent" ] || die "--agent needs a value" 64; shift ;; + --profile) sls_prof="${2-}"; [ "$#" -ge 2 ] && [ -n "$sls_prof" ] || die "--profile needs a value" 64; shift 2 ;; + --profile=*) sls_prof="${1#--profile=}"; [ -n "$sls_prof" ] || die "--profile needs a value" 64; shift ;; + --kind) sls_kind="${2-}"; [ "$#" -ge 2 ] && [ -n "$sls_kind" ] || die "--kind needs a value" 64; shift 2 ;; + --kind=*) sls_kind="${1#--kind=}"; [ -n "$sls_kind" ] || die "--kind needs a value" 64; shift ;; + --) shift ;; + *) die "unknown option '$1' for set-lane-state" 64 ;; + esac + done + lane_state_word_ok "$sls_state" || die "'$sls_state' is not a lane lifecycle state: RUNNING, SWAPPING, SWAPPED and CLOSED are the four, and a fifth word in this file would be a state no reader of it knows" 64 + [ -z "$sls_exp" ] || [ "$sls_exp" = none ] || lane_state_word_ok "$sls_exp" || + die "--expect takes one of the four states, or 'none' for a lane that has no snapshot yet; '$sls_exp' is neither" 64 + case "$sls_expg" in + '') : ;; + *[!0-9]*) die "--expect-generation takes a number; '$sls_expg' is not one" 64 ;; + esac + check_lane_name "$lane" + log_sync + lane="$(canon_lane "$lane")" || exit 2 # Amendment 15 + managed_seam_refuse "$lane" "set-lane-state" # ruling 2026-10-04 + sls_root=""; sls_rrc=0 + sls_root="$(lane_control_root "$lane")" || sls_rrc=$? + [ "$sls_rrc" = 0 ] || + die "lane $lane has no lifecycle control root, so there is nowhere to record that it is $sls_state: its record names no directory (Amendment 11(c)) and \$PROJECTS_ROOT is not a directory here. Set \$LANES_LANE_STATE_ROOT, or start the lane through lane-start so that its record carries a dir." 1 + # THE FENCE, read under the same mutex the write takes, so that two + # transitions cannot both read the state before either writes it. + acquire_lock + # AND THE SCHEMA IS ASKED ABOUT BEFORE ANY TRANSITION FIELD IS READ OR + # WRITTEN (Copilot round 5 on #97). `lane_state_read` fails closed for a + # version it does not know; this writer used to walk past that check into + # the raw fields and rename its own file over the top, so an older helper + # meeting a newer tooling's snapshot destroyed a record it could not read — + # the one act no later reader can undo. It is a 1 and not a 7: 7 says a race + # was lost and invites the caller to re-read and try again, and no re-read + # makes this file readable by this helper. + if ! lane_sidecar_schema_ok "$sls_root/lane-state.yaml"; then + sls_sch="$(lane_sidecar_field "$sls_root/lane-state.yaml" schema 2>/dev/null || :)" + release_lock + die "lane $lane's lifecycle snapshot at $sls_root/lane-state.yaml records schema ${sls_sch:-<none>} and is not a record this helper can read: $LSS_WHY. NOTHING was read out of it and nothing was written over it: a record this helper cannot read is one it cannot safely replace, whether its schema is one this helper does not write or its own and the record is not whole (#115). Upgrade this workstation's lanes-edit.sh if a newer tooling wrote it; if you know what wrote that file, move it aside by hand and re-run." 1 + fi + sls_now=""; sls_nowg=""; sls_nowo="" + if [ -r "$sls_root/lane-state.yaml" ]; then + sls_now="$(lane_sidecar_field "$sls_root/lane-state.yaml" state)" + sls_nowg="$(lane_sidecar_field "$sls_root/lane-state.yaml" generation)" + sls_nowo="$(lane_sidecar_field "$sls_root/lane-state.yaml" operation)" + fi + sls_fence="" + [ -z "$sls_exp" ] || [ "$sls_exp" = "${sls_now:-none}" ] || sls_fence="state is ${sls_now:-none} and --expect named $sls_exp" + [ -z "$sls_expg" ] || [ "$sls_expg" = "${sls_nowg:-0}" ] || sls_fence="${sls_fence:+$sls_fence; }generation is ${sls_nowg:-0} and --expect-generation named $sls_expg" + [ -z "$sls_expo" ] || [ "$sls_expo" = "${sls_nowo:-none}" ] || sls_fence="${sls_fence:+$sls_fence; }operation is ${sls_nowo:-none} and --expect-operation named $sls_expo" + if [ -n "$sls_fence" ]; then + release_lock + printf 'state\t%s\ngeneration\t%s\noperation\t%s\n' "${sls_now:-none}" "${sls_nowg:-0}" "${sls_nowo:-none}" + die "lane $lane did not move to $sls_state: $sls_fence. Another act got there first — a resume that advanced the generation, or a second handoff — and nothing was written. Re-read the state (lanes-edit.sh lane-state $lane) before deciding what this process should do; a stale finalizer must never overwrite a newer owner." 7 + fi + case "$sls_nowg" in ''|*[!0-9]*) sls_nowg=0 ;; esac + # A TRANSITION THAT DOES NOT NAME A FIELD KEEPS IT, and does not blank it. + # `SWAPPED` is the same operation's commit point and `CLOSED` the end of a + # lane that was owned by somebody: writing `owner none` there would lose + # the one fact a later reconciliation compares a live holder against, out of + # a call that was only ever about the state word. + [ -n "$sls_owner" ] || sls_owner="$(lane_sidecar_field "$sls_root/lane-state.yaml" owner 2>/dev/null || :)" + [ -n "$sls_agent" ] || sls_agent="$(lane_sidecar_field "$sls_root/lane-state.yaml" agent 2>/dev/null || :)" + [ -n "$sls_prof" ] || sls_prof="$(lane_sidecar_field "$sls_root/lane-state.yaml" profile 2>/dev/null || :)" + [ -n "$sls_kind" ] || sls_kind="$(lane_sidecar_field "$sls_root/lane-state.yaml" kind 2>/dev/null || :)" + # WHICH TRANSITION ADVANCES THE GENERATION. A new owner or a new operation + # does (`RUNNING`, `SWAPPING`, `CLOSED`); the FINISH of an operation + # already in flight does not, because `SWAPPED` is the same operation + # reaching its commit point and a fence that moved under it would refuse + # the very finalizer that is entitled to write. + case "$sls_state" in + SWAPPED) sls_gen="$sls_nowg"; [ -n "$sls_op" ] || sls_op="${sls_nowo:-none}" ;; + *) sls_gen=$((sls_nowg + 1)); [ -n "$sls_op" ] || sls_op="$(lane_op_id)" ;; + esac + if lane_state_put "$sls_root" "$lane" "$sls_state" "$sls_gen" "$sls_op" \ + "$sls_owner" "$sls_agent" "$sls_prof" "$WS" "$sls_kind"; then + release_lock + LANES_INDEX_NUDGE_INV=1 # opensoft/openRepoTools#161: `cleanup` nudges the indexer + printf 'state\t%s\ngeneration\t%s\noperation\t%s\n' "$sls_state" "$sls_gen" "$sls_op" + else + release_lock + die "lane $lane's lifecycle snapshot could not be written under $sls_root (the shell's own error is above). Nothing was changed: the snapshot is replaced atomically, so the one that was there is the one that is there." 1 + fi + ;; + + lane-trees) + lane="${1-}"; [ -n "$lane" ] || die "usage: lane-trees <lane>" 64 + [ "$#" -le 1 ] || die "lane-trees takes one lane: lane-trees <lane>" 64 + check_lane_name "$lane" + log_sync + lane="$(canon_lane "$lane")" || exit 2 # Amendment 15 + ltr_out=""; ltr_rc=0 + ltr_out="$(lane_trees_list "$lane")" || ltr_rc=$? + case "$ltr_rc" in + 0) : ;; + 8) exit 8 ;; + 10) die "lane $lane's worktree inventory directory $(lane_control_root "$lane" 2>/dev/null || printf '<no control root>')/trees is there and could not be listed. That is NOT 'this lane recorded no tree' — 8 says that, and a reader that goes on over it relaunches writers onto trees nobody looked at (R22, Amendment 7(d)). Read it by hand." 10 ;; + *) die "lane $lane has no lifecycle control root, so its worktree inventory could not be read. That is NOT 'this lane owns no worktree' (Amendment 7(d))." 1 ;; + esac + printf '%s\n' "$ltr_out" + ;; + + set-lane-tree) + lane="${1-}"; [ -n "$lane" ] || die "usage: set-lane-tree <lane> <worktree path> [--checkout <dir>] [--branch <b>] [--head <sha>] [--upstream <ref>] [--dirty <n>] [--unpushed <n>] [--writer <uuid>] [--generation <n>] [--operation <id>]" 64 + shift + slt_path="${1-}"; [ -n "$slt_path" ] || die "set-lane-tree needs the worktree's path" 64 + shift + case "$slt_path" in /*) : ;; *) die "set-lane-tree takes an ABSOLUTE path: a relative one has no meaning to any later reader of this record, which is a different process in a different directory" 64 ;; esac + slt_co=""; slt_b=""; slt_h=""; slt_u=""; slt_d=""; slt_n=""; slt_w=""; slt_g=""; slt_op="" + while [ $# -gt 0 ]; do + case "$1" in + --checkout) slt_co="${2-}"; [ "$#" -ge 2 ] && [ -n "$slt_co" ] || die "--checkout needs a value" 64; shift 2 ;; + --checkout=*) slt_co="${1#--checkout=}"; [ -n "$slt_co" ] || die "--checkout needs a value" 64; shift ;; + --branch) slt_b="${2-}"; [ "$#" -ge 2 ] && [ -n "$slt_b" ] || die "--branch needs a value" 64; shift 2 ;; + --branch=*) slt_b="${1#--branch=}"; [ -n "$slt_b" ] || die "--branch needs a value" 64; shift ;; + --head) slt_h="${2-}"; [ "$#" -ge 2 ] && [ -n "$slt_h" ] || die "--head needs a value" 64; shift 2 ;; + --head=*) slt_h="${1#--head=}"; [ -n "$slt_h" ] || die "--head needs a value" 64; shift ;; + --upstream) slt_u="${2-}"; [ "$#" -ge 2 ] && [ -n "$slt_u" ] || die "--upstream needs a value" 64; shift 2 ;; + --upstream=*) slt_u="${1#--upstream=}"; [ -n "$slt_u" ] || die "--upstream needs a value" 64; shift ;; + --dirty) slt_d="${2-}"; [ "$#" -ge 2 ] && [ -n "$slt_d" ] || die "--dirty needs a value" 64; shift 2 ;; + --dirty=*) slt_d="${1#--dirty=}"; [ -n "$slt_d" ] || die "--dirty needs a value" 64; shift ;; + --unpushed) slt_n="${2-}"; [ "$#" -ge 2 ] && [ -n "$slt_n" ] || die "--unpushed needs a value" 64; shift 2 ;; + --unpushed=*) slt_n="${1#--unpushed=}"; [ -n "$slt_n" ] || die "--unpushed needs a value" 64; shift ;; + --writer) slt_w="${2-}"; [ "$#" -ge 2 ] && [ -n "$slt_w" ] || die "--writer needs a value" 64; shift 2 ;; + --writer=*) slt_w="${1#--writer=}"; [ -n "$slt_w" ] || die "--writer needs a value" 64; shift ;; + --generation) slt_g="${2-}"; [ "$#" -ge 2 ] && [ -n "$slt_g" ] || die "--generation needs a value" 64; shift 2 ;; + --generation=*) slt_g="${1#--generation=}"; [ -n "$slt_g" ] || die "--generation needs a value" 64; shift ;; + --operation) slt_op="${2-}"; [ "$#" -ge 2 ] && [ -n "$slt_op" ] || die "--operation needs a value" 64; shift 2 ;; + --operation=*) slt_op="${1#--operation=}"; [ -n "$slt_op" ] || die "--operation needs a value" 64; shift ;; + --) shift ;; + *) die "unknown option '$1' for set-lane-tree" 64 ;; + esac + done + check_lane_name "$lane" + log_sync + lane="$(canon_lane "$lane")" || exit 2 # Amendment 15 + managed_seam_refuse "$lane" "set-lane-tree" # ruling 2026-10-04 + slt_root=""; slt_rrc=0 + slt_root="$(lane_control_root "$lane")" || slt_rrc=$? + [ "$slt_rrc" = 0 ] || + die "lane $lane has no lifecycle control root, so its worktree inventory has nowhere to go: its record names no directory (Amendment 11(c)) and \$PROJECTS_ROOT is not a directory here." 1 + # WHAT THE CALLER SAW BEATS WHAT THIS PROCESS SEES, because a poll and a + # record written from it are ONE observation and a second reading of the + # same tree a moment later is a different one. Where the caller passed + # nothing, the tree is read HERE through the same `lane_tree_now` + # `lane-reconcile` recomputes with, so the two cannot disagree. + # + # AND AN OBSERVATION NOBODY COULD MAKE IS NOT COMPLETED WITH CLEAN-LOOKING + # VALUES (Copilot round 5 on #97). Until this round a `lane_tree_now` that + # failed left every field empty and `lane_tree_put`'s defaults wrote them as + # `unknown` / `none` / `0` — a record saying *branch unknown, nothing dirty, + # nothing unpushed* for a tree this process never read, which a later + # reconciliation would compare against and call published. + if [ -z "$slt_b$slt_h$slt_u$slt_d$slt_n" ]; then + slt_now=""; slt_nrc=0 + slt_now="$(lane_tree_now "$slt_path")" || slt_nrc=$? + case "$slt_nrc" in + 0) + slt_b="$(printf '%s' "$slt_now" | awk -F"$US" '{print $1}')" + slt_h="$(printf '%s' "$slt_now" | awk -F"$US" '{print $2}')" + slt_u="$(printf '%s' "$slt_now" | awk -F"$US" '{print $3}')" + slt_d="$(printf '%s' "$slt_now" | awk -F"$US" '{print $4}')" + slt_n="$(printf '%s' "$slt_now" | awk -F"$US" '{print $5}')" ;; + 1) die "no worktree was recorded for lane $lane: there is no directory at $slt_path and this command was given no observation of its own to file. A record of a tree nobody read would say 'branch unknown, 0 dirty, 0 unpushed', which a later reconciliation reads as clean and published. Pass what you saw (--branch/--head/--upstream/--dirty/--unpushed), or record the tree while it is there." 1 ;; + 2) die "no worktree was recorded for lane $lane: $slt_path exists and git does not answer in it, so there is no observation to file and this command invents none. The path itself was not touched." 1 ;; + *) die "no worktree was recorded for lane $lane: git answers in $slt_path and one of the reads an observation is made of FAILED, so nothing was written — a branch, a head, a status or an upstream that could not be read is never recorded as a clean tree (Amendment 7(d)). Read it by hand: git -C $slt_path status" 1 ;; + esac + # AND A CALLER'S OBSERVATION IS TAKEN WHOLE OR NOT AT ALL (Codex on ec9847e, + # PR #97). One flag alone used to skip the reading above and let the rest + # reach the record as `unknown`, `none` and — the dangerous two — `dirty 0` + # and `unpushed 0`, which a later reconciliation of a vanished tree reads as + # clean and published although nobody observed either. + elif [ -z "$slt_b" ] || [ -z "$slt_h" ] || [ -z "$slt_u" ] || [ -z "$slt_d" ] || [ -z "$slt_n" ]; then + die "set-lane-tree takes the caller's observation WHOLE — --branch, --head, --upstream, --dirty and --unpushed together — or none of them, when the tree is read here. A partial one would be filed with values nobody observed, and 'dirty 0, unpushed 0' is the record a later reconciliation reads as clean and published. Nothing was written." 64 + fi + # AND IN THE SHAPES A RECORD IS READ BACK IN (#115). The two counts are what + # a reconciliation decides with, and a record carrying one that is neither a + # count nor `unknown` is one no reader may use and no writer may replace — + # so it is refused here, before anything is written, rather than filed. + case "$slt_d" in + ''|*[!0-9]*) die "set-lane-tree's --dirty takes a count of the tree's dirty paths, and '$slt_d' is not one: a record carrying it could be neither read nor replaced. Nothing was written." 64 ;; + esac + case "$slt_n" in + unknown) : ;; + ''|*[!0-9]*) die "set-lane-tree's --unpushed takes a count of commits, or 'unknown' where the upstream is configured and its remote-tracking ref is not here; '$slt_n' is neither, and a record carrying it could be neither read nor replaced. Nothing was written." 64 ;; + esac + # AND NO FIELD THAT IS ONLY BLANKS (review r1 of #252). A reader trims a + # value, so `--branch ' '` files a record with no branch — one the rename + # below refused only after the lock, with exit 1 and "the shell's own error + # is above". It is the caller's usage, said as one, before anything is taken. + for slt_fv in "branch=$slt_b" "head=$slt_h" "upstream=$slt_u" "checkout=$slt_co" "writer=$slt_w"; do + case "${slt_fv#*=}" in + ''|*[![:space:]]*) : ;; + *) die "set-lane-tree's --${slt_fv%%=*} is only blanks: a reader trims a value, so the record would carry no ${slt_fv%%=*} and could be neither read nor replaced. Nothing was written." 64 ;; + esac + done + # THE FENCE, AND IT IS THE LANE'S OWN (Copilot round 5 on #97). A caller + # that names the generation and the operation it is recording under is + # saying *this observation belongs to that transition* — and until this + # round the pair was serialized into the sidecar and compared with nothing, + # so a handoff that stalled while a recovery advanced the lane filed its + # superseded poll straight over the current inventory. The pair is compared + # with the lane's own snapshot under the SAME mutex the transition takes, + # and the write happens inside that mutex, so a transition cannot land + # between the compare and the record. A caller that names NEITHER is making + # an observation of its own — a person, or the read above — and has no fence + # to fail. + # + # AND THE MUTEX IS TAKEN WHETHER OR NOT THERE IS A FENCE TO CHECK (Copilot + # round 6 on #97). It used to be taken only for a FENCED write, which left + # the unfenced ones — a person's `set-lane-tree`, a caller that named no + # transition — racing every other writer of the same sidecar: the atomic + # rename below stops a reader seeing half a file and stops nothing else, so + # an unfenced observation could land after a newer fenced one and replace + # it, and the inventory would then hold a reading older than the transition + # recorded beside it. One mutex over every write of these files, and the + # generation/operation comparison stays what it was for the callers that + # name one. + # + # IT IS TAKEN HERE AND NOT ABOVE THE OBSERVATION, because the observation + # runs `git status` and `git rev-list` in somebody's checkout and this lock + # is the whole workstation's (design decision 14, and the same argument that + # keeps `lane-reconcile` out of it): what must be serialized is the compare + # and the write, not the reading of a repository. + acquire_lock + if [ -n "$slt_g" ] || [ -n "$slt_op" ]; then + if ! lane_sidecar_schema_ok "$slt_root/lane-state.yaml"; then + release_lock + die "the worktree $slt_path was NOT recorded for lane $lane: its lifecycle snapshot is not a record this helper can read ($LSS_WHY), so the generation and operation this observation names cannot be compared with anything. Nothing was written. Upgrade this workstation's lanes-edit.sh if a newer tooling wrote it, or read the snapshot by hand." 1 + fi + slt_ng=""; slt_no=""; slt_ns="" + if [ -r "$slt_root/lane-state.yaml" ]; then + slt_ns="$(lane_sidecar_field "$slt_root/lane-state.yaml" state)" + slt_ng="$(lane_sidecar_field "$slt_root/lane-state.yaml" generation)" + slt_no="$(lane_sidecar_field "$slt_root/lane-state.yaml" operation)" + fi + slt_fence="" + [ -z "$slt_g" ] || [ "$slt_g" = "${slt_ng:-0}" ] || slt_fence="generation is ${slt_ng:-0} and --generation named $slt_g" + [ -z "$slt_op" ] || [ "$slt_op" = "${slt_no:-none}" ] || slt_fence="${slt_fence:+$slt_fence; }operation is ${slt_no:-none} and --operation named $slt_op" + # AND THE OPERATION MUST STILL BE OPEN (opensoft/openRepoTools#114 item 1). + # `SWAPPING -> SWAPPED` keeps the generation AND the operation by design — + # it is the same operation reaching its commit point, and a fence that + # moved under it would refuse the very finalizer entitled to write — so the + # two values alone accepted a poll from that operation AFTER it was + # finalized: a reading taken before the commit point, filed over the + # inventory the commit point closed, and nothing downstream could tell. Every + # other transition advances the generation, so `SWAPPED` is the one state in + # which a matching pair names a FINISHED operation. An observation of the + # lane's own, under no transition, is an unfenced `set-lane-tree`. + [ "$slt_ns" != SWAPPED ] || slt_fence="${slt_fence:+$slt_fence; }the lane is SWAPPED: operation ${slt_no:-none} reached its commit point and its inventory is closed" + if [ -n "$slt_fence" ]; then + release_lock + die "the worktree $slt_path was NOT recorded for lane $lane: $slt_fence. The lane moved while this observation was being made — a recovery advanced it, a second handoff did, or the operation it names was finalized — so filing this poll now would put a superseded reading where the current one belongs, and nothing downstream could tell. Nothing was written and the tree itself was not touched. Re-read the lane (lanes-edit.sh lane-reconcile $lane) before recording anything under this operation; an observation filed under no transition is set-lane-tree without --generation and --operation." 7 + fi + fi + # AND THE SIDECAR THAT IS THERE IS NOT WALKED OVER EITHER, for the same + # reason the snapshot is not: a record written by a newer tooling is one + # this helper cannot read, so it is not one this helper may replace. + if ! lane_sidecar_schema_ok "$slt_root/trees/$(tree_id_for "$slt_path").yaml"; then + release_lock + die "the worktree $slt_path was NOT recorded for lane $lane: its sidecar under $slt_root/trees is not a record this helper can read ($LSS_WHY), and a record it cannot read is one it cannot safely replace. Nothing was written. Upgrade this workstation's lanes-edit.sh if a newer tooling wrote it; if you know what wrote that file, move it aside by hand and re-run." 1 + fi + if lane_tree_put "$slt_root" "$lane" "$slt_path" "$slt_co" "$slt_b" "$slt_h" \ + "$slt_u" "$slt_d" "$slt_n" "$slt_w" "$slt_g" "$slt_op"; then + release_lock + LANES_INDEX_NUDGE_INV=1 # opensoft/openRepoTools#161: `cleanup` nudges the indexer + printf '%s\n' "$(tree_id_for "$slt_path")" + else + release_lock + die "the sidecar for $slt_path could not be written under $slt_root/trees (the shell's own error is above). The tree itself was not touched: this command reads worktrees and writes only its own record of them." 1 + fi + ;; + + # THE OBSERVATION, FROM THE ONE IMPLEMENTATION OF IT (Copilot round 5 on #97). + # `lane-handoff` polls the worktrees this reconciliation recomputes, and until + # this arm it made that observation ITSELF — a second implementation with its + # own error handling, in which a failed upstream lookup became `none` and a + # failed `log @{u}..` became `0`. One function answers both now: the handoff + # records what this prints, for its WRITERS section and for the sidecar alike, + # and `lane-reconcile` recomputes with the same code. It touches no lane, no + # register and no lock — it reads one path with git. + # + # 0 <branch><US><head><US><upstream><US><dirty><US><unpushed> + # 8 no checkout there: the path is gone, or git does not answer in it + # 1 git ANSWERED there and one of the reads FAILED, so nothing is printed + # 64 a usage error of this subcommand's own + lane-tree-now) + ltna="${1-}"; [ -n "$ltna" ] || die "usage: lane-tree-now <worktree path>" 64 + [ "$#" -le 1 ] || die "lane-tree-now takes one path: lane-tree-now <worktree path>" 64 + case "$ltna" in /*) : ;; *) die "lane-tree-now takes an ABSOLUTE path: a relative one means whatever the calling process's directory happens to be, and that is never the tree being asked about" 64 ;; esac + ltna_out=""; ltna_rc=0 + ltna_out="$(lane_tree_now "$ltna")" || ltna_rc=$? + case "$ltna_rc" in + 0) printf '%s\n' "$ltna_out" ;; + 1|2) exit 8 ;; + *) die "git answers in $ltna and one of the reads an observation is made of FAILED, so NOTHING is printed: a branch, a head, a status or an upstream that could not be read is never reported as a clean tree (R22, Amendment 7(d)). Read it by hand: git -C $ltna status" 1 ;; + esac + ;; + + # opensoft/openRepoTools#186, plan task T018 — THE LEGS A CHECKOUT'S + # `project.yaml` DECLARES, by path: `assembly_legs` above, which is the one + # reader every lane tool asks (`lane-worktrees`' sweep, report and `add`, and + # `lane-handoff`'s writer poll), so no two of them can read a triad two ways. + # It reads one file and touches no workspace, so it answers on a workstation + # with no register configured too (the dispatcher exempts it). + # + # 0 <repository><TAB><path as declared><TAB><where it is checked out>, a leg a line + # 8 no legs: no project.yaml there, or one naming no leg but the checkout itself + # 1 a project.yaml is there and could not be read — which is never "no legs" + # 64 a usage error of this subcommand's own + project-legs) + pla="${1-}"; [ -n "$pla" ] || die "usage: project-legs <checkout>" 64 + [ "$#" -le 1 ] || die "project-legs takes one directory: project-legs <checkout>" 64 + case "$pla" in /*) : ;; *) die "project-legs takes an ABSOLUTE path: a relative one means whatever the calling process's directory happens to be, and that is never the checkout being asked about" 64 ;; esac + pla_out=""; pla_rc=0 + pla_out="$(assembly_legs "$pla")" || pla_rc=$? + case "$pla_rc" in + 0) printf '%s\n' "$pla_out" ;; + 8) exit 8 ;; + *) die "${pla%/}/project.yaml is there and could not be read, so which legs that checkout declares is NOT known — which is not the same as none (R22, Amendment 7(d))" 1 ;; + esac + ;; + + lane-reconcile) + lane="${1-}"; [ -n "$lane" ] || die "usage: lane-reconcile <lane>" 64 + [ "$#" -le 1 ] || die "lane-reconcile takes one lane: lane-reconcile <lane>" 64 + check_lane_name "$lane" + log_sync + lane="$(canon_lane "$lane")" || exit 2 # Amendment 15 + lane_reconcile "$lane"; lrec_rc=$? + case "$lrec_rc" in + 0) : ;; + 8) exit 8 ;; + *) die "lane $lane could not be reconciled (exit $lrec_rc)" 1 ;; + esac + ;; + + # ---------- opensoft/openRepoTools#161: every inventoried worktree, as rows + # + # `worktree_rows` above, for one lane or every lane on this workstation, and + # the READ the `worktrees` table answers when `--index` is TYPED (Amendment + # 14(b)): `index_open worktrees` asks `lanes-index export --worktrees` for + # every `inventory:<Workstation>` source the store holds — this + # workstation's and any other that syncs into the same Postgres, which is the + # point of the table — and stderr says which was read: `read: index (<store>) + # at inventory:<ws> synced <UTC>` (and `(last error: <UTC> <why>)` after a + # source this workstation recorded one for, as `status` shows it), or + # `read: sources (index <why>)` and the sidecars answer, exactly as without + # the flag. NO ACT READS THIS: not + # `lane-reconcile`, not `lane-start`, not `lane-end`, not a sweep — each of + # them reads the sidecars and the disk, and this is a listing. + # + # Local by default, as `lanes` is: `--fetch` refreshes the register first. + # 0 rows (`--all`: with one PARTIAL line where the lane listing they were + # read through was not whole, #173) · 8 none · 2 a lane name refused + # (Amendment 15) · 64 usage · 1 a read failed + worktrees) + wt_lane=""; wt_all=0; wt_index=0; wt_fetch=0 + wt_usage="worktrees [<lane> | --all] [--index] [--fetch]" + while [ $# -gt 0 ]; do + case "$1" in + --all) wt_all=1; shift ;; + --index) wt_index=1; shift ;; + --fetch) wt_fetch=1; shift ;; + --) shift ;; + -*) die "unknown option '$1' for worktrees ($wt_usage)" 64 ;; + *) [ -z "$wt_lane" ] || die "worktrees takes ONE lane, or --all: $wt_usage" 64; wt_lane="$1"; shift ;; + esac + done + [ "$wt_all" = 0 ] || [ -z "$wt_lane" ] || die "worktrees takes ONE lane OR --all, not both: $wt_usage" 64 + [ -z "$wt_lane" ] || check_lane_name "$wt_lane" + [ "$wt_fetch" = 1 ] || LANES_NO_FETCH=1 + log_sync + if [ -n "$wt_lane" ]; then + wt_lane="$(canon_lane "$wt_lane")" || exit 2 # Amendment 15 + fi + if [ "$wt_index" = 1 ] && index_open worktrees; then + wt_out="$(awk -F"$US" -v l="$(lc "$wt_lane")" 'l == "" || tolower($3) == l' "$LANES_WT_IDX_DIR/worktrees" 2>/dev/null)" + [ -n "$wt_out" ] || exit 8 + printf '%s\n' "$wt_out" + else + wt_out=""; wt_rc=0 + wt_out="$(worktree_rows "$wt_lane")" || wt_rc=$? + case "$wt_rc" in + 0) : ;; + 8) exit 8 ;; + *) die "the lane listing the inventory is read through could not be read (exit $wt_rc). That is NOT 'no worktree is inventoried' (Amendment 7(d))." 1 ;; + esac + printf '%s\n' "$wt_out" + fi + ;; + + # opensoft/openRepoTools#162 — WHAT A HAND COMMIT OF A HANDOFF'S ATTACHMENTS + # WOULD STAGE THAT IS BYTECODE, asked BEFORE the commit. `commit_push` + # refuses such a pathspec for every write this file makes; attachments are + # committed by hand, so this is the same question for a person to ask first. + # 0 nothing in those paths would stage bytecode, a cache or an environment + # 2 something would: the paths on stdout, the offer on stderr - or git + # could not read what they would stage, which is never "clean" (#170 G13) + # 64 usage + pathspec-check) + [ "$#" -gt 0 ] || die "usage: pathspec-check <path>... (relative to the workspace repository $LANES_REPO)" 64 + pck_rc=0 + pck_out="$(bytecode_in_pathspec "$LANES_REPO" "$@")" || pck_rc=$? + if [ "$pck_rc" != 0 ]; then + note "git could not read what that pathspec would stage (a pathspec it cannot parse, or an index it cannot read), so whether it holds bytecode is unknown, and an unknown is never reported clean (opensoft/openRepoTools#170 G13)" + exit 2 + fi + if [ -n "$pck_out" ]; then + printf '%s\n' "$pck_out" + note "$(bytecode_refusal_text "$pck_out")" + exit 2 + fi + ;; + + *) + die "unknown subcommand '$cmd' (verify-row|set-row-state|append-row-status|replace-in-row|append-session-id|append-line|add-row|retire-rows|archive-rows|migrate-state-cells|commit|rename-lane|log|claim|release|who|history|swapped|session-start|guard|idle-holders|live-holder|window-session|transcript-holders|binding|request-handoff|session-lane|window-lane|lane-dir|lane-profile|lane-agent|lane-transcript|lane-last|workspace-root|last-session|forks|duplicate-holder|workstation|fetch-age|lanes|lane-groups|next-free|sibling-filter|resolve-repo|lane-objects|register-row|register-row-local|retired-identity|canon-lane|resolve-home|managed-projection|lane-state|set-lane-state|lane-trees|set-lane-tree|lane-tree-now|project-legs|lane-reconcile|lane-holders|legacy-restart-check|publish-handoff|restart-intent|set-restart-intent|worktrees|pathspec-check)" 2 + ;; +esac diff --git a/tests/pgcluster.py b/tests/pgcluster.py index 97871b78..4efc76f6 100644 --- a/tests/pgcluster.py +++ b/tests/pgcluster.py @@ -35,7 +35,9 @@ * `stoppable_cluster`, a cluster of the test's own, built like the session's, for the tests that stop the database: `stop()` is a fast shutdown, SIGINT and a wait, and `start_again()` starts it on the same - data and socket directories. + data and socket directories; `start_again(standby=True)` starts it in + recovery, with `standby.signal`, and fails unless `pg_is_in_recovery()` + is true, and the next plain start removes the file (T229d). THE TEMPLATES (T227; the test plan's section 3.1, "The templates"). `tmpl` is built on each cluster by P8's bootstrap, `lanes-index bootstrap --no-passwords` @@ -89,18 +91,26 @@ starts it again on the same directories and runs `SELECT 1`. It exits 0 when each named smoke passes, 1 when one fails or there is no engine, and 2 for a name it does not know. + +PYTEST_DONT_REWRITE (T229s): no assert here is rewritten, whatever hook loads +this plugin, so an assert added later reports its own message and no +operand's value, a tool's text among them. """ from __future__ import annotations import os +import queue import re +import select import shutil import signal +import socket import stat import subprocess import sys import tempfile +import threading import time from pathlib import Path from typing import Dict, List, Optional, Tuple @@ -201,22 +211,32 @@ def required(environ=os.environ) -> bool: # ------------------------------------------------------------ the binaries -def check_bindir(bindir: Path) -> Optional[str]: - """None where `bindir` holds the four tools at major 16, else why not.""" +def check_bindir(bindir: Path, shown: Optional[str] = None) -> Optional[str]: + """None where `bindir` holds the four tools at major 16, else why not. + The reason shows no text a tool printed (T229o; lane 3's ruling + 6949488277 on lane 2's pre-review RV9-38 of P09, B2): a `--version` + that does not say major 16 is shown by its exit and counts, and + `shown` names the directory in place of its path where that path is a + tool's output, `pg_config --bindir`'s.""" + where = str(bindir) if shown is None else shown if not bindir.is_dir(): - return f"{bindir} is not a directory" + return f"{where} is not a directory" missing = [t for t in TOOLS if not os.access(str(bindir / t), os.X_OK) or (bindir / t).is_dir()] if missing: - return f"{bindir} has no {', '.join(missing)}" + return f"{where} has no {', '.join(missing)}" for tool in TOOLS: + label = str(bindir / tool) if shown is None else f"{shown}'s {tool}" try: - said = subprocess.run([str(bindir / tool), "--version"], stdin=DEVNULL, capture_output=True, - text=True, timeout=20, check=False).stdout.strip() + ran = subprocess.run([str(bindir / tool), "--version"], stdin=DEVNULL, capture_output=True, + text=True, timeout=20, check=False) except (OSError, subprocess.SubprocessError) as exc: - said = f"<{exc}>" - m = re.search(r"\(PostgreSQL\) (\d+)", said) + return f"{label} --version did not run: {type(exc).__name__}" + version = ran.stdout or "" + m = re.search(r"\(PostgreSQL\) (\d+)", version) if not m or int(m.group(1)) != MAJOR: - return f"{bindir / tool} is not PostgreSQL {MAJOR}: it says {said!r}" + return (f"{label} is not PostgreSQL {MAJOR}: its --version exited {ran.returncode} " + f"and names {'another major' if m else 'no PostgreSQL major'}; " + f"{len(version.splitlines())} line(s), none shown") return None @@ -231,14 +251,15 @@ def find_bindir(environ=os.environ) -> Tuple[Optional[Path], str]: pg_config = shutil.which("pg_config", path=environ.get("PATH", os.defpath)) if pg_config: try: - out = subprocess.run([pg_config, "--bindir"], stdin=DEVNULL, capture_output=True, - text=True, timeout=20, check=False).stdout.strip() - except (OSError, subprocess.SubprocessError): - out = "" - why = check_bindir(Path(out)) if out else "it printed nothing" + ran = subprocess.run([pg_config, "--bindir"], stdin=DEVNULL, capture_output=True, + text=True, timeout=20, check=False) + out, how = (ran.stdout or "").strip(), f"exited {ran.returncode}" + except (OSError, subprocess.SubprocessError) as exc: + out, how = "", f"did not run ({type(exc).__name__})" + why = check_bindir(Path(out), shown="the directory it printed") if out else "it printed nothing" if why is None: return Path(out), f"`{pg_config} --bindir`" - tried.append(f"`{pg_config} --bindir` says {out or '-'}, and {why}") + tried.append(f"`{pg_config} --bindir` {how}, and {why}") else: tried.append("no pg_config on PATH") why = check_bindir(DEBIAN_BIN) @@ -402,7 +423,15 @@ def sweep_stale() -> List[str]: class ClusterError(Exception): - pass + """A cluster's failure. Its text shows exits and counts, never a line of + a tool's output or of the server's log (T229k; T229l). `could_not_bind` + is True where a start failed and the server log's last five lines name + `bind` (T229l): what `TLSCluster.launch` read in the text before, kept as + a flag, not as text.""" + + def __init__(self, *args, could_not_bind: bool = False) -> None: + super().__init__(*args) + self.could_not_bind = could_not_bind class Bootstrap: @@ -423,16 +452,71 @@ def _masked(text: str) -> str: return _SECRET_FIELD.sub(lambda m: m.group(1) + "<password>", text or "") -def _tail(proc: subprocess.CompletedProcess, size: int = 800) -> str: - """A command's last words, stdout then stderr, on one line.""" - said = " | ".join(line.strip() for line in f"{proc.stdout or ''}\n{proc.stderr or ''}".splitlines() - if line.strip()) - return said[-size:] or "<nothing>" - - -def _client_env(host: Path, user: str, dbname: str, appname: str, bindir: Path) -> dict: +def _counted(proc) -> str: + """What a failure message here shows of a tool's run (T229m; lane 3's + ruling 6949488277 on lane 2's pre-review RV9-38 of P09, B2): its exit + and each stream's count of lines. No line of either is shown: initdb's, + git's, openssl's, psql's and lanes-index's own text can echo a + statement, a password-file line, a path or a server's message.""" + parts = [f"exit {proc.returncode}"] + for name in ("stdout", "stderr"): + said = getattr(proc, name, None) + if isinstance(said, bytes): + said = said.decode("utf-8", "replace") + parts.append(f"{name}: {len(said.splitlines()) if isinstance(said, str) else 0} line(s)") + return "; ".join(parts) + "; no line of either is shown" + + +#: An error line of psql's stderr, after psql's own `psql:<stdin>:1: ` where +#: it is there, and its SQLSTATE where psql prints one (`ERROR: 42P01: ...`, +#: at `VERBOSITY` verbose; at the default, psql prints none). The SQLSTATE is +#: taken only from that form on one line (T229p; lane 2's pre-review RV9-38 of +#: P09, N1): `ERROR:`, spaces or tabs, never a newline, then five of +#: `[0-9A-Z]` with a digit among them, as every SQLSTATE of PostgreSQL's and +#: of the product's has, then `:`. So no five-capital word, such as `SYNTH:`, +#: nor the head of a line after an `ERROR:` that ends its own, is shown as one +#: (T229w). Its limit (T229r): at psql's default verbosity, a message +#: whose first word is five of `[0-9A-Z]` with a digit and a colon would be +#: shown as a SQLSTATE. PostgreSQL's primary messages begin in lower case, and +#: psql's echo of a statement is a `LINE n:` line, which never matches. +_PSQL_ERROR = re.compile(r"^(?:psql:\S*: )?(?:ERROR|FATAL|PANIC):", re.M) +_SQLSTATE = re.compile(r"^(?:psql:\S*: )?(?:ERROR|FATAL|PANIC):[ \t]+(?=[A-Z]{0,4}[0-9])([0-9A-Z]{5}):", + re.M) +#: A line of the server's log at ERROR, FATAL or PANIC (T229l; anchored by +#: T229v, lane 2's pre-review RV9-41 of P09, N3): at the line's start, after +#: one of the fixture's own `log_line_prefix` forms where it is there, the +#: severity as the server writes it, then `:` and two spaces. The forms are +#: the default, `%m [%p] ` (its time's three words and the pid in +#: brackets), and `%p ` (the pid and a space), which managed sets on its +#: clusters (T229x; lane 2's targeted check RV9-43 of P09 at `94a40564`, NIT +#: C). So a logged statement whose text holds `ERROR:` is not counted; a +#: continuation line of a logged statement that itself begins `ERROR: ` +#: would be. It is a count only: no line is shown. +_LOG_SEVERE = re.compile(r"^(?:\S+ \S+ \S+ \[\d+\] |\d+ )?(?:ERROR|FATAL|PANIC): ") + + +def _psql_failed(user: str, dbname: str, proc: subprocess.CompletedProcess) -> str: + """What `Cluster.psql`'s `ClusterError` says when psql fails (T229k; + lane 3's ruling 6947252648 on lane 2's pre-review RV9-37 of P09 at + `d9a1f2bf`, S4): psql's exit, the SQLSTATE where its text has one, and + its stderr's counts. No line of psql's text is shown, since psql echoes + a failed statement (`LINE 1: ...`), and a role's statement can hold its + password. Nothing of the text is kept on the exception: no caller needs + it (CX-36's scan of every caller on `main` and at P09's head).""" + text = proc.stderr if isinstance(proc.stderr, str) else "" + lines = text.splitlines() + states = sorted(set(_SQLSTATE.findall(text))) + errors = len(_PSQL_ERROR.findall(text)) + return (f"psql as {user} on {dbname} exited {proc.returncode}: " + f"{'SQLSTATE ' + ', '.join(states) if states else 'no SQLSTATE in its text'}; " + f"stderr: {len(lines)} line(s), {errors} of them ERROR, FATAL or PANIC lines; " + f"no line of it is shown") + + +def _client_env(host: Path, user: str, dbname: str, appname: str, bindir: Path, + port: int = PORT) -> dict: env = _without_pg() - env.update(PGHOST=str(host), PGPORT=str(PORT), PGUSER=user, PGDATABASE=dbname, + env.update(PGHOST=str(host), PGPORT=str(port), PGUSER=user, PGDATABASE=dbname, PGAPPNAME=appname, PGCONNECT_TIMEOUT="10", LC_ALL="C", PATH=_engine_first(bindir, env.get("PATH", os.defpath))) return env @@ -459,6 +543,9 @@ def __init__(self, bindir: Path, template_sql="", imported: bool = False) -> Non for an empty `tmpl` (the smokes' default). `imported` builds `tmpl_imported` too.""" self.bindir, self.template_sql, self.imported = bindir, template_sql, imported + #: The port (T229): it names the socket file, and a TLS cluster's TCP + #: listener uses it too. `listen` and `settings` are `prepare()`'s. + self.port, self.listen, self.settings = PORT, "", [] self.root: Optional[Path] = None self.proc: Optional[subprocess.Popen] = None self.count, self.timings = 0, {} @@ -489,17 +576,48 @@ def psql(self, sql: str, dbname: str = "postgres", user: str = SUPERUSER, argv += ["-v", f"{name}={value}"] proc = subprocess.run([*argv, "-f", "-"], input=sql, capture_output=True, text=True, timeout=120, env=_client_env(self.root, user, dbname, appname, - self.bindir), + self.bindir, self.port), check=False) if check and proc.returncode != 0: - raise ClusterError(f"psql as {user} on {dbname} exited {proc.returncode}: {proc.stderr.strip()}") + # T229q (lane 2's pre-review RV9-38 of P09, N2): the message is + # made, then psql's run is dropped, so no stream of it stays in + # this frame, which the raise's traceback keeps (`--showlocals`). + failed = _psql_failed(user, dbname, proc) + del proc + raise ClusterError(failed) return proc def log_tail(self) -> str: + """What a failure message shows of the server's log (T229l; lane 3's + ruling 6949488277 on lane 2's pre-review RV9-38 of P09, B2): its + count of lines and of ERROR, FATAL or PANIC lines. No line of it is + shown: under `log_statement = 'all'` a role's statement, its + password among it, is a line of it.""" try: - return " | ".join((self.root / "server.log").read_text().splitlines()[-5:]) + lines = (self.root / "server.log").read_text(errors="replace").splitlines() except OSError: - return "<no log>" + return "server.log: not read" + severe = sum(1 for line in lines if _LOG_SEVERE.search(line)) + return (f"server.log: {len(lines)} line(s), {severe} of them ERROR, FATAL or PANIC " + f"lines; no line of it is shown") + + def _could_not_bind(self) -> bool: + """Whether the server log's last five lines name `bind`, in any case + (T229l): what `TLSCluster.launch` looked for in a failed start's text + when that text held those lines.""" + try: + last = (self.root / "server.log").read_text(errors="replace").splitlines()[-5:] + except OSError: + return False + return any("bind" in line.lower() for line in last) + + def _start_failed(self, what: str) -> ClusterError: + """A failed start's error: `what`, the log's counts, and whether its + last lines name a bind, as words and as `could_not_bind` (T229l).""" + bind = self._could_not_bind() + return ClusterError(f"{what}: {self.log_tail()}" + f"{'; its last 5 lines name a bind' if bind else ''}", + could_not_bind=bind) def ready(self) -> bool: """The postmaster's own `ready` status, line 8 of postmaster.pid: what pg_ctl -w reads.""" @@ -515,7 +633,7 @@ def start(self) -> None: _SWEPT.extend(sweep_stale()) self.root = Path(tempfile.mkdtemp(prefix=PREFIX, dir=SOCKET_PARENT)) # mode 0700 (self.root / "owner").write_text(f"{os.getpid()} {_ticks(os.getpid())}\n") - sock = self.root / f".s.PGSQL.{PORT}" + sock = self.root / f".s.PGSQL.{self.port}" if len(os.fsencode(str(sock))) > SOCKET_MAX: raise ClusterError(f"the socket path {sock} is over {SOCKET_MAX} bytes") t1 = time.monotonic() @@ -524,8 +642,9 @@ def start(self) -> None: capture_output=True, text=True, env=self.server_env(), timeout=120, check=False) if init.returncode != 0: - raise ClusterError(f"initdb exited {init.returncode}: {init.stderr.strip()}") + raise ClusterError(f"initdb failed: {_counted(init)}") t2 = time.monotonic() + self.prepare() self.launch() t3 = time.monotonic() self.build_template() @@ -570,7 +689,7 @@ def admin_service(self, database: str) -> str: name, path = f"fx_{database}", home / ".pg_service.conf" text = path.read_text(encoding="utf-8") if path.exists() else "" if f"[{name}]\n" not in text: - text += (f"[{name}]\nhost={self.root}\nport={PORT}\nuser={SUPERUSER}\n" + text += (f"[{name}]\nhost={self.root}\nport={self.port}\nuser={SUPERUSER}\n" f"dbname={database}\n\n") path.write_text(text, encoding="utf-8") path.chmod(0o600) @@ -652,15 +771,23 @@ def make_logins(self, database: str) -> None: ["login", "add", "--dump-job", "--admin-service", service]): code, out, err = self.lanes_index_tty(argv) if code != 0: - raise ClusterError(f"`lanes-index {' '.join(argv[:3])}` through the admin service " - f"on {database} exited {code}, so the fixture has no logins " - f"(lane 1's T110, L1-A8, builds `login`): " - f"{_masked(out)[-400:]} | {_masked(err)[-400:]}") + failed = (f"`lanes-index {' '.join(argv[:3])}` through the admin service " + f"on {database} exited {code}, so the fixture has no logins " + f"(lane 1's T110, L1-A8, builds `login`): stdout: " + f"{len(out.splitlines())} line(s), " + f"{len(PASSWORD_LINE.findall(out))} of them password-file " + f"lines; stderr: {len(err.splitlines())} line(s); no line of " + f"either is shown") + del out, err + raise ClusterError(failed) self.passwords.update(PASSWORD_LINE.findall(out)) + # T229u (RV9-41, N1): `login add`'s output, its password-file lines + # with their clear passwords, stays in no frame a later raise keeps. + del out, err names = ", ".join(f"'{login}'" for login in FX_LOGINS) can = self.psql(f"SELECT rolname FROM pg_catalog.pg_roles WHERE rolcanlogin AND " f"rolname IN ({names}) ORDER BY 1;").stdout.split() - missing = sorted(set(FX_LOGINS) - set(can)) + sorted(set(FX_LOGINS) - set(self.passwords)) + missing = [login for login in FX_LOGINS if login not in can or login not in self.passwords] if missing: raise ClusterError(f"after `login add`, these logins cannot log in or printed no " f"password line: {', '.join(missing)}") @@ -689,7 +816,7 @@ def bootstrap(self, database: str, label: str) -> str: raise ClusterError(f"`lanes-index bootstrap --no-passwords` through the admin " f"service on {database} exited {proc.returncode}, so the " f"template has no register (lane 1's T109, L1-A7, builds the " - f"bootstrap): {_tail(proc)}") + f"bootstrap): {_counted(proc)}") return proc.stdout def build_imported(self) -> None: @@ -717,7 +844,7 @@ def build_imported(self) -> None: if proc.returncode != 0: self.imported_problem = (f"`lanes-index import --at {register.c}` as {user} " f"exited {proc.returncode} (lane 1's T115, L1-A13, " - f"builds it): {_tail(proc)}") + f"builds it): {_counted(proc)}") else: self.imported_problem = self._imported_check(register.c) except (ClusterError, OSError, subprocess.SubprocessError) as exc: @@ -745,15 +872,23 @@ def _imported_check(self, commit: str) -> Optional[str]: dbname=IMPORTED).stdout.strip() wanted = f"0:import:{commit}|0|files:absent" if said != wanted: - return (f"`lanes-index import --at {commit}` exited 0, and {IMPORTED} reads " - f"{said!r} (journal|head|switch), not {wanted!r}") + got = said.split("|") + differ = [part for i, part in enumerate(("journal", "head", "switch")) + if len(got) != 3 or got[i] != wanted.split("|")[i]] + return (f"`lanes-index import --at {commit}` exited 0, and {IMPORTED}'s " + f"{', '.join(differ)} differ from {wanted!r} (journal|head|switch); none " + f"of what it reads is shown (T229n)") return None + def prepare(self) -> None: + """Between `initdb` and the first start: nothing here; T229's TLS and + counting clusters set their files and settings.""" + def launch(self) -> None: """`postgres` by `Popen` on this cluster's directories, and wait until it is ready.""" - argv = [self.tool("postgres"), "-D", str(self.root / "data"), "-p", str(PORT), - "-c", "listen_addresses=", "-c", f"unix_socket_directories={self.root}"] - for setting in FAST: + argv = [self.tool("postgres"), "-D", str(self.root / "data"), "-p", str(self.port), + "-c", f"listen_addresses={self.listen}", "-c", f"unix_socket_directories={self.root}"] + for setting in [*FAST, *self.settings]: argv += ["-c", setting] with open(self.root / "server.log", "ab") as log: self.proc = subprocess.Popen(argv, stdin=DEVNULL, stdout=log, stderr=subprocess.STDOUT, @@ -761,9 +896,9 @@ def launch(self) -> None: end = time.monotonic() + DEADLINE while not self.ready(): if self.proc.poll() is not None: - raise ClusterError(f"postgres exited {self.proc.returncode} starting: {self.log_tail()}") + raise self._start_failed(f"postgres exited {self.proc.returncode} starting") if time.monotonic() > end: - raise ClusterError(f"postgres was not ready in {DEADLINE:.0f} s: {self.log_tail()}") + raise self._start_failed(f"postgres was not ready in {DEADLINE:.0f} s") time.sleep(POLL) def stop(self) -> None: @@ -777,11 +912,34 @@ def stop(self) -> None: raise ClusterError(f"postgres did not stop in {DEADLINE:.0f} s after SIGINT: " f"{self.log_tail()}") from None - def start_again(self) -> None: - """Start the stopped cluster on the same data and socket directories.""" + def start_again(self, standby: bool = False) -> None: + """Start the stopped cluster on the same data and socket directories. + With `standby` (T229d; TP:5382-5387, check 11's restart in recovery; + lane 3's batch 11 (1), which corrects batch 7's ruling 2), it starts + in recovery: `standby.signal` is written in the data directory, the + start polls `postmaster.pid` for `ready`, as every start does, and + then fails unless `pg_is_in_recovery()` is true. A hot standby writes + `ready`, never `standby`: PostgreSQL 16 writes `standby` only with + `hot_standby` off, where no session connects, and a plain start + writes `ready` too, so only the query proves the recovery. A start + without it removes the file first, so the cluster comes back a + primary. T224 only calls it.""" if self.proc is not None and self.proc.poll() is None: raise ClusterError("the cluster is running, so it cannot be started again") + signal_file = self.root / "data" / "standby.signal" + if standby: + signal_file.write_text("", encoding="utf-8") + elif signal_file.exists(): + signal_file.unlink() self.launch() + if standby: + answer = self.psql("SELECT pg_is_in_recovery();", check=False) + if answer.returncode != 0 or answer.stdout.strip() != "t": + said = (_psql_failed(SUPERUSER, "postgres", answer) if answer.returncode != 0 else + "f" if answer.stdout.strip() == "f" else + f"neither t nor f: {len(answer.stdout.splitlines())} line(s), none shown") + raise ClusterError(f"the start with standby.signal is ready but not in recovery: " + f"pg_is_in_recovery() answered {said}: {self.log_tail()}") def new_database(self, template: str = TEMPLATE) -> str: """`CREATE DATABASE t_<n> TEMPLATE <template>`, then, where the @@ -824,14 +982,14 @@ class Database: """One test's database, and how to reach it as each role.""" def __init__(self, cluster: Cluster, name: str) -> None: - self.cluster, self.name, self.host, self.port = cluster, name, cluster.root, PORT + self.cluster, self.name, self.host, self.port = cluster, name, cluster.root, cluster.port self.psql_bin = cluster.tool("psql") def url(self, user: str = SUPERUSER) -> str: - return f"postgresql://{user}@{quote(str(self.host), safe='')}:{PORT}/{self.name}" + return f"postgresql://{user}@{quote(str(self.host), safe='')}:{self.port}/{self.name}" def env(self, user: str = SUPERUSER, appname: str = "pytest") -> dict: - return _client_env(self.host, user, self.name, appname, self.cluster.bindir) + return _client_env(self.host, user, self.name, appname, self.cluster.bindir, self.port) def psql(self, sql: str, user: str = SUPERUSER, check: bool = True) -> subprocess.CompletedProcess: return self.cluster.psql(sql, dbname=self.name, user=user, check=check) @@ -855,10 +1013,14 @@ def session(self, user: str = SUPERUSER, appname: str = "pytest") -> subprocess. #: whose name differs from its lane's in case, and a lane with no log). def _test7_seed() -> Dict[str, str]: """C'S FILES BEFORE THE OPERATOR'S WRITE (T227b): T211's `SEED`, copied - from `tests/test_sql_register_import.py` at line W3a's `4bfef75c` byte - for byte (its lines 97-104, 112-115, 118-164 and 185-226), so that the - template holds test 7's register on a branch without that module. Each - copy must stay equal to the other until one imports it from here.""" + from `tests/test_sql_register_import.py` at line W3a's `4bfef75c` (its + lines 97-104, 112-115, 118-164 and 185-226), so that the template holds + test 7's register on a branch without that module. It is that `SEED` + byte for byte but for one line, which T227c adds after + `TAKE_LINES["hold-no-utc"]`: its holder's `HOLD RELEASED`, which T211n's + `CutoverRegister` appends by `append-line` before its import instead + (`HOLD_NO_UTC_RELEASE`). Each copy must stay equal to the other, but for + that line, until one imports it from here.""" UUID_A1 = "aaaaaaaa-0001-4000-8000-00000000a001" UUID_A2 = "aaaaaaaa-0003-4000-8000-00000000a003" UUID_B1 = "bbbbbbbb-0001-4000-8000-00000000b001" @@ -1050,7 +1212,7 @@ def __init__(self, root: Path, bindir: Path) -> None: f"repository: {self.origin}\npath: {self.ws}\n", encoding="utf-8") self.env["LANES_REPO"] = str(self.wip) self._run_ok(["bash", str(LANES_EDIT), *TEST7_NOTE], LANES_LANE=TEST7_OPERATOR) - self.c = self.git("rev-parse", "origin/main") + self.c = self.commit_of("origin/main") def run(self, argv: List[str], cwd: Optional[Path] = None, timeout: float = 120, **env: str) -> subprocess.CompletedProcess: @@ -1061,8 +1223,12 @@ def run(self, argv: List[str], cwd: Optional[Path] = None, timeout: float = 120, def _run_ok(self, argv: List[str], **env: str) -> str: proc = self.run(argv, **env) if proc.returncode != 0: - raise ClusterError(f"{' '.join(argv[:3])} exited {proc.returncode} building test 7's " - f"fixture register: {_tail(proc)}") + # T229t (RV9-41, B1): pytest 8.3.4 prints a long entry's locals as + # the arguments of a function with **kw, so no run stays here. + failed = (f"{' '.join(argv[:3])} exited {proc.returncode} building test 7's " + f"fixture register: {_counted(proc)}") + del proc + raise ClusterError(failed) return proc.stdout.strip() def git(self, *args: str, data: Optional[bytes] = None) -> str: @@ -1070,11 +1236,24 @@ def git(self, *args: str, data: Optional[bytes] = None) -> str: proc = subprocess.run(["git", *args], cwd=str(self.wip), env=self.env, input=data, capture_output=True, timeout=120, check=False) if proc.returncode != 0: - raise ClusterError(f"git {' '.join(args[:2])} exited {proc.returncode} building test " - f"7's fixture register: " - f"{proc.stderr.decode('utf-8', 'replace').strip()[-400:]}") + # T229t (RV9-41, B1): as `_run_ok`, for a function with *args. + failed = (f"git {' '.join(args[:2])} exited {proc.returncode} building test " + f"7's fixture register: {_counted(proc)}") + del proc + raise ClusterError(failed) return proc.stdout.decode("utf-8", "replace").strip() + def commit_of(self, ref: str) -> str: + """`git rev-parse <ref>` in the operator lane's checkout: a commit + id, or a ClusterError that shows none of git's text (T229m), since + the id is shown in `imported_problem` and at the run's foot.""" + said = self.git("rev-parse", ref) + if not re.fullmatch(r"[0-9a-f]{40}(?:[0-9a-f]{24})?", said): + raise ClusterError(f"git rev-parse {ref} exited 0 and printed no commit id building " + f"test 7's fixture register: {len(said.splitlines())} line(s), " + f"none of them shown") + return said + def configuration(self, cluster: "Cluster", database: str, user: str) -> Path: """The operator's 0600 configuration, outside every work tree: `mode=index`, `register_url=` as `user` and `reader_url=` as the @@ -1108,6 +1287,579 @@ def import_at(self, cluster: "Cluster", database: str, LANES_LANE=TEST7_OPERATOR) +# ------------------------------------------------------------ section 5.6's clusters (T229) +#: THE TLS CLUSTER'S `pg_hba.conf`, first match wins: the admin's socket by +#: trust; any TCP connect without TLS rejected (the fixture's model of +#: FR-011's server half, R09); TLS on loopback by SCRAM-SHA-256. +TLS_HBA = ("local all all trust\n" + "hostnossl all all 0.0.0.0/0 reject\n" + "hostnossl all all ::/0 reject\n" + "hostssl all all 127.0.0.1/32 scram-sha-256\n") + +#: The test CA's `openssl` configuration: no system `openssl.cnf` is read. +CA_CONFIG = ("[req]\ndistinguished_name = dn\nprompt = no\nx509_extensions = v3_root\n[dn]\n" + "CN = openRepoTools test root\n[v3_root]\nbasicConstraints = critical,CA:TRUE\n" + "keyUsage = critical,keyCertSign,cRLSign\nsubjectKeyIdentifier = hash\n") +CA_INTERMEDIATE = ("basicConstraints = critical,CA:TRUE,pathlen:0\nkeyUsage = critical,keyCertSign," + "cRLSign\nsubjectKeyIdentifier = hash\nauthorityKeyIdentifier = keyid\n") +CA_LEAF = ("basicConstraints = critical,CA:FALSE\nkeyUsage = critical,digitalSignature\n" + "extendedKeyUsage = serverAuth\nsubjectAltName = DNS:localhost,IP:127.0.0.1\n" + "subjectKeyIdentifier = hash\nauthorityKeyIdentifier = keyid\n") + + +def _openssl(args: List[str], cwd: Path) -> None: + env = {k: v for k, v in os.environ.items() if not k.startswith("OPENSSL_")} + proc = subprocess.run(["openssl", *args], cwd=str(cwd), stdin=DEVNULL, capture_output=True, + text=True, env=env, timeout=60, check=False) + if proc.returncode != 0: + raise ClusterError(f"openssl {' '.join(args[:2])} failed: {_counted(proc)}") + + +def make_test_ca(directory: Path) -> Dict[str, Path]: + """THE TEST CA (T229; [X: hosting]): a chain, as the install's private CA + issues the endpoint's certificate, made by `openssl` with P-256 keys for + two days: a root, an intermediate and a leaf for `localhost` and + `127.0.0.1`. `chain` holds the leaf and the intermediate, as the + install's `tls.crt` does; `root` alone is what `sslrootcert=` names.""" + directory.mkdir(mode=0o700, parents=True, exist_ok=True) + (directory / "ca.cnf").write_text(CA_CONFIG, encoding="utf-8") + (directory / "int.ext").write_text(CA_INTERMEDIATE, encoding="utf-8") + (directory / "leaf.ext").write_text(CA_LEAF, encoding="utf-8") + key = ["-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:P-256", "-nodes"] + _openssl(["req", "-x509", "-config", "ca.cnf", *key, "-keyout", "root.key", "-out", "root.crt", + "-days", "2"], directory) + for name, subject, issuer, serial in (("int", "openRepoTools test intermediate", "root", "2"), + ("leaf", "localhost", "int", "3")): + _openssl(["req", "-new", "-config", "ca.cnf", *key, "-keyout", f"{name}.key", "-out", + f"{name}.csr", "-subj", f"/CN={subject}"], directory) + _openssl(["x509", "-req", "-in", f"{name}.csr", "-CA", f"{issuer}.crt", "-CAkey", + f"{issuer}.key", "-set_serial", serial, "-days", "2", "-extfile", f"{name}.ext", + "-out", f"{name}.crt"], directory) + for name in ("root.key", "int.key", "leaf.key"): + (directory / name).chmod(0o600) + chain = directory / "chain.crt" + chain.write_bytes((directory / "leaf.crt").read_bytes() + (directory / "int.crt").read_bytes()) + return {"root": directory / "root.crt", "chain": chain, "leaf": directory / "leaf.crt", + "key": directory / "leaf.key"} + + +def scram_verifier(password: str, iterations: int = 4096) -> str: + """A SCRAM-SHA-256 verifier for `password`, computed here as lane 1's + `register_scram_verifier` and psql's `\\password` compute it (RFC 5802, + RFC 7677), so no statement or log holds the password.""" + import base64 + import hashlib + import hmac + import secrets + salt = secrets.token_bytes(16) + salted = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, iterations) + client = hmac.new(salted, b"Client Key", hashlib.sha256).digest() + server = hmac.new(salted, b"Server Key", hashlib.sha256).digest() + + def b64(raw: bytes) -> str: + return base64.b64encode(raw).decode("ascii") + return (f"SCRAM-SHA-256${iterations}:{b64(salt)}${b64(hashlib.sha256(client).digest())}:" + f"{b64(server)}") + + +def _free_port() -> int: + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as probe_socket: + probe_socket.bind(("127.0.0.1", 0)) + return probe_socket.getsockname()[1] + + +class TLSCluster(Cluster): + """SECTION 5.6'S TLS CLUSTER (T229): a cluster of its own, built like the + session's (its template, its logins), that also listens on 127.0.0.1 at + a free port, with `ssl=on`, `ssl_min_protocol_version = TLSv1.3` (CNPG's + default), the test CA's chain, and `TLS_HBA`. The admin keeps its + socket. `leaf_only` serves the leaf without the intermediate (T230's + `[leaf-only]`). At its start it clones one database, `database_name`. + Clients use lane 1's conninfo form, `sslmode=verify-full` with the root + alone as `sslrootcert=`; the logins authenticate by the SCRAM verifiers + `login add` set (T228).""" + + def __init__(self, bindir: Path, template_sql="", imported: bool = False, + leaf_only: bool = False) -> None: + super().__init__(bindir, template_sql, imported) + self.leaf_only = leaf_only + #: True while `start_again` runs, so `launch` keeps the port (T229h). + self.restarting = False + self.root_cert: Optional[Path] = None + self.database_name: Optional[str] = None + self.labels: Dict[str, str] = {} + + def prepare(self) -> None: + self.tls = make_test_ca(self.root / "tls") + self.root_cert = self.tls["root"] + (self.root / "data" / "pg_hba.conf").write_text(TLS_HBA, encoding="utf-8") + self.port, self.listen = _free_port(), "127.0.0.1" + self._tls_settings() + + def _tls_settings(self) -> None: + served = self.tls["leaf"] if self.leaf_only else self.tls["chain"] + self.settings = ["ssl=on", f"ssl_cert_file={served}", f"ssl_key_file={self.tls['key']}", + "ssl_min_protocol_version=TLSv1.3", "password_encryption=scram-sha-256"] + + def start_again(self, leaf_only: Optional[bool] = None, standby: bool = False) -> None: + """The start options T229 names: start the stopped cluster again on + the same directories and port, serving the leaf alone where + `leaf_only` is True, or the chain again where it is False; and, with + `standby`, in recovery, `Cluster.start_again`'s (T229d; T224's + `[in-recovery]`).""" + if leaf_only is not None: + self.leaf_only = leaf_only + self._tls_settings() + self.restarting = True + try: + super().start_again(standby=standby) + finally: + self.restarting = False + + def launch(self) -> None: + """The start, with a new free port where another process took the + one chosen before the postmaster bound it: at the first start only. + A restart (`start_again`) keeps the port its clients and + configurations were given, so a bind failure there is raised, never + moved past (T229h). A bind failure is the error's `could_not_bind`, + since its text holds no line of the log (T229l).""" + for attempt in range(3): + try: + return super().launch() + except ClusterError as exc: + if attempt == 2 or self.restarting or not exc.could_not_bind: + raise + self.port = _free_port() + + def start(self) -> None: + super().start() + self.database_name = self.new_database() + + def client_env(self, user: str = FX_WRITER, dbname: Optional[str] = None, + appname: str = "pytest") -> dict: + """A client's environment for `user` over TLS: `host=localhost` for + the name check and `hostaddr=127.0.0.1`, so one connect (section + 5.6), `verify-full`, the root alone, and the login's password file.""" + env = _without_pg() + env.update(PGHOST="localhost", PGHOSTADDR="127.0.0.1", PGPORT=str(self.port), PGUSER=user, + PGDATABASE=dbname or self.database_name, PGSSLMODE="verify-full", + PGSSLROOTCERT=str(self.root_cert), PGPASSFILE=str(self.passfile(user)), + PGAPPNAME=appname, PGCONNECT_TIMEOUT="10", LC_ALL="C", + PATH=_engine_first(self.bindir, env.get("PATH", os.defpath))) + return env + + def url(self, user: str = FX_WRITER, dbname: Optional[str] = None) -> str: + """Lane 1's URL form for `user` (Y:2326), at 127.0.0.1, since its six + URL parameters hold no `hostaddr`.""" + return (f"postgresql://{user}@127.0.0.1:{self.port}/{dbname or self.database_name}" + f"?sslmode=verify-full&sslrootcert={self.root_cert}") + + def label_of(self, dbname: Optional[str] = None) -> Optional[str]: + return self.labels.get(dbname or self.database_name, self.label) + + def configuration(self, directory: Path, database: Optional[str] = None, + mode: str = "index") -> Path: + """A 0600 `lanes-index.conf` in `directory`, naming `database` (by + default `database_name`): `register_url=` as `lanes_w_fx` and + `reader_url=` as `lanes_r_fx`, each with its password file, and the + database's switch label as `register_label=`.""" + directory.mkdir(mode=0o700, parents=True, exist_ok=True) + path = directory / "lanes-index.conf" + path.write_text("\n".join([ + f"mode={mode}", f"register_url={self.url(FX_WRITER, database)}", + f"register_passfile={self.passfile(FX_WRITER)}", f"reader_url={self.url(FX_READER, database)}", + f"reader_passfile={self.passfile(FX_READER)}", f"register_label={self.label_of(database)}", + "register_schema=lanes_register", ""]), encoding="utf-8") + path.chmod(0o600) + return path + + def second_database(self, label: str) -> "Database": + """A database of its own on this cluster, made empty and built by the + bootstrap with `label` in its switch (T218b's check 10).""" + self.count += 1 + name = f"t_{self.count}" + self.psql(f"CREATE DATABASE {name};") + self.bootstrap(name, label) + self.labels[name] = label + return Database(self, name) + + +class CountingCluster(Cluster): + """SECTION 5.6'S COUNTING CLUSTER (T229; M13): a cluster of its own, + built like the session's, started with `log_connections=on` and + `log_statement=all`, its log in `server.log` beside its data: one + `connection authorized` line per connection, and one `statement:` line + per Query message.""" + + def prepare(self) -> None: + self.settings = ["log_connections=on", "log_statement=all"] + + def log(self) -> Path: + return self.root / "server.log" + + +def _seam(relay, point: str, name: str = "") -> None: + """THE RELAYS' SEAM (T229f; Codex's SHOULD 5 on f060619c): each relay + calls it where a concurrent `close()` can meet one of its threads, and it + does nothing unless a test has set the relay's `seam` to a callable + `seam(point, name)`. The points: "accepted", in `_accept`, with a client + and its upstream connected, neither registered in `DelayedLoopback`, both + registered before the connect in `SilentAfterStartup` (T229i); "listed", + as the thread `name`, listed and started, leaves the lock it was started + under; "snapshot", in `close()`, + once it has taken its snapshot. A test's hook holds a thread at a point + on an event, so a window that only the scheduler would open is open every + time.""" + if relay.seam is not None: + relay.seam(point, name) + + +class DelayedLoopback: + """THE DELAYED-LOOPBACK RELAY (T229; R-P23, lane 3's option B, #165 + 6741861590): standard library only, needing no root. It listens on + 127.0.0.1 at a free port, `port`, connects each client to 127.0.0.1 at + `target_port`, and delivers each byte `delay_s` after it read it, in each + direction, untouched, so TLS passes through and the client meets the + server's own certificate. An end's close reaches the other end after the + delay; when both directions have ended, both sockets close. It models no + slow start and no loss. `close()`, or leaving its `with`, ends it: a + client accepted while it closes is closed, never relayed (T229f).""" + + #: T229f's seam (`_seam`): None, or a test's hook. + seam = None + + def __init__(self, target_port: int, delay_s: float, target_host: str = "127.0.0.1") -> None: + self.target, self.delay = (target_host, int(target_port)), float(delay_s) + self.lock = threading.Lock() + self.sockets: set = set() + self.threads: List[threading.Thread] = [] + self.closing = False + self.listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self.listener.bind(("127.0.0.1", 0)) + self.listener.listen(16) + self.port = self.listener.getsockname()[1] + self._spawn(self._accept, "accept") + + def _start(self, target, name: str, *args) -> threading.Thread: + """Under `self.lock`, list the thread and start it (T229f): `close()` + snapshots under the same lock, so it never joins a thread not yet + started, and no later sweep of the dead drops one about to start.""" + thread = threading.Thread(target=target, args=args, daemon=True, + name=f"delayed-loopback-{self.port}-{name}") + self.threads = [t for t in self.threads if t.is_alive()] + [thread] + thread.start() + return thread + + def _spawn(self, target, name: str, *args) -> threading.Thread: + with self.lock: + thread = self._start(target, name, *args) + _seam(self, "listed", name) + return thread + + def _accept(self) -> None: + while True: + try: + client, _ = self.listener.accept() + except OSError: + return + try: + upstream = socket.create_connection(self.target, timeout=10) + upstream.settimeout(None) + except OSError: + client.close() + continue + _seam(self, "accepted") + pair = {"open": 2, "sockets": (client, upstream)} + with self.lock: # T229f: registered and started in one act, or not at all + closing = self.closing + if not closing: + self.sockets.update((client, upstream)) + self._start(self._read, "up", client, upstream, pair) + self._start(self._read, "down", upstream, client, pair) + if closing: # accepted as `close()` began: closed, never relayed + client.close() + upstream.close() + return + + def _read(self, source, sink, pair) -> None: + held: "queue.Queue" = queue.Queue() + writer = self._spawn(self._deliver, "deliver", held, sink, pair) + while True: + try: + data = source.recv(65536) + except OSError: + data = b"" + held.put((time.monotonic() + self.delay, data)) + if not data: + break + writer.join() + + def _deliver(self, held, sink, pair) -> None: + while True: + due, data = held.get() + wait = due - time.monotonic() + if wait > 0: + time.sleep(wait) + try: + if not data: + sink.shutdown(socket.SHUT_WR) + break + sink.sendall(data) + except OSError: + for end in pair["sockets"]: + self._shut(end) + break + with self.lock: + pair["open"] -= 1 + done = pair["open"] == 0 + if done: + self.sockets.difference_update(pair["sockets"]) + if done: + for end in pair["sockets"]: + end.close() + + @staticmethod + def _shut(end) -> None: + try: + end.shutdown(socket.SHUT_RDWR) + except OSError: + pass + + def alive(self) -> List[str]: + """The relay's threads still running.""" + with self.lock: + return [t.name for t in self.threads if t.is_alive()] + + def close(self, wait: float = 10.0) -> None: + with self.lock: + self.closing = True # T229f: before the listener's shutdown, under the lock + ends, threads = list(self.sockets), list(self.threads) + _seam(self, "snapshot") + self._shut(self.listener) + self.listener.close() + for end in ends: + self._shut(end) + end_by = time.monotonic() + wait + self.delay + for thread in threads: + thread.join(max(0.0, end_by - time.monotonic())) + + def __enter__(self) -> "DelayedLoopback": + return self + + def __exit__(self, *exc) -> None: + self.close() + + +def delayed_loopback(target_port: int, delay_s: float) -> DelayedLoopback: + """T229's relay in front of `target_port` on 127.0.0.1, `delay_s` each + way: `with delayed_loopback(port, 0.075) as relay:` connect to + `relay.port`.""" + return DelayedLoopback(target_port, delay_s) + + +class SilentAfterStartup: + """THE SILENT-AFTER-STARTUP RELAY (T229c; lane 3's batch 8, "Lane 2's + relay: T229 builds it", #165 6780753157; TP:7682-7684): D9's F2, "a + relay that forwards to the cluster's socket until the startup completes, + then goes silent" (TP:3557-3558), which AT-F7's silent host, the + service's timer and the guard's `[2-service-down]` connect through too. + Standard library only. It listens on 127.0.0.1 at a free port, `port`, + and connects each client to `target_port` on 127.0.0.1, or, with + `socket_dir`, to a cluster's Unix socket, + `<socket_dir>/.s.PGSQL.<target_port>`, which the session's cluster alone + has. + + It forwards both ways, untouched, until the startup completes, at the + server's first ReadyForQuery (`Z`, length 5); from then on it forwards + nothing either way and holds both sockets, reading and dropping what + reaches it, so neither end sees the other's bytes or its close until + `close()`. A close before then reaches the other end. `silenced` holds + the monotonic time each connection went silent, taken before the + ReadyForQuery is passed on. The startup's end is read in the server's + plain bytes, so a TLS stream, whose ReadyForQuery is encrypted, never + goes silent: connect without TLS (PostgreSQL answers an SSLRequest on a + Unix socket with `N`). It is T257's `StartupRelay` (line W3a, + `tests/test_sql_register_bounds.py`) taken over, so that once T257 and + the guard call this, one copy exists.""" + + READY = re.compile(rb"Z\x00\x00\x00\x05[ITE]") + #: T229f's seam (`_seam`): None, or a test's hook. + seam = None + + def __init__(self, target_port: int, socket_dir=None) -> None: + self.target_port = int(target_port) + self.socket_dir = None if socket_dir is None else str(socket_dir) + self.lock = threading.Lock() + self.sockets: set = set() + self.silenced: List[float] = [] + self.threads: List[threading.Thread] = [] + self.done = False + self.listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self.listener.bind(("127.0.0.1", 0)) + self.listener.listen(16) + self.port = self.listener.getsockname()[1] + self._spawn(self._accept, "accept") + + #: The bound on each upstream connect (T229i). A Unix socket's connect can + #: wait on a full backlog until it completes or times out: `CONNECT_WAIT` bounds it. + CONNECT_WAIT = 10.0 + + def _start(self, target, name: str, *args) -> None: + """Under `self.lock`, list the thread and start it (T229f, T229i): + `close()` snapshots under the same lock, so it never joins a thread + not yet started, and no thread starts after its snapshot.""" + thread = threading.Thread(target=target, args=args, daemon=True, + name=f"silent-after-startup-{self.port}-{name}") + self.threads = [t for t in self.threads if t.is_alive()] + [thread] + thread.start() + + def _spawn(self, target, name: str, *args) -> None: + with self.lock: # T229f: listed and started under `close()`'s lock + self._start(target, name, *args) + _seam(self, "listed", name) + + def _upstream(self) -> socket.socket: + """A socket for the target, not yet connected (T229i).""" + family = socket.AF_INET if self.socket_dir is None else socket.AF_UNIX + return socket.socket(family, socket.SOCK_STREAM) + + def _connect(self, upstream: socket.socket) -> None: + """`upstream`'s connect to the target, bounded by CONNECT_WAIT; a + shutdown by `close()` ends a TCP connect under way at once (T229i).""" + upstream.settimeout(self.CONNECT_WAIT) + if self.socket_dir is None: + upstream.connect(("127.0.0.1", self.target_port)) + else: + upstream.connect(f"{self.socket_dir}/.s.PGSQL.{self.target_port}") + upstream.settimeout(None) + + def _accept(self) -> None: + while True: + try: + client, _ = self.listener.accept() + except OSError: + return + try: + upstream = self._upstream() + except OSError: + client.close() + continue + pair = (client, upstream) + with self.lock: # T229i: tracked before the connect, so `close()` shuts both + if self.done: + client.close() + upstream.close() + return + self.sockets.update(pair) + try: + self._connect(upstream) + except OSError: + with self.lock: # untracked and closed here, or left to `close()` + if self.done: + return + self.sockets.difference_update(pair) + client.close() + upstream.close() + continue + _seam(self, "accepted") + with self.lock: # T229i: `done` read, and the pump listed and started, in one act + if self.done: + return + self._start(self._pump, "pump", client, upstream) + _seam(self, "listed", "pump") + + def _pump(self, client: socket.socket, server: socket.socket) -> None: + seen, silent, ends = b"", False, [client, server] + while ends and not self.done: + try: + ready, _, _ = select.select(ends, [], [], 0.2) + except (OSError, ValueError): + return + for end in ready: + try: + data = end.recv(65536) + except OSError: + data = b"" + if silent: + if not data: + ends.remove(end) # held: its close reaches nobody + continue + if not data: + return self._drop(client, server) + if end is server: + seen = (seen + data)[-64:] + if self.READY.search(seen): + silent = True + self.silenced.append(time.monotonic()) + try: + (client if end is server else server).sendall(data) + except OSError: + return self._drop(client, server) + + def _drop(self, *ends: socket.socket) -> None: + """A close before the startup completes reaches the other end.""" + with self.lock: + self.sockets.difference_update(ends) + for end in ends: + self._shut(end) + end.close() + + @staticmethod + def _shut(end) -> None: + try: + end.shutdown(socket.SHUT_RDWR) + except OSError: + pass + + def alive(self) -> List[str]: + """The relay's threads still running.""" + with self.lock: + return [t.name for t in self.threads if t.is_alive()] + + def close(self, wait: float = 10.0) -> None: + """End the relay: no new connection; every socket it tracks, a pair + whose upstream connect is under way among them, shut down before any + join, so that no pump waits in `sendall()` and no TCP connect goes + on; every thread joined by one deadline, `wait` from now; every held + socket closed; and then, with `wait` above 0, a thread still alive + raised as a RuntimeError that names it (T229i; Codex's SHOULD 3 on + P09 at `21dd3642`). `close(wait=0)`, T229f's own case, joins without + waiting and raises nothing: its caller asks `alive()`.""" + with self.lock: + self.done = True + ends, threads = list(self.sockets), list(self.threads) + self.sockets.clear() + _seam(self, "snapshot") + self._shut(self.listener) + self.listener.close() + for end in ends: + self._shut(end) + end_by = time.monotonic() + wait + for thread in threads: + thread.join(max(0.0, end_by - time.monotonic())) + for end in ends: + end.close() + left = [thread.name for thread in threads if thread.is_alive()] + if left and wait > 0: + raise RuntimeError(f"the silent-after-startup relay on port {self.port} has {left} " + f"alive at its close()'s {wait:g} s deadline") + + def __enter__(self) -> "SilentAfterStartup": + return self + + def __exit__(self, *exc) -> None: + self.close() + + +def silent_after_startup(target_port: int, socket_dir=None) -> SilentAfterStartup: + """T229c's relay in front of `target_port` on 127.0.0.1, or of the Unix + socket `<socket_dir>/.s.PGSQL.<target_port>`: `with + silent_after_startup(port) as relay:` connect to 127.0.0.1 at + `relay.port`; the session's cluster is + `silent_after_startup(pg.port, socket_dir=pg.host)`.""" + return SilentAfterStartup(target_port, socket_dir) + + # ------------------------------------------------------------ pytest def pytest_configure(config) -> None: if required() and probe().problem: @@ -1142,8 +1894,8 @@ def pytest_terminal_summary(terminalreporter) -> None: terminalreporter.write_line(f"real-engine: {IMPORTED} holds {what}") -def _started(found: Probe, template_sql, imported: bool = False) -> Cluster: - cluster = Cluster(found.bindir, template_sql, imported) +def _started(found: Probe, template_sql, imported: bool = False, kind=None, **options) -> Cluster: + cluster = (kind or Cluster)(found.bindir, template_sql, imported, **options) try: cluster.start() except (ClusterError, OSError, subprocess.SubprocessError) as exc: @@ -1224,11 +1976,43 @@ def stoppable_cluster(pg_engine, pg_template_sql): cluster.destroy() +def _own_cluster(found: Probe, template_sql, kind, **options): + """A started cluster of `kind` for one test, its tools first on `PATH` + while it is up, destroyed at the end.""" + cluster = _started(found, template_sql, kind=kind, **options) + patch = pytest.MonkeyPatch() + patch.setenv("PATH", _engine_first(found.bindir, os.environ.get("PATH", os.defpath))) + try: + yield cluster + finally: + patch.undo() + cluster.destroy() + + +@_fixture() +def tls_cluster(pg_engine, pg_template_sql, request): + """Section 5.6's TLS cluster (T229), the test's own: a `TLSCluster` built + like the session's. `@pytest.mark.parametrize("tls_cluster", + [{"leaf_only": True}], indirect=True)` starts it serving the leaf + alone.""" + options = dict(getattr(request, "param", None) or {}) + yield from _own_cluster(pg_engine, pg_template_sql, TLSCluster, + leaf_only=bool(options.get("leaf_only"))) + + +@_fixture() +def counting_cluster(pg_engine, pg_template_sql): + """Section 5.6's counting cluster (T229), the test's own: a + `CountingCluster` built like the session's.""" + yield from _own_cluster(pg_engine, pg_template_sql, CountingCluster) + + # ------------------------------------------------------------ the smoke def _select_1(cluster: Cluster, dbname: str = "postgres") -> None: - said = cluster.psql("SELECT 1;", dbname=dbname).stdout.strip() - if said != "1": - raise ClusterError(f"SELECT 1 on {dbname} answered {said!r}") + answer = cluster.psql("SELECT 1;", dbname=dbname).stdout + if answer.strip() != "1": + raise ClusterError(f"SELECT 1 on {dbname} did not answer 1: " + f"{len(answer.splitlines())} line(s), none shown") def _smoke_session(found: Probe) -> str: @@ -1258,7 +2042,59 @@ def _smoke_stoppable(found: Probe) -> str: cluster.destroy() -SMOKES = {"session": _smoke_session, "stoppable": _smoke_stoppable} +def _smoke_tls(found: Probe) -> str: + """A `verify-full` connect to the TLS cluster, the root alone as + `sslrootcert=`, by SCRAM, whose `pg_stat_ssl` row says TLSv1.3; and the + same connect without TLS, refused by the `hostnossl` line.""" + import secrets + cluster = TLSCluster(found.bindir) + try: + cluster.start() + password = secrets.token_urlsafe(24) + cluster.psql(f"CREATE ROLE fx_smoke LOGIN PASSWORD '{scram_verifier(password)}';") + cluster.passwords["fx_smoke"] = password + env = dict(cluster.client_env("fx_smoke"), PGREQUIREAUTH="scram-sha-256") + argv = [cluster.tool("psql"), "-X", "-A", "-t", "-F", "|", "-c", + "SELECT ssl, version FROM pg_stat_ssl WHERE pid = pg_backend_pid()"] + said = subprocess.run(argv, capture_output=True, text=True, env=env, timeout=60, check=False) + tls13 = said.returncode == 0 and said.stdout.strip() == "t|TLSv1.3" + if not tls13: + raise ClusterError(f"the verify-full connect did not answer t|TLSv1.3: {_counted(said)}") + plain = subprocess.run(argv, capture_output=True, text=True, timeout=60, check=False, + env=dict(env, PGSSLMODE="disable")) + if plain.returncode == 0: + raise ClusterError("a connect without TLS was let in: the hostnossl line did not reject it") + return (f"verify-full by SCRAM on 127.0.0.1:{cluster.port} answered t|TLSv1.3, and " + f"sslmode=disable was refused") + finally: + cluster.destroy() + + +def _smoke_counting(found: Probe) -> str: + """Two connects and a query on the counting cluster, whose log holds + their `connection authorized` lines and the query's `statement:` line.""" + import uuid + cluster = CountingCluster(found.bindir) + try: + cluster.start() + name = cluster.new_database() + offset = cluster.log().stat().st_size + marker = f"counting-smoke-{uuid.uuid4().hex[:8]}" + _select_1(cluster, name) + cluster.psql(f"SELECT '{marker}';", dbname=name) + time.sleep(0.2) # the logger's last line + text = cluster.log().read_bytes()[offset:].decode("utf-8", "replace") + connections = len(re.findall(r"connection authorized", text)) + if connections < 2 or f"statement: SELECT '{marker}';" not in text: + raise ClusterError(f"the counting cluster's log holds {connections} connection(s) and " + f"{'a' if marker in text else 'no'} statement line for the query") + return f"{connections} connection lines and the query's statement line in {cluster.log()}" + finally: + cluster.destroy() + + +SMOKES = {"session": _smoke_session, "stoppable": _smoke_stoppable, "tls": _smoke_tls, + "counting": _smoke_counting} def main(argv: List[str]) -> int: diff --git a/tests/sql_register_cleanup.py b/tests/sql_register_cleanup.py new file mode 100644 index 00000000..c2094ee6 --- /dev/null +++ b/tests/sql_register_cleanup.py @@ -0,0 +1,768 @@ +# SPDX-License-Identifier: Apache-2.0 +"""THE CLEAN-UP ENGINE TWO OF 007'S TEST MODULES SHARE (T270): the helpers +that own a case's processes, and the stand-ins of the clean-up regressions, +which `tests/test_sql_register_renderer_git.py` (T270) and +`tests/test_sql_register_rollback.py` (T273) held identical by `ast`, kept +here once, and imported by both (SonarCloud's quality gate on code PR 97 at +`f776b435`, 3.6% duplication on new code against its 3%, comment +6939998291; lane 3's reading, 6940039571; lane 2's ruling in round CX-34). + +It is no test module: it holds no test and no landing-gate table, and +pytest collects nothing from it. The two modules import it from `tests/`, +as they import `tests/sql_register_helpers.py` and as `tests/conftest.py` +imports `tests/sql_register_gate.py`. + +A PROCESS'S IDENTITY HERE (lane 3's Codex reviews of code PR 97 at +`18529e5a`, BLOCKING, and at `46cac748`, BLOCKING; lane 2's decision 1 in +round CX-33): the case's own, proved through the kernel, never by a pid and +a start token alone, which a process that takes the pid within the same +clock tick shares. Each case launches its processes with a fresh nonce in +their environment, `IDENTITY` (`_nonce`), which every process they start +inherits. A clean-up pins a process (`_pin`): its pidfd opened; its +environment, `/proc/<pid>/environ`, read in memory alone, never kept or +shown, and required to hold that exact entry; then a signal 0 sent through +the pidfd, whose success proves that the process the pidfd names held the +pid from the open through the read, so the read was its own. An environment +that cannot be read, is empty or lacks the entry fails closed: that process +is never signalled, and where a record or the estate names it, that is +reported. The case's own child, pinned while it is unreaped, is +authoritative and needs no nonce (`_pin_child`). Every signal goes through a +pidfd (`signal.pidfd_send_signal`), never by a number, and a group is never +signalled by its id. Where this Python or kernel has no pidfd, a clean-up +fails closed (`_pidfds`). The start token, field 22 of `/proc/<pid>/stat` +(`starttime`, in clock ticks since boot), which each module's wrapper logs, +only matches a record to a live process. + +EACH MODULE KEEPS ITS OWN: the renderer's clean-up (`_quiesce` and the +reads it makes) and the rollback's teardown (`_teardown` and its steps); +each module's `GIT_WRAPPER`, `_logged`, `_Stuck`, and its `_let_go` and +`_open_when_held`, whose docstrings name their own module's owners, with +`ABORT` beside its `_let_go`; and each module's own data constants and file +helpers. Their loop of stop, kill, confirm and read again is one, here +(`_Settled`; lane 3's Codex review of code PR 97 at `5a120647`, SHOULD 2): +both engines run it (`_settle_pinned`), and the renderer's `GIT_WRAPPER` +carries its source for the wrapper's `kill_above`. + +Python 3.9 or later: the standard library, and pytest for `LINUX_ONLY`'s +mark. +""" + +from __future__ import annotations + +import os +import signal +import subprocess +import sys +import time +import uuid +from pathlib import Path + +import pytest + + +# ------------------------------------------------------------------ owned processes +#: The environment variable that carries a case's nonce. +IDENTITY = "SQL_REGISTER_CASE_ID" + + +def _nonce() -> str: + """A fresh nonce for one case's processes (`IDENTITY`).""" + return uuid.uuid4().hex + + +def _stat(pid: int) -> dict | None: + """`/proc/<pid>/stat`, read once: the process's state, ppid, process + group, session and start token (field 22, as text); None where no + process has the pid.""" + try: + raw = Path(f"/proc/{pid}/stat").read_bytes() + except OSError: + return None + fields = raw[raw.rindex(b")") + 2:].split() + return {"state": fields[0].decode(), "ppid": int(fields[1]), "pgrp": int(fields[2]), + "session": int(fields[3]), "start": fields[19].decode()} + + +def _carried(pid: int) -> str | None: + """The nonce `pid`'s environment carries (`IDENTITY`), read from + `/proc/<pid>/environ` in memory alone, never kept or shown; None where + it carries none, or its environment cannot be read or is empty.""" + try: + environ = Path(f"/proc/{pid}/environ").read_bytes() + except OSError: + return None + prefix = f"{IDENTITY}=".encode() + for entry in environ.split(b"\0"): + if entry.startswith(prefix): + return entry[len(prefix):].decode("utf-8", "replace") or None + return None + + +def _pidfds() -> None: + """Fails closed (`RuntimeError`) where this Python has no pidfd: no + clean-up here falls back to a signal by number. `os.pidfd_open` and + `signal.pidfd_send_signal` are Python 3.9's, on Linux 5.3 and later; + a kernel without them refuses the open, which `_pin` raises.""" + missing = [name for name, there in (("os.pidfd_open", hasattr(os, "pidfd_open")), + ("signal.pidfd_send_signal", + hasattr(signal, "pidfd_send_signal"))) + if not there] + if missing: + raise RuntimeError(f"{' and '.join(missing)} missing: a clean-up here signals a process " + f"only through a pidfd (Python 3.9 or later, Linux 5.3 or later), " + f"never by its number") + + +class _Pinned: + """A PROCESS PINNED (`_pin`, `_pin_child`): its pid, its start token and + its pidfd, held until `close()`. Every signal goes through the pidfd, + which names this process alone, ended or not; its exit is read from it.""" + + def __init__(self, pid: int, start: str, fd: int): + self.pid, self.start, self.fd = pid, start, fd + + def gone(self, seconds: float = 0) -> bool: + """Whether it has ended, within `seconds`: its pidfd reads as ready + (`POLLIN`).""" + import select + poller = select.poll() + poller.register(self.fd, select.POLLIN) + return bool(poller.poll(int(seconds * 1000))) + + def alive(self) -> bool: + """Whether it still holds its pid and runs: a signal 0 through its + pidfd succeeds, as it does until the process is reaped, and the + pidfd is not readable, as it is once the process has ended.""" + try: + signal.pidfd_send_signal(self.fd, 0) + except ProcessLookupError: + return False + return not self.gone() + + def send(self, sig: int) -> None: + try: + signal.pidfd_send_signal(self.fd, sig) + except ProcessLookupError: + pass # it has ended; the pidfd names it alone, so no other process is signalled + + def close(self) -> None: + os.close(self.fd) + + +def _opened(pid: int) -> int | None: + """`os.pidfd_open(pid)`; None where no process has the pid. Any other + failure raises (`RuntimeError`): there is no fallback to a number.""" + _pidfds() + try: + return os.pidfd_open(pid) + except ProcessLookupError: + return None + except OSError as exc: + raise RuntimeError(f"os.pidfd_open({pid}) failed ({exc}): a clean-up here signals a " + f"process only through a pidfd, never by its number") from exc + + +def _pin(pid: int, nonce: str | None) -> _Pinned | None: + """`pid` PINNED BY THE CASE'S IDENTITY (lane 2's decision 1 in round + CX-33): its pidfd opened; its stat and its environment read, the + environment required to carry `nonce` (`_carried`); then a signal 0 + through the pidfd (`_Pinned.alive`), whose success proves the process + the pidfd names held the pid from the open through both reads, so they + were its own. None, the pidfd closed and nothing signalled, where it has + ended, is a zombie, or its environment cannot be read, is empty, or does + not carry `nonce`: it fails closed. The pidfd is this call's until it + is handed over: whatever a read or the signal 0 raises, it is closed in + a `finally` first (lane 3's Codex review of code PR 97 at `f776b435`, + SHOULD 3).""" + fd = _opened(pid) + if fd is None: + return None + kept = None + try: + now = _stat(pid) + pinned = _Pinned(pid, now["start"] if now else "", fd) + if (nonce and now is not None and now["state"] not in ("Z", "X") + and _carried(pid) == nonce and pinned.alive()): + kept = pinned + finally: + if kept is None: + os.close(fd) + return kept + + +def _pin_child(proc) -> _Pinned | None: + """The case's own child `proc`, pinned while it is unreaped + (`returncode` None): authoritative, with no nonce asked, since the + kernel gives its pid again only once this process reaps it (lane 2's + decision 1 in round CX-33). None where it has been reaped, or no process + has its pid. The pidfd is closed where its stat read raises (SHOULD 3 + at `f776b435`).""" + if proc is None or proc.returncode is not None: + return None + fd = _opened(proc.pid) + if fd is None: + return None + try: + now = _stat(proc.pid) + except BaseException: + os.close(fd) + raise + return _Pinned(proc.pid, now["start"] if now else "", fd) + + +def _table() -> dict: + """{pid: `_stat`} of every process this user owns, but pid 1, this + process and its ancestors, which no clean-up here ever signals.""" + mine, pid = set(), os.getpid() + while pid > 1 and pid not in mine: + mine.add(pid) + above = _stat(pid) + pid = above["ppid"] if above else 0 + table, uid = {}, os.getuid() + for name in os.listdir("/proc"): + if not name.isdigit() or int(name) in mine or int(name) == 1: + continue + try: + if os.stat(f"/proc/{name}").st_uid != uid: + continue + except OSError: + continue + found = _stat(int(name)) + if found is not None: + table[int(name)] = found + return table + + +def _stopped(held: _Pinned) -> bool: + """Whether `held` is seen stopped, or has ended: its stat, read while its + pidfd shows it alive, in state `T` or `t`. A stopped process forks no + child, so a read made once each one found is stopped misses none.""" + now = _stat(held.pid) + if held.gone(): + return True + return now is not None and now["start"] == held.start and now["state"] in ("T", "t") + + +def _seen_stopped(helds, until: float, refused=()) -> str | None: + """None where each of `helds` is seen stopped, or gone (`_stopped`), by + `until` (`time.monotonic()`); else the error naming each one not seen + so: a stop not seen is no stop, so a read made then could miss what it + forked (lane 3's Codex review of code PR 97 at `f776b435`, SHOULD 1). + One of `refused`, whose SIGSTOP raised, is passed over: that error is + kept already (`_send_each`), and is not told twice.""" + helds = [held for held in helds if held not in refused] + if _wait_all(_stopped, helds, until): + return None + late = sorted(held.pid for held in helds if not _stopped(held)) + return (f"pids {late} were never seen stopped, so a read made then could miss what they " + f"forked") if late else None + + +def _owned(table: dict, nonces: set, pinned: dict, fresh: list | None = None) -> list: + """Each process of `table` whose environment carries one of `nonces`, + pinned by it (`_pin`): the case's, found by its identity alone, with no + leader, parent or record needed (lane 3's Codex review of code PR 97 at + `46cac748`, SHOULD 1); returned. One pinned already is passed over only + while its pidfd shows it there: where that one has gone, a process with + its pid and start token, as one that took the pid within the same tick + has, is pinned again by its own identity, never taken for the one that + went (SHOULD 1 at `f776b435`). Where `fresh` is given, each pin is + registered as it is made (`_keep`), so whatever a later one raises, the + caller's `finally` lets every one go (SHOULD 3 at `f776b435`).""" + found = [] + for pid, row in table.items(): + kept = pinned.get((pid, row["start"])) + if kept is not None and not kept.gone(): + continue + nonce = _carried(pid) + held = _pin(pid, nonce) if nonce in nonces else None + if held is not None: + found.append(held) + if fresh is not None: + _keep(pinned, fresh, held) + return found + + +def _keep(pinned: dict, fresh: list, held) -> None: + """`held`, where there is one, registered in `pinned` by its pid and + start token, before any signal, and in `fresh`. One pinned before under + that key, which has gone, is kept under a key of its own, so its pidfd + is still let go (`_release`).""" + if held is not None: + key = (held.pid, held.start) + if key in pinned: + gone = pinned.pop(key) + pinned[(held.pid, held.start, gone.fd)] = gone + pinned[key] = held + fresh.append(held) + + +def _send_each(helds, sig: int, raised: list) -> list: + """`sig` through each pidfd of `helds`, each in a `try` of its own: what + one raises is kept in `raised`, and the rest are still signalled (lane + 3's Codex review of code PR 97 at `46cac748`, SHOULD 6). Returns each + one whose signal raised.""" + refused = [] + for held in helds: + try: + held.send(sig) + except OSError as exc: # kept; the rest are still signalled + raised.append(exc) + refused.append(held) + return refused + + +def _release(helds, raised: list, seconds: float = 5) -> None: + """Each pidfd of `helds` let go: its process killed (SIGKILL) where it + is not yet gone, so none is left stopped, each in a `try` of its own; + then each one so killed seen gone within one bound, `seconds` on, and + each pidfd closed, each in a `try` of its own. What one raises, a close + among them, is kept in `raised`, and the rest are still let go; one + killed that is still there at the bound is an error too (SHOULD 6 at + `46cac748`; lane 3's Codex review of code PR 97 at `f776b435`, + SHOULD 3).""" + helds, killed = list(helds), [] + for held in helds: + try: + if not held.gone(): + held.send(signal.SIGKILL) + killed.append(held) + except (OSError, ValueError) as exc: # kept; the rest are still let go + raised.append(exc) + until = time.monotonic() + seconds + for held in helds: + try: + if held in killed and not held.gone(max(0.0, until - time.monotonic())): + raised.append(RuntimeError(f"pid {held.pid} is still there {seconds:g} s after " + f"its SIGKILL through its pidfd")) + except (OSError, ValueError) as exc: # kept; the rest are still let go + raised.append(exc) + finally: + try: + held.close() + except OSError as exc: # kept; the rest are still closed + raised.append(exc) + + +def _misrecorded(logged, nonces: set, held: set, tail: str = "") -> list: + """WHAT A RECORD NAMES BUT A CLEAN-UP CANNOT OWN, each named once, none + ever signalled (lane 3's Codex review of code PR 97 at `f776b435`, + SHOULD 8): each of `logged`, (pid, start token, what), validated by + itself, from its own read of `/proc`, apart from the table of this + user's processes a clean-up signals from (`_table`). One with no start + token is named; so is one whose pid and start token a live process, not + a zombie and not pinned (its pid not in `held`), has where that process + is another user's, or its environment cannot be read or does not carry + one of `nonces` (`_misowned`). `tail` ends each text that names a live + process.""" + found = [] + for pid, start, what in logged: + if not start: + text = f"{what} names pid {pid} with no start token" + else: + why = _misowned(pid, start, nonces, held) + if why is None: + continue + text = f"{what} names pid {pid} with the start token of a live process {why}{tail}" + if text not in found: + found.append(text) + return found + + +def _misowned(pid, start: str, nonces: set, held: set) -> str | None: + """Why the live process a record names, by `pid` and `start`, is not the + case's: another user's, its environment unreadable, or without one of + `nonces`; None where no live process, but a zombie, has that pair, or + it is pinned (in `held`), or it carries one of `nonces`.""" + def live() -> bool: + now = _stat(pid) if isinstance(pid, int) and pid not in held else None + return now is not None and now["start"] == start and now["state"] not in ("Z", "X") + + if not live(): + return None + try: + if os.stat(f"/proc/{pid}").st_uid != os.getuid(): + return "that is another user's" + environ = Path(f"/proc/{pid}/environ").read_bytes() + except OSError: + environ = b"" + if not environ: # read again: one that ended meanwhile is no record's live process + return "whose environment cannot be read" if live() else None + if _carried(pid) not in nonces: + return "that does not carry the case's identity" + return None + + +def _wait_all(test, helds, until: float, pause: float = 0.01) -> bool: + """Whether `test(held)` holds for each of `helds` by the time `until` + (`time.monotonic()`), polled every `pause` s.""" + while not all(test(held) for held in helds): + if time.monotonic() >= until: + return False + time.sleep(pause) + return True + + +def _raise_first(errors: list) -> None: + """The first of `errors` raised as it is, each other one named in a + `RuntimeError` set as its cause; nothing where there is none. No + exception group, so Python 3.9 parses it.""" + if len(errors) > 1: + raise errors[0] from RuntimeError("; ".join(f"{type(exc).__name__}: {exc}" + for exc in errors[1:])) + if errors: + raise errors[0] + + +# ------------------------------------------------------------------ the one loop +class _Settled: + """THE ONE LOOP OF EVERY CLEAN-UP HERE (lane 3's Codex review of code PR + 97 at `5a120647`, SHOULD 2), `run()`: renderer_git's `_settle` and + rollback's `_stop_owned` and `_see_gone`, each through `_settle_pinned`, + and the git wrapper's `kill_above`, whose script carries this source. + Pass after pass, the absolute deadline `until` (`time.monotonic()`) + checked on each, right after its read and before it can end, whatever + was stopped (lane 3's Codex review of code PR 97 at `bb190f7b`, + SHOULD 1): + - `live()`, the targets not yet seen gone, is taken first; then one + read, `scan()`, registers and stops each target new, and says how + many are new; + - past `until`, the deadline is reported, and it ends (False), even + where that read found none new: a pass that crossed the deadline, + in its read or in the kill's confirmation before it, is no success; + - else a read that finds none new, made once every target was seen + gone, ends it (True); with no `kill` (rollback's step 1, which only + stops), a read that finds none new ends it; + - a read that found any new: `stop(by)` sees each target stopped, or + gone, by `by`, half the time left, so a stop never seen leaves the + rest for the kill, the confirmation and the read after them; the + error text it gives, where one is not seen, is kept; + - a read that found none new, or raised, while a target was there: + `kill(left)` kills each one still there and sees it gone, and gives + back the errors it met; + - a read that raised, with no target there: a pause of `pause` s. + What a read raises, and each error met, is kept in `errors`, each once + (by its type and text), in order. None ends the loop but the deadline, + so an earlier error never spares the read made after the kill. Its + steps are methods of their own, so each stays simple (SonarCloud's + cognitive complexity, python:S3776, at most 15 each).""" + + def __init__(self, scan, stop, kill, live, until, errors, pause=0.01): + self.scan, self.stop, self.kill, self.live = scan, stop, kill, live + self.until, self.errors, self.pause = until, errors, pause + + def keep(self, *found): + """Each of `found` kept in `errors`, unless one of its type and text + is kept already.""" + for exc in found: + if not any(type(old) is type(exc) and str(old) == str(exc) for old in self.errors): + self.errors.append(exc) + + def read(self): + """How many targets one read found new; None where it raised, its + error kept: a read that raised is no read that found none new.""" + try: + return self.scan() + except Exception as exc: # kept; the loop reads again + self.keep(exc) + return None + + def run(self) -> bool: + """The loop: True on its empty read, made by the deadline; False on + the deadline, checked after every read, before its end.""" + while True: + before = self.live() + new = self.read() + if time.monotonic() >= self.until: + self.late() + return False + if new == 0 and (self.kill is None or not before): + return True + self.step(new, before) + + def late(self) -> None: + """The deadline, reported: no read made by it found none new once + each target was seen gone (or stopped). It names the targets not + yet gone, or, where none is left, says the deadline passed in the + last pass (RV7-37, N1: true on both paths).""" + left = sorted(getattr(held, "pid", held) for held in self.live()) + what = "stopped" if self.kill is None else "gone" + rest = (f"pids not yet gone: {left}" if left + else "none is left: the deadline passed in the last pass") + self.keep(RuntimeError(f"the clean-up's deadline passed before a read made by it found " + f"none new once each process found was {what} ({rest})")) + + def step(self, new, before) -> None: + """What one read calls for: stop what it found, kill what is there, + or pause after a read that raised with nothing there.""" + if new: + late = self.stop(time.monotonic() + (self.until - time.monotonic()) / 2) + if late is not None: + self.keep(RuntimeError(late)) + elif before and self.kill is not None: + self.keep(*self.kill(self.live())) + else: + time.sleep(self.pause) + + +def _settle_pinned(scan, books, until: float, errors: list, kill: bool = True) -> bool: + """THE ONE LOOP (`_Settled`) on the processes a clean-up pinned here: the + targets are `books.pinned`'s; a stop is seen by `_seen_stopped`, which + passes over one of `books.refused`, whose SIGSTOP raised; the kill is a + SIGKILL through each pidfd, each in a `try` of its own (`_send_each`), + then each seen gone by `until` or, past it, 1 s on. With `kill` false + it only stops (rollback's step 1). Returns what its `run()` returns.""" + def live() -> list: + return [held for held in books.pinned.values() if not held.gone()] + + def killed(left: list) -> list: + raised: list = [] + _send_each(left, signal.SIGKILL, raised) + _wait_all(_Pinned.gone, left, max(until, time.monotonic() + 1), 0.02) + return raised + + return _Settled(scan, lambda by: _seen_stopped(books.pinned.values(), by, books.refused), + killed if kill else None, live, until, errors).run() + + +# ------------------------------------------------------------------ stand-ins +#: The clean-up regressions of both modules run on Linux alone. +LINUX_ONLY = pytest.mark.skipif(not sys.platform.startswith("linux"), + reason="a FIFO opened O_RDWR, and /proc, are Linux's") + + +#: A reader of one byte from a FIFO, as a held call, a held push or a launcher +#: reads it. +READ_ONE = "import os, sys; os.read(os.open(sys.argv[1], os.O_RDONLY), 1)" + + +#: A process that stays until it is ended. +SLEEP = "import time; time.sleep(300)" + + +#: How a stand-in's process says who it is: its pid and its start token, from +#: its own `/proc/self/stat`, one line on its stdout, which it then lets go, +#: so the case pins exactly that process, by the case's identity, never one +#: that took its pid (`_reported`). +SAY_ME = ("import os, sys, time\n" + "def say_me():\n" + " raw = open('/proc/self/stat', 'rb').read()\n" + " token = raw[raw.rindex(b')') + 2:].split()[19]\n" + " os.write(1, b'%d %s\\n' % (os.getpid(), token))\n" + " os.dup2(os.open(os.devnull, os.O_WRONLY), 1)\n") + + +#: A stand-in that leads a group with one member in it, a child that says who +#: it is (`SAY_ME`): a renderer's (T270), or a held push's, started in a +#: session of its own as T320's `_run_bounded` starts each git call, with +#: its git (T273). Both stay until they are ended. +LEADS_A_GROUP = SAY_ME + ("if os.fork() == 0:\n" + " say_me()\n" + " time.sleep(300)\n" + " os._exit(0)\n" + "time.sleep(300)\n") + + +#: A group's leader that leaves a member behind: it forks a child in its own +#: group, which says who it is (`SAY_ME`) and stays, and ends at once. +LEAVES_A_MEMBER = SAY_ME + ("if os.fork() == 0:\n" + " say_me()\n" + " time.sleep(300)\n" + " os._exit(0)\n") + + +class _Pipe: + """A child's pipe, which only records that it was closed.""" + + def __init__(self): + self.closed = False + + def close(self) -> None: + self.closed = True + + +class _Undying: + """A pin whose process is never seen gone: each signal and the close + are recorded, and nothing is signalled.""" + + pid, start = 4194304 + 9, "1" + + def __init__(self): + self.calls: list = [] + + def gone(self, seconds: float = 0) -> bool: + return False + + def send(self, sig: int) -> None: + self.calls.append(sig) + + def close(self) -> None: + self.calls.append("close") + + +def _with_identity(nonce: str) -> dict: + """This process's environment with the case's nonce (`IDENTITY`), for a + stand-in the clean-up must own by it.""" + return dict(os.environ, **{IDENTITY: nonce}) + + +def _fifo_reader(path, env: dict | None = None) -> subprocess.Popen: + """A child that reads one byte from the FIFO at `path`, in the + environment `env` where given.""" + return subprocess.Popen([sys.executable, "-I", "-c", READ_ONE, str(path)], + stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, + stderr=subprocess.PIPE, text=True, env=env) + + +def _on_fifo(proc: subprocess.Popen, seconds: float = 5, fifo=None) -> bool: + """Whether `proc` is seen on a FIFO within `seconds`: asleep in its + `open()` (`wait_for_partner`) or its `read()`, or, where `fifo` is + given, holding it open (a link in its `/proc/<pid>/fd` is the FIFO's + path), so a wait channel the kernel does not show still finds it. False + where it ends first, the time runs out, or its `/proc` cannot be read.""" + path = os.path.realpath(str(fifo)) if fifo is not None else None + deadline = time.monotonic() + seconds + while proc.poll() is None and time.monotonic() < deadline: + try: + wchan = Path(f"/proc/{proc.pid}/wchan").read_text(encoding="utf-8") + except OSError: + return False + if any(word in wchan for word in ("partner", "pipe", "fifo")): + return True + if path is not None and path in _fd_links(proc.pid): + return True + time.sleep(0.01) + return False + + +def _fd_links(pid: int) -> list: + """What each of `pid`'s open fds links to, as `/proc/<pid>/fd` shows it; + an fd closed while they are read is passed over.""" + links = [] + try: + names = os.listdir(f"/proc/{pid}/fd") + except OSError: + return links + for name in names: + try: + links.append(os.readlink(f"/proc/{pid}/fd/{name}")) + except OSError: + continue + return links + + +def _ended(proc: subprocess.Popen, seconds: float = 5) -> bool: + """Whether `proc` ends within `seconds`.""" + try: + proc.wait(timeout=seconds) + except subprocess.TimeoutExpired: + return False + return True + + +def _reap_one(proc, seconds: float = 30): + """One child a case started, killed by its pid where it is still + unreaped, its output read for at most `seconds`; its pipes closed in a + `finally`, and, where it is still unreaped, one more wait of at most + `seconds`, which raises where it times out. Returns its stderr.""" + try: + if proc.poll() is None: + proc.kill() + return proc.communicate(timeout=seconds)[1] + finally: + for pipe in (proc.stdout, proc.stderr): + if pipe is not None: + pipe.close() + if proc.returncode is None: + proc.wait(timeout=seconds) + + +def _reap_all(procs: list) -> list: + """Each child a case started reaped (`_reap_one`), every one tried + whatever an earlier one raised; the first error raised once the whole + set is done, the others named as its cause (lane 3's Codex review of + code PR 97 at `46cac748`, SHOULD 4). Returns what each wrote to its + stderr, None where that could not be read.""" + said, errors = [], [] + for proc in procs: + try: + said.append(_reap_one(proc)) + except Exception as exc: # every child is still tried; raised below + said.append(None) + errors.append(exc) + _raise_first(errors) + return said + + +def _each(*steps) -> None: + """Each of `steps` called, each tried whatever the one before it raised; + then the first error raised, the others named as its cause.""" + errors = [] + for step in steps: + try: + step() + except Exception as exc: # each step is tried; raised below + errors.append(exc) + _raise_first(errors) + + +class _GapFifo: + """A FIFO's path whose `unlink()` first starts a reader on it and waits + until that reader is on the FIFO: a reader that comes in the gap just + before the unlink (the coordinator's `GapPath`, #165 6934112467).""" + + def __init__(self, path: Path, readers: list): + self.path, self.readers, self.on = path, readers, False + + def __str__(self) -> str: + return str(self.path) + + def unlink(self, missing_ok: bool = False) -> None: + self.readers.append(_fifo_reader(self.path)) + self.on = _on_fifo(self.readers[-1], fifo=self.path) + self.path.unlink(missing_ok=missing_ok) + + +def _reported(proc: subprocess.Popen, what: str, nonce: str, seconds: float = 30) -> _Pinned: + """The process whose pid `proc`'s tree printed (`SAY_ME`), pinned by the + case's identity (`_pin`): exactly that process, alive. Its line is read + without blocking, in increments, each under `select`, all within one + absolute deadline, `seconds` on, until a newline or EOF: where no whole + line comes by then, a part of one or nothing, `proc` is ended and + reaped (`_reap_all`), and it raises with what came and what `proc` + said (lane 3's Codex reviews of code PR 97 at `46cac748` and at + `f776b435`, SHOULD 2).""" + import select + deadline, fd, line = time.monotonic() + seconds, proc.stdout.fileno(), b"" + while b"\n" not in line: + left = deadline - time.monotonic() + if left <= 0 or not select.select([fd], [], [], left)[0]: + said = _reap_all([proc]) + raise AssertionError(f"{what}: nothing was printed within {seconds:g} s but " + f"{line!r}; its starter was ended ({proc.returncode}) and said " + f"{said}") + more = os.read(fd, 4096) + if not more: + break # EOF: what came is all there is + line += more + words = line.split(b"\n", 1)[0].decode("utf-8", "replace").split() + assert len(words) == 2, f"{what}: no pid and start token were printed" + held = _pin(int(words[0]), nonce) + assert held is not None, f"{what}: pid {words[0]} was gone, or not the case's, when pinned" + return held + + +def _end_pin(held, seconds: float = 5) -> None: + """A process the case pinned, killed through its pidfd where it is still + there, and seen gone within `seconds` (its pidfd readable); the pidfd + closed in a `finally`; it raises (`RuntimeError`) unless the process is + seen gone (lane 3's Codex review of code PR 97 at `46cac748`, + SHOULD 3).""" + try: + if not held.gone(): + held.send(signal.SIGKILL) + if not held.gone(seconds): + raise RuntimeError(f"pid {held.pid} is still there {seconds:g} s after its SIGKILL " + f"through its pidfd") + finally: + held.close() diff --git a/tests/sql_register_landed/T210 b/tests/sql_register_landed/T210 new file mode 100644 index 00000000..e69de29b diff --git a/tests/sql_register_landed/T213 b/tests/sql_register_landed/T213 new file mode 100644 index 00000000..e69de29b diff --git a/tests/sql_register_landed/T214 b/tests/sql_register_landed/T214 new file mode 100644 index 00000000..e69de29b diff --git a/tests/sql_register_landed/T215 b/tests/sql_register_landed/T215 new file mode 100644 index 00000000..e69de29b diff --git a/tests/sql_register_landed/T219 b/tests/sql_register_landed/T219 new file mode 100644 index 00000000..e69de29b diff --git a/tests/sql_register_landed/T220 b/tests/sql_register_landed/T220 new file mode 100644 index 00000000..e69de29b diff --git a/tests/sql_register_landed/T224 b/tests/sql_register_landed/T224 new file mode 100644 index 00000000..e69de29b diff --git a/tests/sql_register_landed/T226 b/tests/sql_register_landed/T226 new file mode 100644 index 00000000..e69de29b diff --git a/tests/sql_register_landed/T229 b/tests/sql_register_landed/T229 new file mode 100644 index 00000000..e69de29b diff --git a/tests/sql_register_landed/T230 b/tests/sql_register_landed/T230 new file mode 100644 index 00000000..e69de29b diff --git a/tests/sql_register_landed/T237 b/tests/sql_register_landed/T237 new file mode 100644 index 00000000..e69de29b diff --git a/tests/sql_register_landed/T240 b/tests/sql_register_landed/T240 new file mode 100644 index 00000000..e69de29b diff --git a/tests/sql_register_landed/T241 b/tests/sql_register_landed/T241 new file mode 100644 index 00000000..e69de29b diff --git a/tests/sql_register_landed/T253 b/tests/sql_register_landed/T253 new file mode 100644 index 00000000..e69de29b diff --git a/tests/sql_register_landed/T254 b/tests/sql_register_landed/T254 new file mode 100644 index 00000000..e69de29b diff --git a/tests/sql_register_landed/T255 b/tests/sql_register_landed/T255 new file mode 100644 index 00000000..e69de29b diff --git a/tests/sql_register_landed/T257 b/tests/sql_register_landed/T257 new file mode 100644 index 00000000..e69de29b diff --git a/tests/sql_register_landed/T258 b/tests/sql_register_landed/T258 new file mode 100644 index 00000000..e69de29b diff --git a/tests/sql_register_landed/T270 b/tests/sql_register_landed/T270 new file mode 100644 index 00000000..e69de29b diff --git a/tests/sql_register_landed/T271 b/tests/sql_register_landed/T271 new file mode 100644 index 00000000..e69de29b diff --git a/tests/sql_register_landed/T273 b/tests/sql_register_landed/T273 new file mode 100644 index 00000000..e69de29b diff --git a/tests/sql_register_landed/T274 b/tests/sql_register_landed/T274 new file mode 100644 index 00000000..e69de29b diff --git a/tests/sql_register_landed/T276 b/tests/sql_register_landed/T276 new file mode 100644 index 00000000..e69de29b diff --git a/tests/sql_register_landed/T278 b/tests/sql_register_landed/T278 new file mode 100644 index 00000000..e69de29b diff --git a/tests/sql_register_landed/T279 b/tests/sql_register_landed/T279 new file mode 100644 index 00000000..e69de29b diff --git a/tests/test_sql_register_bounds.py b/tests/test_sql_register_bounds.py new file mode 100644 index 00000000..894bc647 --- /dev/null +++ b/tests/test_sql_register_bounds.py @@ -0,0 +1,6560 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Feature 007's test D9, the timeouts table, its phase-N rows (AT-D9, L2-N5; +section 4.4; T220), and lane 1's T106 case (R-F9-3) +(opensoft/openRepoTools#165). + +LANE 1'S T106 ALONE, `test_postgres_store_register_roles_connect_by_their_own_ +url_with_one_joined_request` (R-F9-3; lane 1, #165 6752661856), needs no +engine. It loads `lanes-index` in process, as `test_lanes_index.py`'s +`load_indexer` does, puts T203's register fake `psql` first on `PATH`, which +answers `psql --version` itself (T203b), sets an inherited `PGHOSTADDR`, +`PGSSLMODE=disable`, `PGOPTIONS` and `PGTARGETSESSIONATTRS`, and makes one +`request(statements, row)` call of two statements through +`PostgresStore(cfg, role)`, then one `_query_many(..., snapshot=True, row=...)` +call on the same store. It fails until lane 1's T106 lands: at `a2073eae` +`load_config` does not know `register_url=`, and `PostgresStore` has no +register role. Its `[J3]` word is `sql_register_bounds and +postgres_store_register_roles`. + +- THE `--version` PROBE: T106 asks `psql --version` once per process + (L1v4.10:152). T203b's fake answers it itself, `psql (PostgreSQL) 16.4`, + and logs it as an entry of its own kind (`"kind": "version"`, no `call`), + so the calls that carry a request are the entries with no such `kind`. + This module's own `--version` wrapper, which T220 carried until T203b was + in, is gone (T220d; F10's item 25). + +D9'S PHASE-N ROWS are real-engine tests, on `tests/pgcluster.py`'s `pg`. The +test plan names the rows but gives them no ids, so each row has a word that +leads its id (the block's T220): `guard`, `answer-2`, `reader`, +`renderer-reads`, `reconcile`, `import`, `status`, `migration`, +`outage-probe` and `mode-query` here. T257, T278 and T237 add theirs to the +same two functions. The faults (AT-D9, "Fixture"): + +- F1, a listener on loopback that accepts and never speaks (`SilentListener`); +- F2, a relay to the cluster's socket that goes silent once the startup has + completed, at the server's first ReadyForQuery (`StartupRelay`); +- F3, an `ALTER TABLE` in an open transaction of the test's own session on + the table the path reads, or, for a writer's commit, the head row held + `FOR UPDATE` (`_hold_head`; T257f); +- F4, a slow statement the test creates in its own database: a row-level + security policy that sleeps, for the path's group role. F4 is the second + function's, `test_a_slow_statement_meets_57014_before_the_client_timer`. + +`c` is 2 s and `N_a` 1: no configuration sets `connect_timeout=` or +`register_addresses=`. Each bound is asserted at twice its value, and the +guard's two rows under 4.5 s strictly; each measured time is recorded with +its margin (section 1.2's timing rules 1 to 3). The paths are lane 1's +commands, and lane 5's guard through `lanes-edit.sh guard`, from T203's +flipped copy where the path reads on primary. They fail until L1-A2, L1-A13, +L1-A15, L1-A18 and L5-A3 land, on T227's template and T228's logins; until +T228 a path's login is made here, in the row's group role. + +THE GUARD'S TWO ROWS' SESSION (T203c's `guard_session`; T220d): today's guard +reads this workstation's session records after its workspace and tmux checks +and before any register read, and refuses 2 where none is live in its window. +So each guard row, `guard` and `answer-2`, is given a live session record +and a stand-in `tmux` by `guard_session(home, bin, checkout)` (the checkout +under `$HOME/projects`), its `env()` and its `hook_input()`, torn down by +`request.addfinalizer(session.close)`; and the case's base environment is +`guard_strip_env(os.environ)`, which takes `PROJECTS_ROOT` and +`AGENT_PROTOCOL_ROOT` out beside the lane's, the harness's, tmux's and +libpq's. + +THE BENCH'S REGISTER NAMES THE LIVE SESSION (T220e): its `lanes/LANES.md` holds +one row, binding the lane's window `repoA-2` to `SID`, the id the guard +session is made with, in `test_lanes_index.py`'s row form (T203c's own unit +test uses it). So the guard's checks on the checkout's register all pass, and +what can refuse the prompt on the bench is the database alone. Without the row, +today's guard refuses 2 at its row check, "the register has no row for +`repoA-2`", which is also exit 2 within 4.5 s, so the guard rows would pass +against a guard that never reads the database. With it, today's guard lets the +prompt through, 0, and the guard rows fail by their exit assertion until L5-A3 +and L5-A5 land. + +THE TIMING WRAPPER (`TIMING_PSQL`): T203's shim records neither a call's +start time nor its stderr, so F4's oracle, "the call ending with 57014 ... no +earlier than the path's `statement_timeout` after the call's start", reads +this module's own wrapper in front of the real `psql`, which logs each +call's start and end on the monotonic clock and its stderr's first line. +Its first statement also stamps the call's begin, with its parent's pid, in +`psql-begin.log`, before it reads stdin, so a call its caller's timer kills +is stamped too (T220f). + +THE SERVICE ROW'S F4 (T237y; line W3aX's finding on T237x): one guard run +meets a cold service, which answers `unavailable` until its `psql` has +connected (socket contract d8:502), and the service's connection is "one +long-lived `psql` child on pipes" (d8:229), which `TIMING_PSQL`, reading its +input to the end before it starts the real `psql`, can never run. So +`[service]`'s case starts `lanes-index serve` once, puts `STREAM_PSQL` first +on `PATH` in place of `TIMING_PSQL`, and warms the service with guard runs +until one is answered through it, with no fallback line (d8, section 5.3); +only then does it make F4's slow statement and run the guard again. +`STREAM_PSQL` starts the real `psql` at once and hands its input on chunk by +chunk, stamping each, so the held child runs through it; the 57014 timed is +the held child's, from the stamp of the request it was handed to its +`ERROR: 57014` line, at the request's 180 ms (lane 5's answer 3, #165 +comment 6771208498; d8:214), the child known by its own argv's +`VERBOSITY=sqlstate` (d8:229). + +`STATUS`'S TWO ROWS (T220f; lane 3's T220 bullet, #165 comment 6772120103, +and its ruling 6, 6770600106) time the register's request alone, from its +start to the exit, never from the command's start: `status` runs #160's half +first, whose `lanes-edit.sh` calls took 17 to 23 s each under load (lane 1's +T117 point 6, 6769905855). `[status-F1]`, `[status-F2]` and `[status-F3]` +take `Bench.request_elapsed()`: from the begin stamp of the first `psql` that +the command's own process starts on the register's path (its once-per-process +`psql --version`, which T117's `_run_register` counts inside the request's +client timer, or else the request's own call) to the command's exit. +`[status]`'s 57014 time was already the request's own call, from its start +to its end, as every row's is. + +`[ANSWER-2-F1]` FOLLOWS A HEALTHY CALL (line BD-19b; lane 3's ruling, #165 +6840828270, on TP:3586-3589). The guard's one prefetch is the first read of +every prompt, an answer to its offer included (T507), and answer 2 adds no +database call to the hook (Y:5417). So the case (`_answer_2_row`) makes the +offer on a healthy register first: the bench at `primary` with a second row, +`repoA-3` PAUSED on another session, and the session named `repoA-3`. Then +it sends `2` through `ArmedFault`, which arms F1 only once `TIMING_PSQL`'s +log shows that the hook's register read has ended. The hook must exit 2 with +"BINDING" under 4.5 s (TP:3595), with that read in the log and no register +call of its own after it (AT-F6 case 21, TP:6190-6191). The detached bind +meets F1 after the hook exits, bounded as AT-F6's fixture bounds its binds +(`LANES_BIND_BOUND_S`). The wrapper names each call's session +(`os.getsid`), and the bind runs in a session of its own (`setsid`), so the +hook's calls are told from the bind's. + +NO WRITER'S TEXT IN A FAILURE (T257zj; lane 2's pre-review RV9-37 of P09 at +`d9a1f2bf`, B1): this module is PYTEST_DONT_REWRITE, as managed and measure +are, since pytest's assertion rewriting would add each tested operand's value +to a failure's message, a writer's raw stream or a whole `CompletedProcess` +with its stderr among them, so an assertion here reports its own message, +made through `_said_safely`, and nothing else. +""" + +from __future__ import annotations + +import ast +import contextlib +import json +import os +import pty +import re +import select +import shutil +import signal +import socket +import subprocess +import sys +import tempfile +import threading +import time +import uuid +from importlib.machinery import SourceFileLoader +from pathlib import Path +from urllib.parse import quote + +import pytest + +from conftest import REPO, WINDOWS_SKIP + +pytestmark = [WINDOWS_SKIP, pytest.mark.skipif( + shutil.which("bash") is None or shutil.which("git") is None, + reason="the lane tooling is bash over git")] + +#: THE LANDING GATE'S TABLE (T280's reader, `tests/sql_register_gate.py`; T281 +#: removes it in the last set). No `"*"` row: the module's waits share no task. +#: Each function or id waits for its owner's fails-until: T220's Order, T257's +#: (its As built line governs the ids it names; lane 3, #165 6877453897), +#: T278's, and T237's service ids. Lane 2's plan GP-24, v2. +SQL_REGISTER_GATE_TABLE = { + "test_a_burst_of_ten_over_a_delayed_tls_link_commits_each_once_or_exits_75_with_nothing_written": ("T103", "T104", "T106", "T111", "T112", "T113", "T114", "T413", "T414", "T415", "T417"), # T257; tasks:2451, :2455 + "test_a_connect_timeout_under_2_is_refused_at_load_config": ("T103", "T104", "T106", "T413", "T414", "T415", "T417"), # T257; tasks:2455 + "test_a_cutover_whose_call_expires_leaves_the_switch_unknown_and_its_rerun_reads_it_first": ("T116", "T304", "T324", "T326", "T327"), # T278; tasks:2558 + "test_a_record_marker_that_expires_leaves_the_marker_adding_and_writes_refusing": ("T116", "T304", "T324", "T326", "T327", "T412", "T415"), # T278; tasks:2558 + "test_a_register_path_drops_each_inherited_pg_variable_before_psql": ("T106",), # T257; tasks:2455 + "test_a_rollback_that_keeps_losing_its_turn_exits_75_at_the_deadline_with_nothing_written": ("T116", "T304", "T324", "T326", "T327"), # T278; tasks:2558 + "test_a_rollback_whose_first_call_expires_rereads_the_switch": ("T116", "T304", "T324", "T326", "T327"), # T278; tasks:2558 + "test_a_slow_statement_meets_57014_before_the_client_timer": ("T103", "T115", "T117", "T121", "T507"), # T220; tasks:2103 + "test_a_stray_ways_out_commit_call_is_in_doubt_like_a_writers": ("T116", "T304", "T324", "T326", "T327"), # T278; tasks:2558 + "test_a_waiting_migration_gives_up_at_its_own_lock_timeout": ("T103", "T115", "T117", "T121", "T507"), # T220; tasks:2103 + "test_an_orphaned_writer_transaction_is_ended_by_the_idle_bound": ("T103", "T104", "T106", "T112", "T413", "T414", "T415", "T417"), # T257; tasks:2451, :2455 + "test_connect_timeout_and_register_addresses_set_each_calls_timer": ("T106",), # T257; tasks:2451, :2455 + "test_each_database_path_exits_inside_its_bound": ("T103", "T115", "T117", "T121", "T507"), # T220; tasks:2103 + "test_each_register_call_is_one_request": ("T103", "T104", "T106", "T413", "T414", "T415", "T417"), # T257; tasks:2455 + "test_import_and_reconcile_set_their_bounds_at_connect": ("T103", "T115", "T117", "T121", "T507"), # T220; tasks:2103 + "test_over_a_delayed_tls_link_no_healthy_call_meets_its_timer": ("T103", "T104", "T106", "T111", "T112", "T113", "T114", "T413", "T414", "T415", "T417"), # T257; tasks:2451, :2455 + "test_postgres_store_register_roles_connect_by_their_own_url_with_one_joined_request": ("T106",), # T220; tasks:2103 + "test_the_aborts_call_that_expires_is_run_again_or_found_done_by_its_rerun": ("T116", "T304", "T324", "T326", "T327"), # T278; tasks:2558 + "test_the_joined_snapshot_logs_one_statement_and_reads_byte_identical_to_the_one_by_one_form": ("T103", "T104", "T106", "T112", "T114", "T413", "T414", "T415", "T417"), # T257; tasks:2451, :2455 + "test_the_lookups_tries_start_inside_the_window_and_end_in_3": ("T114", "T227", "T228"), # T257; tasks:2451, :2455 + "test_the_lookups_wait_counts_from_the_snapshot_calls_end_and_gets_no_lr011": ("T103", "T104", "T106", "T111", "T112", "T113", "T114", "T413", "T414", "T415", "T417"), # T257; tasks:2451, :2455 + "test_the_outage_declare_probe_ends_inside_its_bound_and_the_declaration_follows_the_rule": ("T103", "T115", "T117", "T121", "T507"), # T220; tasks:2103 + "test_a_cutover_whose_call_expires_leaves_the_switch_unknown_and_its_rerun_reads_it_first[F3]": ("T116", "T304", "T324", "T326"), # T278; tasks:2558 + "test_a_slow_statement_meets_57014_before_the_client_timer[cutover]": ("T116", "T304", "T324", "T326", "T327"), # T278; tasks:2558 + "test_a_slow_statement_meets_57014_before_the_client_timer[lookup]": ("T103", "T104", "T106", "T412", "T413", "T414", "T415", "T417"), # T257; tasks:2455 + "test_a_slow_statement_meets_57014_before_the_client_timer[record-marker]": ("T116", "T304", "T324", "T326", "T327"), # T278; tasks:2558 + "test_a_slow_statement_meets_57014_before_the_client_timer[rollback]": ("T116", "T304", "T324", "T326", "T327"), # T278; tasks:2558 + "test_a_slow_statement_meets_57014_before_the_client_timer[service]": ("T507", "T512", "T513"), # T237; tasks:2297 + "test_a_slow_statement_meets_57014_before_the_client_timer[stray-calls]": ("T116", "T304", "T324", "T326", "T327"), # T278; tasks:2558 + "test_a_slow_statement_meets_57014_before_the_client_timer[stray-commit]": ("T116", "T304", "T324", "T326", "T327"), # T278; tasks:2558 + "test_a_slow_statement_meets_57014_before_the_client_timer[switch-to-files]": ("T116", "T304", "T324", "T326", "T327"), # T278; tasks:2558 + "test_a_slow_statement_meets_57014_before_the_client_timer[writer-commit-f2]": ("T103", "T104", "T106", "T412", "T413", "T414", "T415", "T417"), # T257; tasks:2455 + "test_a_slow_statement_meets_57014_before_the_client_timer[writer-snapshot]": ("T103", "T104", "T106", "T412", "T413", "T414", "T415", "T417"), # T257; tasks:2455 + "test_each_database_path_exits_inside_its_bound[answer-2-F1]": ("T103", "T115", "T117", "T121", "T502", "T507"), # T220; tasks:2103 + "test_each_database_path_exits_inside_its_bound[cutover-F1]": ("T116", "T304", "T324", "T326", "T327"), # T278; tasks:2558 + "test_each_database_path_exits_inside_its_bound[lookup-F1]": ("T103", "T104", "T106", "T412", "T413", "T414", "T415", "T417"), # T257; tasks:2455 + "test_each_database_path_exits_inside_its_bound[record-marker-F1]": ("T116", "T304", "T324", "T326", "T327"), # T278; tasks:2558 + "test_each_database_path_exits_inside_its_bound[rollback-F1]": ("T116", "T304", "T324", "T326", "T327"), # T278; tasks:2558 + "test_each_database_path_exits_inside_its_bound[service-F1]": ("T507", "T512", "T513"), # T237; tasks:2297 + "test_each_database_path_exits_inside_its_bound[service-F2]": ("T507", "T512", "T513"), # T237; tasks:2297 + "test_each_database_path_exits_inside_its_bound[service-F3]": ("T507", "T512", "T513"), # T237; tasks:2297 + "test_each_database_path_exits_inside_its_bound[snapshot-miss-F2]": ("T103", "T104", "T106", "T111", "T413", "T414", "T415", "T417"), # T257; tasks:2455 + "test_each_database_path_exits_inside_its_bound[stray-calls-F1]": ("T116", "T304", "T324", "T326", "T327"), # T278; tasks:2558 + "test_each_database_path_exits_inside_its_bound[stray-commit-F1]": ("T116", "T304", "T324", "T326", "T327"), # T278; tasks:2558 + "test_each_database_path_exits_inside_its_bound[switch-to-files-F1]": ("T116", "T304", "T324", "T326", "T327"), # T278; tasks:2558 + "test_each_database_path_exits_inside_its_bound[whole-write-F3]": ("T103", "T104", "T106", "T412", "T413", "T414", "T415", "T417"), # T257; tasks:2455 + "test_each_database_path_exits_inside_its_bound[writer-commit-f2-F2]": ("T103", "T104", "T106", "T412", "T413", "T414", "T415", "T417"), # T257; tasks:2455 + "test_each_database_path_exits_inside_its_bound[writer-commit-f3-F3]": ("T103", "T104", "T106", "T412", "T413", "T414", "T415", "T417"), # T257; tasks:2455 + "test_each_database_path_exits_inside_its_bound[writer-snapshot-F1]": ("T103", "T104", "T106", "T412", "T413", "T414", "T415", "T417"), # T257; tasks:2455 + "test_each_register_call_is_one_request[commit]": ("T112",), # T257; tasks:2451 + "test_each_register_call_is_one_request[lookup]": ("T114",), # T257; tasks:2451 + "test_each_register_call_is_one_request[snapshot-psql-14]": ("T111",), # T257; tasks:2451 + "test_each_register_call_is_one_request[snapshot]": ("T111",), # T257; tasks:2451 +} + +INDEXER = REPO / "lanes-index" +LANES_EDIT = REPO / "lanes-edit.sh" +#: The guard session's id, and the one register row that names it (T220e). +SID = "6b2f6c1e-3c1d-4b8e-9a4f-7d0e5a1b2c3d" +DOT = chr(0xB7) +REGISTER = "\n".join([ + "# LANES.md", "", + "| lane | session id | workstation / env / user | started (UTC) | objects owned " + "| handoff path | state |", + "|---|---|---|---|---|---|---|", + f"| `repoA-2` | harness `{SID}` | Eagle / test / brett | 2026-10-01T00:00Z | none " + f"| handoffs/repoA-2.md | LIVE {DOT} 2026-10-01T02:00:00Z {DOT} working |", + ""]) +#: `[answer-2-F1]`'s register (line BD-19b): `REGISTER` and a second row, +#: `OFFER_TO`, PAUSED on another session, as AT-F6's estate writes its `TO` +#: row. The guard session is named `OFFER_TO` in the window `repoA-2`, whose +#: row names `SID`, so the guard's first prompt makes the offer. +OFFER_TO = "repoA-3" +OFFER_OTHER = "9d4c1b2a-5e6f-4a7b-8c9d-0e1f2a3b4c5d" +REGISTER_OFFER = REGISTER + ( + f"| `{OFFER_TO}` | harness `{OFFER_OTHER}` | Eagle / test / brett | 2026-10-01T00:00Z " + f"| none | handoffs/{OFFER_TO}.md | PAUSED {DOT} 2026-10-01T02:00:00Z {DOT} working |\n") +#: The detached bind's bound in `[answer-2-F1]`, in s, as AT-F6's fixture +#: sets it (`LANES_BIND_BOUND_S` for tests, TP:3595), and the longest the case +#: waits for the bind's outcome: the body's `timeout -k 10` at `bound_s - 10`, +#: the outer's sweep, and a margin. +ANSWER_2_BIND_S = 15 +ANSWER_2_WAIT_S = 45 +SCHEMA = "lanes_register" +#: `c` and `N_a` when no configuration sets them (D9; CLI4.10 section 2.4). +C, N_A = 2, 1 + +# =============================================================== lane 1's T106 + +#: Two statements, sent as ONE request (CLI4.10 section 2.3). +STATEMENTS = ["SELECT seq FROM register_head", "SELECT mode, marker_state FROM register_switch"] +#: CLI4.10:206, "the argv is §2.2's exactly" (lane 1, #165 6752661856). +REGISTER_ARGV = ["--no-psqlrc", "-X", "-q", "-A", "-t", "-v", "ON_ERROR_STOP=1", + "-v", "VERBOSITY=verbose", "-v", "SHOW_CONTEXT=never"] +#: Inherited by the caller, and never to reach `psql` on a register path +#: (L1v4.10:147; lane 3's R-PG-1; NOTES question 26). +INHERITED = {"PGHOSTADDR": "192.0.2.9", "PGSSLMODE": "disable", + "PGOPTIONS": "-c search_path=inherited", "PGTARGETSESSIONATTRS": "read-write"} +#: Each role: `PostgresStore`'s role, a D9 row of that role (T106's +#: `REGISTER_BOUNDS`: a writer's snapshot, a reader's read), and the keys and +#: login its connection comes from (L1v4.10:148-149; CLI4.10:211-214). +ROLES = { + "register-writer": ("register_writer", "snapshot", "register_url", "register_passfile", + "t220_writer"), + "register-reader": ("register_reader", "read", "reader_url", "reader_passfile", + "t220_reader"), +} + + +def load_indexer(): + """`lanes-index` as a module, fresh, as `test_lanes_index.py` loads it. + Called inside a test, never at import.""" + import importlib.util + loader = SourceFileLoader("lanes_index_bounds_module", str(INDEXER)) + spec = importlib.util.spec_from_loader("lanes_index_bounds_module", loader) + module = importlib.util.module_from_spec(spec) + loader.exec_module(module) + return module + + +def _private(path: Path, text: str = "") -> Path: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8") + path.chmod(0o600) + return path + + +def _error_safely(error) -> str: + """What a failure message may show of an exception that the code under + test raised (T257zs; lane 3's ruling 6949488277 on lane 2's pre-review + RV9-38 of P09 at `3f9fcac4`, B2): its class's name, its `kind` where it + has one that is a word of lowercase letters and hyphens (the product's + `StoreUnusable` has, else `[withheld]`), its exit where it has an int + `returncode`, and its text's count of lines. No text of it is shown: + `StoreUnusable`'s text can hold a raw line of psql's stderr + (lanes-index's `StoreUnusable("unreachable", err[0] or err[-1])`).""" + if error is None: + return "nothing" + parts = [type(error).__name__] + kind = getattr(error, "kind", None) + if isinstance(kind, str): + parts.append(f"kind {kind if re.fullmatch(r'[a-z][a-z-]*', kind) else '[withheld]'}") + code = getattr(error, "returncode", None) + if isinstance(code, int) and not isinstance(code, bool): + parts.append(f"exit {code}") + parts.append(f"its text {len(str(error).splitlines())} line(s), not shown") + return ", ".join(parts) + + +def _raised_nothing(error, what: str) -> None: + """Fail where `what`, the code under test, raised `error`, showing it + only as `_error_safely` does (T257zs; RV9-38, B2).""" + assert error is None, f"{what} raised {_error_safely(error)}" + + +def test_a_store_error_shows_its_kind_and_counts_and_no_text_in_pytests_report(request): + """T257zs (lane 3's ruling 6949488277 on lane 2's pre-review RV9-38 of + P09 at `3f9fcac4`, B2), with no engine and no process: the product's + `StoreUnusable`, carrying a planted line of psql's stderr as lanes-index + raises it where psql fails, reaches `_raised_nothing`, the check of the + bounds sites that ask a store to answer. Its failure shows the class, + the kind and the counts, and the planted value is in neither its message + nor pytest's own report of it (`_reported`). Before T257zs those sites + formatted `{error!r}`, the line whole. The planted value is no + credential of any login.""" + mod = load_indexer() + planted = f"fake-{uuid.uuid4().hex}" + error = mod.StoreUnusable("unreachable", f'psql: error: FATAL: role "{planted}" does not exist') + assert planted in str(error), "the planted line is not in the store's error, so this proves nothing" + with pytest.raises(AssertionError) as failed: + _raised_nothing(error, "PostgresStore(cfg, 'register_reader').request(...)") + said = str(failed.value) + assert said == ("PostgresStore(cfg, 'register_reader').request(...) raised StoreUnusable, " + "kind unreachable, its text 1 line(s), not shown"), f"the failure says: {said}" + assert planted not in _reported(request, failed), "the planted value is in pytest's report" + + +@pytest.mark.parametrize("role", list(ROLES)) +def test_postgres_store_register_roles_connect_by_their_own_url_with_one_joined_request( + tmp_path, monkeypatch, role): + """T106 alone (R-F9-3): one `request(statements, row)` call of two + statements through `PostgresStore(cfg, role)` is ONE `psql` call that + carries the request; its argv is exactly CLI4.10's list, with no `-d` + and no URL; its connection is the role's own URL and password file, the + reader's never the writer's; no inherited `PGHOSTADDR`, `PGSSLMODE` or + `PGTARGETSESSIONATTRS` reaches it, and `PGOPTIONS` is not the inherited + value; and its stdin is the two statements joined by `\\;`. Each URL is + a loopback host with no query parameter, and each configuration carries + `register_url=`, the reader's too, since a file with none is #160's. + + Then, on the same store, `_query_many(..., snapshot=True, row=<the + role's row>)` (lane 1's choice (b), #165 comment 6754680212) makes ONE + request and ONE `psql` call, besides the first; that call's stdin opens + with `SET search_path TO <register_schema>` (L1v4.10:150), then has a + `BEGIN`, and carries the marker `COPY (SELECT E'\\x1eLANES-INDEX-NEXT') + TO STDOUT` (CLI4.10:234; L1v4.10:151). The writer's row is `snapshot`; + T106's `bounds()` refuses that row for the reader ("a read never + connects with the writer's credential"), so the reader's own row, `read`, + is the one it sends.""" + from sql_register_helpers import REGISTER_FAKE_PSQL + store_role, row, url_key, pass_key, login = ROLES[role] + bindir = tmp_path / "bin" + bindir.mkdir() + # T203b: the fake answers `psql --version` itself, so it is `psql`. + (bindir / "psql").write_text(REGISTER_FAKE_PSQL, encoding="utf-8") + (bindir / "psql").chmod(0o755) + passfiles = {"register_passfile": _private(tmp_path / "writer.pgpass"), + "reader_passfile": _private(tmp_path / "reader.pgpass")} + config = _private(tmp_path / "conf" / "lanes-index.conf", "\n".join([ + "mode=index", + "register_url=postgresql://t220_writer@127.0.0.1:55432/register_db", + f"register_passfile={passfiles['register_passfile']}", + "reader_url=postgresql://t220_reader@127.0.0.1:55432/register_db", + f"reader_passfile={passfiles['reader_passfile']}", + "register_schema=lanes_register_t220", + ""])) + log = tmp_path / "psql.log" + for key in list(os.environ): + if key.startswith("PG") or key in ("FAKE_PSQL_ANSWERS", "FAKE_PSQL_VERSION_FILE"): + monkeypatch.delenv(key) + monkeypatch.setenv("LANES_INDEX_CONFIG", str(config)) + monkeypatch.setenv("XDG_STATE_HOME", str(tmp_path / "state")) + monkeypatch.setenv("FAKE_PSQL_LOG", str(log)) + monkeypatch.setenv("PATH", str(bindir) + os.pathsep + os.environ.get("PATH", os.defpath)) + for key, value in INHERITED.items(): + monkeypatch.setenv(key, value) + + mod = load_indexer() + error = None + try: + store = mod.PostgresStore(mod.load_config(), store_role) + store.request(list(STATEMENTS), row) + except Exception as exc: # the code under test, not this test, failed + error = exc + _raised_nothing(error, f"PostgresStore(cfg, {store_role!r}).request(<2 statements>, {row!r})") + + records = [json.loads(line) for line in log.read_text(encoding="utf-8").splitlines()] + calls = [r for r in records if r.get("kind") != "version"] + assert len(calls) == 1, f"one psql call carries the request: {len(calls)}" + call = calls[0] + assert "refused" not in call, call["refused"] + assert call["argv"] == REGISTER_ARGV + pg = call["pg"] + assert (pg.get("PGHOST"), pg.get("PGPORT"), pg.get("PGDATABASE"), pg.get("PGUSER")) == \ + ("127.0.0.1", "55432", "register_db", login), f"{url_key}='s mapping: {pg}" + assert pg.get("PGPASSFILE") == str(passfiles[pass_key]) + other = "reader_passfile" if pass_key == "register_passfile" else "register_passfile" + assert pg.get("PGPASSFILE") != str(passfiles[other]) + for key in ("PGHOSTADDR", "PGSSLMODE", "PGTARGETSESSIONATTRS"): + assert key not in pg, f"the inherited {key} reached psql: {pg[key]!r}" + assert pg.get("PGOPTIONS") != INHERITED["PGOPTIONS"], "the inherited PGOPTIONS reached psql" + request = call["stdin"].strip() + assert request.endswith(";") and "\n" not in request, f"one request: {call['stdin']!r}" + assert [part.strip() for part in request[:-1].split("\\;")] == STATEMENTS + + requests, send = [], store.request + + def counted(statements, request_row, **kwargs): + requests.append(request_row) + return send(statements, request_row, **kwargs) + store.request = counted + error = None + try: + store._query_many(list(STATEMENTS), snapshot=True, row=row) + except Exception as exc: # the code under test, not this test, failed + error = exc + _raised_nothing(error, f"PostgresStore(cfg, {store_role!r})._query_many(<2 queries>, " + f"snapshot=True, row={row!r})") + assert requests == [row], f"one request carries the snapshot: {requests}" + records = [json.loads(line) for line in log.read_text(encoding="utf-8").splitlines()] + calls = [r for r in records if r.get("kind") != "version"] + assert len(calls) == 2, f"one more psql call carries the snapshot: {len(calls) - 1}" + assert "refused" not in calls[1], calls[1]["refused"] + parts = [part.strip() for part in calls[1]["stdin"].strip().rstrip(";").split("\\;")] + # L1v4.10:150: the snapshot's `search_path` is `register_schema`. + assert parts[0].startswith("SET search_path TO ") and "lanes_register_t220" in parts[0], parts[0] + begin = [i for i, part in enumerate(parts) if part.startswith("BEGIN")] + assert begin and begin[0] > 0, f"a BEGIN follows the search_path: {parts}" + # CLI4.10:234 (L1v4.10:151): #160's `\echo` marker goes as a `COPY`. + marker = r"COPY (SELECT E'\x1eLANES-INDEX-NEXT') TO STDOUT" + assert marker in parts[begin[0]:], f"the COPY marker follows the BEGIN: {parts}" + probes = [r for r in records if r.get("kind") == "version"] + assert len(probes) <= 1, f"psql --version is asked once per process: {len(probes)}" + + +# ====================================================== D9's rows (real engine) + +class SilentListener: + """F1: a listener on loopback, port 0, that accepts and never speaks.""" + + #: `close()`'s one deadline for every join (T220p). + CLOSE_WAIT = 10.0 + + def __init__(self): + self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self.sock.bind(("127.0.0.1", 0)) + self.sock.listen(64) + self.port = self.sock.getsockname()[1] + self.held, self.done = [], False + self.lock, self.pumps = threading.Lock(), [] + self.thread = threading.Thread(target=self._accept, daemon=True) + self.thread.start() + + def _accept(self): + self.sock.settimeout(0.2) + while not self.done: + try: + conn, _ = self.sock.accept() + except OSError: + continue + with self.lock: # held under close()'s lock, or closed (T220o) + if self.done: + conn.close() + return + self.held.append(conn) + + def close(self): + """No new connection; every held socket shut down, a pair whose + upstream connect is under way among them, so that a pump blocked in + `sendall()` ends at once; the accept thread and every pump joined by + one deadline, CLOSE_WAIT from now; every socket and the listener + closed; and then a thread still alive raised as a RuntimeError that + names it (T220p; Codex's SHOULD 3 on P09 at `21dd3642`). The snapshot + is taken under the lock each accept registers under, so nothing + registered after it is left open or unjoined (T220o).""" + with self.lock: + self.done = True + held, threads = list(self.held), [self.thread] + self.pumps + for conn in held: + with contextlib.suppress(OSError): + conn.shutdown(socket.SHUT_RDWR) + end_by = time.monotonic() + self.CLOSE_WAIT + for thread in threads: # each loop sees `done` within its 0.2 s + thread.join(max(0.0, end_by - time.monotonic())) + left = [thread.name for thread in threads if thread.is_alive()] + for conn in held: + conn.close() + self.sock.close() + if left: + raise RuntimeError(f"the relay on port {self.port} has {left} alive at its " + f"close()'s {self.CLOSE_WAIT:g} s deadline") + + +class StartupRelay(SilentListener): + """F2: a relay on loopback to the cluster's Unix socket that forwards + until the startup completes, at the server's first ReadyForQuery + (`Z`, length 5), then goes silent, holding both ends open. + + `armed`, where given, is asked at each connection's accept (T257f; + TP:3586-3589, "A row that follows a healthy call ... The test arms the + fault once the shim's log shows the earlier call's end, so the call + before it reaches the cluster"): a connection accepted while it answers + False is relayed whole and never goes silent. Asked at the accept, it + has no race with the caller: the timing wrapper logs a call's end before + it hands the call's answer back. `silenced` counts the connections that + went silent.""" + + READY = re.compile(rb"Z\x00\x00\x00\x05[ITE]") + #: The bound on each upstream connect (T220p). A Unix socket's connect can + #: wait on a full backlog until it completes or times out: `CONNECT_WAIT` bounds it. + CONNECT_WAIT = 5.0 + + def __init__(self, unix_path: str, armed=None): + self.unix_path, self.armed, self.silenced = unix_path, armed, 0 + super().__init__() + + def _accept(self): + self.sock.settimeout(0.2) + while not self.done: + try: + conn, _ = self.sock.accept() + except OSError: + continue + self._relay(conn, self.armed is None or bool(self.armed())) + + def _relay(self, conn, fault): + """`conn` relayed to the cluster's socket (T220p): its upstream is + tracked with it under `close()`'s lock before a bounded connect, so + `close()` shuts both down whatever the connect is doing; a connect + that fails untracks and closes both, unless `close()` has begun, + which then owns them; and the pump is listed and started under that + lock, or not at all once `done` is set (T220o).""" + upstream = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + with self.lock: + if self.done: + conn.close() + upstream.close() + return + self.held += [conn, upstream] + try: + upstream.settimeout(self.CONNECT_WAIT) + upstream.connect(self.unix_path) + upstream.settimeout(None) + except OSError: + with self.lock: + if self.done: + return + self.held.remove(conn) + self.held.remove(upstream) + conn.close() + upstream.close() + return + with self.lock: + if not self.done: + pump = threading.Thread(target=self._pump, args=(conn, upstream, fault), + daemon=True) + self.pumps.append(pump) + pump.start() + + def _pump(self, client, server, fault=True): + seen, silent = b"", False + while not self.done: + try: + ready, _, _ = select.select([client, server], [], [], 0.2) + except (OSError, ValueError): # a socket `close()` has closed (T220p) + return + for end in ready: + try: + data = end.recv(65536) + except OSError: + return + if not data: + return + if silent: + continue + try: # `close()`'s shutdown ends a blocked sendall() (T220p) + if end is server: + seen = (seen + data)[-64:] + client.sendall(data) + if fault and self.READY.search(seen): + silent = True + self.silenced += 1 + else: + server.sendall(data) + except OSError: + return + + +#: T220p's cases (Codex's SHOULD 3 on P09 at `21dd3642`), and the bound on each +#: of their waits, which only a failure waits out. +RELAY_CASES, RELAY_WAIT = ["full-backlog", "blocked-pump", "thread-left"], 10.0 + + +class _Accepting: + """A relay's listener, as its accept thread reads it (T220p): `waiting` + is set once an accept waits through it, so a client that connects after + that is accepted through it; `accepted`, once an accept returns, so the + relay has its client and goes on to its upstream connect, which `done` + does not stop.""" + + def __init__(self, sock): + self.sock, self.waiting, self.accepted = sock, threading.Event(), threading.Event() + + def accept(self): + self.waiting.set() + pair = self.sock.accept() + self.accepted.set() + return pair + + def __getattr__(self, name): + return getattr(self.sock, name) + + +def _cluster_stand_in(backlog: int) -> tuple: + """A Unix listener of the standard library in place of the cluster's + socket, in Linux's abstract namespace, so that no path's length or file + is in play: (the listener, the name a relay connects to). With a backlog + of 0, one connection queued fills it.""" + name = f"\0t220p-{uuid.uuid4().hex}" + listener = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + listener.bind(name) + listener.listen(backlog) + return listener, name + + +def _relay_threads_left(relay) -> list: + """The names of the relay's threads still alive: its accept thread and each pump.""" + return [t.name for t in [relay.thread] + list(relay.pumps) if t.is_alive()] + + +def _peer_closed(sock, wait: float) -> bool: + """Whether `sock`'s peer closed it within `wait` seconds, by EOF or by a + reset, after whatever it had sent.""" + sock.settimeout(wait) + try: + while sock.recv(65536): + pass + return True + except socket.timeout: + return False + except OSError: + return True + + +def _stalls(sock) -> bool: + """Send `sock` zeros, which hold no ReadyForQuery, until a send waits a + second: the relay reading from it has stopped, its pump blocked in + `sendall()` to a client that never reads. False if 512 MiB went first.""" + sock.settimeout(1.0) + chunk, sent = bytes(65536), 0 + while sent < (512 << 20): + try: + sent += sock.send(chunk) + except socket.timeout: + return True + return False + + +def _relay_case(relay, stand_in, name: str, case: str, label: str) -> tuple: + """T220p's case `case` on `relay`, in front of `stand_in` at `name`, its + stuck pump named `label`: (what `close()` raised or None, the relay's + threads left after it, whether the client's end was closed). Everything + it opens is closed before it returns.""" + opened, release, raised = [stand_in], threading.Event(), None + listener = relay.sock = _Accepting(relay.sock) + try: + waiting = listener.waiting.wait(RELAY_WAIT) + assert waiting, f"[{case}] the relay's accept thread never waited through its listener" + if case == "full-backlog": # the backlog's one place taken + opened.append(socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)) + opened[-1].connect(name) + client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + opened.append(client) + client.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 4096) + client.settimeout(RELAY_WAIT) + client.connect(("127.0.0.1", relay.port)) + accepted = listener.accepted.wait(RELAY_WAIT) + assert accepted, f"[{case}] the relay never accepted its client" + if case == "blocked-pump": + stand_in.settimeout(RELAY_WAIT) + server, _ = stand_in.accept() + opened.append(server) + stalled = _stalls(server) + pumping = bool(relay.pumps) and relay.pumps[0].is_alive() + assert stalled and pumping, f"[{case}] no pump blocked in sendall(): {stalled}, {pumping}" + if case == "thread-left": + stuck = threading.Thread(target=release.wait, args=(RELAY_WAIT,), daemon=True, + name=label) + stuck.start() + with relay.lock: + relay.pumps.append(stuck) + relay.CLOSE_WAIT = 0.5 + try: + relay.close() + except RuntimeError as error: + raised = error + return raised, _relay_threads_left(relay), _peer_closed(client, 5.0) + finally: + release.set() + for sock in opened: + sock.close() + with contextlib.suppress(RuntimeError): + relay.close() + + +def _relay_closed_as_t220p_has_it(case: str, label: str, raised, left: list, closed: bool) -> None: + if case == "thread-left": + named = raised is not None and label in str(raised) + assert named and left == [label], ( + f"[{case}] close() did not fail on the one pump left alive, and only on it: " + f"{raised!r}, {left}") + else: + assert raised is None and left == [] and closed, ( + f"[{case}] close() left {left} alive (raised {raised!r}), or the client's end open " + f"({closed})") + + +@pytest.mark.skipif(not sys.platform.startswith("linux"), + reason="T220p's stand-in for the cluster is in Linux's abstract Unix namespace") +@pytest.mark.parametrize("case", RELAY_CASES) +def test_the_relays_close_ends_a_connect_and_a_blocked_pump_and_fails_on_a_thread_left(case): + """T220p (Codex's SHOULD 3 on P09 at `21dd3642`), with no engine: a Unix + listener of the standard library stands in for the cluster's socket, in + front of `StartupRelay`, whose `close()` is `SilentListener`'s. + `[full-backlog]`: the stand-in's backlog is full, so a connect to it + would wait; the relay's has a bound, its client's end is closed, and + `close()` leaves no thread. `[blocked-pump]`: the stand-in sends to a + client that never reads until the pump blocks in `sendall()`; `close()` + shuts the sockets down before it joins, so the pump ends and no thread + is left. `[thread-left]`: a pump that never ends; `close()` fails at its + deadline, naming it and only it. Before T220p the connect came before + the sockets were tracked and had no bound, the pumps were joined before + the sockets were shut down, and a join that timed out passed unchecked.""" + stand_in, name = _cluster_stand_in(0 if case == "full-backlog" else 16) + relay = StartupRelay(name) + _relay_closed_as_t220p_has_it(case, "t220p-stuck-pump", + *_relay_case(relay, stand_in, name, case, "t220p-stuck-pump")) + + +TIMING_PSQL = r'''#!/usr/bin/env python3 +# T220's timing wrapper in front of the real psql: each call's start and end +# on the monotonic clock, its exit and its stderr's first line, one JSON +# object per call in psql-timing.log beside it. Its first statement stamps +# the call's begin, written with its parent's pid to psql-begin.log before +# it reads stdin, so a call its caller's timer kills is stamped too (T220f). +# Each logged call also says whether its request was a writer's snapshot, the +# one request that opens REPEATABLE READ (contract section 2.3), so a fault +# can be armed after the snapshot's end and an attempt's start found (T257f), +# and which of the register's write functions it called (T278). Each request +# is also stamped in psql-sent.log once read, before the real psql connects. +# Each logged call names its parent's pid too, the command that made it, so a +# missed snapshot's second request is told from a new attempt's (T257i). +# Each send stamp says whether its request is a snapshot, so a case can tell +# that a writer's SQL path ran even where the snapshot never ended (T257j). +# Each begin stamp and each logged call names its session, so a hook's own +# calls are told from those of a bind it detached with `setsid` (line BD-19b). +import time +begin = time.monotonic() +import json, os, subprocess, sys +here = os.path.dirname(os.path.abspath(__file__)) +with open(os.path.join(here, "psql-begin.log"), "a", encoding="utf-8") as handle: + handle.write(json.dumps({"argv": sys.argv[1:], "ppid": os.getppid(), + "sid": os.getsid(0), "begin": begin}) + "\n") +real = os.environ["T220_REAL_PSQL"] +data = sys.stdin.buffer.read() if sys.argv[1:] != ["--version"] else b"" +KINDS = ("commit_write", "switch_to_files", "record_marker", "find_write") +if sys.argv[1:] != ["--version"]: + # T278: the request read, stamped before the real psql connects, with the + # write functions it calls, so a fault can be armed for one named call. + with open(os.path.join(here, "psql-sent.log"), "a", encoding="utf-8") as handle: + handle.write(json.dumps({"ppid": os.getppid(), "sent": time.monotonic(), + "calls": [k for k in KINDS if k.encode() + b"(" in data], + "snapshot": b"REPEATABLE READ" in data}) + "\n") +start = time.monotonic() +proc = subprocess.run([real] + sys.argv[1:], input=data, capture_output=True) +end = time.monotonic() +err = proc.stderr.decode("utf-8", "replace") +with open(os.path.join(here, "psql-timing.log"), "a", encoding="utf-8") as handle: + handle.write(json.dumps({"argv": sys.argv[1:], "ppid": os.getppid(), + "sid": os.getsid(0), + "start": start, "end": end, "exit": proc.returncode, + "first": (err.strip().splitlines() or [""])[0], + "snapshot": b"REPEATABLE READ" in data, + "calls": [k for k in KINDS if k.encode() + b"(" in data]}) + "\n") +sys.stdout.buffer.write(proc.stdout) +sys.stderr.buffer.write(proc.stderr) +sys.exit(proc.returncode) +''' + +STREAM_PSQL = r'''#!/usr/bin/env python3 +# T237y's streaming wrapper in front of the real psql, for the service row's +# F4 case. Like TIMING_PSQL it stamps each call's begin in psql-begin.log +# before anything else, and logs a call that ends in psql-timing.log in +# TIMING_PSQL's form. Unlike it, it never reads its input to the end first: +# it starts the real psql at once and hands each chunk of stdin on as it +# comes, so the service's one long-lived psql child on pipes (d8:229) runs +# through it. Each chunk handed on is stamped, and each stderr line that +# names 57014 is logged in psql-stream.log with the stamp of the last chunk +# handed on before it: the held child's request, timed from its send to the +# server's answer. SIGINT, which the service sends on a request's expiry +# (d8:215), and SIGTERM go on to the real psql. +import time +begin = time.monotonic() +import json, os, signal, subprocess, sys, threading +here = os.path.dirname(os.path.abspath(__file__)) + + +def log(name, record): + with open(os.path.join(here, name), "a", encoding="utf-8") as handle: + handle.write(json.dumps(record) + "\n") + + +log("psql-begin.log", {"argv": sys.argv[1:], "ppid": os.getppid(), "begin": begin}) +version = sys.argv[1:] == ["--version"] +# THE REAL psql: the bench's, or else the first psql on PATH that is not this +# wrapper, should the service hand its child a reduced environment. +real = os.environ.get("T220_REAL_PSQL") or next( + (os.path.join(d, "psql") for d in os.environ.get("PATH", "").split(os.pathsep) + if d and os.path.realpath(d) != os.path.realpath(here) + and os.access(os.path.join(d, "psql"), os.X_OK)), "psql") +proc = subprocess.Popen([real] + sys.argv[1:], + stdin=subprocess.DEVNULL if version else subprocess.PIPE, + stdout=subprocess.PIPE, stderr=subprocess.PIPE) +start = time.monotonic() +for sig in (signal.SIGINT, signal.SIGTERM): + signal.signal(sig, lambda number, frame: proc.send_signal(number)) +sent, lock, first = [], threading.Lock(), [] + + +def feed(): + while True: + chunk = os.read(0, 65536) + if not chunk: + break + with lock: + sent.append(time.monotonic()) + try: + proc.stdin.write(chunk) + proc.stdin.flush() + except OSError: + break + try: + proc.stdin.close() + except OSError: + pass + + +def out(): + while True: + chunk = os.read(proc.stdout.fileno(), 65536) + if not chunk: + break + os.write(1, chunk) + + +def err(): + for line in iter(proc.stderr.readline, b""): + now = time.monotonic() + os.write(2, line) + text = line.decode("utf-8", "replace").strip() + if text and not first: + first.append(text) + if "57014" in text: + with lock: + request = sent[-1] if sent else start + log("psql-stream.log", {"argv": sys.argv[1:], "ppid": os.getppid(), + "request": request, "error": now, "line": text}) + + +if not version: + threading.Thread(target=feed, daemon=True).start() +readers = [threading.Thread(target=out), threading.Thread(target=err)] +for reader in readers: + reader.start() +code = proc.wait() +for reader in readers: + reader.join() +log("psql-timing.log", {"argv": sys.argv[1:], "start": start, "end": time.monotonic(), + "exit": code, "first": (first or [""])[0]}) +sys.exit(code if code >= 0 else 128 - code) +''' + +#: D9'S PHASE-N ROWS (AT-D9's table; the block's T220): the word that leads +#: each id; how the path runs; the group role its login is in; its expected +#: exit; the design's bound on the elapsed time in s; whether that bound is +#: the guard's, strict (timing rule 1), or asserted at twice its value (rule +#: 2); the faults the first function gives it; its `statement_timeout` in ms +#: where it sets one (F4, the second function's); and the table its reads +#: wait on. `import` runs FP only for its 330 s timer, and has F1 alone. +ROWS = { + "guard": dict(group="lanes_register_reader", exit=2, bound=4.5, strict=True, + faults=("F1", "F2", "F3"), statement_ms=1500, table="register_head"), + "answer-2": dict(group="lanes_register_reader", exit=2, bound=4.5, strict=True, + faults=("F1",), statement_ms=None, table=None), + "reader": dict(group="lanes_register_reader", exit=69, bound=6, strict=False, + faults=("F1", "F2", "F3"), statement_ms=3000, table="register_head"), + "renderer-reads": dict(group="lanes_register_reader", exit=None, bound=15, strict=False, + faults=("F1", "F2", "F3"), statement_ms=10000, table="register_head"), + "reconcile": dict(group="lanes_register_reader", exit=69, bound=15, strict=False, + faults=("F1", "F2", "F3"), statement_ms=10000, table="register_head"), + "import": dict(group="lanes_register_writer", exit=69, bound=330, strict=False, + faults=("F1",), statement_ms=None, table=None), + "status": dict(group="lanes_register_reader", exit=69, bound=8, strict=False, + faults=("F1", "F2", "F3"), statement_ms=5000, table="register_head"), + "migration": dict(group=None, exit=None, bound=None, strict=False, + faults=("F1",), statement_ms=None, table="register_head"), + "outage-probe": dict(group="lanes_register_writer", exit=0, bound=8, strict=False, + faults=("F1", "F2", "F3"), statement_ms=5000, table="register_switch"), + "mode-query": dict(group=None, exit=0, bound=2, strict=False, + faults=("F1",), statement_ms=None, table=None), + # T237's row: the guard through the service, `lanes-index serve` started on + # the same configuration, whose connection meets the fault; the guard's + # request is answered `unavailable` and its direct read meets it too, so + # the hook exits 2 inside its 4.5 s (lane 5's socket contract d8, section + # 5.3's table). Its `statement_timeout` is a request's 180 ms, with + # `lock_timeout` 150 ms, set in `PGOPTIONS` just inside the service's + # 200 ms timer; only the image fetch differs, at 10 s and 1000 ms under an + # 11 s timer (T237x; lane 5's answer 3, #165 comment 6771208498; d8:214, + # d8:244). Its F4 case, `[service]`, warms the service first, then times + # the held child's request through `STREAM_PSQL`, which streams (T237y, + # `_service_57014`): `TIMING_PSQL` reads its stdin to the end before it + # starts the real `psql`, so the held child (d8:229) never ran through it, + # and T237w's case timed the guard's direct read (T237x's finding). + "service": dict(group="lanes_register_reader", exit=2, bound=4.5, strict=True, + faults=("F1", "F2", "F3"), statement_ms=180, table="register_head"), + # T257's five rows (D9's timeouts table, test plan section 3's AT-D9): + # a writer's snapshot, `S` 8 s, 69 at F1; the commit at F2, in doubt then + # 3, at least `C` + `S` + `T_L` = 25 s from the commit call's start; the + # commit at F3, 55P03 per attempt then 75 at the deadline + # (`LANES_REGISTER_DEADLINE_S=3`), at most 3 + 8 + 8 = 19 s; the lookup, + # `find_write`, 3 naming the id, its tries inside the 10 s window, each + # to `T_L` 9 s; and a whole write, 75 at the deadline. + # + # LANE 3'S BATCH 7, ask (1) on T257a (T257f; #165, its analysis's + # "R-F13-1, T257a's four readings"): the snapshot's and the commit's + # `statement_timeout` is 5000 ms (CLI:250-251), the lookup's 6000 ms + # (CLI:252). `whole-write` runs at F3, since F1 ends the first snapshot + # with 69 (TP:3596), with its own cell: no attempt starts after the + # deadline, and the run stays under `T_write` (`WHOLE_WRITE`). And the + # commit's F2 is armed only once the timing log shows the snapshot's end + # (TP:3586-3589), so the snapshot reaches the cluster and the commit + # meets the relay; since T257i, at the commit's own send, so a missed + # snapshot's second request reaches it too (lane 1's cut, #165 + # 6783051626). A writer's F3 is the head row held `FOR UPDATE` + # (`_hold_head`; TP:3560-3561, "for a writer's commit, the head row held + # `FOR UPDATE`"), which a snapshot's plain read does not wait on, so the + # snapshot answers and each attempt's commit meets 55P03. + # + # THE COMMIT'S F4 (T257h; line BD9's finding on T257a): the second + # function's `[writer-commit-f2]` meets a trigger on `journal` that + # sleeps, which the commit's entry meets (`slow`), and the writer exits + # 69, "a refusal the database made", not the F2 row's 3 (`f4_exit`; + # TP:3621-3626 at B14). T257a's policy on `register_head` was met by the + # snapshot's read first. + "writer-snapshot": dict(group="lanes_register_writer", exit=69, bound=8, strict=False, + faults=("F1",), statement_ms=5000, table="register_head"), + "writer-commit-f2": dict(group="lanes_register_writer", exit=3, bound=25, strict=False, + faults=("F2",), statement_ms=5000, table="register_head", + f4_exit=69, slow=("journal", "INSERT")), + "writer-commit-f3": dict(group="lanes_register_writer", exit=75, bound=19, strict=False, + faults=("F3",), statement_ms=None, table="register_head"), + "lookup": dict(group="lanes_register_writer", exit=3, bound=19, strict=False, + faults=("F1",), statement_ms=6000, table="register_head"), + "whole-write": dict(group="lanes_register_writer", exit=75, bound=19, strict=False, + faults=("F3",), statement_ms=None, table="register_head"), + # T257g'S CACHE MISS (F13c's T257 bullet, R-F13c-18; lane 3's batch 7, + # #165 6780364102, text change 18 and its ruling on T111's SHOULD-2, + # option (b)): `register snapshot` misses the image cache, F2 is armed + # once its first request ends, and its second request, the whole fetch + # (Y:2515-2516), runs under what is left of `S` from the first request's + # start, so the command ends 69 within `S`, 8 s (`_snapshot_miss`). It + # runs on the imported register at `primary` (`Operator`): a snapshot + # reads the switch first (its check 4), and a miss fetches from the + # import. Its F4 is `writer-snapshot`'s, so it takes no id of the second + # function (`SLOW_ROWS`). + "snapshot-miss": dict(group=None, exit=69, bound=8, strict=False, + faults=("F2",), statement_ms=5000, table="register_head"), + # T257j: `writer-commit-f2`, `writer-commit-f3` and `whole-write` meet + # their faults after the snapshot's check 4, which refuses any switch but + # `primary` with the marker `present`; `pg` alone is a bootstrap-only + # clone, its switch `files` with the marker `absent` and its head -1. So + # they run on the imported register at `primary` (`Operator`, as T278's + # rows and `snapshot-miss` do; `PRIMARY_WRITER_ROWS`), each with its id, + # its fault and its expected exit unchanged. `writer-snapshot` meets its + # F1 at the connect and its F4 at the snapshot's read, both before check + # 4, so it stays on `Bench`. + # T278'S SIX ROWS (AT-D9's table, TP:3600-3608; "The operator rows run the + # real commands", TP:3627-3641): the operator's commands on test 7's + # fixture register (`Operator`, below), each at F1, timed from the + # faulted call's start. `rollback`, each call 15 s and 69, where step 1's + # call and the switch's re-read both meet F1, 15 + 15 = 30 s; `cutover`, + # its transaction 15 s, 69; `switch-to-files`, the cutover's abort, + # reached by a cutover whose push the `git` wrapper fails, 15 s, 69; + # `record-marker`, after the cutover's push and read-back, 15 s, 69; the + # stray ways out's commit call (`stray-commit`), in doubt as a writer's, + # then the lookup, 3, the commit's F2 row's 35.5 s; and their other calls + # (`stray-calls`), the snapshot read, 69 in 8 s. Each `statement_timeout` + # is lane 1's `REGISTER_BOUNDS`' (`rollback` and `cutover`, 10 s; the + # ways out's calls, 5000 ms, TP:3607). The keys past `table`: `f4_exit`, + # the outcome at F4 ("For a writer's commit that outcome is 69, a refusal + # the database made", TP:3615-3617); `slow`, where F4's slow statement + # sits (TP:3618-3624: a trigger on `journal` for the cutover, its abort + # and the ways out's commit; on `register_switch` for `record_marker`; a + # policy on `register_head` for the snapshot's read); `estate`; and + # `after`, the healthy call before the faulted one, and `target`, the + # faulted call, by the write function it calls. F1 is armed for `target` + # at that call's own send, which `TIMING_PSQL` stamps before the real + # `psql` connects: so "once the shim's log shows the earlier call's end" + # (TP:3586-3589), and never earlier, whatever number of requests the + # earlier call makes. A missed snapshot's second request (lane 1's cut, + # `refs/l1/R-rulings` 8121903; lane 3's batch 7 SHOULD-2) is a snapshot + # request still, and reaches the cluster. + # `rollback`'s F4 is a trigger on `journal` (lane 3's batch 11 (7)(a), + # #165 6783909985, which adds "the rollback's step 1" to TP's F4 list): + # step 1 is `commit_write` with the `rollback` entry (T304), whose + # `INSERT INTO journal` meets the trigger, as the cutover's entry does. + # Its estate is `cutover-done` (T278d): T326's step 0 walks origin for the + # cutover's marker commit, which `_to_primary` never pushes. + "rollback": dict(group=None, exit=69, bound=30, strict=False, faults=("F1",), + statement_ms=10000, table="journal", f4_exit=69, + slow=("journal", "INSERT"), estate="cutover-done", after=None, + target=None), + "cutover": dict(group=None, exit=69, bound=15, strict=False, faults=("F1",), + statement_ms=10000, table="journal", f4_exit=69, + slow=("journal", "INSERT"), estate="imported", after=None, + target=None), + "switch-to-files": dict(group=None, exit=69, bound=15, strict=False, faults=("F1",), + statement_ms=10000, table="journal", f4_exit=69, + slow=("journal", "DELETE"), estate="imported", + after="commit_write", target="switch_to_files"), + "record-marker": dict(group=None, exit=69, bound=15, strict=False, faults=("F1",), + statement_ms=10000, table="register_switch", f4_exit=69, + slow=("register_switch", "UPDATE"), estate="imported", + after="commit_write", target="record_marker"), + "stray-commit": dict(group=None, exit=3, bound=35.5, strict=False, faults=("F1",), + statement_ms=5000, table="journal", f4_exit=69, + slow=("journal", "INSERT"), estate="stray", after="snapshot", + target="commit_write"), + "stray-calls": dict(group=None, exit=69, bound=8, strict=False, faults=("F1",), + statement_ms=5000, table="register_head", f4_exit=69, + slow=("register_head", "policy"), estate="stray", after=None, + target=None), +} +#: T278's rows, which `Operator` runs, not `Bench`. +OPERATOR_ROWS = ("rollback", "cutover", "switch-to-files", "record-marker", "stray-commit", + "stray-calls") +#: T257a's writer rows that `Operator`'s estate at `primary` runs (T257j). +PRIMARY_WRITER_ROWS = ("writer-commit-f2", "writer-commit-f3", "whole-write") + +#: The whole write's own cell (TP's "a whole write" row; T257f): at +#: `LANES_REGISTER_DEADLINE_S=3`, no attempt starts after the deadline, and +#: from the first attempt's start the run takes at most the deadline + `S` + +#: `C` = 3 + 8 + 8 = 19 s (`ROWS`' bound, asserted at twice it), and in no +#: case over `T_write` = 62.5 + 3 * `N_a` * `c` s, 68.5 s here. +WHOLE_WRITE = dict(deadline_s=3, t_write_s=62.5 + 3 * N_A * C) +#: The rows whose F3 is the head row held `FOR UPDATE`, a writer's commit's. +HEAD_HELD_F3 = ("writer-commit-f3", "whole-write") + +FIRST_CASES = [f"{row}-{fault}" for row, spec in ROWS.items() for fault in spec["faults"]] +SLOW_ROWS = [row for row, spec in ROWS.items() + if spec["statement_ms"] and row not in ("import", "snapshot-miss")] + +#: THE SERVICE ROW'S STATE HOME: SHORT, AND OUTSIDE THE TEMPORARY ROOT. The +#: service's one socket is `${XDG_STATE_HOME}/openRepoTools/run/register.sock` +#: (socket contract d8, section 2.1): `serve` binds it, and the guard's read +#: connects to it. `sun_path` holds 107 bytes on Linux and 103 on macOS, and +#: the contract's `serve` refuses a path over 103 bytes (`path-too-long`, +#: exit 2). Under the bench's `tmp_path` the path followed the temporary root, +#: about 147 bytes on the runner, where lane 1's guard rerun met `OSError: +#: AF_UNIX path too long` (verify-r5-c2b, CI run 43140203269; line AN14). So +#: the `service` row's `XDG_STATE_HOME`, for `serve` and for the guard runs it +#: answers alike, is a `mkdtemp` of the bench's own in `/tmp`, as line G's +#: estates make theirs (T213i): `/tmp/l2bd-` and mkdtemp's 8 characters, 18 +#: bytes, which puts the socket at 50 whatever `TMPDIR` or `--basetemp` is. +#: The bench removes it when the test ends (`Bench.service_env`). No other row +#: starts `serve`, so every other row keeps the bench's state home. +STATE_PARENT = "/tmp" +STATE_PREFIX = "l2bd-" +#: The contract's bound on the socket's path, in bytes (section 2.1). +SOCKET_MAX = 103 + + +class Bench: + """One test's bench: a scratch workspace with a bare origin, the lane's + checkout and W, a clone of its own (T220h), a copy of + `lanes-edit.sh` beside T203's flipped `lanes-index` (the copy rule, CLI4.5 + section 6), a configuration naming the endpoint the fault gives, a login + of the row's group where it needs one, and the timing wrapper first on + `PATH`. For the guard's two rows it also makes a live session record and + a stand-in `tmux` (`guard_session`, T203c) when the row is run. + `register` is the text of the register at C (`REGISTER`), and `name` the + guard session's name (the window's where None); `[answer-2-F1]` passes + both (line BD-19b).""" + + def __init__(self, pg, tmp_path: Path, request, *, register: str = REGISTER, + name: str | None = None): + from sql_register_helpers import flipped_copy, guard_strip_env + self.pg, self.root, self.name = pg, tmp_path, name + self.bin = tmp_path / "bin" + self.bin.mkdir() + self.copy = flipped_copy(INDEXER, tmp_path / "tool", True) + for name in ("lanes-edit.sh", "repos.tsv", "lane-start"): + if (REPO / name).exists(): + shutil.copy2(REPO / name, tmp_path / "tool" / name) + (self.bin / "psql").write_text(TIMING_PSQL, encoding="utf-8") + (self.bin / "psql").chmod(0o755) + self.timing = self.bin / "psql-timing.log" + self.passfile = _private(tmp_path / "conf" / "pgpass") + self.origin = tmp_path / "origin.git" + # THE LANE'S CHECKOUT IS UNDER `$HOME/projects` (HOME is `tmp_path` + # below), so that the guard's scope test (`under_projects_root`, + # clause (e)) lets the prompt through to its reads; outside it the + # guard returns 0 before reading anything (line W4a's T215b). + self.wip = tmp_path / "projects" / "wip" + self.wip.parent.mkdir(parents=True) + #: W, the workspace checkout (Amendment 9(a)), a clone of its own. + self.w = tmp_path / "W" + # THE BASE ENVIRONMENT, T203c's: the lane's, the harness's, tmux's and + # libpq's variables out, and `PROJECTS_ROOT` and `AGENT_PROTOCOL_ROOT` + # with them (F10's item 28), which would move the guard's scope test + # and `workspace.yaml` away from this bench's `$HOME`. + env = guard_strip_env(os.environ) + env.update(HOME=str(tmp_path), XDG_STATE_HOME=str(tmp_path / "state"), + XDG_CONFIG_HOME=str(tmp_path / "config"), TMPDIR=str(tmp_path), + LANES_WORKSTATION="Eagle", LANES_NO_GITHUB="1", LANES_REPO=str(self.wip), + LANES_WORKSPACE_ROOT=str(self.w), + T220_REAL_PSQL=pg.psql_bin, GIT_AUTHOR_NAME="t", GIT_AUTHOR_EMAIL="t@example.invalid", + GIT_COMMITTER_NAME="t", GIT_COMMITTER_EMAIL="t@example.invalid", + PATH=str(self.bin) + os.pathsep + os.environ.get("PATH", os.defpath)) + self.env = env + subprocess.run(["git", "init", "-q", "--bare", "-b", "main", str(self.origin)], + check=True, env=env) + subprocess.run(["git", "clone", "-q", str(self.origin), str(self.wip)], check=True, + env=env, capture_output=True) + (self.wip / "lanes" / "log").mkdir(parents=True) + (self.wip / "lanes" / "LANES.md").write_text(register, encoding="utf-8") + for argv in (["add", "-A"], ["commit", "-q", "-m", "C"], ["push", "-q", "origin", "main"]): + subprocess.run(["git", *argv], cwd=str(self.wip), check=True, env=env, + capture_output=True) + # THE WORKSPACE, W (Amendment 9(a)), is a clone of its own at C, never + # the lane's checkout that `LANES_REPO` names: `import` refuses a + # `LANES_REPO` that names W, or one set where W cannot be read + # (contract 4.18:987; lane 1's group 6, #165 6807494089), and `status` + # and `reconcile` read W's `origin/main`. `lanes-edit.sh + # workspace-root` answers W by `LANES_WORKSPACE_ROOT`, its test seam, + # and `workspace.yaml`'s `path:` names the same W. + subprocess.run(["git", "clone", "-q", str(self.origin), str(self.w)], check=True, + env=env, capture_output=True) + (tmp_path / ".agents").mkdir() + (tmp_path / ".agents" / "workspace.yaml").write_text( + f"repository: {self.origin}\npath: {self.w}\n", encoding="utf-8") + self.c = subprocess.run(["git", "rev-parse", "HEAD"], cwd=str(self.wip), env=env, + capture_output=True, text=True, check=True).stdout.strip() + self.request = request + self.session = None + self.service_state = None + + def to_primary(self) -> None: + """THE BENCH'S DATABASE AT `primary` WITH THE MARKER `present` (T257m; + line BD-18): the bench's own C imported by lane 1's `lanes-index + import --at <C>` (T115) as the operator lane, from its checkout, as + the superuser on the cluster's socket, as test 7's `FixtureRegister` + imports; then AT-LR006's route, the import module's `_to_primary` + (TP:4610-4615 at B14), as T257j's writer rows' `Operator` estate takes + it. A writer's snapshot refuses at its check 4 on any other switch, + and `pg` alone, or a TLS cluster's database, is a bootstrap-only + clone, its switch `files` with the marker `absent` and its head -1 + (line BD17's run of the lookup's wait). Made with `TIMING_PSQL` off + `PATH`, so the timing and begin logs hold the case's own calls alone. + Only the cases whose writers commit call it. + + THE MARKER ON ORIGIN (T257p; lane 4's 6899400726, lane 2's + 6899444735): `lanes/STORE`, its bytes as the cutover's entry holds + them, is then pushed to the bench's own origin in one commit on C, so + a writer that falls back to files mode finds the marker at its own + fetch and ends 69 (`cs_marker_refuse`), never 0 with no journal row. + It is not the real marker commit: it carries no `Register-Seq`, so + the renderer that a committed write starts stops at its walk as + before, and the switch still records `_to_primary`'s stand-in + commit.""" + import hashlib + from types import SimpleNamespace + from test_sql_register_import import _to_primary + url = self.pg.url() + config = _private(self.root / "conf" / "import" / "lanes-index.conf", "\n".join([ + "mode=index", f"register_url={url}", f"register_passfile={self.passfile}", + f"reader_url={url}", f"reader_passfile={self.passfile}", + "register_label=register-test", f"register_schema={SCHEMA}", ""])) + env = dict(self.env, LANES_INDEX_CONFIG=str(config), LANES_LANE="repoA-2", + PATH=os.environ.get("PATH", os.defpath)) + proc = subprocess.run([sys.executable, str(INDEXER), "import", "--at", self.c], + capture_output=True, text=True, env=env, cwd=str(self.wip), + timeout=400, stdin=subprocess.DEVNULL) + assert proc.returncode == 0, \ + f"the bench's import --at C (lane 1's T115): {proc.returncode}: {_said_safely(proc.stderr)}" + tree = subprocess.run(["git", "rev-parse", f"{self.c}:lanes"], cwd=str(self.wip), + env=self.env, capture_output=True, text=True, + check=True).stdout.strip() + _to_primary(self.pg, SimpleNamespace(c=self.c, tree=lambda sha: tree), load_indexer()) + read = self.pg.psql(f"SELECT text FROM {SCHEMA}.doc_lines WHERE path = 'lanes/STORE' " + f"ORDER BY line_no;") + rows = read.stdout + digest = self.pg.psql(f"SELECT sha256 FROM {SCHEMA}.files WHERE path = 'lanes/STORE' " + f"AND final_newline;").stdout.strip() + assert hashlib.sha256(rows.encode("utf-8")).hexdigest() == digest, ( + f"lanes/STORE as the register holds it does not hash to the sha256 it holds for it " + f"(the text's read: {_said_safely(read)}; the sha256 read has {len(digest)} characters)") + # A clone of its own, so the bench's checkout and W keep their last fetch. + marker = self.root / "marker" + subprocess.run(["git", "clone", "-q", str(self.origin), str(marker)], check=True, + env=self.env, capture_output=True, stdin=subprocess.DEVNULL) + (marker / "lanes" / "STORE").write_bytes(rows.encode("utf-8")) + for argv in (["add", "--", "lanes/STORE"], + ["commit", "-q", "-m", "The bench's stand-in marker: lanes/STORE alone"], + ["push", "-q", "origin", "HEAD:main"]): + subprocess.run(["git", *argv], cwd=str(marker), check=True, env=self.env, + capture_output=True, stdin=subprocess.DEVNULL) + + def lane_checkout(self) -> Path: + """`<c>`, lane `repoA-2`'s own register checkout, made once (T257l; lane 4's triage, + #165 6833813092, its group b1): on primary a write runs from it, and where it is not there + the write refuses with nothing sent (`lanes-edit.sh`'s `pw_checkout`, T415's R17), since a + clone is a fetch (D12). It sits where `lane_checkout_path` puts it (Amendment 23 S1), + `<W>-lanes/<lane>`, W being the real path of this bench's W, which `LANES_WORKSPACE_ROOT` + names; and it is a clone of W's origin, as `lane-checkout <lane> --create` makes one and + as `test_sql_register_writes.py`'s `make_lane_checkout` makes it. The bench makes `<c>` + itself, because `lane-start` makes it only under `LANES_ROUTE_WRITES=1` with neither + `LANES_REPO` nor `LANES_FILE` set (lane 3, #165 6841265575; + `dfc4ce4c:lane-start:1209-1210`). A bench that runs no writer makes none.""" + real = Path(os.path.realpath(self.w)) + target = real.parent / f"{real.name}-lanes" / "repoA-2" + if not target.exists(): + target.parent.mkdir(parents=True, exist_ok=True) + subprocess.run(["git", "clone", "-q", str(self.origin), str(target)], check=True, + env=self.env, capture_output=True, stdin=subprocess.DEVNULL) + return target + + def guard_session(self): + """The guard rows' live session (T203c): a record on this workstation + for a live pid, and a stand-in `tmux` that answers the guard's window + queries, written to this bench's `bin`, for the checkout under + `$HOME/projects`, with `SID`, the id the bench's register row names + (T220e), named `self.name` where the bench was given one. Made once, + torn down when the test ends.""" + from sql_register_helpers import guard_session + if self.session is None: + self.session = guard_session(self.root, self.bin, self.wip, session_id=SID, + name=self.name) + self.request.addfinalizer(self.session.close) + return self.session + + def login(self, group: str, floors: bool = False) -> str: + """A login of `group`, made here until T228's logins exist. With + `floors`, a writer login also takes the writer's floors that `login + add` sets on each writer login (design.md section 1.4's login step, + Y:2302-2309; `lanes-index`'s `_REGISTER_LOGIN_BLOCK`): `lock_timeout` + 2000 ms, `statement_timeout` 5 s and `idle_in_transaction_session_ + timeout` 5 s, the login's own, so a session that sets none of them + has them, as the idle bound's held session needs (T257m; line + BD-18). A register call's own bounds ride `PGOPTIONS`, which a + login's settings never override.""" + name = f"t220_{uuid.uuid4().hex[:12]}" + self.pg.psql(f"CREATE ROLE {name} LOGIN IN ROLE {group};") + self.request.addfinalizer(lambda: self.pg.cluster.psql(f"DROP ROLE IF EXISTS {name};", + check=False)) + if floors: + assert group == "lanes_register_writer", f"the writer's floors, on {group}" + self.pg.psql(f"ALTER ROLE {name} SET lock_timeout = '2000ms';\n" + f"ALTER ROLE {name} SET statement_timeout = '5s';\n" + f"ALTER ROLE {name} SET idle_in_transaction_session_timeout = '5s';\n") + return name + + def config(self, host: str, port: int, user: str, mode: str = "primary") -> Path: + """A configuration whose two URLs name `host:port` and this test's + database, as `user`; no `connect_timeout=` or `register_addresses=`, + so `c` is 2 and `N_a` 1.""" + url = f"postgresql://{user}@{host}:{port}/{self.pg.name}" + return _private(self.root / "conf" / "lanes-index.conf", "\n".join([ + f"mode={mode}", f"register_url={url}", f"register_passfile={self.passfile}", + f"reader_url={url}", f"reader_passfile={self.passfile}", + "register_label=register-test", f"register_schema={SCHEMA}", ""])) + + def run(self, row: str, config: Path, *, stdin: str | None = None, + service: subprocess.Popen | None = None) -> tuple: + """Run `row`'s path; return (the process, its elapsed seconds). The + `service` row starts `lanes-index serve` for this run alone, unless the + caller passes the one it holds (T237y), and runs under the service's + short state home (`service_env`), as that `serve` does.""" + env = dict(self.env, LANES_INDEX_CONFIG=str(config), LANES_LANE="repoA-2") + tool = self.copy.parent + index = [sys.executable, str(self.copy)] + if row in ("guard", "answer-2", "service"): + argv = ["bash", str(tool / "lanes-edit.sh"), "guard"] + # THE SESSION (T203c): a live record in the window `repoA-2` and a + # stand-in `tmux`, so that the guard gets past its session-record + # check, clause (d), to its register read. The hook's JSON is + # compact, as the harness sends it: the guard's `jstr` reads + # `"cwd":"<dir>"` with no blank after the colon. + session = self.guard_session() + env = session.env(env) + stdin = session.hook_input("2" if row == "answer-2" else "hello") + if row == "service": + env = self.service_env(env) + elif row == "reader": + argv = index + ["register", "read", "--prefetch", "--cache", + str(self.root / "cache" / "reg"), "--files", "register,aliases"] + (self.root / "cache").mkdir(exist_ok=True) + elif row == "renderer-reads": + argv = index + ["journal", "--since", "0"] + elif row == "reconcile": + argv = index + ["reconcile"] + elif row == "import": + argv = index + ["import", "--at", self.c] + elif row == "status": + argv = index + ["status"] + elif row == "outage-probe": + # `--mirror-seq 0` (T220g; T218g's, line RE's A15): on Brett's word + # with no `--mirror-seq`, the declare reads the mirror's `m` after + # a fetch (F11), and this bench's origin holds no `Register-Seq`, + # so it would refuse 2, "no mirror-seq". 0 is T218g's value, which + # lane 1's code takes as any whole number. No closed port: the + # row's own fault keeps the probe from an answer. + argv = index + ["outage", "declare", "--until", "2999-01-01T00:00:00Z", + "--why", "D9's probe row", "--mirror-seq", "0"] + elif row == "mode-query": + argv = index + ["mode"] + elif row == "writer-snapshot": + # A WRITER'S WHOLE PATH, `set-row-state` on the bench's lane, whose + # snapshot meets the fault; the deadline is D9's test value. A + # reading: T257's text names the rows, not the verb that carries + # them. The writer rows whose fault comes after the snapshot's + # check 4 run on `Operator`'s estate (`Operator.write`; T257j). + argv = ["bash", str(tool / "lanes-edit.sh"), "set-row-state", "repoA-2", + f"PAUSED {DOT} T257's writer row"] + env = dict(env, LANES_REGISTER_DEADLINE_S="3", LANES_LANE="repoA-2") + self.lane_checkout() + elif row == "lookup": + # THE LOOKUP'S FORM (AT-F6 case 19; lane 1's T114, `refs/l1/T114-fu3`): + # `journal --write-id <id> --not-after <epoch s> --generation <g> + # --lane <l> --verb <v> --args-sha256 <h>`, for a write the database + # never saw. `--not-after` is epoch seconds, a minute past, so a + # healthy try would answer `absent`, never LR011; with no `--clock` + # the client calls at once (T257c; T257a's UTC text was usage, 64). + self.write_id = str(uuid.uuid4()) + argv = index + ["journal", "--write-id", self.write_id, "--not-after", + str(int(time.time()) - 60), "--generation", str(uuid.uuid4()), + "--lane", "repoA-2", "--verb", "set-row-state", "--args-sha256", + "0" * 64] + else: + raise AssertionError(f"no path for {row}") + serve = None + if row == "service" and service is None: + serve = self.start_service(env) + try: + # `subprocess.run`'s form, with the command's pid and its exit + # stamp kept for `request_elapsed` (T220f). + start = time.monotonic() + with subprocess.Popen(argv, stdin=subprocess.PIPE if stdin is not None + else subprocess.DEVNULL, stdout=subprocess.PIPE, + stderr=subprocess.PIPE, text=True, env=env, + cwd=str(self.wip)) as child: + self.pid = child.pid + try: + out, err = child.communicate(stdin, timeout=700) + except subprocess.TimeoutExpired: + child.kill() + raise + self.exited = time.monotonic() + proc = subprocess.CompletedProcess(argv, child.returncode, out, err) + return proc, self.exited - start + finally: + if serve is not None: + self.stop_service(serve) + + def calls(self) -> list: + if not self.timing.exists(): + return [] + return [json.loads(l) for l in self.timing.read_text(encoding="utf-8").splitlines() + if l and json.loads(l)["argv"] != ["--version"]] + + def request_elapsed(self) -> float: + """`status`'s time (T220f; lane 3's T220 bullet, #165 comment + 6772120103): from the register's request's start to the command's + exit, never from the command's start, since #160's half runs first + (lane 1's T117 point 6, 6769905855). The stamp lane 2 chooses is the + begin stamp of the first `psql` that the command's own process starts + on the register's path: its once-per-process `psql --version`, which + T117's `_run_register` counts inside the request's client timer, or + else the call with section 2.2's argv. A `psql` started by another + process, or with #160's argv, is not the request's.""" + log = self.bin / "psql-begin.log" + begins = [json.loads(l) for l in log.read_text(encoding="utf-8").splitlines() if l] \ + if log.exists() else [] + own = [b["begin"] for b in begins if b["ppid"] == self.pid + and b["argv"] in (["--version"], REGISTER_ARGV)] + assert own, "the command started no psql on the register's path: no request was sent" + return self.exited - min(own) + + def begins(self) -> list: + """The begin stamps (T220f) of each `psql` call that the command's own + process started with section 2.2's argv, in order: a call its client + timer killed is stamped too, though it never reaches the timing log + (T257c).""" + log = self.bin / "psql-begin.log" + begins = [json.loads(l) for l in log.read_text(encoding="utf-8").splitlines() if l] \ + if log.exists() else [] + return [b for b in begins if b["ppid"] == self.pid and b["argv"] == REGISTER_ARGV] + + def guard_env(self, config: Path) -> dict: + """The guard rows' environment for `config`, as `run` makes it: the + bench's, the configuration, the lane, and the live session's.""" + env = dict(self.env, LANES_INDEX_CONFIG=str(config), LANES_LANE="repoA-2") + return self.guard_session().env(env) + + def service_env(self, env: dict) -> dict: + """`env` with the `service` row's state home (`STATE_PREFIX`): one + short directory of this bench's own in `/tmp`, made at the first call + and removed when the test ends, so `serve` and the guard runs it + answers share one socket path within `SOCKET_MAX` bytes.""" + if self.service_state is None: + home = Path(tempfile.mkdtemp(prefix=STATE_PREFIX, dir=STATE_PARENT)) + self.request.addfinalizer(lambda: shutil.rmtree(home, ignore_errors=True)) + sock = home / "openRepoTools" / "run" / "register.sock" + assert len(os.fsencode(str(sock))) <= SOCKET_MAX, \ + f"the service's socket path {sock} is over {SOCKET_MAX} bytes" + self.service_state = home + return dict(env, XDG_STATE_HOME=str(self.service_state)) + + def start_service(self, env: dict) -> subprocess.Popen: + """`lanes-index serve` on `env`, returned once its socket is bound at + the one socket path (socket contract d8, section 2.1).""" + sock = Path(env.get("XDG_STATE_HOME", str(Path(env["HOME"]) / ".local" / "state"))) \ + / "openRepoTools" / "run" / "register.sock" + serve = subprocess.Popen([sys.executable, str(self.copy), "serve"], env=env, + cwd=str(self.wip), stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + start_new_session=True) + end = time.monotonic() + 10 + while not sock.exists() and time.monotonic() < end and serve.poll() is None: + time.sleep(0.05) + if not sock.exists(): + self.stop_service(serve) + assert sock.exists(), f"lanes-index serve bound no socket at {sock}: {serve.poll()}" + return serve + + @staticmethod + def stop_service(serve: subprocess.Popen) -> None: + """`serve` and every process of its session ended and reaped (T237zzl).""" + _end_process(serve, group=True) + + def stream(self) -> None: + """`STREAM_PSQL` first on `PATH` in place of `TIMING_PSQL` (T237y).""" + (self.bin / "psql").write_text(STREAM_PSQL, encoding="utf-8") + (self.bin / "psql").chmod(0o755) + + def streamed(self) -> list: + """`STREAM_PSQL`'s 57014 lines, each with its request's send stamp.""" + log = self.bin / "psql-stream.log" + return [json.loads(l) for l in log.read_text(encoding="utf-8").splitlines() if l] \ + if log.exists() else [] + + +def _end_process(proc: subprocess.Popen, *, group: bool, wait: float = 10.0) -> None: + """`proc` ended and reaped, and never signalled once its pid may be + another process's (T237zzn; Codex's review of P09 at `21dd3642`, + BLOCKING). A process already reaped, `returncode` set, as after a `poll()` + or a `communicate()` that saw it end, gets no signal. Otherwise each + signal is sent while it is still unreaped, so its pid, and with `group` + the id of the process group `start_new_session=True` made it lead, are + still its own: TERM; up to `wait` s for its exit, watched by + `os.waitid(..., WNOWAIT)`, which does not reap it; KILL; then one reap, + `proc.wait(wait)`, whose `TimeoutExpired` is raised, not suppressed. A + reap by anything else meanwhile raises `ChildProcessError` from + `os.waitid`, before the KILL. With `group`, TERM and KILL go to the + group, so a child it started, such as the service's `psql`, gets them.""" + if proc.returncode is not None: + return + + def send(sig: int) -> None: + with contextlib.suppress(ProcessLookupError, PermissionError): + (os.killpg if group else os.kill)(proc.pid, sig) + send(signal.SIGTERM) + end = time.monotonic() + wait + while time.monotonic() < end: + if os.waitid(os.P_PID, proc.pid, os.WEXITED | os.WNOHANG | os.WNOWAIT) is not None: + break + time.sleep(0.05) + send(signal.SIGKILL) + proc.wait(wait) + + +def _signals_kept_to_unreaped(monkeypatch) -> list: + """For the no-engine cases of the bench's clean-up (T237zzx): `os.kill` + and `os.killpg` replaced, for the case, by forms that send a signal only + while its target, a pid or the group its pid leads, is still an unreaped + child of this process, as `os.waitid(..., WNOWAIT)` sees it. Any other + signal is sent to nothing and recorded, as (call, pid, signal), in the + list returned.""" + late, real = [], {"kill": os.kill, "killpg": os.killpg} + + def unreaped(pid: int) -> bool: + try: + os.waitid(os.P_PID, pid, os.WEXITED | os.WNOHANG | os.WNOWAIT) + except ChildProcessError: + return False + return True + + def kept(call: str): + def send(pid: int, sig: int) -> None: + if unreaped(pid): + real[call](pid, sig) + else: + late.append((call, pid, signal.Signals(sig).name)) + return send + monkeypatch.setattr(os, "kill", kept("kill")) + monkeypatch.setattr(os, "killpg", kept("killpg")) + return late + + +def test_the_bench_cleanup_signals_a_process_only_while_it_is_unreaped_and_raises_a_failed_reap( + monkeypatch): + """`_end_process` (T237zzn; Codex's review of P09 at `21dd3642`, + BLOCKING), with no engine (T237zzx): on processes this case starts, each + in a session of its own as the service is, with `group` and without, and + `_signals_kept_to_unreaped` between it and every signal. + + (a) A process already reaped, as `start_service`'s `poll()` leaves a + service that ended before it bound: no signal at all. + (b) One that TERM ends: its exit is -SIGTERM, and nothing is signalled + once it is reaped. + (c) One deaf to TERM: KILL ends it once `wait` has passed. + (d) One whose reap times out (its `wait` replaced by one that raises): + `TimeoutExpired` is raised, not suppressed. + + Before T237zzn, with `group`, (a) sent TERM and KILL to the reaped + process's number and (b) KILL after its own reap; and (d) returned as if + the process were reaped, in both modes.""" + late = _signals_kept_to_unreaped(monkeypatch) + + def start(argv: list) -> subprocess.Popen: + return subprocess.Popen(argv, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, + start_new_session=True) + + for group in (True, False): + proc = start(["true"]) + proc.communicate(timeout=30) + _end_process(proc, group=group, wait=5) + assert late == [], f"(a) group={group}: a reaped process was signalled: {late}" + + proc = start(["sleep", "30"]) + _end_process(proc, group=group, wait=5) + proc.stdout.close() + assert (proc.returncode, late) == (-signal.SIGTERM, []), \ + f"(b) group={group}: exit {proc.returncode}, signals after the reap {late}" + + proc = start(["bash", "-c", "trap '' TERM; echo deaf; exec sleep 30"]) + assert proc.stdout.readline() == b"deaf\n", "(c) the stand-in never ignored TERM" + _end_process(proc, group=group, wait=0.5) + proc.stdout.close() + assert (proc.returncode, late) == (-signal.SIGKILL, []), \ + f"(c) group={group}: exit {proc.returncode}, signals after the reap {late}" + + proc = start(["sleep", "30"]) + + def stuck(timeout=None, proc=proc): + raise subprocess.TimeoutExpired(proc.args, timeout) + proc.wait = stuck + try: + with pytest.raises(subprocess.TimeoutExpired): + _end_process(proc, group=group, wait=5) + finally: + del proc.wait + proc.wait(30) + proc.stdout.close() + assert late == [], f"(d) group={group}: signals after the reap {late}" + + +def _record(row: str, elapsed: float, bound: float, rule: str) -> None: + """Timing rule 2's record: the measured time, the design's bound, its + margin.""" + print(f"D9 {row}: {elapsed:.2f} s against the design's {bound:g} s ({rule}); " + f"margin {bound - elapsed:+.2f} s") + + +def _hold(pg, table: str): + """F3: an `ALTER TABLE` on `table` in an open transaction of the test's + own session, held until the session is closed. Returns the session once + the lock is granted.""" + session = pg.session(appname="t220-f3") + session.stdin.write(f"BEGIN;\nALTER TABLE {SCHEMA}.{table} ADD COLUMN t220_f3 integer;\n") + session.stdin.flush() + deadline = time.monotonic() + 30 + while time.monotonic() < deadline: + held = pg.psql("SELECT count(*) FROM pg_locks l JOIN pg_stat_activity a USING (pid) " + "WHERE a.application_name = 't220-f3' AND l.granted " + "AND l.mode = 'AccessExclusiveLock';").stdout.strip() + if held not in ("", "0"): + return session + time.sleep(0.1) + session.kill() + raise AssertionError("F3's lock was never granted") + + +def _end(session) -> None: + try: + session.stdin.write("ROLLBACK;\n") + session.stdin.close() + session.wait(timeout=30) + except (OSError, subprocess.TimeoutExpired): + session.kill() + + +@pytest.mark.parametrize("case", FIRST_CASES) +def test_each_database_path_exits_inside_its_bound(pg, tmp_path, request, case): + """D9: each phase-N path exits with its row's expiry outcome inside its + bound, under F1 (a silent listener, met at the connect), F2 (a relay + silent after the startup) and F3 (a lock on the table it reads). It owns + test 10's per-path cases (section 4.4). `migration` is the dedicated + test's below, `test_a_waiting_migration_gives_up_at_its_own_lock_timeout`, + and its F1 case here is the migration's connect, through T109's + `bootstrap` (`_migration`).""" + row, fault = case.rsplit("-", 1) + spec = ROWS[row] + if row in OPERATOR_ROWS: + _operator_row(pg, tmp_path, request, row, fault) + return + if row == "snapshot-miss": + _snapshot_miss(pg, tmp_path, request, fault) + return + if row in PRIMARY_WRITER_ROWS: + _primary_writer_row(pg, tmp_path, request, row, fault) + return + if row == "answer-2": + _answer_2_row(pg, tmp_path, request, fault) + return + bench = Bench(pg, tmp_path, request) + user = bench.login(spec["group"]) if spec["group"] else "lanes_test" + if row == "migration": + _migration(bench, fault) + return + listener, session = None, None + try: + if fault == "F1": + listener = SilentListener() + config = bench.config("127.0.0.1", listener.port, user) + elif fault == "F2": + listener = StartupRelay(f"{pg.host}/.s.PGSQL.{pg.port}") + config = bench.config("127.0.0.1", listener.port, user) + else: + session = _hold(pg, spec["table"]) + config = bench.config(quote(str(pg.host), safe=""), pg.port, user) + if row == "mode-query": + config.write_text(config.read_text().replace("mode=primary", "mode=index")) + proc, elapsed = bench.run(row, config) + finally: + if listener is not None: + listener.close() + if session is not None: + _end(session) + if spec["exit"] is not None: + assert proc.returncode == spec["exit"], f"{case}: {proc.returncode}: {_said_safely(proc.stderr)}" + else: + assert proc.returncode != 0, f"{case}: the path ended without its read" + if row == "reader": + # NOTHING PAST THE MODE LINE (T220j; lane 3, #165 6807694145: "the + # contract stands"): `register read` prints its `mode` line first in + # every form (4.18:758-760; B14 tasks:454), so a refused reader's + # "nothing on stdout" (TP:3603) is its `mode primary` line alone. + assert proc.stdout == "mode primary\n", \ + f"a reader's 69 prints its mode line and nothing more: {_said_safely(proc)!r}" + if row == "mode-query": + assert proc.stdout == "index\n" and bench.calls() == [], "the query reads no database" + if row == "status": + # T220f: D9's row bounds the register's request, so `status` is timed + # from that request's start to its exit, never from the command's + # start (lane 3, #165 comments 6772120103 and 6770600106, ruling 6). + elapsed = bench.request_elapsed() + if spec["strict"]: + assert elapsed < spec["bound"], f"{case}: {elapsed:.2f} s, not under {spec['bound']} s" + _record(case, elapsed, spec["bound"], "timing rule 1") + else: + assert elapsed < 2 * spec["bound"], f"{case}: {elapsed:.2f} s against {spec['bound']} s" + _record(case, elapsed, spec["bound"], "timing rule 2" + ( + ", from the register request's start" if row == "status" else "")) + + +def _answer_2_row(pg, tmp_path: Path, request, fault: str) -> None: + """`[answer-2-F1]` (line BD-19b; lane 3's ruling, #165 6840828270): the + row follows a healthy call (TP:3586-3589), since the guard's one prefetch + is the first read of every prompt, an answer to its offer included + (T507), and answer 2 adds no database call to the hook (Y:5417). + + 1. The offer is made on a healthy register: the bench at `primary` + (`Bench.to_primary`) with `REGISTER_OFFER`, its session named + `OFFER_TO`, and one guard prompt, which must leave the offer record, + `mode=name-drift`, as AT-F6's `make_offer` asserts it. + 2. `2` is sent through `ArmedFault`, which passes each connection whole + until `TIMING_PSQL`'s log shows that the hook's register read has + ended, and from then holds each new one (F1). + 3. The hook exits 2 with "BINDING" under 4.5 s (TP:3595); its read is in + the log, ended 0; and it began no register call after it (AT-F6 case + 21, TP:6190-6191). The hook's calls are those in its own session: the + wrapper names each call's, and `guard_answer` detaches the bind with + `setsid` into one of its own. + 4. The detached bind meets F1 after the hook exits, bounded as AT-F6's + fixture bounds its binds (`LANES_BIND_BOUND_S`, `ANSWER_2_BIND_S`). + The relay stays up until the bind has written its outcome, at most + `ANSWER_2_WAIT_S`. F1 held one connection or more, as this module's + other F1 cases assert `silenced`, and the outcome is `bind-failed`, + never `bound` (lane 2's RV20, NIT 12; T220m). + + It fails until T502 (T220's Order).""" + spec = ROWS["answer-2"] + case = f"answer-2-{fault}" + bench = Bench(pg, tmp_path, request, register=REGISTER_OFFER, name=OFFER_TO) + bench.to_primary() + user = bench.login(spec["group"]) + bench.env = dict(bench.env, LANES_BIND_BOUND_S=str(ANSWER_2_BIND_S)) + mine = os.getsid(0) + offer = tmp_path / ".claude" / "lanes" / "offers" / SID + mark = [] + + def read_ended() -> bool: + return bool(mark) and any(c.get("sid") == mine for c in bench.calls()[mark[0]:]) + + relay = ArmedFault(f"{pg.host}/.s.PGSQL.{pg.port}", fault, read_ended) + outcome = {} + try: + config = bench.config("127.0.0.1", relay.port, user) + made, _ = bench.run("guard", config) + record = _offer_record(offer) + assert made.returncode == 2 and record.get("mode") == "name-drift" \ + and record.get("to") == OFFER_TO, \ + f"{case}: the guard made no offer on a healthy register: {made.returncode}: " \ + f"{record}: {_said_safely(made.stderr)}" + begun = len(_begin_log(bench)) + mark.append(len(bench.calls())) + proc, elapsed = bench.run("answer-2", config) + if "BINDING" in proc.stdout + proc.stderr: + outcome = _bind_outcome(offer, ANSWER_2_WAIT_S) + finally: + relay.close() + assert proc.returncode == spec["exit"], f"{case}: {proc.returncode}: {_said_safely(proc.stderr)}" + assert "BINDING" in proc.stdout + proc.stderr, f"{case}: no BINDING: {_said_safely(proc)}" + assert elapsed < spec["bound"], f"{case}: {elapsed:.2f} s, not under {spec['bound']} s" + reads = [c for c in bench.calls()[mark[0]:] if c.get("sid") == mine] + assert len(reads) == 1 and reads[0]["exit"] == 0, \ + f"{case}: the hook's register read is not in the log, ended 0: {reads}" + own = [b for b in _begin_log(bench)[begun:] + if b.get("sid") == mine and b["argv"] != ["--version"]] + later = [b for b in own if b["begin"] > reads[0]["end"]] + assert len(own) == 1 and not later, \ + f"{case}: the hook made a register call besides its read (Y:5417): {own}" + _record(case, elapsed, spec["bound"], "timing rule 1") + print(f"D9 {case}: the detached bind's outcome {outcome.get('mode')} (rc " + f"{outcome.get('rc')}); F1 held {relay.silenced} connection(s) after the hook's read") + assert outcome, (f"{case}: the detached bind wrote no outcome in {ANSWER_2_WAIT_S} s, " + f"bounded at {ANSWER_2_BIND_S} s: {_offer_record(offer)}") + assert relay.silenced >= 1 and outcome.get("mode") == "bind-failed", ( + f"{case}: the detached bind did not meet F1 and fail: F1 held {relay.silenced} connection(s), " + f"and the outcome is {outcome}") + + +def _offer_record(path: Path) -> dict: + """The guard's offer record, its `key=value` lines, the first of each key + winning as the guard reads it (AT-F6's `read_record`); {} where there is + none.""" + try: + text = path.read_text(encoding="utf-8") + except OSError: + return {} + record = {} + for line in text.splitlines(): + key, sep, value = line.partition("=") + if sep: + record.setdefault(key, value) + return record + + +def _bind_outcome(path: Path, limit: float) -> dict: + """The offer record once the detached bind has written its outcome, + `bound` or `bind-failed`; {} where it has not within `limit` s.""" + deadline = time.monotonic() + limit + while time.monotonic() < deadline: + record = _offer_record(path) + if record.get("mode") in ("bound", "bind-failed"): + return record + time.sleep(0.2) + return {} + + +def _begin_log(bench: Bench) -> list: + """`TIMING_PSQL`'s begin stamps, every process's, in order.""" + log = bench.bin / "psql-begin.log" + return [json.loads(l) for l in log.read_text(encoding="utf-8").splitlines() if l] \ + if log.exists() else [] + + +def _slow_statement(pg, table: str, group: str, seconds: float) -> None: + """F4: a sleep the test creates in its own database, never the + template: a row-level security policy on `table` for `group` that sleeps + past the path's `statement_timeout`.""" + pg.psql(f"SET search_path TO {SCHEMA};\n" + f"CREATE FUNCTION t220_slow() RETURNS boolean LANGUAGE sql VOLATILE AS " + f"$$ SELECT pg_sleep({seconds}) IS NOT NULL $$;\n" + f"GRANT EXECUTE ON FUNCTION t220_slow() TO {group};\n" + f"ALTER TABLE {table} ENABLE ROW LEVEL SECURITY;\n" + f"CREATE POLICY t220_slow ON {table} FOR ALL TO {group} USING (t220_slow());\n") + + +#: The guard's line where the service did not answer (socket contract d8, +#: section 5.3), and the warm-up's guard runs at most (T237y). +FALLBACK_LINE = "guard: direct (service unavailable)" +WARM_RUNS = 20 + + +def _service_57014(bench: Bench, spec: dict, user: str) -> None: + """`[service]`'s F4 (T237y; line W3aX's finding on T237x): the guard + through a WARM service, whose held child's request meets 57014 at the + request's 180 ms `statement_timeout` (lane 5's answer 3, #165 comment + 6771208498; d8:214). `lanes-index serve` is started once, with + `STREAM_PSQL` first on `PATH`, so its "one long-lived `psql` child on + pipes" (d8:229) runs through a wrapper that hands each request on as it + comes; guard runs warm it, up to `WARM_RUNS`, until one is answered + through the service, with no `FALLBACK_LINE` (a cold service answers + `unavailable` until its `psql` has connected, d8:502); only then is F4's + slow statement made and the guard run once more. The held child, known + by its own argv's `VERBOSITY=sqlstate` (d8:229), prints `ERROR: 57014` + no earlier than 180 ms after its request was handed to it (timing rule 3) + and under twice it (timing rule 2), and the guard exits 2. It fails until + L5-S1 (lane 5's T511 to T513) and L5-A3 land.""" + config = bench.config(quote(str(bench.pg.host), safe=""), bench.pg.port, user) + statement_s = spec["statement_ms"] / 1000 + bench.stream() + serve = bench.start_service(bench.service_env(bench.guard_env(config))) + try: + proc, warm = None, False + for _ in range(WARM_RUNS): + proc, _ = bench.run("service", config, service=serve) + if FALLBACK_LINE not in proc.stdout + proc.stderr: + warm = True + break + time.sleep(0.25) + assert warm, (f"service: no guard run of {WARM_RUNS} was answered through the " + f"service: {proc.returncode}: {_said_safely(proc.stderr)}") + _slow_statement(bench.pg, spec["table"], spec["group"], 4 * statement_s + 5) + proc, _ = bench.run("service", config, service=serve) + finally: + bench.stop_service(serve) + held = [s for s in bench.streamed() if "VERBOSITY=sqlstate" in s["argv"]] + assert held, f"service: the held child met no 57014: {bench.streamed()}" + took = held[0]["error"] - held[0]["request"] + assert statement_s <= took < 2 * statement_s, \ + f"service: the held child's 57014 {took:.3f} s after its request" + assert proc.returncode == spec["exit"], f"service: {proc.returncode}: {_said_safely(proc.stderr)}" + _record("service-F4", took, statement_s, "timing rules 2 and 3, the held child's request") + + +@pytest.mark.parametrize("row", SLOW_ROWS) +def test_a_slow_statement_meets_57014_before_the_client_timer(pg, tmp_path, request, row): + """F4, on every phase-N row that sets a `statement_timeout`: the call + ends with 57014, the server's bound and not the client timer, no earlier + than the path's `statement_timeout` after the call's start (timing rule + 3) and under twice it (timing rule 2), and the path exits with its row's + outcome (AT-D9, "Oracle"). `[service]` times the warm service's held + child, through `STREAM_PSQL` (T237y, `_service_57014`). A writer's + commit, `[writer-commit-f2]`, meets a trigger on `journal` and exits 69, + a refusal the database made (T257h), on `Operator`'s estate at `primary` + (T257j, `_primary_writer_57014`).""" + spec = ROWS[row] + if row in OPERATOR_ROWS: + _operator_57014(pg, tmp_path, request, row) + return + if row in PRIMARY_WRITER_ROWS: + _primary_writer_57014(pg, tmp_path, request, row) + return + bench = Bench(pg, tmp_path, request) + user = bench.login(spec["group"]) + if row == "service": + _service_57014(bench, spec, user) + return + statement_s = spec["statement_ms"] / 1000 + if row == "lookup": + # `find_write` is SECURITY DEFINER (`lanes-index:7863` at + # `refs/l1/V-round5`), so a policy for the writer's group never binds + # it: it locked the head row unslowed and refused LR007 on the row's + # random `--generation` at once (AN13b's cause 3). The lookup's F4 is + # `_slow_lookup`'s policy, forced on `journal` and `register_head`, as + # the lookup's own `[F4]` case meets it (AT-D9's F4: "a policy forced + # on `journal` for its owner, since `find_write` runs as the owner"). + _slow_lookup(pg, 4 * statement_s + 5) + else: + _slow_statement(pg, spec["table"], spec["group"], 4 * statement_s + 5) + proc, elapsed = bench.run(row, bench.config(quote(str(pg.host), safe=""), pg.port, user)) + ended = [c for c in bench.calls() if "57014" in c["first"]] + assert ended, f"{row}: no call ended with 57014: {bench.calls()}" + took = ended[0]["end"] - ended[0]["start"] + assert statement_s <= took < 2 * statement_s, f"{row}: 57014 after {took:.2f} s" + if spec["exit"] is not None: + assert proc.returncode == spec["exit"], f"{row}: {proc.returncode}: {_said_safely(proc.stderr)}" + _record(f"{row}-F4", took, statement_s, "timing rules 2 and 3") + + +@pytest.mark.parametrize("case", ["F1-word", "F2-word", "F3-word", "F1-rollback", "F2-rollback", + "F3-rollback"]) +def test_the_outage_declare_probe_ends_inside_its_bound_and_the_declaration_follows_the_rule( + pg, tmp_path, request, case): + """`outage declare`'s database probe (section 2.5's row): 2 s, 2000 ms, + 5000 ms, 8 s. On a person's word, the declaration is written, since the + database does not answer from this host; in the `--rollback` form, 2 and + no file, the switch being unread. The probe ends inside twice its 8 s + (AT-D9's table).""" + fault, form = case.split("-", 1) + bench = Bench(pg, tmp_path, request) + user = bench.login("lanes_register_writer") + listener, session = None, None + try: + if fault == "F1": + listener = SilentListener() + config = bench.config("127.0.0.1", listener.port, user) + elif fault == "F2": + listener = StartupRelay(f"{pg.host}/.s.PGSQL.{pg.port}") + config = bench.config("127.0.0.1", listener.port, user) + else: + session = _hold(pg, "register_switch") + config = bench.config(quote(str(pg.host), safe=""), pg.port, user) + # D20 (Y:3073): `outage declare --until <UTC> --why "<words>"`; the rollback + # form is `--rollback --mirror-seq <k>`, with no `--until` (lane 1, #165 + # comment 6754680212). + # On Brett's word the declare is given `--mirror-seq 0`, T218g's value + # (T220g, as `Bench.run`'s `outage-probe` row): the bench's origin + # holds no mirror `Register-Seq` to read after a fetch (F11). No + # closed port: the case's fault keeps the probe from an answer. + argv = [sys.executable, str(bench.copy), "outage", "declare"] + if form == "rollback": + argv += ["--rollback", "--mirror-seq", "1"] + else: + argv += ["--until", "2999-01-01T00:00:00Z", "--why", "D9's probe", + "--mirror-seq", "0"] + env = dict(bench.env, LANES_INDEX_CONFIG=str(config), LANES_LANE="repoA-2") + start = time.monotonic() + proc = subprocess.run(argv, capture_output=True, text=True, env=env, cwd=str(bench.wip), + timeout=120, stdin=subprocess.DEVNULL) + elapsed = time.monotonic() - start + finally: + if listener is not None: + listener.close() + if session is not None: + _end(session) + declaration = config.parent / "register-outage" + if form == "word": + assert proc.returncode == 0, _said_safely(proc) + assert declaration.exists(), "the declaration is written" + else: + assert proc.returncode == 2, _said_safely(proc) + assert not declaration.exists(), "no file in the --rollback form" + assert elapsed < 2 * 8, f"{case}: {elapsed:.2f} s" + _record(f"outage-probe-{case}", elapsed, 8, "timing rule 2") + + +#: T109's argv (lane 1, #165 comment 6754680212): the admin is a libpq service, +#: `--admin-service <service>`, with `--label`, `--repository` and `--lane`, which +#: its USAGE lists on one synopsis (`--lane` is required unless `--roles-only`). +#: It refuses off a terminal unless `--no-passwords` is given, so each call here +#: runs under `_in_pty` and passes no `--no-passwords`. +BOOTSTRAP_FLAGS = ["--admin-service", "t220-admin", "--label", "register-test", + "--repository", "opensoft/t220-register", "--lane", "repoA-2"] + + +def _migration(bench: Bench, fault: str) -> None: + """The migration's path, through `lanes-index bootstrap` under a pty + (T109: it refuses when stdout is not a terminal), its admin reached only + as the libpq service `--admin-service` names (T109). Under F1 its connect + meets the silent listener and it is refused, writing nothing.""" + listener = SilentListener() + try: + service = bench.root / "pg_service.conf" + service.write_text(f"[t220-admin]\nhost=127.0.0.1\nport={listener.port}\n" + f"dbname={bench.pg.name}\nuser=lanes_test\n", encoding="utf-8") + env = dict(bench.env, PGSERVICEFILE=str(service)) + code, elapsed, timed_out = _in_pty([sys.executable, str(bench.copy), "bootstrap", + *BOOTSTRAP_FLAGS], env, bench.wip) + finally: + listener.close() + assert not timed_out and code != 0, "a migration that cannot connect is refused" + assert elapsed < 2 * (N_A * C + 1), f"{elapsed:.2f} s, against its connect, c" + _record(f"migration-{fault}", elapsed, N_A * C + 1, "timing rule 2") + + +def _in_pty(argv: list, env: dict, cwd: Path, *, timeout: float = 120) -> tuple: + """Run `argv` with its stdout on a pty; return (its exit, its elapsed + seconds, whether this helper's own timeout killed it).""" + master, slave = pty.openpty() + start = time.monotonic() + proc = subprocess.Popen(argv, stdin=subprocess.DEVNULL, stdout=slave, stderr=slave, env=env, + cwd=str(cwd)) + os.close(slave) + timed_out = False + while True: + ready, _, _ = select.select([master], [], [], 0.2) + if ready: + try: + os.read(master, 65536) + except OSError: + ready = [] + if proc.poll() is not None and not ready: + break + if time.monotonic() - start > timeout: + proc.kill() + timed_out = True + break + os.close(master) + return proc.wait(), time.monotonic() - start, timed_out + + +def _own_migration(number: int) -> str: + """THE CASE'S OWN MIGRATION `number` (line AF13b; AN13b's cause 4), in + section 1.5's step 3 form (Y:2342), sent by the admin through `psql` as + T221's migration test sends its own (`migration_script` in + `test_sql_register_schema.py`; B15 tasks:2121): one transaction that + sets its own `lock_timeout`, 2000 ms, touches the head row, checks that + `version` is one below its own (else LR003), makes its DDL, raises + `version` and the floors, and records its `migrations` row. Its DDL alters + `register_head`, the table the reader's open transaction read, since an + ACCESS EXCLUSIVE lock on such a table is what a migration waits for + behind a reader; T221's new table waits for no reader. `VERBOSITY + verbose` puts the SQLSTATE in the kept output.""" + return ("\\set VERBOSITY verbose\n" + "BEGIN;\nSET LOCAL ROLE lanes_register_owner;\n" + f"SET LOCAL search_path TO {SCHEMA}, pg_catalog;\n" + "SET LOCAL lock_timeout = '2000ms';\n" + "UPDATE register_head SET seq = seq WHERE id = 1;\n" + f"DO $m$ BEGIN IF (SELECT version FROM schema_version WHERE id = 1) <> {number - 1} " + f"THEN RAISE EXCEPTION 'migration {number} needs schema version {number - 1}, not %', " + "(SELECT version FROM schema_version WHERE id = 1) USING ERRCODE = 'LR003'; " + "END IF; END $m$;\n" + f"ALTER TABLE register_head ADD COLUMN t220_migration_{number} integer;\n" + f"UPDATE schema_version SET version = {number}, writers_from = {number}, " + f"readers_from = {number}, applied_utc = date_trunc('second', clock_timestamp()) " + "WHERE id = 1;\n" + "INSERT INTO migrations (version, script_sha256, by_lane, by_ws) " + f"VALUES ({number}, '{'f' * 64}', 'repoA-2', 't220');\n" + "COMMIT;\n") + + +def test_a_waiting_migration_gives_up_at_its_own_lock_timeout(pg, tmp_path, request): + """A migration waiting behind a reader's open transaction is refused at + its own `lock_timeout`, and a rerun succeeds once the reader's + transaction ends; a new plain read is not held longer than that + `lock_timeout` (AT-D9's migration row). + + The migration is the case's own next one (`_own_migration`), migration 2 + while this build ships migration 1 alone (`REGISTER_SCHEMA_VERSION = 1`, + `lanes-index:6867` at `refs/l1/V-round5`): the case's database is + already at that version, so T109's `bootstrap` has nothing to migrate and + no `lock_timeout` to meet (round 5: "gave up after 0.22 s"). It is sent + once the reader's transaction holds `register_head`, and each + assertion shows the `psql` call's exit and stderr. `[migration-F1]` + still runs `bootstrap`, for the migration's connect.""" + bench = Bench(pg, tmp_path, request) + reader = bench.login("lanes_register_reader") + number = _whole(pg.psql(f"SELECT version FROM {SCHEMA}.schema_version WHERE id = 1;").stdout, + "schema_version's version") + 1 + held = pg.session(user=reader, appname="t220-reader") + held.stdin.write(f"BEGIN;\nSELECT seq FROM {SCHEMA}.register_head;\n") + held.stdin.flush() + try: + deadline = time.monotonic() + 30 + while pg.psql("SELECT count(*) FROM pg_locks l JOIN pg_stat_activity a USING (pid) " + "WHERE a.application_name = 't220-reader' AND l.granted " + f"AND l.relation = '{SCHEMA}.register_head'::regclass " + "AND l.mode = 'AccessShareLock';").stdout.strip() in ("", "0"): + assert time.monotonic() < deadline, "the reader's transaction never read register_head" + time.sleep(0.1) + start = time.monotonic() + proc = pg.psql(_own_migration(number), check=False) + elapsed = time.monotonic() - start + said = f": migration {number} exited {proc.returncode}: {_said_safely(proc.stderr)}" + assert proc.returncode != 0, "the waiting migration is refused" + said + assert "55P03" in proc.stderr, "the migration gave up at its lock_timeout, 55P03" + said + # Y:2342 (design 1.5 step 3): each migration is one transaction that + # begins `SET LOCAL lock_timeout = '2000ms'`: it gives up no sooner + # than that, and well before 10 s. + assert 1.9 <= elapsed < 10, (f"the migration gave up after {elapsed:.2f} s, " + f"against its 2000 ms lock_timeout" + said) + _record("migration-lock", elapsed, 2, "its own lock_timeout, 2000 ms (Y:2342)") + start = time.monotonic() + pg.psql(f"SELECT seq FROM {SCHEMA}.register_head;", user=reader) + assert time.monotonic() - start < 60, "a plain read was held" + finally: + _end(held) + proc = pg.psql(_own_migration(number), check=False) + assert proc.returncode == 0, ("the rerun succeeds once the reader's transaction ends: " + f"migration {number} exited {proc.returncode}: " + f"{_said_safely(proc.stderr.strip())}") + version = pg.psql(f"SELECT version FROM {SCHEMA}.schema_version WHERE id = 1;").stdout + left = _whole(version, "the rerun's schema_version") + assert left == number, f"the rerun left version {left}, not {number}" + + +def test_import_and_reconcile_set_their_bounds_at_connect(tmp_path): + """FP: `import` carries `PGCONNECT_TIMEOUT=2`, `c` here, and sets + `lock_timeout=2000` and `statement_timeout=300s` at connect, under a + 330 s client timer; `reconcile` carries its row's bounds, 1000 ms and + 10 s, at connect (AT-D9's table; T106's `PGOPTIONS`, Y:1573). No engine: + T203's register fake, which answers `psql --version` itself (T203b), + records each call. + + `reconcile`'s row is the register's, on primary (T117: on primary the + register's `reconcile` is the mirror's read-only check against SQL; on + `mode=index` it is #160's, on the local index, and calls no `psql`). So + it runs as `Bench`'s `[reconcile]` rows run it: from T203's flipped copy, + with `lanes-edit.sh` beside it, on a `mode=primary` configuration that + names the same URLs (T220i).""" + from sql_register_helpers import REGISTER_FAKE_PSQL, flipped_copy + bindir = tmp_path / "bin" + bindir.mkdir() + (bindir / "psql").write_text(REGISTER_FAKE_PSQL, encoding="utf-8") + (bindir / "psql").chmod(0o755) + passfile = _private(tmp_path / "conf" / "pgpass") + url = "postgresql://t220_fp@127.0.0.1:55432/register_db" + lines = [f"register_url={url}", f"register_passfile={passfile}", f"reader_url={url}", + f"reader_passfile={passfile}", "register_label=register-test", ""] + config = _private(tmp_path / "conf" / "lanes-index.conf", "\n".join(["mode=index", *lines])) + primary = _private(tmp_path / "conf-primary" / "lanes-index.conf", + "\n".join(["mode=primary", *lines])) + copy = flipped_copy(INDEXER, tmp_path / "tool", True) + for name in ("lanes-edit.sh", "repos.tsv", "lane-start"): + if (REPO / name).exists(): + shutil.copy2(REPO / name, tmp_path / "tool" / name) + origin, wip = tmp_path / "origin.git", tmp_path / "wip" + env = {k: v for k, v in os.environ.items() + if not k.startswith(("LANES_", "CLAUDE_", "TMUX", "PG", "FAKE_PSQL"))} + env.update(HOME=str(tmp_path), XDG_STATE_HOME=str(tmp_path / "state"), + XDG_CONFIG_HOME=str(tmp_path / "config"), LANES_INDEX_CONFIG=str(config), + LANES_LANE="repoA-2", LANES_REPO=str(wip), FAKE_PSQL_LOG=str(tmp_path / "fake.log"), + GIT_AUTHOR_NAME="t", GIT_AUTHOR_EMAIL="t@example.invalid", + GIT_COMMITTER_NAME="t", GIT_COMMITTER_EMAIL="t@example.invalid", + PATH=str(bindir) + os.pathsep + os.environ.get("PATH", os.defpath)) + subprocess.run(["git", "init", "-q", "--bare", "-b", "main", str(origin)], check=True, env=env) + subprocess.run(["git", "clone", "-q", str(origin), str(wip)], check=True, env=env, + capture_output=True) + (wip / "lanes").mkdir() + (wip / "lanes" / "LANES.md").write_text("# LANES.md\n", encoding="utf-8") + for argv in (["add", "-A"], ["commit", "-q", "-m", "C"], ["push", "-q", "origin", "main"]): + subprocess.run(["git", *argv], cwd=str(wip), check=True, env=env, capture_output=True) + c = subprocess.run(["git", "rev-parse", "HEAD"], cwd=str(wip), env=env, capture_output=True, + text=True, check=True).stdout.strip() + # W, A CLONE OF ITS OWN (T220h; lane 1's group 6, #165 6807494089): with + # `LANES_REPO` set, `import` reads W to check that the checkout is not W, + # and refuses where W cannot be read or is the checkout (contract + # 4.18:987), before any `psql` call; `reconcile` reads W's `origin/main`. + # `LANES_WORKSPACE_ROOT` is `lanes-edit.sh`'s test seam. The workstation + # is named too, as `Bench` names it: in a container with none, `import` + # refuses 2 before any call (Amendment 11, R-A11-14). + w = tmp_path / "W" + subprocess.run(["git", "clone", "-q", str(origin), str(w)], check=True, env=env, + capture_output=True) + env.update(LANES_WORKSPACE_ROOT=str(w), LANES_WORKSTATION="Eagle") + log = tmp_path / "fake.log" + for argv, tool, conf, options in ( + (["import", "--at", c], INDEXER, config, + ("-c lock_timeout=2000", "-c statement_timeout=300000")), + (["reconcile"], copy, primary, + ("-c lock_timeout=1000", "-c statement_timeout=10000"))): + if log.exists(): + log.unlink() + proc = subprocess.run([sys.executable, str(tool), *argv], capture_output=True, + text=True, env=dict(env, LANES_INDEX_CONFIG=str(conf)), + cwd=str(wip), timeout=120, stdin=subprocess.DEVNULL) + calls = [json.loads(l) for l in log.read_text().splitlines()] if log.exists() else [] + calls = [c for c in calls if c.get("kind") != "version"] + assert calls, f"{argv[0]} made no psql call: {proc.returncode}: {_said_safely(proc.stderr[-400:])}" + for call in calls: + assert call["connect_timeout"] == str(C), (argv[0], call["connect_timeout"]) + assert all(o in (call["options"] or "") for o in options), (argv[0], call["options"]) + + +# ============================================ AT-D9c and R-PG-1 (T257b), no engine + +#: R-PG-1's three families (lane 3, #165 comment 6747611042, 18:04Z: "one case +#: per family, each set by the caller and each absent at `psql`"). +INHERITED_FAMILIES = { + "pghostaddr-sslmode-disable": {"PGHOSTADDR": "192.0.2.9", "PGSSLMODE": "disable"}, + "pgoptions": {"PGOPTIONS": "-c search_path=inherited"}, + "pgtargetsessionattrs": {"PGTARGETSESSIONATTRS": "read-write"}, +} + + +def _register_fake(tmp_path: Path, monkeypatch, url_tail: str = "", + extra: tuple = ()) -> Path: + """T203's register fake `psql` first on `PATH`, answering `psql --version` + itself (T203b), and a configuration whose two URLs name a loopback host, + each with `url_tail` after the database, and a private password file + each, with the `extra` lines after them (T257c's `register_addresses=`); + every inherited `PG*` and fake variable cleared. Returns the fake's + log.""" + from sql_register_helpers import REGISTER_FAKE_PSQL + bindir = tmp_path / "bin" + bindir.mkdir() + (bindir / "psql").write_text(REGISTER_FAKE_PSQL, encoding="utf-8") + (bindir / "psql").chmod(0o755) + config = _private(tmp_path / "conf" / "lanes-index.conf", "\n".join([ + "mode=index", + f"register_url=postgresql://t257_writer@127.0.0.1:55432/register_db{url_tail}", + f"register_passfile={_private(tmp_path / 'writer.pgpass')}", + f"reader_url=postgresql://t257_reader@127.0.0.1:55432/register_db{url_tail}", + f"reader_passfile={_private(tmp_path / 'reader.pgpass')}", + "register_schema=lanes_register_t257", + *extra, + ""])) + log = tmp_path / "psql.log" + for key in list(os.environ): + if key.startswith("PG") or key.startswith("FAKE_PSQL"): + monkeypatch.delenv(key) + monkeypatch.setenv("LANES_INDEX_CONFIG", str(config)) + monkeypatch.setenv("XDG_STATE_HOME", str(tmp_path / "state")) + monkeypatch.setenv("FAKE_PSQL_LOG", str(log)) + monkeypatch.setenv("PATH", str(bindir) + os.pathsep + os.environ.get("PATH", os.defpath)) + return log + + +@pytest.mark.parametrize("family", list(INHERITED_FAMILIES)) +def test_a_register_path_drops_each_inherited_pg_variable_before_psql(tmp_path, monkeypatch, + family): + """R-PG-1 (lane 3, #165 comment 6747611042): on a register path `psql` + gets only what the configuration gives it, the URL's mapping (SVC-2), + the configured `PGPASSFILE` and `PGCONNECT_TIMEOUT` at `c` (Y:4970); + every inherited variable whose name begins `PG` is dropped first. Each + case sets its family in the caller's environment, sends one register + request, the reader's `read` row through `PostgresStore(cfg, + "register_reader")` in process (lane 1, #165 6752661856: "a phase N case + at T106 can drive only the store, in process"), through T203's register + fake `psql`, whose URL names a loopback host and no query parameter + (lane 2's reading, NOTES question 26), and asserts each variable absent + at every `psql` call, `--version` included. T106 sets `PGOPTIONS` itself, + to D9's bounds, so `[pgoptions]` asserts the inherited value absent. It + fails until lane 1's T106 lands (L1-A5). Its `[J3]` word is + `sql_register_bounds and inherited_pg_variable`, and each case's adds + `and <id>`.""" + log = _register_fake(tmp_path, monkeypatch) + inherited = INHERITED_FAMILIES[family] + for key, value in inherited.items(): + monkeypatch.setenv(key, value) + mod = load_indexer() + error = None + try: + store = mod.PostgresStore(mod.load_config(), "register_reader") + store.request(["SELECT 1"], "read") + except Exception as exc: # the code under test, not this test, failed + error = exc + _raised_nothing(error, "PostgresStore(cfg, 'register_reader').request(...)") + records = [json.loads(line) for line in log.read_text(encoding="utf-8").splitlines()] + requests = [r for r in records if r.get("kind") != "version"] + assert len(requests) == 1, f"one psql call carries the request: {len(requests)}" + assert requests[0]["pg"].get("PGHOST") == "127.0.0.1", \ + f"the URL's mapping reached psql: {requests[0]['pg']}" + for record in records: + pg = record["pg"] + for key, value in inherited.items(): + if key == "PGOPTIONS": + assert pg.get(key) != value, f"the inherited PGOPTIONS reached {record['argv']}" + else: + assert key not in pg, f"the inherited {key} reached {record['argv']}: {pg[key]!r}" + + +#: The under-2 refusal's own words on libpq's reading of each value under 2 +#: (P10's T103 follow-up), the one place a bare 1 or 0 may stand in it (T257zb). +LIBPQ_READING = "libpq reads 1 as 2 and 0 as no limit" + + +def _t257u_refused_with_no_value(said: str, key: str, value: str, its_exit: int | None) -> None: + """An under-2 refusal's text, the case's `tmp_path` blanked out, as T257s's + refused ids read theirs (T257u): it names the URL's key, `connect_timeout=` + and the minimum, and shows no value of the case, neither its + `connect_timeout=` with the value nor the URL's own parts, nor the value + as a token of its own, not part of a word or a dotted number, anywhere + outside the refusal's own words on libpq's reading, `LIBPQ_READING` + (T257zb; Codex's review of P09 at `b8f9e35a`, SHOULD 11: the bare value + was not looked for, so "value 1 is under 2" passed). `its_exit` is the + exit of what refused, or None where it has none, and the helper shows + it (T257zq; lane 2's pre-review RV9-37 of P09 at `d9a1f2bf`, S9; an int + or None since T257zx, lane 2's targeted check RV9-39 of P09 at + `3c5b68bc`, S5: as free text it was a channel no rule watched).""" + case = f"[{key}, connect_timeout={value}]" + assert f"`{key}=`" in said, f"{case} the key is not named: {_said_safely(said, exit=its_exit)}" + assert "`connect_timeout=`" in said and "under 2" in said, ( + f"{case} `connect_timeout=` and its minimum are not named: {_said_safely(said, exit=its_exit)}") + shown = [v for v in (f"connect_timeout={value}", "t257_", "register_db", "127.0.0.1", "55432") + if v in said] + assert not shown, f"{case} the refusal shows {shown}: {_said_safely(said, exit=its_exit)}" + bare = re.findall(rf"(?<![\w.]){re.escape(value)}(?!\w|\.\d)", said.replace(LIBPQ_READING, "")) + assert not bare, (f"{case} the refusal shows the value {value} as a token of its own: " + f"{_said_safely(said, exit=its_exit)}") + + +def test_a_connect_timeout_under_2_is_refused_at_load_config(tmp_path, monkeypatch): + """AT-D9c (b)'s refusal (SVC-2; the phase plan's "`c` and `N_a`, the + connect bound"): `connect_timeout=1` and `connect_timeout=0`, in + `register_url=` or in `reader_url=`, are refused at `load_config`, as + `Refusal` (2), naming the key, `connect_timeout=` and the minimum, 2, + and never the value, before any `psql` call: libpq reads 1 as 2 and 0 as + no limit. `lanes-index mode` then exits 2 with an empty stdout and no + value of the case on either stream. `connect_timeout=2`, `c`'s floor, + loads. No engine. It fails until lane 1's line C (T103's `pg_url_env`, + which `load_config` runs on each URL by T106), and until T103's + follow-up in P10, which names no value (T257u: contracts/config.md:119 + and exit-codes.md:57, as lane 3 rules for P10, #165 6938005990, and for + this case, 6938959205; the form of T257s's refused ids). Its gate row + waits for T103, so it never runs against P09's own refusal text, which + prints the value: an ungated run of it before P10 lands is no reading.""" + log = _register_fake(tmp_path, monkeypatch) + config = Path(os.environ["LANES_INDEX_CONFIG"]) + text = config.read_text(encoding="utf-8") + mod = load_indexer() + for value in ("1", "0"): + for key in ("register_url", "reader_url"): + config.write_text("".join( + line + (f"?connect_timeout={value}" if line.startswith(f"{key}=") else "") + "\n" + for line in text.splitlines()), encoding="utf-8") + error = None + try: + mod.load_config() + except Exception as exc: # the refusal under test, or another failure + error = exc + assert isinstance(error, mod.Refusal), \ + f"{key}=...?connect_timeout={value} loaded: {_error_safely(error)}" + _t257u_refused_with_no_value(str(error).replace(str(tmp_path), "<tmp>"), key, value, + None) # load_config's Refusal, raised in this process + res = _cli(["mode"], tmp_path) + streams = (res.stdout + res.stderr).replace(str(tmp_path), "<tmp>") + assert res.returncode == 2 and res.stdout == "", ( + f"[{key}, connect_timeout={value}] mode exits {res.returncode}, not 2 with an " + f"empty stdout: {_said_safely(streams)}") + _t257u_refused_with_no_value(streams, key, value, res.returncode) + config.write_text("".join( + line + ("?connect_timeout=2" if line.startswith(("register_url=", "reader_url=")) else "") + + "\n" for line in text.splitlines()), encoding="utf-8") + assert mod.load_config()["register_url"].endswith("?connect_timeout=2") + assert not log.exists(), "load_config called psql" + + +# ===================== AT-D9c (a) and (b), no engine, and AT-D9's lookup tries (T257c) + +#: A write's identity, as lane 1's commands take it (contract sections 3.2 to 3.4). +WRITE = {"write_id": "7d3c2b1a-0f9e-4d8c-8b7a-6e5d4c3b2a19", + "generation": "1f2e3d4c-5b6a-4978-8695-a4b3c2d1e0f9", + "lane": "repoA-2", "verb": "set-row-state", "args_sha256": "ab" * 32} +#: `_register_fake`'s `register_schema=`. +T257_SCHEMA = "lanes_register_t257" +#: A FOUND ANSWER AS THE FAKE PRINTS IT for lane 1's T114 follow-up 3 +#: (`refs/l1/T114-fu3`, `fdd5fd04`; lane 1, #165 6775027958): statement 2's seq +#: bare under `-A -t`, then statement 3's ONE escaped text column, one value a +#: line, `workstation=`, `utc=`, then each `journal_files` row, its two tabs +#: printed as COPY's text format escapes them, `\t`. +FOUND_SHA = "c0ffee" + "0" * 58 +FOUND_OUT = ("7\nworkstation=ws-t257\nutc=1762790400\n" + f"lanes/LANES.md\\t1\\t{FOUND_SHA}\nlanes/log/repoA-2.md\\t0\\t-\n") +#: What `journal --write-id` prints for it (contract section 3.4; draft 4.15's +#: E3, F13b-OWED items 11 and 15): `found <seq>`, `workstation=`, `utc=`, then +#: the `file=` rows. +FOUND_PRINTED = ("found 7\nworkstation=ws-t257\nutc=1762790400\n" + f"file=lanes/LANES.md\t1\t{FOUND_SHA}\nfile=lanes/log/repoA-2.md\t0\t-\n") + + +def _one_request(call: dict) -> list: + """One call's stdin read as ONE request (contract section 2.3, "one + request per call"): one line, ending with the request's one `;`, its + statements joined by `psql`'s `\\;`. A statement left to its own `;` fails + the case (AT-D9c (a)). Returns the statements.""" + request = call["stdin"].strip() + assert "\n" not in request and request.endswith(";"), f"not one request: {call['stdin']!r}" + body = request[:-1] + loose = [m.start() for m in re.finditer(r"(?<!\\);", body)] + assert not loose, f"a statement is left to its own semicolon: {request!r}" + return [part.strip() for part in body.split("\\;")] + + +def _cli(argv: list, tmp_path: Path, answers: list | None = None) -> subprocess.CompletedProcess: + """`lanes-index <argv>` in a child, with `_register_fake`'s environment and + configuration and the fake taught `answers`; no lane's, harness's or + tmux's variable.""" + env = {k: v for k, v in os.environ.items() if not k.startswith(("LANES_", "CLAUDE_", "TMUX"))} + env.update(LANES_INDEX_CONFIG=os.environ["LANES_INDEX_CONFIG"], HOME=str(tmp_path)) + if answers is not None: + path = tmp_path / "answers.json" + path.write_text(json.dumps(answers), encoding="utf-8") + env["FAKE_PSQL_ANSWERS"] = str(path) + return subprocess.run([sys.executable, str(INDEXER), *argv], capture_output=True, text=True, + env=env, cwd=str(tmp_path), timeout=120, stdin=subprocess.DEVNULL) + + +def _fake_log(log: Path) -> tuple: + """The fake's log: (the calls that carry a request, the `--version` calls).""" + records = [json.loads(line) for line in log.read_text(encoding="utf-8").splitlines()] \ + if log.exists() else [] + return ([r for r in records if r.get("kind") != "version"], + [r for r in records if r.get("kind") == "version"]) + + +#: `register snapshot`'s form for a new write (contract section 3.2; lane 5's +#: T111 for lane 1, `refs/l5/T111p2`, `6df75975`). +SNAPSHOT_ARGV = ["register", "snapshot", "--write-id", "new", "--lane", WRITE["lane"], + "--verb", WRITE["verb"], "--args-sha256", WRITE["args_sha256"]] + + +@pytest.mark.parametrize("call", ["snapshot", "commit", "lookup", "snapshot-psql-14"]) +def test_each_register_call_is_one_request(tmp_path, monkeypatch, call): + """AT-D9c (a), FP (FR-012; contract section 2.3; the phase plan's "One + request per call"): in T203's register fake's log, each register call is + ONE `psql` call whose stdin is one request, its statements joined by + `\\;`, with section 2.2's argv; a statement left to its own semicolon + fails the case. + + - `[snapshot]`: `register snapshot --write-id new ...` (lane 5's T111 for + lane 1, `refs/l5/T111p2`) sends one call: `SET search_path`, a + `BEGIN ISOLATION LEVEL REPEATABLE READ`, then #160's statements, each + a `COPY (...) TO STDOUT`, the marker among them as `COPY (SELECT + E'\\x1eLANES-INDEX-NEXT') TO STDOUT`, then `COMMIT`. It fails until + T111 lands. + - `[commit]`: `BEGIN ISOLATION LEVEL SERIALIZABLE \\; SELECT + <schema>.commit_write(...) \\; COMMIT;`. `register commit` reads an + attempt directory (contract section 3.3) that only the writer's whole + path makes, so this case drives lane 1's own form in process, + `register_commit_request` through `PostgresStore(cfg, + "register_writer").request(..., "commit")` (lane 2's reading, as + T257b's R-PG-1 cases drive the store). It fails until T112 lands + (`refs/l1/T112-fu2`, in `refs/l1/R-merge6`). + - `[lookup]`: `journal --write-id ...` sends draft 4.16's four statements, + byte for byte (lane 1's T114 follow-up 3, `refs/l1/T114-fu3`; its + `contract-lines-fu3.md`, C1, for `:236`; ERR-50): `BEGIN ISOLATION + LEVEL READ COMMITTED`; `b16f078`'s `SELECT coalesce(<schema>.find_write( + ...)::text, 'absent')`; the one-column `COPY` of `workstation=`, `utc=` + and the `file=` rows; `ROLLBACK`. Taught a found answer in the fakes' + form, the rows as one escaped column, it prints `found <seq>`, + `workstation=`, `utc=`, then the `file=` rows, with 0, after one try + (F13b-OWED items 11 and 15). It fails until T114's follow-up 3 lands. + - `[snapshot-psql-14]` (R-F9b-psql14; lane 1, #165 6752661856 point 1): + the fake's `psql --version` answers 14.11; `register snapshot` exits 69 + naming the version, after one `--version` call and no request + (L1v4.10:152). It fails until T111 lands.""" + log = _register_fake(tmp_path, monkeypatch) + if call == "commit": + answers = tmp_path / "answers.json" + answers.write_text(json.dumps([{"stdout": ""}]), encoding="utf-8") + monkeypatch.setenv("FAKE_PSQL_ANSWERS", str(answers)) + mod = load_indexer() + error = None + try: + store = mod.PostgresStore(mod.load_config(), "register_writer") + store.request(mod.register_commit_request(store.schema, 41, WRITE, {"t257": "commit"}), + "commit") + except Exception as exc: # the code under test, not this test, failed + error = exc + _raised_nothing(error, "sending lane 1's commit request") + calls, _ = _fake_log(log) + assert len(calls) == 1, f"one psql call carries the commit: {len(calls)}" + assert calls[0]["argv"] == REGISTER_ARGV + parts = _one_request(calls[0]) + assert len(parts) == 3, f"the commit is three statements: {parts}" + assert parts[0] == "BEGIN ISOLATION LEVEL SERIALIZABLE", parts[0] + assert parts[1].startswith(f"SELECT {T257_SCHEMA}.commit_write(41, '{WRITE['write_id']}', ") \ + and parts[1].endswith("::jsonb)"), parts[1] + assert parts[2] == "COMMIT", parts[2] + return + if call == "lookup": + not_after = int(time.time()) - 60 + utc = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(not_after)) + proc = _cli(["journal", "--write-id", WRITE["write_id"], "--not-after", str(not_after), + "--generation", WRITE["generation"], "--lane", WRITE["lane"], "--verb", + WRITE["verb"], "--args-sha256", WRITE["args_sha256"]], tmp_path, + [{"match": "find_write", "stdout": FOUND_OUT}]) + calls, _ = _fake_log(log) + assert len(calls) == 1, \ + f"one try, one psql call: {len(calls)}; exit {proc.returncode}: {_said_safely(proc.stderr)}" + assert calls[0]["argv"] == REGISTER_ARGV + write = f"'{WRITE['write_id']}'" + assert _one_request(calls[0]) == [ + "BEGIN ISOLATION LEVEL READ COMMITTED", + f"SELECT coalesce({T257_SCHEMA}.find_write({write}, '{utc}', '{WRITE['generation']}', " + f"'{WRITE['lane']}', '{WRITE['verb']}', '{WRITE['args_sha256']}')::text, 'absent')", + f"COPY (WITH j AS (SELECT seq, workstation, utc FROM {T257_SCHEMA}.journal " + f"WHERE write_id = {write}) SELECT x.line FROM (SELECT 1 AS o, '' AS p, " + "'workstation=' || j.workstation AS line FROM j UNION ALL SELECT 2, '', 'utc=' || " + "extract(epoch FROM j.utc)::bigint::text FROM j UNION ALL SELECT 3, f.path, " + "f.path || chr(9) || CASE WHEN f.present THEN '1' ELSE '0' END || chr(9) || " + f"coalesce(f.sha256, '-') FROM {T257_SCHEMA}.journal_files f JOIN j ON f.seq = j.seq) x " + "ORDER BY x.o, x.p COLLATE \"C\") TO STDOUT", + "ROLLBACK"] + assert (proc.returncode, proc.stdout) == (0, FOUND_PRINTED), \ + f"exit {proc.returncode}: {_said_safely(proc.stdout)!r}: {_said_safely(proc.stderr)}" + return + if call == "snapshot-psql-14": + proc = _cli(SNAPSHOT_ARGV, tmp_path, + [{"kind": "version", "stdout": "psql (PostgreSQL) 14.11\n"}]) + calls, probes = _fake_log(log) + assert proc.returncode == 69, f"exit {proc.returncode}: {_said_safely(proc.stderr)}" + assert "14.11" in proc.stderr, f"the 69 names the version: {_said_safely(proc)}" + assert len(probes) == 1 and calls == [], \ + f"one --version call and no request: {len(probes)}, {len(calls)}" + return + proc = _cli(SNAPSHOT_ARGV, tmp_path) + calls, _ = _fake_log(log) + assert len(calls) == 1, \ + f"one psql call carries the snapshot: {len(calls)}; exit {proc.returncode}: {_said_safely(proc.stderr)}" + assert calls[0]["argv"] == REGISTER_ARGV + parts = _one_request(calls[0]) + assert parts[0].startswith("SET search_path TO ") and T257_SCHEMA in parts[0], parts[0] + assert parts[1].startswith("BEGIN ISOLATION LEVEL REPEATABLE READ"), parts[1] + assert parts[-1] == "COMMIT", parts[-1] + reads = parts[2:-1] + assert reads and all(p.startswith("COPY (") and p.endswith(") TO STDOUT") for p in reads), \ + f"between the BEGIN and the COMMIT, only COPYs: {reads}" + assert r"COPY (SELECT E'\x1eLANES-INDEX-NEXT') TO STDOUT" in reads, \ + f"the marker goes as a COPY: {reads}" + + +#: AT-D9c (b)'s three settings: the URLs' tail, the configuration's other +#: lines, `c`, and each row's client timer in s, `S`, `C` and `T_L`: `N_a`.`c` +#: + 6 s, + 6 s and + 7 s, never below the row's 8, 8 and 9 s. +TIMER_CASES = { + "default": ("", (), 2, {"snapshot": 8, "commit": 8, "lookup": 9}), + "c3": ("?connect_timeout=3", (), 3, {"snapshot": 9, "commit": 9, "lookup": 10}), + "c3-two-addresses": ("?connect_timeout=3", ("register_addresses=2",), 3, + {"snapshot": 12, "commit": 12, "lookup": 13}), +} + + +@pytest.mark.parametrize("case", list(TIMER_CASES)) +def test_connect_timeout_and_register_addresses_set_each_calls_timer(tmp_path, monkeypatch, case): + """AT-D9c (b), FP (D9; SVC-2): `c`, the URLs' `connect_timeout=`, and + `N_a`, `register_addresses=`, set every timer that holds a connect. + `connect_timeout=3` in the URLs gives `PGCONNECT_TIMEOUT=3` in each + call's environment. T203's register fake never answers (it sleeps past + every timer), and each register call ends by its client timer, no + earlier than it (timing rule 3) and under twice it (timing rule 2), its + time recorded against the timer with its margin: the snapshot at `S`, + the commit at `C` and a lookup try at `T_L`, 8, 8 and 9 s with neither + key, 9, 9 and 10 s at `[c3]`, and 12, 12 and 13 s at + `[c3-two-addresses]`. + + Lane 2's reading: the plan's writer, whose snapshot the fake answers and + whose commit and lookup it never does, under `LANES_REGISTER_DEADLINE_S=1`, + is lane 4's L4-B3, so each row's call is made in process, one + `PostgresStore(cfg, "register_writer").request(["SELECT 1"], <row>)` a + row, as T257b's R-PG-1 cases drive the store (lane 1, #165 6752661856). + Each call is cut by its own timer, `PsqlFailed.timer_expired`. It fails + until lane 1's T106 lands (L1-A5: `REGISTER_BOUNDS`' `snapshot`, + `commit` and `lookup` rows). The refusal of a `c` under 2 is + `test_a_connect_timeout_under_2_is_refused_at_load_config`.""" + tail, extra, c, timers = TIMER_CASES[case] + log = _register_fake(tmp_path, monkeypatch, tail, extra) + answers = tmp_path / "answers.json" + answers.write_text(json.dumps([{"sleep": 120}]), encoding="utf-8") + monkeypatch.setenv("FAKE_PSQL_ANSWERS", str(answers)) + mod = load_indexer() + error = None + try: + store = mod.PostgresStore(mod.load_config(), "register_writer") + except Exception as exc: # the code under test, not this test, failed + error = exc + _raised_nothing(error, f"PostgresStore(cfg, 'register_writer') at [{case}]") + for row, timer in timers.items(): + failure = None + start = time.monotonic() + try: + store.request(["SELECT 1"], row) + except Exception as exc: # the timer under test, or another failure + failure = exc + took = time.monotonic() - start + assert failure is not None, f"{row}: a call that never answers was answered" + assert getattr(failure, "timer_expired", False) is True, \ + f"{row}: ended by {_error_safely(failure)}, not by its client timer" + assert timer <= took < 2 * timer, f"{row} at [{case}]: {took:.2f} s against its {timer} s" + _record(f"{row}-{case}", took, timer, "timing rules 2 and 3") + calls, probes = _fake_log(log) + assert len(calls) == len(timers), f"one psql call a row: {len(calls)}" + for record in calls + probes: + assert record["connect_timeout"] == str(c), \ + f"PGCONNECT_TIMEOUT at [{case}]: {record['connect_timeout']!r}, not {c}" + + +#: D9's lookup row (AT-D9's table): the window every try starts inside, from +#: the first try's start, and `T_L`, each try's client timer, at `c` = 2 and +#: `N_a` = 1; the lookup's `statement_timeout`, 6000 ms; and the begin stamp's +#: own allowance, the timing wrapper's start, on each 1 s spacing. +LOOKUP_WINDOW_S, LOOKUP_T_L, LOOKUP_STATEMENT_S, WRAPPER_START_S = 10, 9, 6, 0.1 + + +def _hold_head(pg): + """F3 for a writer's commit and the lookup (AT-D9's F3: "for a writer's + commit, the head row held `FOR UPDATE`"): the head row held by the test's + own session in an open transaction, until the session is closed. Returns + the session once it holds the row.""" + session = pg.session(appname="t257-f3") + session.stdin.write(f"BEGIN;\nSELECT seq FROM {SCHEMA}.register_head FOR UPDATE;\n") + session.stdin.flush() + deadline = time.monotonic() + 30 + while time.monotonic() < deadline: + held = pg.psql("SELECT count(*) FROM pg_stat_activity WHERE application_name = " + "'t257-f3' AND state = 'idle in transaction';").stdout.strip() + if held not in ("", "0"): + return session + time.sleep(0.1) + session.kill() + raise AssertionError("F3's head row was never held") + + +def _slow_lookup(pg, seconds: float) -> None: + """F4 for the lookup (AT-D9's F4: "a policy forced on `journal` for its + owner, since `find_write` runs as the owner"): a sleep the test creates in + its own database, never the template, in a policy for every role, forced + so that it binds the tables' owner: on `journal`, as the plan says, and on + `register_head`, whose one row `find_write` locks first, since a fresh + clone's journal may hold no row for a row policy to run on (lane 2's + reading).""" + pg.psql(f"SET search_path TO {SCHEMA};\n" + f"CREATE FUNCTION t257_slow() RETURNS boolean LANGUAGE sql VOLATILE AS " + f"$$ SELECT pg_sleep({seconds}) IS NOT NULL $$;\n" + f"GRANT EXECUTE ON FUNCTION t257_slow() TO PUBLIC;\n" + + "".join(f"ALTER TABLE {table} ENABLE ROW LEVEL SECURITY;\n" + f"ALTER TABLE {table} FORCE ROW LEVEL SECURITY;\n" + f"CREATE POLICY t257_slow ON {table} FOR ALL TO PUBLIC " + f"USING (t257_slow());\n" for table in ("journal", "register_head"))) + + +@pytest.mark.parametrize("fault", ["F1", "F2", "F3", "F4"]) +def test_the_lookups_tries_start_inside_the_window_and_end_in_3(pg, tmp_path, request, fault): + """AT-D9's lookup row (D9; lane 4's answer 40; lane 1's T114, + `refs/l1/T114-fu3`): `journal --write-id ...` for a write the database + never saw, its `--not-after` a minute past and no `--clock`, so it calls + at once and a healthy try would answer `absent`. Under each fault no try + answers, and it exits 3 naming the id, the pending record kept: F1, a + silent listener, each connect failing at `c`; F2, a relay silent after the + startup, each try cut by `T_L`, 9 s, so a try starts no sooner than the + last one's `T_L` after its start; F3, the head row held `FOR UPDATE`, each + try a 55P03 at its 2000 ms `lock_timeout`; F4, a forced policy that sleeps + (`_slow_lookup`), the first try ending with 57014 no earlier than its + 6000 ms and under twice it (timing rules 3 and 2), whether a further try + follows not asserted. + + From the begin stamps of the command's own `psql` calls (T220f): at least + one try; each try begun at least 1 s after the last began, less the + wrapper's own start (`WRAPPER_START_S`); no try begun after the window, + 10 s from the first try's start, asserted at twice it (timing rule 2); + and from the first try's start to the exit, at most `R` + `T_L` = + 10 + 9 = 19 s, asserted at twice it, its time recorded with its margin. + It fails until lane 1's T114 lands (L1-A3), on T227's template and T228's + logins; until T228 the writer's login is made here.""" + bench = Bench(pg, tmp_path, request) + user = bench.login("lanes_register_writer") + listener, session = None, None + try: + if fault == "F1": + listener = SilentListener() + config = bench.config("127.0.0.1", listener.port, user) + elif fault == "F2": + listener = StartupRelay(f"{pg.host}/.s.PGSQL.{pg.port}") + config = bench.config("127.0.0.1", listener.port, user) + else: + if fault == "F3": + session = _hold_head(pg) + else: + _slow_lookup(pg, 4 * LOOKUP_STATEMENT_S + 5) + config = bench.config(quote(str(pg.host), safe=""), pg.port, user) + proc, _ = bench.run("lookup", config) + finally: + if listener is not None: + listener.close() + if session is not None: + _end(session) + assert proc.returncode == 3, f"lookup-{fault}: {proc.returncode}: {_said_safely(proc.stderr)}" + assert bench.write_id in proc.stderr, f"the 3 names the write's id: {_said_safely(proc)}" + tries = [b["begin"] for b in bench.begins()] + assert tries, "the lookup made no try" + for before, after in zip(tries, tries[1:]): + assert after - before >= 1 - WRAPPER_START_S, \ + f"lookup-{fault}: a try began {after - before:.2f} s after the last" + if fault == "F2": + assert after - before >= LOOKUP_T_L - WRAPPER_START_S, \ + f"lookup-F2: a try began {after - before:.2f} s after the last, inside its T_L" + late = [round(t - tries[0], 2) for t in tries if t - tries[0] >= 2 * LOOKUP_WINDOW_S] + assert not late, f"lookup-{fault}: tries began after the window: {late}" + elapsed = bench.exited - tries[0] + bound = LOOKUP_WINDOW_S + LOOKUP_T_L + assert elapsed < 2 * bound, f"lookup-{fault}: {elapsed:.2f} s against {bound} s" + _record(f"lookup-tries-{fault}", elapsed, bound, f"timing rule 2, {len(tries)} tries") + if fault == "F3": + assert any("55P03" in c["first"] for c in bench.calls()), \ + f"lookup-F3: no try ended with 55P03: {bench.calls()}" + if fault == "F4": + ended = [c for c in bench.calls() if "57014" in c["first"]] + assert ended, f"lookup-F4: no try ended with 57014: {bench.calls()}" + took = ended[0]["end"] - ended[0]["start"] + assert LOOKUP_STATEMENT_S <= took < 2 * LOOKUP_STATEMENT_S, \ + f"lookup-F4: 57014 after {took:.2f} s" + + +# ======== AT-D9's orphaned writer, and AT-D9c's engine half of (a), (c) and (d) (T257d) + +#: `psql`'s statement separator inside one request, `\;`, and #160's marker +#: line as `\echo` prints it (contract section 2.3), built here so that no +#: escape is spelled in this file. +SEP = chr(92) + ";" +ECHO_MARKER = chr(92) + "echo '" + chr(92) + "036LANES-INDEX-NEXT'" + + +def _shim(bench: Bench, arms: list, *, timed: bool = False) -> Path: + """T203's shim (`PSQL_SHIM`, section 3.2) in front of the real `psql`, + armed with `arms`. With `timed`, `TIMING_PSQL` stays first on `PATH` and + hands each call to the shim, so each call's start and end are logged + beside the shim's own log of its script; otherwise the shim is first on + `PATH`. Returns the shim's directory, which holds its logs.""" + from sql_register_helpers import PSQL_SHIM + where = bench.root / "shim" if timed else bench.bin + where.mkdir(exist_ok=True) + (where / "psql").write_text(PSQL_SHIM, encoding="utf-8") + (where / "psql").chmod(0o755) + _arm(where, bench, arms) + if timed: + bench.env["T220_REAL_PSQL"] = str(where / "psql") + return where + + +def _arm(where: Path, bench: Bench, arms: list) -> None: + from sql_register_helpers import PSQL_SHIM_CONTROL + (where / PSQL_SHIM_CONTROL).write_text(json.dumps({"psql": bench.pg.psql_bin, "arms": arms}), + encoding="utf-8") + + +def _shim_calls(where: Path) -> list: + """The shim's log: each call that carries a request, in call order.""" + from sql_register_helpers import PSQL_SHIM_LOG + log = where / PSQL_SHIM_LOG + if not log.exists(): + return [] + entries = [json.loads(line) for line in log.read_text(encoding="utf-8").splitlines() if line] + return [entry for entry in entries if entry.get("kind") != "version"] + + +def _writer(bench: Bench, config: Path, state: str, *, + deadline: str | None = None) -> subprocess.Popen: + """A writer's whole path, started: `lanes-edit.sh set-row-state` on the + bench's lane, T257a's rows' path, which on primary is lane 4's L4-B3 + (T413 to T415). `deadline` is `LANES_REGISTER_DEADLINE_S`; unset, the + deadline is D7's 30 s, as in AT-4 (c). The lane's own checkout is made + first, where the bench has none yet (`Bench.lane_checkout`, T257l). The + writer leads a session, and so a process group, of its own, so its end, + `_end_writers`, reaches the `python3`, `psql` and `git` it starts + (T257t).""" + bench.lane_checkout() + env = dict(bench.env, LANES_INDEX_CONFIG=str(config), LANES_LANE="repoA-2") + env.pop("LANES_REGISTER_DEADLINE_S", None) + if deadline is not None: + env["LANES_REGISTER_DEADLINE_S"] = deadline + return subprocess.Popen(["bash", str(bench.copy.parent / "lanes-edit.sh"), "set-row-state", + "repoA-2", state], stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, env=env, + cwd=str(bench.wip), start_new_session=True) + + +#: How long `_end_writers` reads a writer's pipes after its end, before it +#: closes them (T257w). +WRITER_DRAIN_S = 5.0 + + +def _drained_and_closed(proc: subprocess.Popen) -> None: + """`proc`'s stdout and stderr, each still open, as a `communicate()` that + timed out or never ran leaves them, read together to their ends for up to + `WRITER_DRAIN_S`, what they hold dropped, then closed whatever the read + did (T257w). Pipes a `communicate()` read to their ends are closed + already. A pipe that did not reach its end in that time is raised, after + the closes: a process outside the writer's group holds it.""" + pipes = [pipe for pipe in (proc.stdout, proc.stderr) if pipe is not None and not pipe.closed] + live: list = [] + try: + live = [pipe.fileno() for pipe in pipes] + end = time.monotonic() + WRITER_DRAIN_S + while live and time.monotonic() < end: + ready, _, _ = select.select(live, [], [], max(0.0, end - time.monotonic())) + live = [fd for fd in live if fd not in ready or os.read(fd, 65536)] + finally: + for pipe in pipes: + pipe.close() + if live: + raise RuntimeError(f"writer {proc.pid}'s pipes did not reach their ends {WRITER_DRAIN_S} s " + f"after its end: a process outside its group holds them") + + +def _end_writers(procs: list) -> None: + """Each writer `_writer` started ended with its process group and + reaped, by `_end_process(proc, group=True)` (T257t; Codex's review of P09 + at `21dd3642`, SHOULD 4), which signals no writer whose `returncode` is + set, as `communicate()` leaves one it saw end; then, whatever that end + raised, its pipes drained for up to `WRITER_DRAIN_S` and closed + (`_drained_and_closed`; T257w, Codex's review of P09 at `d3a2fd5c`, + SHOULD 4). Every writer is tried, and the first failure, of an end or of + a drain, is raised after the last.""" + failed = [] + for proc in procs: + try: + _end_process(proc, group=True) + except (subprocess.TimeoutExpired, OSError) as exc: + failed.append(exc) + try: + _drained_and_closed(proc) + except (OSError, RuntimeError) as exc: + failed.append(exc) + if failed: + raise failed[0] + + +def _communicated(writer: subprocess.Popen, timeout: float = 300) -> tuple: + """`writer.communicate(timeout=timeout)`'s (stdout, stderr), with + `_end_writers([writer])` in a `finally`, so its group and its pipes are + ended on a timeout too (T257w). The lookup-wait and delayed-link cases + both call it, and T257w's regression calls it, so a lost `finally` fails + that regression (T257za; Codex's review of P09 at `b8f9e35a`, SHOULD + 10: the regression had its own copy of the two callers' `finally`).""" + try: + return writer.communicate(timeout=timeout) + finally: + _end_writers([writer]) + + +def test_each_writer_leads_a_session_of_its_own_and_its_end_reaches_its_descendants( + tmp_path, monkeypatch): + """`_writer` and `_end_writers` (T257t; Codex's review of P09 at + `21dd3642`, SHOULD 4), with no engine: `_writer` runs a stand-in + `lanes-edit.sh` of the case's own, which starts a descendant, as the real + one starts `python3`, `psql` and `git`, says so on stdout and waits for + it; or, with the state `quick`, exits 0 at once. Each running writer must + lead a session of its own; `_end_writers` must end its descendant with + it, so its stdout reaches its end, as `_end_writers` checks while it + drains and closes both pipes (T257w); and a writer `communicate()` reaped + gets no signal (`_signals_kept_to_unreaped`). Before T257t a writer was + in the case's own session and the burst's end signalled its `bash` + alone, so the descendant outlived the case, holding the pipes.""" + late = _signals_kept_to_unreaped(monkeypatch) + (tmp_path / "lanes-edit.sh").write_text( + '[ "$3" = quick ] && exit 0\nsleep 30 &\necho started\nwait\n', encoding="utf-8") + + class Bare: + """What `_writer` reads of a `Bench`.""" + def __init__(self, root: Path): + self.copy, self.wip, self.env = root / "lanes-index", root, dict(os.environ) + + def lane_checkout(self) -> Path: + return self.wip + + bench = Bare(tmp_path) + quick = _writer(bench, tmp_path / "lanes-index.conf", "quick") + quick.communicate(timeout=60) + slow = [] + try: + for i in range(2): + slow.append(_writer(bench, tmp_path / "lanes-index.conf", f"slow {i}")) + assert slow[-1].stdout.readline() == "started\n", "the stand-in started no descendant" + assert all(os.getsid(proc.pid) == proc.pid for proc in slow), \ + "a writer runs in the case's own session, not one of its own" + finally: + _end_writers([quick, *slow]) + assert late == [], f"a writer was signalled once it was reaped: {late}" + assert [proc.returncode for proc in slow] == [-signal.SIGTERM] * 2, \ + f"the writers' exits: {[proc.returncode for proc in slow]}" + closed = [pipe.closed for proc in slow for pipe in (proc.stdout, proc.stderr)] + assert closed == [True] * 4, f"_end_writers left a writer's pipe open: {closed}" + + +@pytest.mark.skipif(not sys.platform.startswith("linux"), + reason="the stand-in names its descendant by /proc/<pid>/stat field 22, " + "and the case finds it gone through /proc: Linux only (T257z)") +def test_a_writer_whose_communicate_times_out_is_ended_with_its_group_and_its_pipes_closed( + tmp_path, monkeypatch): + """T257w (Codex's review of P09 at `d3a2fd5c`, SHOULD 4: the lookup-wait + and delayed-link cases' `communicate(timeout=300)` had no `finally`, and + `_end_writers` closed no pipe), with no engine, on a stand-in + `lanes-edit.sh` of the case's own that starts a descendant, writes its pid + and start time (`/proc` stat field 22) to a mark, and waits. One writer's + `communicate()` times out in `_communicated`, which the two cases now + call, and its `finally`, `_end_writers([writer])`, must end it with its + group, the descendant + included, reap it and close both its pipes, signalling nothing once it is + reaped. Then two writers, the first one's end made to raise: `_end_writers` + must still end the second, close all four pipes within its drain bound, + and raise the first one's error. Before T257w both pipes of each writer + were left open. The wait for the two marks has a monotonic deadline, and + a stand-in that exits before its mark ends it at once, each one's exit + named; one `finally` passes every writer started to `_end_writers` + (T257y; Codex's review of P09 at `b8f9e35a`, BLOCKING 2: the wait had no + deadline, and its failures ended `first` alone). It runs on Linux alone: + the stand-in names its descendant by `/proc/<pid>/stat`, which the oracle + reads too (T257z; Codex's review of P09 at `b8f9e35a`, SHOULD 9, as + T224q).""" + late = _signals_kept_to_unreaped(monkeypatch) + monkeypatch.setitem(globals(), "WRITER_DRAIN_S", 1.0) + mark = tmp_path / "descendant" + (tmp_path / "lanes-edit.sh").write_text( + f'sleep 30 &\necho "$! $(cut -d" " -f22 /proc/$!/stat)" > "{mark}.$3"\n' + f'echo started\nwait\n', encoding="utf-8") + + class Stand: + """What `_writer` reads of a `Bench`, on the case's own folder.""" + copy, wip, env = tmp_path / "lanes-index", tmp_path, dict(os.environ) + + @staticmethod + def lane_checkout() -> Path: + return tmp_path + + def gone(state: str) -> bool: + pid, started = Path(f"{mark}.{state}").read_text().split() + try: + fields = Path(f"/proc/{pid}/stat").read_text().rsplit(")", 1)[1].split() + except OSError: + return True + return fields[19] != started or fields[0] in ("Z", "X") + conf, real, started = tmp_path / "lanes-index.conf", _end_process, [] + + def first_fails(proc, *, group, wait=10.0): + if proc is first: + raise ChildProcessError("T257w's stand-in: the first writer was reaped elsewhere") + real(proc, group=group, wait=wait) + try: + writer = _writer(Stand, conf, "one") + started.append(writer) + with pytest.raises(subprocess.TimeoutExpired): + _communicated(writer, timeout=1.0) + end = time.monotonic() + 5 + while not gone("one") and time.monotonic() < end: + time.sleep(0.05) + said = (writer.returncode, writer.stdout.closed, writer.stderr.closed, gone("one")) + assert said == (-signal.SIGTERM, True, True, True), ( + f"after a timeout the writer's exit, stdout closed, stderr closed and descendant gone " + f"are {said}, not ({-signal.SIGTERM}, True, True, True)") + for state in ("two-a", "two-b"): + started.append(_writer(Stand, conf, state)) + first, second = started[1:] + end = time.monotonic() + 10 + while True: + exits = [proc.poll() for proc in (first, second)] + marked = [Path(f"{mark}.{state}").exists() for state in ("two-a", "two-b")] + if all(marked): + break + assert exits == [None, None] and time.monotonic() < end, ( + f"the stand-ins two-a and two-b have marked {marked}, their exits {exits}: each " + f"must mark within 10 s and keep running") + time.sleep(0.05) + monkeypatch.setitem(globals(), "_end_process", first_fails) + start = time.monotonic() + with pytest.raises(ChildProcessError, match="the first writer"): + _end_writers([first, second]) + took = time.monotonic() - start + pipes = [pipe.closed for proc in (first, second) for pipe in (proc.stdout, proc.stderr)] + assert second.returncode == -signal.SIGTERM and pipes == [True] * 4 and took < 1.0 + 5, ( + f"with the first writer's end raising, the second's exit is {second.returncode}, " + f"the pipes closed are {pipes}, after {took:.1f} s") + finally: + monkeypatch.setitem(globals(), "_end_process", real) + _end_writers(started) + assert late == [], f"a writer was signalled once it was reaped: {late}" + + +def _activity(pg, appname: str) -> tuple: + """(the session's state, the seconds since that state began), or ('', 0) + where no session of `appname` is connected.""" + said = pg.psql("SELECT state, extract(epoch FROM clock_timestamp() - state_change) " + f"FROM pg_stat_activity WHERE application_name = '{appname}';").stdout.strip() + if not said: + return "", 0.0 + state, _, age = said.splitlines()[0].partition("|") + return state, _whole(age or 0, "pg_stat_activity's state age", float) + + +#: The idle bound on a writer's open transaction, the group's +#: `idle_in_transaction_session_timeout` (AT-D9, "Beside the table"). +IDLE_BOUND_S = 5 + + +def test_an_orphaned_writer_transaction_is_ended_by_the_idle_bound(pg, tmp_path, request): + """AT-D9, beside the table: a session as `lanes_register_writer` that + replays a commit call's script without its `COMMIT` (test 12's held + session) holds the head row and idles. `idle_in_transaction_session_ + timeout` ends it no earlier than 5 s after it idles (timing rule 3) and + under twice that (timing rule 2), from `pg_stat_activity.state_change`, + after which a waiting write commits, 0. + + The script is a real one: a first writer, `lanes-edit.sh set-row-state` + through T203's shim, whose `fail-match` on `commit_write` fails its + commit calls unsent; the shim's log holds the commit call's script, which + the held session replays as the writer's login with its last statement, + `COMMIT`, left off, and its entry's `not_after` moved 30 s past the + replay's start (T257m). The login has the writer's floors, the idle + bound among them, as `login add` sets them (`Bench.login`'s `floors`, + T257m). The waiting write is a second writer under D7's 30 s, + started once the session idles. It fails until lane 4's L4-B3 (T414's + seam and T415's attempt loop; only T413 is in lane 4's share) and lane + 1's T112 land, on T227's template and T228's logins. The bench's + database is at `primary` first (`Bench.to_primary`, T257m).""" + bench = Bench(pg, tmp_path, request) + bench.to_primary() + user = bench.login("lanes_register_writer", floors=True) + config = bench.config(quote(str(pg.host), safe=""), pg.port, user) + where = _shim(bench, [{"mode": "fail-match", "match": "commit_write"}]) + first = _writer(bench, config, f"PAUSED {DOT} T257's orphan, unsent", deadline="3") + out, err = first.communicate(timeout=300) + scripts = [e["stdin"] for e in _shim_calls(where) if "commit_write" in e.get("stdin", "")] + assert scripts, f"the first writer sent no commit call: {first.returncode}: {_said_safely(err)}" + parts = [part.strip() for part in scripts[0].strip().rstrip(";").split(SEP)] + assert parts[-1] == "COMMIT", f"the commit call's script ends with COMMIT: {parts}" + # ITS `not_after` MOVES WITH THE REPLAY (T257m; line BD-18): the entry's + # `not_after` (F3) is the snapshot's clock plus `C` and 2 s, about 10 s on, + # and the replay starts once the first writer has exited, past it, where + # `commit_write` refuses the entry and the session ends before it idles. The + # held session stands for a commit sent in time whose client went away, so it + # carries a `not_after` 30 s past the replay's start; nothing else changes. + fresh = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(time.time() + 30)) + parts = [re.sub(r'"not_after":"[^"]*"', f'"not_after":"{fresh}"', part) for part in parts] + assert sum(part.count('"not_after"') for part in parts) == 1, \ + f"the commit call's entry carries one not_after: {parts}" + _arm(where, bench, []) + orphan = pg.session(user=user, appname="t257-orphan") + waiting = None + try: + orphan.stdin.write((" " + SEP + " ").join(parts[:-1]) + ";\n") + orphan.stdin.flush() + deadline = time.monotonic() + 30 + state, age = _activity(pg, "t257-orphan") + while state != "idle in transaction" and time.monotonic() < deadline: + time.sleep(0.05) + state, age = _activity(pg, "t257-orphan") + assert state == "idle in transaction", f"the replayed commit never idled: {state!r}" + idled = time.monotonic() - age + waiting = _writer(bench, config, f"PAUSED {DOT} T257's waiting write") + while _activity(pg, "t257-orphan")[0] and time.monotonic() - idled < 4 * IDLE_BOUND_S: + time.sleep(0.05) + ended = time.monotonic() - idled + assert not _activity(pg, "t257-orphan")[0], \ + f"the orphan still holds the head row {ended:.2f} s after it idled" + assert IDLE_BOUND_S <= ended < 2 * IDLE_BOUND_S, \ + f"the idle bound ended the orphan {ended:.2f} s after it idled" + _record("orphaned-writer", ended, IDLE_BOUND_S, "timing rules 2 and 3") + out, err = waiting.communicate(timeout=300) + assert waiting.returncode == 0, f"the waiting write did not commit: {waiting.returncode}: {_said_safely(err)}" + finally: + try: + if waiting is not None: + _end_writers([waiting]) # its process group, reaped (T257t) + finally: + _end(orphan) + + +#: AT-D9c (a)'s engine half: #160's reads that need no clock, so that two +#: sends of them answer the same bytes. +SNAPSHOT_READS = ["SELECT version, writers_from, readers_from FROM schema_version WHERE id = 1", + "SELECT mode, marker_state, generation FROM register_switch WHERE id = 1", + "SELECT seq FROM register_head WHERE id = 1"] + + +def test_the_joined_snapshot_logs_one_statement_and_reads_byte_identical_to_the_one_by_one_form( + counting_cluster, tmp_path, monkeypatch): + """AT-D9c (a), the engine half, on section 5.6's counting cluster + (`log_statement=all`: one `statement:` line per Query message): each of + the three register calls, the snapshot, the commit and the lookup, logs + ONE `statement:` line; and the joined snapshot's stdout equals, byte for + byte, the same statements sent one by one, the marker as `\\echo` prints + it, so #160's parse is unchanged. + + The calls are made in process as the fixture's writer login, through + `PostgresStore(cfg, "register_writer")` (lane 2's reading, as T257c's + `[commit]`): the snapshot by `_query_many(SNAPSHOT_READS, snapshot=True, + row="snapshot")`, whose `psql` stdout is kept; the commit by lane 1's + `register_commit_request`, which `commit_write` may refuse, a refusal + being one statement too; the lookup by `register_lookup_request`. The + one-by-one form is the real `psql`, with section 2.2's argv, fed the same + statements each with its own `;`. It fails until lane 1's T106, T112 and + T114 land, on T229's counting cluster.""" + from pgcluster import FX_WRITER, Database + db = Database(counting_cluster, counting_cluster.new_database()) + config = _private(tmp_path / "conf" / "lanes-index.conf", "\n".join([ + "mode=index", f"register_url={db.url(FX_WRITER)}", + f"register_passfile={counting_cluster.passfile(FX_WRITER)}", + f"reader_url={db.url(FX_WRITER)}", + f"reader_passfile={counting_cluster.passfile(FX_WRITER)}", + "register_schema=lanes_register", ""])) + for key in list(os.environ): + if key.startswith("PG"): + monkeypatch.delenv(key) + monkeypatch.setenv("LANES_INDEX_CONFIG", str(config)) + monkeypatch.setenv("XDG_STATE_HOME", str(tmp_path / "state")) + mod = load_indexer() + store = mod.PostgresStore(mod.load_config(), "register_writer") + outs, run = [], store._run + + def kept(*args, **kwargs): + out = run(*args, **kwargs) + if args and "REPEATABLE READ" in str(args[0]): # the snapshot's request alone + outs.append(out) + return out + store._run = kept + log = counting_cluster.log() + + def statements(send) -> int: + offset = log.stat().st_size + try: + send() + except Exception: # a refusal is still one statement: counted below + pass + time.sleep(0.3) # the logger's last line + text = log.read_bytes()[offset:].decode("utf-8", "replace") + return len(re.findall(r"statement: ", text)) + + not_after = int(time.time()) - 60 + counts = { + "snapshot": statements(lambda: store._query_many(list(SNAPSHOT_READS), snapshot=True, + row="snapshot")), + "commit": statements(lambda: store.request( + mod.register_commit_request(store.schema, 0, WRITE, {"t257": "commit"}), "commit")), + "lookup": statements(lambda: store.request( + mod.register_lookup_request(store.schema, WRITE, not_after), "lookup")), + } + assert counts == {"snapshot": 1, "commit": 1, "lookup": 1}, \ + f"each call is one statement line: {counts}" + assert outs, "the snapshot's psql answered nothing to keep" + lines = [f'SET search_path TO "{store.schema}";', + "BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY;"] + for query in SNAPSHOT_READS: + lines += [f"COPY ({query}) TO STDOUT;", ECHO_MARKER] + lines.append("COMMIT;") + one_by_one = subprocess.run([db.psql_bin, *REGISTER_ARGV], input="\n".join(lines) + "\n", + capture_output=True, text=True, env=db.env(FX_WRITER), timeout=60) + assert one_by_one.returncode == 0, _said_safely(one_by_one) + assert outs[0] == one_by_one.stdout, \ + f"the joined snapshot read {outs[0]!r}, one by one {_said_safely(one_by_one)!r}" + + +#: `C`, the commit's client timer, at `c` = 2 and `N_a` = 1 (D9). +COMMIT_C_S = 8 + + +def test_the_lookups_wait_counts_from_the_snapshot_calls_end_and_gets_no_lr011( + pg, tmp_path, request): + """AT-D9c (c): T203's shim holds the snapshot call 2.5 s before it hands + it on (`window`), so the database reads its clock 2.5 s after the call + started, and the first commit call is lost as `before` loses it, under + `LANES_REGISTER_DEADLINE_S=1`. The lookup's first try gets no LR011, and + it starts no earlier than the snapshot call's end plus `C` less 1 s + (timing rule 3) and under twice `C` plus 1 s, 18 s, after that end + (timing rule 2), `C` being 8 s here (lane 4's section, "The in-doubt rule + (F3, D8)"). A client that counted from the call's start would call 2.5 s + early and meet LR011. + + `TIMING_PSQL` hands each call to the shim, so each call's start and end + are logged beside the shim's log of its script, in the same order; no + call may be cut by its timer, or the two logs would not pair. It fails + until lane 4's L4-B3 (T414, T415) and lane 1's T111, T112 and T114 land, + on T227's template and T228's logins. The bench's database is at + `primary` first (`Bench.to_primary`, T257m).""" + bench = Bench(pg, tmp_path, request) + bench.to_primary() + user = bench.login("lanes_register_writer") + config = bench.config(quote(str(pg.host), safe=""), pg.port, user) + where = _shim(bench, [{"mode": "window", "ms": 2500, "call": 1}, + {"mode": "before", "match": "commit_write", "call": 1}], timed=True) + writer = _writer(bench, config, f"PAUSED {DOT} T257's lookup wait", deadline="1") + out, err = _communicated(writer) # its group, its pipes, on a timeout too (T257w) + scripts, times = _shim_calls(where), bench.calls() + assert len(times) == len(scripts), \ + (f"a call was cut by its timer: {len(scripts)} sent, {len(times)} ended: " + f"{_said_safely(subprocess.CompletedProcess(writer.args, writer.returncode, out, err))}") + snapshot = next((i for i, e in enumerate(scripts) if "commit_write" not in e["stdin"] + and "find_write" not in e["stdin"]), None) + lookup = next((i for i, e in enumerate(scripts) if "find_write" in e["stdin"]), None) + assert snapshot is not None and lookup is not None, \ + f"the writer made no snapshot and lookup: {writer.returncode}: {_said_safely(err)}" + assert "LR011" not in times[lookup]["first"], f"the first try met LR011: {times[lookup]}" + gap = times[lookup]["start"] - times[snapshot]["end"] + assert COMMIT_C_S - 1 <= gap < 2 * COMMIT_C_S + 1, \ + f"the lookup's first try started {gap:.2f} s after the snapshot call's end" + _record("lookup-wait", gap, COMMIT_C_S, "timing rules 2 and 3, from the snapshot call's end") + + +#: AT-D9c (d)'s link: 75 ms each way, TLS on (T229's relay, R-P23), `c` = 3 +#: and one address, so `S` = `C` = 9 s, `T_L` = 10 s and a reader's 7 s. +DELAY_S = 0.075 +LINK_TIMERS = {"snapshot": 9, "commit": 9, "lookup": 10, "read": 7} + + +def _link_config(path: Path, cluster, port: int, writer: str) -> Path: + """A configuration for the TLS cluster through the relay at `port`: + lane 1's URL form (`TLSCluster.url`, `verify-full`, the root alone) with + the relay's port and `connect_timeout=3`, as a workstation at that round + trip sets `c`, and one address; `writer` and the fixture's reader, each + with its password file.""" + from pgcluster import FX_READER + + def url(user: str) -> str: + return cluster.url(user).replace(f"@127.0.0.1:{cluster.port}/", + f"@127.0.0.1:{port}/") + "&connect_timeout=3" + return _private(path, "\n".join([ + "mode=primary", f"register_url={url(writer)}", + f"register_passfile={cluster.passfile(writer)}", f"reader_url={url(FX_READER)}", + f"reader_passfile={cluster.passfile(FX_READER)}", + f"register_label={cluster.label_of()}", "register_schema=lanes_register", ""])) + + +def test_over_a_delayed_tls_link_no_healthy_call_meets_its_timer(tls_cluster, tmp_path, + request): + """AT-D9c (d), test 9's per-call runs over the delayed loopback, TLS on: + a writer's whole write (its snapshot and its commit), a lookup of a write + the database never saw, and a reader's read. No healthy call meets its + timer: every call that began has ended with `psql`'s own exit, in the + timing log, none cut by its client timer, and each call's time is + recorded against its timer, `S` = `C` = 9 s, `T_L` = 10 s and a reader's + 7 s, with its margin. The TLS cluster's database is at `primary` first + (`Bench.to_primary`, T257m). It fails until lane 4's L4-B3 (T414, T415) + and lane 1's T111 to T114 land, on T229's TLS cluster and relay.""" + from pgcluster import FX_WRITER, Database, delayed_loopback + bench = Bench(Database(tls_cluster, tls_cluster.database_name), tmp_path, request) + bench.to_primary() + where = _shim(bench, [], timed=True) + with delayed_loopback(tls_cluster.port, DELAY_S) as relay: + config = _link_config(tmp_path / "conf" / "lanes-index.conf", tls_cluster, relay.port, + FX_WRITER) + writer = _writer(bench, config, f"PAUSED {DOT} T257's delayed link") + _, err = _communicated(writer) # its group, its pipes, on a timeout too (T257w) + assert writer.returncode == 0, f"the healthy write: {writer.returncode}: {_said_safely(err)}" + kinds = ["commit" if "commit_write" in e["stdin"] else "snapshot" + for e in _shim_calls(where)] + proc, _ = bench.run("lookup", config) + kinds += ["lookup"] * (len(_shim_calls(where)) - len(kinds)) + proc, _ = bench.run("reader", config) + kinds += ["read"] * (len(_shim_calls(where)) - len(kinds)) + times = bench.calls() + assert len(times) == len(kinds), \ + f"a healthy call was cut by its timer: {len(kinds)} began, {len(times)} ended" + assert {"snapshot", "commit", "lookup", "read"} <= set(kinds), f"the calls made: {kinds}" + for kind, call in zip(kinds, times): + took = call["end"] - call["start"] + assert took < LINK_TIMERS[kind], f"{kind}: {took:.2f} s, at its {LINK_TIMERS[kind]} s timer" + _record(f"link-{kind}", took, LINK_TIMERS[kind], "AT-D9c (d), recorded") + + +#: THE LINES OF A WRITER'S STDERR A FAILURE MESSAGE SHOWS, AND HOW (T257zc; +#: Codex's review of P09 at `fb359e64`, lane 3's post 6945142764, BLOCKING 1; +#: Brett's 6931509747: "sanitize failure diagnostics and avoid publishing +#: credential-bearing stdout/stderr or password-file lines"). T257x showed each +#: line that held `WARNING: ` whole, so a WARNING that carried a `PGPASSWORD=` +#: value, a password-file line, a SCRAM verifier or a server's text that psql +#: passed on was shown with it. Now a line is shown only where it matches, in +#: full, one of these templates: the fixed texts of `lanes-edit.sh`'s WARNING +#: sites, the twelve at `fb359e64` (eight `note` lines to stderr, "CROSS-REPO", +#: "explicitly allowed", "names disagree", "an uncommitted edit to its +#: register", "a per-profile clone", "uncommitted LANES.md changes", "the +#: rename comment" and "the GitHub comment", and four `printf` lines to +#: stdout, "could not be read", two "superseded transcript" and "this window +#: is lane"), and the eleven more of line R's `lanes-edit.sh` at `548b8f2e`, +#: against which the burst case's writers run (hosted run 44016287671): the +#: three files-mode questions, with each `<why>` their callers pass, the stale +#: pending record, a write already in the register, and the six rename moves. +#: A variable part is shown only in a form that cannot hold a secret: `{n}`, a +#: number of at most ten digits; `{id}`, a write id, a UUID; `{cmd}`, one of +#: the product's own verbs. Every other variable part, `{…}`, may be any text, +#: and is never shown: the report prints the template's text, with +#: `[withheld]` in that part's place, and never the line. A line that holds +#: `WARNING` and matches no template is not shown at all, only counted. +_WARNING_VERBS = ("replace-in-row", "append-session-id", "append-line", "add-row", + "start-record", "set-row-state", "migrate-state-cells", "retire-rows", + "archive-rows", "commit", "log", "claim", "release", "request-handoff", + "rename-lane", "register-text", "register-grep") +_WARNING_PARTS = {"{n}": "[0-9]{1,10}", + "{id}": "[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}", + "{cmd}": "(?:" + "|".join(re.escape(verb) for verb in _WARNING_VERBS) + ")", + "{…}": ".*?"} +_WARNING_PART = re.compile("|".join(re.escape(part) for part in _WARNING_PARTS)) +_FILES_MODE = (" so {cmd} runs in files mode", " so {cmd} reads in files mode", + " so the guard reads in files mode") +_FILES_WHY = ("could not be run: there is no lanes-index beside {…}/lanes-edit.sh or on PATH", + "could not be asked: no temporary directory could be made under {…} to hold " + "its answer", + "could not be asked: no cache file could be made under {…} to hold its answer", + "exited 0 without answering one line, index or primary", + "exited 0 without answering one line, mode index or mode primary", + "did not answer within 2 s, and was stopped (exit 124)", + "was killed (exit 137): by its 2 s timer after it ignored the stop, or by a signal", + "was killed by a signal (exit 137)", + "exited {n}", "exited {n} ({…})") +_RENAME_OWED = " The move is owed: {…}." +_WARNING_TEMPLATES = tuple( + ["lanes-edit: WARNING: " + text for text in ( + "CROSS-REPO — {…} is not lane {…}'s home ({…}). Proceeding: Amendment 7 warns here, it " + "never refuses.", + "this lane/session name mismatch was explicitly allowed for this transcript. It will " + "remain allowed only while the lane and session names stay unchanged.", + "the lane and Claude session names disagree. This prompt is paused until you choose how " + "to repair or explicitly allow this lane.", + "W ({…}) holds an uncommitted edit to its register ({…}), and under LANES_ROUTE_WRITES=1 " + "nothing commits in W: this write goes through {…}/ and carries its own edit only, so " + "that one stays in W, unpublished and untouched (Amendment 23 S5). {…}.", + "LANES_REPO names {…}, a per-profile clone of the register beside W. It is honoured, and " + "nothing new should write through it (Amendment 23 S6.2): this lane's own checkout is " + "{…}/. Unset LANES_REPO, LANES_DIR and LANES_FILE in this window, or relaunch it.", + "uncommitted LANES.md changes touch row(s) other than this lane ({…}): {…}", + "the rename comment could not be posted on:{…}. The commit IS the rename and it has " + "landed; post them by hand so that a reader outside this estate can see it.", + "the GitHub comment could not be posted. The log line IS the claim and it has landed; " + "post the comment by hand so that a reader outside this estate can see it.", + "the pending record of this command, write {id} made at {…} against register generation " + "{id}, was last updated at {…}, more than {n} s ago, so this run does not reuse its id: " + "it writes anew, as write {id}, and replaces that record. {…}", + "register write {id} is in the register at seq {n}; {…}.", + "register write {id} is in the register at seq {n}, {…}.", + "the rename is in the register at seq {n}, and its handoff's move could not be handed " + "to the parent that makes it ({…}/rl-move could not be written), so it is NOT made: the " + "row's handoff column names {…}, which is not there yet." + _RENAME_OWED, + "lane {…} is lane {…} in the register already (seq {n}), so this run wrote no register " + "line; its handoff's move could not be handed to the parent that makes it ({…}/rl-move " + "could not be written), so it is NOT made: the row's handoff column names {…}." + + _RENAME_OWED, + "{…}; its handoff's move was named for the checkout {…}, not lane {…}'s {…}, so it is " + "NOT made: the row's handoff column names {…}, which is not there yet." + _RENAME_OWED, + "{…}; the push of its handoff's move and RENAMED stamp in {…} was not confirmed (exit " + "{n}, above). A re-run of these steps confirms the move on origin or makes it: {…}.", + "{…}; its handoff's move and RENAMED stamp in {…} did not complete (exit {n}, above), " + "and the row's handoff column names {…}, which is there: the refusal above says why the " + "act stopped. Once a person has settled what it names, what this rename still owes is " + "made by hand: {…}.", + "{…}; its handoff's move and RENAMED stamp in {…} did not complete (exit {n}, above), so " + "the row's handoff column names {…}, which is not there yet." + _RENAME_OWED)] + + ["WARNING: {…} could not be read, so a window named for a lane RENAMED since could not be " + "resolved to it (Amendment 16(e)) — this block may be about to say no lane binds a window " + "that one does", + "WARNING: this is a superseded transcript of lane {…}; the live one is {…}, which the row " + "records as `unknown` — a relaunch would record nothing either, so run: lane-start " + "--no-launch {…}", + "WARNING: this is a superseded transcript of lane {…}; the live one is {…}; you resumed " + "{…} — exit this session and run: lane-start {…}", + "WARNING: this window is lane {…} whose current session is {…}; this session {…} is in " + "no row — the harness minted a new transcript — run: lane-start --no-launch {…}"] + + ["lanes-edit: WARNING: `lanes-index " + asked + "` " + why + "," + mode.replace( + "{cmd}", "`{cmd}`") + ", as on a workstation with no lanes-index configuration (feature " + "007, D3)." for asked, mode in (("mode", _FILES_MODE[0]), + ("register read --prefetch", _FILES_MODE[1]), + ("register read --for guard --prefetch", _FILES_MODE[2])) + for why in _FILES_WHY]) + + +def _template_pattern(template: str): + """`template` as a pattern its line must match in full: its fixed text + as it stands, each variable part in its form, the i-th as group `p<i>` + (T257zc). Each `{…}` but a template's last part ends where the fixed + text after it first occurs, and is never tried at a later place: the + lookahead `(?=(?P<p<i>>.*?)<text>)` finds that place, and the + backreference `(?P=p<i>)` takes what lies before it (T257zd). So no `{…}` + is tried again, and a line costs time in proportion to its length, not + to a power of it. A line whose `{…}` holds the fixed text that follows + it may therefore match no template; it is then counted, never shown.""" + parts = list(_WARNING_PART.finditer(template)) + at, pattern = 0, [] + for i, part in enumerate(parts): + pattern.append(re.escape(template[at:part.start()])) + form = _WARNING_PARTS[part.group()] + if part.group() == "{…}" and i + 1 < len(parts): + after = template[part.end():parts[i + 1].start()] + assert after, f"a `{{…}}` with no fixed text after it: {template}" + pattern.append(f"(?=(?P<p{i}>{form}){re.escape(after)})(?P=p{i})") + else: + pattern.append(f"(?P<p{i}>{form})") + at = part.end() + return re.compile("".join(pattern) + re.escape(template[at:]), re.S) + + +_WARNING_PATTERNS = tuple((template, _template_pattern(template)) + for template in _WARNING_TEMPLATES) +#: The longest line `_shown_warning` matches against the templates (T257zd); +#: a longer one is counted, never shown. +_WARNING_MAX = 4096 + + +def _shown_warning(line: str): + """`line` as a failure message may show it, or None where it matches no + WARNING template in full (T257zc): the template's fixed text, each `{n}`, + `{id}` and `{cmd}` as the line has it, and `[withheld]` for each `{…}`. + Nothing of the line but those bounded parts is copied. A line longer than + `_WARNING_MAX` is matched against no template (T257zd).""" + if len(line) > _WARNING_MAX: + return None + for template, pattern in _WARNING_PATTERNS: + matched = pattern.fullmatch(line) + if not matched: + continue + shown, at = [], 0 + for i, part in enumerate(_WARNING_PART.finditer(template)): + shown += [template[at:part.start()], + "[withheld]" if part.group() == "{…}" else matched.group(f"p{i}")] + at = part.end() + return "".join(shown) + template[at:] + return None + + +def _warnings_of(err: str) -> tuple: + """Of a writer's stderr `err`: its lines that match a WARNING template in + full, in order, each as `_shown_warning` shows it; and the count of its + other lines that hold `WARNING`, which are not shown (T257zc). No other + line of it is read (T257x).""" + shown, withheld = [], 0 + for line in (err or "").splitlines(): + if "WARNING" not in line: + continue + told = _shown_warning(line) + if told is None: + withheld += 1 + else: + shown.append(told) + return shown, withheld + + +def _whole(text, what: str, kind=int): + """`kind(text)`, an int by default, or an AssertionError that names + `what` and quotes none of `text` (T257zl; lane 2's pre-review RV9-37 of + P09 at `d9a1f2bf`, S5): int()'s and float()'s own ValueError quotes up + to 200 characters of its input, which is a tool's or a writer's output + here. The AssertionError is raised after the `except`, not in it, so + its `__cause__` is None and its `__context__` is not that ValueError + (None, unless `_whole` is itself called inside an `except`): nothing of + `text` is kept on it (T257zr; lane 2's pre-review RV9-38 of P09 at + `3f9fcac4`, N3: before T257zr, `from None` only hid the ValueError from + display, and `__context__` still held it). `text` is still this frame's + argument, which a long traceback prints and a short one does not + (T205e).""" + try: + return kind(text) + except (TypeError, ValueError): + pass + raise AssertionError(f"{what} is not a number; its text is not shown") + + +def _short_only(request) -> None: + """Under an explicit `--tb=long`, `--fulltrace` (which forces long) or + `--showlocals`, which print frames' arguments or locals, fail at once, + naming the run's style: an explicit override is not secret-safe, and the + suite's protection of a failure's report holds only under its default + (T257zzi; lane 2's pre-review RV9-40 of P09 at `161c3087`, N3). Every + report regression calls it before it renders a report: `_reported`, + `_t257zza_seen` and `_t257zzb_seen` (T257zzzh; lane 2's pre-review + RV9-42 of P09 at `857a41d2`, N4). It never skips.""" + style = request.config.getoption("tbstyle", "auto") + shown = request.config.getoption("showlocals", False) + full = request.config.getoption("fulltrace", False) + assert style != "long" and not shown and not full, ( + f"this run's --tb={style}, showlocals={shown}, fulltrace={full} prints frames' arguments or " + f"locals: an explicit override is not secret-safe, and this suite's protection of a failure's " + f"report holds only under its default, --tb=short (T205e), so this case cannot pass here") + + +def _reported(request, failed) -> str: + """pytest's own report of the failure `failed`, a `pytest.raises` + ExceptionInfo, as the running test's item renders a failed test under + the suite's own settings (T257zr; lane 3's ruling 6949488277 on lane 2's + pre-review RV9-38 of P09 at `3f9fcac4`, B1): the terminal's text, which + is also --junitxml's failure body, then --junitxml's failure message. + Under an explicit `--tb=long`, `--fulltrace` or `--showlocals` it fails + at once (`_short_only`; T257zzi). It never skips.""" + _short_only(request) + longrepr = request.node.repr_failure(failed) + return f"{longrepr}\n{longrepr.reprcrash.message}" + + +def test_the_suites_tracebacks_are_short_unless_a_person_asks_for_another_style(request): + """T257zv (lane 3's ruling 6949488277 on lane 2's pre-review RV9-38 of + P09 at `3f9fcac4`, B1; T205e), with no engine and no process: conftest's + `pytest_configure` turns pytest's default `--tb=auto` into `short`, the + style that prints no frame's arguments, and leaves each style a person + gives (`long`, `short`, `no`, `line`, `native`) as given. It is run on a + stand-in config for each, its root refusal and its engine plugin's + registration as in this session. And this session's own style is no + longer `auto`: the hook ran before this case. Every report regression + here (`_reported`) renders under that style.""" + import types + import conftest + + def configured(given: str) -> str: + option = types.SimpleNamespace(tbstyle=given) + config = types.SimpleNamespace( + option=option, getoption=lambda name, default=None: getattr(option, name, default), + pluginmanager=types.SimpleNamespace(has_plugin=lambda name: True)) + conftest.pytest_configure(config) + return option.tbstyle + + styles = {given: configured(given) for given in ("auto", "long", "short", "no", "line", "native")} + assert styles == {"auto": "short", "long": "long", "short": "short", "no": "no", "line": "line", + "native": "native"}, f"--tb given, and the style after the hook: {styles}" + assert request.config.getoption("tbstyle") != "auto", "this session's style is still pytest's auto" + + +def test_whole_keeps_no_text_it_could_not_parse_on_its_error_or_in_the_report(request): + """T257zr (lane 2's pre-review RV9-38 of P09 at `3f9fcac4`, N3; lane 3's + ruling 6949488277, B1), with no engine and no process: `_whole` is given + a planted value it cannot parse, as an int and as a float. Its + AssertionError has no `__cause__` and no `__context__`, and the planted + value is in none of its `str`, `repr`, `args`, formatted traceback or + pytest's own report of the failure (`_reported`). Before T257zr its + `__context__` was int()'s ValueError, which quotes the value. The + planted value is no credential of any login.""" + import traceback + planted = f"fake-{uuid.uuid4().hex}" + for kind in (int, float): + with pytest.raises(AssertionError) as failed: + _whole(f"x {planted} y", "a planted value", kind) + error = failed.value + assert error.__cause__ is None, f"{kind.__name__}: a cause is kept" + assert error.__context__ is None, \ + f"{kind.__name__}: a {type(error.__context__).__name__} is kept as its context" + shown = "".join(traceback.format_exception(type(error), error, error.__traceback__)) + for where, said in (("str", str(error)), ("repr", repr(error)), ("args", repr(error.args)), + ("formatted traceback", shown), ("pytest's report", _reported(request, failed))): + assert planted not in said, f"{kind.__name__}: the planted value is in the error's {where}" + + +class _NotGiven: + """`_said_safely`'s `exit` where no caller gave one (T257zx).""" + + +_NOT_GIVEN = _NotGiven() + + +def _said_safely(said, stream: str = "output", exit: int | None | _NotGiven = _NOT_GIVEN) -> str: + """What a failure message may show of a process's output (T257zh; lane + 3's ruling 6946445277 on lane 2's pre-review RV9-36 of P09 at + `2407ea06`, S2: every failure message that showed a writer's or a + tool's raw stdout or stderr shows this instead). `said` is a captured + stream, text or bytes, or something that ran, with an exit and its two + streams: a `CompletedProcess`, or a writer with `code`, `out` and + `err`. Shown are its exit, where it has one, and for each stream its + count of lines and of WARNING lines, and the WARNING lines that match a + template of the product's WARNING sites in full, as `_shown_warning` + shows them. No other text of it is shown: no line that no template + matches, whole or in part. Text built from a stream, a slice or a + `strip()` of it, is a stream here too. A bare stream's counts are + labelled `stream`, "stderr" or "stdout" where the caller knows which, + else "output" (T257zm; lane 2's pre-review RV9-37 of P09 at `d9a1f2bf`, + N4). An exit is shown only where it is an int, else as `[withheld]` + (T257zm; RV9-37, N3). A bare stream's `exit` may be given: an int is + shown as `exit N`, None as `no exit` (T257zx; lane 2's targeted check + RV9-39 of P09 at `3c5b68bc`, S5).""" + if said is None or isinstance(said, (str, bytes, bytearray)): + code, streams = None, [(stream, said)] + if exit is None: + code = "no exit" + elif not isinstance(exit, _NotGiven): + code = exit + else: + code = getattr(said, "returncode", getattr(said, "code", None)) + streams = [("stdout", getattr(said, "stdout", getattr(said, "out", None))), + ("stderr", getattr(said, "stderr", getattr(said, "err", None)))] + if code is None: + parts = [] + elif code == "no exit": + parts = ["no exit"] + elif isinstance(code, int) and not isinstance(code, bool): + parts = [f"exit {int(code)}"] + else: + parts = ["exit [withheld]"] + for name, text in streams: + if isinstance(text, (bytes, bytearray)): + text = bytes(text).decode("utf-8", "replace") + if text is not None and not isinstance(text, str): + parts.append(f"{name}: not captured as text") + continue + shown, withheld = _warnings_of(text or "") + parts.append(f"{name}: {len((text or '').splitlines())} line(s), " + f"{len(shown) + withheld} of them WARNING lines, {withheld} of no known " + f"template withheld; no other line is shown") + parts.extend(f" {name}'s WARNING line: {line}" for line in shown) + return "\n".join(parts) + + +def _burst_report(logins: str, writers: list, ends: list, rows: list, calls: list) -> str: + """What the burst test's assertions print when one fails (T257o; lane 4's + 6899167909): each writer's index, login, exit and time, from `ends`, with + its stderr's WARNING lines; the journal's new rows, `seq|write_id`, in + `rows`; and each `commit_write` call in the shim's log, `calls`, in the + log's order, with its write id, whether and where the journal has it, its + `PGUSER`, and the `burst N` its state text names (`?` where the log holds + none). It reads nothing and decides nothing. + + Each writer's WARNING lines are printed wherever they fall (T257v), each + that matches a template of the product's WARNING sites in full as + `_shown_warning` shows it, the others only counted, and no other line of + its stderr (T257x, T257zc, `_warnings_of`): a writer whose `lanes-index + mode` question failed says why in a WARNING (`reg_mode_files`, line R's + `lanes-edit.sh`:6415), of which a 300-character tail kept only the last + 18 characters (run 44016287671, writer 3). A writer's time is when the + collection, which reads the writers in order, reached its end, so a writer + that ended early shows a later writer's time.""" + seq_of = {write_id: seq for seq, _, write_id in (row.partition("|") for row in rows)} + lines = [f"burst [{logins}]: {len(ends)} writers' ends, {len(rows)} new journal rows, " + f"and the shim's commit_write calls:"] + for i, (code, took, err) in enumerate(ends): + lines.append(f" writer {i} ({writers[i]}): exit {code} after {took:.2f} s") + shown, withheld = _warnings_of(err) + lines.extend(f" its WARNING line: {line}" for line in shown) + if withheld: + lines.append(f" and {withheld} WARNING line(s) of no known template, withheld") + for row in rows: + seq, _, write_id = row.partition("|") + lines.append(f" journal seq {seq}: write id {write_id}") + for call in calls: + script = call.get("stdin", "") + if "commit_write" not in script: + continue + sent = re.search(r"commit_write\([0-9-]+, '([0-9a-f-]{36})'", script) + write_id = sent.group(1) if sent else "?" + burst = re.findall(r"burst ([0-9]+)", script) + lines.append(f" shim call {call.get('call', '?')}: commit_write of {write_id}, in the " + f"journal as seq {seq_of.get(write_id, 'NONE')}, login " + f"{(call.get('pg') or {}).get('PGUSER', '?')}, state text names burst " + f"{' '.join(burst) or '?'}") + return "\n".join(lines) + + +@pytest.mark.parametrize("logins", ["one-login", "two-logins"]) +def test_a_burst_of_ten_over_a_delayed_tls_link_commits_each_once_or_exits_75_with_nothing_written( + tls_cluster, tmp_path, request, logins): + """AT-D9c (d), test 4's burst of ten over the delayed loopback, TLS on, + one request per call, under D7's 30 s, `LANES_REGISTER_DEADLINE_S` + unset as in AT-4 (c): every writer commits once, or exits 75 with nothing + written, its write id absent from the journal, and no writer ends any + other way; the new seqs have no gap and no repeat. Each writer's time + from the release to its exit, and the burst's snapshot calls in the + shim's log, are recorded, never asserted: act 3's test 4 decides D7. + `[two-logins]` splits the ten across two engineers' writer logins, five + each, the second's made by `lanes-index login add` through the admin + service, as the fixture's are (X, logins), since the head row serialises + every login's commits. + + Lane 2's reading: the ten writers share the bench's one checkout, as + `set-row-state` on one lane, each its own state. The TLS cluster's + database is at `primary` first (`Bench.to_primary`, T257m). It fails + until lane 4's L4-B3 (T414, T415) and lane 1's T111 to T114 land, on + T229's TLS cluster and relay.""" + from pgcluster import FX_WRITER, PASSWORD_LINE, Database, delayed_loopback + db = Database(tls_cluster, tls_cluster.database_name) + bench = Bench(db, tmp_path, request) + bench.to_primary() + where = _shim(bench, [], timed=True) + writers = [FX_WRITER] * 10 + if logins == "two-logins": + service = tls_cluster.admin_service(tls_cluster.database_name) + code, out, _ = tls_cluster.lanes_index_tty(["login", "add", "fx2", + "--admin-service", service]) + assert code == 0, f"login add fx2 exited {code}" + tls_cluster.passwords.update(PASSWORD_LINE.findall(out)) + writers = [FX_WRITER] * 5 + ["lanes_w_fx2"] * 5 + head = _whole(db.psql(f"SELECT seq FROM {SCHEMA}.register_head;").stdout.strip() or 0, + "register_head's seq") + with delayed_loopback(tls_cluster.port, DELAY_S) as relay: + configs = {login: _link_config(tmp_path / "conf" / login / "lanes-index.conf", tls_cluster, + relay.port, login) for login in set(writers)} + bench.lane_checkout() + release = time.monotonic() + procs, ends = [], [] + try: + for i, login in enumerate(writers): + procs.append(_writer(bench, configs[login], f"PAUSED {DOT} T257's burst {i}")) + for proc in procs: + _, err = proc.communicate(timeout=300) + ends.append((proc.returncode, time.monotonic() - release, err)) + finally: + # Whatever ended the collection, no writer it started outlives it, nor + # anything a writer started (T257q; T257t). + _end_writers(procs) + codes = [code for code, _, _ in ends] + rows = db.psql(f"SELECT seq, write_id FROM {SCHEMA}.journal WHERE seq > {head} " + f"ORDER BY seq;").stdout.split() + + def told() -> str: + return _burst_report(logins, writers, ends, rows, _shim_calls(where)) + + assert set(codes) <= {0, 75}, f"a writer ended another way:\n{told()}" + # A writer whose `lanes-index mode` question fails warns on stderr, writes to git in files + # mode and ends 0 with no journal row (lane 4's 6899400726; `reg_mode_files`' own words). + files_mode = [f" writer {i} ({writers[i]}), whose WARNING lines follow" + for i, (_, _, err) in enumerate(ends) if "runs in files mode" in (err or "")] + assert not files_mode, ("a writer says it ran in files mode, so its write is in git and not " + "the journal:\n" + "\n".join(files_mode) + f"\n{told()}") + seqs = [_whole(row.split("|")[0], "a new journal row's seq") for row in rows] + assert seqs == list(range(head + 1, head + 1 + codes.count(0))), \ + f"one entry for each writer that committed, no gap, no repeat: {seqs}, {codes}\n{told()}" + sent = set(re.findall(r"commit_write\([0-9-]+, '([0-9a-f-]{36})'", + "".join(e["stdin"] for e in _shim_calls(where)))) + written = [row.split("|")[1] for row in rows] + assert len(set(written)) == len(written) and set(written) <= sent, \ + (f"each write id committed once, and only the burst's: {len(written)} new journal rows, " + f"{len(set(written))} write ids, {len(set(written) - sent)} not the burst's\n{told()}") + # Each writer by its write id (T257r): a commit call names its writer's `burst <i>` in the + # new row text its entry carries, and only a sha256 of the row it replaces. + named: dict = {} + for script in (e.get("stdin", "") for e in _shim_calls(where)): + call = re.search(r"commit_write\([0-9-]+, '([0-9a-f-]{36})'", script) + if call: + named.setdefault(call.group(1), set()).update(re.findall(r"burst ([0-9]+)", script)) + assert all(len(burst) == 1 for burst in named.values()), \ + f"a write id's commit calls name no writer, or more than one: {named}\n{told()}" + owners = sorted(_whole(min(named[write_id]), "a commit call's burst number") for write_id in written) + assert owners == [i for i, code in enumerate(codes) if code == 0], \ + (f"the journal's rows are by writers {owners}, not one by each writer that exited 0 " + f"and none by one that exited 75: {codes}\n{told()}") + snapshots = sum(1 for e in _shim_calls(where) if "commit_write" not in e["stdin"]) + for i, (code, took, _) in enumerate(ends): + print(f"D9c burst [{logins}] writer {i} ({writers[i]}): exit {code} after {took:.2f} s") + print(f"D9c burst [{logins}]: {codes.count(0)} committed, {codes.count(75)} out with 75, " + f"{snapshots} snapshot calls") + + +def test_the_burst_report_prints_each_warning_whole_and_no_credential(): + """`_burst_report` (T257v, T257x), with no engine, on run 44016287671's + writer 3: `lanes-edit.sh` warned that its `lanes-index mode` question + failed (`reg_mode_files`, :6415), ran in files mode, met the marker and + exited 69 (`cs_marker_refuse`, :3971-3972); its 300-character tail kept + only the warning's last 18 characters, `feature 007, D3).`, so why the + question failed was lost. The report must carry each writer's exit and its + WARNING line as the line's template shows it, and no other line of any + writer's stderr (T257x; Codex's review of P09 at `b8f9e35a`, BLOCKING 1; + T257zc): not the refusal's lines, and none of the credential forms + planted here, a password-file line bare and prefixed, `password=` and + `PGPASSWORD=` values, a URL's secret, a dict's repr, a value on the line + after its key, and a SCRAM verifier. This warning's template has no part + that is withheld, so here the shown line equals the line. The name still + says "whole", from T257v, since a new name would be a new node id; a + WARNING line is shown only through its template (`_shown_warning`, + T257zc), and never whole (T257zg; lane 2's pre-review RV9-36 of P09 at + `2407ea06`, N4). The planted value is no credential of any login.""" + planted = "planted-not-a-password" + warning = ("lanes-edit: WARNING: `lanes-index mode` did not answer within 2 s, and was " + "stopped (exit 124), so `set-row-state` runs in files mode, as on a " + "workstation with no lanes-index configuration (feature 007, D3).") + refusal = ("lanes-edit: lanes/STORE is on origin/main at 17ceb1c26f81, the tip this " + "write's own fetch returned. This workstation writes in files mode, so " + "`set-row-state` refuses, and nothing was written (feature 007, FR-004).\n" + "lanes-edit: this estate's register is SQL; configure `mode=primary`\n") + leaked = (f"*:*:*:lanes_w_fx:{planted}\n" + f"lanes-edit: 127.0.0.1:5432:register:lanes_w_fx:{planted} with a blank\n" + f"lanes-edit: a libpq text with password={planted} and PGPASSWORD = '{planted}'\n" + f"lanes-edit: postgresql://lanes_w_fx:{planted}/x@127.0.0.1:5432/register\n" + f"lanes-edit: its environment {{'PGPASSWORD': '{planted}'}}\n" + f"lanes-edit: PGPASSWORD=\n{planted}\n" + f"lanes-edit: SCRAM-SHA-256$4096:{planted}${planted}:{planted}\n") + committed = "lanes-edit: state cell REPLACED: 46 chars → 46 chars\n" + ends = [(0, 23.5, committed), (69, 23.5, leaked + warning + "\n" + refusal), + (75, 32.85, "lanes-edit: register busy; nothing was written\n" + leaked)] + told = _burst_report("two-logins", ["lanes_w_fx", "lanes_w_fx", "lanes_w_fx2"], ends, + [], []) + assert (warning + "\n" + refusal)[-300:].startswith("feature 007, D3).\n"), \ + "the case's tail is not run 44016287671's" + assert f" its WARNING line: {warning}\n" in told, f"the warning, whole:\n{told}" + assert told.count("its WARNING line:") == 1, f"one WARNING line, writer 1's:\n{told}" + exits = [f" writer {i} ({login}): exit {code} after " + for i, (login, code) in enumerate([("lanes_w_fx", 0), ("lanes_w_fx", 69), + ("lanes_w_fx2", 75)])] + assert all(said in told for said in exits), f"each writer's exit:\n{told}" + others = [line for _, _, err in ends for line in err.splitlines() + if line.strip() and line != warning] + shown = [line for line in others if line in told] + assert not shown and planted not in told, \ + f"{len(shown)} line(s) of stderr other than a WARNING are printed:\n{told}" + + +@pytest.mark.parametrize("form", ["pgpassword", "password-file", "scram-verifier", + "server-warning"]) +def test_the_burst_report_shows_no_credential_a_warning_line_holds(capsys, form): + """`_burst_report` (T257zc; Codex's review of P09 at `fb359e64`, lane 3's + post 6945142764, BLOCKING 1), with no engine: a credential inside a + WARNING line is in no failure message and on no printed stream. `form` is + `PGPASSWORD=` and a generated value, a password-file line after + `lanes-edit: `'s prefix, a SCRAM verifier, or a server's WARNING that psql + passes on. Each is planted twice in one writer's stderr: as a WARNING line + of its own, which matches no template and is counted, never shown; and as + the text a failed `lanes-index mode` printed, inside `reg_mode_files`' + WARNING (`exited 2 (...)`), which matches that template and is shown with + `[withheld]` in that text's place. The planted value is no credential of + any login. + + `_burst_report` returns its text and prints nothing, at `fb359e64` as + here, so the `capsys` half cannot fail today: it guards only against a + print added to `_burst_report` later. The failure-message half is the + one that fails at `fb359e64` (T257zg; lane 2's pre-review RV9-36 of P09 + at `2407ea06`, N1).""" + planted = f"fake-{uuid.uuid4().hex}" + held = {"pgpassword": f"PGPASSWORD={planted}", + "password-file": f"lanes-edit: 127.0.0.1:5432:register:lanes_w_fx:{planted}", + "scram-verifier": f"SCRAM-SHA-256$4096:{planted}=${planted}=:{planted}=", + "server-warning": f'psql:<stdin>:3: WARNING: role "lanes_w_fx" password "{planted}"'} + line = held[form] if form == "server-warning" else f"lanes-edit: WARNING: {held[form]}" + mode = ("lanes-edit: WARNING: `lanes-index mode` exited 2 ({}), so `set-row-state` runs in " + "files mode, as on a workstation with no lanes-index configuration (feature 007, D3).") + ends = [(0, 23.5, f"{line}\n{mode.format(held[form])}\n")] + told = _burst_report("one-login", ["lanes_w_fx"], ends, [], []) + printed = capsys.readouterr() + assert planted not in told, f"the planted {form} is in the failure message:\n{told}" + assert planted not in printed.out + printed.err, f"the planted {form} was printed" + assert f" its WARNING line: {mode.format('[withheld]')}\n" in told, \ + f"the files-mode warning, its why withheld:\n{told}" + assert told.count("its WARNING line:") == 1, f"one WARNING line shown:\n{told}" + assert " and 1 WARNING line(s) of no known template, withheld" in told, \ + f"the unknown WARNING line, counted:\n{told}" + + +def test_a_shown_part_of_a_warning_template_is_never_the_head_of_other_text(): + """`_WARNING_TEMPLATES`' shape (T257ze; lane 2's pre-review RV9-36 of P09 + at `2407ea06`, B1), with no engine: in each template, each part shown as + the line has it, `{n}`, `{id}` or `{cmd}`, is followed by fixed text that + does not begin with a letter, a digit, `_` or `-`, or ends the template. + A shown part followed straight by another part, as `seq {n}{…}.` was, + showed the head of the text after it: up to ten digits of whatever came + after `at seq `. Each template that breaks this is named.""" + broken = [] + for template in _WARNING_TEMPLATES: + parts = list(_WARNING_PART.finditer(template)) + for i, part in enumerate(parts): + if part.group() == "{…}": + continue + end = parts[i + 1].start() if i + 1 < len(parts) else len(template) + after = template[part.end():end] + if (i + 1 < len(parts) and not after) or re.match(r"[\w-]", after): + broken.append(f"{part.group()}, then {after[:12]!r}, in {template!r}") + assert not broken, ("a shown part with no fixed text after it, or with text it can run " + "into:\n" + "\n".join(broken)) + + +def test_the_burst_report_shows_no_digit_of_a_value_after_at_seq(): + """`_burst_report` (T257ze; lane 2's pre-review RV9-36 of P09 at + `2407ea06`, B1), with no engine: a WARNING line in the shape of + `lanes-edit.sh`'s `pw_tail_said` (line R's :10604), `register write <id> + is in the register at seq <s><joiner><what>.`, whose `<s>` is a value in + `token_urlsafe`'s alphabet that starts with ten digits, shows none of it. + The template `... at seq {n}{…}.` showed `{n}`, the value's first ten + digits, with the rest `[withheld]`. Now `{n}` must end at one of the + product's two joiners, `; ` (its default) or `, ` (:10657, :10659), so + that line matches no template and is counted; the product's own lines, + a seq and then a joiner, are still shown. The planted value is no + credential of any login.""" + planted = f"9081726354{uuid.uuid4().hex}-fake_value" + lead = ("lanes-edit: WARNING: register write 0f1e2d3c-4b5a-4968-8776-655443322110 is in the " + "register at seq ") + told = _burst_report("one-login", ["lanes_w_fx"], [(0, 1.0, f"{lead}{planted}.\n")], [], []) + assert "9081726354" not in told and planted not in told, \ + f"the value's leading digits are in the failure message:\n{told}" + assert not re.search(r"at seq [0-9]", told), f"a seq is shown:\n{told}" + assert " and 1 WARNING line(s) of no known template, withheld" in told, \ + f"the line, counted:\n{told}" + for joiner in ("; ", ", "): + line = f"{lead}42{joiner}its after-COMMIT steps ran at 2026-11-17T10:00:00Z in pid 4242." + assert _shown_warning(line) == f"{lead}42{joiner}[withheld].", \ + f"the product's line, joined by {joiner!r}, is not shown: {_shown_warning(line)!r}" + + +def test_the_pending_record_warning_is_shown_with_its_generation_id(): + """`_shown_warning` (T257zf; lane 2's pre-review RV9-36 of P09 at + `2407ea06`, S1), with no engine: the WARNING `lanes-edit.sh` prints where + a pending record is too old to reuse (line R's :8650) names the + record's register generation, `$WR_REC_GENERATION`, a lower-case UUID + (`generation=`, :9145-9146), not a number. Its template took `{n}` + there, so the real line matched none and was only counted; with `{id}` + it is shown, the write ids, the generation and the age as the line has + them, and the times and the lookup text `[withheld]`.""" + ids = ("0f1e2d3c-4b5a-4968-8776-655443322110", "5e6f7a8b-9c0d-4e1f-a2b3-c4d5e6f7a8b9", + "11112222-3333-4444-8555-666677778888") + said = ("lanes-edit: WARNING: the pending record of this command, write {0} made at {3} against " + "register generation {1}, was last updated at {4}, more than 900 s ago, so this run does " + "not reuse its id: it writes anew, as write {2}, and replaces that record. {5}") + line = said.format(*ids, "2026-11-17T09:00:00Z", "2026-11-17T09:05:00Z", + "Its lookup's last call may still run until 2026-11-17T09:06:00Z.") + want = said.format(*ids, "[withheld]", "[withheld]", "[withheld]") + assert _shown_warning(line) == want, f"the pending record's line is not shown: {line}" + assert _warnings_of(line + "\n") == ([want], 0), _warnings_of(line + "\n") + + +def test_a_failure_message_shows_no_line_of_a_writers_output_that_no_template_matches(): + """`_said_safely` (T257zh; lane 3's ruling 6946445277 on lane 2's + pre-review RV9-36 of P09 at `2407ea06`, S2), with no engine and no + process: a writer that ended 75 with a password-file line, a + `PGPASSWORD=` value and a SCRAM verifier on lines of its stderr that no + template matches, and the same value on its stdout, fails a + representative assert, `_sent_a_snapshot`'s, as a writer that sent no + snapshot request does. Its message shows the exit, stderr's counts and + the one WARNING line that matches a template, and not the planted + value. Before T257zh the message held the writer's whole stderr. The + planted value is no credential of any login.""" + planted = f"fake-{uuid.uuid4().hex}" + warning = ("lanes-edit: WARNING: `lanes-index mode` did not answer within 2 s, and was stopped " + "(exit 124), so `set-row-state` runs in files mode, as on a workstation with no " + "lanes-index configuration (feature 007, D3).") + proc = subprocess.CompletedProcess( + ["lanes-edit.sh"], 75, f"lanes-edit: {planted}\n", + f"127.0.0.1:5432:register:lanes_w_fx:{planted}\nlanes-edit: PGPASSWORD={planted}\n" + f"lanes-edit: SCRAM-SHA-256$4096:{planted}=${planted}=:{planted}=\n{warning}\n" + "lanes-edit: register busy; nothing was written\n") + + class _SentNothing: + def sent(self) -> list: + return [] + + with pytest.raises(AssertionError) as failed: + _sent_a_snapshot(_SentNothing(), "[T257zh]", proc) + said = str(failed.value) + assert planted not in said, "the planted value is in the failure message" + assert f"output's WARNING line: {warning}" in said, f"the template's line, shown:\n{said}" + assert "output: 5 line(s), 1 of them WARNING lines, 0 of no known template withheld" in said, \ + f"stderr's counts:\n{said}" + assert "register busy" not in said, f"a line no template matches is shown:\n{said}" + + +#: T257zt's planted writer: it writes the planted value, from its +#: environment, to its stdout and its stderr, then outlives its timeout. +T257ZT_WRITER = ("import os, sys, time\n" + "sys.stdout.write('out ' + os.environ['T257ZT_PLANTED'] + '\\n'); sys.stdout.flush()\n" + "sys.stderr.write('lanes-edit: ' + os.environ['T257ZT_PLANTED'] + '\\n'); sys.stderr.flush()\n" + "time.sleep(60)\n") + + +@pytest.mark.parametrize("case", ["sent-a-snapshot", "refused-with-no-value", "json-loads", + "timed-out-writer"]) +def test_pytests_own_report_of_a_failure_shows_no_planted_writer_text(request, case): + """T257zt (lane 3's ruling 6949488277 on lane 2's pre-review RV9-38 of + P09 at `3f9fcac4`, B1), with no engine: a failure whose raising frames + hold a planted value as arguments or locals, rendered as pytest renders + a failed test under the suite's own settings (`_reported`: the running + item's `repr_failure`, the terminal text that is also --junitxml's + failure body, and the JUnit failure message), holds no planted value. + Each case first proves the value is there to be shown: + - `sent-a-snapshot`: `_sent_a_snapshot`'s argument `proc`, a writer's + `CompletedProcess` whose stdout and stderr hold it; + - `refused-with-no-value`: `_t257u_refused_with_no_value`'s argument + `said`, a refusal's text that holds it; + - `json-loads`: `json.loads` of a writer's output that holds it, whose + frames in the standard library take the text as `s`; + - `timed-out-writer`: a planted writer, run by `subprocess.run` with a + timeout it outlives, whose partial stdout and stderr the standard + library's frames hold (`stdout_seq`, `stderr_seq`) and its + `TimeoutExpired` keeps; its command line holds no planted value. + Under pytest's default `--tb=auto` the first three and the last show it + as a long entry's arguments; T205e's short style shows none. An + explicit `--tb=long` or `--fulltrace` shows them again, and fails this + case: those are not secret-safe. The planted value is no credential of + any login.""" + planted = f"fake-{uuid.uuid4().hex}" + if case == "sent-a-snapshot": + proc = subprocess.CompletedProcess(["lanes-edit.sh"], 75, f"out {planted}\n", f"lanes-edit: {planted}\n") + + class _SentNothing: + def sent(self) -> list: + return [] + + with pytest.raises(AssertionError) as failed: + _sent_a_snapshot(_SentNothing(), "[T257zt]", proc) + assert planted in str(failed.getrepr(style="long", funcargs=True)), \ + "a long report does not show the planted value, so this proves nothing" + elif case == "refused-with-no-value": + with pytest.raises(AssertionError) as failed: + _t257u_refused_with_no_value(f"lanes-index: {planted} refused", "register_url", "1", 3) + assert planted in str(failed.getrepr(style="long", funcargs=True)), \ + "a long report does not show the planted value, so this proves nothing" + elif case == "json-loads": + with pytest.raises(json.JSONDecodeError) as failed: + json.loads(f"lanes-index: {planted}") + assert planted in failed.value.doc, "the planted output is not json's document, so this proves nothing" + else: + with pytest.raises(subprocess.TimeoutExpired) as failed: + subprocess.run([sys.executable, "-I", "-c", T257ZT_WRITER], capture_output=True, timeout=2, + env=dict(os.environ, T257ZT_PLANTED=planted)) + kept = (failed.value.stdout or b"") + (failed.value.stderr or b"") + assert planted.encode() in kept, "the writer's output did not reach its TimeoutExpired, so this proves nothing" + assert planted not in _reported(request, failed), f"[{case}] the planted value is in pytest's report" + + +#: What a failure message may not format but through `_said_safely` (T257zi; +#: T257zp; T257zy): a captured stream's attribute, a name these modules give a +#: stream, and the helpers that showed one before T257zh, T255s and T258l. +_STREAM_ATTRS = ("stdout", "stderr", "err", "out", "errs", "output") +_STREAM_NAMES = ("err", "out", "streams", "stdout", "stderr") +_STREAM_CALLS = ("_said", "_masked") +#: Calls whose result shows no text of the stream given as their first argument +#: (T257zp); each other argument they show as it is, so a stream there is a +#: place (T257zy): `_said_safely`'s `stream`, `_whole`'s `what`. +_SAFE_CALLS = ("_said_safely", "_lanes_shown", "_whole", "len", "_error_safely") +#: Calls whose arguments reach a failure's output, but a `file=` destination, +#: besides an assert's message, a raise, a call whose name ends `Error` or +#: `Exception`, a logging call and a terminal reporter's write (T257zi, T257zp, +#: T257zy, T257zzzd). A call counts by its dotted name with its first part +#: resolved (T257zzzd; lane 2's pre-review RV9-42 of P09 at `857a41d2`, S1): a +#: name from-imported from a module of `_IMPORTED_FROM` is that module's +#: (`stderr.write` after `from sys import stderr` is `sys.stderr.write`), and +#: a module imported under another name is that module (`pt.fail` after +#: `import pytest as pt` is `pytest.fail`). `_raised_nothing` takes its message. +_SINK_CALLS = ("pytest.fail", "pytest.skip", "pytest.xfail", "pytest.exit", "print", + "sys.stderr.write", "sys.stdout.write", "sys.__stderr__.write", + "sys.__stdout__.write", "sys.stderr.writelines", "sys.stdout.writelines", + "sys.__stderr__.writelines", "sys.__stdout__.writelines", "os.write", + "warnings.warn", "_raised_nothing") +_IMPORTED_FROM = ("pytest", "os", "sys", "warnings", "logging", "subprocess", "textwrap") +#: A terminal reporter's write (T257zzzd; RV9-42, S1): `.write_line`, +#: `.write_sep`, `.line`, `.write_raw`, `.section` or `.rewrite` of any object, +#: and `.write` of a name of `_REPORTERS`, of an attribute `_tw`, or of a +#: call's result `get_terminal_writer()` (T257zzzm; lane 2's targeted check +#: RV9-44 of P09 at `3faf9453`, N-2). pgcluster's `pytest_terminal_summary` +#: writes the run's foot so, to CI's terminal. +_REPORTER_WRITES = ("write_line", "write_sep", "line", "write_raw", "section", "rewrite") +_REPORTERS = ("terminalreporter", "tr", "reporter", "tw", "_tw") +#: The one place the check is told not to name, as (file, function, name) +#: (T257zzzd; RV9-42, S1; lane 2's pre-review RV9-41 of P09 at `4895579`, +#: N4): in pgcluster's `pytest_terminal_summary`, the module list `_DATACL`, +#: which holds psql's raw answer for a clone's `pg_database.datacl`, its +#: access list, and which the run's foot prints, as open point 12 requires. +#: It exempts every use of the name in that function, a second write, a loop +#: over it, a name bound from it and a function nested in it among them, not +#: the one foot line, in any module whose file is named pgcluster.py +#: (T257zzzn; lane 2's targeted check RV9-44 of P09 at `3faf9453`, N-1). +#: Today the foot line is its one use there. +_EXEMPT = (("pgcluster.py", "pytest_terminal_summary", "_DATACL"),) +#: A logging call (T257zy): `logging.<method>`, or `<name>.<method>` where the +#: name is `log` or `logger`, in any case. +_LOG_METHODS = ("debug", "info", "warning", "warn", "error", "exception", "critical", "log") +#: Calls whose result keeps the text of a stream given to them; a name bound to +#: any other call's result is not followed (T257zp; T257zy). +_TEXT_CALLS = ("str", "repr", "format", "sorted", "list", "tuple", "set", "reversed", "next", + "min", "max", "iter", "enumerate", "zip", "filter", "map", "dict", "vars", + "textwrap.indent", "textwrap.dedent", "textwrap.fill", "textwrap.wrap", + "textwrap.shorten") +#: Methods whose result is a stream's text, of whatever object they are called +#: on (T257zy; lane 2's targeted check RV9-39 of P09 at `3c5b68bc`, S2): +#: managed's `Session.send`, `said = held.send(...)`. Their object is the +#: stream's base. +_STREAM_RESULTS = ("send",) +#: A whole process (T257zy): a name of these, a name its function binds to one +#: of these calls, or a parameter annotated as one. Formatted whole (`{proc}`, +#: `{proc!r}`, `repr(proc)`), a `CompletedProcess` shows both its streams. +_PROCESS_NAMES = ("proc", "process", "result", "completed") +_PROCESS_CALLS = ("subprocess.run", "subprocess.Popen", "subprocess.CompletedProcess", + "CompletedProcess", "Popen") +#: The words, in a string of the message's own, that say a stream given bare to +#: the helper has no exit (T257zy). They are taken at their word. A string +#: inside a call of `_said_safely`, its `stream=` among them, is the helper's +#: and not the message's (T257zzze; RV9-42, N2). +_NO_EXIT = "no exit" +#: Functions whose returned text is a failure message (T257zy): pgcluster's +#: `_psql_failed` (T229k), `_counted` (T229m) and `Cluster.log_tail` (T229l). +#: Their returns are read as messages. A call of one in a message is read but +#: for a whole process given to it, whose exit and counts it shows (T257zzzf; +#: lane 2's pre-review RV9-42 of P09 at `857a41d2`, N1). A maker's own +#: parameters are no streams to the check, so one that returned its text +#: parameter's text would pass: that is a limit, named here. +_MESSAGE_MAKERS = ("_psql_failed", "_counted", "log_tail") + + +def _raw_streams_in(path: Path, only: tuple = ()) -> list: + """Each place in `path`'s source where a failure message formats a + captured stream other than through `_said_safely` (T257zi; T257zp, lane + 2's pre-review RV9-37 of P09 at `d9a1f2bf`, S6; T257zy, lane 2's + pre-review RV9-38 of P09 at `3f9fcac4`, S1, and targeted check RV9-39 at + `3c5b68bc`, S1, S2 and S4). Each is `file:line: the expression`. With + `only`, qualified function names (`Cluster.psql`), only places inside + those functions are named, and the module's docstring is not read. + + A failure message is an assert's message, the arguments of a raise of + any class, or of a name its function bound to a call and then raised, + the value a function of `_MESSAGE_MAKERS` returns, and the arguments of + a call of `_SINK_CALLS` but its `file=` destination, of a logging call + (`_LOG_METHODS`), of a terminal reporter's write (`_REPORTER_WRITES`, + `_REPORTERS`; T257zzzd), or of a call whose name ends `Error` or + `Exception`, each by its dotted name with its first part resolved + (`_SINK_CALLS`' note). A + stream there is an attribute of `_STREAM_ATTRS`, `getattr(x, "<one of + them>")`, a name of `_STREAM_NAMES`, a call of `_STREAM_CALLS` or of a + method of `_STREAM_RESULTS`, a call `.said()`, a name its function or an + enclosing function binds to text built from any of these (below), or a + whole process (`_PROCESS_NAMES`, a name bound to a call of + `_PROCESS_CALLS`, a parameter annotated `CompletedProcess` or `Popen`) + formatted whole. Inside a call of `_SAFE_CALLS` only its first argument + is exempt: `_said_safely`'s `stream`, `_whole`'s `what` and every other + argument is read as the message is. A pipe's `.closed` is no stream. + + Also a place, anywhere in a function: `int()` or `float()` of a stream, + whose ValueError quotes the text in its own message, which every + traceback style prints; and `pytest.raises(match=<a stream>)`, whose + failure prints its pattern. + + A name is bound to a stream's text (T257zp) by `=`, `+=`, `:=`, a `for` + or a `with` anywhere in its function, from an expression that holds a + stream: an attribute or a slice of one, a method of one (`strip()`, + `split()`, `splitlines()`, `decode()`), a str's `join` of one, one of + `_TEXT_CALLS` given one, or a literal, an f-string or an operator that + holds one. The order of the function's statements is not read: such a + name is one in the whole of its function, in each function nested in it + (a closure, T257zy), and, where a nested function binds it, in its + enclosing function too. A comprehension's result holds a stream where its + element does, its loop names taking their iterables' text. A tuple or + list literal is followed by position, so `said[0]` of `said = + (proc.returncode, proc.stdout)` is not a stream, nor is `argv[0]` where + `argv` is looped over rows of literals and only its third item came from + a stream. A name the module binds at its top level, which a function + gives a stream's text by `.append`, `.extend` or `.insert` + (`_DATACL.append(...)`), is a stream in every function (T257zzzd). + + A module whose docstring does not say PYTEST_DONT_REWRITE is a place too + (T257zj): pytest's assertion rewriting would add each tested operand, a + raw stream among them, to a failure's message. + + THE EXIT (T257zn; T257zq; structural since T257zy, RV9-39's S1: before + it, any `exit`, `returncode` or `.code` anywhere in the message's text, + identifiers and prose among them, counted). Each call of `_said_safely` + in a message, or in a value bound to a name the message formats, that + is given a bare stream, must show that stream's exit, or say that it has + none. Such a name is followed through every value its function binds it + to by `=`, an annotated `=`, `+=` or `:=`, from name to name, in no + order, its rebindings included (T257zzze; lane 2's pre-review RV9-42 of + P09 at `857a41d2`, S2), and what those values show is the message's + too. Bare is: an expression holding a stream attribute, a name bound to + a stream's text, a name bound to a call of a method of + `_STREAM_RESULTS`, a parameter annotated as text (`str`, `bytes`, + `bytearray` or `AnyStr`, anywhere in its annotation, `*args` and + `**kwargs` included), or a `CompletedProcess` made in the message, or + bound to a name, with an exit other than `<X>.returncode` (a constant, + `-1`, `returncode=-9`; T257zzze). The stream's object is its base: `proc` of + `proc.stderr` or of `copied = proc.stderr.strip()`, `held` of `said = + held.send(...)`. Its exit is shown by `exit=` given to the helper, as + `<base>.returncode` or `<base>.code`, as None (the helper says "no + exit"), or as a parameter annotated `int` where the stream has no base; + or, in the message, by `<base>.returncode`, `<base>.code`, + `<base>.exit_now()` or `_said_safely(<base>)`; or by the words of + `_NO_EXIT` in a string of the message's own, outside any call of + `_said_safely` (T257zzze; RV9-42, N2: `stream="no exit"` is the + helper's). + + What it cannot see (T257zp; T257zy): a name bound to the result of any + other call (`files = m.passfiles(proc.stdout)`, `with ctx(proc.stdout) + as t`), though a call given a stream inside a message is a place; text + that reaches a message through another function (`_burst_report`'s + rows), an attribute (`self.err = proc.stderr`) or a container's item + assigned later, but a top-level name's `.append`, `.extend` or + `.insert`; a module-level statement; an exception's own text + formatted in a message (`str(failed.value)`, `{exc}`), which the check + cannot tell from a helper's message, and an exception that code the test + calls raises with text of its own, which pytest prints under every + traceback style (T257zs's `_error_safely` is the form for the product's + errors; `Cluster.psql`'s is T229k's); `pytest.raises(match=...)`'s + failure, which prints the exception's text beside its pattern; a + parser but `int()` and `float()` whose error quotes the text it was + given, which every traceback style prints: a dict's lookup by a stream's + text as its key (its KeyError), `list.index`, `datetime.fromisoformat`, + `strptime` and `ipaddress`'s parsers (T257zzzg; lane 2's pre-review + RV9-42 of P09 at `857a41d2`, N3); `json.loads` of a stream, whose + error quotes no text but whose frame's argument `s` a long traceback + prints, as it prints every frame's + arguments: pytest's own report of a failed test, a fixture or a + teardown prints no frame's arguments only at the short style T205e makes + the default, and an explicit `--tb=long`, `--fulltrace` or + `--showlocals` prints them; the words of `_NO_EXIT`, taken as true; a + name bound more than once, whose every binding is read as one and + whose exit evidence in any binding counts for all, since neither the + order of statements nor a branch is read (`shown = + _said_safely(copied)`, then `if flag: shown = f"exit + {proc.returncode}"`; T257zzzn; RV9-44, N-3); and + output that a test's process writes itself, a child's output on an + inherited stream among them. + + One deliberate exception, named here and in `_EXEMPT`, so not a place + (lane 2's pre-review RV9-41 of P09 at `4895579`, N4; T257zzzd, RV9-42, + S1): pgcluster's `_DATACL` foot line, which `pytest_terminal_summary` + writes with `write_line` on every real-engine run (`... statements (open + point 12): <datacl>`), shows psql's raw answer for the clone's + `pg_database.datacl`, its access list, as open point 12 requires. The + check follows that answer from `new_database`'s `_DATACL.append(...)` to + the foot line, and `_EXEMPT` makes `_DATACL` no stream in that one + function: every use of it there, not only the foot line (T257zzzn; + RV9-44, N-1). Before T257zzzd no terminal reporter's write was a sink, so a + raw stream written there directly passed too.""" + tree = ast.parse(path.read_text(encoding="utf-8")) + found = [] + if not only and "PYTEST_DONT_REWRITE" not in (ast.get_docstring(tree, clean=False) or ""): + found.append(f"{path.name}:1: its docstring does not say PYTEST_DONT_REWRITE") + aliases = {} + for node in ast.walk(tree): + if isinstance(node, ast.ImportFrom) and node.module in _IMPORTED_FROM: + aliases.update({alias.asname or alias.name: f"{node.module}.{alias.name}" for alias in node.names}) + elif isinstance(node, ast.Import): + aliases.update({alias.asname: alias.name for alias in node.names if alias.asname}) + + def dotted(func) -> str: + name = ast.unparse(func) + head, dot, rest = name.partition(".") + return aliases[head] + dot + rest if head in aliases else name + + def names(target) -> list: + if isinstance(target, ast.Starred): + return names(target.value) + if isinstance(target, (ast.Tuple, ast.List)): + return [name for element in target.elts for name in names(element)] + return [target.id] if isinstance(target, ast.Name) else [] + + def raw(node, derived: dict, message: bool = True, whole: frozenset = frozenset()): + """The first stream in `node`, or None. In a message (`message`) a + call given a stream is one, and so is a whole process of `whole`; in + a bound value only `_TEXT_CALLS` and methods are, and a comparison + is not.""" + if isinstance(node, ast.Call) and (dotted(node.func) in _MESSAGE_MAKERS or ( + isinstance(node.func, ast.Attribute) and node.func.attr in _MESSAGE_MAKERS)): + if not message: + return None + shown = [*node.args, *(k.value for k in node.keywords)] + return next((hit for part in shown for hit in [raw(part, derived, message)] if hit), None) + if isinstance(node, ast.Call) and dotted(node.func) in _SAFE_CALLS: + if not message: + return None + shown = [*node.args[1:], *(k.value for k in node.keywords + if k.arg not in ("said", "text", "fields", "error"))] + return next((hit for part in shown for hit in [raw(part, derived, message, whole)] if hit), None) + if isinstance(node, ast.Attribute) and node.attr == "closed": + return None + if isinstance(node, ast.Call) and dotted(node.func) == "getattr" and len(node.args) > 1 and \ + isinstance(node.args[1], ast.Constant) and node.args[1].value in _STREAM_ATTRS: + return node + if isinstance(node, ast.Subscript) and isinstance(node.value, ast.Name) and \ + isinstance(derived.get(node.value.id), frozenset) and \ + isinstance(node.slice, ast.Constant) and isinstance(node.slice.value, int): + return node if node.slice.value in derived[node.value.id] else None + if ((isinstance(node, ast.Attribute) and node.attr in _STREAM_ATTRS) + or (isinstance(node, ast.Name) and (node.id in _STREAM_NAMES or node.id in derived)) + or (isinstance(node, ast.Call) and isinstance(node.func, ast.Name) + and node.func.id in _STREAM_CALLS) + or (isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) + and node.func.attr == "said" and not node.args) + or (isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) + and node.func.attr in _STREAM_RESULTS) + or (message and isinstance(node, ast.Name) and node.id in whole)): + return node + if isinstance(node, (ast.ListComp, ast.SetComp, ast.GeneratorExp, ast.DictComp)): + inner = dict(derived) + for loop in node.generators: + for name in names(loop.target): + inner.pop(name, None) + bind(loop.target, loop.iter, inner, loop=True) + parts = [node.key, node.value] if isinstance(node, ast.DictComp) else [node.elt] + return next((hit for part in parts for hit in [raw(part, inner, message, whole)] if hit), None) + if not message and isinstance(node, ast.Call) and not ( + (isinstance(node.func, ast.Attribute) + and (isinstance(node.func.value, ast.Constant) + or raw(node.func.value, derived, message) is not None)) + or dotted(node.func) in _TEXT_CALLS): + return None + if not message and isinstance(node, (ast.Compare, ast.Lambda)): + return None + for child in ast.iter_child_nodes(node): + base = (isinstance(node, ast.Attribute) and child is node.value) or \ + (isinstance(node, ast.Call) and child is node.func) + hit = raw(child, derived, message, frozenset() if base else whole) + if hit is not None: + return hit + return None + + def shape(value, derived: dict, loop: bool): + """What of `value` is a stream's text: "all", or the positions of a + literal's items that are (a loop's: of any of its rows).""" + rows = value.elts if loop and isinstance(value, (ast.Tuple, ast.List)) else \ + [value] if not loop and isinstance(value, (ast.Tuple, ast.List)) else None + if rows is None: + return "all" if raw(value, derived, message=False) is not None else frozenset() + if any(not isinstance(row, (ast.Tuple, ast.List)) and raw(row, derived, message=False) + for row in rows): + return "all" + return frozenset(i for row in rows if isinstance(row, (ast.Tuple, ast.List)) + for i, item in enumerate(row.elts) + if raw(item, derived, message=False) is not None) + + def bind(target, value, derived: dict, loop: bool = False) -> bool: + """Mark the names `target` binds from `value` that hold a stream's + text; True where one is new.""" + if isinstance(target, ast.Starred): + target = target.value + if isinstance(target, (ast.Tuple, ast.List)): + rows = value.elts if loop and isinstance(value, (ast.Tuple, ast.List)) else \ + [value] if not loop and isinstance(value, (ast.Tuple, ast.List)) else None + if rows is not None and all(isinstance(row, (ast.Tuple, ast.List)) + and len(row.elts) == len(target.elts) for row in rows): + columns = [ast.Tuple(elts=[row.elts[i] for row in rows], ctx=ast.Load()) + for i in range(len(target.elts))] + return any([bind(part, column, derived, loop=True) + for part, column in zip(target.elts, columns)]) + return any([bind(part, value, derived, loop) for part in target.elts]) + if not isinstance(target, ast.Name): + return False + held = shape(value, derived, loop) + if not held or derived.get(target.id) in (held, "all"): + return False + derived[target.id] = held if target.id not in derived else "all" + return True + + def bindings(function) -> list: + """Each (target, value, loop) its function binds, nested ones too.""" + pairs = [] + for node in ast.walk(function): + if isinstance(node, ast.Assign): + pairs += [(target, node.value, False) for target in node.targets] + elif isinstance(node, (ast.AnnAssign, ast.NamedExpr, ast.AugAssign)) and node.value is not None: + pairs.append((node.target, node.value, False)) + elif isinstance(node, ast.For): + pairs.append((node.target, node.iter, True)) + elif isinstance(node, ast.withitem) and node.optional_vars is not None: + pairs.append((node.optional_vars, node.context_expr, False)) + return pairs + + def derived_in(function, seed: dict) -> dict: + derived, changed = dict(seed), True + while changed: + changed = False + for target, value, loop in bindings(function): + changed = bind(target, value, derived, loop) or changed + return derived + + def bases(expr, origin: dict) -> set: + """The objects whose streams `expr` holds (its bases).""" + found_ = set() + for node in ast.walk(expr): + if isinstance(node, ast.Attribute) and node.attr in _STREAM_ATTRS: + found_.add(ast.unparse(node.value)) + elif isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) and \ + node.func.attr in _STREAM_RESULTS: + found_.add(ast.unparse(node.func.value)) + elif isinstance(node, ast.Name) and node.id in origin: + found_ |= origin[node.id] + return found_ + + def origins_in(function, seed: dict, derived: dict) -> dict: + """Each name bound to a stream's text, or by `X.communicate()` or + bounds' `_communicated(X)`: its bases.""" + origin, changed = {k: set(v) for k, v in seed.items()}, True + while changed: + changed = False + for target, value, _ in bindings(function): + if isinstance(value, ast.Call) and isinstance(value.func, ast.Attribute) and \ + value.func.attr == "communicate": + held = {ast.unparse(value.func.value)} + elif isinstance(value, ast.Call) and dotted(value.func) == "_communicated" and value.args: + held = {ast.unparse(value.args[0])} + elif raw(value, derived, message=False) is not None: + held = bases(value, origin) + else: + continue + for name in names(target): + if not held <= origin.get(name, set()): + origin[name] = origin.get(name, set()) | held + changed = True + return origin + + def annotated(function, pattern: str) -> set: + given = [*function.args.posonlyargs, *function.args.args, *function.args.kwonlyargs, + *[a for a in (function.args.vararg, function.args.kwarg) if a is not None]] + return {a.arg for a in given if a.annotation is not None + and re.search(pattern, ast.unparse(a.annotation))} + + def made_in(function) -> dict: + """Each name its function binds to a call: the call (its last).""" + return {target.id: node.value for node in ast.walk(function) + if isinstance(node, (ast.Assign, ast.AnnAssign, ast.NamedExpr)) and isinstance(node.value, ast.Call) + for target in (node.targets if isinstance(node, ast.Assign) else [node.target]) + if isinstance(target, ast.Name)} + + def told_in(function) -> dict: + """Each name its function binds by `=`, an annotated `=`, `+=` or + `:=`: every value it is given, in no order.""" + told_ = {} + for node in ast.walk(function): + if isinstance(node, (ast.Assign, ast.AnnAssign, ast.AugAssign, ast.NamedExpr)) and \ + node.value is not None: + for target in (node.targets if isinstance(node, ast.Assign) else [node.target]): + for name in names(target): + told_.setdefault(name, []).append(node.value) + return told_ + + functions = [node for node in ast.walk(tree) + if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))] + owner = {id(node): function for function in functions for node in ast.walk(function)} + enclosing = {} + + def nest(node, outer) -> None: + for child in ast.iter_child_nodes(node): + if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef)): + if outer is not None: + enclosing[id(child)] = outer + nest(child, child) + else: + nest(child, outer) + nest(tree, None) + qualified = {} + for node in ast.walk(tree): + for child in ast.iter_child_nodes(node): + if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): + prefix = qualified.get(id(node)) + qualified[id(child)] = f"{prefix}.{child.name}" if prefix else child.name + top = {name for node in tree.body if isinstance(node, (ast.Assign, ast.AnnAssign)) + for target in (node.targets if isinstance(node, ast.Assign) else [node.target]) + for name in names(target)} + kept = {} + for function in functions: + local = derived_in(function, {}) + kept.update({node.func.value.id: "all" for node in ast.walk(function) + if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) + and node.func.attr in ("append", "extend", "insert") + and isinstance(node.func.value, ast.Name) and node.func.value.id in top + and any(raw(arg, local, message=False) is not None for arg in node.args)}) + bound, origins, wholes, texts, ints, made, told, helps = {}, {}, {}, {}, {}, {}, {}, {} + + def facts(function) -> None: + if id(function) in bound: + return + outer = enclosing.get(id(function)) + if outer is not None: + facts(outer) + texts[id(function)] = annotated(function, r"\b(str|bytes|bytearray|AnyStr)\b") | \ + (texts[id(outer)] if outer is not None else set()) + ints[id(function)] = annotated(function, r"\bint\b") - texts[id(function)] + bound[id(function)] = derived_in(function, bound[id(outer)] if outer is not None else { + name: held for name, held in kept.items() + if (path.name, qualified.get(id(function)), name) not in _EXEMPT}) + origins[id(function)] = origins_in(function, origins[id(outer)] if outer is not None else {}, + bound[id(function)]) + made[id(function)] = {**(made[id(outer)] if outer is not None else {}), **made_in(function)} + told[id(function)] = {name: list(values) for name, values in + (told[id(outer)] if outer is not None else {}).items()} + for name, values in told_in(function).items(): + told[id(function)].setdefault(name, []).extend(values) + helps[id(function)], changed = set(), True + while changed: + changed = False + for name, values in told[id(function)].items(): + if name not in helps[id(function)] and any( + (isinstance(n, ast.Call) and dotted(n.func) == "_said_safely") + or (isinstance(n, ast.Name) and n.id in helps[id(function)]) + for value in values for n in ast.walk(value)): + helps[id(function)].add(name) + changed = True + wholes[id(function)] = frozenset( + set(_PROCESS_NAMES) | annotated(function, r"\b(CompletedProcess|Popen)\b") + | {name for name, call in made[id(function)].items() if dotted(call.func) in _PROCESS_CALLS} + | (wholes[id(outer)] if outer is not None else frozenset())) - set(bound[id(function)]) + + for function in functions: + facts(function) + + def inside(node) -> bool: + if not only: + return True + function = owner.get(id(node)) + while function is not None: + if qualified.get(id(function)) in only: + return True + function = enclosing.get(id(function)) + return False + + def place(line: int, text: str) -> None: + if f"{path.name}:{line}: {text}" not in found: + found.append(f"{path.name}:{line}: {text}") + + def walk(message: list, function, line: int, here: bool) -> None: + derived = bound[id(function)] if function is not None else {} + whole = wholes[id(function)] if function is not None else frozenset(_PROCESS_NAMES) + for part in message: + hit = raw(part, derived, True, whole) + if hit is not None: + place(line if here else getattr(hit, "lineno", line), ast.unparse(hit)[:80]) + + def exitless(message: list, function, line: int) -> None: + derived = bound[id(function)] if function is not None else {} + origin = origins[id(function)] if function is not None else {} + text_args = texts[id(function)] if function is not None else set() + int_args = ints[id(function)] if function is not None else set() + named = made[id(function)] if function is not None else {} + values = told[id(function)] if function is not None else {} + followed = helps[id(function)] if function is not None else set() + parts, seen, nodes = list(message), set(), [] + while parts: + for n in ast.walk(parts.pop()): + nodes.append(n) + if isinstance(n, ast.Name) and n.id in followed and n.id not in seen: + seen.add(n.id) + parts += values[n.id] + calls = [n for n in nodes if isinstance(n, ast.Call) and dotted(n.func) == "_said_safely"] + helpers = {id(n) for call in calls for n in ast.walk(call)} + words = " ".join(n.value for n in nodes if isinstance(n, ast.Constant) and isinstance(n.value, str) + and id(n) not in helpers) + + def closed(expr): + """The object whose ended process `expr` is: `X` where its + function bound `expr` to `X.close()`.""" + call = named.get(expr.id) if isinstance(expr, ast.Name) else None + if isinstance(call, ast.Call) and isinstance(call.func, ast.Attribute) and call.func.attr == "close": + return ast.unparse(call.func.value) + return None + + def fabricated(expr) -> bool: + """A `CompletedProcess` made in the message, or in any value + bound to the name `expr`, whose exit is not `<X>.returncode`.""" + for call in values.get(expr.id, []) if isinstance(expr, ast.Name) else [expr]: + if isinstance(call, ast.Call) and dotted(call.func).endswith("CompletedProcess"): + code = call.args[1] if len(call.args) > 1 else next( + (k.value for k in call.keywords if k.arg == "returncode"), None) + if not (isinstance(code, ast.Attribute) and code.attr == "returncode"): + return True + return False + + for call in calls: + said = call.args[0] if call.args else next((k.value for k in call.keywords if k.arg == "said"), None) + if said is None: + continue + base = bases(said, origin) + bare = fabricated(said) or raw(said, derived, message=False) is not None or \ + (isinstance(said, ast.Name) and said.id in text_args) + if not bare: + continue + given = next((k.value for k in call.keywords if k.arg == "exit"), None) + if given is not None: + shown = (isinstance(given, ast.Constant) and given.value is None) or \ + (isinstance(given, ast.Attribute) and given.attr in ("returncode", "code") + and ast.unparse(given.value) in base) or \ + (isinstance(given, ast.Name) and given.id in int_args and not base) + else: + shown = _NO_EXIT in words or any( + (isinstance(n, ast.Attribute) and n.attr in ("returncode", "code") + and ast.unparse(n.value) in base) + or (isinstance(n, ast.Call) and isinstance(n.func, ast.Attribute) + and n.func.attr == "exit_now" and ast.unparse(n.func.value) in base) + or (isinstance(n, ast.Call) and dotted(n.func) == "_said_safely" and n.args + and (ast.unparse(n.args[0]) in base or closed(n.args[0]) in base)) + for n in nodes) + if not shown: + place(line, f"a bare stream and no exit: {ast.unparse(call)[:70]}") + + for node in ast.walk(tree): + if not inside(node): + continue + function = owner.get(id(node)) + if isinstance(node, ast.Assert) and node.msg is not None: + message = [node.msg] + elif isinstance(node, ast.Raise) and isinstance(node.exc, ast.Call): + message = [*node.exc.args, *(k.value for k in node.exc.keywords)] + elif isinstance(node, ast.Raise) and isinstance(node.exc, ast.Name) and function is not None \ + and node.exc.id in made[id(function)]: + call = made[id(function)][node.exc.id] + message = [*call.args, *(k.value for k in call.keywords)] + walk(message, function, node.lineno, True) + exitless(message, function, node.lineno) + continue + elif isinstance(node, ast.Return) and node.value is not None and function is not None and \ + function.name in _MESSAGE_MAKERS: + message = [node.value] + elif isinstance(node, ast.Call) and ( + dotted(node.func) in _SINK_CALLS or dotted(node.func).endswith(("Error", "Exception")) + or (isinstance(node.func, ast.Attribute) and node.func.attr in _REPORTER_WRITES) + or (isinstance(node.func, ast.Attribute) and node.func.attr == "write" + and ((isinstance(node.func.value, ast.Name) and node.func.value.id in _REPORTERS) + or (isinstance(node.func.value, ast.Attribute) and node.func.value.attr == "_tw") + or (isinstance(node.func.value, ast.Call) + and ast.unparse(node.func.value.func).endswith("get_terminal_writer")))) + or (isinstance(node.func, ast.Attribute) and node.func.attr in _LOG_METHODS + and (dotted(node.func.value) == "logging" + or (isinstance(node.func.value, ast.Name) + and node.func.value.id.lower() in ("log", "logger"))))): + message = [*node.args, *(k.value for k in node.keywords if k.arg != "file")] + elif isinstance(node, ast.Call) and dotted(node.func) in ("int", "float") and node.args: + derived = bound[id(function)] if function is not None else {} + hit = raw(node.args[0], derived) + if hit is not None: + place(node.lineno, f"{dotted(node.func)}() of a stream: {ast.unparse(hit)[:60]}") + continue + elif isinstance(node, ast.Call) and dotted(node.func) == "pytest.raises": + derived = bound[id(function)] if function is not None else {} + for k in node.keywords: + hit = raw(k.value, derived) if k.arg == "match" else None + if hit is not None: + place(node.lineno, f"pytest.raises(match=) of a stream: {ast.unparse(hit)[:60]}") + continue + else: + continue + walk(message, function, node.lineno, False) + exitless(message, function, node.lineno) + return found + + +def test_no_failure_message_formats_a_captured_stream_but_through_the_one_helper(): + """The static check (T257zi; lane 3's ruling 6946445277 on lane 2's + pre-review RV9-36 of P09 at `2407ea06`, S2: "a test reads the three + modules and fails if an assert message formats a captured stdout or + stderr other than through the helper, so the class stays closed"), with + no engine and nothing imported: bounds, measure and managed are parsed, + and no failure message in them formats a captured stream other than + through `_said_safely` (`_raw_streams_in`). Each place found is named + by file and line. Each of the three must also say PYTEST_DONT_REWRITE in + its docstring (T257zj; RV9-37, B1), since pytest's assertion rewriting + would put each tested operand's value, a raw stream or a whole + `CompletedProcess` among them, beside every message the helper made. + And each message that gives the helper a bare stream shows that + stream's exit, or says it has none (T257zn; T257zq; structural since + T257zy). Since T257zy it also reads the whole of `tests/pgcluster.py` + (lane 3's rulings 6947252648, S4, and 6949488277, B2: T229k to T229s + made its raises show exits and counts only), docstring rule included. + + The forms it catches and the forms it cannot see are listed in + `_raw_streams_in`'s docstring, so a 0 here is no proof that no text of + a stream reaches a failure's output.""" + here = Path(__file__).resolve().parent + found = [place for name in ("test_sql_register_bounds.py", "test_sql_register_measure.py", + "test_sql_register_managed.py") + for place in _raw_streams_in(here / name)] + found += _raw_streams_in(here / "pgcluster.py") + assert not found, (f"{len(found)} place(s) can show a captured stream other than " + f"through _said_safely:\n" + "\n".join(found)) + + +#: A module for `test_the_static_check_names_each_kind_of_place_it_catches` +#: (T257zp; T257zy): each line marked `# planted` is a place, each marked +#: `# clean` is not. Parsed only, never imported or run. +_PLANTED = '''"""PYTEST_DONT_REWRITE""" +import logging +import os +import subprocess +import sys +import textwrap +import warnings + +import pytest +import pytest as pt +from pytest import fail +from sys import stderr + +_HELD: list = [] + + +def test_planted(proc, session, failed, ends, said_by, other, held, log): + message = f"the writer said {proc.stderr}" + assert proc.returncode == 0, message # planted + pytest.fail(message) # planted + assert session, f"held: {session.errs}" # planted + assert failed, f"called: {failed.output}" # planted + raise SystemExit(proc.stdout) # planted + raise Stopped(proc.stderr) # planted + pytest.exit(proc.stderr) # planted + sys.stderr.write(proc.stderr) # planted + sys.stdout.write(proc.stdout) # planted + warnings.warn(proc.stdout) # planted + tail = proc.stderr.strip().splitlines()[-3:] + assert proc.returncode == 0, f"its last lines: {tail}" # planted + for line in proc.stdout.splitlines(): + assert "LR" in line, line # planted + parts = "|".join(proc.stdout.split()) + assert parts, f"{parts}" # planted + assert proc.returncode == 0, f"{_said_safely(proc)} {len(proc.stderr)} {_whole(proc.stdout, 'n')}" # clean + assert proc.stdout.closed, f"{proc.stdout.closed}" # clean + ended = (proc.returncode, proc.stdout, len(proc.stderr)) + assert not ended[0], f"exit {ended[0]} after {ended[2]} bytes" # clean + for argv, tool in ((["import", "--at", proc.stdout], "a"), (["reconcile"], "b")): + assert tool, f"{argv[0]} made no call" # clean + shown = [f"writer {i}" for i, (_, _, err) in enumerate(ends) if "files mode" in err] + assert not shown, f"{shown}" # clean + copied = proc.stderr.strip() + assert not copied, f"its stderr: {_said_safely(copied)}" # planted + assert not copied, f"exit {proc.returncode}: {_said_safely(copied, stream='stderr')}" # clean + assert not said_by, f"{_said_safely(said_by)}" # clean + + def check(): + assert not proc.returncode, f"{tail}" # planted + assert proc.returncode == 0, f"{proc}" # planted + assert proc.returncode == 0, f"{proc!r}" # planted + assert proc.returncode == 0, repr(proc) # planted + assert proc.returncode == 0, f"{proc.returncode}: {_said_safely(proc, stream=proc.stderr)}" # planted + assert proc.returncode == 0, _whole(proc.stdout, proc.stderr) # planted + count = int(proc.stdout) # planted + with pytest.raises(ValueError, match=proc.stderr): # planted + count = int("1") # clean + logging.warning(proc.stderr) # planted + log.error(proc.stderr) # planted + os.write(2, proc.stderr) # planted + fail(proc.stderr) # planted + sys.__stderr__.write(proc.stdout) # planted + sys.stderr.writelines(proc.stdout.splitlines()) # planted + print(proc.stderr, file=sys.stderr) # planted + print(f"{count} fixed words", file=sys.stderr) # clean + wrapped = textwrap.indent(proc.stderr, " ") + assert not count, wrapped # planted + assert not count, getattr(proc, "stderr") # planted + stopped = Stopped(proc.stderr) + raise stopped # planted + assert not copied, f"the exit is not known: {_said_safely(copied)}" # planted + exit_note = "x" + assert not copied, f"{exit_note}: {_said_safely(copied)}" # planted + assert not copied, f"{other.returncode}: {_said_safely(proc.stderr)}" # planted + assert not copied, f"{proc.codec}: {_said_safely(proc.stderr)}" # planted + assert not copied, _said_safely(copied, stream="exit") # planted + assert not copied, _said_safely(subprocess.CompletedProcess([], 0, copied, "")) # planted + precomputed = _said_safely(proc.stderr) + assert not copied, f"{precomputed}" # planted + assert not copied, f"{_said_safely(other)} {_said_safely(copied)}" # planted + assert not copied, f"{_said_safely(proc)} {_said_safely(copied)}" # clean + assert not copied, _said_safely(proc.stderr, exit=proc.returncode) # clean + assert not copied, _said_safely(proc.stderr, exit=other.returncode) # planted + answered = held.send("SELECT 1;", "m") + assert "ERROR" not in answered, f"{_said_safely(answered, stream='stderr')}" # planted + assert "ERROR" not in answered, f"({held.exit_now()}) {_said_safely(answered, stream='stderr')}" # clean + terminalreporter.write_line(proc.stdout) # planted + terminalreporter.write_line(f"real-engine: {proc.stdout}") # planted + reporter.write(proc.stderr) # planted + tr.line(proc.stderr) # planted + tr.write_sep("=", proc.stderr) # planted + terminalreporter.write_raw(proc.stdout) # planted + terminalreporter.write_line(f"{count} fixed words") # clean + notes.write(proc.stderr) # clean + stderr.write(proc.stderr) # planted + pt.fail(proc.stderr) # planted + config.get_terminal_writer().write(proc.stdout) # planted + terminalreporter._tw.write(proc.stderr) # planted + tw = terminalreporter._tw + tw.write(proc.stderr) # planted + terminalreporter.section(proc.stdout) # planted + terminalreporter.rewrite(proc.stdout) # planted + terminalreporter._tw.write(f"{count} fixed words") # clean + _HELD.append(proc.stderr.strip()) + summed: str = _said_safely(copied) + assert not copied, f"{summed}" # planted + noted = f"its stderr: {_said_safely(copied)}" + assert not copied, noted # planted + joined = _said_safely(copied) + "" + assert not copied, joined # planted + rebound = _said_safely(copied) + assert not copied, f"{rebound}" # planted + rebound = len(copied) + assert not copied, _said_safely(subprocess.CompletedProcess([], -1, copied, "")) # planted + assert not copied, _said_safely(subprocess.CompletedProcess(args=[], returncode=-9, stdout=copied)) # planted + assert not copied, _said_safely(copied, stream="no exit") # planted + kept: str = f"exit {proc.returncode}: {_said_safely(proc.stderr)}" + assert not copied, kept # clean + assert not copied, _said_safely(subprocess.CompletedProcess([], proc.returncode, proc.stderr, "")) # clean + raise ClusterError(_psql_failed(proc.stderr, "db", proc)) # planted + raise ClusterError(log_tail(proc.stdout)) # planted + raise ClusterError(f"{_psql_failed(user, 'db', proc)} {_counted(proc)} {held.log_tail()}") # clean + + +def _planted_foot(terminalreporter): + terminalreporter.write_line(f"held: {_HELD[0]}") # planted + + +def _planted_text(text: str, data: bytes): + assert not text, f"{_said_safely(text)}" # planted + assert not data, f"{_said_safely(data, stream='stderr')}" # planted + assert not text, f"{_said_safely(text)}, and has no exit" # clean + + +def _planted_exit(said: str, its_exit: str, code: int | None): + assert not said, f"({its_exit}) {_said_safely(said)}" # planted + assert not said, _said_safely(said, exit=code) # clean + assert not said, _said_safely(said, exit=its_exit) # planted + + +def _planted_annotations(a: Optional[bytes], b: "str", *c: str, d: typing.Optional[str] = None, + e: str | bytes = "", f: AnyStr = "", g: Union[str, bytes] = ""): + assert not a, f"{_said_safely(a)}" # planted + assert not b, f"{_said_safely(b)}" # planted + assert not c, f"{_said_safely(c)}" # planted + assert not d, f"{_said_safely(d)}" # planted + assert not e, f"{_said_safely(e)}" # planted + assert not f, f"{_said_safely(f)}" # planted + assert not g, f"{_said_safely(g)}" # planted +''' +#: A module named pgcluster.py for the same test (T257zzzd; RV9-42, S1): +#: `_EXEMPT`'s `_DATACL` line is no place, and the same line of another list, +#: or of `_DATACL` in another function, is one. +_PLANTED_FOOT = '''"""PYTEST_DONT_REWRITE""" +_DATACL: list = [] +_OTHER: list = [] + + +def new_database(cluster): + acl = cluster.psql("SELECT 1").stdout.strip() + _DATACL.append(acl) + _OTHER.append(acl) + + +def pytest_terminal_summary(terminalreporter): + terminalreporter.write_line(f"open point 12: {_DATACL[0]}") # clean + terminalreporter.write_line(f"open point 12: {_OTHER[0]}") # planted + + +def elsewhere(terminalreporter): + terminalreporter.write_line(f"open point 12: {_DATACL[0]}") # planted +''' + + +def test_the_static_check_names_each_kind_of_place_it_catches(tmp_path): + """T257zp (lane 2's pre-review RV9-37 of P09 at `d9a1f2bf`, S6; lane 3's + ruling 6947252648: "the static check's blind spots, named"), with no + engine and nothing imported: `_raw_streams_in` reads a planted module, + `_PLANTED`, and names each place of each kind T257zi's check did not + see: a message built in a name before its assert or its `pytest.fail`, + `.errs` and `.output`, a raise of a class whose name ends neither + `Error` nor `Exception`, `pytest.exit`, `sys.stderr.write`, + `sys.stdout.write` and `warnings.warn`, text sliced from a stream into a + name, a loop over a stream's lines, and a str's `join` of one. And, for + the exit (T257zq; RV9-37, S9, the limit T257zn stated), a message that + gives the helper only a name holding a stream's text, or a parameter + annotated `str` or `bytes`, and shows no exit. + + Since T257zy (lane 2's pre-review RV9-38 of P09 at `3f9fcac4`, S1, and + targeted check RV9-39 at `3c5b68bc`, S1, S2, S4 and S5), each kind those + reviews found unseen: a closure; a whole process formatted (`{proc}`, + `{proc!r}`, `repr(proc)`); a stream as the helper's `stream` or as + `_whole`'s `what`; `int()` of a stream and `pytest.raises(match=)` of + one; `logging`, a logger's method, `os.write`, `fail` imported from + pytest, `sys.__stderr__.write`, `.writelines` and a stream as `print`'s + content where its `file=` is stderr; `textwrap` and `getattr` of a + stream; an exception made in a name and then raised. For the exit, each + of RV9-39's forms that passed the word rule: "exit" in prose or in an + identifier, another process's `returncode`, `.codec`, `stream='exit'`, a + `CompletedProcess` made with a constant exit, a helper's text made + before the message, a message whose other helper call shows another + process's exit, an `exit=` of another process, a name bound to + `held.send(...)`, `its_exit` as text, and the parameter annotations + `Optional[bytes]`, a quoted `"str"`, `*args: str`, + `typing.Optional[str]`, `str | bytes`, `AnyStr` and `Union[str, + bytes]`. It names no line marked clean: the helper, `len()` and + `_whole()`, a pipe's `.closed`, a literal's item that holds no stream + (`ended[0]`, `argv[0]`), a comprehension whose element holds none, a + message whose stream's own exit is shown (by its `returncode`, the + helper given its process whole, `exit=` of its own `returncode` or of an + `int` parameter, or `exit_now()` of its session), a message that says + it has no exit, and fixed words printed to stderr. + + Since T257zzzd (lane 2's pre-review RV9-42 of P09 at `857a41d2`, S1): + a terminal reporter's `write_line`, `write`, `line`, `write_sep` and + `write_raw`, `stderr.write` after `from sys import stderr`, `pt.fail` + after `import pytest as pt`, and a module list a function appends a + stream's text to, written in another function; and, in a module named + pgcluster.py (`_PLANTED_FOOT`), the same line of `_DATACL` in + `pytest_terminal_summary` (`_EXEMPT`) is clean while that of another + list, or of `_DATACL` elsewhere, is a place. A file's `write` and fixed + words written to the terminal are clean. Since T257zzzm (RV9-44, N-2): + `get_terminal_writer().write`, `_tw.write` (of the attribute, or of a + name `tw` bound to it), `.section` and `.rewrite`. + + Since T257zzze (RV9-42, S2 and N2), for the exit: a helper's text made + before the message by an annotated `=`, in an f-string held in a name, + by a concatenation, or in a name later rebound to another call; a + `CompletedProcess` made with exit `-1` or `returncode=-9`; and the words + "no exit" only in the helper's own `stream=`. A message built in a name + that shows its stream's exit, and a `CompletedProcess` made with its + process's `returncode`, are clean. + + Since T257zzzf (RV9-42, N1): a stream given to a message maker + (`_MESSAGE_MAKERS`) is a place; its process given whole is clean.""" + (tmp_path / "foot").mkdir() + for planted, text in ((tmp_path / "test_planted.py", _PLANTED), + (tmp_path / "foot" / "pgcluster.py", _PLANTED_FOOT)): + planted.write_text(text, encoding="utf-8") + lines = text.splitlines() + want = sorted(i + 1 for i, line in enumerate(lines) if line.endswith("# planted")) + clean = {i + 1 for i, line in enumerate(lines) if line.endswith("# clean")} + found = _raw_streams_in(planted) + named = sorted({int(place.split(":")[1]) for place in found}) + assert named == want, (f"in {planted.name}, the check named lines {named}, not the planted " + f"{want}:\n" + "\n".join(found)) + assert not clean & set(named), f"the check named a clean line: {sorted(clean & set(named))}" + assert all(place.startswith(f"{planted.name}:") for place in found), "\n".join(found) + + +def test_a_failed_psqls_cluster_error_shows_no_line_of_its_stderr(monkeypatch): + """T257zk (lane 3's ruling 6947252648 on lane 2's pre-review RV9-37 of + P09 at `d9a1f2bf`, S4; T229k), with no engine and no process: psql, + run by `Cluster.psql`, exits 3 with stderr that echoes a role statement + holding a planted value, once at psql's default verbosity and once at + verbose, with a SQLSTATE. The `ClusterError` raised shows the exit, the + SQLSTATE where there is one and the counts, and the planted value is in + neither its `str` nor its `repr` nor its formatted traceback. Before + T229k the error held psql's whole stderr. The planted value is no + credential of any login.""" + import traceback + import pgcluster + planted = f"fake-{uuid.uuid4().hex}" + cluster = object.__new__(pgcluster.Cluster) + cluster.root, cluster.bindir, cluster.port = Path("/nonexistent"), Path("/nonexistent/bin"), 5432 + for err, state in ((f"psql:<stdin>:1: ERROR: syntax error at or near \"x\"\n" + f"LINE 1: CREATE ROLE r LOGIN PASSWORD '{planted}' x;\n ^\n", + "no SQLSTATE in its text"), + (f"ERROR: 42601: syntax error at or near \"x\"\n" + f"LINE 1: ALTER ROLE r PASSWORD '{planted}' x;\n" + f"LOCATION: scanner_yyerror, scan.l:1188\n", "SQLSTATE 42601")): + monkeypatch.setattr(pgcluster.subprocess, "run", + lambda argv, err=err, **k: subprocess.CompletedProcess(argv, 3, "", err)) + with pytest.raises(pgcluster.ClusterError) as failed: + cluster.psql("SELECT 1", dbname="register", user="lanes_admin") + said = "".join(traceback.format_exception(failed.type, failed.value, failed.tb)) + assert planted not in str(failed.value), "the planted value is in the error's text" + assert planted not in repr(failed.value), "the planted value is in the error's repr" + assert planted not in said, "the planted value is in the formatted traceback" + assert str(failed.value) == (f"psql as lanes_admin on register exited 3: {state}; stderr: " + f"3 line(s), 1 of them ERROR, FATAL or PANIC lines; no line " + f"of it is shown"), f"the error says: {failed.value}" + + +def test_a_failed_psql_given_a_password_shows_it_in_no_failure_output(monkeypatch, request): + """T257zu (lane 2's pre-review RV9-38 of P09 at `3f9fcac4`, S2; lane 3's + rulings 6947252648, S4, and 6949488277, B1), with no engine and no + process: `Cluster.psql` is given a role statement whose password is a + planted value, as managed sends one (`CREATE ROLE ... LOGIN PASSWORD + '...'`), and psql, a stand-in, fails on it and echoes the statement it + was given, as psql does (`LINE 1: ...`). T257zk's case gave psql + `SELECT 1` and echoed a statement never sent. The `ClusterError` holds + the planted value in none of its `str`, `repr`, `args` or formatted + traceback, nor does pytest's own report of the failure (`_reported`), + where the statement is the raising frame's argument `sql`. The planted + value is no credential of any login.""" + import traceback + import pgcluster + planted = f"fake-{uuid.uuid4().hex}" + cluster = object.__new__(pgcluster.Cluster) + cluster.root, cluster.bindir, cluster.port = Path("/nonexistent"), Path("/nonexistent/bin"), 5432 + echoed = [] + + def psql(argv, input=None, **kwargs): + first = (input or "").splitlines()[0] + echoed.append(first) + return subprocess.CompletedProcess(argv, 3, "", (f"psql:<stdin>:1: ERROR: syntax error at or near \"x\"\n" + f"LINE 1: {first}\n ^\n")) + monkeypatch.setattr(pgcluster.subprocess, "run", psql) + with pytest.raises(pgcluster.ClusterError) as failed: + cluster.psql(f"CREATE ROLE lanes_w_bare LOGIN PASSWORD '{planted}' x;\n", dbname="register", + user="lanes_admin") + assert echoed and planted in echoed[0], "psql was not given the planted statement, so this proves nothing" + error = failed.value + shown = "".join(traceback.format_exception(type(error), error, failed.tb)) + for where, said in (("its str", str(error)), ("its repr", repr(error)), ("its args", repr(error.args)), + ("its formatted traceback", shown), ("pytest's report", _reported(request, failed))): + assert planted not in said, f"the planted value is in {where}" + + +# ============================== D9's rollback and cutover rows (T278), real engine + +#: The `git` wrapper that fails each push (TP:3633-3634, "a cutover whose push +#: the `git` wrapper fails"), first on `PATH`; every other git call goes on to +#: the real `git`, which `T278_REAL_GIT` names. +GIT_NO_PUSH = ('#!/bin/sh\n' + '# T278: the git wrapper that fails the push; every other call goes on\n' + 'for arg in "$@"; do\n' + ' if [ "$arg" = push ]; then echo "T278: push failed by the test" >&2; exit 1; fi\n' + 'done\n' + 'exec "$T278_REAL_GIT" "$@"\n') +#: The rollback's lost turns (TP:3607 at B14): `LANES_REGISTER_DEADLINE_S=6` and its +#: calls' 5000 ms `lock_timeout`. Its check has no figure of its own: the 75 +#: cell's bound takes the last try's check as measured from the `git` +#: wrapper's and the shim's logs, not a fixed 15 s (lane 3's batch 11 (7)(b), +#: #165 6783909985; `_rollback_checks`). +ROLLBACK_DEADLINE_S, ROLLBACK_LOCK_S = 6, 5 +#: T278b's `git` wrapper for the rollback's check (TP:3607 at B14, "where the +#: check is the fetch of `origin main` and the head read, timed from the `git` +#: wrapper's and the shim's logs"): first on `PATH`, it runs the real `git`, +#: which `T278_REAL_GIT` names, on the same standard streams, and then logs +#: the call's argv, its parent's pid, its start and end on the monotonic +#: clock and its exit, one JSON object a call, in `git-timing.log` beside it. +GIT_TIMING = r'''#!/usr/bin/env python3 +# T278b's git wrapper: each call's start and end, logged beside it. +import time +start = time.monotonic() +import json, os, subprocess, sys +here = os.path.dirname(os.path.abspath(__file__)) +real = os.environ.get("T278_REAL_GIT") or next( + (os.path.join(d, "git") for d in os.environ.get("PATH", "").split(os.pathsep) + if d and os.path.realpath(d) != os.path.realpath(here) + and os.access(os.path.join(d, "git"), os.X_OK)), "git") +code = subprocess.call([real] + sys.argv[1:]) +with open(os.path.join(here, "git-timing.log"), "a", encoding="utf-8") as handle: + handle.write(json.dumps({"argv": sys.argv[1:], "ppid": os.getppid(), "start": start, + "end": time.monotonic(), "exit": code}) + "\n") +sys.exit(code if code >= 0 else 128 - code) +''' +#: The register's write functions, as a request calls them (`TIMING_PSQL`'s +#: and the shim's logs). +WRITE_CALLS = ("commit_write(", "switch_to_files(", "record_marker(") + + +class Operator: + """T278's operator estate (TP:3627-3641, "The operator rows run the real + commands"): test 7's fixture register, T211's `FixtureRegister` (a bare + origin and the operator lane's checkout), imported at C into this test's + own database by `lanes-index import --at` (lane 1's T115), as + `pgcluster`'s `tmpl_imported` is built, since a template keeps no origin + a cutover can push to. T203's flipped copy of `lanes-index` + (`RENDER_GIT_HALF` True), so the operator's commands run on the + register's own schema; a login of REGISTER-WRITER's, made here as T220's + rows make theirs (the cluster's socket takes it by trust); and + `TIMING_PSQL` first on `PATH`. + + `estate`: `imported`, as the import leaves it, the switch at `files` with + the marker `absent`; `primary`, brought to `primary` with the marker + `present` by AT-LR006's route (the import module's `_to_primary`), which + pushes nothing, so origin carries no marker commit (T257's writer rows); + `cutover-done`, AT-6's "the cutover done (the switch at `primary`, and + `lanes/STORE` on a bare origin)": the imported estate cut over by the + real `cutover --import <C>` (lane 3's T327), whose marker commit, with + its `Register-Seq`, is pushed to origin, read back and recorded (T278d); + or `stray`, `cutover-done` with test 6's stray commit on origin after + the marker commit, so that it never reached the register (T278e, + `_stand_in_stray`). + + THE STRAY IS A STAND-IN (T278e; line BD15; TP open point 5's second + choice, "a stand-in stray commit, which does not prove the real old + writer"): AT-6's stray is the v1.1.0 `lanes-edit.sh`'s `log NOTED`, + pushed by a stale workstation that knows no marker, and its pinned copy + is test 6's, in another module's fixtures. Today's `lanes-edit.sh` + refuses a files-mode write once origin carries `lanes/STORE` (FR-004's + marker check), so it can make no stray on this estate. So a clone of + origin with no configuration appends one `NOTED` line, in the form the + fixture's own `log NOTED` wrote at C, to the same `lanes/log/` file, and + pushes it by plain `git`. T278 made its stray with today's writer on + `_to_primary`'s estate, whose origin carried no `Register-Seq`, so both + ways out refused 2 there ("origin main's last Register-Seq could not be + found"). Line BD15 saw that only on a scratch probe: on T326-m23 both + ways out end 1 first, a traceback, since T324's `_stray_recognised` + unpacks five of the six values T326 made `_render_read_head` return. + + WHY THE ROLLBACK'S ESTATE IS `cutover-done` (T278d; line BD15): T326's + step 0 fetches `origin main` on every try and walks its first-parent + line for the last `Register-Seq` (`rollback_step_0_git_half`, T322's + pass bounded at seq 0). On `_to_primary`'s estate no commit carries one, + so the rollback refused 2, "walk-failed", before step 1 ever ran. The + setup cutover runs with `TIMING_PSQL` off its `PATH`, so the timing, + send and begin logs hold the test's own command alone.""" + + def __init__(self, pg, tmp_path: Path, request, estate: str = "imported"): + from sql_register_helpers import flipped_copy + from test_sql_register_import import OPERATOR, TIP_A, FixtureRegister, _to_primary + self.pg, self.root, self.request, self.lane = pg, tmp_path, request, OPERATOR + self.reg = FixtureRegister(tmp_path / "reg") + noted = self.reg.c + if estate in ("imported", "cutover-done", "stray"): + # THE SEED'S HOLD WITH NO TIME IS RELEASED BEFORE THE IMPORT (line HC14; W3a's + # T211n `3fe23d7`, whose `HOLD_NO_UTC_RELEASE` this inlines, since BD's import + # module predates it): lane 1's open-`HOLD` check (merge21f6) counts + # `TAKE_LINES["hold-no-utc"]` as open, so a first-form cutover over it refuses 2. + # Its holder, the operator lane, releases it in files mode, and C is the tip after. + # `imported`, `cutover-done` and `stray` cut over; `primary` comes through + # `_to_primary`. + proc = self.reg.edit("append-line", "HOLD RELEASED — lane repoA-2 (Eagle), " + f"2026-10-01T05:20:00Z: opensoft/repoH main {TIP_A}", + env={"LANES_LANE": OPERATOR}) + assert proc.returncode == 0, ( + f"the dead HOLD's release, lanes-edit.sh append-line: {_said_safely(proc)}") + self.reg.c = self.reg.tip() + proc = self.reg.import_at(pg, self.reg.c) + assert proc.returncode == 0, \ + f"lanes-index import --at C (lane 1's T115): {proc.returncode}: {_said_safely(proc.stderr)}" + self.bin = tmp_path / "bin" + self.bin.mkdir() + (self.bin / "psql").write_text(TIMING_PSQL, encoding="utf-8") + (self.bin / "psql").chmod(0o755) + self.timing = self.bin / "psql-timing.log" + self.copy = flipped_copy(INDEXER, tmp_path / "tool", True) + for name in ("lanes-edit.sh", "repos.tsv", "lane-start"): + if (REPO / name).exists(): + shutil.copy2(REPO / name, tmp_path / "tool" / name) + self.passfile = _private(tmp_path / "conf" / "pgpass") + self.user = f"t278_{uuid.uuid4().hex[:12]}" + pg.psql(f"CREATE ROLE {self.user} LOGIN IN ROLE lanes_register_writer;") + request.addfinalizer(lambda: pg.cluster.psql(f"DROP ROLE IF EXISTS {self.user};", + check=False)) + self.env = dict(self.reg.env, T220_REAL_PSQL=pg.psql_bin, LANES_LANE=OPERATOR, + PATH=str(self.bin) + os.pathsep + self.reg.env["PATH"]) + self.mode, self.stray = "index", None + if estate == "primary": + _to_primary(pg, self.reg, load_indexer()) + self.mode = "primary" + if estate in ("cutover-done", "stray"): + # THE REAL CUTOVER (T278d), off `TIMING_PSQL`: the setup's own calls never + # reach the logs the test reads, and no fault is armed by its `commit_write`. + proc, _ = self.run(self.argv("cutover"), self.config(), + {"PATH": self.reg.env["PATH"]}) + assert proc.returncode == 0, ( + f"the estate's cutover --import C (lane 3's T327): {proc.returncode}: " + f"{_said_safely(proc.stderr)}") + switch = self.state()[0].split("|")[:2] + assert switch == ["primary", "present"], f"the estate's cutover left {switch}" + assert self.origin_tip() != self.reg.c, "the cutover's marker commit is not on origin" + self.mode = "primary" + if estate == "stray": + marker = self.origin_tip() + self.stray = self._stand_in_stray(noted) + assert self.stray not in (self.reg.c, marker), "the stray commit reached origin" + + def _git(self, *argv: str) -> str: + """`git` with the fixture's environment; its stdout.""" + return subprocess.run(["git", *argv], capture_output=True, text=True, check=True, + env=self.reg.env, stdin=subprocess.DEVNULL).stdout + + def _stand_in_stray(self, noted: str) -> str: + """Test 6's stray, a stand-in (T278e; the class's docstring): a + clone of origin with no configuration appends one line to the + `lanes/log/` file that the fixture's `log NOTED` at `noted` changed, + that commit's own added line with its text made the stray's, and + pushes it to origin's `main` by plain `git`. Returns origin's tip, + the stray.""" + wip = str(self.reg.wip) + paths = [p for p in self._git("-C", wip, "diff-tree", "--no-commit-id", "--name-only", + "-r", noted).split() if p.startswith("lanes/log/")] + assert len(paths) == 1, f"the fixture's log NOTED changed one log file: {paths}" + added = [line[1:] for line in self._git("-C", wip, "diff", f"{noted}^", noted, "--", + paths[0]).splitlines() + if line.startswith("+") and not line.startswith("+++") + and "the import's fixture, at C" in line] + assert len(added) == 1, f"the fixture's log NOTED added one line of its text: {added}" + clone = self.root / "stale" + self._git("clone", "-q", str(self.reg.origin), str(clone)) + target = clone / paths[0] + text = target.read_text(encoding="utf-8") + target.write_text(text + ("" if text.endswith("\n") else "\n") + + added[0].replace("the import's fixture, at C", "T278's stray commit") + + "\n", encoding="utf-8") + message = self._git("-C", wip, "log", "-1", "--format=%B", noted).replace( + "the import's fixture, at C", "T278's stray commit") + self._git("-C", str(clone), "add", "--", paths[0]) + self._git("-C", str(clone), "commit", "-q", "-m", message) + self._git("-C", str(clone), "push", "-q", "origin", "HEAD:main") + return self.origin_tip() + + def origin_tip(self) -> str: + """The bare origin's `main`, read there, so a push from any checkout + shows.""" + return subprocess.run(["git", "--git-dir", str(self.reg.origin), "rev-parse", "main"], + capture_output=True, text=True, check=True, + env=self.reg.env).stdout.strip() + + def config(self, host: str | None = None, port: int | None = None) -> Path: + """The operator's configuration (CLI section 2.5): both URLs name + `host:port`, or the cluster's socket, as this test's login, a private + password file, `register_label=` and `register_schema=`.""" + from test_sql_register_import import LABEL + host = host or quote(str(self.pg.host), safe="") + url = f"postgresql://{self.user}@{host}:{port or self.pg.port}/{self.pg.name}" + return _private(self.root / "conf" / "lanes-index.conf", "\n".join([ + f"mode={self.mode}", f"register_url={url}", f"register_passfile={self.passfile}", + f"reader_url={url}", f"reader_passfile={self.passfile}", + f"register_label={LABEL}", f"register_schema={SCHEMA}", ""])) + + def argv(self, row: str, form: str = "import-single") -> list: + """The row's command (CLI's USAGE; lane 3's T304, T324, T326 and T327 + for the forms merge10 lacks): `rollback`; `cutover --import <C>`, + which its abort and `record_marker` follow; and the stray ways out, + `import --single <sha>` or `render --revert <sha>` on the stray.""" + if row == "rollback": + return ["rollback"] + if row in ("cutover", "switch-to-files", "record-marker"): + return ["cutover", "--import", self.reg.c] + if form == "render-revert": + return ["render", "--revert", self.stray] + return ["import", "--single", self.stray] + + def fail_push(self) -> None: + """`GIT_NO_PUSH` first on `PATH`, for the cutover's abort.""" + (self.bin / "git").write_text(GIT_NO_PUSH, encoding="utf-8") + (self.bin / "git").chmod(0o755) + self.env["T278_REAL_GIT"] = shutil.which("git", path=self.reg.env["PATH"]) or "git" + + def time_git(self) -> None: + """`GIT_TIMING` first on `PATH`, for the rollback's check (T278b).""" + (self.bin / "git").write_text(GIT_TIMING, encoding="utf-8") + (self.bin / "git").chmod(0o755) + self.env["T278_REAL_GIT"] = shutil.which("git", path=self.reg.env["PATH"]) or "git" + + def git_calls(self) -> list: + """`GIT_TIMING`'s log: each `git` call that ended, in order.""" + log = self.bin / "git-timing.log" + return [json.loads(l) for l in log.read_text(encoding="utf-8").splitlines() if l] \ + if log.exists() else [] + + def run(self, argv: list, config: Path, extra: dict | None = None) -> tuple: + """`lanes-index <argv>` from the operator's checkout, as the operator + lane; (the process, its elapsed seconds). Its pid and exit stamp are + kept for `begins`.""" + env = dict(self.env, LANES_INDEX_CONFIG=str(config), **(extra or {})) + start = time.monotonic() + with subprocess.Popen([sys.executable, str(self.copy), *argv], stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, + env=env, cwd=str(self.reg.wip)) as child: + self.pid = child.pid + try: + out, err = child.communicate(timeout=300) + except subprocess.TimeoutExpired: + child.kill() + raise + self.exited = time.monotonic() + return subprocess.CompletedProcess(argv, child.returncode, out, err), self.exited - start + + def lane_checkout(self) -> Path: + """`<c>`, the operator lane's own register checkout, made once (T257l; + lane 4's triage, #165 6833813092, its group b1), as + `Bench.lane_checkout` makes the bench's: `<W>-lanes/<lane>`, W being + the real path of the fixture's `workspace.yaml` `path:`, its view of + the clone (`self.reg.ws`; Amendment 23 S5), and a clone of W's + origin. On primary a write refuses with nothing sent where it is not + there (`pw_checkout`, T415's R17). Only a writer makes it, after the + estate is built, so no operator command meets it.""" + real = Path(os.path.realpath(self.reg.ws)) + target = real.parent / f"{real.name}-lanes" / self.lane + if not target.exists(): + target.parent.mkdir(parents=True, exist_ok=True) + self._git("clone", "-q", str(self.reg.origin), str(target)) + return target + + def write(self, config: Path) -> tuple: + """A writer's whole path on this estate (T257j): `lanes-edit.sh + set-row-state` on the operator's lane, from its checkout, at + `LANES_REGISTER_DEADLINE_S=3`, D9's test value, as T257a's rows ran it + on `Bench`; (the process, its elapsed seconds), its pid and exit + stamp kept. The lane's own checkout is made first (T257l).""" + argv = ["bash", str(self.copy.parent / "lanes-edit.sh"), "set-row-state", self.lane, + f"PAUSED {DOT} T257's writer row"] + env = dict(self.env, LANES_INDEX_CONFIG=str(config), LANES_REGISTER_DEADLINE_S="3") + self.lane_checkout() + start = time.monotonic() + with subprocess.Popen(argv, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, + stderr=subprocess.PIPE, text=True, env=env, + cwd=str(self.reg.wip)) as child: + self.pid = child.pid + try: + out, err = child.communicate(timeout=300) + except subprocess.TimeoutExpired: + child.kill() + raise + self.exited = time.monotonic() + return subprocess.CompletedProcess(argv, child.returncode, out, err), self.exited - start + + def calls(self) -> list: + """`TIMING_PSQL`'s log: each call that ended, in order.""" + if not self.timing.exists(): + return [] + return [json.loads(l) for l in self.timing.read_text(encoding="utf-8").splitlines() + if l and json.loads(l)["argv"] != ["--version"]] + + def sent(self) -> list: + """`TIMING_PSQL`'s send stamps: each request read, with the write + functions it calls, before its `psql` connects (T278).""" + log = self.bin / "psql-sent.log" + return [json.loads(l) for l in log.read_text(encoding="utf-8").splitlines() if l] \ + if log.exists() else [] + + def armed_for(self, target: str): + """F1's or F2's arming for the faulted call: True once a request + calling `target` has been sent, so that call's own connect, and + every later one, meets the fault.""" + return lambda: any(target in s["calls"] for s in self.sent()) + + def begins(self) -> list: + """The begin stamps of the last run's own register calls, a call its + timer killed among them (T220f).""" + log = self.bin / "psql-begin.log" + begins = [json.loads(l) for l in log.read_text(encoding="utf-8").splitlines() if l] \ + if log.exists() else [] + return [b for b in begins if b["ppid"] == self.pid and b["argv"] == REGISTER_ARGV] + + def state(self) -> tuple: + """(the switch's mode, marker and set_seq; the head; origin's tip), + read as the superuser and from the bare origin.""" + switch = self.pg.psql(f"SELECT mode, marker_state, set_seq FROM {SCHEMA}.register_switch " + f"WHERE id = 1;").stdout.strip() + head = self.pg.psql(f"SELECT seq FROM {SCHEMA}.register_head WHERE id = 1;").stdout.strip() + return switch, head, self.origin_tip() + + +class ArmedFault(StartupRelay): + """A fault armed once an earlier, healthy call has ended (TP:3586-3589): + a relay to the cluster's socket that passes each connection whole while + `armed()` answers False, asked at each accept; once it answers True, F1 + holds each new connection and never speaks, and F2 goes silent after + the startup, as `StartupRelay` does.""" + + def __init__(self, unix_path: str, fault: str, armed): + self.fault = fault + super().__init__(unix_path, armed=armed) + + def _accept(self): + self.sock.settimeout(0.2) + while not self.done: + try: + conn, _ = self.sock.accept() + except OSError: + continue + on = bool(self.armed()) + if not (on and self.fault == "F1"): + # Tracked before a bounded connect, the pump started under + # close()'s lock or not at all: `StartupRelay._relay` (T278i). + self._relay(conn, on and self.fault == "F2") + continue + with self.lock: # F1: held under close()'s lock, never spoken to (T278h) + if self.done: + conn.close() + return + self.held.append(conn) + self.silenced += 1 + + +@pytest.mark.skipif(not sys.platform.startswith("linux"), + reason="T278i's stand-in for the cluster is in Linux's abstract Unix namespace") +@pytest.mark.parametrize("fault", ["F1", "F2"]) +def test_an_armed_faults_relayed_connection_is_tracked_before_a_bounded_connect(fault): + """T278i (Codex's SHOULD 3 on P09 at `21dd3642`), with no engine: + `ArmedFault`, not yet armed, relays each connection whole, in front of + a Unix listener of the standard library whose backlog is full, so a + connect to it would wait. The relay's connect has a bound, its client's + end is closed, and `close()` leaves no thread, for F1 and F2 alike. + Before T278i its accept connected with no bound before it tracked + either socket, so the connect waited on, out of `close()`'s reach, and + the client stayed open. T220p's case, `[full-backlog]`.""" + stand_in, name = _cluster_stand_in(0) + relay = ArmedFault(name, fault, lambda: False) + _relay_closed_as_t220p_has_it( + "full-backlog", "t278i-stuck-pump", + *_relay_case(relay, stand_in, name, "full-backlog", "t278i-stuck-pump")) + + +def _did(call: dict, what: str) -> bool: + """Whether a logged call is `what`: `snapshot`, or a write function's name.""" + return bool(call.get("snapshot")) if what == "snapshot" else what in call.get("calls", ()) + + +def _slow_trigger(pg, table: str, event: str, seconds: float) -> None: + """F4 for an operator's write (TP:3618-3621): a trigger the test creates in + its own database, after the import, never in the template, that sleeps + past the call's `statement_timeout`: `BEFORE <event>` on `table`, for each + row. On `register_switch` it fires only where the marker becomes + `present`, so the cutover's own update passes and `record_marker`'s + meets it; on `journal`, an `INSERT` trigger takes the write's entry and a + `DELETE` one the abort's.""" + when = " WHEN (NEW.marker_state = 'present')" if table == "register_switch" else "" + pg.psql(f"SET search_path TO {SCHEMA};\n" + f"CREATE FUNCTION t278_slow() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN " + f"PERFORM pg_sleep({seconds}); " + f"RETURN CASE WHEN TG_OP = 'DELETE' THEN OLD ELSE NEW END; END $$;\n" + f"GRANT EXECUTE ON FUNCTION t278_slow() TO PUBLIC;\n" + f"CREATE TRIGGER t278_slow BEFORE {event} ON {table} FOR EACH ROW{when} " + f"EXECUTE FUNCTION t278_slow();\n") + + +def _faulted_start(op: Operator, target: str | None) -> float: + """The faulted call's start (TP:3577-3579, "from the faulted call's + start"): the send stamp of the run's first request calling `target` + where the row names one, else the begin stamp of its first call.""" + if target is None: + begins = [b["begin"] for b in op.begins()] + assert begins, "the command made no register call" + return begins[0] + sends = [s["sent"] for s in op.sent() if s["ppid"] == op.pid and target in s["calls"]] + assert sends, f"the command sent no {target} call" + return sends[0] + + +def _fetches_origin(argv: list) -> bool: + """Whether a `git` call is a fetch from `origin`.""" + return "fetch" in argv and "origin" in argv + + +def _rollback_checks(op: Operator) -> list: + """Each try's check, as the 75 cell times it (TP:3607 at B14; lane 3's + batch 11 (7)(b), #165 6783909985): step 0's head read, T304's + `_rollback_read`, in the shim's log (`TIMING_PSQL`'s), and T326's fetch + of `origin main` right before step 1 (B14 tasks:1539), in the `git` + wrapper's (`GIT_TIMING`'s); a try's parts are the calls that start after + the try before's step 1 call ended and before its own step 1 call + starts. Returns each try's (its check's start, its check's span in s), + the span from its first part's start to its last part's end. The last + try's check must hold both its head read and its fetch: the bound is + measured on them.""" + calls, gits = op.calls(), op.git_calls() + steps = [c for c in calls if "commit_write" in c.get("calls", ())] + assert steps, f"the rollback made no step 1 call: {calls}" + checks, after = [], float("-inf") + for n, step in enumerate(steps, 1): + reads = [c for c in calls if not c.get("calls") and after <= c["start"] < step["start"]] + fetches = [g for g in gits if _fetches_origin(g["argv"]) + and after <= g["start"] < step["start"]] + parts = reads + fetches + if n == len(steps): + assert reads, f"the last try made no head read before its step 1: {calls}" + assert fetches, ("the last try fetched no origin main before its step 1 (T326's " + f"step 0, B14 tasks:1539): {gits}") + if parts: + begin = min(p["start"] for p in parts) + checks.append((begin, max(p["end"] for p in parts) - begin)) + after = step["end"] + return checks + + +def _operator_row(pg, tmp_path: Path, request, row: str, fault: str) -> None: + """`test_each_database_path_exits_inside_its_bound`'s T278 rows, at F1: + each operator command whose faulted call meets a silent listener at its + connect, armed at that call's own send where the row follows a healthy + call (`target`; `after`, the earlier call), exits with its row's outcome + inside twice its bound, timed from the faulted call's start. Where the + fault is armed, the earlier call reached the cluster. They fail until + lane 1's L1-A14 and lane 3's T304, T324, T326 and T327 land.""" + spec = ROWS[row] + op = Operator(pg, tmp_path, request, spec["estate"]) + before = op.state() + if row == "switch-to-files": + op.fail_push() + after, target = spec["after"], spec["target"] + if target is None: + listener = SilentListener() + else: + listener = ArmedFault(f"{pg.host}/.s.PGSQL.{pg.port}", fault, op.armed_for(target)) + try: + proc, _ = op.run(op.argv(row), op.config("127.0.0.1", listener.port)) + finally: + listener.close() + case = f"{row}-{fault}" + assert proc.returncode == spec["exit"], f"{case}: {proc.returncode}: {_said_safely(proc.stderr)}" + if after is not None: + assert any(_did(c, after) and c["exit"] == 0 for c in op.calls()), \ + f"{case}: the {after} call before the fault never reached the cluster" + assert listener.silenced, f"{case}: the {target} call never met F1" + if row in ("rollback", "cutover", "stray-calls"): + assert op.state() == before, f"{case}: something was written: {before} -> {op.state()}" + elapsed = op.exited - _faulted_start(op, target) + assert elapsed < 2 * spec["bound"], f"{case}: {elapsed:.2f} s against {spec['bound']} s" + _record(case, elapsed, spec["bound"], "timing rule 2, from the faulted call's start") + + +def _operator_57014(pg, tmp_path: Path, request, row: str) -> None: + """`test_a_slow_statement_meets_57014_before_the_client_timer`'s T278 + rows: F4's slow statement where the row's call works (`slow`), made + after the estate is built; the call ends with 57014 no earlier than its + `statement_timeout` after its start and under twice it, and the command + exits with the row's F4 outcome (`f4_exit`). They fail until lane 1's + L1-A14 and lane 3's T304, T324, T326 and T327 land.""" + spec = ROWS[row] + op = Operator(pg, tmp_path, request, spec["estate"]) + statement_s = spec["statement_ms"] / 1000 + table, event = spec["slow"] + if event == "policy": + _slow_statement(pg, table, "lanes_register_writer", 4 * statement_s + 5) + else: + _slow_trigger(pg, table, event, 4 * statement_s + 5) + if row == "switch-to-files": + op.fail_push() + proc, _ = op.run(op.argv(row), op.config()) + ended = [c for c in op.calls() if "57014" in c["first"]] + assert ended, f"{row}: no call ended with 57014: {op.calls()}" + took = ended[0]["end"] - ended[0]["start"] + assert statement_s <= took < 2 * statement_s, f"{row}: 57014 after {took:.2f} s" + assert proc.returncode == spec["f4_exit"], f"{row}: {proc.returncode}: {_said_safely(proc.stderr)}" + _record(f"{row}-F4", took, statement_s, "timing rules 2 and 3") + + +#: T257g: the image cache's head planted above the register's head, through +#: the flipped copy's own `image_cache_put` and `image_cache_record` (lane 1's +#: cache, design Y:4963), run in the operator's environment, so the cache is +#: the one `state_dir()` names for the command. A head above `k` is a miss +#: once the snapshot's request answers (`_register_snapshot_start`; lane 3's +#: ruling, #165 6746004829). Prints the cache's head as read back. +MISS_CACHE = r''' +import importlib.util, sys +from importlib.machinery import SourceFileLoader +copy, seq, path, text = sys.argv[1:5] +loader = SourceFileLoader("lanes_index_t257g", copy) +module = importlib.util.module_from_spec(importlib.util.spec_from_loader(loader.name, loader)) +loader.exec_module(module) +module.image_cache_record(int(seq), {path: module.image_cache_put(text.encode("utf-8"))}) +head = module.image_cache_head() +print(head[0] if head else "none") +''' + + +def _snapshot_miss(pg, tmp_path: Path, request, fault: str) -> None: + """`[snapshot-miss-F2]` (T257g; F13c's T257 bullet, R-F13c-18; lane 3's + batch 7, #165 6780364102, text change 18 and its ruling on T111's + SHOULD-2, option (b)): a writer's `register snapshot --write-id new + ... --tree <dir> --checkout <c>` (contract section 3.2) on the imported + register at `primary` misses the image cache, whose head is planted + above the register's (`MISS_CACHE`). F2 is armed once the first request + has ended, so that request reaches the cluster and the second, the whole + fetch (Y:2515-2516), meets the relay, silent after the startup. + `bounds` cuts that request's client timer to what is left of `S` from + the first request's start (lane 1's cut, #165 6783051626), so the + command sends both requests and ends 69 within `S`, 8 s, from the first + request's start (timing rule 2). It fails until lane 1's cut in T106 and + T111's use of it are on line R.""" + spec = ROWS["snapshot-miss"] + case = f"snapshot-miss-{fault}" + op = Operator(pg, tmp_path, request, "primary") + head = _whole(op.state()[1], "the register's head") + planted = subprocess.run([sys.executable, "-c", MISS_CACHE, str(op.copy), str(head + 5), + "lanes/LANES.md", "# LANES.md\n"], capture_output=True, text=True, + env=op.env, cwd=str(op.reg.wip), timeout=120, + stdin=subprocess.DEVNULL) + assert planted.stdout.strip() == str(head + 5), \ + f"{case}: the cache's head was not planted at {head + 5}: {_said_safely(planted)}" + relay = StartupRelay(f"{pg.host}/.s.PGSQL.{pg.port}", + armed=lambda: any(c.get("snapshot") for c in op.calls())) + argv = ["register", "snapshot", "--write-id", "new", "--lane", op.lane, + "--verb", WRITE["verb"], "--args-sha256", WRITE["args_sha256"], + "--tree", str(tmp_path / "snapshot-tree"), "--checkout", str(op.reg.wip)] + try: + proc, _ = op.run(argv, op.config("127.0.0.1", relay.port)) + finally: + relay.close() + assert proc.returncode == spec["exit"], f"{case}: {proc.returncode}: {_said_safely(proc.stderr)}" + first = [c for c in op.calls() if c.get("snapshot")] + assert first and first[0]["exit"] == 0, \ + f"{case}: the first request never reached the cluster: {op.calls()}" + requests = op.begins() + assert len(requests) == 2, \ + f"{case}: the miss's second request was not sent: {len(requests)} requests: {_said_safely(proc)}" + assert relay.silenced, f"{case}: the second request never met F2" + elapsed = op.exited - requests[0]["begin"] + assert elapsed < 2 * spec["bound"], f"{case}: {elapsed:.2f} s against {spec['bound']} s" + _record(case, elapsed, spec["bound"], "timing rule 2, from the first request's start") + + +#: T257j: the writer's SQL path is lane 4's (L4-B2, `lanes-edit.sh`'s SQL +#: writer), which line R's `lanes-edit.sh` lacks: until it lands, the writer +#: sends no snapshot request, and the cases say so rather than fail later. +NO_SQL_WRITER = "it fails until L4-B2, lanes-edit.sh's SQL writer" + + +def _sent_a_snapshot(op: Operator, case: str, proc) -> None: + """The writer sent its snapshot request: its SQL path ran (T257j).""" + assert any(s.get("snapshot") for s in op.sent()), \ + (f"{case}: the writer sent no snapshot request, so {NO_SQL_WRITER}: " + f"{proc.returncode}: {_said_safely(proc.stderr)}") + + +def _primary_writer_row(pg, tmp_path: Path, request, row: str, fault: str) -> None: + """`test_each_database_path_exits_inside_its_bound`'s T257a writer rows + whose fault comes after the snapshot's check 4 (T257j; line BD10's + doubt 1): `writer-commit-f2` at F2, `writer-commit-f3` and `whole-write` + at F3, each with its id, its fault and its expected exit, on the + imported register at `primary` (`Operator`), since `pg` alone is a + bootstrap-only clone whose switch reads `files` with the marker `absent` + and whose head is -1, where check 4 would end each write 69 before its + commit. The writer is `Operator.write`. F2 is armed at the commit's own + send (T257i; TP:3586-3589); F3 is the head row held `FOR UPDATE` + (`_hold_head`). They fail until L4-B2 and L4-B5.""" + spec = ROWS[row] + case = f"{row}-{fault}" + op = Operator(pg, tmp_path, request, "primary") + listener, session = None, None + try: + if fault == "F2": + # THE COMMIT'S F2 IS ARMED AT THE COMMIT'S OWN SEND (T257i; T257f + # armed it after the snapshot's end, TP:3586-3589): the relay + # passes each snapshot request whole, a missed snapshot's second + # request among them, which lane 1's cut sends under what is left + # of `S` (#165 6783051626) and which F2 would end 69, not 3. + listener = StartupRelay(f"{pg.host}/.s.PGSQL.{pg.port}", + armed=op.armed_for("commit_write")) + config = op.config("127.0.0.1", listener.port) + else: + session = _hold_head(pg) if row in HEAD_HELD_F3 else _hold(pg, spec["table"]) + config = op.config() + proc, elapsed = op.write(config) + finally: + if listener is not None: + listener.close() + if session is not None: + _end(session) + _sent_a_snapshot(op, case, proc) + assert proc.returncode == spec["exit"], f"{case}: {proc.returncode}: {_said_safely(proc.stderr)}" + if row == "writer-commit-f2": + # Every snapshot request sent before the commit's, a miss's second + # among them, reached the cluster and ended 0, and the commit's + # connection met the armed relay (TP:3589; T257i). + sends = [s["sent"] for s in op.sent() if "commit_write" in s["calls"]] + assert sends, f"{case}: the write sent no commit call: {op.sent()}" + snapshots = [c for c in op.calls() if c.get("snapshot") and c["start"] < sends[0]] + assert snapshots and all(c["exit"] == 0 for c in snapshots), \ + f"{case}: a snapshot request before the commit failed: {op.calls()}" + assert listener.silenced, f"{case}: no call met F2 at the commit's send" + if row == "whole-write": + # ITS OWN CELL (T257f): no attempt, each begun by its snapshot call, + # starts after the deadline, asserted at twice it (timing rule 2); the + # time runs from the first attempt's start, and stays under `T_write`. + # An attempt's start is its process's first snapshot request: a + # missed snapshot's second request, in the same process, starts no + # attempt (T257i; lane 1's cut, #165 6783051626). + firsts: dict = {} + for c in op.calls(): + if c.get("snapshot"): + firsts.setdefault(c.get("ppid"), c["start"]) + starts = sorted(firsts.values()) + assert starts, f"{case}: the write made no attempt" + late = [round(s - starts[0], 2) for s in starts + if s - starts[0] >= 2 * WHOLE_WRITE["deadline_s"]] + assert not late, f"{case}: attempts started after the deadline: {late}" + elapsed = op.exited - starts[0] + assert elapsed < WHOLE_WRITE["t_write_s"], \ + f"{case}: {elapsed:.2f} s, over T_write's {WHOLE_WRITE['t_write_s']} s" + _record(f"{case}-T_write", elapsed, WHOLE_WRITE["t_write_s"], + f"T_write, from the first attempt's start, {len(starts)} attempts") + assert elapsed < 2 * spec["bound"], f"{case}: {elapsed:.2f} s against {spec['bound']} s" + _record(case, elapsed, spec["bound"], "timing rule 2" + ( + ", from the first attempt's start" if row == "whole-write" else "")) + + +def _primary_writer_57014(pg, tmp_path: Path, request, row: str) -> None: + """`test_a_slow_statement_meets_57014_before_the_client_timer`'s + `[writer-commit-f2]` (T257h, T257j): on the imported register at + `primary` (`Operator`), past the snapshot's check 4, the commit's entry + meets a trigger on `journal` that sleeps (`slow`), made after the + estate is built; the call ends with 57014 no earlier than its + `statement_timeout` after its start and under twice it, and the writer + exits 69 (`f4_exit`), a refusal the database made (TP:3621-3626 at + B14). It fails until L4-B2 and L4-B5.""" + spec = ROWS[row] + op = Operator(pg, tmp_path, request, "primary") + statement_s = spec["statement_ms"] / 1000 + _slow_trigger(pg, *spec["slow"], 4 * statement_s + 5) + proc, _ = op.write(op.config()) + _sent_a_snapshot(op, row, proc) + ended = [c for c in op.calls() if "57014" in c["first"]] + assert ended, f"{row}: no call ended with 57014: {op.calls()}" + took = ended[0]["end"] - ended[0]["start"] + assert statement_s <= took < 2 * statement_s, f"{row}: 57014 after {took:.2f} s" + assert proc.returncode == spec["f4_exit"], f"{row}: {proc.returncode}: {_said_safely(proc.stderr)}" + _record(f"{row}-F4", took, statement_s, "timing rules 2 and 3") + + +def test_a_rollback_whose_first_call_expires_rereads_the_switch(pg, tmp_path, request): + """AT-D9's `rollback` row (TP:3604): "Where step 1's call expires, the + rollback reads the switch again and never goes on to step 2 on an + unknown switch." On the `cutover-done` estate (T278d), F2 is armed at + step 1's own send, its `commit_write` (TP:3586-3589, "once the shim's + log shows the earlier call's end"), so every call of the check before + it reaches the cluster, and step 1's call expires at its 15 s timer, and + so does the switch's re-read: 69, inside twice 15 + 15 = 30 s from step + 1's start; exactly two calls after the check's last, step 1's and then + the re-read, a read that calls no write function, and none after them; + the switch, the head and origin unchanged. + + THE ARMING (T278d; line BD15): T278 armed F2 once the rollback's first + call had ended, its head read (lane 3's batch 11 (7)(b), #165 + 6783909985). Since T326 the check is that read, then step 0's fetch of + `origin main` and the head read after it (`rollback_step_0_git_half`), + so that arming put F2 on step 0's read, and the rollback ended 69 with + one call after the first, never reaching step 1. It fails until lane 3's + T304, T326 and T327 land (the estate's cutover is T327's).""" + op = Operator(pg, tmp_path, request, "cutover-done") + before = op.state() + relay = ArmedFault(f"{pg.host}/.s.PGSQL.{pg.port}", "F2", op.armed_for("commit_write")) + try: + proc, _ = op.run(["rollback"], op.config("127.0.0.1", relay.port)) + finally: + relay.close() + assert proc.returncode == 69, f"rollback: {proc.returncode}: {_said_safely(proc.stderr)}" + calls = op.calls() + assert calls and all(c["exit"] == 0 for c in calls), \ + f"a call of the check before step 1 did not answer: {calls}" + healthy = max(c["end"] for c in calls) + later = [b["begin"] for b in op.begins() if b["begin"] >= healthy] + assert len(later) == 2, \ + f"step 1's call and the switch's re-read, and nothing after: {len(later)} calls" + sends = [s for s in op.sent() if s["ppid"] == op.pid and s["sent"] >= healthy] + assert [s["calls"] for s in sends] == [["commit_write"], []], \ + f"step 1's commit_write, then a read of the switch: {sends}" + assert op.state() == before, f"the rollback wrote: {before} -> {op.state()}" + elapsed = op.exited - later[0] + assert elapsed < 2 * 30, f"rollback: {elapsed:.2f} s against 15 + 15 s" + _record("rollback-first-call", elapsed, 30, "timing rule 2, step 1's and the re-read's") + + +def test_a_rollback_that_keeps_losing_its_turn_exits_75_at_the_deadline_with_nothing_written( + pg, tmp_path, request): + """AT-D9's `rollback` row under F3 (TP:3604): step 1's call ends in a lost + turn, 55P03 at its 5000 ms `lock_timeout`, against the head row held + `FOR UPDATE` by the test's own session (`_hold_head`); the rollback reads + the head afresh and tries again, and at `LANES_REGISTER_DEADLINE_S=6` + exits 75, with nothing written and the switch still `primary`. From the + rollback's start (TP:3607 at B14): no check starts after the deadline, + asserted at twice it (timing rule 2), and the run ends inside twice the + deadline, plus one check, plus the last call's 5 s. The check is each + try's head read and its fetch of `origin main`, timed from the shim's + log and the `git` wrapper's (`GIT_TIMING`), and the bound takes the last + try's as measured, not a fixed 15 s (lane 3's batch 11 (7)(b), + `_rollback_checks`). It runs on the `cutover-done` estate (T278d): on + `_to_primary`'s, T326's step 0 found no `Register-Seq` on origin and + refused 2 before step 1. It fails until lane 3's T304, T326 and T327 + land (the estate's cutover is T327's).""" + op = Operator(pg, tmp_path, request, "cutover-done") + before = op.state() + op.time_git() + session = _hold_head(pg) + try: + proc, elapsed = op.run(["rollback"], op.config(), + {"LANES_REGISTER_DEADLINE_S": str(ROLLBACK_DEADLINE_S)}) + finally: + _end(session) + assert proc.returncode == 75, f"rollback-F3: {proc.returncode}: {_said_safely(proc.stderr)}" + assert any("55P03" in c["first"] for c in op.calls()), \ + f"no call ended with 55P03: {op.calls()}" + assert op.state() == before, f"the rollback wrote: {before} -> {op.state()}" + start = op.exited - elapsed + checks = _rollback_checks(op) + late = [round(begin - start, 2) for begin, _ in checks + if begin - start >= 2 * ROLLBACK_DEADLINE_S] + assert not late, f"rollback-F3: checks started after the deadline: {late}" + check = checks[-1][1] + bound = ROLLBACK_DEADLINE_S + check + ROLLBACK_LOCK_S + assert elapsed < 2 * bound, \ + f"rollback-F3: {elapsed:.2f} s against {bound:.2f} s, the last check {check:.2f} s" + _record("rollback-F3-75", elapsed, bound, f"timing rule 2, from the rollback's start; " + f"the last try's check measured at {check:.2f} s, {len(checks)} tries") + + +@pytest.mark.parametrize("fault", ["F1", "F2", "F3", "F4"]) +def test_a_cutover_whose_call_expires_leaves_the_switch_unknown_and_its_rerun_reads_it_first( + pg, tmp_path, request, fault): + """AT-D9's `cutover` row (TP:3606; TP:3629-3631): on the imported + register and its origin, the fault takes the transaction's call, so no + marker is pushed: F1 and F2 armed at the transaction's own send, after + the cutover's read has ended (TP:3586-3589), F3 the head row held `FOR + UPDATE`, which `commit_write` takes, and F4 a trigger on `journal` that + sleeps (`_slow_trigger`). It + exits 69, the switch still `files` with the marker `absent`, the head + and origin unchanged; the transaction's call inside twice 15 s, or under + F3 twice its 5000 ms `lock_timeout`, from its start. A rerun after the + fault is removed reads the switch and the journal first, its first call + no commit, and goes on: 0, one `cutover` entry, the switch `primary` with + the marker `adding` or, with T327's push and read-back, `present`. It + fails until lane 1's L1-A14 and lane 3's T327 land.""" + op = Operator(pg, tmp_path, request, "imported") + before = op.state() + listener, session = None, None + try: + if fault in ("F1", "F2"): + listener = ArmedFault(f"{pg.host}/.s.PGSQL.{pg.port}", fault, + op.armed_for("commit_write")) + config = op.config("127.0.0.1", listener.port) + else: + if fault == "F3": + session = _hold_head(pg) + else: + _slow_trigger(pg, "journal", "INSERT", 45) + config = op.config() + proc, _ = op.run(op.argv("cutover"), config) + finally: + if listener is not None: + listener.close() + if session is not None: + _end(session) + assert proc.returncode == 69, f"cutover-{fault}: {proc.returncode}: {_said_safely(proc.stderr)}" + assert op.state() == before, f"cutover-{fault} wrote or pushed: {before} -> {op.state()}" + calls = op.calls() + assert calls and calls[0]["exit"] == 0, f"the cutover's read never answered: {calls}" + bound = 5 if fault == "F3" else 15 + elapsed = op.exited - _faulted_start(op, "commit_write") + assert elapsed < 2 * bound, f"cutover-{fault}: {elapsed:.2f} s against {bound} s" + _record(f"cutover-{fault}", elapsed, bound, "timing rule 2, from the transaction's start") + if fault == "F4": + pg.psql(f"DROP TRIGGER t278_slow ON {SCHEMA}.journal;") + mark = len(op.calls()) + proc, _ = op.run(op.argv("cutover"), op.config()) + assert proc.returncode == 0, f"the rerun: {proc.returncode}: {_said_safely(proc.stderr)}" + rerun = op.calls()[mark:] + assert rerun and "commit_write" not in rerun[0]["calls"], \ + f"the rerun's first call is not a read of the switch: {rerun}" + entries = pg.psql(f"SELECT count(*) FROM {SCHEMA}.journal WHERE kind = 'cutover';").stdout + assert entries.strip() == "1", \ + f"one cutover entry, not {_whole(entries, 'the count of cutover entries')}" + mode, marker, _ = op.state()[0].split("|") + assert mode == "primary" and marker in ("adding", "present"), op.state() + + +@pytest.mark.parametrize("landed", ["not-landed", "landed"]) +def test_the_aborts_call_that_expires_is_run_again_or_found_done_by_its_rerun( + pg, tmp_path, request, landed): + """AT-D9's `switch_to_files` row (TP:3606; TP:3632-3635): a cutover whose + push the `git` wrapper fails (`GIT_NO_PUSH`) runs its abort, whose call + meets T203's shim, first on `PATH`: `[not-landed]`, its `before` mode, so + the call is lost before its `COMMIT`; `[landed]`, its `timer` mode at + 20 s, so the call commits and its answer comes after the 15 s timer. + Either way the cutover exits 69, inside twice 15 s from the abort's call. + Once the fault is removed, the rerun, `cutover` again with the push + still failing (lane 3's batch 11 (7)(c), #165 6783909985), reads the + switch. After `before` the abort did not land, so the rerun runs it + again, one `switch_to_files` call, and ends with the abort's 2, the + switch `files` with the marker `absent`. After `timer` it landed, and + the switch at `files` with the marker `absent` is also "before any + cutover" (Y:1531), so the rerun runs no abort for that entry and goes on + as a first cutover would: its first write call is `commit_write`, never + `switch_to_files`; with the push still failing it then aborts its own + entry once and ends 2, the switch `files` with the marker `absent` and + the head back at the import's seq. "Sends nothing" (TP:3641-3642 at B14) + cannot hold, and B15 drops it. It fails until lane 1's L1-A14 and lane + 3's T327 land.""" + op = Operator(pg, tmp_path, request, "imported") + imported = op.state()[1] + op.fail_push() + arm = {"mode": "before"} if landed == "not-landed" else {"mode": "timer", "ms": 20000} + where = _shim(op, [dict(arm, match="switch_to_files")]) + proc, _ = op.run(op.argv("switch-to-files"), op.config()) + assert proc.returncode == 69, f"abort-{landed}: {proc.returncode}: {_said_safely(proc.stderr)}" + sent = [e for e in _shim_calls(where) if "switch_to_files(" in e["stdin"]] + assert len(sent) == 1, f"abort-{landed}: one abort call: {len(sent)}" + mode = op.state()[0].split("|")[:2] + assert mode == (["primary", "adding"] if landed == "not-landed" else ["files", "absent"]), \ + f"abort-{landed}: the switch reads {mode}" + _arm(where, op, []) + mark = len(_shim_calls(where)) + proc, _ = op.run(op.argv("switch-to-files"), op.config()) + rerun = _shim_calls(where)[mark:] + aborts = [e for e in rerun if "switch_to_files(" in e["stdin"]] + if landed == "not-landed": + assert len(aborts) == 1, f"the rerun runs the abort again, once: {len(aborts)}" + assert proc.returncode == 2, f"the rerun's abort: {proc.returncode}: {_said_safely(proc.stderr)}" + else: + writes = [[w[:-1] for w in WRITE_CALLS if w in e["stdin"]] for e in rerun] + writes = [w for w in writes if w] + assert writes and writes[0] == ["commit_write"], \ + f"the rerun's first write call is commit_write, never switch_to_files: {writes}" + assert len(aborts) == 1, f"the rerun aborts its own entry once: {len(aborts)}" + assert proc.returncode == 2, f"the rerun's own abort: {proc.returncode}: {_said_safely(proc.stderr)}" + assert op.state()[1] == imported, \ + f"the head is back at the import's seq {imported}: {op.state()}" + assert op.state()[0].split("|")[:2] == ["files", "absent"], op.state() + + +def test_a_record_marker_that_expires_leaves_the_marker_adding_and_writes_refusing( + pg, tmp_path, request): + """AT-D9's `record_marker` row (TP:3607; TP:3636-3638): reached after the + cutover's push and read-back. The fault takes its call: T203's shim, + first on `PATH`, holds the `record_marker` call on a FIFO no one opens, + so it is never sent and the cutover's 15 s timer ends it: 69. The push + stands, the marker reads `adding`, and a writer's commit, `lanes-edit.sh + set-row-state` on the operator's lane with `mode=primary` (lane 3's batch + 11 (7)(d), #165 6783909985), refuses with 69, its stderr naming the + marker's refusal (TP:4180-4181; Y:3580): LR002, or its snapshot's words + on the switch it read, the marker `adding` (TP:4221-4222; T278f). + T409's placeholder exits 69 on primary too (B14 tasks:937), so the exit + alone proves nothing. The + rerun, the fault removed, records the marker once: one `record_marker` + call, 0, the marker `present`. The writer runs from the operator lane's + own checkout, made first (`Operator.lane_checkout`, T278f; lane 4's + triage, #165 6833813092, b1): without it T415's write refuses before + any call (R17). It fails until lane 1's L1-A14, lane 3's T327 and lane + 4's L4-B2 land, and its writer until lane 4's T415.""" + op = Operator(pg, tmp_path, request, "imported") + fifo = tmp_path / "hold-record-marker" + os.mkfifo(fifo) + where = _shim(op, [{"mode": "hold", "match": "record_marker", "fifo": str(fifo)}]) + proc, elapsed = op.run(op.argv("record-marker"), op.config()) + assert proc.returncode == 69, f"record-marker: {proc.returncode}: {_said_safely(proc.stderr)}" + assert any("record_marker(" in e["stdin"] for e in _shim_calls(where)), \ + "the cutover made no record_marker call" + assert op.origin_tip() != op.reg.c, "the cutover's push stands on origin" + assert op.state()[0].split("|")[:2] == ["primary", "adding"], op.state() + _arm(where, op, []) + config = op.config() + config.write_text(config.read_text().replace("mode=index", "mode=primary")) + op.lane_checkout() + writer = subprocess.run(["bash", str(op.copy.parent / "lanes-edit.sh"), "set-row-state", + op.lane, f"PAUSED {DOT} T278's write behind the marker"], + capture_output=True, text=True, timeout=300, cwd=str(op.reg.wip), + stdin=subprocess.DEVNULL, + env=dict(op.env, LANES_INDEX_CONFIG=str(config))) + assert writer.returncode == 69, f"the writer's commit: {writer.returncode}: {_said_safely(writer.stderr)}" + # THE MARKER'S REFUSAL (T278f; line BD17): the write "exits 69 on the switch + # its snapshot reads, or on LR002" (TP:4221-4222). T415's writer meets + # the marker at its first snapshot, whose own words name the switch it read, + # the marker `adding`, before any commit call; a commit call would get LR002. + # Either is the marker's, never T409's placeholder, which names no marker. + assert "LR002" in writer.stderr or "marker adding" in writer.stderr, \ + (f"the writer's 69 is the marker's refusal, at its snapshot or LR002, not T409's " + f"placeholder: {_said_safely(writer)}") + mark = len(_shim_calls(where)) + proc, _ = op.run(op.argv("record-marker"), op.config()) + recorded = [e for e in _shim_calls(where)[mark:] if "record_marker(" in e["stdin"]] + assert proc.returncode == 0 and len(recorded) == 1, \ + f"the rerun records the marker once: {proc.returncode}, {len(recorded)}: {_said_safely(proc.stderr)}" + assert op.state()[0].split("|")[:2] == ["primary", "present"], op.state() + + +@pytest.mark.parametrize("form", ["import-single", "render-revert"]) +def test_a_stray_ways_out_commit_call_is_in_doubt_like_a_writers(pg, tmp_path, request, form): + """AT-D9's rows for `import --single <sha>` and `render --revert <sha>` + (TP:3607; TP:3639): on test 6's stray commit, F2 is armed at the commit + call's own send, after the command's snapshot has ended (TP:3586-3589), + so a missed snapshot's second request still reaches the cluster (lane + 1's cut, `refs/l1/R-rulings` 8121903), and the commit call meets the + silent relay: in doubt, as a writer's commit, then the lookup, whose + tries meet it too, and 3. The snapshot reached the cluster, a call met + the relay, and nothing was written; from the commit call's start, inside + twice the commit's F2 row's 35.5 s (`C` + `S` + `R` + `T_L` + `p`), and + no call begins after D7's 30 s deadline, at twice it. The stray sits on + the `cutover-done` estate, after the marker commit (T278e). It fails + until lane 1's L1-A14 and lane 3's T324 and T327 land, and until T326's + `_render_read_head` and T324's `_stray_recognised` agree on its values + (line BD15: on T326-m23 `552c22d4` both forms end 1, a traceback).""" + op = Operator(pg, tmp_path, request, "stray") + before = op.state() + relay = ArmedFault(f"{pg.host}/.s.PGSQL.{pg.port}", "F2", op.armed_for("commit_write")) + try: + proc, _ = op.run(op.argv("stray-commit", form), op.config("127.0.0.1", relay.port)) + finally: + relay.close() + assert proc.returncode == 3, f"{form}: {proc.returncode}: {_said_safely(proc.stderr)}" + assert any(c.get("snapshot") and c["exit"] == 0 for c in op.calls()), \ + f"{form}: the snapshot never reached the cluster: {op.calls()}" + assert relay.silenced, f"{form}: no call met F2 after the snapshot" + assert op.state()[:2] == before[:2], f"{form} wrote: {before} -> {op.state()}" + start = _faulted_start(op, "commit_write") + late = [round(b["begin"] - start, 2) for b in op.begins() if b["begin"] - start >= 2 * 30] + assert not late, f"{form}: calls began after the deadline: {late}" + elapsed = op.exited - start + assert elapsed < 2 * 35.5, f"{form}: {elapsed:.2f} s against 35.5 s" + _record(f"stray-{form}", elapsed, 35.5, "timing rule 2, from the commit call's start") + + +# ============================== no tool's or server log's text in pgcluster's failures (T257zza-T257zzf), no engine + +def _t257zza_seen(request, failed, planted: str) -> list: + """Where `planted` shows in a failure (T257zza; lane 3's ruling + 6949488277 on lane 2's pre-review RV9-38 of P09, B2): the exception's + `str`, `repr`, `args` and formatted traceback, and pytest's own report + of it, rendered through the running item as pytest renders a failed + test, `request.node.repr_failure(failed)`: its `str()` is what the + terminal and JUnit's failure body print, and its `reprcrash.message` is + JUnit's message. Each place that holds it is named; none is printed. + The report must name the exception's class, or the rendering is not + one. Under an explicit `--tb=long`, `--fulltrace` or `--showlocals` it + fails at once (`_short_only`; T257zzzh).""" + import traceback + _short_only(request) + report = request.node.repr_failure(failed) + crash = getattr(report, "reprcrash", None) + shown = {"str": str(failed.value), "repr": repr(failed.value), "args": repr(failed.value.args), + "traceback": "".join(traceback.format_exception(failed.type, failed.value, failed.tb)), + "report": str(report), "reprcrash": "" if crash is None else str(crash.message)} + assert failed.type.__name__ in shown["report"], "pytest's report of the failure was not rendered" + return sorted(name for name, text in shown.items() if planted in text) + + +def test_a_server_log_holding_a_roles_password_reaches_no_cluster_error_or_its_report( + monkeypatch, tmp_path, request): + """T257zza (lane 3's ruling 6949488277 on lane 2's pre-review RV9-38 of + P09, B2; T229l), with no engine and no process: under `log_statement = + 'all'` the server log holds a role's statement with its password, + planted here in `server.log` as `statement: CREATE ROLE ... PASSWORD + '<planted>'`. A start whose postmaster exits, a start not ready by the + deadline and a stop that outlasts it each raise a `ClusterError` that + shows the log's counts, and the planted value is in none of its `str`, + `repr`, `args` or formatted traceback, nor in pytest's report of it, as + the terminal and JUnit print it (`_t257zza_seen`). Before T229l each + held the log's last five lines. A log whose last lines name a bind sets + `could_not_bind`, which `TLSCluster.launch` now reads in place of the + text: it moves to a new port at a first start, three tries in all, and + raises at once on a restart. The planted value is no credential of any + login.""" + import pgcluster + planted = f"fake-{uuid.uuid4().hex}" + stamp = "2026-11-17 00:00:00.000 UTC [4242]" + logged = [f"{stamp} LOG: statement: CREATE ROLE lanes_w_t LOGIN PASSWORD '{planted}';", + f"{stamp} ERROR: role \"lanes_w_t\" already exists"] + bound = [f"{stamp} LOG: could not bind IPv4 address \"127.0.0.1\": Address already in use", + f"{stamp} FATAL: could not create any TCP/IP sockets"] + started = [] + + class Postmaster: + """A stand-in postmaster: `code` None runs on, else it has exited.""" + pid = 4242 + + def __init__(self, code): + self.returncode = code + + def poll(self): + return self.returncode + + def send_signal(self, sig): + pass + + def wait(self, timeout=None): + raise subprocess.TimeoutExpired(["postgres"], timeout) + + def popen(code): + def made(argv, **kw): + started.append(argv[0]) + return Postmaster(code) + return made + + monkeypatch.setattr(pgcluster, "DIE_WITH_PYTEST", False) + monkeypatch.setattr(pgcluster, "_free_port", lambda: 40000 + len(started)) + cluster = pgcluster.Cluster(tmp_path / "bin") + cluster.root = tmp_path + (tmp_path / "data").mkdir() + for lines, bind in ((logged, False), (logged + bound, True)): + (tmp_path / "server.log").write_text("\n".join(lines) + "\n", encoding="utf-8") + for case, code in (("exited", 1), ("not-ready", None)): + monkeypatch.setattr(pgcluster.subprocess, "Popen", popen(code)) + monkeypatch.setattr(pgcluster, "DEADLINE", -1.0 if code is None else 30.0) + with pytest.raises(pgcluster.ClusterError) as failed: + cluster.launch() + assert not _t257zza_seen(request, failed, planted), \ + f"{case}: the planted value shows in {_t257zza_seen(request, failed, planted)}" + assert (f"server.log: {len(lines)} line(s), {1 + bind} of them ERROR, FATAL or PANIC lines" + in str(failed.value)), f"{case}: the error shows no count of the log's lines" + assert getattr(failed.value, "could_not_bind", None) is bind, \ + f"{case}: could_not_bind is not {bind}" + cluster.proc = Postmaster(None) + with pytest.raises(pgcluster.ClusterError) as failed: + cluster.stop() + assert not _t257zza_seen(request, failed, planted), \ + f"stop: the planted value shows in {_t257zza_seen(request, failed, planted)}" + # TLSCluster.launch reads the flag: three tries at a first start, one at a restart. + monkeypatch.setattr(pgcluster.subprocess, "Popen", popen(1)) + monkeypatch.setattr(pgcluster, "DEADLINE", 30.0) + for restarting, tries in ((False, 3), (True, 1)): + tls = pgcluster.TLSCluster(tmp_path / "bin") + tls.root, tls.restarting, before = tmp_path, restarting, len(started) + with pytest.raises(pgcluster.ClusterError) as failed: + tls.launch() + assert len(started) - before == tries, \ + f"restarting={restarting}: {len(started) - before} start(s), not {tries}" + assert not _t257zza_seen(request, failed, planted), \ + f"restarting={restarting}: the planted value shows in {_t257zza_seen(request, failed, planted)}" + (tmp_path / "server.log").write_text("\n".join(logged) + "\n", encoding="utf-8") + tls = pgcluster.TLSCluster(tmp_path / "bin") + tls.root, before = tmp_path, len(started) + with pytest.raises(pgcluster.ClusterError): + tls.launch() + assert len(started) - before == 1, "a start that failed with no bind was tried again" + + +def _t257zzb_seen(request, failed, planted: str) -> list: + """`_t257zza_seen`'s places (T257zzb), for any failure pytest renders, + a `pytest.fail(..., pytrace=False)` among them, whose report is its + message alone: the exception's `str`, `repr`, `args` and formatted + traceback, and `request.node.repr_failure(failed)`'s `str()` (the + terminal's and JUnit's failure body) and `reprcrash.message` (JUnit's + message). The `reprcrash` must name the exception's class, or the + rendering is not one. Under an explicit `--tb=long`, `--fulltrace` or + `--showlocals` it fails at once (`_short_only`; T257zzzh).""" + import traceback + _short_only(request) + report = request.node.repr_failure(failed) + crash = getattr(report, "reprcrash", None) + message = "" if crash is None else str(crash.message) + assert failed.type.__name__ in message, "pytest's report of the failure was not rendered" + shown = {"str": str(failed.value), "repr": repr(failed.value), "args": repr(failed.value.args), + "traceback": "".join(traceback.format_exception(failed.type, failed.value, failed.tb)), + "report": str(report), "reprcrash": message} + return sorted(name for name, text in shown.items() if planted in text) + + +@pytest.mark.parametrize("kind", ["initdb", "bootstrap", "import", "lanes-edit", "git", "commit-id", + "openssl", "login-add", "tls-connect"]) +def test_a_failed_tools_cluster_error_in_pgcluster_shows_no_line_of_its_output( + monkeypatch, tmp_path, request, kind): + """T257zzb (lane 3's ruling 6949488277 on lane 2's pre-review RV9-38 of + P09, B2; T229m), with no engine and no process: each tool pgcluster + runs fails with a planted value on both its streams, subprocess.run or + the cluster's own runner being a stand-in, and the failure shows only + the exit and counts. The kinds: initdb in `start()`; `lanes-index + bootstrap`; `lanes-index import --at`, whose failure is + `imported_problem`, raised as `pg_imported` raises it; `lanes-edit.sh` + through `_run_ok`; git; `git rev-parse` printing no commit id (exit 0); + openssl; `lanes-index login add`, with a password-file line among its + output; and the TLS smoke's verify-full connect. The planted value is + in none of the failure's `str`, `repr`, `args` or formatted traceback, + nor in pytest's report of it (`_t257zzb_seen`). Before T229m each + showed the tool's text. The planted value is no credential of any + login.""" + import pgcluster + planted = f"fake-{uuid.uuid4().hex}" + said_on = (f"{planted} on stdout\n", f"{kind}: {planted} on stderr\n") + + def ran(code=1, answer=None): + def run(argv, **kw): + lines = said_on if answer is None else (answer, "") + if not kw.get("text"): + lines = tuple(part.encode() for part in lines) + return subprocess.CompletedProcess(argv, code, *lines) + return run + + monkeypatch.setattr(pgcluster, "_IMPORTED", []) + cluster = pgcluster.Cluster(tmp_path / "bin") + cluster.root = tmp_path + register = object.__new__(pgcluster.ImportedRegister) + register.root, register.wip, register.env = tmp_path, tmp_path, {} + kinds = pgcluster.ClusterError + if kind == "initdb": + root = tmp_path / "root" + root.mkdir() + cluster.root = None + monkeypatch.setattr(pgcluster, "sweep_stale", lambda: []) + monkeypatch.setattr(pgcluster.tempfile, "mkdtemp", lambda **kw: str(root)) + monkeypatch.setattr(pgcluster, "SOCKET_MAX", 1 << 20) + monkeypatch.setattr(pgcluster.subprocess, "run", ran()) + call = cluster.start + elif kind == "bootstrap": + monkeypatch.setattr(cluster, "lanes_index", lambda argv: ran()(argv, text=True)) + call = lambda: cluster.bootstrap(pgcluster.TEMPLATE, pgcluster.FX_LABEL) # noqa: E731 + elif kind == "import": + class Register: + def __init__(self, root, bindir): + self.c = "0" * 40 + + def import_at(self, cluster, database, user): + return ran()(["lanes-index", "import"], text=True) + cluster.label = pgcluster.FX_LABEL + monkeypatch.setattr(pgcluster, "ImportedRegister", Register) + monkeypatch.setattr(cluster, "psql", lambda *a, **kw: subprocess.CompletedProcess(a, 0, "", "")) + monkeypatch.setattr(cluster, "drop_database", lambda name: None) + + def call(): + cluster.build_imported() + # `pg_imported`'s own words, where the session has no tmpl_imported + pytest.fail(f"no {pgcluster.IMPORTED} on the session cluster, so this case cannot " + f"clone it: {cluster.imported_problem}", pytrace=False) + kinds = pytest.fail.Exception + elif kind == "lanes-edit": + monkeypatch.setattr(pgcluster.subprocess, "run", ran()) + call = lambda: register._run_ok(["bash", "lanes-edit.sh", "log"]) # noqa: E731 + elif kind == "git": + monkeypatch.setattr(pgcluster.subprocess, "run", ran(code=128)) + call = lambda: register.git("push", "-q", "origin", "main") # noqa: E731 + elif kind == "commit-id": + monkeypatch.setattr(pgcluster.subprocess, "run", ran(code=0, answer=planted)) + call = lambda: register.commit_of("origin/main") # noqa: E731 + elif kind == "openssl": + monkeypatch.setattr(pgcluster.subprocess, "run", ran()) + call = lambda: pgcluster._openssl(["req", "-x509"], tmp_path) # noqa: E731 + elif kind == "login-add": + line = f"*:*:{pgcluster.TEMPLATE}:{pgcluster.FX_WRITER}:{planted}\n" + monkeypatch.setattr(cluster, "lanes_index_tty", + lambda argv: (1, line + said_on[0], said_on[1])) + call = lambda: cluster.make_logins(pgcluster.TEMPLATE) # noqa: E731 + else: + class Found: + bindir = tmp_path / "bin" + + def connect(argv, **kw): + failing = any("pg_stat_ssl" in part for part in argv) + return ran(code=2 if failing else 0, answer=None if failing else "")(argv, text=True) + monkeypatch.setattr(pgcluster.TLSCluster, "start", lambda self: None) + monkeypatch.setattr(pgcluster.TLSCluster, "client_env", lambda self, *a, **kw: {}) + monkeypatch.setattr(pgcluster.TLSCluster, "destroy", lambda self: None) + monkeypatch.setattr(pgcluster.subprocess, "run", connect) + call = lambda: pgcluster._smoke_tls(Found()) # noqa: E731 + with pytest.raises(kinds) as failed: + call() + assert not _t257zzb_seen(request, failed, planted), \ + f"{kind}: the planted value shows in {_t257zzb_seen(request, failed, planted)}" + assert "line(s)" in str(failed.value), f"{kind}: the failure shows no count of lines" + + +@pytest.mark.parametrize("kind", ["select-1", "standby-answer", "standby-failed", "imported-check"]) +def test_a_psql_answer_pgcluster_did_not_expect_is_counted_never_quoted( + monkeypatch, tmp_path, request, kind): + """T257zzc (lane 3's ruling 6949488277 on lane 2's pre-review RV9-38 of + P09, B2, `{said!r}` at pgcluster :845 and :1899; T229n), with no engine + and no process: psql, run by `Cluster.psql` with subprocess.run a + stand-in, answers with a planted value where pgcluster expects a fixed + answer: `SELECT 1` in the smokes' `_select_1`; `pg_is_in_recovery()` in + `start_again(standby=True)`, once on stdout and once failing with it + on stderr, the server log holding a role's statement with the planted + password too; and `_imported_check`'s journal|head|switch, raised as + `pg_imported` raises `imported_problem`. The planted value is in none + of the failure's `str`, `repr`, `args` or formatted traceback, nor in + pytest's report of it (`_t257zzb_seen`). Before T229n each quoted the + answer. The planted value is no credential of any login.""" + import pgcluster + planted = f"fake-{uuid.uuid4().hex}" + + class Postmaster: + pid, returncode = 4242, None + + def poll(self): + return None + + def answers(code, said, told=""): + return lambda argv, **kw: subprocess.CompletedProcess(argv, code, said, told) + + monkeypatch.setattr(pgcluster, "DIE_WITH_PYTEST", False) + cluster = pgcluster.Cluster(tmp_path / "bin") + cluster.root = tmp_path + (tmp_path / "data").mkdir() + (tmp_path / "data" / "postmaster.pid").write_text( + "\n".join(["4242", str(tmp_path / "data"), "0", "5432", str(tmp_path), "*", "0", "ready"]) + + "\n", encoding="utf-8") + (tmp_path / "server.log").write_text( + f"LOG: statement: ALTER ROLE lanes_w_t PASSWORD '{planted}';\n", encoding="utf-8") + monkeypatch.setattr(pgcluster.subprocess, "Popen", lambda argv, **kw: Postmaster()) + kinds = pgcluster.ClusterError + if kind == "select-1": + monkeypatch.setattr(pgcluster.subprocess, "run", answers(0, f"{planted}\n")) + call = lambda: pgcluster._select_1(cluster) # noqa: E731 + elif kind == "standby-answer": + monkeypatch.setattr(pgcluster.subprocess, "run", answers(0, f"{planted}\n")) + call = lambda: cluster.start_again(standby=True) # noqa: E731 + elif kind == "standby-failed": + monkeypatch.setattr(pgcluster.subprocess, "run", + answers(2, "", f"psql: error: {planted}\nLINE 1: {planted}\n")) + call = lambda: cluster.start_again(standby=True) # noqa: E731 + else: + monkeypatch.setattr(pgcluster.subprocess, "run", + answers(0, f"0:import:{planted}|0|files:absent\n")) + + def call(): + problem = cluster._imported_check("0" * 40) + # `pg_imported`'s own words, where the session has no tmpl_imported + pytest.fail(f"no {pgcluster.IMPORTED} on the session cluster, so this case cannot " + f"clone it: {problem}", pytrace=False) + kinds = pytest.fail.Exception + with pytest.raises(kinds) as failed: + call() + assert not _t257zzb_seen(request, failed, planted), \ + f"{kind}: the planted value shows in {_t257zzb_seen(request, failed, planted)}" + + +@pytest.mark.parametrize("kind", ["version", "pg-config"]) +def test_the_engine_probes_problem_shows_no_text_a_tool_printed(monkeypatch, tmp_path, request, kind): + """T257zzd (lane 3's ruling 6949488277 on lane 2's pre-review RV9-38 of + P09, B2; T229o), with no engine and no process: the probe that finds + the binaries (`Probe`) meets a tool whose output holds a planted value, + subprocess.run a stand-in. `[version]`: `PG_BIN` names a directory of + the four tools, whose `--version` names another major beside the + planted value. `[pg-config]`: `PG_BIN` unset, the only `pg_config` on + `PATH` prints a directory named by the planted value. The problem, + failed as `pg_engine` fails it under the switch, holds `real + PostgreSQL 16`, `PG_BIN` and the package's name, as the fixture's tests + and the gate read them, and the planted value is in none of the + failure's `str`, `repr`, `args` or formatted traceback, nor in pytest's + report of it (`_t257zzb_seen`). Before T229o the problem quoted the + `--version` line and printed `pg_config`'s output twice. The planted + value is no credential of any login.""" + import pgcluster + planted = f"fake-{uuid.uuid4().hex}" + tools = tmp_path / "bin" + tools.mkdir() + for name in pgcluster.TOOLS + ("pg_config",): + (tools / name).write_text("#!/bin/sh\nexit 0\n", encoding="utf-8") + (tools / name).chmod(0o755) + + def run(argv, **kw): + said = (f"/nonexistent/{planted}\n" if argv[-1] == "--bindir" else + f"{Path(argv[0]).name} {planted} (PostgreSQL) {pgcluster.MAJOR - 1}.4\n") + return subprocess.CompletedProcess(argv, 0, said, "") + + monkeypatch.setattr(pgcluster.subprocess, "run", run) + if kind == "version": + monkeypatch.setenv("PG_BIN", str(tools)) + else: + monkeypatch.delenv("PG_BIN", raising=False) + monkeypatch.setenv("PATH", str(tools)) + found = pgcluster.Probe() + assert found.bindir is None and found.problem, f"{kind}: the probe found binaries" + for word in (pgcluster.SKIP_TAG, "PG_BIN", pgcluster.PACKAGE): + assert word in found.problem, f"{kind}: the problem does not say {word}" + with pytest.raises(pytest.fail.Exception) as failed: + pytest.fail(found.problem, pytrace=False) # `pg_engine`'s, under the switch + assert not _t257zzb_seen(request, failed, planted), \ + f"{kind}: the planted value shows in {_t257zzb_seen(request, failed, planted)}" + + +@pytest.mark.parametrize("form", ["five-capitals", "across-a-newline", "verbose"]) +def test_a_failed_psqls_sqlstate_is_taken_only_from_its_verbose_form_on_one_line( + monkeypatch, request, form): + """T257zze (lane 2's pre-review RV9-38 of P09, N1; lane 3's ruling + 6949488277, "`_SQLSTATE`'s pattern made strict"; T229p), with no engine + and no process: psql, run by `Cluster.psql` with subprocess.run a + stand-in, exits 3. `[five-capitals]`, RV9-38's F2 `fiveupper` case: + its message's first word is five capitals and a colon (`ERROR: + <word>: ...`). `[across-a-newline]`: an `ERROR:` line ends, and the + next line begins with five of `[0-9A-Z]`, a digit among them, and a + colon, at once and after psql's own prefix. Neither word is shown, as + a SQLSTATE or at all, and the error says "no SQLSTATE in its text". + `[verbose]`: psql's real verbose form, `ERROR: 42601: ...` after its + prefix and `ERROR:<tab>42P01: ...`, shows SQLSTATE 42601 and 42P01, + and the planted value echoed on a `LINE 1:` is shown nowhere. Each is + checked in the error's `str`, `repr`, `args` and formatted traceback, + and in pytest's report of it (`_t257zzb_seen`). Each word is drawn at + run time, and drawn again while any source or path a report prints + holds it (T257zzzb; lane 2's pre-review RV9-41 of P09, N2), so only + the error can show it. The planted value is no credential of any + login.""" + import pgcluster + # T257zzzb: the letters by their code points, so no run of them is in any + # source; and a word is drawn again while this module's or pgcluster's + # source or path, or the working directory, holds it. + letters = [chr(code) for code in (74, 75, 81, 86, 87, 88, 90)] + printed = "\n".join([Path(__file__).read_text(encoding="utf-8"), + Path(pgcluster.__file__).read_text(encoding="utf-8"), + str(Path(__file__).resolve()), str(Path(pgcluster.__file__).resolve()), + os.getcwd()]) + + def drawn(size: int, digit: bool) -> str: + while True: + candidate = "".join(letters[b % 7] for b in os.urandom(size)) + candidate += str(os.urandom(1)[0] % 10) if digit else "" + if candidate not in printed: + return candidate + word, coded = drawn(5, False), drawn(4, True) + planted = f"fake-{uuid.uuid4().hex}" + told, state, hidden = { + "five-capitals": (f"ERROR: {word}: a planted head\n", "no SQLSTATE in its text", word), + "across-a-newline": (f"ERROR:\n{coded}: a planted line\npsql:<stdin>:2: ERROR: \n" + f"{coded}: again\n", "no SQLSTATE in its text", coded), + "verbose": (f"psql:<stdin>:1: ERROR: 42601: syntax error at or near \"x\"\n" + f"LINE 1: ALTER ROLE r PASSWORD '{planted}' x;\nERROR:\t42P01: relation " + f"\"t\" does not exist\n", "SQLSTATE 42601, 42P01", planted), + }[form] + cluster = pgcluster.Cluster(Path("/nonexistent/bin")) + cluster.root = Path("/nonexistent") + monkeypatch.setattr(pgcluster.subprocess, "run", + lambda argv, **kw: subprocess.CompletedProcess(argv, 3, "", told)) + with pytest.raises(pgcluster.ClusterError) as failed: + cluster.psql("SELECT 1", dbname="register", user="lanes_admin") + assert not _t257zzb_seen(request, failed, hidden), \ + f"{form}: the planted word shows in {_t257zzb_seen(request, failed, hidden)}" + assert str(failed.value).startswith(f"psql as lanes_admin on register exited 3: {state}; "), \ + f"{form}: the error does not say {state}" + + +def test_a_failed_psqls_raising_frame_keeps_no_stream_of_its_run(monkeypatch, request): + """T257zzf (lane 2's pre-review RV9-38 of P09, N2; T229q), with no + engine and no process: psql, run by `Cluster.psql` with subprocess.run + a stand-in, exits 3 with a planted value on both its streams. The + `ClusterError`'s traceback keeps each frame it passed through, and + pytest prints a frame's locals under `--showlocals`; no local of any + frame of pgcluster's in it holds the planted value, nor does its + `str`, `repr`, `args`, formatted traceback, or pytest's report of it + (`_t257zzb_seen`). Before T229q the raising frame kept psql's run as + `proc`, its stdout and stderr with it. `sql`, the frame's argument, + is the caller's own, here `SELECT 1`. The planted value is no + credential of any login.""" + import pgcluster + planted = f"fake-{uuid.uuid4().hex}" + cluster = pgcluster.Cluster(Path("/nonexistent/bin")) + cluster.root = Path("/nonexistent") + monkeypatch.setattr(pgcluster.subprocess, "run", lambda argv, **kw: subprocess.CompletedProcess( + argv, 3, f"{planted}\n", f"psql:<stdin>:1: ERROR: 42601: x\nLINE 1: {planted}\n")) + with pytest.raises(pgcluster.ClusterError) as failed: + cluster.psql("SELECT 1", dbname="register", user="lanes_admin") + assert not _t257zzb_seen(request, failed, planted), \ + f"the planted value shows in {_t257zzb_seen(request, failed, planted)}" + ours, held = 0, [] + tb = failed.tb + while tb is not None: + frame = tb.tb_frame + if Path(frame.f_code.co_filename).resolve() == Path(pgcluster.__file__).resolve(): + ours += 1 + held += [f"{frame.f_code.co_name}.{name}" for name, value in frame.f_locals.items() + if planted in repr(value)] + tb = tb.tb_next + assert ours, "no frame of pgcluster's is in the error's traceback" + assert not held, f"a frame of pgcluster's keeps the planted value in: {held}" + + +@pytest.mark.parametrize("path", ["started", "from-lanes-edit", "from-git"]) +def test_a_chained_pgcluster_failure_shows_no_tool_text_in_pytests_report( + monkeypatch, tmp_path, request, path): + """T257zzza (lane 2's pre-review RV9-41 of P09 at `4895579`, S1, and its + B1; lane 3's ruling 6949488277; the coordinator's 6949514036 asks for + chained-exception cases), with no engine and no process: a failing + tool's two streams hold a planted value, and the failure reaches + pytest's report chained, as the fixtures' real paths chain it. + `[started]`: initdb fails in `_started`, which the cluster fixtures + call, and whose `pytest.fail(..., pytrace=False)`, raised in its + `except`, carries the `ClusterError` as its implicit context, which + pytest prints. `[from-lanes-edit]` and `[from-git]`: + `ImportedRegister._run_ok`'s and `.git`'s `ClusterError`, wrapped as + disaster's and drill's estates wrap it, `raise AssertionError(...) + from exc`. The chain is checked to be there, and to be rendered: the + report holds pytest's block for that very link ("During handling of + the above exception" for `__context__`, "The above exception was the + direct cause" for `__cause__`), and before it the chained error's own + text and, for a cause, the file and line of the last entry of its own + traceback, as each style prints it (T257zzzi; lane 2's targeted check RV9-43 of P09 at + `94a40564`, NIT A: before, the error's first words were looked for + anywhere in the report, where the message's own `{exc}` put them, so a + severed chain passed). And the planted value is in neither the + error's `str`, `repr` or `args` nor in pytest's report, + rendered by `_reported` under the suite's own style, the JUnit message + included. Before T229t, under pytest 8.3.4 with long tracebacks, the + cause's last entry printed `_run_ok`'s and `git`'s `proc`. The planted + value is no credential of any login.""" + import pgcluster + planted = f"fake-{uuid.uuid4().hex}" + + def run(argv, **kw): + lines = (f"{planted} on stdout\n", f"{path}: {planted} on stderr\n") + if not kw.get("text"): + lines = tuple(part.encode() for part in lines) + return subprocess.CompletedProcess(argv, 1, *lines) + + monkeypatch.setattr(pgcluster.subprocess, "run", run) + if path == "started": + class Found: + bindir, how = tmp_path / "bin", "a stand-in" + root = tmp_path / "root" + root.mkdir() + monkeypatch.setattr(pgcluster, "sweep_stale", lambda: []) + monkeypatch.setattr(pgcluster.tempfile, "mkdtemp", lambda **kw: str(root)) + monkeypatch.setattr(pgcluster, "SOCKET_MAX", 1 << 20) + with pytest.raises(pytest.fail.Exception) as failed: + pgcluster._started(Found(), "") + chained = failed.value.__context__ + else: + register = object.__new__(pgcluster.ImportedRegister) + register.root, register.wip, register.env = tmp_path, tmp_path, {} + with pytest.raises(AssertionError) as failed: + try: + if path == "from-lanes-edit": + register._run_ok(["bash", "lanes-edit.sh", "log"]) + else: + register.git("push", "-q", "origin", "main") + except pgcluster.ClusterError as exc: + raise AssertionError(f"[B] the estate's register was not built: {exc}") from exc + chained = failed.value.__cause__ + assert isinstance(chained, pgcluster.ClusterError), f"{path}: no ClusterError is chained" + said = _reported(request, failed) + link = ("During handling of the above exception" if path == "started" else + "The above exception was the direct cause") + assert link in said, f"{path}: pytest's report renders no chained error" + before = said.split(link, 1)[0] + # A pytrace=False failure's chain is rendered as each error's text alone, with no class. + assert str(chained).splitlines()[0] in before, f"{path}: the chain rendered is not the chained error's" + if path != "started": + last = chained.__traceback__ + while last.tb_next is not None: + last = last.tb_next + entry = f"{Path(last.tb_frame.f_code.co_filename).name}:{last.tb_lineno}: " + assert entry in before, f"{path}: the chain rendered does not end where the chained error was raised" + shown = [name for name, text in (("str", str(failed.value)), ("repr", repr(failed.value)), + ("args", repr(failed.value.args)), ("report", said)) + if planted in text] + assert not shown, f"{path}: the planted value shows in {shown}" + + +@pytest.mark.parametrize("site", ["run-ok", "git", "make-logins", "make-logins-then-psql"]) +def test_a_failed_tools_raising_frame_in_pgcluster_keeps_no_text_of_its_run(monkeypatch, tmp_path, site): + """T257zzzj (lane 2's targeted check RV9-43 of P09 at `94a40564`, NIT + B; T229t; T229u), with no engine and no process: a tool's run fails + with a planted value on both its streams, in `ImportedRegister._run_ok` + (`[run-ok]`) and `.git` (`[git]`), whose run is a stand-in of + subprocess.run, and in `Cluster.make_logins` (`[make-logins]`), whose + `login add` under the pty is a stand-in. The `ClusterError`'s + traceback, walked frame by frame, holds the planted value in no local + of any frame of pgcluster's, whatever the traceback style: pytest + 8.3.4 prints a long entry's locals as the arguments of `_run_ok`'s + `**env` and `git`'s `*args`, and every style but short prints frames' + arguments, `--showlocals` their locals. `[make-logins-then-psql]` + (T257zzzl; lane 2's targeted check RV9-44 of P09 at `3faf9453`, S-1): + `login add` succeeds, printing the planted value, and the psql that + follows in `make_logins` raises, so its frame is walked past T229u's + `del` after a successful `login add`, not only past the one before + its own raise. Under the suite's short style + T257zzza's and T257zzb's cases pass with T229t undone; this one does + not. Before T229t `_run_ok` and `git` kept the run as `proc`; before + T229u `make_logins` kept `login add`'s `out` and `err`, its printed + password lines among them. The planted value is no credential of any + login.""" + import pgcluster + planted = f"fake-{uuid.uuid4().hex}" + + def run(argv, **kw): + lines = (f"{planted} on stdout\n", f"{site}: {planted} on stderr\n") + if not kw.get("text"): + lines = tuple(part.encode() for part in lines) + return subprocess.CompletedProcess(argv, 1, *lines) + + monkeypatch.setattr(pgcluster.subprocess, "run", run) + with pytest.raises(pgcluster.ClusterError) as failed: + if site == "make-logins": + cluster = object.__new__(pgcluster.Cluster) + cluster.passwords = {} + monkeypatch.setattr(cluster, "admin_service", lambda database: f"fx_{database}") + monkeypatch.setattr(cluster, "lanes_index_tty", lambda argv: ( + 1, f"{planted} printed\n", f"{site}: {planted} on stderr\n")) + cluster.make_logins("register") + elif site == "make-logins-then-psql": + cluster = object.__new__(pgcluster.Cluster) + cluster.passwords = {} + + def psql(sql, **kwargs): + raise pgcluster.ClusterError("psql as postgres on register exited 2: a stand-in") + monkeypatch.setattr(cluster, "admin_service", lambda database: f"fx_{database}") + monkeypatch.setattr(cluster, "lanes_index_tty", lambda argv: ( + 0, f"{planted} printed\n", f"{site}: {planted} on stderr\n")) + monkeypatch.setattr(cluster, "psql", psql) + cluster.make_logins("register") + else: + register = object.__new__(pgcluster.ImportedRegister) + register.root, register.wip, register.env = tmp_path, tmp_path, {} + if site == "run-ok": + register._run_ok(["bash", "lanes-edit.sh", "log"]) + else: + register.git("push", "-q", "origin", "main") + ours, held = [], [] + tb = failed.tb + while tb is not None: + frame = tb.tb_frame + if Path(frame.f_code.co_filename).resolve() == Path(pgcluster.__file__).resolve(): + ours.append(frame.f_code.co_name) + held += [f"{frame.f_code.co_name}.{name}" for name, value in frame.f_locals.items() + if planted in repr(value)] + tb = tb.tb_next + want = {"run-ok": "_run_ok", "git": "git", "make-logins": "make_logins", + "make-logins-then-psql": "make_logins"}[site] + assert want in ours, f"{site}: {want} is not in the error's traceback, only {ours}" + assert not held, f"{site}: a frame of pgcluster's keeps the planted value in: {held}" + assert planted not in str(failed.value), f"{site}: the planted value is in the error's text" + + +@pytest.mark.parametrize("prefix", ["none", "default", "pid"]) +def test_a_server_logs_severe_lines_are_counted_under_each_prefix_the_fixture_uses(tmp_path, prefix): + """T257zzzk (lane 2's targeted check RV9-43 of P09 at `94a40564`, NIT + C; T229v; T229x), with no engine and no process: `Cluster.log_tail` + counts a server log's lines at ERROR, FATAL or PANIC, and shows none of + them, under each `log_line_prefix` the fixture's clusters write: none, + the default `%m [%p] ` (`[default]`), and `%p ` (`[pid]`), which + managed sets on its clusters. The planted log has 7 lines, 4 of them + truly severe (ERROR, FATAL, PANIC, and a verbose `ERROR: 42601:`); a + logged statement holding `ERROR: `, a `STATEMENT:` echo of a role's + password and a connection line are not. Before T229x a `%p ` line was + never counted. The planted value is no credential of any login.""" + import pgcluster + planted = f"fake-{uuid.uuid4().hex}" + lead = {"none": "", "default": "2026-11-17 14:48:04.123 UTC [1234] ", "pid": "1234 "}[prefix] + lines = [f"LOG: statement: SELECT 'ERROR: {planted}'", "ERROR: relation \"t\" does not exist", + f"STATEMENT: ALTER ROLE r PASSWORD '{planted}'", + "FATAL: password authentication failed for user \"x\"", + "LOG: connection received: host=[local]", "PANIC: could not write to file", + "ERROR: 42601: syntax error at or near \"x\""] + (tmp_path / "server.log").write_text("".join(f"{lead}{line}\n" for line in lines), encoding="utf-8") + cluster = object.__new__(pgcluster.Cluster) + cluster.root = tmp_path + said = cluster.log_tail() + assert planted not in said, f"[{prefix}] the planted value is in log_tail's text" + assert said == ("server.log: 7 line(s), 4 of them ERROR, FATAL or PANIC lines; no line of it " + "is shown"), f"[{prefix}] log_tail says: {said}" diff --git a/tests/test_sql_register_disaster.py b/tests/test_sql_register_disaster.py new file mode 100644 index 00000000..2db542b2 --- /dev/null +++ b/tests/test_sql_register_disaster.py @@ -0,0 +1,1629 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Feature 007's D22 and AT-F18: the disaster path (L2-G4; L2-G5's AT-F18; +AT-D22; AT-F18; T274; FR-053, FR-059) (opensoft/openRepoTools#165). + +T274 writes this module: 12 tests, AT-D22's 6 and AT-F18's 6 (B15 tasks:2511, +"Write D22 and AT-F18, the disaster path"). The test plan's AT-F18 gives the +label rules' test four ids, `[no-label-reimport]`, `[no-label-restore]`, +`[own-label-at-primary]` and `[reimport-at-files]`, so T274's verify, which +names that function bare, collects 15 ids from the 12 tests. + +THE ESTATE, `Disaster` (the test plan's AT-D22, "Fixture"): + +- CLUSTER A, the live database: section 5.6's TLS cluster, T229's + `tls_cluster`, stoppable, with SCRAM on loopback. The register is a database + of its own on it, made empty and bootstrapped through the admin service with + `--label register-a` (`TLSCluster.second_database`). The engineer `ds`'s two + logins are made on it by `lanes-index login add ds` under a pty; the dump + login, `lanes_register_dump`, is the one T228's `login add --dump-job` made + on the same cluster when its template was built. +- A BARE ORIGIN WITH THE FIXTURE REGISTER, test 7's (pgcluster's + `ImportedRegister`, T227b). Its operator checkout, with its W and + `workspace.yaml`, is ws1's: the operator lane `repoA-2` on `Eagle` (F12). +- WS1'S TOOLS AND CONFIGURATION, as test 13's drill has them: T203's flipped + `lanes-index` (`RENDER_GIT_HALF = True`), `lanes-edit.sh`, `lanes`, + `lane-start` and `repos.tsv` beside it, check 1's digest list, and a 0600 + `lanes-index.conf` naming `ds`'s two logins over `verify-full` with their + password files, `register_label=` and `register_addresses=1`. In front of + them on `PATH`: test 5's `git` wrapper, which fails each `fetch`, or the + push of the commit carrying one `Register-Seq`, when armed, and section + 3.2's `psql` shim, which logs every request. +- THE OPERATOR LANE'S OWN REGISTER CHECKOUT, `<c>`, `<W>-lanes/repoA-2/`, W + being `ro/wip`, the path `workspace.yaml` names: a clone of the origin, + made with ws1 before A's first write, as `lane-checkout repoA-2 --create` + makes one (the writes module's `make_lane_checkout`, T241e). On primary a + write refuses with 2 where it is missing (lane 4's T415; tasks:1154). + Every operator command runs "through its checkout" (AT-D22's fixture; + design.md S5, "`<W>-lanes/<operator lane>/`"), and the loss is the + database's, not the host's: the re-pointing is one edit of the + configuration alone (AT-D22's fixture; S5's disaster path, step 5). So the + `<c>` made before the loss serves every write on B too. +- A WRITTEN THROUGH `m`, THEN `k`: the import at C (T115) and the first + cutover (T116, T327) from ws1, `set-mode primary` (T120), then writes on + primary from ws1, `log NOTED` (lane 4's T415), each forking its render (lane + 4's T416; lane 3's T321 to T323). The first `RENDERED` writes reach origin, + so `m` is the mirror's last `Register-Seq`. The wrapper then fails every + `fetch`, and the next writes are each waited for by the renderer's exit + (open point 8's second wait: a failed `fetch` logged, then a free + `lanes-render.lock`), so `k` is the head and `status` shows a lag of + `k - m`. The restore branch's backup is taken between them, at `b`. +- THE BACKUP (act 3's daily dump): O2's command, `pg_dump --format=custom` of + both schemas as `lanes_register_dump` over TLS, its password file from its + environment; `b` is read from the file alone by `pg_restore --data-only + --schema=lanes_register --table=register_head --file=-`. `pg_dump` and + `pg_restore` are the fixture's, from its binaries' directory (open point 15). +- THE LOSS: `status` reads A at `k` (recording `h`), A is stopped, `status` + prints `m` and `h`, the outage is declared on ws1 (D20), and A is destroyed. +- CLUSTER B, the replacement: a TLS cluster of the test's own whose template + holds nothing, so no register role exists on it; its one database stands + for the one the admin creates first (R-P41). One admin service naming it + serves every step (R1's S4): `bootstrap --roles-only`, then for the + re-import `bootstrap --label register-b` and `login add ds` and `login add + --dump-job`; for the restore `login add` for both, `pg_restore + --exit-on-error --no-password` through the service, then `bootstrap + --label register-b`, which prints `unchanged`. +- THE RE-POINTING (F18): ws1's configuration is rewritten in one edit, + `register_url=`, `reader_url=`, their password files and + `register_label=`, B's, before any `lanes-index` command of ws1's reaches + B. A second configuration that still reaches A keeps A's label: the host + not yet re-pointed. + +WHAT EACH FAILS UNTIL. B15's Order (tasks:2511's last bullet): it waits for +T205, and its tests fail until L1-A7, L1-A13 and T327 land. Each labelled +assertion also names the tasks its own commands rest on: `bootstrap` and +`--roles-only` (T109, L1-A7); `login` (T110); `import --at` and `--after-loss` +(T115, L1-A13); `cutover` in its three forms (T116, L1-A14) and its marker's +push, read-back, `record_marker`, the restore form's render and the abort's +trigger (lane 3's T327); `set-mode` (T120); `status`'s two seqs (T117) and the +declaration (T121, L1-A18); `ready`'s check 10 (T119); a write on primary +(lane 4's T415) and its render's fork (T416), rendered by lane 3's T321 to +T323; the pending record, its generation and exit 3's printed rerun (lane 4's +T412 and T417); the rollback (T304, lane 3's T326). The label rules (direct +calls, T107) and `--roles-only` (T109) rest on nothing else, and can pass on +line R now. The host still on the live database needs A at `primary` with the +marker `present`, so T327 alone. + +READINGS, NOT FOUND IN A CONTRACT: +- WHICH ESTATE EACH RUNS. The re-import, the restore, the abort, `status` and + the restore route's label run A through `m` and `k`. The host still on the + live database runs on A at `primary` just after the cutover: its oracle reads + no lag. AT-F18's four estate cases run D22's re-import with A written + through `m` and then the write in doubt at `m`, with no lost tail after it, + since their oracles read only the record and B's generation. +- THE PENDING RECORD "for a write at a seq up to `m`" is a write whose commit + call is lost before COMMIT (the shim's `no-reconnect` arm, `as: before`, as + T244's `exit3` makes one): it ends 3 with its record kept and its printed + rerun, at head `m`, and its effect is on neither A nor the mirror, so B's + effect check finds it absent. +- "LR007'S TEXT" is read as naming the write id and both generations, as + `commit_write`'s LR007 message does ("write <id> belongs to register + generation <A>, not <B>"). +- "A PLAIN RERUN AFTER IT FINDS NO RECORD OF A'S": the same command with no + variable, after the replacement's write, is not refused for A's record: it + exits 0, names neither A's id nor A's generation, and journals a write of its + own. +- THE ABORT'S DUMP orders each of the twelve tables by its primary key's + columns, as `pg_index` gives them, and holds each row as `to_jsonb` prints + it. `stderr`'s first line naming the abort is read as carrying "abort". +- `STATUS` AT A IS READ BY ITS REGISTER LINES, NOT ITS EXIT. The test plan + gives it no exit ("`status` shows a lag of `k - m`"; "`status` reads A at + `k`, recording `h`"). Its exit is #160's index's as well, and ws1 syncs no + index, so it is 1 there (`index: missing`) while it reads A. So A's lag + line, or its `n` at `k`, is the oracle, with 69, the register unread, + refused; with A stopped it is 69, as the loss asserts. +- `bootstrap` on B runs with `--no-passwords`: no password of the indexer's + is under test here, and the logins' are `login add`'s (as pgcluster's own + bootstrap runs). + +HELPERS COPIED, NEVER SHARED (a module's own): the drill's `Workstation` +form, `_rows`, `_renders`, `RENDER_SET`, `REGISTER_SEQ`, `LAG_0`, `CHECK_LINE`, +`_checks`, `mirror_problem` and `wait_for_seq` from T276's +`test_sql_register_drill.py` (line DR's `ca9b1a3a`); test 5's `git` wrapper +from T273b's `GIT_WRAPPER` (`test_sql_register_rollback.py`, this base), with +a `fail` arm and a push arm added; AT-LR006's entries (`_entry` and its +kinds) from T273's `RollbackRegister`; `exit3`'s arm, the record's path and +the rerun's two patterns from T244's `test_sql_register_in_doubt.py` (line +ID's `3965033`); O2's `DUMP_COMMAND`, the object lines and the three +database-level checks of `dump_restore_privileges` from T224's +`test_sql_register_managed.py` (line MG). From the fixture and H's helpers, +which each real-engine module imports: `tls_cluster`, `pg`, `TLSCluster`, +`ImportedRegister`, `PASSWORD_LINE`, `ClusterError`, `PSQL_SHIM`, +`flipped_copy` and `guard_strip_env`. + +THE PATH (wave 11's policy, mask and never drop): no call here drops a `PATH` +directory. ws1 puts its fake `tmux`, the wrapper and the shim, its tools and +the engine's binaries first, and keeps every inherited directory behind them. + +Every wait here has a ceiling: each poll, `SETTLE_S`; each command, its +`timeout`. Every id is RE: without PostgreSQL 16 it skips with T205's banner. +""" + +from __future__ import annotations + +import base64 +import fcntl +import hashlib +import json +import os +import re +import shutil +import subprocess +import sys +import time +import uuid +from pathlib import Path + +import pytest + +from conftest import REPO, WINDOWS_SKIP +from pgcluster import (FX_DUMP, FX_LANE, FX_REPOSITORY, PASSWORD_LINE, SUPERUSER, ClusterError, + Database, ImportedRegister, TLSCluster) +from sql_register_helpers import (PSQL_SHIM, PSQL_SHIM_CONTROL, PSQL_SHIM_LOG, flipped_copy, + guard_strip_env) + +#: THE LANDING GATE'S TABLE (T280's reader, `tests/sql_register_gate.py`), TEMPORARY: +#: T281 removes it in the last set. Where the gate is active, an id is skipped until +#: every task its rows name has landed: the `"*"` row holds for every id of the module, +#: and a function's row adds to it for each of that function's ids. Each row is the +#: fails-until clause of T274's **Order** (tasks:2521 at lane 3's commit 17, 204145ae), +#: each lane 1 label read as the tasks it covers. `"*"` is T109, which every case waits +#: for; the label rules' four ids, by direct calls, add T107 alone; and +#: `test_bootstrap_roles_only_makes_the_roles_and_no_schema` has no row of its own, +#: since it waits only for T109. +SQL_REGISTER_GATE_TABLE = { + "*": ("T109",), # every id: the tasks all its rows share + "test_a_backup_newer_than_the_mirror_is_restored_and_rendered": ("T110", "T115", "T117", "T120", "T121", "T327", "T415", "T416"), # T274; tasks:2521 + "test_a_pending_record_from_the_lost_database_is_refused_2_at_the_snapshot": ("T110", "T115", "T117", "T120", "T121", "T327", "T412", "T415", "T416", "T417"), # T274; tasks:2521 + "test_an_abort_after_a_restore_form_cutover_restores_every_table_byte_for_byte": ("T110", "T115", "T117", "T120", "T121", "T327", "T415", "T416"), # T274; tasks:2521 + "test_an_after_loss_cutover_from_a_host_still_on_the_live_database_is_refused_with_2_and_writes_nothing": ("T110", "T115", "T120", "T327"), # T274; tasks:2521 + "test_lanes_write_id_new_on_the_replacement_replaces_the_old_record_and_writes_once": ("T110", "T115", "T117", "T120", "T121", "T327", "T412", "T415", "T416", "T417"), # T274; tasks:2521 + "test_status_prints_the_mirror_tip_and_the_last_head_that_bound_the_loss": ("T110", "T115", "T117", "T120", "T121", "T327", "T415", "T416"), # T274; tasks:2521 + "test_the_after_loss_cutovers_label_rules_in_the_transaction": ("T107",), # T274; tasks:2521 + "test_the_disaster_path_reimports_at_the_mirrors_tip_and_continues_the_sequence": ("T110", "T115", "T117", "T120", "T121", "T327", "T415", "T416"), # T274; tasks:2521 + "test_the_disaster_path_rewrites_the_marker_by_the_after_loss_cutover": ("T110", "T115", "T117", "T120", "T121", "T304", "T326", "T327", "T412", "T415", "T416", "T417"), # T274; tasks:2521 + "test_the_printed_rerun_between_a_reimports_bootstrap_and_its_cutover_exits_2_not_69": ("T110", "T115", "T117", "T120", "T121", "T327", "T412", "T415", "T416", "T417"), # T274; tasks:2521 + "test_the_restore_route_commits_under_the_replacements_register_label_and_check_10_fails_until_it_does": ("T110", "T115", "T117", "T119", "T120", "T121", "T327", "T415", "T416"), # T274; tasks:2521 +} + +pytestmark = [WINDOWS_SKIP, pytest.mark.skipif( + shutil.which("bash") is None or shutil.which("git") is None, + reason="the lane tooling is bash over git")] + +INDEXER = REPO / "lanes-index" + +#: The register's schema, `register_schema=`'s default. +SCHEMA = "lanes_register" +#: The lost database's label and the replacement's (each its bootstrap's +#: `--label`): they differ, as a restore needs (N4). +LABEL_A, LABEL_B = "register-a", "register-b" +#: The engineer, its two logins, and the dump job's login. +ENGINEER = "ds" +WRITER_LOGIN, READER_LOGIN = f"lanes_w_{ENGINEER}", f"lanes_r_{ENGINEER}" +LOGINS = (WRITER_LOGIN, READER_LOGIN, FX_DUMP) +#: ws1: its name (Rule 10) and the operator lane, which test 7's register +#: holds LIVE. +WORKSTATION, OPERATOR = "Eagle", "repoA-2" +#: The release `ready` checks the installed tools against (check 1's list). +RELEASE, ENV_NAME = "0.0.0-t274", "disaster" +DIGEST_LIST = f"openRepoTools-{RELEASE}.sha256" +#: Step 2's declaration, on Brett's word (D20). +UNTIL = "2999-01-01T00:00:00Z" +WHY = "the disaster path: the register database is lost" + +#: The writes A takes: `RENDERED` reach origin (so the head is `m`), then +#: `LOST` are never rendered (so the head is `k`); the backup is taken after +#: `BACKUP_AFTER` of them (so `m < b < k`). +RENDERED, LOST, BACKUP_AFTER = 1, 3, 2 +#: The ceiling of every poll here. +SETTLE_S = 60 + +#: The render set (Q18 (A); CLI4.10 section 3.6), as T211's module has it. +RENDER_SET = re.compile(r"^lanes/(LANES\.md|aliases\.tsv|archive/[^/]+\.md" + r"|log/(?!README\.md$)[^/]+\.md)$") +#: The trailer each mirror commit and each operator entry's commit carry. +REGISTER_SEQ = re.compile(r"^Register-Seq: ([0-9]+)$", re.M) +#: `status`'s lag lines (lane 1's T117): read, and unread. +LAG_0 = re.compile(r"^\s*lag:\s+0 seq", re.M) +LAG_N = re.compile(r"^\s*lag:\s+([0-9]+) seq\(s\)", re.M) +LAG_AT_LEAST = re.compile(r"^\s*lag:\s+at least ([0-9]+) seq\(s\)", re.M) +#: `status`'s `n`, the head it read and records as `h` (T117); where the +#: register cannot be read its `n` is "unknown", which this does not match. +REGISTER_N = re.compile(r"^\s*n:\s+(-?[0-9]+)\b", re.M) +#: `status`'s two seqs where the register cannot be read (T117; ops 2.3, step 4). +MIRROR_M = re.compile(r"^\s*mirror:\s+Register-Seq ([0-9]+) at ([0-9a-f]{12})", re.M) +LAST_HEAD = re.compile(r"^\s*last head:\s+(-?[0-9]+),", re.M) +#: One check's line of `ready` (T119's form). +CHECK_LINE = re.compile(r"^check (\d+): (ok|FAIL)\b:?[ \t]*(.*)$", re.M) +#: An object line of `bootstrap` (T109's form). +OBJECT_LINE = re.compile(r"^(.+?): (created|unchanged)\b", re.M) +#: The printed rerun's two variables (T417's report; T244's patterns). +UUID_RE = r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}" +WRITE_ID_SAID = re.compile(r"LANES_WRITE_ID=(" + UUID_RE + r")") +GENERATION_SAID = re.compile(r"LANES_WRITE_GENERATION=(" + UUID_RE + r")") +#: The pending records, `<state>/openRepoTools/register-pending/<d>` (T412). +PENDING = Path("openRepoTools") / "register-pending" +#: The shim's arm that loses the first commit call before its COMMIT and every +#: call after it, so the writer ends 3 with its record kept (T244's `exit3`). +NO_RECONNECT = {"mode": "no-reconnect", "as": "before", "match": "commit_write", "call": 1} +#: A password-file line's last field, hidden by `_masked`. +_SECRET_FIELD = re.compile(r"^(\*:\*:.*:)[^:\n]*$", re.M) + +#: O2's dump command, run as the dump job's login (6722541787; T224's). +DUMP_COMMAND = ("umask 077 && pg_dump --no-password --schema=lanes_register " + "--schema=lanes_index --format=custom --file={file}") + +#: Section 1.2's tables but `schema_version`, `migrations` and `mirror_state`: +#: the twelve the restore form's abort puts back (AT-D22's abort). +ABORT_TABLES = ("register_switch", "register_head", "journal", "journal_edits", "journal_files", + "journal_scopes", "files", "doc_lines", "lanes", "log_lines", "object_holds", + "register_lines") + +#: The roles `--roles-only` makes (design.md section 1.4; T109). +REGISTER_ROLES = ("lanes_register_owner", "lanes_register_writer", "lanes_register_reader", + "lanes_indexer") +WRITER_GROUP = "lanes_register_writer" + + +# ------------------------------------------------------------------ test 5's git wrapper +#: TEST 5'S `git` WRAPPER (TP:1060-1080), T273b's, with two arms AT-D22 adds: +#: `fail`, the subcommands it fails without running them (every `fetch`, for +#: the lag), and `fail_push_seq`, a `Register-Seq` whose commit's push it fails +#: (the abort: only the marker's). Each call is one JSON line of +#: `git-wrapper.log`: its subcommand, its argv, its pid, and its outcome. +GIT_WRAPPER = r'''#!/usr/bin/env -S python3 -I +import json, os, re, subprocess, sys +HERE = os.path.dirname(os.path.abspath(__file__)) +CONTROL = os.path.join(HERE, "git-wrapper.json") +LOG = os.path.join(HERE, "git-wrapper.log") +WITH_VALUE = {"-C", "-c", "--git-dir", "--work-tree", "--namespace", "--exec-path", + "--config-env"} +PUSH_VALUE = {"-o", "--push-option", "--receive-pack", "--exec", "--repo"} + + +def split(args): + """(the options before the subcommand, the subcommand, its arguments).""" + i = 0 + while i < len(args): + if args[i] in WITH_VALUE: + i += 2 + elif args[i].startswith("-"): + i += 1 + else: + return args[:i], args[i], args[i + 1:] + return args, "", [] + + +def pushed_seqs(git, prefix, rest): + """The Register-Seq values of each commit a push names as its source.""" + words, i = [], 0 + while i < len(rest): + if rest[i] in PUSH_VALUE: + i += 2 + continue + if not rest[i].startswith("-"): + words.append(rest[i]) + i += 1 + seqs = [] + for spec in words[1:]: + source = spec.lstrip("+").split(":", 1)[0] + if not source: + continue + proc = subprocess.run([git] + prefix + ["log", "-1", "--format=%B", source, "--"], + capture_output=True, text=True) + if proc.returncode == 0: + seqs += [int(s) for s in re.findall(r"^Register-Seq: ([0-9]+)$", proc.stdout, re.M)] + return seqs + + +def log(record): + with open(LOG, "a", encoding="utf-8") as handle: + handle.write(json.dumps(record) + "\n") + + +def main(): + args = sys.argv[1:] + with open(CONTROL, encoding="utf-8") as handle: + control = json.load(handle) + prefix, sub, rest = split(args) + record = {"sub": sub, "argv": args, "pid": os.getpid()} + if sub in control.get("fail", []): + log(dict(record, outcome="failed", rc=1)) + sys.stderr.write("fatal: t274 wrapper: this %s fails\n" % sub) + return 1 + seq = control.get("fail_push_seq") + if sub == "push" and seq is not None: + seqs = pushed_seqs(control["git"], prefix, rest) + if seq in seqs: + log(dict(record, outcome="failed", rc=1, seqs=seqs)) + sys.stderr.write("fatal: t274 wrapper: the push of Register-Seq %d fails\n" % seq) + return 1 + rc = subprocess.run([control["git"]] + args).returncode + log(dict(record, outcome="ran", rc=rc)) + return rc + + +sys.exit(main()) +''' + + +# ------------------------------------------------------------------ small helpers +def _private(path: Path, text: str) -> Path: + """`text` at `path`, 0600, replaced in one rename.""" + path.parent.mkdir(parents=True, exist_ok=True) + temp = path.with_name(f".{path.name}.tmp") + temp.write_text(text, encoding="utf-8") + temp.chmod(0o600) + os.replace(temp, path) + return path + + +def _script(path: Path, text: str) -> Path: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8") + path.chmod(0o755) + return path + + +def _masked(text: str) -> str: + """`text` with each password-file line's password hidden.""" + return _SECRET_FIELD.sub(lambda m: m.group(1) + "<password>", text or "") + + +def _said(proc) -> str: + return (f"exit {proc.returncode}\n--- stdout ---\n{_masked(proc.stdout)[-2500:]}" + f"\n--- stderr ---\n{_masked(proc.stderr)[-2500:]}") + + +def _jsonl(path: Path) -> list: + if not path.exists(): + return [] + return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line] + + +def _checks(text: str) -> dict: + """`ready`'s check lines, by number: (`ok` or `FAIL`, the reason).""" + return {int(m.group(1)): (m.group(2), m.group(3) or "") for m in CHECK_LINE.finditer(text)} + + +def _fields(text: str) -> dict: + return dict(line.split("=", 1) for line in text.splitlines() if "=" in line) + + +def _rows(db, sql: str) -> list: + """`sql`'s rows as JSON objects, in the register's schema, by `jsonb_agg`, + whose text is one line.""" + out = db.psql(f"SET search_path TO {SCHEMA};\n" + f"SELECT coalesce(jsonb_agg(t), '[]'::jsonb) FROM ({sql}) t;\n").stdout + return json.loads(out.strip().splitlines()[-1]) + + +def _value(db, sql: str) -> str: + return db.psql(sql).stdout.strip() + + +def _renders(db) -> dict: + """SQL's own render (lane 1's T107, `render_file`) of every path in + `files`, {path: bytes}.""" + return {r["path"]: base64.b64decode(r["b64"]) for r in _rows( + db, "SELECT path, encode(render_file(path), 'base64') AS b64 FROM files ORDER BY path")} + + +def _passfile(path: Path, login: str, password: str) -> Path: + """A 0600 libpq password file holding `login`'s line at any host, port + and database.""" + return _private(path, f"*:*:*:{login}:{password}\n") + + +def _connects(cluster, login: str, database: str, passfile: Path) -> bool: + """Whether `login` logs in to `database` on `cluster` over TLS + (`verify-full`, the root alone) with the password in `passfile`.""" + env = {k: v for k, v in os.environ.items() if not k.startswith("PG")} + env.update(PGHOST="localhost", PGHOSTADDR="127.0.0.1", PGPORT=str(cluster.port), + PGUSER=login, PGDATABASE=database, PGSSLMODE="verify-full", + PGSSLROOTCERT=str(cluster.root_cert), PGPASSFILE=str(passfile), + PGCONNECT_TIMEOUT="10", LC_ALL="C") + proc = subprocess.run([cluster.tool("psql"), "-X", "-q", "-A", "-t", "-w", "-c", "SELECT 1"], + env=env, capture_output=True, text=True, timeout=60, + stdin=subprocess.DEVNULL, check=False) + return proc.returncode == 0 and proc.stdout.strip() == "1" + + +def _abort_dump(db) -> dict: + """AT-D22's abort dump: each of `ABORT_TABLES`, ordered by its primary + key, each row as `to_jsonb` prints it, as one text per table, read by the + admin connection. No identity sequence is read.""" + dumped = {} + for table in ABORT_TABLES: + keys = [r["k"] for r in sorted(_rows( + db, f"SELECT a.attname AS k, array_position(i.indkey::int2[], a.attnum) AS n " + f"FROM pg_index i JOIN pg_attribute a " + f"ON a.attrelid = i.indrelid AND a.attnum = ANY (i.indkey) " + f"WHERE i.indrelid = '{SCHEMA}.{table}'::regclass AND i.indisprimary"), + key=lambda r: r["n"])] + order = ", ".join(f't."{key}"' for key in keys) or "to_jsonb(t)::text" + dumped[table] = _value(db, f"SELECT coalesce(jsonb_agg(to_jsonb(t) ORDER BY {order}), " + f"'[]'::jsonb)::text FROM {SCHEMA}.{table} t;") + return dumped + + +def _lock_free(lock: Path) -> bool: + """A non-blocking `flock` on the render lock succeeds (AT-5's [L4-4]); a + lock file not made yet is free.""" + try: + fd = os.open(str(lock), os.O_RDWR) + except FileNotFoundError: + return True + try: + fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + except OSError: + return False + else: + fcntl.flock(fd, fcntl.LOCK_UN) + return True + finally: + os.close(fd) + + +# ------------------------------------------------------------------ ws1, the operator's host +class Host: + """ws1 (see the module's notes): test 7's operator checkout and W, its + installed tools, test 5's wrapper and the shim, and its configuration, + first at A, then re-pointed at B. Every command runs as the operator lane + through its checkout (F12).""" + + def __init__(self, estate: "Disaster", register: ImportedRegister): + self.estate, self.root = estate, estate.root / "ws1" + self.root.mkdir(parents=True) + self.home, self.checkout = register.home, register.wip + self.real_git = shutil.which("git") + self.tools = self.root / "tools" + try: + self.copy = flipped_copy(INDEXER, self.tools, True) + except ValueError as exc: + raise AssertionError(f"[estate] lanes-index cannot be flipped to its git half " + f"({exc}): lane 1's RENDER_GIT_HALF (T105) has not " + f"landed") from exc + for companion in ("lanes-edit.sh", "lanes", "lane-start", "repos.tsv"): + if (REPO / companion).exists(): + shutil.copy2(REPO / companion, self.tools / companion) + (self.tools / DIGEST_LIST).write_text("".join( + f"{hashlib.sha256((self.tools / tool).read_bytes()).hexdigest()} {tool}\n" + for tool in ("lanes-index", "lanes-edit.sh")), encoding="utf-8") + self.fakebin = self.root / "fakebin" + _script(self.fakebin / "tmux", "#!/bin/sh\nexit 1\n") + self.bin = self.root / "bin" + _script(self.bin / "git", GIT_WRAPPER) + _script(self.bin / "psql", PSQL_SHIM) + for directory in ("state", "config", "tmp"): + (self.root / directory).mkdir() + self.state = self.root / "state" + self.conf = self.root / "conf" / "lanes-index.conf" + env = guard_strip_env(os.environ, strip=("XDG_", "GIT_", "EMAIL", "WORKBENCHES_")) + inherited = [entry for entry in os.environ.get("PATH", os.defpath).split(os.pathsep) + if entry] + env.update( + HOME=str(self.home), AGENT_PROTOCOL_ROOT=str(self.home / ".agents"), + TMPDIR=str(self.root / "tmp"), XDG_STATE_HOME=str(self.state), + XDG_CONFIG_HOME=str(self.root / "config"), + CLAUDE_CONFIG_DIR=str(self.home / ".claude"), LANES_WORKSTATION=WORKSTATION, + LANES_HOST=WORKSTATION.lower(), LANES_OS="linux", LANES_CONTAINER="none", + LANES_IN_CONTAINER="0", LANES_NO_GITHUB="1", LANES_REPO=str(self.checkout), + LANES_EDIT=str(self.tools / "lanes-edit.sh"), LANES_INDEX_CONFIG=str(self.conf), + LANES_LANE=OPERATOR, GIT_AUTHOR_NAME=f"Disaster {ENGINEER}", + GIT_AUTHOR_EMAIL=f"{ENGINEER}@example.invalid", + GIT_COMMITTER_NAME=f"Disaster {ENGINEER}", + GIT_COMMITTER_EMAIL=f"{ENGINEER}@example.invalid", + GIT_CONFIG_NOSYSTEM="1", GIT_CONFIG_GLOBAL=os.devnull, GIT_TERMINAL_PROMPT="0", + PATH=os.pathsep.join([str(self.fakebin), str(self.bin), str(self.tools), + str(estate.a.bindir), *inherited])) + self.env = env + self.lane_checkout = self.make_lane_checkout(register) + self.arm() + + def make_lane_checkout(self, register: ImportedRegister) -> Path: + """`<c>` (see the module's notes), where `lanes-edit.sh`'s + `lane_checkout_path` puts it: `<W>-lanes/<lane>`, W being the real + path of `workspace.yaml`'s `path:`. A clone of the origin by the real + git, as `lane-checkout <lane> --create` makes one.""" + real = Path(os.path.realpath(register.ws)) + target = real.parent / f"{real.name}-lanes" / OPERATOR + target.parent.mkdir(parents=True, exist_ok=True) + proc = subprocess.run([self.real_git, "clone", "-q", str(register.origin), str(target)], + env=self.env, capture_output=True, text=True, timeout=120, + stdin=subprocess.DEVNULL, check=False) + assert proc.returncode == 0, f"[estate] the operator lane's own checkout:\n{_said(proc)}" + return target + + # ------------------------------------------------------------ the wrapper and the shim + def arm(self, *, fail=(), fail_push_seq: int | None = None, psql_arms=()) -> None: + """The wrapper's arms and the shim's, each log started afresh.""" + (self.bin / "git-wrapper.json").write_text(json.dumps( + {"git": self.real_git, "fail": list(fail), "fail_push_seq": fail_push_seq}), + encoding="utf-8") + (self.bin / PSQL_SHIM_CONTROL).write_text(json.dumps( + {"psql": str(self.estate.a.bindir / "psql"), "arms": list(psql_arms)}), + encoding="utf-8") + for name in (PSQL_SHIM_LOG, "psql-shim.ends", "git-wrapper.log"): + (self.bin / name).write_text("", encoding="utf-8") + (self.bin / "psql-shim.state").write_text("{}", encoding="utf-8") + + def git_calls(self) -> list: + return _jsonl(self.bin / "git-wrapper.log") + + def failed_fetches(self) -> int: + return sum(1 for c in self.git_calls() if c["sub"] == "fetch" and c["outcome"] == "failed") + + def pushes(self) -> list: + return [c for c in self.git_calls() if c["sub"] == "push"] + + def commit_calls(self) -> list: + """The shim's requests that carried a `commit_write` call.""" + return [c for c in _jsonl(self.bin / PSQL_SHIM_LOG) + if "commit_write(" in (c.get("stdin") or "")] + + # ------------------------------------------------------------ the configuration + def point_at(self, cluster, database: str, label: str, passfiles: dict, + mode: str = "index", path: Path | None = None) -> Path: + """The 0600 configuration naming `database` on `cluster`, in one edit: + `ds`'s two logins over TLS, their password files, the label, the + schema and check 13's count.""" + return _private(path or self.conf, "\n".join([ + f"mode={mode}", f"register_url={cluster.url(WRITER_LOGIN, database)}", + f"register_passfile={passfiles[WRITER_LOGIN]}", + f"reader_url={cluster.url(READER_LOGIN, database)}", + f"reader_passfile={passfiles[READER_LOGIN]}", f"register_label={label}", + f"register_schema={SCHEMA}", "register_addresses=1", ""])) + + def conf_lines(self) -> list: + return self.conf.read_text(encoding="utf-8").splitlines() + + def outage_file(self) -> Path: + return self.conf.parent / "register-outage" + + # ------------------------------------------------------------ commands + def _env(self, env: dict | None) -> dict: + child = dict(self.env) + for key, value in (env or {}).items(): + if value is None: + child.pop(key, None) + else: + child[key] = value + return child + + def index(self, *args: str, env: dict | None = None, + timeout: float = 300) -> subprocess.CompletedProcess: + """ws1's `lanes-index`, in its checkout, as the operator lane.""" + return subprocess.run([sys.executable, str(self.copy), *args], cwd=str(self.checkout), + env=self._env(env), capture_output=True, text=True, + timeout=timeout, stdin=subprocess.DEVNULL, check=False) + + def edit(self, *args: str, env: dict | None = None, + timeout: float = 300) -> subprocess.CompletedProcess: + """ws1's `lanes-edit.sh`, in its checkout, as the operator lane.""" + return subprocess.run(["bash", str(self.tools / "lanes-edit.sh"), *args], + cwd=str(self.checkout), env=self._env(env), capture_output=True, + text=True, timeout=timeout, stdin=subprocess.DEVNULL, check=False) + + def git(self, *args: str) -> str: + """The real git in ws1's checkout, past the wrapper.""" + proc = subprocess.run([self.real_git, "-C", str(self.checkout), *args], env=self.env, + capture_output=True, text=True, timeout=120, + stdin=subprocess.DEVNULL, check=False) + assert proc.returncode == 0, f"git {' '.join(args[:2])} in ws1:\n{_said(proc)}" + return proc.stdout + + def render_lock(self) -> Path: + return self.checkout / ".git" / "lanes-render.lock" + + def pending(self) -> list: + """ws1's pending records, `<state>/openRepoTools/register-pending/<d>`.""" + where = self.state / PENDING + return sorted(p for p in where.iterdir() + if re.fullmatch(r"[0-9a-f]{64}", p.name)) if where.is_dir() else [] + + +# ------------------------------------------------------------------ the estate +class Disaster: + """AT-D22'S ESTATE and its steps, each with its labelled assertions (see + the module's notes). `db` is the database ws1 points at: A's, then B's.""" + + def __init__(self, request, root: Path): + # Without an engine, T205's `pg_engine` skips first, with its banner. + self.engine = request.getfixturevalue("pg_engine") + self.request, self.root = request, root + self.a = request.getfixturevalue("tls_cluster") + try: + self.a_db = self.a.second_database(label=LABEL_A) + except ClusterError as exc: + raise AssertionError(f"[estate] A's register, bootstrapped through the admin service " + f"with --label {LABEL_A} (T109, L1-A7): {exc}") from exc + self.db = self.a_db + self._login_add(self.a, self.a_db.name, [ENGINEER]) + if FX_DUMP not in self.a.passwords: + raise AssertionError(f"[estate] cluster A has no {FX_DUMP}: T228's `login add " + f"--dump-job` (T110) made none when its template was built") + #: A's password files, kept outside A's directory, so they outlive A. + self.a_files = {login: _passfile(root / "pass-a" / f"{login}.pgpass", login, + self.a.passwords[login]) for login in LOGINS} + try: + self.register = ImportedRegister(root / "estate", self.a.bindir) + except ClusterError as exc: + raise AssertionError(f"[estate] test 7's fixture register on a bare origin " + f"(T227b): {exc}") from exc + self.origin = self.register.origin + self.host = Host(self, self.register) + self.host.point_at(self.a, self.a_db.name, LABEL_A, self.a_files) + self.b = self.b_db = None + self.b_files: dict = {} + self.c = self.cut = self.marker = None + self.m = self.k = self.b_seq = self.h = None + self.dump = None + self.generation_a = self.generation_boot = None + + # ------------------------------------------------------------ clusters and logins + def _login_add(self, cluster, database: str, engineers: list, dump_job: bool = False) -> None: + """`lanes-index login add` through the admin service on `database`, + under a pty (lane 1's T110): each password line it prints is kept in + the cluster's memory, never printed.""" + service = cluster.admin_service(database) + argvs = [["login", "add", engineer, "--admin-service", service] for engineer in engineers] + if dump_job: + argvs.append(["login", "add", "--dump-job", "--admin-service", service]) + for argv in argvs: + code, out, err = cluster.lanes_index_tty(argv) + assert code == 0, (f"[logins] `lanes-index {' '.join(argv[:3])}` exited {code} " + f"(lane 1's T110, L1-A8): {_masked(out)[-400:]} | " + f"{_masked(err)[-400:]}") + found = dict(PASSWORD_LINE.findall(out)) + assert found, f"[logins] `{' '.join(argv[:3])}` printed no password line" + cluster.passwords.update(found) + + def new_b(self) -> None: + """Cluster B, new: a TLS cluster whose template holds nothing, so no + register role is on it; its one database is the register's.""" + cluster = TLSCluster(self.engine.bindir, "") + try: + cluster.start() + except (ClusterError, OSError, subprocess.SubprocessError) as exc: + cluster.destroy() + raise AssertionError(f"[B] the replacement's cluster did not start: {exc}") from exc + self.request.addfinalizer(cluster.destroy) + self.b, self.b_db = cluster, Database(cluster, cluster.database_name) + + def b_lanes_index(self, *args: str) -> subprocess.CompletedProcess: + """The admin's `lanes-index` on B, through the one admin service.""" + return self.b.lanes_index([args[0], "--admin-service", self.b.admin_service( + self.b_db.name), *args[1:]]) + + def b_bootstrap(self, *, roles_only: bool = False) -> subprocess.CompletedProcess: + extra = ["--roles-only"] if roles_only else [ + "--label", LABEL_B, "--repository", FX_REPOSITORY, "--lane", FX_LANE] + proc = self.b_lanes_index("bootstrap", *extra, "--no-passwords") + assert proc.returncode == 0, ( + f"[B] `bootstrap {' '.join(extra[:2])}` through the admin service failed (lane 1's " + f"T109, L1-A7):\n{_said(proc)}") + return proc + + def b_logins(self) -> None: + """`login add ds` and `login add --dump-job` on B: new passwords.""" + self._login_add(self.b, self.b_db.name, [ENGINEER], dump_job=True) + self.b_files = {login: _passfile(self.root / "pass-b" / f"{login}.pgpass", login, + self.b.passwords[login]) for login in LOGINS} + + def repoint(self) -> None: + """F18's re-pointing of ws1, in one edit, at B, with B's label.""" + mode = _fields(self.host.conf.read_text(encoding="utf-8")).get("mode", "index") + self.host.point_at(self.b, self.b_db.name, LABEL_B, self.b_files, mode=mode) + self.db = self.b_db + + # ------------------------------------------------------------ origin and SQL + def origin_git(self, *args: str) -> str: + """git in the bare origin itself, so no checkout's refs move.""" + proc = subprocess.run([self.host.real_git, f"--git-dir={self.origin}", *args], + capture_output=True, text=True, env=self.register.env, timeout=120, + stdin=subprocess.DEVNULL, check=False) + assert proc.returncode == 0, f"git {' '.join(args[:2])} in origin:\n{_said(proc)}" + return proc.stdout + + def origin_tip(self) -> str: + return self.origin_git("rev-parse", "refs/heads/main").strip() + + def seqs_of(self, sha: str) -> list: + return [int(s) for s in REGISTER_SEQ.findall(self.origin_git("log", "-1", "--format=%B", + sha))] + + def commits_after(self, base: str) -> list: + """[(commit, its Register-Seq values)] on origin's `main` after `base`, + oldest first, first parents only.""" + out = self.origin_git("rev-list", "--reverse", "--first-parent", + f"{base}..refs/heads/main") + return [(sha, self.seqs_of(sha)) for sha in out.split()] + + def origin_seqs(self) -> list: + out = self.origin_git("log", "--reverse", "--format=%B%x00", "refs/heads/main") + return [int(s) for body in out.split("\0") for s in REGISTER_SEQ.findall(body)] + + def store_on_origin(self, rev: str = "refs/heads/main") -> dict | None: + names = self.origin_git("ls-tree", "-r", "--name-only", rev, "lanes/").split() + if "lanes/STORE" not in names: + return None + return _fields(self.origin_git("show", f"{rev}:lanes/STORE")) + + def changed_paths(self, sha: str) -> list: + return self.origin_git("diff-tree", "--no-commit-id", "--name-status", "-r", f"{sha}^", + sha).splitlines() + + def head(self, db=None) -> int: + return _rows(db or self.db, "SELECT seq FROM register_head")[0]["seq"] + + def switch(self, db=None) -> dict: + return _rows(db or self.db, "SELECT * FROM register_switch")[0] + + def journal(self, db=None) -> list: + return [[r["seq"], r["kind"], r["operator"]] for r in _rows( + db or self.db, "SELECT seq, kind, operator FROM journal ORDER BY seq")] + + def mirror_problem(self, rev: str = "refs/heads/main") -> str | None: + """None where origin's render set at `rev` equals a full render from + `db`, byte for byte; else what differs.""" + on_origin = {} + for path in self.origin_git("ls-tree", "-r", "--name-only", rev, "lanes/").split(): + if RENDER_SET.match(path): + on_origin[path] = subprocess.run( + [self.host.real_git, f"--git-dir={self.origin}", "show", f"{rev}:{path}"], + capture_output=True, env=self.register.env, timeout=60, check=True, + stdin=subprocess.DEVNULL).stdout + from_sql = {p: b for p, b in _renders(self.db).items() if RENDER_SET.match(p)} + if on_origin == from_sql: + return None + differ = sorted(p for p in on_origin if p in from_sql and on_origin[p] != from_sql[p]) + return (f"paths on one side only: {sorted(set(on_origin) ^ set(from_sql))}; paths that " + f"differ: {differ}") + + # ------------------------------------------------------------ waits + def wait_for_seq(self, seq: int, label: str) -> None: + """Poll origin's `main` until a commit carries `Register-Seq: <seq>`.""" + deadline = time.monotonic() + SETTLE_S + while seq not in self.origin_seqs(): + assert time.monotonic() < deadline, ( + f"{label}: no commit on origin's main carries Register-Seq: {seq} within " + f"{SETTLE_S} s (the render a write forks: lane 4's T416, lane 3's T321 to T323): " + f"{self.origin_seqs()[-6:]}") + time.sleep(0.25) + + def wait_renderer_exit(self, failed_before: int, label: str) -> None: + """Open point 8's second wait: a `fetch` the wrapper failed since + `failed_before`, then the render lock free.""" + deadline = time.monotonic() + SETTLE_S + while not (self.host.failed_fetches() > failed_before + and _lock_free(self.host.render_lock())): + assert time.monotonic() < deadline, ( + f"{label}: the renderer the write forked did not fail its fetch and exit within " + f"{SETTLE_S} s (lane 4's T416; lane 3's T321 to T323): " + f"{[c['sub'] + ':' + c['outcome'] for c in self.host.git_calls()][-8:]}") + time.sleep(0.25) + + def settled(self, seq: int, label: str) -> None: + """After a write on primary with fetches working: its render on + origin, the renderer gone, ws1's checkout fetched, a lag of 0.""" + self.wait_for_seq(seq, label) + deadline = time.monotonic() + SETTLE_S + while not _lock_free(self.host.render_lock()): + assert time.monotonic() < deadline, f"{label}: the renderer never released its lock" + time.sleep(0.25) + self.host.git("fetch", "-q", "origin") + while True: + proc = self.host.index("status", timeout=120) + if LAG_0.search(proc.stdout): + return + assert time.monotonic() < deadline, ( + f"{label}: `status` shows no lag of 0 within {SETTLE_S} s (lane 1's T117):\n" + f"{_said(proc)}") + time.sleep(0.25) + + # ------------------------------------------------------------ A + def a_to_primary(self) -> None: + """`import --at C`, the first cutover with its marker, then + `set-mode primary`, all from ws1 at A.""" + self.host.git("fetch", "-q", "origin") + self.host.git("merge", "-q", "--ff-only", "refs/remotes/origin/main") + self.c = self.origin_tip() + proc = self.host.index("import", "--at", self.c, timeout=400) + assert proc.returncode == 0, ( + f"[A] `import --at {self.c[:12]}` from ws1 failed (lane 1's T115, L1-A13):\n" + f"{_said(proc)}") + proc = self.host.index("cutover", "--import", self.c) + assert proc.returncode == 0, ( + f"[A] `cutover --import {self.c[:12]}` failed (lane 1's T116, L1-A14):\n{_said(proc)}") + switch = self.switch() + assert (switch["mode"], switch["marker_state"]) == ("primary", "present"), ( + f"[A] after the cutover the switch reads {switch['mode']} with the marker " + f"{switch['marker_state']}: the marker's push, its read-back and record_marker are " + f"lane 3's T327, so this fails until it lands") + self.cut = _rows(self.db, "SELECT seq FROM journal WHERE kind = 'cutover'")[0]["seq"] + self.marker = self.origin_tip() + self.generation_a = switch["generation"] + flip = self.host.index("set-mode", "primary", "--config", str(self.host.conf)) + assert flip.returncode == 0, f"[A] `set-mode primary` (lane 1's T120):\n{_said(flip)}" + + def write(self, label: str, text: str) -> int: + """`log NOTED` on primary from ws1 (R3b's smoke test's verb): exit 0 + and one journal entry, at the head plus 1. Returns its seq.""" + before = self.head() + proc = self.host.edit("log", "NOTED", f"lane:{OPERATOR}", text) + assert proc.returncode == 0, ( + f"{label}: `log NOTED` on primary from ws1 failed (lane 4's T415):\n{_said(proc)}") + rows = _rows(self.db, f"SELECT seq, kind, lane FROM journal WHERE seq > {before} " + f"ORDER BY seq") + assert rows == [{"seq": before + 1, "kind": "write", "lane": OPERATOR}], ( + f"{label}: the write's row is not the head plus 1: {rows}") + return before + 1 + + def a_written(self, *, lost: int = LOST, backup_after: int | None = None) -> None: + """A through `m`, rendered, then `lost` writes no render reaches (a + fetch that fails), each waited for by the renderer's exit; the + backup after `backup_after` of them. `status` then shows `k - m`.""" + for n in range(1, RENDERED + 1): + seq = self.write("[A]", f"T274: write {n}, rendered") + self.settled(seq, f"[A] write {n}") + self.m = self.head() + assert max(self.origin_seqs()) == self.m, ( + f"[A] origin's last Register-Seq is not m = {self.m}: {self.origin_seqs()[-4:]}") + self.host.arm(fail=["fetch"]) + for n in range(1, lost + 1): + failed = self.host.failed_fetches() + self.write("[A]", f"T274: write {RENDERED + n}, never rendered") + self.wait_renderer_exit(failed, f"[A] lost write {n}") + if backup_after == n: + self.take_backup() + self.k = self.head() + assert max(self.origin_seqs()) == self.m, ( + f"[A] a render reached origin while every fetch failed: {self.origin_seqs()[-4:]}") + status = self.host.index("status", timeout=120) + lag = LAG_N.search(status.stdout) + # Not its exit: that is #160's index's too, 1 on ws1 (see the readings). + assert status.returncode != 69 and lag and int(lag.group(1)) == self.k - self.m, ( + f"[A] `status` at A does not show a lag of k - m = {self.k - self.m} (lane 1's " + f"T117):\n{_said(status)}") + # Every renderer has exited: the wrapper lets git through again, for B. + self.host.arm() + + def take_backup(self) -> None: + """O2's dump of A as `lanes_register_dump`, then `b` read from the + file alone, equal to A's head when the dump was taken.""" + head = self.head(self.a_db) + target = self.root / "backup" / "lanes-register.dump" + target.parent.mkdir(parents=True) + env = {k: v for k, v in os.environ.items() if not k.startswith("PG")} + env.update(PGHOST="localhost", PGHOSTADDR="127.0.0.1", PGPORT=str(self.a.port), + PGUSER=FX_DUMP, PGDATABASE=self.a_db.name, PGSSLMODE="verify-full", + PGSSLROOTCERT=str(self.a.root_cert), PGPASSFILE=str(self.a_files[FX_DUMP]), + PGCONNECT_TIMEOUT="10", LC_ALL="C", + PATH=os.pathsep.join([str(self.a.bindir), os.environ.get("PATH", "")])) + proc = subprocess.run(["bash", "-c", DUMP_COMMAND.format(file=target)], env=env, + capture_output=True, text=True, timeout=300, + stdin=subprocess.DEVNULL, check=False) + assert proc.returncode == 0 and target.exists(), ( + f"[backup] O2's pg_dump as {FX_DUMP} failed (T110's dump login; T224):\n{_said(proc)}") + read = subprocess.run([self.a.tool("pg_restore"), "--data-only", f"--schema={SCHEMA}", + "--table=register_head", "--file=-", str(target)], + capture_output=True, text=True, timeout=120, + stdin=subprocess.DEVNULL, check=False) + block = re.search(r"^COPY \S*register_head \(([^)]*)\) FROM stdin;\n([^\n]*)\n", + read.stdout, re.M) + assert read.returncode == 0 and block, ( + f"[backup] pg_restore --data-only gives no register_head row:\n{_said(read)}") + columns = [c.strip().strip('"') for c in block.group(1).split(",")] + b = int(block.group(2).split("\t")[columns.index("seq")]) + assert b == head, f"[backup] the dump's head is {b}, not A's head {head} when it was taken" + self.b_seq, self.dump = b, target + + def in_doubt_write(self) -> dict: + """A write on A whose commit call is lost before its COMMIT: exit 3, + its record kept, its printed rerun (lane 4's T412, T415 and T417). + Returns the argv, the id, the generation and the record.""" + argv = ["log", "NOTED", f"lane:{OPERATOR}", "T274: the write in doubt when A was lost"] + head = self.head() + self.host.arm(psql_arms=[NO_RECONNECT]) + proc = self.host.edit(*argv) + self.host.arm() + assert proc.returncode == 3, ( + f"[record] a write whose commit call is lost is not 3 with its rerun printed (lane " + f"4's T417):\n{_said(proc)}") + ids, gens = WRITE_ID_SAID.findall(proc.stderr), GENERATION_SAID.findall(proc.stderr) + assert ids and gens, f"[record] exit 3 printed no LANES_WRITE_ID rerun:\n{_said(proc)}" + records = self.host.pending() + assert len(records) == 1, f"[record] {len(records)} pending records, not one (T412)" + assert gens[-1] == self.generation_a, ( + f"[record] the printed rerun's generation is {gens[-1]}, not A's {self.generation_a}") + assert self.head() == head == self.m, ( + f"[record] the lost call moved the head: {self.head()}, not m = {self.m}") + return {"argv": argv, "id": ids[-1], "generation": gens[-1], "path": records[0], + "bytes": records[0].read_bytes()} + + def loss_recorded(self) -> None: + """`status` at A records `h`; A stops; `status` prints `m` and `h` and + exits 69; the outage is declared on ws1.""" + status = self.host.index("status", timeout=120) + read = REGISTER_N.search(status.stdout) + assert status.returncode != 69 and read and int(read.group(1)) == self.k, ( + f"[loss] `status` at A does not read A's head k = {self.k}, so it records no h " + f"(lane 1's T117):\n{_said(status)}") + self.a.stop() + status = self.host.index("status", timeout=120) + mirror, last = MIRROR_M.search(status.stdout), LAST_HEAD.search(status.stdout) + assert status.returncode == 69 and mirror and last, ( + f"[loss] `status` with A stopped does not exit 69 printing the mirror's m and the " + f"last head it recorded (lane 1's T117; ops 2.3, step 4):\n{_said(status)}") + self.h = int(last.group(1)) + assert (int(mirror.group(1)), self.h) == (self.m, self.k), ( + f"[loss] `status` prints m {mirror.group(1)} and h {self.h}, not m {self.m} and " + f"h {self.k}:\n{_said(status)}") + declared = self.host.index("outage", "declare", "--until", UNTIL, "--why", WHY) + assert declared.returncode == 0 and self.host.outage_file().exists(), ( + f"[loss] `outage declare` on ws1 declared nothing (lane 1's T121, L1-A18):\n" + f"{_said(declared)}") + + def a_destroyed(self) -> None: + self.a.destroy() + + # ------------------------------------------------------------ B + def b_reimport_route(self) -> None: + """R-P41's re-import route on B: `--roles-only`, `bootstrap`, the + logins made again after it, the re-pointing.""" + self.new_b() + self.b_bootstrap(roles_only=True) + self.b_bootstrap() + self.b_logins() + self.repoint() + + def b_restore_route(self) -> subprocess.CompletedProcess: + """R-P41's restore route on B: `--roles-only`, the logins, the + restore of A's dump, `bootstrap` again, the re-pointing. Returns the + second bootstrap.""" + self.new_b() + self.b_bootstrap(roles_only=True) + self.b_logins() + env = {k: v for k, v in self.b.admin_env().items() if not k.startswith("PG")} + env["PGSERVICE"] = self.b.admin_service(self.b_db.name) + restore = subprocess.run([self.b.tool("pg_restore"), "--exit-on-error", "--no-password", + f"--dbname={self.b_db.name}", str(self.dump)], + capture_output=True, text=True, timeout=300, env=env, + stdin=subprocess.DEVNULL, check=False) + assert restore.returncode == 0, ( + f"[restore] pg_restore of A's dump through the admin service failed:\n" + f"{_said(restore)}") + again = self.b_bootstrap() + self.repoint() + return again + + def reimport(self) -> str: + """`import --at <M> --after-loss` from ws1, M origin's tip: B's head + is `m`, and the journal's one root sits there. Returns M.""" + self.host.git("fetch", "-q", "origin") + self.host.git("merge", "-q", "--ff-only", "refs/remotes/origin/main") + tip = self.origin_tip() + proc = self.host.index("import", "--at", tip, "--after-loss", timeout=400) + assert proc.returncode == 0, ( + f"[re-import] `import --at {tip[:12]} --after-loss` failed (lane 1's T115, " + f"L1-A13):\n{_said(proc)}") + assert (self.head(), self.journal()) == (self.m, [[self.m, "import", False]]), ( + f"[re-import] B's head is {self.head()} with the journal {self.journal()}, not m = " + f"{self.m} with its one root there") + switch = self.switch() + assert (switch["mode"], switch["marker_state"], switch["database_label"]) == ( + "files", "absent", LABEL_B), f"[re-import] B's switch after the import: {switch}" + self.generation_boot = switch["generation"] + return tip + + def cutover_after_loss(self, tip: str | None) -> subprocess.CompletedProcess: + """`cutover --import <M> --after-loss` (the re-import's form), or + `cutover --after-loss` (the restore's), from ws1 at B.""" + args = ["cutover", "--import", tip, "--after-loss"] if tip else ["cutover", "--after-loss"] + return self.host.index(*args) + + def marker_rewritten(self, proc, seq: int, label: str) -> str: + """The after-loss cutover's oracle: exit 0; the switch at `primary` + with the marker `present`, B's label, a new generation and `set_seq` + its own seq; the entry an operator entry; origin's tip its marker + commit, carrying `Register-Seq: <seq>`, changing `lanes/STORE` alone, + whose `database=` names B. Returns the marker commit.""" + assert proc.returncode == 0, ( + f"{label}: the after-loss cutover failed (lane 1's T116, L1-A14; its push, and the " + f"restore form's render, are lane 3's T327):\n{_said(proc)}") + switch = self.switch() + assert (switch["mode"], switch["marker_state"]) == ("primary", "present"), ( + f"{label}: after the cutover B's switch reads {switch['mode']} with the marker " + f"{switch['marker_state']}: the marker's push, read-back and record_marker are lane " + f"3's T327") + assert (switch["database_label"], switch["set_seq"]) == (LABEL_B, seq), ( + f"{label}: B's switch names {switch['database_label']} at set_seq " + f"{switch['set_seq']}, not {LABEL_B} at {seq}") + assert switch["generation"] not in (self.generation_a, self.generation_boot), ( + f"{label}: the after-loss cutover set no new generation: {switch['generation']}") + assert self.journal()[-1] == [seq, "cutover", True], ( + f"{label}: the journal's last entry is not the cutover's operator entry at {seq}: " + f"{self.journal()[-3:]}") + tip = self.origin_tip() + assert self.seqs_of(tip) == [seq] and switch["marker_commit"] == tip, ( + f"{label}: origin's tip {tip[:12]} is not the recorded marker commit carrying " + f"Register-Seq: {seq} (T327)") + assert self.changed_paths(tip) == ["M\tlanes/STORE"], ( + f"{label}: the marker commit does not rewrite lanes/STORE alone: " + f"{self.changed_paths(tip)}") + store = self.store_on_origin(tip) or {} + assert (store.get("store"), store.get("database")) == ("primary", LABEL_B), ( + f"{label}: lanes/STORE on origin does not name B: {store}") + return tip + + def resumed(self) -> None: + """ops 2.3's step 7: `outage clear` on ws1 removes the declaration.""" + cleared = self.host.index("outage", "clear") + assert cleared.returncode == 0 and not self.host.outage_file().exists(), ( + f"[resumption] `outage clear` on ws1 left the declaration (lane 1's T121):\n" + f"{_said(cleared)}") + + +def _estate(request, tmp_path: Path) -> Disaster: + return Disaster(request, tmp_path) + + +# =================================================================== AT-D22 +def test_the_disaster_path_reimports_at_the_mirrors_tip_and_continues_the_sequence(request, + tmp_path): + """AT-D22's re-import: after the loss, B's `--roles-only`, `bootstrap` + and logins, and the re-pointing, `import --at <M> --after-loss` puts B's + head at `m` with its one root there; `cutover --import <M> --after-loss` + writes its operator entry at `m+1`, sets B's label, a new generation and + `set_seq` `m+1`, and pushes `lanes/STORE` naming B; the declaration + cleared, the next write is `m+2`, its render follows the marker commit, + the lag is 0, and the mirror equals a full render from B. Each login's + new password file connects to B, and its old one is refused. Fails until + L1-A7, L1-A13 and T327 land, and lane 4's T415 and T416.""" + estate = _estate(request, tmp_path) + estate.a_to_primary() + estate.a_written() + estate.loss_recorded() + estate.a_destroyed() + estate.b_reimport_route() + tip = estate.reimport() + for login in LOGINS: + assert _connects(estate.b, login, estate.b_db.name, estate.b_files[login]), ( + f"[logins] after the re-import, {login} does not log in to B with its new password " + f"file (T110)") + assert not _connects(estate.b, login, estate.b_db.name, estate.a_files[login]), ( + f"[logins] {login}'s old password file logs in to B") + m = estate.m + marker = estate.marker_rewritten(estate.cutover_after_loss(tip), m + 1, "[cutover]") + estate.resumed() + seq = estate.write("[next write]", "T274: the first write on B") + assert seq == m + 2, f"[next write] the next write is seq {seq}, not m+2 = {m + 2}" + estate.settled(seq, "[next write]") + assert [seqs for _sha, seqs in estate.commits_after(marker)] == [[m + 2]], ( + f"[next write] its render does not follow the marker commit: " + f"{estate.commits_after(marker)}") + problem = estate.mirror_problem() + assert problem is None, f"[mirror] the mirror is not a full render from B: {problem}" + + +def test_a_backup_newer_than_the_mirror_is_restored_and_rendered(request, tmp_path): + """AT-D22's restore: with `m < b < k`, B restored from the dump holds the + journal through `b`, its switch at `primary` with the marker `present` and + A's label, which the second `bootstrap` keeps (every object `unchanged`); + `cutover --after-loss` renders `m+1` to `b`, in order, then writes its + entry at `b+1`, rewriting `lanes/STORE` to name B; the next write is + `b+2`, and `status`'s `m` and `h`, read before B existed, put the loss at + `b+1` to `k`. Fails until L1-A7, L1-A13 and T327 land, and lane 4's T415 + and T416.""" + estate = _estate(request, tmp_path) + estate.a_to_primary() + estate.a_written(backup_after=BACKUP_AFTER) + estate.loss_recorded() + estate.a_destroyed() + again = estate.b_restore_route() + m, b, k = estate.m, estate.b_seq, estate.k + assert m < b < k, f"[backup] not m < b < k: {m}, {b}, {k}" + assert [row[0] for row in estate.journal()] == list(range(0, b + 1)), ( + f"[restore] B's journal is not seqs 0 to b = {b}: {estate.journal()[-4:]}") + switch = estate.switch() + assert (switch["mode"], switch["marker_state"], switch["database_label"]) == ( + "primary", "present", LABEL_A), ( + f"[restore] B's restored switch is not A's, primary with the marker present: {switch}") + states = {state for _what, state in OBJECT_LINE.findall(again.stdout)} + assert states == {"unchanged"}, ( + f"[restore] the second bootstrap did not print unchanged for every object (T109):\n" + f"{_said(again)}") + named = sorted(what for what, _state in OBJECT_LINE.findall(again.stdout)) + assert named == sorted(_restored_inventory(estate.b_db.name)), ( + f"[restore] the second bootstrap does not name each object of a restored register " + f"once (T274g):\n{_said(again)}") + before = estate.origin_tip() + assert max(estate.origin_seqs()) == m, f"[restore] origin is not at m = {m}" + marker = estate.marker_rewritten(estate.cutover_after_loss(None), b + 1, "[cutover]") + rendered = estate.commits_after(before) + assert [seqs for _sha, seqs in rendered] == [[n] for n in range(m + 1, b + 2)], ( + f"[cutover] origin's commits after the restore are not the renders of m+1 to b, in " + f"order, then the marker's at b+1 (lane 3's T327, ops:382): {rendered}") + estate.resumed() + seq = estate.write("[next write]", "T274: the first write on the restored B") + assert seq == b + 2, f"[next write] the next write is seq {seq}, not b+2 = {b + 2}" + estate.settled(seq, "[next write]") + assert [seqs for _sha, seqs in estate.commits_after(marker)] == [[b + 2]], ( + f"[next write] its render does not follow the marker commit") + assert estate.h == k and b + 1 <= k, ( + f"[loss] status's h {estate.h} does not put the loss at b+1 = {b + 1} to k = {k}") + + +def test_an_abort_after_a_restore_form_cutover_restores_every_table_byte_for_byte(request, + tmp_path): + """AT-D22's abort: with the wrapper failing only the push of the commit + carrying `Register-Seq: b+1`, the restore form's cutover pushes the + renders of `m+1` to `b`, proves its own commit absent, and aborts with + 2: the twelve tables, dumped by the admin connection at head `b` before + the cutover, equal the same dump after the abort, byte for byte, and the + head is `b`. Fails until L1-A7, L1-A13 and T327 land, and lane 4's T415 + and T416.""" + estate = _estate(request, tmp_path) + estate.a_to_primary() + estate.a_written(backup_after=BACKUP_AFTER) + estate.loss_recorded() + estate.a_destroyed() + estate.b_restore_route() + m, b = estate.m, estate.b_seq + before_dump, before_tip = _abort_dump(estate.b_db), estate.origin_tip() + assert json.loads(before_dump["register_switch"])[0]["restore_prior"] is None, ( + "[abort] the restored switch already holds a restore_prior") + estate.host.arm(fail_push_seq=b + 1) + proc = estate.cutover_after_loss(None) + first = (proc.stderr.splitlines() or [""])[0] + assert proc.returncode == 2 and "abort" in first.lower(), ( + f"[abort] the cutover whose marker push failed did not abort with 2, its first stderr " + f"line naming the abort (lane 3's T327; cutover_abort):\n{_said(proc)}") + assert [c["seqs"] for c in estate.host.pushes() if c["outcome"] == "failed"] != [], ( + f"[abort] the wrapper failed no push of Register-Seq: {b + 1}") + after = estate.commits_after(before_tip) + assert [seqs for _sha, seqs in after] == [[n] for n in range(m + 1, b + 1)], ( + f"[abort] origin does not hold the renders of m+1 to b and nothing after them: {after}") + assert estate.head() == b, f"[abort] the head is {estate.head()}, not b = {b}" + after_dump = _abort_dump(estate.b_db) + differ = [table for table in ABORT_TABLES if before_dump[table] != after_dump[table]] + assert differ == [], ( + f"[abort] these tables differ from their dump before the cutover: {differ} " + f"(switch_to_files at b+1)") + + +def test_status_prints_the_mirror_tip_and_the_last_head_that_bound_the_loss(request, tmp_path): + """AT-D22's `status` before B exists: with A unreachable it exits 69 and + prints `m`, the mirror tip's `Register-Seq`, and `h`, the last head it + recorded, `k`, with a lag of at least `k - m`: the loss is `m+1` to `k`. + Fails until L1-A13 and T327 land, and lane 4's T415 and T416.""" + estate = _estate(request, tmp_path) + estate.a_to_primary() + estate.a_written() + estate.loss_recorded() + status = estate.host.index("status", timeout=120) + lag = LAG_AT_LEAST.search(status.stdout) + assert status.returncode == 69 and lag and int(lag.group(1)) == estate.k - estate.m, ( + f"[status] the lag with A stopped is not at least k - m = {estate.k - estate.m} " + f"(lane 1's T117):\n{_said(status)}") + assert estate.m < estate.k == estate.h, ( + f"[status] the loss is not m+1 = {estate.m + 1} to k = {estate.k}: h = {estate.h}") + + +def test_the_restore_route_commits_under_the_replacements_register_label_and_check_10_fails_until_it_does( # noqa: E501 + request, tmp_path): + """AT-D22's restore route: on ws1, re-pointed at the restored B with B's + label, `ready`'s check 10 fails naming B's label and A's, since the + restored switch names A's; `cutover --after-loss` sends B's label and + commits; the switch's `database_label` and `lanes/STORE`'s `database=` + then name B, and check 10 is `ok` on the same host. Fails until L1-A7, + L1-A13 and T327 land, and lane 4's T415 and T416.""" + estate = _estate(request, tmp_path) + estate.a_to_primary() + estate.a_written(backup_after=BACKUP_AFTER) + estate.loss_recorded() + estate.a_destroyed() + estate.b_restore_route() + ready = estate.host.index("ready", "--expect", "primary", "--release", RELEASE, "--env", + ENV_NAME) + state, reason = _checks(ready.stdout).get(10, (None, "")) + assert state == "FAIL" and LABEL_A in reason and LABEL_B in reason, ( + f"[check 10] before the cutover check 10 does not fail naming {LABEL_B} and {LABEL_A} " + f"(lane 1's T119):\n{_said(ready)}") + estate.marker_rewritten(estate.cutover_after_loss(None), estate.b_seq + 1, "[cutover]") + ready = estate.host.index("ready", "--expect", "primary", "--release", RELEASE, "--env", + ENV_NAME) + assert _checks(ready.stdout).get(10, (None, ""))[0] == "ok", ( + f"[check 10] after the cutover check 10 is not ok on the same host (T119):\n" + f"{_said(ready)}") + + +def test_an_after_loss_cutover_from_a_host_still_on_the_live_database_is_refused_with_2_and_writes_nothing( # noqa: E501 + request, tmp_path): + """AT-D22's host still on the live database: with A at `primary`, a + configuration that still reaches A with A's `register_label=` runs + `cutover --after-loss`, which sends A's own label, the switch's: it + exits 2, and A's head, its switch row, its journal and `lanes/STORE` on + origin are as they were, with no push. Fails until T327 lands.""" + estate = _estate(request, tmp_path) + estate.a_to_primary() + stale = estate.root / "stale" / "lanes-index.conf" + _private(stale, estate.host.conf.read_text(encoding="utf-8")) + assert _fields(stale.read_text(encoding="utf-8"))["register_label"] == LABEL_A + kept = (estate.head(), estate.switch(), estate.journal(), estate.origin_tip(), + estate.store_on_origin()) + estate.host.arm() + proc = estate.host.index("cutover", "--after-loss", env={"LANES_INDEX_CONFIG": str(stale)}) + assert proc.returncode == 2, ( + f"[live host] an after-loss cutover with A's own label at primary is not refused with 2 " + f"(N4; lane 1's T116):\n{_said(proc)}") + assert (estate.head(), estate.switch(), estate.journal(), estate.origin_tip(), + estate.store_on_origin()) == kept, ( + "[live host] the refused cutover changed A's head, switch row or journal, or origin") + assert estate.host.pushes() == [], f"[live host] it pushed: {estate.host.pushes()}" + + +# =================================================================== AT-F18 +def _restored_inventory(database: str) -> list: + """Every object a full `bootstrap` names on B restored at `primary`, each + once (T274g; Codex's review of P09 at `f4f0ebce`, SHOULD 8): what line R + `9bdd317b`'s `_bootstrap` prints where the switch reads `primary` and no + migration is pending. These are section 1.4's four roles, the admin's + GRANT, the schema, the switch, the head, the three database-level lines + and the privileges line. The admin is the cluster's superuser, through + `admin_service`, and the schema is the default, since the admin's home + holds no configuration.""" + roles = ("lanes_register_owner", "lanes_register_writer", "lanes_register_reader", + "lanes_indexer") + return [*(f"role {role}" for role in roles), + f"the admin {SUPERUSER}'s membership of lanes_register_owner and lanes_indexer, " + f"WITH INHERIT TRUE, SET TRUE", + f"schema {SCHEMA}", "switch", "head", + f"database {database}, REVOKE ALL FROM PUBLIC", + f"database {database}, GRANT CONNECT to lanes_register_writer, " + f"lanes_register_reader and lanes_indexer", + "default privileges of lanes_register_owner, REVOKE EXECUTE ON FUNCTIONS FROM PUBLIC", + f"privileges in the schemas {SCHEMA} and lanes_index"] + + +def _f18_estate(request, tmp_path: Path) -> tuple: + """AT-F18's fixture: D22's re-import, with A written through `m` and the + write in doubt at `m` (see the readings). Returns the estate and the + record, with B bootstrapped and ws1 re-pointed at it.""" + estate = _estate(request, tmp_path) + estate.a_to_primary() + estate.a_written(lost=0) + record = estate.in_doubt_write() + estate.loss_recorded() + estate.a_destroyed() + estate.b_reimport_route() + return estate, record + + +def _cut_over_on_b(estate: Disaster) -> None: + """B's re-import, its after-loss cutover, and the declaration cleared.""" + tip = estate.reimport() + estate.marker_rewritten(estate.cutover_after_loss(tip), estate.m + 1, "[cutover]") + estate.resumed() + + +def test_a_pending_record_from_the_lost_database_is_refused_2_at_the_snapshot(request, tmp_path): + """AT-F18: on B after its cutover, a plain rerun that meets A's record + exits 2 at its first snapshot, naming the write id, both generations, the + effect check and `LANES_WRITE_ID=new`, and leaves the record as it was; + the printed rerun, under A's `LANES_WRITE_GENERATION=`, exits 2 at its + snapshot with LR007's text. The shim logs no commit call for either, and + the journal does not move. Fails until L1-A7, L1-A13 and T327 land, and + lane 4's T412, T415 and T417.""" + estate, record = _f18_estate(request, tmp_path) + _cut_over_on_b(estate) + generation_b = estate.switch()["generation"] + journal = estate.journal() + estate.host.arm() + plain = estate.host.edit(*record["argv"]) + assert plain.returncode == 2 and estate.host.commit_calls() == [], ( + f"[plain rerun] a plain rerun meeting A's record is not refused 2 before any commit " + f"call (lane 4's T412, T415):\n{_said(plain)}") + for said in (record["id"], record["generation"], generation_b, "LANES_WRITE_ID=new"): + assert said in plain.stderr, ( + f"[plain rerun] the refusal does not name {said!r}:\n{_said(plain)}") + assert [p.read_bytes() for p in estate.host.pending()] == [record["bytes"]], ( + "[plain rerun] A's record was not left as it was") + estate.host.arm() + printed = estate.host.edit(*record["argv"], env={ + "LANES_WRITE_ID": record["id"], "LANES_WRITE_GENERATION": record["generation"]}) + assert printed.returncode == 2 and estate.host.commit_calls() == [], ( + f"[printed rerun] the printed rerun under A's generation is not refused 2 at its " + f"snapshot (lane 4's T412, T417):\n{_said(printed)}") + for said in (record["id"], record["generation"], generation_b): + assert said in printed.stderr, ( + f"[printed rerun] the refusal's LR007 text does not name {said!r}:\n{_said(printed)}") + assert estate.journal() == journal, "[reruns] the refused reruns moved the journal" + + +def test_the_printed_rerun_between_a_reimports_bootstrap_and_its_cutover_exits_2_not_69(request, + tmp_path): + """AT-F18: between B's re-import and its cutover, with B's switch at + `files`, the printed rerun under A's generation exits 2, not 69, since + the generation is checked before the switch; it sends no commit call and + the journal holds the import's root alone. Fails until L1-A7, L1-A13 and + T327 land, and lane 4's T412, T415 and T417.""" + estate, record = _f18_estate(request, tmp_path) + estate.reimport() + assert estate.switch()["mode"] == "files" + estate.host.arm() + proc = estate.host.edit(*record["argv"], env={"LANES_WRITE_ID": record["id"], + "LANES_WRITE_GENERATION": record["generation"]}) + assert proc.returncode == 2, ( + f"[between] the printed rerun before B's cutover is not 2 (the generation before the " + f"switch; lane 4's T412, T417):\n{_said(proc)}") + assert estate.host.commit_calls() == [], "[between] the printed rerun sent a commit call" + assert record["id"] in proc.stderr and record["generation"] in proc.stderr, ( + f"[between] the refusal does not name A's write id and generation:\n{_said(proc)}") + assert estate.journal() == [[estate.m, "import", False]], ( + f"[between] the journal moved: {estate.journal()}") + + +def test_lanes_write_id_new_on_the_replacement_replaces_the_old_record_and_writes_once(request, + tmp_path): + """AT-F18's replacement: on B after its cutover, the effect check finds + the write absent; the same command under `LANES_WRITE_ID=new` mints a new + id, writes once, and leaves no record of A's generation; a plain rerun + after it finds no record of A's. Fails until L1-A7, L1-A13 and T327 land, + and lane 4's T412, T415, T416 and T417.""" + estate, record = _f18_estate(request, tmp_path) + _cut_over_on_b(estate) + generation_b = estate.switch()["generation"] + text = record["argv"][-1] + on_b = _rows(estate.db, "SELECT raw FROM log_lines") + assert not any(text in row["raw"] for row in on_b), ( + "[effect check] the write in doubt is already on B") + before = estate.head() + estate.host.arm() + proc = estate.host.edit(*record["argv"], env={"LANES_WRITE_ID": "new"}) + assert proc.returncode == 0, ( + f"[new] the command under LANES_WRITE_ID=new did not write (lane 4's T412, T415):\n" + f"{_said(proc)}") + rows = _rows(estate.db, f"SELECT seq, write_id::text AS id FROM journal WHERE seq > {before} " + f"ORDER BY seq") + assert len(rows) == 1 and rows[0]["id"] != record["id"], ( + f"[new] the journal did not gain exactly one write under a new id: {rows}") + calls = estate.host.commit_calls() + assert len(calls) == 1 and rows[0]["id"] in calls[0]["stdin"] and \ + generation_b in calls[0]["stdin"], ( + f"[new] not one commit call, carrying the new id {rows[0]['id']} and B's generation " + f"{generation_b} (T274f): {len(calls)} call(s)") + left = [p.read_text(encoding="utf-8") for p in estate.host.pending()] + assert not any(record["generation"] in text_ or record["id"] in text_ for text_ in left), ( + "[new] a record of A's generation is left") + again = estate.host.edit(*record["argv"]) + assert again.returncode == 0 and record["id"] not in again.stderr and \ + record["generation"] not in again.stderr, ( + f"[plain rerun] a plain rerun after the replacement met A's record:\n{_said(again)}") + + +@pytest.mark.parametrize("case", ["no-label-reimport", "no-label-restore", "own-label-at-primary", + "reimport-at-files"]) +def test_the_after_loss_cutovers_label_rules_in_the_transaction(pg, case): + """AT-F18's label rules, by direct `commit_write` calls as REGISTER-WRITER + on a bootstrapped register (N4; lane 1's v2.6, behaviour 5): an after-loss + `cutover` entry with no `database_label` is LR004, after an after-loss + import (`[no-label-reimport]`) and on a switch at `primary` with the + marker `present` (`[no-label-restore]`); one that meets that switch with + the switch's own label is LR004 (`[own-label-at-primary]`); each writes + nothing. After an after-loss import at `files`, where the switch holds the + replacement's own label, the label is not compared, and the entry commits + (`[reimport-at-files]`). Fails until T107 and T109 land (L1-A6, L1-A7).""" + labels = LabelRules(pg) + own = labels.switch()["database_label"] + if case in ("no-label-reimport", "reimport-at-files"): + root = labels.commit(labels.head(), labels.import_entry(root_seq=M_DIRECT), "the import") + assert root == M_DIRECT, f"[{case}] the after-loss import's root is {root}, not m" + base = root + else: + base = labels.to_primary() + switch = {"after_loss": True} + if case in ("own-label-at-primary", "reimport-at-files"): + switch["database_label"] = own + kept = labels.state() + proc = labels.send(base, labels.cutover_entry(own, switch=switch)) + if case == "reimport-at-files": + assert proc.returncode == 0, ( + f"[{case}] the re-import form at files with the switch's own label did not commit " + f"(T107):\n{_said(proc)}") + after = labels.switch() + assert (after["mode"], after["database_label"], after["set_seq"], labels.head()) == ( + "primary", own, base + 1, base + 1), f"[{case}] after the entry: {after}" + assert after["generation"] != kept["switch"]["generation"], ( + f"[{case}] the after-loss entry kept the generation") + else: + assert proc.returncode != 0 and "LR004" in proc.stderr, ( + f"[{case}] the entry is not refused with LR004 (N4; T107):\n{_said(proc)}") + assert labels.state() == kept, f"[{case}] the refused entry wrote something" + + +def test_bootstrap_roles_only_makes_the_roles_and_no_schema(request, tmp_path): + """AT-F18: on cluster B, new, with no register role, `bootstrap + --roles-only` through the admin service makes the owner, the two groups + and the indexer, and no schema; and the three database-level statements + hold as T224's `dump_restore_privileges` asserts them: PUBLIC has no + CONNECT on the database, the writer, the reader and the indexer have it, + and the owner's global default privilege gives PUBLIC no EXECUTE on its + functions. Fails until T109 lands (L1-A7).""" + estate = Roles(request, tmp_path) + found = estate.roles() + assert found == [], f"[roles-only] B already has register roles: {found}" + estate.roles_only() + assert estate.roles() == sorted(REGISTER_ROLES), ( + f"[roles-only] B's register roles after --roles-only: {estate.roles()}") + schemas = _value(estate.db, f"SELECT count(*) FROM pg_namespace WHERE nspname = '{SCHEMA}';") + assert schemas == "0", "[roles-only] --roles-only created the register's schema" + acl = _value(estate.db, f"SELECT coalesce(datacl::text, '') FROM pg_database " + f"WHERE datname = '{estate.db.name}';") + assert not re.search(r"(^|[{,])=[A-Za-z]*c", acl), f"[roles-only] PUBLIC holds CONNECT: {acl}" + estate.db.psql("CREATE ROLE t274_outsider NOLOGIN;") + assert _value(estate.db, f"SELECT has_database_privilege('t274_outsider', " + f"'{estate.db.name}', 'CONNECT');") == "f", ( + "[roles-only] a role outside the register may connect") + for role in (WRITER_GROUP, "lanes_register_reader", "lanes_indexer"): + assert _value(estate.db, f"SELECT has_database_privilege('{role}', '{estate.db.name}', " + f"'CONNECT');") == "t", f"[roles-only] {role} holds no CONNECT" + default = _value(estate.db, "SELECT coalesce(string_agg(defaclacl::text, ' '), '') FROM " + "pg_default_acl WHERE defaclrole = 'lanes_register_owner'::regrole " + "AND defaclnamespace = 0 AND defaclobjtype = 'f';") + assert default and not re.search(r"(^|[{,])=[A-Za-z]*X", default), ( + f"[roles-only] the owner's global default privilege on functions is {default!r}: PUBLIC " + f"keeps EXECUTE, or the statement made no row") + + +def test_the_disaster_path_rewrites_the_marker_by_the_after_loss_cutover(request, tmp_path): + """AT-F18: the marker is rewritten by the cutover's own entry in its + after-loss form at `m+1`, never a third operator entry: `lanes/STORE`'s + `database=` names B, and in its life on B the journal holds exactly two + operator entries, the cutover's at `m+1` and, after the smoke test and a + later rollback, the rollback's. Fails until L1-A7, L1-A13 and T327 land, + and lane 4's T415 and T416, T304 and lane 3's T326.""" + estate, _record = _f18_estate(request, tmp_path) + _cut_over_on_b(estate) + m = estate.m + seq = estate.write("[smoke]", "T274: the smoke test on B") + estate.settled(seq, "[smoke]") + proc = estate.host.index("rollback") + assert proc.returncode == 0, ( + f"[rollback] the rollback on B (T304, lane 3's T326):\n{_said(proc)}") + switch = estate.switch() + assert (switch["mode"], switch["marker_state"]) == ("files", "absent"), ( + f"[rollback] after the rollback B's switch is {switch}") + operators = [row[:2] for row in estate.journal() if row[2]] + assert operators == [[m + 1, "cutover"], [seq + 1, "rollback"]], ( + f"[marker] B's journal does not hold exactly the after-loss cutover's and the " + f"rollback's operator entries: {operators}") + + +# ------------------------------------------------------------------ the direct calls +#: The label rules' after-loss import root, an `m` of the test's own. +M_DIRECT = 7 +#: What the direct entries carry (AT-LR006's, T273's). +COMMIT_C, TREE_C, MARKER_COMMIT = "c" * 40, "d" * 40, "e" * 40 +NOT_AFTER = "2100-01-01T00:00:00Z" +LANES_MD = ["# Lanes"] +DIRECT_LANE, DIRECT_WS = "t274-operator", "ws-t274" +DIRECT_AUTHOR = "T274 operator <t274@example.invalid>" + + +def _sha(lines) -> str: + return hashlib.sha256(("\n".join(lines) + "\n").encode("utf-8")).hexdigest() + + +def _entry(kind: str, **parts) -> dict: + """One `commit_write` entry: the journal object, `not_after`, and `parts`.""" + journal = {"kind": kind, "verb": kind, "lane": DIRECT_LANE, "workstation": DIRECT_WS, + "author": DIRECT_AUTHOR, "message": f"t274: {kind}"} + journal.update(parts.pop("journal", {})) + return {"journal": journal, "not_after": NOT_AFTER, **parts} + + +class LabelRules: + """A clone of the session's template (T227), bootstrapped with its label, + and `commit_write` sent as the writer sends it, as REGISTER-WRITER.""" + + def __init__(self, pg): + self.db = pg + + def psql(self, script: str, role: str | None = None) -> subprocess.CompletedProcess: + head = "\\set VERBOSITY verbose\n\\set SHOW_CONTEXT never\nSET client_encoding = 'UTF8';\n" + if role: + head += f"SET ROLE {role};\n" + return subprocess.run([self.db.psql_bin, "-X", "-q", "-A", "-t", "-v", "ON_ERROR_STOP=1"], + input=head + script, capture_output=True, encoding="utf-8", + errors="replace", env=self.db.env(appname="t274"), timeout=120, + check=False) + + def switch(self) -> dict: + return _rows(self.db, "SELECT * FROM register_switch")[0] + + def head(self) -> int: + return _rows(self.db, "SELECT seq FROM register_head")[0]["seq"] + + def state(self) -> dict: + return {"switch": self.switch(), "head": self.head(), + "journal": _rows(self.db, "SELECT seq, kind FROM journal ORDER BY seq"), + "files": _rows(self.db, "SELECT path, final_newline, sha256, last_seq FROM files " + "ORDER BY path")} + + def send(self, base: int, entry: dict) -> subprocess.CompletedProcess: + literal = json.dumps(entry, ensure_ascii=True).replace("'", "''") + version = _rows(self.db, "SELECT version FROM schema_version")[0]["version"] + return self.psql(f"BEGIN ISOLATION LEVEL SERIALIZABLE;\n" + f"SELECT {SCHEMA}.commit_write({base}, '{uuid.uuid4()}'::uuid, " + f"{version}, '{self.switch()['generation']}'::uuid, " + f"'{literal}'::jsonb);\nCOMMIT;\n", WRITER_GROUP) + + def commit(self, base: int, entry: dict, what: str) -> int: + proc = self.send(base, entry) + assert proc.returncode == 0, f"[setup] {what}: commit_write refused it:\n{_said(proc)}" + return int(proc.stdout.strip().splitlines()[-1]) + + def import_entry(self, **parts) -> dict: + edits = [{"ord": 1, "op": "create", "path": "lanes/LANES.md"}] + edits += [{"ord": n, "op": "append", "path": "lanes/LANES.md", "new_text": text} + for n, text in enumerate(LANES_MD, start=2)] + return _entry("import", journal={"git_commit": COMMIT_C, "git_tree": TREE_C}, + edits=edits, files=[{"path": "lanes/LANES.md", "present": True, + "sha256": _sha(LANES_MD), "final_newline": True}], + **parts) + + def cutover_entry(self, label: str, **parts) -> dict: + lines = ("store=primary", f"database={label}", f"import={COMMIT_C}", + f"lanes-tree={TREE_C}", "utc=2026-11-12T00:00:00Z") + edits = [{"ord": 1, "op": "create", "path": "lanes/STORE"}] + edits += [{"ord": n, "op": "append", "path": "lanes/STORE", "new_text": line} + for n, line in enumerate(lines, start=2)] + return _entry("cutover", edits=edits, files=[{"path": "lanes/STORE", "present": True, + "sha256": _sha(lines), + "final_newline": True}], **parts) + + def to_primary(self) -> int: + """AT-LR006's route: an import at 0, a cutover over it, then + `record_marker`. Returns the head.""" + imported = self.commit(self.head(), self.import_entry(), "the import") + own = self.switch()["database_label"] + cut = self.commit(imported, self.cutover_entry(own), "the cutover") + version = _rows(self.db, "SELECT version FROM schema_version")[0]["version"] + proc = self.psql(f"SELECT {SCHEMA}.record_marker({version}, {cut}, '{MARKER_COMMIT}', " + f"'{DIRECT_WS}');", WRITER_GROUP) + assert proc.returncode == 0 and proc.stdout.strip().endswith("present"), ( + f"[setup] record_marker did not answer present:\n{_said(proc)}") + switch = self.switch() + assert (switch["mode"], switch["marker_state"]) == ("primary", "present"), switch + return cut + + +class Roles: + """Cluster B alone, new, for `--roles-only`: a TLS cluster whose template + holds nothing, its one database the register's, and the admin service + naming it.""" + + def __init__(self, request, root: Path): + engine = request.getfixturevalue("pg_engine") + cluster = TLSCluster(engine.bindir, "") + try: + cluster.start() + except (ClusterError, OSError, subprocess.SubprocessError) as exc: + cluster.destroy() + raise AssertionError(f"[B] the replacement's cluster did not start: {exc}") from exc + request.addfinalizer(cluster.destroy) + self.cluster, self.db = cluster, Database(cluster, cluster.database_name) + + def roles(self) -> list: + names = ", ".join(f"'{role}'" for role in REGISTER_ROLES) + return sorted(_value(self.db, f"SELECT string_agg(rolname, ' ') FROM pg_roles " + f"WHERE rolname IN ({names});").split()) + + def roles_only(self) -> None: + proc = self.cluster.lanes_index(["bootstrap", "--admin-service", + self.cluster.admin_service(self.db.name), + "--roles-only", "--no-passwords"]) + assert proc.returncode == 0, ( + f"[roles-only] `bootstrap --roles-only` through the admin service failed (lane 1's " + f"T109, L1-A7):\n{_said(proc)}") diff --git a/tests/test_sql_register_divergence.py b/tests/test_sql_register_divergence.py new file mode 100644 index 00000000..d22bb16e --- /dev/null +++ b/tests/test_sql_register_divergence.py @@ -0,0 +1,1619 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Feature 007's test 6, a stray commit and its two ways out, with AT-MIR's +gating case and the model of the server-side gate (L2-G2; L2-G5's AT-MIR +gating case; AT-6; AT-MIR; T271; FR-047, FR-048, FR-059; US6) +(opensoft/openRepoTools#165). + +T271 writes this module: 11 tests, 10 from AT-6 (9) and AT-MIR (1), and one +new since v3f, R-F10-34's, which holds lane 3's two strays for T324, +R-F13c-10's third id and, new in B15, lane 3's L2-8 fourth, +`[stray-no-longer-applies]`. Lane 3's T324 runs the whole module by its +word, `sql_register_divergence`. + +THE V1.1.0 WRITER (PC-12; the test plan's open point 5). +`tests/fixtures/lanes-edit-v1.1.0/lanes-edit.sh` is `lanes-edit.sh` byte for +byte as code `2a057a6d` (tag `v1.1.0`) holds it: blob `d28ed8f2`, 1139720 +bytes. CI checks out at depth 1 with no tags, so the copy is the only way the +suite runs the real old writer. Its digest is recorded twice: in +`tests/fixtures/lanes-edit-v1.1.0/SHA256SUMS`, in `sha256sum`'s form, and in +this module's `V110_SHA256`, beside its git blob id and size. Every case that +runs it calls `v1_1_0_writer()` first, which checks all four, so a drift in +the fixture fails loudly instead of testing something else (AT-6, +"Flakiness"). The copy is never run from its own directory's neighbours: no +`lanes-index` and no `repos.tsv` sit beside it, and the stale clone's `PATH` +masks `lanes-index`, so it makes no index nudge. + +THE ESTATE (AT-6, "Fixture"), `Estate`, built inside each case so that a +step a lane has not built fails the case at its own assertion: + +- the fixture register at C: a files-mode workspace on a bare origin + (`Workspace`), its seed `SEED`, and a files-mode `log NOTED` on top as the + operator lane, so C's tip is bytes `lanes-edit.sh` wrote, as test 7's + fixture register is built; +- imported on `pg` by `lanes-index import --at <C>` (lane 1's T115), as the + operator lane through its checkout; +- the cutover by AT-LR006's route (TP:4610-4615): `commit_write` with a + `cutover` entry, as REGISTER-WRITER, then the marker commit, `lanes/STORE` + with D21's fields and `Register-Seq: 1`, pushed to the bare origin as a + fast-forward of C, then `record_marker`, so the switch reads `primary` + with the marker `present`. Neither T116 nor T327 is in T271's Order, so the + estate runs neither `cutover` nor its push; +- each primary write is a `commit_write` call of a `write` entry, as + REGISTER-WRITER (AT-LR006's "one write"), that appends a line of no kind to + `lanes/LANES.md`, so it carries no structured row; and each render a fork + would start is `lanes-index render --checkout <c>` run by the case, as a + fork runs it (TP:1160-1167), in the operator lane's checkout. Lane 4's + writes on primary and their fork (T415, T416) are not in T271's Order. + +The commands run from the operator lane's checkout, `LANES_LANE=repoA-2`, by +T203's flipped copy of `lanes-index` (`RENDER_GIT_HALF = True`), which the +renderer and the two ways out need on `lanes_register`; `import --at` runs the +shipped `lanes-index`, as test 7's does. Their configuration names the +session cluster's socket as its superuser, as test 7's does. + +THE STALE WORKSTATION (AT-6, "Fixture"), `StaleWorkstation`: a clone of +origin with a home, a workspace pointer and a lane of its own (`repoW-1`), no +`lanes-index` configuration, and the v1.1.0 writer. Its `log NOTED` pushes a +commit changing `lanes/log/repoW-1.md`; it knows no marker. + +THE WAITS (open point 8). The stop is read after the renderer's exit: the +case runs the render itself, in the foreground, so its exit is the wait. +Where the lag must reach 0, the case polls `lanes-index status` every 100 ms +until it prints a lag of 0, with a 30 s ceiling, after a render of its own; +a render a way out forks itself is the same render lock's, so the case's own +render then marks a rerun and the poll waits for both. + +THE GATE MODEL (AT-6, "Options", Q21(b)): `GATE_HOOK`, a pre-receive hook in +the bare origin, refuses a push whose commits change a path of the render +set or `lanes/STORE` (`lanes/LANES.md`, `lanes/log/<lane>.md`, +`lanes/aliases.tsv`, anything under `lanes/archive/`, and `lanes/STORE`), and +lets every other path through, `lanes/repos.tsv` and `lanes/log/README.md` +among them. It is a model: the suite cannot reach GitHub. Its two tests need +no engine. + +WHAT EACH FAILS UNTIL (T271's Order, B15 tasks:2487): it waits for T205, +and its tests fail until L1-A6, L1-A15, T322, T324 and T326 land. Case by +case: the estate needs lane 1's T107 (`commit_write`, `record_marker`, +`record_mirror_state`; L1-A6) and T115 (`import --at`, L1-A13), and each +case reads `status` (T117, L1-A15) and runs the renderer's pass (lane 3's +T321 to T323). Then: + +- the stop, the row's two ids and the three commits outside the render set + fail until those alone; +- `test_status_prints_diverged_at_the_stray_sha_and_reconcile_imports_nothing` + also fails until T325, whose re-render gives `reconcile` the renderer's 1 + for a recorded `diverged at`, where T117's check alone, like `--dry-run`, + exits 0 (lane 3, #165 6809045090, L2-6); +- the two ways out, the strays and the `Register-Seq` above the head fail + until T324 too; +- `test_rollback_works_after_each_way_out` and the `Register-Seq` case's last + part fail until T326 (the rollback's render and push); +- `[stray-revives-a-pair]` fails until T324's refusal and T107's + `one_live_claim`; `[stray-no-longer-applies]` also fails until T324's + `import --single` refusal (lane 3, #165 6809045090, L2-8); the other two + strays' oracle needs T115's `import --at`; +- the gate model's seven ids wait for nothing: they test the model and the + pinned copy, and pass now. + +COPIED, NOT SHARED (lane 2's rule for wave 12: no module imports another's +helpers). From `test_sql_register_import.py` (line W3a at T211m, `c9989b5`): +`Workspace`, the fixture register's `config` and `import_at`, +`flipped_indexer`, `_rows`, `_renders`, `RENDER_SET`, `REGISTER_SEQ` and +`LAG_0`. From `test_sql_register_landing_expired.py` (line LX at T253e, +`e9b949e`): `_masked_path`, with its mirrors. From +`test_sql_register_schema.py` (line W3b at T221j, `0154c91`): `STRUCTURED` +and `structured`, T221's step-6 comparison, and the commit call's form. From +`test_sql_register_rollback.py` (line RB at T273b, `35b616ff`): test 8's first +oracle, `_assert_rolled_back`, and `_said`. + +READINGS, NOT FOUND IN A CONTRACT: + +- "A later primary write still commits to SQL" is a `commit_write` of a + `write` entry that returns the next seq while `diverged at` is recorded. +- "SQL writes refused", in test 8's first oracle, is `commit_write`'s LR002 + for a `write` entry once the switch reads `files`, with the head unmoved. +- "Its line edits equal the stray commit's diff": the v1.1.0 writer's stray + appends lines to one log, so the entry's edits are one `append` per added + line, in order, on that path. +- A revert's message "names" the stray where it holds the stray's first 7 + hex digits, git's shortest abbreviation, or more; its `git_commit` is the + full sha (design.md's kinds paragraph). +- "Its render commit puts SQL's state back over the stray" is read over the + render commits that follow the stray up to the revert's seq: a write that + lands between the stray and the revert is rendered first and already puts + the stray's path back (design.md's prototype note on the import), so on + each path the stray changed, the tip after the resume equals the stray's + parent. +- "The pending seqs reach origin in order": the `Register-Seq` values of the + commits after the stray, oldest first, are each seq from `m+1` to the head, + once each. +- "Between renders": the `repos.tsv` and `handoffs/` commits land after a + render of their own estate's first write; the cutover's `lanes/STORE` + commit is origin's tip when the first render starts. +- The negative and the row-only cases' "status shows no divergence" is + `status`'s `divergence: none recorded` line, where the row is empty. +- `[stray-revives-a-pair]`'s "writes nothing" also leaves `mirror_state` + recording the stray. +- `[stray-no-longer-applies]`'s "a primary write changes a line after the + stray commit changed it": the stray retitles `lanes/LANES.md`'s first + line, its heading, a line of no kind, by hand; then a `commit_write` of a + `write` entry replaces the same line in SQL with other text, by its old + text's digest. So the stray's one edit, a `replace` at line 1, finds there + a line its parent never held. +- Its "sends no commit call" is read through a `psql` first on the import's + `PATH` that logs each call's stdin, where `lanes-index` sends each request: + no request holds `commit_write(`, and at least one was sent, since the + refusal reads SQL's images. Its "naming the edit" is stderr naming the + edit's path and that its edits "no longer apply" (TP:1292). Its "writes + nothing" is the head, the journal's count, the four structured tables and + SQL's images as they were, `mirror_state` still recording the stray, and + origin's tip still the stray. +- The ways out run "on a person's word from the operator lane's checkout" + (TP:1276-1277), where that person's git names an author: the checkout's + own `user.name` and `user.email` name `AUTHOR`, set once C is made. A way + out removes every inherited `GIT_*` variable before it asks git (D12), so + the module's `GIT_AUTHOR_*` variables, which still sign the estate's own + commits, cannot name it; T324 as built refuses with 2 where git names no + author there. +- The stale clone's `sleep` is a stub that returns at once, so the v1.1.0 + writer's six push attempts, three seconds apart, take no time; what it + does at each attempt is unchanged. + +RULED BY LANE 3 (#165 6809045090; its RULINGS-batch-e-analysis-20261111.md, +L2-6 to L2-8; B15 folds them): + +- L2-6: AT-6's stop stands (TP:1285): `reconcile` exits non-zero on a + diverged mirror once T325 lands. T325 re-renders what the mirror lacks + through T322's pass, and the pass's recorded stop, `diverged at` among + them, is the renderer's 1 (exit-codes.md section 3.4's `reconcile` 1 + row). T117's check alone, like `reconcile --dry-run`, exits 0 whatever it + found. So the status case asserts 1, the code the contract names, and + fails until T325. +- L2-7: T117 is right. With `m` above the head there is no lag (Y:2850): + until a revert names `R`, its `Register-Seq` counts, so `m` = `h`+10 is + past `n` = `h`+1, and `status` prints the lag as "none, and the mirror's + <m> is past n <n>" (TP:1319 at B15: "no lag: its `m` is past `n` + (Y:2850), as `status` says"). The `Register-Seq` case asserts that line, + naming `h`+10 and `h`+1. The plain stray's "a lag of at least 1" + (TP:1284) stands: that stray carries no `Register-Seq`. +- L2-8: AT-6's "case of its own", the import's refusal where the stray's + edits no longer apply to SQL's images (TP:1292-1293), is + `[stray-no-longer-applies]`, a fourth id of the strays' function beside + `[stray-revives-a-pair]`, whose LR005 is the other refusal: `import + --single` refuses with 2 before any commit call, naming `render --revert + <sha>` as the way out (PC-4; T324 `9a664ef`:16115-16117), writes nothing, + and leaves the tables unchanged (B15 tasks:2486). It fails until T324's + refusal. +""" + +from __future__ import annotations + +import atexit +import base64 +import hashlib +import json +import os +import re +import shlex +import shutil +import subprocess +import sys +import tempfile +import time +import uuid +from pathlib import Path + +import pytest + +from conftest import REPO, WINDOWS_SKIP +from pgcluster import Database + +pytestmark = [WINDOWS_SKIP, pytest.mark.skipif( + shutil.which("bash") is None or shutil.which("git") is None, + reason="the lane tooling is bash over git")] + +# ------------------------------------------------------------------ the landing gate +#: THE LANDING GATE'S TABLE (T280; task sets version 12b's rule 11, +#: opensoft/openRepoTools#165 6877673742), read by `tests/sql_register_gate.py`. +#: Where the gate is active, an id whose tasks have not all landed is skipped, +#: and the skip names them; an id waits for the `"*"` row and its own. T281 +#: removes this block in the last set. It is T271's Order (tasks:2489 at lane +#: 3's commit 17, 204145ae), as lane 2's plan GP-24 keys it (sha256 16d738b9): +#: +#: - `"*"`: the module's tests fail until L1-A6 (T107, T108), L1-A15 (T117), +#: T322, T324 and T326. The gate model's seven ids need none of them (their +#: docstrings: "waits for nothing"), but the Order names the module's tests +#: whole, so `"*"` holds them too; +#: - the status case also fails until T325 (lane 3's L2-6): its own row; +#: - `[stray-no-longer-applies]`'s T324, and `[stray-revives-a-pair]`'s T324 +#: and T107, are in `"*"` already. The two other strays' T115 (L1-A13) has +#: no row: it lands in an earlier set than T326, so a row would hold no id +#: longer. +SQL_REGISTER_GATE_TABLE = { + "*": ("T107", "T108", "T117", "T322", "T324", "T326"), + "test_status_prints_diverged_at_the_stray_sha_and_reconcile_imports_nothing": ("T325",), +} + +LANES_EDIT = REPO / "lanes-edit.sh" +INDEXER = REPO / "lanes-index" + +# ------------------------------------------------------------------ the v1.1.0 writer +#: PC-12's copy and its pin (see the module's docstring). +FIXTURE_DIR = Path(__file__).resolve().parent / "fixtures" / "lanes-edit-v1.1.0" +V110 = FIXTURE_DIR / "lanes-edit.sh" +V110_SUMS = FIXTURE_DIR / "SHA256SUMS" +V110_COMMIT = "2a057a6d84e58c8acb4bda20d2b7b667b552c3fe" +V110_BLOB = "d28ed8f2d18adcabc4483eaf2a9424410e288cc6" +V110_SHA256 = "b68d0cbac35ac3bbac9e70790cafe63538821be582ca28cec0f7ec0f5c4745d2" +V110_SIZE = 1139720 + + +def v1_1_0_writer() -> Path: + """The pinned v1.1.0 `lanes-edit.sh`, once its bytes are proved: its + size, its sha256 against this module's pin and against `SHA256SUMS`, and + its git blob id against the tag's. Any drift fails here, loudly.""" + assert V110.is_file(), f"PC-12's copy of the v1.1.0 writer is missing: {V110}" + data = V110.read_bytes() + sums = V110_SUMS.read_text(encoding="ascii") if V110_SUMS.is_file() else None + assert sums == f"{V110_SHA256} lanes-edit.sh\n", ( + f"{V110_SUMS} does not record the pinned digest {V110_SHA256} (PC-12): {sums!r}") + got = (len(data), hashlib.sha256(data).hexdigest(), + hashlib.sha1(b"blob %d\0" % len(data) + data).hexdigest()) + assert got == (V110_SIZE, V110_SHA256, V110_BLOB), ( + f"{V110} is not lanes-edit.sh as v1.1.0 ({V110_COMMIT[:8]}) holds it: size, sha256 and " + f"blob {got}, pinned {(V110_SIZE, V110_SHA256, V110_BLOB)}. The fixture drifted, so " + f"test 6 would test something else (PC-12; open point 5)") + return V110 + + +# ------------------------------------------------------------------ the register +EM, DOT, ARROW = chr(0x2014), chr(0xB7), chr(0x2192) + +#: The register's schema, `register_schema=`'s default, and the writer's group. +SCHEMA = "lanes_register" +WRITER = "lanes_register_writer" +#: The operator lane (lane 1's T115: "It runs with `LANES_LANE=<operator +#: lane>`, through that lane's checkout"), its workstation and git's author. +OPERATOR = "repoA-2" +WS = "Eagle" +AUTHOR_NAME, AUTHOR_EMAIL = "T271 operator", "t271@example.invalid" +AUTHOR = f"{AUTHOR_NAME} <{AUTHOR_EMAIL}>" +#: The label the configuration's `register_label=` and `lanes/STORE` carry. +LABEL = "t271" +#: The stale workstation's lane and name. +STALE_LANE = "repoW-1" +STALE_WS = "Stale" + +ARGS_SHA256 = "a" * 64 +NOT_AFTER = "2100-01-01T00:00:00Z" +STORE_UTC = "2026-11-11T10:00:00Z" + +UUID_A2 = "aaaaaaaa-0003-4000-8000-00000000a003" +UUID_D1 = "dddddddd-0002-4000-8000-00000000d002" +UUID_I1 = "11111111-0001-4000-8000-000000001001" +UUID_W1 = "eeeeeeee-0002-4000-8000-00000000e002" +UUID_X1 = "cccccccc-0001-4000-8000-00000000c001" +UUID_Y1 = "cccccccc-0002-4000-8000-00000000c002" +UUID_Z1 = "eeeeeeee-0001-4000-8000-00000000e001" + +#: The object two lanes held, one after the other: repoX-1 claimed and +#: released it, then repoY-1 claimed it. One claim is live at C, so the +#: import marks no pair `exempt`. +PAIR_OBJECT = "opensoft/repoQ#1" + + +def _row(lane: str, uid: str, state: str) -> str: + return (f"| `{lane}` | harness `{uid}` | Eagle / test / brett | 2026-10-01T00:00Z | none | " + f"handoffs/{lane}.md | {state} |") + + +def _started(lane: str, uid: str, home: str, utc: str = "2026-10-01T00:00:00Z") -> str: + return (f"STARTED {EM} lane {lane}, session {uid}@Eagle, {utc}, lane:{lane} {ARROW} home " + f"{home}; dir /work/{lane}") + + +def _line(verb: str, lane: str, uid: str, utc: str, obj: str, text: str) -> str: + return f"{verb} {EM} lane {lane}, session {uid}@Eagle, {utc}, {obj} {EM} {text}" + + +def _log(lane: str, *lines: str) -> str: + return "\n".join([f"# lane {lane} {EM} object log (lane-collision-protocol Amendment 7)", + *lines, ""]) + + +#: The row the first stray deletes, with no archive copy. +ROW_D = _row("repoD-1", UUID_D1, f"PAUSED {DOT} 2026-10-02T00:00:00Z {DOT} a row a stray deletes") +#: The release the third stray deletes, which revives repoX-1's claim. +RELEASED_X = _line("RELEASED", "repoX-1", UUID_X1, "2026-10-01T03:00:00Z", PAIR_OBJECT, + "handed back") +#: The line the second stray inserts before its log's end. +INSERTED_I = _line("NOTED", "repoI-1", UUID_I1, "2026-10-03T00:00:00Z", "lane:repoI-1", + "a line a person inserted by hand") +#: `lanes/LANES.md`'s first line, a heading of no kind. The fourth stray +#: retitles it by hand, then a primary write retitles it in SQL (L2-8). +TITLE = f"# LANES.md {EM} test 6's register" +TITLE_BY_HAND = TITLE + ", retitled by hand" +TITLE_IN_SQL = TITLE + ", retitled by a primary write" + +#: C's files, before the `lanes-edit.sh` write on top. `lanes/repos.tsv` and +#: `lanes/log/README.md` are outside the render set (Q18 (A)). +SEED = { + "lanes/LANES.md": "\n".join([ + TITLE, + "", + "| lane | session id | workstation / env / user | started (UTC) | objects owned | " + "handoff path | state |", + "|---|---|---|---|---|---|---|", + _row("repoA-2", UUID_A2, f"LIVE {DOT} 2026-10-01T02:00:00Z {DOT} the operator lane"), + _row("repoW-1", UUID_W1, f"LIVE {DOT} 2026-10-02T00:00:00Z {DOT} the stale workstation"), + _row("repoX-1", UUID_X1, f"LIVE {DOT} 2026-10-01T00:00:00Z {DOT} it released repoQ#1"), + _row("repoY-1", UUID_Y1, f"LIVE {DOT} 2026-10-01T00:00:00Z {DOT} it holds repoQ#1"), + ROW_D, + _row("repoI-1", UUID_I1, f"LIVE {DOT} 2026-10-01T00:00:00Z {DOT} a log with claims"), + "", + ]), + "lanes/log/README.md": "# the object logs\n", + "lanes/repos.tsv": "# alias\towner/repo\nrepoE\topensoft/repoE\n", + "lanes/aliases.tsv": "# old\tnew\tutc\nrepoOld-1\trepoA-2\t2026-09-30T00:00:00Z\n", + "lanes/archive/LANES-retired.md": "\n".join([ + "# retired rows (Amendment 19(d))", "", + _row("repoZ-1", UUID_Z1, f"RETIRED {DOT} 2026-09-02T00:00:00Z {DOT} retired"), ""]), + "lanes/log/repoA-2.md": _log("repoA-2", _started("repoA-2", UUID_A2, "opensoft/repoA")), + "lanes/log/repoW-1.md": _log("repoW-1", _started("repoW-1", UUID_W1, "opensoft/repoW")), + "lanes/log/repoX-1.md": _log( + "repoX-1", _started("repoX-1", UUID_X1, "opensoft/repoQ"), + _line("CLAIMED", "repoX-1", UUID_X1, "2026-10-01T01:00:00Z", PAIR_OBJECT, "mine"), + RELEASED_X), + "lanes/log/repoY-1.md": _log( + "repoY-1", _started("repoY-1", UUID_Y1, "opensoft/repoQ"), + _line("CLAIMED", "repoY-1", UUID_Y1, "2026-10-01T04:00:00Z", PAIR_OBJECT, + "after repoX-1 let it go")), + "lanes/log/repoI-1.md": _log( + "repoI-1", _started("repoI-1", UUID_I1, "opensoft/repoI"), + _line("CLAIMED", "repoI-1", UUID_I1, "2026-10-01T01:00:00Z", "opensoft/repoI#1", "one"), + _line("CLAIMED", "repoI-1", UUID_I1, "2026-10-01T01:10:00Z", "opensoft/repoI#2", "two"), + _line("OPENED", "repoI-1", UUID_I1, "2026-10-01T01:20:00Z", "opensoft/repoI#3", + "three")), +} + +#: The render set (Q18 (A); CLI4.10 section 3.6): `lanes/LANES.md`, +#: `lanes/aliases.tsv`, each `lanes/log/<lane>.md` but the README, and the +#: archive. `lanes/STORE` is the marker, never rendered. +RENDER_SET = re.compile(r"^lanes/(LANES\.md|aliases\.tsv|archive/[^/]+\.md" + r"|log/(?!README\.md$)[^/]+\.md)$") +#: The trailer each mirror commit and the marker commit carry (section 1.3). +REGISTER_SEQ = re.compile(r"^Register-Seq: ([0-9]+)$", re.M) +#: `status`'s lag line (lane 1's T117): at 0, and as a number of seqs. +LAG_0 = re.compile(r"^\s*lag:\s+0 seq", re.M) +LAG_N = re.compile(r"^\s*lag:\s+([0-9]+) seq", re.M) +#: ... and with `m` above `n` at `primary`, no lag (R2's N6; Y:2850; lane 3's +#: L2-7): "none, and the mirror's <m> is past n <n>". +LAG_PAST_N = re.compile(r"^\s*lag:\s+none\b[^\n]*?\b([0-9]+) is past n ([0-9]+)", re.M) +NO_DIVERGENCE = re.compile(r"^\s*divergence:\s+none recorded", re.M) + + +def _said(proc) -> str: + return (f"exit {proc.returncode}\n--- stdout ---\n{(proc.stdout or '')[-3000:]}" + f"\n--- stderr ---\n{(proc.stderr or '')[-3000:]}") + + +def _sha256(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +# ------------------------------------------------------------------ the PATH mask +#: `_masked_path`'s mirrors, by each directory's real path (None where the +#: directory holds no masked name), and the one temporary root they share. +_PATH_MIRRORS: dict = {} +_PATH_MIRROR_ROOT: list = [] + + +def _masked_path() -> str: + """The caller's PATH with every directory kept in its place, and each one + that holds a `psql`, a `lanes-index` or a name that starts `pg_` swapped + for a private mirror of it: a directory of links, one to each of its + entries by its absolute path, those names left out. An installed + indexer, a real `psql` or one of the `pg_` client wrappers shipped beside + it is never what a case runs, but the tools beside them are: on a GitHub + runner `postgresql-16`'s client puts `psql` in `/usr/bin` with `git` and + `bash` (and `/bin` is a link to it), so dropping the directory would drop + `git` and `bash` too (lane 1's census, #165 6807454856). A directory that + holds none of those names passes through unchanged. Each mirror is made + once per process, under one `mkdtemp` that an `atexit` handler removes. + The estate's commands reach the session cluster's `psql` through a + directory of their own, first on their `PATH`.""" + parts = [] + for part in os.environ.get("PATH", "").split(os.pathsep): + if not part: + continue + real = os.path.realpath(part) + if real not in _PATH_MIRRORS: + try: + names = os.listdir(real) + except OSError: + names = [] + masked = {name for name in names + if name in ("psql", "lanes-index") or name.startswith("pg_")} + mirror = None + if masked: + if not _PATH_MIRROR_ROOT: + _PATH_MIRROR_ROOT.append(tempfile.mkdtemp(prefix="l2-pathmask-")) + atexit.register(shutil.rmtree, _PATH_MIRROR_ROOT[0], ignore_errors=True) + mirror = os.path.join(_PATH_MIRROR_ROOT[0], str(len(_PATH_MIRRORS))) + os.mkdir(mirror) + for name in names: + if name not in masked: + os.symlink(os.path.join(real, name), os.path.join(mirror, name)) + _PATH_MIRRORS[real] = mirror + parts.append(_PATH_MIRRORS[real] or part) + return os.pathsep.join(parts) + + +def _script(path: Path, text: str) -> Path: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8") + path.chmod(0o755) + return path + + +def _logging_psql(directory: Path, real: str, log: Path) -> Path: + """A directory for the front of one command's `PATH`, holding a `psql` + that appends `--- psql <its argv>` and then its stdin to `log` as it + streams them, through `tee`, to the real `psql` at `real`, whose exit it + keeps. `lanes-index` sends each request as one `psql` call with its SQL on + stdin, so `log` holds every request the command sent.""" + _script(directory / "psql", "#!/bin/sh\n" + f"printf '%s\\n' \"--- psql $*\" >> {shlex.quote(str(log))}\n" + f"tee -a {shlex.quote(str(log))} | {shlex.quote(str(real))} \"$@\"\n") + return directory + + +# ------------------------------------------------------------------ the workspace +class Workspace: + """A whole files-mode workspace in `root`: a bare origin, its clone, the + pointer file that joins them (Amendment 23 S5's view of the clone), a + fake `tmux`, and the environment every command here runs in. With + `files`, a new origin is made and `files` committed and pushed by git + alone; with `origin`, that origin is cloned as it stands.""" + + def __init__(self, root: Path, files: dict | None = None, *, origin: Path | None = None, + lane: str = OPERATOR, workstation: str = WS): + self.root = root + self.home = root / "home" + self.agents = self.home / ".agents" + self.origin = origin or root / "origin.git" + self.wip = self.home / "projects" / "wip" + self.fakebin = root / "fakebin" + self.conf = root / "conf" + for d in (self.home, self.agents, self.fakebin, self.conf, root / "state", + root / "config", root / "tmp"): + d.mkdir(parents=True, exist_ok=True) + _script(self.fakebin / "tmux", "#!/bin/sh\nexit 1\n") + env = {k: v for k, v in os.environ.items() + if not k.startswith(("LANES_", "CLAUDE_", "WORKBENCHES_", "TMUX", "XDG_", "PG", + "AGENT_PROTOCOL_ROOT", "PROJECTS_", "GIT_"))} + env.update( + HOME=str(self.home), AGENT_PROTOCOL_ROOT=str(self.agents), TMPDIR=str(root / "tmp"), + XDG_STATE_HOME=str(root / "state"), XDG_CONFIG_HOME=str(root / "config"), + CLAUDE_CONFIG_DIR=str(self.home / ".claude"), LANES_WORKSTATION=workstation, + LANES_HOST="eagle", LANES_OS="linux", LANES_CONTAINER="none", + LANES_IN_CONTAINER="0", LANES_NO_GITHUB="1", LANES_EDIT=str(LANES_EDIT), + GIT_AUTHOR_NAME="lanes-index tests", GIT_AUTHOR_EMAIL="test@example.invalid", + GIT_COMMITTER_NAME="lanes-index tests", GIT_COMMITTER_EMAIL="test@example.invalid", + PATH=str(self.fakebin) + os.pathsep + _masked_path()) + self.env = env + if origin is None: + subprocess.run(["git", "init", "-q", "--bare", "-b", "main", str(self.origin)], + check=True, env=self.env, capture_output=True) + subprocess.run(["git", "clone", "-q", str(self.origin), str(self.wip)], + check=True, env=self.env, capture_output=True) + if files: + self.commit(files, "seed the register") + self.ws = root / "ro" / "wip" + self.ws.mkdir(parents=True) + (self.ws / ".git").write_text(f"gitdir: {os.path.realpath(self.wip / '.git')}\n", + encoding="utf-8") + (self.ws / "lanes").symlink_to(self.wip / "lanes") + (self.agents / "workspace.yaml").write_text( + f"repository: {self.origin}\npath: {self.ws}\n", encoding="utf-8") + self.env["LANES_REPO"] = str(self.wip) + self.lane = lane + + def git(self, *args: str, input_bytes: bytes | None = None, check: bool = True) -> str: + proc = subprocess.run(["git", *args], cwd=str(self.wip), capture_output=True, + input=input_bytes, env=self.env, check=False) + assert not check or proc.returncode == 0, ( + f"git {' '.join(args)}: {proc.stderr.decode(errors='replace')}") + return proc.stdout.decode("utf-8", "replace") + + def commit(self, files: dict, message: str, *, push: bool = True) -> str: + """Commit `files` ({path: str or bytes, or None to remove}) through + git alone, push it unless told not to, and return the commit.""" + for path, text in files.items(): + if text is None: + self.git("rm", "-q", "--cached", "--", path) + continue + data = text.encode("utf-8") if isinstance(text, str) else text + sha = self.git("hash-object", "-w", "--stdin", input_bytes=data).strip() + self.git("-c", "core.ignorecase=false", "update-index", "--add", "--cacheinfo", + f"100644,{sha},{path}") + self.git("-c", "core.ignorecase=false", "commit", "-q", "-m", message) + if push: + self.git("push", "-q", "origin", "main") + self.git("-c", "core.ignorecase=false", "checkout", "-q", "-f", "HEAD") + return self.git("rev-parse", "HEAD").strip() + + def run(self, *argv, env: dict | None = None, timeout: float = 120, + cwd: Path | None = None) -> subprocess.CompletedProcess: + child = dict(self.env) + for key, value in (env or {}).items(): + if value is None: + child.pop(key, None) + else: + child[key] = value + return subprocess.run([str(a) for a in argv], capture_output=True, text=True, + env=child, timeout=timeout, cwd=str(cwd or self.root), + stdin=subprocess.DEVNULL) + + def edit(self, *args, env: dict | None = None, **kw) -> subprocess.CompletedProcess: + return self.run("bash", LANES_EDIT, *args, env=env, **kw) + + def tip(self) -> str: + return self.git("rev-parse", "origin/main").strip() + + def tree(self, sha: str, path: str = "lanes") -> str: + return self.git("rev-parse", f"{sha}:{path}").strip() + + # ------------------------------------------------------------ the bare origin + def origin_git(self, *args: str) -> str: + """git in the bare origin itself, so no clone's refs move.""" + proc = subprocess.run(["git", f"--git-dir={self.origin}", *args], capture_output=True, + env=self.env, check=False, stdin=subprocess.DEVNULL) + assert proc.returncode == 0, f"git {' '.join(args)}: {proc.stderr.decode(errors='replace')}" + return proc.stdout.decode("utf-8", "replace") + + def origin_tip(self) -> str: + return self.origin_git("rev-parse", "refs/heads/main").strip() + + def origin_blob(self, rev: str, path: str) -> bytes | None: + proc = subprocess.run(["git", f"--git-dir={self.origin}", "cat-file", "blob", + f"{rev}:{path}"], capture_output=True, env=self.env, + check=False, stdin=subprocess.DEVNULL) + return proc.stdout if proc.returncode == 0 else None + + def origin_changed(self, sha: str) -> list: + """The paths `sha` changes against its first parent.""" + out = self.origin_git("diff-tree", "--root", "--no-commit-id", "-r", "--no-renames", + "--name-only", "-z", sha) + return sorted(p for p in out.split("\0") if p) + + def origin_parent(self, sha: str) -> str: + return self.origin_git("rev-parse", f"{sha}^").strip() + + def commits_after(self, since: str) -> list: + """The commits on origin's `main` after `since`, oldest first, each + with its `Register-Seq` values.""" + commits = self.origin_git("rev-list", "--reverse", f"{since}..refs/heads/main").split() + return [(sha, [int(s) for s in REGISTER_SEQ.findall( + self.origin_git("log", "-1", "--format=%B", sha))]) for sha in commits] + + def origin_render_set(self, rev: str) -> dict: + """The render set at `rev` on origin, {path: bytes}.""" + paths = self.origin_git("ls-tree", "-r", "--name-only", "-z", rev, "--", "lanes/") + return {p: self.origin_blob(rev, p) for p in paths.split("\0") if p and RENDER_SET.match(p)} + + +class StaleWorkstation(Workspace): + """THE STALE WORKSTATION (AT-6, "Fixture"): a clone of `origin` with no + `lanes-index` configuration, its own home and pointer, lane `STALE_LANE`, + and the pinned v1.1.0 writer. `lanes-index` and `psql` are masked off its + `PATH`, and its `sleep` returns at once (the module's readings).""" + + def __init__(self, root: Path, origin: Path): + super().__init__(root, origin=origin, lane=STALE_LANE, workstation=STALE_WS) + _script(self.fakebin / "sleep", "#!/bin/sh\nexit 0\n") + self.env.update(LANES_LANE=STALE_LANE, GIT_AUTHOR_NAME="A stale workstation", + GIT_COMMITTER_NAME="A stale workstation") + self.env.pop("LANES_EDIT", None) + self.writer = v1_1_0_writer() + + def v110(self, *args, env: dict | None = None) -> subprocess.CompletedProcess: + """The v1.1.0 `lanes-edit.sh`, run by `bash` in the stale clone.""" + return self.run("bash", self.writer, *args, env=env, cwd=self.wip, timeout=300) + + def note(self, text: str) -> subprocess.CompletedProcess: + """`log NOTED`, AT-6's stale write: a commit changing the lane's log.""" + return self.v110("log", "NOTED", f"lane:{STALE_LANE}", text) + + def local_commit(self, path: str, text: str, message: str) -> str: + """A person's commit in the stale clone, appending `text` to `path`, + not pushed.""" + target = self.wip / path + target.write_text(target.read_text(encoding="utf-8") + text, encoding="utf-8") + self.git("add", "--", path) + self.git("commit", "-q", "-m", message) + return self.git("rev-parse", "HEAD").strip() + + +# ------------------------------------------------------------------ the gate model +#: AT-6'S MODEL OF Q21(b)'s PUSH RULESET (Brett's scope, "Render set + +#: STORE", lane 3's 6721583757), a pre-receive hook in the bare origin: it +#: refuses a push whose commits change a path of the render set or +#: `lanes/STORE`, and lets every other path through. Each push is one JSON +#: line of its log. +GATE_HOOK = r'''#!/usr/bin/env -S python3 -I +# T271's model of the server-side gate (test plan, AT-6, "Options"): a model, +# since the suite cannot reach GitHub. +import json, re, subprocess, sys +LOG = LOG_PATH +GUARDED = re.compile(r"^lanes/(LANES\.md|aliases\.tsv|STORE|archive/.+" + r"|log/(?!README\.md$)[^/]+\.md)$") +ZERO = "0" * 40 + + +def git(*args): + return subprocess.run(["git", *args], capture_output=True, text=True, + check=True).stdout + + +def changed(old, new): + revs = git("rev-list", new if old == ZERO else f"{old}..{new}").split() + paths = set() + for rev in revs: + out = git("diff-tree", "--root", "--no-commit-id", "-r", "-m", "--no-renames", + "--name-only", "-z", rev) + paths.update(p for p in out.split("\0") if p) + return sorted(paths) + + +def main(): + pushes, refused = [], [] + for line in sys.stdin: + old, new, ref = line.split() + if new == ZERO: + continue + paths = changed(old, new) + hits = [p for p in paths if GUARDED.match(p)] + pushes.append({"ref": ref, "old": old, "new": new, "paths": paths, "guarded": hits}) + refused += hits + with open(LOG, "a", encoding="utf-8") as handle: + handle.write(json.dumps({"outcome": "refused" if refused else "accepted", + "pushes": pushes}) + "\n") + if refused: + sys.stderr.write("t271 gate model: a push to the render set or lanes/STORE is " + "refused: " + ", ".join(sorted(set(refused))) + "\n") + return 1 + return 0 + + +sys.exit(main()) +''' + + +class GatedOrigin(Workspace): + """The gate model's register: the seed and a files-mode write, then + `lanes/STORE` as the cutover's marker commit leaves it, on a bare origin + that `GATE_HOOK` guards. No database: the model needs none.""" + + def __init__(self, root: Path): + super().__init__(root, SEED) + proc = self.edit("log", "NOTED", f"lane:{OPERATOR}", "test 6's register, at C", + env={"LANES_LANE": OPERATOR}) + assert proc.returncode == 0, f"lanes-edit.sh log NOTED: {_said(proc)}" + self.c = self.tip() + self.marker = self.commit({"lanes/STORE": _store_text(LABEL, self.c, self.tree(self.c))}, + "cutover: lanes/STORE, the marker\n\nRegister-Seq: 1") + self.gate_log = root / "gate.log" + _script(self.origin / "hooks" / "pre-receive", + GATE_HOOK.replace("LOG_PATH", repr(str(self.gate_log)))) + + def gate_records(self) -> list: + if not self.gate_log.exists(): + return [] + return [json.loads(line) for line in self.gate_log.read_text(encoding="utf-8").splitlines() + if line] + + +# ------------------------------------------------------------------ the estate +def flipped_indexer(directory: Path) -> Path: + """T203's flipped copy, `RENDER_GIT_HALF = True`, in `directory`, with + `lanes-edit.sh` and `repos.tsv` beside it (the copy rule, CLI4.5 section + 6), so that the renderer and the two ways out take `lanes_register`.""" + from sql_register_helpers import RENDER_GIT_HALF_LINE, flipped_copy + assert len(RENDER_GIT_HALF_LINE.findall(INDEXER.read_bytes())) == 1, ( + f"{INDEXER} holds no single `RENDER_GIT_HALF = ...` line, Q6(c)'s build constant " + f"(L1-A4, lane 1's T105), so no copy can be flipped") + copy = flipped_copy(INDEXER, directory, True) + for name in ("lanes-edit.sh", "repos.tsv"): + if (REPO / name).exists(): + shutil.copy2(REPO / name, copy.parent / name) + return copy + + +def _store_text(label: str, c: str, tree: str) -> str: + """`lanes/STORE` with D21's fields, one per line.""" + return "\n".join(_store_lines(label, c, tree)) + "\n" + + +def _store_lines(label: str, c: str, tree: str) -> list: + return ["store=primary", f"database={label}", f"import={c}", f"lanes-tree={tree}", + f"utc={STORE_UTC}"] + + +def _entry(kind: str, verb: str, message: str, **parts) -> dict: + """One `commit_write` entry (section 1.3): the journal object, + `not_after`, and `parts`.""" + journal = {"kind": kind, "verb": verb, "lane": OPERATOR, "workstation": WS, + "author": AUTHOR, "message": message} + journal.update(parts.pop("journal", {})) + return {"journal": journal, "not_after": NOT_AFTER, **parts} + + +#: The four structured tables, each row keyed by its line's `(path, line_no)` +#: in place of a line id, without the columns a write stamps: the written seq, +#: the mode and the workstation (T221's step-6 comparison; lane 2's reading, +#: NOTES question 33). +STRUCTURED = { + "lanes": f"SELECT to_jsonb(t) - 'row_line_id' - 'last_seq' - 'last_mode' - 'workstation' || " + f"jsonb_build_object('path', d.path, 'line_no', d.line_no) FROM {SCHEMA}.lanes t " + f"LEFT JOIN {SCHEMA}.doc_lines d ON d.line_id = t.row_line_id", + "log_lines": f"SELECT to_jsonb(t) - 'line_id' - 'seq' - 'mode' - 'workstation' || " + f"jsonb_build_object('path', d.path, 'line_no', d.line_no) FROM " + f"{SCHEMA}.log_lines t LEFT JOIN {SCHEMA}.doc_lines d ON d.line_id = t.line_id", + "register_lines": f"SELECT to_jsonb(t) - 'line_id' - 'seq' - 'mode' - 'workstation' || " + f"jsonb_build_object('path', d.path, 'line_no', d.line_no) FROM " + f"{SCHEMA}.register_lines t LEFT JOIN {SCHEMA}.doc_lines d " + f"ON d.line_id = t.line_id", + "object_holds": f"SELECT to_jsonb(t) - 'seq' - 'mode' FROM {SCHEMA}.object_holds t", +} + + +def _psql(db, script: str, role: str | None = None) -> subprocess.CompletedProcess: + """One `psql` as the fixture's superuser, as `role` where one is named, + with the commit call's settings, so a refusal's first stderr line is + `ERROR: <SQLSTATE>: <message>`.""" + head = "\\set VERBOSITY verbose\n\\set SHOW_CONTEXT never\nSET client_encoding = 'UTF8';\n" + if role: + head += f"SET ROLE {role};\n" + return subprocess.run([db.psql_bin, "-X", "-q", "-A", "-t", "-v", "ON_ERROR_STOP=1"], + input=head + script, capture_output=True, encoding="utf-8", + errors="replace", env=db.env(appname="t271"), timeout=120, check=False) + + +def _sql(db, script: str, role: str | None = None) -> str: + proc = _psql(db, script, role) + assert proc.returncode == 0, (f"psql{' as ' + role if role else ''} exited " + f"{proc.returncode}: {proc.stderr.strip()}\n{script}") + return proc.stdout.strip() + + +def _rows(db, query: str) -> list: + """`query`'s rows as JSON objects, read in the register's schema, by + `jsonb_agg`, whose text is one line.""" + return json.loads(_sql(db, f"SET search_path TO {SCHEMA};\n" + f"SELECT coalesce(jsonb_agg(t), '[]'::jsonb) FROM ({query}) t;") + .splitlines()[-1]) + + +def structured(db) -> dict: + """The four structured tables of `db`, as `STRUCTURED` reads them, each a + sorted list.""" + return {table: json.loads(_sql(db, f"SELECT coalesce(jsonb_agg(r ORDER BY r::text), '[]') " + f"FROM ({query}) AS q(r);")) + for table, query in STRUCTURED.items()} + + +def _renders(db) -> dict: + """SQL's own render (lane 1's T107, `render_file`) of every path in + `files`, {path: bytes}.""" + return {r["path"]: base64.b64decode(r["b64"]) for r in _rows( + db, "SELECT path, encode(render_file(path), 'base64') AS b64 FROM files ORDER BY path")} + + +class Estate(Workspace): + """TEST 6'S PRIMARY ESTATE (AT-6, "Fixture"), as the module's docstring + sets it out: the fixture register at C imported on `pg`, and the cutover + by AT-LR006's route, its marker commit on the bare origin. Until a step's + task lands, the case fails at that step's own assertion, naming it.""" + + def __init__(self, root: Path, pg): + super().__init__(root, SEED) + proc = self.edit("log", "NOTED", f"lane:{OPERATOR}", "test 6's register, at C", + env={"LANES_LANE": OPERATOR}) + assert proc.returncode == 0, f"lanes-edit.sh log NOTED: {_said(proc)}" + self.c = self.tip() + # The operator lane's git author, in its checkout's own configuration: + # a way out names its entry's author as git does there, with every + # inherited `GIT_*` variable removed first (D12), so this module's + # `GIT_AUTHOR_*` never reach it (the module's readings). + self.git("config", "user.name", AUTHOR_NAME) + self.git("config", "user.email", AUTHOR_EMAIL) + self.pg = pg + self.bin = root / "bin" + self.bin.mkdir() + (self.bin / "psql").symlink_to(pg.psql_bin) + self.env["PATH"] = str(self.bin) + os.pathsep + self.env["PATH"] + self.copy = flipped_indexer(root / "flip") + self.index_conf = self.config(pg, "index") + self.primary_conf = self.config(pg, "primary") + self.persons = 0 + imported = self.import_at(self.c) + assert imported.returncode == 0, ( + f"test 6's import at C failed (lane 1's T115, `import --at`):\n{_said(imported)}") + assert self.head() == 0, f"after the import the head is {self.head()}, not 0" + self.marker = self._cutover() + + # ------------------------------------------------------------ the configuration + def config(self, pg, mode: str, name: str = "") -> Path: + """The operator's configuration (CLI4.10 section 2.5): `mode`, the + register's two URLs on the cluster's Unix socket, a private password + file each, `register_label=` and `register_schema=`. Mode 0600.""" + passfile = self.conf / "pgpass" + if not passfile.exists(): + passfile.write_text("", encoding="utf-8") + passfile.chmod(0o600) + path = self.conf / f"lanes-index-{name or mode}.conf" + path.write_text("\n".join([ + f"mode={mode}", f"register_url={pg.url()}", f"register_passfile={passfile}", + f"reader_url={pg.url()}", f"reader_passfile={passfile}", + f"register_label={LABEL}", f"register_schema={SCHEMA}", ""]), encoding="utf-8") + path.chmod(0o600) + return path + + # ------------------------------------------------------------ the SQL side + def rows(self, query: str) -> list: + return _rows(self.pg, query) + + def head(self) -> int: + return self.rows("SELECT seq FROM register_head")[0]["seq"] + + def switch(self) -> dict: + return self.rows("SELECT * FROM register_switch")[0] + + def mirror(self) -> dict: + return self.rows("SELECT * FROM mirror_state")[0] + + def count(self) -> int: + return self.rows("SELECT count(*) AS n FROM journal")[0]["n"] + + def entry(self, seq: int) -> dict: + found = self.rows(f"SELECT seq, kind, verb, message, git_commit, operator FROM journal " + f"WHERE seq = {seq}") + assert len(found) == 1, f"the journal holds no entry at seq {seq}: {found}" + return found[0] + + def edits(self, seq: int) -> list: + return [(r["op"], r["path"], r["new_text"]) for r in self.rows( + f"SELECT ord, op, path, new_text FROM journal_edits WHERE seq = {seq} ORDER BY ord")] + + def renders(self) -> dict: + return _renders(self.pg) + + def commit_call(self, base: int, body: dict) -> subprocess.CompletedProcess: + """The commit call as a writer sends it (section 1.3's step 3; + AT-LR006's fixture): one SERIALIZABLE transaction around + `commit_write`, as REGISTER-WRITER.""" + version = self.rows("SELECT version FROM schema_version")[0]["version"] + generation = self.switch()["generation"] + literal = json.dumps(body, ensure_ascii=True).replace("'", "''") + return _psql(self.pg, f"BEGIN ISOLATION LEVEL SERIALIZABLE;\n" + f"SELECT {SCHEMA}.commit_write({base}, '{uuid.uuid4()}'::uuid, " + f"{version}, '{generation}'::uuid, '{literal}'::jsonb);\nCOMMIT;\n", + WRITER) + + def committed(self, base: int, body: dict, what: str) -> int: + proc = self.commit_call(base, body) + assert proc.returncode == 0, (f"{what}: commit_write refused it (lane 1's T107):\n" + f"{proc.stderr.strip()}") + return int(proc.stdout.strip().splitlines()[-1]) + + def _cutover(self) -> str: + """AT-LR006's route from the import: the `cutover` entry, its marker + commit pushed as a fast-forward of C, then `record_marker`.""" + lines = _store_lines(LABEL, self.c, self.tree(self.c)) + text = "\n".join(lines) + "\n" + edits = [{"ord": 1, "op": "create", "path": "lanes/STORE"}] + edits += [{"ord": n, "op": "append", "path": "lanes/STORE", "new_text": line} + for n, line in enumerate(lines, start=2)] + cut = self.committed(0, _entry( + "cutover", "cutover", "t271: the cutover", edits=edits, + files=[{"path": "lanes/STORE", "present": True, + "sha256": _sha256(text.encode("utf-8")), "final_newline": True}]), + "the cutover entry") + marker = self.commit({"lanes/STORE": text}, + f"cutover: lanes/STORE, the marker\n\nRegister-Seq: {cut}") + assert self.origin_parent(marker) == self.c, "the marker commit is a fast-forward of C" + version = self.rows("SELECT version FROM schema_version")[0]["version"] + answer = _sql(self.pg, f"SELECT {SCHEMA}.record_marker({version}, {cut}, '{marker}', " + f"'{WS}');", WRITER) + assert answer == "present", f"record_marker answered {answer!r}, not present" + switch = self.switch() + assert (switch["mode"], switch["marker_state"], self.head()) == ("primary", "present", 1), ( + f"AT-LR006's route left the switch {switch} and the head {self.head()}, not primary, " + f"present and 1") + return marker + + def write_body(self, text: str) -> dict: + """A write that appends `text`, a line of no kind, to + `lanes/LANES.md`: no structured row.""" + after = self.renders()["lanes/LANES.md"] + (text + "\n").encode("utf-8") + return _entry("write", "log", f"LANES({OPERATOR}@{WS}): {text}", + journal={"args_sha256": ARGS_SHA256}, + edits=[{"ord": 1, "op": "append", "path": "lanes/LANES.md", + "new_text": text}], + files=[{"path": "lanes/LANES.md", "present": True, + "sha256": _sha256(after), "final_newline": True}]) + + def write(self, text: str) -> int: + """A primary write (the module's docstring): its seq.""" + base = self.head() + seq = self.committed(base, self.write_body(text), f"a primary write, {text!r}") + assert seq == base + 1, f"the write took seq {seq}, not {base + 1}" + return seq + + def replace_line(self, path: str, line_no: int, text: str) -> int: + """A primary write that replaces line `line_no` of `path`, a line of + no kind, with `text`: one `replace` edit, naming the line by its old + text's digest (section 1.3), and no structured row. Its seq.""" + image = self.renders()[path] + lines = image.decode("utf-8").split("\n") + assert image.endswith(b"\n") and 1 <= line_no < len(lines), (path, line_no, lines) + old, lines[line_no - 1] = lines[line_no - 1], text + after = "\n".join(lines).encode("utf-8") + base = self.head() + seq = self.committed(base, _entry( + "write", "log", f"LANES({OPERATOR}@{WS}): t271: {path} line {line_no} replaced", + journal={"args_sha256": ARGS_SHA256}, + edits=[{"ord": 1, "op": "replace", "path": path, "line_no": line_no, + "old_sha256": _sha256(old.encode("utf-8")), "new_text": text}], + files=[{"path": path, "present": True, "sha256": _sha256(after), + "final_newline": True}]), + f"a primary write replacing line {line_no} of {path}") + assert seq == base + 1, f"the write took seq {seq}, not {base + 1}" + return seq + + def record(self, sha: str | None, error: str | None = None, + ws: str = "ws-t271") -> subprocess.CompletedProcess: + return _psql(self.pg, f"SELECT {SCHEMA}.record_mirror_state('{ws}', " + f"{'NULL' if sha is None else repr(sha)}, " + f"{'NULL' if error is None else repr(error)});", WRITER) + + # ------------------------------------------------------------ lanes-index + def index(self, *args, conf: Path | None = None, env: dict | None = None, + timeout: float = 300) -> subprocess.CompletedProcess: + """The flipped copy, as the operator lane through its checkout.""" + child = {"LANES_INDEX_CONFIG": str(conf or self.primary_conf), "LANES_LANE": OPERATOR, + "LANES_INDEX": None, "LANES_EDIT": str(self.copy.parent / "lanes-edit.sh")} + child.update(env or {}) + return self.run(sys.executable, self.copy, *args, cwd=self.wip, timeout=timeout, + env=child) + + def import_at(self, sha: str, *, conf: Path | None = None, + cwd: Path | None = None, env: dict | None = None) -> subprocess.CompletedProcess: + """`lanes-index import --at <sha>`, the shipped one, as the operator + lane through its checkout (test 7's form).""" + child = {"LANES_INDEX_CONFIG": str(conf or self.index_conf), "LANES_LANE": OPERATOR, + "LANES_INDEX": None} + child.update(env or {}) + return self.run(sys.executable, INDEXER, "import", "--at", sha, cwd=cwd or self.wip, + timeout=400, env=child) + + def render(self) -> subprocess.CompletedProcess: + """The render a primary write forks, `render --checkout <c>`, run in + the foreground: its exit is the wait for it.""" + return self.index("render", "--checkout", str(self.wip)) + + def status(self) -> subprocess.CompletedProcess: + """`lanes-index status`, after a fetch in the checkout: `status` + never fetches, and reads `m` on `origin/main` as last fetched.""" + self.git("fetch", "-q", "origin", check=False) + return self.index("status", conf=self.index_conf) + + def wait_lag_0(self, ceiling: float = 30.0) -> subprocess.CompletedProcess: + """Open point 8's first wait: `status` every 100 ms until its lag is + 0, under `ceiling`. Returns the last `status`.""" + end = time.monotonic() + ceiling + while True: + proc = self.status() + if LAG_0.search(proc.stdout) or time.monotonic() > end: + return proc + time.sleep(0.1) + + def reconcile(self) -> subprocess.CompletedProcess: + return self.index("reconcile") + + def import_single(self, sha: str) -> subprocess.CompletedProcess: + """The single-write import, on a person's word (T324).""" + return self.index("import", "--single", sha) + + def revert(self, sha: str) -> subprocess.CompletedProcess: + """The renderer's revert, on a person's word (T324).""" + return self.index("render", "--revert", sha) + + def rollback(self) -> subprocess.CompletedProcess: + return self.index("rollback") + + # ------------------------------------------------------------ other hands + def stale(self) -> StaleWorkstation: + return StaleWorkstation(self.root / "stale", self.origin) + + def push_as_person(self, files: dict, message: str) -> str: + """A person's commit of `files` ({path: str}), from a clone of their + own, pushed to origin's `main`. Returns it.""" + self.persons += 1 + clone = self.root / f"person-{self.persons}" + subprocess.run(["git", "clone", "-q", str(self.origin), str(clone)], check=True, + env=self.env, capture_output=True, stdin=subprocess.DEVNULL) + for path, text in files.items(): + target = clone / path + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(text.encode("utf-8")) + for argv in (["add", "--", *files], ["commit", "-q", "-m", message], + ["push", "-q", "origin", "HEAD:main"]): + subprocess.run(["git", "-C", str(clone), *argv], check=True, env=self.env, + capture_output=True, stdin=subprocess.DEVNULL) + sha = self.origin_tip() + assert subprocess.run(["git", "-C", str(clone), "rev-parse", "HEAD"], capture_output=True, + text=True, env=self.env).stdout.strip() == sha + return sha + + def origin_text(self, path: str) -> str: + return self.origin_blob(self.origin_tip(), path).decode("utf-8") + + +# ------------------------------------------------------------------ the oracles +def _lag(text: str) -> int | None: + m = LAG_N.search(text) + return int(m.group(1)) if m else None + + +def _stop(est: Estate) -> tuple: + """AT-6's stray and stop: the stale workstation's `log NOTED`, then a + primary write and its render. Returns (the stray, the write's seq, the + render).""" + before = est.origin_tip() + stale = est.stale() + proc = stale.note("a note the v1.1.0 writer pushes to a primary estate") + assert proc.returncode == 0, ( + f"the v1.1.0 writer's log NOTED did not push (it knows no marker, so on an estate " + f"with no gate it pushes):\n{_said(proc)}") + stray = est.origin_tip() + assert stray != before and est.origin_parent(stray) == before, ( + f"origin's tip {stray} is not one commit on {before}") + assert est.origin_changed(stray) == [f"lanes/log/{STALE_LANE}.md"], ( + f"the stale write changes {est.origin_changed(stray)}, not its lane's log alone") + k = est.write("t271: a primary write after the stray") + return stray, k, est.render() + + +def _assert_stopped(est: Estate, stray: str, render) -> None: + """The stop, read after the renderer's exit: no render commit, origin's + tip still the stray, and `diverged at` recorded (D16).""" + assert est.origin_tip() == stray, ( + f"origin's tip moved past the stray {stray} to {est.origin_tip()}: the render pushed " + f"over a commit it did not make (lane 3's T322)\n{_said(render)}") + diverged = est.mirror()["diverged_sha"] + assert diverged == stray, ( + f"mirror_state.diverged_sha is {diverged!r}, not the stray {stray} (D16; lane 3's T322)" + f"\n{_said(render)}") + + +def _assert_status_diverged(est: Estate, sha: str, past: tuple | None = None) -> None: + """`status` prints `diverged at <sha>` with the full sha, and the lag: + for a plain stray, a lag of at least 1 (TP:1284); with `past`, `(m, n)` + for a `Register-Seq` above the head, no lag, `m` past `n`, as `status` + says (TP:1319 at B15; lane 3's L2-7).""" + proc = est.status() + assert f"diverged at {sha}" in proc.stdout, ( + f"status does not print `diverged at {sha}` with the full sha (lane 1's T117):\n" + f"{_said(proc)}") + if past is not None: + found = LAG_PAST_N.search(proc.stdout) + assert found and _lag(proc.stdout) is None and ( + int(found.group(1)), int(found.group(2))) == past, ( + f"status does not print no lag, the mirror's {past[0]} past n {past[1]} " + f"(TP:1319; Y:2850; lane 3's L2-7):\n{_said(proc)}") + return + lag = _lag(proc.stdout) + assert lag is not None and lag >= 1, ( + f"status does not print a lag of at least 1 seq (AT-6's stop):\n{_said(proc)}") + + +def _resume(est: Estate, since: str, first: int) -> None: + """THE RESUME (AT-6, each way out): the renderer renders every pending + seq onto origin's tip in order; `status` then shows a lag of 0 and no + divergence; origin's rendered paths equal a full render from SQL, byte + for byte; and `reconcile` exits 0.""" + render = est.render() + proc = est.wait_lag_0() + assert LAG_0.search(proc.stdout), ( + f"after the way out, status shows no lag of 0 within 30 s (the renderer did not " + f"resume):\n{_said(proc)}\nthe render: {_said(render)}") + assert NO_DIVERGENCE.search(proc.stdout) and "diverged at" not in proc.stdout, ( + f"status still shows a divergence:\n{_said(proc)}") + seqs = [s for _sha, found in est.commits_after(since) for s in found] + assert seqs == list(range(first, est.head() + 1)), ( + f"the seqs pushed after {since[:12]} are {seqs}, not {first} to {est.head()} in order") + tip = est.origin_tip() + from_sql = {p: b for p, b in est.renders().items() if RENDER_SET.match(p)} + on_origin = est.origin_render_set(tip) + assert on_origin == from_sql, ( + f"origin's rendered paths at {tip[:12]} differ from a full render from SQL: " + f"{sorted(set(on_origin) ^ set(from_sql))} or " + f"{sorted(p for p in on_origin if p in from_sql and on_origin[p] != from_sql[p])}") + rec = est.reconcile() + assert rec.returncode == 0, f"reconcile does not pass after the way out:\n{_said(rec)}" + + +def _way_out(est: Estate, stray: str, way: str) -> int: + """`import --single <stray>` or `render --revert <stray>`, on a person's + word: one journal entry naming the stray, and `diverged at` cleared. + Returns the entry's seq.""" + n, count = est.head(), est.count() + proc = est.import_single(stray) if way == "import" else est.revert(stray) + verb = "import --single" if way == "import" else "render --revert" + assert proc.returncode == 0, f"lanes-index {verb} {stray} (lane 3's T324):\n{_said(proc)}" + assert (est.head(), est.count()) == (n + 1, count + 1), ( + f"{verb} did not add exactly one journal entry: the head {n} -> {est.head()}, the " + f"count {count} -> {est.count()}") + got = est.entry(n + 1) + kind = "stray-import" if way == "import" else "stray-revert" + assert (got["kind"], got["git_commit"]) == (kind, stray), ( + f"seq {n + 1} is {got}, not a {kind} entry naming {stray} (design.md's kinds)") + mirror = est.mirror() + assert mirror["diverged_sha"] is None, ( + f"after {verb} mirror_state still records diverged at {mirror['diverged_sha']} (D16)") + return n + 1 + + +def _assert_rolled_back(est: Estate, proc) -> None: + """TEST 8'S FIRST ORACLE (test 8 (a)): exit 0; the switch at `files` + with the marker `absent`; origin's last commit removes `lanes/STORE` + alone and carries the rollback entry's seq, the journal's last; origin's + rendered paths equal a full render from SQL, byte for byte; and SQL + writes refused: a `write` entry is LR002, and the head does not move.""" + assert proc.returncode == 0, f"the rollback did not end 0 (lane 3's T326):\n{_said(proc)}" + switch = est.switch() + assert (switch["mode"], switch["marker_state"]) == ("files", "absent"), ( + f"the switch is {switch['mode']}/{switch['marker_state']}, not files/absent") + last = est.rows("SELECT seq, kind, operator FROM journal ORDER BY seq DESC LIMIT 1")[0] + assert (last["kind"], last["operator"]) == ("rollback", True), f"the last entry is {last}" + tip = est.origin_tip() + assert REGISTER_SEQ.findall(est.origin_git("log", "-1", "--format=%B", tip)) == [ + str(last["seq"])], f"origin's last commit does not carry Register-Seq: {last['seq']}" + changed = est.origin_git("diff-tree", "--no-commit-id", "--name-status", "-r", f"{tip}^", tip) + assert changed.split("\n") == ["D\tlanes/STORE", ""], ( + f"origin's last commit does not remove lanes/STORE alone: {changed!r}") + from_sql = {p: b for p, b in est.renders().items() if RENDER_SET.match(p)} + assert est.origin_render_set(tip) == from_sql, ( + "origin's rendered paths differ from a full render from SQL after the rollback") + head = est.head() + refused = est.commit_call(head, est.write_body("t271: a write after the rollback")) + assert refused.returncode != 0 and "LR002" in refused.stderr, ( + f"a write after the rollback was not refused with LR002:\n{_said(refused)}") + assert est.head() == head + + +# =================================================================== the gate model +GUARDED = { + "lanes-md": "lanes/LANES.md", + "log-lane": f"lanes/log/{STALE_LANE}.md", + "aliases-tsv": "lanes/aliases.tsv", + "archive": "lanes/archive/LANES-retired.md", + "store": "lanes/STORE", +} +UNGUARDED = {"repos-tsv": "lanes/repos.tsv", "log-readme": "lanes/log/README.md"} + + +@pytest.mark.parametrize("path", list(GUARDED)) +def test_a_server_side_gate_refuses_the_stale_writers_push(tmp_path, path): + """A MODEL (AT-6, "Options", Q21(b)): with `GATE_HOOK` in the bare + origin, the v1.1.0 writer's push to each guarded path is refused. Its + exit is v1.1.0's 6 (six rejected pushes, "your commit is local"), the + hook's log names the path, and origin's `main` does not move. + + `[lanes-md]` is a hand edit the writer commits (`commit`); `[log-lane]` + is `log NOTED`; `[aliases-tsv]`, `[archive]` and `[store]` are a + person's local commit that the writer publishes (`commit`, #194's + publish of the commits ahead, which takes any added or modified file + under `lanes/`). Needs no engine, and waits for nothing.""" + reg = GatedOrigin(tmp_path / "e") + stale = StaleWorkstation(tmp_path / "stale", reg.origin) + target = GUARDED[path] + before = reg.origin_tip() + if path == "lanes-md": + page = stale.wip / target + page.write_text(page.read_text(encoding="utf-8") + "a hand edit of the register\n", + encoding="utf-8") + proc = stale.v110("commit", "t271: a hand edit of LANES.md") + elif path == "log-lane": + proc = stale.note("a note the gate refuses") + else: + stale.local_commit(target, "a line a person added\n", f"t271: an edit of {target}") + proc = stale.v110("commit", f"t271: publish the edit of {target}") + assert proc.returncode == 6, ( + f"the v1.1.0 writer's push to {target} did not end with its six-attempt refusal, " + f"6:\n{_said(proc)}") + records = reg.gate_records() + assert records and all(r["outcome"] == "refused" for r in records), records + assert {p for r in records for push in r["pushes"] for p in push["guarded"]} == {target}, ( + f"the gate model refused {records}, not {target} alone") + assert reg.origin_tip() == before, "origin's main moved under a refused push" + + +@pytest.mark.parametrize("path", list(UNGUARDED)) +def test_the_gate_model_lets_a_push_to_an_unguarded_path_through(tmp_path, path): + """A MODEL (AT-6, "Options"): a person's push of an edit to + `lanes/repos.tsv` or `lanes/log/README.md`, from the stale workstation's + clone, is accepted ("A person's `repos.tsv` edit is not gated"): origin's + `main` is that commit, and the hook's log says it was let through. Needs + no engine, and waits for nothing.""" + reg = GatedOrigin(tmp_path / "e") + stale = StaleWorkstation(tmp_path / "stale", reg.origin) + target = UNGUARDED[path] + sha = stale.local_commit(target, "a line a person added\n", f"t271: an edit of {target}") + stale.git("push", "-q", "origin", "main") + assert reg.origin_tip() == sha, "the push to an unguarded path did not land" + records = reg.gate_records() + assert [r["outcome"] for r in records] == ["accepted"], records + assert records[0]["pushes"][0]["paths"] == [target], records + + +# =================================================================== the stop +def test_the_v1_1_0_writer_pushing_to_a_primary_estate_stops_the_renderer(pg, tmp_path): + """AT-6, the stop: the stale workstation's `log NOTED`, by the pinned + v1.1.0 writer, lands on origin over a primary estate; the next primary + write's render makes no commit, origin's tip is still the stray, and + `mirror_state.diverged_sha` records it (D16). A later primary write + still commits to SQL, since the mirror is write-behind. Fails until + T107, T115, T117 and lane 3's T321 to T323 land.""" + est = Estate(tmp_path / "e", pg) + stray, k, render = _stop(est) + _assert_stopped(est, stray, render) + assert est.commits_after(stray) == [], "the render pushed a commit after the stray" + later = est.write("t271: a later write, while the mirror is diverged") + assert later == k + 1 and est.head() == later + assert est.mirror()["diverged_sha"] == stray + + +def test_status_prints_diverged_at_the_stray_sha_and_reconcile_imports_nothing(pg, tmp_path): + """AT-6, the stop: after the renderer's exit, `status` prints `diverged + at <the stray's full sha>` and a lag of at least 1; `reconcile` exits + non-zero, the journal's count is unchanged, and `status` still prints + `diverged at` after it. The non-zero is 1: T325's re-render runs T322's + pass, whose recorded stop is the renderer's 1 (exit-codes.md section + 3.4's `reconcile` 1 row; lane 3's L2-6). Fails until T107, T115, T117 + and T321 to T323 land, and also until T325, where T117's check alone + exits 0 (B15 tasks:2487).""" + est = Estate(tmp_path / "e", pg) + stray, _k, render = _stop(est) + _assert_stopped(est, stray, render) + _assert_status_diverged(est, stray) + count, head = est.count(), est.head() + rec = est.reconcile() + assert (est.count(), est.head()) == (count, head), "reconcile wrote to the journal" + assert rec.returncode == 1, ( + f"reconcile on a diverged mirror does not exit 1, the renderer's code for a recorded " + f"`diverged at` (AT-6: non-zero; exit-codes.md section 3.4; lane 3's T325, without " + f"which T117's check alone exits 0; L2-6):\n{_said(rec)}") + after = est.status() + assert f"diverged at {stray}" in after.stdout, ( + f"status no longer prints `diverged at {stray}` after reconcile:\n{_said(after)}") + + +# =================================================================== the ways out +def test_the_single_write_import_resumes_the_renderer_and_reconcile_passes(pg, tmp_path): + """AT-6, the single-write import: `lanes-index import --single <stray>` + adds exactly one journal entry, a `stray-import` naming the stray, whose + line edits equal the stray commit's diff; `mirror_state` no longer + records `diverged at`; the renderer resumes and the pending seqs reach + origin in order; `status` shows a lag of 0 and no divergence; origin's + rendered paths equal a full render; and `reconcile` exits 0. Fails until + T324 (and T107, T115, T117, T321 to T323).""" + est = Estate(tmp_path / "e", pg) + stray, _k, render = _stop(est) + _assert_stopped(est, stray, render) + path = f"lanes/log/{STALE_LANE}.md" + old = est.origin_blob(f"{stray}^", path).decode("utf-8").split("\n") + new = est.origin_blob(stray, path).decode("utf-8").split("\n") + assert new[:len(old) - 1] == old[:-1] and old[-1] == new[-1] == "", "the stray only appends" + added = new[len(old) - 1:-1] + seq = _way_out(est, stray, "import") + assert est.edits(seq) == [("append", path, line) for line in added], ( + f"the import's edits {est.edits(seq)} are not the stray's diff, {added} appended to " + f"{path}") + _resume(est, stray, 2) + assert all(line.encode("utf-8") in est.renders()[path] for line in added) + + +def test_the_renderers_revert_resumes_it_and_reconcile_passes(pg, tmp_path): + """AT-6, the renderer's revert: `lanes-index render --revert <stray>` + journals one `stray-revert` entry with no edits, whose message names the + stray (D16); `diverged at` clears; the resume as for the import; and the + render puts SQL's state back over the stray: on each path the stray + changed, origin's tip equals the stray's parent (the module's readings). + Fails until T324 (and T107, T115, T117, T321 to T323).""" + est = Estate(tmp_path / "e", pg) + stray, _k, render = _stop(est) + _assert_stopped(est, stray, render) + seq = _way_out(est, stray, "revert") + assert est.edits(seq) == [], f"the revert's entry has edits: {est.edits(seq)}" + assert stray[:7] in (est.entry(seq)["message"] or ""), ( + f"the revert's message does not name the stray: {est.entry(seq)['message']!r}") + _resume(est, stray, 2) + tip = est.origin_tip() + for path in est.origin_changed(stray): + assert est.origin_blob(tip, path) == est.origin_blob(f"{stray}^", path), ( + f"{path} at origin's tip is not SQL's state from before the stray") + + +@pytest.mark.parametrize("way", ["import", "revert"]) +def test_rollback_works_after_each_way_out(pg, tmp_path, way): + """AT-6, after each way out and the resume: a rollback, with the + database up, ends with the files byte-identical, the marker gone and SQL + writes refused (test 8's first oracle). Fails until T324 and T326 (and + T107, T115, T117, T321 to T323).""" + est = Estate(tmp_path / "e", pg) + stray, _k, render = _stop(est) + _assert_stopped(est, stray, render) + _way_out(est, stray, way) + _resume(est, stray, 2) + _assert_rolled_back(est, est.rollback()) + + +# =================================================================== the negative cases +OUTSIDE = ["cutover-store", "repos-tsv", "handoff"] + + +@pytest.mark.parametrize("commit", OUTSIDE) +def test_commits_outside_the_render_set_do_not_stop_the_renderer(pg, tmp_path, commit): + """AT-6's negative cases (P366-374): the cutover's own `lanes/STORE` + commit, a person's `lanes/repos.tsv` edit, and a person's commit under + `handoffs/`, each between renders, do not stop the renderer: the next + render renders onto that tip, and `status` shows a lag of 0 and no + divergence. Fails until T107, T115, T117 and T321 to T323 land.""" + est = Estate(tmp_path / "e", pg) + if commit == "cutover-store": + tip = est.origin_tip() + assert tip == est.marker and est.origin_changed(tip) == ["lanes/STORE"] + else: + est.write("t271: a write rendered before the commit") + settled = est.render(), est.wait_lag_0() + assert LAG_0.search(settled[1].stdout), ( + f"the first write was not rendered:\n{_said(settled[0])}\n{_said(settled[1])}") + if commit == "repos-tsv": + files = {"lanes/repos.tsv": est.origin_text("lanes/repos.tsv") + + "repoQ\topensoft/repoQ\n"} + else: + files = {f"handoffs/{OPERATOR}.md": "# a handoff, between renders\n"} + tip = est.push_as_person(files, f"t271: a person's {commit} commit") + assert est.origin_changed(tip) == sorted(files) + k = est.write("t271: the write after the commit") + render = est.render() + proc = est.wait_lag_0() + assert LAG_0.search(proc.stdout) and NO_DIVERGENCE.search(proc.stdout), ( + f"after the {commit} commit the render stopped or lags:\n{_said(proc)}\n{_said(render)}") + gained = est.commits_after(tip) + assert gained and gained[-1][1] == [k], f"origin gained {gained} after {tip[:12]}, not seq {k}" + assert est.origin_parent(gained[0][0]) == tip, "the render did not render onto that tip" + assert est.mirror()["diverged_sha"] is None + + +# =================================================================== R2's N6 at primary +def test_a_register_seq_above_the_head_stops_the_renderer_at_primary_and_the_revert_resumes_it( + pg, tmp_path): + """AT-6, a `Register-Seq` above the head (R2's N6), at `primary`: a + person's commit of a file under `handoffs/` carrying `Register-Seq: + <h+10>` in its final trailer block, then a write at `h+1` and its + render. The pass records a divergence at that commit and pushes nothing; + `status` prints `diverged at` its full sha and no lag, its `m` (`h`+10) + past `n` (`h`+1), as `status` says (TP:1319 at B15; Y:2850; lane 3's + L2-7); `render --revert <sha>` journals one entry with no + edits naming it, and `diverged at` clears; the renderer then finds `m` + at the last render commit before it and renders on, on top of it, to the + revert's own seq; origin equals a full render, `reconcile` exits 0, and a + rollback afterwards works. Fails until T324 and T326 (and T107, T115, + T117, T321 to T323).""" + est = Estate(tmp_path / "e", pg) + est.write("t271: a write rendered before the forged trailer") + est.render() + assert LAG_0.search(est.wait_lag_0().stdout), "the first write was not rendered" + h = est.head() + forged = est.push_as_person({f"handoffs/{OPERATOR}.md": "# a handoff, its trailer copied\n"}, + f"t271: a handoff carrying a copied trailer\n\n" + f"Register-Seq: {h + 10}") + assert est.origin_changed(forged) == [f"handoffs/{OPERATOR}.md"] + est.write("t271: a write after the forged trailer") + render = est.render() + _assert_stopped(est, forged, render) + _assert_status_diverged(est, forged, past=(h + 10, h + 1)) + seq = _way_out(est, forged, "revert") + assert est.edits(seq) == [], f"the revert's entry has edits: {est.edits(seq)}" + assert forged[:7] in (est.entry(seq)["message"] or "") + _resume(est, forged, h + 1) + assert est.origin_parent(est.commits_after(forged)[0][0]) == forged, ( + "the renderer did not render on top of the commit it passed over") + _assert_rolled_back(est, est.rollback()) + + +# =================================================================== AT-MIR's gating case +@pytest.mark.parametrize("case", ["row-only", "git-only"]) +def test_the_mirror_state_row_never_gates_alone(pg, tmp_path, case): + """AT-MIR, the row never gates alone (G; D16): `[row-only]`, with + `mirror_state` recording a divergence by `record_mirror_state` and git + holding no stray, the next render renders and `status` shows a lag of + 0; `[git-only]`, with a stray on origin and the row empty, the renderer + still stops (test 6's oracle). Fails until T107, T115, T117 and T321 to + T323 land.""" + est = Estate(tmp_path / "e", pg) + if case == "row-only": + recorded = est.record("1" * 40) + assert recorded.returncode == 0, f"record_mirror_state: {_said(recorded)}" + assert est.mirror()["diverged_sha"] == "1" * 40 + tip = est.origin_tip() + k = est.write("t271: a write with the row set") + render = est.render() + proc = est.wait_lag_0() + assert LAG_0.search(proc.stdout), ( + f"with the row set and no stray, the render did not render:\n{_said(proc)}\n" + f"{_said(render)}") + gained = est.commits_after(tip) + assert [s for _sha, found in gained for s in found] == [k], gained + return + assert est.mirror()["diverged_sha"] is None, "the row is not empty before the stray" + stray, _k, render = _stop(est) + _assert_stopped(est, stray, render) + _assert_status_diverged(est, stray) + + +# =================================================================== T324's strays +def _stray_files(est: Estate, stray: str) -> tuple: + """The stray's files, from origin's tip: `[stray-deletes-a-row]` deletes + repoD-1's row with no archive copy; `[stray-inserts-before-the-end]` + inserts a line in repoI-1's log after its `STARTED`, above its claims; + `[stray-revives-a-pair]` deletes repoX-1's `RELEASED`, so its `CLAIMED` + on `PAIR_OBJECT` is live beside repoY-1's; `[stray-no-longer-applies]` + retitles `lanes/LANES.md`'s heading by hand.""" + if stray == "stray-deletes-a-row": + path, old, new = "lanes/LANES.md", ROW_D + "\n", "" + elif stray == "stray-inserts-before-the-end": + path = "lanes/log/repoI-1.md" + old = _started("repoI-1", UUID_I1, "opensoft/repoI") + "\n" + new = old + INSERTED_I + "\n" + elif stray == "stray-no-longer-applies": + path, old, new = "lanes/LANES.md", TITLE + "\n", TITLE_BY_HAND + "\n" + else: + path, old, new = "lanes/log/repoX-1.md", RELEASED_X + "\n", "" + text = est.origin_text(path) + assert text.count(old) == 1, f"{path} does not hold the line the stray changes once" + return path, {path: text.replace(old, new)} + + +def _assert_no_longer_applies(est: Estate, sha: str, path: str) -> None: + """L2-8'S REFUSAL (TP:1292-1293; B15 tasks:2486): `import --single <sha>`, + where the stray's edits no longer apply to SQL's images, refuses with 2 + on stderr, naming the edit's path, that its edits no longer apply, and + `render --revert <sha>` as the way out (PC-4); it sends no commit call; + and it writes nothing (the module's readings).""" + before = (est.head(), est.count(), structured(est.pg), est.renders()) + log = est.root / "psql-calls.log" + front = _logging_psql(est.root / "psql-log-bin", est.pg.psql_bin, log) + proc = est.index("import", "--single", sha, + env={"PATH": str(front) + os.pathsep + est.env["PATH"]}) + assert proc.returncode == 2 and all(w in proc.stderr for w in ( + "no longer apply", path, f"render --revert {sha}")), ( + f"import --single of a stray whose edits no longer apply to SQL's images is not " + f"refused with 2 on stderr, naming {path}, that they no longer apply, and " + f"`render --revert {sha}` (lane 3's T324; L2-8):\n{_said(proc)}") + calls = (log.read_text(encoding="utf-8", errors="replace").split("--- psql ")[1:] + if log.exists() else []) + requests = [call for call in calls if not call.startswith("--version")] + assert requests, ( + "the refused import sent no request through the psql first on its PATH, so the log " + "cannot show that it sent no commit call") + sent = [call for call in requests if "commit_write(" in call] + assert not sent, ( + f"the refused import sent {len(sent)} commit call(s): it refuses before any (TP:1292; " + f"B15 tasks:2486):\n{sent[0][:1500]}") + assert (est.head(), est.count(), structured(est.pg), est.renders()) == before, ( + "the refused import changed the head, the journal, the structured tables or SQL's " + "images") + assert est.mirror()["diverged_sha"] == sha, "the refused import cleared the divergence" + assert est.origin_tip() == sha, "the refused import moved origin's main" + + +@pytest.mark.parametrize("stray", ["stray-deletes-a-row", "stray-inserts-before-the-end", + "stray-revives-a-pair", "stray-no-longer-applies"]) +def test_a_strays_single_write_import_leaves_the_tables_equal_to_the_imports_derivation( + pg, tmp_path, stray): + """T324'S STRAYS (R-F10-34; lane 3, #165 6755386771; ERR-48) and a stray + that revives a pair (R-F13c-10; lane 3's batch 5, #165 6778890211): a + person's stray commit on origin's `lanes`; the next write's render stops + `diverged at <sha>`. + + `[stray-deletes-a-row]` and `[stray-inserts-before-the-end]`: `lanes-index + import --single <sha>` loads it through `register commit` and exits 0; + the renderer resumes and `reconcile` passes; and the four structured + tables equal what `import --at` of the same mirror leaves in a second + clone's database, compared as T221's step-6 cases compare them, without + the columns a write stamps, which ERR-48's re-stamped later lines are. + The insert's holds below its line each point at their own line. + + `[stray-revives-a-pair]`: two claims on one object are live after it, + neither `exempt`, since only an import sets `exempt`; `import --single` + refuses with 2, LR005 `one-live-claim` and `held-by=`, writes nothing, + and leaves the four tables as they were. Its way out is the revert, + which `test_the_renderers_revert_resumes_it_and_reconcile_passes` covers. + + `[stray-no-longer-applies]` (lane 3, #165 6809045090, L2-8; AT-6, + TP:1292-1293; B15 tasks:2486): a primary write changes a line after the + stray commit changed it, so the stray's edits no longer apply to SQL's + images; `import --single` refuses with 2, naming the edit and `render + --revert <sha>` as the way out (PC-4), sends no commit call, writes + nothing, and leaves the four tables as they were. + + Fail until T324 (and T107, T115, T117, T321 to T323); the oracle, until + T115's `import --at`; `[stray-revives-a-pair]`, until T324's refusal and + T107's `one_live_claim`; `[stray-no-longer-applies]`, until T324's + `import --single` refusal.""" + est = Estate(tmp_path / "e", pg) + if stray == "stray-revives-a-pair": + holds = {(h["lane_key"], h["verb"], h["exempt"]) for h in est.rows( + f"SELECT lane_key, verb, exempt FROM object_holds " + f"WHERE lower(object) = lower('{PAIR_OBJECT}')")} + assert holds == {("repox-1", "RELEASED", False), ("repoy-1", "CLAIMED", False)}, ( + f"the control: at C repoX-1 has released {PAIR_OBJECT} and repoY-1 holds it, " + f"neither exempt: {holds}") + path, files = _stray_files(est, stray) + sha = est.push_as_person(files, f"t271: a stray edit of {path}, by hand") + assert est.origin_changed(sha) == [path] + if stray == "stray-no-longer-applies": + est.replace_line(path, 1, TITLE_IN_SQL) + else: + est.write("t271: a primary write after the stray") + render = est.render() + _assert_stopped(est, sha, render) + if stray == "stray-no-longer-applies": + _assert_no_longer_applies(est, sha, path) + return + if stray == "stray-revives-a-pair": + before, head, count = structured(est.pg), est.head(), est.count() + proc = est.import_single(sha) + said = proc.stdout + proc.stderr + assert proc.returncode == 2 and all(w in said for w in ("LR005", "one-live-claim", + "held-by=")), ( + f"import --single of a stray that revives a pair is not refused with 2, LR005 " + f"one-live-claim and held-by= (lane 3's T324):\n{_said(proc)}") + assert (est.head(), est.count()) == (head, count), "the refused import wrote an entry" + assert structured(est.pg) == before, "the refused import changed the structured tables" + assert est.mirror()["diverged_sha"] == sha, "the refused import cleared the divergence" + return + _way_out(est, sha, "import") + _resume(est, sha, 2) + got = structured(est.pg) + tip = est.origin_tip() + second = Workspace(tmp_path / "oracle", origin=est.origin) + oracle_db = Database(est.pg.cluster, est.pg.cluster.new_database()) + try: + conf = est.config(oracle_db, "index", name="oracle") + proc = est.import_at(tip, conf=conf, cwd=second.wip, + env={"LANES_REPO": str(second.wip), "HOME": str(second.home), + "AGENT_PROTOCOL_ROOT": str(second.agents)}) + assert proc.returncode == 0, ( + f"the oracle's import --at {tip[:12]} of the mirror failed (lane 1's T115):\n" + f"{_said(proc)}") + want = structured(oracle_db) + finally: + est.pg.cluster.drop_database(oracle_db.name) + for table in STRUCTURED: + assert got[table] == want[table], ( + f"{stray}: {table} is not the import's derivation of the mirror:\n" + f"got {json.dumps(got[table], indent=1)[:3000]}\n" + f"want {json.dumps(want[table], indent=1)[:3000]}") + if stray == "stray-inserts-before-the-end": + lines = {(r["path"], r["line_no"]): r for r in got["log_lines"]} + for hold in got["object_holds"]: + if hold["file"] == path: + line = lines[(hold["file"], hold["ordinal"])] + assert (line["object"], line["verb"]) == (hold["object"], hold["verb"]), ( + hold, line) diff --git a/tests/test_sql_register_drill.py b/tests/test_sql_register_drill.py new file mode 100644 index 00000000..bf3fa7b5 --- /dev/null +++ b/tests/test_sql_register_drill.py @@ -0,0 +1,1409 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Feature 007's test 13 and AT-F4: the drill, and the ruleset's order (L2-G5; +AT-13; AT-F4; T276; FR-050, FR-051, FR-059; also US7) +(opensoft/openRepoTools#165). + +T276 writes this module: 5 tests, AT-13's 2 and AT-F4's 3 (B15 tasks:2535, +"Write test 13 and AT-F4, the drill and the ruleset's order"). Lane 3's T326 +runs it whole: its verify's word `sql_register_drill` selects these five ids +(B15 tasks:1542). + +THE ESTATE, `Drill` (the test plan's AT-13, "Fixture"): + +- SECTION 5.6'S TLS CLUSTER, T229's `tls_cluster`: a stoppable cluster on + loopback TCP with TLS 1.3 and SCRAM, and a test CA of its own. The drill's + database is a database of its own on it, made empty and bootstrapped by P8's + bootstrap through the admin service with `--label register-drill`, as AT-P8's + ready environment makes one (`TLSCluster.second_database`). Step 1's + readiness check needs check 11, which a Unix socket always fails (AT-LRMPG). +- TWO ENGINEERS' LOGINS, `drill_a` and `drill_b`, made after the bootstrap by + `lanes-index login add <engineer> --admin-service <service>` under a pty + (operations.md act 3's step 2, "Then the logins"; `Cluster.lanes_index_tty`, + as T228 makes the fixture's). The passwords each prints once are kept in the + cluster's memory for its password files, and never printed. +- A BARE ORIGIN WITH THE FIXTURE REGISTER: test 7's, by pgcluster's + `ImportedRegister` (T227b): AT-7's seed and the operator lane's `log NOTED` + on top. Its operator checkout, with its W and `workspace.yaml`, is ws1's. +- TWO WORKSTATIONS, ws1 (`Eagle`, the operator lane `repoA-2`, engineer + `drill_a`) and ws2 (`Hawk`, lane `repoW-1`, engineer `drill_b`, a clone of + its own), each with its own `$HOME`, `workspace.yaml`, register checkout, W + and 0600 configuration at `mode=index`. A configuration names only its own + engineer's two logins and password files, over `sslmode=verify-full` with + the test CA's root as `sslrootcert=`, with `register_label=register-drill` + (the cutover takes its label from it, S5) and `register_addresses=1` + (127.0.0.1 is one address; check 13). Each workstation's installed-tools + directory holds T203's flipped `lanes-index` (`RENDER_GIT_HALF = True`, so + `cutover`, `rollback` and a write on primary take `lanes_register` while + lane 3's T328 has not set the constant), with `lanes-edit.sh`, `lanes`, + `lane-start` and `repos.tsv` beside it, and check 1's digest list naming + both tools. +- EACH LANE'S OWN REGISTER CHECKOUT, `<c>` (lane 3's batch g Q119, #165 + 6813027223): on primary a write reads its author, its pending hand edits + and its `repos.tsv` from `<W>-lanes/<lane>`, W being the real path of its + workstation's `workspace.yaml` `path:`, and refuses 2 where it is not there + (B15 tasks:1154; lane 4's T415). So each workstation makes its own lane's, + `repoA-2` on ws1 and `repoW-1` on ws2, a clone of origin, as step 3 flips + it to `mode=primary`, after the cutover's push and before any write on + primary (`Workstation.lane_checkout`; T276e). +- THE RULESET'S MODEL (AT-F4; Q21(b), the render set and `lanes/STORE`, + Brett's "Render set + STORE", comment 6721583757): `RULESET_HOOK`, T271's + pre-receive hook (test 6) with a switch file the drill's runbook steps set, + and the renderer's identity let through. +- THE FREEZE (Q4(a)(i)): no other writer runs during steps 2 and 3; the drill + runs none. + +THE ORDER (AT-F4's ruling): the drain's last `PAUSED` write, the ruleset on, +the import at C, the cutover, then the flips; the rollback stops at +`--hold-marker` once the mirror is proved current, the ruleset goes off, and +the rerun pushes the removal of `lanes/STORE`. + +WHAT EACH FAILS UNTIL. B15's Order (tasks:2542): it waits for T229, and its +tests fail until L1-A18, T326 and T327 land. Each step's labelled assertion +also names the tasks its own verbs rest on, by their B15 bullets, and lane +4's by lane 4's reading of its own code (#165 6826679959, item 1): + 1. `ready` (T119; its fourteenth check, git 2.32 or later, is lane 1's + T119 follow-up 2), the logins (T110) and the TLS cluster (T229); + 2. `import --at` (T115, L1-A13); + 3. `cutover` (T116, L1-A14) and its marker's push, read-back and + `record_marker` (lane 3's T327); the flips (T120); + 4. a write on primary (lane 4's T415), its render fork (T416) and the + renderer (lane 3's T321 to T323); `status`'s lag (T117); + 5. `claim` and `log` on primary from both workstations (lane 4's T415), + each rendered and settled as at step 4 (T416); + 6. a write's 69 (T415); the guard's direct read and its refusal (lane 5's + T507); the mirror line (lane 5's T505); `status` (T117); `outage + declare` (T121, L1-A18) and the guard's declared path (T507's SVC-12); + 7. `rollback`'s 69 (T304) and `outage clear` (T121); + 8. `rollback --hold-marker` and its rerun (lane 3's T326), and its + declaration (T121, T304); + 9. the writer not yet cleared, 69, ended at its snapshot (lane 4's T415); + 10. the rollback's last render (T326). +The drill runs no `commit`, and no step reads the `register seq` text of +`claim`, so lane 4's T420 and T421 are none of its waits (lane 4, #165 +6826679959, item 1). Lane 5's T507 is step 6's alone: only `step_6_outage` +calls the guard (lane 5, #165 6826891706). +On line R's `V-round5` (`e8804a4a`), which holds T110, T115, T116, T119, T120, +T121, T304 and T320 to T323 but not T327, T326, T415 or T507, every test stops +at step 3's assertion on the marker: `cutover` exits 0 with the marker +`adding` and nothing pushed (T116's point 1). On lane 3's `T326-m23` +(`552c22d4`), which adds T327 and T326 but not T415, step 3 passes, and a +test that runs step 4 stops there: `lanes-edit.sh` has no SQL write path. +With lane 4's `pair-m23s` (`d949b78`) on it too, step 4 refused 2 where its +lane's `<c>` was not there (line RB15's run e03), which step 3 now makes +(T276e). + +READINGS, NOT FOUND IN A CONTRACT: +- "THE RENDERER'S IDENTITY" (AT-F4's fixture): a bare origin on disk cannot + see D23's deploy key, and a render commit carries the journal's author as + its committer (D15), so neither tells the renderer apart. The model reads + the pushing program instead: a push is the renderer's where a process above + the receiving `git` runs `lanes-index` (the renderer's pass, `cutover`'s + marker push and `rollback`'s removal, each through T320's one push + function), and anyone else's otherwise (`lanes-edit.sh`'s files-mode push, + a person's `git push`). Lane 3 accepted this model, with the check outside + pytest as its control, and suggested that the hook log the process it + found, so that a failure names it (#165 6813027223): each record carries + `found` and `walked`. +- C IS ORIGIN'S TIP AT THE IMPORT, after the freeze's `PAUSED` write and + AT-F4's accepted pushes: the cutover checks that the tip's `lanes` tree is + C's (T327's step 2), and the import runs from ws1's checkout fetched to it. +- "THE LAST `PAUSED` WRITE" is the drain's row write, `set-row-state <lane> + "PAUSED ..."` (lane-handoff's W9), for `repoD-1`, a LIVE row of the fixture + register that no other step writes, run in files mode from ws2. +- STEP 6'S "THE GUARD ANSWERS FROM THE MIRROR" is AT-D20's oracle for a + bound lane (T215; TP:3931 in Y's frame, "the guard exits 0 for `ok` and 2 + for `refuse`, printing the declared line"): the `read: mirror at <sha12>` + line, the declared line in place of the cause, and exit 0. The guard runs + in the lane's window with a live session record (T203c's + `guard_session`), the lane's row's session id as its own, so it reaches + its direct read (lane 3's T507 ruling (1)), and the mirror's row binds it. + ITS CONTRAST, in the same step: the same session, its id and name, in a + window named for the other workstation's lane, whose row names another + session as AT-D20's `refuse` row does, gets the same two lines and exit 2, + for that row's own cause alone: it ends on that lane's session and does + not name this one at all, with no Amendment 18(h) duplicate (T276h). So + the mirror's own row decides, a 0 that only fails open cannot pass, and + neither can a 2 for another cause. T276 compared the exit with a + reference instead, the same guard with a `mode=index` copy of the + configuration. Once the cutover has put `lanes/STORE` on origin, + `mode=index` refuses 2 whatever the session, by design (F17, + `reg_marker_check`'s `guard` arm), so no bound lane's 0 could equal it + (lane 5, #165 6868723007; lane 2's choice (a), T276g). + THE CONTRAST'S CAUSE IS A PIN: it holds the guard's own sentence word for + word, from the last `guard_refuse_start` in `lanes-edit.sh`'s `guard_run`, + the name table's last arm ("whose row does not name this uuid at all"): + `lanes-edit.sh:21565` on line R's merge106 (`bc9ed80b`), `:21515` on + merge104 (`142afd90`) and `:21493` on merge101 (`44f487d1`), where T276h + took it character for character. A change of that sentence fails step + 6's contrast, so change the two together (T276i). +- STEP 6'S REFUSAL names the database as `register_url=` gives it, without + credentials (lane 3, #165 6809045090 and 6812459759, as the outage module + holds AT-P3's oracle), and its stderr carries no password. +- WHICH STEPS EACH TEST RUNS: `test_the_drill_import_cutover_outage_rollback_ + and_files_mode_write` runs all ten. `test_a_workstation_not_yet_cleared_ + refuses_after_rollback` runs steps 1 to 4 and 8, then step 9's ws2 half + with a fuller oracle. AT-F4's three run the order's steps they read: the + freeze, the import, the cutover and the flips, and, for the two after the + rollback, step 8; never steps 1, 4, 5, 6 or 7, whose oracles are AT-13's. + So their rollback starts with the head at the cutover's seq: AT-F4's + oracle names no write on primary, and its Order (B17 tasks:2544, "Order: + waits for T229") has its tests fail until L1-A18, T326 and T327 alone, + where step 4's write would also need lane 4's T415 and T416 (T276d, + after line DR15's run on T326-m23 met T415's placeholder there). +- OPEN POINT 8'S POLL READS A FETCHED W: `status` reads `m` on W's + `origin/main` as last fetched and never fetches (tasks:545), and no write + on primary fetches W (D12), while the render pushes from the lane's `<c>`. + So `wait_lag_0` fetches ws1's W with plain git before each poll (lane 3's + ruling (a), #165 6833830078), as the drill's act, not a write's. +- STEP 10'S "EVERY OBJECT HAS AT MOST ONE HOLDER" is read for the objects the + drill claims, across SQL's live holds and origin's logs, as T273b's + `_claim_holders` reads one. + +HELPERS COPIED, NEVER SHARED (a module's own): `_rows`, `_renders`, +`RENDER_SET`, `REGISTER_SEQ` and `LAG_0` from `test_sql_register_import.py` +(T211's and T272's, in this base); `CHECK_LINE` and `_checks` from +`test_sql_register_operator_tools.py` (T218); the hook's path rule and its +`changed` from T271's `GATE_HOOK` (`test_sql_register_divergence.py`, line +DV's `92fbaf27`); the guard's run and `_label` from T215's outage module +(line W4a); `MIRROR_LINE` from the readers module (line N1); the holders' +rule from T273b's `_claim_holders` (line RB); `_masked` from +`tests/pgcluster.py`. From the fixture and H's helpers, which each real-engine +module imports: `tls_cluster`, `ImportedRegister`, `PASSWORD_LINE`, +`ClusterError`, `flipped_copy`, `guard_session` and `guard_strip_env`. + +THE PATH (wave 11's policy, mask and never drop): no call here drops a `PATH` +directory. Each workstation puts its fake `tmux`, its tools and the engine's +binaries first and keeps every inherited directory behind them, so its `psql` +is the server's and its `lanes-index` its own copy; nothing is masked. + +Every wait here has a ceiling: each poll, `SETTLE_S`; each command, its +`timeout`; the guard, its 5 s kill. Every id is RE: it asks for the TLS +cluster, and without PostgreSQL 16 it skips with T205's banner. +""" + +from __future__ import annotations + +import base64 +import hashlib +import json +import os +import re +import shutil +import signal +import subprocess +import sys +import time +from pathlib import Path + +import pytest + +from conftest import REPO, WINDOWS_SKIP +from pgcluster import PASSWORD_LINE, ClusterError, ImportedRegister +from sql_register_helpers import flipped_copy, guard_session, guard_strip_env + +pytestmark = [WINDOWS_SKIP, pytest.mark.skipif( + shutil.which("bash") is None or shutil.which("git") is None, + reason="the lane tooling is bash over git")] + +#: THE LANDING GATE'S TABLE (T280, `tests/sql_register_gate.py`; task sets +#: version 12b's rule 11, opensoft/openRepoTools#165 6877673742), TEMPORARY: +#: T281 removes it in the last set. Where the gate is active, each id here is +#: skipped until every task its row names has landed, and the skip names them. +#: Each row is the fails-until clause of T276's Order (tasks:2544) in tasks.md +#: at lane 3's commit 17, 204145ae, L1-A18 as T121, the task that covers it, +#: as lane 2's plan GP-24 v2 (sha256 9600adda) gives it. Every id waits for +#: the "*" row; the drill itself also for T415, T416 and T507, and the +#: uncleared workstation's case for T415 and T416. AT-F4's three wait for +#: nothing more. Since T276k the two AT-13 ids also wait for T119: step 1, +#: which both run, counts `ready`'s fourteen checks, and check 14 is lane 1's +#: T119 follow-up 2 (T276's line, tasks:2537 at lane 3's commit 24, f9d6069e). +SQL_REGISTER_GATE_TABLE = { + "*": ("T121", "T326", "T327"), # every id: the tasks all its rows share + "test_a_workstation_not_yet_cleared_refuses_after_rollback": ("T119", "T415", "T416"), # T276; tasks:2544; T119: tasks:2537 + "test_the_drill_import_cutover_outage_rollback_and_files_mode_write": ("T119", "T415", "T416", "T507"), # T276; tasks:2544; T119: tasks:2537 +} + +INDEXER = REPO / "lanes-index" + +#: The register's schema, `register_schema=`'s default. +SCHEMA = "lanes_register" +#: The drill database's switch label: the bootstrap's `--label`, and each +#: configuration's `register_label=`. +LABEL = "register-drill" + +#: Each workstation's engineer (`lanes-index login add <engineer>` makes +#: `lanes_w_<engineer>` and `lanes_r_<engineer>`), its name (Rule 10), its +#: lane, and that lane's row's session id in the fixture register (pgcluster's +#: `_test7_seed`), which its guard session takes as its own. +ENGINEERS = {"ws1": "drill_a", "ws2": "drill_b"} +WORKSTATIONS = {"ws1": "Eagle", "ws2": "Hawk"} +OPERATOR = "repoA-2" +WS2_LANE = "repoW-1" +SESSIONS = {OPERATOR: "aaaaaaaa-0003-4000-8000-00000000a003", + WS2_LANE: "eeeeeeee-0002-4000-8000-00000000e002"} +#: The lane whose row the drain's last `PAUSED` write sets: LIVE at C, and +#: written by no other step. +DRAINED = "repoD-1" + +#: The release `ready` checks the installed tools against (check 1's list). +RELEASE, ENV_NAME = "0.0.0-t276", "drill" +DIGEST_LIST = f"openRepoTools-{RELEASE}.sha256" + +#: The objects the drill claims: on primary from each workstation (step 5), +#: then in files mode after the rollback (step 9). +OBJECTS = {"ws1": "opensoft/repoQ#31", "ws2": "opensoft/repoQ#32", + "ws1-files": "opensoft/repoQ#33", "ws2-files": "opensoft/repoQ#34"} + +#: Step 6's declaration, on Brett's word (D20). +UNTIL = "2999-01-01T00:00:00Z" +WHY = "the drill: the register database is stopped" + +#: AT-D9's `status` row, 8 s; step 6 holds it to twice that (timing rule 2). +STATUS_BOUND_S = 8 +#: The prompt hook's kill timer. +GUARD_TIMEOUT = 5 +#: The ceiling of every poll here: a render to reach origin, `status`'s lag. +SETTLE_S = 60 +#: The declaration's file, beside the configuration (D20; config.md section 6). +OUTAGE_FILE = "register-outage" + +DOT = chr(0xB7) + +#: The render set (Q18 (A); CLI4.10 section 3.6), as T211's module has it. +RENDER_SET = re.compile(r"^lanes/(LANES\.md|aliases\.tsv|archive/[^/]+\.md" + r"|log/(?!README\.md$)[^/]+\.md)$") +#: The trailer each mirror commit and each operator entry's commit carry. +REGISTER_SEQ = re.compile(r"^Register-Seq: ([0-9]+)$", re.M) +#: `status`'s lag line at a lag of 0, on primary (lane 1's T117). +LAG_0 = re.compile(r"^\s*lag:\s+0 seq", re.M) +#: One check's line of `ready` (T119's form). +CHECK_LINE = re.compile(r"^check (\d+): (ok|FAIL)\b:?[ \t]*(.*)$", re.M) +#: The `read: mirror` line (design S3): stderr, `read: mirror at <sha12>, ...`. +MIRROR_LINE = re.compile(r"^read: mirror at [0-9a-f]{12}, .*$", re.M) +#: The refusal's added name, after "the register could not be read (". +ADDED_NAME = re.compile(r"the register could not be read \(([^)]*)\)") +#: A holding line in a lane's log, and its lane. +HOLDS = re.compile(r"^(CLAIMED|TAKEOVER) \S+ lane ([^,\s]+),") +#: A password-file line's last field, hidden by `_masked`. +_SECRET_FIELD = re.compile(r"^(\*:\*:.*:)[^:\n]*$", re.M) + + +# ------------------------------------------------------------------ the ruleset's model +#: AT-F4'S MODEL OF THE ORGANISATION'S PUSH RULESET: T271's `GATE_HOOK` (test +#: 6's pre-receive hook, guarding exactly the render set and `lanes/STORE`), +#: with two things AT-F4's fixture adds. It is SWITCHED by a file the drill's +#: runbook steps set: off, it lets every push through. It LETS THE RENDERER'S +#: IDENTITY THROUGH: a push from a process tree that runs `lanes-index` (see +#: the readings). Each push is one JSON line of its log, with the switch's +#: state, who pushed, the process it found (`found`, null for `other`), the +#: processes it walked to find it (`walked`), and the outcome. So each AT-F4 +#: failure, which prints the records, names the process the model saw, and a +#: refusal's stderr names the walk (lane 3, #165 6813027223). +RULESET_HOOK = r'''#!/usr/bin/env -S python3 -I +# T276's model of the organisation's push ruleset (AT-F4), from T271's model +# of the server-side gate (test 6): a model, since the suite cannot reach +# GitHub. +import json, os, re, subprocess, sys +SWITCH = SWITCH_PATH +LOG = LOG_PATH +TOP = TOP_PID +GUARDED = re.compile(r"^lanes/(LANES\.md|aliases\.tsv|STORE|archive/.+" + r"|log/(?!README\.md$)[^/]+\.md)$") +ZERO = "0" * 40 +RENDERER = "lanes-index" + + +def git(*args): + return subprocess.run(["git", *args], capture_output=True, text=True, + check=True, timeout=60).stdout + + +def changed(old, new): + revs = git("rev-list", new if old == ZERO else f"{old}..{new}").split() + paths = set() + for rev in revs: + out = git("diff-tree", "--root", "--no-commit-id", "-r", "-m", "--no-renames", + "--name-only", "-z", rev) + paths.update(p for p in out.split("\0") if p) + return sorted(paths) + + +def parent(pid): + """(the parent's pid, the first words of the process's argv).""" + try: + with open(f"/proc/{pid}/stat", "rb") as handle: + stat = handle.read().decode("utf-8", "replace") + with open(f"/proc/{pid}/cmdline", "rb") as handle: + argv = [a.decode("utf-8", "replace") for a in handle.read().split(b"\0") if a] + return int(stat.rsplit(") ", 1)[1].split()[1]), argv[:4] + except (OSError, ValueError, IndexError): + out = subprocess.run(["ps", "-o", "ppid=", "-o", "args=", "-p", str(pid)], + capture_output=True, text=True, timeout=10).stdout.split() + if not out: + return 0, [] + return int(out[0]), out[1:5] + + +def pusher(): + """(who, found, walked): `renderer` where a process above this hook runs + `lanes-index`, else `other`; `found`, that process as {"pid", "argv"}, + or None; and `walked`, each process the walk read, from the hook's + parent up, each argv's first four words, so that a failure names what + the model saw (lane 3's suggestion, #165 6813027223). The walk stops + below `TOP`, the test's own process, which every push the drill makes + descends from: no process the case did not start is read or logged.""" + pid, walked = os.getppid(), [] + for _ in range(64): + if pid <= 1 or pid == TOP: + break + up, argv = parent(pid) + seen = {"pid": pid, "argv": argv} + walked.append(seen) + if any(os.path.basename(word) == RENDERER for word in argv): + return "renderer", seen, walked + pid = up + return "other", None, walked + + +def main(): + try: + with open(SWITCH, encoding="utf-8") as handle: + state = handle.read().strip() + except OSError: + state = "off" + who, found, walked = pusher() + pushes, hits = [], [] + for line in sys.stdin: + old, new, ref = line.split() + if new == ZERO: + continue + paths = changed(old, new) + guarded = [p for p in paths if GUARDED.match(p)] + pushes.append({"ref": ref, "old": old, "new": new, "paths": paths, "guarded": guarded}) + hits += guarded + refused = state == "on" and bool(hits) and who != "renderer" + with open(LOG, "a", encoding="utf-8") as handle: + handle.write(json.dumps({"state": state, "pusher": who, "found": found, + "walked": walked, + "outcome": "refused" if refused else "accepted", + "pushes": pushes}) + "\n") + if refused: + sys.stderr.write("t276 ruleset model: a push to the render set or lanes/STORE by " + "an identity other than the renderer's is refused: " + + ", ".join(sorted(set(hits))) + "; no lanes-index above the " + "hook, which walked: " + + " < ".join(f"{p['pid']} {' '.join(p['argv'])}" for p in walked) + + "\n") + return 1 + return 0 + + +sys.exit(main()) +''' + + +def _private(path: Path, text: str) -> Path: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8") + path.chmod(0o600) + return path + + +def _script(path: Path, text: str) -> Path: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8") + path.chmod(0o755) + return path + + +def _masked(text: str) -> str: + """`text` with each password-file line's password hidden.""" + return _SECRET_FIELD.sub(lambda m: m.group(1) + "<password>", text or "") + + +def _said(proc) -> str: + return (f"exit {proc.returncode}\n--- stdout ---\n{_masked(proc.stdout)[-2000:]}" + f"\n--- stderr ---\n{_masked(proc.stderr)[-2000:]}") + + +def _checks(text: str) -> dict: + """`ready`'s check lines, by number: (`ok` or `FAIL`, the reason).""" + return {int(m.group(1)): (m.group(2), m.group(3) or "") for m in CHECK_LINE.finditer(text)} + + +def _fields(path: Path) -> dict: + return dict(line.split("=", 1) for line in + path.read_text(encoding="utf-8").splitlines() if "=" in line) + + +def _label(fields: dict) -> str: + """The declared line the guard prints in place of the cause (D20).""" + return f"(declared outage {fields['utc']}: {fields['why']})" + + +def _rows(db, sql: str) -> list: + """`sql`'s rows as JSON objects, in the register's schema, by `jsonb_agg`, + whose text is one line.""" + out = db.psql(f"SET search_path TO {SCHEMA};\n" + f"SELECT coalesce(jsonb_agg(t), '[]'::jsonb) FROM ({sql}) t;\n").stdout + return json.loads(out.strip().splitlines()[-1]) + + +def _renders(db) -> dict: + """SQL's own render (lane 1's T107, `render_file`) of every path in + `files`, {path: bytes}.""" + return {r["path"]: base64.b64decode(r["b64"]) for r in _rows( + db, "SELECT path, encode(render_file(path), 'base64') AS b64 FROM files ORDER BY path")} + + +class Ruleset: + """`RULESET_HOOK` in origin's `hooks/`, its switch file and its log, both + beside origin and never in a work tree, and this test's own pid, where + the hook's walk stops. It starts off.""" + + def __init__(self, root: Path, origin: Path): + root.mkdir(parents=True, exist_ok=True) + self.switch, self.log = root / "ruleset-state", root / "ruleset.log" + self.off() + _script(origin / "hooks" / "pre-receive", + RULESET_HOOK.replace("SWITCH_PATH", repr(str(self.switch))) + .replace("LOG_PATH", repr(str(self.log))) + .replace("TOP_PID", str(os.getpid()))) + + def on(self) -> None: + self.switch.write_text("on\n", encoding="utf-8") + + def off(self) -> None: + self.switch.write_text("off\n", encoding="utf-8") + + def state(self) -> str: + return self.switch.read_text(encoding="utf-8").strip() + + def records(self) -> list: + if not self.log.exists(): + return [] + return [json.loads(line) for line in self.log.read_text(encoding="utf-8").splitlines() + if line] + + def record_of(self, sha: str) -> list: + """The records of each push that moved a ref to `sha`.""" + return [r for r in self.records() if any(p["new"] == sha for p in r["pushes"])] + + +class Person: + """A person's clone of origin, for AT-F4's probes: plain `git` with an + identity of its own, outside every lane tool, so the model sees no + renderer above its push.""" + + def __init__(self, root: Path, origin: Path): + self.root, self.clone = root, root / "clone" + (root / "home").mkdir(parents=True) + env = {k: v for k, v in os.environ.items() if not k.startswith(("GIT_", "LANES_", "PG"))} + env.update(HOME=str(root / "home"), GIT_CONFIG_NOSYSTEM="1", GIT_CONFIG_GLOBAL=os.devnull, + GIT_TERMINAL_PROMPT="0", GIT_AUTHOR_NAME="A person", + GIT_AUTHOR_EMAIL="person@example.invalid", GIT_COMMITTER_NAME="A person", + GIT_COMMITTER_EMAIL="person@example.invalid") + self.env = env + self.git("clone", "-q", str(origin), str(self.clone), cwd=root) + + def git(self, *args: str, cwd: Path | None = None, check: bool = True): + proc = subprocess.run(["git", *args], cwd=str(cwd or self.clone), env=self.env, + capture_output=True, text=True, timeout=120, + stdin=subprocess.DEVNULL, check=False) + if check: + assert proc.returncode == 0, f"the person's git {' '.join(args[:2])}:\n{_said(proc)}" + return proc + + def push(self, path: str, text: str) -> tuple: + """One commit on origin's tip adding `text` to `path`, pushed to + `main`: (the push, the commit).""" + self.git("fetch", "-q", "origin") + self.git("reset", "-q", "--hard", "origin/main") + target = self.clone / path + target.parent.mkdir(parents=True, exist_ok=True) + old = target.read_text(encoding="utf-8") if target.exists() else "" + target.write_text(old + text, encoding="utf-8") + self.git("add", "--", path) + self.git("commit", "-q", "-m", f"a person's edit of {path}") + sha = self.git("rev-parse", "HEAD").stdout.strip() + return self.git("push", "-q", "origin", "HEAD:main", check=False), sha + + +# ------------------------------------------------------------------ the workstations +class Workstation: + """One workstation of the drill (see the module's notes): its `$HOME`, its + register checkout and W, its configuration, its installed tools, and the + environment each of its commands runs in, as its lane, on its name.""" + + def __init__(self, drill: "Drill", name: str, lane: str, *, home: Path | None = None, + checkout: Path | None = None): + self.drill, self.name, self.lane = drill, name, lane + self.engineer, self.workstation = ENGINEERS[name], WORKSTATIONS[name] + self.root = drill.root / name + self.root.mkdir(parents=True) + if home is None: + home = self.root / "home" + checkout = home / "projects" / "wip" + checkout.parent.mkdir(parents=True) + drill.git("clone", "-q", str(drill.origin), str(checkout)) + # W, a view of the checkout (Amendment 23 S5), which + # `workspace.yaml` names, so `LANES_REPO` is never W. + w = self.root / "ro" / "wip" + w.mkdir(parents=True) + (w / ".git").write_text(f"gitdir: {os.path.realpath(checkout / '.git')}\n", + encoding="utf-8") + (w / "lanes").symlink_to(checkout / "lanes") + (home / ".agents").mkdir(parents=True) + (home / ".agents" / "workspace.yaml").write_text( + f"repository: {drill.origin}\npath: {w}\n", encoding="utf-8") + self.home, self.checkout = home, checkout + # W, as this workstation's `workspace.yaml` names it: ws1's is the + # estate's, ws2's the view above. Its lane's `<c>` goes beside it. + named = [line[len("path:"):].strip() for line in + (home / ".agents" / "workspace.yaml").read_text(encoding="utf-8").splitlines() + if line.startswith("path:")] + assert len(named) == 1, f"[estate] {name}'s workspace.yaml names no one W: {named}" + self.w = Path(named[0]) + # THE INSTALLED TOOLS: the flipped copy, its companions, check 1's list. + self.tools = self.root / "tools" + try: + self.copy = flipped_copy(INDEXER, self.tools, True) + except ValueError as exc: + raise AssertionError(f"[estate] lanes-index cannot be flipped to its git half " + f"({exc}): lane 1's RENDER_GIT_HALF (T105) has not " + f"landed") from exc + for companion in ("lanes-edit.sh", "lanes", "lane-start", "repos.tsv"): + if (REPO / companion).exists(): + shutil.copy2(REPO / companion, self.tools / companion) + (self.tools / DIGEST_LIST).write_text("".join( + f"{hashlib.sha256((self.tools / tool).read_bytes()).hexdigest()} {tool}\n" + for tool in ("lanes-index", "lanes-edit.sh")), encoding="utf-8") + self.fakebin = self.root / "fakebin" + _script(self.fakebin / "tmux", "#!/bin/sh\nexit 1\n") + for directory in ("state", "config", "tmp"): + (self.root / directory).mkdir() + self.conf = _private(self.root / "conf" / "lanes-index.conf", self.conf_text("index")) + cluster = drill.cluster + env = guard_strip_env(os.environ, strip=("XDG_", "GIT_", "EMAIL", "WORKBENCHES_")) + inherited = [entry for entry in os.environ.get("PATH", os.defpath).split(os.pathsep) + if entry] + env.update( + HOME=str(home), AGENT_PROTOCOL_ROOT=str(home / ".agents"), + TMPDIR=str(self.root / "tmp"), XDG_STATE_HOME=str(self.root / "state"), + XDG_CONFIG_HOME=str(self.root / "config"), CLAUDE_CONFIG_DIR=str(home / ".claude"), + LANES_WORKSTATION=self.workstation, LANES_HOST=self.workstation.lower(), + LANES_OS="linux", LANES_CONTAINER="none", LANES_IN_CONTAINER="0", + LANES_NO_GITHUB="1", LANES_REPO=str(checkout), + LANES_EDIT=str(self.tools / "lanes-edit.sh"), LANES_INDEX_CONFIG=str(self.conf), + LANES_LANE=lane, GIT_AUTHOR_NAME=f"Drill {self.engineer}", + GIT_AUTHOR_EMAIL=f"{self.engineer}@example.invalid", + GIT_COMMITTER_NAME=f"Drill {self.engineer}", + GIT_COMMITTER_EMAIL=f"{self.engineer}@example.invalid", + GIT_CONFIG_NOSYSTEM="1", GIT_CONFIG_GLOBAL=os.devnull, GIT_TERMINAL_PROMPT="0", + PATH=os.pathsep.join([str(self.fakebin), str(self.tools), str(cluster.bindir), + *inherited])) + self.env = env + self._session = None + + def lane_checkout(self) -> Path: + """`<c>`, THIS LANE'S OWN REGISTER CHECKOUT (the module's notes; lane + 3's batch g Q119, #165 6813027223): `<W>-lanes/<lane>`, W being the + real path of `workspace.yaml`'s `path:`, as `lanes-edit.sh`'s + `lane_checkout_path` puts it (Amendment 23 S1). A clone of origin, as + `lane-checkout <lane> --create` makes one, in LX's T253f style; one + that is already there is kept.""" + real = Path(os.path.realpath(self.w)) + target = real.parent / f"{real.name}-lanes" / self.lane + if not target.exists(): + target.parent.mkdir(parents=True, exist_ok=True) + self.drill.git("clone", "-q", str(self.drill.origin), str(target)) + return target + + # ------------------------------------------------------------ configuration + def conf_text(self, mode: str) -> str: + """The 0600 configuration's text at `mode`: this engineer's two logins + over TLS (lane 1's URL form, `verify-full` and the root alone), their + password files, the label, the schema, and check 13's count.""" + cluster, database = self.drill.cluster, self.drill.db.name + writer, reader = f"lanes_w_{self.engineer}", f"lanes_r_{self.engineer}" + return "\n".join([ + f"mode={mode}", f"register_url={cluster.url(writer, database)}", + f"register_passfile={cluster.passfile(writer)}", + f"reader_url={cluster.url(reader, database)}", + f"reader_passfile={cluster.passfile(reader)}", f"register_label={LABEL}", + f"register_schema={SCHEMA}", "register_addresses=1", ""]) + + def conf_state(self) -> tuple: + return (self.conf.read_text(encoding="utf-8").splitlines(), + self.conf.stat().st_mode & 0o777) + + def outage_file(self) -> Path: + return self.conf.parent / OUTAGE_FILE + + # ------------------------------------------------------------ commands + def _env(self, env: dict | None) -> dict: + child = dict(self.env) + for key, value in (env or {}).items(): + if value is None: + child.pop(key, None) + else: + child[key] = value + return child + + def index(self, *args: str, env: dict | None = None, + timeout: float = 300) -> subprocess.CompletedProcess: + """This workstation's `lanes-index`, in its checkout, as its lane.""" + return subprocess.run([sys.executable, str(self.copy), *args], cwd=str(self.checkout), + env=self._env(env), capture_output=True, text=True, + timeout=timeout, stdin=subprocess.DEVNULL, check=False) + + def edit(self, *args: str, env: dict | None = None, + timeout: float = 300) -> subprocess.CompletedProcess: + """This workstation's `lanes-edit.sh`, in its checkout, as its lane.""" + return subprocess.run(["bash", str(self.tools / "lanes-edit.sh"), *args], + cwd=str(self.checkout), env=self._env(env), capture_output=True, + text=True, timeout=timeout, stdin=subprocess.DEVNULL, check=False) + + def lanes(self) -> subprocess.CompletedProcess: + return subprocess.run(["bash", str(self.tools / "lanes"), "--all"], + cwd=str(self.checkout), env=self._env(None), capture_output=True, + text=True, timeout=120, stdin=subprocess.DEVNULL, check=False) + + def git(self, *args: str) -> str: + proc = subprocess.run(["git", "-C", str(self.checkout), *args], env=self.env, + capture_output=True, text=True, timeout=120, + stdin=subprocess.DEVNULL, check=False) + assert proc.returncode == 0, f"git {' '.join(args[:2])} in {self.name}:\n{_said(proc)}" + return proc.stdout + + def tip(self) -> str: + return self.git("rev-parse", "refs/remotes/origin/main").strip() + + def fetch_w(self) -> None: + """THE READER'S FETCH OF W (lane 3's ruling (a), #165 6833830078): + `git -C <W> fetch -q origin main`, with plain git, so that `status`, + which reads `m` on W's `origin/main` as last fetched and never + fetches (tasks:545), reads the render the lane's `<c>` pushed. It is + the drill's own act, not a write's (D12).""" + proc = subprocess.run(["git", "-C", str(self.w), "fetch", "-q", "origin", "main"], + env=self.env, capture_output=True, text=True, timeout=120, + stdin=subprocess.DEVNULL, check=False) + assert proc.returncode == 0, ( + f"the harness's fetch of {self.name}'s W, git -C {self.w} fetch -q origin " + f"main:\n{_said(proc)}") + + def lanes_files(self) -> dict: + """The bytes of every file under `lanes/` in the work tree, by digest.""" + return {str(p.relative_to(self.checkout)): hashlib.sha256(p.read_bytes()).hexdigest() + for p in sorted((self.checkout / "lanes").rglob("*")) if p.is_file()} + + # ------------------------------------------------------------ the guard + def guard_session(self): + """The lane's live session (T203c), its row's session id as its own, + in a window named for the lane; ended with the test.""" + if self._session is None: + self._session = guard_session(self.home, self.root / "guard-bin", self.checkout, + window=self.lane, session_id=SESSIONS[self.lane]) + self.drill.request.addfinalizer(self._session.close) + return self._session + + def guard(self, session=None) -> dict: + """The hook, `lanes-edit.sh guard`, in the window of `session` (the + lane's own, `guard_session`, where None), under its 5 s kill timer, + in a process group of its own.""" + if session is None: + session = self.guard_session() + base = self._env({"LANES_INDEX_CONFIG": str(self.conf), "LANES_LANE": self.lane}) + env = session.env(base) + proc = subprocess.Popen(["bash", str(self.tools / "lanes-edit.sh"), "guard"], + stdin=subprocess.PIPE, stdout=subprocess.PIPE, + stderr=subprocess.PIPE, text=True, cwd=str(self.checkout), + env=env, start_new_session=True) + killed = False + try: + out, err = proc.communicate(session.hook_input(), timeout=GUARD_TIMEOUT) + except subprocess.TimeoutExpired: + killed = True + os.killpg(proc.pid, signal.SIGKILL) + out, err = proc.communicate(timeout=30) + return {"exit": None if killed else proc.returncode, "killed": killed, + "out": out + err, "err": err} + + def guard_in_another_window(self, window: str) -> dict: + """STEP 6'S CONTRAST (the module's notes): the same guard, on the same + checkout and configuration, for the lane's own session, its id and + name, in a window named `window`, another lane's, which the stand-in + `tmux` answers `#W` with (`guard_session`). The lane's own session + ends first, so one live process holds the transcript (Amendment + 18(h)). The contrast's session then stays live until its finalizer + ends it with the test, so a later `guard()` on this workstation + would start a second live process on the same transcript, a second + holder; none follows the contrast today (lane 5, #165 6870260047).""" + if self._session is not None: + self._session.close() + self._session = None + session = guard_session(self.home, self.root / f"guard-bin-{window}", self.checkout, + window=window, session_id=SESSIONS[self.lane], name=self.lane) + self.drill.request.addfinalizer(session.close) + return self.guard(session) + + +# ------------------------------------------------------------------ the drill +class Drill: + """TEST 13'S ESTATE and its steps, each with its labelled assertions (see + the module's notes). `k` is the head when the rollback starts; `cut` is + the cutover's seq; `marker` the marker commit.""" + + def __init__(self, request, root: Path): + # Without an engine, T205's `pg_engine` skips first, with its banner. + request.getfixturevalue("pg_engine") + self.request, self.root = request, root + self.cluster = request.getfixturevalue("tls_cluster") + try: + self.db = self.cluster.second_database(label=LABEL) + except ClusterError as exc: + raise AssertionError(f"[estate] the drill's database, bootstrapped through the admin " + f"service with --label {LABEL} (T109): {exc}") from exc + for engineer in ENGINEERS.values(): + self._login_add(engineer) + try: + self.estate = ImportedRegister(root / "estate", self.cluster.bindir) + except ClusterError as exc: + raise AssertionError(f"[estate] test 7's fixture register on a bare origin " + f"(T227b): {exc}") from exc + self.origin = self.estate.origin + self.ruleset = Ruleset(root / "ruleset", self.origin) + self.ws1 = Workstation(self, "ws1", OPERATOR, home=self.estate.home, + checkout=self.estate.wip) + self.ws2 = Workstation(self, "ws2", WS2_LANE) + self.both = (self.ws1, self.ws2) + self.c = self.cut = self.marker = self.k = self.removal = None + #: The journal's count and origin's tip as step 6 stops the cluster. + self.stopped = None + + def _login_add(self, engineer: str) -> None: + """`lanes-index login add <engineer>` through the admin service on the + drill's database, under a pty (lane 1's T110): its two password lines + are kept in the cluster's memory, never printed.""" + service = self.cluster.admin_service(self.db.name) + code, out, err = self.cluster.lanes_index_tty( + ["login", "add", engineer, "--admin-service", service]) + assert code == 0, (f"[estate] `lanes-index login add {engineer}` exited {code} (lane 1's " + f"T110, L1-A8): {_masked(out)[-400:]} | {_masked(err)[-400:]}") + found = dict(PASSWORD_LINE.findall(out)) + wanted = (f"lanes_w_{engineer}", f"lanes_r_{engineer}") + assert all(login in found for login in wanted), ( + f"[estate] `login add {engineer}` printed no password line for " + f"{[login for login in wanted if login not in found]}") + self.cluster.passwords.update({login: found[login] for login in wanted}) + + # ------------------------------------------------------------ origin and SQL + def git(self, *args: str, cwd: Path | None = None) -> str: + proc = subprocess.run(["git", *args], cwd=str(cwd or self.root), env=self.estate.env, + capture_output=True, text=True, timeout=120, + stdin=subprocess.DEVNULL, check=False) + assert proc.returncode == 0, f"git {' '.join(args[:2])}:\n{_said(proc)}" + return proc.stdout + + def origin_git(self, *args: str) -> str: + """git in the bare origin itself, so no checkout's refs move.""" + return self.git(f"--git-dir={self.origin}", *args) + + def origin_tip(self) -> str: + return self.origin_git("rev-parse", "refs/heads/main").strip() + + def on_origin(self, path: str, rev: str = "refs/heads/main") -> bool: + return path in self.origin_git("ls-tree", "-r", "--name-only", rev, "lanes/").split() + + def seqs_of(self, sha: str) -> list: + return [int(s) for s in REGISTER_SEQ.findall(self.origin_git("log", "-1", "--format=%B", + sha))] + + def commits_after(self, base: str) -> list: + """[(commit, its Register-Seq values)] on origin's `main` after `base`, + oldest first, first parents only.""" + out = self.origin_git("rev-list", "--reverse", "--first-parent", + f"{base}..refs/heads/main") + return [(sha, self.seqs_of(sha)) for sha in out.split()] + + def origin_seqs(self) -> list: + out = self.origin_git("log", "--reverse", "--format=%B%x00", "refs/heads/main") + return [int(s) for body in out.split("\0") for s in REGISTER_SEQ.findall(body)] + + def head(self) -> int: + return _rows(self.db, "SELECT seq FROM register_head")[0]["seq"] + + def switch(self) -> dict: + return _rows(self.db, "SELECT mode, marker_state, marker_seq, marker_commit " + "FROM register_switch")[0] + + def journal(self) -> list: + return [[r["seq"], r["kind"], r["operator"]] for r in + _rows(self.db, "SELECT seq, kind, operator FROM journal ORDER BY seq")] + + def count(self) -> int: + return _rows(self.db, "SELECT count(*) AS n FROM journal")[0]["n"] + + def mirror_problem(self, rev: str = "refs/heads/main") -> str | None: + """None where origin's render set at `rev` equals a full render from + SQL, byte for byte; else what differs.""" + on_origin = {} + for path in self.origin_git("ls-tree", "-r", "--name-only", rev, "lanes/").split(): + if RENDER_SET.match(path): + on_origin[path] = subprocess.run( + ["git", f"--git-dir={self.origin}", "show", f"{rev}:{path}"], + capture_output=True, env=self.estate.env, timeout=60, check=True, + stdin=subprocess.DEVNULL).stdout + from_sql = {p: b for p, b in _renders(self.db).items() if RENDER_SET.match(p)} + if on_origin == from_sql: + return None + differ = sorted(p for p in on_origin if p in from_sql and on_origin[p] != from_sql[p]) + return (f"paths on one side only: {sorted(set(on_origin) ^ set(from_sql))}; paths that " + f"differ: {differ}") + + def wait_for_seq(self, seq: int, label: str) -> None: + """Poll origin's `main` until a commit carries `Register-Seq: <seq>`.""" + deadline = time.monotonic() + SETTLE_S + while seq not in self.origin_seqs(): + assert time.monotonic() < deadline, ( + f"{label}: no commit on origin's main carries Register-Seq: {seq} within " + f"{SETTLE_S} s (the render a write forks: lane 4's T416, lane 3's T321 to T323): " + f"{self.origin_seqs()[-6:]}") + time.sleep(0.25) + + def wait_lag_0(self, ws: Workstation, label: str) -> None: + """Open point 8's poll: `status` until it shows a lag of 0, each poll + after the harness's fetch of the W `status` reads (`fetch_w`; lane + 3's ruling (a), #165 6833830078): `status` never fetches, and no + write on primary fetches W.""" + deadline = time.monotonic() + SETTLE_S + while True: + ws.fetch_w() + proc = ws.index("status", timeout=120) + if LAG_0.search(proc.stdout): + return + assert time.monotonic() < deadline, ( + f"{label}: `status` on {ws.name}, each read after a fetch of its W, shows no " + f"lag of 0 within {SETTLE_S} s (open point 8):\n{_said(proc)}") + time.sleep(0.25) + + def settled(self, label: str) -> None: + """After a write on primary: its render on origin, a lag of 0, the + mirror byte-identical to SQL, and one commit per seq since the + marker.""" + head = self.head() + self.wait_for_seq(head, label) + self.wait_lag_0(self.ws1, label) + problem = self.mirror_problem() + assert problem is None, f"{label}: the mirror is not byte-identical to SQL: {problem}" + after = self.commits_after(self.marker) + assert [seqs for _sha, seqs in after] == [[n] for n in range(self.cut + 1, head + 1)], ( + f"{label}: origin does not carry one commit per seq from {self.cut + 1} to {head}: " + f"{after}") + + # ------------------------------------------------------------ the steps + def step_1_ready(self) -> None: + """`ready --expect index` passes in ws1 and ws2, every check `ok`.""" + for ws in self.both: + proc = ws.index("ready", "--expect", "index", "--release", RELEASE, "--env", ENV_NAME) + checks = _checks(proc.stdout) + assert proc.returncode == 0, ( + f"[step 1] `ready --expect index` fails in {ws.name} (lane 1's T119; the TLS " + f"cluster, T229; the logins, T110):\n{_said(proc)}") + assert sorted(checks) == list(range(1, 15)) and all( + state == "ok" for state, _ in checks.values()), ( + f"[step 1] not every check of the fourteen is ok in {ws.name} (check 14, git " + f"2.32 or later, is lane 1's T119 follow-up 2):\n{_said(proc)}") + + def freeze(self, *, ruleset: bool = True) -> str: + """The drain's last `PAUSED` write, in files mode from ws2 as the + drained lane, pushed; then the ruleset on, unless `ruleset` is False. + Returns the write's commit on origin.""" + before = self.origin_tip() + proc = self.ws2.edit("set-row-state", DRAINED, f"PAUSED {DOT} the drill's freeze", + env={"LANES_LANE": DRAINED}) + assert proc.returncode == 0, ( + f"[freeze] the last PAUSED write, a files-mode set-row-state of {DRAINED}, " + f"failed:\n{_said(proc)}") + paused = self.origin_tip() + assert paused != before, "[freeze] the last PAUSED write was not pushed to origin" + row = [line for line in self.origin_git("show", f"{paused}:lanes/LANES.md").splitlines() + if f"`{DRAINED}`" in line] + assert row and "PAUSED" in row[0], f"[freeze] {DRAINED}'s row on origin: {row}" + if ruleset: + self.ruleset.on() + return paused + + def step_2_import(self) -> None: + """`import --at C` from ws1, C origin's tip, proves its render.""" + self.ws1.git("fetch", "-q", "origin") + self.ws1.git("merge", "-q", "--ff-only", "refs/remotes/origin/main") + self.c = self.origin_tip() + proc = self.ws1.index("import", "--at", self.c, timeout=400) + assert proc.returncode == 0, ( + f"[step 2] `import --at {self.c[:12]}` from ws1 failed (lane 1's T115, " + f"L1-A13):\n{_said(proc)}") + seq0 = _rows(self.db, "SELECT seq, kind, git_commit FROM journal ORDER BY seq") + assert seq0 == [{"seq": 0, "kind": "import", "git_commit": self.c}], ( + f"[step 2] the journal after the import is {seq0}, not the one import at C") + switch = self.switch() + assert (switch["mode"], switch["marker_state"]) == ("files", "absent"), ( + f"[step 2] the import moved the switch: {switch}") + problem = self.mirror_problem(self.c) + assert problem is None, f"[step 2] SQL's render is not C's: {problem}" + + def step_3_cutover_and_flips(self) -> None: + """The cutover sets the switch and pushes the marker; then `set-mode + primary` in each workstation changes only that line, and the file + stays 0600. Each workstation, once flipped, has its lane's own + register checkout, made after the cutover's push (`lane_checkout`).""" + proc = self.ws1.index("cutover", "--import", self.c) + assert proc.returncode == 0, ( + f"[step 3] `cutover --import {self.c[:12]}` failed (lane 1's T116, " + f"L1-A14):\n{_said(proc)}") + switch = self.switch() + assert (switch["mode"], switch["marker_state"]) == ("primary", "present"), ( + f"[step 3] after the cutover the switch reads {switch['mode']} with the marker " + f"{switch['marker_state']}: the marker's push, its read-back and record_marker are " + f"lane 3's T327, so the drill fails until it lands") + self.cut = _rows(self.db, "SELECT seq FROM journal WHERE kind = 'cutover'")[0]["seq"] + self.marker = self.origin_tip() + assert self.on_origin("lanes/STORE") and self.seqs_of(self.marker) == [self.cut], ( + f"[step 3] origin's tip {self.marker[:12]} is not the marker commit carrying " + f"lanes/STORE and Register-Seq: {self.cut}") + assert switch["marker_commit"] == self.marker, ( + f"[step 3] record_marker recorded {switch['marker_commit']}, not origin's tip") + for ws in self.both: + lines, mode = ws.conf_state() + flip = ws.index("set-mode", "primary", "--config", str(ws.conf)) + assert flip.returncode == 0, ( + f"[step 3] `set-mode primary` in {ws.name} failed (lane 1's T120):\n{_said(flip)}") + after, mode_after = ws.conf_state() + assert after == ["mode=primary" if line == "mode=index" else line for line in lines], ( + f"[step 3] the flip in {ws.name} changed more than the mode= line: " + f"{lines} -> {after}") + assert mode == mode_after == 0o600, f"[step 3] {ws.name}'s file is {oct(mode_after)}" + ws.lane_checkout() + + def step_4_smoke_test(self) -> None: + """R3b's smoke test: `log NOTED` gives its row at the cutover's seq + plus 1, a mirror commit carrying it, and a lag of 0.""" + proc = self.ws1.edit("log", "NOTED", f"lane:{OPERATOR}", "the drill's smoke test") + assert proc.returncode == 0, ( + f"[step 4] `log NOTED` on primary from ws1 failed (lane 4's T415):\n{_said(proc)}") + rows = _rows(self.db, f"SELECT seq, kind, lane FROM journal WHERE seq > {self.cut} " + f"ORDER BY seq") + assert rows == [{"seq": self.cut + 1, "kind": "write", "lane": OPERATOR}], ( + f"[step 4] the smoke test's row is not the cutover's seq plus 1: {rows}") + self.settled("[step 4]") + + def step_5_writes_from_both(self) -> None: + """`claim` and `log` from both workstations; after each, the mirror + is byte-identical and origin has one commit per seq.""" + for ws in self.both: + for verb, args in (("claim", ["claim", OBJECTS[ws.name], "--no-github"]), + ("log", ["log", "NOTED", f"lane:{ws.lane}", + f"the drill: a write from {ws.name}"])): + count = self.count() + proc = ws.edit(*args) + assert proc.returncode == 0, ( + f"[step 5] `{verb}` on primary from {ws.name} failed (lane 4's " + f"T415):\n{_said(proc)}") + assert self.count() == count + 1, f"[step 5] {ws.name}'s {verb} journaled no entry" + self.settled(f"[step 5] after {ws.name}'s {verb}") + + def step_6_outage(self) -> None: + """The cluster stopped: writes 69, the guard's refusal, the mirror + line, `status` inside twice its bound, then the declaration, after + which the guard answers from the mirror: 0 for the lane's bound + session (AT-D20), and 2 for the same session in a window named for + the other workstation's lane, whose row names another session (the + contrast; the module's notes).""" + self.stopped = (self.count(), self.origin_tip()) + for ws in self.both: + ws.git("fetch", "-q", "origin") + self.cluster.stop() + for ws in self.both: + wrote = ws.edit("log", "NOTED", f"lane:{ws.lane}", "the drill: during the outage") + assert wrote.returncode == 69, ( + f"[step 6] a write on {ws.name} with the cluster stopped is not 69 (lane 4's " + f"T415):\n{_said(wrote)}") + refused = ws.guard() + out = refused["out"] + assert not refused["killed"] and refused["exit"] == 2, ( + f"[step 6] the guard on {ws.name} did not exit 2 inside 5 s (lane 5's T507): " + f"exit {refused['exit']}: {_masked(out)[-600:]}") + added = ADDED_NAME.search(out) + assert added and self.db.name in added.group(1), ( + f"[step 6] the guard's refusal on {ws.name} does not name the database as " + f"register_url= gives it (T507): {_masked(out)[-600:]}") + users = [user for user in (f"lanes_w_{ws.engineer}", f"lanes_r_{ws.engineer}") + if user in added.group(1)] + assert users == [], ( + f"[step 6] the guard's added name carries a URL's user, {users}: " + f"{added.group(1)!r}") + for words in ("lanes-index status", "lanes-index rollback", "CLAUDE_NO_LANE=1"): + assert words in out, ( + f"[step 6] the guard's refusal on {ws.name} does not carry {words!r} (P3; " + f"T507): {_masked(out)[-600:]}") + secrets = [self.cluster.passwords[f"lanes_{half}_{ws.engineer}"] for half in "wr"] + assert not any(secret in refused["err"] for secret in secrets), ( + f"[step 6] the guard's stderr on {ws.name} carries its engineer's password") + listing = ws.lanes() + assert MIRROR_LINE.search(listing.stderr), ( + f"[step 6] `lanes` on {ws.name} prints no `read: mirror` line (lane 5's " + f"T505):\n{_said(listing)}") + start = time.monotonic() + status = ws.index("status", timeout=120, + env={"CLAUDE_NO_LANE": "1", "LANES_LANE": None, "TMUX": None, + "TMUX_PANE": None}) + elapsed = time.monotonic() - start + assert elapsed < 2 * STATUS_BOUND_S, ( + f"[step 6] `status` on {ws.name} took {elapsed:.2f} s, not inside twice AT-D9's " + f"{STATUS_BOUND_S} s (lane 1's T117)") + assert status.returncode == 69 and (LABEL in status.stdout + status.stderr or + self.db.name in status.stdout + status.stderr), ( + f"[step 6] `status` on {ws.name} does not answer 69 naming the store (lane 1's " + f"T117):\n{_said(status)}") + for ws, other in zip(self.both, self.both[::-1]): + declared = ws.index("outage", "declare", "--until", UNTIL, "--why", WHY) + path = ws.outage_file() + assert declared.returncode == 0 and path.exists(), ( + f"[step 6] `outage declare` on {ws.name} declared nothing (lane 1's T121, " + f"L1-A18):\n{_said(declared)}") + fields = _fields(path) + assert (fields.get("kind"), fields.get("database"), fields.get("host")) == ( + "word", LABEL, ws.workstation), f"[step 6] {ws.name}'s declaration: {fields}" + mirror = f"read: mirror at {ws.tip()[:12]}" + answered = ws.guard() + out = answered["out"] + assert not answered["killed"], f"[step 6] the declared guard on {ws.name} was killed" + assert mirror in out and _label(fields) in out, ( + f"[step 6] under the declaration the guard on {ws.name} does not answer from the " + f"mirror with the declared line (lane 5's T507, SVC-12): {_masked(out)[-600:]}") + assert answered["exit"] == 0, ( + f"[step 6] under the declaration the guard on {ws.name}, its lane's bound session " + f"in its lane's window, exits {answered['exit']}, not AT-D20's 0 for a bound lane " + f"(lane 5's T507, SVC-12): {_masked(out)[-600:]}") + # THE CONTRAST: the same session in a window named for the other + # workstation's lane, whose row on the mirror names that lane's + # session, not this one, so the mirror's row refuses it. + contrast = ws.guard_in_another_window(other.lane) + out = contrast["out"] + assert not contrast["killed"], ( + f"[step 6] the declared guard on {ws.name} in {other.lane}'s window was killed") + assert mirror in out and _label(fields) in out, ( + f"[step 6] under the declaration the guard on {ws.name}, in a window named " + f"{other.lane}, does not answer from the mirror with the declared line (lane 5's " + f"T507, SVC-12): {_masked(out)[-600:]}") + # Its own cause, in the guard's words (`lanes-edit.sh`'s table, the + # row that names no such uuid; a pin, whose place the module's + # notes name), not only the row's session, which the triple's + # `row` line of any refusal after the row's read carries too, + # Amendment 18(h)'s duplicate among them (lane 5, #165 + # 6870260047). + cause = (f"this window is lane {other.lane}, whose row ends on " + f"{SESSIONS[other.lane]} and does not name {SESSIONS[ws.lane]} at all") + assert (contrast["exit"] == 2 and cause in out + and "ANOTHER LIVE PROCESS" not in out), ( + f"[step 6] under the declaration the guard on {ws.name}, for its lane's session " + f"in a window named {other.lane}, does not refuse 2 from the mirror's row for " + f"that row's own cause alone, {cause!r}: exit {contrast['exit']}: " + f"{_masked(out)[-600:]}") + + def step_7_rollback_refused_while_down(self) -> None: + """A rollback with the cluster stopped is refused and changes nothing; + the cluster restarts, and `outage clear` removes step 6's + declaration on both workstations.""" + count, tip = self.stopped + kept = self.ws1.outage_file().read_bytes() + proc = self.ws1.index("rollback") + port = self.cluster.port + self.cluster.start_again() + assert self.cluster.port == port, ( + f"[step 7] the TLS cluster came back on port {self.cluster.port}, not {port}, so the " + f"configurations no longer name it") + assert proc.returncode == 69, ( + f"[step 7] a rollback with the cluster stopped is not refused 69 (T304):\n" + f"{_said(proc)}") + switch = self.switch() + assert (switch["mode"], switch["marker_state"]) == ("primary", "present"), ( + f"[step 7] the refused rollback moved the switch: {switch}") + assert (self.count(), self.origin_tip()) == (count, tip), ( + "[step 7] the outage's writes or the refused rollback changed the journal or origin") + assert self.on_origin("lanes/STORE"), "[step 7] lanes/STORE left origin" + assert self.ws1.outage_file().read_bytes() == kept, ( + "[step 7] the refused rollback replaced step 6's declaration") + for ws in self.both: + cleared = ws.index("outage", "clear") + assert cleared.returncode == 0 and not ws.outage_file().exists(), ( + f"[step 7] `outage clear` on {ws.name} left the declaration (lane 1's T121):\n" + f"{_said(cleared)}") + + def step_8_rollback(self) -> None: + """Rollback from ws1 as the operator lane: its start declares the + outage; `--hold-marker` stops with the mirror proved current and the + marker still on origin while the ruleset is on; the ruleset goes off; + the rerun pushes the removal; then `set-mode index` clears ws1 alone + (AT-F4's oracle; operations.md 2.3).""" + self.k = k = self.head() + assert self.ruleset.state() == "on", "[step 8] the ruleset is not on at the rollback" + hold = self.ws1.index("rollback", "--hold-marker") + assert hold.returncode == 0, ( + f"[step 8] `rollback --hold-marker` did not stop 0 at step 3 (lane 3's T326):\n" + f"{_said(hold)}") + path = self.ws1.outage_file() + assert path.exists(), "[step 8] the rollback's start declared no outage (T121, T304)" + fields = _fields(path) + assert (fields.get("kind"), fields.get("mirror-seq")) == ("rollback", str(k)), ( + f"[step 8] the declaration is not the rollback's at mirror-seq {k}: {fields}") + switch = self.switch() + assert (switch["mode"], switch["marker_state"]) == ("files", "removing"), ( + f"[step 8] at --hold-marker the switch is {switch}, not files with the marker " + f"removing (T304, T326)") + assert self.journal()[-1] == [k + 1, "rollback", True], ( + f"[step 8] the journal's last entry is not the rollback's at {k + 1}: " + f"{self.journal()[-3:]}") + assert self.on_origin("lanes/STORE"), ( + "[step 8] AT-F4: --hold-marker pushed the removal of lanes/STORE before the " + "ruleset was off") + assert k in self.origin_seqs(), f"[step 8] the mirror does not hold k = {k} (T326's step 2)" + problem = self.mirror_problem() + assert problem is None, f"[step 8] the mirror is not proved current at k: {problem}" + self.ruleset.off() + rerun = self.ws1.index("rollback") + assert rerun.returncode == 0, ( + f"[step 8] the rerun after --hold-marker did not end 0 (lane 3's T326):\n" + f"{_said(rerun)}") + switch = self.switch() + assert (switch["mode"], switch["marker_state"]) == ("files", "absent"), ( + f"[step 8] after the rerun the switch is {switch}, not files with the marker absent") + self.removal = self.origin_tip() + assert self.seqs_of(self.removal) == [k + 1], ( + f"[step 8] origin's tip does not carry the rollback's Register-Seq: {k + 1}") + changed = self.origin_git("diff-tree", "--no-commit-id", "--name-status", "-r", + f"{self.removal}^", self.removal) + assert changed.split("\n") == ["D\tlanes/STORE", ""], ( + f"[step 8] origin's last commit does not remove lanes/STORE alone: {changed!r}") + records = self.ruleset.record_of(self.removal) + assert records and all(r["state"] == "off" and r["outcome"] == "accepted" + for r in records), ( + f"[step 8] AT-F4: the removal was not pushed after the ruleset was off: {records}") + lines, mode = self.ws1.conf_state() + flip = self.ws1.index("set-mode", "index", "--config", str(self.ws1.conf)) + assert flip.returncode == 0, f"[step 8] `set-mode index` on ws1 (T120):\n{_said(flip)}" + after, mode_after = self.ws1.conf_state() + assert after == ["mode=index" if line == "mode=primary" else line for line in lines], ( + f"[step 8] the flip on ws1 changed more than the mode= line: {lines} -> {after}") + assert mode_after == 0o600, f"[step 8] ws1's file is {oct(mode_after)}" + assert "mode=primary" in self.ws2.conf_state()[0], ( + "[step 8] the flip on ws1 cleared ws2 too") + + def files_mode_write(self, ws: Workstation, label: str, *args: str) -> str: + """A files-mode write on `ws` that exits 0 and is pushed: one commit + on origin's `main`, with no `Register-Seq`. Returns it.""" + before = self.origin_tip() + proc = ws.edit(*args) + assert proc.returncode == 0, f"{label}: the files-mode write on {ws.name}:\n{_said(proc)}" + after = self.commits_after(before) + assert len(after) == 1 and after[0][1] == [], ( + f"{label}: the files-mode write on {ws.name} is not one pushed commit with no " + f"Register-Seq: {after}") + return after[0][0] + + def step_9_files_mode_writes(self) -> None: + """A files-mode `claim` on ws1 exits 0 and is pushed; a write on ws2, + not yet cleared, exits 69; once cleared, its files-mode write exits 0.""" + sha = self.files_mode_write(self.ws1, "[step 9]", "claim", OBJECTS["ws1-files"], + "--no-github") + log = self.origin_git("show", f"{sha}:lanes/log/{OPERATOR}.md") + assert any(line.startswith("CLAIMED") and OBJECTS["ws1-files"] in line + for line in log.splitlines()), ( + f"[step 9] ws1's files-mode claim is not in {OPERATOR}'s log on origin") + count, tip = self.count(), self.origin_tip() + refused = self.ws2.edit("claim", OBJECTS["ws2-files"], "--no-github") + assert refused.returncode == 69, ( + f"[step 9] a write on ws2, not yet cleared, is not 69, ended at its snapshot " + f"(lane 4's T415):\n" + f"{_said(refused)}") + assert (self.count(), self.origin_tip()) == (count, tip), ( + "[step 9] ws2's refused write changed the journal or origin") + flip = self.ws2.index("set-mode", "index", "--config", str(self.ws2.conf)) + assert flip.returncode == 0, f"[step 9] `set-mode index` on ws2 (T120):\n{_said(flip)}" + self.files_mode_write(self.ws2, "[step 9] once ws2 is cleared", "claim", + OBJECTS["ws2-files"], "--no-github") + + def holders(self, obj: str) -> set: + """The lanes holding `obj`, across SQL's live claims and origin's logs + (a lane whose log's last line naming it is a CLAIMED or TAKEOVER).""" + rows = _rows(self.db, f"SELECT lane FROM object_holds WHERE lower(object) = " + f"lower('{obj}') AND verb IN ('CLAIMED', 'TAKEOVER') AND " + f"superseded_by IS NULL") + held = {r["lane"] for r in rows} + for path in self.origin_git("ls-tree", "-r", "--name-only", "refs/heads/main", + "lanes/log/").split(): + last = None + for line in self.origin_git("show", f"refs/heads/main:{path}").splitlines(): + if obj.lower() in line.lower(): + last = line + match = HOLDS.match(last or "") + if match: + held.add(match.group(2)) + return held + + def step_10_the_end(self) -> None: + """Origin carries no `lanes/STORE`; its files are the rollback's last + render plus the files-mode commits after it; every object the drill + claimed has at most one holder.""" + assert not self.on_origin("lanes/STORE"), "[step 10] origin still carries lanes/STORE" + problem = self.mirror_problem(self.removal) + assert problem is None, ( + f"[step 10] the rollback's last commit is not a full render from SQL (T326): {problem}") + after = self.commits_after(self.removal) + assert len(after) == 2 and all(seqs == [] for _sha, seqs in after), ( + f"[step 10] origin's commits after the rollback's are not step 9's two files-mode " + f"writes: {after}") + for obj in OBJECTS.values(): + held = self.holders(obj) + assert len(held) <= 1, f"[step 10] {obj} has more than one holder: {sorted(held)}" + + +# =================================================================== AT-13 +def test_the_drill_import_cutover_outage_rollback_and_files_mode_write(request, tmp_path): + """AT-13, the drill (TP's "The sequence, and its oracle at each step"): + the readiness check, the freeze with the ruleset on, the import at C, the + cutover and the flips, R3b's smoke test, writes from both workstations, + the outage with its refusals and its declaration, a rollback refused + while the cluster is down, the rollback through `--hold-marker`, the + files-mode writes, and the end state. Each step's assertions carry its + number. Fails until L1-A18, T326 and T327 land, and each step's own tasks + (the module's notes); on `V-round5` it stops at step 3, T327.""" + drill = Drill(request, tmp_path) + drill.step_1_ready() + drill.freeze() + drill.step_2_import() + drill.step_3_cutover_and_flips() + drill.step_4_smoke_test() + drill.step_5_writes_from_both() + drill.step_6_outage() + drill.step_7_rollback_refused_while_down() + drill.step_8_rollback() + drill.step_9_files_mode_writes() + drill.step_10_the_end() + + +def test_a_workstation_not_yet_cleared_refuses_after_rollback(request, tmp_path): + """AT-13's second test: after the rollback, which `set-mode index` + cleared on ws1 alone, ws2, still `mode=primary`, exits 69 for `claim` + and for `log`, and changes neither the journal, nor origin, nor its own + files under `lanes/`; once `set-mode index` clears it, its files-mode + write exits 0 and is pushed. Runs the drill's steps 1 to 4 and 8. Fails + until L1-A18, T326 and T327 land, and lane 4's T415 and T416.""" + drill = Drill(request, tmp_path) + drill.step_1_ready() + drill.freeze() + drill.step_2_import() + drill.step_3_cutover_and_flips() + drill.step_4_smoke_test() + drill.step_8_rollback() + ws2 = drill.ws2 + count, tip, files = drill.count(), drill.origin_tip(), ws2.lanes_files() + for verb, args in (("claim", ["claim", OBJECTS["ws2"], "--no-github"]), + ("log", ["log", "NOTED", f"lane:{ws2.lane}", "not yet cleared"])): + proc = ws2.edit(*args) + assert proc.returncode == 69, ( + f"[not yet cleared] ws2's {verb} after the rollback is not 69, ended at its " + f"snapshot (lane 4's T415):\n" + f"{_said(proc)}") + assert drill.count() == count, "[not yet cleared] ws2's refused writes journaled" + assert drill.origin_tip() == tip, "[not yet cleared] ws2's refused writes moved origin" + assert ws2.lanes_files() == files, "[not yet cleared] ws2's files under lanes/ changed" + flip = ws2.index("set-mode", "index", "--config", str(ws2.conf)) + assert flip.returncode == 0, f"[cleared] `set-mode index` on ws2 (T120):\n{_said(flip)}" + drill.files_mode_write(ws2, "[cleared]", "log", "NOTED", f"lane:{ws2.lane}", + "cleared after the rollback") + + +# =================================================================== AT-F4 +def test_the_ruleset_goes_on_after_the_last_paused_write_and_before_the_import(request, + tmp_path): + """AT-F4, the ruleset on: the last `PAUSED` write is pushed while the + model is off; with it on, a person's push to a rendered path is refused, + and so is one to `lanes/STORE`, while a push that changes only + `lanes/repos.tsv`, or only `lanes/log/README.md`, goes through; the + import, the cutover (its marker pushed through the model as the + renderer's) and the flips succeed, and the model refused no files-mode + write, only the two probes. Fails until L1-A18, T326 and T327 land; on + `V-round5` it stops at the cutover's marker, T327.""" + drill = Drill(request, tmp_path) + paused = drill.freeze(ruleset=False) + records = drill.ruleset.record_of(paused) + assert records and all(r["state"] == "off" and r["outcome"] == "accepted" for r in records), ( + f"[AT-F4] the last PAUSED write was not pushed before the ruleset was on: {records}") + drill.ruleset.on() + person = Person(tmp_path / "person", drill.origin) + probes = [] + for path, text, accepted in ( + ("lanes/log/repoB-1.md", "a person's line in a rendered log\n", False), + ("lanes/STORE", "store=primary\ndatabase=register-drill\n", False), + ("lanes/repos.tsv", "repoQ\topensoft/repoQ\n", True), + ("lanes/log/README.md", "a person's note\n", True)): + before = drill.origin_tip() + pushed, sha = person.push(path, text) + if accepted: + assert pushed.returncode == 0 and drill.origin_tip() == sha, ( + f"[AT-F4] a push that changes only {path} was refused:\n{_said(pushed)}") + else: + assert pushed.returncode != 0 and drill.origin_tip() == before, ( + f"[AT-F4] a person's push to {path} was not refused with the ruleset on:\n" + f"{_said(pushed)}") + probes.append(sha) + found = drill.ruleset.record_of(sha) + assert [r["outcome"] for r in found] == ["accepted" if accepted else "refused"], ( + f"[AT-F4] the model's record of the push to {path}: {found}") + drill.step_2_import() + drill.step_3_cutover_and_flips() + marked = drill.ruleset.record_of(drill.marker) + assert marked and all(r["state"] == "on" and r["pusher"] == "renderer" + and r["outcome"] == "accepted" for r in marked), ( + f"[AT-F4] the cutover's marker was not pushed through the ruleset as the renderer's: " + f"{marked}") + refused = [r for r in drill.ruleset.records() if r["outcome"] == "refused"] + assert sorted(p["new"] for r in refused for p in r["pushes"]) == sorted(probes), ( + f"[AT-F4] the model refused a push other than the two probes: {refused}") + + +def test_the_rollback_turns_the_ruleset_off_before_the_marker_removal_is_pushed(request, + tmp_path): + """AT-F4, the ruleset off: after the freeze, the import, the cutover and + the flips, `rollback --hold-marker` exits 0 with the mirror proved + current at the cutover's seq and the marker still on origin, the switch + at `files` and the marker `removing`, while the model is on; it is then + switched off, and the rerun pushes the removal and ends with the marker + `absent` (the drill's step 8, whose assertions are AT-F4's). No write on + primary comes between, since AT-F4's oracle names none (T276d; see the + module's notes). Fails until L1-A18, T326 and T327 land.""" + drill = Drill(request, tmp_path) + drill.freeze() + drill.step_2_import() + drill.step_3_cutover_and_flips() + drill.step_8_rollback() + + +def test_a_files_mode_write_after_the_rollback_is_pushed(request, tmp_path): + """AT-F4, after the removal: once the rollback has run through + `--hold-marker` and its rerun with the model off, and `set-mode index` + has cleared ws1, a files-mode write on ws1 exits 0 and is pushed, one + commit with no `Register-Seq` that the model let through. As in the + test above, no write on primary comes before the rollback (T276d). + Fails until L1-A18, T326 and T327 land.""" + drill = Drill(request, tmp_path) + drill.freeze() + drill.step_2_import() + drill.step_3_cutover_and_flips() + drill.step_8_rollback() + sha = drill.files_mode_write(drill.ws1, "[AT-F4]", "log", "NOTED", f"lane:{OPERATOR}", + "a files-mode write after the rollback") + records = drill.ruleset.record_of(sha) + assert records and all(r["outcome"] == "accepted" for r in records), ( + f"[AT-F4] the files-mode write after the rollback was not let through: {records}") diff --git a/tests/test_sql_register_fixture.py b/tests/test_sql_register_fixture.py index 90017765..7803e04c 100644 --- a/tests/test_sql_register_fixture.py +++ b/tests/test_sql_register_fixture.py @@ -39,6 +39,7 @@ import json import os +import socket import subprocess import sys import threading @@ -50,6 +51,25 @@ from conftest import REPO +#: THE LANDING GATE'S TABLE (T280's reader, `tests/sql_register_gate.py`), TEMPORARY: +#: T281 removes it in the last set. Where the gate is active, an id is skipped until +#: every task its row names has landed, and the skip names them. Two ids start a +#: cluster on the session's template, T227's `Bootstrap()` with T228's logins: +#: `[tls-untouched]`, by T229's `tls_cluster`, and `[psql-on-the-socket]`, by `pg` on +#: `pg_cluster`. That template is built by `lanes-index bootstrap --admin-service`, +#: L1-A7 (T109), which applies L1-A6's migration 1 and role block (T107 and T108), +#: then by `lanes-index login add --admin-service`, L1-A8 (T110). So each waits for +#: T107, T108, T109 and T110, as T221's and T231's Orders read a case on `pg` +#: (tasks:2127 and :2231 at lane 3's commit 17, 204145ae): it takes "the logins step +#: of the session template", and fails until L1-A6, L1-A7 and L1-A8 (lane 1, +#: opensoft/openRepoTools#165 6897250155; lane 3's ruling, 6897276895). Each row is +#: its id's own, since no other id of either function starts a cluster. The module's +#: other 22 ids have no row, so they always run, and there is no `"*"` row. +SQL_REGISTER_GATE_TABLE = { + "test_the_delayed_loopback_relay_delays_each_direction_and_passes_tls_through[tls-untouched]": ("T107", "T108", "T109", "T110"), # T229; tasks:2127, :2231 + "test_the_silent_after_startup_relay_forwards_the_startup_then_nothing_and_holds_both_sockets[psql-on-the-socket]": ("T107", "T108", "T109", "T110"), # T229 (T229c); tasks:2127, :2231 +} + #: The variable, as `tests/pgcluster.py` and `tests.yml` spell it. SWITCH = "OPENREPOTOOLS_REQUIRE_PG" @@ -256,6 +276,457 @@ def test_no_real_engine_test_is_selected_by_the_launch_jobs_filter(tmp_path): f"no part of its id holds either word: {offenders}") +# ---------------------------------------------------------------- T229's relay +#: THE DELAYED-LOOPBACK RELAY'S OWN TEST (T229; R-P23), before the cases that +#: use it: `tests/pgcluster.py`'s `delayed_loopback(target_port, delay_s)`. +#: `[each-direction]`, `[clean-close]` and `[no-root]` run on a loopback +#: peer of the standard library, so they need no engine; `[tls-untouched]` +#: checks the bytes on such a peer, then asks for T229's TLS cluster for its +#: `verify-full` connect and query, and skips with T205's banner without one. +RELAY_DELAY = 0.2 +RELAY_CASES = ["each-direction", "tls-untouched", "clean-close", "no-root"] + + +def _peer(handler): + """A loopback server for one connection: `handler(conn, seen)` in a + thread. Returns (port, thread, seen).""" + server = socket.create_server(("127.0.0.1", 0)) + seen: dict = {} + + def run(): + try: + conn, _ = server.accept() + with conn: + handler(conn, seen) + finally: + server.close() + thread = threading.Thread(target=run, daemon=True) + thread.start() + return server.getsockname()[1], thread, seen + + +def _read_all(sock, size: int) -> bytes: + data = b"" + while len(data) < size: + chunk = sock.recv(size - len(data)) + if not chunk: + break + data += chunk + return data + + +def _relay_each_direction(relay_of): + def handler(conn, seen): + conn.recv(1) + seen["up"] = time.monotonic() + seen["sent"] = time.monotonic() + conn.sendall(b"d") + port, thread, seen = _peer(handler) + with relay_of(port, RELAY_DELAY) as relay: + with socket.create_connection(("127.0.0.1", relay.port), timeout=10) as client: + sent = time.monotonic() + client.sendall(b"u") + assert client.recv(1) == b"d" + down = time.monotonic() + thread.join(10) + assert seen["up"] - sent >= RELAY_DELAY, f"the first byte up came {seen['up'] - sent:.3f} s after it was sent" + assert down - seen["sent"] >= RELAY_DELAY, f"the first byte down came {down - seen['sent']:.3f} s after it was sent" + assert seen["up"] - sent < RELAY_DELAY + 5 and down - seen["sent"] < RELAY_DELAY + 5, seen + + +def _relay_tls_untouched(relay_of, request): + up, down = os.urandom(200_000), os.urandom(100_000) + + def handler(conn, seen): + seen["up"] = _read_all(conn, len(up)) + conn.sendall(down) + port, thread, seen = _peer(handler) + with relay_of(port, 0.01) as relay: + with socket.create_connection(("127.0.0.1", relay.port), timeout=30) as client: + client.sendall(up) + got = _read_all(client, len(down)) + thread.join(30) + assert seen.get("up") == up, "the bytes the relay delivered up are not the bytes it was sent" + assert got == down, "the bytes the relay delivered down are not the bytes it was sent" + tls = request.getfixturevalue("tls_cluster") + with relay_of(tls.port, 0.01) as relay: + env = dict(tls.client_env(), PGPORT=str(relay.port)) + proc = subprocess.run([tls.tool("psql"), "-X", "-A", "-t", "-c", + "SELECT ssl FROM pg_stat_ssl WHERE pid = pg_backend_pid()"], + capture_output=True, text=True, env=env, timeout=60, check=False) + assert (proc.returncode, proc.stdout.strip()) == (0, "t"), ( + f"a verify-full connect and query through the relay: {shown(proc)}") + + +def _relay_clean_close(relay_of): + for first in ("client", "peer"): + def handler(conn, seen, first=first): + if first == "peer": + conn.close() + return + seen["eof"] = conn.recv(1) + port, thread, seen = _peer(handler) + with relay_of(port, RELAY_DELAY) as relay: + client = socket.create_connection(("127.0.0.1", relay.port), timeout=10) + if first == "client": + client.close() + thread.join(10) + assert seen.get("eof") == b"", "the client's close did not reach the peer" + else: + assert client.recv(1) == b"", "the peer's close did not reach the client" + client.close() + end = time.monotonic() + 5 + while relay.sockets and time.monotonic() < end: + time.sleep(0.05) + assert not relay.sockets, f"[{first} first] the relay still holds {len(relay.sockets)} socket(s)" + assert relay.alive() == [], f"[{first} first] the relay's threads outlive it: {relay.alive()}" + + +NO_ROOT_CHILD = """ +import json, os, socket, sys, threading +sys.path.insert(0, sys.argv[1]) +import pgcluster +server = socket.create_server(("127.0.0.1", 0)) +def echo(): + conn, _ = server.accept() + with conn: + conn.sendall(conn.recv(16)) +threading.Thread(target=echo, daemon=True).start() +with pgcluster.delayed_loopback(server.getsockname()[1], 0.05) as relay: + with socket.create_connection(("127.0.0.1", relay.port), timeout=10) as client: + client.sendall(b"no-root") + said = client.recv(16) +# T229e: where there is no /proc, as on macOS, there is no capability set to read +status = open(sys.argv[2] + "/self/status").read() if os.path.isdir(sys.argv[2]) else "" +cap = [line.split()[1] for line in status.splitlines() if line.startswith("CapEff:")] +print(json.dumps({"uid": os.geteuid(), "cap": cap[0] if cap else None, "said": said.decode()})) +""" + + +def _relay_no_root(): + if os.geteuid() == 0: + pytest.skip("[no-root] shows the relay needs no capability, and this run is root") + import pgcluster + proc = subprocess.run([sys.executable, "-I", "-B", "-c", NO_ROOT_CHILD, str(SUITE), + str(pgcluster._PROC)], + capture_output=True, text=True, timeout=60, check=False) + assert proc.returncode == 0, shown(proc) + said = json.loads(proc.stdout.strip().splitlines()[-1]) + assert said["said"] == "no-root", said + assert said["uid"] == os.getuid(), f"the relay ran as uid {said['uid']}, not the job's {os.getuid()}" + if said["cap"] is not None: + assert int(said["cap"], 16) == 0, f"the relay's process holds capabilities {said['cap']}" + + +@pytest.mark.parametrize("case", RELAY_CASES) +def test_the_delayed_loopback_relay_delays_each_direction_and_passes_tls_through(request, case): + """T229's relay (R-P23): `[each-direction]`, each direction's first byte + arrives no sooner than the delay after it was sent, on a monotonic + clock; `[tls-untouched]`, the bytes it delivers each way equal the bytes + it was sent, and a `verify-full` connect and a query through it to the + TLS cluster succeed (R2f-S11); `[clean-close]`, a close on either side + closes the other, and leaves no thread or socket of the relay's; + `[no-root]`, a process with no added capability, under the job's own + uid, starts and uses it.""" + import pgcluster + relay_of = getattr(pgcluster, "delayed_loopback", None) + assert relay_of is not None, "tests/pgcluster.py has no delayed_loopback: T229 builds it" + if case == "each-direction": + _relay_each_direction(relay_of) + elif case == "tls-untouched": + _relay_tls_untouched(relay_of, request) + elif case == "clean-close": + _relay_clean_close(relay_of) + else: + _relay_no_root() + + +# ---------------------------------------------------------------- T229c's relay +#: THE SILENT-AFTER-STARTUP RELAY'S OWN TEST (T229c; lane 3's batch 8, "Lane +#: 2's relay: T229 builds it", #165 6780753157, and its text change 8; +#: TP:7682-7684), before the cases that connect through it: D9's F2, AT-F7's +#: silent host, the service's timer and the guard's `[2-service-down]`. +#: `tests/pgcluster.py`'s `silent_after_startup(target_port)`. +#: `[forwards-the-startup]`, `[then-nothing]` and `[holds-both-sockets]` run on +#: a loopback peer of the standard library that answers a startup as +#: PostgreSQL does on trust, so they need no engine; `[psql-on-the-socket]` +#: runs the engine's `psql` through it to the session cluster's Unix socket, +#: and skips with T205's banner without one. +SILENT_CASES = ["forwards-the-startup", "then-nothing", "holds-both-sockets", "psql-on-the-socket"] +#: How long a case waits to see that nothing arrives. +SILENT_WAIT = 1.0 + + +def _message(kind: bytes, body: bytes) -> bytes: + return kind + (len(body) + 4).to_bytes(4, "big") + body + + +#: A startup as libpq sends it (protocol 3.0), and PostgreSQL's answer on +#: trust: AuthenticationOk, a ParameterStatus, BackendKeyData, whose key here +#: ends like a ReadyForQuery's head, and ReadyForQuery (`Z`, length 5, idle). +_STARTUP_BODY = (196608).to_bytes(4, "big") + b"user\x00fx\x00database\x00fx\x00\x00" +STARTUP = (len(_STARTUP_BODY) + 4).to_bytes(4, "big") + _STARTUP_BODY +STARTUP_ANSWER = (_message(b"R", (0).to_bytes(4, "big")) + + _message(b"S", b"server_version\x0016.15\x00") + + _message(b"K", (4242).to_bytes(4, "big") + b"Z\x00\x00\x00") + + _message(b"Z", b"I")) +QUERY = _message(b"Q", b"SELECT 1;\x00") + + +def _within(sock, wait: float): + """What reaches `sock` within `wait` seconds: None for nothing, b"" for a + close, else the bytes.""" + sock.settimeout(wait) + try: + return sock.recv(65536) + except socket.timeout: + return None + + +def _startup_peer(after): + """A loopback peer for one connection: it reads a startup, answers it, + its ReadyForQuery 0.2 s after the rest, then runs `after(conn, seen)`.""" + def handler(conn, seen): + seen["startup"] = _read_all(conn, len(STARTUP)) + cut = len(STARTUP_ANSWER) - 6 + conn.sendall(STARTUP_ANSWER[:cut]) + time.sleep(0.2) + conn.sendall(STARTUP_ANSWER[cut:]) + after(conn, seen) + return _peer(handler) + + +def _started(relay): + client = socket.create_connection(("127.0.0.1", relay.port), timeout=10) + client.sendall(STARTUP) + return client, _read_all(client, len(STARTUP_ANSWER)) + + +def _silent_forwards_the_startup(relay_of): + port, thread, seen = _startup_peer(lambda conn, seen: None) + with relay_of(port) as relay: + assert relay.port != port, "the relay listens on its target's own port" + client, got = _started(relay) + with client: + assert client.getpeername() == ("127.0.0.1", relay.port), client.getpeername() + thread.join(10) + assert seen.get("startup") == STARTUP, "the startup the peer read is not the one the client sent" + assert got == STARTUP_ANSWER, ( + f"the client read {got!r}, not the peer's answer up to its ReadyForQuery") + assert len(relay.silenced) == 1, f"one startup silenced the relay {len(relay.silenced)} time(s)" + + +def _silent_then_nothing(relay_of): + def after(conn, seen): + seen["up"] = _within(conn, SILENT_WAIT) + conn.sendall(_message(b"N", b"SNOTICE\x00\x00")) + seen["down"] = True + _within(conn, SILENT_WAIT) + port, thread, seen = _startup_peer(after) + with relay_of(port) as relay: + client, got = _started(relay) + with client: + assert got == STARTUP_ANSWER, got + client.sendall(QUERY) + heard = _within(client, 2 * SILENT_WAIT) + thread.join(10) + assert seen.get("up") is None, f"after the startup the client's query reached the peer: {seen.get('up')!r}" + assert seen.get("down"), "the peer did not speak after the startup" + assert heard is None, f"after the startup the peer's bytes reached the client: {heard!r}" + + +def _silent_holds_both_sockets(relay_of): + def after(conn, seen): + seen["eof"] = _within(conn, SILENT_WAIT) + port, thread, seen = _startup_peer(after) + with relay_of(port) as relay: + client, got = _started(relay) + with client: + assert got == STARTUP_ANSWER, got + client.shutdown(socket.SHUT_WR) + thread.join(10) + assert seen.get("eof") is None, ( + f"after the startup the client's close reached the peer: {seen.get('eof')!r}") + held = _within(client, SILENT_WAIT) + assert held is None, f"after the startup the peer's close reached the client: {held!r}" + assert len(relay.sockets) == 2, f"the relay holds {len(relay.sockets)} socket(s), not both" + relay.close() + assert _within(client, 5) == b"", "the relay's close did not close the client's end" + assert not relay.sockets and relay.alive() == [], (relay.sockets, relay.alive()) + + +def _silent_psql_on_the_socket(relay_of, request): + pg = request.getfixturevalue("pg") + marker = f"silent-relay-{os.getpid()}" + activity = (f"SELECT state || '|' || query FROM pg_stat_activity " + f"WHERE application_name = '{marker}';") + with relay_of(pg.port, socket_dir=pg.host) as relay: + env = dict(pg.env(appname=marker), PGHOST="127.0.0.1", PGPORT=str(relay.port)) + psql = subprocess.Popen([pg.psql_bin, "-X", "-A", "-t", "-c", "SELECT 'through the relay'"], + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, env=env) + try: + row, end = "", time.monotonic() + 15 + while not row and time.monotonic() < end and psql.poll() is None: + row = pg.psql(activity).stdout.strip() + time.sleep(0.05) + assert row, f"no session logged in through the relay, so the startup did not complete: {psql.poll()}" + time.sleep(SILENT_WAIT) + row = pg.psql(activity).stdout.strip() + assert row == "idle|", f"the session through the silent relay is not idle with no query: {row!r}" + assert psql.poll() is None, f"psql was answered through the silent relay: {psql.communicate()}" + assert len(relay.silenced) == 1, relay.silenced + finally: + psql.kill() + psql.communicate() + + +@pytest.mark.parametrize("case", SILENT_CASES) +def test_the_silent_after_startup_relay_forwards_the_startup_then_nothing_and_holds_both_sockets( + request, case): + """T229c's relay (lane 3's batch 8; TP:7682-7684), a relay of the + standard library on 127.0.0.1 at a free port: `[forwards-the-startup]`, + the client's startup and the server's answer, up to and including its + first ReadyForQuery, arrive byte for byte; `[then-nothing]`, after it + nothing is forwarded either way; `[holds-both-sockets]`, after it a close + on either side reaches neither, and both ends stay open until the relay + closes; `[psql-on-the-socket]`, the engine's `psql`, through it to the + session cluster's Unix socket, logs in and is never answered, its + session idle with no query.""" + import pgcluster + relay_of = getattr(pgcluster, "silent_after_startup", None) + assert relay_of is not None, ( + "tests/pgcluster.py has no silent_after_startup: T229 builds it (lane 3's batch 8)") + if case == "forwards-the-startup": + _silent_forwards_the_startup(relay_of) + elif case == "then-nothing": + _silent_then_nothing(relay_of) + elif case == "holds-both-sockets": + _silent_holds_both_sockets(relay_of) + else: + _silent_psql_on_the_socket(relay_of, request) + + +# ---------------------------------------------------------------- T229f's races +#: THE RELAYS' SHUTDOWN RACES (T229f; Codex's SHOULD 5 on f060619c, +#: opensoft/openRepoTools#165 6882190927). Each case opens its window with a +#: hook on the relay's seam, `tests/pgcluster.py`'s `_seam`, which holds one +#: of the relay's threads on an event where a concurrent `close()` meets it, +#: never with a sleep. Both relays, in front of a loopback listener of the +#: standard library that never accepts, so no engine is needed. +RACE_RELAYS = ["delayed-loopback", "silent-after-startup"] +#: The bound on each wait for a held thread to arrive, or for a relay's +#: thread to end: only a failure waits it out. +RACE_WAIT = 30.0 + + +def _race_relay(kind: str): + """A relay of `kind` in front of a listener that never accepts, whose + backlog completes the relay's upstream connect: (relay, listener).""" + import pgcluster + server = socket.create_server(("127.0.0.1", 0)) + port = server.getsockname()[1] + if kind == "delayed-loopback": + return pgcluster.delayed_loopback(port, 0.0), server + return pgcluster.silent_after_startup(port), server + + +def _race_end(relay) -> list: + """The relay closed once more, since a red case's `close()` may have + stopped short, and each of its threads, found by its name, given until + RACE_WAIT to end, so that no leak outlives its case: the names of those + still alive.""" + try: + relay.close(wait=0.0) + except RuntimeError: + pass + prefixes = tuple(f"{kind}-{relay.port}-" for kind in RACE_RELAYS) + end = time.monotonic() + RACE_WAIT + while True: + live = [t for t in threading.enumerate() if t.name.startswith(prefixes) and t.is_alive()] + if not live or time.monotonic() >= end: + return sorted(t.name for t in live) + live[0].join(max(0.0, end - time.monotonic())) + + +@pytest.mark.parametrize("kind", RACE_RELAYS) +def test_a_relay_closed_while_it_connects_upstream_relays_nothing_and_leaves_no_thread(kind): + """T229f (Codex's SHOULD 5 on f060619c): a client the relay has accepted, + whose upstream connect is still under way when `close()` takes its + snapshot, is closed, never relayed. The seam holds `_accept`, with the + client and its upstream in hand, until `close()` has its snapshot, as a + slow upstream connect would; when `close()` returns, no thread of the + relay's is alive, and the client's end is closed. + `[silent-after-startup]` passed before T229f, on its `done` flag; + `[delayed-loopback]`, with no closing flag, registered the pair after the + snapshot and started its readers, which `close()` never saw.""" + relay, server = _race_relay(kind) + arrived, snapshot = threading.Event(), threading.Event() + + def hook(point, name): + if point == "accepted": + arrived.set() + snapshot.wait(RACE_WAIT) + elif point == "snapshot": + snapshot.set() + relay.seam = hook + client = socket.create_connection(("127.0.0.1", relay.port), timeout=RACE_WAIT) + try: + assert arrived.wait(RACE_WAIT), f"[{kind}] the relay's accept never reached its seam" + relay.close() + left = relay.alive() + assert left == [], f"[{kind}] close() has returned, and the relay's threads are alive: {left}" + assert _within(client, RACE_WAIT) == b"", ( + f"[{kind}] the client accepted as close() began was not closed") + finally: + snapshot.set() + client.close() + server.close() + _race_end(relay) + + +@pytest.mark.parametrize("kind", RACE_RELAYS) +def test_a_relay_closed_while_it_starts_a_thread_never_joins_one_not_yet_started(kind): + """T229f (Codex's SHOULD 5 on f060619c): `close()` meets threads the + relay is spawning, each listed by `_spawn` under the lock `close()` + snapshots under, and held by the seam as `_spawn` leaves that lock: + `[delayed-loopback]`'s two readers, each as it spawns its deliverer, and + `[silent-after-startup]`'s acceptor as it spawns the pump. + `close(wait=0)`, as when an earlier join has spent the deadline, joins + each thread of its snapshot and raises nothing, and once the hold is + released every thread of the relay's ends. Before T229f, `_spawn` started + the thread only after it left the lock, so `close()` joined a thread not + yet started, and `Thread.join` raised RuntimeError.""" + relay, server = _race_relay(kind) + name, count = ("deliver", 2) if kind == "delayed-loopback" else ("pump", 1) + arrived, release, lock, held = threading.Event(), threading.Event(), threading.Lock(), [] + + def hook(point, spawned): + if point != "listed" or spawned != name: + return + with lock: + held.append(threading.current_thread().name) + if len(held) == count: + arrived.set() + release.wait(RACE_WAIT) + relay.seam = hook + client = socket.create_connection(("127.0.0.1", relay.port), timeout=RACE_WAIT) + raised = None + try: + assert arrived.wait(RACE_WAIT), f"[{kind}] the seam holds {held}, not {count} {name} spawn(s)" + try: + relay.close(wait=0.0) + except RuntimeError as error: + raised = error + assert raised is None, ( + f"[{kind}] close() joined a thread `_spawn` had listed and not yet started: {raised!r}") + finally: + release.set() + client.close() + server.close() + left = _race_end(relay) + assert left == [], f"[{kind}] the relay's threads outlive it: {left}" + + #: THE STALE SWEEP'S CASES (T205c). Every pid is fake, above any system's pid #: limit, and every signal goes to a recorder through the module's seam. SWEEP_CASES = ["no-proc", "pid-not-positive", "malformed", "does-not-stop", "reused-pid", "orphan"] @@ -318,6 +789,16 @@ def kill(target, sig): assert swept == ([] if kept else [str(root)]), f"[{case}] the sweep reports {swept}" +def test_the_delayed_loopback_relay_needs_no_proc_for_its_no_root_case(monkeypatch, tmp_path): + """T229e (Codex's BLOCKING 3 on f060619c): T229's `[no-root]` case, run + with the module's `/proc` a directory that does not exist, as on macOS, + still starts and uses the relay under the job's own uid, and reads no + capability set where there is none to read.""" + import pgcluster + monkeypatch.setattr(pgcluster, "_PROC", tmp_path / "no-proc") + _relay_no_root() + + class _HeldChild: """A stand-in for `lanes-index login` (T228b's case): it never opens the pty, so the pty ends at once, and it holds its stderr open until it is diff --git a/tests/test_sql_register_guard.py b/tests/test_sql_register_guard.py new file mode 100644 index 00000000..2ea1f359 --- /dev/null +++ b/tests/test_sql_register_guard.py @@ -0,0 +1,8179 @@ +# SPDX-License-Identifier: Apache-2.0 +"""The name guard's own cases, `lanes-edit.sh guard` and answer 2's detached +bind, `guard-bind` (feature 007; L2-N3; opensoft/openRepoTools#165). + +T214 writes AT-F6's phase-N cases (the test plan's "Answer 2's bind, +detached"): lane 4's cases 1 to 7, 12 to 17 and 22, the four rows (a) to (d), +the `bind-failed` record for each code, lane 4's rows 34 and 35, and lane 5's +two (A5). The bind's writes, cases 8 to 11 and 18 to 21, are T254's, with the +`[primary]` half of every test below that binds through `start-record` in +both modes (A1): the mode is each such id's last part, `[files]` here. + +THE ORACLE is the test plan's AT-F6 and lane 5's bind-record contract, draft 7 +(`bind-record-d7-a832486c.md`): the record's keys and modes (its sections 1 to +3), the bound (section 4), the guard's eleven cases (section 5) and +`pid_start_of` (section 6). Where a text is quoted below it is the contract's; +where the code's own spelling differs from the contract's (a capital letter, +a sentence's opening), the case matches the words both share. + +THE ESTATE is T203c's (`test_sql_register_helpers.py`): a bare origin, the +lane's checkout under `$HOME/projects` with `lanes/LANES.md` pushed, +`$HOME/.agents/workspace.yaml`, the compact hook JSON, and `guard_session`'s +live session record and stand-in `tmux` (T203c; R-F10-27, R-F10-28), in files +mode. The window is lane `repoA-2`, whose row names the session; the session +is named `repoA-3`, a lane with a row of its own; so the guard's first prompt +makes the offer, and a `2` answers it. `LANES_LANE_START` names a stand-in +`lane-start` that logs its argv and environment and holds, fails or forks as +the case says; `LANES_EDIT` names a stand-in that logs each call and answers +`set-row-state` (or sleeps on it); `LANES_BIND_BODY` names a stand-in body +(R48). The hook runs under a runner that, like Claude Code 2.1.319, sends +`SIGTERM` to the hook's whole process group at its 5 s timeout and does not +wait on pipes a child inherits. + +EVERY CASE BUT TWO IS RED TODAY by its own assertion: today's answer 2 runs +`lane-start` inside the hook, so no "BINDING" is printed and the runner stops +the hook at 5 s; today's guard has no bind modes, no `guard-bind` and no +`pid_start_of`. They fail until L5-A1, lane 5's T502. Case 22's +`test_guard_bind_computes_bound_s_from_c_n_a_and_the_service` and lane 5's +`test_the_post_bind_refill_is_one_register_read_and_never_git` also fail until +L5-A3, lane 5's T507, which copies `c`, `n_a` and `w_s_ms` from `.head` and +makes the post-bind refill. Of the `[files]` cases that run the real +`lane-start`, only `test_the_bind_child_records_bind_failed_with_the_code_and_binds_nothing` +also fails until lane 4's `start-record` (L4-B9, T427 and T428), whose calls it +asserts; case 17 and row (d) need nothing more, and pass on lane 5's `6050581` +with T214g's estate (T214h, T214i). The two are +`test_the_hook_string_and_guard_timeout_are_unchanged`, an invariant that holds +today, and `test_an_unreadable_bind_record_is_dropped_with_exit_2`, whose +oracle is today's text and today's drop. +""" + +from __future__ import annotations + +import atexit +import calendar +import errno +import hashlib +import json +import os +import re +import shlex +import shutil +import signal +import subprocess +import sys +import tempfile +import threading +import time +import types +import uuid +from pathlib import Path +from urllib.parse import urlsplit + +import pytest + +from conftest import REPO, WINDOWS_SKIP +from sql_register_helpers import (ARGV_LOG, GUARD_PANE, GUARD_WINDOW, PSQL_SHIM, + PSQL_SHIM_CONTROL, PSQL_SHIM_ENDS, PSQL_SHIM_LOG, + contract_stub, + guard_session, guard_strip_env) + +pytestmark = [WINDOWS_SKIP, pytest.mark.skipif( + shutil.which("bash") is None or shutil.which("git") is None + or not Path("/proc/self/stat").exists(), + reason="the lane tooling is bash over git, and the bind's liveness test reads /proc")] + +#: THE LANDING GATE'S TABLE (T280; task sets version 12b's rule 11, +#: opensoft/openRepoTools#165 6877673742), TEMPORARY: T281 removes it in the +#: last set. `tests/sql_register_gate.py` reads it: in a code pull request's +#: full CI, each id below is skipped until every task its row names has +#: landed, and the skip names them. The rows are from the Orders of T213 +#: (tasks:1992), T214 (:2013), T226 (:2177), T237 (:2302, with :2297) and T254 +#: (:2419), tasks.md at lane 3's commit 17 `204145ae`, each row's owner and +#: cite beside it. T214n's five rows, lane 5's five cases of +#: `bind-record.md`'s section 8, are from T214's Order at the follow-up's +#: commit 24 `f9d6069e` (tasks:2013), which keeps that line number. T214o's +#: nine rows, section 8's other bullets at spec#47's draft 14 `96d14916`, are +#: from the same Order (lane 2, #165 6882026139, Part B). T254zw's row, its +#: :376, is from T254's Order (tasks:2419; K1). T214t's +#: row, for T502's part 21 (lane 5, opensoft/openRepoTools#165 6885608994), +#: is keyed by the same Order: its case fails until T502 lands. T214v's +#: and T214w's rows, for T502's part 22 and its rule for the hook's writes +#: (lane 3's ruling 5, (A), opensoft/openRepoTools#165 6885771975, and its +#: confirmation, 6886113842), are keyed by the same Order, and so is +#: T214x's, for the back-out of the same rule (6dd8bbbd:23333-23384). T213r's +#: row for `test_no_session_environment_carries_a_database_url_or_password` +#: adds T512 to T213's Order: its `PGPASSFILE` assertions read the +#: service's own held `psql` child (TP:1952 at `f9d6069e`), which only +#: T512's `serve` starts, and T512's verify runs it (tasks:1604). T214's +#: two cases that pass today, +#: `test_the_hook_string_and_guard_timeout_are_unchanged` and +#: `test_an_unreadable_bind_record_is_dropped_with_exit_2` (tasks:2013), have +#: no row, so they always run. T237zzb's row, for its `session-start` cases +#: off primary, is keyed by analogy with T513's verify case's, +#: `test_the_session_start_block_reads_the_mirror_and_only_starts_the_service` +#: (T237's Order, tasks:2302 at commit 24 `f9d6069e`: its tests fail until +#: L5-S1 lands, lane 5's T511 to T513). T237zze's row, for the client's own +#: check of the server's uid, is the row of SVC-2's other case, +#: `test_a_client_of_another_uid_is_closed_by_so_peercred`: tasks:2278 at +#: lane 3's commit 31 `8f50d105` says it fails until L5-S1, lane 5's T512, +#: under the same Order (tasks:2302 there). No task is common to every row, +#: so there is no "*" row. +SQL_REGISTER_GATE_TABLE = { + "test_a_65536_byte_request_is_sent_and_taken_and_a_65537_byte_one_is_neither": ("T512", "T513"), # T237; tasks:2302 + "test_a_bind_body_past_its_bound_ends_with_the_bounds_code_and_leaves_no_process": ("T502",), # T214; tasks:2013 + "test_a_bind_in_doubt_looks_its_write_up_before_a_rerun": ("T427", "T428", "T502", "T510"), # T254; tasks:2419 + "test_a_bind_killed_mid_commit_waits_for_ended_utc_plus_c_before_its_lookup": ("T427", "T428", "T502", "T510"), # T254; tasks:2419 + "test_a_bind_over_a_delayed_tls_link_at_c_3_ends_bound_inside_530_s": ("T427", "T428", "T502", "T510"), # T254; tasks:2419 + "test_a_bind_whose_write_id_no_pending_record_holds_makes_no_lookup": ("T427", "T428", "T502", "T510"), # T254; tasks:2419 + "test_a_bind_with_no_timeout_says_bounded_no_and_kill_stops_its_group_once": ("T502",), # T214; tasks:2013 + "test_a_binding_from_another_host_or_container_is_not_judged_by_its_pid_until_the_deadline_plus_60_s": ("T502",), # T214; tasks:2013 + "test_a_cache_miss_at_the_service_answers_unavailable_and_fetches_in_the_background": ("T302", "T512", "T513"), # T237; tasks:2302 + "test_a_client_of_another_uid_is_closed_by_so_peercred": ("T512", "T513"), # T237; tasks:2302 + "test_a_connect_timeout_above_the_direct_reads_share_is_cut_at_the_parse_start_line": ("T103", "T113", "T507"), # T213; tasks:1992 + "test_a_database_that_does_not_answer_is_2_inside_4_5_s": ("T103", "T113", "T507"), # T213; tasks:1992 + "test_a_dead_bind_outer_answers_in_progress_while_its_session_lives_then_no_outcome": ("T502",), # T214; tasks:2013 + "test_a_failed_bind_can_be_answered_again": ("T502",), # T214; tasks:2013 + "test_a_failed_bind_renames_back_keeps_the_offer_and_allows_three_attempts": ("T502",), # T214; tasks:2013 + "test_a_guard_that_starts_too_late_refuses_2_without_a_read": ("T103", "T113", "T507"), # T213; tasks:1992 + "test_a_live_bind_past_its_bound_that_timeout_has_not_ended_answers_2_and_names_the_pid_to_kill": ("T502",), # T214; tasks:2013 + "test_a_malformed_bind_pid_waits_for_the_deadline_then_is_stale": ("T502",), # T214; tasks:2013 + "test_a_noncanonical_out_names_no_facts_file_and_no_words": ("T502",), # T214; tasks:2013 + "test_a_prompt_mid_bind_is_not_passed_and_leaves_the_record": ("T502",), # T214; tasks:2013 + "test_a_rerun_after_a_failed_stamp_push_writes_one_stamp": ("T427", "T428", "T502", "T510"), # T254; tasks:2419 + "test_a_reused_bind_pid_gives_no_outcome_with_no_session_test": ("T502",), # T214; tasks:2013 + "test_a_second_read_past_the_start_line_is_noted_not_refused": ("T103", "T113", "T507"), # T213; tasks:1992 + "test_a_service_that_cannot_start_falls_back_to_the_direct_read": ("T512", "T513"), # T237; tasks:2302 + "test_a_service_that_never_answers_falls_back_inside_5_s": ("T512", "T513"), # T237; tasks:2302 + "test_a_stale_socket_is_unlinked_under_the_lock_and_rebound": ("T512", "T513"), # T237; tasks:2302 + "test_a_whole_file_fetch_the_start_line_cuts_fills_the_image_cache_for_the_next_prompt": ("T103", "T113", "T507"), # T213; tasks:1992 + "test_a_write_between_two_requests_is_in_the_next_answer": ("T107", "T227", "T228", "T512", "T513"), # T237; tasks:2302 + "test_after_bound_one_moved_then_the_next_prompt_passes": ("T502",), # T214; tasks:2013 + "test_an_outer_that_wrote_pid_alone_still_writes_its_outcome": ("T502",), # T214; tasks:2013 + "test_an_owner_file_from_another_namespace_or_boot_is_no_service": ("T512", "T513"), # T237; tasks:2302 + "test_answer_2_binds_nothing_where_its_offer_is_gone_or_no_longer_the_one_answered": ("T502",), # T214; tasks:2013 + "test_answer_2_exits_2_binding_before_t0_plus_1_s_and_the_runner_sees_eof": ("T502",), # T214; tasks:2013 + "test_answer_2_survives_a_group_sigterm_at_the_hooks_timeout": ("T502",), # T214; tasks:2013 + "test_answer_2s_back_out_writes_nothing_where_its_binding_is_gone_or_no_longer_binding": ("T502",), # T214; tasks:2013 + "test_case_11_with_a_live_outer_drops_the_record_and_keeps_its_files": ("T502",), # T214; tasks:2013 + "test_choice_1_allows_nothing_where_its_offer_is_gone_or_no_longer_the_one_answered": ("T502",), # T214; tasks:2013 + "test_claude_no_lane_still_skips_before_any_input": ("T103", "T113", "T507"), # T213; tasks:1992 + "test_each_service_request_is_one_query": ("T229", "T512", "T513"), # T237; tasks:2302 + "test_every_bind_rewrite_is_0600_and_a_failed_one_leaves_the_record": ("T502",), # T214; tasks:2013 + "test_guard_bind_computes_bound_s_from_c_n_a_and_the_service": ("T502", "T507"), # T214; tasks:2013 + "test_guard_bind_exits_as_section_7_gives": ("T502",), # T214; tasks:2013 + "test_kill_of_the_bind_outer_ends_the_record_with_the_signals_code": ("T502",), # T214; tasks:2013 + "test_no_session_environment_carries_a_database_url_or_password": ("T103", "T113", "T502", "T507", "T512"), # T213; tasks:1992, and T512 (T213r) + "test_one_instance_holds_register_lock_and_a_second_starter_exits_0": ("T512", "T513"), # T237; tasks:2302 + "test_pid_start_of_answers_live_dead_and_unreadable": ("T502",), # T214; tasks:2013 + "test_serve_refuses_unless_the_mode_answer_is_primary": ("T512", "T513"), # T237; tasks:2302 + "test_session_start_starts_no_service_outside_primary": ("T512", "T513"), # T237; tasks:2302 + "test_status_prints_the_services_lines_and_its_failure_stamp": ("T512", "T513"), # T237; tasks:2302 + "test_the_bind_child_environment_is_as_lane_4_lists_it": ("T502",), # T214; tasks:2013 + "test_the_bind_child_reaches_tmux_through_tmux_pane": ("T502",), # T214; tasks:2013 + "test_the_bind_child_records_bind_failed_with_the_code_and_binds_nothing": ("T427", "T428", "T502"), # T214; tasks:2013 + "test_the_bind_child_survives_a_group_kill_and_hangup_and_ends_bound": ("T502",), # T214; tasks:2013 + "test_the_bind_childs_lookup_sends_the_five_copied_values": ("T427", "T428", "T502", "T510"), # T254; tasks:2419 + "test_the_bind_is_one_register_write_and_refuses_a_changed_row": ("T427", "T428", "T502", "T510"), # T254; tasks:2419 + "test_the_bind_records_grammar_as_every_reader_takes_it": ("T502",), # T214; tasks:2013 + "test_the_bind_resume_path_makes_at_most_n_r_read_calls": ("T502",), # T214; tasks:2013 + "test_the_client_treats_a_service_of_another_uid_as_unavailable": ("T512", "T513"), # T237; tasks:2302, with :2278 + "test_the_database_unreachable_with_the_service_up_is_2_never_a_cached_ok": ("T512", "T513"), # T237; tasks:2302 + "test_the_direct_read_connects_as_its_engineers_reader_login": ("T103", "T113", "T507"), # T213; tasks:1992 + "test_the_facts_file_is_made_empty_first_and_its_absence_is_reported": ("T502",), # T214; tasks:2013 + "test_the_files_index_passes_six_digits": ("T502",), # T214; tasks:2013 + "test_the_first_call_starts_the_service_with_no_supervisor": ("T512", "T513"), # T237; tasks:2302 + "test_the_guard_answer_time_is_recorded_beside_todays_direct_guard": ("T512", "T513"), # T237; tasks:2302 + "test_the_guard_maps_69_75_and_3_to_2": ("T103", "T113", "T507"), # T213; tasks:1992 + "test_the_guard_through_the_service_answers_byte_identical_to_the_direct_read": ("T512", "T513"), # T237; tasks:2302 + "test_the_guards_last_budget_line_is_below_guard_timeout": ("T103", "T113", "T507"), # T213; tasks:1992 + "test_the_guards_register_parse_is_timed_on_a_real_sized_register_beside_todays_six_reads_through_git": ("T111", "T112", "T507"), # T226; tasks:2177 + "test_the_guards_request_carries_only_file_names": ("T512", "T513"), # T237; tasks:2302 + "test_the_next_offers_files_index_runs_above_a_case_11_leftover": ("T502",), # T214; tasks:2013 + "test_the_outcome_rewrite_has_three_results": ("T502",), # T214; tasks:2013 + "test_the_outer_gathers_its_copies_before_its_last_ownership_read": ("T502",), # T214; tasks:2013 + "test_the_outer_leaves_a_record_no_longer_its_own": ("T502",), # T214; tasks:2013 + "test_the_outer_matches_host_and_container_without_regard_to_case": ("T502",), # T214; tasks:2013 + "test_the_outer_runs_nothing_where_its_record_is_not_binding_at_its_start": ("T502",), # T214; tasks:2013 + "test_the_post_bind_refill_is_one_register_read_and_never_git": ("T502", "T507"), # T214; tasks:2013 + "test_the_service_reaches_the_database_only_through_psql": ("T512", "T513"), # T237; tasks:2302 + "test_the_service_stops_after_its_idle_time_and_unlinks_its_socket": ("T512", "T513"), # T237; tasks:2302 + "test_the_services_idle_check_replaces_a_dropped_connection_in_the_background": ("T512", "T513"), # T237; tasks:2302 + "test_the_services_request_timer_follows_register_rtt_ms": ("T512", "T513"), # T237; tasks:2302 + "test_the_session_start_block_makes_no_register_call_on_primary": ("T103", "T113", "T507"), # T213; tasks:1992 + "test_the_session_start_block_reads_the_mirror_and_only_starts_the_service": ("T512", "T513"), # T237; tasks:2302 + "test_the_socket_directory_is_a_0700_directory_of_this_uid_and_never_a_symlink": ("T512", "T513"), # T237; tasks:2302 + "test_the_stale_row_copies_a_dead_outers_pending_call_and_the_next_2_looks_it_up": ("T427", "T428", "T502", "T510"), # T254; tasks:2419 + "test_todays_direct_guard_is_timed_in_its_four_parts": ("T111", "T112", "T507"), # T226; tasks:2177 + "test_two_sessions_binding_one_lane_in_files_mode_both_binds_land": ("T502",), # T214; tasks:2013 + "test_two_sessions_binding_one_lane_one_start_record_commits": ("T427", "T428", "T502", "T510"), # T254; tasks:2419 + "test_with_the_service_down_the_hook_falls_back_and_says_so": ("T507", "T512", "T513"), # T237; tasks:2302 + "test_a_connect_timeout_above_the_direct_reads_share_is_cut_at_the_parse_start_line[service-up]": ("T507", "T512", "T513"), # T237; tasks:2302 + "test_a_database_that_does_not_answer_is_2_inside_4_5_s[1-service-up]": ("T507", "T512", "T513"), # T237; tasks:2302 + "test_a_database_that_does_not_answer_is_2_inside_4_5_s[2-service-down]": ("T103", "T113", "T229", "T507"), # T213; tasks:1992 + "test_a_database_that_does_not_answer_is_2_inside_4_5_s[2-service-up]": ("T507", "T512", "T513"), # T237; tasks:2302 + "test_a_database_that_does_not_answer_is_2_inside_4_5_s[3-service-up]": ("T507", "T512", "T513"), # T237; tasks:2302 + "test_a_database_that_does_not_answer_is_2_inside_4_5_s[4-service-up]": ("T507", "T512", "T513"), # T237; tasks:2302 + "test_the_guard_through_the_service_answers_byte_identical_to_the_direct_read[offer]": ("T107", "T108", "T227", "T228", "T507", "T512", "T513"), # T237; tasks:2297 + "test_the_guard_through_the_service_answers_byte_identical_to_the_direct_read[ok]": ("T107", "T108", "T227", "T228", "T507", "T512", "T513"), # T237; tasks:2297 + "test_the_guard_through_the_service_answers_byte_identical_to_the_direct_read[refuse]": ("T107", "T108", "T227", "T228", "T507", "T512", "T513"), # T237; tasks:2297 +} + +GUARD = REPO / "lanes-edit.sh" +INSTALLER = REPO / "openRepoTools" +#: The window's lane and the lane the session is named for: the offer's +#: `from` and `to`. +FROM = GUARD_WINDOW +TO = "repoA-3" +#: This guard's host and container, as the record's `host` and `container` +#: name them (`LANES_WORKSTATION`, `LANES_CONTAINER`; contract section 3). +HOST = "Eagle" +CONTAINER = "g-box" +#: The hook's timeout, `GUARD_TIMEOUT` (plan.md, "Governed invariants"). +HOOK_TIMEOUT = 5.0 +DOT = chr(0xB7) +#: The five copies a record holds only on primary (contract section 3; T254). +COPIES = ("write_id", "generation", "not_after", "write_lane", "args_sha256") +#: The shim's counters beside it (T203's `PSQL_SHIM`, whose docstring names +#: the file); `Estate.shim` drops a lost host from it (T254w). +PSQL_SHIM_STATE = "psql-shim.state" +#: The lock the shim takes around each call's read and rewrite of that state +#: and its read of the control file (`PSQL_SHIM`'s `main`, `LOCK`), which +#: `Estate.shim` takes too (T254zl), and how long it waits for it. +PSQL_SHIM_LOCK = "psql-shim.lock" +SHIM_LOCK_S = 30.0 +#: CASE 10's `[found]` ARMS, and case 19's (T254w): "the shim's `after` mode +#: on that commit call, which commits, then exit 2 on every later call" +#: (TP:6094-6095 at a6497d00), as `no-reconnect` as `after` on the bind's +#: first commit call. So the write's own retry snapshot fails too and cannot +#: answer `found=` inside the run (lane 5, #165 6842157774; lane 3, +#: 6842243851), and the guard's prefetch calls, before the commit, are not +#: failed (T254t). The case's next `est.shim()` brings the host back. +FOUND_ARMS = ({"mode": "no-reconnect", "match": "commit_write", "call": 1, "as": "after"},) + +#: The contract's texts (section 5), as the guard prints them on stderr. +OFFER = "WARNING: the lane and Claude session names disagree" +BINDING = f"BINDING: this window is now named {TO}" +IN_PROGRESS = "BINDING IN PROGRESS" +NOT_SENT = "Your prompt was NOT sent" +NO_OUTCOME = "IS NO LONGER RUNNING AND LEFT NO OUTCOME" +UNREADABLE = ("could not be read, so it has been dropped rather than answered on a guess. " + "Send your prompt again and the question will be asked afresh.") +NO_LONGER_2 = "choice 2 is no longer offered" +KEPT = "offer is KEPT" +BY_BOUND = "stopped by its bound" +BY_SIGNAL = "stopped by a signal" +UNKNOWN = "what it wrote is not known" + +REGISTER_HEADER = ["# LANES.md", "", + "| lane | session id | workstation / env / user | started (UTC) | objects " + "owned | handoff path | state |", + "|---|---|---|---|---|---|---|"] + + +# ---------------------------------------------------------------- the stand-ins + +#: THE STAND-IN `lane-start` (the test plan's fixture: one that sleeps, exits a +#: given code, or forks a `( ... & )` child as `index_nudge` does). It logs one +#: JSON line at its start and one at its end to `<ctl>/lane-start.log`, with +#: its argv, its process's ids, the variables lane 4's table names, and where +#: its stdin points. Before that line it writes its whole environment, what +#: the bind hands `lane-start` and so a session, to +#: `<ctl>/lane-start.environ.<pid>.json`, whole, by a temporary file and a +#: rename (T213r reads it for a URL or a password), so the log's lines stay +#: as short as they were. The files in `<ctl>` steer it: `hold` (wait for +#: `release`, at most that many seconds), `sleep` (that many seconds), +#: `rc`, `ignore-term`, `tmux` (make one untargeted `tmux` call) and `fork` +#: (leave a child that ignores TERM, living that many seconds). +#: `pending-record` (T254z; case 20) makes it write, before it holds, a whole +#: `start-record` pending record with one `call=` line, as T412's +#: `wr_record_write` lays one out, from the JSON in that file: `generation`, +#: `lane`, `session`, `host`, `container`, `database` and `base`. Its +#: `not_after` is the stand-in's clock, so a lookup may decide at once. +#: With `not_after_offsets` (T254zj), a list of seconds, it writes one `call=` +#: line per offset, its clock and `not_after` the stand-in's clock plus it. +#: Each entry carries the start time of each pid it logs, `start` and +#: `fork_start`, by which the teardown signals it (T237zzg; RZ-27's NIT 3). +_STUB_LANE_START = r'''#!@PY@ -I +import json, os, signal, subprocess, sys, time +CTL = @CTL@ +KEYS = ("LANES_NO_FETCH", "LANES_ACT", "LANES_EXPECT", "LANES_WRITE_ID", + "LANES_WRITE_GENERATION", "LANE_START_HANDOFF_ANSWER", "LANES_GIT_TIMEOUT", + "TMUX", "TMUX_PANE", "LANES_BIND_BODY", "LANES_BIND_FACTS") +def ctl(name, default=None): + try: + with open(os.path.join(CTL, name), encoding="utf-8") as handle: + return handle.read().strip() + except OSError: + return default +def ids(): + with open("/proc/self/stat", encoding="utf-8") as handle: + f = handle.read().rsplit(") ", 1)[1].split() + return {"ppid": int(f[1]), "pgid": int(f[2]), "sid": int(f[3]), "start": f[19]} +def start_of(pid): + try: + with open("/proc/%d/stat" % pid, encoding="utf-8") as handle: + return handle.read().rsplit(") ", 1)[1].split()[19] + except OSError: + return None +def log(entry): + with open(os.path.join(CTL, "lane-start.log"), "a", encoding="utf-8") as handle: + handle.write(json.dumps(entry, sort_keys=True) + "\n") +environ_file = os.path.join(CTL, "lane-start.environ.%d.json" % os.getpid()) +with open(environ_file + ".tmp", "w", encoding="utf-8") as handle: + json.dump(dict(os.environ), handle, sort_keys=True) +os.replace(environ_file + ".tmp", environ_file) +entry = dict(event="start", argv=sys.argv[1:], pid=os.getpid(), t=time.time(), + env={k: os.environ.get(k) for k in KEYS}, **ids()) +try: + entry["stdin"] = os.readlink("/proc/self/fd/0") +except OSError: + entry["stdin"] = None +if ctl("ignore-term") is not None: + signal.signal(signal.SIGTERM, signal.SIG_IGN) +if ctl("tmux") is not None: + done = subprocess.run(["tmux", "display-message", "-p", "#{pane_id}"], + capture_output=True, text=True) + entry["tmux"] = [done.returncode, done.stdout.strip()] +if ctl("fork") is not None: + child = subprocess.Popen( + [sys.executable, "-I", "-c", + "import signal, time; signal.signal(signal.SIGTERM, signal.SIG_IGN); " + "time.sleep(%s)" % float(ctl("fork"))], + stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + entry["fork"] = child.pid + entry["fork_start"] = start_of(child.pid) +if ctl("pending-record") is not None: + import hashlib, uuid + spec = json.loads(ctl("pending-record")) + state = os.environ.get("XDG_STATE_HOME") or os.path.join( + os.environ.get("HOME") or "/", ".local", "state") + pending = os.path.join(state, "openRepoTools", "register-pending") + os.makedirs(pending, mode=0o700, exist_ok=True) + now, clock = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), int(time.time()) + digest = hashlib.sha256(("start-record %s %s" % (spec["lane"], spec["session"]) + ).encode("utf-8")).hexdigest() + with open("/proc/self/stat", encoding="utf-8") as handle: + started = handle.read().rsplit(") ", 1)[1].split()[19] + lines = ["format=1", "write_id=%s" % uuid.uuid4(), "generation=%s" % spec["generation"], + "database=%s" % spec["database"], "lane=%s" % spec["lane"], + "session=%s" % spec["session"], "verb=start-record", "args_sha256=%s" % digest, + "cmdline=lanes-edit.sh start-record %s" % spec["lane"], "created_utc=%s" % now, + "updated_utc=%s" % now, "pid=%d" % os.getpid(), "pid_start=%s" % started, + "host=%s" % spec["host"], "container=%s" % spec["container"]] + offsets = spec.get("not_after_offsets") or [0] + lines.append("attempts=%d" % len(offsets)) + for n, offset in enumerate(offsets, 1): + lines.append("call=%d %d %d %s %s" % ( + int(spec["base"]), clock + int(offset), clock + int(offset), + hashlib.sha256(b"").hexdigest(), + os.path.join(pending, "stand-in-attempt" if n == 1 else "stand-in-attempt-%d" % n))) + path = os.path.join(pending, digest) + with open(path + ".tmp", "w", encoding="utf-8") as handle: + handle.write("\n".join(lines) + "\n") + os.chmod(path + ".tmp", 0o600) + os.replace(path + ".tmp", path) + entry["pending"] = path +log(entry) +if ctl("sleep") is not None: + time.sleep(float(ctl("sleep"))) +elif ctl("hold") is not None: + end = time.time() + float(ctl("hold") or 60) + while time.time() < end and not os.path.exists(os.path.join(CTL, "release")): + time.sleep(0.05) +code = int(ctl("rc", "0") or 0) +if code: + sys.stderr.write("lane-start: the stand-in refuses with %d (T214's fixture)\n" % code) +log(dict(event="end", pid=os.getpid(), t=time.time(), rc=code)) +sys.exit(code) +''' + +#: THE STAND-IN BODY, put in through `LANES_BIND_BODY` (R48; case 7's seam, +#: and case 22's "stub body that exits 0"). It logs its argv, its ids and its +#: parent's argv (`timeout`'s, where the outer bounds it) to `<ctl>/body.log`. +#: `body-ignore-term` makes it ignore TERM in its own process; +#: `body-grandchild` leaves a child that ignores TERM; `body-sleep` and +#: `body-rc` say how long it runs and how it ends. Each entry carries the +#: start of each pid it logs, `start` and `grandchild_start` (T237zzg). +_STUB_BODY = r'''#!@PY@ -I +import json, os, signal, subprocess, sys, time +CTL = @CTL@ +def ctl(name, default=None): + try: + with open(os.path.join(CTL, name), encoding="utf-8") as handle: + return handle.read().strip() + except OSError: + return default +def ids(): + with open("/proc/self/stat", encoding="utf-8") as handle: + f = handle.read().rsplit(") ", 1)[1].split() + return {"ppid": int(f[1]), "pgid": int(f[2]), "sid": int(f[3]), "start": f[19]} +def start_of(pid): + try: + with open("/proc/%d/stat" % pid, encoding="utf-8") as handle: + return handle.read().rsplit(") ", 1)[1].split()[19] + except OSError: + return None +def argv_of(pid): + try: + with open("/proc/%d/cmdline" % pid, "rb") as handle: + return [a.decode("utf-8", "replace") for a in handle.read().split(b"\0")[:-1]] + except OSError: + return [] +if ctl("body-ignore-term") is not None: + signal.signal(signal.SIGTERM, signal.SIG_IGN) +entry = dict(event="body", argv=sys.argv[1:], pid=os.getpid(), t=time.time(), + parent=argv_of(os.getppid()), + env={k: os.environ.get(k) for k in ("LANES_BIND_BODY", "LANES_BIND_FACTS")}, + **ids()) +if ctl("body-grandchild") is not None: + child = subprocess.Popen( + [sys.executable, "-I", "-c", + "import signal, time; signal.signal(signal.SIGTERM, signal.SIG_IGN); time.sleep(60)"], + stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + entry["grandchild"] = child.pid + entry["grandchild_start"] = start_of(child.pid) +with open(os.path.join(CTL, "body.log"), "a", encoding="utf-8") as handle: + handle.write(json.dumps(entry, sort_keys=True) + "\n") +if ctl("body-sleep") is not None: + time.sleep(float(ctl("body-sleep"))) +sys.exit(int(ctl("body-rc", "0") or 0)) +''' + +#: THE STAND-IN `LANES_EDIT` (the fixture's "`LANES_EDIT` stub that logs and +#: counts each call"): it logs each call's argv and the bind's variables to +#: `<ctl>/lanes-edit.log`, then answers `set-row-state` with 0, or sleeps on it +#: (`edit-sleep`), and answers `start-record` with the code in +#: `start-record-rc` where that file is there; every other call, and every call +#: where `edit-real` is there, runs the checkout's `lanes-edit.sh`. T254's +#: `inject-row` runs the real `act-begin`, then a rival's `set-row-state` on +#: the lane it names, outside the act (case 9's injected row change). +_STUB_EDIT = r'''#!@PY@ -I +import json, os, sys, time +CTL = @CTL@ +REAL = @REAL@ +def ctl(name, default=None): + try: + with open(os.path.join(CTL, name), encoding="utf-8") as handle: + return handle.read().strip() + except OSError: + return default +args = sys.argv[1:] +with open(os.path.join(CTL, "lanes-edit.log"), "a", encoding="utf-8") as handle: + handle.write(json.dumps(dict(argv=args, pid=os.getpid(), t=time.time(), env={ + k: os.environ.get(k) for k in ("LANES_ACT", "LANES_EXPECT", "LANES_WRITE_ID")}), + sort_keys=True) + "\n") +verb = args[0] if args else "" +if verb == "act-begin" and ctl("inject-row") is not None: + import subprocess + done = subprocess.run(["bash", REAL] + args) + env = {k: v for k, v in os.environ.items() if k not in ("LANES_ACT", "LANES_EXPECT")} + lane = ctl("inject-row") + # THE PHRASE IS `<STATE> <middle dot> <one line>` (`row_state_check`): with an ASCII + # hyphen it was refused 2 and no rival change happened (T254u; lane 5, + # #165 6841545201). The rival's exit is kept for the case to check. + rival = subprocess.run(["bash", REAL, "set-row-state", lane, + "LIVE \u00b7 a rival's change"], env=env) + with open(os.path.join(CTL, "inject-row.rc"), "w", encoding="utf-8") as handle: + handle.write(str(rival.returncode)) + sys.exit(done.returncode) +if verb == "start-record" and ctl("start-record-rc") is not None: + sys.stderr.write("lanes-edit.sh start-record: the stand-in's code\n") + sys.exit(int(ctl("start-record-rc"))) +if verb == "set-row-state" and ctl("edit-real") is None: + if ctl("edit-sleep") is not None: + time.sleep(float(ctl("edit-sleep"))) + sys.exit(0) +os.execvp("bash", ["bash", REAL] + args) +''' + + +def _q(value) -> str: + """`value` as a Python literal, for the stand-ins' `@...@` words.""" + return repr(str(value)) + + +def _script(path: Path, text: str, **words) -> Path: + for key, value in words.items(): + text = text.replace(f"@{key}@", value) + path.write_text(text, encoding="utf-8") + path.chmod(0o755) + return path + + +# ---------------------------------------------------------------- processes + +def _stat(pid) -> dict: + """`/proc/<pid>/stat`'s state and ids, or {} where it is gone.""" + try: + text = Path(f"/proc/{pid}/stat").read_text(encoding="utf-8", errors="replace") + except OSError: + return {} + f = text.rsplit(") ", 1)[1].split() + return {"state": f[0], "ppid": int(f[1]), "pgid": int(f[2]), "sid": int(f[3]), + "start": f[19]} + + +def _alive(pid) -> bool: + return _stat(pid).get("state", "Z") not in ("Z", "X", "x", "Z") + + +def _members(field: str, value: int) -> dict: + """The live processes whose `sid` or `pgid` is `value` (zombies left out, + as the guard's session test leaves them out), as `{pid: start}`, each + start taken from the one `/proc/<pid>/stat` read that found it (T237zzg; + RZ-27's NIT 2), so the teardown signals a member only while it is that + process. A caller that tests, counts or walks it reads it as it read + the list it was.""" + found = {} + for entry in Path("/proc").iterdir(): + if not entry.name.isdigit(): + continue + st = _stat(entry.name) + if st and st[field] == value and st["state"] not in ("Z", "X", "x"): + found[int(entry.name)] = st["start"] + return found + + +def _argv(pid) -> list: + try: + raw = Path(f"/proc/{pid}/cmdline").read_bytes() + except OSError: + return [] + return [a.decode("utf-8", "replace") for a in raw.split(b"\0")[:-1]] + + +def _homed(state_home, *more) -> dict: + """THIS ESTATE'S PROCESSES (T237zzd), `{pid: start}`: the live processes + of this uid whose environment's `XDG_STATE_HOME` is exactly `state_home`, + or exactly one of `more`: the other state homes the estate's commands + were given under its own root (T237zzg; `Estate.swept_homes`). + Each estate's state home is a `mkdtemp` of its own (`_state_home`) that + only its `env()` passes on, and a child inherits it; every service of the + estate carries it, whether `_Service` started it with `est.env()` or the + client did (`register_serve_launch` keeps every `XDG_*`). Neither pytest + nor another estate's process holds it. + + - Only this uid's (`/proc/<pid>`'s owner), so a run as root never takes + another user's process. + - The variable's FIRST entry, the one `getenv` answers, decides, where a + process has two; and it must equal `state_home` byte for byte, so a + trailing `/`, a longer name, a subdirectory and a symlink's spelling + are never this estate's. + - The start time is read before and after the environment, and kept only + where both agree, so the start recorded is that process's: the + teardown signals a pid only while it still has it (`_kill_same`).""" + want = {os.fsencode(str(home)) for home in (state_home, *more)} + uid = os.getuid() + found = {} + for entry in Path("/proc").iterdir(): + if not entry.name.isdigit(): + continue + before = _stat(entry.name) + if not before or before["state"] in ("Z", "X", "x"): + continue + try: + if entry.stat().st_uid != uid: + continue + environ = (entry / "environ").read_bytes() + except OSError: + continue + home = next((pair[len(b"XDG_STATE_HOME="):] for pair in environ.split(b"\0") + if pair.startswith(b"XDG_STATE_HOME=")), None) + if home not in want: + continue + if _stat(entry.name).get("start") == before["start"]: + found[int(entry.name)] = before["start"] + return found + + +def _kill_same(pid, start, sig=signal.SIGKILL) -> bool: + """`sig` to `pid` only while it is the process its scan saw, by the start + time read then (T237zzd; T214u's `_record_pid` test), and never to a + member of pytest's own session, whatever its number (rule 2): such a pid + is printed and left. True where it was sent, through `_kill` alone. A + pidfd would close the gap between the check and the signal, but + `signals_recorded` (T214o) records `os.kill` and `os.killpg` only, and a + `pidfd_send_signal` would pass it by, so the check is `_record_pid`'s.""" + st = _stat(pid) + if start is None or not st or st.get("start") != start: + return False + if st.get("sid") == os.getsid(0): + print(f"Estate.close: pid {pid} is in pytest's own session, so it is not signalled: " + f"{_argv(pid)}") + return False + _kill(pid, sig) + return True + + +#: THE TEARDOWN'S LAST SWEEP (T237zzd): passes, and the seconds between them. +SWEEP_PASSES, SWEEP_STEP_S = 20, 0.1 + + +def _teardown_round(targets: dict, own: set) -> None: + """One round of `Estate.close` (T237zzd): each of `targets`, `{pid: + start}`, and the members of the session and of the group each one leads, + each member's start read in `_members`' own pass (T237zzg; RZ-27's NIT + 2), signalled through `_kill_same`; never a pid of 1 or less, nor one of + `own` (this process, its group, its session). + + A leader already gone still names the members that keep its number + (T214u): the kernel gives no new process a number that a session or a + group still holds. So a number a live process holds with another start + than its target's was given again after its session and group had + ended, and its members are the new owner's: they are not taken + (T237zzg; lane 1's NIT 1, #165 6892179926, where `_Service.stop` reaps + a pid that stays in `spare`). Nor are they where the target's start was + never read and its number is live.""" + every = dict(targets) + for pid, start in targets.items(): + if pid <= 1 or pid in own: + continue + now = _stat(pid).get("start") + if now is not None and (start is None or now != start): + continue + for member, began in {**_members("sid", pid), **_members("pgid", pid)}.items(): + every.setdefault(member, began) + for pid, start in every.items(): + if pid > 1 and pid not in own: + _kill_same(pid, start) + + +def _kill(pid, sig=signal.SIGKILL) -> None: + """`sig` to the one process `pid`, and never to more (T214u). A pid of 1 + or less is refused, and so is this process's own: `os.kill(0, ...)` + signals this process's whole group, which `tests/run.sh`'s `set -m` + makes pytest's; a negative pid signals a group, and -1 every process this + user owns; and 1 is the container's init.""" + if isinstance(pid, bool) or not isinstance(pid, int) or pid <= 1 or pid == os.getpid(): + return + try: + os.kill(pid, sig) + except (ProcessLookupError, PermissionError): + pass + + +def _record_pid(record: dict): + """THE RECORD'S `pid` AS THE ESTATE'S TEARDOWN MAY SIGNAL IT (T214u), else + None: well-formed by the guard's own rule, `guard_bind_pid_ok` (decimal + digits, no leading 0, above 1, at most 10 digits); and, where the record + holds an all-digit `pidstart` and that pid is live, live with that start + (`pid_start_of`'s test), so a pid a case wrote dead is never taken once + another process has it. A dead pid is still taken, for the members of the + session or group it led, which keep its number from being reused. + + T214o's :371 writes `pid=0`, `1`, `0<pid>` and eleven digits. Taken as + digits, `0` was `os.kill(0, SIGKILL)` to pytest's own process group, + which ended S8-26's three runs with 137 at `[pid-0]`'s teardown; `1` + swept session 1, which in a container holds its init and its main + process; and eleven digits raised `OverflowError` out of the teardown.""" + pid = record.get("pid", "") + if not re.fullmatch(r"[1-9][0-9]{0,9}", pid) or int(pid) <= 1: + return None + start = record.get("pidstart", "") + now = _stat(pid).get("start") + if re.fullmatch(r"[0-9]+", start) and now is not None and now != start: + return None + return int(pid) + + +def _until(predicate, limit: float, step: float = 0.05): + """`predicate()`'s first true value inside `limit` seconds, else None.""" + end = time.monotonic() + limit + while True: + value = predicate() + if value: + return value + if time.monotonic() >= end: + return None + time.sleep(step) + + +def _release(fifo: Path, limit: float) -> bool: + """Let go the call the shim holds on `fifo` (its `hold` arm, which reads + the FIFO to its end): open it for writing and close it, inside `limit` + seconds. True where a call was held and is let go; False where no call + held the FIFO in that time. A plain `open(fifo, "w")` waits until a + reader opens the FIFO, which is for ever where the engine never made the + call the arm names, or the call died before it reached the FIFO; that + open hung test 10's case 6 in lane 1's CI rounds 3, 4 and 5 (#165 + 6810924785). So the open is `O_NONBLOCK`, which fails at once with ENXIO + while no reader holds the FIFO, and it is tried again until `limit`.""" + def once() -> bool: + try: + fd = os.open(fifo, os.O_WRONLY | os.O_NONBLOCK) + except OSError as exc: + if exc.errno == errno.ENXIO: + return False + raise + os.close(fd) + return True + return bool(_until(once, limit)) + + +def _held(fifo: Path, limit: float): + """`fifo` open for writing once a call is held on it, inside `limit` + seconds, else None: the open `_release` makes, `O_NONBLOCK`, which fails + with ENXIO while no reader holds the FIFO, kept open where `_release` + closes it at once, as `hold_point` keeps it (T243's, in + `tests/test_sql_register_order.py`). The shim's `block` holds the FIFO + open for reading, before the real `psql` under a `hold` arm and once + `psql` has returned under a `timer` arm, so the open succeeds only then; + and the call stays held until the handle is closed (T254zu).""" + def once(): + try: + return os.fdopen(os.open(fifo, os.O_WRONLY | os.O_NONBLOCK), "wb") + except OSError as exc: + if exc.errno == errno.ENXIO: + return None + raise + return _until(once, limit) + + +def _utc(epoch: float) -> str: + return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(epoch)) + + +def _epoch(utc: str) -> int: + return calendar.timegm(time.strptime(utc, "%Y-%m-%dT%H:%M:%SZ")) + + +# ---------------------------------------------------------------- the runner + +class Hook: + """One run of the hook: its exit, its two streams, and the runner's times + (monotonic, from `t0`, the runner's exec): the exit, each stream's EOF, + and whether the runner's timer stopped it.""" + + def __init__(self, code, out, err, t0, t_exit, eof, killed, pgid): + self.code, self.out, self.err = code, out, err + self.t0, self.t_exit, self.eof, self.killed, self.pgid = t0, t_exit, eof, killed, pgid + + @property + def text(self) -> str: + return self.out + self.err + + def __repr__(self) -> str: + return (f"<hook exit {self.code} after {self.t_exit - self.t0:.2f} s" + f"{' (stopped by the runner)' if self.killed else ''}:\n{self.text[-1500:]}>") + + +def run_hook(argv, stdin_text: str, env: dict, cwd, timeout: float = HOOK_TIMEOUT) -> Hook: + """THE RUNNER: Claude Code 2.1.319's way with a `UserPromptSubmit` hook, as + lane 4's hook probe found it (the test plan's AT-F6 fixture). It starts + the hook as the leader of a process group of its own, feeds its JSON on + stdin, and at `timeout` sends `SIGTERM` to that whole group; it never + waits on a pipe a child inherited, only for the hook's own exit, and it + logs when each stream reached EOF. Every wait is bounded: 10 s after the + `SIGTERM`, then `SIGKILL` to the group and 10 s more, and a hook that + outlives that is a `TimeoutExpired`, never a wait without end.""" + t0 = time.monotonic() + proc = subprocess.Popen(argv, stdin=subprocess.PIPE, stdout=subprocess.PIPE, + stderr=subprocess.PIPE, cwd=str(cwd), env=env, + start_new_session=True) + chunks = {"out": [], "err": []} + eof = {} + + def read(name, stream): + fd = stream.fileno() + while True: + try: + data = os.read(fd, 65536) + except OSError: + data = b"" + if not data: + eof[name] = time.monotonic() + return + chunks[name].append(data) + + readers = [threading.Thread(target=read, args=(name, stream), daemon=True) + for name, stream in (("out", proc.stdout), ("err", proc.stderr))] + for reader in readers: + reader.start() + try: + proc.stdin.write(stdin_text.encode("utf-8")) + proc.stdin.close() + except OSError: + pass + killed = False + try: + code = proc.wait(timeout) + except subprocess.TimeoutExpired: + killed = True + try: + os.killpg(proc.pid, signal.SIGTERM) + except ProcessLookupError: + pass + try: + code = proc.wait(10) + except subprocess.TimeoutExpired: + os.killpg(proc.pid, signal.SIGKILL) + code = proc.wait(10) + t_exit = time.monotonic() + for reader in readers: + reader.join(timeout=1.0) + text = {k: b"".join(v).decode("utf-8", "replace") for k, v in chunks.items()} + return Hook(code, text["out"], text["err"], t0, t_exit, eof, killed, proc.pid) + + +# ---------------------------------------------------------------- the record + +def read_record(path: Path) -> dict: + """The record's `key=value` lines, the first of each key winning as the + guard reads it (`guard_bind_load`), and the `note=` lines in a list.""" + record = {"note": []} + try: + text = path.read_text(encoding="utf-8") + except OSError: + return {} + for line in text.splitlines(): + if "=" not in line: + continue + key, value = line.split("=", 1) + if key == "note": + record["note"].append(value) + else: + record.setdefault(key, value) + return record + + +def write_record(path: Path, lines) -> None: + """A record written as every writer of it writes one: a temporary file in + `offers/` at 0600, then a rename (contract section 1).""" + path.parent.mkdir(parents=True, exist_ok=True, mode=0o700) + tmp = path.parent / f".{path.name}.t214" + tmp.write_text("".join(f"{line}\n" for line in lines), encoding="utf-8") + tmp.chmod(0o600) + os.replace(tmp, path) + + +# ---------------------------------------------------------------- the estate + +def _row(lane: str, cell: str, state: str) -> str: + return (f"| `{lane}` | harness `{cell}` | {HOST} / test / brett | 2026-10-01T00:00Z | none " + f"| handoffs/{lane}.md | {state} {DOT} 2026-10-01T02:00:00Z {DOT} working |") + + +def register_text(rows) -> str: + return "\n".join(REGISTER_HEADER + list(rows) + [""]) + + +#: THE ESTATE'S STATE HOME: SHORT, AND OUTSIDE THE TEMPORARY ROOT. The +#: service's one socket is `${XDG_STATE_HOME}/openRepoTools/run/register.sock` +#: (lane 5's socket contract d8, section 2.1): `_Listener` binds it, `serve` +#: binds it, and the client connects to it. `sun_path` holds 107 bytes on +#: Linux and 103 on macOS, and the contract's client and `serve` refuse a +#: path over 103 bytes (`path-too-long`). Under `tmp_path` the path followed +#: the temporary root: on the runner, `run.sh`'s basetemp put it at about 147 +#: bytes, and both of `_Listener`'s cases failed with `OSError: AF_UNIX path +#: too long` (lane 1's verify-r5-c2b, CI run 43140203269); every service case +#: would meet `path-too-long` once T512 lands (line AN14). So each estate's +#: `XDG_STATE_HOME` is a `mkdtemp` of its own in `/tmp`, as `tests/pgcluster.py` +#: makes its socket directory: `/tmp/l2g-` and mkdtemp's 8 characters, 17 +#: bytes, which puts the socket at 49 whatever `TMPDIR` or `--basetemp` is. +#: The estate removes it at its close (`Estate.close`), and one `atexit` +#: handler removes any that an estate which failed to finish left. +STATE_PARENT = "/tmp" +STATE_PREFIX = "l2g-" +#: The contract's bound on the socket's path, in bytes (section 2.1). +SOCKET_MAX = 103 +#: Every state home made in this process, for the `atexit` handler. +_STATE_HOMES: list = [] + + +def _remove_state_homes() -> None: + for home in _STATE_HOMES: + shutil.rmtree(home, ignore_errors=True) + + +def _state_home() -> Path: + """A new state home (`STATE_PARENT`, `STATE_PREFIX`), 0700 as `mkdtemp` + makes it, whose socket path is within `SOCKET_MAX`.""" + if not _STATE_HOMES: + atexit.register(_remove_state_homes) + home = Path(tempfile.mkdtemp(prefix=STATE_PREFIX, dir=STATE_PARENT)) + _STATE_HOMES.append(home) + sock = home / "openRepoTools" / "run" / "register.sock" + assert len(os.fsencode(str(sock))) <= SOCKET_MAX, \ + f"the service's socket path {sock} is over {SOCKET_MAX} bytes" + return home + + +class _Spare(list): + """THE CASE'S OWN PIDS, `Estate.spare`, EACH WITH ITS START TIME READ AS + IT IS ADDED, in `starts` (T237zzg; lane 1's NIT 1, #165 6892179926): + the teardown signals each only while it is still that process, so a pid + reaped meanwhile (`_Service.stop`) is never taken from its next owner. A + pid already gone when it is added has no start, and only the members + that keep its number are taken (`_teardown_round`).""" + + def __init__(self): + super().__init__() + self.starts = {} + + def append(self, pid) -> None: + self.starts[pid] = _stat(pid).get("start") + super().append(pid) + + def extend(self, pids) -> None: + for pid in pids: + self.append(pid) + + def __iadd__(self, pids): + self.extend(pids) + return self + + +class Estate: + """T203c's estate with the guard's offer for this session: the window is + `FROM`, whose row names the session; the session is named `TO`, whose row + ends on another session; and the stand-ins above in `<root>/ctl`. Its + `XDG_STATE_HOME` is a short directory of its own in `/tmp`, never under + `root` (`_state_home`), so the service's socket path is 49 bytes.""" + + def __init__(self, root: Path, *, to=TO, to_row=True, guard=GUARD, path=None): + self.root = root + self.sid = str(uuid.uuid4()) + self.other = str(uuid.uuid4()) + self.to = to + self.guard = guard + #: The `lanes-index` the estate's own calls run (`_index`, `_Service`): + #: the checkout's, or on primary the flipped copy beside the guard. + self.index = REPO / "lanes-index" + self.home = root / "home" + self.wip = self.home / "projects" / "wip" + self.origin = root / "origin.git" + self.bin = root / "bin" + self.ctl = root / "ctl" + for d in (self.wip.parent, root / "t", self.bin, self.ctl): + d.mkdir(parents=True, exist_ok=True) + self.state_home = _state_home() + #: Every other `XDG_STATE_HOME` its `env()` has handed out (T237zzg). + self.given_homes = [] + env = guard_strip_env(os.environ) + if path is not None: + env["PATH"] = path + env.update(HOME=str(self.home), XDG_STATE_HOME=str(self.state_home), + XDG_CONFIG_HOME=str(root / "config"), TMPDIR=str(root / "t"), + LANES_WORKSTATION=HOST, LANES_CONTAINER=CONTAINER, LANES_NO_GITHUB="1", + LANES_NO_FETCH="1", LANES_REPO=str(self.wip), LANES_LANE=FROM, + GIT_AUTHOR_NAME="t", GIT_AUTHOR_EMAIL="t@example.invalid", + GIT_COMMITTER_NAME="t", GIT_COMMITTER_EMAIL="t@example.invalid") + self.base = env + self._git(["init", "-q", "--bare", "-b", "main", str(self.origin)], cwd=root) + self._git(["clone", "-q", str(self.origin), str(self.wip)], cwd=root) + (self.wip / "lanes" / "log").mkdir(parents=True) + rows = [_row(FROM, self.sid, "LIVE")] + if to_row: + rows.append(_row(to, self.other, "PAUSED")) + self.push_register(rows, first=True) + (self.home / ".agents").mkdir() + (self.home / ".agents" / "workspace.yaml").write_text( + f"repository: {self.origin}\npath: {self.wip}\n", encoding="utf-8") + py = sys.executable + self.lane_start = _script(self.root / "stub-lane-start", _STUB_LANE_START, + PY=py, CTL=_q(self.ctl)) + self.body = _script(self.root / "stub-body", _STUB_BODY, PY=py, CTL=_q(self.ctl)) + self.edit = _script(self.root / "stub-lanes-edit", _STUB_EDIT, PY=py, + CTL=_q(self.ctl), REAL=_q(self.guard)) + self.offer = self.home / ".claude" / "lanes" / "offers" / self.sid + self.extra = {"LANES_LANE_START": str(self.lane_start), "LANES_EDIT": str(self.edit)} + self.session = guard_session(self.home, self.bin, self.wip, window=FROM, + session_id=self.sid, name=to) + self.sessions = [self.session] + self.spare = _Spare() + + def primary(self, pg) -> None: + """T254: the estate on `mode=primary` against the session cluster + (T205's `pg`), in T220's configuration form (its `Bench.config`: two + URLs naming this test's database). The register's tables come from + T227's `tmpl_imported` and its logins from T228, so a primary case + waits for both besides lane 4's and lane 5's code; the bind's own + calls go through T203's `PSQL_SHIM`, whose log the case reads. + + THE BUILD IS FLIPPED (lane 5's F2, #165 6812547449): the checkout's + `lanes-index` keeps lane 1's `RENDER_GIT_HALF = False`, so its + `load_config` refuses `mode=primary` with 78 before any request, and + no case here would reach the database. So, as the outage module's + `Estate` does (`tests/test_sql_register_outage.py:303-311` at W4a's + `bc6e00a4`), the estate runs `flipped_copy`'s `lanes-index` with + copies of `lanes-edit.sh`, `repos.tsv` and `lane-start` beside it + (the copy rule, CLI4.5:885): the guard, the stand-in `LANES_EDIT`'s + real verbs, the bind's real `lane-start` (`_real_estate`) and the + estate's own `lanes-index` calls all run that build. A case that + names its own guard keeps it. The database's switch stays at + `files` until a case brings its register to primary (`_Register`).""" + if self.guard == GUARD: + from sql_register_helpers import flipped_copy + tool = self.root / "tool" + try: + self.index = flipped_copy(REPO / "lanes-index", tool, True) + except ValueError as exc: + raise AssertionError(f"lanes-index cannot be flipped to its git half ({exc}): " + f"lane 1's RENDER_GIT_HALF (T105) has not landed, and " + f"mode=primary is refused without it") from exc + for name in ("lanes-edit.sh", "repos.tsv", "lane-start"): + if (REPO / name).exists(): + shutil.copy2(REPO / name, tool / name) + self.guard = tool / "lanes-edit.sh" + self.edit = _script(self.root / "stub-lanes-edit", _STUB_EDIT, PY=sys.executable, + CTL=_q(self.ctl), REAL=_q(self.guard)) + conf = self.root / "conf" / "lanes-index.conf" + conf.parent.mkdir(mode=0o700) + url = pg.url() + conf.write_text("\n".join([ + "mode=primary", f"register_url={url}", f"reader_url={url}", + "register_label=register-test", ""]), encoding="utf-8") + conf.chmod(0o600) + self.pg = pg + self.extra["LANES_INDEX_CONFIG"] = str(conf) + + def shim(self, arms=()) -> Path: + """T203's `PSQL_SHIM` first on `PATH`, handing calls to the cluster's + own `psql`, with `arms`; its log is `<bin>/psql-shim.log`. + + EACH ARMING BRINGS A LOST HOST BACK (T254w): a `no-reconnect` arm + fails every later call "until the test removes a second control + file" (TP:2277-2278 at a6497d00), and the shim keeps the lost call in + its state, `psql-shim.state`, past a new control file. So the state's + `lost` is dropped here, and its call counts kept. + + UNDER THE SHIM'S OWN LOCK (T254zl; lane 2's review RV22, NIT 4): the + shim reads and rewrites its state, and reads the control file, under + `psql-shim.lock`. So the drop and the new control file are written + under it too, each by a temporary file and a rename, as the shim + writes its state. A call still in flight at the re-arming, such as a + detached render's, then cannot write `lost` back over the drop, nor + read either file half written. The wait for the lock is bounded, as + every wait here is: the shim holds it only for its bookkeeping.""" + import fcntl + shim = _script(self.bin / "psql", PSQL_SHIM) + state = self.bin / PSQL_SHIM_STATE + control = self.bin / PSQL_SHIM_CONTROL + + def put(path: Path, text: str) -> None: + tmp = path.with_name(path.name + ".t254zl") + tmp.write_text(text, encoding="utf-8") + os.replace(tmp, path) + + with open(self.bin / PSQL_SHIM_LOCK, "a", encoding="utf-8") as lock: + def take() -> bool: + try: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError: + return False + return True + + assert _until(take, SHIM_LOCK_S), \ + f"the shim's lock {lock.name} was held for {SHIM_LOCK_S} s" + if state.exists(): + held = json.loads(state.read_text(encoding="utf-8") or "{}") + if held.pop("lost", None) is not None: + put(state, json.dumps(held)) + put(control, json.dumps({"psql": self.pg.cluster.tool("psql"), "arms": list(arms)})) + return shim + + def shim_calls(self) -> list: + """The shim's request calls (its `--version` probes left out).""" + path = self.bin / PSQL_SHIM_LOG + if not path.exists(): + return [] + calls = [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() + if line.strip()] + return [c for c in calls if "kind" not in c] + + def _git(self, argv, cwd) -> str: + return subprocess.run(["git", *argv], cwd=str(cwd), env=self.base, check=True, + capture_output=True, text=True, timeout=60).stdout + + def push_register(self, rows, first=False) -> None: + """The register pushed to the bare origin. Once this estate has put its + register in the SQL store (`_seed_primary`, T254q), each line that + changed goes there too, one `write` entry per line (`_Register.replace`), + so a case's stand-in for what a bind leaves reads the same on primary + as in files mode (case 4).""" + text = register_text(rows) + (self.wip / "lanes" / "LANES.md").write_text(text, encoding="utf-8") + if first: + (self.wip / "lanes" / "log" / "README.md").write_text("logs.\n", encoding="utf-8") + self._git(["add", "-A"], self.wip) + self._git(["commit", "-q", "-m", "register"], self.wip) + self._git(["push", "-q", "origin", "main"], self.wip) + sql = getattr(self, "sql_register", None) + if sql is not None: + path = "lanes/LANES.md" + old, new = sql.files[path].split("\n"), text.split("\n") + assert len(old) == len(new), \ + f"the SQL store's register has {len(old)} lines and the new one {len(new)}" + for line_no, (was, now) in enumerate(zip(old, new), 1): + if was != now: + sql.replace(path, line_no, now) + + def origin_head(self) -> str: + return self._git(["rev-parse", "main"], self.origin).strip() + + def set(self, name: str, value="") -> None: + (self.ctl / name).write_text(str(value), encoding="utf-8") + + def env(self, **extra) -> dict: + """The estate's environment, `extra` over `self.extra`. Another + `XDG_STATE_HOME` it hands out, through `self.extra` (T254zg's + `_state_home_with_no_service`) or `extra` (`[start-fails]`), is + noted, so that the teardown sweeps it too (T237zzg; `swept_homes`).""" + merged = dict(self.extra) + merged.update(extra) + env = self.session.env(self.base, **merged) + home = env.get("XDG_STATE_HOME") + if home and home != str(self.state_home) and home not in self.given_homes: + self.given_homes.append(home) + return env + + def swept_homes(self) -> list: + """THE STATE HOMES THE TEARDOWN SWEEPS AND REMOVES (T237zzg; lane 1's + SHOULD 1, #165 6892179926): its own, and each other one its commands + were given (`env()`, or `self.extra` as it stands) that lies under + its own `root`, and so is this estate's alone. One given elsewhere + is printed and is neither swept nor removed, since it may be another + estate's or another lane's (rule 4).""" + root = os.path.realpath(self.root) + homes = [self.state_home] + given = list(self.given_homes) + if self.extra.get("XDG_STATE_HOME"): + given.append(self.extra["XDG_STATE_HOME"]) + for home in dict.fromkeys(given): + if home == str(self.state_home): + continue + if os.path.commonpath([os.path.realpath(home), root]) == root: + homes.append(home) + else: + print(f"Estate.close: XDG_STATE_HOME {home} is not under the estate's root " + f"{self.root}, so it is neither swept nor removed") + return homes + + def hook(self, prompt="hello", timeout=HOOK_TIMEOUT, **extra) -> Hook: + """One guard run. On primary, the register is put in the SQL store + before the first one (`_seed_primary`, T254r), so a case that reads + without making an offer, rows (a) and (b) among them, reads it there.""" + if getattr(self, "pg", None) is not None: + _seed_primary(self) + return run_hook(["bash", str(self.guard), "guard"], + self.session.hook_input(prompt=prompt), self.env(**extra), + self.session.cwd, timeout) + + def make_offer(self) -> dict: + """The guard's first prompt makes the offer (`guard_offer`). On + primary, the register the estate pushed is put in the SQL store first + (`_seed_primary`, T254q), where the case has not put it there itself.""" + if getattr(self, "pg", None) is not None: + _seed_primary(self) + hook = self.hook("hello") + record = read_record(self.offer) + assert hook.code == 2 and OFFER in hook.text and record.get("mode") == "name-drift", \ + f"the guard made no offer for this estate: {record}\n{hook!r}" + assert record.get("from") == FROM and record.get("to") == self.to, record + return record + + def answer_2(self, **extra) -> Hook: + """The person's `2`; the case's first assertion is always that the hook + printed "BINDING" and exited 2, which today's in-hook bind never does. + The line names the lane this estate's offer binds, `self.to` (T214l): + `repoA-5` for the bind-failed test's `new` kind, which `BINDING`, on + `TO`, never matched (lane 5, #165 6837268276).""" + hook = self.hook("2", **extra) + binding = f"BINDING: this window is now named {self.to}" + assert not hook.killed and hook.code == 2 and binding in hook.err, \ + f"answer 2 did not exit 2 with BINDING: {hook!r}" + return hook + + def record(self) -> dict: + return read_record(self.offer) + + def outer(self, limit=10.0) -> dict: + """The record once the outer has rewritten it with its `pid`.""" + record = _until(lambda: (lambda r: r if r.get("pid") else None)(self.record()), limit) + assert record, f"no outer wrote its pid into the record: {self.record()}" + return record + + def ended(self, limit=30.0) -> dict: + """The record once the outer has written an outcome.""" + record = _until(lambda: (lambda r: r if r.get("mode") in ("bound", "bind-failed") + else None)(self.record()), limit, 0.1) + assert record, f"the bind wrote no outcome in {limit} s: {self.record()}" + return record + + def log(self, name: str) -> list: + path = self.ctl / name + if not path.exists(): + return [] + return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() + if line.strip()] + + def starts(self) -> list: + return [e for e in self.log("lane-start.log") if e["event"] == "start"] + + def release(self) -> None: + self.set("release") + + def swap_window(self, window: str, name: str): + """The window renamed to `window`: the stand-in answers `#W` with its + name, so the session's live process is replaced by one in a window of + that name (T203c's `guard_session`), with the same session id.""" + for session in self.sessions: + session.close() + self.session = guard_session(self.home, self.bin, self.wip, window=window, + session_id=self.sid, name=name) + self.sessions.append(self.session) + return self.session + + def close(self) -> None: + """Every process the bind left, ended: the case's own (`spare`), the + record's outer (`_record_pid`: only a value a bind's pid can take), + the stand-ins' logged pids, and the members of each one's session and + group; never this process, its group or its session (T214u). + + AND EVERY PROCESS OF THIS ESTATE (T237zzd), whoever started it: each + live process whose environment's `XDG_STATE_HOME` is this estate's + own state home (`_homed`), the estate's services among them and an + outer a case held and never released, with the members of the session + and group it leads. So a service a client of the case started, which + no case puts in `spare`, ends with its estate even where the case + fails first, and no process of the estate is left to start one once + the state home is gone. A service left running outlived its estate, + and a later case's look for "another service" saw it: merge 151's and + 158's c2 runs, `[namespace|boot]`'s four leftover pids. + + - The selector is the state home alone, which only this estate's + `env()` passes on; never the path of `Estate.index`, which a + files-mode estate shares with every other (`REPO/lanes-index`). + - Nothing in pytest's own session is signalled, however it was + reached (`_kill_same` prints it and leaves it). A case that runs an + estate command in pytest's session, a `subprocess.run` with + `est.env()` and no new session, leaves any process that outlives + the command to end on its own. Any service such a command starts + is in a session of its own (`register_serve_launch` starts it with + `start_new_session=True`), which the sweep takes; what it leaves in + pytest's session, such as `lane-checkout --create`'s heartbeat + `sleep 60`, starts none. + - Every target is signalled only while it has the start time read at + its scan (`_kill_same`; `_homed` reads it in the same pass). + - T237zzg (lane 1's review, #165 6892179926, and RZ-27's NITs): the + sweep also takes, and then removes, each other state home the + estate's commands were given under its root (`swept_homes`: + T254zg's and `[start-fails]`'s); each pid is signalled by the + start recorded with it (`spare` as it was added, the record's + `pidstart`, the stand-ins' logs), read now only where none was; + and a sweep that gives up fails the case, naming the estate's + processes outside pytest's session that outlived it. + - The sessions are closed first. Then the sweep is repeated, at most + `SWEEP_PASSES` times `SWEEP_STEP_S` apart, until no process of the + estate is left outside pytest's session, and only then is the + state home removed, so nothing forked meanwhile outlives it.""" + self.release() + mine = os.getsid(0) + own = {os.getpid(), os.getpgrp(), mine} + targets = {pid: self.spare.starts.get(pid) for pid in self.spare} + record = self.record() + outer = _record_pid(record) + if outer is not None: + written = record.get("pidstart", "") + targets.setdefault(outer, written if re.fullmatch(r"[0-9]+", written) + else _stat(outer).get("start")) + elif record.get("pid"): + print(f"Estate.close: the record's pid {record['pid']!r} is no bind's pid " + f"(guard_bind_pid_ok), so it is not signalled") + for entry in self.log("lane-start.log") + self.log("body.log"): + for key in ("pid", "fork", "grandchild"): + if isinstance(entry.get(key), int): + logged = entry.get("start" if key == "pid" else f"{key}_start") + targets.setdefault(entry[key], logged or _stat(entry[key]).get("start")) + homes = self.swept_homes() + targets.update(_homed(*homes)) + _teardown_round(targets, own) + for session in self.sessions: + session.close() + left = {} + for _ in range(SWEEP_PASSES): + left = {pid: start for pid, start in _homed(*homes).items() + if _stat(pid).get("sid") != mine} + if not left: + break + _teardown_round(left, own) + time.sleep(SWEEP_STEP_S) + else: + left = {pid: start for pid, start in _homed(*homes).items() + if _stat(pid).get("sid") != mine} + for home in homes: + shutil.rmtree(home, ignore_errors=True) + # A SWEEP THAT GIVES UP FAILS THE CASE (T237zzg; lane 1's NIT 2), and + # names the estate's processes outside pytest's session that outlived + # every pass, and only those: one in pytest's session is never waited on. + assert not left, (f"Estate.close: after {SWEEP_PASSES} sweeps, still live outside " + f"pytest's session in {[str(home) for home in homes]}: " + f"{[(pid, _argv(pid)) for pid in sorted(left)]}") + + +@pytest.fixture +def estate(tmp_path, request): + """The estate of the module's docstring, torn down with every process its + bind left (the outer, its body, `timeout`, the stand-ins and their + children). + + ON PRIMARY, A DATABASE PER ESTATE (T254q): the first primary estate of a + case takes T205's `pg`; each later one a database of its own, cloned from + the same template and dropped at the teardown, as each estate has a bare + origin of its own in files mode, so case 9's rival reads its own register + and not the one the first bind changed. A caller that means two estates to + share one register passes `pg` (`_two_binds`).""" + made, own = [], [] + + def make(mode="files", pg=None, **kwargs) -> Estate: + if mode != "primary": + pg = None + elif pg is None: + pg = request.getfixturevalue("pg") + if any(getattr(e, "pg", None) is not None for e in made): + name = pg.cluster.new_database() + own.append((pg.cluster, name)) + pg = type(pg)(pg.cluster, name) + est = Estate(tmp_path / f"e{len(made)}", **kwargs) + made.append(est) + if pg is not None: + est.primary(pg) + return est + + yield make + # EVERY ESTATE IS CLOSED, though an earlier one's close fails (T237zzg: a + # sweep that gives up fails it), and the first failure is raised after. + failed = [] + try: + for est in made: + try: + est.close() + except Exception as exc: + failed.append(exc) + finally: + for cluster, name in own: + cluster.drop_database(name) + if failed: + raise failed[0] + + +def _sleeper() -> subprocess.Popen: + """A live process in a session of its own: the stand-in for a bind's + outer where a case writes the record itself (rows (a) to (c)).""" + return subprocess.Popen([sys.executable, "-I", "-c", "import time; time.sleep(300)"], + stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, start_new_session=True) + + +def _dead_pid() -> int: + """A pid that has exited and been reaped. The wait is bounded, as every + wait in this module is.""" + proc = subprocess.Popen([sys.executable, "-I", "-c", "pass"]) + proc.wait(30) + return proc.pid + + +def _binding(est: Estate, *, started: float, bound_s=500, bounded="yes", deadline=None, + pid=None, pidstart=None, host=HOST, container=CONTAINER, extra=()) -> list: + """A `mode=binding` record in the keys and order the hook and the outer + write it (contract sections 1 and 3), for rows (a) and (b).""" + if deadline is None: + deadline = int(started) + bound_s + 5 + lines = ["mode=binding", f"from={FROM}", f"to={est.to}", f"session={est.to}", + f"uuid={est.sid}", f"utc={_utc(started)}", "window=testsess:@1", + f"pane={GUARD_PANE}", "bind=1", f"started_utc={_utc(started)}", + f"bound_s={bound_s}", f"bounded={bounded}", f"deadline_epoch={deadline}", + f"host={host}", f"container={container}", f"out={est.offer}.bind.1.out", + "detach=setsid"] + if pid is not None: + lines.append(f"pid={pid}") + if pidstart is not None: + lines.append(f"pidstart={pidstart}") + return lines + list(extra) + + +def _timeout_argv(outer: int, sid: str): + """The `timeout` the outer bounds its body with, as `/proc` gives its + argv: a member of the session the outer leads.""" + for pid in _members("sid", outer): + argv = _argv(pid) + if argv and os.path.basename(argv[0]) == "timeout" and sid in argv: + return pid, argv + return None + + +def _renames(est: Estate, since: int = 0) -> list: + return [c for c in est.session.tmux_calls()[since:] if c and c[0] == "rename-window"] + + +# ============================================================ T214: AT-F6, phase N + +@pytest.mark.parametrize("mode", ["files", "primary"]) +def test_answer_2_exits_2_binding_before_t0_plus_1_s_and_the_runner_sees_eof(estate, mode): + """AT-F6 case 1: answer `2` exits 2 with "BINDING" before `T0 + 1 s`, + asserted at twice it (section 4's rule 2), while the stand-in `lane-start` + holds; the runner sees EOF on both pipes at once, before the stand-in + ends; the hook itself writes nothing to the register. Under the default + bound the record holds `bound_s=500`, `bounded=yes` and a + `deadline_epoch` 505 s after `started_utc`, "BINDING" says "bounded at + 500 s" and to send the work again in a minute or so, and the body runs as + `timeout -k 10 490 ... guard-bind --body <uuid>`.""" + est = estate(mode=mode) + est.set("hold", 60) + est.make_offer() + head = est.origin_head() + hook = est.answer_2() + took = hook.t_exit - hook.t0 + print(f"T214 case 1: the hook exited {took:.3f} s after T0 (bound 1 s, asserted at 2 s); " + f"EOF {max(hook.eof.values()) - hook.t_exit:+.3f} s after the exit") + assert took < 2.0, f"answer 2 exited {took:.2f} s after T0, past T0 + 2 s: {hook!r}" + assert set(hook.eof) == {"out", "err"}, f"the runner saw no EOF on {hook.eof}: {hook!r}" + assert max(hook.eof.values()) - hook.t_exit < 0.5, f"EOF came late: {hook.eof}" + assert "bounded at 500 s" in hook.err and "send your work again in a minute or so" \ + in hook.err, hook.err + assert est.origin_head() == head, "the hook's own process wrote to the register" + record = est.outer() + assert not [e for e in est.log("lane-start.log") if e["event"] == "end"], \ + "the stand-in lane-start ended before the runner's EOF was asserted" + assert record["mode"] == "binding" and record["bound_s"] == "500" \ + and record["bounded"] == "yes", record + assert int(record["deadline_epoch"]) == _epoch(record["started_utc"]) + 505, record + assert re.search(rf"pid {record['pid']}\b", hook.err), hook.err + found = _until(lambda: _timeout_argv(int(record["pid"]), est.sid), 5) + assert found, f"no timeout in the outer's session: {_members('sid', int(record['pid']))}" + argv = found[1] + assert argv[1:4] == ["-k", "10", "490"] and argv[-3:] == ["guard-bind", "--body", est.sid], argv + + +@pytest.mark.parametrize("mode", ["files", "primary"]) +def test_the_bind_child_survives_a_group_kill_and_hangup_and_ends_bound(estate, mode): + """AT-F6 case 2: the child survives a `SIGKILL` and a `SIGHUP` sent to the + hook's whole process group, and the record ends `bound`. Its `ended_utc` + less `started_utc` is recorded beside `bound_s`, never asserted (lane 4's + row 37).""" + est = estate(mode=mode) + est.set("hold", 60) + est.make_offer() + hook = est.answer_2() + record = est.outer() + for sig in (signal.SIGHUP, signal.SIGKILL): + try: + os.killpg(hook.pgid, sig) + except ProcessLookupError: + pass + assert _alive(int(record["pid"])), "the bind's outer died with the hook's group" + est.release() + record = est.ended() + assert record["mode"] == "bound" and record["rc"] == "0", record + print(f"T214 case 2: ended_utc - started_utc = " + f"{_epoch(record['ended_utc']) - _epoch(record['started_utc'])} s " + f"beside bound_s = {record['bound_s']} s") + + +@pytest.mark.parametrize("mode", ["files", "primary"]) +def test_a_prompt_mid_bind_is_not_passed_and_leaves_the_record(estate, mode): + """AT-F6 case 3: a prompt mid-bind gets "BINDING IN PROGRESS" with exit 2, + is not passed, and the record is byte for byte unchanged.""" + est = estate(mode=mode) + est.set("hold", 60) + est.make_offer() + est.answer_2() + est.outer() + before = est.offer.read_bytes() + hook = est.hook("please do the work") + assert hook.code == 2 and IN_PROGRESS in hook.err and NOT_SENT in hook.err, repr(hook) + assert est.offer.read_bytes() == before, "the prompt mid-bind changed the record" + assert len(est.starts()) == 1, "a prompt mid-bind started a second bind" + + +@pytest.mark.parametrize("mode", ["files", "primary"]) +def test_after_bound_one_moved_then_the_next_prompt_passes(estate, mode): + """AT-F6 case 4: after `bound`, one "MOVED" naming the lane and this + session (lane 5's draft 7, #165 6767031889), with the owed notes, the + record removed, and the prompt not sent; the next prompt, in the window + now named `<to>` whose row ends on this session, exits 0. The row and the + window's name are the test's stand-ins for what the real `lane-start + --bind` and the guard's rename leave.""" + est = estate(mode=mode) + est.make_offer() + est.answer_2() + record = est.ended() + assert record["mode"] == "bound", record + hook = est.hook("the next prompt") + moved = f"MOVED: this window is lane {TO}, bound to this session ({est.sid}) at " + assert hook.code == 2 and moved + record["ended_utc"] in hook.err, repr(hook) + for note in record["note"]: + assert f"still owed: {note}" in hook.err, (note, hook.err) + assert not est.offer.exists(), "MOVED left the record in place" + assert "NOT sent" in hook.err, hook.err + est.push_register([_row(FROM, est.other, "PAUSED"), _row(TO, est.sid, "LIVE")]) + est.swap_window(TO, TO) + hook = est.hook("and the one after") + assert hook.code == 0 and "MOVED" not in hook.text, repr(hook) + + +@pytest.mark.parametrize("mode", ["files", "primary"]) +def test_a_failed_bind_renames_back_keeps_the_offer_and_allows_three_attempts(estate, mode): + """AT-F6 case 5: after a stand-in failure, the why, the window renamed back + to `<from>`, the offer kept (`mode=name-drift`, `bind=k`), attempt 2 on + the next `2`; after the third failure choice 2 is no longer offered, and + a `2` typed anyway is refused with the offer kept.""" + est = estate(mode=mode) + est.set("rc", 1) + est.make_offer() + for attempt in (1, 2, 3): + hook = est.answer_2() + record = est.record() + assert record["bind"] == str(attempt) and record["mode"] in ( + "binding", "bind-failed"), record + record = est.ended() + assert record["mode"] == "bind-failed" and record["rc"] == "1", record + assert "the stand-in refuses with 1" in record["why"], record + calls = len(est.session.tmux_calls()) + hook = est.hook("after the failure") + assert hook.code == 2 and f"THE BIND TO LANE {TO} FAILED (exit 1)" in hook.err, repr(hook) + assert [c for c in _renames(est, calls) if c[-1] == FROM], \ + f"the window was not renamed back to {FROM}: {est.session.tmux_calls()[calls:]}" + record = est.record() + assert record["mode"] == "name-drift" and record["bind"] == str(attempt), record + assert record["from"] == FROM and record["to"] == TO, record + if attempt < 3: + assert KEPT in hook.err and NO_LONGER_2 not in hook.err, hook.err + else: + assert NO_LONGER_2 in hook.err, hook.err + hook = est.hook("2") + assert hook.code == 2 and NO_LONGER_2 in hook.err and BINDING not in hook.err, repr(hook) + record = est.record() + assert record["mode"] == "name-drift" and record["bind"] == "3", record + assert len(est.starts()) == 3, est.starts() + + +@pytest.mark.parametrize("mode", ["files", "primary"]) +def test_a_dead_bind_outer_answers_in_progress_while_its_session_lives_then_no_outcome( + estate, mode): + """AT-F6 case 6: the outer killed with `-9` while the stand-in holds: its + pid is dead, but the body, its `timeout` and the stand-in are still in the + session it led, so a prompt, `2` among them, gets "BINDING IN PROGRESS", + the record unchanged, and no second `guard-bind` starts. Once no process + of that session is left, the next prompt gets "no outcome" once: exit 2, + `name-drift`, `rc=unknown`, `ended_utc` the guard's time, the offer kept, + and none of the five values copied (the stand-in made no pending record); + the next `2` binds anew.""" + est = estate(mode=mode) + est.set("hold", 60) + est.make_offer() + est.answer_2() + record = est.outer() + outer = int(record["pid"]) + assert _until(lambda: _timeout_argv(outer, est.sid), 5), "no body under timeout" + _kill(outer, signal.SIGKILL) + assert _until(lambda: not _alive(outer), 5), "the outer survived kill -9" + assert _members("sid", outer), "nothing was left in the session the outer led" + before = est.offer.read_bytes() + for prompt in ("hello", "2"): + hook = est.hook(prompt) + assert hook.code == 2 and IN_PROGRESS in hook.err, (prompt, repr(hook)) + assert est.offer.read_bytes() == before, f"{prompt!r} changed the record" + assert len(est.starts()) == 1 and len(list(est.offer.parent.glob( + f"{est.sid}.bind.*.out"))) == 1, "a second guard-bind started" + est.release() + assert _until(lambda: not _members("sid", outer), 15), "the outer's session never emptied" + t_before = int(time.time()) + hook = est.hook("hello") + assert hook.code == 2 and NO_OUTCOME in hook.err, repr(hook) + record = est.record() + assert record["mode"] == "name-drift" and record["rc"] == "unknown", record + assert t_before - 1 <= _epoch(record["ended_utc"]) <= int(time.time()) + 1, record + assert record["from"] == FROM and record["to"] == TO, record + assert not [k for k in COPIES if k in record], record + est.set("rc", 0) + hook = est.answer_2() + assert est.record()["bind"] == "2", est.record() + + +@pytest.mark.parametrize("mode", ["files", "primary"]) +def test_a_reused_bind_pid_gives_no_outcome_with_no_session_test(estate, mode): + """AT-F6 case 6's last sentence: an altered `pidstart` reads as dead with + no session test, "no outcome" at once, while the outer and its session + still live.""" + est = estate(mode=mode) + est.set("hold", 60) + est.make_offer() + est.answer_2() + record = est.outer() + outer = int(record["pid"]) + lines = [line for line in est.offer.read_text(encoding="utf-8").splitlines() + if not line.startswith("pidstart=")] + write_record(est.offer, lines + [f"pidstart={int(record['pidstart']) + 7}"]) + hook = est.hook("hello") + assert hook.code == 2 and NO_OUTCOME in hook.err, repr(hook) + assert f"pid, {outer}, now belongs to another process" in hook.err, hook.err + record = est.record() + assert record["mode"] == "name-drift" and record["rc"] == "unknown", record + assert _alive(outer) and _members("sid", outer), "the outer or its session had ended" + + +@pytest.mark.parametrize("case", ["term", "ignores-term", "slow-set-row-state", + "grandchild-ignores-term", "after-137", "after-trap"]) +def test_a_bind_body_past_its_bound_ends_with_the_bounds_code_and_leaves_no_process( + estate, case): + """AT-F6 case 7, with lane 5's answers to open point 39 as lane 3 ruled them + (R47, R48): under `LANES_BIND_BOUND_S=15` the body runs under `timeout -k + 10 5`. `[term]`: the stand-in `lane-start` holding past the bound ends + `rc=124` at `timeout`'s TERM; `[ignores-term]`: a stand-in body that + ignores TERM ends `rc=137` at its KILL; `[slow-set-row-state]`: the + stand-in ends 0 at once and `set-row-state` sleeps past the bound, 124; + `[grandchild-ignores-term]`: the body's child ignores TERM and outlives + `timeout`'s 124, and the outer sweeps the group `timeout` led; + `[after-137]`: the sweep after `[ignores-term]`'s 137 with such a + grandchild; `[after-trap]`: a TERM to the outer fires its trap, which + sweeps the same way. Each ends with its `why` and "what it wrote is not + known", the outcome written inside `deadline_epoch`, and no process of the + group `timeout` led left. The body binds through no `start-record` in + either mode, so the case takes no mode id (A1). Where the stub body runs, + section 8's seam (T214o): the outer ran it, with the uuid alone, under + `timeout`, and `LANES_BIND_BODY` was unset in it.""" + est = estate() + extra = {"LANES_BIND_BOUND_S": "15"} + if case == "term": + est.set("hold", 60) + elif case == "slow-set-row-state": + est.set("edit-sleep", 60) + else: + extra["LANES_BIND_BODY"] = str(est.body) + est.set("body-sleep", 60) + if case in ("ignores-term", "after-137"): + est.set("body-ignore-term") + if case in ("grandchild-ignores-term", "after-137", "after-trap"): + est.set("body-grandchild") + est.make_offer() + est.answer_2(**extra) + record = est.outer() + outer = int(record["pid"]) + assert record["bound_s"] == "15", record + found = _until(lambda: _timeout_argv(outer, est.sid), 5) + assert found and found[1][1:4] == ["-k", "10", "5"], found + group = found[0] + if case == "after-trap": + time.sleep(1.0) + _kill(outer, signal.SIGTERM) + record = est.ended(limit=40) + expect = {"term": "124", "ignores-term": "137", "slow-set-row-state": "124", + "grandchild-ignores-term": "124", "after-137": "137", "after-trap": "143"}[case] + why = BY_SIGNAL if case == "after-trap" else BY_BOUND + assert record["mode"] == "bind-failed" and record["rc"] == expect, record + assert why in record["why"] and UNKNOWN in record["why"], record + assert _epoch(record["ended_utc"]) <= int(record["deadline_epoch"]), record + assert not _members("pgid", group), f"the group timeout led ({group}) was left running" + if "LANES_BIND_BODY" in extra: + # SECTION 8's SEAM (spec#47's draft 14, :353-357; T214o): the outer + # keeps `LANES_BIND_BODY` and runs it, with the uuid alone, in place of + # `guard-bind --body`, under its `timeout`; and the body runs with it + # unset. + body = est.log("body.log") + assert body and body[0]["argv"] == [est.sid], body + assert os.path.basename(body[0]["parent"][0]) == "timeout" \ + and body[0]["parent"][-2:] == [str(est.body), est.sid], body + assert body[0]["env"]["LANES_BIND_BODY"] is None, \ + f"LANES_BIND_BODY was not unset in the body: {body[0]['env']}" + if case == "slow-set-row-state": + assert [e for e in est.log("lanes-edit.log") if e["argv"][:1] == ["set-row-state"]], \ + "the bind's set-row-state never ran" + + +@pytest.mark.parametrize("mode", ["files", "primary"]) +def test_a_live_bind_past_its_bound_that_timeout_has_not_ended_answers_2_and_names_the_pid_to_kill( + estate, mode): + """Row (a): a `binding` record with `bounded=yes` and `bound_s=500`, its + `deadline_epoch` past, whose pid and `pidstart` are a live process's on + this host: exit 2, the record unchanged, "THE BIND HAS RUN PAST ITS 500 s + BOUND and is still running (pid <p>, started <utc>)", that its `timeout` + has not ended it and it is likely stuck on the disk or the network, and + what `kill <p>` costs.""" + est = estate(mode=mode) + holder = _sleeper() + est.spare.append(holder.pid) + started = time.time() - 600 + write_record(est.offer, _binding(est, started=started, deadline=int(started) + 505, + pid=holder.pid, pidstart=_stat(holder.pid)["start"])) + before = est.offer.read_bytes() + hook = est.hook("hello") + assert hook.code == 2, repr(hook) + assert (f"THE BIND HAS RUN PAST ITS 500 s BOUND and is still running (pid {holder.pid}, " + f"started {_utc(started)})") in hook.err, hook.err + assert "timeout` has not ended it; it is likely stuck on the disk or the network" \ + in hook.err, hook.err + assert f"`kill {holder.pid}`" in hook.err and NOT_SENT in hook.err, hook.err + assert est.offer.read_bytes() == before, "the record changed" + + +@pytest.mark.parametrize("where", ["host-files", "container-files", "host-primary", + "container-primary"]) +def test_a_binding_from_another_host_or_container_is_not_judged_by_its_pid_until_the_deadline_plus_60_s( + estate, where): + """Row (b): a `binding` record whose `host` or `container` differs from the + guard's, with a pid dead on this host: until `deadline_epoch` plus 60 s, + exit 2, the record unchanged, "A BIND OF THIS TRANSCRIPT IS RUNNING ON + <host>/<container>" and "Your prompt was NOT sent"; with `bounded=no` the + text adds that the child there may still be running and that on primary + `bind:<to>` refuses whichever bind commits second; past it, stale with no + copies: exit 2 once, `name-drift`, `rc=unknown`, and no rename.""" + est = estate(mode=where.rsplit("-", 1)[1]) + host, container = (("Elsewhere", CONTAINER) if where.startswith("host") + else (HOST, "other-box")) + dead = _dead_pid() + now = time.time() + for bounded in ("yes", "no"): + write_record(est.offer, _binding(est, started=now - 30, bounded=bounded, + deadline=int(now) + 100, pid=dead, pidstart="1", + host=host, container=container)) + before = est.offer.read_bytes() + hook = est.hook("hello") + assert hook.code == 2, repr(hook) + assert f"A BIND OF THIS TRANSCRIPT IS RUNNING ON {host}/{container}" in hook.err \ + and NOT_SENT in hook.err, hook.err + assert est.offer.read_bytes() == before, "the record changed before deadline + 60 s" + if bounded == "no": + assert "may still be running" in hook.err and f"`bind:{TO}`" in hook.err, hook.err + write_record(est.offer, _binding(est, started=now - 700, deadline=int(now) - 62, pid=dead, + pidstart="1", host=host, container=container)) + calls = len(est.session.tmux_calls()) + hook = est.hook("hello") + assert hook.code == 2 and NO_OUTCOME in hook.err, repr(hook) + record = est.record() + assert record["mode"] == "name-drift" and record["rc"] == "unknown", record + assert not [k for k in COPIES if k in record], record + assert not _renames(est, calls), f"case 10 renamed the window: {_renames(est, calls)}" + + +def test_an_unreadable_bind_record_is_dropped_with_exit_2(estate): + """Row (c): an offer file the guard cannot read, a truncated `binding` + record: exit 2 with today's text (contract section 5, case 11), the record + dropped and its `<uuid>.bind.*` files left for the next removal, so the + next prompt meets the ordinary table, which asks afresh.""" + est = estate() + est.offer.parent.mkdir(parents=True, exist_ok=True) + out = est.offer.parent / f"{est.sid}.bind.1.out" + out.write_text("an earlier attempt's output\n", encoding="utf-8") + write_record(est.offer, ["mode=binding", f"from={FROM}", "to="]) + hook = est.hook("hello") + assert hook.code == 2 and UNREADABLE in hook.err, repr(hook) + assert not est.offer.exists(), "the unreadable record was not dropped" + assert out.exists(), "case 11 removed the attempt's files" + hook = est.hook("hello") + assert hook.code == 2 and OFFER in hook.err, repr(hook) + + +#: THE STAND-IN `tmux` OF A REAL BIND (T214g): T203c's stand-in, kept beside +#: it as `tmux.t203c` and run for every call, so its log and its answers are +#: unchanged, but for one thing: this window's name follows `rename-window`, as +#: tmux's does. Answer 2 renames the window to `<to>` before the bind's child +#: runs, and the real `lane-start --no-launch --bind` then reads `#W`; T203c's +#: stand-in answers it with the name it was made with, `<from>`, a lane with +#: a row, so `lane-start` refuses with its veto 2, "this window is named +#: 'repoA-2', which is another lane the register has a row for" +#: (`lane-start:2274` at lane 5's `6050581`). +_FOLLOW_TMUX = r'''#!/bin/sh +# T214g: T203c's stand-in tmux (beside this file as tmux.t203c), with this +# window's name following rename-window, as tmux's does. +name=@NAME@ +out="$(@ORIG@ "$@")"; rc=$? +if [ "$rc" = 0 ] && [ "${1-}" = rename-window ]; then + target=""; prev=""; last="" + for a in "$@"; do + [ "$prev" = -t ] && target="$a" + prev="$a"; last="$a" + done + case "$target" in + ''|@ID@|@SESSION@:@ID@|@PANE@|@SESSION@:@ID@.@PANE@) printf '%s\n' "$last" > "$name" ;; + esac +fi +if [ "$rc" = 0 ] && [ "${1-}" = display-message ] && [ "$out" = @WINDOW@ ] && [ -f "$name" ]; then + cat "$name" + exit 0 +fi +[ -z "$out" ] || printf '%s\n' "$out" +exit "$rc" +''' + + +def _follow_renames(session) -> None: + """Put `_FOLLOW_TMUX` in front of `session`'s stand-in `tmux`, once: a + stand-in `guard_session` writes again is wrapped again.""" + tmux = Path(session.tmux) + if "T214g" in tmux.read_text(encoding="utf-8"): + return + orig = tmux.with_name("tmux.t203c") + _script(orig, tmux.read_text(encoding="utf-8")) + _, window_id, pane = re.split(r"[:.]", session.target) + words = {"NAME": tmux.with_name("tmux.window-name"), "ORIG": orig, "ID": window_id, + "SESSION": session.target.split(":", 1)[0], "PANE": pane, "WINDOW": session.window} + _script(tmux, _FOLLOW_TMUX, **{k: shlex.quote(str(v)) for k, v in words.items()}) + + +def _real_estate(estate, register=True, **kwargs) -> Estate: + """The estate with the checkout's own `lane-start` in place of the + stand-in: the bind's real `lane-start --no-launch --bind`, the copy + beside the guard on primary (`Estate.primary`), so it runs that build. + + TWO THINGS THE REAL `lane-start` NEEDS THAT THE STAND-IN DID NOT (T214g; + lane 5's CI run 43239525007, where case 17 and row (d) ended `bind-failed` + with 2 on T502's tree): + - THE LANE'S CHECKOUT. Its ladder (`lane-start:1331-1460` at `6050581`) + reads the swap record, the lane's log and `$PROJECTS_ROOT/<repo>`, and + proves a candidate only against a recorded home. This estate has no swap + record, no log line for `<to>`, no home and no `PROJECTS_ROOT` + (`GUARD_ENV_STRIP`), so it refused at `:1475`: "lane repoA-3 has no + recorded checkout and none could be PROVED, so nothing was started." + So `$HOME/projects/<repo>` is made, the ladder's default (rung 4); it + writes nothing to the register. + - THE WINDOW'S NEW NAME: the stand-in `tmux` follows the hook's rename + (`_follow_renames`), as tmux does. + + AND RULE 3'S STAMP NEEDS THE LANE'S HANDOFF (T214k): where the lane has a + row, `_handoff` commits the file that row names, so the bind's + `write-handoff --stamp` writes the stamp as it does on a real lane. A new + lane (`to_row=False`) has no handoff yet, and its `lane-start` writes no + stamp (`lane-start:4352-4356` at `6050581`). + + AND ON PRIMARY, THE REGISTER IN ITS SQL STORE (T254p): `_seed_primary`, + unless `register` is false, for a caller that seeds it later itself + (`_two_binds`). AND EACH LANE'S OWN REGISTER CHECKOUT (T254s): + `_lane_checkouts`.""" + est = estate(**kwargs) + est.extra["LANES_LANE_START"] = str(est.guard.parent / "lane-start") + est.set("edit-real") + (est.home / "projects" / est.to.rsplit("-", 1)[0]).mkdir(exist_ok=True) + _follow_renames(est.session) + if kwargs.get("to_row", True): + _handoff(est) + if kwargs.get("mode") == "primary": + _lane_checkouts(est, [FROM] + ([est.to] if kwargs.get("to_row", True) else [])) + if register and kwargs.get("mode") == "primary": + _seed_primary(est) + return est + + +def _seed_primary(est: Estate) -> None: + """Bring the primary estate's register into its SQL store (T254p), as the + service cases do (`_guard_state`): `_Register` imports the `lanes/LANES.md` + the estate pushed, cuts over and records the marker, so the switch reads + `primary` with the marker `present`. + + WHY: `Estate.primary` leaves `tmpl`'s switch at `files`. From lane 5's T507 + on (line R's merge25), the guard on `mode=primary` reads the register's + SQL store, which refuses that switch: `lanes-index register read --for + guard --prefetch` exits 69, "the register's switch is `files`, not + `primary`", and the guard refuses the prompt with 2, so no offer is made + (G-18's run A, case 17 `[primary]`, on lane 4's `pair-m33a` `afc6c67d`). + A write on primary refuses the same switch with 69 at its snapshot's + check 4 (line BD17's run e03). + + ONCE PER DATABASE: where the case, or an estate sharing its database, + already brought this `pg` to `primary`, nothing is sent. Otherwise the + `_Register` is kept as `est.sql_register`, and `Estate.push_register` + sends later changes through it (T254q). `Estate.make_offer` calls this + before the first offer, so every primary estate that makes one reads its + register there (T254q). + + AND BEFORE ANY READ (T254r): `Estate.hook` calls it before every guard + run, and `_Service` before it starts `serve`, so the cases that read + without an offer read a register at `primary` too: rows (a) and (b), the + service and read cases, and SVC-10, which measured the refusal path + (lane 5, #165 6837268276). A case that seeds its register itself does so + before its first read (`_Register`; `_guard_state`), so this finds it at + `primary` and sends nothing. The answer is kept on the estate + (`est.seeded`), so the switch is asked once per estate.""" + if getattr(est, "seeded", False): + return + out = est.pg.psql("SELECT mode FROM lanes_register.register_switch;", + check=False).stdout.split() + if not (out and out[-1] == "primary"): + est.sql_register = _Register(est) + est.seeded = True + + +def _lane_checkouts(est: Estate, lanes) -> None: + """EACH LANE'S OWN REGISTER CHECKOUT ON PRIMARY (T254s), `<W>-lanes/<lane>/`, + made by `lanes-edit.sh lane-checkout <lane> --create` (the estate's build), + as the real layout has one register checkout per lane. + + WHY: on primary, T415's `pw_checkout` asks every write for its lane's + own checkout, even under an explicit `LANES_REPO` + (`lanes-edit.sh:8578-8583` at G-18c's `050dc9b4`), while `lane-start` + makes it only under `LANES_ROUTE_WRITES=1` and its default resolution + (`lane-start:1146-1147`, `:3981-3990`). The estate names `LANES_REPO`, + so each of the bind's writes refused with 2, "lane repoA-3's own + register checkout, ... is not here, and on primary a write makes no + clone"; the session cell never ended on the bound uuid, and T503's rerun + rule could not hold (case 11; G-18c's run cL). A slice of its own, so a + later one can reverse it if lanes 3 and 4 rule that the tools should + agree instead. The clone is a fetch, so `LANES_NO_FETCH` is left out.""" + env = {k: v for k, v in est.base.items() if k != "LANES_NO_FETCH"} + for lane in lanes: + done = subprocess.run(["bash", str(est.guard), "lane-checkout", lane, "--create"], + cwd=str(est.wip), env=env, capture_output=True, text=True, + timeout=120) + assert done.returncode == 0, \ + f"lane-checkout {lane} --create exited {done.returncode}: {done.stderr}" + + +#: THE LANE'S HANDOFF (T214k), as a real lane's register holds it: the file +#: its row's handoff cell names (`_row`'s `handoffs/<lane>.md`; `lane-start` +#: reads the cell as field 7, `lane-start:4413` at `6050581`), whose head is +#: the one `lane-handoff`'s `top_block` writes (`lane-handoff:2559-2563`): the +#: lane header on line 1, the blank line that ends the header block, then the +#: resume prompt. `write-handoff --stamp` puts Rule 3's stamp immediately +#: after that blank (`lanes-edit.sh:22439`; `lane-start:4358-4361`). +DASH = chr(0x2014) +HANDOFF_HEAD = ( + "Lane: {lane} (test, session {sid}) " + DASH + " single-use resume prompt: stamp " + "RESUMED-by before acting (lane-collision-protocol rule 3)\n" + "\n" + "## RESUME PROMPT " + DASH + " PAUSED 2026-10-01T02:00:00Z (T214's estate), agent claude, " + "transcript {sid}, kind unknown\n" + "\n" + "**STATE at 2026-10-01T02:00:00Z.** Lane {lane} is paused, and the guard's answer 2 " + "resumes it.\n") + + +def _handoff(est: Estate) -> Path: + """Commit and push the lane's handoff (`HANDOFF_HEAD`) where the row for + `est.to` names it, so that `write-handoff --stamp` finds a tracked file + to stamp, as on a real lane. Without it the stamp exits 8, "lane + repoA-3's handoff is not at ..., so there is nothing to write into" + (`lanes-edit.sh:22426-22428` at `6050581`), `lane-start` goes on with the + stamp owed (`lane-start:4481-4483`), and a case passed on a path where + the stamp stopped early (G17's doubt, wave 17). It is a commit of its own + after the estate's first, so the estate every other case builds is + unchanged; an untracked file would not do, since `write-handoff` refuses + a handoff git has never had (`lanes-edit.sh:22414`).""" + rel = f"handoffs/{est.to}.md" + register = (est.wip / "lanes" / "LANES.md").read_text(encoding="utf-8") + assert f"| `{est.to}` | harness `{est.other}` |" in register and f"| {rel} |" in register, \ + f"the register names no handoff {rel} for {est.to}:\n{register}" + path = est.wip / rel + path.parent.mkdir(exist_ok=True) + path.write_text(HANDOFF_HEAD.format(lane=est.to, sid=est.other), encoding="utf-8") + est._git(["add", "--", rel], est.wip) + est._git(["commit", "-q", "-m", f"handoff({est.to}): the lane's handoff", "--", rel], est.wip) + est._git(["push", "-q", "origin", "main"], est.wip) + return path + + +def _two_binds(estate, mode="files") -> tuple: + """Two sessions, in windows `FROM` and `repoA-4`, each named `TO`, both + answering `2` with the real `lane-start`: the two estates and their + outcomes. On primary, the register goes into the SQL store once both + windows' rows are pushed (`_seed_primary`), and `two` runs the same + flipped build as `one` on `one`'s database (T254q): built in files mode, + it ran the checkout's `lanes-edit.sh`, whose `lanes-index` refuses + `mode=primary` (`Estate.primary`), so it could make no offer.""" + one = _real_estate(estate, register=False, mode=mode) + two = _real_estate(estate, register=False, mode=mode, pg=getattr(one, "pg", None)) + if mode == "primary": + two.extra["LANES_INDEX_CONFIG"] = one.extra["LANES_INDEX_CONFIG"] + two.home, two.wip, two.origin = one.home, one.wip, one.origin + two.offer = one.offer.parent / two.sid + two.base.update(HOME=str(one.home), LANES_REPO=str(one.wip)) + two.push_register([_row(FROM, one.sid, "LIVE"), _row("repoA-4", two.sid, "LIVE"), + _row(TO, one.other, "PAUSED")]) + if mode == "primary": + _seed_primary(one) + for session in two.sessions: + session.close() + two.session = guard_session(one.home, two.bin, one.wip, window="repoA-4", + session_id=two.sid, name=TO) + _follow_renames(two.session) + two.sessions.append(two.session) + if mode == "primary": + _lane_checkouts(two, ["repoA-4"]) + one.make_offer() + two.hook("hello") + assert read_record(two.offer).get("mode") == "name-drift", read_record(two.offer) + one.answer_2() + two.answer_2() + return one, two, [one.ended(60), two.ended(60)] + + +def test_two_sessions_binding_one_lane_in_files_mode_both_binds_land(estate): + """Row (d): two sessions answer `2` for one lane on the files-mode + fixture, and both binds land, which is what files mode does (lane 3's + ruling (a), #165 6827853480, on lane 4's check, 6827539379). Each bind + reads `binding` once on `lane-start --no-launch --bind`, before either + writes, and finds the lane free; nothing in files mode refuses the second: + only a handoff wait or a Claude resolution sets `bind_recheck` for a second + read (`lane-start:2654-2655`, `:2751` at `6050581`), and neither runs here: + the lane has no live holder to wait for, and the resolution never runs + under `--no-launch` (`:708`). So the race is one read wide, the log + carries two bindings, and the reservation stays #84's + (`lane-start:2724-2733` at `6050581`). Both records end `bound`, and the + lane's log holds two `RESUMED` lines, one for each bind. Primary keeps its + own case, case 8, `test_two_sessions_binding_one_lane_one_start_record_commits`, + where `bind:<to>` refuses whichever bind commits second. Each record's + code and notes are printed, not asserted.""" + one, two, ends = _two_binds(estate) + print(f"T214 row (d): the codes {[r.get('rc') for r in ends]}, " + f"the notes {[r.get('note') for r in ends]}") + assert [r["mode"] for r in ends] == ["bound", "bound"], ends + log = one._git(["show", f"main:lanes/log/{TO}.md"], one.origin) + assert log.count("RESUMED") == 2, log + + +@pytest.mark.parametrize("kind,code,mode", [ + (kind, code, mode) for mode in ("files", "primary") for kind in ("resume", "new") + for code in (2, 75, 3, 69)], + ids=[f"{kind}-{code}-{mode}" for mode in ("files", "primary") for kind in ("resume", "new") + for code in (2, 75, 3, 69)]) +def test_the_bind_child_records_bind_failed_with_the_code_and_binds_nothing(estate, kind, code, + mode): + """The record's code: the child runs the real `lane-start --no-launch + --bind`, for a resume and for a new lane the offer names; where + `start-record` ends with 2, 75, 3 or 69, the record ends `bind-failed` + with `rc` that code, the register holds none of the bind's lines and the + child writes no stamp. In files mode the five copies are never written. + `start-record`'s code is the `LANES_EDIT` stand-in's; it fails until lane + 4's `start-record` (L4-B9) as well as L5-A1.""" + est = _real_estate(estate, mode=mode, to=TO if kind == "resume" else "repoA-5", + to_row=kind == "resume") + est.set("start-record-rc", code) + est.make_offer() + head = est.origin_head() + est.answer_2() + record = est.ended(90) + calls = [e["argv"] for e in est.log("lanes-edit.log")] + assert ["start-record"] == [a[0] for a in calls if a[:1] == ["start-record"]][:1], \ + f"lane-start made no start-record call: {calls}" + assert record["mode"] == "bind-failed" and record["rc"] == str(code), record + assert est.origin_head() == head, "the failed bind wrote to the register or stamped" + assert not [k for k in COPIES if k in record], record + + +@pytest.mark.parametrize("mode", ["files", "primary"]) +def test_the_bind_child_reaches_tmux_through_tmux_pane(estate, mode): + """AT-F6 case 12: the child's untargeted `tmux` call reaches the stand-in + with `TMUX_PANE` set to the hook's pane and its stdin on `/dev/null`.""" + est = estate(mode=mode) + est.set("tmux") + est.make_offer() + est.answer_2() + est.ended() + start = est.starts()[0] + assert start["env"]["TMUX_PANE"] == GUARD_PANE and start["env"]["TMUX"], start + assert start["stdin"] == "/dev/null", start + assert start["tmux"] == [0, GUARD_PANE], start + assert ["display-message", "-p", "#{pane_id}"] in est.session.tmux_calls() + + +@pytest.mark.parametrize("mode", ["files", "primary"]) +def test_the_bind_child_environment_is_as_lane_4_lists_it(estate, mode): + """AT-F6 case 13: the stand-in `lane-start` sees `LANES_NO_FETCH`, + `LANES_ACT` and `LANES_EXPECT` unset, `TMUX` and `TMUX_PANE` set, + `LANES_WRITE_ID`, `LANES_WRITE_GENERATION` (R52) and + `LANE_START_HANDOFF_ANSWER` unset, and `LANES_GIT_TIMEOUT=45`, each set + in the hook's own environment. The `LANES_ACT` and `LANES_EXPECT` of the + `set-row-state` on the lane left are primary's, T254's.""" + est = estate(mode=mode) + est.make_offer() + est.answer_2(LANES_ACT="act-0@1:g", LANES_EXPECT="row:x", LANES_WRITE_ID="w-1", + LANES_WRITE_GENERATION="g-1", LANE_START_HANDOFF_ANSWER="y", + LANES_GIT_TIMEOUT="7", LANES_NO_FETCH="1") + est.ended() + env = est.starts()[0]["env"] + for key in ("LANES_NO_FETCH", "LANES_ACT", "LANES_EXPECT", "LANES_WRITE_ID", + "LANES_WRITE_GENERATION", "LANE_START_HANDOFF_ANSWER"): + assert env[key] is None, (key, env) + assert env["TMUX"] and env["TMUX_PANE"] == GUARD_PANE, env + assert env["LANES_GIT_TIMEOUT"] == "45", env + + +def test_the_hook_string_and_guard_timeout_are_unchanged(): + """AT-F6 case 14: the hook string and `GUARD_TIMEOUT` are byte for byte + unchanged (plan.md, "Governed invariants"; PC-16).""" + lines = INSTALLER.read_bytes().splitlines() + assert b"GUARD_COMMAND='~/projects/xFactory/lanes-edit.sh guard'" in lines + assert b"GUARD_TIMEOUT=5" in lines + + +@pytest.mark.parametrize("mode", ["files", "primary"]) +def test_kill_of_the_bind_outer_ends_the_record_with_the_signals_code(estate, mode): + """AT-F6 case 15: `kill <p>` on the outer mid-bind, while the stand-in + holds, ends the record with the signal's code, 143 (lane 3's point 11), + the `why` "stopped by a signal" and "what it wrote is not known".""" + est = estate(mode=mode) + est.set("hold", 60) + est.make_offer() + est.answer_2() + record = est.outer() + assert _until(lambda: est.starts(), 5), "the stand-in never started" + _kill(int(record["pid"]), signal.SIGTERM) + record = est.ended() + assert record["mode"] == "bind-failed" and record["rc"] == "143", record + assert BY_SIGNAL in record["why"] and UNKNOWN in record["why"], record + + +def _no_timeout_path(root: Path, *first: Path) -> str: + """A `PATH` that holds every tool this host has but `timeout`: each + directory in `first` as it is, then a farm of links to the tools of + `/usr/local/bin`, `/usr/bin` and `/bin`. On primary, `first` is the + engine's own directory, which the session's `PATH` holds first: the + guard's read runs `psql`, which a `PG_BIN` outside those three, as a + workstation's non-root build, holds nowhere else, and whose tools there + are wrappers that find their tree from their own path, so a link to one + runs nothing (a GitHub runner's `postgresql-16` also puts a `psql` in + `/usr/bin`, lane 1's census, #165 6807454856).""" + farm = root / "no-timeout" + farm.mkdir() + for d in ("/usr/local/bin", "/usr/bin", "/bin"): + if not os.path.isdir(d): + continue + for name in os.listdir(d): + if name == "timeout" or (farm / name).exists(): + continue + src = os.path.join(d, name) + if os.path.isfile(src) and os.access(src, os.X_OK): + (farm / name).symlink_to(src) + return os.pathsep.join([*map(str, first), str(farm)]) + + +@pytest.mark.parametrize("mode", ["files", "primary"]) +def test_a_bind_with_no_timeout_says_bounded_no_and_kill_stops_its_group_once( + estate, tmp_path, mode, request): + """AT-F6 case 16: with `timeout` hidden from `PATH` and + `LANES_BIND_BOUND_S=15`, the record says `bounded=no` and the body leads a + process group of its own, outside the outer's. A prompt after + `deadline_epoch`, while the stand-in still holds, gets exit 2, the record + unchanged, "THE BIND HAS RUN PAST ITS 15 s BOUND and is still running", + that this host has no `timeout`, so nothing stops it, what `kill <p>` + costs, and "Your prompt was NOT sent". Then `kill <p>` stops the body's + group and the outer writes the outcome.""" + engine = [request.getfixturevalue("pg_engine").bindir] if mode == "primary" else [] + est = estate(mode=mode, path=_no_timeout_path(tmp_path, *engine)) + est.set("hold", 60) + est.make_offer() + hook = est.answer_2(LANES_BIND_BOUND_S="15") + record = est.outer() + outer = int(record["pid"]) + assert record["bounded"] == "no", record + start = _until(lambda: est.starts(), 5) + assert start and start[0]["pgid"] != outer and start[0]["sid"] == outer, start + deadline = int(record["deadline_epoch"]) + assert deadline == _epoch(record["started_utc"]) + 20, record + _until(lambda: time.time() > deadline + 1, 30, 0.2) + before = est.offer.read_bytes() + hook = est.hook("hello") + assert hook.code == 2 and (f"THE BIND HAS RUN PAST ITS 15 s BOUND and is still running " + f"(pid {outer}, started {record['started_utc']})") in hook.err, \ + repr(hook) + assert "no `timeout`, so nothing stops it" in hook.err and f"`kill {outer}`" in hook.err \ + and NOT_SENT in hook.err, hook.err + assert est.offer.read_bytes() == before, "the record changed" + _kill(outer, signal.SIGTERM) + record = est.ended() + assert record["mode"] == "bind-failed" and BY_SIGNAL in record["why"], record + assert not _members("pgid", start[0]["pgid"]), "the body's group was left running" + + +#: CASE 17'S READ CALLS (T214h). TP:6164-6166 bounds the `lanes-edit.sh` +#: processes on the resume path that each make one `register read`, and Y:5443 +#: is that term of `bound_s`'s sum. Lane 3 ruled that the case counts those +#: calls only, and that `N_r` = 17 stands (#165 6827853480), on lane 4's count of +#: lane 5's 29 calls, 13 of them register reads (6827539379). A call whose verb +#: is below is not counted, by its kind; every other verb is, so a read this +#: table does not know still counts against 17: +#: - "write": the bind's writes, which Y:5440-5450 bounds as terms of their own +#: (`S`, `M` + `W`, the stamp): `act-begin`, `start-record` and +#: `write-handoff` at lane 4's T428; at lane 5's T502, Y:5523's +#: `append-session-id`, `set-row-state LIVE` and `log RESUMED`, the stamp's +#: `publish-handoff`, and `add-row` for a new lane; and the guard child's own +#: `set-row-state` on the lane left; +#: - "none": the arms that touch no register state, class "none" at Y:4898, "no +#: door, no call": the four it names, and `workspace-root`, which reads +#: `$HOME/.agents/workspace.yaml` and the checkout it names, never the +#: register (`lanes-edit.sh:21593`, `:1004` at `6050581`), and which R2B's +#: section 2, the inventory Y:4894 cites, lists as local-only; +#: - "host-local": Y:5646's host-local reads that Y:4898 does not name, which +#: lane 4 counted apart from the 13. The case prints their count beside the +#: reads: Y:4894 would give these hybrid arms a door of their own. +#: `LANES_INDEX=off` is set for the bind, so `index_nudge` returns at once +#: (`lanes-edit.sh:3855` at `6050581`), and no detached `lanes-index sync` adds +#: calls of its own after a write lands: 6 of the 29, varying with timing. +CASE_17_NOT_A_READ = { + **{verb: "write" for verb in ("act-begin", "start-record", "write-handoff", + "append-session-id", "set-row-state", "log", + "publish-handoff", "add-row")}, + **{verb: "none" for verb in ("workstation", "fetch-age", "window-session", + "transcript-holders", "workspace-root")}, + **{verb: "host-local" for verb in ("live-holder", "lane-holders", "idle-holders", + "restart-intent")}, +} + + +@pytest.mark.parametrize("mode", ["files", "primary"]) +def test_the_bind_resume_path_makes_at_most_n_r_read_calls(estate, mode): + """AT-F6 case 17: a counting `LANES_EDIT` stand-in sees at most `N_r` = 17 + read calls on the real `lane-start --no-launch --bind`'s resume path, each + a `lanes-edit.sh` process that makes one `register read`; the test fails + where `N_r` must grow (lane 4's section, "The record, and its liveness + test"). It counts the read calls only (`CASE_17_NOT_A_READ`), with + `LANES_INDEX=off`, as lane 3 ruled (#165 6827853480).""" + est = _real_estate(estate, mode=mode) + est.extra["LANES_INDEX"] = "off" + est.make_offer() + est.answer_2() + record = est.ended(90) + calls = [e["argv"] for e in est.log("lanes-edit.log")] + kinds = [CASE_17_NOT_A_READ.get(a[0] if a else "", "read") for a in calls] + reads = [a[:1] for a, kind in zip(calls, kinds) if kind == "read"] + print(f"T214 case 17: {len(reads)} read calls of {len(calls)} lanes-edit.sh calls on the " + f"resume path, {kinds.count('host-local')} more host-local; the reads: {reads}; " + f"every call: {[(a[:1], kind) for a, kind in zip(calls, kinds)]}") + assert record["mode"] == "bound", record + assert 0 < len(reads) <= 17, reads + + +def _record_with(est: Estate, keys) -> None: + """A `binding` record as the hook leaves it before the outer's start, with + T507's keys `c`, `n_a` and `w_s_ms` as the hook copies them from + `.head` (contract section 3).""" + lines = _binding(est, started=time.time(), bound_s=500) + lines = [line for line in lines if not line.startswith(("pid=", "pidstart="))] + write_record(est.offer, lines + [f"{k}={v}" for k, v in keys.items()]) + + +#: Case 22's configurations: `c`, `n_a` and `w_s_ms` (300, or +#: `register_rtt_ms` + 200 where it is over 100, with the service's socket; +#: 0 without), and the `bound_s` each gives (Y:5459, Y:5462; contract +#: section 4). +#: +#: THE 540 s BAND (T214m; the follow-up's commit 24, Z3, from Codex's +#: re-review of spec#47 at `746e931c`, its SHOULD 8; tasks:2008, TP:6409, +#: map row 442): with one address and `c` = 3, `w_s_ms` 473 gives 530 s and +#: 474 gives 540 s, (437000 + 84000 + 19 * w_s_ms + 9999) // 10000 * 10, so +#: a bound clamped to 530 fails `[c3-w474]` (`bind-record.md` section 4 at +#: draft 13 `cd578400`). The two ids are lane 3's names from that fold. +#: +#: THE 510 s BAND AT `c` = 2 (T214p; Codex's r8 of spec#17 at commit 25 +#: `d1a66b2e`, its BLOCKING: `register-cli.md` draft 4.31's K12, :303, gives +#: 510 s at `c` = 2 where `w_s_ms` passes 368; lane 3's fix for its commit +#: 26, #165 6882323446, at TP:6258-6265 and :6408-6409, tasks:2008 and map +#: row 442; lane 2 confirmed it, 6882513333): with one address and `c` = 2, +#: `w_s_ms` 368 gives 500 s and 369 gives 510 s, +#: (437000 + 56000 + 19 * w_s_ms + 9999) // 10000 * 10, so a bound clamped +#: to 500 at `c` = 2 fails `[c2-w369]`. The two ids are lane 3's names, on +#: the `[c3-w473]` pattern. +BOUND_CASES = { + "c2": ({"c": 2, "n_a": 1, "w_s_ms": 0}, 500), + "c3": ({"c": 3, "n_a": 1, "w_s_ms": 0}, 530), + "c2-socket": ({"c": 2, "n_a": 1, "w_s_ms": 300}, 500), + "c3-socket": ({"c": 3, "n_a": 1, "w_s_ms": 300}, 530), + "a2-c2": ({"c": 2, "n_a": 2, "w_s_ms": 0}, 550), + "a2-c3": ({"c": 3, "n_a": 2, "w_s_ms": 0}, 610), + "a2-c2-socket": ({"c": 2, "n_a": 2, "w_s_ms": 300}, 560), + "a2-c3-socket": ({"c": 3, "n_a": 2, "w_s_ms": 300}, 620), + "c2-rtt120": ({"c": 2, "n_a": 1, "w_s_ms": 320}, 500), + "c3-rtt270": ({"c": 3, "n_a": 1, "w_s_ms": 470}, 530), + "c3-w473": ({"c": 3, "n_a": 1, "w_s_ms": 473}, 530), + "c3-w474": ({"c": 3, "n_a": 1, "w_s_ms": 474}, 540), + "c2-w368": ({"c": 2, "n_a": 1, "w_s_ms": 368}, 500), + "c2-w369": ({"c": 2, "n_a": 1, "w_s_ms": 369}, 510), +} + +#: Case 22's `[answer-2]`: the contract stub's constants line as T207 writes +#: it (section 2.4's defaults, `sql_register_helpers.py`'s `_CONTRACT_STUB`), +#: and the line this case's own copy of the stub carries instead, so that its +#: `.head` gives `c=3`, `n_a=2` and `w_s_ms=300`: `BOUND_CASES["a2-c3-socket"]`, +#: 620 s. A record missing any one of the three gives another bound: 560 +#: without `c` (`"a2-c2-socket"`), 530 without `n_a` (`"c3-socket"`) and 610 +#: without `w_s_ms` (`"a2-c3"`). +ANSWER_2 = "answer-2" +STUB_HEAD_LINE = "C, N_A, W_S_MS, SCHEMA = 2, 1, 0, 1" +ANSWER_2_HEAD_LINE = "C, N_A, W_S_MS, SCHEMA = 3, 2, 300, 1" + + +def _bound_through_answer_2_on_the_stub(estate, tmp_path) -> None: + """Case 22's `[answer-2]`: the contract's stub `lanes-index` (T207), its + register the estate's own `lanes/LANES.md`, with `lanes-edit.sh`, + `repos.tsv` and `lane-start` copied beside it and a configuration naming + the store, as `test_the_guard_maps_69_75_and_3_to_2` does, so the guard + reads the register through the stub and the stub's `.head` (form 2). The + stand-in `lane-start` holds, so the record is read at `mode=binding`.""" + code = tmp_path / "code" + code.mkdir() + for name in ("lanes-edit.sh", "repos.tsv", "lane-start"): + shutil.copy2(REPO / name, code / name) + est = estate(guard=code / "lanes-edit.sh") + stub = contract_stub(code, register={ + "lanes/LANES.md": (est.wip / "lanes" / "LANES.md").read_text(encoding="utf-8")}) + text, made = re.subn(re.escape(STUB_HEAD_LINE), ANSWER_2_HEAD_LINE, + stub.read_text(encoding="utf-8")) + assert made == 1, f"the contract stub's constants line was replaced {made} times, not once" + stub.write_text(text, encoding="utf-8") + conf = tmp_path / "lanes-index.conf" + conf.write_text(f"register_url=postgresql:///register?host={tmp_path}/sock\n", + encoding="utf-8") + est.extra["LANES_INDEX_CONFIG"] = str(conf) + est.set("hold", 60) + est.make_offer() + est.answer_2() + record = est.outer() + assert record["mode"] == "binding", record + assert (record.get("c"), record.get("n_a"), record.get("w_s_ms")) == ("3", "2", "300"), \ + f"the record does not hold .head's c=3, n_a=2 and w_s_ms=300: {record}" + assert record["bound_s"] == "620", record + assert int(record["deadline_epoch"]) == _epoch(record["started_utc"]) + 625, record + + +@pytest.mark.parametrize("configuration", sorted(BOUND_CASES) + [ANSWER_2]) +def test_guard_bind_computes_bound_s_from_c_n_a_and_the_service(estate, tmp_path, configuration): + """AT-F6 case 22: `bound_s` as `guard-bind` computes it from the record's + `c`, `n_a` and `w_s_ms`, which the hook copies from `.head` (R05: it + reads no configuration), with a stand-in body that exits 0: each record's + `deadline_epoch` is its start plus `bound_s` plus 5 s, and its body runs + under `timeout -k 10` at `bound_s` - 10. + + `[answer-2]` writes no record of its own: it reaches `guard-bind` through + answer 2 on the contract stub (T207), its `.head` set to `c=3`, `n_a=2` + and `w_s_ms=300`, and the record at `mode=binding` holds the three as + `.head` gives them, with `bound_s=620` and a `deadline_epoch` 625 s after + `started_utc`. It fails until L5-A3 (lane 5's T507), which copies them.""" + if configuration == ANSWER_2: + _bound_through_answer_2_on_the_stub(estate, tmp_path) + return + keys, bound = BOUND_CASES[configuration] + est = estate() + _record_with(est, keys) + proc = subprocess.run(["bash", str(GUARD), "guard-bind", est.sid], capture_output=True, + text=True, env=est.env(LANES_BIND_BODY=str(est.body)), + cwd=str(est.wip), timeout=60) + record = est.record() + assert proc.returncode == 0 and record.get("mode") == "bound", \ + f"guard-bind {proc.returncode}: {record}\n{proc.stdout}{proc.stderr}" + assert record["bound_s"] == str(bound), (configuration, record) + assert int(record["deadline_epoch"]) == _epoch(record["started_utc"]) + bound + 5, record + body = est.log("body.log") + assert body and os.path.basename(body[0]["parent"][0]) == "timeout", body + assert body[0]["parent"][1:4] == ["-k", "10", str(bound - 10)], body + + +@pytest.mark.parametrize("mode", ["files", "primary"]) +def test_answer_2_survives_a_group_sigterm_at_the_hooks_timeout(estate, mode): + """Lane 4's row 34, answer 2 killed partway: a stand-in `lane-start` that + takes 10.5 s, today's measured bind, and forks a `( ... & )` child as + `index_nudge` does. Under the runner's group SIGTERM at 5 s the detached + form's hook has exited 2 before the timer, and its child completes, the + record ending `bound`. The body ended on its own, so the outer sweeps + nothing: the forked child is still alive after the outcome.""" + est = estate(mode=mode) + est.set("sleep", 10.5) + est.set("fork", 40) + est.make_offer() + hook = est.answer_2() + assert hook.t_exit - hook.t0 < HOOK_TIMEOUT, repr(hook) + _until(lambda: time.monotonic() - hook.t0 >= HOOK_TIMEOUT, 6) + try: + os.killpg(hook.pgid, signal.SIGTERM) + except ProcessLookupError: + pass + record = est.ended(30) + assert record["mode"] == "bound" and record["rc"] == "0", record + fork = est.starts()[0]["fork"] + est.spare.append(fork) + assert _alive(fork), "the body's own exit was followed by a sweep of its group" + + +@pytest.mark.parametrize("mode", ["files", "primary"]) +def test_a_failed_bind_can_be_answered_again(estate, mode): + """Lane 4's row 35, a failed bind answered again: after the stand-in fails + once, the window is renamed back to `<from>`, the offer kept, and the next + `2` starts attempt 2.""" + est = estate(mode=mode) + est.set("rc", 1) + est.make_offer() + est.answer_2() + est.ended() + calls = len(est.session.tmux_calls()) + hook = est.hook("hello") + assert hook.code == 2 and KEPT in hook.err, repr(hook) + assert [c for c in _renames(est, calls) if c[-1] == FROM], est.session.tmux_calls()[calls:] + assert est.record()["mode"] == "name-drift", est.record() + est.set("rc", 0) + est.answer_2() + assert est.record()["bind"] == "2", est.record() + assert _until(lambda: len(est.starts()) == 2, 10), f"attempt 2 never ran: {est.starts()}" + + +def _pid_start_of() -> str: + """`pid_start_of` as `lanes-edit.sh` defines it: self-contained on purpose, + so a test can take the function as it stands (its own comment).""" + text = GUARD.read_text(encoding="utf-8") + found = re.search(r"^pid_start_of\(\) \{.*?^\}\n", text, re.S | re.M) + assert found, "lanes-edit.sh defines no pid_start_of (lane 5's T502, L5-A1)" + return found.group(0) + + +@pytest.mark.parametrize("case", ["live", "dead", "reused", "unreadable"]) +def test_pid_start_of_answers_live_dead_and_unreadable(tmp_path, case): + """Lane 5's (A5; R49): `pid_start_of <pid>` exits 0 for a live pid, + printing its start token, field 22 of `/proc/<pid>/stat`; 1 for one not + live; and 2 where the start cannot be read or the argument is no + well-formed pid, which every caller reads as live. `[reused]`: a live pid + prints its own token, not the one a record holds for an earlier process + of that number, so the caller reads it as not live.""" + function = _pid_start_of() + script = tmp_path / "pso.sh" + script.write_text(function + 'pid_start_of "$1"\n', encoding="utf-8") + + def ask(arg): + done = subprocess.run(["bash", "--noprofile", "--norc", str(script), str(arg)], + capture_output=True, text=True, timeout=30, + env={"PATH": os.environ.get("PATH", os.defpath)}) + return done.returncode, done.stdout.strip() + + if case in ("live", "reused"): + holder = _sleeper() + try: + code, token = ask(holder.pid) + assert code == 0 and token == _stat(holder.pid)["start"], (code, token) + if case == "reused": + assert token != str(int(token) + 7) + finally: + holder.kill() + holder.wait(10) + elif case == "dead": + assert ask(_dead_pid())[0] == 1 + else: + for arg in ("", "0", "007", "12a", "12345678901"): + assert ask(arg)[0] == 2, arg + + +def test_the_post_bind_refill_is_one_register_read_and_never_git(estate, tmp_path): + """Lane 5's (A5; S36-C1): after `bound`, the refill is form 1, `register + read --prefetch --cache <file> --files register,aliases`, with a reader's + row, never `--for guard`, and no `git` call. On primary through the + contract's stub `lanes-index` (T207), beside a copy of `lanes-edit.sh` + (the copy rule, CLI4.5:885), with a `git` that logs its calls. The stub's + register is the estate's own `lanes/LANES.md`, as `[answer-2]`'s is: on + primary the guard reads the register from the prefetch's `.register`, and + a register with no `lanes/LANES.md` is a failed read there (T505), which + would end the hook 2 at its text check before any offer. The refill's + filter leaves out every `--for` call: the two hooks' own form-2 reads, + `register read --for guard --prefetch`, at the offer's prompt and the + answer's, are no refill (lane 5, #165 6809022654). A refill sent with + `--for guard` is then no refill either, and the count of one refuses it. + Fails until L5-A3 (lane 5's T507).""" + code = tmp_path / "code" + code.mkdir() + for name in ("lanes-edit.sh", "repos.tsv", "lane-start"): + shutil.copy2(REPO / name, code / name) + est = estate(guard=code / "lanes-edit.sh") + stub = contract_stub(code, register={ + "lanes/LANES.md": (est.wip / "lanes" / "LANES.md").read_text(encoding="utf-8")}) + real_git = shutil.which("git") + git_log = est.ctl / "git.log" + _script(est.bin / "git", "#!/bin/sh\nprintf '%s %s\\n' \"$(date +%s.%N)\" \"$*\" >> @LOG@\n" + "exec @GIT@ \"$@\"\n", LOG=repr(str(git_log)), GIT=repr(real_git)) + conf = tmp_path / "lanes-index.conf" + conf.write_text(f"register_url=postgresql:///register?host={tmp_path}/sock\n", + encoding="utf-8") + est.extra["LANES_INDEX_CONFIG"] = str(conf) + est.make_offer() + est.answer_2() + end = est.ended() + assert end["mode"] == "bound", end + done_at = [e["t"] for e in est.log("lane-start.log") if e["event"] == "end"][0] + calls = [json.loads(line) for line in (code / ARGV_LOG).read_text( + encoding="utf-8").splitlines()] if (code / ARGV_LOG).exists() else [] + refills = [c for c in calls if c[:2] == ["register", "read"] and "--prefetch" in c + and "--for" not in c] + assert len(refills) == 1, f"the refill was not one register read: {calls}" + refill = refills[0] + assert "--cache" in refill and refill[refill.index("--files") + 1] == "register,aliases" \ + and "--for" not in refill, refill + logged = git_log.read_text(encoding="utf-8").splitlines() if git_log.exists() else [] + after = [line for line in logged if float(line.split(" ", 1)[0]) > done_at] + assert not after, f"git was called after lane-start's end, by the refill: {after}" + assert stub.exists() + + +# ------------------------------------------------ T214: lane 5's five of section 8 +# +# LANE 5's FIVE CASES OF `bind-record.md`'s SECTION 8 (T214n; spec#47's draft +# 13 `cd578400`; the follow-up's commit 24 `f9d6069e`, S9: tasks:2009 and +# :2013, TP:6413, map rows 610 to 614; lane 5's names, #165 6880616998; lane +# 3's Codex re-review of spec#47, #165 6880414089, S1 to S4 and S6). Each +# binds through the stand-in `lane-start` (`LANES_LANE_START`) and the real +# body, so the body makes and fills its facts file, with no `start-record` +# and no mode id (tasks:2005). Each fails until L5-A1, lane 5's T502 (its +# round 2, `12eddddf`), and waits for no other task (tasks:2013). Where a case +# needs the outer to do what the shipped script will not do on its own, it +# runs the outer from a test-only copy of `lanes-edit.sh` (`_bind_copy`), and +# no seam goes into the shipped script (lane 3's ruling, #165 6879754335, +# point 23). + +#: What the outer says, as T502 writes it: the 16(d) `note=` where its body +#: left no facts file, so an outcome without it shows the facts file was +#: there and was read; the 16(c) `why` where the body ended 1 and gave no +#: reason; its words where it leaves a record that is not its own; and where +#: its outcome could not be written. And the stand-in `lane-start`'s refusal. +NO_FACTS_NOTE = "whatever the bind's body left undone is not known" +NO_REASON_WHY = "the bind's body ended with exit 1 and gave no reason" +NOT_ITS_OWN = "is no longer this bind's own" +NOT_WRITTEN = "the outcome could not be written to" +STAND_IN_REFUSES = "the stand-in refuses with 1" + +#: THE TEST-ONLY COPY'S ANCHORS: each is text that `lanes-edit.sh` holds once, +#: at line R's merge106 and at T502's round 2 `12eddddf` alike, so a copy made +#: from either makes the edit the case means. The outer's own start token +#: (`guard_bind_outer`); the rewrite's `mv` and its drop list, made before it +#: opens the record (`guard_bind_rewrite`); the outer's gathering of the five +#: copies; and the record's one reader. +ANCHOR_PIDSTART = 'gbo_ps="$(pid_start_of "$$" 2>/dev/null)" || gbo_psrc=$?' +ANCHOR_MV = 'mv -f -- "$gbw_t" "$gbw_f" 2>/dev/null || { rm -f -- "$gbw_t"; return 1; }' +ANCHOR_DROP = 'for gbw_a in "$@"; do gbw_drop="$gbw_drop${gbw_a%%=*} "; done' +ANCHOR_COPIES = 'guard_bind_copies "$gbo_u"' +ANCHOR_LOAD = 'guard_bind_load() { # <offer file>' +#: The rewrite's test that the record exists, before it opens it +#: (`guard_bind_rewrite`): the window of T502's part 17, `f67f76a7` (T214q). +#: `lanes-edit.sh` holds it once at line R's merge144 and at every T502 head +#: from `12eddddf` to `ae702c74`. +ANCHOR_EXISTS = 'if [ -e "$gbw_f" ]; then' +#: The outcome's rewrite is the one whose drop list holds `mode` (the outer's +#: start drops `pid` and `pidstart`, and the body rewrites nothing). +OUTCOME_REWRITE = 'case "$gbw_drop" in *" mode "*)' +#: THE FIRST WRITES (T214s, `[failed-first-write]`; lane 2, #165 6885568373): +#: the line `guard_bind_rewrite` writes first, the `mode=` it is given, which +#: of the hook's rewrites only answer 2's gives (`mode=binding`; the offer's +#: own write and the head copy's rewrite give none); and choice 1's first +#: `mode=allow` line. `lanes-edit.sh` holds each once at line R's merge144 +#: and at every T502 head from `12eddddf` to `beeae571`. A copy appends +#: `>/dev/full` to each, so that write fails as a full disk fails it. +ANCHOR_FIRST_WRITE = "mode=*) printf '%s\\n' \"$gbw_a\"" +ANCHOR_ALLOW_WRITE = "{ printf 'mode=allow\\n'" + + +def _bind_copy(est: Estate, edits) -> Path: + """POINT 23's TEST-ONLY COPY (lane 3's ruling, #165 6879754335): the + checkout's `lanes-edit.sh`, with `repos.tsv`, `lane-start` and + `lanes-index` beside it as the checkout has them (the copy rule, + CLI4.5:885), and each of `edits`, an (anchor, text) pair, made once, as + `[answer-2]` edits its stub (`_bound_through_answer_2_on_the_stub`): an + anchor found other than once fails the case there, so a copy never runs + without the edit it was made for. The shipped script is never changed.""" + code = est.root / "bind-copy" + code.mkdir() + for name in ("lanes-edit.sh", "repos.tsv", "lane-start", "lanes-index"): + if (REPO / name).exists(): + shutil.copy2(REPO / name, code / name) + copy = code / "lanes-edit.sh" + text = copy.read_text(encoding="utf-8") + for anchor, new in edits: + text, made = re.subn(re.escape(anchor), lambda _found, new=new: new, text) + assert made == 1, f"the test-only copy's anchor was found {made} times, not once: {anchor}" + copy.write_text(text, encoding="utf-8") + return copy + + +def _hold_sh(est: Estate, name: str) -> str: + """Bash for the test-only copy: make `<ctl>/<name>.held`, then wait for + `<ctl>/<name>.release`, 30 s at most, so a case that fails never leaves + the outer held.""" + held = shlex.quote(str(est.ctl / f"{name}.held")) + release = shlex.quote(str(est.ctl / f"{name}.release")) + return (f': > {held}; t214n_n=0; while [ ! -e {release} ] && [ "$t214n_n" -lt 600 ]; ' + f'do sleep 0.05; t214n_n=$((t214n_n + 1)); done') + + +def _direct_record(est: Estate, index="1", **keys) -> Path: + """A `binding` record as the hook leaves it before the outer's start + (`_binding`, less `pid` and `pidstart`), written directly as case 22's + are (`_record_with`), with `keys` (`host`, `container`) in place of the + estate's own and its `out` at the files' index `index`. Returns that + `out`'s path.""" + out = Path(f"{est.offer}.bind.{index}.out") + lines = _binding(est, started=time.time(), bound_s=500, **keys) + write_record(est.offer, [f"out={out}" if line.startswith("out=") else line + for line in lines if not line.startswith(("pid=", "pidstart="))]) + return out + + +def _outer(est: Estate, program: Path, out: Path) -> subprocess.Popen: + """`guard-bind <uuid>` from `program`, the shipped script or a test-only + copy, as the hook's fork starts it (Y:5394; contract section 1): its + stdout and stderr in the record's `out`, 0600, so its words are where + the contract puts them, and in a session of its own, as `detach=setsid` + says. No `LANES_BIND_BODY`: the real body runs, and reaches the stand-in + `lane-start`. `$$` in the outer is the process's pid.""" + fd = os.open(out, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + try: + proc = subprocess.Popen(["bash", str(program), "guard-bind", est.sid], + stdin=subprocess.DEVNULL, stdout=fd, stderr=fd, env=est.env(), + cwd=str(est.wip), start_new_session=True) + finally: + os.close(fd) + est.spare.append(proc.pid) + return proc + + +@pytest.mark.parametrize("result", [ + "written", "io-failure", "not-its-own", "gone-at-its-open", + pytest.param("unreadable-at-its-open", marks=pytest.mark.skipif( + hasattr(os, "geteuid") and os.geteuid() == 0, + reason="root opens a mode-000 record, so its open cannot fail"))]) +def test_the_outcome_rewrite_has_three_results(estate, result): + """S1, the outcome's rewrite gives three results, and the outer's exit + and its facts file follow each. The stand-in `lane-start` exits 0, so + the real body makes its facts file and fills it, and the outer reads it: + its outcome holds no 16(d) `note=` (`NO_FACTS_NOTE`). + + - `[written]`, the rewrite's 0: the record is written, `bound`, the facts + file is removed, and the outer exits 0. + - `[io-failure]`, its 1: a test-only copy fails the outcome's rewrite at + its `mv`, as an I/O failure would. The record is as the rewrite found + it, the outer's own `binding`; no temporary file is left; the outcome + is in the `.out` alone; the outer exits 1; and its facts file is + REMOVED, as T502's round 2 does (`12eddddf`, part 11) and lane 3 ruled + on S1 (#165 6880978929: "the facts file is removed on all three + results"). Commit 24's words, "its facts file left for the next + removal to sweep" (tasks:2009, TP:6413), predate that ruling, and lane + 2 sends lane 3 the correction. + - `[not-its-own]`, its 2: a test-only copy holds the outer at its + outcome's rewrite, after the outer's own read and before the rewrite + reads the record (section 8's narrowed window), and the case installs a + record that is not the outer's own, a `binding` of another `pid`. The + rewrite's own test leaves it byte for byte; the outcome is in the + `.out` alone; the facts file, there at the hold, is removed; and the + outer exits 0. + - `[gone-at-its-open]`, its 2 by a second way (T214q; T502's part 17, + `f67f76a7`; spec#47's draft 16 `5e095c52`, section 8, d16:382): a + test-only copy holds the outcome's rewrite after its test that the + record exists and before its open (`ANCHOR_EXISTS`), and the case + removes the record there. No record is made; no temporary file is + left; the outcome is in the `.out` alone, named as the record now + stands, `mode=none`, since the outer's re-load finds nothing; the + facts file is removed; and the outer exits 0. Before part 17 the + rewrite gave 1 there, and the outer exited 1. + - `[unreadable-at-its-open]`, its control, the same hold with the record + made mode 000: the record is still there, so the rewrite's 1 stands. + The record is unchanged (read after 0600 is restored); no temporary + file is left; the outcome is in the `.out` alone; the facts file is + removed; and the outer exits 1. It passes at every T502 head, and is + red only where a 2 is given for any failed open, so it shows part 17 + kept the 1 for a record that is still there. Skipped as root, which + opens a mode-000 file (lane 2's reader AF6-27, #165 6885568373).""" + est = estate() + out = _direct_record(est) + facts = Path(f"{est.offer}.bind.1.facts") + program = GUARD + if result == "io-failure": + program = _bind_copy(est, [(ANCHOR_MV, ( + f'{OUTCOME_REWRITE} rm -f -- "$gbw_t"; return 1 ;; esac; {ANCHOR_MV}'))]) + elif result == "not-its-own": + program = _bind_copy(est, [(ANCHOR_DROP, ( + f"{ANCHOR_DROP}\n{OUTCOME_REWRITE} {_hold_sh(est, 'rewrite')} ;; esac"))]) + elif result in ("gone-at-its-open", "unreadable-at-its-open"): + program = _bind_copy(est, [(ANCHOR_EXISTS, ( + f"{ANCHOR_EXISTS}\n{OUTCOME_REWRITE} {_hold_sh(est, 'open')} ;; esac"))]) + proc = _outer(est, program, out) + planted = None + if result in ("gone-at-its-open", "unreadable-at-its-open"): + held = _until(lambda: (est.ctl / "open.held").exists(), 60) + mine, had_facts = est.record(), facts.exists() + try: + if held and result == "gone-at-its-open": + est.offer.unlink() + elif held: + planted = est.offer.read_bytes() + est.offer.chmod(0o000) + finally: + est.set("open.release") + assert held, f"the outer's outcome rewrite never came to its open: {out.read_text()}" + assert mine.get("mode") == "binding" and mine.get("pid") == str(proc.pid), \ + f"the record at the rewrite's open was not the outer's own binding: {mine}" + assert had_facts, "the body's facts file was not there when the outer came to write" + installed = None + if result == "not-its-own": + held = _until(lambda: (est.ctl / "rewrite.held").exists(), 60) + mine, had_facts = est.record(), facts.exists() + if held: + # ANOTHER OUTER'S `binding`: a live process of its own session, + # with its own start token, which the estate stops at its close. + other = _sleeper() + est.spare.append(other.pid) + write_record(est.offer, _binding(est, started=time.time(), pid=other.pid, + pidstart=_stat(other.pid)["start"])) + installed = est.offer.read_bytes() + est.set("rewrite.release") + assert held, f"the outer never came to its outcome's rewrite: {out.read_text()}" + assert mine.get("mode") == "binding" and mine.get("pid") == str(proc.pid), \ + f"the record at the outer's rewrite was not its own binding: {mine}" + assert had_facts, "the body's facts file was not there when the outer came to write" + code = proc.wait(60) + if result == "unreadable-at-its-open" and est.offer.exists(): + est.offer.chmod(0o600) + said = out.read_text(encoding="utf-8", errors="replace") + record = est.record() + ends = [line for line in said.splitlines() if "mode=bound rc=0" in line] + temporaries = [p.name for p in est.offer.parent.iterdir() if p.name.startswith(f".{est.sid}.")] + if result == "gone-at-its-open": + assert code == 0, \ + (f"guard-bind exited {code}, not 0, where its record went between the outcome " + f"rewrite's test that it exists and its open (before T502's part 17 the rewrite " + f"gives 1 there, and the outer exits 1): {said}") + assert not est.offer.exists(), \ + f"the outer's rewrite made a record where it found none: {record}\n{said}" + assert not temporaries, f"the rewrite left its temporary file: {temporaries}" + assert [line for line in ends if f"{NOT_ITS_OWN} (mode=none," in line + and NO_FACTS_NOTE not in line], \ + f"the outcome, its facts folded in, is not in the .out alone, with mode=none: {said}" + assert not facts.exists(), f"the outer left its facts file after its rewrite's 2: {facts}" + return + if result == "unreadable-at-its-open": + assert code == 1, \ + (f"guard-bind exited {code}, not 1, where its record was still there and could not " + f"be opened, so the rewrite's 1 stands: {said}") + assert est.offer.exists() and est.offer.read_bytes() == planted, \ + f"the record that could not be opened was changed or removed: {record}\n{said}" + assert not temporaries, f"the rewrite left its temporary file: {temporaries}" + assert [line for line in ends if NOT_WRITTEN in line and NO_FACTS_NOTE not in line], \ + f"the outcome, its facts folded in, is not in the .out alone: {said}" + assert not facts.exists(), f"the outer left its facts file after its rewrite's 1: {facts}" + return + if result == "written": + assert code == 0 and record.get("mode") == "bound" and record.get("rc") == "0", \ + f"guard-bind {code}: {record}\n{said}" + assert not any(note.startswith(NO_FACTS_NOTE) for note in record.get("note", [])), \ + f"the outer found no facts file to fold in: {record}" + assert not facts.exists(), f"the outer left its facts file after its rewrite's 0: {facts}" + return + if result == "io-failure": + assert code == 1, f"guard-bind exited {code}, not 1, where its outcome's mv failed: {said}" + assert record.get("mode") == "binding" and record.get("pid") == str(proc.pid) \ + and "rc" not in record, f"the record is not as the failed rewrite found it: {record}" + assert not [p.name for p in est.offer.parent.iterdir() + if p.name.startswith(f".{est.sid}.")], "the failed rewrite left its temporary file" + assert [line for line in ends if NOT_WRITTEN in line and NO_FACTS_NOTE not in line], \ + f"the outcome, its facts folded in, is not in the .out alone: {said}" + assert not facts.exists(), \ + (f"the outer left its facts file after its rewrite's 1, where lane 3's ruling on S1 " + f"(#165 6880978929) removes it on all three results: {facts}") + return + assert code == 0, f"guard-bind exited {code}, not 0, after its rewrite's 2: {said}" + assert est.offer.read_bytes() == installed, \ + f"the outer's outcome was written over a record that is not its own: {record}\n{said}" + assert [line for line in ends if NOT_ITS_OWN in line and NO_FACTS_NOTE not in line], \ + f"the outcome, its facts folded in, is not in the .out alone: {said}" + assert not facts.exists(), f"the outer left its facts file after its rewrite's 2: {facts}" + + +@pytest.mark.parametrize("case", ["gone-before-its-start", "no-longer-binding-at-its-start"]) +def test_the_outer_runs_nothing_where_its_record_is_not_binding_at_its_start(estate, case): + """T502's part 21 (T214t; lane 5, #165 6885608994): the outer's start + rewrite, which writes its `pid`, `pidstart` and the start's keys, runs + only on a record that still says `mode=binding`. Where the record is + gone, or reads otherwise, it writes nothing, and the outer runs nothing + and exits 2, as it does where its own load finds no record or one that + is not `binding`. A rewrite never creates a record: `guard_offer`'s + write is its only creation (lane 3's ruling on spec#47's point 26), and + the record is the bind's authority. + + A test-only copy (`_bind_copy`, point 23) holds the outer after its load + and before its start rewrite, at its own start token + (`ANCHOR_PIDSTART`). At the hold the record is the `binding` the outer + loaded, with no `pid` yet; then the case changes it and releases: + + - `[gone-before-its-start]`: the record is removed. No record is made. + - `[no-longer-binding-at-its-start]`: the record is replaced, by a + temporary file and a rename, with a `name-drift` offer the guard made + in this estate. It is left byte for byte. + + In both, the outer exits 2, no temporary file is left, and the bind does + not run: the stand-in `lane-start` logs no start, and no facts file is + made. Red at every T502 head through `ae702c74`, whose start rewrite has + no `--own`: it makes a record of the start's keys alone, or writes them + into the offer, and the bind runs (lane 2's reader AF6-27, #165 + 6885568373, "Not one of the four").""" + est = estate() + drift = None + if case == "no-longer-binding-at-its-start": + est.make_offer() + drift = est.offer.read_bytes() + out = _direct_record(est) + facts = Path(f"{est.offer}.bind.1.facts") + program = _bind_copy(est, [(ANCHOR_PIDSTART, f"{_hold_sh(est, 'start')}\n{ANCHOR_PIDSTART}")]) + proc = _outer(est, program, out) + held = _until(lambda: (est.ctl / "start.held").exists(), 60) + mine = est.record() + try: + if held and drift is None: + est.offer.unlink() + elif held: + tmp = est.offer.parent / f".{est.offer.name}.t214t" + tmp.write_bytes(drift) + tmp.chmod(0o600) + os.replace(tmp, est.offer) + finally: + est.set("start.release") + assert held, f"the outer never came to its start rewrite: {out.read_text()}" + assert mine.get("mode") == "binding" and "pid" not in mine, \ + f"the record at the outer's start was not the binding it loaded, with no pid yet: {mine}" + code = proc.wait(60) + said = out.read_text(encoding="utf-8", errors="replace") + record = est.record() + temporaries = [p.name for p in est.offer.parent.iterdir() if p.name.startswith(f".{est.sid}.")] + was = "gone" if drift is None else "a name-drift offer" + assert code == 2, \ + (f"guard-bind exited {code}, not 2, where its record was {was} at its start rewrite " + f"(through T502's ae702c74 that rewrite has no --own, writes the start's keys, and " + f"the bind runs): {record}\n{said}") + if drift is None: + assert not est.offer.exists(), \ + f"the outer's start rewrite made a record where it found none: {record}\n{said}" + else: + assert est.offer.read_bytes() == drift, \ + f"the outer's start rewrite wrote over the name-drift offer: {record}\n{said}" + assert not temporaries, f"the start rewrite left its temporary file: {temporaries}" + assert not est.starts(), \ + f"the bind ran, though its record was {was} at its start: {est.starts()}\n{said}" + assert not facts.exists(), f"the bind's body made its facts file: {facts}" + + +#: S2's records: the key each case gives the record, and its value, the +#: outer's own (`HOST`, `CONTAINER`) in other case, or another host or +#: container. ASCII case, since `lower_into` maps A to Z alone. +OWNER_CASES = { + "case-only-host": ("host", HOST.upper()), + "case-only-container": ("container", CONTAINER.upper()), + "other-host": ("host", "Kestrel"), + "other-container": ("container", "h-box"), +} + + +@pytest.mark.parametrize("case", list(OWNER_CASES)) +def test_the_outer_matches_host_and_container_without_regard_to_case(estate, case): + """S2, the outer's test of its own `binding` matches the record's `host` + and `container` with its own, `WS` and `LANES_CONTAINER_NAME` (`HOST` and + `CONTAINER`, through `LANES_WORKSTATION` and `LANES_CONTAINER`), without + regard to case, as the guard's site does (contract section 1). + + - `[case-only-host]` and `[case-only-container]` differ from the outer's + own in case alone, and the outer writes its outcome, `bound`. + - `[other-host]` and `[other-container]` are real mismatches, with the + outer's own `pid` and no `pidstart`: a test-only copy makes its own + `pid_start_of $$` exit 2, so it writes `pid` alone, as an outer on + another host with the same pid would. The outer leaves the record as + its own start left it, `binding`, and its outcome goes to its `.out` + alone.""" + key, value = OWNER_CASES[case] + est = estate() + out = _direct_record(est, **{key: value}) + program = GUARD + if case.startswith("other-"): + program = _bind_copy(est, [(ANCHOR_PIDSTART, 'gbo_ps=""; gbo_psrc=2')]) + proc = _outer(est, program, out) + code = proc.wait(60) + said = out.read_text(encoding="utf-8", errors="replace") + record = est.record() + assert code == 0 and record.get(key) == value, f"guard-bind {code}: {record}\n{said}" + if case.startswith("case-only-"): + assert record.get("mode") == "bound" and record.get("rc") == "0", \ + (f"the outer did not write its outcome over its own binding, whose {key} differs " + f"from its own in case alone: {record}\n{said}") + return + assert record.get("pid") == str(proc.pid) and "pidstart" not in record, \ + f"the record does not hold the outer's own pid and no pidstart: {record}" + assert record.get("mode") == "binding" and "rc" not in record, \ + f"the outer wrote its outcome over a binding of another {key}: {record}\n{said}" + assert NOT_ITS_OWN in said, f"the outer's outcome is not in its .out: {said}" + + +@pytest.mark.parametrize("index", ["0", "01", "١"], + ids=["bind-0", "bind-01", "bind-u0661"]) +def test_a_noncanonical_out_names_no_facts_file_and_no_words(estate, index): + """S3, an `out` whose index is not canonical, `[1-9][0-9]*` (contract + section 3's `out` row), names no facts file: nothing is read from, + written to or removed at `.bind.<index>.facts`, and the body reads none + of its own words back from the `out`. A sentinel `.facts` file stands + where a derivation would put it, and the stand-in `lane-start` refuses + 1, its words in the `out`. The sentinel is left byte for byte, no other + file is made beside the `out`, and the record ends `bind-failed` with + point 16(c)'s `why`, not the stand-in's line. + + `[bind-0]` and `[bind-01]` stop at the predicate's `0*` branch. + `[bind-u0661]` (T214r) is an index of U+0661, the Arabic-Indic digit + one, which reaches its non-digit branch, `*[!0123456789]*` (T502's part + 19, `a6ee7c0b`), the branch that keeps an `out` from naming an arbitrary + facts path. Its id is ASCII, set by `ids=`. It is coverage, not a red + for part 19: bash 5.x's `*[!0-9]*` before it already rejects U+0661 on + this host, so it goes red only where the non-digit test is dropped + (lane 5's `[non-ascii-digit]`, #165 6884069915; lane 2's reader AF6-27, + #165 6885568373).""" + est = estate() + est.set("rc", 1) + out = _direct_record(est, index=index) + sentinel = Path(f"{est.offer}.bind.{index}.facts") + write_record(sentinel, ["why=a sentinel, where an out of this form names no facts file"]) + planted = sentinel.read_bytes() + proc = _outer(est, GUARD, out) + code = proc.wait(60) + said = out.read_text(encoding="utf-8", errors="replace") + record = est.record() + assert sentinel.exists() and sentinel.read_bytes() == planted, \ + f"{sentinel.name} was removed or written, though .bind.{index}.out names no facts file" + beside = sorted(p.name for p in est.offer.parent.glob(f"{est.sid}.bind.*")) + assert beside == sorted([out.name, sentinel.name]), f"a file was made beside the out: {beside}" + assert code == 0 and record.get("mode") == "bind-failed" and record.get("rc") == "1", \ + f"guard-bind {code}: {record}\n{said}" + assert STAND_IN_REFUSES in said, f"the stand-in lane-start's words are not in the out: {said}" + why = record.get("why", "") + assert why.startswith(NO_REASON_WHY) and STAND_IN_REFUSES not in why, \ + f"the body read its words back from .bind.{index}.out: {record}" + + +@pytest.mark.parametrize("leftovers", [("999999",), ("999999", "1000000")], + ids=["999999", "1000000"]) +def test_the_files_index_passes_six_digits(estate, leftovers): + """S4, every canonical index counts, compared as a number at any length + (contract section 1's files' index). An earlier offer's `.out` files, + left as a case 11 leaves them, stand before the `2`: `[999999]` leaves + `<uuid>.bind.999999.out`, and the attempt's `out` is `.bind.1000000.out`; + `[1000000]` leaves `.bind.999999.out` and `.bind.1000000.out`, and the + attempt's `out` is `.bind.1000001.out`. So an index over six digits + passed over, or compared as a string, fails `[1000000]`, which a lone + `.bind.1000000.out` would not show. Each leftover is as it was: the + hook's `>` never met it.""" + est = estate() + est.make_offer() + left = {} + for index in leftovers: + path = Path(f"{est.offer}.bind.{index}.out") + path.write_text(f"attempt {index}'s output, left by an earlier offer\n", encoding="utf-8") + left[path] = path.read_bytes() + est.answer_2() + record = est.ended() + want = f"{est.sid}.bind.{int(leftovers[-1]) + 1}.out" + assert Path(record.get("out", "")).name == want, \ + f"the attempt's out is {record.get('out')}, not {want}, one above the leftovers {leftovers}" + for path, data in left.items(): + assert path.read_bytes() == data, f"the leftover {path.name} was changed" + + +def test_the_outer_gathers_its_copies_before_its_last_ownership_read(estate): + """S6, the outer gathers what its outcome writes, the five copies among + them (`guard_bind_copies`), BEFORE it reads the record again, and never + between that read and its write (contract section 1). The bind ends + non-0, the stand-in `lane-start` refusing 1, since the outer gathers the + copies only for an outcome other than `bound`. A test-only copy logs each + of the outer's reads of the record (`guard_bind_load`) and its call of + `guard_bind_copies`, and holds the outer after its second read, the one + before its outcome: at that hold the log already names the copies, and + that read is the outer's last.""" + est = estate() + est.set("rc", 1) + out = _direct_record(est) + log = est.ctl / "outer.log" + where = shlex.quote(str(log)) + program = _bind_copy(est, [ + (ANCHOR_COPIES, f"printf 'copies\\n' >> {where}; {ANCHOR_COPIES}"), + (ANCHOR_LOAD, ( + "guard_bind_load() { # T214n's copy: the outer's reads, logged, and held at its 2nd\n" + ' if [ -n "${gbo_u-}" ]; then T214N_READS=$(( ${T214N_READS:-0} + 1 )); ' + f"printf 'read %s\\n' \"$T214N_READS\" >> {where}; fi\n" + ' t214n_rc=0; guard_bind_load_shipped "$@" || t214n_rc=$?\n' + ' if [ -n "${gbo_u-}" ] && [ "$T214N_READS" = 2 ]; then ' + f"{_hold_sh(est, 'read')}; fi\n" + ' return "$t214n_rc"\n' + "}\n" + "guard_bind_load_shipped() { # <offer file>")), + ]) + proc = _outer(est, program, out) + held = _until(lambda: (est.ctl / "read.held").exists(), 60) + at_hold = log.read_text(encoding="utf-8").splitlines() if log.exists() else [] + est.set("read.release") + code = proc.wait(60) + said = out.read_text(encoding="utf-8", errors="replace") + record = est.record() + lines = log.read_text(encoding="utf-8").splitlines() if log.exists() else [] + assert held and at_hold[:1] == ["read 1"] and at_hold[-1:] == ["read 2"], \ + f"the outer never made its read before its outcome: {lines}\n{said}" + assert "copies" in at_hold, \ + (f"guard_bind_copies had not run when the outer held after its read before its " + f"outcome: {at_hold}") + reads = [line for line in lines if line.startswith("read ")] + assert reads[-1] == "read 2" and lines.index("copies") < lines.index("read 2"), \ + f"the outer read its record again after it gathered the copies: {lines}" + assert code == 0 and record.get("mode") == "bind-failed" and record.get("rc") == "1", \ + f"guard-bind {code}: {record}\n{said}" + + +# ------------------------------------------------ T214: section 8's other bullets +# +# SECTION 8's OTHER BULLETS (T214o; spec#47's draft 14 `96d14916`, section 8, +# its bullets at :359 to :375; lane 5's names, #165 6881714002; lane 2's +# confirmation with K1 to K5, #165 6882026139, Part B). Each binds through the +# stand-in `lane-start` and the real body, or calls `guard-bind` itself, with +# no `start-record` and no mode id (tasks:2005). They are coverage cases: each +# passes on line R's merge106 and on lane 5's T502 head, whose guard and +# `guard-bind` they read, and each fails on code `main` until L5-A1, lane 5's +# T502, and waits for no other task (tasks:2013). Where a case needs the +# shipped script to do what it will not do on its own, it runs a test-only +# copy (`_bind_copy`; lane 3's ruling, #165 6879754335, point 23). Section 8's +# :374 is case 22's `[c3-w473]` and `[c3-w474]` (T214m), its :376 is T254's +# (K1), and its optional :352 is not written. + +#: The outcome the outer says in its `.out`, beside `NOT_ITS_OWN`, where it +#: leaves a record that is not its own after a bind that ended 0. +OUTCOME_BOUND = "mode=bound rc=0" +#: The outer's own read before its start, the anchor of `[was-0644]`'s hold +#: there: one line, once in `lanes-edit.sh` at line R's merge106, T502's +#: round 2 `12eddddf` and its part 14 `66a0f1e3` alike. +ANCHOR_OUTER_START = 'gbo_k="$GBR_BIND"' + + +def _offer_lines(est: Estate, now: float) -> list: + """A fresh `mode=name-drift` offer of this session, in the keys and the + order `guard_offer` writes them.""" + return ["mode=name-drift", f"from={FROM}", f"to={est.to}", f"session={est.to}", + f"uuid={est.sid}", f"utc={_utc(now)}", "window=testsess:@1", f"pane={GUARD_PANE}"] + + +def _mode_bits(path: Path) -> int: + return path.stat().st_mode & 0o777 + + +def _temporaries(est: Estate) -> list: + """The temporary files a rewrite left in `offers/`, `.<uuid>.XXXXXX`.""" + offers = est.offer.parent + if not offers.is_dir(): + return [] + return sorted(p.name for p in offers.iterdir() if p.name.startswith(f".{est.sid}.")) + + +def _fail_mv(pattern: str) -> str: + """The test-only copy's text for `ANCHOR_MV`: the rewrite whose written + keys hold one that matches `pattern`, a `case` glob, fails at its `mv`, + as an I/O failure would. The shipped text after the `mv`, which removes + the temporary file and returns 1, is kept as it is, so the case reads + the shipped failure path.""" + return (f't214o_f=0; for t214o_a in "$@"; do case "$t214o_a" in {pattern}) t214o_f=1 ;; ' + 'esac; done\n' + ' if [ "$t214o_f" = 1 ]; then false; else mv -f -- "$gbw_t" "$gbw_f"; fi 2>/dev/null ' + '|| { rm -f -- "$gbw_t"; return 1; }') + + +def _guard_bind(est: Estate, *args, program: Path = GUARD, **extra) -> subprocess.CompletedProcess: + """`guard-bind` called directly, as case 22 calls it.""" + return subprocess.run(["bash", str(program), "guard-bind", *args], capture_output=True, + text=True, env=est.env(**extra), cwd=str(est.wip), timeout=60) + + +@pytest.mark.parametrize("code", ["0", "1"], ids=["lane-start-0", "lane-start-1"]) +def test_an_outer_that_wrote_pid_alone_still_writes_its_outcome(estate, code): + """Section 8's :359 (lane 3's ruling, #165 6879754335, point 19): an outer + whose own `pid_start_of $$` exits 2, made so by a test-only copy, writes + `pid` alone at its start, and still writes its outcome over its own + `binding`, whose `pidstart` is then none. While the stand-in `lane-start` + holds, the record holds the outer's `pid` and no `pidstart`. + + - `[lane-start-0]`: the stand-in exits 0; the record ends `bound`, still + with that `pid` and no `pidstart`, and the next prompt says "MOVED" + and removes it. + - `[lane-start-1]`: it exits 1; the record ends `bind-failed`, and the + next prompt answers as case 6: the failure, the window renamed back to + `<from>`, and the offer KEPT at `bind=1`.""" + est = estate() + est.set("hold", 60) + est.set("rc", code) + out = _direct_record(est) + program = _bind_copy(est, [(ANCHOR_PIDSTART, 'gbo_ps=""; gbo_psrc=2')]) + proc = _outer(est, program, out) + started = _until(est.starts, 60) + mid = est.record() + est.release() + rc = proc.wait(60) + said = out.read_text(encoding="utf-8", errors="replace") + record = est.record() + assert started, f"the stand-in lane-start never started: {said}" + assert mid.get("mode") == "binding" and mid.get("pid") == str(proc.pid) \ + and "pidstart" not in mid, f"the outer did not write its pid alone at its start: {mid}" + assert rc == 0 and record.get("pid") == str(proc.pid) and "pidstart" not in record, \ + f"guard-bind {rc}: {record}\n{said}" + calls = len(est.session.tmux_calls()) + hook = est.hook("the next prompt") + if code == "0": + assert record.get("mode") == "bound" and record.get("rc") == "0", \ + f"the outer that wrote pid alone wrote no outcome over its own binding: {record}\n{said}" + moved = f"MOVED: this window is lane {TO}, bound to this session ({est.sid}) at " + assert hook.code == 2 and moved + record["ended_utc"] in hook.err, repr(hook) + assert not est.offer.exists(), "MOVED left the record in place" + return + assert record.get("mode") == "bind-failed" and record.get("rc") == "1" \ + and STAND_IN_REFUSES in record.get("why", ""), \ + f"the outer that wrote pid alone wrote no failure over its own binding: {record}\n{said}" + assert hook.code == 2 and f"THE BIND TO LANE {TO} FAILED (exit 1)" in hook.err \ + and KEPT in hook.err and NO_LONGER_2 not in hook.err, repr(hook) + assert [c for c in _renames(est, calls) if c[-1] == FROM], \ + f"the window was not renamed back to {FROM}: {est.session.tmux_calls()[calls:]}" + after = est.record() + assert after.get("mode") == "name-drift" and after.get("bind") == "1", after + + +@pytest.mark.parametrize("change", ["other-pid", "binding-no-pid", "new-offer"]) +def test_the_outer_leaves_a_record_no_longer_its_own(estate, change): + """Section 8's :360 (lane 3's ruling, #165 6751772589, point 18): while + the stand-in `lane-start` holds, before the outer reads its record again, + the case rewrites the record, and the outer leaves it as it is, exits 0, + and says its outcome in its `.out` alone; its facts file goes, as on each + of its ends. `[other-pid]`: another outer's `binding`, a live process + with its own start token; `[binding-no-pid]`: a `binding` with no `pid`; + `[new-offer]`: a fresh `name-drift` offer. A record of another `host` or + `container` with the outer's own `pid` is S2's `[other-host]` and + `[other-container]`, and a change after the outer's read is S1's + `[not-its-own]` (K2).""" + est = estate() + est.set("hold", 60) + out = _direct_record(est) + facts = Path(f"{est.offer}.bind.1.facts") + proc = _outer(est, GUARD, out) + started = _until(est.starts, 60) + mine, installed = est.record(), None + if started: + now = time.time() + if change == "other-pid": + # ANOTHER OUTER: a live process of its own session, with its own + # start token, which the estate stops at its close. + other = _sleeper() + est.spare.append(other.pid) + lines = _binding(est, started=now, pid=other.pid, pidstart=_stat(other.pid)["start"]) + elif change == "binding-no-pid": + lines = _binding(est, started=now) + else: + lines = _offer_lines(est, now) + write_record(est.offer, lines) + installed = est.offer.read_bytes() + est.release() + code = proc.wait(60) + said = out.read_text(encoding="utf-8", errors="replace") + assert started, f"the stand-in lane-start never started: {said}" + assert mine.get("mode") == "binding" and mine.get("pid") == str(proc.pid), \ + f"the record while lane-start held was not the outer's own binding: {mine}" + assert code == 0, f"guard-bind exited {code}, not 0, over a record not its own: {said}" + assert est.offer.read_bytes() == installed, \ + f"the outer's outcome was written over a record that is not its own: {est.record()}\n{said}" + assert [line for line in said.splitlines() if NOT_ITS_OWN in line and OUTCOME_BOUND in line], \ + f"the outcome is not in the .out: {said}" + assert not facts.exists(), f"the outer left its facts file: {facts}" + + +def test_the_next_offers_files_index_runs_above_a_case_11_leftover(estate): + """Section 8's :368 (lane 3's correction, #165 6751818233): an earlier + offer's `<uuid>.bind.4.out`, left by a real case 11 (an unreadable + `binding` record, dropped with its `.bind.*` files left), and then the + next offer's `2`: its attempt's `out` is `<uuid>.bind.5.out`, one above + the leftover, while its `bind`, the attempt, is 1 again. The leftover is + as it was.""" + est = estate() + est.offer.parent.mkdir(parents=True, exist_ok=True, mode=0o700) + left = Path(f"{est.offer}.bind.4.out") + left.write_text("an earlier offer's output, left by a case 11\n", encoding="utf-8") + kept = left.read_bytes() + write_record(est.offer, ["mode=binding", f"from={FROM}", "to=", "bind=3", f"out={left}"]) + hook = est.hook("hello") + assert hook.code == 2 and UNREADABLE in hook.err, repr(hook) + assert not est.offer.exists() and left.read_bytes() == kept, \ + "case 11 did not drop the record alone" + est.make_offer() + est.answer_2() + record = est.record() + want = f"{est.sid}.bind.5.out" + assert record.get("bind") == "1" and Path(record.get("out", "")).name == want, \ + f"the next offer's first attempt is not bind=1 with out {want}: {record}" + record = est.ended() + assert record["mode"] == "bound" and Path(record["out"]).name == want, record + assert left.read_bytes() == kept, f"the leftover {left.name} was changed" + + +@pytest.mark.parametrize("case", ["made-empty-first", "none-after-0", "none-after-nonzero"]) +def test_the_facts_file_is_made_empty_first_and_its_absence_is_reported(estate, case): + """Section 8's :369 (lane 3's ruling, #165 6747528875, point 16; lane 3's + ruling, #165 6752064118; TP:6413 and tasks:2009 at spec#48's commit 29, + after Codex's delta review 7i of commit 26, its second BLOCKING finding): + the parts of the facts file the S1 and S3 cases leave open. Before the + body, an old facts file stands at the attempt's name, not empty, with a + `why=` and a `note=` of its own. + + - `[made-empty-first]`: the body truncates it. The real body is called + as its outer calls it, `guard-bind --body <uuid>` with the path in + `LANES_BIND_FACTS`, and with no outer, so the old file is still there + when the body starts; the stand-in `lane-start` holds. At the body's + first step the case can hold, `lane-start`, the facts file is `out`'s + stem with `.facts`, the only one, and empty (spec#47's `bind-record.md` + at `5e095c52`, :135, "The body creates it, empty, before its first + step"). The body exits 0, and none of the old lines is in the file it + leaves. + - `[none-after-0]` and `[none-after-nonzero]`: through the outer, which + removes the old file before its body starts (a hard link keeps the old + bytes and inode, so the case tells a file removed from one emptied in + place), and the stub body (`LANES_BIND_BODY`), handed that path in + `LANES_BIND_FACTS`, which writes no facts file and exits 0 or 1: the + record ends `bound` with point 16(d)'s `note=` naming the `out`, or + `bind-failed` with point 16(c)'s `why`, and nothing of the old file; + the old file's bytes are as they were, and no facts file is left.""" + est = estate() + out = _direct_record(est) + facts = Path(f"{est.offer}.bind.1.facts") + old_lines = ["why=an old account, from before this outer", + "note=an old act, from before this outer"] + write_record(facts, old_lines) + assert facts.read_bytes(), f"the old facts file {facts} is empty before the body" + if case == "made-empty-first": + est.set("hold", 60) + fd = os.open(out, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + try: + body = subprocess.Popen(["bash", str(GUARD), "guard-bind", "--body", est.sid], + stdin=subprocess.DEVNULL, stdout=fd, stderr=fd, + env=est.env(LANES_BIND_FACTS=str(facts)), + cwd=str(est.wip), start_new_session=True) + finally: + os.close(fd) + est.spare.append(body.pid) + seen = None + if _until(est.starts, 60): + made = sorted(p.name for p in est.offer.parent.glob(f"{est.sid}.bind.*.facts")) + seen = (made, facts.read_bytes() if facts.exists() else None) + est.release() + code = body.wait(60) + said = out.read_text(encoding="utf-8", errors="replace") + assert seen, f"the stand-in lane-start never started: {said}" + assert seen[0] == [facts.name] and seen[1] == b"", \ + (f"at the body's first step the facts file was not {facts.name} alone and empty: " + f"{seen[0]}, {seen[1]!r}\n{said}") + left = facts.read_text(encoding="utf-8") if facts.exists() else "" + assert code == 0, f"the body exited {code}: {said}" + assert not [line for line in left.splitlines() if line in old_lines], \ + f"an old line is in the facts file the body left: {left!r}" + return + keep = est.root / "facts-before" + os.link(facts, keep) + old = keep.read_bytes() + est.extra["LANES_BIND_BODY"] = str(est.body) + if case == "none-after-nonzero": + est.set("body-rc", 1) + proc = _outer(est, GUARD, out) + code = proc.wait(60) + said = out.read_text(encoding="utf-8", errors="replace") + record = est.record() + assert keep.read_bytes() == old, \ + "the old facts file was written over in place, not removed before the body started" + assert not facts.exists(), f"the outer left its facts file: {facts}" + body = est.log("body.log") + assert body and body[0]["env"]["LANES_BIND_FACTS"] == str(facts), \ + f"the outer did not hand its body the facts path {facts}: {body}" + assert code == 0, f"guard-bind exited {code}: {record}\n{said}" + if case == "none-after-0": + assert record.get("mode") == "bound" and record.get("rc") == "0" \ + and [n for n in record["note"] if n.startswith(NO_FACTS_NOTE) and str(out) in n] \ + and not [n for n in record["note"] if "from before this outer" in n], \ + f"a 0 with no facts file did not end bound with point 16(d)'s note: {record}" + return + why = record.get("why", "") + assert record.get("mode") == "bind-failed" and record.get("rc") == "1" \ + and why.startswith(NO_REASON_WHY) and str(out) in why, \ + f"a 1 with no facts file did not end bind-failed with point 16(c)'s why: {record}" + + +def test_case_11_with_a_live_outer_drops_the_record_and_keeps_its_files(estate): + """Section 8's :370 (lane 3's ruling, #165 6747528875, points 6 and 13): + case 11 met by a live outer, held in the stand-in `lane-start`. The + record is dropped; `<uuid>.bind.*`, its `.out` and its facts file, stays; + and the live outer's `.out` is not unlinked: it is still the file the + outer writes to. Released, the outer finds no record of its own, writes + none, and says its outcome in its `.out`. The `.out` then stays until + the next removal, choice 1's `mode=allow` on the next offer, which sweeps + `<uuid>.bind.*`.""" + est = estate() + est.set("hold", 60) + out = _direct_record(est) + facts = Path(f"{est.offer}.bind.1.facts") + proc = _outer(est, GUARD, out) + started = _until(est.starts, 60) + hook, files, same = None, [], False + if started: + write_record(est.offer, ["mode=binding", f"from={FROM}", "to="]) + hook = est.hook("hello") + files = sorted(p.name for p in est.offer.parent.glob(f"{est.sid}.bind.*")) + try: + same = os.stat(out).st_ino == os.stat(f"/proc/{proc.pid}/fd/1").st_ino + except OSError: + same = False + dropped = not est.offer.exists() + est.release() + code = proc.wait(60) + said = out.read_text(encoding="utf-8", errors="replace") + assert started, f"the stand-in lane-start never started: {said}" + assert hook.code == 2 and UNREADABLE in hook.err, repr(hook) + assert dropped, "case 11 left the unreadable record" + assert files == sorted([out.name, facts.name]), f"case 11 did not leave <uuid>.bind.*: {files}" + assert same, "case 11 unlinked the live outer's .out" + assert code == 0 and not est.offer.exists() and NOT_ITS_OWN in said, \ + f"the live outer wrote a record after case 11 dropped it: {est.record()}\n{said}" + est.make_offer() + assert out.exists(), "the .out went before the next removal" + hook = est.hook("1") + assert hook.code == 2 and "ALLOWED" in hook.err, repr(hook) + left = sorted(p.name for p in est.offer.parent.glob(f"{est.sid}.bind.*")) + assert not left, f"the next removal, choice 1's allow, left {left}" + + +#: Section 8's :371, with K5's names: each malformed `pid`, beside a +#: well-formed `pidstart`, and a well-formed `pid` beside each malformed +#: `pidstart` on Linux. `{live}` is a live process's pid, and `{start}` its +#: start token, so a guard that tested the value would find it live, or its +#: pid reused, and never wait for the deadline. +MALFORMED_PIDS = { + "pid-0": ("0", "{start}"), + "pid-1": ("1", "{start}"), + "pid-leading-0": ("0{live}", "{start}"), + "pid-eleven-digits": ("12345678901", "{start}"), + "pid-non-digit": ("{live}x", "{start}"), + "pidstart-empty": ("{live}", ""), + "pidstart-non-digit": ("{live}", "{start}x"), +} + +#: :371's RECORDING STUBS, SO THAT NO PROCESS OF THE CASE SENDS A SIGNAL +#: (T214o). Its record holds `pid=0`, `pid=1` and other values that no bind's +#: pid takes, and a signal to one of them reaches a whole process group, or +#: the container's init and its main process; so every call that can send a +#: signal is written to `<ctl>/calls.log` and none is sent. +#: +#: THE SHELL'S BUILTIN `kill`, which no `PATH` entry can shadow, is the case's +#: `BASH_ENV`, which every non-interactive bash reads before its first line: +#: the guard's copy, and any bash it starts. It disables the builtin +#: (`enable -n kill`), so neither `builtin kill` nor `command kill` reaches +#: it, and defines a function `kill`, which bash finds before any builtin or +#: file. `kill -0 <pid>` alone is answered from `/proc`, as the builtin +#: answers it for this user's processes (`pid_alive`'s test of the session's +#: live process); every other call is answered 1, not sent. `@LOG@` is the +#: log, quoted for the shell. +T214O_BASH_ENV = r"""# T214o's recording stub: no bash of this case sends a signal. +enable -n kill 2>/dev/null || : +kill() { + { printf 'kill'; printf ' %s' "$@"; printf '\n'; } >> @LOG@ + if [ "$#" -eq 2 ] && [ "$1" = -0 ]; then + case "$2" in ''|0*|*[!0-9]*) return 1 ;; esac + [ -e "/proc/$2" ] + return + fi + return 1 +} +""" + +#: THE COMMANDS THAT SEND SIGNALS, first on `PATH` (`@NAME@` each one's): +#: each logs its argv, sends nothing, and exits 1. +T214O_NO_SIGNAL = r"""#!/bin/sh +{ printf '%s' @NAME@; printf ' %s' "$@"; printf '\n'; } >> @LOG@ +exit 1 +""" + +#: `timeout`, first on `PATH`: it logs its argv and runs the command with no +#: timer, so it sends nothing. +T214O_TIMEOUT = r"""#!/bin/sh +{ printf 'timeout'; printf ' %s' "$@"; printf '\n'; } >> @LOG@ +while [ "$#" -gt 0 ]; do + case "$1" in + -k|-s|--kill-after|--signal) shift 2 ;; + --) shift; break ;; + -*) shift ;; + *) break ;; + esac +done +[ "$#" -gt 0 ] && shift +exec "$@" +""" + +#: `lanes-index` beside the guard's copy, where the guard finds it: it logs +#: its argv, then runs the copy's own `lanes-index` (`@REAL@`) in a Python +#: whose `os.kill` and `os.killpg` log each call and send nothing. +T214O_INDEX = r"""#!/bin/sh +{ printf 'lanes-index'; printf ' %s' "$@"; printf '\n'; } >> @LOG@ +exec @PY@ -c ' +import os, runpy, sys +log, real = sys.argv[1], sys.argv[2] +def stub(name): + def record(pid, sig): + with open(log, "a", encoding="utf-8") as handle: + handle.write("%s %s %s\n" % (name, pid, int(sig))) + return record +os.kill, os.killpg = stub("os.kill"), stub("os.killpg") +sys.argv = [real] + sys.argv[3:] +runpy.run_path(real, run_name="__main__") +' @LOG@ @REAL@ "$@" +""" + +#: The words of the case's log whose arguments are pids: no call of these may +#: carry the record's `pid` (`timeout` and `lanes-index` are logged, and +#: their arguments are not pids). +T214O_PID_CALLS = ("kill", "pkill", "killall", "pgrep", "pid_start_of") + + +@pytest.fixture +def signals_recorded(monkeypatch): + """THE PYTEST PROCESS SENDS NO SIGNAL (T214o): `os.kill`, `os.killpg` and + `signal.pidfd_send_signal`, through which `_kill`, `run_hook`'s timer and + a `subprocess.Popen`'s `kill` and `terminate` all go, record each call + and send nothing, from before the estate is made until after its + teardown, since a case requests this fixture before `estate`, and + fixtures end in the reverse of the order they were made. At the end the + calls are printed; one that would have reached a pid of 1 or less, or + this process, its group or its session, fails the case; and so does none + at all, since the estate's teardown always signals the case's own + holder, so an empty list means the teardown ran after the stubs were + gone.""" + made = [] + + def stub(name): + def record(target, sig, *rest): + made.append((name, int(target), int(sig))) + return record + + monkeypatch.setattr(os, "kill", stub("os.kill")) + monkeypatch.setattr(os, "killpg", stub("os.killpg")) + monkeypatch.setattr(signal, "pidfd_send_signal", stub("signal.pidfd_send_signal"), + raising=False) + yield made + own = {os.getpid(), os.getpgrp(), os.getsid(0)} + + def signame(sig: int) -> str: + try: + return signal.Signals(sig).name + except ValueError: + return str(sig) + + said = ", ".join(f"{name}({target}, {signame(sig)})" for name, target, sig in made) + print(f"signals_recorded: the pytest process would have sent: {said or 'nothing'}") + bad = [m for m in made if m[1] <= 1 or m[1] in own] + assert not bad, f"a signal would have reached init, a whole group or this process: {bad}" + assert made, "no signal was recorded: the estate's teardown ran after the stubs had gone" + + +@pytest.mark.parametrize("case", list(MALFORMED_PIDS)) +def test_a_malformed_bind_pid_waits_for_the_deadline_then_is_stale(signals_recorded, estate, + case): + """Section 8's :371 (lane 3's rulings, #165 6746215510, point 4, + 6747528875, point 15, and 6751772589, point 17): a `binding` record of + this host and container without a well-formed `pid` and `pidstart` + answers "BINDING IN PROGRESS" with no pid until `deadline_epoch`, the + record unchanged, and after it case 9 with no session test: "no + outcome", `name-drift` and `rc=unknown`. The guard is a test-only copy + that logs each `pid_start_of` it makes; every `kill`, `pkill`, + `killall`, `timeout`, `pgrep` and `lanes-index` call of the guard and of + what it runs is logged by a stub (`T214O_BASH_ENV` and the stand-ins + first on `PATH`), and the stubs send no signal; so the case reads that + no call is made with the record's `pid`. The pytest process sends none + either (`signals_recorded`). The live process the values name is left + for the estate's teardown, whose SIGKILL to it is the one the stubs + record, and it ends on its own, with no signal, once that teardown has + removed the estate's state home, or after 300 s, `_sleeper`'s bound, + whichever is first (T237zzd), or once its parent is no longer pytest + (T237zzg).""" + est = estate() + # T237zzd: THE HOLDER IS LIVE AT THE ESTATE'S TEARDOWN, which signals + # only a live process with the start it had at the scan (`_kill_same`). + # The case ended and reaped it first, so T214u's teardown signalled a + # reaped pid by its number alone, and v3's signalled nothing, which + # `signals_recorded` fails. Not `est.env()`: it is not of the estate's + # state home, so the sweep never waits on it; it ends once that home is + # gone, or after 300 s, `_sleeper`'s bound, whichever is first, or once + # its parent is no longer pytest, as when pytest is killed (T237zzg; + # lane 1's NIT 3): pytest's pid is its `argv[2]`, so a parent gone before + # its first look is seen too. + holder = subprocess.Popen([sys.executable, "-I", "-c", + "import os, sys, time\n" + "end = time.monotonic() + 300\n" + "while (os.path.isdir(sys.argv[1]) and time.monotonic() < end\n" + " and os.getppid() == int(sys.argv[2])):\n" + " time.sleep(0.05)\n", str(est.state_home), str(os.getpid())], + stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, start_new_session=True) + est.spare.append(holder.pid) + start = _stat(holder.pid)["start"] + pid, pidstart = (v.format(live=holder.pid, start=start) for v in MALFORMED_PIDS[case]) + calls = est.ctl / "calls.log" + where = shlex.quote(str(calls)) + est.guard = _bind_copy(est, [(ANCHOR_LOAD, ( + "# T214o's copy: each pid_start_of logged\n" + "eval \"$(declare -f pid_start_of | sed '1s/^pid_start_of /t214o_pid_start_of_shipped /')\"\n" + f"pid_start_of() {{ {{ printf 'pid_start_of'; printf ' %s' \"$@\"; printf '\\n'; }} >> {where}; " + 't214o_pid_start_of_shipped "$@"; }\n' + f"{ANCHOR_LOAD}"))]) + bash_env = _script(est.ctl / "t214o-bash-env.sh", T214O_BASH_ENV, LOG=where) + est.extra["BASH_ENV"] = str(bash_env) + for name in ("kill", "pkill", "killall"): + _script(est.bin / name, T214O_NO_SIGNAL, LOG=where, NAME=shlex.quote(name)) + _script(est.bin / "timeout", T214O_TIMEOUT, LOG=where) + index = est.guard.parent / "lanes-index" + if index.exists(): + real_index = index.rename(est.guard.parent / "lanes-index.t214o-real") + _script(index, T214O_INDEX, LOG=where, PY=shlex.quote(sys.executable), + REAL=shlex.quote(str(real_index))) + real = shutil.which("pgrep") + if real: + _script(est.bin / "pgrep", "#!/bin/sh\n" + f"{{ printf 'pgrep'; printf ' %s' \"$@\"; printf '\\n'; }} >> {where}\n" + f"exec {shlex.quote(real)} \"$@\"\n") + now = time.time() + write_record(est.offer, _binding(est, started=now - 30, deadline=int(now) + 100, + pid=pid, pidstart=pidstart)) + before = est.offer.read_bytes() + hook = est.hook("hello") + assert hook.code == 2 and IN_PROGRESS in hook.err and "its outer's pid not recorded" \ + in hook.err, f"[{case}] pid={pid!r} pidstart={pidstart!r}: {hook!r}" + assert est.offer.read_bytes() == before, "the record changed before its deadline" + write_record(est.offer, _binding(est, started=now - 600, deadline=int(now) - 1, + pid=pid, pidstart=pidstart)) + hook = est.hook("hello") + assert hook.code == 2 and NO_OUTCOME in hook.err \ + and "it recorded no well-formed pid and start for its outer" in hook.err, \ + f"[{case}] pid={pid!r} pidstart={pidstart!r}: {hook!r}" + record = est.record() + assert record.get("mode") == "name-drift" and record.get("rc") == "unknown", record + logged = calls.read_text(encoding="utf-8").splitlines() if calls.exists() else [] + print(f"[{case}] pid={pid!r} pidstart={pidstart!r}; the stubs logged " + f"{len(logged)} call(s), none sent:") + for line in logged: + print(f" {line}") + made = [] + for line in logged: + words = line.split(" ") + if words[0] not in T214O_PID_CALLS: + continue + tail = words[words.index("--") + 1:] if "--" in words else [] + if pid in words[1:] or f"-{pid}" in tail: + made.append(line) + assert not made, f"a kill, pgrep or pid_start_of call was made with pid {pid!r}: {made}" + + +@pytest.mark.parametrize("case", ["was-0644", "new-offers-dir", "failed-write", + "failed-first-write"]) +def test_every_bind_rewrite_is_0600_and_a_failed_one_leaves_the_record(estate, case): + """Section 8's :372 (lane 3's ruling, #165 6746215510, points 1 and 2; + lane 3's Codex review, #165 6877006381, finding 2), under a umask of + 022, so the modes are the guard's own. + + - `[was-0644]`: the record made 0644 before each rewrite of one bind, + and 0600 after it: the hook's answer 2 (the outer held, by a test-only + copy, before its own start), the outer's start, its outcome, the + guard's restored offer after the failure, and choice 1's `mode=allow`. + - `[new-offers-dir]`: the offer makes `offers/`, which was not there, + 0700, and its record 0600. + - `[failed-write]` (K4): the hook's answer-2 rewrite failing at its `mv` + in a test-only copy: the offer kept as it was, byte for byte, no + temporary file in `offers/`, exit 2 with "the bind could not be + recorded", no attempt started, and the window renamed back to `<from>` + after the hook named it `<to>`. + - `[failed-first-write]` (T214s; lane 2, #165 6885568373; lane 5's + `[failed-first-write]`, #165 6884069915): a test-only copy fails each + first write at `/dev/full`. Half (i): the hook's answer-2 rewrite, its + first line, `mode=binding`, failing (`ae702c74`:22453-22459), answers + as `[failed-write]` does, K4's oracle: exit 2 with "the bind could not + be recorded", KEPT and no BINDING, the offer byte for byte, no + temporary file, nothing started, and the window renamed back. Before + T502's part 16 the rewrite lost the line and returned 0. Half (ii), + on the same offer: choice 1's `mode=allow` record failing at its first + write (:22346-22358) exits 2 with "the explicit allow could not be + recorded", the offer byte for byte, no temporary file, and nothing + renamed. Before T502's part 20 it said ALLOWED and the record lost + its mode line.""" + est = estate() + offers = est.offer.parent + mask = os.umask(0o022) + try: + if case == "new-offers-dir": + assert not offers.exists(), f"{offers} was there before the offer" + est.make_offer() + assert _mode_bits(offers) == 0o700 and _mode_bits(est.offer) == 0o600, \ + (oct(_mode_bits(offers)), oct(_mode_bits(est.offer))) + return + if case == "failed-write": + est.guard = _bind_copy(est, [(ANCHOR_MV, _fail_mv("mode=binding"))]) + est.make_offer() + before = est.offer.read_bytes() + calls = len(est.session.tmux_calls()) + hook = est.hook("2") + renames = [c[-1] for c in _renames(est, calls)] + assert hook.code == 2 and "the bind could not be recorded" in hook.err \ + and KEPT in hook.err and BINDING not in hook.err, repr(hook) + assert est.offer.read_bytes() == before, \ + f"the failed rewrite changed the offer: {est.record()}" + assert not _temporaries(est), f"the failed rewrite left {_temporaries(est)}" + assert not list(offers.glob(f"{est.sid}.bind.*")) and not est.starts(), \ + "an attempt started after its record could not be written" + assert TO in renames and renames[-1] == FROM, \ + f"the window was not named {TO} and then renamed back to {FROM}: {renames}" + return + if case == "failed-first-write": + est.guard = _bind_copy(est, [(ANCHOR_FIRST_WRITE, f"{ANCHOR_FIRST_WRITE} >/dev/full"), + (ANCHOR_ALLOW_WRITE, f"{ANCHOR_ALLOW_WRITE} >/dev/full")]) + est.make_offer() + before = est.offer.read_bytes() + calls = len(est.session.tmux_calls()) + hook = est.hook("2") + renames = [c[-1] for c in _renames(est, calls)] + assert hook.code == 2 and "the bind could not be recorded" in hook.err \ + and KEPT in hook.err and BINDING not in hook.err, \ + f"half (i), answer 2's rewrite failing at its first write: {hook!r}" + assert est.offer.read_bytes() == before, \ + f"half (i): the failed first write changed the offer: {est.record()}" + assert not _temporaries(est), f"half (i) left {_temporaries(est)}" + assert not list(offers.glob(f"{est.sid}.bind.*")) and not est.starts(), \ + "half (i): an attempt started after its record could not be written" + assert TO in renames and renames[-1] == FROM, \ + f"half (i): the window was not named {TO} and then renamed back to {FROM}: {renames}" + calls = len(est.session.tmux_calls()) + hook = est.hook("1") + assert hook.code == 2 and "the explicit allow could not be recorded" in hook.err \ + and "ALLOWED:" not in hook.err, \ + f"half (ii), choice 1's allow failing at its first write: {hook!r}" + assert est.offer.read_bytes() == before, \ + f"half (ii): the failed allow changed the offer: {est.record()}" + assert not _temporaries(est), f"half (ii) left {_temporaries(est)}" + assert not _renames(est, calls), f"half (ii) renamed the window: {_renames(est, calls)}" + return + est.guard = _bind_copy(est, [(ANCHOR_OUTER_START, ( + f"{_hold_sh(est, 'start')}\n {ANCHOR_OUTER_START}"))]) + est.set("hold", 60) + est.set("rc", 1) + est.make_offer() + modes = {} + os.chmod(est.offer, 0o644) + est.answer_2() + held = _until(lambda: (est.ctl / "start.held").exists(), 30) + at_hold = est.record() + modes["the hook's answer 2"] = _mode_bits(est.offer) + os.chmod(est.offer, 0o644) + est.set("start.release") + assert held and at_hold.get("mode") == "binding" and "pid" not in at_hold, \ + f"the outer was not held before its start: {at_hold}" + est.outer() + modes["the outer's start"] = _mode_bits(est.offer) + assert _until(est.starts, 30), "the stand-in lane-start never started" + os.chmod(est.offer, 0o644) + est.release() + assert est.ended()["mode"] == "bind-failed", est.record() + modes["the outer's outcome"] = _mode_bits(est.offer) + os.chmod(est.offer, 0o644) + hook = est.hook("after the failure") + assert hook.code == 2 and est.record().get("mode") == "name-drift", repr(hook) + modes["the guard's restored offer"] = _mode_bits(est.offer) + os.chmod(est.offer, 0o644) + hook = est.hook("1") + assert hook.code == 2 and est.record().get("mode") == "allow", repr(hook) + modes["choice 1's allow"] = _mode_bits(est.offer) + assert all(bits == 0o600 for bits in modes.values()), \ + {name: oct(bits) for name, bits in modes.items()} + finally: + os.umask(mask) + + +# ------------------------------------- T214v and T214w: ruling 5's (A), the hook's writes +# +# NO REWRITE CREATES A RECORD, AND THE HOOK'S WRITES GO ONLY TO THE OFFER IT +# ANSWERED (T214v and T214w; lane 3's ruling, opensoft/openRepoTools#165 +# 6885771975, ruling 5, with (A) for the hook's answer 2; lane 5's rule for +# the hook's own writes, #165 6886054653, which lane 3 confirmed, #165 +# 6886113842, choice 1's mirror of (A) among it; T502's parts 22 to 26, +# `2497b864`, and part 32, `820bbf11`, at its head `6253b0ed`; spec#47's +# draft 17 `8bc6b29e`, section 5's case 1 and choice 1, and section 7; lane +# 5's check of these ids and its additions, #165 6888777622). Each case +# holds the hook in a test-only copy (point 23) before one of its writes on +# the offer, changes the record there, and releases the hold: the window is +# made by the hold, never by a sleep. + +#: THE HOLDS' ANCHORS, each text that `lanes-edit.sh` holds once at T502's +#: part 21 `beeae571`, at part 26 `2497b864` and at `6253b0ed`: +#: - the head copy's test that `.head` gave it a key to copy, just before its +#: write (`guard_bind_head_copy`), so a hold there is reached only where +#: the head copy writes (lane 5's precondition A; d17:377); +#: - the head copy's definition and its one call in `guard_answer`, through +#: which the copy logs the head copy's result, so a case knows which write +#: met the change; +#: - answer 2's bound, after the head copy and before its rewrite to +#: `binding`; +#: - choice 1's temporary file: a hold just before it is before the +#: temporary file and before `guard_offer_still` (6253b0ed:22809), never +#: between that test and the `mv`, the window draft 17 accepts (d17:148). +ANCHOR_HEAD_COPY = '[ "${#ghc_kv[@]}" -gt 0 ] || return 0' +ANCHOR_HEAD_COPY_DEF = 'guard_bind_head_copy() {' +ANCHOR_HEAD_COPY_CALL = 'guard_bind_head_copy "$ga_f"' +ANCHOR_ANSWER_2_BOUND = 'ga_bs="$(guard_bind_bound_s "$ga_f")"' +ANCHOR_ALLOW_TEMP = ("ga_t=\"$(umask 077; mktemp \"${ga_f%/*}/.${ga_f##*/}.XXXXXX\" " + "2>/dev/null || printf '')\"") +#: (A)'s words, and choice 1's mirror of them (`guard_answer_moved`, +#: 6253b0ed:22675-22697); the I/O paths' words, which say the offer is +#: KEPT (:22915, :22945) or that the allow could not be recorded (:22820); +#: and the outer's start, which no case here may reach (:22999, :23001). +DROPPED_BIND = "the offer was dropped before the bind could be recorded, so the bind was NOT started" +CHANGED_BIND = ("was changed before the bind could be recorded (it is another offer now, not " + "the one that was answered), so the bind was NOT started") +NO_OUTER = "and no outer was started" +BIND_IO = "could not be recorded in" +DROPPED_ALLOW = ("the offer was dropped before the allow could be recorded, so the mismatch " + "remains unapproved. Nothing was renamed or written") +ALLOW_IO = "the explicit allow could not be recorded at" +ALLOWED = "ALLOWED:" + + +def _renamed_back(lane: str) -> str: + """`guard_window_back`'s note (6253b0ed:22216), only as far as lane 5 + asks it asserted: the clause after it, "so the offer it keeps is still + this window's", is lane 5's to reword for (A) (#165 6888777622).""" + return f"This window has been renamed back to {lane}, the lane it was before the answer `2`" + + +def _answer_preconditions(est: Estate) -> None: + """Lane 5's precondition B (#165 6888777622): the stand-in `tmux` first + on the hook's `PATH`, so the rename to `<to>` and back is made, and the + stand-in `lane-start` executable at `LANES_LANE_START`, so answer 2 gets + past its test of it (6253b0ed:22836-22837) to the rename.""" + env = est.env() + first = env["PATH"].split(os.pathsep)[0] + assert first == str(est.session.directory) and os.access(est.session.tmux, os.X_OK), \ + f"the stand-in tmux is not first on PATH: {first}, {est.session.tmux}" + start = Path(env.get("LANES_LANE_START", "")) + assert start.is_file() and os.access(start, os.X_OK), \ + f"the stand-in lane-start is not executable at LANES_LANE_START: {start}" + + +def _head_copy_logged(est: Estate) -> list: + """The edits that make a test-only copy log the head copy's result, 0, + 1 or 2, to `<ctl>/head-copy.rc`, through a wrapper at its one call: so a + case knows whether the head copy's own rewrite met the change (2), or + wrote nothing (0) and left it to the rewrite to `binding`.""" + rc = shlex.quote(str(est.ctl / "head-copy.rc")) + wrapper = ('t214v_head_copy() { t214v_hrc=0; guard_bind_head_copy "$@" || t214v_hrc=$?; ' + f'echo "$t214v_hrc" > {rc}; return "$t214v_hrc"; }}') + return [(ANCHOR_HEAD_COPY_DEF, f"{wrapper}\n{ANCHOR_HEAD_COPY_DEF}"), + (ANCHOR_HEAD_COPY_CALL, 't214v_head_copy "$ga_f"')] + + +def _estate_on_the_stub(estate, tmp_path, edits_of) -> Estate: + """Case 22's `[answer-2]` estate (`_bound_through_answer_2_on_the_stub`), + with the stub's constants as T207 writes them, so its `.head` gives + `c=2`, `n_a=1` and `w_s_ms=0`, each a whole number, and the hook's head + copy writes (lane 5's precondition A): the contract's stub `lanes-index` + beside a copy of `lanes-edit.sh`, `repos.tsv` and `lane-start`, and a + configuration naming the store. The copy takes `edits_of(est)`'s + (anchor, text) pairs, each made once, as `_bind_copy` makes them.""" + code = tmp_path / "code" + code.mkdir() + for name in ("lanes-edit.sh", "repos.tsv", "lane-start"): + shutil.copy2(REPO / name, code / name) + est = estate(guard=code / "lanes-edit.sh") + copy = code / "lanes-edit.sh" + text = copy.read_text(encoding="utf-8") + for anchor, new in edits_of(est): + text, made = re.subn(re.escape(anchor), lambda _found, new=new: new, text) + assert made == 1, f"the test-only copy's anchor was found {made} times, not once: {anchor}" + copy.write_text(text, encoding="utf-8") + contract_stub(code, register={ + "lanes/LANES.md": (est.wip / "lanes" / "LANES.md").read_text(encoding="utf-8")}) + conf = tmp_path / "lanes-index.conf" + conf.write_text(f"register_url=postgresql:///register?host={tmp_path}/sock\n", + encoding="utf-8") + est.extra["LANES_INDEX_CONFIG"] = str(conf) + return est + + +def _answer_held(est: Estate, prompt: str, hold: str, change): + """The hook answering `prompt`, from a test-only copy that holds at + `hold` (`_hold_sh`), run in a thread with a 30 s timeout, so that the + hold is not cut short as the hook's own 5 s would cut it. At the hold, + `change()` runs and its value is kept; the hold is released whatever + `change` does. Returns the hook and that value.""" + box = {} + thread = threading.Thread(target=lambda: box.update(hook=est.hook(prompt, timeout=30.0)), + daemon=True) + thread.start() + held = _until(lambda: (est.ctl / f"{hold}.held").exists(), 30) + seen = None + try: + if held: + seen = change() + finally: + est.set(f"{hold}.release") + thread.join(45) + assert held, f"the hook never came to its hold at its {hold}: {box.get('hook')!r}" + assert "hook" in box, f"the hook did not end within 45 s of its release at its {hold}" + return box["hook"], seen + + +def _other_binding(est: Estate): + """ANOTHER INVOCATION'S `binding`, put in the offer's place as a writer + puts a record (`write_record`): a live process of its own session, with + its own start token, which the estate stops at its close (`spare`), as + `[not-its-own]`'s is; a `deadline_epoch` ahead, and the guard's own + `host` and `container`, so the guard's site answers it in progress, not + stale and not as another host's (lane 5, #165 6888777622); and its + attempt's `.bind.1.out`, which its `out` names. Returns the record's + bytes, that `.out` and its bytes.""" + other = _sleeper() + est.spare.append(other.pid) + now = time.time() + write_record(est.offer, _binding(est, started=now, pid=other.pid, + pidstart=_stat(other.pid)["start"])) + record = est.record() + assert int(record["deadline_epoch"]) > now and record.get("host") == HOST \ + and record.get("container") == CONTAINER, f"the other binding is not live here: {record}" + out = Path(record["out"]) + out.write_text("the other bind's output, which no answer may touch\n", encoding="utf-8") + out.chmod(0o600) + return est.offer.read_bytes(), out, out.read_bytes() + + +def _guard_bind_processes(est: Estate) -> list: + """Every live process whose argv holds `guard-bind` and this estate's + uuid: an outer this answer started.""" + found = [] + for entry in Path("/proc").iterdir(): + if not entry.name.isdigit(): + continue + try: + argv = (entry / "cmdline").read_bytes().split(b"\0") + except OSError: + continue + if b"guard-bind" in argv and est.sid.encode() in argv: + found.append(int(entry.name)) + return found + + +def _nothing_new(est: Estate, before: set, made: set, who: str) -> None: + """After the hook's exit, `offers/` holds nothing that was not there + before it, or that the case put there itself: no temporary file, no + record made and no `.bind.<N>.out`; and no outer was started: no + `lane-start` start and no `guard-bind` process (lane 5, #165 + 6888777622).""" + offers = est.offer.parent + new = sorted(set(os.listdir(offers)) - before - made) if offers.is_dir() else [] + assert not new, f"{who} left new files in offers/: {new}" + assert not est.starts() and not _guard_bind_processes(est), \ + f"{who} started an outer: {est.starts()}, {_guard_bind_processes(est)}" + + +#: T214x: THE OTHER RECORDS A HOLD CAN MEET IN THE OFFER'S PLACE (lane 5's +#: list of what T214v's and T214w's first ids leave out, #165 6888777622), by +#: id, each answered once by `guard_answer_moved` (6dd8bbbd:22904-22952): +#: another invocation's `bound` (heard as MOVED) or `bind-failed` (case 6), +#: another prompt's allowance (3, judged afresh), and a record of another mode. +IN_PLACE = {"bound-at-its-rewrite": "bound", "bind-failed-at-its-rewrite": "bind-failed", + "allow-at-its-rewrite": "allow", "another-mode-at-its-rewrite": "weird", + "bound-before-its-mv": "bound", "bind-failed-before-its-mv": "bind-failed", + "allow-before-its-mv": "allow", "another-mode-before-its-mv": "weird"} +#: Their words: case 5's MOVED and its last line (6dd8bbbd:22710, :22718), +#: case 6's failure (:22726), the allowance's pass (`guard_allow_pass`, +#: :21921-21925), the default rename-back note's last clause, which says an +#: offer is kept (:22372), and the why of the bind that failed. +MOVED_TO = f"MOVED: this window is lane {TO}, bound to this session (" +HEARS = "This prompt was NOT sent: it is the one that hears how the bind ended" +FAILED_TO = f"THE BIND TO LANE {TO} FAILED (exit 1)" +OTHER_WHY = "the other bind's stand-in failed" +ALLOW_PASS = ("WARNING: this lane/session name mismatch was explicitly allowed for this " + "transcript") +OFFER_KEPT_NOTE = "so the offer it keeps is still this window's" +NOT_STARTED = "so the bind was NOT started" +UNAPPROVED = "so the mismatch remains unapproved" + + +def _put_in_place(est: Estate, kind: str) -> bytes: + """T214x: ANOTHER RECORD IN THE OFFER'S PLACE, put there at the hold as + a writer puts a record (`write_record`), for this offer's two lanes, and + its bytes: + + - `bound`: another answer 2's bind, ended `bound` (`rc=0`, `ended_utc`); + - `bind-failed`: its attempt 1, ended `bind-failed` (`rc=1`, a `why`); + - `allow`: another prompt's choice 1, the allowance as `guard_answer` + writes it (6dd8bbbd:23130-23135), for this session and this transcript; + - `weird`: the offer itself, its `mode` line saying `weird`.""" + now = time.time() + if kind in ("bound", "bind-failed"): + ended = ["rc=0"] if kind == "bound" else ["rc=1", f"why={OTHER_WHY}"] + lines = ([f"mode={kind}"] + _binding(est, started=now - 60)[1:] + + ended + [f"ended_utc={_utc(now)}"]) + elif kind == "allow": + lines = ["mode=allow", f"from={FROM}", f"to={est.to}", + f"session={read_record(est.offer)['session']}", f"uuid={est.sid}", + f"utc={_utc(now)}"] + else: + text, n = re.subn(r"(?m)^mode=name-drift$", f"mode={kind}", + est.offer.read_text(encoding="utf-8"), count=1) + assert n == 1, f"the offer holds no mode=name-drift line: {est.offer.read_text()!r}" + lines = text.splitlines() + write_record(est.offer, lines) + return est.offer.read_bytes() + + +def _changed_to(est: Estate, kind: str, what: str) -> str: + """`guard_answer_moved`'s why for a record of another mode, `<what>` being + `bind` or `allow` (6dd8bbbd:22928-22929; d18, section 5).""" + return (f"the offer at {est.offer} was changed before the {what} could be recorded " + f"(it says mode={kind} now)") + + +def _in_place_answered(est: Estate, hook, kind: str, installed: bytes, renames: list, + answer: str) -> None: + """T214x: the answer `answer` (`2`, which renamed the window to `TO` + before its hold, or `1`, which renames nothing) met another + invocation's `bound` or `bind-failed`, or another prompt's allowance, + in the offer's place, and wrote nothing over it (d18, section 5): + + - `bound`: `guard_bind_site`'s case 5, as the guard's first read hears + it: exit 2, MOVED for this session, "This prompt was NOT sent: it is + the one that hears how the bind ended", the record dropped as the one + loaded; nothing renamed back. + - `bind-failed`: case 6: exit 2, "THE BIND TO LANE `TO` FAILED (exit + 1)", the record rewritten to the question with `bind=1`, the offer + KEPT, and the window renamed back to `FROM` by case 6 itself. + - `allow`: `guard_answer` answers 3 and the prompt is judged afresh: the + allowance still fits, so it passes with its warning, exit 0, the + allowance left byte for byte. Answer 2 renames the window back first, + in `none`'s words, not the default's, which says an offer is kept + (part 48, `3e6dc617`; 6dd8bbbd:22914-22918). + + In none of them is (A) or its mirror said, BINDING or ALLOWED printed.""" + err = hook.err + who = f"answer {answer}" + assert "BINDING:" not in err and ALLOWED not in err, \ + f"{who} wrote its own record over another's {kind}: {hook!r}" + assert NOT_STARTED not in err and UNAPPROVED not in err, \ + f"{who} refused with (A) or its mirror where the record in place said {kind}: {hook!r}" + if kind == "bound": + assert not hook.killed and hook.code == 2, f"{who} did not exit 2: {hook!r}" + assert MOVED_TO + f"{est.sid}) at " in err and HEARS in err, \ + f"{who} did not hear the bound record in place as MOVED: {hook!r}" + assert not est.offer.exists(), f"case 5 did not drop the bound it heard: {est.record()}" + assert renames == ([TO] if answer == "2" else []), \ + f"tmux saw {renames}, where case 5 renames nothing back" + elif kind == "bind-failed": + assert not hook.killed and hook.code == 2, f"{who} did not exit 2: {hook!r}" + assert FAILED_TO in err and KEPT in err and _renamed_back(FROM) in err, \ + f"{who} did not answer the bind-failed record in place as case 6: {hook!r}" + record = est.record() + assert record.get("mode") == "name-drift" and record.get("bind") == "1" \ + and record.get("from") == FROM and record.get("to") == TO, \ + f"case 6 did not rewrite the record to the question with bind=1: {record}" + assert renames == ([TO, FROM] if answer == "2" else [FROM]), \ + f"tmux saw {renames}, where case 6 renames the window back to {FROM}" + else: + assert not hook.killed and hook.code == 0 and ALLOW_PASS in err, \ + f"{who} did not pass the prompt on the allowance in place, with its warning: {hook!r}" + assert est.offer.read_bytes() == installed, \ + f"{who} wrote over the allowance in place: {est.record()}" + if answer == "2": + back = _renamed_back(FROM) + assert back in err and OFFER_KEPT_NOTE not in err \ + and err.index(back) < err.index(ALLOW_PASS), \ + f"answer 2 did not rename the window back first, in none's words: {hook!r}" + assert renames == [TO, FROM], f"tmux saw {renames}, not {TO} and then {FROM}" + else: + assert renames == [], f"choice 1 renamed the window: {renames}" + + +@pytest.mark.parametrize("case", ["gone-at-its-head-copy", "gone-at-its-rewrite", + "another-offer-at-its-rewrite", "binding-at-its-rewrite", + "bound-at-its-rewrite", "bind-failed-at-its-rewrite", + "allow-at-its-rewrite", "another-mode-at-its-rewrite"]) +def test_answer_2_binds_nothing_where_its_offer_is_gone_or_no_longer_the_one_answered( + estate, tmp_path, case): + """T214v, ruling 5's (A) for the hook's answer 2, and the hook's writes + on the offer it answered (draft 17's section 5, case 1; section 7). The + hook's head copy of `.head`'s `c`, `n_a` and `w_s_ms` and its rewrite to + `binding` each run only on a record that is there, still says + `name-drift` and is still the offer that was answered, by its `from`, + `to`, `session` and `utc` (`--offer` with `guard_answer_match`; + 6253b0ed:20744, :22908-22913, :22935-22943). Where it is not, they write + nothing, and the record's mode is read once and answered for + (`guard_answer_moved`, :22641-22700). With the stand-in `tmux` and + `lane-start` in place (lane 5's precondition B), a test-only copy holds + the hook after it has renamed the window to `<to>`, and logs what the + head copy returned; at the hold the record is still the offer answered. + Each id exits 2, but `[allow-at-its-rewrite]`, which exits 0, leaves + nothing new in `offers/` and starts no outer. + + - `[gone-at-its-head-copy]`: on the contract's stub, whose `.head` gives + the head copy keys to write, held just before that write, and the + offer removed there; the head copy's own rewrite returns 2 (lane 5's + precondition A). (A): "the offer was dropped before the bind could be + recorded, so the bind was NOT started: this window has NOT moved to + `<to>` (this answer renamed it, and it was renamed back to `<from>`) + ... and no outer was started", after "This window has been renamed + back to `<from>`, the lane it was before the answer `2`"; no `KEPT`, + no `BINDING:` and no "could not be recorded in"; no record made; tmux + renamed to `<to>`, then back to `<from>`. At `beeae571` the head copy + made a record of `c`, `n_a` and `w_s_ms` alone, the rewrite then wrote + `binding` with no `from` and no `to`, and an outer started. + - `[gone-at-its-rewrite]`: with no `.head`, so the head copy writes + nothing (0), held after it and before the rewrite to `binding`, the + offer removed there. (A), as above. At `beeae571` the rewrite made the + record again with its own keys, and an outer started. + - `[another-offer-at-its-rewrite]`: the same hold, with the offer, which + carries a `utc` line, put back by a temporary file and a rename with a + later `utc`: a re-made offer, not the one answered. (A) with "the + offer at `<file>` was changed before the bind could be recorded (it is + another offer now, not the one that was answered)"; that offer left + byte for byte. At `beeae571`, and at `2497b864` before part 32, the + rewrite wrote `binding` over it. + - `[binding-at-its-rewrite]`: the same hold, with another invocation's + live `binding` put in the offer's place, its deadline ahead, on the + guard's own host and container, with its own `.bind.1.out`. + `guard_bind_site`'s answer, as the guard's first read gives it: that + record and its `.out` left byte for byte; "BINDING IN PROGRESS" and + not "BINDING: this window is now named"; tmux renamed to `<to>` only, + nothing renamed back (section 5). At `beeae571` the rewrite wrote this + answer's `binding` over it and started a second outer. + + T214x, the records lane 5 listed as not yet covered (#165 6888777622), + each put in the offer's place at the same hold (`_put_in_place`) and + answered as `_in_place_answered` says, by draft 18's section 5 at + `f8e5cfa8` and `guard_answer_moved` at T502's `6dd8bbbd`:22904-22952: + + - `[bound-at-its-rewrite]`: another invocation's `bound`: MOVED, the + record dropped, tmux renamed to `<to>` only. + - `[bind-failed-at-its-rewrite]`: another invocation's `bind-failed`: + case 6, the record back to the question with `bind=1`, the offer + KEPT, tmux renamed to `<to>` and back to `<from>` by case 6. + - `[allow-at-its-rewrite]`: another prompt's allowance: the window + renamed back first, not in the default form's words, then the prompt + passed on the allowance with its warning, exit 0. + - `[another-mode-at-its-rewrite]`: the offer saying `mode=weird`: (A), + with "the offer at `<file>` was changed before the bind could be + recorded (it says mode=weird now)", that record left byte for byte.""" + if case == "gone-at-its-head-copy": + hold = "head-copy" + est = _estate_on_the_stub(estate, tmp_path, lambda e: _head_copy_logged(e) + [( + ANCHOR_HEAD_COPY, f"{ANCHOR_HEAD_COPY}\n {_hold_sh(e, hold)}")]) + else: + hold = "rewrite" + est = estate() + est.guard = _bind_copy(est, _head_copy_logged(est) + [(ANCHOR_ANSWER_2_BOUND, ( + f"{_hold_sh(est, hold)}\n {ANCHOR_ANSWER_2_BOUND}"))]) + _answer_preconditions(est) + est.make_offer() + offers = est.offer.parent + offer = est.offer.read_bytes() + assert re.search(rb"(?m)^utc=", offer), f"the offer carries no utc= line: {offer!r}" + before = set(os.listdir(offers)) + calls = len(est.session.tmux_calls()) + made = set() + + def change(): + at_hold = est.offer.read_bytes() if est.offer.exists() else None + renamed = [c[-1] for c in _renames(est, calls)] + other = None + if case.startswith("gone-"): + est.offer.unlink() + elif case == "another-offer-at-its-rewrite": + text, n = re.subn(r"(?m)^utc=.*$", f"utc={_utc(time.time() + 60)}", + offer.decode("utf-8"), count=1) + assert n == 1, f"the offer holds no utc= line: {offer!r}" + write_record(est.offer, text.splitlines()) + other = (est.offer.read_bytes(), None, None) + elif case in IN_PLACE: + other = (_put_in_place(est, IN_PLACE[case]), None, None) + else: + other = _other_binding(est) + made.add(other[1].name) + return at_hold, renamed, other + + hook, (at_hold, renamed, other) = _answer_held(est, "2", hold, change) + err = hook.err + renames = [c[-1] for c in _renames(est, calls)] + rc_file = est.ctl / "head-copy.rc" + head_copy = rc_file.read_text(encoding="utf-8").strip() if rc_file.exists() else None + assert at_hold == offer, f"the record at the hook's {hold} was not the offer answered: {at_hold!r}" + assert TO in renamed, f"the window was not named {TO} before the hook's {hold}: {renamed}" + site = IN_PLACE.get(case) in ("bound", "bind-failed", "allow") + if not site: + assert not hook.killed and hook.code == 2, f"answer 2 did not exit 2: {hook!r}" + if site: + _in_place_answered(est, hook, IN_PLACE[case], other[0], renames, "2") + elif case == "binding-at-its-rewrite": + installed, out, out_bytes = other + assert est.offer.read_bytes() == installed, \ + f"another invocation's bind record did not survive answer 2: {est.record()}\n{err}" + assert out.exists() and out.read_bytes() == out_bytes, \ + f"another invocation's {out.name} did not survive answer 2" + assert IN_PROGRESS in err and BINDING not in err, \ + f"answer 2 did not give guard_bind_site's answer for the bind record at its rewrite: {hook!r}" + assert renames == [TO], \ + f"tmux saw {renames}, where section 5 has this answer rename to {TO} and nothing back" + else: + why = {"another-offer-at-its-rewrite": CHANGED_BIND, + "another-mode-at-its-rewrite": f"{_changed_to(est, 'weird', 'bind')}, {NOT_STARTED}", + }.get(case, DROPPED_BIND) + back = (f"this window has NOT moved to {TO} (this answer renamed it, and it was renamed " + f"back to {FROM})") + assert why in err and "BINDING:" not in err, \ + f"answer 2 did not refuse with (A) where its offer was {case}: {hook!r}" + assert "KEPT" not in err and BIND_IO not in err, \ + f"answer 2 refused on its I/O path, or said the offer is KEPT: {hook!r}" + assert _renamed_back(FROM) in err and back in err and NO_OUTER in err, repr(hook) + assert renames == [TO, FROM], f"tmux saw {renames}, not {TO} and then {FROM}" + if case.startswith("gone-"): + assert not est.offer.exists(), \ + f"answer 2 made a record where its offer was gone: {est.record()}" + else: + assert est.offer.read_bytes() == other[0], \ + f"answer 2 wrote over an offer that is not the one answered: {est.record()}" + if case == "gone-at-its-head-copy": + assert head_copy == "2", \ + f"the head copy's own rewrite did not meet the offer gone: it returned {head_copy!r}" + else: + assert head_copy == "0", \ + f"the head copy did not write nothing before the hold at the rewrite: {head_copy!r}" + _nothing_new(est, before, made, "answer 2") + + +@pytest.mark.parametrize("case", ["gone-before-its-mv", "binding-before-its-mv", + "bound-before-its-mv", "bind-failed-before-its-mv", + "allow-before-its-mv", "another-mode-before-its-mv"]) +def test_choice_1_allows_nothing_where_its_offer_is_gone_or_no_longer_the_one_answered( + estate, case): + """T214w, choice 1's mirror of (A) (lane 3's confirmation, #165 + 6886113842; draft 17's section 5, "Choice 1, where the offer is gone"). + Just before its `mv`, choice 1's `mode=allow` record tests that the + offer answered is still there, still says `name-drift` and is still the + one answered (`guard_offer_still`, 6253b0ed:22706, :22809). Where it is + not, its temporary file is removed, nothing is written, and the record's + mode is read once and answered for (`guard_answer_moved`, :22817). A + test-only copy holds choice 1 before its temporary file, so before that + test, never between it and the `mv` (d17:148; lane 5, #165 6888777622, + whose names these ids are). Each id exits 2, but `[allow-before-its-mv]`, + which exits 0; renames nothing, but `[bind-failed-before-its-mv]`, whose + case 6 renames the window back to `<from>`; leaves nothing new in + `offers/` and starts no outer. + + - `[gone-before-its-mv]`: the offer removed at the hold. "the offer was + dropped before the allow could be recorded, so the mismatch remains + unapproved. Nothing was renamed or written"; no ALLOWED, and not the + I/O path's "the explicit allow could not be recorded at" (:22820); no + record made. At `beeae571` the write and its `mv` made an `allow` + record, and the hook said ALLOWED. + - `[binding-before-its-mv]`: another invocation's live `binding` put in + the offer's place, its deadline ahead, on the guard's own host and + container, with its own `.bind.1.out`. `guard_bind_site`'s answer: + that record and its `.out` left byte for byte; "BINDING IN PROGRESS", + and no ALLOWED and no "BINDING: this window is now named". At + `beeae571` the `allow` record was written over it, and its sweep, + `rm -f "$ga_f".bind.*` (:22376), removed the other's `.out`. + + T214x, the records lane 5 listed as not yet covered (#165 6888777622), + each put in the offer's place at the same hold (`_put_in_place`) and + answered as `_in_place_answered` says, by draft 18's section 5 at + `f8e5cfa8` and `guard_answer_moved` at T502's `6dd8bbbd`:22904-22952, + choice 1 itself renaming nothing and writing nothing: + + - `[bound-before-its-mv]`: another invocation's `bound`: MOVED, the + record dropped, nothing renamed. + - `[bind-failed-before-its-mv]`: another invocation's `bind-failed`: + case 6, the record back to the question with `bind=1`, the offer + KEPT, the window renamed to `<from>` by case 6, the one rename here. + - `[allow-before-its-mv]`: another prompt's allowance: the prompt + passed on it with its warning, exit 0, nothing renamed. + - `[another-mode-before-its-mv]`: the offer saying `mode=weird`: the + mirror of (A), "the offer at `<file>` was changed before the allow + could be recorded (it says mode=weird now), so the mismatch remains + unapproved. Nothing was renamed or written"; that record left byte + for byte.""" + est = estate() + est.guard = _bind_copy(est, [(ANCHOR_ALLOW_TEMP, ( + f"{_hold_sh(est, 'choice-1')}\n {ANCHOR_ALLOW_TEMP}"))]) + _answer_preconditions(est) + est.make_offer() + offers = est.offer.parent + offer = est.offer.read_bytes() + before = set(os.listdir(offers)) + calls = len(est.session.tmux_calls()) + made = set() + + def change(): + at_hold = est.offer.read_bytes() if est.offer.exists() else None + if case == "gone-before-its-mv": + est.offer.unlink() + return at_hold, None + if case in IN_PLACE: + return at_hold, (_put_in_place(est, IN_PLACE[case]), None, None) + other = _other_binding(est) + made.add(other[1].name) + return at_hold, other + + hook, (at_hold, other) = _answer_held(est, "1", "choice-1", change) + err = hook.err + assert at_hold == offer, f"the record at choice 1's hold was not the offer answered: {at_hold!r}" + site = IN_PLACE.get(case) in ("bound", "bind-failed", "allow") + if not site: + assert not hook.killed and hook.code == 2, f"choice 1 did not exit 2: {hook!r}" + if site: + _in_place_answered(est, hook, IN_PLACE[case], other[0], + [c[-1] for c in _renames(est, calls)], "1") + elif case == "another-mode-before-its-mv": + why = f"{_changed_to(est, 'weird', 'allow')}, {UNAPPROVED}. Nothing was renamed or written" + assert why in err and ALLOWED not in err, \ + f"choice 1 did not refuse with (A)'s mirror where the offer said mode=weird: {hook!r}" + assert ALLOW_IO not in err, f"choice 1 refused on its I/O path: {hook!r}" + assert est.offer.read_bytes() == other[0], \ + f"choice 1 wrote over a record of another mode: {est.record()}" + elif case == "gone-before-its-mv": + assert DROPPED_ALLOW in err and ALLOWED not in err, \ + f"choice 1 did not refuse with (A)'s mirror where its offer was gone: {hook!r}" + assert ALLOW_IO not in err, f"choice 1 refused on its I/O path: {hook!r}" + assert not est.offer.exists(), \ + f"choice 1 made a record where its offer was gone: {est.record()}" + else: + installed, out, out_bytes = other + assert out.exists() and out.read_bytes() == out_bytes, \ + f"another invocation's {out.name} did not survive choice 1" + assert est.offer.read_bytes() == installed, \ + f"another invocation's bind record did not survive choice 1: {est.record()}\n{err}" + assert IN_PROGRESS in err and ALLOWED not in err and BINDING not in err, \ + f"choice 1 did not give guard_bind_site's answer for the bind record: {hook!r}" + if IN_PLACE.get(case) != "bind-failed": + assert not _renames(est, calls), f"choice 1 renamed the window: {_renames(est, calls)}" + _nothing_new(est, before, made, "choice 1") + + +#: T214x's back-out anchors, each found once in `lanes-edit.sh` at T502's +#: `6253b0ed` and `6dd8bbbd`: the fork of the bind's child, which the +#: test-only copy makes start nothing (a child that could not be started: +#: its subshell prints no pid), and the case on that pid, before which the +#: copy holds, after the rewrite to `binding` and before the back-out. +ANCHOR_FORK = 'ga_p="$( ( umask 077' +ANCHOR_NO_CHILD = 'case "$ga_p" in' +#: The back-out's refusal where the record is gone or no longer `binding` +#: (6dd8bbbd:23373-23374; d18, section 5). +NO_CHILD = "the bind's child could not be started, so " +BACKED_OUT_NOTHING = ("and NOTHING has been written; the offer was dropped or changed " + "meanwhile, so there is none of this answer's to keep") + + +@pytest.mark.parametrize("case", ["gone-at-its-back-out", "not-binding-at-its-back-out"]) +def test_answer_2s_back_out_writes_nothing_where_its_binding_is_gone_or_no_longer_binding( + estate, case): + """T214x, THE HOOK'S BACK-OUT under lane 3's ruling 5, "No rewrite + creates a record" (opensoft/openRepoTools#165 6885771975), the last of + the cases lane 5 listed as not yet covered (#165 6888777622). Where no + child started, answer 2 puts the record back to the question, by a + rewrite that runs only on a record still saying `binding` (`--binding`, + 6dd8bbbd:23338-23344). Where the record is gone or no longer `binding`, + there is nothing of this answer's to back out: nothing is written, the + window is renamed back first in `guard_window_back`'s `none` form, and + the refusal is "the bind's child could not be started, so this window + has NOT moved to `<to>` (it was renamed back to `<from>`) and NOTHING has + been written; the offer was dropped or changed meanwhile, so there is + none of this answer's to keep" (:23353-23374; draft 18's section 5 at + `f8e5cfa8`, "The hook's back-out, where no child started"). + + A test-only copy (point 23) makes the fork start nothing, so the + subshell prints no pid (`ANCHOR_FORK`), and holds before the case on + that pid (`ANCHOR_NO_CHILD`), with the stand-in `tmux` and `lane-start` + in place (lane 5's precondition B). At the hold the record is this + answer's `binding`, attempt 1 with no `pid`, and the window is named + `<to>`; the case changes the record and releases the hold. + + - `[gone-at-its-back-out]`: the record removed there; none is made. + - `[not-binding-at-its-back-out]`: the offer made again in its place, + with a later `utc`; it is left byte for byte. + + Each id exits 2 with that refusal, says no KEPT, no "still says + binding" and no BINDING, renames the window to `<to>` and back to + `<from>`, not in the default form's words, which say an offer is kept, + leaves nothing new in `offers/` and starts no outer.""" + est = estate() + est.guard = _bind_copy(est, [ + (ANCHOR_FORK, ANCHOR_FORK.replace("( umask", "( exit 1; umask")), + (ANCHOR_NO_CHILD, f"{_hold_sh(est, 'back-out')}\n {ANCHOR_NO_CHILD}")]) + _answer_preconditions(est) + est.make_offer() + offers = est.offer.parent + offer = est.offer.read_bytes() + assert re.search(rb"(?m)^utc=", offer), f"the offer carries no utc= line: {offer!r}" + before = set(os.listdir(offers)) + calls = len(est.session.tmux_calls()) + + def change(): + at_hold = est.record() if est.offer.exists() else {} + renamed = [c[-1] for c in _renames(est, calls)] + if case == "gone-at-its-back-out": + est.offer.unlink() + return at_hold, renamed, None + text, n = re.subn(r"(?m)^utc=.*$", f"utc={_utc(time.time() + 60)}", + offer.decode("utf-8"), count=1) + assert n == 1, f"the offer holds no utc= line: {offer!r}" + write_record(est.offer, text.splitlines()) + return at_hold, renamed, est.offer.read_bytes() + + hook, (at_hold, renamed, installed) = _answer_held(est, "2", "back-out", change) + err = hook.err + renames = [c[-1] for c in _renames(est, calls)] + assert at_hold.get("mode") == "binding" and at_hold.get("bind") == "1" \ + and not at_hold.get("pid"), \ + f"the record at the back-out's hold was not this answer's binding: {at_hold}" + assert TO in renamed, f"the window was not named {TO} before the back-out's hold: {renamed}" + assert not hook.killed and hook.code == 2, f"answer 2 did not exit 2: {hook!r}" + window = f"this window has NOT moved to {TO} (it was renamed back to {FROM}) " + assert NO_CHILD + window + BACKED_OUT_NOTHING in err, \ + f"the back-out did not refuse with nothing of this answer's to keep: {hook!r}" + assert "KEPT" not in err and "still says binding" not in err and "BINDING:" not in err, \ + f"the back-out said the offer is kept, or that the record still says binding: {hook!r}" + assert _renamed_back(FROM) in err and OFFER_KEPT_NOTE not in err, \ + f"the window was not renamed back in none's words: {hook!r}" + assert renames == [TO, FROM], f"tmux saw {renames}, not {TO} and then {FROM}" + if case == "gone-at-its-back-out": + assert not est.offer.exists(), \ + f"the back-out made a record where its binding was gone: {est.record()}" + else: + assert est.offer.read_bytes() == installed, \ + f"the back-out wrote over a record that is not its binding: {est.record()}" + _nothing_new(est, before, set(), "answer 2's back-out") + + +#: `[unknown-key]`'s line, which no reader of the record knows. +UNKNOWN_KEY = "t214o_unknown=a key that no reader of the record knows" + + +@pytest.mark.parametrize("case", ["key-twice", "unknown-key", "bounded-other", "bound-rc-nonzero"]) +def test_the_bind_records_grammar_as_every_reader_takes_it(estate, case): + """Section 8's :373 (the contract's section 3, its grammar; lane 3's + Codex review, #165 6877006381, finding 3). + + - `[key-twice]`: a key given twice is read by its first line, by each + reader: the guard's site (`mode=binding` then `mode=bound`, and a + `deadline_epoch` ahead then one past: "BINDING IN PROGRESS", the record + unchanged); the outer's bound (`c=3` then `c=2`: `bound_s=530`); and + the hook's answer 2 (`bind=1` then `bind=7`: attempt 2). + - `[unknown-key]`: a line no reader knows survives every rewrite of the + record: the hook's and the outer's start, the outcome, the guard's + restored offer, the stale row and case 10's. + - `[bounded-other]`: `bounded=maybe` reads as `yes`: "at the latest" + inside the deadline, `timeout`'s text past it, and on another host no + word that the child there may still be running. + - `[bound-rc-nonzero]`: a `bound` record whose `rc` is 1 is case 11: + dropped with today's text, its `.out` left.""" + est = estate() + now = time.time() + if case == "key-twice": + holder = _sleeper() + est.spare.append(holder.pid) + lines = _binding(est, started=now - 30, deadline=int(now) + 100, pid=holder.pid, + pidstart=_stat(holder.pid)["start"]) + write_record(est.offer, lines + ["mode=bound", "rc=0", f"deadline_epoch={int(now) - 1000}"]) + before = est.offer.read_bytes() + hook = est.hook("hello") + assert hook.code == 2 and IN_PROGRESS in hook.err and "MOVED" not in hook.err, repr(hook) + assert est.offer.read_bytes() == before, "the guard's site took a key's second line" + lines = [line for line in _binding(est, started=time.time()) + if not line.startswith(("pid=", "pidstart="))] + write_record(est.offer, lines + ["c=3", "n_a=1", "w_s_ms=0", "c=2"]) + proc = _guard_bind(est, est.sid, LANES_BIND_BODY=str(est.body)) + record = est.record() + assert proc.returncode == 0 and record.get("bound_s") == "530", \ + f"the outer's bound took c's second line: {record}\n{proc.stderr}" + hook = est.hook("the next prompt") + assert hook.code == 2 and "MOVED" in hook.err, repr(hook) + est.make_offer() + write_record(est.offer, est.offer.read_text(encoding="utf-8").splitlines() + + ["bind=1", "bind=7"]) + est.answer_2() + assert est.record().get("bind") == "2", \ + f"the hook's answer 2 took bind's second line: {est.record()}" + assert est.ended()["mode"] == "bound", est.record() + return + if case == "unknown-key": + est.set("rc", 1) + est.make_offer() + write_record(est.offer, est.offer.read_text(encoding="utf-8").splitlines() + [UNKNOWN_KEY]) + + def kept() -> bool: + return UNKNOWN_KEY in est.offer.read_text(encoding="utf-8").splitlines() + + survived = {} + est.answer_2() + est.outer() + survived["the hook's answer 2 and the outer's start"] = kept() + est.ended() + survived["the outer's outcome"] = kept() + hook = est.hook("after the failure") + assert hook.code == 2 and est.record().get("mode") == "name-drift", repr(hook) + survived["the guard's restored offer"] = kept() + dead = _dead_pid() + write_record(est.offer, _binding(est, started=now - 600, deadline=int(now) - 1, pid=dead, + pidstart="1") + [UNKNOWN_KEY]) + hook = est.hook("hello") + assert hook.code == 2 and NO_OUTCOME in hook.err, repr(hook) + survived["the stale row"] = kept() + write_record(est.offer, _binding(est, started=now - 700, deadline=int(now) - 62, pid=dead, + pidstart="1", host="Elsewhere") + [UNKNOWN_KEY]) + hook = est.hook("hello") + assert hook.code == 2 and NO_OUTCOME in hook.err, repr(hook) + survived["case 10's"] = kept() + assert all(survived.values()), f"a rewrite dropped {UNKNOWN_KEY!r}: {survived}" + return + if case == "bounded-other": + holder = _sleeper() + est.spare.append(holder.pid) + start = _stat(holder.pid)["start"] + write_record(est.offer, _binding(est, started=now - 30, bounded="maybe", + deadline=int(now) + 100, pid=holder.pid, pidstart=start)) + hook = est.hook("hello") + assert hook.code == 2 and IN_PROGRESS in hook.err and "at the latest" in hook.err, repr(hook) + write_record(est.offer, _binding(est, started=now - 600, bounded="maybe", + deadline=int(now) - 95, pid=holder.pid, pidstart=start)) + hook = est.hook("hello") + assert hook.code == 2 and "has not ended it; it is likely stuck on the disk or the network" \ + in hook.err and "This host has no" not in hook.err, repr(hook) + write_record(est.offer, _binding(est, started=now - 30, bounded="maybe", + deadline=int(now) + 100, pid=_dead_pid(), pidstart="1", + host="Elsewhere")) + hook = est.hook("hello") + assert hook.code == 2 and "A BIND OF THIS TRANSCRIPT IS RUNNING ON Elsewhere/" in hook.err \ + and "may still be running" not in hook.err, repr(hook) + return + est.offer.parent.mkdir(parents=True, exist_ok=True, mode=0o700) + out = Path(f"{est.offer}.bind.1.out") + out.write_text("the attempt's output\n", encoding="utf-8") + write_record(est.offer, ["mode=bound"] + _binding(est, started=now - 60)[1:] + + ["rc=1", f"ended_utc={_utc(now)}"]) + hook = est.hook("hello") + assert hook.code == 2 and UNREADABLE in hook.err and "MOVED" not in hook.err, repr(hook) + assert not est.offer.exists() and out.exists(), \ + "a bound record whose rc is 1 was not dropped as case 11, its .out left" + + +#: Section 8's :375, with K3: section 7's table, row by row, for the outer and +#: the body, but for the rows other cases take (S1, :360, S2, case 6, case 5 +#: and T254's cases 10 and 19). +EXIT_CASES = ["outer-usage", "outer-unsafe-name", "outer-no-record", "outer-not-binding", + "outer-has-pid", "outer-start-rewrite-fails", "body-usage", "body-unsafe-name", + "body-not-binding-with-facts", "body-not-binding-without-facts", "body-lane-start-0"] + + +@pytest.mark.parametrize("case", EXIT_CASES) +def test_guard_bind_exits_as_section_7_gives(estate, case): + """Section 8's :375 (lane 3's Codex review, #165 6877006381, finding 6; + K3): `guard-bind` called directly, as case 22 calls it, exits as section + 7's table gives, and where nothing ran, the record is as it was and no + `lane-start` started. + + - The outer's 2: its usage, no argument or two; a name that is no safe + name for `offers/<uuid>`; no record; a record not `binding`; and one + that already holds a `pid`. + - `[outer-start-rewrite-fails]`, its 1: a test-only copy fails its start + rewrite at the `mv`. Nothing ran, the record is as it was, no + temporary file is in `offers/`, and the guard reads the `binding`, + which holds no pid, as in progress. + - The body's 2: its usage; an unsafe name; and a record not `binding`, + with a `why=` in its facts file where `LANES_BIND_FACTS` hands it a + valid path, and with no facts file where it has none. + - `[body-lane-start-0]`: `lane-start` ends 0 and the act after it fails, + the lane left's `set-row-state` through a `LANES_EDIT` that refuses + with 1: a `note=` in the facts file, no `why=`, and the body exits 0.""" + est = estate() + facts = Path(f"{est.offer}.bind.1.facts") + if case in ("outer-no-record",): + done = [_guard_bind(est, est.sid)] + assert [d.returncode for d in done] == [2], [(d.returncode, d.stderr) for d in done] + assert not est.offer.exists() and not est.starts(), "an outer with no record ran" + return + if case in ("outer-not-binding", "body-not-binding-with-facts", + "body-not-binding-without-facts"): + est.make_offer() + elif case == "outer-has-pid": + holder = _sleeper() + est.spare.append(holder.pid) + write_record(est.offer, _binding(est, started=time.time(), pid=holder.pid, + pidstart=_stat(holder.pid)["start"])) + else: + _direct_record(est) + before = est.offer.read_bytes() + program = GUARD + if case == "outer-start-rewrite-fails": + program = _bind_copy(est, [(ANCHOR_MV, _fail_mv("pid=*"))]) + unsafe = [f"../{est.sid}", f"x/{est.sid}"] + calls = { + "outer-usage": [(), (est.sid, est.sid)], + "outer-unsafe-name": [(name,) for name in unsafe], + "outer-not-binding": [(est.sid,)], + "outer-has-pid": [(est.sid,)], + "outer-start-rewrite-fails": [(est.sid,)], + "body-usage": [("--body",), ("--body", est.sid, est.sid)], + "body-unsafe-name": [("--body", name) for name in unsafe], + "body-not-binding-with-facts": [("--body", est.sid)], + "body-not-binding-without-facts": [("--body", est.sid)], + "body-lane-start-0": [("--body", est.sid)], + }[case] + extra = {} + if case in ("body-unsafe-name", "body-not-binding-with-facts", "body-lane-start-0"): + extra["LANES_BIND_FACTS"] = str(facts) + if case == "body-lane-start-0": + refusals = est.ctl / "refusing-edit.log" + extra["LANES_EDIT"] = str(_script( + est.root / "refusing-lanes-edit", + f"#!/bin/sh\nprintf '%s\\n' \"$*\" >> {shlex.quote(str(refusals))}\n" + "echo 'lanes-edit.sh: the stand-in refuses with 1 (T214o)' >&2\nexit 1\n")) + done = [_guard_bind(est, *args, program=program, **extra) for args in calls] + codes = [d.returncode for d in done] + said = "\n".join(d.stderr for d in done) + if case == "body-lane-start-0": + lines = facts.read_text(encoding="utf-8").splitlines() if facts.exists() else [] + assert codes == [0], f"the body exited {codes}, not 0: {said}" + assert len(est.starts()) == 1, est.starts() + assert refusals.exists() and refusals.read_text(encoding="utf-8").startswith( + "set-row-state "), "the body's set-row-state never ran" + assert [line for line in lines + if line.startswith(f"note=lane {FROM}'s row was not marked PAUSED")] \ + and not [line for line in lines if line.startswith("why=")], \ + f"the failed act after lane-start's 0 is not a note= alone: {lines}\n{said}" + return + want = 1 if case == "outer-start-rewrite-fails" else 2 + assert codes == [want] * len(calls), f"guard-bind exited {codes}, not {want}: {said}" + assert est.offer.read_bytes() == before, f"the record changed: {est.record()}" + assert not est.starts(), f"lane-start ran: {est.starts()}" + if case.endswith("-usage"): + usage = "usage: guard-bind --body <session uuid>" if case.startswith("body") \ + else "usage: guard-bind <session uuid>" + assert all(usage in d.stderr for d in done), said + if case == "outer-start-rewrite-fails": + assert not _temporaries(est), f"the failed start rewrite left {_temporaries(est)}" + assert not list(est.offer.parent.glob(f"{est.sid}.bind.*")), \ + "the outer made its attempt's files though nothing ran" + hook = est.hook("hello") + assert hook.code == 2 and IN_PROGRESS in hook.err \ + and "its outer's pid not recorded" in hook.err, repr(hook) + return + if case == "body-not-binding-with-facts": + why = read_record(facts).get("why", "") + assert "mode=binding" in why, f"the body's 2 left no why= in its facts file: {why!r}" + return + assert not list(est.offer.parent.glob(f"{est.sid}.bind.*")), \ + f"a file was made beside the record: {sorted(est.offer.parent.glob(f'{est.sid}.bind.*'))}" + + +# ============================================================ T254: AT-F6's writes, primary +# +# AT-F6's cases 8 to 11 and 18 to 21 bind on primary only and take no mode id +# (A1). Each runs on the session cluster (T205's `pg`), so on a bench with no +# engine it is collected and skipped with T205's banner; each fails until +# lane 4's `start-record` (L4-B9), lane 5's bind (L5-A1) and its phase 2's +# lookup (L5-B1, T510) land, and on the register's template and logins (T227, +# T228). The lookup's tries follow AT-F3's rule (R26, 40): they start inside +# a closed 10 s window, with D9's 9 s timer (open point 37). + +#: The lookup's argv, which the child sends with the five values it copied +#: from `start-record`'s pending record (case 19). +LOOKUP = ("journal", "--write-id") + + +def _lookups(est: Estate) -> list: + """The shim's calls that carry the bind's lookup (`find_write`).""" + return [c for c in est.shim_calls() if "find_write" in c.get("sent", "")] + + +def _commits(est: Estate) -> list: + """The shim's calls that carry a commit (`commit_write`).""" + return [c for c in est.shim_calls() if "commit_write" in c.get("sent", "")] + + +def test_two_sessions_binding_one_lane_one_start_record_commits(estate): + """AT-F6 case 8: two sessions answer `2` for one lane on the primary + fixture: one `start-record` commits, and the other is refused 2 by its + `bind:<to>` expectation. + + THE SCOPE IS READ IN THE ATTEMPT'S `out` FILE (T254y): the writer's + `expectation:` line names `bind:<L>` in lower case (Y:5584, Y:5589), + and a failed bind keeps that line in its attempt's `out` file, while + the record's `why=` stays `lane-start`'s last refusal line, which + names no scope (Y:5487; lane 3, #165 6841918192). The `out` file's + `expectation:` and `row:` lines are printed, for lane 3's check that + `start-record` lists `row:<L>` first (Y:5528). + + THE REFUSAL ITSELF NAMES THE SCOPE (T254zn; lane 2's review RV22, NIT + 6): the line matched is `commit_write`'s LR009, "expectation: <scope> + changed at seq <s> by <lane>/<verb>" (`f9e1449c:lanes-index:9981`), + with the scope `bind:<L>`, so a later line that only lists the + expectations, such as `row:<L> bind:<L>`, cannot pass for it.""" + one, two, ends = _two_binds(estate, mode="primary") + assert sorted(r["mode"] for r in ends) == ["bind-failed", "bound"], ends + (est, failed), = [(e, r) for e, r in zip((one, two), ends) if r["mode"] == "bind-failed"] + assert failed["rc"] == "2", failed + out = Path(failed.get("out") or f"{est.offer}.bind.{failed.get('bind', 1)}.out") + text = out.read_text(encoding="utf-8", errors="replace") if out.exists() else "" + for line in text.splitlines(): + if "expectation" in line or "row:" in line: + print(f"T254 case 8, {out.name}: {line}") + refused = re.compile(rf"expectation: bind:{re.escape(TO.lower())} changed at seq [0-9]+ by ") + assert refused.search(text), (str(out), failed, text[-2000:]) + + +def test_the_bind_is_one_register_write_and_refuses_a_changed_row(estate): + """AT-F6 case 9: on primary the bind is one journal entry, and with the + `set-row-state` on the lane left answer 2 journals two; a row change + injected after `act-begin` refuses it with 2 and writes nothing. + + "WRITES NOTHING" IS READ IN THE RIVAL'S JOURNAL (T254zc; lane 2's + review RV20, finding 4): from its offer to its end, the rival's + database gains one entry, the injected `set-row-state`, and no + `start-record`.""" + est = _real_estate(estate, mode="primary") + est.shim() + est.make_offer() + est.answer_2() + record = est.ended(90) + assert record["mode"] == "bound", record + assert len(_commits(est)) == 2, [c.get("arms") for c in _commits(est)] + rival = _real_estate(estate, mode="primary") + rival.shim() + rival.set("inject-row", TO) + rival.make_offer() + head = int(rival.pg.psql("SELECT seq FROM lanes_register.register_head;").stdout.split()[-1]) + rival.answer_2() + record = rival.ended(90) + # THE RIVAL'S CHANGE LANDED (T254u): its `set-row-state` exited 0, or the + # refusal below would not be the changed row's. + injected = rival.ctl / "inject-row.rc" + rc = injected.read_text(encoding="utf-8") if injected.exists() else "never ran" + assert rc == "0", f"the rival's injected set-row-state exited {rc}: no row changed" + assert record["mode"] == "bind-failed" and record["rc"] == "2", record + grown = rival.pg.psql("SELECT string_agg(verb, ' ' ORDER BY seq) FROM " + f"lanes_register.journal WHERE seq > {head};").stdout.split() + assert grown == ["set-row-state"], f"the rival's journal after seq {head}: {grown}" + + +@pytest.mark.parametrize("held", ["found", "absent"]) +def test_a_bind_in_doubt_looks_its_write_up_before_a_rerun(estate, held): + """AT-F6 case 10: an injected `psql` exit 2 gives `rc=3` with the id: + `[absent]`, exit 2 on every call from the bind's commit call on; + `[found]`, the shim's `after` mode on that call, which commits, then exit + 2 on every later call. At the next `2` the child's + lookup runs first: `[absent]` binds anew under a new id; `[found]` writes + no second `RESUMED`, its done mark says `done`, and the record ends + `bound`. + + `[found]`'s later failures are not `fail-call` from the shim's second + call: that counted every call, and calls 1 and 2 are both the guard's own + prefetch, so the guard refused before its offer (T254t; lane 5, #165 + 6841545201). Nor are they the lookup's alone: the write's own retry + snapshot then answered `found=` and the record ended `bound` (lane 5, + #165 6842157774). They are `FOUND_ARMS`, every call after the commit + call (T254w). + + `[absent]` FAILS THE LOOKUP'S TRIES TOO (T254x): "exit 2 on every + call of the bind's write from its commit call on, its deadline's + lookup included" (TP:6092-6094 at a6497d00), by `fail-match` on + `find_write` (TP:7355). No try then takes the lock, so the run ends 3 + and keeps the record (Y:5245), not the 75 of a lookup that answers + absent (Y:5244; lane 3, #165 6841918192, point 5). The case's + `est.shim()` disarms both before the next `2`, so that lookup answers + absent and the bind starts again under a new id. + + THE SECOND HALF READS ITS EVIDENCE (T254zm; lane 2's review RV22, NIT + 5), in the calls after the second `2`, as case 18 reads its own + (T254zb): `[absent]` sends a `start-record` commit, under a write id + other than the copied one; `[found]` replays, and the shim's log shows + `register snapshot --tree <dir> --at <s-1>` (TP:6108 at a6497d00), + `s` being the found entry's seq in the journal. The shim logs `psql`'s + script, not `lanes-index`'s argv, so the replay is known by the one + request only that form sends: under `--tree` and `--at <k>`, the + `repos_blob` of the entry at `k + 1` + (`f9e1449c:lanes-index:3454`, `:3752`; the replay's call, + `f9e1449c:lanes-edit.sh:10725-10728`). + + AND `[found]`'s DONE MARK SAYS `done` (T254zp; Y TP:6110-6113 at + a6497d00): `<state>/register-done/<write_id>`, under the estate's own + state home, holds `tail=done ...`, as the run that removes the record + on 0 writes it (`4d96f8c5:lanes-edit.sh:8063-8077`). Two more items of + that row are not read, since the case cannot see them: the replay + child's `seam.out` `tail`, because a run's own `<run>/` goes at its end + and a kept attempt directory keeps only `snapshot`, `files` and + `preimages` (`:9722-9724`); and `lane_state_follow`'s one move of the + lane's `lane-state.yaml` `generation`, a sidecar written only for a + legacy lane on a seam verdict and a pre-image (`:25895-25906`, `:25769`), + whose place in this estate is not established.""" + est = _real_estate(estate, mode="primary") + arms = ([{"mode": "fail-match", "match": "commit_write", "from": 1}, + {"mode": "fail-match", "match": "find_write", "from": 1}] + if held == "absent" else list(FOUND_ARMS)) + est.shim(arms) + est.make_offer() + est.answer_2() + record = est.ended(120) + assert record["mode"] == "bind-failed" and record["rc"] == "3", record + assert all(k in record for k in COPIES), record + copied = record["write_id"] + est.shim() + est.hook("hello") + before = len(est.shim_calls()) + est.answer_2() + record = est.ended(120) + calls = est.shim_calls()[before:] + look = [i for i, c in enumerate(calls) if "find_write" in c.get("sent", "")] + start = [i for i, c in enumerate(calls) if "start-record" in c.get("sent", "") + and "commit_write" in c.get("sent", "")] + assert look and (not start or look[0] < start[0]), calls + assert record["mode"] == "bound", record + if held == "found": + assert not start, f"the found write was committed again: {calls}" + seq = est.pg.psql("SELECT seq FROM lanes_register.journal " + f"WHERE write_id = '{copied}'::uuid;").stdout.split() + assert seq, f"the found write {copied} is not in the journal" + at = f"FROM journal j WHERE j.seq = {int(seq[-1]) - 1} + 1" + assert [c for c in calls if at in c.get("sent", "")], \ + (f"no replay at seq {int(seq[-1]) - 1}, the found entry's base, in calls " + f"{[c.get('call') for c in calls]}") + done = est.state_home / "openRepoTools" / "register-done" / copied + mark = done.read_text(encoding="utf-8").splitlines() if done.exists() else [] + assert [line for line in mark if line.startswith("tail=done")], \ + f"the found write's done mark {done} does not say done: {mark}" + else: + assert start and all(copied not in calls[i].get("sent", "") for i in start), \ + (copied, [calls[i].get("call") for i in start]) + + +def test_a_rerun_after_a_failed_stamp_push_writes_one_stamp(estate): + """AT-F6 case 11 (R-F10-32; lane 5's T503, #165 6755410581): a rerun after + a failed stamp push writes no register line and no second stamp; its + output holds exactly one line with both `Rule 3's stamp` and `NOT` while + the stamp is unpushed, and none once it is published (lane 5's hand + counts 1, 0, 1 and 1 for unpushed, published, no upstream and + `LANES_NO_GIT`); and a rerun never retries a failed `set-row-state` + (Y:5511).""" + est = _real_estate(estate, mode="primary") + est.shim() + hooks = est.root / "origin-hooks" + hooks.mkdir() + _script(hooks / "pre-receive", "#!/bin/sh\nexit 1\n") + est._git(["config", "core.hooksPath", str(hooks)], est.origin) + est.make_offer() + est.answer_2() + record = est.ended(120) + owed = [n for n in record["note"] if "Rule 3's stamp" in n and "NOT" in n] + assert record["mode"] == "bound" and len(owed) == 1, record + commits = len(_commits(est)) + edits = [e for e in est.log("lanes-edit.log") if e["argv"][:1] == ["set-row-state"]] + rerun = subprocess.run(["bash", str(REPO / "lane-start"), "--no-launch", "--bind", est.sid, + "repoA", "3"], capture_output=True, text=True, timeout=120, + env=est.env(), cwd=str(est.wip)) + lines = [line for line in (rerun.stdout + rerun.stderr).splitlines() + if "Rule 3's stamp" in line and "NOT" in line] + assert len(lines) == 1, rerun.stdout + rerun.stderr + assert len(_commits(est)) == commits, "the rerun wrote a register line" + assert [e for e in est.log("lanes-edit.log") if e["argv"][:1] == ["set-row-state"]] \ + == edits, "the rerun retried set-row-state" + est._git(["config", "--unset", "core.hooksPath"], est.origin) + + +@pytest.mark.parametrize("held", ["found", "absent"]) +def test_a_bind_killed_mid_commit_waits_for_ended_utc_plus_c_before_its_lookup( + estate, tmp_path, request, held): + """AT-F6 case 18: a bind stopped by `kill <p>` while the shim holds + `start-record`'s commit call on a FIFO, and answered `2` at once: the + outer copies the five values; the child's lookup starts, in the shim's + log, no earlier than the record's `ended_utc` plus `C`, `N_a`*`c` + 6 s, + 8 s at `c` = 2, and gets no LR011; `[found]` writes no second + `RESUMED`, where the shim held the call after the real `psql` had + returned (`timer`), and `[absent]` binds anew, where it held it before + (`hold`). + + THE END AND THE WAIT ARE BOTH READ (T254zb; lane 2's review RV20, + finding 3): the second bind ends `bound`; `[found]` sends no second + `start-record` commit, so no second `RESUMED`, and `[absent]` sends + one under a new write id, not the copied one. And the `2` must go out + at least 2 s inside `ended_utc` + 8 s, or the lookup's time could not + tell a child that waited from a test that was slow: the case then + fails as inconclusive. + + THE KILL LANDS WHILE THE CALL IS HELD (T254zu; lane 5, #165 + 6871773273): the shim logs a call before it runs the real `psql`, and + a `timer` arm blocks on its FIFO only once `psql` has returned, so a + kill sent as soon as the commit call was logged could land before + `psql` had sent the commit; nothing then landed, the lookup found it + absent, and `[found]` bound anew (round 6l, `assert not starts`, + `[46]`). So the kill waits until the shim holds the call on the FIFO + (`_held`), in both ids, and the FIFO's writer stays open to the case's + end, so that only the kill ends the held call. The premise is then + read in the journal: `[found]`'s copied write id has landed, and + `[absent]`'s has not.""" + est = _real_estate(estate, mode="primary") + fifo = tmp_path / f"hold-{held}" + os.mkfifo(fifo) + mode = "timer" if held == "found" else "hold" + est.shim([{"mode": mode, "match": "commit_write", "call": 1, "fifo": str(fifo)}]) + est.make_offer() + est.answer_2() + record = est.outer() + assert _until(lambda: _commits(est), 60), "start-record's commit call never came" + writer = _held(fifo, 60) + assert writer, (f"start-record's commit call was never held on {fifo.name} " + f"({mode}): {[c.get('arms') for c in _commits(est)]}") + request.addfinalizer(writer.close) + _kill(int(record["pid"]), signal.SIGTERM) + record = est.ended(60) + assert all(k in record for k in COPIES), record + landed = est.pg.psql("SELECT seq FROM lanes_register.journal " + f"WHERE write_id = '{record['write_id']}'::uuid;").stdout.split() + assert bool(landed) == (held == "found"), \ + (f"[{held}]: the held commit's write {record['write_id']} is " + f"{'' if landed else 'not '}in the journal {landed}, so the kill did not land " + f"{'after' if held == 'found' else 'before'} the real psql") + ended = _epoch(record["ended_utc"]) + est.shim() + # THE FIRST PROMPT AFTER A FAILURE IS SPENT ON THE BIND-FAILED REPLY + # (T254v), so `hello` goes first, as case 10's does; without it the next + # `2` was that prompt and never reached the bind (lane 5, #165 6841545201). + est.hook("hello") + before = len(est.shim_calls()) + sent_at = time.time() + assert sent_at < ended + 6, (f"inconclusive: the 2 went out {sent_at - ended:.1f} s " + f"after ended_utc, too near C = 8 s to show a wait") + est.answer_2() + # THE SHIM LOGS NO TIME, so the lookup's start is read by watching for its + # entry, at 50 ms: the time seen is at most 50 ms after the start. + seen = _until(lambda: time.time() if [c for c in est.shim_calls()[before:] + if "find_write" in c.get("sent", "")] else None, + 120, 0.05) + assert seen, est.shim_calls()[before:] + print(f"T254 case 18: the lookup seen {seen - ended:.2f} s after ended_utc (C = 8 s)") + assert seen >= ended + 8, (seen, ended) + end = est.ended(120) + assert "LR011" not in end.get("why", ""), end + assert end["mode"] == "bound", end + starts = [c for c in est.shim_calls()[before:] + if "commit_write" in c.get("sent", "") and "start-record" in c.get("sent", "")] + if held == "found": + assert not starts, [c.get("call") for c in starts] + else: + assert starts and all(record["write_id"] not in c["sent"] for c in starts), \ + (record["write_id"], [c.get("call") for c in starts]) + + +@pytest.mark.parametrize("case", ["found", "another-write", "generation"]) +def test_the_bind_childs_lookup_sends_the_five_copied_values(estate, case): + """AT-F6 case 19: with the window's name spelled otherwise than the lane's + canonical name, after case 10's `[found]` `rc=3`, the child's lookup is + `lanes-index journal --write-id <id> --not-after <n> --generation <g> + --lane <write_lane> --verb start-record --args-sha256 <h>`, the five + values copied from `start-record`'s pending record, never derived from + `to`, and the found entry writes no second `RESUMED`. `[another-write]`: + the record's `args_sha256` copy changed, LR007 `another-write` ends `rc=2` + with the server's message and the copies dropped; `[generation]`: the + `generation` copy changed, `rc=2` with a plain rerun's refusal and the + copies kept. + + `[found]` SENDS NO SECOND COMMIT (T254zh; lane 2's review RV22, + finding 1): after the second `2`, no `start-record` commit is sent, as + case 10 checks, so a lookup that missed its write and bound anew fails. + + "NEVER DERIVED FROM `to`" IS READ THROUGH THE RECORD'S `to` (T254zo; + lane 2's reviews RV22, finding 1, and RV23, SHOULD 4). No spelling of + the window or the session makes `to` differ from the write's lane: the + guard writes `to` as the register's row spells it, its case-insensitive + hit (`G_SES_LANE`, `4d96f8c5:lanes-edit.sh:21162`, `:21546`), and + `lane-start` takes the row's spelling too (`f9e1449c:lane-start:1386- + 1394`). So `[found]` respells the record's `to` in lower case after the + bind-failed reply, before the second `2`, and the bound record still + holds it. The bind's `lane-start` is given that spelling and + takes the row's back, while a lookup whose lane came from `to` would + send the respelling, which `find_write` compares exactly + (`f9e1449c:lanes-index:10442`), and would end `rc=2` with LR007 + `another-write`, not `bound`; and the lookup must not carry it. The + guard itself never writes such a record, since it writes `to=` as the + row spells it (lane 5, #165 6867385794: `lanes-edit.sh:21606` at + merge97), so the respelled record stands for a damaged or hand-edited + one (lane 3's ruling, #165 6867533114).""" + est = _real_estate(estate, mode="primary") + # CASE 10's `[found]` ARMS (T254t, T254w): every call after the commit + # call fails, and the guard's own prefetch calls before it do not. + est.shim(list(FOUND_ARMS)) + est.make_offer() + est.answer_2() + record = est.ended(120) + assert record["rc"] == "3" and all(k in record for k in COPIES), record + copies = {k: record[k] for k in COPIES} + if case != "found": + key = "args_sha256" if case == "another-write" else "generation" + lines = [line for line in est.offer.read_text(encoding="utf-8").splitlines() + if not line.startswith(f"{key}=")] + # THE COPY ALWAYS CHANGES (T254zf; lane 4, #165 6852642520 and + # 6858782368): the digest and the generation are both lowercase hex, + # a sha256 and a random uuid, so a `0` put first changed nothing + # where the value began with `0`, about 1 run in 16. The lookup then + # found the bind's own write, and the bind ended `bound` with rc 0 + # (lane 5's T510 call 1 on line R, #165 6852280934). So the first + # digit is swapped for another, and the record is read back. + old = copies[key] + copies[key] = ("1" if old[0] == "0" else "0") + old[1:] + write_record(est.offer, lines + [f"{key}={copies[key]}"]) + assert est.record().get(key) == copies[key] != old, (key, old, est.record().get(key)) + est.shim() + est.hook("hello") + if case == "found": + to = est.to.lower() + lines = [f"to={to}" if line.startswith("to=") else line + for line in est.offer.read_text(encoding="utf-8").splitlines()] + write_record(est.offer, lines) + assert est.record().get("to") == to != copies["write_lane"], (to, est.record()) + est.to = to + # THIS ATTEMPT'S LOOKUP ALONE (T254zf; lane 4, #165 6858782368): the + # shim's log is never reset, and the first attempt's lookups sent the + # copies as they were, so the check below read them and passed without + # the second `2`'s own lookup. Only the calls after this point count. + before = len(est.shim_calls()) + est.answer_2() + record = est.ended(120) + lookups = [c for c in est.shim_calls()[before:] if "find_write" in c.get("sent", "")] + assert lookups, f"the second 2 made no lookup: {record}" + sent = " ".join(c.get("sent", "") for c in lookups) + # THE FIVE VALUES AS THE LOOKUP SENDS THEM (T254zd): `--not-after <n>` + # takes the copy's epoch seconds, and `find_write` gets them in their UTC + # form, `'2026-11-13T10:57:06Z'` for 1794567426 (the shim's log, lane 2's + # G-20 run k4b); the other four go as copied, a changed one as changed. + copies["not_after"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", + time.gmtime(int(copies["not_after"]))) + for key in COPIES: + assert copies[key] in sent, (key, copies[key]) + if case == "found": + assert f"'{est.to}'" not in sent, f"the lookup sent the record's to, {est.to}" + assert record["mode"] == "bound" and record.get("to") == est.to, record + again = [c.get("call") for c in est.shim_calls()[before:] + if "start-record" in c.get("sent", "") + and "commit_write" in c.get("sent", "")] + assert not again, f"the found write was committed again, call(s) {again}" + elif case == "another-write": + assert record["rc"] == "2" and not [k for k in COPIES if k in record], record + else: + assert record["rc"] == "2" and all(k in record for k in COPIES), record + + +def test_the_stale_row_copies_a_dead_outers_pending_call_and_the_next_2_looks_it_up(estate): + """AT-F6 case 20: the outer killed with `-9` while a stand-in `lane-start` + has written a `start-record` pending record of this session with a `call` + line: once no process of the outer's session is left, the stale row + copies the five values, `not_after` the largest among its `call` lines, + and the next `2` makes the lookup, in the shim's log, before any + `start-record` call. + + THE STAND-IN WRITES THAT RECORD (T254z; lane 5, #165 6841545201): a + whole `start-record` pending record of this session, with one `call=` + line (`pending-record`), at the register's own generation, host and + container, so the stale row has something to copy. `LANES_HOST` pins + the host the guard compares (`wr_here`), as a workstation outside a + container would otherwise read `hostname`. + + THE COPIES ARE THE RECORD'S, AND THE ORDER IS READ (T254zj; lane 2's + review RV22, finding 2): the stand-in writes three `call=` lines + (`NOT_AFTER_OFFSETS`), the largest `not_after` neither first nor last, + and the stale row's five copies must equal that record's write id, + generation, lane and digest and that largest `not_after`. The second + bind is a real one, as `_real_estate` makes it: the lane's projects + directory, its handoff and each lane's own register checkout before + the offer, then the window's renames followed and the `lane-start` + beside the flipped guard. The lookup answers absent for the stand-in's + id, the bind binds anew, and its `start-record` commit is in the shim's + log, so "the lookup before any `start-record` call" is read, not held + by an empty list (G-20's run k12 ended `bind-failed` at `lane-start`, + with no checkout for repoA).""" + est = estate(mode="primary") + (est.home / "projects" / est.to.rsplit("-", 1)[0]).mkdir(exist_ok=True) + _handoff(est) + _lane_checkouts(est, [FROM, est.to]) + est.shim() + est.set("hold", 60) + est.extra["LANES_HOST"] = HOST + est.make_offer() + generation = est.pg.psql("SELECT generation FROM lanes_register.register_switch;" + ).stdout.split()[-1] + head = est.pg.psql("SELECT seq FROM lanes_register.register_head;").stdout.split()[-1] + est.set("pending-record", json.dumps({ + "generation": generation, "lane": TO, "session": est.sid, "host": HOST, + "container": CONTAINER, "database": "register-test", "base": int(head), + "not_after_offsets": NOT_AFTER_OFFSETS})) + est.answer_2() + record = est.outer() + written = _until(lambda: [e for e in est.starts() if e.get("pending")], 30) + assert written, "the stand-in wrote no pending record" + lines = Path(written[0]["pending"]).read_text(encoding="utf-8").splitlines() + pending = read_record(Path(written[0]["pending"])) + not_afters = [int(line[len("call="):].split(" ")[2]) for line in lines + if line.startswith("call=")] + assert len(not_afters) == len(NOT_AFTER_OFFSETS) \ + and max(not_afters) not in (not_afters[0], not_afters[-1]), lines + want = {"write_id": pending["write_id"], "generation": pending["generation"], + "not_after": str(max(not_afters)), "write_lane": pending["lane"], + "args_sha256": pending["args_sha256"]} + outer = int(record["pid"]) + _kill(outer, signal.SIGKILL) + est.release() + assert _until(lambda: not _members("sid", outer), 30), "the outer's session never emptied" + hook = est.hook("hello") + assert hook.code == 2 and NO_OUTCOME in hook.err, repr(hook) + record = est.record() + assert {k: record.get(k) for k in COPIES} == want, (record, want) + est.extra["LANES_LANE_START"] = str(est.guard.parent / "lane-start") + est.set("edit-real") + _follow_renames(est.session) + before = len(est.shim_calls()) + est.answer_2() + end = est.ended(120) + calls = est.shim_calls()[before:] + print(f"T254 case 20: the second bind ended {end.get('mode')} rc {end.get('rc', '-')}; " + f"{len(calls)} call(s) after the second 2") + first_lookup = next((i for i, c in enumerate(calls) if "find_write" in c.get("sent", "")), + None) + assert first_lookup is not None, f"the second 2 made no lookup: {end}" + # A `start-record` CALL IS ITS COMMIT (T254ze): the lookup's own call + # names the verb too, `find_write(<id>, <utc>, <g>, <lane>, 'start-record', + # <h>)`, so a filter on the verb alone counted the lookup as a start + # (lane 2's G-20 run k12), as case 10 already filters. + starts = [i for i, c in enumerate(calls) if "start-record" in c.get("sent", "") + and "commit_write" in c.get("sent", "")] + assert starts and first_lookup < min(starts), \ + f"the lookup at {first_lookup}, start-record commits at {starts}: {end}" + + +#: CASE 20'S THREE `call=` LINES (T254zj), in seconds from the stand-in's +#: clock: the largest, 0, is neither first nor last, and none is in the +#: future, so the lookup decides at once. +NOT_AFTER_OFFSETS = [-30, 0, -20] + + +@pytest.mark.parametrize("copy", ["no-write-id", "no-pending-record", "write-id-not-uuid"]) +def test_a_bind_whose_write_id_no_pending_record_holds_makes_no_lookup(estate, copy): + """Section 8's :376 (spec#47's draft 14 `96d14916`; the contract's section + 3, its `write_id` row; lane 5's name, #165 6881714002; T254's, lane 2's + K1, #165 6882026139: phase 2 on primary, AT-F6's writes). A first bind, + whose stand-in `lane-start` writes a whole `start-record` pending record + of this session with a `call=` line, as case 20's does, and exits 3, + leaves a record holding the five copies; the bind-failed reply restores + the offer with them. Then its `write_id` is changed, and `ended_utc` set + to now, so a `w₀` wait would hold the body `N_a`*`c` + 6 s, 8 s at the + defaults: + + - `[no-write-id]`: the record holds no `write_id`, the other four kept; + - `[no-pending-record]`: a new uuid, which no pending record holds, + while the first attempt's pending record of this session is still + there with its own; + - `[write-id-not-uuid]`: the first attempt's id in upper case, which is + no uuid in the record's grammar. + + At the next `2` the body makes no lookup, no `find_write` call in the + shim's log after it, and no `w₀` wait: the stand-in `lane-start` starts + before `ended_utc` plus that `C`, and the record ends `bound`, holding + none of the copies. The first attempt's pending record is left, as + nothing looked it up or settled it.""" + est = estate(mode="primary") + est.shim() + est.extra["LANES_HOST"] = HOST + est.make_offer() + generation = est.pg.psql("SELECT generation FROM lanes_register.register_switch;" + ).stdout.split()[-1] + head = est.pg.psql("SELECT seq FROM lanes_register.register_head;").stdout.split()[-1] + est.set("pending-record", json.dumps({ + "generation": generation, "lane": TO, "session": est.sid, "host": HOST, + "container": CONTAINER, "database": "register-test", "base": int(head), + "not_after_offsets": [0]})) + est.set("rc", 3) + est.answer_2() + first = est.ended(120) + written = [e["pending"] for e in est.starts() if e.get("pending")] + assert first["mode"] == "bind-failed" and first["rc"] == "3" \ + and all(k in first for k in COPIES), first + assert written and read_record(Path(written[0])).get("write_id") == first["write_id"], \ + (written, first) + est.hook("hello") + # THE SECOND ATTEMPT'S STAND-IN WRITES NO PENDING RECORD, AND ENDS 0. + (est.ctl / "pending-record").unlink() + est.set("rc", 0) + lines = [line for line in est.offer.read_text(encoding="utf-8").splitlines() + if not line.startswith(("write_id=", "ended_utc="))] + if copy == "no-pending-record": + lines.append(f"write_id={uuid.uuid4()}") + elif copy == "write-id-not-uuid": + upper = first["write_id"].upper() + assert upper != first["write_id"], first["write_id"] + lines.append(f"write_id={upper}") + ended = int(time.time()) + write_record(est.offer, lines + [f"ended_utc={_utc(ended)}"]) + record = est.record() + assert record.get("mode") == "name-drift" and record.get("write_id") != first["write_id"] \ + and all(k in record for k in COPIES if k != "write_id"), record + c = max(2, int(record.get("c") or 2)) + n_a = max(1, int(record.get("n_a") or 1)) + before = len(est.shim_calls()) + est.answer_2() + end = est.ended(120) + calls = est.shim_calls()[before:] + starts = est.starts() + assert not [call for call in calls if "find_write" in call.get("sent", "")], \ + f"[{copy}]: the body looked up a write no pending record holds: {calls}" + assert len(starts) == 2 and starts[1]["t"] < ended + n_a * c + 6, \ + (f"[{copy}]: the second lane-start started {starts[-1]['t'] - ended:.1f} s after " + f"ended_utc, at or past C = {n_a * c + 6} s: a w0 wait") + assert end["mode"] == "bound" and end["rc"] == "0" \ + and not [k for k in COPIES if k in end], end + assert Path(written[0]).exists(), "the first attempt's pending record was settled" + + +def test_a_bind_over_a_delayed_tls_link_at_c_3_ends_bound_inside_530_s(estate, request): + """AT-F6 case 21 (R-P23): on the primary fixture behind T229's delayed + loopback, 75 ms each way with TLS on, and `connect_timeout=3` with one + address: `guard-bind` records `bound_s=530`, the bind ends `bound`, its + `ended_utc` less `started_utc` recorded beside the 530 s, and the + guard's register read is the hook's last database call in the shim's + log. The relay is T229's `delayed_loopback`, which FX's + `tests/pgcluster.py` holds (`a048fddb:tests/pgcluster.py:1400`), and + which the case asserts is there (T254zq; lane 2's review RV23, NIT 5). + + THE LINK IS ROUTED (T254za; lane 5, #165 6841545201): the estate + reads and writes T229's TLS cluster, which listens on 127.0.0.1 (the + session cluster has its socket alone), through the delayed loopback + at 0.075 s each way, by that cluster's own configuration + (`TLSCluster.configuration`, its two logins and their password files) + with each URL's port the relay's and `connect_timeout=3`, one address + and no `register_addresses=`. So the prefetch's `.head` says `c=3`, + and `guard-bind` sums 530 s (TP:6183-6187 at a6497d00). + + THE IMAGE CACHE IS FILLED FIRST (T254zg; lane 5, #165 6852197902): a + cold prompt reads form 2 and then fetches the whole files in a second + `lanes-index` with a connect of its own (`f9e1449c:lanes-index:6856`, + waited for to the cut at `:6862`), which the design prices past the + start line at 150 ms of round trip (design.md:4261-4273 at b8e3df74); + lane 2's G-20 saw it cut at `T0` + 3.75 s on py-bench. So the offer is + made through the cluster's own port, and its fetch fills the cache; then + the configuration is pointed at the relay, with `connect_timeout=3`, for + the `2`, whose read is one call (design.md:4287-4289 at b8e3df74). + + THAT PREMISE IS CHECKED, WITH NO WAIT (T254zk; lane 2's MK-22, on lane + 3's #165 6860626333, item 2): the guard's read waits for its fetch to + the read's cut (`f9e1449c:lanes-index:6862`), and the fetch puts each + image in the cache and records its head before it answers + (`:7451-7460`), while a read the cut leaves makes no offer. So right + after the offer, its prompt made the whole-file fetch, D9's + `guard-fetch` row (`statement_timeout=14000`, `:4573`), and the image + cache's `head` reads the register's head. Without them, the `2`'s read + would fetch through the relay and fail late, at the calls' check. + + AND NO SERVICE ANSWERS (T254zg): the estate's state home is one whose + socket path is over `SOCKET_MAX` (`_state_home_with_no_service`), where + the client reads directly and starts nothing + (`f9e1449c:lanes-index:7568`). Otherwise the offer's fallback starts + `serve` (`:9324`) on the configuration of the cluster's own port; each + prompt's cache family is its own (`f9e1449c:lanes-edit.sh:11792`), so + no earlier `.direct` keeps the `2`'s read direct (`lanes-index:9311`), + and that `serve` would answer it off the delayed link, with no call of + the hook's in the shim's log. So the row's last oracle is read: the + calls the shim logs between the `2` and the hook's exit are the guard's + read alone (D9's guard row, `statement_timeout=1500`, + `lanes-index:4563`), the last of them through the relay at `c` = 3; + answer 2 adds none. + + THE ROW'S OTHER TWO SHIM-LOG ORACLES (T254zi; lane 2's review RV22, + on case 21): "no step at its timer" is read as no register call cut + by its client timer: the shim writes a call's line to its ends file + only once the call returns, so once the bind has ended, every call it + logged has one, bounded at `ENDS_LIMIT_S` for a detached render. And + "the exit's lag after the read" is the hook's exit less the ends + file's mtime as the hook exits, when the guard's read was the last + call to end, recorded and asserted as case 1 asserts its exit: 1 s, + at twice it. + + A CALL THE SERVER'S OWN TIMER CUTS STILL HAS ITS END (T254zt; lane 2's + review RV23, NIT 8): a `statement_timeout` or `lock_timeout` ends the + call inside `psql`, which returns 1, and the shim writes that call's + line all the same. So the `2`'s guard read must also have ended 0. The + lag's bound stays at twice TP's 1 s, by section 1.2's timing rule, as + every bound here but the hook's 4.5 s is asserted.""" + pgcluster = pytest.importorskip("pgcluster") + delayed = pgcluster.__dict__.get("delayed_loopback") + assert delayed is not None, "tests/pgcluster.py has no delayed_loopback (T229)" + cluster = request.getfixturevalue("tls_cluster") + db = pgcluster.Database(cluster, cluster.database_name) + est = _real_estate(estate, mode="primary", pg=db) + est.extra["XDG_STATE_HOME"] = str(_state_home_with_no_service(est)) + with delayed(cluster.port, 0.075) as relay: + conf = cluster.configuration(est.root / "tls-conf", mode="primary") + text = conf.read_text(encoding="utf-8") + direct = f"@127.0.0.1:{cluster.port}/" + assert text.count(direct) == 2 and "register_addresses" not in text, text + est.extra["LANES_INDEX_CONFIG"] = str(conf) + est.shim() + est.make_offer() + offered = est.shim_calls() + fetched = [c for c in offered + if "statement_timeout=14000" in c.get("pg", {}).get("PGOPTIONS", "")] + assert fetched, ("the offer's prompt made no whole-file fetch: " + f"{[c.get('pg', {}).get('PGOPTIONS') for c in offered]}") + cached = Path(est.extra["XDG_STATE_HOME"]) / "openRepoTools" / "register-images" / "head" + n = est.pg.psql("SELECT seq FROM lanes_register.register_head;").stdout.split()[-1] + head = cached.read_text(encoding="utf-8").strip() if cached.exists() else None + assert head == n, (f"the offer's whole-file fetch left the image cache's head at " + f"{head!r}, not the register's head {n}: {cached}") + text = text.replace(direct, f"@127.0.0.1:{relay.port}/").replace( + "?sslmode=verify-full", "?connect_timeout=3&sslmode=verify-full") + assert text.count("connect_timeout=3") == 2, text + conf.write_text(text, encoding="utf-8") + hook = est.answer_2() + read_end = os.stat(est.bin / PSQL_SHIM_ENDS).st_mtime + exited = time.time() - (time.monotonic() - hook.t_exit) + calls = est.shim_calls()[len(offered):] + record = est.outer() + assert record["bound_s"] == "530", record + record = est.ended(530) + port = str(relay.port) + seen = [(c.get("call"), c.get("pg", {}).get("PGPORT"), c.get("pg", {}).get("PGCONNECT_TIMEOUT"), + c.get("pg", {}).get("PGOPTIONS")) for c in calls] + print(f"T254 case 21: the offer's prompt made {len(offered)} call(s) through the cluster's " + f"own port, {len(fetched)} of them the whole-file fetch; the 2's prompt exited " + f"{hook.t_exit - hook.t0:.2f} s after T0, its calls {seen}") + assert calls and all("statement_timeout=1500" in (s[3] or "") for s in seen) \ + and seen[-1][1:3] == (port, "3"), \ + f"the 2's prompt made calls other than the guard's read through the relay {port}: {seen}" + ends = _ends(est) + cut = [(c.get("call"), ends.get(c.get("call"))) for c in calls + if (ends.get(c.get("call")) or {}).get("exit") != 0] + assert not cut, f"the 2's guard read did not end 0, as a call its server's timer cut: {cut}" + lag = exited - read_end + print(f"T254 case 21: the hook exited {lag:.3f} s after its read ended " + f"(bound 1 s, asserted at 2 s)") + assert 0 <= lag < 2.0, f"the hook exited {lag:.2f} s after its read ended" + _until(lambda: not _calls_with_no_end(est), ENDS_LIMIT_S, 0.5) + unended = _calls_with_no_end(est) + assert not unended, f"call(s) {unended} never ended: cut at a timer, or still held" + assert record["mode"] == "bound", record + print(f"T254 case 21: ended_utc - started_utc = " + f"{_epoch(record['ended_utc']) - _epoch(record['started_utc'])} s beside 530 s") + assert hook.code == 2 + + +#: How long case 21 waits, once its bind has ended, for each logged call's end +#: (T254zi): a detached render may still be on the delayed link. +ENDS_LIMIT_S = 30.0 + + +def _ends(est: Estate) -> dict: + """The shim's ends file, {call: its line}: `exit`, and `psql`'s own code + where the real `psql` ran (T254zt).""" + path = est.bin / PSQL_SHIM_ENDS + if not path.exists(): + return {} + lines = [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() + if line.strip()] + return {line.get("call"): line for line in lines} + + +def _calls_with_no_end(est: Estate) -> list: + """The shim's request calls with no line in its ends file (T254zi): a + call killed at its client timer, or one still running.""" + ends = _ends(est) + return sorted(c.get("call") for c in est.shim_calls() if c.get("call") not in ends) + + +def _state_home_with_no_service(est: Estate) -> Path: + """A STATE HOME WHERE NO SERVICE CAN RUN (T254zg), under the estate's + root: its socket path is over `SOCKET_MAX`, so the client reads + directly and starts nothing, as on a workstation whose socket path is + too long (`f9e1449c:lanes-index:7568`, Y:3777-3781). The image cache + and the pending records live there too, as in any state home.""" + home = est.root / ("state-with-no-service-" + "s" * 90) + home.mkdir(mode=0o700) + sock = home / "openRepoTools" / "run" / "register.sock" + assert len(os.fsencode(str(sock))) > SOCKET_MAX, sock + return home + + +# ============================================================ T213: test 10's direct part +# +# Test 10's direct part, the guard without the service (AT-10; section 4.4): +# each case runs with the service down, so the guard's own direct read meets +# the fault; T237 adds the `service-up` cases. The database cases run on the +# session cluster, so here they are collected and skipped with T205's banner; +# they fail until L1-A2, L1-A11 and L5-A3, and the second read past the start +# line's until L1v4.5's T113 and lane 5's T507. The hook's 4.5 s is asserted +# as stated; every other bound at twice its value, recorded beside it (section +# 1.2's timing rule). + +#: The guard's frame (design, "One budget"; section 4's rule 1). +BUDGET = 4.5 +#: The parse's start line, `T0 + 3.75 s` (SVC-8), asserted at twice it. +START_LINE = 3.75 +#: How long case 6 waits, once the hook has exited, for the shim to hold the +#: whole-file fetch on its FIFO. The fetch starts before the cut, so it is +#: held by then; this is a margin, the outer's 10 s (`Estate.outer`). +HOLD_LIMIT = 10.0 +#: How long case 6 then waits for the released fetch to record the image +#: cache (T254zr): the `guard-fetch` row's least client timer, `N_a`*`c` + +#: 15 s at `c` = 2 (`f9e1449c:lanes-index:4573`). +CACHE_LIMIT_S = 17.0 +#: FORM 4 AS THE SHIM SEES IT (lane 5's F2b, #165 6812547449). The shim logs +#: `psql`'s own argv, never `lanes-index`'s, so no `--for` is ever in it; +#: form 4 is known by its SQL instead, which the shim logs as `sent` and +#: which an arm's `match` reads. It is the one request that reads the +#: latest import at or below `n` (contract section 3.6's form 4; +#: `register_read_queries(at=n)` in lane 5's writer A, T507A `319cd928`, +#: `lanes-index:6081`). Form 2, the whole-file fetch and the render read +#: send no such bound. +FORM_4_SQL = "WHERE i.kind = 'import' AND i.seq <= " +#: THE WINDOW'S LANE, SPELLED ANOTHER WAY IN ITS ROW (lane 5's call 4, #165 +#: 6813284257 and 6813607794): `RepoA-2` under the window `repoA-2`. The +#: guard's prefetch, form 2, asks with `--lane=` the window's name, and +#: `lanes-index` writes `.log.<that key>` even where the lane has no log; the +#: binding scan takes the row's own spelling from its case-insensitive match +#: (`G_LANE="$gr_hits"`), and only a key the cache lacks reaches form 4. +ROW_SPELLING = FROM[:1].upper() + FROM[1:] +#: The guard's note where a lane's object log could not be read, in today's +#: words (contract 4.19 section 3.6, B4: "the guard notes it as today", at +#: `lanes-edit.sh:10707-10710` at pin `2a057a6d`), which form 4's every end +#: but 0 reaches. +LOG_UNREAD = "object log could not be read" + + +def _silent_listener(host="127.0.0.1"): + """Section 4.4's case 1: a loopback listener on port 0 that accepts and + never speaks. Returns (its port, a function that closes it).""" + import socket + server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + server.bind((host, 0)) + server.listen(16) + held, stop = [], threading.Event() + + def accept(): + server.settimeout(0.2) + while not stop.is_set(): + try: + conn, _ = server.accept() + held.append(conn) + except OSError: + continue + + thread = threading.Thread(target=accept, daemon=True) + thread.start() + + def close(): + stop.set() + thread.join(1) + for conn in held: + conn.close() + server.close() + + return server.getsockname()[1], close + + +def _db_config(est: Estate, reader_url: str, **keys) -> Path: + """The estate's configuration with its reader's URL replaced (T220's + form), plus any of `register_addresses=` and the like.""" + conf = Path(est.extra["LANES_INDEX_CONFIG"]) + lines = [line for line in conf.read_text(encoding="utf-8").splitlines() + if not line.startswith("reader_url=")] + lines.append(f"reader_url={reader_url}") + lines.extend(f"{k}={v}" for k, v in keys.items()) + conf.write_text("\n".join(lines) + "\n", encoding="utf-8") + return conf + + +def _refuses_inside_the_budget(hook: Hook) -> None: + took = hook.t_exit - hook.t0 + print(f"T213: the guard exited {hook.code} after {took:.3f} s (budget {BUDGET} s)") + assert not hook.killed and hook.code == 2, repr(hook) + assert took < BUDGET, f"the guard took {took:.2f} s, past the {BUDGET} s budget" + + +@pytest.mark.parametrize("case", [f"{n}-service-{s}" for s in ("down", "up") + for n in (1, 2, 3, 4)]) +def test_a_database_that_does_not_answer_is_2_inside_4_5_s(estate, case): + """Section 4.4's cases 1 to 4 with the service down: a loopback listener + that never speaks; a host silent after connecting (a relay that stops + forwarding at the first query); a read behind a migration's lock, held + by the test's own session; and a conninfo with two loopback hosts, + `127.0.0.1` and `127.0.0.2` (T104's TLS refusal at load does not reach + them). In each the hook exits 2, was not killed, and finished in under + 4.5 s, its refusal naming the store. T237 adds the `service-up` ids, where + the service's connection meets the fault.""" + est = estate(mode="primary", to=FROM, to_row=False) + closers = [] + if case.endswith("service-up"): + closers.append(_Service(est).stop) + try: + if case.startswith("1-"): + port, close = _silent_listener() + closers.append(close) + _db_config(est, f"postgresql://reader@127.0.0.1:{port}/{est.pg.name}") + elif case.startswith("2-"): + # T229c's RELAY in front of the case's own database: it passes the + # startup on, then goes silent at the first ReadyForQuery, so the + # read connects and logs in and its query is never answered. Its + # login is the estate's own `reader_url=`'s (`pg.url()`'s), which + # the cluster has; case 1's `reader` reaches no server, but here + # a login the cluster lacks would end the read at once on its + # FATAL, a refusal that is not this case's fault. + silent = pytest.importorskip("pgcluster").__dict__.get("silent_after_startup") + assert silent is not None, "tests/pgcluster.py has no silent-after-startup relay" + relay = silent(est.pg.port, socket_dir=est.pg.host) + closers.append(relay.close) + login = urlsplit(est.pg.url()).username + _db_config(est, f"postgresql://{login}@127.0.0.1:{relay.port}/{est.pg.name}") + elif case.startswith("3-"): + # The register goes to the SQL store BEFORE the lock (T213o): + # `est.hook` seeds it first (`_seed_primary`, T254r), and that + # seeding reads `register_head`, so seeding after the lock waited + # on this case's own lock until psql's 120 s timeout (lane 5, + # #165 6841316861). Seeded here, the hook's seeding sends nothing + # and the guard's own read is the one that meets the lock. + _seed_primary(est) + holder = est.pg.session() + closers.append(holder.kill) + holder.stdin.write("BEGIN; LOCK TABLE lanes_register.register_head IN ACCESS EXCLUSIVE MODE;\n") + holder.stdin.flush() + # THE LOCK IS HELD BEFORE THE HOOK (T213p; lane 2's review RV20, + # finding 5): the LOCK goes to `psql`'s stdin with no answer, so + # on a loaded runner the guard could read before it was taken, + # and exit 0. It is waited for, granted, in `pg_locks`. + assert _until(lambda: _head_locked(est), 10, 0.1), \ + "the case's ACCESS EXCLUSIVE lock on register_head was never granted" + else: + ports = [_silent_listener(h) for h in ("127.0.0.1", "127.0.0.2")] + closers.extend(c for _, c in ports) + _db_config(est, "postgresql://reader@127.0.0.1:%d,127.0.0.2:%d/%s" + % (ports[0][0], ports[1][0], est.pg.name)) + hook = est.hook("hello") + _refuses_inside_the_budget(hook) + if case.startswith("3-"): + # AND THE REFUSAL IS THE STORE'S (T213p; RV20, finding 5): the + # guard's read met the lock, D9's guard row ended it at its + # `lock_timeout`, 1 s, which is no cut, so 69, and the guard + # refused with S3's text (`reg_guard_s3`), not at its start line, + # "too late to verify", before or without a read. + assert STORE_REFUSAL in hook.err, hook.err + finally: + for close in closers: + close() + + +#: S3'S REFUSAL, the guard's where its register read ended 69 with no outage +#: declared (`f9e1449c:lanes-edit.sh:20761`, `reg_guard_s3`). +STORE_REFUSAL = "the register's SQL store did not answer the guard's read" + + +def _head_locked(est: Estate) -> bool: + """Whether a session holds `register_head`'s ACCESS EXCLUSIVE lock in the + case's database, granted (T213p).""" + sql = ("SELECT count(*) FROM pg_catalog.pg_locks l " + "JOIN pg_catalog.pg_class c ON c.oid = l.relation " + "JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace " + "WHERE l.database = (SELECT oid FROM pg_catalog.pg_database " + "WHERE datname = current_database()) AND n.nspname = 'lanes_register' " + "AND c.relname = 'register_head' AND l.mode = 'AccessExclusiveLock' AND l.granted;") + return int(est.pg.psql(sql).stdout.strip() or 0) > 0 + + +@pytest.mark.parametrize("case", ["service-down", "service-up"]) +def test_a_connect_timeout_above_the_direct_reads_share_is_cut_at_the_parse_start_line( + estate, case): + """Section 4.4's case 5: `reader_url=` carries `connect_timeout=3`, so the + connect alone would end past the start line; against case 1's listener + the read's own timer ends it at `T0 + 3.75 s`, the hook exits 2 in under + 4.5 s, and the direct read's call carries `PGCONNECT_TIMEOUT=3`.""" + est = estate(mode="primary", to=FROM, to_row=False) + port, close = _silent_listener() + svc = _Service(est) if case == "service-up" else None + try: + _db_config(est, f"postgresql://reader@127.0.0.1:{port}/{est.pg.name}?connect_timeout=3") + est.shim() + hook = est.hook("hello") + _refuses_inside_the_budget(hook) + calls = est.shim_calls() + assert calls and calls[-1]["pg"].get("PGCONNECT_TIMEOUT") == "3", calls[-1:] + finally: + close() + if svc is not None: + svc.stop() + + +#: Where the too-late case's guard arrives at its prefetch: just past the +#: start line, `T0 + 3.8 s` from the runner's own start (lane 3, #165 +#: 6812673125, on lane 5's F3, 6812547449). +ARRIVAL = 3.8 +#: The stand-in `tmux`'s hold for that case, put in before its `case "$fmt"`: +#: on the guard's last query before its prefetch, `record_window_state`'s +#: targeted `#{session_name}`, once, it sleeps until the wall time in +#: `@DEADLINE@`, then writes the time it woke to `@ARRIVED@`. +_TOO_LATE_HOLD = r'''if [ "$fmt" = '#{session_name}' ] && [ -n "$target" ] && [ ! -e @ARRIVED@ ]; then + : > @ARRIVED@ + rem=$(awk -v d="$(cat @DEADLINE@)" -v n="$(date +%s.%N)" 'BEGIN { r = d - n; if (r < 0) r = 0; printf "%.3f", r }') + sleep "$rem" + date +%s.%N > @ARRIVED@ +fi +''' + + +def test_a_guard_that_starts_too_late_refuses_2_without_a_read(estate): + """AT-10: a guard that starts at or past the direct read's cap refuses 2 + and makes no read (the 5 s is one budget, spent once). The stand-in + `tmux` holds the guard's last query before its prefetch, + `record_window_state`'s targeted `#{session_name}`, until `T0 + 3.8 s` + from the runner's own start (`ARRIVAL`), once, so `T0` is early and the + read would start just past the start line; the arrival and the exit + are printed beside the 4.5 s, which is asserted as stated (lane 3, #165 + 6812673125; design:6181-6183 records every measured time). A sleep on + every `tmux` call put four of them, 5.2 s, before the prefetch, so the + runner killed the hook first (lane 5's F3, #165 6812547449). The estate + is G1's, `to=FROM, to_row=False`, so the guard's only refusal is the + late start's, never the name offer's (lane 3's reason in #165 + 6812490130).""" + est = estate(mode="primary", to=FROM, to_row=False) + est.shim() + deadline, arrived = est.bin / "tmux-deadline", est.bin / "tmux-arrived" + hold = _TOO_LATE_HOLD.replace("@ARRIVED@", f"'{arrived}'").replace( + "@DEADLINE@", f"'{deadline}'") + tmux = est.session.tmux + text = tmux.read_text(encoding="utf-8") + assert text.count('case "$fmt" in') == 1, "the stand-in tmux has changed its shape" + tmux.write_text(text.replace('case "$fmt" in', hold + 'case "$fmt" in'), encoding="utf-8") + mono0, wall0 = time.monotonic(), time.time() + deadline.write_text(f"{wall0 + ARRIVAL:.6f}\n", encoding="utf-8") + hook = est.hook("hello") + woke = arrived.read_text(encoding="utf-8").strip() if arrived.exists() else "" + took = hook.t_exit - hook.t0 + if woke: + at = float(woke) - wall0 - (hook.t0 - mono0) + print(f"T213: the guard's last tmux query before its prefetch returned at T0 + " + f"{at:.3f} s (set for {ARRIVAL} s); the hook exited {hook.code} at T0 + " + f"{took:.3f} s (budget {BUDGET} s)") + assert woke, ("the guard made no targeted `#{session_name}` query (record_window_state's), " + f"or was stopped in it, so nothing held it to the start line\n{hook!r}") + _refuses_inside_the_budget(hook) + assert not est.shim_calls(), "a guard past its start line still read" + + +def test_a_whole_file_fetch_the_start_line_cuts_fills_the_image_cache_for_the_next_prompt( + estate, tmp_path): + """Section 4.4's case 6, with the service down: the image cache lacks + `lanes/LANES.md` at `n`, and the shim holds the direct read's whole-file + fetch on a FIFO; the hook exits 2 at the cut inside the budget; the fetch + runs on in a detached child, and once released writes the file to the + image cache, so the next prompt's read fetches no whole file and + answers. The FIFO is let go by `_release`, bounded at `HOLD_LIMIT`, so + where no call is held on it the case fails, and never waits. The estate + is G1's, `to=FROM, to_row=False`, as T213c built it for cases 1, 3, 4 + and 5: with the default estate the first prompt's 2 is the name offer's, + and an oracle's refusal must come from the fault under test alone (lane + 3, #165 6812490130). The case's database holds the estate's register at + primary (`_Register`; lane 5's F2, #165 6812547449): at `files` the + first request ends 69, `switch-files`, and no whole-file fetch is ever + made. + + THE NEXT PROMPT WAITS FOR THE CACHE, NOT FOR A SECOND (T254zr; lane 2's + MK-22, on lane 3's #165 6860626333): once released, the detached child + runs its `psql`, puts the image in the cache and records its head + before it answers (`f9e1449c:lanes-index:7451-7460`), and nothing waits + for it, so the old `time.sleep(1.0)` raced it: a child slower than 1 s + left the next prompt to fetch the file again. So the case polls the + cache's `head` until it reads the register's head, bounded at + `CACHE_LIMIT_S`, the fetch row's own least timer, then reads that the + head's manifest names `lanes/LANES.md` (`head` moves only after + `seq/<n>` is written, `:2949-2988`).""" + est = estate(mode="primary", to=FROM, to_row=False) + _Register(est) + fifo = tmp_path / "whole-file" + os.mkfifo(fifo) + est.shim([{"mode": "hold", "match": "lanes/LANES.md", "call": 1, "fifo": str(fifo)}]) + try: + hook = est.hook("hello") + _refuses_inside_the_budget(hook) + assert _release(fifo, HOLD_LIMIT), ( + f"no call naming lanes/LANES.md was held on the FIFO {HOLD_LIMIT:.0f} s after the " + f"hook exited, so the guard's direct read started no whole-file fetch for the cut " + f"to leave running (fails until lane 5's T507); the shim logged " + f"{len(est.shim_calls())} call(s)\n{hook!r}") + finally: + _release(fifo, 0) + before = len(est.shim_calls()) + n = est.pg.psql("SELECT seq FROM lanes_register.register_head;").stdout.split()[-1] + images = est.state_home / "openRepoTools" / "register-images" + + def filled() -> bool: + head = images / "head" + return head.exists() and head.read_text(encoding="utf-8").strip() == n + + assert _until(filled, CACHE_LIMIT_S, 0.1), \ + f"the released fetch did not record the image cache at {n} in {CACHE_LIMIT_S:.0f} s: {images}" + manifest = (images / "seq" / n).read_text(encoding="utf-8").splitlines() + assert [line for line in manifest if line.split("\t")[0] == "lanes/LANES.md"], manifest + hook = est.hook("hello") + assert hook.code in (0, 2) and not hook.killed, repr(hook) + assert not [c for c in est.shim_calls()[before + 1:] + if "lanes/LANES.md" in c.get("sent", "")], "the next prompt fetched it again" + + +def test_the_direct_read_connects_as_its_engineers_reader_login(estate): + """AT-10: the guard's direct read connects as the engineer's reader login + (design section 1.4, `lanes-index login add`), never as the writer.""" + est = estate(mode="primary") + est.shim() + est.hook("hello") + calls = est.shim_calls() + assert calls, "the guard made no direct read" + assert all("writer" not in (c.get("pg", {}).get("PGUSER") or "") for c in calls), calls + + +#: How long the case waits for the service's held `psql` child to start: the +#: service starts its connect as it listens (`begin`, lane 3's ruling, #165 +#: 6827356485, point 3), so the child is there almost at once. +HELD_CHILD_S = 10.0 + + +def _role_passfiles(est: Estate) -> dict: + """EACH REGISTER ROLE'S OWN PASSWORD FILE (TP:1952 at `f9d6069e`; + `contracts/config.md`'s password-file row; contract section 2.2), as + T220's case configures them (`b8785b8b:tests/test_sql_register_bounds.py:316-323`): + the estate's configuration gains `reader_passfile=`, the READER's 0600 + file, which the guard's direct read and the service both connect with + (each a `PostgresStore(cfg, "register_reader")`), and + `register_passfile=`, the REGISTER-WRITER's, which no read may carry. + Each file is one libpq line, `*:*:*:*:<password>`, its password a new + uuid's hex, so the case can look for it in any variable. The cluster + trusts its own socket, so libpq never sends either. Returns + {key: (path, password)}.""" + made = {} + for key, role in (("reader_passfile", "reader"), ("register_passfile", "writer")): + path = est.root / "conf" / f"{role}.pgpass" + password = f"{role}-{uuid.uuid4().hex}" + handle = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + with os.fdopen(handle, "w", encoding="utf-8") as out: + out.write(f"*:*:*:*:{password}\n") + path.chmod(0o600) + made[key] = (path, password) + _db_config(est, est.pg.url(), **{key: path for key, (path, _) in made.items()}) + return made + + +def _json_file(path: Path): + """A JSON file a stand-in wrote whole, by a temporary file and a rename, + or None where it is not there.""" + try: + return json.loads(path.read_text(encoding="utf-8")) + except FileNotFoundError: + return None + + +def _held_children(stream) -> list: + """The service's held `psql` children whose start `stream` (a + `_StreamPsql`) logged, by their `VERBOSITY=sqlstate`; none yet where the + log's last line is still being written.""" + try: + return [r for r in stream.log("stream-begin.log") if r.get("held")] + except ValueError: + return [] + + +def _carried(where: str, env: dict, secrets) -> list: + """Each variable of `env` whose value holds a secret of `secrets`, each + (what, text), or a `postgresql://` or `postgres://` URL (libpq's two + schemes), one line each, naming `where`.""" + found = [] + for key, value in sorted(env.items()): + value = value or "" + found += [f"{where}: {key} carries {what}" for what, text in secrets if text in value] + if "postgresql://" in value or "postgres://" in value: + found.append(f"{where}: {key} carries a URL, {value!r}") + return found + + +def _child_findings(where: str, argv, passfile: str, pgpassword: bool, variables: dict, + role_file: Path, secrets) -> list: + """TP:1952-1953 FOR ONE `psql` CHILD, the service's or a direct read's: + its `PGPASSFILE` is its role's configured file, `PGPASSWORD` is not set, + and no variable or argument carries a password, the other role's file, + a configured URL or any `postgresql://` string, since the connection is + the URL's mapping into `PGHOST`, `PGPORT`, `PGDATABASE` and `PGUSER` + alone (contract section 2.2). One line per finding.""" + found = [] + if passfile != str(role_file): + found.append(f"{where}: PGPASSFILE is {passfile!r}, not its role's file {role_file}") + if pgpassword: + found.append(f"{where}: PGPASSWORD is set") + found += _carried(where, variables, secrets) + found += [f"{where}: an argument carries {what}" for what, text in secrets + if any(text in arg for arg in argv)] + found += [f"{where}: an argument is a URL, {arg!r}" for arg in argv if "://" in arg] + return found + + +def test_no_session_environment_carries_a_database_url_or_password(estate): + """AT-10 (TP:1949-1953 at `f9d6069e`; tasks:1979): no variable of an + environment a session inherits carries a database URL or a password, + while each `psql` child, the service's own and each direct read's, + carries its role's 0600 password file as `PGPASSFILE` and no password, + URL or `PGPASSWORD`. + + THE ORACLE ASSERTED, NOT ONLY OWNED (T213r; RC-26's section A, whose four + gaps lane 2's post opensoft/openRepoTools#165 6881947623 names): the + estate configures each role's own file (`_role_passfiles`), so a call + that drops it, or carries the writer's, differs from the role's file, + which the empty `lanes-index.nopass` never could; and the case reads + four records: + + - THE SERVICE'S OWN HELD `psql` CHILD, through `_StreamPsql` on the + service's `PATH` alone, as SVC-10 does: the stand-in records the + child's whole environment, `PGPASSWORD` written `*`, and the child is + the one call that carries the service's `VERBOSITY=sqlstate` + (`REGISTER_SERVE_PSQL_ARGS`). The service starts it by its connect at + listen, so no request is needed. PSQL_SHIM never runs that child, + since it reads its stdin to the end first. The service is stopped + before the first prompt, so the hook's own first call starts the next + one, with PSQL_SHIM as its `psql`, which never connects. + - EACH DIRECT READ'S `psql`, through PSQL_SHIM's log: its `passfile`, + `pgpassword`, `pg` (the call's `PG*` variables) and `url` (the shim's + own `postgresql://` rendering of those variables, which may hold no + second URL). + - THE SESSION'S ENVIRONMENT, which the runner hands the hook + (`Estate.env`), with no `PG*` variable at all, as before. + - WHAT THE BIND HANDS `lane-start`, and so a session: the stand-in's + whole environment (`lane-start.environ.<pid>.json`). The test plan's + fake `claude` records what `lane-start` hands a session (TP:1916); the + bind's `lane-start --no-launch` starts none, so the stand-in in its + place records it. + + Neither session environment may hold either role's password or file's + path, either configured URL or any `postgresql://` string. Every finding + is gathered first and asserted once, so one red run names every record + a fault reaches. Fails until T512, whose `serve` starts the held child + and whose verify runs this case (tasks:1604), besides T502 and T507.""" + est = estate(mode="primary") + files = _role_passfiles(est) + (reader_file, reader_pw), (writer_file, writer_pw) = (files["reader_passfile"], + files["register_passfile"]) + conf = dict(line.split("=", 1) for line in Path(est.extra["LANES_INDEX_CONFIG"]).read_text( + encoding="utf-8").splitlines() if "=" in line) + urls = [("register_url='s value", conf["register_url"])] + if conf["reader_url"] != conf["register_url"]: + urls.append(("reader_url='s value", conf["reader_url"])) + passwords = [("the reader's password", reader_pw), ("the writer's password", writer_pw)] + child_secrets = passwords + urls + [("the writer's password file's path", str(writer_file))] + session_secrets = child_secrets + [("the reader's password file's path", str(reader_file))] + est.shim() + stream = _StreamPsql(est, est.root / "service-bin") + svc = _Service(est, PATH=stream.path(est)) + try: + _until(lambda: _held_children(stream), HELD_CHILD_S, 0.1) + finally: + svc.stop() + held = _held_children(stream) + assert held, (f"the service started no held psql child in {HELD_CHILD_S:.0f} s: " + f"{stream.log('stream-begin.log')}") + envs = {r["pid"]: _json_file(stream.dir / f"stream-env.{r['pid']}.json") for r in held} + assert None not in envs.values(), f"a held child recorded no environment: {envs}" + est.make_offer() + est.answer_2() + est.ended() + calls = est.shim_calls() + assert calls, "the guard made no direct read" + starts = est.starts() + assert starts, "the bind never started lane-start" + handed = _json_file(est.ctl / f"lane-start.environ.{starts[0]['pid']}.json") + assert handed, f"the lane-start stand-in recorded no environment: {starts[0]}" + found = [] + for record in held: + env = envs[record["pid"]] + found += _child_findings(f"the service's held psql child (pid {record['pid']})", + record["argv"], env.get("PGPASSFILE", ""), "PGPASSWORD" in env, + env, reader_file, child_secrets) + for call in calls: + where = f"direct read call {call['call']}" + found += _child_findings(where, call["argv"], call.get("passfile", ""), + call.get("pgpassword", False), call.get("pg") or {}, + reader_file, child_secrets) + rendered = call.get("url") or "" + rest = rendered.split("://", 1)[1] if rendered.startswith("postgresql://") else rendered + found += _carried(f"{where}'s url", {"url": rest}, passwords + urls) + session = est.env() + found += [f"the session's environment: {key} is set" for key in session + if key.startswith("PG")] + found += _carried("the session's environment", session, session_secrets) + found += [f"what the bind hands lane-start: {key} is set" for key in handed + if "PGPASSWORD" in key] + found += _carried("what the bind hands lane-start", handed, session_secrets) + assert not found, "\n".join([f"{len(found)} finding(s), over {len(held)} held child(ren) " + f"and {len(calls)} direct read(s):"] + found) + + +def test_claude_no_lane_still_skips_before_any_input(estate): + """AT-10: `CLAUDE_NO_LANE=1` still makes the guard exit 0 before it reads + any input: nothing printed, no `tmux` call and no read.""" + est = estate() + calls = len(est.session.tmux_calls()) + hook = run_hook(["bash", str(est.guard), "guard"], "not json at all", + est.env(CLAUDE_NO_LANE="1"), est.session.cwd) + assert hook.code == 0 and hook.text == "", repr(hook) + assert len(est.session.tmux_calls()) == calls, est.session.tmux_calls()[calls:] + + +def test_the_guard_maps_69_75_and_3_to_2(estate, tmp_path): + """AT-10, "The codes the guard maps (D10)" (TP:1958-1963; + exit-codes.md:294): the guard exits 2 (the hook's only refusal), never + the code it met. + + 75 AND 3 ARE THE BIND'S (lane 5, #165 6814614032): `register read` never + ends 75 (a lost turn, from `register commit` only, register-cli.md:337) + or 3 (in doubt, from two commands only, :335), and the guard reads any + read code outside 0, 2, 69 and 78 as files mode with a warning (:340). + So answer 2's detached bind is made to exit 75, then 3, by the module's + stand-in `lane-start` (`rc`, the AT-F6 fixture case 5 uses, in place of + test 12's shim): the child records `mode=bind-failed` with `rc=` that + code, and the next prompt's hook exits 2 with "THE BIND TO LANE `<to>` + FAILED (exit `<rc>`)". In files mode, with the module's estate, whose + offer the `2` answers. They fail until L5-A1 (lane 5's T502, its + `bind-failed` arm). + + 69 STAYS AT THE READ, where it is the outage's 2: through the contract's + stub `lanes-index`, beside a copy of `lanes-edit.sh`, the end injected by + `stub_outcome`. The estate is G1's, `to=FROM, to_row=False`: the session + is named for the window's lane, whose row names it, so the guard's + answer with a register it could read is 0, and its 2 can only be the + read's (lane 3's reason in #165 6812490130). The module's default estate + makes the name offer, whose own 2 would pass this half wherever the + guard went on past a failed read (line AN14). It fails until L5-A3 + (lane 5's T507).""" + for end in (75, 3): + est = estate() + est.set("rc", end) + est.make_offer() + est.answer_2() + record = est.ended() + assert record["mode"] == "bind-failed" and record["rc"] == str(end), (end, record) + hook = est.hook("after the failure") + assert hook.code == 2 and not hook.killed, (end, repr(hook)) + assert f"THE BIND TO LANE {TO} FAILED (exit {end})" in hook.err, (end, repr(hook)) + from sql_register_helpers import stub_outcome + code = tmp_path / "code" + contract_stub(code) + for name in ("lanes-edit.sh", "repos.tsv", "lane-start"): + shutil.copy2(REPO / name, code / name) + for end in (69,): + est = estate(guard=code / "lanes-edit.sh", to=FROM, to_row=False) + conf = tmp_path / f"lanes-index-{end}.conf" + conf.write_text(f"register_url=postgresql:///register?host={tmp_path}/sock\n", + encoding="utf-8") + est.extra["LANES_INDEX_CONFIG"] = str(conf) + stub_outcome(code, ["register", "read"], exit=end) + hook = est.hook("hello") + assert hook.code == 2 and not hook.killed, (end, repr(hook)) + calls = [json.loads(line) for line in (code / ARGV_LOG).read_text( + encoding="utf-8").splitlines()] if (code / ARGV_LOG).exists() else [] + assert [c for c in calls if c[:2] == ["register", "read"]], (end, calls) + + +@pytest.mark.parametrize("case", ["at-the-cap", "under-a-declaration", "no-declaration-read"]) +def test_a_second_read_past_the_start_line_is_noted_not_refused(estate, case): + """S36-T507, lane 5's name: the guard's second read, form 4 (`register + read --for guard --at <n> --pid <pid> --cache <file> --lane=<key>`). + `[at-the-cap]`: started at or past `T0 + 3.75 s` it ends 2 and writes no + `.log.<key>`, and the guard notes the log as unreadable and does not + refuse (B4); `[under-a-declaration]`: its cut stays `T0 + 3.75 s` under + an unexpired declaration (B5); `[no-declaration-read]`: it reads no + declaration. The case's database holds the estate's register at primary + (`_Register`; lane 5's F2, #165 6812547449), so form 2 answers. + + FORM 4 IS ASKED ONLY FOR A KEY FORM 2 DID NOT FILL (lane 5's call 4, #165 + 6813284257 and 6813607794): the window's row is spelled `ROW_SPELLING`, + so the binding scan asks for `.log.RepoA-2`, which the prefetch's + `--lane=repoA-2` did not write, and the guard makes its second read. + + THE CUT, in `[at-the-cap]` and `[under-a-declaration]`: the shim holds + form 4's request 3.9 s (`FORM_4_SQL`), so it would reach the database + only past `T0 + 3.75 s`, and the read's own cut ends it 2, too late to + verify (T113's fix round, MUST-2). `[under-a-declaration]` does so under + an unexpired declaration that names this database, `database=` the + configuration's `register_label=` (config.md section 6.4), so the + declaration counts; there form 4 still starts, is cut and is noted. Both + end inside the budget, noted as today (`LOG_UNREAD`; B4). + `[no-declaration-read]` has no declaration and no hold: its form 4 ends + 0, and the guard notes no log it could not read. + + NOT REFUSED, in the module's estate, is the guard's own answer to it: the + name offer, 2 with the offer's text and the record at `name-drift`. A + refusal on the read makes no offer. `.log.<key>` is not asserted: the + guard removes its cache files when it exits (`cleanup`).""" + est = estate(mode="primary") + est.push_register([_row(ROW_SPELLING, est.sid, "LIVE"), _row(est.to, est.other, "PAUSED")]) + _Register(est) + cut = case in ("at-the-cap", "under-a-declaration") + est.shim([{"mode": "window", "ms": 3900, "match": FORM_4_SQL}] if cut else []) + if case == "under-a-declaration": + conf = Path(est.extra["LANES_INDEX_CONFIG"]) + label = next((line.split("=", 1)[1] for line in conf.read_text(encoding="utf-8") + .splitlines() if line.startswith("register_label=")), "") + assert label, f"the estate's configuration names no register_label=: {conf}" + (conf.parent / "register-outage").write_text( + f"format=1\nkind=word\ndatabase={label}\nutc=2026-11-10T00:00:00Z\nhost={HOST}\n" + f"until={_utc(time.time() + 3600)}\nmirror-seq=1\nwhy=test\n", encoding="utf-8") + hook = est.hook("hello") + assert not hook.killed and hook.t_exit - hook.t0 < BUDGET, repr(hook) + record = est.record() + assert hook.code == 2 and OFFER in hook.text and record.get("mode") == "name-drift", \ + f"the guard did not answer with its name offer (a refusal on its read makes none): " \ + f"{record}\n{hook!r}" + forms = [c for c in est.shim_calls() if FORM_4_SQL in c.get("sent", "")] + assert forms, "the guard made no second read (no call in the shim's log is form 4's SQL)" + if cut: + assert "window" in forms[0].get("arms", []), f"the shim did not hold form 4: {forms[0]}" + assert LOG_UNREAD in hook.err, \ + f"the guard did not note the log its cut second read left unread: {hook!r}" + else: + assert LOG_UNREAD not in hook.err, \ + f"form 4 was made, yet the guard noted the log as unread: {hook!r}" + + +def test_the_guards_last_budget_line_is_below_guard_timeout(): + """Lane 5's (A5): the last line of SVC-8's budget, the guard's own + printing of its refusal, is below `GUARD_TIMEOUT`, 5 s: the guard's + largest budget constant, read from `lanes-edit.sh`, is under 5000 ms. + Fails until L5-A3 (lane 5's T507) writes the budget.""" + text = GUARD.read_text(encoding="utf-8") + found = re.findall(r"^GUARD_BUDGET_[A-Z_]*_MS=(\d+)", text, re.M) + assert found, "lanes-edit.sh states no GUARD_BUDGET_*_MS line (lane 5's T507)" + assert max(int(v) for v in found) < 5000, found + + +#: A MIRROR READ'S LABEL, in the form the text gives it: `read: mirror at +#: <sha12>, …` on stderr (the test plan's AT-11 oracle, TP:2878-2881, which +#: names `session-start`; B15 tasks:728's mirror class). The words after the +#: comma are not fixed for the `SessionStart` block on primary (lane 5's +#: point 2 to lane 3, #165 6814032480), so only the prefix, the 12 hex digits +#: and the comma are pinned, as the readers module's `MIRROR_LINE` pins them. +MIRROR_LINE = re.compile(r"^read: mirror at [0-9a-f]{12}, .*$", re.M) + + +def test_the_session_start_block_makes_no_register_call_on_primary(estate): + """Lane 5's (A5; R39): the `SessionStart` block, in the mirror class, + makes no register call on primary: the shim logs no call while it + runs. And it reads the mirror offline, labelled `read: mirror` (T508, + B15 tasks:822): its stderr carries the label (`MIRROR_LINE`), its stdout + does not, and it exits 0. A build with no SQL path makes no register + call either, so the call count alone passed at the base and proved + nothing for T508 (lane 5's point 4, #165 6814032480); the label is T508's + own, so the case fails at the base on it, until T508 (L5-A4).""" + est = estate(mode="primary") + est.shim() + proc = subprocess.run(["bash", str(est.guard), "session-start"], + input=est.session.hook_input(), capture_output=True, text=True, + env=est.env(), cwd=str(est.wip), timeout=60) + assert proc.returncode == 0, proc.stderr + assert not est.shim_calls(), est.shim_calls() + assert MIRROR_LINE.search(proc.stderr), \ + f"the block printed no `read: mirror at <sha12>, ...` line on stderr (T508): {proc.stderr}" + assert not MIRROR_LINE.search(proc.stdout), proc.stdout + + +# ============================================================ T226: the guard's measured parts +# +# M5b and M10 (section 5.1), the guard module's half of T226; line M wrote +# the measure module's half (T226m). Each asserts correctness only; its +# figures go to the job's log and to `$GITHUB_STEP_SUMMARY`, never into a +# threshold (section 5.4). Ten runs each, as section 5.1's table gives them. + +MEASURE_RUNS = 10 +#: The measurement's register (the test plan's AT-10 fixture): about 2.6 MB +#: with 73 lanes, shaped as the real one is, the bound lane's log about 90 KB. +MEASURE_LANES = 73 +MEASURE_BYTES = 2_600_000 +MEASURE_LOG = 90_000 + + +def _record_figure(title: str, figures: dict) -> None: + """A measurement's figures, printed for the job's log and appended to + `$GITHUB_STEP_SUMMARY` where it is set.""" + _record_line(f"{title}: " + ", ".join(f"{k} {v}" for k, v in figures.items())) + + +def _record_line(line: str) -> None: + """One line, printed for the job's log and appended to + `$GITHUB_STEP_SUMMARY` where it is set: a figure's, or a warning's + (T237zs), which a passing test's captured output would otherwise hide.""" + print(line) + summary = os.environ.get("GITHUB_STEP_SUMMARY") + if summary: + with open(summary, "a", encoding="utf-8") as handle: + handle.write(f"- {line}\n") + + +def _median(values) -> float: + ordered = sorted(values) + mid = len(ordered) // 2 + return ordered[mid] if len(ordered) % 2 else (ordered[mid - 1] + ordered[mid]) / 2 + + +def _measurement_register(est: Estate) -> tuple: + """The measurement's register on the estate's checkout, pushed: `FROM`'s + row naming the session, 72 other lanes, each with its log, `FROM`'s about + 90 KB and the whole about 2.6 MB. Returns (its render set as a mapping of + paths to text, its build time in seconds).""" + t0 = time.monotonic() + lanes = [FROM] + [f"bench{i:02d}-1" for i in range(1, MEASURE_LANES)] + sids = {lane: (est.sid if lane == FROM else str(uuid.uuid4())) for lane in lanes} + rows = [_row(lane, sids[lane], "LIVE" if lane == FROM else "PAUSED") for lane in lanes] + rest = (MEASURE_BYTES - MEASURE_LOG) // (MEASURE_LANES - 1) + files = {} + for lane in lanes: + # THE LOG'S LINE FORM, as the helper suite writes it + # (`tests/test_lane_helpers.sh`): `<VERB> - lane <l>, session + # <id>@<ws>, <utc>, lane:<l>`, the dash an em dash. + entry = (f"RESUMED {chr(0x2014)} lane {lane}, session {sids[lane]}@{HOST}, " + f"2026-10-01T00:00:00Z, lane:{lane}\n") + size = MEASURE_LOG if lane == FROM else rest + files[f"lanes/log/{lane}.md"] = f"# {lane}\n\n" + entry * (size // len(entry)) + for path, text in files.items(): + (est.wip / path).write_text(text, encoding="utf-8") + est.push_register(rows) + files["lanes/LANES.md"] = register_text(rows) + files["lanes/log/README.md"] = "logs.\n" + return files, time.monotonic() - t0 + + +def _timing_wrappers(est: Estate) -> tuple: + """`tmux` and `git` wrappers ahead of the stand-in on `PATH`, each logging + its call's wall time and arguments, then running the stand-in `tmux` or + the real `git`. Returns (the `PATH` to pass, the two logs).""" + wrap = est.root / "timing" + wrap.mkdir(exist_ok=True) + logs = (est.ctl / "tmux-times.log", est.ctl / "git-times.log") + for name, target, log in (("tmux", est.bin / "tmux", logs[0]), + ("git", shutil.which("git"), logs[1])): + _script(wrap / name, "#!/bin/sh\nprintf '%s %s\\n' \"$(date +%s.%N)\" \"$*\" >> @LOG@\n" + "exec @TARGET@ \"$@\"\n", LOG=repr(str(log)), TARGET=repr(str(target))) + path = os.pathsep.join([str(wrap), str(est.bin), est.base.get("PATH", os.defpath)]) + return path, logs + + +def _times(log: Path, since: float) -> list: + if not log.exists(): + return [] + out = [] + for line in log.read_text(encoding="utf-8").splitlines(): + stamp, _, args = line.partition(" ") + if float(stamp) >= since: + out.append((float(stamp), args)) + return out + + +def test_todays_direct_guard_is_timed_in_its_four_parts(estate): + """M5b (AT-10): today's direct guard, timed in the four parts the design + measured (design, "What today's guard costs, in four parts"), on the + measurement's register: reaching the guard's arm, to its first `tmux` + call; the `tmux` read, to its last `tmux` call before the register's; + `transcript_holders` and the rest, to the first `git` read of the + register; and the register read with its parses, to the exit. The + figures are recorded, never asserted; it asserts that each run lets the + prompt through (the row names the session), that each part was reached, + and that the four parts make up the run.""" + est = estate() + _, built = _measurement_register(est) + est.swap_window(FROM, FROM) + path, (tmux_log, git_log) = _timing_wrappers(est) + parts = {"arm": [], "tmux": [], "holders": [], "register": [], "total": []} + for _ in range(MEASURE_RUNS): + start = time.time() + hook = est.hook("hello", PATH=path) + end = time.time() + assert hook.code == 0 and not hook.killed, repr(hook) + tmux = [t for t, _ in _times(tmux_log, start)] + reads = [t for t, args in _times(git_log, start) if "lanes/" in args] + assert tmux and reads, f"a part was not reached: tmux {tmux}, register reads {reads}" + before = [t for t in tmux if t <= reads[0]] + assert before, "the register was read before the tmux read" + marks = [start, tmux[0], before[-1], reads[0], end] + assert marks == sorted(marks), marks + for name, (a, b) in zip(("arm", "tmux", "holders", "register"), zip(marks, marks[1:])): + parts[name].append(b - a) + parts["total"].append(end - start) + assert abs(sum(parts[n][-1] for n in ("arm", "tmux", "holders", "register")) + - parts["total"][-1]) < 1e-6 + _record_figure("M5b, today's direct guard in four parts (median ms)", + {k: f"{_median(v) * 1000:.1f}" for k, v in parts.items()} + | {"register built in": f"{built:.2f} s"}) + + +def test_the_guards_register_parse_is_timed_on_a_real_sized_register_beside_todays_six_reads_through_git( + estate, tmp_path): + """M10 (AT-10): on the measurement's register, written twice, as the + files of a git checkout and as SVC-8's cache files, the guard's register + read is timed both ways: today's reads through `git` on the checkout, + and the parse alone on the cache files, which the guard's prefetch + (`register read --prefetch --cache <file>`, lane 5's T507) fills from the + contract's stub `lanes-index` (T207) beside a copy of `lanes-edit.sh`. + Each is recorded with the parse's 0.5 s reserve, never asserted. + Correctness alongside: both ways the guard gives the same answer, and the + parse alone makes no `git` read of the register. Fails until L5-A3.""" + code = tmp_path / "code" + for name in ("lanes-edit.sh", "repos.tsv", "lane-start"): + code.mkdir(exist_ok=True) + shutil.copy2(REPO / name, code / name) + est = estate(guard=code / "lanes-edit.sh") + files, built = _measurement_register(est) + est.swap_window(FROM, FROM) + path, (_, git_log) = _timing_wrappers(est) + through_git, reads = [], [] + for _ in range(MEASURE_RUNS): + start = time.time() + files_hook = est.hook("hello", PATH=path) + end = time.time() + assert files_hook.code == 0, repr(files_hook) + got = [t for t, args in _times(git_log, start) if "lanes/" in args] + assert got, "today's guard made no git read of the register" + reads.append(len(got)) + through_git.append(end - got[0]) + t0 = time.monotonic() + contract_stub(code, register={k: v for k, v in files.items() + if k != "lanes/log/README.md"}) + built += time.monotonic() - t0 + conf = tmp_path / "lanes-index.conf" + conf.write_text(f"register_url=postgresql:///register?host={tmp_path}/sock\n", + encoding="utf-8") + parse = [] + for _ in range(MEASURE_RUNS): + start = time.time() + hook = est.hook("hello", PATH=path, LANES_INDEX_CONFIG=str(conf)) + end = time.time() + calls = [json.loads(line) for line in (code / ARGV_LOG).read_text( + encoding="utf-8").splitlines()] if (code / ARGV_LOG).exists() else [] + assert [c for c in calls if c[:2] == ["register", "read"] and "--prefetch" in c], \ + f"the guard made no prefetch into the cache files: {calls}" + assert not [a for _, a in _times(git_log, start) if "lanes/" in a], \ + "the parse alone still read the register through git" + assert (hook.code, hook.out) == (files_hook.code, files_hook.out), repr(hook) + parse.append(end - start) + _record_figure("M10, the guard's register read on a real-sized register (median ms)", { + "today's reads through git": f"{_median(through_git) * 1000:.1f}", + "git reads per run": f"{_median(reads):.0f}", + "the parse alone": f"{_median(parse) * 1000:.1f}", + "the parse's reserve": "500", "register built in": f"{built:.2f} s"}) + + +# ============================================================ T237: test 10 through the service +# +# Test 10 through the service (L2-S1; AT-10; section 4.4; A5; A7; A10), and the +# service's own cases lane 5 asked for. Every case needs L5-S1's `lanes-index +# serve` (lane 5's T511 to T513); SVC-5's `mode=primary` comes from the +# session cluster, so these run on T205's `pg` and here are collected and +# skipped with T205's banner, but for `serve`'s and `status`'s refusals in +# files mode, which need no engine and are red today by their own assertions. +# THE FORMS ARE LANE 5's SOCKET CONTRACT, draft 8 (`socket-api-d8-563157a7.md`): +# the fixed path and its five files (sections 2.1 to 2.4), the failure stamp +# (8.6) and the request's first line (12). `status`'s `service` lines are +# T512's in `cmd_status` (R44), whose words the contract does not fix. + +#: The checkout's `lanes-index`, which a case loads in process. A case's own +#: calls run its estate's (`Estate.index`), the flipped copy on primary. +INDEX = REPO / "lanes-index" +#: The fallback line, printed once wherever the service was unavailable and +#: the client then read directly (svc:104; lane 5's socket contract, draft 8, +#: section 5.3's table and OP-11). +FALLBACK = "guard: direct (service unavailable)" + + +def _index(est: Estate, *args, env=None, timeout=60) -> subprocess.CompletedProcess: + return subprocess.run([sys.executable, str(est.index), *args], capture_output=True, text=True, + env=env or est.env(), cwd=str(est.wip), timeout=timeout) + + +def _run_dir(est: Estate) -> Path: + """The service's one directory, fixed by lane 5's socket contract d8 + (section 2.1): `${XDG_STATE_HOME:-~/.local/state}/openRepoTools/run/`, + holding `register.sock`, `register.lock`, `register.owner`, + `register.failed` and `register.log` (section 2.3). Under the estate's + own state home (`_state_home`), its socket path is 49 bytes.""" + return Path(est.base["XDG_STATE_HOME"]) / "openRepoTools" / "run" + + +def _service_dir(est: Estate, stale=None): + """The run directory, where the service's socket is bound; with `stale`, + a socket's inode, only once the socket there is another one (T237zi).""" + run = _run_dir(est) + sock = run / "register.sock" + if not sock.exists(): + return None + if stale is not None: + try: + if os.lstat(sock).st_ino == stale: + return None + except OSError: + return None + return run + + +def _stale_socket(est: Estate): + """The inode of a socket in the run directory that no process answers on, + a dead service's (SVC-4), or None (T237zi): a connect refused, or a file + that is not a socket, is stale; one that connects is a live service's.""" + import socket as _socket + path = _run_dir(est) / "register.sock" + try: + inode = os.lstat(path).st_ino + except OSError: + return None + probe = _socket.socket(_socket.AF_UNIX, _socket.SOCK_STREAM) + try: + probe.settimeout(1.0) + probe.connect(str(path)) + except OSError: + return inode + finally: + probe.close() + return None + + +def _failure_stamp(est: Estate, done: subprocess.CompletedProcess) -> list: + """The words of `serve`'s failure stamp, `register.failed` (section 8.6), + read only once `serve` has exited 2 and the stamp exists. Until lane 5's + T512 adds `serve` (L5-S1), `lanes-index` answers it 64, unknown + subcommand, and writes no stamp: the case then ends on this assertion, + never on a missing file (line AN14).""" + path = _run_dir(est) / "register.failed" + assert done.returncode == 2 and path.is_file(), ( + f"`lanes-index serve` exited {done.returncode} and wrote " + f"{'a' if path.is_file() else 'no'} failure stamp; lane 5's T512 (L5-S1) exits 2 " + f"and stamps it: {done.stdout}{done.stderr}") + return path.read_text(encoding="utf-8").split() + + +def _owner_lines(index: Path) -> list: + """`register.owner`'s lines as the service writes them (T237zz; socket + API section 2.4, "Its bytes", at draft 13 `fa613b9d`; T512's + `register_serve_owner_text`, `register_serve_install` and + `register_serve_host`, `88b50886:lanes-index:8064-8097`), for a socket + of the case's own (`_Listener`), in the contract's order: + + - `pid=` and `started=` name this process, the listener's, where the + contract names the service's, its start UTC in whole seconds; + - `install=` is the size, mtime in nanoseconds and inode of `index`, + the `lanes-index` the case's client runs (`Estate.index`: the guard + runs the one beside its `lanes-edit.sh`, which is it), so the client + finds its own install and starts no service (section 8.1); + - `boot=` and `pidns=`, each where it can be read, are this host's, as + the client reads its own, so the client finds its own boot and pid + namespace. + + Each key once, each line ending in `\\n`, and `install=` three decimals: + so the file is one a client can use under lane 3's OP-19 (b) too + (opensoft/openRepoTools#165 6880543448), not only under T512's reader.""" + st = os.stat(index) + lines = [f"pid={os.getpid()}", f"started={_utc(time.time())}", + f"install={st.st_size} {st.st_mtime_ns} {st.st_ino}"] + host = {} + try: + host["pidns"] = os.readlink("/proc/self/ns/pid") + except OSError: + pass + try: + with open("/proc/sys/kernel/random/boot_id", "rb") as handle: + host["boot"] = handle.read(100).decode("ascii").strip() + except (OSError, UnicodeDecodeError): + pass + return lines + [f"{key}={value}" for key, value in sorted(host.items())] + + +class _Listener: + """A socket of the test's own at the contract's fixed path (section + 2.1), in a 0700 directory of this uid (section 2.2): it records what a + client sends, and either never answers (`hang`) or closes at once. + + WITH `whole` (T237zt), each record is the request read to its `end` + line, or to the client's close or a 1 s pause, not one `recv`'s bytes: + a request of 64 KiB may come in more than one, and the case that sends + one must read every byte of it (`REQUEST_MAX`). + + ITS OWNER FILE (T237zz; lane 5, opensoft/openRepoTools#165 6880500257): + T512's client, since its OP-17 (b) (`690c2cc3`, in `88b50886`), reads + `register.owner` after its connect and before it sends a byte, and a + file that is absent, or names no install, is unavailable: it closes the + socket and sends nothing (`88b50886:lanes-index:9160-9173`; socket API + section 13.8 at `fa613b9d`). So the listener writes the owner file the + service would (`_owner_lines`), whole, at 0600, by a temporary file and + a rename (`write_record`), after its bind and before its listen, as the + service writes its own before its socket can be reached (section 2.4, + "How it is written"). Nothing removes it, as nothing removes the + service's: the next service replaces it. + + WITH `answer` (T237zze), a connection that sent any bytes is answered + with `answer` before it is closed, as a service answers a request; one + that sent none is closed with nothing sent, and its record is `b""`.""" + + def __init__(self, est: Estate, hang: bool, whole: bool = False, answer: bytes = None): + import socket + run = _run_dir(est) + run.mkdir(parents=True, exist_ok=True, mode=0o700) + run.chmod(0o700) + self.path = run / "register.sock" + self.server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + self.server.bind(str(self.path)) + write_record(run / "register.owner", _owner_lines(est.index)) + self.server.listen(8) + self.got, self.held, self.stop_ = [], [], threading.Event() + # Every socket `accept` gave before `stop_`, registered under `lock`, + # and taken out, under `lock`, only as `_take` closes it (T237zzw). + # One `accept` gives once `stop_` is set is closed by the thread, at + # once, and never registered (T237zzza). + self.lock, self.conns = threading.Lock(), [] + + def serve(): + self.server.settimeout(0.2) + while not self.stop_.is_set(): + try: + conn, _ = self.server.accept() + except OSError: + continue + self._accepted(conn) + with self.lock: + if self.stop_.is_set(): + # `close()` has begun, and its passes over `conns` may + # be over: no one else would close it (T237zzza). + conn.close() + break + self.conns.append(conn) + self._take(conn, hang, whole, answer) + + self.thread = threading.Thread(target=serve, daemon=True) + self.thread.start() + + def _accepted(self, conn) -> None: + """THE SEAM BETWEEN `accept` AND THE REGISTRY (T237zzza; Codex's + review of P09 at `d3a2fd5c`, SHOULD 1): `serve` calls it with each + socket `accept` gives, before it takes `lock`. Here it does nothing; + a case's subclass holds the thread in it, so the window in which a + socket is accepted and not yet registered stays open while `close()` + runs.""" + + def _take(self, conn, hang: bool, whole: bool, answer: bytes) -> None: + """One registered connection, taken as `serve` took it before + T237zzza, which moved it here unchanged: its request read (with + `whole`, to its `end`), recorded in `got`, answered with `answer` + where it sent bytes, then held (`hang`), or taken out of `conns` and + closed under `lock`.""" + conn.settimeout(1.0) + data = b"" + try: + data = conn.recv(65536) + while whole and data and b"\nend\n" not in data: + chunk = conn.recv(65536) + if not chunk: + break + data += chunk + except OSError: + pass + self.got.append(data) + if answer is not None and data: + try: + conn.sendall(answer) + except OSError: + pass + if hang: + self.held.append(conn) + else: + with self.lock: + self.conns.remove(conn) + conn.close() + + #: How long `close()` waits for the thread once it has shut down every + #: socket the thread holds (T237zzw). + JOIN_S = 5.0 + + def close(self) -> None: + """The thread ended, and every socket it accepted closed, then the + listening one (T237zzw; Codex's review of P09 at `21dd3642`, SHOULD + 8). `stop_` is set; then, under `lock`, the listening socket is shut + down, so a connect is refused from here on (one already queued may + still be accepted, and is closed as below), and each registered + socket too, so a `recv` or `sendall` on it returns at once. Then the + thread has `JOIN_S` s to end, and only then is each registered socket + closed, so none is added after the closing pass. + + A socket `accept` gave and the thread has not yet registered, as + where the thread is held between the two (`_accepted`), is never + registered once `stop_` is set: the thread closes it itself, under + `lock`, and ends (T237zzza; Codex's review at `d3a2fd5c`, SHOULD 1). + Before that, a thread let go after the closing pass registered it, + saw `stop_` and ended, and `close()` returned with it open. So where + the thread has ended, every socket it accepted is closed, by `close()` + or by the thread; a thread still running fails the case, once every + registered socket is closed.""" + import socket + self.stop_.set() + with self.lock: + for sock in [self.server, *self.conns]: + try: + sock.shutdown(socket.SHUT_RDWR) + except OSError: + pass + self.thread.join(self.JOIN_S) + with self.lock: + for conn in self.conns: + conn.close() + self.server.close() + self.path.unlink(missing_ok=True) + if self.thread.is_alive(): + raise AssertionError(f"the listener's thread still runs {self.JOIN_S:g} s after " + f"close() shut its sockets down") + + +def test_the_listeners_close_ends_its_thread_and_closes_each_socket_it_accepted(): + """`_Listener.close()` (T237zzw; Codex's review of P09 at `21dd3642`, + SHOULD 8), with no engine, service or hook: a socket of the case's own in + a state home of its own (`_state_home`), and a client that is this case. + + (a) A held connection still being read when `close()` comes: the client + sends a byte every 0.2 s and never `end`, so `whole`'s read never meets + its 1 s pause. `close()` must return with the thread ended and each socket + the thread accepted closed. Before T237zzw it joined for 1 s, closed what + `held` held then, and returned with the thread still reading, so the + connection it went on to hold was never closed. + + (b) A thread that does not end: `close()` must fail the case, not return + as if it had ended. The listener's own thread is set aside for a stand-in + that waits on an event, and `JOIN_S` is 0.3 s.""" + import socket + + class Bare: + """What `_Listener` reads of an `Estate`: its state home, and a file + for `register.owner`'s `install=`.""" + def __init__(self): + self.base = {"XDG_STATE_HOME": str(_state_home())} + self.index = Path(__file__) + + listener = _Listener(Bare(), hang=True, whole=True) + client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + client.connect(str(listener.path)) + stop = threading.Event() + + def trickle(): + while not stop.is_set(): + try: + client.sendall(b"x") + except OSError: + return + stop.wait(0.2) + + feeder = threading.Thread(target=trickle, daemon=True) + feeder.start() + try: + deadline = time.monotonic() + 30 + while time.monotonic() < deadline: + with listener.lock: + if listener.conns: + break + time.sleep(0.05) + time.sleep(0.5) + listener.close() + ended = not listener.thread.is_alive() + finally: + stop.set() + feeder.join(5) + client.close() + assert ended, "close() returned while the listener's thread was still reading a held connection" + assert len(listener.conns) == 1 and all(conn.fileno() == -1 for conn in listener.conns), \ + f"close() left a socket the thread accepted open: {listener.conns!r}" + assert all(set(data) <= {ord("x")} for data in listener.got), listener.got + + stuck = _Listener(Bare(), hang=False) + own, gate = stuck.thread, threading.Event() + stuck.thread = threading.Thread(target=gate.wait, daemon=True) + stuck.thread.start() + stuck.JOIN_S = 0.3 + try: + with pytest.raises(AssertionError, match="still runs"): + stuck.close() + finally: + gate.set() + stuck.thread.join(5) + own.join(5) + assert not own.is_alive(), "the listener's own thread outlived close()" + + +class _LateThread: + """A stand-in for `_Listener`'s thread while the real one is held in its + seam, `_accepted` (T237zzza): `close()`'s `join` returns at once, as a + join whose `JOIN_S` ran out, once it has tried one connect, which a + listener shut down before the join refuses (`refused`); `is_alive` first + lets the real thread go and waits for it, so the thread goes on after + `close()`'s closing pass and before `close()` reads whether it ended.""" + + def __init__(self, thread: threading.Thread, let_go: threading.Event, path: Path): + self.thread, self.let_go, self.path, self.refused = thread, let_go, path, None + + def join(self, timeout=None) -> None: + import socket + knock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + try: + knock.connect(str(self.path)) + self.refused = False + except ConnectionRefusedError: + self.refused = True + finally: + knock.close() + + def is_alive(self) -> bool: + self.let_go.set() + self.thread.join(30) + return self.thread.is_alive() + + +@pytest.mark.parametrize("released", ["inside-close", "after-close"]) +def test_a_socket_accepted_as_the_listener_closes_is_closed_and_close_tells_the_truth(released): + """`_Listener`'s window between `accept` and its registry (T237zzza; + Codex's review of P09 at `d3a2fd5c`, SHOULD 1), with no engine, service + or hook: a socket of the case's own in a state home of its own + (`_state_home`), a client that is this case, and the listener's seam, + `_accepted`, in which the thread is held with the client's socket + accepted and not registered while `close()` runs. + + `[inside-close]`: the window is let go inside `close()`, after its + closing pass and before its last look at the thread, as Codex's + descheduled thread would be (`_LateThread`). Before T237zzza the thread + then registered the socket, saw `stop_` and ended, and `close()` + returned with the socket open. Now `close()` returns, the thread has + ended and the socket is closed; and a connect tried while `close()` + waited for the thread is refused, the listener being shut down first. + + `[after-close]`: the window is held through all of `close()`, with + `JOIN_S` 0.3 s, so `close()` must fail the case, its thread alive. Let + go, the thread must end and close the socket itself: before T237zzza it + registered it after the closing pass, and no one closed it.""" + import socket + arrived, let_go, taken = threading.Event(), threading.Event(), [] + + class Held(_Listener): + def _accepted(self, conn) -> None: + taken.append(conn) + arrived.set() + let_go.wait(30) + + listener = Held(types.SimpleNamespace(base={"XDG_STATE_HOME": str(_state_home())}, + index=Path(__file__)), hang=True) + own, late = listener.thread, _LateThread(listener.thread, let_go, listener.path) + client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + try: + client.connect(str(listener.path)) + assert arrived.wait(10), "the listener's thread never held an accepted socket in its seam" + if released == "inside-close": + listener.thread = late + listener.close() + else: + listener.JOIN_S = 0.3 + with pytest.raises(AssertionError, match="still runs"): + listener.close() + finally: + let_go.set() + listener.stop_.set() + own.join(30) + client.close() + assert not own.is_alive(), "the listener's thread outlived the window it was held in" + assert len(taken) == 1 and taken[0].fileno() == -1, \ + f"a socket accepted as close() came was left open: {taken!r}" + assert not listener.conns, f"a socket accepted once stop_ was set was registered: {listener.conns!r}" + assert released == "after-close" or late.refused, \ + "a connect tried while close() waited for the thread was not refused: the listener was not shut down first" + + +class _Service: + """`lanes-index serve` started by the test, stopped at teardown.""" + + def __init__(self, est: Estate, program=None, **extra): + self.est = est + if getattr(est, "pg", None) is not None: + _seed_primary(est) + # A DEAD SERVICE'S SOCKET IS NOT THIS ONE'S (T237zi; lane 5, #165 + # 6837268276): where one is left, the wait is for the socket that + # replaces it, so a case never reads the stale inode as the new one. + stale = _stale_socket(est) + self.proc = subprocess.Popen([sys.executable, str(program or est.index), "serve"], + stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, + stderr=subprocess.PIPE, env=est.env(**extra), + cwd=str(est.wip), start_new_session=True) + est.spare.append(self.proc.pid) + self.dir = _until(lambda: _service_dir(est, stale), 10) + if not self.dir: + # WHAT `serve` SAID, where it has exited: until lane 5's T512 + # (L5-S1), `lanes-index` answers 64, "unknown subcommand 'serve'". + # Read without waiting, so a child holding the pipe cannot hang it. + code, said = self.proc.poll(), b"" + if code is not None: + os.set_blocking(self.proc.stderr.fileno(), False) + said = self.proc.stderr.read() or b"" + assert self.dir, (f"the service named no socket: {code} " + f"{said.decode('utf-8', 'replace').strip()}") + + def stop(self) -> None: + _kill(self.proc.pid, signal.SIGTERM) + try: + self.proc.wait(10) + except subprocess.TimeoutExpired: + _kill(self.proc.pid) + + +def _both(est: Estate) -> tuple: + """The guard's answer with the service up, then with it down. The + service is warmed by one request first: a cold service answers + `unavailable` until its `psql` has connected (d8:502), and a service + holding no image answers its first request so (the cache miss).""" + svc = _Service(est) + try: + est.hook("hello") + up = est.hook("hello") + finally: + svc.stop() + down = est.hook("hello") + return up, down + + +#: THE STREAMING `psql`, T237y's `STREAM_PSQL` (`tests/test_sql_register_bounds.py` +#: on line W3a) in this module's own form, since this line does not carry that +#: module. PSQL_SHIM reads its stdin to the end before it hands a call on (its +#: `main()`), so the service's "one long-lived `psql` child on pipes" (d8 +#: section 7, d8:229) never answers through it, and a case that rested on it +#: read the direct read's calls instead (lane 5's T512 plan, point 2, #165 +#: 6827295319). This stand-in starts the real `psql` at once, on the caller's +#: stdout and stderr, and hands its stdin on chunk by chunk through a delay +#: line: each chunk goes on `stream-hold-ms` milliseconds (a file beside it, +#: read as each chunk comes) after it was read where the call is the service's +#: held child, known by its own argv's `VERBOSITY=sqlstate` (d8:229), and at +#: once for every other call, the guard's direct reads among them. It logs +#: each call's argv in `stream-begin.log`, after it has written the call's +#: whole environment, `PGPASSWORD`'s value written `*` as PSQL_SHIM writes +#: it, to `stream-env.<pid>.json` beside it, by a temporary file and a rename +#: (T213r reads the held child's `PGPASSFILE`, `PGPASSWORD` and any URL +#: there, since PSQL_SHIM never runs that child); and each chunk as it reads it, with +#: its monotonic time, the hold in force and whether the call is the held +#: child, in `stream-chunks.log`, so a chunk that the service's SIGINT +#: overtakes is logged all the same. SIGINT and SIGTERM go on to the real +#: `psql`; `psql --version` is the real one's. +_STREAM_PSQL = r'''#!@PY@ -I +import json, os, queue, signal, subprocess, sys, threading, time +HERE = @HERE@ +REAL = @REAL@ +args = sys.argv[1:] +held = "VERBOSITY=sqlstate" in args + + +def log(name, record): + with open(os.path.join(HERE, name), "a", encoding="utf-8") as handle: + handle.write(json.dumps(record, sort_keys=True) + "\n") + + +def hold_ms(): + try: + with open(os.path.join(HERE, "stream-hold-ms"), encoding="utf-8") as handle: + return float(handle.read().strip() or 0) + except (OSError, ValueError): + return 0.0 + + +env_file = os.path.join(HERE, "stream-env.%d.json" % os.getpid()) +with open(env_file + ".tmp", "w", encoding="utf-8") as handle: + json.dump({k: "*" if k == "PGPASSWORD" else v for k, v in os.environ.items()}, handle, + sort_keys=True) +os.replace(env_file + ".tmp", env_file) +log("stream-begin.log", {"argv": args, "pid": os.getpid(), "held": held, "t": time.monotonic()}) +if args == ["--version"]: + os.execv(REAL, [REAL] + args) +proc = subprocess.Popen([REAL] + args, stdin=subprocess.PIPE) +for number in (signal.SIGINT, signal.SIGTERM): + signal.signal(number, lambda sig, frame: proc.send_signal(sig)) +line = queue.Queue() + + +def read(): + while True: + try: + chunk = os.read(0, 65536) + except OSError: + chunk = b"" + now = time.monotonic() + hold = hold_ms() if held else 0.0 + if chunk: + log("stream-chunks.log", {"pid": os.getpid(), "held": held, "read": now, + "hold_ms": hold, "bytes": len(chunk)}) + line.put((now + hold / 1000, chunk)) + if not chunk: + return + + +def feed(): + while True: + due, chunk = line.get() + if not chunk: + break + wait = due - time.monotonic() + if wait > 0: + time.sleep(wait) + try: + proc.stdin.write(chunk) + proc.stdin.flush() + except OSError: + break + try: + proc.stdin.close() + except OSError: + pass + + +for target in (read, feed): + threading.Thread(target=target, daemon=True).start() +code = proc.wait() +sys.exit(code if code >= 0 else 128 - code) +''' + + +class _StreamPsql: + """`_STREAM_PSQL` first on the estate's `PATH` as `psql` (its `bin`, as + `Estate.shim` puts PSQL_SHIM), in front of the case's cluster's own + `psql`, with no hold until `hold` sets one. + + IN A DIRECTORY OF ITS OWN, with `where` (T237zu): no `PATH` holds it + until a case puts it first on one (`path`), as SVC-10 does on the + service's alone, so the guard's own reads run the real `psql`.""" + + def __init__(self, est: Estate, where=None): + self.dir = est.bin if where is None else Path(where) + self.dir.mkdir(parents=True, exist_ok=True) + _script(self.dir / "psql", _STREAM_PSQL, PY=sys.executable, HERE=_q(self.dir), + REAL=_q(est.pg.cluster.tool("psql"))) + + def path(self, est: Estate) -> str: + """The estate's `PATH` with this stand-in's directory first.""" + return os.pathsep.join([str(self.dir), est.env()["PATH"]]) + + def hold(self, ms: int) -> None: + """Each chunk handed to the service's held child from now on is held + `ms` milliseconds.""" + (self.dir / "stream-hold-ms").write_text(str(ms), encoding="utf-8") + + def log(self, name: str = "stream-chunks.log") -> list: + path = self.dir / name + if not path.exists(): + return [] + return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() + if line.strip()] + + def handed(self, hook: Hook) -> list: + """The chunks the service's held child read while `hook` ran (one + monotonic clock for the runner and the stand-in, as on Linux).""" + return [c for c in self.log() if c["held"] and hook.t0 <= c["read"] <= hook.t_exit] + + +#: How long a case warms the service, in guard runs, before it reads it. +WARM_S = 15.0 + + +def _warm(est: Estate, limit: float = WARM_S) -> Hook: + """Guard runs until one is answered by the service, with no fallback + line (d8 section 5.3), returned: a cold service answers `unavailable` + until its `psql` has connected (d8:502), and one holding no image + answers its first request so (the cache miss), as T237y's case warms + it.""" + end = time.monotonic() + limit + while True: + hook = est.hook("hello") + if FALLBACK not in hook.err: + return hook + assert time.monotonic() < end, \ + f"no guard run was answered by the service in {limit:.0f} s: {hook!r}" + time.sleep(0.2) + + +def _service_backends(pg) -> set: + """The pids of the case's database's `lanes-index` client backends, by + the `application_name` the service's `psql` carries (`PGAPPNAME`, d8 + section 7). Between guard runs that is the service's held connection + alone, once a direct read's backend has gone.""" + sql = ("SELECT pid FROM pg_catalog.pg_stat_activity WHERE datname = current_database() " + "AND application_name LIKE 'lanes-index%' AND pid <> pg_backend_pid();") + return {int(word) for word in pg.psql(sql).stdout.split()} + + +def _sha(text: str) -> str: + return hashlib.sha256(text.encode("utf-8")).hexdigest() + + +class _Register: + """THE ESTATE'S REGISTER IN THE CASE'S DATABASE (T205's `pg`), brought to + `primary` with the marker `present` by lane 1's own functions, as line + N1's `RealRegister` does (T217h): as T228's writer login, one + `commit_write` `import` entry holding the estate's `lanes/LANES.md`, then + a `cutover` entry, which writes `lanes/STORE` alone (ruling 1), then + `record_marker`. So the guard on `mode=primary`, through the service or + directly, reads the register the case seeded, and the case knows each + file's whole text (lane 2's reading). `lanes/log/README.md` is not sent: + the `files` table's path CHECK refuses it (Q18 (A)). + + THE FORMS are `refs/l1/T112-fu2`'s `lanes-index` (L1-A6, T107): the call + `commit_write(bigint, uuid, integer, uuid, jsonb)` as one request, + `BEGIN ISOLATION LEVEL SERIALIZABLE`, the call, `COMMIT` + (`register_commit_request`), at `register_head.seq` and + `register_switch.generation`, with the client version the schema's own + `version`; the entry's `journal` keys as `register_commit_entry` writes + them, its `edits` with `ord` from 1, and a `files` row per path carrying + the sha256 of the path's whole new text (step 8's proof). A write sends + no structured rows: no step requires them, and the guard reads files. + + FAILS UNTIL T227 builds `tmpl` by the bootstrap (lane 1's L1-A7) and + T228 makes the logins, each by its own assertion, never a psql error.""" + + #: T228's fixture writer login, a member of REGISTER-WRITER. + WRITER = "lanes_w_fx" + #: The render set the case seeds: the estate's register file. + PATHS = ("lanes/LANES.md",) + + def __init__(self, est: Estate): + self.pg = est.pg + assert self._one("SELECT to_regclass('lanes_register.register_head') IS NOT NULL;") \ + == "t", ("the pg fixture's database holds no lanes_register schema: lane 2's T227 " + "builds tmpl by the bootstrap, which waits for lane 1's L1-A7") + can = self._one("SELECT count(*) FROM pg_catalog.pg_roles WHERE rolcanlogin AND " + f"rolname = '{self.WRITER}';") + assert can == "1", (f"no {self.WRITER} login: lane 2's T228 makes it by `lanes-index " + "login add fx`; the group REGISTER-WRITER is NOLOGIN") + self.client = int(self._one("SELECT version FROM lanes_register.schema_version;")) + self.generation = self._one("SELECT generation FROM lanes_register.register_switch;") + self.files = {path: (est.wip / path).read_text(encoding="utf-8") for path in self.PATHS} + edits, rows = [], [] + for path, text in self.files.items(): + edits.append({"ord": len(edits) + 1, "op": "create", "path": path}) + for line in text[:-1].split("\n") if text.endswith("\n") else text.split("\n"): + edits.append({"ord": len(edits) + 1, "op": "append", "path": path, + "new_text": line}) + rows.append({"path": path, "present": True, "sha256": _sha(text), + "final_newline": text.endswith("\n")}) + self.send("import", "import", edits, rows) + store = "mode primary\n" + self.send("cutover", "cutover", + [{"ord": 1, "op": "create", "path": "lanes/STORE"}, + {"ord": 2, "op": "append", "path": "lanes/STORE", "new_text": store[:-1]}], + [{"path": "lanes/STORE", "present": True, "sha256": _sha(store), + "final_newline": True}]) + marked = self._one(f"SELECT lanes_register.record_marker({self.client}, {self.head()}, " + f"'{'3' * 40}', '{HOST}');", user=self.WRITER) + assert marked == "present", ("record_marker answered", marked) + + def _one(self, sql: str, user=None) -> str: + proc = self.pg.psql(sql) if user is None else self.pg.psql(sql, user=user) + out = proc.stdout.strip().splitlines() + return out[-1].strip() if out else "" + + def head(self) -> int: + return int(self._one("SELECT seq FROM lanes_register.register_head;")) + + def line_of(self, path: str, lane: str) -> int: + """The line number of `lane`'s row in `path`.""" + lines = self.files[path].split("\n") + found = [n for n, line in enumerate(lines, 1) if line.startswith(f"| `{lane}` |")] + assert len(found) == 1, (lane, found) + return found[0] + + def send(self, kind: str, verb: str, edits: list, rows: list) -> int: + """One `commit_write` call as the writer's login, at the head the + database holds; the seq it committed.""" + # `journal.author` is `Name <address>` (its CHECK, `^[^<>]+ <[^<>]*>$`). + journal = {"kind": kind, "verb": verb, "lane": FROM, "workstation": HOST, + "author": "T237 case <t237@example.invalid>", + "message": f"{kind} by T237's case", + "git_commit": "1" * 40 if kind == "import" else None, + "git_tree": "2" * 40 if kind == "import" else None, + "repos_blob": None, "args_sha256": "0" * 64} + entry = {"journal": journal, "not_after": "2999-12-31T00:00:00Z", "edits": edits, + "files": rows} + literal = json.dumps(entry, ensure_ascii=True, separators=(",", ":")) + sql = ("BEGIN ISOLATION LEVEL SERIALIZABLE;\n" + f"SELECT lanes_register.commit_write({self.head()}, '{uuid.uuid4()}'::uuid, " + f"{self.client}, '{self.generation}'::uuid, $entry${literal}$entry$::jsonb);\n" + "COMMIT;\n") + return int(self.pg.psql(sql, user=self.WRITER).stdout.split()[0]) + + def replace(self, path: str, line_no: int, new_text: str) -> int: + """THE WRITE: one committed `write` entry whose one edit replaces line + `line_no` of `path`, its `old_sha256` the sha256 of the line's text + without its LF (step 6), and whose `files` row carries the sha256 of + the path's whole new text; the seq it made.""" + lines = self.files[path].split("\n") + old = lines[line_no - 1] + lines[line_no - 1] = new_text + text = "\n".join(lines) + seq = self.send("write", "start-record", + [{"ord": 1, "op": "replace", "path": path, "line_no": line_no, + "old_sha256": _sha(old), "new_text": new_text, "to_path": None}], + [{"path": path, "present": True, "sha256": _sha(text), + "final_newline": text.endswith("\n")}]) + self.files[path] = text + return seq + + +def _live_other(est: Estate): + """Another session, `est.other`, live in a window of the lane `FROM`: its + own live record under the estate's `HOME` (T203c's `guard_session`), its + stand-in `tmux` in a directory of its own, never on the case's `PATH`.""" + other = guard_session(est.home, est.root / "other-bin", est.wip, window=FROM, + session_id=est.other, name=FROM) + est.sessions.append(other) + return other + + +#: The test plan's three states, one for each guard answer (TP:1883-1886). +GUARD_STATES = ["ok", "refuse", "offer"] + + +def _guard_state(estate, state: str) -> Estate: + """THE STATE, in the register the guard reads on primary (`_Register`): + + - `ok`, this session's lane bound to this window: the session named + `FROM`, in the window `FROM`, whose row names it; + - `refuse`, another session holding the lane, and live: the window's row + names `est.other`, which `_live_other` makes live; + - `offer`, the module's estate: the window `FROM`, whose row names this + session, and the session named `TO`, a lane with a row of its own, so + the guard makes its offer (`Estate.make_offer`). The test plan words it + "an unbound window"; lane 5's bind-record contract makes the offer on + this name drift (lane 2's reading).""" + if state == "offer": + est = estate(mode="primary") + else: + est = estate(mode="primary", to=FROM, to_row=False) + if state == "refuse": + _live_other(est) + est.push_register([_row(FROM, est.other, "LIVE")]) + _Register(est) + return est + + +def _connected(est: Estate) -> bool: + """Wait until the service holds its connection: a client backend on the + case's database other than this read's own.""" + sql = ("SELECT count(*) FROM pg_catalog.pg_stat_activity WHERE datname = current_database() " + "AND pid <> pg_backend_pid() AND backend_type = 'client backend';") + return bool(_until(lambda: int(est.pg.psql(sql).stdout.strip() or 0) > 0, 10, 0.1)) + + +@pytest.mark.parametrize("state", GUARD_STATES) +def test_the_guard_through_the_service_answers_byte_identical_to_the_direct_read(estate, state): + """AT-10: on one state, the service path and the direct path give equal + stdout, equal stderr once the one fallback line is removed, and equal + exit codes: `[ok|refuse|offer]`, one state for each guard answer + (TP:2009; the states at TP:1883-1886, `_guard_state`).""" + est = _guard_state(estate, state) + up, down = _both(est) + assert down.err.count(FALLBACK) == 1 and FALLBACK not in up.err, (up.err, down.err) + err = [line for line in down.err.splitlines() if line != FALLBACK] + assert (up.code, up.out) == (down.code, down.out), (up, down) + assert up.err.splitlines() == err, (up.err, down.err) + + +def test_with_the_service_down_the_hook_falls_back_and_says_so(estate): + """AT-10: with the service down the hook reads directly and its stderr + carries the fallback line exactly once.""" + est = estate(mode="primary") + hook = est.hook("hello") + assert hook.err.splitlines().count(FALLBACK) == 1, hook.err + assert not hook.killed and hook.t_exit - hook.t0 < BUDGET, repr(hook) + + +def test_a_service_that_never_answers_falls_back_inside_5_s(estate): + """AT-10: a socket that accepts and never answers: the hook falls back to + the direct read and ends inside its 5 s, not killed.""" + est = estate(mode="primary") + listener = _Listener(est, hang=True) + try: + hook = est.hook("hello") + finally: + listener.close() + assert listener.got, "the client never connected to the socket at the fixed path" + assert not hook.killed and hook.t_exit - hook.t0 < HOOK_TIMEOUT, repr(hook) + assert hook.err.count(FALLBACK) == 1, hook.err + + +def test_the_database_unreachable_with_the_service_up_is_2_never_a_cached_ok(estate): + """AT-10: with the service up and the database unreachable, the guard + exits 2, never a cached 0.""" + est = estate(mode="primary") + svc = _Service(est) + est.hook("hello") + est.pg.cluster.stop() + try: + hook = est.hook("hello") + finally: + est.pg.cluster.start_again() + svc.stop() + assert hook.code == 2 and not hook.killed, repr(hook) + + +#: THE HOLD on each chunk handed to the service's held child in the timer's +#: case: past the 200 ms timer with no `register_rtt_ms=`, and inside the +#: 250 ms at 150 (d8 section 6.2). The answer comes the hold and the real +#: `psql`'s run, a few ms, after the request reached the service, near the +#: middle of that window. +STREAM_HOLD_MS = 220 + + +@pytest.mark.parametrize("rtt", ["none", "rtt-150"]) +def test_the_services_request_timer_follows_register_rtt_ms(estate, rtt): + """SVC-6 at X: the service's request timer is 200 ms, or the round trip + plus 100 ms where `register_rtt_ms=` is over 100 (250 ms at 150). + + The contract fixes the timer, not a `status` key, so the case reads it + from the answer, through the service's own `psql` (`_StreamPsql`, since + PSQL_SHIM never runs the held child: lane 5's T512 plan, point 2). The + service is warmed with no hold until a guard run is answered by it; then + each chunk handed to its held child is held `STREAM_HOLD_MS`, and one more + guard run's request reaches the held child and is held there: `[none]` + falls back, its 200 ms timer having expired, and `[rtt-150]` is answered + inside its 250 ms.""" + est = estate(mode="primary") + if rtt != "none": + _db_config(est, est.pg.url(), register_rtt_ms=150) + stream = _StreamPsql(est) + svc = _Service(est) + try: + _warm(est) + stream.hold(STREAM_HOLD_MS) + hook = est.hook("hello") + finally: + svc.stop() + held = [c for c in stream.handed(hook) if c["hold_ms"] == STREAM_HOLD_MS] + assert held, f"the guard's request never reached the service's held psql: {stream.log()}" + if rtt == "none": + assert hook.err.count(FALLBACK) == 1, hook.err + else: + assert FALLBACK not in hook.err, hook.err + + +def test_each_service_request_is_one_query(estate, request): + """AT-10: each request the service answers is one Query message. + + PSQL_SHIM's log cannot count it: the shim reads its stdin to the end + before it hands a call on, so the service's held `psql` never answers + through it, and the call it counted was the direct read's (lane 5's T512 + plan, point 2). So the case runs on T229's counting cluster (line FX's + `CountingCluster`), which logs one `statement:` line per Query message, + each with its backend's pid (`log_statement=all`): the service is warmed + until a guard run is answered by it, its held connection is then the one + `lanes-index` backend (d8 section 7), and one more answered guard run, + one request (form 2, d8 section 13.9), is one `statement:` line of that + backend's.""" + pgcluster = pytest.importorskip("pgcluster") + assert "CountingCluster" in vars(pgcluster), "tests/pgcluster.py has no counting cluster (T229)" + cluster = request.getfixturevalue("counting_cluster") + db = pgcluster.Database(cluster, cluster.new_database()) + est = estate() + est.primary(db) + svc = _Service(est) + try: + _warm(est) + held = _until(lambda: (lambda s: s if len(s) == 1 else None)(_service_backends(db)), + 10, 0.1) + assert held, f"no one lanes-index backend is left for the service: {_service_backends(db)}" + offset = cluster.log().stat().st_size + hook = est.hook("hello") + finally: + svc.stop() + time.sleep(0.2) # the server's last log line, as T229's smoke waits + text = cluster.log().read_bytes()[offset:].decode("utf-8", "replace") + pid = next(iter(held)) + queries = [line for line in text.splitlines() if f"[{pid}]" in line and "statement: " in line] + assert FALLBACK not in hook.err, hook.err + assert len(queries) == 1, queries + + +#: THE IDLE CHECK'S DEFAULT, kept for a value the contract ignores (d8 +#: section 10), and the case's two reads of it: no replacement by +#: `IDLE_CHECK_EARLY_S`, `[interval]`'s old wait, and one by +#: `IDLE_CHECK_LIMIT_S`. `[interval]` itself, at 1 s, waits for its +#: replacement to `IDLE_CHECK_INTERVAL_LIMIT_S`, ten checks (T237zm). +IDLE_CHECK_DEFAULT_S = 60 +IDLE_CHECK_EARLY_S = 2.5 +IDLE_CHECK_LIMIT_S = IDLE_CHECK_DEFAULT_S + 30 +IDLE_CHECK_INTERVAL_LIMIT_S = 10 + + +@pytest.mark.parametrize("case", ["interval", "floor", "cap"]) +def test_the_services_idle_check_replaces_a_dropped_connection_in_the_background(estate, case): + """SVC-6 (R37): `[interval]`, at `LANES_REGISTER_SERVE_IDLE_CHECK_S=1`, a + dropped connection is replaced in the background before the next + request. + + `[floor]`, 0.5, under the 1 s floor, and `[cap]`, 240, the load + balancer's 240 s: such a value is ignored, with the default 60 s kept, + never `config-refused` (tasks:1643; lane 5's socket contract d8, section + 10; lane 3's OP-14, #165 6746215510, which stands, #165 6827356485). So + `serve` listens and runs on, with no failure stamp (section 8.6), and + `[interval]`'s own observable shows the 60 s: the service's dropped + connection is not replaced within `IDLE_CHECK_EARLY_S`, as a check at + the value given or at the 1 s floor would have replaced it, and is + replaced within `IDLE_CHECK_LIMIT_S`, as a check at 240 s would not + have; the next request is then answered by the service. The replacement + is read in `pg_stat_activity` by its `application_name` (d8 section 7), + with no request in between, since a request on the dropped connection + would itself start the new one (d8 section 6.2).""" + est = estate(mode="primary") + value = {"interval": "1", "floor": "0.5", "cap": "240"}[case] + if case != "interval": + svc = _Service(est, LANES_REGISTER_SERVE_IDLE_CHECK_S=value) + try: + _warm(est) + dropped = _until(lambda: _service_backends(est.pg), 10, 0.1) + assert dropped, "the warmed service held no connection to drop" + est.pg.psql("SELECT pg_terminate_backend(pid) FROM pg_catalog.pg_stat_activity " + f"WHERE pid IN ({','.join(str(p) for p in dropped)});") + time.sleep(IDLE_CHECK_EARLY_S) + early = _service_backends(est.pg) - dropped + replaced = early or _until(lambda: _service_backends(est.pg) - dropped, + IDLE_CHECK_LIMIT_S - IDLE_CHECK_EARLY_S, 1.0) + hook = est.hook("hello") + code = svc.proc.poll() + stamp = (_run_dir(est) / "register.failed").exists() + finally: + svc.stop() + assert code is None and not stamp, \ + f"serve exited {code} or stamped a failure under LANES_REGISTER_SERVE_IDLE_CHECK_S={value}" + assert not early, (f"the dropped connection was replaced within {IDLE_CHECK_EARLY_S} s: " + f"the check ran at {value} s or at the 1 s floor, not at the default " + f"{IDLE_CHECK_DEFAULT_S} s") + assert replaced, (f"the dropped connection was not replaced within {IDLE_CHECK_LIMIT_S} s: " + f"the check did not run at the default {IDLE_CHECK_DEFAULT_S} s") + assert FALLBACK not in hook.err, hook.err + return + # WARMED FIRST, as `[floor]` and `[cap]` are (T237zj): the idle check's + # promise is the next request "answered from the new connection, not + # `unavailable`" (TP:1977-1981 at a6497d00), which presumes a service + # that already holds an image. An unwarmed one answers its first request + # `unavailable`, the cache miss (TP:1982-1987; d8 sections 5.1 and 5.3), + # so without the warm-up this hook fell back whatever the idle check did + # (lane 5, #165 6841406701). + # + # WHAT `[floor]` AND `[cap]` READ, READ HERE TOO (T237zm; lane 2's review + # RV20, finding 6): the service's own connection is found, and only it + # is dropped; its replacement is seen in `pg_stat_activity`, bounded at + # `IDLE_CHECK_INTERVAL_LIMIT_S`, before the hook; and the window and the + # session are both `FROM` (`swap_window`, as SVC-10's are), so the hook + # answers 0 only after a read that verified the triple. A refusal before + # any read, such as the start line's, is a 2, and fails the case. + est.swap_window(FROM, FROM) + svc = _Service(est, LANES_REGISTER_SERVE_IDLE_CHECK_S=value) + try: + _warm(est) + dropped = _until(lambda: _service_backends(est.pg), 10, 0.1) + assert dropped, "the warmed service held no connection to drop" + est.pg.psql("SELECT pg_terminate_backend(pid) FROM pg_catalog.pg_stat_activity " + f"WHERE pid IN ({','.join(str(p) for p in dropped)});") + replaced = _until(lambda: _service_backends(est.pg) - dropped, + IDLE_CHECK_INTERVAL_LIMIT_S, 0.1) + hook = est.hook("hello") + finally: + svc.stop() + assert replaced, (f"the dropped connection {sorted(dropped)} was not replaced within " + f"{IDLE_CHECK_INTERVAL_LIMIT_S} s at LANES_REGISTER_SERVE_IDLE_CHECK_S=1") + assert hook.code == 0 and FALLBACK not in hook.err, repr(hook) + + +@pytest.mark.parametrize("cache", ["empty-cache", "cache-holds-n"]) +def test_a_cache_miss_at_the_service_answers_unavailable_and_fetches_in_the_background( + estate, cache): + """AT-10, "A cache miss" (TP:2023; T302's image cache), on a service + that holds its connection: + + - `[empty-cache]`: a service holding no image yet, with the + per-environment image cache empty, answers its first request + `unavailable`; the client reads directly, the service fetches the + files whole in the background, and the next request is answered by + the service; + - `[cache-holds-n]`: with the cache already holding the files at `n`, + the first request is answered from it. A first service fills the + cache and is stopped, with the register still at `n`; a second + answers.""" + est = estate(mode="primary") + _Register(est) + if cache == "cache-holds-n": + svc = _Service(est) + try: + est.hook("hello") + filled = est.hook("hello") + finally: + svc.stop() + assert FALLBACK not in filled.err, f"the first service never filled the cache: {filled!r}" + svc = _Service(est) + try: + assert _connected(est), "the service held no connection in 10 s" + first = est.hook("hello") + second = est.hook("hello") + finally: + svc.stop() + if cache == "empty-cache": + assert first.err.count(FALLBACK) == 1 and FALLBACK not in second.err, (first, second) + else: + assert FALLBACK not in first.err and FALLBACK not in second.err, (first, second) + + +def test_a_write_between_two_requests_is_in_the_next_answer(estate): + """AT-10, "A fresh write": request, a write by another process, request; + the second answer equals the direct read made after the write. + + The write is T107's `commit_write` as T228's `lanes_w_fx`, in a + SERIALIZABLE transaction at `register_head.seq` and + `register_switch.generation` (`_Register.replace`): it replaces the + window's row so that another live session holds the lane, the test + plan's `refuse` state, where the first request met its `ok` state. So + the second answer differs from the first only by the write, and a + cached answer cannot pass. The service is warmed first, since a cold + service answers `unavailable` until its `psql` has connected (d8:502). + It fails until L1-A6 (T107) lands and T228's logins with T227's + template, as T237's Order says, beside L5-S1.""" + est = estate(mode="primary", to=FROM, to_row=False) + _live_other(est) + reg = _Register(est) + svc = _Service(est) + try: + est.hook("hello") + first = est.hook("hello") + seq = reg.replace("lanes/LANES.md", reg.line_of("lanes/LANES.md", FROM), + _row(FROM, est.other, "LIVE")) + second = est.hook("hello") + finally: + svc.stop() + direct = est.hook("hello") + assert seq == reg.head(), (seq, reg.head()) + assert FALLBACK not in first.err and FALLBACK not in second.err, (first, second) + assert direct.err.splitlines().count(FALLBACK) == 1, direct.err + assert (first.code, first.out, first.err) != (second.code, second.out, second.err), \ + f"the answer after the write is the answer before it: {second!r}" + assert not second.killed and (second.code, second.out) == (direct.code, direct.out), \ + (second, direct) + assert second.err.splitlines() == [line for line in direct.err.splitlines() + if line != FALLBACK], (second.err, direct.err) + + +#: `_masked_path`'s mirrors, by each directory's real path (None where the +#: directory holds no masked name), and the one temporary root they share. +_PATH_MIRRORS: dict = {} +_PATH_MIRROR_ROOT: list = [] + + +def _masked_path(path: str) -> str: + """`path` with every directory kept in its place, and each one that holds + a `psql`, a `lanes-index` or a name that starts `pg_` swapped for a + private mirror of it: a directory of links, one to each of its entries + by its absolute path, those names left out. The case below runs `serve` + with no `psql` on a `PATH` of Python's own directory and `/bin`; on a + GitHub runner `postgresql-16`'s client puts `psql` in `/usr/bin` with + `git` and `bash`, and `/bin` is a link to it, so that `PATH` held a + `psql` there (lane 1's census, #165 6807454856). A directory that holds + none of those names passes through unchanged. Each mirror is made once + per process, under one `mkdtemp` that an `atexit` handler removes.""" + parts = [] + for part in path.split(os.pathsep): + if not part: + continue + real = os.path.realpath(part) + if real not in _PATH_MIRRORS: + try: + names = os.listdir(real) + except OSError: + names = [] + masked = {name for name in names + if name in ("psql", "lanes-index") or name.startswith("pg_")} + mirror = None + if masked: + if not _PATH_MIRROR_ROOT: + _PATH_MIRROR_ROOT.append(tempfile.mkdtemp(prefix="l2-pathmask-")) + atexit.register(shutil.rmtree, _PATH_MIRROR_ROOT[0], ignore_errors=True) + mirror = os.path.join(_PATH_MIRROR_ROOT[0], str(len(_PATH_MIRRORS))) + os.mkdir(mirror) + for name in names: + if name not in masked: + os.symlink(os.path.join(real, name), os.path.join(mirror, name)) + _PATH_MIRRORS[real] = mirror + parts.append(_PATH_MIRRORS[real] or part) + return os.pathsep.join(parts) + + +def test_the_service_reaches_the_database_only_through_psql(estate): + """OP-10 (R-F10-20): every answer from the database is a call through + `psql`; with no `psql` at the start, `serve` stamps `no-psql` and exits 2 + before any socket exists, and the client's direct read answers. + + The first half reads the service's own `psql` through `_StreamPsql`: + PSQL_SHIM, which reads its stdin to the end first, never runs the + service's held child, so the call it logged was the direct read's (lane + 5's T512 plan, point 2). The guard run the service answers, with no + fallback line, handed its request to the held child, the `psql` the + service ran from `PATH`.""" + est = estate(mode="primary") + stream = _StreamPsql(est) + svc = _Service(est) + try: + hook = _warm(est) + finally: + svc.stop() + assert stream.handed(hook), \ + f"an answer came from the database without psql: {stream.log('stream-begin.log')}" + nopsql = subprocess.run([sys.executable, str(est.index), "serve"], capture_output=True, + text=True, timeout=30, cwd=str(est.wip), + env=est.env(PATH=_masked_path(os.pathsep.join( + [os.path.dirname(sys.executable), "/bin"])))) + stamp = _failure_stamp(est, nopsql) + # THE STAMP HOLDS THE UTC AND THE FIXED CAUSE, AND NO OTHER TEXT (section 8.6). + assert "no-psql" in stamp and len(stamp) == 2, (nopsql, stamp) + assert not (_run_dir(est) / "register.sock").exists(), "serve left a socket" + assert est.hook("hello").code in (0, 2) + + +def test_the_session_start_block_reads_the_mirror_and_only_starts_the_service(estate): + """A7: the `SessionStart` block reads the mirror and only starts the + service: no register call of its own, and a service running after.""" + est = estate(mode="primary") + est.shim() + proc = subprocess.run(["bash", str(est.guard), "session-start"], + input=est.session.hook_input(), capture_output=True, text=True, + env=est.env(), cwd=str(est.wip), timeout=60) + assert proc.returncode == 0 and not est.shim_calls(), est.shim_calls() + assert _until(lambda: _service_dir(est), 10), "the block did not start the service" + + +#: T237zzb: HOW LONG A CASE WAITS FOR A START IT MUST NOT MAKE, from its +#: `session-start`'s exit: past the start's own limit, `timeout -k 1 1` +#: (`reg_service_start`, at most 2 s), and past the 10 s in which the +#: control, `test_the_session_start_block_reads_the_mirror_and_only_starts_the_service`, +#: finds the socket its start made. +NO_START_S = 12.0 + +#: T237zzb's STAND-IN `lanes-index`, beside a copy of the estate's +#: `lanes-edit.sh`, where `lanes_index_bin` looks first. It logs each call's +#: words to @LOG@; answers `mode`, the block's one mode question +#: (`reg_mode_query`), as the case's state says, `index` with "index" and 0, +#: `78` with 78, EX_CONFIG, the code of a build that refuses `mode=primary`; +#: answers `serve` 0, starting nothing, while @OFF@ exists (the case's twin, +#: with T513's start disabled); and hands every other call, `serve --start` +#: included, to the estate's flipped `lanes-index`, @REAL@, on its primary +#: configuration. +_SESSION_SEAM = r'''#!/bin/sh +printf '%s\n' "$*" >> @LOG@ +case "${1-}" in + mode) + case @STATE@ in + index) printf 'index\n'; exit 0 ;; + 78) printf 'lanes-index: REFUSED: mode=primary in this build (T237zzb stand-in)\n' >&2 + exit 78 ;; + esac ;; + serve) + if [ -e @OFF@ ]; then exit 0; fi ;; +esac +exec @REAL@ "$@" +''' + +#: The block's last line (`ssb_tail`), whose age is the one word two runs +#: of one state can differ in (`fetch_age`: seconds, under 90 s). +AS_OF = re.compile(r"^as of .+ \(no fetch\)$", re.M) + + +def _estate_servers(est: Estate) -> list: + """The live processes of this estate's own `lanes-index`, its flipped + copy (`Estate.index`), with `serve` among the words after it: a start, + `serve --start`, or the service one starts, whose argv is that path and + `serve` (`register_serve_launch`). The path is compared by its real + path, as the guard resolves its own directory (`readlink -f`). For a + primary estate on the module's own guard it is the estate's own copy, + under its root, so no other estate's process carries it; a files-mode + estate's `Estate.index` is the checkout's `lanes-index`, which every + such estate shares. So it is a lookup for the primary cases that call + it, and never what the teardown signals by (T237zzd).""" + index = os.path.realpath(est.index) + found = [] + for entry in Path("/proc").iterdir(): + if entry.name.isdigit() and _alive(entry.name): + argv = _argv(entry.name) + at = [i for i, word in enumerate(argv) if word.startswith("/") + and os.path.realpath(word) == index] + if at and "serve" in argv[at[0] + 1:]: + found.append(int(entry.name)) + return found + + +@pytest.mark.parametrize("state", ["index", "78", "compact"]) +def test_session_start_starts_no_service_outside_primary(estate, state): + """T513's start runs only where the block's one mode answer is primary: + the `session-start` arm runs it after `session_start_block` returns, + keyed on that answer (lane 1's U5 review of T513, which asks for these + three cases, opensoft/openRepoTools#165 6882025131; lane 5, #165 + 6882048675, which gives them to lane 2 as T237zzb). `[index]`: the + answer `mode index`. `[78]`: `lanes-index mode` exits 78, EX_CONFIG, + which the block reads as a refused mode and a failed read + (`reg_mode_query`'s `78:*` arm, under `mirror`). `[compact]`: a + `SessionStart` whose `source` is `compact`, which returns before the + mode question. Each runs `session-start` and gets exit 0 and no register + call; after `NO_START_S` no `register.sock` exists and no `serve` of the + estate's `lanes-index` runs; the stand-in's log holds no `serve` call + and the block's one `mode` call, none for `[compact]`; and its stdout is + the bytes of the same state with T513's start disabled, the fetch's age + aside (`AS_OF`). + + THE CONTROL'S ESTATE, WITH ONE ANSWER CHANGED. Each case is the + control's primary estate, flipped build and configuration, with + `_SESSION_SEAM` beside a copy of its `lanes-edit.sh`: the block's one + mode question gets the case's answer, and every other call, `serve + --start` included, reaches the flipped `lanes-index` on that primary + configuration. A real index configuration or a refusing build is + refused again by `serve --start` (`register_serve_start_only`, which + refuses any mode but primary) and by `serve`, so a start there makes no + socket either, and a case run there would pass with the arm's mode test + gone. Here any start makes the control's socket, so "no socket" is + measured against a start that would make one.""" + est = estate(mode="primary") + est.shim() + seam = est.root / "seam" + seam.mkdir() + for name in ("lanes-edit.sh", "repos.tsv", "lane-start"): + if (est.guard.parent / name).exists(): + shutil.copy2(est.guard.parent / name, seam / name) + calls, off = seam / "lanes-index.calls", seam / "start-off" + _script(seam / "lanes-index", _SESSION_SEAM, LOG=shlex.quote(str(calls)), + STATE=shlex.quote(state), OFF=shlex.quote(str(off)), + REAL=shlex.quote(str(est.index))) + hook_input = est.session.hook_input() + if state == "compact": + hook_input = json.dumps(dict(json.loads(hook_input), hook_event_name="SessionStart", + source="compact"), separators=(",", ":")) + + def block() -> subprocess.CompletedProcess: + return subprocess.run(["bash", str(seam / "lanes-edit.sh"), "session-start"], + input=hook_input, capture_output=True, text=True, + env=est.env(), cwd=str(est.wip), timeout=60) + + proc = block() + assert proc.returncode == 0 and not est.shim_calls(), \ + (proc.returncode, est.shim_calls(), proc.stderr) + started = _until(lambda: _service_dir(est) or _estate_servers(est), NO_START_S, 0.25) + servers = _estate_servers(est) + est.spare.extend(servers) + assert not started and not servers and not (_run_dir(est) / "register.sock").exists(), \ + f"session-start [{state}] started the service: {started} {servers}\n{proc.stderr}" + words = [line.split(" ", 1)[0] for line in + calls.read_text(encoding="utf-8").splitlines()] if calls.exists() else [] + assert words.count("mode") == (0 if state == "compact" else 1) and "serve" not in words, words + off.write_text("", encoding="utf-8") + twin = block() + assert twin.returncode == 0, twin.stderr + assert AS_OF.sub("as of <age> (no fetch)", proc.stdout) == \ + AS_OF.sub("as of <age> (no fetch)", twin.stdout), (proc.stdout, twin.stdout) + + +def test_the_first_call_starts_the_service_with_no_supervisor(estate): + """A7: the first guard call starts the service detached, with no + supervisor: its parent is init or a subreaper, not the hook. + + AND ITS OWN REQUEST IS ANSWERED, by the direct read, since the guard + never waits for a start (TP:2051-2053, SVC-4; lane 3's erratum, on lane + 5's SHOULD 3, row 1). Since T237zza (lane 5, opensoft/openRepoTools#165 + 6881986067) the case asserts that answer, not only the start: the + estate's first prompt gets what `Estate.make_offer` asserts of it, exit 2 + with the name offer and the offer's record, from `FROM` to the session's + name; inside the guard's budget and not stopped by the runner; and with + the fallback line on stderr exactly once, the client's own word that the + service was unavailable and it read directly (`FALLBACK`). A first call + that started the service and then dropped its own request, or answered + it otherwise, passed the start's assertions alone.""" + est = estate(mode="primary") + # T237zzc: ONLY THIS ESTATE'S OWN SERVICE IS TAKEN, AND STOPPED AT THE + # TEARDOWN. The lookup took any process on the workstation whose argv + # ended in `serve`, another lane's service included, and `spare` stopped + # it. It now takes the processes of this estate's own `lanes-index` + # (`_estate_servers`, the `serve` its client starts); any other `serve` + # is printed and left alone, never signalled. A decoy this case starts, + # whose argv ends in `serve` as a service's does, shows it each run: it + # must be left out. It ends on its own when its stdin closes (or after + # 60 s), and nothing here signals it. + decoy = subprocess.Popen([sys.executable, "-c", + "import select, sys; select.select([sys.stdin], [], [], 60)", + "serve"], stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL) + try: + hook = est.hook("hello") + assert _until(lambda: _service_dir(est), 10), "the first call started no service" + servers = [p for p in _estate_servers(est) if _argv(p)[-1:] == ["serve"]] + foreign = [int(e.name) for e in Path("/proc").iterdir() if e.name.isdigit() + and _argv(e.name)[-1:] == ["serve"] and int(e.name) not in servers] + for pid in foreign: + print(f"T237zzc: a serve not this estate's, left alone: pid {pid} {_argv(pid)}") + assert decoy.poll() is None and decoy.pid in foreign and decoy.pid not in servers, \ + f"the lookup took a serve that is not this estate's (the decoy {decoy.pid}): {servers}" + finally: + decoy.stdin.close() + decoy.wait(10) + assert servers and all(_stat(p).get("ppid") != hook.pgid for p in servers), servers + est.spare.extend(servers) + # T237zza: THE FIRST CALL'S OWN ANSWER, after the start's assertions, so + # the service it started is already in `spare` when one of these fails. + record = est.record() + assert not hook.killed and hook.t_exit - hook.t0 < BUDGET, repr(hook) + assert hook.code == 2 and OFFER in hook.text, \ + f"the first call's own request was not answered with the name offer: {hook!r}" + assert record.get("mode") == "name-drift" and record.get("from") == FROM \ + and record.get("to") == est.to, f"the first call wrote no offer: {record}\n{hook!r}" + assert hook.err.splitlines().count(FALLBACK) == 1, \ + f"the first call was not answered by the direct read, once: {hook.err}" + + +@pytest.mark.parametrize("case", ["start-fails", "psql-14"]) +def test_a_service_that_cannot_start_falls_back_to_the_direct_read(estate, case): + """AT-10 and OP-10 (a): `[start-fails]`, a service that cannot start, and + the guard reads directly; `[psql-14]`, T203's fake answering 14, `serve` + stamps `no-psql`, exits 2 and leaves no socket, and the fallback read + refuses with 69 naming the version after one `--version` call and no + request.""" + est = estate(mode="primary") + if case == "psql-14": + est.shim() + control = est.bin / PSQL_SHIM_CONTROL + data = json.loads(control.read_text(encoding="utf-8")) + data["version"] = "psql (PostgreSQL) 14.11" + control.write_text(json.dumps(data), encoding="utf-8") + done = _index(est, "serve", timeout=30) + stamp = _failure_stamp(est, done) + assert "no-psql" in stamp and len(stamp) == 2, (done, stamp) + assert not (_run_dir(est) / "register.sock").exists(), "serve left a socket" + assert not [c for c in est.shim_calls()], "a request was sent past an old psql" + extra = {} + if case == "start-fails": + # A STATE PATH PAST 103 BYTES (section 2.1): the client starts nothing + # and reads directly, and `serve` refuses it with `path-too-long`. It + # is long on purpose, in place of the estate's short state home: its + # last part alone is 120 bytes, whatever the temporary root is. + deep = est.root / ("s" * 120) + deep.mkdir() + extra["XDG_STATE_HOME"] = str(deep) + done = _index(est, "serve", env=est.env(**extra), timeout=30) + failed = deep / "openRepoTools" / "run" / "register.failed" + assert done.returncode == 2 and "path-too-long" in failed.read_text(encoding="utf-8") + hook = est.hook("hello", **extra) + assert hook.code in (0, 2) and not hook.killed, repr(hook) + if case == "psql-14": + assert "14" in hook.err, hook.err + + +def test_the_guards_request_carries_only_file_names(estate): + """AT-10: the guard's request to the service carries only file names: no + URL, no password and no row text.""" + est = estate(mode="primary") + listener = _Listener(est, hang=False) + try: + est.hook("hello") + finally: + listener.close() + text = b"".join(listener.got).decode("utf-8", "replace") + # ITS FORM (the contract's request section): `read 1`; one line per thing + # it wants, `file <path>`, `set <prefix>` or `list`; then `end`. + lines = text.split("\n") + assert lines[0] == "read 1" and "end" in lines, text + body = lines[1:lines.index("end")] + assert body and all(line == "list" or (line.split(" ")[0] in ("file", "set") + and line.split(" ", 1)[1].startswith("lanes/")) + for line in body), text + assert "postgresql://" not in text and "password" not in text.lower(), text + + +#: THE REQUEST'S BOUND (T511's N-3; lane 5's one reading, #165 6868247441): +#: the whole request, its `end` line included, in bytes (socket API section +#: 13.3). T512's code takes it at both ends: the service refuses where +#: `end + 5 > REGISTER_SERVE_REQUEST_MAX`, `end` the offset of `\nend\n`, and +#: the client sends only where `len(data) <= REGISTER_SERVE_REQUEST_MAX` +#: (`lanes-index:8112` and `:9060` at line R's merge101 `44f487d1`). +REQUEST_MAX = 65536 +#: A request's bytes around its one log key, as the client writes form 1 for +#: one `log:<key>` member (socket API section 13.9): `read 1`, the `file` +#: line's words before the key, then its `.md` and the `end` line. +REQUEST_HEAD = b"read 1\nfile lanes/log/" +REQUEST_TAIL = b".md\nend\n" +#: How many times the 65,536-byte request is asked of a warmed service (lane +#: 2's RV26, NIT 6): a busy one can fall short of an answer by its request +#: timer or its read window (`lanes-index:8027-8039` at merge101), giving +#: `unavailable` or nothing with no `bad request` line, so only those ends +#: are asked again, and the assert is on the last answer. +TAKEN_TRIES = 3 + + +def _request_key(size: int) -> str: + """A log key that makes a form-1 request of one `log:<key>` member exactly + `size` bytes: letters alone, so it is in `check_lane_name`'s class and + goes as `--files log:<key>`, and no log has it.""" + return "k" * (size - len(REQUEST_HEAD) - len(REQUEST_TAIL)) + + +def _request(size: int) -> bytes: + """That request's bytes, as the client writes them (`_request_key`).""" + data = REQUEST_HEAD + _request_key(size).encode("ascii") + REQUEST_TAIL + assert len(data) == size, (len(data), size) + return data + + +def _ask_service(est: Estate, data: bytes, limit: float = 10.0) -> bytes: + """`data` sent whole on the service's socket, and its answer read to the + end of its stream: the service closes each connection after its one + answer (socket API section 3).""" + import socket as _socket + conn = _socket.socket(_socket.AF_UNIX, _socket.SOCK_STREAM) + conn.settimeout(limit) + try: + conn.connect(str(_run_dir(est) / "register.sock")) + conn.sendall(data) + out = b"" + while True: + chunk = conn.recv(1 << 20) + if not chunk: + return out + out += chunk + finally: + conn.close() + + +def _read_end(stderr: str, *masks: str) -> str: + """A read's last stderr line, each of `masks` (its cache path, its key) + put as `<m>` and its bracketed detail as `(...)`, which names a temp file + by pid: so two reads that end alike give the same text.""" + lines = [line for line in stderr.splitlines() if line.strip()] + end = lines[-1] if lines else "" + for mask in masks: + end = end.replace(mask, "<m>") + return re.sub(r"\(.*\)", "(...)", end) + + +def _bad_requests(est: Estate) -> int: + """`register.log`'s `bad request` lines, `<UTC> bad request`: the line the + service writes for a request it cannot take, the bound's refusal among + them, and for no other `unavailable` (`lanes-index:8713-8719` at + merge101), so never for a cold or busy service's.""" + path = _run_dir(est) / "register.log" + if not path.exists(): + return 0 + return sum(1 for line in path.read_text(encoding="utf-8").splitlines() + if line.endswith(" bad request")) + + +def test_a_65536_byte_request_is_sent_and_taken_and_a_65537_byte_one_is_neither(estate): + """T511'S REQUEST BOUND, N-3 (T237zt; lane 5's one reading, #165 + 6868247441, which T512's code takes at both ends): the whole request, its + `end` line included, is at most `REQUEST_MAX`, 65,536 bytes (socket API + section 13.3). One log key pads each request to its size + (`_request_key`); no log has it, so the service's answer needs no image + and meets no cache miss. + + - THE CLIENT, against a socket of the case's own (`_Listener`, `whole`): + `register read --prefetch --files log:<key>` (form 1) whose request is + 65,536 bytes sends it whole, those bytes exactly, and on the listener's + close falls back, writing `.direct`; one whose request would be 65,537 + bytes makes no connection and reads directly by its own decision, + writing no `.direct` (N5; `lanes-index:9313-9315` at merge101). That + it read directly is shown by its end: the same exit and last line as + the 65,536-byte fallback's direct read, cache, key and bracketed + detail masked (`_read_end`; lane 2's RV26, NIT 5), so a client that + refused the request itself fails. In this estate both direct reads + fail alike, exit 69, since its register's switch is `files`. + - THE SERVICE, warmed (`_warm`): those 65,536 bytes are taken, an answer + at `n` naming the log `absent`, with no `bad request` line, asked up to + `TAKEN_TRIES` times while a busy service gives `unavailable` or no + answer with no new `bad request` line (lane 2's RV26, NIT 6); 65,537 + bytes, the same request with one more byte of key, are answered + `unavailable`, with one `bad request` line in `register.log`, which the + bound's refusal writes and a cold or busy service's `unavailable` does + not (`_bad_requests`).""" + est = estate(mode="primary") + listener = _Listener(est, hang=False, whole=True) + sent, direct, said, ended = {}, {}, {}, {} + try: + for size in (REQUEST_MAX, REQUEST_MAX + 1): + cache = est.root / "t" / f"request-{size}" + before = len(listener.got) + done = _index(est, "register", "read", "--prefetch", "--cache", str(cache), + "--files", f"log:{_request_key(size)}") + sent[size] = [len(data) for data in listener.got[before:]] + direct[size] = os.path.lexists(f"{cache}.direct") + said[size] = f"exit {done.returncode}: {done.stderr.strip()[-300:]}" + ended[size] = (done.returncode, _read_end(done.stderr, str(cache), + _request_key(size))) + if sent[size] == [size]: + assert listener.got[before] == _request(size), \ + f"the client's {size}-byte request is not the bytes of `_request`" + finally: + listener.close() + assert sent[REQUEST_MAX] == [REQUEST_MAX] and direct[REQUEST_MAX], \ + (f"the client did not send its {REQUEST_MAX}-byte request whole and fall back: sent " + f"{sent[REQUEST_MAX]} bytes, .direct {direct[REQUEST_MAX]}; {said[REQUEST_MAX]}") + assert sent[REQUEST_MAX + 1] == [] and not direct[REQUEST_MAX + 1], \ + (f"the client sent a request of {REQUEST_MAX + 1} bytes: sent {sent[REQUEST_MAX + 1]} " + f"bytes, .direct {direct[REQUEST_MAX + 1]}; {said[REQUEST_MAX + 1]}") + assert ended[REQUEST_MAX + 1] == ended[REQUEST_MAX], \ + (f"the client's {REQUEST_MAX + 1}-byte read did not end as the direct read its " + f"{REQUEST_MAX}-byte fallback made: exit and last line {ended[REQUEST_MAX + 1]} " + f"against {ended[REQUEST_MAX]}; {said[REQUEST_MAX + 1]}") + svc = _Service(est) + try: + _warm(est) + bad = _bad_requests(est) + for _ in range(TAKEN_TRIES): + taken = _ask_service(est, _request(REQUEST_MAX)) + bad_taken = _bad_requests(est) + if taken not in (b"", b"unavailable\n") or bad_taken != bad: + break + refused = _ask_service(est, _request(REQUEST_MAX + 1)) + bad_refused = _bad_requests(est) + finally: + svc.stop() + name = b"lanes/log/" + _request_key(REQUEST_MAX).encode("ascii") + b".md" + lines = taken.split(b"\n") + assert lines[0].startswith(b"text ") and lines[1:] == [b"absent " + name, b"end", b""] \ + and bad_taken == bad, \ + (f"the service did not take a request of {REQUEST_MAX} bytes: {taken[:80]!r}, " + f"{len(taken)} bytes in all; bad request lines {bad} then {bad_taken}") + assert refused == b"unavailable\n" and bad_refused == bad_taken + 1, \ + (f"the service did not refuse a request of {REQUEST_MAX + 1} bytes as one it cannot " + f"take: {refused[:80]!r}; bad request lines {bad_taken} then {bad_refused}") + + +#: SVC-10'S 50 ms (TP:7976-7979 at a6497d00), recorded beside the served median, +#: and past which the case prints a warning and fails nothing (T237zo). +SVC10_BOUND_MS = 50 + + +def test_the_guard_answer_time_is_recorded_beside_todays_direct_guard(estate): + """SVC-10: the guard's answer time through the service is recorded beside + today's direct guard (M5b), with a warning past 50 ms and no failure. + + EACH SAMPLE'S READ PATH IS RECORDED BESIDE IT (T237zk; lane 5, #165 + 6841316861, and lane 3, 6838735040): SC-005 bounds the service's + answer, so a median over refusals and fallbacks says nothing of it. + Exit 2 is a refusal; exit 0 with the fallback line (`FALLBACK`, T507's + F1, tasks:806) matched whole on a stderr line is a fallback; exit 0 + without it was served, where the service shows it answered (below). + Each path's count is recorded, and the median of the served samples + alone, or "none served" where none was. A sample with any other end is + counted as `other`, so none is put in a path it did not take. The case + times the whole hook (`t_exit - t0`), so the served median is a + whole-hook figure, beside M5b's, not SC-005's 50 ms. + + SERVED IS THE SERVICE'S OWN WORD, NOT AN EXIT ALONE (T237zu; lane 2's + review RV23, NIT 1): exit 0 with no fallback line is also the end of a + client that never asked the service, as one that reads directly by its + own decision does (N5), with no fallback line. So a sample is served + only where the service's held `psql` child read a request while it ran + (`_StreamPsql.handed`), since each request the service answers is one + Query on that child (`test_each_service_request_is_one_query`); a + sample that ended 0 with neither is `other`. The stand-in is on the + service's `PATH` alone, with no hold, so the guard's own reads run the + real `psql`, and a served sample's time carries only the stand-in's one + pipe between the service and its child. + + THE PROMPT GOES THROUGH, AS M5b'S DOES (T237zl): the estate's session is + named `TO` in the window `FROM`, so every guard run made the name + guard's offer and exited 2, ten refusals and no served answer (lane 2's + G-19b capture). The window and the session are both `FROM` here, as + M5b's and M10's are (`swap_window`), and the service is warmed first + (`_warm`), so the samples read a service that holds its image, not the + cache miss of its first request.""" + est = estate(mode="primary") + est.swap_window(FROM, FROM) + stream = _StreamPsql(est, est.root / "service-bin") + svc = _Service(est, PATH=stream.path(est)) + paths = {"refusal": [], "fallback": [], "served": [], "other": []} + try: + _warm(est) + for _ in range(MEASURE_RUNS): + hook = est.hook("hello") + took = hook.t_exit - hook.t0 + if hook.code == 2: + paths["refusal"].append(took) + elif hook.code == 0 and FALLBACK in hook.err.splitlines(): + paths["fallback"].append(took) + elif hook.code == 0 and stream.handed(hook): + paths["served"].append(took) + else: + paths["other"].append(took) + finally: + svc.stop() + served = paths["served"] + _record_figure("SVC-10, the guard through the service (median ms)", + {"served answer (whole hook)": + f"{_median(served) * 1000:.1f}" if served else "none served", + "bound": f"{SVC10_BOUND_MS}"} + | {f"{name} samples": len(times) for name, times in paths.items()}) + # THE WARNING PAST 50 ms (T237zo; RV20, NIT 11): "the test prints a + # warning when the median exceeds it, without failing" (TP:7976-7979 at + # a6497d00). The median here is a whole-hook figure, so the warning says + # so; it fails nothing. It is RECORDED as the figures are (T237zs; lane + # 2's review RV23, NIT 2): pytest hides a passing test's own output, so + # a bare print reached no job summary. + if served and _median(served) * 1000 > SVC10_BOUND_MS: + _record_line(f"WARNING: SVC-10's served median, {_median(served) * 1000:.1f} ms for the " + f"whole hook, is over its {SVC10_BOUND_MS} ms (recorded, not failed)") + # SERVED, AND NOTHING ELSE UNKNOWN (T237zn; lane 2's review RV20, finding + # 10): every sample lands in one path, so `any(paths.values())` held + # whatever the paths were, ten refusals or ten fallbacks among them. The + # time stays unasserted, as TP:7976-7979 at a6497d00 has it, "without + # failing". NOR A REFUSAL (T237zr; lane 2's review RV23, NIT 1): with the + # window and the session both `FROM`, the guard has nothing to refuse, + # so a refusal is a path the case did not mean, and nine of them beside + # one served sample passed. A fallback stays counted and allowed: the + # service may answer `unavailable` while it fetches. AND SERVED BY THE + # SERVICE ITSELF (T237zu; RV23, NIT 1, the rest): a sample that ended 0 + # with no request read by the service's held child is `other`, never + # served, so a client that read directly with no fallback line fails + # here, where its exit alone passed before. + assert served and not paths["other"] and not paths["refusal"], \ + {name: len(times) for name, times in paths.items()} + + +def test_status_prints_the_services_lines_and_its_failure_stamp(estate): + """A5 (R44): `lanes-index status` prints the service's lines and its + failure stamp, as T512 writes them in `cmd_status`; with no service in + files mode it still prints the service's line, saying none runs. + + THE STAMP (lane 5, #165 6879639005): on `mode=primary`, with the + service's directory made by a service started and stopped, and a + failure stamp written in it, `register.failed`, in its form, `<UTC> + <cause>` (`lanes-index:7592-7600` at line R's merge106), `status` + prints its `service:` line and `service stamp: <cause> at <UTC> (` + (`:8904`), the stamp still holding back starts.""" + est = estate() + done = _index(est, "status") + assert [line for line in done.stdout.splitlines() if line.startswith("service")], \ + f"status printed no service line: {done.stdout}{done.stderr}" + est = estate(mode="primary") + _Service(est).stop() + utc = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) + (_run_dir(est) / "register.failed").write_text(f"{utc} no-psql\n", encoding="ascii") + done = _index(est, "status") + lines = done.stdout.splitlines() + assert [line for line in lines if line.startswith("service: ")], \ + f"status printed no service line on mode=primary: {done.stdout}{done.stderr}" + assert [line for line in lines + if line.startswith(f"service stamp: no-psql at {utc} (it holds back every start")], \ + f"status printed no service stamp line for the stamp {utc} no-psql: {done.stdout}{done.stderr}" + + +def test_the_socket_directory_is_a_0700_directory_of_this_uid_and_never_a_symlink(estate): + """SVC-2: the socket directory is a 0700 directory of this uid, never a + symlink.""" + est = estate(mode="primary") + svc = _Service(est) + st = os.lstat(svc.dir) + svc.stop() + import stat as stat_mod + assert stat_mod.S_ISDIR(st.st_mode) and (st.st_mode & 0o777) == 0o700, oct(st.st_mode) + assert st.st_uid == os.getuid() + # THE REFUSAL'S HALF (section 2.2; ERR-28): a directory that fails the + # check is never used: `serve` exits 2 naming it and writes nothing in it. + run = _run_dir(est) + run.chmod(0o755) + before = sorted(p.name for p in run.iterdir()) + done = _index(est, "serve", timeout=30) + assert done.returncode == 2 and str(run) in done.stdout + done.stderr, done + assert sorted(p.name for p in run.iterdir()) == before, "serve wrote in a refused directory" + + +#: A STAND-IN FOR `lanes-index serve` WHOSE PEER IS ANOTHER UID (lane 5, #165 +#: 6879639005): it loads `lanes-index` and replaces its one peer-credential +#: read, `register_peercred` (`lanes-index:7652` at line R's merge106), with +#: one that answers `os.getuid() + 1`, then runs `serve` as `main` does. +_OTHER_UID_SERVE = r'''import importlib.machinery, importlib.util, os, sys +sys.dont_write_bytecode = True +loader = importlib.machinery.SourceFileLoader("lanes_index_other_uid", @INDEX@) +module = importlib.util.module_from_spec(importlib.util.spec_from_loader(loader.name, loader)) +sys.modules[loader.name] = module +loader.exec_module(module) +if not callable(getattr(module, "register_peercred", None)): + sys.exit("lanes-index reads no peer credential through register_peercred (T512)") +module.register_peercred = lambda conn: os.getuid() + 1 +sys.exit(module.main(sys.argv[1:])) +''' + + +def _closed_for_another_uid(est: Estate) -> int: + """`register.log`'s lines for a client the service closed as another + uid's (`lanes-index:8704-8708` at line R's merge106).""" + path = _run_dir(est) / "register.log" + if not path.exists(): + return 0 + return sum(1 for line in path.read_text(encoding="utf-8").splitlines() + if line.endswith(" closed a client of another uid")) + + +def test_a_client_of_another_uid_is_closed_by_so_peercred(estate): + """SVC-2: a client of another uid is closed, with no answer, and the + service logs "closed a client of another uid". CI has no second uid, so + the service runs through a stand-in that loads `lanes-index` and replaces + its one peer-credential read, `register_peercred`, with one that answers + another uid (`_OTHER_UID_SERVE`; lane 5, #165 6879639005): this test's + own connection is then another uid's, and its request gets no answer.""" + est = estate(mode="primary") + stand_in = est.root / "t" / "serve-other-uid.py" + stand_in.parent.mkdir(parents=True, exist_ok=True) + stand_in.write_text(_OTHER_UID_SERVE.replace("@INDEX@", repr(str(est.index))), + encoding="utf-8") + svc = _Service(est, program=stand_in) + try: + before = _closed_for_another_uid(est) + try: + answer = _ask_service(est, b"read 1\nlist\nend\n") + except (BrokenPipeError, ConnectionResetError): + answer = b"" + after = _closed_for_another_uid(est) + finally: + svc.stop() + assert answer == b"" and after == before + 1, \ + (f"the service did not close a client of another uid with no answer: answered " + f"{answer[:80]!r}; 'closed a client of another uid' lines {before} then {after}") + + +#: T237zze: THE GUARD'S `lanes-index` WHOSE SERVER IS ANOTHER UID, the +#: client's half of `_OTHER_UID_SERVE` (tasks:2278 at lane 3's commit 31 +#: `8f50d105`). It goes beside a copy of the estate's `lanes-edit.sh`, where +#: `lanes_index_bin` looks first. It loads the estate's own `lanes-index`, +#: @INDEX@, so `register_serve_install` still states that file, the one the +#: owner file names, and replaces its one peer-credential read, +#: `register_peercred` (`lanes-index:7709` at line R's merge161), with one +#: that logs each call, its pid and its caller, to @LOG@ and answers +#: `os.getuid() + 1`. Then it runs `main` as the script does. +_OTHER_UID_CLIENT = r'''#!@PY@ -I +import importlib.machinery, importlib.util, os, sys +sys.dont_write_bytecode = True +loader = importlib.machinery.SourceFileLoader("lanes_index_other_uid_client", @INDEX@) +module = importlib.util.module_from_spec(importlib.util.spec_from_loader(loader.name, loader)) +sys.modules[loader.name] = module +loader.exec_module(module) +if not callable(getattr(module, "register_peercred", None)): + sys.exit("lanes-index reads no peer credential through register_peercred (T512)") + + +def register_peercred(conn): + with open(@LOG@, "a", encoding="utf-8") as log: + log.write(f"{os.getpid()} {sys._getframe(1).f_code.co_name}\n") + return os.getuid() + 1 + + +module.register_peercred = register_peercred +sys.exit(module.main(sys.argv[1:])) +''' + + +def test_the_client_treats_a_service_of_another_uid_as_unavailable(estate): + """SVC-2, THE CLIENT'S HALF: the guard's client treats a server of + another uid as unavailable and trusts no answer from it (tasks:2278 at + lane 3's commit 31 `8f50d105`, with T237's Tests at :2272 and T512's + verify at :1604; test-map row 634; design:3838-3843; socket API section + 3, `fa613b9d`:157-158, at draft 13). CI has no second uid, so, as + `test_a_client_of_another_uid_is_closed_by_so_peercred` does for the + service, the guard runs a stand-in `lanes-index`, `_OTHER_UID_CLIENT`, + whose `register_peercred` answers `os.getuid() + 1`. + + THE ORACLE (tasks:2278): a server of the case's own at the socket path + answers every request with the `ok` state's answer, in an estate whose + state is `refuse`. The guard prints `guard: direct (service + unavailable)` once, and its exit, stdout and stderr are the `refuse` + state's direct read, byte for byte. An answer it trusted would show: + the `ok` state's guard run is checked to differ from that direct read, + the fallback line aside. + + CODEX'S SHOULD ON COMMIT 31 (its delta review of `8f50d105`, which lane + 2 takes): the client reads the owner file after its connect and before + its uid check (socket API section 2.4, `fa613b9d`:143-145), and a file + it cannot use falls back the same way for another reason. So the server + is `_Listener`, which writes a whole, matching, 0600 `register.owner` + with `install=`, `pidns=` and `boot=` (`_owner_lines`). The case asserts + exactly one `register_peercred` call by the guard's client, and that + the one connection the server accepted got no request bytes: the + client sends none to a server of another uid (`lanes-index:9704-9705`, + before `sendall` at :9709, at line R's merge161; + `bc9ed80b:lanes-index:9102-9106`). + + THE `ok` STATE'S ANSWER is the real service's, on this estate's own + register. In the `ok` state (`_guard_state`'s), a `_Listener` records + the guard's request; the service is started and warmed (`_warm`, whose + run is the `ok` state's guard answer), and `_ask_service` sends it that + request. Then one write brings the register to `refuse`, as + `_guard_state` makes it, and the direct read is the guard's own + fallback from a `_Listener` that answers nothing: a client of this uid, + which sends the same request and starts no service. It fails until + L5-S1, lane 5's T512, whose client check it runs.""" + est = estate(mode="primary", to=FROM, to_row=False) + est.sql_register = _Register(est) + probe = _Listener(est, hang=False, whole=True) + try: + est.hook("hello") + finally: + probe.close() + assert len(probe.got) == 1 and probe.got[0].endswith(b"\nend\n"), \ + f"the guard's client sent no whole request to a server of this uid: {probe.got!r}" + request = probe.got[0] + + def text_answer(): + got = _ask_service(est, request) + return got if got.startswith(b"text ") else None + + svc = _Service(est) + try: + ok = _warm(est) + answer = _until(text_answer, WARM_S, 0.2) + finally: + svc.stop() + assert answer, "the service gave the guard's request no text answer in the ok state" + _live_other(est) + est.push_register([_row(FROM, est.other, "LIVE")]) + plain = _Listener(est, hang=False, whole=True) + try: + direct = est.hook("hello") + finally: + plain.close() + assert plain.got == [request] and direct.err.count(FALLBACK) == 1 and not direct.killed, \ + (f"the refuse state's direct read did not send the ok state's request and fall back: " + f"{plain.got!r} {direct!r}") + unfallen = [line for line in direct.err.splitlines() if line != FALLBACK] + assert (ok.code, ok.out, ok.err.splitlines()) != (direct.code, direct.out, unfallen), \ + f"the ok state's guard answer is the refuse state's direct read: {ok!r}" + seam = est.root / "seam-other-uid" + seam.mkdir() + for name in ("lanes-edit.sh", "repos.tsv", "lane-start"): + if (est.guard.parent / name).exists(): + shutil.copy2(est.guard.parent / name, seam / name) + calls = seam / "register_peercred.calls" + _script(seam / "lanes-index", _OTHER_UID_CLIENT, PY=sys.executable, INDEX=_q(est.index), + LOG=_q(calls)) + server = _Listener(est, hang=False, whole=True, answer=answer) + try: + hook = run_hook(["bash", str(seam / "lanes-edit.sh"), "guard"], + est.session.hook_input(prompt="hello"), est.env(), est.session.cwd) + finally: + server.close() + made = calls.read_text(encoding="utf-8").splitlines() if calls.exists() else [] + assert hook.err.count(FALLBACK) == 1 and not hook.killed and \ + (hook.code, hook.out, hook.err) == (direct.code, direct.out, direct.err), \ + (f"the guard did not treat a server of another uid as unavailable with the refuse " + f"state's direct read: register_peercred calls {made}, the server got " + f"{server.got!r}\nthrough the server: {hook!r}\ndirect: {direct!r}") + assert len(made) == 1, f"the guard's client made {len(made)} register_peercred calls: {made}" + assert server.got == [b""], f"a server of another uid was sent request bytes: {server.got!r}" + + +@pytest.mark.parametrize("case", ["namespace", "boot"]) +def test_an_owner_file_from_another_namespace_or_boot_is_no_service(estate, case): + """SVC-2: an owner file naming another pid namespace or another boot is no + service: the client falls back and a new service may start.""" + est = estate(mode="primary") + svc = _Service(est) + owner = svc.dir / "register.owner" + text = owner.read_text(encoding="utf-8") + # THE CLIENT'S OWN VALUE, REPLACED WHEREVER THE FILE HOLDS IT (section 2.4: + # `readlink /proc/self/ns/pid` and `/proc/sys/kernel/random/boot_id`), so + # the case needs no line format the contract does not fix. + mine = (os.readlink("/proc/self/ns/pid") if case == "namespace" else + Path("/proc/sys/kernel/random/boot_id").read_text(encoding="utf-8").strip()) + assert mine in text, f"register.owner does not hold this {case}: {text}" + owner.write_text(text.replace(mine, "pid:[1]" if case == "namespace" else + "00000000-0000-0000-0000-000000000000"), encoding="utf-8") + # A SOCKET THAT ANSWERS (section 2.4, 13.8): the client treats the service + # as unavailable, reads directly and starts none. + # T237zzd: ONLY THIS ESTATE'S OWN SERVICES ARE COUNTED (`_estate_servers`, + # the `serve` its client would start), as T237zzc counts them. The look + # took every process on the workstation whose argv ended in `serve`, so a + # service an earlier case left, or another lane's, failed this case as + # one its client started: merge 151's and 158's c2 runs, four leftover + # pids, the same four in both ids. + try: + hook = est.hook("hello") + serves = [p for p in _estate_servers(est) if _argv(p)[-1:] == ["serve"] + and p != svc.proc.pid and _stat(p).get("sid") != _stat(svc.proc.pid).get("sid")] + finally: + svc.stop() + assert hook.err.count(FALLBACK) == 1 and not hook.killed, repr(hook) + assert not serves, f"the client started another service: {serves}" + + +@pytest.mark.parametrize("case", ["files", "index", "refusing-build"]) +def test_serve_refuses_unless_the_mode_answer_is_primary(estate, tmp_path, case): + """SVC-5 (R36; A10): `serve` exits 2, with no socket, in files mode, in + `mode=index`, and on the shipped build, whose constant still refuses + `primary`; its refusal names the mode it needs.""" + est = estate() + env = est.env() + if case != "files": + conf = tmp_path / "lanes-index.conf" + conf.write_text(f"mode={'index' if case == 'index' else 'primary'}\n" + f"register_url=postgresql:///register?host={tmp_path}/sock\n", + encoding="utf-8") + env["LANES_INDEX_CONFIG"] = str(conf) + done = _index(est, "serve", env=env, timeout=30) + assert done.returncode == 2 and "primary" in done.stdout + done.stderr, \ + f"serve {done.returncode}: {done.stdout}{done.stderr}" + + +def test_one_instance_holds_register_lock_and_a_second_starter_exits_0(estate): + """SVC-4: one instance holds the register lock; a second starter exits 0 + and starts nothing.""" + est = estate(mode="primary") + svc = _Service(est) + second = _index(est, "serve", timeout=30) + svc.stop() + assert second.returncode == 0, second + + +def test_a_stale_socket_is_unlinked_under_the_lock_and_rebound(estate): + """SVC-4: a socket left by a dead service is unlinked under the lock and + bound again by the next start.""" + est = estate(mode="primary") + svc = _Service(est) + path = svc.dir / "register.sock" + inode = os.lstat(path).st_ino + _kill(svc.proc.pid) + svc.proc.wait(10) + assert path.exists(), "a service killed with -9 left no stale socket to test" + again = _Service(est) + try: + assert path.exists() and os.lstat(path).st_ino != inode, \ + "the stale socket was not unlinked and bound again at the same path" + finally: + again.stop() + + +#: How long `[floor]`'s service must run on: ten times the 0.5 s given, five +#: times the 1 s floor, and past `[stops]`'s 2 s. +IDLE_STOP_RUNS_ON_S = 5.0 + + +@pytest.mark.parametrize("case", ["stops", "floor"]) +def test_the_service_stops_after_its_idle_time_and_unlinks_its_socket(estate, case): + """SVC-4 (R37): `[stops]`, with `LANES_REGISTER_SERVE_IDLE_STOP_S=2` the + service stops after it and unlinks its socket. + + `[floor]`, 0.5, under the 1 s floor: the value is ignored, with the + default 900 s kept, never `config-refused` (tasks:1643; d8 section 10; + lane 3's OP-14, #165 6746215510, which stands, #165 6827356485). So + `serve` listens, with no failure stamp (section 8.6), and by section + 8.4's own observable, its process and its socket, it runs on for + `IDLE_STOP_RUNS_ON_S`, past the 0.5 s given and the 1 s floor. The 900 s + itself is not waited for.""" + est = estate(mode="primary") + if case == "floor": + svc = _Service(est, LANES_REGISTER_SERVE_IDLE_STOP_S="0.5") + sock = svc.dir / "register.sock" + try: + stopped = _until(lambda: svc.proc.poll() is not None or not sock.exists(), + IDLE_STOP_RUNS_ON_S) + code = svc.proc.poll() + stamp = (_run_dir(est) / "register.failed").exists() + finally: + svc.stop() + assert not stamp, "serve stamped a failure under LANES_REGISTER_SERVE_IDLE_STOP_S=0.5" + assert not stopped, (f"serve stopped (exit {code}) or unlinked its socket inside " + f"{IDLE_STOP_RUNS_ON_S} s under LANES_REGISTER_SERVE_IDLE_STOP_S=0.5: " + f"the value was taken, not ignored with the default 900 s kept") + return + svc = _Service(est, LANES_REGISTER_SERVE_IDLE_STOP_S="2") + sock = svc.dir / "register.sock" + assert _until(lambda: svc.proc.poll() is not None, 15), "the service did not stop" + assert not sock.exists(), "the stopped service left its socket" diff --git a/tests/test_sql_register_landing_expired.py b/tests/test_sql_register_landing_expired.py new file mode 100644 index 00000000..1493f5ff --- /dev/null +++ b/tests/test_sql_register_landing_expired.py @@ -0,0 +1,1841 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Feature 007's AT-F13 (opensoft/openRepoTools#165, L2-W5; lane 2's T253): +`LANDING EXPIRED`'s verb, `append-line --landing-expired`, and a take with no +UTC. + +THE RULING (F13, Brett's "Adopt, on my word (Recommended)", #165 6721583757; +U3 and U7, lane 3's ruling, #165 6722541787; lane 4's section, "`LANDING +EXPIRED`'s verb"): on primary a `LANDING EXPIRED` line is written only by +`append-line --landing-expired <holder> --pr <n> --repo <repo>`, with Brett's +word as `--word`, `--word-where` and `--word-utc`. The form copies the holder, +the PR, the repository's token and the UTC from the holder's open `LANDING` at +`n`, byte for byte, the newest post where there are several; it refuses with +2, sending nothing, without the word, off primary, and where that `LANDING` is +not open or is 30 minutes old or less by the snapshot's clock. On primary +`append-line` refuses, before the lock, the kind typed by hand and a take whose +UTC it cannot read (U3). F13's check in the commit decides what the line +releases; its LR005 exits 2 with the server's message and its DETAIL token, +and a caller that branches reads the token, never the message (U7). On primary +`who --landing` no longer lists a released `LANDING`, through `RULE6_PRIMARY`, +`rule6_primary_on` and `RULE6_EXPIRED_AWK`; off primary `RULE6_AWK` is +byte-identical to today's. + +THE CASES: (a) to (g) and (k) to (m) are FP; (i) and (j) are RE, on T205's +`pg_cluster`, skipped without PostgreSQL 16 by its banner. Case (h), with +its rollback, is T279's, RE, at the module's end. The fifteenth test, new +since v3f, is T112's AT-F13 +case (R-F10-34): `register commit` expires an imported stale `LANDING` by +Rule 6's key, the shipped table then the per-wip one (RE; at its section). + +THE FP BENCH (`Bench`): `lanes-edit.sh` copied beside a `lanes-index` that is +T207's contract stub (`contract_stub`, CLI4.5 section 6's copy rule, with +`repos.tsv` and `lane-start` beside it), behind a small wrapper that sets the +clock `register snapshot` prints to the test's `CLOCK`, far from `date` (D13: +every age is the snapshot's time less the `LANDING`'s UTC). The stub's +register at `n` holds the case's `lanes/LANES.md`, as the files-mode workspace +under it does (test 1's sync form, `test_sql_register_render.py`'s +`workspace`), and its `register read` is the fake prefetch. T203's register +fake `psql` is first on `PATH`, and the configuration names a Unix socket +directory (the fake-`psql` host rule, L1v4.5:525; lane 1, #165 6741670709 item +9). "Nothing sent" is read here as: no `register commit` reached the stub and +no `psql` call was made; on primary T424's and T425's refusals run in the +attempt's child, after the parent's snapshot and before its seam, so a +snapshot call may precede a refusal (B11 tasks:1087, :1152, :1271). Beside +the checkout, each lane the module writes for has its own register checkout, +`<W>-lanes/<lane>`, a clone of the same origin (`WRITE_LANES`; lane 3's +(119), #165 6813027223), as every estate at primary does. + +TWO READS OF `who --landing` (lane 4's RC-W49, #165 6871131058): off primary +it prints each `LANDING`'s age by the host's `date`, not by `CLOCK`, so (f) +and (l), which compare two of its reads, compare them through `aged_out`: +each age is masked, once it is shown to be its UTC's age by the host's clock +during its own read. Every other byte is still compared. + +WHAT THEY FAIL UNTIL. At this base `lanes-edit.sh` never asks `lanes-index` +its mode and writes the files whatever it would say, and its `append-line` +takes `--landing-expired` as the line's text. So every FP case is red by its +own assertion, and fails until lane 4's T424 (L4-B10's refusals) and T425 +(L4-B10, the form, `RULE6_PRIMARY` and `RULE6_EXPIRED_AWK`), with T415's +attempt loop (L4-B3) and lane 5's T504 (the mode door, `reg_open`) under them; +(g) fails only until lane 1's T118 (L1-A16), and (i) and (j) until lane 1's +T107, T111 and T112 (L1-A6, L1-A9, L1-A10) and lane 2's T227 and T228, with +T425 for the form and the awk. +""" + +from __future__ import annotations + +import atexit +import calendar +import hashlib +import importlib.machinery +import importlib.util +import itertools +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +import threading +import time +import uuid +from pathlib import Path +from urllib.parse import quote + +import pytest + +from conftest import WINDOWS_SKIP +from sql_register_helpers import (ARGV_LOG, LANES_INDEX, PSQL_SHIM, PSQL_SHIM_CONTROL, + REGISTER_FAKE_PSQL, REPO, contract_stub, flipped_copy, + stub_outcome) + +pytestmark = [WINDOWS_SKIP, pytest.mark.skipif( + shutil.which("bash") is None or shutil.which("git") is None, + reason="the lane tooling is bash over git")] + +#: THE LANDING GATE'S TABLE (T280; `tests/sql_register_gate.py` reads it, and +#: T281 removes it in the last set): the tasks each id of this module waits +#: for, by T253's and T279's Orders (tasks.md at 204145ae), keyed by function. +#: Lane 2's plan GP-24 wrote it (task sets 12b's rule 11); C1's fourth text and +#: (b, U3) also wait for T415 and T504, as tasks:2408 names them. +SQL_REGISTER_GATE_TABLE = { + "test_a_landed_between_the_forms_snapshot_and_commit_leaves_the_retry_nothing_to_release": ("T107", "T108", "T111", "T112", "T115", "T118", "T227", "T228", "T415", "T424", "T425"), # T253; tasks:2408 + "test_a_landing_expired_on_primary_frees_main_and_who_landing_until_a_rollback_to_files": ("T121", "T304", "T326", "T424", "T425"), # T279; tasks:2564 + "test_in_files_mode_the_landing_expired_form_exits_2_and_changes_nothing": ("T107", "T108", "T118", "T415", "T424", "T425", "T504"), # T253; tasks:2408 + "test_off_primary_rule6_awk_is_the_pin_and_the_flag_cannot_be_inherited": ("T107", "T108", "T118", "T415", "T424", "T425", "T504"), # T253; tasks:2408 + "test_on_primary_a_landing_take_whose_lane_cannot_be_read_is_refused_before_the_lock_and_written_off_primary": ("T107", "T108", "T118", "T415", "T424", "T425", "T504"), # T253; tasks:2408 + "test_on_primary_a_take_with_no_readable_utc_is_refused_before_the_lock_and_written_off_primary": ("T107", "T108", "T118", "T415", "T424", "T425", "T504"), # T253; tasks:2408 + "test_on_primary_the_landing_expired_kind_typed_by_hand_is_refused_naming_the_form": ("T107", "T108", "T118", "T415", "T424", "T425", "T504"), # T253; tasks:2408 + "test_parse_register_line_reads_the_landing_expired_fields_before_the_word_clause": ("T107", "T108", "T118", "T424", "T425"), # T253; tasks:2408 + "test_register_commit_expires_an_imported_stale_landing_by_the_shipped_then_per_wip_repo_key": ("T105", "T107", "T111", "T112", "T227", "T228"), # T253; tasks:2408 + "test_rule6_primary_on_is_called_only_where_lane_4_places_it_and_who_landing_stays_pinned": ("T107", "T108", "T118", "T415", "T424", "T425", "T504"), # T253; tasks:2408 + "test_rule6_with_the_expired_branch_agrees_with_main_slots_on_imported_history": ("T107", "T108", "T111", "T112", "T118", "T227", "T228", "T424", "T425"), # T253; tasks:2408 + "test_the_landing_expired_form_composes_its_line_from_the_open_landing": ("T107", "T108", "T118", "T415", "T424", "T425", "T504"), # T253; tasks:2408 + "test_the_landing_expired_form_prints_its_seq_once_and_an_lr005_with_its_detail_token": ("T107", "T108", "T118", "T415", "T424", "T425", "T504"), # T253; tasks:2408 + "test_the_landing_expired_form_refuses_with_2_before_the_lock_without_the_word": ("T107", "T108", "T118", "T415", "T424", "T425", "T504"), # T253; tasks:2408 + "test_the_landing_expired_form_sends_nothing_where_no_landing_is_stale_at_the_snapshot": ("T107", "T108", "T118", "T415", "T424", "T425", "T504"), # T253; tasks:2408 + "test_the_writer_reads_lr005s_reason_from_its_detail_token_never_its_message": ("T107", "T108", "T118", "T415", "T424", "T425", "T504"), # T253; tasks:2408 + "test_who_landing_on_primary_drops_only_the_released_landing": ("T107", "T108", "T118", "T415", "T424", "T425", "T504"), # T253; tasks:2408 +} + +LANES_EDIT = REPO / "lanes-edit.sh" + +#: The register's punctuation, by code point, so no raw character enters this +#: file: the em dash, the middle dot of a state cell, the arrow of a `LANDED`. +EM, DOT, ARROW = chr(0x2014), chr(0x00B7), chr(0x2192) + +#: The workstation, and the lanes: the writer who releases, the holder whose +#: `LANDING` goes stale, a third lane, and the holder's former name. +WS = "Eagle" +WRITER, HOLDER, OTHER, OLD_NAME = "repoA-2", "repoB-1", "repoC-1", "repoOld-1" +SID_W = "aaaaaaaa-0253-4000-8000-00000000a253" +SID_H = "bbbbbbbb-0253-4000-8000-00000000b253" +SID_O = "cccccccc-0253-4000-8000-00000000c253" +SESSIONS = {WRITER: SID_W, HOLDER: SID_H, OTHER: SID_O} +TIP = "0123456789abcdef0123456789abcdef01234567" + +#: The repository: `lanes/repos.tsv` maps `r9` to `opensoft/r9` (the test +#: plan's AT-F13 fixture), and `r8` to another key. +KEY, ALIAS, OTHER_KEY = "opensoft/r9", "r9", "opensoft/r8" +PR, OTHER_PR = 9, 8 +REPOS_TSV = f"# alias\towner/repo\n{ALIAS}\t{KEY}\nr8\t{OTHER_KEY}\n" + +#: THE SNAPSHOT'S CLOCK (D13), far from `date`: 2026-06-01T12:00:00Z. Every +#: `LANDING`'s UTC is set from it, so a form that dated by `date` would see +#: each one months old. +CLOCK = calendar.timegm((2026, 6, 1, 12, 0, 0, 0, 0, 0)) + +#: Brett's word, as the form's three arguments carry it. +WORD = "Release the stale LANDING (Recommended)" +WHERE = "lane openRepoTools-2's session" +WORD_UTC = "2026-06-01T11:58:00Z" + +#: RULE 6'S PROGRAM AS IT IS PINNED, `RULE6_AWK`'s text at code `a2073eae` +#: (`lanes-edit.sh:6959`), between its quotes: 1874 bytes. +RULE6_AWK_PIN = "618e9235c3a838ea0fe67134097063377c21f6acf57eb1f240a5cda1ad00007e" +#: `who_landing`'s pinned line (`lanes-edit.sh:7057` at `a2073eae`). +WHO_LANDING_LINE = (' wd_rows="$(register_text | LANES_RULE6_ALIASES="$wd_aliases" ' + 'awk "$RULE6_AWK")"') +#: What the files-mode refusal says (AT-F13 (f)), word by word. +FILES_MODE_WORDS = ("release of a stale", "exists only on", "mode=primary", "nothing was written") +STALE_MARK = "STALE (Rule 6: >30 min)" +#: A `who --landing` line's age, `<UTC> (<h>h <mm>m ago)` (`age_of`), the one +#: part of its output that the host's clock decides and the register does not. +#: Off primary `now_epoch` is `date -u +%s`, so two reads that straddle a +#: minute differ there alone (`lanes-edit.sh`'s `now_epoch`, `age_of` and +#: `who_landing`, `:7443-7446`, `:12769-12775` and `:16233` at line R's +#: merge104 `142afd90`; lane 4's RC-W49, #165 6871131058: `3976h 04m ago` +#: against `3976h 05m ago`). +WHO_AGE_RE = re.compile(r"(?P<utc>[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}(?::[0-9]{2})?Z)" + r" \((?P<hours>[0-9]+)h (?P<minutes>[0-9]{2})m ago\)") + + +# ------------------------------------------------------------------ the lines +def utc_of(epoch: int) -> str: + return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(epoch)) + + +def ago(minutes: float, clock: int = CLOCK) -> str: + """The UTC `minutes` before the snapshot's clock.""" + return utc_of(clock - int(round(minutes * 60))) + + +def _epoch_of(utc: str): + """`utc` as epoch seconds, or None where the line carries no UTC.""" + return calendar.timegm(time.strptime(utc, "%Y-%m-%dT%H:%M:%SZ")) if utc else None + + +def aged_out(stdout: str, before: int, after: int) -> str: + """`who --landing`'s `stdout` with each age masked, `<UTC> (<age> ago)`, + once it is shown to be its line's UTC's age by the host's clock at some + whole second from `before` to `after`, the clock as `date -u +%s` reads it + just before the read began and just after it ended (`age_of`'s whole + minutes, 0 for a UTC ahead of the clock). So two reads compared through it + still differ at every other byte that changed, the UTC and the STALE mark + among them, and an age that is not the host clock's, such as one by the + snapshot's `CLOCK`, fails here (RC-W49's SHOULD 1).""" + def masked(m) -> str: + utc = m["utc"] + epoch = calendar.timegm(time.strptime( + utc, "%Y-%m-%dT%H:%M:%SZ" if utc.count(":") == 2 else "%Y-%m-%dT%H:%MZ")) + shown = int(m["hours"]) * 60 + int(m["minutes"]) + low, high = max(0, before - epoch) // 60, max(0, after - epoch) // 60 + assert int(m["minutes"]) < 60 and low <= shown <= high, ( + f"who --landing's age {m.group(0)!r} is not its UTC's age by the host's " + f"clock during the read, {low} to {high} min") + return f"{utc} (<age> ago)" + return WHO_AGE_RE.sub(masked, stdout) + + +def landing(lane: str = HOLDER, minutes: float = 31, pr: int = PR, repo: str = KEY, + session: str = None) -> str: + sid = session or SESSIONS.get(lane, SID_H) + return f"LANDING {EM} lane {lane}, session {sid}@{WS}, {ago(minutes)}, PR #{pr} into {repo} main" + + +def landed(lane: str = HOLDER, minutes: float = 40, pr: int = PR, repo: str = KEY) -> str: + sid = SESSIONS.get(lane, SID_H) + return (f"LANDED {EM} lane {lane}, session {sid}@{WS}, {ago(minutes)}, PR #{pr} into {repo} " + f"main {ARROW} abc1234") + + +def expired(writer: str = OTHER, minutes: float = 5, holder: str = HOLDER, pr: int = PR, + repo: str = KEY, landing_utc: str = None, word: str = WORD, where: str = WHERE, + word_utc: str = WORD_UTC, clause: bool = True) -> str: + """A `LANDING EXPIRED` line in the form's own shape (Y:5109; + `lanes-edit.sh:3375` at `c8acf67c`), as the form composes it (case (a)), + a re-import after a rollback holds it, or a line typed by hand in files + mode copies it: `lane <writer>` first, the session, its UTC `minutes` + before the snapshot's clock, `for lane <holder>:`, the PR, the + repository, `its LANDING of <landing UTC>` (`landing_utc`, 45 minutes + before the clock where it is not given), the whole minutes past Rule 6's + 30 (0 where the two are 30 minutes apart or less, which only a line typed + by hand can be), and the word clause last: where and when Brett gave his + word, then his quote. `clause=False` leaves the word clause off.""" + sid = SESSIONS.get(writer, SID_O) + landing_utc = landing_utc or ago(45) + apart = _epoch_of(ago(minutes)) - _epoch_of(landing_utc) + text = (f"LANDING EXPIRED {EM} lane {writer}, session {sid}@{WS}, {ago(minutes)}, " + f"for lane {holder}: PR #{pr} into {repo} main, its LANDING of {landing_utc}, " + f"{max(0, (apart - 30 * 60) // 60)} min past Rule 6's 30") + if clause: + text += f"; on Brett's word ({where}, {word_utc}): \"{word}\"" + return text + + +def _row(lane: str, sid: str) -> str: + return (f"| `{lane}` | harness `{sid}` | {WS} / test / brett | 2026-05-01T00:00Z | none " + f"| handoffs/{lane}.md | LIVE {DOT} 2026-05-01T00:00:00Z {DOT} working |") + + +def register_files(lines=(), repos: str = REPOS_TSV) -> dict: + """The case's checkout and register: three lanes' rows, `lines` after the + table, the holder's former name in `aliases.tsv`, a log per lane, and + `lanes/repos.tsv` (outside the render set, from the checkout).""" + lanes = "\n".join([ + f"# LANES.md {EM} AT-F13's register (T253)", "", + "| lane | session id | workstation / env / user | started (UTC) | objects owned " + "| handoff path | state |", + "|---|---|---|---|---|---|---|", + *(_row(lane, sid) for lane, sid in SESSIONS.items()), "", *lines, ""]) + files = {"lanes/LANES.md": lanes, + "lanes/aliases.tsv": f"# old\tnew\tutc\n{OLD_NAME}\t{HOLDER}\t2026-05-01T00:00:00Z\n", + "lanes/log/README.md": "# the object logs\n", + "lanes/repos.tsv": repos} + for lane in SESSIONS: + files[f"lanes/log/{lane}.md"] = (f"# lane {lane} {EM} object log " + f"(lane-collision-protocol Amendment 7)\n") + return files + + +RENDER_SET = re.compile(r"^lanes/(LANES\.md|aliases\.tsv|archive/[^/]+\.md" + r"|log/(?!README\.md$)[^/]+\.md)$") + + +# ------------------------------------------------------------------ the estate +def git(cwd: Path, *args: str, env: dict = None) -> str: + proc = subprocess.run(["git", *args], cwd=str(cwd), capture_output=True, text=True, + env=env, check=False) + assert proc.returncode == 0, f"git {' '.join(args)} in {cwd}: {proc.stderr}{proc.stdout}" + return proc.stdout + + +#: `_masked_path`'s mirrors, by each directory's real path (None where the +#: directory holds no masked name), and the one temporary root they share. +_PATH_MIRRORS: dict = {} +_PATH_MIRROR_ROOT: list = [] + + +def _masked_path() -> str: + """The caller's PATH with every directory kept in its place, and each one + that holds a `psql`, a `lanes-index` or a name that starts `pg_` swapped + for a private mirror of it: a directory of links, one to each of its + entries by its absolute path, those names left out. An installed + indexer, a real `psql` or one of the `pg_` client wrappers shipped beside + it is never what a case runs, but the tools beside them are: on a GitHub + runner `postgresql-16`'s client puts `psql` in `/usr/bin` with `git` and + `bash` (and `/bin` is a link to it), so dropping the directory dropped + `git` and `bash` too (lane 1's census, #165 6807454856). A directory that + holds none of those names passes through unchanged. Each mirror is made + once per process, under one `mkdtemp` that an `atexit` handler removes.""" + parts = [] + for part in os.environ.get("PATH", "").split(os.pathsep): + if not part: + continue + real = os.path.realpath(part) + if real not in _PATH_MIRRORS: + try: + names = os.listdir(real) + except OSError: + names = [] + masked = {name for name in names + if name in ("psql", "lanes-index") or name.startswith("pg_")} + mirror = None + if masked: + if not _PATH_MIRROR_ROOT: + _PATH_MIRROR_ROOT.append(tempfile.mkdtemp(prefix="l2-pathmask-")) + atexit.register(shutil.rmtree, _PATH_MIRROR_ROOT[0], ignore_errors=True) + mirror = os.path.join(_PATH_MIRROR_ROOT[0], str(len(_PATH_MIRRORS))) + os.mkdir(mirror) + for name in names: + if name not in masked: + os.symlink(os.path.join(real, name), os.path.join(mirror, name)) + _PATH_MIRRORS[real] = mirror + parts.append(_PATH_MIRRORS[real] or part) + return os.pathsep.join(parts) + + +#: EACH WRITE LANE'S OWN REGISTER CHECKOUT, `<c>` (lane 3, #165 6813027223, +#: batch g Q119; T241e's `WRITE_LANES` in `test_sql_register_writes.py` is the +#: model). On primary a write reads its author, its pending hand edits and its +#: `repos.tsv` from the checkout of the lane it is made for, `<W>-lanes/<lane>` +#: (`lanes-edit.sh`'s `lane_checkout_path`, `R-merge20:lanes-edit.sh:18342`), +#: W being the real path of `workspace.yaml`'s `path:`, and refuses with 2, +#: sending nothing, where that is not there, since a clone there would be +#: D12's fetch (B15 tasks:1154; T415's `pw_checkout`). So `_workspace` makes +#: it itself, because `lane-start` makes it only under `LANES_ROUTE_WRITES=1` +#: with neither `LANES_REPO` nor `LANES_FILE` set (lane 3, #165 6841265575; +#: `dfc4ce4c:lane-start:1209-1210`). It makes it for each lane this module's +#: writes are made for (`write_lane_of`'s): `WRITER`, the `LANES_LANE` of every +#: form and take, and `HOLDER`, (a)'s `[writer-is-the-holder]`. Until T415 +#: nothing reads it: no case sets `LANES_ROUTE_WRITES`, so each write goes +#: through `LANES_REPO` as before. +WRITE_LANES = (WRITER, HOLDER) + + +def _lane_checkouts(origin: Path, checkout: Path, env: dict, lanes=WRITE_LANES) -> list: + """`<c>` for each of `lanes`, beside the checkout `workspace.yaml` names + as W: `<W>-lanes/<lane>`, W being its real path, as `lane_checkout_path` + puts it (Amendment 23 S1). Each is a clone of W's own origin, as + `lane-checkout <lane> --create` makes one, so it is at W's commit when + made after the case's last push from W (T241e's "after the case's + prep").""" + real = Path(os.path.realpath(checkout)) + made = [] + for lane in lanes: + target = real.parent / f"{real.name}-lanes" / lane + target.parent.mkdir(parents=True, exist_ok=True) + git(target.parent, "clone", "-q", str(origin), str(target), env=env) + made.append(target) + return made + + +def _workspace(root: Path, fakebin: Path, files: dict, source: Path = None, + lanes=WRITE_LANES) -> tuple: + """A files-mode workspace on a bare origin at `files`, in test 1's sync + form (`test_sql_register_render.py`'s `workspace`): `workspace.yaml` + names the origin and the checkout, a fake `tmux` and `fakebin` are first + on `PATH`, and the workstation is configured. Where `source` is given + (T279's case (h)), the origin is a bare clone of that repository and + `files` is not written. Each of `lanes` has its own register checkout + beside the checkout (`_lane_checkouts`); a case that pushes from the + checkout afterwards passes none and makes them after its push. Returns + (the origin, the checkout, the environment).""" + home = root / "home" + home.mkdir(parents=True, exist_ok=True) + env = {k: v for k, v in os.environ.items() + if not k.startswith(("GIT_", "PG", "LANES_", "TMUX", "RULE6_", "FAKE_PSQL"))} + env.update(HOME=str(home), GIT_CONFIG_NOSYSTEM="1", GIT_CONFIG_GLOBAL=os.devnull, + GIT_AUTHOR_NAME="T253 estate", GIT_AUTHOR_EMAIL="t253@example.invalid", + GIT_COMMITTER_NAME="T253 estate", GIT_COMMITTER_EMAIL="t253@example.invalid", + LC_ALL="C") + origin, checkout = root / "origin.git", root / "checkout" + if source is not None: + git(root, "clone", "-q", "--bare", str(source), str(origin), env=env) + git(root, "clone", "-q", str(origin), str(checkout), env=env) + else: + git(root, "init", "-q", "--bare", "-b", "main", str(origin), env=env) + git(root, "clone", "-q", str(origin), str(checkout), env=env) + for path, text in files.items(): + target = checkout / path + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(text.encode("utf-8")) + git(checkout, "add", "-A", env=env) + git(checkout, "commit", "-q", "-m", "C: AT-F13's register", env=env) + git(checkout, "push", "-q", "origin", "main", env=env) + _lane_checkouts(origin, checkout, env, lanes) + agents = home / ".agents" + agents.mkdir(parents=True, exist_ok=True) + (agents / "workspace.yaml").write_text(f"repository: {origin}\npath: {checkout}\n", + encoding="utf-8") + fakebin.mkdir(parents=True, exist_ok=True) + (fakebin / "tmux").write_text("#!/bin/sh\nexit 1\n", encoding="utf-8") + (fakebin / "tmux").chmod(0o755) + for d in ("state", "config", "tmp"): + (root / d).mkdir(parents=True, exist_ok=True) + env.update(AGENT_PROTOCOL_ROOT=str(agents), TMPDIR=str(root / "tmp"), + XDG_STATE_HOME=str(root / "state"), XDG_CONFIG_HOME=str(root / "config"), + CLAUDE_CONFIG_DIR=str(home / ".claude"), LANES_WORKSTATION=WS, + LANES_HOST="eagle", LANES_OS="linux", LANES_CONTAINER="none", + LANES_IN_CONTAINER="0", LANES_NO_GITHUB="1", LANES_REPO=str(checkout), + PATH=str(fakebin) + os.pathsep + _masked_path()) + return origin, checkout, env + + +#: THE SNAPSHOT'S CLOCK, SET BY THE TEST: the contract stub's `register +#: snapshot` prints `clock=` from `time.time()`; this wrapper hands every call +#: to the stub and, on `register snapshot` alone, rewrites that one line to the +#: epoch in its clock file. `not_after=` stays the stub's, so a commit is in +#: time. +_CLOCK_WRAPPER = r'''#!/usr/bin/env python3 +# AT-F13's snapshot clock (T253): the contract stub, its `clock=` set. +import os, subprocess, sys +STUB = STUB_PATH +CLOCK = CLOCK_PATH +args = sys.argv[1:] +if args[:2] != ["register", "snapshot"] or not os.path.exists(CLOCK): + os.execv(sys.executable, [sys.executable, STUB] + args) +with open(CLOCK, encoding="utf-8") as handle: + clock = handle.read().strip() +proc = subprocess.run([sys.executable, STUB] + args, stdout=subprocess.PIPE) +out = proc.stdout.decode("utf-8") +sys.stdout.write("\n".join("clock=" + clock if line.startswith("clock=") else line + for line in out.split("\n"))) +sys.stdout.flush() +sys.exit(proc.returncode) +''' + + +class Bench: + """One case's workstation (see the module's docstring): `mode` is what + the mode query answers, `primary`, `files`, `index`, `unconfigured` + (no configuration, answered `files`) or `fall` (the query fails, F8's + fall to files mode).""" + + def __init__(self, tmp_path: Path, lines=(), mode: str = "primary", repos: str = REPOS_TSV): + self.root = tmp_path + self.fakebin = tmp_path / "fakebin" + self.fakebin.mkdir(parents=True, exist_ok=True) + (self.fakebin / "psql").write_text(REGISTER_FAKE_PSQL, encoding="utf-8") + (self.fakebin / "psql").chmod(0o755) + self.psql_log = self.fakebin / "psql.log" + self.files = register_files(lines, repos) + self.origin, self.checkout, self.env = _workspace(tmp_path / "ws", self.fakebin, + self.files) + self.stub_dir = tmp_path / "stub" + contract_stub(self.stub_dir, register={p: t for p, t in self.files.items() + if RENDER_SET.match(p)}) + self.bin = tmp_path / "bin" + self.bin.mkdir() + for name in ("lanes-edit.sh", "repos.tsv", "lane-start"): + shutil.copy2(str(REPO / name), str(self.bin / name)) + self.lanes_edit = self.bin / "lanes-edit.sh" + clock = tmp_path / "snapshot-clock" + clock.write_text(f"{CLOCK}\n", encoding="utf-8") + wrapper = self.bin / "lanes-index" + wrapper.write_text(_CLOCK_WRAPPER.replace("STUB_PATH", repr(str(self.stub_dir / "lanes-index"))) + .replace("CLOCK_PATH", repr(str(clock))), encoding="utf-8") + wrapper.chmod(0o755) + conf_dir = tmp_path / "conf" + conf_dir.mkdir() + sock = tmp_path / "sock" + sock.mkdir() + host = quote(sock.as_posix(), safe="") + passfile = conf_dir / "pgpass" + passfile.write_text("", encoding="utf-8") + passfile.chmod(0o600) + if mode != "unconfigured": + conf = conf_dir / "lanes-index.conf" + conf.write_text("\n".join([ + f"mode={'files' if mode == 'fall' else mode}", + f"register_url=postgresql://lanes_w_t253@{host}:5432/lanes_t253", + f"reader_url=postgresql://lanes_r_t253@{host}:5432/lanes_t253", + f"register_passfile={passfile}", f"reader_passfile={passfile}", ""]), + encoding="utf-8") + conf.chmod(0o600) + self.env["LANES_INDEX_CONFIG"] = str(conf) + self.env["FAKE_PSQL_LOG"] = str(self.psql_log) + self.env.pop("LANES_INDEX", None) + self.mode = mode + if mode in ("files", "index", "unconfigured"): + said = "files" if mode == "unconfigured" else mode + self.outcome("mode", stdout=f"{said}\n") + self.outcome("register read", stdout=f"mode {said}\n") + elif mode == "fall": + for prefix in ("mode", "register read"): + self.outcome(prefix, exit=1, stderr="lanes-index: the mode query failed (T253)\n") + + def outcome(self, prefix, **answer) -> None: + stub_outcome(self.stub_dir, prefix, **answer) + + def run(self, argv, lane: str = WRITER, session: str = None, extra: dict = None, + drop=()) -> subprocess.CompletedProcess: + env = dict(self.env) + if lane: + env["LANES_LANE"] = lane + env["LANES_SESSION"] = session or SESSIONS.get(lane, SID_W) + env.update(extra or {}) + for name in drop: + env.pop(name, None) + return subprocess.run(["bash", str(self.lanes_edit), *[str(a) for a in argv]], + capture_output=True, encoding="utf-8", errors="replace", env=env, + timeout=120, cwd=str(self.checkout), check=False, + stdin=subprocess.DEVNULL) + + def who(self, extra: dict = None) -> subprocess.CompletedProcess: + return self.run(["who", "--landing", KEY], lane=None, extra=extra) + + def who_aged(self, extra: dict = None) -> tuple: + """`who()`, with the host's clock read just before and just after it: + (the process, its stdout through `aged_out`). Two reads compare by that + stdout, so a minute the clock crosses between them is no change.""" + before = int(time.time()) + proc = self.who(extra) + return proc, aged_out(proc.stdout, before, int(time.time())) + + # -------------------------------------------------- what reached the store + def calls(self, *words: str) -> list: + """The stub's calls whose arguments begin with `words`.""" + log = self.stub_dir / ARGV_LOG + if not log.exists(): + return [] + found = [json.loads(line) for line in log.read_text(encoding="utf-8").splitlines() if line] + return [argv for argv in found if argv[:len(words)] == list(words)] + + def asked_the_mode(self) -> bool: + return bool(self.calls("mode") or self.calls("register", "read")) + + def psql_calls(self) -> list: + if not self.psql_log.exists(): + return [] + entries = [json.loads(line) for line in self.psql_log.read_text(encoding="utf-8") + .splitlines() if line] + return [e for e in entries if e.get("kind") != "version"] + + def head(self) -> int: + return json.loads((self.stub_dir / "lanes-index.state").read_text(encoding="utf-8"))["n"] + + def register(self, seq: int, path: str = "lanes/LANES.md") -> str: + target = self.stub_dir / "lanes-index.register" / str(seq) / path + return target.read_text(encoding="utf-8") if target.exists() else None + + def added_lines(self) -> list: + """The lines `lanes/LANES.md` gained from seq 1 to the head.""" + before = self.register(1).split("\n") + after = self.register(self.head()).split("\n") + assert after[:len(before) - 1] == before[:-1], "lines before the end changed" + return [line for line in after[len(before) - 1:] if line] + + def git_state(self) -> tuple: + """The checkout's HEAD and status, `origin/main`, and origin's + `lanes/LANES.md`.""" + return (git(self.checkout, "rev-parse", "HEAD", env=self.env), + git(self.checkout, "status", "--porcelain=v1", "-uall", env=self.env), + git(self.origin, "log", "--format=%H", "main", env=self.env), + git(self.origin, "show", "main:lanes/LANES.md", env=self.env)) + + def locks(self) -> list: + return sorted(p.relative_to(self.root).as_posix() for p in self.root.rglob("*") + if p.name in (".lanes-edit.lock", "index.lock")) + + +def form(holder: str = HOLDER, pr=PR, repo: str = KEY, word: str = WORD, where: str = WHERE, + word_utc: str = WORD_UTC, omit=(), empty=()) -> list: + """`append-line --landing-expired`'s argument list (T425's usage).""" + argv = ["append-line", "--landing-expired", holder, "--pr", str(pr), "--repo", repo] + for flag, value in (("--word", word), ("--word-where", where), ("--word-utc", word_utc)): + if flag in omit: + continue + argv += [flag, "" if flag in empty else value] + return argv + + +def assert_nothing_sent(bench: Bench, proc: subprocess.CompletedProcess, before: tuple, + what: str) -> None: + """No `register commit` reached the stub, no `psql` call was made, the + head did not move, git is as it was and no lock is left.""" + assert bench.calls("register", "commit") == [], ( + f"{what}: a `register commit` was sent: {bench.calls('register', 'commit')}") + assert bench.psql_calls() == [], f"{what}: a psql call was made: {bench.psql_calls()}" + assert bench.head() == 1, f"{what}: the register's head moved to {bench.head()}" + assert bench.git_state() == before, f"{what}: git changed" + assert bench.locks() == [], f"{what}: a lock was left: {bench.locks()}" + + +def lanes_index_module(source: Path = LANES_INDEX): + """`lanes-index` loaded as a module, as T207's stub loads it for + `register classify`, so the case reads the checkout's own classifier.""" + loader = importlib.machinery.SourceFileLoader(f"lanes_index_t253_{uuid.uuid4().hex}", + str(source)) + spec = importlib.util.spec_from_loader(loader.name, loader) + module = importlib.util.module_from_spec(spec) + loader.exec_module(module) + return module + + +# ============================================================ (a) compose +COMPOSE = { + # case: (the register's lines, the form's arguments, the writer, the + # holder's spelling the line copies, the repository token it copies, the + # LANDING UTC it copies) + "plain": ([landing()], form(), WRITER, HOLDER, KEY, ago(31)), + "repo-alias-in-the-form": ([landing()], form(repo=ALIAS), WRITER, HOLDER, KEY, ago(31)), + "repo-alias-in-the-landing": ([landing(repo=ALIAS)], form(repo=KEY), WRITER, HOLDER, ALIAS, + ago(31)), + "old-name": ([landing(lane=OLD_NAME, session=SID_H)], form(), WRITER, OLD_NAME, KEY, ago(31)), + "other-case": ([landing(lane=HOLDER.lower(), session=SID_H)], form(), WRITER, + HOLDER.lower(), KEY, ago(31)), + "writer-is-the-holder": ([landing()], form(), HOLDER, HOLDER, KEY, ago(31)), + "newest-post": ([landing(minutes=50), landing(minutes=40)], form(), WRITER, HOLDER, KEY, + ago(40)), +} + + +@pytest.mark.parametrize("case", list(COMPOSE)) +def test_the_landing_expired_form_composes_its_line_from_the_open_landing(tmp_path, case): + """(a): on primary the form sends one `LANDING EXPIRED` line: `lane + <writer>` first, as `canon_lane` gives `LANES_LANE`; the session; the + snapshot's UTC (D13); `for lane <holder>`; then the PR, the repository's + token and the `LANDING`'s UTC copied byte for byte from the holder's + newest open `LANDING` at `n`, also where `--repo` is a `repos.tsv` alias + or the `LANDING`'s lane is an old name or in another case; and the word + clause last, where and when Brett gave his word, then his quote (Y:5109). + A writer who is also the holder is accepted. One `register commit` is + sent, and the line is the only change at `n+1`.""" + lines, argv, writer, holder, token, landing_utc = COMPOSE[case] + bench = Bench(tmp_path, lines) + proc = bench.run(argv, lane=writer) + assert proc.returncode == 0, ( + f"the form exited {proc.returncode}, not 0 (L4-B10, lane 4's T425): {proc.stderr[-800:]}") + assert len(bench.calls("register", "commit")) == 1, ( + f"{len(bench.calls('register', 'commit'))} commit calls, not one: the line was not sent " + f"on primary (L4-B3, T415; L4-B10, T425): {bench.calls()}") + added = bench.added_lines() + assert len(added) == 1, f"{len(added)} lines were sent, not one: {added}" + line = added[0] + head = f"LANDING EXPIRED {EM} lane {writer}, session {SESSIONS[writer]}@{WS}, {utc_of(CLOCK)}" + assert line.startswith(head), f"the line does not open with {head!r}: {line!r}" + parts = [f"for lane {holder}", f"PR #{PR}", f"into {token} main", landing_utc] + places = [line.find(part, len(head)) for part in parts] + assert -1 not in places, f"the line lacks one of {parts}: {line!r}" + word_at = line.find(WORD) + assert word_at > max(places), f"Brett's quote is not after the copied fields: {line!r}" + # Where and when Brett gave his word sit between the copied fields and the + # quote, which is last (Y:5109, `lanes-edit.sh:3375`; lane 4's TRIAGE-W13c). + where_at, when_at = line.find(WHERE, max(places)), line.find(WORD_UTC, max(places)) + assert max(places) < where_at < when_at < word_at, ( + f"the line lacks where or when Brett gave his word before his quote: {line!r}") + assert line.endswith(f"; on Brett's word ({WHERE}, {WORD_UTC}): \"{WORD}\""), ( + f"the line does not end with the form's word clause (Y:5109): {line!r}") + for path, text in bench.files.items(): + if RENDER_SET.match(path) and path != "lanes/LANES.md": + assert bench.register(bench.head(), path) == text, f"{path} changed" + + +# ============================================================ (b) the word +WORD_REFUSALS = { + "word-missing": (dict(argv=form(omit=("--word",))), "--word"), + "word-empty": (dict(argv=form(empty=("--word",))), "--word"), + "word-where-missing": (dict(argv=form(omit=("--word-where",))), "--word-where"), + "word-where-empty": (dict(argv=form(empty=("--word-where",))), "--word-where"), + "word-utc-missing": (dict(argv=form(omit=("--word-utc",))), "--word-utc"), + "word-utc-empty": (dict(argv=form(empty=("--word-utc",))), "--word-utc"), + "word-utc-not-a-utc": (dict(argv=form(word_utc="yesterday at noon")), "--word-utc"), + # A newline or a CR in any argument is refused before any is parsed, so + # the refusal names the break, not the flag (Y:5114; TP (b)); as + # `[newline-in-the-holder]`. + "newline-in-the-word": (dict(argv=form(word=WORD + "\nand more")), "newline"), + "cr-in-the-where": (dict(argv=form(where=WHERE + "\r")), "newline"), + "newline-in-the-holder": (dict(argv=form(holder=HOLDER + "\n")), "newline"), + "lanes-lane-unset": (dict(argv=form(), drop=("LANES_LANE",)), "LANES_LANE"), + "lanes-session-unset": (dict(argv=form(), drop=("LANES_SESSION",)), "LANES_SESSION"), +} + + +@pytest.mark.parametrize("argument", list(WORD_REFUSALS)) +def test_the_landing_expired_form_refuses_with_2_before_the_lock_without_the_word(tmp_path, + argument): + """(b): each exits 2, the lock not taken and nothing sent, and stderr + names what is wrong: any of the three word arguments missing or empty; + `--word-utc` not a UTC; a newline or a CR in any argument; `LANES_LANE` + or `LANES_SESSION` unset.""" + spec, names = WORD_REFUSALS[argument] + bench = Bench(tmp_path, [landing()]) + before = bench.git_state() + proc = bench.run(spec["argv"], drop=spec.get("drop", ())) + assert proc.returncode == 2, ( + f"[{argument}] the form exited {proc.returncode}, not 2 (L4-B10, T425): " + f"{proc.stderr[-600:]}") + assert names.lower() in proc.stderr.lower(), ( + f"[{argument}] stderr does not name {names!r}: {proc.stderr!r}") + assert_nothing_sent(bench, proc, before, argument) + + +# ============================================================ (b, U3) a take with no UTC +TAKES = { + "hold": (f"HOLD {EM} lane {WRITER} ({WS}), window w: {KEY} main {TIP} for AT-F13", True), + "landing": (f"LANDING {EM} lane {WRITER}, session {SID_W}@{WS}, PR #5 into {KEY} main", True), + "bad-stamp": (f"LANDING {EM} lane {WRITER}, session {SID_W}@{WS}, 2026-13-45T99:99Z, " + f"PR #5 into {KEY} main", True), + "hold-refresh": (f"HOLD (refresh) {EM} lane {WRITER} ({WS}), window w: {KEY} main {TIP} " + f"for AT-F13", False), + "off-primary": (f"HOLD {EM} lane {WRITER} ({WS}), window w: {KEY} main {TIP} for AT-F13", + False), +} + + +@pytest.mark.parametrize("case", list(TAKES)) +def test_on_primary_a_take_with_no_readable_utc_is_refused_before_the_lock_and_written_off_primary( + tmp_path, case): + """(b, U3): on primary `append-line` with a text the one classifier + reads as a `HOLD` with no UTC exits 2 before the lock, names the rule + and sends nothing; so do a `LANDING` with no UTC and a take whose stamp + does not parse, `2026-13-45T99:99Z`. A `HOLD (refresh)` with no UTC is not + refused by this rule, and is sent. Off primary the same `HOLD` is written + as today, after the mode query answered files.""" + text, refused = TAKES[case] + bench = Bench(tmp_path, [], mode="files" if case == "off-primary" else "primary") + before = bench.git_state() + proc = bench.run(["append-line", text]) + if refused: + assert proc.returncode == 2, ( + f"[{case}] append-line exited {proc.returncode}, not 2 (L4-B10, lane 4's T424): " + f"{proc.stderr[-600:]}") + assert "UTC" in proc.stderr, f"[{case}] stderr does not name the rule: {proc.stderr!r}" + assert_nothing_sent(bench, proc, before, case) + return + assert proc.returncode == 0, f"[{case}] append-line exited {proc.returncode}: {proc.stderr}" + if case == "hold-refresh": + assert len(bench.calls("register", "commit")) == 1, ( + f"[{case}] {len(bench.calls('register', 'commit'))} commit calls, not one " + f"(L4-B3, T415): the line was not sent on primary") + assert bench.added_lines() == [text] + return + assert bench.calls("register", "commit") == [], "files mode sent a commit" + assert git(bench.origin, "show", "main:lanes/LANES.md", env=bench.env).rstrip("\n") \ + .endswith(text), "files mode did not write the line as today" + assert bench.asked_the_mode(), ( + f"[{case}] the mode query was never asked, so this is not 'off primary' (lane 5's " + f"T504, reg_open): {bench.calls()}") + + +# ============================================================ C1's fourth text (T253c) +# +# Lane 4's question 11 (#165 6752694348; R-F11-1; lane 3's (a), 6747761107; +# B11 tasks:608, :1267): on primary `append-line` refuses, before the lock, a +# `LANDING` take whose lane cannot be read, which would hold `main` with +# nothing able to close it; files mode, which has no slot table, writes it as +# today. The line is a `LANDING` that names no lane, lane 2's reading of +# "whose lane cannot be read" until the contract's draft after 4.9 words the +# text (F11's NOTES question 34): it has a UTC and a repository, so neither of +# T424's other take refusals meets it. The case asserts the 2 and that nothing +# is written, not the wording. +LANELESS_LANDING = f"LANDING {EM} session {SID_W}@{WS}, {ago(1)}, PR #12 into {KEY} main" + + +def test_on_primary_a_landing_take_whose_lane_cannot_be_read_is_refused_before_the_lock_and_written_off_primary( + tmp_path): + """C1's fourth text: on primary, `append-line` of a `LANDING` line that + names no lane exits 2 before the lock, with no commit call, no `psql` + call and nothing written; off primary, after the mode query answered + files, the same line is written as today.""" + fields = lanes_index_module().parse_register_line(LANELESS_LANDING) + assert fields and fields["kind"] == "LANDING" and fields["lane"] is None, fields + assert fields["utc"] and fields["repo"] == KEY, fields + bench = Bench(tmp_path / "primary", []) + before = bench.git_state() + proc = bench.run(["append-line", LANELESS_LANDING]) + assert proc.returncode == 2, ( + f"append-line of a LANDING whose lane cannot be read exited {proc.returncode}, not 2, " + f"on primary (L4-B10, lane 4's T424): {proc.stderr[-600:]}") + assert_nothing_sent(bench, proc, before, "laneless-landing") + files = Bench(tmp_path / "files", [], mode="files") + written = files.run(["append-line", LANELESS_LANDING]) + assert written.returncode == 0, f"files mode refused the line: {written.stderr}" + assert files.calls("register", "commit") == [], "files mode sent a commit" + assert git(files.origin, "show", "main:lanes/LANES.md", env=files.env).rstrip("\n") \ + .endswith(LANELESS_LANDING), "files mode did not write the line as today" + assert files.asked_the_mode(), ( + f"the mode query was never asked, so this is not 'off primary' (lane 5's T504, " + f"reg_open): {files.calls()}") + + +# ============================================================ (c) the kind typed by hand +TYPED = { + "em-dash": (f"LANDING EXPIRED {EM} ", True), + "hyphen": ("LANDING EXPIRED - ", True), + "tab-em-dash": (f"LANDING EXPIRED\t{EM}\t", True), + "tab-hyphen": ("LANDING EXPIRED\t-\t", True), + "landing": (f"LANDING {EM} ", False), + "landed": (f"LANDED {EM} ", False), + "landing-expiredx": (f"LANDING EXPIREDX {EM} ", False), +} + + +def _typed(opening: str) -> str: + rest = (f"lane {WRITER}, session {SID_W}@{WS}, {ago(1)}, for lane {HOLDER}, PR #12 into {KEY} " + f"main") + if opening.startswith("LANDED"): + rest += f" {ARROW} abc1234" + return opening + rest + + +@pytest.mark.parametrize("text", list(TYPED)) +def test_on_primary_the_landing_expired_kind_typed_by_hand_is_refused_naming_the_form(tmp_path, + text): + """(c): on primary `LANDING EXPIRED <dash> ` and its tab forms each exit + 2 with nothing sent, and stderr names `append-line --landing-expired`. + The rule does not refuse `LANDING <dash> `, `LANDED <dash> ` or `LANDING + EXPIREDX <dash> `. The grown `REGISTER_KIND_RE` (lane 1's T118) reads the + kind `LANDING EXPIRED` from exactly the refused rows.""" + opening, refused = TYPED[text] + line = _typed(opening) + kind_re = lanes_index_module().REGISTER_KIND_RE + m = kind_re.match(line) + assert bool(m and m.group(1) == "LANDING EXPIRED") == refused, ( + f"[{text}] REGISTER_KIND_RE reads {(m.group(1) if m else None)!r}: the client's rule and " + f"the one classifier disagree (L1-A16, lane 1's T118)") + bench = Bench(tmp_path, []) + before = bench.git_state() + proc = bench.run(["append-line", line]) + if refused: + assert proc.returncode == 2, ( + f"[{text}] append-line exited {proc.returncode}, not 2 (L4-B10, T424): " + f"{proc.stderr[-600:]}") + assert "append-line --landing-expired" in proc.stderr, ( + f"[{text}] stderr does not name the form: {proc.stderr!r}") + assert_nothing_sent(bench, proc, before, text) + return + assert proc.returncode == 0, f"[{text}] append-line exited {proc.returncode}: {proc.stderr}" + assert len(bench.calls("register", "commit")) == 1, ( + f"[{text}] the line was not sent on primary (L4-B3, T415): {bench.calls()}") + assert bench.added_lines() == [line] + + +# ============================================================ (d) nothing stale +NOTHING_STALE = { + "no-landing": ([landing(lane=OTHER)], {}), + "closed-by-landed": ([landing(minutes=45), landed(minutes=40)], {}), + "already-released": ([landing(minutes=45), expired(minutes=10, landing_utc=ago(45))], {}), + "other-pr": ([landing(pr=OTHER_PR)], {}), + "other-repository": ([landing(repo=OTHER_KEY)], {}), + "age-29": ([landing(minutes=29)], {}), + "age-30": ([landing(minutes=30)], {}), + "posted-again-40-and-10": ([landing(minutes=40), landing(minutes=10)], {}), + "landing-minutes-5": ([landing(minutes=10)], {"LANES_LANDING_MINUTES": "5"}), +} + + +@pytest.mark.parametrize("case", list(NOTHING_STALE)) +def test_the_landing_expired_form_sends_nothing_where_no_landing_is_stale_at_the_snapshot( + tmp_path, case): + """(d): each exits 2 with no commit call and nothing written: no + `LANDING`; one closed by `LANDED`; one already released by an earlier + `LANDING EXPIRED`; the holder's `LANDING` for another PR or repository; + ages of 29 and 30 minutes by the snapshot's clock, far from `date`; a + `LANDING` posted again, 40 and 10 minutes before, whose newest post is not + past 30 minutes; and `LANES_LANDING_MINUTES=5` changes nothing. At 31 + minutes the line is composed: case (a)'s `[plain]`.""" + lines, extra = NOTHING_STALE[case] + bench = Bench(tmp_path, lines) + before = bench.git_state() + proc = bench.run(form(), extra=extra) + assert proc.returncode == 2, ( + f"[{case}] the form exited {proc.returncode}, not 2 (L4-B10, T425): {proc.stderr[-600:]}") + assert proc.stderr.strip(), f"[{case}] the refusal says nothing" + assert_nothing_sent(bench, proc, before, case) + + +# ============================================================ (e) what it prints +LR005_YOUNG = (f"ERROR: LR005: lane {HOLDER}'s LANDING of {ago(12)} for PR #{PR} into {KEY} " + f"main is too young (F13): its age by the database's clock is 12 min\n" + f"DETAIL: expired-young\n") + + +@pytest.mark.parametrize("case", ["success", "lr005-expired-young", "in-doubt"]) +def test_the_landing_expired_form_prints_its_seq_once_and_an_lr005_with_its_detail_token(tmp_path, + case): + """(e): success prints one line, `register seq <s>: released lane + <holder>'s LANDING of <UTC> (PR #<n> into <repo> main), <m> min past Rule + 6's 30`, and exits 0. A fake LR005 exits 2, and stderr has LR005, its + token and that nothing was written. A fake in-doubt commit, whose lookup + is in doubt too, exits 3 and prints the rerun once; the rerun with the + same arguments sends the same `--args-sha256`, and commits.""" + bench = Bench(tmp_path, [landing(minutes=31)]) + if case == "lr005-expired-young": + bench.outcome("register commit", exit=2, stderr=LR005_YOUNG) + if case == "in-doubt": + bench.outcome("register commit", exit=3, + stderr="ERROR: 57014: canceling statement due to statement timeout\n") + bench.outcome("journal", exit=3, stderr="lanes-index: journal: in doubt (T253)\n") + proc = bench.run(form()) + said = proc.stdout + proc.stderr + if case == "success": + assert proc.returncode == 0, f"the form exited {proc.returncode} (L4-B10): {proc.stderr}" + want = (f"register seq 2: released lane {HOLDER}'s LANDING of {ago(31)} (PR #{PR} into " + f"{KEY} main), 1 min past Rule 6's 30") + assert proc.stdout.splitlines().count(want) == 1, f"stdout is not {want!r}: {proc.stdout!r}" + assert said.count("register seq") == 1, f"the seq is printed more than once: {said!r}" + return + if case == "lr005-expired-young": + assert proc.returncode == 2, f"exit {proc.returncode}, not 2 (L4-B10): {proc.stderr}" + for part in ("LR005", "expired-young", "nothing was written"): + assert part in proc.stderr, f"stderr lacks {part!r}: {proc.stderr!r}" + assert "register seq" not in said + return + assert proc.returncode == 3, f"exit {proc.returncode}, not 3 (L4-B3, T415): {proc.stderr}" + assert said.count("--landing-expired") == 1, f"the rerun is not printed once: {said!r}" + first = bench.calls("register", "commit") + assert first, "no commit call was made" + bench.outcome("register commit") + bench.outcome("journal") + again = bench.run(form()) + assert again.returncode == 0, f"the rerun exited {again.returncode}: {again.stderr}" + sums = {argv[argv.index("--args-sha256") + 1] for argv in bench.calls("register", "commit")} + assert len(sums) == 1, f"the rerun's digest differs from the pending record's: {sums}" + + +# ============================================================ (f) files mode +@pytest.mark.parametrize("mode", ["files", "fall-to-files"]) +def test_in_files_mode_the_landing_expired_form_exits_2_and_changes_nothing(tmp_path, mode): + """(f): in files mode, and after the mode query's fall to files mode + (F8), the form exits 2 saying the release of a stale `LANDING` exists + only on `mode=primary` and nothing was written; the register file, `git + log` and `who --landing`'s output are byte-identical before and after, + each line's age aside, which the host's clock moves and each read must + show as its UTC's age by that clock (`aged_out`; RC-W49's SHOULD 1). + Plain `append-line "LANDING EXPIRED <dash> ..."` is written as today.""" + bench = Bench(tmp_path, [landing()], mode="files" if mode == "files" else "fall") + before, (_, listed) = bench.git_state(), bench.who_aged() + proc = bench.run(form()) + assert proc.returncode == 2, ( + f"[{mode}] the form exited {proc.returncode}, not 2 (L4-B10, T425): {proc.stderr[-600:]}") + for part in FILES_MODE_WORDS: + assert part in proc.stderr, f"[{mode}] stderr lacks {part!r}: {proc.stderr!r}" + assert bench.git_state() == before, f"[{mode}] git changed" + assert bench.who_aged()[1] == listed, f"[{mode}] who --landing changed" + typed = _typed(f"LANDING EXPIRED {EM} ") + plain = bench.run(["append-line", typed]) + assert plain.returncode == 0, f"[{mode}] the plain line was refused: {plain.stderr}" + assert git(bench.origin, "show", "main:lanes/LANES.md", env=bench.env).rstrip("\n") \ + .endswith(typed), f"[{mode}] the plain line was not written as today" + + +# ============================================================ (g) parse +def test_parse_register_line_reads_the_landing_expired_fields_before_the_word_clause(): + """(g): Brett's quote carries `lane x`, `PR #9`, `into a/b main`, a UTC + and `session s@w`; `parse_register_line` still reads the writer, the PR, + the repository, the UTC and the session from before the word clause, and + `for_lane` is the holder (lane 1's T118, which grows `REGISTER_KIND_RE` + to `LANDING EXPIRED` and adds `for_lane`).""" + line = expired(writer=WRITER, minutes=0, pr=7, landing_utc=ago(45), + word="lane x, PR #9 into a/b main, 2026-01-02T03:04:05Z, session s@w", + where="lane x's session", word_utc="2026-01-02T03:05:00Z") + fields = lanes_index_module().parse_register_line(line) + assert fields is not None, ( + "parse_register_line reads no kind from a LANDING EXPIRED line (L1-A16, lane 1's T118)") + assert fields["kind"] == "LANDING EXPIRED", fields + assert (fields["lane"], fields["pr"], fields["repo"], fields["utc"], fields["session"]) == \ + (WRITER, "7", KEY, utc_of(CLOCK), SID_W), fields + assert fields.get("for_lane") == HOLDER, fields + + +# ============================================================ (k) who --landing on primary +WHO_CASES = { + # case: (the lines, the lanes listed, the lanes not listed) + "released-only-one": ([landing(minutes=45), expired()], [], [HOLDER]), + "another-lane-still-listed": ([landing(minutes=45), landing(lane=OTHER, minutes=20, pr=11), + expired(writer=WRITER)], [OTHER], [HOLDER]), + "names-another-pr": ([landing(minutes=45), expired(pr=OTHER_PR)], [HOLDER], []), + "names-another-repository": ([landing(minutes=45), expired(repo=OTHER_KEY)], [HOLDER], []), + "names-the-holder-in-another-case": ([landing(minutes=45), expired(holder=HOLDER.upper())], + [HOLDER], []), + "a-later-landing": ([landing(minutes=45), expired(minutes=20), landing(minutes=2)], + [HOLDER], []), + "the-quote-names-another-lane": ([landing(minutes=45), landing(lane=OTHER, minutes=20, pr=11), + expired(writer=WRITER, word=f"lane {OTHER}, PR #11 into " + f"{OTHER_KEY} main")], + [OTHER], [HOLDER]), +} + + +@pytest.mark.parametrize("case", list(WHO_CASES)) +def test_who_landing_on_primary_drops_only_the_released_landing(tmp_path, case): + """(k): on primary, with the fake `register read` prefetch whose text at + `n` holds the lines, a released `LANDING` is not listed, and `none open + <dash> ...` is printed where it was the only one; another lane's `LANDING` + on that repository is still listed; a `LANDING EXPIRED` naming another + PR, another repository or the holder in another case closes nothing; the + holder's later `LANDING` is listed again; Brett's quote naming another + lane, PR or repository changes nothing; and no empty row is listed.""" + lines, listed, dropped = WHO_CASES[case] + bench = Bench(tmp_path, lines) + proc = bench.who() + assert proc.returncode == 0, f"[{case}] who --landing exited {proc.returncode}: {proc.stderr}" + rows = [line for line in proc.stdout.splitlines() if line.startswith("LANDING ")] + for lane in dropped: + assert not any(f" lane {lane}," in row for row in rows), ( + f"[{case}] lane {lane}'s released LANDING is still listed on primary (L4-B10, " + f"T425's RULE6_EXPIRED_AWK): {rows}") + for lane in listed: + assert any(f" lane {lane}," in row for row in rows), ( + f"[{case}] lane {lane}'s LANDING is not listed: {proc.stdout!r}") + if not listed: + assert any(line.startswith(f"none open {EM} ") for line in proc.stdout.splitlines()), ( + f"[{case}] `none open` is not printed: {proc.stdout!r}") + assert not any(re.search(r"#\s|lane ,", row) for row in rows), f"an empty row: {rows}" + assert bench.calls("register", "read"), ( + f"[{case}] who --landing did not read the register through the prefetch (lane 5's " + f"T504, reg_open): {bench.calls()}") + + +# ============================================================ (l) off primary, and the flag +INHERITED = {"RULE6_PRIMARY": "1", "RULE6_AWK": '{ print "INHERITED" }', + "RULE6_EXPIRED_AWK": '{ print "INHERITED" }'} + + +@pytest.mark.parametrize("mode", ["files", "index", "unconfigured", "fall-to-files"]) +def test_off_primary_rule6_awk_is_the_pin_and_the_flag_cannot_be_inherited(tmp_path, mode): + """(l): the same register text, read in files mode, in `index` mode, on + an unconfigured workstation and after F8's fall to files mode, lists the + holder's `LANDING`, marked STALE, as today; a caller's environment + carrying `RULE6_PRIMARY=1`, `RULE6_AWK` or `RULE6_EXPIRED_AWK` changes + nothing, each line's age aside, as in (f); and `RULE6_AWK`'s text is the + pin's. The mode query was asked where a configuration exists, and not on + the unconfigured workstation, which starts no process (D3).""" + bench = Bench(tmp_path, [landing(minutes=45), expired()], + mode="fall" if mode == "fall-to-files" else mode) + plain, plain_aged = bench.who_aged() + assert plain.returncode == 0, f"[{mode}] who --landing exited {plain.returncode}" + rows = [line for line in plain.stdout.splitlines() + if line.startswith(f"LANDING {KEY}#{PR} lane {HOLDER}, {ago(45)}")] + assert len(rows) == 1 and rows[0].endswith(STALE_MARK), ( + f"[{mode}] the holder's LANDING is not listed STALE as today: {plain.stdout!r}") + flagged, flagged_aged = bench.who_aged(extra=INHERITED) + assert (flagged.returncode, flagged_aged) == (plain.returncode, plain_aged), ( + f"[{mode}] an inherited RULE6_* changed who --landing: {flagged.stdout!r}") + text = bench.lanes_edit.read_text(encoding="utf-8") + assert _rule6_awk_sha(text) == RULE6_AWK_PIN, f"[{mode}] RULE6_AWK is not the pin" + # D3 (Y:368-371): `lanes-index mode` is asked only where a configuration + # exists, so the unconfigured workstation starts no process and asks + # nothing (T504's `asks_lanes_index_mode_only_where_a_configuration_exists`). + asked = mode != "unconfigured" + said = "was never asked" if asked else "was asked with no configuration, against D3" + assert bench.asked_the_mode() == asked, ( + f"[{mode}] the mode query {said} (lane 5's T504, reg_open; T425's one line sets " + f"rule6_primary_on from its answer): {bench.calls()}") + + +def _rule6_awk_sha(text: str) -> str: + found = re.findall(r"^RULE6_AWK='(.*?)'$", text, re.S | re.M) + assert len(found) == 1, f"{len(found)} `RULE6_AWK='...'` assignments, not one" + return hashlib.sha256(found[0].encode("utf-8")).hexdigest() + + +def _function_body(text: str, name: str) -> str: + m = re.search(rf"^{re.escape(name)}\(\) \{{\n(.*?)^\}}$", text, re.S | re.M) + return m.group(1) if m else None + + +def _awks() -> list: + found = [] + for name in ("awk", "mawk", "gawk", "original-awk", "nawk"): + path = shutil.which(name) + if path and os.path.realpath(path) not in [os.path.realpath(p) for p in found]: + found.append(path) + busybox = shutil.which("busybox") + if busybox: + found.append(f"{busybox} awk") + return found + + +def test_rule6_primary_on_is_called_only_where_lane_4_places_it_and_who_landing_stays_pinned(): + """(l), the source check: `rule6_primary_on` is defined once and called + at one site, T425's one line that reads `REG_MODE` after both doors and + before the arm (R45; B11 tasks:729, :1102, :1282); it appends + `RULE6_EXPIRED_AWK` to `RULE6_AWK` once and sets `RULE6_PRIMARY`; + `RULE6_AWK` itself is the pin; `who_landing`'s pinned line is unchanged; + and the program with the branch gives one output on every awk here.""" + text = LANES_EDIT.read_text(encoding="utf-8") + body = _function_body(text, "rule6_primary_on") + assert body is not None, "lanes-edit.sh defines no rule6_primary_on (L4-B10, lane 4's T425)" + calls = [line for line in text.splitlines() + if "rule6_primary_on" in line and not line.lstrip().startswith("#") + and not line.startswith("rule6_primary_on()")] + assert len(calls) == 1 and "REG_MODE" in calls[0], ( + f"rule6_primary_on is called at {len(calls)} sites, not at T425's one line on " + f"REG_MODE: {calls}") + assert body.count("RULE6_EXPIRED_AWK") == 1 and "RULE6_PRIMARY=" in body, body + assert _rule6_awk_sha(text) == RULE6_AWK_PIN, "RULE6_AWK is not the pin" + assert text.count(WHO_LANDING_LINE + "\n") == 1, "who_landing's pinned line changed" + branch = re.findall(r"^RULE6_EXPIRED_AWK='(.*?)'$", text, re.S | re.M) + assert len(branch) == 1, "no single RULE6_EXPIRED_AWK='...' assignment" + program = re.findall(r"^RULE6_AWK='(.*?)'$", text, re.S | re.M)[0] + branch[0] + sample = "\n".join([landing(minutes=45), expired(), landing(lane=OTHER, minutes=20, pr=11)]) + outputs = {} + for awk in _awks(): + proc = subprocess.run([*awk.split(), program], input=sample + "\n", capture_output=True, + encoding="utf-8", env={"PATH": "/usr/bin:/bin", "LC_ALL": "C", + "LANES_RULE6_ALIASES": f"{ALIAS}\037{KEY}"}, + timeout=60, check=False) + assert proc.returncode == 0, f"{awk} refused the program: {proc.stderr}" + outputs[awk] = sorted(proc.stdout.splitlines()) + assert len({json.dumps(o) for o in outputs.values()}) == 1, outputs + + +# ============================================================ (m) the token decides +FAKE_LR005 = { + # case: (the verb's arguments, the lane, the server's message, the token, + # what stderr must also carry) + "expired-none": (form(), WRITER, + f"no open LANDING of lane {HOLDER} for PR #{PR} into {KEY} main to release " + f"(F13)", "expired-none", ()), + "expired-closed": (form(), WRITER, + f"lane {HOLDER}'s LANDING for PR #{PR} is already closed, by a LANDED of " + f"{HOLDER} (F13)", "expired-closed", ()), + "expired-young": (form(), WRITER, LR005_YOUNG.splitlines()[0][len("ERROR: LR005: "):], + "expired-young", ()), + "take-no-utc": (["append-line", f"HOLD {EM} lane {WRITER} ({WS}), window w, {ago(1)}: {KEY} " + f"main {TIP} for AT-F13"], WRITER, + "a take whose UTC cannot be read takes nothing (U3)", "take-no-utc", ()), + "one-live-claim": (["claim", f"{KEY}#{PR}", "--no-github"], WRITER, + f"{KEY}#{PR} already has a live claim, lane {OTHER}'s at seq 4 (D19)", + "one-live-claim", (OTHER,)), + "claim-spellings": (["claim", f"{ALIAS}#{PR}", "--no-github"], WRITER, + f"{ALIAS}#{PR} is {KEY}#{PR}, claimed by lane {OTHER} at seq 4 (D19)", + "claim-spellings", (OTHER,)), + "main-held": (["append-line", f"HOLD {EM} lane {WRITER} ({WS}), window w, {ago(1)}: {KEY} " + f"main {TIP} for AT-F13"], WRITER, + f"{KEY} main is held by lane {OTHER}'s LANDING at seq 4 (D18)", "main-held", + (OTHER,)), +} +F13_TOKENS = ("expired-none", "expired-closed", "expired-young") + + +@pytest.mark.parametrize("case", [*FAKE_LR005, "swapped-message"]) +def test_the_writer_reads_lr005s_reason_from_its_detail_token_never_its_message(tmp_path, case): + """(m), U7: the commit call ends LR005 with exit 2, `ERROR: LR005: + <message>` and `DETAIL: <token>`. For each of F13's three tokens and + `take-no-utc`, the writer exits 2 and stderr carries the server's + message, the token and that nothing was written; for `one-live-claim`, + `claim-spellings` and `main-held` it exits 2 as AT-4's losers do, naming + the holder. `[swapped-message]`: F13's message under `main-held` gives no + F13 token, and D18's message under `expired-young` gives `expired-young`: + the writer follows the token.""" + bench = Bench(tmp_path, [landing(minutes=45)]) + if case == "swapped-message": + runs = [(FAKE_LR005["main-held"][0], FAKE_LR005["expired-young"][2], "main-held"), + (form(), FAKE_LR005["main-held"][2], "expired-young")] + for argv, message, token in runs: + bench.outcome("register commit", exit=2, + stderr=f"ERROR: LR005: {message}\nDETAIL: {token}\n") + proc = bench.run(argv) + assert proc.returncode == 2, f"[{token}] exit {proc.returncode}, not 2: {proc.stderr}" + carried = [t for t in F13_TOKENS if t in proc.stderr] + want = [] if token == "main-held" else [token] + assert carried == want, ( + f"[{token}] stderr carries {carried}, not {want}: the writer read the message, " + f"not the token (U7; L4-B10): {proc.stderr!r}") + bench.outcome("register commit") + return + argv, lane, message, token, names = FAKE_LR005[case] + bench.outcome("register commit", exit=2, stderr=f"ERROR: LR005: {message}\nDETAIL: {token}\n") + before = bench.git_state() + proc = bench.run(argv, lane=lane) + assert proc.returncode == 2, ( + f"[{case}] the writer exited {proc.returncode}, not 2 (L4-B3, T415; L4-B10): " + f"{proc.stderr[-600:]}") + if names: + for name in names: + assert name in proc.stderr, f"[{case}] stderr does not name {name}: {proc.stderr!r}" + else: + for part in (message, token, "nothing was written"): + assert part in proc.stderr, f"[{case}] stderr lacks {part!r}: {proc.stderr!r}" + assert bench.head() == 1 and bench.git_state() == before, f"[{case}] something was written" + + +# ============================================================ the real engine: (i) and (j) +# +# AT-F13's fixture for (h) to (j) (the test plan's section on AT-F13, +# "Fixture"): a clone of `tmpl_imported` (or of `tmpl`, where the case imports +# its own history) brought to `primary` with the marker `present` by +# AT-LR006's route, the documented functions called as REGISTER-WRITER through +# T228's `lanes_w_fx`, in T223's form (`test_sql_register_order.py`'s `Clone`) +# and T210's (`import_to_primary`). + +SCHEMA = "lanes_register" +WRITER_LOGIN = "lanes_w_fx" +CONNECT_TO = "lanes_register_writer, lanes_register_reader, lanes_indexer" +AUTHOR = "T253 Fixture <t253@example.invalid>" +OPERATOR = "operator-t253" +MARKER_COMMIT = "c0ffee" + "0" * 34 +_NAMES = itertools.count(1) + + +class Register: + """A clone of `template`, its own, dropped by the fixture at the end.""" + + def __init__(self, cluster, template: str) -> None: + found = cluster.psql(f"SELECT datname FROM pg_database WHERE datname = '{template}';") + assert found.stdout.split() == [template], ( + f"no {template} on the session cluster: lane 2's T227 builds it") + self.cluster, self.name = cluster, f"t253_{next(_NAMES)}" + cluster.psql(f"CREATE DATABASE {self.name} TEMPLATE {template};") + cluster.psql(f"REVOKE ALL ON DATABASE {self.name} FROM PUBLIC;\n" + f"GRANT CONNECT ON DATABASE {self.name} TO {CONNECT_TO};\n") + from pgcluster import Database + self.db = Database(cluster, self.name) + + def value(self, sql: str) -> str: + return self.db.psql(sql).stdout.strip() + + def rows(self, query: str) -> list: + out = self.value(f"SET search_path TO {SCHEMA};\n" + f"SELECT coalesce(jsonb_agg(q), '[]'::jsonb) FROM ({query}) q;") + return json.loads(out.splitlines()[-1]) + + def head(self) -> int: + return self.rows("SELECT seq FROM register_head")[0]["seq"] + + def clock(self) -> int: + return self.rows("SELECT floor(extract(epoch FROM clock_timestamp()))::bigint AS s")[0]["s"] + + def call(self, sql: str) -> subprocess.CompletedProcess: + argv = [self.db.psql_bin, "-X", "-q", "-A", "-t", "-v", "ON_ERROR_STOP=1", + "-v", "VERBOSITY=verbose", "-v", "SHOW_CONTEXT=never"] + return subprocess.run(argv, input=sql, capture_output=True, text=True, timeout=60, + env=self.db.env(WRITER_LOGIN), check=False) + + def commit(self, body: dict) -> int: + """The commit call, as `lanes_w_fx`, at the head; the seq it made.""" + sw = self.rows("SELECT generation FROM register_switch")[0] + version = self.rows("SELECT version FROM schema_version")[0]["version"] + literal = json.dumps(body, ensure_ascii=True).replace("'", "''") + proc = self.call(f"BEGIN ISOLATION LEVEL SERIALIZABLE;\n" + f"SELECT {SCHEMA}.commit_write({self.head()}, '{uuid.uuid4()}'::uuid, " + f"{version}, '{sw['generation']}'::uuid, '{literal}'::jsonb);\nCOMMIT;\n") + assert proc.returncode == 0, f"commit_write exited {proc.returncode}: {proc.stderr[-800:]}" + return int(proc.stdout.strip().splitlines()[-1]) + + def entry(self, kind: str, verb: str, lane: str, **parts) -> dict: + journal = {"kind": kind, "verb": verb, "lane": lane, "workstation": WS, "author": AUTHOR, + "message": f"t253: {kind}"} + journal.update(parts.pop("journal", {})) + return {"journal": journal, "not_after": "2100-01-01T00:00:00Z", **parts} + + def import_files(self, files: dict, register_lines: list) -> int: + """An `import` entry of `files` ({path: text}), with `register_lines`.""" + edits, rows, ordinal = [], [], 0 + for path in sorted(files): + ordinal += 1 + edits.append({"ord": ordinal, "op": "create", "path": path}) + for text in files[path].rstrip("\n").split("\n"): + ordinal += 1 + edits.append({"ord": ordinal, "op": "append", "path": path, "new_text": text}) + rows.append({"path": path, "present": True, "final_newline": True, + "sha256": hashlib.sha256(files[path].encode("utf-8")).hexdigest()}) + return self.commit(self.entry("import", "import", OPERATOR, + journal={"git_commit": "1" * 40, "git_tree": "2" * 40}, + edits=edits, files=rows, register_lines=register_lines)) + + def to_primary(self) -> int: + """AT-LR006's route: a `cutover` entry, then `record_marker`.""" + store = "store=primary\n" + cut = self.commit(self.entry("cutover", "cutover", OPERATOR, + edits=[{"ord": 1, "op": "create", "path": "lanes/STORE"}, + {"ord": 2, "op": "append", "path": "lanes/STORE", + "new_text": "store=primary"}], + files=[{"path": "lanes/STORE", "present": True, + "final_newline": True, + "sha256": hashlib.sha256(store.encode()).hexdigest()}])) + version = self.rows("SELECT version FROM schema_version")[0]["version"] + marked = self.call(f"SELECT {SCHEMA}.record_marker({version}, {cut}, '{MARKER_COMMIT}', " + f"'{WS}');\n") + assert (marked.returncode, marked.stdout.strip()) == (0, "present"), marked.stderr + return cut + + def open_landings(self) -> set: + return {(r["lane"], str(r["pr"]), r["repo_key"]) for r in self.rows( + "SELECT lane, pr, repo_key FROM main_slots WHERE slot_kind = 'landing'")} + + +@pytest.fixture() +def registers(pg_cluster): + made = [] + + def make(template: str = "tmpl_imported") -> Register: + reg = Register(pg_cluster, template) + made.append(reg.name) + return reg + + yield make + for name in made: + pg_cluster.drop_database(name) + + +def line_rows(lines: list, clock: int, repos: dict, path: str = "lanes/LANES.md", + first_line: int = 1) -> list: + """Each line's `register_lines` row, as the checkout's own classifier + (lane 1's T118: `parse_register_line`, `REGISTER_SLOTS`) reads it, its + `repo_key` by `repos` ({spelling: key}, Rule 6's map), its `utc_ts` the + line's UTC as epoch seconds.""" + module = lanes_index_module() + rows = [] + for k, text in enumerate(lines): + fields = module.parse_register_line(text) + if fields is None: + continue + role, slot = module.REGISTER_SLOTS.get(fields["kind"], (None, None)) + repo = fields.get("repo") + key = repos.get((repo or "").lower(), repo) + utc = fields.get("utc") + epoch = calendar.timegm(time.strptime(utc, "%Y-%m-%dT%H:%M:%SZ")) if utc else None + rows.append({"kind": fields["kind"], "slot_role": role, "slot_kind": slot, + "lane": fields["lane"], "repo": repo, "repo_key": key, + "repo_spellings": sorted({repo, key}) if repo else None, + "pr": int(fields["pr"]) if fields.get("pr") else None, "tip": fields.get("tip"), + "utc": utc, "utc_ts": utc_of(epoch).replace("T", " ").replace("Z", "+00") + if epoch is not None else None, + "session": fields.get("session"), "for_lane": fields.get("for_lane"), + "path": path, "line_no": first_line + k, "raw": text, "workstation": WS}) + return rows + + +def _shift(text: str, clock: int) -> str: + """`text` with every UTC read from `CLOCK` moved to `clock`, so a + history's ages hold against the database's clock.""" + return re.sub(r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z", + lambda m: utc_of(calendar.timegm(time.strptime(m.group(0), "%Y-%m-%dT%H:%M:%SZ")) + - CLOCK + clock), text) + + +def primary_program_rows(text: str, aliases: dict) -> set: + """The primary program, `RULE6_AWK` with `RULE6_EXPIRED_AWK` (lane 4's + T425), over `text`: its open `LANDING`s, (lane, pr, canonical repo).""" + source = LANES_EDIT.read_text(encoding="utf-8") + base = re.findall(r"^RULE6_AWK='(.*?)'$", source, re.S | re.M) + branch = re.findall(r"^RULE6_EXPIRED_AWK='(.*?)'$", source, re.S | re.M) + assert len(base) == 1 and len(branch) == 1, ( + "lanes-edit.sh has no RULE6_EXPIRED_AWK beside RULE6_AWK (L4-B10, lane 4's T425)") + table = "\n".join(f"{a}\037{k}" for a, k in aliases.items()) + proc = subprocess.run(["awk", base[0] + branch[0]], input=text, capture_output=True, + encoding="utf-8", env={"PATH": "/usr/bin:/bin", "LC_ALL": "C", + "LANES_RULE6_ALIASES": table}, + timeout=60, check=False) + assert proc.returncode == 0, proc.stderr + found = set() + for row in proc.stdout.splitlines(): + parts = row.split("\037") + if parts[0] == "LANDING": + found.add((parts[1], parts[2], aliases.get(parts[4].lower(), parts[4]))) + return found + + +#: THE FORM'S WORD CLAUSE, the line's last part as `lanes-edit.sh:3375` composes +#: it (Y:5109): where and when Brett gave his word, then his quote. +WORD_CLAUSE_RE = re.compile(r"; on Brett's word \([^()]+, [0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:" + r"[0-9]{2}:[0-9]{2}Z\): \"[^\"]+\"$") + + +def f13_findings(rows: list) -> dict: + """LANE 2'S OWN CHECK of each imported `LANDING EXPIRED` (Y:5141, AT-F13 + (j)): the import does not run F13's check, so a line typed by hand in + files mode would release a `LANDING` that F13 never judged, and both + readers would agree on it. A line is a finding unless it meets F13's + condition by its own UTC and its `LANDING`'s, matched as lane 1's check in + the commit matches them (`lanes-index:7690-7715` at `c8acf67c`): the + holder's newest `LANDING` before it for that PR and `repo_key`, the + holder compared case-blind; no close of that `LANDING` between; and more + than 30 minutes apart; and unless it ends with the form's word clause + (Y:5109). `rows` are `line_rows`' in file order; the answer is {the line: + what it fails}.""" + found = {} + for k, row in enumerate(rows): + if row["kind"] != "LANDING EXPIRED": + continue + holder, why = (row["for_lane"] or "").lower(), [] + takes = [j for j in range(k) if rows[j]["slot_role"] == "take" + and rows[j]["slot_kind"] == "landing" and (rows[j]["lane"] or "").lower() == holder + and rows[j]["pr"] == row["pr"] and rows[j]["repo_key"] == row["repo_key"]] + if not takes: + why.append("no LANDING of the holder for that PR and repo_key before it") + else: + take = rows[takes[-1]] + if any(c["slot_role"] == "close" and c["slot_kind"] == "landing" + and (c["for_lane"] or c["lane"] or "").lower() == holder + and c["pr"] == row["pr"] and c["repo_key"] == row["repo_key"] + for c in rows[takes[-1] + 1:k]): + why.append("a close of its LANDING between") + own, its = _epoch_of(row["utc"]), _epoch_of(take["utc"]) + if own is None or its is None or own - its <= 30 * 60: + why.append("not more than 30 minutes after its LANDING") + if not WORD_CLAUSE_RE.search(row["raw"]): + why.append("no word clause") + if why: + found[row["raw"]] = why + return found + + +HISTORIES = { + # history: (its lines, whether the two readers agree, and what lane 2's + # own check of F13's condition finds in its `LANDING EXPIRED`, or None) + "today": ([landing(minutes=45), landing(lane=OTHER, minutes=50, pr=11), landed(lane=OTHER, + minutes=48, + pr=11)], + True, None), + "re-import-after-a-rollback": ([landing(minutes=45), expired(minutes=10)], True, None), + "typed-in-files-mode-meeting-f13": ([landing(minutes=45), expired(minutes=10)], True, None), + "typed-10-minutes-after-its-landing": ([landing(minutes=45), expired(minutes=35)], True, + "not more than 30 minutes"), + "no-word-clause": ([landing(minutes=45), expired(minutes=10, clause=False)], True, + "no word clause"), + "naming-another-pr": ([landing(minutes=45), expired(minutes=10, pr=OTHER_PR)], True, + "no LANDING"), + "holder-in-another-case": ([landing(minutes=45), expired(minutes=10, holder=HOLDER.lower())], + False, None), +} + + +@pytest.mark.parametrize("history", list(HISTORIES)) +def test_rule6_with_the_expired_branch_agrees_with_main_slots_on_imported_history(registers, + history): + """(j), RE: D18's agreement on imported history (Y:5141; lane 3's ruling, + #165 6833678789). The primary program (`RULE6_AWK` with + `RULE6_EXPIRED_AWK`) and `main_slots` show no difference, and lane 2's + own check of F13's condition (`f13_findings`) names nothing, on today's + history (no `LANDING EXPIRED`), on a re-import that holds a + primary-written `LANDING EXPIRED`, and on one typed in files mode that + meets F13's condition by its own UTC and its `LANDING`'s and carries the + form's word clause. Each of the four others is a finding, and the case + shows it: one typed 10 minutes after its `LANDING`, one with no word + clause, and one naming another PR, each by the test's own check of F13's + condition, which names the line, since both readers agree on a typed + line; and one whose holder is in another case, by the readers' + difference, since `main_slots` closes it and the awk does not.""" + lines, agree, finding = HISTORIES[history] + reg = registers("tmpl") + clock = reg.clock() + shifted = [_shift(text, clock) for text in lines] + files = register_files(shifted) + body = files["lanes/LANES.md"] + first = body.split("\n").index(shifted[0]) + 1 + rows = line_rows(shifted, clock, {ALIAS: KEY, KEY.lower(): KEY}, first_line=first) + reg.import_files({p: t for p, t in files.items() if RENDER_SET.match(p)}, rows) + reg.to_primary() + program = primary_program_rows(body, {ALIAS: KEY, KEY.lower(): KEY}) + slots = reg.open_landings() + if agree: + assert program == slots, f"[{history}] the awk {program} and main_slots {slots} differ" + else: + assert program != slots, ( + f"[{history}] the awk and main_slots agree on a history that is a finding: " + f"{program}") + findings = f13_findings(rows) + if finding is None: + assert findings == {}, ( + f"[{history}] lane 2's check of F13's condition names a line it should not: {findings}") + else: + assert list(findings) == [shifted[-1]], ( + f"[{history}] lane 2's check of F13's condition does not name the typed line, and " + f"only it: {findings}") + assert any(finding in why for why in findings[shifted[-1]]), ( + f"[{history}] the check does not find {finding!r}: {findings}") + + +def test_a_landed_between_the_forms_snapshot_and_commit_leaves_the_retry_nothing_to_release( + registers, tmp_path): + """(i), RE: lane B's `LANDED` commits between the form's snapshot and its + commit, staged by the shim's `hold` on the commit call, not by timing. The + commit fails with LR001, the retry exits 2 with "no open `LANDING`", and + nothing of the form's is written.""" + reg = registers("tmpl_imported") + reg.to_primary() + clock = reg.clock() + stale = _shift(landing(minutes=31), clock) + start = int(reg.rows("SELECT count(*) AS n FROM doc_lines WHERE path = 'lanes/LANES.md'")[0]["n"]) + + def append(lane: str, text: str) -> int: + before = reg.rows("SELECT text FROM doc_lines WHERE path = 'lanes/LANES.md' ORDER BY line_no") + lines = [r["text"] for r in before] + [text] + rendered = ("\n".join(lines) + "\n").encode("utf-8") + return reg.commit(reg.entry( + "write", "append-line", lane, + journal={"args_sha256": hashlib.sha256(text.encode()).hexdigest()}, + edits=[{"ord": 1, "op": "append", "path": "lanes/LANES.md", "new_text": text}], + files=[{"path": "lanes/LANES.md", "present": True, "final_newline": True, + "sha256": hashlib.sha256(rendered).hexdigest()}], + register_lines=line_rows([text], clock, {ALIAS: KEY, KEY.lower(): KEY}, + first_line=len(lines)))) + + append(HOLDER, stale) + fakebin = tmp_path / "shimbin" + fakebin.mkdir() + (fakebin / "psql").write_text(PSQL_SHIM, encoding="utf-8") + (fakebin / "psql").chmod(0o755) + fifo = tmp_path / "hold.fifo" + os.mkfifo(fifo) + (fakebin / PSQL_SHIM_CONTROL).write_text(json.dumps({ + "psql": reg.db.psql_bin, + "arms": [{"mode": "hold", "match": "commit_write", "call": 1, "fifo": str(fifo)}]}), + encoding="utf-8") + origin, checkout, env = _workspace(tmp_path / "ws", fakebin, register_files([stale])) + bindir = tmp_path / "bin" + flipped_copy(LANES_INDEX, bindir, True) + for name in ("lanes-edit.sh", "repos.tsv", "lane-start"): + shutil.copy2(str(REPO / name), str(bindir / name)) + conf = tmp_path / "lanes-index.conf" + conf.write_text(f"mode=primary\nregister_url={reg.db.url(WRITER_LOGIN)}\n" + f"reader_url={reg.db.url()}\n", encoding="utf-8") + conf.chmod(0o600) + env.update(LANES_INDEX_CONFIG=str(conf), LANES_LANE=WRITER, LANES_SESSION=SID_W) + env.pop("LANES_INDEX", None) + proc = subprocess.Popen(["bash", str(bindir / "lanes-edit.sh"), *form()], cwd=str(checkout), + env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + encoding="utf-8", stdin=subprocess.DEVNULL) + released = {} + + def release() -> None: + with open(fifo, "w") as held: + released["seq"] = append(HOLDER, _shift(landed(minutes=1), clock)) + held.write("go\n") + + gate = threading.Thread(target=release, daemon=True) + gate.start() + out, err = proc.communicate(timeout=120) + gate.join(timeout=60) + assert "seq" in released, "the form's commit call never reached the shim's hold" + assert proc.returncode == 2, f"the retry exited {proc.returncode}, not 2: {err[-800:]}" + assert "no open" in err and "LANDING" in err, f"stderr does not say no open LANDING: {err!r}" + assert reg.head() == released["seq"], "something was written after lane B's LANDED" + # `register_lines` is keyed by `line_id`, and the path and the line's place + # are `doc_lines`' (Y:1254; `lanes-index:7103`). + kinds = reg.rows("SELECT r.kind FROM register_lines r JOIN doc_lines d USING (line_id) " + f"WHERE d.path = 'lanes/LANES.md' AND d.line_no > {start} ORDER BY d.line_no") + assert [r["kind"] for r in kinds] == ["LANDING", "LANDED"], kinds + + +# ============================================================ T112's AT-F13 case (T253b) +# +# R-F10-34 (lane 3, #165 6755386771, reading 7; B10 tasks:413, :429; +# `PLACEMENT.md` section 2 as `PLACEMENT-2.md` amends it), with lane 3's point 4 +# (#165 6768050756): the fixture is accepted, and the alias is also listed in the +# case's own shipped table, through `LANES_REPOS_TSV_SHIPPED` (lane 1, #165 +# 6766921904, point 2), with a third key, so that one case proves both halves of +# Rule 6's order: the per-wip table overrides the shipped one, and within it the +# last row wins. Each table read alone, or the per-wip table's first row +# (`alias_lookup`'s, `lanes-edit.sh:3436-3446` at `39839dc`), gives another key. + +#: The alias, and its three keys: the shipped table's, the per-wip table's +#: first row's, and Rule 6's (the per-wip table's last row). +STALE_ALIAS = "r7x" +SHIPPED_KEY, FIRST_ROW_KEY, RULE6_KEY = "opensoft/r7-shipped", "opensoft/r7-first", "opensoft/r7-rule6" +SHIPPED_TSV = f"# alias\towner/repo\n{STALE_ALIAS}\t{SHIPPED_KEY}\n" +PER_WIP_TSV = (f"# alias\towner/repo\n{STALE_ALIAS}\t{FIRST_ROW_KEY}\n" + f"{STALE_ALIAS}\t{RULE6_KEY}\n") + + +def git_blob_id(data: bytes) -> str: + """The blob id git gives `data`, as `changes.tsv` names it.""" + return hashlib.sha1(b"blob %d\0" % len(data) + data).hexdigest() + + +def test_register_commit_expires_an_imported_stale_landing_by_the_shipped_then_per_wip_repo_key( + registers, tmp_path): + """T112's AT-F13 case, RE (R-F10-34): a clone of `tmpl`, brought to + `primary` by AT-LR006's route, whose `import` entry loads a `LANDING` + older than Rule 6's 30 minutes, for one PR, on a repository the line + spells by an alias. The case's per-wip `lanes/repos.tsv` lists the alias + twice, the earlier row naming another key, and its own shipped table + (`LANES_REPOS_TSV_SHIPPED`) lists it with a third key; the import's row + carries Rule 6's key, the last row's (`rule6_aliases`, + `lanes-edit.sh:6938` at code `39839dc`). Then `lanes-index register + commit`, from T203's flipped copy, on an attempt directory in T101's + format built on `register snapshot --tree`, appends a `LANDING EXPIRED` + for that PR and spelling in T223's line form. It exits 0 with `committed + <seq>`, with no LR005 `expired-none`, and the `LANDING`'s slot in + `main_slots` is freed for Rule 6's key (Y:1989). It runs no + `append-line`, so it needs no L4-B10. It fails until T107, T227's + `tmpl`, T111 and T112 land (L1-A6, L1-A9, L1-A10; T227).""" + reg = registers("tmpl") + clock = reg.clock() + stale_utc = utc_of(clock - 45 * 60) + stale = (f"LANDING {EM} lane {HOLDER}, session {SID_H}@{WS}, {stale_utc}, PR #{PR} into " + f"{STALE_ALIAS} main") + files = register_files([stale], repos=PER_WIP_TSV) + body = files["lanes/LANES.md"] + line_no = body.split("\n").index(stale) + 1 + rows = line_rows([stale], clock, {STALE_ALIAS: RULE6_KEY}, first_line=line_no) + assert [r["repo_key"] for r in rows] == [RULE6_KEY], rows + reg.import_files({p: t for p, t in files.items() if RENDER_SET.match(p)}, rows) + reg.to_primary() + taken = (HOLDER, str(PR), RULE6_KEY) + assert taken in reg.open_landings(), ( + f"the import's LANDING does not take main for Rule 6's key: {reg.open_landings()}") + + # THE WORKSTATION: the checkout's origin carries the per-wip table, the + # shipped table is the case's own, and `lanes-index` is T203's flipped copy. + fakebin = tmp_path / "fakebin" + origin, checkout, env = _workspace(tmp_path / "ws", fakebin, files) + shipped = tmp_path / "shipped-repos.tsv" + shipped.write_text(SHIPPED_TSV, encoding="utf-8") + copy = flipped_copy(LANES_INDEX, tmp_path / "bin", True) + conf = tmp_path / "lanes-index.conf" + conf.write_text(f"mode=primary\nregister_url={reg.db.url(WRITER_LOGIN)}\n" + f"reader_url={reg.db.url()}\n", encoding="utf-8") + conf.chmod(0o600) + env.update(LANES_INDEX_CONFIG=str(conf), LANES_REPOS_TSV_SHIPPED=str(shipped), + PATH=str(reg.cluster.bindir) + os.pathsep + env["PATH"]) + env.pop("LANES_INDEX", None) + + def index(*args: str) -> subprocess.CompletedProcess: + return subprocess.run([sys.executable, str(copy), *args], capture_output=True, + encoding="utf-8", errors="replace", env=env, timeout=120, + cwd=str(checkout), check=False, stdin=subprocess.DEVNULL) + + # THE ATTEMPT DIRECTORY (T101's format, contract section 3.3), on the + # scratch tree `register snapshot --tree` builds at `n`. + released = (f"LANDING EXPIRED {EM} lane {OTHER} {EM} PR #{PR} into {STALE_ALIAS} main " + f"for lane {HOLDER} {EM} {utc_of(clock)}") + args_sha = hashlib.sha256(f"{OTHER}\0append-line\0{released}".encode("utf-8")).hexdigest() + attempt = tmp_path / "attempt" + attempt.mkdir() + snap = index("register", "snapshot", "--write-id", "new", "--lane", OTHER, "--verb", + "append-line", "--args-sha256", args_sha, "--tree", str(attempt / "tree"), + "--checkout", str(checkout)) + assert snap.returncode == 0, f"register snapshot exited {snap.returncode}: {snap.stderr}" + keys = dict(line.partition("=")[::2] for line in snap.stdout.splitlines() if "=" in line) + (attempt / "snapshot").write_text(snap.stdout, encoding="utf-8") + tree_head = git(attempt / "tree", "rev-parse", "HEAD:lanes/LANES.md", env=env).strip() + base = git(attempt / "tree", "cat-file", "blob", tree_head, env=env).encode("utf-8") + image = base + released.encode("utf-8") + b"\n" + (attempt / "images" / "lanes").mkdir(parents=True) + (attempt / "images" / "lanes" / "LANES.md").write_bytes(image) + (attempt / "changes.tsv").write_text( + f"M\tlanes/LANES.md\t{tree_head}\t{git_blob_id(image)}\n", encoding="utf-8") + (attempt / "files").write_text( + f"lanes/LANES.md\t1\t{hashlib.sha256(image).hexdigest()}\n", encoding="utf-8") + (attempt / "msg").write_text(f"LANES({OTHER}@{WS}): append line {EM} T253's case\n", + encoding="utf-8") + (attempt / "author").write_text(f"{AUTHOR}\n", encoding="utf-8") + (attempt / "not_after").write_text(keys["not_after"] + "\n", encoding="utf-8") + + done = index("register", "commit", "--write-id", keys["write_id"], "--generation", + keys["generation"], "--lane", OTHER, "--verb", "append-line", "--args-sha256", + args_sha, "--workstation", WS, str(attempt)) + assert "expired-none" not in done.stderr, ( + f"register commit met LR005 expired-none: the LANDING EXPIRED's repo_key is not Rule " + f"6's (shipped, then per-wip, the last row winning): {done.stderr}") + assert done.returncode == 0, f"register commit exited {done.returncode}: {done.stderr}" + assert re.fullmatch(r"committed [0-9]+\n", done.stdout), done.stdout + assert taken not in reg.open_landings(), ( + f"main_slots still holds the LANDING for {RULE6_KEY}: {reg.open_landings()}") + + + +# ============================================================ (h), T279's +# +# AT-F13 (h), RE, end to end, with its rollback in phase G (B15 tasks:2557, +# T279's "AT-F13 (h): a `LANDING EXPIRED` on primary frees `main` and +# `who_landing` until a rollback to files"). Its fixture is (h) to (j)'s +# (TP's AT-F13 "Fixture"): `tmpl_imported` brought to `primary` with the +# marker `present`, and lane B's `LANDING` dated 31 minutes or more back. + + +def _commit_line(reg: Register, clock: int, lane: str, text: str) -> int: + """`text` appended to `lanes/LANES.md` by one commit call as lane `lane`, + in (i)'s form: the entry an `append-line` would send, with the line's + `register_lines` row by the checkout's own classifier. The seq it made.""" + before = reg.rows("SELECT text FROM doc_lines WHERE path = 'lanes/LANES.md' ORDER BY line_no") + lines = [r["text"] for r in before] + [text] + rendered = ("\n".join(lines) + "\n").encode("utf-8") + return reg.commit(reg.entry( + "write", "append-line", lane, + journal={"args_sha256": hashlib.sha256(text.encode()).hexdigest()}, + edits=[{"ord": 1, "op": "append", "path": "lanes/LANES.md", "new_text": text}], + files=[{"path": "lanes/LANES.md", "present": True, "final_newline": True, + "sha256": hashlib.sha256(rendered).hexdigest()}], + register_lines=line_rows([text], clock, {ALIAS: KEY, KEY.lower(): KEY}, + first_line=len(lines)))) + + +def _to_primary_with_the_marker(reg: Register, checkout: Path, env: dict) -> int: + """AT-LR006's route, as `Register.to_primary` takes it, with the marker + on origin as T327's push leaves it: the `cutover` entry, then a commit on + origin's `main` that adds `lanes/STORE` with the entry's text and + carries its `Register-Seq`, then `record_marker` naming that commit. + Returns the entry's seq.""" + store = "store=primary\n" + cut = reg.commit(reg.entry("cutover", "cutover", OPERATOR, + edits=[{"ord": 1, "op": "create", "path": "lanes/STORE"}, + {"ord": 2, "op": "append", "path": "lanes/STORE", + "new_text": "store=primary"}], + files=[{"path": "lanes/STORE", "present": True, + "final_newline": True, + "sha256": hashlib.sha256(store.encode()).hexdigest()}])) + (checkout / "lanes" / "STORE").write_bytes(store.encode("utf-8")) + git(checkout, "add", "lanes/STORE", env=env) + git(checkout, "commit", "-q", "-m", f"cutover: the marker (T279's estate)\n\nRegister-Seq: {cut}", + env=env) + git(checkout, "push", "-q", "origin", "HEAD:main", env=env) + marker = git(checkout, "rev-parse", "HEAD", env=env).strip() + version = reg.rows("SELECT version FROM schema_version")[0]["version"] + marked = reg.call(f"SELECT {SCHEMA}.record_marker({version}, {cut}, '{marker}', '{WS}');\n") + assert (marked.returncode, marked.stdout.strip()) == (0, "present"), marked.stderr + return cut + + +def test_a_landing_expired_on_primary_frees_main_and_who_landing_until_a_rollback_to_files( + registers, pg_cluster, tmp_path): + """(h), RE, end to end (TP's AT-F13 oracle (h)). On a clone of + `tmpl_imported` brought to `primary` with the marker `present`, lane B's + (`HOLDER`'s) `LANDING`, 31 minutes back by the database's clock, is + committed; then lane A's (`WRITER`'s) form, `append-line + --landing-expired`, commits over it and exits 0. Then: + - `main_slots` no longer shows lane B's `LANDING` as a take for its + `repo_key`; + - no other take on it being open, a later `LANDING` by lane C (`OTHER`) + is accepted, not refused by D18; + - on primary `who --landing` no longer lists lane B's `LANDING`, and + lists lane C's; + - after a rollback to files, `who --landing` lists lane B's `LANDING` + again, marked STALE: off primary Rule 6's program is the pin, with no + expired branch. + + READINGS: + - "THE MARKER `present`" is read as both its halves: the switch's + marker `present`, and `lanes/STORE` on origin. So the workstation's + origin is a copy of the repository `tmpl_imported` was imported from + (`pg_cluster.imported_register`, whose C the import's entry names), + and AT-LR006's route pushes the cutover's marker commit there, with + the entry's `Register-Seq`, before `record_marker` names it, as T327's + push would. A rollback needs that origin: it renders onto the mirror + of this database and removes `lanes/STORE` from it (T326). + - Lane B's and lane C's `LANDING`s are committed as (i) commits its + lines: one commit call each, the entry `append-line` would send. + - "A ROLLBACK TO FILES" is `lanes-index rollback` as the operator lane, + through that lane's own register checkout, `<W>-lanes/<operator>`, + which `LANES_REPO` names, never W (D24); then `set-mode index` on this + workstation, as Brett runs it at the rollback's step 5 (operations.md + 2.3), so `who --landing` reads the files: origin's `main` as the + rollback rendered it, after the harness's fetch of W (lane 3's ruling + (a), #165 6833830078), since the rollback pushed from the operator + lane's checkout. + + Fails until lane 1's T107, T111 and T112 (F13 and D18 in the commit), + lane 4's T415 and T425 (L4-B10: the form and `RULE6_EXPIRED_AWK`), lane + 5's T504 (the prefetch), and the rollback's T304 and T326 (L1-A18 for + its declaration).""" + reg = registers("tmpl_imported") + source = pg_cluster.imported_register + assert source is not None, f"no repository for tmpl_imported: {pg_cluster.imported_problem}" + origin, checkout, env = _workspace(tmp_path / "ws", tmp_path / "fakebin", {}, + source=source.origin, lanes=()) + _to_primary_with_the_marker(reg, checkout, env) + _lane_checkouts(origin, checkout, env) # after the marker's push, at W's commit (119) + clock = reg.clock() + _commit_line(reg, clock, HOLDER, _shift(landing(minutes=31), clock)) + taken = (HOLDER, str(PR), KEY) + assert taken in reg.open_landings(), ( + f"lane B's LANDING does not take main for {KEY}: {reg.open_landings()}") + + bindir = tmp_path / "bin" + copy = flipped_copy(LANES_INDEX, bindir, True) + for name in ("lanes-edit.sh", "repos.tsv", "lane-start"): + shutil.copy2(str(REPO / name), str(bindir / name)) + conf = tmp_path / "conf" / "lanes-index.conf" + conf.parent.mkdir() + conf.write_text(f"mode=primary\nregister_url={reg.db.url(WRITER_LOGIN)}\n" + f"reader_url={reg.db.url()}\nregister_label={pg_cluster.label}\n", + encoding="utf-8") + conf.chmod(0o600) + env.update(LANES_INDEX_CONFIG=str(conf), PATH=str(reg.cluster.bindir) + os.pathsep + env["PATH"]) + env.pop("LANES_INDEX", None) + + def run(argv: list, lane: str = None, repo: Path = None) -> subprocess.CompletedProcess: + child = dict(env) + if lane: + child.update(LANES_LANE=lane, LANES_SESSION=SESSIONS.get(lane, SID_W)) + if repo is not None: + child["LANES_REPO"] = str(repo) + return subprocess.run(argv, capture_output=True, encoding="utf-8", errors="replace", + env=child, timeout=300, cwd=str(checkout), check=False, + stdin=subprocess.DEVNULL) + + def who() -> list: + proc = run(["bash", str(bindir / "lanes-edit.sh"), "who", "--landing", KEY]) + assert proc.returncode == 0, f"who --landing exited {proc.returncode}: {proc.stderr[-800:]}" + return [line for line in proc.stdout.splitlines() if line.startswith("LANDING ")] + + released = run(["bash", str(bindir / "lanes-edit.sh"), *form()], lane=WRITER) + assert released.returncode == 0, ( + f"lane A's form exited {released.returncode} (L4-B10, T425's form; T415): " + f"{released.stderr[-800:]}") + assert taken not in reg.open_landings(), ( + f"main_slots still holds lane B's LANDING for {KEY}: {reg.open_landings()}") + try: + _commit_line(reg, clock, OTHER, _shift(landing(lane=OTHER, minutes=1), clock)) + except AssertionError as exc: + raise AssertionError(f"lane C's later LANDING on {KEY} was refused, though no take on " + f"it is open (D18): {exc}") from None + assert (OTHER, str(PR), KEY) in reg.open_landings(), reg.open_landings() + rows = who() + assert not any(f" lane {HOLDER}," in row for row in rows), ( + f"on primary who --landing still lists lane B's released LANDING (T425's " + f"RULE6_EXPIRED_AWK): {rows}") + assert any(f" lane {OTHER}," in row for row in rows), ( + f"on primary who --landing does not list lane C's LANDING: {rows}") + + # THE OPERATOR LANE'S OWN REGISTER CHECKOUT (D24; Amendment 23 S2 item 3): + # the rollback reads origin through it, never W, and refuses 2 where + # `LANES_REPO` names W itself (`lanes-index:19061-19106` at pair-m33a + # `8ba10b4e`, `lane_own_checkout`). `<W>-lanes/<operator>`, a clone of + # origin made after the case's last write, as T272d makes the cutover + # module's and T254s the guard module's; `LANES_REPO` names it for the + # rollback alone. + (operator_checkout,) = _lane_checkouts(origin, checkout, env, lanes=(OPERATOR,)) + rolled = run([sys.executable, str(copy), "rollback"], lane=OPERATOR, repo=operator_checkout) + assert rolled.returncode == 0, ( + f"the rollback to files exited {rolled.returncode} (T304, T326): {rolled.stderr[-800:]}") + flipped = run([sys.executable, str(copy), "set-mode", "index"]) + assert flipped.returncode == 0, f"set-mode index exited {flipped.returncode}: {flipped.stderr}" + # THE READER'S FETCH OF W (lane 3's ruling (a), #165 6833830078; T272e's + # `fetch_w`): the rollback pushed from the operator lane's checkout, so + # W's `origin/main`, which `who` reads off primary (`register_text`) and + # whose `lanes/STORE` F17 checks as last fetched, moves only by a fetch. + git(checkout, "fetch", "-q", "origin", "main", env=env) + rows = who() + held = [row for row in rows if f" lane {HOLDER}," in row] + assert held and all(row.endswith(STALE_MARK) for row in held), ( + f"after the rollback to files who --landing does not list lane B's LANDING again, " + f"marked STALE: {rows}") diff --git a/tests/test_sql_register_managed.py b/tests/test_sql_register_managed.py new file mode 100644 index 00000000..8d416798 --- /dev/null +++ b/tests/test_sql_register_managed.py @@ -0,0 +1,3021 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Feature 007's AT-LRMPG, a managed PostgreSQL: its phase-N cases (T224; +FR-009, FR-053, FR-054, FR-055, FR-059) and its phase-W cases (T258; FR-009, +FR-054, FR-059) (opensoft/openRepoTools#165). + +The test plan's thirteen phase-N names, byte for byte (AT-LRMPG, "Tests."), +and lane 1's two new since v3f, `dump_restore_privileges` (L1-2, T109's option +(a)) and `rotate_dump_job` (L1-3, T110's `rotate --dump-job`): 15 tests. The +phase-W cases, the logins' writes and reads through the flipped copy, are +T258's five, in the last section, "phase W (T258)", which says how they run. + +THE SERVER (X, `97147aa8`, kept at Y): the register runs on CNPG, so the +admin of every case stands for the database's owner as CNPG's `initdb` makes +it, `lanes_register_admin` (lane 1's T109 name), `LOGIN CREATEROLE CREATEDB` +and no `SUPERUSER`. The cluster's own superuser stands for the provider: it +makes that admin and nothing of the register. One admin service (R-P41, lane +3's ruling on open point 41): the admin creates the register's database +first, as his own act, through his own maintenance connection, so he owns +it; every `lanes-index` step then runs through ONE service in the test's own +`$HOME/.pg_service.conf`, which names that database. `lanes-index` never +picks a database. + +THE FIXTURE (AT-LRMPG, "Fixture"). Each engine case runs on a +`stoppable_cluster` of its own, since roles are global to a cluster and no +test changes a role on the session cluster; with no engine it skips with +T205's banner. Its `pg_hba.conf` takes `scram-sha-256` on the socket for +every login but the superuser and the admin, and it logs as section 5.6's +counting cluster does (`log_connections`, `log_statement=all`, each line +prefixed with its backend's pid). `bootstrap` runs with `--no-passwords` +where no password is under test, and under a pty where a password line is; +every `lanes-index login` runs under a pty, since it refuses off a terminal. +Each password line the run prints goes into a 0600 file under the test's +`$HOME/passfiles` (`passfiles-new` after a restore), which a login's +`PGPASSFILE` names. A second server, for a restore, is a `pgcluster.Cluster` +the test starts itself and destroys at its teardown. + +CHECK 11 runs on section 5.6's TLS cluster, T229's `tls_cluster`, which +`tests/pgcluster.py` gives since this line merged line FX at T229d: each id +skips with T205's banner where there is no engine. What this module reads +of that fixture, from F12b's T229 text and not from a contract, is +`TlsEnvironment`'s docstring. + +THE NO-ENGINE CASE is `login`'s refusals: each is refused before any +connection, so the register's fake `psql` (T203) stands in for the server and +its log shows that nothing was made. Its control, a good name under the pty, +reaches the fake, so each refusal is the condition's and never a verb this +build lacks. + +READ FROM LANE 1'S CODE, NOT A CONTRACT (T109, T110 and T119 at +`l1-007-R-merge5`, `1511fa7f`): each object line is `<what>: created` or +`<what>: unchanged`, with a detail in brackets after it; a password-file line +is `*:*:<database>:<login>:<password>`; `login`'s argv is `login add|rotate +<engineer>|--dump-job --admin-service <service>`; the floors as +`pg_roles.rolconfig` holds them; and `ready`'s line form, `check <n>: ok` or +`check <n>: FAIL: <reason>`, as T218b reads it. + +NO PASSWORD IN A FAILURE (T224j, T224k; Codex's review of P09 at +`f4f0ebce`, BLOCKING 3): `login add`'s, `login rotate`'s and `bootstrap`'s +stdout carry password-file lines, so `_said` and `_passwords` hide each +line's password. This module is also PYTEST_DONT_REWRITE: pytest's +assertion rewriting would add each operand's value to a failure's message, +a `CompletedProcess` with that stdout or a dict of password-file lines +among them, so an assertion here reports its own message and nothing else. +""" + +from __future__ import annotations + +import atexit +import contextlib +import errno +import hashlib +import itertools +import json +import os +import re +import select +import shutil +import signal +import stat +import subprocess +import sys +import tempfile +import threading +import time +import uuid +from pathlib import Path +from urllib.parse import quote + +import pytest + +from conftest import REPO, WINDOWS_SKIP +from sql_register_helpers import (LANES_INDEX, PSQL_SHIM, PSQL_SHIM_CONTROL, PSQL_SHIM_ENDS, + PSQL_SHIM_LOG, REGISTER_FAKE_PSQL, RENDER_SET_PATH, flipped_copy, + guard_strip_env) +from test_sql_register_bounds import _said_safely # the one helper for a failure's output (T258l) +from test_sql_register_bounds import _whole # a number from output, quoting none of it (T258n) +from test_sql_register_bounds import _reported # pytest's own report of a failure (T258r) + +pytestmark = [WINDOWS_SKIP] + +#: THE LANDING GATE'S TABLE (T280; task sets version 12b's rule 11, +#: opensoft/openRepoTools#165 6877673742), TEMPORARY: T281 removes it in the +#: last set. `tests/sql_register_gate.py` reads it: in a code pull request's +#: full CI, each id of a function below is skipped until every task its row +#: names has landed, and the skip names them. The rows are T224's Order +#: (tasks:2156), T230's (tasks:2220, with its As built at :2219) and T258's +#: (tasks:2464), tasks.md at lane 3's commit 17 `204145ae`. No task is common +#: to all of its functions, so there is no "*" row. T224j's, T224n's, T224o's, +#: T224p's, T258e's, T258f's, T258g's and T258h's cases, which run on synthetic text +#: and stand-ins with no database, have no row: they run ungated. +SQL_REGISTER_GATE_TABLE = { + # T224: until L1-A7 (T109), L1-A8 (T110), L1-A17 (T119, T120) and T229. + # Lane 1's two cases' T109 and T110, and `[in-recovery]`'s T229, are in + # that list. T230's three check-11 ids keep check 11's row, which holds + # their T119 (L1-A17). + "test_bootstrap_without_a_superuser_runs_twice_with_one_catalog": + ("T109", "T110", "T119", "T120", "T229"), + "test_bootstrap_refuses_a_database_its_admin_does_not_own": + ("T109", "T110", "T119", "T120", "T229"), + "test_login_add_makes_an_engineers_two_logins_with_their_floors_and_prints_their_lines_once": + ("T109", "T110", "T119", "T120", "T229"), + "test_login_add_run_again_puts_back_a_lost_membership_and_changes_nothing_else": + ("T109", "T110", "T119", "T120", "T229"), + "test_a_member_made_without_the_login_step_carries_no_floor_and_fails_ready_check_12": + ("T109", "T110", "T119", "T120", "T229"), + "test_ready_check_12_passes_the_logins_the_step_made": + ("T109", "T110", "T119", "T120", "T229"), + "test_login_rotate_keeps_an_open_session_and_refuses_the_old_password": + ("T109", "T110", "T119", "T120", "T229"), + "test_login_refuses_a_bad_name_a_connection_string_and_a_pipe": + ("T109", "T110", "T119", "T120", "T229"), + "test_an_open_session_gets_42501_between_the_revokes_steps_then_57p01": + ("T109", "T110", "T119", "T120", "T229"), + "test_the_reader_login_dumps_both_schemas_and_still_cannot_write": + ("T109", "T110", "T119", "T120", "T229"), + "test_a_restore_from_the_dump_equals_its_source_with_new_passwords": + ("T109", "T110", "T119", "T120", "T229"), + "test_a_restore_from_the_providers_copy_keeps_the_roles_and_takes_new_passwords": + ("T109", "T110", "T119", "T120", "T229"), + "test_ready_check_11_needs_tls_and_the_primary": + ("T109", "T110", "T119", "T120", "T229"), + "test_dump_restore_privileges_hold_after_roles_only_the_restore_and_bootstrap": + ("T109", "T110", "T119", "T120", "T229"), + "test_rotate_dump_job_changes_only_the_dump_logins_password": + ("T109", "T110", "T119", "T120", "T229"), + # T230: `tls_at_load` until L1-A3 (T104); its `[for-guard]` also until + # T113, which builds the `register read` it needs (tasks:2219), and its + # `[journal-write-id]` until T114 (L1-A12), which builds the `journal` it + # runs (lane 1, opensoft/openRepoTools#165 6899134636; T224i). + "test_tls_at_load_refuses_a_url_off_loopback_without_verify_full_and_a_root_file": + ("T104",), + "test_tls_at_load_refuses_a_url_off_loopback_without_verify_full_and_a_root_file[for-guard]": + ("T104", "T113"), + "test_tls_at_load_refuses_a_url_off_loopback_without_verify_full_and_a_root_file[journal-write-id]": + ("T104", "T114"), + # T258: until L1-A8 (T110), L4-B3 (T413, T414, T415) and L4-B5 (T417). + "test_two_writer_logins_write_alike_and_the_log_names_each": + ("T110", "T413", "T414", "T415", "T417"), + "test_a_revoked_login_is_refused_69_and_writes_nothing": + ("T110", "T413", "T414", "T415", "T417"), + "test_a_write_cut_by_a_revoke_mid_commit_is_in_doubt_and_ends_3_with_nothing_written": + ("T110", "T413", "T414", "T415", "T417"), + "test_reader_url_takes_target_session_attrs_primary_not_read_write": + ("T110", "T413", "T414", "T415", "T417"), + "test_after_login_rotate_the_old_password_files_write_exits_69_and_the_new_lines_commit_once": + ("T110", "T413", "T414", "T415", "T417"), +} + +#: The admin, as CNPG's `initdb` makes the database's owner (lane 1's T109 +#: name, opsXfactory-6's; `[X: hosting]`). +ADMIN = "lanes_register_admin" + +#: Design.md section 1.4's roles. +OWNER, WRITER, READER = "lanes_register_owner", "lanes_register_writer", "lanes_register_reader" +INDEXER, DUMP = "lanes_indexer", "lanes_register_dump" +REGISTER, INDEX = "lanes_register", "lanes_index" + +#: The bootstrap's inputs. +LABEL, REPOSITORY, LANE = "register-t224", "opensoft/t224-workspace", "t224-managed" + +#: Each half's floors as `pg_roles.rolconfig` holds them (the login step, +#: Y:2288-2300), and as `SHOW` prints them in a session of that login. +ROLCONFIG = {"w": ["lock_timeout=2000ms", "statement_timeout=5s", + "idle_in_transaction_session_timeout=5s"], + "r": ["default_transaction_read_only=on", "lock_timeout=1000ms", + "statement_timeout=1500ms"]} +SHOWN = {"w": {"lock_timeout": "2s", "statement_timeout": "5s", + "idle_in_transaction_session_timeout": "5s"}, + "r": {"default_transaction_read_only": "on", "lock_timeout": "1s", + "statement_timeout": "1500ms"}} +#: What a member made without the login step shows (lane 1's run). +NO_FLOORS = {"lock_timeout": "0", "statement_timeout": "0", + "idle_in_transaction_session_timeout": "0", "default_transaction_read_only": "off"} + +#: One object line of `bootstrap` or `login` (lane 1's `_bootstrap_say`). +OBJECT_LINE = re.compile(r"^(?P<what>[^\n]+?): (?P<state>created|unchanged)(?: \([^\n]*\))?$", re.M) +#: One password-file line (lane 1's `_register_pgpass_line`). +PASS_LINE = re.compile(r"^\*:\*:(?P<db>[^:\n]+):(?P<login>[^:\n]+):(?P<password>[^:\s]+)$", re.M) +#: One of `ready`'s check lines (T119's line form). +CHECK_LINE = re.compile(r"^check (\d+): (ok|FAIL)\b:?[ \t]*(.*)$", re.M) + +#: The three database-level statements `--roles-only` runs (T109's option (a)). +DB_LEVEL = ("REVOKE ALL FROM PUBLIC", "GRANT CONNECT", "REVOKE EXECUTE ON FUNCTIONS FROM PUBLIC") + +#: O2's dump command, run as the dump job's login (6722541787). +DUMP_COMMAND = ("umask 077 && pg_dump --no-password --schema=lanes_register " + "--schema=lanes_index --format=custom --file={file}") + +#: The import entry's fields (T222f's form, AT-LR006's first step). +WS, AUTHOR, OPERATOR = "ws-t224", "T224 Fixture <t224@example.invalid>", "operator-t224" +MARKER_COMMIT = "c0ffee" + "4" * 34 + + +def _said(proc: subprocess.CompletedProcess) -> str: + """`proc` for a failure's message: its exit, each stream's counts and the + WARNING lines that match a template, through bounds' one helper, + `_said_safely` (T258l; lane 3's ruling 6946445277 on lane 2's pre-review + RV9-36 of P09 at `2407ea06`, S2). Before T258l it showed both streams, + each password-file line's password hidden (`pgcluster._masked`; T224j), + and every other line whole. The failure messages call `_said_safely` + themselves; this name stays for T224j's case.""" + return _said_safely(proc) + + +def _unverified(roles: dict) -> dict: + """`Managed.role`'s dicts by login, for a failure's message, each without + its `verifier`: a SCRAM verifier is derived from the login's password, so + no message shows one (T224m).""" + return {login: {key: value for key, value in role.items() if key != "verifier"} + for login, role in roles.items()} + + +def _private(path: Path, text: str) -> Path: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8") + path.chmod(0o600) + return path + + +#: Each bounded step of ending a process this module started: `_end_process`'s +#: wait for its exit after TERM and its reap after KILL, and the join of a phase-W +#: writer's reader after them (T258e). +END_S = 10.0 + +#: How long a phase-W writer's reader waits on its pipes at a time, so a cut +#: reaches it (T258h). +READ_POLL_S = 0.1 + + +def _end_process(proc: subprocess.Popen, *, group: bool, wait: float = 10.0) -> None: + """`proc` ended and reaped, and never signalled once its pid may be another + process's (T258e; Codex's review of P09 at `21dd3642`, SHOULD 6 in lane 3's + numbering, by its BLOCKING's identity-safe form, as the bounds and measure + modules' own copies have it). A process already reaped, `returncode` set, + gets no signal. Otherwise each signal is sent while it is still unreaped, so + its pid, and with `group` the id of the process group `start_new_session=True` + made it lead, are still its own: TERM; up to `wait` s for its exit, watched by + `os.waitid(..., WNOWAIT)`, which does not reap it; KILL; then one reap, + `proc.wait(wait)`, whose `TimeoutExpired` is raised, not suppressed. A reap + by anything else meanwhile raises `ChildProcessError` from `os.waitid`, + before the KILL. With `group`, TERM and KILL go to the group, so a child it + started gets them too.""" + if proc.returncode is not None: + return + _signal_unreaped(proc, group=group, wait=wait) + proc.wait(wait) + + +def _signal_unreaped(proc: subprocess.Popen, *, group: bool, wait: float) -> None: + """`_end_process`'s signals, and not its reap (T258f): TERM; up to `wait` s + for `proc`'s exit, watched by `os.waitid(..., WNOWAIT)`, which leaves it + unreaped; KILL. `proc` is unreaped throughout, so its pid, and with `group` + the id of the group it leads, are its own for each signal. Its caller reaps + it after, as `W258Writer` does once its reader is joined and its pipes are + closed.""" + def send(sig: int) -> None: + with contextlib.suppress(ProcessLookupError, PermissionError): + (os.killpg if group else os.kill)(proc.pid, sig) + send(signal.SIGTERM) + end = time.monotonic() + wait + while time.monotonic() < end: + if os.waitid(os.P_PID, proc.pid, os.WEXITED | os.WNOHANG | os.WNOWAIT) is not None: + break + time.sleep(0.05) + send(signal.SIGKILL) + + +def _gone(pid: int, started: str) -> bool: + """Whether the process `pid` that started at `started`, its `/proc` stat + field 22, has ended: no process has its pid, another process has it now, + or it is a zombie (T258f).""" + try: + fields = Path(f"/proc/{pid}/stat").read_text().rsplit(")", 1)[1].split() + except OSError: + return True + return fields[19] != started or fields[0] in ("Z", "X") + + +def _gone_by(pid: int, started: str, deadline: float) -> bool: + """Whether the process `pid` that started at `started` is seen `_gone` + before the monotonic `deadline`: the clock is read after each look, and + absence counts only where that reading is still before the deadline, so + a pause of the case past it never turns a later end into a pass (T224r; + Codex's review of P09 at `b8f9e35a`, SHOULD 3).""" + while True: + gone = _gone(pid, started) + if time.monotonic() >= deadline: + return False + if gone: + return True + time.sleep(0.05) + + +def _end_if_left(pid: int, started: str) -> None: + """A case's last clean-up of a process it did not start itself, known by + its pid and its start time (T258f): pinned by a pidfd, then killed through + that pidfd only where the pinned process is still the one that started at + `started`, so no other process is ever signalled.""" + try: + pinned = os.pidfd_open(pid) + except ProcessLookupError: + return + try: + if not _gone(pid, started): + with contextlib.suppress(ProcessLookupError): + signal.pidfd_send_signal(pinned, signal.SIGKILL) + finally: + os.close(pinned) + + +#: One deadline, in seconds, for all of a `_run`: its terminal or stdout pipe and +#: its stderr, read together, and then its exit; and one for a held session's +#: close (T224o). +RUN_S, CLOSE_S = 300.0, 60.0 + + +def _drain(fds: list, deadline: float) -> tuple: + """Each of `fds` read to its end, all of them together, until the + monotonic `deadline` (T224o; Codex's review of P09 at `21dd3642`, SHOULD 1 + in lane 3's numbering): no read waits on one while another fills. Returns + each fd's bytes, in order, and whether every one reached its end. A + terminal's EIO, once no process holds its other side, is its end.""" + got = {fd: bytearray() for fd in fds} + live = list(fds) + while live: + left = deadline - time.monotonic() + if left <= 0: + break + ready, _, _ = select.select(live, [], [], left) + for fd in ready: + try: + chunk = os.read(fd, 65536) + except OSError: + chunk = b"" + if chunk: + got[fd] += chunk + else: + live.remove(fd) + return [bytes(got[fd]) for fd in fds], not live + + +def _run(argv: list, env: dict, cwd: Path, *, pty_run: bool) -> subprocess.CompletedProcess: + """`argv`, its stdout a pipe, or a terminal (`pty.openpty()`) where + `pty_run`; its stdin is /dev/null and its stderr a pipe. All of it runs + under one monotonic deadline, `RUN_S` (T224o; Codex's review of P09 at + `21dd3642`, SHOULD 1 in lane 3's numbering). Through a pipe that is + `subprocess.run`'s `timeout`. Under the terminal, the run has a session + of its own, the terminal and stderr are read together (`_drain`), and its + exit is reaped before the same deadline. A run that does not end by then + raises `TimeoutExpired`, which carries no output, since a login's stdout + holds password-file lines. On that and on any other way out unreaped, the + run is ended with its group by `_end_process`, signalled only while it is + unreaped, and reaped, both bounded.""" + if not pty_run: + return subprocess.run(argv, capture_output=True, text=True, env=env, cwd=str(cwd), + timeout=RUN_S, stdin=subprocess.DEVNULL) + import pty + deadline = time.monotonic() + RUN_S + primary, secondary = pty.openpty() + try: + proc = subprocess.Popen(argv, stdout=secondary, stderr=subprocess.PIPE, + stdin=subprocess.DEVNULL, env=env, cwd=str(cwd), + start_new_session=True) + os.close(secondary) + secondary = -1 + try: + (out, err), ended = _drain([primary, proc.stderr.fileno()], deadline) + if ended: + try: + proc.wait(max(0.0, deadline - time.monotonic())) + except subprocess.TimeoutExpired: + ended = False + if not ended: + raise subprocess.TimeoutExpired(argv, RUN_S) + finally: + try: + _end_process(proc, group=True, wait=END_S) + finally: + proc.stderr.close() + finally: + os.close(primary) + if secondary >= 0: + os.close(secondary) + return subprocess.CompletedProcess(argv, proc.returncode, + out.decode("utf-8", "replace").replace("\r\n", "\n"), + err.decode("utf-8", "replace")) + + +def _objects(text: str) -> list: + """Each object line's (what, state), in order.""" + return [(m.group("what"), m.group("state")) for m in OBJECT_LINE.finditer(text)] + + +def _passwords(text: str) -> dict: + """Each password-file line, by login. A login printed twice fails, its + text masked, and the check is a bool: pytest's report of an assertion + shows each operand's value, and `found` holds the lines (T224j). The + message names no login: a login is a field of a line a writer printed, + so it shows how many logins were read before it instead (T258t; lane + 2's targeted check RV9-39 of P09 at `3c5b68bc`, S6).""" + found: dict = {} + for m in PASS_LINE.finditer(text): + twice = m.group("login") in found + assert not twice, (f"a password-file line's login is printed twice, with {len(found)} login(s) " + f"read before it (_passwords is given the text alone, so no exit):\n" + f"{_said_safely(text, stream='stdout')}") + found[m.group("login")] = m.group(0) + return found + + +def _checks(text: str) -> dict: + return {int(m.group(1)): (m.group(2), m.group(3) or "") for m in CHECK_LINE.finditer(text)} + + +def _sha256(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +class Session: + """A `psql` session of a login, held open by the test (AT-LRMPG's FIFO): + its statements go on stdin, each followed by a `\\warn` marker, and the + test waits for each marker on stderr, which `psql` writes unbuffered. No + `ON_ERROR_STOP`, so a refused statement leaves the session open.""" + + def __init__(self, argv: list, env: dict): + self.proc = subprocess.Popen(argv, stdin=subprocess.PIPE, stdout=subprocess.PIPE, + stderr=subprocess.PIPE, env=env) + self.err = b"" + + def send(self, sql: str, marker: str, deadline: float = 30.0) -> str: + """`sql`, then the marker; the stderr written until the marker, or + until `psql` ended.""" + start = len(self.err) + try: + self.proc.stdin.write(f"{sql}\n\\warn {marker}\n".encode("utf-8")) + self.proc.stdin.flush() + except BrokenPipeError: + pass + fd = self.proc.stderr.fileno() + end = time.monotonic() + deadline + while marker.encode() not in self.err[start:]: + assert time.monotonic() < end, ( + f"psql gave no {marker!r} within {deadline:.0f} s, and has no exit, its session still open: " + f"{_said_safely(self.err[start:], stream='stderr')!r}") + ready, _, _ = select.select([fd], [], [], 0.2) + if ready: + chunk = os.read(fd, 65536) + if not chunk: + break + self.err += chunk + return self.err[start:].decode("utf-8", "replace") + + def exit_now(self) -> str: + """Its `psql`'s exit where it has ended, else that it still runs, at + the moment it is asked (T258s; lane 2's targeted check RV9-39 of P09 + at `3c5b68bc`, S3: `send` returns where `psql` ended too, so a message + that said "its session still open" could say the opposite of the + truth). It waits for the exit at most 1 s (T258u; lane 2's pre-review + RV9-40 of P09 at `161c3087`, S2): a `psql` closes its pipes as it + ends, before its exit can be reaped, so `poll()` alone, right after + `send` returned at stderr's end, said "still running" for a `psql` + that had ended in 8 of 300 runs. Only a failure's message asks.""" + try: + code = self.proc.wait(timeout=1.0) + except subprocess.TimeoutExpired: + return "no exit in 1 s, its psql still running" + return f"its psql exit {code}" + + def close(self) -> subprocess.CompletedProcess: + """`psql`'s stdin closed; then its stdout and stderr read together to + their ends (`_drain`) and its exit reaped, all under one monotonic + deadline, `CLOSE_S` (T224o; Codex's review of P09 at `21dd3642`, + SHOULD 1 in lane 3's numbering). A `psql` that does not end by then + raises `TimeoutExpired`, with no output. On that and on any other way + out unreaped, it is ended by `_end_process`, signalled only while it is + unreaped, and reaped, both bounded.""" + deadline = time.monotonic() + CLOSE_S + try: + self.proc.stdin.close() + except BrokenPipeError: + pass + try: + (out, err), ended = _drain([self.proc.stdout.fileno(), self.proc.stderr.fileno()], + deadline) + self.err += err + if ended: + try: + self.proc.wait(max(0.0, deadline - time.monotonic())) + except subprocess.TimeoutExpired: + ended = False + if not ended: + raise subprocess.TimeoutExpired(self.proc.args, CLOSE_S) + finally: + try: + _end_process(self.proc, group=False, wait=END_S) + finally: + self.proc.stdout.close() + self.proc.stderr.close() + return subprocess.CompletedProcess([], self.proc.returncode, out.decode("utf-8", "replace"), + self.err.decode("utf-8", "replace")) + + +def _another_cluster(request, *, data_from: Path | None = None): + """A second server for a restore: a `pgcluster.Cluster` of the test's + own, destroyed at its teardown. With `data_from`, it starts on a copy of + that stopped data directory, which stands for the provider's snapshot or + point-in-time restore; otherwise it is a new cluster.""" + engine = request.getfixturevalue("pg_engine") + import pgcluster + cluster = pgcluster.Cluster(engine.bindir) + request.addfinalizer(cluster.destroy) + if data_from is None: + cluster.start() + return cluster + cluster.root = Path(tempfile.mkdtemp(prefix=pgcluster.PREFIX, dir=pgcluster.SOCKET_PARENT)) + (cluster.root / "owner").write_text(f"{os.getpid()} {pgcluster._ticks(os.getpid())}\n") + shutil.copytree(data_from, cluster.root / "data", symlinks=True) + (cluster.root / "data").chmod(0o700) + cluster.launch() + return cluster + + +class Managed: + """One test's managed PostgreSQL: a cluster whose superuser stands for + the provider, the admin it made, the admin's services, and the + `lanes-index` runs, each with the test's own `$HOME`.""" + + def __init__(self, request, root: Path, *, cluster=None, scram: bool = True): + # A CLUSTER OF THE TEST'S OWN WITH AN EMPTY TEMPLATE, as the provider's + # new server is: T227 makes `stoppable_cluster`'s template the bootstrap, + # with T228's logins, which would leave this admin, no superuser, + # without ADMIN OPTION on roles it did not make (PostgreSQL 16). + self.cluster = cluster if cluster is not None else _another_cluster(request) + import pgcluster + self.pgcluster = pgcluster + self.port = int(getattr(self.cluster, "port", pgcluster.PORT)) + self.root = root + self.home = root / "home" + self.home.mkdir(parents=True, exist_ok=True) + (root / "t").mkdir(exist_ok=True) + self.services: dict = {} + env = guard_strip_env(os.environ, strip=("T224_", "XDG_")) + env.update(HOME=str(self.home), XDG_CONFIG_HOME=str(root / "config"), + XDG_STATE_HOME=str(root / "state"), TMPDIR=str(root / "t"), + LANES_WORKSTATION="Eagle", LANES_NO_GITHUB="1", LC_ALL="C", + PATH=os.pathsep.join([str(self.cluster.bindir), + os.environ.get("PATH", os.defpath)])) + self.env = env + # THE PROVIDER makes the admin, CNPG's initdb owner: no SUPERUSER. + self.cluster.psql(f"DO $$ BEGIN IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = '{ADMIN}') THEN " + f"CREATE ROLE {ADMIN} LOGIN CREATEROLE CREATEDB NOSUPERUSER; END IF; END $$;") + # SECTION 5.6'S COUNTING CLUSTER'S LOG: each connection and statement, + # each line prefixed with its backend's pid. + self.cluster.psql("ALTER SYSTEM SET log_connections = on;\n" + "ALTER SYSTEM SET log_statement = 'all';\n" + "ALTER SYSTEM SET log_line_prefix = '%p ';\n" + "SELECT pg_reload_conf();\n") + if scram: + # SCRAM ON THE SOCKET for every login but the provider and the admin. + (self.cluster.root / "data" / "pg_hba.conf").write_text( + f"local all {pgcluster.SUPERUSER} trust\nlocal all {ADMIN} trust\n" + "local all all scram-sha-256\n", encoding="utf-8") + self.cluster.psql("SELECT pg_reload_conf();") + + # ------------------------------------------------------------ the server + def psql(self, sql: str, db: str = "postgres", user: str | None = None, + check: bool = True) -> subprocess.CompletedProcess: + """`sql` as the provider (the cluster's superuser), or as `user` + where trust lets it in: the admin's own maintenance connection.""" + return self.cluster.psql(sql, dbname=db, user=user or self.pgcluster.SUPERUSER, + check=check) + + def value(self, sql: str, db: str) -> str: + return self.psql(sql, db).stdout.strip() + + def log(self) -> str: + return (self.cluster.root / "server.log").read_text(encoding="utf-8", errors="replace") + + def database(self, name: str) -> str: + """The admin's own act (R-P41): he creates the register's database + through his maintenance connection, so he owns it, and one service + in `~/.pg_service.conf` names it. Returns the service.""" + self.psql(f"CREATE DATABASE {name};", user=ADMIN) + return self.service(name) + + def service(self, database: str) -> str: + service = f"t224_{database}" + self.services[service] = database + _private(self.home / ".pg_service.conf", "".join( + f"[{s}]\nhost={self.cluster.root}\nport={self.port}\nuser={ADMIN}\ndbname={d}\n\n" + for s, d in self.services.items())) + return service + + # ------------------------------------------------------------ lanes-index + def lanes(self, *args: str, pty_run: bool = False, + config: Path | None = None) -> subprocess.CompletedProcess: + env = dict(self.env) + if config is not None: + env["LANES_INDEX_CONFIG"] = str(config) + return _run([sys.executable, str(REPO / "lanes-index"), *args], env, self.root, + pty_run=pty_run) + + def bootstrap(self, service: str, *flags: str, pty_run: bool = False) -> subprocess.CompletedProcess: + args = ["bootstrap", "--admin-service", service] + if "--roles-only" not in flags: + args += ["--label", LABEL, "--repository", REPOSITORY, "--lane", LANE] + return self.lanes(*args, *flags, pty_run=pty_run) + + def bootstrapped(self, service: str) -> None: + proc = self.bootstrap(service, "--no-passwords") + assert proc.returncode == 0, f"the bootstrap failed:\n{_said_safely(proc)}" + + def login(self, action: str, who: str, service: str, *, pty_run: bool = True) -> subprocess.CompletedProcess: + target = ["--dump-job"] if who == DUMP else [who] + return self.lanes("login", action, *target, "--admin-service", service, pty_run=pty_run) + + def logins(self, service: str, *engineers: str, dump: bool = True, + folder: str = "passfiles") -> dict: + """`login add` for each engineer, and for the dump job, under the pty: + each printed line in its login's 0600 file. Returns the files. Each + run is `_added`'s, so this frame, whose `*engineers` makes pytest + 8.3.4 print its locals as arguments in a long entry, holds no printed + password line (T258w; lane 2's pre-review RV9-41 of P09 at + `4895579`, B1). That is this frame only (T258x; lane 2's pre-review + RV9-42 of P09 at `857a41d2`, N6): where `_passwords` raises, its + frame, `_passwords(text)`, and `passfiles(self, text, ...)`'s hold + the printed lines as their genuine argument `text`, which an explicit + `--tb=long`, `--fulltrace` or `--showlocals` prints on every pytest + version; the suite's default, `--tb=short` (T205e), prints no + frame's arguments.""" + files: dict = {} + for who in [*engineers, *([DUMP] if dump else [])]: + files.update(self.passfiles(self._added(who, service), folder)) + return files + + def _added(self, who: str, service: str) -> str: + """`login add <who>`'s stdout, its printed password lines, or an + AssertionError that shows its exit and counts (T258w).""" + proc = self.login("add", who, service) + assert proc.returncode == 0, f"login add {who} failed:\n{_said_safely(proc)}" + return proc.stdout + + def passfiles(self, text: str, folder: str = "passfiles") -> dict: + return {login: _private(self.home / folder / login, line + "\n") + for login, line in _passwords(text).items()} + + # ------------------------------------------------------------ the logins + def login_env(self, login: str, db: str, passfile: Path | None) -> dict: + env = {k: v for k, v in self.env.items() if not k.startswith("PG")} + env.update(PGHOST=str(self.cluster.root), PGPORT=str(self.port), PGUSER=login, + PGDATABASE=db, PGCONNECT_TIMEOUT="10") + if passfile is not None: + env["PGPASSFILE"] = str(passfile) + return env + + def as_login(self, login: str, db: str, sql: str, passfile: Path | None, + **variables) -> subprocess.CompletedProcess: + """`sql` in a new session of `login`, on the socket, with its + password file; `VERBOSITY=verbose`, so an error carries its SQLSTATE.""" + argv = [self.cluster.tool("psql"), "-X", "-q", "-A", "-t", "-w", "-v", "ON_ERROR_STOP=1", + "-v", "VERBOSITY=verbose"] + for name, value in variables.items(): + argv += ["-v", f"{name}={value}"] + return subprocess.run(argv + ["-f", "-"], input=sql, capture_output=True, text=True, + timeout=60, env=self.login_env(login, db, passfile), check=False) + + def session(self, login: str, db: str, passfile: Path | None) -> Session: + argv = [self.cluster.tool("psql"), "-X", "-q", "-A", "-t", "-w", "-v", "VERBOSITY=verbose"] + return Session(argv, self.login_env(login, db, passfile)) + + def shown(self, login: str, db: str, passfile: Path | None) -> dict: + """`SHOW` of the four floors in a session of `login`.""" + names = sorted(NO_FLOORS) + proc = self.as_login(login, db, "".join(f"SHOW {name};\n" for name in names), passfile) + assert proc.returncode == 0, f"{login} could not log in to SHOW its floors:\n{_said_safely(proc)}" + return dict(zip(names, proc.stdout.split())) + + def role(self, login: str) -> dict: + """A role's attributes, its own settings, its verifier and its groups, + read by the provider.""" + row = self.value( + "SELECT json_build_object('canlogin', a.rolcanlogin, 'super', a.rolsuper, " + "'config', coalesce(r.rolconfig, '{}'), 'verifier', a.rolpassword, " + "'groups', ARRAY(SELECT g.rolname::text FROM pg_auth_members m JOIN pg_roles g " + "ON g.oid = m.roleid WHERE m.member = a.oid ORDER BY 1)) " + f"FROM pg_authid a JOIN pg_roles r ON r.oid = a.oid WHERE a.rolname = '{login}';", "postgres") + return json.loads(row) if row else {} + + # ------------------------------------------------------------ the register + def entry(self, db: str, kind: str, path: str, text: str) -> dict: + """An entry creating `path` with one line (T222f's form): `import` for + `lanes/LANES.md`, AT-LR006's first step, or `cutover` for + `lanes/STORE`.""" + clock = self.value("SELECT (clock_timestamp() + interval '60 s')::text;", db) + journal = {"kind": kind, "verb": kind, "lane": OPERATOR, "workstation": WS, + "author": AUTHOR, "message": f"{kind} by {OPERATOR} (T224)"} + if kind == "import": + journal.update(git_commit="c" * 40, git_tree="d" * 40) + return {"journal": journal, "not_after": clock, + "edits": [{"ord": 1, "op": "create", "path": path}, + {"ord": 2, "op": "append", "path": path, "new_text": text}], + "files": [{"path": path, "present": True, "final_newline": True, + "sha256": _sha256((text + "\n").encode("utf-8"))}]} + + def commit(self, db: str, login: str, passfile: Path, entry: dict) -> subprocess.CompletedProcess: + """ONE `commit_write` call as `login`, at SERIALIZABLE (T222f's form).""" + head = self.value(f"SELECT seq FROM {REGISTER}.register_head;", db) + client = self.value(f"SELECT version FROM {REGISTER}.schema_version;", db) + generation = self.value(f"SELECT generation FROM {REGISTER}.register_switch;", db) + sql = ("BEGIN ISOLATION LEVEL SERIALIZABLE;\n" + f"SELECT {REGISTER}.commit_write(:base, :'wid'::uuid, :client, :'gen'::uuid, " + ":'entry'::jsonb);\nCOMMIT;\n") + return self.as_login(login, db, sql, passfile, base=head, wid=str(uuid.uuid4()), + client=client, gen=generation, + entry=json.dumps(entry, ensure_ascii=False)) + + def to_primary(self, db: str, login: str, passfile: Path) -> None: + """AT-LR006's route on a bootstrapped database: an `import` entry, a + `cutover` entry over it, then `record_marker`, as `login`.""" + for kind, path, text in (("import", "lanes/LANES.md", "# Lanes"), + ("cutover", "lanes/STORE", "primary")): + proc = self.commit(db, login, passfile, self.entry(db, kind, path, text)) + assert proc.returncode == 0, f"the {kind} entry did not commit:\n{_said_safely(proc)}" + seq = self.value(f"SELECT seq FROM {REGISTER}.register_head;", db) + client = self.value(f"SELECT version FROM {REGISTER}.schema_version;", db) + proc = self.as_login(login, db, f"SELECT {REGISTER}.record_marker(:client, :seq, " + ":'commit', :'ws');\n", passfile, client=client, seq=seq, + commit=MARKER_COMMIT, ws=WS) + assert proc.returncode == 0 and proc.stdout.strip() == "present", _said_safely(proc) + + def config(self, name: str, register_url: str, register_passfile: Path, + reader_url: str, reader_passfile: Path) -> Path: + return _private(self.root / name / "lanes-index.conf", "\n".join([ + "mode=index", f"register_url={register_url}", f"register_passfile={register_passfile}", + f"reader_url={reader_url}", f"reader_passfile={reader_passfile}", + f"register_label={LABEL}", ""])) + + def socket_url(self, login: str, db: str) -> str: + return f"postgresql://{login}@{quote(str(self.cluster.root), safe='')}:{self.port}/{db}" + + def ready(self, config: Path) -> subprocess.CompletedProcess: + return self.lanes("ready", "--expect", "index", "--release", "0.0.0-t224", "--env", + "t224", config=config) + + def dump(self, db: str, passfile: Path, name: str) -> tuple: + """O2's command as the dump job's login, its connection from its + environment and `PGPASSFILE` naming its password file.""" + target = self.root / name + proc = subprocess.run(["bash", "-c", DUMP_COMMAND.format(file=target)], + capture_output=True, text=True, timeout=300, + env=self.login_env(DUMP, db, passfile), check=False) + return proc, target + + def catalog(self, db: str) -> list: + """Both schemas' catalogs: each object, its kind, its owner and its + ACL as a set of its elements; each function's signature, owner, ACL + and security; each default ACL; and the roles' attributes and + memberships. One sorted list.""" + sql = f""" +SELECT json_agg(x ORDER BY x) FROM ( + SELECT format('rel %s.%s %s owner=%s acl=%s', n.nspname, c.relname, c.relkind, + pg_get_userbyid(c.relowner), + (SELECT string_agg(a::text, ',' ORDER BY a::text) FROM unnest(c.relacl) a)) AS x + FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace + WHERE n.nspname IN ('{REGISTER}', '{INDEX}') + UNION ALL + SELECT format('fn %s.%s(%s) owner=%s secdef=%s acl=%s', n.nspname, p.proname, + pg_get_function_identity_arguments(p.oid), pg_get_userbyid(p.proowner), + p.prosecdef, + (SELECT string_agg(a::text, ',' ORDER BY a::text) FROM unnest(p.proacl) a)) + FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace + WHERE n.nspname IN ('{REGISTER}', '{INDEX}') + UNION ALL + SELECT format('ns %s owner=%s acl=%s', n.nspname, pg_get_userbyid(n.nspowner), + (SELECT string_agg(a::text, ',' ORDER BY a::text) FROM unnest(n.nspacl) a)) + FROM pg_namespace n WHERE n.nspname IN ('{REGISTER}', '{INDEX}') + UNION ALL + SELECT format('defacl %s %s %s %s', pg_get_userbyid(d.defaclrole), + coalesce(d.defaclnamespace::regnamespace::text, '-'), d.defaclobjtype, + (SELECT string_agg(a::text, ',' ORDER BY a::text) FROM unnest(d.defaclacl) a)) + FROM pg_default_acl d + UNION ALL + SELECT format('role %s login=%s super=%s createrole=%s createdb=%s config=%s', r.rolname, + r.rolcanlogin, r.rolsuper, r.rolcreaterole, r.rolcreatedb, + coalesce(array_to_string(r.rolconfig, ' '), '-')) + FROM pg_roles r WHERE r.rolname LIKE 'lanes%' + UNION ALL + SELECT format('member %s of %s inherit=%s set=%s', pg_get_userbyid(m.member), + pg_get_userbyid(m.roleid), m.inherit_option, m.set_option) + FROM pg_auth_members m + WHERE pg_get_userbyid(m.roleid) LIKE 'lanes%' OR pg_get_userbyid(m.member) LIKE 'lanes%' +) AS t(x); +""" + return json.loads(self.value(sql, db) or "[]") + + def rows(self, db: str) -> str: + """Both schemas' rows, table by table, each table's rows sorted.""" + tables = self.value( + "SELECT string_agg(format('%I.%I', schemaname, tablename), ' ' ORDER BY schemaname, tablename) " + f"FROM pg_tables WHERE schemaname IN ('{REGISTER}', '{INDEX}');", db).split() + views = self.value( + "SELECT string_agg(format('%I.%I', schemaname, viewname), ' ' ORDER BY schemaname, viewname) " + f"FROM pg_views WHERE schemaname IN ('{REGISTER}', '{INDEX}');", db).split() + return "\n".join(f"{name}: " + self.value( + f"SELECT coalesce(json_agg(r ORDER BY r::text), '[]') FROM {name} r;", db) + for name in tables + views) + + def connects(self, login: str, db: str, passfile: Path) -> bool: + return self.as_login(login, db, "SELECT 1;\n", passfile).returncode == 0 + + +def _no_clear_text(log: str, lines: dict) -> None: + """The server's log holds each printed password only as a SCRAM + verifier, never as clear text (O6). The message names no login, a + field of a line a writer printed, only its place among `lines` (T258v; + lane 2's pre-review RV9-40 of P09 at `161c3087`, S3, as T258t for + `_passwords`).""" + for n, line in enumerate(lines.values(), 1): + secret = line.rsplit(":", 1)[1] + leaked = secret in log # a bool, so pytest's report never shows the secret (T224j) + assert not leaked, (f"the server's log holds a printed password in clear text (login {n} " + f"of {len(lines)})") + + +# ============================================================ a failure's message (T224j) +def test_a_failure_message_keeps_no_password_of_a_password_file_line(): + """T224j (Codex's review of P09 at `f4f0ebce`, BLOCKING 3; lane 3's + ruling 6932114864): `_said` and `_passwords`' refusal of a line printed + twice keep no password, on synthetic text alone, with no database. The + line is built in the form of lane 1's `_register_pgpass_line`, with a + fresh uuid as its password. Each check is a bool, so no failure of this + case prints the password either.""" + secret = uuid.uuid4().hex + line = ":".join(("*", "*", "t224_reg", "lanes_w_t224", secret)) + proc = subprocess.CompletedProcess([], 1, f"login lanes_w_t224: created\n{line}\n", f"{line}\n") + said = _said(proc) + kept = secret in said + counted = "stdout: 2 line(s)" in said and "stderr: 1 line(s)" in said + assert not kept and counted, "_said keeps the password, or does not count its streams' lines" + with pytest.raises(AssertionError) as twice: + _passwords(f"{line}\n{line}\n") + kept = secret in str(twice.value) + assert not kept, "_passwords' refusal of a line printed twice keeps its password" + found = _passwords(f"{line}\n") + read = found.get("lanes_w_t224") == line + assert read, "_passwords no longer reads the line it is given" + + def none_printed(lines: dict) -> None: + assert lines == {}, "a password line was printed" + with pytest.raises(AssertionError) as failed: # T224k: an operand that holds the line + none_printed(found) + kept = secret in str(failed.value) + assert not kept, "a failed assertion whose operand holds the line reports its password" + + +@pytest.mark.parametrize("case", ["passwords", "no-clear-text"]) +def test_pytests_own_report_of_a_password_check_shows_no_password(request, case): + """T258r (lane 3's ruling 6949488277 on lane 2's pre-review RV9-38 of + P09 at `3f9fcac4`, B1), with no engine and no process: T224j's checks + fail with a password-file line's password as their frames' arguments, + and pytest's own report of the failure, rendered as pytest renders a + failed test under the suite's own settings (bounds' `_reported`), holds + no password. T224j checked `str()` alone, and its "a bool, so pytest's + report never shows the secret" held for the assert's operand, not for + the frame's arguments, which pytest's default `--tb=auto` prints: + - `passwords`: `_passwords(text)`, a line printed twice, where `text` + is a login's stdout holding the line (RV9-38: managed :413); + - `no-clear-text`: `_no_clear_text(log, lines)`, a server log that + holds the password in clear text, where `log` and `lines` both hold + it (RV9-38: managed :795). + T205e's short style prints no frame's arguments. An explicit + `--tb=long` or `--fulltrace` is not secret-safe. The password is a + fresh uuid, no credential of any login.""" + secret = uuid.uuid4().hex + line = ":".join(("*", "*", "t224_reg", "lanes_w_t224", secret)) + with pytest.raises(AssertionError) as failed: + if case == "passwords": + _passwords(f"{line}\n{line}\n") + else: + _no_clear_text(f"LOG: statement: ALTER ROLE lanes_w_t224 PASSWORD '{secret}'\n", + {"lanes_w_t224": line}) + shown = secret in _reported(request, failed) + assert not shown, f"[{case}] the password is in pytest's report" + + +# ============================================================ one deadline (T224o) +#: T224o's stand-in, run by this Python with `-I`, its mode and a mark file +#: as its arguments. Each mode reads its stdin to the end first. `full-stderr` +#: fills its stderr pipe, 256 KiB, four times a pipe's 64 KiB, before it writes +#: one line to stdout and exits 0. `hung` writes one line and waits, and a child +#: in its group holds its stdout and stderr too; it writes its pid to the mark, +#: and the child writes its pid and start time (`/proc` stat field 22) to the +#: mark's `.child`. `hung-alone` writes one line and waits, alone. Every process +#: of it ends itself by SIGALRM within 8 s, whatever is done to it. +T224O_STAND_IN = """ +import os, signal, sys, time +signal.alarm(8) +mode, mark = sys.argv[1], sys.argv[2] +sys.stdin.read() +if mode == "full-stderr": + sys.stderr.buffer.write(b"e" * 262144) + sys.stderr.buffer.flush() + print("done", flush=True) + sys.exit(0) +if mode == "hung" and os.fork() == 0: + signal.alarm(8) + started = open("/proc/self/stat").read().rsplit(")", 1)[1].split()[19] + open(mark + ".child", "w").write(f"{os.getpid()} {started}") + time.sleep(8) + os._exit(0) +open(mark, "w").write(str(os.getpid())) +print("started", flush=True) +time.sleep(8) +""" + + +#: T224O_STAND_IN's watchdog: each of its processes ends itself by SIGALRM this +#: many seconds after it starts (T224p). +T224O_WATCHDOG_S = 8 + + +def _t224p_hung_run(script: Path, mark: Path, env: dict) -> tuple: + """T224O_STAND_IN's `hung` run, its mark `mark`, under `_run`'s terminal, + which must raise `TimeoutExpired`: the monotonic times it started and + ended (T224p).""" + start = time.monotonic() + with pytest.raises(subprocess.TimeoutExpired): + _run([sys.executable, "-I", str(script), "hung", str(mark)], env, mark.parent, pty_run=True) + return start, time.monotonic() + + +def _t224p_child_gone_by(mark: Path, start: float) -> bool: + """Whether the hung run's child, its pid and start time in `mark`'s + `.child`, is gone by `RUN_S + END_S` after the run's `start` (T224p; the + coordinator's review of P09 at `d3a2fd5c`, item 2, #165 6938473998). + With the case's `RUN_S` of 3 s and `END_S` of 2 s that is 5 s after the + start, at least 3 s before the child's own watchdog, `T224O_WATCHDOG_S`, + which the child arms after its fork, after `start`: only the run's end + can satisfy it, never the watchdog. The clock is read after each look, + so a pause of the case past the deadline fails it (`_gone_by`; T224r).""" + pid, started = Path(f"{mark}.child").read_text().split() + return _gone_by(_whole(pid, "the stand-in's pid"), started, start + RUN_S + END_S) + + +def _t224p_end_child(mark: Path) -> None: + """The hung run's child, if it wrote its `.child` mark, ended by pidfd + where it is still that process (`_end_if_left`): each case's last + clean-up, whatever its oracle found (T224p).""" + child = Path(f"{mark}.child") + if child.exists(): + pid, started = child.read_text().split() + _end_if_left(_whole(pid, "the stand-in's pid"), started) + + +@pytest.mark.skipif(not sys.platform.startswith("linux"), + reason="T224O_STAND_IN's hung run forks a child with os.fork(), the child " + "names itself by /proc/<pid>/stat field 22, and the case finds it " + "gone through /proc: Linux only (T224q)") +def test_run_reads_its_terminal_and_stderr_together_and_ends_a_run_at_its_one_deadline( + tmp_path, monkeypatch): + """T224o (Codex's review of P09 at `21dd3642`, SHOULD 1 in lane 3's + numbering), no database, on T224O_STAND_IN under `_run`'s terminal. A + run that fills its stderr pipe before it writes to its terminal ends 0 + with all of both, since neither is read only after the other ends. A run + that does not end, with a child in its group holding both, is ended at + `RUN_S`: `_run` raises `TimeoutExpired` within `RUN_S + END_S`, 5 s, the + run is reaped, and its child is seen gone by that same 5 s after the run + started, at least 3 s before the child's own 8 s watchdog, so the + watchdog cannot pass the case (T224p; its negative control is the next + case), nor can a pause of the case past those 5 s (T224r; Codex's review + of P09 at `b8f9e35a`, SHOULD 3). The child is ended in a finally whatever happened. It runs on Linux + alone: the stand-in's child comes of `os.fork()` and names itself by + `/proc/<pid>/stat`, which the oracle reads too (T224q; Codex's review of + P09 at `d3a2fd5c`, SHOULD 5).""" + monkeypatch.setitem(globals(), "RUN_S", 3.0) + monkeypatch.setitem(globals(), "END_S", 2.0) + script = _private(tmp_path / "stand_in.py", T224O_STAND_IN) + env = {"PATH": os.environ.get("PATH", os.defpath)} + full = _run([sys.executable, "-I", str(script), "full-stderr", str(tmp_path / "full")], env, + tmp_path, pty_run=True) + said = (full.returncode, full.stdout, len(full.stderr)) + assert said == (0, "done\n", 262144), ( + f"a run that filled its stderr pipe ended {said[0]}, with {said[2]} bytes of stderr, " + f"not 0 with 262144") + mark = tmp_path / "hung" + try: + start, ended = _t224p_hung_run(script, mark, env) + took = ended - start + assert took < RUN_S + END_S, ( # T224r: `_run` itself ends within 5 s + f"_run ended a hung run after {took:.1f} s, past its {RUN_S + END_S:.0f} s bound") + try: + os.waitid(os.P_PID, _whole(mark.read_text(), "the hung run's pid"), os.WEXITED | os.WNOHANG | os.WNOWAIT) + reaped = False + except ChildProcessError: + reaped = True + assert reaped, "_run did not reap the hung run it ended" + gone = _t224p_child_gone_by(mark, start) + assert gone, (f"the hung run's child, in its group, was not gone {RUN_S + END_S:.0f} s " + f"after the run started, {T224O_WATCHDOG_S - RUN_S - END_S:.0f} s before " + f"its own watchdog") + finally: + _t224p_end_child(mark) + + +@pytest.mark.skipif(not sys.platform.startswith("linux"), + reason="T224p's oracle reads Linux's /proc and its clean-up pins by a pidfd") +def test_a_leader_only_end_of_a_hung_run_leaves_its_child_and_the_absence_oracle_fails( + tmp_path, monkeypatch): + """T224p (the coordinator's review of P09 at `d3a2fd5c`, item 2, #165 + 6938473998), no database: the negative control of the case above. Here + `_run`'s clean-up ends the hung run's leader alone, `_end_process` with + `group=False`, so its child, in its group, is not ended; the oracle, + `_t224p_child_gone_by`, must then find it still there at its deadline, + which comes at least 3 s before the child's own watchdog. Were the + watchdog able to satisfy the oracle, as the 5 s wait after `_run`'s end + before T224p let it, this case would fail. The child is ended in a + finally, by pidfd.""" + monkeypatch.setitem(globals(), "RUN_S", 3.0) + monkeypatch.setitem(globals(), "END_S", 2.0) + group_end = _end_process + monkeypatch.setitem(globals(), "_end_process", + lambda proc, *, group, wait=10.0: group_end(proc, group=False, wait=wait)) + script = _private(tmp_path / "stand_in.py", T224O_STAND_IN) + env = {"PATH": os.environ.get("PATH", os.defpath)} + mark = tmp_path / "hung" + try: + start, _ = _t224p_hung_run(script, mark, env) + gone = _t224p_child_gone_by(mark, start) + assert not gone, ("with the leader alone ended, the hung run's child was gone by the " + "oracle's deadline: the oracle does not tell a group's end from a " + "leader's") + finally: + _t224p_end_child(mark) + + +def test_a_held_sessions_close_reads_both_pipes_together_and_ends_it_at_its_one_deadline( + tmp_path, monkeypatch): + """T224o (Codex's review of P09 at `21dd3642`, SHOULD 1 in lane 3's + numbering), no database, on T224O_STAND_IN as a held session's `psql`. + One that fills its stderr pipe before it writes its stdout closes with 0 + and all of both. One that does not end once its stdin is closed is ended + at `CLOSE_S`: `close` raises `TimeoutExpired` within its bounds, and the + process is reaped.""" + monkeypatch.setitem(globals(), "CLOSE_S", 3.0) + monkeypatch.setitem(globals(), "END_S", 2.0) + script = _private(tmp_path / "stand_in.py", T224O_STAND_IN) + env = {"PATH": os.environ.get("PATH", os.defpath)} + full = Session([sys.executable, "-I", str(script), "full-stderr", str(tmp_path / "full")], + env).close() + said = (full.returncode, full.stdout, len(full.stderr)) + assert said == (0, "done\n", 262144), ( + f"a session that filled its stderr pipe closed with {said[0]}, with {said[2]} bytes of " + f"stderr, not 0 with 262144") + held = Session([sys.executable, "-I", str(script), "hung-alone", str(tmp_path / "hung")], env) + start = time.monotonic() + with pytest.raises(subprocess.TimeoutExpired): + held.close() + took = time.monotonic() - start + assert took < 3.0 + 2 * 2.0 + 1.5, f"close ended a hung session after {took:.1f} s, past its bounds" + assert held.proc.returncode is not None, "close did not reap the hung session it ended" + + +# ============================================================ the bootstrap +def test_bootstrap_without_a_superuser_runs_twice_with_one_catalog(tmp_path, request): + m = Managed(request, tmp_path) + service = m.database("t224_reg") + first = m.bootstrap(service, "--no-passwords") + assert first.returncode == 0, f"the first bootstrap, as {ADMIN}, failed:\n{_said_safely(first)}" + assert m.role(ADMIN)["super"] is False, f"{ADMIN} is a superuser: the case proves nothing" + catalog = m.catalog("t224_reg") + second = m.bootstrap(service, "--no-passwords") + assert second.returncode == 0, f"the second bootstrap failed:\n{_said_safely(second)}" + states = {state for _what, state in _objects(second.stdout)} + assert states == {"unchanged"}, f"the second run changed something:\n{_said_safely(second)}" + assert m.catalog("t224_reg") == catalog, "the second run changed the catalog" + # A SECURITY DEFINER function owned by a role that cannot log in works: + # `commit_write`, as a writer login, commits an import entry. + files = m.logins(service, "e1", dump=False) + proc = m.commit("t224_reg", "lanes_w_e1", files["lanes_w_e1"], + m.entry("t224_reg", "import", "lanes/LANES.md", "# Lanes")) + assert proc.returncode == 0, f"commit_write as lanes_w_e1 did not commit:\n{_said_safely(proc)}" + head = m.value(f"SELECT seq FROM {REGISTER}.register_head;", "t224_reg") + assert head == "0", f"the import as lanes_w_e1 left the register's head at {head!r}, not 0" + + +def test_bootstrap_refuses_a_database_its_admin_does_not_own(tmp_path, request): + m = Managed(request, tmp_path) + m.psql("CREATE DATABASE t224_theirs;") # the provider's, not the admin's + service = m.service("t224_theirs") + acl = m.value("SELECT coalesce(datacl, acldefault('d', datdba))::text FROM pg_database " + "WHERE datname = 't224_theirs';", "postgres") + proc = m.bootstrap(service, "--no-passwords") + assert proc.returncode == 2, f"bootstrap on a database its admin does not own is not 2:\n{_said_safely(proc)}" + assert m.value(f"SELECT count(*) FROM pg_namespace WHERE nspname = '{REGISTER}';", + "t224_theirs") == "0", "the refused bootstrap made the register's schema" + # THE CONTROL: there, as that admin, the database-level REVOKE and GRANT + # only warn, 01006 and 01007, and `datacl` is unchanged. + warned = m.psql("\\set VERBOSITY verbose\nREVOKE ALL ON DATABASE t224_theirs FROM PUBLIC;\n" + f"GRANT CONNECT ON DATABASE t224_theirs TO {ADMIN};\n", user=ADMIN) + assert "01006" in warned.stderr and "01007" in warned.stderr, _said_safely(warned) + kept = m.value("SELECT coalesce(datacl, acldefault('d', datdba))::text FROM pg_database " + "WHERE datname = 't224_theirs';", "postgres") + assert kept == acl, f"the warned REVOKE and GRANT changed t224_theirs's datacl: {acl} -> {kept}" + + +# ============================================================ the login step +def test_login_add_makes_an_engineers_two_logins_with_their_floors_and_prints_their_lines_once( + tmp_path, request): + m = Managed(request, tmp_path) + service = m.database("t224_reg") + m.bootstrapped(service) + proc = m.login("add", "e1", service) + assert proc.returncode == 0, f"login add e1 failed:\n{_said_safely(proc)}" + lines = _passwords(proc.stdout) + assert sorted(lines) == ["lanes_r_e1", "lanes_w_e1"], _said_safely(proc) + for key, login in (("register_url=", "lanes_w_e1"), ("reader_url=", "lanes_r_e1")): + urls = [line for line in proc.stdout.splitlines() if line.startswith(key)] + assert len(urls) == 1 and f"//{login}@" in urls[0], f"no one {key} line for {login}" + files = m.passfiles(proc.stdout) + for login, half, group in (("lanes_w_e1", "w", WRITER), ("lanes_r_e1", "r", READER)): + role = m.role(login) + assert role["canlogin"] and role["groups"] == [group], _unverified({login: role}) + assert sorted(role["config"]) == sorted(ROLCONFIG[half]), (login, role["config"]) + assert role["verifier"].startswith("SCRAM-SHA-256$"), f"{login}'s password is not SCRAM" + floors = {k: v for k, v in m.shown(login, "t224_reg", files[login]).items() if k in SHOWN[half]} + assert floors == SHOWN[half], f"{login} shows the floors {floors}, not {SHOWN[half]}" + _no_clear_text(m.log(), lines) + # THE DUMP JOB: `lanes_register_dump`, a member of READER alone, with the + # reader's floors, and its one line. + dump = m.login("add", DUMP, service) + assert dump.returncode == 0, f"login add --dump-job failed:\n{_said_safely(dump)}" + assert sorted(_passwords(dump.stdout)) == [DUMP], _said_safely(dump) + role = m.role(DUMP) + assert role["groups"] == [READER] and sorted(role["config"]) == sorted(ROLCONFIG["r"]), ( + _unverified({DUMP: role})) + _no_clear_text(m.log(), _passwords(dump.stdout)) + + +def test_login_add_run_again_puts_back_a_lost_membership_and_changes_nothing_else( + tmp_path, request): + m = Managed(request, tmp_path) + service = m.database("t224_reg") + m.bootstrapped(service) + m.logins(service, "e1", dump=False) + before = {login: m.role(login) for login in ("lanes_w_e1", "lanes_r_e1")} + m.psql(f"REVOKE {WRITER} FROM lanes_w_e1 GRANTED BY {ADMIN};") + assert m.role("lanes_w_e1")["groups"] == [], "the membership was not revoked by hand" + again = m.login("add", "e1", service) + assert again.returncode == 0, f"login add e1, run again, failed:\n{_said_safely(again)}" + printed = sorted(_passwords(again.stdout)) # the logins alone, as pytest reports it (T224j) + assert printed == [], f"the rerun printed a password line:\n{_said_safely(again)}" + after = {login: m.role(login) for login in ("lanes_w_e1", "lanes_r_e1")} + assert after == before, ( + f"the rerun changed more than the membership: {_unverified(before)} -> {_unverified(after)}; " + f"verifier changed for {sorted(k for k in before if after[k].get('verifier') != before[k].get('verifier'))}") + + +def test_a_member_made_without_the_login_step_carries_no_floor_and_fails_ready_check_12( + tmp_path, request): + m = Managed(request, tmp_path) + service = m.database("t224_reg") + m.bootstrapped(service) + files = m.logins(service, "e1", dump=False) + bare = {} + for login, group in (("lanes_w_bare", WRITER), ("lanes_r_bare", READER)): + password = uuid.uuid4().hex + m.psql(f"CREATE ROLE {login} LOGIN PASSWORD '{password}';\nGRANT {group} TO {login};\n") + bare[login] = _private(m.home / "passfiles" / login, f"*:*:t224_reg:{login}:{password}\n") + assert m.shown(login, "t224_reg", bare[login]) == NO_FLOORS, login + config = m.config("bare", m.socket_url("lanes_w_bare", "t224_reg"), bare["lanes_w_bare"], + m.socket_url("lanes_r_e1", "t224_reg"), files["lanes_r_e1"]) + proc = m.ready(config) + state, reason = _checks(proc.stdout).get(12, ("", "")) + assert proc.returncode == 2 and state == "FAIL", f"check 12 does not fail:\n{_said_safely(proc)}" + assert "lanes_w_bare" in reason, f"check 12 does not name the login:\n{_said_safely(proc)}" + for floor in ROLCONFIG["w"]: + assert floor.split("=", 1)[0] in reason, f"check 12 does not name {floor}:\n{_said_safely(proc)}" + + +def test_ready_check_12_passes_the_logins_the_step_made(tmp_path, request): + m = Managed(request, tmp_path) + service = m.database("t224_reg") + m.bootstrapped(service) + files = m.logins(service, "e1", dump=False) + config = m.config("e1", m.socket_url("lanes_w_e1", "t224_reg"), files["lanes_w_e1"], + m.socket_url("lanes_r_e1", "t224_reg"), files["lanes_r_e1"]) + proc = m.ready(config) + checks = _checks(proc.stdout) + state, _reason = checks.get(12, ("", "")) + assert state == "ok", f"check 12 fails the logins the step made:\n{_said_safely(proc)}" + # "check 12 passes, `check 12: ok`" (lane 3's batch 7, ruling 1: lane 1's + # bare line stands, Y-ops:457; tasks:572): the line is bare, with no floor. + assert re.search(r"^check 12: ok$", proc.stdout, re.M), ( + f"check 12's line is not the bare `check 12: ok`:\n{_said_safely(proc)}") + # Exit 0 where every check passes. On this socket fixture not every check + # can (check 11 always fails on a Unix socket, AT-LRMPG's own + # `[unix-socket]`), so the run's exit follows the other checks: 2, with + # check 12 not among the failures `ready` names. + failed = sorted(number for number, (said, _why) in checks.items() if said == "FAIL") + assert proc.returncode == (2 if failed else 0), ( + f"ready's exit does not follow its checks ({failed} failed):\n{_said_safely(proc)}") + assert 12 not in failed, f"check 12 is among the checks ready fails: {failed}" + # Check 11 fails on this case's Unix socket by TP:5382-5384's own oracle + # (`[unix-socket]`), so the exit's 2 arm is always the one exercised + # (lane 3's batch 11 (3), its optional assertion). + assert 11 in failed, ( + f"check 11 does not fail on this case's Unix socket, so the exit's 2 arm is not " + f"exercised:\n{_said_safely(proc)}") + + +def test_login_rotate_keeps_an_open_session_and_refuses_the_old_password(tmp_path, request): + m = Managed(request, tmp_path) + service = m.database("t224_reg") + m.bootstrapped(service) + old = m.logins(service, "e1", dump=False) + held = m.session("lanes_w_e1", "t224_reg", old["lanes_w_e1"]) + assert "ERROR" not in held.send("SELECT 'before';", "t224-before"), "the session did not open" + proc = m.login("rotate", "e1", service) + assert proc.returncode == 0, f"login rotate e1 failed:\n{_said_safely(proc)}" + new = m.passfiles(proc.stdout, "passfiles-new") + assert sorted(new) == ["lanes_r_e1", "lanes_w_e1"], _said_safely(proc) + answered = held.send("SELECT 'after';", "t224-after") + assert "ERROR" not in answered, (f"the session open across the rotation got an error ({held.exit_now()}):" + f"\n{_said_safely(answered, stream='stderr')}") + ended = held.close() + assert ended.returncode == 0 and ended.stdout.split() == ["before", "after"], ( + f"the session open across the rotation did not go on:\n{_said_safely(ended)}") + for login in ("lanes_w_e1", "lanes_r_e1"): + refused = m.as_login(login, "t224_reg", "SELECT 1;\n", old[login]) + assert refused.returncode == 2 and "password authentication failed" in refused.stderr, ( + f"{login}'s old password file is not refused at login:\n{_said_safely(refused)}") + assert m.connects(login, "t224_reg", new[login]), f"{login}'s new line does not connect" + _no_clear_text(m.log(), _passwords(proc.stdout)) + + +#: `login`'s refusals: each argv, and whether it runs under the pty. +LOGIN_REFUSALS = { + "name": [["login", "add", name, "--admin-service", "t224_admin"] + for name in ("E1", "1e", "e" * 42)], + "connection-string": [["login", "add", "e1", "--admin-service", value] + for value in ("host=/tmp port=5432 dbname=register_db", + "postgresql://lanes_register_admin@127.0.0.1/register_db")], + "pipe": [["login", "add", "e1", "--admin-service", "t224_admin"]], +} + + +class LoginBench: + """FP: the register's fake `psql` first on `PATH`, logging every call, a + service file naming a loopback admin, and the test's own `$HOME`.""" + + def __init__(self, root: Path): + self.root = root + fakebin = root / "fakebin" + fakebin.mkdir(parents=True) + (fakebin / "psql").write_text(REGISTER_FAKE_PSQL, encoding="utf-8") + (fakebin / "psql").chmod(0o755) + self.log = root / "psql.log" + home = root / "home" + home.mkdir() + (root / "t").mkdir() + _private(home / ".pg_service.conf", f"[t224_admin]\nhost=127.0.0.1\nport=55432\n" + f"user={ADMIN}\ndbname=register_db\n") + env = guard_strip_env(os.environ, strip=("T224_", "XDG_")) + env.update(HOME=str(home), XDG_CONFIG_HOME=str(root / "config"), + XDG_STATE_HOME=str(root / "state"), TMPDIR=str(root / "t"), + LANES_WORKSTATION="Eagle", LANES_NO_GITHUB="1", FAKE_PSQL_LOG=str(self.log), + PATH=os.pathsep.join([str(fakebin), os.environ.get("PATH", os.defpath)])) + self.env = env + + def run(self, argv: list, *, pty_run: bool) -> subprocess.CompletedProcess: + return _run([sys.executable, str(REPO / "lanes-index"), *argv], self.env, self.root, + pty_run=pty_run) + + def requests(self) -> list: + if not self.log.exists(): + return [] + entries = [json.loads(line) for line in self.log.read_text(encoding="utf-8").splitlines() + if line] + return [entry for entry in entries if entry.get("kind") != "version"] + + +def _making(entries: list) -> list: + return [entry for entry in entries + if re.search(r"\b(CREATE|GRANT|ALTER)\b", entry.get("stdin", ""))] + + +@pytest.mark.parametrize("case", list(LOGIN_REFUSALS)) +def test_login_refuses_a_bad_name_a_connection_string_and_a_pipe(tmp_path, case): + bench = LoginBench(tmp_path) + for argv in LOGIN_REFUSALS[case]: + proc = bench.run(argv, pty_run=(case != "pipe")) + assert proc.returncode == 2, f"[{case}] {argv[1:3]} is not refused with 2:\n{_said_safely(proc)}" + assert _making(bench.requests()) == [], f"[{case}] the refused login sent a making statement" + for value in argv: + if "=" in value or "://" in value: + assert value not in proc.stdout + proc.stderr, f"[{case}] the refusal echoed {value}" + # THE CONTROL: a good name, under the pty, gets past every refusal and + # reaches the admin service (the fake), so each refusal was the case's. + control = bench.run(["login", "add", "e1", "--admin-service", "t224_admin"], pty_run=True) + assert bench.requests(), ( + f"[{case}] the control, a good name under a terminal, sent nothing:\n{_said_safely(control)}") + + +# ============================================================ the revoke +def test_an_open_session_gets_42501_between_the_revokes_steps_then_57p01(tmp_path, request): + m = Managed(request, tmp_path) + service = m.database("t224_reg") + m.bootstrapped(service) + files = m.logins(service, "e1", "e2", dump=False) + held = m.session("lanes_w_e2", "t224_reg", files["lanes_w_e2"]) + opened = held.send("SELECT 1;", "t224-open") + assert "ERROR" not in opened, (f"e2's session did not open ({held.exit_now()}):" + f"\n{_said_safely(opened, stream='stderr')}") + # [steps-by-hand]: the revoke block's steps 1 and 2, by the admin. + m.psql(f"ALTER ROLE lanes_w_e2 NOLOGIN;\nREVOKE {WRITER} FROM lanes_w_e2;\n", "t224_reg", + user=ADMIN) + write = held.send(f"SELECT {REGISTER}.commit_write(NULL, NULL, NULL, NULL, NULL);", + "t224-write") + read = held.send(f"SELECT seq FROM {REGISTER}.register_head;", "t224-read") + for what, said in (("write", write), ("read", read)): + assert "42501" in said and f"permission denied for schema {REGISTER}" in said, ( + f"the open session's {what} between steps 2 and 3 is not 42501 ({held.exit_now()}): " + f"{_said_safely(said, stream='stderr')}") + # Step 3 by hand: its sessions ended. + m.psql("GRANT lanes_w_e2 TO CURRENT_USER WITH INHERIT TRUE, SET FALSE;\n" + "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE usename = 'lanes_w_e2';\n" + "REVOKE lanes_w_e2 FROM CURRENT_USER;\n", "t224_reg", user=ADMIN) + after = held.send(f"SELECT seq FROM {REGISTER}.register_head;", "t224-after") + ended = held.close() + said = after + ended.stderr + assert "57P01" in said or "terminating connection due to administrator command" in said or \ + "server closed the connection" in said, ( + f"the next statement after step 3 was answered: its stderr then and at its end, " + f"{_said_safely(said, stream='stderr')}; its end, {_said_safely(ended)}") + assert "permission denied" not in after, (f"after step 3 a statement got 42501, not 57P01: " + f"{_said_safely(after, stream='stderr')}; its end, " + f"{_said_safely(ended)}") + assert m.connects("lanes_w_e1", "t224_reg", files["lanes_w_e1"]), "e1 can no longer log in" + + +# ============================================================ the dump +def test_the_reader_login_dumps_both_schemas_and_still_cannot_write(tmp_path, request): + m = Managed(request, tmp_path) + service = m.database("t224_reg") + m.bootstrapped(service) + files = m.logins(service, "e1") + proc = m.commit("t224_reg", "lanes_w_e1", files["lanes_w_e1"], + m.entry("t224_reg", "import", "lanes/LANES.md", "# Lanes")) + assert proc.returncode == 0, _said_safely(proc) + # The indexer's store, made as the indexer (`lanes-index`'s own #160 + # scripts are not run here: see the report), with a row. + m.psql(f"SET ROLE {INDEXER};\nCREATE TABLE {INDEX}.t224_rows (id int PRIMARY KEY);\n" + f"INSERT INTO {INDEX}.t224_rows VALUES (1);\n", "t224_reg") + dumped, target = m.dump("t224_reg", files[DUMP], "first.dump") + assert dumped.returncode == 0, f"the dump job's dump failed:\n{_said_safely(dumped)}" + assert stat.S_IMODE(target.stat().st_mode) == 0o600, "the dump file is not 0600" + listing = subprocess.run([m.cluster.tool("pg_restore"), "--list", str(target)], + capture_output=True, text=True, timeout=120, check=False).stdout + for name in m.value("SELECT string_agg(schemaname || ' ' || tablename, ',') FROM pg_tables " + f"WHERE schemaname IN ('{REGISTER}', '{INDEX}');", "t224_reg").split(","): + schema, table = name.split() + assert re.search(rf"TABLE {schema} {table}\b", listing), f"the dump lacks {name}" + restored = subprocess.run([m.cluster.tool("pg_restore"), "--data-only", f"--schema={REGISTER}", + "--table=register_head", "--file=-", str(target)], + capture_output=True, text=True, timeout=120, check=False) + head = restored.stdout + b = m.value(f"SELECT seq FROM {REGISTER}.register_head;", "t224_reg") + assert re.search(rf"^1\t{b}\b", head, re.M) or re.search(rf"\t{b}\b", head), ( + f"the dump's register_head does not give the head {b}: pg_restore's " + f"{_said_safely(restored)}") + # M6: a sequence the indexer makes later is dumped, by the default privilege. + m.psql(f"SET ROLE {INDEXER};\nCREATE SEQUENCE {INDEX}.t224_seq_ok;\n", "t224_reg") + again, _ = m.dump("t224_reg", files[DUMP], "second.dump") + assert again.returncode == 0, f"a later sequence stopped the dump:\n{_said_safely(again)}" + # THE CONTROLS: the default privilege revoked before a sequence is made, + # and the reader's SELECT on doc_lines' sequence revoked. + m.psql(f"ALTER DEFAULT PRIVILEGES FOR ROLE {INDEXER} IN SCHEMA {INDEX} " + f"REVOKE SELECT ON SEQUENCES FROM {READER};\n", "t224_reg", user=ADMIN) + m.psql(f"SET ROLE {INDEXER};\nCREATE SEQUENCE {INDEX}.t224_seq_hidden;\n", "t224_reg") + hidden, _ = m.dump("t224_reg", files[DUMP], "third.dump") + assert hidden.returncode != 0 and "t224_seq_hidden" in hidden.stderr, _said_safely(hidden) + m.psql(f"SET ROLE {INDEXER};\nDROP SEQUENCE {INDEX}.t224_seq_hidden;\n", "t224_reg") + m.psql(f"SET ROLE {OWNER};\nREVOKE SELECT ON {REGISTER}.doc_lines_line_id_seq FROM {READER};\n", + "t224_reg") + seq, _ = m.dump("t224_reg", files[DUMP], "fourth.dump") + assert seq.returncode != 0 and "doc_lines_line_id_seq" in seq.stderr, _said_safely(seq) + # STILL CANNOT WRITE: each refused inside BEGIN READ WRITE, then ROLLBACK. + tries = [f"SELECT nextval('{REGISTER}.doc_lines_line_id_seq')", + f"UPDATE {REGISTER}.register_head SET seq = seq", + f"SELECT nextval('{INDEX}.t224_seq_ok')", f"SELECT setval('{INDEX}.t224_seq_ok', 5)", + f"INSERT INTO {INDEX}.t224_rows VALUES (2)", f"UPDATE {INDEX}.t224_rows SET id = id", + f"DELETE FROM {INDEX}.t224_rows", f"TRUNCATE {INDEX}.t224_rows"] + for statement in tries: + tried = m.as_login(DUMP, "t224_reg", f"BEGIN READ WRITE;\n{statement};\nROLLBACK;\n", + files[DUMP]) + assert tried.returncode != 0 and "42501" in tried.stderr, ( + f"the dump login's {statement!r} was not refused with 42501:\n{_said_safely(tried)}") + + +# ============================================================ the restores +def _source(request, root: Path, *, primary: bool): + """A bootstrapped register with rows: e1's logins and the dump job's, an + import, and, where `primary`, the cutover and the marker; and its dump, + by O2's command.""" + m = Managed(request, root) + service = m.database("t224_reg") + m.bootstrapped(service) + files = m.logins(service, "e1") + if primary: + m.to_primary("t224_reg", "lanes_w_e1", files["lanes_w_e1"]) + else: + proc = m.commit("t224_reg", "lanes_w_e1", files["lanes_w_e1"], + m.entry("t224_reg", "import", "lanes/LANES.md", "# Lanes")) + assert proc.returncode == 0, _said_safely(proc) + dumped, target = m.dump("t224_reg", files[DUMP], "source.dump") + assert dumped.returncode == 0, f"the source's dump failed:\n{_said_safely(dumped)}" + return m, files, target + + +def _restored(request, root: Path, source_dump: Path): + """R-P41's order on a new cluster with the admin role: the database + created first by the admin; then, through one service naming it, + `bootstrap --roles-only`, `login add e1` and `login add --dump-job`, the + restore, and `bootstrap`. Returns the target, its runs and its files.""" + target = Managed(request, root, cluster=_another_cluster(request)) + service = target.database("t224_reg") + roles = target.bootstrap(service, "--roles-only", pty_run=True) + assert roles.returncode == 0, f"bootstrap --roles-only failed:\n{_said_safely(roles)}" + files = target.logins(service, "e1", folder="passfiles-new") + env = {k: v for k, v in target.env.items() if not k.startswith("PG")} + env["PGSERVICE"] = service + restore = subprocess.run([target.cluster.tool("pg_restore"), "--exit-on-error", "--no-password", + "--dbname=t224_reg", str(source_dump)], + capture_output=True, text=True, timeout=300, env=env, check=False) + assert restore.returncode == 0, f"pg_restore through the admin service failed:\n{_said_safely(restore)}" + mark = len(target.log()) + after = target.bootstrap(service, pty_run=True) + assert after.returncode == 0, f"bootstrap after the restore failed:\n{_said_safely(after)}" + return target, roles, after, files, mark + + +def test_a_restore_from_the_dump_equals_its_source_with_new_passwords(tmp_path, request): + source, old, dump = _source(request, tmp_path / "source", primary=False) + target, roles, after, new, _mark = _restored(request, tmp_path / "target", dump) + # `--roles-only` prints the indexer's line, and `created` for each of the + # three database-level statements (option (a)). + assert sorted(_passwords(roles.stdout)) == [INDEXER], _said_safely(roles) + objects = dict(_objects(roles.stdout)) + for words in DB_LEVEL: + assert [state for what, state in objects.items() if words in what] == ["created"], ( + f"--roles-only does not print `created` for {words}:\n{_said_safely(roles)}") + assert {state for _what, state in _objects(after.stdout)} == {"unchanged"}, _said_safely(after) + assert target.catalog("t224_reg") == source.catalog("t224_reg"), "the catalogs differ" + assert target.rows("t224_reg") == source.rows("t224_reg"), "the rows differ" + for login in ("lanes_w_e1", "lanes_r_e1", DUMP): + assert not target.connects(login, "t224_reg", old[login]), ( + f"the source's password file for {login} connects to the restore") + assert target.connects(login, "t224_reg", new[login]), f"{login}'s printed line does not connect" + _no_clear_text(target.log(), {**_passwords(roles.stdout), **{ + login: path.read_text(encoding="utf-8").strip() for login, path in new.items()}}) + + +def test_a_restore_from_the_providers_copy_keeps_the_roles_and_takes_new_passwords( + tmp_path, request): + source, old, _dump = _source(request, tmp_path / "source", primary=False) + logins = ("lanes_w_e1", "lanes_r_e1", DUMP) + before = {login: source.role(login) for login in logins} + source.cluster.stop() + copy = Managed(request, tmp_path / "copy", + cluster=_another_cluster(request, data_from=source.cluster.root / "data"), + scram=False) + for login in logins: + assert copy.role(login) == before[login], f"{login} differs on the provider's copy" + assert copy.connects(login, "t224_reg", old[login]), f"{login}'s old file does not connect" + service = copy.service("t224_reg") + roles = copy.bootstrap(service, "--roles-only", pty_run=True) + assert roles.returncode == 0, f"bootstrap --roles-only failed:\n{_said_safely(roles)}" + assert {state for _what, state in _objects(roles.stdout)} == {"unchanged"}, _said_safely(roles) + printed = sorted(_passwords(roles.stdout)) # the logins alone, as pytest reports it (T224j) + assert printed == [], f"--roles-only printed a password line:\n{_said_safely(roles)}" + new: dict = {} + for who in ("e1", DUMP): + proc = copy.login("rotate", who, service) + assert proc.returncode == 0, f"login rotate {who} failed:\n{_said_safely(proc)}" + new.update(copy.passfiles(proc.stdout, "passfiles-new")) + _no_clear_text(copy.log(), _passwords(proc.stdout)) + assert sorted(new) == sorted(logins), f"the rotations printed lines for {sorted(new)}, not {sorted(logins)}" + for login in logins: + assert not copy.connects(login, "t224_reg", old[login]), f"{login}'s old file still connects" + assert copy.connects(login, "t224_reg", new[login]), f"{login}'s new line does not connect" + + +# ============================================================ check 11 +class TlsEnvironment: + """Check 11's environment on section 5.6's TLS cluster, T229's + `tls_cluster`, which `tests/pgcluster.py` gives since this line merged + line FX at T229d. Each id skips with T205's banner where `pg_engine` + finds none. + + LINE FX'S PLANNED NAMES (the coordinator, 16:50Z), NOT A CONTRACT: a + `TLSCluster` with `root_cert`, `database_name`, `url(user)`, + `client_env(user)`, `configuration(directory, database=None, + mode="index")` and `second_database(label)`. This module uses + `configuration(directory)`, a 0600 `lanes-index.conf` naming the + fixture's logins (T228's `lanes_w_fx` and `lanes_r_fx`) on loopback TCP + with `sslmode=verify-full` and `sslrootcert=` the root alone, and + `root_cert`. READ FROM F12B'S T229 TEXT, and not in that list: it is a + `pgcluster.Cluster` (`root`, `bindir`, `stop`, `start_again`), its Unix + socket at `root`; and its two start options are + `start_again(leaf_only=True)`, the leaf served without the intermediate + (T230's `[leaf-only]`), and `start_again(standby=True)`, T229d's, which + writes `standby.signal`, polls for `ready` as every start does, and + fails the start unless `pg_is_in_recovery()` is true (the test plan's + `[in-recovery]`; lane 3's batch 11 (1)).""" + + NEEDS = ("configuration", "root_cert", "root", "bindir", "stop", "start_again") + + def __init__(self, request, root: Path): + request.getfixturevalue("pg_engine") + import pgcluster + assert getattr(pgcluster, "tls_cluster", None) is not None, ( + "check 11 needs section 5.6's TLS cluster, T229's, since it always fails on a Unix " + "socket; tests/pgcluster.py has no tls_cluster yet") + self.tls = request.getfixturevalue("tls_cluster") + missing = [name for name in self.NEEDS if not hasattr(self.tls, name)] + assert not missing, f"T229's tls_cluster has no {', '.join(missing)}" + self.root = root + made = Path(self.tls.configuration(root / "conf")) + self.base = made / "lanes-index.conf" if made.is_dir() else made + self.lines = self.base.read_text(encoding="utf-8").splitlines() + self.register_url = next(line.split("=", 1)[1] for line in self.lines + if line.startswith("register_url=")) + self.login = self.register_url.split("//", 1)[1].split("@", 1)[0] + (root / "home").mkdir(exist_ok=True) + (root / "t").mkdir(exist_ok=True) + env = guard_strip_env(os.environ, strip=("T224_", "XDG_")) + env.update(HOME=str(root / "home"), XDG_CONFIG_HOME=str(root / "config"), + XDG_STATE_HOME=str(root / "state"), TMPDIR=str(root / "t"), + LANES_WORKSTATION="Eagle", LANES_NO_GITHUB="1", LC_ALL="C", + PATH=os.pathsep.join([str(self.tls.bindir), os.environ.get("PATH", os.defpath)])) + self.env = env + + def url(self, **query: str | None) -> str: + """The configuration's `register_url=`, with `query`'s parameters set, + or dropped where None.""" + head, _, tail = self.register_url.partition("?") + params = dict(piece.split("=", 1) for piece in tail.split("&") if "=" in piece) + params.update(query) + tail = "&".join(f"{k}={v}" for k, v in params.items() if v is not None) + return head + (f"?{tail}" if tail else "") + + def socket_url(self) -> str: + """The same URL at the cluster's own Unix socket.""" + head, _, tail = self.register_url.partition("?") + _scheme, _, rest = head.partition("//") + port = rest.split("@", 1)[1].split("/", 1)[0].rsplit(":", 1)[1] + database = rest.split("/", 1)[1] + return (f"postgresql://{self.login}@{quote(str(self.tls.root), safe='')}:{port}/{database}" + + (f"?{tail}" if tail else "")) + + def ready(self, register_url: str) -> subprocess.CompletedProcess: + config = _private(self.root / f"c{uuid.uuid4().hex[:8]}" / "lanes-index.conf", "\n".join( + [f"register_url={register_url}" if line.startswith("register_url=") else line + for line in self.lines]) + "\n") + env = dict(self.env, LANES_INDEX_CONFIG=str(config)) + return _run([sys.executable, str(REPO / "lanes-index"), "ready", "--expect", "index", + "--release", "0.0.0-t224", "--env", "t224"], env, self.root, pty_run=False) + + def restart(self, **option: bool) -> None: + """Stop the TLS cluster and start it again with T229's start option, + `leaf_only=` (T230's `[leaf-only]`) or `standby=True` + (`[in-recovery]`). The option is only passed on: T229d's + `start_again(standby=True)` writes `standby.signal` and proves the + recovery itself (lane 3's batch 7, ruling 2, and batch 11 (1)).""" + self.tls.stop() + self.tls.start_again(**option) + + +#: Check 11's ids: what each does to the environment, and whether it passes. +CHECK_11 = { + "passes": (lambda env: env.url(), True), + "sslmode-prefer": (lambda env: env.url(sslmode="prefer"), False), + "no-sslrootcert": (lambda env: env.url(sslrootcert=None), False), + "unix-socket": (lambda env: env.socket_url(), False), + "in-recovery": (lambda env: (env.restart(standby=True), env.url())[1], False), + # T230 (R2's S3; X's TLS rules and FR-011's server half, R09). Each meets + # the TLS cluster at a loopback host, so T104's refusal at load lets its + # URL load and check 11 meets it. + "leaf-only": (lambda env: (env.restart(leaf_only=True), env.url())[1], False), + "system-root": (lambda env: env.url(sslrootcert="system"), False), + "plaintext": (lambda env: env.url(sslmode="disable", sslrootcert=None), False), +} + + +def _says(*words: str): + """A failing check-11 case's predicate on check 11's reason: it holds + each of `words` (T224n). `words` stays on it for a failure's message.""" + def holds(reason: str) -> bool: + return all(word in reason for word in words) + holds.words = words + return holds + + +#: The fault each failing case is built to show, as a predicate on check 11's reason, +#: one for EVERY failing case (T224l, T224n): a FAIL for another cause, a restart's +#: stale port among them, does not pass. The URL's faults are in the words of +#: `_ready_check_tls` (line R `9bdd317b`), which puts them first in its connection's +#: part of the line. `[leaf-only]`'s is libpq's own, for a chain it cannot verify: the +#: server sends the leaf without its intermediate, so the root alone cannot verify it, +#: and psql 16 says, under the `LC_ALL=C` that `TlsEnvironment` sets, `connection to +#: server at "127.0.0.1", port <port> failed: SSL error: certificate verify failed`, +#: which `_ready_psql_why` puts in the line (Codex's review of P09 at `21dd3642`, +#: SHOULD 5 in lane 3's numbering). +CHECK_11_FAULT = { + "sslmode-prefer": _says("its URL carries sslmode=prefer, not sslmode=verify-full"), + "no-sslrootcert": _says("its URL carries no sslrootcert= naming the issuer's root file"), + "unix-socket": _says("its URL names a Unix socket"), + "in-recovery": _says("pg_is_in_recovery() is not false"), + "leaf-only": _says("SSL error: certificate verify failed"), + "system-root": _says("its sslrootcert= is system"), + "plaintext": _says("its URL carries sslmode=disable, not sslmode=verify-full"), +} + + +@pytest.mark.parametrize("case", list(CHECK_11)) +def test_ready_check_11_needs_tls_and_the_primary(tmp_path, request, case): + env = TlsEnvironment(request, tmp_path) + make, passes = CHECK_11[case] + proc = env.ready(make(env)) + state, reason = _checks(proc.stdout).get(11, ("", "")) + if passes: + assert state == "ok", f"[{case}] check 11 does not pass:\n{_said_safely(proc)}" + else: + assert state == "FAIL" and proc.returncode == 2, ( + f"[{case}] check 11 does not fail, or ready does not exit 2:\n{_said_safely(proc)}") + assert env.login in reason, f"[{case}] check 11 does not name the connection:\n{_said_safely(proc)}" + fault = CHECK_11_FAULT[case] + wanted = " and ".join(repr(word) for word in fault.words) + assert fault(reason), ( + f"[{case}] check 11 fails, but not for {wanted} (T224l, T224n):\n{_said_safely(proc)}") + + +#: Check 11's reason for each failing case as `ready` would print it, the URL's faults +#: in `_ready_check_tls`'s words (line R `9bdd317b`) and a connection's in libpq 16's +#: (psql under `LC_ALL=C`), for T224n's regression; and a FAIL for another cause, the +#: port a restart did not keep. +CHECK_11_SAID = { + "sslmode-prefer": "its URL carries sslmode=prefer, not sslmode=verify-full", + "no-sslrootcert": "its URL carries no sslrootcert= naming the issuer's root file", + "unix-socket": ("its URL names a Unix socket, where libpq ignores sslmode and nothing is " + "encrypted; its own pg_stat_ssl row shows ssl false: the connection is not " + "encrypted"), + "in-recovery": "pg_is_in_recovery() is not false: it reached a server in recovery, not the primary", + "leaf-only": ('its connection and read failed (c 10 s, N_a 1): psql: error: connection to server ' + 'at "127.0.0.1", port 54321 failed: SSL error: certificate verify failed'), + "system-root": ("its sslrootcert= is system, whose store holds no private root (C7, design " + "Y:2324); its connection and read failed (c 10 s, N_a 1): psql: error: " + 'connection to server at "127.0.0.1", port 54321 failed: SSL error: ' + "certificate verify failed"), + "plaintext": ("its URL carries sslmode=disable, not sslmode=verify-full; its URL carries no " + "sslrootcert= naming the issuer's root file"), +} +CHECK_11_STALE_PORT = ('its connection and read failed (c 10 s, N_a 1): psql: error: connection to ' + 'server at "127.0.0.1", port 54321 failed: Connection refused') + + +def test_each_failing_check_11_case_passes_its_own_fault_and_no_other_cause(tmp_path, monkeypatch): + """T224n (Codex's review of P09 at `21dd3642`, SHOULD 5 in lane 3's + numbering): check 11's case itself, run with a stand-in for its TLS + environment whose `ready` prints one check-11 FAIL line, with no + database. Each failing case passes its own fault and fails the same FAIL + for a restart's stale port, `[leaf-only]` among them; and every failing + case has a predicate. No password is in any line.""" + login = "lanes_w_fx" + + class StandIn: + said = "" + + def __init__(self, _request, _root): + self.login = login + + def url(self, **_query) -> str: + return f"postgresql://{login}@127.0.0.1:54321/t229" + + def socket_url(self) -> str: + return self.url() + + def restart(self, **_option) -> None: + pass + + def ready(self, _register_url: str) -> subprocess.CompletedProcess: + return subprocess.CompletedProcess( + [], 2, f"check 11: FAIL: writer {login} (`register_url=`): {StandIn.said}\n", "") + + monkeypatch.setitem(globals(), "TlsEnvironment", StandIn) + failing = [case for case, (_make, passes) in CHECK_11.items() if not passes] + for case in failing: + StandIn.said = CHECK_11_SAID[case] + test_ready_check_11_needs_tls_and_the_primary(tmp_path, None, case) + StandIn.said = CHECK_11_STALE_PORT + with pytest.raises(AssertionError, match=r"check 11 fails, but not for"): + test_ready_check_11_needs_tls_and_the_primary(tmp_path, None, case) + missing = sorted(set(failing) - set(CHECK_11_FAULT)) + assert not missing, f"no fault predicate for the failing check-11 cases {missing} (T224n)" + + +# ============================================================ tls_at_load +# +# T230, lane 1's `tls_at_load` (L1-1; T104; CLI4.5 section 2.5): each item +# through `lanes-index mode`, with `mode=index` in the file, so Q6(c) never +# answers. FP: nothing connects. A refused file is 2 from `mode`, naming the +# key and what is missing and printing no URL; 3 from `journal --write-id` +# (CO-3); and 1 under `register read --for guard`'s prefetch, form 2 (O14). +# That read's `--pid` is a stand-in for the hook started just before it +# (`hook_pid`), so the 1 is the refused file's and never the hook's age. + +#: A TCP host that is not loopback, and the loopback stand-ins. +REMOTE = "db.t230.invalid" +LOOPBACK = "127.0.0.1" + + +def _tls_url(login: str, host: str, query: str = "") -> str: + return f"postgresql://{login}@{host}:5432/register_db" + (f"?{query}" if query else "") + + +def _tls_files(root: Path) -> dict: + """Each item's configuration lines, and what it expects: `index` (it + loads), or the key its refusal names and the words of what is missing.""" + rootfile = _private(root / "ca" / "root.crt", "not a certificate: only its existence counts\n") + socket = quote("/tmp/t230-socket", safe="") + reader = f"reader_url={_tls_url('lanes_r_t230', LOOPBACK)}" + return { + "no-sslmode": ([f"register_url={_tls_url('lanes_w_t230', REMOTE)}", reader], + ("register_url=", "sslmode")), + "system-root": ([f"register_url={_tls_url('lanes_w_t230', REMOTE, 'sslmode=verify-full&sslrootcert=system')}", + reader], ("register_url=", "system")), + "missing-root": ([f"register_url={_tls_url('lanes_w_t230', REMOTE, 'sslmode=verify-full&sslrootcert=' + str(root / 'ca' / 'absent.crt'))}", + reader], ("register_url=", "sslrootcert")), + "root-file": ([f"register_url={_tls_url('lanes_w_t230', REMOTE, 'sslmode=verify-full&sslrootcert=' + str(rootfile))}", + reader], "index"), + "socket": ([f"register_url={_tls_url('lanes_w_t230', socket)}", reader], "index"), + "loopback": ([f"register_url={_tls_url('lanes_w_t230', LOOPBACK)}", reader], "index"), + "no-register-url": ([f"url={_tls_url('lanes_writer', REMOTE)}", + f"reader_url={_tls_url('lanes_reader', REMOTE)}"], "index"), + "reader-url": ([f"register_url={_tls_url('lanes_w_t230', LOOPBACK)}", + f"reader_url={_tls_url('lanes_r_t230', REMOTE)}"], ("reader_url=", "sslmode")), + "two-hosts": ([f"register_url=postgresql://lanes_w_t230@{LOOPBACK}:5432,{REMOTE}:5432/register_db", + reader], ("register_url=", "sslmode")), + } + + +@contextlib.contextmanager +def hook_pid(): + """THE HOOK'S `$$`, FOR A GUARD READ'S `--pid` (contract section 3.6: + "`--pid <pid>` ... is the hook's own pid, `$$`, in forms 2 and 4", and + "the client reads `T0` from it"). It yields the pid of a stand-in for the + hook, a `sleep` started just before the read, as a hook's own start is, + and stops it after the read. T507 cuts a guard read at `T0` + 3.75 s + from that start, and an age at or above the cut exits 2, "too late to + verify" (section 3.6's 2; `register_guard_t0`). The pytest process's own + pid is minutes old on a runner, and with it the measure module's `[m10]` + ended 2 (lane 1's round 6b census, #165 6827592167, item 2). Here + `[for-guard]`'s file is refused at load, which merge27's client answers + 1 before it checks the age, so the old pid did not change that case's + exit there; the stand-in makes its read the hook's, as the contract + says, whatever order a client checks in. It is AT-F7's stand-in, + `test_sql_register_outage.py`'s `_stand_in`, at an age of 0, as the + measure and readers modules' `hook_pid` are.""" + standin = subprocess.Popen(["sleep", "120"], start_new_session=True, + stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL) + try: + yield str(standin.pid) + finally: + # Kill it, then a reap bounded at 10 s, as `GuardSession.close()` does: a + # stand-in that a kill does not take fails the case and never hangs the + # run (T230c). + standin.kill() + try: + standin.wait(timeout=10) + except subprocess.TimeoutExpired: + standin.kill() + standin.wait(timeout=10) + + +#: The items, and the two that read the refused file through another verb. +TLS_AT_LOAD = ["no-sslmode", "system-root", "missing-root", "root-file", "socket", "loopback", + "no-register-url", "reader-url", "two-hosts", "journal-write-id", "for-guard"] + + +@pytest.mark.parametrize("item", TLS_AT_LOAD) +def test_tls_at_load_refuses_a_url_off_loopback_without_verify_full_and_a_root_file(tmp_path, item): + bench = LoginBench(tmp_path) + files = _tls_files(tmp_path) + lines, expect = files["no-sslmode" if item in ("journal-write-id", "for-guard") else item] + config = _private(tmp_path / "conf" / "lanes-index.conf", "\n".join(["mode=index", *lines, ""])) + bench.env["LANES_INDEX_CONFIG"] = str(config) + urls = [line.split("=", 1)[1] for line in lines] + if item == "journal-write-id": + proc = bench.run(["journal", "--write-id", str(uuid.uuid4()), "--not-after", "2000000000", + "--generation", str(uuid.uuid4()), "--lane", "t230", "--verb", "append-line", + "--args-sha256", "0" * 64], pty_run=False) + assert proc.returncode == 3, f"[{item}] journal --write-id on a refused file is not 3:\n{_said_safely(proc)}" + elif item == "for-guard": + repo = tmp_path / "repo" + repo.mkdir() + with hook_pid() as pid: + proc = bench.run(["register", "read", "--for", "guard", "--prefetch", "--cache", + str(tmp_path / "cache"), "--pid", pid, "--repo", str(repo)], + pty_run=False) + assert proc.returncode == 1, ( + f"[{item}] register read --for guard --prefetch on a refused file is not 1:\n{_said_safely(proc)}") + else: + proc = bench.run(["mode"], pty_run=False) + if expect == "index": + assert (proc.returncode, proc.stdout) == (0, "index\n"), f"[{item}] does not load:\n{_said_safely(proc)}" + else: + key, missing = expect + assert proc.returncode == 2 and proc.stdout == "", f"[{item}] is not refused with 2:\n{_said_safely(proc)}" + assert key in proc.stderr and missing in proc.stderr, ( + f"[{item}] the refusal does not name {key} and {missing}:\n{_said_safely(proc)}") + for url in urls: + if expect != "index" or item in ("journal-write-id", "for-guard"): + assert url not in proc.stdout + proc.stderr, f"[{item}] the refusal printed a URL" + assert bench.requests() == [], f"[{item}] a request was sent: nothing connects at load" + + +# ============================================================ lane 1's two +def test_dump_restore_privileges_hold_after_roles_only_the_restore_and_bootstrap( + tmp_path, request): + source, _old, dump = _source(request, tmp_path / "source", primary=True) + label = source.value(f"SELECT database_label FROM {REGISTER}.register_switch;", "t224_reg") + target, _roles, after, _new, mark = _restored(request, tmp_path / "target", dump) + end = len(target.log()) + db = "t224_reg" + acl = target.value(f"SELECT coalesce(datacl::text, '') FROM pg_database WHERE datname = '{db}';", + "postgres") + assert not re.search(r"(^|[{,])=[A-Za-z]*c", acl), f"PUBLIC holds CONNECT on {db}: {acl}" + target.psql("CREATE ROLE t224_outsider LOGIN PASSWORD 'outside-t224';") + outsider = _private(target.home / "passfiles" / "t224_outsider", f"*:*:{db}:t224_outsider:outside-t224\n") + refused = target.as_login("t224_outsider", db, "SELECT 1;\n", outsider) + assert refused.returncode == 2 and "permission denied for database" in refused.stderr, _said_safely(refused) + for role in (WRITER, READER, INDEXER): + assert target.value(f"SELECT has_database_privilege('{role}', '{db}', 'CONNECT');", + "postgres") == "t", f"{role} holds no CONNECT on {db}" + target.psql(f"SET ROLE {OWNER};\nCREATE FUNCTION {REGISTER}.t224_later() RETURNS int " + "LANGUAGE sql AS 'SELECT 1';\n", db) + assert target.value(f"SELECT has_function_privilege('t224_outsider', '{REGISTER}.t224_later()', " + "'EXECUTE');", db) == "f", "an outsider may execute a later function of the owner's" + # `bootstrap` after the restore re-ran no statement and wrote no label. + assert {state for _what, state in _objects(after.stdout)} == {"unchanged"}, _said_safely(after) + since = target.log()[mark:end] + ran = [found.group(1) for found in + (re.search(r"statement: (CREATE|GRANT|REVOKE|ALTER|INSERT|UPDATE)\b", line) + for line in since.splitlines()) if found] + # Only the count and the verbs: a role's statement can hold its password (T258m). + assert ran == [], (f"bootstrap after the restore re-ran {len(ran)} statement(s): " + f"{', '.join(sorted(set(ran)))}; no statement's text is shown") + restored = target.value(f"SELECT database_label FROM {REGISTER}.register_switch;", db) + assert restored == label, f"the restored register's label is {restored!r}, not the source's {label!r}" + + +def test_rotate_dump_job_changes_only_the_dump_logins_password(tmp_path, request): + m = Managed(request, tmp_path) + service = m.database("t224_reg") + m.bootstrapped(service) + old = m.logins(service, "e1") + verifiers = {login: m.role(login)["verifier"] for login in ("lanes_w_e1", "lanes_r_e1", DUMP)} + # Off a terminal it refuses with 2 and changes nothing. + piped = m.login("rotate", DUMP, service, pty_run=False) + assert piped.returncode == 2, f"rotate --dump-job through a pipe is not 2:\n{_said_safely(piped)}" + assert m.role(DUMP)["verifier"] == verifiers[DUMP], "the refused rotation changed the verifier" + # Neither an engineer nor --dump-job, or both: 64. + for argv in (["login", "rotate", "--admin-service", service], + ["login", "rotate", "e1", "--dump-job", "--admin-service", service]): + usage = m.lanes(*argv, pty_run=True) + assert usage.returncode == 64, f"{argv[1:]} is not usage, 64:\n{_said_safely(usage)}" + proc = m.login("rotate", DUMP, service) + assert proc.returncode == 0, f"login rotate --dump-job failed:\n{_said_safely(proc)}" + lines = _passwords(proc.stdout) + assert sorted(lines) == [DUMP], f"not one line, the dump login's:\n{_said_safely(proc)}" + new = m.passfiles(proc.stdout, "passfiles-new") + assert m.role(DUMP)["verifier"] != verifiers[DUMP], "the dump login's verifier did not change" + for login in ("lanes_w_e1", "lanes_r_e1"): + assert m.role(login)["verifier"] == verifiers[login], f"{login}'s verifier changed" + assert not m.connects(DUMP, "t224_reg", old[DUMP]), "the old dump password still logs in" + dumped, _target = m.dump("t224_reg", new[DUMP], "rotated.dump") + assert dumped.returncode == 0, f"the new dump password does not dump:\n{_said_safely(dumped)}" + _no_clear_text(m.log(), lines) + + +# ============================================================ phase W (T258) +# +# AT-LRMPG'S PHASE W (T258; the test plan's "Phase and kind": the logins' +# writes and reads, which run through the flipped test copy of `lanes-index`, +# test 14's second state, are W). Each case runs on a managed PostgreSQL of +# its own, as phase N's do (`Managed`): the admin's database, the bootstrap, +# and `login add` for the case's engineers, whose printed lines go into 0600 +# password files. `PhaseW` then brings the register to `primary` by AT-LR006's +# route (TP:4610-4615), as e1's writer login: an `import` entry of the render +# set at a bare origin's `main`, a `cutover` entry naming `lanes/STORE`, and +# `record_marker`. Each engineer gets a checkout of that origin, a protocol +# root naming it, and a `mode=primary` `lanes-index.conf` whose +# `register_url=` and `reader_url=` name that engineer's own two logins on +# the cluster's socket, each with its own password file (section 1.4, "One +# engineer's file"). +# +# A WRITE is `lanes-edit.sh log NOTED lane:<lane> <text>`, a READ is +# `lanes-edit.sh binding <lane>` (S3's table), each from the flipped copy, +# with `lanes-edit.sh` beside it (CLI4.5 section 6's copy rule), as T241's +# and T243's writers run; this module builds the workstation itself, since +# neither of their modules is on this branch. Each run puts T203's shim first +# on `PATH`, in a directory of its own, so the shim's log is that run's calls, +# and the mid-commit case arms its `hold` there. The two writer logins' log +# lines are the server's own: `log_connections` and `log_statement=all`, each +# line prefixed with its backend's pid (`Managed`). +# +# Rotate's write half is the fifth case (lane 3's batch 7, lane 2's item (3); +# TP:5317-5318): with the old password file, e1's write exits 69 at its +# snapshot and the journal gains nothing; with the new lines it commits once. +# T224's rotate case keeps the connection half. +# +# They FAIL UNTIL lane 1's T110 (L1-A8, `lanes-index login`) and lane 4's +# writer on primary land, its attempt loop (L4-B3) and its in-doubt rule and +# pending record (L4-B5): merge10's `lanes-edit.sh` has no primary branch and +# writes the files whatever `mode=` says, so each write case fails at its +# own assertion. `target_session_attrs` (M5) is `psql`'s alone and needs only +# L1-A8. Without PostgreSQL 16 each skips with T205's banner. + +W_DB = "t224_reg" +#: Phase W's lanes, one per engineer, and their sessions. +W_LANES = {"e1": "repoE-1", "e2": "repoE-2"} +W_SESSIONS = {"e1": "eeeeeeee-0258-4000-8000-00000000e001", + "e2": "eeeeeeee-0258-4000-8000-00000000e002"} +W_WS = "Eagle" +#: The register's punctuation, spelled by code point, as the render module +#: spells it: the em dash, the middle dot of a state cell, the arrow. +EM, DOT, ARROW = chr(0x2014), chr(0x00B7), chr(0x2192) +STORE_PATH = "lanes/STORE" +UUID_RE = r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}" +#: The pending records (L4-B5): `<state>/openRepoTools/register-pending/<d>`, +#: as T245 reads them. +PENDING = Path("openRepoTools") / "register-pending" +#: Everything a write that wrote nothing leaves as it was (T243's form). +W_STATE_SQL = f""" +SELECT md5(concat_ws('|', + (SELECT seq::text FROM {REGISTER}.register_head), + (SELECT string_agg(j::text, ',' ORDER BY j.seq) FROM {REGISTER}.journal j), + (SELECT string_agg(e::text, ',' ORDER BY e.seq, e.ord) FROM {REGISTER}.journal_edits e), + (SELECT string_agg(f::text, ',' ORDER BY f.path) FROM {REGISTER}.files f), + (SELECT string_agg(d::text, ',' ORDER BY d.line_id) FROM {REGISTER}.doc_lines d), + (SELECT string_agg(s::text, ',') FROM {REGISTER}.register_switch s))); +""" +#: A server log line under `log_line_prefix = '%p '`: the pid, the level and +#: the message. A line without the prefix continues the one before it. +LOG_LINE = re.compile(r"^([0-9]+) ([A-Z]+): (.*)$") +AUTHORIZED = re.compile(r"connection authorized: user=(\S+)") + + +def _w_row(lane: str, sid: str) -> str: + return (f"| `{lane}` | harness `{sid}` | {W_WS} / test / brett | 2026-10-01T00:00Z | none " + f"| handoffs/{lane}.md | LIVE {DOT} 2026-10-01T01:00:00Z {DOT} working |") + + +def _w_seed() -> dict: + """Phase W's register at C: a row and a log for each engineer's lane, an + empty aliases table; `lanes/repos.tsv` and `lanes/log/README.md`, which + the checkout gives and the register does not hold.""" + files = { + "lanes/LANES.md": "\n".join([ + f"# LANES.md {EM} AT-LRMPG's phase W register (T258)", "", + "| lane | session id | workstation / env / user | started (UTC) | objects owned " + "| handoff path | state |", + "|---|---|---|---|---|---|---|", + *(_w_row(W_LANES[who], W_SESSIONS[who]) for who in W_LANES), ""]), + "lanes/aliases.tsv": "# old\tnew\tutc\n", + "lanes/log/README.md": "# the object logs\n", + "lanes/repos.tsv": "# alias\towner/repo\nrepoE\topensoft/repoE\n", + } + for who, lane in W_LANES.items(): + files[f"lanes/log/{lane}.md"] = "\n".join([ + f"# lane {lane} {EM} object log (lane-collision-protocol Amendment 7)", + f"STARTED {EM} lane {lane}, session {W_SESSIONS[who]}@{W_WS}, 2026-10-01T00:00:00Z, " + f"lane:{lane} {ARROW} home opensoft/repoE; dir /work/{lane}", ""]) + return files + + +def _w_creates(files: dict) -> tuple: + """Each of `files` ({path: text}) created, then its lines appended, and + its `files` row with its digest as it renders (AT-LR006's first step).""" + edits: list = [] + rows: list = [] + for path in sorted(files): + edits.append({"ord": len(edits) + 1, "op": "create", "path": path}) + for text in files[path].rstrip("\n").split("\n"): + edits.append({"ord": len(edits) + 1, "op": "append", "path": path, "new_text": text}) + rows.append({"path": path, "present": True, "final_newline": True, + "sha256": _sha256(files[path].encode("utf-8"))}) + return edits, rows + + +def _w_git(cwd: Path, env: dict, *args: str) -> str: + """git's stdout, or an AssertionError that shows its exit and counts. Its + run is dropped before the raise (T258w; lane 2's pre-review RV9-41 of + P09 at `4895579`, B1): pytest 8.3.4 prints a long entry's locals as its + arguments where the function takes `*args`.""" + proc = subprocess.run(["git", *args], cwd=str(cwd), capture_output=True, text=True, env=env, + timeout=120, check=False) + if proc.returncode != 0: + said = f"git {' '.join(args)} in {cwd}: {_said_safely(proc)}" + del proc + raise AssertionError(said) + return proc.stdout + + +#: `_masked_path`'s mirrors, by each directory's real path (None where the +#: directory holds no masked name), and the one temporary root they share. +_PATH_MIRRORS: dict = {} +_PATH_MIRROR_ROOT: list = [] + + +def _masked_path() -> str: + """The caller's PATH with every directory kept in its place, and each one + that holds a `psql`, a `lanes-index` or a name that starts `pg_` swapped + for a private mirror of it: a directory of links, one to each of its + entries by its absolute path, those names left out. Neither an installed + indexer nor a `psql` (or a `pg_` client wrapper shipped beside it) behind + the shim's back is what a case runs, but the tools beside them are: on a + GitHub runner `postgresql-16`'s client puts `psql` in `/usr/bin` with + `git` and `bash` (and `/bin` is a link to it), so dropping the directory + dropped `git` and `bash` too (lane 1's census, #165 6807454856). A + directory that holds none of those names passes through unchanged. Each + mirror is made once per process, under one `mkdtemp` that an `atexit` + handler removes.""" + parts = [] + for part in os.environ.get("PATH", os.defpath).split(os.pathsep): + if not part: + continue + real = os.path.realpath(part) + if real not in _PATH_MIRRORS: + try: + names = os.listdir(real) + except OSError: + names = [] + masked = {name for name in names + if name in ("psql", "lanes-index") or name.startswith("pg_")} + mirror = None + if masked: + if not _PATH_MIRROR_ROOT: + _PATH_MIRROR_ROOT.append(tempfile.mkdtemp(prefix="l2-pathmask-")) + atexit.register(shutil.rmtree, _PATH_MIRROR_ROOT[0], ignore_errors=True) + mirror = os.path.join(_PATH_MIRROR_ROOT[0], str(len(_PATH_MIRRORS))) + os.mkdir(mirror) + for name in names: + if name not in masked: + os.symlink(os.path.join(real, name), os.path.join(mirror, name)) + _PATH_MIRRORS[real] = mirror + parts.append(_PATH_MIRRORS[real] or part) + return os.pathsep.join(parts) + + +def _commit_logins(log: str) -> list: + """The login of each `commit_write` call in `log`: each statement line, + or a line continuing one, that carries `commit_write(`, tied by its + backend's pid to that backend's `connection authorized` line.""" + users: dict = {} + found: list = [] + pid, in_statement = None, False + for line in log.splitlines(): + m = LOG_LINE.match(line) + if m: + pid, level, said = m.groups() + in_statement = level == "LOG" and said.startswith("statement:") + authorized = AUTHORIZED.match(said) + if authorized: + users[pid] = authorized.group(1) + else: + said = line + if in_statement and "commit_write(" in said: + found.append(users.get(pid, f"no connection authorized line for pid {pid}")) + in_statement = False + return found + + +class W258Writer: + """One `lanes-edit.sh` run, its shim's directory and its outcome. `launch` + starts it in a session of its own (`start_new_session=True`). Its thread + only reads its two pipes; the reap is the main thread's, in `wait`, or in + `stop` at the case's teardown (T258e), and it comes last: until the reader + is joined and the pipes are closed, the run is left unreaped, so the group + it leads is still its own to end (T258f).""" + + def __init__(self, who: str, proc: subprocess.Popen, psql_dir: Path, state: Path): + self.who, self.proc, self.psql_dir, self.state = who, proc, psql_dir, state + self.ended = None + self.out = self.err = "" + self.cut = False + self._cancel = threading.Event() + self._thread = threading.Thread(target=self._read, daemon=True) + self._thread.start() + + def _read(self) -> None: + """Both pipes read to their ends together, as `communicate()` reads + them, and decoded as its text mode decodes them; then closed, and + `ended` set. No wait and no reap: those are the main thread's (T258e; + Codex's review of P09 at `21dd3642`, SHOULD 6 in lane 3's numbering). + It waits `READ_POLL_S` at a time, so it always ends once `_cancel` is + set, `cut` then naming pipes left before their ends; and it closes + both pipes itself, in a `finally`, whichever way it ends (T258h; + Codex's review of P09 at `b8f9e35a`, SHOULD 4).""" + pipes = (self.proc.stdout, self.proc.stderr) + got = {pipe.fileno(): bytearray() for pipe in pipes} + live = list(got) + try: + while live and not self._cancel.is_set(): + ready, _, _ = select.select(live, [], [], READ_POLL_S) + for fd in ready: + try: + chunk = os.read(fd, 65536) + except OSError: + chunk = b"" + if chunk: + got[fd] += chunk + else: + live.remove(fd) + finally: + self.cut = bool(live) + self.out, self.err = (bytes(data).decode("utf-8", "replace").replace("\r\n", "\n") + .replace("\r", "\n") for data in got.values()) + for pipe in pipes: + pipe.close() + if not live: + self.ended = time.monotonic() + + def _cut_reader(self) -> None: + """The reader joined within `END_S`; one still reading then, a process + outside the group holding a pipe, is cut, `_cancel` set, and joined + again: it ends within one `READ_POLL_S`, its pipes closed by itself. + One still alive after that is raised here, so no reap follows it + (T258h).""" + self._thread.join(END_S) + self._cancel.set() + self._thread.join(END_S) + if self._thread.is_alive(): + raise RuntimeError(f"{self.who}'s reader did not end {END_S} s after its cut") + + def _exited(self, end: float) -> bool: + """Whether the run has exited by the monotonic `end`, as + `os.waitid(..., WNOWAIT)` sees it, which leaves it unreaped (T258f).""" + while os.waitid(os.P_PID, self.proc.pid, os.WEXITED | os.WNOHANG | os.WNOWAIT) is None: + if time.monotonic() >= end: + return False + time.sleep(0.05) + return True + + def _end_unreaped(self) -> None: + """The run's end, its reap last (T258f; the coordinator's review of P09 + at `d3a2fd5c`, item 1, #165 6938473998). While it is unreaped, the id + of the group it leads is still its own: `_signal_unreaped` ends that + group, TERM then KILL; then `_cut_reader` ends the reader, which closes + both pipes itself: it is joined within `END_S`, and one still reading + then, a process outside the group holding a pipe, is cut and joined + again, and raised where it outlives its cut (T258h; Codex's review of + P09 at `b8f9e35a`, SHOULD 4). This method closes no pipe. Only then is + the run reaped, `proc.wait(END_S)`, whose `TimeoutExpired` is raised; + no signal follows the reap, and no reap follows a reader that + `_cut_reader` raised. `_cut_reader` runs in a `finally`, so a signal + step that raises (`os.waitid`'s `ChildProcessError`, where something + else reaped the run) still has the reader ended and its pipes closed + before its error goes on, with no reap after it (T258g; Codex's review + of P09 at `d3a2fd5c`, SHOULD 3's last point; this text T258k).""" + try: + _signal_unreaped(self.proc, group=True, wait=END_S) + finally: + self._cut_reader() + self.proc.wait(END_S) + + def wait(self, timeout: float = 150) -> int: + """The run's exit and its reader's end, both within one `timeout`, and + then its reap (T258e, T258f). The exit is watched by `_exited`, which + leaves the run unreaped, so the group it leads is still its own while + the reader is joined. A run that does not exit in time fails the case, + and `stop` ends it at the teardown. A run that exited while a process of + its group still holds a pipe fails the case too, after + `_end_unreaped` has ended that group, joined the reader, closed the + pipes and only then reaped it.""" + end = time.monotonic() + timeout + if self.proc.returncode is None and not self._exited(end): + raise AssertionError(f"{self.who}'s run did not end in {timeout} s") + self._thread.join(max(0.0, end - time.monotonic())) + if self.proc.returncode is None and self._thread.is_alive(): + self._end_unreaped() + raise AssertionError(f"{self.who}'s run ended, but its pipes did not end in " + f"{timeout} s: its group was ended before its reap") + assert not self._thread.is_alive(), ( + f"{self.who}'s run ended, but its pipes did not end in {timeout} s") + self.proc.wait(END_S) + return self.proc.returncode + + def stop(self) -> None: + """This run's end at the case's teardown (T258e; Codex's review of P09 + at `21dd3642`, SHOULD 6 in lane 3's numbering; T258f): a run already + reaped, `returncode` set, gets no signal, since `wait` reaps it only + once its pipes have ended or its group has been ended. Otherwise + `_end_unreaped` ends its group, its own since `launch` started it in a + session of its own, while it is unreaped, joins its reader, closes its + pipes, and only then reaps it, raising a reap that times out. Pipes + that a process outside its group still holds are raised, not left.""" + if self.proc.returncode is None: + self._end_unreaped() + else: + self._cut_reader() + if self.cut: + raise RuntimeError(f"{self.who}'s run is reaped, but its pipes did not end in {END_S} s: " + f"a process outside its group holds them") + + @property + def code(self) -> int: + return self.proc.returncode + + def said(self) -> str: + """The writer for a failure's message, through bounds' one helper (T258l).""" + return _said_safely(subprocess.CompletedProcess([], self.code, self.out, self.err)) + + def _jsonl(self, name: str) -> list: + path = self.psql_dir / name + if not path.exists(): + return [] + return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line] + + def calls(self) -> list: + """The shim's calls that carry a request, in order.""" + return [e for e in self._jsonl(PSQL_SHIM_LOG) if e.get("kind") != "version"] + + def commit_calls(self) -> list: + return [e for e in self.calls() if "commit_write" in (e.get("stdin") or "")] + + def lookups(self) -> list: + return [e for e in self.calls() if "find_write" in (e.get("stdin") or "")] + + def ends(self) -> dict: + return {e["call"]: e for e in self._jsonl(PSQL_SHIM_ENDS) if "call" in e} + + def write_ids(self) -> list: + """Each commit call's write id, `commit_write`'s second argument, as + T243's `Writer` reads it.""" + found = [] + for call in self.commit_calls(): + m = re.search(r"commit_write\(\s*-?[0-9]+\s*,\s*'(" + UUID_RE + ")'", call.get("stdin") or "") + assert m, f"{self.who}'s commit call carries no write id: {(call.get('stdin') or '')[:300]}" + found.append(m.group(1)) + return found + + def pending(self) -> list: + where = self.state / PENDING + return sorted(p for p in where.iterdir() + if re.fullmatch(r"[0-9a-f]{64}", p.name)) if where.is_dir() else [] + + +class PhaseW: + """AT-LRMPG's phase W on one test's managed PostgreSQL (see the section's + head): the server, the register at `primary`, the flipped copy, and a + workstation for each engineer.""" + + def __init__(self, request, root: Path, engineers: tuple = ("e1", "e2")): + self.root = root + self.m = Managed(request, root / "server") + self.service = self.m.database(W_DB) + self.m.bootstrapped(self.service) + self.files = self.m.logins(self.service, *engineers, dump=False) + self.genv = self._git_env(root / "git-home") + self.seed = _w_seed() + self.origin = root / "origin.git" + _w_git(root, self.genv, "init", "-q", "--bare", "-b", "main", str(self.origin)) + seed = root / "seed" + _w_git(root, self.genv, "clone", "-q", str(self.origin), str(seed)) + for path, text in self.seed.items(): + (seed / path).parent.mkdir(parents=True, exist_ok=True) + (seed / path).write_bytes(text.encode("utf-8")) + _w_git(seed, self.genv, "add", "-A") + _w_git(seed, self.genv, "commit", "-q", "-m", "C: phase W's register (T258)") + _w_git(seed, self.genv, "push", "-q", "origin", "main") + self.c = _w_git(seed, self.genv, "rev-parse", "HEAD").strip() + self.lanes_tree = _w_git(seed, self.genv, "rev-parse", f"{self.c}:lanes").strip() + self.cut = self._to_primary() + self.bindir = root / "bin" + flipped_copy(LANES_INDEX, self.bindir, True) + for name in ("lanes-edit.sh", "repos.tsv", "lane-start"): + if (REPO / name).exists(): + shutil.copy2(str(REPO / name), str(self.bindir / name)) + self.lanes_edit = self.bindir / "lanes-edit.sh" + self.fakebin = root / "fakebin" + self.fakebin.mkdir() + (self.fakebin / "tmux").write_text("#!/bin/sh\nexit 1\n", encoding="utf-8") + (self.fakebin / "tmux").chmod(0o755) + self.engineers = {who: self._engineer(who) for who in engineers} + self.writers: list = [] + self._runs = itertools.count(1) + request.addfinalizer(self._stop) + + @staticmethod + def _git_env(home: Path) -> dict: + home.mkdir(parents=True, exist_ok=True) + env = {k: v for k, v in os.environ.items() + if not k.startswith(("GIT_", "PG", "LANES_", "TMUX", "RULE6_", "FAKE_PSQL", "CLAUDE_", + "PROJECTS_ROOT", "XDG_", "T224_"))} + env.update(HOME=str(home), GIT_CONFIG_NOSYSTEM="1", GIT_CONFIG_GLOBAL=os.devnull, + GIT_AUTHOR_NAME="T258 estate", GIT_AUTHOR_EMAIL="t258@example.invalid", + GIT_COMMITTER_NAME="T258 estate", GIT_COMMITTER_EMAIL="t258@example.invalid", + LC_ALL="C") + return env + + def _commit(self, kind: str, files: dict, **journal) -> int: + """One entry creating `files`, committed by `commit_write` as e1's + writer login; its seq.""" + edits, rows = _w_creates(files) + clock = self.m.value("SELECT (clock_timestamp() + interval '60 s')::text;", W_DB) + entry = {"journal": {"kind": kind, "verb": kind, "lane": OPERATOR, "workstation": WS, + "author": AUTHOR, "message": f"{kind} by {OPERATOR} (T258)", **journal}, + "not_after": clock, "edits": edits, "files": rows} + return self._committed(kind, entry) + + def _committed(self, kind: str, entry: dict) -> int: + """`entry` committed by `commit_write` as e1's writer login; its seq. + Kept out of `_commit`, whose `**journal` makes pytest 8.3.4 print its + locals as arguments in a long entry, so that no frame with `**` holds + the writer's run when it fails (T258w; lane 2's pre-review RV9-41 of + P09 at `4895579`, B1).""" + proc = self.m.commit(W_DB, "lanes_w_e1", self.files["lanes_w_e1"], entry) + assert proc.returncode == 0, f"the {kind} entry did not commit:\n{_said_safely(proc)}" + return _whole(proc.stdout.split()[-1], f"the {kind} entry's seq") + + def _to_primary(self) -> int: + """AT-LR006's route over C, as e1's writer login: the render set's + `import`, a `cutover` entry, then `record_marker`. The cutover's seq.""" + render = {p: t for p, t in self.seed.items() if RENDER_SET_PATH.match(p)} + self._commit("import", render, git_commit=self.c, git_tree=self.lanes_tree) + store = "".join(f"{line}\n" for line in ( + "store=primary", f"database={W_DB}", f"import={self.c}", + f"lanes-tree={self.lanes_tree}", "utc=2026-11-10T00:00:00Z")) + cut = self._commit("cutover", {STORE_PATH: store}) + client = self.m.value(f"SELECT version FROM {REGISTER}.schema_version;", W_DB) + proc = self.m.as_login("lanes_w_e1", W_DB, f"SELECT {REGISTER}.record_marker(:client, :seq, " + ":'commit', :'ws');\n", self.files["lanes_w_e1"], client=client, + seq=cut, commit=MARKER_COMMIT, ws=W_WS) + assert proc.returncode == 0 and proc.stdout.strip() == "present", _said_safely(proc) + switch = self.m.value(f"SELECT mode || ' ' || marker_state FROM {REGISTER}.register_switch;", + W_DB) + assert switch == "primary present", f"the register is not at primary with its marker: {switch}" + return cut + + def _engineer(self, who: str) -> dict: + lane, where = W_LANES[who], self.root / who + checkout = where / "checkout" + _w_git(self.root, self.genv, "clone", "-q", str(self.origin), str(checkout)) + home = where / "home" + agents = home / ".agents" + agents.mkdir(parents=True) + (agents / "workspace.yaml").write_text(f"repository: {self.origin}\npath: {checkout}\n", + encoding="utf-8") + for name in ("t", "state", "config"): + (where / name).mkdir() + conf = _private(where / "conf" / "lanes-index.conf", "\n".join([ + "mode=primary", + f"register_url={self.m.socket_url(f'lanes_w_{who}', W_DB)}", + f"register_passfile={self.files[f'lanes_w_{who}']}", + f"reader_url={self.m.socket_url(f'lanes_r_{who}', W_DB)}", + f"reader_passfile={self.files[f'lanes_r_{who}']}", + f"register_label={LABEL}", ""])) + env = dict(self.genv) + env.update(HOME=str(home), TMPDIR=str(where / "t"), XDG_STATE_HOME=str(where / "state"), + XDG_CONFIG_HOME=str(where / "config"), CLAUDE_CONFIG_DIR=str(home / ".claude"), + AGENT_PROTOCOL_ROOT=str(agents), LANES_WORKSTATION=W_WS, LANES_HOST="eagle", + LANES_OS="linux", LANES_CONTAINER="none", LANES_IN_CONTAINER="0", + LANES_NO_GITHUB="1", LANES_REPO=str(checkout), LANES_INDEX_CONFIG=str(conf), + LANES_LANE=lane, LANES_SESSION=W_SESSIONS[who]) + # THE LANE CHECKOUT, made first: on primary the writer takes `<c>` from + # `lane_checkout_path` and refuses 2 where it does not exist, naming + # `lane-checkout <lane> --create` (lane 4's T415, B14's text). + # `lane-checkout` reads the register through `canon_lane`, so it is a + # decide arm (`lanes-edit.sh:4369` at `refs/l1/V-round5`), and since + # T504 it prefetches on primary (B15 tasks:725), which needs a `psql`: + # T203's shim, with no arms, first on `PATH` in a directory of its + # own, as `launch()` gives a writer (AN13a's B2; line AF13b). + psql_dir = where / "psql-lane-checkout" + psql_dir.mkdir() + (psql_dir / "psql").write_text(PSQL_SHIM, encoding="utf-8") + (psql_dir / "psql").chmod(0o755) + (psql_dir / PSQL_SHIM_CONTROL).write_text(json.dumps( + {"psql": str(self.m.cluster.tool("psql")), "arms": []}), encoding="utf-8") + made = subprocess.run(["bash", str(self.lanes_edit), "lane-checkout", lane, "--create"], + cwd=str(checkout), capture_output=True, text=True, timeout=120, + stdin=subprocess.DEVNULL, check=False, + env=dict(env, PATH=os.pathsep.join([str(psql_dir), str(self.fakebin), + _masked_path()]))) + assert made.returncode == 0 and Path(made.stdout.strip()).is_dir(), ( + f"lane-checkout {lane} --create did not make {who}'s lane checkout:\n{_said_safely(made)}") + return {"lane": lane, "checkout": checkout, "env": env, "state": where / "state"} + + # -------------------------------------------------- running the client + def launch(self, who: str, argv: list, arms: tuple = ()) -> W258Writer: + """`lanes-edit.sh <argv>` as `who`, with T203's shim, armed with + `arms`, first on `PATH` in a directory of its own.""" + e = self.engineers[who] + psql_dir = self.root / f"psql-{next(self._runs):02d}-{who}" + psql_dir.mkdir() + (psql_dir / "psql").write_text(PSQL_SHIM, encoding="utf-8") + (psql_dir / "psql").chmod(0o755) + (psql_dir / PSQL_SHIM_CONTROL).write_text(json.dumps( + {"psql": str(self.m.cluster.tool("psql")), "arms": list(arms)}), encoding="utf-8") + env = dict(e["env"], PATH=os.pathsep.join([str(psql_dir), str(self.fakebin), + _masked_path()])) + proc = subprocess.Popen(["bash", str(self.lanes_edit), *argv], cwd=str(e["checkout"]), + env=env, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, + stderr=subprocess.PIPE, encoding="utf-8", errors="replace", + start_new_session=True) + writer = W258Writer(who, proc, psql_dir, e["state"]) + self.writers.append(writer) + return writer + + def run(self, who: str, argv: list, arms: tuple = ()) -> W258Writer: + writer = self.launch(who, argv, arms) + writer.wait() + return writer + + def note(self, who: str, text: str) -> list: + """One write: a `NOTED` line in the engineer's lane's log.""" + return ["log", "NOTED", f"lane:{W_LANES[who]}", text] + + def _stop(self) -> None: + """Each writer's `stop` (T258e), every one tried; what any of them + could not end is raised after.""" + failed = [] + for writer in self.writers: + try: + writer.stop() + except (RuntimeError, OSError, subprocess.SubprocessError) as exc: + failed.append(f"{writer.who}: {type(exc).__name__}: {exc}") + assert not failed, "phase W's teardown did not end every writer:\n" + "\n".join(failed) + + # -------------------------------------------------- the register, read by the provider + def journal_after(self) -> list: + """The journal's rows after the cutover: seq, write id, lane and verb.""" + return json.loads(self.m.value( + "SELECT coalesce(json_agg(j ORDER BY j.seq), '[]') FROM (SELECT seq, write_id::text " + f"AS write_id, lane, verb FROM {REGISTER}.journal WHERE seq > {self.cut}) j;", W_DB)) + + def state(self) -> str: + return self.m.value(W_STATE_SQL, W_DB) + + +def _hold_point(fifo: Path, writer: W258Writer, timeout: float = 90): + """`fifo` opened for writing once `writer`'s call is held on it (the + shim's `hold`), bounded: a writer that never reaches the call fails the + case and never hangs it. Closing the handle lets the call go (T243's).""" + deadline = time.monotonic() + timeout + while True: + try: + return os.fdopen(os.open(str(fifo), os.O_WRONLY | os.O_NONBLOCK), "wb") + except OSError as error: + if error.errno != errno.ENXIO: + raise + assert writer.ended is None, ( + f"{writer.who}'s run ended before its commit call was held:\n{_said_safely(writer)}") + assert time.monotonic() < deadline, f"{writer.who}'s commit call was not held in {timeout} s" + time.sleep(0.05) + + +def _w_stand_in(who: str, script: str, *args: str) -> W258Writer: + """A stand-in for a `lanes-edit.sh` run, `bash -c <script>` with `args`, + started as `PhaseW.launch` starts one, in a session of its own, with no + database (T258e's regressions).""" + proc = subprocess.Popen(["bash", "-c", script, "bash", *args], stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="utf-8", + errors="replace", start_new_session=True) + return W258Writer(who, proc, Path(os.devnull), Path(os.devnull)) + + +def test_a_phase_w_writers_thread_only_reads_its_pipes_and_the_main_thread_reaps_it(): + """T258e (Codex's review of P09 at `21dd3642`, SHOULD 6 in lane 3's + numbering), no database: a stand-in writer closes both its pipes, then + ends 0.3 s later. Its reader ends at the pipes' end and leaves it + unreaped, as `os.waitid(..., WNOWAIT)` sees once it has ended, until the + main thread's `wait` reaps it.""" + + class Phase: + writers = [_w_stand_in("w-closes", "exec >&- 2>&-; sleep 0.3")] + writer = Phase.writers[0] + try: + writer._thread.join(10) + assert not writer._thread.is_alive(), "the reader did not end at its pipes' end" + end, seen = time.monotonic() + 10, None + while seen is None and time.monotonic() < end: + try: + seen = os.waitid(os.P_PID, writer.proc.pid, os.WEXITED | os.WNOHANG | os.WNOWAIT) + except ChildProcessError: + seen = "reaped" + if seen is None: + time.sleep(0.05) + assert seen != "reaped", "the reader thread reaped the writer: the reap is the main thread's" + assert seen is not None, "the stand-in writer did not end in 10 s" + code = writer.wait(10) + assert (code, writer.out, writer.err) == (0, "", ""), f"the stand-in ended {code}, not 0" + finally: + PhaseW._stop(Phase) + + +def test_phase_w_teardown_ends_and_reaps_a_hung_writer_and_reports_a_pipe_held_outside_it( + tmp_path, monkeypatch): + """T258e (Codex's review of P09 at `21dd3642`, SHOULD 6 in lane 3's + numbering), no database, with stand-in writers started as `launch` + starts them. A writer whose pipes a process in a session of its own + still holds: the teardown ends its group and reaps it, then raises, + naming it, within its bounds. A hung writer whose group holds its pipes: + `wait` fails at its bound, and the teardown ends the group, reaps the + writer and joins its reader. A writer already reaped: the teardown sends + no signal.""" + monkeypatch.setitem(globals(), "END_S", 2.0) + + class Phase: + writers: list = [] + started: list = [] + try: + mark = tmp_path / "held" + held = _w_stand_in("w-held", '"$2" -c \'import os, sys, time; os.setsid(); ' + 'open(sys.argv[1], "w").write("held"); time.sleep(6)\' "$1" & sleep 20', + str(mark), sys.executable) + started.append(held) + end = time.monotonic() + 10 + while not (mark.exists() and mark.read_text() == "held"): + assert time.monotonic() < end, "the stand-in's holder did not start in 10 s" + time.sleep(0.05) + Phase.writers = [held] + with pytest.raises(AssertionError, match="w-held's run is reaped, but its pipes"): + PhaseW._stop(Phase) + assert held.proc.returncode is not None, "the teardown did not reap the writer" + hung = _w_stand_in("w-hung", "sleep 20 & sleep 20") + started.append(hung) + with pytest.raises(AssertionError, match="did not end in 0.5 s"): + hung.wait(0.5) + Phase.writers = [hung] + PhaseW._stop(Phase) + assert hung.proc.returncode is not None and not hung._thread.is_alive(), ( + "the teardown did not reap the hung writer and join its reader") + done = _w_stand_in("w-done", "exit 0") + started.append(done) + assert done.wait(10) == 0, "the stand-in that exits 0 did not" + sent: list = [] + with monkeypatch.context() as patch: + patch.setattr(os, "killpg", lambda *call: sent.append(("killpg", *call))) + patch.setattr(os, "kill", lambda *call: sent.append(("kill", *call))) + Phase.writers = [done] + PhaseW._stop(Phase) + assert sent == [], f"the teardown signalled a writer already reaped: {sent}" + finally: + Phase.writers = [writer for writer in started if writer.proc.returncode is None] + PhaseW._stop(Phase) + for writer in started: + writer._thread.join(15) + + +#: T258f's stand-in writer, `bash -c` with the mark file, this Python and an +#: fd as `$1`, `$2` and `$3`: a descendant in its group closes the fd, its +#: stdout (1) or its stderr (2), writes its pid and start time (`/proc` stat +#: field 22) to the mark and sleeps 30 s, holding the other pipe; the writer +#: exits 0 once the mark is written. +T258F_STAND_IN = ( + '"$2" -c \'import os, sys, time; os.close(int(sys.argv[2])); ' + 'f = open("/proc/self/stat").read().rsplit(")", 1)[1].split(); ' + 'open(sys.argv[1], "w").write(f"{os.getpid()} {f[19]}"); time.sleep(30)\' "$1" "$3" & ' + 'while [ ! -s "$1" ]; do sleep 0.05; done; exit 0') + + +def _t258f_recorded(monkeypatch, writer: W258Writer, events: list) -> None: + """Each signal by pid or group, and each reap of `writer` with whether its + reader is alive and its two pipes are closed at it, appended to `events` + in order; each is still done (T258f).""" + real_kill, real_killpg, real_wait = os.kill, os.killpg, writer.proc.wait + + def kill(pid: int, sig: int) -> None: + events.append(("kill", pid, sig)) + real_kill(pid, sig) + + def killpg(pgid: int, sig: int) -> None: + events.append(("killpg", pgid, sig)) + real_killpg(pgid, sig) + + def reap(*args, **kwargs): + events.append(("reap", writer._thread.is_alive(), writer.proc.stdout.closed, + writer.proc.stderr.closed)) + return real_wait(*args, **kwargs) + monkeypatch.setattr(os, "kill", kill) + monkeypatch.setattr(os, "killpg", killpg) + monkeypatch.setattr(writer.proc, "wait", reap) + + +@pytest.mark.skipif(not sys.platform.startswith("linux"), + reason="T258f's case reads Linux's /proc and pins by a pidfd") +@pytest.mark.parametrize("held", ["stdout", "stderr"]) +def test_a_phase_w_writer_that_exits_while_its_group_holds_a_pipe_is_reaped_after_the_group_ends( + tmp_path, monkeypatch, held): + """T258f (the coordinator's review of P09 at `d3a2fd5c`, item 1, #165 + 6938473998), no database: a stand-in writer, started as `launch` starts + one, exits 0 and leaves a descendant in its group that holds its `held` + pipe. `wait` sees the exit and leaves the writer unreaped while it joins + the reader within its bound; the pipe is still held, so it ends the + group while the writer is unreaped, joins the reader, closes both pipes + and only then reaps, and fails the case, naming it. Every signal to the + group comes before the one reap, the descendant is gone within 2 s of + `wait`'s end, though it sleeps 30 s, the reader is joined, both pipes + are closed, the exit is the writer's own 0, and the teardown sends no + signal after. Before T258f `wait` reaped the writer first, so nothing + ended its group: the reader, the pipes and the descendant were left. + The descendant's absence counts only where it is seen before those 2 s, + by `_gone_by`, so a pause of the case past them never turns its own + 30 s end into a pass (T258i; Codex's review of P09 at `b8f9e35a`, + SHOULD 5: absence was accepted before the deadline was checked).""" + monkeypatch.setitem(globals(), "END_S", 2.0) + + class Phase: + writers: list = [] + mark = tmp_path / "descendant" + writer = _w_stand_in(f"w-{held}", T258F_STAND_IN, str(mark), sys.executable, + "2" if held == "stdout" else "1") + Phase.writers = [writer] + events: list = [] + pid = started = None + try: + end = time.monotonic() + 10 + while os.waitid(os.P_PID, writer.proc.pid, os.WEXITED | os.WNOHANG | os.WNOWAIT) is None: + assert time.monotonic() < end, f"[{held}] the stand-in writer did not exit in 10 s" + time.sleep(0.05) + pid, started = mark.read_text().split() + _t258f_recorded(monkeypatch, writer, events) + with pytest.raises(AssertionError, match=f"w-{held}'s run ended, but its pipes did not"): + writer.wait(1.0) + gone = _gone_by(_whole(pid, "the stand-in's pid"), started, time.monotonic() + 2) # seen before it (T258i) + kinds = [event[0] for event in events] + ordered = kinds.count("reap") == 1 and kinds[-1] == "reap" and "killpg" in kinds + assert ordered and events[-1][1:] == (False, True, True), ( + f"[{held}] the writer was not reaped once, after every signal to its group, with " + f"its reader joined and both pipes closed: {events}") + assert gone, f"[{held}] the descendant holding the writer's {held} was not ended" + code = writer.proc.returncode + assert code == 0, f"[{held}] the writer's exit is {code}, not its own 0" + events.clear() + PhaseW._stop(Phase) + assert events == [], f"[{held}] the teardown signalled a writer already reaped: {events}" + finally: + if pid is not None: + _end_if_left(_whole(pid, "the stand-in's pid"), started) + Phase.writers = [writer] if writer.proc.returncode is None else [] + PhaseW._stop(Phase) + writer._thread.join(15) + + +def test_a_phase_w_writers_stop_joins_its_reader_and_closes_its_pipes_when_its_signal_step_raises( + tmp_path, monkeypatch): + """T258g (Codex's review of P09 at `d3a2fd5c`, SHOULD 3's last point: + `stop()` skipped its join when `_end_process()` raised), no database: a + stand-in writer, started as `launch` starts one, holds both pipes until + a FIFO barrier is released, then 0.3 s more, closes them and lives 0.5 s + more. Its `stop()` runs with the signal step, `_end_process` or + `_signal_unreaped`, made to raise `ChildProcessError` as `os.waitid` + does where something else reaped the run. That step, the signal seam, + is reached once: it records the reader alive and both pipes open, then + raises. The barrier is released at the reader's first join, by a wrapper + set as `writer._thread.join`, and only the clean-up after the seam joins + the reader. The error must reach the caller, and by then the reader must + be joined and both pipes closed. Before T258g the error left `stop()` + before the join, with the reader still reading and both pipes open; with + that bug no join runs, so the barrier is never released and the case + fails whatever the timing. The barrier replaces a 0.5 s sleep from the + stand-in's start, which a delayed case could outlive, so the old code + passed (T258j; Codex's review of P09 at `b8f9e35a`, SHOULD 6). T258j + released it at the seam, so a stall of 0.3 s or more after the seam + could still let the old code pass; it is released at the join instead + (T258k; lane 2's pre-review RV9-35, NIT 1).""" + monkeypatch.setitem(globals(), "END_S", 2.0) + barrier, seen = tmp_path / "barrier", [] + os.mkfifo(barrier) + + def release() -> None: + """The barrier released: a line written to it, opened without + blocking once the stand-in has it open to read, within 10 s.""" + end = time.monotonic() + 10 + while True: + try: + fd = os.open(barrier, os.O_WRONLY | os.O_NONBLOCK) + break + except OSError as exc: + assert exc.errno == errno.ENXIO and time.monotonic() < end, ( + f"the stand-in did not open its barrier in 10 s: {exc}") + time.sleep(0.05) + try: + os.write(fd, b"go\n") + finally: + os.close(fd) + + def fails(*args, **kwargs): + seen.append((writer._thread.is_alive(), writer.proc.stdout.closed, + writer.proc.stderr.closed)) + raise ChildProcessError("T258g's stand-in: the run was reaped elsewhere") + + def joins(timeout=None): + """The reader's join, the barrier released at its first call (T258k).""" + if not released: + released.append(True) + release() + return join(timeout) + writer = _w_stand_in("w-raises", 'read -r _ < "$1"; sleep 0.3; exec >&- 2>&-; sleep 0.5', + str(barrier)) + join, released = writer._thread.join, [] + + class Phase: + writers = [writer] + try: + with monkeypatch.context() as patch: + patch.setitem(globals(), "_end_process", fails) + patch.setitem(globals(), "_signal_unreaped", fails) + patch.setattr(writer._thread, "join", joins) + with pytest.raises(ChildProcessError, match="reaped elsewhere"): + writer.stop() + state = (writer._thread.is_alive(), writer.proc.stdout.closed, + writer.proc.stderr.closed) + assert seen == [(True, False, False)], ( + f"at the signal seam the reader alive, stdout closed and stderr closed are {seen}, " + f"not once (True, False, False)") + assert state == (False, True, True), ( + f"stop()'s signal step raised, and the reader alive, stdout closed and stderr " + f"closed are {state}, not (False, True, True)") + finally: + Phase.writers = [writer] if writer.proc.returncode is None else [] + PhaseW._stop(Phase) + writer._thread.join(15) + + +@pytest.mark.skipif(not sys.platform.startswith("linux"), + reason="T258h's case reads Linux's /proc and pins by a pidfd") +def test_a_phase_w_writers_reader_cut_by_a_pipe_held_outside_its_group_ends_and_closes_before_the_reap( + tmp_path, monkeypatch): + """T258h (Codex's review of P09 at `b8f9e35a`, SHOULD 4), no database: a + stand-in writer, started as `launch` starts one, exits 0 and leaves a + descendant in a session of its own, outside the writer's group, holding + its stdout; T258f's stand-in run under `setsid`. Its `stop()` ends the + group, which does not reach the holder, and the reader cannot reach the + pipe's end: it must be cut, end and close both pipes itself before the + one reap, and `stop()` must raise the held pipe. Before T258h the reader + blocked with no timeout: the writer was reaped with its reader alive and + both pipes open, and they stayed so.""" + monkeypatch.setitem(globals(), "END_S", 2.0) + mark = tmp_path / "descendant" + writer = _w_stand_in("w-outside", f"setsid {T258F_STAND_IN}", str(mark), sys.executable, "2") + + class Phase: + writers = [writer] + events: list = [] + pid = started = None + try: + end = time.monotonic() + 10 + while os.waitid(os.P_PID, writer.proc.pid, os.WEXITED | os.WNOHANG | os.WNOWAIT) is None: + assert time.monotonic() < end, "the stand-in writer did not exit in 10 s" + time.sleep(0.05) + pid, started = mark.read_text().split() + assert os.getsid(_whole(pid, "the stand-in's pid")) != writer.proc.pid, "the holder is in the writer's session" + _t258f_recorded(monkeypatch, writer, events) + with pytest.raises(RuntimeError, match="a process outside its group holds them"): + writer.stop() + reaps = [event for event in events if event[0] == "reap"] + state = (reaps, writer._thread.is_alive()) + assert state == ([("reap", False, True, True)], False), ( + f"with its stdout held outside its group, the writer's reaps (reader alive, stdout " + f"closed, stderr closed at each) and its reader alive are {state}") + finally: + if pid is not None: + _end_if_left(_whole(pid, "the stand-in's pid"), started) + Phase.writers = [writer] if writer.proc.returncode is None else [] + PhaseW._stop(Phase) + writer._thread.join(15) + + +def test_two_writer_logins_write_alike_and_the_log_names_each(tmp_path, request): + """Two writer logins (section 1.4, "One engineer's logins"): E1 and E2, + each with its own `register_url=` and password file, each make one + write, and both commit as one login does: one journal row each, at + consecutive seqs. The server's log ties each commit call, by its + backend's pid, to its `connection authorized` line, which names E1 or E2 + (`operations.md` act 3's step 1, "Who connected").""" + w = PhaseW(request, tmp_path) + marks = [len(w.m.log())] + writers = [] + for who in ("e1", "e2"): + writer = w.run(who, w.note(who, f"{who}'s write (T258)")) + assert writer.code == 0, f"{who}'s write on primary did not exit 0:\n{_said_safely(writer)}" + writers.append(writer) + marks.append(len(w.m.log())) + rows = w.journal_after() + assert [r["lane"] for r in rows] == [W_LANES["e1"], W_LANES["e2"]], ( + f"the journal after the cutover (seq {w.cut}) is not one row each, e1's then e2's: {rows}") + assert [r["seq"] for r in rows] == [w.cut + 1, w.cut + 2], ( + f"the two writes are not at consecutive seqs after the cutover's {w.cut}: {rows}") + for writer, row in zip(writers, rows): + assert row["write_id"] in writer.write_ids(), ( + f"{writer.who}'s row {row} is not its commit call's write id {writer.write_ids()}") + log = w.m.log() + for k, who in enumerate(("e1", "e2")): + logins = _commit_logins(log[marks[k]:marks[k + 1]]) + assert logins and set(logins) == {f"lanes_w_{who}"}, ( + f"the server's log ties {who}'s commit calls to {logins or 'no commit call'}, " + f"not to lanes_w_{who}'s connection authorized line") + + +#: AT-LRMPG's revoked login: `[revoke]`, `lanes-index login revoke e2`; and +#: `[membership-only]`, the revoke block's step 2 alone, by the admin's hand. +#: Each: the words a new connection by each refused login is refused with. +REVOKED = { + "revoke": {"lanes_w_e2": "is not permitted to log in", "lanes_r_e2": "is not permitted to log in"}, + "membership-only": {"lanes_w_e2": "permission denied for database"}, +} + + +@pytest.mark.parametrize("case", list(REVOKED)) +def test_a_revoked_login_is_refused_69_and_writes_nothing(tmp_path, request, case): + """A revoked login (section 1.4, "What a revoked login sees"; section + 2.4's `revoke`), while a session of `lanes_w_e2` is open and idle, held + by the test. `[revoke]`: `login revoke e2` prints each step's result; a + new connection by either of e2's logins is refused, FATAL 28000, so e2's + write exits 69 with nothing written, since the snapshot sent nothing that + writes, and e2's read exits 69 (S3's table); the open session's next + statement gets FATAL 57P01, or a lost connection, and never 42501 or an + answer; the admin, with no superuser, needed no `pg_signal_backend`; both + roles still exist; e1 still writes. `[membership-only]`: the revoke + block's step 2 alone, by the admin, so `lanes_w_e2` keeps `LOGIN` and + loses its membership: a new connection is refused, FATAL 42501, + "permission denied for database", and e2's write exits 69 with nothing + written.""" + w = PhaseW(request, tmp_path) + m = w.m + held = m.session("lanes_w_e2", W_DB, w.files["lanes_w_e2"]) + assert "ERROR" not in held.send("SELECT 'open';", "t258-open"), "e2's session did not open" + if case == "revoke": + proc = m.login("revoke", "e2", w.service) + assert proc.returncode == 0, f"login revoke e2 failed:\n{_said_safely(proc)}" + for login in ("lanes_w_e2", "lanes_r_e2"): + for step in (1, 2, 3): + assert re.search(rf"^login {login}, step {step}, ", proc.stdout, re.M), ( + f"login revoke printed no result for {login}'s step {step}:\n{_said_safely(proc)}") + else: + m.psql(f"REVOKE {WRITER} FROM lanes_w_e2;\n", W_DB, user=ADMIN) + role = m.role("lanes_w_e2") + assert role["canlogin"] and role["groups"] == [], ( + f"step 2 alone did not keep LOGIN and take the membership: canlogin {role.get('canlogin')}, " + f"groups {role.get('groups')}") + for login, words in REVOKED[case].items(): + refused = m.as_login(login, W_DB, "SELECT 1;\n", w.files[login]) + assert refused.returncode == 2 and words in refused.stderr, ( + f"[{case}] a new connection by {login} is not refused with {words!r}:\n{_said_safely(refused)}") + before = w.state() + write = w.run("e2", w.note("e2", f"e2's write after [{case}] (T258)")) + assert write.code == 69, f"[{case}] e2's write on primary did not exit 69:\n{_said_safely(write)}" + assert write.commit_calls() == [], ( + f"[{case}] e2's refused write sent a commit call: the snapshot must send nothing that writes") + assert w.state() == before, f"[{case}] e2's refused write changed the register" + if case != "revoke": + held.close() + return + read = w.run("e2", ["binding", W_LANES["e2"]]) + assert read.code == 69 and read.out == "", f"e2's read on primary did not exit 69:\n{_said_safely(read)}" + said = held.send(f"SELECT {REGISTER}.commit_write(NULL, NULL, NULL, NULL, NULL);", "t258-next") + ended = held.close() + said += ended.stderr + assert ("57P01" in said or "terminating connection due to administrator command" in said + or "server closed the connection" in said), ( + f"the open session's next statement after the revoke was not ended: its stderr then and at its " + f"end, {_said_safely(said, stream='stderr')}; its end, {_said_safely(ended)}") + assert "42501" not in said and "permission denied" not in said, ( + f"the open session's next statement got 42501, so revoke returned between its steps: its stderr " + f"then and at its end, {_said_safely(said, stream='stderr')}; its end, {_said_safely(ended)}") + assert ended.stdout.split() == ["open"], f"the open session got an answer after the revoke: {_said_safely(ended)!r}" + assert m.value("SELECT count(*) FROM pg_roles WHERE rolname IN ('lanes_w_e2', 'lanes_r_e2');", + "postgres") == "2", "a revoked login's role was dropped" + assert m.role(ADMIN)["super"] is False and m.value( + f"SELECT pg_has_role('{ADMIN}', 'pg_signal_backend', 'MEMBER');", "postgres") == "f", ( + f"{ADMIN} is a superuser or holds pg_signal_backend: the case proves nothing of the revoke") + mine = w.run("e1", w.note("e1", "e1 still writes after e2's revoke (T258)")) + assert mine.code == 0, f"e1's write after e2's revoke did not exit 0:\n{_said_safely(mine)}" + assert [r["lane"] for r in w.journal_after()] == [W_LANES["e1"]], ( + f"e1's write is not the journal's one new row: {w.journal_after()}") + + +def test_a_write_cut_by_a_revoke_mid_commit_is_in_doubt_and_ends_3_with_nothing_written( + tmp_path, request): + """`[mid-commit]` (section 2.4's `revoke`): the shim's `hold` blocks e2's + commit call while `login revoke e2` runs, then releases it: its `psql` + is refused at login and exits 2, which section 1.3's signals table makes + in doubt for a commit call; its lookup's tries are refused at login too, + and it exits 3 naming the id, the pending record kept. The journal holds + no entry for the id, and so answers it; nothing is written. The journal + is read here by the provider, the cluster's superuser.""" + w = PhaseW(request, tmp_path) + gate = tmp_path / "mid-commit.fifo" + os.mkfifo(str(gate)) + before = w.state() + writer = w.launch("e2", w.note("e2", "e2's write cut mid-commit (T258)"), + arms=({"mode": "hold", "match": "commit_write", "call": 1, "fifo": str(gate)},)) + held = _hold_point(gate, writer) + try: + revoke = w.m.login("revoke", "e2", w.service) + finally: + held.close() + assert revoke.returncode == 0, f"login revoke e2 failed:\n{_said_safely(revoke)}" + writer.wait(timeout=150) + assert writer.code == 3, f"e2's write cut mid-commit did not exit 3:\n{_said_safely(writer)}" + ids = writer.write_ids() + assert ids and len(set(ids)) == 1, f"e2's commit calls carried {ids}, not one write id" + write_id = ids[0] + assert write_id in writer.err, f"exit 3 does not name the write id {write_id}:\n{_said_safely(writer)}" + ends = writer.ends() + first = writer.commit_calls()[0]["call"] + assert ends.get(first, {}).get("exit") == 2, ( + f"the held commit call's psql was not refused at login with exit 2: {ends.get(first)}") + tries = writer.lookups() + assert tries and all(ends.get(t["call"], {}).get("exit") == 2 for t in tries), ( + f"the lookup's tries were not each refused at login: {[ends.get(t['call']) for t in tries]}") + records = writer.pending() + assert len(records) == 1 and write_id in records[0].read_text(encoding="utf-8"), ( + f"the pending record naming {write_id} was not kept: {records}") + assert w.m.value(f"SELECT count(*) FROM {REGISTER}.journal WHERE write_id = '{write_id}';", + W_DB) == "0", f"the journal holds an entry for the id {write_id}" + assert w.state() == before, "the write cut mid-commit changed the register" + + +#: `target_session_attrs` (M5): each id's login, the value in its URL, and +#: whether it gets in and reads `register_head`. +TARGET_SESSION_ATTRS = { + "primary": ("lanes_r_e1", "primary", True), + "read-write": ("lanes_r_e1", "read-write", False), + "read-write-bare-member": ("lanes_r_bare", "read-write", True), +} + + +@pytest.mark.parametrize("case", list(TARGET_SESSION_ATTRS)) +def test_reader_url_takes_target_session_attrs_primary_not_read_write(tmp_path, request, case): + """`target_session_attrs` (M5; section 1.4, "TLS and the endpoint"): + `lanes_r_e1`'s `psql` with `target_session_attrs=primary` in its URL + connects and reads `register_head`; with `read-write`, the connection is + refused with libpq's `session is read-only`, since the login step made + its sessions read-only by default. `lanes_r_bare`, a member made without + the step, is let in by `read-write`: the floor is the login's own, since + `ALTER ROLE ... SET` binds the role it names and not its members.""" + login, attrs, gets_in = TARGET_SESSION_ATTRS[case] + m = Managed(request, tmp_path) + service = m.database(W_DB) + m.bootstrapped(service) + files = m.logins(service, "e1", dump=False) + if login == "lanes_r_bare": + password = uuid.uuid4().hex + m.psql(f"CREATE ROLE {login} LOGIN PASSWORD '{password}';\nGRANT {READER} TO {login};\n") + files[login] = _private(m.home / "passfiles" / login, f"*:*:{W_DB}:{login}:{password}\n") + env = {k: v for k, v in m.env.items() if not k.startswith("PG")} + env.update(PGPASSFILE=str(files[login]), PGCONNECT_TIMEOUT="10") + url = f"{m.socket_url(login, W_DB)}?target_session_attrs={attrs}" + proc = subprocess.run([m.cluster.tool("psql"), "-X", "-q", "-A", "-t", "-w", "-v", "ON_ERROR_STOP=1", + "-d", url, "-c", f"SELECT seq FROM {REGISTER}.register_head;"], + capture_output=True, text=True, timeout=60, env=env, check=False) + head = m.value(f"SELECT seq FROM {REGISTER}.register_head;", W_DB) + if gets_in: + assert proc.returncode == 0 and proc.stdout.strip() == head, ( + f"[{case}] {login} with target_session_attrs={attrs} did not read the head {head}:\n" + f"{_said_safely(proc)}") + else: + assert proc.returncode == 2 and "session is read-only" in proc.stderr, ( + f"[{case}] {login} with target_session_attrs={attrs} was not refused with " + f"`session is read-only`:\n{_said_safely(proc)}") + + +def test_after_login_rotate_the_old_password_files_write_exits_69_and_the_new_lines_commit_once( + tmp_path, request): + """Rotate's write half (TP:5317-5318; lane 3's batch 7, lane 2's item + (3)): after `login rotate e1`, e1's write with the old password file + exits 69 at its snapshot, since a refused login is "refused in any other + way" (CLI:336), and the journal gains nothing; with the new lines written + into the files e1's configuration names, the write exits 0 and commits + once.""" + w = PhaseW(request, tmp_path, engineers=("e1",)) + proc = w.m.login("rotate", "e1", w.service) + assert proc.returncode == 0, f"login rotate e1 failed:\n{_said_safely(proc)}" + new = _passwords(proc.stdout) + assert sorted(new) == ["lanes_r_e1", "lanes_w_e1"], _said_safely(proc) + before = w.state() + old = w.run("e1", w.note("e1", "e1's write with the old password file (T258)")) + assert old.code == 69, f"e1's write with the old password file did not exit 69:\n{_said_safely(old)}" + assert old.commit_calls() == [], "e1's refused write sent a commit call: the 69 is the snapshot's" + assert w.state() == before, "e1's refused write changed the register" + for login, line in new.items(): + _private(w.files[login], line + "\n") + wrote = w.run("e1", w.note("e1", "e1's write with the new lines (T258)")) + assert wrote.code == 0, f"e1's write with the new lines did not exit 0:\n{_said_safely(wrote)}" + rows = w.journal_after() + assert [r["lane"] for r in rows] == [W_LANES["e1"]], f"the journal did not gain one row, e1's: {rows}" + assert set(wrote.write_ids()) == {rows[0]["write_id"]}, ( + f"the row's write id is not the one e1's commit calls carried: {wrote.write_ids()}") diff --git a/tests/test_sql_register_measure.py b/tests/test_sql_register_measure.py new file mode 100644 index 00000000..4691791d --- /dev/null +++ b/tests/test_sql_register_measure.py @@ -0,0 +1,2435 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Feature 007's test 9, the measured cost of one write and what a lane feels +(AT-9; the test plan's section 5; opensoft/openRepoTools#165). + +THIS MODULE TODAY holds lane 2's T226 part (L2-N8, phase N): + + * `test_one_write_cost_is_recorded_and_every_write_commits[<path>-<store>]` + (M1 and M2), at the fixture's settings and durable: `[new-psql-<store>]`, + 200 writes through a new `psql` process each; `[design-<store>]`, M1 in + the design's form (Q7 (A'')), a `register snapshot` call and a `register + commit` call, each a `lanes-index` process, cold once and 20 warm; and + `[session-<store>]`, 200 writes in one session under `\\timing`; + * `test_a_tls_and_scram_connect_on_loopback_is_timed_and_verified` (M12's + CI row), on T229's TLS cluster; + * lane 3's `--last` cost rows (#165 6755922262; F10-OWED item 35): + `test_journal_last_is_explained_per_statement_and_timed_against_t_r[<log>]`, + on a clone of `tmpl_imported` for its largest log and for a renamed log, + then with the journal grown 2x and 5x; and + `test_swapped_with_several_candidates_is_timed_beside_its_journal_last_calls`. + +and lane 2's T255 part (L2-W6, phase W): + + * `test_each_verb_is_timed_end_to_end_in_both_modes[<verb>]` (M7), in files + mode against a local bare origin and on primary; + * `test_each_paths_connections_and_queries_are_counted[<path>]` (M13), the + paths `m1`, `m2`, `m6`, `m7`, `m9` and `m10` once each on T229's counting + cluster (T237 writes `[m5]`); + * `test_the_image_cache_check_and_a_miss_are_timed_per_attempt`, through + lane 1's T302 API; + * `test_each_shape_on_a_delayed_relay_is_recorded[<shape>-<rtt>]`, under + section 5.6's option B, which lane 3 ruled (R-P23); + +and T254's M9 (L2-W5, phase W): +`test_the_bind_and_the_guards_set_row_state_are_timed_in_both_modes[<mode>]`, +one case per mode, `[files]` and `[primary]` (TP:6346; F12b's T254 text, +R-F11-2). T254's AT-F6 guard cases are in `tests/test_sql_register_guard.py`, +the guard line's. + +T226's guard parts, M5b's `test_todays_direct_guard_is_timed_in_its_four_parts` +and M10's `test_the_guards_register_parse_is_timed_on_a_real_sized_register_beside_todays_six_reads_through_git`, +are in `tests/test_sql_register_guard.py`, which a later line writes once +T203c's session-record helper is built. + +EACH CASE ASSERTS CORRECTNESS ONLY (section 5.4): every timed write +committed, so the journal grew by exactly n and each `write_id` appears once; +every call exited 0 with the answer it must give. Its figures go to the +job's log and to `$GITHUB_STEP_SUMMARY` where that is set, each row naming +the host, the store, the path, the statistic and n, and the link (the RTT, +TLS, and the path's connections and Query messages from M13), never into a +CI threshold. Statistics are section 5.3's: the first call apart as cold, +then median and p95 by nearest rank, min-max and n over the warm calls. + +THE REGISTER, "against an import", in T210's form (lane 2's +`test_sql_register_render.py`, whose helpers are copied below, since each +task owns one file): a files-mode estate at commit C with a bare origin, +loaded by AT-LR006's route (TP:4610-4615) as `lanes_register_writer`: +`commit_write` with an `import` entry of C's render set, a `cutover` entry +writing D21's five `lanes/STORE` fields, then `record_marker`, so the switch +is `primary` with the marker `present`. The `--last` rows clone +`tmpl_imported` instead (T227; N2's form in `test_sql_register_order.py`), +since lane 3 asks for them there, and bring the clone to `primary` the same +way. + +A WRITE HERE IS ONE APPENDED LOG LINE (a `log NOTED` line), sent as the +commit call sends it (contract section 2.3; lane 1's +`register_commit_request` at `refs/l1/T112`): one request on stdin, +`BEGIN ISOLATION LEVEL SERIALIZABLE \\; SELECT lanes_register.commit_write(n, +'<write id>', <client>, '<generation>', '<entry>'::jsonb) \\; COMMIT;`, with +section 2.2's argv and D9's commit row in `PGOPTIONS`. Its entry carries the +edit and the `files` row, the image's digest computed here, and no +structured rows, which `commit_write` takes as empty lists. + +REAL ENGINE. Every case depends on `pg_engine` (T205), so without +PostgreSQL 16 each skips with T205's banner; the cases of this module's own +clean-up helpers (from T237zzy on) are the exception, take no engine and +run on any host with bash. The engine's cases fail until lane 1's T107 +(L1-A6, the schema and `commit_write`), T111 (L1-A9, `register snapshot`), +T112 (L1-A10, `register commit`) and T114 (L1-A12, `journal --last`), lane +5's L5-A3 and L5-A5 (T506's `swapped` on primary), and lane 2's T227 (the +bootstrap's template and `tmpl_imported`), T228 and T229 (the TLS and +counting clusters, and the relay) land; T255's also wait for lane 4's L4-B3 +and L4-B8 (the verbs on primary) and lane 1's T302 (the image cache); M9 +waits for lane 4's L4-B9 and lane 5's L5-A1 and L5-B1. `lanes-index` runs as T203's flipped copy, `RENDER_GIT_HALF = True`, +so `mode=primary` loads (open point 3), and connects as two logins of this +module's own, members of the writer and the reader groups, by the cluster's +trust. + +NO WRITER'S TEXT IN A FAILURE (T255t; lane 2's pre-review RV9-37 of P09 at +`d9a1f2bf`, B1): this module is PYTEST_DONT_REWRITE, as managed is, since +pytest's assertion rewriting would add each tested operand's value to a +failure's message, a writer's raw stream or a whole `CompletedProcess` with +its stderr among them, so an assertion here reports its own message, made +through `_said_safely`, and nothing else. +""" + +from __future__ import annotations + +import base64 +import contextlib +import hashlib +import importlib.machinery +import importlib.util +import json +import os +import platform +import queue +import re +import shutil +import signal +import subprocess +import sys +import tempfile +import threading +import time +import uuid +from pathlib import Path + +import pytest + +import pgcluster +from conftest import REPO, WINDOWS_SKIP +from pgcluster import Database +from sql_register_helpers import LANES_INDEX, RENDER_GIT_HALF_LINE, flipped_copy +from test_sql_register_bounds import _said_safely # the one helper for a failure's output (T255s) +from test_sql_register_bounds import _reported # pytest's own report of a failure (T255z) + +pytestmark = [WINDOWS_SKIP, pytest.mark.skipif( + shutil.which("bash") is None or shutil.which("git") is None, + reason="the lane tooling is bash over git")] + +#: THE LANDING GATE'S TABLE (T280; `tests/sql_register_gate.py` reads it): the +#: tasks each id waits for, from the Orders of T226, T237, T254 and T255 +#: (tasks:2177, :2302, :2412, :2419 and :2428 at 204145ae). In a gated run an +#: id is skipped while any of its tasks has no marker in +#: `tests/sql_register_landed/`. M9's `[files]` waits for T107, T108, T109 and +#: T110, since it takes `pg`, whose session template needs them (T221's and +#: T231's Orders, tasks:2127 and :2231 at 204145ae; lane 3, #165 6897276895). +#: T281 removes it with the gate. +SQL_REGISTER_GATE_TABLE = { + "test_a_tls_and_scram_connect_on_loopback_is_timed_and_verified": ("T111", "T112", "T229"), # T226; tasks:2177 + "test_each_paths_connections_and_queries_are_counted": ("T302", "T413", "T414", "T415", "T421", "T422"), # T255; tasks:2428 + "test_each_shape_on_a_delayed_relay_is_recorded": ("T302", "T413", "T414", "T415", "T421", "T422"), # T255; tasks:2428 + "test_each_verb_is_timed_end_to_end_in_both_modes": ("T302", "T413", "T414", "T415", "T421", "T422"), # T255; tasks:2428 + "test_journal_last_is_explained_per_statement_and_timed_against_t_r": ("T111", "T112", "T114"), # T226; tasks:2177 + "test_one_write_cost_is_recorded_and_every_write_commits": ("T105", "T107", "T227"), # T226; tasks:2177 + "test_swapped_with_several_candidates_is_timed_beside_its_journal_last_calls": ("T111", "T112", "T114", "T401", "T402", "T403", "T404", "T405", "T406", "T407", "T408", "T504", "T505", "T506"), # T226; tasks:2177 + "test_the_bind_and_the_guards_set_row_state_are_timed_in_both_modes": ("T427", "T428", "T502", "T510"), # T254; tasks:2419 + "test_the_image_cache_check_and_a_miss_are_timed_per_attempt": ("T302", "T413", "T414", "T415", "T421", "T422"), # T255; tasks:2428 + "test_each_paths_connections_and_queries_are_counted[m5]": ("T229", "T512", "T513"), # T237; tasks:2302 + "test_the_bind_and_the_guards_set_row_state_are_timed_in_both_modes[files]": ("T107", "T108", "T109", "T110"), # T254; tasks:2412 + "test_one_write_cost_is_recorded_and_every_write_commits[design-durable]": ("T105", "T107", "T111", "T112", "T227"), # T226; tasks:2177 + "test_one_write_cost_is_recorded_and_every_write_commits[design-fixture]": ("T105", "T107", "T111", "T112", "T227"), # T226; tasks:2177 +} + +LANES_EDIT = REPO / "lanes-edit.sh" + +#: The register's schema, `register_schema=`'s default (contract section 2.5). +SCHEMA = "lanes_register" +WRITER, READER = "lanes_register_writer", "lanes_register_reader" +#: The logins `lanes-index` and this module's own calls connect as. Made +#: once per cluster, members of the writer and the reader groups, with no +#: password. +LOGIN_WRITER, LOGIN_READER = "t226_register_writer", "t226_register_reader" +#: T227's template with test 7's register imported, and the database-level +#: grants a clone does not copy (section 1.4; N2's `CONNECT_TO`). +IMPORTED = "tmpl_imported" +CONNECT_TO = "lanes_register_writer, lanes_register_reader, lanes_indexer" + +WS = "Eagle" +AUTHOR = "T226 measure <t226@example.invalid>" +OPERATOR = "repoA-2" +MARKER_COMMIT = "e" * 40 +STORE_UTC = "2026-11-09T10:00:00Z" + +#: The register's punctuation, spelled by code point so no raw character +#: enters this file: the em dash, the middle dot of a state cell, the arrow. +EM, DOT, ARROW = chr(0x2014), chr(0x00B7), chr(0x2192) + +SID_A1 = "aaaaaaaa-0001-4000-8000-00000000a001" +SID_A2 = "aaaaaaaa-0003-4000-8000-00000000a003" +SID_Z1 = "eeeeeeee-0001-4000-8000-00000000e001" +TIP = "0123456789abcdef0123456789abcdef01234567" + +RENDER_SET = re.compile(r"^lanes/(LANES\.md|aliases\.tsv|archive/[^/]+\.md" + r"|log/(?!README\.md$)[^/]+\.md)$") +LOG_PATH = re.compile(r"^lanes/log/(?!README\.md$)[^/]+\.md$") +STORE_PATH = "lanes/STORE" + +#: Section 2.2's one argv for every register call (F10-OWED item 4), and +#: D9's rows as `PGOPTIONS` (lane 1's `REGISTER_BOUNDS` at `refs/l1/T114`, +#: CLI412:250-255): the commit's, and the reader's for `journal --last`. +PSQL_REGISTER_ARGV = ("--no-psqlrc", "-X", "-q", "-A", "-t", "-v", "ON_ERROR_STOP=1", + "-v", "VERBOSITY=verbose", "-v", "SHOW_CONTEXT=never") +COMMIT_OPTIONS = "-c lock_timeout=2000 -c statement_timeout=5000" +READ_STATEMENT_MS = 3000 +#: `T_r` = `N_a`*`c` + 4 s (CLI412:255): 6 s at `c` = 2 and one address, +#: the URL's `connect_timeout` default (CLI412:296). +T_R_S = 1 * 2 + 4 + +N_WRITES = 200 # M1 and M2: at least 200 writes (section 5.3; R1) +N_WARM = 20 # M7, M12 and act 3's rows: 20 warm runs and the first + +def _row(lane: str, sid: str, state: str, started: str = "2026-10-01T00:00Z") -> str: + return (f"| `{lane}` | harness `{sid}` | Eagle / test / brett | {started} | none " + f"| handoffs/{lane}.md | {state} |") + + +#: AT-1's fixture register at C ("Fixture"): three lanes, one of them +#: archived; `aliases.tsv` entries; a lane with `HOLD`, `LANDING` and +#: `LANDED` lines; a log with `WORD` lines whose UTC carries milliseconds +#: (Q4(d)(i)). `lanes/repos.tsv` and `lanes/log/README.md` are outside the +#: render set, and `register snapshot --tree` takes them from the checkout. +SEED = { + "lanes/LANES.md": "\n".join([ + f"# LANES.md {EM} test 1's fixture register", + "", + "| lane | session id | workstation / env / user | started (UTC) | objects owned " + "| handoff path | state |", + "|---|---|---|---|---|---|---|", + _row("repoA-1", SID_A1, f"LIVE {DOT} 2026-10-01T01:00:00Z {DOT} working"), + _row("repoA-2", SID_A2, f"PAUSED {DOT} 2026-10-01T02:00:00Z {DOT} parked"), + "", + f"HOLD {EM} lane repoA-1 (Eagle), window w, 2026-10-01T03:00:00Z: opensoft/repoA main " + f"{TIP} for a frozen window", + f"LANDING {EM} lane repoA-1, session {SID_A1}@Eagle, 2026-10-01T03:10:00Z, PR #7 into " + f"opensoft/repoA main", + f"LANDED {EM} lane repoA-1, session {SID_A1}@Eagle, 2026-10-01T03:15:00Z, PR #7 into " + f"opensoft/repoA main {ARROW} abc1234", + ""]), + "lanes/aliases.tsv": "# old\tnew\tutc\nrepoOld-1\trepoA-2\t2026-09-30T00:00:00Z\n", + "lanes/archive/LANES-retired.md": "\n".join([ + "# retired rows (Amendment 19(d))", "", + _row("repoZ-1", SID_Z1, f"RETIRED {DOT} 2026-09-02T00:00:00Z {DOT} retired"), + ""]), + "lanes/log/repoA-1.md": "\n".join([ + f"# lane repoA-1 {EM} object log (lane-collision-protocol Amendment 7)", + f"STARTED {EM} lane repoA-1, session {SID_A1}@Eagle, 2026-10-01T00:00:00Z, " + f"lane:repoA-1 {ARROW} home opensoft/repoA; dir /work/repoA1", + ""]), + "lanes/log/repoA-2.md": "\n".join([ + f"# lane repoA-2 {EM} object log (lane-collision-protocol Amendment 7)", + f"STARTED {EM} lane repoA-2, session {SID_A2}@Eagle, 2026-10-01T02:00:00Z, " + f"lane:repoA-2 {ARROW} home opensoft/repoA; dir /work/repoA2", + f"NOTED {EM} lane repoA-2, session {SID_A2}@Eagle, 2026-10-01T02:10:00.123Z, " + f"lane:repoA-2 {EM} a stamp with milliseconds", + f"NOTED {EM} lane repoA-2, session {SID_A2}@Eagle, 2026-10-01T02:11:00.456Z, " + f"lane:repoA-2 {EM} another", + ""]), + "lanes/log/README.md": "# the object logs\n", + "lanes/repos.tsv": "# alias\towner/repo\nrepoA\topensoft/repoA\n", +} + + +# ------------------------------------------------------------------ the estate +def git(cwd: Path, *args: str, env: dict | None = None) -> str: + """git's stdout, or an AssertionError that shows its exit and counts. Its + run is dropped before the raise (T255zf; lane 2's pre-review RV9-41 of + P09 at `4895579`, B1): pytest 8.3.4 prints a long entry's locals as its + arguments where the function takes `*args`, so `proc`, both streams, + would show under an explicit `--tb=long`.""" + proc = subprocess.run(["git", *args], cwd=str(cwd), capture_output=True, text=True, + env=env, check=False) + if proc.returncode != 0: + said = f"git {' '.join(args)} in {cwd}: {_said_safely(proc)}" + del proc + raise AssertionError(said) + return proc.stdout + + +def git_env(home: Path) -> dict: + """A git with no person's configuration in it, and an identity of its own.""" + env = {k: v for k, v in os.environ.items() + if not k.startswith(("GIT_", "PG", "LANES_", "TMUX"))} + env.update(HOME=str(home), GIT_CONFIG_NOSYSTEM="1", GIT_CONFIG_GLOBAL=os.devnull, + GIT_AUTHOR_NAME="T226 estate", GIT_AUTHOR_EMAIL="t226@example.invalid", + GIT_COMMITTER_NAME="T226 estate", GIT_COMMITTER_EMAIL="t226@example.invalid", + LC_ALL="C") + return env + + +class Estate: + """A bare origin and the lane's checkout at C: SEED (or `files`) committed + and pushed to `main`. `register snapshot --checkout` reads + `lanes/repos.tsv` and `lanes/log/README.md` from its `origin/main`.""" + + def __init__(self, root: Path, files: dict = None): + self.root = root + self.home = root / "home" + self.home.mkdir(parents=True, exist_ok=True) + self.env = git_env(self.home) + self.origin = root / "origin.git" + self.checkout = root / "checkout" + git(root, "init", "-q", "--bare", "-b", "main", str(self.origin), env=self.env) + git(root, "clone", "-q", str(self.origin), str(self.checkout), env=self.env) + self.files = dict(files if files is not None else SEED) + for path, text in self.files.items(): + target = self.checkout / path + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(text.encode("utf-8")) + git(self.checkout, "add", "-A", env=self.env) + git(self.checkout, "commit", "-q", "-m", "C: the fixture register", env=self.env) + git(self.checkout, "push", "-q", "origin", "main", env=self.env) + self.c = git(self.checkout, "rev-parse", "HEAD", env=self.env).strip() + self.lanes_tree = git(self.checkout, "rev-parse", f"{self.c}:lanes", env=self.env).strip() + + def render_set(self) -> dict: + """C's render set, {path: bytes}.""" + return {p: t.encode("utf-8") for p, t in self.files.items() if RENDER_SET.match(p)} + + def state(self) -> tuple: + """What a write through the storage layer never changes in the + checkout: HEAD, `status --porcelain=v1 -uall`, the index's digest and + `origin/main`.""" + index = self.checkout / ".git" / "index" + return (git(self.checkout, "rev-parse", "HEAD", env=self.env), + git(self.checkout, "status", "--porcelain=v1", "-uall", env=self.env), + hashlib.sha256(index.read_bytes()).hexdigest() if index.exists() else "-", + git(self.checkout, "rev-parse", "origin/main", env=self.env)) + + +# ------------------------------------------------------------------ the SQL side +def psql(db, script: str, role: str = None) -> subprocess.CompletedProcess: + """One `psql` as the fixture's superuser, as `role` where one is named, + with the commit call's settings, so a refusal's first stderr line is + `ERROR: <SQLSTATE>: <message>`.""" + head = "\\set VERBOSITY verbose\n\\set SHOW_CONTEXT never\nSET client_encoding = 'UTF8';\n" + if role: + head += f"SET ROLE {role};\n" + return subprocess.run([db.psql_bin, "-X", "-q", "-A", "-t", "-v", "ON_ERROR_STOP=1"], + input=head + script, capture_output=True, encoding="utf-8", + errors="replace", env=db.env(appname="t226"), timeout=120, check=False) + + +def sql(db, script: str, role: str = None) -> str: + proc = psql(db, script, role) + assert proc.returncode == 0, (f"psql{' as ' + role if role else ''} exited " + f"{proc.returncode}: {_said_safely(proc.stderr.strip())}\n{script}") + return proc.stdout.strip() + + +def rows(db, query: str) -> list: + """`query`'s rows as JSON objects, read in the register's schema.""" + out = sql(db, f"SET search_path TO {SCHEMA};\n" + f"SELECT coalesce(jsonb_agg(q), '[]'::jsonb) FROM ({query}) q;") + return json.loads(out.splitlines()[-1]) + + +def head(db) -> int: + return rows(db, "SELECT seq FROM register_head")[0]["seq"] + + +def _lines(data: bytes) -> list: + text = data.decode("utf-8") + assert text.endswith("\n"), "every fixture file ends with a newline" + return text[:-1].split("\n") + + +def _entry(kind: str, verb: str, journal: dict = None, **parts) -> dict: + body = {"kind": kind, "verb": verb, "lane": OPERATOR, "workstation": WS, "author": AUTHOR, + "message": f"t226: {kind}"} + body.update(journal or {}) + return {"journal": body, "not_after": "2100-01-01T00:00:00Z", **parts} + + +def _creates(files: dict) -> tuple: + """Each of `files` ({path: bytes}) created, then its lines appended, and + each path's digest as it renders: the edits and the `files` rows.""" + edits, ordinal = [], 0 + for path in sorted(files): + ordinal += 1 + edits.append({"ord": ordinal, "op": "create", "path": path}) + for text in _lines(files[path]): + ordinal += 1 + edits.append({"ord": ordinal, "op": "append", "path": path, "new_text": text}) + return edits, [{"path": p, "present": True, "sha256": hashlib.sha256(files[p]).hexdigest(), + "final_newline": True} for p in sorted(files)] + + +def _commit_call(db, base: int, body: dict) -> int: + """The commit call as the writer sends it, as `lanes_register_writer` + (section 1.3's step 3; AT-LR006's fixture), and the seq it committed.""" + gen = rows(db, "SELECT generation FROM register_switch")[0]["generation"] + version = rows(db, "SELECT version FROM schema_version")[0]["version"] + literal = json.dumps(body, ensure_ascii=True).replace("'", "''") + out = sql(db, f"BEGIN ISOLATION LEVEL SERIALIZABLE;\n" + f"SELECT {SCHEMA}.commit_write({base}, '{uuid.uuid4()}'::uuid, {version}, " + f"'{gen}'::uuid, '{literal}'::jsonb);\nCOMMIT;", WRITER) + return _whole(out.splitlines()[-1], "commit_write's seq on psql's last line") + + +def import_to_primary(db, estate: Estate) -> int: + """AT-LR006's route (TP:4610-4615) over C: an `import` entry of C's render + set, a `cutover` entry, then `record_marker`, by the documented functions + as `lanes_register_writer`. Returns the import's seq.""" + edits, files = _creates(estate.render_set()) + imported = _commit_call(db, head(db), _entry( + "import", "import", {"git_commit": estate.c, "git_tree": estate.lanes_tree}, + edits=edits, files=files)) + store = "".join(f"{line}\n" for line in ( + "store=primary", "database=t226", f"import={estate.c}", + f"lanes-tree={estate.lanes_tree}", f"utc={STORE_UTC}")).encode("utf-8") + edits, files = _creates({STORE_PATH: store}) + cut = _commit_call(db, imported, _entry("cutover", "cutover", edits=edits, files=files)) + version = rows(db, "SELECT version FROM schema_version")[0]["version"] + marker = sql(db, f"SELECT {SCHEMA}.record_marker({version}, {cut}, '{MARKER_COMMIT}', " + f"'{WS}');", WRITER) + assert marker.splitlines()[-1] == "present", f"record_marker answered {marker!r}" + assert rows(db, "SELECT mode, marker_state FROM register_switch") == \ + [{"mode": "primary", "marker_state": "present"}] + return imported + + +# ------------------------------------------------------------------ lanes-index +def require_the_constant() -> None: + """The flipped copy needs Q6(c)'s constant (lane 1's T105, L1-A4): an + assertion, so a case without it fails by saying so.""" + assert len(RENDER_GIT_HALF_LINE.findall(LANES_INDEX.read_bytes())) == 1, ( + f"{LANES_INDEX} holds no single `RENDER_GIT_HALF = ...` line, Q6(c)'s build constant " + f"(L1-A4, lane 1's T105), so no copy can be flipped to load mode=primary") + + +def flipped(tmp_path: Path, name: str = "bin") -> Path: + """T203's flipped copy, `RENDER_GIT_HALF = True`, so `mode=primary` loads, + with `lanes-edit.sh` beside it (the copy rule, CLI4.5 section 6).""" + require_the_constant() + copy = flipped_copy(LANES_INDEX, tmp_path / name, True) + shutil.copy2(str(LANES_EDIT), str(copy.parent / "lanes-edit.sh")) + return copy + + +def ensure_logins(db) -> None: + """The writer's and the reader's login, once per cluster (roles are + cluster-wide), members of their groups, with no password.""" + for login, group in ((LOGIN_WRITER, WRITER), (LOGIN_READER, READER)): + sql(db, f"DO $l$ BEGIN CREATE ROLE {login} LOGIN IN ROLE {group}; " + f"EXCEPTION WHEN duplicate_object THEN NULL; END $l$;") + + +def primary_config(path: Path, register_url: str, reader_url: str, + passfile: Path | None = None) -> Path: + """A 0600 `lanes-index.conf` with `mode=primary` and the register's two + URLs (contract section 2.5), outside every work tree.""" + lines = ["mode=primary", f"register_url={register_url}", f"reader_url={reader_url}"] + if passfile is not None: + lines += [f"register_passfile={passfile}", f"reader_passfile={passfile}"] + path.write_text("\n".join(lines) + "\n", encoding="utf-8") + path.chmod(0o600) + return path + + +def index_env(tmp_path: Path, conf: Path, home: Path, **extra) -> dict: + """The environment `lanes-index` runs in: no inherited `PG*`, `LANES_*`, + `GIT_*` or `TMUX*` (#160's run-wide `LANES_INDEX=off` among them), this + case's configuration, state directory and git identity.""" + env = {k: v for k, v in os.environ.items() + if not k.startswith(("PG", "LANES_", "GIT_", "TMUX"))} + env.update(git_env(home)) + env.update(LANES_INDEX_CONFIG=str(conf), XDG_STATE_HOME=str(tmp_path / "state"), LC_ALL="C") + env.update(extra) + return env + + +def run_index(copy: Path, args, env: dict, cwd: Path = None) -> subprocess.CompletedProcess: + return subprocess.run([sys.executable, str(copy), *[str(a) for a in args]], + capture_output=True, encoding="utf-8", errors="replace", env=env, + timeout=120, cwd=str(cwd) if cwd else None, check=False, + stdin=subprocess.DEVNULL) + + +def keys(stdout: str) -> dict: + """A `key=value` output's keys, each its first value (section 3.2).""" + found = {} + for line in stdout.splitlines(): + key, sep, value = line.partition("=") + if sep and key not in found: + found[key] = value + return found + + +def utc_of(epoch: int) -> str: + return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(epoch)) + + +def _canonical_rows(changes: list, images: dict) -> str: + """Section 3.2's canonical rows for every path in `changes.tsv`, sorted by + path bytewise, each LF-ended: `<path>` TAB `1` TAB `<sha256>`, or `0` and + `-` for a path the write removes.""" + out = [] + for path in sorted({c[1] for c in changes}, key=lambda p: p.encode("utf-8")): + if path in images: + out.append(f"{path}\t1\t{hashlib.sha256(images[path]).hexdigest()}\n") + else: + out.append(f"{path}\t0\t-\n") + return "".join(out) + + +class PrimaryRegister: + """C imported and brought to `primary`, a flipped copy, and the + configuration that reaches the test's database as this module's logins.""" + + def __init__(self, pg, tmp_path: Path, files: dict = None): + self.pg = pg + self.estate = Estate(tmp_path / "estate", files) + self.imported = import_to_primary(pg, self.estate) + ensure_logins(pg) + self.copy = flipped(tmp_path) + (tmp_path / "conf").mkdir() + conf = primary_config(tmp_path / "conf" / "lanes-index.conf", pg.url(LOGIN_WRITER), + pg.url(LOGIN_READER)) + self.env = index_env(tmp_path, conf, self.estate.home) + + +# ------------------------------------------------------------------ the fake writer +def _edit_log_noted(lane: str, sid: str, words: str): + """`log NOTED`'s line on `lane`'s log, as an edit of the scratch tree.""" + def edit(tree: Path, utc: str) -> dict: + line = f"NOTED {EM} lane {lane}, session {sid}@{WS}, {utc}, lane:{lane} {EM} {words}" + path = tree / "lanes" / "log" / f"{lane}.md" + path.write_bytes(path.read_bytes() + line.encode("utf-8") + b"\n") + return {"line": line, "renames": {}} + return edit + + +def _edit_rename_log(old: str, new: str): + """A log renamed whole (`renames.tsv`, contract section 3.3; the verb's + `LOG_RENAMED_FROM`, Y:5060): a `D` and an `A` line in `changes.tsv`.""" + def edit(tree: Path, utc: str) -> dict: + (tree / new).parent.mkdir(parents=True, exist_ok=True) + os.replace(str(tree / old), str(tree / new)) + return {"line": None, "renames": {old: new}} + return edit + + +def fake_write(copy: Path, env: dict, checkout: Path, root: Path, lane: str, verb: str, + edit, message: str) -> dict: + """One attempt of the storage layer's write entry, as T210's + `projection_entry` makes it (contract sections 3.2 and 3.3): `register + snapshot --write-id new ... --tree <root>/tree --checkout <c>`; on 0 + alone, the edit, the attempt directory (with `renames.tsv` where the + edit renamed) and `register commit`. Returns each call, the code (the + snapshot's where it did not answer 0, else the commit's) and the + snapshot's fields.""" + args_sha256 = hashlib.sha256(json.dumps([lane, verb, message]).encode("utf-8")).hexdigest() + root.mkdir(parents=True, exist_ok=True) + out = {"snapshot": None, "commit": None, "code": None, "fields": {}, "line": None} + snap = run_index(copy, ["register", "snapshot", "--write-id", "new", "--lane", lane, + "--verb", verb, "--args-sha256", args_sha256, + "--tree", root / "tree", "--checkout", checkout], env) + out["snapshot"] = snap + if snap.returncode != 0: + out["code"] = snap.returncode + return out + fields = out["fields"] = keys(snap.stdout) + tree = root / "tree" + (root / "snapshot").write_text(snap.stdout, encoding="utf-8") + done = edit(tree, utc_of(_whole(fields["clock"], "the snapshot's clock"))) + out["line"] = done["line"] + git(tree, "add", "-A", "--", "lanes", env=env) + changes = [] + for raw in git(tree, "diff", "--cached", "--no-renames", "--raw", "--no-abbrev", "HEAD", + env=env).splitlines(): + meta, path = raw.split("\t", 1) + parts = meta.split() + changes.append((parts[4], path, parts[2], parts[3])) + assert changes, "the edit staged a change" + (root / "changes.tsv").write_text( + "".join(f"{s}\t{p}\t{o}\t{n}\n" for s, p, o, n in changes), encoding="utf-8") + if done["renames"]: + (root / "renames.tsv").write_text( + "".join(f"{a}\t{b}\n" for a, b in done["renames"].items()), encoding="utf-8") + images = {} + for status, path, _old, _new in changes: + if status in ("A", "M"): + images[path] = (tree / path).read_bytes() + target = root / "images" / path + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(images[path]) + (root / "files").write_text(_canonical_rows(changes, images), encoding="utf-8") + (root / "msg").write_text(message, encoding="utf-8") + (root / "author").write_text(AUTHOR + "\n", encoding="utf-8") + (root / "not_after").write_text(fields["not_after"] + "\n", encoding="utf-8") + commit = run_index(copy, ["register", "commit", "--write-id", fields["write_id"], + "--generation", fields["generation"], "--lane", lane, + "--verb", verb, "--args-sha256", args_sha256, + "--workstation", WS, root], env) + out["commit"] = commit + out["code"] = commit.returncode + return out + + +# ------------------------------------------------------------------ the writes +def sha256(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def images_of(db, paths) -> dict: + """`render_file` (lane 1's T107) of each of `paths`, {path: bytes}.""" + wanted = ", ".join("'" + p.replace("'", "''") + "'" for p in paths) + return {r["path"]: base64.b64decode(r["b64"]) for r in rows( + db, f"SELECT path, encode(render_file(path), 'base64') AS b64 FROM files " + f"WHERE path IN ({wanted}) ORDER BY path")} + + +class Appends: + """Writes of appended log lines, each built as AT-LR006 builds an entry: + the edits and each touched path's `files` row, whose digest is the image + `render_file` gives after the write, tracked here from the images read + at the start. `base` is the head each next write is sent against.""" + + def __init__(self, db, paths) -> None: + self.db = db + self.images = images_of(db, paths) + missing = sorted(set(paths) - set(self.images)) + assert not missing, f"no such file in the register: {missing}" + switch = rows(db, "SELECT generation FROM register_switch")[0] + self.generation = switch["generation"] + self.version = rows(db, "SELECT version FROM schema_version")[0]["version"] + self.base = head(db) + self.write_ids: list = [] + + def entry(self, lane: str, path: str, texts) -> dict: + edits = [] + for text in texts: + assert "\n" not in text and "\r" not in text + edits.append({"ord": len(edits) + 1, "op": "append", "path": path, "new_text": text}) + self.images[path] += text.encode("utf-8") + b"\n" + args = sha256(json.dumps([lane, "log", list(texts)]).encode("utf-8")) + return _entry("write", "log", {"lane": lane, "args_sha256": args}, edits=edits, + files=[{"path": path, "present": True, "sha256": sha256(self.images[path]), + "final_newline": True}]) + + def statements(self, entry: dict) -> list: + """The commit call's three statements for the next write (lane 1's + `register_commit_request`), and the base moved on by one.""" + write_id = str(uuid.uuid4()) + self.write_ids.append(write_id) + literal = json.dumps(entry, ensure_ascii=True, separators=(",", ":")).replace("'", "''") + sent = ["BEGIN ISOLATION LEVEL SERIALIZABLE", + f"SELECT {SCHEMA}.commit_write({self.base}, '{write_id}', {self.version}, " + f"'{self.generation}', '{literal}'::jsonb)", + "COMMIT"] + self.base += 1 + return sent + + +def one_call(db, statements: list) -> subprocess.CompletedProcess: + """One commit call through a new `psql` process: ONE request, the + statements joined by `\\;`, as the writer's login with D9's commit row.""" + env = db.env(LOGIN_WRITER, appname="t226-commit") + env["PGOPTIONS"] = COMMIT_OPTIONS + return subprocess.run([db.psql_bin, *PSQL_REGISTER_ARGV], input=" \\; ".join(statements) + ";\n", + capture_output=True, encoding="utf-8", errors="replace", env=env, + timeout=60, check=False) + + +def in_one_session(db, writes: list, timing: bool = False) -> subprocess.CompletedProcess: + """`writes` (each the commit call's three statements) in ONE `psql` + session as the writer's login, each statement its own Query, under + `\\timing` where asked (M2: it leaves out the client).""" + script = ["\\timing on"] if timing else [] + for statements in writes: + script += [s + ";" for s in statements] + env = db.env(LOGIN_WRITER, appname="t226-session") + return subprocess.run([db.psql_bin, "--no-psqlrc", "-X", "-A", "-t", "-v", "ON_ERROR_STOP=1"], + input="\n".join(script) + "\n", capture_output=True, encoding="utf-8", + errors="replace", env=env, timeout=1800, check=False) + + +def committed_once(db, before: int, write_ids: list) -> None: + """Section 5.3's correctness alongside: the journal grew by exactly n + above `before`, and each of the writes' ids appears once.""" + n = len(write_ids) + assert head(db) == before + n, f"the head is {head(db)}, not {before} + {n}" + grown = rows(db, f"SELECT count(*) AS n, count(DISTINCT write_id) AS d FROM journal " + f"WHERE seq > {before}")[0] + assert grown == {"n": n, "d": n}, f"the journal grew by {grown}, not {n} distinct writes" + ids = ", ".join(f"'{w}'" for w in write_ids) + found = rows(db, f"SELECT count(*) AS n FROM journal WHERE write_id IN ({ids})")[0]["n"] + assert found == n, f"{found} of the {n} write ids are in the journal" + + +# ------------------------------------------------------------------ the record +def _stats(samples: list) -> dict: + """Section 5.3's statistics: median and p95 by nearest rank, min-max, n.""" + ordered = sorted(samples) + rank = lambda p: ordered[max(0, -(-p * len(ordered) // 100) - 1)] # noqa: E731 + return {"median": rank(50), "p95": rank(95), "min": ordered[0], "max": ordered[-1], + "n": len(ordered)} + + +def figure(measure: str, store: str, path: str, times_ms: list, link: str, + cold: bool = True) -> str: + """One recorded row (section 5.4): the host, the store, the path, the + statistic and n, and the link.""" + warm = _stats(times_ms[1:] if cold else times_ms) + first = f"cold {times_ms[0]:.2f} ms" if cold else "-" + return (f"| {measure} | {platform.node()}, {store} | {path} | {first} | median " + f"{warm['median']:.2f} ms, p95 {warm['p95']:.2f} ms, {warm['min']:.2f}-" + f"{warm['max']:.2f} ms, n={warm['n']} | {link} |") + + +def record(lines: list) -> None: + """The job's log, and `$GITHUB_STEP_SUMMARY` where it is set.""" + print("\n" + "\n".join(lines)) + summary = os.environ.get("GITHUB_STEP_SUMMARY") + if summary: + with open(summary, "a", encoding="utf-8") as handle: + handle.write("\n".join(lines) + "\n") + + +def timed(run) -> tuple: + """`run()` bracketed on the monotonic clock, exec to exit: (ms, its value).""" + start = time.monotonic_ns() + value = run() + return (time.monotonic_ns() - start) / 1e6, value + + +def needs(request, name: str, owner: str): + """A fixture another task provides, looked up only once the engine is + there, so a case without PostgreSQL 16 skips with T205's banner, and one + with it fails by saying which task it waits for.""" + try: + return request.getfixturevalue(name) + except pytest.FixtureLookupError: + pytest.fail(f"no fixture `{name}`: {owner} provides it", pytrace=False) + + +def setting(db, name: str) -> str: + return sql(db, f"SHOW {name};").splitlines()[-1] + + +# ------------------------------------------------------------------ the stores +@pytest.fixture() +def durable_db(pg_engine, pg_template_sql, monkeypatch): + """Test 8's stoppable cluster started with the defaults (section 5.1: + `fsync`, `synchronous_commit` and `full_page_writes` on): T205's + `Cluster`, its `FAST` settings left out for this start alone, its own + template from `pg_template_sql`, and one database cloned from it.""" + monkeypatch.setattr(pgcluster, "FAST", ()) + cluster = pgcluster._started(pg_engine, pg_template_sql) + monkeypatch.undo() + patch = pytest.MonkeyPatch() + patch.setenv("PATH", pgcluster._engine_first(pg_engine.bindir, os.environ.get("PATH", os.defpath))) + try: + name = cluster.new_database() + yield Database(cluster, name) + finally: + patch.undo() + cluster.destroy() + + +STORES = {"fixture": "pg", "durable": "durable_db"} +#: The store's settings the figure names, as each store must show them. +STORE_SETTINGS = {"fixture": "off", "durable": "on"} + + +# ============================================================ T226: M1 and M2 (phase N) + +@pytest.mark.parametrize("store", list(STORES)) +@pytest.mark.parametrize("path", ["new-psql", "design", "session"]) +def test_one_write_cost_is_recorded_and_every_write_commits(pg_engine, request, tmp_path, path, + store): + """M1 and M2 (section 5.1), at the fixture's settings and durable: 200 + writes, each one appended log line on a register brought to `primary`. + + `[new-psql-<store>]` is M1 as R1 measured it: each write one commit + call through a new `psql` process. `[design-<store>]` is M1 in the + design's form under Q7 (A''): a `register snapshot` call and a `register + commit` call, each a `lanes-index` process with its own Python start, + cold once and 20 warm (act 3's count, section 5.3; 200 would add minutes + to the job). `[session-<store>]` is M2: the 200 writes in one `psql` + session, each write's time the sum of its three statements' `\\timing`. + + The oracle: each call exits 0 and answers the seq it committed; the + journal grew by exactly n and each `write_id` appears once; the store + shows the settings its id names. The figures are recorded, never + asserted.""" + db = request.getfixturevalue(STORES[store]) + reg = PrimaryRegister(db, tmp_path) + for name in ("fsync", "synchronous_commit", "full_page_writes"): + assert setting(db, name) == STORE_SETTINGS[store], ( + f"the {store} store runs {name}={setting(db, name)}") + log = "lanes/log/repoA-1.md" + writes = Appends(db, [log]) + before = writes.base + lines = [] + texts = [f"NOTED {EM} lane repoA-1, session {SID_A1}@{WS}, 2026-11-10T00:00:00Z, " + f"lane:repoA-1 {EM} t226 {path} {store} write {k}" for k in range(N_WRITES)] + if path == "new-psql": + times = [] + for k, text in enumerate(texts): + sent = writes.statements(writes.entry("repoA-1", log, [text])) + ms, proc = timed(lambda: one_call(db, sent)) + assert (proc.returncode, proc.stdout.strip()) == (0, str(before + k + 1)), ( + f"write {k}: exit {proc.returncode}: {_said_safely(proc.stderr.strip()[-600:])}") + times.append(ms) + committed_once(db, before, writes.write_ids) + lines.append(figure("M1", f"{store} cluster, Unix socket", "one commit call, new `psql`", + times, "rtt=0, tls=none, c=1, q=1")) + elif path == "design": + design_before, totals = head(db), [] + for k in range(1 + N_WARM): + ms, done = timed(lambda: fake_write( + reg.copy, reg.env, reg.estate.checkout, tmp_path / "attempts" / str(k), "repoA-1", + "log", _edit_log_noted("repoA-1", SID_A1, f"t226 design write {k}"), + f"lanes-edit.sh log: t226 design write {k}")) + assert done["code"] == 0, (_said_safely(done["snapshot"]), + _said_safely(done["commit"]) if done["commit"] else "the commit did not run, so it has no exit") + assert done["commit"].stdout.split() == ["committed", str(design_before + k + 1)], ( + _said_safely(done["commit"])) + totals.append(ms) + assert head(db) == design_before + 1 + N_WARM, "each design-form write committed once" + assert rows(db, f"SELECT count(DISTINCT write_id) AS d FROM journal WHERE seq > " + f"{design_before}")[0]["d"] == 1 + N_WARM + lines.append(figure("M1", f"{store} cluster, Unix socket", + "the design's write: `register snapshot` + `register commit`", + totals, "rtt=0, tls=none, c=2, q=2")) + else: + batch = [writes.statements(writes.entry("repoA-1", log, [text])) for text in texts] + proc = in_one_session(db, batch, timing=True) + assert proc.returncode == 0, _said_safely(proc) + out = proc.stdout.splitlines() + seqs = [line for line in out if line.isdigit()] + stamps = [float(m.group(1)) for m in map(re.compile(r"^Time: ([0-9.]+) ms").match, out) if m] + assert seqs == [str(before + k + 1) for k in range(N_WRITES)], "each write answered its seq" + assert len(stamps) == 3 * N_WRITES, f"{len(stamps)} timings, not three per write" + committed_once(db, before, writes.write_ids) + per_write = [sum(stamps[3 * k:3 * k + 3]) for k in range(N_WRITES)] + lines.append(figure("M2", f"{store} cluster, Unix socket", "one write in a held session", + per_write, "rtt=0, tls=none, c=0, q=3")) + record(lines) + + +# ============================================================ T226: M12 (phase N) + +def test_a_tls_and_scram_connect_on_loopback_is_timed_and_verified(pg_engine, request): + """M12's CI row (section 5.1; section 5.6): `psql -X -A -t -c 'SELECT 1'` + against T229's TLS cluster on loopback TCP, with `sslmode=verify-full` + and SCRAM, exec to exit, cold once and 20 warm; each answers `1`. It is + verified once: a connect that requires SCRAM (`PGREQUIREAUTH`, libpq 16) + succeeds, and `pg_stat_ssl` for its own backend says TLS, whose version is + recorded beside the time (on T229's cluster, `TLSv1.3`). X changed no + oracle: it asserts TLS in use, never the figure.""" + tls = needs(request, "tls_cluster", "lane 2's T229 (section 5.6's TLS cluster)") + env = tls.client_env() + argv = [tls.tool("psql"), "-X", "-A", "-t", "-c", "SELECT 1"] + times = [] + for _ in range(1 + N_WARM): + ms, proc = timed(lambda: subprocess.run(argv, capture_output=True, text=True, env=env, + timeout=60, check=False)) + assert (proc.returncode, proc.stdout.strip()) == (0, "1"), _said_safely(proc) + times.append(ms) + check = dict(env, PGREQUIREAUTH="scram-sha-256") + said = subprocess.run([tls.tool("psql"), "-X", "-A", "-t", "-F", "|", "-c", + "SELECT ssl, version FROM pg_stat_ssl WHERE pid = pg_backend_pid()"], + capture_output=True, text=True, env=check, timeout=60, check=False) + assert said.returncode == 0, f"a connect that requires SCRAM failed: {_said_safely(said)}" + ssl, version = said.stdout.strip().split("|") + assert ssl == "t", f"pg_stat_ssl says the connect is not TLS: {_said_safely(said)!r}" + record([figure("M12", "TLS cluster, loopback TCP", "`psql -c 'SELECT 1'`, a new connect", + times, f"rtt=0 (loopback), tls={version}, scram, c=1, q=1")]) + + +# ============================================================ T226: lane 3's `--last` cost rows + +#: `journal --last`'s five reads, in `register_last_queries`' order +#: (`refs/l1/T114`, `lanes-index:7086-7108`). +LAST_READS = ("the head", "the generation", "the import seqs", + "the edits of the path's rename closure", "the journal_files rows of the closure") + + +def _lanes_index_module(): + """`lanes-index` loaded as a module, as T207's stub loads it for + `classify`, so this module calls lane 1's own functions.""" + loader = importlib.machinery.SourceFileLoader("lanes_index_t226", str(LANES_INDEX)) + spec = importlib.util.spec_from_loader(loader.name, loader) + module = importlib.util.module_from_spec(spec) + loader.exec_module(module) + return module + + +def last_statements(path: str) -> list: + """`journal --last`'s reads as lane 1's code builds them, + `register_last_queries(path, None)`, so what is explained is what is + sent.""" + make = getattr(_lanes_index_module(), "register_last_queries", None) + assert make is not None, ("lanes-index has no `register_last_queries`: lane 1's T114 " + "(L1-A12, `journal --last`) builds it") + statements = make(path, None) + assert len(statements) == len(LAST_READS), statements + return statements + + +@pytest.fixture() +def imported_clone(pg_cluster): + """One clone of `tmpl_imported` (T227), with section 1.4's two + database-level statements, dropped `WITH (FORCE)` at the end (N2's + `clones`).""" + found = pg_cluster.psql(f"SELECT datname FROM pg_database WHERE datname = '{IMPORTED}';").stdout.split() + assert found == [IMPORTED], f"no {IMPORTED} on the session cluster: lane 2's T227 builds it" + name = f"t226_last_{uuid.uuid4().hex[:8]}" + pg_cluster.psql(f"CREATE DATABASE {name} TEMPLATE {IMPORTED};") + try: + pg_cluster.psql(f"REVOKE ALL ON DATABASE {name} FROM PUBLIC;\n" + f"GRANT CONNECT ON DATABASE {name} TO {CONNECT_TO};\n") + yield Database(pg_cluster, name) + finally: + pg_cluster.drop_database(name) + + +def imported_to_primary(db) -> int: + """The clone's import brought to `primary` by AT-LR006's route: a + `cutover` entry writing D21's five `lanes/STORE` fields over the import, + then `record_marker`, as T210's `import_to_primary` does. Returns the + cutover's seq.""" + switch = rows(db, "SELECT mode, marker_state FROM register_switch")[0] + assert (switch["mode"], switch["marker_state"]) == ("files", "absent"), switch + last = rows(db, "SELECT seq, git_commit, git_tree FROM journal WHERE kind = 'import' " + "ORDER BY seq DESC LIMIT 1") + assert last and last[0]["seq"] == head(db), f"{IMPORTED}'s head is not its import" + imp = last[0] + store = "".join(f"{line}\n" for line in ( + "store=primary", "database=t226", f"import={imp['git_commit']}", + f"lanes-tree={imp['git_tree']}", f"utc={STORE_UTC}")).encode("utf-8") + edits, files = _creates({STORE_PATH: store}) + cut = _commit_call(db, imp["seq"], _entry("cutover", "cutover", edits=edits, files=files)) + version = rows(db, "SELECT version FROM schema_version")[0]["version"] + marker = sql(db, f"SELECT {SCHEMA}.record_marker({version}, {cut}, '{MARKER_COMMIT}', " + f"'{WS}');", WRITER) + assert marker.splitlines()[-1] == "present", f"record_marker answered {marker!r}" + return cut + + +def lane_logs(db) -> list: + return [r["path"] for r in rows( + db, "SELECT path FROM files WHERE path LIKE 'lanes/log/%' AND path <> 'lanes/log/README.md' " + "ORDER BY path")] + + +def largest_log(db) -> str: + """The register's longest lane log, by its lines.""" + found = rows(db, "SELECT f.path, count(d.line_id) AS n FROM files f LEFT JOIN doc_lines d " + "ON d.path = f.path WHERE f.path LIKE 'lanes/log/%' AND f.path <> " + "'lanes/log/README.md' GROUP BY f.path ORDER BY n DESC, f.path LIMIT 1") + assert found, f"{IMPORTED} holds no lane log" + return found[0]["path"] + + +def journal_size(db) -> dict: + return rows(db, "SELECT (SELECT count(*) FROM journal) AS entries, " + "(SELECT count(*) FROM journal_edits) AS edits")[0] + + +def explained(db, statements: list) -> list: + """Each statement under `EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)`, as + the reader's login, in one REPEATABLE READ READ ONLY transaction with the + schema on `search_path`, as `_query_many` reads (lane 1's + `lanes-index:2227-2262` at T114): each plan's server time, buffers and + rows. No D9 bound is set here, so a statement past 3000 ms is measured, + and the timed `journal --last` below meets the bound itself.""" + script = [f'SET search_path TO "{SCHEMA}";', "BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY;"] + script += [f"EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) {statement};" for statement in statements] + script.append("COMMIT;") + proc = subprocess.run([db.psql_bin, "--no-psqlrc", "-X", "-q", "-A", "-t", "-v", "ON_ERROR_STOP=1"], + input="\n".join(script) + "\n", capture_output=True, encoding="utf-8", + errors="replace", env=db.env(LOGIN_READER, appname="t226-explain"), + timeout=600, check=False) + assert proc.returncode == 0, f"EXPLAIN as {LOGIN_READER}: {_said_safely(proc)}" + plans, text, at, decoder = [], proc.stdout, 0, json.JSONDecoder() + while True: + while at < len(text) and text[at].isspace(): + at += 1 + if at >= len(text): + break + value, at = decoder.raw_decode(text, at) + plans.append(value[0]) + assert len(plans) == len(statements), f"{len(plans)} plans for {len(statements)} statements" + return [{"execution_ms": p["Execution Time"], "planning_ms": p["Planning Time"], + "hit": p["Plan"].get("Shared Hit Blocks", 0), "read": p["Plan"].get("Shared Read Blocks", 0), + "rows": p["Plan"].get("Actual Rows")} for p in plans] + + +def grow_to(db, target_edits: int, logs: list, batch: int, tag: str) -> int: + """Writes of `batch` appended lines each, round robin over `logs`, in + one session, until `journal_edits` holds at least `target_edits` rows. + No line holds the measured key. Returns the writes made.""" + have, appends, writes, k = journal_size(db)["edits"], Appends(db, logs), [], 0 + while have < target_edits: + path = logs[k % len(logs)] + lane = path[len("lanes/log/"):-len(".md")] + texts = [f"NOTED {EM} lane {lane}, session {SID_A1}@{WS}, 2026-11-10T00:00:00Z, " + f"lane:{lane} {EM} t226 growth {tag} {k}.{i}" for i in range(batch)] + writes.append(appends.statements(appends.entry(lane, path, texts))) + have += batch + k += 1 + if writes: + before = head(db) + proc = in_one_session(db, writes) + assert proc.returncode == 0, f"growth write: {_said_safely(proc)}" + committed_once(db, before, appends.write_ids) + return len(writes) + + +@pytest.mark.parametrize("log", ["largest-log", "renamed-log"]) +def test_journal_last_is_explained_per_statement_and_timed_against_t_r(pg_engine, imported_clone, + tmp_path, log): + """Lane 3's `--last` cost rows (#165 6755922262; F10-OWED item 35), on a + clone of `tmpl_imported` brought to `primary`: + + * `[largest-log]`: the register's longest log, with one line holding + the case's key appended by one write, so the match is that write's + seq; + * `[renamed-log]`: the same, then that log renamed whole through + `register commit`'s `renames.tsv`, so `journal --last` reads the + new path's rename closure, and the match is the rename's seq (a + file renamed in counts what it brings, C7 as lane 1's + `register_pickaxe` reads it). + + At the clone's own size, then with `journal_edits` grown to 2x and 5x + its rows by writes of appended lines round robin over every lane log: + each of the five reads' server time by `EXPLAIN (ANALYZE, BUFFERS)`, as + the reader's login; and `journal --last --path <p> --grep <key>`'s wall + time, exec to exit, cold once and 20 warm, beside `T_r`. Each run exits + 0 and prints `format=1`, `n=<head>` and `seq=<the match>`. The figures + are recorded, never asserted; each statement's share of the read row's + 3000 ms is printed beside it, so a statement that nears it is seen + (lane 3: indexes on `journal_edits (path)` and `(to_path) WHERE op = + 'rename'` go into migration 1, T107).""" + db = imported_clone + imported_to_primary(db) + ensure_logins(db) + estate = Estate(tmp_path / "estate", {p: SEED[p] for p in ("lanes/repos.tsv", "lanes/log/README.md")}) + copy = flipped(tmp_path) + (tmp_path / "conf").mkdir() + conf = primary_config(tmp_path / "conf" / "lanes-index.conf", db.url(LOGIN_WRITER), + db.url(LOGIN_READER)) + env = index_env(tmp_path, conf, estate.home) + target = largest_log(db) + lane = target[len("lanes/log/"):-len(".md")] + key = f"t226-last-key-{uuid.uuid4().hex[:12]}" + appends = Appends(db, [target]) + proc = one_call(db, appends.statements(appends.entry(lane, target, [ + f"NOTED {EM} lane {lane}, session {SID_A1}@{WS}, 2026-11-10T00:00:00Z, lane:{lane} {EM} {key}"]))) + assert proc.returncode == 0, _said_safely(proc) + match, measured = _whole(proc.stdout.strip(), "the appended entry's seq"), target + if log == "renamed-log": + measured = f"lanes/log/{lane}-t226-renamed.md" + done = fake_write(copy, env, estate.checkout, tmp_path / "rename", lane, "rename-lane", + _edit_rename_log(target, measured), + f"lanes-edit.sh rename-lane: t226 renames {target}") + assert done["code"] == 0, (_said_safely(done["snapshot"]), + _said_safely(done["commit"]) if done["commit"] else "the commit did not run, so it has no exit") + match = _whole(done["commit"].stdout.split()[1], "the rename commit's seq") + assert rows(db, f"SELECT count(*) AS n FROM journal_edits WHERE seq = {match} AND op = " + f"'rename' AND path = '{target}' AND to_path = '{measured}'")[0]["n"] == 1 + statements = last_statements(measured) + base = journal_size(db)["edits"] + batch = max(1, base // 1000) + lines = [] + for size, factor in (("1x", 1), ("2x", 2), ("5x", 5)): + if factor > 1: + grow_to(db, factor * base, lane_logs(db), batch, f"{log}-{size}") + grown = journal_size(db) + where = (f"tmpl_imported clone, {size}: {grown['entries']} entries, {grown['edits']} " + f"edits, Unix socket") + for what, plan in zip(LAST_READS, explained(db, statements)): + lines.append(f"| --last | {platform.node()}, {where} | {log} `{measured}`: {what} | " + f"server {plan['execution_ms']:.2f} ms, planning {plan['planning_ms']:.2f} ms " + f"| buffers hit {plan['hit']}, read {plan['read']}; rows {plan['rows']} | " + f"{100 * plan['execution_ms'] / READ_STATEMENT_MS:.1f} % of " + f"{READ_STATEMENT_MS} ms |") + n, times = head(db), [] + for _ in range(1 + N_WARM): + ms, proc = timed(lambda: run_index(copy, ["journal", "--last", "--path", measured, + "--grep", key], env)) + assert proc.returncode == 0, f"journal --last exited {proc.returncode}: {_said_safely(proc.stderr)}" + assert proc.stdout.splitlines() == ["format=1", f"n={n}", f"seq={match}"], _said_safely(proc) + times.append(ms) + lines.append(figure("--last", where, f"{log} `journal --last`, exec to exit", times, + f"rtt=0, tls=none, c=1, q=1; T_r={T_R_S} s (CLI412:255)")) + record(lines) + + +# ------------------------------------------------------------------ `swapped` +CANDIDATES = [f"repoC-{k}" for k in range(1, 7)] + +#: The wrapper that stands where `lanes-edit.sh` finds `lanes-index`, +#: beside it (the copy rule, CLI4.5 section 6): it logs each call's argv and +#: hands it to the flipped copy, so each `journal --last` is counted. +CALL_LOG_WRAPPER = r'''#!/usr/bin/env python3 +import os, sys +here = os.path.dirname(os.path.abspath(__file__)) +with open(os.path.join(here, "lanes-index.calls"), "a", encoding="utf-8") as handle: + handle.write("\t".join(sys.argv[1:]) + "\n") +real = os.path.join(here, "lanes-index.real") +os.execv(sys.executable, [sys.executable, real] + sys.argv[1:]) +''' + + +def _sid(k: int) -> str: + return f"cccccccc-{k:04d}-4000-8000-{k:012d}" + + +def _candidate_log(lane: str, k: int) -> str: + return "\n".join([ + f"# lane {lane} {EM} object log (lane-collision-protocol Amendment 7)", + f"STARTED {EM} lane {lane}, session {_sid(k)}@{WS}, 2026-10-02T00:00:00Z, " + f"lane:{lane} {ARROW} home opensoft/repoC; dir /work/{lane}", ""]) + + +def _paused(lane: str, k: int) -> str: + """A swap's PAUSED line, its payload after the arrow that follows the + object (Amendment 7's grammar: object, then the arrow and the payload, + then the em dash and the free text), which `swapped_candidates` reads as + the line's payload: `swap; window ...; workstation ...; dir ...; profile + ...; agent ...; transcript ...`. After the em dash it is free text, which + `swapped` does not read.""" + return (f"PAUSED {EM} lane {lane}, session {_sid(k)}@{WS}, 2026-11-10T0{k}:00:00Z, " + f"lane:{lane} {ARROW} swap; window w{k}; workstation {WS}; dir /work/{lane}; " + f"profile p{k}; agent a{k}; transcript t{k}") + + +def _lanes_shown(fields: list) -> list: + """`swapped`'s listed lanes as a failure message may show them (T255u; + lane 2's pre-review RV9-37 of P09 at `d9a1f2bf`, B2): a field that is one + of this module's own lane names (`CANDIDATES`) is shown, and any other is + `[withheld]`. A field is a stdout line's text up to its first tab, so + where a line has no tab it is the whole line, a writer's text that is + never shown raw.""" + return [field if field in CANDIDATES else "[withheld]" for field in fields] + + +def _listed_as_expected(proc, mode: str, expected: list) -> None: + """`lanes-edit.sh swapped`'s stdout lists `expected`, each line's lane + before its first tab, or the assert fails with a message that shows the + listed lanes only as `_lanes_shown` does, beside the exit and the counts + `_said_safely` gives (T255u; RV9-37, B2).""" + listed = [line.split("\t", 1)[0] for line in proc.stdout.splitlines() if line] + assert listed == expected, (f"{mode} mode listed {_lanes_shown(listed)}, not {expected}: " + f"{_said_safely(proc)}") + + +def test_a_swapped_line_with_no_tab_is_withheld_from_the_failure_message(): + """T255u (lane 2's pre-review RV9-37 of P09 at `d9a1f2bf`, B2), with no + engine and no process: `swapped` exited 0 with one listed lane, a line + with a planted value and no tab, and a `PGPASSWORD=` line. The listing + is not what was expected, so `_listed_as_expected` fails, and its message + shows the one known lane, `[withheld]` for each other line, the exit + and the counts, and not the planted value. Before T255u the message + showed each line up to its first tab, so the whole of a line with none. + The planted value is no credential of any login.""" + planted = f"fake-{uuid.uuid4().hex}" + proc = subprocess.CompletedProcess( + ["lanes-edit.sh", "swapped", WS], 0, + f"{CANDIDATES[1]}\tw2\n{planted}\nPGPASSWORD={planted}\n", "") + with pytest.raises(AssertionError) as failed: + _listed_as_expected(proc, "files", [CANDIDATES[1], CANDIDATES[0]]) + said = str(failed.value) + assert planted not in said, "the planted value is in the failure message" + assert f"listed ['{CANDIDATES[1]}', '[withheld]', '[withheld]']" in said, \ + f"the listed lanes, shown:\n{said}" + assert "exit 0" in said, f"the exit, shown:\n{said}" + + +@pytest.mark.parametrize("case", ["listed-as-expected", "end-held-chain"]) +def test_pytests_own_report_of_a_measure_failure_shows_no_planted_writer_text(request, case): + """T255zb (lane 3's ruling 6949488277 on lane 2's pre-review RV9-38 of + P09 at `3f9fcac4`, B1), with no engine and no process: a failure whose + frames or chain hold a planted value, rendered as pytest renders a + failed test under the suite's own settings (bounds' `_reported`), holds + no planted value. Each case first proves the value is there: + - `listed-as-expected`: `_listed_as_expected`'s argument `proc`, + `swapped`'s `CompletedProcess`, whose stdout holds it (RV9-38: + measure :1124, T255u's new path); + - `end-held-chain`: `_end_held`'s explicit chain (T255q, T255r): a + held session whose kill fails, whose bounded reap times out with + the planted value in its `TimeoutExpired`'s kept stdout and stderr, + and whose stdin's close fails. pytest prints each error of the + chain, under short too; none of their messages holds a stream. + Under pytest's default `--tb=auto` the first shows the value as a long + entry's argument; T205e's short style shows none. An explicit + `--tb=long` or `--fulltrace` is not secret-safe. The planted value is no + credential of any login.""" + planted = f"fake-{uuid.uuid4().hex}" + if case == "listed-as-expected": + proc = subprocess.CompletedProcess(["lanes-edit.sh", "swapped", WS], 0, + f"{CANDIDATES[1]}\tw2\n{planted}\n", "") + with pytest.raises(AssertionError) as failed: + _listed_as_expected(proc, "files", [CANDIDATES[0]]) + assert planted in str(failed.getrepr(style="long", funcargs=True)), \ + "a long report does not show the planted value, so this proves nothing" + else: + class _Pipe: + def close(self) -> None: + raise BrokenPipeError(32, "Broken pipe") + + class _Held: + args, returncode, readers = ["psql", "-X", "-q"], None, [] + stdin = stdout = stderr = _Pipe() + + def poll(self): + return None + + def kill(self) -> None: + raise ProcessLookupError(3, "No such process") + + def wait(self, timeout=None): + raise subprocess.TimeoutExpired(self.args, timeout, output=f"out {planted}\n".encode(), + stderr=f"psql: {planted}\n".encode()) + + with pytest.raises(ProcessLookupError) as failed: + _end_held(_Held(), kill=True) + reaped = failed.value.__cause__ + assert isinstance(reaped, subprocess.TimeoutExpired) and planted.encode() in reaped.output, \ + "the chain does not hold the planted output, so this proves nothing" + assert isinstance(reaped.__cause__, BrokenPipeError), "the chain does not end at the close's error" + assert planted not in _reported(request, failed), f"[{case}] the planted value is in pytest's report" + + +def test_swapped_with_several_candidates_is_timed_beside_its_journal_last_calls(pg_engine, pg, tmp_path): + """Lane 3's third `--last` row (#165 6755922262): `lanes-edit.sh swapped + <ws>` with one, three and six swapped lanes, exec to exit, cold once and + ten warm, in files mode (one `git log -S` pickaxe per candidate, + `swapped_lanes` at the base) and on primary (one `journal --last` per + candidate, T506). Each candidate's PAUSED line is one write, committed in + the register and pushed to the estate's origin in the same order, so + both modes rank alike. + + The oracle: every run exits 0 and lists the candidates most recently + paused first, the same in both modes; on primary, each run makes exactly + one `journal --last` call per candidate, naming its log. That last + assertion is red until lane 5's T506 (L5-A5) reads `swapped`'s rank + through `journal --last`.""" + files = dict(SEED) + for k, lane in enumerate(CANDIDATES, 1): + files[f"lanes/log/{lane}.md"] = _candidate_log(lane, k) + reg = PrimaryRegister(pg, tmp_path, files) + bin_dir = reg.copy.parent + os.replace(str(reg.copy), str(bin_dir / "lanes-index.real")) + wrapper = bin_dir / "lanes-index" + wrapper.write_text(CALL_LOG_WRAPPER, encoding="utf-8") + wrapper.chmod(0o755) + calls = bin_dir / "lanes-index.calls" + checkout = reg.estate.checkout + base_env = {k: v for k, v in reg.env.items() if k != "LANES_INDEX_CONFIG"} + base_env.update(LANES_REPO=str(checkout), LANES_BRANCH="main", LANES_WORKSTATION=WS) + modes = {"files": base_env, "primary": dict(base_env, LANES_INDEX_CONFIG=reg.env["LANES_INDEX_CONFIG"])} + lines, paused = [], 0 + for count in (1, 3, 6): + while paused < count: + lane = CANDIDATES[paused] + path = f"lanes/log/{lane}.md" + text = _paused(lane, paused + 1) + appends = Appends(pg, [path]) + proc = one_call(pg, appends.statements(appends.entry(lane, path, [text]))) + assert proc.returncode == 0, _said_safely(proc) + target = checkout / path + target.write_bytes(target.read_bytes() + text.encode("utf-8") + b"\n") + git(checkout, "commit", "-q", "-am", f"{lane}: PAUSED", env=reg.estate.env) + git(checkout, "push", "-q", "origin", "main", env=reg.estate.env) + paused += 1 + expected = list(reversed(CANDIDATES[:count])) + for mode, env in modes.items(): + times = [] + for _ in range(11): + calls.write_text("", encoding="utf-8") + ms, proc = timed(lambda: subprocess.run( + ["bash", str(bin_dir / "lanes-edit.sh"), "swapped", WS], capture_output=True, + encoding="utf-8", errors="replace", env=env, cwd=str(checkout), timeout=120, + check=False)) + assert proc.returncode == 0, f"swapped in {mode} mode: {_said_safely(proc)}" + _listed_as_expected(proc, mode, expected) + if mode == "primary": + lasts = [c.split("\t") for c in calls.read_text(encoding="utf-8").splitlines() + if c.startswith("journal\t--last")] + paths = sorted(c[c.index("--path") + 1] for c in lasts) + assert paths == sorted(f"lanes/log/{lane}.md" for lane in expected), ( + f"swapped on primary made {len(lasts)} `journal --last` call(s), not one " + f"per candidate: lane 5's T506 (L5-A5) reads the rank through it") + times.append(ms) + lines.append(figure("--last", f"{mode} mode, {count} candidate(s), local bare origin", + f"`lanes-edit.sh swapped {WS}`, exec to exit", times, + f"rtt=0, tls=none; {count} pickaxe(s)")) + record(lines) + + +# ============================================================ T255: test 9's phase-W measurements + +#: M7's verbs (section 5.1), each as `lanes-edit.sh` (or `lane-start`) takes +#: it, with `{k}` for the run's number so no two runs collide, and the +#: register writes each makes. The argv are read from `lanes-edit.sh`'s usage +#: at the base; "a landing's five writes" is lane 2's reading of Rule 6's +#: landing (the take, its log line, the close, its log line, the release), +#: for lane 4 to confirm against its [L4-c] section. A landing's object is +#: an `owner/repo#<n>` key, one of the forms `lanes-edit.sh`'s `canon_object` +#: takes (`owner/repo#<n>`, `#<n>`, `lane:<name>` and the OpenSpec form), +#: which has no `pr:` form. `{dir}` is the estate's checkout: SEED's log +#: records `dir /work/repoA1`, which exists on no host, so the dry run names +#: a directory that exists with `--dir`, and it runs in a tmux window of its +#: own, `_window`'s, since `lane-start` refuses outside tmux. +VERBS = { + "log-noted": ([["log", "NOTED", "lane:repoA-1", "t255 measured note {k}"]], 1), + "claim": ([["claim", "opensoft/repoA#{k}", "--no-github"]], 1), + "landing": ([ + ["append-line", f"LANDING {EM} lane repoA-1, session {SID_A1}@{WS}, {{utc}}, PR #{{k}} into " + f"opensoft/repoA main"], + ["log", "LANDING", "opensoft/repoA#{k}", "t255 landing {k}"], + ["append-line", f"LANDED {EM} lane repoA-1, session {SID_A1}@{WS}, {{utc}}, PR #{{k}} into " + f"opensoft/repoA main {ARROW} abc1234"], + ["log", "CLOSED", "opensoft/repoA#{k}", "merged abc1234"], + ["release", "opensoft/repoA#{k}", "landed", "--no-github"]], 5), + "lane-start-dry-run": ([["@lane-start", "--dry-run", "--dir", "{dir}", "repoA", "1"]], 0), +} +MODES = ("files", "primary") + + +class VerbEstate: + """The estate a verb runs in, in one mode: T210's estate at C, with the + workspace `lanes-edit.sh workspace-root` answers (`$HOME/.agents/ + workspace.yaml`, W4a's form) and the lane's identity; on primary the + register brought to `primary` and `LANES_INDEX_CONFIG`, in files mode + the twin on its own local bare origin (AT-9's fixture: the files-mode + figure is a lower bound of today's cost).""" + + def __init__(self, db, root: Path, mode: str, reg=None, files: dict = None): + self.mode, self.db = mode, db + if mode == "primary": + self.reg = reg or PrimaryRegister(db, root, files) + self.estate, self.bin = self.reg.estate, self.reg.copy.parent + if (REPO / "lane-start").exists(): + shutil.copy2(str(REPO / "lane-start"), str(self.bin / "lane-start")) + env = dict(self.reg.env) + else: + self.reg, self.estate = None, Estate(root / "estate", files) + self.bin = root / "bin" + self.bin.mkdir(parents=True) + for name in ("lanes-edit.sh", "lanes-index", "lane-start"): + if (REPO / name).exists(): + shutil.copy2(str(REPO / name), str(self.bin / name)) + env = index_env(root, root / "no-config", self.estate.home) + env.pop("LANES_INDEX_CONFIG") + (self.estate.home / ".agents").mkdir(parents=True, exist_ok=True) + (self.estate.home / ".agents" / "workspace.yaml").write_text( + f"repository: {self.estate.origin}\npath: {self.estate.checkout}\n", encoding="utf-8") + env.update(LANES_REPO=str(self.estate.checkout), LANES_BRANCH="main", LANES_WORKSTATION=WS, + LANES_NO_GITHUB="1", LANES_LANE="repoA-1", LANES_SESSION=SID_A1) + self.env = env + # EACH WRITE LANE'S OWN REGISTER CHECKOUT, `<c>`: on primary a write runs + # from `<W>-lanes/<lane>` (`lane_checkout_path`), W being the real path of + # `workspace.yaml`'s `path:`, and refuses 2 where it is not there, since a + # clone is a fetch (T415's `pw_checkout`, `23bbd25f:lanes-edit.sh:7934-7936`). + # The estate makes it itself, because `lane-start` makes it only under + # `LANES_ROUTE_WRITES=1` with neither `LANES_REPO` nor `LANES_FILE` set + # (lane 3, #165 6841265575; `dfc4ce4c:lane-start:1209-1210`): a clone of + # W's origin, as the writes module's `make_lane_checkout` makes one, for + # `repoA-1`, every verb's lane, and `BIND_TO`, the bind's. It is made once + # per W, since `[m7]` and `[m9]` build their estates on one register. + if mode == "primary": + real = Path(os.path.realpath(self.estate.checkout)) + for lane in ("repoA-1", BIND_TO): + target = real.parent / f"{real.name}-lanes" / lane + if not target.exists(): + target.parent.mkdir(parents=True, exist_ok=True) + git(target.parent, "clone", "-q", str(self.estate.origin), str(target), + env=self.estate.env) + + def run(self, argv: list) -> subprocess.CompletedProcess: + if argv[0].startswith("@"): + command = ["bash", str(self.bin / argv[0][1:]), *argv[1:]] + else: + command = ["bash", str(self.bin / "lanes-edit.sh"), *argv] + return subprocess.run(command, capture_output=True, encoding="utf-8", errors="replace", + env=self.env, cwd=str(self.estate.checkout), timeout=300, + stdin=subprocess.DEVNULL, check=False) + + def origin_commits(self) -> int: + return _whole(git(self.estate.origin, "rev-list", "--count", "main", env=self.estate.env).strip(), + "the origin's commit count") + + +def _window(estate: VerbEstate, root: Path, lane: str, session_id: str = None): + """The tmux window `lane-start` runs in, named `lane`, with a live session + in it (T203c's `guard_session`, imported here so the module still loads + where T203c is not in the tree). `lane-start` refuses outside tmux (its + step 2: "run this inside the tmux window that will carry the lane"), and + `--bind` takes only the transcript uuid of the session live in its + window. So a run gets the stand-in `tmux` in `<root>/window`, answering + as the window `lane`, and a live session record under the estate's + `HOME` whose `sessionId` is `session_id` (a new uuid where None); the + estate's environment then carries that window's `TMUX`, `TMUX_PANE` and + the stand-in first on `PATH`, no inherited `CLAUDE_*` (a person's + `CLAUDE_CONFIG_DIR` would move the records), and `CLAUDE_CODE_SESSION_ID` + naming the session, as the harness exports it. The record's `cwd`, + `<HOME>/projects/repoA`, is the helper's rule; `lane-start` does not read + it. The caller closes the session.""" + try: + from sql_register_helpers import guard_session + except ImportError: + pytest.fail("tests/sql_register_helpers.py has no `guard_session`: T203c provides it", + pytrace=False) + home = estate.estate.home + session = guard_session(home, root / "window", home / "projects" / "repoA", window=lane, + session_id=session_id) + base = {k: v for k, v in estate.env.items() if not k.startswith("CLAUDE_")} + estate.env = session.env(base, CLAUDE_CODE_SESSION_ID=session.session_id) + return session + + +@pytest.mark.parametrize("verb", list(VERBS)) +def test_each_verb_is_timed_end_to_end_in_both_modes(pg_engine, pg, tmp_path, verb, request): + """M7 (section 5.1; P5, what a lane feels): the verb, exec to exit, cold + once and 20 warm, in files mode against a local bare origin and on + primary, on the same host. The oracle: every run exits 0; on primary the + journal grows by exactly the verb's writes per run and each `write_id` + appears once; in files mode the origin's `main` grows by them. The + figures are recorded, never asserted. Fails until lane 4's L4-B3 and + L4-B8 route the verbs through the storage layer on primary.""" + steps, writes = VERBS[verb] + lines = [] + for mode in MODES: + estate = VerbEstate(pg, tmp_path / mode, mode) + if any(step[0] == "@lane-start" for step in steps): + request.addfinalizer(_window(estate, tmp_path / mode, "repoA-1").close) + before = head(pg) if mode == "primary" else estate.origin_commits() + times = [] + for k in range(1 + N_WARM): + utc = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) + argvs = [[part.format(k=1000 + k, utc=utc, dir=estate.estate.checkout) for part in step] + for step in steps] + start = time.monotonic_ns() + for argv in argvs: + proc = estate.run(argv) + assert proc.returncode == 0, (f"{verb} in {mode} mode, run {k}: `{' '.join(argv)}` " + f"exited {proc.returncode}: {_said_safely((proc.stdout + proc.stderr)[-600:])}") + times.append((time.monotonic_ns() - start) / 1e6) + runs = 1 + N_WARM + if mode == "primary": + assert head(pg) == before + runs * writes, ( + f"{verb} on primary: the journal grew by {head(pg) - before}, not {runs * writes}") + grown = rows(pg, f"SELECT count(*) AS n, count(DISTINCT write_id) AS d FROM journal " + f"WHERE seq > {before}")[0] + assert grown == {"n": runs * writes, "d": runs * writes}, grown + elif writes: + assert estate.origin_commits() >= before + runs * writes, ( + f"{verb} in files mode pushed {estate.origin_commits() - before} commit(s)") + link = ("rtt=0, tls=none, local bare origin" if mode == "files" + else f"rtt=0, tls=none, {writes} write(s) per run") + lines.append(figure("M7", f"{mode} mode", f"`{verb}`, exec to exit", times, link)) + record(lines) + + +# ------------------------------------------------------------------ M13 +def _counted(log: Path, offset: int) -> tuple: + """The counting cluster's log lines after `offset`: (connections, + Query messages), from `log_connections`' "connection authorized" lines + and `log_statement=all`'s "statement:" lines, one per simple Query.""" + text = log.read_bytes()[offset:].decode("utf-8", "replace") + return (len(re.findall(r"connection authorized", text)), + len(re.findall(r"LOG: statement: ", text))) + + +def _path_m1(reg, root: Path): + done = fake_write(reg.copy, reg.env, reg.estate.checkout, root / "m1", "repoA-1", "log", + _edit_log_noted("repoA-1", SID_A1, "t255 m1"), "lanes-edit.sh log: t255 m1") + assert done["code"] == 0, (_said_safely(done["snapshot"]), + _said_safely(done["commit"]) if done["commit"] else "the commit did not run, so it has no exit") + + +def _path_m2(reg, root: Path): + log = "lanes/log/repoA-1.md" + appends = Appends(reg.pg, [log]) + text = f"NOTED {EM} lane repoA-1, session {SID_A1}@{WS}, 2026-11-10T00:00:00Z, lane:repoA-1 {EM} t255 m2" + proc = in_one_session(reg.pg, [appends.statements(appends.entry("repoA-1", log, [text]))]) + assert proc.returncode == 0, _said_safely(proc) + + +def _path_m6(reg, root: Path): + proc = run_index(reg.copy, ["render", "--images", "--at", head(reg.pg), "--out", root / "m6"], reg.env) + assert proc.returncode == 0, _said_safely(proc) + + +def _path_m7(reg, root: Path): + proc = VerbEstate(reg.pg, root, "primary", reg).run(["log", "NOTED", "lane:repoA-1", "t255 m7"]) + assert proc.returncode == 0, _said_safely(proc) + + +def _path_m9(reg, root: Path): + """M9's path: answer 2's bind, `lane-start --no-launch --bind <uuid> + repoA 2`, then the guard's `set-row-state` on the lane it leaves (section + 5.1), as `_bind_run` runs them: the body's argv (`_bind_argv`), from + SID_BIND's live session in a window named `BIND_TO` (`_window`). The + case builds `[m9]`'s register with `_bind_seed`, so the lane's log + records a `dir` that exists.""" + estate = VerbEstate(reg.pg, root, "primary", reg) + estate.env.update(LANES_BIND_BOUND_S=str(BOUND_S), LANES_SESSION=SID_BIND) + session = _window(estate, root, BIND_TO, SID_BIND) + try: + for argv in (_bind_argv(), ["set-row-state", "repoA-1", f"PAUSED {DOT} t255 m9"]): + proc = estate.run(argv) + assert proc.returncode == 0, f"`{' '.join(argv)}`: {_said_safely(proc)}" + finally: + session.close() + + +@contextlib.contextmanager +def hook_pid(): + """THE HOOK'S `$$`, FOR A GUARD READ'S `--pid` (contract section 3.6: + "`--pid <pid>` ... is the hook's own pid, `$$`, in forms 2 and 4", and + "the client reads `T0` from it"). It yields the pid of a stand-in for the + hook, a `sleep` started just before the read, as a hook's own start is, + and stops it after the read. T507 cuts a guard read at `T0` + 3.75 s + from that start, and an age at or above the cut exits 2, "too late to + verify" (section 3.6's 2; `register_guard_t0`). The pytest process's own + pid is minutes old on a runner, so with it `[m10]` ended 2 (lane 1's + round 6b census, #165 6827592167, item 2). `[m10]` and `[m5]` each take + one. The stand-in is AT-F7's, `test_sql_register_outage.py`'s + `_stand_in`, at an age of 0.""" + standin = subprocess.Popen(["sleep", "120"], start_new_session=True, + stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL) + try: + yield str(standin.pid) + finally: + _end_group(standin) # T255j: bounded, as `[m5]`'s service is (lane 5's pointer) + + +def _path_m10(reg, root: Path): + """M10's part 4 on primary: the guard's register read through the + direct read, the service down: form 2, the guard's prefetch, + `register read --for guard --prefetch --cache <file> --pid <pid> --repo + <dir> [--lane=<window>]` (CLI412:661; lane 1's T113, called by T507's + `guard_run`). Its `--pid` is a stand-in started just before the read + (`hook_pid`), as the hook's `$$` is, so T507's cut at `T0 + 3.75 s` runs + from the read's own start. The cache file's directory is made first: the + read writes the file's family beside it and makes no directory.""" + (root / "m10").mkdir(parents=True, exist_ok=True) + with hook_pid() as pid: + proc = run_index(reg.copy, ["register", "read", "--for", "guard", "--prefetch", "--cache", + root / "m10" / "cache", "--pid", pid, "--repo", + reg.estate.checkout, "--lane=repoA-1"], reg.env) + assert proc.returncode == 0, _said_safely(proc) + + +#: `[m5]`'S STATE HOME: SHORT, AND OUTSIDE THE TEMPORARY ROOT. The service's +#: one socket is `${XDG_STATE_HOME}/openRepoTools/run/register.sock` (lane 5's +#: socket contract d8, section 2.1): `serve` binds it, and the client +#: connects to it. `sun_path` holds 107 bytes on Linux and 103 on macOS, and +#: the contract's `serve` refuses a path over 103 bytes (`path-too-long`, +#: exit 2). Under `tmp_path` the path followed the temporary root, about 147 +#: bytes on the runner, where lane 1's guard rerun met `OSError: AF_UNIX path +#: too long` (verify-r5-c2b, CI run 43140203269; line AN14). So `[m5]`'s +#: `XDG_STATE_HOME` is a `mkdtemp` of its own in `/tmp`, as line G's estates +#: make theirs (T213i): `/tmp/l2m-` and mkdtemp's 8 characters, 17 bytes, +#: which puts the socket at 49 whatever `TMPDIR` or `--basetemp` is. The case +#: removes it when it ends. +STATE_PARENT = "/tmp" +STATE_PREFIX = "l2m-" +#: The contract's bound on the socket's path, in bytes (section 2.1). +SOCKET_MAX = 103 +#: The guard's line for a read the service did not answer (`7893339:lanes-index:7499`), +#: and how long `[m5]` warms the service before the read it asserts on, as the +#: guard module's `_warm` does (`afc5b2b4:tests/test_sql_register_guard.py:3198`, +#: `:3480`). +FALLBACK = "guard: direct (service unavailable)" +WARM_S = 15.0 + + +def _end_group(proc: subprocess.Popen, wait: float = 10.0) -> None: + """`proc`, started with `start_new_session=True`, ended with its process + group and reaped, and its group never signalled once its id may be + another's (T237zzo; Codex's review of P09 at `21dd3642`, BLOCKING). A + process already reaped, `returncode` set, as after a `poll()` that saw it + end, gets no signal. Otherwise each signal goes to its group while it is + still unreaped, so the group's id is still its own: TERM; up to `wait` s + for its exit, watched by `os.waitid(..., WNOWAIT)`, which does not reap + it; KILL; then one reap, `proc.wait(wait)`, whose `TimeoutExpired` is + raised, not suppressed. A reap by anything else meanwhile raises + `ChildProcessError` from `os.waitid`, before the KILL.""" + if proc.returncode is not None: + return + with contextlib.suppress(ProcessLookupError, PermissionError): + os.killpg(proc.pid, signal.SIGTERM) + end = time.monotonic() + wait + while time.monotonic() < end: + if os.waitid(os.P_PID, proc.pid, os.WEXITED | os.WNOHANG | os.WNOWAIT) is not None: + break + time.sleep(0.05) + with contextlib.suppress(ProcessLookupError, PermissionError): + os.killpg(proc.pid, signal.SIGKILL) + proc.wait(wait) + + +def _signals_kept_to_unreaped(monkeypatch) -> list: + """For the no-engine cases of this module's clean-up (T237zzy): + `os.kill` and `os.killpg` replaced, for the case, by forms that send a + signal only while its target, a pid or the group its pid leads, is still + an unreaped child of this process, as `os.waitid(..., WNOWAIT)` sees it. + Any other signal is sent to nothing and recorded, as (call, pid, + signal), in the list returned.""" + late, real = [], {"kill": os.kill, "killpg": os.killpg} + + def unreaped(pid: int) -> bool: + try: + os.waitid(os.P_PID, pid, os.WEXITED | os.WNOHANG | os.WNOWAIT) + except ChildProcessError: + return False + return True + + def kept(call: str): + def send(pid: int, sig: int) -> None: + if unreaped(pid): + real[call](pid, sig) + else: + late.append((call, pid, signal.Signals(sig).name)) + return send + monkeypatch.setattr(os, "kill", kept("kill")) + monkeypatch.setattr(os, "killpg", kept("killpg")) + return late + + +def test_m13s_group_cleanup_signals_a_group_only_while_its_leader_is_unreaped_and_raises_a_failed_reap( + monkeypatch): + """`_end_group` (T237zzo; Codex's review of P09 at `21dd3642`, + BLOCKING), with no engine (T237zzy): on process groups this case starts, + each led by a process in a session of its own as `[m5]`'s service and + `hook_pid`'s stand-in are, with `_signals_kept_to_unreaped` between it + and every signal. + + (a) A leader already reaped, as `[m5]`'s `poll()` leaves a service that + ended before its socket: no signal at all. + (b) One that TERM ends: its exit is -SIGTERM, and nothing is signalled + once it is reaped. + (c) One deaf to TERM: KILL ends it once `wait` has passed. + (d) One whose reap times out (its `wait` replaced by one that raises): + `TimeoutExpired` is raised, not suppressed. + + Before T237zzo, (a) sent TERM and KILL to the reaped leader's group, (b) + KILL after its own reap, and (d) returned as if the leader were reaped.""" + late = _signals_kept_to_unreaped(monkeypatch) + + def start(argv: list) -> subprocess.Popen: + return subprocess.Popen(argv, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, + start_new_session=True) + + proc = start(["true"]) + proc.communicate(timeout=30) + _end_group(proc, wait=5) + assert late == [], f"(a) a reaped leader's group was signalled: {late}" + + proc = start(["sleep", "30"]) + _end_group(proc, wait=5) + proc.stdout.close() + assert (proc.returncode, late) == (-signal.SIGTERM, []), \ + f"(b) exit {proc.returncode}, signals after the reap {late}" + + proc = start(["bash", "-c", "trap '' TERM; echo deaf; exec sleep 30"]) + assert proc.stdout.readline() == b"deaf\n", "(c) the stand-in never ignored TERM" + _end_group(proc, wait=0.5) + proc.stdout.close() + assert (proc.returncode, late) == (-signal.SIGKILL, []), \ + f"(c) exit {proc.returncode}, signals after the reap {late}" + + proc = start(["sleep", "30"]) + + def stuck(timeout=None, proc=proc): + raise subprocess.TimeoutExpired(proc.args, timeout) + proc.wait = stuck + try: + with pytest.raises(subprocess.TimeoutExpired): + _end_group(proc, wait=5) + finally: + del proc.wait + proc.wait(30) + proc.stdout.close() + assert late == [], f"(d) signals after the reap {late}" + + +def _path_m5(reg, root: Path): + """M13's `[m5]`, T237's (R1's M1): the guard's register read through the + service. `lanes-index serve` starts on the reader's configuration at the + one socket path lane 5's socket contract d8 fixes, + `${XDG_STATE_HOME}/openRepoTools/run/register.sock` (its section 2.1), + under a short state home of the case's own (`STATE_PREFIX`); then form 2, + the guard's prefetch, with the service up, so the counting cluster logs + the service's connection and its one Query per request (section 5.6). + Its `--pid` is a stand-in started just before the read, once the socket + is bound (`hook_pid`), as `[m10]`'s is, so T507's cut at `T0 + 3.75 s` + runs from the read's own start, never from the pytest process's or the + service's. The cache file's directory is made first, as `[m10]`'s is. + + THE SERVICE IS WARMED FIRST, by reads of the same form until one is + answered by the service, with no fallback line, for `WARM_S` at most, + as the guard module's `_warm` warms it + (`afc5b2b4:tests/test_sql_register_guard.py:3483-3496`; lane 2's RV23, + SHOULD 3). One read was not enough: the service answers `unavailable` + while its child is `down` or `connecting` and while a background + whole-file fetch holds it (`7893339:lanes-index:8786-8790`; d8:502), + and a cache miss answers so and starts that fetch (`:8627-8632`), so a + second read could still meet a cold service. The read the case asserts + on is the one after, M5's "with the service warm" (TP:7797). Each + warming read has its own stand-in pid and its own cache file, so the + asserted read is the one this case made before, and a warming read's + end is asserted only by its fallback line: it may fall back to the + direct read. The counts this path adds therefore hold the service's + connection, each warming read's, their direct reads' where they fell + back, and the asserted read's (lane 3's round 6h reading, #165 + 6859307928). + Fails until L5-S1 (lane 5's T512) and T229.""" + state = Path(tempfile.mkdtemp(prefix=STATE_PREFIX, dir=STATE_PARENT)) + try: + sock = state / "openRepoTools" / "run" / "register.sock" + assert len(os.fsencode(str(sock))) <= SOCKET_MAX, \ + f"the service's socket path {sock} is over {SOCKET_MAX} bytes" + env = dict(reg.env, XDG_STATE_HOME=str(state)) + (root / "m5").mkdir(parents=True, exist_ok=True) + serve = subprocess.Popen([sys.executable, str(reg.copy), "serve"], env=env, + stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, start_new_session=True) + try: + end = time.monotonic() + 10 + while not sock.exists() and time.monotonic() < end and serve.poll() is None: + time.sleep(0.05) + assert sock.exists(), f"lanes-index serve bound no socket at {sock}: {serve.poll()}" + + def read(name: str) -> subprocess.CompletedProcess: + with hook_pid() as pid: + return run_index(reg.copy, ["register", "read", "--for", "guard", "--prefetch", + "--cache", root / "m5" / name, "--pid", pid, "--repo", + reg.estate.checkout, "--lane=repoA-1"], env) + + end, warmed = time.monotonic() + WARM_S, 0 + while True: + warmed += 1 + warm = read(f"warm-{warmed}") + if FALLBACK not in warm.stderr: + break + assert time.monotonic() < end, \ + (f"no warming read was answered by the service in {WARM_S:.0f} s ({warmed} reads)", + warm.returncode, _said_safely(warm.stderr, stream="stderr")) + time.sleep(0.2) + proc = read("cache") + assert proc.returncode == 0, (_said_safely(proc), + f"the last of {warmed} warming reads: {warm.returncode}", + _said_safely(warm.stderr, stream="stderr")) + assert FALLBACK not in proc.stderr, \ + (_said_safely(proc), f"the last of {warmed} warming reads: {warm.returncode}", + _said_safely(warm.stderr, stream="stderr")) + finally: + _end_group(serve) + finally: + shutil.rmtree(state, ignore_errors=True) + + +M13_PATHS = {"m1": _path_m1, "m2": _path_m2, "m5": _path_m5, "m6": _path_m6, "m7": _path_m7, + "m9": _path_m9, "m10": _path_m10} + + +@pytest.mark.parametrize("path", list(M13_PATHS)) +def test_each_paths_connections_and_queries_are_counted(pg_engine, request, tmp_path, path): + """M13 (section 5.1; section 5.6): each path run once on T229's counting + cluster, whose log holds each connection and each Query message; the + path's connections (c) and Query messages (q) are read from the lines it + added and recorded, with the path's own oracle (it exits 0). Whether a + ceiling is asserted per path is open point 24, so none is. T237 writes + `[m5]` through the service; each `verify:` names its own ids, so + neither passes with the other's alone (R1's M1).""" + counting = needs(request, "counting_cluster", "lane 2's T229 (section 5.6's counting cluster)") + db = Database(counting, counting.new_database()) + try: + reg = PrimaryRegister(db, tmp_path, _bind_seed(tmp_path / "estate" / "checkout") + if path == "m9" else None) + log = Path(counting.root) / "server.log" + offset = log.stat().st_size + M13_PATHS[path](reg, tmp_path) + c, q = _counted(log, offset) + assert c >= 1, f"{path} made no connection the counting cluster logged" + # Each path's connections are `psql`'s, each sending its statements as simple Query + # messages, so a path that connected sent one; q = 0 is a count that failed (T255i). + assert q >= 1, f"{path} made {c} connection(s) and no Query message the cluster logged" + record([f"| M13 | {platform.node()}, counting cluster, Unix socket | `{path}` | " + f"c={c}, q={q} | n=1 (a count does not vary with load) |"]) + finally: + counting.drop_database(db.name) + + +# ------------------------------------------------------------------ the image cache +def test_the_image_cache_check_and_a_miss_are_timed_per_attempt(pg_engine, pg, tmp_path, monkeypatch): + """Per attempt (AT-9's oracle; lane 4's "[L4-c]", about 3 ms for the + check and about 10 ms for a miss), through lane 1's T302 API in process + (#165 6755106847): the snapshot's image-cache check, `image_cache_head()` + and one `image_cache_get` per path of the head's manifest, each a hit; + and a miss, `image_cache_get` answering None, then `image_cache_put` of + the image read from SQL. Cold once, then 20 warm, each in this case's own + state directory. The oracle: every hit returns bytes that hash to its + digest and equal `render_file`'s image; a miss's put returns that digest, + and the next get returns the bytes. AT-4 (g) proves the cache correct; + this case times it. Fails until T302.""" + reg = PrimaryRegister(pg, tmp_path) + monkeypatch.setenv("XDG_STATE_HOME", str(tmp_path / "cache-state")) + module = _lanes_index_module() + for name in ("image_cache_get", "image_cache_put", "image_cache_head", "image_cache_record"): + assert hasattr(module, name), f"lanes-index has no `{name}`: lane 1's T302 builds it" + paths = sorted(p for p in reg.estate.render_set()) + images = images_of(pg, paths) + n = head(pg) + manifest = {p: module.image_cache_put(images[p]) for p in paths} + assert manifest == {p: sha256(images[p]) for p in paths}, "put returns each image's digest" + module.image_cache_record(n, manifest) + checks, misses = [], [] + for k in range(1 + N_WARM): + start = time.monotonic_ns() + found = module.image_cache_head() + hits = {p: module.image_cache_get(d) for p, d in (found[1] if found else {}).items()} + checks.append((time.monotonic_ns() - start) / 1e6) + assert found is not None and found[0] == n, f"the cache's head is {found and found[0]}, not {n}" + assert hits == images, "each hit is the image render_file gives" + fresh = f"t255 miss {k} {uuid.uuid4()}\n".encode("utf-8") + start = time.monotonic_ns() + assert module.image_cache_get(sha256(fresh)) is None, "a new image is a miss" + digest = module.image_cache_put(fresh) + misses.append((time.monotonic_ns() - start) / 1e6) + assert digest == sha256(fresh) and module.image_cache_get(digest) == fresh + record([figure("AT-9", "fixture cluster, Unix socket", f"the image cache's check, {len(paths)} paths", + checks, "in process, no psql; lane 4: about 3 ms"), + figure("AT-9", "fixture cluster, Unix socket", "an image-cache miss: get, then put", + misses, "in process, no psql; lane 4: about 10 ms")]) + + +# ------------------------------------------------------------------ the delayed relay +#: Section 5.6's shapes as lane 5's netem run times them (#165 6722703424), +#: on T229's TLS cluster: A, a new `psql` per read with one query through +#: `-c`; B1, a held session sending a reader's statements one by one; B2, +#: the same as one Query joined with `\;`. C stays on the bench. +SHAPE_READS = ["SET search_path TO pg_catalog", "BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY", + "SELECT 1", "COMMIT"] +RTTS_MS = (20, 150) + + +#: How long `_ask` waits for its marker, by the monotonic clock (T255k). +ASK_S = 60.0 +#: How long a held session's end waits for its reap once it is killed, and +#: then for its two readers together (T255m). +REAP_S = 10.0 + + +def _lines_of(stream, lines: queue.Queue) -> None: + """Each line of `stream` onto `lines`, then None, at its end or where a + read fails, so no reader ends without it (T255k; T255m). The reader + closes `stream` itself, in a `finally`, before its None (T255o; Codex's + review of P09 at `b8f9e35a`, item 7): no other thread need close a pipe + while its read may be blocked, and a reader that outlives its session's + end still closes its pipe when it reaches the pipe's end.""" + try: + for line in stream: + lines.put(line) + finally: + try: + stream.close() + finally: + lines.put(None) + + +def _held(env: dict, psql: str): + """A held `psql` session, its stdout read line by line into + `session.lines` and its stderr into `session.errs`, each by a thread of + its own, both kept in `session.readers` (T255k; T255m). So `_ask` can + wait with a deadline, a full stderr pipe never stalls `psql`, and its end + (`_end_held`) can join both.""" + session = subprocess.Popen([psql, "-X", "-q", "-A", "-t", "-v", "ON_ERROR_STOP=1"], + stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, env=env, bufsize=1) + session.lines, session.errs = queue.Queue(), queue.Queue() + session.readers = [threading.Thread(target=_lines_of, args=(stream, into), daemon=True) + for stream, into in ((session.stdout, session.lines), + (session.stderr, session.errs))] + for reader in session.readers: + reader.start() + return session + + +def _whole(text, what: str) -> int: + """`text` as an int, or an AssertionError that names `what` and quotes + none of `text` (T255w; lane 2's pre-review RV9-37 of P09 at `d9a1f2bf`, + S5): int()'s own ValueError quotes up to 200 characters of its input, + which is a tool's or a writer's output here. The AssertionError is + raised after the `except`, not in it, so its `__cause__` is None and its + `__context__` is not that ValueError (None, unless `_whole` is itself + called inside an `except`): nothing of `text` is kept on it (T255z; lane + 2's pre-review RV9-38 of P09 at `3f9fcac4`, N3: before T255z, `from + None` only hid the ValueError from display, and `__context__` still held + it). `text` is still this frame's argument, which a long traceback + prints and a short one does not (T205e).""" + try: + return int(text) + except (TypeError, ValueError): + pass + raise AssertionError(f"{what} is not a whole number; its text is not shown") + + +def test_measures_whole_keeps_no_text_it_could_not_parse_on_its_error_or_in_the_report(request): + """T255z (lane 2's pre-review RV9-38 of P09 at `3f9fcac4`, N3; lane 3's + ruling 6949488277, B1), with no engine and no process: measure's + `_whole` is given a planted value it cannot parse. Its AssertionError + has no `__cause__` and no `__context__`, and the planted value is in + none of its `str`, `repr`, `args`, formatted traceback or pytest's own + report of the failure (bounds' `_reported`). Before T255z its + `__context__` was int()'s ValueError, which quotes the value. The + planted value is no credential of any login.""" + import traceback + planted = f"fake-{uuid.uuid4().hex}" + with pytest.raises(AssertionError) as failed: + _whole(f"x {planted} y", "a planted value") + error = failed.value + assert error.__cause__ is None, "a cause is kept" + assert error.__context__ is None, f"a {type(error.__context__).__name__} is kept as its context" + shown = "".join(traceback.format_exception(type(error), error, error.__traceback__)) + for where, said in (("str", str(error)), ("repr", repr(error)), ("args", repr(error.args)), + ("formatted traceback", shown), ("pytest's report", _reported(request, failed))): + assert planted not in said, f"the planted value is in the error's {where}" + + +def _drained(lines: queue.Queue) -> str: + """What a reader put on `lines`, up to its None or to what is there now + (T255m).""" + text = [] + while True: + try: + line = lines.get_nowait() + except queue.Empty: + return "".join(text) + if line is None: + return "".join(text) + text.append(line) + + +def _end_pipes(session): + """The held session's two readers joined, `REAP_S` together by one + deadline, then its pipes closed: stdin, and the stdout and stderr whose + readers have ended (T255n; Codex's review of P09 at `d3a2fd5c`, SHOULD + 2). A reader still running is blocked in a read of its pipe, and a close + of that pipe waits for that read, which a process the session started + can hold without end; so that pipe is left to its reader, which closes + it at that pipe's end (`_lines_of`, T255o), and the reader is named. An + ended reader has closed its own pipe, so its close here does nothing. + Returns the first failure, for `_end_held` to raise: a reader + still running, or a close that failed; None where all is ended. Each + later failure is the `__cause__` of the one before it, so none is + dropped (T255r; lane 2's pre-review RV9-36 of P09 at `2407ea06`, N2); + before T255r only the first was returned.""" + end = time.monotonic() + REAP_S + for reader in session.readers: + reader.join(max(0.0, end - time.monotonic())) + alive = [reader.is_alive() for reader in session.readers] + running = [reader.name for reader, on in zip(session.readers, alive) if on] + failures = [] + if running: + failures.append(AssertionError( + f"the held session's reader {', '.join(running)} still ran {REAP_S:g} s after its " + f"reap (exit {session.returncode}, None where the reap failed): a process it " + f"started, or the session itself where unreaped, holds its stdout or stderr")) + ended = [pipe for pipe, on in zip((session.stdout, session.stderr), alive) if not on] + for pipe in [session.stdin, *ended]: + try: + pipe.close() + except OSError as exc: + failures.append(exc) + for failure, cause in zip(failures, failures[1:]): + failure.__cause__ = cause + return failures[0] if failures else None + + +def _end_held(session, *, kill: bool) -> None: + """The held session ended and reaped, its two readers joined and its + pipes closed, each wait bounded and each failure raised (T255m; T255n; + Codex's reviews of P09 at `21dd3642` and at `d3a2fd5c`, SHOULD 2 each). + Its stdin is closed under `suppress(OSError)` first, so a pipe a failed + `_ask` broke cannot skip the rest. Without `kill` it has 60 s to end once + its stdin is closed, and one that outlives them is killed, as T255l did: + the case does not fail for that alone. With `kill`, as `_ask` gives up, + it is killed at once. The kill is sent only while the session is + unreaped, `poll()` first; then one reap, `wait(REAP_S)`. + + Whatever the kill and the reap do, the readers are joined and the pipes + closed (`_end_pipes`), in a `finally`. Before T255n a reap that raised + skipped both. A kill that raises is kept and the bounded reap is still + tried (T255p; Codex's review of P09 at `b8f9e35a`, item 8); before + T255p it skipped the reap. Each failure is kept and raised once all + are done, in one chain (T255q; Codex's review of P09 at `fb359e64`, + lane 3's post 6945142764, SHOULD 1): the kill's error first, then the + reap's, as its `TimeoutExpired`, then the first clean-up failure, each + the `__cause__` of the one before it, and each only where it happened. + So where both the kill and the reap fail, the raised error still says + that the session may be alive and unreaped; before T255q the reap's + error was dropped there.""" + with contextlib.suppress(OSError): + session.stdin.close() + if not kill: + with contextlib.suppress(subprocess.TimeoutExpired): + session.wait(timeout=60) + killed = reaped = None + try: + try: + if session.poll() is None: + session.kill() + except Exception as exc: + killed = exc + try: + session.wait(timeout=REAP_S) + except Exception as exc: + reaped = exc + finally: + left = _end_pipes(session) + failures = [failure for failure in (killed, reaped, left) if failure is not None] + for failure, cause in zip(failures, failures[1:]): + failure.__cause__ = cause + if failures: + raise failures[0] + + +def _ask(session, text: str) -> None: + """Send `text` on the held session and wait for its marker line, `ASK_S` + at most (T255k; Codex's review of P09 at `f4f0ebce`, SHOULD 5; lane 3's + ruling 6932114864, by a reader thread): the lines come from + `session.lines`, with a monotonic deadline. Past it, or where the session + ends first, the session is ended, killed, reaped and its readers joined, + each bounded and raised where it fails (`_end_held`, T255m), and the case + fails with its exit and the stderr its reader read.""" + marker = f"t255-{uuid.uuid4().hex[:8]}" + session.stdin.write(text + f"\n\\echo {marker}\n") + session.stdin.flush() + end, line = time.monotonic() + ASK_S, "" + while line is not None and line.strip() != marker: + try: + line = session.lines.get(timeout=max(0.0, end - time.monotonic())) + except queue.Empty: + line = None + if line is None: + _end_held(session, kill=True) + raise AssertionError(f"the held session gave no {marker} line within {ASK_S:g} s, or " + f"ended (exit {session.returncode}); " + f"{_said_safely(_drained(session.errs), stream='stderr')}") + + +#: T255m's stand-ins for `psql`: one that answers each `\echo` line as +#: `psql` does and ends at its stdin's end, and one that never answers and, +#: with `T255M_HOLD` set, first starts a process that holds its stdout and +#: stderr that many seconds. +T255M_ANSWERS = r"""#!/bin/bash +echo "t255m stand-in: answers" >&2 +while IFS= read -r line; do + case $line in + '\echo '*) printf '%s\n' "${line#'\echo '}" ;; + esac +done +""" +T255M_SILENT = r"""#!/bin/bash +echo "t255m stand-in: silent" >&2 +if [ -n "${T255M_HOLD:-}" ]; then sleep "$T255M_HOLD" & fi +exec sleep 30 +""" + + +@pytest.mark.parametrize("case", ["read-fails", "answers", "never-answers", "reap-times-out", + "end-reap-times-out", "pipe-held"]) +def test_a_held_sessions_end_is_bounded_joins_its_readers_and_raises_what_it_cannot_end( + tmp_path, monkeypatch, case): + """The held session's helpers, `_lines_of`, `_held`, `_ask` and + `_end_held` (T255m; Codex's review of P09 at `21dd3642`, SHOULD 2), with + no engine: `psql` is one of T255m's stand-ins, `ASK_S` is 0.5 s and + `REAP_S` 1 s. + + `[read-fails]`: a reader whose read fails still ends its lines with None, + its stream closed by then (T255o). Every other case ends with both + readers ended and both their pipes closed (T255o; Codex's review of P09 + at `b8f9e35a`, item 7). + `[answers]`: `_ask` returns, and `_end_held` ends the session 0 with both + readers joined. `[never-answers]`: `_ask` fails naming its marker and the + stderr the reader read, the session killed and reaped and both readers + joined. `[reap-times-out]`: the same, with the reap after the kill timing + out (the session's `wait` replaced by one that raises): `_ask` raises + `TimeoutExpired`. `[end-reap-times-out]`: `_end_held` without `kill`, on a + session that does not end at its stdin's end and whose reap after the + kill times out, raises `TimeoutExpired`. `[pipe-held]`: the session has + started a process that holds its pipes for 5 s; `_ask` fails within + `REAP_S` of its kill, naming the reader still running, and the readers end + once that process does, each closing its own pipe at that pipe's end. + + Before T255m, a failed read ended the reader with no None; the reader + was never kept or joined; `_ask`'s reap after the kill and the shapes' + `finally`'s were suppressed; and `_ask` then read stderr to its end, + which waited as long as any process held the pipe. Before T255o a reader + closed no stream, so a pipe left to its reader at the deadline stayed + open after that reader's end.""" + monkeypatch.setitem(globals(), "ASK_S", 0.5) + monkeypatch.setitem(globals(), "REAP_S", 1.0) + if case == "read-fails": + class Breaks: + closed = False + + def __iter__(self): + yield "one\n" + raise OSError("the pipe broke") + + def close(self): + self.closed = True + lines, broken = queue.Queue(), Breaks() + with pytest.raises(OSError): + _lines_of(broken, lines) + got = [lines.get_nowait() for _ in range(lines.qsize())] + assert got == ["one\n", None], f"a reader whose read fails must end with None: {got}" + assert broken.closed, "a reader whose read fails must close its own stream" + return + psql = tmp_path / "psql" + psql.write_text(T255M_ANSWERS if case == "answers" else T255M_SILENT, encoding="utf-8") + psql.chmod(0o755) + session = _held(dict(os.environ, T255M_HOLD="5" if case == "pipe-held" else ""), str(psql)) + try: + if case == "answers": + _ask(session, "SELECT 1;") + _end_held(session, kill=False) + assert session.returncode == 0, f"the answering stand-in ended {session.returncode}" + elif case == "never-answers": + with pytest.raises(AssertionError, match="gave no t255-") as failed: + _ask(session, "SELECT 1;") + said = str(failed.value) + assert "t255m stand-in: silent" not in said, f"the stand-in's stderr is shown:\n{said}" + assert "); stderr: 1 line(s), 0 of them WARNING lines" in said, f"its stderr's counts:\n{said}" + assert session.returncode == -signal.SIGKILL, f"exit {session.returncode}" + elif case in ("reap-times-out", "end-reap-times-out"): + def stuck(timeout=None): + raise subprocess.TimeoutExpired(session.args, timeout) + session.wait = stuck + with pytest.raises(subprocess.TimeoutExpired): + if case == "reap-times-out": + _ask(session, "SELECT 1;") + else: + _end_held(session, kill=False) + else: + start = time.monotonic() + with pytest.raises(AssertionError, match="still ran"): + _ask(session, "SELECT 1;") + took = time.monotonic() - start + assert took < 3.5, f"_ask took {took:.1f} s, waiting on a pipe another process holds" + end = time.monotonic() + 30 + for reader in session.readers: + reader.join(max(0.0, end - time.monotonic())) + finally: + session.__dict__.pop("wait", None) + if case != "pipe-held": + _end_held(session, kill=True) + assert not any(reader.is_alive() for reader in session.readers), "a reader outlived the end" + closed = (session.stdout.closed, session.stderr.closed) + assert closed == (True, True), f"(stdout, stderr) closed are {closed} once the readers ended" + + +class _StandInPipe: + """One of a held session's pipes, for T255n's case: its close is + recorded in `events`, and then raises `OSError` where it `breaks` + (T255q).""" + + def __init__(self, name: str, events: list, breaks: bool = False): + self.name, self.events, self.breaks = name, events, breaks + + def close(self) -> None: + self.events.append(f"close {self.name}") + if self.breaks: + raise OSError(f"T255q's stand-in: the close of {self.name} failed") + + +class _StandInReader: + """One of a held session's readers, for T255n's case: its join is + recorded in `events`, and it has ended once joined, unless it `stays`.""" + + def __init__(self, name: str, events: list, stays: bool): + self.name, self.events, self.stays, self.joined = name, events, stays, False + + def join(self, timeout=None) -> None: + self.events.append(f"join {self.name}") + self.joined = True + + def is_alive(self) -> bool: + return self.stays or not self.joined + + +class _StandInSession: + """A held session that never ends in the time it is given, for T255n's + case, with no process: its kill and each wait are recorded in `events`, + with its readers' joins and its pipes' closes, and each wait raises + `TimeoutExpired`. Its stderr reader `stays` running where asked, its + kill raises `PermissionError` where it `refuses` (T255p), and its + stdout's close raises `OSError` where it `breaks` (T255q).""" + + args, returncode = ("psql",), None + + def __init__(self, stays: bool, refuses: bool = False, breaks: bool = False): + self.events, self.refuses = [], refuses + self.stdin, self.stdout, self.stderr = (_StandInPipe(name, self.events, + breaks and name == "stdout") + for name in ("stdin", "stdout", "stderr")) + self.readers = [_StandInReader("stdout-reader", self.events, False), + _StandInReader("stderr-reader", self.events, stays)] + + def poll(self): + return None + + def kill(self) -> None: + self.events.append("kill") + if self.refuses: + raise PermissionError("T255p's stand-in: the kill was refused") + + def wait(self, timeout=None): + self.events.append(f"wait {timeout:g}") + raise subprocess.TimeoutExpired(self.args, timeout) + + +@pytest.mark.parametrize("case", ["kill", "no-kill", "reader-left", "kill-fails", "reader-left-clean"]) +def test_a_held_sessions_end_joins_its_readers_and_closes_its_pipes_where_its_reap_fails(case): + """`_end_held` where the reap after the kill raises (T255n; Codex's + review of P09 at `d3a2fd5c`, SHOULD 2), with no engine and no process: + the session, its two readers and its three pipes are stand-ins that + record, in order, each kill, wait, join and close (`_StandInSession`), + and each of the session's waits raises `TimeoutExpired`. + + `[kill]`, as `_ask` gives up, and `[no-kill]`, as a shape's `finally` + ends its session: the reap's `TimeoutExpired` is raised, and only once + both readers are joined and stdin, stdout and stderr closed. Before + T255n it was raised straight from the reap, with no reader joined and + neither reader's pipe closed. `[reader-left]`: the stderr reader still + runs at the deadline, and stdout's close raises `OSError`. The reap's + error is still the one raised, with that reader named in its cause and + stdout's `OSError` as that cause's own (T255r; lane 2's pre-review + RV9-36 of P09 at `2407ea06`, N2: before T255r the `OSError` was + dropped); stdin and stdout are closed, and stderr is left to its + reader, since a close of it would wait on the read the reader is + blocked in (`_end_pipes`). `[kill-fails]`: the kill raises + `PermissionError` (T255p; Codex's review of P09 at `b8f9e35a`, item 8), + and stdout's close raises `OSError` (T255q). The bounded reap is still + tried, and the kill's error is the one raised, once both readers are + joined and the three pipes closed, with the reap's `TimeoutExpired` as + its cause and stdout's `OSError` as the reap's (T255q; Codex's review of + P09 at `fb359e64`, lane 3's post 6945142764, SHOULD 1). Before T255p + the kill's error skipped the reap; before T255q the reap's error was + dropped, and the `OSError` was the kill's cause. `[reader-left-clean]` + (T255x; lane 2's pre-review RV9-37 of P09 at `d9a1f2bf`, S8): the stderr + reader still runs at the deadline and every close succeeds, as + `[reader-left]` was before T255r. The reap's error is raised, with only + that reader's error as its cause, and nothing after it.""" + session = _StandInSession(stays=case in ("reader-left", "reader-left-clean"), + refuses=case == "kill-fails", + breaks=case in ("kill-fails", "reader-left")) + raised = PermissionError if case == "kill-fails" else subprocess.TimeoutExpired + with pytest.raises(raised) as failed: + _end_held(session, kill=case != "no-kill") + want = (["close stdin"] + (["wait 60"] if case == "no-kill" else []) + + ["kill", f"wait {REAP_S:g}", "join stdout-reader", "join stderr-reader", + "close stdin", "close stdout"] + + ([] if case in ("reader-left", "reader-left-clean") else ["close stderr"])) + assert session.events == want, f"_end_held did {session.events}, not {want}" + cause = failed.value.__cause__ + if case == "reader-left": + assert isinstance(cause, AssertionError) and "stderr-reader still ran" in str(cause), repr(cause) + after = cause.__cause__ + assert isinstance(after, OSError) and "close of stdout" in str(after), \ + f"the reader's error has not stdout's close as its cause: {after!r}" + assert after.__cause__ is None, f"the chain goes on: {after.__cause__!r}" + elif case == "reader-left-clean": + assert isinstance(cause, AssertionError) and "stderr-reader still ran" in str(cause), repr(cause) + assert cause.__cause__ is None, f"a clean close gave the reader's error a cause: {cause.__cause__!r}" + elif case == "kill-fails": + chain = [failed.value, cause, getattr(cause, "__cause__", None)] + assert isinstance(cause, subprocess.TimeoutExpired), \ + f"the kill's error has not the reap's as its cause: {chain!r}" + assert isinstance(chain[2], OSError) and "close of stdout" in str(chain[2]), \ + f"the reap's error has not stdout's close as its cause: {chain!r}" + assert chain[2].__cause__ is None, f"the chain goes on: {chain[2].__cause__!r}" + else: + assert cause is None, f"a clean clean-up gave the reap's error a cause: {cause!r}" + + +@pytest.mark.parametrize("rtt", RTTS_MS, ids=[str(r) for r in RTTS_MS]) +@pytest.mark.parametrize("shape", ["a", "b1", "b2"]) +def test_each_shape_on_a_delayed_relay_is_recorded(pg_engine, request, shape, rtt): + """Section 5.6's option B, which lane 3 ruled for open point 23 (R-P23; + #165 6741861590): each shape through T229's `delayed_loopback` in front + of the TLS cluster, `delay_s` = RTT / 2 each way, 30 timed runs after 3 + warm-ups (lane 5's counts), beside the same shape at RTT 0 on the TLS + cluster itself, so the row gives the network share and the round trips + it implies (n = (median - median at 0) / RTT). Every run answers. Never + asserted; the relay models no slow start, loss or kernel timer, so it + checks n for small messages.""" + tls = needs(request, "tls_cluster", "lane 2's T229 (section 5.6's TLS cluster)") + relay_of = getattr(pgcluster, "delayed_loopback", None) + assert relay_of is not None, "tests/pgcluster.py has no delayed_loopback: lane 2's T229 builds it" + psql = tls.tool("psql") + + def timings(env: dict) -> list: + times = [] + if shape == "a": + for _ in range(33): + ms, proc = timed(lambda: subprocess.run([psql, "-X", "-A", "-t", "-c", "SELECT 1"], + capture_output=True, text=True, env=env, + timeout=120, check=False)) + assert (proc.returncode, proc.stdout.strip()) == (0, "1"), _said_safely(proc) + times.append(ms) + else: + session = _held(env, psql) + try: + text = ("\n".join(s + ";" for s in SHAPE_READS) if shape == "b1" + else " \\; ".join(SHAPE_READS) + ";") + for _ in range(33): + ms, _none = timed(lambda: _ask(session, text)) + times.append(ms) + finally: + # Ended, reaped and its readers joined, each wait bounded and each failure + # raised; one that outlives 60 s is still killed, and that alone does not + # fail the case (T255l; T255m). + _end_held(session, kill=False) + return times[3:] + + env = tls.client_env() + local = _stats(timings(env)) + with relay_of(int(env["PGPORT"]), rtt / 2000.0) as relay: + port = getattr(relay, "port", relay) + delayed = _stats(timings(dict(env, PGHOST="127.0.0.1", PGPORT=str(port)))) + trips = (delayed["median"] - local["median"]) / rtt + record([f"| relay | {platform.node()}, TLS cluster behind the delayed loopback | shape {shape.upper()} " + f"at RTT {rtt} ms | median {delayed['median']:.1f} ms, p95 {delayed['p95']:.1f} ms, " + f"n={delayed['n']}; at RTT 0 median {local['median']:.1f} ms | about {trips:.1f} round trips |"]) + + +# ============================================================ T254: M9 (phase W) + +#: `bound_s` at `c` = 2 with one address, as `guard-bind` computes it from +#: the configuration (section 5.1's M9 rule; lane 4's "The record, and its +#: liveness test"), and the variable tests set it by. +BOUND_S = 500 +#: The session that answers 2 and binds, and the lane it leaves. +SID_BIND = "bbbbbbbb-0009-4000-8000-00000000b009" +#: The lane answer 2 binds, whose name the guard gives the window before the +#: bind (`guard_answer`'s rename), and its `lane-start` arguments as the +#: guard's `lane_start_args` prints them. +BIND_TO, BIND_ARGS = "repoA-2", ("repoA", "2") + + +def _bind_argv() -> list: + """The body's bind, `lane-start --no-launch --bind "$G_ID" <args>` (B14 + tasks:677; design W:5444; the guard's call in `lanes-edit.sh`): `--bind` + takes the transcript uuid of the session live in the window, then the + lane's arguments.""" + return ["@lane-start", "--no-launch", "--bind", SID_BIND, *BIND_ARGS] + + +def _bind_seed(checkout: Path) -> dict: + """SEED with `BIND_TO`'s log recording `checkout` as its `dir`, so the + bind finds a directory that exists where `lane-start` looks for it (its + rung 3, the lane's log), with the guard's own arguments. SEED's + `dir /work/repoA2` exists on no host.""" + files = dict(SEED) + log = f"lanes/log/{BIND_TO}.md" + assert files[log].count("; dir /work/repoA2\n") == 1, files[log] + files[log] = files[log].replace("; dir /work/repoA2\n", f"; dir {checkout}\n") + return files + + +def _bind_run(db, root: Path, mode: str) -> tuple: + """One M9 run on a fresh estate with a local bare origin (section 5.3): + answer 2's bind, `lane-start --no-launch --bind repoA 2`, then the + guard's `set-row-state` on the lane it leaves, each exec to exit in the + guard's own path. Returns (the bind's ms, `set-row-state`'s ms, the + register writes on primary or the origin's new commits in files mode, + and the head or the commit count before the bind). + The bind's argv is the body's (`_bind_argv`), run from SID_BIND's live + session in a window named `BIND_TO` (`_window`), on an estate whose log + records a `dir` that exists (`_bind_seed`).""" + estate = VerbEstate(db, root, mode, files=_bind_seed(root / "estate" / "checkout")) + estate.env.update(LANES_BIND_BOUND_S=str(BOUND_S), LANES_SESSION=SID_BIND, + CLAUDE_CODE_SESSION_ID=SID_BIND) + session = _window(estate, root, BIND_TO, SID_BIND) + try: + before = head(db) if mode == "primary" else estate.origin_commits() + spent = [] + for argv in (_bind_argv(), + ["set-row-state", "repoA-1", f"PAUSED {DOT} answer 2 bound this session to repoA-2"]): + ms, proc = timed(lambda: estate.run(argv)) + assert proc.returncode == 0, (f"{mode}: `{' '.join(argv)}` exited {proc.returncode}: " + f"{_said_safely((proc.stdout + proc.stderr)[-600:])}") + spent.append(ms) + finally: + session.close() + grown = (head(db) if mode == "primary" else estate.origin_commits()) - before + return spent[0], spent[1], grown, before + + +@pytest.mark.parametrize("mode", list(MODES)) +def test_the_bind_and_the_guards_set_row_state_are_timed_in_both_modes(pg_engine, pg, tmp_path, mode): + """M9 (section 5.1; AT-F6): answer 2's bind and the guard's + `set-row-state` on the lane it leaves, exec to exit, cold once and 20 + warm, each run on a fresh estate with a local bare origin; recorded + beside `bound_s` (500 s at `c` = 2), never asserted (ruling 16: the + detached form applies, so M9 decides nothing). One case per mode, as + TP:6346 gives them and F12b's T254 text owes them (R-F11-2): `[files]` + and `[primary]`. Each id records its own two figures, the bind's and + `set-row-state`'s, and asserts no time. + + The oracle, in each id: every call exits 0; on primary each run's bind + is one `start-record` write and `set-row-state` one more, so the journal + grows by exactly two and their write ids are distinct (AT-F6: one + journal entry for the bind, two for answer 2); in files mode the + origin's `main` grows by at least those two commits. `[files]` waits for + T107 to T110, and `[primary]` fails until lane 4's L4-B9 and lane 5's + L5-A1 and L5-B1 land (tasks:2412; lane 3, #165 6808937880, batch e L2-5).""" + binds, rows_set = [], [] + for k in range(1 + N_WARM): + if mode == "primary": + name = pg.cluster.new_database() + db = Database(pg.cluster, name) + else: + name, db = None, pg + try: + bind_ms, set_ms, grown, before = _bind_run(db, tmp_path / f"{mode}-{k}", mode) + if mode == "primary": + assert grown == 2, f"run {k}: the journal grew by {grown}, not 2" + ids = rows(db, f"SELECT count(DISTINCT write_id) AS d FROM journal WHERE seq > {before}") + assert ids == [{"d": 2}], ids + else: + assert grown >= 2, f"run {k}: the origin's main grew by {grown} commit(s)" + finally: + if name is not None: + pg.cluster.drop_database(name) + binds.append(bind_ms) + rows_set.append(set_ms) + link = f"rtt=0, tls=none; bound_s={BOUND_S} (c=2, N_a=1)" + record([figure("M9", f"{mode} mode, fresh estate, local bare origin", + "`lane-start --no-launch --bind`, exec to exit", binds, link), + figure("M9", f"{mode} mode, fresh estate, local bare origin", + "the guard's `set-row-state` on the lane it leaves", rows_set, link)]) diff --git a/tests/test_sql_register_outage.py b/tests/test_sql_register_outage.py new file mode 100644 index 00000000..3e7269c0 --- /dev/null +++ b/tests/test_sql_register_outage.py @@ -0,0 +1,2570 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Feature 007's AT-F7 and AT-F11: the guard under a declared outage and over +a stale mirror (L2-N3; T215; FR-037, FR-056, FR-059) +(opensoft/openRepoTools#165). + +The test plan's twelve names, byte for byte. Its case ids: AT-F7's +`[floor|clamp|room]` and AT-F11's `[depth-200|depth-250]`; M11 is +`test_the_register_seq_lookup_is_timed_bounded_beside_the_unbounded_and_grep_forms`. + +THE RULE TESTED IS TODAY'S (open point 31; R-B4S): with the database +unreachable the guard refuses 2, and it answers from the mirror only under a +declaration. Those refusals are the prefetch's, form 2's (contract section +3.6): `register read --for guard --prefetch --cache <file> --pid <pid> --repo +<dir> [--lane=<window>]`. The guard's second read, form 4, is noted and never +refused, and no case here reaches it. + +THE DECLARATION is always written by lane 1's `lanes-index outage declare` +(T121; L1-A18), in D20's form, `--until <UTC> --why <words>`, with +`--mirror-seq <m>` where the test names `m` (lane 1, #165 comment +6754680212), never by hand. So the declaration side of every case is green +once T121 is in, and the guard side waits for lane 5's T507 (L5-A3, L5-A5). + +THE GUARD is driven as T220 drives it (`test_sql_register_bounds.py`): +`bash lanes-edit.sh guard` from a copy of `lanes-edit.sh` beside T203's +flipped `lanes-index` (`flipped_copy`), the hook's JSON on stdin, a live +session record and a stand-in `tmux` in the lane's window (T203c's +`guard_session`), and `LANES_INDEX_CONFIG` naming a `mode=primary` +configuration. Two things are this module's own: + +- the lane's checkout is under `$HOME/projects`, so that the guard's scope + test (`under_projects_root`, clause (e)) lets the prompt through to the + register read; outside it the guard returns 0 before any read; +- "exits as the mirror's answer gives" is read as: exits as the same guard, + on the same hook input and the same checkout, exits in files mode + (`mode=index`, the reference run, with `LANES_NO_FETCH=1` so that it moves + no ref). The mirror's answer is then today's parser's. + +THE SESSION (T203c's `guard_session(home, bin, checkout, session_id=...)`; +T215d): today's guard reads this workstation's session records after its +workspace and tmux checks and before any register read, and refuses 2 where +none is live in its window (lane 5, #165 6755266457: T507's prefetch reads +after that check). So each case that drives the guard in the lane's window +runs with a live record whose session id is the estate's own, `Estate.session`, +the one a register row names (`{session}`), in the window `repoA-2`, and the +stand-in `tmux` it writes to the estate's `bin`; the case's `env()` and +`hook_input()` come from it. The hook's JSON is compact, as the harness sends +it, since the guard's `jstr` reads `"cwd":"<dir>"` with no blank after the +colon. A case that takes the session out of any window (`TMUX=None`) has no +session record at all: AT-P3's `CLAUDE_NO_LANE=1` and `status` cases, as its +text says, and AT-D20's write case. AT-P3's guard refusal runs in the window +with a live record: the guard refuses 2 before any read without one, so only +a lane session reaches the prefetch and the direct read it asserts (lane 3's +T507 ruling (1), #165 6783977598). An estate has no `request`, so +`_end_guard_sessions`, an autouse fixture, ends each session with the test, +as `request.addfinalizer(session.close)` would. The estate's base +environment is `guard_strip_env(os.environ, strip=("T215_",))`, which takes +`PROJECTS_ROOT` and `AGENT_PROTOCOL_ROOT` out beside the lane's, the +harness's, tmux's, libpq's and the fake's variables (F10's items 27, 28). + +THE STAND-INS, each first on `PATH`: + +- T203's register fake `psql`, which answers `psql --version` itself since + T203b, behind this module's start logger (`START_PSQL`): the fake's log + holds no time, so the logger writes each call's start, on the wall clock, + to `psql-starts.log` beside it, and a `--version` call goes straight on and + is not logged. The fake is taught to exit 2, as a stopped database does + (`STOPPED`); the service's socket is absent, since phase 1 has no service; +- a `git` wrapper (`GIT_WRAPPER`) that logs each call's wall-clock start and + argv. A MIRROR CALL is a `git` call with an argument naming + `origin/<branch>`: the guard's mirror path reads `origin/$LANES_BRANCH` as + last fetched (contract section 3.6, "Form C"). This is the module's reading + of "the `git` wrapper's log shows no mirror call"; +- for the real-engine case, a timing wrapper in front of the real `psql` + (`TIMING_PSQL`), whose watcher logs the call's end even where the client's + timer kills it. + +`Register-Seq` histories are written by `git fast-import` into a bare origin: +a render commit carries the trailer `Register-Seq: <k>`, a handoff commit +none. + +Every case fails until L5-A3, L5-A5 and L1-A18 land, and the rollback's head +until lane 3's T304 and, for the write on primary before it, lane 4's T415; +`test_the_guard_refuses_a_ref_behind_a_rollbacks_head` +and the silent database are real-engine cases on `tests/pgcluster.py`'s `pg`. +""" + +from __future__ import annotations + +import calendar +import errno +import json +import os +import re +import select +import shutil +import signal +import socket +import statistics +import subprocess +import sys +import threading +import time +import uuid +from pathlib import Path + +import pytest + +from conftest import REPO, WINDOWS_SKIP + +pytestmark = [WINDOWS_SKIP, pytest.mark.skipif( + shutil.which("bash") is None or shutil.which("git") is None, + reason="the lane tooling is bash over git")] + +#: THE LANDING GATE'S TABLE (T280; its reader, `tests/sql_register_gate.py`, +#: says how a table is read), TEMPORARY: T281 removes it in the last set. +#: Where the gate is active, each id is skipped until every task its row +#: names has landed, and the skip names them; an id's own row, +#: `name[param]`, replaces its function's. Each row holds the fails-until +#: clauses of the task that owns the test (T215, T219 or T279), each L-label +#: read as the task that covers it, as lane 2's gate tables plan (GP-24, +#: version 2) gives them. Each `tasks:<n>` is tasks.md's line at `204145ae`, +#: the reader's `SPEC_COMMIT`. There is no `"*"` row: T121, which every row +#: shares, is in each row itself (T219m, T215r), since the reader adds a +#: `"*"` row to every id, one with no row of its own too. T215p's relay case +#: and T219k's password-absence case, which run on stand-ins with no engine, +#: have no row: they run ungated. +SQL_REGISTER_GATE_TABLE = { + "test_a_declared_outage_lets_the_guard_answer_from_the_mirror": ("T117", "T121", "T304", "T409", "T507"), # T219; tasks:2082 + "test_a_declared_outage_lets_the_guard_read_the_mirror_with_service_and_database_down": ("T121", "T504", "T505", "T506", "T507"), # T215; tasks:2022 + "test_a_rollback_rerun_declares_before_it_goes_on": ("T121", "T304", "T326", "T424", "T425"), # T279; tasks:2564 + "test_a_rollbacks_declaration_counts_only_where_the_guards_read_finds_the_switch_at_files": ("T117", "T121", "T304", "T326", "T327", "T409", "T507"), # T219; tasks:2082 + "test_a_rollbacks_start_declares_the_outage": ("T121", "T304", "T326", "T424", "T425"), # T279; tasks:2564 + "test_an_expired_or_foreign_declaration_changes_nothing": ("T117", "T121", "T304", "T409", "T507"), # T219; tasks:2082 + "test_claude_no_lane_lets_a_session_through_before_any_input": ("T117", "T121", "T304", "T409", "T507"), # T219; tasks:2082 + "test_outage_declare_is_refused_where_the_probe_reads_primary": ("T117", "T121", "T304", "T409", "T507"), # T219; tasks:2082 + "test_outage_declare_on_a_persons_word_during_a_rollback_is_refused_and_prints_the_rollback_form": ("T121", "T304"), # T219; tasks:2082 + "test_outage_declare_refuses_while_the_database_answers_or_without_until": ("T117", "T121", "T304", "T409", "T507"), # T219; tasks:2082 + "test_outage_declare_rollback_is_refused_for_a_wrong_k_a_missing_mirror_seq_or_a_switch_it_cannot_read": ("T117", "T121", "T304", "T409", "T507"), # T219; tasks:2082 + "test_outage_declare_takes_mirror_seq_from_a_fetch_or_the_flag_and_refuses_with_neither": ("T121", "T504", "T505", "T506", "T507"), # T215; tasks:2022 + "test_outage_declare_writes_its_fields_and_clear_removes_it": ("T117", "T121", "T304", "T409", "T507"), # T219; tasks:2082 + "test_status_and_rollback_run_with_no_lane_session_and_no_guard": ("T117", "T121", "T304", "T409", "T507"), # T219; tasks:2082 + "test_status_reports_a_declaration_left_in_place": ("T117", "T121", "T304", "T409", "T507"), # T219; tasks:2082 + "test_the_declaration_is_read_once_at_the_prefetch": ("T121", "T504", "T505", "T506", "T507"), # T215; tasks:2022 + "test_the_guard_refuses_2_when_no_commit_within_the_bound_carries_register_seq": ("T121", "T504", "T505", "T506", "T507"), # T215; tasks:2022 + "test_the_guard_refuses_a_mirror_older_than_the_declared_seq": ("T121", "T504", "T505", "T506", "T507"), # T215; tasks:2022 + "test_the_guard_refuses_a_ref_behind_a_rollbacks_head": ("T121", "T304", "T326", "T327", "T504", "T505", "T506", "T507"), # T215; tasks:2022 + "test_the_guards_outage_refusal_names_the_store_the_cause_and_both_ways_out": ("T117", "T121", "T304", "T409", "T507"), # T219; tasks:2082 + "test_the_register_seq_lookup_finds_the_trailer_at_depths_0_and_199": ("T121", "T504", "T505", "T506", "T507"), # T215; tasks:2022 + "test_the_register_seq_lookup_is_timed_bounded_beside_the_unbounded_and_grep_forms": ("T121", "T504", "T505", "T506", "T507"), # T215; tasks:2022 + "test_under_a_declaration_a_direct_read_left_under_0_5_s_does_not_start": ("T121", "T504", "T505", "T506", "T507"), # T215; tasks:2022 + "test_under_a_declaration_a_silent_database_is_capped_and_the_mirror_answers_inside_the_budget": ("T121", "T504", "T505", "T506", "T507"), # T215; tasks:2022 + "test_with_no_declaration_the_guard_exits_2_with_service_and_database_down": ("T121", "T504", "T505", "T506", "T507"), # T215; tasks:2022 + "test_without_a_declaration_the_same_age_still_starts_the_direct_read": ("T121", "T504", "T505", "T506", "T507"), # T215; tasks:2022 + "test_writes_and_deciding_reads_still_refuse_during_a_declared_outage": ("T117", "T121", "T304", "T409", "T415", "T507"), # T219; tasks:2082 + "test_outage_declare_rollback_is_refused_for_a_wrong_k_a_missing_mirror_seq_or_a_switch_it_cannot_read[not-a-rollback-entry]": ("T121", "T304"), # T219; tasks:2082 + "test_outage_declare_rollback_is_refused_for_a_wrong_k_a_missing_mirror_seq_or_a_switch_it_cannot_read[wrong-k]": ("T121", "T304"), # T219; tasks:2082 +} + +INDEXER = REPO / "lanes-index" +#: The lane, and the tmux window it runs in. +WINDOW = "repoA-2" +#: `register_label=`: the database the declaration names. +LABEL = "register-test" +#: D20's form on Brett's word (Y:3073): an expiry far ahead, and his words. +UNTIL = "2999-01-01T00:00:00Z" +WHY = "the register database is down for its host move" +#: SVC-8's shares under a declaration (AT-F7, "Ruling"): the direct read's +#: cap, the mirror path's start line, the floor, and the guard's budget. +CAP_DECLARED, CAP, START_LINE, FLOOR, BUDGET = 3.65, 3.75, 3.75, 0.5, 4.5 +#: The harness's `GUARD_TIMEOUT`: the hook runs under its 5 s kill timer. +GUARD_TIMEOUT = 5 +#: Form C's page (SVC-12; AT-F11, "The bounded lookup"). +PAGE = 200 +#: The register's schema on the session cluster (T205). +SCHEMA = "lanes_register" +#: A stopped database: every call refused at the connect. +STOPPED = [{"exit": 2, "stderr": "psql: error: connection to server at \"127.0.0.1\", port " + "55432 failed: Connection refused\n"}] + +START_PSQL = r'''#!/usr/bin/env python3 +# T215's start logger in front of T203's register fake: each call that carries +# a request has its start (wall clock) logged to psql-starts.log beside it, +# since the fake's log holds no time. T203b's fake answers `psql --version` +# itself (F10's item 25), so a --version call goes straight on, unlogged. +import json, os, sys, time +here = os.path.dirname(os.path.abspath(__file__)) +if sys.argv[1:] != ["--version"]: + with open(os.path.join(here, "psql-starts.log"), "a", encoding="utf-8") as handle: + handle.write(json.dumps({"start": time.time(), "argv": sys.argv[1:]}) + "\n") +fake = os.path.join(here, "register-fake-psql") +os.execv(fake, [fake] + sys.argv[1:]) +''' + +#: The `git` wrapper: one line per call, its wall-clock start, its working +#: directory and its argv, each field ended by US (0x1f); then the real `git`. +GIT_WRAPPER = r'''#!/bin/sh +{ date +%s.%N | tr -d '\n'; printf '\037%s\037' "$(pwd -P)"; for a in "$@"; do printf '%s\037' "$a"; done; printf '\n'; } >> "$T215_GIT_LOG" +exec "$T215_REAL_GIT" "$@" +''' + +#: THE TIMING WRAPPER for the real-engine case: logs the call's start, then a +#: watcher in a session of its own logs the call's end once the call's +#: process is gone, whether it exited or the client's timer killed it. +TIMING_PSQL = r'''#!/usr/bin/env python3 +import json, os, sys, time +here = os.path.dirname(os.path.abspath(__file__)) +real = os.environ["T215_REAL_PSQL"] +if sys.argv[1:] == ["--version"]: + os.execv(real, [real] + sys.argv[1:]) +log = os.path.join(here, "psql-timing.log") +start = time.time() +me = os.getpid() +with open(log, "a", encoding="utf-8") as handle: + handle.write(json.dumps({"call": me, "start": start}) + "\n") +if os.fork() == 0: + os.setsid() + devnull = os.open(os.devnull, os.O_RDWR) + for fd in (0, 1, 2): + os.dup2(devnull, fd) + while os.getppid() == me: + time.sleep(0.005) + with open(log, "a", encoding="utf-8") as handle: + handle.write(json.dumps({"call": me, "end": time.time()}) + "\n") + os._exit(0) +os.execv(real, [real] + sys.argv[1:]) +''' + +#: THE WATCHER'S LAG (lane 5, #165 6813898970): `TIMING_PSQL`'s watcher polls +#: `os.getppid()` every 5 ms, so the `end` it logs trails the call's real end +#: by up to one poll, and by its own wake-up besides on a busy runner (T507's +#: CI round 3 saw the mirror's first `git` 2.2 ms before a logged end). Each +#: comparison of that `end` with another clock allows 10 ms, two polls: one +#: for the poll, one for the wake-up. A mirror path started during the read, +#: which runs on to its cut, still fails: it starts far more than 10 ms early. +WATCHER_LAG_S = 0.010 + + +def _script(path: Path, text: str) -> Path: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8") + path.chmod(0o755) + return path + + +def _private(path: Path, text: str = "") -> Path: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8") + path.chmod(0o600) + return path + + +def _render(seq: int) -> str: + return f"render the register at seq {seq}\n\nRegister-Seq: {seq}\n" + + +def _handoff(i: int) -> str: + return f"handoff {i}\n" + + +def _fast_import(bare: Path, messages: list, env: dict, register: str = "# LANES.md\n") -> None: + """Append `messages`, one commit each, first-parent, to `bare`'s `main` + by `git fast-import`. The first commit of an empty repository writes the + register; every later one keeps its parent's tree.""" + git = env["T215_REAL_GIT"] + has_main = subprocess.run([git, "--git-dir", str(bare), "rev-parse", "-q", "--verify", + "refs/heads/main"], capture_output=True, env=env).returncode == 0 + out = [] + register = register.encode("utf-8") + for i, message in enumerate(messages, 1): + data = message.encode("utf-8") + out.append(b"commit refs/heads/main\n") + out.append(b"mark :%d\n" % i) + out.append(b"committer t <t@example.invalid> %d +0000\n" % (1700000000 + i)) + out.append(b"data %d\n%s\n" % (len(data), data)) + if i > 1: + out.append(b"from :%d\n" % (i - 1)) + elif has_main: + out.append(b"from refs/heads/main^0\n") + else: + out.append(b"M 100644 inline lanes/LANES.md\ndata %d\n%s\n" % (len(register), + register)) + out.append(b"M 100644 inline lanes/log/README.md\ndata 7\nlogs.\n\n") + out.append(b"done\n") + subprocess.run([git, "--git-dir", str(bare), "fast-import", "--quiet", "--done"], + input=b"".join(out), check=True, env=env, capture_output=True) + + +def _subcommand(args: list) -> str: + """git's subcommand in `args`, past `-C <dir>`, `-c <k=v>` and the + global flags.""" + i = 0 + while i < len(args): + a = args[i] + if a in ("-C", "-c", "--git-dir", "--work-tree", "--namespace"): + i += 2 + continue + if a.startswith("-"): + i += 1 + continue + return a + return "" + + +def _run_dir(cwd: str, args: list) -> str: + """The directory a `git` call runs in: its working directory, moved by + each `-C <dir>` ahead of the subcommand.""" + here, i = cwd, 0 + while i < len(args) and args[i].startswith("-"): + if args[i] == "-C" and i + 1 < len(args): + here = os.path.join(here, args[i + 1]) + i += 2 if args[i] in ("-C", "-c", "--git-dir", "--work-tree", "--namespace") else 1 + return os.path.realpath(here) + + +def _workspace_resolution(args: list) -> bool: + """`args` is one of `lanes_workspace_root`'s three calls (lane 5's F1): + `rev-parse --is-inside-work-tree`, `remote get-url origin` or + `rev-parse --show-toplevel`.""" + i = 0 + while i < len(args) and args[i].startswith("-"): + i += 2 if args[i] in ("-C", "-c", "--git-dir", "--work-tree", "--namespace") else 1 + sub, rest = (args[i], args[i + 1:]) if i < len(args) else ("", []) + return ((sub == "rev-parse" and rest in (["--is-inside-work-tree"], ["--show-toplevel"])) + or (sub == "remote" and rest == ["get-url", "origin"])) + + +def _bounded(args: list) -> bool: + """`args` is form C: `log --first-parent` limited to 200, with no + `--grep`.""" + joined = " ".join(args) + limited = (re.search(r"(^| )-n ?200( |$)", joined) is not None + or "--max-count=200" in args or "-200" in args) + return limited and "--first-parent" in args and not any(a.startswith("--grep") + for a in args) + + +#: The live guard sessions this test's estates have made (T203c), ended by +#: `_end_guard_sessions` when the test ends. +_SESSIONS: list = [] + + +@pytest.fixture(autouse=True) +def _end_guard_sessions(request): + """`request.addfinalizer(session.close)` for every guard session an + estate made in the test (an `Estate` has no `request` of its own).""" + def end(): + while _SESSIONS: + _SESSIONS.pop().close() + request.addfinalizer(end) + + +class Estate: + """One test's estate: a bare origin, the lane's register checkout under + `$HOME/projects`, the copies of `lanes-edit.sh` and the flipped + `lanes-index`, the stand-ins, and a `mode=primary` configuration. The + guard's session (a live record and a stand-in `tmux`, T203c's + `guard_session`) is made when the first case that needs it asks.""" + + def __init__(self, root: Path, origin_messages: list, register: str = "# LANES.md\n"): + """`register` is `lanes/LANES.md`'s text, with `{session}` standing for + this estate's session id, the one the hook's input carries.""" + from sql_register_helpers import REGISTER_FAKE_PSQL, flipped_copy, guard_strip_env + self.root = root + #: The session's id: the hook's `session_id`, the record's, and the one + #: a register row names (`{session}`). + self.session = str(uuid.uuid4()) + self._guard_session = None + root.mkdir(parents=True, exist_ok=True) + try: + self.copy = flipped_copy(INDEXER, root / "tool", True) + except ValueError as exc: + raise AssertionError(f"lanes-index cannot be flipped to its git half ({exc}): " + f"lane 1's RENDER_GIT_HALF (T105) has not landed, and " + f"mode=primary is refused without it") from exc + for name in ("lanes-edit.sh", "repos.tsv", "lane-start"): + if (REPO / name).exists(): + shutil.copy2(REPO / name, root / "tool" / name) + self.bin, self.fakebin = root / "bin", root / "fakebin" + _script(self.bin / "git", GIT_WRAPPER) + _script(self.fakebin / "register-fake-psql", REGISTER_FAKE_PSQL) + _script(self.fakebin / "psql", START_PSQL) + self.git_log = root / "git.log" + self.psql_log = root / "psql.log" + self.starts = self.fakebin / "psql-starts.log" + self.answers = root / "psql-answers.json" + self.answers.write_text(json.dumps(STOPPED), encoding="utf-8") + home = self.home = root / "home" + self.origin = root / "origin.git" + self.wip = home / "projects" / "wip" + self.wip.parent.mkdir(parents=True) + #: W, the workspace checkout (Amendment 9(a)), a clone of its own. + self.w = root / "W" + (root / "t").mkdir() + self.cache = root / "cache" / "se" + self.cache.parent.mkdir() + self.passfile = _private(root / "conf" / "pgpass") + # THE BASE ENVIRONMENT, T203c's: the lane's, the harness's, tmux's, + # libpq's and the fake's variables out, `PROJECTS_ROOT` and + # `AGENT_PROTOCOL_ROOT` with them (F10's items 27 and 28), and this + # module's own. + env = guard_strip_env(os.environ, strip=("T215_",)) + env.update(HOME=str(home), XDG_STATE_HOME=str(root / "state"), + XDG_CONFIG_HOME=str(root / "config"), TMPDIR=str(root / "t"), + LANES_WORKSTATION="Eagle", LANES_NO_GITHUB="1", LANES_REPO=str(self.wip), + LANES_WORKSPACE_ROOT=str(self.w), + T215_REAL_GIT=shutil.which("git"), T215_GIT_LOG=str(self.git_log), + FAKE_PSQL_LOG=str(self.psql_log), FAKE_PSQL_ANSWERS=str(self.answers), + GIT_AUTHOR_NAME="t", GIT_AUTHOR_EMAIL="t@example.invalid", + GIT_COMMITTER_NAME="t", GIT_COMMITTER_EMAIL="t@example.invalid", + PATH=os.pathsep.join([str(self.bin), str(self.fakebin), + os.environ.get("PATH", os.defpath)])) + self.env = env + git = env["T215_REAL_GIT"] + subprocess.run([git, "init", "-q", "--bare", "-b", "main", str(self.origin)], + check=True, env=env) + _fast_import(self.origin, origin_messages, env, register.replace("{session}", self.session)) + subprocess.run([git, "clone", "-q", str(self.origin), str(self.wip)], check=True, + env=env, capture_output=True) + # THE WORKSPACE, W (Amendment 9(a)): whatever `lanes-edit.sh + # workspace-root` answers, the checkout `outage declare` fetches in + # (lane 1's reading 1; #165 comment 6755305741, item 4), and whose + # `origin/main` `status` reads. It is a clone of its own, never the + # lane's checkout that `LANES_REPO` names: `import`, and `cutover + # --import` through it, refuse a `LANES_REPO` that names W (contract + # 4.18:987; lane 1's group 6, #165 6807494089). `LANES_WORKSPACE_ROOT`, + # `lanes-edit.sh`'s test seam, names it, and `workspace.yaml`'s + # `path:` names the same W. + subprocess.run([git, "clone", "-q", str(self.origin), str(self.w)], check=True, + env=env, capture_output=True) + (home / ".agents").mkdir() + (home / ".agents" / "workspace.yaml").write_text( + f"repository: {self.origin}\npath: {self.w}\n", encoding="utf-8") + + # -------------------------------------------------------------- the estate + def grow(self, messages: list) -> None: + """Origin gains `messages`; the checkout's `origin/main` stays as + last fetched.""" + _fast_import(self.origin, messages, self.env) + + def fetch(self) -> None: + subprocess.run([self.env["T215_REAL_GIT"], "-C", str(self.wip), "fetch", "-q", "origin"], + check=True, env=self.env, capture_output=True) + + def tip(self) -> str: + return subprocess.run([self.env["T215_REAL_GIT"], "-C", str(self.wip), "rev-parse", + "refs/remotes/origin/main"], check=True, env=self.env, + capture_output=True, text=True).stdout.strip() + + def lane_checkout(self, lane: str = WINDOW) -> Path: + """`<c>`, lane `lane`'s own register checkout (T219g): a clone of + origin where `lanes-edit.sh`'s `lane_checkout_path` puts it + (Amendment 23 S1), `<W>-lanes/<lane>`, W being the real path of the + W that `LANES_WORKSPACE_ROOT` names, as `lane-checkout <lane> + --create` makes one. On primary a write refuses with 2, nothing sent, + where `<c>` is not there (T415's `pw_checkout`; tasks:1154), so a case + whose write must reach the register makes it first, as the writes + module's `make_lane_checkout` does (T241e). Real git, so the git log + holds none of it.""" + real = Path(os.path.realpath(self.w)) + target = real.parent / f"{real.name}-lanes" / lane + target.parent.mkdir(parents=True, exist_ok=True) + subprocess.run([self.env["T215_REAL_GIT"], "clone", "-q", str(self.origin), str(target)], + check=True, env=self.env, capture_output=True) + return target + + def config(self, mode: str = "primary", url: str | None = None, + name: str = "conf") -> Path: + """A configuration with both URLs on loopback (the fake's host rule), + the label the declaration names, and `mode`.""" + url = url or "postgresql://t215_login@127.0.0.1:55432/register_db" + return _private(self.root / name / "lanes-index.conf", "\n".join([ + f"mode={mode}", f"register_url={url}", f"register_passfile={self.passfile}", + f"reader_url={url}", f"reader_passfile={self.passfile}", + f"register_label={LABEL}", f"register_schema={SCHEMA}", ""])) + + # ------------------------------------------------------------ the declaration + def declare(self, config: Path, *, mirror_seq: int | None = None, + rollback: bool = False) -> subprocess.CompletedProcess: + """`lanes-index outage declare` (T121), under the stopped fake, so the + probe's database does not answer from this host.""" + argv = [sys.executable, str(self.copy), "outage", "declare"] + if rollback: + argv += ["--rollback"] + else: + argv += ["--until", UNTIL, "--why", WHY] + if mirror_seq is not None: + argv += ["--mirror-seq", str(mirror_seq)] + env = dict(self.env, LANES_INDEX_CONFIG=str(config), LANES_LANE=WINDOW, + PATH=os.pathsep.join([str(self.fakebin), self.env["PATH"]])) + return subprocess.run(argv, capture_output=True, text=True, env=env, + cwd=str(self.wip), timeout=120, stdin=subprocess.DEVNULL) + + def declared(self, config: Path, *, mirror_seq: int) -> dict: + """Declare on Brett's word at `mirror_seq`, assert it was written, and + return its fields.""" + proc = self.declare(config, mirror_seq=mirror_seq) + path = config.parent / "register-outage" + assert proc.returncode == 0 and path.exists(), ( + f"`outage declare --until --why --mirror-seq {mirror_seq}` (T121) exited " + f"{proc.returncode} and wrote {'a' if path.exists() else 'no'} declaration: " + f"{proc.stderr.strip()[-400:]}") + return dict(line.split("=", 1) for line in + path.read_text(encoding="utf-8").splitlines() if "=" in line) + + # ------------------------------------------------------------------ the guard + def guard_session(self): + """The live session the guard cases run in (T203c): a record for a + live pid, `self.session` in the window `repoA-2`, on this workstation + (`$HOME/.claude/sessions`), and the stand-in `tmux` it writes to `bin`. + Made once, and ended with the test by `_end_guard_sessions`.""" + from sql_register_helpers import guard_session + if self._guard_session is None: + self._guard_session = guard_session(self.home, self.bin, self.wip, window=WINDOW, + session_id=self.session) + _SESSIONS.append(self._guard_session) + return self._guard_session + + def guard_env(self, config: Path, **extra) -> dict: + """The hook's environment, in the lane's window: the session's + (`TMUX`, `TMUX_PANE`, the stand-in `tmux` first on `PATH`). An `extra` + value of None removes that variable. `TMUX=None` takes the session out + of any window: there is then no session, and no record is written.""" + base = dict(self.env, LANES_INDEX_CONFIG=str(config), LANES_LANE=WINDOW) + if "TMUX" in extra and extra["TMUX"] is None: + for key, value in extra.items(): + if value is None: + base.pop(key, None) + else: + base[key] = value + return base + return self.guard_session().env(base, **extra) + + def hook_input(self, windowed: bool = True) -> str: + """The hook's JSON, compact as the harness sends it: the guard's + `jstr` reads `"<key>":"<value>"` with no blank after the colon. In the + lane's window it is the session's (`guard_session().hook_input()`); + out of any window (`windowed=False`) it is the same JSON, built here, + and no session record is written.""" + if windowed: + return self.guard_session().hook_input() + return json.dumps({"hook_event_name": "UserPromptSubmit", + "session_id": self.session, "cwd": str(self.wip), + "prompt": "hello"}, separators=(",", ":")) + + def guard(self, config: Path, **extra) -> dict: + """The hook, `lanes-edit.sh guard`, under its 5 s kill timer, in a + process group of its own. Returns its exit (None where killed), its + output, `t0` (wall clock, at its start) and its elapsed seconds.""" + argv = ["bash", str(self.root / "tool" / "lanes-edit.sh"), "guard"] + env = self.guard_env(config, **extra) + hook = self.hook_input(windowed=extra.get("TMUX", True) is not None) + t0 = time.time() + start = time.monotonic() + proc = subprocess.Popen(argv, stdin=subprocess.PIPE, stdout=subprocess.PIPE, + stderr=subprocess.PIPE, text=True, cwd=str(self.wip), + env=env, start_new_session=True) + killed = False + try: + out, err = proc.communicate(hook, timeout=GUARD_TIMEOUT) + except subprocess.TimeoutExpired: + killed = True + os.killpg(proc.pid, signal.SIGKILL) + out, err = proc.communicate() + return {"exit": None if killed else proc.returncode, "killed": killed, + "out": out + err, "err": err, "t0": t0, "elapsed": time.monotonic() - start} + + def reference(self) -> int: + """The same guard on the same checkout in files mode: the mirror's + answer, as today's parser gives it. It fetches nothing.""" + result = self.guard(self.config(mode="index", name="conf-index"), LANES_NO_FETCH="1") + assert not result["killed"], "the files-mode guard was killed at 5 s" + return result["exit"] + + # --------------------------------------------------------------------- logs + def psql_starts(self) -> list: + if not self.starts.exists(): + return [] + return [json.loads(line) for line in self.starts.read_text(encoding="utf-8").splitlines()] + + def git_calls(self) -> list: + if not self.git_log.exists(): + return [] + calls = [] + for line in self.git_log.read_text(encoding="utf-8", errors="replace").splitlines(): + fields = line.split("\x1f") + calls.append({"t": float(fields[0]), "cwd": fields[1], + "args": [f for f in fields[2:] if f != ""]}) + return calls + + def mirror_calls(self) -> list: + """Every `git` call run in the mirror checkout, `git -C <root>` or a + call whose working directory is it: T121's three are `fetch -q origin + <branch>`, `rev-parse --verify -q refs/remotes/origin/<branch>^{commit}` + and the paged `log` given the tip's sha (lane 1, #165 comment + 6755305741, reading 1). + + Left out: the three calls `lanes-edit.sh` makes at file scope on every + start where it resolves its workspace from `workspace.yaml` + (`lanes_workspace_root`): `rev-parse --is-inside-work-tree`, `remote + get-url origin` and `rev-parse --show-toplevel`. They read no mirror, + and they come before the guard's read (lane 5's F1, #165 6812547449). + This estate's `LANES_WORKSPACE_ROOT` (T215f) skips them, so they are + left out for a guard run whose workspace is the checkout itself.""" + root = os.path.realpath(self.wip) + return [c for c in self.git_calls() if _run_dir(c["cwd"], c["args"]) == root + and not _workspace_resolution(c["args"])] + + def log_calls(self) -> list: + return [c for c in self.git_calls() if _subcommand(c["args"]) == "log"] + + def reset_logs(self) -> None: + for path in (self.git_log, self.psql_log, self.starts): + if path.exists(): + path.unlink() + + # -------------------------------------------------------- the guard's client + def client(self, config: Path, pid: int) -> tuple: + """Form 2, the guard's prefetch, run as the guard's client with the + pid of a stand-in for the hook. Returns (the process, its end on the + wall clock).""" + argv = [sys.executable, str(self.copy), "register", "read", "--for", "guard", + "--prefetch", "--cache", str(self.cache), "--pid", str(pid), + "--repo", str(self.wip), f"--lane={WINDOW}"] + proc = subprocess.run(argv, capture_output=True, text=True, cwd=str(self.wip), + env=self.guard_env(config), timeout=60, + stdin=subprocess.DEVNULL) + return proc, time.time() + + +def _label(fields: dict) -> str: + """The declared line the guard prints in place of the cause (D20; + contract section 3.6, `.outage`'s `label=`).""" + return f"(declared outage {fields['utc']}: {fields['why']})" + + +def _behind(seen: int, declared: int) -> str: + """Lane 5's SVC-12 text (Y:4472-4474), up to its semicolon.""" + return f"the mirror here is at seq {seen}, behind the declared outage's seq {declared}" + + +def _record(what: str, measured: float, bound: float, rule: str) -> None: + print(f"T215 {what}: {measured:.3f} s against the design's {bound:g} s ({rule}); " + f"margin {bound - measured:+.3f} s") + + +def _answers_from_the_mirror(estate: Estate, result: dict, fields: dict, reference: int, + tip: str) -> None: + assert not result["killed"], "the hook was killed at 5 s, and the prompt passed" + assert f"read: mirror at {tip[:12]}" in result["out"], ( + f"the guard does not say it read the mirror at {tip[:12]}: {result['out'][-600:]}") + assert _label(fields) in result["out"], ( + f"the guard does not print the declared line {_label(fields)!r}: " + f"{result['out'][-600:]}") + assert result["exit"] == reference, ( + f"the guard exited {result['exit']}, where the mirror's answer is {reference}") + + +# ==================================================================== AT-F7 + +def test_a_declared_outage_lets_the_guard_read_the_mirror_with_service_and_database_down( + tmp_path): + """AT-F7: with the outage declared, the service's socket absent and the + database stopped, the guard's direct read fails, and then it answers + from the mirror, says so with the declared line, and exits as the + mirror's answer gives, never killed. The direct read comes first.""" + estate = Estate(tmp_path, [_render(1), _render(2), _render(3)]) + config = estate.config() + fields = estate.declared(config, mirror_seq=3) + estate.reset_logs() + result = estate.guard(config) + starts, mirror = estate.psql_starts(), estate.mirror_calls() + assert starts, "the guard made no direct read before the mirror: the fake psql has no call" + assert mirror, "the guard made no mirror call" + assert mirror[0]["t"] >= starts[0]["start"], "the mirror was read before the direct read" + _answers_from_the_mirror(estate, result, fields, estate.reference(), estate.tip()) + + +def test_with_no_declaration_the_guard_exits_2_with_service_and_database_down(tmp_path): + """AT-F7: with nothing declared, the service's socket absent and the + database stopped, the guard tries its direct read, exits 2, and never + reads the mirror.""" + estate = Estate(tmp_path, [_render(1), _render(2), _render(3)]) + config = estate.config() + result = estate.guard(config) + assert not result["killed"], "the hook was killed at 5 s, and the prompt passed" + assert estate.psql_starts(), "the guard made no direct read: the fake psql has no call" + assert result["exit"] == 2, f"the guard exited {result['exit']}: {result['out'][-600:]}" + assert estate.mirror_calls() == [], f"the guard read the mirror: {estate.mirror_calls()}" + assert "read: mirror" not in result["out"] + + +class StartupRelay: + """D9's F2, as T220 has it: a relay on loopback, port 0, to the cluster's + Unix socket, that forwards until the server's first ReadyForQuery and then + goes silent, holding both ends open.""" + + READY = re.compile(rb"Z\x00\x00\x00\x05[ITE]") + #: The bound on each upstream connect (T215p). A Unix socket's connect can + #: wait on a full backlog until it completes or times out: `CONNECT_WAIT` bounds it. + CONNECT_WAIT = 5.0 + #: `close()`'s one deadline for every join (T215p). + CLOSE_WAIT = 10.0 + + def __init__(self, unix_path: str): + self.unix_path, self.held, self.done = unix_path, [], False + self.lock, self.pumps = threading.Lock(), [] + self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self.sock.bind(("127.0.0.1", 0)) + self.sock.listen(64) + self.port = self.sock.getsockname()[1] + self.thread = threading.Thread(target=self._accept, daemon=True) + self.thread.start() + + def _accept(self): + self.sock.settimeout(0.2) + while not self.done: + try: + conn, _ = self.sock.accept() + except OSError: + continue + self._relay(conn) + + def _relay(self, conn): + """`conn` relayed to the cluster's socket (T215p): its upstream is + tracked with it under `close()`'s lock before a bounded connect, so + `close()` shuts both down whatever the connect is doing; a connect + that fails untracks and closes both, unless `close()` has begun, + which then owns them; and the pump is listed and started under that + lock, or not at all once `done` is set (T215n).""" + upstream = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + with self.lock: + if self.done: + conn.close() + upstream.close() + return + self.held += [conn, upstream] + try: + upstream.settimeout(self.CONNECT_WAIT) + upstream.connect(self.unix_path) + upstream.settimeout(None) + except OSError: + with self.lock: + if self.done: + return + self.held.remove(conn) + self.held.remove(upstream) + conn.close() + upstream.close() + return + with self.lock: + if not self.done: + pump = threading.Thread(target=self._pump, args=(conn, upstream), daemon=True) + self.pumps.append(pump) + pump.start() + + def _pump(self, client, server): + seen, silent = b"", False + while not self.done: + try: + ready, _, _ = select.select([client, server], [], [], 0.2) + except (OSError, ValueError): # a socket `close()` has closed (T215p) + return + for end in ready: + try: + data = end.recv(65536) + except OSError: + return + if not data: + return + if silent: + continue + try: # `close()`'s shutdown ends a blocked sendall() (T215p) + if end is server: + seen = (seen + data)[-64:] + client.sendall(data) + if self.READY.search(seen): + silent = True + else: + server.sendall(data) + except OSError: + return + + def close(self): + """No new connection; every held socket shut down, a pair whose + upstream connect is under way among them, so that a pump blocked in + `sendall()` ends at once; the accept thread and every pump joined by + one deadline, CLOSE_WAIT from now; every socket and the listener + closed; and then a thread still alive raised as a RuntimeError that + names it (T215p; Codex's SHOULD 3 on P09 at `21dd3642`). The snapshot + is taken under the lock each accept registers under, so nothing + registered after it is left open or unjoined (T215n).""" + with self.lock: + self.done = True + held, threads = list(self.held), [self.thread] + self.pumps + for conn in held: + try: + conn.shutdown(socket.SHUT_RDWR) + except OSError: + pass + end_by = time.monotonic() + self.CLOSE_WAIT + for thread in threads: # each loop sees `done` within its 0.2 s + thread.join(max(0.0, end_by - time.monotonic())) + left = [thread.name for thread in threads if thread.is_alive()] + for conn in held: + conn.close() + self.sock.close() + if left: + raise RuntimeError(f"AT-F7's relay on port {self.port} has {left} alive at its " + f"close()'s {self.CLOSE_WAIT:g} s deadline") + + +#: T215p's cases (Codex's SHOULD 3 on P09 at `21dd3642`), and the bound on each +#: of their waits, which only a failure waits out. +RELAY_CASES, RELAY_WAIT = ["full-backlog", "blocked-pump", "thread-left"], 10.0 + + +class _Accepting: + """A relay's listener, as its accept thread reads it (T215p): `waiting` + is set once an accept waits through it, so a client that connects after + that is accepted through it; `accepted`, once an accept returns, so the + relay has its client and goes on to its upstream connect, which `done` + does not stop.""" + + def __init__(self, sock): + self.sock, self.waiting, self.accepted = sock, threading.Event(), threading.Event() + + def accept(self): + self.waiting.set() + pair = self.sock.accept() + self.accepted.set() + return pair + + def __getattr__(self, name): + return getattr(self.sock, name) + + +def _cluster_stand_in(backlog: int) -> tuple: + """A Unix listener of the standard library in place of the cluster's + socket, in Linux's abstract namespace, so that no path's length or file + is in play: (the listener, the name a relay connects to). With a backlog + of 0, one connection queued fills it.""" + name = f"\0t215p-{uuid.uuid4().hex}" + listener = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + listener.bind(name) + listener.listen(backlog) + return listener, name + + +def _relay_threads_left(relay) -> list: + """The names of the relay's threads still alive: its accept thread and each pump.""" + return [t.name for t in [relay.thread] + list(relay.pumps) if t.is_alive()] + + +def _peer_closed(sock, wait: float) -> bool: + """Whether `sock`'s peer closed it within `wait` seconds, by EOF or by a + reset, after whatever it had sent.""" + sock.settimeout(wait) + try: + while sock.recv(65536): + pass + return True + except socket.timeout: + return False + except OSError: + return True + + +def _stalls(sock) -> bool: + """Send `sock` zeros, which hold no ReadyForQuery, until a send waits a + second: the relay reading from it has stopped, its pump blocked in + `sendall()` to a client that never reads. False if 512 MiB went first.""" + sock.settimeout(1.0) + chunk, sent = bytes(65536), 0 + while sent < (512 << 20): + try: + sent += sock.send(chunk) + except socket.timeout: + return True + return False + + +@pytest.mark.skipif(not sys.platform.startswith("linux"), + reason="T215p's stand-in for the cluster is in Linux's abstract Unix namespace") +@pytest.mark.parametrize("case", RELAY_CASES) +def test_the_relays_close_ends_a_connect_and_a_blocked_pump_and_fails_on_a_thread_left(case): + """T215p (Codex's SHOULD 3 on P09 at `21dd3642`), with no engine: a Unix + listener of the standard library stands in for the cluster's socket, in + front of AT-F7's `StartupRelay`. `[full-backlog]`: the stand-in's + backlog is full, so a connect to it would wait; the relay's has a bound, + its client's end is closed, and `close()` leaves no thread. + `[blocked-pump]`: the stand-in sends to a client that never reads until + the pump blocks in `sendall()`; `close()` shuts the sockets down before + it joins, so the pump ends and no thread is left. `[thread-left]`: a + pump that never ends; `close()` fails at its deadline, naming it and + only it. Before T215p the connect came before the sockets were tracked + and had no bound, the pumps were joined before the sockets were shut + down, and a join that timed out passed unchecked.""" + stand_in, name = _cluster_stand_in(0 if case == "full-backlog" else 16) + relay = StartupRelay(name) + opened, release, raised, label = [stand_in], threading.Event(), None, "t215p-stuck-pump" + listener = relay.sock = _Accepting(relay.sock) + try: + waiting = listener.waiting.wait(RELAY_WAIT) + assert waiting, f"[{case}] the relay's accept thread never waited through its listener" + if case == "full-backlog": # the backlog's one place taken + opened.append(socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)) + opened[-1].connect(name) + client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + opened.append(client) + client.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 4096) + client.settimeout(RELAY_WAIT) + client.connect(("127.0.0.1", relay.port)) + accepted = listener.accepted.wait(RELAY_WAIT) + assert accepted, f"[{case}] the relay never accepted its client" + if case == "blocked-pump": + stand_in.settimeout(RELAY_WAIT) + server, _ = stand_in.accept() + opened.append(server) + stalled = _stalls(server) + pumping = bool(relay.pumps) and relay.pumps[0].is_alive() + assert stalled and pumping, f"[{case}] no pump blocked in sendall(): {stalled}, {pumping}" + if case == "thread-left": + stuck = threading.Thread(target=release.wait, args=(RELAY_WAIT,), daemon=True, + name=label) + stuck.start() + with relay.lock: + relay.pumps.append(stuck) + relay.CLOSE_WAIT = 0.5 + try: + relay.close() + except RuntimeError as error: + raised = error + left, closed = _relay_threads_left(relay), _peer_closed(client, 5.0) + finally: + release.set() + for sock in opened: + sock.close() + try: + relay.close() + except RuntimeError: + pass + if case == "thread-left": + named = raised is not None and label in str(raised) + assert named and left == [label], ( + f"[{case}] close() did not fail on the one pump left alive, and only on it: " + f"{raised!r}, {left}") + else: + assert raised is None and left == [] and closed, ( + f"[{case}] close() left {left} alive (raised {raised!r}), or the client's end open " + f"({closed})") + + +def test_under_a_declaration_a_silent_database_is_capped_and_the_mirror_answers_inside_the_budget( + pg, tmp_path, request): + """AT-F7, real engine: under the declaration, the direct read meets F2's + silent host and is cut by its timer; the mirror path's first `git` call + follows the read's end (rule 3); the cut, `T0 + 3.65 s`, and the start + line, `T0 + 3.75 s`, are each asserted at twice their value (rule 2) and + recorded with their margins; and the hook answers from the mirror in + under 4.5 s, never killed (rule 1). `T0` is the hook's start. + + Lane 3's E1 ruling (#165 6807694145) is this case's reading: under an + unexpired declaration that names this database, a direct read cut at + the declared cap, `T0 + 3.65 s`, ends 69 with `.outage`, so the guard + starts the mirror path by `T0 + 3.75 s`; T507's writer A handles the + cut. It fails until T507 (L5-A3, L5-A5).""" + estate = Estate(tmp_path, [_render(1), _render(2), _render(3)]) + fields = estate.declared(estate.config(), mirror_seq=3) + login = f"t215_{uuid.uuid4().hex[:12]}" + pg.psql(f"CREATE ROLE {login} LOGIN IN ROLE lanes_register_reader;") + request.addfinalizer(lambda: pg.cluster.psql(f"DROP ROLE IF EXISTS {login};", check=False)) + timed = tmp_path / "timedbin" + _script(timed / "psql", TIMING_PSQL) + relay = StartupRelay(f"{pg.host}/.s.PGSQL.{pg.port}") + try: + config = estate.config(url=f"postgresql://{login}@127.0.0.1:{relay.port}/{pg.name}") + estate.reset_logs() + result = estate.guard(config, T215_REAL_PSQL=pg.psql_bin, + PATH=os.pathsep.join([str(estate.bin), str(timed), + os.environ.get("PATH", os.defpath)])) + finally: + relay.close() + assert not result["killed"], "the hook was killed at 5 s, and the prompt passed" + assert result["elapsed"] < BUDGET, f"the hook took {result['elapsed']:.2f} s" + _record("hook end to end", result["elapsed"], BUDGET, "timing rule 1") + # The wrapper writes its log at the first call, so a guard that made no + # direct read leaves none; that is the case's own "no direct read" + # (T215g; line AN11b's U4), never a FileNotFoundError. + log = timed / "psql-timing.log" + timing = [json.loads(line) for line in + log.read_text(encoding="utf-8").splitlines()] if log.exists() else [] + starts = [t for t in timing if "start" in t] + ends = {t["call"]: t["end"] for t in timing if "end" in t} + assert starts, f"the guard made no direct read: {result['out'][-600:]}" + read = starts[0] + assert read["call"] in ends, "the direct read never ended" + cut = ends[read["call"]] - result["t0"] + # The logged end trails the real one by up to `WATCHER_LAG_S`. + assert cut - WATCHER_LAG_S < 2 * CAP_DECLARED, f"the direct read ended {cut:.2f} s after T0" + _record("the direct read's end after T0, its timer included", cut, CAP_DECLARED, + "timing rule 2") + mirror = estate.mirror_calls() + assert mirror, "the guard made no mirror call" + # Writer A runs form C's first `git` only once the cut `psql` is killed + # and reaped; the logged end may trail that by up to `WATCHER_LAG_S`. + assert mirror[0]["t"] >= ends[read["call"]] - WATCHER_LAG_S, ( + "the mirror path started before the read ended") + line = mirror[0]["t"] - result["t0"] + assert line < 2 * START_LINE, f"the mirror path started {line:.2f} s after T0" + _record("the mirror path's first git call after T0", line, START_LINE, "timing rule 2") + _answers_from_the_mirror(estate, result, fields, estate.reference(), estate.tip()) + + +def test_the_declaration_is_read_once_at_the_prefetch(tmp_path): + """AT-F7: the shim holds the direct read on a FIFO; the test removes + `register-outage`, then releases the read to fail; the guard still + answers from the mirror, with the declared line. The shim hands its calls + to the stopped fake, so no engine is needed.""" + from sql_register_helpers import PSQL_SHIM + estate = Estate(tmp_path, [_render(1), _render(2), _render(3)]) + config = estate.config() + fields = estate.declared(config, mirror_seq=3) + reference = estate.reference() + shimbin = tmp_path / "shimbin" + _script(shimbin / "psql", PSQL_SHIM) + fifo = tmp_path / "hold.fifo" + os.mkfifo(fifo) + (shimbin / "psql-shim.json").write_text(json.dumps({ + "psql": str(estate.fakebin / "psql"), + "arms": [{"mode": "hold", "fifo": str(fifo), "match": "SELECT", "call": 1}]}), + encoding="utf-8") + estate.reset_logs() + env = estate.guard_env(config, PATH=os.pathsep.join([str(estate.bin), str(shimbin), + estate.env["PATH"]])) + hook = tmp_path / "hook.json" + hook.write_text(estate.hook_input(), encoding="utf-8") + with open(hook, "rb") as stdin: + proc = subprocess.Popen(["bash", str(tmp_path / "tool" / "lanes-edit.sh"), "guard"], + stdin=stdin, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, cwd=str(estate.wip), env=env, + start_new_session=True) + holder, deadline = None, time.monotonic() + GUARD_TIMEOUT + try: + while holder is None and time.monotonic() < deadline and proc.poll() is None: + try: + holder = os.open(str(fifo), os.O_WRONLY | os.O_NONBLOCK) + except OSError as exc: + if exc.errno != errno.ENXIO: + raise + time.sleep(0.01) + held = holder is not None + if held: + (config.parent / "register-outage").unlink() + os.close(holder) + try: + out, err = proc.communicate(timeout=max(0.1, deadline - time.monotonic())) + killed = False + except subprocess.TimeoutExpired: + os.killpg(proc.pid, signal.SIGKILL) + out, err = proc.communicate() + killed = True + finally: + if proc.poll() is None: + os.killpg(proc.pid, signal.SIGKILL) + proc.wait() + assert held, (f"the guard ended (exit {proc.returncode}) without a direct read for the " + f"shim to hold: {(out + err)[-600:]}") + assert not (config.parent / "register-outage").exists() + result = {"exit": None if killed else proc.returncode, "killed": killed, "out": out + err} + _answers_from_the_mirror(estate, result, fields, reference, estate.tip()) + + +def _stand_in(age: float) -> subprocess.Popen: + """A stand-in for the hook, started `age` seconds before its return: the + client reads `T0` from its pid (SVC-8, "How the client knows `T0`").""" + standin = subprocess.Popen(["sleep", "120"], start_new_session=True, + stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL) + born = time.monotonic() + while time.monotonic() - born < age: + time.sleep(0.01) + return standin + + +@pytest.mark.parametrize("case", ["floor", "clamp", "room"]) +def test_under_a_declaration_a_direct_read_left_under_0_5_s_does_not_start(tmp_path, case): + """AT-F7's floor (SVC-8; V2's NIT 7), on the guard's client, form 2, run + with the pid of a stand-in started earlier, so that it reads an age of + about 3.3 s (`floor`), 3.7 s (`clamp`) and 2.0 s (`room`). Under a + declaration the read's cap is `T0 + 3.65 s`: + - `floor` and `clamp`: less than 0.5 s is left before the cap, or none; + the client starts no direct read and exits 2, too late to verify: the + fake's log holds no read, and the `git` wrapper's no mirror call; + - `room`: the read starts; the fake holds it past any timer, so the + client's timer, at most 1.65 s, ends it, and the mirror answers: + `.outage` says `open`, with the declared line. The read's life, from + its start to the client's end, is asserted at twice 1.65 s (rule 2) + and recorded.""" + age = {"floor": 3.3, "clamp": 3.7, "room": 2.0}[case] + estate = Estate(tmp_path, [_render(1), _render(2), _render(3)]) + config = estate.config() + fields = estate.declared(config, mirror_seq=3) + if case == "room": + estate.answers.write_text(json.dumps([{"sleep": 30, "exit": 2}]), encoding="utf-8") + estate.reset_logs() + standin = _stand_in(age) + try: + proc, end = estate.client(config, standin.pid) + finally: + # Kill it, then a reap bounded at 10 s, as `GuardSession.close()` does: a + # stand-in that a kill does not take fails the case and never hangs the + # run (T215o). + standin.kill() + try: + standin.wait(timeout=10) + except subprocess.TimeoutExpired: + standin.kill() + standin.wait(timeout=10) + starts = estate.psql_starts() + if case in ("floor", "clamp"): + assert proc.returncode == 2, f"{case}: the client exited {proc.returncode}: {proc.stderr}" + assert "lanes-index: too late to verify" in proc.stderr, proc.stderr + assert starts == [], f"{case}: a direct read started: {starts}" + assert estate.mirror_calls() == [], f"{case}: the mirror was read" + return + assert len(starts) == 1, f"room: {len(starts)} direct reads started" + assert proc.returncode == 69, f"room: the client exited {proc.returncode}: {proc.stderr}" + life = end - starts[0]["start"] + assert life < 2 * (CAP_DECLARED - age), f"room: the read lived {life:.2f} s" + _record("room: the direct read's timer", life, CAP_DECLARED - age, "timing rule 2") + outage = Path(str(estate.cache) + ".outage") + assert outage.exists(), "room: no .outage was written" + text = outage.read_text(encoding="utf-8") + assert "verdict=open\n" in text and f"label={_label(fields)}\n" in text, text + + +#: AT-F7's control's age: the stand-in's, when the client starts. The client +#: reads the age only after its own start, so the age it reads is this plus +#: that start, above `T0` + 3.15 s, past which the declared floor refuses a +#: read, wherever the start takes 0.15 s or more; and it leaves 0.75 s for +#: the start and the stopped database's read before `T0` + 3.75 s. +SAME_AGE = 3.0 + + +def test_without_a_declaration_the_same_age_still_starts_the_direct_read(tmp_path): + """AT-F7's control: with nothing declared, the cap is `T0 + 3.75 s` and + no floor applies, so at an age the declared floor refuses, the direct + read still starts; the stopped database fails it, and the client exits + 69, writing no `.outage` and never too late. + + THE AGE (lane 5, #165 6808764772). The client reads the stand-in's age + after its own start, and its direct read must also end before the cap, + or the client's timer cuts it and the client exits 2, too late. At + 3.3 s, as the test plan has it (TP:6412), that left 0.45 s, and the + case failed once in four of lane 5's runs, with the client's start at + 0.2 to 0.5 s. Under T507A in lane 2's probe (W4a13, 2026-11-12, a load + of about 24 on 32 cores), the client's launch to its first `psql` call + took 0.46 to 0.57 s, and to its end 0.53 to 0.63 s; at stand-in ages + 2.9, 3.0 and 3.1 the read started and ended 69, and at 3.16 and 3.2 it + was cut, 2. So `SAME_AGE` is 3.0. The age the client reads, `SAME_AGE` + plus its own start, stays above the declared floor's `T0` + 3.15 s + (`[floor]` is at 3.3 s). The client's start to its direct read is + recorded beside the 0.75 s it has.""" + estate = Estate(tmp_path, [_render(1), _render(2), _render(3)]) + config = estate.config() + standin = _stand_in(SAME_AGE) + launched = time.time() + try: + proc, _ = estate.client(config, standin.pid) + finally: + # Bounded, as the floor case's reap is (T215o). + standin.kill() + try: + standin.wait(timeout=10) + except subprocess.TimeoutExpired: + standin.kill() + standin.wait(timeout=10) + starts = estate.psql_starts() + if starts: + _record("the client's start, from its launch to its direct read", + starts[0]["start"] - launched, CAP - SAME_AGE, + "the control's room, T0 + 3.75 s less SAME_AGE") + assert len(starts) == 1, f"the direct read did not start: {proc.stderr}" + assert "too late to verify" not in proc.stderr + assert proc.returncode == 69, f"the client exited {proc.returncode}: {proc.stderr}" + assert not Path(str(estate.cache) + ".outage").exists() + + +# =================================================================== AT-F11 + +def test_the_guard_refuses_a_mirror_older_than_the_declared_seq(tmp_path): + """AT-F11: declared at `m`, with the guard's checkout last fetched at + `m - 1`, the guard exits 2 with lane 5's text and does not answer from + the mirror; fetched at `m`, it answers from the mirror.""" + m = 4 + estate = Estate(tmp_path, [_render(k) for k in range(1, m)]) + estate.grow([_render(m)]) + config = estate.config() + fields = estate.declared(config, mirror_seq=m) + estate.reset_logs() + result = estate.guard(config) + assert not result["killed"], "the hook was killed at 5 s" + assert result["exit"] == 2, f"at m - 1 the guard exited {result['exit']}" + assert _behind(m - 1, m) in result["out"], result["out"][-600:] + assert "read: mirror" not in result["out"] + estate.fetch() + result = estate.guard(config) + _answers_from_the_mirror(estate, result, fields, estate.reference(), estate.tip()) + + +@pytest.mark.parametrize("case", ["depth-200", "depth-250"]) +def test_the_guard_refuses_2_when_no_commit_within_the_bound_carries_register_seq( + tmp_path, case): + """AT-F11's bounded lookup: `origin/main`'s newest render commit at depth + 200, the first outside the bound, under 200 handoff commits, and at + depth 250: the guard exits 2, and never finds the deeper trailer. The + `git` wrapper's log shows one `git log` call, `--first-parent` with + `-n 200` and no `--grep`.""" + depth = int(case.split("-")[1]) + m = 5 + estate = Estate(tmp_path, [_render(k) for k in range(1, m + 1)] + + [_handoff(i) for i in range(depth)]) + config = estate.config() + estate.declared(config, mirror_seq=m) + estate.reset_logs() + result = estate.guard(config) + assert not result["killed"], "the hook was killed at 5 s" + logs = estate.log_calls() + assert len(logs) == 1, f"{case}: {len(logs)} git log calls: {[c['args'] for c in logs]}" + assert _bounded(logs[0]["args"]), f"{case}: not form C: {logs[0]['args']}" + assert result["exit"] == 2, f"{case}: the guard exited {result['exit']}" + assert "read: mirror" not in result["out"], f"{case}: the guard found the deeper trailer" + + +def test_the_register_seq_lookup_finds_the_trailer_at_depths_0_and_199(tmp_path): + """AT-F11: the render commit at depth 0, and at depth 199 under 199 + handoff commits: the guard's one bounded `git log` finds it, and the + guard answers from the mirror.""" + m = 5 + for depth in (0, 199): + estate = Estate(tmp_path / f"depth-{depth}", [_render(k) for k in range(1, m + 1)] + + [_handoff(i) for i in range(depth)]) + config = estate.config() + fields = estate.declared(config, mirror_seq=m) + estate.reset_logs() + result = estate.guard(config) + logs = estate.log_calls() + assert len(logs) == 1 and _bounded(logs[0]["args"]), ( + f"depth {depth}: {[c['args'] for c in logs]}") + _answers_from_the_mirror(estate, result, fields, estate.reference(), estate.tip()) + + +def test_outage_declare_takes_mirror_seq_from_a_fetch_or_the_flag_and_refuses_with_neither( + tmp_path): + """AT-F11 (D20, SVC-12, ops section 2.5), lane 1's T121 on Brett's word, + the database not answering from this host: + - with no `--mirror-seq`, `mirror-seq=` is the newest `Register-Seq` on + `origin/main` read after a fetch: origin is at 3, and the checkout was + last fetched at 2; + - with the fetch failing, `--mirror-seq 7` writes `mirror-seq=7`; + - with the fetch failing and no `--mirror-seq`, it exits 2 and writes no + file. + The checkout fetched is the workspace's, W, as `lanes-edit.sh + workspace-root` names it (lane 1's reading 1, #165 comment 6754714549), + so the fetch is made to fail in W (T215f).""" + estate = Estate(tmp_path, [_render(1), _render(2)]) + estate.grow([_render(3)]) + fetched = estate.config(name="conf-fetch") + proc = estate.declare(fetched) + path = fetched.parent / "register-outage" + assert proc.returncode == 0, f"from a fetch: exit {proc.returncode}: {proc.stderr}" + text = path.read_text(encoding="utf-8") + assert "mirror-seq=3\n" in text, f"from a fetch: {text}" + assert "kind=word\n" in text and f"database={LABEL}\n" in text and f"until={UNTIL}\n" in text + assert estate.psql_log.exists(), "the probe was not sent" + subprocess.run([estate.env["T215_REAL_GIT"], "-C", str(estate.w), "remote", "set-url", + "origin", str(tmp_path / "no-such-origin.git")], check=True, + env=estate.env) + flagged = estate.config(name="conf-flag") + proc = estate.declare(flagged, mirror_seq=7) + assert proc.returncode == 0, f"by the flag: exit {proc.returncode}: {proc.stderr}" + assert "mirror-seq=7\n" in (flagged.parent / "register-outage").read_text(encoding="utf-8") + neither = estate.config(name="conf-neither") + proc = estate.declare(neither) + assert proc.returncode == 2, f"with neither: exit {proc.returncode}: {proc.stderr}" + assert not (neither.parent / "register-outage").exists(), "with neither: a file was written" + + +def test_the_guard_refuses_a_ref_behind_a_rollbacks_head(pg, tmp_path, request): + """AT-F11, a ref behind a rollback's head (A9: phase N, on lane 3's T304, + against this test's own database). The database is brought to primary + and rolled back by the real commands, `import --at <C>`, `cutover + --import <C>` and `rollback`, with one write on primary between the + cutover and the rollback, so its switch is at `files` with a `rollback` + entry at `set_seq`, and `rollback` writes its declaration, marked as from + a rollback, with `mirror-seq=<k>`, `k` being `set_seq - 1`. With the + guard's read finding the switch at `files`: its checkout last fetched at + `k - 1`, one behind the rollback's head, the guard exits 2 with lane 5's + text for seqs `k - 1` and `k`, and does not answer from the mirror; + fetched at `k`, it answers from the mirror, `read: mirror`. + + THE WRITE MAKES `k` 2 (lane 1, #165 6869810000): the import's entry is + at seq 0, the cutover's at 1, the write's at 2 and the rollback's at 3. + Without it `k` is 1, and "a ref at `k - 1`" is a ref at seq 0, which no + render commit here carries: the guard's history was then empty, its + checkout held no `lanes/LANES.md`, and the name guard refused it before + any mirror read (rounds 6b to 6j). The write is `log NOTED`, R3b's + smoke-test write, from the lane's own register checkout `<c>`, made after + the cutover's push (T219g; T415's `pw_checkout`). The guard's checkout is + built on a fetched register commit at `k - 1`, as the rollback cases' + `found-files` builds its own at `k`. + + WHETHER THE WRITE'S FORKED RENDER REACHED ORIGIN (T416) by the end of + the 60 s wait is recorded beside the result, never asserted: the line + `[T215 forked-render]`, which is also the case's junit property + `T215 forked-render`, as the order module's `record` writes its figures + (T243l), and the note on `k`'s assertion. Where origin did not carry the + write's seq, the rollback renders `k` itself and the case rests on that; + the record says which way it went (T215l).""" + estate = Estate(tmp_path, [_render(1)]) + writer = f"t215_{uuid.uuid4().hex[:12]}" + reader = f"t215_{uuid.uuid4().hex[:12]}" + pg.psql(f"CREATE ROLE {writer} LOGIN IN ROLE lanes_register_writer;\n" + f"CREATE ROLE {reader} LOGIN IN ROLE lanes_register_reader;") + request.addfinalizer(lambda: pg.cluster.psql(f"DROP ROLE IF EXISTS {writer}, {reader};", + check=False)) + config = _private(tmp_path / "conf-pg" / "lanes-index.conf", "\n".join([ + "mode=primary", f"register_url={pg.url(writer)}", f"register_passfile={estate.passfile}", + f"reader_url={pg.url(reader)}", f"reader_passfile={estate.passfile}", + f"register_label={LABEL}", f"register_schema={SCHEMA}", ""])) + env = dict(estate.env, LANES_INDEX_CONFIG=str(config), LANES_LANE=WINDOW, + PATH=os.pathsep.join([str(estate.bin), str(Path(pg.psql_bin).parent), + os.environ.get("PATH", os.defpath)])) + c = estate.tip() + git = estate.env["T215_REAL_GIT"] + forked = "no write was made" + for argv in (["import", "--at", c], ["cutover", "--import", c], "write", ["rollback"]): + if argv == "write": + # ONE WRITE ON PRIMARY, from the lane's `<c>`, made after the + # cutover's push. Its forked render pushes to origin (T416); the + # rollback starts once origin carries the write's seq, or after + # 60 s, since the rollback renders `k` itself where it does not. + estate.lane_checkout() + wrote = subprocess.run( + ["bash", str(estate.root / "tool" / "lanes-edit.sh"), "log", "NOTED", + f"lane:{WINDOW}", "T215: one write on primary before the rollback"], + capture_output=True, text=True, env=dict(env, LANES_SESSION=estate.session), + cwd=str(estate.wip), timeout=300, stdin=subprocess.DEVNULL) + assert wrote.returncode == 0, ( + f"`log NOTED` on primary exited {wrote.returncode} (lane 4's T415): " + f"{(wrote.stdout + wrote.stderr)[-600:]}") + head = pg.psql(f"SELECT seq FROM {SCHEMA}.register_head WHERE id = 1;").stdout.strip() + began = time.monotonic() + while True: + carried = subprocess.run( + [git, "--git-dir", str(estate.origin), "log", "-1", + "--format=%(trailers:key=Register-Seq,valueonly)", "main"], + capture_output=True, text=True, env=estate.env).stdout.split() + if head in carried or time.monotonic() - began >= 60: + break + time.sleep(0.2) + # WHETHER THE FORK'S PUSH REACHED ORIGIN, recorded and never + # asserted (T215l): where it did not, the case rests on the + # rollback rendering `k` itself, and the record says so. + waited = time.monotonic() - began + forked = (f"origin's main {'carried' if head in carried else 'did not carry'} the " + f"write's seq {head or '(none read)'} after {waited:.1f} s of the 60 s " + f"wait (its tip's Register-Seq: {' '.join(carried) or 'none'})") + print(f"[T215 forked-render] {forked}") + request.node.user_properties.append(("T215 forked-render", forked)) + continue + proc = subprocess.run([sys.executable, str(estate.copy), *argv], capture_output=True, + text=True, env=env, cwd=str(estate.wip), timeout=300, + stdin=subprocess.DEVNULL) + assert proc.returncode == 0, f"`{' '.join(argv)}` exited {proc.returncode}: {proc.stderr}" + path = config.parent / "register-outage" + assert path.exists(), "the rollback wrote no declaration" + fields = dict(line.split("=", 1) for line in path.read_text(encoding="utf-8").splitlines()) + assert fields.get("kind") == "rollback" and "until" not in fields, fields + k = int(fields["mirror-seq"]) + assert k >= 2, ( + f"the rollback's head k is {k}, not 2 or more, though a write on primary came between " + f"the cutover and the rollback: a ref one behind it, at {k - 1}, would carry no " + f"Register-Seq here; the write's forked render: {forked}") + # The guard's checkout: built on a fetched register commit at k - 1, the + # ref one behind the rollback's head; origin then gains k, unfetched. + guard_estate = Estate(tmp_path / "guard", [_render(1)]) + guard_estate.grow([_render(s) for s in range(2, k)]) + guard_estate.fetch() + behind = subprocess.run([git, "-C", str(guard_estate.wip), "log", "-1", + "--format=%(trailers:key=Register-Seq,valueonly)", + "refs/remotes/origin/main"], capture_output=True, text=True, + env=guard_estate.env).stdout.split() + assert behind == [str(k - 1)], ( + f"the guard's checkout, as last fetched, carries Register-Seq {behind}, not {k - 1}") + guard_estate.grow([_render(k)]) + estate_config = guard_estate.config(url=pg.url(reader)) + shutil.copy2(path, estate_config.parent / "register-outage") + real = os.pathsep.join([str(guard_estate.bin), str(Path(pg.psql_bin).parent), + os.environ.get("PATH", os.defpath)]) + result = guard_estate.guard(estate_config, PATH=real) + assert result["exit"] == 2, f"at k - 1 the guard exited {result['exit']}" + assert _behind(k - 1, k) in result["out"], result["out"][-600:] + assert "read: mirror" not in result["out"] + guard_estate.fetch() + result = guard_estate.guard(estate_config, PATH=real) + assert not result["killed"] + assert f"read: mirror at {guard_estate.tip()[:12]}" in result["out"], result["out"][-600:] + + +def test_the_register_seq_lookup_is_timed_bounded_beside_the_unbounded_and_grep_forms(tmp_path): + """M11 (section 5.1), recorded and never asserted: on a checkout of + 30,000 first-parent commits made by `git fast-import`, with a + commit-graph, the bounded lookup (form C, T121's own paged `log`) is timed beside the unbounded + form and the `--grep` form, 30 warm runs and the first; the three find + the same `Register-Seq`. The build time is recorded beside the figures. + Then the bounded form is shown to be the one the guard runs.""" + total, newest_depth, m = 30000, 37, 9000 + started = time.monotonic() + messages = [] + seq = 0 + for i in range(total): + depth = total - 1 - i + if depth == newest_depth or (depth > newest_depth and depth % 1000 == 0): + seq = m if depth == newest_depth else seq + 1 + messages.append(_render(seq)) + else: + messages.append(_handoff(i)) + estate = Estate(tmp_path, messages) + git = estate.env["T215_REAL_GIT"] + subprocess.run([git, "-C", str(estate.wip), "commit-graph", "write", "--reachable"], + check=True, env=estate.env, capture_output=True) + built = time.monotonic() - started + print(f"T215 M11: the checkout of {total} first-parent commits, with its commit-graph, " + f"built in {built:.2f} s") + fmt = "--format=%H%x00%(trailers:key=Register-Seq,valueonly)" + tip = estate.tip() + + def log(*args: str) -> str: + return subprocess.run([git, "-C", str(estate.wip), "log", *args], check=True, + env=estate.env, capture_output=True, text=True).stdout + + def paged() -> str: + """T121's own lookup: `log --first-parent -n 200 --skip <s> <fmt> <tip + sha> --`, given the tip's sha and not the ref, a page at a time, + taking the first non-empty `Register-Seq` value. Returns the page that + holds it.""" + skip = 0 + while True: + out = log("--first-parent", "-n", str(PAGE), "--skip", str(skip), fmt, tip, "--") + if first_seq(out) or "\x00" not in out: + return out + skip += PAGE + + # T121 never uses `--grep` (`lanes-index:2714`, lane 1, #165 comment + # 6755305741): the unbounded and `--grep` forms are comparisons only. + forms = { + "bounded": paged, + "unbounded": lambda: log("--first-parent", fmt, "origin/main", "--"), + "grep": lambda: log("--first-parent", "-n", "1", "--grep=^Register-Seq: ", fmt, + "origin/main", "--"), + } + + def first_seq(out: str) -> str: + commit = "" + for line in out.split("\n"): + if "\x00" in line: + commit, _, line = line.partition("\x00") + if commit and line.strip(): + return line.strip() + return "" + + for name, form in forms.items(): + times, found = [], set() + for _ in range(31): + t = time.monotonic() + out = form() + times.append(time.monotonic() - t) + found.add(first_seq(out)) + assert found == {str(m)}, f"M11 {name}: found {found}, not {m}" + warm = sorted(times[1:]) + print(f"T215 M11 {name}: first {times[0] * 1000:.1f} ms; 30 warm: median " + f"{statistics.median(warm) * 1000:.1f} ms, p95 {warm[28] * 1000:.1f} ms") + config = estate.config() + estate.declared(config, mirror_seq=m) + estate.reset_logs() + estate.guard(config) + logs = estate.log_calls() + assert len(logs) == 1 and _bounded(logs[0]["args"]), ( + f"the guard's lookup is not the bounded form: {[c['args'] for c in logs]}") + + +# ===================================================================== T219 +# +# Test P3 and test D20's phase-N cases (L2-N5; AT-P3; AT-D20). The FP cases +# run on the stopped fake, or on the fake taught the probe's one answer, +# `<mode>|<set_seq>|<kind of the entry at set_seq>` (D9's `outage` row, as +# T121 reads it). The cases whose probe or guard reads a database whose +# switch is at `files` after a `rollback` entry run on `pg`, brought there by +# the real commands, `import --at <C>`, `cutover --import <C>` and `rollback` +# (T121's usage; lane 3's T304 for `rollback`), and wait for T304. + +DOT = chr(0xB7) +REGISTER_HEADER = ["# LANES.md", "", + "| lane | session id | workstation / env / user | started (UTC) | objects " + "owned | handoff path | state |", + "|---|---|---|---|---|---|---|"] +#: A password in the configuration's password file, which no output carries. +SECRET = "t215-secret-password" +#: A password-file form, `<host>:<port>:<database>:<user>:<password>` (`*` for +#: any of the first four, `\:` and `\\` escaped), wherever it is: in a run of +#: text with no blank, all that follows the fourth colon is taken as the +#: password, so a field more, before or after it, hides no password. +_PASSWORD_FILE_FORM = re.compile(r"((?:(?:[^:\s\\]|\\.)*:){4})(?:[^\s\\]|\\.)+") +#: The probe's answer where the database answers with the switch at primary. +PRIMARY = [{"match": "register_switch", "stdout": "primary|5|cutover\n", "exit": 0}] + + +def _redacted(text: str) -> str: + """`text` as a failure may quote it (T219k): SECRET, and the last field of + each password-file form, read `<password>`. The two password-absence + cases take each oracle on their output as a bool, from the output itself, + and quote the output only redacted, so that neither a message of theirs + nor pytest's rewrite of an operand prints a password (Codex's SHOULD 7 on + P09 at `21dd3642`; 6931509747).""" + return _PASSWORD_FILE_FORM.sub(r"\1<password>", (text or "").replace(SECRET, "<password>")) + + +def _register(session_cell: str) -> str: + """A register whose one row binds `WINDOW` to `session_cell`, in + `test_lanes_index.py`'s row form.""" + row = (f"| `{WINDOW}` | harness `{session_cell}` | Eagle / test / brett | 2026-10-01T00:00Z " + f"| none | handoffs/{WINDOW}.md | LIVE {DOT} 2026-10-01T02:00:00Z {DOT} working |") + return "\n".join(REGISTER_HEADER + [row, ""]) + + +def _index(estate: Estate, config: Path, *argv, env: dict | None = None, + timeout: float = 120) -> tuple: + """`lanes-index <argv>` from the flipped copy, on the fake's `PATH` + unless `env` is given; returns (the process, its elapsed seconds).""" + if env is None: + env = dict(estate.env, LANES_INDEX_CONFIG=str(config), LANES_LANE=WINDOW) + start = time.monotonic() + proc = subprocess.run([sys.executable, str(estate.copy), *argv], capture_output=True, + text=True, env=env, cwd=str(estate.wip), timeout=timeout, + stdin=subprocess.DEVNULL) + return proc, time.monotonic() - start + + +def _fields(path: Path) -> dict: + return dict(line.split("=", 1) for line in + path.read_text(encoding="utf-8").splitlines() if "=" in line) + + +def _names_the_store(out: str) -> bool: + """`status`'s store, named without credentials: its label or its + database. The guard's refusal is held to the database as `register_url=` + gives it (lane 3, #165 6809045090), in its own case.""" + return LABEL in out or "register_db" in out + + +def test_the_guards_outage_refusal_names_the_store_the_cause_and_both_ways_out(tmp_path): + """AT-P3: with `mode=primary` and the database stopped, the guard tries + its direct read and exits 2; its refusal names the store, without + credentials, and the cause, and carries both ways out, `lanes-index + status` and `lanes-index rollback` from a shell or a `CLAUDE_NO_LANE=1` + session. + + The guard runs in the lane's window with a live session record (T203c's + `guard_session`), as this module's other guard cases do. The guard keeps + its order: with no window, or no session record, it refuses 2 before + any read, and T507's prefetch comes after the session-record check (B8 + item 40; lane 5, #165 6755266457). So only a lane session reaches the + prefetch and the direct read this case asserts (lane 3's T507 ruling + (1), #165 6783977598). + + THE NAME (lane 3's ruling on lane 5's seam question, #165 6809045090): + under `--for guard`, the cause line names the database as + `register_url=` gives it, without credentials, not `register_label=`. + Lane 3 set this oracle exactly (#165 6812459759): + - the database name is in the added name, the text after "the register + could not be read (" and before ")" (lane 5's form, `database <db> at + <host>:<port>`), so the label alone does not do; + - no password appears anywhere on stderr; + - no user, `t215_login`, appears in the added name; + - there is no assert on `psql`'s own cause, which is relayed whole. + So the cause is asserted in `lanes-index`'s own words, "the register + could not be read", and no longer by `psql`'s "Connection refused". It + fails until lane 5's T507A-fix1 (`373d481`, A6), which adds that name.""" + estate = Estate(tmp_path, [_render(1)]) + estate.passfile.write_text(f"127.0.0.1:55432:register_db:t215_login:{SECRET}\n", + encoding="utf-8") + config = estate.config() + result = estate.guard(config) + # NO PASSWORD IN A FAILURE (T219k): each oracle on the output is a bool + # taken from the raw text, and each message quotes it `_redacted`; no + # assert has the output as an operand, which pytest's rewrite prints. + raw, leaked = result["out"], SECRET in result["err"] + out, err = _redacted(raw), _redacted(result["err"]) + assert not result["killed"], "the hook was killed at 5 s, and the prompt passed" + assert estate.psql_starts(), ( + f"the guard made no direct read: the fake psql has no call: {out[-600:]}") + assert result["exit"] == 2, f"the guard exited {result['exit']}" + added = re.search(r"the register could not be read \(([^)]*)\)", raw) + assert added, f"the refusal adds no name after `the register could not be read`: {out[-600:]}" + name = added.group(1) + names_db, names_user = "register_db" in name, "t215_login" in name + assert names_db, ( + f"the added name {_redacted(name)!r} does not name the database as register_url= gives it") + assert not names_user, f"the added name {_redacted(name)!r} carries the URL's user" + assert not leaked, f"stderr carries the password: {err[-600:]}" + for words in ("lanes-index status", "lanes-index rollback", "CLAUDE_NO_LANE=1"): + carried = words in raw + assert carried, f"the refusal does not carry {words!r}: {out[-600:]}" + + +def test_claude_no_lane_lets_a_session_through_before_any_input(tmp_path): + """AT-P3: with `CLAUDE_NO_LANE=1` the hook exits 0 at once, before any + input is read: its stdin is a pipe whose writer never writes nor closes, + so a read would block past the 5 s kill timer.""" + estate = Estate(tmp_path, [_render(1)]) + config = estate.config() + read_end, write_end = os.pipe() + try: + proc = subprocess.Popen(["bash", str(tmp_path / "tool" / "lanes-edit.sh"), "guard"], + stdin=read_end, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, cwd=str(estate.wip), start_new_session=True, + env=estate.guard_env(config, CLAUDE_NO_LANE="1", TMUX=None, + TMUX_PANE=None)) + os.close(read_end) + read_end = -1 + try: + out, err = proc.communicate(timeout=GUARD_TIMEOUT) + except subprocess.TimeoutExpired: + os.killpg(proc.pid, signal.SIGKILL) + proc.communicate() + raise AssertionError("the hook read its stdin and blocked past 5 s") + finally: + for fd in (read_end, write_end): + if fd >= 0: + os.close(fd) + assert proc.returncode == 0, f"the hook exited {proc.returncode}: {(out + err)[-400:]}" + assert estate.psql_starts() == [], "the skipped hook read the database" + + +#: AT-D9's rows for the two ways out: `status`, 8 s, and `rollback`, 15 s for +#: each call (TP's AT-D9 table). +WAY_OUT_BOUND = {"status": 8, "rollback": 15} + + +@pytest.mark.parametrize("verb", ["status", "rollback"]) +def test_status_and_rollback_run_with_no_lane_session_and_no_guard(tmp_path, verb): + """AT-P3: `status` and `rollback` run with no lane session (no window and + no session record) and no guard; with the database stopped each answers + inside twice its bound, AT-D9's row (timing rule 2), with its own exit, + 69, and no credential in its output. + + - `[status]` (T219) runs with no lane either, and names the unreachable + store (AT-P3's oracle). + - `[rollback]` (T279) runs as the operator lane from a shell: B15 + tasks:1033's T304 bullet, "It runs with `LANES_LANE=<operator lane>`, + from a shell or a `CLAUDE_NO_LANE=1` session", so `LANES_LANE` is the + lane's name and there is still no window and no session record. It is + refused with the database down, rather than blocked by a guard + (AT-P3's oracle; Q4(b)(iii)): T304's "With the database unreachable, + it exits 69 and changes neither the switch nor the marker". Its bound + is AT-D9's `rollback` row, 15 s for each call. AT-P3's oracle names + the store for `status` alone, so `[rollback]` asserts no name. The + estate's `lanes-index` is the flipped copy, so the scratch-schema rule + of T304, which holds only while Q6(c)'s constant is unset, does not + apply. It needs T304, which line R holds since its merge14.""" + estate = Estate(tmp_path, [_render(1)]) + estate.passfile.write_text(f"127.0.0.1:55432:register_db:t215_login:{SECRET}\n", + encoding="utf-8") + config = estate.config() + lane = WINDOW if verb == "rollback" else None + env = estate.guard_env(config, TMUX=None, TMUX_PANE=None, LANES_LANE=lane) + proc, elapsed = _index(estate, config, verb, env=env) + # NO PASSWORD IN A FAILURE (T219k), as in the guard's refusal above: no + # operand is the output, or `proc`, whose repr pytest's rewrite would print + # with its stdout and stderr. + raw = proc.stdout + proc.stderr + code, leaked, out = proc.returncode, SECRET in raw, _redacted(raw) + bound = WAY_OUT_BOUND[verb] + assert elapsed < 2 * bound, f"{verb} took {elapsed:.2f} s" + _record(f"{verb} with the database stopped", elapsed, bound, "timing rule 2") + assert code == 69, f"{verb} exited {code}: {out[-600:]}" + if verb == "status": + named = _names_the_store(raw) + assert named, f"{verb} names no store: {out[-600:]}" + assert not leaked, f"{verb}'s output carries the password: {out[-600:]}" + + +class _Leaky: + """T219k's stand-in for `Estate` in the two password-absence cases: no + guard runs, and `guard()` and `psql_starts()` answer as the case gives.""" + + def __init__(self, root: Path, answer: dict, started: bool = True): + self.passfile = root / "pgpass" + self.answer, self.started = answer, started + + def config(self) -> Path: + return self.passfile.parent / "lanes-index.conf" + + def guard(self, config: Path) -> dict: + return dict(self.answer) + + def psql_starts(self) -> list: + return [{"start": 0.0}] if self.started else [] + + def guard_env(self, config: Path, **extra) -> dict: + return {} + + +def test_a_password_absence_case_that_fails_prints_no_password(tmp_path, monkeypatch): + """T219k (Codex's SHOULD 7 on P09 at `21dd3642`; 6931509747), with no + guard, no `lanes-index` and no database: the guard's refusal case and + both ids of the way-out case run on stand-ins for `Estate` and `_index` + whose output carries SECRET, bare and in its password-file line, and + another password, in a password-file line of its own. Each oracle of the + two cases is made to fail in turn; each failure is that oracle's own, and + its text, the message with pytest's rewrite of the operands, holds + neither password. A healthy output passes both cases. Before T219k the + messages quoted the raw output, and `assert SECRET not in out`, rewritten, + printed SECRET and the output. Each check here is a bool, so no failure of + this case prints a password either.""" + module = sys.modules[__name__] + other = uuid.uuid4().hex + lines = (f"127.0.0.1:55432:other_db:t215_login:{SECRET}\n" + f"*:*:other_db:lanes_w_t219:{other}\n" + f"psql: the password {SECRET} was refused\n") + refusal = "lanes-index: the register could not be read (database register_db at 127.0.0.1:55432)\n" + ways = "run lanes-index status, or lanes-index rollback from a shell or a CLAUDE_NO_LANE=1 session\n" + + def guard(out: str, err: str, started: bool = True, code: int = 2): + def run(): + answer = {"exit": code, "killed": False, "out": out + err, "err": err, + "t0": 0.0, "elapsed": 0.1} + monkeypatch.setattr(module, "Estate", lambda root, messages: _Leaky(root, answer, started)) + test_the_guards_outage_refusal_names_the_store_the_cause_and_both_ways_out(tmp_path) + return run + + def way_out(verb: str, out: str, err: str, code: int = 69): + def run(): + proc = subprocess.CompletedProcess(["lanes-index", verb], code, out, err) + monkeypatch.setattr(module, "Estate", lambda root, messages: _Leaky(root, {})) + monkeypatch.setattr(module, "_index", lambda *argv, **options: (proc, 0.1)) + test_status_and_rollback_run_with_no_lane_session_and_no_guard(tmp_path, verb) + return run + + failing = [ + ("no-read", guard(lines, refusal + ways, started=False), "the fake psql has no call"), + ("exit", guard(lines, refusal + ways, code=0), "the guard exited 0"), + ("no-name", guard(lines, ways), "adds no name"), + ("no-database", guard(lines, f"the register could not be read (login {SECRET})\n" + ways), + "does not name the database"), + ("user", guard(lines, f"the register could not be read (register_db t215_login:{SECRET})\n" + + ways), "carries the URL's user"), + ("stderr", guard("", refusal + ways + lines), "stderr carries the password"), + ("way-out", guard(lines, refusal + "run lanes-index status\n"), + "does not carry 'lanes-index rollback'"), + ("status-exit", way_out("status", lines, refusal, code=1), "status exited 1"), + ("status-no-store", way_out("status", lines, "lanes-index: the store is down\n"), + "status names no store"), + ("status-leak", way_out("status", refusal, lines), "status's output carries the password"), + ("rollback-exit", way_out("rollback", lines, refusal, code=0), "rollback exited 0"), + ("rollback-leak", way_out("rollback", "", lines), "rollback's output carries the password"), + ] + for case, run, want in failing: + with pytest.raises(AssertionError) as failed: + run() + said = str(failed.value) + kept, own = SECRET in said or other in said, want in said + assert not kept, f"[{case}] the failure's text holds a password" + assert own, f"[{case}] the failure is not the oracle's own, {want!r}: {said[-300:]}" + for run in (guard("", refusal + ways), way_out("status", refusal, ""), way_out("rollback", "", "")): + run() + + +def test_outage_declare_writes_its_fields_and_clear_removes_it(tmp_path): + """AT-D20: on Brett's word, with the database not answering from this + host, `outage declare --until <UTC> --why <words> --mirror-seq <m>` + sends its probe and writes `register-outage` beside `lanes-index.conf`, + 0600, in config.md section 6.3's form and order (T121): `format=1`, + `kind=word`, `database=` the label, `utc=` now, `host=` the + workstation, `until=`, `mirror-seq=` and `why=` verbatim. `last-head=` + follows only where `status` recorded a head, which none has here. + `outage clear` removes it, and a second clear exits 0, none recorded.""" + estate = Estate(tmp_path, [_render(1), _render(2)]) + config = estate.config() + before = time.time() + proc = estate.declare(config, mirror_seq=2) + after = time.time() + path = config.parent / "register-outage" + assert proc.returncode == 0, f"outage declare exited {proc.returncode}: {proc.stderr}" + assert len(estate.psql_starts()) == 1, "the probe was not sent once" + assert path.stat().st_mode & 0o777 == 0o600 + lines = path.read_text(encoding="utf-8").splitlines() + keys = [line.split("=", 1)[0] for line in lines] + assert keys == ["format", "kind", "database", "utc", "host", "until", "mirror-seq", "why"], keys + fields = _fields(path) + assert (fields["format"], fields["kind"], fields["database"], fields["host"], + fields["until"], fields["mirror-seq"], fields["why"]) == \ + ("1", "word", LABEL, "Eagle", UNTIL, "2", WHY), fields + stamp = calendar.timegm(time.strptime(fields["utc"], "%Y-%m-%dT%H:%M:%SZ")) + assert before - 2 <= stamp <= after + 2, f"utc={fields['utc']} is not the declaration's time" + proc, _ = _index(estate, config, "outage", "clear") + assert proc.returncode == 0 and not path.exists(), f"clear: {proc.returncode}: {proc.stderr}" + proc, _ = _index(estate, config, "outage", "clear") + assert proc.returncode == 0, f"a second clear exited {proc.returncode}: {proc.stderr}" + assert "no declared outage" in proc.stdout + proc.stderr + + +def test_outage_declare_refuses_while_the_database_answers_or_without_until(tmp_path): + """AT-D20: with the database answering from this host and the switch at + `primary`, Brett's word is refused, 2, and no file is written; with no + `--until`, 2 and no file. Lane 1's usage besides (#165 comment + 6754714549): `--until` beside `--rollback` is 64, and no file.""" + estate = Estate(tmp_path, [_render(1), _render(2)]) + config = estate.config() + path = config.parent / "register-outage" + estate.answers.write_text(json.dumps(PRIMARY), encoding="utf-8") + proc = estate.declare(config, mirror_seq=2) + assert proc.returncode == 2 and not path.exists(), f"answering: {proc.returncode}: {proc.stderr}" + estate.answers.write_text(json.dumps(STOPPED), encoding="utf-8") + proc, _ = _index(estate, config, "outage", "declare", "--why", WHY, "--mirror-seq", "2") + assert proc.returncode == 2 and not path.exists(), f"no --until: {proc.returncode}: {proc.stderr}" + proc, _ = _index(estate, config, "outage", "declare", "--rollback", "--mirror-seq", "2", + "--until", UNTIL) + assert proc.returncode == 64 and not path.exists(), f"--until beside --rollback: {proc.returncode}" + + +@pytest.mark.parametrize("case", ["ok", "refuse"]) +def test_a_declared_outage_lets_the_guard_answer_from_the_mirror(tmp_path, case): + """AT-D20: with a valid declaration and the database stopped, the guard + answers from the mirror, whose register binds this session's lane + (`ok`, exit 0) or holds it for another session (`refuse`, exit 2), + printing the declared line in place of the cause.""" + other = str(uuid.uuid4()) + estate = Estate(tmp_path, [_render(1), _render(2), _render(3)], + register=_register("{session}" if case == "ok" else other)) + config = estate.config() + fields = estate.declared(config, mirror_seq=3) + estate.reset_logs() + result = estate.guard(config) + assert not result["killed"], "the hook was killed at 5 s" + assert estate.psql_starts(), "the guard made no direct read: the fake psql has no call" + assert f"read: mirror at {estate.tip()[:12]}" in result["out"], result["out"][-600:] + assert _label(fields) in result["out"], result["out"][-600:] + assert result["exit"] == (0 if case == "ok" else 2), f"{case}: exit {result['exit']}" + + +@pytest.mark.parametrize("case", ["expired", "other_database"]) +def test_an_expired_or_foreign_declaration_changes_nothing(tmp_path, case): + """AT-D20: a declaration past its `until=` (`expired`), or naming + another database (`other_database`), opens nothing: the guard tries its + direct read and exits 2 with the ordinary outage refusal, never reading + the mirror nor printing a declared line. Expiry is a UTC already past, + never a wait.""" + estate = Estate(tmp_path, [_render(1), _render(2), _render(3)]) + config = estate.config() + path = config.parent / "register-outage" + if case == "expired": + proc, _ = _index(estate, config, "outage", "declare", "--until", "2000-01-01T00:00:00Z", + "--why", WHY, "--mirror-seq", "3", + env=dict(estate.env, LANES_INDEX_CONFIG=str(config), LANES_LANE=WINDOW)) + assert proc.returncode == 0 and path.exists(), f"expired: {proc.returncode}: {proc.stderr}" + else: + foreign = estate.config(name="conf-other") + foreign.write_text(foreign.read_text(encoding="utf-8").replace( + f"register_label={LABEL}", "register_label=another-register"), encoding="utf-8") + estate.declared(foreign, mirror_seq=3) + shutil.copy2(foreign.parent / "register-outage", path) + estate.reset_logs() + result = estate.guard(config) + assert not result["killed"], "the hook was killed at 5 s" + assert estate.psql_starts(), "the guard made no direct read: the fake psql has no call" + assert result["exit"] == 2, f"{case}: the guard exited {result['exit']}" + assert "read: mirror" not in result["out"] and "declared outage" not in result["out"] + assert estate.mirror_calls() == [], f"{case}: the guard read the mirror" + + +def test_writes_and_deciding_reads_still_refuse_during_a_declared_outage(tmp_path): + """AT-D20: under a valid declaration, with the database stopped, a write, + `claim`, and a deciding read, `who`, each still refuse with 69: the + declaration opens the guard's read alone. The lane's own register + checkout `<c>` is made first (T219g), so that the outage, not a missing + `<c>`, is what refuses `claim`: T415's `pw_checkout` refuses a write with + 2 before any register call where `<c>` is not there (tasks:1154). + + THE 69 IS THE DATABASE'S, not the code alone (lane 2's RV22, NIT 10): + each command also makes a register call, the stopped fake `psql`'s start + log growing while it runs (`START_PSQL`), and every call that fake takes + is refused at the connect (`STOPPED`). A 69 made before any register + call, as T409's placeholder 69 once passed this case (T219g), fails + here.""" + estate = Estate(tmp_path, [_render(1), _render(2), _render(3)]) + config = estate.config() + estate.declared(config, mirror_seq=3) + estate.lane_checkout() + env = estate.guard_env(config, TMUX=None, TMUX_PANE=None, LANES_SESSION=estate.session) + for argv in (["claim", "opensoft/t215#1"], ["who", "opensoft/t215#1"]): + before = len(estate.psql_starts()) + proc = subprocess.run(["bash", str(tmp_path / "tool" / "lanes-edit.sh"), *argv], + capture_output=True, text=True, env=env, cwd=str(estate.wip), + timeout=120, stdin=subprocess.DEVNULL) + assert proc.returncode == 69, (f"`{argv[0]}` exited {proc.returncode}: " + f"{(proc.stdout + proc.stderr)[-400:]}") + assert len(estate.psql_starts()) > before, ( + f"`{argv[0]}` exited 69 with no register call: the stopped fake psql has no call from it, " + f"so the 69 is not the database's: {(proc.stdout + proc.stderr)[-400:]}") + + +def _free_port() -> int: + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + sock.bind(("127.0.0.1", 0)) + port = sock.getsockname()[1] + sock.close() + return port + + +def _on_pg(pg, root: Path, request, steps: list) -> tuple: + """An estate whose configuration names this test's database on `pg`, as + a writer's and a reader's logins made here until T228's exist, brought + through `steps` by the real commands: `import --at <C>`, `cutover + --import <C>` and `rollback`. Returns (the estate, the configuration, the + real `psql`'s environment, the reader's login). + + AN IMPORT AFTER A `rollback` IS A RE-IMPORT, at origin's tip as fetched + after the rollback, and a later `cutover` names that commit, as + the rollback module's `test_a_reimport_after_a_rollback_continues_the_journal` + makes them (TP:5470-5472): a cutover follows the import it names, at the + head (design.md section 1.3), and lane 1's `cutover` refuses one whose head is + past the latest import's seq, "after a rollback, import again before a + cutover" (`f9e1449c:lanes-index:21956-21958`).""" + estate = Estate(root, [_render(1)]) + writer, reader = (f"t215_{uuid.uuid4().hex[:12]}" for _ in range(2)) + pg.psql(f"CREATE ROLE {writer} LOGIN IN ROLE lanes_register_writer;\n" + f"CREATE ROLE {reader} LOGIN IN ROLE lanes_register_reader;") + request.addfinalizer(lambda: pg.cluster.psql(f"DROP ROLE IF EXISTS {writer}, {reader};", + check=False)) + config = _private(root / "conf-pg" / "lanes-index.conf", "\n".join([ + "mode=primary", f"register_url={pg.url(writer)}", f"register_passfile={estate.passfile}", + f"reader_url={pg.url(reader)}", f"reader_passfile={estate.passfile}", + f"register_label={LABEL}", f"register_schema={SCHEMA}", ""])) + env = dict(estate.env, LANES_INDEX_CONFIG=str(config), LANES_LANE=WINDOW, + PATH=os.pathsep.join([str(estate.bin), str(Path(pg.psql_bin).parent), + os.environ.get("PATH", os.defpath)])) + c = estate.tip() + done = [] + for step in steps: + if step == "import" and "rollback" in done: + estate.fetch() + c = estate.tip() + forms = {"import": ["import", "--at", c], "cutover": ["cutover", "--import", c], + "rollback": ["rollback"]} + proc, _ = _index(estate, config, *forms[step], env=env, timeout=300) + assert proc.returncode == 0, (f"`{step}` (after {done}) exited {proc.returncode}: " + f"{proc.stderr[-600:]}") + done.append(step) + return estate, config, env, reader + + +def _rollbacks_k(config: Path) -> int: + """`k` from the declaration `rollback` wrote (T304), set aside so that the + case can declare again.""" + path = config.parent / "register-outage" + assert path.exists(), "`rollback` wrote no declaration (T304)" + fields = _fields(path) + assert fields.get("kind") == "rollback" and "until" not in fields, fields + path.rename(config.parent / "register-outage.rollbacks") + return int(fields["mirror-seq"]) + + +@pytest.mark.parametrize("form", ["word", "rollback"]) +def test_outage_declare_is_refused_where_the_probe_reads_primary(tmp_path, form): + """AT-D20: the probe reads the switch at `primary`: `outage declare` + exits 2 and writes no file, on Brett's word and in the `--rollback + --mirror-seq <k>` form alike. FP: the fake answers the probe as the + database would.""" + estate = Estate(tmp_path, [_render(1), _render(2)]) + config = estate.config() + estate.answers.write_text(json.dumps(PRIMARY), encoding="utf-8") + proc = estate.declare(config, mirror_seq=4, rollback=(form == "rollback")) + assert proc.returncode == 2, f"{form}: exit {proc.returncode}: {proc.stderr}" + assert not (config.parent / "register-outage").exists(), f"{form}: a file was written" + assert len(estate.psql_starts()) == 1, f"{form}: the probe was not sent once" + + +def test_outage_declare_on_a_persons_word_during_a_rollback_is_refused_and_prints_the_rollback_form( + pg, tmp_path, request): + """AT-D20, real engine, on T304: the probe reads the switch at `files` + with a `rollback` entry at `set_seq`: Brett's word exits 2, writes no + file and prints `outage declare --rollback --mirror-seq <k>`, `k` being + `set_seq - 1`; that command, as printed, writes the declaration, marked + as from a rollback, with `mirror-seq=<k>` and no expiry.""" + estate, config, env, _ = _on_pg(pg, tmp_path, request, ["import", "cutover", "rollback"]) + k = _rollbacks_k(config) + path = config.parent / "register-outage" + proc, _ = _index(estate, config, "outage", "declare", "--until", UNTIL, "--why", WHY, + "--mirror-seq", str(k + 5), env=env) + assert proc.returncode == 2 and not path.exists(), f"Brett's word: {proc.returncode}" + printed = f"outage declare --rollback --mirror-seq {k}" + assert printed in proc.stdout + proc.stderr, (proc.stdout + proc.stderr)[-600:] + proc, _ = _index(estate, config, *printed.split(), env=env) + assert proc.returncode == 0, f"as printed: {proc.returncode}: {proc.stderr}" + fields = _fields(path) + assert fields["kind"] == "rollback" and fields["mirror-seq"] == str(k), fields + assert "until" not in fields + + +@pytest.mark.parametrize("case", ["wrong-k", "no-mirror-seq", "not-a-rollback-entry", + "unreadable"]) +def test_outage_declare_rollback_is_refused_for_a_wrong_k_a_missing_mirror_seq_or_a_switch_it_cannot_read( + tmp_path, request, case): + """AT-D20: the `--rollback` form exits 2 and writes no file for a wrong + `<k>`, with no `--mirror-seq`, where the entry at `set_seq` is not a + `rollback`, and where the probe cannot read the switch. FP for + `no-mirror-seq` (refused before the probe) and `unreadable` (the fake + exits 2); `wrong-k` and `not-a-rollback-entry` run on `pg`, after + `rollback` (T304) and after `import` alone.""" + if case in ("no-mirror-seq", "unreadable"): + estate = Estate(tmp_path, [_render(1), _render(2)]) + config = estate.config() + if case == "no-mirror-seq": + proc, _ = _index(estate, config, "outage", "declare", "--rollback") + else: + proc = estate.declare(config, mirror_seq=4, rollback=True) + else: + pg = request.getfixturevalue("pg") + steps = ["import", "cutover", "rollback"] if case == "wrong-k" else ["import"] + estate, config, env, _ = _on_pg(pg, tmp_path, request, steps) + k = _rollbacks_k(config) + 1 if case == "wrong-k" else 1 + proc, _ = _index(estate, config, "outage", "declare", "--rollback", "--mirror-seq", + str(k), env=env) + assert proc.returncode == 2, f"{case}: exit {proc.returncode}: {proc.stderr}" + assert not (config.parent / "register-outage").exists(), f"{case}: a file was written" + + +@pytest.mark.parametrize("case", ["found-files", "found-primary", "failed-primary-again", + "failed-partition"]) +def test_a_rollbacks_declaration_counts_only_where_the_guards_read_finds_the_switch_at_files( + pg, tmp_path, request, case): + """AT-D20, real engine, on T304: a rollback's declaration (SVC-12's + condition 2) by what the guard's read finds: + - `found-files`: the switch at `files`: the guard answers from the + mirror, with the declared line; + - `found-primary`: a cutover has set `primary` again: the guard answers + from the database, and `status` reports the file; + - `failed-primary-again` and `failed-partition`: the read fails, the + switch being `primary` again, or the guard cut off: the guard exits 2 + with the ordinary refusal, and never reads the mirror. + The cutover that sets `primary` again follows a re-import, since a + cutover after a rollback needs one (`_on_pg`; TP:5470-5472).""" + steps = ["import", "cutover", "rollback"] + if case in ("found-primary", "failed-primary-again"): + steps += ["import", "cutover"] + estate, config, env, reader = _on_pg(pg, tmp_path, request, steps) + path = config.parent / "register-outage" + assert path.exists(), "`rollback` wrote no declaration (T304)" + fields = _fields(path) + k = int(fields["mirror-seq"]) + estate.grow([_render(k)]) + estate.fetch() + url = (pg.url(reader) if case.startswith("found") + else f"postgresql://{reader}@127.0.0.1:{_free_port()}/{pg.name}") + guard_config = estate.config(url=url, name="conf-guard") + shutil.copy2(path, guard_config.parent / "register-outage") + estate.reset_logs() + result = estate.guard(guard_config, PATH=env["PATH"]) + assert not result["killed"], "the hook was killed at 5 s" + if case == "found-files": + assert f"read: mirror at {estate.tip()[:12]}" in result["out"], result["out"][-600:] + assert _label(fields) in result["out"], result["out"][-600:] + return + assert "read: mirror" not in result["out"] and _label(fields) not in result["out"] + if case == "found-primary": + proc, _ = _index(estate, config, "status", env=env) + assert "register-outage" in proc.stdout + proc.stderr, (proc.stdout + proc.stderr)[-600:] + return + assert result["exit"] == 2, f"{case}: exit {result['exit']}" + assert estate.mirror_calls() == [], f"{case}: the guard read the mirror" + + +def test_status_reports_a_declaration_left_in_place(pg, tmp_path, request): + """AT-D20, real engine: with the database answering and the switch at + `primary`, a declaration left in place is ignored by the guard, which + answers from the database, and `status` reports it. + + `status` keeps T117's exit (lane 3's (L2-1), #165 6808937880). The + register reads, so the exit is #160's own (B15 tasks:545, "Exits: 69 + where the register cannot be read ...; otherwise #160's own 0 or 1"; + exit-codes.md section 3.4), never 69. This estate has no local index, + so #160's half gives its 1, with its `index: missing - <path> does not + exist` line. Lane 3's corrected oracle (#165 6812031872, on lane 1's + 6810924785): "the case asserts the declaration's `outage:` line and + #160's `index: missing - ... does not exist` line, both on stdout, and + that the exit is #160's 1, never 69. That oracle names the cause, so + it cannot pass on another failure." Stderr is not in the oracle: `say` + writes stdout, and `status` prints both lines through it + (`lanes-index:205-206`, `:16417` at `465680ee`).""" + estate, config, env, reader = _on_pg(pg, tmp_path, request, ["import", "cutover"]) + estate.declared(config, mirror_seq=1) + guard_config = estate.config(url=pg.url(reader), name="conf-guard") + shutil.copy2(config.parent / "register-outage", guard_config.parent / "register-outage") + result = estate.guard(guard_config, PATH=env["PATH"]) + assert not result["killed"], "the hook was killed at 5 s" + assert "read: mirror" not in result["out"] and "declared outage" not in result["out"] + proc, _ = _index(estate, config, "status", env=env) + said = f"stdout: {proc.stdout[-900:]!r}; stderr: {proc.stderr[-300:]!r}" + outage = [line.strip() for line in proc.stdout.splitlines() + if line.strip().startswith("outage:")] + assert any("declared outage" in line and "register-outage" in line for line in outage), ( + f"stdout has no `outage:` line naming the declaration left in place: {said}") + assert re.search(r"^index: missing - .+ does not exist$", proc.stdout, re.M), ( + f"stdout has no `index: missing - ... does not exist` line, #160's: {said}") + assert proc.returncode == 1, f"status exited {proc.returncode}, not #160's 1: {said}" + + +# ===================================================================== T279 +# +# The rollback's cases of D20 (AT-D20 in phase G; L2-N5; B15 tasks:2557, +# "Write the rollback's cases of D20, P3 and AT-F13"): a rollback's start +# declares the outage, writable and read-only, and a rollback rerun declares +# before it goes on, on test 8's estate. TP's AT-D20 "Fixture": "For the +# rollback's cases, test 8's estate, its rollback held at its push by the +# `git` wrapper; once with a writable configuration directory, and once with +# it read-only. For the rerun, the rollback is killed on the shim's FIFO +# signal right after its transaction returns, so no declaration was written." +# +# TEST 8'S ESTATE is copied from `tests/test_sql_register_rollback.py` at DV's +# tip `92fbaf27` (RB's T273b), since the modules share no helper file: its +# `RollbackEstate` (the parts these cases use), its `git` wrapper (here +# `ROLLBACK_GIT_WRAPPER`), `_estate` (here `_rollback_estate`), +# `_held_at_push`, `_open_when_held`, `_said` and `_jsonl`. `unhold` is this +# module's own: the wrapper's hold is taken off before a held call is +# released, so a second call of that subcommand never blocks on a FIFO no +# one opens. Like the rollback module, the estate builds on test 7's cutover +# host, `test_sql_register_import.py`'s `CutoverRegister`, imported when a +# case runs. +# +# Its tests fail until L1-A18, L4-B10, T304 and T326 land (T279's Order), +# and test 8's estate until T327, T321 to T323, T415 and T416, as its +# `prepare()` says. + +#: TEST 5'S `git` WRAPPER as test 8 has it (TP:1060-1080): each call is one +#: JSON line of `git-wrapper.log`, its subcommand, its argv, its pid, and +#: `psql_before`, the number of requests the `psql` log named in the control +#: file held when it started. `hold`, `{"call": <subcommand>, "fifo": path}`, +#: blocks that call on the FIFO until the test closes its end. +ROLLBACK_GIT_WRAPPER = r'''#!/usr/bin/env -S python3 -I +import json, os, subprocess, sys +HERE = os.path.dirname(os.path.abspath(__file__)) +CONTROL = os.path.join(HERE, "git-wrapper.json") +LOG = os.path.join(HERE, "git-wrapper.log") +WITH_VALUE = {"-C", "-c", "--git-dir", "--work-tree", "--namespace", "--exec-path", + "--config-env"} + + +def subcommand(args): + i = 0 + while i < len(args): + if args[i] in WITH_VALUE: + i += 2 + elif args[i].startswith("-"): + i += 1 + else: + return args[i] + return "" + + +def requests(path): + try: + with open(path, encoding="utf-8") as handle: + return sum(1 for line in handle + if line.strip() and json.loads(line).get("kind") != "version") + except (OSError, ValueError): + return 0 + + +def log(record): + with open(LOG, "a", encoding="utf-8") as handle: + handle.write(json.dumps(record) + "\n") + + +def main(): + args = sys.argv[1:] + with open(CONTROL, encoding="utf-8") as handle: + control = json.load(handle) + sub = subcommand(args) + record = {"sub": sub, "argv": args, "pid": os.getpid(), + "psql_before": requests(control.get("psql_log") or "")} + hold = control.get("hold") + if hold and hold.get("call") == sub: + log(dict(record, outcome="held")) + with open(hold["fifo"], "rb") as fifo: + fifo.read() + rc = subprocess.run([control["git"]] + args).returncode + log(dict(record, outcome="ran", rc=rc)) + return rc + + +sys.exit(main()) +''' + +#: The rollback's declaration's file name, beside its configuration (D20; +#: config.md section 6.1). +OUTAGE_FILE = "register-outage" + + +def _rb_imp(): + """`test_sql_register_import`: test 7's fixture register and cutover host.""" + import test_sql_register_import as module + return module + + +def _said(proc) -> str: + return (f"exit {proc.returncode}\n--- stdout ---\n{(proc.stdout or '')[-3000:]}" + f"\n--- stderr ---\n{(proc.stderr or '')[-3000:]}") + + +def _jsonl(path: Path) -> list: + if not path.exists(): + return [] + return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line] + + +def _open_when_held(fifo: Path, proc: subprocess.Popen, seconds: float = 120): + """The FIFO's write end, opened once a call is held on it; None where + `proc` ends, or the time runs out, first. Closing it releases the call.""" + deadline = time.monotonic() + seconds + while time.monotonic() < deadline and proc.poll() is None: + try: + return os.open(str(fifo), os.O_WRONLY | os.O_NONBLOCK) + except OSError: + time.sleep(0.05) + return None + + +def _ended(proc: subprocess.Popen, seconds: float = 300) -> tuple: + """`proc`'s stdout and stderr once it ends, killed at `seconds`, so a + case never waits without a bound.""" + try: + return proc.communicate(timeout=seconds) + except subprocess.TimeoutExpired: + proc.kill() + out, err = proc.communicate() + return out, f"{err}\n(killed: still running after {seconds} s)" + + +class RollbackEstate: + """TEST 8'S ESTATE (TP:1592-1636), on test 7's cutover host, copied from + the rollback module (see this section's head). `prepare()` makes the + cutover and the writes; until their tasks land it fails at its own + assertion, naming them.""" + + def __init__(self, root: Path, db, *, writes: int = 2): + from sql_register_helpers import PSQL_SHIM + imp = _rb_imp() + self.imp, self.db, self.root, self.writes = imp, db, root, writes + self.bin = root / "bin" + _script(self.bin / "git", ROLLBACK_GIT_WRAPPER) + _script(self.bin / "psql", PSQL_SHIM) + self.real_git = shutil.which("git") + assert self.real_git, "no git on PATH" + self.arm() + self.reg = imp.CutoverRegister(root / "ws1", db, extra_path=self.bin) + self.k = None + + # ------------------------------------------------------------ the wrapper and the shim + def arm(self, arms=(), hold: dict | None = None) -> None: + """The shim's arms and the wrapper's hold, each log started afresh.""" + from sql_register_helpers import PSQL_SHIM_CONTROL, PSQL_SHIM_LOG + (self.bin / PSQL_SHIM_CONTROL).write_text( + json.dumps({"psql": self.db.psql_bin, "arms": list(arms)}), encoding="utf-8") + for name in (PSQL_SHIM_LOG, "psql-shim.ends", "git-wrapper.log"): + (self.bin / name).write_text("", encoding="utf-8") + (self.bin / "psql-shim.state").write_text("{}", encoding="utf-8") + self._control(hold) + + def _control(self, hold: dict | None) -> None: + from sql_register_helpers import PSQL_SHIM_LOG + control = {"git": self.real_git, "psql_log": str(self.bin / PSQL_SHIM_LOG)} + if hold: + control["hold"] = hold + (self.bin / "git-wrapper.json").write_text(json.dumps(control), encoding="utf-8") + + def unhold(self) -> None: + """The wrapper's hold taken off, its logs kept (this module's own).""" + self._control(None) + + def git_calls(self) -> list: + return [c for c in _jsonl(self.bin / "git-wrapper.log") if c.get("outcome") == "ran" + or c.get("outcome") == "held"] + + # ------------------------------------------------------------ the database + def rows(self, sql: str) -> list: + return self.imp._rows(self.db, sql) + + def switch(self) -> dict: + return self.rows("SELECT * FROM register_switch")[0] + + def head(self) -> int: + return self.rows("SELECT seq FROM register_head")[0]["seq"] + + def journal(self) -> list: + return [[r["seq"], r["kind"], r["operator"]] + for r in self.rows("SELECT seq, kind, operator FROM journal ORDER BY seq")] + + # ------------------------------------------------------------ the commands + def prepare(self) -> None: + """The cutover, then `writes` writes on primary from ws1, each + rendered: `k` is the head.""" + proc = self.reg.cutover() + assert proc.returncode == 0, f"the cutover (T116) failed:\n{_said(proc)}" + switch = self.switch() + assert (switch["mode"], switch["marker_state"]) == ("primary", "present"), ( + f"after the cutover the switch reads {switch['mode']} with the marker " + f"{switch['marker_state']}: the marker's push, read-back and record_marker are lane " + f"3's T327, so test 8's estate fails until it lands") + for n in range(1, self.writes + 1): + proc = self.reg.write(f"test 8: write {n}") + assert proc.returncode == 0, ( + f"write {n} on primary from ws1 failed (lane 4's T415 and T416):\n{_said(proc)}") + self.k = self.head() + assert self.reg.wait_for_seq(self.k), ( + f"no mirror commit carries Register-Seq: {self.k} (lane 3's T321 to T323): " + f"{self.reg.seqs_on_origin()}") + self.arm() + + def popen_rollback(self) -> subprocess.Popen: + return self.reg.popen("rollback", conf=self.reg.primary_conf) + + def outage_file(self) -> Path: + return self.reg.primary_conf.parent / OUTAGE_FILE + + +def _rollback_estate(request, root: Path) -> RollbackEstate: + """A prepared `RollbackEstate` on a database of the session cluster's + own, dropped at the case's end.""" + from pgcluster import Database + cluster = request.getfixturevalue("pg_cluster") + name = cluster.new_database() + request.addfinalizer(lambda: cluster.drop_database(name) if cluster.ready() else None) + estate = RollbackEstate(root, Database(cluster, name)) + estate.cluster = cluster + estate.prepare() + return estate + + +def _held_at_push(estate: RollbackEstate): + """The rollback from ws1, held by the wrapper at its push: (the process, + the FIFO's write end), or a failure where it ends first.""" + fifo = estate.root / "push.fifo" + if not fifo.exists(): + os.mkfifo(str(fifo), 0o600) + estate.arm(hold={"call": "push", "fifo": str(fifo)}) + proc = estate.popen_rollback() + fd = _open_when_held(fifo, proc, 300) + if fd is None: + out, err = _ended(proc, 60) + pytest.fail(f"the rollback never reached its push: exit {proc.returncode}\n{out}\n{err}") + return proc, fd + + +def _read_only(directory: Path, request) -> None: + """`directory` made read-only, as a bench's mount is (Q23(a)), and given + its mode back when the case ends. An account that still creates a file + there (root) cannot run a read-only case, and the case says so.""" + mode = directory.stat().st_mode & 0o777 + directory.chmod(0o555) + request.addfinalizer(lambda: directory.chmod(mode)) + probe = directory / ".t279-probe" + try: + probe.write_text("", encoding="utf-8") + except OSError: + return + probe.unlink() + raise AssertionError(f"{directory} is 0555 and this account still writes in it: a " + f"read-only case needs an account the mode binds") + + +def _conf_value(conf: Path, key: str, default: str | None = None) -> str: + for line in conf.read_text(encoding="utf-8").splitlines(): + if line.startswith(key + "="): + return line.split("=", 1)[1] + assert default is not None, f"{conf} has no {key}=" + return default + + +def _rollback_fields(fields: dict, k: int, where: str) -> None: + """A rollback's declaration (config.md section 6.3): marked as from a + rollback, `mirror-seq=<k>`, and no expiry.""" + assert fields.get("format") == "1" and fields.get("kind") == "rollback", ( + f"{where}: the declaration is not marked as from a rollback: {fields}") + assert fields.get("mirror-seq") == str(k), ( + f"{where}: mirror-seq is {fields.get('mirror-seq')}, not k = {k}, the head the " + f"rollback's transaction found: {fields}") + assert "until" not in fields, f"{where}: a rollback's declaration carries an expiry: {fields}" + + +def _guard_for(estate: RollbackEstate, request, root: Path) -> tuple: + """The guard's workstation for a rollback's declaration, as + `[found-files]` builds its own: an `Estate` whose origin carries renders + up to `k`, so its mirror is at the declaration's `mirror-seq`, and a + `mode=primary` configuration naming test 8's database through a reader + login of its own, with the label of the rollback's configuration, which + the declaration's `database=` names. Returns (the estate, its + configuration, the `PATH` with the real `psql`).""" + guard = Estate(root, [_render(s) for s in range(1, estate.k + 1)]) + reader = f"t279_{uuid.uuid4().hex[:12]}" + estate.db.psql(f"CREATE ROLE {reader} LOGIN IN ROLE lanes_register_reader;") + request.addfinalizer(lambda: estate.cluster.psql(f"DROP ROLE IF EXISTS {reader};", + check=False)) + conf = estate.reg.primary_conf + url = estate.db.url(reader) + guard_conf = _private(root / "conf-guard" / "lanes-index.conf", "\n".join([ + "mode=primary", f"register_url={url}", f"register_passfile={guard.passfile}", + f"reader_url={url}", f"reader_passfile={guard.passfile}", + f"register_label={_conf_value(conf, 'register_label')}", + f"register_schema={_conf_value(conf, 'register_schema', SCHEMA)}", ""])) + path = os.pathsep.join([str(guard.bin), str(Path(estate.db.psql_bin).parent), + os.environ.get("PATH", os.defpath)]) + return guard, guard_conf, path + + +@pytest.mark.parametrize("mode", ["writable", "read-only"]) +def test_a_rollbacks_start_declares_the_outage(request, tmp_path, mode): + """AT-D20, the rollback's start (TP's AT-D20 oracle, "The rollback's + start"; operations.md 2.3, step 2's "The declaration"), on test 8's + estate, the rollback held at its push by the `git` wrapper. `k` is the + estate's head, and the rollback's own entry is `k+1` (T304's step 1). + + - `[writable]`: while the rollback is held, `register-outage` is beside + its configuration, marked as from a rollback, with `mirror-seq=<k>`, + the head its transaction found (the switch's `set_seq` less 1), and + no expiry; the guard, whose read finds the switch at `files`, answers + from the mirror, with the declared line. Released, the rollback ends 0, + and step 6's `outage clear` (operations.md 2.3, step 6: "Brett then + runs `lanes-index outage clear`"), run here as Brett runs it, removes + the file. + - `[read-only]`: the configuration's directory is read-only, as a + bench's mount is (Q23(a)): no file is written, while it is held or + after, and stdout carries `outage declare --rollback --mirror-seq <k>`. + + Fails until T304 and T326, and test 8's estate until T327, T321 to T323, + T415 and T416; the guard's half until T507 (L5-A3, L5-A5).""" + estate = _rollback_estate(request, tmp_path / "rollback") + k, conf, path = estate.k, estate.reg.primary_conf, estate.outage_file() + guard = guard_conf = guard_path = reference = None + if mode == "writable": + guard, guard_conf, guard_path = _guard_for(estate, request, tmp_path / "guard") + reference = guard.reference() + else: + _read_only(conf.parent, request) + proc, fd = _held_at_push(estate) + result = None + try: + switch = estate.switch() + declared = path.exists() + fields = _fields(path) if declared else {} + if guard is not None and declared: + shutil.copy2(path, guard_conf.parent / OUTAGE_FILE) + result = guard.guard(guard_conf, PATH=guard_path) + finally: + estate.unhold() + os.close(fd) + out, err = _ended(proc) + ended = f"exit {proc.returncode}\n--- stdout ---\n{out[-3000:]}\n--- stderr ---\n{err[-3000:]}" + assert (switch["mode"], switch["set_seq"]) == ("files", k + 1), ( + f"held at its push, the switch is {switch}, not files at the rollback's own seq {k + 1}") + if mode == "read-only": + assert not declared and not path.exists(), ( + f"a declaration was written beside a read-only configuration:\n{ended}") + printed = f"outage declare --rollback --mirror-seq {k}" + assert printed in out, f"stdout does not carry {printed!r}:\n{ended}" + assert proc.returncode == 0, f"the rollback did not end 0:\n{ended}" + return + assert declared, f"held at its push, the rollback had declared no outage at {path}:\n{ended}" + _rollback_fields(fields, switch["set_seq"] - 1, "held at its push") + _answers_from_the_mirror(guard, result, fields, reference, guard.tip()) + assert proc.returncode == 0, f"the rollback did not end 0:\n{ended}" + cleared = estate.reg.index("outage", "clear", conf=conf) + assert cleared.returncode == 0 and not path.exists(), ( + f"step 6's `outage clear` did not remove the declaration:\n{_said(cleared)}") + + +@pytest.mark.parametrize("mode", ["writable", "read-only"]) +def test_a_rollback_rerun_declares_before_it_goes_on(request, tmp_path, mode): + """AT-D20, the rollback's rerun (TP's AT-D20 oracle, "The rollback's + rerun"; operations.md 2.3, step 2's "A rerun"), on test 8's estate. + + THE FIRST RUN is killed on the shim's FIFO signal right after its + transaction returns: the shim's `timer` arm with a FIFO, on step 1's + call (the first that carries `commit_write`), runs the real `psql` and + then blocks before it answers; the test kills the rollback there, so it + never declared. The switch is then at `files`, the marker `removing`, + and the rollback's own entry, `k+1`, the last seq. + + THE RERUN declares first, with the `git` wrapper holding it at its first + render call: + - `[writable]`: the file exists by then, marked as from a rollback, with + `mirror-seq=<k>` for `k = set_seq - 1`, and no expiry; + - `[read-only]`: the configuration's directory is read-only, no file is + written, and the rerun's stdout carries `outage declare --rollback + --mirror-seq <k>`. + Then it goes on from the render: released, it ends 0, with no entry of + its own past `k+1`. + + THE FIRST RENDER CALL is read as the render's `git fetch`: a rerun goes + on from step 2 (B15 tasks:1033, T304's "A rerun ... declares first, and + goes on from step 2"), which renders as T322's pass does (T326's step + 2), and that pass fetches first (exit-codes.md section 3.4, `reconcile`'s + 1: "a failed fetch, walk, build or push"). A rerun runs no step 0 or 1, + so its first `fetch` is the render's. + + Fails until T304 and T326, and test 8's estate until T327, T321 to T323, + T415 and T416.""" + estate = _rollback_estate(request, tmp_path / "rollback") + k, conf, path = estate.k, estate.reg.primary_conf, estate.outage_file() + step_1 = tmp_path / "step-1.fifo" + os.mkfifo(str(step_1), 0o600) + estate.arm([{"mode": "timer", "match": "commit_write", "call": 1, "fifo": str(step_1)}]) + first = estate.popen_rollback() + fd = _open_when_held(step_1, first, 300) + if fd is None: + out, err = _ended(first, 60) + pytest.fail(f"the first run's step-1 call never returned to the shim's FIFO: exit " + f"{first.returncode}\n{out}\n{err}") + first.kill() + first.wait() + os.close(fd) + switch, last = estate.switch(), estate.journal()[-1] + assert (switch["mode"], switch["marker_state"], last) == ("files", "removing", + [k + 1, "rollback", True]), ( + f"after the kill the switch is {switch} and the last entry {last}, not files, removing " + f"and the rollback's own entry at {k + 1}") + assert not path.exists(), ( + "the first run declared before its transaction returned, so no rerun can show that it " + "declares first") + if mode == "read-only": + _read_only(conf.parent, request) + render = tmp_path / "render.fifo" + os.mkfifo(str(render), 0o600) + estate.arm(hold={"call": "fetch", "fifo": str(render)}) + rerun = estate.popen_rollback() + fd = _open_when_held(render, rerun, 300) + if fd is None: + out, err = _ended(rerun, 60) + pytest.fail(f"the rerun made no render call (its fetch): exit {rerun.returncode}\n" + f"{out}\n{err}") + try: + seen = estate.switch() + declared = path.exists() + fields = _fields(path) if declared else {} + finally: + estate.unhold() + os.close(fd) + out, err = _ended(rerun) + ended = f"exit {rerun.returncode}\n--- stdout ---\n{out[-3000:]}\n--- stderr ---\n{err[-3000:]}" + if mode == "read-only": + assert not declared and not path.exists(), ( + f"a declaration was written beside a read-only configuration:\n{ended}") + printed = f"outage declare --rollback --mirror-seq {seen['set_seq'] - 1}" + assert printed in out, f"the rerun's stdout does not carry {printed!r}:\n{ended}" + else: + assert declared, f"at its first render call the rerun had not declared:\n{ended}" + _rollback_fields(fields, seen["set_seq"] - 1, "at the rerun's first render call") + assert rerun.returncode == 0, f"the rerun did not go on from the render to its end:\n{ended}" + assert estate.journal()[-1] == [k + 1, "rollback", True], ( + f"the rerun wrote an entry of its own: {estate.journal()[-3:]}") diff --git a/tests/test_sql_register_render.py b/tests/test_sql_register_render.py new file mode 100644 index 00000000..3e89fadd --- /dev/null +++ b/tests/test_sql_register_render.py @@ -0,0 +1,2837 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Feature 007's test 1 (AT-1, L2-N1; opensoft/openRepoTools#165): the mirror +byte-identical to a full render from SQL after a write. + +THIS MODULE TODAY holds test 1's phase-N part, lane 2's T210: + + * `test_a_storage_layer_entry_renders_byte_identical_to_a_full_render[<entry>]` + (N, RE): the storage layer's write entry, called as the projection writer + will call it, then the pure renderer; + * `test_the_render_of_one_entry_and_of_a_full_render_is_timed_and_recorded` + (N, RE; M6): the pure renderer timed, never asserted; + * `test_sync_source_register_does_nothing_on_primary_and_says_so` (FP, no + engine); + +and the image cache's own cases, lane 2's T210e (B10 tasks:972's +`PENDING-L2`), each named with `image_cache` so that lane 1's T302 selects +them with `-k 'sql_register_render and image_cache'`, with no engine: see +"the image cache (T302's API)" below; + +and the render read's one case with `start`, lane 2's T210f (B10 tasks:1003; +lane 1's T301 cache-forward, #165 6767347563): with `start`, +`register_render_read` returns the images, `{path: bytes}`, and not the rows. +No engine, no image cache: see "the render read's `start`" below; + +and test 1's phase-W part, lane 2's T240: each verb through `lanes-edit.sh` +on `mode=primary` with the pure renderer writing a scratch mirror, its +files-mode twin, `rename-lane`'s transaction then its move, a caller's UTC +kept, and no register `sync` nudge on primary (see "phase W: T240" below); + +and test 1's phase-G part, lane 2's T270's one case here: the mirror read +from the bare origin's `main` after the forked render (see "phase G: T270" +below). + +THE STORAGE-LAYER ENTRY (design S4; the delta spec's "The managed seam stays +the ledger's"). The managed projection writer arrives with the 001 feature's +T024; this change provides the entry it will call and tests it with a fake +writer. Its storage layer is `lanes-index`, the one database client (D2), and +one attempt of S1's loop is two calls (contract section 1): + + 1. `lanes-index register snapshot --write-id new --lane <l> --verb <v> + --args-sha256 <h> --tree <attempt>/tree --checkout <c>` (section 3.2), + which mints the write id and builds the scratch tree at `n`; + 2. the verb's edit in the scratch tree, then the attempt directory, as the + seam writes it (section 3.3's table: `snapshot`, `changes.tsv`, + `images/`, `tree/`, `msg`, `author`, `files`, `not_after`); + 3. `lanes-index register commit --write-id <w> --generation <g> --lane <l> + --verb <v> --args-sha256 <h> --workstation <ws> <attempt>` (section 3.3). + +The fake writer, `projection_entry`, does exactly that, and abandons on any +end of the snapshot but 0 (section 3.3, "The caller's map"). Its cases are +the managed projection itself, which rewrites a row's state cell to carry a +managed-owner marker (`lanes-edit.sh`'s ported reader at 3c26041), and two +other entries of S1's writes, a log line and a `LANES.md` take, so that the +renderer is checked on a row, a line of `LANES.md` and a log. + +THE REGISTER, "against an import": a files-mode repository at commit C, +holding AT-1's fixture register (three lanes, one archived; aliases; a lane +with `HOLD`, `LANDING` and `LANDED` lines; a log with `WORD` lines whose UTC +carries milliseconds), loaded by AT-LR006's route (the test plan at +4610-4615): as `lanes_register_writer`, `commit_write` with an `import` entry +of C's render set, then a `cutover` entry, then `record_marker`, so the +switch is `primary` with the marker `present`. No `lanes-index import` or +`cutover` runs (those are L1-A13's and group C's). + +THE PURE RENDERER is lane 3's T301, as lane 1 built it (#165 6754569755): +`lanes-index render --images --at <k> --out <dir>` (contract section 3.6), +which writes the render set's images at seq `k` from the journal alone. The +full render from SQL is `render_file` (lane 1's T107) of every path in +`files`. + +REAL ENGINE. The entry's cases ask for `pg` (`tests/pgcluster.py`), one +database cloned from the template that T227 builds by the bootstrap; on T205's +empty template they fail, since the schema is not there, and without +PostgreSQL 16 they skip with T205's banner. They fail until L1-A6 (T107 and +T108), L1-A9 (T111, `register snapshot`), L1-A10 (T112, `register commit`) +and T301 land. `lanes-index` runs as T203's flipped copy, `RENDER_GIT_HALF = +True`, so `mode=primary` loads (open point 3), and connects as two logins of +this module's own, members of the writer and the reader groups, by the +cluster's trust. + +`sync --source register` NEEDS NO ENGINE: on primary it makes no `psql` +call, writes nothing and says it does nothing on primary (L1-A15, lane 1's +T117). It runs with T203's register fake first on `PATH`, whose log, with no +call that carries a request in it, is the oracle for "no `psql` call"; the +fake answers T106's `psql --version` probe itself since T203b. +""" + +from __future__ import annotations + +import atexit +import base64 +import hashlib +import json +import os +import re +import shlex +import shutil +import stat +import subprocess +import sys +import tempfile +import time +import uuid +from pathlib import Path +from urllib.parse import quote + +import pytest + +from conftest import REPO, WINDOWS_SKIP +from sql_register_helpers import (LANES_INDEX, PSQL_SHIM, PSQL_SHIM_CONTROL, PSQL_SHIM_LOG, + REGISTER_FAKE_PSQL, RENDER_GIT_HALF_LINE, contract_stub, + flipped_copy) + +pytestmark = [WINDOWS_SKIP, pytest.mark.skipif( + shutil.which("bash") is None or shutil.which("git") is None, + reason="the lane tooling is bash over git")] + +#: THE LANDING GATE'S TABLE (T280; `tests/sql_register_gate.py` reads it, and +#: T281 removes it in the last set): the tasks each id of this module waits +#: for, by T210's, T240's and T270's Orders (tasks.md at 204145ae), keyed by +#: function. Lane 2's plan GP-24 wrote it (task sets 12b's rule 11). +SQL_REGISTER_GATE_TABLE = { + "test_a_caller_composed_utc_and_log_paused_utc_stay_as_written": ("T414", "T415", "T416", "T421", "T422"), # T240; tasks:2313 + "test_a_storage_layer_entry_renders_byte_identical_to_a_full_render": ("T105", "T107", "T108", "T111", "T112", "T227", "T301"), # T210; tasks:1951 + "test_each_write_leaves_the_mirror_byte_identical_to_a_full_render": ("T414", "T415", "T416", "T421", "T422"), # T240; tasks:2313 + "test_each_write_matches_its_files_mode_twin_byte_for_byte": ("T414", "T415", "T416", "T421", "T422"), # T240; tasks:2313 + "test_each_write_reads_back_primary_as_the_mode_that_wrote_it_last": ("T414", "T415", "T416", "T421", "T422"), # T240; tasks:2313 + "test_on_primary_a_write_does_not_nudge_a_register_sync": ("T414", "T415", "T416", "T421", "T422"), # T240; tasks:2313 + "test_rename_lane_commits_the_transaction_only_where_its_handoffs_path_has_no_cache_part_on_primary": ("T414", "T415", "T416", "T421", "T422"), # T240; tasks:2313 + "test_rename_lane_commits_the_transaction_then_a_rerun_makes_only_the_move": ("T414", "T415", "T416", "T421", "T422"), # T240; tasks:2313 + "test_rename_lane_commits_the_transaction_then_its_move_on_primary_takes_no_bytecode_to_to": ("T414", "T415", "T416", "T421", "T422"), # T240; tasks:2313 + "test_sync_source_register_does_nothing_on_primary_and_says_so": ("T105", "T107", "T108", "T111", "T112", "T227", "T301"), # T210; tasks:1951 + "test_the_image_cache_collects_all_but_the_last_three_manifests_past_the_floor": ("T302",), # T210; tasks:1951 + "test_the_image_cache_follows_no_symlink_at_its_lock_or_its_head": ("T302",), # T210; tasks:1951 + "test_the_image_cache_puts_and_gets_an_object_only_by_its_digest": ("T302",), # T210; tasks:1951 + "test_the_image_cache_records_manifests_and_a_head_that_moves_only_forward": ("T302",), # T210; tasks:1951 + "test_the_image_cache_skips_a_busy_or_odd_lock_and_never_waits": ("T302",), # T210; tasks:1951 + "test_the_mirror_on_origin_equals_a_full_render_after_each_write": ("T320", "T321", "T322", "T323", "T325", "T415", "T416"), # T270; tasks:2479 + "test_the_render_of_one_entry_and_of_a_full_render_is_timed_and_recorded": ("T105", "T107", "T108", "T111", "T112", "T227", "T301"), # T210; tasks:1951 + "test_the_render_read_with_start_returns_the_images_and_a_bad_start_costs_one_full_read": ("T301",), # T210; tasks:1951 +} + +LANES_EDIT = REPO / "lanes-edit.sh" + +#: The register's schema, `register_schema=`'s default (contract section 2.5). +SCHEMA = "lanes_register" +WRITER, READER = "lanes_register_writer", "lanes_register_reader" +#: The logins `lanes-index` connects as in this module's real-engine cases. +#: Made once per cluster, members of the writer and the reader groups, with +#: no password. +LOGIN_WRITER, LOGIN_READER = "t210_register_writer", "t210_register_reader" + +#: What the fake writer stamps: the workstation (`--workstation`, and each +#: line's `session <uuid>@<ws>`), the author, and the operator lane. +WS = "Eagle" +AUTHOR = "T210 fake writer <t210@example.invalid>" +OPERATOR = "repoA-2" +MARKER_COMMIT = "e" * 40 +STORE_UTC = "2026-11-09T10:00:00Z" + +#: The register's punctuation, spelled by code point so no raw character +#: enters this file: the em dash, the middle dot of a state cell, the arrow +#: of a `LANDED` line. +EM, DOT, ARROW = chr(0x2014), chr(0x00B7), chr(0x2192) + +SID_A1 = "aaaaaaaa-0001-4000-8000-00000000a001" +SID_A2 = "aaaaaaaa-0003-4000-8000-00000000a003" +SID_Z1 = "eeeeeeee-0001-4000-8000-00000000e001" +TIP = "0123456789abcdef0123456789abcdef01234567" + +#: The render set (Q18 (A); contract section 3.6): `lanes/LANES.md`, +#: `lanes/aliases.tsv`, each `lanes/log/<lane>.md` but the README, and the +#: archive. `lanes/STORE` is the operator entries' alone, never a write's. +RENDER_SET = re.compile(r"^lanes/(LANES\.md|aliases\.tsv|archive/[^/]+\.md" + r"|log/(?!README\.md$)[^/]+\.md)$") +STORE_PATH = "lanes/STORE" +UTC_RE = re.compile(r"^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z$") + + +def _row(lane: str, sid: str, state: str, started: str = "2026-10-01T00:00Z") -> str: + return (f"| `{lane}` | harness `{sid}` | Eagle / test / brett | {started} | none " + f"| handoffs/{lane}.md | {state} |") + + +#: AT-1's fixture register at C ("Fixture"): three lanes, one of them +#: archived; `aliases.tsv` entries; a lane with `HOLD`, `LANDING` and +#: `LANDED` lines; a log with `WORD` lines whose UTC carries milliseconds +#: (Q4(d)(i)). `lanes/repos.tsv` and `lanes/log/README.md` are outside the +#: render set, and `register snapshot --tree` takes them from the checkout. +SEED = { + "lanes/LANES.md": "\n".join([ + f"# LANES.md {EM} test 1's fixture register", + "", + "| lane | session id | workstation / env / user | started (UTC) | objects owned " + "| handoff path | state |", + "|---|---|---|---|---|---|---|", + _row("repoA-1", SID_A1, f"LIVE {DOT} 2026-10-01T01:00:00Z {DOT} working"), + _row("repoA-2", SID_A2, f"PAUSED {DOT} 2026-10-01T02:00:00Z {DOT} parked"), + "", + f"HOLD {EM} lane repoA-1 (Eagle), window w, 2026-10-01T03:00:00Z: opensoft/repoA main " + f"{TIP} for a frozen window", + f"LANDING {EM} lane repoA-1, session {SID_A1}@Eagle, 2026-10-01T03:10:00Z, PR #7 into " + f"opensoft/repoA main", + f"LANDED {EM} lane repoA-1, session {SID_A1}@Eagle, 2026-10-01T03:15:00Z, PR #7 into " + f"opensoft/repoA main {ARROW} abc1234", + ""]), + "lanes/aliases.tsv": "# old\tnew\tutc\nrepoOld-1\trepoA-2\t2026-09-30T00:00:00Z\n", + "lanes/archive/LANES-retired.md": "\n".join([ + "# retired rows (Amendment 19(d))", "", + _row("repoZ-1", SID_Z1, f"RETIRED {DOT} 2026-09-02T00:00:00Z {DOT} retired"), + ""]), + "lanes/log/repoA-1.md": "\n".join([ + f"# lane repoA-1 {EM} object log (lane-collision-protocol Amendment 7)", + f"STARTED {EM} lane repoA-1, session {SID_A1}@Eagle, 2026-10-01T00:00:00Z, " + f"lane:repoA-1 {ARROW} home opensoft/repoA; dir /work/repoA1", + ""]), + "lanes/log/repoA-2.md": "\n".join([ + f"# lane repoA-2 {EM} object log (lane-collision-protocol Amendment 7)", + f"STARTED {EM} lane repoA-2, session {SID_A2}@Eagle, 2026-10-01T02:00:00Z, " + f"lane:repoA-2 {ARROW} home opensoft/repoA; dir /work/repoA2", + f"NOTED {EM} lane repoA-2, session {SID_A2}@Eagle, 2026-10-01T02:10:00.123Z, " + f"lane:repoA-2 {EM} a stamp with milliseconds", + f"NOTED {EM} lane repoA-2, session {SID_A2}@Eagle, 2026-10-01T02:11:00.456Z, " + f"lane:repoA-2 {EM} another", + ""]), + "lanes/log/README.md": "# the object logs\n", + "lanes/repos.tsv": "# alias\towner/repo\nrepoA\topensoft/repoA\n", +} + + +# ------------------------------------------------------------------ the estate +def git(cwd: Path, *args: str, env: dict | None = None) -> str: + proc = subprocess.run(["git", *args], cwd=str(cwd), capture_output=True, text=True, + env=env, check=False) + assert proc.returncode == 0, f"git {' '.join(args)} in {cwd}: {proc.stderr}{proc.stdout}" + return proc.stdout + + +def git_env(home: Path) -> dict: + """A git with no person's configuration in it, and an identity of its own.""" + env = {k: v for k, v in os.environ.items() + if not k.startswith(("GIT_", "PG", "LANES_", "TMUX"))} + env.update(HOME=str(home), GIT_CONFIG_NOSYSTEM="1", GIT_CONFIG_GLOBAL=os.devnull, + GIT_AUTHOR_NAME="T210 estate", GIT_AUTHOR_EMAIL="t210@example.invalid", + GIT_COMMITTER_NAME="T210 estate", GIT_COMMITTER_EMAIL="t210@example.invalid", + LC_ALL="C") + return env + + +class Estate: + """A bare origin and the lane's checkout at C: SEED (or `files`) committed + and pushed to `main`. `register snapshot --checkout` reads + `lanes/repos.tsv` and `lanes/log/README.md` from its `origin/main`.""" + + def __init__(self, root: Path, files: dict = None): + self.root = root + self.home = root / "home" + self.home.mkdir(parents=True, exist_ok=True) + self.env = git_env(self.home) + self.origin = root / "origin.git" + self.checkout = root / "checkout" + git(root, "init", "-q", "--bare", "-b", "main", str(self.origin), env=self.env) + git(root, "clone", "-q", str(self.origin), str(self.checkout), env=self.env) + self.files = dict(files if files is not None else SEED) + for path, text in self.files.items(): + target = self.checkout / path + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(text.encode("utf-8")) + git(self.checkout, "add", "-A", env=self.env) + git(self.checkout, "commit", "-q", "-m", "C: the fixture register", env=self.env) + git(self.checkout, "push", "-q", "origin", "main", env=self.env) + self.c = git(self.checkout, "rev-parse", "HEAD", env=self.env).strip() + self.lanes_tree = git(self.checkout, "rev-parse", f"{self.c}:lanes", env=self.env).strip() + + def render_set(self) -> dict: + """C's render set, {path: bytes}.""" + return {p: t.encode("utf-8") for p, t in self.files.items() if RENDER_SET.match(p)} + + def state(self) -> tuple: + """What a write through the storage layer never changes in the + checkout: HEAD, `status --porcelain=v1 -uall`, the index's digest and + `origin/main`.""" + index = self.checkout / ".git" / "index" + return (git(self.checkout, "rev-parse", "HEAD", env=self.env), + git(self.checkout, "status", "--porcelain=v1", "-uall", env=self.env), + hashlib.sha256(index.read_bytes()).hexdigest() if index.exists() else "-", + git(self.checkout, "rev-parse", "origin/main", env=self.env)) + + +# ------------------------------------------------------------------ the SQL side +def psql(db, script: str, role: str = None) -> subprocess.CompletedProcess: + """One `psql` as the fixture's superuser, as `role` where one is named, + with the commit call's settings, so a refusal's first stderr line is + `ERROR: <SQLSTATE>: <message>`.""" + head = "\\set VERBOSITY verbose\n\\set SHOW_CONTEXT never\nSET client_encoding = 'UTF8';\n" + if role: + head += f"SET ROLE {role};\n" + return subprocess.run([db.psql_bin, "-X", "-q", "-A", "-t", "-v", "ON_ERROR_STOP=1"], + input=head + script, capture_output=True, encoding="utf-8", + errors="replace", env=db.env(appname="t210"), timeout=120, check=False) + + +def sql(db, script: str, role: str = None) -> str: + proc = psql(db, script, role) + assert proc.returncode == 0, (f"psql{' as ' + role if role else ''} exited " + f"{proc.returncode}: {proc.stderr.strip()}\n{script}") + return proc.stdout.strip() + + +def rows(db, query: str) -> list: + """`query`'s rows as JSON objects, read in the register's schema.""" + out = sql(db, f"SET search_path TO {SCHEMA};\n" + f"SELECT coalesce(jsonb_agg(q), '[]'::jsonb) FROM ({query}) q;") + return json.loads(out.splitlines()[-1]) + + +def head(db) -> int: + return rows(db, "SELECT seq FROM register_head")[0]["seq"] + + +def db_clock(db) -> int: + """The database's clock, floored to whole seconds, as epoch seconds.""" + return rows(db, "SELECT floor(extract(epoch FROM clock_timestamp()))::bigint AS s")[0]["s"] + + +def full_render(db) -> dict: + """The full render from SQL: `render_file` (lane 1's T107) of every path + in `files`, {path: bytes}.""" + return {r["path"]: base64.b64decode(r["b64"]) for r in rows( + db, "SELECT path, encode(render_file(path), 'base64') AS b64 FROM files ORDER BY path")} + + +def _lines(data: bytes) -> list: + text = data.decode("utf-8") + assert text.endswith("\n"), "every fixture file ends with a newline" + return text[:-1].split("\n") + + +def _entry(kind: str, verb: str, journal: dict = None, **parts) -> dict: + body = {"kind": kind, "verb": verb, "lane": OPERATOR, "workstation": WS, "author": AUTHOR, + "message": f"t210: {kind}"} + body.update(journal or {}) + return {"journal": body, "not_after": "2100-01-01T00:00:00Z", **parts} + + +def _creates(files: dict) -> tuple: + """Each of `files` ({path: bytes}) created, then its lines appended, and + each path's digest as it renders: the edits and the `files` rows.""" + edits, ordinal = [], 0 + for path in sorted(files): + ordinal += 1 + edits.append({"ord": ordinal, "op": "create", "path": path}) + for text in _lines(files[path]): + ordinal += 1 + edits.append({"ord": ordinal, "op": "append", "path": path, "new_text": text}) + return edits, [{"path": p, "present": True, "sha256": hashlib.sha256(files[p]).hexdigest(), + "final_newline": True} for p in sorted(files)] + + +def _commit_call(db, base: int, body: dict) -> int: + """The commit call as the writer sends it, as `lanes_register_writer` + (section 1.3's step 3; AT-LR006's fixture), and the seq it committed.""" + gen = rows(db, "SELECT generation FROM register_switch")[0]["generation"] + version = rows(db, "SELECT version FROM schema_version")[0]["version"] + literal = json.dumps(body, ensure_ascii=True).replace("'", "''") + out = sql(db, f"BEGIN ISOLATION LEVEL SERIALIZABLE;\n" + f"SELECT {SCHEMA}.commit_write({base}, '{uuid.uuid4()}'::uuid, {version}, " + f"'{gen}'::uuid, '{literal}'::jsonb);\nCOMMIT;", WRITER) + return int(out.splitlines()[-1]) + + +def import_to_primary(db, estate: Estate, marker_on_origin: bool = False) -> int: + """AT-LR006's route (TP:4610-4615) over C: an `import` entry of C's render + set, a `cutover` entry, then `record_marker`, by the documented functions + as `lanes_register_writer`. Returns the import's seq. + + `record_marker` records a made-up sha, `MARKER_COMMIT`, and origin stays + at C, for every estate but part G's: only part G's `PrimaryWrites` sets + `marker_on_origin` (T270's line, tasks:2477; lane 2, #165 6866688575; + lane 3, #165 6866808028). There the cutover's marker commit is put on + origin's `main` before `record_marker`, which records it by its sha + (`_marker_commit_on_origin`). It cannot come after: `record_marker` runs + once a cutover, and refuses LR002 once the marker is `present`.""" + edits, files = _creates(estate.render_set()) + imported = _commit_call(db, head(db), _entry( + "import", "import", {"git_commit": estate.c, "git_tree": estate.lanes_tree}, + edits=edits, files=files)) + store = "".join(f"{line}\n" for line in ( + "store=primary", "database=t210", f"import={estate.c}", + f"lanes-tree={estate.lanes_tree}", f"utc={STORE_UTC}")).encode("utf-8") + edits, files = _creates({STORE_PATH: store}) + cut = _commit_call(db, imported, _entry("cutover", "cutover", edits=edits, files=files)) + marker_sha = MARKER_COMMIT + if marker_on_origin: + rendered = rows(db, f"SELECT encode(render_file('{STORE_PATH}'), 'base64') AS b64") + assert base64.b64decode(rendered[0]["b64"]) == store, ( + f"SQL renders {STORE_PATH} otherwise than the cutover entry's bytes") + marker_sha = _marker_commit_on_origin(estate, store, cut) + version = rows(db, "SELECT version FROM schema_version")[0]["version"] + marker = sql(db, f"SELECT {SCHEMA}.record_marker({version}, {cut}, '{marker_sha}', " + f"'{WS}');", WRITER) + assert marker.splitlines()[-1] == "present", f"record_marker answered {marker!r}" + assert rows(db, "SELECT mode, marker_state FROM register_switch") == \ + [{"mode": "primary", "marker_state": "present"}] + if marker_on_origin: + assert rows(db, "SELECT marker_commit FROM register_switch") == \ + [{"marker_commit": marker_sha}], "record_marker did not record the marker commit" + return imported + + +def _marker_commit_on_origin(estate: Estate, store: bytes, cut: int) -> str: + """The cutover's marker commit, put on the bare origin's `main` as a + cutover's own push puts it (Y:2812-2814), and its sha: C's tree plus + `STORE_PATH` holding `store`, the cutover entry's bytes, on parent C, with + `Register-Seq: <cut>` alone in its message's last paragraph. It is made in + the origin through an index of its own, as RG's `commit_in_origin` makes + one (`fdab9267:tests/test_sql_register_renderer_git.py:573-586`), and + `main` moves to it from C, so no clone's refs move; the lane checkouts + that `PrimaryWrites` clones after this are at it.""" + git_dir = f"--git-dir={estate.origin}" + env = dict(estate.env, GIT_INDEX_FILE=str(estate.root / "marker.index")) + blob_file = estate.root / "marker-STORE" + blob_file.write_bytes(store) + git(estate.root, git_dir, "read-tree", estate.c, env=env) + blob = git(estate.root, git_dir, "hash-object", "-w", str(blob_file), env=env).strip() + git(estate.root, git_dir, "update-index", "--add", "--cacheinfo", + f"100644,{blob},{STORE_PATH}", env=env) + tree = git(estate.root, git_dir, "write-tree", env=env).strip() + commit = git(estate.root, git_dir, "commit-tree", tree, "-p", estate.c, + "-m", "t270: the cutover, by AT-LR006's route", + "-m", f"Register-Seq: {cut}", env=estate.env).strip() + git(estate.root, git_dir, "update-ref", "refs/heads/main", commit, estate.c, + env=estate.env) + trailer = git(estate.root, git_dir, "log", "-1", + "--format=%(trailers:key=Register-Seq,valueonly)", commit, + env=estate.env).strip() + assert trailer == str(cut), f"the marker commit's Register-Seq reads {trailer!r}, not {cut}" + return commit + + +# ------------------------------------------------------------------ lanes-index +def require_the_constant() -> None: + """The flipped copy needs Q6(c)'s constant (lane 1's T105, L1-A4): an + assertion, so a case without it fails by saying so.""" + assert len(RENDER_GIT_HALF_LINE.findall(LANES_INDEX.read_bytes())) == 1, ( + f"{LANES_INDEX} holds no single `RENDER_GIT_HALF = ...` line, Q6(c)'s build constant " + f"(L1-A4, lane 1's T105), so no copy can be flipped to load mode=primary") + + +def flipped(tmp_path: Path, name: str = "bin") -> Path: + """T203's flipped copy, `RENDER_GIT_HALF = True`, so `mode=primary` loads, + with `lanes-edit.sh` beside it (the copy rule, CLI4.5 section 6).""" + require_the_constant() + copy = flipped_copy(LANES_INDEX, tmp_path / name, True) + shutil.copy2(str(LANES_EDIT), str(copy.parent / "lanes-edit.sh")) + return copy + + +def ensure_logins(db) -> None: + """The writer's and the reader's login, once per cluster (roles are + cluster-wide), members of their groups, with no password.""" + for login, group in ((LOGIN_WRITER, WRITER), (LOGIN_READER, READER)): + sql(db, f"DO $l$ BEGIN CREATE ROLE {login} LOGIN IN ROLE {group}; " + f"EXCEPTION WHEN duplicate_object THEN NULL; END $l$;") + + +def primary_config(path: Path, register_url: str, reader_url: str, + passfile: Path | None = None) -> Path: + """A 0600 `lanes-index.conf` with `mode=primary` and the register's two + URLs (contract section 2.5), outside every work tree.""" + lines = ["mode=primary", f"register_url={register_url}", f"reader_url={reader_url}"] + if passfile is not None: + lines += [f"register_passfile={passfile}", f"reader_passfile={passfile}"] + path.write_text("\n".join(lines) + "\n", encoding="utf-8") + path.chmod(0o600) + return path + + +def index_env(tmp_path: Path, conf: Path, home: Path, **extra) -> dict: + """The environment `lanes-index` runs in: no inherited `PG*`, `LANES_*`, + `GIT_*` or `TMUX*` (#160's run-wide `LANES_INDEX=off` among them), this + case's configuration, state directory and git identity.""" + env = {k: v for k, v in os.environ.items() + if not k.startswith(("PG", "LANES_", "GIT_", "TMUX"))} + env.update(git_env(home)) + env.update(LANES_INDEX_CONFIG=str(conf), XDG_STATE_HOME=str(tmp_path / "state"), LC_ALL="C") + env.update(extra) + return env + + +def run_index(copy: Path, args, env: dict, cwd: Path = None) -> subprocess.CompletedProcess: + return subprocess.run([sys.executable, str(copy), *[str(a) for a in args]], + capture_output=True, encoding="utf-8", errors="replace", env=env, + timeout=120, cwd=str(cwd) if cwd else None, check=False, + stdin=subprocess.DEVNULL) + + +def keys(stdout: str) -> dict: + """A `key=value` output's keys, each its first value (section 3.2).""" + found = {} + for line in stdout.splitlines(): + key, sep, value = line.partition("=") + if sep and key not in found: + found[key] = value + return found + + +def utc_of(epoch: int) -> str: + return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(epoch)) + + +def epoch_of(utc: str) -> int: + import calendar + return calendar.timegm(time.strptime(utc, "%Y-%m-%dT%H:%M:%SZ")) + + +# ------------------------------------------------------------------ the fake writer +def _edit_managed_projection(tree: Path, utc: str) -> str: + """S4's projection: repoA-1's row's state cell carries a managed-owner + marker, in the form `lanes-edit.sh`'s ported reader parses (3c26041's + T019): `<STATE> . <utc> . managed-owner mode=... daemon=... generation=... + bound-lane=<lane>`. Returns the new line.""" + path = tree / "lanes" / "LANES.md" + text = path.read_text(encoding="utf-8") + old = _row("repoA-1", SID_A1, f"LIVE {DOT} 2026-10-01T01:00:00Z {DOT} working") + new = _row("repoA-1", SID_A1, f"LIVE {DOT} {utc} {DOT} managed-owner mode=managed " + f"daemon=t210d generation=7 bound-lane=repoA-1") + assert text.count(old + "\n") == 1, "the fixture row is in the scratch tree once" + path.write_text(text.replace(old + "\n", new + "\n"), encoding="utf-8") + return new + + +def _edit_log_noted(tree: Path, utc: str) -> str: + """`log NOTED`'s line, appended to repoA-1's log.""" + line = (f"NOTED {EM} lane repoA-1, session {SID_A1}@{WS}, {utc}, lane:repoA-1 {EM} " + f"test 1's part N") + path = tree / "lanes" / "log" / "repoA-1.md" + path.write_bytes(path.read_bytes() + line.encode("utf-8") + b"\n") + return line + + +def _edit_append_hold(tree: Path, utc: str) -> str: + """`append-line`'s take: a `HOLD` on a repository nobody holds.""" + line = (f"HOLD {EM} lane repoA-2 ({WS}), window w, {utc}: opensoft/repoB main {TIP} " + f"for a check") + path = tree / "lanes" / "LANES.md" + path.write_bytes(path.read_bytes() + line.encode("utf-8") + b"\n") + return line + + +#: The entries the fake writer drives: {id: (lane, verb, the edit, the path +#: it touches)}. The managed projection is S4's own verb (design S4: "run +#: through S1's attempt loop as the verb `managed-projection`"). +ENTRIES = { + "managed-projection": ("repoA-1", "managed-projection", _edit_managed_projection, + "lanes/LANES.md"), + "log-noted": ("repoA-1", "log", _edit_log_noted, "lanes/log/repoA-1.md"), + "append-line-hold": ("repoA-2", "append-line", _edit_append_hold, "lanes/LANES.md"), +} + + +def _canonical_rows(changes: list, images: dict) -> str: + """Section 3.2's canonical rows for every path in `changes.tsv`, sorted by + path bytewise, each LF-ended: `<path>` TAB `1` TAB `<sha256>`, or `0` and + `-` for a path the write removes.""" + out = [] + for path in sorted({c[1] for c in changes}, key=lambda p: p.encode("utf-8")): + if path in images: + out.append(f"{path}\t1\t{hashlib.sha256(images[path]).hexdigest()}\n") + else: + out.append(f"{path}\t0\t-\n") + return "".join(out) + + +def projection_entry(copy: Path, env: dict, checkout: Path, root: Path, entry: str, + message: str) -> dict: + """The storage layer's write entry, driven by a fake writer as the + projection writer will call it (design S4; contract sections 3.2 and 3.3): + `register snapshot --write-id new ... --tree <root>/attempt/tree + --checkout <checkout>`; on 0 alone, the edit, the attempt directory and + `register commit`. Returns what each call answered, the entry's code + (the snapshot's where it did not answer 0, else the commit's), the + attempt directory, the message and the line the edit wrote.""" + lane, verb, edit, _path = ENTRIES[entry] + args_sha256 = hashlib.sha256(json.dumps([lane, verb, message]).encode("utf-8")).hexdigest() + attempt = root / "attempt" + out = {"snapshot": None, "commit": None, "code": None, "attempt": attempt, + "message": message, "line": None, "fields": {}, "args_sha256": args_sha256} + # THE ATTEMPT DIRECTORY EXISTS BEFORE THE FIRST SNAPSHOT, as the seam's + # does (contract section 3.3: its digest, run nonce and attempt "are + # known before the first snapshot"); `--tree` names an empty `tree/` in it. + attempt.mkdir(parents=True, exist_ok=True) + snap = run_index(copy, ["register", "snapshot", "--write-id", "new", "--lane", lane, + "--verb", verb, "--args-sha256", args_sha256, + "--tree", attempt / "tree", "--checkout", checkout], env) + out["snapshot"] = snap + if snap.returncode != 0: + out["code"] = snap.returncode + return out + fields = keys(snap.stdout) + out["fields"] = fields + tree = attempt / "tree" + (attempt / "snapshot").write_text(snap.stdout, encoding="utf-8") + out["line"] = edit(tree, utc_of(int(fields["clock"]))) + git(tree, "add", "-A", "--", "lanes", env=env) + changes = [] + for raw in git(tree, "diff", "--cached", "--no-renames", "--raw", "--no-abbrev", "HEAD", + env=env).splitlines(): + meta, path = raw.split("\t", 1) + parts = meta.split() + changes.append((parts[4], path, parts[2], parts[3])) + assert changes, "the edit staged a change" + (attempt / "changes.tsv").write_text( + "".join(f"{s}\t{p}\t{o}\t{n}\n" for s, p, o, n in changes), encoding="utf-8") + images = {} + for status, path, _old, _new in changes: + if status in ("A", "M"): + images[path] = (tree / path).read_bytes() + target = attempt / "images" / path + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(images[path]) + (attempt / "files").write_text(_canonical_rows(changes, images), encoding="utf-8") + (attempt / "msg").write_text(message, encoding="utf-8") + (attempt / "author").write_text(AUTHOR + "\n", encoding="utf-8") + (attempt / "not_after").write_text(fields["not_after"] + "\n", encoding="utf-8") + commit = run_index(copy, ["register", "commit", "--write-id", fields["write_id"], + "--generation", fields["generation"], "--lane", lane, + "--verb", verb, "--args-sha256", args_sha256, + "--workstation", WS, attempt], env) + out["commit"] = commit + out["code"] = commit.returncode + return out + + +def render_images(copy: Path, env: dict, k: int, out_dir: Path) -> tuple: + """The pure renderer, T301: `render --images --at <k> --out <dir>` + (contract section 3.6). Returns the call and {path: bytes} of every file + it wrote under `out_dir`.""" + proc = run_index(copy, ["render", "--images", "--at", k, "--out", out_dir], env) + written = {} + if out_dir.is_dir(): + for path in sorted(out_dir.rglob("*")): + if path.is_file(): + written[path.relative_to(out_dir).as_posix()] = path.read_bytes() + return proc, written + + +def _rendered_only(files: dict) -> dict: + return {p: b for p, b in files.items() if RENDER_SET.match(p)} + + +class PrimaryRegister: + """C imported and brought to `primary`, a flipped copy, and the + configuration that reaches the test's database as this module's logins.""" + + def __init__(self, pg, tmp_path: Path): + self.pg = pg + self.estate = Estate(tmp_path / "estate") + self.imported = import_to_primary(pg, self.estate) + ensure_logins(pg) + self.copy = flipped(tmp_path) + (tmp_path / "conf").mkdir() + conf = primary_config(tmp_path / "conf" / "lanes-index.conf", pg.url(LOGIN_WRITER), + pg.url(LOGIN_READER)) + self.env = index_env(tmp_path, conf, self.estate.home) + + +# ============================================================ part N (real engine) + +@pytest.mark.parametrize("entry", list(ENTRIES)) +def test_a_storage_layer_entry_renders_byte_identical_to_a_full_render(pg, tmp_path, entry): + """AT-1's part N: the storage layer's write entry, called as the + projection writer will call it, commits one entry; then the pure + renderer's images at that seq equal the full render from SQL, path set + and bytes, over the four paths, and it writes nothing outside them. The + journal gains exactly one entry, at the old head plus one, carrying the + write's message byte for byte and its write id, unique in the journal; + every row the entry touched reads `primary` as the mode that wrote it + last; the new line's UTC is the database's, in whole seconds, between the + clock read before the write and after it. The checkout is unchanged.""" + reg = PrimaryRegister(pg, tmp_path) + before_head = head(pg) + before_ids = {r["write_id"] for r in rows(pg, "SELECT write_id FROM journal")} + checkout_before = reg.estate.state() + message = f"lanes-edit.sh {ENTRIES[entry][1]}: test 1's part N, {entry}" + clock_before = db_clock(pg) + done = projection_entry(reg.copy, reg.env, reg.estate.checkout, tmp_path, entry, message) + clock_after = db_clock(pg) + assert done["snapshot"].returncode == 0, ( + f"register snapshot exited {done['snapshot'].returncode}: {done['snapshot'].stderr}") + assert done["code"] == 0, f"register commit exited {done['code']}: {done['commit'].stderr}" + seq = before_head + 1 + assert done["commit"].stdout == f"committed {seq}\n", done["commit"].stdout + + # THE JOURNAL: one entry, at the old head plus one, with the message and + # the write id the snapshot minted, unique in the journal. + new = rows(pg, f"SELECT seq, write_id, kind, verb, lane, message FROM journal " + f"WHERE seq > {before_head} ORDER BY seq") + lane, verb, _edit, path = ENTRIES[entry] + assert new == [{"seq": seq, "write_id": done["fields"]["write_id"], "kind": "write", + "verb": verb, "lane": lane, "message": message}], new + assert done["fields"]["write_id"] not in before_ids + assert rows(pg, f"SELECT count(*) AS n FROM journal " + f"WHERE write_id = '{done['fields']['write_id']}'") == [{"n": 1}] + + # THE ROWS: every row the entry wrote reads `primary` as its last writer's. + touched = rows(pg, f"SELECT 'doc_lines' AS t, written_mode AS m FROM doc_lines " + f"WHERE written_seq = {seq} " + f"UNION ALL SELECT 'lanes', last_mode FROM lanes WHERE last_seq = {seq} " + f"UNION ALL SELECT 'log_lines', mode FROM log_lines WHERE seq = {seq} " + f"UNION ALL SELECT 'register_lines', mode FROM register_lines " + f"WHERE seq = {seq} " + f"UNION ALL SELECT 'object_holds', mode FROM object_holds WHERE seq = {seq}") + assert touched and {r["m"] for r in touched} == {"primary"}, touched + + # THE UTC: the database's clock in whole seconds (S6, D13). + utc = utc_of(int(done["fields"]["clock"])) + assert UTC_RE.match(utc) and utc in done["line"] + assert clock_before <= epoch_of(utc) <= clock_after, (clock_before, utc, clock_after) + + # THE MIRROR: the pure renderer at seq equals the full render from SQL. + proc, images = render_images(reg.copy, reg.env, seq, tmp_path / "mirror") + assert proc.returncode == 0, f"render --images exited {proc.returncode}: {proc.stderr}" + assert all(RENDER_SET.match(p) or p == STORE_PATH for p in images), ( + f"the renderer wrote outside its four paths: {sorted(images)}") + full = _rendered_only(full_render(pg)) + assert sorted(_rendered_only(images)) == sorted(full), "the path sets are equal" + for name in full: + assert _rendered_only(images)[name] == full[name], f"{name}'s bytes differ" + assert done["line"].encode("utf-8") + b"\n" in full[path] + assert images[path] == (done["attempt"] / "images" / path).read_bytes(), ( + "the image the writer sent is the one rendered") + assert reg.estate.state() == checkout_before, "the lane checkout is unchanged" + + +def _stats(samples: list) -> dict: + """Section 5.3's statistics: median and p95 by nearest rank, min-max, n.""" + ordered = sorted(samples) + rank = lambda p: ordered[max(0, -(-p * len(ordered) // 100) - 1)] # noqa: E731 + return {"median": rank(50), "p95": rank(95), "min": ordered[0], "max": ordered[-1], + "n": len(ordered)} + + +def test_the_render_of_one_entry_and_of_a_full_render_is_timed_and_recorded(pg, tmp_path): + """M6 (section 5.1): the pure renderer's time, exec to exit, cold once + and ten warm, for a full render of the fixture register (its images at + the import's seq) and for one journal entry's image (its images at the + seq of one entry the storage layer committed on top), each recorded with + section 5.3's statistics and its n in the job's log and + `$GITHUB_STEP_SUMMARY` where it is set; never asserted. The correctness + alongside: every run answers 0; the full render equals C's files byte for + byte; the one entry's render equals the full render from SQL for the + same paths, so a measurement that rendered wrongly fails, whatever its + time.""" + reg = PrimaryRegister(pg, tmp_path) + done = projection_entry(reg.copy, reg.env, reg.estate.checkout, tmp_path, "log-noted", + "lanes-edit.sh log: test 1's measured entry") + assert done["code"] == 0, (done["snapshot"].stderr, done["commit"] and done["commit"].stderr) + seq = int(done["commit"].stdout.split()[1]) + path = ENTRIES["log-noted"][3] + sql_render = _rendered_only(full_render(reg.pg)) + figures = {} + for label, k in (("full render, the fixture register", reg.imported), + ("one entry's image", seq)): + times = [] + for n in range(11): + out_dir = tmp_path / "timed" / f"{k}-{n}" + start = time.monotonic_ns() + proc, images = render_images(reg.copy, reg.env, k, out_dir) + times.append((time.monotonic_ns() - start) / 1e6) + assert proc.returncode == 0, f"render --images --at {k}: {proc.stderr}" + if k == reg.imported: + assert _rendered_only(images) == reg.estate.render_set(), ( + "the full render is C's render set, byte for byte") + else: + assert images[path] == sql_render[path], ( + "the one entry's render equals the full render from SQL") + figures[label] = (times[0], _stats(times[1:])) + lines = [] + for label, (cold, warm) in figures.items(): + lines.append(f"| M6 | fixture cluster, Unix socket | `render --images`, {label} | " + f"cold {cold:.1f} ms | median {warm['median']:.1f} ms, p95 " + f"{warm['p95']:.1f} ms, {warm['min']:.1f}-{warm['max']:.1f} ms, " + f"n={warm['n']} |") + print("\n" + "\n".join(lines)) + summary = os.environ.get("GITHUB_STEP_SUMMARY") + if summary: + with open(summary, "a", encoding="utf-8") as handle: + handle.write("\n".join(lines) + "\n") + + +# ============================================================ `sync --source register` (FP) + +def fake_psql_dir(directory: Path, answers: list = None) -> dict: + """T203's register fake, written to `directory` as `psql`, which a case + puts first on `PATH`. Since T203b it answers `psql --version` itself, + `psql (PostgreSQL) 16.4` (`PSQL_VERSION_LINE`), the probe lane 1's T106 + makes once per process on a register path, and logs that probe as its + own kind (`"kind": "version"`, no `call`). Returns the variables the fake + reads: its log, and its answers where `answers` teaches any (T203's + docstring).""" + directory.mkdir(parents=True, exist_ok=True) + (directory / "psql").write_text(REGISTER_FAKE_PSQL, encoding="utf-8") + (directory / "psql").chmod(0o755) + env = {"FAKE_PSQL_LOG": str(directory / "psql.log")} + if answers is not None: + (directory / "answers.json").write_text(json.dumps(answers), encoding="utf-8") + env["FAKE_PSQL_ANSWERS"] = str(directory / "answers.json") + return env + + +def fake_calls(fake: dict) -> list: + """The fake's log, one object per call that carried a request: the + entries with no `kind`. A `psql --version` probe (T203b's `"kind": + "version"`) sends nothing, so it is left out, as T210's own wrapper + left it out before T203b.""" + log = Path(fake["FAKE_PSQL_LOG"]) + if not log.exists(): + return [] + entries = [json.loads(line) for line in log.read_text(encoding="utf-8").splitlines() if line] + return [e for e in entries if e.get("kind") != "version"] + + +#: What `_masked_path` keeps off a case's `PATH`: an installed `lanes-index`, +#: a real `psql`, and every `pg_` client that `postgresql-16` puts beside it. +_MASKED_NAMES = ("psql", "lanes-index") +_MASKED_PREFIX = "pg_" +#: `_masked_path`'s mirrors, built once per process: each masked directory's +#: real path, to its mirror under the one `l2-pathmask-` directory. +_PATH_MIRRORS: dict = {} +_PATH_MIRROR_ROOT: list = [] + + +def _masked_path() -> str: + """The caller's PATH with every directory kept, in its place, and each one + that holds a masked name swapped for a mirror of it without them. A real + `psql` or `pg_` client, or an installed `lanes-index`, is never what a + case runs; but dropping the directory that holds one drops what sits + beside it. On a GitHub runner, `postgresql-16`'s client package puts + `psql` in `/usr/bin` together with `git` and `bash`, and `/bin` links + there, so a filter that drops the directory leaves a case no `git` or + `bash` to run. The mirror is a directory of symlinks, one per entry, each + to the original entry's absolute path, the masked names left out. It is + built once per process, keyed by the directory's real path, under one + temporary directory that an `atexit` handler removes. A directory that + holds no masked name passes through unchanged, so where no `PATH` + directory holds one, the PATH is what the old filter gave; empty entries + are left out, as that filter left them.""" + kept = [] + for part in os.environ.get("PATH", "").split(os.pathsep): + if not part: + continue + real = os.path.realpath(part) + if real not in _PATH_MIRRORS: + try: + names = os.listdir(real) + except OSError: + names = [] + if not any(_is_masked(name) for name in names): + kept.append(part) + continue + _PATH_MIRRORS[real] = _path_mirror(real, names) + kept.append(_PATH_MIRRORS[real]) + return os.pathsep.join(kept) + + +def _is_masked(name: str) -> bool: + return name in _MASKED_NAMES or name.startswith(_MASKED_PREFIX) + + +def _path_mirror(real: str, names: list) -> str: + """`real`'s mirror: a new directory under the one `l2-pathmask-` + directory, holding a symlink to each entry of `real` but the masked.""" + if not _PATH_MIRROR_ROOT: + root = tempfile.mkdtemp(prefix="l2-pathmask-") + atexit.register(shutil.rmtree, root, ignore_errors=True) + _PATH_MIRROR_ROOT.append(root) + mirror = tempfile.mkdtemp(prefix=(os.path.basename(real) or "root") + "-", + dir=_PATH_MIRROR_ROOT[0]) + for name in names: + if not _is_masked(name): + os.symlink(os.path.join(real, name), os.path.join(mirror, name)) + return mirror + + +def workspace(root: Path, fakebin: Path) -> tuple: + """A files-mode workspace on a bare origin, at C (SEED), whose + `workspace.yaml` names that origin as its `repository:` and the checkout + as its `path:`, as `test_sql_register_import.py`'s `Workspace` names + them, with a fake `tmux` and `fakebin` first on `PATH`, in the + environment that `Workspace` sets. Returns (the estate, the environment, + the register source `sync --source` must name: `register:` and the + repository as `lanes-index`'s `source_of` normalizes it, its `.git` + dropped).""" + estate = Estate(root) + agents = estate.home / ".agents" + agents.mkdir(parents=True, exist_ok=True) + (agents / "workspace.yaml").write_text( + f"repository: {estate.origin}\npath: {estate.checkout}\n", encoding="utf-8") + source = "register:" + re.sub(r"\.git$", "", str(estate.origin)) + fakebin.mkdir(parents=True, exist_ok=True) + (fakebin / "tmux").write_text("#!/bin/sh\nexit 1\n", encoding="utf-8") + (fakebin / "tmux").chmod(0o755) + for d in ("state", "config", "tmp"): + (root / d).mkdir(parents=True, exist_ok=True) + env = dict(estate.env) + env.update(AGENT_PROTOCOL_ROOT=str(agents), TMPDIR=str(root / "tmp"), + XDG_STATE_HOME=str(root / "state"), XDG_CONFIG_HOME=str(root / "config"), + CLAUDE_CONFIG_DIR=str(estate.home / ".claude"), LANES_WORKSTATION=WS, + LANES_HOST="eagle", LANES_OS="linux", LANES_CONTAINER="none", + LANES_IN_CONTAINER="0", LANES_NO_GITHUB="1", LANES_REPO=str(estate.checkout), + PATH=str(fakebin) + os.pathsep + _masked_path()) + return estate, env, source + + +def test_sync_source_register_does_nothing_on_primary_and_says_so(tmp_path): + """`lanes-index sync --source register:<owner/repo>` on a `mode=primary` + workstation, this workstation's own source, makes no `psql` call, writes + nothing (the checkout's HEAD, status, index and `origin/main` as they + were, and nothing in `lanes-index`'s state directory but its sync lock: + no index store, no status record), exits 0, and its output says it does + nothing on primary (AT-1's + FP case; lane 1's T117, "`cmd_sync` with a `register:<owner/repo>` + source does nothing on primary, and says so"; the delta's "The post-write + nudge does not re-index the mirror into its own source"). #160's + run-wide `LANES_INDEX=off` is unset, or it would say nothing of + primary.""" + fakebin = tmp_path / "fakebin" + fake = fake_psql_dir(fakebin) + estate, env, source = workspace(tmp_path / "ws", fakebin) + copy = flipped(tmp_path) + sock = tmp_path / "sock" + sock.mkdir() + passfile = tmp_path / "conf" / "pgpass" + passfile.parent.mkdir() + passfile.write_text("", encoding="utf-8") + passfile.chmod(0o600) + host = quote(sock.as_posix(), safe="") + conf = primary_config(tmp_path / "conf" / "lanes-index.conf", + f"postgresql://lanes_w_t210@{host}:5432/lanes_t210", + f"postgresql://lanes_r_t210@{host}:5432/lanes_t210", passfile) + env.update(fake, LANES_INDEX_CONFIG=str(conf)) + env.pop("LANES_INDEX", None) + state_root = Path(env["XDG_STATE_HOME"]) + before, state_before = estate.state(), _files_under(state_root) + proc = run_index(copy, ["sync", "--source", source], env, cwd=estate.checkout) + said = proc.stdout + proc.stderr + assert proc.returncode == 0, f"sync exited {proc.returncode}: {said}" + assert fake_calls(fake) == [], f"sync made a psql call on primary: {fake_calls(fake)}" + assert "primary" in said, f"sync's output does not say it does nothing on primary: {said!r}" + assert estate.state() == before, "sync wrote to the checkout" + state_after = _files_under(state_root) + written = sorted(p for p, digest in state_after.items() if state_before.get(p) != digest) + assert all(SYNC_LOCK_FILES.match(p) for p in written), ( + f"sync wrote under {state_root} on primary, beyond its lock: {written}") + + +#: What a sync may leave in `lanes-index`'s state directory, +#: `$XDG_STATE_HOME/openRepoTools/`, when it does nothing: its one-at-a-time +#: lock and the lock's rerun marks (`SyncLock`, 14(d) and #161). An index +#: store (`lanes-index.sqlite`) or a status record is a write. +SYNC_LOCK_FILES = re.compile(r"^openRepoTools/lanes-index\.(lock|rerun(-[a-z]+)?)$") + + +def _files_under(root: Path) -> dict: + """Every file under `root`, {relative path: sha256}.""" + if not root.is_dir(): + return {} + return {p.relative_to(root).as_posix(): hashlib.sha256(p.read_bytes()).hexdigest() + for p in sorted(root.rglob("*")) if p.is_file()} + + +# ============================================================ the image cache (T302's API) +# +# THE IMAGE CACHE'S OWN TEST (lane 2's T210e; B10 tasks:972's `PENDING-L2`; +# F10-OWED items 26 and 34): lane 1's T302 adds the cache to `lanes-index`, +# under its state directory, `register-images/` (design Y:4963; PC-1), with +# the five functions and two constants of lane 3's ruling (#165 6746004829, +# extended by 6755051914) and lane 1's formats (#165 6755106847, "The +# formats, for lane 2's test"), as its fix round left them (6755799745; lane +# 3's delta check, 6755954683). T302's first run selects these cases with +# `-k 'sql_register_render and image_cache'`. They need no engine: each loads +# `lanes-index` as a module, with `XDG_STATE_HOME` under the case's own +# directory, and calls the API in process. They fail until T302 lands, by the +# assertion `image_cache_module` makes; the last one fails until lane 1's +# follow-up commit too (6755954683, doubts 1 and 2). + +#: The API lane 3's ruling fixes: five functions and two constants. +IMAGE_CACHE_API = ("image_cache_get", "image_cache_put", "image_cache_head", + "image_cache_record", "image_cache_collect") +IMAGE_CACHE_CONSTANTS = {"IMAGE_CACHE_KEEP": 3, "IMAGE_CACHE_FLOOR_SECONDS": 600} +#: A temp file as lane 1's format names it: `.<name>.tmp-<pid>-<8 hex>`. +IMAGE_CACHE_TEMP = re.compile(r"^\..+\.tmp-[0-9]+-[0-9a-f]{8}$") +#: Older than collection's floor, with room: an hour before now. +IMAGE_CACHE_OLD = 3600 + + +class ImageCache: + """`lanes-index` loaded as a module whose state directory is `state` + (`XDG_STATE_HOME`), with the cache's paths.""" + + def __init__(self, module, state: Path): + self.m = module + self.root = state / "openRepoTools" / "register-images" + self.objects = self.root / "objects" + self.seq = self.root / "seq" + self.head_file = self.root / "head" + self.lock = self.root / "lock" + + def object(self, digest: str) -> Path: + return self.objects / digest + + def age(self, path: Path, seconds: int = IMAGE_CACHE_OLD) -> None: + """Sets `path`'s mtime `seconds` before now, past the floor.""" + then = time.time() - seconds + os.utime(path, (then, then), follow_symlinks=False) + + def temps(self) -> list: + """Every temp file of lane 1's form left anywhere in the cache.""" + if not self.root.is_dir(): + return [] + return sorted(p.relative_to(self.root).as_posix() for p in self.root.rglob(".*") + if IMAGE_CACHE_TEMP.match(p.name)) + + +def image_cache_module(tmp_path: Path, monkeypatch) -> ImageCache: + """`lanes-index` as a module, under its own name so nothing else in the + run shares it, with `XDG_STATE_HOME` set to `<tmp_path>/state`, where + `state_dir()` puts `openRepoTools/register-images/`. Asserts the API is + there: lane 1's T302, B10 tasks:972 (the case's red until it lands).""" + from importlib.machinery import SourceFileLoader + import importlib.util + loader = SourceFileLoader(f"lanes_index_image_cache_{uuid.uuid4().hex}", str(LANES_INDEX)) + spec = importlib.util.spec_from_loader(loader.name, loader) + module = importlib.util.module_from_spec(spec) + loader.exec_module(module) + missing = [name for name in (*IMAGE_CACHE_API, *IMAGE_CACHE_CONSTANTS) + if not hasattr(module, name)] + assert not missing, ( + f"{LANES_INDEX} has no image cache API, {missing} missing: lane 1's T302 (B10 " + f"tasks:972; #165 6755106847) has not landed") + state = tmp_path / "state" + monkeypatch.setenv("XDG_STATE_HOME", str(state)) + return ImageCache(module, state) + + +def _mode(path: Path) -> int: + return stat.S_IMODE(os.lstat(path).st_mode) + + +def _digest(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def test_the_image_cache_puts_and_gets_an_object_only_by_its_digest(tmp_path, monkeypatch): + """`image_cache_put(data)` returns `data`'s sha256 as 64 lowercase hex and + writes `objects/<digest>` under `$XDG_STATE_HOME/openRepoTools/ + register-images/`, the file 0600 and each directory 0700, by a temp file + and a rename that leaves no temp file; a `bytearray` is taken as bytes, + and anything else raises `TypeError` before the cache is touched, the + one error that escapes. `image_cache_get(digest)` returns the bytes only + when they hash to `digest`: a missing object, a digest that is not 64 + lowercase hex, a name outside `objects/`, an object whose bytes changed + and a symlink at the object's name are each a miss (None), and `put` + replaces the bad object and leaves a link's target alone. A second `put` + of an object already whole rewrites nothing and sets its mtime to now, + so the floor keeps it (lane 1's readings 1 and 2; fix round NIT-3 and + NIT-4).""" + cache = image_cache_module(tmp_path, monkeypatch) + m = cache.m + with pytest.raises(TypeError): + m.image_cache_put("lanes/LANES.md as text, not bytes") + assert not (tmp_path / "state").exists(), "put touched the cache before its TypeError" + + data = f"# LANES.md {EM} the image cache's own test\n".encode("utf-8") + digest = m.image_cache_put(data) + assert digest == _digest(data) and re.fullmatch(r"[0-9a-f]{64}", digest), digest + assert cache.object(digest).read_bytes() == data + assert _mode(cache.object(digest)) == 0o600, oct(_mode(cache.object(digest))) + for directory in (tmp_path / "state" / "openRepoTools", cache.root, cache.objects): + assert _mode(directory) == 0o700, f"{directory} is {oct(_mode(directory))}, not 0700" + assert m.image_cache_get(digest) == data + assert m.image_cache_put(bytearray(data)) == digest + assert cache.temps() == [], f"a temp file was left: {cache.temps()}" + + # MISSES: an object that is not there, and digests out of form. + other = _digest(b"never put\n") + assert m.image_cache_get(other) is None + for bad in (digest.upper(), digest[:63], digest + "0", "", "../head", None, 7): + assert m.image_cache_get(bad) is None, f"get({bad!r}) was not a miss" + + # A WHOLE OBJECT IS NOT WRITTEN AGAIN; ITS MTIME COMES TO NOW. + inode = os.lstat(cache.object(digest)).st_ino + cache.age(cache.object(digest)) + assert m.image_cache_put(data) == digest + assert os.lstat(cache.object(digest)).st_ino == inode, "a whole object was rewritten" + assert time.time() - os.lstat(cache.object(digest)).st_mtime < 60, ( + "put of a whole object left its old mtime, so the floor would not keep it") + + # AN OBJECT WHOSE BYTES CHANGED IS A MISS, AND PUT REPLACES IT. + cache.object(digest).write_bytes(b"torn") + assert m.image_cache_get(digest) is None, "get returned bytes that do not hash to the name" + assert m.image_cache_put(data) == digest + assert m.image_cache_get(digest) == data and cache.object(digest).read_bytes() == data + + # A SYMLINK AT THE OBJECT'S NAME IS A MISS, AND PUT REPLACES IT (NIT-4). + outside = tmp_path / "outside" + outside.write_bytes(data) + cache.object(digest).unlink() + cache.object(digest).symlink_to(outside) + assert m.image_cache_get(digest) is None, "get followed a symlink at an object's name" + assert m.image_cache_put(data) == digest + assert not cache.object(digest).is_symlink() and cache.object(digest).read_bytes() == data + assert outside.read_bytes() == data, "put changed a link's target" + assert cache.temps() == [], f"a temp file was left: {cache.temps()}" + + +def test_the_image_cache_records_manifests_and_a_head_that_moves_only_forward(tmp_path, + monkeypatch): + """`image_cache_record(n, manifest)` writes `seq/<n>`, one `<path>` TAB + `<digest>` line per path, each LF-ended, sorted by path bytewise, an + empty manifest an empty file, 0600; a second record of one `n` merges + into the first, a path in both taking the second's digest. `head` is + `<n>` and an LF, read with or without the LF and never with a leading + zero, and moves only forward; a missing `head`, or one with no seq, is + written as the larger of `n` and the highest seq `seq/` lists (NIT-2). + `image_cache_head()` answers (seq, manifest), or None. A record whose `n` + is not a whole number from 0 to 2**63 - 1, or whose manifest is not a + dict of paths with no control character to digests, is skipped, and no + call raises (lane 1's readings 6 and 7).""" + cache = image_cache_module(tmp_path, monkeypatch) + m = cache.m + assert m.image_cache_head() is None + accented = "lanes/log/repo" + chr(0x00E9) + "-1.md" + d1, d2, d3 = (_digest(f"image {k}\n".encode("ascii")) for k in (1, 2, 3)) + m.image_cache_record(5, {"lanes/log/repoA-1.md": d2, accented: d3, "lanes/LANES.md": d1}) + expected = [("lanes/LANES.md", d1), ("lanes/log/repoA-1.md", d2), (accented, d3)] + assert (cache.seq / "5").read_bytes() == "".join( + f"{p}\t{d}\n" for p, d in expected).encode("utf-8"), "the manifest's form or order" + assert cache.head_file.read_bytes() == b"5\n" + assert _mode(cache.seq / "5") == 0o600 and _mode(cache.head_file) == 0o600 + assert _mode(cache.seq) == 0o700 + assert m.image_cache_head() == (5, dict(expected)) + + # THE HEAD NEVER MOVES BACK. + m.image_cache_record(3, {"lanes/LANES.md": d2}) + assert (cache.seq / "3").read_bytes() == f"lanes/LANES.md\t{d2}\n".encode("ascii") + assert cache.head_file.read_bytes() == b"5\n", "a lower record moved the head back" + + # A SECOND RECORD OF ONE SEQ MERGES, ITS OWN DIGEST WINNING. + m.image_cache_record(5, {"lanes/LANES.md": d3, "lanes/aliases.tsv": d1}) + assert m.image_cache_head() == (5, {"lanes/LANES.md": d3, "lanes/aliases.tsv": d1, + "lanes/log/repoA-1.md": d2, accented: d3}) + + # AN EMPTY MANIFEST IS AN EMPTY FILE; THE HEAD READS WITH OR WITHOUT ITS LF. + m.image_cache_record(7, {}) + assert (cache.seq / "7").read_bytes() == b"" and cache.head_file.read_bytes() == b"7\n" + assert m.image_cache_head() == (7, {}) + cache.head_file.write_bytes(b"7") + assert m.image_cache_head() == (7, {}), "a head with no LF is not read" + for bad in (b"07\n", b"7\n\n", b" 7\n", b"seven\n", b""): + cache.head_file.write_bytes(bad) + assert m.image_cache_head() is None, f"a head of {bad!r} was read" + + # A HEAD WITH NO SEQ, OR NONE, IS WRITTEN AS THE LARGER OF n AND seq/'s HIGHEST. + cache.head_file.write_bytes(b"seven\n") + m.image_cache_record(4, {"lanes/LANES.md": d1}) + assert cache.head_file.read_bytes() == b"7\n", "a junk head was not repaired to 7" + cache.head_file.unlink() + m.image_cache_record(2, {"lanes/LANES.md": d1}) + assert cache.head_file.read_bytes() == b"7\n", "a missing head moved back to 2" + + # RECORDS OUT OF FORM ARE SKIPPED, AND RAISE NOTHING. + before = sorted(p.name for p in cache.seq.iterdir()) + for n, manifest in ((-1, {}), (True, {}), (2 ** 63, {}), ("9", {}), (9.0, {}), + (9, {"lanes/LANES.md": d1.upper()}), (9, {"lanes/a\tb.md": d1}), + (9, {"lanes/a\nb.md": d1}), (9, {"lanes/a" + chr(0) + ".md": d1}), + (9, {"": d1}), (9, [("lanes/LANES.md", d1)]), (9, None)): + m.image_cache_record(n, manifest) + assert sorted(p.name for p in cache.seq.iterdir()) == before, ( + "a record out of form wrote a manifest") + assert cache.head_file.read_bytes() == b"7\n" + assert m.image_cache_record(2 ** 63 - 1, {}) is None + assert cache.head_file.read_bytes() == str(2 ** 63 - 1).encode("ascii") + b"\n" + assert cache.temps() == [], f"a temp file was left: {cache.temps()}" + + +def test_the_image_cache_collects_all_but_the_last_three_manifests_past_the_floor( + tmp_path, monkeypatch): + """Collection keeps the manifests of the `IMAGE_CACHE_KEEP` = 3 highest + seqs and removes every older one; it removes an object named in none of + them only when its mtime is over `IMAGE_CACHE_FLOOR_SECONDS` = 600 old, + so an old object a kept manifest names, and a young one none names, both + stay. It removes a temp file of the form `.<name>.tmp-<pid>-<8 hex>` + only past the same floor, and no other name. Where one of the kept + manifests is out of form, it removes no object (lane 1's readings 3, 4 + and 5). `image_cache_record` collects too, under the same lock.""" + cache = image_cache_module(tmp_path, monkeypatch) + m = cache.m + for name, value in IMAGE_CACHE_CONSTANTS.items(): + assert getattr(m, name) == value, f"{name} is {getattr(m, name)!r}, not {value}" + data = [f"image {k}\n".encode("ascii") for k in range(1, 8)] + o = [m.image_cache_put(d) for d in data] + for k in range(1, 6): + m.image_cache_record(k, {"lanes/LANES.md": o[k - 1]}) + assert sorted(p.name for p in cache.seq.iterdir()) == ["3", "4", "5"], ( + "record kept a manifest older than the last three") + + for k in (0, 1, 2, 3, 6): + cache.age(cache.object(o[k])) + temps = {"objects/.x.tmp-41-0123abcd": True, "objects/.y.tmp-42-89abcdef": False, + ".head.tmp-43-deadbeef": True, "seq/.5.tmp-44-cafef00d": True} + strays = ("objects/notes.txt", "objects/" + "A" * 64, "objects/.x.tmp-45-XYZ") + for rel, old in temps.items(): + (cache.root / rel).write_bytes(b"part") + if old: + cache.age(cache.root / rel) + for rel in strays: + (cache.root / rel).write_bytes(b"stray") + cache.age(cache.root / rel) + + m.image_cache_collect() + kept = {k for k in range(7) if cache.object(o[k]).exists()} + assert kept == {2, 3, 4, 5}, ( + f"objects kept: {sorted(kept)}, not images 3 and 4 (old, named by seqs 3 and 4), 5 " + f"(named by the head) and 6 (named by none, younger than the floor)") + assert sorted(p.name for p in cache.seq.iterdir() if not p.name.startswith(".")) == \ + ["3", "4", "5"] + for rel, old in temps.items(): + assert (cache.root / rel).exists() is not old, ( + f"{rel}: a temp file {'over' if old else 'under'} the floor was " + f"{'kept' if old else 'removed'}") + for rel in strays: + assert (cache.root / rel).exists(), f"collection removed {rel}, not a name it writes" + assert m.image_cache_head() == (5, {"lanes/LANES.md": o[4]}) + + # A KEPT MANIFEST OUT OF FORM: NO OBJECT IS REMOVED. + cache.age(cache.object(o[5])) + (cache.seq / "4").write_bytes(b"lanes/LANES.md") + m.image_cache_collect() + assert cache.object(o[5]).exists(), ( + "collection removed an object while a kept manifest could not be read") + + +def test_the_image_cache_skips_a_busy_or_odd_lock_and_never_waits(tmp_path, monkeypatch): + """Recording and collection take `register-images/lock` with `LOCK_EX | + LOCK_NB`, tried once: while another holder has it, `image_cache_record` + writes nothing and `image_cache_collect` removes nothing, and neither + waits. A `lock` that is not a regular file, a FIFO with no reader here, + counts as busy, and the call returns at once with nothing changed + (lane 1's fix round, SHOULD-1). The lock file is 0600.""" + import fcntl + import threading + cache = image_cache_module(tmp_path, monkeypatch) + m = cache.m + d1, d2 = (m.image_cache_put(f"image {k}\n".encode("ascii")) for k in (1, 2)) + m.image_cache_record(1, {"lanes/LANES.md": d1}) + assert _mode(cache.lock) == 0o600, oct(_mode(cache.lock)) + loose = m.image_cache_put(b"named by no manifest\n") + cache.age(cache.object(loose)) + + held = os.open(str(cache.lock), os.O_WRONLY | os.O_APPEND) + try: + fcntl.flock(held, fcntl.LOCK_EX | fcntl.LOCK_NB) + start = time.monotonic() + m.image_cache_record(2, {"lanes/LANES.md": d2}) + m.image_cache_collect() + assert time.monotonic() - start < 5, "a call waited for the held lock" + assert not (cache.seq / "2").exists(), "record wrote while the lock was held" + assert cache.head_file.read_bytes() == b"1\n" + assert cache.object(loose).exists(), "collect removed an object while the lock was held" + finally: + os.close(held) + + m.image_cache_collect() + assert not cache.object(loose).exists(), "collect did nothing once the lock was free" + m.image_cache_record(2, {"lanes/LANES.md": d2}) + assert cache.head_file.read_bytes() == b"2\n" + + # A FIFO AT THE LOCK'S NAME: BUSY, AT ONCE, WHETHER OR NOT IT BLOCKS ITS OPEN. + os.replace(str(cache.lock), str(cache.root / "lock.aside")) + os.mkfifo(str(cache.lock), 0o600) + loose = m.image_cache_put(b"named by no manifest, again\n") + cache.age(cache.object(loose)) + worker = threading.Thread(target=lambda: (m.image_cache_record(3, {"lanes/LANES.md": d1}), + m.image_cache_collect()), daemon=True) + worker.start() + worker.join(10) + assert not worker.is_alive(), "record or collect blocked on a FIFO at the lock's name" + assert not (cache.seq / "3").exists() and cache.head_file.read_bytes() == b"2\n" + assert cache.object(loose).exists(), "collect ran through a FIFO lock" + assert stat.S_ISFIFO(os.lstat(cache.lock).st_mode) + + +def test_the_image_cache_follows_no_symlink_at_its_lock_or_its_head(tmp_path, monkeypatch): + """Lane 1's follow-up to T302's fix round (lane 3's delta check, #165 + 6755954683, doubts 1 and 2): the lock is opened with `O_NOFOLLOW`, so a + symlink planted at `register-images/lock` is a skip, its target neither + changed nor created; and `record` treats a symlinked `head` as a missing + one, so it replaces the link with a regular `head` and leaves the link's + target alone. Until that commit lands, this case fails by its own + assertion, where the rest of the image cache's cases pass.""" + cache = image_cache_module(tmp_path, monkeypatch) + m = cache.m + d1 = m.image_cache_put(b"image 1\n") + m.image_cache_record(1, {"lanes/LANES.md": d1}) + + # A SYMLINKED HEAD: RECORD REPLACES THE LINK, NOT ITS TARGET. + target = tmp_path / "elsewhere-head" + target.write_bytes(b"1\n") + cache.head_file.unlink() + cache.head_file.symlink_to(target) + m.image_cache_record(2, {"lanes/LANES.md": d1}) + assert target.read_bytes() == b"1\n", "record wrote through a symlinked head" + assert not cache.head_file.is_symlink() and cache.head_file.read_bytes() == b"2\n", ( + "record left a symlinked head in place (lane 3's 6755954683, doubt 2's fix: ELOOP as " + "FileNotFoundError), so image_cache_head() stays unreadable") + + # A SYMLINKED LOCK, DANGLING: A SKIP, AND ITS TARGET IS NOT CREATED. + planted = tmp_path / "elsewhere" / "lock-target" + planted.parent.mkdir() + os.replace(str(cache.lock), str(cache.root / "lock.aside")) + cache.lock.symlink_to(planted) + m.image_cache_record(3, {"lanes/LANES.md": d1}) + assert not planted.exists(), ( + "the lock's open followed a symlink and created its target (lane 3's 6755954683, " + "doubt 1: O_NOFOLLOW on the lock)") + assert not (cache.seq / "3").exists(), "record ran under a symlinked lock" + + +# ======================================== the render read's `start` (T301's cache-forward) +# +# LANE 1'S CACHE-FORWARD COMMIT (T301's `e4d28a505af8`, tag `l1-007-T301-cf1`; +# #165 6767347563; the cache signature lane 3 accepted in 6755051914, B10 +# tasks:996-1003). B10 gives T210 "one case with `start`, so that both arms are +# covered", and lane 1's doubt 1 says what it expects: with `start`, +# `register_render_read` returns THE IMAGES, `{path: bytes}`, and not the rows; +# without it, still `(journal, edits, files)`. T210f (line W4b, wave 6) is this +# case. It needs no engine: the read runs in process against a stand-in store +# that answers each SELECT the code sends from an in-memory sqlite database, as +# lane 1's own hand checks do ("sqlite stood in for PostgreSQL"), and fails +# until the cache-forward commit lands, by the assertion `render_read_module` +# makes. +# +# What the case reads from lane 1's code rather than from a contract, since +# section 3.6 fixes only the CLI: `register_render_read(store, k, *, start=None, +# row="render")`, `register_render_queries(k, *, since=None)`, +# `register_cache_state(images)`, `register_images(journal, edits, files, *, +# start=None)`, `RenderRefused`, and the store's one method the read calls, +# `_query_many(queries, snapshot=True, row=...)`, whose answer is a list of +# result sets of rows of text fields (`t`/`f` for a boolean, None for NULL). + +#: The paths of the journal below: the render set's files, and `lanes/STORE`, +#: which is journaled and is never an image. +LANES_MD, ALPHA_LOG, BETA_LOG, GAMMA_LOG = ("lanes/LANES.md", "lanes/log/alpha.md", + "lanes/log/beta.md", "lanes/log/gamma.md") +ALIASES_TSV, ARCHIVE_MD = "lanes/aliases.tsv", "lanes/archive/old.md" +#: The files whose row says `final_newline` false: an image with no last LF. +NO_LAST_LF = frozenset({ALIASES_TSV}) + +#: AT-1's journal in miniature, as `commit_write` leaves it (design section 1.3.1): an +#: import, then writes. An entry is `(kind, edits, no_last_lf)`; an edit is +#: `("create", path)`, `("append", path, text)`, `("replace", path, n, text)`, +#: `("delete", path, n)` or `("remove", path)`. Seq 2 touches `lanes/STORE`; +#: seq 3 replaces a line, seq 4 deletes one, seq 5 removes a file, and +#: `lanes/archive/old.md` is never touched after the import. +RENDER_JOURNAL = [ + ("import", [("create", LANES_MD), ("append", LANES_MD, "# LANES"), + ("append", LANES_MD, "| alpha | held |"), + ("create", ALPHA_LOG), ("append", ALPHA_LOG, "alpha 1"), + ("append", ALPHA_LOG, f"alpha 2 {EM} two"), + ("create", ALIASES_TSV), ("append", ALIASES_TSV, "old\talpha"), + ("create", ARCHIVE_MD), ("append", ARCHIVE_MD, "archived")], NO_LAST_LF), + ("write", [("append", LANES_MD, "| beta | free |")], ()), + ("write", [("append", ALPHA_LOG, "alpha 3"), ("create", BETA_LOG), + ("append", BETA_LOG, "beta 1"), ("create", STORE_PATH)], ()), + ("write", [("replace", ALPHA_LOG, 1, "alpha 1 (edited)")], ()), + ("write", [("delete", ALPHA_LOG, 2), ("append", ALIASES_TSV, "new\tbeta")], NO_LAST_LF), + ("write", [("remove", BETA_LOG), ("append", LANES_MD, "| gamma | free |")], ()), +] +#: The same register after a re-import at seq 4 (before a confirmed cutover): +#: the root is replaced, so alpha and beta are gone and the seqs 0 to 3 of the +#: old root are history a cache may still hold. +RENDER_REIMPORT = RENDER_JOURNAL[:4] + [ + ("import", [("create", LANES_MD), ("append", LANES_MD, "# LANES (re-imported)"), + ("create", GAMMA_LOG), ("append", GAMMA_LOG, "gamma 1"), + ("create", ALIASES_TSV), ("append", ALIASES_TSV, "old\tgamma")], NO_LAST_LF), + ("write", [("append", GAMMA_LOG, "gamma 2")], ()), +] + + +def _render_image_bytes(lines: list, final_newline: bool) -> bytes: + """One file's bytes as `render_file` builds them (design Y:1297), spelled + out here so that the case's oracle is not the code's own function.""" + return ("\n".join(lines) + ("\n" if final_newline and lines else "")).encode("utf-8") + + +class RenderJournal: + """`entries` replayed by this test's own model, which gives what the + register would hold: the rows of `journal`, `journal_edits` and + `journal_files`, and for each seq the render set's images and its state, + `{path: (lines, final_newline)}`, as the cache's read-back should give.""" + + def __init__(self, entries: list): + self.rows = {"journal": [], "journal_edits": [], "journal_files": []} + self.images_at, self.state_at = [], [] + state: dict = {} + for seq, (kind, edits, no_last_lf) in enumerate(entries): + self.rows["journal"].append((seq, kind)) + if kind == "import": + state.clear() + touched = [] + for ordinal, edit in enumerate(edits, 1): + op, path = edit[0], edit[1] + if path not in touched: + touched.append(path) + lines = state[path][0] if path in state else None + row = (None, None, None) + if op == "create": + state[path] = [[], True] + elif op == "append": + row = (len(lines) + 1, None, edit[2]) + lines.append(edit[2]) + elif op == "replace": + row = (edit[2], _digest(lines[edit[2] - 1].encode("utf-8")), edit[3]) + lines[edit[2] - 1] = edit[3] + elif op == "delete": + row = (edit[2], _digest(lines[edit[2] - 1].encode("utf-8")), None) + del lines[edit[2] - 1] + else: + del state[path] + self.rows["journal_edits"].append((seq, ordinal, op, path, *row, None)) + for path in touched: + if path not in state: + self.rows["journal_files"].append((seq, path, "f", None, None)) + continue + if path in no_last_lf: + state[path][1] = False + lines, final_newline = state[path] + self.rows["journal_files"].append( + (seq, path, "t", _digest(_render_image_bytes(lines, final_newline)), + "t" if final_newline else "f")) + self.images_at.append({p: _render_image_bytes(*v) for p, v in state.items() + if RENDER_SET.match(p)}) + self.state_at.append({p: (list(v[0]), v[1]) for p, v in state.items() + if RENDER_SET.match(p)}) + self.last = len(entries) - 1 + + +class RenderRegister: + """The stand-in store: `register_render_read` calls `store._query_many( + queries, snapshot=True, row=...)`, and this answers each SELECT it is + given from an in-memory sqlite database holding `journal`'s rows. It + records each call in `requests`, as `(queries, snapshot, row)`. With + `raises` set, a call records itself and raises that, as a dead connection + does. Line R's `_register_render_rows` also passes `first_request_at=` + (`lanes-index:2434-2435` at `refs/l1/V-round4`), the bound's clock for + `register snapshot`'s second request (#165 6780364102), which the stand-in + takes and does not use.""" + + DDL = ( + "CREATE TABLE schema_version (id INTEGER PRIMARY KEY, version INTEGER, " + "writers_from INTEGER, readers_from INTEGER)", + "CREATE TABLE register_head (id INTEGER PRIMARY KEY, seq INTEGER)", + "CREATE TABLE journal (seq INTEGER PRIMARY KEY, kind TEXT)", + "CREATE TABLE journal_edits (seq INTEGER, ord INTEGER, op TEXT, path TEXT, " + "line_no INTEGER, old_sha256 TEXT, new_text TEXT, to_path TEXT)", + "CREATE TABLE journal_files (seq INTEGER, path TEXT, present TEXT, sha256 TEXT, " + "final_newline TEXT)", + ) + + def __init__(self, module, journal: RenderJournal): + import sqlite3 + self.db = sqlite3.connect(":memory:") + for statement in self.DDL: + self.db.execute(statement) + self.db.execute("INSERT INTO schema_version VALUES (1, ?, 1, 1)", + (module.REGISTER_SCHEMA_VERSION,)) + self.db.execute("INSERT INTO register_head VALUES (1, ?)", (journal.last,)) + for table, rows in journal.rows.items(): + self.db.executemany(f"INSERT INTO {table} VALUES ({', '.join('?' * len(rows[0]))})", + rows) + self.requests: list = [] + self.raises = None + + def _query_many(self, queries, snapshot=False, *, row=None, timer=None, + first_request_at=None): + self.requests.append((list(queries), snapshot, row)) + if self.raises is not None: + raise self.raises + return [[[None if value is None else str(value) for value in fetched] + for fetched in self.db.execute(query).fetchall()] for query in queries] + + +def render_read_module(): + """`lanes-index` as a module, under its own name so nothing else in the run + shares it. Asserts lane 1's cache-forward commit is there: the case's red + until `register_render_read`, `register_images` and `register_render_queries` + take their `start` and `since`, and `register_cache_state` reads images + back (#165 6755040818, 6767347563).""" + from importlib.machinery import SourceFileLoader + import importlib.util + import inspect + loader = SourceFileLoader(f"lanes_index_render_read_{uuid.uuid4().hex}", str(LANES_INDEX)) + spec = importlib.util.spec_from_loader(loader.name, loader) + module = importlib.util.module_from_spec(spec) + loader.exec_module(module) + missing = [name for name in ("register_render_read", "register_render_queries", + "register_images", "register_cache_state", "RenderRefused", + "PsqlFailed", "REGISTER_SCHEMA_VERSION") + if not hasattr(module, name)] + assert not missing, ( + f"{LANES_INDEX} has no render read, {missing} missing: lane 1's T301, with its " + f"cache-forward commit (`e4d28a505af8`, #165 6767347563), has not landed") + wanting = [f"{name}'s {keyword}" for name, keyword in ( + ("register_render_read", "start"), ("register_images", "start"), + ("register_render_queries", "since")) + if keyword not in inspect.signature(getattr(module, name)).parameters] + assert not wanting, ( + f"{LANES_INDEX} takes no {wanting}: lane 1's T301 cache-forward commit " + f"(`e4d28a505af8`, #165 6767347563) has not landed") + return module + + +def test_the_render_read_with_start_returns_the_images_and_a_bad_start_costs_one_full_read(): + """T210's case with `start` (B10 tasks:1003; lane 1, #165 6767347563, doubt + 1: "**Lane 2:** T210's `start` case should expect images"). Both arms of + `register_render_read`, against a register built by this test's own model + of `commit_write`: + + WITHOUT `start` it returns `(journal, edits, files)`, the rows from the + latest import to `k`, which `register_images` builds into the images, in + one request. + + WITH `start=(c, state)`, `state` being `register_cache_state` of the + images at `c`, it returns THE IMAGES AT `k`, a `dict` of `bytes` and not + the rows, equal to the model's for every `c` from 0 to `k`: in ONE request, + which reads only the entries after `c` (`register_render_queries(k, + since=c)`), and `start` is left as it was. + + A START IT CANNOT TRUST IS A MISS, NOT AN ERROR, AND THE COUNT SAYS + WHICH KIND (lane 1, #165 6769176187, for the cache-forward commit + `e4d28a5`): a `start` of another form, or a `c` above `k`, is refused + before any request and costs exactly ONE, the full read; a cached image + of an untouched path that is wrong (a cache from a reused seq), a cached + image that an edit does not apply on, and a path the cache lacks are + found after the read since `c` and cost exactly TWO, that read and then + the full one. Each returns the right images, the full read last. An + import among entries `c+1` to `k` sets `start` aside, so even a wrong + cache is no miss there, one request. Only the full read's failure ends in + `RenderRefused`, after the two requests; a dead connection (`PsqlFailed`) + is raised as it is, after one, and is never tried twice. And + `register_cache_state` misses (None) on an image that is empty, is not + UTF-8 or is not bytes, so an estate with an empty file in its render set + always replays in full.""" + pytest.importorskip("sqlite3") + import copy + m = render_read_module() + journal = RenderJournal(RENDER_JOURNAL) + register = RenderRegister(m, journal) + last = journal.last + + def read(k, **kwargs): + """One call and the requests it made. A `RenderRefused` is no answer, and + fails the expectation that asked.""" + before = len(register.requests) + try: + answer = m.register_render_read(register, k, **kwargs) + except m.RenderRefused as refusal: + raise AssertionError(f"read(k={k}) ended in RenderRefused: {refusal}") from None + return answer, register.requests[before:] + + def kinds(k, sent): + """The requests as `full` or `since`, for a failure's message.""" + return ["full" if queries == m.register_render_queries(k) else "since" + for queries, _snapshot, _row in sent] + + def full(k, row="render"): + return (m.register_render_queries(k), True, row) + + def since(k, c, row="render"): + return (m.register_render_queries(k, since=c), True, row) + + # THE READ WITHOUT `start` GIVES THE ROWS, IN ONE REQUEST, AND THE ROWS BUILD THE IMAGES. + for k in range(last + 1): + rows, sent = read(k) + assert isinstance(rows, tuple) and len(rows) == 3, ( + f"read(k={k}) without start returned {type(rows).__name__}, not " + f"(journal, edits, files)") + assert sent == [full(k)], f"read({k}) sent {kinds(k, sent)}" + assert rows[0][0] == (0, "import") and rows[0][-1][0] == k, rows[0] + assert m.register_images(*rows) == journal.images_at[k], f"the images at seq {k}" + + # THE CACHE'S READ-BACK: THE STATE THE MODEL HOLDS, FOR EVERY SEQ. + for c in range(last + 1): + assert m.register_cache_state(journal.images_at[c]) == journal.state_at[c], ( + f"register_cache_state of the images at seq {c}") + + # WITH `start`: THE IMAGES AT `k`, FOR EVERY `c` UP TO `k`, IN ONE REQUEST SINCE `c`. + for c in range(last + 1): + start = (c, m.register_cache_state(journal.images_at[c])) + frozen = copy.deepcopy(start) + for k in range(c, last + 1): + images, sent = read(k, start=start) + assert isinstance(images, dict) and not isinstance(images, tuple), ( + f"read(k={k}, start at {c}) returned {type(images).__name__}: with `start` " + f"it returns the images, {{path: bytes}}, and not the rows") + assert all(isinstance(p, str) and isinstance(b, bytes) for p, b in images.items()) + assert images == journal.images_at[k], f"the images at seq {k} from a cache at {c}" + assert sent == [since(k, c)], ( + f"read(k={k}, start at {c}) sent {kinds(k, sent)}, not one request since {c}") + assert start == frozen, "register_render_read changed `start`" + + # A START IT CANNOT TRUST IS A MISS: THE RIGHT IMAGES, AND A FULL READ LAST. + k, c = last, 2 + good = dict(journal.images_at[c]) + wrong_untouched = {**good, ARCHIVE_MD: b"another root's archive\n"} + wrong_edit_base = {**good, ALPHA_LOG: b"not alpha's first line\nalpha 2\nalpha 3\n"} + lacks_untouched = {p: b for p, b in good.items() if p != ARCHIVE_MD} + for what, images in (("a wrong image of an untouched path (a cache from a reused seq)", + wrong_untouched), + ("an image the seq-3 replace does not apply on", wrong_edit_base), + ("a cache that lacks an untouched path", lacks_untouched)): + state = m.register_cache_state(images) + assert state is not None, f"register_cache_state refused {what}" + answer, sent = read(k, start=(c, state)) + assert answer == journal.images_at[k], f"the images after {what}" + assert sent == [since(k, c), full(k)], ( + f"{what}: a failed proof or edit costs exactly two requests, the first since " + f"seq {c} and the second the full read; sent {kinds(k, sent)}") + ok_state = m.register_cache_state(good) + for what, start, at in (("a `c` above `k`", (5, m.register_cache_state(journal.images_at[5])), + 3), + ("a `c` that is not an int", ("2", ok_state), last), + ("a `c` that is a bool", (True, ok_state), last), + ("a state that is not a dict", (2, "not a state"), last), + ("a state of the wrong value form", (2, {LANES_MD: "text"}), last), + ("a start of one item", (2,), last), + ("a start that is not a pair", [], last)): + answer, sent = read(at, start=start) + assert isinstance(answer, dict) and answer == journal.images_at[at], ( + f"the images after {what}") + assert sent == [full(at)], ( + f"{what}: a start of another form, or a `c` above `k`, is refused before any " + f"request and costs exactly one, the full read; sent {kinds(at, sent)}") + + # AN IMPORT AMONG ENTRIES `c+1` TO `k` SETS `start` ASIDE: EVEN A WRONG CACHE IS NO MISS. + again = RenderJournal(RENDER_REIMPORT) + reimport = RenderRegister(m, again) + old_root = m.register_cache_state(journal.images_at[2]) + for caches, cached in (("the old root's images", old_root), + ("images the seq-3 replace does not apply on, which is never " + "applied", m.register_cache_state(wrong_edit_base))): + for c, k in ((2, 5), (2, 4), (3, 5)): + before = len(reimport.requests) + answer = m.register_render_read(reimport, k, start=(c, cached)) + assert answer == again.images_at[k], f"the images at seq {k} past the re-import" + assert reimport.requests[before:] == [(m.register_render_queries(k, since=c), True, + "render")], ( + f"a start at {c}, {caches}, was set aside by the re-import at 4, and cost " + f"one request") + # A CACHE AT OR AFTER THE IMPORT IS BROUGHT FORWARD AS ANY IS. + new_root = m.register_cache_state(again.images_at[4]) + before = len(reimport.requests) + assert m.register_render_read(reimport, 5, start=(4, new_root)) == again.images_at[5] + assert reimport.requests[before:] == [(m.register_render_queries(5, since=4), True, "render")] + + # ONLY THE FULL READ'S FAILURE ENDS IN `RenderRefused`: k=3 is before the latest import. + before = len(reimport.requests) + with pytest.raises(m.RenderRefused): + m.register_render_read(reimport, 3, start=(2, old_root)) + assert reimport.requests[before:] == [ + (m.register_render_queries(3, since=2), True, "render"), + (m.register_render_queries(3), True, "render")], ( + "a refused k, with a start, is two requests and then the refusal") + + # A DEAD CONNECTION IS RAISED AS IT IS, AFTER ONE REQUEST, AND NEVER TRIED TWICE. + register.raises = m.PsqlFailed("unreachable", "the database did not answer") + before = len(register.requests) + with pytest.raises(m.PsqlFailed): + m.register_render_read(register, last, start=(2, ok_state)) + assert register.requests[before:] == [since(last, 2)], "a dead connection was tried twice" + register.raises = None + + # THE CACHE'S READ-BACK MISSES ON AN IMAGE IT CANNOT READ BACK: THE ESTATE REPLAYS IN FULL. + images = journal.images_at[last] + assert m.register_cache_state(images) == journal.state_at[last] + for what, bad in (("an empty image", {**images, "lanes/log/empty.md": b""}), + ("an image that is not UTF-8", {**images, ALPHA_LOG: b"\xff\xfe\n"}), + ("an image that is not bytes", {**images, ALPHA_LOG: "alpha\n"}), + ("images that are not a dict", list(images.items()))): + assert m.register_cache_state(bad) is None, f"register_cache_state took {what}" + + +# ============================================================ phase W: T240 +# +# TEST 1'S PHASE-W PART (lane 2's T240; AT-1, the test plan's lines 537-645; +# FR-018, FR-027, FR-042, FR-059): each of S1's writes through `lanes-edit.sh` +# on a `mode=primary` workstation, from T203's flipped copy (`RENDER_GIT_HALF = +# True`, test 14's second state) with `lanes-edit.sh` beside it, over test 1's +# imported register (`import_to_primary`, AT-LR006's route), then the pure +# renderer writing a scratch mirror, `render --images --at <seq> --out <dir>`. +# +# THE VERBS (`W_VERBS`) are the thirteen of P192-196, `log` once per verb of +# its grammar: the fourteen arms of `lanes-edit.sh`'s write dispatch but +# `commit`, whose direct write is 2 (D10), with the argument lists the writes +# module's `WRITE_VERBS` gives them (T241), and `log` once for each verb of +# `VERB_LIST` that `log` writes by hand. That is twelve: `log` refuses CLAIMED, +# TAKEOVER, RELEASED, CLAIM-LOST, HANDOFF-REQUESTED and RENAMED, which their own +# verbs write. The lists are copied here, never imported: the writes module +# imports this one. Every verb runs from the same starting state, C with the +# verb's prep (`W_PREPS`), and each case gets a database of its own. Each +# argument list exits 0 and makes one commit in files mode on line R's +# V-round4 (line W1-12's probe). +# +# THE TWIN (AT-1, "Part W adds an FM twin"): a files-mode clone of W's origin +# at C, with its own origin and its own `$HOME`, makes the same verb. The +# mirror's render set equals the twin's origin's, path set and bytes, with +# every UTC masked in both, in a line or in a path (`migrate-state-cells`' +# archive is named by its UTC): open point 4 leaves the mask in place until a +# test can fix the database's clock. The journal entry's message is the twin's +# commit message, but `rename-lane`'s, which on primary is the message the +# design names under Q13(a) (lane 3's ruling (A), #165 6859179515). +# +# GB SECTION 4.3'S CASES (R29), each an assertion of a named test: D12, the +# fake `git`'s log holding no `fetch` on primary that the verb itself makes, +# for any verb, the renderer the write forks left out by the process above +# the call (lane 3, #165 6859073786), in the mirror case; `rename-lane`'s +# `register seq` and its tail under Q13(a), the +# transaction first and then the move, in +# `test_rename_lane_commits_the_transaction_then_a_rerun_makes_only_the_move`; +# and `start-record` in both modes, its twin run once more under +# `LANES_ROUTE_WRITES=1`, as the twin case's `[start-record]`. +# +# THE MOVE ON PRIMARY (lane 3's batch c, #165 6807881675, Q55 and Q56, B15 +# texts (2) to (4) for F13d:502, :497 and :496): `rename-lane` renames one +# regular file inside its own folder and commits those two paths alone, so a +# folder's tracked bytecode never rides it (#162); a handoff whose own path has +# a cache, bytecode or environment part refuses 2 before the seam (Y:5138; +# REV422c N1). The rerun is `LANES_LANE=<new> lanes-edit.sh rename-lane <old> +# <new>` (batch c Q71 and Q74, #165 6808141050). +# +# THEY FAIL UNTIL lane 4's L4-B4 (T414's seam), L4-B8 (T422, `rename-lane`'s +# tail and its seq) and L4-B13 (T415's author, T416's fork, `<c>` and the +# nudge) land, each by its own assertion here: line R's `lanes-edit.sh` writes +# the files whatever `mode=` says. `[start-record]` fails until L4-B9 (T427) +# too, and the two `rename-lane` cases B15 adds until lane 4's T422. + +#: The lanes these writes are for, each with its own checkout `<c>`, +#: `<W>-lanes/<lane>` (B14 tasks:1142's T415 bullets; R17): repoA-1 and +#: repoA-2, as `LANES_LANE` or a verb's `<lane>`, and repoA-3, `add-row`'s new +#: row and `rename-lane`'s new name (the writes module's `WRITE_LANES`). +W_LANES = ("repoA-1", "repoA-2", "repoA-3") + +#: The writer's password in the 0600 `register_passfile=` (AT-1's fixture), +#: which the cluster's trust never asks for and no output may carry. +W_SECRET = "t240-never-printed-5d2a" + + +def _w_with_row(lane: str, sid: str, cell: str, log: str = None) -> dict: + """A prep: test 1's SEED with one more row in `LANES.md`'s table, after + repoA-2's, and the lane's log (its header, then `log`'s lines). Copied + from the writes module's `_with_row`.""" + lanes = SEED["lanes/LANES.md"] + anchor = next(line for line in lanes.split("\n") if line.startswith("| `repoA-2` |")) + row = (f"| `{lane}` | harness `{sid}` | Eagle / test / brett | 2026-09-01T00:00Z | none " + f"| handoffs/{lane}.md | {cell} |") + header = f"# lane {lane} {EM} object log (lane-collision-protocol Amendment 7)\n" + return {"lanes/LANES.md": lanes.replace(anchor + "\n", anchor + "\n" + row + "\n", 1), + f"lanes/log/{lane}.md": header + (log or "")} + + +def _w_with_handoffs(handoffs: dict, extra: dict = None) -> dict: + """A prep: test 1's SEED with each lane of `handoffs`, {lane: (path, + bytes)}, naming the handoff at `path` in its row's handoff column, and that + handoff committed there; and `extra`, {path: bytes}, committed beside + them.""" + lanes = SEED["lanes/LANES.md"] + files: dict = {} + for lane, (path, data) in handoffs.items(): + old = next(line for line in lanes.split("\n") if line.startswith(f"| `{lane}` |")) + assert old.count(f"| handoffs/{lane}.md |") == 1, old + lanes = lanes.replace(old, old.replace(f"| handoffs/{lane}.md |", f"| {path} |"), 1) + files[path] = data + files["lanes/LANES.md"] = lanes + files.update(extra or {}) + return files + + +#: The starting state three verbs need, or they refuse for want of work (2), +#: as the writes module's `PREPS` gives it: `archive-rows <repo>` moves a +#: repository's RETIRED rows, `retire-rows` takes a dormant row, and +#: `migrate-state-cells` migrates a diary cell. +W_PREPS = { + "archive-rows": _w_with_row( + "repoZ-2", "eeeeeeee-0002-4000-8000-00000000e002", + f"RETIRED {DOT} 2026-09-03T00:00:00Z {DOT} retired", + f"RETIRED {EM} lane repoZ-2, session eeeeeeee-0002-4000-8000-00000000e002@Eagle, " + f"2026-09-03T00:00:00Z, lane:repoZ-2 {EM} retired\n"), + "retire-rows": _w_with_row("repoA-4", "aaaaaaaa-0005-4000-8000-00000000a005", + f"MIGRATED {DOT} 2026-09-01T00:00:00Z {DOT} migrated"), + "migrate-state-cells": _w_with_row("repoA-5", "aaaaaaaa-0006-4000-8000-00000000a006", + f"parked 2026-09-01 {DOT} picked up 2026-09-02"), +} + +#: The session `request-handoff --force` writes its `PAUSED` for, as the +#: writes module's `SID_REQUESTER`. +W_SID_REQUESTER = "bbbbbbbb-0007-4000-8000-00000000b007" + +#: A lane's binding payload, for `log STARTED` and `log RESUMED`. +W_BINDING = "home opensoft/repoA; dir /work/repoA2" + +#: S1's writes but `commit`, `log` once per verb of its grammar: {id: (its +#: arguments, the lane it writes as)}. The forms are `lanes-edit.sh`'s usage +#: lines at a2073eae; `log`'s are its arm's, at line R's V-round4. +#: THE LANE IT WRITES AS is the lane the write is for, D12's writing lane, +#: whose checkout `<c>` T415's `pw_checkout` takes through `write_lane_of` +#: (lane 3, #165 6869860086; lane 4, #165 6869806372): for `add-row` the new +#: row's, repoA-3, and for `request-handoff` its target's, repoA-1, as +#: `lane-start` and `lane` set `LANES_LANE` for those two verbs. For every +#: other verb the two lanes are one already. +W_VERBS = { + "add-row": (["add-row", f"| `repoA-3` | harness `aaaaaaaa-0004-4000-8000-00000000a004` | " + f"Eagle / test / brett | 2026-11-10T00:00Z | none | handoffs/repoA-3.md | " + f"LIVE {DOT} 2026-11-10T00:00:00Z {DOT} test 1 |"], "repoA-3"), + "append-line": (["append-line", f"HOLD {EM} lane repoA-2 ({WS}), window w, " + f"2026-11-10T00:00:00Z: opensoft/repoB main {TIP} for test 1"], "repoA-2"), + "append-session-id": (["append-session-id", "repoA-2", f"harness `{SID_A2}`", + " (test 1)"], "repoA-2"), + "archive-rows": (["archive-rows", "repoZ", "--yes"], "repoA-2"), + "claim": (["claim", "opensoft/repoA#9", "--no-github"], "repoA-2"), + "log-closed": (["log", "CLOSED", "opensoft/repoA#9", "closed for test 1"], "repoA-2"), + "log-opened": (["log", "OPENED", "opensoft/repoA#8", "test 1's PR"], "repoA-2"), + "log-landing": (["log", "LANDING", "opensoft/repoA#8", "test 1"], "repoA-2"), + "log-landed": (["log", "LANDED", "opensoft/repoA#8", ARROW, "abc1234"], "repoA-2"), + "log-withdrawn": (["log", "WITHDRAWN", "opensoft/repoA#8", "test 1"], "repoA-2"), + "log-started": (["log", "STARTED", "lane:repoA-2", ARROW, W_BINDING], "repoA-2"), + "log-paused": (["log", "PAUSED", "lane:repoA-1", "parked for test 1"], "repoA-1"), + "log-resumed": (["log", "RESUMED", "lane:repoA-2", ARROW, W_BINDING], "repoA-2"), + "log-ended": (["log", "ENDED", "lane:repoA-1", "ended for test 1"], "repoA-1"), + "log-retired": (["log", "RETIRED", "lane:repoA-1", "retired for test 1"], "repoA-1"), + "log-noted": (["log", "NOTED", "lane:repoA-2", "test 1's note"], "repoA-2"), + "log-ruled": (["log", "RULED", "lane:repoA-2", ARROW, "opensoft/repoA#9", + "the words, verbatim"], "repoA-2"), + "migrate-state-cells": (["migrate-state-cells", "--yes"], "repoA-2"), + "release": (["release", "opensoft/repoA#7", "test 1", "--no-github"], "repoA-1"), + "rename-lane": (["rename-lane", "repoA-2", "repoA-3", "test 1", "--no-github"], "repoA-2"), + "replace-in-row": (["replace-in-row", "repoA-2", "parked", "parked for test 1"], "repoA-2"), + "request-handoff": (["request-handoff", "repoA-1", "--force", "test 1", "--session", + W_SID_REQUESTER], "repoA-1"), + "retire-rows": (["retire-rows", "repoA-4", "--reason", "test 1"], "repoA-2"), + "set-row-state": (["set-row-state", "repoA-2", f"PAUSED {DOT} test 1"], "repoA-2"), +} + +#: The twin's verbs: `W_VERBS`, and GB section 4.3's `start-record`, lane 4's +#: T427 verb (L4-B9), as a resume of repoA-2, which `LANES_SESSION` names by +#: its transcript uuid and `LANES_LANE` by the row's own spelling (B14 +#: tasks:1325-1333): {id: (its arguments, the lane, what the run adds to the +#: environment)}. +TWIN_VERBS = {**{verb: (argv, lane, {}) for verb, (argv, lane) in W_VERBS.items()}, + "start-record": (["start-record", "repoA-2", "RESUMED", "--state", + f"LIVE {DOT} resumed for test 1", "--log", "lane:repoA-2", + ARROW, W_BINDING], "repoA-2", {"LANES_SESSION": SID_A2})} + + +def _logging_git(path: Path, log: Path, real: str = None) -> None: + """A `git` at `path` that appends each call to `log`, then runs the real + `git` (or `real`) with its arguments (D12's oracle: GB section 4.3, "the + fake `git`'s log"). A call is one record, written by one `printf`, so a + forked renderer's calls and the verb's never interleave: the pid above + the call; where any argument is `fetch` or `pull`, that process's command + line, as open point 8's wrapper reads it (`ps -ww -o command=`; TP:8799-8800, + test 5's wrapper in `test_sql_register_renderer_git.py`), and the + directory the call runs in; then its arguments. Each field is ended by a + US (0x1f) and the record by an RS (0x1e) and a LF.""" + real = real or shutil.which("git") + assert real, "no git on PATH" + path.write_text("#!/bin/sh\n" + "u='\x1f' above=$PPID command= here=\n" + "for a in \"$@\"; do case $a in fetch|pull)\n" + " command=$(ps -ww -o command= -p \"$above\" 2>/dev/null" + " | tr '\\n\\036\\037' ' ')\n" + " here=$PWD; break ;; esac; done\n" + "record=\"$above$u$command$u$here$u\"\n" + "for a in \"$@\"; do record=\"$record$a$u\"; done\n" + f"printf '%s\\036\\n' \"$record\" >> {shlex.quote(str(log))}\n" + f"exec {shlex.quote(real)} \"$@\"\n", encoding="utf-8") + path.chmod(0o755) + + +#: `git`'s own options that take the next argument as their value. +_GIT_VALUE_OPTIONS = frozenset({"-C", "-c", "--git-dir", "--work-tree", "--namespace", + "--exec-path", "--super-prefix", "--config-env"}) + + +def _render_checkout(command: str): + """The `<c>` of a `lanes-index render --checkout <c>` command line, the + renderer a write forks (`pw_render_fork`, T416), or None for any other + process.""" + words = command.split() + for i in range(len(words) - 3): + if (words[i].rsplit("/", 1)[-1] == "lanes-index" + and words[i + 1:i + 3] == ["render", "--checkout"]): + return words[i + 3] + return None + + +def _git_calls(log: Path) -> list: + """`_logging_git`'s log: each call as a dict, its subcommand (`sub`, the + first argument that is not one of `git`'s own options or such an + option's value), its arguments (`args`), the pid above it (`above`), and, + for a `fetch` or a `pull`, the `<c>` of the `lanes-index render + --checkout` process above it, or None (`render`), and the real path of + the repository it ran in, its directory moved by each `-C` (`where`).""" + if not log.exists(): + return [] + calls = [] + for record in log.read_bytes().decode("utf-8", "replace").split("\x1e\n"): + if not record: + continue + above, command, here, *args = record.split("\x1f")[:-1] + i = 0 + where = here + while i < len(args) and args[i].startswith("-"): + if args[i] == "-C" and i + 1 < len(args): + where = os.path.join(where, args[i + 1]) + i += 2 if args[i] in _GIT_VALUE_OPTIONS else 1 + calls.append({"sub": args[i] if i < len(args) else "", "args": args, "above": above, + "render": _render_checkout(command), + "where": os.path.realpath(where) if here else ""}) + return calls + + +def _d12_control(root: Path, checkout: str) -> None: + """D12's control: the render pass's own fetch argv (`lanes-index`'s + `render_pass`, step 1), in `checkout`, logged by `_logging_git` with + `true` for `git`, so nothing is fetched. Once from this test, which is + no renderer: kept, as a fetch of the verb's would be. Once from a + stand-in whose command line is `lanes-index render --checkout + <checkout>`: left out, with its `<c>`. The same argv both times, so the + two are told apart by the process above the call alone.""" + root.mkdir(parents=True, exist_ok=True) + log, shim, stand_in = root / "git-calls.log", root / "git", root / "lanes-index" + _logging_git(shim, log, real=shutil.which("true")) + stand_in.write_text("#!/bin/sh\nshift 4\n\"$D12_SHIM\" \"$@\"\nexit $?\n", + encoding="utf-8") + stand_in.chmod(0o755) + argv = ["-C", checkout, "-c", "gc.auto=0", "-c", "maintenance.auto=false", "fetch", + "--no-tags", "--no-write-fetch-head", "--no-recurse-submodules", "-q", "origin", + "+refs/heads/main:refs/remotes/origin/main"] + env = dict(os.environ, D12_SHIM=str(shim)) + for command in ([str(shim), *argv], + [str(stand_in), "render", "--checkout", checkout, "--", *argv]): + done = subprocess.run(command, cwd=str(root), env=env, capture_output=True, + timeout=60, check=False) + assert done.returncode == 0, f"the D12 control's {command[0]}: {done.stderr!r}" + got = [(call["sub"], call["args"], call["render"], call["where"]) + for call in _git_calls(log)] + assert got == [("fetch", argv, None, checkout), ("fetch", argv, checkout, checkout)], ( + f"the D12 control: the renderer's fetch argv run by no renderer must be kept, " + f"and under a `lanes-index render --checkout` left out: {got}") + + +def _git_bytes(cwd: Path, env: dict, *args: str) -> bytes: + proc = subprocess.run(["git", *args], cwd=str(cwd), capture_output=True, env=env, + check=False) + assert proc.returncode == 0, f"git {' '.join(args)} in {cwd}: {proc.stderr!r}" + return proc.stdout + + +def _origin_render_set(origin: Path, env: dict, ref: str = "main") -> dict: + """The render set on a bare repository's `ref`, read by object: {path: + bytes}.""" + names = _git_bytes(origin, env, "ls-tree", "-r", "-z", "--name-only", ref, "--", "lanes") + return {name: _git_bytes(origin, env, "cat-file", "blob", f"{ref}:{name}") + for name in names.decode("utf-8").split("\0") if name and RENDER_SET.match(name)} + + +def _origin_paths(origin: Path, env: dict, ref: str = "main", where: str = ".") -> dict: + """Every path under `where` on a bare repository's `ref`, to its blob.""" + out = _git_bytes(origin, env, "ls-tree", "-r", "-z", ref, "--", where).decode("utf-8") + found = {} + for entry in out.split("\0"): + if entry: + meta, path = entry.split("\t", 1) + found[path] = meta.split()[2] + return found + + +def _raw_message(origin: Path, env: dict, ref: str = "main") -> str: + """A commit's message as git stores it, every byte after the header.""" + raw = _git_bytes(origin, env, "cat-file", "commit", ref) + return raw.split(b"\n\n", 1)[1].decode("utf-8") if b"\n\n" in raw else "" + + +#: A UTC in any form a register file spells it: whole minutes (a row's +#: `started` cell), whole seconds, or with a fraction (Q4(d)(i)). +_UTC_ANY = re.compile(r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}(?::[0-9]{2}(?:\.[0-9]+)?)?Z") +_UTC_ANY_BYTES = re.compile(_UTC_ANY.pattern.encode("ascii")) + + +def _utc_masked(files: dict) -> dict: + """`files`, {path: bytes}, with every UTC masked, in each path and in + each file's bytes (AT-1's twin oracle; open point 4).""" + return {_UTC_ANY.sub("<utc>", path): _UTC_ANY_BYTES.sub(b"<utc>", data) + for path, data in files.items()} + + +def _first_difference(ours: bytes, theirs: bytes) -> str: + a = ours.decode("utf-8", "replace").split("\n") + b = theirs.decode("utf-8", "replace").split("\n") + for n, (x, y) in enumerate(zip(a, b), 1): + if x != y: + return f"line {n}: {x!r} != {y!r}" + return f"{len(a)} lines != {len(b)} lines" + + +def _assert_same_files(ours: dict, theirs: dict, what: str) -> None: + assert sorted(ours) == sorted(theirs), ( + f"{what}: the path sets differ: only ours {sorted(set(ours) - set(theirs))}, only " + f"theirs {sorted(set(theirs) - set(ours))}") + for name in sorted(ours): + assert ours[name] == theirs[name], ( + f"{what}: {name}'s bytes differ, {_first_difference(ours[name], theirs[name])}") + + +def _stamped_utcs(before: dict, after: dict, argv: list) -> list: + """Each UTC in whole seconds or finer that a write put on a line of the + render set, (path, line, utc): one not already anywhere in the register + before it, and not one the caller typed. A UTC in whole minutes is a row's + `started` cell, never a write's clock. For `migrate-state-cells` alone + (`argv[0]`), nor is a minute already in the register with `:00` added, + which that verb writes on primary for an entry's minute-only time or its + row's `started` cell; no other verb adds it (design.md:5114 at + `8e8d1b49`; `44f487d1:lanes-edit.sh:23907-23922`, its arm's `msc_eutc`; + lane 3, #165 6859073786). Any other verb's `:00` UTC is still checked + against the clock, though its minute was in the register.""" + old = set(_UTC_ANY.findall("\n".join(d.decode("utf-8", "replace") for d in before.values()))) + typed = set(_UTC_ANY.findall(" ".join(argv))) + minute_kept = argv[0] == "migrate-state-cells" + found = [] + for path, data in sorted(after.items()): + lines_before = set(before.get(path, b"").decode("utf-8", "replace").split("\n")) + for line in data.decode("utf-8", "replace").split("\n"): + if line in lines_before: + continue + for utc in _UTC_ANY.findall(line): + if (utc.count(":") == 2 and utc not in old and utc not in typed + and not (minute_kept and utc.endswith(":00Z") + and utc[:-4] + "Z" in old)): + found.append((path, line, utc)) + return found + + +class PrimaryWrites: + """AT-1's part-W workstation over the test's database, a copy of the + writes module's `RegisterWorkstation` (that module imports this one): the + files-mode workspace of the sync case (`workspace`) at C, the case's prep + committed and pushed first; C imported and brought to `primary` with the + marker `present` (`import_to_primary`, AT-LR006's route); T203's flipped + copy with `lanes-edit.sh` beside it; a 0600 `lanes-index.conf` with + `mode=primary`, both URLs naming the cluster's socket as this module's + logins, and a 0600 `register_passfile=`; `<c>` for each of `W_LANES`, a + clone of origin; and first on `PATH`, T203's `psql` shim, which hands each + call to the cluster's `psql` and logs it, and `_logging_git`. + `marker_on_origin`, which only part G sets, puts the cutover's marker + commit on origin's `main` before `record_marker` (`import_to_primary`), + so each `<c>` is cloned at it; every other case keeps a made-up marker + sha and an origin at C (T270's line, tasks:2477).""" + + def __init__(self, pg, tmp_path: Path, prep: dict = None, + marker_on_origin: bool = False): + self.pg = pg + self.fakebin = tmp_path / "fakebin" + self.fakebin.mkdir(parents=True, exist_ok=True) + (self.fakebin / "psql").write_text(PSQL_SHIM, encoding="utf-8") + (self.fakebin / "psql").chmod(0o755) + (self.fakebin / PSQL_SHIM_CONTROL).write_text(json.dumps({"psql": pg.psql_bin}), + encoding="utf-8") + self.git_log = tmp_path / "git-calls.log" + _logging_git(self.fakebin / "git", self.git_log) + self.estate, self.env, _source = workspace(tmp_path / "ws", self.fakebin) + if prep: + self._prep(prep) + ensure_logins(pg) + self.copy = flipped(tmp_path) + self.lanes_edit = self.copy.parent / "lanes-edit.sh" + conf_dir = tmp_path / "conf" + conf_dir.mkdir() + passfile = conf_dir / "pgpass" + passfile.write_text(f"*:*:*:{LOGIN_WRITER}:{W_SECRET}\n", encoding="utf-8") + passfile.chmod(0o600) + self.conf = primary_config(conf_dir / "lanes-index.conf", pg.url(LOGIN_WRITER), + pg.url(LOGIN_READER), passfile) + self.env.update(LANES_INDEX_CONFIG=str(self.conf)) + self.env.pop("LANES_INDEX", None) + #: The environment the pure renderer and `status` run in. + self.index = index_env(tmp_path, self.conf, self.estate.home) + self.imported = import_to_primary(pg, self.estate, marker_on_origin) + for lane in W_LANES: + self.make_lane_checkout(lane) + + def _prep(self, files: dict) -> None: + """`files` ({path: text or bytes}) written over the checkout, + committed and pushed, so the case starts from them; C is that + commit.""" + estate = self.estate + for path, data in files.items(): + target = estate.checkout / path + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data if isinstance(data, bytes) else data.encode("utf-8")) + git(estate.checkout, "add", "-A", env=estate.env) + git(estate.checkout, "commit", "-q", "-m", "C': the case's starting state", + env=estate.env) + git(estate.checkout, "push", "-q", "origin", "main", env=estate.env) + estate.files.update({p: d for p, d in files.items() if isinstance(d, str)}) + estate.c = git(estate.checkout, "rev-parse", "HEAD", env=estate.env).strip() + estate.lanes_tree = git(estate.checkout, "rev-parse", f"{estate.c}:lanes", + env=estate.env).strip() + + def lane_checkout(self, lane: str) -> Path: + """`<c>`, `<W>-lanes/<lane>`, W being the real path of + `workspace.yaml`'s `path:` (Amendment 23 S1).""" + real = Path(os.path.realpath(self.estate.checkout)) + return real.parent / f"{real.name}-lanes" / lane + + def make_lane_checkout(self, lane: str) -> Path: + target = self.lane_checkout(lane) + target.parent.mkdir(parents=True, exist_ok=True) + git(target.parent, "clone", "-q", str(self.estate.origin), str(target), + env=self.estate.env) + return target + + def checkouts(self) -> list: + """W's checkout and each lane's `<c>`.""" + return [self.estate.checkout, *(self.lane_checkout(lane) for lane in W_LANES)] + + def run(self, argv: list, lane: str, **extra) -> subprocess.CompletedProcess: + """`lanes-edit.sh <argv>` in W's checkout, as lane `lane`.""" + env = dict(self.env, LANES_LANE=lane, **extra) + return subprocess.run(["bash", str(self.lanes_edit), *argv], capture_output=True, + encoding="utf-8", errors="replace", env=env, timeout=120, + cwd=str(self.estate.checkout), check=False, + stdin=subprocess.DEVNULL) + + def shim_calls(self) -> list: + log = self.fakebin / PSQL_SHIM_LOG + if not log.exists(): + return [] + entries = [json.loads(x) for x in log.read_text(encoding="utf-8").splitlines() if x] + return [e for e in entries if e.get("kind") != "version"] + + def commit_calls(self) -> list: + return [c for c in self.shim_calls() if "commit_write(" in (c.get("stdin") or "")] + + def git_calls(self) -> list: + return _git_calls(self.git_log) + + +class FilesTwin: + """AT-1's twin: a files-mode clone of W's origin at C, "under its own + `$HOME`", with an origin of its own, a bare clone of W's, so its push + moves nothing the primary case reads, and the environment `workspace` + sets, with no `lanes-index.conf`: `lanes-edit.sh` beside the flipped copy + asks its mode, and `files` answers. Made before the primary write, so it + is at C whatever a forked render pushes to W's origin. A `routed` twin + runs under `LANES_ROUTE_WRITES=1` with `LANES_REPO` unset, so each write + goes through its lane's own checkout, `<W>-lanes/<lane>`, made on first + use: an explicit `LANES_REPO` naming W is refused there (Amendment 23 S2, + S5; `f9e1449c:lanes-edit.sh:28132-28160`; lane 3, #165 6859073786). The + lane is named by `LANES_LANE`, as `run` sets it.""" + + def __init__(self, root: Path, estate: Estate, lanes_edit: Path, routed: bool = False): + self.root = root + self.home = root / "home" + self.home.mkdir(parents=True, exist_ok=True) + self.git_env = git_env(self.home) + self.origin = root / "origin.git" + self.checkout = root / "checkout" + git(root, "clone", "-q", "--bare", str(estate.origin), str(self.origin), + env=self.git_env) + git(root, "clone", "-q", str(self.origin), str(self.checkout), env=self.git_env) + self.c = git(self.origin, "rev-parse", "main", env=self.git_env).strip() + assert self.c == estate.c, "the twin is not at C" + agents = self.home / ".agents" + agents.mkdir(parents=True, exist_ok=True) + (agents / "workspace.yaml").write_text( + f"repository: {self.origin}\npath: {self.checkout}\n", encoding="utf-8") + fakebin = root / "fakebin" + fakebin.mkdir(parents=True, exist_ok=True) + (fakebin / "tmux").write_text("#!/bin/sh\nexit 1\n", encoding="utf-8") + (fakebin / "tmux").chmod(0o755) + for d in ("state", "config", "tmp"): + (root / d).mkdir(parents=True, exist_ok=True) + self.env = dict(self.git_env) + self.env.update(AGENT_PROTOCOL_ROOT=str(agents), TMPDIR=str(root / "tmp"), + XDG_STATE_HOME=str(root / "state"), + XDG_CONFIG_HOME=str(root / "config"), + CLAUDE_CONFIG_DIR=str(self.home / ".claude"), LANES_WORKSTATION=WS, + LANES_HOST="eagle", LANES_OS="linux", LANES_CONTAINER="none", + LANES_IN_CONTAINER="0", LANES_NO_GITHUB="1", + LANES_REPO=str(self.checkout), + PATH=str(fakebin) + os.pathsep + _masked_path()) + self.env.pop("LANES_INDEX", None) + self.env.pop("LANES_INDEX_CONFIG", None) + if routed: + self.env.pop("LANES_REPO") + self.env.update(LANES_ROUTE_WRITES="1") + self.lanes_edit = lanes_edit + + def run(self, argv: list, lane: str, **extra) -> subprocess.CompletedProcess: + env = dict(self.env, LANES_LANE=lane, **extra) + return subprocess.run(["bash", str(self.lanes_edit), *argv], capture_output=True, + encoding="utf-8", errors="replace", env=env, timeout=120, + cwd=str(self.checkout), check=False, stdin=subprocess.DEVNULL) + + def commits(self) -> list: + """The commits the twin pushed since C, oldest first.""" + out = git(self.origin, "rev-list", "--reverse", f"{self.c}..main", env=self.git_env) + return out.split() + + def render_set(self) -> dict: + return _origin_render_set(self.origin, self.git_env) + + def message(self) -> str: + return _raw_message(self.origin, self.git_env) + + +#: Files mode's `rename-lane` subject, "... the row, <log>, the handoff and +#: <aliases> in one commit" (`f9e1449c:lanes-edit.sh:30289`). +_RENAME_FILES_SUBJECT = re.compile( + r"^(LANES\(\S+\): RENAMED lane .+ the row, )(\S+), the handoff and (\S+) in one commit$", + re.M) + + +def _primary_message(verb: str, message: str) -> str: + """The journal message a primary write of `verb` composes, from its + files-mode twin's commit `message`: the same, but `rename-lane`'s, whose + handoff is not in the entry (Q13(a)), so T422 composes "... the row, + <log> and <aliases> in one register write; the handoff's move and stamp + follow in the lane's checkout (Q13(a))" (`f9e1449c:lanes-edit.sh:30293-30294`), + the message the design names (lane 3's ruling (A), #165 6859179515).""" + if verb != "rename-lane": + return message + named, n = _RENAME_FILES_SUBJECT.subn( + r"\1\2 and \3 in one register write; the handoff's move and stamp follow in " + r"the lane's checkout (Q13(a))", message, count=1) + assert n == 1, f"rename-lane: the twin's message has no files-mode subject: {message!r}" + return named + + +def _journal_since(db, seq: int) -> list: + return rows(db, f"SELECT seq, write_id, kind, verb, lane, message FROM journal " + f"WHERE seq > {seq} ORDER BY seq") + + +def _one_entry(db, before: int, proc: subprocess.CompletedProcess, what: str) -> dict: + """A write on primary that exited 0, and its one journal entry, at the old + head plus one.""" + assert proc.returncode == 0, ( + f"{what} on primary exited {proc.returncode} (L4-B4, L4-B8, L4-B13): " + f"{proc.stderr[-800:]}") + new = _journal_since(db, before) + assert len(new) == 1 and new[0]["seq"] == before + 1, ( + f"{what} on primary added {len(new)} journal entries after seq {before}, not one at " + f"{before + 1}: line R's lanes-edit.sh writes the files whatever mode= says (L4-B4, " + f"T414's seam): {new}") + return new[0] + + +def _rows_written_at(db, seq: int) -> list: + """Every register row whose last writer is the entry at `seq`, with the + mode it records: part N's five tables.""" + return rows(db, f"SELECT 'doc_lines' AS t, written_mode AS m FROM doc_lines " + f"WHERE written_seq = {seq} " + f"UNION ALL SELECT 'lanes', last_mode FROM lanes WHERE last_seq = {seq} " + f"UNION ALL SELECT 'log_lines', mode FROM log_lines WHERE seq = {seq} " + f"UNION ALL SELECT 'register_lines', mode FROM register_lines " + f"WHERE seq = {seq} " + f"UNION ALL SELECT 'object_holds', mode FROM object_holds WHERE seq = {seq}") + + +def _mirror(ws: PrimaryWrites, seq: int, out_dir: Path) -> dict: + """The pure renderer's scratch mirror at `seq`, its render set: {path: + bytes}. It writes nothing outside its four paths (and `lanes/STORE`).""" + proc, images = render_images(ws.copy, ws.index, seq, out_dir) + assert proc.returncode == 0, f"render --images --at {seq} exited {proc.returncode}: " \ + f"{proc.stderr}" + assert all(RENDER_SET.match(p) or p == STORE_PATH for p in images), ( + f"the renderer wrote outside its four paths: {sorted(images)}") + return _rendered_only(images) + + +@pytest.mark.parametrize("verb", list(W_VERBS)) +def test_each_write_leaves_the_mirror_byte_identical_to_a_full_render(pg, tmp_path, verb): + """AT-1's part W, the mirror: `lanes-edit.sh <verb>` on primary exits 0; + the journal gains exactly one entry, at the old head plus one, with a + `write_id` unique in the journal; the pure renderer's scratch mirror at + that seq equals the full render from SQL (`render_file` of every path in + `files`), path set and bytes, over `lanes/LANES.md`, `lanes/log/*.md`, + `lanes/aliases.tsv` and `lanes/archive/**`, and holds nothing outside + them; the write changed a rendered file; each UTC the write put on a line + is the database's, in whole seconds, between its clock read before the + write and after it (S6; D13). And D12 (GB section 4.3): the fake `git`'s + log holds no `fetch` (nor a `pull`) on primary that the verb itself + makes, for any verb. The renderer the write forks fetches origin, as each + pass does (Y:2839; AT-C8, TP:3187-3188), so a call with a `lanes-index + render --checkout` process above it is left out, by that process, never + by the call's argv, since the pass's read-back fetch has the same argv; + each one left out ran in the writing lane's checkout (lane 3, #165 + 6859073786). A control shows the test tells them apart by process. Fails + until L4-B4, L4-B8 and L4-B13.""" + argv, lane = W_VERBS[verb] + ws = PrimaryWrites(pg, tmp_path, W_PREPS.get(verb)) + before_head = head(pg) + before_ids = {r["write_id"] for r in rows(pg, "SELECT write_id FROM journal")} + before = _rendered_only(full_render(pg)) + clock_before = db_clock(pg) + proc = ws.run(argv, lane) + clock_after = db_clock(pg) + entry = _one_entry(pg, before_head, proc, verb) + seq = entry["seq"] + assert entry["write_id"] and entry["write_id"] not in before_ids, entry + assert rows(pg, f"SELECT count(*) AS n FROM journal " + f"WHERE write_id = '{entry['write_id']}'") == [{"n": 1}] + + # THE MIRROR: the scratch mirror at seq is the full render from SQL. + mirror = _mirror(ws, seq, tmp_path / "mirror") + full = _rendered_only(full_render(pg)) + _assert_same_files(mirror, full, f"{verb}: the mirror at seq {seq} and the full render") + assert mirror != before, f"{verb} changed no rendered file" + + # THE UTC: the database's clock, in whole seconds. + for path, line, utc in _stamped_utcs(before, mirror, argv): + assert UTC_RE.match(utc), f"{verb} wrote {utc!r}, not whole seconds, in {path}: {line!r}" + assert clock_before <= epoch_of(utc) <= clock_after, ( + f"{verb} wrote {utc} in {path}, outside the database's clock " + f"[{utc_of(clock_before)}, {utc_of(clock_after)}]: {line!r}") + + # D12: NO FETCH ON PRIMARY BY THE VERB ITSELF. The forked renderer's own + # fetches are left out by the process above them, each in the writing + # lane's checkout. + fetches = [call for call in ws.git_calls() if call["sub"] in ("fetch", "pull")] + own = [call["args"] for call in fetches if call["render"] is None] + assert own == [], f"{verb} fetched on primary (D12): {own}" + checkout = os.path.realpath(ws.lane_checkout(lane)) + astray = [call for call in fetches + if os.path.realpath(call["render"]) != checkout or call["where"] != checkout] + assert astray == [], ( + f"{verb}: its forked renderer fetched outside the writing lane's checkout " + f"{checkout} (D12): {astray}") + _d12_control(tmp_path / "d12-control", checkout) + + +@pytest.mark.parametrize("verb", list(TWIN_VERBS)) +def test_each_write_matches_its_files_mode_twin_byte_for_byte(pg, tmp_path, verb): + """AT-1's part W, the twin: `lanes-edit.sh <verb>` on primary exits 0 with + one journal entry; its files-mode twin, a clone of W's origin at C under + its own `$HOME`, makes the same verb, exits 0 and pushes one commit; the + scratch mirror at the entry's seq equals the render set on the twin's + origin, path set and bytes, every UTC masked in both (open point 4); and + the entry's message is the twin's commit message, byte for byte, or but + for the one LF git ends a stored message with; for `rename-lane`, the + message the design names under Q13(a), `_primary_message`'s. GB section 4.3's + `start-record` (lane 4's T427, L4-B9) is `[start-record]`, a resume of + repoA-2 in both modes, whose twin runs once more, in a second clone at C, + under `LANES_ROUTE_WRITES=1` with `LANES_REPO` unset, through the lane's + own checkout (Amendment 23 S2, S5), with the same render set and message. Fails + until L4-B4, L4-B8 and L4-B13; `[start-record]` until L4-B9 too.""" + argv, lane, extra = TWIN_VERBS[verb] + ws = PrimaryWrites(pg, tmp_path, W_PREPS.get(verb)) + twin = FilesTwin(tmp_path / "twin", ws.estate, ws.lanes_edit) + routed = (FilesTwin(tmp_path / "twin-routed", ws.estate, ws.lanes_edit, routed=True) + if verb == "start-record" else None) + before_head = head(pg) + proc = ws.run(argv, lane, **extra) + entry = _one_entry(pg, before_head, proc, verb) + mirror = _mirror(ws, entry["seq"], tmp_path / "mirror") + + for label, files_twin in (("the twin", twin), ("the routed twin", routed)): + if files_twin is None: + continue + done = files_twin.run(argv, lane, **extra) + assert done.returncode == 0, ( + f"{label}'s {verb} in files mode exited {done.returncode}: {done.stderr[-800:]}") + assert len(files_twin.commits()) == 1, ( + f"{label}'s {verb} pushed {len(files_twin.commits())} commits, not one") + _assert_same_files(_utc_masked(mirror), _utc_masked(files_twin.render_set()), + f"{verb}: the mirror and {label}'s files, every UTC masked") + message = _primary_message(verb, files_twin.message()) + bare = message[:-1] if message.endswith("\n") else message + assert entry["message"] in (message, bare), ( + f"{verb}: the journal's message {entry['message']!r} is not {label}'s commit " + f"message, as primary composes it, {message!r}") + + +@pytest.mark.parametrize("verb", list(W_VERBS)) +def test_each_write_reads_back_primary_as_the_mode_that_wrote_it_last(pg, tmp_path, verb): + """AT-1's part W, the rows (P183-188): after `lanes-edit.sh <verb>` on + primary exits 0 with one journal entry, every register row that entry + wrote last (`doc_lines`, `lanes`, `log_lines`, `register_lines` and + `object_holds`, by its seq) reads `primary` as the mode that wrote it, + and there is at least one. Fails until L4-B4, L4-B8 and L4-B13.""" + argv, lane = W_VERBS[verb] + ws = PrimaryWrites(pg, tmp_path, W_PREPS.get(verb)) + before_head = head(pg) + proc = ws.run(argv, lane) + entry = _one_entry(pg, before_head, proc, verb) + touched = _rows_written_at(pg, entry["seq"]) + assert touched, f"{verb}'s entry at seq {entry['seq']} wrote no register row" + assert {r["m"] for r in touched} == {"primary"}, ( + f"{verb}'s rows do not all read primary as the mode that wrote them last: {touched}") + + +#: AT-1's `rename-lane` handoffs: a handoff named for its lane, under its +#: estate's folder, as `lane-start` computes it, and where the rename moves it. +RL_HANDOFF = "handoffs/eagle/session-handoff-2026-10-01-lane-repoA-2.md" +RL_MOVED = "handoffs/eagle/session-handoff-2026-10-01-lane-repoA-3.md" +#: A handoff Rule 3's stamp can go into: a header line, a blank line, a body. +RL_TEXT = b"# handoff of lane repoA-2\n\nwhat the lane left\n" +#: A handoff that cannot take the stamp without a byte of it rewritten: one +#: line and no LF, so the stamp would join its only line. +RL_UNSTAMPABLE = ("handoffs/eagle/session-handoff-2026-10-01-lane-repoA-1.md", + b"# handoff of lane repoA-1, with no LF") +#: The rename's arguments, its old lane and its new. +RL_ARGV = ["rename-lane", "repoA-2", "repoA-3", "test 1", "--no-github"] + + +def _rl_stamped(old: bytes, new: bytes) -> bool: + """`new` is `old` with exactly one line put in, which names both lanes: + Rule 3's stamp (Amendment 16(d)).""" + a, b = old.split(b"\n"), new.split(b"\n") + return len(b) == len(a) + 1 and any( + b[:i] + b[i + 1:] == a and b"repoA-2" in b[i] and b"repoA-3" in b[i] + for i in range(len(b))) + + +def test_rename_lane_commits_the_transaction_then_a_rerun_makes_only_the_move(pg, tmp_path): + """AT-1's part W, Brett's row 18 (comment 6721583757), with GB section + 4.3's `rename-lane` cases (R29): on primary the transaction comes first, + and the handoff's move and Rule 3 stamp follow it as the verb's + after-COMMIT tail (Q13(a); Y:5092; B14 tasks:1270-1279). + + A HANDOFF THAT CANNOT BE STAMPED refuses before anything is sent (Y:5138): + repoA-1's, one line with no LF; its rename exits non-zero with no commit + call, the journal and origin as they were. + + THEN repoA-2's, with the move made to fail after the commit (its folder in + repoA-2's `<c>` read-only): the rename exits 0 with one WARNING, the move + owed; it prints `register seq <s>`, the entry's seq; the journal holds the + rename once; the handoff paths left the change set (no `handoffs/` path + among the entry's files), and the row's handoff column names the new path + in the transaction; origin still holds the handoff at its old path. A + rerun, `LANES_LANE=repoA-3 lanes-edit.sh rename-lane repoA-2 repoA-3` + (batch c Q71 and Q74), exits 0, adds no journal entry, and makes the move: + origin holds the handoff at the new path, stamped, and not at the old. + Fails until L4-B8 (lane 4's T422), L4-B4 and L4-B13.""" + prep = _w_with_handoffs({"repoA-2": (RL_HANDOFF, RL_TEXT), "repoA-1": RL_UNSTAMPABLE}) + ws = PrimaryWrites(pg, tmp_path, prep) + origin, env = ws.estate.origin, ws.estate.env + + # A HANDOFF THAT CANNOT BE STAMPED: refused before anything is sent. + before_head, refs = head(pg), _origin_paths(origin, env) + refused = ws.run(["rename-lane", "repoA-1", "repoA-9", "test 1", "--no-github"], "repoA-1") + assert refused.returncode != 0, ( + f"a rename of a handoff that cannot take Rule 3's stamp exited 0 (Y:5138): " + f"{refused.stderr[-800:]}") + assert ws.commit_calls() == [], f"the refusal sent a commit call: {ws.commit_calls()}" + assert head(pg) == before_head and _origin_paths(origin, env) == refs + + # THE MOVE MADE TO FAIL AFTER THE COMMIT. + folder = ws.lane_checkout("repoA-2") / Path(RL_HANDOFF).parent + folder.chmod(0o555) + try: + if os.access(str(folder), os.W_OK): + pytest.skip("this user writes into a read-only directory, so the move cannot be " + "made to fail") + first = ws.run(RL_ARGV, "repoA-2") + finally: + folder.chmod(0o755) + entry = _one_entry(pg, before_head, first, "rename-lane, its move made to fail") + said = first.stdout + first.stderr + assert re.search(rf"\bregister seq {entry['seq']}\b", said), ( + f"rename-lane on primary did not print `register seq {entry['seq']}`: {said[-800:]}") + assert first.stderr.count("WARNING") == 1, ( + f"a failed move ends 0 with ONE WARNING, the move owed: {first.stderr[-1200:]}") + entry_files = rows(pg, f"SELECT path FROM journal_files WHERE seq = {entry['seq']}") + assert not [r for r in entry_files if r["path"].startswith("handoffs/")], ( + f"the handoff paths did not leave the change set: {entry_files}") + lanes_md = _rendered_only(full_render(pg))["lanes/LANES.md"].decode("utf-8") + row = next((line for line in lanes_md.split("\n") if line.startswith("| `repoA-3`")), "") + assert f"| {RL_MOVED} |" in row, f"the row's handoff column is not the new path: {row!r}" + paths = _origin_paths(origin, env) + assert RL_HANDOFF in paths and RL_MOVED not in paths, ( + "the failed move reached origin, or the handoff left its old path") + + # THE RERUN: no entry, only the move. + again = ws.run(RL_ARGV, "repoA-3") + assert again.returncode == 0, f"the rerun exited {again.returncode}: {again.stderr[-800:]}" + assert _journal_since(pg, entry["seq"]) == [], "the rerun added a journal entry" + paths = _origin_paths(origin, env) + assert RL_MOVED in paths and RL_HANDOFF not in paths, ( + f"the rerun did not make the move on origin: " + f"{sorted(p for p in paths if p.startswith('handoffs/'))}") + moved = _git_bytes(origin, env, "cat-file", "blob", f"main:{RL_MOVED}") + assert _rl_stamped(RL_TEXT, moved), f"the moved handoff is not stamped: {moved!r}" + + +def test_a_caller_composed_utc_and_log_paused_utc_stay_as_written(pg, tmp_path): + """AT-1's part W: a UTC the caller wrote into the line, `append-line`'s + `HOLD` line, and `log PAUSED --utc`'s, Amendment 17's late PAUSED, are + stored and rendered byte for byte, never replaced by the database's + clock: after each write on primary (exit 0, one journal entry), the line + is in `doc_lines`, in the full render from SQL and in the scratch mirror + at the entry's seq, carrying the caller's UTC, which is not the + database's clock. Fails until L4-B4, L4-B8 and L4-B13.""" + ws = PrimaryWrites(pg, tmp_path) + hold = (f"HOLD {EM} lane repoA-2 ({WS}), window w, 2026-11-02T03:04:05Z: " + f"opensoft/repoB main {TIP} for test 1's own UTC") + late = "2026-11-01T09:08:07Z" + paused = re.compile(rf"^PAUSED {EM} lane repoA-1, session [^,]+@{WS}, {late}, lane:repoA-1" + rf"(?: |$)") + for what, argv, lane, path, utc, wanted in ( + ("append-line's HOLD", ["append-line", hold], "repoA-2", "lanes/LANES.md", + "2026-11-02T03:04:05Z", lambda line: line == hold), + ("log PAUSED --utc", ["log", "PAUSED", "lane:repoA-1", "--utc", late, + "parked late for test 1"], "repoA-1", "lanes/log/repoA-1.md", + late, lambda line: bool(paused.match(line)))): + assert abs(db_clock(pg) - epoch_of(utc)) > 3600, "the caller's UTC is the clock's" + before_head = head(pg) + proc = ws.run(argv, lane) + entry = _one_entry(pg, before_head, proc, what) + stored = [r["text"] for r in rows(pg, f"SELECT text FROM doc_lines WHERE path = '{path}' " + f"AND written_seq = {entry['seq']}")] + assert any(wanted(text) for text in stored), ( + f"{what}: no line the write stored carries the caller's UTC as written: {stored}") + for label, files in (("the full render", _rendered_only(full_render(pg))), + ("the mirror", _mirror(ws, entry["seq"], + tmp_path / f"mirror-{entry['seq']}"))): + lines = files[path].decode("utf-8").split("\n") + assert any(wanted(line) for line in lines), ( + f"{what}: {label}'s {path} holds no line with the caller's UTC as written") + + +def test_on_primary_a_write_does_not_nudge_a_register_sync(tmp_path): + """AT-1's FP case (the delta's "The post-write nudge does not re-index the + mirror into its own source"; FR-027; T416, "The nudge: `index_nudge`'s + register `sync` is suppressed on primary. Its inventory nudge stays"): a + `log RESUMED` on a `mode=primary` workstation whose `lanes-index` is the + contract's stub (T207), beside a copy of `lanes-edit.sh`, `repos.tsv` and + `lane-start` (CLI4.5 section 6's copy rule) and first on `PATH`, where + `index_nudge` finds it, its register holding C's render set. The write + exits 0 and is a primary write (the stub's log holds its `register + commit`); then the stub's log holds no register `sync` (`sync` with no + `--source`, or one naming the register), and holds the inventory's, + `sync --source inventory`, which a `RESUMED`'s lifecycle follow leaves + (`LANES_LANE_STATE_ROOT` gives it a control root). The nudges are + detached forks, so the case waits for the inventory's, 30 s at most, and + one second more. No engine. Fails until L4-B13 (T416's nudge) and L4-B4: + on line R's V-round4 the write runs files mode, exits 0 and makes no + `register commit`.""" + code = tmp_path / "code" + code.mkdir() + for name in ("lanes-edit.sh", "repos.tsv", "lane-start"): + shutil.copy2(str(REPO / name), str(code / name)) + fakebin = tmp_path / "fakebin" + estate, env, _source = workspace(tmp_path / "ws", fakebin) + contract_stub(code, register={p: t for p, t in estate.files.items() if RENDER_SET.match(p)}) + argv_log = code / "lanes-index.argv" + dead = tmp_path / "dead" + dead.mkdir() + host = quote(dead.as_posix(), safe="") + (tmp_path / "conf").mkdir() + conf = primary_config(tmp_path / "conf" / "lanes-index.conf", + f"postgresql://{LOGIN_WRITER}@{host}:5432/lanes_t240", + f"postgresql://{LOGIN_READER}@{host}:5432/lanes_t240") + env.update(LANES_INDEX_CONFIG=str(conf), LANES_LANE="repoA-2", + LANES_LANE_STATE_ROOT=str(tmp_path / "lane-state"), + PATH=str(code) + os.pathsep + env["PATH"]) + env.pop("LANES_INDEX", None) + real = Path(os.path.realpath(estate.checkout)) + lane_c = real.parent / f"{real.name}-lanes" / "repoA-2" + lane_c.parent.mkdir(parents=True, exist_ok=True) + git(lane_c.parent, "clone", "-q", str(estate.origin), str(lane_c), env=estate.env) + + proc = subprocess.run(["bash", str(code / "lanes-edit.sh"), *W_VERBS["log-resumed"][0]], + capture_output=True, encoding="utf-8", errors="replace", env=env, + timeout=120, cwd=str(estate.checkout), check=False, + stdin=subprocess.DEVNULL) + assert proc.returncode == 0, ( + f"log RESUMED on primary exited {proc.returncode} (L4-B4, L4-B13): " + f"{proc.stderr[-800:]}") + + def calls() -> list: + if not argv_log.exists(): + return [] + return [json.loads(x) for x in argv_log.read_text(encoding="utf-8").splitlines() if x] + + assert any(c[:2] == ["register", "commit"] for c in calls()), ( + f"the write made no `register commit`, so it was no primary write: {calls()}") + inventory = ["sync", "--source", "inventory"] + deadline = time.monotonic() + 30 + while inventory not in calls() and time.monotonic() < deadline: + time.sleep(0.1) + time.sleep(1) + syncs = [c for c in calls() if c and c[0] == "sync"] + register_syncs = [c for c in syncs if c != inventory] + assert register_syncs == [], ( + f"a primary write nudged a register sync, which re-indexes the mirror into its own " + f"source (T416): {register_syncs}") + assert inventory in syncs, f"the inventory's nudge did not run: {calls()}" + + +def test_rename_lane_commits_the_transaction_then_its_move_on_primary_takes_no_bytecode_to_to( + pg, tmp_path): + """The move's bytecode on primary (R-F13c-23; lane 3's batch 8, Q32, as + lane 3's batch c corrects it, #165 6807881675, Q55 and Q56; #162; B15 text + (2) for F13d:502): `rename-lane` on primary moves a handoff whose folder + also tracks a pre-#162 `__pycache__` file and a tool-cache path + (`.mypy_cache`). The rename exits 0 with one journal entry; the move + renames that one handoff inside its folder, and its commit, the one commit + on origin that changes a path under `handoffs/`, holds only the handoff's + D at `<from>` and A at `<to>`; the folder's other tracked paths stay in + `<c>`'s index and on origin as they were; no note names them; and T420's + backstop passes the push (origin holds the move). The files-mode twin + moves as today: its rename exits 0, and its origin holds the handoff at + `<to>` alone, with the folder's other paths kept. Fails until lane 4's + T422 lands, with L4-B4 and L4-B13.""" + bytecode = {"handoffs/eagle/__pycache__/notes.cpython-312.pyc": b"\x00pyc, before #162", + "handoffs/eagle/.mypy_cache/3.12/notes.meta.json": b"{}\n"} + ws = PrimaryWrites(pg, tmp_path, _w_with_handoffs({"repoA-2": (RL_HANDOFF, RL_TEXT)}, + bytecode)) + twin = FilesTwin(tmp_path / "twin", ws.estate, ws.lanes_edit) + origin, env = ws.estate.origin, ws.estate.env + lane_c = ws.lane_checkout("repoA-2") + base = git(origin, "rev-parse", "main", env=env).strip() + kept_on_origin = {p: b for p, b in _origin_paths(origin, env).items() if p in bytecode} + kept_in_c = git(lane_c, "ls-files", "-s", "--", *bytecode, env=env) + assert len(kept_on_origin) == 2 and len(kept_in_c.splitlines()) == 2 + + before_head = head(pg) + proc = ws.run(RL_ARGV, "repoA-2") + _one_entry(pg, before_head, proc, "rename-lane over a folder that tracks bytecode") + moves = git(origin, "log", "--format=%H", f"{base}..main", "--", "handoffs", + env=env).split() + assert len(moves) == 1, f"{len(moves)} commits on origin change handoffs/, not one: {moves}" + changed = git(origin, "diff-tree", "--no-commit-id", "-r", "--no-renames", "--name-status", + moves[0], env=env).split("\n") + assert sorted(x for x in changed if x) == sorted([f"D\t{RL_HANDOFF}", f"A\t{RL_MOVED}"]), ( + f"the move's commit holds more than the handoff's D and A: {changed}") + assert {p: b for p, b in _origin_paths(origin, env).items() if p in bytecode} == \ + kept_on_origin, "the folder's other tracked paths changed on origin" + assert git(lane_c, "ls-files", "-s", "--", *bytecode, env=env) == kept_in_c, ( + "the folder's other tracked paths left <c>'s index") + said = proc.stdout + proc.stderr + assert "__pycache__" not in said and ".mypy_cache" not in said, ( + f"a note names the folder's bytecode or tool-cache paths: {said[-800:]}") + + done = twin.run(RL_ARGV, "repoA-2") + assert done.returncode == 0, f"the files-mode twin's rename exited {done.returncode}: " \ + f"{done.stderr[-800:]}" + theirs = _origin_paths(twin.origin, twin.git_env) + assert RL_MOVED in theirs and RL_HANDOFF not in theirs, "the twin did not move the handoff" + assert {p: b for p, b in theirs.items() if p in bytecode} == kept_on_origin, ( + "the twin's move changed the folder's other tracked paths") + + +#: N1's handoff paths (REV422c N1; batch c Q56): a row whose handoff is at a +#: path with a `venv/` part, and one whose handoff is at a path with a +#: `__pycache__/` part, each named for its lane: {lane: (path, its new name)}. +RL_CACHE_PARTS = { + "repoA-2": ("handoffs/venv/session-handoff-2026-10-01-lane-repoA-2.md", "repoA-3", "venv"), + "repoA-1": ("handoffs/eagle/__pycache__/session-handoff-2026-10-01-lane-repoA-1.md", + "repoA-9", "__pycache__"), +} + + +def test_rename_lane_commits_the_transaction_only_where_its_handoffs_path_has_no_cache_part_on_primary( # noqa: E501 + pg, tmp_path): + """N1's refusal (REV422c N1; lane 3's batch c, #165 6807881675, Q56; B15 + text (2) for F13d:502; Y:5138, "a handoff that cannot be stamped refuses + before anything is sent"): on primary, a row whose handoff is at a path + with a `venv/` part, and one whose handoff is at a path with a + `__pycache__/` part (each tracked in the lane's `<c>`, committed there + before #162), each refuse 2 before the seam: stderr names the part; the + run sent the register a read, the attempt's snapshot, so the refusal is + primary's, made in the attempt's child before the seam (files mode's own + #162 refusal of the same move sends nothing, and exits 2 as well); no + commit call is sent; no register line is written (the journal's head and + the rendered files as they were); and no move is made (origin, and the + handoff in `<c>`, as they were). Fails until lane 4's T422 lands, with + L4-B4 and L4-B13: it passes on T422 `eda2411` over line R's V-round4.""" + prep = _w_with_handoffs({lane: (path, f"# handoff of lane {lane}\n\nbody\n".encode("ascii")) + for lane, (path, _new, _part) in RL_CACHE_PARTS.items()}) + ws = PrimaryWrites(pg, tmp_path, prep) + origin, env = ws.estate.origin, ws.estate.env + for lane, (path, new, part) in RL_CACHE_PARTS.items(): + before_head, before_files = head(pg), _rendered_only(full_render(pg)) + paths = _origin_paths(origin, env) + handoff = ws.lane_checkout(lane) / path + held = handoff.read_bytes() + sent_before = len(ws.shim_calls()) + proc = ws.run(["rename-lane", lane, new, "test 1", "--no-github"], lane) + sent = ws.shim_calls()[sent_before:] + assert proc.returncode == 2, ( + f"rename-lane {lane} on primary, its handoff at {path}, exited {proc.returncode}, " + f"not 2 (N1; lane 4's T422): {proc.stderr[-800:]}") + assert part in proc.stderr, f"the refusal does not name {part!r}: {proc.stderr!r}" + assert sent, ( + f"rename-lane {lane} sent the register nothing, so its 2 is not primary's refusal " + f"after the attempt's snapshot (N1; lane 4's T422; L4-B4): {proc.stderr[-800:]}") + assert not [c for c in sent if "commit_write(" in (c.get("stdin") or "")], ( + f"the refusal sent a commit call: {sent}") + assert head(pg) == before_head and _rendered_only(full_render(pg)) == before_files, ( + "the refusal wrote a register line") + assert _origin_paths(origin, env) == paths and handoff.read_bytes() == held, ( + "the refusal moved the handoff") + + +# ============================================================ phase G: T270 +# +# TEST 1'S PHASE-G PART (lane 2's T270, its one case in this module; AT-1, the +# test plan's line 606; the rest of T270 is test 5 and C8, in +# `test_sql_register_renderer_git.py`): the same verbs as part W, on the same +# workstation, with the mirror read from the bare origin's `main`, by object, +# after the renderer the write forks (T416's `render --checkout <c>`, lane 3's +# T320 to T323) has pushed it. The wait is open point 8's first: `lanes-index +# status`, every 100 ms, 30 s at most, until its lag is 0 (`lag: 0 +# seq(s)`, lane 1's `status_register`). `status` reads `m` from `origin/<b>` as +# last fetched in W's checkout, `workspace-root`'s answer, `workspace.yaml`'s +# `path:`, whatever `LANES_REPO` names (`7893339348a5:lanes-index:20357`, +# `:1400-1412`; `7893339348a5:lanes-edit.sh:1411-1416`), and fetches nothing +# (`_register_mirror`); the render pushes from the writing lane's `<c>`. So +# each poll comes after the harness's own fetch of W, `git -C <W> fetch -q +# origin main`, with plain git, never through `_logging_git`: lane 3's ruling +# (a), #165 6833830078, as RG's `wait_lag_0` (T270e) and the drill's have it. +# It fails until T320 to T323, T325 and L4-B13 land. +# +# ITS ESTATE, AND NO OTHER, PUTS THE CUTOVER'S MARKER COMMIT ON W'S ORIGIN +# (T270's line, tasks:2477; lane 2, #165 6866688575; lane 3, #165 +# 6866808028): `PrimaryWrites(marker_on_origin=True)`, C plus `lanes/STORE` +# with the cutover entry's bytes, `Register-Seq: <cut>` in the last paragraph, +# made before `record_marker` and recorded by it. On a made-up sha and an +# origin at C the forked render finds no `m`, and renders and pushes nothing +# (Y:2845-2847), and `status`'s lag is unknown at every poll. With the commit +# `m` is the cut and the lag 0 before the write, which commits seq cut + 1 +# before the poll starts, so a lag of 0 can then only be the render's push, +# and a lag that `status` cannot read for want of `m` fails at once. + +#: `status`'s lag line when the mirror has caught up (`status_register`). +STATUS_LAG_ZERO = re.compile(r"^\s*lag:\s+0 seq\(s\)", re.M) +#: `status`'s lag line when no `Register-Seq` is found (`status_register`). +STATUS_LAG_NO_M = re.compile(r"^\s*lag:\s+unknown, since the mirror's m cannot be read", re.M) + + +def _checkout_state(checkout: Path, env: dict) -> tuple: + """A checkout's HEAD, its index's digest and `status --porcelain=v1 -uall`.""" + index = checkout / ".git" / "index" + return (git(checkout, "rev-parse", "HEAD", env=env), + hashlib.sha256(index.read_bytes()).hexdigest() if index.exists() else "-", + git(checkout, "status", "--porcelain=v1", "-uall", env=env)) + + +def _status_after_fetching_w(ws: PrimaryWrites) -> subprocess.CompletedProcess: + """`status` in W's checkout, after the harness's own fetch of W, with plain + git (the estate's environment, no `_logging_git` on its `PATH`).""" + git(ws.estate.checkout, "fetch", "-q", "origin", "main", env=ws.estate.env) + return run_index(ws.copy, ["status"], ws.env, cwd=ws.estate.checkout) + + +def _wait_for_the_render(ws: PrimaryWrites, ceiling: float = 30.0) -> None: + """Open point 8's first wait: a bounded poll of `status`, each after a + fetch of W, until its lag is 0. Origin carries `m` from the marker commit + on, so a lag unknown for want of `m` fails at once.""" + deadline = time.monotonic() + ceiling + last = "" + while True: + proc = _status_after_fetching_w(ws) + if STATUS_LAG_ZERO.search(proc.stdout): + return + last = f"exit {proc.returncode}: {proc.stdout[-700:]}{proc.stderr[-300:]}" + assert not STATUS_LAG_NO_M.search(proc.stdout), ( + f"status found no Register-Seq on W's origin/main, though origin carries the " + f"marker commit; status said {last}") + assert time.monotonic() < deadline, ( + f"the forked render did not bring the lag to 0 within {ceiling:.0f} s (T320 to " + f"T323, L4-B13); status said {last}") + time.sleep(0.1) + + +@pytest.mark.parametrize("verb", list(W_VERBS)) +def test_the_mirror_on_origin_equals_a_full_render_after_each_write(pg, tmp_path, verb): + """AT-1's part G: `lanes-edit.sh <verb>` on primary exits 0 with one + journal entry; once the forked render has brought `status`'s lag to 0 + (open point 8), origin has gained exactly one commit, whose + `Register-Seq:` trailer, in its message's last paragraph in `Key: value` + form, is the entry's seq, so `git log + --format='%(trailers:key=Register-Seq,valueonly)'` reads it (AT-F11); the + render set on origin's `main`, read by object, equals the full render from + SQL, path set and bytes; and W's checkout and each lane's `<c>` keep their + HEAD, index and working tree (Q27(a), the private-index form). Origin + starts at the cutover's marker commit on C, the sha `record_marker` + recorded, where `status`, after a fetch of W, reads a lag of 0 before the + write, and the render commit's parent is that marker commit + (tasks:2477). Fails until T320 to T323, T325 and L4-B13, with L4-B4 and + L4-B8.""" + argv, lane = W_VERBS[verb] + ws = PrimaryWrites(pg, tmp_path, W_PREPS.get(verb), marker_on_origin=True) + origin, env = ws.estate.origin, ws.estate.env + base = git(origin, "rev-parse", "main", env=env).strip() + recorded = rows(pg, "SELECT marker_commit FROM register_switch")[0]["marker_commit"] + assert base == recorded and git(origin, "rev-parse", f"{base}^", env=env).strip() == \ + ws.estate.c, (f"origin's main is {base}, not the marker commit {recorded} on C " + f"{ws.estate.c}") + status = _status_after_fetching_w(ws) + assert STATUS_LAG_ZERO.search(status.stdout), ( + f"before the write, status after a fetch of W did not read a lag of 0 from the " + f"marker commit: exit {status.returncode}: {status.stdout[-700:]}" + f"{status.stderr[-300:]}") + checkouts = {str(c): _checkout_state(c, env) for c in ws.checkouts()} + before_head = head(pg) + proc = ws.run(argv, lane) + entry = _one_entry(pg, before_head, proc, verb) + _wait_for_the_render(ws) + + gained = git(origin, "rev-list", f"{base}..main", env=env).split() + assert len(gained) == 1, f"origin gained {len(gained)} commits, not one: {gained}" + assert git(origin, "rev-parse", f"{gained[0]}^", env=env).strip() == base, ( + "the render commit's parent is not the marker commit") + trailer = git(origin, "log", "-1", "--format=%(trailers:key=Register-Seq,valueonly)", + gained[0], env=env).strip() + assert trailer == str(entry["seq"]), ( + f"the render commit's Register-Seq trailer reads {trailer!r}, not {entry['seq']}") + _assert_same_files(_origin_render_set(origin, env), _rendered_only(full_render(pg)), + f"{verb}: origin's main and the full render") + assert {str(c): _checkout_state(c, env) for c in ws.checkouts()} == checkouts, ( + "the render changed a lane checkout's HEAD, index or working tree") diff --git a/tests/test_sql_register_renderer_git.py b/tests/test_sql_register_renderer_git.py new file mode 100644 index 00000000..37b74dab --- /dev/null +++ b/tests/test_sql_register_renderer_git.py @@ -0,0 +1,3854 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Feature 007's test 5 and AT-C8: the renderer's git half and its push +(L2-G1; L2-G5's C8; AT-5; AT-C8; T270; FR-044, FR-045, FR-046, FR-059) +(opensoft/openRepoTools#165). + +T270 writes 25 tests: AT-5's 23 and AT-C8's one are here (TP:1016-1246, +TP:3173-3196, at the test plan `8702b70a`). Its 25th, test 1's part G, +`test_the_mirror_on_origin_equals_a_full_render_after_each_write`, is in +`test_sql_register_render.py`, which line W4b owns; it is not here. Twenty +more, at the end, test no AT case: they are the fault-path regressions of +this module's own clean-up (lane 3's Codex reviews of code PR 97 at +`6d479418`, SHOULDs 1, 3 and 4, at `18529e5a`, BLOCKING and SHOULDs 1, 3 +and 4, and at `46cac748`, BLOCKING and SHOULDs 1 to 7; the coordinator's +#165 6934112467 and his three points, #165 6938182757). + +THE ESTATE (AT-5, "Fixture"; AT-C8, "Fixture"). Each case's database is +`pg_imported` (T227b): test 7's register imported at seq 0, the switch at +`files`. Its origin is a bare copy of the session's `imported_register` +origin, at C, so a case that pushes pushes to its own. The estate goes to +`primary` by AT-LR006's route (TP:4610-4615), as T304's own test does: a +`cutover` entry at seq 1 through `commit_write`, as REGISTER-WRITER, which +creates `lanes/STORE` with D21's fields; the marker commit, C plus that +`lanes/STORE` (SQL's own `render_file` of it), with `Register-Seq: 1`, +pushed to origin's `main` by hand; then `record_marker`. That is the open +point 27 form, "AT-5's `files` case pushes the marker commit by hand and +needs only the renderer's side", taken for `primary` too, so no case here +waits for lane 3's T327 (the cutover's own push). `n`, the head after the +cutover, is 1. Lane checkouts are clones of that origin, each with its own +`$HOME`, `workspace.yaml` naming a view of it, and `LANES_REPO` at it (test +7's `Workspace` form). That view is W. A lane whose writes fork the +renderer also has its own register checkout `<c>`, `<W>-lanes/<lane>/`, +made by `lanes-edit.sh lane-checkout <lane> --create`, since on primary +each write goes through it whatever `LANES_REPO` says, and its fork +renders there (T270e; `RenderEstate.own_checkout`). + +ENTRIES "WRITTEN THROUGH THE WRITE PATH" (TP:1055-1056) come two ways: +- by `commit_write` as REGISTER-WRITER, the write path's SQL half (T107), + where the case then starts the renderer itself, as a fork starts it, + `lanes-index render --checkout <c>` in a session of its own. Each of + these cases tests the renderer, never the writer or the fork; +- by `lanes-edit.sh log NOTED` on `primary` through T203's flipped copy, + whose fork starts the renderer (lane 4's T415 and T416, L4-B13), where + the oracle is about writers and forks (the writer- and fork-side cases, + at the end). + +TEST 5'S `git` WRAPPER (TP:1059-1082; open point 8, TP:8792-8812) is first +on the `PATH` of every `lanes-index` and `lanes-edit.sh` run here. It logs +each call as a JSON line: its subcommand, argv, pid, the pid above it (the +renderer) with that process's start token, field 22 of its +`/proc/<pid>/stat`, the repository it runs in, the time, and the environment's +`GIT_SSH_COMMAND`, `GIT_CONFIG_GLOBAL`, `GIT_CONFIG_NOSYSTEM`, +`SSH_AUTH_SOCK`, `LANES_NO_FETCH` and `GIT_INDEX_FILE`. Before anything +else each call writes its launch record, its pid and start token, to +`git-wrapper.started`, which `arm()` never resets. Its arms, each on +one subcommand, and on one repository where `where` names it: `hold` on a +FIFO (re-armed per call, `times` bounding it), where an abort release +(`_let_go`'s `abort`) ends the call with no git; `kill`, SIGKILL to the +renderer's process group, member by member through pidfds, each pinned by +the case's identity (`IDENTITY`, the nonce in the estate's environment), +after leaving `<GIT_INDEX_FILE>.lock` where `index_lock` asks, as git +inside `read-tree` leaves it; `fail`, exit 1; +`reject`, git's non-fast-forward refusal with exit 1, N times, then +disarmed; `stall`, a sleep before the real git. `render_only` limits an +arm to the calls of a `lanes-index render --checkout`, by the argv of the +process above the call (`/proc/<pid>/cmdline`, read in memory), which the +log keeps as `render`, true or false. `redirect` sends a +`fetch` or `push` of a GitHub URL to the bare origin in its place. +Section 3.2's `psql` shim is beside it, handing every call to the +engine's own `psql` by its path. + +THE PATH: every directory of the caller's `PATH` is kept, in its place; one +that holds a `psql`, a `lanes-index` or a `pg_` name is swapped for a +private mirror without them (`_masked_path`, lane 2's mask policy, as LX's +T253e has it). The case's own `psql` is the shim, in the estate's `bin`. + +THE WAITS. A case that starts the renderer itself waits for its exit. A +render forked by a write is waited for by open point 8's two waits, and no +other: a poll of `status` every 100 ms until its lag is 0, under 30 s, +each poll after the harness's own fetch of the W `status` reads; or, +where the lag must stay above 0, a wait for every renderer pid the wrapper +logged after the write to exit. + +WHAT EACH FAILS UNTIL. Every case fails until lane 3's T320 to T323 (the +push, the lock and its handshake, the pass, its bounds); line R holds them +at `refs/l1/V-round4`. `test_six_lost_races_leave_the_last_write_for_the_ +next_write_or_reconcile`, which T325's verify selects by `reconcile`, also +fails until T325, at its own assertion: until then `reconcile` on `primary` +is T117's read-only check. The cases whose writes fork the renderer, at the end, +also fail until lane 4's T415 and T416 (L4-B13). Every case is RE: without +PostgreSQL 16 it skips with T205's banner. + +COPIED, NEVER SHARED (lane 2's rule for wave 12): `_masked_path` from line +LX's T253e (`tests/test_sql_register_landing_expired.py`); `_rows`, the +`Workspace` form of a lane checkout, and T203's flipped copy with +`lanes-edit.sh` beside it (`flipped_indexer`) from line W3a's +`tests/test_sql_register_import.py`; the cutover entry and the commit call +from line RB's `tests/test_sql_register_rollback.py`; `_open_when_held` +from the same; `_stats` from the import module. + +READINGS, NOT FOUND IN A CONTRACT: +- AT-LR006'S ROUTE to `primary`, and the marker commit pushed by hand, as + above. +- "WRITTEN THROUGH THE WRITE PATH" is read as the commit call alone where + the oracle is the renderer's, so those cases start the renderer + themselves. The six-lost-races case is one: the renderer that loses six + races is started as a fork starts it, for its one write. +- `reconcile` "in the given checkout" (B14 tasks:1531) is read as + `lanes-index reconcile` run in the lane's checkout, its workspace root, + with the `mode=primary` configuration, and no `--checkout`. +- AT DEPTH 0 "no `--skip`" (TP:1198-1199) is read as no page after the + first: the walk's one `log` call may say `--skip 0`, as line R's does. +- THE COMMIT'S MESSAGE: "each message equals its journal entry's" is read + through T322's form: the entry's message, then `Register-Seq: <k>`, in its + final trailer block where its last paragraph is one, or as a new last + paragraph after one blank line. +""" + +from __future__ import annotations + +import atexit +import hashlib +import inspect +import json +import os +import re +import shlex +import shutil +import signal +import subprocess +import sys +import tempfile +import time +import uuid +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from conftest import REPO, WINDOWS_SKIP +from sql_register_cleanup import (IDENTITY, LEADS_A_GROUP, LEAVES_A_MEMBER, LINUX_ONLY, SAY_ME, + SLEEP, _GapFifo, _Pipe, _Settled, _Undying, _carried, _each, + _end_pin, _ended, _fifo_reader, _keep, _misrecorded, _nonce, + _owned, _pidfds, _pin, _pin_child, _raise_first, _reap_all, + _release, _reported, _send_each, _settle_pinned, _stat, _table, + _with_identity) +from sql_register_helpers import PSQL_SHIM, PSQL_SHIM_CONTROL, PSQL_SHIM_LOG, flipped_copy + +pytestmark = [WINDOWS_SKIP, pytest.mark.skipif( + shutil.which("bash") is None or shutil.which("git") is None, + reason="the lane tooling is bash over git")] + +#: THE LANDING GATE'S TABLE (T280's reader, `tests/sql_register_gate.py`; T281 +#: removes it in the last set). Each AT case waits for T270's own fails-until, +#: T320 to T323, T325 and L4-B13, which is lane 4's T415 (the author) and T416 +#: (the fork), and for T227, whose T227b makes `pg_imported` and +#: `pg_cluster.imported_register`, on which every case builds its estate +#: (`_estate`; lane 3, #165 6877365776, point 2). Lane 2's plan GP-24. The +#: clean-up's own fault-path regressions, at the end, need no engine and no +#: task, so each has an empty row and ordinary PR CI runs it. These rows +#: replace the module's `"*"` row, each AT case's row equal to what that row +#: gave it (lane 3's Codex review of code PR 97 at `18529e5a`, SHOULD 5). +SQL_REGISTER_GATE_TABLE = { + "test_a_burst_from_one_lane_gives_at_most_two_renders": ("T227", "T320", "T321", "T322", "T323", "T325", "T415", "T416"), # T270; the former "*" row + "test_a_clean_up_ends_each_member_of_a_group_whose_leader_is_gone": (), # T270; the clean-up's own fault path, no task (Codex at 46cac748, SHOULD 1; the coordinator's 6938182757, point 1) + "test_a_clean_up_ends_what_it_knows_before_it_raises_an_unreadable_log": (), # T270; the clean-up's own fault path, no task (the coordinator's 6938182757, point 2) + "test_a_clean_up_kills_and_closes_every_pin_whatever_a_signal_raised": (), # T270; the clean-up's own fault path, no task (Codex at 46cac748, SHOULD 6) + "test_a_clean_up_names_a_logged_live_process_it_cannot_own": (), # T270; the clean-up's own fault path, no task (Codex at f776b435, SHOULD 8) + "test_a_clean_up_never_signals_a_logged_pid_and_start_token_without_the_case_s_identity": (), # T270; the clean-up's own fault path, no task (Codex at 46cac748, BLOCKING) + "test_a_clean_up_pins_again_a_pid_whose_pinned_process_is_gone": (), # T270; the clean-up's own fault path, no task (Codex at f776b435, SHOULD 1) + "test_a_clean_up_raises_on_a_process_logged_with_no_start_token": (), # T270; the clean-up's own fault path, no task (Codex at 18529e5a, SHOULD 1) + "test_a_clean_up_raises_where_a_stop_is_never_seen": (), # T270; the clean-up's own fault path, no task (Codex at f776b435, SHOULD 1) + "test_a_clean_up_signals_through_pidfds_alone_and_spares_a_wrong_start_token": (), # T270; the clean-up's own fault path, no task (Codex at 18529e5a, BLOCKING) + "test_a_failed_render_shows_its_lag_and_the_next_render_catches_up": ("T227", "T320", "T321", "T322", "T323", "T325", "T415", "T416"), # T270; the former "*" row + "test_a_fifo_let_go_leaves_no_reader_blocked": (), # T270; the clean-up's own fault path, no task (Codex at 6d479418, SHOULD 1) + "test_a_held_burst_ends_its_renders_before_its_assertion_fails": (), # T270; the clean-up's own fault path, no task (Codex at 6d479418, SHOULD 3) + "test_a_held_burst_leaves_no_fifo_where_its_first_log_read_fails": (), # T270; the clean-up's own fault path, no task (Codex at 18529e5a, SHOULD 3) + "test_a_held_renderer_delays_no_writer_beyond_the_fork": ("T227", "T320", "T321", "T322", "T323", "T325", "T415", "T416"), # T270; the former "*" row + "test_a_hold_clean_up_ends_a_call_forked_before_its_first_record": (), # T270; the clean-up's own fault path, no task (Codex at 18529e5a, SHOULD 1) + "test_a_lost_push_race_never_rebases_a_render": ("T227", "T320", "T321", "T322", "T323", "T325", "T415", "T416"), # T270; the former "*" row + "test_a_non_github_origin_with_render_key_is_refused_with_2": ("T227", "T320", "T321", "T322", "T323", "T325", "T415", "T416"), # T270; the former "*" row + "test_a_pass_renders_at_most_64_seqs": ("T227", "T320", "T321", "T322", "T323", "T325", "T415", "T416"), # T270; the former "*" row + "test_a_pin_and_a_release_close_every_pidfd_whatever_a_read_or_a_close_raised": (), # T270; the clean-up's own fault path, no task (Codex at f776b435, SHOULD 3) + "test_a_pinned_process_s_end_raises_unless_it_is_seen_gone": (), # T270; the clean-up's own fault path, no task (Codex at 46cac748, SHOULD 3) + "test_a_register_seq_above_the_head_with_the_switch_at_files_is_no_divergence_and_renders_nothing": ("T227", "T320", "T321", "T322", "T323", "T325", "T415", "T416"), # T270; the former "*" row + "test_a_render_clean_up_ends_a_detached_render_no_log_names": (), # T270; the clean-up's own fault path, no task (Codex at 18529e5a, SHOULD 1) + "test_a_render_commit_with_a_private_index_and_its_push_are_timed_and_recorded": ("T227", "T320", "T321", "T322", "T323", "T325", "T415", "T416"), # T270; the former "*" row + "test_a_render_forked_from_a_no_fetch_verb_still_renders": ("T227", "T320", "T321", "T322", "T323", "T325", "T415", "T416"), # T270; the former "*" row + "test_a_renderer_hands_over_once_after_16_passes": ("T227", "T320", "T321", "T322", "T323", "T325", "T415", "T416"), # T270; the former "*" row + "test_a_renderer_killed_between_commit_and_push_blocks_nothing": ("T227", "T320", "T321", "T322", "T323", "T325", "T415", "T416"), # T270; the former "*" row + "test_a_renderer_killed_by_sigkill_leaves_the_checkout_able_to_render_at_once": ("T227", "T320", "T321", "T322", "T323", "T325", "T415", "T416"), # T270; the former "*" row + "test_a_renderer_killed_inside_read_tree_does_not_block_the_next_render": ("T227", "T320", "T321", "T322", "T323", "T325", "T415", "T416"), # T270; the former "*" row + "test_a_report_of_a_part_line_ends_its_starter_and_raises": (), # T270; the clean-up's own fault path, no task (Codex at f776b435, SHOULD 2) + "test_a_report_that_never_comes_ends_its_starter_and_raises": (), # T270; the clean-up's own fault path, no task (Codex at 46cac748, SHOULD 2) + "test_a_wrapper_kill_ends_a_gone_leader_s_group_and_every_pidfd_whatever_a_stop_or_a_close_did": (), # T270; the clean-up's own fault path, no task (Codex at f776b435, SHOULDs 1 and 3) + "test_a_wrapper_kill_ends_every_target_whatever_its_discovery_or_a_kill_raised": (), # T270; the clean-up's own fault path, no task (Codex at 46cac748, SHOULD 6; the coordinator's 6938182757, point 3) + "test_a_wrapper_kill_raises_its_first_error_with_every_later_one_as_its_cause": (), # T270; the clean-up's own fault path, no task (Codex at bb190f7b, SHOULD 2) + "test_a_wrapper_kill_reads_again_once_every_target_is_gone_whatever_a_stop_did": (), # T270; the clean-up's own fault path, no task (Codex at 5a120647, SHOULD 2) + "test_a_wrapper_kill_signals_only_the_case_s_own_and_finds_each_member_without_its_leader": (), # T270; the clean-up's own fault path, no task (Codex at 46cac748, BLOCKING and SHOULD 1; the coordinator's 6938182757, point 1) + "test_a_write_that_commits_as_the_render_lets_go_is_rendered_with_no_later_write": ("T227", "T320", "T321", "T322", "T323", "T325", "T415", "T416"), # T270; the former "*" row + "test_an_abort_release_runs_neither_a_held_call_nor_a_launched_command": (), # T270; the clean-up's own fault path, no task (Codex at 18529e5a, SHOULD 1) + "test_end_session_raises_rather_than_return_with_its_child_unreaped": (), # T270; the clean-up's own fault path, no task (Codex at 6d479418, SHOULD 4) + "test_form_c_reads_the_trailer_from_each_message_shape": ("T227", "T320", "T321", "T322", "T323", "T325", "T415", "T416"), # T270; the former "*" row + "test_no_rerun_mark_is_left_and_the_last_write_is_rendered_after_a_burst": ("T227", "T320", "T321", "T322", "T323", "T325", "T415", "T416"), # T270; the former "*" row + "test_race_raises_its_clean_up_error_and_leaves_no_barrier_fifo": (), # T270; the clean-up's own fault path, no task (Codex at 6d479418, SHOULDs 4 and 1) + "test_reap_all_tries_every_child_and_raises_after_the_whole_set": (), # T270; the clean-up's own fault path, no task (Codex at 46cac748, SHOULD 4) + "test_renderers_make_identical_commits_for_one_seq": ("T227", "T320", "T321", "T322", "T323", "T325", "T415", "T416"), # T270; the former "*" row + "test_six_lost_races_leave_the_last_write_for_the_next_write_or_reconcile": ("T227", "T320", "T321", "T322", "T323", "T325", "T415", "T416"), # T270; the former "*" row + "test_the_last_write_of_a_burst_is_rendered_with_no_later_write": ("T227", "T320", "T321", "T322", "T323", "T325", "T415", "T416"), # T270; the former "*" row + "test_the_one_loop_reports_its_deadline_where_a_read_past_it_finds_none_new": (), # T270; the clean-up's own fault path, no task (Codex at bb190f7b, SHOULD 1) + "test_the_render_push_alone_carries_the_deploy_key": ("T227", "T320", "T321", "T322", "T323", "T325", "T415", "T416"), # T270; the former "*" row + "test_the_renderer_finds_m_by_paging_form_c": ("T227", "T320", "T321", "T322", "T323", "T325", "T415", "T416"), # T270; the former "*" row + "test_two_renderers_racing_push_one_commit_per_seq_in_order": ("T227", "T320", "T321", "T322", "T323", "T325", "T415", "T416"), # T270; the former "*" row + "test_wait_renders_exit_waits_for_a_renderer_that_took_a_logged_pid_and_keeps_its_deadline": (), # T270; the clean-up's own fault path, no task (Codex at 46cac748, SHOULD 7) + "test_with_no_register_seq_found_the_renderer_pushes_nothing_and_records_why": ("T227", "T320", "T321", "T322", "T323", "T325", "T415", "T416"), # T270; the former "*" row + "test_without_render_key_the_push_goes_to_origin": ("T227", "T320", "T321", "T322", "T323", "T325", "T415", "T416"), # T270; the former "*" row +} + +LANES_EDIT = REPO / "lanes-edit.sh" +INDEXER = REPO / "lanes-index" + +#: The register's schema, and the role the commit call runs as. +SCHEMA = "lanes_register" +WRITER_ROLE = "lanes_register_writer" + +#: Test 7's operator lane, and the two lanes whose checkouts race: `repoW-1` +#: and `repoD-1` are LIVE rows of test 7's register. `OPERATOR` is T227b's +#: `TEST7_OPERATOR` in `tests/pgcluster.py`, written out here: a name imported +#: from there at module level fails this module's collection wherever T227 has +#: not landed, and no landing gate skips a collection error (lane 3, #165 +#: 6877365776, point 2). Each case checks that the two agree +#: (`_operator_is_test7s`). +OPERATOR = "repoA-2" +L1, L2 = "repoW-1", "repoD-1" +WS = "Eagle" +AUTHOR = "T270 writer <t270@example.invalid>" +OPERATOR_AUTHOR = "T270 operator <t270-operator@example.invalid>" +NOT_AFTER = "2100-01-01T00:00:00Z" +ARGS_SHA256 = "a" * 64 +STORE_UTC = "2026-11-11T10:00:00Z" +#: The file the commit-call entries append to. +APPENDED = "lanes/LANES.md" + +#: A commit's `Register-Seq` trailer, `status`'s lag at `primary`, and its +#: divergence and failed-pass lines (lane 1's T117; line R). +REGISTER_SEQ = re.compile(r"^Register-Seq: ([0-9]+)$", re.M) +LAG = re.compile(r"^\s*lag:\s+([0-9]+) seq", re.M) +DIVERGED = re.compile(r"diverged at ([0-9a-f]{40})") +FAILED_PASS = re.compile(r"^\s*renderer:\s+its last failed pass", re.M) + +#: Open point 8's ceiling and poll. +CEILING, POLL = 30.0, 0.1 + +#: The GitHub repository the deploy-key case names, by HTTPS and by SSH. +GITHUB_REPO = "opensoft/t270-mirror" +GITHUB_HTTPS = f"https://github.com/{GITHUB_REPO}.git" +GITHUB_SSH = f"ssh://git@github.com/{GITHUB_REPO}.git" + +#: The environment no case inherits. +DROPPED = ("LANES_", "CLAUDE_", "WORKBENCHES_", "TMUX", "XDG_", "PG", "AGENT_PROTOCOL_ROOT", + "PROJECTS_", "GIT_", "SSH_", "FAKE_PSQL", "RULE6_", "OPENREPOTOOLS_") + +#: The subcommands that would rewrite history, which no render may run. +REWRITES = ("rebase", "pull", "cherry-pick", "am", "reset", "merge", "commit") + + +# ------------------------------------------------------------------ the PATH mask +#: `_masked_path`'s mirrors, by each directory's real path (None where the +#: directory holds no masked name), and the one temporary root they share. +#: Copied from line LX's T253e. +_PATH_MIRRORS: dict = {} +_PATH_MIRROR_ROOT: list = [] + + +def _masked_path() -> str: + """The caller's PATH with every directory kept in its place, and each one + that holds a `psql`, a `lanes-index` or a name that starts `pg_` swapped + for a private mirror of it: a directory of links, one to each of its + entries by its absolute path, those names left out. An installed + indexer, a real `psql` or one of the `pg_` client wrappers shipped beside + it is never what a case runs, but the tools beside them are: on a GitHub + runner `postgresql-16`'s client puts `psql` in `/usr/bin` with `git` and + `bash` (and `/bin` is a link to it), so dropping the directory dropped + `git` and `bash` too (lane 1's census, #165 6807454856). A directory that + holds none of those names passes through unchanged. Each mirror is made + once per process, under one `mkdtemp` that an `atexit` handler removes.""" + parts = [] + for part in os.environ.get("PATH", "").split(os.pathsep): + if not part: + continue + real = os.path.realpath(part) + if real not in _PATH_MIRRORS: + try: + names = os.listdir(real) + except OSError: + names = [] + masked = {name for name in names + if name in ("psql", "lanes-index") or name.startswith("pg_")} + mirror = None + if masked: + if not _PATH_MIRROR_ROOT: + _PATH_MIRROR_ROOT.append(tempfile.mkdtemp(prefix="l2-pathmask-")) + atexit.register(shutil.rmtree, _PATH_MIRROR_ROOT[0], ignore_errors=True) + mirror = os.path.join(_PATH_MIRROR_ROOT[0], str(len(_PATH_MIRRORS))) + os.mkdir(mirror) + for name in names: + if name not in masked: + os.symlink(os.path.join(real, name), os.path.join(mirror, name)) + _PATH_MIRRORS[real] = mirror + parts.append(_PATH_MIRRORS[real] or part) + return os.pathsep.join(parts) + + +# ------------------------------------------------------------------ small helpers +def _script(path: Path, text: str) -> Path: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8") + path.chmod(0o755) + return path + + +def _private(path: Path, text: str) -> Path: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8") + path.chmod(0o600) + return path + + +def _said(proc) -> str: + return (f"exit {proc.returncode}\n--- stdout ---\n{(proc.stdout or '')[-3000:]}" + f"\n--- stderr ---\n{(proc.stderr or '')[-3000:]}") + + +def _jsonl(path: Path) -> list: + if not path.exists(): + return [] + return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line] + + +def _sha256(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def _stats(samples: list) -> dict: + """Section 5.3's statistics: median and p95 by nearest rank, min-max, n. + Copied from the import module.""" + ordered = sorted(samples) + rank = lambda p: ordered[max(0, -(-p * len(ordered) // 100) - 1)] # noqa: E731 + return {"median": rank(50), "p95": rank(95), "min": ordered[0], "max": ordered[-1], + "n": len(ordered)} + + +def _open_when_held(fifo: Path, proc: subprocess.Popen, seconds: float = 120): + """The FIFO's write end, opened once a reader holds a call on it; None + where `proc` ends, or the time runs out, first. Closing it releases the + call. Copied from line RB's rollback module.""" + deadline = time.monotonic() + seconds + while time.monotonic() < deadline and proc.poll() is None: + try: + return os.open(str(fifo), os.O_WRONLY | os.O_NONBLOCK) + except OSError: + time.sleep(0.05) + return None + + +#: What an abort release writes into its FIFO (`_let_go`), beside its mark. +ABORT = b"abort\n" + + +def _let_go(fifo: Path, fd: int | None = None, abort: bool = False) -> None: + """A FIFO'S LAST RELEASE, in its owner's outer `finally` (and on the path + that succeeds), with no moment at which a reader can open it and be left + on it (lane 3's Codex review of code PR 97 at `6d479418`, SHOULD 1). + Where the owner still holds its write end `fd`, the FIFO is unlinked + first and `fd` closed after: a reader that holds it open reads EOF, and + none can open it once it is unlinked. Where the owner holds none, the + FIFO is opened once with `O_RDWR | O_NONBLOCK`, which on Linux neither + blocks nor fails for want of a reader, unlinked while that end is held, + and the end closed: a reader blocked in its `open()` is let go by that + open and reads EOF at the close, and one that comes later finds no FIFO + (ENOENT) and exits. A FIFO already gone is left so. T320's + `_run_bounded` (line R) runs each git call in a session of its own, so a + wrapper held on a FIFO is in no group a case signals (lane 2's RV7-30, + N1). EOF is a held call's release into its git, so a release on the + path that succeeds is EOF alone. An ABORT RELEASE (`abort`, each outer + `finally`'s, after its quiescence, `_quiesce`) first writes `ABORT` + into the FIFO and makes the mark `<fifo>.abort` beside it: a wrapper's + held call, or a launcher, let go then reads one or the other and runs + nothing (lane 3's Codex review of code PR 97 at `18529e5a`, SHOULD 1). + The mark stays beside the FIFO's path, so an abort release is that + path's last use in its case: each is in its owner's outer `finally`, + and no case here makes a FIFO at that path again.""" + if fd is None: + try: + fd = os.open(str(fifo), os.O_RDWR | os.O_NONBLOCK) + except FileNotFoundError: + return + try: + if abort: + try: + os.write(fd, ABORT) + except (BrokenPipeError, BlockingIOError): + pass # no reader is left to read it, or the FIFO already holds it + Path(f"{fifo}.abort").touch() + finally: + try: + fifo.unlink(missing_ok=True) + finally: + os.close(fd) + + +def _end_session(proc: subprocess.Popen, grace: float = 10) -> str: + """A child that leads a session of its own (`popen_render`'s + `start_new_session`) ended with its process group, and reaped, with no + wait unbounded: SIGTERM to the group and a `communicate()` of at most + `grace` s, then SIGKILL to the group and another. The group is signalled + only while the child is unreaped, so its pid is still the group's id: + the kernel issues neither the pid nor the group's id again before this + process reaps the child, so no other process can have them (the one + `os.killpg` left in the module, on this process's own child alone). + Where both waits timed out, the child's pipes are closed, in a + `finally`, and it is waited for once more, at most `grace` s; where that + times out too it raises (`RuntimeError`), so it never returns with the + child unreaped (lane 3's Codex review of code PR 97 at `6d479418`, + SHOULD 4). Returns what the child said (`_said`). `_open_when_held` + gives None with the child still running once its time runs out, where a + `communicate()` with no timeout waited for ever (lane 3's Codex review + of code PR 97 at `4e9821ab`, BLOCKING 2; lane 3's check v97 of it; lane + 2's RV7-30, N3). The hold FIFO is not this call's: its owner lets it go + in its own outer `finally` (`_let_go`, `_end_hold`).""" + said = None + try: + for sig in (signal.SIGTERM, signal.SIGKILL): + if proc.returncode is None: + try: + os.killpg(proc.pid, sig) + except ProcessLookupError: + pass + try: + out, err = proc.communicate(timeout=grace) + except subprocess.TimeoutExpired: + continue + said = _said(SimpleNamespace(returncode=proc.returncode, stdout=out, stderr=err)) + break + finally: + if said is None: + for pipe in (proc.stdout, proc.stderr): + if pipe is not None: + pipe.close() + if proc.returncode is None: + try: + proc.wait(timeout=grace) + except subprocess.TimeoutExpired as exc: + raise RuntimeError(f"pid {proc.pid} is still unreaped {grace:g} s after its " + f"pipes were closed, SIGTERM and SIGKILL having gone to " + f"its process group") from exc + return said or (f"exit {proc.returncode}: its output was still open {2 * grace:g} s after " + f"SIGTERM and SIGKILL to its process group") + + +def _end_hold(proc, fifo: Path, fd: int | None, est) -> None: + """A HOLD SITE'S OUTER `finally`, from the FIFO's making to the end: + first every process of the estate `est` stopped, killed and seen gone + (`_quiesce`), `proc` among them as the case's own child, and every + process carrying the case's identity, so a call it forked in a session + of its own, logged or not, is ended and never let go into its git; then + `proc`, the renderer held at its push, where there is one and it is + still unreaped, reaped with its session ended (`_end_session`, which + raises where it cannot reap it); then, whatever those raised, the hold + FIFO let go with an abort and unlinked (`_let_go`), with the write end + `fd` where the case still holds one (lane 2's RV7-30, S1; lane 3's Codex + reviews of code PR 97 at `6d479418`, SHOULDs 1 and 4, at `18529e5a`, + SHOULD 1, and at `46cac748`, BLOCKING).""" + try: + try: + _quiesce(est, roots=[proc] if proc is not None else []) + finally: + if proc is not None and proc.returncode is None: + _end_session(proc) + finally: + _let_go(fifo, fd, abort=True) + + +# ------------------------------------------------------------------ owned processes +#: A PROCESS'S IDENTITY HERE, and the helpers that pin, signal and release a +#: case's processes (`IDENTITY`, `_nonce`, `_stat`, `_carried`, `_pidfds`, +#: `_Pinned`, `_pin_child`, `_table`, `_stopped`, `_owned`, `_keep`, +#: `_send_each`, `_release`, `_wait_all` and `_raise_first`), are +#: `tests/sql_register_cleanup.py`'s, which this module and the rollback +#: module import (round CX-34): its docstring says how a process is owned. +#: So is the one loop of stop, kill, confirm and read again (`_Settled`, +#: `_settle_pinned`; round CX-35), which `_settle` and the wrapper run. +#: The clean-up below, `_quiesce` and the reads it makes, is this module's. + + +def _in_estate(pid: int, roots: set) -> bool: + """Whether `pid`'s argv names a path at or under one of `roots`, or its + cwd is there. The argv is read in memory alone, never kept or shown.""" + def under(path: str) -> bool: + return any(path == root or path.startswith(root + os.sep) for root in roots) + try: + argv = Path(f"/proc/{pid}/cmdline").read_bytes().split(b"\0") + except OSError: + argv = [] + if any(under(os.fsdecode(arg)) for arg in argv if arg): + return True + try: + return under(os.readlink(f"/proc/{pid}/cwd")) + except OSError: + return False + + +def _logged(est, after: int | None) -> list: + """(pid, start token, what) of each call's launch record + (`git-wrapper.started`) and, where `after` is a mark, of each renderer + the wrapper's log names after it.""" + found = [(rec.get("pid"), rec.get("start") or "", "a git call's launch record") + for rec in _jsonl(est.bin / "git-wrapper.started")] + if after is not None: + found += [(call["renderer"], call.get("renderer_start") or "", "a logged renderer") + for call in est.render_calls(after)] + return found + + +def _unowned(est, after: int | None, table: dict, nonces: set, books: SimpleNamespace) -> None: + """WHAT A CLEAN-UP FINDS OF THE ESTATE'S BUT CANNOT OWN, each named once + in `books.errors` and never signalled: a process logged with no start + token; a live one, not a zombie, whose pid and start token a record + names but whose environment does not carry the case's identity, as a + process that took the pid within the same tick would be; and one whose + argv or cwd is in `est.root` without it (`_strangers`). Each record is + validated by itself, apart from the table of this user's processes, so + a live one another user owns, or whose environment cannot be read, is + named too (`_misrecorded`; lane 3's Codex review of code PR 97 at + `f776b435`, SHOULD 8). Where the logs cannot be read (`_logged` raises: + an I/O or JSON error), the first such error is kept in `books.log`, and + the rest is still found and ended before it is raised (the + coordinator's #165 6938182757, point 2).""" + try: + logged = _logged(est, after) + except Exception as exc: # kept, and raised once what is known is ended + books.log = books.log or exc + logged = [] + held = {key[0] for key in books.pinned} + books.errors += [text for text in _misrecorded(logged, nonces, held, + ", which was never signalled") + if text not in books.errors] + books.errors += [text for text in _strangers(est, table, nonces, held) + if text not in books.errors] + + +def _strangers(est, table: dict, nonces: set, held: set) -> list: + """What `_unowned` names of a live process, not pinned and not a zombie, + whose argv or cwd is in `est.root` (`_in_estate`) but whose environment + does not carry the case's identity.""" + homes = {str(est.root), os.path.realpath(str(est.root))} + return [f"pid {pid} is in the estate without the case's identity, and was never signalled" + for pid, row in table.items() + if pid not in held and row["state"] not in ("Z", "X") + and _carried(pid) not in nonces and _in_estate(pid, homes)] + + +def _sweep(est, roots, after: int | None, books: SimpleNamespace) -> int: + """ONE READ of `_quiesce`: each of `roots`, the case's own children not + yet reaped, pinned as such (`_pin_child`); then each process whose + environment carries the estate's nonce, or one a root carries, pinned + by it (`_owned`); what cannot be owned noted (`_unowned`). Each one new + is registered in `books.pinned` before any signal, then each is stopped + (SIGSTOP), each in a `try` of its own. Returns how many are new.""" + table = _table() + nonces = {getattr(est, "nonce", None)} + fresh: list = [] + for proc in roots: + if proc is not None and proc.returncode is None and proc.pid in table: + nonces.add(_carried(proc.pid)) + if (proc.pid, table[proc.pid]["start"]) not in books.pinned: + _keep(books.pinned, fresh, _pin_child(proc)) + nonces.discard(None) + _owned(table, nonces, books.pinned, fresh) + _unowned(est, after, table, nonces, books) + books.refused += _send_each(fresh, signal.SIGSTOP, books.raised) + return len(fresh) + + +def _settle(est, roots, after: int | None, grace: float, books: SimpleNamespace) -> None: + """The rounds of `_quiesce`, the shared clean-up's one loop + (`_settle_pinned`; lane 3's Codex review of code PR 97 at `5a120647`, + SHOULD 2): read after read (`_sweep`), each made once every process + pinned is seen stopped, until one finds nothing new; then each still + there is killed and seen gone, and the estate read again, until a read + made once every one is seen gone finds nothing new. The deadline, + `grace` s on, is checked on every read, whatever was stopped, and is an + error; a stop not seen is one too, and an earlier error never spares + the read after the kill. Each error is kept in `books.raised`.""" + _settle_pinned(lambda: _sweep(est, roots, after, books), books, time.monotonic() + grace, + books.raised) + + +def _quiesce(est, roots=(), after: int | None = None, grace: float = 10) -> None: + """THE ESTATE QUIESCENT: every process of `est` stopped, then killed, + then seen gone, each through its pidfd, every wait bounded (lane 3's + Codex reviews of code PR 97 at `18529e5a`, BLOCKING and SHOULD 1, and at + `46cac748`, BLOCKING and SHOULDs 1 and 6). Found, round after round + until a round finds none not pinned already: + - `roots`, the case's own children not yet reaped (`_pin_child`); + - every process whose environment carries the estate's nonce + (`est.nonce`, `IDENTITY`), or the one a root carries: a write's + detached fork, a git call before its first record, a member of a + group whose leader is gone, each found by its identity alone + (`_owned`). + Each is registered before any signal, then stopped (SIGSTOP), so none + forks or runs on while the rest are found, and the next read is made + only once each one found is seen stopped (`_stopped`); then every one + still there is killed (SIGKILL), and once each is gone the estate is + read again, until a read made then finds nothing new, or the deadline, + `grace` s on and checked on every read, is reported (`_settle`). Each + signal is sent in a `try` of its own, and every pidfd is let go in its + own `finally` (`_release`), so whatever is raised, none is left stopped + or open. A process logged with no start token, one that a record names + and that is there without the identity, and one in the estate without + it, are never signalled, and are errors (`_unowned`); so is one still + there at the end. Where the logs cannot be read, their first error is + kept and the rest is still found and ended. Then the first error is + raised as it is, the log's own first, the others named as its cause + (`_raise_first`). Where the case passed, nothing is left, and nothing + is signalled.""" + _pidfds() + books = SimpleNamespace(pinned={}, errors=[], raised=[], log=None, refused=[]) + try: + _settle(est, roots, after, grace, books) + finally: + _release(books.pinned.values(), books.raised) + _raise_first(([books.log] if books.log is not None else []) + books.raised + + ([RuntimeError("; ".join(books.errors))] if books.errors else [])) + + +def _lock_is_free(path: Path) -> bool: + """A non-blocking `flock` on `path` succeeds (D14; [L4-4]).""" + import fcntl + fd = os.open(str(path), os.O_RDWR | os.O_CREAT, 0o600) + try: + fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + except OSError: + return False + else: + fcntl.flock(fd, fcntl.LOCK_UN) + return True + finally: + os.close(fd) + + +def _flipped(directory: Path) -> Path: + """T203's flipped copy, `RENDER_GIT_HALF = True`, with `lanes-edit.sh` + and `repos.tsv` beside it (the copy rule, CLI4.5 section 6), so a + `mode=primary` configuration loads and a render runs. Copied from line + W3a's `flipped_indexer`.""" + copy = flipped_copy(INDEXER, directory, True) + for name in ("lanes-edit.sh", "repos.tsv"): + if (REPO / name).exists(): + shutil.copy2(REPO / name, copy.parent / name) + return copy + + +# ------------------------------------------------------------------ the wrapper +GIT_WRAPPER = r'''#!/usr/bin/env -S python3 -I +# TEST 5'S `git` WRAPPER (TP:1059-1082; open point 8, TP:8792-8812), first on +# the renderer's PATH, standard library only. Each call is one JSON line of +# git-wrapper.log beside it; git-wrapper.json beside it holds `git` (the real +# git, by its path), `arms` and `redirect`. Before anything else each call +# writes its launch record, its pid and start token, to git-wrapper.started. +import fcntl, json, os, select, signal, subprocess, sys, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +CONTROL = os.path.join(HERE, "git-wrapper.json") +LOG = os.path.join(HERE, "git-wrapper.log") +STATE = os.path.join(HERE, "git-wrapper.state") +STARTED = os.path.join(HERE, "git-wrapper.started") +IDENTITY = "SQL_REGISTER_CASE_ID" +WITH_VALUE = {"-C", "-c", "--git-dir", "--work-tree", "--namespace", "--exec-path", + "--config-env"} +ENV_KEYS = ("GIT_SSH_COMMAND", "GIT_CONFIG_GLOBAL", "GIT_CONFIG_NOSYSTEM", "SSH_AUTH_SOCK", + "LANES_NO_FETCH", "GIT_INDEX_FILE") +NETWORK = ("fetch", "push", "ls-remote", "pull") + + +def subcommand(args): + i = 0 + while i < len(args): + if args[i] in WITH_VALUE: + i += 2 + elif args[i].startswith("-"): + i += 1 + else: + return args[i] + return "" + + +def where(args): + """The repository the call runs in: its cwd, moved by each `-C`.""" + found = os.getcwd() + i = 0 + while i < len(args): + if args[i] == "-C" and i + 1 < len(args): + found = os.path.join(found, args[i + 1]) + i += 2 + elif args[i] in WITH_VALUE: + i += 2 + elif args[i].startswith("-"): + i += 1 + else: + break + return os.path.realpath(found) + + +def stat(pid): + """The fields of /proc/<pid>/stat after the command's name, or None.""" + try: + with open("/proc/%d/stat" % pid, "rb") as handle: + raw = handle.read() + except OSError: + return None + return raw[raw.rindex(b")") + 2:].split() + + +def started(pid): + """`pid`'s start token: field 22 of its /proc stat, its start in clock + ticks since boot, which no process that uses the pid again shares; "" + where it is gone.""" + fields = stat(pid) + return fields[19].decode() if fields else "" + + +def is_render(pid): + """Whether the process above the call is a `lanes-index render + --checkout`, by its argv, read in memory; only that answer is kept.""" + try: + with open("/proc/%d/cmdline" % pid, "rb") as handle: + argv = [arg.decode("utf-8", "replace") for arg in handle.read().split(b"\0") if arg] + except OSError: + return False + return " render --checkout " in " %s " % " ".join(argv) + + +def above(): + """(the pid above this call, its start token, whether it is a render), + read so the token is that process's own: the pid above is read again + after, and where it has changed the process has ended, its token then + "gone".""" + pid = os.getppid() + start, render = started(pid), is_render(pid) + if os.getppid() != pid or not start: + return pid, "gone", False + return pid, start, render + + +def launched(): + """THE LAUNCH RECORD, before anything else the call does: its pid and + start token, one line of git-wrapper.started, which `arm()` never + resets, so a clean-up owns the call from its launch.""" + me = os.getpid() + with open(STARTED, "a", encoding="utf-8") as handle: + fcntl.flock(handle, fcntl.LOCK_EX) + handle.write(json.dumps({"pid": me, "start": started(me)}) + "\n") + handle.flush() + + +def carried(pid): + """The nonce `pid`'s environment carries (IDENTITY), read from + /proc/<pid>/environ in memory alone, never kept or shown; None where it + carries none or cannot be read.""" + try: + with open("/proc/%d/environ" % pid, "rb") as handle: + environ = handle.read() + except OSError: + return None + prefix = ("%s=" % IDENTITY).encode() + for entry in environ.split(b"\0"): + if entry.startswith(prefix): + return entry[len(prefix):].decode("utf-8", "replace") or None + return None + + +def alive(fd): + """Whether the process `fd` names still holds its pid and runs: a signal + 0 through the pidfd succeeds, as it does until the process is reaped, + and the pidfd is not readable, as it is once the process has ended.""" + try: + signal.pidfd_send_signal(fd, 0) + except ProcessLookupError: + return False + return not select.select([fd], [], [], 0)[0] + + +def pin(pid, nonce, pgrp=None): + """A pidfd on `pid`, kept only where the process it names carries the + case's nonce (`carried`), is no zombie, is in the group `pgrp` where + given, and, by a signal 0 through the pidfd after those reads (`alive`), + held the pid through them; else None, and it is never signalled. Any + failure of the open but ESRCH is raised; the pidfd is closed first, + whatever a read raises, unless it is handed over (lane 3's Codex review + of code PR 97 at `f776b435`, SHOULD 3).""" + try: + fd = os.pidfd_open(pid) + except ProcessLookupError: + return None + kept = None + try: + fields = stat(pid) + if (fields and fields[0] not in (b"Z", b"X") and (pgrp is None or int(fields[2]) == pgrp) + and carried(pid) == nonce and alive(fd)): + kept = fd + finally: + if kept is None: + os.close(fd) + return kept + + +def send(fd, sig): + try: + signal.pidfd_send_signal(fd, sig) + except ProcessLookupError: + pass # it has ended; the pidfd names it alone, so no other process is signalled + + +def stopped(pid, fd): + """Whether the process `fd` names is seen stopped (state T or t, read + while its pidfd shows it alive), or has ended.""" + fields = stat(pid) + if select.select([fd], [], [], 0)[0]: + return True + return bool(fields) and fields[0] in (b"T", b"t") + + +def wait_until(test, seconds): + """Whether `test()` holds within `seconds`.""" + deadline = time.monotonic() + seconds + while not test(): + if time.monotonic() >= deadline: + return False + time.sleep(0.01) + return True + + +def members(pid, nonce, targets, ended): + """ONE READ of /proc for the group `pid` leads: each member that carries + the case's nonce pinned (`pin`), recorded in `targets` before any + signal, then stopped. It needs no live leader: a group's id is no other + group's while any member of it lives. A pid in `targets` is passed over + only while its pidfd shows it there: where it has gone, the process + that has the pid now is pinned again by its own identity, and the old + pidfd kept in `ended`, to be closed (SHOULD 1 at `f776b435`). Returns + how many are new.""" + found = 0 + for name in os.listdir("/proc"): + if not name.isdigit() or int(name) == os.getpid(): + continue + old = targets.get(int(name)) + if old is not None and not select.select([old], [], [], 0)[0]: + continue + fields = stat(int(name)) + if not fields or int(fields[2]) != pid: + continue + fd = pin(int(name), nonce, pgrp=pid) + if fd is not None: + if old is not None: + ended.append(old) + targets[int(name)] = fd + send(fd, signal.SIGSTOP) + found += 1 + return found + + +def end_all(targets, errors, ended=()): + """SIGKILL through each pidfd of `targets`, each in a try of its own; + then each seen gone within one bound, 10 s on, and each pidfd closed, + with each of `ended` (pidfds of processes already gone), each wait and + each close in a try of its own, so a close that raises leaves no other + open (SHOULD 3 at `f776b435`). Each error met here is appended to + `errors`, after those met before, so none is lost (lane 3's Codex + review of code PR 97 at `bb190f7b`, SHOULD 2).""" + for fd in targets.values(): + try: + send(fd, signal.SIGKILL) + except OSError as exc: # kept; the rest are still killed + errors.append(exc) + deadline = time.monotonic() + 10 + for pid, fd in targets.items(): + try: + if not wait_until(lambda: select.select([fd], [], [], 0)[0], + max(0, deadline - time.monotonic())): + errors.append(RuntimeError("pid %d is still there 10 s after its SIGKILL " + "through its pidfd" % pid)) + except OSError as exc: # kept; the rest are still seen gone and closed + errors.append(exc) + for fd in list(targets.values()) + list(ended): + try: + os.close(fd) + except OSError as exc: # kept; the rest are still closed + errors.append(exc) + + +''' + inspect.getsource(_raise_first) + r''' + + +''' + inspect.getsource(_Settled) + r''' + +def kill_above(pid): + """SIGKILL to the process above, and to every other member of the group + it leads, each through a pidfd pinned by the case's identity (`pin`), + never by a number or a group's id (lane 3's Codex review of code PR 97 + at `46cac748`, BLOCKING and SHOULDs 1 and 6; the coordinator's points 1 + and 3, #165 6938182757): the process above is pinned and sent SIGSTOP; + then /proc is read for the members of its group, each pinned, recorded + and stopped; after a read that finds any new, the next read is made + only once every target, the process above among them, is seen stopped, + until a read finds none new; the leader need not live for its members + to be found. The first read follows the leader's SIGSTOP with no wait, + and where it finds no member the leader is killed with its stop + unchecked: no error is kept for a stop of its that is never seen, and + the read after the kill still runs (lane 2's pre-review RV7-35, N1). + Whatever is raised on the way, every target is then + killed, seen gone and its pidfd closed (`end_all`), and the first error + is raised, each later one named in its cause (`_raise_first`, whose + source this script carries; lane 3's Codex review of code PR 97 at + `bb190f7b`, SHOULD 2). A process without the case's identity is never + signalled. + Where the process above is gone before it is pinned, its group's + members are still found by the nonce and the group's id; a stop not + seen, where one is awaited after a read that found any new, is an + error; and the discovery and the end are the shared + clean-up's one loop (`_Settled`, whose source this script carries; lane + 3's Codex review of code PR 97 at `5a120647`, SHOULD 2): read after + read (`members`), then each target killed and seen gone, then /proc + read again, until a read made once every target is seen gone finds + none new, or the one deadline, 10 s on and checked on every read, + whatever was stopped, is reported. An earlier error never spares the + read after the kill, so a member forked by one whose stop was never + seen is still found and ended; each error is kept, and the first is + raised with every later one as its cause.""" + nonce = os.environ.get(IDENTITY) + if not hasattr(os, "pidfd_open") or not hasattr(signal, "pidfd_send_signal") or not nonce: + sys.stderr.write("the test's git wrapper kills only through a pidfd pinned by the case's " + "identity (%s; Python 3.9 or later, Linux 5.3 or later), and it has " + "none\n" % IDENTITY) + sys.exit(70) + targets, ended, errors = {}, [], [] + lead = pin(pid, nonce) + there = stat(pid) if lead is None else None + if lead is not None: + targets[pid] = lead + elif there and there[0] not in (b"Z", b"X"): + sys.stderr.write("the process above is not the case's: nothing is signalled\n") + return + until = time.monotonic() + 10 + + def live(): + return [p for p, fd in targets.items() if not select.select([fd], [], [], 0)[0]] + + def stop(by): + if wait_until(lambda: all(stopped(p, fd) for p, fd in targets.items()), + max(0, by - time.monotonic())): + return None + return "pids %s were never seen stopped" % sorted( + p for p, fd in targets.items() if not stopped(p, fd)) + + def kill(left): + raised = [] + for p in left: + try: + send(targets[p], signal.SIGKILL) + except OSError as exc: # kept; the rest are still killed + raised.append(exc) + wait_until(lambda: not live(), max(0, until - time.monotonic()) + 1) + return raised + + try: + if lead is not None: + send(lead, signal.SIGSTOP) + except OSError as exc: # kept; its group is still read, and every target ended + errors.append(exc) + try: + _Settled(lambda: members(pid, nonce, targets, ended), stop, kill, live, until, + errors).run() + except BaseException as exc: # kept; every target is still ended, then the first is raised + errors.append(exc) + end_all(targets, errors, ended) + _raise_first(errors) + + +def log(record): + with open(LOG, "a", encoding="utf-8") as handle: + fcntl.flock(handle, fcntl.LOCK_EX) + handle.write(json.dumps(record) + "\n") + handle.flush() + + +def take(index, times): + """Whether arm `index` takes this call: a count per arm, under a lock; + `times` below 0 takes every call.""" + with open(STATE, "a+", encoding="utf-8") as handle: + fcntl.flock(handle, fcntl.LOCK_EX) + handle.seek(0) + text = handle.read() + counts = json.loads(text) if text.strip() else {} + used = counts.get(str(index), 0) + if times >= 0 and used >= times: + return False + counts[str(index)] = used + 1 + handle.seek(0) + handle.truncate() + handle.write(json.dumps(counts)) + return True + + +def applies(arm, sub, args, here, render): + if arm.get("sub") != sub: + return False + if arm.get("where") and os.path.realpath(arm["where"]) != here: + return False + if arm.get("has") and arm["has"] not in args: + return False + if arm.get("render_only") and not render: + return False + return True + + +def main(): + launched() + args = sys.argv[1:] + with open(CONTROL, encoding="utf-8") as handle: + control = json.load(handle) + sub = subcommand(args) + here = where(args) + parent, parent_start, render = above() + record = {"sub": sub, "argv": args, "pid": os.getpid(), "renderer": parent, + "renderer_start": parent_start, "render": render, "where": here, + "env": {key: os.environ.get(key) for key in ENV_KEYS}, "t0": time.time()} + for index, arm in enumerate(control.get("arms", [])): + if (not applies(arm, sub, args, here, record["render"]) + or not take(index, arm.get("times", -1))): + continue + do = arm["do"] + if do == "hold": + log(dict(record, outcome="held")) + with open(arm["fifo"], "rb") as fifo: + said = fifo.read() + if said or os.path.exists(arm["fifo"] + ".abort"): + log(dict(record, outcome="aborted", rc=75)) + return 75 # an abort release: this call runs no git + elif do == "stall": + log(dict(record, outcome="stalled")) + time.sleep(float(arm.get("seconds", 5))) + elif do == "fail": + log(dict(record, outcome="failed", rc=1)) + sys.stderr.write("fatal: the test's git wrapper fails this %s\n" % sub) + return 1 + elif do == "reject": + log(dict(record, outcome="rejected", rc=1)) + refspec = next((a for a in reversed(args) if ":" in a and not a.startswith("-")), + "HEAD") + dest = args[args.index(refspec) - 1] if refspec in args else "origin" + if "--porcelain" in args: + sys.stdout.write("To %s\n!\t%s\t[rejected] (non-fast-forward)\nDone\n" + % (dest, refspec)) + sys.stderr.write(" ! [rejected] %s (non-fast-forward)\nerror: failed to " + "push some refs to '%s'\nhint: Updates were rejected because " + "the remote contains work that you do not have locally.\n" + % (refspec, dest)) + return 1 + elif do == "kill": + index_file = os.environ.get("GIT_INDEX_FILE") + if arm.get("index_lock") and index_file: + open(index_file + ".lock", "a").close() + log(dict(record, outcome="killed")) + # The renderer's own group where it leads one (a detached fork, or + # a case's render in a session of its own); else the renderer + # alone, each through a pidfd pinned by the case's identity + # (`kill_above`). Each git call runs in + # a group of its own (`_run_bounded`), so this call, which stands + # for git, then ends itself. + kill_above(parent) + signal.raise_signal(signal.SIGKILL) + return 137 + command = [control["git"]] + redirect = control.get("redirect") or {} + if sub in NETWORK: + for url, path in sorted(redirect.items()): + command += ["-c", "url.%s.insteadOf=%s" % (path, url)] + args = [redirect.get(arg, arg) for arg in args] + ran = time.time() + rc = subprocess.run(command + args).returncode + log(dict(record, outcome="ran", rc=rc, ran=ran, t1=time.time())) + return rc + + +if __name__ == "__main__": + sys.exit(main()) +''' + +#: Test 4's start barrier (TP:886-888): the launcher blocks on the FIFO it is +#: given until the test opens and closes it, then becomes the command; let go +#: by an abort release (`_let_go`'s `abort`), it ends with 75 and runs none. +LAUNCH = r'''#!/usr/bin/env -S python3 -I +import os, sys +with open(sys.argv[1], "rb") as fifo: + said = fifo.read() +if said or os.path.exists(sys.argv[1] + ".abort"): + sys.exit(75) # an abort release: the command never runs +os.execv(sys.argv[2], sys.argv[2:]) +''' + + +def _rows(db, sql: str) -> list: + """`sql`'s rows as JSON objects, read in the register's schema, by + `jsonb_agg`, whose text is one line. Copied from the import module.""" + out = db.psql(f"SET search_path TO {SCHEMA};\n" + f"SELECT coalesce(jsonb_agg(t), '[]'::jsonb) FROM ({sql}) t;\n").stdout + return json.loads(out.strip().splitlines()[-1]) + + +# ------------------------------------------------------------------ the estate +class RenderEstate: + """TEST 5'S ESTATE: see the module's docstring. `stage` is `primary` (the + default), `imported` (seq 0, the switch at `files`) or `empty` (no + journal, on `pg`). At `primary`, `marker` is `pushed`, or `recorded` for + a marker commit `record_marker` names that is not on origin's `main`.""" + + def __init__(self, root: Path, db, cluster, *, stage: str = "primary", + marker: str = "pushed"): + assert stage in ("primary", "imported", "empty"), stage + source = cluster.imported_register + if source is None: + pytest.fail(f"no imported register on the session cluster: " + f"{cluster.imported_problem}", pytrace=False) + self.root, self.db, self.stage = root, db, stage + root.mkdir(parents=True, exist_ok=True) + masked = _masked_path() + self.real_git = shutil.which("git", path=masked) + assert self.real_git, "no git on PATH" + self.bin, self.fakebin = root / "bin", root / "fakebin" + _script(self.bin / "git", GIT_WRAPPER) + _script(self.bin / "psql", PSQL_SHIM) + _script(self.bin / "launch", LAUNCH) + _script(self.fakebin / "tmux", "#!/bin/sh\nexit 1\n") + self.copy = _flipped(root / "flip") + env = {k: v for k, v in os.environ.items() if not k.startswith(DROPPED)} + #: The case's nonce, which every process it launches carries (`IDENTITY`). + self.nonce = _nonce() + env[IDENTITY] = self.nonce + env.update(TMPDIR=str(root / "tmp"), LANES_WORKSTATION=WS, LANES_HOST="eagle", + LANES_OS="linux", LANES_CONTAINER="none", LANES_IN_CONTAINER="0", + LANES_NO_GITHUB="1", LANES_EDIT=str(self.copy.parent / "lanes-edit.sh"), + GIT_AUTHOR_NAME="T270 estate", GIT_AUTHOR_EMAIL="t270@example.invalid", + GIT_COMMITTER_NAME="T270 estate", GIT_COMMITTER_EMAIL="t270@example.invalid", + PATH=os.pathsep.join([str(self.bin), str(self.fakebin), masked])) + (root / "tmp").mkdir(exist_ok=True) + self.env = env + #: The test's own git calls: the real git, no wrapper on PATH. + self.plain_env = dict(env, PATH=os.pathsep.join([str(self.fakebin), masked])) + self.arm() + self.c = source.c + self.origin = root / "origin.git" + self.git(None, "clone", "-q", "--bare", str(source.origin), str(self.origin)) + assert self.origin_tip() == self.c, "the imported register's origin is not at C" + self.label = self.switch()["database_label"] + self.conf_dir = root / "conf" + self.passfile = _private(self.conf_dir / "empty.pgpass", "") + self.index_conf = self.config("index", "index") + self.primary_conf = self.config("primary", "primary") + self.checkouts: dict = {} + head = self.head() + if stage == "empty": + assert head == -1, f"`pg`'s journal is not empty: head {head}" + else: + assert head == 0 and self.switch()["mode"] == "files", ( + f"`pg_imported` is not test 7's register at seq 0 at files: head {head}, " + f"switch {self.switch()}") + self.n = head + self.marker = None + if stage == "primary": + self._to_primary(marker) + + # ------------------------------------------------------------ git + def git(self, cwd, *args: str, env: dict | None = None, data: bytes | None = None) -> str: + proc = subprocess.run([self.real_git, *args], cwd=str(cwd) if cwd else None, + env=env or self.plain_env, input=data, capture_output=True, + timeout=300, check=False) + assert proc.returncode == 0, (f"git {' '.join(args[:4])}: " + f"{proc.stderr.decode('utf-8', 'replace')[-800:]}") + return proc.stdout.decode("utf-8", "replace") + + def origin_git(self, *args: str, env: dict | None = None, data: bytes | None = None, + origin: Path | None = None) -> str: + """git in a bare origin itself, so no clone's refs move.""" + return self.git(None, f"--git-dir={origin or self.origin}", *args, env=env, data=data) + + def origin_tip(self, origin: Path | None = None) -> str: + return self.origin_git("rev-parse", "refs/heads/main", origin=origin).strip() + + def commit_in_origin(self, parent: str, files: dict, message: str, + origin: Path | None = None) -> str: + """A commit on `parent` with `files` ({path: bytes}) changed, made in + the bare origin through an index of its own; no ref moves.""" + index = self.root / f"build-{uuid.uuid4().hex[:8]}.index" + env = dict(self.plain_env, GIT_INDEX_FILE=str(index)) + self.origin_git("read-tree", parent, env=env, origin=origin) + for path, data in files.items(): + blob = self.origin_git("hash-object", "-w", "--stdin", data=data, origin=origin).strip() + self.origin_git("update-index", "--add", "--cacheinfo", f"100644,{blob},{path}", + env=env, origin=origin) + tree = self.origin_git("write-tree", env=env, origin=origin).strip() + return self.origin_git("commit-tree", tree, "-p", parent, data=message.encode("utf-8"), + origin=origin).strip() + + def push_by_hand(self, commit: str, origin: Path | None = None) -> None: + """Origin's `main` moved to `commit`, a fast-forward, as a push makes it.""" + old = self.origin_tip(origin) + self.origin_git("merge-base", "--is-ancestor", old, commit, origin=origin) + self.origin_git("update-ref", "refs/heads/main", commit, old, origin=origin) + + def second_origin(self, name: str) -> Path: + """A bare copy of origin as it stands.""" + path = self.root / f"{name}.git" + self.git(None, "clone", "-q", "--bare", str(self.origin), str(path)) + return path + + def commits_after(self, old: str, origin: Path | None = None) -> list: + """[(sha, its Register-Seq values, its raw message)] on origin's + `main`'s first-parent line after `old`, oldest first.""" + out = self.origin_git("rev-list", "--reverse", "--first-parent", + f"{old}..refs/heads/main", origin=origin) + found = [] + for sha in out.split(): + raw = self.origin_git("cat-file", "commit", sha, origin=origin) + message = raw.split("\n\n", 1)[1] if "\n\n" in raw else "" + found.append((sha, [int(s) for s in REGISTER_SEQ.findall(message)], message)) + return found + + def identity(self, sha: str, origin: Path | None = None) -> dict: + out = self.origin_git("log", "-1", "--format=%an <%ae>%x00%at%x00%cn <%ce>%x00%ct", sha, + origin=origin).rstrip("\n").split("\0") + return {"author": out[0], "author_epoch": int(out[1]), "committer": out[2], + "committer_epoch": int(out[3])} + + def form_c(self, sha: str, origin: Path | None = None) -> str: + """Form C on one commit, with the walk's pins (Y:2843-2847).""" + out = self.origin_git("-c", "trailer.separators=:", "-c", "core.commentChar=#", + "log", "-n", "1", + "--format=%(trailers:key=Register-Seq,valueonly)", sha, + origin=origin) + return next((line.strip() for line in out.split("\n") if line.strip()), "") + + # ------------------------------------------------------------ the database + def rows(self, sql: str) -> list: + return _rows(self.db, sql) + + def sql(self, script: str, role: str | None = None) -> subprocess.CompletedProcess: + head = f"SET search_path TO {SCHEMA};\n" + (f"SET ROLE {role};\n" if role else "") + return self.db.psql(head + script, check=False) + + def head(self) -> int: + return self.rows("SELECT seq FROM register_head")[0]["seq"] + + def window(self) -> int: + return self.rows("SELECT version FROM schema_version")[0]["version"] + + def switch(self) -> dict: + return self.rows("SELECT * FROM register_switch")[0] + + def mirror(self) -> dict: + return self.rows("SELECT * FROM mirror_state")[0] + + def journal(self, after: int = -1) -> list: + return self.rows(f"SELECT seq, kind, message, author, " + f"extract(epoch FROM utc)::bigint AS epoch FROM journal " + f"WHERE seq > {after} ORDER BY seq") + + def render_sql(self, path: str) -> bytes: + """SQL's own render of `path` at the head (lane 1's T107).""" + quoted = path.replace("'", "''") + rows = self.rows(f"SELECT encode(render_file('{quoted}'), 'hex') AS hex") + return bytes.fromhex(rows[0]["hex"]) + + def commit_entries(self, bodies: list) -> list: + """THE COMMIT CALL, as a writer sends it (section 1.3's step 3): one + SERIALIZABLE transaction around `commit_write` per entry, as + REGISTER-WRITER, in one `psql`. Returns the entries' seqs.""" + head, window = self.head(), self.window() + generation = self.switch()["generation"] + script = [] + for n, body in enumerate(bodies): + literal = json.dumps(body, ensure_ascii=True).replace("'", "''") + script += ["BEGIN ISOLATION LEVEL SERIALIZABLE;", + f"SELECT commit_write({head + n}, '{uuid.uuid4()}'::uuid, {window}, " + f"'{generation}'::uuid, '{literal}'::jsonb);", "COMMIT;"] + proc = self.sql("\n".join(script) + "\n", WRITER_ROLE) + assert proc.returncode == 0, f"commit_write refused an entry: {proc.stderr[-1500:]}" + seqs = [int(word) for word in proc.stdout.split()] + assert seqs == list(range(head + 1, head + 1 + len(bodies))), ( + f"the commit calls answered {seqs}, not {head + 1} to {head + len(bodies)}") + return seqs + + def write_sql(self, texts: list, *, lane: str = L1, messages: list | None = None) -> list: + """One write entry per text, each appending it to `APPENDED`, through + the commit call alone (no fork). Returns their seqs.""" + data = self.render_sql(APPENDED) + assert data.endswith(b"\n"), f"SQL's {APPENDED} does not end with a newline" + bodies = [] + for n, text in enumerate(texts): + data += text.encode("utf-8") + b"\n" + bodies.append({ + "journal": {"kind": "write", "verb": "log", "lane": lane, "workstation": WS, + "author": AUTHOR, "args_sha256": ARGS_SHA256, + "message": messages[n] if messages else f"t270: {text}"}, + "not_after": NOT_AFTER, + "edits": [{"ord": 1, "op": "append", "path": APPENDED, "new_text": text}], + "files": [{"path": APPENDED, "present": True, "sha256": _sha256(data), + "final_newline": True}]}) + return self.commit_entries(bodies) + + def _to_primary(self, marker: str) -> None: + """AT-LR006'S ROUTE (TP:4610-4615): the cutover entry at seq 1, the + marker commit pushed by hand (or only recorded), `record_marker`.""" + tree = self.origin_git("rev-parse", f"{self.c}:lanes").strip() + lines = ("store=primary", f"database={self.label}", f"import={self.c}", + f"lanes-tree={tree}", f"utc={STORE_UTC}") + data = ("\n".join(lines) + "\n").encode("utf-8") + message = "t270: the cutover, by AT-LR006's route" + edits = [{"ord": 1, "op": "create", "path": "lanes/STORE"}] + edits += [{"ord": n, "op": "append", "path": "lanes/STORE", "new_text": line} + for n, line in enumerate(lines, start=2)] + (cut,) = self.commit_entries([{ + "journal": {"kind": "cutover", "verb": "cutover", "lane": OPERATOR, + "workstation": WS, "author": OPERATOR_AUTHOR, "message": message}, + "not_after": NOT_AFTER, "edits": edits, + "files": [{"path": "lanes/STORE", "present": True, "sha256": _sha256(data), + "final_newline": True}]}]) + assert cut == 1, f"the cutover entry took seq {cut}, not 1" + assert self.render_sql("lanes/STORE") == data, "SQL renders lanes/STORE otherwise" + self.marker = self.commit_in_origin(self.c, {"lanes/STORE": data}, + f"{message}\n\nRegister-Seq: {cut}\n") + if marker == "pushed": + self.push_by_hand(self.marker) + proc = self.sql(f"SELECT record_marker({self.window()}, {cut}, '{self.marker}', " + f"'{WS}');", WRITER_ROLE) + assert proc.returncode == 0 and proc.stdout.strip() == "present", ( + f"record_marker answered {proc.stdout.strip()!r}: {proc.stderr[-800:]}") + switch = self.switch() + assert (switch["mode"], switch["marker_state"]) == ("primary", "present"), switch + self.n = cut + + # ------------------------------------------------------------ configuration + def config(self, name: str, mode: str, extra=()) -> Path: + """A 0600 `lanes-index.conf` outside every work tree: `mode`, the two + URLs on the cluster's socket as its own user, an empty password file, + the switch's label and the schema, and `extra` lines.""" + lines = [f"mode={mode}", f"register_url={self.db.url()}", + f"register_passfile={self.passfile}", f"reader_url={self.db.url()}", + f"reader_passfile={self.passfile}", f"register_label={self.label}", + f"register_schema={SCHEMA}", *extra] + return _private(self.conf_dir / name / "lanes-index.conf", "\n".join(lines) + "\n") + + # ------------------------------------------------------------ lane checkouts + def checkout(self, name: str, lane: str = L1, *, origin: Path | None = None, + repository: str | None = None, own: bool = False) -> SimpleNamespace: + """A lane's register checkout, a clone of `origin`, in test 7's + `Workspace` form: its own `$HOME`, W a view of the clone that + `workspace.yaml` names (with `repository:` `repository`, origin's + path by default), and `LANES_REPO` at the clone. With `own`, for a + lane whose writes fork the renderer, also the lane's own register + checkout `<c>` (`own_checkout`), as `.own`.""" + root = self.root / name + home = root / "home" + agents = home / ".agents" + agents.mkdir(parents=True) + clone = home / "projects" / "wip" + self.git(None, "clone", "-q", str(origin or self.origin), str(clone)) + view = root / "ro" / "wip" + view.mkdir(parents=True) + (view / ".git").write_text(f"gitdir: {os.path.realpath(clone / '.git')}\n", + encoding="utf-8") + (view / "lanes").symlink_to(clone / "lanes") + (agents / "workspace.yaml").write_text( + f"repository: {repository or (origin or self.origin)}\npath: {view}\n", + encoding="utf-8") + for d in ("state", "config", "tmp"): + (root / d).mkdir() + env = dict(self.env, HOME=str(home), AGENT_PROTOCOL_ROOT=str(agents), + XDG_STATE_HOME=str(root / "state"), XDG_CONFIG_HOME=str(root / "config"), + TMPDIR=str(root / "tmp"), CLAUDE_CONFIG_DIR=str(home / ".claude"), + LANES_REPO=str(clone), LANES_LANE=lane) + lane_checkout = SimpleNamespace(name=name, lane=lane, root=root, home=home, clone=clone, + git_dir=clone / ".git", env=env, w=view, own=None) + if own: + lane_checkout.own = self.own_checkout(lane_checkout) + self.checkouts[name] = lane_checkout + return lane_checkout + + def own_checkout(self, lc) -> SimpleNamespace: + """THE LANE'S OWN REGISTER CHECKOUT ON PRIMARY, `<c>`, `<W>-lanes/<lane>/` + (T270e), made by `lanes-edit.sh lane-checkout <lane> --create` through the + flipped copy, as line G's T254s makes it for each primary lane. The estate makes + `<c>` itself, because `lane-start` makes it only under `LANES_ROUTE_WRITES=1` + with neither `LANES_REPO` nor `LANES_FILE` set (lane 3, #165 6841265575; + `dfc4ce4c:lane-start:1209-1210`). + + WHY: on primary, T415's `pw_checkout` takes each write's checkout from + `lane_checkout_path`, `<W>-lanes/<lane>`, and `LANES_REPO` never enters it + (lane 4, #165 6840794493: `a38af255:lanes-edit.sh:6273`, `:20738`, `:1673-1674`). + Where it is not there, the write refuses 2 and nothing is sent. The write's fork + then renders there, `render --checkout "$PW_C"` (`pw_render_fork`). So the + render's calls, lock and marks are `<c>`'s. The clone is a fetch, so + `LANES_NO_FETCH` is left out. Returns `<c>`'s `clone` and `git_dir`.""" + proc = subprocess.run(["bash", str(self.copy.parent / "lanes-edit.sh"), "lane-checkout", + lc.lane, "--create"], cwd=str(lc.clone), + env=self.lane_env(lc, None, {"LANES_NO_FETCH": None}), + capture_output=True, text=True, timeout=300, + stdin=subprocess.DEVNULL, check=False) + assert proc.returncode == 0, f"lane-checkout {lc.lane} --create:\n{_said(proc)}" + c = Path(proc.stdout.strip().splitlines()[-1]) + expected = Path(os.path.realpath(lc.w) + "-lanes") / lc.lane + assert c == expected and c.is_dir(), ( + f"lane-checkout {lc.lane} --create made {c}, not {expected}:\n{_said(proc)}") + git_dir = Path(self.git(c, "rev-parse", "--absolute-git-dir").strip()) + return SimpleNamespace(clone=c, git_dir=git_dir) + + def snapshot(self, lc) -> dict: + """The checkout's HEAD, index digest and `status --porcelain`, the + index read first and `status` run with no optional lock, so this + read never rewrites the index it digests.""" + index = _sha256((lc.git_dir / "index").read_bytes()) + return {"head": self.git(lc.clone, "rev-parse", "HEAD").strip(), "index": index, + "status": self.git(lc.clone, "--no-optional-locks", "status", "--porcelain")} + + # ------------------------------------------------------------ the wrapper and the shim + def arm(self, arms=(), redirect: dict | None = None, shim_arms=()) -> None: + """The wrapper's arms and the shim's, each log and count started + afresh.""" + for name in ("git-wrapper.log", "git-wrapper.state", PSQL_SHIM_LOG, "psql-shim.ends"): + (self.bin / name).write_text("", encoding="utf-8") + (self.bin / "psql-shim.state").write_text("{}", encoding="utf-8") + control = {"git": self.real_git, "arms": list(arms), "redirect": redirect or {}} + (self.bin / "git-wrapper.json").write_text(json.dumps(control), encoding="utf-8") + (self.bin / PSQL_SHIM_CONTROL).write_text( + json.dumps({"psql": self.db.psql_bin, "arms": list(shim_arms)}), encoding="utf-8") + + def calls(self, sub: str | None = None, lc=None) -> list: + """The wrapper's log, in order: each call that ran, or that an arm + took, once (its `ran` line, else its arm's line).""" + entries = _jsonl(self.bin / "git-wrapper.log") + ran = {e["pid"] for e in entries if e.get("outcome") == "ran"} + kept = [e for e in entries if e.get("outcome") == "ran" or e["pid"] not in ran] + if sub is not None: + kept = [e for e in kept if e["sub"] == sub] + if lc is not None: + kept = [e for e in kept if e["where"] == os.path.realpath(lc.clone)] + return kept + + # ------------------------------------------------------------ the commands + def lane_env(self, lc, conf: Path | None, env: dict | None) -> dict: + child = dict(lc.env, LANES_INDEX_CONFIG=str(conf or self.primary_conf)) + for key, value in (env or {}).items(): + if value is None: + child.pop(key, None) + else: + child[key] = value + return child + + def render_argv(self, lc) -> list: + return [sys.executable, str(self.copy), "render", "--checkout", str(lc.clone)] + + def render(self, lc, *, conf: Path | None = None, env: dict | None = None, + timeout: float = 300) -> subprocess.CompletedProcess: + """`lanes-index render --checkout <c>`, as a fork starts it: in a + session of its own, through the flipped copy, with the `mode=primary` + configuration. Waited for to its exit.""" + return subprocess.run(self.render_argv(lc), cwd=str(lc.clone), + env=self.lane_env(lc, conf, env), capture_output=True, text=True, + timeout=timeout, stdin=subprocess.DEVNULL, start_new_session=True, + check=False) + + def popen_render(self, lc, *, conf: Path | None = None, env: dict | None = None, + argv: list | None = None) -> subprocess.Popen: + return subprocess.Popen(argv or self.render_argv(lc), cwd=str(lc.clone), + env=self.lane_env(lc, conf, env), text=True, + stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, + stderr=subprocess.PIPE, start_new_session=True) + + def index(self, lc, *args: str, conf: Path | None = None, env: dict | None = None, + timeout: float = 300) -> subprocess.CompletedProcess: + """Another `lanes-index` command in the lane's checkout.""" + return subprocess.run([sys.executable, str(self.copy), *args], cwd=str(lc.clone), + env=self.lane_env(lc, conf or self.index_conf, env), + capture_output=True, text=True, timeout=timeout, + stdin=subprocess.DEVNULL, check=False) + + def status(self, lc) -> subprocess.CompletedProcess: + """`lanes-index status` in the lane's checkout: its lag is `n` less + the `m` origin's `main` carried as last fetched there.""" + return self.index(lc, "status") + + def lag(self, lc) -> int | None: + found = LAG.search(self.status(lc).stdout) + return int(found.group(1)) if found else None + + def race(self, checkouts: list, *, conf: Path | None = None) -> list: + """Test 4's barrier (TP:886-888, TP:1083): one renderer per checkout, + each launched blocking on a FIFO of its own, released together once + all are waiting. Returns each one's (returncode, stdout, stderr). + By then each launcher holds its FIFO open, so every FIFO is unlinked + before the release and none can be opened after it. The `finally` + owns every child and FIFO: first the estate is made quiescent + (`_quiesce`, each launcher not yet reaped among its roots, so its + render and every call it forked are stopped, killed and seen gone + through their pidfds); then each child not yet reaped has its + session ended and is reaped (`_end_session`), each step in a `try` of + its own that keeps its error; only then is each FIFO let go with an + abort and unlinked (`_let_go`) and each write end still open closed, + so no launcher is released into a render the case has given up on, + or left on an unlinked FIFO; then the first error kept is raised, or, + where a child is still unreaped, that is (lane 3's Codex reviews of + code PR 97 at `4e9821ab`, SHOULD 4, at `6d479418`, SHOULDs 1 and 4, + and at `18529e5a`, BLOCKING and SHOULD 1; lane 2's RV7-30, N4). A + launcher that never waited is ended and drained into that failure.""" + procs, fifos, fds = [], [], [] + try: + for lc in checkouts: + fifo = self.root / f"barrier-{lc.name}.fifo" + os.mkfifo(str(fifo), 0o600) + fifos.append(fifo) + procs.append(self.popen_render(lc, conf=conf, argv=[ + sys.executable, "-I", str(self.bin / "launch"), str(fifo), + *self.render_argv(lc)])) + for fifo, proc in zip(fifos, procs): + fd = _open_when_held(fifo, proc) + assert fd is not None, f"a launcher never waited on {fifo}:\n{_end_session(proc)}" + fds.append(fd) + for fifo in fifos: + fifo.unlink() + while fds: + os.close(fds.pop(0)) + ended = [] + for proc in procs: + out, err = proc.communicate(timeout=300) + ended.append(SimpleNamespace(returncode=proc.returncode, stdout=out, stderr=err)) + return ended + finally: + errors = [] + try: + _quiesce(self, roots=[proc for proc in procs if proc.returncode is None]) + except Exception as exc: # its error is kept; every child is still tried + errors.append(exc) + for proc in procs: + if proc.returncode is None: + try: + _end_session(proc) + except Exception as exc: # every child is tried; the first error is raised + errors.append(exc) + for fifo in fifos: + try: + _let_go(fifo, abort=True) + except OSError as exc: + errors.append(exc) + while fds: + os.close(fds.pop(0)) + unreaped = [proc.pid for proc in procs if proc.returncode is None] + if errors: + raise errors[0] + if unreaped: + raise RuntimeError(f"launcher pids {unreaped} are still unreaped") + + # ------------------------------------------------------------ writes that fork + def rearm(self, arms=()) -> None: + """The wrapper's arms changed, its log and counts kept.""" + control = json.loads((self.bin / "git-wrapper.json").read_text(encoding="utf-8")) + control["arms"] = list(arms) + (self.bin / "git-wrapper.json").write_text(json.dumps(control), encoding="utf-8") + + def edit(self, lc, *args: str, env: dict | None = None, + timeout: float = 300) -> subprocess.CompletedProcess: + """`lanes-edit.sh <args>` in the lane's checkout, as its lane, through + the flipped copy's `lanes-edit.sh`, with the `mode=primary` + configuration: a write on `primary`, which forks the renderer (lane + 4's T415 and T416).""" + return subprocess.run(["bash", str(self.copy.parent / "lanes-edit.sh"), *args], + cwd=str(lc.clone), env=self.lane_env(lc, None, env), + capture_output=True, text=True, timeout=timeout, + stdin=subprocess.DEVNULL, check=False) + + def write(self, lc, text: str, env: dict | None = None, + timeout: float = 300) -> subprocess.CompletedProcess: + """One `log NOTED lane:<L> <text>` from the lane's checkout.""" + return self.edit(lc, "log", "NOTED", f"lane:{lc.lane}", text, env=env, timeout=timeout) + + def entries(self) -> int: + """The wrapper log's length, the mark a wait starts after.""" + return len(_jsonl(self.bin / "git-wrapper.log")) + + def render_calls(self, after: int = 0) -> list: + """The calls a `lanes-index render --checkout` made, logged after the + mark `after`, each once.""" + entries = _jsonl(self.bin / "git-wrapper.log")[after:] + ran = {e["pid"] for e in entries if e.get("outcome") == "ran"} + return [e for e in entries if e.get("render") + and (e.get("outcome") == "ran" or e["pid"] not in ran)] + + def wait_lag_0(self, lc, what: str) -> None: + """OPEN POINT 8'S FIRST WAIT: `status` every 100 ms until its lag is + 0, under 30 s, each poll after the harness's fetch of the W `status` + reads (T270e; lane 3's ruling (a), #165 6833830078): + `git -C <W> fetch -q origin main`, with plain git, never through the + wrapper. `status` reads `m` on W's `origin/main` as last fetched and + never fetches, no write on primary fetches (D12), and the + render pushes from the lane's `<c>`. The fetch is the harness's own + act, not a write's, as the drill's `wait_lag_0` has it (DR's + T276f).""" + deadline = time.monotonic() + CEILING + while True: + self.git(lc.w, "fetch", "-q", "origin", "main") + if self.lag(lc) == 0: + return + if time.monotonic() > deadline: + shown = self.status(lc) + pytest.fail(f"{what}: the lag, each read after a fetch of W, is not 0 within " + f"{CEILING:g} s:\n{shown.stdout}" + f"{shown.stderr[-800:]}", pytrace=False) + time.sleep(POLL) + + def wait_renders_exit(self, after: int, what: str) -> list: + """OPEN POINT 8'S SECOND WAIT: under 30 s, a render's call logged + after the mark `after` (every pass begins with a fetch), then the + exit of every renderer logged after it, a re-fork's included, each + sought as the pair of its pid and the start token logged, read from + `/proc` (`_exited`): a pid whose token no longer matches counts as + exited, and an older record of a pid never hides a later renderer + that took it. The deadline holds on every path, a read that finds + another renderer logged among them (lane 3's Codex review of code PR + 97 at `46cac748`, SHOULD 7). Returns the renderer pids.""" + deadline = time.monotonic() + CEILING + while not self.render_calls(after): + if time.monotonic() > deadline: + pytest.fail(f"{what}: no render's call was logged within {CEILING:g} s", + pytrace=False) + time.sleep(POLL) + seen: set = set() + while True: + seen |= {(c["renderer"], c["renderer_start"]) for c in self.render_calls(after)} + live = sorted({pid for pid, start in seen if not _exited(pid, start)}) + if not live and {(c["renderer"], c["renderer_start"]) + for c in self.render_calls(after)} <= seen: + return sorted({pid for pid, _start in seen}) + if time.monotonic() > deadline: + pytest.fail(f"{what}: renderer pids {live} did not exit, or more were logged, " + f"within {CEILING:g} s", pytrace=False) + time.sleep(POLL) + +def _exited(pid: int, start: str) -> bool: + """Whether `pid`, which started at `start` (its start token, field 22 of + its `/proc/<pid>/stat`, as the wrapper logs it), is gone: no process has + the pid, the one that has it started at another time, or it is a zombie. + One read of `/proc`, with no command run and no signal sent, so it never + blocks (lane 3's Codex review of code PR 97 at `18529e5a`, SHOULD 2).""" + now = _stat(pid) + return now is None or now["start"] != start or now["state"] in ("Z", "X") + + +def _until(predicate, seconds: float) -> bool: + """`predicate()` polled every 100 ms until it holds, or `seconds` pass; + its last answer.""" + deadline = time.monotonic() + seconds + while not predicate(): + if time.monotonic() > deadline: + return bool(predicate()) + time.sleep(POLL) + return True + + +def _held_fd(fifo: Path, what: str, seconds: float = 120) -> int: + """The FIFO's write end, once the wrapper or the shim holds a call on + it; the case fails, naming `what`, where none does in time.""" + deadline = time.monotonic() + seconds + while time.monotonic() < deadline: + try: + return os.open(str(fifo), os.O_WRONLY | os.O_NONBLOCK) + except OSError: + time.sleep(0.05) + pytest.fail(f"{what}: nothing was held on {fifo.name} within {seconds:g} s", pytrace=False) + + +def _held_pushes(est: RenderEstate) -> int: + """The render pushes the wrapper has held so far, each counted by its + own `held` line in the raw `git-wrapper.log`. Not `render_calls()`, + which drops a pid's `held` line once its push has run.""" + return sum(1 for c in _jsonl(est.bin / "git-wrapper.log") + if c.get("render") and c["sub"] == "push" and c.get("outcome") == "held") + + +def _kth_held_fd(est: RenderEstate, fifo: Path, k: int, what: str, + seconds: float = 120) -> int: + """`_held_fd`, opened only once the raw log holds the `k`-th held + render push. A pass starts only after the previous push's wrapper has + exited, so the open lands on the `k`-th push, never on one just + released whose wrapper has not yet seen EOF (lane 3's #38, #165 + 6859801732).""" + if not _until(lambda: _held_pushes(est) >= k, seconds): + pytest.fail(f"{what}: the wrapper's log holds {_held_pushes(est)} held render pushes, " + f"not {k}, within {seconds:g} s", pytrace=False) + return _held_fd(fifo, what, seconds) + + +def _end_renders(est: RenderEstate, after: int, grace: float = 10) -> None: + """EVERY RENDERER LOGGED AFTER THE MARK `after` ENDED, and with it every + other process of the estate, with no wait unbounded (`_quiesce`; lane + 3's Codex reviews of code PR 97 at `6d479418`, SHOULD 3, at `18529e5a`, + BLOCKING and SHOULDs 1 and 2, and at `46cac748`, BLOCKING and SHOULD 1). + A write's renderer is a detached fork (lane 4's T416), no child of this + process, leading a group of its own: it is found, with every process it + started, by the case's identity, the estate's nonce its environment + inherits, and it is stopped, then killed, through its pidfd alone, never + by its number or its group's. A renderer the wrapper logged whose pid + and start token a live process has without that identity is never + signalled. Raises where one is still there `grace` s on, one was logged + with no start token, or one is there without the identity. Where the + case passed, every renderer has exited (`wait_renders_exit`), and none + is signalled.""" + _quiesce(est, after=after, grace=grace) + + +def _end_held_renders(est: RenderEstate, fifo: Path, fd: int | None, after: int) -> None: + """A HOLD ON FORKED RENDERS, ENDED: the outer `finally` of a case that + holds a write's render on `fifo`, from the FIFO's making to the end. The + wrapper's hold is disarmed (`rearm`); every process of the estate, each + renderer logged after the mark `after` among them, is stopped, killed + and seen gone (`_end_renders`), so a held call is ended, never let go + into its git; only then is the FIFO let go with an abort and unlinked + (`_let_go`, with the write end `fd` where the case still holds one). + Each step is tried whatever the one before it raised (lane 3's Codex + reviews of code PR 97 at `6d479418`, SHOULDs 1 and 3, and at + `18529e5a`, SHOULD 1).""" + try: + try: + est.rearm() + finally: + _end_renders(est, after) + finally: + _let_go(fifo, fd, abort=True) + + +def _wrote(proc, what: str) -> None: + assert proc.returncode == 0, ( + f"{what} on primary did not exit 0 (lane 4's T415 and T416, L4-B13):\n{_said(proc)}") + + +#: Test 7's seed's session of `L1`'s row (pgcluster's `_test7_seed`). +UUID_L1 = "eeeeeeee-0002-4000-8000-00000000e002" + + +def _operator_is_test7s() -> None: + """THE OPERATOR'S ONE VALUE: `OPERATOR` equals T227b's `TEST7_OPERATOR`. + The name is imported here, when a case runs, and never at module level, + so the module collects where T227 has not landed. Every case here waits + for T227 anyway, since its estate is built on `pg_imported` and + `pg_cluster.imported_register`, both T227's. So on a tree without the + name each case fails here, naming T227, and on a tree whose value + differs each case fails here, before it asks for the engine.""" + try: + from pgcluster import TEST7_OPERATOR + except ImportError as exc: + pytest.fail(f"tests/pgcluster.py has no TEST7_OPERATOR ({exc}): every case " + f"here waits for T227, whose T227b adds it with `pg_imported`", + pytrace=False) + assert OPERATOR == TEST7_OPERATOR, ( + f"this module's OPERATOR {OPERATOR!r} is not pgcluster's TEST7_OPERATOR " + f"{TEST7_OPERATOR!r} (T227b): change the copy here to match") + + +def _estate(request, tmp_path: Path, **kw) -> RenderEstate: + """A `RenderEstate` on `pg_imported`, or `pg` where `stage` is `empty`, + once `OPERATOR` is checked against T227b's (`_operator_is_test7s`).""" + _operator_is_test7s() + stage = kw.get("stage", "primary") + db = request.getfixturevalue("pg" if stage == "empty" else "pg_imported") + cluster = request.getfixturevalue("pg_cluster") + return RenderEstate(tmp_path / "estate", db, cluster, **kw) + + +def _assert_rendered(est: RenderEstate, old: str, seqs: list, origin: Path | None = None) -> list: + """THE RACE'S ORACLE (TP:1092-1099): origin's `main` gains exactly one + commit per seq after `old`, carrying `seqs` in order with none repeated, + each message the journal entry's with its `Register-Seq` (T322's form), + and author, committer and both dates the journal's (D15). Returns the + commits.""" + gained = est.commits_after(old, origin) + assert [s for _sha, carried, _m in gained for s in carried] == seqs, ( + f"origin's main gained {[(sha[:12], carried) for sha, carried, _m in gained]}, not one " + f"commit for each of {seqs} in order") + assert len(gained) == len(seqs), f"origin's main gained {len(gained)} commits for {seqs}" + journal = {row["seq"]: row for row in est.journal(min(seqs) - 1)} + for sha, (k,), message in gained: + entry = journal[k] + assert message.rstrip("\n") == _with_trailer(entry["message"], k), ( + f"the commit for seq {k} carries {message!r}, not the journal's message " + f"{entry['message']!r} with Register-Seq: {k} (T322's form)") + ident = est.identity(sha, origin) + assert ident == {"author": entry["author"], "author_epoch": entry["epoch"], + "committer": entry["author"], "committer_epoch": entry["epoch"]}, ( + f"the commit for seq {k} has {ident}, not the journal's author {entry['author']} " + f"as author and committer, both at {entry['epoch']} (D15)") + return [sha for sha, _c, _m in gained] + + +#: A line of a trailer block, `Token: value` (F29; B14 tasks:1504). +TRAILER_LINE = re.compile(r"[A-Za-z0-9-]+: .*") + + +def _with_trailer(message: str, k: int) -> str: + """T322'S FORM (B14 tasks:1504), with no final LF: the entry's message, + its blank last lines dropped, then `Register-Seq: <k>` as the last line + of its final trailer block, where it has two paragraphs or more and every + line of the last is `Token: value`; otherwise as a new last paragraph + after one blank line.""" + lines = message.split("\n") + while lines and not lines[-1].strip(" \t"): + lines.pop() + paragraphs, current = [], [] + for line in lines: + if line.strip(" \t"): + current.append(line) + elif current: + paragraphs.append(current) + current = [] + paragraphs.append(current) + block = len(paragraphs) >= 2 and all(TRAILER_LINE.fullmatch(line) for line in paragraphs[-1]) + return "\n".join(lines) + ("\n" if block else "\n\n") + f"Register-Seq: {k}" + + +def _no_rewrite(est: RenderEstate) -> None: + """The wrapper's log shows no `rebase`, no `pull --rebase` and no other + command that moves a HEAD (TP:1099; P314-318).""" + bad = [c["argv"] for c in est.calls() if c["sub"] in REWRITES] + assert not bad, f"a render ran a command that rewrites or moves a HEAD: {bad}" + + +def _push_tip(call: dict) -> str: + """The commit a push call names, from its `<tip>:refs/heads/main`.""" + spec = next((a for a in reversed(call["argv"]) if a.endswith(":refs/heads/main")), "") + return spec.split(":", 1)[0].lstrip("+") + + +# =================================================================== AT-5: the race +def test_two_renderers_racing_push_one_commit_per_seq_in_order(request, tmp_path): + """AT-5's race (TP:1092-1099): `n+1` to `n+5` committed, then two + renderers, in `L1`'s and `L2`'s checkouts of one bare origin, started + through test 4's barrier. Origin's `main` gains exactly five commits, + carrying `n+1` to `n+5` in order with none repeated, each message and + identity the journal's; both renderers exit 0; and the wrapper's log + shows no `rebase` and no `pull --rebase`. Fails until T320 to T322.""" + est = _estate(request, tmp_path) + one, two = est.checkout("L1", L1), est.checkout("L2", L2) + seqs = est.write_sql([f"race entry {i}" for i in range(1, 6)]) + assert seqs == list(range(est.n + 1, est.n + 6)), seqs + old = est.origin_tip() + est.arm() + ended = est.race([one, two]) + for lc, proc in zip((one, two), ended): + assert proc.returncode == 0, f"{lc.name}'s renderer:\n{_said(proc)}" + _assert_rendered(est, old, seqs) + _no_rewrite(est) + + +def _held_and_rendered(est: RenderEstate, one, two, seqs: list) -> tuple: + """`two`'s renderer held at its first push, `one`'s run to its end, then + `two` released: returns (the commit `two` had built for its push, + origin's commits for `seqs`, `two`'s exit). `held` and the FIFO are + owned from the FIFO's making to the end (`_end_hold`).""" + fifo = est.root / f"hold-{two.name}.fifo" + os.mkfifo(str(fifo), 0o600) + held = fd = None + try: + old = est.origin_tip() + est.arm([{"sub": "push", "do": "hold", "fifo": str(fifo), "where": str(two.clone), + "times": 1}]) + held = est.popen_render(two) + fd = _open_when_held(fifo, held) + if fd is None: + pytest.fail(f"{two.name}'s renderer never reached its push:\n{_end_session(held)}", + pytrace=False) + proc = est.render(one) + assert proc.returncode == 0, f"{one.name}'s renderer:\n{_said(proc)}" + end, fd = fd, None + _let_go(fifo, end) # `two` released: its FIFO unlinked, then the write end closed + out, err = held.communicate(timeout=300) + finally: + _end_hold(held, fifo, fd, est) + first = next(c for c in est.calls("push", two)) + commits = _assert_rendered(est, old, seqs) + return _push_tip(first), commits, SimpleNamespace(returncode=held.returncode, stdout=out, + stderr=err) + + +def test_renderers_make_identical_commits_for_one_seq(request, tmp_path): + """AT-5's identical commits (TP:1100-1102; P1363-1367): with `n+1` + committed, `L2`'s renderer is held at its push while `L1`'s renders and + pushes; the commit `L2` built for `n+1`, the one its push names, is the + sha `L1` pushed, its author and committer the journal's identity, both + dated by the entry's commit UTC (D15). Released, `L2` exits 0. Fails + until T320 to T322.""" + est = _estate(request, tmp_path) + one, two = est.checkout("L1", L1), est.checkout("L2", L2) + seqs = est.write_sql(["one seq, two renderers"]) + built, commits, two_ended = _held_and_rendered(est, one, two, seqs) + assert built == commits[0], (f"L2's renderer built {built} for seq {seqs[0]}, and L1's " + f"pushed {commits[0]}: two renderers made different commits") + assert two_ended.returncode == 0, f"L2's renderer after the release:\n{_said(two_ended)}" + + +# =================================================================== AT-5: the kill +def test_a_renderer_killed_by_sigkill_leaves_the_checkout_able_to_render_at_once(request, + tmp_path): + """[L4-4] (TP:1107-1109): the wrapper sends SIGKILL to the renderer's + process group just before its push. Then a non-blocking `flock` on + `lanes-render.lock` succeeds at once, no lock directory is left, and, + with no hand removal, the next render pushes every missing seq in order. + Fails until T320 to T322.""" + est = _estate(request, tmp_path) + one = est.checkout("L1", L1) + seqs = est.write_sql(["killed before its push, 1", "killed before its push, 2"]) + old = est.origin_tip() + est.arm([{"sub": "push", "do": "kill", "where": str(one.clone), "times": 1}]) + killed = est.render(one) + assert killed.returncode == -signal.SIGKILL, ( + f"the renderer was not killed at its push:\n{_said(killed)}") + assert est.origin_tip() == old, "the killed renderer pushed" + lock = one.git_dir / "lanes-render.lock" + assert not lock.is_dir(), "a lock directory is left behind" + assert not [p.name for p in one.git_dir.iterdir() + if p.is_dir() and p.name.startswith("lanes-render")], "a lock directory is left" + assert _lock_is_free(lock), "the SIGKILL did not release lanes-render.lock (D14; [L4-4])" + est.arm() + proc = est.render(one) + assert proc.returncode == 0, f"the next render, with no hand removal:\n{_said(proc)}" + _assert_rendered(est, old, seqs) + + +def test_a_renderer_killed_inside_read_tree_does_not_block_the_next_render(request, tmp_path): + """AT-5 (TP:1065-1067, :1223-1224): the wrapper leaves + `lanes-render.index.lock` behind, as git inside `read-tree` does, and + sends SIGKILL to the renderer's process group. The lock is free at once, + and the next render clears the stale `.lock` under the lock and pushes + every missing seq in order. Fails until T320 to T322.""" + est = _estate(request, tmp_path) + one = est.checkout("L1", L1) + seqs = est.write_sql(["killed inside read-tree"]) + old = est.origin_tip() + est.arm([{"sub": "read-tree", "do": "kill", "index_lock": True, "where": str(one.clone), + "times": 1}]) + killed = est.render(one) + assert killed.returncode == -signal.SIGKILL, ( + f"the renderer was not killed inside read-tree:\n{_said(killed)}") + stale = one.git_dir / "lanes-render.index.lock" + assert stale.exists(), (f"no {stale.name} was left: the build ran no read-tree under " + f"GIT_INDEX_FILE {one.git_dir / 'lanes-render.index'}") + assert _lock_is_free(one.git_dir / "lanes-render.lock"), "the render lock is still held" + est.arm() + proc = est.render(one) + assert proc.returncode == 0, f"the next render after the stale index lock:\n{_said(proc)}" + _assert_rendered(est, old, seqs) + assert not stale.exists(), f"{stale.name} is still there after the next render" + + +# =================================================================== AT-5: the lost race +def test_a_lost_push_race_never_rebases_a_render(request, tmp_path): + """P314-318 (TP:1034, :1181): `L1`'s renderer is held at its first push + while another clone pushes a handoff commit, so the push is rejected as a + non-fast-forward. The renderer fetches, builds again on the new tip, and + pushes: origin's `main` is the handoff commit and then one commit per + seq, in order; the wrapper's log shows two pushes with a fetch between, + and no `rebase`, `pull` or other command that moves a HEAD; and `L1`'s + HEAD, index and status are as before. Fails until T320 to T322.""" + est = _estate(request, tmp_path) + one = est.checkout("L1", L1) + seqs = est.write_sql(["a lost race, 1", "a lost race, 2"]) + before = est.snapshot(one) + fifo = est.root / "hold.fifo" + os.mkfifo(str(fifo), 0o600) + held = fd = None + try: # `held` and the FIFO owned to the end (`_end_hold`) + est.arm([{"sub": "push", "do": "hold", "fifo": str(fifo), "where": str(one.clone), + "times": 1}]) + held = est.popen_render(one) + fd = _open_when_held(fifo, held) + if fd is None: + pytest.fail(f"the renderer never reached its push:\n{_end_session(held)}", + pytrace=False) + handoff = est.commit_in_origin(est.origin_tip(), { + f"handoffs/{L2}.md": b"# a handoff pushed while the render was held\n"}, + "a handoff commit, pushed during the render's push") + est.push_by_hand(handoff) + end, fd = fd, None + _let_go(fifo, end) # the render released: its FIFO unlinked, then the write end closed + out, err = held.communicate(timeout=300) + finally: + _end_hold(held, fifo, fd, est) + assert held.returncode == 0, _said(SimpleNamespace(returncode=held.returncode, stdout=out, + stderr=err)) + _assert_rendered(est, handoff, seqs) + pushes = est.calls("push", one) + assert [p.get("rc") for p in pushes] == [1, 0], ( + f"not one rejected push then one that landed: {[(p['outcome'], p.get('rc')) for p in pushes]}") + calls = est.calls(lc=one) + first, second = (calls.index(p) for p in pushes) + assert any(c["sub"] == "fetch" for c in calls[first + 1:second]), ( + "the renderer pushed again with no fetch after the rejection") + _no_rewrite(est) + assert est.snapshot(one) == before, "the render moved L1's HEAD, index or status" + + +# =================================================================== AT-5: the push (T320) +def test_the_render_push_alone_carries_the_deploy_key(request, tmp_path): + """D23 (TP:1182-1193): with `render_key=` set, origin named by a GitHub + HTTPS URL, a global `url.*.insteadOf` rewriting SSH URLs to HTTPS and + `SSH_AUTH_SOCK` in the case's own environment, the wrapper records the + push and makes it to the bare origin in its place. The push names + `ssh://git@github.com/<owner>/<repo>.git` and `<tip>:refs/heads/main`, + with `--no-verify` and no force; its environment alone carries + `GIT_SSH_COMMAND` with `-i` the key file, `IdentitiesOnly=yes` and + `BatchMode=yes`, `GIT_CONFIG_GLOBAL=/dev/null` and + `GIT_CONFIG_NOSYSTEM=1`, and no `SSH_AUTH_SOCK`; the checkout's + configuration is unchanged, with no `pushurl`; and the read-back fetches + `origin`. Fails until T320 to T322.""" + est = _estate(request, tmp_path) + one = est.checkout("L1", L1, repository=GITHUB_HTTPS) + est.git(one.clone, "remote", "set-url", "origin", GITHUB_HTTPS) + (one.home / ".gitconfig").write_text( + '[url "https://github.com/"]\n\tinsteadOf = ssh://git@github.com/\n', encoding="utf-8") + key = _private(one.root / "keys" / "render_key", "not a key: the git wrapper makes the push\n") + conf = est.config("deploy-key", "primary", [f"render_key={key}"]) + local_before = est.git(one.clone, "config", "--local", "--list") + seqs = est.write_sql(["pushed with the deploy key"]) + old = est.origin_tip() + est.arm(redirect={GITHUB_HTTPS: str(est.origin), GITHUB_SSH: str(est.origin)}) + proc = est.render(one, conf=conf, env={"SSH_AUTH_SOCK": str(one.root / "agent.sock")}) + assert proc.returncode == 0, f"the render with render_key=:\n{_said(proc)}" + _assert_rendered(est, old, seqs) + calls = est.calls(lc=one) + pushes = [c for c in calls if c["sub"] == "push"] + assert len(pushes) == 1, f"not one push: {[p['argv'] for p in pushes]}" + push = pushes[0] + argv = push["argv"] + assert GITHUB_SSH in argv, f"the push does not name {GITHUB_SSH}: {argv}" + assert any(a.endswith(":refs/heads/main") and not a.startswith("+") for a in argv), argv + assert "--no-verify" in argv and not {"-f", "--force", "--force-with-lease"} & set(argv), argv + ssh = push["env"]["GIT_SSH_COMMAND"] or "" + words = shlex.split(ssh) + assert "-i" in words and words[words.index("-i") + 1] == str(key), ( + f"GIT_SSH_COMMAND does not name the key file with -i: {ssh!r}") + for option in ("IdentitiesOnly=yes", "BatchMode=yes"): + assert option in ssh, f"GIT_SSH_COMMAND lacks {option}: {ssh!r}" + assert (push["env"]["GIT_CONFIG_GLOBAL"], push["env"]["GIT_CONFIG_NOSYSTEM"]) == ( + os.devnull, "1"), push["env"] + assert push["env"]["SSH_AUTH_SOCK"] is None, "the push inherited SSH_AUTH_SOCK" + others = [c for c in calls if c is not push] + assert not [c["argv"] for c in others if c["env"]["GIT_SSH_COMMAND"]], ( + "another git call than the push carried GIT_SSH_COMMAND") + assert not [c["argv"] for c in others if str(key) in json.dumps(c["argv"])], ( + "another git call named the key file") + local_after = est.git(one.clone, "config", "--local", "--list") + assert local_after == local_before, f"the checkout's configuration changed:\n{local_after}" + assert "pushurl" not in local_after.lower(), local_after + after = calls[calls.index(push) + 1:] + assert any(c["sub"] == "fetch" and "origin" in c["argv"] for c in after), ( + "the read-back fetched no `origin` after the push") + + +def test_a_non_github_origin_with_render_key_is_refused_with_2(request, tmp_path): + """D23 (TP:1194; B14 tasks:1472): with `render_key=` set and the + checkout's origin a plain path, no GitHub repository, `render --checkout` + exits 2, names the origin as not a GitHub repository, makes no push, and + origin's `main` does not move. Fails until T320 to T322.""" + est = _estate(request, tmp_path) + one = est.checkout("L1", L1) + key = _private(one.root / "keys" / "render_key", "not a key\n") + conf = est.config("deploy-key", "primary", [f"render_key={key}"]) + est.write_sql(["refused: the origin is no GitHub repository"]) + old = est.origin_tip() + est.arm() + proc = est.render(one, conf=conf) + assert proc.returncode == 2, f"a non-GitHub origin with render_key= is not refused 2:\n{_said(proc)}" + assert "not a GitHub repository" in proc.stderr, _said(proc) + assert est.calls("push") == [], f"a push was made: {[c['argv'] for c in est.calls('push')]}" + assert est.origin_tip() == old, "origin's main moved" + + +def test_without_render_key_the_push_goes_to_origin(request, tmp_path): + """Q21(b)(A) (TP:1195; B14 tasks:1473-1477): without `render_key=` the + push names `origin` as it stands, `<tip>:refs/heads/main`, never forced, + with no `GIT_SSH_COMMAND`; origin gains the seq; and the checkout's + configuration is unchanged. Fails until T320 to T322.""" + est = _estate(request, tmp_path) + one = est.checkout("L1", L1) + local_before = est.git(one.clone, "config", "--local", "--list") + seqs = est.write_sql(["pushed to origin as it stands"]) + old = est.origin_tip() + est.arm() + proc = est.render(one) + assert proc.returncode == 0, f"the render without render_key=:\n{_said(proc)}" + commits = _assert_rendered(est, old, seqs) + pushes = est.calls("push", one) + assert len(pushes) == 1, f"not one push: {[p['argv'] for p in pushes]}" + argv = pushes[0]["argv"] + assert argv[argv.index(next(a for a in argv if a.endswith(":refs/heads/main"))) - 1] == "origin", ( + f"the push does not name `origin`: {argv}") + assert _push_tip(pushes[0]) == commits[-1], argv + assert not {"-f", "--force", "--force-with-lease"} & set(argv) and not any( + a.startswith("+") for a in argv), argv + assert pushes[0]["env"]["GIT_SSH_COMMAND"] is None, pushes[0]["env"] + assert est.git(one.clone, "config", "--local", "--list") == local_before + + +# =================================================================== AT-5: the pass and form C +def _deepen(est: RenderEstate, depth: int) -> str: + """`depth` commits under `handoffs/` on origin's `main`, none in the + render set, by one `git fast-import`. Returns the new tip.""" + old = est.origin_tip() + stream = [] + for n in range(1, depth + 1): + message = f"t270: handoff commit {n} of {depth}\n".encode() + content = f"# handoff {n}\n".encode() + stream.append(b"commit refs/heads/main\n") + stream.append(f"mark :{n}\n".encode()) + stream.append(f"committer T270 estate <t270@example.invalid> {1762858800 + n} +0000\n" + .encode()) + stream.append(b"data %d\n" % len(message) + message) + stream.append(f"from {old if n == 1 else ':' + str(n - 1)}\n".encode()) + stream.append(b"M 100644 inline handoffs/t270-depth.md\n") + stream.append(b"data %d\n" % len(content) + content) + est.origin_git("fast-import", "--quiet", data=b"".join(stream)) + tip = est.origin_tip() + assert est.origin_git("rev-list", "--count", f"{old}..{tip}").strip() == str(depth) + return tip + + +def _walks(est: RenderEstate, lc) -> list: + """The wrapper's `log --first-parent` calls in the checkout: form C's + walk, as (`-n`, `--skip`, whether it says `--grep`).""" + found = [] + for call in est.calls("log", lc): + argv = call["argv"] + if "--first-parent" not in argv or any(a.startswith("--raw") for a in argv): + continue + n = argv[argv.index("-n") + 1] if "-n" in argv else None + skip = argv[argv.index("--skip") + 1] if "--skip" in argv else None + found.append((n, skip, any(a.startswith("--grep") for a in argv))) + return found + + +@pytest.mark.parametrize("depth", ["depth-0", "depth-250"]) +def test_the_renderer_finds_m_by_paging_form_c(request, tmp_path, depth): + """Lane 4's section (TP:1040-1043, :1196-1203): at depth 0 the newest + render commit is the tip, and the renderer finds it in one page, the + wrapper's log showing each pass's walk as one page of `-n 200`, no page + after the first and no `--grep`; T323's holder runs a second pass after + a pass that made progress, F15, and that pass walks its first page + again from the new tip. At depth 250 it is 250 first-parent commits below the + tip: the renderer pages with `--skip` and finds it, the log showing + `-n 200`, the `--skip 200` page and no `--grep`. Either way it renders + the seq after it on top of the tip. Fails until T320 to T322.""" + est = _estate(request, tmp_path) + one = est.checkout("L1", L1) + tip = _deepen(est, 250) if depth == "depth-250" else est.origin_tip() + seqs = est.write_sql([f"found at {depth}"]) + est.arm() + proc = est.render(one) + assert proc.returncode == 0, f"the render at {depth}:\n{_said(proc)}" + _assert_rendered(est, tip, seqs) + walks = _walks(est, one) + assert walks and all(n == "200" for n, _skip, _grep in walks), ( + f"form C's walk is not in pages of 200: {walks}") + assert not any(grep for _n, _skip, grep in walks), f"form C's walk used --grep: {walks}" + if depth == "depth-0": + assert all(skip in (None, "0") for _n, skip, _g in walks), ( + f"at depth 0 a pass's walk took more than its first page: {walks}") + else: + assert [skip or "0" for _n, skip, _g in walks[:2]] == ["0", "200"], ( + f"at depth 250 the walk did not page on with --skip 200: {walks}") + + +@pytest.mark.parametrize("why", ["none", "out-of-time"]) +def test_with_no_register_seq_found_the_renderer_pushes_nothing_and_records_why(request, + tmp_path, why): + """Lane 4's section (TP:1040-1043, :1204-1206): `[none]`, origin's + `main` is C, no commit of which carries a `Register-Seq` (the marker + commit is recorded and not on origin); `[out-of-time]`, the wrapper + stalls the walk's `log` past `LANES_GIT_TIMEOUT`, set to 2 s. The + renderer pushes nothing and exits non-zero; `mirror_state.last_error` + and its time are set through `record_mirror_state`, `diverged_sha` stays + NULL; `status` shows the failed pass; and origin is unchanged. Fails + until T320 to T322.""" + est = _estate(request, tmp_path, marker="pushed" if why == "out-of-time" else "recorded") + one = est.checkout("L1", L1) + est.write_sql([f"no Register-Seq found: {why}"]) + old = est.origin_tip() + env = None + if why == "out-of-time": + est.arm([{"sub": "log", "do": "stall", "has": "--first-parent", "seconds": 6, + "where": str(one.clone)}]) + env = {"LANES_GIT_TIMEOUT": "2"} + else: + assert old == est.c and est.form_c(old) == "", "origin's main carries a Register-Seq" + est.arm() + proc = est.render(one, env=env, timeout=120) + assert proc.returncode != 0, f"the renderer found no m and still ended 0:\n{_said(proc)}" + assert est.calls("push") == [], f"it pushed: {[c['argv'] for c in est.calls('push')]}" + assert est.origin_tip() == old, "origin's main moved" + mirror = est.mirror() + assert mirror["last_error"] and mirror["last_error_utc"], ( + f"no failed pass is recorded in mirror_state: {mirror}\n{_said(proc)}") + assert mirror["diverged_sha"] is None, f"a divergence was recorded: {mirror}" + shown = est.status(one) + assert FAILED_PASS.search(shown.stdout), f"status does not show the failed pass:\n{_said(shown)}" + + +def test_a_pass_renders_at_most_64_seqs(request, tmp_path): + """PC-3 (TP:1044-1045, :1207-1209): a backlog of 70 seqs reaches origin + as `m+1` to `m+64` in one pass, one push, and the rest in the next; and + the commits are those of any other batching: a second origin, rendered + in batches of 10 and then 60, carries the same 70 shas. Fails until + T320 to T323.""" + est = _estate(request, tmp_path) + other_origin = est.second_origin("origin-batched") + one = est.checkout("L1", L1) + batched = est.checkout("L2", L2, origin=other_origin) + old = est.origin_tip() + m = est.n + first = est.write_sql([f"backlog entry {i}" for i in range(1, 11)]) + est.arm() + proc = est.render(batched) + assert proc.returncode == 0, f"the batched render of 10:\n{_said(proc)}" + rest = est.write_sql([f"backlog entry {i}" for i in range(11, 71)]) + seqs = first + rest + assert seqs == list(range(m + 1, m + 71)), seqs + est.arm() + proc = est.render(one) + assert proc.returncode == 0, f"the render of a backlog of 70:\n{_said(proc)}" + commits = _assert_rendered(est, old, seqs) + tips = [_push_tip(p) for p in est.calls("push", one)] + assert tips == [commits[63], commits[69]], ( + f"the pushes named {tips}, not seq {m + 64}'s commit, then seq {m + 70}'s: a pass " + f"renders at most 64 seqs") + est.arm() + proc = est.render(batched) + assert proc.returncode == 0, f"the batched render of 60:\n{_said(proc)}" + assert _assert_rendered(est, old, seqs, other_origin) == commits, ( + "batches of 10 and 60 made other commits than batches of 64 and 6") + + +@pytest.mark.parametrize("shape", ["subject-only", "trailer-block", "prose"]) +def test_form_c_reads_the_trailer_from_each_message_shape(request, tmp_path, shape): + """Lane 4's section (TP:1225-1226): a journal message of each shape, a + subject alone, a body ending in a trailer block, and a body ending in + prose. Two checkouts give one sha for it (`L2` held at its push while + `L1` renders), and form C reads `<k>` from it. The trailer joins the + final trailer block, or is a new last paragraph after one blank line + (T322). Fails until T320 to T322.""" + message = { + "subject-only": "t270: a subject alone", + "trailer-block": (f"t270: a subject\n\nA body line.\n\nLane: {L1}\n" + f"Co-Authored-By: T270 <t270@example.invalid>"), + "prose": ("t270: a subject\n\nA body that ends in prose, a paragraph with no " + "trailer in it."), + }[shape] + est = _estate(request, tmp_path) + one, two = est.checkout("L1", L1), est.checkout("L2", L2) + old = est.origin_tip() + (k,) = est.write_sql([f"form C, {shape}"], messages=[message]) + fifo = est.root / "hold.fifo" + os.mkfifo(str(fifo), 0o600) + held = fd = None + try: # `held` and the FIFO owned to the end (`_end_hold`) + est.arm([{"sub": "push", "do": "hold", "fifo": str(fifo), "where": str(two.clone), + "times": 1}]) + held = est.popen_render(two) + fd = _open_when_held(fifo, held) + if fd is None: + pytest.fail(f"L2's renderer never reached its push:\n{_end_session(held)}", + pytrace=False) + proc = est.render(one) + assert proc.returncode == 0, f"L1's renderer:\n{_said(proc)}" + end, fd = fd, None + _let_go(fifo, end) # L2's render released: its FIFO unlinked, then the write end closed + held.communicate(timeout=300) + finally: + _end_hold(held, fifo, fd, est) + assert held.returncode == 0, "L2's renderer after the release" + gained = est.commits_after(old) + assert [carried for _s, carried, _m in gained] == [[k]], gained + sha, _carried, raw = gained[0] + assert _push_tip(est.calls("push", two)[0]) == sha, "two checkouts gave two shas" + assert est.form_c(sha) == str(k), f"form C reads {est.form_c(sha)!r} from {sha}, not {k}" + joined = "\n" if shape == "trailer-block" else "\n\n" + assert raw.rstrip("\n") == f"{message}{joined}Register-Seq: {k}", ( + f"the {shape} message is not the journal's with Register-Seq: {k} " + f"{'in its trailer block' if shape == 'trailer-block' else 'as a new paragraph'}: {raw!r}") + + +@pytest.mark.parametrize("case", ["marker-first-head-minus-1", "marker-first-head-0", "forged"]) +def test_a_register_seq_above_the_head_with_the_switch_at_files_is_no_divergence_and_renders_nothing( + request, tmp_path, case): + """R2's N6, at `files` (TP:1150-1167, :1227-1228): the switch reads + `files`, and origin's `main` carries a commit whose last `Register-Seq` + is above the head `h`: the marker commit `S` with `Register-Seq: 1`, + pushed ahead of the import (`h` -1, on `pg`) or after it (`h` 0); or a + forged commit under `handoffs/` carrying `Register-Seq: <h+10>`. A pass + run by `render --checkout <c>`, as a fork runs it, records no + divergence (`diverged_sha` NULL, no `diverged at` in `status`), pushes + nothing, and exits 0. Fails until T320 to T322.""" + est = _estate(request, tmp_path, stage="empty" if case.endswith("minus-1") else "imported") + h = est.head() + if case == "forged": + top = est.commit_in_origin(est.c, {f"handoffs/{L1}.md": b"# a forged commit\n"}, + f"a forged handoff commit\n\nRegister-Seq: {h + 10}\n") + else: + top = est.commit_in_origin(est.c, {"lanes/STORE": b"store=primary\n"}, + "t270: the marker commit, pushed first\n\nRegister-Seq: 1\n") + est.push_by_hand(top) + one = est.checkout("L1", L1) + est.arm() + proc = est.render(one) + assert proc.returncode == 0, f"the pass at files:\n{_said(proc)}" + assert est.calls("push") == [] and est.origin_tip() == top, "the pass at files pushed" + assert est.mirror()["diverged_sha"] is None, f"a divergence was recorded: {est.mirror()}" + shown = est.status(one) + assert not DIVERGED.search(shown.stdout), f"status prints a divergence:\n{shown.stdout}" + assert est.head() == h and est.switch()["mode"] == "files" + + +def test_a_render_commit_with_a_private_index_and_its_push_are_timed_and_recorded(request, + tmp_path): + """M6, section 5.1 (TP:1229-1235): the render commit made through the + private index, and its push to the local origin, each timed from the + wrapper's log, which tells the commit (`commit-tree`) from the push, over + five renders of one seq each; recorded with section 5.3's statistics and + their n, never asserted. Correctness alongside: each `write-tree` ran + under `GIT_INDEX_FILE` `lanes-render.index`, and origin gains each commit + with its `Register-Seq`. Fails until T320 to T322.""" + est = _estate(request, tmp_path) + one = est.checkout("L1", L1) + commits, pushes = [], [] + for n in range(1, 6): + old = est.origin_tip() + seqs = est.write_sql([f"timed render {n}"]) + est.arm() + proc = est.render(one) + assert proc.returncode == 0, f"timed render {n}:\n{_said(proc)}" + _assert_rendered(est, old, seqs) + trees = est.calls("write-tree", one) + assert trees and all((c["env"]["GIT_INDEX_FILE"] or "").endswith("lanes-render.index") + for c in trees), ( + f"a write-tree ran without the private index: {[c['env'] for c in trees]}") + commits += [(c["t1"] - c["ran"]) * 1000 for c in est.calls("commit-tree", one)] + pushes += [(c["t1"] - c["ran"]) * 1000 for c in est.calls("push", one)] + assert commits and pushes + for what, samples in (("render commit, private index", commits), ("its push", pushes)): + stats = _stats(samples) + row = (f"| M6 | fixture cluster, local bare origin | {what} | median " + f"{stats['median']:.1f} ms, p95 {stats['p95']:.1f} ms, " + f"{stats['min']:.1f}-{stats['max']:.1f} ms, n={stats['n']} |") + print("\n" + row) + summary = os.environ.get("GITHUB_STEP_SUMMARY") + if summary: + with open(summary, "a", encoding="utf-8") as handle: + handle.write(row + "\n") + + +# =================================================================== AT-5: six lost races (T323, T325) +def test_six_lost_races_leave_the_last_write_for_the_next_write_or_reconcile(request, + tmp_path): + """Lane 4's known gap (TP:1044-1045, :1074-1080, :1216-1218): the wrapper + rejects six pushes in a row as non-fast-forwards. The renderer makes six + push attempts in all, a fetch before each new one, and ends non-zero; + origin is unchanged and `status` shows a lag of 1. Then `reconcile`, + run in the lane's checkout with the `mode=primary` configuration, + renders it: origin carries the seq, and the lag is 0. Fails until T320 + to T323, and T325 (the re-render), at its own assertion.""" + est = _estate(request, tmp_path) + one = est.checkout("L1", L1) + seqs = est.write_sql(["the last write, six races lost"]) + old = est.origin_tip() + est.arm([{"sub": "push", "do": "reject", "where": str(one.clone), "times": 6}]) + proc = est.render(one) + assert proc.returncode != 0, f"the renderer that lost six races ended 0:\n{_said(proc)}" + assert est.origin_tip() == old, "origin moved" + calls = est.calls(lc=one) + pushes = [i for i, c in enumerate(calls) if c["sub"] == "push"] + assert len(pushes) == 6 and all(calls[i]["outcome"] == "rejected" for i in pushes), ( + f"not six rejected pushes: {[(c['sub'], c['outcome']) for c in calls]}") + for before, after in zip(pushes, pushes[1:]): + assert any(c["sub"] == "fetch" for c in calls[before + 1:after]), ( + "a push was retried with no fetch after its rejection") + assert est.lag(one) == 1, f"status does not show a lag of 1:\n{est.status(one).stdout}" + proc = est.index(one, "reconcile", conf=est.primary_conf) + assert proc.returncode == 0, f"reconcile:\n{_said(proc)}" + assert est.commits_after(old) and est.commits_after(old)[-1][1] == seqs, ( + f"reconcile did not render seq {seqs[0]} (T325: it re-renders what the mirror lacks, " + f"through T322's pass): origin carries {est.commits_after(old)}\n{_said(proc)}") + _assert_rendered(est, old, seqs) + assert est.lag(one) == 0, f"the lag is not 0 after reconcile:\n{est.status(one).stdout}" + + +# =================================================================== writes that fork +#: THE WRITER- AND FORK-SIDE CASES: each write is `lanes-edit.sh log NOTED` +#: (or lane-start's stamp) on `primary` from a lane's checkout, through the +#: flipped copy, and its fork starts the renderer in the lane's own register +#: checkout `<c>` (`own=True`, T270e), whose calls, lock and marks each case +#: reads. Each fails until lane 4's T415 and T416 (L4-B13), with T320 to +#: T323. Every wait for a forked render is open point 8's. + + +def test_a_renderer_killed_between_commit_and_push_blocks_nothing(request, tmp_path): + """AT-5's kill (TP:1103-1115; P319-346; concern 3, ADV-C6): `L1`'s write + forks a render that the wrapper kills by SIGKILL just before its push. + Read after the renderer's exit (open point 8's second wait): `L1`'s + HEAD, index digest and `status --porcelain` are as before the render. + Then, with no other command between, `L1`'s next write forks a render + that pushes every missing seq in order, and `L1`'s next handoff commit, + lane-handoff's commit block, exits 0 and is pushed. A second kill, then + a write, then lane-start's stamp (`append-session-id`), which exits 0 + and is rendered. Fails until L4-B13 and T320 to T322.""" + est = _estate(request, tmp_path) + one = est.checkout("L1", L1, own=True) + old = est.origin_tip() + before = est.snapshot(one.own) + est.arm([{"sub": "push", "do": "kill", "render_only": True, "where": str(one.own.clone), + "times": 1}]) + mark = est.entries() + _wrote(est.write(one, "a write whose render is killed before its push"), "log NOTED") + est.wait_renders_exit(mark, "the killed render") + assert [c for c in est.render_calls(mark) if c["outcome"] == "killed"], ( + "the wrapper killed no render at its push") + assert est.snapshot(one.own) == before, "the killed render moved L1's HEAD, index or status" + assert _lock_is_free(one.own.git_dir / "lanes-render.lock"), "the render lock is still held" + # The next write, then lane-handoff's commit block, with nothing between. + est.rearm() + _wrote(est.write(one, "the next write after the kill"), "the next log NOTED") + est.wait_lag_0(one, "the next write's render") + _assert_rendered(est, old, list(range(est.n + 1, est.head() + 1))) + handoff = f"handoffs/{L1}.md" + (one.own.clone / "handoffs").mkdir(exist_ok=True) + (one.own.clone / handoff).write_text("# a handoff, after the killed render\n", + encoding="utf-8") + env = dict(est.plain_env, HOME=str(one.home)) + for argv in (["add", "--", handoff], + ["commit", "-q", "-m", f"handoff({L1}@{WS}): PAUSED, t270", "-m", + f"Lane: {L1}", "--", handoff], + ["pull", "--rebase", "-q", "origin", "main"], ["push", "-q", "origin", "main"]): + est.git(one.own.clone, *argv, env=env) + assert handoff in est.origin_git("ls-tree", "-r", "--name-only", "refs/heads/main", + "handoffs/").split(), "the handoff commit was not pushed" + # The second case: a kill, a write, then lane-start's stamp. It arms the + # kill afresh with `est.arm()`, which starts the wrapper's log and its + # counts again: `rearm()` keeps each arm's count of uses, and the first + # case's kill used arm 0's one (`times: 1`), so a re-armed kill never + # fired and the second case passed with no kill (RV20, finding 2). + est.arm([{"sub": "push", "do": "kill", "render_only": True, "where": str(one.own.clone), + "times": 1}]) + mark = est.entries() + _wrote(est.write(one, "a second write whose render is killed"), "log NOTED") + est.wait_renders_exit(mark, "the second killed render") + assert [c for c in est.render_calls(mark) if c["outcome"] == "killed"], ( + f"the wrapper killed no render at the second case's push: " + f"{[(c['sub'], c['outcome']) for c in est.render_calls(mark)]}") + est.rearm() + _wrote(est.write(one, "the write after the second kill"), "log NOTED") + stamp = est.edit(one, "append-session-id", L1, f"harness `{UUID_L1}`", " (t270)") + _wrote(stamp, "lane-start's stamp, append-session-id") + est.wait_lag_0(one, "the stamp's render") + + +def _held_burst(est: RenderEstate, one) -> SimpleNamespace: + """AT-5's HELD RENDERER (TP:1116-1125): `L1`'s render held at its push + (the hold re-armed for each push) while four more writes from `L1` each + exit 0; then the hold is disarmed and released, and both of open point + 8's waits run. Returns what the case reads. The hold, the FIFO and every + renderer are owned from the FIFO's making to the end: the `try` begins + at once after `mkfifo`, with every fallible call inside it, and its + `finally` disarms the hold, ends every process of the estate, then lets + the FIFO go with an abort and unlinks it (`_end_held_renders`). The hold + is released into its push only where the four forks were seen; where + they were not, the held call is ended with the rest and never let go + into its git. The four forks' result, saved while the hold stood, is + asserted only after the clean-up (lane 3's Codex reviews of code PR 97 + at `6d479418`, SHOULD 3, and at `18529e5a`, SHOULDs 1 and 3).""" + fifo = est.root / "held.fifo" + os.mkfifo(str(fifo), 0o600) + fd, mark = None, 0 + try: + rerun = one.own.git_dir / "lanes-render.rerun" + old = est.origin_tip() + est.arm([{"sub": "push", "do": "hold", "render_only": True, "fifo": str(fifo), + "where": str(one.own.clone)}]) + mark = est.entries() + _wrote(est.write(one, "the first write of a burst"), "log NOTED") + fd = _held_fd(fifo, "the first write's render, at its push") + holder = {c["renderer"] for c in est.render_calls(mark) if c["outcome"] == "held"} + waited = [] + for n in range(2, 6): + start = time.monotonic() + _wrote(est.write(one, f"write {n} of a burst, while the render is held", + timeout=120), f"write {n}") + waited.append(time.monotonic() - start) + + def forks() -> dict: + return {c["renderer"]: c["renderer_start"] for c in est.render_calls(mark) + if c["renderer"] not in holder} + # A detached fork may start after its write returns: wait, the hold + # standing, until the four have run a git call and exited, or 30 s. + # The hold is released only once that holds: four writes, four forks, + # each a renderer other than the holder (TP:1116-1120; lane 3's Codex + # review of code PR 97, SHOULD 5). + settled = _until(lambda: len(forks()) >= 4 + and all(_exited(p, s) for p, s in forks().items()), CEILING) + held_forks = forks() + forks_live = [pid for pid, start in held_forks.items() if not _exited(pid, start)] + marked = rerun.exists() + four = settled and len(held_forks) >= 4 + if four: # where they were not seen, the case fails below, after the clean-up + est.rearm() + end, fd = fd, None + _let_go(fifo, end) # the hold released: its FIFO unlinked, then the write end closed + est.wait_lag_0(one, "the burst's last write") + est.wait_renders_exit(mark, "the burst's renders") + finally: + _end_held_renders(est, fifo, fd, mark) + assert four, ( + f"with the render held, {len(held_forks)} renderers besides the holder ran " + f"`render --checkout`, not at least four, one per write, all exited within " + f"{CEILING:g} s: {sorted(held_forks)}, still live {forks_live}") + assert _lock_is_free(one.own.git_dir / "lanes-render.lock"), "the render lock is still held" + pushes = [c for c in est.render_calls(mark) if c["sub"] == "push" and c["outcome"] == "ran"] + return SimpleNamespace(old=old, holder=holder, marked=marked, forks=forks(), + forks_live=forks_live, waited=waited, pushes=pushes, + rerun_left=rerun.exists()) + + +def test_a_held_renderer_delays_no_writer_beyond_the_fork(request, tmp_path): + """AT-5's held renderer (TP:1116-1120, :1240-1241): with `L1`'s render + held at its push, four more writes from `L1` each exit 0 while it is + held, so no fork waited; each fork that found the lock held left + `lanes-render.rerun` in the checkout's git directory and had exited + while the hold still stood (D14). Fails until L4-B13 and T320 to T322.""" + est = _estate(request, tmp_path) + one = est.checkout("L1", L1, own=True) + seen = _held_burst(est, one) + assert len(seen.holder) == 1, f"not one held render: {seen.holder}" + assert seen.marked, "no fork that found the lock held left lanes-render.rerun" + assert seen.forks, "no fork of the four writes ran `render --checkout`" + assert not seen.forks_live, ( + f"forks {seen.forks_live} that found the lock held had not exited while it was held") + + +def test_a_burst_from_one_lane_gives_at_most_two_renders(request, tmp_path): + """[L4-3], qualified (TP:1028-1030, :1121-1125, :1242): the held + renderer's burst of five writes. Once the lag is 0 and every renderer + has exited, at most two renders made commits, the wrapper's log + counting their pushes, and origin carries the burst's last seq, each + seq once, in order. Fails until L4-B13 and T320 to T323.""" + est = _estate(request, tmp_path) + one = est.checkout("L1", L1, own=True) + seen = _held_burst(est, one) + assert 1 <= len(seen.pushes) <= 2, ( + f"{len(seen.pushes)} pushes for a burst that arrived within one pass, not at most two: " + f"{[_push_tip(p)[:12] for p in seen.pushes]}") + _assert_rendered(est, seen.old, list(range(est.n + 1, est.head() + 1))) + + +def test_the_last_write_of_a_burst_is_rendered_with_no_later_write(request, tmp_path): + """S2 (TP:1031): five writes from `L1` in a row, no hold, and no later + write. Within open point 8's waits the lag reaches 0 and every renderer + exits; origin carries every seq of the burst, its last included, in + order. Fails until L4-B13 and T320 to T323.""" + est = _estate(request, tmp_path) + one = est.checkout("L1", L1, own=True) + old = est.origin_tip() + est.arm() + for n in range(1, 6): + _wrote(est.write(one, f"burst write {n}, with no later write"), f"write {n}") + est.wait_lag_0(one, "the burst's last write") + est.wait_renders_exit(0, "the burst's renders") + _assert_rendered(est, old, list(range(est.n + 1, est.head() + 1))) + + +@pytest.mark.parametrize("fail", ["fetch", "push"]) +def test_a_failed_render_shows_its_lag_and_the_next_render_catches_up(request, tmp_path, fail): + """AT-5's failed render (TP:1134-1149): every render's `fetch` (or + `push`) fails. After the write, open point 8's second wait: SQL holds + the seq and `status` shows a lag of 1; `last_error` and its time are set + by the failed pass, and `diverged_sha` stays NULL; in the push case each + push follows a fetch, six pushes at most; and after the renderer's exit + no pass follows it, no render's `fetch` or `push` until the next write. + Released, the next write's render leaves both seqs on origin in order, + and a lag of 0. Fails until L4-B13 and T320 to T323.""" + est = _estate(request, tmp_path) + one = est.checkout("L1", L1, own=True) + old = est.origin_tip() + est.arm([{"sub": fail, "do": "fail", "render_only": True, "where": str(one.own.clone)}]) + mark = est.entries() + _wrote(est.write(one, f"a write whose render's {fail} fails"), "log NOTED") + est.wait_renders_exit(mark, f"the render whose {fail} fails") + k = est.head() + assert k == est.n + 1 and est.origin_tip() == old, "the failed render pushed" + assert est.lag(one) == 1, f"status does not show a lag of 1:\n{est.status(one).stdout}" + mirror = est.mirror() + assert mirror["last_error"] and mirror["last_error_utc"], ( + f"the failed pass recorded nothing: {mirror}") + assert mirror["diverged_sha"] is None, f"a divergence was recorded: {mirror}" + calls = est.render_calls(mark) + if fail == "push": + pushes = [i for i, c in enumerate(calls) if c["sub"] == "push"] + assert 1 <= len(pushes) <= 6, f"{len(pushes)} pushes, not one to six" + for i in pushes: + assert any(c["sub"] == "fetch" for c in calls[:i]), "a push with no fetch before it" + ended = est.entries() + est.rearm() + assert not [c for c in est.render_calls(ended) if c["sub"] in ("fetch", "push")], ( + "a pass followed the failed one (F15: a pass that pushed nothing ends the renderer)") + _wrote(est.write(one, "the next write, after the release"), "the next log NOTED") + est.wait_lag_0(one, "the next write's render") + _assert_rendered(est, old, [k, k + 1]) + + +def test_a_renderer_hands_over_once_after_16_passes(request, tmp_path): + """PC-3's handover (TP:1046-1049, :1210-1215): a stream of 17 writes + from `L1`, one per pass, each made while that pass is held at its push + (the hold re-arms for each push). Each write waits for that pass's push + in the wrapper's raw log, so no two writes share a pass. No renderer + process makes more than 16 passes (a pass begins with its fetch), a + second process follows once, and the last write reaches origin. Fails + until L4-B13 and T320 to T323.""" + est = _estate(request, tmp_path) + one = est.checkout("L1", L1, own=True) + old = est.origin_tip() + fifo = est.root / "pass.fifo" + os.mkfifo(str(fifo), 0o600) + fd = None + try: # the hold, the FIFO and the renders owned to the end (`_end_held_renders`) + est.arm([{"sub": "push", "do": "hold", "render_only": True, "fifo": str(fifo), + "where": str(one.own.clone)}]) + _wrote(est.write(one, "stream write 1"), "write 1") + # Write n waits for pass n-1's push, the (n-1)-th held line in the raw + # log (lane 3's #38, #165 6859801732). `_held_fd` alone could reopen the + # FIFO onto the push just released, before its wrapper saw EOF: that + # push stayed held through write n, and the next pass rendered two seqs. + for n in range(2, 18): + fd = _kth_held_fd(est, fifo, n - 1, f"pass {n - 1}'s push") + _wrote(est.write(one, f"stream write {n}", timeout=120), f"write {n}") + end, fd = fd, None + os.close(end) # pass n-1's push let go; the FIFO stays, for pass n's + fd = _kth_held_fd(est, fifo, 17, "the last pass's push") + est.rearm() + end, fd = fd, None + _let_go(fifo, end) # the last push let go: the FIFO unlinked, then the write end closed + est.wait_lag_0(one, "the stream's last write") + est.wait_renders_exit(0, "the stream's renders") + finally: + _end_held_renders(est, fifo, fd, 0) + # Each pass renders one write and pushes it once (nothing rejects here), + # so a renderer's pushes count its passes that made progress. + passes: dict = {} + for call in est.render_calls(0): + if call["sub"] == "push" and call["outcome"] == "ran": + passes[call["renderer"]] = passes.get(call["renderer"], 0) + 1 + assert sum(passes.values()) == 17, ( + f"the 17 writes did not go out in 17 render pushes, one per pass: {passes}") + assert passes and max(passes.values()) <= 16, f"a renderer made more than 16 passes: {passes}" + assert len(passes) == 2, ( + f"{len(passes)} renderer processes pushed, not the first and one that follows it: " + f"{passes}") + _assert_rendered(est, old, list(range(est.n + 1, est.n + 18))) + + +def test_no_rerun_mark_is_left_and_the_last_write_is_rendered_after_a_burst(request, tmp_path): + """D14's handshake (TP:1219-1221): after each of two bursts of 10 forks + from `L1`, both halves of the `flock` handshake leave no + `lanes-render.rerun`, and origin carries the last seq. Fails until + L4-B13 and T320 to T323.""" + est = _estate(request, tmp_path) + one = est.checkout("L1", L1, own=True) + old = est.origin_tip() + est.arm() + for burst in (1, 2): + mark = est.entries() + for n in range(1, 11): + _wrote(est.write(one, f"burst {burst}, fork {n}"), f"burst {burst}, write {n}") + est.wait_lag_0(one, f"burst {burst}") + est.wait_renders_exit(mark, f"burst {burst}'s renders") + assert not (one.own.git_dir / "lanes-render.rerun").exists(), ( + f"burst {burst} left lanes-render.rerun") + assert est.commits_after(old)[-1][1] == [est.head()], ( + f"origin does not carry burst {burst}'s last seq {est.head()}") + _assert_rendered(est, old, list(range(est.n + 1, est.head() + 1))) + + +def test_a_write_that_commits_as_the_render_lets_go_is_rendered_with_no_later_write(request, + tmp_path): + """Commit I's "A write that commits as the render lets go" (TP:1084-1090, + :1126-1133; S2's two halves of `SyncLock`'s handshake): `L1`'s first + write forks a render, and the `psql` shim holds that render's second + pass, one-shot, once the real `psql` has returned its read of the head, + which holds no entry after `m`. A second write from `L1` commits and + exits 0; its fork finds the lock held, leaves `lanes-render.rerun`, and + exits. The case releases the shim and makes no later write: the second + write's seq reaches origin, `status` shows a lag of 0, and no + `lanes-render.rerun` is left. Fails until L4-B13 and T320 to T323.""" + est = _estate(request, tmp_path) + one = est.checkout("L1", L1, own=True) + old = est.origin_tip() + fifo = est.root / "lets-go.fifo" + os.mkfifo(str(fifo), 0o600) + fd, mark = None, 0 + try: # the hold, the FIFO and the renders owned to the end (`_end_held_renders`) + est.arm(shim_arms=[{"mode": "timer", "fifo": str(fifo), + "match": "FROM register_head h, register_switch s", "call": 2}]) + mark = est.entries() + _wrote(est.write(one, "the first write; its render lets go"), "write 1") + fd = _held_fd(fifo, "the render's second pass, after its read of the head") + _wrote(est.write(one, "the write that commits as the render lets go", timeout=120), + "write 2") + assert _until(lambda: (one.own.git_dir / "lanes-render.rerun").exists(), CEILING), ( + "the second write's fork found the lock held and left no lanes-render.rerun") + end, fd = fd, None + _let_go(fifo, end) # the render let go: its FIFO unlinked, then the write end closed + est.wait_lag_0(one, "the write that commits as the render lets go") + est.wait_renders_exit(mark, "the renders") + finally: + _end_held_renders(est, fifo, fd, mark) + _assert_rendered(est, old, [est.n + 1, est.n + 2]) + assert not (one.own.git_dir / "lanes-render.rerun").exists(), "lanes-render.rerun is left" + + +# =================================================================== AT-C8 +def test_a_render_forked_from_a_no_fetch_verb_still_renders(request, tmp_path): + """AT-C8 (C172-184; TP:3173-3196): `log NOTED` run with + `LANES_NO_FETCH=1` from `L1`'s checkout on a primary estate. Its render + commit reaches origin and `status` reports a lag of 0 (open point 8's + first wait); the wrapper's log shows the renderer's own fetch, made with + the variable absent from its environment, and no render's call made + with it set (D12). Fails until L4-B13 and T320 to T322.""" + est = _estate(request, tmp_path) + one = est.checkout("L1", L1, own=True) + old = est.origin_tip() + est.arm() + _wrote(est.write(one, "a write under LANES_NO_FETCH=1", env={"LANES_NO_FETCH": "1"}), + "log NOTED under LANES_NO_FETCH=1") + est.wait_lag_0(one, "the no-fetch write's render") + est.wait_renders_exit(0, "the no-fetch write's render") + _assert_rendered(est, old, [est.n + 1]) + renders = est.render_calls(0) + fetches = [c for c in renders if c["sub"] == "fetch"] + assert fetches and all(c["env"]["LANES_NO_FETCH"] is None for c in fetches), ( + f"the renderer made no fetch of its own with LANES_NO_FETCH absent: " + f"{[(c['argv'], c['env']['LANES_NO_FETCH']) for c in fetches]}") + assert not [c["argv"] for c in renders if c["env"]["LANES_NO_FETCH"] is not None], ( + "a render's git call inherited LANES_NO_FETCH") + + +# =================================================================== the clean-up's own faults +#: The fault-path regressions of this module's own clean-up (lane 3's Codex +#: reviews of code PR 97 at `6d479418`, SHOULDs 1, 3 and 4, at `18529e5a`, +#: BLOCKING and SHOULDs 1, 3 and 4, and at `46cac748`, BLOCKING and SHOULDs 1 +#: to 7; the coordinator's reproductions, #165 6934112467, and his three +#: points, #165 6938182757). They need no engine and no task, so each has an +#: empty gate row and ordinary PR CI runs it (SHOULD 5 at `18529e5a`). Each +#: process they start is theirs: a child by its `Popen`, any other launched +#: with the case's nonce (`_with_identity`) and pinned by it (`_pin`). Each +#: case owns what it makes from its making: its variables first, then each +#: FIFO made with the `try` at once after it, whose `finally` ends every +#: process, lets each FIFO go with an abort, kills each pin and reaps each +#: child, each step tried whatever the one before it raised (`_each`; +#: SHOULD 5 at `46cac748`). No process of anyone else's is signalled: +#: `os.killpg` is stubbed where a stub child stands for a renderer, and the +#: clean-up under test signals only what it pinned by the case's identity. +#: The stand-ins and helpers these share with the rollback module's +#: (`LINUX_ONLY`, `SLEEP`, `SAY_ME`, `LEADS_A_GROUP`, `LEAVES_A_MEMBER`, +#: `_Pipe`, `_Undying`, `_with_identity`, `_fifo_reader`, `_ended`, +#: `_reap_all`, `_each`, `_GapFifo`, `_reported` and `_end_pin`) are +#: `tests/sql_register_cleanup.py`'s (round CX-34). + + +#: A renderer's stand-in that forks a git call into a session of its own and +#: stays. The call says who it is (`SAY_ME`), blocks on the FIFO `argv[1]` as +#: a held wrapper's call does and, let go by EOF with no abort mark, makes +#: the file `argv[2]`, as its git would run. +FORKS_A_CALL = SAY_ME + ("if os.fork() == 0:\n" + " os.setsid()\n" + " say_me()\n" + " with open(sys.argv[1], 'rb') as fifo:\n" + " said = fifo.read()\n" + " if not said and not os.path.exists(sys.argv[1] + '.abort'):\n" + " open(sys.argv[2], 'x').close()\n" + " os._exit(0)\n" + "time.sleep(300)\n") + +#: A write's detached fork's stand-in: a child in a session of its own that +#: says who it is (`SAY_ME`) and stays, its starter ending at once, so it is +#: no child of the case. Its argv names `argv[1]`. +DETACHES = SAY_ME + ("if os.fork() == 0:\n" + " os.setsid()\n" + " say_me()\n" + " time.sleep(300)\n" + " os._exit(0)\n") + + +#: THE WRAPPER'S KILL, MODELLED (lane 2's decisions 1, 2 and 7 in round +#: CX-33): `GIT_WRAPPER`'s functions, imported from the file `argv[1]` with no +#: `main()` run (its last line runs it only as a script), on the model named +#: `argv[2]`, with stand-ins for its `os`, `signal`, `select`, `time` and +#: `sys`, and for its readers of `/proc` (`stat`, `carried`): no process is +#: read or signalled. The renderer is pid 4000; 4001 and 4002 are members of +#: its group with the case's nonce; 4003 has the nonce in a group of its own; +#: 4004 is in the renderer's group without the nonce. It prints, as JSON, each +#: signal sent through a pidfd, by pid, each pidfd opened and closed, and +#: what `kill_above` raised. Round CX-34's models (lane 3's Codex review of +#: code PR 97 at `f776b435`, SHOULDs 1 and 3): `lead-gone`, the renderer gone +#: before it is pinned; `stop-never`, 4002's stop never seen; `close-error`, +#: the close of 4001's pidfd fails (EIO); `pin-raises`, the signal 0 of +#: 4002's pin is refused (EPERM). Round CX-35's model (lane 3's Codex review +#: of code PR 97 at `5a120647`, SHOULD 2): `stop-forks`, 4002's stop never +#: seen, and in that gap it forks 4005, a late member of the group, shown +#: only once 4002 has been sent SIGKILL, so only a read made after the kill +#: finds it (lane 2's pre-review RV7-35, S1). +KILL_HARNESS = r''' +import errno, importlib.util, io, json, sys +from types import SimpleNamespace + +NONCE, MODEL, IDENTITY = "n0nce", sys.argv[2], sys.argv[3] +GROUP = {4000: 4000, 4001: 4000, 4002: 4000, 4003: 4003, 4004: 4000, 4005: 4000} +CARRY = {4000: NONCE, 4001: NONCE, 4002: NONCE, 4003: NONCE, 4005: NONCE} +if MODEL == "stranger-above": + del CARRY[4000] # the pid and start token above, but not the case's identity +sent, opened, opens, closed, now = [], {}, [], [], {"t": 0.0, "reads": {}} +gone, stops = ({4000} if MODEL == "lead-gone" else set()), set() + + +def listdir(path): + if MODEL == "proc-error": + raise OSError(errno.EIO, "a read of /proc failed") + late = (MODEL == "late-stop" and now["reads"].get(4002, 0) >= 1) or ( + MODEL == "stop-forks" and [4002, "KILL"] in sent) + return [str(pid) for pid in sorted(GROUP) if pid != 4005 or late] + ["self"] + + +def pidfd_open(pid): + if MODEL == "member-emfile" and pid == 4002: + raise OSError(errno.EMFILE, "Too many open files") + if pid in gone or pid not in GROUP: + raise ProcessLookupError(errno.ESRCH, "No such process") + opened[100 + pid - 4000] = pid + opens.append(pid) + return 100 + pid - 4000 + + +def pidfd_send_signal(fd, sig): + pid = opened[fd] + if sig != 0: + sent.append([pid, sig]) + if pid in gone: + raise ProcessLookupError(errno.ESRCH, "No such process") + if MODEL == "pin-raises" and pid == 4002 and sig == 0: + raise PermissionError(errno.EPERM, "Operation not permitted") + if MODEL == "kill-refused" and pid == 4001 and sig == "KILL": + raise PermissionError(errno.EPERM, "Operation not permitted") + if sig == "STOP": + stops.add(pid) + if MODEL == "lead-ends" and pid == 4000: + gone.add(4000) # the leader ends once it is stopped, its members left + elif sig == "KILL": + gone.add(pid) + + +def stat(pid): + if pid in gone or pid not in GROUP: + return None + reads = now["reads"][pid] = now["reads"].get(pid, 0) + (pid in stops) + landed = pid in stops and not (MODEL == "late-stop" and pid == 4002 and reads < 2) and not ( + MODEL in ("stop-never", "stop-forks") and pid == 4002) + return [b"T" if landed else b"S", b"1", str(GROUP[pid]).encode(), b"1"] + [b"0"] * 15 + [b"500"] + [b"0"] * 5 + + +def select_(r, w, x, t): + return [fd for fd in r if opened.get(fd) in gone], [], [] + + +def sleep(seconds): + now["t"] += seconds + + +def close(fd): + closed.append(fd) + if MODEL == "close-error" and opened[fd] == 4001: + raise OSError(errno.EIO, "the close failed") + + +spec = importlib.util.spec_from_file_location("git_wrapper", sys.argv[1]) +wrapper = importlib.util.module_from_spec(spec) +spec.loader.exec_module(wrapper) +wrapper.os = SimpleNamespace(listdir=listdir, pidfd_open=pidfd_open, getpid=lambda: 9999, + close=close, environ={IDENTITY: NONCE}) +wrapper.signal = SimpleNamespace(SIGSTOP="STOP", SIGKILL="KILL", + pidfd_send_signal=pidfd_send_signal) +wrapper.select = SimpleNamespace(select=select_) +wrapper.time = SimpleNamespace(monotonic=lambda: now["t"], sleep=sleep) +wrapper.sys = SimpleNamespace(stderr=io.StringIO(), exit=sys.exit) +wrapper.stat = stat +wrapper.carried = CARRY.get +raised = cause = None +try: + wrapper.kill_above(4000) +except Exception as exc: # recorded for the case to assert + raised = [type(exc).__name__, errno.errorcode.get(getattr(exc, "errno", None))] + cause = None if exc.__cause__ is None else str(exc.__cause__) +print(json.dumps({"sent": sent, "opened": sorted(opens), + "closed": sorted(opened[fd] for fd in closed), "raised": raised, + "cause": cause, "said": wrapper.sys.stderr.getvalue()})) +''' + + +class _Stuck: + """A child that never ends: each `communicate()` and `wait()` times + out, and nothing ever sets its `returncode`. Its pid is never + signalled: the cases that use it stub `os.killpg`.""" + + pid = 4194304 + 7 # above Linux's pid_max ceiling, so no process has it + + def __init__(self): + self.returncode = None + self.stdout, self.stderr = _Pipe(), _Pipe() + self.calls: list = [] + + def communicate(self, input=None, timeout=None): + self.calls.append("communicate") + raise subprocess.TimeoutExpired("stuck", timeout) + + def wait(self, timeout=None): + self.calls.append("wait") + raise subprocess.TimeoutExpired("stuck", timeout) + + def poll(self): + return None + + +def _kill_pinned(pins: list) -> None: + """Each process a case pinned (`_reported`) ended and seen gone, its + pidfd closed (`_end_pin`), every one tried whatever an earlier one + raised; then the first error raised, the others named as its cause.""" + _each(*[lambda held=held: _end_pin(held) for held in pins]) + + +def _kill_models(tmp_path: Path, *models: str) -> dict: + """`KILL_HARNESS` run on each of `models` against this module's + `GIT_WRAPPER`, each in a child Python of its own, bounded: {model: what + it printed}.""" + wrapper = tmp_path / "git_wrapper.py" + harness = tmp_path / "kill_harness.py" + wrapper.write_text(GIT_WRAPPER, encoding="utf-8") + harness.write_text(KILL_HARNESS, encoding="utf-8") + found = {} + for model in models: + ran = subprocess.run([sys.executable, "-I", "-B", str(harness), str(wrapper), model, + IDENTITY], + capture_output=True, text=True, timeout=60, check=False) + assert ran.returncode == 0, f"the harness failed on {model}:\n{_said(ran)}" + found[model] = json.loads(ran.stdout) + return found + + +def _killed(model: dict) -> set: + """The pids a modelled kill sent SIGKILL to.""" + return {pid for pid, sig in model["sent"] if sig == "KILL"} + + +def test_end_session_raises_rather_than_return_with_its_child_unreaped(monkeypatch): + """SHOULD 4 at `6d479418`: `_end_session`, on a child whose every + `communicate()` and `wait()` times out, signals its group SIGTERM, then + SIGKILL (stubbed), closes the child's pipes, waits once more, bounded, + and then raises: it never returns with `returncode` None.""" + signals = [] + monkeypatch.setattr(os, "killpg", lambda pid, sig: signals.append((pid, sig))) + stuck = _Stuck() + with pytest.raises(RuntimeError, match="still unreaped"): + _end_session(stuck, grace=0) + assert signals == [(stuck.pid, signal.SIGTERM), (stuck.pid, signal.SIGKILL)], signals + assert stuck.calls == ["communicate", "communicate", "wait"], stuck.calls + assert stuck.stdout.closed and stuck.stderr.closed, "the child's pipes were left open" + + +def test_race_raises_its_clean_up_error_and_leaves_no_barrier_fifo(monkeypatch, tmp_path): + """SHOULDs 4 and 1 at `6d479418`, `RenderEstate.race`: where a launcher + never waits and cannot be reaped, the case fails with the clean-up's own + error, not with the launcher left unreaped behind an assertion, and its + barrier FIFO is gone. Stubbed: the launcher (`_Stuck`), `os.killpg`, and + `_open_when_held`, which gives None at once.""" + signals = [] + monkeypatch.setattr(os, "killpg", lambda pid, sig: signals.append((pid, sig))) + monkeypatch.setattr(sys.modules[__name__], "_open_when_held", lambda fifo, proc: None) + stuck = _Stuck() + estate = SimpleNamespace(root=tmp_path, bin=tmp_path / "bin", + popen_render=lambda lc, conf=None, argv=None: stuck, + render_argv=lambda lc: ["render"]) + with pytest.raises(RuntimeError, match="still unreaped"): + RenderEstate.race(estate, [SimpleNamespace(name="L1")]) + assert not (tmp_path / "barrier-L1.fifo").exists(), "race() left its barrier FIFO" + assert signals and set(signals) <= {(stuck.pid, signal.SIGTERM), + (stuck.pid, signal.SIGKILL)}, signals + + +@LINUX_ONLY +def test_a_fifo_let_go_leaves_no_reader_blocked(tmp_path): + """SHOULD 1 at `6d479418`: `_let_go`, the owner's last release, leaves + no reader blocked on its FIFO. With no write end held, a reader that + comes in the gap just before the unlink is let go. With the write end + held, as a hold site holds it, the reader already on the FIFO and one + that comes in that gap both read EOF. Either way the FIFO is gone, and a + reader that comes after finds none (ENOENT) and ends. Each gap reader + must be seen on the FIFO before its unlink, so the race is exercised, + before any exit is read: then the three readers before the release exit + 0, and only the one after it meets ENOENT (lane 3's Codex review of code + PR 97 at `18529e5a`, SHOULD 4).""" + fifo = tmp_path / "held.fifo" + readers: list = [] + try: + os.mkfifo(str(fifo), 0o600) + first = _GapFifo(fifo, readers) + _let_go(first) + assert _ended(readers[0]), ( + "with no write end held, a reader that came in the gap before the unlink is left " + "blocked on the unlinked FIFO") + os.mkfifo(str(fifo), 0o600) + readers.append(_fifo_reader(fifo)) + fd = _held_fd(fifo, "the reader already on the FIFO", 10) + second = _GapFifo(fifo, readers) + _let_go(second, fd) + assert not fifo.exists(), "the FIFO is still there after its let-go" + readers.append(_fifo_reader(fifo)) + left = [n for n, proc in enumerate(readers) if not _ended(proc)] + assert not left, f"readers {left} of {len(readers)} are left blocked" + finally: + said = _reap_all(readers) + assert first.on and second.on, ( + f"a gap reader was not seen on the FIFO before its unlink (first {first.on}, second " + f"{second.on}), so the race went unexercised") + assert [proc.returncode for proc in readers[:3]] == [0, 0, 0], ( + [proc.returncode for proc in readers], said) + assert readers[3].returncode != 0 and "FileNotFoundError" in said[3], ( + f"a reader that came after the let-go found a FIFO: {said[3]}") + + +@LINUX_ONLY +def test_a_held_burst_ends_its_renders_before_its_assertion_fails(monkeypatch, tmp_path): + """SHOULD 3 at `6d479418`: where the four forks are not seen while the + hold stands, `_held_burst` fails only after its clean-up: the hold + disarmed, the held call ended and never let go into its git, the FIFO + unlinked, and the renderer the wrapper logged killed through its pidfd, + pinned by the case's identity (SHOULDs 1 and 2 at `18529e5a`; BLOCKING + at `46cac748`). Stubbed: the estate and its writes, and `CEILING`, 1 s; + the held call is a FIFO reader of this case's, the renderer a child of + this case's in a session of its own, each launched with the estate's + nonce.""" + monkeypatch.setattr(sys.modules[__name__], "CEILING", 1.0) + fifo = tmp_path / "held.fifo" + held, renderers, arms, nonce = [], [], [], _nonce() + try: + renderers.append(subprocess.Popen( + [sys.executable, "-I", "-c", SLEEP], stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True, + env=_with_identity(nonce))) + logged = [{"renderer": renderers[0].pid, "renderer_start": _stat(renderers[0].pid)["start"], + "sub": "push", "outcome": "held", "render": True}] + + def write(lc, text, env=None, timeout=300): + if not held: # the first write's render, held at its push + held.append(_fifo_reader(fifo, _with_identity(nonce))) + return SimpleNamespace(returncode=0, stdout="", stderr="") + + est = SimpleNamespace(root=tmp_path, bin=tmp_path / "bin", nonce=nonce, + origin_tip=lambda: "0" * 40, entries=lambda: 0, arm=arms.append, + rearm=lambda new=(): arms.append(list(new)), write=write, + render_calls=lambda after=0: logged) + one = SimpleNamespace(own=SimpleNamespace(git_dir=tmp_path, clone=tmp_path)) + with pytest.raises(AssertionError, match="not at least four"): + _held_burst(est, one) + assert arms[-1] == [], f"the hold was not disarmed: {arms}" + assert not fifo.exists(), "the hold FIFO is still there" + assert held and _ended(held[0]), "the held call was not ended" + assert _ended(renderers[0]), "the renderer was not ended" + finally: + _reap_all(held + renderers) + assert renderers[0].returncode == -signal.SIGKILL, renderers[0].returncode + + +@LINUX_ONLY +def test_a_clean_up_signals_through_pidfds_alone_and_spares_a_wrong_start_token(monkeypatch, + tmp_path): + """BLOCKING at `18529e5a`: the render clean-up (`_end_renders`) signals + only through pidfds, each pinned by the case's identity, never by a + number or a group's id, and runs no command. A renderer that leads a + session of its own, with a member in its group, both launched with the + estate's nonce, is logged with its right start token; a stranger, alive + and without the nonce, is logged with its token one tick off, as a + process that took a logged pid would be. With `os.kill`, `os.killpg`, + `os.getpgid`, `subprocess.run` and `subprocess.Popen` stubbed as + recorders, the clean-up calls none of them; the renderer ends by + SIGKILL, its member is gone, and the stranger is untouched.""" + estate = tmp_path / "estate" + procs, pins, calls, nonce = [], [], [], _nonce() + + def recorder(name): + def record(*args, **kwargs): + calls.append(name) + return SimpleNamespace(returncode=0, stdout="", stderr="") + return record + + try: + leader = subprocess.Popen([sys.executable, "-I", "-c", LEADS_A_GROUP], + stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, text=True, start_new_session=True, + env=_with_identity(nonce)) + procs.append(leader) + stranger = subprocess.Popen([sys.executable, "-I", "-c", SLEEP], stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + procs.append(stranger) + pins.append(_reported(leader, "the renderer's group member", nonce)) + token = int(_stat(stranger.pid)["start"]) + logged = [{"renderer": leader.pid, "renderer_start": _stat(leader.pid)["start"]}, + {"renderer": stranger.pid, "renderer_start": str(token + 1)}] + est = SimpleNamespace(root=estate, bin=estate / "bin", nonce=nonce, + render_calls=lambda after=0: logged) + with monkeypatch.context() as stubs: + for owner, name in ((os, "kill"), (os, "killpg"), (os, "getpgid"), + (subprocess, "run"), (subprocess, "Popen")): + stubs.setattr(owner, name, recorder(f"{owner.__name__}.{name}")) + _end_renders(est, 0, grace=2) + assert not calls, f"the clean-up ran a command or signalled by a number: {calls}" + assert _ended(leader) and leader.returncode == -signal.SIGKILL, ( + f"the logged renderer was not killed: {leader.returncode}") + assert _until(pins[0].gone, 5), "the renderer's group member is still there" + assert stranger.poll() is None, "the process logged with a wrong start token was signalled" + finally: + _each(lambda: _kill_pinned(pins), lambda: _reap_all(procs)) + + +@LINUX_ONLY +def test_a_hold_clean_up_ends_a_call_forked_before_its_first_record(tmp_path): + """SHOULD 1 at `18529e5a`: a hold site's clean-up (`_end_hold`) ends a + call its renderer forked into a session of its own before the call made + any record, so before the wrapper's log or its launch records name it: + found by the case's identity, which it inherits from the renderer, and + ended through its pidfd before the FIFO is let go, so it is never let go + into its git. The renderer's stand-in leads a session of its own; the + call blocks on the hold FIFO and, let go with no abort, makes the file + `ran`, as its git would run. Its argv, its cwd and the FIFO are outside + the estate's root, and nothing is logged, so only its identity finds + it. The FIFO is owned from its making (SHOULD 5 at `46cac748`).""" + estate, outside = tmp_path / "estate", tmp_path / "outside" + estate.mkdir() + outside.mkdir() + fifo, ran = outside / "call.fifo", outside / "ran" + renderer, pins, fd, nonce = None, [], None, _nonce() + est = SimpleNamespace(root=estate, bin=estate / "bin", nonce=nonce) + try: + os.mkfifo(str(fifo), 0o600) + renderer = subprocess.Popen([sys.executable, "-I", "-c", FORKS_A_CALL, str(fifo), + str(ran)], cwd=str(outside), stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, + start_new_session=True, env=_with_identity(nonce)) + pins.append(_reported(renderer, "the call the renderer forked", nonce)) + fd = _open_when_held(fifo, renderer, 30) + assert fd is not None, "the forked call never blocked on the hold FIFO" + end, fd = fd, None + _end_hold(renderer, fifo, end, est) + assert _until(pins[0].gone, 5), "the call forked before its first record is still there" + assert not ran.exists(), "the clean-up let the forked call go into its git" + finally: + _each(lambda: _quiesce(est, roots=[renderer], grace=5), + lambda: _let_go(fifo, fd, abort=True), lambda: _kill_pinned(pins), + lambda: _reap_all([renderer] if renderer is not None else [])) + + +@LINUX_ONLY +def test_a_render_clean_up_ends_a_detached_render_no_log_names(tmp_path): + """SHOULD 1 at `18529e5a`: a forked-render case's clean-up + (`_end_held_renders`) ends a detached render that no line of the + wrapper's log names, a write's fork that never reached its first git + call: no child of this process, in a session of its own, found by the + case's identity, which it inherits from the write that started it, and + killed through its pidfd. The hold is disarmed, and the FIFO let go with + an abort and gone. The FIFO is owned from its making (SHOULD 5 at + `46cac748`).""" + estate = tmp_path / "estate" + estate.mkdir() + fifo = estate / "held.fifo" + arms, pins, starter, nonce = [], [], None, _nonce() + est = SimpleNamespace(root=estate, bin=estate / "bin", nonce=nonce, + rearm=lambda new=(): arms.append(list(new)), + render_calls=lambda after=0: []) + try: + os.mkfifo(str(fifo), 0o600) + starter = subprocess.Popen([sys.executable, "-I", "-c", DETACHES, + str(estate / "flip" / "lanes-index")], + stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, text=True, + env=_with_identity(nonce)) + pins.append(_reported(starter, "the detached render", nonce)) + assert _ended(starter, 10), "the detached render's starter did not end" + _end_held_renders(est, fifo, None, 0) + assert _until(pins[0].gone, 5), "the detached render that no log names is still there" + assert not fifo.exists(), "the hold FIFO is still there" + assert arms == [[]], f"the hold was not disarmed once: {arms}" + finally: + _each(lambda: _quiesce(est, roots=[starter], grace=5), + lambda: _let_go(fifo, abort=True), lambda: _kill_pinned(pins), + lambda: _reap_all([starter] if starter is not None else [])) + + +@LINUX_ONLY +def test_a_clean_up_raises_on_a_process_logged_with_no_start_token(tmp_path): + """SHOULD 1 at `18529e5a`: a clean-up never skips a process it cannot + identify. A git call's launch record (`git-wrapper.started`) and a + renderer in the wrapper's log, each with an empty start token, make + `_end_renders` raise (`RuntimeError`, "no start token") once the rest + is done, where it read such a renderer as gone and returned. Their pids + are above Linux's pid_max ceiling, so no process has them, and nothing + is signalled.""" + estate = tmp_path / "estate" + (estate / "bin").mkdir(parents=True) + call, renderer = _Stuck.pid, _Stuck.pid + 1 + (estate / "bin" / "git-wrapper.started").write_text( + json.dumps({"pid": call, "start": ""}) + "\n", encoding="utf-8") + logged = [{"renderer": renderer, "renderer_start": "", "sub": "push", "outcome": "held", + "render": True}] + est = SimpleNamespace(root=estate, bin=estate / "bin", render_calls=lambda after=0: logged) + with pytest.raises(RuntimeError, match="no start token") as raised: + _end_renders(est, 0, grace=1) + assert f"pid {call} " in str(raised.value) and f"pid {renderer} " in str(raised.value), ( + f"not both processes with no start token are named: {raised.value}") + + +@LINUX_ONLY +def test_an_abort_release_runs_neither_a_held_call_nor_a_launched_command(tmp_path): + """SHOULD 1 at `18529e5a`: an abort release (`_let_go`'s `abort`) is not + the success release. The real wrapper (`GIT_WRAPPER`), its call held at + a push by its `hold` arm, and the real launcher (`LAUNCH`), each let go + by an abort, run nothing: the wrapper's git and the launcher's command, + each a script that makes a file, never run, and both end with 75. The + wrapper wrote its launch record first: its pid, and the start token + `/proc` gave it while its call was held. Both FIFOs are owned from their + making, each let go with an abort in the `finally` (SHOULD 5 at + `46cac748`).""" + bin_ = tmp_path / "bin" + made = {what: tmp_path / f"{what}.ran" for what in ("git", "command")} + for what, path in made.items(): + _script(tmp_path / what, f"#!/bin/sh\n: > {shlex.quote(str(path))}\n") + _script(bin_ / "git", GIT_WRAPPER) + _script(bin_ / "launch", LAUNCH) + held, barrier = tmp_path / "push.fifo", tmp_path / "barrier.fifo" + (bin_ / "git-wrapper.json").write_text(json.dumps({ + "git": str(tmp_path / "git"), "redirect": {}, + "arms": [{"sub": "push", "do": "hold", "fifo": str(held)}]}), encoding="utf-8") + procs, token, said = [], None, [] + try: + for fifo in (held, barrier): + os.mkfifo(str(fifo), 0o600) + for argv in ([str(bin_ / "git"), "push", "origin", "HEAD:refs/heads/main"], + [str(bin_ / "launch"), str(barrier), str(tmp_path / "command")]): + procs.append(subprocess.Popen([sys.executable, "-I", *argv], cwd=str(tmp_path), + stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, + stderr=subprocess.PIPE, text=True)) + for proc, fifo in zip(procs, (held, barrier)): + fd = _open_when_held(fifo, proc, 30) + assert fd is not None, f"nothing was held on {fifo.name}" + if proc is procs[0]: + token = _stat(proc.pid)["start"] # read while the call is held + _let_go(fifo, fd, abort=True) + for proc in procs: + proc.wait(timeout=30) + finally: + _each(lambda: _let_go(held, abort=True), lambda: _let_go(barrier, abort=True), + lambda: said.extend(_reap_all(procs))) + ran = [what for what, path in made.items() if path.exists()] + assert not ran, f"an abort release ran {ran}: {said}" + assert [proc.returncode for proc in procs] == [75, 75], ( + [proc.returncode for proc in procs], said) + records = _jsonl(bin_ / "git-wrapper.started") + assert records == [{"pid": procs[0].pid, "start": token}], ( + f"the wrapper's launch record is not its pid {procs[0].pid} and start token {token}: " + f"{records}") + + +@LINUX_ONLY +def test_a_held_burst_leaves_no_fifo_where_its_first_log_read_fails(tmp_path): + """SHOULD 3 at `18529e5a`: `_held_burst` owns its FIFO from its making, + every fallible call inside its `try`. Where the first read of the + wrapper's log fails (`est.entries()`, stubbed to raise `OSError`), that + error is what the case raises, the hold is disarmed and the FIFO is + gone. Stubbed: the estate; no process is started.""" + arms = [] + + def unreadable(): + raise OSError("the wrapper's log cannot be read") + + est = SimpleNamespace(root=tmp_path, bin=tmp_path / "bin", origin_tip=lambda: "0" * 40, + entries=unreadable, arm=arms.append, + rearm=lambda new=(): arms.append(list(new)), + render_calls=lambda after=0: []) + one = SimpleNamespace(own=SimpleNamespace(git_dir=tmp_path, clone=tmp_path)) + with pytest.raises(OSError, match="cannot be read"): + _held_burst(est, one) + assert not (tmp_path / "held.fifo").exists(), ( + "_held_burst left its FIFO behind where its first read of the wrapper's log failed") + assert arms and arms[-1] == [], f"the hold was not disarmed: {arms}" + + +@LINUX_ONLY +def test_a_clean_up_never_signals_a_logged_pid_and_start_token_without_the_case_s_identity( + tmp_path): + """BLOCKING at `46cac748` (lane 2's decision 1 in round CX-33): a process + is never owned on its pid and start token alone, which a process that + takes a logged pid within the same clock tick shares. A stranger without + the case's nonce is logged as a renderer with its own pid and its own + start token, exactly, as such a successor would match; a renderer + launched with the nonce is logged beside it. `_end_renders` kills the + renderer (-9) through its pidfd, never signals the stranger, which is + still running and not stopped, and raises (`RuntimeError`) naming the + stranger's pid as without the identity.""" + estate = tmp_path / "estate" + procs, nonce = [], _nonce() + try: + renderer = subprocess.Popen([sys.executable, "-I", "-c", SLEEP], + stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, start_new_session=True, + env=_with_identity(nonce)) + procs.append(renderer) + stranger = subprocess.Popen([sys.executable, "-I", "-c", SLEEP], stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + start_new_session=True) + procs.append(stranger) + until = time.monotonic() + 5 # their environments are set only once their execs are done + while (_carried(renderer.pid) != nonce + or not Path(f"/proc/{stranger.pid}/environ").read_bytes()): + assert time.monotonic() < until, "a child's environment was never set" + time.sleep(0.005) + logged = [{"renderer": proc.pid, "renderer_start": _stat(proc.pid)["start"]} + for proc in procs] + est = SimpleNamespace(root=estate, bin=estate / "bin", nonce=nonce, + render_calls=lambda after=0: logged) + with pytest.raises(RuntimeError, match="does not carry the case's identity") as raised: + _end_renders(est, 0, grace=2) + assert f"pid {stranger.pid} " in str(raised.value), raised.value + assert _ended(renderer) and renderer.returncode == -signal.SIGKILL, renderer.returncode + assert stranger.poll() is None and _stat(stranger.pid)["state"] not in ("T", "t"), ( + "the stranger with a logged pid and start token, but not the case's identity, was " + "signalled") + finally: + _reap_all(procs) + + +@LINUX_ONLY +def test_a_clean_up_ends_each_member_of_a_group_whose_leader_is_gone(tmp_path): + """SHOULD 1 at `46cac748` and the coordinator's point 1 (#165 + 6938182757): discovery needs no live leader. A leader in a session of + its own forks a member into its group and ends; the case reaps it, so + no leader is left to pin, and nothing is logged. The member's argv and + cwd are outside the estate. `_end_renders` still finds the member by + the case's identity alone, and it is gone.""" + estate = tmp_path / "estate" + leader, pins, nonce = None, [], _nonce() + est = SimpleNamespace(root=estate, bin=estate / "bin", nonce=nonce, + render_calls=lambda after=0: []) + try: + leader = subprocess.Popen([sys.executable, "-I", "-c", LEAVES_A_MEMBER], + stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, text=True, start_new_session=True, + env=_with_identity(nonce)) + pins.append(_reported(leader, "the member its leader left", nonce)) + assert _ended(leader, 10), "the leader did not end" + _end_renders(est, 0, grace=2) + assert _until(pins[0].gone, 5), "the member of a group whose leader is gone is still there" + finally: + _each(lambda: _quiesce(est, grace=5), lambda: _kill_pinned(pins), + lambda: _reap_all([leader] if leader is not None else [])) + + +@LINUX_ONLY +def test_a_clean_up_ends_what_it_knows_before_it_raises_an_unreadable_log(tmp_path): + """The coordinator's point 2 (#165 6938182757): where the launch records + cannot be read (`git-wrapper.started` is a directory, so `_logged` + raises `IsADirectoryError`), `_quiesce` still finds and ends what it + knows: its root, the case's child leading a session of its own, ends + -9, and the root's group member, found by the case's identity, is gone. + Then the log's own error is what it raises. Its `finally` first ends + every process carrying the case's nonce (`_quiesce`, with no log to + read), then each pin and the root (lane 3's Codex review of code PR 97 + at `f776b435`, SHOULD 5).""" + estate = tmp_path / "estate" + (estate / "bin" / "git-wrapper.started").mkdir(parents=True) + root, pins, nonce = None, [], _nonce() + est = SimpleNamespace(root=estate, bin=estate / "bin", nonce=nonce) + owner = SimpleNamespace(root=estate, bin=tmp_path / "no-log", nonce=nonce) + try: + root = subprocess.Popen([sys.executable, "-I", "-c", LEADS_A_GROUP], + stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, text=True, start_new_session=True, + env=_with_identity(nonce)) + pins.append(_reported(root, "the root's group member", nonce)) + with pytest.raises(IsADirectoryError): + _quiesce(est, roots=[root], grace=2) + assert _ended(root) and root.returncode == -signal.SIGKILL, ( + f"the root was not ended before the log's error was raised: {root.returncode}") + assert _until(pins[0].gone, 5), "the root's group member is still there" + finally: + _each(lambda: _quiesce(owner, roots=[root], grace=5), lambda: _kill_pinned(pins), + lambda: _reap_all([root] if root is not None else [])) + + +@LINUX_ONLY +def test_a_report_that_never_comes_ends_its_starter_and_raises(tmp_path): + """SHOULD 2 at `46cac748`: `_reported` reads its stand-in's line under + `select` with an absolute deadline. A stand-in that prints nothing and + stays makes it raise within the bound, its starter ended and reaped, + where a `readline()` with no bound waited for ever. The bound is 1 s, + held to within a cushion of 1.5 s (lane 3's Codex review of code PR 97 + at `f776b435`, SHOULD 7).""" + proc = subprocess.Popen([sys.executable, "-I", "-c", SLEEP], stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) + start = time.monotonic() + try: + with pytest.raises(AssertionError, match="nothing was printed"): + _reported(proc, "the silent stand-in", _nonce(), seconds=1) + assert 0.9 <= time.monotonic() - start < 2.5, "the bound of 1 s was not kept" + assert proc.returncode == -signal.SIGKILL, f"its starter was not ended: {proc.returncode}" + finally: + _reap_all([proc]) + + +def test_a_pinned_process_s_end_raises_unless_it_is_seen_gone(): + """SHOULD 3 at `46cac748`: `_kill_pinned` confirms each end. A pin whose + process is never seen gone (`_Undying`) is sent SIGKILL, its pidfd is + closed, and it raises (`RuntimeError`, "still there"), where it + returned with the process alive. No process is signalled.""" + held = _Undying() + with pytest.raises(RuntimeError, match="still there"): + _kill_pinned([held]) + assert held.calls == [signal.SIGKILL, "close"], held.calls + + +@LINUX_ONLY +def test_reap_all_tries_every_child_and_raises_after_the_whole_set(): + """SHOULD 4 at `46cac748`: `_reap_all` tries every child. The first + never ends (`_Stuck`, its `kill` recorded); the second is a real child + that stays. The second is still killed and reaped (-9), the first's + pipes are closed after its bounded waits, and only then is the first + error raised (`subprocess.TimeoutExpired`).""" + stuck = _Stuck() + stuck.kill = lambda: stuck.calls.append("kill") + child = subprocess.Popen([sys.executable, "-I", "-c", SLEEP], stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) + try: + with pytest.raises(subprocess.TimeoutExpired): + _reap_all([stuck, child]) + assert child.returncode == -signal.SIGKILL, f"the second child: {child.returncode}" + assert stuck.calls == ["kill", "communicate", "wait"], stuck.calls + assert stuck.stdout.closed and stuck.stderr.closed, "the first child's pipes are open" + finally: + if child.returncode is None: + child.kill() + child.wait(timeout=30) + + +@LINUX_ONLY +def test_a_clean_up_kills_and_closes_every_pin_whatever_a_signal_raised(monkeypatch, tmp_path): + """SHOULD 6 at `46cac748`: each pin is registered before any signal, and + each signal and pidfd has its own `try`. Two processes carry the case's + nonce; the first SIGSTOP sent through a pidfd raises `PermissionError` + (stubbed: every other call goes to the real `signal.pidfd_send_signal`). + `_end_renders` still kills both (-9), leaves this process no more + fds open than before, and then raises that error.""" + estate = tmp_path / "estate" + procs, nonce, real = [], _nonce(), signal.pidfd_send_signal + refused = [] + + def first_stop_refused(fd, sig, *args): + if sig == signal.SIGSTOP and not refused: + refused.append(fd) + raise PermissionError("the first SIGSTOP is refused") + return real(fd, sig, *args) + + est = SimpleNamespace(root=estate, bin=estate / "bin", nonce=nonce, + render_calls=lambda after=0: []) + try: + for _ in range(2): + procs.append(subprocess.Popen([sys.executable, "-I", "-c", SLEEP], + stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, start_new_session=True, + env=_with_identity(nonce))) + until = time.monotonic() + 5 # their environments are set only once their execs are done + while any(_carried(proc.pid) != nonce for proc in procs): + assert time.monotonic() < until, "a child's environment never carried the nonce" + time.sleep(0.005) + fds = len(os.listdir("/proc/self/fd")) + with monkeypatch.context() as stubs: + stubs.setattr(signal, "pidfd_send_signal", first_stop_refused) + with pytest.raises(PermissionError, match="refused"): + _end_renders(est, 0, grace=2) + assert refused, "no SIGSTOP was sent" + assert [_ended(proc) and proc.returncode for proc in procs] == [-signal.SIGKILL] * 2, ( + [proc.returncode for proc in procs]) + assert len(os.listdir("/proc/self/fd")) <= fds, "a pidfd was left open" + finally: + _reap_all(procs) + + +def test_wait_renders_exit_waits_for_a_renderer_that_took_a_logged_pid_and_keeps_its_deadline( + monkeypatch): + """SHOULD 7 at `46cac748`: `wait_renders_exit` seeks each renderer as the + pair of its pid and start token, and keeps its deadline on every path. + First, a renderer still running (this process, whose pid and token + `/proc` gives) is logged after an older record of its pid with another + token: the older one never hides it, and the wait fails at its deadline. + Then each read of the log names a renderer more, each already gone (a + pid above pid_max): the wait still fails at its deadline, where it went + on for ever. `CEILING` is 1 s, held to within a cushion of 1.5 s (lane + 3's Codex review of code PR 97 at `f776b435`, SHOULD 7); nothing is + started or signalled.""" + monkeypatch.setattr(sys.modules[__name__], "CEILING", 1.0) + me = os.getpid() + live = [{"renderer": me, "renderer_start": str(int(_stat(me)["start"]) + 1)}, + {"renderer": me, "renderer_start": _stat(me)["start"]}] + est = SimpleNamespace(render_calls=lambda after=0: live) + with pytest.raises(pytest.fail.Exception, match=f"pids \\[{me}\\] did not exit"): + RenderEstate.wait_renders_exit(est, 0, "the renderer that took a logged pid") + reads = [] + + def one_more(after=0): + reads.append(len(reads)) + return [{"renderer": _Stuck.pid + n, "renderer_start": "1"} for n in range(len(reads))] + + start = time.monotonic() + with pytest.raises(pytest.fail.Exception, match="within"): + RenderEstate.wait_renders_exit(SimpleNamespace(render_calls=one_more), 0, "renders") + assert 0.9 <= time.monotonic() - start < 2.5, "the deadline of 1 s was not kept" + + +@LINUX_ONLY +def test_a_wrapper_kill_signals_only_the_case_s_own_and_finds_each_member_without_its_leader( + tmp_path): + """BLOCKING and SHOULD 1 at `46cac748`, and the coordinator's point 1 + (#165 6938182757): `GIT_WRAPPER`'s `kill_above`, run on models + (`KILL_HARNESS`), with no process read or signalled. + - The process above has the pid and the start token, but not the case's + identity: nothing is signalled at all. + - The renderer ends once it is stopped, before its group is read: each + member with the identity (4001, 4002) is still found, stopped and + killed; 4003, in another group, and 4004, without the identity, are + never signalled. + - A member's stop lands late, and in that gap it forks 4005: each stop is + seen before the next read, so 4005 is found and killed too. + In each, every pidfd opened is closed.""" + said = _kill_models(tmp_path, "stranger-above", "lead-ends", "late-stop") + for model, what in said.items(): + assert what["raised"] is None and what["closed"] == what["opened"], (model, what) + assert not {pid for pid, _sig in what["sent"]} & {4003, 4004}, (model, what) + assert said["stranger-above"]["sent"] == [], said["stranger-above"] + assert _killed(said["lead-ends"]) == {4000, 4001, 4002}, said["lead-ends"] + assert _killed(said["late-stop"]) == {4000, 4001, 4002, 4005}, said["late-stop"] + + +@LINUX_ONLY +def test_a_wrapper_kill_ends_every_target_whatever_its_discovery_or_a_kill_raised(tmp_path): + """SHOULD 6 at `46cac748` and the coordinator's point 3 (#165 + 6938182757): `GIT_WRAPPER`'s `kill_above`, run on models + (`KILL_HARNESS`), with no process read or signalled. Where a member's + pidfd cannot be opened (EMFILE), or a read of /proc fails (EIO), the + renderer and each member already stopped are killed and their pidfds + closed, and that error is raised. Where the SIGKILL through one pidfd + is refused (EPERM), the others are still killed, every pidfd is + closed, and that error is raised.""" + said = _kill_models(tmp_path, "member-emfile", "proc-error", "kill-refused") + emfile, proc_error, refused = said["member-emfile"], said["proc-error"], said["kill-refused"] + assert emfile["raised"] == ["OSError", "EMFILE"], emfile + assert _killed(emfile) == {4000, 4001} and emfile["closed"] == [4000, 4001], emfile + assert proc_error["raised"] == ["OSError", "EIO"], proc_error + assert _killed(proc_error) == {4000} and proc_error["closed"] == [4000], proc_error + assert refused["raised"] == ["PermissionError", "EPERM"], refused + assert _killed(refused) == {4000, 4001, 4002}, refused + assert refused["closed"] == refused["opened"], refused + + +#: A stand-in that prints a part of a line, with no newline, and stays. +PART_LINE = "import os, time; os.write(1, b'4194'); time.sleep(300)" + + +@LINUX_ONLY +def test_a_report_of_a_part_line_ends_its_starter_and_raises(): + """SHOULD 2 at `f776b435`: `_reported` reads its stand-in's line without + blocking, in increments, under one deadline, to a newline or EOF. A + stand-in prints a part of a line, with no newline, and stays; once that + part can be read, `_reported` raises within its bound, 1 s, held to + within a cushion of 1.5 s, with what came, its starter ended and reaped + (-9), where a `readline()` after the first byte waited for ever.""" + import select + proc = subprocess.Popen([sys.executable, "-I", "-c", PART_LINE], stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) + try: + assert select.select([proc.stdout], [], [], 30)[0], "the stand-in printed nothing" + start = time.monotonic() + with pytest.raises(AssertionError, match="nothing was printed within 1 s but b'4194'"): + _reported(proc, "the stand-in with a part of a line", _nonce(), seconds=1) + assert 0.9 <= time.monotonic() - start < 2.5, "the bound of 1 s was not kept" + assert proc.returncode == -signal.SIGKILL, f"its starter was not ended: {proc.returncode}" + finally: + _reap_all([proc]) + + +@LINUX_ONLY +def test_a_clean_up_raises_where_a_stop_is_never_seen(monkeypatch, tmp_path): + """SHOULD 1 at `f776b435`: a stop not seen is no stop. A process carrying + the case's nonce is found, but each SIGSTOP sent through a pidfd is + dropped (stubbed: every other signal goes to the real + `signal.pidfd_send_signal`), so it is never seen stopped. `_end_renders` + still kills it (-9), and raises (`RuntimeError`, "never seen stopped"), + where it returned as if the estate were quiescent.""" + estate = tmp_path / "estate" + procs, nonce, real, dropped = [], _nonce(), signal.pidfd_send_signal, [] + + def stop_dropped(fd, sig, *args): + if sig == signal.SIGSTOP: + dropped.append(fd) + return None + return real(fd, sig, *args) + + est = SimpleNamespace(root=estate, bin=estate / "bin", nonce=nonce, + render_calls=lambda after=0: []) + try: + procs.append(subprocess.Popen([sys.executable, "-I", "-c", SLEEP], + stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, start_new_session=True, + env=_with_identity(nonce))) + until = time.monotonic() + 5 # its environment is set only once its exec is done + while _carried(procs[0].pid) != nonce: + assert time.monotonic() < until, "the child's environment never carried the nonce" + time.sleep(0.005) + with monkeypatch.context() as stubs: + stubs.setattr(signal, "pidfd_send_signal", stop_dropped) + with pytest.raises(RuntimeError, match="never seen stopped"): + _end_renders(est, 0, grace=1) + assert dropped, "no SIGSTOP was sent" + assert _ended(procs[0]) and procs[0].returncode == -signal.SIGKILL, procs[0].returncode + finally: + _each(lambda: _quiesce(est, grace=5), lambda: _reap_all(procs)) + + +@LINUX_ONLY +def test_a_clean_up_pins_again_a_pid_whose_pinned_process_is_gone(): + """SHOULD 1 at `f776b435`: a pid and start token pinned before never + hide the process that has them now. The pin held under a live + process's pid and start token is one whose pidfd reads as gone, as a + process that ended, its pid then taken within the same tick, would + leave it. `_owned` pins the live process again, by its own identity, + and keeps the gone pin under a key of its own, to be let go.""" + nonce, proc, fresh, pinned, raised = _nonce(), None, [], {}, [] + try: + proc = subprocess.Popen([sys.executable, "-I", "-c", SLEEP], stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + start_new_session=True, env=_with_identity(nonce)) + until = time.monotonic() + 5 # its environment is set only once its exec is done + while _carried(proc.pid) != nonce: + assert time.monotonic() < until, "the child's environment never carried the nonce" + time.sleep(0.005) + now = _stat(proc.pid) + ended = SimpleNamespace(pid=proc.pid, start=now["start"], fd=-1, + gone=lambda seconds=0: True, close=lambda: None) + pinned[(proc.pid, now["start"])] = ended + _owned({proc.pid: now}, {nonce}, pinned, fresh) + assert [held.pid for held in fresh] == [proc.pid], ( + "the live process with a gone pin's pid and start token was not pinned again") + assert pinned[(proc.pid, now["start"])] is fresh[0] and ended in pinned.values(), pinned + finally: + _each(lambda: _release(pinned.values(), raised), lambda: _raise_first(raised), + lambda: _reap_all([proc] if proc is not None else [])) + assert proc.returncode == -signal.SIGKILL, f"the pinned one was not ended: {proc.returncode}" + + +@LINUX_ONLY +def test_a_clean_up_names_a_logged_live_process_it_cannot_own(tmp_path): + """SHOULD 8 at `f776b435`: each record is validated by itself, apart + from the table of this user's processes a clean-up signals from. A + renderer is logged with the pid and start token of pid 1, a live process + this case cannot own: another user's, where the case does not run as + root, else one without the case's identity. `_end_renders` raises + naming it, where it passed it over; it is never signalled, as a + clean-up signals only what it pinned from this user's processes, and + never pid 1.""" + init = _stat(1) + assert init is not None, "pid 1 cannot be read" + logged = [{"renderer": 1, "renderer_start": init["start"]}] + est = SimpleNamespace(root=tmp_path / "estate", bin=tmp_path / "estate" / "bin", + nonce=_nonce(), render_calls=lambda after=0: logged) + with pytest.raises(RuntimeError, match="names pid 1 with the start token of a live process " + "(that is another user's|whose environment cannot be " + "read|that does not carry the case's identity)"): + _end_renders(est, 0, grace=1) + + +@LINUX_ONLY +def test_a_pin_and_a_release_close_every_pidfd_whatever_a_read_or_a_close_raised(monkeypatch): + """SHOULD 3 at `f776b435`: each pidfd has an owner from its opening. + `_pin`, whose signal 0 is refused (`PermissionError`, stubbed), closes + the pidfd it opened before it raises. `_release` lets each handle go + whatever one raised: the case's process is killed (-9), seen gone and + closed; a pin never seen gone (`_Undying`), whose close raises, is sent + SIGKILL, is an error, and its close's error is kept. This process has no + more fds open than before. Only the case's own child is signalled.""" + nonce, real, raised = _nonce(), signal.pidfd_send_signal, [] + child = subprocess.Popen([sys.executable, "-I", "-c", SLEEP], stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + start_new_session=True, env=_with_identity(nonce)) + undying = _Undying() + + def zero_refused(fd, sig, *args): + if sig == 0: + raise PermissionError("the signal 0 is refused") + return real(fd, sig, *args) + + def close_refused(): + undying.calls.append("close") + raise OSError("the close failed") + + try: + until = time.monotonic() + 5 # its environment is set only once its exec is done + while _carried(child.pid) != nonce: + assert time.monotonic() < until, "the child's environment never carried the nonce" + time.sleep(0.005) + fds = len(os.listdir("/proc/self/fd")) + with monkeypatch.context() as stubs: + stubs.setattr(signal, "pidfd_send_signal", zero_refused) + with pytest.raises(PermissionError, match="refused"): + _pin(child.pid, nonce) + assert len(os.listdir("/proc/self/fd")) <= fds, "the pidfd `_pin` opened was left open" + held = _pin(child.pid, nonce) + assert held is not None, "the case's process could not be pinned" + undying.close = close_refused + _release([held, undying], raised, seconds=0.5) + assert _ended(child) and child.returncode == -signal.SIGKILL, child.returncode + assert undying.calls == [signal.SIGKILL, "close"], undying.calls + assert [type(exc).__name__ for exc in raised] == ["RuntimeError", "OSError"], raised + assert len(os.listdir("/proc/self/fd")) <= fds, "a pidfd was left open" + finally: + _reap_all([child]) + + +@LINUX_ONLY +def test_a_wrapper_kill_ends_a_gone_leader_s_group_and_every_pidfd_whatever_a_stop_or_a_close_did( + tmp_path): + """SHOULDs 1 and 3 at `f776b435`: `GIT_WRAPPER`'s `kill_above`, run on + models (`KILL_HARNESS`), with no process read or signalled. + - The renderer is gone before it is pinned: its group's members with the + identity (4001, 4002) are still found by it and the group's id, and + killed; 4003 and 4004 are never signalled. + - 4002's stop is never seen: every target is still killed, and it + raises (`RuntimeError`) by the one deadline. + - The close of 4001's pidfd fails (EIO): every other pidfd is still + closed, and that error is raised. + - The signal 0 of 4002's pin is refused (EPERM): its pidfd is closed, + the targets found are killed, and that error is raised. + In each, every pidfd opened is closed, or its close tried.""" + said = _kill_models(tmp_path, "lead-gone", "stop-never", "close-error", "pin-raises") + for model, what in said.items(): + assert what["closed"] == what["opened"], (model, what) + assert not {pid for pid, _sig in what["sent"]} & {4003, 4004}, (model, what) + assert said["lead-gone"]["raised"] is None, said["lead-gone"] + assert _killed(said["lead-gone"]) == {4001, 4002}, said["lead-gone"] + assert said["stop-never"]["raised"] == ["RuntimeError", None], said["stop-never"] + assert _killed(said["stop-never"]) == {4000, 4001, 4002}, said["stop-never"] + assert said["close-error"]["raised"] == ["OSError", "EIO"], said["close-error"] + assert _killed(said["close-error"]) == {4000, 4001, 4002}, said["close-error"] + assert said["pin-raises"]["raised"] == ["PermissionError", "EPERM"], said["pin-raises"] + assert _killed(said["pin-raises"]) == {4000, 4001}, said["pin-raises"] + + +@LINUX_ONLY +def test_a_wrapper_kill_reads_again_once_every_target_is_gone_whatever_a_stop_did(tmp_path): + """SHOULD 2 at `5a120647`: the shared clean-up's one loop (`_Settled`), + run by `GIT_WRAPPER`'s `kill_above` on a model (`KILL_HARNESS`), with + no process read or signalled. 4002's stop is never seen, and in that + gap it forks 4005, a late member of the group, which the model shows + only once 4002 has been sent SIGKILL: no read before the kill can find + it (lane 2's pre-review RV7-35, S1). Every target is still killed and + seen gone, and /proc is read again after the kill, so 4005 is found by + that read and killed too, and the stop's error is raised + (`RuntimeError`), where that error spared the read after the kill and + 4005 was left. 4003 and 4004 are never signalled, and every pidfd + opened is closed.""" + said = _kill_models(tmp_path, "stop-forks")["stop-forks"] + assert said["raised"] == ["RuntimeError", None], said + assert _killed(said) == {4000, 4001, 4002, 4005}, said + assert said["closed"] == said["opened"], said + assert not {pid for pid, _sig in said["sent"]} & {4003, 4004}, said + + +@LINUX_ONLY +def test_a_wrapper_kill_raises_its_first_error_with_every_later_one_as_its_cause(tmp_path): + """SHOULD 2 at `bb190f7b`: `GIT_WRAPPER`'s `kill_above`, run on a model + (`KILL_HARNESS`), with no process read or signalled. The SIGKILL + through 4001's pidfd is refused (EPERM), so 4001 is never seen gone: + the loop's deadline passes, and `end_all` meets the refusal again and + 4001 still there 10 s on. The first error, the refusal, is raised, and + every later one is named in its cause (`_raise_first`), where + `end_all` was given the first alone and the rest were lost. Every + pidfd opened is closed, and 4003 and 4004 are never signalled.""" + said = _kill_models(tmp_path, "kill-refused")["kill-refused"] + assert said["raised"] == ["PermissionError", "EPERM"], said + assert "the clean-up's deadline passed" in (said["cause"] or ""), said + assert "pid 4001 is still there 10 s after its SIGKILL" in (said["cause"] or ""), said + assert said["closed"] == said["opened"], said + assert not {pid for pid, _sig in said["sent"]} & {4003, 4004}, said + +@LINUX_ONLY +def test_the_one_loop_reports_its_deadline_where_a_read_past_it_finds_none_new(monkeypatch): + """SHOULD 1 at `bb190f7b`: the shared clean-up's one loop (`_Settled`) + checks its absolute deadline right after each read, before it ends on + one that found none new. On a modelled clock, with no process read or + signalled: the first read finds one target, whose stop is seen; the + next finds none new, so the target is killed, and the kill's + confirmation ends past the deadline, 10 s on; the read after it finds + none new. The loop reports the deadline (`RuntimeError`) and returns + False, where that pass crossed the deadline and returned True.""" + clock, targets, reads, errors = [0.0], [], [], [] + + def scan(): + reads.append(clock[0]) + if len(reads) == 1: + targets.append(4100) + return 1 if len(reads) == 1 else 0 + + def kill(left): + clock[0] = 11.0 # the confirmation ends past the deadline + targets.clear() + return [] + + monkeypatch.setattr(sys.modules[_Settled.__module__], "time", + SimpleNamespace(monotonic=lambda: clock[0], sleep=lambda seconds: None)) + settled = _Settled(scan, lambda by: None, kill, lambda: list(targets), 10.0, errors) + assert settled.run() is False, errors + assert reads == [0.0, 0.0, 11.0], reads + assert [type(exc) for exc in errors] == [RuntimeError], errors + assert "deadline passed" in str(errors[0]), errors diff --git a/tests/test_sql_register_rollback.py b/tests/test_sql_register_rollback.py new file mode 100644 index 00000000..3d11a810 --- /dev/null +++ b/tests/test_sql_register_rollback.py @@ -0,0 +1,3246 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Feature 007's test 8, section 4.2 and AT-F1: the rollback (L2-G4; L2-G5's +AT-F1; AT-8; T273; FR-051, FR-052, FR-059; also US6) (opensoft/openRepoTools#165). + +T273 writes this module: 21 tests, 20 from AT-8 (11), AT-F1 (7) and section +4.2 (2), and T304's own (R-F10-34), and T273d a 22nd: AT-F2's rollback rerun +after a 3 with a files-mode write between (lane 3's #165 6814260122), not yet +in B15's T273 text. Fourteen more, at the end, test no AT case: the +fault-path regressions of the module's own teardown (lane 3's Codex reviews +of code PR 97 at `6d479418`, SHOULDs 1 and 2, at `18529e5a`, BLOCKING and +SHOULD 1, and at `46cac748`, BLOCKING and SHOULDs 1 to 6; the coordinator's +#165 6934112467 and his point 2, #165 6938182757; lane 2's CX-32 +integration, open item 1), whose rows wait for no task. T304's own test, +`test_rollback_steps_0_and_1_run_only_against_a_scratch_schema` (NOTES +question 6; B10 tasks:1011-1024; `PLACEMENT.md` section 4), is phase 1's, +and lane 3's T304 selects it with its word `sql_register_rollback and +scratch`: those six ids and nothing else. No other name or id in this module +holds that word. The other 20 (T273b) are after it, with their own notes. + +T304'S OWN TEST: steps 0 and 1 of `lanes-index rollback` (lane 3's T304), run +by the shipped `lanes-index` with Q6(c)'s constant unset (`RENDER_GIT_HALF = +False`), as the operator lane, `LANES_LANE=<operator lane>` (B10 tasks:1015), +with this workstation's name and git's author set, on a database of the +session cluster that `lanes-index bootstrap` made for a scratch +`register_schema=` (T109's DEC-23 rendering), brought to `primary` with the +marker `present` by AT-LR006's route (TP:4610-4615). A scratch schema is any +`register_schema=` but the default `lanes_register` (Y:2323; lane 2's +reading). Its ids: + + * `[diverged-refuses-2]`: with `mirror_state.diverged_sha` set, it exits 2, + and the switch, the marker and the head do not move (B10 tasks:1016); + * `[step-1-one-transaction]`: one transaction leaves the switch at `files`, + the head at `k+1`, an operator entry removing `lanes/STORE` last, and the + marker `removing` (tasks:1017). The case asserts the database's state, not + the exit after step 1, which T326's steps follow; + * `[outage-declared-with-mirror-seq]`: its start declares the outage, + marked as from a rollback, through `outage declare --rollback --mirror-seq + <k>` (tasks:1020; T121); + * `[lost-turn-rechecks-step-0]`: a second session holds the head row past + `rollback`'s `lock_timeout`, so step 1 meets 55P03, and records a + divergence meanwhile; once released, the rollback goes back to step 0 with + the head read afresh and exits 2, with the switch and the marker unchanged + (tasks:1018, :1016); + * `[database-unreachable-69]`: 69, with neither the switch nor the marker + changed (tasks:1021); + * `[not-a-scratch-schema-2]`: with `register_schema=` unset and the constant + unset, 2 (tasks:1023; `exit-codes.md` :145 at `23e4494`; Y:4872). + +D7's 75 (tasks:1019) and the rerun's step 2 (tasks:1022) stay with the phase +G cases (T273b). Each id fails until T107, T109's rendering, T121 and T304 +land (L1-A6, L1-A7, L1-A18; R-F10-34). Every id is RE: it asks for the +session cluster, and without PostgreSQL 16 it skips with T205's banner. + +READINGS, NOT FOUND IN A CONTRACT: +- AT-LR006'S ROUTE is the documented functions as REGISTER-WRITER, by direct + calls, as T231's cases reach `primary`: `commit_write` with an `import` + entry at seq 0, then a `cutover` entry at 1, then `record_marker`, then one + write at 2, so the rollback's `k` (2) is neither the import's seq nor the + cutover's. +- "ONE TRANSACTION" is read as: of every `psql` call the rollback makes, one + alone carries a function that writes (`commit_write`, `record_marker`, + `switch_to_files`, `record_mirror_state`), and that call is step 1's one + request, `BEGIN ISOLATION LEVEL SERIALIZABLE`, the `commit_write` call, + then `COMMIT` (section 3.2's shim logs each call as sent). The database + then holds what that one call leaves. +- THE SECOND SESSION of `[lost-turn-rechecks-step-0]` is the fixture's + superuser holding `register_head`'s row `FOR UPDATE`. The divergence is + recorded in that same session, as REGISTER-WRITER by `record_mirror_state`, + so its `COMMIT` records it and releases the row at once. The shim holds the + rollback's second read (the second call carrying `diverged_sha`) until + then, so the read after the lost turn is the one that finds the divergence, + whatever the machine's speed. +- "THE DATABASE UNREACHABLE" is a configuration whose URLs name the cluster's + socket directory at a port where no server listens. The database itself, + read by the test, shows the switch, the marker and the head unchanged. +- THE CONSTANT: the shipped `lanes-index` must carry `RENDER_GIT_HALF = + False`. Each id says so where it does not (lane 3's T328 sets it True), since + the scratch-schema rule holds only while it is unset. Once T328 has set it, + with one `RENDER_GIT_HALF = True` line, each id skips before its setup, + saying why (`CONSTANT_SET`; tasks:2511). Anything else fails. +""" + +from __future__ import annotations + +import hashlib +import json +import os +import re +import shutil +import signal +import subprocess +import sys +import time +import uuid +from pathlib import Path +from types import SimpleNamespace +from urllib.parse import quote + +import pytest + +from conftest import WINDOWS_SKIP +from pgcluster import SUPERUSER, Database +from sql_register_cleanup import (IDENTITY, LEADS_A_GROUP, LEAVES_A_MEMBER, LINUX_ONLY, SLEEP, + _GapFifo, _Pinned, _Pipe, _Undying, _carried, _each, _end_pin, + _ended, _fifo_reader, _keep, _misrecorded, _nonce, _on_fifo, + _owned, _pin, _pin_child, _reap_all, _release, _reported, + _send_each, _settle_pinned, _stat, _table, _with_identity) +from sql_register_helpers import (LANES_INDEX, PSQL_SHIM, PSQL_SHIM_CONTROL, PSQL_SHIM_LOG, + REGISTER_FAKE_PSQL, RENDER_GIT_HALF_LINE, flipped_copy, + guard_strip_env) + +pytestmark = [WINDOWS_SKIP] + +#: THE LANDING GATE'S TABLE (T280; `tests/sql_register_gate.py` reads it): the +#: tasks each id waits for, from T273's Order (tasks:2512 at 204145ae). In a +#: gated run an id is skipped while any of its tasks has no marker in +#: `tests/sql_register_landed/`. T281 removes it with the gate. The module +#: has no `"*"` row: each test has its own. The teardown's own fault-path +#: regressions, at the end, need no engine and no task, so each has an empty +#: row and ordinary PR CI runs it (lane 3's Codex review of code PR 97 at +#: `18529e5a`, SHOULD 5, read for this module). +SQL_REGISTER_GATE_TABLE = { + "test_a_cutover_and_a_rollback_leave_exactly_two_operator_entries": ("T121", "T304", "T326"), # T273; tasks:2512 + "test_a_files_mode_claim_after_rollback_leaves_one_holder": ("T121", "T304", "T326"), # T273; tasks:2512 + "test_a_missed_primary_writer_is_refused_after_rollback": ("T111", "T121", "T304", "T326", "T327", "T415", "T416", "T420"), # T273; tasks:2512 + "test_a_missed_writer_is_refused_once_the_partitioned_rollback_completes": ("T111", "T121", "T304", "T326", "T327", "T415", "T416", "T420"), # T273; tasks:2512 + "test_a_pinned_process_s_end_raises_unless_it_is_seen_gone": (), # T273; the teardown's own fault path, no task (Codex at 46cac748, SHOULD 3) + "test_a_push_fifo_let_go_leaves_no_reader_blocked": (), # T273; the teardown's own fault path, no task (Codex at 6d479418, SHOULD 1) + "test_a_reimport_after_a_rollback_continues_the_journal": ("T121", "T304", "T326"), # T273; tasks:2512 + "test_a_report_that_never_comes_ends_its_starter_and_raises": (), # T273; the teardown's own fault path, no task (Codex at 46cac748, SHOULD 2) + "test_a_rerun_after_an_unconfirmed_removal_and_a_files_mode_write_ends_0_with_the_marker_absent": ("T121", "T304", "T326"), # T273; tasks:2512 + "test_a_rollback_entry_over_a_recorded_divergence_is_lr012": ("T107", "T109"), # T273; tasks:2512 + "test_a_rollback_finds_a_stray_not_yet_recorded_records_it_and_exits_2": ("T121", "T304", "T326"), # T273; tasks:2512 + "test_a_rollback_goes_back_to_its_check_on_each_lost_turn_code": ("T326",), # T273; tasks:2512 + "test_a_rollback_goes_back_to_its_check_past_a_last_error_and_refuses_a_divergence_recorded_meanwhile": ("T121", "T304", "T326"), # T273; tasks:2512 + "test_a_rollback_rerun_resumes_after_its_own_entry": ("T121", "T304", "T326"), # T273; tasks:2512 + "test_a_rollback_retries_a_lost_turn_on_a_fresh_k_through_its_check": ("T121", "T304", "T326"), # T273; tasks:2512 + "test_a_teardown_ends_a_live_call_whose_pid_an_old_record_names_with_another_token": (), # T273; the teardown's own fault path, no task (lane 2's CX-32 integration, open item 1) + "test_a_teardown_ends_a_push_forked_before_its_first_record": (), # T273; the teardown's own fault path, no task (Codex at 18529e5a, SHOULD 1) + "test_a_teardown_ends_each_member_of_a_group_whose_leader_is_gone": (), # T273; the teardown's own fault path, no task (Codex at 46cac748, SHOULD 1) + "test_a_teardown_ends_what_it_knows_before_it_raises_an_unreadable_log": (), # T273; the teardown's own fault path, no task (the coordinator's 6938182757, point 2) + "test_a_teardown_kills_and_closes_every_pin_whatever_a_signal_raised": (), # T273; the teardown's own fault path, no task (Codex at 46cac748, SHOULD 6) + "test_a_teardown_never_signals_a_logged_pid_and_start_token_without_the_case_s_identity": (), # T273; the teardown's own fault path, no task (Codex at 46cac748, BLOCKING) + "test_a_teardown_raises_on_a_call_logged_with_no_start_token": (), # T273; the teardown's own fault path, no task (Codex at 18529e5a, SHOULD 1) + "test_a_teardown_raises_where_a_stop_is_never_seen": (), # T273; the teardown's own fault path, no task (Codex at f776b435, SHOULD 1) + "test_a_teardown_signals_through_pidfds_alone_and_spares_a_wrong_start_token": (), # T273; the teardown's own fault path, no task (Codex at 18529e5a, BLOCKING) + "test_a_write_that_committed_before_the_rollback_is_found_by_its_rerun_after_it": ("T121", "T304", "T326", "T327", "T415", "T416", "T417"), # T273; tasks:2512 + "test_an_abort_release_runs_neither_git_nor_the_held_command": (), # T273; the teardown's own fault path, no task (Codex at 18529e5a, SHOULD 1) + "test_an_estate_whose_construction_fails_ends_what_it_started": (), # T273; the teardown's own fault path, no task (Codex at f776b435, BLOCKING) + "test_held_at_push_never_returns_with_its_rollback_unreaped": (), # T273; the teardown's own fault path, no task (Codex at 6d479418, SHOULD 2) + "test_reap_all_tries_every_child_and_raises_after_the_whole_set": (), # T273; the teardown's own fault path, no task (Codex at 46cac748, SHOULD 4) + "test_rollback_exits_2_on_lr012_naming_the_divergence_and_both_ways_out": ("T107", "T109", "T121", "T304"), # T273; tasks:2512 + "test_rollback_from_a_partitioned_clone_is_refused_and_removes_no_marker": ("T121", "T304", "T326"), # T273; tasks:2512 + "test_rollback_leaves_files_byte_identical_marker_gone_and_sql_writes_refused": ("T121", "T304", "T326"), # T273; tasks:2512 + "test_rollback_refuses_to_start_while_the_mirror_is_diverged": ("T121", "T304", "T326"), # T273; tasks:2512 + "test_rollback_steps_0_and_1_run_only_against_a_scratch_schema": ("T107", "T109", "T121", "T304"), # T273; tasks:2512 + "test_rollback_with_the_database_stopped_is_refused_and_changes_neither_switch_nor_marker": ("T121", "T304", "T326"), # T273; tasks:2512 + "test_the_marker_removal_entry_is_written_with_the_switch_in_step_1": ("T121", "T304", "T326"), # T273; tasks:2512 + "test_the_rollback_oracle_fails_on_a_last_fetched_tip_writer": ("T121", "T304", "T326"), # T273; tasks:2512 + "test_the_rollback_oracle_fails_on_a_switch_reset_when_the_database_returns": ("T121", "T304", "T326"), # T273; tasks:2512 +} + +#: The scratch schema the cases bootstrap: any `register_schema=` but the +#: default (Y:2323; lane 2's reading, NOTES question 6). +SCRATCH = "t273_scratch" +DEFAULT_SCHEMA = "lanes_register" +WRITER, READER = "lanes_register_writer", "lanes_register_reader" + +#: The logins `lanes-index` connects as, made once per cluster (roles are +#: cluster-wide), members of the writer and the reader groups, with no +#: password: the cluster's socket trusts them. +LOGIN_WRITER, LOGIN_READER = "t273_register_writer", "t273_register_reader" + +#: The bootstrap's admin service and the switch's label, which the +#: configuration's `register_label=` names too (the declaration's `database=`). +ADMIN_SERVICE = "t273_admin" +LABEL = "t273" + +#: The operator lane (D24; F12), this workstation (Rule 10) and git's author +#: (D15), through git's own variables and no git configuration. +OPERATOR_LANE = "t273-operator" +WS = "ws-t273" +AUTHOR = "T273 operator <t273@example.invalid>" +OPERATOR_GIT = {"GIT_AUTHOR_NAME": "T273 operator", "GIT_AUTHOR_EMAIL": "t273@example.invalid", + "GIT_COMMITTER_NAME": "T273 operator", + "GIT_COMMITTER_EMAIL": "t273@example.invalid", + "GIT_CONFIG_NOSYSTEM": "1", "GIT_CONFIG_GLOBAL": os.devnull} + +#: What AT-LR006's entries carry. +COMMIT_C, TREE_C, MARKER_COMMIT = "c" * 40, "d" * 40, "e" * 40 +ARGS_SHA256 = "a" * 64 +NOT_AFTER = "2100-01-01T00:00:00Z" +LANES_MD = ["# Lanes"] +STORE_UTC = "2026-11-11T10:00:00Z" +STORE_LINES = ("store=primary", f"database={LABEL}", f"import={COMMIT_C}", + f"lanes-tree={TREE_C}", f"utc={STORE_UTC}") + +#: The divergences the cases record, and who records them. +SHA_DIVERGED, SHA_MEANWHILE = "1" * 40, "2" * 40 +WS_MEANWHILE = "ws-t273-meanwhile" + +#: The configuration's own values (`c`, `n_a`), so neither is the default. +CONNECT_TIMEOUT, ADDRESSES = 3, 2 + +#: The functions that write, which "one transaction" counts. +WRITE_CALLS = ("commit_write(", "record_marker(", "switch_to_files(", "record_mirror_state(") + +#: The declaration's file, beside the configuration (D20; config.md section 6.1). +OUTAGE_FILE = "register-outage" + +#: The second session's `application_name`, which the case waits on. +HOLDER = "t273-holder" + + +def _private(path: Path, text: str) -> Path: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8") + path.chmod(0o600) + return path + + +def _said(proc) -> str: + return (f"exit {proc.returncode}\n--- stdout ---\n{(proc.stdout or '')[-3000:]}" + f"\n--- stderr ---\n{(proc.stderr or '')[-3000:]}") + + +def _render_git_half() -> list: + """The shipped `lanes-index`'s `RENDER_GIT_HALF = ` values, each line's + `True` or `False`; none where it cannot be read.""" + try: + return RENDER_GIT_HALF_LINE.findall(LANES_INDEX.read_bytes()) + except OSError: + return [] + + +#: T328'S CONSTANT SET (tasks:2511; lane 2, #165 6859084292; lane 3's sweep, +#: #165 6851829112). T304's own test reads the shipped `lanes-index`'s +#: `RENDER_GIT_HALF = ` line at collection, before its setup. With one True +#: line, T328's, each of its six ids skips with this reason, which never holds +#: `tests/pgcluster.py`'s `SKIP_TAG`, so no run counts it as a real-engine +#: skip. With one False line they run. Anything else fails at +#: `_constant_unset()`. +CONSTANT_SET = ( + "RENDER_GIT_HALF = True in the shipped lanes-index (lane 3's T328): the scratch-schema " + "rule this test checks ends with T328, and test 8's and AT-F1's cases carry steps 0 and 1 " + "on lanes_register") + + +def _constant_unset() -> None: + """The shipped `lanes-index` carries Q6(c)'s constant unset: the + scratch-schema rule this test checks holds only while it does.""" + found = _render_git_half() + assert found == [b"False"], ( + f"{LANES_INDEX} carries {found!r} for `RENDER_GIT_HALF = `, not one False line: T304's " + f"own test runs the shipped lanes-index with the constant unset (B10 tasks:1015), and " + f"lane 3's T328 sets it") + + +# ------------------------------------------------------------------ AT-LR006's entries +def _rendered(lines) -> str: + """The sha256 of a file of `lines`, LF-joined with a final LF, as + `render_file` renders it.""" + return hashlib.sha256(("\n".join(lines) + "\n").encode("utf-8")).hexdigest() + + +def _entry(kind: str, verb: str, **parts) -> dict: + """One `commit_write` entry: the journal object, `not_after`, and `parts`.""" + journal = {"kind": kind, "verb": verb, "lane": OPERATOR_LANE, "workstation": WS, + "author": AUTHOR, "message": f"t273: {kind}"} + journal.update(parts.pop("journal", {})) + return {"journal": journal, "not_after": NOT_AFTER, **parts} + + +def _import_entry() -> dict: + edits = [{"ord": 1, "op": "create", "path": "lanes/LANES.md"}] + edits += [{"ord": n, "op": "append", "path": "lanes/LANES.md", "new_text": text} + for n, text in enumerate(LANES_MD, start=2)] + return _entry("import", "import", journal={"git_commit": COMMIT_C, "git_tree": TREE_C}, + edits=edits, files=[{"path": "lanes/LANES.md", "present": True, + "sha256": _rendered(LANES_MD), "final_newline": True}]) + + +def _cutover_entry() -> dict: + edits = [{"ord": 1, "op": "create", "path": "lanes/STORE"}] + edits += [{"ord": n, "op": "append", "path": "lanes/STORE", "new_text": line} + for n, line in enumerate(STORE_LINES, start=2)] + return _entry("cutover", "cutover", edits=edits, + files=[{"path": "lanes/STORE", "present": True, + "sha256": _rendered(STORE_LINES), "final_newline": True}]) + + +def _write_entry(text: str) -> dict: + """A write that appends `text` to `lanes/LANES.md`.""" + return _entry("write", "log", journal={"args_sha256": ARGS_SHA256}, + edits=[{"ord": 1, "op": "append", "path": "lanes/LANES.md", "new_text": text}], + files=[{"path": "lanes/LANES.md", "present": True, + "sha256": _rendered([*LANES_MD, text]), "final_newline": True}]) + + +def _open_when_held(fifo: Path, proc: subprocess.Popen, seconds: float = 120): + """The FIFO's write end, opened once the shim holds a call on it; None + where `proc` ends, or the time runs out, first. Closing it releases the + call.""" + deadline = time.monotonic() + seconds + while time.monotonic() < deadline and proc.poll() is None: + try: + return os.open(str(fifo), os.O_WRONLY | os.O_NONBLOCK) + except OSError: + time.sleep(0.05) + return None + + +#: What an abort release writes into its FIFO (`_let_go`), beside its mark. +ABORT = b"abort\n" + + +def _let_go(fifo: Path, fd: int | None = None, abort: bool = False) -> None: + """A FIFO'S LAST RELEASE, with no moment at which a reader can open it + and be left on it (lane 3's Codex review of code PR 97 at `6d479418`, + SHOULD 1; lane 2's RV7-30, N1). Where the owner still holds its write + end `fd`, the FIFO is unlinked first and `fd` closed after: a reader that + holds it open reads EOF, and none can open it once it is unlinked. Where + the owner holds none, the FIFO is opened once with `O_RDWR | + O_NONBLOCK`, which on Linux neither blocks nor fails for want of a + reader, unlinked while that end is held, and the end closed: a reader + blocked in its `open()` is let go by that open and reads EOF at the + close, and one that comes later finds no FIFO (ENOENT) and exits. A FIFO + already gone is left so. EOF is a held push's release into its git, so a + release on the path that succeeds is EOF alone. An ABORT RELEASE + (`abort`, the teardown's, once what it owns is killed, `_teardown`) + first writes `ABORT` into the FIFO and makes the mark `<fifo>.abort` + beside it: the wrapper's held push, let go then, reads one or the other + and runs no git (lane 3's Codex review of code PR 97 at `18529e5a`, + SHOULD 1). The mark stays beside the FIFO's path, so an abort release is + that path's last use in its case: each is in its owner's outer + `finally`, and no case here makes a FIFO at that path again. Copied from + T270's renderer module.""" + if fd is None: + try: + fd = os.open(str(fifo), os.O_RDWR | os.O_NONBLOCK) + except FileNotFoundError: + return + try: + if abort: + try: + os.write(fd, ABORT) + except (BrokenPipeError, BlockingIOError): + pass # no reader is left to read it, or the FIFO already holds it + Path(f"{fifo}.abort").touch() + finally: + try: + fifo.unlink(missing_ok=True) + finally: + os.close(fd) + + +# ------------------------------------------------------------------ owned processes +#: A PROCESS'S IDENTITY HERE, and the helpers that pin, signal and release a +#: case's processes (`IDENTITY`, `_nonce`, `_stat`, `_carried`, `_Pinned`, +#: `_pin`, `_pin_child`, `_table`, `_stopped`, `_owned`, `_keep`, +#: `_send_each`, `_release` and `_wait_all`), are +#: `tests/sql_register_cleanup.py`'s (T270's), which this module and the +#: renderer module import (round CX-34): its docstring says how a process +#: is owned. So is the one loop of stop, kill, confirm and read again +#: (`_settle_pinned`; round CX-35), which steps 1 and 5 of `_teardown` run. +#: The teardown below is this module's; unlike T270's clean-up, +#: it finds no process by a path (`_find`). + + +def _held_pushes(estate) -> list: + """(pid, start) of each call the wrapper logged as held: a push held at + the FIFO, a process of the rollback's own session's making, never this + process's child.""" + return [(g["pid"], g.get("start", "")) for g in _jsonl(estate.bin / "git-wrapper.log") + if g.get("outcome") == "held"] + + +def _logged(estate) -> list: + """(pid, start token, what) of each git call's launch record + (`git-wrapper.started`), which the wrapper writes before anything else + and `arm()` never resets, and of each push it logged as held + (`_held_pushes`).""" + found = [(rec.get("pid"), rec.get("start") or "", "a git call's launch record") + for rec in _jsonl(estate.bin / "git-wrapper.started")] + found += [(pid, start or "", "a held push") for pid, start in _held_pushes(estate)] + return found + + +def _unlogged(estate, table: dict, nonces: set, books: SimpleNamespace) -> None: + """WHAT THE TEARDOWN'S RECORDS NAME BUT IT CANNOT OWN, each named once in + `books.problems` and never signalled: a launch record or a `held` line + with no start token, and one whose pid and start token a live process, + not a zombie and not pinned, has without the case's identity, as a + process that took the pid within the same tick would be. Each record + is validated by itself, apart from the table of this user's processes + (`table`), so a live one another user owns, or whose environment cannot + be read, is named too (`_misrecorded`; lane 3's Codex review of code PR + 97 at `f776b435`, SHOULD 8). Where the logs cannot be read (`_logged` + raises: an I/O or JSON error), the first such error is kept in + `books.logs`, and the rest is still found and ended before it is raised + (the coordinator's #165 6938182757, point 2).""" + try: + logged = _logged(estate) if estate is not None else [] + except Exception as exc: # kept, and raised once what is known is ended + books.logs[:] = books.logs or [exc] + logged = [] + held = {key[0] for key in books.pinned} + books.problems += [text for text in _misrecorded(logged, nonces, held) + if text not in books.problems] + + +def _find(procs, estate, books: SimpleNamespace) -> int: + """ONE READ of what the teardown owns: each process found, and not + pinned already, registered in `books.pinned` before any signal, then + stopped (SIGSTOP) through its pidfd, each in a `try` of its own, so none + forks or runs on while the rest are found. Returns how many are new. + Owned are: + - `procs`, the case's own children not yet reaped, pinned as such + (`_pin_child`); + - every process whose environment carries the case's nonce (`IDENTITY`): + the estate's (`estate.nonce`), or one a child in `procs` carries, + read while it runs and kept in `books.nonces` for every later read; + each found by its identity alone (`_owned`), with no leader, parent + or record needed: a push the rollback forked before its first + record, the git under a held push, a member of a group whose leader + is gone (lane 3's Codex review of code PR 97 at `46cac748`, BLOCKING + and SHOULD 1). + What the records name but the teardown cannot own is noted + (`_unlogged`). No path is scanned for: the estates here are shared, so + only what the case started, or what carries its identity, is the + teardown's.""" + table, fresh = _table(), [] + books.nonces.add(getattr(estate, "nonce", None)) + for proc in procs: + if proc is not None and proc.returncode is None and proc.pid in table: + books.nonces.add(_carried(proc.pid)) + if (proc.pid, table[proc.pid]["start"]) not in books.pinned: + _keep(books.pinned, fresh, _pin_child(proc)) + books.nonces.discard(None) + _owned(table, books.nonces, books.pinned, fresh) + _unlogged(estate, table, books.nonces, books) + books.refused += _send_each(fresh, signal.SIGSTOP, books.errors) + return len(fresh) + + +def _drain(proc, grace: float): + """`proc`'s output, read for at most `grace` s. Where that times out, + its pipes are closed and it is waited for once more, at most `grace` s; + where that times out too it raises (`RuntimeError`), so it never + returns with `proc` unreaped.""" + try: + return proc.communicate(timeout=grace) + except subprocess.TimeoutExpired as exc: + for pipe in (proc.stdout, proc.stderr): + if pipe is not None: + pipe.close() + try: + proc.wait(timeout=grace) + except subprocess.TimeoutExpired as late: + raise RuntimeError(f"pid {proc.pid} is still unreaped {grace:g} s after its SIGKILL " + f"and its pipes were closed") from late + return exc.stdout, exc.stderr + + +def _attempt(errors: list, step, *args): + """`step(*args)`, where it raises its error kept in `errors` and None + given: each step of the teardown is tried whatever an earlier one + raised.""" + try: + return step(*args) + except Exception as exc: # each step is tried; the errors are raised at the end + errors.append(exc) + return None + + +def _stop_owned(procs, estate, books: SimpleNamespace, grace: float) -> None: + """`_teardown`'s step 1, the shared clean-up's one loop, stopping only + (`_settle_pinned`, its `kill` false; lane 3's Codex review of code PR 97 + at `5a120647`, SHOULD 2): read after read (`_find`), each made once + every process found is seen stopped (`_stopped`), until one finds + nothing new. The deadline, `grace` s on, is checked on every read, + whatever was stopped, and is an error; so is one not seen stopped + (`_seen_stopped`; SHOULD 1 at `f776b435`). Errors are kept in + `books.errors`, and what is found is killed next.""" + _settle_pinned(lambda: _find(procs, estate, books), books, time.monotonic() + grace, + books.errors, kill=False) + + +def _end_children(procs, books: SimpleNamespace, fifo, fd, grace: float) -> list: + """`_teardown`'s steps 2 to 4: each process found killed through its + pidfd, each in a `try` of its own, and each child by its own + `Popen.kill` too; then `fifo` let go with an abort; then each child + drained (`_drain`). Returns each child's (stdout, stderr).""" + _send_each(books.pinned.values(), signal.SIGKILL, books.errors) + for proc in procs: + if proc is not None: + _attempt(books.errors, proc.kill) + if fifo is not None: + _attempt(books.errors, _let_go, fifo, fd, True) + return [_attempt(books.errors, _drain, proc, grace) if proc is not None else None + for proc in procs] + + +def _see_gone(procs, estate, books: SimpleNamespace, grace: float) -> list: + """`_teardown`'s step 5, the shared clean-up's one loop (`_settle_pinned`; + lane 3's Codex review of code PR 97 at `5a120647`, SHOULD 2): each + process found seen gone, then step 1's read made again, and what it + finds seen stopped, killed and seen gone, until a read made once every + one is seen gone finds nothing new. The deadline, `grace` s on, is + checked on every read, whatever was stopped, and is an error; so is a + process found here and not seen stopped (SHOULD 1 at `f776b435`). An + earlier error never spares the read after the kill. Returns the pids + still there.""" + _settle_pinned(lambda: _find(procs, estate, books), books, time.monotonic() + grace, + books.errors) + return sorted(held.pid for held in books.pinned.values() if not held.gone()) + + +def _teardown(*procs, estate=None, fifo: Path | None = None, fd: int | None = None, + grace: float = 60) -> list: + """THE ROLLBACK MODULE'S ONE TEARDOWN, for a case's outer `finally`, from + the making of what it ends (lane 3's Codex reviews of code PR 97 at + `6d479418`, SHOULDs 1 and 2, at `18529e5a`, BLOCKING and SHOULDs 1 and + 2, and at `46cac748`, BLOCKING and SHOULDs 1 and 6). Whatever ended the + case, in this order, each step tried whatever an earlier one raised: + 1. what it owns found, registered, then stopped through its pidfd + (`_find`), read after read, each read made once every process found + is seen stopped (`_stopped`), until a read finds nothing new, or the + deadline, `grace` s on and checked on every read, is reported (the + shared clean-up's one loop, `_settle_pinned`, stopping only): each + child in `procs` not yet reaped (a None is skipped), + and every process carrying the case's identity, the estate's nonce + or one a child carries, so a push forked before its first record, + or a member of a group whose leader is gone, is found by it; + 2. each process found killed (SIGKILL) through its pidfd, never by a + number, each in a `try` of its own, and each child in `procs` by its + own `Popen.kill` too, which signals no child already reaped (the + rollback and the `psql` sessions share this process's group, so + never `killpg`): a push is killed before the FIFO lets it go, so it + never runs (the rerun case is that kill); + 3. `fifo`, where one is given, let go with an abort and unlinked + (`_let_go`), with the write end `fd` where the case still holds one: + a push held on it that no read found, or one that reaches it later, + runs no git; + 4. each child drained, bounded, its pipes closed on a last timeout, and + waited for, bounded (`_drain`), which raises where one stays unreaped; + 5. each process found seen gone, then step 1's read made again, and + what it finds stopped, killed and seen gone, until a read made once + every one is seen gone finds nothing new, or the deadline, `grace` s + on and checked on every read, is reported (the one loop again; + lane 3's Codex review of code PR 97 at `5a120647`, SHOULD 2). + A launch record or a `held` line with no start token, or one whose pid + and start token a live process has without the case's identity, is + never signalled, and is an error. Where the logs cannot be read, their + first error is kept, the rest is still found and ended, and it is the + first error raised. Then the errors are raised: the one alone, or each + named in one, chained from the first; a process found that is still + there is one: the teardown never returns with a process it owns left, + and whatever is raised, every pidfd is let go in its own `finally`, so + none it pinned is left stopped or open (`_release`). Returns each + child's (stdout, stderr), as far as each came.""" + books = SimpleNamespace(pinned={}, problems=[], errors=[], logs=[], nonces=set(), + refused=[]) + try: + _stop_owned(procs, estate, books, grace) + said = _end_children(procs, books, fifo, fd, grace) + left = _see_gone(procs, estate, books, grace) + finally: + _release(books.pinned.values(), books.errors) + errors = books.logs + books.errors + if books.problems: + errors.insert(len(books.logs), RuntimeError( + f"{'; '.join(books.problems)}: a process so logged cannot be told from one that " + f"uses its pid again, so it was never signalled")) + if left: + errors.append(RuntimeError(f"pids {left} are still there {grace:g} s after their " + f"SIGKILL through their pidfds")) + if len(errors) == 1: + raise errors[0] + if errors: + raise RuntimeError("; ".join(f"{type(exc).__name__}: {exc}" + for exc in errors)) from errors[0] + return said + + +# ------------------------------------------------------------------ the register +class RollbackRegister: + """A database of the session cluster, from `template0`, bootstrapped by + `lanes-index bootstrap` for `SCRATCH` (T109; DEC-23), brought to `primary` + with the marker `present` by AT-LR006's route at head `k`, and section + 3.2's shim in front of the real `psql` for every `lanes-index` run here.""" + + def __init__(self, cluster, root: Path): + self.cluster, self.root = cluster, root + #: The case's nonce, which each process the register launches carries + #: (`IDENTITY`): `env()`'s, `psql()`'s and `_bootstrap()`'s (lane 3's + #: Codex review of code PR 97 at `f776b435`, BLOCKING). + self.nonce = _nonce() + root.mkdir(parents=True, exist_ok=True) + name = f"t273_{uuid.uuid4().hex[:8]}" + cluster.psql(f"CREATE DATABASE {name} TEMPLATE template0;") + try: # every step after CREATE DATABASE: on any end, drop it, then re-raise + self.db = Database(cluster, name) + self._bootstrap() + for login, group in ((LOGIN_WRITER, WRITER), (LOGIN_READER, READER)): + self.sql(f"DO $l$ BEGIN CREATE ROLE {login} LOGIN IN ROLE {group}; " + f"EXCEPTION WHEN duplicate_object THEN NULL; END $l$;") + self.k = self._to_primary() + self.shim = root / "shim" + self.shim.mkdir() + (self.shim / "psql").write_text(PSQL_SHIM, encoding="utf-8") + (self.shim / "psql").chmod(0o755) + self.arm([]) + (root / "operator").mkdir() + except BaseException: + try: # what a failed step left, carrying the nonce, ended first (BLOCKING) + _teardown(estate=self.owner(), grace=10) + finally: + cluster.drop_database(name) + raise + + def drop(self) -> None: + self.cluster.drop_database(self.db.name) + + def owner(self) -> SimpleNamespace: + """What `_teardown` reads of the register (its `estate=`): its nonce, + by which the teardown finds each process the register's launches + started, its direct child reaped or not, and a `bin` with no + wrapper's logs in it (lane 3's Codex review of code PR 97 at + `f776b435`, BLOCKING and SHOULD 4).""" + return SimpleNamespace(nonce=self.nonce, bin=self.root / "bin") + + # ---------------------------------------------------------------- the SQL side + def psql(self, script: str, role: str = None, appname: str = "t273") -> subprocess.CompletedProcess: + """One `psql` as the fixture's superuser, as `role` where one is named, + with the commit call's settings, so a refusal's first stderr line is + `ERROR: <SQLSTATE>: <message>`.""" + head = "\\set VERBOSITY verbose\n\\set SHOW_CONTEXT never\nSET client_encoding = 'UTF8';\n" + if role: + head += f"SET ROLE {role};\n" + return subprocess.run([self.db.psql_bin, "-X", "-q", "-A", "-t", "-v", "ON_ERROR_STOP=1"], + input=head + script, capture_output=True, encoding="utf-8", + errors="replace", + env=dict(self.db.env(appname=appname), **{IDENTITY: self.nonce}), + timeout=120, check=False) + + def sql(self, script: str, role: str = None) -> str: + proc = self.psql(script, role) + assert proc.returncode == 0, (f"psql{' as ' + role if role else ''} exited " + f"{proc.returncode}: {proc.stderr.strip()}\n{script}") + return proc.stdout.strip() + + def _bootstrap(self) -> None: + """`lanes-index bootstrap` through the admin service, with a + configuration that holds `register_schema=` `SCRATCH` alone.""" + home = self.root / "admin" + _private(home / ".pg_service.conf", + f"[{ADMIN_SERVICE}]\nhost={self.db.host}\nport={self.db.port}\n" + f"dbname={self.db.name}\nuser={SUPERUSER}\n") + conf = _private(self.root / "boot" / "lanes-index.conf", f"register_schema={SCRATCH}\n") + env = guard_strip_env(os.environ, strip=("XDG_",)) + env.update(HOME=str(home), XDG_CONFIG_HOME=str(home / ".config"), + XDG_STATE_HOME=str(self.root / "admin-state"), LANES_WORKSTATION=WS, + LANES_INDEX_CONFIG=str(conf), **{IDENTITY: self.nonce}) + proc = subprocess.run([sys.executable, str(LANES_INDEX), "bootstrap", "--admin-service", + ADMIN_SERVICE, "--label", LABEL, "--repository", "opensoft/t273", + "--lane", OPERATOR_LANE, "--no-passwords"], + capture_output=True, encoding="utf-8", errors="replace", env=env, + timeout=300, stdin=subprocess.DEVNULL, check=False) + assert proc.returncode == 0, (f"the scratch schema's bootstrap (T109's DEC-23 rendering) " + f"failed:\n{_said(proc)}") + schemas = self.sql(f"SELECT string_agg(nspname, ',' ORDER BY nspname) FROM pg_namespace " + f"WHERE nspname IN ('{SCRATCH}', '{DEFAULT_SCHEMA}');") + assert schemas == SCRATCH, (f"the bootstrap for {SCRATCH} made the schemas {schemas!r}, " + f"not {SCRATCH} alone") + + def window(self) -> dict: + return json.loads(self.sql(f"SELECT to_jsonb(v) FROM {SCRATCH}.schema_version v;")) + + def commit(self, base: int, body: dict, what: str) -> int: + """The commit call as a writer sends it (section 1.3's step 3; AT-LR006's + fixture): one SERIALIZABLE transaction around `commit_write`, as + REGISTER-WRITER. Returns the entry's seq.""" + literal = json.dumps(body, ensure_ascii=True).replace("'", "''") + proc = self.psql(f"BEGIN ISOLATION LEVEL SERIALIZABLE;\n" + f"SELECT {SCRATCH}.commit_write({base}, '{uuid.uuid4()}'::uuid, " + f"{self.window()['version']}, '{self.switch()['generation']}'::uuid, " + f"'{literal}'::jsonb);\nCOMMIT;\n", WRITER) + assert proc.returncode == 0, f"{what}: commit_write refused it: {proc.stderr.strip()}" + return int(proc.stdout.strip().splitlines()[-1]) + + def _to_primary(self) -> int: + """AT-LR006's route (TP:4610-4615): an import, a cutover and + `record_marker`, then one write. Returns the head, `k`.""" + imported = self.commit(self.head(), _import_entry(), "the import") + cut = self.commit(imported, _cutover_entry(), "the cutover") + marker = self.sql(f"SELECT {SCRATCH}.record_marker({self.window()['version']}, {cut}, " + f"'{MARKER_COMMIT}', '{WS}');", WRITER) + assert marker == "present", f"record_marker answered {marker!r}, not present" + k = self.commit(cut, _write_entry("t273: a write after the cutover"), "the write") + switch = self.switch() + assert (switch["mode"], switch["marker_state"], k) == ("primary", "present", 2), ( + f"AT-LR006's route left the switch {switch} and the head {k}, not primary, present " + f"and 2") + return k + + def switch(self) -> dict: + return json.loads(self.sql(f"SELECT to_jsonb(s) FROM {SCRATCH}.register_switch s;")) + + def head(self) -> int: + return int(self.sql(f"SELECT seq FROM {SCRATCH}.register_head;")) + + def mirror(self) -> dict: + return json.loads(self.sql(f"SELECT to_jsonb(m) FROM {SCRATCH}.mirror_state m;")) + + def journal(self) -> list: + """Each entry's seq, kind and generated `operator` flag, by seq.""" + return json.loads(self.sql( + f"SELECT coalesce(jsonb_agg(jsonb_build_array(j.seq, j.kind, j.operator) " + f"ORDER BY j.seq), '[]') FROM {SCRATCH}.journal j;")) + + def state(self) -> dict: + """The switch whole, the head and the journal: what "does not move" compares.""" + return {"switch": self.switch(), "head": self.head(), "journal": self.journal()} + + def wait_sql(self, count_query: str, what: str, ceiling: float = 10.0) -> None: + """Poll `count_query` in 0.05 s steps under `ceiling` until it counts + one row or more.""" + end = time.monotonic() + ceiling + while time.monotonic() < end: + if self.sql(count_query) != "0": + return + time.sleep(0.05) + pytest.fail(f"{what}: not seen within {ceiling} s") + + # ---------------------------------------------------------------- lanes-index + def config(self, name: str, *, schema: str | None = SCRATCH, port: int | None = None) -> Path: + """A 0600 `lanes-index.conf` in a directory of its own: `mode=index`, + the URLs of the cluster's socket (at `port` where it is given), the + label, and `register_schema=` `schema` where it is not None.""" + where = (f"{quote(str(self.db.host), safe='')}:{self.db.port if port is None else port}" + f"/{self.db.name}?connect_timeout={CONNECT_TIMEOUT}") + lines = ["mode=index", f"register_url=postgresql://{LOGIN_WRITER}@{where}", + f"reader_url=postgresql://{LOGIN_READER}@{where}", + f"register_addresses={ADDRESSES}", f"register_label={LABEL}"] + if schema is not None: + lines.append(f"register_schema={schema}") + return _private(self.root / name / "lanes-index.conf", "\n".join(lines) + "\n") + + def env(self, conf: Path) -> dict: + """The operator lane's environment (D24): no inherited `PG*`, lane, + session, git or XDG variable; `LANES_LANE`, this workstation, git's + author, the configuration, the shim first on `PATH`, and the case's + nonce (`IDENTITY`), so the teardown owns what it starts.""" + env = guard_strip_env(os.environ, strip=("GIT_", "XDG_", "EMAIL")) + env[IDENTITY] = self.nonce + env.update(HOME=str(self.root / "home"), XDG_STATE_HOME=str(self.root / "state"), + XDG_CONFIG_HOME=str(self.root / "config"), LANES_INDEX_CONFIG=str(conf), + LANES_LANE=OPERATOR_LANE, LANES_WORKSTATION=WS, + PATH=f"{self.shim}{os.pathsep}{os.environ.get('PATH', os.defpath)}", + **OPERATOR_GIT) + return env + + def argv(self) -> list: + return [sys.executable, str(LANES_INDEX), "rollback"] + + def rollback(self, conf: Path) -> subprocess.CompletedProcess: + """`lanes-index rollback`, the shipped one, in the operator's directory.""" + return subprocess.run(self.argv(), capture_output=True, encoding="utf-8", + errors="replace", env=self.env(conf), cwd=str(self.root / "operator"), + timeout=180, stdin=subprocess.DEVNULL, check=False) + + def arm(self, arms: list) -> None: + (self.shim / PSQL_SHIM_CONTROL).write_text( + json.dumps({"psql": self.db.psql_bin, "arms": arms}), encoding="utf-8") + + def calls(self) -> list: + """The shim's entries that carried a request, in call order.""" + log = self.shim / PSQL_SHIM_LOG + if not log.exists(): + return [] + entries = [json.loads(line) for line in log.read_text(encoding="utf-8").splitlines() + if line] + return [entry for entry in entries if entry.get("kind") != "version"] + + def writes(self) -> list: + """The calls that carried a function that writes (`WRITE_CALLS`).""" + return [c for c in self.calls() if any(w in c.get("sent", "") for w in WRITE_CALLS)] + + +@pytest.fixture +def rb_register(pg_cluster, tmp_path): + reg = RollbackRegister(pg_cluster, tmp_path / "reg") + try: + yield reg + finally: + reg.drop() + + +# =================================================================== T304's own test +def _diverged_refuses_2(reg: RollbackRegister) -> None: + proc = reg.psql(f"SELECT {SCRATCH}.record_mirror_state('{WS}', '{SHA_DIVERGED}', NULL);", + WRITER) + assert proc.returncode == 0, f"record_mirror_state refused the divergence: {proc.stderr}" + before = reg.state() + conf = reg.config("conf") + proc = reg.rollback(conf) + assert proc.returncode == 2, f"a rollback with a divergence recorded is not refused 2:\n{_said(proc)}" + assert f"diverged at {SHA_DIVERGED}" in proc.stderr, _said(proc) + for way in ("import --single", "render --revert"): + assert way in proc.stderr, f"the refusal does not name S2's way out {way!r}:\n{_said(proc)}" + assert reg.writes() == [], ( + f"step 0's database half did not refuse before step 1: a call that writes was sent: " + f"{[c.get('sent') for c in reg.writes()]}") + assert reg.state() == before, "the refused rollback moved the switch, the marker or the head" + assert not (conf.parent / OUTAGE_FILE).exists(), "the refused rollback declared the outage" + + +def _step_1_one_transaction(reg: RollbackRegister) -> None: + k = reg.k + proc = reg.rollback(reg.config("conf")) + switch = reg.switch() + assert (switch["mode"], switch["marker_state"]) == ("files", "removing"), ( + f"step 1 left the switch {switch}, not files with the marker removing:\n{_said(proc)}") + assert (switch["set_seq"], switch["marker_seq"]) == (k + 1, k + 1), ( + f"set_seq and marker_seq are not the rollback's own seq {k + 1}: {switch}") + assert reg.head() == k + 1, f"the head is {reg.head()}, not k+1 = {k + 1}:\n{_said(proc)}" + journal = reg.journal() + assert journal[-1] == [k + 1, "rollback", True], ( + f"the last entry is {journal[-1]}, not the operator's rollback entry at {k + 1}: {journal}") + assert [seq for seq, _kind, _operator in journal] == list(range(k + 2)), journal + edits = json.loads(reg.sql( + f"SELECT coalesce(jsonb_agg(jsonb_build_array(e.ord, e.op, e.path) ORDER BY e.ord), '[]') " + f"FROM {SCRATCH}.journal_edits e WHERE e.seq = {k + 1};")) + assert edits == [[1, "remove", "lanes/STORE"]], f"the rollback's entry's edits are {edits}" + files = json.loads(reg.sql( + f"SELECT coalesce(jsonb_agg(jsonb_build_array(f.path, f.present) ORDER BY f.path), '[]') " + f"FROM {SCRATCH}.journal_files f WHERE f.seq = {k + 1};")) + assert files == [["lanes/STORE", False]], f"the rollback's entry's files rows are {files}" + writes = reg.writes() + assert len(writes) == 1 and "commit_write(" in writes[0]["sent"], ( + f"not one call that writes, step 1's commit call: " + f"{[c.get('sent', '')[:300] for c in writes]}") + sent = writes[0]["sent"] + begin, call, end = (sent.find("BEGIN ISOLATION LEVEL SERIALIZABLE"), + sent.find("commit_write("), sent.rfind("COMMIT")) + assert 0 <= begin < call < end, ( + f"step 1's call is not one SERIALIZABLE transaction around commit_write: {sent[:600]}") + + +def _outage_declared_with_mirror_seq(reg: RollbackRegister) -> None: + k = reg.k + conf = reg.config("conf") + proc = reg.rollback(conf) + path = conf.parent / OUTAGE_FILE + assert path.exists(), (f"the rollback's start declared no outage beside its configuration " + f"({path}):\n{_said(proc)}") + lines = path.read_text(encoding="utf-8").splitlines() + fields = dict(line.split("=", 1) for line in lines) + assert lines[0] == "format=1", lines + assert (fields.get("kind"), fields.get("mirror-seq")) == ("rollback", str(k)), ( + f"the declaration is not marked as from a rollback with mirror-seq k = {k}: {lines}") + assert (fields.get("database"), fields.get("host")) == (LABEL, WS), lines + assert "until" not in fields, f"a rollback's declaration carries an expiry: {lines}" + assert "outage declared:" in proc.stdout, _said(proc) + + +def _lost_turn_rechecks_step_0(reg: RollbackRegister) -> None: + k = reg.k + before = reg.state() + fifo = reg.root / "hold.fifo" + proc = fd = holder = None + try: # owned to the end, the FIFO with them (`_teardown`) + os.mkfifo(str(fifo), 0o600) + # The rollback's second read, the second call carrying `diverged_sha`, is held. + reg.arm([{"mode": "hold", "fifo": str(fifo), "match": "diverged_sha", "call": 2}]) + holder = reg.db.session(appname=HOLDER) + holder.stdin.write(f"BEGIN;\nSELECT seq FROM {SCRATCH}.register_head WHERE id = 1 " + f"FOR UPDATE;\n") + holder.stdin.flush() + reg.wait_sql(f"SELECT count(*) FROM pg_stat_activity WHERE application_name = '{HOLDER}' " + f"AND state = 'idle in transaction' AND backend_xid IS NOT NULL;", + "the second session's lock on the head row") + proc = subprocess.Popen(reg.argv(), stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, + stderr=subprocess.PIPE, text=True, + env=reg.env(reg.config("conf")), cwd=str(reg.root / "operator")) + fd = _open_when_held(fifo, proc) + assert fd is not None, "the rollback never reached a second read: it did not lose its turn" + # Step 1's call has ended; the divergence is recorded and the row released at once. + out, err = holder.communicate( + input=(f"SET ROLE {WRITER};\nSELECT {SCRATCH}.record_mirror_state('{WS_MEANWHILE}', " + f"'{SHA_MEANWHILE}', NULL);\nCOMMIT;\n"), timeout=60) + assert holder.returncode == 0, f"the second session could not record the divergence: {err}" + assert reg.mirror()["diverged_sha"] == SHA_MEANWHILE, reg.mirror() + end, fd = fd, None + _let_go(fifo, end) # the read released: its FIFO unlinked, then the write end closed + out, err = proc.communicate(timeout=120) + finally: + _teardown(proc, holder, estate=reg.owner(), fifo=fifo, fd=fd) + ended = f"exit {proc.returncode}\n--- stdout ---\n{out[-3000:]}\n--- stderr ---\n{err[-3000:]}" + assert proc.returncode == 2, f"the rollback did not end 2 after its lost turn:\n{ended}" + assert "55P03" in err and "lost its turn" in err, ( + f"step 1 did not meet 55P03 at rollback's lock_timeout and go back:\n{ended}") + assert f"diverged at {SHA_MEANWHILE}" in err, ( + f"step 0 did not refuse the divergence recorded meanwhile:\n{ended}") + kinds = ["write" if any(w in c.get("sent", "") for w in WRITE_CALLS) else + "read" if "diverged_sha" in c.get("sent", "") else "other" for c in reg.calls()] + assert kinds == ["read", "write", "read"], ( + f"not step 0's read, step 1's one lost call, then step 0's read afresh: {kinds}") + after = reg.state() + assert after == before, f"the switch, the marker or the head moved: {before} -> {after}" + assert after["head"] == k + + +def _database_unreachable_69(reg: RollbackRegister) -> None: + port = reg.db.port + 1 + assert not (Path(reg.db.host) / f".s.PGSQL.{port}").exists() + before = reg.state() + conf = reg.config("unreachable", port=port) + proc = reg.rollback(conf) + assert proc.returncode == 69, f"a rollback that cannot reach the database is not 69:\n{_said(proc)}" + assert "could not be read" in proc.stderr, _said(proc) + assert reg.calls(), "the rollback sent no read, so it never met the database's silence" + assert reg.writes() == [], "a call that writes was sent" + assert reg.state() == before, "the switch, the marker or the head moved" + assert not (conf.parent / OUTAGE_FILE).exists(), "the failed rollback declared the outage" + + +def _not_a_scratch_schema_2(reg: RollbackRegister) -> None: + before = reg.state() + conf = reg.config("default-schema", schema=None) + proc = reg.rollback(conf) + assert proc.returncode == 2, (f"a rollback with register_schema= unset is not refused 2 " + f"while the constant is unset:\n{_said(proc)}") + assert f"register_schema={DEFAULT_SCHEMA}" in proc.stderr and "scratch schema" in proc.stderr, ( + f"the refusal does not name the default schema and the scratch-schema rule:\n{_said(proc)}") + assert reg.calls() == [], f"the refused rollback sent a request: {reg.calls()}" + assert reg.state() == before, "the switch, the marker or the head moved" + assert not (conf.parent / OUTAGE_FILE).exists(), "the refused rollback declared the outage" + + +T304_CASES = { + "diverged-refuses-2": _diverged_refuses_2, + "step-1-one-transaction": _step_1_one_transaction, + "outage-declared-with-mirror-seq": _outage_declared_with_mirror_seq, + "lost-turn-rechecks-step-0": _lost_turn_rechecks_step_0, + "database-unreachable-69": _database_unreachable_69, + "not-a-scratch-schema-2": _not_a_scratch_schema_2, +} + + +@pytest.mark.skipif(_render_git_half() == [b"True"], reason=CONSTANT_SET) +@pytest.mark.parametrize("case", list(T304_CASES)) +def test_rollback_steps_0_and_1_run_only_against_a_scratch_schema(rb_register, case): + """T304's own test (R-F10-34): steps 0 and 1 of the shipped `lanes-index + rollback`, the constant unset, on `SCRATCH` at `primary` with the marker + `present` and head `k`. Each id is in the module's docstring.""" + _constant_unset() + T304_CASES[case](rb_register) + + +# =================================================================== T273b: test 8, 4.2, AT-F1 +#: T273b: AT-8's test 8 (11), section 4.2 (2) and AT-F1 (7), as the test plan +#: (TP:1546-1734, TP:5447-5509, TP:7568-7609) and F13d's T273 bullet give them. +#: +#: THE ESTATE (TP:1592-1636). Test 7's cutover host, `CutoverRegister` in +#: `test_sql_register_import.py` (line W3a's T211j, merged into this line for +#: it, as AT-F2's cases build on it): the fixture register at C imported, ws1 +#: the operator lane's checkout (`LANES_LANE=repoA-2`, F12) running T203's +#: flipped copy, so that `rollback` takes `lanes_register` with the renderer's +#: git half; then the cutover, and two writes on primary from ws1, each +#: rendered, so `k` is the head, 3. Test 5's `git` wrapper and section 3.2's +#: shim are first on ws1's `PATH`. ws2, the missed workstation, is a clone of +#: its own with its own `$HOME` and a `mode=primary` configuration, lane +#: `repoW-1`, and a shim of its own. +#: +#: WHAT EACH WAITS FOR. Every estate case fails until lane 3's T327 (the +#: cutover's push and read-back, so the marker reads `present`), lane 4's +#: T415 and T416 (a write on primary, and its render's fork), lane 3's T321 to +#: T323 (the render), and T326 (step 0's fetch and steps 2 to 4). Of the +#: missed writer's ids, the eight `commit-*` also wait for lane 4's T420 +#: (D10's refusals on primary), and the other 40 for lane 1's T111 (AT-3's +#: line in check 4's 69); case (i) also waits for T417 (exit 3 and its +#: rerun). No id waits for lane 4's T421 or lane 5's T507: none runs the +#: guard, and with T421's merge reverted the `claim` ids fail as they do with +#: it (T273's Order, tasks:2512 at 204145ae; lane 2's RB15; lane 4, #165 +#: 6826679959). `test_a_rollback_entry_over_a_recorded_divergence_is_lr012` (direct +#: calls, lane 1's T107) and `test_rollback_exits_2_on_lr012_naming_the_ +#: divergence_and_both_ways_out` (a False copy on the scratch schema, T304) +#: need neither, and can pass on line R now. The four FP lost-turn ids need +#: no engine, and fail until T326, at their own assertion. +#: +#: READINGS, NOT FOUND IN A CONTRACT: +#: - "A fetch of `origin main`" is a `git fetch` whose arguments name +#: `origin`, logged by the wrapper; "between" two `psql` calls is read from +#: the wrapper's own count of the requests the shim or the fake had logged +#: when the fetch started, so no clock is shared. +#: - The held session of (g) and of T304's lost turn is the fixture's +#: superuser holding `register_head`'s row `FOR UPDATE`, not a writer +#: replaying a commit call: the rollback's call meets the same lock, and a +#: divergence recorded meanwhile then fails its `FOR SHARE` read of +#: `mirror_state` with 40001 in the same way. +#: - (g)'s `[last-error-only]` and AT-F1's retries read "the marker +#: `removing`" as step 1's state: where T326's steps 2 to 4 have run to +#: their end, the marker reads `absent` and the rollback exits 0, which the +#: case accepts too. +#: - (c)'s ids are `<verb>-<fetch>-<no_fetch>`, with `fetched` or +#: `not-fetched`, and `unset` or `no-fetch` for `LANES_NO_FETCH`. +#: - AT-F1's removal entry and rerun cases run on the clean estate, not after +#: a single-write import: what they check is step 1 and the rerun, which the +#: import does not change. +#: - (h)'s FP register is a clean estate at `Register-Seq: 1`: the import at +#: 0, whose images are the workspace's render set, and the cutover at 1, the +#: head, with no divergence. The fake answers from it every read a try makes +#: before step 1, T326's git half's two included (`HEAD_READ_MARK` and +#: `IMAGE_READ_MARK`), so each try's check passes and reaches step 1's lost +#: turn (lane 3's #165 6813528630). + +EM, DOT = chr(0x2014), chr(0xB7) +#: AT-3's line, which the missed writer's refusal carries (TP:1651-1652). +AT3_LINE = "this estate's register is SQL; configure `mode=primary`" +#: The missed workstation's lane: a LIVE row of test 7's fixture register. +MISSED_LANE = "repoW-1" +#: The object every `claim` case names, held by no lane at C. +CLAIMED = "opensoft/repoQ#8" +VERB_NAMES = ("set-row-state", "replace-in-row", "append-session-id", "append-line", "commit", + "claim") +MISSED_CASES = [f"{verb}-{fetch}-{no_fetch}" for verb in VERB_NAMES + for fetch in ("fetched", "not-fetched") for no_fetch in ("unset", "no-fetch")] +#: The text the `commit` case's hand edit changes in `MISSED_LANE`'s row. +ROW_TEXT = "its log has WORD lines" +#: A `Register-Seq` trailer. +REGISTER_SEQ = re.compile(r"^Register-Seq: ([0-9]+)$", re.M) +#: The rollback's read, and its step-1 call, as the shim and the fake see them. +READ_MARK, STEP_1_MARK = "diverged_sha", "commit_write(" +EXIT_BUSY = 75 +#: A push it cannot confirm (exit-codes.md's 3; ops:340). +EXIT_IN_DOUBT = 3 + + +def _imp(): + """`test_sql_register_import`: test 7's fixture register and cutover host.""" + import test_sql_register_import as module + return module + + +def _cut(): + """`test_sql_register_cutover`: AT-F2's fixture, `F2Register`, test 7's + cutover host with test 5's `git` wrapper, whose arms leave a push + unconfirmed, and `_first_reach`.""" + import test_sql_register_cutover as module + return module + + +def _script(path: Path, text: str) -> Path: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8") + path.chmod(0o755) + return path + + +def _jsonl(path: Path) -> list: + if not path.exists(): + return [] + return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line] + + +def _requests(log: Path) -> list: + """A `psql` log's entries that carried a request: never a `--version`.""" + return [entry for entry in _jsonl(log) if entry.get("kind") != "version"] + + +#: TEST 5'S `git` WRAPPER (TP:1060-1080), with what AT-8 needs: each call is +#: one JSON line of `git-wrapper.log`, its subcommand, its argv, its pid, and +#: `psql_before`, the number of requests the `psql` log named in the control +#: file held when it started. Before anything else each call writes its +#: launch record, its pid and start token, field 22 of its `/proc/<pid>/stat`, +#: to `git-wrapper.started`, which `arm()` never resets, so the teardown owns +#: it from its launch (`_teardown`). `hold`, `{"call": <subcommand>, "fifo": +#: path}`, blocks that call on the FIFO until the test closes its end; its +#: `held` line also carries `start`, its start token, by which the teardown +#: knows it is still that process (`_pin`). Let go by an abort release +#: (`_let_go`'s `abort`), the held call ends with 75 and runs no git. +GIT_WRAPPER = r'''#!/usr/bin/env -S python3 -I +# Before anything else each call writes its launch record, its pid and start +# token, to git-wrapper.started. +import fcntl, json, os, subprocess, sys +HERE = os.path.dirname(os.path.abspath(__file__)) +CONTROL = os.path.join(HERE, "git-wrapper.json") +LOG = os.path.join(HERE, "git-wrapper.log") +STARTED = os.path.join(HERE, "git-wrapper.started") +WITH_VALUE = {"-C", "-c", "--git-dir", "--work-tree", "--namespace", "--exec-path", + "--config-env"} + + +def subcommand(args): + i = 0 + while i < len(args): + if args[i] in WITH_VALUE: + i += 2 + elif args[i].startswith("-"): + i += 1 + else: + return args[i] + return "" + + +def requests(path): + try: + with open(path, encoding="utf-8") as handle: + return sum(1 for line in handle + if line.strip() and json.loads(line).get("kind") != "version") + except (OSError, ValueError): + return 0 + + +def stat(pid): + """The fields of /proc/<pid>/stat after the command's name, or None.""" + try: + with open("/proc/%d/stat" % pid, "rb") as handle: + raw = handle.read() + except OSError: + return None + return raw[raw.rindex(b")") + 2:].split() + + +def started(pid): + """`pid`'s start token: field 22 of its /proc stat, its start in clock + ticks since boot, which no process that uses the pid again shares; "" + where it is gone.""" + fields = stat(pid) + return fields[19].decode() if fields else "" + + +def launched(): + """THE LAUNCH RECORD, before anything else the call does: its pid and + start token, one line of git-wrapper.started, which `arm()` never + resets, so the teardown owns the call from its launch.""" + me = os.getpid() + with open(STARTED, "a", encoding="utf-8") as handle: + fcntl.flock(handle, fcntl.LOCK_EX) + handle.write(json.dumps({"pid": me, "start": started(me)}) + "\n") + handle.flush() + + +def log(record): + with open(LOG, "a", encoding="utf-8") as handle: + handle.write(json.dumps(record) + "\n") + + +def main(): + launched() + args = sys.argv[1:] + with open(CONTROL, encoding="utf-8") as handle: + control = json.load(handle) + sub = subcommand(args) + record = {"sub": sub, "argv": args, "pid": os.getpid(), + "psql_before": requests(control.get("psql_log") or "")} + hold = control.get("hold") + if hold and hold.get("call") == sub: + log(dict(record, outcome="held", start=started(os.getpid()))) + with open(hold["fifo"], "rb") as fifo: + said = fifo.read() + if said or os.path.exists(hold["fifo"] + ".abort"): + log(dict(record, outcome="aborted", rc=75)) + return 75 # an abort release: this call runs no git + rc = subprocess.run([control["git"]] + args).returncode + log(dict(record, outcome="ran", rc=rc)) + return rc + + +sys.exit(main()) +''' + + +def _real_git() -> str: + found = shutil.which("git") + assert found, "no git on PATH" + return found + + +def _lane_checkout(origin: Path, checkout: Path, lane: str, env: dict) -> Path: + """`<c>`, THE WRITE LANE'S OWN CHECKOUT (lane 3's batch g Q119, #165 + 6813027223): beside the checkout `workspace.yaml` names as W, at + `<W>-lanes/<lane>`, W being its real path, as `lane_checkout_path` puts + it (Amendment 23 S1). On primary a write reads its author, its pending + hand edits and its `repos.tsv` from there, and refuses 2 where it is not + there, "Nothing was sent" (B15 tasks:1154). A clone of W's own origin, as + `lane-checkout <lane> --create` makes one, made after the case's last + push from W, as LX's T253f and N2's T243f make theirs. One that is + already there is kept, so a register that makes its own keeps it.""" + real = Path(os.path.realpath(checkout)) + target = real.parent / f"{real.name}-lanes" / lane + if not target.exists(): + target.parent.mkdir(parents=True, exist_ok=True) + subprocess.run(["git", "clone", "-q", str(origin), str(target)], check=True, env=env, + capture_output=True, stdin=subprocess.DEVNULL) + return target + + +class MissedWorkstation: + """ws2, THE MISSED WORKSTATION (TP:1600-1604): a clone of origin of its + own, its own `$HOME` and `workspace.yaml`, a `mode=primary` + configuration naming the same database, lane `MISSED_LANE`, the flipped + copy's `lanes-edit.sh`, and a shim of its own first on `PATH`.""" + + def __init__(self, estate: "RollbackEstate", name: str): + reg = estate.reg + self.estate, self.root = estate, estate.root / name + self.home = self.root / "home" + agents = self.home / ".agents" + agents.mkdir(parents=True) + self.clone = self.home / "projects" / "wip" + subprocess.run(["git", "clone", "-q", str(reg.origin), str(self.clone)], check=True, + env=reg.env, capture_output=True, stdin=subprocess.DEVNULL) + # `MISSED_LANE`'s `<c>`, cloned with W: a ws2 kept behind the + # rollback's push keeps it behind too (Q119), and `fetch` moves both. + self.c = _lane_checkout(reg.origin, self.clone, MISSED_LANE, reg.env) + (agents / "workspace.yaml").write_text(f"repository: {reg.origin}\npath: {self.clone}\n", + encoding="utf-8") + self.conf = _private(self.root / "conf" / "lanes-index.conf", + reg.primary_conf.read_text(encoding="utf-8")) + self.shim = self.root / "shim" + _script(self.shim / "psql", PSQL_SHIM) + self.arm([]) + for d in ("state", "config", "tmp"): + (self.root / d).mkdir() + env = dict(reg.env) + env.pop("LANES_INDEX", None) + env.update(HOME=str(self.home), AGENT_PROTOCOL_ROOT=str(agents), + XDG_STATE_HOME=str(self.root / "state"), + XDG_CONFIG_HOME=str(self.root / "config"), TMPDIR=str(self.root / "tmp"), + CLAUDE_CONFIG_DIR=str(self.home / ".claude"), LANES_REPO=str(self.clone), + LANES_INDEX_CONFIG=str(self.conf), LANES_LANE=MISSED_LANE, + LANES_EDIT=str(reg.copy.parent / "lanes-edit.sh"), + PATH=f"{self.shim}{os.pathsep}{reg.env['PATH']}") + self.env = env + + def arm(self, arms: list) -> None: + """The shim's arms, with its log, ends and counters started afresh.""" + (self.shim / PSQL_SHIM_CONTROL).write_text( + json.dumps({"psql": self.estate.db.psql_bin, "arms": arms}), encoding="utf-8") + for name in (PSQL_SHIM_LOG, "psql-shim.ends"): + (self.shim / name).write_text("", encoding="utf-8") + (self.shim / "psql-shim.state").write_text("{}", encoding="utf-8") + + def git(self, *args: str) -> str: + proc = subprocess.run(["git", "-C", str(self.clone), *args], capture_output=True, + text=True, env=self.env, stdin=subprocess.DEVNULL, check=False) + assert proc.returncode == 0, f"git {' '.join(args)} in ws2: {proc.stderr}" + return proc.stdout + + def fetch(self) -> None: + self.git("fetch", "-q", "origin") + subprocess.run(["git", "-C", str(self.c), "fetch", "-q", "origin"], check=True, + env=self.env, capture_output=True, stdin=subprocess.DEVNULL) + + def edit(self, *args: str, env: dict | None = None) -> subprocess.CompletedProcess: + child = dict(self.env) + for key, value in (env or {}).items(): + if value is None: + child.pop(key, None) + else: + child[key] = value + return subprocess.run(["bash", str(self.estate.reg.copy.parent / "lanes-edit.sh"), + *args], capture_output=True, text=True, env=child, + cwd=str(self.clone), timeout=300, stdin=subprocess.DEVNULL) + + def snapshot(self) -> dict: + """ws2's HEAD, its index, its last-fetched tip, and the bytes of every + file under `lanes/` in its work tree.""" + lanes = {str(p.relative_to(self.clone)): hashlib.sha256(p.read_bytes()).hexdigest() + for p in sorted((self.clone / "lanes").rglob("*")) if p.is_file()} + return {"head": self.git("rev-parse", "HEAD").strip(), + "fetched": self.git("rev-parse", "refs/remotes/origin/main").strip(), + "index": hashlib.sha256(self.git("ls-files", "-s").encode()).hexdigest(), + "lanes": lanes} + + def hand_edit(self) -> bool: + """`commit`'s hand edit of `MISSED_LANE`'s row, left uncommitted.""" + path = self.clone / "lanes" / "LANES.md" + text = path.read_text(encoding="utf-8") + if ROW_TEXT not in text: + return False + path.write_text(text.replace(ROW_TEXT, ROW_TEXT + " by hand", 1), encoding="utf-8") + return True + + def undo_hand_edit(self) -> None: + self.git("checkout", "-q", "--", "lanes/LANES.md") + + +def _verb_args(verb: str) -> list: + """The verb's arguments, as lane `MISSED_LANE` writes them (each checked + in files mode on test 7's fixture register).""" + imp = _imp() + return { + "set-row-state": ["set-row-state", MISSED_LANE, f"PAUSED {DOT} test 8"], + "replace-in-row": ["replace-in-row", MISSED_LANE, ROW_TEXT, f"{ROW_TEXT}, test 8"], + "append-session-id": ["append-session-id", MISSED_LANE, f"harness `{imp.UUID_W1}`", + " (test 8)"], + "append-line": ["append-line", f"HOLD {EM} lane {MISSED_LANE} (Eagle), window w, " + f"2026-11-11T00:00:00Z: opensoft/repoQ main {imp.TIP_A} for test 8"], + "commit": ["commit", "test 8's hand edit"], + "claim": ["claim", CLAIMED, "--no-github"], + }[verb] + + +class RollbackEstate: + """TEST 8'S ESTATE (TP:1592-1636), on test 7's cutover host: see the + notes above T273b. `prepare()` makes the cutover and the writes; until + their tasks land it fails at its own assertion, naming them. + + THE ENVIRONMENT WINDOW (lane 3's Codex review of code PR 97 at + `5a120647`, SHOULD 3): while `__init__` builds test 7's cutover host, + the case's nonce is in this process's `os.environ`. While that window + is open, no other thread of this worker may launch a process or change + the environment: a process launched then would carry the nonce, and + this estate's teardown would end it; a change to `IDENTITY` would be + overwritten as the window closes. Pytest runs a worker's tests one at a + time, and each xdist worker is a process with its own environment.""" + + def __init__(self, root: Path, db, *, writes: int = 2): + imp = _imp() + self.imp, self.db, self.root, self.writes = imp, db, root, writes + self.bin = root / "bin" + #: The case's nonce (`IDENTITY`), made before anything is launched, and + #: in the environment every command of the register launches from, its + #: construction's among them (lane 3's Codex review of code PR 97 at + #: `f776b435`, BLOCKING): test 7's `Workspace` copies this process's + #: environment once, as it is built, so the nonce is in it for the + #: construction alone, and the value before put back after, whatever + #: is raised. Where the construction raises, what it started is ended + #: by the nonce (`_teardown`) before the error goes on. While this + #: window is open, no other thread of this worker may launch a process + #: or change the environment (the class docstring; SHOULD 3 at + #: `5a120647`). + self.nonce = _nonce() + _script(self.bin / "git", GIT_WRAPPER) + _script(self.bin / "psql", PSQL_SHIM) + self.real_git = _real_git() + self.arm() + before = os.environ.get(IDENTITY) + os.environ[IDENTITY] = self.nonce + try: + self.reg = imp.CutoverRegister(root / "ws1", db, extra_path=self.bin) + except BaseException: + _teardown(estate=self, grace=10) + raise + finally: + if before is None: + os.environ.pop(IDENTITY, None) + else: + os.environ[IDENTITY] = before + self.reg.env[IDENTITY] = self.nonce + self.k = None + + # ------------------------------------------------------------ the wrapper and the shim + def arm(self, arms=(), hold: dict | None = None) -> None: + """The shim's arms and the wrapper's hold, each log started afresh.""" + (self.bin / PSQL_SHIM_CONTROL).write_text( + json.dumps({"psql": self.db.psql_bin, "arms": list(arms)}), encoding="utf-8") + for name in (PSQL_SHIM_LOG, "psql-shim.ends", "git-wrapper.log"): + (self.bin / name).write_text("", encoding="utf-8") + (self.bin / "psql-shim.state").write_text("{}", encoding="utf-8") + control = {"git": self.real_git, "psql_log": str(self.bin / PSQL_SHIM_LOG)} + if hold: + control["hold"] = hold + (self.bin / "git-wrapper.json").write_text(json.dumps(control), encoding="utf-8") + + def calls(self) -> list: + return _requests(self.bin / PSQL_SHIM_LOG) + + def git_calls(self) -> list: + return [c for c in _jsonl(self.bin / "git-wrapper.log") if c.get("outcome") == "ran" + or c.get("outcome") == "held"] + + # ------------------------------------------------------------ the database + def rows(self, sql: str) -> list: + return self.imp._rows(self.db, sql) + + def switch(self) -> dict: + return self.rows("SELECT * FROM register_switch")[0] + + def head(self) -> int: + return self.rows("SELECT seq FROM register_head")[0]["seq"] + + def journal(self) -> list: + return [[r["seq"], r["kind"], r["operator"]] + for r in self.rows("SELECT seq, kind, operator FROM journal ORDER BY seq")] + + def count(self) -> int: + return self.rows("SELECT count(*) AS n FROM journal")[0]["n"] + + def mirror(self) -> dict: + return self.rows("SELECT * FROM mirror_state")[0] + + def state(self) -> dict: + return {"switch": self.switch(), "head": self.head(), "journal": self.journal()} + + # ------------------------------------------------------------ origin + def store_on_origin(self) -> bool: + return "lanes/STORE" in self.reg.origin_git("ls-tree", "-r", "--name-only", + "refs/heads/main", "lanes/").split() + + def origin_seqs(self) -> list: + """Every `Register-Seq` on origin's `main`, oldest first.""" + out = self.reg.origin_git("log", "--reverse", "--format=%B%x00", "refs/heads/main") + return [int(s) for body in out.split("\0") for s in REGISTER_SEQ.findall(body)] + + # ------------------------------------------------------------ the commands + def prepare(self) -> None: + """The cutover, then `writes` writes on primary from ws1, each + rendered: `k` is the head. The operator lane's `<c>` is made after + the cutover's push from W, before the first write.""" + proc = self.reg.cutover() + assert proc.returncode == 0, f"the cutover (T116) failed:\n{_said(proc)}" + switch = self.switch() + assert (switch["mode"], switch["marker_state"]) == ("primary", "present"), ( + f"after the cutover the switch reads {switch['mode']} with the marker " + f"{switch['marker_state']}: the marker's push, read-back and record_marker are lane " + f"3's T327, so test 8's estate fails until it lands") + self.c = _lane_checkout(self.reg.origin, self.reg.ws, self.imp.OPERATOR, self.reg.env) + for n in range(1, self.writes + 1): + proc = self.reg.write(f"test 8: write {n}") + assert proc.returncode == 0, ( + f"write {n} on primary from ws1 failed (lane 4's T415 and T416):\n{_said(proc)}") + self.k = self.head() + assert self.reg.wait_for_seq(self.k), ( + f"no mirror commit carries Register-Seq: {self.k} (lane 3's T321 to T323): " + f"{self.reg.seqs_on_origin()}") + self.arm() + + def rollback(self, conf: Path | None = None, env: dict | None = None, + timeout: float = 300) -> subprocess.CompletedProcess: + """`lanes-index rollback` from ws1, as the operator lane, with ws1's + `mode=primary` configuration.""" + return self.reg.index("rollback", conf=conf or self.reg.primary_conf, env=env, + timeout=timeout) + + def popen_rollback(self) -> subprocess.Popen: + return self.reg.popen("rollback", conf=self.reg.primary_conf) + + def outage_file(self) -> Path: + return self.reg.primary_conf.parent / OUTAGE_FILE + + +def _estate(request, tmp_path: Path, *, stoppable: bool = False, prepare: bool = True): + """A `RollbackEstate` on a database of its own: the session cluster's, + or a `stoppable_cluster`'s where the case stops the database. The + database is dropped at the case's end.""" + cluster = request.getfixturevalue("stoppable_cluster" if stoppable else "pg_cluster") + name = cluster.new_database() + request.addfinalizer(lambda: cluster.drop_database(name) if cluster.ready() else None) + estate = RollbackEstate(tmp_path / "estate", Database(cluster, name)) + estate.cluster = cluster + if prepare: + estate.prepare() + return estate + + +def _origin_blob(reg, rev: str, path: str) -> bytes: + """`path` at `rev` in the bare origin, as bytes.""" + proc = subprocess.run(["git", f"--git-dir={reg.origin}", "show", f"{rev}:{path}"], + capture_output=True, env=reg.env, check=True, stdin=subprocess.DEVNULL) + return proc.stdout + + +def _assert_rolled_back(estate: RollbackEstate, proc) -> None: + """TEST 8 (a)'S ORACLE (TP:1638-1647): exit 0; the switch at `files` with + the marker `absent`; origin's last commit removes `lanes/STORE` and + carries the rollback entry's seq, `k+1`, the journal's last; and origin's + rendered paths equal a full render from SQL, byte for byte.""" + imp, reg = estate.imp, estate.reg + assert proc.returncode == 0, f"the rollback did not end 0:\n{_said(proc)}" + switch = estate.switch() + assert (switch["mode"], switch["marker_state"]) == ("files", "absent"), ( + f"the switch is {switch['mode']}/{switch['marker_state']}, not files/absent after " + f"record_marker confirmed the removal") + journal = estate.journal() + last = journal[-1] + assert last[1:] == ["rollback", True], f"the journal's last entry is {last}: {journal}" + tip = reg.origin_tip() + assert REGISTER_SEQ.findall(reg.origin_git("log", "-1", "--format=%B", tip)) == [str(last[0])], ( + f"origin's last commit does not carry Register-Seq: {last[0]}") + changed = reg.origin_git("diff-tree", "--no-commit-id", "--name-status", "-r", f"{tip}^", tip) + assert changed.split("\n") == ["D\tlanes/STORE", ""], ( + f"origin's last commit does not remove lanes/STORE alone: {changed!r}") + on_origin = {p: _origin_blob(reg, tip, p) + for p in reg.origin_git("ls-tree", "-r", "--name-only", tip, "lanes/").split() + if imp.RENDER_SET.match(p)} + from_sql = {p: b for p, b in imp._renders(estate.db).items() if imp.RENDER_SET.match(p)} + assert on_origin == from_sql, ( + f"origin's rendered paths differ from a full render from SQL: " + f"{sorted(set(on_origin) ^ set(from_sql))} or " + f"{sorted(p for p in on_origin if p in from_sql and on_origin[p] != from_sql[p])}") + + +# ------------------------------------------------------------------ (a), (b) +def test_rollback_leaves_files_byte_identical_marker_gone_and_sql_writes_refused(request, + tmp_path): + """Test 8 (a) (TP:1549-1550, :1638-1647): the rollback with the database + up, then a `mode=primary` write from ws1 exits 69, and `set-mode index` + on ws1, as Brett runs it at the rollback's step 5 (operations.md 2.3), + leaves ws1's configuration without `mode=primary`. Fails until T326, + T327, T321 to T323, T415 and T416.""" + estate = _estate(request, tmp_path) + proc = estate.rollback() + _assert_rolled_back(estate, proc) + count = estate.count() + wrote = estate.reg.write("test 8 (a): a write after the rollback") + assert wrote.returncode == 69, f"a mode=primary write after the rollback is not 69:\n{_said(wrote)}" + assert estate.count() == count, "the refused write journaled" + mode = estate.reg.index("set-mode", "index", conf=estate.reg.primary_conf) + assert mode.returncode == 0, f"set-mode index on ws1:\n{_said(mode)}" + lines = estate.reg.primary_conf.read_text(encoding="utf-8").splitlines() + assert "mode=primary" not in lines, f"ws1's configuration still says mode=primary: {lines}" + + +def test_rollback_with_the_database_stopped_is_refused_and_changes_neither_switch_nor_marker( + request, tmp_path): + """Test 8 (b) (TP:1551-1552, :1648-1655): with the database stopped + (`stoppable_cluster`), the rollback exits 69 and stops at its step 1; + after the restart the switch still reads `primary` with the marker + `present`, `lanes/STORE` is still on origin, ws1 is still + `mode=primary`, and no `register-outage` is beside ws1's configuration. + Fails until T327, T321 to T323, T415 and T416 (its estate).""" + estate = _estate(request, tmp_path, stoppable=True) + before = estate.switch() + estate.cluster.stop() + try: + proc = estate.rollback() + finally: + estate.cluster.start_again() + assert proc.returncode == 69, f"a rollback with the database stopped is not 69:\n{_said(proc)}" + assert not any(STEP_1_MARK in c.get("sent", "") for c in estate.calls()), ( + "a step-1 call was sent with the database stopped") + after = estate.switch() + assert (after["mode"], after["marker_state"]) == ("primary", "present"), after + assert after == before, f"the switch moved: {before} -> {after}" + assert estate.store_on_origin(), "lanes/STORE is no longer on origin" + assert "mode=primary" in estate.reg.primary_conf.read_text(encoding="utf-8").splitlines() + assert not estate.outage_file().exists(), "a rollback refused at its step 1 declared" + + +# ------------------------------------------------------------------ (c), (e) and the claim +def _missed_failures(estate: RollbackEstate, ws2: MissedWorkstation, verb: str, *, + no_fetch: bool, writer=None) -> list: + """TEST 8 (c)'S ORACLE (TP:1648-1667), as a list of what fails, empty + where it holds: the writer exits 69 with AT-3's line (`commit`: 2, with + nothing reaching SQL or `lanes/`); the journal's count is unchanged; and + ws2's HEAD, index, last-fetched tip and files under `lanes/` are + unchanged. `writer` stands in for ws2's `lanes-edit.sh` (case (e)).""" + edited = verb == "commit" and ws2.hand_edit() + try: + before, count = ws2.snapshot(), estate.count() + env = {"LANES_NO_FETCH": "1" if no_fetch else None} + proc = (writer or ws2.edit)(*_verb_args(verb), env=env) + failures = [] + want = 2 if verb == "commit" else 69 + if proc.returncode != want: + failures.append(f"{verb} exited {proc.returncode}, not {want}: {proc.stderr[-800:]}") + if verb != "commit" and AT3_LINE not in proc.stderr: + failures.append(f"{verb}'s stderr does not carry AT-3's line: {proc.stderr[-800:]}") + if estate.count() != count: + failures.append(f"{verb}: the journal's count moved from {count} to {estate.count()}") + if ws2.snapshot() != before: + failures.append(f"{verb}: ws2's HEAD, index, last-fetched tip or lanes/ files changed") + return failures + finally: + if edited: + ws2.undo_hand_edit() + + +@pytest.fixture(scope="module") +def missed_estate(pg_cluster, tmp_path_factory): + """Test 8's estate after a whole rollback, shared by (c)'s 24 ids, (e)'s + two stubs and the files-mode claim: ws2 cloned at the cutover's estate, + twice, one fetched after the rollback's push and one not. Where the + estate cannot be built or the rollback does not end 0, each case fails + with why.""" + name = pg_cluster.new_database() + shared = SimpleNamespace(problem=None) + try: + estate = RollbackEstate(tmp_path_factory.mktemp("missed"), Database(pg_cluster, name)) + estate.prepare() + ws2 = {fetch: MissedWorkstation(estate, f"ws2-{fetch}") + for fetch in ("fetched", "not-fetched")} + cached = estate.switch()["mode"] + proc = estate.rollback() + _assert_rolled_back(estate, proc) + ws2["fetched"].fetch() + shared = SimpleNamespace(problem=None, estate=estate, ws2=ws2, cached_mode=cached) + except AssertionError as exc: + shared = SimpleNamespace(problem=f"test 8's estate after a whole rollback: {exc}") + except BaseException: # any other end of the build: drop, then re-raise + pg_cluster.drop_database(name) + raise + try: + yield shared + finally: + pg_cluster.drop_database(name) + + +def _ready(shared): + if shared.problem: + pytest.fail(shared.problem[:4000], pytrace=False) + return shared + + +@pytest.mark.parametrize("case", MISSED_CASES) +def test_a_missed_primary_writer_is_refused_after_rollback(missed_estate, case): + """Test 8 (c) (TP:1553-1561, :1656-1667): once the rollback has run to + its end, ws2, whose `mode=primary` was not cleared, exits 69 for each + verb (`commit`: 2), fetched or not, with `LANES_NO_FETCH=1` or without, + and changes nothing. Fails until T326, T327, T415, T420 and T421.""" + shared = _ready(missed_estate) + fetch = "not-fetched" if "-not-fetched-" in case else "fetched" + verb = case[:case.index(f"-{fetch}-")] + failures = _missed_failures(shared.estate, shared.ws2[fetch], verb, + no_fetch=case.endswith("-no-fetch")) + assert not failures, "\n".join(failures) + + +def _leak(estate: RollbackEstate, lane: str) -> subprocess.CompletedProcess: + """A stub's write: one journal row through the real `psql`, as the admin + under `SET ROLE lanes_register_owner`, since REGISTER-WRITER has no INSERT + and `commit_write` would refuse it LR002 (TP:1609-1616).""" + return estate.db.psql( + f"SET search_path TO {estate.imp.SCHEMA};\nSET ROLE lanes_register_owner;\n" + f"INSERT INTO journal (seq, base_seq, write_id, kind, verb, lane, workstation, author, " + f"message, args_sha256) SELECT max(seq) + 1, max(seq), '{uuid.uuid4()}'::uuid, 'write', " + f"'log', '{lane}', 'Eagle', 'stub <stub@example.invalid>', 'a stub writer''s leak', " + f"'{'b' * 64}' FROM journal;\n", check=False) + + +def _stub(estate: RollbackEstate, leaks) -> callable: + """A stub writer for (e): it writes `_leak`'s row and exits 0 where + `leaks()` says so, and otherwise refuses as the product does.""" + def writer(*args, env=None): + if leaks(): + written = _leak(estate, MISSED_LANE) + assert written.returncode == 0, ( + f"the stub could not write its row, so it models no leak: {written.stderr}") + return SimpleNamespace(returncode=0, stdout="", stderr="") + return SimpleNamespace(returncode=69, stdout="", stderr=AT3_LINE + "\n") + return writer + + +def test_the_rollback_oracle_fails_on_a_last_fetched_tip_writer(missed_estate): + """Test 8 (e), the first stub (TP:1562-1564, :1668-1670, Q4(b)(i)): a + writer that refuses only when its last-fetched tip lacks `lanes/STORE` + leaks on ws2's clone that has not fetched since the rollback's push, and + (c)'s oracle reports it. Fails until (c)'s estate can be built.""" + shared = _ready(missed_estate) + ws2 = shared.ws2["not-fetched"] + stub = _stub(shared.estate, lambda: subprocess.run( + ["git", "-C", str(ws2.clone), "cat-file", "-e", "refs/remotes/origin/main:lanes/STORE"], + env=ws2.env, capture_output=True).returncode == 0) + failures = _missed_failures(shared.estate, ws2, "append-line", no_fetch=False, writer=stub) + assert failures, "test 8's oracle passed a writer that leaks on its last-fetched tip" + + +def test_the_rollback_oracle_fails_on_a_switch_reset_when_the_database_returns(missed_estate): + """Test 8 (e), the second stub (TP:1562-1564, :1668-1670, Q4(b)(ii)): a + writer that checks the switch only when it first reconnects, and so + keeps the `primary` it read before the rollback, leaks, and (c)'s oracle + reports it. Fails until (c)'s estate can be built.""" + shared = _ready(missed_estate) + stub = _stub(shared.estate, lambda: shared.cached_mode == "primary") + failures = _missed_failures(shared.estate, shared.ws2["fetched"], "claim", no_fetch=True, + writer=stub) + assert failures, "test 8's oracle passed a writer that keeps the switch it first read" + + +def _claim_holders(estate: RollbackEstate) -> set: + """The lanes holding `CLAIMED`, across SQL's live claims and the files on + origin's `main` (a lane whose log's last line on it is `CLAIMED`).""" + rows = estate.rows(f"SELECT lane FROM object_holds WHERE lower(object) = lower('{CLAIMED}') " + f"AND verb IN ('CLAIMED', 'TAKEOVER') AND superseded_by IS NULL") + held = {r["lane"] for r in rows} + reg = estate.reg + for path in reg.origin_git("ls-tree", "-r", "--name-only", "refs/heads/main", + "lanes/log/").split(): + last = None + for line in reg.origin_git("show", f"refs/heads/main:{path}").splitlines(): + if CLAIMED.lower() in line.lower(): + last = line + if last and last.startswith("CLAIMED"): + match = re.match(r"CLAIMED \S+ lane ([^,\s]+),", last) + held.add(match.group(1) if match else path) + return held + + +def test_a_files_mode_claim_after_rollback_leaves_one_holder(missed_estate): + """Test 8 (c)'s last step (TP:1666-1667): after the missed writer's + cases, a files-mode `claim` of the same object on ws1 exits 0, and the + object has exactly one holder across SQL and the files. Fails until + (c)'s estate can be built.""" + shared = _ready(missed_estate) + operator = _imp().OPERATOR + proc = shared.estate.reg.edit("claim", CLAIMED, "--no-github", env={"LANES_LANE": operator}) + assert proc.returncode == 0, f"a files-mode claim on ws1 after the rollback:\n{_said(proc)}" + assert _claim_holders(shared.estate) == {operator}, _claim_holders(shared.estate) + + +# ------------------------------------------------------------------ section 4.2: the partition +def _partitioned_conf(estate: RollbackEstate) -> Path: + """ws1's configuration naming a fresh, empty socket directory (TP:1605).""" + empty = estate.root / "empty-socket" + empty.mkdir(exist_ok=True) + live = quote(str(estate.db.host), safe="") + text = estate.reg.primary_conf.read_text(encoding="utf-8").replace( + live, quote(str(empty), safe="")) + assert text != estate.reg.primary_conf.read_text(encoding="utf-8"), ( + "ws1's configuration does not name the cluster's socket directory") + return _private(estate.root / "partitioned" / "lanes-index.conf", text) + + +def test_rollback_from_a_partitioned_clone_is_refused_and_removes_no_marker(request, tmp_path): + """Section 4.2, while partitioned (TP:7579-7584): ws1's rollback, from a + configuration naming an empty socket directory, exits 69; the switch + reads `primary`; `lanes/STORE` is still on origin's `main`; and ws2's + writes exit 0, since the estate is still primary. Fails until T327, T415, + T416 and T421.""" + estate = _estate(request, tmp_path) + ws2 = MissedWorkstation(estate, "ws2") + proc = estate.rollback(conf=_partitioned_conf(estate)) + assert proc.returncode == 69, f"the partitioned rollback is not 69:\n{_said(proc)}" + switch = estate.switch() + assert (switch["mode"], switch["marker_state"]) == ("primary", "present"), switch + assert estate.store_on_origin(), "lanes/STORE left origin's main" + for verb in ("append-line", "claim"): + wrote = ws2.edit(*_verb_args(verb)) + assert wrote.returncode == 0, f"ws2's {verb} on the still-primary estate:\n{_said(wrote)}" + + +def _assert_partitioned_refusal(refused) -> None: + """Section 4.2's first rollback, from the empty socket directory, exits 69 + (TP:7579-7584). A helper, as `_assert_rolled_back` is, so that no `assert` + stands in `partitioned_estate`'s `try`, whose `except AssertionError` + turns a failure into each case's (python:S5779). pytest rewrites this + `assert` as it rewrote the fixture's, so each case's message is unchanged; + a raised exception of the module's own would lose pytest's explanation.""" + assert refused.returncode == 69, f"the partitioned rollback:\n{_said(refused)}" + + +@pytest.fixture(scope="module") +def partitioned_estate(pg_cluster, tmp_path_factory): + """Section 4.2's estate after the partitioned rollback and the whole one: + ws1's rollback from the empty socket directory (69), then from its own + configuration to its end. ws2 cloned before, twice; one fetched after.""" + name = pg_cluster.new_database() + try: + estate = RollbackEstate(tmp_path_factory.mktemp("partition"), + Database(pg_cluster, name)) + estate.prepare() + ws2 = {fetch: MissedWorkstation(estate, f"ws2-{fetch}") + for fetch in ("fetched", "not-fetched")} + refused = estate.rollback(conf=_partitioned_conf(estate)) + _assert_partitioned_refusal(refused) + proc = estate.rollback() + _assert_rolled_back(estate, proc) + ws2["fetched"].fetch() + shared = SimpleNamespace(problem=None, estate=estate, ws2=ws2, + last=estate.journal()[-1][0]) + except AssertionError as exc: + shared = SimpleNamespace(problem=f"section 4.2's estate: {exc}") + except BaseException: # any other end of the build: drop, then re-raise + pg_cluster.drop_database(name) + raise + try: + yield shared + finally: + pg_cluster.drop_database(name) + + +@pytest.mark.parametrize("case", MISSED_CASES) +def test_a_missed_writer_is_refused_once_the_partitioned_rollback_completes(partitioned_estate, + case): + """Section 4.2, after the rollback completes (TP:7585-7590): every ws2 + case exits 69 (`commit`: 2); the journal's count no longer changes; the + files equal a full render at the rollback's last seq; and every object + has one holder. Fails until T326, T327, T415, T420 and T421.""" + shared = _ready(partitioned_estate) + fetch = "not-fetched" if "-not-fetched-" in case else "fetched" + verb = case[:case.index(f"-{fetch}-")] + failures = _missed_failures(shared.estate, shared.ws2[fetch], verb, + no_fetch=case.endswith("-no-fetch")) + assert not failures, "\n".join(failures) + assert shared.estate.journal()[-1][0] == shared.last, "the journal moved past the rollback" + live = shared.estate.rows("SELECT object, count(*) AS n FROM object_holds WHERE verb IN " + "('CLAIMED', 'TAKEOVER') AND superseded_by IS NULL AND NOT exempt " + "GROUP BY object HAVING count(*) > 1") + assert live == [], f"an object has more than one holder: {live}" + + +# ------------------------------------------------------------------ (f), (g), (h), (i) +@pytest.mark.parametrize("stray", ["rendered-path", "register-seq-above-head"]) +def test_a_rollback_finds_a_stray_not_yet_recorded_records_it_and_exits_2(request, tmp_path, + stray): + """Test 8 (f) (TP:1565-1567, :1671-1679): a stray pushed to origin with no + write after it, so `diverged_sha` is NULL when the rollback starts, is + caught by its fetch right before its transaction: it exits 2 naming + `diverged at <sha>` and S2's two ways out, records the stray's sha, and + leaves the switch, the journal, the head and `lanes/STORE` as they were. + `[rendered-path]` changes a rendered path; `[register-seq-above-head]` + changes none and carries `Register-Seq: <h+10>`. Fails until T326.""" + estate = _estate(request, tmp_path) + reg = estate.reg + other = reg.other_clone("stray") + if stray == "rendered-path": + log = "lanes/log/repoB-1.md" + sha = reg.push_from(other, log, _origin_blob(reg, "refs/heads/main", log).decode("utf-8") + + "a stray line, pushed past the renderer\n", "a stray commit") + else: + h = estate.head() + target = other / "handoffs" / "stray.md" + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text("# a stray, outside the render set\n", encoding="utf-8") + for argv in (["add", "--", "handoffs/stray.md"], + ["commit", "-q", "-m", f"a stray commit\n\nRegister-Seq: {h + 10}"], + ["push", "-q", "origin", "HEAD:main"]): + subprocess.run(["git", "-C", str(other), *argv], check=True, env=reg.env, + capture_output=True, stdin=subprocess.DEVNULL) + sha = reg.origin_tip() + assert estate.mirror()["diverged_sha"] is None, "the stray was recorded before the rollback" + before, count = estate.state(), estate.count() + proc = estate.rollback() + assert proc.returncode == 2, f"[{stray}] the rollback is not 2:\n{_said(proc)}" + assert f"diverged at {sha}" in proc.stderr, _said(proc) + for way in ("import --single", "render --revert"): + assert way in proc.stderr, f"S2's way out {way!r} is not named:\n{_said(proc)}" + assert estate.mirror()["diverged_sha"] == sha, estate.mirror() + assert estate.state() == before and estate.count() == count, "the rollback wrote" + assert estate.store_on_origin(), "lanes/STORE left origin" + + +def _holder(db, appname: str) -> subprocess.Popen: + """The held session: the fixture's superuser holding `register_head`'s row + `FOR UPDATE`, in a transaction left open (see the readings).""" + holder = db.session(appname=appname) + holder.stdin.write("BEGIN;\nSELECT seq FROM lanes_register.register_head WHERE id = 1 " + "FOR UPDATE;\n") + holder.stdin.flush() + return holder + + +def _wait_for(db, query: str, what: str, ceiling: float = 20.0) -> None: + """Poll `query`, a count, in 0.05 s steps under `ceiling` until it counts + one row or more.""" + end = time.monotonic() + ceiling + while time.monotonic() < end: + if db.psql(query).stdout.strip() not in ("", "0"): + return + time.sleep(0.05) + pytest.fail(f"{what}: not seen within {ceiling} s") + + +def _locked(db, appname: str) -> str: + return (f"SELECT count(*) FROM pg_stat_activity WHERE datname = '{db.name}' AND " + f"application_name = '{appname}' AND wait_event_type = 'Lock';") + + +def _holding(db, appname: str) -> str: + return (f"SELECT count(*) FROM pg_stat_activity WHERE datname = '{db.name}' AND " + f"application_name = '{appname}' AND state = 'idle in transaction' AND " + f"backend_xid IS NOT NULL;") + + +def _record(db, ws: str, sha: str | None, error: str | None, + schema: str = "lanes_register") -> subprocess.CompletedProcess: + """`record_mirror_state` as REGISTER-WRITER, in a session of its own.""" + lit = (lambda v: "NULL" if v is None else "'" + v.replace("'", "''") + "'") + return db.psql(f"SET ROLE {WRITER};\nSELECT {schema}.record_mirror_state({lit(ws)}, " + f"{lit(sha)}, {lit(error)});\n", check=False) + + +@pytest.mark.parametrize("case", ["recorded", "last-error-only"]) +def test_a_rollback_goes_back_to_its_check_past_a_last_error_and_refuses_a_divergence_recorded_meanwhile( + request, tmp_path, case): + """Test 8 (g) (TP:1568-1572, :1680-1692): with the held session on the + head row and the rollback's call waiting on it (`wait_event_type = + 'Lock'`), the test records with `record_mirror_state`, then ends the held + session by `ROLLBACK`; the call's `FOR SHARE` on `mirror_state` raises + 40001, and the command goes back to its check. `[recorded]`: it exits 2 + with `diverged at <sha>`, the switch, marker and journal unchanged. + `[last-error-only]`: the check finds no divergence and the retry commits + at `k+1`, the journal's last. Fails until T326 and T327.""" + estate = _estate(request, tmp_path) + db, k, sha = estate.db, estate.k, "3" * 40 + before = estate.state() + holder = proc = None + try: # both owned to the end (`_teardown`) + holder = _holder(db, "t273-g-holder") + _wait_for(db, _holding(db, "t273-g-holder"), "the held session's lock on the head row") + proc = estate.popen_rollback() + _wait_for(db, _locked(db, "lanes-index"), "the rollback's call waiting on the head row") + recorded = _record(db, "ws-t273-g", sha if case == "recorded" else None, + None if case == "recorded" else "the push was refused") + assert recorded.returncode == 0, recorded.stderr + holder.communicate(input="ROLLBACK;\n", timeout=60) + out, err = proc.communicate(timeout=300) + finally: + _teardown(proc, holder, estate=estate) + ended = f"exit {proc.returncode}\n--- stdout ---\n{out}\n--- stderr ---\n{err}" + assert "40001" in err and "lost its turn" in err, f"[{case}] no 40001 sent it back:\n{ended}" + if case == "recorded": + assert proc.returncode == 2 and f"diverged at {sha}" in err, ended + assert estate.state() == before, "the refused rollback moved the switch or the journal" + else: + switch, journal = estate.switch(), estate.journal() + assert switch["mode"] == "files", f"the retry did not commit:\n{ended}" + assert journal[-1] == [k + 1, "rollback", True], journal + assert switch["marker_state"] == "removing" or ( + switch["marker_state"] == "absent" and proc.returncode == 0), ended + + +def _between(calls: list, git_calls: list, sub: str = "fetch") -> list: + """For each two step-1 calls in `calls` (the shim's or the fake's + requests), whether a read came between them, and whether a `git <sub>` + naming `origin` started between them.""" + steps = [n for n, c in enumerate(calls) if STEP_1_MARK in c.get("sent", c.get("stdin", ""))] + found = [] + for a, b in zip(steps, steps[1:]): + read = any(READ_MARK in calls[n].get("sent", calls[n].get("stdin", "")) + for n in range(a + 1, b)) + fetch = any(g["sub"] == sub and "origin" in g["argv"] and a + 1 <= g["psql_before"] <= b + for g in git_calls) + found.append((read, fetch)) + return found + + +def test_a_rollback_retries_a_lost_turn_on_a_fresh_k_through_its_check(request, tmp_path): + """Test 8 (h), RE (TP:1573-1576, :1693-1699): the shim holds the + rollback's step-1 call for a window, and ws2 commits one write in it. + The call gets LR001, the rollback reads the head afresh, runs its check + again and commits on the new head: its entry is seq `k+2`, the journal's + last; the shim's log shows two step-1 calls with a head read between + them, and the wrapper's a fetch of `origin main` between them. Fails + until T326, T327, T415 and T416.""" + estate = _estate(request, tmp_path) + ws2 = MissedWorkstation(estate, "ws2") + k = estate.k + estate.arm([{"mode": "window", "match": "commit_write", "call": 1, "ms": 8000}]) + proc = None + try: # owned to the end (`_teardown`) + proc = estate.popen_rollback() + end = time.monotonic() + 60 + while not any(STEP_1_MARK in c.get("sent", "") for c in estate.calls()): + assert proc.poll() is None and time.monotonic() < end, ( + f"the rollback sent no step-1 call: {proc.poll()}") + time.sleep(0.05) + wrote = ws2.edit("log", "NOTED", f"lane:{MISSED_LANE}", "test 8 (h): in the window") + out, err = proc.communicate(timeout=300) + finally: + _teardown(proc, estate=estate) + ended = f"exit {proc.returncode}\n--- stdout ---\n{out}\n--- stderr ---\n{err}" + assert wrote.returncode == 0, f"ws2's write in the window:\n{_said(wrote)}" + assert "LR001" in err, f"the step-1 call did not get LR001:\n{ended}" + journal = estate.journal() + assert journal[-2:] == [[k + 1, "write", False], [k + 2, "rollback", True]], ( + f"the rollback's entry is not k+2 = {k + 2} after ws2's write: {journal}\n{ended}") + between = _between(estate.calls(), estate.git_calls()) + assert between and between[0] == (True, True), ( + f"two step-1 calls with a head read and a fetch of origin main between them: {between}") + + +#: The rollback's read as the fake answers it (FP): `_ROLLBACK_READS`' six +#: SELECTs, each a COPY's rows then the marker line: the window, the switch at +#: `primary` with the marker `present`, the head 1, the cutover's entry at it, +#: no divergence, and the database's clock. +NEXT = "\x1eLANES-INDEX-NEXT" + + +def _canned_read(version: int) -> str: + rows = [f"{version}\t{version}\t{version}", + f"primary\tpresent\t1\t{uuid.uuid4()}\t1", "1", f"cutover\t{uuid.uuid4()}", + "\\N\t\\N\t\\N", f"{time.time():.3f}"] + return "".join(f"{row}\n{NEXT}\n" for row in rows) + + +#: STEP 0'S GIT HALF AS THE FAKE ANSWERS IT (FP; lane 3's #165 6813528630, a +#: SHOULD from T326's builder). Right before step 1, T326 fetches `origin +#: main` and checks it as T322 recognises a divergence (B15 tasks:1546, "Step +#: 0's git half"). That makes two reads the rollback's own does not, each +#: answered by its own rule, placed before `READ_MARK`'s: +#: - T322's head read, after the fetch (`_render_read_head`, +#: `4353eb08:lanes-index:15025`): four SELECTs, the window, the head with +#: the switch, the resolved strays, and `mirror_state mir`'s `diverged_sha` +#: and `last_error`. That last SELECT holds `READ_MARK` too, so without a +#: rule of its own the fake gave it the rollback read's six answers, and +#: the head read failed: 69. Since T326's `01cd35c` the second SELECT also +#: reads the switch's `marker_state`, and any answer but those three fields +#: is refused (`ed8e7d2:lanes-index:14995`, `:15020-15023`; lane 3's #165 +#: 6814531692, a SHOULD from T326's fixer); +#: - T301's image read at `m` (`register_render_queries`, `:2265`): five +#: SELECTs, which T322's image half replays and compares with the render +#: set at the commit carrying `m` (`render_pass`, `:15377-15398`). No rule +#: matched it, so the fake answered nothing: 69. +#: Each mark is a text of that request alone among the case's requests. +HEAD_READ_MARK, IMAGE_READ_MARK = "FROM mirror_state mir", "FROM journal_files f" + + +def _copy_field(value) -> str: + """One field as `COPY ... TO STDOUT` writes it in TEXT format, which + `_pg_unescape` reads back: `\\N` for NULL, `t` or `f` for a boolean, and + a backslash, a tab, an LF or a CR escaped.""" + if value is None: + return "\\N" + if isinstance(value, bool): + return "t" if value else "f" + return (str(value).replace("\\", "\\\\").replace("\t", "\\t").replace("\n", "\\n") + .replace("\r", "\\r")) + + +def _copy_answer(selects: list) -> str: + """The fake's stdout for one request of SELECTs, as `_query_many` reads + it: each SELECT's rows, one line each, then the marker line.""" + return "".join("".join("\t".join(_copy_field(field) for field in row) + "\n" + for row in rows) + f"{NEXT}\n" for rows in selects) + + +def _canned_head_read(version: int) -> str: + """T322's head read as the fake answers it, from the same canned register + as `_canned_read`: the window, the head 1 with the switch at `primary` + and the marker `present` (T326's three fields), no resolved stray, and + neither a divergence nor a `last_error`.""" + return _copy_answer([[(version, version, version)], [(1, "primary", "present")], [], + [(None, None)]]) + + +def _image_lines(data: bytes) -> tuple: + """A file's lines, and whether it ends with an LF, as T301's + `register_image_bytes` joins them back into `data`.""" + text = data.decode("utf-8") + if not text: + return [], True + final = text.endswith("\n") + return (text[:-1] if final else text).split("\n"), final + + +def _canned_images(version: int, rendered: dict, store: bytes) -> str: + """T301's image read at seq 1 as the fake answers it: the import at 0, + whose `create` and `append` edits rebuild `rendered`, the render set at + the commit carrying `Register-Seq: 1` (`{path: bytes}`), each path proved + by its `journal_files` row; then the cutover's entry at 1, which adds + `lanes/STORE`, outside the render set. So the images at `m` are the + render set there, and T322's image half finds no divergence.""" + edits, files = [], [] + for seq, paths in ((0, rendered), (1, {"lanes/STORE": store})): + ordinal = 0 + for path in sorted(paths): + lines, final = _image_lines(paths[path]) + ordinal += 1 + edits.append((seq, ordinal, "create", path, None, None, None, None)) + for number, line in enumerate(lines, 1): + ordinal += 1 + edits.append((seq, ordinal, "append", path, number, None, line, None)) + files.append((seq, path, True, hashlib.sha256(paths[path]).hexdigest(), final)) + return _copy_answer([[(version, version, version)], [(1, 0)], + [(0, "import"), (1, "cutover")], edits, files]) + + +#: T124'S MODULE (tasks:2850 to :2854; FR-064), which T203's flipped copy has +#: beside it once T124 lands: `lanes-index` is then a launcher, and the module +#: holds `REGISTER_SCHEMA_VERSION`. Before T124 the copy holds it itself. The +#: name is lane 1's, `LANES_INDEX_MODULE` in `sql_register_helpers` at its +#: T124 prototype's 11b56a1f, which line R does not have (T273j). +LANES_INDEX_MODULE = "lanes_index_main.py" + + +@pytest.mark.parametrize("code", ["40001", "40P01", "55P03", "LR001"]) +def test_a_rollback_goes_back_to_its_check_on_each_lost_turn_code(tmp_path, code): + """Test 8 (h), FP (TP:1700-1706): the register's fake `psql` answers the + rollback's reads, and step 0's git half's two, T322's head read and + T301's image read (`HEAD_READ_MARK`, `IMAGE_READ_MARK`), from a canned + register whose images at seq 1 are the workspace's render set there, and + every step-1 call with exit 3 and `ERROR: <code>: <message>`, and + `LANES_REGISTER_DEADLINE_S=6` ends the tries: the fake's log shows two + step-1 calls or more, each after the first preceded by a head read, and + the wrapper's a fetch of `origin main` between each two; the exit is 75 + (AT-D9's row holds its bound). Runs by T203's flipped copy, on a files + workspace whose origin carries the cutover's `lanes/STORE` at + `Register-Seq: 1`, the canned head. Needs no engine; fails until T326, + at its own assertion.""" + imp = _imp() + ws = imp.Workspace(tmp_path / "w", imp.SEED) + cutover = ws.commit({"lanes/STORE": "store=primary\ndatabase=register-test\n"}, + "LANES(repoA-2@Eagle): cutover\n\nRegister-Seq: 1") + copy = imp.flipped_indexer(tmp_path / "flip") + module = copy.with_name(LANES_INDEX_MODULE) + version = int(re.search(r"^REGISTER_SCHEMA_VERSION = ([0-9]+)$", + (module if module.is_file() else copy).read_text(encoding="utf-8"), + re.M).group(1)) + bin_ = tmp_path / "bin" + _script(bin_ / "psql", REGISTER_FAKE_PSQL) + _script(bin_ / "git", GIT_WRAPPER) + log, answers = tmp_path / "psql.log", tmp_path / "answers.json" + answers.write_text(json.dumps([ + {"match": HEAD_READ_MARK, "stdout": _canned_head_read(version)}, + {"match": IMAGE_READ_MARK, "stdout": _canned_images( + version, ws.rendered(cutover), ws.blob(cutover, "lanes/STORE"))}, + {"match": READ_MARK, "stdout": _canned_read(version)}, + {"match": "commit_write", "exit": 3, + "stderr": f"ERROR: {code}: the test's lost turn ({code})\n"}]), encoding="utf-8") + (bin_ / "git-wrapper.json").write_text(json.dumps({"git": _real_git(), "psql_log": str(log)}), + encoding="utf-8") + passfile = _private(tmp_path / "secret" / "pgpass", + "127.0.0.1:55432:register_db:t273:not-a-secret\n") + url = "postgresql://t273@127.0.0.1:55432/register_db" + conf = _private(tmp_path / "conf" / "lanes-index.conf", "\n".join([ + "mode=primary", f"register_url={url}", f"register_passfile={passfile}", + f"reader_url={url}", f"reader_passfile={passfile}", "register_label=register-test", + ""])) + env = dict(ws.env, LANES_INDEX_CONFIG=str(conf), LANES_LANE=imp.OPERATOR, + LANES_REGISTER_DEADLINE_S="6", FAKE_PSQL_LOG=str(log), + FAKE_PSQL_ANSWERS=str(answers), LANES_EDIT=str(copy.parent / "lanes-edit.sh"), + PATH=f"{bin_}{os.pathsep}{ws.env['PATH']}") + proc = subprocess.run([sys.executable, str(copy), "rollback"], capture_output=True, + text=True, env=env, cwd=str(ws.wip), timeout=120, + stdin=subprocess.DEVNULL) + calls = _requests(log) + steps = [c for c in calls if STEP_1_MARK in c.get("stdin", "")] + assert proc.returncode == EXIT_BUSY, ( + f"[{code}] the tries did not end 75 at the deadline ({len(steps)} step-1 calls):\n" + f"{_said(proc)}") + assert len(steps) >= 2, f"[{code}] fewer than two step-1 calls: {len(steps)}" + between = _between(calls, [g for g in _jsonl(bin_ / "git-wrapper.log")]) + assert between and all(pair == (True, True) for pair in between), ( + f"[{code}] each two step-1 calls have a head read and a fetch of origin main " + f"between them: {between}") + + +def test_a_write_that_committed_before_the_rollback_is_found_by_its_rerun_after_it(request, + tmp_path): + """Test 8 (i) (TP:1577-1579, :1707-1716): ws2's write is lost after it + lands (the shim's `no-reconnect` as `after` on its commit call), so ws2 + exits 3 with its pending record; the rollback then runs to its end from + ws1; with the shim disarmed, the printed rerun on ws2 exits 0, not 69, + the journal holds one entry for its id, and ws2's next new write exits + 69. Fails until T326, T327, T415, T416, T417 and T420.""" + estate = _estate(request, tmp_path) + ws2 = MissedWorkstation(estate, "ws2") + ws2.arm([{"mode": "no-reconnect", "as": "after", "match": "commit_write", "call": 1}]) + lost = ws2.edit("log", "NOTED", f"lane:{MISSED_LANE}", "test 8 (i): lost after it lands") + assert lost.returncode == 3, f"ws2's lost write is not in doubt (3):\n{_said(lost)}" + rerun = re.search(r"LANES_WRITE_ID=([0-9a-f-]{36})", lost.stderr) + assert rerun, f"ws2 printed no rerun under the same id:\n{_said(lost)}" + write_id = rerun.group(1) + generation = re.search(r"LANES_WRITE_GENERATION=([0-9a-f-]{36})", lost.stderr) + rerun_env = {"LANES_WRITE_ID": write_id} + if generation: + rerun_env["LANES_WRITE_GENERATION"] = generation.group(1) + proc = estate.rollback() + _assert_rolled_back(estate, proc) + ws2.arm([]) + count = estate.count() + again = ws2.edit("log", "NOTED", f"lane:{MISSED_LANE}", "test 8 (i): lost after it lands", + env=rerun_env) + assert again.returncode == 0, f"the rerun is not 0 (the write id first, S1):\n{_said(again)}" + assert estate.count() == count, "the rerun journaled" + assert estate.rows(f"SELECT count(*) AS n FROM journal WHERE write_id = '{write_id}'") == \ + [{"n": 1}] + fresh = ws2.edit("log", "NOTED", f"lane:{MISSED_LANE}", "test 8 (i): a new write") + assert fresh.returncode == 69, f"ws2's next new write is not 69:\n{_said(fresh)}" + + +# ------------------------------------------------------------------ AT-F1 +def test_rollback_refuses_to_start_while_the_mirror_is_diverged(request, tmp_path): + """AT-F1, diverged (TP:5456-5459): test 6's diverged estate, a stray + commit on origin that a write's render recorded; `rollback` exits 2 + before step 1, naming the divergence and S2's two tools, and the switch + reads `primary` with the marker `present`, the journal and head unchanged, + and `lanes/STORE` still on origin. Fails until T322, T326 and T327.""" + estate = _estate(request, tmp_path) + reg = estate.reg + log = "lanes/log/repoB-1.md" + sha = reg.push_from(reg.other_clone("stray"), log, _origin_blob( + reg, "refs/heads/main", log).decode("utf-8") + "a stray line\n", "a stray commit") + wrote = reg.write("AT-F1: a write after the stray") + assert wrote.returncode == 0, _said(wrote) + deadline = time.monotonic() + 60 + while estate.mirror()["diverged_sha"] is None and time.monotonic() < deadline: + time.sleep(0.5) + assert estate.mirror()["diverged_sha"] == sha, ( + f"the render did not record the stray (T322): {estate.mirror()}") + estate.arm() + before = estate.state() + proc = estate.rollback() + assert proc.returncode == 2 and f"diverged at {sha}" in proc.stderr, _said(proc) + for way in ("import --single", "render --revert"): + assert way in proc.stderr, _said(proc) + assert not any(STEP_1_MARK in c.get("sent", "") for c in estate.calls()), "step 1 was sent" + assert estate.state() == before, "the refused rollback moved the switch, journal or head" + assert estate.store_on_origin() + + +def _held_at_push(estate: RollbackEstate): + """The rollback from ws1, held by the wrapper at its push: (the process, + the FIFO's write end), which the caller then owns, with the FIFO, to the + end of its outer `finally` (`_teardown`); or a failure where it ends + first. Until it returns it owns them itself: on any end before then, or + where the push is never held, it tears down all it made (`_teardown`: + a push held meanwhile killed, the rollback killed and reaped, the FIFO + let go and unlinked) before the failure goes on, and it fails with what + the rollback said (lane 3's Codex review of code PR 97 at `6d479418`, + SHOULDs 1 and 2; lane 3's check v97, SHOULD 4; lane 2's RV7-30, N6).""" + fifo = estate.root / "push.fifo" + if not fifo.exists(): + os.mkfifo(str(fifo), 0o600) + proc = fd = None + try: + estate.arm(hold={"call": "push", "fifo": str(fifo)}) + proc = estate.popen_rollback() + fd = _open_when_held(fifo, proc, 300) + except BaseException: + _teardown(proc, estate=estate, fifo=fifo, fd=fd) + raise + if fd is None: + ((out, err),) = _teardown(proc, estate=estate, fifo=fifo) + pytest.fail(f"the rollback never reached its push: exit {proc.returncode}\n{out}\n{err}") + return proc, fd + + +def _write_entry_now(estate: RollbackEstate, text: str) -> dict: + """A write appending `text` to `lanes/LANES.md` as SQL renders it now.""" + old = estate.imp._renders(estate.db)["lanes/LANES.md"] + new = old + text.encode("utf-8") + b"\n" + return {"journal": {"kind": "write", "verb": "log", "lane": _imp().OPERATOR, + "workstation": "Eagle", "author": AUTHOR, "message": "AT-F1: meanwhile", + "args_sha256": ARGS_SHA256}, + "not_after": NOT_AFTER, + "edits": [{"ord": 1, "op": "append", "path": "lanes/LANES.md", "new_text": text}], + "files": [{"path": "lanes/LANES.md", "present": True, + "sha256": hashlib.sha256(new).hexdigest(), "final_newline": True}]} + + +def test_the_marker_removal_entry_is_written_with_the_switch_in_step_1(request, tmp_path): + """AT-F1, the removal entry (TP:5460-5466): while the rollback is held at + its push, one snapshot shows the switch at `files` with the marker + `removing` and the removal entry, an operator entry, as the journal's + last seq `k+1`: both or neither; a write tried meanwhile fails LR002 and + journals nothing; on release the rollback ends with test 8 (a)'s oracle. + Fails until T326 and T327.""" + estate = _estate(request, tmp_path) + k = estate.k + fifo = estate.root / "push.fifo" + proc, fd = _held_at_push(estate) + try: + seen = estate.rows( + "SELECT s.mode, s.marker_state, h.seq AS head, j.kind, j.operator FROM " + "register_switch s, register_head h JOIN journal j ON j.seq = h.seq")[0] + count = estate.count() + entry = json.dumps(_write_entry_now(estate, "AT-F1: a write meanwhile")).replace( + "'", "''") + gen = estate.switch()["generation"] + version = estate.rows("SELECT version FROM schema_version")[0]["version"] + tried = estate.db.psql( + f"\\set VERBOSITY verbose\nSET search_path TO lanes_register;\n" + f"SET ROLE {WRITER};\n" + f"BEGIN ISOLATION LEVEL SERIALIZABLE;\nSELECT commit_write({estate.head()}, " + f"'{uuid.uuid4()}'::uuid, {version}, '{gen}'::uuid, '{entry}'::jsonb);\nCOMMIT;\n", + check=False) + counted = estate.count() + end, fd = fd, None + _let_go(fifo, end) # the push released: its FIFO unlinked, then the write end closed + out, err = proc.communicate(timeout=300) + finally: + # The rollback owned to the end (lane 2's RV7-30, S2; lane 3's Codex + # review of code PR 97 at `6d479418`, SHOULD 2): where anything above + # failed, the held push and the rollback are killed, the FIFO let go + # and unlinked, and both reaped or seen gone, bounded (`_teardown`). + _teardown(proc, estate=estate, fifo=fifo, fd=fd) + assert seen == {"mode": "files", "marker_state": "removing", "head": k + 1, + "kind": "rollback", "operator": True}, f"one snapshot read {seen}" + assert tried.returncode != 0 and "LR002" in tried.stderr, ( + f"a write while the marker is removing is not LR002: {tried.stderr}") + assert counted == count, "the refused write journaled" + _assert_rolled_back(estate, SimpleNamespace(returncode=proc.returncode, stdout=out, + stderr=err)) + + +def test_a_rollback_rerun_resumes_after_its_own_entry(request, tmp_path): + """AT-F1, the rerun (TP:5467-5469): a rerun after a kill at the push + finds the marker `removing` and its own entry as the last seq, declares + first, and goes on from the render: it ends with test 8 (a)'s oracle, no + entry past `k+1`, and the declaration beside ws1's configuration. Fails + until T326 and T327.""" + estate = _estate(request, tmp_path) + k = estate.k + proc, fd = _held_at_push(estate) + # The kill at the push is the teardown itself, with nothing between it + # and `_held_at_push`, which owns all until it returns: the rollback and + # the held push with its git, each stopped, then killed through a pidfd + # pinned to its start token, the rollback by its pid too, so the push + # never runs; then the FIFO is let go with an abort and unlinked, the + # rollback reaped and the push seen gone, every wait bounded (lane 3's + # Codex reviews of code PR 97 at `6d479418`, SHOULD 2, and at + # `18529e5a`, BLOCKING). + _teardown(proc, estate=estate, fifo=estate.root / "push.fifo", fd=fd) + switch = estate.switch() + assert (switch["marker_state"], estate.journal()[-1]) == ("removing", [k + 1, "rollback", True]) + first = estate.outage_file() + if first.exists(): + os.replace(str(first), str(first.with_name(OUTAGE_FILE + ".first-run"))) + estate.arm() + again = estate.rollback() + assert "stands" in again.stdout and "step 2" in again.stdout, _said(again) + _assert_rolled_back(estate, again) + assert estate.journal()[-1][0] == k + 1, "the rerun wrote an entry of its own" + assert estate.outage_file().exists(), "the rerun did not declare first" + + +def test_a_rerun_after_an_unconfirmed_removal_and_a_files_mode_write_ends_0_with_the_marker_absent( + pg, tmp_path): + """AT-F2, "Unconfirmed", the rollback's removal push (B15 TP:5563-5566), with + ops:338's files-mode write between the 3 and the rerun (lane 3's #165 + 6814260122: T326's review, MUST-1, and its probe). On AT-F2's fixture, + after a clean cutover and `rollback --hold-marker`, the removal is pushed + and the read-back's fetch fails: `rollback` exits 3, the marker stays + `removing`, and origin's tip is the removal, with `lanes/STORE` gone and + `Register-Seq: k+1`. With the marker gone from origin, a files-mode write + lands on it (ops:338, "after it, a files-mode write lands"), a commit of + `lanes/LANES.md` from another clone, as the probe makes it. The rerun + reads origin back first (ops:340; B15 tasks:1549), finds its removal, and + ends 0: the switch reads `files` with the marker `absent`, it pushes + nothing, the write stays origin's tip, and no divergence is recorded. + Fails until T326's fix round, and T327 for the cutover's marker.""" + cut = _cut() + f2 = cut.F2Register(tmp_path / "e", pg) + reg, imp = f2.reg, f2.imp + cutover = reg.cutover(conf=f2.conf) + assert cutover.returncode == 0, f"[cutover] `cutover --import <C>` (T116):\n{_said(cutover)}" + switch = imp._switch(pg) + assert switch["marker_state"] == "present", ( + f"[cutover] the marker reads {switch['marker_state']}: the cutover's push, its read-back " + f"and record_marker are lane 3's T327") + k = imp._head(pg) + held = reg.index("rollback", "--hold-marker", conf=f2.conf) + assert held.returncode == 0, f"[hold-marker] `rollback --hold-marker` (T326):\n{_said(held)}" + f2.arm({"call": "fetch", "mode": "fail", "after_push": True}) + proc = reg.index("rollback", conf=f2.conf) + assert proc.returncode == EXIT_IN_DOUBT, ( + f"[3] the removal pushed, its read-back's fetch failed: not in doubt (T326):\n" + f"{_said(proc)}") + switch = imp._switch(pg) + assert (switch["mode"], switch["marker_state"]) == ("files", "removing"), f"[3] {switch}" + removal = reg.origin_tip() + assert REGISTER_SEQ.findall(reg.origin_git("log", "-1", "--format=%B", removal)) == [ + str(k + 1)], f"[3] origin's tip {removal} does not carry Register-Seq: {k + 1}" + assert "lanes/STORE" not in reg.origin_git("ls-tree", "-r", "--name-only", removal, + "lanes/"), "[3] the removal is not on origin" + f2.arm() + clone = reg.other_clone("files-mode") + path, line = "lanes/LANES.md", "a files-mode line, after the removal (ops:338)" + text = (clone / path).read_text(encoding="utf-8") + line + "\n" + wrote = reg.push_from(clone, path, text, "LANES(repoA-2@Raven): a files-mode write") + assert wrote != removal, "[files-mode write] it did not land on origin" + f2.arm() + rerun = reg.index("rollback", conf=f2.conf) + assert rerun.returncode == 0, ( + f"[rerun] after the 3 and a files-mode write, the rerun did not end 0: it reads origin " + f"back first and finds its removal (T326's fix round, MUST-1):\n{_said(rerun)}") + calls = f2.calls() + assert cut._first_reach(calls) == "fetch", f"[rerun] it reached origin first by: {calls}" + assert not any(c["sub"] == "push" for c in calls), "[rerun] the rerun pushed again" + switch = imp._switch(pg) + assert (switch["mode"], switch["marker_state"]) == ("files", "absent"), f"[rerun] {switch}" + assert reg.origin_tip() == wrote, "[rerun] the files-mode write is no longer origin's tip" + assert line in reg.origin_git("show", f"{wrote}:{path}"), "[rerun] the write's line is gone" + mirror = imp._rows(pg, "SELECT diverged_sha FROM mirror_state")[0] + assert mirror["diverged_sha"] is None, ( + f"[rerun] the files-mode write was recorded as a divergence: {mirror}") + + +def test_a_reimport_after_a_rollback_continues_the_journal(request, tmp_path): + """AT-F1, the re-import (TP:5470-5472): after the rollback, a re-import's + baseline takes `k+2` with base `k+1`, and a later cutover takes `k+3`, so + no `Register-Seq` repeats on `main`. Fails until T326 and T327.""" + estate = _estate(request, tmp_path) + reg, k = estate.reg, estate.k + _assert_rolled_back(estate, estate.rollback()) + reg.git("fetch", "-q", "origin") + tip = reg.origin_tip() + imported = reg.import_at(estate.db, tip, config=reg.index_conf) + assert imported.returncode == 0, _said(imported) + rows = estate.rows(f"SELECT seq, base_seq, kind FROM journal WHERE seq > {k + 1} ORDER BY seq") + assert rows == [{"seq": k + 2, "base_seq": k + 1, "kind": "import"}], rows + cut = reg.index("cutover", "--import", tip) + assert cut.returncode == 0, _said(cut) + assert estate.journal()[-1][:2] == [k + 3, "cutover"], estate.journal() + seqs = estate.origin_seqs() + assert len(seqs) == len(set(seqs)), f"a Register-Seq repeats on main: {seqs}" + + +def test_a_cutover_and_a_rollback_leave_exactly_two_operator_entries(request, tmp_path): + """AT-F1 (TP:5473-5475): over the life of one database, a cutover and then + a rollback leave exactly two journal rows with `operator` true, the + cutover's and the rollback's. Fails until T326 and T327.""" + estate = _estate(request, tmp_path) + _assert_rolled_back(estate, estate.rollback()) + operators = [[seq, kind] for seq, kind, operator in estate.journal() if operator] + assert operators == [[1, "cutover"], [estate.k + 1, "rollback"]], operators + + +# ------------------------------------------------------------------ AT-F1: LR012 +def _writer_session(db, appname: str) -> subprocess.Popen: + """A session as REGISTER-WRITER, with the commit call's settings.""" + session = db.session(appname=appname) + session.stdin.write(f"\\set VERBOSITY verbose\n\\set SHOW_CONTEXT never\n" + f"SET ROLE {WRITER};\n") + session.stdin.flush() + return session + + +def _rollback_call(reg: RollbackRegister, base: int, open_: bool = False) -> str: + """The rollback's commit call, by hand: one SERIALIZABLE transaction + around `commit_write` with a `rollback` entry; without its `COMMIT` where + `open_`.""" + body = _entry("rollback", "rollback", + edits=[{"ord": 1, "op": "remove", "path": "lanes/STORE"}], + files=[{"path": "lanes/STORE", "present": False}]) + literal = json.dumps(body, ensure_ascii=True).replace("'", "''") + call = (f"BEGIN ISOLATION LEVEL SERIALIZABLE;\nSELECT {SCRATCH}.commit_write({base}, " + f"'{uuid.uuid4()}'::uuid, {reg.window()['version']}, " + f"'{reg.switch()['generation']}'::uuid, '{literal}'::jsonb);\n") + return call if open_ else call + "COMMIT;\n" + + +def _mirror_text(reg: RollbackRegister) -> list: + return reg.sql(f"SELECT diverged_sha || '|' || found_utc::text || '|' || found_by_ws " + f"FROM {SCRATCH}.mirror_state;").split("|") + + +@pytest.mark.parametrize("case", ["recorded", "recorder-first", "last-error-only", + "rollback-first"]) +def test_a_rollback_entry_over_a_recorded_divergence_is_lr012(rb_register, case): + """AT-F1, LR012 in the transaction (TP:5476-5498), by direct calls as + REGISTER-WRITER on `primary` with the marker `present` (AT-LR006's route; + lane 1's T107): + * `[recorded]`: with a divergence recorded, the `rollback` entry gets + LR012 with lane 1's text and `mirror_state`'s values, and nothing + moves; + * `[recorder-first]`: `record_mirror_state`'s transaction open first, + the rollback's call waits on `mirror_state`, gets 40001 once it + commits, and its retry on the head read afresh gets LR012; + * `[last-error-only]`: the same with only `last_error` recorded: the + retry commits; + * `[rollback-first]`: the rollback's call open first, before its + `COMMIT`, `record_mirror_state` waits on the row until it ends; + * no session gets 40P01.""" + reg = rb_register + k, sha, ws = reg.k, "4" * 40, "ws-t273-f1" + record = f"SELECT {SCRATCH}.record_mirror_state('{ws}', " + ( + "NULL, 'the push was refused');\n" if case == "last-error-only" else f"'{sha}', NULL);\n") + said = [] + if case == "recorded": + assert reg.psql(record, WRITER).returncode == 0 + before = reg.state(), reg.mirror() + proc = reg.psql(_rollback_call(reg, k), WRITER) + said.append(proc.stderr) + utc = _mirror_text(reg)[1] + first = proc.stderr.strip().splitlines()[0] if proc.stderr.strip() else "" + assert first == (f"ERROR: LR012: rollback refused: diverged at {sha}, found {utc} by " + f"{ws}; resolve it first with import --single or render --revert " + f"(F1, S5)"), proc.stderr + assert (reg.state(), reg.mirror()) == before, "the refused entry moved something" + elif case in ("recorder-first", "last-error-only"): + recorder = call = None + try: # both owned to the end (`_teardown`) + recorder = _writer_session(reg.db, "t273-recorder") + recorder.stdin.write("BEGIN;\n" + record) + recorder.stdin.flush() + reg.wait_sql("SELECT count(*) FROM pg_stat_activity WHERE application_name = " + "'t273-recorder' AND state = 'idle in transaction' AND backend_xid IS " + "NOT NULL;", "the recorder's open transaction") + call = _writer_session(reg.db, "t273-call") + call.stdin.write(_rollback_call(reg, k)) + call.stdin.flush() + reg.wait_sql(_locked(reg.db, "t273-call"), "the rollback's call waiting") + out, err = recorder.communicate(input="COMMIT;\n", timeout=60) + said.append(err) + assert recorder.returncode == 0, err + out, err = call.communicate(timeout=60) + said.append(err) + assert "40001" in err, f"the waiting call did not get 40001: {err}" + finally: + _teardown(recorder, call) + retry = reg.psql(_rollback_call(reg, reg.head()), WRITER) + said.append(retry.stderr) + if case == "recorder-first": + assert retry.returncode != 0 and "LR012" in retry.stderr, retry.stderr + assert reg.head() == k + else: + assert retry.returncode == 0, retry.stderr + assert reg.head() == k + 1 and reg.journal()[-1] == [k + 1, "rollback", True] + else: + call = recorder = None + try: # both owned to the end (`_teardown`) + call = _writer_session(reg.db, "t273-call") + call.stdin.write(_rollback_call(reg, k, open_=True)) + call.stdin.flush() + reg.wait_sql(_holding(reg.db, "t273-call"), "the rollback's open call") + recorder = _writer_session(reg.db, "t273-recorder") + recorder.stdin.write(record) + recorder.stdin.flush() + reg.wait_sql(_locked(reg.db, "t273-recorder"), "record_mirror_state waiting") + assert reg.mirror()["diverged_sha"] is None, "the record did not wait" + out, err = call.communicate(input="COMMIT;\n", timeout=60) + said.append(err) + assert call.returncode == 0, err + out, err = recorder.communicate(timeout=60) + said.append(err) + assert recorder.returncode == 0, err + finally: + _teardown(recorder, call) + assert reg.journal()[-1] == [k + 1, "rollback", True] + assert reg.mirror()["diverged_sha"] == sha + assert not any("40P01" in text for text in said), f"a session got 40P01: {said}" + + +def test_rollback_exits_2_on_lr012_naming_the_divergence_and_both_ways_out(rb_register): + """AT-F1, LR012 through the command (TP:5499-5503): the shim holds + `lanes-index rollback`'s step-1 call after its divergence check has + passed, and the test records a divergence meanwhile; on release the call + gets LR012, and `rollback` exits 2 with `diverged at <sha>` and S2's two + ways out, writing nothing: the switch still reads `primary` with the + marker `present`. Runs a copy with the constant False on the scratch + schema, so it needs T304 alone.""" + reg = rb_register + sha = "5" * 40 + copy = flipped_copy(LANES_INDEX, reg.root / "false-copy", False) + fifo = reg.root / "step1.fifo" + proc = fd = None + try: # owned to the end, the FIFO with it (`_teardown`) + os.mkfifo(str(fifo), 0o600) + reg.arm([{"mode": "hold", "fifo": str(fifo), "match": "commit_write", "call": 1}]) + before = reg.state() + proc = subprocess.Popen([sys.executable, str(copy), "rollback"], + stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, + stderr=subprocess.PIPE, text=True, + env=reg.env(reg.config("conf")), cwd=str(reg.root / "operator")) + fd = _open_when_held(fifo, proc) + assert fd is not None, "the rollback's step-1 call was never held" + recorded = reg.psql(f"SELECT {SCRATCH}.record_mirror_state('ws-t273-lr012', '{sha}', " + f"NULL);", WRITER) + assert recorded.returncode == 0, recorded.stderr + end, fd = fd, None + _let_go(fifo, end) # the call released: its FIFO unlinked, then the write end closed + out, err = proc.communicate(timeout=120) + finally: + _teardown(proc, estate=reg.owner(), fifo=fifo, fd=fd) + ended = f"exit {proc.returncode}\n--- stdout ---\n{out}\n--- stderr ---\n{err}" + assert proc.returncode == 2, ended + assert "LR012" in err and f"diverged at {sha}" in err, ended + for way in ("import --single", "render --revert"): + assert way in err, ended + assert reg.state() == before, "the refused rollback wrote" + switch = reg.switch() + assert (switch["mode"], switch["marker_state"]) == ("primary", "present"), switch + + +# ------------------------------------------------------------------ the teardown's own faults +#: The fault-path regressions of this module's own teardown (lane 3's Codex +#: reviews of code PR 97 at `6d479418`, SHOULDs 1 and 2, at `18529e5a`, +#: BLOCKING and SHOULD 1, and at `46cac748`, BLOCKING and SHOULDs 1 to 6; +#: the coordinator's reproductions, #165 6934112467, and his point 2, #165 +#: 6938182757). They need no engine and no task, so their rows wait for +#: none. Each child they start is theirs, ended and reaped in their own +#: `finally`, and each process it starts in turn carries the case's nonce +#: (`_with_identity`), is pinned by it (`_pin`) and, where still there, +#: killed through that pidfd and seen gone; each FIFO is owned from its +#: making (SHOULD 5 at `46cac748`). The rollback they hold is a stub or a +#: stand-in, never `lanes-index`. `LINUX_ONLY`, `SLEEP`, `LEADS_A_GROUP`, +#: `LEAVES_A_MEMBER`, `_Pipe`, `_Undying`, `_with_identity`, `_fifo_reader`, +#: `_on_fifo`, `_ended`, `_reap_all`, `_each`, `_GapFifo`, `_reported` and +#: `_end_pin` are `tests/sql_register_cleanup.py`'s (T270's), which this +#: module imports (round CX-34). + + +class _Stuck: + """A rollback that never ends: `kill()` is recorded and changes nothing, + each `communicate()` and `wait()` times out, and nothing ever sets its + `returncode`. It is no process, so nothing is signalled.""" + + pid = 4194304 + 7 # above Linux's pid_max ceiling, so no process has it + + def __init__(self): + self.returncode = None + self.stdout, self.stderr = _Pipe(), _Pipe() + self.calls: list = [] + + def kill(self) -> None: + self.calls.append("kill") + + def communicate(self, input=None, timeout=None): + self.calls.append("communicate") + raise subprocess.TimeoutExpired("stuck", timeout) + + def wait(self, timeout=None): + self.calls.append("wait") + raise subprocess.TimeoutExpired("stuck", timeout) + + def poll(self): + return None + + +@LINUX_ONLY +def test_a_push_fifo_let_go_leaves_no_reader_blocked(tmp_path): + """SHOULD 1 at `6d479418`: `_let_go`, the release every teardown and + every held window here ends with, leaves no reader blocked on its FIFO. + With no write end held, a reader that comes in the gap just before the + unlink is let go. With the write end held, as a held window holds it, + the reader already on the FIFO and one that comes in that gap both read + EOF. Either way the FIFO is gone, and a reader that comes after finds + none (ENOENT) and ends. Each reader of the gap must be seen on the FIFO + before its unlink, so the race is exercised, not passed by default; + then every reader before the let-go exits 0, and only the one after it + meets ENOENT (lane 3's Codex review of code PR 97 at `18529e5a`, + SHOULD 4).""" + fifo = tmp_path / "push.fifo" + readers: list = [] + try: + os.mkfifo(str(fifo), 0o600) + first = _GapFifo(fifo, readers) + _let_go(first) + assert _ended(readers[0]), ( + "with no write end held, a reader that came in the gap before the unlink is left " + "blocked on the unlinked FIFO") + os.mkfifo(str(fifo), 0o600) + readers.append(_fifo_reader(fifo)) + fd = _open_when_held(fifo, readers[-1], 10) + assert fd is not None, "the reader never came to the FIFO" + second = _GapFifo(fifo, readers) + _let_go(second, fd) + assert not fifo.exists(), "the FIFO is still there after its let-go" + readers.append(_fifo_reader(fifo)) + left = [n for n, proc in enumerate(readers) if not _ended(proc)] + assert not left, f"readers {left} of {len(readers)} are left blocked" + finally: + said = _reap_all(readers) + assert first.on and second.on, ( + f"a reader that came in the gap before the unlink was not seen on the FIFO (without " + f"the write end: {first.on}; with it: {second.on}), so the race went unexercised") + assert [proc.returncode for proc in readers[:3]] == [0, 0, 0], ( + f"a reader that came before the let-go did not exit 0: " + f"{[proc.returncode for proc in readers]} {said}") + assert readers[3].returncode != 0 and "FileNotFoundError" in said[3], ( + f"a reader that came after the let-go found a FIFO: {said[3]}") + + +@LINUX_ONLY +def test_held_at_push_never_returns_with_its_rollback_unreaped(monkeypatch, tmp_path): + """SHOULD 2 at `6d479418`: where the push is never held, `_held_at_push` + tears down all it made (`_teardown`) and never leaves its rollback + unreaped: the rollback, whose every `communicate()` and `wait()` times + out, is killed by its pid and drained, its pipes are closed, a call + parked on the FIFO is let go, the FIFO is gone, and the case fails with + the teardown's own error, not with the rollback left running behind a + failure. Stubbed: the estate, the rollback (`_Stuck`) and + `_open_when_held`, which gives None at once; the parked call is a FIFO + reader of this case's.""" + monkeypatch.setattr(sys.modules[__name__], "_open_when_held", + lambda fifo, proc, seconds=120: None) + stuck, parked = _Stuck(), [] + + def arm(arms=(), hold=None): + if hold: + parked.append(_fifo_reader(hold["fifo"])) + _on_fifo(parked[-1]) + + estate = SimpleNamespace(root=tmp_path, bin=tmp_path / "bin", arm=arm, + popen_rollback=lambda: stuck) + try: + with pytest.raises(RuntimeError, match="still unreaped"): + _held_at_push(estate) + assert stuck.calls == ["kill", "communicate", "wait"], stuck.calls + assert stuck.stdout.closed and stuck.stderr.closed, "the rollback's pipes were left open" + assert not (tmp_path / "push.fifo").exists(), "the push FIFO is still there" + assert parked and _ended(parked[0]), "the call parked on the FIFO is left blocked" + finally: + _reap_all(parked) + + +#: A ROLLBACK'S STAND-IN that forks a push before the push writes any +#: record: the push, in a session of its own and with no pipe of the +#: rollback's, blocks on the FIFO argv[1] and, let go, makes `ran` (EOF) or +#: `aborted` (an abort release) in argv[2], then ends; the rollback writes +#: the push's pid to argv[3], then sleeps. +FORKS_A_PUSH = """ +import os, sys, time +fifo, out, record = sys.argv[1:4] +pid = os.fork() +if pid == 0: + os.setsid() + null = os.open(os.devnull, os.O_RDWR) + for fd in (0, 1, 2): + os.dup2(null, fd) + with open(fifo, "rb") as handle: + said = handle.read() + aborted = said or os.path.exists(fifo + ".abort") + open(os.path.join(out, "aborted" if aborted else "ran"), "w").close() + os._exit(0) +with open(record + ".tmp", "w") as handle: + handle.write(str(pid)) +os.replace(record + ".tmp", record) +time.sleep(300) +""" + + +def _written_pid(path: Path, proc: subprocess.Popen, seconds: float = 10) -> int | None: + """The pid `proc` writes to `path`, once it is there; None where `proc` + ends, or the time runs out, first.""" + deadline = time.monotonic() + seconds + while proc.poll() is None and time.monotonic() < deadline: + if path.exists(): + return int(path.read_text(encoding="utf-8")) + time.sleep(0.01) + return None + + +def _pin_now(pid: int | None, nonce: str) -> _Pinned | None: + """`pid` pinned by the case itself, by the case's identity (`_pin`); + None where there is none, or it is not the case's.""" + return _pin(pid, nonce) if pid is not None else None + + +def _gone(held: _Pinned, seconds: float = 5) -> bool: + """Whether the process pinned as `held` ends within `seconds`.""" + deadline = time.monotonic() + seconds + while not held.gone() and time.monotonic() < deadline: + time.sleep(0.01) + return held.gone() + + +def _end_pinned(held) -> None: + """A process the case pinned, where there is one, ended and seen gone, + its pidfd closed (`_end_pin`), which raises unless it is seen gone + (lane 3's Codex review of code PR 97 at `46cac748`, SHOULD 3).""" + if held is not None: + _end_pin(held) + + +@LINUX_ONLY +def test_a_teardown_signals_through_pidfds_alone_and_spares_a_wrong_start_token(monkeypatch, + tmp_path): + """BLOCKING at `18529e5a`: the teardown signals no process by a number + and runs no `ps`. A held push, in a session of its own, logged as held + with its start token, whose group holds a second member, its git, both + launched with the case's nonce; and a stranger without it, logged as + held and launched with a token one tick on, so not the process that has + its pid. With `os.kill`, `os.killpg`, `os.getpgid`, `subprocess.run` and + `subprocess.Popen` each a recorder, `_teardown` calls none of them, + kills the push (-9) and its git through their pidfds, pinned by the + case's identity, and leaves the stranger running.""" + bin_ = tmp_path / "bin" + bin_.mkdir() + nonce = _nonce() + push = subprocess.Popen([sys.executable, "-I", "-c", LEADS_A_GROUP], stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, + start_new_session=True, env=_with_identity(nonce)) + stranger = subprocess.Popen([sys.executable, "-I", "-c", SLEEP], stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + start_new_session=True) + member, called = None, [] + + def recorder(name: str): + def record(*args, **kwargs): + called.append(name) + return SimpleNamespace(returncode=0, stdout="", stderr="") + return record + + try: + member = _reported(push, "the push's git, a member of its group", nonce) + token, wrong = _stat(push.pid)["start"], str(int(_stat(stranger.pid)["start"]) + 1) + (bin_ / "git-wrapper.log").write_text("".join(json.dumps( + {"sub": "push", "pid": pid, "outcome": "held", "start": start}) + "\n" + for pid, start in ((push.pid, token), (stranger.pid, wrong))), encoding="utf-8") + (bin_ / "git-wrapper.started").write_text( + json.dumps({"pid": stranger.pid, "start": wrong}) + "\n", encoding="utf-8") + with monkeypatch.context() as patch: + for owner, name in ((os, "kill"), (os, "killpg"), (os, "getpgid"), + (subprocess, "run"), (subprocess, "Popen")): + patch.setattr(owner, name, recorder(f"{owner.__name__}.{name}")) + _teardown(estate=SimpleNamespace(bin=bin_, nonce=nonce), grace=5) + assert called == [], f"the teardown signalled by a number, or ran a command: {called}" + assert _ended(push) and push.returncode == -signal.SIGKILL, ( + f"the held push was not killed (SIGKILL): {push.returncode}") + assert _gone(member), "the push's git, a member of its group, is still there" + assert stranger.poll() is None, ( + "the stranger, logged with a start token not its own, was signalled") + finally: + _each(lambda: _end_pinned(member), lambda: _reap_all([push, stranger])) + + +@LINUX_ONLY +def test_a_teardown_ends_a_push_forked_before_its_first_record(tmp_path): + """SHOULD 1 at `18529e5a`: a push the rollback forked, in a session of + its own, parked on the FIFO before it wrote any record (no launch + record, no `held` line), is found by the teardown by the case's + identity, which it inherits from the rollback, stopped, and killed + before the FIFO is let go: it runs nothing, neither on EOF nor on the + abort. The rollback is a stand-in, the case's child, killed and reaped + (-9), and the FIFO is gone. The FIFO is owned from its making (SHOULD 5 + at `46cac748`).""" + bin_ = tmp_path / "bin" + bin_.mkdir() + fifo, record = tmp_path / "push.fifo", tmp_path / "push.pid" + rollback, push, nonce = None, None, _nonce() + try: + os.mkfifo(str(fifo), 0o600) + rollback = subprocess.Popen([sys.executable, "-I", "-c", FORKS_A_PUSH, str(fifo), + str(tmp_path), str(record)], stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, + env=_with_identity(nonce)) + push = _pin_now(_written_pid(record, rollback), nonce) + assert push is not None, "the stand-in rollback never forked its push" + parked = SimpleNamespace(pid=push.pid, poll=lambda: 0 if push.gone() else None) + assert _on_fifo(parked, 10, fifo=fifo), "the push never came to the FIFO" + _teardown(rollback, estate=SimpleNamespace(bin=bin_), fifo=fifo, grace=10) + _gone(push) + made = sorted(name for name in ("ran", "aborted") if (tmp_path / name).exists()) + assert made == [], ( + f"the push forked before its first record was let go, not killed: it made {made}") + assert push.gone(), "the push forked before its first record is still there" + assert rollback.returncode == -signal.SIGKILL, rollback.returncode + assert not fifo.exists(), "the push FIFO is still there" + finally: + _each(lambda: _teardown(rollback, estate=SimpleNamespace(bin=bin_, nonce=nonce), + fifo=fifo, grace=10), + lambda: _end_pinned(push)) + + +@LINUX_ONLY +def test_a_teardown_raises_on_a_call_logged_with_no_start_token(tmp_path): + """SHOULD 1 at `18529e5a`: a launch record, and a `held` line, whose + start token is empty each name a process the teardown cannot tell from + one that uses its pid again: it signals neither, does the rest (the FIFO + is let go and gone), then raises (`RuntimeError`) naming each. Their + pids are above Linux's pid_max ceiling, so no process has them.""" + bin_ = tmp_path / "bin" + bin_.mkdir() + launched, held = _Stuck.pid + 1, _Stuck.pid + 2 + (bin_ / "git-wrapper.started").write_text( + json.dumps({"pid": launched, "start": ""}) + "\n", encoding="utf-8") + (bin_ / "git-wrapper.log").write_text(json.dumps( + {"sub": "push", "pid": held, "outcome": "held", "start": ""}) + "\n", encoding="utf-8") + fifo = tmp_path / "push.fifo" + try: # the FIFO owned from its making (lane 3's Codex review at `f776b435`, SHOULD 6) + os.mkfifo(str(fifo), 0o600) + with pytest.raises(RuntimeError, match="no start token") as raised: + _teardown(estate=SimpleNamespace(bin=bin_), fifo=fifo, grace=2) + assert not fifo.exists(), "the push FIFO is still there after the teardown raised" + finally: + _let_go(fifo, abort=True) + assert f"pid {launched} " in str(raised.value) and f"pid {held} " in str(raised.value), ( + f"the error does not name each pid logged with no start token: {raised.value}") + + +@LINUX_ONLY +def test_an_abort_release_runs_neither_git_nor_the_held_command(tmp_path): + """SHOULD 1 at `18529e5a`: the real wrapper (`GIT_WRAPPER`), its push + held on the FIFO, has written its launch record first: its pid, with the + start token it has while it runs. Let go by an abort release + (`_let_go`'s `abort`), the held call ends 75 and logs `aborted`: its + "git", a script that would leave a mark, never runs, so neither does the + push it holds, and no `ran` line is logged. The wrapper runs in a + session of its own, as T320's `_run_bounded` starts each git call, and + is the case's child, ended and reaped in its `finally`, which owns the + FIFO from its making and lets it go with an abort (SHOULD 5 at + `46cac748`).""" + bin_ = tmp_path / "bin" + wrapper_path = _script(bin_ / "git", GIT_WRAPPER) + fake = _script(tmp_path / "real-git", '#!/bin/sh\n: > "$0.ran"\n') + fifo = tmp_path / "push.fifo" + wrapper, said, token = None, [], None + try: + os.mkfifo(str(fifo), 0o600) + (bin_ / "git-wrapper.json").write_text(json.dumps( + {"git": str(fake), "psql_log": "", "hold": {"call": "push", "fifo": str(fifo)}}), + encoding="utf-8") + wrapper = subprocess.Popen([str(wrapper_path), "push", "origin", "HEAD:main"], + stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, + stderr=subprocess.PIPE, text=True, cwd=str(tmp_path), + start_new_session=True) + assert _on_fifo(wrapper, 30, fifo=fifo), "the wrapper never held its push on the FIFO" + token = _stat(wrapper.pid)["start"] + _let_go(fifo, abort=True) + _ended(wrapper, 30) + finally: + _each(lambda: _let_go(fifo, abort=True), + lambda: said.extend(_reap_all([wrapper] if wrapper is not None else []))) + calls = _jsonl(bin_ / "git-wrapper.log") + assert wrapper.returncode == 75, f"the aborted push ended {wrapper.returncode}, not 75: {said}" + assert not (tmp_path / "real-git.ran").exists(), "the aborted push ran its git" + assert [call.get("outcome") for call in calls] == ["held", "aborted"], calls + assert calls[0].get("start") == token, f"the held line's start is not its token: {calls[0]}" + assert _jsonl(bin_ / "git-wrapper.started") == [{"pid": wrapper.pid, "start": token}], ( + "the wrapper's launch record is not its pid with the start token it had while it ran") + + +@LINUX_ONLY +def test_a_teardown_ends_a_live_call_whose_pid_an_old_record_names_with_another_token(tmp_path): + """Lane 2's CX-32 integration, open item 1 (BLOCKING and SHOULD 1 at + `18529e5a`): a launch record of a call long gone, whose pid a live call + has since taken, names that pid with a start token not the live one's, + and it never hides the live call. The live call is a push the rollback + forked, parked on the FIFO with no record of its own; the old record, + read before the rollback's children in each read, names its pid with + its token one tick on. The teardown finds the push by the case's + identity, which it inherits from the rollback, stops it and kills it + before the FIFO is let go: it runs nothing, neither on EOF nor on the + abort. The rollback is a stand-in, the case's child, killed and reaped + (-9). The FIFO is owned from its making (SHOULD 5 at `46cac748`).""" + bin_ = tmp_path / "bin" + bin_.mkdir() + fifo, record = tmp_path / "push.fifo", tmp_path / "push.pid" + rollback, push, nonce = None, None, _nonce() + try: + os.mkfifo(str(fifo), 0o600) + rollback = subprocess.Popen([sys.executable, "-I", "-c", FORKS_A_PUSH, str(fifo), + str(tmp_path), str(record)], stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, + env=_with_identity(nonce)) + push = _pin_now(_written_pid(record, rollback), nonce) + assert push is not None, "the stand-in rollback never forked its push" + parked = SimpleNamespace(pid=push.pid, poll=lambda: 0 if push.gone() else None) + assert _on_fifo(parked, 10, fifo=fifo), "the push never came to the FIFO" + (bin_ / "git-wrapper.started").write_text(json.dumps( + {"pid": push.pid, "start": str(int(push.start) + 1)}) + "\n", encoding="utf-8") + _teardown(rollback, estate=SimpleNamespace(bin=bin_), fifo=fifo, grace=10) + _gone(push) + made = sorted(name for name in ("ran", "aborted") if (tmp_path / name).exists()) + assert made == [], ( + f"an old record naming the push's pid with another start token hid the live push: " + f"it was let go, not killed, and made {made}") + assert push.gone(), "the live push whose pid an old record names is still there" + assert rollback.returncode == -signal.SIGKILL, rollback.returncode + assert not fifo.exists(), "the push FIFO is still there" + finally: + _each(lambda: _teardown(rollback, estate=SimpleNamespace(bin=bin_, nonce=nonce), + fifo=fifo, grace=10), + lambda: _end_pinned(push)) + + +@LINUX_ONLY +def test_a_teardown_never_signals_a_logged_pid_and_start_token_without_the_case_s_identity( + tmp_path): + """BLOCKING at `46cac748` (lane 2's decision 1 in round CX-33): a process + is never owned on its pid and start token alone, which a process that + takes a logged pid within the same clock tick shares. A stranger + without the case's nonce has a launch record and a `held` line with its + own pid and its own start token, exactly, as such a successor would + match; a held push launched with the nonce is logged beside it. + `_teardown` kills the push (-9) through its pidfd, never signals the + stranger, which is still running and not stopped, and raises + (`RuntimeError`) naming the stranger's pid as without the identity.""" + bin_ = tmp_path / "bin" + bin_.mkdir() + procs, nonce = [], _nonce() + try: + push = subprocess.Popen([sys.executable, "-I", "-c", SLEEP], stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + start_new_session=True, env=_with_identity(nonce)) + procs.append(push) + stranger = subprocess.Popen([sys.executable, "-I", "-c", SLEEP], stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + start_new_session=True) + procs.append(stranger) + until = time.monotonic() + 5 # their environments are set only once their execs are done + while _carried(push.pid) != nonce or not Path(f"/proc/{stranger.pid}/environ").read_bytes(): + assert time.monotonic() < until, "a child's environment was never set" + time.sleep(0.005) + (bin_ / "git-wrapper.log").write_text("".join(json.dumps( + {"sub": "push", "pid": proc.pid, "outcome": "held", "start": _stat(proc.pid)["start"]}) + + "\n" for proc in procs), encoding="utf-8") + (bin_ / "git-wrapper.started").write_text(json.dumps( + {"pid": stranger.pid, "start": _stat(stranger.pid)["start"]}) + "\n", encoding="utf-8") + with pytest.raises(RuntimeError, match="does not carry the case's identity") as raised: + _teardown(estate=SimpleNamespace(bin=bin_, nonce=nonce), grace=5) + assert f"pid {stranger.pid} " in str(raised.value), raised.value + assert _ended(push) and push.returncode == -signal.SIGKILL, push.returncode + assert stranger.poll() is None and _stat(stranger.pid)["state"] not in ("T", "t"), ( + "the stranger with a logged pid and start token, but not the case's identity, was " + "signalled") + finally: + _reap_all(procs) + + +@LINUX_ONLY +def test_a_teardown_ends_each_member_of_a_group_whose_leader_is_gone(tmp_path): + """SHOULD 1 at `46cac748`: discovery needs no live leader. A held push's + stand-in leads a session of its own, forks a member into its group, its + git, and ends; the case reaps it, so no leader is left to pin, and + nothing is logged. `_teardown` still finds the member by the case's + identity alone, and it is gone.""" + bin_ = tmp_path / "bin" + bin_.mkdir() + leader, member, nonce = None, None, _nonce() + try: + leader = subprocess.Popen([sys.executable, "-I", "-c", LEAVES_A_MEMBER], + stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, text=True, start_new_session=True, + env=_with_identity(nonce)) + member = _reported(leader, "the git its push left", nonce) + assert _ended(leader, 10), "the push did not end" + _teardown(estate=SimpleNamespace(bin=bin_, nonce=nonce), grace=5) + assert _gone(member), "the member of a group whose leader is gone is still there" + finally: # what carries the nonce ended first (lane 3's Codex review at `f776b435`, SHOULD 5) + _each(lambda: _teardown(leader, estate=SimpleNamespace(bin=bin_, nonce=nonce), grace=5), + lambda: _end_pinned(member), + lambda: _reap_all([leader] if leader is not None else [])) + + +@LINUX_ONLY +def test_a_teardown_ends_what_it_knows_before_it_raises_an_unreadable_log(tmp_path): + """The coordinator's point 2 (#165 6938182757): where the launch records + cannot be read (`git-wrapper.started` is a directory, so `_logged` + raises `IsADirectoryError`), `_find` keeps that error and goes on: the + rollback, the case's child leading a session of its own, ends -9, and + its descendant, a member of its group found by the case's identity, is + gone. Then the log's own error is what `_teardown` raises, alone, as it + is.""" + bin_ = tmp_path / "bin" + (bin_ / "git-wrapper.started").mkdir(parents=True) + rollback, member, nonce = None, None, _nonce() + try: + rollback = subprocess.Popen([sys.executable, "-I", "-c", LEADS_A_GROUP], + stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, text=True, start_new_session=True, + env=_with_identity(nonce)) + member = _reported(rollback, "the rollback's descendant", nonce) + with pytest.raises(IsADirectoryError): + _teardown(rollback, estate=SimpleNamespace(bin=bin_), grace=5) + assert rollback.returncode == -signal.SIGKILL, rollback.returncode + assert _gone(member), "the rollback's descendant is still there" + finally: # what carries the nonce ended first (lane 3's Codex review at `f776b435`, SHOULD 5) + _each(lambda: _teardown(rollback, estate=SimpleNamespace(bin=tmp_path / "no-log", + nonce=nonce), grace=5), + lambda: _end_pinned(member), + lambda: _reap_all([rollback] if rollback is not None else [])) + + +@LINUX_ONLY +def test_a_report_that_never_comes_ends_its_starter_and_raises(tmp_path): + """SHOULD 2 at `46cac748`: `_reported` reads its stand-in's line under + `select` with an absolute deadline. A stand-in that prints nothing and + stays makes it raise within the bound, its starter ended and reaped, + where a `readline()` with no bound waited for ever. The bound is 1 s, + held to within a cushion of 1.5 s (lane 3's Codex review of code PR 97 + at `f776b435`, SHOULD 7).""" + proc = subprocess.Popen([sys.executable, "-I", "-c", SLEEP], stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) + start = time.monotonic() + try: + with pytest.raises(AssertionError, match="nothing was printed"): + _reported(proc, "the silent stand-in", _nonce(), seconds=1) + assert 0.9 <= time.monotonic() - start < 2.5, "the bound of 1 s was not kept" + assert proc.returncode == -signal.SIGKILL, f"its starter was not ended: {proc.returncode}" + finally: + _reap_all([proc]) + + +def test_a_pinned_process_s_end_raises_unless_it_is_seen_gone(): + """SHOULD 3 at `46cac748`: `_end_pinned` confirms the end. A pin whose + process is never seen gone (`_Undying`) is sent SIGKILL, its pidfd is + closed, and it raises (`RuntimeError`, "still there"), where it + returned with the process alive. No process is signalled.""" + held = _Undying() + with pytest.raises(RuntimeError, match="still there"): + _end_pinned(held) + assert held.calls == [signal.SIGKILL, "close"], held.calls + + +@LINUX_ONLY +def test_reap_all_tries_every_child_and_raises_after_the_whole_set(): + """SHOULD 4 at `46cac748`: `_reap_all` tries every child. The first + never ends (`_Stuck`, its `kill` recorded); the second is a real child + that stays. The second is still killed and reaped (-9), the first's + pipes are closed after its bounded waits, and only then is the first + error raised (`subprocess.TimeoutExpired`).""" + stuck = _Stuck() + child = subprocess.Popen([sys.executable, "-I", "-c", SLEEP], stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) + try: + with pytest.raises(subprocess.TimeoutExpired): + _reap_all([stuck, child]) + assert child.returncode == -signal.SIGKILL, f"the second child: {child.returncode}" + assert stuck.calls == ["kill", "communicate", "wait"], stuck.calls + assert stuck.stdout.closed and stuck.stderr.closed, "the first child's pipes are open" + finally: + if child.returncode is None: + child.kill() + child.wait(timeout=30) + + +@LINUX_ONLY +def test_a_teardown_kills_and_closes_every_pin_whatever_a_signal_raised(monkeypatch, tmp_path): + """SHOULD 6 at `46cac748`: each pin is registered before any signal, and + each signal and pidfd has its own `try`. Two processes carry the case's + nonce; the first SIGSTOP sent through a pidfd raises `PermissionError` + (stubbed: every other call goes to the real `signal.pidfd_send_signal`). + `_teardown` still kills both (-9), leaves this process no more fds open + than before, and then raises that error.""" + bin_ = tmp_path / "bin" + bin_.mkdir() + procs, nonce, real, refused = [], _nonce(), signal.pidfd_send_signal, [] + + def first_stop_refused(fd, sig, *args): + if sig == signal.SIGSTOP and not refused: + refused.append(fd) + raise PermissionError("the first SIGSTOP is refused") + return real(fd, sig, *args) + + try: + for _ in range(2): + procs.append(subprocess.Popen([sys.executable, "-I", "-c", SLEEP], + stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, start_new_session=True, + env=_with_identity(nonce))) + until = time.monotonic() + 5 # their environments are set only once their execs are done + while any(_carried(proc.pid) != nonce for proc in procs): + assert time.monotonic() < until, "a child's environment never carried the nonce" + time.sleep(0.005) + fds = len(os.listdir("/proc/self/fd")) + with monkeypatch.context() as stubs: + stubs.setattr(signal, "pidfd_send_signal", first_stop_refused) + with pytest.raises(PermissionError, match="refused"): + _teardown(estate=SimpleNamespace(bin=bin_, nonce=nonce), grace=2) + assert refused, "no SIGSTOP was sent" + assert [_ended(proc) and proc.returncode for proc in procs] == [-signal.SIGKILL] * 2, ( + [proc.returncode for proc in procs]) + assert len(os.listdir("/proc/self/fd")) <= fds, "a pidfd was left open" + finally: + _reap_all(procs) + + +#: A STAND-IN THAT LEAVES A PROCESS DETACHED: it forks a child into a session +#: of its own, which forks the process that stays and ends, and the stand-in +#: ends once that child has, so the one left is no child of the case. The one +#: left writes its pid and start token, one line, to the file argv[1], made +#: new (`O_EXCL`), then stays. +LEAVES_A_DETACHED = """ +import os, sys, time +if os.fork() == 0: + os.setsid() + if os.fork() == 0: + raw = open('/proc/self/stat', 'rb').read() + token = raw[raw.rindex(b')') + 2:].split()[19] + fd = os.open(sys.argv[1], os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + os.write(fd, b'%d %s\\n' % (os.getpid(), token)) + os.close(fd) + null = os.open(os.devnull, os.O_RDWR) + for each in (0, 1, 2): + os.dup2(null, each) + time.sleep(300) + os._exit(0) +os.wait() +""" + + +@LINUX_ONLY +def test_an_estate_whose_construction_fails_ends_what_it_started(monkeypatch, tmp_path): + """BLOCKING at `f776b435`: the estate's nonce is made before anything is + launched, and is in the environment test 7's cutover host copies as it + is built, so a process its construction leaves carries it. The host, a + stand-in for `CutoverRegister`, copies `os.environ` once, at its + construction, as its `Workspace` does, starts a stand-in that leaves a + detached process, and fails. The estate's construction raises that + error, and the process left, which carries the estate's nonce, has been + ended (`_teardown`), where it carried none and outlived the case. This + process's environment is as it was before.""" + record, outer, carried, left = tmp_path / "left.pid", _nonce(), [], None + monkeypatch.setenv(IDENTITY, outer) + + class Failing: + def __init__(self, root, db, extra_path=None): + self.env = dict(os.environ) + carried.append(self.env.get(IDENTITY)) + subprocess.run([sys.executable, "-I", "-c", LEAVES_A_DETACHED, str(record)], + stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, env=self.env, timeout=30, check=True) + until = time.monotonic() + 10 + while not (record.exists() and record.read_bytes().endswith(b"\n")): + assert time.monotonic() < until, "the stand-in left no record" + time.sleep(0.01) + raise RuntimeError("the cutover host's construction failed") + + monkeypatch.setattr(sys.modules[__name__], "_imp", + lambda: SimpleNamespace(CutoverRegister=Failing)) + try: + with pytest.raises(RuntimeError, match="construction failed"): + RollbackEstate(tmp_path / "estate", SimpleNamespace(psql_bin="/bin/false")) + pid, start = record.read_text(encoding="utf-8").split() + left = int(pid) + assert carried and carried[0] != outer, "the cutover host was built without the nonce" + assert os.environ.get(IDENTITY) == outer, "the estate's nonce was left in the environment" + until = time.monotonic() + 5 + while True: # one read of its stat a pass: it can be reaped between two (Codex at 5a120647) + now = _stat(left) + if now is None or now["start"] != start or now["state"] in ("Z", "X"): + break + assert time.monotonic() < until, ( + f"pid {left}, which the failed construction left, is still there") + time.sleep(0.02) + finally: + if left is not None and carried and carried[0]: + _end_pinned(_pin(left, carried[0])) + + +@LINUX_ONLY +def test_a_teardown_raises_where_a_stop_is_never_seen(monkeypatch, tmp_path): + """SHOULD 1 at `f776b435`: a stop not seen is no stop. A process carrying + the case's nonce is found, but each SIGSTOP sent through a pidfd is + dropped (stubbed: every other signal goes to the real + `signal.pidfd_send_signal`), so it is never seen stopped. `_teardown` + still kills it (-9), and raises (`RuntimeError`, "never seen stopped"), + where it returned as if all it owns had stopped.""" + bin_ = tmp_path / "bin" + bin_.mkdir() + procs, nonce, real, dropped = [], _nonce(), signal.pidfd_send_signal, [] + + def stop_dropped(fd, sig, *args): + if sig == signal.SIGSTOP: + dropped.append(fd) + return None + return real(fd, sig, *args) + + try: + procs.append(subprocess.Popen([sys.executable, "-I", "-c", SLEEP], + stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, start_new_session=True, + env=_with_identity(nonce))) + until = time.monotonic() + 5 # its environment is set only once its exec is done + while _carried(procs[0].pid) != nonce: + assert time.monotonic() < until, "the child's environment never carried the nonce" + time.sleep(0.005) + with monkeypatch.context() as stubs: + stubs.setattr(signal, "pidfd_send_signal", stop_dropped) + with pytest.raises(RuntimeError, match="never seen stopped"): + _teardown(estate=SimpleNamespace(bin=bin_, nonce=nonce), grace=1) + assert dropped, "no SIGSTOP was sent" + assert _ended(procs[0]) and procs[0].returncode == -signal.SIGKILL, procs[0].returncode + finally: + _each(lambda: _teardown(estate=SimpleNamespace(bin=bin_, nonce=nonce), grace=5), + lambda: _reap_all(procs)) diff --git a/tests/test_sql_register_shape.py b/tests/test_sql_register_shape.py new file mode 100644 index 00000000..64fb0064 --- /dev/null +++ b/tests/test_sql_register_shape.py @@ -0,0 +1,80 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Feature 007's register shape (opensoft/openRepoTools#165): what each register +call looks like from outside, its argv, its credentials and its text. + +THIS MODULE TODAY holds test 2's FP case, lane 2's T241 (AT-2, the test plan's +lines 646-781; FR-018, FR-059): +`test_an_unreachable_store_is_69_naming_the_store_and_never_the_files[<verb>]`. +Lane 1's T106 and T111 select their own cases here by `sql_register_shape` +and their words (B10 tasks:275 and :399); those cases are other tasks', which +add them to this module. + +THE CASE runs each of S1's writes but `commit` as `lanes-edit.sh <verb>` on a +`mode=primary` workstation (`test_sql_register_writes.py`'s +`PrimaryWorkstation` and `WRITE_VERBS`), with T203's register fake first on +`PATH` answering every call that carries a request with `psql`'s exit 2 and +its "connection to server ... failed" text (AT-2, "Unreachable (FP)"). It +needs no engine, and fails until lane 4's L4-B3 (T415's attempt loop) lands, +by its own assertion: today's `lanes-edit.sh` writes the files whatever +`mode=` says. +""" + +from __future__ import annotations + +import re +import shutil + +import pytest + +from conftest import WINDOWS_SKIP +from test_sql_register_render import fake_calls, fake_psql_dir +from test_sql_register_writes import (PREPS, SECRET, WRITE_VERBS, PrimaryWorkstation, + unreachable_answers) + +pytestmark = [WINDOWS_SKIP, pytest.mark.skipif( + shutil.which("bash") is None or shutil.which("git") is None, + reason="the lane tooling is bash over git")] + +#: THE LANDING GATE'S TABLE (T280; `tests/sql_register_gate.py` reads it, and +#: T281 removes it in the last set): every id of this module waits for the +#: tasks T241's Order names, L4-B3's, L4-B4's and L4-B11's (tasks.md at +#: 204145ae). Lane 2's plan GP-24 wrote it (task sets 12b's rule 11). +SQL_REGISTER_GATE_TABLE = { + "*": ("T413", "T414", "T415", "T420"), # every id: the tasks all its rows share +} + +#: What a writer that fell back to the files, or offered to, would say: the +#: register's file paths as a target, or the files mode by name. None may +#: appear in a refusal on primary (P213-215: "nothing ever written to the +#: files instead"). +FILES_WORDS = re.compile(r"lanes/LANES\.md|lanes/log/|mode=files|files mode|files-mode" + r"|fall(ing)? ?back", re.I) + + +@pytest.mark.parametrize("verb", list(WRITE_VERBS)) +def test_an_unreachable_store_is_69_naming_the_store_and_never_the_files(tmp_path, verb): + """AT-2's FP oracle for the refusal's text (P213-214; contract section + 2.6): `lanes-edit.sh <verb>` on primary, with the database unreachable, + exits 69; stderr names the store, `psql`'s own first line with the socket + it tried, and the error, with no password, no `PGPASSWORD` and no URL; + it never names the files as a target or a fallback; no call follows the + failed one; and the files under `lanes/` are as they were.""" + ws = PrimaryWorkstation(tmp_path, prep=PREPS.get(verb)) + fake = fake_psql_dir(ws.fakebin, answers=unreachable_answers(ws.dead)) + ws.env.update(fake) + argv, lane = WRITE_VERBS[verb] + lanes_before = ws.git_state()[1] + proc = ws.run(argv, lane) + said = proc.stdout + proc.stderr + assert proc.returncode == 69, ( + f"lanes-edit.sh {verb} on primary exited {proc.returncode}, not 69, with the store " + f"unreachable (L4-B3, T415's attempt loop): {proc.stderr[-800:]}") + assert str(ws.dead) in proc.stderr and "connection to server" in proc.stderr, ( + f"stderr does not name the store and the error: {proc.stderr!r}") + assert SECRET not in said and "PGPASSWORD" not in said, "a credential reached the output" + assert not re.search(r"postgres(ql)?://", said), f"a URL reached the output: {said!r}" + assert not FILES_WORDS.search(proc.stderr), ( + f"the refusal names the files: {FILES_WORDS.search(proc.stderr).group(0)!r} in " + f"{proc.stderr!r}") + assert len(fake_calls(fake)) == 1, f"calls after the failed one: {fake_calls(fake)}" + assert ws.git_state()[1] == lanes_before, "a file under lanes/ changed" diff --git a/tests/test_sql_register_writes.py b/tests/test_sql_register_writes.py new file mode 100644 index 00000000..2104acec --- /dev/null +++ b/tests/test_sql_register_writes.py @@ -0,0 +1,1086 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Feature 007's test 2 (AT-2; opensoft/openRepoTools#165): a register write +exits 69 when the database is unreachable, with nothing written. + +THIS MODULE holds test 2's storage-layer case, phase N (the test plan's +section 1.3; lane 2's T210): +`test_the_storage_layer_entry_exits_69_when_the_database_is_unreachable`; +and test 2's per-verb cases, its refused transactions, its partial failures +and S1's other tests, phase W, lane 2's T241 (see "phase W: T241" below), +with lane 3's reading 3 of T112, an image holding a CR or a NUL refused with +2 by `register commit`, and lane 3's Q35, `request-handoff`'s refusals before +its claim, 64 and never 2 (T241d). + +THE STORAGE-LAYER ENTRY is the managed projection writer's (design S4), driven +by the fake writer AT-1's part N drives it with, +`test_sql_register_render.py`'s `projection_entry`: one attempt of S1's loop, +`register snapshot --write-id new ... --tree <dir> --checkout <c>` (contract +section 3.2), then, on 0 alone, the attempt directory and `register commit` +(section 3.3), as the verb `managed-projection`. + +WHY THE 69 IS THE SNAPSHOT'S. With the database unreachable, the entry's first +call is a read, and a read that cannot reach its database is 69 (contract +section 2.7, "On a read"; section 3.2's exits; AT-2's outcome table, "no +connection at the first snapshot is 69"). `register commit` against an +unreachable database is 3, in doubt, never 69 (section 2.7, CO-5 and CO-6; +lane 1's T112 builds it so), so the entry never reaches it: the writer +abandons on a snapshot's 69 (section 3.3, "The caller's map"). The case fails +until L1-A9 (lane 1's T111, `register snapshot`) lands, and, for the flipped +copy, L1-A4 (T105's constant). + +THE FAULT, WITH NO ENGINE (AT-2's "Unreachable"): the configuration's +`register_url=` names a fresh, empty socket directory, and the `psql` first on +`PATH` is T203's register fake, which since T203b answers T106's `psql +--version` itself with 16.4 (logged as its own kind, and left out of +`fake_calls`), and every call that carries a request with `psql`'s own exit 2 +and its "connection to server ... failed" text, as the real `psql` answers an +empty socket directory. The fake's log is the oracle for what reached the store: +one call, the snapshot's, with no `commit_write` in it, the configured +password file and no `PGPASSWORD`, and no call after it (no retry that reads +as a write, and no fallback). With no request that reached a database, the +register's rows and the journal are unchanged; on the real engine, the +per-verb cases (T241) read them back by digest. +""" + +from __future__ import annotations + +import atexit +import hashlib +import json +import os +import re +import shlex +import shutil +import subprocess +import tempfile +import time +import uuid +from pathlib import Path +from urllib.parse import quote + +import pytest + +from conftest import WINDOWS_SKIP +from pgcluster import Database +from sql_register_helpers import PSQL_SHIM, PSQL_SHIM_CONTROL, PSQL_SHIM_LOG +from test_sql_register_render import (AUTHOR, DOT, EM, LOGIN_READER, LOGIN_WRITER, SCHEMA, SEED, + SID_A1, SID_A2, TIP, WRITER, WS, Estate, _canonical_rows, + ensure_logins, fake_calls, fake_psql_dir, + flipped, git, import_to_primary, index_env, primary_config, + projection_entry, rows, run_index, sql, workspace) + +pytestmark = [WINDOWS_SKIP, pytest.mark.skipif( + shutil.which("bash") is None or shutil.which("git") is None, + reason="the lane tooling is bash over git")] + +#: THE LANDING GATE'S TABLE (T280; `tests/sql_register_gate.py` reads it, and +#: T281 removes it in the last set): the tasks each id of this module waits +#: for, by T210's and T241's Orders (tasks.md at 204145ae), keyed by function +#: or by one id, with T241's As built for `[log]`. Lane 2's plan GP-24 wrote +#: it (task sets 12b's rule 11). +SQL_REGISTER_GATE_TABLE = { + "test_a_failure_in_a_late_statement_leaves_journal_lines_and_head_unchanged": ("T413", "T414", "T415", "T420"), # T241; tasks:2324 + "test_a_hand_edit_commit_is_refused_on_primary": ("T413", "T414", "T415", "T420"), # T241; tasks:2324 + "test_a_pending_hand_edit_names_the_file_and_a_recovery_that_works": ("T413", "T414", "T415", "T420"), # T241; tasks:2324 + "test_a_queued_handoff_commit_is_still_published": ("T413", "T414", "T415", "T420"), # T241; tasks:2324 + "test_a_queued_lanes_commit_is_refused_as_a_divergence": ("T413", "T414", "T415", "T420"), # T241; tasks:2324 + "test_a_refused_write_leaves_no_lock": ("T413", "T414", "T415", "T420"), # T241; tasks:2324 + "test_a_write_goes_on_with_the_service_down": ("T413", "T414", "T415", "T420"), # T241; tasks:2324 + "test_an_image_holding_a_cr_or_a_nul_is_refused_with_2_and_nothing_sent": ("T112",), # T241; tasks:2324 + "test_each_direct_write_refuses_with_2_on_primary": ("T413", "T414", "T415", "T420"), # T241; tasks:2324 + "test_each_write_exits_69_when_the_database_is_unreachable": ("T413", "T414", "T415", "T420"), # T241; tasks:2324 + "test_each_write_exits_69_when_the_database_refuses_the_transaction": ("T413", "T414", "T415", "T420"), # T241; tasks:2324 + "test_each_write_exits_69_when_the_switch_is_not_primary": ("T413", "T414", "T415", "T420"), # T241; tasks:2324 + "test_request_handoff_refuses_64_never_2_on_primary": ("T413", "T414", "T415", "T420"), # T241; tasks:2324 + "test_the_storage_layer_entry_exits_69_when_the_database_is_unreachable": ("T105", "T107", "T108", "T111", "T112", "T227", "T301"), # T210; tasks:1951 + "test_a_failure_in_a_late_statement_leaves_journal_lines_and_head_unchanged[rename-lane]": ("T413", "T414", "T415", "T420", "T422"), # T241; tasks:2324 + "test_a_refused_write_leaves_no_lock[rename-lane]": ("T413", "T414", "T415", "T420", "T422"), # T241; tasks:2324 + "test_each_write_exits_69_when_the_switch_is_not_primary[log]": ("T412", "T413", "T414", "T415", "T417", "T420"), # T241; tasks:2322 +} + +#: Contract section 2.2's argv, exactly. +PSQL_ARGV = ["--no-psqlrc", "-X", "-q", "-A", "-t", "-v", "ON_ERROR_STOP=1", "-v", + "VERBOSITY=verbose", "-v", "SHOW_CONTEXT=never"] + +#: The writer's login and its password, which must never be printed. +WRITER_LOGIN = "lanes_w_t210" +SECRET = "t210-never-printed-0b5e" + +#: The session `request-handoff --force` writes its `PAUSED` for (`--session`). +#: Without it the verb refuses with 2, naming no uuid (`lanes-edit.sh`'s +#: `requester_uuid`, at a2073eae:10691), before it reaches any SQL, so a case +#: that expects the write's own refusal or 69 would fail by that usage refusal. +SID_REQUESTER = "bbbbbbbb-0007-4000-8000-00000000b007" + +#: What `_masked_path` keeps off a case's `PATH`: an installed `lanes-index`, +#: a real `psql`, and every `pg_` client that `postgresql-16` puts beside it. +_MASKED_NAMES = ("psql", "lanes-index") +_MASKED_PREFIX = "pg_" +#: `_masked_path`'s mirrors, built once per process: each masked directory's +#: real path, to its mirror under the one `l2-pathmask-` directory. +_PATH_MIRRORS: dict = {} +_PATH_MIRROR_ROOT: list = [] + + +def _masked_path() -> str: + """The caller's PATH with every directory kept, in its place, and each one + that holds a masked name swapped for a mirror of it without them. A real + `psql` or `pg_` client, or an installed `lanes-index`, is never what a + case runs; but dropping the directory that holds one drops what sits + beside it. On a GitHub runner, `postgresql-16`'s client package puts + `psql` in `/usr/bin` together with `git` and `bash`, and `/bin` links + there, so a filter that drops the directory leaves a case no `git` or + `bash` to run. The mirror is a directory of symlinks, one per entry, each + to the original entry's absolute path, the masked names left out. It is + built once per process, keyed by the directory's real path, under one + temporary directory that an `atexit` handler removes. A directory that + holds no masked name passes through unchanged, so where no `PATH` + directory holds one, the PATH is what the old filter gave; empty entries + are left out, as that filter left them.""" + kept = [] + for part in os.environ.get("PATH", "").split(os.pathsep): + if not part: + continue + real = os.path.realpath(part) + if real not in _PATH_MIRRORS: + try: + names = os.listdir(real) + except OSError: + names = [] + if not any(_is_masked(name) for name in names): + kept.append(part) + continue + _PATH_MIRRORS[real] = _path_mirror(real, names) + kept.append(_PATH_MIRRORS[real]) + return os.pathsep.join(kept) + + +def _is_masked(name: str) -> bool: + return name in _MASKED_NAMES or name.startswith(_MASKED_PREFIX) + + +def _path_mirror(real: str, names: list) -> str: + """`real`'s mirror: a new directory under the one `l2-pathmask-` + directory, holding a symlink to each entry of `real` but the masked.""" + if not _PATH_MIRROR_ROOT: + root = tempfile.mkdtemp(prefix="l2-pathmask-") + atexit.register(shutil.rmtree, root, ignore_errors=True) + _PATH_MIRROR_ROOT.append(root) + mirror = tempfile.mkdtemp(prefix=(os.path.basename(real) or "root") + "-", + dir=_PATH_MIRROR_ROOT[0]) + for name in names: + if not _is_masked(name): + os.symlink(os.path.join(real, name), os.path.join(mirror, name)) + return mirror + + +def test_the_storage_layer_entry_exits_69_when_the_database_is_unreachable(tmp_path): + """The storage-layer entry, called as AT-1's part N calls it, against a + `register_url=` whose socket directory is fresh and empty: it exits 69, + and stderr names the store and the error, `psql`'s own first line, which + names the socket, with no credential and no URL. The fake's log holds one + call, the snapshot's, sent with section 2.2's argv, as the configured + login, with the configured password file and no `PGPASSWORD`, and + carrying no `commit_write`; no call follows it. Nothing is written: no + scratch tree, no attempt directory beyond it, and the lane checkout's + HEAD, status, index and `origin/main` as they were (AT-2, "Unreachable + (RE), the storage-layer entry"; the delta spec's "Unreachable or refused + is exit 69 with nothing written").""" + dead = tmp_path / "dead" + dead.mkdir() + socket = dead / ".s.PGSQL.5432" + psql_error = (f'psql: error: connection to server on socket "{socket}" failed: ' + f"No such file or directory") + fake = fake_psql_dir(tmp_path / "fakebin", answers=[ + {"exit": 2, "stderr": psql_error + "\n\tIs the server running locally and accepting " + "connections on that socket?\n"}]) + estate = Estate(tmp_path / "estate") + copy = flipped(tmp_path) + conf_dir = tmp_path / "conf" + conf_dir.mkdir() + passfile = conf_dir / "pgpass" + passfile.write_text(f"*:*:*:{WRITER_LOGIN}:{SECRET}\n", encoding="utf-8") + passfile.chmod(0o600) + host = quote(dead.as_posix(), safe="") + conf = primary_config(conf_dir / "lanes-index.conf", + f"postgresql://{WRITER_LOGIN}@{host}:5432/lanes_t210", + f"postgresql://lanes_r_t210@{host}:5432/lanes_t210", passfile) + env = index_env(tmp_path, conf, estate.home, **fake) + env["PATH"] = str(tmp_path / "fakebin") + os.pathsep + _masked_path() + before = estate.state() + + done = projection_entry(copy, env, estate.checkout, tmp_path, "managed-projection", + "lanes-edit.sh managed-projection: test 2's storage-layer case") + snap = done["snapshot"] + said = snap.stdout + snap.stderr + assert done["code"] == 69, (f"the storage-layer entry exited {done['code']}, not 69: " + f"{snap.stderr}") + assert done["commit"] is None, "the entry went on to `register commit` after a 69" + + # THE ERROR AND THE STORE, WITHOUT CREDENTIALS (contract section 2.6). + assert psql_error in snap.stderr, f"stderr does not carry psql's error: {snap.stderr!r}" + assert SECRET not in said, "a password reached the output" + assert not re.search(r"postgres(ql)?://", said), f"a URL reached the output: {said!r}" + + # WHAT REACHED THE STORE: the snapshot's one call, and nothing after it. + calls = fake_calls(fake) + assert len(calls) == 1, f"{len(calls)} psql calls reached the store, not one: {calls}" + call = calls[0] + assert call["argv"] == PSQL_ARGV, call["argv"] + assert call["url"].startswith(f"postgresql://{WRITER_LOGIN}@"), call["url"] + assert call["passfile"] == str(passfile) and call["pgpassword"] is False, call + assert "commit_write" not in call["stdin"], "the snapshot's call carried a commit" + + # NOTHING WRITTEN: no scratch tree, and the lane checkout as it was. + tree = done["attempt"] / "tree" + assert not tree.exists() or not any(tree.iterdir()), "a scratch tree was built" + assert not (done["attempt"] / "snapshot").exists() + assert estate.state() == before, "the lane checkout changed" + + +# ============================================================ phase W: T241 +# +# TEST 2'S REFUSALS AND ITS PARTIAL FAILURE (lane 2's T241; AT-2, the test +# plan's lines 646-781; FR-018, FR-019, FR-026, FR-059). Each of S1's writes +# runs as `lanes-edit.sh <verb>` on a `mode=primary` workstation, from the +# flipped copy (T203's, `RENDER_GIT_HALF = True`) with `lanes-edit.sh` beside +# it, so the verb's `lanes-index` is that copy (CLI4.5 section 6's copy rule). +# +# THE VERBS are S1's writes but `commit` (the test plan's line 750): the +# fourteen arms of `lanes-edit.sh`'s write dispatch at a2073eae (`:16537`), +# `commit` left out, whose direct write is 2 (D10). Each runs once, with the +# argument list `WRITE_VERBS` gives it; `log` runs once, as `log NOTED`. +# +# NO ENGINE (FP): the database unreachable, as a fake `psql` (T203's register +# fake, which answers T106's `--version` itself) that exits 2 with `psql`'s own +# "connection to server ... failed" text; D10's refusals; the queued commits; +# `request-handoff`'s 64s before its claim. +# REAL ENGINE (RE, on `pg`, skipped without PostgreSQL 16 by T205's banner): +# the switch not `primary`, the refused GRANTs, the late statement, the lock, +# the pending hand edit and the service down, each over test 1's imported +# register (`import_to_primary`, AT-LR006's route). +# +# They fail until lane 4's L4-B3 (T415's attempt loop), L4-B4 and L4-B11 +# (T420, D10's refusals) land, each by its own assertion here: today's +# `lanes-edit.sh` writes the files whatever `mode=` says. +# +# R02 (lane 1, #165 6755590769; lane 3, 6755615338; F10-OWED items 35 and +# 37): after LR004, `register commit` re-reads once and never resends. No case +# here meets LR004; the refused-transaction and late-statement cases assert +# that a refused commit call is never sent again, so a resend under any +# refusal fails them. LR004's own cases are T221's (`lr004_on_an_edit`, +# `lr004_reloads_once`). +# +# LANE 3'S READING 3 OF T112 (#165 6755386771; F10-OWED item 31): the +# malformed-directory refusals are 2, with nothing sent. An image that holds a +# CR or a NUL is one, so its case below expects 2 and never 69; it needs no +# engine and no lane 4 code, and runs `register commit` directly. + +def _with_row(lane: str, sid: str, cell: str, log: str = None) -> dict: + """A prep: test 1's SEED with one more row in `LANES.md`'s table, after + repoA-2's, and the lane's log (its header, then `log`'s lines).""" + lanes = SEED["lanes/LANES.md"] + anchor = next(line for line in lanes.split("\n") if line.startswith("| `repoA-2` |")) + row = (f"| `{lane}` | harness `{sid}` | Eagle / test / brett | 2026-09-01T00:00Z | none " + f"| handoffs/{lane}.md | {cell} |") + header = f"# lane {lane} {EM} object log (lane-collision-protocol Amendment 7)\n" + return {"lanes/LANES.md": lanes.replace(anchor + "\n", anchor + "\n" + row + "\n", 1), + f"lanes/log/{lane}.md": header + (log or "")} + + +#: The starting state three verbs need, or they refuse for want of work (2): +#: `archive-rows <repo>` moves a repository's RETIRED rows; `retire-rows` +#: takes a dormant row, whose log has no lane-kind line and whose cell is not +#: a current state (`lanes-edit.sh:13316-13352` at a2073eae); and +#: `migrate-state-cells` migrates a diary cell, one that is not Amendment +#: 13(a)'s phrase. Each is committed and pushed before the case runs, and on +#: the real engine before the import. +PREPS = { + "archive-rows": _with_row( + "repoZ-2", "eeeeeeee-0002-4000-8000-00000000e002", + f"RETIRED {DOT} 2026-09-03T00:00:00Z {DOT} retired", + f"RETIRED {EM} lane repoZ-2, session eeeeeeee-0002-4000-8000-00000000e002@Eagle, " + f"2026-09-03T00:00:00Z, lane:repoZ-2 {EM} retired\n"), + "retire-rows": _with_row("repoA-4", "aaaaaaaa-0005-4000-8000-00000000a005", + f"MIGRATED {DOT} 2026-09-01T00:00:00Z {DOT} migrated"), + "migrate-state-cells": _with_row("repoA-5", "aaaaaaaa-0006-4000-8000-00000000a006", + f"parked 2026-09-01 {DOT} picked up 2026-09-02"), +} + +#: S1's writes but `commit`: {verb: (its arguments, the lane it writes as)}. +#: The argument forms are `lanes-edit.sh`'s usage lines at a2073eae. +WRITE_VERBS = { + "add-row": (["add-row", f"| `repoA-3` | harness `aaaaaaaa-0004-4000-8000-00000000a004` | " + f"Eagle / test / brett | 2026-11-10T00:00Z | none | handoffs/repoA-3.md | " + f"LIVE {DOT} 2026-11-10T00:00:00Z {DOT} test 2 |"], "repoA-2"), + "append-line": (["append-line", f"HOLD {EM} lane repoA-2 ({WS}), window w, " + f"2026-11-10T00:00:00Z: opensoft/repoB main {TIP} for test 2"], "repoA-2"), + "append-session-id": (["append-session-id", "repoA-2", f"harness `{SID_A2}`", + " (test 2)"], "repoA-2"), + "archive-rows": (["archive-rows", "repoZ", "--yes"], "repoA-2"), + "claim": (["claim", "opensoft/repoA#9", "--no-github"], "repoA-2"), + "log": (["log", "NOTED", "lane:repoA-2", "test 2's write"], "repoA-2"), + "migrate-state-cells": (["migrate-state-cells", "--yes"], "repoA-2"), + "release": (["release", "opensoft/repoA#7", "test 2", "--no-github"], "repoA-1"), + "rename-lane": (["rename-lane", "repoA-2", "repoA-3", "test 2", "--no-github"], "repoA-2"), + "replace-in-row": (["replace-in-row", "repoA-2", "parked", "parked for test 2"], "repoA-2"), + "request-handoff": (["request-handoff", "repoA-1", "--force", "test 2", "--session", + SID_REQUESTER], "repoA-2"), + "retire-rows": (["retire-rows", "repoA-4", "--reason", "test 2"], "repoA-2"), + "set-row-state": (["set-row-state", "repoA-2", f"PAUSED {DOT} test 2"], "repoA-2"), +} + +#: P11's writes that change several files (the test plan's lines 653-656). +LATE_WRITES = { + "LANDING": (["append-line", f"LANDING {EM} lane repoA-2, session {SID_A2}@{WS}, " + f"2026-11-10T00:00:00Z, PR #8 into opensoft/repoA main"], "repoA-2"), + "LANDED": (["append-line", f"LANDED {EM} lane repoA-1, session {SID_A1}@{WS}, " + f"2026-11-10T00:00:00Z, PR #7 into opensoft/repoA main {chr(0x2192)} " + f"abc1234"], "repoA-1"), + "rename-lane": WRITE_VERBS["rename-lane"], + "retire-rows": WRITE_VERBS["retire-rows"], + "archive-rows": WRITE_VERBS["archive-rows"], + "migrate-state-cells": WRITE_VERBS["migrate-state-cells"], +} + +#: EACH LATE WRITE'S LAST STRUCTURED ROW, AND HOW IT IS BROKEN (TP:686-690, +#: "its last structured row breaks a CHECK"; T241i): the `edit-entry` arm's +#: `field` and `value` for the last row of the last list the write's entry +#: carries, in the order `commit_write`'s step 7 applies them, `lanes`, +#: `log_lines`, `register_lines`, then `object_holds` (a2935aee:lanes-index:7282). +#: - A `LANDING` or `LANDED` that `append-line` writes changes `lanes/LANES.md` +#: alone: one `register_lines` row (lane 4's TRIAGE-W12 run 2 logged +#: LANDED's entry: `lanes`, `log_lines` and `object_holds` empty). +#: - `rename-lane`, `retire-rows` and `migrate-state-cells` end with the +#: `log_lines` rows of the lines they add to a log. +#: - `archive-rows` writes `lanes/LANES.md` and the archive alone: its last +#: row is the archived lane's `lanes` row. +#: The `register_lines` and `log_lines` rows lose their `workstation`, which +#: each table's primary CHECK requires (`mode = 'files' OR +#: coalesce(workstation, '') <> ''`, a2935aee:lanes-index:7122 and :7065); the +#: database stamps `mode`, so the row breaks it on primary alone. A `lanes` +#: row has no such CHECK, so it gets a `lane` that is not its key +#: (`lower(lane) = lane_key`, :7038). +LATE_ROWS = { + "LANDING": ("register_lines.-1.workstation", ""), + "LANDED": ("register_lines.-1.workstation", ""), + "rename-lane": ("log_lines.-1.workstation", ""), + "retire-rows": ("log_lines.-1.workstation", ""), + "archive-rows": ("lanes.-1.lane", "t241i-not-its-key"), + "migrate-state-cells": ("log_lines.-1.workstation", ""), +} + +#: AT-3's line, which a writer prints where the switch is not `primary`. +NOT_PRIMARY_LINE = "this estate's register is SQL; configure `mode=primary`" + +#: EACH WRITE LANE'S OWN CHECKOUT, `<c>` (T241e; B14 tasks:1142's T415 +#: bullets; R17). On primary a write reads its pending hand edits, its author +#: and the snapshot's `repos.tsv` from the checkout of the lane it writes for, +#: `<W>-lanes/<lane>`, and refuses with nothing sent where that is not there +#: (2, or 64 for `request-handoff`), since a clone would be D12's fetch. The +#: lanes these writes are for (`lanes-edit.sh`'s `write_lane_of`): repoA-1 and +#: repoA-2, as `LANES_LANE` or a verb's `<lane>`, and repoA-3, `add-row`'s new +#: row. `PrimaryWorkstation` makes `<c>` for each, unless a case asks for none. +WRITE_LANES = ("repoA-1", "repoA-2", "repoA-3") + + +class PrimaryWorkstation: + """A `mode=primary` workstation for `lanes-edit.sh`'s writes: the + files-mode workspace of test 1's sync case (`workspace`), at C, the + flipped copy with `lanes-edit.sh` beside it, and a `lanes-index.conf` + whose `register_url=` and `reader_url=` name `urls`, or a fresh, empty + socket directory, with a 0600 `register_passfile=`. `fakebin` is first on + `PATH`. Each lane in `checkouts` gets `<c>`, its own checkout, a clone of + origin made after the case's prep (`WRITE_LANES` by default).""" + + def __init__(self, tmp_path: Path, urls: tuple = None, fakebin: Path = None, + prep: dict = None, checkouts: tuple = WRITE_LANES): + self.fakebin = fakebin or tmp_path / "fakebin" + self.fakebin.mkdir(parents=True, exist_ok=True) + self.estate, self.env, _source = workspace(tmp_path / "ws", self.fakebin) + if prep: + self._prep(prep) + self.copy = flipped(tmp_path) + self.lanes_edit = self.copy.parent / "lanes-edit.sh" + conf_dir = tmp_path / "conf" + conf_dir.mkdir() + self.passfile = conf_dir / "pgpass" + self.passfile.write_text(f"*:*:*:{WRITER_LOGIN}:{SECRET}\n", encoding="utf-8") + self.passfile.chmod(0o600) + self.dead = tmp_path / "dead" + self.dead.mkdir() + host = quote(self.dead.as_posix(), safe="") + register_url, reader_url = urls or ( + f"postgresql://{WRITER_LOGIN}@{host}:5432/lanes_t241", + f"postgresql://lanes_r_t241@{host}:5432/lanes_t241") + self.conf = primary_config(conf_dir / "lanes-index.conf", register_url, reader_url, + self.passfile) + self.env.update(LANES_INDEX_CONFIG=str(self.conf)) + self.env.pop("LANES_INDEX", None) + for lane in checkouts: + self.make_lane_checkout(lane) + + def _prep(self, files: dict) -> None: + """`files` written over the checkout, committed and pushed, so the + case starts from them; C is that commit.""" + estate = self.estate + for path, text in files.items(): + (estate.checkout / path).parent.mkdir(parents=True, exist_ok=True) + (estate.checkout / path).write_bytes(text.encode("utf-8")) + git(estate.checkout, "add", "-A", env=estate.env) + git(estate.checkout, "commit", "-q", "-m", "C': the case's starting state", + env=estate.env) + git(estate.checkout, "push", "-q", "origin", "main", env=estate.env) + estate.files.update(files) + estate.c = git(estate.checkout, "rev-parse", "HEAD", env=estate.env).strip() + estate.lanes_tree = git(estate.checkout, "rev-parse", f"{estate.c}:lanes", + env=estate.env).strip() + + def lane_checkout(self, lane: str) -> Path: + """`<c>`, lane `lane`'s own register checkout, where `lanes-edit.sh`'s + `lane_checkout_path` puts it (Amendment 23 S1): `<W>-lanes/<lane>`, W + being the real path of `workspace.yaml`'s `path:`, this checkout.""" + real = Path(os.path.realpath(self.estate.checkout)) + return real.parent / f"{real.name}-lanes" / lane + + def make_lane_checkout(self, lane: str) -> Path: + """`<c>` for `lane`, a clone of W's origin, as `lane-checkout <lane> + --create` makes one.""" + target = self.lane_checkout(lane) + target.parent.mkdir(parents=True, exist_ok=True) + git(target.parent, "clone", "-q", str(self.estate.origin), str(target), + env=self.estate.env) + return target + + def run(self, argv: list, lane: str | None, **extra) -> subprocess.CompletedProcess: + """`lanes-edit.sh <argv>` in the checkout, as lane `lane` + (`LANES_LANE`), or with `LANES_LANE` unset where `lane` is None.""" + env = dict(self.env, **extra) + if lane is None: + env.pop("LANES_LANE", None) + else: + env["LANES_LANE"] = lane + return subprocess.run(["bash", str(self.lanes_edit), *argv], capture_output=True, + encoding="utf-8", errors="replace", env=env, timeout=120, + cwd=str(self.estate.checkout), check=False, + stdin=subprocess.DEVNULL) + + def git_state(self) -> tuple: + """AT-2's git oracle: the checkout's HEAD, status, index digest and + `origin/main`, the files under `lanes/`, and origin's refs.""" + lanes = self.estate.checkout / "lanes" + files = {p.relative_to(lanes).as_posix(): hashlib.sha256(p.read_bytes()).hexdigest() + for p in sorted(lanes.rglob("*")) if p.is_file()} + refs = git(self.estate.origin, "for-each-ref", "--format=%(refname) %(objectname)", + env=self.estate.env) + return self.estate.state(), files, refs + + +def unreachable_answers(dead: Path) -> list: + """The fake's answer for every call that carries a request: `psql`'s own + exit 2 and its text for an empty socket directory (AT-2, "Unreachable + (FP)").""" + socket = dead / ".s.PGSQL.5432" + return [{"exit": 2, "stderr": f'psql: error: connection to server on socket "{socket}" ' + f"failed: No such file or directory\n\tIs the server running " + f"locally and accepting connections on that socket?\n"}] + + +def _lock_files(ws: PrimaryWorkstation) -> list: + """The writers' mutexes left anywhere under the workspace: the lane + checkout's and any scratch tree's `.lanes-edit.lock` (`lanes-edit.sh`'s + `LOCK`, :1212 at a2073eae; `design.md` S1, step 2), and git's + `index.lock`.""" + root = ws.estate.root + return sorted(p.relative_to(root).as_posix() for p in root.rglob("*") + if p.name in (".lanes-edit.lock", "index.lock")) + + +# ------------------------------------------------------------ no engine (FP) + +@pytest.mark.parametrize("verb", list(WRITE_VERBS)) +def test_each_write_exits_69_when_the_database_is_unreachable(tmp_path, verb): + """AT-2, "Unreachable (FP)": with every `psql` call answered by `psql`'s + exit 2 and its "connection to server ... failed" text, `lanes-edit.sh + <verb>` on primary exits 69; stderr names the store and the error with + no credential and no URL; a read verb's stdout is empty; the fake's log + shows the writer connected with `register_url=`'s login and + `register_passfile=`, `PGPASSWORD` never set, and no call after the + failed one (no retry that reads as a write, no fallback); and git is as + it was (the checkout, the files under `lanes/`, origin's refs).""" + ws = PrimaryWorkstation(tmp_path, prep=PREPS.get(verb)) + fake = fake_psql_dir(ws.fakebin, answers=unreachable_answers(ws.dead)) + ws.env.update(fake) + argv, lane = WRITE_VERBS[verb] + before = ws.git_state() + proc = ws.run(argv, lane) + said = proc.stdout + proc.stderr + assert proc.returncode == 69, ( + f"lanes-edit.sh {verb} on primary exited {proc.returncode}, not 69, with the database " + f"unreachable (L4-B3, T415's attempt loop): {proc.stderr[-800:]}") + assert "connection to server" in proc.stderr, f"stderr names no error: {proc.stderr!r}" + assert SECRET not in said and not re.search(r"postgres(ql)?://", said), said + calls = fake_calls(fake) + assert len(calls) == 1, ( + f"{len(calls)} psql calls carried a request, not one: a call followed the failed one " + f"(a retry that reads as a write, or a fallback): {calls}") + for call in calls: + assert call["url"].startswith(f"postgresql://{WRITER_LOGIN}@"), call["url"] + assert call["passfile"] == str(ws.passfile) and call["pgpassword"] is False, call + assert ws.git_state() == before, "git changed: a write fell back to the files" + + +@pytest.mark.parametrize("write", ["commit-carry", "push-beyond-handoffs"]) +def test_each_direct_write_refuses_with_2_on_primary(tmp_path, write): + """D10, as T420 builds it at 1b (B10 tasks:1213-1231; R16): on primary, + `commit`'s carry form (a hand edit under `lanes/`, staged and committed by + `lanes-edit.sh commit`) and a push of a commit that changes a path + outside `handoffs/` (T420's backstop) each exit 2 before any SQL: the + fake's log holds no call that carries a request, the files under `lanes/` + are as they were, and origin's refs are unchanged. The captures and + `add-row`'s compensating commit do not exist at 1b (T420: "compensat" + matches nothing), so they have no id.""" + ws = PrimaryWorkstation(tmp_path) + fake = fake_psql_dir(ws.fakebin, answers=unreachable_answers(ws.dead)) + ws.env.update(fake) + checkout = ws.estate.checkout + if write == "commit-carry": + target = checkout / "lanes" / "LANES.md" + target.write_bytes(target.read_bytes() + b"a hand edit\n") + argv = ["commit", "a hand edit, carried"] + else: + (checkout / "notes.md").write_text("outside handoffs/\n", encoding="utf-8") + git(checkout, "add", "notes.md", env=ws.estate.env) + git(checkout, "commit", "-q", "-m", "a queued commit outside handoffs/", + env=ws.estate.env) + argv = ["commit", "publish the queued commit"] + refs = git(ws.estate.origin, "for-each-ref", "--format=%(refname) %(objectname)", + env=ws.estate.env) + lanes_before = {p: (checkout / p).read_bytes() for p in SEED if (checkout / p).exists()} + proc = ws.run(argv, "repoA-1") + assert proc.returncode == 2, ( + f"{write} on primary exited {proc.returncode}, not 2 (D10; L4-B11, T420): " + f"{proc.stderr[-800:]}") + assert fake_calls(fake) == [], f"a direct write reached SQL: {fake_calls(fake)}" + assert git(ws.estate.origin, "for-each-ref", "--format=%(refname) %(objectname)", + env=ws.estate.env) == refs, "origin moved" + if write == "push-beyond-handoffs": + assert {p: (checkout / p).read_bytes() for p in lanes_before} == lanes_before + + +def test_a_hand_edit_commit_is_refused_on_primary(tmp_path): + """GB section 4.3's D10 case (R29; R16): `lanes-edit.sh commit`'s carry + form, over a hand edit of `lanes/LANES.md`, exits 2 on primary, says the + register is SQL, reaches no SQL, and leaves the file, the index, HEAD and + origin as they were (the test plan's line 734).""" + ws = PrimaryWorkstation(tmp_path) + fake = fake_psql_dir(ws.fakebin, answers=unreachable_answers(ws.dead)) + ws.env.update(fake) + target = ws.estate.checkout / "lanes" / "LANES.md" + target.write_bytes(target.read_bytes() + b"a hand edit\n") + edited = target.read_bytes() + before = ws.estate.state() + proc = ws.run(["commit", "a hand edit"], "repoA-1") + assert proc.returncode == 2, ( + f"a hand-edit commit on primary exited {proc.returncode}, not 2 (D10; T420's carry " + f"form): {proc.stderr[-800:]}") + assert fake_calls(fake) == [], f"the refusal reached SQL: {fake_calls(fake)}" + assert target.read_bytes() == edited, "the hand edit was changed" + assert ws.estate.state() == before, "HEAD, the index or origin moved" + + +def _queue(ws: PrimaryWorkstation, path: str, text: str) -> str: + """A local commit, not pushed, that writes `path`. Returns its sha.""" + checkout = ws.estate.checkout + target = checkout / path + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(text.encode("utf-8")) + git(checkout, "add", "--", path, env=ws.estate.env) + git(checkout, "commit", "-q", "-m", f"queued: {path}", env=ws.estate.env) + return git(checkout, "rev-parse", "HEAD", env=ws.estate.env).strip() + + +def test_a_queued_handoff_commit_is_still_published(tmp_path): + """GB section 4.3's D10 case (R16): on primary, the publish act stays, + fenced to `handoffs/`. A queued local commit that writes only + `handoffs/repoA-1.md` is published by `lanes-edit.sh commit` with nothing + staged: it exits 0, origin's `main` is that commit, and no `psql` call is + made, since `commit` is exempt from the attempt loop (T420, review M2).""" + ws = PrimaryWorkstation(tmp_path) + fake = fake_psql_dir(ws.fakebin, answers=unreachable_answers(ws.dead)) + ws.env.update(fake) + sha = _queue(ws, "handoffs/repoA-1.md", "# repoA-1's handoff, queued\n") + proc = ws.run(["commit", "publish the queued commit"], "repoA-1") + assert proc.returncode == 0, ( + f"the publish act exited {proc.returncode} on primary (T420 keeps it): " + f"{proc.stderr[-800:]}") + assert git(ws.estate.origin, "rev-parse", "refs/heads/main", + env=ws.estate.env).strip() == sha, "the queued handoff commit was not published" + assert fake_calls(fake) == [], f"the publish act reached SQL: {fake_calls(fake)}" + + +def test_a_queued_lanes_commit_is_refused_as_a_divergence(tmp_path): + """GB section 4.3's D10 case (R16): on primary, a queued local commit that + writes under `lanes/` is refused by the publish act as a divergence: a + nonzero exit that names the divergence and the commit, no push (origin's + refs unchanged), no SQL, and the local commit left for the operator.""" + ws = PrimaryWorkstation(tmp_path) + fake = fake_psql_dir(ws.fakebin, answers=unreachable_answers(ws.dead)) + ws.env.update(fake) + refs = git(ws.estate.origin, "for-each-ref", "--format=%(refname) %(objectname)", + env=ws.estate.env) + lanes = ws.estate.checkout / "lanes" / "LANES.md" + sha = _queue(ws, "lanes/LANES.md", lanes.read_text(encoding="utf-8") + "queued\n") + proc = ws.run(["commit", "publish the queued commit"], "repoA-1") + assert proc.returncode == 2, ( + f"a queued lanes/ commit on primary exited {proc.returncode}, not 2 (T420's fence): " + f"{proc.stderr[-800:]}") + assert "diverge" in proc.stderr.lower() and sha[:7] in proc.stderr, proc.stderr + assert git(ws.estate.origin, "for-each-ref", "--format=%(refname) %(objectname)", + env=ws.estate.env) == refs, "origin moved" + assert git(ws.estate.checkout, "rev-parse", "HEAD", env=ws.estate.env).strip() == sha + assert fake_calls(fake) == [], f"the refusal reached SQL: {fake_calls(fake)}" + + +#: An image that breaks the register's text: a line holding a CR, and one +#: holding a NUL, each in `lanes/LANES.md`'s new image. +BAD_IMAGES = {"image-cr": "\r", "image-nul": "\0"} + + +@pytest.mark.parametrize("bad", list(BAD_IMAGES)) +def test_an_image_holding_a_cr_or_a_nul_is_refused_with_2_and_nothing_sent(tmp_path, bad): + """Lane 3's reading 3 of T112 (#165 6755386771; F10-OWED item 31; contract + section 3.3, "a listed file breaks its format ... 2"): `register commit` + over an attempt directory whose image of `lanes/LANES.md` holds a CR (the + line ends CRLF) or a NUL exits 2, never 69, before anything is sent: no + `psql` call at all, not even T106's `--version` probe, and the attempt + directory is as it was. Stderr names the image's path. No engine and no + lane 4 code: the directory is built by hand, in section 3.3's table.""" + copy = flipped(tmp_path) + fake = fake_psql_dir(tmp_path / "fakebin", answers=[{"exit": 3, "stderr": + "ERROR: XX000: never sent\n"}]) + estate = Estate(tmp_path / "estate") + conf_dir = tmp_path / "conf" + conf_dir.mkdir() + passfile = conf_dir / "pgpass" + passfile.write_text(f"*:*:*:{WRITER_LOGIN}:{SECRET}\n", encoding="utf-8") + passfile.chmod(0o600) + host = quote((tmp_path / "dead").as_posix(), safe="") + conf = primary_config(conf_dir / "lanes-index.conf", + f"postgresql://{WRITER_LOGIN}@{host}:5432/lanes_t241", + f"postgresql://lanes_r_t241@{host}:5432/lanes_t241", passfile) + env = index_env(tmp_path, conf, estate.home, **fake) + env["PATH"] = str(tmp_path / "fakebin") + os.pathsep + _masked_path() + + write_id, generation = str(uuid.uuid4()), str(uuid.uuid4()) + args_sha256 = hashlib.sha256(b"t241 " + bad.encode("ascii")).hexdigest() + not_after = str(int(time.time()) + 300) + attempt = tmp_path / "attempt" + path = "lanes/LANES.md" + old = SEED[path].encode("utf-8") + new = old + (f"HOLD {EM} lane repoA-2 ({WS}), window w, 2026-11-10T00:00:00Z: " + f"opensoft/repoB main {TIP} for a check{BAD_IMAGES[bad]}").encode("utf-8") + new += b"\n" + blob = lambda data: hashlib.sha1(b"blob %d\0" % len(data) + data).hexdigest() # noqa: E731 + (attempt / "images" / "lanes").mkdir(parents=True) + (attempt / "images" / path).write_bytes(new) + (attempt / "tree").mkdir() + (attempt / "snapshot").write_text( + f"format=1\nwrite_id={write_id}\ngeneration={generation}\nn=5\n" + f"not_after={not_after}\nclock={int(time.time())}\n", encoding="utf-8") + (attempt / "not_after").write_text(not_after + "\n", encoding="utf-8") + (attempt / "changes.tsv").write_text(f"M\t{path}\t{blob(old)}\t{blob(new)}\n", + encoding="utf-8") + (attempt / "files").write_text(_canonical_rows([("M", path, "", "")], {path: new}), + encoding="utf-8") + (attempt / "msg").write_text("lanes-edit.sh append-line: test 2's bad image\n", + encoding="utf-8") + (attempt / "author").write_text(AUTHOR + "\n", encoding="utf-8") + before = {p.relative_to(attempt).as_posix(): p.read_bytes() + for p in sorted(attempt.rglob("*")) if p.is_file()} + + proc = run_index(copy, ["register", "commit", "--write-id", write_id, "--generation", + generation, "--lane", "repoA-2", "--verb", "append-line", + "--args-sha256", args_sha256, "--workstation", WS, attempt], env) + assert proc.returncode != 69, ( + f"an image holding {bad[6:].upper()} gave 69; lane 3's reading 3 makes it 2: " + f"{proc.stderr}") + assert proc.returncode == 2, f"register commit exited {proc.returncode}: {proc.stderr}" + assert f"images/{path}" in proc.stderr, f"stderr names no image: {proc.stderr!r}" + log = Path(fake["FAKE_PSQL_LOG"]) + assert not log.exists() or log.read_text(encoding="utf-8") == "", ( + f"psql was called before the refusal: {log.read_text(encoding='utf-8')}") + assert {p.relative_to(attempt).as_posix(): p.read_bytes() + for p in sorted(attempt.rglob("*")) if p.is_file()} == before + + +# REQUEST-HANDOFF'S 64S (lane 2's T241d; R-F13c-23; lane 3's batch 8, #165 +# 6780753157, Q35 and its text change 5 for B14 tasks:1149; lane 4's +# questions, `QUESTIONS-L3-1110g-b-a5582b2d.md`, 35). On primary every write +# runs four checks before its claim (B14 tasks:1142's T415 bullets): it names +# its lane, the lane's own checkout `<c>` is there (`lanes-edit.sh +# lane-checkout <lane> --create` makes it; a write makes no clone, which +# would be D12's fetch), `LANES_LANE` is a lane name, and `LANES_NO_GIT=1` is +# not set. Each refuses with nothing sent: 2 for every verb but +# `request-handoff`, which refuses 64, never 2, since `lane` reads a 2 from it +# as "lane <L> is still bound elsewhere" (REV415b NIT 6's reason). `lane` +# calls it with no `LANES_LANE` (lane 4's question 35), and lane 3 rules that +# `lane` sets it (T432), and that the verb's refusal is 64 all the same. +# +# The write's lane is `request-handoff`'s `<lane>`, repoA-1, and its `<c>` is +# `<W>-lanes/repoA-1`. Every check but the id's own is met, so each id meets +# its own refusal and no other: `<c>` is made first, a clone of origin, but +# for `[missing-checkout]`. No engine; fails until lane 4's T415 takes Q35. +# +# Lane 3's batch c, Q67 (#165 6807881675; B15 text 5 for B14 tasks:1149 and +# text 7 for F13d:513), adds the two other refusals the primary branch makes +# before its claim: a pending hand edit of a rendered file in `<c>` +# (`pw_hand_edit_refuse`, `[hand-edit]`) and no author identity in `<c>` +# (`pw_author_read`, `[no-author]`). Each is 64 for `request-handoff`, by +# `pw_pre_rc`. They fail until lane 4's T415 takes Q67; the first four ids +# pass on lane 4's T415 `15af6b9c`. + +#: The arguments `WRITE_VERBS` gives `request-handoff`, and its `<lane>`. +REQUEST_HANDOFF_ARGV = WRITE_VERBS["request-handoff"][0] +REQUEST_HANDOFF_LANE = REQUEST_HANDOFF_ARGV[1] + +#: {id: (the arguments, `LANES_LANE` or None for it unset, what the run adds +#: to the environment, whether `<c>` is made first, what stderr names)}. +REQUEST_HANDOFF_64 = { + # No `<lane>`: the arm's own usage code (B14 tasks:1162). + "missing-lane": (["request-handoff"], "repoA-2", {}, True, "request-handoff <lane>"), + # B14 tasks:1149: refused "before the claim, naming it". + "no-git": (REQUEST_HANDOFF_ARGV, "repoA-2", {"LANES_NO_GIT": "1"}, True, "LANES_NO_GIT"), + # `pw_lane_given`: `LANES_LANE` unset, as `lane` calls the verb; B14 + # tasks:1142, "naming the command with it". + "lane-given": (REQUEST_HANDOFF_ARGV, None, {}, True, "LANES_LANE"), + # B14 tasks:1142: "naming `lanes-edit.sh lane-checkout <lane> --create`". + "missing-checkout": (REQUEST_HANDOFF_ARGV, "repoA-2", {}, False, + f"lane-checkout {REQUEST_HANDOFF_LANE} --create"), + # Q67, `pw_hand_edit_refuse`: Y:2459's refusal names each file. + "hand-edit": (REQUEST_HANDOFF_ARGV, "repoA-2", {}, True, "lanes/LANES.md"), + # Q67, `pw_author_read`: "no author identity in `<c>`" (B15 text 5). + "no-author": (REQUEST_HANDOFF_ARGV, "repoA-2", {}, True, "author identity"), +} + + +def _hand_edit_in_c(ws: PrimaryWorkstation, checkout: Path) -> None: + """A pending hand edit of a rendered file in `<c>`: a line appended to + its `lanes/LANES.md`, not committed (B14 tasks:1151, "looked for in the + lane checkout").""" + with open(checkout / "lanes" / "LANES.md", "a", encoding="utf-8") as handle: + handle.write("a hand edit in the lane's checkout, never committed\n") + + +def _no_author_in_c(ws: PrimaryWorkstation, checkout: Path) -> None: + """No author identity in `<c>`: the run loses the estate's `GIT_AUTHOR_*` + (and any `EMAIL`), and `<c>` sets `user.useConfigOnly`, so `git -C <c> + var GIT_AUTHOR_IDENT` gives none, whatever the host's name; the global + and system configurations are already empty (`git_env`).""" + for name in ("GIT_AUTHOR_NAME", "GIT_AUTHOR_EMAIL", "EMAIL"): + ws.env.pop(name, None) + git(checkout, "config", "user.useConfigOnly", "true", env=ws.estate.env) + + +#: What a `REQUEST_HANDOFF_64` id does to `<c>` before its run, where it does +#: anything. +REQUEST_HANDOFF_C_PREP = {"hand-edit": _hand_edit_in_c, "no-author": _no_author_in_c} + + +@pytest.mark.parametrize("refusal", list(REQUEST_HANDOFF_64)) +def test_request_handoff_refuses_64_never_2_on_primary(tmp_path, refusal): + """Lane 3's batch 8, Q35 (B15 text 5 for B14 tasks:1149): on primary, + `request-handoff` refuses 64, never 2, for its missing lane + (`[missing-lane]`, no `<lane>` at all), `LANES_NO_GIT=1` (`[no-git]`), + `pw_lane_given`'s refusal (`[lane-given]`, `LANES_LANE` unset), a + missing `<c>`, the lane's own checkout (`[missing-checkout]`), and, by + lane 3's batch c, Q67 (B15 text 7 for F13d:513), a pending hand edit of + a rendered file in `<c>` (`[hand-edit]`) and no author identity in + `<c>` (`[no-author]`), since `lane` reads a 2 from it as "lane <L> is + still bound elsewhere". Each is a refusal before the claim: stderr names + its cause, the fake's log holds no call that carries a request, git is + as it was, and no clone is made. The other writer verbs' `LANES_NO_GIT=1` + refusal stays 2 (B14 tasks:1149), and is not this case's. Its first four + ids fail until lane 4's T415 takes Q35, and pass on T415 `15af6b9c`; + `[missing-lane]` passes before it, since main's arm already refuses a + missing lane 64, and holds that code against a 2. `[hand-edit]` and + `[no-author]` fail until lane 4's T415 takes Q67.""" + argv, lane, extra, with_checkout, names = REQUEST_HANDOFF_64[refusal] + ws = PrimaryWorkstation(tmp_path, + checkouts=(REQUEST_HANDOFF_LANE,) if with_checkout else ()) + fake = fake_psql_dir(ws.fakebin, answers=unreachable_answers(ws.dead)) + ws.env.update(fake) + checkout = ws.lane_checkout(REQUEST_HANDOFF_LANE) + if refusal in REQUEST_HANDOFF_C_PREP: + REQUEST_HANDOFF_C_PREP[refusal](ws, checkout) + before = ws.git_state() + proc = ws.run(argv, lane, **extra) + assert proc.returncode != 2, ( + f"request-handoff on primary refused [{refusal}] with 2, which `lane` reads as 'lane " + f"{REQUEST_HANDOFF_LANE} is still bound elsewhere' (Q35, Q67; lane 4's T415): " + f"{proc.stderr[-800:]}") + assert proc.returncode == 64, ( + f"request-handoff on primary exited {proc.returncode} for [{refusal}], not 64 (Q35, " + f"Q67; lane 4's T415): {proc.stderr[-800:]}") + assert names in proc.stderr, f"stderr does not name {names!r}: {proc.stderr!r}" + assert fake_calls(fake) == [], f"the refusal reached SQL: {fake_calls(fake)}" + assert ws.git_state() == before, "git changed: the refusal wrote" + assert checkout.is_dir() == with_checkout, ( + f"the refusal {'removed' if with_checkout else 'made'} {checkout}: a write on primary " + f"makes no clone (D12)") + + +# ------------------------------------------------------------ real engine (RE) + +class RegisterWorkstation(PrimaryWorkstation): + """`PrimaryWorkstation` over the test's database: its workspace's C is + imported and brought to `primary` with the marker `present` (test 1's + `import_to_primary`), and `lanes-edit.sh` connects as this module's + logins, through T203's `psql` shim, first on `PATH`, which hands every + call to the cluster's `psql` until a case arms it.""" + + def __init__(self, pg, tmp_path: Path, prep: dict = None): + fakebin = tmp_path / "fakebin" + fakebin.mkdir(parents=True, exist_ok=True) + (fakebin / "psql").write_text(PSQL_SHIM, encoding="utf-8") + (fakebin / "psql").chmod(0o755) + (fakebin / PSQL_SHIM_CONTROL).write_text(json.dumps({"psql": pg.psql_bin}), + encoding="utf-8") + ensure_logins(pg) + super().__init__(tmp_path, (pg.url(LOGIN_WRITER), pg.url(LOGIN_READER)), fakebin, + prep) + self.pg = pg + import_to_primary(pg, self.estate) + + def arm(self, arms: list) -> None: + (self.fakebin / PSQL_SHIM_CONTROL).write_text( + json.dumps({"psql": self.pg.psql_bin, "arms": arms}), encoding="utf-8") + + def shim_calls(self) -> list: + log = self.fakebin / PSQL_SHIM_LOG + if not log.exists(): + return [] + entries = [json.loads(x) for x in log.read_text(encoding="utf-8").splitlines() if x] + return [e for e in entries if e.get("kind") != "version"] + + def db_digest(self) -> dict: + """Each register table, the journal and the head row, copied out in + a fixed order and digested (AT-2's database oracle).""" + tables = [r["t"] for r in rows(self.pg, f"SELECT table_name AS t FROM " + f"information_schema.tables WHERE table_schema " + f"= '{SCHEMA}' AND table_type = 'BASE TABLE' " + f"ORDER BY 1")] + return {t: rows(self.pg, f"SELECT md5(coalesce(string_agg(x::text, E'\\n' ORDER BY " + f"x::text), '')) AS d FROM {t} x")[0]["d"] for t in tables} + + def foreign_locks(self) -> list: + return rows(self.pg, "SELECT pid, locktype, mode FROM pg_locks WHERE pid <> " + "pg_backend_pid() AND pid IN (SELECT pid FROM pg_stat_activity " + "WHERE application_name NOT LIKE 't210%' AND backend_type = " + "'client backend')") + + +def _commit_calls(ws: RegisterWorkstation) -> list: + return [c for c in ws.shim_calls() if "commit_write(" in (c.get("stdin") or "")] + + +@pytest.mark.parametrize("verb", list(WRITE_VERBS)) +def test_each_write_exits_69_when_the_switch_is_not_primary(pg, tmp_path, verb): + """AT-2, "Refused: the switch" (P170-171): with the switch row set to + `files`, `lanes-edit.sh <verb>` exits 69, stderr carries AT-3's line, + the register's tables and git are unchanged, and no commit call is sent + twice.""" + ws = RegisterWorkstation(pg, tmp_path, PREPS.get(verb)) + sql(pg, f"UPDATE {SCHEMA}.register_switch SET mode = 'files', marker_state = 'absent';") + before_db, before_git = ws.db_digest(), ws.git_state() + argv, lane = WRITE_VERBS[verb] + proc = ws.run(argv, lane) + assert proc.returncode == 69, f"{verb} exited {proc.returncode}: {proc.stderr[-800:]}" + assert NOT_PRIMARY_LINE in proc.stderr, proc.stderr + assert ws.db_digest() == before_db and ws.git_state() == before_git + assert len(_commit_calls(ws)) <= 1, "a refused commit call was sent again" + + +@pytest.mark.parametrize("verb", list(WRITE_VERBS)) +def test_each_write_exits_69_when_the_database_refuses_the_transaction(pg, tmp_path, verb): + """AT-2, "Refused: a GRANT": with `EXECUTE` on `commit_write` revoked from + `lanes_register_writer`, the commit call fails with 42501 and the write + exits 69; then, with that restored and `SELECT` on `register_head` + revoked, the snapshot is refused and the write exits 69. Each time the + register's tables and git are unchanged, stderr names the store and the + error without credentials, and the refused commit call is never sent + again (R02: no resend).""" + ws = RegisterWorkstation(pg, tmp_path, PREPS.get(verb)) + argv, lane = WRITE_VERBS[verb] + signature = f"{SCHEMA}.commit_write(bigint, uuid, integer, uuid, jsonb)" + for revoke, grant, code in ( + (f"REVOKE EXECUTE ON FUNCTION {signature} FROM {WRITER};", + f"GRANT EXECUTE ON FUNCTION {signature} TO {WRITER};", "42501"), + (f"REVOKE SELECT ON {SCHEMA}.register_head FROM {WRITER};", + f"GRANT SELECT ON {SCHEMA}.register_head TO {WRITER};", "42501")): + sql(pg, revoke) + before_db, before_git, calls = ws.db_digest(), ws.git_state(), len(_commit_calls(ws)) + proc = ws.run(argv, lane) + sql(pg, grant) + assert proc.returncode == 69, f"{verb} exited {proc.returncode}: {proc.stderr[-800:]}" + assert code in proc.stderr and "postgresql://" not in proc.stderr, proc.stderr + assert ws.db_digest() == before_db and ws.git_state() == before_git + assert len(_commit_calls(ws)) - calls <= 1, "a refused commit call was sent again" + + +def _unarmed_control(pg, tmp_path: Path, write: str) -> None: + """THE CONTROL (T241j; lane 3's ruling, #165 6833755920): `write`, with no + arm, on an estate of its own in a database of its own on the same cluster, + made the way the armed case makes its own, must exit 0 on primary. Where + it does not, the write fails there by itself, and the armed case could + not tell its injected row's 23514 from the write's own, so the case fails + here, saying that it is the control.""" + name = pg.cluster.new_database() + try: + control = RegisterWorkstation(Database(pg.cluster, name), tmp_path / "control", + PREPS.get(write)) + argv, lane = LATE_WRITES[write] + proc = control.run(argv, lane) + finally: + pg.cluster.drop_database(name) + assert proc.returncode == 0, ( + f"THE CONTROL FAILED, NOT THE INJECTED ROW: {write} with no edit-entry arm, on an " + f"estate and a database of its own, exited {proc.returncode} on primary, so the " + f"armed case cannot show that a 23514 is its injected row's. Its stderr ends: " + f"{proc.stderr[-800:]}") + + +@pytest.mark.parametrize("write", list(LATE_WRITES)) +def test_a_failure_in_a_late_statement_leaves_journal_lines_and_head_unchanged(pg, tmp_path, + write): + """AT-2, "Partway" (P11; D6; TP:686-690): the shim's `edit-entry` rewrites + commit call 1's entry so that its last structured row breaks a CHECK, as + `LATE_ROWS` names it for each write: the transaction fails with 23514 + after the head row, the line edits and the earlier rows changed inside + it. The shim's log shows the arm applied to commit call 1 with no error, + so an arm the shim cannot apply fails here first, not as an exit 0 when + the next attempt commits unarmed. The write exits 69; the journal, the + line store and the head row are unchanged (each table's digest); git is + unchanged; the refused call is never sent again. + + NO WRITE HERE CARRIES A HOLD ROW (T241i; lane 4's #165 6827643168, item + 5): every log line these writes add, or carry through a rename, names a + lane's own object, `lane:<name>` (a LANDING or LANDED adds none), and + `register_hold_object` gives no hold for those + (a2935aee:lanes-index:11570), so T241b's + `object_holds.-1.exempt` found an empty list. Nor could a hold row's + `exempt` break a CHECK on a write: `commit_write` stores it only for an + import (`v_kind = 'import' AND coalesce(x.exempt, false)`, + a2935aee:lanes-index:7656). It needs T203d's shim, which names a list's + element by its index, a negative one from the list's end. + + THE CONTROL COMES FIRST (T241j; lane 3's ruling, #165 6833755920): the + same write, unarmed, on an estate and a database of its own, must exit + 0 (`_unarmed_control`). Where the write fails on primary by itself, its + own 23514 would pass this case for the injected row's, so the case fails + at the control instead. `[rename-lane]` and `[migrate-state-cells]` fail + there until their own causes are fixed, by a task lanes 4 and 1 name + (HW17: the renamed log's lines go out as unreadable `log_lines` rows + stamped primary, and migrated lines carry a time with no seconds).""" + _unarmed_control(pg, tmp_path, write) + ws = RegisterWorkstation(pg, tmp_path, PREPS.get(write)) + field, value = LATE_ROWS[write] + ws.arm([{"mode": "edit-entry", "match": "commit_write", "call": 1, + "field": field, "value": value}]) + before_db, before_git = ws.db_digest(), ws.git_state() + argv, lane = LATE_WRITES[write] + proc = ws.run(argv, lane) + commits = _commit_calls(ws) + assert commits and commits[0]["arms"] == ["edit-entry"] and "error" not in commits[0], \ + f"the shim did not rewrite {field} in commit call 1: " \ + f"{commits[0].get('error') if commits else 'no commit call'}" + assert proc.returncode == 69, f"{write} exited {proc.returncode}: {proc.stderr[-800:]}" + assert "23514" in proc.stderr, proc.stderr + assert ws.db_digest() == before_db and ws.git_state() == before_git + assert len(commits) == 1, "the failed commit call was sent again" + + +@pytest.mark.parametrize("verb", list(WRITE_VERBS)) +def test_a_refused_write_leaves_no_lock(pg, tmp_path, verb): + """AT-2's lock oracle: a write refused with the database unreachable (the + shim's `fail-match` on every call) leaves no mutex, neither the scratch + tree's nor the lane checkout's, and no scratch tree; once the fault is + removed, the same write made at once exits 0; and `pg_locks` shows no + lock held by another client backend.""" + ws = RegisterWorkstation(pg, tmp_path, PREPS.get(verb)) + ws.arm([{"mode": "fail-call", "from": 1}]) + argv, lane = WRITE_VERBS[verb] + proc = ws.run(argv, lane) + assert proc.returncode == 69, f"{verb} exited {proc.returncode}: {proc.stderr[-800:]}" + assert _lock_files(ws) == [], f"a mutex was left: {_lock_files(ws)}" + ws.arm([]) + again = ws.run(argv, lane) + assert again.returncode == 0, f"the write after the fault exited {again.returncode}: " \ + f"{again.stderr[-800:]}" + assert ws.foreign_locks() == [], ws.foreign_locks() + + +def test_a_pending_hand_edit_names_the_file_and_a_recovery_that_works(pg, tmp_path): + """P361-365 (TP:764-769 and Y:2505-2507, "in the writing lane's + checkout"; B14 tasks:1151, "It is looked for in the lane checkout"): with + a hand edit of `lanes/LANES.md` pending in the writing lane's own + checkout `<c>` (`<W>-lanes/<lane>`, which `RegisterWorkstation` makes), + a write refuses with exit 2 (spec.md:1131; tasks:1157, "a pending hand + edit refuses 2") before its snapshot (the shim's log is empty), naming the + file and one recovery command, the one backticked `git` command in its + stderr, its argv by `shlex.split` the restore of that file alone; running it, + with no shell, in `<c>` leaves `<c>`'s `status --porcelain` empty, and + the next write exits 0. Its stderr prints no `lanes-edit.sh commit` + (the delta spec's sql-register/spec.md:518). W's own checkout holds no edit: lane + 4's answer (#165 6808439918) puts the edit in `<c>`, and keeps this + oracle. It fails until lane 4's T415 round that prints that one command, + `git -C <c> restore --source=HEAD --staged --worktree -- <paths>`, in + backticks, with its read line holding none; T415 `15af6b9c` prints both + as plain notes.""" + ws = RegisterWorkstation(pg, tmp_path) + argv, lane = WRITE_VERBS["set-row-state"] + checkout = ws.lane_checkout(lane) + target = checkout / "lanes" / "LANES.md" + target.write_bytes(target.read_bytes() + b"a pending hand edit\n") + proc = ws.run(argv, lane) + assert proc.returncode == 2 and ws.shim_calls() == [], (proc.returncode, ws.shim_calls()) + assert "lanes/LANES.md" in proc.stderr, proc.stderr + commands = re.findall(r"`(git [^`]+)`", proc.stderr) + assert len(commands) == 1, f"the refusal names {len(commands)} recovery commands: " \ + f"{proc.stderr!r}" + # The delta spec, sql-register/spec.md:518: "It SHALL NOT print `lanes-edit.sh + # commit` as the recovery." Looked for in the whole stderr, backticked or not, + # after a `LANES_LANE=<lane>` or a path, and with a quote closing the path. + published = re.findall(r"lanes-edit\.sh['\"]?\s+commit\b", proc.stderr) + assert published == [], ( + f"the refusal prints `lanes-edit.sh commit` {len(published)} time(s), the recovery " + f"the delta spec forbids (spec.md:518): {proc.stderr!r}") + restore = shlex.split(commands[0]) + # Its paths as `pw_hand_edit_refuse` lists them: `git diff --name-only HEAD`'s, + # relative to `<c>`'s top, each through `printf '%q'`. `<c>` is a fresh clone, + # so the file edited above is the one path that differs. + edited = [target.relative_to(checkout).as_posix()] + expected = ["git", "-C", str(checkout), "restore", "--source=HEAD", "--staged", "--worktree", + "--", *edited] + assert restore == expected, ( + f"the recovery command's argv is {restore}, not {expected}, the restore of the " + f"hand-edited file and no other") + subprocess.run(restore, shell=False, cwd=str(checkout), env=ws.estate.env, check=True, + capture_output=True) + assert git(checkout, "status", "--porcelain", env=ws.estate.env) == "" + assert ws.run(argv, lane).returncode == 0 + + +def test_a_write_goes_on_with_the_service_down(pg, tmp_path): + """Round 1's 4A: with no service started (no socket under the service's + directory), a write goes on through its own transaction (the journal + gains one entry) and never falls back to the files (the checkout's + `lanes/` unchanged).""" + ws = RegisterWorkstation(pg, tmp_path) + before = rows(pg, f"SELECT count(*) AS n FROM {SCHEMA}.journal")[0]["n"] + lanes_before = ws.git_state()[1] + argv, lane = WRITE_VERBS["log"] + proc = ws.run(argv, lane) + assert proc.returncode == 0, f"log exited {proc.returncode}: {proc.stderr[-800:]}" + assert rows(pg, f"SELECT count(*) AS n FROM {SCHEMA}.journal")[0]["n"] == before + 1 + assert ws.git_state()[1] == lanes_before, "the write fell back to the files"