From b65d836b4ea939a43f89cf4e582055bb9e80f890 Mon Sep 17 00:00:00 2001 From: Brett Heap <1513478+brettheap@users.noreply.github.com> Date: Sun, 15 Nov 2026 03:25:38 +0000 Subject: [PATCH 1/2] 007 S007-09: Test 14's refusing and flipped states, `wip init`'s cases and the marker's unit form (T212, T256, T225, T242; part of opensoft/openRepoTools#165) Pull request P06 of feature 007's task sets, version 12f: lane 2's set S007-09 in one commit, through the code queue. It is stacked on P01, code pull request opensoft/openRepoTools-code#88, whose head is 7f1141be15ac9c0d20c25c802ba9533c2fec811c on code main c9c65cc14695732c9badf9f1f7cac795f661d524 (rule 2); when P01 lands, this pull request is retargeted to main with its head unchanged (landing note 24). It is cut from lane 1's line R at merge158 7e11b7712678fc57d190d7b2b77d92f0c012eab7. Its 18 task commits, all of lane 2's tasks, T225's and T242's built by lane 2 and T212's and T256's built by lane 5, were picked with cherry-pick -x in line R's order; the part below lists them in that order. Two commits that line R holds in this set's module are not in this commit: T277 a12fd85e6c5cac097033229926e3f1000b321f28 (S007-56, P31), between T256 and T212b in line R's merge137, and T282 66e6cabd5126047f2ea87965daccfebbc2a70601 (S007-55a, P29), line R's merge145 8bed8591374f0bed272d874a63f255ef16acadad. Nor are the merges inside the two lines that line R took, which bring in only P01's task commits, of T200, T201, T203, T205, T206 and T207: 1b807ae97ab2e5bb49a7739c6fd2258bd240122a in merge113, and cf29e7a315a025cee6dbc4c3831f54cc0559e61b and 59f9a716250082b3b9e192c028773a73a95090d9 in merge137. No plain commit of landing note 15 falls in this set, and no line R commit holds its code by hunk. Both of its modules carry their gate tables (rule 11): the marker module's from T225f and T225g, and the build_flip module's from T212f. The full shas are pointers into lane 1's share. 007 S007-09: Test 14's refusing and flipped states, `wip init`'s cases and the marker's unit form (T212, T256, T225, T242; part of opensoft/openRepoTools#165) - T225 and T242, lane 2's, each whole, in line R's merge113 919cb377d1b7f8b51c303565a4bf44d63bad10ea: T225 61fe8735ef49fca2cdd3efd680551dc3ab6341a4, T225b c299afb388f2ef1d0103cff42a3dbb38d0f07348, T242 b973b6377b7927f8c5ca59ec2c25c9fc9df0fe67, T225c 16f183d148cc0918b896640dfd444fcdadbaac9c, T225d ce42f8dd79708c7454d3aa1ae4d4732e9a71ef73, T242b 3646b1c64a013771ec60891c6f82fed878b8db30, T225e e592dce819f2604108ed1f1f02229f915dc6b297, T225f 34be7b557c991b9153e90557cce49f96fb674e99 (the marker module's gate table) and T225g 20a7fdc2d017dfebf402a8ab9069caee2b891b7b. Each pick is clean, with its commit's own patch-id. tests/test_sql_register_marker.py then equals line R's merge158 blob 20d23b806f9f8b8b78789e52b4c58ab3cf2e9420, which line R has held unchanged since merge113. - T212 and T256, lane 2's, built by lane 5, each whole, in line R's merge137 ae1d4ceadd6388ce87846d27792568fc0122d090: T212 5ebe46e98f949319adc52a10746d5174ee9aefdd, T256 56a81e1a081d178dfea1f09ce21d63038ac8a482, T212b 250e08a0064cadcd279a335f8d03739ff64664cc, T212c fe26c262d19b54e87e90f4136ab4a1efcd5d439c, T212d 63d0d09fbb2d4f0942506ede7165c802acedaa4a, T212e ebf1e6150abe07080ccc45e0d730c67b25baf004, T256b 1d2c3ed0ab689c410a747fdd720ae5bcc05d8281, T256c c7615d89d1c76c43b40c8d4fb8297c9ed91a36c2 and T212f 3d9c5b0905960bbda9f88b31c1ab6ed92018cea5 (the build_flip module's gate table). Each pick but T256c's is clean, with its commit's own patch-id. T256c's pick conflicts in one hunk, the module docstring's paragraph WHAT EACH WAITS FOR, whose last sentence is T277's: "T277's test needs T105's constant, and fails between T321 and T328." It is settled as T256c's paragraph less exactly that sentence (version 12f's cut note for P06): in the hunk, three of its four settled lines are T256c's verbatim, and the fourth is T256c's less its last two words, "T277's test". tests/test_sql_register_build_flip.py then equals line R's merge137 blob 6d237ce26f382f955ef59cc171eadda724111787 less exactly T277's lines: its 10-line entry in the docstring, its sentence in that paragraph, and the 41 lines that add its test at the end of the module. Line R's merge158 blob a09d2d5bf51dd0c1d3503fd99d9367ee61811296 is that merge137 blob with exactly T282's patch applied, patch-id 024fa397, 312 insertions and 1 deletion: the deletion is T277's last line of that paragraph, which comes back as itself with T282's sentence appended, and the other 311 insertions are T282's new lines. - Markers: tests/sql_register_landed/T212, T256, T225 and T242. Lane: openRepoTools-1 Co-Authored-By: Claude Opus 5.5 --- tests/sql_register_landed/T212 | 0 tests/sql_register_landed/T225 | 0 tests/sql_register_landed/T242 | 0 tests/sql_register_landed/T256 | 0 tests/test_sql_register_build_flip.py | 1195 +++++++++++++++++++++++++ tests/test_sql_register_marker.py | 1091 ++++++++++++++++++++++ 6 files changed, 2286 insertions(+) create mode 100644 tests/sql_register_landed/T212 create mode 100644 tests/sql_register_landed/T225 create mode 100644 tests/sql_register_landed/T242 create mode 100644 tests/sql_register_landed/T256 create mode 100644 tests/test_sql_register_build_flip.py create mode 100644 tests/test_sql_register_marker.py diff --git a/tests/sql_register_landed/T212 b/tests/sql_register_landed/T212 new file mode 100644 index 00000000..e69de29b diff --git a/tests/sql_register_landed/T225 b/tests/sql_register_landed/T225 new file mode 100644 index 00000000..e69de29b diff --git a/tests/sql_register_landed/T242 b/tests/sql_register_landed/T242 new file mode 100644 index 00000000..e69de29b diff --git a/tests/sql_register_landed/T256 b/tests/sql_register_landed/T256 new file mode 100644 index 00000000..e69de29b diff --git a/tests/test_sql_register_build_flip.py b/tests/test_sql_register_build_flip.py new file mode 100644 index 00000000..952a3581 --- /dev/null +++ b/tests/test_sql_register_build_flip.py @@ -0,0 +1,1195 @@ +# SPDX-License-Identifier: Apache-2.0 +"""TEST 14: THE BUILD BEFORE THE RENDERER'S GIT HALF (feature 007; the test +plan's AT-14; FR-001, FR-002, FR-003, FR-059). + +One constant is the flip: `RENDER_GIT_HALF`, beside `SCHEMA_VERSION` in the +checkout's `lanes-index` (lane 1's T105, L1-A3). While it is False, Q6(c)'s +refusal of `mode=primary` is built in, and lane 3's T328 is the only change +that sets it True. So the module builds both states from the one checkout, +with T203's `flipped_copy` (PC-5): the REFUSING copy has the constant False, +the FLIPPED copy has it True, whichever way the checkout's own says. + +WHAT IT HOLDS, by task: + + * T212 (L2-N2), the refusing state: + - `test_mode_primary_is_refused_until_the_git_half_and_goes_to_sql_once_ + flipped[refusing]`: `lanes-index mode` exits 78 with the fixed text and + nothing on stdout, and so does it over `store=sqlite` or no + `register_url=`, since Q6(c)'s check runs first (Y:4849; lane 1, #165 + 6747929926 point 1); every other command this build has that reads the + configuration exits 2 with the same text: `status`, `sync` and + `reconcile` with `LANES_INDEX` unset, and `export`, which writes it to + `/why`; `cutover --import `, `rollback` and `set-mode + primary` exit 2 with it too, once a build has them (TP:2598-2600). No + `psql` runs, no store is made, and the files, the HEAD and origin are + unchanged; + - `[mode-under-index-off]`: with `LANES_INDEX=off` kept set over the same + file, `lanes-index mode` still exits 78 with the text, never `index` + (lane 3, #165 6747957479; lane 1, 6748099727). Its `[J3]` word is + `sql_register_build_flip and mode-under-index-off`; + - `test_lanes_edit_asks_lanes_index_mode_only_where_a_configuration_ + exists` (D3): with no configuration file and `LANES_INDEX_CONFIG` + unset, a logging stand-in at `lanes-index`'s path records no call, and + the verb writes in files mode; + - `test_mode_primary_with_sqlite_is_refused` (P162-163; R-F9-5): on T203's + FLIPPED copy, where Q6(c)'s refusal is lifted, `mode=primary` with + `store=sqlite`, or with no `register_url=`, is T104's refusal, 2 (lane + 1's L1v4.10:117), and not Q6(c)'s text. On the refusing copy Q6(c)'s 78 + comes first, which `[refusing]` holds. This is lane 2's reading of the + two lines together (NOTES question 29); + - `test_register_read_exits_78_under_the_refusal[readers|for-guard]`: + `register read` exits 78 with the text, never 2, in the readers' forms + (contract section 3.6's forms 1 and 3) and in `--for guard`'s (forms 2 + and 4), as contract section 2.7's 78 row names them; + - `test_readers_under_the_refusal_answer_the_78_as_a_failed_read[| + listing|session-start|guard|projection]`: run from the same estate under + the refusal, with the fake `psql`'s log empty, a read that decides + exits 69 with nothing on stdout; the listings and the `SessionStart` + block answer from the mirror, exit 0, and carry the `read: mirror` + line; the prompt guard exits 2, run in the lane's window with a live + session record and compact hook JSON, since without them it refuses 2 + before any read (lane 3's T507 ruling (1), #165 6783977598); and + `managed-projection` answers 1, UNKNOWN, never 8. + * T256 (L2-W6), the flipped state and the render fork's stub test, each a + REAL-ENGINE case (the flipped state is RE: its write is a `register + snapshot` reply and a commit, which a fake cannot fabricate), and + `[replay-keeps-pid]`, which needs no engine: + - `[flipped]`: on the FLIPPED copy, with `register_url=` on the session + cluster's socket, on an imported register after the cutover, the same + `log NOTED` exits 0, the journal gains one entry, the shim's log holds + one attempt of two calls (the snapshot and the commit, sent as + `register_url=`'s login with `register_passfile=` and no `PGPASSWORD`), + the files are unchanged, since there is no git half in this build, and + the stand-in logs one `mode` call, the primary half of the rule that + the ask is made once: the parent asks it, and the attempt's child asks + none (Y:5038, Y:5452); + - `[replay-keeps-pid]` (R-T409-9; lane 3, #165 6747281902, T409's item + 9; lane 3's proposal, 6852014823, which lane 2 confirmed in + 6858869119): with a configuration, an unrouted write whose first push + loses a race runs again by S4's replay, an `exec` that keeps the pid, + and the stand-in logs one `mode` call across it (Y:4858, Y:5121: the + ask is made once). It runs in `index` mode, with no engine, since no + primary writer that asks the mode ever replays. Its `[J3]` word is + `sql_register_build_flip and replay-keeps-pid`; + - `test_a_primary_write_forks_render_checkout_on_the_lane_checkout_ + detached[plain|no-fetch-set|index-off-set]`: after a primary write + commits, the stand-in's log holds one `render` call, `render --checkout + `, `` the writing lane's checkout, `-lanes//`; its + environment has no `LANES_NO_FETCH`, though the verb ran with it set in + `[no-fetch-set]` (D12); it is made though `LANES_INDEX=off` is set in + `[index-off-set]`; its stdin is closed or `/dev/null` and its + descriptors 3 to 9 are closed, as `index_nudge`'s fork has them; and + the writer exits with the verb's own code while the stand-in holds the + `render` call on a FIFO, so no fork waits, and the flipped copy's + answer to it, "git half not installed", is never read. + +THE CODES ARE READ FROM THE CONSTANTS (contracts/exit-codes.md section 1: +"the tests read the constant, never a literal"): `EXIT_CONFIG` and +`EXIT_REFUSED`, which T105 names in `lanes-index`. A code `lanes-edit.sh` +exits with (69, 1 and 2 from the readers) has no constant, and is a literal. + +THE REFUSING STATE'S CONFIGURATION (T212's bullet; lane 1's CLI4.5 section +2.5; R09): `mode=primary`, with `register_url=` and `reader_url=` on +`db.invalid`, each carrying `sslmode=verify-full` and an `sslrootcert=` that +names a test root file, and 0600 password files. That meets the block's +configuration rule, and Q6(c)'s 78 does not rest on it: Q6(c) runs before +T104's R8, R9, R10 and R15, so test 14's own state, a register URL on +`db.invalid` with no TLS, gives the same 78 (R-F9-5). + +THE FAKE-`psql` HOST RULE (L1v4.5:525; lane 1, #165 6741670709 item 9): the +refusing state's `register_url=`, on `db.invalid`, meets it by `verify-full` +and a root file, and every other configuration here either names no URL or +carries the same `verify-full` and root file, since T104 refuses any other at +load (CLI4.5 section 2.5). The fake is T203's `REGISTER_FAKE_PSQL`, first on +`PATH`; its log stays empty in every case here, since nothing connects. + +`LANES_INDEX` (R-F9-5): `tests/conftest.py` sets `LANES_INDEX=off` for the +whole run, and `Estate` builds its environment without it. Under it `sync` +and `reconcile` keep #160's no-op exit 0, even over a `mode=primary` file, so +`[refusing]` runs them with it unset; `lanes-index mode` reads the +configuration whatever it says, which `[mode-under-index-off]` holds. + +THE STAND-IN AT `lanes-index`'S PATH. The checkout's `lanes-edit.sh` finds +`lanes-index` beside itself (`$SCRIPT_DIR/lanes-index`, then `PATH`), so each +`lanes-edit.sh` case runs a copy of it, with what it reads beside it, and puts +`LOGGING_WRAPPER` at `lanes-index`'s path there: it logs each call, then runs +the `lanes-index` it stands in front of. A reader case first asserts that the +reader asked `lanes-index`, so a case that never reaches the refusal fails on +that, never vacuously (`session-start` excepted, as T217's mirror test does). + +NO NETWORK. Every remote is a bare repository under `tmp_path`, `$HOME` is +temporary, and `db.invalid` is never resolved: in the refusing state nothing +connects. + +THE REAL ENGINE, for T256's flipped state and render fork only. The flipped +state takes `pg` from `tests/pgcluster.py`, one database cloned from the +session's template, and so skips with T205's banner where no PostgreSQL 16 is +found, unless `OPENREPOTOOLS_REQUIRE_PG=1`. The render fork's test asks for +`pg` itself, so its fixture closure holds `pg_engine` (T200's rule). +`[flipped]` shares its function with the refusing state and with +`[replay-keeps-pid]`, which need no engine and always run (AT-14: "The +refusing state is FP"), so it takes `pg` by `request.getfixturevalue` and +skips alone. Its register is reached as +AT-LR006's fixture reaches one (TP:4610-4615), by the documented functions as +`lanes_register_writer`: `commit_write` with an `import` entry holding the +estate's render set, then a `cutover` entry, then `record_marker`, as T221's +module does; the template is T227's, built by `lanes-index bootstrap +--no-passwords`. Two logins join the writer and the reader groups and connect +by the cluster's trust. The shim (T203's `PSQL_SHIM`, unarmed) stands in front +of the cluster's own `psql` and logs every call. Each flipped estate also has +the writing lane's own register checkout ``, `-lanes//`, a clone +of W's origin, as lane 2's writes module makes one (`make_lane_checkout`): on +primary a write makes no clone, since a clone is a fetch (D12), so lane 4's +T415 refuses a write whose lane has none (`pw_checkout`; tasks:1154-1155). + +`[replay-keeps-pid]`'S ESTATE (lane 3's proposal, 6852014823; lane 2's build +notes, 6858869119). No primary writer that asks the mode replays: on primary +T415's arm runs `pw_run` before 1a's routing (R17), and the attempt's child +asks nothing and stops at the seam before any push (Y:5038, Y:5040, Y:5042). +So the case runs in `index` mode, which `lanes-index mode` answers from the +file alone: a 0600 `mode=index` file named by `LANES_INDEX_CONFIG`, with +`LANES_INDEX=off`, which skips the index's nudge and never the mode question +(Y:5718), and the logging stand-in in front of the checkout's `lanes-index`. +The write is unrouted, through `Estate`'s explicit `LANES_REPO`, so it has no +`LANES__PID` and its replay keeps the mode only by `LANES__REPLAY_PID`, which is +R-T409-9's half. Its first push loses a race: `tests/a23_box.py`'s `NET_GIT` +is `LANES_GIT`, and its `FAKE_NET_HOOK` lands one commit of a peer, a clone of +the estate's origin, before the first push only, as +`tests/test_a23_publish_replay.py`'s `Box.race` does. With no race there is no +`push refused` note, and with no stand-in found there is no `mode` call, so +the case cannot pass vacuously. + +WHAT EACH WAITS FOR (the block's Order): T212's tests fail until L1-A3, L1-A4, +L1-A11 and L5-A5 land: lane 1's T105 (the constant and `mode`), T113 +(`register read`) and lane 5's T504 (the read door). D3's test passes at once +on a build that never asks the mode. T256's real-engine cases fail until L4-B1 +and L4-B13 land, and on an engine they also need T227's template and lane 1's +T107 functions. `[replay-keeps-pid]` fails until lane 4's T409 follow-up for +its item 9, and needs Amendment 23's S4 replay and `NET_GIT`. +""" + +from __future__ import annotations + +import hashlib +import importlib.util +import json +import os +import re +import shlex +import shutil +import subprocess +import sys +import time +import uuid +from importlib.machinery import SourceFileLoader +from pathlib import Path +from urllib.parse import quote + +import pytest + +import sql_register_helpers as helpers +from conftest import REPO, WINDOWS_SKIP +from test_lanes_index import UUID_A2, Estate, estate + +__all__ = ["estate"] # the fixture, imported so that pytest finds it here + +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")] + +SQL_REGISTER_GATE_TABLE = { + "test_a_primary_write_forks_render_checkout_on_the_lane_checkout_detached": ("T409", "T415", "T416"), # T256; tasks:2436 + "test_lanes_edit_asks_lanes_index_mode_only_where_a_configuration_exists": ("T104", "T105", "T113", "T504", "T505", "T506"), # T212; tasks:1974 + "test_mode_primary_is_refused_until_the_git_half_and_goes_to_sql_once_flipped": ("T104", "T105", "T113", "T504", "T505", "T506"), # T212; tasks:1974 + "test_mode_primary_with_sqlite_is_refused": ("T104", "T105", "T113", "T504", "T505", "T506"), # T212; tasks:1974 + "test_readers_under_the_refusal_answer_the_78_as_a_failed_read": ("T104", "T105", "T113", "T504", "T505", "T506"), # T212; tasks:1974 + "test_register_read_exits_78_under_the_refusal": ("T104", "T105", "T113", "T504", "T505", "T506"), # T212; tasks:1974 + "test_mode_primary_is_refused_until_the_git_half_and_goes_to_sql_once_flipped[flipped]": ("T409", "T415", "T416"), # T256; tasks:2436 + "test_mode_primary_is_refused_until_the_git_half_and_goes_to_sql_once_flipped[replay-keeps-pid]": ("T409",), # T256; tasks:2436 +} + +LANES_EDIT = REPO / "lanes-edit.sh" + +#: Q6(c)'S FIXED TEXT (agreement test 14; the test plan's AT-14, TP:2540-2542; +#: design Y:4872). The design may reword it, not weaken it (P1413), and the +#: test pins what the design prints. +REFUSED_TEXT = ("mode=primary is not available in this build: the renderer's git half is not " + "installed, so a write could not be mirrored; nothing was written") + +#: `lanes-index`'s own stderr lines are prefixed so (contract section 2.6). +PREFIX = "lanes-index: " + +#: A subcommand a build does not have yet answers 64 with these words (lane +#: 1's T105; #165 6747929926: "so does every subcommand not yet built"). +NOT_BUILT = "this build does not have it" + +#: What a case copies beside the stand-in, as T217's `Primary` does (CLI4.5:885). +COPIED_BESIDE = ("lanes-edit.sh", "lanes", "repos.tsv", "lane-start", "lane-worktrees") + +#: The stand-in's files, beside it: its log, the FIFO a `render` call is held +#: on where a case names one, and the held calls' ends. +CALL_LOG = "lanes-index.calls" +HOLD_FILE = "lanes-index.hold" +ENDS_LOG = "lanes-index.ends" + +#: THE LOGGING STAND-IN (AT-14's fixture; TP:2613-2616: "a logging wrapper +#: that records each call's argv, environment and open descriptors, and then +#: runs the flipped copy"): `lanes-index` at the path `lanes-edit.sh` finds. +#: It logs each call, one JSON object per line: its argv, the NAMES in its +#: environment (never a value), and the state of descriptors 0 to 9 as it +#: found them, `closed`, `devnull` or `open`. Then it runs `TARGET`, the +#: `lanes-index` it stands in front of, with the same argv, stdin and +#: descriptors. A `render` call, where `lanes-index.hold` beside it names a +#: FIFO, is first held on that FIFO until a case opens it for writing and +#: closes it; then it runs, and its end goes to `lanes-index.ends`. +LOGGING_WRAPPER = r'''#!/usr/bin/env python3 +# TEST 14's LOGGING STAND-IN at lanes-index's path (feature 007, AT-14; +# TP:2613-2616): one JSON object per call in lanes-index.calls beside it, with +# the call's argv, the names in its environment and the state of descriptors 0 +# to 9, then the lanes-index it stands in front of. A `render` call, where +# lanes-index.hold beside it names a FIFO, is held on that FIFO first, then +# run, and its end is logged in lanes-index.ends. +import json, os, stat, sys + +HERE = os.path.dirname(os.path.abspath(__file__)) + + +def descriptor(number): + try: + found = os.fstat(number) + except OSError: + return "closed" + try: + null = os.stat(os.devnull) + except OSError: + return "open" + if stat.S_ISCHR(found.st_mode) and found.st_rdev == null.st_rdev: + return "devnull" + return "open" + + +# THE DESCRIPTORS FIRST, before this script opens anything of its own. +fds = {str(number): descriptor(number) for number in range(10)} +argv = sys.argv[1:] +record = {"argv": argv, "pid": os.getpid(), "ppid": os.getppid(), "fds": fds, + "env": sorted(os.environ)} +with open(os.path.join(HERE, "lanes-index.calls"), "a", encoding="utf-8") as log: + log.write(json.dumps(record) + "\n") +hold = os.path.join(HERE, "lanes-index.hold") +if argv[:1] == ["render"] and os.path.exists(hold): + import subprocess + with open(hold, encoding="utf-8") as handle: + fifo = handle.read().strip() + with open(fifo, encoding="utf-8") as held: + held.read() + code = subprocess.call([sys.executable, TARGET] + argv) + with open(os.path.join(HERE, "lanes-index.ends"), "a", encoding="utf-8") as ends: + ends.write(json.dumps({"argv": argv, "exit": code}) + "\n") + sys.exit(code) +os.execv(sys.executable, [sys.executable, TARGET] + argv) +''' + +#: The `read: mirror` line (design S3, "The mirror reads"), on stderr. +MIRROR_LINE = re.compile(r"^read: mirror at [0-9a-f]{12}, .*$", re.M) + +#: THE GUARD'S WINDOW (lane 3's T507 ruling (1), #165 6783977598; lane 5's +#: post that found this case, 6809022654). The guard keeps its order: with no +#: window, or no live session record in it, it refuses 2 before any read, and +#: T507's prefetch, the first call that asks `lanes-index`, comes after the +#: session-record check (lane 5, #165 6755266457). So `[guard]` runs in the +#: lane's window with a live record of the hook's session, as lane 2's T215e +#: gave AT-P3's case in the outage module (T203c's `guard_session`; built +#: here in its form, since this module runs on lines that lack that helper). +#: The window's stand-in `tmux` answers `display-message` as a real one does, +#: with each `@...@` word below filled in. +GUARD_WINDOW, GUARD_TMUX_SESSION, GUARD_WINDOW_ID, GUARD_PANE = "repoA-2", "testsess", "@1", "%1" +GUARD_TMUX = r'''#!/bin/sh +# TEST 14's STAND-IN tmux for the guard's window (feature 007, T507 ruling +# (1)): it answers display-message as the lane's window does, a target that is +# not that window with tmux's own "can't find window" and 1, and every other +# command with nothing and 0. +[ "${1-}" = display-message ] || exit 0 +target=""; prev=""; fmt="" +for a in "$@"; do + [ "$prev" = -t ] && target="$a" + prev="$a"; fmt="$a" +done +case "$target" in + ''|'@ID@'|'@SESSION@:@ID@'|'@PANE@'|'@SESSION@:@ID@.@PANE@') ;; + *) printf "can't find window: %s\n" "$target" >&2; exit 1 ;; +esac +case "$fmt" in + '#{session_name}:#{window_id}') printf '%s\n' '@SESSION@:@ID@' ;; + '#{session_name}') printf '%s\n' '@SESSION@' ;; + '#{window_id}') printf '%s\n' '@ID@' ;; + '#{pane_id}') printf '%s\n' '@PANE@' ;; + '#{pane_pid}') printf '%s\n' '@PID@' ;; + *) printf '%s\n' '@WINDOW@' ;; +esac +exit 0 +''' + +#: THE READS THAT DECIDE (TP:2587-2589), each with an argv `Estate` answers in +#: files mode, as T217's readers' table gives them: under the refusal each +#: exits 69 with nothing on stdout. +DECIDE_READS = { + "who": ("who", "opensoft/repoA#7"), + "binding": ("binding", "repoA-1"), + "live-holder": ("live-holder", "repoA-1"), + "next-free": ("next-free", "repoA"), + "lane-last": ("lane-last", "repoA-1"), + "register-row": ("register-row", "repoC-9"), + "session-lane": ("session-lane", UUID_A2), + "canon-lane": ("canon-lane", "repoA-1"), + "resolve-home": ("resolve-home", "repoA-1"), +} + +#: The listings (TP:2590): each answers from the mirror, exit 0. +LISTINGS = (("lanes",), ("history", "--all")) + +#: `[|listing|session-start|guard|projection]` (TP:2644). +READER_CASES = sorted(DECIDE_READS) + ["listing", "session-start", "guard", "projection"] + +#: What a decide read and `managed-projection` exit, `lanes-edit.sh`'s own +#: codes (contracts/exit-codes.md, `lanes-edit.sh`'s table; design S3). +READ_FAILED, PROJECTION_UNKNOWN, PROJECTION_NEVER, GUARD_REFUSED = 69, 1, 8, 2 + +#: THE FLIPPED STATE'S REGISTER (T256), as T221's module names it: the +#: schema, its three groups, and the two logins `lanes-index` connects as, +#: made once per cluster, members of the writer and the reader groups, with no +#: password. +SCHEMA = "lanes_register" +WRITER, READER = "lanes_register_writer", "lanes_register_reader" +LOGIN_WRITER, LOGIN_READER = "t256_register_writer", "t256_register_reader" + +#: What the fixture's own entries are stamped with (AT-LR006's fixture). +FIXTURE_LANE, FIXTURE_WS, FIXTURE_AUTHOR = "Lane-T256", "ws-t256", "T256 " +NOT_AFTER = "2100-01-01T00:00:00Z" # well past every case (lane 1's v2.3) +MARKER_COMMIT = "e" * 40 +STORE_LABEL, STORE_UTC = "t256", "2026-11-10T12:00:00Z" + +#: The writing lane of every flipped write: a LIVE row in `Estate`'s register. +WRITING_LANE = "repoA-2" + +#: How long a case waits for a detached fork to show in the stand-in's log. +FORK_SECONDS = 20.0 + +#: `[replay-keeps-pid]`'S RACE: the body of `FAKE_NET_HOOK` behind +#: `tests/a23_box.py`'s `NET_GIT`, as `tests/test_a23_publish_replay.py`'s +#: `Box.race` writes it with `times=1`: before the helper's first push only, +#: the peer, a clone of the estate's origin, lands one commit of its own on +#: origin, so that push is refused and the write runs again. `@PEER@` and +#: `@COUNT@` are filled in, each quoted. +RACE_HOOK = """#!/usr/bin/env bash +[ "$1" = push ] || exit 0 +n=$(cat @COUNT@ 2>/dev/null || echo 0) +[ "$n" -lt 1 ] || exit 0 +echo $((n + 1)) > @COUNT@ +git -C @PEER@ fetch -q origin +git -C @PEER@ merge -q --ff-only refs/remotes/origin/main +git -C @PEER@ commit -q --allow-empty -m "a peer's commit lands first ($((n + 1)))" +git -C @PEER@ push -q origin main +exit 0 +""" + +#: THE RENDER FORK'S THREE (TP:2621-2624): the verb's own environment. +FORK_CASES = { + "plain": {}, + "no-fetch-set": {"LANES_NO_FETCH": "1"}, + "index-off-set": {"LANES_INDEX": "off"}, +} + + +# ------------------------------------------------------------------ helpers +def shown(proc: subprocess.CompletedProcess) -> str: + return (f"exit {proc.returncode}\n--- stdout ---\n{proc.stdout[-3000:]}" + f"\n--- stderr ---\n{proc.stderr[-3000:]}") + + +def load_index(path: Path = helpers.LANES_INDEX): + """`lanes-index` as a module, fresh, as `test_lanes_index.py` loads it.""" + loader = SourceFileLoader("lanes_index_build_flip_module", str(path)) + spec = importlib.util.spec_from_loader(loader.name, loader) + module = importlib.util.module_from_spec(spec) + loader.exec_module(module) + return module + + +def exit_code(name: str) -> int: + """The checkout's `lanes-index`'s named exit code (contracts/exit-codes.md + section 1), asserted to be there: T105 names `EXIT_CONFIG`, `EXIT_REFUSED` + and `EXIT_USAGE`.""" + module = load_index() + assert isinstance(getattr(module, name, None), int), ( + f"the checkout's lanes-index names no `{name}`: Q6(c)'s exit codes are named " + f"with lane 1's T105 (L1-A4; contracts/exit-codes.md section 1)") + return getattr(module, name) + + +def constant_lines(path: Path = helpers.LANES_INDEX) -> list: + return helpers.RENDER_GIT_HALF_LINE.findall(Path(path).read_bytes()) + + +def state_copy(directory: Path, value: bool) -> Path: + """T203's `flipped_copy` of the checkout's `lanes-index` (PC-5): `False` + is the refusing state, `True` the flipped one. The checkout must hold the + constant's one line, which lane 1's T105 adds (L1-A3).""" + found = constant_lines() + assert len(found) == 1, ( + f"the checkout's lanes-index holds {len(found)} `RENDER_GIT_HALF = ` lines, not one: " + f"Q6(c)'s constant lands with lane 1's T105 (L1-A3)") + return helpers.flipped_copy(helpers.LANES_INDEX, directory, value) + + +def write_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 calls(bin_dir: Path) -> list: + """The stand-in's log: one dict per call, in call order.""" + path = bin_dir / CALL_LOG + if not path.exists(): + return [] + return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line] + + +def forget_calls(bin_dir: Path) -> None: + path = bin_dir / CALL_LOG + if path.exists(): + path.write_text("", encoding="utf-8") + + +def beside(bin_dir: Path, target: Path) -> Path: + """`bin_dir` holding a copy of the checkout's `lanes-edit.sh` and what it + reads beside it, with `LOGGING_WRAPPER` at `lanes-index`'s path there in + front of `target`. Returns the copied `lanes-edit.sh`.""" + bin_dir.mkdir(parents=True, exist_ok=True) + for name in COPIED_BESIDE: + shutil.copy2(REPO / name, bin_dir / name) + wrapper = bin_dir / "lanes-index" + wrapper.write_text(LOGGING_WRAPPER.replace("TARGET", repr(str(target))), encoding="utf-8") + wrapper.chmod(0o755) + return bin_dir / "lanes-edit.sh" + + +class Refusing: + """Test 14's refusing state over an `Estate`: the configuration that says + `mode=primary` at the workstation's default path (and named by + `LANES_INDEX_CONFIG`), the refusing copy of `lanes-index`, and T203's fake + `psql` first on `PATH`, logging every call.""" + + def __init__(self, estate: Estate): + self.e = estate + self.root = estate.root / "test14" + self.root.mkdir(parents=True, exist_ok=True) + # A stand-in root file for `sslrootcert=`: it must exist as a regular + # file (contract section 2.5), and nothing ever reads it as a root. + self.root_file = self.root / "tls" / "register-root.pem" + self.root_file.parent.mkdir(parents=True, exist_ok=True) + self.root_file.write_text("test 14's stand-in root file; nothing connects to db.invalid\n", + encoding="utf-8") + self.passfile = write_private(self.root / "secrets" / "register.pgpass", + "db.invalid:5432:lanes:lanes_w_test14:not-a-secret\n") + self.reader_passfile = write_private(self.root / "secrets" / "reader.pgpass", + "db.invalid:5432:lanes:lanes_r_test14:not-a-secret\n") + self.config = estate.write_config(self.config_text()) + self.copy = state_copy(self.root / "refusing", False) + self.psql_dir = self.root / "psqlbin" + self.psql_dir.mkdir(parents=True, exist_ok=True) + fake = self.psql_dir / "psql" + fake.write_text(helpers.REGISTER_FAKE_PSQL, encoding="utf-8") + fake.chmod(0o755) + self.psql_log = self.root / "psql.log" + + def url(self, user: str) -> str: + """A URL on `db.invalid` that meets the block's configuration rule.""" + root = quote(str(self.root_file), safe="/") + return f"postgresql://{user}@db.invalid:5432/lanes?sslmode=verify-full&sslrootcert={root}" + + def config_text(self, *, mode: str = "primary", store: str | None = None, + register: bool = True) -> str: + lines = [f"mode={mode}"] + if store: + lines.append(f"store={store}") + if register: + lines += [f"register_url={self.url('lanes_w_test14')}", + f"register_passfile={self.passfile}", + f"reader_url={self.url('lanes_r_test14')}", + f"reader_passfile={self.reader_passfile}"] + return "\n".join(lines) + "\n" + + def other_config(self, name: str, text: str) -> Path: + """A second 0600 configuration, outside every work tree, for a case + that names it by `LANES_INDEX_CONFIG`.""" + return write_private(self.root / "configs" / name, text) + + def env(self, **extra) -> dict: + env = {"LANES_INDEX_CONFIG": str(self.config), "FAKE_PSQL_LOG": str(self.psql_log), + "PATH": self.e.path_with(self.psql_dir), "LANES_INDEX": None, + "LANES_EDIT": str(LANES_EDIT)} + env.update(extra) + return env + + def index(self, copy: Path, *args, **extra) -> subprocess.CompletedProcess: + """`copy` run as `Estate.index` runs the checkout's `lanes-index`.""" + return self.e.run(sys.executable, copy, *args, env=self.env(**extra)) + + def edit(self, edit_path: Path, *args, input_text: str | None = None, + **extra) -> subprocess.CompletedProcess: + """The copied `lanes-edit.sh` at `edit_path`, on this workstation.""" + env = self.env(LANES_EDIT=str(edit_path), **extra) + return self.e.run("bash", edit_path, *args, env=env, input_text=input_text) + + def psql_calls(self) -> list: + if not self.psql_log.exists(): + return [] + return [line for line in self.psql_log.read_text(encoding="utf-8").splitlines() if line] + + def origin_and_head(self) -> tuple: + return self.e.tip(), self.e._git("rev-parse", "HEAD").strip() + + +def proc_start(pid: int) -> str: + """The start token the guard compares, field 22 of `/proc//stat`, cut + after the last `) ` as `pid_alive` cuts it. Empty where there is no + `/proc`, where `pid_alive` asks `kill -0` alone.""" + try: + stat = Path(f"/proc/{pid}/stat").read_text(encoding="utf-8", errors="replace") + except OSError: + return "" + return stat.rsplit(") ", 1)[1].split()[19] + + +def in_the_lane_window(state: Refusing) -> tuple: + """`[guard]`'s window and session (see `GUARD_TMUX`): the environment the + hook runs in, and its input. The environment names the stand-in `tmux`'s + server, pane and directory (first on `PATH`). The stand-in is written to + `/guard-window`, and the session's record to the estate's + `$HOME/.claude/sessions/.json`, mode 0600, one line of compact JSON + in the suite's record form: its live process is this test's own, so it + needs no teardown, and its `procStart` is the live one, so the guard reads + it live. The record's `tmux` names the window the stand-in answers for, + and its `sessionId` is the hook's. The input is the hook's JSON, compact + as the harness sends it, since the guard's `jstr` reads `"cwd":""` + with no blank after the colon; its `cwd` is the lane's checkout, under + `$HOME/projects`, since a `cwd` outside the projects root is silent + (clause (e)).""" + pid, cwd = os.getpid(), str(state.e.wip) + directory = state.root / "guard-window" + directory.mkdir(parents=True, exist_ok=True) + text = GUARD_TMUX + for word, value in (("@SESSION@", GUARD_TMUX_SESSION), ("@ID@", GUARD_WINDOW_ID), + ("@PANE@", GUARD_PANE), ("@PID@", str(pid)), ("@WINDOW@", GUARD_WINDOW)): + text = text.replace(word, value) + tmux = directory / "tmux" + tmux.write_text(text, encoding="utf-8") + tmux.chmod(0o755) + write_private(state.e.home / ".claude" / "sessions" / f"{pid}.json", json.dumps( + {"pid": pid, "sessionId": UUID_A2, "cwd": cwd, "procStart": proc_start(pid), + "tmux": f"{GUARD_TMUX_SESSION}:{GUARD_WINDOW_ID}.{GUARD_PANE}", "name": GUARD_WINDOW, + "nameSource": "user", "status": "busy", "kind": "interactive"}, + separators=(",", ":")) + "\n") + env = {"TMUX": f"{directory / 'tmux-server'},{pid},0", "TMUX_PANE": GUARD_PANE, + "PATH": os.pathsep.join([str(directory), state.env()["PATH"]])} + hook = json.dumps({"hook_event_name": "UserPromptSubmit", "session_id": UUID_A2, + "cwd": cwd, "prompt": "hello"}, separators=(",", ":")) + return env, hook + + +# ------------------------------------------ T256: the flipped state's world +def db_psql(db, script: str, role: str | None = None) -> subprocess.CompletedProcess: + """One `psql` as the fixture's superuser, with the commit call's settings, + as `role` where one is named (T221's form).""" + 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="t256"), timeout=120, check=False) + + +def sql(db, script: str, role: str | None = None) -> str: + proc = db_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 window(db) -> dict: + return json.loads(sql(db, f"SELECT to_jsonb(v) FROM {SCHEMA}.schema_version v;")) + + +def journal_count(db) -> int: + return int(sql(db, f"SELECT count(*) FROM {SCHEMA}.journal;")) + + +def rendered(lines) -> str: + """The sha256 of a file of `lines`, LF-ended, as `render_file` renders it.""" + return hashlib.sha256("".join(line + "\n" for line in lines).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": FIXTURE_LANE, "workstation": FIXTURE_WS, + "author": FIXTURE_AUTHOR, "message": f"t256: {kind}"} + journal.update(parts.pop("journal", {})) + return {"journal": journal, "not_after": NOT_AFTER, **parts} + + +def render_lines(estate: Estate) -> dict: + """The render set at the estate's origin (CLI4.5 section 3.2), each file + as its lines: what the import loads, so the register answers as the files + do.""" + found = {} + for path in sorted((estate.wip / "lanes").rglob("*")): + rel = path.relative_to(estate.wip).as_posix() + if not (path.is_file() and helpers.RENDER_SET_PATH.match(rel)): + continue + text = estate.head_text(rel) + assert text.endswith("\n"), f"{rel} has no final newline, which the import entry assumes" + found[rel] = text[:-1].split("\n") + return found + + +def import_entry(files: dict, commit: str, tree: str) -> dict: + """An import of `files` (path to its lines) at `commit`: each created, its + lines appended, and each path's digest as it renders.""" + edits, order = [], 0 + for path in sorted(files): + order += 1 + edits.append({"ord": order, "op": "create", "path": path}) + for text in files[path]: + order += 1 + edits.append({"ord": order, "op": "append", "path": path, "new_text": text}) + return entry("import", "import", journal={"git_commit": commit, "git_tree": tree}, + edits=edits, + files=[{"path": p, "present": True, "sha256": rendered(files[p]), + "final_newline": True} for p in sorted(files)]) + + +def cutover_entry(commit: str, tree: str) -> dict: + """The cutover's `lanes/STORE` (D21's five fields, as T221's module writes + them).""" + lines = ("store=primary", f"database={STORE_LABEL}", f"import={commit}", + f"lanes-tree={tree}", f"utc={STORE_UTC}") + return entry("cutover", "cutover", + edits=[{"ord": 1, "op": "create", "path": "lanes/STORE"}, + *({"ord": n, "op": "append", "path": "lanes/STORE", "new_text": line} + for n, line in enumerate(lines, start=2))], + files=[{"path": "lanes/STORE", "present": True, "sha256": rendered(lines), + "final_newline": True}]) + + +def committed(db, base: int, body: dict, what: str) -> int: + """The commit call as the writer sends it (AT-LR006's fixture): one + SERIALIZABLE transaction around `commit_write`, as `lanes_register_writer`.""" + generation = sql(db, f"SELECT generation FROM {SCHEMA}.register_switch;") + literal = json.dumps(body, ensure_ascii=True).replace("'", "''") + proc = db_psql(db, f"BEGIN ISOLATION LEVEL SERIALIZABLE;\n" + f"SELECT {SCHEMA}.commit_write({base}, '{uuid.uuid4()}'::uuid, " + f"{window(db)['version']}, '{generation}'::uuid, '{literal}'::jsonb);\n" + f"COMMIT;\n", WRITER) + assert proc.returncode == 0, f"{what}: commit_write refused it: {proc.stderr.strip()}" + return int(proc.stdout.strip().splitlines()[-1]) + + +def bring_to_primary(db, estate: Estate) -> int: + """AT-LR006's route (TP:4610-4615): as `lanes_register_writer`, an import + of the estate's render set at its origin, then a cutover, then + `record_marker`. Returns the head, the cutover's seq.""" + commit = estate.tip() + tree = estate._git("rev-parse", "origin/main:lanes").strip() + head = int(sql(db, f"SELECT seq FROM {SCHEMA}.register_head;")) + imported = committed(db, head, import_entry(render_lines(estate), commit, tree), "the import") + cut = committed(db, imported, cutover_entry(commit, tree), "the cutover") + marker = sql(db, f"SELECT {SCHEMA}.record_marker({window(db)['version']}, {cut}, " + f"'{MARKER_COMMIT}', '{FIXTURE_WS}');", WRITER) + assert marker == "present", f"record_marker answered {marker!r}, not present" + switch = json.loads(sql(db, f"SELECT to_jsonb(s) FROM {SCHEMA}.register_switch s;")) + assert (switch["mode"], switch["marker_state"]) == ("primary", "present"), switch + return cut + + +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 lane_checkout(estate: Estate, lane: str = WRITING_LANE) -> Path: + """``, lane `lane`'s own register checkout, where `lanes-edit.sh`'s + `lane_checkout_path` puts it (Amendment 23 S1): `-lanes/`, W + being the real path of `workspace.yaml`'s `path:`, `Estate.ws` (lane 2's + form, the writes module's `lane_checkout`).""" + real = Path(os.path.realpath(estate.ws)) + return real.parent / f"{real.name}-lanes" / lane + + +def make_lane_checkout(estate: Estate, lane: str = WRITING_LANE) -> Path: + """`` for `lane`, a clone of W's origin, as `lane-checkout + --create` makes one (lane 2's `make_lane_checkout`, 5614d15:tests/ + test_sql_register_writes.py:420-427). On primary a write makes no clone, + since a clone is a fetch (D12), so T415's `pw_checkout` refuses a write + whose lane has no checkout before anything is sent (tasks:1154-1155).""" + target = lane_checkout(estate, lane) + target.parent.mkdir(parents=True, exist_ok=True) + proc = estate.run("git", "clone", "-q", str(estate.origin), str(target)) + assert proc.returncode == 0, ("the lane's own register checkout was not made", shown(proc)) + return target + + +class Flipped: + """Test 14's flipped state over an `Estate` and one `pg` database: the + register imported from the estate and brought to `primary` with the + marker `present`; a 0600 configuration whose `register_url=` and + `reader_url=` name the session cluster's socket; T203's flipped copy, with + the checkout's `lanes-edit.sh` beside the logging stand-in in front of it; + the shim in front of the cluster's own `psql`; and the writing lane's own + register checkout ``, which T415's `pw_checkout` reads and never makes + (`make_lane_checkout`).""" + + def __init__(self, estate: Estate, db): + self.e, self.db = estate, db + self.root = estate.root / "test14-flipped" + self.root.mkdir(parents=True, exist_ok=True) + self.checkout = make_lane_checkout(estate) + self.passfile = write_private(self.root / "secrets" / "register.pgpass", + f"*:*:*:{LOGIN_WRITER}:not-a-secret\n") + self.reader_passfile = write_private(self.root / "secrets" / "reader.pgpass", + f"*:*:*:{LOGIN_READER}:not-a-secret\n") + ensure_logins(db) + self.cut = bring_to_primary(db, estate) + self.config = estate.write_config(self.config_text()) + self.copy = state_copy(self.root / "flipped", True) + self.shim_dir = self.root / "shimbin" + self.shim_dir.mkdir(parents=True, exist_ok=True) + shim = self.shim_dir / "psql" + shim.write_text(helpers.PSQL_SHIM, encoding="utf-8") + shim.chmod(0o755) + self.bin = self.root / "bin" + self.edit_path = beside(self.bin, self.copy) + + def config_text(self) -> str: + """Unix-socket URLs, so the fake-`psql` host rule holds (L1v4.5:525).""" + return (f"mode=primary\n" + f"register_url={self.db.url(LOGIN_WRITER)}\n" + f"register_passfile={self.passfile}\n" + f"reader_url={self.db.url(LOGIN_READER)}\n" + f"reader_passfile={self.reader_passfile}\n") + + def env(self, **extra) -> dict: + env = {"LANES_EDIT": str(self.edit_path), "LANES_INDEX_CONFIG": str(self.config), + "PATH": self.e.path_with(self.shim_dir, Path(self.db.cluster.bindir)), + "LANES_INDEX": None, "LANES_LANE": WRITING_LANE} + env.update(extra) + return env + + def write(self, text: str, timeout: float = 120, **extra) -> subprocess.CompletedProcess: + """`log NOTED` as the writing lane: one primary write.""" + return self.e.run("bash", self.edit_path, "log", "NOTED", f"lane:{WRITING_LANE}", text, + env=self.env(**extra), timeout=timeout) + + def routed(self) -> dict: + """Slice 1a's routing (Amendment 23 S2): no `LANES_REPO`, and + `LANES_ROUTE_WRITES=1`.""" + return {"LANES_REPO": None, "LANES_ROUTE_WRITES": "1"} + + def lane_checkout(self) -> Path: + """`-lanes//`, W being the real path `workspace.yaml` names: + the checkout `make_lane_checkout` made.""" + return self.checkout + + def shim_calls(self) -> list: + """The calls the shim handed on that carry a request: not `--version`.""" + path = self.shim_dir / helpers.PSQL_SHIM_LOG + if not path.exists(): + return [] + rows = [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line] + return [row for row in rows if row.get("kind") != "version"] + + def origin_and_head(self) -> tuple: + return self.e.tip(), self.e._git("rev-parse", "HEAD").strip() + + +def the_78(proc: subprocess.CompletedProcess, config_code: int, what: str) -> None: + """Q6(c)'s answer from `mode`: 78, nothing on stdout, and stderr exactly + one line, the fixed text.""" + assert proc.returncode == config_code, (what, shown(proc)) + assert proc.stdout == "", (what, "stdout must be empty, never `index` or `primary`", + shown(proc)) + assert proc.stderr.splitlines() == [PREFIX + REFUSED_TEXT], (what, shown(proc)) + + +# ---------------------------------------------- T212: test 14, refusing +def refusing_case(state: Refusing) -> None: + """`[refusing]`: 78 from `mode`, 2 from every other command, the same + text, nothing connected and nothing written.""" + config_code, refused, usage = (exit_code("EXIT_CONFIG"), exit_code("EXIT_REFUSED"), + exit_code("EXIT_USAGE")) + before = state.origin_and_head() + the_78(state.index(state.copy, "mode"), config_code, "mode") + # Q6(c) FIRST (Y:4849; R-F9-5): `store=sqlite`, or no `register_url=`, + # is the same 78 while the constant is False, never T104's 2. + for name, text in (("store-sqlite", state.config_text(store="sqlite")), + ("no-register-url", state.config_text(register=False))): + conf = state.other_config(f"{name}.conf", text) + the_78(state.index(state.copy, "mode", LANES_INDEX_CONFIG=str(conf)), config_code, + f"mode over {name}") + # EVERY OTHER COMMAND THIS BUILD HAS THAT READS THE CONFIGURATION: 2 with + # the text. `sync` and `reconcile` with `LANES_INDEX` unset (R-F9-5). + for argv in (("status",), ("sync",), ("reconcile",)): + proc = state.index(state.copy, *argv, LANES_INDEX=None) + assert proc.returncode == refused, (argv, shown(proc)) + assert REFUSED_TEXT in proc.stderr, (argv, shown(proc)) + out = state.root / "export-out" + out.mkdir() + proc = state.index(state.copy, "export", "--out", str(out), LANES_INDEX=None) + assert proc.returncode == refused, ("export", shown(proc)) + why = (out / "why").read_text(encoding="utf-8") if (out / "why").exists() else "" + assert REFUSED_TEXT in proc.stderr + why, ("export: the text, on stderr or in /why", + why, shown(proc)) + assert not (out / "meta").exists(), "export wrote an image under the refusal" + # THE OPERATOR'S ACTS on a schema that is not a scratch schema (TP:2598- + # 2600): 2 with the text, in a build that has them; before that, 64. Each + # is given an argument list that parses, since a build checks a verb's + # arguments before it reads the configuration (lane 1's T116, opensoft/ + # openRepoTools#165 6810924785): a bare `cutover` is a 64, "needs + # --import ... or --after-loss", and never reaches the refusal. + # `--import` takes a full 40-digit sha, which names no commit here. + imported = "0123456789abcdef0123456789abcdef01234567" + for argv in (("cutover", "--import", imported), ("rollback",), ("set-mode", "primary")): + proc = state.index(state.copy, *argv, LANES_INDEX=None) + if proc.returncode == usage and NOT_BUILT in proc.stderr: + continue + assert proc.returncode == refused, (argv, shown(proc)) + assert REFUSED_TEXT in proc.stderr, (argv, shown(proc)) + assert state.psql_calls() == [], ("a refused configuration connected", state.psql_calls()) + assert not state.e.sqlite.exists(), "a store was made under the refusal" + assert state.origin_and_head() == before, "the files, the HEAD or origin moved" + assert state.config.read_text(encoding="utf-8") == state.config_text(), \ + "the configuration was rewritten" + + +def mode_under_index_off_case(state: Refusing) -> None: + """`[mode-under-index-off]`: `LANES_INDEX=off` kept set over the same + `mode=primary` file, and `mode` still answers 78 with the text, never + `index` (lane 3, #165 6747957479; lane 1, 6748099727).""" + config_code = exit_code("EXIT_CONFIG") + the_78(state.index(state.copy, "mode", LANES_INDEX="off"), config_code, + "mode under LANES_INDEX=off") + assert state.psql_calls() == [], state.psql_calls() + + +def flipped_case(world: Flipped) -> None: + """`[flipped]` (TP:2601-2606): the same `log NOTED` exits 0, the journal + gains one entry, the shim's log holds one attempt of two calls (Q7 (A'')), + the snapshot and then the commit, each as `register_url=`'s login with + `register_passfile=` and no `PGPASSWORD`, and the files are unchanged.""" + before, entries = world.origin_and_head(), journal_count(world.db) + proc = world.write("test 14 - flipped, a primary write") + assert proc.returncode == 0, shown(proc) + assert journal_count(world.db) == entries + 1, "the journal did not gain one entry" + sent = world.shim_calls() + assert len(sent) == 2, ("one attempt is two calls, the snapshot and the commit", sent) + assert "commit_write" not in sent[0]["stdin"] and "commit_write" in sent[1]["stdin"], \ + ("the snapshot first, then the commit", [s["stdin"][:200] for s in sent]) + for call in sent: + pg = call.get("pg", {}) + assert (pg.get("PGUSER"), pg.get("PGHOST"), pg.get("PGDATABASE")) == ( + LOGIN_WRITER, str(world.db.host), world.db.name), ("not register_url='s login", pg) + assert call.get("passfile") == str(world.passfile), ("not register_passfile=", call) + assert call.get("pgpassword") is False, ("PGPASSWORD reached psql", call) + assert world.origin_and_head() == before, "the files moved: this build has no git half" + modes = [c for c in calls(world.bin) if c["argv"] == ["mode"]] + assert len(modes) == 1, ("the primary write asked the mode more than once, or never: the " + "parent asks it once, and the attempt's child asks none (Y:5038, " + "Y:5452)", [c["argv"] for c in calls(world.bin)]) + + +def replay_keeps_pid_case(state: Refusing) -> None: + """`[replay-keeps-pid]` (R-T409-9; lane 3, #165 6747281902, T409's item + 9; lane 3's proposal, 6852014823, confirmed by lane 2 in 6858869119): with + a configuration, an unrouted write whose first push loses a race runs + again by S4's replay, an `exec` that keeps the pid, and asks the mode + once: one `mode` call in the stand-in's log (Y:4858, Y:5121). In `index` + mode, with no engine: a 0600 `mode=index` file named by + `LANES_INDEX_CONFIG`, `LANES_INDEX=off`, the write through `Estate`'s + explicit `LANES_REPO` with no routing, and `tests/a23_box.py`'s + `NET_GIT` as `LANES_GIT` with `RACE_HOOK` behind it. It asserts exit 0, + `push refused (attempt 1 of 6)`, `pushed origin/main (attempt 2)`, and + one `mode` call.""" + import a23_box + net_git = getattr(a23_box, "NET_GIT", None) + assert net_git, ("tests/a23_box.py has no NET_GIT, the LANES_GIT this case races the " + "write's first push through (Amendment 23 S4)") + e = state.e + conf = state.other_config("index.conf", "mode=index\n") + bin_dir = state.root / "replay-bin" + edit = beside(bin_dir, helpers.LANES_INDEX) + peer = state.root / "peer" + for argv in (("clone", "-q", str(e.origin), str(peer)), + ("-C", str(peer), "config", "user.name", "test 14's peer"), + ("-C", str(peer), "config", "user.email", "peer@example.invalid")): + proc = e.run("git", *argv) + assert proc.returncode == 0, ("the peer, a clone of origin", argv, shown(proc)) + net = bin_dir / "net-git" + net.write_text(net_git, encoding="utf-8") + net.chmod(0o755) + hook = bin_dir / "net-hook" + hook.write_text(RACE_HOOK.replace("@PEER@", shlex.quote(str(peer))) + .replace("@COUNT@", shlex.quote(str(state.root / "race.count"))), + encoding="utf-8") + hook.chmod(0o755) + proc = state.edit(edit, "log", "NOTED", f"lane:{WRITING_LANE}", + "test 14 - a replay keeps its pid", + LANES_INDEX_CONFIG=str(conf), LANES_INDEX="off", LANES_LANE=WRITING_LANE, + LANES_GIT=str(net), FAKE_NET_LOG=str(state.root / "net.log"), + FAKE_NET_HOOK=str(hook)) + assert proc.returncode == 0, shown(proc) + assert "push refused (attempt 1 of 6)" in proc.stderr, \ + ("the first push did not lose the race, so the write did not replay", shown(proc)) + assert "pushed origin/main (attempt 2)" in proc.stderr, \ + ("the replayed write did not publish", shown(proc)) + modes = [c for c in calls(bin_dir) if c["argv"] == ["mode"]] + assert len(modes) == 1, ("the mode ask was made more than once, or never, across the replay", + [c["argv"] for c in calls(bin_dir)]) + + +STATE_CASES = { + "refusing": refusing_case, + "mode-under-index-off": mode_under_index_off_case, + "flipped": flipped_case, + "replay-keeps-pid": replay_keeps_pid_case, +} + +#: The case that needs the real engine, taken by `request.getfixturevalue`. +FLIPPED_CASES = ("flipped",) + + +@pytest.mark.parametrize("case", list(STATE_CASES)) +def test_mode_primary_is_refused_until_the_git_half_and_goes_to_sql_once_flipped( + estate, request, case): + """Test 14's one test of both states (AT-14): with the refusal in place, + `mode=primary` is refused where the configuration is read, 78 from + `mode`, 2 from every other command, with the fixed text; with the constant + flipped, the same write goes to SQL.""" + if case in FLIPPED_CASES: + STATE_CASES[case](Flipped(estate, request.getfixturevalue("pg"))) + else: + STATE_CASES[case](Refusing(estate)) + + +def test_lanes_edit_asks_lanes_index_mode_only_where_a_configuration_exists(estate): + """D3 (FR-002; contract section 3.1, "Asked only where a configuration + exists"): with no configuration file and `LANES_INDEX_CONFIG` unset, a + logging stand-in at `lanes-index`'s path records no call, and the verb + writes in files mode. `LANES_INDEX=off`, which `tests/conftest.py` sets + for the run and which skips the index's nudge, never skips the mode query + (Y:5717), so under it the only call a write could make is the one D3 + bars. Then `--index`, with the variable unset, reaches the stand-in, so + the stand-in is where `lanes-edit.sh` finds `lanes-index`.""" + bin_dir = estate.root / "d3-bin" + edit = beside(bin_dir, helpers.LANES_INDEX) + assert not (estate.config / "openRepoTools" / "lanes-index.conf").exists() + env = {"LANES_EDIT": str(edit), "LANES_INDEX_CONFIG": None, "LANES_INDEX": "off", + "LANES_LANE": "repoA-2"} + tip = estate.tip() + text = "test 14 - D3, a write with no configuration" + proc = estate.run("bash", edit, "log", "NOTED", "lane:repoA-2", text, env=env) + assert proc.returncode == 0, shown(proc) + assert calls(bin_dir) == [], ("the stand-in at lanes-index's path was called", calls(bin_dir)) + assert estate.tip() != tip, "the write did not push" + assert text in estate._git("show", "origin/main:lanes/log/repoA-2.md"), \ + "the note is not in the files" + proc = estate.run("bash", edit, "lanes", "--index", + env={"LANES_EDIT": str(edit), "LANES_INDEX_CONFIG": None, + "LANES_INDEX": None}) + assert [c["argv"][:1] for c in calls(bin_dir)] == [["export"]], ( + "`lanes --index` did not reach the stand-in, so it is not where lanes-edit.sh " + "finds lanes-index", calls(bin_dir), shown(proc)) + + +def test_mode_primary_with_sqlite_is_refused(estate): + """`mode=primary` with `store=sqlite`, or with no `register_url=` (whose + store is SQLite by default), on T203's flipped copy, where Q6(c)'s + refusal is lifted: T104's refusal answers 2 (L1v4.10:117), with nothing + on stdout and a `REFUSED:` line that is not Q6(c)'s text (lane 2's + reading, NOTES question 29). `lanes-index mode` reads the configuration + whatever `LANES_INDEX` says (lane 3, #165 6747957479).""" + refused = exit_code("EXIT_REFUSED") + state = Refusing(estate) + copy = state_copy(state.root / "flipped", True) + for name, text in (("store-sqlite", state.config_text(store="sqlite")), + ("no-register-url", state.config_text(register=False))): + conf = state.other_config(f"{name}.conf", text) + proc = state.index(copy, "mode", LANES_INDEX_CONFIG=str(conf)) + assert proc.returncode == refused, (name, shown(proc)) + assert proc.stdout == "", (name, shown(proc)) + lines = proc.stderr.splitlines() + assert len(lines) == 1 and lines[0].startswith(PREFIX + "REFUSED: "), (name, shown(proc)) + assert REFUSED_TEXT not in proc.stderr, (name, "Q6(c)'s text from the flipped copy", + shown(proc)) + assert state.psql_calls() == [], state.psql_calls() + + +#: `register read`'s forms (contract section 3.6; its section 2.7's 78 row): +#: the readers', forms 1 and 3, and `--for guard`'s, forms 2 and 4. +def read_forms(family: str, state: Refusing) -> list: + cache = str(state.root / "cache") + pid = str(os.getpid()) + if family == "readers": + return [["--prefetch", "--cache", cache, "--all"], + ["--since", "0", "--cache", cache, "--files", "register"]] + return [["--for", "guard", "--prefetch", "--cache", cache, "--pid", pid, + "--repo", str(state.e.wip), "--lane=repoA-2"], + ["--for", "guard", "--at", "1", "--pid", pid, "--cache", cache, + "--lane=repoA-2"]] + + +@pytest.mark.parametrize("family", ["readers", "for-guard"]) +def test_register_read_exits_78_under_the_refusal(estate, family): + """`lanes-index register read`, in each of its forms, exits 78 with the + text, never 2 (AT-14; contract section 2.7): readers and the guard learn + the mode from it. Nothing connects, and no cache is written.""" + config_code = exit_code("EXIT_CONFIG") + state = Refusing(estate) + for argv in read_forms(family, state): + proc = state.index(state.copy, "register", "read", *argv) + assert proc.returncode == config_code, (argv, shown(proc)) + assert REFUSED_TEXT in proc.stderr, (argv, shown(proc)) + assert state.psql_calls() == [], state.psql_calls() + assert not (state.root / "cache").exists(), "a cache was written under the refusal" + + +@pytest.mark.parametrize("reader", READER_CASES) +def test_readers_under_the_refusal_answer_the_78_as_a_failed_read(estate, reader): + """The readers, run from the same estate under the refusal (AT-14; the + delta's "Readers under the refusal"; the phase plan's "D3's refusal"): + `register read` answers 78, and each reader answers it as a failed read. + A read that decides exits 69 with nothing on stdout; a listing and the + `SessionStart` block answer from the mirror, exit 0, with the `read: + mirror` line on stderr; the prompt guard exits 2; `managed-projection` + answers 1, UNKNOWN, never 8. The fake `psql`'s log stays empty, and the + files and origin are unchanged. The guard runs in the lane's window with + a live session record (`in_the_lane_window`), as the guard keeps its + order: with no window, or no session record, it refuses 2 before any + read, so it would never ask `lanes-index` (lane 3's T507 ruling (1), + #165 6783977598).""" + state = Refusing(estate) + bin_dir = state.root / "bin" + edit = beside(bin_dir, state.copy) + before = state.origin_and_head() + + def asked(proc, what): + assert calls(bin_dir), (what, "lanes-edit.sh never asked lanes-index, so it never met " + "the refusal", shown(proc)) + + if reader in DECIDE_READS: + proc = state.edit(edit, *DECIDE_READS[reader]) + asked(proc, reader) + assert proc.returncode == READ_FAILED, (reader, shown(proc)) + assert proc.stdout == "", (reader, shown(proc)) + elif reader == "listing": + for argv in LISTINGS: + forget_calls(bin_dir) + proc = state.edit(edit, *argv) + asked(proc, argv) + assert proc.returncode == 0, (argv, shown(proc)) + assert MIRROR_LINE.search(proc.stderr), (argv, "no `read: mirror` line", shown(proc)) + assert not MIRROR_LINE.search(proc.stdout), (argv, shown(proc)) + assert proc.stdout.strip(), (argv, "the mirror gave no answer", shown(proc)) + elif reader == "session-start": + proc = state.edit(edit, "session-start") + assert proc.returncode == 0, shown(proc) + assert MIRROR_LINE.search(proc.stderr), ("no `read: mirror` line", shown(proc)) + assert not MIRROR_LINE.search(proc.stdout), shown(proc) + elif reader == "guard": + window_env, hook = in_the_lane_window(state) + proc = state.edit(edit, "guard", input_text=hook, **window_env) + asked(proc, "guard") + assert proc.returncode == GUARD_REFUSED, shown(proc) + else: + proc = state.edit(edit, "managed-projection", "repoM-1") + asked(proc, "managed-projection") + assert proc.returncode == PROJECTION_UNKNOWN, shown(proc) + assert proc.returncode != PROJECTION_NEVER, shown(proc) + assert "UNKNOWN" in proc.stderr, shown(proc) + assert state.psql_calls() == [], ("a reader connected under the refusal", state.psql_calls()) + assert state.origin_and_head() == before, "the files or origin moved" + + +# ------------------------------------- T256: the render fork's stub test +def release(fifo: Path) -> bool: + """Let a call held on `fifo` go: open it for writing, which a held reader + makes possible at once, and close it. False where nothing holds it.""" + try: + fd = os.open(str(fifo), os.O_WRONLY | os.O_NONBLOCK) + except OSError: + return False + os.close(fd) + return True + + +def within(seconds: float, find): + """`find()` once it is truthy, or its last answer when `seconds` pass.""" + deadline = time.monotonic() + seconds + found = find() + while not found and time.monotonic() < deadline: + time.sleep(0.05) + found = find() + return found + + +@pytest.mark.parametrize("case", list(FORK_CASES)) +def test_a_primary_write_forks_render_checkout_on_the_lane_checkout_detached(estate, pg, case): + """The render fork (phase W's stub test; TP:2612-2629; lane 4's section, + "What phase 2 ships for phase 3", "The renderer fork"): after a primary + write commits, the stand-in's log holds one `render` call, made by a + detached fork, `render --checkout `, `` the writing lane's + checkout, `-lanes//`; with no `LANES_NO_FETCH` in its + environment though the verb ran with it in `[no-fetch-set]` (D12); made + though `LANES_INDEX=off` is set in `[index-off-set]`, since + `lane-worktrees` sets that variable on every call (Y:5717); with its stdin + closed or `/dev/null` and its descriptors 3 to 9 closed, as + `index_nudge`'s fork has them; and the writer exits with the verb's own + code while the stand-in holds the call on a FIFO, so no fork waits.""" + world = Flipped(estate, pg) + fifo = world.root / "render.fifo" + os.mkfifo(str(fifo)) + (world.bin / HOLD_FILE).write_text(str(fifo) + "\n", encoding="utf-8") + try: + try: + proc = world.write(f"test 14 - the render fork, {case}", timeout=90, + **world.routed(), **FORK_CASES[case]) + except subprocess.TimeoutExpired: + pytest.fail("the writer did not exit while the render call was held: it waited for " + "its fork", pytrace=False) + assert proc.returncode == 0, ("the verb's own code", shown(proc)) + + def renders(): + return [c for c in calls(world.bin) if c["argv"][:1] == ["render"]] + + held = within(FORK_SECONDS, renders) + assert len(held) == 1, ("one render call, made by the fork", + [c["argv"] for c in calls(world.bin)]) + call = held[0] + argv = call["argv"] + assert argv[:2] == ["render", "--checkout"] and len(argv) == 3, argv + assert os.path.realpath(argv[2].rstrip("/")) == os.path.realpath(world.lane_checkout()), \ + (" is the writing lane's checkout", argv[2], world.lane_checkout()) + assert "LANES_NO_FETCH" not in call["env"], ("the fork carries LANES_NO_FETCH", case) + assert call["fds"]["0"] in ("closed", "devnull"), ("the fork's stdin is open", call["fds"]) + assert [n for n in range(3, 10) if call["fds"][str(n)] != "closed"] == [], \ + ("descriptors 3 to 9 are not all closed", call["fds"]) + assert not (world.bin / ENDS_LOG).exists(), \ + "the held render call ended before it was let go" + finally: + released = within(FORK_SECONDS, lambda: release(fifo)) + assert released, "no render call was held on the FIFO to let go" + ended = within(FORK_SECONDS, lambda: (world.bin / ENDS_LOG).exists()) + assert ended, "the render call did not end once it was let go" diff --git a/tests/test_sql_register_marker.py b/tests/test_sql_register_marker.py new file mode 100644 index 00000000..20d23b80 --- /dev/null +++ b/tests/test_sql_register_marker.py @@ -0,0 +1,1091 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Feature 007's test 3, the marker `lanes/STORE` (AT-3; opensoft/openRepoTools#165). + +T225 (L2-N7; A8): `wip init`'s two cases, AT-3's three reader cases and lane +5's three marker guesses, all in phase N, all FM, with no database: + +- `openRepoTools wip init` refuses under the marker, and wherever any file + under `lanes/` exists with no marker, with no configuration and with + `mode=index` (Q14(a); FR-005). The refusal exits 2, under the marker and + without it, names the path it found, and prints no `mode=primary` line: that + line and AT-3's 69 are the writers' (lane 3, #165 6771319904; T225c). They + fail until lane 3's T303 lands. +- The readers' marker check, F17 (design Y, "F17: the marker check for + readers"; Y:3055-3068): on a workstation that is not `mode=primary`, a + reader checks the ref its read uses for `lanes/STORE`; an act refuses 69 + and the guard 2, both with Amendment 22's text, and the listings and the + `SessionStart` block read on with the `read: mirror` line. All six are + lane 5's L5-A5, T504 to T508 (T225's Order), and each fails only until the + task whose `verify:` runs it: AT-3's three reader cases until T504 + (tasks:713, at B19 and at the follow-up head `09096c6d`), and lane 5's + three guesses until T506, T507 and T508, one each, as their docstrings + say. + +T242 (L2-W1, L2-W5; FR-002, FR-004, FR-059) adds test 3's unit form and +AT-F8, phase W, FM, with no database: the writers' marker check, and every +failure of the mode query. They fail until lane 4's L4-B1 (T409) and L4-B12 +(T419) and lane 5's L5-A5 land. See "phase W: T242" below. + +The estate is T215's and T220's, as T203c's helper test builds it: a bare +origin, the lane's checkout under `$HOME/projects`, `$HOME/.agents/ +workspace.yaml` naming it, and the register pushed. The marker is committed +by hand on the origin (lane 4's row 8), with D21's five fields one per line in +D21's order (Y:613-615; lane 1, F10's items 22 and 23). +""" + +from __future__ import annotations + +import hashlib +import json +import os +import re +import shutil +import subprocess +import textwrap +import time +import uuid +from pathlib import Path + +import pytest + +from conftest import REPO, WINDOWS_SKIP +from sql_register_helpers import GUARD_WINDOW, 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; 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 T225's Order +#: (tasks:2166) and T242's (tasks:2331), tasks.md at lane 3's commit 17 +#: `204145ae`. No task is common to all 13 functions, so there is no "*" row. +SQL_REGISTER_GATE_TABLE = { + # T225: `wip init`'s two cases until T303; AT-3's three reader cases until + # T504, whose verify runs them (tasks:713); lane 5's three guesses until + # their own tasks, one each: T506 (tasks:769), T508 (tasks:822) and T507 + # (tasks:780). + "test_wip_init_refuses_under_the_marker": ("T303",), + "test_wip_init_refuses_where_a_lanes_file_exists_with_no_marker": ("T303",), + "test_a_readers_refusal_under_the_marker_names_the_refs_age": ("T504",), + "test_a_reader_refuses_when_its_read_ref_carries_the_marker_and_its_tree_does_not": ("T504",), + "test_an_unconfigured_workstations_acts_refuse_and_listings_read_the_mirror": ("T504",), + "test_the_marker_check_runs_at_the_end_of_log_sync": ("T506",), + "test_the_session_start_block_reads_on_under_the_marker_with_its_mirror_line": ("T508",), + "test_a_mode_index_guard_refuses_2_under_the_marker": ("T507",), + # T242: the writer cases until T419 (L4-B12), the `mode=index` one also + # until T409 (L4-B1); the q6c case until T409; and AT-F8's ids until + # T409, its `sql` ones also until T419: the function's row holds both, + # and each of its 20 `files` ids has its own row, T409 alone (lane 3's + # ruling 7, opensoft/openRepoTools#165 6879724890). + "test_a_files_mode_writer_refuses_under_the_marker": ("T419",), + "test_a_mode_index_writer_refuses_under_the_marker": ("T409", "T419"), + "test_a_writer_with_no_fetch_refuses_when_its_tip_carries_the_marker": ("T419",), + "test_the_q6c_refusal_has_its_own_code_and_the_writer_exits_69": ("T409",), + "test_any_other_mode_query_failure_runs_files_mode_with_a_warning": ("T409", "T419"), + "test_any_other_mode_query_failure_runs_files_mode_with_a_warning[refused-2-index-files]": + ("T409",), + "test_any_other_mode_query_failure_runs_files_mode_with_a_warning[refused-2-primary-files]": + ("T409",), + "test_any_other_mode_query_failure_runs_files_mode_with_a_warning[too-old-64-index-files]": + ("T409",), + "test_any_other_mode_query_failure_runs_files_mode_with_a_warning[too-old-64-primary-files]": + ("T409",), + "test_any_other_mode_query_failure_runs_files_mode_with_a_warning[crash-1-index-files]": + ("T409",), + "test_any_other_mode_query_failure_runs_files_mode_with_a_warning[crash-1-primary-files]": + ("T409",), + "test_any_other_mode_query_failure_runs_files_mode_with_a_warning[removed-127-index-files]": + ("T409",), + "test_any_other_mode_query_failure_runs_files_mode_with_a_warning[removed-127-primary-files]": + ("T409",), + "test_any_other_mode_query_failure_runs_files_mode_with_a_warning[signal-index-files]": + ("T409",), + "test_any_other_mode_query_failure_runs_files_mode_with_a_warning[signal-primary-files]": + ("T409",), + "test_any_other_mode_query_failure_runs_files_mode_with_a_warning[not-one-line-index-files]": + ("T409",), + "test_any_other_mode_query_failure_runs_files_mode_with_a_warning[not-one-line-primary-files]": + ("T409",), + "test_any_other_mode_query_failure_runs_files_mode_with_a_warning[exit-69-index-files]": + ("T409",), + "test_any_other_mode_query_failure_runs_files_mode_with_a_warning[exit-69-primary-files]": + ("T409",), + "test_any_other_mode_query_failure_runs_files_mode_with_a_warning[exit-75-index-files]": + ("T409",), + "test_any_other_mode_query_failure_runs_files_mode_with_a_warning[exit-75-primary-files]": + ("T409",), + "test_any_other_mode_query_failure_runs_files_mode_with_a_warning[exit-3-index-files]": + ("T409",), + "test_any_other_mode_query_failure_runs_files_mode_with_a_warning[exit-3-primary-files]": + ("T409",), + "test_any_other_mode_query_failure_runs_files_mode_with_a_warning[hang-index-files]": + ("T409",), + "test_any_other_mode_query_failure_runs_files_mode_with_a_warning[hang-primary-files]": + ("T409",), +} + +EDIT = REPO / "lanes-edit.sh" +LANES = REPO / "lanes" +COMMAND = REPO / "openRepoTools" + +#: Amendment 22's text, the refusal of an act and of the guard under the +#: marker (Y:3060-3062; AT-3's oracle). +AMENDMENT_22 = "this estate's register is SQL; configure `mode=primary`" +#: The third line of the `read:` family (Y:3048-3050): `read: mirror at +#: , sequences behind or unknown (sql unreachable: )`. +MIRROR_LINE = "read: mirror at " +#: How old the ref is, in the refusal (AT-3: "its text says how old the ref it +#: read is"): a count with a unit, or "ago". The form is not fixed by any +#: contract; this is the loosest reading of it. +AGE = re.compile(r"\b\d+ ?(s|sec|secs|second|seconds|m|min|mins|minute|minutes|h|hour|hours|" + r"d|day|days|w|week|weeks)\b|\bago\b", re.I) + +#: D21's five fields, one per line, in D21's order. +STORE_TEXT = ("store=primary\ndatabase=lanes-register-test\n" + "import=0123456789abcdef0123456789abcdef01234567\n" + "lanes-tree=89abcdef0123456789abcdef0123456789abcdef\n" + "utc=2026-10-01T00:00:00Z\n") +#: The marker commit's date, so its age is days, never seconds. +MARKER_DATE = "2026-10-01T00:00:00Z" +DOT = chr(0xB7) +REGISTER_HEADER = ["# LANES.md", "", + "| lane | session id | workstation / env / user | started (UTC) | objects " + "owned | handoff path | state |", + "|---|---|---|---|---|---|---|"] +CONFIGURATIONS = ("none", "index") +#: `wip init`'s refusal code, under the marker and without it (lane 3, #165 +#: 6771319904; `openRepoTools:3682`: "EXIT CODES ARE 0 AND 2"), and the text of +#: the `mode=primary` line, which is the writers' and never `wip init`'s. +WIP_REFUSED = 2 +MODE_PRIMARY = "mode=primary" + + +def _register(session_id: str) -> str: + """A register whose one row binds `GUARD_WINDOW` to `session_id`, in + T215's row form.""" + row = (f"| `{GUARD_WINDOW}` | harness `{session_id}` | Eagle / test / brett " + f"| 2026-10-01T00:00Z | none | handoffs/{GUARD_WINDOW}.md " + f"| LIVE {DOT} 2026-10-01T02:00:00Z {DOT} working |") + return "\n".join(REGISTER_HEADER + [row, ""]) + + +def _git(cwd: Path, env: dict, *argv: str) -> str: + return subprocess.run(["git", *argv], cwd=str(cwd), check=True, env=env, + capture_output=True, text=True).stdout.strip() + + +def _configure(root: Path, env: dict, configuration: str) -> None: + """No configuration, or `mode=index` (AT-3's two configurations), in + `$XDG_CONFIG_HOME/openRepoTools/lanes-index.conf`, mode 0600 (CLI section 2.5).""" + if configuration == "index": + conf = Path(env["XDG_CONFIG_HOME"]) / "openRepoTools" / "lanes-index.conf" + conf.parent.mkdir(parents=True, exist_ok=True) + conf.write_text("mode=index\n", encoding="utf-8") + conf.chmod(0o600) + + +def _push_marker(root: Path, origin: Path, env: dict) -> str: + """Commit `lanes/STORE` by hand on origin's `main`, from a clone of its + own (lane 4's row 8). Returns the marker commit's sha.""" + hand = root / "hand" + subprocess.run(["git", "clone", "-q", str(origin), str(hand)], check=True, env=env, + capture_output=True) + (hand / "lanes" / "STORE").write_text(STORE_TEXT, encoding="utf-8") + dated = dict(env, GIT_AUTHOR_DATE=MARKER_DATE, GIT_COMMITTER_DATE=MARKER_DATE) + _git(hand, dated, "add", "lanes/STORE") + _git(hand, dated, "commit", "-q", "-m", "cutover: lanes/STORE") + _git(hand, dated, "push", "-q", "origin", "main") + return _git(hand, env, "rev-parse", "HEAD") + + +def _estate(root: Path, session_id: str, configuration: str = "none") -> tuple: + """T215's and T220's estate, whose register's row names `session_id`. + Returns (`home`, the checkout, the origin, the base environment).""" + home = root / "home" + wip = home / "projects" / "wip" + origin = root / "origin.git" + wip.parent.mkdir(parents=True) + (root / "t").mkdir() + env = guard_strip_env(os.environ) + 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_NO_FETCH="1", + LANES_REPO=str(wip), + GIT_AUTHOR_NAME="t", GIT_AUTHOR_EMAIL="t@example.invalid", + GIT_COMMITTER_NAME="t", GIT_COMMITTER_EMAIL="t@example.invalid") + 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" / "log").mkdir(parents=True) + (wip / "lanes" / "LANES.md").write_text(_register(session_id), encoding="utf-8") + (wip / "lanes" / "log" / "README.md").write_text("logs.\n", encoding="utf-8") + for argv in (["add", "-A"], ["commit", "-q", "-m", "C"], ["push", "-q", "origin", "main"]): + _git(wip, env, *argv) + (home / ".agents").mkdir() + (home / ".agents" / "workspace.yaml").write_text( + f"repository: {origin}\npath: {wip}\n", encoding="utf-8") + _configure(root, env, configuration) + return home, wip, origin, env + + +def _run(argv: list, env: dict, cwd: Path, stdin: str = "") -> tuple: + """One run of the lane tooling. Returns (its exit, stdout, stderr).""" + proc = subprocess.run(["bash", *map(str, argv)], input=stdin, capture_output=True, + text=True, cwd=str(cwd), env=env, timeout=120, + start_new_session=True) + return proc.returncode, proc.stdout, proc.stderr + + +# --- `wip init` (T303) -------------------------------------------------------- + +#: The nine template files (`openRepoTools`' `WIP_TEMPLATE_FILES`), served by +#: the fake `gh` from a directory of its own, so these cases need no submodule. +TEMPLATE_FILES = ("README.md", "AGENTS.md", "CLAUDE.md", ".gitattributes", + ".gitignore", "handoffs/README.md", "lanes/LANES.md", + "lanes/log/README.md", "workspaces/.gitkeep") + + +def _template_text(rel: str) -> str: + """A template file's stand-in text: one comment line, so `.gitignore` + ignores nothing, and `.gitkeep` empty, as upstream's is.""" + return "" if rel.endswith(".gitkeep") else f"# {rel}\n" + + +def _wip_fake_gh(root: Path) -> Path: + """A `gh` that answers `wip init`'s calls as `test_wip_init_command.py`'s + does, with the repository already created by an administrator, and serves + the template from `/shape`. A `curl` that refuses.""" + shape = root / "shape" / "templates" / "workspace-root" + for rel in TEMPLATE_FILES: + (shape / rel).parent.mkdir(parents=True, exist_ok=True) + (shape / rel).write_text(_template_text(rel), encoding="utf-8") + server = root / "github" + fake = root / "fake-path" + fake.mkdir() + (fake / "gh").write_text(textwrap.dedent(f"""\ + #!/usr/bin/env bash + set -u + server={server!s} + slug_path() {{ printf '%s\\n' "$server/$1.git"; }} + case "$1 ${{2-}}" in + "api user") printf '%s\\n' brettheap; exit 0 ;; + "api --paginate") printf '%s\\n' platform; exit 0 ;; + esac + case "$*" in + "repo view "*) [ -d "$(slug_path "$3")" ] && exit 0; exit 1 ;; + "repo create "*) exit 1 ;; + "repo clone "*) + git clone -q "$(slug_path "$3")" "$4" || exit 1 + git -C "$4" config user.email wip@example.invalid + git -C "$4" config user.name "wip init tests" + exit 0 ;; + "api --method PUT"*) exit 0 ;; + *"/contents/"*) + path="${{*}}"; path="${{path##*/contents/}}"; path="${{path%%\\?*}}" + src="{root / 'shape'!s}/$path" + [ -f "$src" ] && exec cat -- "$src" + exit 1 ;; + esac + printf 'fake gh: unexpected call: %s\\n' "$*" >&2 + exit 1 + """), encoding="utf-8") + (fake / "curl").write_text("#!/bin/sh\nprintf 'no test here may reach the network\\n' >&2\n" + "exit 1\n", encoding="utf-8") + for name in ("gh", "curl"): + (fake / name).chmod(0o755) + return fake + + +def _wip_origin(root: Path, files: dict, env: dict) -> Path: + """`opensoft/brettheap-wip` on the fake server, its `main` carrying + `files` (path to text), as an administrator or a cutover left it.""" + origin = root / "github" / "opensoft" / "brettheap-wip.git" + origin.parent.mkdir(parents=True) + subprocess.run(["git", "init", "-q", "--bare", "-b", "main", str(origin)], check=True, + env=env) + seed = root / "seed" + subprocess.run(["git", "clone", "-q", str(origin), str(seed)], check=True, env=env, + capture_output=True) + for rel, text in files.items(): + (seed / rel).parent.mkdir(parents=True, exist_ok=True) + (seed / rel).write_text(text, encoding="utf-8") + _git(seed, env, "add", "-A") + _git(seed, env, "commit", "-q", "-m", "the estate as it stands") + _git(seed, env, "push", "-q", "origin", "main") + return origin + + +def _wip_init(root: Path, files: dict, configuration: str) -> tuple: + """Runs `openRepoTools wip init` against an origin carrying `files`. + Returns (exit, output, origin's refs before, origin's refs after, the + checkouts under `$HOME/projects` with a commit origin's `main` lacks).""" + root.mkdir(parents=True, exist_ok=True) + home = root / "home" + (home / "projects").mkdir(parents=True) + env = {k: v for k, v in os.environ.items() + if not k.startswith(("LANES_", "OPENREPOTOOLS_", "CLAUDE_", "GIT_")) + and k not in ("AGENT_PROTOCOL_ROOT", "PROJECTS_DIR", "PROJECTS_ROOT", "TMUX", + "TMUX_PANE")} + env.update(HOME=str(home), AGENT_PROTOCOL_ROOT=str(home / ".agents"), + PROJECTS_DIR=str(home / "projects"), OPENREPOTOOLS_BIN_DIR=str(home / "bin"), + XDG_CONFIG_HOME=str(root / "config"), XDG_STATE_HOME=str(root / "state"), + GIT_AUTHOR_NAME="wip tests", GIT_COMMITTER_NAME="wip tests", + GIT_AUTHOR_EMAIL="wip@example.invalid", + GIT_COMMITTER_EMAIL="wip@example.invalid") + fake = _wip_fake_gh(root) + env["PATH"] = f"{fake}{os.pathsep}{env.get('PATH', '/usr/bin:/bin')}" + origin = _wip_origin(root, files, env) + _configure(root, env, configuration) + before = _git(origin, env, "for-each-ref", "--format=%(refname) %(objectname)") + main = _git(origin, env, "rev-parse", "main") + proc = subprocess.run(["bash", str(COMMAND), "wip", "init"], capture_output=True, + text=True, cwd=str(REPO), env=env, input="", timeout=120, + check=False) + after = _git(origin, env, "for-each-ref", "--format=%(refname) %(objectname)") + ahead = [] + for checkout in sorted((home / "projects").iterdir()): + if (checkout / ".git").exists(): + head = _git(checkout, env, "rev-parse", "HEAD") + status = _git(checkout, env, "status", "--porcelain", "--", ".") + if head != main or status: + ahead.append(f"{checkout.name}: HEAD {head[:12]}, status {status!r}") + return proc.returncode, proc.stdout + proc.stderr, before, after, ahead + + +def _assert_wip_refused(code: int, out: str, before: str, after: str, ahead: list, + path: str, where: str) -> None: + """T303's refusal (lane 3, #165 6771319904): exit 2, `openRepoTools`' + refusal code ("EXIT CODES ARE 0 AND 2", `openRepoTools:3682`), the path it + found named, no `mode=primary` line, nothing committed or queued, and + origin's refs unchanged.""" + assert code == WIP_REFUSED, \ + f"{where}: wip init exited {code}, not {WIP_REFUSED}, with {path} on origin\n{out[-900:]}" + assert path in out, f"{where}: the refusal does not name {path}\n{out[-900:]}" + primary = [x for x in out.splitlines() if MODE_PRIMARY in x] + assert not primary, \ + f"{where}: wip init prints a {MODE_PRIMARY} line, which is the writers': {primary}" + assert after == before, f"{where}: origin's refs moved\n{before}\n->\n{after}" + assert not ahead, f"{where}: a commit or a write is queued: {ahead}\n{out[-900:]}" + + +def test_wip_init_refuses_under_the_marker(tmp_path): + """AT-3 (Q14(a); FR-005): with `lanes/STORE` on origin's `main`, `wip init` + refuses with 2, names the marker, prints no `mode=primary` line and + commits nothing, the same with no configuration and with `mode=index`. + Fails until T303.""" + files = {rel: _template_text(rel) for rel in TEMPLATE_FILES + if not rel.endswith(".gitkeep")} + files["lanes/log/README.md"] = "logs.\n" + files["lanes/STORE"] = STORE_TEXT + for configuration in CONFIGURATIONS: + code, out, before, after, ahead = _wip_init(tmp_path / configuration, files, + configuration) + _assert_wip_refused(code, out, before, after, ahead, "lanes/STORE", configuration) + + +@pytest.mark.parametrize("found", ["LANES.md", "repos.tsv"]) +@pytest.mark.parametrize("configuration", CONFIGURATIONS) +def test_wip_init_refuses_where_a_lanes_file_exists_with_no_marker(tmp_path, configuration, + found): + """AT-3's third exception: with no marker and one file under `lanes/`, + `wip init` refuses with 2, names the file, prints no `mode=primary` line + and commits nothing. `LANES.md` is found with `lanes/log/README.md` + missing, the file today's run commits as owed (`openRepoTools:5026-5080`); + `repos.tsv` is found alone. Fails until T303.""" + files = {"README.md": _template_text("README.md"), f"lanes/{found}": f"lanes/{found}\n"} + code, out, before, after, ahead = _wip_init(tmp_path, files, configuration) + _assert_wip_refused(code, out, before, after, ahead, f"lanes/{found}", + f"{configuration}-{found}") + + +# --- the readers' marker check, F17 (L5-A5) ----------------------------------- + +def _who(wip: Path, env: dict) -> tuple: + return _run([EDIT, "who", "--lane", GUARD_WINDOW], env, wip) + + +def test_a_readers_refusal_under_the_marker_names_the_refs_age(tmp_path): + """AT-3 (Q21(a)(A)): an unconfigured reader whose read ref carries the + marker refuses with 69, Amendment 22's text, and how old that ref is + (Y:3065: "the refusal says how old it is"). Fails until T504.""" + home, wip, origin, env = _estate(tmp_path, str(uuid.uuid4())) + _push_marker(tmp_path, origin, env) + _git(wip, env, "fetch", "-q", "origin", "main") + _git(wip, env, "merge", "-q", "--ff-only", "origin/main") + code, out, err = _who(wip, env) + assert code == 69, f"who exited {code} under the marker\n{out[-600:]}{err[-600:]}" + assert AMENDMENT_22 in err, f"no Amendment 22 text on stderr\n{err[-900:]}" + line = next(x for x in err.splitlines() if AMENDMENT_22 in x or "origin/main" in x) + assert "origin/main" in err and AGE.search(err), \ + f"the refusal names no age for the ref it read ({line!r})\n{err[-900:]}" + + +def test_a_reader_refuses_when_its_read_ref_carries_the_marker_and_its_tree_does_not( + tmp_path): + """AT-3: the check runs on the ref the read uses, never the working tree. + The checkout's tree lacks `lanes/STORE` and `origin/main` carries it: the + reader refuses 69. Then a tree that carries it over a ref that does not + reads on as today. Fails until T504.""" + home, wip, origin, env = _estate(tmp_path / "a", str(uuid.uuid4())) + _push_marker(tmp_path / "a", origin, env) + _git(wip, env, "fetch", "-q", "origin", "main") + assert not (wip / "lanes" / "STORE").exists() + code, out, err = _who(wip, env) + assert code == 69 and AMENDMENT_22 in err, \ + f"the ref carries the marker, the tree does not: {code}\n{out[-600:]}{err[-600:]}" + + home, wip, origin, env = _estate(tmp_path / "b", str(uuid.uuid4())) + (wip / "lanes" / "STORE").write_text(STORE_TEXT, encoding="utf-8") + _git(wip, env, "add", "lanes/STORE") + _git(wip, env, "commit", "-q", "-m", "a local marker, never pushed") + code, out, err = _who(wip, env) + assert code != 69 and AMENDMENT_22 not in err, \ + f"the tree carries the marker, the ref does not: {code}\n{out[-600:]}{err[-600:]}" + + +def test_an_unconfigured_workstations_acts_refuse_and_listings_read_the_mirror(tmp_path): + """AT-3 (Q21(a)(A)): on an unconfigured workstation under the marker, + `who` exits 69 with Amendment 22's text, and the listing, `lanes --all` + (which today exits 0 and lists the lane), reads on, exits 0 and prints the + `read: mirror` line at origin's tip. Fails until T504, whose `verify:` + runs it (tasks:713); T507, the guard's, does not bear on it (T225d).""" + home, wip, origin, env = _estate(tmp_path, str(uuid.uuid4())) + marker = _push_marker(tmp_path, origin, env) + _git(wip, env, "fetch", "-q", "origin", "main") + code, out, err = _who(wip, env) + assert code == 69 and AMENDMENT_22 in err, f"who: {code}\n{out[-600:]}{err[-600:]}" + code, out, err = _run([LANES, "--all"], env, wip) + assert code == 0, f"lanes --all: {code}\n{out[-600:]}{err[-600:]}" + assert f"{MIRROR_LINE}{marker[:12]}" in err, \ + f"lanes --all printed no `read: mirror at {marker[:12]}` line on stderr\n{err[-900:]}" + assert GUARD_WINDOW in out, f"lanes --all did not read on\n{out[-900:]}" + + +def test_the_marker_check_runs_at_the_end_of_log_sync(tmp_path): + """Lane 5's guess for T506 (A5), its name kept: the checkout has not + fetched since the cutover, so its ref has no marker; the act's own + `log_sync` fetch brings it, and F17 at `log_sync`'s end refuses 69 with + Amendment 22's text. Fails until T506.""" + home, wip, origin, env = _estate(tmp_path, str(uuid.uuid4())) + _push_marker(tmp_path, origin, env) + env = dict(env) + env.pop("LANES_NO_FETCH") + code, out, err = _who(wip, env) + assert _git(wip, env, "rev-parse", "origin/main") == _git(origin, env, "rev-parse", "main"), \ + "the act's log_sync did not fetch" + assert code == 69 and AMENDMENT_22 in err, \ + f"log_sync brought the marker: {code}\n{out[-600:]}{err[-600:]}" + + +def test_the_session_start_block_reads_on_under_the_marker_with_its_mirror_line(tmp_path): + """Lane 5's guess for T508 (A5), its name kept: off primary, under the + marker, the `SessionStart` block reads on, exits 0, and prints the + `read: mirror` line at origin's tip. Fails until T508.""" + sid = str(uuid.uuid4()) + home, wip, origin, env = _estate(tmp_path, sid) + marker = _push_marker(tmp_path, origin, env) + _git(wip, env, "fetch", "-q", "origin", "main") + hook = '{"session_id":"%s","source":"startup"}' % sid + code, out, err = _run([EDIT, "session-start"], env, wip, stdin=hook) + assert code == 0, f"session-start: {code}\n{out[-600:]}{err[-600:]}" + assert f"{MIRROR_LINE}{marker[:12]}" in out + err, \ + f"no `read: mirror at {marker[:12]}` line\n{out[-600:]}{err[-600:]}" + assert GUARD_WINDOW in out + err, f"the block did not read on\n{out[-900:]}" + + +def test_a_mode_index_guard_refuses_2_under_the_marker(tmp_path): + """Lane 5's guess for T507 (A7), its name kept: on a `mode=index` + workstation, the guard whose register row names its session refuses 2 + with Amendment 22's text once its read ref carries the marker (F17 in + `guard_run`; W:4896). Without the marker the same guard passes, 0. + Fails until T507.""" + sid = str(uuid.uuid4()) + home, wip, origin, env = _estate(tmp_path, sid, configuration="index") + env = dict(env, LANES_LANE=GUARD_WINDOW) + with guard_session(home, tmp_path / "bin", wip, session_id=sid) as session: + def guard(): + return subprocess.run(["bash", str(EDIT), "guard"], input=session.hook_input(), + capture_output=True, text=True, cwd=str(wip), + env=session.env(env), timeout=60, start_new_session=True) + proc = guard() + assert proc.returncode == 0, \ + f"the mode=index guard with no marker: {proc.returncode}\n" \ + f"{proc.stdout[-600:]}{proc.stderr[-600:]}" + _push_marker(tmp_path, origin, env) + _git(wip, env, "fetch", "-q", "origin", "main") + proc = guard() + assert proc.returncode == 2 and AMENDMENT_22 in proc.stderr, \ + f"the mode=index guard under the marker: {proc.returncode}\n" \ + f"{proc.stdout[-600:]}{proc.stderr[-600:]}" + + +# ============================================================ phase W: T242 +# +# TEST 3'S UNIT FORM AND AT-F8 (lane 2's T242; the test plan's AT-3 and AT-F8). +# +# THE WRITERS' MARKER CHECK (T419, L4-B12): a writer that is not `mode=primary` +# tests the tip its own S3 fetch brought for `lanes/STORE`, and under the +# marker exits 69 with Amendment 22's text, writing nothing; under +# `LANES_NO_FETCH=1` it tests the tip as last fetched. The marker is committed +# by hand on a bare origin (lane 4's row 8), and the writer's clone is one +# commit behind it, so the writer's own fetch brings it. +# +# THE MODE QUERY (T409, L4-B1; design Y, "The mode query's failures", F8's +# table): where a configuration exists the writer asks `lanes-index mode` once, +# on a 2 s client timer. Q6(c)'s 78 exits 69 with the build's refusal text, +# writing nothing; every other failure runs files mode with one warning, and +# the marker check then refuses it on a SQL estate. `LANES_INDEX=off` never +# skips the ask. The answers come from a stand-in at `lanes-index`'s path, +# `$SCRIPT_DIR/lanes-index`, the resolver's first choice (T409, "One +# resolver"), so the case runs a copy of `lanes-edit.sh` beside it, with +# `repos.tsv` and `lane-start`, the other files it reads from `$SCRIPT_DIR` +# (T409, "The tests' copy rule"; plan section 4.1). +# +# THE VERBS are S1's writes, the write guard's fourteen verbs at a2073eae +# (`lanes-edit.sh:16537`), `commit`'s publish act among them (T419: "That is +# the write guard's verbs, `commit`'s publish act included"). Each one's +# arguments reach its write today: with no marker each writes, pushes and +# exits 0. Under the marker, at a2073eae, eleven still write and exit 0, and +# `archive-rows`, `migrate-state-cells` and `retire-rows` refuse 2, since +# their own fetch leaves the checkout behind origin; from slice 1b on, each +# of the three runs `checkout_sync` first, which fast-forwards it, and T419's +# check sits there, after the fetch. `start-record` (T427, L4-B9) is not +# among them: it lands in no fixed order with T419, whose verify selects +# these ids. +# +# THE ESTATE is test 1's fixture register (T210's `SEED`, at C) on a bare +# origin, with the start state three verbs need (T241's `PREPS`), the +# workspace `workspace.yaml` names, and a `tmux` that answers nothing. +# +# They fail until L4-B1, L4-B12 and L5-A5 land, each by its own assertion: +# today's `lanes-edit.sh` asks no mode and checks no marker, so every write +# lands and exits 0. + +EM, ARROW = chr(0x2014), chr(0x2192) +WRITER_WS = "Eagle" +SID_A1 = "aaaaaaaa-0001-4000-8000-00000000a001" +SID_A2 = "aaaaaaaa-0003-4000-8000-00000000a003" +SID_Z1 = "eeeeeeee-0001-4000-8000-00000000e001" +#: The session `request-handoff --force` writes its `PAUSED` for (`--session`). +SID_REQUESTER = "bbbbbbbb-0007-4000-8000-00000000b007" +TIP = "0123456789abcdef0123456789abcdef01234567" + + +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} |") + + +#: Test 1's fixture register at C (T210's `SEED`): two lanes and an archived +#: one, `aliases.tsv`, a lane with `HOLD`, `LANDING` and `LANDED` lines, and +#: `repos.tsv` naming `repoA`. +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", + ""]), + "lanes/log/README.md": "# the object logs\n", + "lanes/repos.tsv": "# alias\towner/repo\nrepoA\topensoft/repoA\n", +} + +#: The one more row, and its log, three verbs need, or they refuse for want of +#: work (T241's `PREPS`; `lanes-edit.sh:13316-13352` at a2073eae): +#: `archive-rows ` moves a repository's RETIRED rows; `retire-rows` +#: takes a dormant row; `migrate-state-cells` migrates a diary cell. +PREP_ROWS = { + "archive-rows": ("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" + f"@Eagle, 2026-09-03T00:00:00Z, lane:repoZ-2 {EM} retired\n"), + "retire-rows": ("repoA-4", "aaaaaaaa-0005-4000-8000-00000000a005", + f"MIGRATED {DOT} 2026-09-01T00:00:00Z {DOT} migrated", ""), + "migrate-state-cells": ("repoA-5", "aaaaaaaa-0006-4000-8000-00000000a006", + f"parked 2026-09-01 {DOT} picked up 2026-09-02", ""), +} + +#: S1's writes, the write guard's verbs: {verb: (its arguments, the lane it +#: writes as)}. The forms are `lanes-edit.sh`'s usage lines at a2073eae, T241's +#: for the thirteen it shares; `commit` publishes a hand edit of `LANES.md` +#: (`HAND_EDIT`), the one thing it commits (`:16940-16970`). +WRITER_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 3 |"], "repoA-2"), + "append-line": (["append-line", f"HOLD {EM} lane repoA-2 ({WRITER_WS}), window w, " + f"2026-11-10T00:00:00Z: opensoft/repoB main {TIP} for test 3"], "repoA-2"), + "append-session-id": (["append-session-id", "repoA-2", f"harness `{SID_A2}`", + " (test 3)"], "repoA-2"), + "archive-rows": (["archive-rows", "repoZ", "--yes"], "repoA-2"), + "claim": (["claim", "opensoft/repoA#9", "--no-github"], "repoA-2"), + "commit": (["commit", "test 3's hand edit"], "repoA-2"), + "log": (["log", "NOTED", "lane:repoA-2", "test 3's write"], "repoA-2"), + "migrate-state-cells": (["migrate-state-cells", "--yes"], "repoA-2"), + "release": (["release", "opensoft/repoA#7", "test 3", "--no-github"], "repoA-1"), + "rename-lane": (["rename-lane", "repoA-2", "repoA-3", "test 3", "--no-github"], "repoA-2"), + "replace-in-row": (["replace-in-row", "repoA-2", "parked", "parked for test 3"], "repoA-2"), + "request-handoff": (["request-handoff", "repoA-1", "--force", "test 3", "--session", + SID_REQUESTER], "repoA-2"), + "retire-rows": (["retire-rows", "repoA-4", "--reason", "test 3"], "repoA-2"), + "set-row-state": (["set-row-state", "repoA-2", f"PAUSED {DOT} test 3"], "repoA-2"), +} + +#: `commit`'s hand edit: repoA-2's row in `LANES.md`, left uncommitted. +HAND_EDIT = ("lanes/LANES.md", f"{DOT} parked |", f"{DOT} parked by hand |") + + +def _seed(verbs=()) -> dict: + """`SEED`, with `PREP_ROWS`' row and log for each of `verbs` that has one, + each after repoA-2's row.""" + files = dict(SEED) + lanes = files["lanes/LANES.md"] + anchor = next(line for line in lanes.split("\n") if line.startswith("| `repoA-2` |")) + rows = [] + for verb in verbs: + if verb in PREP_ROWS: + lane, sid, cell, log = PREP_ROWS[verb] + rows.append(_row(lane, sid, cell, started="2026-09-01T00:00Z")) + files[f"lanes/log/{lane}.md"] = ( + f"# lane {lane} {EM} object log (lane-collision-protocol Amendment 7)\n" + log) + files["lanes/LANES.md"] = lanes.replace(anchor + "\n", "\n".join([anchor] + rows) + "\n", 1) + return files + + +def _sanitized_path() -> str: + """The caller's `PATH` without any directory that holds a `lanes-index` or + a `lane-start`: an installed lane tool is never what a case runs. The + case's own `tmux` comes first.""" + return os.pathsep.join( + part for part in os.environ.get("PATH", "/usr/bin:/bin").split(os.pathsep) + if part and not any(os.path.exists(os.path.join(part, name)) + for name in ("lanes-index", "lane-start"))) + + +def _writer_estate(root: Path, verbs=(), configuration: str = "none") -> tuple: + """A files-mode estate at C (`_seed(verbs)`) on a bare origin: the lane + checkout, `workspace.yaml` naming it, a `tmux` that answers nothing, and no + configuration or `mode=index` (`_configure`). Returns (the checkout, the + origin, the environment).""" + home, checkout, origin = root / "home", root / "checkout", root / "origin.git" + for name in ("home/.agents", "state", "config", "t", "fakebin"): + (root / name).mkdir(parents=True) + env = guard_strip_env(os.environ, strip=("GIT_", "OPENREPOTOOLS_")) + env.update(HOME=str(home), GIT_CONFIG_NOSYSTEM="1", GIT_CONFIG_GLOBAL=os.devnull, LC_ALL="C", + GIT_AUTHOR_NAME="t", GIT_AUTHOR_EMAIL="t@example.invalid", + GIT_COMMITTER_NAME="t", GIT_COMMITTER_EMAIL="t@example.invalid", + AGENT_PROTOCOL_ROOT=str(home / ".agents"), TMPDIR=str(root / "t"), + XDG_STATE_HOME=str(root / "state"), XDG_CONFIG_HOME=str(root / "config"), + CLAUDE_CONFIG_DIR=str(home / ".claude"), LANES_WORKSTATION=WRITER_WS, + LANES_HOST="eagle", LANES_OS="linux", LANES_CONTAINER="none", + LANES_IN_CONTAINER="0", LANES_NO_GITHUB="1", LANES_REPO=str(checkout), + PATH=str(root / "fakebin") + os.pathsep + _sanitized_path()) + (root / "fakebin" / "tmux").write_text("#!/bin/sh\nexit 1\n", encoding="utf-8") + (root / "fakebin" / "tmux").chmod(0o755) + subprocess.run(["git", "init", "-q", "--bare", "-b", "main", str(origin)], check=True, + env=env) + subprocess.run(["git", "clone", "-q", str(origin), str(checkout)], check=True, env=env, + capture_output=True) + for rel, text in _seed(verbs).items(): + (checkout / rel).parent.mkdir(parents=True, exist_ok=True) + (checkout / rel).write_bytes(text.encode("utf-8")) + for argv in (["add", "-A"], ["commit", "-q", "-m", "C: the fixture register"], + ["push", "-q", "origin", "main"]): + _git(checkout, env, *argv) + (home / ".agents" / "workspace.yaml").write_text( + f"repository: {origin}\npath: {checkout}\n", encoding="utf-8") + _configure(root, env, configuration) + return checkout, origin, env + + +def _hand_edit(checkout: Path, verb: str) -> None: + """`commit`'s hand edit, left in the working tree; nothing for any other + verb.""" + if verb == "commit": + rel, old, new = HAND_EDIT + text = (checkout / rel).read_text(encoding="utf-8") + assert text.count(old) == 1, f"the hand edit's anchor is not once in {rel}" + (checkout / rel).write_text(text.replace(old, new), encoding="utf-8") + + +def _write(edit: Path, argv: list, lane: str, env: dict, cwd: Path, + **extra) -> subprocess.CompletedProcess: + """One run of ` ` as `lane`.""" + return subprocess.run(["bash", str(edit), *argv], capture_output=True, encoding="utf-8", + errors="replace", env=dict(env, LANES_LANE=lane, **extra), + cwd=str(cwd), timeout=120, check=False, stdin=subprocess.DEVNULL, + start_new_session=True) + + +def _git_state(checkout: Path, origin: Path, env: dict) -> dict: + """AT-3's oracle of what a refusal leaves unchanged: the clone's HEAD, + index, working tree and files under `lanes/`, and origin's refs.""" + index = checkout / ".git" / "index" + lanes = checkout / "lanes" + return { + "HEAD": _git(checkout, env, "rev-parse", "HEAD"), + "index": hashlib.sha256(index.read_bytes()).hexdigest() if index.exists() else "-", + "status": _git(checkout, env, "status", "--porcelain=v1", "-uall"), + "lanes/": {p.relative_to(lanes).as_posix(): hashlib.sha256(p.read_bytes()).hexdigest() + for p in sorted(lanes.rglob("*")) if p.is_file()}, + "origin": _git(origin, env, "for-each-ref", "--format=%(refname) %(objectname)"), + } + + +def _queued(checkout: Path, env: dict) -> str: + """The local commits the publish act would push: those `origin/main`, as + last fetched, lacks.""" + return _git(checkout, env, "log", "--oneline", "refs/remotes/origin/main..HEAD") + + +def _said(proc: subprocess.CompletedProcess) -> str: + return f"\n--- stdout\n{proc.stdout[-700:]}\n--- stderr\n{proc.stderr[-1500:]}" + + +def _assert_wrote_nothing(before: dict, checkout: Path, origin: Path, env: dict, + where: str) -> None: + after = _git_state(checkout, origin, env) + changed = sorted(k for k in before if before[k] != after[k]) + assert not changed, f"{where}: the refusal changed {changed}: {before} -> {after}" + queued = _queued(checkout, env) + assert not queued, f"{where}: a commit is queued for the publish act: {queued}" + + +def _assert_refused_under_the_marker(root: Path, verb: str, configuration: str) -> None: + """AT-3's oracle for one verb in one configuration: origin's `main` carries + the marker, the clone is one commit behind, and the verb's own fetch + brings it; the writer exits 69 with Amendment 22's text and writes + nothing.""" + checkout, origin, env = _writer_estate(root, [verb], configuration) + _push_marker(root, origin, env) + _hand_edit(checkout, verb) + argv, lane = WRITER_VERBS[verb] + before = _git_state(checkout, origin, env) + proc = _write(EDIT, argv, lane, env, checkout) + where = f"lanes-edit.sh {verb}, configuration {configuration}, under the marker" + assert proc.returncode == 69, \ + f"{where}: exited {proc.returncode}, not 69 (T419's marker check){_said(proc)}" + assert AMENDMENT_22 in proc.stderr, f"{where}: no Amendment 22 text on stderr{_said(proc)}" + _assert_wrote_nothing(before, checkout, origin, env, where) + + +@pytest.mark.parametrize("verb", list(WRITER_VERBS)) +def test_a_files_mode_writer_refuses_under_the_marker(tmp_path, verb): + """AT-3 (FR-004): with no configuration, each of S1's verbs whose own + fetch brings `lanes/STORE` exits 69 with Amendment 22's text; the clone's + HEAD, index, working tree and `lanes/`, and origin's refs, are unchanged, + and no commit is queued for the publish act. Fails until T419 (L4-B12).""" + _assert_refused_under_the_marker(tmp_path, verb, "none") + + +@pytest.mark.parametrize("verb", list(WRITER_VERBS)) +def test_a_mode_index_writer_refuses_under_the_marker(tmp_path, verb): + """AT-3 (Q20(B)): the same on a `mode=index` workstation, every + workstation act 3 configured, which T409's ask answers `index`. Fails + until T409 (L4-B1) and T419 (L4-B12).""" + _assert_refused_under_the_marker(tmp_path, verb, "index") + + +def test_a_writer_with_no_fetch_refuses_when_its_tip_carries_the_marker(tmp_path): + """AT-3: a second clone, made at the marker's commit, run with + `LANES_NO_FETCH=1`: `log NOTED` still exits 69 with Amendment 22's text and + writes nothing, with no configuration and with `mode=index` (T419: under + `LANES_NO_FETCH=1` the check tests the tip as last fetched). Fails until + T419 (L4-B12).""" + argv, lane = WRITER_VERBS["log"] + for configuration in CONFIGURATIONS: + root = tmp_path / configuration + first, origin, env = _writer_estate(root, configuration=configuration) + marker = _push_marker(root, origin, env) + second = root / "second" + subprocess.run(["git", "clone", "-q", str(origin), str(second)], check=True, env=env, + capture_output=True) + assert _git(second, env, "rev-parse", "HEAD") == marker + assert (second / "lanes" / "STORE").is_file() + (root / "home" / ".agents" / "workspace.yaml").write_text( + f"repository: {origin}\npath: {second}\n", encoding="utf-8") + env = dict(env, LANES_REPO=str(second), LANES_NO_FETCH="1") + before = _git_state(second, origin, env) + proc = _write(EDIT, argv, lane, env, second) + where = f"log NOTED with LANES_NO_FETCH=1, configuration {configuration}" + assert proc.returncode == 69, \ + f"{where}: exited {proc.returncode} with the marker in its tip{_said(proc)}" + assert AMENDMENT_22 in proc.stderr, f"{where}: no Amendment 22 text{_said(proc)}" + _assert_wrote_nothing(before, second, origin, env, where) + + +# --- AT-F8: every failure of the mode query ---------------------------------- + +#: Q6(c)'s text, as lane 1's T105 spells it (`MODE_PRIMARY_REFUSED_TEXT`; +#: design Y:4872), which the stand-in's 78 carries. +Q6C_TEXT = ("mode=primary is not available in this build: the renderer's git half is not " + "installed, so a write could not be mirrored; nothing was written") +#: The query's client timer, D9's row for the mode query, and the bound a test +#: asserts, twice it (section 4's rule 2). +MODE_TIMER_S = 2.0 +MODE_BOUND_S = 2 * MODE_TIMER_S +MODES = ("index", "primary") +ESTATES = ("files", "sql") + +#: The stand-in's answers to `mode`: each row of lane 4's table ("The mode +#: query's failures") but 78, which `Q6C` answers. `exit` is the code, `signal` +#: a death by that signal, `sleep` a hang past the client timer, `stdout` and +#: `stderr` what it prints first. +MODE_FAILURES = { + "refused-2": {"exit": 2, "stderr": "lanes-index: lanes-index.conf: line 1: the " + "configuration is refused\n"}, + "too-old-64": {"exit": 64, "stderr": "lanes-index: unknown subcommand 'mode'\n"}, + "crash-1": {"exit": 1, "stderr": "Traceback (most recent call last):\n RuntimeError\n"}, + "removed-127": {"exit": 127, "stderr": "lanes-index: python3: No such file or directory\n"}, + "signal": {"signal": "TERM"}, + "not-one-line": {"exit": 0, "stdout": "index\nprimary\n"}, + "exit-69": {"exit": 69, "stderr": "lanes-index: unavailable\n"}, + "exit-75": {"exit": 75, "stderr": "lanes-index: busy\n"}, + "exit-3": {"exit": 3, "stderr": "lanes-index: in doubt\n"}, + "hang": {"sleep": 60, "stdout": "index\n"}, +} +Q6C = {"exit": 78, "stderr": f"lanes-index: {Q6C_TEXT}\n"} + +#: THE STAND-IN at `lanes-index`'s path: it logs every call (its argv, its pid, +#: its start, and `LANES_INDEX` as it found it), answers `mode` as +#: `lanes-index.answer` beside it says, and every other call with 0. Where it +#: hangs, a SIGTERM is logged with its time before it ends. +_MODE_STANDIN = r'''#!/usr/bin/env python3 +# A STAND-IN lanes-index (feature 007, T242; AT-F8): it logs every call, one +# JSON object per line, and answers `mode` as lanes-index.answer says. +import json, os, signal, sys, time +HERE = os.path.dirname(os.path.abspath(__file__)) +LOG = os.path.join(HERE, "lanes-index.calls") +ARGS = sys.argv[1:] + + +def log(record): + with open(LOG, "a", encoding="utf-8") as handle: + handle.write(json.dumps(record) + "\n") + + +log({"argv": ARGS, "pid": os.getpid(), "start": time.time(), + "lanes_index": os.environ.get("LANES_INDEX")}) +if ARGS != ["mode"]: + sys.exit(0) +with open(os.path.join(HERE, "lanes-index.answer"), encoding="utf-8") as handle: + ANSWER = json.load(handle) +if ANSWER.get("sleep"): + def ended(signum, frame): + log({"argv": ARGS, "pid": os.getpid(), "ended": time.time(), "signal": signum}) + os._exit(128 + signum) + signal.signal(signal.SIGTERM, ended) + time.sleep(ANSWER["sleep"]) +sys.stdout.write(ANSWER.get("stdout", "")) +sys.stderr.write(ANSWER.get("stderr", "")) +sys.stdout.flush() +sys.stderr.flush() +if ANSWER.get("signal"): + os.kill(os.getpid(), getattr(signal, "SIG" + ANSWER["signal"])) +sys.exit(ANSWER.get("exit", 0)) +''' + +#: One warning that the mode query failed and the write runs in files mode +#: (D3). No contract fixes its words, so this counts only a warning line of +#: `lanes-edit.sh`'s that names the query: one that starts +#: `lanes-edit: WARNING:` and names `lanes-index mode`. A line naming the +#: mode and files mode alone also matched T419's refusal note on a SQL +#: estate, "This workstation writes in files mode, so `log` refuses" +#: (`lanes-edit.sh:2771` at `refs/l1/V-round5`), and counted 2 for AT-F8's +#: `[*-sql]` ids (AN13b's cause 1; line AF13b). +MODE_WARNING = re.compile(r"^lanes-edit: WARNING: .*\blanes-index mode\b") +TIMEOUT_WORDS = re.compile(r"tim(e|ed)[ -]?out|timer|\b2 ?s\b|seconds?\b", re.I) + + +class _ModeBench: + """AT-F8's fixture: `_writer_estate`'s files-mode estate with a + `mode=` configuration, `lanes/STORE` on origin for the `sql` estate + (the clone one commit behind it), and a copy of `lanes-edit.sh` with + `repos.tsv`, `lane-start` and the stand-in beside it.""" + + def __init__(self, root: Path, mode: str, estate: str, answer: dict, verbs=()): + self.checkout, self.origin, self.env = _writer_estate(root, verbs) + conf = Path(self.env["XDG_CONFIG_HOME"]) / "openRepoTools" / "lanes-index.conf" + conf.parent.mkdir(parents=True, exist_ok=True) + conf.write_text(f"mode={mode}\n", encoding="utf-8") + conf.chmod(0o600) + self.bin = root / "bin" + self.bin.mkdir() + for name in ("lanes-edit.sh", "repos.tsv", "lane-start"): + shutil.copy2(REPO / name, self.bin / name) + self.edit = self.bin / "lanes-edit.sh" + (self.bin / "lanes-index").write_text(_MODE_STANDIN, encoding="utf-8") + (self.bin / "lanes-index").chmod(0o755) + (self.bin / "lanes-index.answer").write_text(json.dumps(answer), encoding="utf-8") + self.log = self.bin / "lanes-index.calls" + if estate == "sql": + _push_marker(root, self.origin, self.env) + + def calls(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 write(self, verb: str, index_off: bool, text: str = None) -> tuple: + """Runs `verb`, with `LANES_INDEX=off` where `index_off`. Returns (the + run, its `mode` calls, its wall time).""" + argv, lane = WRITER_VERBS[verb] + if text is not None: + argv = argv[:-1] + [text] + seen = len(self.calls()) + extra = {"LANES_INDEX": "off"} if index_off else {} + started = time.monotonic() + proc = _write(self.edit, argv, lane, self.env, self.checkout, **extra) + wall = time.monotonic() - started + asked = [c for c in self.calls()[seen:] if c["argv"] == ["mode"] and "start" in c] + return proc, asked, wall + + def state(self) -> dict: + return _git_state(self.checkout, self.origin, self.env) + + +def _where(verb: str, mode: str, estate: str, index_off: bool) -> str: + return (f"lanes-edit.sh {verb} on mode={mode}, {estate} estate, " + f"LANES_INDEX {'off' if index_off else 'unset'}") + + +def _assert_asked_once(asked: list, where: str, proc: subprocess.CompletedProcess) -> None: + """T409: the writer asks `lanes-index mode` once, where a configuration + exists, and `LANES_INDEX=off` never skips the ask (lane 4's row 25).""" + assert len(asked) == 1, \ + f"{where}: the stand-in was asked `mode` {len(asked)} times, not once (T409's ask)" \ + f"{_said(proc)}" + + +def test_the_q6c_refusal_has_its_own_code_and_the_writer_exits_69(tmp_path): + """AT-F8: the stand-in answers `mode` with Q6(c)'s 78 and its text. On + `mode=index` and `mode=primary`, on a files estate and a SQL estate, with + `LANES_INDEX` unset and `off`, `log NOTED` asks once, exits 69, its stderr + repeats the text, and nothing is written. Then AT-14's refusing line for + the writer (T14C's SHOULD-2: this case holds it): each of S1's verbs, on + `mode=primary` and a files estate, exits 69 repeating the text, with the + files, HEAD and origin unchanged. Fails until T409 (L4-B1).""" + for estate in ESTATES: + for mode in MODES: + bench = _ModeBench(tmp_path / f"{mode}-{estate}", mode, estate, Q6C) + for index_off in (False, True): + where = _where("log NOTED", mode, estate, index_off) + before = bench.state() + proc, asked, _wall = bench.write("log", index_off) + _assert_asked_once(asked, where, proc) + assert proc.returncode == 69, \ + f"{where}: Q6(c)'s 78 gave {proc.returncode}, not 69{_said(proc)}" + assert Q6C_TEXT in proc.stderr, f"{where}: stderr lacks Q6(c)'s text{_said(proc)}" + _assert_wrote_nothing(before, bench.checkout, bench.origin, bench.env, where) + verbs = [v for v in WRITER_VERBS if v != "commit"] + ["commit"] + bench = _ModeBench(tmp_path / "verbs", "primary", "files", Q6C, verbs) + for verb in verbs: + _hand_edit(bench.checkout, verb) + where = _where(verb, "primary", "files", False) + before = bench.state() + proc, asked, _wall = bench.write(verb, False) + _assert_asked_once(asked, where, proc) + assert proc.returncode == 69, \ + f"{where}: Q6(c)'s 78 gave {proc.returncode}, not 69{_said(proc)}" + assert Q6C_TEXT in proc.stderr, f"{where}: stderr lacks Q6(c)'s text{_said(proc)}" + _assert_wrote_nothing(before, bench.checkout, bench.origin, bench.env, where) + + +def _process_alive(pid: int, program: Path) -> bool: + """Whether `pid` is still the stand-in: a pid reused by another program, + or a reaped one, is not.""" + try: + cmdline = Path(f"/proc/{pid}/cmdline").read_bytes() + except OSError: + return False + return str(program).encode() in cmdline + + +def _record(where: str, elapsed: float) -> None: + """Timing rule 2's record: the query's measured end beside D9's 2 s timer, + and its margin to the bound.""" + print(f"AT-F8 {where}: the mode query ended {elapsed:.2f} s after it started, against " + f"D9's {MODE_TIMER_S:g} s timer (bound {MODE_BOUND_S:g} s); " + f"margin {MODE_BOUND_S - elapsed:+.2f} s") + + +@pytest.mark.parametrize(("failure", "mode", "estate"), [ + pytest.param(failure, mode, estate, id=f"{failure}-{mode}-{estate}") + for failure in MODE_FAILURES for mode in MODES for estate in ESTATES]) +def test_any_other_mode_query_failure_runs_files_mode_with_a_warning(tmp_path, failure, mode, + estate): + """AT-F8: each failure of the mode query but 78 (lane 4's table), on + `mode=` and a `` estate, with `LANES_INDEX` unset and then + `off`: `log NOTED` asks once and prints one warning on stderr, then runs in + files mode. On a files estate the write exits 0 and lands on origin; on a + SQL estate the marker check after S3's fetch refuses it, 69 with Amendment + 22's text, and nothing is written. The hang: the query's 2 s client timer + ends the stand-in, which is gone once the verb returns; the query ends + under 4 s, recorded with its margin, and the warning names the timeout. + Fails until T409 (L4-B1), and on a SQL estate T419 (L4-B12).""" + bench = _ModeBench(tmp_path, mode, estate, MODE_FAILURES[failure]) + for index_off in (False, True): + where = _where("log NOTED", mode, estate, index_off) + f", the query's {failure}" + text = f"test 3's AT-F8 write, {failure}, LANES_INDEX {'off' if index_off else 'unset'}" + before = bench.state() + proc, asked, wall = bench.write("log", index_off, text) + _assert_asked_once(asked, where, proc) + warnings = [line for line in proc.stderr.splitlines() if MODE_WARNING.search(line)] + assert len(warnings) == 1, \ + f"{where}: {len(warnings)} warnings that the write runs in files mode, not one" \ + f"{_said(proc)}" + if failure == "hang": + call = asked[0] + ended = [c["ended"] for c in bench.calls() + if c.get("pid") == call["pid"] and "ended" in c] + elapsed = (ended[0] if ended else call["start"] + wall) - call["start"] + _record(where, elapsed) + assert not _process_alive(call["pid"], bench.bin / "lanes-index"), \ + f"{where}: the hanging stand-in (pid {call['pid']}) outlived the verb" + assert elapsed < MODE_BOUND_S, \ + f"{where}: the query ended {elapsed:.2f} s after it started, not under " \ + f"{MODE_BOUND_S:g} s" + assert TIMEOUT_WORDS.search(warnings[0]), \ + f"{where}: the warning does not name the timeout: {warnings[0]!r}" + if estate == "files": + assert proc.returncode == 0, \ + f"{where}: the files-mode write exited {proc.returncode}, not 0{_said(proc)}" + landed = _git(bench.origin, bench.env, "show", "main:lanes/log/repoA-2.md") + assert text in landed, f"{where}: the write did not land on origin{_said(proc)}" + else: + assert proc.returncode == 69, \ + f"{where}: exited {proc.returncode}, not 69 (the marker check after the " \ + f"files-mode fallback){_said(proc)}" + assert AMENDMENT_22 in proc.stderr, \ + f"{where}: no Amendment 22 text on stderr{_said(proc)}" + _assert_wrote_nothing(before, bench.checkout, bench.origin, bench.env, where) From bcc8858bf587fbe86b00264b41caca1b39ccfc72 Mon Sep 17 00:00:00 2001 From: Brett Heap <1513478+brettheap@users.noreply.github.com> Date: Sun, 15 Nov 2026 15:14:03 +0000 Subject: [PATCH 2/2] P06 follow-up 1: T212g, lane 2's empty gate row for D3's test, on lane 3's SHOULD that it skips until P16 but should guard P11 This commit is added to P06's branch on its head b65d836b4ea939a43f89cf4e582055bb9e80f890 (code PR 94), with no force-push: the branch keeps its cut's one commit, and a later commit carries its own explicit message (landing note 23). Lane 3's SHOULD. Lane 3's review of P06 at b65d836b found that the build_flip module's table, T212f's, keys D3's test, test_lanes_edit_asks_lanes_index_mode_only_where_a_configuration_exists, to T104, T105, T113 and T504 to T506 (T212's Order, tasks:1974), though T212's own text (tasks:1970) and the module's docstring say it passes at once and "holds D3 through group B". So in gated CI it skips until P16, where T504 to T506 land, while P11 lands T409, the change D3 guards, before it: run 6 against run 9 (opensoft/openRepoTools#165 comment 6894592205). Lane 3 ruled that D3 be given an empty row now: lane 2 builds the one-line table change on T212's line, lane 1 adds it to PR 94 as a commit of its own (landing note 23), follow-ups 4 aligns T212's Order, and lane 3 reviews the new head. Lane 2 built it as T212g, on T282b 209720ea, tag l2-007-T212g, and posted it (opensoft/openRepoTools#165 comment 6895859508). Lane 4 checked that the empty row does not fail P11: on its preview of P11's cut, with T409 and a one-line stand-in for this row, D3's test passed (run 43721199211), and it passed in the control without T409 (run 43721200179), in opensoft/openRepoTools#165 comment 6895364188. What T212g changes, in lane 2's words. It changes one line of tests/test_sql_register_build_flip.py, at P06's head blob 952a3581 to 940de94e: D3's row becomes (), and its key and its comment, "# T212; tasks:1974", are kept. An empty row waits for no task (the gate's waits_for gives ()), so D3's test runs in every gated run, from P06's own CI on, and guards T409 in P11. No id, no other row, no docstring and no comment changes: the docstring already says D3's test passes at once, and nothing in the module names D3's old keys. The table keeps its 8 keys (6 function rows and 2 id rows), and the module still holds 6 test functions and collects 24 ids. Lane 2's runs, through tests/run.sh, the whole module, gated (SQL_REGISTER_GATE=on, P06's eleven markers, a real PostgreSQL 16): - at b65d836b: 24 skipped, D3 among them, "waits for T104, T105, T113, T504, T505, T506"; - with T212g picked on: 1 passed, D3, and 23 skipped, and no other id moves; - an ast check, at T282b and at b65d836b: the test functions, their decorators and arguments, and every other top-level node are the same; the table keeps its keys in order, and only D3's row differs, from T212's six tasks to (); the collected ids are the same before and after, 24 at P06. How it was made here. cherry-pick -x of 59279958 onto b65d836b applied with no conflict, at :202 (offset -29), giving tree c237317c, with T212g's own patch-id, 7ca1ab06760023072c32dc67a6ca87dfc9591f1b. Lane 1's gated run of the whole module through tests/run.sh agrees with lane 2's: 24 skipped at b65d836b, and at this commit 1 passed, D3, and 23 skipped, the same 24 ids in both, with no other id's outcome or skip reason moved. The path is in T212's files: (T212 is S007-09's, this pull request's set) at spec main f8c1d3dac0102bb148ca495a2b8008a4cd8f7718 (tasks.md blob f56ad0a7, line 1962); it is in T256's too. T212g has no task line of its own, so it adds no marker: tests/sql_register_landed/T212 is already in P06. T212's Order (tasks:1974) is aligned by follow-ups 4: as lane 2 says, line 1974 gains "except D3's". (cherry picked from commit 59279958569b7bc69f3376560f97782e84fb59b0) Lane: openRepoTools-1 Co-Authored-By: Claude Opus 5.5 --- tests/test_sql_register_build_flip.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_sql_register_build_flip.py b/tests/test_sql_register_build_flip.py index 952a3581..940de94e 100644 --- a/tests/test_sql_register_build_flip.py +++ b/tests/test_sql_register_build_flip.py @@ -199,7 +199,7 @@ SQL_REGISTER_GATE_TABLE = { "test_a_primary_write_forks_render_checkout_on_the_lane_checkout_detached": ("T409", "T415", "T416"), # T256; tasks:2436 - "test_lanes_edit_asks_lanes_index_mode_only_where_a_configuration_exists": ("T104", "T105", "T113", "T504", "T505", "T506"), # T212; tasks:1974 + "test_lanes_edit_asks_lanes_index_mode_only_where_a_configuration_exists": (), # T212; tasks:1974 "test_mode_primary_is_refused_until_the_git_half_and_goes_to_sql_once_flipped": ("T104", "T105", "T113", "T504", "T505", "T506"), # T212; tasks:1974 "test_mode_primary_with_sqlite_is_refused": ("T104", "T105", "T113", "T504", "T505", "T506"), # T212; tasks:1974 "test_readers_under_the_refusal_answer_the_78_as_a_failed_read": ("T104", "T105", "T113", "T504", "T505", "T506"), # T212; tasks:1974