From a84d3716c9921f69b290943b64350632bc9e0328 Mon Sep 17 00:00:00 2001 From: Brett Heap <1513478+brettheap@users.noreply.github.com> Date: Sun, 15 Nov 2026 01:54:57 +0000 Subject: [PATCH] 007 S007-01+04: The real-engine fixture and plugin, the test helpers, the stub `lanes-index` and the landing gate, and CI requiring the real engine (7 tasks; part of opensoft/openRepoTools#165) Pull request P01 of feature 007's task sets, version 12f: lane 2's sets S007-01 and S007-04 in one commit, a control PR outside the code queue (rule 9). It is cut from lane 1's line R at merge153 68b581cdb14c2cd8d79e6c5508243bd1b1586a34 onto its base, code main c9c65cc14695732c9badf9f1f7cac795f661d524, which line R takes as merge154. Its 25 task commits, all built by lane 2, were picked with cherry-pick -x in line R's order across the two sets; each part below lists its own, in that order. No plain commit of landing note 15 falls in these sets, no line R commit holds their code by hunk, and the PR holds no module that needs a gate table (rule 11). Lane 2's merges on its E and FX lines are not picked: T201b 59384bc2737b6e1c4f194a42a47f53d217f351ce, T206b 34454cc8b18100a7560360d185e643c79d32e5cb, line H's two merges, 963d32496e941d7d6764033c5a49a3174604b0a7 and ca6633ddb283d10d1664fa28e3c765aac0e9b2bd, and FX's merge of T205d, ea7bd45615b8adb5d0b797ba723151d23c680b5d. FX's commits of T227 and T228, T228b among them (S007-05), and of T229 (S007-13) are not in this commit. The full shas are pointers into lane 1's share. 007 S007-01: The real-engine fixture and switch's plugin, the test helpers, the contract's stub `lanes-index`, and the landing gate (T200, T205, T203, T207, T280; part of opensoft/openRepoTools#165) - T200, lane 2's, whole: 0bdb856ac5fdb90b1325771c5d126a90724d47b0, line R's merge107 4cb8eea038922fbea11faa08c40e1c2129e355dd. - T205, lane 2's, whole: e85085938c08ddd74f59601c17d4fac0a88283d6, line R's merge107. - T280, lane 2's, whole, in line R's merge107: T280 f97d07b3de31acbf93ed543fe4144ec613768de9, T280b ee22c3fb5ee19bd1de21a70f34d68faaf5f03c07, T280c 6309773297a1800ff81c30255511891e5c79dcb2, T280d 854defd1fd6475569d1766f96192bcaaf0f94b81, T280e d166a901e713899ed211118f3d83d3fce12362d0, T280f 321d7d1d0c88c470cd1aca2c4566ef9cc2226064 (TASK_IDS re-keyed to tasks.md's 158 task lines at spec commit 17) and T280g d58f3b82032b864c35071d68bf94f43b0ae38b9d. - T203 and T207, lane 2's, whole, in line R's merge108 9a2fdfeaf95b72945f5ff488bc0212f95b416230: T203 0dc0b416ae6abf8b9bce54444e078386cb16e137, T207 69926464097c7518246b33d1f05a3c3e8c3a288c and 43b48d9469b95564886d698b1ae07eb6eb9b0cee, T207c cda4dbb467e45f9443adad9bd5280a07adebd554, T203b e8366b36404c669448ae0a831fc116807f6976c8 and T203c 1e073fcfdaf55b191063664f93dae644c2f38bcb. - T205b, lane 2's, whole: a66f5e3688ca8e0e0808c857e6805e8e2ce61d66, line R's merge108. - T203d, lane 2's, whole: c4ca0ab16b059122bc0723abfebb8d1e5dbe3034, line R's merge111 813795b84facb27eb95f0d88a218618655fcd700. - T280h and T280i, lane 2's, whole: T280h 2289d88c3ce787dd1584229b26c29f2bca7cfd94 and T280i d974da25a88d6836d96fe79c385f349b91977691, line R's merge138 3954d9c5483aaec3f97a0459121792fc8b9017e5. - T205c, lane 2's, whole: 932605364e57954e1c4239797ec0c0d52e277867, line R's merge139 618b8accc6bb9c08b2cf0feef8b38ca651be457b. Its test hunk is in T200's tests/test_sql_register_fixture.py, in this set. Its pick conflicts in one hunk, at the end of that module: T205c appends its 62 lines after T229's cases, which this commit does not hold. The hunk is resolved as this commit's text plus T205c's own 62 lines, which line R's blob holds in one run. - T205d, lane 2's, whole: 467959eecc6b57325b0f6fa19cd6accd986e0f7d, line R's merge146 941ffaeef205bafe96d9cf087c957c09e19d0af3. It adds the fixture module's `import pytest`, which T205c's cases need, so the module collects without T229b (lane 3's ruling 1, opensoft/openRepoTools#165 6885378657). The module then equals line R's blob less T229b's, T229c's and T229e's lines, but for the two T229b also adds, `import pytest` and its blank line. - Markers: tests/sql_register_landed/T200, T205, T203, T207 and T280. 007 S007-04: CI requires the real engine: `OPENREPOTOOLS_REQUIRE_PG: '1'` in tests.yml's workflow `env:`, with its test (T201, T206; part of opensoft/openRepoTools#165) - T201, lane 2's, whole: 627bc80da8bd3b1032f0013dba2f48f8ad97d782, line R's merge107. Its pick conflicts in one hunk, at the end of tests/test_tests_workflow.py: code main's WHEEL_TWICE loop, 6 lines, against T201's 54. It is resolved as a union, main's lines first and T201's after, as lane 2's T201b and T206b resolved it; the module then equals line R's blob 6384c6cad99443b5a6b09e29d8c23d9894152a54. - T206, lane 2's, whole: d07732ba7e6b77378bc05d79f5e2f3958537bb6f, line R's merge107. - T206c, lane 2's, whole: f060619ceb3ff5bb69fec1130fa9c44c47869275, line R's merge108. - T201c, lane 2's, whole: 7bcb419e73316652e9c13f85ed4dd5f2442ad18a, line R's merge147 a7945c9046435d5fad88439505f9aebdcb4a1dc4. T201's oracle reads the `ci_shards.py run` and `verify` steps as suite steps, and a new case gives each of the four shard and aggregate jobs a job-level OPENREPOTOOLS_REQUIRE_PG of '0' and requires the oracle to fail it (Codex's SHOULD 4, opensoft/openRepoTools#165 6882190927; lane 2, opensoft/openRepoTools#165 6885734771). tests/test_tests_workflow.py then equals line R's blob 27bdb58a3f979319e03687a41c83f135a5a504c1. - Coverage review of the baseline edit (batching-pilot.md:17-18): .github/ci/full-ci-baseline.json's `environment` gains "OPENREPOTOOLS_REQUIRE_PG": "1", the value tests.yml's workflow `env:` now sets, and `amendments` gains one environment-only entry in the form of the one before it. `job_sha256` and `expanded_jobs` are unchanged: no job, event or test selection changes, and a run without PostgreSQL 16 fails where it would have skipped its real-engine tests. - Markers: tests/sql_register_landed/T201 and T206. Lane: openRepoTools-1 Co-Authored-By: Claude Opus 5.5 --- .github/ci/full-ci-baseline.json | 8 +- .github/workflows/tests.yml | 1 + tests/conftest.py | 106 +- tests/pgcluster.py | 660 +++++++++ tests/sql_register_gate.py | 271 ++++ tests/sql_register_helpers.py | 2030 ++++++++++++++++++++++++++++ tests/sql_register_landed/T200 | 0 tests/sql_register_landed/T201 | 0 tests/sql_register_landed/T203 | 0 tests/sql_register_landed/T205 | 0 tests/sql_register_landed/T206 | 0 tests/sql_register_landed/T207 | 0 tests/sql_register_landed/T280 | 0 tests/test_repo_hygiene.py | 49 + tests/test_sql_register_fixture.py | 316 +++++ tests/test_sql_register_gate.py | 516 +++++++ tests/test_sql_register_helpers.py | 174 +++ tests/test_tests_workflow.py | 95 ++ 18 files changed, 4223 insertions(+), 3 deletions(-) create mode 100644 tests/pgcluster.py create mode 100644 tests/sql_register_gate.py create mode 100644 tests/sql_register_helpers.py create mode 100644 tests/sql_register_landed/T200 create mode 100644 tests/sql_register_landed/T201 create mode 100644 tests/sql_register_landed/T203 create mode 100644 tests/sql_register_landed/T205 create mode 100644 tests/sql_register_landed/T206 create mode 100644 tests/sql_register_landed/T207 create mode 100644 tests/sql_register_landed/T280 create mode 100644 tests/test_sql_register_fixture.py create mode 100644 tests/test_sql_register_gate.py create mode 100644 tests/test_sql_register_helpers.py diff --git a/.github/ci/full-ci-baseline.json b/.github/ci/full-ci-baseline.json index 7b044287..1fd9698a 100644 --- a/.github/ci/full-ci-baseline.json +++ b/.github/ci/full-ci-baseline.json @@ -24,7 +24,8 @@ }, "environment": { "OPENREPOTOOLS_CODE_ROOT": "${{ github.workspace }}", - "OPENREPOTOOLS_COMPOSED": "0" + "OPENREPOTOOLS_COMPOSED": "0", + "OPENREPOTOOLS_REQUIRE_PG": "1" }, "job_sha256": { "guard-launch-mode": "8373bf9a986071903e92b950aa64103a135d994a21365af98d18014d452316bb", @@ -43,6 +44,11 @@ "tests-shard", "tests-no-submodule-shard" ] + }, + { + "reason": "007-sql-register T206: environment only, workflow-level OPENREPOTOOLS_REQUIRE_PG '1', so a run without PostgreSQL 16 fails instead of skipping its real-engine tests; no job/event/test-selection change", + "source_commit": "a15a6b54f4b8b6ebb9e7ced8aa9d2b8cdd4e078d", + "jobs": [] } ] } diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 9ec17dc5..e46aca51 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -88,6 +88,7 @@ on: env: OPENREPOTOOLS_CODE_ROOT: ${{ github.workspace }} OPENREPOTOOLS_COMPOSED: '0' + OPENREPOTOOLS_REQUIRE_PG: '1' jobs: delivery-route: diff --git a/tests/conftest.py b/tests/conftest.py index 83411240..5c4e3d18 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -35,19 +35,31 @@ assembly pins — REFUSES the session before a test runs, and a test that reaches an absent root FAILS. Nothing skips its way into composed acceptance (FR-008). + +THE REAL ENGINE (opensoft/openRepoTools#165, L2-0a and L2-0b). The tests +that need a real PostgreSQL 16 take it from `tests/pgcluster.py`, a plugin +`pytest_configure` registers below. Where no engine is found they SKIP, +loudly, naming `PG_BIN` and the package; under `OPENREPOTOOLS_REQUIRE_PG=1`, +as CI sets it, the run is REFUSED before a test runs, as a composed run +missing a root is. """ from __future__ import annotations +import atexit import os import shutil import stat import subprocess +import tempfile from pathlib import Path -from typing import Dict, List, Mapping, Optional, Tuple +from typing import Dict, List, Mapping, Optional, Set, Tuple import pytest +import pgcluster +import sql_register_gate + #: THE TREE THIS SUITE WAS LOADED FROM, which is the code root unless #: `OPENREPOTOOLS_CODE_ROOT` names another one. SUITE_ROOT = Path(__file__).resolve().parents[1] @@ -511,10 +523,17 @@ def pytest_configure(config): A `UsageError` is pytest's own refusal (exit 4, `ERROR: `), which is what a composed run that cannot be the claim it makes should be: not a - session of skips that exits 0.""" + session of skips that exits 0. + + THEN THE REAL ENGINE'S PLUGIN, `tests/pgcluster.py` (#165, L2-0a): its + fixtures, its loud skip, and `OPENREPOTOOLS_REQUIRE_PG`'s refusal, the + same `UsageError`. This hook is historic, so the plugin's own + `pytest_configure` runs the moment it is registered, before any test.""" refusal = ROOTS.refusal() if refusal: raise pytest.UsageError(refusal) + if not config.pluginmanager.has_plugin(pgcluster.PLUGIN_NAME): + config.pluginmanager.register(pgcluster, pgcluster.PLUGIN_NAME) def pytest_report_header(config): @@ -543,6 +562,24 @@ def pytest_terminal_summary(terminalreporter, exitstatus, config): #: builds every environment it runs from scratch and decides for itself. os.environ["LANES_INDEX"] = "off" +#: opensoft/openRepoTools#165, batch e Q91 (lane 3, 6808937880) — AND NO WRITER +#: UNDER TEST ASKS `lanes-index mode` OF THE WORKSTATION'S CONFIGURATION. A +#: writer asks wherever `LANES_INDEX_CONFIG` is set and non-empty, or a file is +#: at `${XDG_CONFIG_HOME:-$HOME/.config}/openRepoTools/lanes-index.conf` +#: (`lanes-edit.sh`'s `reg_config_present`, `lanes-index`'s `config_path`), and +#: a case that moves `HOME` but copies `os.environ` still carries the person's +#: `XDG_CONFIG_HOME`. So the run drops the one and points the other at an empty +#: directory of its own, made here in `TMPDIR` (under `tests/run.sh`, the run +#: root its trap removes) and removed at exit; an empty value would not do, as +#: both read it as unset. A case that needs a configuration names its own, by +#: `LANES_INDEX_CONFIG` or an `XDG_CONFIG_HOME` in its sandbox. The same +#: variable keeps the workstation's `sweep.conf` from `lane-worktrees`, and its +#: `git/config` from git. +os.environ.pop("LANES_INDEX_CONFIG", None) +EMPTY_CONFIG_HOME = Path(tempfile.mkdtemp(prefix="orpt-config-")) +atexit.register(shutil.rmtree, str(EMPTY_CONFIG_HOME), True) +os.environ["XDG_CONFIG_HOME"] = str(EMPTY_CONFIG_HOME) + #: opensoft/openRepoTools#162 — and no `lane-start` a test runs starts the #: estate's daily report: it is detached, it reads the whole estate, and the #: state directory it stamps may be the workstation's own. @@ -626,3 +663,68 @@ def git(*args: str, cwd: Path, check: bool = True) -> subprocess.CompletedProces raise AssertionError(f"git {' '.join(args)} in {cwd} failed:\n" f"{proc.stderr}{proc.stdout}") return proc + + +#: THE LANDING GATE (T280; Brett's "Temporary landing gate (Recommended)", +#: 2026-11-13; FR-059), TEMPORARY: T281 removes this block in the last set, +#: with `tests/sql_register_gate.py`, which says what the gate reads. In a +#: GitHub Actions run whose workflow is not `verify` and whose ref is not a +#: `verify/` branch, or wherever `SQL_REGISTER_GATE=on`, each 007 test whose +#: tasks have not all landed is SKIPPED, and the skip names them. Every run +#: checks the tables and the markers, so a bad row fails a local run too. +#: Nothing else changes in a run where the gate is not active, so a local run +#: is otherwise ungated. The skips are marked after `-k` has deselected +#: (`trylast`), so no fixture of a gated id runs, and no cluster starts for +#: one. +SQL_REGISTER_LANDED = Path(__file__).resolve().parent / sql_register_gate.LANDED + +#: Every module the run collected, by `id()`, before `-k` deselects: each one's +#: table is checked whether or not its ids are selected. +_GATE_MODULES: Dict[int, object] = {} + + +#: Every id and function each module's collection holds, by the module's +#: `id()`, read from its collect report and its classes' before any `-k`, +#: `-m`, `--deselect` or node-id selection: a table key outside them fails the +#: run (Codex's review of E `d58f3b82`, BLOCKING 1). A class the run did not +#: collect, under a node id elsewhere in its module, leaves the module +#: unchecked (`None`). +_GATE_NAMES: Dict[int, Set[str]] = {} +_GATE_CLASSES: Dict[int, Set[str]] = {} + + +def pytest_itemcollected(item): + module = getattr(item, "module", None) + if module is not None: + _GATE_MODULES.setdefault(id(module), module) + + +@pytest.hookimpl(wrapper=True, trylast=True) +def pytest_make_collect_report(collector): + report = yield + if isinstance(collector, (pytest.Module, pytest.Class)) and report.passed: + key = id(collector.module) + names = _GATE_NAMES.setdefault(key, set()) + pending = _GATE_CLASSES.setdefault(key, set()) + pending.discard(collector.nodeid) + for node in report.result or (): + if isinstance(node, pytest.Function): + names.update((node.name, node.originalname)) + elif isinstance(node, pytest.Class): + pending.add(node.nodeid) + return report + + +@pytest.hookimpl(trylast=True) +def pytest_collection_modifyitems(config, items): + """THE GATE: pytest's own `UsageError`, exit 4, for a table or a marker it + cannot read, and a skip naming the tasks each gated id still waits for.""" + try: + names = {key: (None if _GATE_CLASSES.get(key) else found) + for key, found in _GATE_NAMES.items()} + skips = sql_register_gate.gate(items, list(_GATE_MODULES.values()), + os.environ, SQL_REGISTER_LANDED, names) + except sql_register_gate.GateError as exc: + raise pytest.UsageError(f"the landing gate (T280): {exc}") from None + for item, why in skips: + item.add_marker(pytest.mark.skip(reason=why)) diff --git a/tests/pgcluster.py b/tests/pgcluster.py new file mode 100644 index 00000000..14eb9360 --- /dev/null +++ b/tests/pgcluster.py @@ -0,0 +1,660 @@ +# SPDX-License-Identifier: Apache-2.0 +"""A REAL POSTGRESQL 16 FOR THE TESTS THAT NEED ONE (#165, L2-0a and L2-0b). + +What only an engine decides, a fake `psql` cannot show: a SERIALIZABLE +conflict's 40001, a GRANT that refuses, a COMMIT whose session dies. This is +the fixture those tests run on, R1's option (a) as the test plan's section +3.1 settles it, from the fixture probe's prototype (sha256 `5f20d742…`). +Python 3.9 or later, standard library only. `tests/conftest.py` registers it +as a pytest plugin from its `pytest_configure`. + +ONE DISPOSABLE CLUSTER PER SESSION. `initdb -N` into a 0700 +`mkdtemp(prefix="orpg-", dir="/tmp")`, whose socket path is 32 bytes whatever +`TMPDIR` is; a postmaster started by `Popen` on that Unix socket alone, with +no TCP; and one database per test, cloned from the session's template. A +`Popen` postmaster stays in pytest's process group, so `tests/run.sh`'s stop +of the group reaches it, where `pg_ctl`'s would not; on Linux it also dies +with a SIGKILLed pytest, and the next session's start sweeps what a killed +one left. + +THE FIXTURES: + + * `pg_engine`, session-scoped: the binaries, found once. EVERY CLUSTER + DEPENDS ON IT, so a test whose fixture closure holds it is a real-engine + test, which is how `test_sql_register_fixture.py` tells one apart; + * `pg_template_sql`, session-scoped and overridable: the SQL that builds the + template's schema, empty until the bootstrap lands (T227); + * `pg_cluster`, session-scoped: the session's cluster, with the template + `tmpl` built, then closed to connections; + * `pg`, one database per test, `CREATE DATABASE t_ TEMPLATE tmpl`, and + dropped `WITH (FORCE)` at its teardown; + * `stoppable_cluster`, a cluster of the test's own, built like the + session's, for the tests that stop the database: `stop()` is a fast + shutdown, SIGINT and a wait, and `start_again()` starts it on the same + data and socket directories. + +The binaries' directory goes first on `PATH` while a cluster is up, so the +code under test runs the `psql` of the server it talks to, and every +subprocess the fixture runs has no inherited `PG*` variable. + +THE SWITCH, `OPENREPOTOOLS_REQUIRE_PG`, unset, `0` or `1`, and nothing else. +Where no PostgreSQL 16 is found, or the run is root (`initdb` refuses root): + + * unset or `0`, every real-engine test SKIPS, naming each place tried, + `PG_BIN` and the package, and a banner says so even under `-q`; + * `1`, as CI sets it, `pytest_configure` refuses the run before any test, + `UsageError`, exit 4. The refusal is EAGER: a run that selects no + real-engine test is refused too, so a job cannot go green without the + engine it was promised. + +The binaries are `PG_BIN`, which is final (one that fails is reported, never +replaced), then `pg_config --bindir`, then `/usr/lib/postgresql/16/bin`. Each +candidate needs `initdb`, `pg_ctl`, `postgres` and `psql`, all saying +`(PostgreSQL) 16`. Where they were found is printed at the run's foot whenever +they were looked for, which under the switch is every run (open point 12). + +THE SMOKE, `python3 -I -B tests/pgcluster.py --smoke …`, runs without +pytest. `session` starts a cluster, clones a database from an empty template +and runs `SELECT 1` in it; `stoppable` starts a cluster, stops it by SIGINT, +starts it again on the same directories and runs `SELECT 1`. It exits 0 when +each named smoke passes, 1 when one fails or there is no engine, and 2 for a +name it does not know. +""" + +from __future__ import annotations + +import os +import re +import shutil +import signal +import stat +import subprocess +import sys +import tempfile +import time +from pathlib import Path +from typing import Dict, List, Optional, Tuple +from urllib.parse import quote + +#: THE SMOKE IMPORTS NO PYTEST: run as a script, this module is standard +#: library only, and the fixtures below are plain functions it never calls. +if __name__ == "__main__": + pytest = None +else: + import pytest + +#: The name `tests/conftest.py` registers this plugin under. +PLUGIN_NAME = "openrepotools-pg" + +ENV_REQUIRE = "OPENREPOTOOLS_REQUIRE_PG" +MAJOR, PACKAGE = 16, "postgresql-16" +DEBIAN_BIN = Path("/usr/lib/postgresql/16/bin") +TOOLS = ("initdb", "pg_ctl", "postgres", "psql") +SUPERUSER, PORT, TEMPLATE = "lanes_test", 5432, "tmpl" +SOCKET_PARENT, PREFIX = "/tmp", "orpg-" # /tmp/orpg-XXXXXXXX/.s.PGSQL.5432 = 32 bytes +SOCKET_MAX = 100 # sun_path: 107 usable on Linux, 103 on macOS +FAST = ("fsync=off", "synchronous_commit=off", "full_page_writes=off") +DEADLINE, POLL = 30.0, 0.005 +SKIP_TAG = "real PostgreSQL 16" +DIE_WITH_PYTEST = True # Linux: PR_SET_PDEATHSIG(SIGQUIT) on the postmaster +DEVNULL = subprocess.DEVNULL +_SKIPPED: List[str] = [] +_SWEPT: List[str] = [] + + +def _fixture(**options): + """`pytest.fixture(**options)`; in the smoke, which runs without pytest, + the function as it is.""" + if pytest is None: + return lambda function: function + return pytest.fixture(**options) + + +def switch_problem(environ=os.environ) -> Optional[str]: + """Why the switch's value is refused, or None for unset, `0` or `1`.""" + value = environ.get(ENV_REQUIRE, "") + if value in ("", "0", "1"): + return None + return (f"{ENV_REQUIRE}={value!r} is neither 1 (the real-engine tests are " + f"required, as in CI) nor 0 or unset (they skip, loudly, where " + f"PostgreSQL {MAJOR} is missing)") + + +def required(environ=os.environ) -> bool: + """Whether the real-engine tests must run: a usage error, exit 4, for a + value that is neither.""" + problem = switch_problem(environ) + if problem: + raise pytest.UsageError(problem) + return environ.get(ENV_REQUIRE, "") == "1" + + +# ------------------------------------------------------------ the binaries +def check_bindir(bindir: Path) -> Optional[str]: + """None where `bindir` holds the four tools at major 16, else why not.""" + if not bindir.is_dir(): + return f"{bindir} is not a directory" + missing = [t for t in TOOLS if not os.access(str(bindir / t), os.X_OK) or (bindir / t).is_dir()] + if missing: + return f"{bindir} has no {', '.join(missing)}" + for tool in TOOLS: + try: + said = subprocess.run([str(bindir / tool), "--version"], stdin=DEVNULL, capture_output=True, + text=True, timeout=20, check=False).stdout.strip() + except (OSError, subprocess.SubprocessError) as exc: + said = f"<{exc}>" + m = re.search(r"\(PostgreSQL\) (\d+)", said) + if not m or int(m.group(1)) != MAJOR: + return f"{bindir / tool} is not PostgreSQL {MAJOR}: it says {said!r}" + return None + + +def find_bindir(environ=os.environ) -> Tuple[Optional[Path], str]: + """(directory, how found), or (None, every place tried and why not).""" + named = environ.get("PG_BIN", "") + if named: + why = check_bindir(Path(named)) + return ((Path(named), "PG_BIN") if why is None else + (None, f"PG_BIN={named}, and {why}; a named PG_BIN is never replaced by a found one")) + tried = ["PG_BIN is unset"] + pg_config = shutil.which("pg_config", path=environ.get("PATH", os.defpath)) + if pg_config: + try: + out = subprocess.run([pg_config, "--bindir"], stdin=DEVNULL, capture_output=True, + text=True, timeout=20, check=False).stdout.strip() + except (OSError, subprocess.SubprocessError): + out = "" + why = check_bindir(Path(out)) if out else "it printed nothing" + if why is None: + return Path(out), f"`{pg_config} --bindir`" + tried.append(f"`{pg_config} --bindir` says {out or '-'}, and {why}") + else: + tried.append("no pg_config on PATH") + why = check_bindir(DEBIAN_BIN) + if why is None: + return DEBIAN_BIN, "the Debian and Ubuntu layout" + return None, "; ".join(tried + [why]) + + +class Probe: + """Where the binaries are and how they were found, or the problem.""" + + def __init__(self) -> None: + self.bindir, self.how = find_bindir() + self.problem: Optional[str] = None + if self.bindir is None: + self.problem = (f"no {SKIP_TAG} for the real-engine tests ({self.how}): install the " + f"package {PACKAGE} (server and client), or set PG_BIN to a directory " + f"holding {', '.join(TOOLS)} of major version {MAJOR}") + elif hasattr(os, "geteuid") and os.geteuid() == 0: + self.problem = (f"{SKIP_TAG} is at {self.bindir} ({self.how}), but this run is root, and " + f"initdb refuses to run as root: run the suite as an ordinary user") + + def found(self) -> str: + return f"{SKIP_TAG} at {self.bindir} ({self.how})" + + +_PROBE: Optional[Probe] = None + + +def probe() -> Probe: + global _PROBE + if _PROBE is None: + _PROBE = Probe() + return _PROBE + + +def _engine_first(bindir: Path, path: str) -> str: + """`path` with `bindir` first, once.""" + rest = [entry for entry in path.split(os.pathsep) if entry and entry != str(bindir)] + return os.pathsep.join([str(bindir), *rest]) + + +def _without_pg(environ=os.environ) -> Dict[str, str]: + """`environ` with no variable whose name begins `PG`: a person's + `PGHOST`, `PGSERVICE` or `PGPASSWORD` never steers a test.""" + return {k: v for k, v in environ.items() if not k.startswith("PG")} + + +# ------------------------------------------------------------ the cluster +#: THE STALE SWEEP'S SEAMS (T205c): where a process's identity is read, and +#: how a signal is sent. Its test points them at a fake `/proc`, or none, as +#: on macOS, and at a recorder, so that no real process can be signalled. +_PROC = Path("/proc") +_kill = os.kill +ORPHAN_WAIT = 10.0 # seconds a stale postmaster gets to end, per signal + + +def _ticks(pid: int) -> str: + """The process's start time (Linux), so a reused pid is not taken for its owner.""" + try: + return (_PROC / str(pid) / "stat").read_text().rsplit(")", 1)[1].split()[19] + except (OSError, IndexError): + return "-" + + +def _running(pid: int, ticks: str = "-") -> bool: + try: + _kill(pid, 0) + except ProcessLookupError: + return False + except PermissionError: + return True + try: + if (_PROC / str(pid) / "stat").read_text().rsplit(")", 1)[1].split()[0] == "Z": + return False # a zombie counts as dead + except (OSError, IndexError): + pass + return ticks == "-" or _ticks(pid) == ticks + + +def _stop_orphan(root: Path) -> bool: + """Stop the postmaster a dead session left in `root`, if it is provably + that one (T205c). True when no process of the root's is left: there is no + pidfile; its pid names no process, or one this user may not signal, or + one whose command line does not hold the root's data directory; or the + postmaster, proved by its command line and start time, ended on SIGQUIT + or SIGKILL. False, with nothing signalled, where the pidfile does not + parse to a positive pid and the root's data directory, or where the + process cannot be proved to be that postmaster (no `/proc`, as on + macOS); False too where the proved postmaster does not end. A pid is + never signalled on the pidfile's word alone.""" + try: + lines = (root / "data" / "postmaster.pid").read_text().splitlines() + except FileNotFoundError: + return True + except OSError: + return False + try: + pid_n, datadir = int(lines[0]), lines[1] + except (IndexError, ValueError): + return False + if pid_n <= 0 or datadir != str(root / "data"): + return False # 0 is a process group, -1 every process + try: + _kill(pid_n, 0) + except ProcessLookupError: + return True + except PermissionError: + return True # another user's process: not this user's postmaster + if not _running(pid_n): + return True # a zombie + ticks = _ticks(pid_n) + try: + argv = (_PROC / str(pid_n) / "cmdline").read_bytes().split(b"\0") + except OSError: + return False # no `/proc`: who holds the pid cannot be proved + if ticks == "-" or argv == [b""]: + return False + if os.fsencode(datadir) not in argv: + return True # a reused pid: that postmaster is gone + for sig in (signal.SIGQUIT, signal.SIGKILL): + if not _running(pid_n, ticks): + return True + try: + _kill(pid_n, sig) + except ProcessLookupError: + return True + except PermissionError: + return False + end = time.monotonic() + ORPHAN_WAIT + while time.monotonic() < end and _running(pid_n, ticks): + time.sleep(0.02) + if not _running(pid_n, ticks): + return True + return False + + +def sweep_stale() -> List[str]: + """What a SIGKILLed session left: this user's PREFIX dirs whose owner is gone.""" + swept = [] + for root in Path(SOCKET_PARENT).glob(PREFIX + "*"): + try: + info = root.lstat() + if not stat.S_ISDIR(info.st_mode) or info.st_uid != os.getuid(): + continue + owner = (root / "owner").read_text().split() if (root / "owner").exists() else [] + except OSError: + continue + if len(owner) == 2 and owner[0].isdigit() and _running(int(owner[0]), owner[1]): + continue + if not owner and time.time() - info.st_mtime < 60: + continue # being made this instant: not ours to judge yet + if not _stop_orphan(root): + continue # its postmaster is unproved or alive: not to be removed + shutil.rmtree(root, ignore_errors=True) + swept.append(str(root)) + return swept + + +class ClusterError(Exception): + pass + + +def _client_env(host: Path, user: str, dbname: str, appname: str, bindir: Path) -> dict: + env = _without_pg() + env.update(PGHOST=str(host), PGPORT=str(PORT), PGUSER=user, PGDATABASE=dbname, + PGAPPNAME=appname, PGCONNECT_TIMEOUT="10", LC_ALL="C", + PATH=_engine_first(bindir, env.get("PATH", os.defpath))) + return env + + +def _die_with_parent(parent: int): + if not (DIE_WITH_PYTEST and sys.platform.startswith("linux")): + return None + import ctypes + prctl = ctypes.CDLL(None, use_errno=True).prctl + + def preexec() -> None: + prctl(1, int(signal.SIGQUIT), 0, 0, 0) # PR_SET_PDEATHSIG + if os.getppid() != parent: + os._exit(70) + return preexec + + +class Cluster: + """One cluster: its private directory, its postmaster and its template.""" + + def __init__(self, bindir: Path, template_sql: str = "") -> None: + self.bindir, self.template_sql = bindir, template_sql + self.root: Optional[Path] = None + self.proc: Optional[subprocess.Popen] = None + self.count, self.timings = 0, {} + + def tool(self, name: str) -> str: + return str(self.bindir / name) + + def server_env(self) -> dict: + env = _without_pg() + env.update(LC_ALL="C", TZ="UTC", PATH=_engine_first(self.bindir, env.get("PATH", os.defpath))) + return env + + def psql(self, sql: str, dbname: str = "postgres", user: str = SUPERUSER, + check: bool = True, appname: str = "pytest") -> subprocess.CompletedProcess: + proc = subprocess.run([self.tool("psql"), "-X", "-q", "-A", "-t", "-v", "ON_ERROR_STOP=1", + "-f", "-"], input=sql, capture_output=True, text=True, timeout=120, + env=_client_env(self.root, user, dbname, appname, self.bindir), + check=False) + if check and proc.returncode != 0: + raise ClusterError(f"psql as {user} on {dbname} exited {proc.returncode}: {proc.stderr.strip()}") + return proc + + def log_tail(self) -> str: + try: + return " | ".join((self.root / "server.log").read_text().splitlines()[-5:]) + except OSError: + return "" + + def ready(self) -> bool: + """The postmaster's own `ready` status, line 8 of postmaster.pid: what pg_ctl -w reads.""" + try: + lines = (self.root / "data" / "postmaster.pid").read_text().splitlines() + except OSError: + return False + return len(lines) >= 8 and lines[0] == str(self.proc.pid) and lines[7].strip() == "ready" + + def start(self) -> None: + """Sweep, make the directory, `initdb`, start, and build the template.""" + t0 = time.monotonic() + _SWEPT.extend(sweep_stale()) + self.root = Path(tempfile.mkdtemp(prefix=PREFIX, dir=SOCKET_PARENT)) # mode 0700 + (self.root / "owner").write_text(f"{os.getpid()} {_ticks(os.getpid())}\n") + sock = self.root / f".s.PGSQL.{PORT}" + if len(os.fsencode(str(sock))) > SOCKET_MAX: + raise ClusterError(f"the socket path {sock} is over {SOCKET_MAX} bytes") + t1 = time.monotonic() + init = subprocess.run([self.tool("initdb"), "-D", str(self.root / "data"), "-N", "-A", "trust", + "-U", SUPERUSER, "-E", "UTF8", "--locale=C"], stdin=DEVNULL, + capture_output=True, text=True, env=self.server_env(), timeout=120, + check=False) + if init.returncode != 0: + raise ClusterError(f"initdb exited {init.returncode}: {init.stderr.strip()}") + t2 = time.monotonic() + self.launch() + t3 = time.monotonic() + self.psql(f"CREATE DATABASE {TEMPLATE};") + if self.template_sql.strip(): + self.psql(self.template_sql, dbname=TEMPLATE) + self.psql(f"ALTER DATABASE {TEMPLATE} WITH IS_TEMPLATE true ALLOW_CONNECTIONS false;") + t4 = time.monotonic() + self.timings = {"initdb": t2 - t1, "ready": t3 - t2, "template": t4 - t3, "start": t4 - t0} + + def launch(self) -> None: + """`postgres` by `Popen` on this cluster's directories, and wait until it is ready.""" + argv = [self.tool("postgres"), "-D", str(self.root / "data"), "-p", str(PORT), + "-c", "listen_addresses=", "-c", f"unix_socket_directories={self.root}"] + for setting in FAST: + argv += ["-c", setting] + with open(self.root / "server.log", "ab") as log: + self.proc = subprocess.Popen(argv, stdin=DEVNULL, stdout=log, stderr=subprocess.STDOUT, + env=self.server_env(), preexec_fn=_die_with_parent(os.getpid())) + end = time.monotonic() + DEADLINE + while not self.ready(): + if self.proc.poll() is not None: + raise ClusterError(f"postgres exited {self.proc.returncode} starting: {self.log_tail()}") + if time.monotonic() > end: + raise ClusterError(f"postgres was not ready in {DEADLINE:.0f} s: {self.log_tail()}") + time.sleep(POLL) + + def stop(self) -> None: + """A fast shutdown: SIGINT to the postmaster this cluster started, and a wait.""" + if self.proc is None or self.proc.poll() is not None: + raise ClusterError("the cluster is not running, so it cannot be stopped") + self.proc.send_signal(signal.SIGINT) + try: + self.proc.wait(timeout=DEADLINE) + except subprocess.TimeoutExpired: + raise ClusterError(f"postgres did not stop in {DEADLINE:.0f} s after SIGINT: " + f"{self.log_tail()}") from None + + def start_again(self) -> None: + """Start the stopped cluster on the same data and socket directories.""" + if self.proc is not None and self.proc.poll() is None: + raise ClusterError("the cluster is running, so it cannot be started again") + self.launch() + + def new_database(self) -> str: + self.count += 1 + name = f"t_{self.count}" + self.psql(f"CREATE DATABASE {name} TEMPLATE {TEMPLATE};") + return name + + def drop_database(self, name: str) -> None: + self.psql(f"DROP DATABASE IF EXISTS {name} WITH (FORCE);") + + def destroy(self) -> None: + """SIGQUIT, a wait (SIGKILL after the deadline), and the directory removed.""" + try: + if self.proc is not None and self.proc.poll() is None: + self.proc.send_signal(signal.SIGQUIT) # immediate shutdown + try: + self.proc.wait(timeout=DEADLINE) + except subprocess.TimeoutExpired: + self.proc.kill() + self.proc.wait() + finally: + if self.root is not None: + shutil.rmtree(self.root, ignore_errors=True) + + +class Database: + """One test's database, and how to reach it as each role.""" + + def __init__(self, cluster: Cluster, name: str) -> None: + self.cluster, self.name, self.host, self.port = cluster, name, cluster.root, PORT + self.psql_bin = cluster.tool("psql") + + def url(self, user: str = SUPERUSER) -> str: + return f"postgresql://{user}@{quote(str(self.host), safe='')}:{PORT}/{self.name}" + + def env(self, user: str = SUPERUSER, appname: str = "pytest") -> dict: + return _client_env(self.host, user, self.name, appname, self.cluster.bindir) + + def psql(self, sql: str, user: str = SUPERUSER, check: bool = True) -> subprocess.CompletedProcess: + return self.cluster.psql(sql, dbname=self.name, user=user, check=check) + + def session(self, user: str = SUPERUSER, appname: str = "pytest") -> subprocess.Popen: + """A psql of its own, fed on stdin: a separate session, for concurrency.""" + return subprocess.Popen([self.psql_bin, "-X", "-q", "-A", "-t", "-v", "ON_ERROR_STOP=1"], + stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, env=self.env(user, appname)) + + +# ------------------------------------------------------------ pytest +def pytest_configure(config) -> None: + if required() and probe().problem: + raise pytest.UsageError(f"{ENV_REQUIRE}=1, so the real-engine tests must run, and they " + f"cannot - this run is refused rather than let them skip: " + f"{probe().problem}") + + +def pytest_runtest_logreport(report) -> None: + if report.skipped and SKIP_TAG in str(report.longrepr): + _SKIPPED.append(report.nodeid) + + +def pytest_terminal_summary(terminalreporter) -> None: + """LOUD, where -q cannot hide it: the skips, where the binaries were found + whenever they were looked for, and anything a killed session left.""" + if _SKIPPED: + terminalreporter.write_sep("!", f"{len(_SKIPPED)} real-engine test(s) SKIPPED", yellow=True) + terminalreporter.write_line(probe().problem or "") + elif _PROBE is not None and _PROBE.problem is None: + terminalreporter.write_line(f"real-engine: {_PROBE.found()}") + if _SWEPT: + terminalreporter.write_line(f"real-engine: removed {len(_SWEPT)} cluster(s) a killed " + f"session left: {', '.join(_SWEPT)}") + + +def _started(found: Probe, template_sql: str) -> Cluster: + cluster = Cluster(found.bindir, template_sql) + try: + cluster.start() + except (ClusterError, OSError, subprocess.SubprocessError) as exc: + cluster.destroy() + pytest.fail(f"{SKIP_TAG} is at {found.bindir} ({found.how}), and its cluster did not " + f"start: {exc}", pytrace=False) + return cluster + + +@_fixture(scope="session") +def pg_engine() -> Probe: + """The binaries every cluster runs: a skip without them, or under the + switch a failure (the run was refused already, so this is a guard).""" + found = probe() + if found.problem: + if required(): + pytest.fail(found.problem, pytrace=False) + pytest.skip(found.problem) + return found + + +@_fixture(scope="session") +def pg_template_sql() -> str: + """The template's schema. Empty until L1-A7 lands: T227 overrides this + with the bootstrap's roles, migrations and grants.""" + return "" + + +@_fixture(scope="session") +def pg_cluster(pg_engine, pg_template_sql): + cluster = _started(pg_engine, pg_template_sql) + patch = pytest.MonkeyPatch() + patch.setenv("PATH", _engine_first(pg_engine.bindir, os.environ.get("PATH", os.defpath))) + try: + yield cluster + finally: + patch.undo() + cluster.destroy() + + +@_fixture() +def pg(pg_cluster): + name = pg_cluster.new_database() + yield Database(pg_cluster, name) + pg_cluster.drop_database(name) + + +@_fixture() +def stoppable_cluster(pg_engine, pg_template_sql): + """A cluster of the test's own, on the same `Cluster` class: `stop()` and + `start_again()`, and its own template.""" + cluster = _started(pg_engine, pg_template_sql) + patch = pytest.MonkeyPatch() + patch.setenv("PATH", _engine_first(pg_engine.bindir, os.environ.get("PATH", os.defpath))) + try: + yield cluster + finally: + patch.undo() + cluster.destroy() + + +# ------------------------------------------------------------ the smoke +def _select_1(cluster: Cluster, dbname: str = "postgres") -> None: + said = cluster.psql("SELECT 1;", dbname=dbname).stdout.strip() + if said != "1": + raise ClusterError(f"SELECT 1 on {dbname} answered {said!r}") + + +def _smoke_session(found: Probe) -> str: + cluster = Cluster(found.bindir) + try: + cluster.start() + name = cluster.new_database() + _select_1(cluster, name) + cluster.drop_database(name) + return (f"{name} cloned from the empty {TEMPLATE} in {cluster.root}, and SELECT 1 " + f"answered 1; started in {cluster.timings['start']:.2f} s") + finally: + cluster.destroy() + + +def _smoke_stoppable(found: Probe) -> str: + cluster = Cluster(found.bindir) + try: + cluster.start() + first = cluster.proc.pid + cluster.stop() + cluster.start_again() + _select_1(cluster) + return (f"postmaster {first} stopped by SIGINT, {cluster.proc.pid} started again on " + f"{cluster.root}, and SELECT 1 answered 1") + finally: + cluster.destroy() + + +SMOKES = {"session": _smoke_session, "stoppable": _smoke_stoppable} + + +def main(argv: List[str]) -> int: + """`--smoke …`: 0 when each passes, 1 when one fails, 2 for a usage error.""" + if len(argv) < 2 or argv[0] != "--smoke": + print(f"usage: python3 -I -B tests/pgcluster.py --smoke <{'|'.join(SMOKES)}>...", + file=sys.stderr) + return 2 + unknown = [name for name in argv[1:] if name not in SMOKES] + if unknown: + print(f"pgcluster: no smoke named {', '.join(unknown)}; the smokes are " + f"{', '.join(SMOKES)}", file=sys.stderr) + return 2 + found = Probe() + if found.problem: + print(f"pgcluster: FAIL: {found.problem}", file=sys.stderr) + return 1 + print(f"pgcluster: {found.found()}") + failed = 0 + for name in argv[1:]: + try: + said = SMOKES[name](found) + except (ClusterError, OSError, subprocess.SubprocessError) as exc: + print(f"pgcluster: smoke {name}: FAIL: {exc}", file=sys.stderr) + failed += 1 + else: + print(f"pgcluster: smoke {name}: ok: {said}") + for root in _SWEPT: + print(f"pgcluster: removed {root}, which a killed session left") + return 1 if failed else 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/tests/sql_register_gate.py b/tests/sql_register_gate.py new file mode 100644 index 00000000..0d0a30d3 --- /dev/null +++ b/tests/sql_register_gate.py @@ -0,0 +1,271 @@ +# SPDX-License-Identifier: Apache-2.0 +"""THE LANDING GATE'S READER (T280; Brett's "Temporary landing gate +(Recommended)", 2026-11-13; FR-059). TEMPORARY: T281 removes it in the last +set, T328's, with the hook in `tests/conftest.py`, the marker directory, +`tests/test_sql_register_gate.py`, its `repo_hygiene` row and every module's +table, and the whole suite then runs ungated. + +Every 007 code pull request passes full CI, and 007's tests land before the +code they test. So from the first set until the last, a 007 test whose tasks +have not all landed is SKIPPED, and the skip names the tasks it waits for: +"waits for T415, T416". + +THE TABLES. A 007 test module carries its own table, `SQL_REGISTER_GATE_TABLE`, +written from its task's **Order** and lane 2's per-id verdict rows, in that +task's own files. A key is one of: + + * `"*"`, the tasks every id of the module waits for; + * a test function's name, for every id of that function; + * one id with its parameters, `name[param]`, which replaces the function's + row for that one id. + +Each value is a tuple of 007 task ids. An id waits for the union of the +module's `"*"` row and its own row. An id that no table names runs, and so does +every id of a module with no table. This module adds no table of its own. + +A key other than `"*"` that names no test of its module FAILS THE RUN, gated or +not, since a misspelled key matches nothing and the test it meant would run +ungated (Codex's review of E `d58f3b82`, BLOCKING 1). The names are every id +pytest's collection of the module holds and each id's function, read from the +module's own collect report before any `-k`, `-m`, `--deselect` or node-id +selection: `tests/conftest.py` gathers them. A module whose test class was not +collected (a node id elsewhere in it was named) is not checked in that run. + +THE MARKERS. `tests/sql_register_landed/` is one empty file for each +landed task: a marker that is not an empty regular file, or a marker +directory that is a symlink, fails the run. Each code PR adds its tasks' markers at its cut, outside every +task's `files:`, and that one change turns the set's own tests on in its own +full CI. Git keeps no empty directory, so before the first set's cut there is +no directory, and a missing directory is read as "no task has landed". + +007'S TASK IDS. The code leg holds no `tasks.md`, so the ids are carried here, +as `TASK_IDS`: tasks.md's task lines at `SPEC_COMMIT`. A table or a marker that +names anything else FAILS THE RUN, gated or not, so a bad row fails a local run +too. A task added to tasks.md later is added to `TASK_IDS` by the first code +PR whose table or marker names it. + +WHEN THE GATE IS ACTIVE (lane 3's rulings, 2026-11-13 and 2026-11-14). Only in +a GitHub Actions run (`GITHUB_ACTIONS=true`) whose workflow is not `verify` and +whose ref is not a `verify/` branch. The ref is `GITHUB_HEAD_REF` on a +`pull_request` or `pull_request_target` event, whose `GITHUB_REF_NAME` is +`/merge`, and `GITHUB_REF_NAME` on any other event. That covers each +pull request's CI, `main`'s CI and the merge queue's runs. Local runs, line R's +census, every `verify/` branch and every run of `verify.yml` run ungated: those +branches are cut from line R, which holds no markers, and a dispatched verify +run may be on any ref (`GITHUB_WORKFLOW` is `verify`), so no verify passes by +the gate's skip. `SQL_REGISTER_GATE=on` or `=off` overrides that either way, +and any other value of it is refused. Nothing under `.github/` sets it, nor +does `tests/run.sh`, as a `repo_hygiene` row holds. + +The gate decides by landing state alone. With `OPENREPOTOOLS_REQUIRE_PG=1`, a +missing engine still refuses the run in `pgcluster.py`'s `pytest_configure`, +before any test is collected, so the gate's skip cannot hide one. Nor does +the reason carry pgcluster's "real PostgreSQL 16", so its banner never counts +a gated id as an engine skip. + +Python 3.9 or later, standard library only. `tests/conftest.py` calls `gate()` +from its `pytest_collection_modifyitems`, after `-k` has deselected. +""" + +from __future__ import annotations + +import stat +from pathlib import Path +from typing import AbstractSet, Dict, Iterable, List, Mapping, Optional, Tuple + +#: The variable that overrides when the gate is active. +SWITCH = "SQL_REGISTER_GATE" + +#: The name of a module's table. +TABLE = "SQL_REGISTER_GATE_TABLE" + +#: The marker directory's name, beside `tests/conftest.py`. +LANDED = "sql_register_landed" + +#: The key of a table's row for every id of its module. +EVERY = "*" + +#: The spec commit `TASK_IDS` was read from: lane 3's commit 17 of 007's +#: follow-up, whose tasks.md has 158 task lines, T236's among them. +SPEC_COMMIT = "204145ae4b1acaeee0a841306a0563c3550c3528" + +#: 007'S TASK IDS: the id of every task line of tasks.md at `SPEC_COMMIT`. +TASK_IDS = frozenset(""" + T101 T102 T103 T104 T105 T106 T107 T108 T109 T110 T111 T112 T113 T114 + T115 T116 T117 T118 T119 T120 T121 T122 T123 T124 + T200 T201 T202 T203 T204 T205 T206 T207 T210 T211 T212 T213 T214 T215 + T216 T217 T218 T219 T220 T221 T222 T223 T224 T225 T226 T227 T228 T229 + T230 T231 T232 T233 T234 T235 T236 T237 T240 T241 T242 T243 T244 T245 + T246 T247 T248 T251 T252 T253 T254 T255 T256 T257 T258 T259 T270 T271 + T272 T273 T274 T275 T276 T277 T278 T279 T280 T281 + T301 T302 T303 T304 T320 T321 T322 T323 T324 T325 T326 T327 T328 T340 + T341 T342 T343 T344 T345 T346 T347 + T401 T402 T403 T404 T405 T406 T407 T408 T409 T410 T411 T412 T413 T414 + T415 T416 T417 T418 T419 T420 T421 T422 T423 T424 T425 T426 T427 T428 + T429 T430 T431 T432 T433 T434 + T501 T502 T503 T504 T505 T506 T507 T508 T509 T510 T511 T512 T513 +""".split()) + +#: `verify.yml`'s `name:`, which GitHub gives a run of it as `GITHUB_WORKFLOW` +#: whatever its ref: a dispatched verify run is ungated too (lane 3's (b), +#: opensoft/openRepoTools#165 comment 6870017590). +VERIFY_WORKFLOW = "verify" + +#: The events whose head branch is `GITHUB_HEAD_REF`. +PULL_REQUEST_EVENTS = ("pull_request", "pull_request_target") + + +class GateError(Exception): + """A table, a marker or the switch the gate cannot read: the run fails. + `tests/conftest.py` raises it as pytest's `UsageError`, exit 4.""" + + +def in_task_order(tasks: Iterable[str]) -> Tuple[str, ...]: + """`tasks` once each, by number: T205 before T415 before T416.""" + return tuple(sorted(set(tasks), key=lambda task: int(task[1:]))) + + +def ref(environ: Mapping[str, str]) -> str: + """The branch a GitHub Actions run is for.""" + if environ.get("GITHUB_EVENT_NAME", "") in PULL_REQUEST_EVENTS: + return environ.get("GITHUB_HEAD_REF", "") + return environ.get("GITHUB_REF_NAME", "") + + +def active(environ: Mapping[str, str]) -> bool: + """Whether this run skips the ids whose tasks have not all landed.""" + value = environ.get(SWITCH, "") + if value == "on": + return True + if value == "off": + return False + if value: + raise GateError(f"{SWITCH}={value!r} is neither on nor off; unset, the " + f"landing gate (T280) is active only in a GitHub " + f"Actions run whose workflow is not {VERIFY_WORKFLOW} " + f"and whose ref is not a verify/ branch") + if environ.get("GITHUB_ACTIONS", "") != "true": + return False + if environ.get("GITHUB_WORKFLOW", "") == VERIFY_WORKFLOW: + return False + return not ref(environ).startswith("verify/") + + +def landed(directory: Path) -> frozenset: + """The tasks with a marker in `directory`. A missing directory is no task + landed; anything in it but an empty regular file named for one of 007's + task ids fails the run, and so does a `directory` that is a symlink or + cannot be read (Codex's review of E `d58f3b82`, SHOULD 7).""" + if directory.is_symlink(): + raise GateError(f"{directory} is a symlink: the landing gate (T280) " + f"reads its markers in a directory of the tree") + if not directory.exists(): + return frozenset() + if not directory.is_dir(): + raise GateError(f"{directory} is not a directory: the landing gate " + f"(T280) reads its markers there") + found, refused = [], [] + try: + entries = sorted(directory.iterdir()) + except OSError as exc: + raise GateError(f"{directory} cannot be read ({exc.strerror or exc}): " + f"the landing gate (T280) reads its markers there") from None + for entry in entries: + try: + mode = entry.lstat() + except OSError: + mode = None + if (entry.name in TASK_IDS and mode is not None + and stat.S_ISREG(mode.st_mode) and mode.st_size == 0): + found.append(entry.name) + else: + refused.append(entry.name) + if refused: + raise GateError(f"{directory} holds {', '.join(refused)}: a marker is a " + f"file named for one of 007's task ids (tasks.md at " + f"{SPEC_COMMIT[:8]}), one for each landed task") + return frozenset(found) + + +def table_of(module, names: Optional[AbstractSet[str]] = None + ) -> Optional[Dict[str, Tuple[str, ...]]]: + """`module`'s table, checked, or None where it has none. Where `names`, the + module's every id and function, is given, a key outside it is refused.""" + raw = getattr(module, TABLE, None) + if raw is None: + return None + where = f"{TABLE} in {getattr(module, '__file__', None) or module.__name__}" + if not isinstance(raw, dict): + raise GateError(f"{where} is a {type(raw).__name__}, not a dict of test " + f"name to the task ids it waits for") + table: Dict[str, Tuple[str, ...]] = {} + problems: List[str] = [] + for key, tasks in raw.items(): + if not isinstance(key, str) or not key: + problems.append(f"the key {key!r} is not a test name, an id or {EVERY!r}") + continue + if isinstance(tasks, str) or not isinstance(tasks, (tuple, list)): + problems.append(f"{key!r} maps to {tasks!r}, not a tuple of task ids") + continue + unknown = [task for task in tasks + if not isinstance(task, str) or task not in TASK_IDS] + if unknown: + problems.append(f"{key!r} names {', '.join(map(str, unknown))}, " + f"which {'is' if len(unknown) == 1 else 'are'} not " + f"one of 007's task ids") + continue + table[key] = tuple(tasks) + if problems: + raise GateError(f"{where}: {'; '.join(problems)} (007's task ids are " + f"tasks.md's task lines at {SPEC_COMMIT[:8]})") + strangers = [key for key in table if key != EVERY and names is not None + and key not in names] + if strangers: + raise GateError(f"{where}: " + "; ".join( + f"{key!r} names no test of its module" for key in strangers) + + f" (a key is {EVERY!r}, a test function's name, or one of its ids " + f"with its parameters)") + return table + + +def waits_for(table: Mapping[str, Tuple[str, ...]], name: str, + function: str) -> Tuple[str, ...]: + """The tasks the id `name` of the test `function` waits for: the module's + `"*"` row and its own, the id's row in place of the function's.""" + own = table[name] if name in table else table.get(function, ()) + return in_task_order(tuple(table.get(EVERY, ())) + tuple(own)) + + +def reason(missing: Iterable[str]) -> str: + """The skip's reason, naming the tasks it still waits for.""" + return (f"waits for {', '.join(in_task_order(missing))} (the landing gate, " + f"T280: no marker in tests/{LANDED}/)") + + +def gate(items, modules: Iterable[object], environ: Mapping[str, str], + directory: Path, names: Optional[Mapping[int, Optional[AbstractSet[str]]]] = None + ) -> List[Tuple[object, str]]: + """Each item to skip, with its reason. Every table of `modules` and every + marker is checked first, gated or not; nothing is skipped where the gate + is not active. `names` maps a module's `id()` to its every id and + function, against which its table's keys are checked.""" + items = list(items) + names = names or {} + tables: Dict[int, Optional[Dict[str, Tuple[str, ...]]]] = {} + for module in [*modules, *(getattr(item, "module", None) for item in items)]: + if module is not None and id(module) not in tables: + tables[id(module)] = table_of(module, names.get(id(module))) + marked = landed(directory) + if not active(environ): + return [] + skips = [] + for item in items: + table = tables.get(id(getattr(item, "module", None))) + if not table: + continue + name = item.name + tasks = waits_for(table, name, getattr(item, "originalname", None) or name) + missing = [task for task in tasks if task not in marked] + if missing: + skips.append((item, reason(missing))) + return skips diff --git a/tests/sql_register_helpers.py b/tests/sql_register_helpers.py new file mode 100644 index 00000000..cc357350 --- /dev/null +++ b/tests/sql_register_helpers.py @@ -0,0 +1,2030 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Stand-ins for feature 007's SQL-register tests (L2-0d): the copies and the +stubs of `lanes-index`, and the `psql`s a test puts first on `PATH`. + +Test modules import it from `tests/`, as three modules import +`package_layout.py`. What it holds: + +- `flipped_copy(source, dest, value)`: `source`, a `lanes-index`, copied to + `/lanes-index` with its one `RENDER_GIT_HALF = …` line rewritten to + `value`, True or False. It takes the constant in either state, so test 14's + refusing copy still builds once lane 3's T328 sets it True (T277). There is + no environment override, which would be a production bypass of Q6(c)'s + refusal (the test plan's open point 3; PC-5). `dest` is a directory, so a + test copies `lanes-edit.sh` and what it reads beside the copy, where + `lanes-index` and `lanes-edit.sh` each look for the other. +- `primary_stub(directory)`: a stub `lanes-index` for the bash tests, at + `/lanes-index`, that answers `mode` with `primary` and logs every + call. The contract's whole stub is T207's `contract_stub`. +- `REGISTER_FAKE_PSQL`: the register's fake `psql` (the test plan's section + 3.2), which extends `test_lanes_index.py`'s `FAKE_PSQL`. +- `PSQL_SHIM`: section 3.2's shim in front of the real `psql`, armed per test + by a control file beside it. +- `contract_stub(directory, register=None)` and `stub_outcome(directory, + argv_prefix, …)`: the contract's stub `lanes-index`, as CLI4.5 §6 states + it, and the outcomes a test injects into it (T207). `contract_stub`'s + docstring is its manual. +- `guard_session(home, directory, cwd, ...)`, `guard_strip_env(...)` and + `GUARD_ENV_STRIP`: what a case gives `lanes-edit.sh guard` before it runs + it, so that the guard gets past its session-record check to its register + read (T203c): a live session record on this workstation, a stand-in `tmux` + that answers the guard's window queries, the compact hook JSON, and the + environment with the variables that would steer the guard elsewhere taken + out. `guard_session`'s docstring is its manual. + +THE FAKE-`psql` HOST RULE (lane 1's L1v4.5:525; #165 6741670709 item 9): the +fake and the shim are made for configurations whose `register_url=` names a +Unix socket or a loopback host (`localhost`, `127.0.0.0/8`, `::1`), or carries +`sslmode=verify-full` with an `sslrootcert=` naming a root file, never +`system`. Lane 1's T104 refuses any other at load (CLI4.5 §2.5), before any +`psql` runs. + +THE ARGV LOG: each stub writes `/lanes-index.argv`, one line per +call, the call's arguments as one JSON array, so a test can assert that the +stub ran and what it was asked. + +THE REGISTER'S FAKE `psql`. A test writes `REGISTER_FAKE_PSQL` to `/psql`, +makes it executable and puts `` first on `PATH`. Its environment: + +- `FAKE_PSQL_LOG` (required) names its log: one JSON object per call, in call + order, with `FAKE_PSQL`'s fields, `url`, `passfile`, `pgpassword` and + `stdin`, and these besides: + - `call`, the call's number in this log, from 1, counting only the calls + that carry a request: a `psql --version` call is not counted (below); + - `argv`, the whole argument list (P1475): what each path sends is the + test's to assert, and the fake asserts no `VERBOSITY` for the calls the + design leaves unnamed (the test plan's open point 29); + - `connect_timeout`, `options` and `service`: `PGCONNECT_TIMEOUT`, + `PGOPTIONS` (the path's `options=-c lock_timeout=… -c + statement_timeout=…`) and `PGSERVICE`, each null where it is unset; + - `pg`: every variable it received whose name begins `PG`, with its value, + `PGPASSWORD`'s alone recorded as `*`, for T257's inherited-`PG*` cases + (lane 3's R-PG-1, #165 6747611042). + + `url` is the connection rebuilt from the `PG*` variables, as lane 1's T103 + hands it on, `postgresql://@[:]/`, with + no port where `PGPORT` is unset, and empty where none of the four is set. +- An argument that is `-d`, `--dbname` or one that holds a connection URL is + refused: the call is logged with `refused`, and the fake exits 1. No + register path puts a connection string in an argument list (Y:3491; CLI4.5 + §2.2 and §6). +- `psql --version`, a call whose whole argument list is `--version`, is a + call of its own kind. Lane 1's T106 runs it once per process on a register + path, before it sends anything, and refuses a `psql` older than 15 with 69, + naming its version, with nothing sent (L1v4.10:152; lane 1, #165 + 6752661856). The fake reads no stdin for it and answers `psql (PostgreSQL) + 16.4` (`PSQL_VERSION_LINE`) with exit 0, unless a `version` rule in + `FAKE_PSQL_ANSWERS` answers it. Its log entry is + `{"kind": "version", "url": …, "passfile": …, "pgpassword": …, "argv": + ["--version"], "connect_timeout": …, "options": …, "service": …, "pg": + {…}}`, with no `call` and no `stdin`. So the calls that carry a request are + the entries with no `kind`, a case counting them leaves the probe out + (`e.get("kind") != "version"`), and their `call` numbers are the ones a + test without the probe sees. +- `FAKE_PSQL_ANSWERS` (optional) names a JSON file: a list of answers, each + taught for the calls it names. The first that names a call answers it: + - it names calls by `call` (that call alone), `from` (every call from that + one on) and `match` (a text the call's stdin carries), all that it gives + holding; an answer with none of the three names every call; + - it answers with `sleep` (seconds, before anything else: a hang past the + caller's timer), then `stdout` and `stderr`, then `signal` (a name, such + as `KILL`, that the fake sends itself: a death by a signal) or `exit` + (default 0); + - a rule with `"kind": "version"` names the `psql --version` calls, every + one, and only them: it takes no `call`, `from` or `match`, and answers + as any rule does. Every other rule names only the calls that carry a + request. So T257's `[snapshot-psql-14]` teaches `{"kind": "version", + "stdout": "psql (PostgreSQL) 14.11\\n"}`, and a `--version` that hangs or + fails is taught with `sleep` or `exit`. + + So the 69 refusal is `{"call": 1, "exit": 2}`; the retry's shape is + `{"match": "commit_write", "exit": 3, "stderr": "ERROR: 40001: could not + serialize access due to concurrent update\\n"}`; and a code taught for exit + 3 is taught as `ERROR: : `, an LR005 or an LR007 with its + `DETAIL: ` line after it (section 3.2, "The line it is taught"). +- A call no answer names is answered as `FAKE_PSQL` answers it, as an empty + schema-1 store would, with `FAKE_PSQL_VERSION_FILE` read as it reads it. + +THE SHIM. A test writes `PSQL_SHIM` to `/psql`, makes it executable, +puts `` first on `PATH`, ahead of the directory of the real `psql`, and +arms it by writing `/psql-shim.json`. It runs as `python3 -I`, standard +library only. With no control file it hands every call on unchanged. The +control file: + +- `psql` (optional): the real `psql` to hand calls to; otherwise the first + `psql` on `PATH` that is not the shim. +- `version` (optional): the line the shim answers `psql --version` with, + `psql (PostgreSQL) 16.4` (`PSQL_VERSION_LINE`) where it is absent, such as + `"psql (PostgreSQL) 14.11"` for T257's `[snapshot-psql-14]`. A call whose + whole argument list is `--version` (lane 1's T106 probe, once per process + on a register path: L1v4.10:152) is answered by the shim itself, that line + and exit 0, and is never handed on: it reads no stdin, no arm applies to it, + and it is not counted in `call`, `from` or the state. +- `arms`: a list, each arm a mode and the calls it applies to. An arm names + calls by `call` (call k alone), `from` (every call from call k on) or + `match` (a text the call's script carries, such as `find_write` for a + lookup try or `commit_write` for a commit call). With `match`, `call` and + `from` count only the calls that carry the text, so `{"match": + "commit_write", "call": 2}` is the second commit call. An arm with none of + the three applies to every call. One test may arm several modes, each on + its own calls. + +The modes, with the keys each takes: + +- `window`, `ms`: sleep before handing the call on; +- `before` and `after`: a `pg_terminate_backend(pg_backend_pid())` statement + before or after the script's last `COMMIT`, joined with psql's `\\;`, so the + call stays one request. `after` exits 2 once the call has landed; with + `fifo`, it first blocks on that FIFO; +- `timer`, `ms` or `fifo`: run the real `psql`, then sleep, or block on the + FIFO in place of the sleep, then answer as `psql` answered; +- `fail-call` (by `call` or `from`) and `fail-match` (by `match`): exit 2, + sending nothing; +- `edit-entry`, `field` and `value`: rewrite one field of the commit call's + entry, the `'…'::jsonb` argument of `commit_write(`, before handing the + call on. `field` may be a dotted path, such as `act.base`, and must exist. + A part that meets a list is an index into it, a negative one counting from + the list's end, so `register_lines.-1.workstation` is the last + `register_lines` row's `workstation` (T203d); an index past either end is a + field that is not there. Without `value` the field, or the list's element, + is removed; +- `no-reconnect`, `as` (`before` or `after`): the first call the arm names + is lost as that mode loses it, and every later call exits 2, sending + nothing, as from a host that cannot reconnect; +- `hold`, `fifo`: block on the FIFO before handing the call on. A test's + `open(fifo, "w")` returns once the call is held, and closing it lets the + call go; +- `fork`, `fifo`, optional `exit`: start the call in a session of its own + (`setsid`), where it blocks on the FIFO before it runs the real `psql`, and + wait for it, so the caller's timer, which kills the shim, never reaches + the call. With `"exit": true` the shim exits 2 once the fork is made. + +Per call, the failures come first (a lost host, then `fail-call` and +`fail-match`), then `edit-entry`, `before` and `after` rewrite the script, +then `hold`, `window`, `fork`, the real `psql`, `after` and `timer`. + +The shim writes, beside itself, `psql-shim.log`, one JSON object per call +when the call starts: `call`, `argv`, `stdin`, `sent` (the script as handed +on), `arms` (the modes applied), and the fake's `url`, `passfile`, +`pgpassword` and `pg`; `psql-shim.ends`, one line per call that ended, with +the codes; and its counters in `psql-shim.state`. A `psql --version` call's +entry in `psql-shim.log` is its own kind, `{"kind": "version", "argv": +["--version"], "url": …, "passfile": …, "pgpassword": …, "pg": {…}}`, with +no `call`, and it writes nothing to `psql-shim.ends` or the state, so the +calls that carry a request are the entries with no `kind`. A control file it +cannot read, an arm it does not know, or an arm that cannot apply to the call +it names (a `before` on a call with no `COMMIT`, an `edit-entry` field that is +not there) ends the call with exit 1 and `psql-shim: …` on stderr, recorded +in the log as `error`, sending nothing; on a `--version` call, so does a +control file it cannot read or a `version` that is not a string. + +STANDARD LIBRARY ONLY, AND NOTHING FROM THE SUITE: no `conftest`, no pytest, +so the module loads the same way under pytest and under a task's +`python3 -I -c` verify, on Python 3.9 and up. Each script it writes is +standard library only too. +""" + +from __future__ import annotations + +import json +import os +import re +import subprocess +import sys +import time +import uuid +from pathlib import Path + +#: THE CODE ROOT: the parent of this file's `tests/`, and the `lanes-index` in +#: it, which `flipped_copy` copies. +REPO = Path(__file__).resolve().parent.parent +LANES_INDEX = REPO / "lanes-index" + +#: Q6(c)'S CONSTANT, AS `lanes-index` SPELLS IT (lane 1's T105): one line, +#: `RENDER_GIT_HALF = False` until lane 3's T328 sets it True. +RENDER_GIT_HALF_LINE = re.compile(rb"^RENDER_GIT_HALF = (True|False)$", re.M) + +#: The name of each stub's argv log, beside the stub. +ARGV_LOG = "lanes-index.argv" + +#: The shim's own files, beside it. +PSQL_SHIM_CONTROL = "psql-shim.json" +PSQL_SHIM_LOG = "psql-shim.log" +PSQL_SHIM_ENDS = "psql-shim.ends" + +#: The shim's ten modes (the test plan's section 3.2). +PSQL_SHIM_MODES = ("window", "before", "after", "timer", "fail-call", "fail-match", + "edit-entry", "no-reconnect", "hold", "fork") + +#: WHAT BOTH `psql`s ANSWER `psql --version` WITH, unless a test names another +#: (the fake's `version` rule, the shim's `version` key): a `psql` lane 1's +#: T106 accepts, 15 or later (L1v4.10:152). Each script holds this text too. +PSQL_VERSION_LINE = "psql (PostgreSQL) 16.4" + + +def flipped_copy(source, dest, value) -> Path: + """Copy the `lanes-index` at `source` to `/lanes-index`, its + `RENDER_GIT_HALF` line rewritten to `value`, and return the copy's path. + + The copy is the source's bytes but that one line, with the executable bit. + `dest` is made if it is missing. A source with no such line, or with more + than one, is refused, so a test never runs a copy it did not flip.""" + if not isinstance(value, bool): + raise TypeError(f"flipped_copy: value must be True or False, not {value!r}") + text = Path(source).read_bytes() + found = RENDER_GIT_HALF_LINE.findall(text) + if len(found) != 1: + raise ValueError(f"flipped_copy: {source} holds {len(found)} `RENDER_GIT_HALF = ` " + f"lines, not one") + directory = Path(dest) + directory.mkdir(parents=True, exist_ok=True) + copy = directory / "lanes-index" + copy.write_bytes(RENDER_GIT_HALF_LINE.sub(b"RENDER_GIT_HALF = " + str(value).encode(), text)) + copy.chmod(0o755) + return copy + + +#: THE STUB FOR THE BASH TESTS (R2's S8): a Python script a test runs by its +#: path. `mode` alone is answered, `primary`; anything else is not stubbed, +#: and ends 64 with that said, so a test sees what reached it. +_PRIMARY_STUB = r'''#!/usr/bin/env python3 +# A STUB lanes-index (feature 007, L2-0d): it answers `mode` with `primary` +# and logs every call, one JSON array of arguments per line. Nothing else is +# stubbed here: the contract's whole stub is contract_stub (T207). +import json, sys + +with open(ARGV_LOG_PATH, "a", encoding="utf-8") as handle: + handle.write(json.dumps(sys.argv[1:]) + "\n") +if sys.argv[1:] == ["mode"]: + sys.stdout.write("primary\n") + sys.exit(0) +sys.stderr.write("lanes-index: this stub answers only `mode`: %s\n" % json.dumps(sys.argv[1:])) +sys.exit(64) +''' + + +def primary_stub(directory) -> Path: + """Write `/lanes-index`, the stub that answers `mode` with + `primary` and logs every call to `/lanes-index.argv`, and + return its path. `directory` is made if it is missing.""" + directory = Path(directory) + directory.mkdir(parents=True, exist_ok=True) + stub = directory / "lanes-index" + log = str((directory / ARGV_LOG).resolve()) + stub.write_text(_PRIMARY_STUB.replace("ARGV_LOG_PATH", repr(log)), encoding="utf-8") + stub.chmod(0o755) + return stub + + +REGISTER_FAKE_PSQL = r'''#!/usr/bin/env python3 +# The REGISTER's FAKE psql (feature 007, L2-0d; the test plan's section 3.2). +# It extends test_lanes_index.py's FAKE_PSQL: it records what FAKE_PSQL +# records, the URL (rebuilt from the PG* variables), PGPASSFILE, whether +# PGPASSWORD is set, and stdin, and also the call's number, the whole argv, +# PGCONNECT_TIMEOUT, PGOPTIONS, PGSERVICE and every PG* variable it received. +# A test may teach it an answer per call (FAKE_PSQL_ANSWERS); otherwise it +# answers as FAKE_PSQL does. No database exists. It asserts no VERBOSITY. +# `psql --version` (lane 1's T106 probe) is a call of its own kind: answered +# DEFAULT_VERSION, or by a {"kind": "version"} rule, logged with +# "kind": "version" and never counted in `call`. +import fcntl, json, os, signal, sys, time + +DEFAULT_VERSION = "psql (PostgreSQL) 16.4" +log = os.environ["FAKE_PSQL_LOG"] +answers = os.environ.get("FAKE_PSQL_ANSWERS", "") +vfile = os.environ.get("FAKE_PSQL_VERSION_FILE", "") +version = open(vfile).read().strip() if vfile else "1" +args = sys.argv[1:] +asks_version = args == ["--version"] +stdin = "" if asks_version else sys.stdin.read() +env = os.environ +url = "" +if any(env.get(k) for k in ("PGHOST", "PGPORT", "PGDATABASE", "PGUSER")): + url = "postgresql://%s@%s%s/%s" % (env.get("PGUSER", ""), env.get("PGHOST", ""), + ":" + env["PGPORT"] if env.get("PGPORT") else "", + env.get("PGDATABASE", "")) +record = {"url": url, "passfile": env.get("PGPASSFILE", ""), "pgpassword": "PGPASSWORD" in env, + "stdin": stdin, "argv": args, "connect_timeout": env.get("PGCONNECT_TIMEOUT"), + "options": env.get("PGOPTIONS"), "service": env.get("PGSERVICE"), + "pg": {k: ("*" if k == "PGPASSWORD" else v) for k, v in sorted(env.items()) + if k.startswith("PG")}} +# NO CONNECTION STRING IN THE ARGUMENTS (Y:3491; CLI4.5 section 2.2 and 6). +refused = [a for a in args if a == "--dbname" or a.startswith("--dbname=") or + (a.startswith("-d") and not a.startswith("--")) or + "postgresql://" in a or "postgres://" in a] +if refused: + record["refused"] = "a connection string or -d in the arguments: %s" % json.dumps(refused) +if asks_version: + record = dict({"kind": "version"}, **{k: v for k, v in record.items() if k != "stdin"}) +with open(log, "a+", encoding="utf-8") as handle: + fcntl.flock(handle, fcntl.LOCK_EX) + handle.seek(0) + # `call` counts the calls that carry a request: never a --version entry. + call = sum(1 for line in handle if not line.startswith('{"kind": "version"')) + 1 + if not asks_version: + record = dict({"call": call}, **record) + handle.write(json.dumps(record) + "\n") +if refused: + sys.stderr.write("psql: error: the fake refuses %s\n" % record["refused"]) + sys.exit(1) + + +def taught(): + # A {"kind": "version"} rule names every --version call and only them; + # every other rule names only the calls that carry a request. + if not answers: + return None + with open(answers, encoding="utf-8") as handle: + rules = json.load(handle) + for rule in rules: + if (rule.get("kind") == "version") != asks_version: + continue + if asks_version: + return rule + if "call" in rule and rule["call"] != call: + continue + if "from" in rule and call < rule["from"]: + continue + if "match" in rule and rule["match"] not in stdin: + continue + return rule + return None + + +rule = taught() +if rule is not None: + if rule.get("sleep"): + time.sleep(float(rule["sleep"])) + sys.stdout.write(rule.get("stdout", "")) + sys.stderr.write(rule.get("stderr", "")) + sys.stdout.flush() + sys.stderr.flush() + if rule.get("signal"): + os.kill(os.getpid(), getattr(signal, "SIG" + rule["signal"])) + time.sleep(5) + sys.exit(int(rule.get("exit", 0))) +if asks_version: + sys.stdout.write(DEFAULT_VERSION + "\n") + sys.exit(0) +if vfile and "CREATE TABLE IF NOT EXISTS" in stdin: + with open(vfile, "w") as handle: + handle.write("1\n") + + +def echo(text): + # `\echo` AS psql's OWN LEXER READS IT (opensoft/openRepoTools#166 item 4; + # psqlscanslash.l's `xslashquote`), as test_lanes_index.py's FAKE_PSQL + # reads it: words split on blanks, a quoted run taken whole, and inside + # the quotes `''`, `\n \t \b \r \f`, octal `\ooo` and hex `\xhh` decoded. + words, word, quoted, i = [], "", False, 0 + while i < len(text): + ch = text[i] + if not quoted and ch in " \t": + if word: + words.append(word) + word = "" + i += 1 + elif ch == "'" and quoted and text[i + 1:i + 2] == "'": + word, i = word + "'", i + 2 + elif ch == "'": + quoted, i = not quoted, i + 1 + elif quoted and ch == "\\" and i + 1 < len(text): + nxt = text[i + 1] + octal = len(text[i + 1:i + 4]) - len(text[i + 1:i + 4].lstrip("01234567")) + hexes = len(text[i + 2:i + 4]) - len(text[i + 2:i + 4].lstrip("0123456789abcdefABCDEF")) + if nxt in "ntbrf": + word, i = word + {"n": "\n", "t": "\t", "b": "\b", "r": "\r", "f": "\f"}[nxt], i + 2 + elif octal: + word, i = word + chr(int(text[i + 1:i + 1 + octal], 8)), i + 1 + octal + elif nxt == "x" and hexes: + word, i = word + chr(int(text[i + 2:i + 2 + hexes], 16)), i + 2 + hexes + else: + word, i = word + nxt, i + 2 + else: + word, i = word + ch, i + 1 + if word: + words.append(word) + return " ".join(words) + + +for line in stdin.splitlines(): + if line.startswith("COPY (SELECT version"): + if version: + print(version) + elif line.startswith("\\echo"): + print(echo(line[len("\\echo"):])) +sys.exit(0) +''' + + +PSQL_SHIM = r'''#!/usr/bin/env -S python3 -I +# THE PSQL SHIM (feature 007, L2-0d; the test plan's section 3.2): one +# `python3 -I` script, standard library only, in front of the REAL psql, armed +# per test by psql-shim.json beside it. Its modes: window, before, after, +# timer, fail-call, fail-match, edit-entry, no-reconnect, hold and fork. +# `psql --version` (lane 1's T106 probe) it answers itself, DEFAULT_VERSION or +# the control file's `version`, logged with "kind": "version" and never counted. +# tests/sql_register_helpers.py's docstring is its manual. +import fcntl, json, os, re, signal, subprocess, sys, time + +DEFAULT_VERSION = "psql (PostgreSQL) 16.4" +HERE = os.path.dirname(os.path.abspath(__file__)) +CONTROL = os.path.join(HERE, "psql-shim.json") +LOG = os.path.join(HERE, "psql-shim.log") +ENDS = os.path.join(HERE, "psql-shim.ends") +STATE = os.path.join(HERE, "psql-shim.state") +LOCK = os.path.join(HERE, "psql-shim.lock") +MODES = ("window", "before", "after", "timer", "fail-call", "fail-match", "edit-entry", + "no-reconnect", "hold", "fork") +KEYS = {"mode", "call", "from", "match", "ms", "fifo", "exit", "field", "value", "as"} +NEEDS = {"window": ("ms",), "hold": ("fifo",), "fork": ("fifo",), "edit-entry": ("field",), + "no-reconnect": ("as",), "fail-match": ("match",)} +TERMINATE = "SELECT pg_terminate_backend(pg_backend_pid())" +COMMIT = re.compile(r"\bCOMMIT\b[ \t]*;?", re.I) +ENTRY = re.compile(r"'((?:[^']|'')*)'::jsonb") + + +class ShimError(Exception): + pass + + +def arm_key(arm): + return json.dumps(arm, sort_keys=True) + + +def check(arms): + if not isinstance(arms, list): + raise ShimError("`arms` is not a list") + for arm in arms: + if not isinstance(arm, dict) or arm.get("mode") not in MODES: + raise ShimError("an arm with no mode of %s: %s" % (", ".join(MODES), json.dumps(arm))) + unknown = sorted(set(arm) - KEYS) + if unknown: + raise ShimError("an arm with keys it does not know, %s: %s" + % (", ".join(unknown), json.dumps(arm))) + for key in NEEDS.get(arm["mode"], ()): + if key not in arm: + raise ShimError("a `%s` arm needs `%s`: %s" % (arm["mode"], key, json.dumps(arm))) + if arm["mode"] == "timer" and "ms" not in arm and "fifo" not in arm: + raise ShimError("a `timer` arm needs `ms` or `fifo`: %s" % json.dumps(arm)) + if arm["mode"] == "no-reconnect" and arm["as"] not in ("before", "after"): + raise ShimError("a `no-reconnect` arm's `as` is `before` or `after`: %s" + % json.dumps(arm)) + + +def names(arm, call, script, state): + # Whether `arm` names this call. With `match`, `call` and `from` count the + # calls that carry the text (the count is kept in the state, per arm). + number = call + if "match" in arm: + if arm["match"] not in script: + return False + seen = state.setdefault("seen", {}) + number = seen[arm_key(arm)] = seen.get(arm_key(arm), 0) + 1 + if "call" in arm and number != arm["call"]: + return False + if "from" in arm and number < arm["from"]: + return False + return True + + +def terminate(script, where): + found = list(COMMIT.finditer(script)) + if not found: + raise ShimError("`%s`: the call's script has no COMMIT" % where) + m = found[-1] + if where == "before": + return script[:m.start()] + TERMINATE + " \\; " + script[m.start():] + statement = script[m.start():m.end()].rstrip(" \t;") + return script[:m.start()] + statement + " \\; " + TERMINATE + ";" + script[m.end():] + + +def step(node, key): + # One part of `field`: in a list, a whole number is an index, a negative + # one counting from the list's end (`register_lines.-1.workstation`, T203d); + # every other part is the key as written, so a dict's path reads as before. + if isinstance(node, list) and re.fullmatch(r"-?[0-9]+", key): + return int(key) + return key + + +def edit_entry(script, arm): + at = script.find("commit_write(") + if at < 0: + raise ShimError("`edit-entry`: the call carries no commit_write(") + m = ENTRY.search(script, at) + if not m: + raise ShimError("`edit-entry`: no '...'::jsonb entry after commit_write(") + try: + entry = json.loads(m.group(1).replace("''", "'")) + path = arm["field"].split(".") + node = entry + for key in path[:-1]: + node = node[step(node, key)] + last = step(node, path[-1]) + if isinstance(last, int): + if not -len(node) <= last < len(node): + raise IndexError("list index %d out of range for %d items" % (last, len(node))) + elif last not in node: + raise KeyError(last) + except (ValueError, KeyError, TypeError, IndexError) as exc: + raise ShimError("`edit-entry`: the entry has no field %s (%s)" % (arm["field"], exc)) + if "value" in arm: + node[last] = arm["value"] + else: + del node[last] + text = json.dumps(entry, ensure_ascii=False, separators=(",", ":")).replace("'", "''") + return script[:m.start()] + "'" + text + "'::jsonb" + script[m.end():] + + +def real_psql(control): + if control.get("psql"): + return control["psql"] + me = os.path.realpath(__file__) + for directory in os.environ.get("PATH", "").split(os.pathsep): + candidate = os.path.join(directory or ".", "psql") + if os.path.realpath(candidate) == me: + continue + if os.path.isfile(candidate) and os.access(candidate, os.X_OK): + return candidate + raise ShimError("no real psql on PATH behind the shim, and the control file names none") + + +def block(fifo): + with open(fifo, "rb") as handle: + handle.read() + + +def append(path, record): + with open(path, "a", encoding="utf-8") as handle: + fcntl.flock(handle, fcntl.LOCK_EX) + handle.write(json.dumps(record) + "\n") + + +def connection(): + env = os.environ + url = "" + if any(env.get(k) for k in ("PGHOST", "PGPORT", "PGDATABASE", "PGUSER")): + url = "postgresql://%s@%s%s/%s" % (env.get("PGUSER", ""), env.get("PGHOST", ""), + ":" + env["PGPORT"] if env.get("PGPORT") else "", + env.get("PGDATABASE", "")) + return {"url": url, "passfile": env.get("PGPASSFILE", ""), "pgpassword": "PGPASSWORD" in env, + "pg": {k: ("*" if k == "PGPASSWORD" else v) for k, v in sorted(env.items()) + if k.startswith("PG")}} + + +def relay(out, err): + sys.stdout.buffer.write(out) + sys.stderr.buffer.write(err) + sys.stdout.flush() + sys.stderr.flush() + + +def text(data): + return data.decode("utf-8", "surrogateescape") + + +def version(args): + # `psql --version`, as lane 1's T106 asks it once per process (L1v4.10:152): + # answered here, never handed on; no arm applies to it, it reads no stdin, + # and it is not counted in the state or written to the ends. + record = {"kind": "version", "argv": args} + record.update(connection()) + error, line = "", DEFAULT_VERSION + try: + try: + with open(CONTROL, encoding="utf-8") as handle: + control = json.load(handle) + except FileNotFoundError: + control = {} + except ValueError as exc: + raise ShimError("the control file is not JSON: %s" % exc) + if not isinstance(control, dict): + raise ShimError("the control file is not a JSON object") + line = control.get("version", DEFAULT_VERSION) + if not isinstance(line, str): + raise ShimError("`version` is not a string: %s" % json.dumps(line)) + except ShimError as exc: + error = str(exc) + record["error"] = error + append(LOG, record) + if error: + sys.stderr.write("psql-shim: %s\n" % error) + return 1 + sys.stdout.write(line + "\n") + sys.stdout.flush() + return 0 + + +def main(): + args = sys.argv[1:] + if args == ["--version"]: + return version(args) + raw = sys.stdin.buffer.read() + script = text(raw) + record = {"argv": args, "stdin": script} + record.update(connection()) + error = "" + chosen, lost = [], False + with open(LOCK, "a") as lock: + fcntl.flock(lock, fcntl.LOCK_EX) + try: + with open(STATE, encoding="utf-8") as handle: + state = json.load(handle) + except FileNotFoundError: + state = {} + call = state["calls"] = state.get("calls", 0) + 1 + record = dict({"call": call}, **record) + try: + try: + with open(CONTROL, encoding="utf-8") as handle: + control = json.load(handle) + except FileNotFoundError: + control = {} + except ValueError as exc: + raise ShimError("the control file is not JSON: %s" % exc) + arms = control.get("arms", []) + check(arms) + chosen = [arm for arm in arms if names(arm, call, script, state)] + if state.get("lost") and call > state["lost"]: + lost = True + for arm in chosen: + if arm["mode"] == "no-reconnect" and not state.get("lost"): + state["lost"] = call + except ShimError as exc: + error = str(exc) + with open(STATE + ".tmp", "w", encoding="utf-8") as handle: + json.dump(state, handle) + os.replace(STATE + ".tmp", STATE) + modes = [arm["mode"] for arm in chosen] + failing = [arm for arm in chosen if arm["mode"] in ("fail-call", "fail-match")] + sent = script + if not error and not lost and not failing: + try: + for arm in chosen: + if arm["mode"] == "edit-entry": + sent = edit_entry(sent, arm) + for arm in chosen: + if arm["mode"] in ("before", "after"): + sent = terminate(sent, arm["mode"]) + elif arm["mode"] == "no-reconnect" and state.get("lost") == call: + sent = terminate(sent, arm["as"]) + psql = real_psql(control) + except ShimError as exc: + error = str(exc) + record.update({"sent": sent, "arms": modes}) + if error: + record["error"] = error + if lost: + record["lost"] = True + append(LOG, record) + if error: + sys.stderr.write("psql-shim: %s\n" % error) + append(ENDS, {"call": call, "exit": 1, "error": error}) + return 1 + if lost or failing: + why = "no-reconnect" if lost else failing[0]["mode"] + sys.stderr.write("psql: error: connection to server failed: psql-shim %s (call %d)\n" + % (why, call)) + append(ENDS, {"call": call, "exit": 2, "failed": why}) + return 2 + for arm in chosen: + if arm["mode"] == "hold": + block(arm["fifo"]) + for arm in chosen: + if arm["mode"] == "window": + time.sleep(float(arm["ms"]) / 1000) + after = [arm for arm in chosen if arm["mode"] == "after" or + (arm["mode"] == "no-reconnect" and arm["as"] == "after" and state.get("lost") == call)] + forks = [arm for arm in chosen if arm["mode"] == "fork"] + data = sent.encode("utf-8", "surrogateescape") + if forks: + code, out, err = fork(forks[0], psql, args, data, call) + if code is None: + append(ENDS, {"call": call, "exit": 2, "forked": True}) + return 2 + else: + proc = subprocess.run([psql] + args, input=data, capture_output=True) + code, out, err = proc.returncode, proc.stdout, proc.stderr + for arm in after: + if arm.get("fifo"): + block(arm["fifo"]) + for arm in chosen: + if arm["mode"] == "timer": + if arm.get("fifo"): + block(arm["fifo"]) + else: + time.sleep(float(arm["ms"]) / 1000) + relay(out, err) + exit_code = 2 if after else code + append(ENDS, {"call": call, "exit": exit_code, "psql": code}) + return exit_code + + +def fork(arm, psql, args, data, call): + # The call in a session of its own, blocked on the FIFO before the real + # psql runs; its answer goes to a file, never to the shim's pipes, which + # the caller may have stopped reading. + result = os.path.join(HERE, "psql-shim.fork-%d.json" % call) + pid = os.fork() + if pid == 0: + code = 70 + try: + os.setsid() + null = os.open(os.devnull, os.O_RDWR) + for fd in (0, 1, 2): + os.dup2(null, fd) + os.closerange(3, 1024) + block(arm["fifo"]) + proc = subprocess.run([psql] + args, input=data, capture_output=True) + code = proc.returncode + with open(result + ".tmp", "w", encoding="utf-8") as handle: + json.dump({"exit": code, "stdout": text(proc.stdout), + "stderr": text(proc.stderr)}, handle) + os.replace(result + ".tmp", result) + append(ENDS, {"call": call, "exit": code, "fork": os.getpid()}) + finally: + os._exit(code) + if arm.get("exit"): + return None, b"", b"" + os.waitpid(pid, 0) + with open(result, encoding="utf-8") as handle: + answer = json.load(handle) + return (answer["exit"], answer["stdout"].encode("utf-8", "surrogateescape"), + answer["stderr"].encode("utf-8", "surrogateescape")) + + +def finish(code): + # A psql that died by a signal: the shim dies by the same one, so the + # caller reads a death by a signal, as it would from psql itself. + if code < 0: + try: + signal.signal(-code, signal.SIG_DFL) + except (OSError, ValueError): + pass + os.kill(os.getpid(), -code) + time.sleep(5) + sys.exit(code) + + +finish(main()) +''' + + +#: THE RENDER SET'S PATHS (CLI4.5 §3.2): `lanes/LANES.md`, `lanes/aliases.tsv`, +#: each `lanes/log/.md` and `lanes/archive/*`. `lanes/repos.tsv` and +#: `lanes/log/README.md` come from the checkout, never from the register. +RENDER_SET_PATH = re.compile(r"^lanes/(LANES\.md|aliases\.tsv|log/(?!README\.md$)[^/]+\.md" + r"|archive/[^/]+)$") + +#: The contract stub's own files, beside it. +STUB_OUTCOMES = "lanes-index.outcomes" +STUB_RENDER_LOG = "lanes-index.render" + + +#: THE CONTRACT'S STUB `lanes-index` (T207; CLI4.5 §6, "What the fakes must +#: do", CLI4.5:881-903). Its manual is `contract_stub`'s docstring. +_CONTRACT_STUB = r'''#!/usr/bin/env python3 +# THE CONTRACT'S STUB lanes-index (feature 007, L2-0d, T207), as CLI4.5 +# section 6 states it: sections 3.1 to 3.5 exactly, section 3.6's four forms of +# `register read`, and section 3.7's argv record. Its register is the files +# under lanes-index.register// beside it, its journal and head are in +# lanes-index.state, and a test injects an outcome with stub_outcome. It logs +# every call to lanes-index.argv, one JSON array of arguments per line. +# tests/sql_register_helpers.py's contract_stub is its manual. +import datetime, fcntl, hashlib, importlib.machinery, importlib.util, json, os, re, shutil +import subprocess, sys, time, uuid + +HERE = STUB_DIRECTORY +LANES_INDEX_SOURCE = LANES_INDEX_PATH +ARGV_LOG = os.path.join(HERE, "lanes-index.argv") +STATE = os.path.join(HERE, "lanes-index.state") +OUTCOMES = os.path.join(HERE, "lanes-index.outcomes") +RENDERS = os.path.join(HERE, "lanes-index.render") +REGISTER = os.path.join(HERE, "lanes-index.register") +LOCK = os.path.join(HERE, "lanes-index.lock") +SETS = os.path.join(HERE, "lanes-index.sets") + +UUID = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$") +HEX64 = re.compile(r"^[0-9a-f]{64}$") +HEX40 = re.compile(r"^[0-9a-f]{40}$") +NUMBER = re.compile(r"^[0-9]+$") +# check_lane_name's class: letters, digits, `.`, `_` and `-`, not opening +# with `.` or `-`. +LANE_CLASS = re.compile(r"^[A-Za-z0-9_][A-Za-z0-9._-]*$") +RENDER_SET = re.compile(r"^lanes/(LANES\.md|aliases\.tsv|log/(?!README\.md$)[^/]+\.md" + r"|archive/[^/]+)$") +ZEROS = "0" * 40 +# Section 2.4 and 2.5 at their defaults: c = 2, N_a = 1, no service (w_s 0), +# and the commit's timer C = N_a.c + 6 s; schema_version.version is 1. +C, N_A, W_S_MS, SCHEMA = 2, 1, 0, 1 +C_TIMER = N_A * C + 6 +SECRET = re.compile(r"TOKEN|SECRET|PASSWORD|PASSWD|KEY", re.I) + + +class Exit(Exception): + def __init__(self, code, out="", err=""): + Exception.__init__(self, code) + self.code, self.out, self.err = code, out, err + + +def usage(what): + raise Exit(64, "", "lanes-index: usage: %s\n" % what) + + +def refuse(code, sqlstate, message, token=None): + # Section 2.6: psql's ERROR line, then its DETAIL token, verbatim. + raise Exit(code, "", "ERROR: %s: %s\n" % (sqlstate, message) + + ("DETAIL: %s\n" % token if token else "")) + + +def options(args, values=(), equals=(), flags=(), positional=0): + got, rest, i = {}, [], 0 + while i < len(args): + arg = args[i] + name, eq, value = arg.partition("=") + if eq and name in equals: + if name in got: + usage("%s given twice" % name) + got[name] = value + i += 1 + elif arg in equals: + usage("%s takes its value in the = form, %s= (L1-D1)" % (arg, arg)) + elif arg in values: + if arg in got: + usage("%s given twice" % arg) + if i + 1 >= len(args): + usage("%s needs a value" % arg) + got[arg] = args[i + 1] + i += 2 + elif arg in flags: + if arg in got: + usage("%s given twice" % arg) + got[arg] = True + i += 1 + elif arg.startswith("-"): + usage("%s is not an option of this command" % arg) + else: + rest.append(arg) + i += 1 + if len(rest) != positional: + usage("%d operand(s), not %d" % (positional, len(rest))) + return got, rest + + +class Locked(object): + def __enter__(self): + self.handle = open(LOCK, "a") + fcntl.flock(self.handle, fcntl.LOCK_EX) + with open(STATE, encoding="utf-8") as handle: + self.state = json.load(handle) + return self.state + + def __exit__(self, *exc): + with open(STATE + ".tmp", "w", encoding="utf-8") as handle: + json.dump(self.state, handle) + os.replace(STATE + ".tmp", STATE) + self.handle.close() + return False + + +def put(path, data): + # Each family file by temp file and rename, as section 3.6 has it. + with open(path + ".tmp.%d" % os.getpid(), "wb") as handle: + handle.write(data) + os.replace(path + ".tmp.%d" % os.getpid(), path) + + +def images(seq): + root = os.path.join(REGISTER, str(seq)) + found = {} + for top, _dirs, files in os.walk(root): + for name in files: + full = os.path.join(top, name) + rel = os.path.relpath(full, root).replace(os.sep, "/") + if RENDER_SET.match(rel): + with open(full, "rb") as handle: + found[rel] = handle.read() + return found + + +def sha(data): + return hashlib.sha256(data).hexdigest() + + +def rows(state, seq): + for entry in state["journal"].values(): + if entry["seq"] == seq: + return entry["files"] + return [] + + +def identity(entry, lane, verb, digest): + return (entry["lane"], entry["verb"], entry["args_sha256"]) == (lane, verb, digest) + + +def git(cwd, *args): + env = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")} + return subprocess.run(["git", "-C", cwd, "-c", "user.name=lanes-index stub", + "-c", "user.email=stub@lanes-index.invalid", "-c", "commit.gpgsign=false"] + + list(args), capture_output=True, env=env, check=True) + + +def build_tree(tree, checkout, seq, state): + # Section 3.2's --tree: the render set at `seq`, from this stub's register; + # lanes/repos.tsv and lanes/log/README.md from --checkout's origin/main + # (under --at, repos.tsv as that seq's commit recorded it); one commit, + # and refs/remotes/origin/main pointing at it. + if os.path.exists(tree) and (not os.path.isdir(tree) or os.listdir(tree)): + usage("--tree %s must not exist or must be empty" % tree) + os.makedirs(tree, exist_ok=True) + files = images(seq) + for name in ("lanes/repos.tsv", "lanes/log/README.md"): + recorded = os.path.join(REGISTER, "%d.repos.tsv" % seq) + if name == "lanes/repos.tsv" and seq != state["n"] and os.path.exists(recorded): + with open(recorded, "rb") as handle: + files[name] = handle.read() + continue + env = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")} + shown = subprocess.run(["git", "-C", checkout, "show", "origin/main:" + name], + capture_output=True, env=env) + if shown.returncode == 0: + files[name] = shown.stdout + for rel, data in files.items(): + full = os.path.join(tree, rel) + os.makedirs(os.path.dirname(full), exist_ok=True) + with open(full, "wb") as handle: + handle.write(data) + git(tree, "init", "-q") + git(tree, "add", "-A") + git(tree, "commit", "-q", "--allow-empty", "-m", "register at seq %d" % seq) + git(tree, "update-ref", "refs/remotes/origin/main", "HEAD") + if "lanes/repos.tsv" not in files: + return ZEROS + return git(tree, "rev-parse", "HEAD:lanes/repos.tsv").stdout.decode().strip() + + +def snapshot(args): + o, _ = options(args, values=("--write-id", "--generation", "--lane", "--verb", "--args-sha256", + "--tree", "--checkout", "--at")) + wid, gen, at = o.get("--write-id"), o.get("--generation"), o.get("--at") + rest = [o.get(k) for k in ("--lane", "--verb", "--args-sha256")] + if ("--tree" in o) != ("--checkout" in o): + usage("--tree and --checkout go together") + if at is not None and not NUMBER.match(at): + usage("--at takes a seq") + if wid is None and gen is None and rest == [None, None, None]: + kind = "act-begin" + elif wid == "new" and gen is None and None not in rest: + kind = "new" + elif wid is not None and wid != "new" and gen is None: + usage("--write-id without --generation") + elif wid is not None and wid != "new" and None not in rest: + kind = "known" + elif wid is None and gen is not None and rest == [None, None, None] and at is not None: + kind = "generation" + else: + usage("the identity is all five flags, --write-id new with --lane, --verb and " + "--args-sha256, or none") + if at is not None and kind not in ("known", "generation"): + usage("--at without --generation") + if kind == "known" and not UUID.match(wid): + usage("--write-id is a lowercase UUID") + if gen is not None and not UUID.match(gen): + usage("--generation is a lowercase UUID") + if rest[2] is not None and not HEX64.match(rest[2]): + usage("--args-sha256 is 64 lowercase hex") + return lambda: snapshot_run(o, kind, wid, gen, at, rest) + + +def snapshot_run(o, kind, wid, gen, at, rest): + with Locked() as state: + if gen is not None and gen != state["generation"]: + refuse(2, "LR007", "the write's generation is not the register's", "generation") + seq = state["n"] + lines = ["format=1", "generation=%s" % state["generation"]] + if at is not None: + seq = int(at) + if seq > state["n"] or seq < state["first"]: + raise Exit(69, "", "lanes-index: register snapshot: seq %d is not in this " + "generation's journal\n" % seq) + elif kind == "known" and wid in state["journal"]: + entry = state["journal"][wid] + if not identity(entry, *rest): + refuse(2, "LR007", "the write id belongs to another write", "another-write") + lines += ["write_id=%s" % wid, "found=%d" % entry["seq"]] + lines += ["file=%s" % row for row in entry["files"]] + clock = int(time.time()) + lines += ["switch=primary", "marker=present", "n=%d" % state["n"], "clock=%d" % clock, + "not_after=%d" % (clock + C_TIMER + 2), "schema=%d" % SCHEMA, + "c=%d" % C, "n_a=%d" % N_A] + return Exit(0, "".join(line + "\n" for line in lines)) + if kind == "new": + wid = str(uuid.uuid4()) + if wid is not None: + lines.append("write_id=%s" % wid) + clock = int(time.time()) + lines += ["switch=primary", "marker=present", "n=%d" % state["n"], "clock=%d" % clock, + "not_after=%d" % (clock + C_TIMER + 2), "schema=%d" % SCHEMA] + if "--tree" in o: + lines.append("repos_blob=%s" % build_tree(o["--tree"], o["--checkout"], seq, state)) + lines += ["c=%d" % C, "n_a=%d" % N_A] + return Exit(0, "".join(line + "\n" for line in lines)) + + +def attempt(directory, o): + # Section 3.3's check of the attempt directory: 2, nothing sent. + def bad(what): + raise Exit(2, "", "lanes-index: attempt directory: %s; nothing was sent\n" % what) + + for name in ("snapshot", "changes.tsv", "msg", "author", "files", "not_after"): + if not os.path.isfile(os.path.join(directory, name)): + bad("%s is missing" % name) + if not os.path.isdir(os.path.join(directory, "tree")): + bad("tree/ is missing") + with open(os.path.join(directory, "snapshot"), encoding="utf-8") as handle: + snap = dict(line.partition("=")[::2] for line in handle.read().splitlines() if "=" in line) + if snap.get("generation") != o["--generation"] or snap.get("write_id") != o["--write-id"]: + bad("the flags differ from snapshot") + changes = {} + with open(os.path.join(directory, "changes.tsv"), encoding="utf-8") as handle: + for line in handle.read().splitlines(): + parts = line.split("\t") + if (len(parts) != 4 or parts[0] not in ("A", "M", "D") or not HEX40.match(parts[2]) + or not HEX40.match(parts[3])): + bad("changes.tsv has a line that is not TAB TAB TAB ") + if not RENDER_SET.match(parts[1]): + bad("%s is outside the render set" % parts[1]) + changes[parts[1]] = parts[0] + root = os.path.join(directory, "images") + staged = set() + for top, _dirs, files in os.walk(root): + for name in files: + staged.add(os.path.relpath(os.path.join(top, name), root).replace(os.sep, "/")) + for path in sorted(staged): + if changes.get(path) not in ("A", "M"): + bad("images/%s has no A or M line" % path) + recomputed = [] + for path, status in sorted(changes.items()): + if status == "D": + recomputed.append("%s\t0\t-" % path) + continue + if path not in staged: + bad("images/%s is missing" % path) + with open(os.path.join(root, path), "rb") as handle: + recomputed.append("%s\t1\t%s" % (path, sha(handle.read()))) + with open(os.path.join(directory, "files"), encoding="utf-8") as handle: + listed = handle.read().splitlines() + if sorted(row.split("\t")[0] for row in listed) != sorted(changes): + bad("files and changes.tsv name different paths") + if listed != recomputed: + bad("files differs from the rows its images give") + with open(os.path.join(directory, "not_after"), encoding="utf-8") as handle: + not_after = handle.read().strip() + if not NUMBER.match(not_after): + bad("not_after is not epoch seconds") + return snap, changes, recomputed, int(not_after) + + +def commit(args): + o, rest = options(args, values=("--write-id", "--generation", "--lane", "--verb", + "--args-sha256", "--workstation"), positional=1) + for key in ("--write-id", "--generation", "--lane", "--verb", "--args-sha256", "--workstation"): + if key not in o: + usage("register commit needs %s" % key) + if not UUID.match(o["--write-id"]) or not UUID.match(o["--generation"]): + usage("--write-id and --generation are lowercase UUIDs") + if not HEX64.match(o["--args-sha256"]): + usage("--args-sha256 is 64 lowercase hex") + return lambda: commit_run(o, rest[0]) + + +def commit_run(o, directory): + snap, changes, files, not_after = attempt(directory, o) + ident = (o["--lane"], o["--verb"], o["--args-sha256"]) + with Locked() as state: + if o["--generation"] != state["generation"]: + refuse(2, "LR007", "the write's generation is not the register's", "generation") + entry = state["journal"].get(o["--write-id"]) + if entry is not None: + if not identity(entry, *ident): + refuse(2, "LR007", "the write id belongs to another write", "another-write") + return Exit(0, "already %d\n" % entry["seq"] + + "".join("file=%s\n" % row for row in entry["files"])) + if snap.get("n") != str(state["n"]): + refuse(75, "LR001", "the head moved since the snapshot") + if int(time.time()) > not_after: + refuse(75, "LR008", "the attempt reached its not_after") + seq = state["n"] + 1 + shutil.copytree(os.path.join(REGISTER, str(state["n"])), os.path.join(REGISTER, str(seq))) + for path, status in changes.items(): + target = os.path.join(REGISTER, str(seq), path) + if status == "D": + if os.path.exists(target): + os.remove(target) + continue + os.makedirs(os.path.dirname(target), exist_ok=True) + shutil.copyfile(os.path.join(directory, "images", path), target) + repos = os.path.join(directory, "tree", "lanes", "repos.tsv") + if os.path.isfile(repos): + shutil.copyfile(repos, os.path.join(REGISTER, "%d.repos.tsv" % seq)) + state["journal"][o["--write-id"]] = { + "seq": seq, "lane": ident[0], "verb": ident[1], "args_sha256": ident[2], + "workstation": o["--workstation"], "generation": state["generation"], "files": files} + state["n"] = seq + return Exit(0, "committed %d\n" % seq) + + +def journal(args): + o, _ = options(args, values=("--write-id", "--not-after", "--generation", "--lane", "--verb", + "--args-sha256", "--clock", "--clock-age")) + for key in ("--write-id", "--not-after", "--generation", "--lane", "--verb", "--args-sha256"): + if key not in o: + usage("journal --write-id needs %s" % key) + if ("--clock" in o) != ("--clock-age" in o): + usage("--clock and --clock-age go together") + if not UUID.match(o["--write-id"]) or not UUID.match(o["--generation"]): + usage("--write-id and --generation are lowercase UUIDs") + if not HEX64.match(o["--args-sha256"]): + usage("--args-sha256 is 64 lowercase hex") + for key in ("--not-after", "--clock", "--clock-age"): + if key in o and not NUMBER.match(o[key]): + usage("%s takes whole seconds" % key) + return lambda: journal_run(o) + + +def journal_run(o): + with Locked() as state: + if o["--generation"] != state["generation"]: + refuse(2, "LR007", "the write's generation is not the register's", "generation") + entry = state["journal"].get(o["--write-id"]) + if entry is None: + return Exit(0, "absent\n") + if not identity(entry, o["--lane"], o["--verb"], o["--args-sha256"]): + refuse(2, "LR007", "the write id belongs to another write", "another-write") + return Exit(0, "found %d\n" % entry["seq"] + + "".join("file=%s\n" % row for row in entry["files"])) + + +def epoch(utc, module): + # ``: the stamp in epoch seconds, `-` where there is none or it + # cannot be a time, by the checkout's register_utc_epoch where it has one. + if not utc: + return "-" + reader = getattr(module, "register_utc_epoch", None) + if reader is not None: + value = reader(utc) + return "-" if value is None else str(value) + form = "%Y-%m-%dT%H:%M:%SZ" if utc.count(":") == 2 else "%Y-%m-%dT%H:%MZ" + try: + stamp = datetime.datetime.strptime(utc, form) + except ValueError: + return "-" + return str(int(stamp.replace(tzinfo=datetime.timezone.utc).timestamp())) + + +def five_fields(module): + # The checkout's own classify_register_line where it has one (lane 1's + # T122); before it, the five fields as CLI4.10:636 defines them, from the + # checkout's own REGISTER_KIND_RE, REGISTER_SLOTS where it has them, and + # parse_register_line's repository, UTC and lane: never a second copy of + # the classifier (CLI4.5:633). + one = getattr(module, "classify_register_line", None) + if one is not None: + return one + slots = getattr(module, "REGISTER_SLOTS", {}) + + def fields_of(line): + m = module.REGISTER_KIND_RE.match(line) + if not m: + return ("-", "-", "-", "-", "-") + kind = m.group(1) + fields = module.parse_register_line(line) or {} + return (kind, (slots.get(kind) or (None, None))[0] or "-", fields.get("repo") or "-", + epoch(fields.get("utc"), module), fields.get("lane") or "-") + return fields_of + + +def classify(args): + # Section 3.5 as contract draft 4.10 states it (CLI4.10:629-638; lane 1, + # #165 6752238370): one LF-ended line per LF-cut input line, `` TAB + # `` TAB `` TAB `` TAB ``, each `-` + # where absent. Any argument is 64, before stdin is read. + options(args) + + def run(): + loader = importlib.machinery.SourceFileLoader("lanes_index_classifier", LANES_INDEX_SOURCE) + spec = importlib.util.spec_from_loader(loader.name, loader) + module = importlib.util.module_from_spec(spec) + loader.exec_module(module) + one = five_fields(module) + decode = getattr(module, "_decode", None) or ( + lambda raw: raw.decode("utf-8", "surrogateescape")) + lines = sys.stdin.buffer.read().split(b"\n") + if lines[-1] == b"": + lines.pop() + return Exit(0, "".join("\t".join(one(decode(raw))) + "\n" for raw in lines)) + return run + + +def suffix(key): + # Section 3.6's file name for a log key: the key, or `%` outside the + # class (O18). + return key if LANE_CLASS.match(key) else "%" + key.encode("utf-8").hex() + + +def resolve(key, files): + want = ("lanes/log/%s.md" % key).lower() + hits = sorted(path for path in files if path.lower() == want) + return hits + + +def row(text): + # A `.head` row's present flag and digest: `1` and its sha256, or `0` and + # `-` where the path is absent at `n` (CLI4.10:699 and :703). + return ("0", "-") if text is None else ("1", sha(text)) + + +def logs_at(files): + return sorted(path for path in files if path.startswith("lanes/log/")) + + +def write_members(cache, members, files, head_rows, absent): + # Each member at `n`, and its `.head` rows: one per path it names, present + # or not (CLI4.10:699, :703). `logs` is `--all`'s set of logs, one row per + # log it holds at `n`, its text cached or not (CLI4.11:703, S-a). + for member in members: + if member == "register": + text = files.get("lanes/LANES.md") + put(cache + ".register", (text or b"").rstrip(b"\n") + b"\n") + head_rows["lanes/LANES.md"] = row(text) + elif member == "paths": + # Never `lanes/STORE` (CLI4.11:680): the stub's register holds the + # render set alone. + put(cache + ".paths", "".join(path + "\n" for path in sorted(files)).encode()) + elif member == "archive": + names = sorted(path for path in files if path.startswith("lanes/archive/")) + put(cache + ".archive", b"".join(files[path] for path in names)) + for path in names: + head_rows[path] = row(files[path]) + elif member == "aliases": + text = files.get("lanes/aliases.tsv") + put(cache + ".aliases", text if text else b"# no lane aliases\n") + head_rows["lanes/aliases.tsv"] = row(text) + elif member == "logs": + for path in logs_at(files): + head_rows[path] = row(files[path]) + else: + key = member[len("log:"):] + hits = resolve(key, files) + if len(hits) > 1: + continue + text = files[hits[0]] if hits else b"" + put(cache + ".log." + suffix(key), text) + put(cache + ".logpath." + suffix(key), (hits[0] + "\n").encode() if hits else b"") + if not LANE_CLASS.match(key): + continue + if hits: + head_rows[hits[0]] = row(text) + elif key not in absent: + absent.append(key) + + +def write_head(cache, state, n, head_rows, absent, logs_set): + lines = ["format=1", "n=%d" % n, "generation=%s" % state["generation"], "c=%d" % C, + "n_a=%d" % N_A, "w_s_ms=%d" % W_S_MS] + lines += ["file=%s\t%s\t%s" % ((path,) + head_rows[path]) for path in sorted(head_rows)] + lines += ["absent=%s" % key for key in absent] + data = "".join(line + "\n" for line in lines).encode() + put(cache + ".head", data) + # Whether this family holds `--all`'s set of logs: the stub's own record, + # beside the stub, never in the family, and true only for this `.head`. + try: + with open(SETS, encoding="utf-8") as handle: + sets = json.load(handle) + except FileNotFoundError: + sets = {} + sets[os.path.abspath(cache)] = {"head": sha(data), "logs": bool(logs_set)} + with open(SETS + ".tmp", "w", encoding="utf-8") as handle: + json.dump(sets, handle) + os.replace(SETS + ".tmp", SETS) + + +def holds_logs(cache): + try: + with open(SETS, encoding="utf-8") as handle: + record = json.load(handle).get(os.path.abspath(cache)) + with open(cache + ".head", "rb") as handle: + current = sha(handle.read()) + except (OSError, ValueError): + return False + return bool(record and record["head"] == current and record["logs"]) + + +def read_head(cache): + try: + with open(cache + ".head", encoding="utf-8") as handle: + text = handle.read().splitlines() + except OSError: + return None + head = {"rows": {}, "absent": []} + for line in text: + key, _eq, value = line.partition("=") + if key == "file": + path, present, digest = value.split("\t") + head["rows"][path] = (present, digest) + elif key == "absent": + head["absent"].append(value) + else: + head[key] = value + return head + + +def members_of(o, files): + if "--all" in o: + return ["register", "paths", "archive", "aliases", "logs"] + [ + "log:" + name for name in all_logs(files)] + members = o["--files"].split(",") + for member in members: + if member in ("register", "paths", "archive", "aliases"): + continue + if member.startswith("log:") and LANE_CLASS.match(member[len("log:"):]): + continue + usage("--files takes register, paths, archive, aliases and log: for a key in " + "check_lane_name's class, not %s" % member) + return members + + +def all_logs(files): + # `--all`'s logs: each `lanes/log/.md` whose `` is in the class. + names = [path[len("lanes/log/"):-len(".md")] for path in logs_at(files)] + return [name for name in names if LANE_CLASS.match(name)] + + +def cached_members(cache): + directory, base = os.path.split(cache) + found = [] + for name in ("register", "paths", "archive", "aliases"): + if os.path.exists(cache + "." + name): + found.append(name) + for name in sorted(os.listdir(directory or ".")): + if name.startswith(base + ".log.") and LANE_CLASS.match(name[len(base + ".log."):]): + found.append("log:" + name[len(base + ".log."):]) + return found + + +def read(args): + o, _ = options(args, values=("--for", "--cache", "--files", "--pid", "--repo", "--at", + "--since"), + equals=("--lane", "--log-key"), flags=("--prefetch", "--all")) + has = set(o) + if o.get("--for") not in (None, "guard"): + usage("--for takes guard") + if "--cache" not in o: + usage("register read needs --cache ") + for key in ("--pid", "--at", "--since"): + if key in o and not NUMBER.match(o[key]): + usage("%s takes a whole number" % key) + if has <= {"--prefetch", "--cache", "--files", "--all"} and "--prefetch" in has: + if ("--files" in has) == ("--all" in has): + usage("form 1 takes --files or --all") + form = 1 + elif has <= {"--for", "--prefetch", "--cache", "--pid", "--repo", "--lane"} and \ + {"--for", "--prefetch", "--pid", "--repo"} <= has: + form = 2 + elif has <= {"--since", "--cache", "--files", "--log-key"} and "--since" in has and \ + ("--files" in has or "--log-key" in has): + form = 3 + elif has == {"--for", "--at", "--pid", "--cache", "--lane"}: + form = 4 + else: + usage("not one of register read's four forms (section 3.6)") + if form in (2, 4) and o.get("--lane") == "": + usage("an empty --lane= key") + if o.get("--log-key") == "": + usage("an empty --log-key= key") + if "--files" in o: + members_of(o, {}) + return lambda: read_run(o, form) + + +def two_logs(key): + raise Exit(69, "mode primary\n", "lanes-index: register read: two logs differ from %s " + "only by case\n" % key) + + +def read_run(o, form): + cache = o["--cache"] + with Locked() as state: + n = state["n"] + if form == 4: + head = read_head(cache) + at = int(o["--at"]) + if head is None or head.get("generation") != state["generation"]: + raise Exit(69, "mode primary\n", "lanes-index: register read: the cache's .head " + "is missing or names another generation\n") + if at > n or at < state["first"]: + raise Exit(69, "mode primary\n", "lanes-index: register read: seq %d is not in " + "this generation's journal\n" % at) + files = images(at) + key = o["--lane"] + if len(resolve(key, files)) > 1: + two_logs(key) + write_members(cache, ["log:" + key], files, {}, []) + return Exit(0, "mode primary\n") + files = images(n) + if form in (1, 2): + if form == 1: + members = members_of(o, files) + else: + members = ["register", "aliases"] + if o.get("--lane") and LANE_CLASS.match(o["--lane"]): + members.append("log:" + o["--lane"]) + head_rows, absent = {}, [] + write_members(cache, members, files, head_rows, absent) + write_head(cache, state, n, head_rows, absent, "logs" in members) + return Exit(0, "mode primary\n") + return form_3(o, cache, state, n, files) + + +def form_3(o, cache, state, n, files): + # Form 3 as draft 4.10 and 4.11 state it (CLI4.10:730-733; CLI4.11:673): + # the CACHED paths changed in (n, n'] by their digests at n'; 69 only for + # a key the call asked for; a cached member that now matches two logs is + # dropped from the family. + asked = members_of(o, files) if "--files" in o else [] + if "--log-key" in o: + asked.append("log:" + o["--log-key"]) + asked_keys = [m[len("log:"):] for m in asked if m.startswith("log:")] + for key in asked_keys: + if len(resolve(key, files)) > 1: + two_logs(key) + since = int(o["--since"]) + head = read_head(cache) + logs_set = holds_logs(cache) + cached = cached_members(cache) + whole = (head is None or head.get("n") != str(since) + or head.get("generation") != state["generation"] + or not state["first"] <= since <= n) + changed = set() + if not whole: + before = images(since) + moved = set(before) ^ set(files) + for path, kept in head["rows"].items(): + if row(files.get(path)) != kept: + changed.add(path) + if "paths" in cached: + changed |= moved + if "archive" in cached: + changed |= {path for path in moved if path.startswith("lanes/archive/")} + if logs_set: + changed |= {path for path in moved if path.startswith("lanes/log/")} + for key in head["absent"]: + changed.update(resolve(key, files)) + dropped = [] + for member in cached: + key = member[len("log:"):] + if member.startswith("log:") and key not in asked_keys and len(resolve(key, files)) > 1: + try: + with open(cache + ".logpath." + key, encoding="utf-8") as handle: + dropped.append((key, handle.read().strip())) + except OSError: + dropped.append((key, "")) + for name in (".log.", ".logpath."): + if os.path.exists(cache + name + key): + os.remove(cache + name + key) + gone = {key for key, _path in dropped} + refetch = whole or bool(changed) + if refetch: + family = [m for m in cached if not (m.startswith("log:") and m[len("log:"):] in gone)] + if logs_set: + family += ["logs"] + ["log:" + name for name in all_logs(files)] + head_rows, absent = {}, [] + write_members(cache, family + asked, files, head_rows, absent) + else: + head_rows = {path: kept for path, kept in head["rows"].items() + if path not in {old for _key, old in dropped}} + absent = [key for key in head["absent"] if key not in gone] + write_members(cache, asked, files, head_rows, absent) + write_head(cache, state, n, head_rows, absent, logs_set) + out = ["mode primary", "n=%d" % n] + ["changed=%s" % path for path in sorted(changed)] + out.append("refetched=%d" % (1 if refetch else 0)) + return Exit(0, "".join(line + "\n" for line in out)) + + +def render(args): + # Section 3.7: the record of the fork's argv and environment, and the + # flipped build's answer, which the detached caller never reads. + options(args, values=("--checkout",)) + return lambda: render_run(args) + + +def render_run(args): + env = {k: ("*" if SECRET.search(k) else v) for k, v in sorted(os.environ.items())} + with open(RENDERS, "a", encoding="utf-8") as handle: + fcntl.flock(handle, fcntl.LOCK_EX) + handle.write(json.dumps({"argv": ["render"] + args, "env": env}) + "\n") + return Exit(69, "", "lanes-index: render: git half not installed\n") + + +def route(argv): + # The handler of a call this stub answers, its argv checked now (64), or + # None for a form it does not answer unless a test injects one. + words = argv[:2] + if argv[:1] == ["mode"]: + if argv[1:]: + usage("mode takes no argument") + return lambda: Exit(0, "primary\n") + if words == ["register", "snapshot"]: + if any(a in ("--files", "--all", "--out") for a in argv[2:]): + return None + return snapshot(argv[2:]) + if words == ["register", "commit"]: + return commit(argv[2:]) + if argv[:1] == ["journal"] and "--write-id" in argv[1:]: + return journal(argv[1:]) + if words == ["register", "classify"]: + return classify(argv[2:]) + if words == ["register", "read"]: + return read(argv[2:]) + if argv[:2] == ["render", "--checkout"]: + return render(argv[1:]) + return None + + +def injected(argv): + try: + with open(OUTCOMES, encoding="utf-8") as handle: + outcomes = json.load(handle) + except FileNotFoundError: + return None + for outcome in reversed(outcomes): + if argv[:len(outcome["argv"])] == outcome["argv"]: + return outcome + return None + + +def main(argv): + with open(ARGV_LOG, "a", encoding="utf-8") as handle: + fcntl.flock(handle, fcntl.LOCK_EX) + handle.write(json.dumps(argv) + "\n") + try: + handler = route(argv) + outcome = injected(argv) + if outcome is not None: + if outcome.get("committed") and handler is not None: + try: + handler() + except Exit: + pass + if outcome.get("hang"): + time.sleep(float(outcome["hang"])) + raise Exit(int(outcome.get("exit") or 0), outcome.get("stdout") or "", + outcome.get("stderr") or "") + if handler is None: + usage("the contract stub does not answer %s; inject an outcome" % json.dumps(argv)) + raise handler() + except Exit as end: + sys.stdout.write(end.out) + sys.stderr.write(end.err) + return end.code + + +sys.exit(main(sys.argv[1:])) +''' + + +def contract_stub(directory, register=None) -> Path: + """Write `/lanes-index`, the contract's stub `lanes-index` + (T207; CLI4.5 §6, CLI4.5:881-903), and return its path: a Python script + with a `#!/usr/bin/env python3` line and the executable bit, which a test + runs by its path (R2's S8). `directory` is made if it is missing. + + THE COPY RULE (CLI4.5 §6, CLI4.5:885; O11): a test copies `lanes-edit.sh`, + `repos.tsv` and `lane-start` beside the stub, where `lanes_index_bin` looks + first, `$SCRIPT_DIR/lanes-index`. + + ITS REGISTER: the render set's files at each seq, under + `/lanes-index.register//`; its head, its generation and its + journal in `/lanes-index.state`. Called again on one + directory, it starts a new register and moves the old one aside. The head starts at seq 1, the + generation's first, holding `register`, a mapping of render-set paths + (`lanes/LANES.md`, `lanes/aliases.tsv`, `lanes/log/.md`, + `lanes/archive/`) to their text, empty by default. The generation + is a new UUID. Each `register commit` that commits makes the next seq. + + WHAT IT ANSWERS, by CLI4.5's sections; every other end is a test's to + inject with `stub_outcome`: + + - §3.1 `mode`: `primary`, 0; with any argument, 64. + - §3.2 `register snapshot`: the argv's forms, each other form 64 (an id + without `--generation`, `--at` without it, `--tree` without + `--checkout`); check 1, the generation, 2 with `ERROR: LR007: …` and + `DETAIL: generation`; check 2, the id found with its lane, verb and + `args_sha256`, 0 with `found=` and its `file=` rows; check 2′, the id + another write's, 2 with `DETAIL: another-write`; then the `key=value` + lines in §3.2's order, the id minted for `--write-id new`, `not_after=` + the clock plus `C` plus 2 s. `--tree --checkout ` builds the + scratch tree from the stub's register at `n` (or at `--at `), with + `lanes/repos.tsv` and `lanes/log/README.md` from ``'s `origin/main`, + one commit and `refs/remotes/origin/main` on it, and prints + `repos_blob=`. Under `--at` only the generation is checked, and a seq + outside the generation's journal is 69. `--files`, `--all` and `--out` + (§3.6's image form) are not answered. + - §3.3 `register commit`: the argv, each flag required (64); the attempt + directory's check, 2 with `lanes-index: attempt directory: ; + nothing was sent` (a listed file missing, an image with no `A` or `M` + line, `files` and `changes.tsv` naming different paths, `files` + differing from the images' rows, the flags differing from `snapshot`, a + path outside the render set); then LR007 `generation` and + `another-write` (2), LR006 (0, `already ` and its `file=` rows), + LR001 where `snapshot`'s `n=` is not the head (75), LR008 past + `not_after` (75), and otherwise `committed `, 0. + - §3.4 `journal --write-id …`: the argv (64); LR007 `generation` and + `another-write` (2); `found ` with its `file=` rows, or `absent`, + 0. It answers at once: the wait and the window are the real + `journal`'s, and LR011 and the lookup's 3s are injected. + - §3.5 `register classify`, as contract draft 4.10 states it + (CLI4.10:629-638; lane 1, #165 6752238370), not CLI4.5:636's four + fields: one LF-ended line per LF-cut input line, five TAB-separated + fields, ``, ``, ``, `` (epoch + seconds) and ``, each `-` where absent; any argument 64, before + stdin is read. The fields are the checkout's own: its + `classify_register_line` (lane 1's T122) where `LANES_INDEX` has one, + and before it CLI4.10:636's fields from its `REGISTER_KIND_RE`, + `REGISTER_SLOTS` (T118) where it has them, and `parse_register_line`, + so the stub holds no second classifier (CLI4.5:633). A test teaches + other fields with `stub_outcome`. + - §3.6's four forms of `register read`, as contract draft 4.10 and + draft 4.11 state them (lane 1, #165 6752925109), each form's argv (an + empty `--lane=` 64 in forms 2 and 4; `--lane` and `--log-key` only in + the `=` form): the first stdout line `mode primary`; the cache family + written by temp file and rename beside `--cache `, `.head` last; + a key outside `check_lane_name`'s class as `.log.%`, never cached; + two logs that differ only by case written by no form; form 4's `.head` + checks (69 where it is missing, names another generation, or `--at` is + outside the journal), its one log at `--at`, and no `.head`. + `.outage`, `.direct` and the guard's "too late" are injected. + - `.head`'s rows (CLI4.10:699, :703; CLI4.11:703, S-a): a `file=` row + for every path a member names at `n`, present or not, `1` and its + digest or `0` and `-`; a set member (`archive`, and `--all`'s logs) + one row per file it holds at `n`, its text cached or not, a log + outside the class or one of a case pair included; a `log:` that + resolves to no log an `absent=` row instead. + - `.paths` never holds `lanes/STORE` (CLI4.11:680): the register holds + the render set alone. + - Form 3 (CLI4.10:730-733): the cached paths changed in `(n, n′]` by + their digests at `n′` (a row whose digest differs or is absent, a + path created or removed against a cached `.paths` or under a cached + set member, an `absent=` key that now resolves), printed as `n=`, + one `changed=` per path, sorted, and `refetched=0` or `1`; + where any is found, or `.head` is missing or names another `n` or + generation, the whole family rewritten at `n′`, `.head` last; + otherwise the members `--files` names, with their rows added. It + exits 69 only for a key it was asked for, by `--files` or + `--log-key=`; a cached member that now matches two logs is dropped + from the family, its `.log.` and `.logpath.` removed + (CLI4.11:673, N-g). Whether a family holds `--all`'s set of logs is + the stub's own record, `lanes-index.sets` beside the stub, true only + for the `.head` it wrote with it. + - §3.7 `render --checkout `: one JSON line per call in + `/lanes-index.render`, its argv and its environment (the + value of a variable whose name holds TOKEN, SECRET, PASSWORD, PASSWD or + KEY recorded as `*`), and "git half not installed" on stderr, 69. + - Anything else: 64, unless a test injects an outcome for it. + + Every call is logged to `/lanes-index.argv`, one JSON array of + its arguments per line (lane 4's M9).""" + directory = Path(directory) + directory.mkdir(parents=True, exist_ok=True) + old = directory / "lanes-index.register" + if old.exists(): + old.rename(directory / f"lanes-index.register.old-{time.time_ns()}") + seed = directory / "lanes-index.register" / "1" + seed.mkdir(parents=True, exist_ok=True) + for path, text in (register or {}).items(): + if not RENDER_SET_PATH.match(path): + raise ValueError(f"contract_stub: {path} is not a render-set path") + target = seed / path + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(text.encode("utf-8") if isinstance(text, str) else text) + state = {"generation": str(uuid.uuid4()), "n": 1, "first": 1, "journal": {}} + (directory / "lanes-index.state").write_text(json.dumps(state), encoding="utf-8") + stub = directory / "lanes-index" + here = str(directory.resolve()) + text = _CONTRACT_STUB.replace("STUB_DIRECTORY", repr(here), 1) + text = text.replace("LANES_INDEX_PATH", repr(str(LANES_INDEX)), 1) + stub.write_text(text, encoding="utf-8") + stub.chmod(0o755) + return stub + + +def stub_outcome(directory, argv_prefix, exit=None, stdout=None, stderr=None, committed=False, + hang=None) -> None: + """Inject an outcome into the contract stub in `directory`: every later + call whose arguments begin with `argv_prefix` (a string of words, such as + `"register commit"`, or a list) ends with `exit` (0 where only output is + given), printing `stdout` and `stderr`. The last injected outcome whose + prefix matches answers, after the call's argv has been checked (64 still + comes first). + + - `committed=True`: the call first does what it would, its own answer + dropped, as "committed, then exit 3", agreement test 12's pair. + - `hang=`: it sleeps first, a hang past the caller's timer. + - Each LR code is its `exit` with `stderr` in §2.6's shape, such as + `"ERROR: LR005: \\nDETAIL: main-held\\n"` with 2. + - On `journal --write-id`, a crash (`exit=1`, a traceback on stderr) and an + unknown code (any other) are the caller's to read as 3 (CO-2). + + Called with no outcome (no `exit`, `stdout`, `stderr` or `hang`), it + removes the outcomes injected for that prefix.""" + words = argv_prefix.split() if isinstance(argv_prefix, str) else list(argv_prefix) + path = Path(directory) / STUB_OUTCOMES + outcomes = json.loads(path.read_text(encoding="utf-8")) if path.exists() else [] + if exit is None and stdout is None and stderr is None and hang is None: + outcomes = [o for o in outcomes if o["argv"] != words] + else: + outcomes.append({"argv": words, "exit": exit, "stdout": stdout, "stderr": stderr, + "committed": bool(committed), "hang": hang}) + tmp = path.with_name(path.name + ".tmp") + tmp.write_text(json.dumps(outcomes), encoding="utf-8") + os.replace(tmp, path) + + +# ------------------------------------------------ the guard's session (T203c) +# +# WHY: lane 5's T507 prefetch reads the register AFTER the guard's own +# checks, and each of them refuses with 2 (lane 5, #165 6755266457; F10's +# items 27 and 28). In `guard_run` at `a2073eae` (`lanes-edit.sh:10922`), in +# order: the subagent and `cwd` reads of the hook's JSON (`jstr`, which reads +# only the compact `"key":"value"`); the scope test against +# `${PROJECTS_ROOT:-$HOME/projects}` (`:10939`), which returns 0 outside it; +# the workspace check (`LANES_REPO`, `LANES_DIR`, `LANES_FILE`, `:10948`); the +# tmux checks (`here_context`'s `display-message -p +# '#{session_name}:#{window_id}'` and `'#{pane_pid}'`, `:10954`, then `'#W'`, +# `:10964`); and this workstation's session records, `transcript_holders +# "$G_ID"` (`:10986`), which needs a live record whose `sessionId` is the +# hook's `session_id` and whose window is this one, or it refuses "no live +# session record in THIS window" (`:11010`). Only then comes the register's +# text (`register_text`, `:11049`), the guard's first register read. Lane 5's +# `refs/l5/T502` changes the offer site, not these checks. + +#: THE VARIABLES THAT WOULD STEER THE GUARD AWAY FROM A CASE'S OWN ESTATE, by +#: the prefixes of their names: the lane's own (`LANES_`, among them +#: `LANES_REPO` and `LANES_INDEX_CONFIG`), the harness's (`CLAUDE_`, among +#: them `CLAUDE_CODE_SESSION_ID` and `CLAUDE_NO_LANE`), tmux's, libpq's and +#: the fake's; `PROJECTS_ROOT`, which moves the scope test's root off +#: `$HOME/projects` so the guard returns 0 before any read (T220c's note, +#: F10's item 28); and `AGENT_PROTOCOL_ROOT`, which moves `workspace.yaml` off +#: `$HOME/.agents` (`lanes-edit.sh:785`). +GUARD_ENV_STRIP = ("LANES_", "CLAUDE_", "TMUX", "PG", "FAKE_PSQL", "PROJECTS_ROOT", + "AGENT_PROTOCOL_ROOT") + +#: The stand-in's window, in the form the suite's session records carry +#: (`testsess:@1.%1`, `tests/test_supervised_restart_regressions.py`), and +#: `TMUX_PANE` as T215's and T220's benches set it; the window's name is the +#: lane's, `repoA-2` there. +GUARD_WINDOW = "repoA-2" +GUARD_TMUX_SESSION = "testsess" +GUARD_WINDOW_ID = "@1" +GUARD_PANE = "%1" +#: The stand-in's call log, beside it. +GUARD_TMUX_LOG = "tmux.log" + +#: THE STAND-IN `tmux`, in the form of T215's and T220's `FAKE_TMUX` (a +#: `#!/bin/sh` that answers `display-message` as the lane's window and exits +#: 0 to the rest), with each query the guard makes answered as a real tmux +#: answers it, and every call logged. The `@…@` words are filled in, each +#: quoted for the shell, by `guard_session`. +_GUARD_TMUX = r'''#!/bin/sh +# A STAND-IN tmux (feature 007, T203c): it logs every call, each argument +# ended by US (0x1f), one call per line, and answers display-message as the +# lane's window does. A target that is not that window gets tmux's own +# "can't find window" and 1. Every other command is answered with nothing +# and 0. +{ for a in "$@"; do printf '%s\037' "$a"; done; printf '\n'; } >> @LOG@ +[ "${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 SESSION'S LIVE PROCESS: it reads its stdin to the end, so it lives +#: until `GuardSession.close` closes that pipe, or the test's process dies. +_GUARD_HOLDER = "import sys; sys.stdin.buffer.read()" + + +def _sh(value) -> str: + """`value` quoted for the shell, as one word.""" + return "'" + str(value).replace("'", "'\\''") + "'" + + +def _proc_start(pid) -> str: + """The start token the guard compares, field 22 of `/proc//stat`, + cut after the last `) ` as `pid_alive` cuts it (`lanes-edit.sh:5154`). + 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 guard_strip_env(environ=None, strip=()) -> dict: + """A copy of `environ` (`os.environ` where it is None) without each + variable whose name begins with a prefix in `GUARD_ENV_STRIP`, or in + `strip`, a module's own (T215's `T215_`, for one).""" + prefixes = tuple(GUARD_ENV_STRIP) + tuple(strip) + source = os.environ if environ is None else environ + return {k: v for k, v in source.items() if not k.startswith(prefixes)} + + +class GuardSession: + """A live session for a guard case, made by `guard_session`, whose + docstring is its manual.""" + + def __init__(self, home, directory, cwd, window, session_id, name, name_source, + status, proc_start): + self.home, self.directory, self.cwd = Path(home), Path(directory), Path(cwd) + self.window, self.session_id = window, session_id + self.target = f"{GUARD_TMUX_SESSION}:{GUARD_WINDOW_ID}.{GUARD_PANE}" + self.directory.mkdir(parents=True, exist_ok=True) + self.holder = subprocess.Popen([sys.executable, "-I", "-c", _GUARD_HOLDER], + stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, start_new_session=True) + self.pid = self.holder.pid + self.proc_start = _proc_start(self.pid) if proc_start is None else str(proc_start) + self.tmux_env = f"{self.directory / 'tmux-server'},{self.pid},0" + self.tmux_log = self.directory / GUARD_TMUX_LOG + self.tmux = self.directory / "tmux" + words = {"@LOG@": _sh(self.tmux_log), "@SESSION@": _sh(GUARD_TMUX_SESSION), + "@ID@": _sh(GUARD_WINDOW_ID), "@PANE@": _sh(GUARD_PANE), + "@PID@": _sh(self.pid), "@WINDOW@": _sh(window)} + text = _GUARD_TMUX + for word, value in words.items(): + text = text.replace(word, value) + self.tmux.write_text(text, encoding="utf-8") + self.tmux.chmod(0o755) + sessions = self.home / ".claude" / "sessions" + sessions.mkdir(parents=True, exist_ok=True) + self.record = sessions / f"{self.pid}.json" + self.record.write_text(json.dumps( + {"pid": self.pid, "sessionId": session_id, "cwd": str(self.cwd), + "procStart": self.proc_start, "tmux": self.target, "name": name, + "nameSource": name_source, "status": status, "kind": "interactive"}, + separators=(",", ":")) + "\n", encoding="utf-8") + self.record.chmod(0o600) + + def env(self, base, **extra) -> dict: + """`base`, a case's environment for the guard (see `guard_strip_env`), + with this session's window, `TMUX` and `TMUX_PANE`, and the stand-in's + directory first on `PATH` where it is not already. An `extra` value + of None removes that variable, as `TMUX=None` takes the session out + of any window; any other sets it.""" + env = dict(base) + env.update(TMUX=self.tmux_env, TMUX_PANE=GUARD_PANE) + path = env.get("PATH", os.defpath) + if path.split(os.pathsep)[0] != str(self.directory): + env["PATH"] = os.pathsep.join([str(self.directory), path]) + for key, value in extra.items(): + if value is None: + env.pop(key, None) + else: + env[key] = value + return env + + def hook_input(self, prompt="hello", cwd=None) -> str: + """The hook's JSON for this session, compact as the harness sends it, + since the guard's `jstr` reads `"":""` with no blank after + the colon: `hook_event_name`, `session_id`, `cwd` (this session's, + unless given) and `prompt`, in T215's and T220's order.""" + return json.dumps({"hook_event_name": "UserPromptSubmit", + "session_id": self.session_id, + "cwd": str(self.cwd if cwd is None else cwd), "prompt": prompt}, + separators=(",", ":")) + + def tmux_calls(self) -> list: + """Every call the stand-in `tmux` took, in order, each its list of + arguments.""" + if not self.tmux_log.exists(): + return [] + return [line.split("\x1f")[:-1] + for line in self.tmux_log.read_text(encoding="utf-8", + errors="replace").splitlines()] + + def close(self) -> None: + """End the session's process. Its record stays, naming a dead pid, so + the guard reads it as not live; the files stay for the test's + `tmp_path`. Safe to call twice.""" + holder = self.holder + if holder.stdin is not None and not holder.stdin.closed: + try: + holder.stdin.close() + except OSError: + pass + if holder.poll() is None: + try: + holder.wait(timeout=10) + except subprocess.TimeoutExpired: + holder.kill() + holder.wait(timeout=10) + + def __enter__(self): + return self + + def __exit__(self, *exc): + self.close() + return False + + +def guard_session(home, directory, cwd, *, window=GUARD_WINDOW, session_id=None, name=None, + name_source="user", status="busy", proc_start=None) -> GuardSession: + """Give a guard case a live session, so that `lanes-edit.sh guard` gets + past its session-record check to its register read, and return it as a + `GuardSession`. + + - `home`: the `HOME` the guard runs with. The record is written under it. + - `directory`: a directory the case puts first on `PATH` (its `bin`); the + stand-in `tmux` and its log are written there, replacing any `tmux` + the case wrote before. + - `cwd`: the lane's checkout, the hook's `cwd`. It must be under + `/projects`, or the guard's scope test returns 0 before any read + (T215b, T220c), and a `ValueError` says so. + - `window`: the window's name, the lane's (`GUARD_WINDOW`, `repoA-2`). + - `session_id`: the hook's `session_id` and the record's `sessionId`, in + lower case as the harness writes it (another is a `ValueError`); a new + uuid4 where None, so a case that writes a register row naming the + session passes its own. + - `name` and `name_source`: the record's `name` (the window's where None) + and `nameSource` (`user`, as `/rename` or `--name` gives it). + - `status`: the record's `status` (`busy`; `ended`, `exited`, `dead` or + `stopped` makes it not live). + - `proc_start`: the record's `procStart`; the live process's own start + token where None. Any other value forges a recycled pid, so the record + is not live. + + WHAT IT WRITES: + + - THE LIVE PROCESS: a child of the test (`GuardSession.pid`, `.holder`) + in a session of its own, a Python that reads its stdin to the end, so + it lives until `close()` or the test's process ends. + - THE RECORD, `/.claude/sessions/.json`, mode 0600, one line + of compact JSON in the suite's record form: `pid`, `sessionId`, `cwd`, + `procStart`, `tmux` (`testsess:@1.%1`), `name`, `nameSource`, `status` + and `kind` (`interactive`). The guard's `transcript_holders` finds it + by `"sessionId":""`, reads it live by `pid_alive` (`kill -0`, then + field 22 of `/proc//stat` equal to `procStart`), and here because + its `tmux` target names the window the stand-in answers for. + - THE STAND-IN, `/tmux`, logging each call to + `/tmux.log` (`tmux_calls()` reads it). `display-message + -p` answers `'#{session_name}:#{window_id}'` with `testsess:@1`, + `'#{session_name}'` with `testsess`, `'#{window_id}'` with `@1`, + `'#{pane_id}'` with `%1`, `'#{pane_pid}'` with the live pid, and any + other format (`'#W'` among them) with `window`, as T215's and T220's + `FAKE_TMUX` answers every one. A `-t` naming another window gets + "can't find window" and 1. Every other command: nothing, and 0. + + WHAT IT RETURNS: the `GuardSession`, with `session_id`, `window`, `pid`, + `proc_start`, `record`, `tmux`, `tmux_log`, `target`, `home`, + `directory` and `cwd`, and: + + - `env(base, **extra)`: `base` with `TMUX` (`/tmux-server, + ,0`), `TMUX_PANE` (`%1`) and `directory` first on `PATH`. Make + `base` with `guard_strip_env(os.environ, strip=(,))`, then set `HOME` to `home` and the case's own variables + (`LANES_REPO`, `LANES_INDEX_CONFIG`, `LANES_LANE`, ...); + - `hook_input(prompt="hello", cwd=None)`: the compact hook JSON, for the + guard's stdin; + - `tmux_calls()`: the stand-in's calls. + + TEARDOWN: `close()` (or a `with` block, or + `request.addfinalizer(session.close)`) ends the live process; the record + then names a dead pid, which the guard reads as no live session, and its + files stay in the case's `tmp_path`. Without a `close()`, the process + still ends when the test's process does, at the end of its stdin.""" + home, cwd = os.path.abspath(home), os.path.abspath(cwd) + projects = os.path.join(home, "projects") + if not (cwd + os.sep).startswith(projects + os.sep): + raise ValueError(f"guard_session: the checkout {cwd} is not under {projects}, so the " + f"guard's scope test would return 0 before any read") + session_id = str(uuid.uuid4()) if session_id is None else str(session_id) + if session_id != session_id.lower(): + raise ValueError(f"guard_session: the session id {session_id} is not in lower case; " + f"the guard lower-cases the hook's and greps the records for it") + return GuardSession(home, directory, cwd, window, session_id, + window if name is None else name, name_source, status, proc_start) diff --git a/tests/sql_register_landed/T200 b/tests/sql_register_landed/T200 new file mode 100644 index 00000000..e69de29b diff --git a/tests/sql_register_landed/T201 b/tests/sql_register_landed/T201 new file mode 100644 index 00000000..e69de29b diff --git a/tests/sql_register_landed/T203 b/tests/sql_register_landed/T203 new file mode 100644 index 00000000..e69de29b diff --git a/tests/sql_register_landed/T205 b/tests/sql_register_landed/T205 new file mode 100644 index 00000000..e69de29b diff --git a/tests/sql_register_landed/T206 b/tests/sql_register_landed/T206 new file mode 100644 index 00000000..e69de29b diff --git a/tests/sql_register_landed/T207 b/tests/sql_register_landed/T207 new file mode 100644 index 00000000..e69de29b diff --git a/tests/sql_register_landed/T280 b/tests/sql_register_landed/T280 new file mode 100644 index 00000000..e69de29b diff --git a/tests/test_repo_hygiene.py b/tests/test_repo_hygiene.py index d94d4cf0..d670318c 100644 --- a/tests/test_repo_hygiene.py +++ b/tests/test_repo_hygiene.py @@ -4626,3 +4626,52 @@ def test_the_suite_wrapper_takes_one_lock_and_names_it_where_agents_read_it(): by_hand = [ln for ln in agents.splitlines() if lock in ln and "python3 -m pytest" in ln] assert by_hand and all("-p no:cacheprovider" in ln and "PYTHONPYCACHEPREFIX=" in ln for ln in by_hand), by_hand + + +def test_no_workflow_sets_the_landing_gates_switch(): + """T280'S LANDING GATE DECIDES BY THE RUN, NOT BY A WORKFLOW (Brett's + "Temporary landing gate (Recommended)", 2026-11-13; lane 3's ruling on + when it is active). `tests/conftest.py` skips each 007 test whose tasks + have not all landed, but only in a GitHub Actions run whose workflow is + not `verify` and whose ref is not a `verify/` branch. It reads that from + `GITHUB_ACTIONS`, `GITHUB_WORKFLOW` and the run's ref. + `SQL_REGISTER_GATE=on` or `=off` is a person's override. + + A workflow that set the variable would decide for every run of that + workflow, whatever its ref. Set to `off`, a pull request's CI would run + 007 tests whose code has not landed. Set to `on`, a `verify/` branch, cut + from line R with no markers, would pass by the gate's skip. So no + workflow file names it, and none changes for the gate. + + A workflow file is not the only place that could set it for CI (lane 2's + review RV26, NIT 2). So the row reads every file under `.github/` but its + Markdown prose and bytecode: the workflows, any composite action, and the + launchers in `.github/ci/`, where `ci_shards.py` builds each shard's + environment, `sonar_coverage/sitecustomize.py` runs inside each Python + process of a coverage run and `sonar_coverage/bash-env.sh` is sourced by + its bash. It also reads `tests/run.sh`, which `tests.yml`'s + `guard-launch-mode` job runs and the tasks' verify commands call: set + there, the variable would decide every run of the wrapper, and a verify + could pass by the gate's skip. A comment line, whose first character other + than a blank is `#`, does not count, so a file may say why it never sets + the switch. T281 removes this row with the gate, in the last set.""" + github = REPO / ".github" + workflows = github / "workflows" + wrapper = REPO / "tests" / "run.sh" + files = sorted(path for path in github.rglob("*") + if path.is_file() and path.suffix != ".md" + and "__pycache__" not in path.relative_to(github).parts) + assert any(path.parent == workflows and path.suffix in (".yml", ".yaml") + for path in files), ( + f"no workflow file under {workflows}: this rule would hold of nothing") + assert wrapper.is_file(), f"no {wrapper}: this rule reads the suite's wrapper" + found = [f"{path.relative_to(REPO).as_posix()}:{number}" + for path in [*files, wrapper] + for number, line in enumerate( + path.read_text(encoding="utf-8", errors="replace").splitlines(), 1) + if "SQL_REGISTER_GATE" in line and not line.lstrip().startswith("#")] + assert not found, ( + "a file CI reads names SQL_REGISTER_GATE, which only a person sets: " + "the landing gate is active in an Actions run whose workflow is not " + "verify and whose ref is not a verify/ branch, and a file that set it " + "would gate or ungate every run that reads it (T280): " + ", ".join(found)) diff --git a/tests/test_sql_register_fixture.py b/tests/test_sql_register_fixture.py new file mode 100644 index 00000000..3c3f9c09 --- /dev/null +++ b/tests/test_sql_register_fixture.py @@ -0,0 +1,316 @@ +# SPDX-License-Identifier: Apache-2.0 +"""The real-engine fixture's switch, `OPENREPOTOOLS_REQUIRE_PG` (#165, L2-0b). + +THE TEST PLAN'S SECTION 3.3, ITS FOUR CASES. `tests/pgcluster.py` gives the +tests that need a real PostgreSQL 16 their cluster, and `tests/conftest.py` +registers it from its `pytest_configure`. The switch decides what a missing +engine is: + + * unset or `0`, a SKIP of every real-engine test, whose reason names + `PG_BIN` and the package `postgresql-16`, loud even under `-q`; + * `1`, as CI sets it, a REFUSAL of the whole run before any test starts: + pytest's own `UsageError`, exit 4, even where the run selects no + real-engine test (the refusal is eager); + * anything else, a refusal too, as `OPENREPOTOOLS_COMPOSED` refuses a + value that is neither. + +EACH CASE RUNS A CHILD PYTEST, since a refusal ends the session that makes it. +The child is `python -m pytest` on this suite's own `conftest.py`, with no +`OPENREPOTOOLS_*`, `PG*` or `PYTEST_ADDOPTS` of the outer run, and with only +what the case sets. Its real-engine test is a PROBE written into the case's +own temporary directory, which asks for `pg`, one database cloned from the +session's template: the suite holds no such test of its own until the +template's tasks land, and a case must not wait for one. + +A REAL-ENGINE TEST IS ONE WHOSE FIXTURE CLOSURE HOLDS `pg_engine`, the +session fixture through which every cluster of `tests/pgcluster.py` finds its +binaries, or skips, or fails. A test asks for `pg`, `pg_cluster`, +`stoppable_cluster` or a cluster built on them, and the closure pytest +computes from their definitions reaches `pg_engine`. So the last case reads +pytest's public `fixturenames`, and a cluster fixture added later is held to +the rule by depending on `pg_engine`, as each one must to find the binaries. + +Until `tests/conftest.py` registers the plugin, each case FAILS on its own +assertion: the probe's `pg` is a fixture nobody defines, so the child errors +where it should refuse or skip, and the filter's check cannot see the probe. +""" + +from __future__ import annotations + +import json +import os +import subprocess +import sys +import xml.etree.ElementTree as ElementTree +from pathlib import Path + +import pytest + +from conftest import REPO + +#: The variable, as `tests/pgcluster.py` and `tests.yml` spell it. +SWITCH = "OPENREPOTOOLS_REQUIRE_PG" + +#: THIS MODULE AND ITS SUITE: the child loads the `conftest.py` beside it. +THIS = Path(__file__).resolve() +SUITE = THIS.parent + +#: The fixture every cluster finds its binaries through. +ENGINE_FIXTURE = "pg_engine" + +#: THE `guard-launch-mode` JOB'S FILTER, as `tests.yml` runs it: +#: `bash tests/run.sh -k ''`. The job is the launch contract's own, +#: and a real-engine test it selected would turn it into a database job. +LAUNCH_JOB_FILTER = "guard_launch_mode or repo_hygiene" + +#: THE PROBE: one real-engine test, written by this module into a case's +#: temporary directory. Its function's name holds the launch job's first word, +#: so that job's filter selects it, and its module's name holds `PROBE_WORD`, +#: which selects it alone where a case runs it. +PROBE_MODULE = "test_engine_probe.py" +PROBE_TEST = "test_guard_launch_mode_sees_this_real_engine_probe" +PROBE_WORD = "engine_probe" +PROBE_SOURCE = f'''# A real-engine test, written by tests/test_sql_register_fixture.py. + + +def {PROBE_TEST}(pg): + assert pg.name +''' + +#: A PLUGIN FOR THE CHILD'S COLLECTION, loaded by `-p`: every item the +#: collection keeps, its path, and whether its fixture closure holds +#: `ENGINE_FIXTURE`, one JSON line each, in the file `$ENGINE_REPORT` names. +REPORTER_MODULE = "engine_report" +REPORTER_SOURCE = f'''import json +import os + + +def pytest_collection_finish(session): + with open(os.environ["ENGINE_REPORT"], "w", encoding="utf-8") as report: + for item in session.items: + names = getattr(item, "fixturenames", ()) + report.write(json.dumps({{"nodeid": item.nodeid, "path": str(item.path), + "engine": {ENGINE_FIXTURE!r} in names}}) + "\\n") +''' + + +def shown(proc: subprocess.CompletedProcess) -> str: + return (f"exit {proc.returncode}\n--- stdout ---\n{proc.stdout[-4000:]}" + f"\n--- stderr ---\n{proc.stderr[-4000:]}") + + +def write_probe(tmp_path: Path) -> Path: + directory = tmp_path / "probe" + directory.mkdir() + probe = directory / PROBE_MODULE + probe.write_text(PROBE_SOURCE, encoding="utf-8") + return probe + + +def no_engine(tmp_path: Path) -> Path: + """An empty directory for `PG_BIN`: a named `PG_BIN` is final, so it is a + missing engine on a host that has one, CI's runners among them.""" + directory = tmp_path / "no-engine" + directory.mkdir() + return directory + + +def child(tmp_path: Path, args: list, switch=None, pg_bin=None, + extra_env=None) -> subprocess.CompletedProcess: + """`python -m pytest -q` on `args`, from the case's temporary directory, + with `switch` and `pg_bin` as the only switch and `PG_BIN` it sees.""" + env = {key: value for key, value in os.environ.items() + if not key.startswith(("OPENREPOTOOLS_", "PG")) + and key not in ("PYTEST_ADDOPTS", "PYTEST_PLUGINS")} + env["PYTHONDONTWRITEBYTECODE"] = "1" + if switch is not None: + env[SWITCH] = switch + if pg_bin is not None: + env["PG_BIN"] = str(pg_bin) + env.update(extra_env or {}) + command = [sys.executable, "-m", "pytest", "-q", "-p", "no:cacheprovider", + f"--basetemp={tmp_path / 'child-basetemp'}", + f"--rootdir={SUITE.parent}", *args] + return subprocess.run(command, cwd=str(tmp_path), env=env, + capture_output=True, text=True, timeout=900, + check=False) + + +def probe_run(tmp_path: Path, probe: Path, *options: str, **kwargs): + """The probe alone: this module is collected beside it, so the child + loads this suite's `conftest.py`, and `-k` keeps only the probe.""" + return child(tmp_path, [*options, "-k", PROBE_WORD, str(THIS), str(probe)], + **kwargs) + + +def test_the_engine_switch_turns_a_missing_engine_into_a_failure(tmp_path): + """`OPENREPOTOOLS_REQUIRE_PG=1` with `PG_BIN` naming an empty directory: + pytest exits 4 before the probe runs, and says why, naming the switch and + the `PG_BIN` it could not use (section 3.3; the probe's b1, b8 and b9). + Exit 4 alone is not enough: a missing file is a usage error too.""" + empty = no_engine(tmp_path) + proc = probe_run(tmp_path, write_probe(tmp_path), switch="1", pg_bin=empty) + output = proc.stdout + proc.stderr + assert proc.returncode == 4, ( + f"{SWITCH}=1 with no engine must refuse the run, exit 4:\n{shown(proc)}") + assert f"{SWITCH}=1" in output and f"PG_BIN={empty}" in output, ( + f"the refusal names neither the switch nor the PG_BIN it could not " + f"use:\n{shown(proc)}") + assert PROBE_TEST not in output, f"the probe ran:\n{shown(proc)}" + + +def test_without_the_switch_a_missing_engine_skips_naming_pg_bin_and_postgresql_16( + tmp_path): + """The switch unset, and at `0`, with `PG_BIN` naming an empty directory: + the probe SKIPS, the run exits 0, and the skip's reason names `PG_BIN` + and the package `postgresql-16` (the probe's a1 and b10). The child runs + `-q` with no `-rs`, as the `tests` job does, and its output names both + too, since a skip a person cannot read is a skip nobody audits.""" + empty = no_engine(tmp_path) + probe = write_probe(tmp_path) + for switch in (None, "0"): + label = "unset" if switch is None else f"at {switch}" + junit = tmp_path / f"probe-{label.replace(' ', '-')}.xml" + proc = probe_run(tmp_path, probe, f"--junitxml={junit}", + switch=switch, pg_bin=empty) + assert proc.returncode == 0, ( + f"with the switch {label}, a missing engine must skip, exit 0:\n" + f"{shown(proc)}") + cases = {case.get("name"): case for case in + ElementTree.parse(str(junit)).getroot().iter("testcase")} + assert PROBE_TEST in cases, f"the probe did not run:\n{shown(proc)}" + skipped = cases[PROBE_TEST].find("skipped") + assert skipped is not None, ( + f"with the switch {label}, the probe did not skip:\n{shown(proc)}") + reason = (skipped.get("message") or "") + (skipped.text or "") + for word in ("PG_BIN", "postgresql-16"): + assert word in reason, ( + f"with the switch {label}, the skip's reason names no " + f"{word}: {reason}") + assert word in proc.stdout, ( + f"with the switch {label}, the -q output names no {word}, so " + f"the tests job's log would not show why:\n{shown(proc)}") + + +def test_the_engine_switch_refuses_a_value_that_is_not_0_or_1(tmp_path): + """A value that is neither `1` nor `0` (nor unset) is pytest's usage + error, exit 4, naming the variable and the value, before any engine is + looked for (the probe's b3). `true` and `yes` are what a person might + write; neither is `1`.""" + probe = write_probe(tmp_path) + for value in ("2", "yes", "true"): + proc = probe_run(tmp_path, probe, switch=value) + output = proc.stdout + proc.stderr + assert proc.returncode == 4, ( + f"{SWITCH}={value!r} must be refused, exit 4:\n{shown(proc)}") + assert f"{SWITCH}={value!r}" in output, ( + f"the refusal of {SWITCH}={value!r} does not name it:\n" + f"{shown(proc)}") + assert PROBE_TEST not in output, f"the probe ran:\n{shown(proc)}" + + +def test_no_real_engine_test_is_selected_by_the_launch_jobs_filter(tmp_path): + """L2-0b's hygiene rule: the `guard-launch-mode` job's `-k` selects no + real-engine test. The child collects this whole suite as the job does, + with the job's own filter, which pytest matches against each test's + function, class, module and parametrize id, case-insensitively, so every + test any later task adds is held to it. The probe, which the filter + selects on purpose, shows that the check sees a real-engine test; it + cannot, until the plugin defines `pg`.""" + workflow = (REPO / ".github" / "workflows" / "tests.yml").read_text( + encoding="utf-8") + assert f"bash tests/run.sh -k '{LAUNCH_JOB_FILTER}'" in workflow, ( + f"tests.yml no longer runs `bash tests/run.sh -k " + f"'{LAUNCH_JOB_FILTER}'`: this case must follow the job's filter") + probe = write_probe(tmp_path) + plugins = tmp_path / "plugins" + plugins.mkdir() + (plugins / f"{REPORTER_MODULE}.py").write_text(REPORTER_SOURCE, + encoding="utf-8") + report = tmp_path / "selected.jsonl" + path = os.pathsep.join([str(plugins), *filter(None, [os.environ.get( + "PYTHONPATH")])]) + proc = child(tmp_path, ["--collect-only", "-p", REPORTER_MODULE, + "-k", LAUNCH_JOB_FILTER, str(SUITE), str(probe)], + switch="0", + extra_env={"ENGINE_REPORT": str(report), "PYTHONPATH": path}) + assert proc.returncode == 0 and report.is_file(), shown(proc) + rows = [json.loads(line) for line in + report.read_text(encoding="utf-8").splitlines()] + probes = [row for row in rows if Path(row["path"]).resolve() == probe.resolve()] + assert probes and all(row["engine"] for row in probes), ( + f"the filter selected the probe, a test that asks for `pg`, and its " + f"fixture closure holds no `{ENGINE_FIXTURE}`: this check cannot see " + f"a real-engine test, so it would pass whatever the suite held. " + f"The probe's rows: {probes}") + suite = [row for row in rows + if Path(row["path"]).resolve().is_relative_to(SUITE)] + assert suite, (f"the launch job's filter selects nothing in {SUITE}:\n" + f"{shown(proc)}") + offenders = sorted(row["nodeid"] for row in suite if row["engine"]) + assert not offenders, ( + f"`-k '{LAUNCH_JOB_FILTER}'`, the guard-launch-mode job's filter, " + f"selects {len(offenders)} real-engine test(s); rename each so that " + f"no part of its id holds either word: {offenders}") + + +#: THE STALE SWEEP'S CASES (T205c). Every pid is fake, above any system's pid +#: limit, and every signal goes to a recorder through the module's seam. +SWEEP_CASES = ["no-proc", "pid-not-positive", "malformed", "does-not-stop", "reused-pid", "orphan"] +FAKE_PID = 2 ** 30 + 7 + + +@pytest.mark.parametrize("case", SWEEP_CASES) +def test_the_stale_sweep_signals_and_removes_only_what_it_proves_is_a_dead_sessions_postmaster( + monkeypatch, tmp_path, case): + """T205c (Codex's BLOCKING 2 on f060619c): `sweep_stale` signals a stale + root's postmaster only where its command line and start time prove it + is that postmaster, never on the pidfile's word alone, and removes the + root only where no such process is left. `[no-proc]`, no `/proc`, as on + macOS, and the pidfile's pid alive: nothing signalled, the root kept; + `[pid-not-positive]`, a pidfile naming -1 (every process) with no + `/proc`: nothing signalled, kept; `[malformed]`, a pidfile whose pid does + not parse: kept; `[does-not-stop]`, the proved postmaster outlives + SIGQUIT and SIGKILL: kept; `[reused-pid]`, the pid held by another + command line: nothing signalled, removed; `[orphan]`, the proved + postmaster, ended by SIGQUIT: removed. No real process is signalled.""" + import signal + + import pgcluster + parent = tmp_path / "parent" + root = parent / f"{pgcluster.PREFIX}stale" + (root / "data").mkdir(parents=True) + (root / "owner").write_text(f"{FAKE_PID + 1} 1\n") # the session that left it is gone + datadir = str(root / "data") + pid = {"pid-not-positive": "-1", "malformed": "7x"}.get(case, str(FAKE_PID)) + (root / "data" / "postmaster.pid").write_text( + f"{pid}\n{datadir}\n0\n5432\n{root}\n\n0 0\nready\n") + proc = tmp_path / "proc" + if case not in ("no-proc", "pid-not-positive"): + argv = (["/usr/bin/sleep", "600"] if case == "reused-pid" + else ["/pg/bin/postgres", "-D", datadir, "-p", "5432"]) + (proc / str(FAKE_PID)).mkdir(parents=True) + (proc / str(FAKE_PID) / "cmdline").write_bytes(b"".join(os.fsencode(a) + b"\0" for a in argv)) + fields = ["S"] + ["0"] * 18 + ["4242"] # the state, then the start time + (proc / str(FAKE_PID) / "stat").write_text(f"{FAKE_PID} (postgres) {' '.join(fields)}\n") + alive, sent = {FAKE_PID}, [] + + def kill(target, sig): + if sig: + sent.append((target, signal.Signals(sig).name)) + if target not in alive: + raise ProcessLookupError(target) + if sig and case != "does-not-stop": + alive.discard(target) + + monkeypatch.setattr(pgcluster, "SOCKET_PARENT", str(parent)) + monkeypatch.setattr(pgcluster, "_PROC", proc) + monkeypatch.setattr(pgcluster, "_kill", kill) + monkeypatch.setattr(pgcluster, "ORPHAN_WAIT", 0.05) + swept = pgcluster.sweep_stale() + want_sent, kept = {"does-not-stop": ([(FAKE_PID, "SIGQUIT"), (FAKE_PID, "SIGKILL")], True), + "reused-pid": ([], False), + "orphan": ([(FAKE_PID, "SIGQUIT")], False)}.get(case, ([], True)) + assert sent == want_sent, f"[{case}] the sweep signalled {sent}, not {want_sent}" + assert root.is_dir() == kept, f"[{case}] the sweep {'removed' if kept else 'kept'} {root}" + assert swept == ([] if kept else [str(root)]), f"[{case}] the sweep reports {swept}" diff --git a/tests/test_sql_register_gate.py b/tests/test_sql_register_gate.py new file mode 100644 index 00000000..d6920539 --- /dev/null +++ b/tests/test_sql_register_gate.py @@ -0,0 +1,516 @@ +# SPDX-License-Identifier: Apache-2.0 +"""THE LANDING GATE, T280: ITS ELEVEN CASES (Brett's "Temporary landing gate +(Recommended)", 2026-11-13; FR-059). TEMPORARY: T281 removes this module with +the gate, in the last set. + +`tests/conftest.py`'s hook, through its reader `tests/sql_register_gate.py`, +skips each 007 test whose tasks have not all landed, and the skip names them. +A test waits for what its module's `SQL_REGISTER_GATE_TABLE` says. A task has +landed when its marker is in `tests/sql_register_landed/`. The gate is active +only in a GitHub Actions run whose workflow is not `verify` and whose ref is +not a `verify/` branch, unless `SQL_REGISTER_GATE` is `on` or `off` (lane 3's +rulings, 2026-11-13, and (b), 2026-11-14, opensoft/openRepoTools#165 comments +6867533114 and 6870017590). Eight cases are T280's; the ninth is (b)'s; the +tenth, a gated run with no marker directory, is lane 2's review RV26's; the +eleventh, a table key naming no test, is Codex's review of E `d58f3b82`. + +EACH CASE RUNS A CHILD PYTEST, since a table or a marker the gate cannot read +ends the session that reads it. The child runs in a code root of the case's +own, made of: + * a copy of this suite's `conftest.py` and the local modules it imports, so + the hook under test is the suite's own, byte for byte; + * a probe module with a table; + * a module with no table; + * the marker directory the case writes. + +The child sees no `GITHUB_*`, `SQL_REGISTER_GATE`, `OPENREPOTOOLS_*`, `PG*` or +`PYTEST_*` of the outer run, only what the case sets. It reports each id +through a JUnit file, which names the reason of every skip. + +The cases about WHEN the gate is active also ask the reader's `active()` +directly. That covers the refs a child cannot be put on cheaply: a pull +request's head, the merge queue's branches, and a `verify/` head. +""" + +from __future__ import annotations + +import ast +import os +import shutil +import subprocess +import sys +import xml.etree.ElementTree as ElementTree +from pathlib import Path +from typing import Dict, Iterable, NamedTuple, Tuple + +import pytest + +import sql_register_gate +from sql_register_gate import SWITCH, active + +#: THIS SUITE: the child's `conftest.py` is a copy of the one beside this file. +SUITE = Path(__file__).resolve().parent + +#: The probe module's table. Its ids wait for: +#: * `test_gate_probe_waits`: T205, T415 and T416; +#: * `test_gate_probe_runs`: T205 alone, from the `"*"` row; +#: * `test_gate_probe_param[a]`: T205 and T415, by the function's row; +#: * `test_gate_probe_param[b]`: T205 and T416, by its own row, which +#: replaces the function's. +TABLE: Dict[str, Tuple[str, ...]] = { + "*": ("T205",), + "test_gate_probe_waits": ("T416", "T415"), + "test_gate_probe_param": ("T415",), + "test_gate_probe_param[b]": ("T416",), +} + +PROBE = '''\ +import pytest + +SQL_REGISTER_GATE_TABLE = {table!r} + + +def test_gate_probe_waits(): + pass + + +def test_gate_probe_runs(): + pass + + +@pytest.mark.parametrize("case", ["a", "b"]) +def test_gate_probe_param(case): + pass +''' + +#: A module with no table: its id runs, gated or not. +FREE = '''\ +def test_gate_free_runs(): + pass +''' + +ALL_IDS = ("test_gate_probe_waits", "test_gate_probe_runs", + "test_gate_probe_param[a]", "test_gate_probe_param[b]", + "test_gate_free_runs") + +#: An Actions run of `tests.yml` on a push to `main`, where the gate is active. +ON_MAIN = {"GITHUB_ACTIONS": "true", "GITHUB_WORKFLOW": "tests", + "GITHUB_EVENT_NAME": "push", "GITHUB_REF_NAME": "main"} + +#: THE SKIP'S WORDS, WRITTEN OUT: what follows the tasks in every reason. A case +#: that pins the words compares with this and never with the reader's own +#: `reason()` (lane 2's RV26, SHOULD 2). +REASON_TAIL = " (the landing gate, T280: no marker in tests/sql_register_landed/)" + +#: pgcluster's tag, which its banner counts as an engine skip: a gated id's +#: reason must never hold it (`pgcluster.py`'s `SKIP_TAG`). +ENGINE_TAG = "real PostgreSQL 16" + +#: What the child must not inherit from the outer run. +NOT_INHERITED = ("GITHUB_", "OPENREPOTOOLS_", "PG", "PYTEST_", SWITCH) + + +def local_imports(path: Path) -> set: + """The modules beside this one that `path` imports, at any depth.""" + names = set() + for node in ast.walk(ast.parse(path.read_text(encoding="utf-8"))): + if isinstance(node, ast.Import): + names.update(alias.name.split(".")[0] for alias in node.names) + elif isinstance(node, ast.ImportFrom) and node.level == 0 and node.module: + names.add(node.module.split(".")[0]) + return {name for name in names if (SUITE / f"{name}.py").is_file()} + + +def estate(where: Path, table=TABLE, markers: Iterable[str] = ()) -> Path: + """A code root for one child: the suite's `conftest.py` and what it imports, + the probe with `table`, the free module, and a marker for each of + `markers`. No marker directory at all where `markers` is empty.""" + tests = where / "code" / "tests" + tests.mkdir(parents=True) + todo, copied = ["conftest"], set() + while todo: + name = todo.pop() + if name not in copied: + copied.add(name) + shutil.copyfile(SUITE / f"{name}.py", tests / f"{name}.py") + todo.extend(local_imports(SUITE / f"{name}.py") - copied) + assert "sql_register_gate" in copied, f"conftest.py imports no reader: {copied}" + (tests / "test_gate_probe.py").write_text(PROBE.format(table=table), encoding="utf-8") + (tests / "test_gate_free.py").write_text(FREE, encoding="utf-8") + markers = list(markers) + if markers: + landed = tests / sql_register_gate.LANDED + landed.mkdir() + for name in markers: + (landed / name).write_text("", encoding="utf-8") + return where / "code" + + +class Run(NamedTuple): + code: int + output: str + #: Each id's outcome, `passed`, `skipped` or `failed`, and a skip's reason. + ids: Dict[str, Tuple[str, str]] + + +def child(root: Path, *args: str, where: str = "tests", **env: str) -> Run: + """`python -m pytest -q -rs tests` in `root`, with `env` and nothing of the + outer run's that the gate or the suite's switches read. `args`, such as a + `-k` selection, go before `tests`. `where`, in place of `tests`, names one + node id to collect alone.""" + environ = {key: value for key, value in os.environ.items() + if not key.startswith(NOT_INHERITED)} + environ["PYTHONDONTWRITEBYTECODE"] = "1" + environ.update(env) + junit = root.parent / "junit.xml" + command = [sys.executable, "-m", "pytest", "-q", "-rs", "-p", "no:cacheprovider", + f"--basetemp={root.parent / 'basetemp'}", f"--rootdir={root}", + f"--junitxml={junit}", *args, where] + proc = subprocess.run(command, cwd=str(root), env=environ, capture_output=True, + text=True, timeout=600, check=False) + ids: Dict[str, Tuple[str, str]] = {} + if junit.is_file(): + for case in ElementTree.parse(str(junit)).getroot().iter("testcase"): + skipped = case.find("skipped") + if skipped is not None: + ids[case.get("name")] = ("skipped", skipped.get("message", "")) + elif case.find("failure") is not None or case.find("error") is not None: + ids[case.get("name")] = ("failed", "") + else: + ids[case.get("name")] = ("passed", "") + return Run(proc.returncode, proc.stdout + proc.stderr, ids) + + +def shown(run: Run) -> str: + return f"exit {run.code}; ids {run.ids}\n{run.output}" + + +def waits(*tasks: str) -> Tuple[str, str]: + """A gated id's outcome: skipped, naming `tasks`.""" + return ("skipped", sql_register_gate.reason(tasks)) + + +def every_id_runs(run: Run) -> bool: + return run.code == 0 and run.ids == {name: ("passed", "") for name in ALL_IDS} + + +def gated_on_t205_alone(run: Run) -> bool: + """With T205's marker alone, the outcome of a run whose gate is active.""" + return run.code == 0 and run.ids == { + "test_gate_probe_waits": waits("T415", "T416"), + "test_gate_probe_runs": ("passed", ""), + "test_gate_probe_param[a]": waits("T415"), + "test_gate_probe_param[b]": waits("T416"), + "test_gate_free_runs": ("passed", ""), + } + + +def test_a_table_naming_an_id_that_is_no_007_task_fails_the_run(tmp_path): + """A table whose rows name T999 (a number no task line has) and T252x (a + slice's letter, not a task) fails the run: pytest's own + `UsageError`, exit 4, before any test runs. The refusal names the module's + table, each row and each id. The run here is not gated (no Actions, no + switch), so a bad row fails a local run too. A row whose task id is a list, + which cannot be looked up, is refused the same way, exit 4, and is not + pytest's internal error, exit 3 (lane 2's RV26, NIT 3). So is a table that + is not a dict, a list of pairs here, named by its type. And a bad table + fails the run even where `-k` deselects every id of its module, since the + hook checks the table of every module the run collected, selected or not + (lane 2's RV26, NIT 4). The control is the same code root with a good + table, where every id runs, and where the same `-k` runs the module with + no table alone.""" + bad = dict(TABLE) + bad["test_gate_probe_waits"] = ("T415", "T999") + bad["test_gate_probe_param[b]"] = ("T252x",) + run = child(estate(tmp_path / "bad", table=bad)) + assert run.code == 4, f"a table naming no 007 task must fail the run:\n{shown(run)}" + assert "ERROR: the landing gate (T280): SQL_REGISTER_GATE_TABLE in " in run.output, shown(run) + assert "test_gate_probe.py" in run.output, shown(run) + assert "'test_gate_probe_waits' names T999, which is not one of 007's task ids" in run.output, shown(run) + assert "'test_gate_probe_param[b]' names T252x, which is not one of 007's task ids" in run.output, shown(run) + assert "passed" not in run.output and not run.ids, f"a test ran:\n{shown(run)}" + listed = dict(TABLE) + listed["*"] = (["T205"],) + unhashable = child(estate(tmp_path / "unhashable", table=listed)) + assert unhashable.code == 4, ( + f"a task id that is a list must be the gate's own refusal, not pytest's " + f"internal error:\n{shown(unhashable)}") + assert "'*' names ['T205'], which is not one of 007's task ids" in unhashable.output, shown(unhashable) + assert "INTERNALERROR" not in unhashable.output and not unhashable.ids, shown(unhashable) + wrong = child(estate(tmp_path / "wrong", table=[("*", ("T205",))])) + assert wrong.code == 4, f"a table that is not a dict must fail the run:\n{shown(wrong)}" + assert "test_gate_probe.py is a list, not a dict of test name to the task ids it waits for" in wrong.output, shown(wrong) + assert "INTERNALERROR" not in wrong.output and not wrong.ids, shown(wrong) + deselected = child(estate(tmp_path / "deselected", table=bad), "-k", "gate_free") + assert deselected.code == 4, ( + f"a bad table must fail the run where -k deselects its module:\n{shown(deselected)}") + assert "'test_gate_probe_waits' names T999, which is not one of 007's task ids" in deselected.output, shown(deselected) + assert "passed" not in deselected.output and not deselected.ids, f"a test ran:\n{shown(deselected)}" + good = child(estate(tmp_path / "good")) + assert every_id_runs(good), f"the same root with a good table must run:\n{shown(good)}" + good_k = child(estate(tmp_path / "good-k"), "-k", "gate_free") + assert good_k.code == 0 and good_k.ids == {"test_gate_free_runs": ("passed", "")}, ( + f"-k 'gate_free' must deselect every id of the probe:\n{shown(good_k)}") + assert "4 deselected" in good_k.output, shown(good_k) + + +def test_a_table_key_naming_no_test_of_its_module_fails_the_run(tmp_path): + """A table key that names no test of its module fails the run, exit 4, + before any test runs, gated or not: a misspelled function name, + `test_gate_probe_wiats`, and an id with parameters its function does not + have, `test_gate_probe_param[c]`. Either would otherwise match nothing, + and the test it meant would run ungated (Codex's review of E `d58f3b82`, + BLOCKING 1). The refusal names the module's table and each key. It holds + where `-k` deselects every id of the module. The keys are checked against + every id pytest's collection of the module holds, before any selection: + with a good table, a run that names one node id, a function or one + parametrized id, still accepts the rows of the ids it did not select, and + gates the id it did.""" + bad = dict(TABLE) + bad["test_gate_probe_wiats"] = bad.pop("test_gate_probe_waits") + bad["test_gate_probe_param[c]"] = ("T416",) + run = child(estate(tmp_path / "typo", table=bad)) + assert run.code == 4, f"a key naming no test must fail the run:\n{shown(run)}" + assert "ERROR: the landing gate (T280): SQL_REGISTER_GATE_TABLE in " in run.output, shown(run) + assert "test_gate_probe.py" in run.output, shown(run) + assert "'test_gate_probe_wiats' names no test of its module" in run.output, shown(run) + assert "'test_gate_probe_param[c]' names no test of its module" in run.output, shown(run) + assert "passed" not in run.output and not run.ids, f"a test ran:\n{shown(run)}" + deselected = child(estate(tmp_path / "typo-k", table=bad), "-k", "gate_free", **{SWITCH: "on"}) + assert deselected.code == 4, ( + f"a key naming no test must fail the run where -k deselects its module:\n{shown(deselected)}") + assert "'test_gate_probe_wiats' names no test of its module" in deselected.output, shown(deselected) + assert "passed" not in deselected.output and not deselected.ids, f"a test ran:\n{shown(deselected)}" + good = child(estate(tmp_path / "good")) + assert every_id_runs(good), f"the same root with a good table must run:\n{shown(good)}" + one = child(estate(tmp_path / "one", markers=("T205",)), + where="tests/test_gate_probe.py::test_gate_probe_runs", **{SWITCH: "on"}) + assert one.code == 0 and one.ids == {"test_gate_probe_runs": ("passed", "")}, ( + f"one node id must not refuse the rows of the ids it did not select:\n{shown(one)}") + param = child(estate(tmp_path / "param", markers=("T205",)), + where="tests/test_gate_probe.py::test_gate_probe_param[a]", **{SWITCH: "on"}) + assert param.code == 0 and param.ids == {"test_gate_probe_param[a]": waits("T415")}, ( + f"one parametrized id must not refuse its sibling's row:\n{shown(param)}") + + +def test_a_marker_naming_an_id_that_is_no_007_task_fails_the_run(tmp_path): + """A marker directory holding `T999` (a number no task line has) and a + `.gitkeep` (the placeholder git's lack of empty directories invites) fails + the run, exit 4, naming both and the directory. The run is not gated, so a + bad marker fails a local run too. So does a marker named for a 007 task + that is a directory, `T415`, or a symlink, `T416`, here to T205's own + marker file: a marker is a file, and not a symlink (lane 2's RV26, + NIT 4). So does a marker that is not empty, `T415` here, since a marker + is one empty file; and a marker directory that is itself a symlink, here + to a directory of good markers, since the markers are read in the tree + (Codex's review of E `d58f3b82`, SHOULD 7). The control holds only 007 + tasks' markers, T236's among them (a task line since lane 3's commit 17, + `204145ae`), and every id runs.""" + run = child(estate(tmp_path / "bad", markers=("T205", "T999", ".gitkeep"))) + assert run.code == 4, f"a marker naming no 007 task must fail the run:\n{shown(run)}" + assert "ERROR: the landing gate (T280): " in run.output, shown(run) + assert f"{sql_register_gate.LANDED} holds .gitkeep, T999: a marker is a file named for one of 007's task ids" in run.output, shown(run) + assert "passed" not in run.output and not run.ids, f"a test ran:\n{shown(run)}" + kinds = estate(tmp_path / "kinds", markers=("T205",)) + landed = kinds / "tests" / sql_register_gate.LANDED + (landed / "T415").mkdir() + (landed / "T416").symlink_to("T205") + assert (landed / "T416").is_symlink() and (landed / "T416").is_file() + shapes = child(kinds) + assert shapes.code == 4, f"a marker that is a directory or a symlink must fail the run:\n{shown(shapes)}" + assert f"{sql_register_gate.LANDED} holds T415, T416: a marker is a file named for one of 007's task ids" in shapes.output, shown(shapes) + assert "passed" not in shapes.output and not shapes.ids, f"a test ran:\n{shown(shapes)}" + full = estate(tmp_path / "full", markers=("T205",)) + (full / "tests" / sql_register_gate.LANDED / "T415").write_text("landed\n", encoding="utf-8") + nonempty = child(full) + assert nonempty.code == 4, f"a marker that is not empty must fail the run:\n{shown(nonempty)}" + assert f"{sql_register_gate.LANDED} holds T415: a marker is a file named for one of 007's task ids" in nonempty.output, shown(nonempty) + assert "passed" not in nonempty.output and not nonempty.ids, f"a test ran:\n{shown(nonempty)}" + linked = estate(tmp_path / "linked") + elsewhere = tmp_path / "elsewhere" + elsewhere.mkdir() + for name in ("T205", "T415", "T416"): + (elsewhere / name).write_text("", encoding="utf-8") + (linked / "tests" / sql_register_gate.LANDED).symlink_to(elsewhere, target_is_directory=True) + rooted = child(linked, **{SWITCH: "on"}) + assert rooted.code == 4, f"a marker directory that is a symlink must fail the run:\n{shown(rooted)}" + assert f"{sql_register_gate.LANDED} is a symlink" in rooted.output, shown(rooted) + assert "passed" not in rooted.output and not rooted.ids, f"a test ran:\n{shown(rooted)}" + good = child(estate(tmp_path / "good", markers=("T205", "T236", "T415"))) + assert every_id_runs(good), f"markers of 007 tasks must not fail the run:\n{shown(good)}" + + +def test_a_gated_id_is_reported_skipped_naming_the_tasks_it_waits_for(tmp_path): + """With the gate on and T205's marker alone, `test_gate_probe_waits` is + reported skipped with "waits for T415, T416". Its tasks are in task order, + and T205, which has landed, is not named. Under `-rs` the line is at the + probe's own path. `[a]` waits for the function's T415 and `[b]` for its own + row's T416. The `"*"` row's id and the module with no table run. With T415 + marked too, the skips name T416 alone. The skips are marked after `-k` has + deselected (`tests/conftest.py`'s `trylast`): with `-k 'gate_probe and not + skip'`, every probe id is selected and the three gated ones are skipped as + before. A hook that marked them before `-k` would let `not skip` deselect + them, since `-k` matches an id's marker names (lane 2's RV26, NIT 4).""" + run = child(estate(tmp_path / "t205", markers=("T205",)), **{SWITCH: "on"}) + assert gated_on_t205_alone(run), f"the gated ids, by the table:\n{shown(run)}" + assert "SKIPPED [1] tests/test_gate_probe.py:" in run.output, shown(run) + assert f"{sql_register_gate.reason(('T415', 'T416'))}" in run.output, shown(run) + assert "waits for T415, T416 (" in run.output, shown(run) + assert run.ids["test_gate_probe_waits"] == ( + "skipped", "waits for T415, T416" + REASON_TAIL), shown(run) + assert not any(ENGINE_TAG in message for _, message in run.ids.values()), shown(run) + assert "3 skipped" in run.output and "2 passed" in run.output, shown(run) + later = child(estate(tmp_path / "t415", markers=("T205", "T415")), **{SWITCH: "on"}) + assert later.code == 0 and later.ids == { + "test_gate_probe_waits": waits("T416"), + "test_gate_probe_runs": ("passed", ""), + "test_gate_probe_param[a]": ("passed", ""), + "test_gate_probe_param[b]": waits("T416"), + "test_gate_free_runs": ("passed", ""), + }, f"with T415 landed, only T416 is waited for:\n{shown(later)}" + selected = child(estate(tmp_path / "selected", markers=("T205",)), + "-k", "gate_probe and not skip", **{SWITCH: "on"}) + assert selected.code == 0 and selected.ids == { + "test_gate_probe_waits": waits("T415", "T416"), + "test_gate_probe_runs": ("passed", ""), + "test_gate_probe_param[a]": waits("T415"), + "test_gate_probe_param[b]": waits("T416"), + }, f"the skips are marked after -k, so `not skip` keeps every gated id:\n{shown(selected)}" + assert "1 deselected" in selected.output, shown(selected) + + +def test_with_the_gate_on_and_no_marker_directory_every_row_is_waited_for(tmp_path): + """With the gate on and no marker directory at all, as the code leg is until + the first set's cut (git keeps no empty directory), no task has landed. + Every probe id is skipped, and each reason names every task of its rows in + task order, the `"*"` row's T205 first: `test_gate_probe_runs` waits for + T205 alone, by the `"*"` row. The module with no table runs. The reasons + are written out here, not built by the reader. A reader that dropped the + `"*"` row, or read a missing directory as every task landed, fails here + (lane 2's RV26, SHOULDs 1 and 2).""" + root = estate(tmp_path / "none") + assert not (root / "tests" / sql_register_gate.LANDED).exists() + run = child(root, **{SWITCH: "on"}) + assert run.code == 0 and run.ids == { + "test_gate_probe_waits": ("skipped", "waits for T205, T415, T416" + REASON_TAIL), + "test_gate_probe_runs": ("skipped", "waits for T205" + REASON_TAIL), + "test_gate_probe_param[a]": ("skipped", "waits for T205, T415" + REASON_TAIL), + "test_gate_probe_param[b]": ("skipped", "waits for T205, T416" + REASON_TAIL), + "test_gate_free_runs": ("passed", ""), + }, f"no marker directory is no task landed:\n{shown(run)}" + assert "4 skipped" in run.output and "1 passed" in run.output, shown(run) + assert not any(ENGINE_TAG in message for _, message in run.ids.values()), shown(run) + + +def test_an_id_whose_tasks_all_have_markers_is_never_skipped(tmp_path): + """With the gate on and a marker for each of T205, T415 and T416, every + id runs and passes, and nothing is skipped.""" + run = child(estate(tmp_path / "all", markers=("T205", "T415", "T416")), + **{SWITCH: "on"}) + assert every_id_runs(run), f"every task has landed:\n{shown(run)}" + assert "skipped" not in run.output and "SKIPPED" not in run.output, shown(run) + + +def test_the_gate_is_active_in_an_actions_run_on_a_ref_outside_verify(tmp_path): + """An Actions run of a push to `main`, with no switch, is gated. So, by the + reader, is every other run on a ref outside `verify/`: + * a pull request's CI, whose ref is its head branch, not + `GITHUB_REF_NAME`'s `/merge`; + * the merge queue's runs, on Mergify's `mergify/merge-queue/…` + candidates or a `gh-readonly-queue/…` ref; + * `main`'s nightly, a release branch, and a dispatch. + A head ref is read only on a pull request's events.""" + run = child(estate(tmp_path / "main", markers=("T205",)), **ON_MAIN) + assert gated_on_t205_alone(run), f"a push to main in Actions is gated:\n{shown(run)}" + actions = {"GITHUB_ACTIONS": "true"} + for event, ref_name, head in ( + ("pull_request", "12/merge", "lane2/007-T243"), + ("pull_request_target", "12/merge", "lane2/007-T243"), + ("pull_request", "13/merge", "mergify/merge-queue/0123456789"), + ("merge_group", "gh-readonly-queue/main/pr-12-" + "0" * 40, ""), + ("schedule", "main", ""), + ("workflow_dispatch", "lane2/007-T280", ""), + ("push", "release/v1.3", ""), + ("push", "main", "verify/not-read-on-a-push")): + environ = dict(actions, GITHUB_EVENT_NAME=event, GITHUB_REF_NAME=ref_name, + GITHUB_HEAD_REF=head) + assert active(environ), f"not active on {environ}" + + +def test_the_gate_is_inactive_on_a_verify_ref(tmp_path): + """An Actions run of a push to a `verify/` branch runs every id: such a + branch is cut from line R and holds no markers, and no verify may pass by + the gate's skip. By the reader, a pull request whose head is under + `verify/` is not gated either.""" + run = child(estate(tmp_path / "verify", markers=("T205",)), + GITHUB_ACTIONS="true", GITHUB_EVENT_NAME="push", + GITHUB_REF_NAME="verify/lane2/T280") + assert every_id_runs(run), f"a verify/ ref runs ungated:\n{shown(run)}" + for event in ("pull_request", "pull_request_target"): + environ = {"GITHUB_ACTIONS": "true", "GITHUB_EVENT_NAME": event, + "GITHUB_REF_NAME": "12/merge", "GITHUB_HEAD_REF": "verify/lane2/T280"} + assert not active(environ), f"active on {environ}" + + +def test_the_gate_is_inactive_in_a_dispatched_verify_run_on_any_ref(tmp_path): + """A run of `verify.yml` dispatched on `main` runs every id: GitHub names + its workflow `verify` (`GITHUB_WORKFLOW`, verify.yml's `name:`), and a + verify run is ungated on any ref, so no verify passes by the gate's skip + (lane 3's (b), 6870017590). By the reader the same holds on a lane's + branch and on a pull request's head. The same dispatch of `tests.yml` + is gated, and so is a workflow merely named like it. `SQL_REGISTER_GATE=on` + still gates a verify run.""" + run = child(estate(tmp_path / "dispatch", markers=("T205",)), + GITHUB_ACTIONS="true", GITHUB_WORKFLOW="verify", + GITHUB_EVENT_NAME="workflow_dispatch", GITHUB_REF_NAME="main") + assert every_id_runs(run), f"a dispatched verify run is ungated:\n{shown(run)}" + verify = {"GITHUB_ACTIONS": "true", "GITHUB_WORKFLOW": "verify"} + for event, ref_name, head in ( + ("workflow_dispatch", "lane2/007-T280", ""), + ("pull_request", "12/merge", "lane2/007-T243"), + ("push", "main", "")): + environ = dict(verify, GITHUB_EVENT_NAME=event, GITHUB_REF_NAME=ref_name, + GITHUB_HEAD_REF=head) + assert not active(environ), f"active on {environ}" + for workflow in ("tests", "Verify", "verify-shadow"): + environ = {"GITHUB_ACTIONS": "true", "GITHUB_WORKFLOW": workflow, + "GITHUB_EVENT_NAME": "workflow_dispatch", "GITHUB_REF_NAME": "main"} + assert active(environ), f"not active on {environ}" + assert active(dict(verify, GITHUB_EVENT_NAME="workflow_dispatch", + GITHUB_REF_NAME="main", **{SWITCH: "on"})), "on must gate verify" + + +def test_the_gate_is_inactive_outside_github_actions(tmp_path): + """A run on `main` that is not a GitHub Actions run runs every id: + `GITHUB_ACTIONS` is not `true` there. Local runs and line R's census are such + runs.""" + run = child(estate(tmp_path / "local", markers=("T205",)), + GITHUB_EVENT_NAME="push", GITHUB_REF_NAME="main") + assert every_id_runs(run), f"a run outside Actions runs ungated:\n{shown(run)}" + for value in (None, "", "false", "1"): + environ = {"GITHUB_EVENT_NAME": "push", "GITHUB_REF_NAME": "main"} + if value is not None: + environ["GITHUB_ACTIONS"] = value + assert not active(environ), f"active on {environ}" + + +def test_the_switch_at_on_or_off_overrides_where_the_gate_is_active(tmp_path): + """`SQL_REGISTER_GATE=on` gates a run outside Actions, and `=off` ungates + an Actions run on `main`. By the reader, each holds on any ref. Any other + value is refused, exit 4, naming it, as the suite's other switches refuse + a value that is neither.""" + on = child(estate(tmp_path / "on", markers=("T205",)), **{SWITCH: "on"}) + assert gated_on_t205_alone(on), f"on, outside Actions, is gated:\n{shown(on)}" + off = child(estate(tmp_path / "off", markers=("T205",)), **dict(ON_MAIN, **{SWITCH: "off"})) + assert every_id_runs(off), f"off, in Actions on main, is ungated:\n{shown(off)}" + bad = child(estate(tmp_path / "bad", markers=("T205",)), **{SWITCH: "1"}) + assert bad.code == 4, f"{SWITCH}=1 must be refused:\n{shown(bad)}" + assert f"ERROR: the landing gate (T280): {SWITCH}='1' is neither on nor off" in bad.output, shown(bad) + assert "passed" not in bad.output and not bad.ids, f"a test ran:\n{shown(bad)}" + verify = {"GITHUB_ACTIONS": "true", "GITHUB_EVENT_NAME": "push", + "GITHUB_REF_NAME": "verify/lane2/T280"} + assert active(dict(verify, **{SWITCH: "on"})), "on must gate a verify/ ref" + assert not active({**ON_MAIN, SWITCH: "off"}), "off must ungate main" + assert not active({SWITCH: "off"}), "off must ungate a local run" + with pytest.raises(sql_register_gate.GateError): + active({SWITCH: "ON"}) diff --git a/tests/test_sql_register_helpers.py b/tests/test_sql_register_helpers.py new file mode 100644 index 00000000..2ef36ce1 --- /dev/null +++ b/tests/test_sql_register_helpers.py @@ -0,0 +1,174 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Feature 007's own test of T203c's `guard_session`, in +`tests/sql_register_helpers.py` (L2-0d; opensoft/openRepoTools#165). + +T203's and T207's helpers are checked by their tasks' `verify:` lines; the +guard's session helper is checked here, against today's `lanes-edit.sh +guard`, because its whole job is what that guard does with it: with it, the +guard gets past its session-record check (`transcript_holders`, clause (d)) +to its next step, the register's text; without it, the guard stops at that +check with 2 (lane 5, #165 6755266457; F10's items 27 and 28). + +The estate is T215's and T220's (`test_sql_register_outage.py`, +`test_sql_register_bounds.py`): a bare origin, the lane's checkout under +`$HOME/projects` with `lanes/LANES.md` pushed, `$HOME/.agents/workspace.yaml` +naming it, and the compact hook JSON, in files mode (no configuration), so +nothing here waits for another lane's code. Three registers tell the step the +guard reached: an empty one (the guard refuses at the register's text), one +whose row names the session (it lets the prompt through, 0) and one whose row +names another session (it refuses on the row). +""" + +from __future__ import annotations + +import json +import os +import shutil +import subprocess +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")] + +GUARD = REPO / "lanes-edit.sh" +#: The guard's refusal at its session-record check (`lanes-edit.sh:11010` at +#: `a2073eae`), and at its next step, the register's text (`:11050`). +NO_RECORD = "no live session record in THIS window" +NO_TEXT = "the register's TEXT could not be read" +DOT = chr(0xB7) +REGISTER_HEADER = ["# LANES.md", "", + "| lane | session id | workstation / env / user | started (UTC) | objects " + "owned | handoff path | state |", + "|---|---|---|---|---|---|---|"] + + +def _register(session_cell: str) -> str: + """A register whose one row binds `GUARD_WINDOW` to `session_cell`, in + T215's row form.""" + row = (f"| `{GUARD_WINDOW}` | harness `{session_cell}` | 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 _estate(root: Path, register: str) -> tuple: + """T215's and T220's estate, with `register` as `lanes/LANES.md`. Returns + (`home`, the checkout, the `bin` directory, the guard's 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), LANES_LANE=GUARD_WINDOW, + 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, 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"]): + subprocess.run(["git", *argv], cwd=str(wip), check=True, env=env, capture_output=True) + (home / ".agents").mkdir() + (home / ".agents" / "workspace.yaml").write_text( + f"repository: {origin}\npath: {wip}\n", encoding="utf-8") + return home, wip, root / "bin", env + + +def _guard(session, env: dict, **extra) -> tuple: + """`lanes-edit.sh guard` at the base, the session's hook JSON on stdin. + Returns (its exit, its stdout and stderr).""" + proc = subprocess.run(["bash", str(GUARD), "guard"], input=session.hook_input(), + capture_output=True, text=True, cwd=str(session.cwd), + env=session.env(env, **extra), timeout=60, start_new_session=True) + return proc.returncode, proc.stdout + proc.stderr + + +@pytest.mark.parametrize("register", ["empty-register", "row-names-the-session", + "row-names-another-session"]) +def test_guard_session_takes_the_guard_past_its_session_record_check(tmp_path, register): + """T203c: with `guard_session`'s record, the guard gets past its + session-record check to its next step, the register's text: it refuses + there for an empty register, lets the prompt through where the row names + the session, and refuses on the row where it names another. With the same + estate and stand-in but no record, or after `close()`, it stops at the + session-record check with 2.""" + sid, other = str(uuid.uuid4()), str(uuid.uuid4()) + text = {"empty-register": "", "row-names-the-session": _register(sid), + "row-names-another-session": _register(other)}[register] + home, wip, bin_dir, env = _estate(tmp_path, text) + session = guard_session(home, bin_dir, wip, session_id=sid) + try: + record = json.loads(session.record.read_text(encoding="utf-8")) + assert session.record == home / ".claude" / "sessions" / f"{session.pid}.json" + assert (session.record.stat().st_mode & 0o777) == 0o600 + assert record["sessionId"] == sid and record["pid"] == session.pid, record + assert record["tmux"] == "testsess:@1.%1" and record["kind"] == "interactive", record + + aside = session.record.with_name(session.record.name + ".aside") + session.record.rename(aside) + code, out = _guard(session, env) + assert code == 2 and NO_RECORD in out, f"without the record: {code}\n{out[-600:]}" + aside.rename(session.record) + + code, out = _guard(session, env) + assert NO_RECORD not in out, f"with the record: {code}\n{out[-600:]}" + if register == "empty-register": + assert code == 2 and NO_TEXT in out, f"{register}: {code}\n{out[-600:]}" + elif register == "row-names-the-session": + assert code == 0, f"{register}: {code}\n{out[-600:]}" + else: + assert code == 2 and f"does not name {sid} at all" in out, \ + f"{register}: {code}\n{out[-600:]}" + calls = session.tmux_calls() + for query in (["display-message", "-p", "#{session_name}:#{window_id}"], + ["display-message", "-p", "#{pane_pid}"], + ["display-message", "-p", "#W"], + ["display-message", "-p", "-t", "@1", "#{session_name}"]): + assert query in calls, f"the stand-in was not asked {query}: {calls}" + finally: + session.close() + assert session.holder.poll() is not None, "close() left the session's process alive" + code, out = _guard(session, env) + assert code == 2 and NO_RECORD in out, f"after close(): {code}\n{out[-600:]}" + + +def test_guard_session_refuses_a_checkout_outside_home_projects_and_strips_projects_root( + tmp_path): + """T203c: `guard_session` refuses a checkout outside `/projects`, + where the guard's scope test returns 0 before any read (T220c); + `guard_strip_env` drops `PROJECTS_ROOT` (F10's item 28) with the other + prefixes and a module's own; and an exported `PROJECTS_ROOT` naming + another root does make today's guard return 0 with nothing said, before + its session-record check.""" + with pytest.raises(ValueError, match="is not under"): + guard_session(tmp_path / "home", tmp_path / "bin", tmp_path / "wip") + with pytest.raises(ValueError, match="not in lower case"): + guard_session(tmp_path / "home", tmp_path / "bin", tmp_path / "home" / "projects" / "w", + session_id=str(uuid.uuid4()).upper()) + kept = guard_strip_env({"PROJECTS_ROOT": "/x", "AGENT_PROTOCOL_ROOT": "/y", "TMUX": "z", + "TMUX_PANE": "%9", "LANES_REPO": "r", "CLAUDE_CODE_SESSION_ID": "s", + "PGHOST": "h", "FAKE_PSQL_LOG": "l", "T215_X": "1", "KEEP": "1"}, + strip=("T215_",)) + assert kept == {"KEEP": "1"}, kept + + home, wip, bin_dir, env = _estate(tmp_path / "e", "") + with guard_session(home, bin_dir, wip) as session: + code, out = _guard(session, env, PROJECTS_ROOT=str(tmp_path / "elsewhere")) + assert code == 0 and out == "", f"PROJECTS_ROOT elsewhere: {code}\n{out[-600:]}" + code, out = _guard(session, env) + assert code == 2 and NO_TEXT in out, f"stripped: {code}\n{out[-600:]}" diff --git a/tests/test_tests_workflow.py b/tests/test_tests_workflow.py index 7a81b1f9..27bdb58a 100644 --- a/tests/test_tests_workflow.py +++ b/tests/test_tests_workflow.py @@ -81,6 +81,7 @@ import zipfile from datetime import datetime, timezone from pathlib import Path +from typing import List, Tuple import pytest @@ -1569,3 +1570,97 @@ def test_tests_yml_synthetic_wheels_are_wheel_md_s_members(head, tmp_path): with zipfile.ZipFile(path) as wheel: listed = wheel.namelist() assert all(listed.count(name) == 2 for name in again), (case, listed) + + +# --- the real engine (#165, L2-0b) --------------------------------------------- + +#: THE REAL-ENGINE SWITCH, `tests/pgcluster.py`'s. At `1` a run that finds no +#: PostgreSQL 16 is refused, pytest's exit 4, where unset or `0` it would +#: skip every real-engine test and exit 0. +REQUIRE_PG = "OPENREPOTOOLS_REQUIRE_PG" + +#: A `run:` that runs the suite or a module of it: pytest, or the wrapper. +RUNS_PYTEST = re.compile(r"-m[ \t]+pytest\b|\btests/run\.sh\b" + r"|\bci_shards\.py[ \t]+(?:run|verify)\b") # T201c: the shard jobs + + +def suite_steps(workflow: dict) -> Tuple[List[str], List[str]]: + """T201's oracle (T201c moves it here, unchanged, so a mutant can be + read by it): the steps that run the suite, and each problem with their + `OPENREPOTOOLS_REQUIRE_PG`.""" + top = workflow.get("env") or {} + assert isinstance(top, dict), "tests.yml's workflow-level `env:` is not a mapping" + runs_pytest, problems = [], [] + for job_id, job in jobs_of(workflow).items(): + assert isinstance(job, dict), f"`{job_id}` is not a mapping" + for number, step in enumerate(job.get("steps") or [], 1): + run = as_text(step.get("run")) + if REQUIRE_PG in run: + problems.append(f"`{job_id}` step {number}'s `run:` names " + f"{REQUIRE_PG}; set it only in an `env:`") + if not RUNS_PYTEST.search(run): + continue + runs_pytest.append(f"{job_id} step {number}") + effective = {} + for level in (top, job.get("env") or {}, step.get("env") or {}): + effective.update(level) + value = effective.get(REQUIRE_PG) + if value is None or as_text(value) != "1": + said = "unset" if value is None else f"{as_text(value)!r}" + problems.append(f"`{job_id}` step {number} runs pytest with " + f"{REQUIRE_PG} {said}, not '1'") + return runs_pytest, problems + + +@NEEDS_UPSTREAM +def test_tests_yml_requires_the_real_engine_in_every_job_that_runs_it(workflow): + """FR-059 and FR-060 (#165, L2-0b; the test plan's section 3.3): every + step that runs pytest, in whichever job, runs it with + `OPENREPOTOOLS_REQUIRE_PG` at `1`, so a runner without the engine turns + the job red, `package` and `guard-launch-mode` among them, instead of + letting the real-engine tests skip. + + Each step's effective `env:` is resolved as the runner resolves it: the + workflow's `env:`, then the job's, then the step's, a later level winning. + The jobs are read as they are, not named, so the rule holds whatever jobs + the file has. And no `run:` may name the variable: a script that exports, + unsets or appends it to `$GITHUB_ENV` would change it behind the `env:` + this test reads.""" + top = workflow.get("env") or {} + runs_pytest, problems = suite_steps(workflow) + assert runs_pytest, "no step of tests.yml runs pytest or tests/run.sh" + assert not problems, ( + f"a job that runs the suite without {REQUIRE_PG}: '1' lets a missing " + f"engine skip instead of failing. The workflow-level `env:` is " + f"{top!r}; the steps that run pytest are {runs_pytest}:\n " + + "\n ".join(problems)) + + +#: T201c: the steps of the shard jobs and their aggregates, which launch and +#: collect pytest themselves (`.github/ci/ci_shards.py`'s `run` and `verify`). +SHARD_STEP = re.compile(r"\bci_shards\.py[ \t]+(?:run|verify)\b") + + +@NEEDS_UPSTREAM +def test_tests_yml_oracle_fails_a_shard_job_that_turns_the_real_engine_off(workflow): + """T201c (Codex's SHOULD 4 on f060619c): a job whose step runs + `ci_shards.py run` or `ci_shards.py verify` runs the suite, so T201's + oracle reads it: given `OPENREPOTOOLS_REQUIRE_PG: '0'` in its job-level + `env:`, each such job, shard and aggregate alike, fails the oracle, while + the workflow as it is passes.""" + import copy + shard_jobs = [job_id for job_id, job in jobs_of(workflow).items() + if any(SHARD_STEP.search(as_text(step.get("run"))) for step in job.get("steps") or [])] + assert len(shard_jobs) >= 2, f"tests.yml's shard jobs are {shard_jobs}: expected their `run` and `verify`" + _, problems = suite_steps(workflow) + assert problems == [], f"the workflow as it is fails T201's oracle: {problems}" + missed = [] + for job_id in shard_jobs: + mutant = copy.deepcopy(workflow) + job = jobs_of(mutant)[job_id] + job["env"] = dict(job.get("env") or {}, **{REQUIRE_PG: "0"}) + _, problems = suite_steps(mutant) + if not any(f"`{job_id}` step" in problem for problem in problems): + missed.append(job_id) + assert missed == [], (f"a job-level {REQUIRE_PG}: '0' passes T201's oracle in {missed}: " + f"its `ci_shards.py` step is not read as running the suite")