From 0dcd7873390d4fda4019d24f11e7e6b48186df93 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sat, 21 Nov 2026 18:06:02 -0600 Subject: [PATCH 01/74] Pin that check-privileges --json escapes controls and bidi characters Two tests run the command with --json, one on its result output (an unobservable store probe whose detail holds the characters) and one on its error output (settings that do not load). Each asserts the printed text is ASCII with no C0 control or DEL, carries ESC, DEL, CSI (U+009B), U+202E and U+2028 as \uXXXX escapes, and decodes back to the original text. Both fail when _print_json or _emit_error passes ensure_ascii=False (checked by hand). Vault BACKLOG #2891, PR 2390 note 3: fixed with a test. Proposed PR title: Batch 284: check-privileges --json escape tests; route-walk items already met Proposed banners: - #2891: PR 2390 note 3 met with a test. Open, unchanged: note 2 (and item 4, the terminal_text.py docstring tied to it) waits on an owner ruling; the other PR 2390 notes as the row records them. - #3177: added items 5 to 15 read met at engine main by PR 3015 (cd0a4a2f907), checked against the code and tests: 5, 6, 7, 10 to 15 fixed with tests; 8 kept as the refusal (a mount cycle raises RecursionError, pinned by a test); 9 kept because a served app nests a handful of mounts and one walk per level keeps the refusal free of shared state. PR 3015's own open findings were left for the Lander to file under R2; where they landed is not checked here. --- tests/test_store_privilege_check.py | 47 +++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/tests/test_store_privilege_check.py b/tests/test_store_privilege_check.py index ce0f1acb07..c0c36e9123 100644 --- a/tests/test_store_privilege_check.py +++ b/tests/test_store_privilege_check.py @@ -631,6 +631,53 @@ def test_cli_json_reports_every_family_and_no_secret( assert by_hop["smtp"]["state"] == "not_probed" +#: ESC, DEL, a C1 control (CSI), RIGHT-TO-LEFT OVERRIDE and LINE SEPARATOR: each one a terminal or +#: a line reader acts on. ``--json`` output must carry them as ``\uXXXX`` escapes (BACKLOG #2891, +#: PR 2390 note 3). +_HOSTILE = "a\x1b[31mb\x7fc\x9bd‮e
f" + + +def _assert_escaped(out: str) -> None: + assert out.isascii(), f"--json output carries a non-ASCII character: {out!r}" + controls = [ch for ch in out.rstrip("\n") if ch < " " or ch == "\x7f"] + assert not controls, f"--json output carries a control: {out!r}" + for escape in ("\\u001b", "\\u007f", "\\u009b", "\\u202e", "\\u2028"): + assert escape in out + + +def test_cli_json_result_escapes_controls_and_bidi_in_a_detail( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + _clear_env(monkeypatch) + _stub_probe( + monkeypatch, + StorePrivilegeReport( + backend=StoreBackend.SQLSERVER, + status=StorePrivilegeStatus.UNOBSERVABLE, + detail=_HOSTILE, + ), + ) + argv = ["check-privileges", "--service-config", str(_server_toml(tmp_path)), "--json"] + assert main(argv) == 4 + out = capsys.readouterr().out + _assert_escaped(out) + store = next(h for h in json.loads(out)["hops"] if h["hop"] == "store") + assert _HOSTILE in store["detail"] + + +def test_cli_json_error_escapes_controls_and_bidi_in_the_message( + monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + _clear_env(monkeypatch) + monkeypatch.setattr( + "messagefoundry.__main__._load_service_settings", lambda *a, **k: (None, _HOSTILE) + ) + assert main(["check-privileges", "--service-config", "unused.toml", "--json"]) == 1 + out = capsys.readouterr().out + _assert_escaped(out) + assert json.loads(out) == {"error": _HOSTILE} + + def test_cli_says_serve_would_refuse_an_over_grant_under_enforce( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] ) -> None: From 407981516a050d6f67f3c76bfbe8613cf6e2bc30 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sat, 21 Nov 2026 18:13:21 -0600 Subject: [PATCH 02/74] check settings memo: key on the working directory and environment; hermetic memo tests The run memo keyed settings resolution and load on their arguments only, so a change to the working directory or the environment during a run reused the answer to a different question. Adding both to the key can only turn a hit into a miss, never a miss into a wrong hit. The memo tests now run in an empty working directory with no MEFOR_* variables. Vault BACKLOG #2950 (PR 3013 open findings). --- messagefoundry/checks.py | 25 +++++++++++++--- tests/test_checks_settings_memo.py | 48 ++++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+), 4 deletions(-) diff --git a/messagefoundry/checks.py b/messagefoundry/checks.py index 8c023dcea7..ee0f5d9323 100644 --- a/messagefoundry/checks.py +++ b/messagefoundry/checks.py @@ -130,6 +130,21 @@ ) +def _ambient() -> tuple[str | None, tuple[tuple[str, str], ...]]: + """The working directory and the environment, as a :data:`_RUN_MEMO` key part. Both feed the + answer as well as the arguments do: the search reads ``./messagefoundry.toml``, a relative + path resolves against the working directory, and the load reads ``MEFOR_*``. Keying on them + means a change during a run, by the caller or another thread, reads afresh rather than reusing + an answer to a different question; the whole environment, because the loader may read more than + ``MEFOR_*``. An unreadable working directory is ``None``: the uncached call then meets the same + fault itself.""" + try: + cwd: str | None = os.getcwd() + except OSError: + cwd = None + return cwd, tuple(sorted(os.environ.items())) + + def _config_modules( name: str, config_dir: str | Path, *, required: bool = False ) -> list[Path] | CheckResult: @@ -2218,14 +2233,15 @@ def _settings_source( ``(None, False)`` is the SKIP the legs have always given a bare dir. - Inside :func:`run_checks` it resolves once per distinct argument set (:data:`_RUN_MEMO`).""" + Inside :func:`run_checks` it resolves once per distinct argument set, working directory and + environment (:data:`_RUN_MEMO`).""" memo = _RUN_MEMO.get() if memo is None: return _settings_source_uncached( config_dir, service_config=service_config, suppress_search=suppress_search, env=env ) explicit = None if service_config is None else str(service_config) - key = ("source", str(config_dir), explicit, suppress_search, env) + key = ("source", str(config_dir), explicit, suppress_search, env, _ambient()) if key not in memo: memo[key] = _settings_source_uncached( config_dir, service_config=service_config, suppress_search=suppress_search, env=env @@ -2270,13 +2286,14 @@ def _load_check_settings( ``env`` is ``check --env``, applied as ``serve`` applies its own ``--env``: a CLI override of ``[ai].environment``, above the file and ``MEFOR_AI_ENVIRONMENT`` (vault BACKLOG #2355). - Inside :func:`run_checks` the load runs once per distinct argument set, a refusal of + Inside :func:`run_checks` the load runs once per distinct argument set, working directory and + environment, a refusal of :data:`_SETTINGS_LOAD_ERRORS` included, and every later leg gets that answer (:data:`_RUN_MEMO`): its own deep copy, so no leg sees another's change to the model.""" memo = _RUN_MEMO.get() if memo is None: return _load_check_settings_uncached(toml, cli=cli, env=env) - key = ("load", None if toml is None else str(toml), repr(cli), env) + key = ("load", None if toml is None else str(toml), repr(cli), env, _ambient()) if key not in memo: try: memo[key] = _load_check_settings_uncached(toml, cli=cli, env=env) diff --git a/tests/test_checks_settings_memo.py b/tests/test_checks_settings_memo.py index aedbd30662..1cf7dc2612 100644 --- a/tests/test_checks_settings_memo.py +++ b/tests/test_checks_settings_memo.py @@ -8,6 +8,7 @@ from __future__ import annotations +import os from collections import Counter from pathlib import Path from typing import Any @@ -20,6 +21,19 @@ SAMPLES_CONFIG = Path(__file__).resolve().parents[1] / "samples" / "config" +@pytest.fixture(autouse=True) +def _hermetic(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """Each test runs in an empty working directory with no ``MEFOR_*`` variables, so neither a + ``./messagefoundry.toml`` where pytest was started nor a variable the shell exports reaches + what the legs grade.""" + work = tmp_path / "cwd" + work.mkdir() + monkeypatch.chdir(work) + for name in list(os.environ): + if name.upper().startswith("MEFOR_"): + monkeypatch.delenv(name) + + def _count_reads(monkeypatch: pytest.MonkeyPatch) -> Counter[str]: calls: Counter[str] = Counter() real_load = checks._load_check_settings_uncached @@ -104,3 +118,37 @@ def test_a_leg_called_outside_a_run_reads_afresh( checks._load_check_settings(toml) assert calls["source"] == 2 assert calls["load"] == 2 + + +def test_a_change_to_the_environment_or_working_directory_during_a_run_reads_afresh( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """RED when: the memo key leaves out the environment or the working directory, so a change to + either during a run gets the answer to the question asked before it. Control: the same call + with neither changed is answered from the memo.""" + calls = _count_reads(monkeypatch) + token = checks._RUN_MEMO.set({}) + try: + + def source() -> tuple[Path | None, bool]: + return checks._settings_source( + SAMPLES_CONFIG, service_config=None, suppress_search=False, env=None + ) + + assert source() == (None, False) + assert source() == (None, False) + assert calls["source"] == 1 + # The environment now declares an instance, which the bare dir's SKIP must not hide. + monkeypatch.setenv("MEFOR_AI_ENVIRONMENT", "dev") + assert source() == (None, True) + assert calls["source"] == 2 + # A messagefoundry.toml in the new working directory is what the search now finds. + other = tmp_path / "other" + other.mkdir() + (other / "messagefoundry.toml").write_text("", encoding="utf-8") + monkeypatch.chdir(other) + found, _ = source() + assert found is not None and found.resolve() == (other / "messagefoundry.toml").resolve() + assert calls["source"] == 3 + finally: + checks._RUN_MEMO.reset(token) From c1d7afbd29d554832f2d21bf31b443ac3ef14ee5 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sat, 21 Nov 2026 18:14:22 -0600 Subject: [PATCH 03/74] sign-in timeout census: read async methods and inline read timeouts The census of EngineClient methods that take the sign-in timeout skipped async def methods, and a method that built its own httpx.Timeout(read=...) escaped it. Both are now read. Vault BACKLOG #2950 (PR 3013 open finding 10). --- tests/test_apiclient_sign_in_timeout.py | 37 +++++++++++++++++++++---- 1 file changed, 32 insertions(+), 5 deletions(-) diff --git a/tests/test_apiclient_sign_in_timeout.py b/tests/test_apiclient_sign_in_timeout.py index c9c66d9d6c..27a3a68a39 100644 --- a/tests/test_apiclient_sign_in_timeout.py +++ b/tests/test_apiclient_sign_in_timeout.py @@ -171,16 +171,19 @@ def test_a_client_timeout_up_to_the_floor_gets_the_floor_on_the_queued_reads(own assert seen["/auth/me"] == _every_phase(own) -def _methods_calling(name: str) -> set[str]: - """The ``EngineClient`` methods whose body calls ``self.()``, read from its source.""" +def _client_methods() -> list[ast.FunctionDef | ast.AsyncFunctionDef]: + """The ``EngineClient`` methods, ``async def`` ones included, read from its source.""" tree = ast.parse(Path(inspect.getfile(EngineClient)).read_text(encoding="utf-8")) cls = next( n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == EngineClient.__name__ ) + return [fn for fn in cls.body if isinstance(fn, (ast.FunctionDef, ast.AsyncFunctionDef))] + + +def _methods_calling(name: str) -> set[str]: + """The ``EngineClient`` methods whose body calls ``self.()``, read from its source.""" found: set[str] = set() - for fn in cls.body: - if not isinstance(fn, ast.FunctionDef): - continue + for fn in _client_methods(): for node in ast.walk(fn): if ( isinstance(node, ast.Call) @@ -193,6 +196,23 @@ def _methods_calling(name: str) -> set[str]: return found +def _methods_setting_a_read_timeout() -> set[str]: + """The ``EngineClient`` methods that build an ``httpx.Timeout`` with its own ``read=``.""" + found: set[str] = set() + for fn in _client_methods(): + for node in ast.walk(fn): + if ( + isinstance(node, ast.Call) + and ( + (isinstance(node.func, ast.Attribute) and node.func.attr == "Timeout") + or (isinstance(node.func, ast.Name) and node.func.id == "Timeout") + ) + and any(kw.arg == "read" for kw in node.keywords) + ): + found.add(fn.name) + return found + + def test_the_census_of_queued_calls_matches_the_client() -> None: """RED when: an ``EngineClient`` method gains or loses the sign-in timeout without this census, and so ``_QUEUED``, moving with it (vault BACKLOG #2950 added item 10). The census is of @@ -208,6 +228,13 @@ def test_the_census_of_queued_calls_matches_the_client() -> None: assert _methods_calling("_adopt_rotated") == {"reauth", "verify_mfa", "confirm_mfa"} +def test_no_method_raises_its_read_timeout_inline() -> None: + """RED when: an ``EngineClient`` method builds its own ``httpx.Timeout(..., read=...)`` rather + than calling ``_sign_in_timeout``, so a longer reply wait escapes the census above. Control: + the scan finds the one method that does build one, ``_sign_in_timeout`` itself.""" + assert _methods_setting_a_read_timeout() == {"_sign_in_timeout"} + + def test_confirm_mfa_sends_the_enrolment_code_only_when_given() -> None: """ADR 0207: a directory account's first factor needs the Administrator's code on an unstamped session, so the shared client must be able to carry it. RED when it cannot.""" From 8a46f828e442160e5b8c8c0d175acd65deaddd23 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sat, 21 Nov 2026 18:15:18 -0600 Subject: [PATCH 04/74] IDE: track the step-up re-proof like a sign-in POST /me/reauth rotates the session token, but it ran outside the sign-in tracking, so peekToken and a sign-in started meanwhile did not wait for it: the sign-in could name the token the re-proof had just ended, and the re-proof's late store could overwrite the newer token. reproveTracked shares signInSuperseding's tracking and stores the rotated token inside it. Vault BACKLOG #2950 (PR 3013 earlier-round open finding). --- changelog.d/2950-ide-reauth-tracked.fixed.md | 5 ++ ide/src/auth.ts | 13 +++-- ide/src/signInSession.ts | 47 ++++++++++++++++--- ide/src/test/suite/sign-in-supersedes.test.ts | 44 ++++++++++++++++- 4 files changed, 97 insertions(+), 12 deletions(-) create mode 100644 changelog.d/2950-ide-reauth-tracked.fixed.md diff --git a/changelog.d/2950-ide-reauth-tracked.fixed.md b/changelog.d/2950-ide-reauth-tracked.fixed.md new file mode 100644 index 0000000000..237f4e3c5d --- /dev/null +++ b/changelog.d/2950-ide-reauth-tracked.fixed.md @@ -0,0 +1,5 @@ +- **The IDE's step-up re-proof is now tracked like a sign-in.** `/me/reauth` rotates the session + token, but a cache reader did not wait for it and a sign-in started meanwhile did not either, so + the sign-in could name the token the re-proof had just ended and the re-proof's late store could + then overwrite the sign-in's newer token. Both now wait for the re-proof in that VS Code window. + (`vault BACKLOG #2950`) diff --git a/ide/src/auth.ts b/ide/src/auth.ts index e39ffd42aa..1d6386b8e0 100644 --- a/ide/src/auth.ts +++ b/ide/src/auth.ts @@ -8,7 +8,7 @@ import * as vscode from "vscode"; import { getJson, HttpError, postJson } from "./engineClient"; import { mustChangeProblem } from "./engineStatusModel"; import { assertBrowsableUrl, assertTargetAllowed, targetRefusalNotice } from "./engineTarget"; -import { SIGN_IN_TIMEOUT_MS, signInSettled, signInSuperseding } from "./signInSession"; +import { SIGN_IN_TIMEOUT_MS, reproveTracked, signInSettled, signInSuperseding } from "./signInSession"; import { type StepUpHost, withStepUp } from "./stepUp"; const SECRET_PREFIX = "messagefoundry.token:"; @@ -371,11 +371,14 @@ export async function withStepUpAuth( // It rotates the token and queues behind the account's re-proof lock, as the sign-in does, // so it gets the sign-in's timeout (vault BACKLOG #2950), named here rather than left to // postJson's default so the two cannot drift apart. - // Unlike a sign-in it is not tracked in signInSession.ts, so peekToken does not wait for it. + // Tracked in signInSession.ts as a sign-in is, and it stores the rotated token there, so + // peekToken and a later sign-in wait for it and its store cannot overwrite a newer sign-in's. // A timeout after the engine finished leaves the cached token dead, as a lost sign-in reply // does: the next call gets a 401 and signs in again. - const reply = await postJson<{ token?: unknown }>(url, "/me/reauth", body, token, SIGN_IN_TIMEOUT_MS); - return typeof reply.token === "string" ? reply.token : undefined; + return await reproveTracked(ctx.secrets, secretKey(url), async () => { + const reply = await postJson<{ token?: unknown }>(url, "/me/reauth", body, token, SIGN_IN_TIMEOUT_MS); + return typeof reply.token === "string" ? reply.token : undefined; + }); }, }; return await withAuthAdopting(ctx, url, (token, adopt) => @@ -384,9 +387,9 @@ export async function withStepUpAuth( // The re-proof ended the token withAuthAdopting handed in, so it is told which one this call // now holds: a 401 on it is then not mistaken for a sign-in elsewhere merely because the // cache holds the rotated token (BACKLOG #5960). + // reauth above already stored it, inside the tracked span. storeToken: async (rotated) => { adopt(rotated); - await ctx.secrets.store(secretKey(url), rotated); }, }), ); diff --git a/ide/src/signInSession.ts b/ide/src/signInSession.ts index 9ab53324a9..aa550d1c5f 100644 --- a/ide/src/signInSession.ts +++ b/ide/src/signInSession.ts @@ -14,8 +14,9 @@ // // THE COST IS THE ORDER ON THIS SIDE. The old token now dies inside the request, before the new one is // in the cache. Four things follow. -// 1. A reader of the cache could pick up the dead token in that span. Each sign-in is therefore -// tracked from before its request leaves until the new token is stored, and `peekToken` in +// 1. A reader of the cache could pick up the dead token in that span. Each sign-in, and each step-up +// re-proof (`reproveTracked`), is therefore tracked from before its request leaves until the new +// token is stored, and `peekToken` in // auth.ts awaits `signInSettled` before it reads. A call already sent on the old token can still // get a 401, and `withAuth` then reads the cache again through `peekToken`. // 2. Two sign-ins for one engine run one after the other. The second reads the cache only once the @@ -95,15 +96,49 @@ export function signInSuperseding( post: (body: Record) => Promise, waitMs: number = SIGN_IN_WAIT_MS, ): Promise { - const earlier = inFlight.get(key); - const attempt = (async () => { - await bounded(earlier, waitMs); + return tracked(key, waitMs, async () => { const prior = await cache.get(key); const reply = await post(prior ? { ...credentials, supersedes: prior } : credentials); await cache.store(key, reply.token); return reply; + }); +} + +/** + * Send one step-up re-proof for the engine cached under `key`, and store the token it returns. + * + * `post` sends `POST /me/reauth` on the token the call holds and resolves to the rotated token, or to + * `undefined` or `""` when the engine sent none (an older engine), which leaves the cache as it was. + * The engine ends the old token when it rotates, as a sign-in does, so the re-proof is tracked the same + * way: it waits up to `waitMs` for a sign-in or re-proof already in flight for `key`, and a later one, + * and `peekToken`, wait for it in turn. So in this window its store does not land on top of a token a + * newer sign-in stored, unless a wait runs out (point 3 above) or the sign-in was in another window + * (point 4). + */ +export function reproveTracked( + cache: TokenCache, + key: string, + post: () => Promise, + waitMs: number = SIGN_IN_WAIT_MS, +): Promise { + return tracked(key, waitMs, async () => { + const rotated = await post(); + if (rotated !== undefined && rotated !== "") { + await cache.store(key, rotated); + } + return rotated; + }); +} + +/** Run `run` once any attempt already tracked for `key` settles or `waitMs` passes, tracked itself + * from before it starts until it settles. */ +function tracked(key: string, waitMs: number, run: () => Promise): Promise { + const earlier = inFlight.get(key); + const attempt = (async () => { + await bounded(earlier, waitMs); + return await run(); })(); - // The attempt waits for the earlier sign-in first, so one await covers them all. Set in the same + // The attempt waits for the earlier attempt first, so one await covers them all. Set in the same // tick the attempt starts, which is before its request can leave. const settled = attempt.then( () => undefined, diff --git a/ide/src/test/suite/sign-in-supersedes.test.ts b/ide/src/test/suite/sign-in-supersedes.test.ts index 51fe5d2be4..c10d8e9fe7 100644 --- a/ide/src/test/suite/sign-in-supersedes.test.ts +++ b/ide/src/test/suite/sign-in-supersedes.test.ts @@ -7,7 +7,7 @@ import type { AddressInfo } from "node:net"; import * as path from "node:path"; import { HttpError, postJson } from "../../engineClient"; -import { signInSettled, signInSuperseding, type TokenCache } from "../../signInSession"; +import { reproveTracked, signInSettled, signInSuperseding, type TokenCache } from "../../signInSession"; // BACKLOG #2281 (ASVS 7.2.4): a sign-in names the token it replaces as `supersedes`, so the engine ends // that session before its per-user cap counts. The IDE used to sign in and then POST /auth/logout with @@ -238,6 +238,41 @@ suite("a caller can wait out a sign-in in flight (BACKLOG #2281)", () => { hung.fail(new Error("cleanup")); // release it, so the next test starts with nothing in flight await signInSettled(key, 1000); }); + + test("a sign-in started during a step-up re-proof names the token the re-proof stored", async () => { + const cache = new MapCache(); + cache.values.set(key, "tok-old"); + const held = heldPost(); + const reproving = reproveTracked(cache, key, async () => (await held.post({})).token); + await held.sent; // the engine has rotated tok-old by now + let settled = false; + const waiting = signInSettled(key).then(() => (settled = true)); + const named: Array = []; + const signingIn = signInSuperseding(cache, key, CREDENTIALS, async (body) => { + named.push(body.supersedes); + return { token: "tok-signed-in" }; + }); + await new Promise((resolve) => setImmediate(resolve)); + // RED when: the re-proof is not tracked. The sign-in then names the dead tok-old, the re-proof's + // late store overwrites the sign-in's token, and peekToken reads tok-old meanwhile. + assert.strictEqual(settled, false, "the wait ended while the re-proof was still in flight"); + assert.deepStrictEqual(named, [], "the sign-in did not wait for the re-proof"); + held.answer("tok-rotated"); + assert.strictEqual(await reproving, "tok-rotated"); + await signingIn; + await waiting; + assert.deepStrictEqual(named, ["tok-rotated"]); + assert.strictEqual(cache.values.get(key), "tok-signed-in"); + }); + + test("a re-proof with no token in its reply leaves the cache alone", async () => { + const cache = new MapCache(); + cache.values.set(key, "tok-old"); + for (const reply of [undefined, ""]) { + assert.strictEqual(await reproveTracked(cache, key, async () => reply), reply); + assert.strictEqual(cache.values.get(key), "tok-old"); + } + }); }); suite("auth.ts routes sign-in through the superseding path (BACKLOG #2281)", () => { @@ -261,6 +296,13 @@ suite("auth.ts routes sign-in through the superseding path (BACKLOG #2281)", () const logoutSites = (text: string): string[] => text.split(/\r?\n/).filter((l) => l.includes('"/auth/logout"')); + test("the step-up re-proof posts through reproveTracked (vault BACKLOG #2950)", () => { + const text = fs.readFileSync(AUTH_TS, "utf8"); + // Control: the sign-in's own call is found by the same kind of scan. + assert.ok(text.includes("signInSuperseding(ctx.secrets, secretKey(url), body"), "signIn's call moved"); + assert.ok(text.includes("reproveTracked(ctx.secrets, secretKey(url), async () =>"), "the re-proof is untracked"); + }); + test("the step-up re-proof carries the sign-in's timeout (vault BACKLOG #2950)", () => { const text = fs.readFileSync(AUTH_TS, "utf8"); const sites = text.split(/\r?\n/).filter((l) => l.includes('"/me/reauth"') && l.includes("postJson")); From 9b1ee0dbef64fc2ebc9e53828796d95bab539a5c Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sat, 21 Nov 2026 18:15:40 -0600 Subject: [PATCH 05/74] Coord scripts: box-activity reads the profile literally, NO_LOGIN names directory rows Vault BACKLOG #2985 (batch 287), added items 1 to 3. - Added item 2, box-activity half: Get-TranscriptAgeHours listed USERPROFILE with -Path, a wildcard pattern, so a profile named home[1] found no transcript. It now uses -LiteralPath, and an unset profile names no root, as Get-ClaudeConfigRoots does. - Added item 3: the announce hook's NO_LOGIN receipt called a directory named *.json "maybe still being written". Directory rows are counted apart and named as not self-resolving. - Added item 1, end-state part: a test that a removal whose directory cannot be confirmed gone (its folder denied listing) is not reported clean. Red with the old Test-PresentOrThrow rule put back. Proposed PR title: Coord scripts: box-activity profile read, NO_LOGIN directory rows, remove.ps1 end-state test (BACKLOG #2985) Part A items 2, 13, 19 and part B items 2 and 4 are recorded as accepted with reasons in the PR body, not changed here. Proposed banner #2985: PARTIAL -- added items 1 (end-state test), 2 (last listing) and 3 built; added item 4 met in code by engine PR 3027; closing step 1 waits on #1017 for items 1, 7 and 12, and item 6 beyond the caller's own config root remains. --- scripts/coord/box-activity.ps1 | 6 +++- scripts/hooks/announce-session.ps1 | 16 ++++++++-- tests/test_announce_hook.py | 29 ++++++++++++++++++ tests/test_coord_box_activity.py | 44 ++++++++++++++++++++++++++++ tests/test_worktree_remove_in_use.py | 16 ++++++++++ 5 files changed, 108 insertions(+), 3 deletions(-) diff --git a/scripts/coord/box-activity.ps1 b/scripts/coord/box-activity.ps1 index cc05e3795c..e96a6ee335 100644 --- a/scripts/coord/box-activity.ps1 +++ b/scripts/coord/box-activity.ps1 @@ -123,9 +123,13 @@ function Get-TranscriptAgeHours { # NOT Get-ClaudeConfigRoots: that one filters to roots holding a sessions/ directory, which is the # right question for the liveness fence and the wrong one here. A root can hold transcripts and no # session registry, and dropping it would turn an evaluable signal into a missing one. + # -LiteralPath, as Get-ClaudeConfigRoots reads it: -Path takes the profile as a wildcard pattern, + # so a profile named home[1] matched only a folder named home1. No profile names no root, because + # -LiteralPath throws on a null path where -Path listed the current directory. $roots = if ($ConfigRoot) { @($ConfigRoot | Where-Object { Test-Path -LiteralPath $_ }) } + elseif (-not $env:USERPROFILE) { @() } else { - @(Get-ChildItem -Path $env:USERPROFILE -Directory -Filter '.claude*' -Force -EA SilentlyContinue | + @(Get-ChildItem -LiteralPath $env:USERPROFILE -Directory -Filter '.claude*' -Force -EA SilentlyContinue | ForEach-Object { $_.FullName }) } foreach ($r in $roots) { diff --git a/scripts/hooks/announce-session.ps1 b/scripts/hooks/announce-session.ps1 index 958d856409..669ba05c57 100644 --- a/scripts/hooks/announce-session.ps1 +++ b/scripts/hooks/announce-session.ps1 @@ -803,8 +803,16 @@ try { # lookup started returning its match count -- sent an operator hunting for a missing file # that was in fact present TWICE, which is the one place the cause was visible. $matched = if ($lookup) { [int]$lookup.Matched } else { 0 } - $unreadable = if ($matched -gt 1) { 0 } else { - @(Get-SessionRecords -IncludeUnreadable | Where-Object { $_.Unreadable }).Count + # A DIRECTORY ROW IS NOT A WRITE IN PROGRESS. The registry lists a directory named *.json + # as an unreadable row, and it stays one on every prompt, so it is counted apart from the + # files and the note does not call it "maybe still being written". + $unreadable = 0 + $dirRows = 0 + if ($matched -le 1) { + foreach ($u in @(Get-SessionRecords -IncludeUnreadable | Where-Object { $_.Unreadable })) { + $unreadable++ + if (Test-Path -LiteralPath $u.File -PathType Container) { $dirRows++ } + } } # LEAD WITH THE DISCRIMINATOR. Write-Receipt folds this through Get-Clean with an 80-char # cap, so anything past that is gone from the only durable record of the decision. The @@ -813,6 +821,10 @@ try { # a duplicated one, which is the failure this note exists to prevent. $why = if ($matched -gt 1) { "AMBIGUOUS: $matched config roots hold a record for this id; will not self-resolve" + } elseif ($dirRows -gt 0 -and $dirRows -eq $unreadable) { + "UNREADABLE: $dirRows registry row(s) are directories; will not self-resolve" + } elseif ($dirRows -gt 0) { + "UNREADABLE: $unreadable registry row(s) unparsed, $dirRows directories; files maybe mid-write" } elseif ($unreadable -gt 0) { "UNREADABLE: $unreadable registry record(s) unparsed, maybe still being written" } else { diff --git a/tests/test_announce_hook.py b/tests/test_announce_hook.py index 09c13f16c4..51e7019a05 100644 --- a/tests/test_announce_hook.py +++ b/tests/test_announce_hook.py @@ -1143,6 +1143,35 @@ def test_a_duplicated_session_id_is_reported_as_ambiguous_not_missing( assert "MISSING" not in note, f"reported missing when it was duplicated: {note}" +@pytest.mark.parametrize( + ("directory", "bad_file", "want"), + [ + (True, False, "1 registry row(s) are directories; will not self-resolve"), + (True, True, "2 registry row(s) unparsed, 1 directories; files maybe mid-write"), + (False, True, "1 registry record(s) unparsed, maybe still being written"), + ], + ids=["directory-only", "directory-and-file", "file-only"], +) +def test_a_directory_row_is_not_called_a_record_being_written( + repo: Path, tmp_path: Path, directory: bool, bad_file: bool, want: str +) -> None: + """Vault BACKLOG #2985, added item 3. The registry lists a directory named *.json as an + unreadable row, and the NO_LOGIN receipt called it "maybe still being written". A directory is + not a write in progress and stays on every prompt. Red before the fix: the directory cases read + as a record being written. The file-only case is the control.""" + home = _registry(tmp_path / "home", "00000000-0000-0000-0000-000000000000", ".claude") + sessions = home / ".claude" / "sessions" + if directory: + (sessions / "dir.json").mkdir() + if bad_file: + (sessions / "bad.json").write_text("{ not json", encoding="utf-8") + sd = tmp_path / "sd" + run(repo, tmp_path=tmp_path, state_dir=sd, rows=[PEER, ACCT], env={"USERPROFILE": str(home)}) + assert outcomes(sd) == ["NO_LOGIN"], outcomes(sd) + note = " ".join(receipts(sd)) + assert f"UNREADABLE: {want}" in note, note + + def test_repeated_stand_downs_do_not_arm_the_kill_ladder(repo: Path, tmp_path: Path) -> None: """A STAND-DOWN MUST BE RECOVERABLE, and one invocation cannot show that. diff --git a/tests/test_coord_box_activity.py b/tests/test_coord_box_activity.py index e31301beba..535af72266 100644 --- a/tests/test_coord_box_activity.py +++ b/tests/test_coord_box_activity.py @@ -442,3 +442,47 @@ def test_dot_sourcing_does_not_change_the_callers_strict_mode(self, sandbox: Pat ) assert proc.returncode == 0, proc.stderr assert "lenient" in proc.stdout + + +class TestTheProfileIsReadByItsOwnName: + """Vault BACKLOG #2985, added item 2. With no -ConfigRoot, Get-TranscriptAgeHours listed + USERPROFILE with -Path, which reads its argument as a wildcard pattern: a profile named home[1] + matched only a folder named home1, so the transcript was never found and the signal read as + UNEVALUABLE. Red before the fix: the bracketed case returned null.""" + + def _age(self, sandbox: Path, home: Path | None) -> str: + env = {k: v for k, v in os.environ.items() if k.upper() != "USERPROFILE"} + if home is not None: + env["USERPROFILE"] = str(home) + ps = ( + f". '{sandbox / 'scripts' / 'coord' / 'box-activity.ps1'}'; " + "$a = Get-TranscriptAgeHours -WorktreePath 'D:\\proj\\App'; " + "if ($null -eq $a) { 'null' } else { [string]$a }" + ) + proc = subprocess.run( + ["pwsh", "-NoProfile", "-NonInteractive", "-Command", ps], + capture_output=True, + text=True, + timeout=TIMEOUT, + check=False, + env=env, + cwd=str(sandbox), + ) + assert proc.returncode == 0 and not proc.stderr.strip(), proc.stderr + return proc.stdout.strip() + + @pytest.mark.parametrize("home_name", ["home", "home[1]"]) + def test_a_transcript_under_the_profile_is_found(self, sandbox: Path, home_name: str) -> None: + d = sandbox / home_name / ".claude" / "projects" / "D--proj-App" + d.mkdir(parents=True) + f = d / "turn.jsonl" + f.write_text('{"t":1}\n', encoding="utf-8") + _back_date(f, 5) + assert float(self._age(sandbox, sandbox / home_name)) == pytest.approx(5, abs=0.1) + + def test_an_unset_profile_names_no_root(self, sandbox: Path) -> None: + """No profile reads as UNEVALUABLE, not as a throw, and not as the current directory.""" + d = sandbox / ".claude" / "projects" / "D--proj-App" + d.mkdir(parents=True) + (d / "turn.jsonl").write_text('{"t":1}\n', encoding="utf-8") + assert self._age(sandbox, None) == "null" diff --git a/tests/test_worktree_remove_in_use.py b/tests/test_worktree_remove_in_use.py index 7ee4c56a75..a289b10e32 100644 --- a/tests/test_worktree_remove_in_use.py +++ b/tests/test_worktree_remove_in_use.py @@ -795,3 +795,19 @@ def test_a_directory_git_leaves_behind_is_reported_and_exits_non_zero(rig: Rig) assert proc.returncode != 0, _out(proc) assert "the directory is still there" in _out(proc), _out(proc) assert "Removed worktree" not in _out(proc), _out(proc) + + +def test_a_removal_that_cannot_be_confirmed_gone_is_not_reported_clean(rig: Rig) -> None: + """Vault BACKLOG #2985, added item 1, its end-state part. After git removes the tree, the run + checks the directory is CONFIRMED gone: a not-found under a folder this user may not list is not + a removal. Red with the rule before engine PR 3027 (Test-PresentOrThrow) put back: it read that + not-found as gone and said "Removed". The folder holding the tree is denied listing; git still + removes the tree by name.""" + wt = rig.add(rig.primary.parent / "box" / "Repo-unlisted") + + with _denied_listing(rig, wt.parent) as probe: + proc = rig.run("-Path", str(wt)) + assert not wt.exists(), _explain(wt.parent, probe, proc) + assert proc.returncode != 0, _explain(wt.parent, probe, proc) + assert "could not be confirmed gone" in _out(proc), _explain(wt.parent, probe, proc) + assert "Removed worktree" not in _out(proc), _explain(wt.parent, probe, proc) From 2bc9cd2bd1d732db2906bf17e18c58c7130e4ce1 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sat, 21 Nov 2026 18:16:01 -0600 Subject: [PATCH 06/74] ADR 0019 and ADR 0173 point to the record instead of restating it ADR 0019 (vault BACKLOG #1173 item 3): RNG amendment point 4 and its two 2026-10-10 notes no longer restate ADR 0138's Transit start gate; they name enforce_transit_bound_attestation and link ADR 0138's 2026-10-07 amendment. Item 2 is true as written and left. ADR 0173 (vault BACKLOG #3009, PR 2899 notes 3 and 4): the 2026-11-11 ODBC amendment gives run times in UTC only, drops the decisions' dual-zone logging times, and states the tested versions once. Proposed PR title: ADR 0019 and ADR 0173 state each fact once Banner #1173: PARTIAL -- item 3 fixed; item 2 true as written, still open Banner #3009: PARTIAL -- PR 2899 notes 3 and 4 fixed --- ...019-pluggable-keyprovider-hsm-kms-vault.md | 32 ++++++----- ...ss-terminating-and-originating-surfaces.md | 26 +++++---- tests/test_adr_0019_0173_stated_once.py | 57 +++++++++++++++++++ 3 files changed, 88 insertions(+), 27 deletions(-) create mode 100644 tests/test_adr_0019_0173_stated_once.py diff --git a/docs/adr/0019-pluggable-keyprovider-hsm-kms-vault.md b/docs/adr/0019-pluggable-keyprovider-hsm-kms-vault.md index b4344de942..eb56428546 100644 --- a/docs/adr/0019-pluggable-keyprovider-hsm-kms-vault.md +++ b/docs/adr/0019-pluggable-keyprovider-hsm-kms-vault.md @@ -660,13 +660,13 @@ lifetime is Vault's to version. The bound is a no-op there and for the identity > [ADR 0138](0138-transit-bulk-crypto-provider-dek-out-of-engine-heap-for-asvs-13-3-3-demand-gated.md)'s > 2026-09-28 amendment states the deployment precondition and cites the pages read. -> **Corrected 2026-10-10 (BACKLOG #1173).** The rotation precondition above still stands, and the -> engine still counts no Transit encrypts. What changed is the record. Since BACKLOG #2337, an -> operator attests to the precondition with `messagefoundry store attest-transit-bound`, and -> `Engine.start` reads that record through `enforce_transit_bound_attestation`. So "documented" -> now undersells it. The R3 ruling above judged the precondition before that record existed; -> whether the record meets R3 is a scorecard call. ADR 0138's 2026-10-07 amendment says what the -> check does under each enforcement level, and what it does not change. +> **Corrected 2026-10-10 (BACKLOG #1173).** The rotation precondition above still stands. What +> changed is the record: since BACKLOG #2337 an operator attests to the precondition, and the engine +> reads that attestation at start, so "documented" now undersells it. The R3 ruling above judged the +> precondition before that record existed. ADR 0138's 2026-10-07 amendment says what was built, what +> the check does under each enforcement level, what it does not change, and who judges the record +> against R3. *(Corrected 2026-11-21, vault BACKLOG #1173: this note also restated that amendment's +> account of the CLI command, the start call, the uncounted encrypts and the scorecard question.)* **Status: 11.3.4 — the bound is persisted, aggregated, alarmed and enforced.** As before, this ADR records the build and does not itself re-score; ADR 0115 / the ASVS-L3 re-score governs the sweep. @@ -801,12 +801,13 @@ above. 96-bit random AES-GCM nonce, and that is a limit on the key, not on the generator. The default path counts it: the 2026-07-22 amendment above, and `store/gcm_bound.py`. The `vault_transit` path counts nothing. In its place, `Engine.start` calls `enforce_transit_bound_attestation` in - `store/transit_attestation.py`, which checks for a recorded operator attestation naming the - configured Transit data key (BACKLOG #2337). Without one, the engine refuses to start under - `[security].enforcement = enforce` and only logs a warning under `warn`. An attestation is still - weaker than the counted bound. [ADR 0138](0138-transit-bulk-crypto-provider-dek-out-of-engine-heap-for-asvs-13-3-3-demand-gated.md)'s - 2026-10-07 amendment records how that gate works and the forgery it does not catch. Its - 2026-09-28 amendment states the rotation precondition the operator attests to. + `store/transit_attestation.py` (BACKLOG #2337). + [ADR 0138](0138-transit-bulk-crypto-provider-dek-out-of-engine-heap-for-asvs-13-3-3-demand-gated.md)'s + 2026-10-07 amendment records how that gate works, what it does not catch and what it does not + change. Its 2026-09-28 amendment states the rotation precondition the operator attests to. + *(Corrected 2026-11-21, vault BACKLOG #1173: this point also restated what the gate checks, what + it does under each enforcement level, and that an attestation is weaker than the counted bound. + That amendment states each of them.)* **What this statement does not cover.** How fast the operating system's generator runs is a property of Windows and Linux. The 2026-10-10 amendment below says what the platform pages state about @@ -815,8 +816,9 @@ blocking and failure, and where they say nothing. > **Corrected 2026-10-10 (BACKLOG #1173).** Point 2 and the paragraph above each said a page had > not been read for this amendment. They now point to the 2026-10-10 amendment, which reads them. > Point 4 described the Transit bound as a precondition the operator documents. It now names the -> shipped attestation check. That check counts no invocations, and the -> bound stays weaker than the counted one. +> shipped attestation check. *(Corrected 2026-11-21, vault BACKLOG #1173: this note also restated +> that the check counts no invocations and is weaker than the counted bound, which ADR 0138's +> 2026-10-07 amendment states.)* **What stops a weak generator coming back, and where it stops short.** Bandit B311 now runs in both the CI scan and the pre-commit hook, with each seeded non-security `random` use marked per line. B311 is a diff --git a/docs/adr/0173-tls-peer-revocation-checking-and-ocsp-stapling-across-terminating-and-originating-surfaces.md b/docs/adr/0173-tls-peer-revocation-checking-and-ocsp-stapling-across-terminating-and-originating-surfaces.md index f47a2322d2..e4fabfe2d3 100644 --- a/docs/adr/0173-tls-peer-revocation-checking-and-ocsp-stapling-across-terminating-and-originating-surfaces.md +++ b/docs/adr/0173-tls-peer-revocation-checking-and-ocsp-stapling-across-terminating-and-originating-surfaces.md @@ -1262,8 +1262,8 @@ ruling: bullet of the 2026-10-04 reading below says. No owner answer and no planned test covers one. - **Only two runs have results, and the run on the SQL Server test box is still owed.** The test needs a SQL Server whose certificate can be revoked. A control connection to a - certificate that is not revoked shows that a refusal comes from the revocation. The amendment of 2026-11-11 below states what - the runs measured, their limits, and which run is still owed. *(Corrected 2026-11-17, vault + certificate that is not revoked shows that a refusal comes from the revocation. The amendment of + 2026-11-11 below states what the runs measured and their limits. *(Corrected 2026-11-17, vault BACKLOG #3009: this bullet's heading read "Driver 18 was tested on one build on Windows Server 2022, and other drivers were not tested", which restated the amendment's limits.)* *(Until 2026-11-11 this bullet read: "**The drivers' own revocation behaviour is still @@ -1283,8 +1283,7 @@ ruling: amendment does not change the grade. A Manager decided under the owner's delegation of 2026-11-11 that the five rows keep the grade R6 gives them, that R6's named gap stands as named, and that #2194's guard and driver-control options are not reopened now: decision - d20261112T022118464-c27c39, logged at 02:21 UTC on 2026-11-12, the evening of 2026-11-11 in - Central time.)* + d20261112T022118464-c27c39.)* *(Until 2026-10-11 this paragraph read: "**What is open on the five ODBC hops.** BACKLOG #2194 names three outcomes for a hop: a guard, a documented driver control, or an accepted gap. This note @@ -1323,9 +1322,8 @@ ODBC revocation runbook that reached a result. Their contents beyond this summar here. It changes no code. For the grade, see the limit headed *What a result would mean for the grade*, under the ruling above, and its note of 2026-11-11. -- **Where it ran.** Two runs with results, dated 2026-10-16 and 2026-10-17 in Central time. In - UTC, the first run's legs ran from 02:22 to 02:25 and the second's from 05:18 to 05:19, both on - 2026-10-17. The first run's record says it ran on a disposable virtual machine built for the +- **Where it ran.** Two runs with results. The first run's legs ran from 02:22 to 02:25 UTC on + 2026-10-17, and the second's from 05:18 to 05:19 UTC the same day. The first run's record says it ran on a disposable virtual machine built for the test, not on the SQL Server test box, and that the runbook puts the next run there. The second run's record says it ran inside a virtual machine, after a revert to checkpoint `post-3009-clean-2026-10-16`, a tightening of folder permissions and a new checkpoint, @@ -1336,8 +1334,7 @@ grade*, under the ruling above, and its note of 2026-11-11. took place on the SQL Server test box", which leaned on a name the second record had replaced with a placeholder.)* The run there is still owed, and BACKLOG #3009's step 2 stays open for it: a Manager decided so under the owner's delegation of 2026-11-11, decision - d20261112T022119877-2ccc8b, logged at 02:21 UTC on 2026-11-12, the evening of 2026-11-11 in - Central time. + d20261112T022119877-2ccc8b. - **Versions.** ODBC Driver 18 for SQL Server, 64-bit: `msodbcsql18.dll` ProductVersion 18.7, build 1, revision 1, reporting driver version `18.07.0001`. Windows Server 2022 Datacenter, build 20348, update revision 5256. SQL Server 2022 RTM, 16.0.1000.6. Both records list @@ -1373,9 +1370,8 @@ grade*, under the ruling above, and its note of 2026-11-11. the pin legs mean for the pin is the amendment of 2026-10-17 below. For the strict legs that reading is the second record's own, because the runbook's table has no row for them. - **The limits.** At least these. - - Only that driver build, only Windows Server 2022, and only SQL Server 2022 RTM. Linux, macOS, - other Driver 18 builds, and other drivers, which the generic dialect and the `odbc_driver` - setting can name, were not measured. + - Only the versions above. Linux, macOS, other Driver 18 builds, and other drivers, which the + generic dialect and the `odbc_driver` setting can name, were not measured. - Only a CRL over HTTP. No OCSP responder was offered, so this does not show that the driver never checks revocation. - Only a same-machine connection: the client ran on the machine SQL Server ran on, so no @@ -1385,6 +1381,12 @@ grade*, under the ruling above, and its note of 2026-11-11. pool, so the result says nothing about how the engine builds or sends its own strings. - Only a throwaway root, with no intermediate CA. +*(Corrected 2026-11-21, vault BACKLOG #3009: this amendment gave the runs' dates in Central time +beside their UTC times, and its first limit repeated the versions. The note under the fourth limit +above and this amendment's first bullet each gave a decision's logging time in UTC and in Central +time, and the third limit above repeated which run is still owed. The UTC run times are kept; the +rest is removed.)* + *(End of the amendment of 2026-11-11. The next paragraph continues the 2026-10-04 note.)* **What is open on the three Vault hops.** *(Built on 2026-10-13, under vault BACKLOG #2983; diff --git a/tests/test_adr_0019_0173_stated_once.py b/tests/test_adr_0019_0173_stated_once.py new file mode 100644 index 0000000000..84e1d4f3bb --- /dev/null +++ b/tests/test_adr_0019_0173_stated_once.py @@ -0,0 +1,57 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +# Copyright (C) 2026 MessageFoundry Foundation, LLC and contributors +"""ADR 0019 and ADR 0173 point to the record that states a fact, rather than restating it. + +ADR 0019's RNG amendment once restated ADR 0138's Transit start gate (vault BACKLOG #1173, item 3), +and ADR 0173's ODBC test amendment gave its times in two zones and restated its versions and +decision times (vault BACKLOG #3009, PR 2899 notes 3 and 4). SDS-3.5: a fact lives in one place. +""" + +from __future__ import annotations + +from pathlib import Path + +_ADR = Path(__file__).resolve().parent.parent / "docs" / "adr" +_ADR_0019 = _ADR / "0019-pluggable-keyprovider-hsm-kms-vault.md" +_ADR_0173 = ( + _ADR + / "0173-tls-peer-revocation-checking-and-ocsp-stapling-across-terminating-and-originating-surfaces.md" +) + + +def _between(text: str, start: str, end: str) -> str: + head = text.index(start) + return text[head : text.index(end, head)] + + +def test_adr_0019_point_4_does_not_restate_the_transit_gate() -> None: + text = _ADR_0019.read_text(encoding="utf-8") + point_4 = _between( + text, + "4. **Volume wears out a key, not the generator.**", + "**What this statement does not cover.**", + ) + # Stop before any correction note, which names what was removed. + point_4 = point_4.split("*(Corrected", 1)[0] + for restated in ("refuses to start", "logs a warning", "weaker than the counted bound"): + assert restated not in point_4, restated + assert "enforce_transit_bound_attestation" in point_4 # positive control: the pointer stays + assert "0138-transit-bulk-crypto-provider" in point_4 + + +def test_adr_0173_odbc_amendment_states_times_in_one_zone() -> None: + text = _ADR_0173.read_text(encoding="utf-8") + amendment = _between( + text, + "**Amendment 2026-11-11 -- what the ODBC Driver 18 test measured", + "*(End of the amendment of 2026-11-11.", + ) + # The amendment's own body, before the limits and the correction note that names what went. + findings = amendment[: amendment.index("- **The limits.**")] + assert "Central time" not in findings + assert "logged at" not in amendment + assert amendment.count("Windows Server 2022") == 1 + assert "02:22 to 02:25 UTC" in findings # positive control: the UTC times stay + grade_note = _between(text, "*(Note 2026-11-11: two recorded results exist", ")*") + assert "logged at" not in grade_note + assert "d20261112T022118464-c27c39" in grade_note # positive control: the decision stays From 6e4886e39102f1612b8876b83040bdcdd72fbbf6 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sat, 21 Nov 2026 18:16:08 -0600 Subject: [PATCH 07/74] Revocation census: pin the exempt sites and floor both membership tests; name the via-token limit Vault BACKLOG #3512, steps 6 and 12. Step 6: moving a Guarded hop to Exempt and deleting its guard call passed every census test on origin/main (measured with EmailDestination.__init__). _EXEMPT_SITES pins the Exempt set exactly, so that change now fails test_the_exempt_sites_are_the_pinned_list unless the pin moves too. The two census-membership tests each passed alone over an empty scan or an empty census; each now has a floor. The _GUARDS floor was already built by engine PR 2544. Step 12: not fixed. A via token names the module and class, not the function, by the documented choice in operation_token, so a call from cert_expiry.py to pki.make_self_signed adds no token (probed). Closing it needs a token-granularity or taxonomy change; the limit is now named in crypto_operations.py's residual list. Proposed PR title: Revocation census pins its exempt sites and floors its membership tests; crypto residual names the via-token limit (BACKLOG #3512) Proposed banner: PARTIAL - step 6 built (exempt pin, membership floors; _GUARDS floor already met by engine PR 2544). Step 12 declined as a design choice (via-token granularity or a sign/verify split), limit recorded in the crypto_operations residual. --- scripts/security/crypto_operations.py | 4 +++ tests/test_revocation_guard_census.py | 50 +++++++++++++++++++++++++-- 2 files changed, 51 insertions(+), 3 deletions(-) diff --git a/scripts/security/crypto_operations.py b/scripts/security/crypto_operations.py index e2f1c242fe..1d14aa0b2a 100644 --- a/scripts/security/crypto_operations.py +++ b/scripts/security/crypto_operations.py @@ -30,6 +30,10 @@ * a SECOND call to a callee a file already lists. The inventory is kept per file and token, so a new ``hashlib.sha256`` call beside an existing one changes nothing; +* a call to ANOTHER provider in a module a file already reaches, for a class the file already lists + through it. A ``via`` token names the module and the class, not the function, so a call from + ``pipeline/cert_expiry.py`` to ``pki.make_self_signed``, which signs, adds no token beside the + ``sign_verify:via messagefoundry.pki`` its CRL signature check already holds (vault BACKLOG #3512); * an algorithm or TLS value held in a VARIABLE. A token carries the algorithm only when the call names it, in the callee or as a literal or named constant anywhere in its arguments; * a plain ``ctx.options = ...`` or ``setattr(ctx, "options", ...)``. ``options`` is too common a diff --git a/tests/test_revocation_guard_census.py b/tests/test_revocation_guard_census.py index 5cd4f7ec9d..6509154fdf 100644 --- a/tests/test_revocation_guard_census.py +++ b/tests/test_revocation_guard_census.py @@ -34,7 +34,10 @@ renaming either link of the chain from the mount to the Vault guard failed :func:`test_every_guard_name_reaches_a_root`. So did a second def named ``refuse_an_unrevoked_hop`` in another module, and renaming the Vault guard's ``_crossed_unrevoked`` call failed -:func:`test_the_vault_root_decides_through_the_authority`. +:func:`test_the_vault_root_decides_through_the_authority`. Moving the ``EmailDestination.__init__`` +entry from Guarded to Exempt and deleting its ``RevocationHopGuard.capture`` call failed +:func:`test_the_exempt_sites_are_the_pinned_list` and no other test in this file; before that test +existed, the same change passed them all (vault BACKLOG #3512). **The relaxed-hop handoff census** at the end of this file is a second list, of the sites that reach ``relax_verify_expiry`` (vault BACKLOG #5086). ``RevocationHopGuard.capture`` gives no CRL @@ -324,6 +327,31 @@ def __post_init__(self) -> None: ), } +#: The sites :data:`_CENSUS` lists as Exempt, pinned exactly (vault BACKLOG #3512). A Guarded hop +#: moved to Exempt, with its guard call deleted, can pass every other check here (a relaxed +#: hop fails its own census below), so this list is the second edit such a change needs, and review sees it. A diff that +#: edits both still passes. +_EXEMPT_SITES = frozenset( + { + "messagefoundry/apiclient/client.py::_build_verify_context", + "messagefoundry/auth/trust_anchors.py::anchor_cadata", + "messagefoundry/config/tls_policy.py::", + "messagefoundry/config/tls_policy.py::crl_scratch_context", + "messagefoundry/config/tls_probe.py::_offer_context", + "messagefoundry/pki.py::_all_load_as_no_ca", + "messagefoundry/pki.py::_openssl_reads_as_ca", + "messagefoundry/pki.py::_refuse_unless_openssl_loads", + "messagefoundry/transports/http_listener.py::HttpSource.__init__", + "messagefoundry/transports/mllp.py::MLLPSource.__init__", + "messagefoundry/transports/rest.py::_insecure_opener", + "messagefoundry/transports/rest.py::_shared_no_redirect_opener", + "messagefoundry/tray/probe.py::_pinned_context", + "messagefoundry/tray/probe.py::build_verify", + "messagefoundry/verify/federation.py::_idp_opener", + "messagefoundry/verify/smoke.py::live_smoke_ssl_context", + } +) + @dataclass(frozen=True, slots=True) class _Scan: @@ -435,7 +463,11 @@ def _scan() -> _Scan: def test_every_site_is_in_the_census() -> None: """The check that stops the next unguarded hop: a new site fails here until it is classified.""" - unlisted = sorted(_scan().sites - _CENSUS.keys()) + sites = _scan().sites + # 42 sites when this floor was set (vault BACKLOG #3512), so 30 lets twelve go with no edit here. + # It fails a scan that finds nothing, over which the check below would pass. + assert len(sites) >= 30, f"the scan found only {len(sites)} sites, floor 30" + unlisted = sorted(sites - _CENSUS.keys()) assert not unlisted, ( f"verifying client TLS context(s) with no census entry: {unlisted}. Add a guard " f"(RevocationHopGuard.capture, refuse_unrevoked_verified_hop for an https hop, or " @@ -447,6 +479,9 @@ def test_every_site_is_in_the_census() -> None: def test_every_census_entry_is_still_a_site() -> None: """A stale entry would keep an exemption alive for code that no longer exists.""" + # 42 entries when this floor was set (vault BACKLOG #3512). It fails a census emptied, over + # which the check below would pass. + assert len(_CENSUS) >= 30, f"only {len(_CENSUS)} census entries, floor 30" stale = sorted(_CENSUS.keys() - _scan().sites) assert not stale, f"census entries that are no longer a site: {stale}" @@ -456,7 +491,7 @@ def test_every_guarded_site_calls_a_guard() -> None: guarded = {site: entry for site, entry in _CENSUS.items() if isinstance(entry, Guarded)} # 15 sites were Guarded when this floor was set, so 10 lets up to five retire with no edit here. # It is a floor against a census emptied or turned all Exempt, over which the check below would - # pass on nothing. It does not catch a single hop moved from Guarded to Exempt; review does. + # pass on nothing. A single hop moved from Guarded to Exempt is caught by the test below. assert len(guarded) >= 10, f"only {len(guarded)} Guarded census entries, floor 10" unguarded = [ f"{site} (guard expected in {entry.by or 'the site itself'}; {entry.note or 'no note'})" @@ -466,6 +501,15 @@ def test_every_guarded_site_calls_a_guard() -> None: assert not unguarded, f"census sites marked Guarded whose guard call is gone: {unguarded}" +def test_the_exempt_sites_are_the_pinned_list() -> None: + """A Guarded hop moved to Exempt fails here, naming it, unless :data:`_EXEMPT_SITES` moves too.""" + exempt = {site for site, entry in _CENSUS.items() if isinstance(entry, Exempt)} + assert sorted(exempt - _EXEMPT_SITES) == [], "census sites Exempt but not in _EXEMPT_SITES" + assert sorted(_EXEMPT_SITES - exempt) == [], ( + "_EXEMPT_SITES names sites the census does not exempt" + ) + + def _def_count(name: str) -> int: """How many ``def``s named ``name`` the package holds, nested ones and methods included.""" return sum( From 31d9eb40101978645bc4d3802c97c38e5ad48cf0 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sat, 21 Nov 2026 18:19:32 -0600 Subject: [PATCH 08/74] Listeners write a reply_replaced connection event for each altered reply The MLLP, raw-TCP and X12 listeners replace characters a narrow inbound charset cannot encode in their post-commit reply. The WARNING for that is logged once per connection per process, so later altered replies left no record. frame_reply_reporting and encode_reply_reporting now return whether a replacement was made, and each listener writes a `reply_replaced` event with a fixed reason, the MLLP handler-fault NAK included. The kind is declared in connection_events.py and described in PHI.md section 7. BACKLOG #5799 item 1, built as decided under the owner's delegation of 2026-11-21. Tests fail on origin/main (measured by swapping its five source files back). --- .../5799-reply-replaced-event.added.md | 4 ++ docs/PHI.md | 2 +- messagefoundry/connection_events.py | 1 + messagefoundry/transports/framing.py | 40 ++++++++++-- messagefoundry/transports/mllp.py | 40 ++++++++---- messagefoundry/transports/tcp.py | 23 ++++--- messagefoundry/transports/x12.py | 17 ++++- tests/test_mllp_handler_failure.py | 65 +++++++++++++++++++ tests/test_one_frame_one_message.py | 22 ++++++- tests/test_tcp_x12_handler_failure.py | 7 +- 10 files changed, 189 insertions(+), 32 deletions(-) create mode 100644 changelog.d/5799-reply-replaced-event.added.md diff --git a/changelog.d/5799-reply-replaced-event.added.md b/changelog.d/5799-reply-replaced-event.added.md new file mode 100644 index 0000000000..ed2060ae9b --- /dev/null +++ b/changelog.d/5799-reply-replaced-event.added.md @@ -0,0 +1,4 @@ +- The MLLP, raw-TCP and X12 listeners write a `reply_replaced` connection event for each reply in + which characters the inbound's charset cannot encode were replaced before it was sent. The + WARNING log line for a replacement is still written once per connection per process. + [PHI.md](../docs/PHI.md) section 7 says what the event carries. (`BACKLOG #5799`) diff --git a/docs/PHI.md b/docs/PHI.md index b9aaaed809..510ef6f4ec 100644 --- a/docs/PHI.md +++ b/docs/PHI.md @@ -2326,7 +2326,7 @@ with materially different PHI profiles, so they get their own rows; stream 4 is | **4. Off-box syslog/SIEM forwarder** — the shared **transport** for 1–3 | a copy of every record from 1–3 | `forward_format`, default **JSON** (independent of the stdout format) | the operator's collector (`forward_host`/`_port`) | off-box evidence retention / SIEM correlation | **default-on when a collector is named.** Transport: `udp` (default) / `tcp` / **`tls`** (RFC 5425, CA-anchored, verified by default). `serve` gates the hop on the shared posture gradient before the handler is installed: verified TLS ungated; otherwise loopback / attested ALLOW, non-enforcing WARN, **enforcing REFUSE (exit 2)** — there is no synthetic arm, and [ADR 0186](adr/0186-retire-the-synthetic-data-declaration-every-instance-carries-patient-data.md) left this cell with no per-hop way to accept the risk at all | the collector's, not the engine's | the identical handler filters are installed on this handler. So the forwarded copy gets the same best-effort PHI redaction and credential scrub as stdout. A single-token identifier can survive it, as it can there. The copy also carries usernames, connection names, message ids, client addresses and the audit chain. That is the engine's own stated reason for gating the hop | | **5. `audit_log` table** (SQLite, Postgres, SQL Server) | who / what / **where-from** / when of auth + PHI *access* and admin actions — plus, while `[security].audit_all_authorization_decisions` is on (**default `true`** since BACKLOG #1277, 2026-09-02, which reversed the ADR 0118 §5 `false`; the internal field it desugars to is `audit_all_authz`, whose old `[diagnostics]` TOML spelling is **refused at load** — ADR 0118), an `authz` row for **every** authorization decision including successes. That is the shipped volume of this stream, not an opt-in addition to it: one row per authenticated request on each `require()`-gated route, and this row's retention cell records that **nothing prunes the table** — `actor`, `action`, `channel_id`, `client`, `detail`, `row_hash` | JSON `detail`; **tamper-evident hash chain** over `prev_hash` + the row (the `client` address is **inside** the chained payload — ADR 0150) | the store database | HIPAA §164.312(b) audit controls; incident response; `verify_audit_chain` integrity checks | `GET /audit` requires **`audit:read`**; `GET /audit/export` requires the separate **`audit:export`** and streams CSV with formula-injection neutralisation, recording its own `audit.export` row *before* streaming; `GET /me/security-events` is a per-user view of the same table | **`[retention].audit_days` is reserved and NOT enforced — keep-forever by design** (the audit-retention requirement, ~6 years — **not** chain-breakage; [§8](#8-retention--purge) states the position and cites its source of record) | `detail` is stored **in the clear** (it is not a cipher-covered column): its protection is that writers store at least filter shapes, counts, ids, keyed digests, bounded engine-authored text and client addresses, the `audit_log.detail` row above says which — never bodies or credentials — plus the store ACL and the volume layer. *Corrected 2026-10-16 (vault BACKLOG #3145):* this said writers "only ever store filter shapes, counts and ids" | | **6. `message_events` table** | the per-message disposition timeline — the **complete** vocabulary is `received`, `routed`, `unrouted`, `filtered`, `transformed`, `delivered`, `failed`, `dead`, `error`, `replayed`, `resent`, `reingressed`, `passthrough`, `passthrough_dropped`, `cancelled`, `edit_resend`, `edit_resubmit`, `viewed`, `not_deployed`, the ADR 0154 synchronous-reply pair `reply_returned` / `reply_timeout` (names, counts and `waited_ms` only — **never** a fragment of the partner's reply body), and `reply_dropped`, a delivery whose 2xx reply body was over the byte bound and dropped (the status and the bound only, vault BACKLOG #3040) (CI asserts this list against the engine's own `MESSAGE_EVENT_KINDS`). `[diagnostics].message_events` can thin the set, but never below the compliance floor `viewed` / `dead` / `error` / `failed` / `not_deployed` / `reply_timeout` / `reply_dropped` | rows: `message_id`, `ts`, `event`, `destination`, `detail` | the store database | operator timeline on the message-detail view; the `viewed` row is the HIPAA PHI-access record | `GET /messages/{id}` under **`messages:view_raw`** + `require_phi_read`; the read itself writes a `viewed` event **and** a `message_view` audit row | no dedicated window — `purge_message_bodies` sets `message_events.detail` to `NULL` in the same transaction that blanks the body, so it inherits `[retention].messages_days` | `detail` is `safe_text()`-scrubbed **then** cipher-encrypted (AAD `("message_events","detail",message_id,ts,event)`). Verbosity gate `[diagnostics].message_events` = `all` (default) / `errors` / `off`, with a **compliance floor that can never be thinned**: `viewed`, `dead`, `error`, `failed`, `not_deployed`, `reply_timeout`, `reply_dropped` are retained at every level (`reply_timeout` is the one row that explains a "we called you and got a 504" complaint, so an instance that thinned its logs would lose exactly the record it is later asked for; `reply_dropped` is the one row that answers "you ignored our reply", for the same reason) | -| **7. `connection_event` table — DEFAULT ON** (`[diagnostics].connection_events = true`) | transport/lifecycle events per connection: `established`, `closed` (reason `eof`, `idle_timeout` or `frame_deadline` — a fixed vocabulary chosen by the listener, never free text), `idle_timeout`, `at_capacity`, `peer_not_allowlisted`, `frame_oversize`, `framing_error`, `peer_reset`, the MLLP, raw-TCP, X12 and HTTP listeners' and the DATABASE poll source's `handler_error` (BACKLOG #1619, #5022, #5680 for the HTTP listener, which answers it `503` or `500` by the exception's type, as [CONNECTIONS.md Table B](CONNECTIONS.md#table-b--per-service-resource-strategy-asvs-1313) states -- the inbound handler faulted on a frame the listener read cleanly, such as a failed ingress commit; on the X12 listener also, BACKLOG #5971, the engine's own reply to an interchange already recorded could not be encoded in the inbound's charset, so it was not sent; on the DATABASE source, BACKLOG #4921, on a polled row, which is left unmarked and, when the source has a mark statement, stops that poll; the reason is scrubbed at the source like every other), the MLLP and HTTP listeners' `tls_handshake_failed` (vault BACKLOG #2613, #3302 and #3785 -- an inbound TLS handshake failed, on any event loop. **This is the one statement of the failed-handshake throttle, and other pages link here.** The first failure is reported at once, then at most one report per listener per minute, carrying the count since the last report. The reason is a count, an exception class name and OpenSSL's reason mnemonic, never the peer's bytes or certificate. A report names a peer only for a single failure, and only where the listener runs its own handshakes or awaits each one's outcome itself, which the MLLP and HTTP listeners do on every loop (BACKLOG #1606, #2479) and the DICOM C-STORE SCP always does. Such a listener also counts a handshake that runs past its bound. Where only the loop sees them, which is at least the API listener on every loop, the report names no peer, since the loop's hook does not read it (the module docstring of `messagefoundry/tls_handshake_failures.py` says what was measured), and a handshake that only runs past its bound is not counted. A peer that closes or resets the socket mid-handshake is not counted anywhere. That is what a load balancer's TCP health check does. The past-bound and hang-up limits stand by owner ruling 2026-10-26 (vault BACKLOG #3785 items 7 and 8), and that ruling covers only those two. Whether the API's report should name the peer is still an open owner question (vault BACKLOG #3302). The item 8 decline keeps the hang-up counting that came before #3785 and adds none. So a close_notify after the ClientHello is still counted, and the DICOM C-STORE SCP counts it too. A handshake that the listener's own stop ends is not counted. At least every listener also drops a genuine failure that lands once its stop has begun. The DICOM C-STORE SCP drops them for the whole of its server shutdown. On the MLLP and HTTP listeners, a stop that is cancelled before it finishes loses the failures its trailing report still held. The DICOM C-STORE SCP still reports them when its server shutdown raises or is cancelled. The API listener and the DICOM C-STORE SCP write the same report, throttled the same way, as a WARNING log line rather than an event: the API has no connection to carry one, and the SCP emits none (vault BACKLOG #3784)), the DATABASE poll source's `row_undecodable` (BACKLOG #1662 — a polled row the source cannot turn into a body; the reason is scrubbed at the source and names the exception type or the operator's own configured column, never a row value), the FILE poll source's quarantine kinds `file_oversize` / `file_decompress_failed` / `file_content_mismatch` / `file_scan_rejected` (BACKLOG #1621 — a drop moved to `.error`; the reason is a size, a content type or a codec or scanner message, and **that message can still name the file**. The name scrub on both the FILE and REMOTEFILE sources is `safe_exc(exc, file_name=...)`. safe_exc replaces the file name and, at least, its repr, ascii, bytes-repr and JSON-escaped forms. A scanner's `ScanRejected` message that quotes the name in at least another case, without its extension, percent-encoded, in another Unicode normalization, or escaped in a spelling those forms do not produce, such as a JSON escape with uppercase hex digits, keeps that text in the reason (`tests/test_file_source_quarantine_events.py` and `tests/test_remotefile_source_quarantine_events.py` pin this on each source's scan-reject arm), so a scan hook should leave the name out of its message; the REMOTEFILE poll source records the same kinds except `file_decompress_failed`, since it does not decompress), the inbound-HTTP intake-auth refusals `intake_auth_failed` / `auth_subject_denied` / `auth_rate_limited` (ADR 0154 D6 — peer address and mode only, plus, behind a proxy the connection lists in its trusted_proxies setting, the forwarded client address as a forwarded_for suffix on the reason and the audit detail (BACKLOG #5525); **never** the credential, a prefix of it, or its length. Each of these also writes a tamper-evident audit-log row — the copy that survives an operator turning this diagnostics stream off. The MLLP listener writes `auth_subject_denied` and `auth_rate_limited` too, with the same audit rows, when its expected-sender allowlist refuses a sender, naming the peer address and never a certificate field; BACKLOG #4907), plus the runner's `connection_lost` / `connection_restored` / `config_fault`. That is the whole vocabulary, asserted in CI against the literal emit call sites in `transports/` and the pipeline runner **and** against `CONNECTION_EVENT_KINDS` (`messagefoundry/connection_events.py`), the one set the store enforces on write and the console's filter reads (BACKLOG #1624). The MLLP, raw-TCP, X12 and HTTP listeners emit these; the **DATABASE poll source** emits `row_undecodable` and `handler_error` and nothing else (it dials out, so there is no lifecycle to report and its rows carry a **NULL peer column**); the **FILE poll source** emits only its four quarantine kinds, and the **REMOTEFILE poll source** only three of them, both with a NULL peer column; the **DICOM inbound C-STORE SCP** emits none — the runner injects the sink onto **every** source (`wiring_runner.py`, over the base-class `on_connection_event` field), so that connector *has* the wiring and simply never calls it — so this stream covers those four listeners plus those poll-source events and the runner's outbound-lane transitions — not literally every connection. A DICOM association's connects and refusals are therefore **absent** from this stream. The **`ISA`/`IEA`-framed X12 inbound** was equally absent until BACKLOG #1665 and is not any more: it emits the same kinds as the raw-TCP listener | rows: `ts`, `connection`, `transport`, `direction`, `kind`, `peer_host`, `message_id` (correlation hint), `reason` | the store database, **all three backends** | Corepoint-style transport diagnostics — "did the sender connect, and why did it drop" | `GET /events` and `GET /connections/{name}/events` under **`monitoring:read`** (**not** a PHI permission) with per-channel RBAC — an out-of-scope `connection=` is 403'd *and* audited — server-clamped to ≤1000 rows. `reason` alone is gated on `messages:view_summary` and masked as `****` until the audited per-event `reveal=` act (BACKLOG #2443; the `connection_event.reason` row of §3's PL-2 block says how) | `[retention].connection_event_retention_hours` (its own **hours** window); 0 inherits `[retention].messages_days`; both 0 = keep forever. Plain age `DELETE` | **`reason` is free text that can carry sensitive fragments.** Defended twice — `safe_exc()` at the source, `safe_text(reason, limit=200)` at the store (the bound §3's PL-2 block states) — then cipher-encrypted (AAD `("connection_event","reason",connection,ts,kind)`). Every other column is engine or config metadata except `peer_host`, and `reason` is not metadata-only: the [data-at-rest inventory](#2-where-phi-lives--data-at-rest-inventory) grades `reason` and `peer_host` in rows of their own (BACKLOG #5021). Writes are a pure side observer: a bounded in-memory queue drained by a background task outside any handoff transaction, so a flood can never block a listener or pin a message disposition | +| **7. `connection_event` table — DEFAULT ON** (`[diagnostics].connection_events = true`) | transport/lifecycle events per connection: `established`, `closed` (reason `eof`, `idle_timeout` or `frame_deadline` — a fixed vocabulary chosen by the listener, never free text), `idle_timeout`, `at_capacity`, `peer_not_allowlisted`, `frame_oversize`, `framing_error`, `peer_reset`, the MLLP, raw-TCP, X12 and HTTP listeners' and the DATABASE poll source's `handler_error` (BACKLOG #1619, #5022, #5680 for the HTTP listener, which answers it `503` or `500` by the exception's type, as [CONNECTIONS.md Table B](CONNECTIONS.md#table-b--per-service-resource-strategy-asvs-1313) states -- the inbound handler faulted on a frame the listener read cleanly, such as a failed ingress commit; on the X12 listener also, BACKLOG #5971, the engine's own reply to an interchange already recorded could not be encoded in the inbound's charset, so it was not sent; on the DATABASE source, BACKLOG #4921, on a polled row, which is left unmarked and, when the source has a mark statement, stops that poll; the reason is scrubbed at the source like every other), the MLLP, raw-TCP and X12 listeners' `reply_replaced` (BACKLOG #5799 -- the engine's own reply held characters the inbound's charset cannot encode, and each was replaced before the reply was sent; one event per such reply, while the WARNING log line is written once per connection per process; the reason is fixed text that names neither the charset setting nor any part of the reply), the MLLP and HTTP listeners' `tls_handshake_failed` (vault BACKLOG #2613, #3302 and #3785 -- an inbound TLS handshake failed, on any event loop. **This is the one statement of the failed-handshake throttle, and other pages link here.** The first failure is reported at once, then at most one report per listener per minute, carrying the count since the last report. The reason is a count, an exception class name and OpenSSL's reason mnemonic, never the peer's bytes or certificate. A report names a peer only for a single failure, and only where the listener runs its own handshakes or awaits each one's outcome itself, which the MLLP and HTTP listeners do on every loop (BACKLOG #1606, #2479) and the DICOM C-STORE SCP always does. Such a listener also counts a handshake that runs past its bound. Where only the loop sees them, which is at least the API listener on every loop, the report names no peer, since the loop's hook does not read it (the module docstring of `messagefoundry/tls_handshake_failures.py` says what was measured), and a handshake that only runs past its bound is not counted. A peer that closes or resets the socket mid-handshake is not counted anywhere. That is what a load balancer's TCP health check does. The past-bound and hang-up limits stand by owner ruling 2026-10-26 (vault BACKLOG #3785 items 7 and 8), and that ruling covers only those two. Whether the API's report should name the peer is still an open owner question (vault BACKLOG #3302). The item 8 decline keeps the hang-up counting that came before #3785 and adds none. So a close_notify after the ClientHello is still counted, and the DICOM C-STORE SCP counts it too. A handshake that the listener's own stop ends is not counted. At least every listener also drops a genuine failure that lands once its stop has begun. The DICOM C-STORE SCP drops them for the whole of its server shutdown. On the MLLP and HTTP listeners, a stop that is cancelled before it finishes loses the failures its trailing report still held. The DICOM C-STORE SCP still reports them when its server shutdown raises or is cancelled. The API listener and the DICOM C-STORE SCP write the same report, throttled the same way, as a WARNING log line rather than an event: the API has no connection to carry one, and the SCP emits none (vault BACKLOG #3784)), the DATABASE poll source's `row_undecodable` (BACKLOG #1662 — a polled row the source cannot turn into a body; the reason is scrubbed at the source and names the exception type or the operator's own configured column, never a row value), the FILE poll source's quarantine kinds `file_oversize` / `file_decompress_failed` / `file_content_mismatch` / `file_scan_rejected` (BACKLOG #1621 — a drop moved to `.error`; the reason is a size, a content type or a codec or scanner message, and **that message can still name the file**. The name scrub on both the FILE and REMOTEFILE sources is `safe_exc(exc, file_name=...)`. safe_exc replaces the file name and, at least, its repr, ascii, bytes-repr and JSON-escaped forms. A scanner's `ScanRejected` message that quotes the name in at least another case, without its extension, percent-encoded, in another Unicode normalization, or escaped in a spelling those forms do not produce, such as a JSON escape with uppercase hex digits, keeps that text in the reason (`tests/test_file_source_quarantine_events.py` and `tests/test_remotefile_source_quarantine_events.py` pin this on each source's scan-reject arm), so a scan hook should leave the name out of its message; the REMOTEFILE poll source records the same kinds except `file_decompress_failed`, since it does not decompress), the inbound-HTTP intake-auth refusals `intake_auth_failed` / `auth_subject_denied` / `auth_rate_limited` (ADR 0154 D6 — peer address and mode only, plus, behind a proxy the connection lists in its trusted_proxies setting, the forwarded client address as a forwarded_for suffix on the reason and the audit detail (BACKLOG #5525); **never** the credential, a prefix of it, or its length. Each of these also writes a tamper-evident audit-log row — the copy that survives an operator turning this diagnostics stream off. The MLLP listener writes `auth_subject_denied` and `auth_rate_limited` too, with the same audit rows, when its expected-sender allowlist refuses a sender, naming the peer address and never a certificate field; BACKLOG #4907), plus the runner's `connection_lost` / `connection_restored` / `config_fault`. That is the whole vocabulary, asserted in CI against the literal emit call sites in `transports/` and the pipeline runner **and** against `CONNECTION_EVENT_KINDS` (`messagefoundry/connection_events.py`), the one set the store enforces on write and the console's filter reads (BACKLOG #1624). The MLLP, raw-TCP, X12 and HTTP listeners emit these; the **DATABASE poll source** emits `row_undecodable` and `handler_error` and nothing else (it dials out, so there is no lifecycle to report and its rows carry a **NULL peer column**); the **FILE poll source** emits only its four quarantine kinds, and the **REMOTEFILE poll source** only three of them, both with a NULL peer column; the **DICOM inbound C-STORE SCP** emits none — the runner injects the sink onto **every** source (`wiring_runner.py`, over the base-class `on_connection_event` field), so that connector *has* the wiring and simply never calls it — so this stream covers those four listeners plus those poll-source events and the runner's outbound-lane transitions — not literally every connection. A DICOM association's connects and refusals are therefore **absent** from this stream. The **`ISA`/`IEA`-framed X12 inbound** was equally absent until BACKLOG #1665 and is not any more: it emits the same kinds as the raw-TCP listener | rows: `ts`, `connection`, `transport`, `direction`, `kind`, `peer_host`, `message_id` (correlation hint), `reason` | the store database, **all three backends** | Corepoint-style transport diagnostics — "did the sender connect, and why did it drop" | `GET /events` and `GET /connections/{name}/events` under **`monitoring:read`** (**not** a PHI permission) with per-channel RBAC — an out-of-scope `connection=` is 403'd *and* audited — server-clamped to ≤1000 rows. `reason` alone is gated on `messages:view_summary` and masked as `****` until the audited per-event `reveal=` act (BACKLOG #2443; the `connection_event.reason` row of §3's PL-2 block says how) | `[retention].connection_event_retention_hours` (its own **hours** window); 0 inherits `[retention].messages_days`; both 0 = keep forever. Plain age `DELETE` | **`reason` is free text that can carry sensitive fragments.** Defended twice — `safe_exc()` at the source, `safe_text(reason, limit=200)` at the store (the bound §3's PL-2 block states) — then cipher-encrypted (AAD `("connection_event","reason",connection,ts,kind)`). Every other column is engine or config metadata except `peer_host`, and `reason` is not metadata-only: the [data-at-rest inventory](#2-where-phi-lives--data-at-rest-inventory) grades `reason` and `peer_host` in rows of their own (BACKLOG #5021). Writes are a pure side observer: a bounded in-memory queue drained by a background task outside any handoff transaction, so a flood can never block a listener or pin a message disposition | | **8. `alert_instance` table — default on wherever an `[alerts]` notifier exists** | resolvable operator alerts: `connection_stopped`, `queue_buildup`, `lane_stuck`, `message_stall`, `saturation`, `connection_error`, `connection_error.config_fault`, `storage_threshold`, `cert_expiry`, `secret_rotation`, `initial_credential_expiring` (an UNCLAIMED admin-issued temporary password nearing the instant the login gate stops accepting it -- ASVS 6.4.5, BACKLOG #1141; keyed on `user:`, and the payload is the ISO deadline plus whole hours remaining, repeated in the reason column, never the password), `integrity_drift`, `update_available`, `backup_failed`, `store_privilege_warning` (the store privilege preflight found the store principal over-granted or could not read it -- BACKLOG #305; the payload is the finding, a count and the preflight's summary line, which names the login, the database and role names, never a password or message content), `vault_privilege_warning` (the Vault privilege preflight found a Vault token over-granted or could not read it -- BACKLOG #2903, ADR 0216; keyed on `vault:store` or `vault:secrets`, and the payload is the finding, a count of refusing-class grants and the hop's judgment, which names policy names, paths and capabilities, never a token, an accessor, a digest of either or message content), `leadership_acquired`, `dr_activated`, `log_write_failed` (an application-log sink was rolled after a write failure, or is UNWRITABLE and this process's connections were stopped -- BACKLOG #122, ADR 0162; the payload is the sink LABEL, the stage, a `safe_exc` reason and a count of connections stopped, never the record whose write failed), `log_forward_failed` (the off-box log forwarder is absent, losing records or not sending -- BACKLOG #2612; keyed on `forwarder:`, with `@node:` or `@shard:` appended when several engine processes share the store, and the payload is that key, fixed reason words and a count, never a record, the collector's address or an error text; an unpinned cluster node's `node_id` holds this engine's own host name and process id, so the key carries them), `gcm_invocations` (the per-key AES-GCM invocation bound crossing its 2^31 soft warn — ASVS 11.3.4; its payload carries a one-way `key_id` fingerprint plus counters, never key bytes), `approval_stale_requester` (a dual-control release refused because the requester no longer holds the authority the operation needs -- ASVS 8.3.2, BACKLOG #289; keyed on the approval id, and the payload is that id, the operation key and a closed-set reason slug, never the requester's name or the captured params), `approval_too_early` (a dual-control release refused because it arrived before `[approvals].min_dwell_seconds` -- ASVS 2.4.2, BACKLOG #287; keyed on `approval:`, and the payload is that key, the operation key and a fixed reason string, never the approver's or requester's name or the captured params), `audit_write_failed` (the approval gate could not write one of its audit rows -- vault BACKLOG #2255; keyed on `approval:`, on `approval::resolve` for a resolution's lost provenance row -- vault BACKLOG #3438, on the fixed `approval:listing` for a queue listing's lost `approval.standing_shown` row -- vault BACKLOG #3747, on `config_reload:inline` when an ungated config reload could not write its `config_reload_attempted` row -- vault BACKLOG #2254, or on `step_up_return:audit_budget:` when the IdP step-up return audit budget's backstop stopped a row -- BACKLOG #3965, or on `directory-reconciler:` when a directory reconcile pass that completed could not write a row -- BACKLOG #3018 step 2, or on `directory-sign-in:` when a directory sign-in's role-sync row was refused twice -- BACKLOG #2221; the payload is that key and the lost row's audit action name, never the row's detail, a username or the captured params; the ERROR log line beside it holds the detail on some paths and only the exception on others), `audit_offbox_copy_missing` (an approval audit row whose write the gate read back as committed, whose off-box copy was never sent -- vault BACKLOG #3193; keyed on `approval:`, and the payload is that key and the row's audit action name, never the row's detail, a username or the captured params), `ad_reconcile_aborted` (a directory reconciler pass left signed-in accounts unrevoked and needs an operator: the mass-revoke breaker tripped and nothing was revoked, or one or more probes were answered with an LDAP referral and those accounts were left unjudged while the rest of the pass was applied, BACKLOG #2538, or one or more probes raised a fault the engine could not read and those accounts were left unjudged the same way, BACKLOG #3100, or the directory refused one or more probes with a result code that points at the configuration, such as a deleted search base, and those accounts were left unjudged the same way, vault BACKLOG #3010, or an account's group search was refused for the engine's own deadline or cap, so a role or scope change in the directory does not revoke that account's sessions, though a disable or deletion still does, vault BACKLOG #3696, or every lookup failed to reach the directory for `[auth].ad_reconcile_outage_passes` passes running, BACKLOG #3709; for the breaker, a referral, a probe fault, a configuration refusal and a lasting outage the payload is a fixed source label, `directory-reconciler` for the breaker, `directory-reconciler-referral` for a referral, `directory-reconciler-probe-fault` for a probe fault, `directory-reconciler-misconfigured` for a configuration refusal and `directory-reconciler-outage` for a lasting outage so each is its own instance, the closed-set reason slug `mass_revoke_breaker`, `directory_referral`, `probe_fault`, `directory_misconfigured` or `directory_unavailable`, a count (the accounts the breaker judged, or for each of the other four the lookups the pass sent, which leaves out an id-less row -- vault BACKLOG #3170) and the latched operator explanation, or for a lasting outage a fixed sentence with the run's length, never a username; a paging refusal is instead keyed on that operator account's username, as `directory-reconciler-paging:`, so each account is its own instance, raised as the account enters that state and again after a restart while it stands, and the payload is that key, the closed-set reason slug `group_search_deadline` or `group_search_cap`, the same count as the breaker's and a fixed sentence naming the cause, never anything else about the account; an account the directory keeps failing to answer for is keyed the same way, as `directory-reconciler-unreached:`, raised as it enters that state, and its payload is that key, the closed-set reason slug `account_unreachable`, the count of lookups the pass sent and a fixed sentence with two numbers, how many probes failed and the most recent probes its window can hold (faults aside), never anything else about the account -- vault BACKLOG #3100, #3709; on a rolled-up pass, those entering page as one instance under the bare `directory-reconciler-unreached` source, with no username, and the `ad_reconcile_outage_passes` row of [CONFIGURATION.md](CONFIGURATION.md) states when), `ad_reconcile_held` (the reconciler is holding accounts whose `userAccountControl` it cannot read, ADR 0195; the payload is the same fixed source label, a closed-set reason slug, the count of undetermined accounts and the latched operator explanation, never a username), `ad_session_revoked` (the reconciler revoked a directory principal's sessions; keyed on that operator account's username, with at least a `directory_absent`, `directory_disabled`, `directory_undetermined`, `directory_object_id_missing`, `roles_changed` or `scope_changed` reason), `approval_approver_provenance` (a dual-control release, or the resolution of an interrupted one, went ahead with an approver or resolver account created, re-passworded or TOTP-enrolled after the request -- BACKLOG #315, #2125; keyed on `approval:`, or `approval::resolve` for a resolution, and the payload is the operation key and the closed-set change slugs, never a username or the captured params), `administrator_granted` (the built-in Administrator role was granted by account creation, a role change, a directory group newly mapped to it -- BACKLOG #315 --, a directory sign-in whose role sync newly gave the account the role -- vault BACKLOG #2610 -- or a directory reconcile pass whose role re-diff did -- vault BACKLOG #3141; keyed on `user:` or `ad-group:`, with the grant route and the granting administrator's username, or `` for a directory sign-in or reconcile pass), `no_enabled_administrator` (a directory sign-in's role sync or the session reconciler took Administrator from its last enabled holder -- vault BACKLOG #3229; keyed on `user:`, and the payload is `via`, `ad-sync` or `ad-reconcile`, and a fixed reason sentence, never message content), `intake_paused` (the engine paused intake because the staged backlog went over `[inbound].max_staged_depth` or the SQLite volume fell below `[retention].min_free_disk_mb` -- BACKLOG #290; keyed on `intake:staged_depth` or `intake:disk_floor`, with `@node:` or `@shard:` appended when several engine processes share the store (BACKLOG #2272), and the payload is the reason, a count or a MiB figure, its limit and the store backend's name, never message content), `config_changed` (a start's config differs from the store's baseline: the bytes it loaded, or the directory just after the load -- vault BACKLOG #2597, #3765; keyed on `config:`, and the payload is the two digests, the node and engine shard labels, the action, actor username, time and node of the row the older digest came from, and the `comparison` outcome, never the config directory, a git commit or message content), `crl_reload_refused` (the CRL reload refused a replaced CRL file, so running TLS contexts keep the copy they hold -- vault BACKLOG #2904; keyed on `crl_reload:`, with `@node:` or `@shard:` appended when several engine processes share the store, and the payload is that key, the file's path, a short class token for the remedy, a count of contexts, the engine's own fixed remedy sentence and, when a start would refuse the file too, a `start_refuses` flag, never the refusal's reason, which quotes CRL issuer names and dates; that reason is in the application log, and in the `detail` of the CRL expiry alert once the held copy nears its `nextUpdate`), `remote_debug_refused` (the engine's remote-debugging guard refused scripts that another process injected into the engine process -- vault BACKLOG #2742; keyed on `remote_debug:refused`, with `@node:` or `@shard:` appended when several engine processes share the store, and the payload is that key, the count of scripts refused since the alert was last raised, the count since the process started and a fixed sentence built from the two, never a script's file name, which the injecting process chooses; that name is in the application log, in the guard's WARNING line), `sandbox_worker_refused` (a `[sandbox].mode = "subprocess"` worker was refused because the graph it loaded differs from the engine's, most often a config file edited on disk with no reload -- vault BACKLOG #2724; keyed on the inbound's name, raised once per refusal, and the payload is that name and a fixed sentence naming the cause and the remedy, never a message body or the refusal text, which names config names and digests and is in the application log), `store_restored` (the first `serve` on a store `messagefoundry restore` placed ended every session -- BACKLOG #2614; keyed on `store:restored`, raised once per restore, and the payload is that key; a fixed sentence carrying the archive's age in days, the count of sessions ended, a pointer to `messagefoundry restore --help` and the time of the archive's newest audit row, of which the alert instance's reason column keeps the age, the count and the pointer whole and the time redacted or cut; that time again as `last_audit_at`; and the fixed notice of what a restore rolls back as `rollback_notice` (`messagefoundry/restore_notice.py`, BACKLOG #5094), fixed text the reason column never holds; never an account name or a row's content), and the seven security signals of the audit-stream rule layer -- vault BACKLOG #2613: `signin_failure_burst` (keyed on `signin:`, never the typed username), `access_denied_burst`, `body_view_burst` and `bulk_export` (each keyed on `account:`), `peer_refused_burst` (keyed on `inbound:`, never the refused peer's address), `log_level_debug` (keyed on `logging:debug`) and `posture_loosened` (keyed on `posture:start`, with `@node:` or `@shard:` appended when several engine processes share the store); the payload is a count and a fixed sentence holding a level name, switch names or a username, never a message body, a message id or an audit row's detail. The reachable **inverse** signals — `connection_restored`, `leadership_lost`, `dr_released`, `store_privilege_clean`, `vault_privilege_clean`, `intake_resumed`, `posture_restored` (it resolves `posture_loosened` under the same key, so for the same engine process, when a start records no security loosening in a row marked neither `superseded` nor `baseline_unchecked` and a live posture read then names none -- vault BACKLOG #2613; an unpinned cluster node's key changes on every start, so that node raises the inverse for its own instance as it shuts down; when that instance can still stay open is in [SECURITY.md](SECURITY.md)), `crl_reload_applied` (it resolves `crl_reload_refused` under the same key, so for the same file and the same engine identity, at least once the reload's record no longer holds the refusal, once no hop holds any CRL, and when the reload stops -- vault BACKLOG #2904; it is also raised once per held file outside a CA bundle, at the first pass that judges it with no refusal standing, whether or not an alert is open, so it can resolve nothing, and it then clears one an earlier run under that identity left open -- vault BACKLOG #3543. An alert for a file no hop holds now stays open, and so does one an unpinned cluster node raised, because that node's identity changes on every start; [CONFIGURATION.md](CONFIGURATION.md), *The alert resolves itself*, is the source of record), `ad_reconcile_breaker_cleared`, `ad_reconcile_hold_released` (the last two resolve `ad_reconcile_held` and `ad_reconcile_aborted`, the latter only under the breaker's, the referral's or the lasting outage's source: the probe fault's, the configuration refusal's, a paging refusal's and an unreached account's instances have no inverse; when they do, and where they never do, is stated once in [CONFIGURATION.md](CONFIGURATION.md#when-the-reconcilers-alerts-resolve-themselves) -- BACKLOG #2136) — are never rows here: `_record_state` routes an inverse through `_AUTO_RESOLVE` to `resolve_alert_instances_fenced` (BACKLOG #4916), or `resolve_alert_instances_for` on a store without the fence methods, never to `upsert_alert_instance`. So is `connection_started`, which resolves `connection_stopped` under the bare connection name: the runner raises it only when an operator's start or restart finds an inbound up and no cause it can see still holds the name down in either direction (BACKLOG #1741). Every other start raises nothing, at least an engine start, a committed reload, the scheduler and every alert rule's restart, so an open stop keeps its instance, ack and suspend across them. `AlertSink.connection_started` states the full contract, including the operator starts that still raise nothing. An instance raised under a prefixed stand-in such as `reference:` is never resolved by it. | rows: `event_type`, `connection`, `severity`, `status`, `first_seen`, `last_seen`, `count`, `reason`, `acked_by`, `acked_at`, `resolved_at`, `suspended_until`, `escalation_tier`, `raised_by` (a random per-process id naming the newest raise's writer, BACKLOG #4916; never a host, user or message value) | the store database, **all three backends** | the operator alert list — acknowledge / resolve / suspend. Durable state is recorded **before** any suppression or throttle return, so a muted alert still leaves a record | `GET /alerts/active` under **`monitoring:diagnose`** (**not** a PHI permission) with the same per-channel scope, and `reason` alone gated on `messages:view_summary` and masked as `****` until the audited per-alert `reveal=` act (BACKLOG #2443; the `alert_instance.reason` row of §3's PL-2 block says how); ack/resolve/suspend/**resume** are POSTs on the same tier, and the separate read-only `GET /alerts/rules` view sits on its own gate | shares the connection-event window; **only RESOLVED instances are DELETEd**, by `resolved_at` — retention never ages out an open or acknowledged condition from under an operator; a row can still close with no inverse and no operator, at least through the `intake_paused` staleness sweep (BACKLOG #3269), which resolves another engine process's open or acknowledged pause under the expiry rule in [CONFIGURATION.md](CONFIGURATION.md#alerts), after which retention treats it as any resolved row | **`reason` is free text** taken from the event's internal `_detail` (the `connection_error` reason kept off the wire, BACKLOG #5021), `detail` or `reason`: `safe_text(reason, limit=200)` (the bound §3's PL-2 block states) then cipher-encrypted (AAD `("alert_instance","reason",event_type,connection)` — the de-dup grain, so one AAD covers both the INSERT and the re-fire UPDATE). | | **9. `response` rows with `kind='ack_sent'` — DEFAULT ON** (`[diagnostics].response_sent = true`) | the ACK/NAK the engine returned to an inbound sender, under a sentinel destination `\x1fack:` | rows: `ack_code` (`AA`/`AE`/`AR`/`CA`/`CE`/`CR`), `ack_phase` (`decode`/`parse`/`strict`/`ingest`), `outcome`, `body`, `detail` | the store database | "what did we actually reply, and why" — the operator's answer to a sender disputing an ACK | `GET /messages/{id}/responses` under `messages:read` + `require_phi_read`; the `body` only for a caller who also holds `messages:view_raw` and `messages:view_summary`; every read writes a `response.read` audit row | `body`, `detail` and `resp_headers` are set to `NULL` in place by `purge_message_bodies` on the message-body window, on all three backends | **PHI fail-safe:** the ACK **body** is stored **only when the store cipher is active** — on a keyless store it is `NULL` rather than plaintext — and every NAK passes no body at all, so the offending field value is never persisted. The disposition metadata (`ack_code`/`ack_phase`/`outcome`) is non-PHI and always captured; `detail` is `safe_text`-scrubbed, held to the 200-character bound §3's PL-2 block states, and encrypted | | **10. `[alerts]` webhook transport** (off by default — `webhook_url` unset) | one HTTPS POST per alert, carrying every non-underscore event key as JSON | JSON | the operator's webhook endpoint (Slack/Teams/PagerDuty/custom) | operator notification | **`https` only** — a plaintext `http://` webhook URL is refused at construction. Redirects are refused; an optional `webhook_allowed_hosts` egress allowlist gates the host. A verifying `https` hop off this box also takes the revocation guard at build, on a host the `webhook_allowed_hosts` allowlist admits. An unset or empty allowlist admits every host, an explicit `[]` included, and so does an environment value that splits to no host, such as `""` or `","`. A host off a non-empty allowlist is refused at build, before this guard (BACKLOG #5088). A TOML list keeps its entries as written, so `[""]` or `[","]` is not empty and names no real host, and the build refuses every real host. Under an enforcing or unknown posture the guarded hop is refused unless the `[alerts].webhook_tls_revocation_attested` pair is set ([ADR 0173](adr/0173-tls-peer-revocation-checking-and-ocsp-stapling-across-terminating-and-originating-surfaces.md) states the guard and its levers) | the endpoint's | **carries the alert's `detail`/`reason` free text** for at least `connection_stopped`, `log_write_failed` and `backup_failed` (`safe_exc()`-scrubbed at the emit sites, but **not** re-run through `safe_text` on this path, and a scrubbed reason can still echo a partner's reply text). `connection_error` no longer carries its detail: in its place it sends the exception class (or the fixed token `unnamed error` for a class that is not a plain identifier), beside at least the connection and the kind, and keeps the detail under the internal `_detail` key, which the notifier pops before any transport is handed the event and which the alert instance's stored `reason` (row 8) still keeps (`NotifierAlertSink.connection_error`, BACKLOG #5021). Internal `_`-prefixed keys, at least `_detail`, `_transports`, the per-rule recipients, the rule id and the cooldown, are stripped before send, so recipient addresses never cross the wire | diff --git a/messagefoundry/connection_events.py b/messagefoundry/connection_events.py index 05dc4ba6a4..469b0c0f22 100644 --- a/messagefoundry/connection_events.py +++ b/messagefoundry/connection_events.py @@ -63,6 +63,7 @@ "peer_reset", "framing_error", "handler_error", # BACKLOG #1619 + "reply_replaced", # BACKLOG #5799 "tls_handshake_failed", # vault BACKLOG #2613, #3302 "row_undecodable", # BACKLOG #1662 "file_oversize", # BACKLOG #1621, and the three below diff --git a/messagefoundry/transports/framing.py b/messagefoundry/transports/framing.py index 735fc9ba0e..5801faad10 100644 --- a/messagefoundry/transports/framing.py +++ b/messagefoundry/transports/framing.py @@ -36,6 +36,7 @@ __all__ = [ "FRAMING_CODE", "MULTIPLE_MESSAGES_CODE", + "REPLY_REPLACED_REASON", "FrameError", "FrameByteFault", "FramePayloadError", @@ -49,8 +50,10 @@ "codec_for", "declared_encoding", "encode_reply", + "encode_reply_reporting", "frame_for_delivery", "frame_reply", + "frame_reply_reporting", ] logger = logging.getLogger(__name__) @@ -69,9 +72,18 @@ _reply_fallback_logged: set[str] = set() #: The listeners whose reply-character replacement has been logged, once per connection for the -#: same reason (BACKLOG #5799): a narrow charset meets the same characters on every message. +#: same reason (BACKLOG #5799): a narrow charset meets the same characters on every message. Each +#: replaced reply still writes a ``reply_replaced`` connection event, through the listeners that call +#: :func:`frame_reply_reporting` or :func:`encode_reply_reporting`. _reply_replacement_logged: set[str] = set() +#: The ``reason`` of a ``reply_replaced`` connection event. Fixed text: it names neither the charset +#: setting nor any part of the reply, which echoes the message. +REPLY_REPLACED_REASON = ( + "the reply held characters the inbound charset cannot encode; each was replaced before it " + "was sent" +) + def frame_for_delivery(codec: FrameCodec, payload: str, encoding: str, *, transport: str) -> bytes: """Frame one outbound ``payload`` for the wire, or refuse it permanently (ADR 0205 rule 1). @@ -153,13 +165,21 @@ def frame_reply(codec: FrameCodec, reply: str, encoding: str, *, connection: str the ACK builder already puts in place of an echoed CR or LF. The replacement is on bytes, for the reason :func:`frame_for_delivery` checks bytes. The reply is encoded by :func:`encode_reply`, which says what it does with a charset that cannot hold it.""" - body = encode_reply(reply, encoding, connection=connection) + return frame_reply_reporting(codec, reply, encoding, connection=connection)[0] + + +def frame_reply_reporting( + codec: FrameCodec, reply: str, encoding: str, *, connection: str = "" +) -> tuple[bytes, bool]: + """:func:`frame_reply`, and whether characters the charset cannot hold were replaced, so a + listener can write a ``reply_replaced`` connection event for that reply (BACKLOG #5799).""" + body, replaced = encode_reply_reporting(reply, encoding, connection=connection) if codec.start in body or codec.end in body: logger.warning( "reply held a frame start or end byte; each was replaced by a space before framing" ) # The replacement is the leaf's rule, shared with the test harness's ACK writers. - return codec.frame(codec.neutralise(body)) + return codec.frame(codec.neutralise(body)), replaced def encode_reply(reply: str, encoding: str, *, connection: str = "") -> bytes: @@ -182,6 +202,16 @@ def encode_reply(reply: str, encoding: str, *, connection: str = "") -> bytes: the warning each fallback logs, once per connection for each, since a narrow charset meets the same characters message after message. The charset setting and the reply are never logged: the setting is configuration that may hold anything, and the reply echoes the message.""" + return encode_reply_reporting(reply, encoding, connection=connection)[0] + + +def encode_reply_reporting( + reply: str, encoding: str, *, connection: str = "" +) -> tuple[bytes, bool]: + """:func:`encode_reply`, and whether characters the charset cannot hold were replaced. The + warning is logged once per connection; the flag is set on every reply replaced, for the + listener's ``reply_replaced`` connection event (BACKLOG #5799). A reply sent in ``utf-8`` + because the charset name is unusable is not a replacement, and the flag is False.""" unencodable = False try: body = reply.encode(encoding) @@ -200,8 +230,8 @@ def encode_reply(reply: str, encoding: str, *, connection: str = "") -> bytes: ) body = reply.encode("utf-8") if unencodable: - body = _encode_replacing(reply, encoding, connection) - return body + return _encode_replacing(reply, encoding, connection), True + return body, False def _encode_replacing(reply: str, encoding: str, connection: str) -> bytes: diff --git a/messagefoundry/transports/mllp.py b/messagefoundry/transports/mllp.py index 0749da33a1..0db638f5b9 100644 --- a/messagefoundry/transports/mllp.py +++ b/messagefoundry/transports/mllp.py @@ -130,10 +130,11 @@ from messagefoundry.transports.base import cap_setting as _cap_setting from messagefoundry.transports.framing import ( MLLP_CODEC, + REPLY_REPLACED_REASON, check_frame_bytes, declared_encoding, frame_for_delivery, - frame_reply, + frame_reply_reporting, ) __all__ = [ @@ -3038,9 +3039,10 @@ def _owes_handler_failure_reply(self) -> bool: """ return owes_hl7_reply(self.ack_mode, self.content_type) - def _handler_failure_nak(self, message: bytes) -> bytes | None: + def _handler_failure_nak(self, message: bytes) -> tuple[bytes, bool] | None: """The framed ``AE`` NAK (``CE`` in enhanced mode) for a frame the inbound handler faulted - on, or ``None`` if none can be framed. Call it only when a reply is owed. + on, and whether characters its charset cannot hold were replaced in it, or ``None`` if none + can be framed. Call it only when a reply is owed. **Why AE.** It is this engine's code for "not accepted, and not because of what the message says". The runner answers ``AR`` for every refusal it treats as final and ``AE`` only for a @@ -3074,7 +3076,9 @@ def _handler_failure_nak(self, message: bytes) -> bytes | None: nak = build_ack( inbound, code="AE", text=_HANDLER_FAILURE_NAK_TEXT, ack_mode=self.ack_mode ) - return frame_reply(MLLP_CODEC, nak, self.encoding, connection=self._pacing_name) + return frame_reply_reporting( + MLLP_CODEC, nak, self.encoding, connection=self._pacing_name + ) except Exception as exc: # noqa: BLE001 -- fall back to the defaults, then give up logger.warning( "MLLP-level NAK for a handler fault could not be built: %s", safe_exc(exc) @@ -3114,7 +3118,8 @@ async def _answer_handler_failure( """ reason = safe_exc(exc) owed = self._owes_handler_failure_reply() - nak = self._handler_failure_nak(message) if owed else None + framed = self._handler_failure_nak(message) if owed else None + nak = None if framed is None else framed[0] if nak is not None: outcome = f"answering MSA-1 {_CODES[self.ack_mode]['AE']}, then closing the connection" elif owed: @@ -3131,6 +3136,10 @@ async def _answer_handler_failure( outcome, ) await self._emit_event("handler_error", peer_host=peer_host, reason=reason) + if framed is not None and framed[1]: + await self._emit_event( + "reply_replaced", peer_host=peer_host, reason=REPLY_REPLACED_REASON + ) return owed, nak async def _on_client( @@ -3309,14 +3318,21 @@ async def _on_client( failed = False if reply is not None: # ADR 0205: a reply never carries a second frame boundary. - writer.write( - frame_reply( - MLLP_CODEC, - reply, - self.encoding, - connection=self._pacing_name, - ) + wire, replaced = frame_reply_reporting( + MLLP_CODEC, + reply, + self.encoding, + connection=self._pacing_name, ) + writer.write(wire) + if replaced: + # BACKLOG #5799: the log line is once per connection; the + # event records every reply that was altered. + await self._emit_event( + "reply_replaced", + peer_host=peer_host, + reason=REPLY_REPLACED_REASON, + ) await self._drain_ack(writer) if unlisted and decoded: # BACKLOG #4907: every frame this read completed was recorded above, diff --git a/messagefoundry/transports/tcp.py b/messagefoundry/transports/tcp.py index ff0faec71c..a35786b3c5 100644 --- a/messagefoundry/transports/tcp.py +++ b/messagefoundry/transports/tcp.py @@ -54,13 +54,14 @@ wait_for_intake, ) from messagefoundry.transports.framing import ( + REPLY_REPLACED_REASON, FrameCodec, FrameError, check_frame_bytes, codec_for, declared_encoding, frame_for_delivery, - frame_reply, + frame_reply_reporting, ) from messagefoundry.transports.mllp import ( DEFAULT_MAX_CONNECTIONS, @@ -730,14 +731,20 @@ async def _on_client(self, reader: asyncio.StreamReader, writer: asyncio.StreamW break # handler_error is recorded; close failed = False if reply is not None: - writer.write( - frame_reply( - self.codec, - reply, - self.encoding, - connection=self._pacing_name, - ) + wire, replaced = frame_reply_reporting( + self.codec, + reply, + self.encoding, + connection=self._pacing_name, ) + writer.write(wire) + if replaced: + # BACKLOG #5799, as the MLLP listener records it. + await self._emit_event( + "reply_replaced", + peer_host=peer_host, + reason=REPLY_REPLACED_REASON, + ) await self._drain_reply(writer) if failed: break diff --git a/messagefoundry/transports/x12.py b/messagefoundry/transports/x12.py index 3ed3335186..e9e36f7f36 100644 --- a/messagefoundry/transports/x12.py +++ b/messagefoundry/transports/x12.py @@ -67,7 +67,11 @@ register_source, wait_for_intake, ) -from messagefoundry.transports.framing import declared_encoding, encode_reply +from messagefoundry.transports.framing import ( + REPLY_REPLACED_REASON, + declared_encoding, + encode_reply_reporting, +) from messagefoundry.transports.mllp import ( DEFAULT_MAX_CONNECTIONS, DEFAULT_MAX_CONNECTIONS_PER_HOST, @@ -1037,9 +1041,9 @@ async def _on_client(self, reader: asyncio.StreamReader, writer: asyncio.StreamW # event is sent outside the except clause, so nothing chains the # encode error, whose `object` is the whole reply. reply_fault: str | None = None - wire = b"" + wire, replaced = b"", False try: - wire = encode_reply( + wire, replaced = encode_reply_reporting( reply, self.encoding, connection=self._pacing_name ) except (LookupError, UnicodeError) as exc: @@ -1068,6 +1072,13 @@ async def _on_client(self, reader: asyncio.StreamReader, writer: asyncio.StreamW break continue writer.write(wire) # unframed: the interchange is the frame + if replaced: + # BACKLOG #5799, as the MLLP listener records it. + await self._emit_event( + "reply_replaced", + peer_host=peer_host, + reason=REPLY_REPLACED_REASON, + ) await self._drain_reply(writer) if failed: break diff --git a/tests/test_mllp_handler_failure.py b/tests/test_mllp_handler_failure.py index a72886da5e..0ce27b6733 100644 --- a/tests/test_mllp_handler_failure.py +++ b/tests/test_mllp_handler_failure.py @@ -33,6 +33,7 @@ import pytest import messagefoundry.transports.base as base_mod +import messagefoundry.transports.framing as framing_mod from messagefoundry.config.models import AckMode, ConnectorType, ContentType, Source from messagefoundry.config.settings import EgressSettings from messagefoundry.config.wiring import ConnectionSpec, InboundConnection, Registry @@ -646,6 +647,70 @@ async def narrow(raw: bytes) -> str: assert "framing_error" not in cap.kinds(), cap.kinds() +async def test_each_reply_a_narrow_charset_altered_writes_a_reply_replaced_event( + monkeypatch: pytest.MonkeyPatch, +) -> None: + # BACKLOG #5799 item 1: the replacement's WARNING is logged once per connection per process, so + # without an event the second altered ACK left no record at all. Each altered reply now writes + # one `reply_replaced` event with a fixed reason; a clean reply writes none. Red on the code + # before: the event list holds no `reply_replaced`. + monkeypatch.setattr(framing_mod, "_reply_replacement_logged", set()) + cap = _Capture() + source = _mllp(encoding="ascii") + source.on_connection_event = cap + texts = iter(["café", "plain", "naïve"]) + + async def narrow(raw: bytes) -> str: + return build_ack(raw, code="AA", text=next(texts)) + + await source.start(narrow) + try: + reader, writer = await asyncio.open_connection("127.0.0.1", source.sockport) + for _ in range(3): + writer.write(frame(_ADT)) + await writer.drain() + await _read_reply(reader) + writer.close() + await writer.wait_closed() + finally: + await asyncio.wait_for(source.stop(), timeout=5.0) + replaced = [e for e in cap.events if e[0] == "reply_replaced"] + assert len(replaced) == 2, cap.events + assert all(reason == framing_mod.REPLY_REPLACED_REASON for _, _, reason in replaced) + assert all(host is not None for _, host, _ in replaced) + + +async def test_a_handler_fault_nak_the_charset_altered_writes_a_reply_replaced_event( + monkeypatch: pytest.MonkeyPatch, +) -> None: + # BACKLOG #5799 item 1: the handler-fault NAK echoes the control id, and a byte the ascii + # inbound cannot decode reaches it as a character ascii cannot encode, so the NAK is altered + # too. It writes `reply_replaced` after `handler_error`. Red on the code before: no such event. + monkeypatch.setattr(framing_mod, "_reply_replacement_logged", set()) + cap = _Capture() + source = _mllp(encoding="ascii") + source.on_connection_event = cap + await source.start(_boom) + try: + reader, writer = await asyncio.open_connection("127.0.0.1", source.sockport) + writer.write(frame(_ADT.replace("MSG1", "MSG\xe91").encode("latin-1"))) + await writer.drain() + assert b"MSA|AE|MSG?1|" in await _read_reply(reader) + writer.close() + await writer.wait_closed() + finally: + await asyncio.wait_for(source.stop(), timeout=5.0) + assert cap.kinds()[:3] == ["established", "handler_error", "reply_replaced"], cap.kinds() + + +def test_the_handler_fault_nak_flags_a_replacement_only_when_one_was_made() -> None: + source = _mllp(encoding="ascii") + clean = source._handler_failure_nak(b"MSH|^~\\&|S|F|R|F|20260101||ADT^A01|C1|P|2.5\r") + altered = source._handler_failure_nak(b"MSH|^~\\&|S|F|R|F|20260101||ADT^A01|C\xe91|P|2.5\r") + assert clean is not None and clean[1] is False + assert altered is not None and altered[1] is True + + async def _raise_locked(*args: Any, **kwargs: Any) -> NoReturn: raise RuntimeError("database is locked") diff --git a/tests/test_one_frame_one_message.py b/tests/test_one_frame_one_message.py index e747728952..5d25281c1a 100644 --- a/tests/test_one_frame_one_message.py +++ b/tests/test_one_frame_one_message.py @@ -680,6 +680,22 @@ def test_frame_reply_replaces_what_a_narrow_charset_cannot_hold( assert "utf-8" not in warnings[0] +def test_the_reporting_variants_flag_a_replaced_reply_every_time() -> None: + """BACKLOG #5799 item 1: the warning is once per connection, but the flag a listener writes its + ``reply_replaced`` event from is set on every reply replaced, and on no other. A clean reply and + the utf-8 fallback for an unusable charset name are not replacements.""" + reply = MSH + CR + "MSA|AA|CTRL1|\u00e9" + CR + for _ in range(2): + wire, replaced = framing_mod.frame_reply_reporting( + MLLP_CODEC, reply, "ascii", connection="IB_FLAG" + ) + assert replaced and wire == frame_reply(MLLP_CODEC, reply, "ascii", connection="IB_FLAG") + assert framing_mod.encode_reply_reporting(reply, "ascii", connection="IB_FLAG")[1] + assert not framing_mod.frame_reply_reporting(MLLP_CODEC, CLEAN, "ascii")[1] + assert not framing_mod.encode_reply_reporting(reply, "utf-8")[1] + assert not framing_mod.encode_reply_reporting(reply, "not-a-real-codec")[1] + + @pytest.mark.parametrize( "msh2", ["?~" + BS + "&", "^?" + BS + "&", "^~?&", "^~" + BS + "?"], @@ -842,8 +858,10 @@ async def handler(raw: bytes) -> str: def test_the_mllp_handler_fault_nak_is_one_frame_when_the_header_holds_a_start_byte() -> None: source = MLLPSource(Source(type=ConnectorType.MLLP, settings={"host": "127.0.0.1", "port": 0})) header = f"MSH|{ENC}|S|F|R|F|20260101||ADT^A01|C{SB}1|P|2.5{CR}" - nak = source._handler_failure_nak(header.encode("utf-8")) - assert nak is not None and nak.count(b"\x0b") == 1 and nak.count(b"\x1c") == 1 + framed = source._handler_failure_nak(header.encode("utf-8")) + assert framed is not None + nak = framed[0] + assert nak.count(b"\x0b") == 1 and nak.count(b"\x1c") == 1 async def test_the_tcp_listener_sends_one_frame_when_its_reply_holds_its_start_byte() -> None: diff --git a/tests/test_tcp_x12_handler_failure.py b/tests/test_tcp_x12_handler_failure.py index 7d7a021597..2b31950b46 100644 --- a/tests/test_tcp_x12_handler_failure.py +++ b/tests/test_tcp_x12_handler_failure.py @@ -391,6 +391,10 @@ async def handler(raw: bytes) -> str: assert "framing_error" not in _kinds(events), name sent = b"".join(writer.written) assert b"MSA|AA|C1|note ?" in sent, name + # BACKLOG #5799 item 1: the altered reply is recorded as an event, not only in the warn-once + # log line. Red on the code before: no `reply_replaced` in the events. + replaced = [e for e in events if e[0] == "reply_replaced"] + assert [reason for _, _, reason in replaced] == [framing_mod.REPLY_REPLACED_REASON], name async def test_an_x12_reply_in_an_unusable_charset_name_is_sent_in_utf8( @@ -478,7 +482,8 @@ async def narrow_reply(raw: bytes) -> str: events = await _drive(source, _ThenEof(EDI * 2), writer, handler=narrow_reply) assert seen == [EDI] * 2 assert writer.written == [b"synthetic reply ?"] * 2 - assert _kinds(events) == ["established", "closed"] + # One `reply_replaced` per altered reply (BACKLOG #5799 item 1). + assert _kinds(events) == ["established", "reply_replaced", "reply_replaced", "closed"] assert_capture_sees(caplog, "messagefoundry.transports.x12") assert not [r for r in caplog.records if r.levelno >= logging.ERROR] From cd2eefa3f006a1175e089a63d2a9e70a1845988c Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sat, 21 Nov 2026 18:19:37 -0600 Subject: [PATCH 09/74] Stage dispatcher test 8 re-readies a stranded lane; FIFO test waits on storage BACKLOG #3456 (batch 453). - tests/test_stage_dispatcher.py: test 8's 30-round drive loop never re-readied a lane. In the three SQL Server 2025 logs read (jobs 115089711377, 118344840905, 120753069373), all four lanes fault once and only IB_OUTAGE_3 faults again, which is what a lane stranded in T12 terminal IDLE after an EMPTY claim shows, with the sweep disabled. The logs do not show the lock-timeout line itself (INFO, not captured), so that is a reading, not a proven cause. _drive_lanes_to_stop bounds the drive by wall time and re-readies a stranded lane under the existing capped, warned stand-in. A new sqlite arm injects the abort with _ClaimShim; the old loop fails it (all four lanes one fault, then stuck), the new one passes 10 of 10. - tests/test_per_lane_wake.py: the FIFO test writes the next file only once the last is stored, instead of sleeping 0.05 s. --- tests/test_per_lane_wake.py | 19 +++---- tests/test_stage_dispatcher.py | 95 ++++++++++++++++++++++++++++------ 2 files changed, 87 insertions(+), 27 deletions(-) diff --git a/tests/test_per_lane_wake.py b/tests/test_per_lane_wake.py index b07692f5f0..7fa3b6b01e 100644 --- a/tests/test_per_lane_wake.py +++ b/tests/test_per_lane_wake.py @@ -368,12 +368,14 @@ async def test_multi_message_fifo_order_preserved_under_per_lane_wake( try: for i in range(3): (inbox / f"m{i}.hl7").write_bytes(ADT.format(cid=f"MSG{i}").encode("utf-8")) - await asyncio.sleep(0.05) # keep arrival order deterministic + # Arrival order: the next file is written only once this one is stored, which a fixed + # sleep did not ensure on a runner whose poll ran late (BACKLOG #3456). + await _until(lambda n=i + 1: _n_messages(store, n)) # Poll the ACTUAL asserted condition — all 3 messages finalized to PROCESSED — not a proxy like # "N outbound rows DONE" (each message fans out to 2, so that proxy trips at 1.5 messages; it # false-greened on a fast runner and flaked on a slow one — mf-ci-test-flakes). try: - await _until(lambda: _n_processed(store, 3)) + await _until(lambda: _n_messages(store, 3, MessageStatus.PROCESSED.value)) except AssertionError as exc: # Print how far each message got. ROUTED covers both transform and delivery, so this # separates intake from the later stages, not transform from delivery. @@ -391,15 +393,10 @@ async def test_multi_message_fifo_order_preserved_under_per_lane_wake( assert [row["control_id"] for row in await cur.fetchall()] == ["MSG0", "MSG1", "MSG2"] -async def _n_processed(store: MessageStore, n: int) -> bool: - return ( - len( - await store.list_messages( - channel_id="file_in", status=MessageStatus.PROCESSED.value, allowed_channels=None - ) - ) - >= n - ) +async def _n_messages(store: MessageStore, n: int, status: str | None = None) -> bool: + """At least ``n`` messages on the inbound, any status when ``status`` is None.""" + msgs = await store.list_messages(channel_id="file_in", status=status, allowed_channels=None) + return len(msgs) >= n # --- env-flag plumbing (AC-12) ---------------------------------------------- diff --git a/tests/test_stage_dispatcher.py b/tests/test_stage_dispatcher.py index a0746c80bf..0bc077a841 100644 --- a/tests/test_stage_dispatcher.py +++ b/tests/test_stage_dispatcher.py @@ -2335,10 +2335,48 @@ async def test_adr0070_7_reload_resumes_idempotently(store: Any) -> None: await d.stop() -async def test_adr0070_8_correlated_outage_single_reload_rearms_all(store: Any) -> None: - """ADR 0070 test 8: N lanes STOP under one (store-down-style) root cause; each emits its own - connection_stopped (ADR-0044 durable dedup collapses them to one operator signal downstream), and a - SINGLE ``notify_work`` reload broadcast re-arms ALL of them with the streak reset.""" +async def _drive_lanes_to_stop( + d: StageDispatcher, mc: ManualClock, lanes: list[str], *, timeout: float = 30.0 +) -> None: + """Fire every due park timer until each of ``lanes`` is STOPPED, bounded by real time. + + The loop this replaced ran 30 rounds and never re-readied a lane, and it failed on the SQL + Server 2025 leg (BACKLOG #3456, four hits). Each captured log shows the same pattern: all four + lanes fault once, and only ``IB_OUTAGE_3`` faults again. A lane parked after its first fault + whose re-claim comes back EMPTY takes T12: ``phase=IDLE`` with no timer. The sweep that would + re-ready it is disabled here, so no clock advance re-claims it. That fits what `_wait_lane` + stands in for (a swallowed 1222). The logs do not show it as the cause: the dispatcher's + lock-timeout line is INFO and was not captured. So a stranded lane is re-readied under the + same capped, warned allowance, and the loop's bound is a wall-clock ceiling, not a round count. + """ + + def all_stopped() -> bool: + return all(d.phase(ln) is _LanePhase.STOPPED for ln in lanes) + + loop = asyncio.get_running_loop() + deadline = loop.time() + timeout + while loop.time() < deadline: + if all_stopped(): + return + for ln in lanes: + # IDLE is never a waypoint on this path (PARKED -> READY -> CLAIMING -> PROCESSING -> + # PARKED or STOPPED), so an IDLE lane with no timer is a stranding. + if _terminal_idle(d, ln): + await _stand_in_for_sweep(d, ln) + mc.advance(120.0) # past every lane's capped backoff, so every armed park timer fires + await _settle(rounds=4) + if all_stopped(): + return + phases = {ln: d.phase(ln) for ln in lanes} + raise _WaitTimeout( + f"not every lane STOPPED within {timeout:g}s: {phases!r}\n" + + await _expiry_report(all_stopped) + ) + + +async def _correlated_outage_rearms_all(store: Any, *, abort_second_claim: bool) -> None: + """The body of ADR 0070 test 8. ``abort_second_claim`` aborts the claim that follows the + first fault on a store lock timeout, the shape SQL Server returns on a 1222.""" mc = ManualClock(1000.0) stub = RecordingStub(store, mc.time) stub.set_policy(_always_raise) # the shared root cause: every lane's handoff raises @@ -2346,22 +2384,26 @@ async def test_adr0070_8_correlated_outage_single_reload_rearms_all(store: Any) lanes = [f"IB_OUTAGE_{i}" for i in range(4)] for lane in lanes: await _seed(store, lane, [100.0]) - d = _make(store, stub, set(), clock=mc, alert_sink=alert, infra_fault_stop_after=2) + shim = _ClaimShim( + store, lanes[0], mode="lock_timeout_once", extra_lanes=frozenset(lanes[1:]), times=0 + ) # armed by hand below + d = _make(shim, stub, set(), clock=mc, alert_sink=alert, infra_fault_stop_after=2) await d.start() try: for lane in lanes: d.mark_ready(lane) - # Drive every lane to STOP (stop_after=2 → two faults each). GENEROUSLY bounded, not a fixed - # round count: the slow SQL Server 2025 async needs more advance/settle rounds than - # SQLite/SS-2022 to march all four lanes through both faults + the STOP latch. Each round fires - # the (due) park timers and settles; once a lane STOPs it stays STOPPED, so the loop just needs - # enough rounds for the slowest lane — 30 is far past the ~2 a fast backend takes. - for _ in range(30): - if all(d.phase(ln) == _LanePhase.STOPPED for ln in lanes): - break - mc.advance(120.0) # past every lane's capped backoff → fire all park timers - await _settle(rounds=20) - assert all(d.phase(ln) == _LanePhase.STOPPED for ln in lanes) + if abort_second_claim: + for lane in lanes: + await _wait_lane(d, lane, _LanePhase.PARKED) # each lane's first fault + shim._remaining = 1 + # Drive every lane to STOP (stop_after=2 → two faults each). + await _drive_lanes_to_stop(d, mc, lanes) + if abort_second_claim: + assert shim._remaining == 0, "the armed abort never reached a claim" + assert d.claim_lock_timeouts >= 1 + assert any(_sweep_standins(ln) for ln in lanes), ( + "the abort stranded no lane, so this arm did not exercise the stand-in" + ) # Each stopped lane emitted its own connection_stopped (the dedup is downstream, ADR 0044). assert {name for name, _ in alert.stopped} == set(lanes) @@ -2382,6 +2424,27 @@ async def test_adr0070_8_correlated_outage_single_reload_rearms_all(store: Any) await d.stop() +async def test_adr0070_8_correlated_outage_single_reload_rearms_all(store: Any) -> None: + """ADR 0070 test 8: N lanes STOP under one (store-down-style) root cause; each emits its own + connection_stopped (ADR-0044 durable dedup collapses them to one operator signal downstream), and a + SINGLE ``notify_work`` reload broadcast re-arms ALL of them with the streak reset.""" + await _correlated_outage_rearms_all(store, abort_second_claim=False) + + +async def test_adr0070_8_correlated_outage_survives_an_aborted_reclaim(store: Any) -> None: + """Test 8 with the claim after every lane's first fault aborted on a lock timeout, which + strands the lanes it covered in terminal IDLE. The 30-round loop `_drive_lanes_to_stop` + replaced fails this arm, because nothing re-claims a stranded lane, and each lane then shows + one fault, as three of the four did in the SQL Server 2025 logs. + + SQLite only: the abort is injected, so the backend adds nothing, and a server's own 1222 on + top of it would spend a lane's single stand-in twice.""" + if store._test_backend != "sqlite": + pytest.skip("the injected abort is backend-independent; one real 1222 more breaks the cap") + with pytest.warns(UserWarning, match="sweep stand-in"): + await _correlated_outage_rearms_all(store, abort_second_claim=True) + + async def test_adr0070_9_content_retry_is_not_an_infra_fault(store: Any) -> None: """ADR 0070 test 9 (sharp edge 2 — the discriminator): a repeated CONTENT retry (the body ``mark_failed``s its head — a message-content re-pend, ``i==0`` / ``made_progress=False``) must NOT From c46bda6e7aa5b07468580490efebc6bca6f6f68c Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sat, 21 Nov 2026 18:20:37 -0600 Subject: [PATCH 10/74] Review round 1: the escape tests write their characters as escapes and prove their check can fail From the xhigh review of round-9f857a8b on this branch: - The hostile string held a literal U+202E and U+2028 in the source; it now spells every character as an escape, so the file is ASCII again. - The result test builds its report from _unobservable_report() with the postgres backend the service config names. - The escapes asserted are derived from the hostile string, the check is one isascii/isprintable assert, and a control test proves it fails on output written without ensure_ascii. - The comment no longer says a terminal acts on DEL; it says which of the characters json.dumps escapes only under ensure_ascii. Vault BACKLOG #2891, PR 2390 note 3. Proposed PR title: Batch 284: check-privileges --json escape tests; route-walk items already met Proposed banners: - #2891: PR 2390 note 3 met with a test. Open, unchanged: note 2 (and item 4, the terminal_text.py docstring tied to it) waits on an owner ruling; the other PR 2390 notes as the row records them. - #3177: added items 5 to 15 read met at engine main by PR 3015 (cd0a4a2f907), checked against the code and tests: 5, 6, 11, 12 fixed with tests; 7, 10, 13, 14, 15 fixed in docstrings and tests; 8 kept as the refusal (a mount cycle raises RecursionError, pinned by a test); 9 kept because a served app nests a handful of mounts and one walk per level keeps the refusal free of shared state. PR 3015's own open findings were left for the Lander to file under R2; where they landed is not checked here. --- tests/test_store_privilege_check.py | 34 +++++++++++++++-------------- 1 file changed, 18 insertions(+), 16 deletions(-) diff --git a/tests/test_store_privilege_check.py b/tests/test_store_privilege_check.py index c0c36e9123..c6ee1e24b2 100644 --- a/tests/test_store_privilege_check.py +++ b/tests/test_store_privilege_check.py @@ -631,32 +631,34 @@ def test_cli_json_reports_every_family_and_no_secret( assert by_hop["smtp"]["state"] == "not_probed" -#: ESC, DEL, a C1 control (CSI), RIGHT-TO-LEFT OVERRIDE and LINE SEPARATOR: each one a terminal or -#: a line reader acts on. ``--json`` output must carry them as ``\uXXXX`` escapes (BACKLOG #2891, -#: PR 2390 note 3). -_HOSTILE = "a\x1b[31mb\x7fc\x9bd‮e
f" +#: ESC, DEL, a C1 control (CSI), RIGHT-TO-LEFT OVERRIDE and LINE SEPARATOR. ``json.dumps`` always +#: escapes ESC; it escapes the other four only under ``ensure_ascii``, so ``--json`` output must +#: carry each as a ``\uXXXX`` escape (BACKLOG #2891, PR 2390 note 3). +_HOSTILE = "a\x1b[31mb\x7fc\x9bd\u202ee\u2028f" def _assert_escaped(out: str) -> None: - assert out.isascii(), f"--json output carries a non-ASCII character: {out!r}" - controls = [ch for ch in out.rstrip("\n") if ch < " " or ch == "\x7f"] - assert not controls, f"--json output carries a control: {out!r}" - for escape in ("\\u001b", "\\u007f", "\\u009b", "\\u202e", "\\u2028"): - assert escape in out + line = out.rstrip("\n") + assert line.isascii() and line.isprintable(), f"--json output carries a raw character: {out!r}" + for ch in sorted({ch for ch in _HOSTILE if not (ch.isascii() and ch.isprintable())}): + assert f"\\u{ord(ch):04x}" in out, f"--json output lacks the escape for {ch!r}: {out!r}" + + +def test_the_escape_assertion_fails_on_unescaped_json() -> None: + """The control for :func:`_assert_escaped`: output written without ``ensure_ascii`` fails it.""" + with pytest.raises(AssertionError): + _assert_escaped(json.dumps({"error": _HOSTILE}, ensure_ascii=False)) + _assert_escaped(json.dumps({"error": _HOSTILE})) def test_cli_json_result_escapes_controls_and_bidi_in_a_detail( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] ) -> None: _clear_env(monkeypatch) - _stub_probe( - monkeypatch, - StorePrivilegeReport( - backend=StoreBackend.SQLSERVER, - status=StorePrivilegeStatus.UNOBSERVABLE, - detail=_HOSTILE, - ), + report = dataclasses.replace( + _unobservable_report(), backend=StoreBackend.POSTGRES, detail=_HOSTILE ) + _stub_probe(monkeypatch, report) argv = ["check-privileges", "--service-config", str(_server_toml(tmp_path)), "--json"] assert main(argv) == 4 out = capsys.readouterr().out From de953b9a88258158454bae4cec95bab9bf5498a3 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sat, 21 Nov 2026 18:20:50 -0600 Subject: [PATCH 11/74] Record route-body step-up refusals as auth.gate_refused A proof_in_route gate writes auth.permission_granted, then the route body spends the bound proof (spend_step_up_action) or checks the session window (refuse_unless_step_up_window_live). A refusal there left the grant row and no row for the refusal. The gate now leaves what it admitted on request.state, and both route body refusals write auth.gate_refused through the writer the gates' own decision block uses, naming the same permission and reason step_up, only where the gate wrote a grant row. A failed row write raises in place of the refusal, as in the decision block, so the request is still refused. BACKLOG #1197 (ASVS 16.3.2), steps 1 and 2 of the steps added 2026-11-06 from engine PR 2808 finding 2. Proposed PR title: Route-body step-up refusals write an audit row (BACKLOG #1197) Proposed ledger banner for #1197: PARTIAL, stays open. Steps 1 and 2 of the 2026-11-06 added steps are built: the proof_in_route spends through spend_step_up_action and refuse_unless_step_up_window_live write auth.gate_refused, with tests. Still open: steps 3 to 6 (_admit_reveal's refusals, enforce_phi_read_pacing in a route body, the WebSocket cap after authorize_ws, the docs/SECURITY.md require_ui restatement), console grant parity, and the refusals PR 2808 findings 1 and 5 name. --- ...197-route-body-step-up-refusal.security.md | 8 + messagefoundry/api/security.py | 101 +++++++++--- messagefoundry/auth/service.py | 5 +- tests/test_derived_gate_decision_audit.py | 156 ++++++++++++++++-- 4 files changed, 236 insertions(+), 34 deletions(-) create mode 100644 changelog.d/1197-route-body-step-up-refusal.security.md diff --git a/changelog.d/1197-route-body-step-up-refusal.security.md b/changelog.d/1197-route-body-step-up-refusal.security.md new file mode 100644 index 0000000000..b74475ca6d --- /dev/null +++ b/changelog.d/1197-route-body-step-up-refusal.security.md @@ -0,0 +1,8 @@ +- **A step-up refusal made in a route body after its gate admitted the request now writes + `auth.gate_refused`.** A `proof_in_route` route's gate writes `auth.permission_granted`, and the + route then spends the bound proof (`spend_step_up_action`) or checks the session window + (`refuse_unless_step_up_window_live`). In the shipped code a refusal there left the grant row and + no row for the refusal. It now also writes an `auth.gate_refused` row naming the same permission + and a `reason` of `step_up`, only where the gate wrote its grant row. No request is allowed that + was refused before. A refusal whose row cannot be written answers with a server error instead of + the 403, as a gate's own refusal already does. (`BACKLOG #1197`) diff --git a/messagefoundry/api/security.py b/messagefoundry/api/security.py index e8312ef1c7..26787c97c7 100644 --- a/messagefoundry/api/security.py +++ b/messagefoundry/api/security.py @@ -1479,28 +1479,76 @@ async def _recorded_decision( inside it writes ``auth.gate_refused`` instead, naming the permission the grant row would have named and why. - A refusal row is written exactly where the grant row would have been, so a request still writes - at most one decision row, and a gate that wrote no grant row writes no refusal row either. That - keeps the per-request volume where the shipped trail already put it while the audit chain has no - drain (BACKLOG #1421). The reason comes from the :class:`_GateRefusal` the check raised. Any - other exception leaves the block with no decision row from it, which is right for the - :func:`_mfa_refusal` 403: it wrote its own ``auth.mfa_denied`` row where it was raised.""" + A refusal row is written exactly where the grant row would have been, so a gate writes at most + one decision row per request, and a gate that wrote no grant row writes no refusal row either. + That keeps the per-request volume where the shipped trail already put it while the audit chain + has no drain (BACKLOG #1421). A step-up refusal a route body makes after its gate has admitted + the request adds a second row, through :func:`_record_route_refusal`. The reason comes from the + :class:`_GateRefusal` the check raised. Any other exception leaves the block with no decision + row from it, which is right for the :func:`_mfa_refusal` 403: it wrote its own + ``auth.mfa_denied`` row where it was raised. A failed refusal-row write raises in place of the + refusal, so the request is still refused.""" try: yield except _GateRefusal as refusal: - audited = _audited_permission(request, permissions) - if audited is not None: - await auth.audit_gate_refused( - identity, - audited, - request.url.path, - reason=refusal.reason, - client=client_ip(request), - ) + await _record_gate_refusal(request, auth, identity, permissions, refusal) raise await _record_grant(request, auth, identity, permissions) +async def _record_gate_refusal( + request: Request, + auth: AuthService, + identity: Identity, + permissions: tuple[Permission, ...], + refusal: _GateRefusal, +) -> None: + """Write the ``auth.gate_refused`` row for ``refusal``, where a grant row would have been.""" + audited = _audited_permission(request, permissions) + if audited is not None: + await auth.audit_gate_refused( + identity, + audited, + request.url.path, + reason=refusal.reason, + client=client_ip(request), + ) + + +@dataclass(frozen=True) +class _AdmittedDecision: + """What a ``proof_in_route`` gate admitted, kept for the refusal row its route body may owe.""" + + auth: AuthService + identity: Identity + permissions: tuple[Permission, ...] + + +#: The ``request.state`` attribute a ``proof_in_route`` gate leaves its :class:`_AdmittedDecision` on. +_ADMITTED_DECISION_ATTR = "mefor_admitted_decision" + + +async def _record_route_refusal(request: Request, refusal: _GateRefusal) -> None: + """Record a step-up refusal a route body makes after its ``proof_in_route`` gate admitted it. + + BACKLOG #1197 (ASVS 16.3.2). The gate has already written its grant row, so without this the + refusal of :func:`spend_step_up_action` or :func:`refuse_unless_step_up_window_live` left no + row. The row names the permission the gate's grant row named, through the same writer as the + gate's own refusals. A route that reaches here without such a gate writes no row, and says so + in the log; the caller raises the refusal either way.""" + admitted = getattr(request.state, _ADMITTED_DECISION_ATTR, None) + if not isinstance(admitted, _AdmittedDecision): + log.warning( + "a route-body step-up refusal has no admitting proof_in_route gate to record against:" + " path=%s", + scrub_log_argument(request.url.path), + ) + return + await _record_gate_refusal( + request, admitted.auth, admitted.identity, admitted.permissions, refusal + ) + + #: The step-up refusal's detail for a session whose step-up is a password or directory re-proof. #: Clients and tests read it, so it stays byte-for-byte what it was before BACKLOG #2158. _STEP_UP_DETAIL = "step-up re-verification required; POST /me/reauth then retry" @@ -1520,7 +1568,7 @@ async def _recorded_decision( async def _step_up_refusal( auth: AuthService, token: str | None, action: str | None = None -) -> HTTPException: +) -> _GateRefusal: """The 403 every JSON step-up gate raises, for the session that holds ``token``. One place for the step-up raise sites (BACKLOG #2158), at least the four ``require_step_up*`` @@ -2139,6 +2187,13 @@ async def dependency(request: Request) -> Identity: raise await _step_up_refusal(auth, token, action) elif new_ip or not await _action_step_up_ok(auth, token, action): raise await _step_up_refusal(auth, token, action) + if proof_in_route: + # For the refusal row the route body's spend may owe (_record_route_refusal). + setattr( + request.state, + _ADMITTED_DECISION_ATTR, + _AdmittedDecision(auth, identity, permissions), + ) return identity return _gate(dependency, _authenticate_session_before_body) @@ -2154,13 +2209,16 @@ async def spend_step_up_action(request: Request, action: str) -> None: ``AuthService.refund_action_step_up``, as edit-resend does for a refusal before its store write (owner ruling 2026-10-13, #3241 R1), other than one in ``_EDIT_RESEND_SPENDING_REFUSALS`` in ``api/app.py`` (owner ruling 2026-11-07, #3241 added item 1). With no auth service attached it - does nothing, as the dependency does.""" + does nothing, as the dependency does. Its refusal writes ``auth.gate_refused`` + (:func:`_record_route_refusal`).""" auth = get_auth(request) if auth is None: return token = bearer_token(request) if not await _action_step_up_ok(auth, token, action): - raise await _step_up_refusal(auth, token, action) + refusal = await _step_up_refusal(auth, token, action) + await _record_route_refusal(request, refusal) + raise refusal async def step_up_window_live(request: Request) -> bool: @@ -2184,11 +2242,14 @@ async def refuse_unless_step_up_window_live(request: Request) -> None: Moving a route to ``proof_in_route=True`` drops its dependency's window check, so without this call that branch would take no step-up at all. The 403 carries ``X-Step-Up-Required`` and no ``X-Step-Up-Action``, so a client refreshes the window with a plain ``POST /me/reauth``. Does - nothing with no auth service attached, as the dependency then checks nothing.""" + nothing with no auth service attached, as the dependency then checks nothing. Its refusal + writes ``auth.gate_refused`` (:func:`_record_route_refusal`).""" auth = get_auth(request) if auth is None or await step_up_window_live(request): return - raise await _step_up_refusal(auth, bearer_token(request)) + refusal = await _step_up_refusal(auth, bearer_token(request)) + await _record_route_refusal(request, refusal) + raise refusal def require_reauth_only_action( diff --git a/messagefoundry/auth/service.py b/messagefoundry/auth/service.py index 71948edcf8..5203deb41a 100644 --- a/messagefoundry/auth/service.py +++ b/messagefoundry/auth/service.py @@ -22116,8 +22116,9 @@ async def audit_gate_refused( The caller holds ``permission``, so this is not :meth:`audit_permission_denied`: that row says the permission was missing, and the denial-burst detector counts it. - ``_recorded_decision`` in ``api/security.py`` decides when this row is written. ``client`` - is required, as for :meth:`audit_self_target_refused`.""" + ``_record_gate_refusal`` in ``api/security.py`` decides when this row is written, for a + gate's own refusals and for the step-up refusals a ``proof_in_route`` route body makes. + ``client`` is required, as for :meth:`audit_self_target_refused`.""" await self._audit( "auth.gate_refused", actor=identity.username, diff --git a/tests/test_derived_gate_decision_audit.py b/tests/test_derived_gate_decision_audit.py index ceb5dc87f5..0842f8e28e 100644 --- a/tests/test_derived_gate_decision_audit.py +++ b/tests/test_derived_gate_decision_audit.py @@ -29,21 +29,26 @@ from messagefoundry.api.security import ( _GateRefusal, _mfa_refusal, + _record_route_refusal, _recorded_decision, + refuse_unless_step_up_window_live, require_paced, require_phi_read, require_reauth_only, require_reauth_only_action, require_step_up, require_step_up_action, + spend_step_up_action, ) from messagefoundry.auth import Permission, Role from messagefoundry.auth.identity import ALL_CHANNELS, Identity from messagefoundry.auth.service import ( STEP_UP_ACTION_ADMIN_USER_UPDATE, + STEP_UP_ACTION_CONFIG_RELOAD, STEP_UP_ACTION_SESSION_TERMINATE, AuthService, ) +from messagefoundry.auth.tokens import hash_token from messagefoundry.config.settings import AuthSettings, EgressSettings from messagefoundry.pipeline import Engine from tests._admin_account import create_local_user_chosen @@ -67,21 +72,20 @@ async def engine(tmp_path: Path) -> AsyncIterator[Engine]: await eng.stop() -async def _service(engine: Engine) -> AuthService: +async def _service(engine: Engine, **overrides: Any) -> AuthService: """One administrator; one paced write and one PHI read per window; the new-address check on. ``require_mfa`` is off so the base gate's factor refusal does not answer first, and the minimum - write interval is off so the second write is refused by the count alone.""" - service = AuthService( - engine.store, - AuthSettings( - require_mfa=False, - admin_new_ip_step_up=True, - admin_write_min_interval_seconds=0, - admin_write_rate_limit_per_actor=1, - phi_read_rate_limit_per_actor=1, - ), - ) + write interval is off so the second write is refused by the count alone. ``overrides`` replace + any of those settings.""" + settings: dict[str, Any] = { + "require_mfa": False, + "admin_new_ip_step_up": True, + "admin_write_min_interval_seconds": 0, + "admin_write_rate_limit_per_actor": 1, + "phi_read_rate_limit_per_actor": 1, + } + service = AuthService(engine.store, AuthSettings(**(settings | overrides))) await service.initialize() user_id = await create_local_user_chosen( service, @@ -419,3 +423,131 @@ def test_a_gate_refusal_survives_copy_and_pickle_with_its_reason() -> None: "throttled", {"Retry-After": "3"}, ) + + +# --- A step-up refusal a route body makes after its gate admitted the request (BACKLOG #1197) --- +# +# A ``proof_in_route`` gate writes its grant row, then the route body spends the proof +# (``spend_step_up_action``) or, when only the session window is owed, checks it +# (``refuse_unless_step_up_window_live``). Each refusal there used to leave the grant row alone. + +_ROUTE_ACTION = STEP_UP_ACTION_CONFIG_RELOAD + + +def _route_body_app( + engine: Engine, service: AuthService, check: Callable[[Request], Any], ran: list[str] +) -> FastAPI: + """A POST probe gated as purge and reload are, whose body runs ``check`` and then records that + it got past it.""" + app = create_app(engine, auth=service) + gate = Depends( + require_step_up_action(_ROUTE_ACTION, Permission.USERS_MANAGE, proof_in_route=True) + ) + + async def probe(request: Request, _: Identity = gate) -> dict[str, str]: + await check(request) + ran.append("past the check") + return {"ok": "1"} + + app.add_api_route(_PROBE, probe, methods=["POST"]) + return app + + +async def _spend(request: Request) -> None: + await spend_step_up_action(request, _ROUTE_ACTION) + + +async def _reauth(app: FastAPI, token: str, purpose: str | None) -> str: + body = {"password": PW} if purpose is None else {"password": PW, "purpose": purpose} + async with _client(app, _HOME) as c: + r = await c.post("/me/reauth", json=body, headers={"Authorization": f"Bearer {token}"}) + assert r.status_code == 200, r.text + return str(r.json()["token"]) + + +_GRANT_ROW = (_GRANTED, {"permission": Permission.USERS_MANAGE.value, "path": _PROBE}, _HOME) +_REFUSAL_ROW = ( + _REFUSED, + {"permission": Permission.USERS_MANAGE.value, "path": _PROBE, "reason": "step_up"}, + _HOME, +) + + +async def test_a_refused_spend_in_the_route_body_leaves_a_refusal_row(engine: Engine) -> None: + """RED when: ``spend_step_up_action`` refuses without recording it, so the request leaves only + its gate's grant row. The control is the same request with the bound proof minted: the spend + passes and adds no refusal row.""" + service = await _service(engine, admin_write_rate_limit_per_actor=10) + ran: list[str] = [] + app = _route_body_app(engine, service, _spend, ran) + token = await _login(app) + + refused = await _call(app, "POST", token, _HOME) + assert refused.status_code == 403, refused.text + assert refused.headers.get("X-Step-Up-Action") == _ROUTE_ACTION + assert ran == [] + assert await _decisions(engine) == [_GRANT_ROW, _REFUSAL_ROW] + + token = await _reauth(app, token, _ROUTE_ACTION) + admitted = await _call(app, "POST", token, _HOME) + assert admitted.status_code == 200, admitted.text + assert ran == ["past the check"] + assert await _decisions(engine) == [_GRANT_ROW, _REFUSAL_ROW, _GRANT_ROW] + + +async def test_a_lapsed_window_refused_in_the_route_body_leaves_a_refusal_row( + engine: Engine, +) -> None: + """RED when: ``refuse_unless_step_up_window_live`` refuses without recording it. The control is + the same request once a plain re-proof has made the window live again.""" + service = await _service(engine, admin_write_rate_limit_per_actor=10) + ran: list[str] = [] + app = _route_body_app(engine, service, refuse_unless_step_up_window_live, ran) + token = await _login(app) + await engine.store.mark_session_reauthed(hash_token(token), now=0.0) # lapse the window + + refused = await _call(app, "POST", token, _HOME) + assert refused.status_code == 403, refused.text + assert "X-Step-Up-Action" not in refused.headers + assert ran == [] + assert await _decisions(engine) == [_GRANT_ROW, _REFUSAL_ROW] + + token = await _reauth(app, token, None) + admitted = await _call(app, "POST", token, _HOME) + assert admitted.status_code == 200, admitted.text + assert ran == ["past the check"] + assert await _decisions(engine) == [_GRANT_ROW, _REFUSAL_ROW, _GRANT_ROW] + + +@pytest.mark.parametrize("check", [_spend, refuse_unless_step_up_window_live]) +async def test_a_failed_refusal_row_write_still_refuses( + engine: Engine, check: Callable[[Request], Any], monkeypatch: pytest.MonkeyPatch +) -> None: + """The refusal never fails open: when the refusal row cannot be written, the request is still + refused and the route body never gets past the check, as in the gate's own decision block.""" + service = await _service(engine, admin_write_rate_limit_per_actor=10) + + async def broken(*_: object, **__: object) -> None: + raise RuntimeError("audit store down") + + monkeypatch.setattr(service, "audit_gate_refused", broken) + ran: list[str] = [] + app = _route_body_app(engine, service, check, ran) + token = await _login(app) + await engine.store.mark_session_reauthed(hash_token(token), now=0.0) # lapse the window + transport = httpx.ASGITransport(app=app, client=(_HOME, 12345), raise_app_exceptions=False) + async with httpx.AsyncClient(transport=transport, base_url="http://t") as c: + r = await c.post(_PROBE, headers={"Authorization": f"Bearer {token}"}) + assert r.status_code == 500, r.text + assert ran == [] + + +async def test_a_route_body_refusal_with_no_admitting_gate_logs_its_missing_row( + caplog: pytest.LogCaptureFixture, +) -> None: + """A route that refuses with no ``proof_in_route`` gate in front has no permission to name, so + it writes no row, and says so in the log rather than dropping the row silently.""" + request = _post_request() + with caplog.at_level("WARNING", logger="messagefoundry.api.security"): + await _record_route_refusal(request, _GateRefusal(403, "refused", reason="step_up")) + assert "no admitting proof_in_route gate" in caplog.text From df8a8bd9532b90e2023fdde3bb1762695adcf399 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sat, 21 Nov 2026 18:20:53 -0600 Subject: [PATCH 12/74] simplify: one census scan helper; terser re-proof store and adopt Vault BACKLOG #2950. --- ide/src/auth.ts | 6 +-- ide/src/signInSession.ts | 2 +- tests/test_apiclient_sign_in_timeout.py | 57 ++++++++++++------------- 3 files changed, 31 insertions(+), 34 deletions(-) diff --git a/ide/src/auth.ts b/ide/src/auth.ts index 1d6386b8e0..bd530ad299 100644 --- a/ide/src/auth.ts +++ b/ide/src/auth.ts @@ -387,10 +387,8 @@ export async function withStepUpAuth( // The re-proof ended the token withAuthAdopting handed in, so it is told which one this call // now holds: a 401 on it is then not mistaken for a sign-in elsewhere merely because the // cache holds the rotated token (BACKLOG #5960). - // reauth above already stored it, inside the tracked span. - storeToken: async (rotated) => { - adopt(rotated); - }, + // Adopt only: reauth above already stored it in the cache, inside the tracked span. + storeToken: async (rotated) => adopt(rotated), }), ); } diff --git a/ide/src/signInSession.ts b/ide/src/signInSession.ts index aa550d1c5f..84fa7c15e7 100644 --- a/ide/src/signInSession.ts +++ b/ide/src/signInSession.ts @@ -123,7 +123,7 @@ export function reproveTracked( ): Promise { return tracked(key, waitMs, async () => { const rotated = await post(); - if (rotated !== undefined && rotated !== "") { + if (rotated) { await cache.store(key, rotated); } return rotated; diff --git a/tests/test_apiclient_sign_in_timeout.py b/tests/test_apiclient_sign_in_timeout.py index 27a3a68a39..81d639de0b 100644 --- a/tests/test_apiclient_sign_in_timeout.py +++ b/tests/test_apiclient_sign_in_timeout.py @@ -20,6 +20,7 @@ import ast import inspect +from collections.abc import Callable from pathlib import Path import httpx @@ -171,46 +172,44 @@ def test_a_client_timeout_up_to_the_floor_gets_the_floor_on_the_queued_reads(own assert seen["/auth/me"] == _every_phase(own) -def _client_methods() -> list[ast.FunctionDef | ast.AsyncFunctionDef]: - """The ``EngineClient`` methods, ``async def`` ones included, read from its source.""" +def _methods_with_a_call(matches: Callable[[ast.Call], bool]) -> set[str]: + """The ``EngineClient`` methods, ``async def`` ones included, whose body holds a call that + ``matches``, read from its source.""" tree = ast.parse(Path(inspect.getfile(EngineClient)).read_text(encoding="utf-8")) cls = next( n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == EngineClient.__name__ ) - return [fn for fn in cls.body if isinstance(fn, (ast.FunctionDef, ast.AsyncFunctionDef))] + return { + fn.name + for fn in cls.body + if isinstance(fn, (ast.FunctionDef, ast.AsyncFunctionDef)) + and any(isinstance(node, ast.Call) and matches(node) for node in ast.walk(fn)) + } def _methods_calling(name: str) -> set[str]: - """The ``EngineClient`` methods whose body calls ``self.()``, read from its source.""" - found: set[str] = set() - for fn in _client_methods(): - for node in ast.walk(fn): - if ( - isinstance(node, ast.Call) - and isinstance(node.func, ast.Attribute) - and node.func.attr == name - and isinstance(node.func.value, ast.Name) - and node.func.value.id == "self" - ): - found.add(fn.name) - return found + """The ``EngineClient`` methods whose body calls ``self.()``.""" + return _methods_with_a_call( + lambda call: ( + isinstance(call.func, ast.Attribute) + and call.func.attr == name + and isinstance(call.func.value, ast.Name) + and call.func.value.id == "self" + ) + ) def _methods_setting_a_read_timeout() -> set[str]: """The ``EngineClient`` methods that build an ``httpx.Timeout`` with its own ``read=``.""" - found: set[str] = set() - for fn in _client_methods(): - for node in ast.walk(fn): - if ( - isinstance(node, ast.Call) - and ( - (isinstance(node.func, ast.Attribute) and node.func.attr == "Timeout") - or (isinstance(node.func, ast.Name) and node.func.id == "Timeout") - ) - and any(kw.arg == "read" for kw in node.keywords) - ): - found.add(fn.name) - return found + return _methods_with_a_call( + lambda call: ( + ( + (isinstance(call.func, ast.Attribute) and call.func.attr == "Timeout") + or (isinstance(call.func, ast.Name) and call.func.id == "Timeout") + ) + and any(kw.arg == "read" for kw in call.keywords) + ) + ) def test_the_census_of_queued_calls_matches_the_client() -> None: From c99bad8442d04c19d0962e25de014ebc44045c55 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sat, 21 Nov 2026 18:20:55 -0600 Subject: [PATCH 13/74] X12 tests: say the IEA trailer rule is open, not kept The comment over the trailer tests said a backlog row "keeps that rule", while that row is open and asks for the separator check those tests would fail. It now says the build was reverted in PR 3031 and the row is open. BACKLOG #5807: comment only. The separator check itself is not built, because it regresses origin/main: those pinned tests hold a dropped-separator or longer-id trailer that main closes at once. --- tests/test_x12_parsing.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/tests/test_x12_parsing.py b/tests/test_x12_parsing.py index eb7ab0d88d..9e7007beef 100644 --- a/tests/test_x12_parsing.py +++ b/tests/test_x12_parsing.py @@ -387,8 +387,9 @@ def test_split_keeps_the_whitespace_terminator_of_a_malformed_interchange_cut_at # Three trailers that close the frame at once, two of them not a clean IEA. Any segment opening with -# IEA closes it (BACKLOG #5807 keeps that rule): the reader cannot see a connection end, so a frame -# it held there would be dropped with no row. +# IEA closes it: the reader cannot see a connection end, so a frame it held there would be dropped +# with no row. BACKLOG #5807 asks for a separator check after IEA, which would break these; a build +# of it was reverted in PR 3031, and the row is open. _TRAILERS_THAT_CLOSE = [ pytest.param("IEA1*000000001~", id="dropped-separator"), pytest.param("IEAX*1~", id="longer-id"), From 5d026811cb8a1639a12bbe76669d65c35aee072b Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sat, 21 Nov 2026 18:23:40 -0600 Subject: [PATCH 14/74] Server schema check: refuse or read the DDL forms it misread without raising BACKLOG #5062. The live-schema reader in store/server_schema_verify.py read at least these forms into a wrong expected shape, or let them through: - ADD COLUMN index|period|exclude skipped as a constraint; now a column. A SQL Server inline INDEX, and PERIOD or EXCLUDE not in their constraint shape, now raise. - An ADD CONSTRAINT read on into the next ALTER/CREATE/DROP or data statement and took that statement's PRIMARY KEY; the clause now ends there (ON DELETE / ON UPDATE excepted). - A PRIMARY KEY over a quoted name with a space, and a PRIMARY KEY inside a CHECK literal. - PRIMARY KEY or UNIQUE USING INDEX, a key that only casts a column, a PostgreSQL 18 NOT NULL table constraint, COLLATE CATALOG_DEFAULT, ALTER INDEX (now named as such), a second CREATE TABLE no DROP removed, and a DROP COLUMN an expression, INCLUDE or predicate index may use: each now raises. - COLLATE DATABASE_DEFAULT reads as the database collation. - DEFAULT - at a column's end raised IndexError; ADD COLUMN IF NOT EXISTS with nothing after it added a column named "if"; RENAME COLUMN without TO was accepted; DROP TABLE IF EXISTS #tmp raised; legacy SQL Server DROP INDEX table.index ignored the table. - The scanners now share one quote reader, so [a,b] and [end] are one name. The shipped batches' expected shapes are byte-identical before and after, so SCHEMA_CHECK_REV is not bumped. The module docstring names the forms that now raise, the misreads that still do not, and corrects the default premise (a missing default fails an insert only on a NOT NULL column). --- messagefoundry/store/server_schema_verify.py | 234 ++++++++++++----- tests/test_server_schema_verify_5062.py | 255 +++++++++++++++++++ 2 files changed, 432 insertions(+), 57 deletions(-) create mode 100644 tests/test_server_schema_verify_5062.py diff --git a/messagefoundry/store/server_schema_verify.py b/messagefoundry/store/server_schema_verify.py index 056a41eabc..62c9aec59f 100644 --- a/messagefoundry/store/server_schema_verify.py +++ b/messagefoundry/store/server_schema_verify.py @@ -40,19 +40,25 @@ DDL the reader cannot place raises ``ValueError`` rather than being skipped or misread, at least: a ``CREATE ... INDEX``, ``CREATE TABLE``, ``DROP TABLE``, ``DROP INDEX`` or ``sp_rename`` its patterns do not match, an ``ALTER TABLE`` with more than one clause or an action it does not know, a table rename, -a ``USING`` access method, a key column or expression carrying a collation, an operator class or a -``NULLS`` order, a column type or clause it does not know, a SQL Server column that leaves its -nullability to the session, and a ``--`` or ``/*`` inside a quoted string, which may be dynamic SQL's -comment or a literal's text. A unit test reads each shipped batch, so a new form fails there before -it reaches an open. +an ``ALTER INDEX``, a second ``CREATE TABLE`` of a table no ``DROP`` removed, a ``USING`` access +method, a key column or expression carrying a collation, an operator class or a ``NULLS`` order, a key +that only casts a column, a key built ``USING INDEX``, a SQL Server inline ``INDEX``, a ``NOT NULL`` +table constraint, a ``DROP COLUMN`` of a column an expression, ``INCLUDE`` or predicate of an +index on its table may name, a column type or clause it does not know, a SQL Server column that +leaves its nullability to the session, ``COLLATE CATALOG_DEFAULT``, and a ``--`` or ``/*`` inside a +quoted string, which may be dynamic SQL's comment or a literal's text. A unit test reads each shipped +batch, so a new form fails there before it reaches an open. Not every misread raises: at least DDL +text inside a string literal is read as run, and an ``ALTER COLUMN`` is read as reaching only an older +store, whether or not either holds (BACKLOG #5062). What is NOT compared includes at least: a column's default, other than whether PostgreSQL's is a ``nextval()`` call, which reads as numbering; a PostgreSQL column's collation; constraint indexes (a ``PRIMARY KEY`` or ``UNIQUE`` declared on the table); ``CHECK`` and foreign keys; an index's ``INCLUDE`` list and storage options; and a partial index's predicate, of which only its presence is compared. A default is not compared because each catalog prints it in its own rewritten form -(PostgreSQL ``''::text``, SQL Server ``((0))``), and a missing one fails the first insert that relies -on it rather than passing silently. An index that exists but cannot serve, such as +(PostgreSQL ``''::text``, SQL Server ``((0))``). A missing one on a ``NOT NULL`` column fails the +first insert that relies on it; on a column that takes NULL, that insert stores NULL and nothing +fails. An index that exists but cannot serve, such as an invalid or non-btree one on PostgreSQL or a disabled one on SQL Server, is reported by the backend that reads it. A store whose marker already matches is not re-read at open: the ADR 0064 fast path skips the batch and this check together, so a change made by hand after the marker was written is not @@ -153,12 +159,12 @@ ) #: Every place a table or an index is created, dropped or renamed, read loosely, so a form the #: patterns above miss is counted and refused rather than silently left unchecked. A ``#`` temporary -#: table is not the store's. +#: table is not the store's, behind an ``IF [NOT] EXISTS`` guard too. _LOOSE: Final = ( - (re.compile(r"\bCREATE\s+TABLE\s+(?!#)", re.I), _CREATE_TABLE), + (re.compile(r"\bCREATE\s+TABLE\s+(?!(?:IF\s+NOT\s+EXISTS\s+)?#)", re.I), _CREATE_TABLE), (re.compile(r"\bCREATE\s+(?:UNIQUE\s+)?(?:(?:NON)?CLUSTERED\s+)?INDEX\b", re.I), _CREATE_INDEX), - (re.compile(r"\bALTER\s+TABLE\s+(?!#)", re.I), _ALTER_TABLE), - (re.compile(r"\bDROP\s+TABLE\s+(?!#)", re.I), _DROP_TABLE), + (re.compile(r"\bALTER\s+TABLE\s+(?!(?:IF\s+EXISTS\s+)?#)", re.I), _ALTER_TABLE), + (re.compile(r"\bDROP\s+TABLE\s+(?!(?:IF\s+EXISTS\s+)?#)", re.I), _DROP_TABLE), (re.compile(r"\bDROP\s+INDEX\b", re.I), _DROP_INDEX), (re.compile(r"\bsp_rename\b", re.I), _SP_RENAME), ) @@ -172,6 +178,17 @@ {"constraint", "primary", "unique", "check", "foreign", "exclude", "default", "period", "index"} ) _TABLE_PRIMARY_KEY = re.compile(r"\bPRIMARY\s+KEY\s*(?:(?:NON)?CLUSTERED\s*)?\(", re.I) +#: PostgreSQL's ``PRIMARY KEY`` or ``UNIQUE`` ``USING INDEX ``, which turns an existing index +#: into the constraint. ``USING INDEX TABLESPACE`` is only a storage option. +_USING_INDEX = re.compile(r"\bUSING\s+INDEX\s+(?!TABLESPACE\b)", re.I) +#: A key that is only a cast of a column, ``a::text`` or ``CAST(a AS text)``. PostgreSQL stores a +#: cast to the column's own type as the column, and any other as an expression, and the reader does +#: not know which. +_CAST_TYPE = r"\w[\w ]*?(?:\s*\(\s*\d+(?:\s*,\s*\d+)?\s*\))?(?:\s*\[\])?" +_CAST_KEY = re.compile( + rf'^(?:"[^"]+"|\w+)\s*::\s*{_CAST_TYPE}$|^CAST\s*\(\s*(?:"[^"]+"|\w+)\s+AS\s+{_CAST_TYPE}\s*\)$', + re.I, +) _PLAIN_KEY = re.compile(r'^(\[?[A-Za-z_][\w$]*\]?|"[^"]+")(?:\s+(ASC|DESC))?$', re.I) _PLAIN_NAME = re.compile(r'^(?:\[?[A-Za-z_][\w$]*\]?|"[^"]+")$') #: A key that is an expression: a call such as ``left(actor, 200)``, or a parenthesised expression. @@ -183,6 +200,12 @@ #: The words a statement inside a block starts with, at which an ``ALTER TABLE`` clause has ended #: when no ``;`` closes it. None can appear inside a column definition. _STATEMENT_START = frozenset({"if", "begin", "end", "exec", "execute", "else", "declare", "go"}) +#: Words that start a data statement, which a clause ends at unless ``ON`` precedes them (BACKLOG +#: #5062: an ``ADD CONSTRAINT`` read on into the next statement took that statement's ``PRIMARY KEY`` +#: as its own). +_DATA_STATEMENT = frozenset({"insert", "update", "delete", "merge", "select", "truncate"}) +#: What an ``ALTER`` or ``DROP`` that starts the next statement names, after the word itself. +_DDL_OBJECT = re.compile(r"\s+(?:TABLE|INDEX|VIEW|PROC|PROCEDURE|TRIGGER|FUNCTION)\b", re.I) _TOKEN = re.compile(r"""N?'(?:[^']|'')*'|"[^"]*"|\[[^\]]*\]|\w+|\S""") @@ -312,18 +335,32 @@ def _string_spans(text: str) -> list[tuple[int, int]]: return spans +def _quoted_end(text: str, i: int) -> int | None: + """The index after the quoted run that opens at ``text[i]``: a ``'`` string, a ``"`` name or a + SQL Server ``[...]`` name, in which a doubled close continues the run. ``None`` when ``text[i]`` + opens none. The scanners below share it, so a ``[a,b]`` or ``[end]`` reads as one name in each.""" + ch = text[i] + if ch not in "'\"[": + return None + close = "]" if ch == "[" else ch + j = i + 1 + while (end := text.find(close, j)) >= 0: + if not text.startswith(close * 2, end): + return end + 1 + j = end + 2 + raise ValueError(f"unterminated quote in DDL near {text[i : i + 40]!r}") + + def _balanced(text: str, start: int) -> tuple[str, int]: """The text inside the parenthesis opened at ``text[start - 1]``, and the index after its close. Quoted text is skipped, so a parenthesis inside a string literal does not count.""" - depth, i, quote = 1, start, "" + depth, i = 1, start while i < len(text): + if (end := _quoted_end(text, i)) is not None: + i = end + continue ch = text[i] - if quote: - if ch == quote: - quote = "" - elif ch in "'\"": - quote = ch - elif ch == "(": + if ch == "(": depth += 1 elif ch == ")": depth -= 1 @@ -336,24 +373,21 @@ def _balanced(text: str, start: int) -> tuple[str, int]: def _top_level_items(body: str) -> list[str]: """``body`` split on its top-level commas, so a ``DECIMAL(10, 2)`` stays one item.""" items: list[str] = [] - current: list[str] = [] - depth, quote = 0, "" - for ch in body: - if quote: - if ch == quote: - quote = "" - elif ch in "'\"": - quote = ch - elif ch == "(": + depth, i, last = 0, 0, 0 + while i < len(body): + if (end := _quoted_end(body, i)) is not None: + i = end + continue + ch = body[i] + if ch == "(": depth += 1 elif ch == ")": depth -= 1 elif ch == "," and depth == 0: - items.append("".join(current)) - current = [] - continue - current.append(ch) - items.append("".join(current)) + items.append(body[last:i]) + last = i + 1 + i += 1 + items.append(body[last:]) return [item.strip() for item in items if item.strip()] @@ -371,15 +405,13 @@ def _clause(segment: str) -> str: """The one clause of an ``ALTER TABLE`` that ``segment`` starts with: up to a top-level ``;``, an unmatched ``)``, a word that starts the next statement, or the end. A top-level comma means more than one clause, which raises.""" - depth, quote, i, n = 0, "", 0, len(segment) + depth, i, n, prev = 0, 0, len(segment), "" while i < n: + if (end := _quoted_end(segment, i)) is not None: + i = end + continue ch = segment[i] - if quote: - if ch == quote: - quote = "" - elif ch in "'\"": - quote = ch - elif ch == "(": + if ch == "(": depth += 1 elif ch == ")": if depth == 0: @@ -394,11 +426,21 @@ def _clause(segment: str) -> str: ): word = re.match(r"\w+", segment[i:]) assert word is not None + lower = word.group(0).lower() after = segment[i + len(word.group(0)) :] - if word.group(0).lower() in _STATEMENT_START and not ( - word.group(0).lower() == "if" and re.match(r"\s+(?:NOT\s+)?EXISTS\b", after, re.I) + if lower in _STATEMENT_START and not ( + lower == "if" and re.match(r"\s+(?:NOT\s+)?EXISTS\b", after, re.I) + ): + break + # A data or DDL statement starts here too. ON DELETE and ON UPDATE are a foreign + # key's actions; ALTER COLUMN and DROP COLUMN are the clause's own verbs. + if ( + lower == "create" + or (lower in _DATA_STATEMENT and prev != "on") + or (lower in ("alter", "drop") and _DDL_OBJECT.match(after)) ): break + prev = lower i += len(word.group(0)) continue i += 1 @@ -623,7 +665,9 @@ def word(k: int) -> str: i = _skip_group(tokens, i) elif w == "default" and i + 1 < len(tokens): numbered_default = dialect == "postgres" and _numbers(" ".join(tokens[i + 1 :])) - i += 2 if tokens[i + 1] not in "+-" else 3 + i += 3 if tokens[i + 1] in ("+", "-") else 2 + if i > len(tokens): # a sign with nothing after it + raise ValueError(f"a default the live-schema check cannot read: {text!r}") if tokens[i - 1] == "(": i = _skip_group(tokens, i - 1) elif word(i) == "(": @@ -634,6 +678,11 @@ def word(k: int) -> str: if dialect == "postgres": raise ValueError(f"a PostgreSQL column collation is not compared: {text!r}") collation, i = _ident(tokens[i + 1]), i + 2 + if collation == "database_default": + collation = None # the database's own, which an expected None matches + elif collation == "catalog_default": + # The metadata catalog's collation, which the live read cannot tell apart. + raise ValueError(f"a catalog_default collation is not compared: {text!r}") elif w == "identity" and dialect == "sqlserver": identity, i = True, i + 1 if word(i) == "(": @@ -700,6 +749,8 @@ def _declared_key(text: str) -> str: inner = inner[1:-1].strip() if _PLAIN_NAME.match(inner): key = inner + elif _CAST_KEY.match(inner): + raise ValueError(f"index key {text!r} is a cast the live-schema check cannot place") elif inner != key and re.search(r"\bCOLLATE\b", inner, re.I): # PostgreSQL stores ((col COLLATE x)) as the column with an index collation. raise ValueError(f"index key {text!r} carries options the live-schema check cannot compare") @@ -773,10 +824,38 @@ def altered(self, change: Callable[[ColumnShape], ColumnShape]) -> None: def _pk_columns(text: str) -> set[str]: """The columns of a ``PRIMARY KEY (...)`` in ``text``, a table item or an ``ADD CONSTRAINT``.""" - if (pk := _TABLE_PRIMARY_KEY.search(text)) is None: + if _USING_INDEX.search(text): + raise ValueError(f"a key built from an existing index is not compared: {text[:120]!r}") + # A string literal's text, as in a CHECK, is blanked first, so a PRIMARY KEY inside one is not + # taken for the item's own. + blanked = text + for start, end in _string_spans(text): + blanked = blanked[:start] + "'" + " " * (end - start - 2) + "'" + blanked[end:] + if (pk := _TABLE_PRIMARY_KEY.search(blanked)) is None: return set() inner, _ = _balanced(text, pk.end()) - return {_bare(k.split()[0]) for k in _top_level_items(inner)} + return {_bare(_TOKEN.findall(k)[0]) for k in _top_level_items(inner)} + + +def _is_constraint(item: str) -> bool: + """Whether a table item, or what follows an ``ADD`` without ``COLUMN``, is a constraint rather + than a column. A SQL Server inline ``INDEX`` raises, because it builds a named index the reader + does not model, and so do ``PERIOD`` and ``EXCLUDE`` when what follows is not their constraint's + own shape, because each may also be a column's name. A ``NOT NULL`` table constraint raises: + the reader does not apply it.""" + if re.match(r"(?:CONSTRAINT\s+\S+\s+)?NOT\s+NULL\b", item, re.I): + # PostgreSQL 18's NOT NULL table constraint, perhaps NOT VALID. + raise ValueError(f"a not-null constraint is not compared: {item[:120]!r}") + words = [w.lower() for w in _TOKEN.findall(item)[:2]] + [""] + if words[0] not in _NOT_A_COLUMN: + return False + if words[0] == "index": + raise ValueError(f"an inline index the live-schema check does not compare: {item[:120]!r}") + if (words[0] == "period" and words[1] != "for") or ( + words[0] == "exclude" and words[1] not in ("(", "using") + ): + raise ValueError(f"a table item the live-schema check cannot place: {item[:120]!r}") + return True class _Reader: @@ -788,15 +867,26 @@ def __init__(self, dialect: Dialect | None) -> None: self.dialect = dialect self.columns: dict[str, dict[str, _Built]] = {} self.indexes: dict[str, IndexShape] = {} + #: The words of each index whose key, INCLUDE list or predicate may name a column its key + #: columns do not show: an expression key, an INCLUDE or a WHERE. A DROP COLUMN of one of + #: those words raises, because PostgreSQL drops such an index and the reader cannot tell. + self.opaque: dict[str, frozenset[str]] = {} + #: The tables a CREATE TABLE has built and no DROP TABLE has removed since. + self.created: set[str] = set() def table(self, text: str, m: re.Match[str]) -> None: body, _end = _balanced(text, m.end()) - cols = self.columns.setdefault(_bare(m["name"]), {}) + table = _bare(m["name"]) + if table in self.created: + # A guarded second CREATE TABLE never runs: the first one built the table. + raise ValueError(f"a second create table of {table}, which its guard skips") + self.created.add(table) + cols = self.columns.setdefault(table, {}) keys: set[str] = set() pending: list[tuple[str, _Column, str]] = [] for item in _top_level_items(body): - first = item.split()[0] - if first.lower() in _NOT_A_COLUMN: + first = _TOKEN.findall(item)[0] + if _is_constraint(item): keys |= _pk_columns(item) elif self.dialect is None: cols.setdefault(_bare(first), _Built()) @@ -817,16 +907,26 @@ def index(self, text: str, m: re.Match[str]) -> None: if m["using"]: raise ValueError(f"index access method not compared: {m.group(0)!r}") body, end = _balanced(text, m.end()) + include = False while clause := _INDEX_TAIL.match(text, end): end = clause.end() + include = include or clause.group(0).lstrip().upper().startswith("INCLUDE") if text[end - 1] == "(": end = _balanced(text, end)[1] - self.indexes[_bare(m["name"])] = IndexShape( + name = _bare(m["name"]) + shape = IndexShape( _bare(m["table"]), tuple(_declared_key(item) for item in _top_level_items(body)), bool(m["unique"]), text[end:].lstrip().upper().startswith("WHERE"), ) + self.indexes[name] = shape + self.opaque.pop(name, None) + if include or shape.partial or any(k.startswith("") for k in shape.columns): + # To the statement's end: a predicate has no closing mark of its own. + stop = text.find(";", end) + definition = text[m.end() : len(text) if stop < 0 else stop] + self.opaque[name] = frozenset(_ident(w) for w in _TOKEN.findall(definition)) def _built(self, table: str, name: str, action: str) -> _Built: cols = self.columns.get(table) @@ -846,21 +946,33 @@ def alter(self, text: str, m: re.Match[str], spans: list[tuple[int, int]]) -> No words = clause.split() verb = [w.lower() for w in words[:2]] if verb[:1] == ["add"]: - rest = re.sub(r"^ADD\s+(?:COLUMN\s+)?(?:IF\s+NOT\s+EXISTS\s+)?", "", clause, flags=re.I) - first = rest.split()[0].lower() if rest.split() else "" - if first in _NOT_A_COLUMN: + head = re.match(r"ADD(\s+COLUMN\b)?\s*(?:IF\s+NOT\s+EXISTS\b\s*)?", clause, re.I) + assert head is not None + rest = clause[head.end() :] + if not rest: + raise ValueError(f"an add with nothing to add: {clause!r}") + # After ADD COLUMN what follows is a column, whatever its name (BACKLOG #5062). + if not head.group(1) and _is_constraint(rest): for key in _pk_columns(rest): self._not_null(table, key) return if self.dialect is None: - self.columns.setdefault(table, {}).setdefault(_bare(rest.split()[0]), _Built()) + self.columns.setdefault(table, {}).setdefault( + _bare(_TOKEN.findall(rest)[0]), _Built() + ) return name, col = _read_column(self.dialect, rest) built = self.columns.setdefault(table, {}).setdefault(name, _Built()) built.later.add(_finish(self.dialect, col, rest)) elif verb == ["drop", "column"]: name = re.sub(r"^DROP\s+COLUMN\s+(?:IF\s+EXISTS\s+)?", "", clause, flags=re.I) - column = _bare(name.split()[0]) + column = _bare(_TOKEN.findall(name)[0]) + for index, used in self.opaque.items(): + if index in self.indexes and self.indexes[index].table == table and column in used: + raise ValueError( + f"a drop column of {table}.{column}, which index {index}'s expression," + " INCLUDE or predicate may use, so the reader cannot tell whether it goes" + ) self.columns.get(table, {}).pop(column, None) # PostgreSQL drops an index on a dropped column; SQL Server refuses the drop. self._rewrite_keys(table, column, None) @@ -870,7 +982,7 @@ def alter(self, text: str, m: re.Match[str], spans: list[tuple[int, int]]) -> No return # a table's storage options, such as LOCK_ESCALATION: not compared elif verb == ["alter", "column"]: self._alter_column(table, clause, words) - elif verb[:1] == ["rename"] and len(words) == 5 and words[1].lower() == "column": + elif verb == ["rename", "column"] and len(words) == 5 and words[3].lower() == "to": self._rename(table, _bare(words[2]), _bare(words[4])) else: raise ValueError(f"an alter table the live-schema check cannot read: {clause[:120]!r}") @@ -954,6 +1066,7 @@ def drop_tables(self, m: re.Match[str]) -> None: for name in _dropped(m, _DROPPED_TABLE): table = _bare(name) self.columns.pop(table, None) + self.created.discard(table) for index in [n for n, shape in self.indexes.items() if shape.table == table]: del self.indexes[index] @@ -964,6 +1077,9 @@ def drop_indexes(self, m: re.Match[str]) -> None: parts = item.split() name = _bare(parts[0]) on = _bare(parts[-1]) if len(parts) == 3 else None + if on is None and self.dialect == "sqlserver" and "." in parts[0]: + # SQL Server's legacy DROP INDEX .. + on = _bare(parts[0].rsplit(".", 1)[0]) shape = self.indexes.get(name) if shape is not None and (on is None or shape.table == on): del self.indexes[name] @@ -977,8 +1093,8 @@ def shape(self) -> ServerSchemaShape: if len(ways) > 1: listed = " and ".join(sorted(s.describe() for s in ways)) raise ValueError( - f"column {table}.{name} is built two ways, as {listed}: a guarded ADD," - " an alter column or a second create table disagrees with the first" + f"column {table}.{name} is built two ways, as {listed}: its create" + " table, a guarded ADD or an alter column disagree" ) if ways: one[name] = next(iter(ways)) @@ -1008,8 +1124,12 @@ def declared_schema( for loose, strict in _LOOSE: if len(loose.findall(text)) != len(strict.findall(text)): raise ValueError(f"DDL the live-schema check cannot read: {text.strip()[:120]!r}") - if re.search(r"\bRENAME\s+TO\b|\bALTER\s+INDEX\b", text, re.I): + if re.search(r"\bRENAME\s+TO\b", text, re.I): raise ValueError(f"a rename the live-schema check cannot read: {text.strip()[:120]!r}") + if re.search(r"\bALTER\s+INDEX\b", text, re.I): + raise ValueError( + f"an alter index the live-schema check cannot read: {text.strip()[:120]!r}" + ) spans = _string_spans(text) events: list[tuple[int, str, re.Match[str]]] = [] for kind, pattern in ( diff --git a/tests/test_server_schema_verify_5062.py b/tests/test_server_schema_verify_5062.py new file mode 100644 index 0000000000..f3731a67b1 --- /dev/null +++ b/tests/test_server_schema_verify_5062.py @@ -0,0 +1,255 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +# Copyright (C) 2026 MessageFoundry Foundation, LLC and contributors +"""BACKLOG #5062: DDL forms the server-DB live schema check misread without raising. + +Each test here failed before its fix: the reader either built a wrong expected shape or let a form +it cannot place through. A form the reader cannot place now raises ``ValueError``, which the unit +test that reads each shipped batch would surface before an open does. The shipped batches' own +expected shapes are pinned by ``tests/test_sqlserver_postgres_schema_verify_1720.py``. +""" + +from __future__ import annotations + +import pytest + +from messagefoundry.store.server_schema_verify import declared_schema + + +def test_add_column_takes_any_name_as_a_column() -> None: + """After ``ADD COLUMN`` what follows is a column, so a column named like a constraint word, + ``index``, ``period`` or ``exclude``, enters the expected shape rather than being skipped.""" + shape = declared_schema( + ( + "CREATE TABLE t (a INT)", + "ALTER TABLE t ADD COLUMN index TEXT", + "ALTER TABLE t ADD COLUMN IF NOT EXISTS period TEXT", + "ALTER TABLE t ADD COLUMN exclude TEXT NOT NULL", + ), + "postgres", + ) + assert shape.columns["t"] == frozenset({"a", "index", "period", "exclude"}) + assert shape.column_shapes["t"]["exclude"].nullable is False + + +@pytest.mark.parametrize( + ("item", "match"), + [ + ("INDEX ix_t (a)", "inline index"), + ("INDEX ix_t NONCLUSTERED (a)", "inline index"), + ("period INT NULL", "cannot place"), + ("exclude INT NULL", "cannot place"), + ], +) +def test_a_table_item_that_is_an_index_or_could_be_a_column_raises(item: str, match: str) -> None: + with pytest.raises(ValueError, match=match): + declared_schema((f"CREATE TABLE t (a INT NULL, {item})",), "sqlserver") + + +def test_a_constraint_of_the_period_or_exclude_shape_is_still_a_constraint() -> None: + shape = declared_schema(("CREATE TABLE t (a INT, EXCLUDE USING gist (a WITH =))",), "postgres") + assert shape.columns["t"] == frozenset({"a"}) + + +def test_an_add_constraint_does_not_read_on_into_the_next_statement() -> None: + """An ``ADD CONSTRAINT`` with no ``;`` after it used to read on into the next ``ALTER TABLE`` + and take that statement's ``PRIMARY KEY`` columns as its own table's.""" + shape = declared_schema( + ( + "CREATE TABLE a (x INT NOT NULL, id INT NULL)", + "CREATE TABLE b (id INT NOT NULL)", + "IF 1 = 1 ALTER TABLE a ADD CONSTRAINT ck_a CHECK (x > 0)\n" + "ALTER TABLE b ADD CONSTRAINT pk_b PRIMARY KEY (id)", + "IF 1 = 1 ALTER TABLE a ADD CONSTRAINT ck_b CHECK (x < 9)\n" + "UPDATE b SET id = 1 WHERE id = 0", + ), + "sqlserver", + ) + assert shape.column_shapes["a"]["id"].nullable is True + assert shape.column_shapes["b"]["id"].nullable is False + + +def test_a_foreign_key_action_does_not_end_an_add_clause() -> None: + shape = declared_schema( + ( + "CREATE TABLE a (id INT NOT NULL PRIMARY KEY)", + "CREATE TABLE b (x INT NULL)", + "ALTER TABLE b ADD a_id INT NULL REFERENCES a(id) ON DELETE CASCADE ON UPDATE NO ACTION", + ), + "sqlserver", + ) + assert shape.column_shapes["b"]["a_id"].nullable is True + + +def test_a_primary_key_over_a_quoted_name_with_a_space_is_not_null() -> None: + shape = declared_schema(('CREATE TABLE t ("my col" INT, PRIMARY KEY ("my col"))',), "postgres") + assert shape.column_shapes["t"]["my col"].nullable is False + + +def test_a_primary_key_inside_a_check_literal_marks_nothing() -> None: + shape = declared_schema( + ("CREATE TABLE t (a INT, b INT, CHECK (a::text <> 'PRIMARY KEY (b)'))",), "postgres" + ) + assert shape.column_shapes["t"]["b"].nullable is True + + +@pytest.mark.parametrize( + "clause", + [ + "ADD CONSTRAINT pk_t PRIMARY KEY USING INDEX ix_t", + "ADD PRIMARY KEY USING INDEX ix_t", + "ADD CONSTRAINT uq_t UNIQUE USING INDEX ix_t", + ], +) +def test_a_key_built_from_an_existing_index_raises(clause: str) -> None: + with pytest.raises(ValueError, match="existing index"): + declared_schema(("CREATE TABLE t (a INT)", f"ALTER TABLE t {clause}"), "postgres") + + +def test_using_index_tablespace_is_only_a_storage_option() -> None: + shape = declared_schema( + ( + "CREATE TABLE t (a INT)", + "ALTER TABLE t ADD CONSTRAINT pk_t PRIMARY KEY (a) USING INDEX TABLESPACE fast", + ), + "postgres", + ) + assert shape.column_shapes["t"]["a"].nullable is False + + +@pytest.mark.parametrize("key", ["(a::text)", "((a :: varchar(10)))", "CAST(a AS text)"]) +def test_a_key_that_only_casts_a_column_raises(key: str) -> None: + """PostgreSQL stores a cast to the column's own type as the column, so the key may read live + as ``a`` while the reader would say ````.""" + with pytest.raises(ValueError, match="cast"): + declared_schema((f"CREATE INDEX ix ON t ({key})",)) + + +def test_an_expression_around_a_cast_is_still_an_expression() -> None: + shape = declared_schema(("CREATE INDEX ix ON t (lower(a::text))",)) + assert shape.named_indexes["ix"].columns == ("",) + + +def test_a_default_sign_with_nothing_after_it_is_a_value_error() -> None: + with pytest.raises(ValueError, match="default"): + declared_schema(("CREATE TABLE t (a INT DEFAULT -)",), "postgres") + + +@pytest.mark.parametrize("clause", ["ADD COLUMN IF NOT EXISTS", "ADD COLUMN"]) +def test_an_add_with_nothing_to_add_raises(clause: str) -> None: + with pytest.raises(ValueError, match="nothing to add"): + declared_schema(("CREATE TABLE t (a INT)", f"ALTER TABLE t {clause}")) + + +def test_an_alter_index_is_refused_as_what_it_is() -> None: + with pytest.raises(ValueError, match="alter index"): + declared_schema(("ALTER INDEX ix_t SET (fillfactor = 70)",)) + + +def test_collate_database_default_is_the_database_collation() -> None: + shape = declared_schema( + ("CREATE TABLE t (a NVARCHAR(64) COLLATE DATABASE_DEFAULT NOT NULL)",), "sqlserver" + ) + assert shape.column_shapes["t"]["a"].collation is None + + +def test_collate_catalog_default_raises() -> None: + with pytest.raises(ValueError, match="catalog_default"): + declared_schema( + ("CREATE TABLE t (a NVARCHAR(64) COLLATE CATALOG_DEFAULT NOT NULL)",), "sqlserver" + ) + + +def test_a_guarded_drop_of_a_temporary_table_is_not_the_stores() -> None: + shape = declared_schema(("CREATE TABLE t (a INT)", "DROP TABLE IF EXISTS #tmp")) + assert set(shape.columns) == {"t"} + + +def test_a_rename_column_without_to_raises() -> None: + with pytest.raises(ValueError, match="cannot read"): + declared_schema(("CREATE TABLE t (a INT)", "ALTER TABLE t RENAME COLUMN a x b")) + + +def test_a_bracketed_name_with_a_comma_or_a_keyword_is_one_name() -> None: + shape = declared_schema( + ( + "CREATE TABLE t ([a,b] INT NULL, c INT NULL)", + "IF COL_LENGTH('t','end') IS NULL ALTER TABLE t ADD [end] INT NULL", + ), + "sqlserver", + ) + assert shape.columns["t"] == frozenset({"a,b", "c", "end"}) + + +def test_a_second_create_table_raises() -> None: + """A guarded second ``CREATE TABLE`` never runs, so the columns it alone names are never built.""" + with pytest.raises(ValueError, match="second create table"): + declared_schema( + ("CREATE TABLE IF NOT EXISTS t (a INT)", "CREATE TABLE IF NOT EXISTS t (a INT, b INT)") + ) + # After a DROP the table is created again. + shape = declared_schema(("CREATE TABLE t (a INT)", "DROP TABLE t", "CREATE TABLE t (b INT)")) + assert shape.columns["t"] == frozenset({"b"}) + + +@pytest.mark.parametrize( + "index", + [ + "CREATE INDEX ix ON t (lower(b))", + "CREATE INDEX ix ON t (a) WHERE b IS NOT NULL", + "CREATE INDEX ix ON t (a) INCLUDE (b)", + ], +) +def test_a_drop_column_an_opaque_index_may_use_raises(index: str) -> None: + with pytest.raises(ValueError, match="drop column"): + declared_schema(("CREATE TABLE t (a INT, b INT)", index, "ALTER TABLE t DROP COLUMN b")) + + +def test_a_drop_column_an_opaque_index_does_not_name_keeps_the_index() -> None: + shape = declared_schema( + ( + "CREATE TABLE t (a INT, b INT, c INT)", + "CREATE INDEX ix ON t (a) WHERE b IS NOT NULL", + "ALTER TABLE t DROP COLUMN c", + ) + ) + assert "ix" in shape.named_indexes and shape.columns["t"] == frozenset({"a", "b"}) + + +def test_a_legacy_sqlserver_drop_index_names_its_table() -> None: + shape = declared_schema( + ( + "CREATE TABLE t (a INT NULL)", + "CREATE TABLE u (a INT NULL)", + "CREATE INDEX ix ON u (a)", + "DROP INDEX t.ix", + ), + "sqlserver", + ) + assert shape.named_indexes["ix"].table == "u" + gone = declared_schema( + ("CREATE TABLE u (a INT NULL)", "CREATE INDEX ix ON u (a)", "DROP INDEX u.ix"), + "sqlserver", + ) + assert "ix" not in gone.named_indexes + + +@pytest.mark.parametrize( + "statements", + [ + ("CREATE TABLE t (a INT)", "ALTER TABLE t ADD CONSTRAINT nn_a NOT NULL a NOT VALID"), + ("CREATE TABLE t (a INT, CONSTRAINT nn_a NOT NULL a)",), + ("CREATE TABLE t (a INT, NOT NULL a)",), + ], +) +def test_a_not_null_table_constraint_raises(statements: tuple[str, ...]) -> None: + with pytest.raises(ValueError, match="not-null constraint"): + declared_schema(statements, "postgres") + + +def test_the_postgres_expected_shape_holds_no_table_the_migration_drops() -> None: + """The migration runs ``DROP TABLE IF EXISTS lane_leases`` outside the declared batch, so the + expected shape must not hold that table, or every open would report it missing.""" + postgres = pytest.importorskip( + "messagefoundry.store.postgres", reason="requires the postgres extra (asyncpg)" + ) + assert "lane_leases" not in postgres._declared_schema().columns From 86e6bed3d594d48d3b11863dc776d04c30cb2cd6 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sat, 21 Nov 2026 18:24:34 -0600 Subject: [PATCH 15/74] Pin that a serve start before any rotate-key run on a keyless chain stamps BACKLOG #4942. A real Engine.start over a store opened through open_store as serve opens it, with no before_first_write hook (only rotate-key passes one, BACKLOG #4936), on a store with no keyed audit chain: it stamps the new key and opens no rotation record. The test passes on main: the open_store hook does not cover this case. Whether the order is refused, held, or left to the PHI.md warning is the row's open decision. Proposed PR title: Server schema check reads or refuses the DDL forms it misread; pin the keyless-chain serve-before-rotate-key stamp (BACKLOG #5062, #4942) Proposed banners: #5062 PARTIAL: items 3, 4 and 5 built except as left; item 1 partly (DROP COLUMN over an opaque index, legacy DROP INDEX table.index, PRIMARY KEY in a CHECK literal, second CREATE TABLE, Postgres 18 NOT NULL built); item 2 partly (DATABASE_DEFAULT/CATALOG_DEFAULT, bracket scanners, default docstring premise built). Remains: skip_tables from taken, unguarded ALTER COLUMN, DDL in a non-run literal, EXEC-string cut clauses, ADD PRIMARY KEY vs SET NOT NULL, cross-type default opclass, first parse on the event loop, multi-token DEFAULT messages, scratch-schema altitude, lower-cased refusal, item 6, item 7's postgres.py rollback finding, the dead label branch, and test_store_schema_hash's cannot-fail assertion. #4942 PARTIAL: the open_store hook does not cover a serve start before any rotate-key run on a keyless chain; it still stamps, pinned by a test. Step 1's decision (warning alone, or refuse or hold) is the owner's. --- tests/test_rotate_key_rotation_record.py | 38 ++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/tests/test_rotate_key_rotation_record.py b/tests/test_rotate_key_rotation_record.py index 0eae5cc024..ceac37b7be 100644 --- a/tests/test_rotate_key_rotation_record.py +++ b/tests/test_rotate_key_rotation_record.py @@ -941,3 +941,41 @@ async def test_engine_start_passes_the_chain_answer_and_holds_the_key(tmp_path: assert rows[_DEK].fingerprint == dek_fingerprint(_key_id(key_a)) assert rows[_DEK].last_rotated == _OLD_DATE assert rows[ROTATION_RECORD_ID].fingerprint == dek_fingerprint(_key_id(key_b)) + + +async def test_engine_start_before_any_run_on_a_store_with_no_keyed_chain_still_stamps( + tmp_path: Path, +) -> None: + """BACKLOG #4942's remainder, as the code stands. A ``serve`` start on a new key before any + ``rotate-key`` run, on a store with no keyed audit chain: the store is opened through + ``open_store`` as ``serve`` opens it, with no ``before_first_write`` hook (only ``rotate-key`` + passes one, BACKLOG #4936), and a real ``Engine.start`` runs the reconcile. Nothing tells this + start from a key changed by hand after a run, so it stamps the new key and opens no record. + Whether this order is to be refused or held, or left to the warning, is the row's open + decision; this test pins what the code does until it is made.""" + from messagefoundry.config.settings import EgressSettings, StoreSettings + from messagefoundry.pipeline.engine import Engine + from messagefoundry.store.base import open_store + + db, key_a, key_b = tmp_path / "keyless.db", generate_key(), generate_key() + await _seed_keyless_chain(db, tmp_path / "uploads", key_a) + store = await open_store( + StoreSettings(path=str(db), encryption_key=key_b, encryption_keys_retired=key_a), + keyless_chain_refusal=None, + ) + assert isinstance(store, MessageStore) + assert audit_chain_rolled(store) is None # no keyed chain to answer from + engine = Engine( + store, + secret_rotation_settings=SecretRotationSettings(), + security_enforcement=SecurityEnforcement.WARN, + egress_settings=EgressSettings(deny_by_default=False), + ) + try: + await engine.start() + rows = await store.get_secret_rotation_meta() + finally: + await engine.stop() + assert rows[_DEK].fingerprint == dek_fingerprint(_key_id(key_b)) + assert rows[_DEK].last_rotated != _OLD_DATE + assert ROTATION_RECORD_ID not in rows From e2bff915e350f1023ce61c4e5b71cd75379fa62f Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sat, 21 Nov 2026 18:25:16 -0600 Subject: [PATCH 16/74] Store schema check: drop remedy for a foreign view or trigger, refuse a shape error from the read BACKLOG #6719 item 3: SQLite's re-check after a migration's ALTER names a view or trigger it cannot parse ("error in view V: no such module"). That object is another tool's, since this build creates no view and no trigger (now pinned), so run_schema_step gives the remedy to drop it rather than to recreate the store. Measured: with the object dropped, the RENAME COLUMN migration runs. BACKLOG #6720 item 4: verify_live_schema's own read now goes through run_schema_step, so a shape failure there (an unloaded virtual table whose stored SQL the ordinary-table predicate does not recognise, under an expected name) is refused with the remedy instead of escaping as the bare OperationalError. run_schema_step returns the step's result for this. BACKLOG #6720 item 1: measured not a failure on the local SQLite. A foreign view using an unloaded function or collation stops neither the script, the RENAME COLUMN migration nor the verify; a test pins that the open succeeds. --- .../6719-6720-foreign-view-remedy.fixed.md | 6 + messagefoundry/store/schema_verify.py | 53 ++++-- tests/test_schema_verify_6719_6720.py | 170 +++++++++++++++++- 3 files changed, 210 insertions(+), 19 deletions(-) create mode 100644 changelog.d/6719-6720-foreign-view-remedy.fixed.md diff --git a/changelog.d/6719-6720-foreign-view-remedy.fixed.md b/changelog.d/6719-6720-foreign-view-remedy.fixed.md new file mode 100644 index 0000000000..28db7e30f7 --- /dev/null +++ b/changelog.d/6719-6720-foreign-view-remedy.fixed.md @@ -0,0 +1,6 @@ +- **A SQLite store whose upgrade is stopped by a view or trigger another tool left now names that + object.** When SQLite's re-check after a migration's `ALTER` fails on a view or trigger, the open + refuses the store with the remedy to drop that object and restart, not to recreate the store. A + failure on the store's shape raised by the check's own read, after the schema script and the + migrations, is now refused with the recreate remedy rather than escaping as SQLite's bare error. + (`BACKLOG #6719`, `BACKLOG #6720`) diff --git a/messagefoundry/store/schema_verify.py b/messagefoundry/store/schema_verify.py index 1440d5bb69..beef8e52af 100644 --- a/messagefoundry/store/schema_verify.py +++ b/messagefoundry/store/schema_verify.py @@ -80,13 +80,23 @@ " so restarting under the old key would zero its AES-GCM use count, which lives in the store. If" " you set [secret_rotation].store_key_last_rotated, update it." ) +# The ALTER re-check's prefix when an object other than the altered table fails to parse. Only the +# view and trigger forms: this build creates neither (see _ORDINARY_TABLE), so the object named is +# another tool's. SQLite uses the same form for a table or an index, which may be this build's own. +_FOREIGN_OBJECT_PREFIXES = ("error in view ", "error in trigger ") +# Dropping a view or a trigger removes no row, so this remedy keeps the store and its key. +_REMEDY_FOREIGN = ( + "holds a view or trigger this build did not create, which stops its upgrade: drop that object," + " then restart." +) # The reads below skip a table whose stored SQL is LIKE 'CREATE VIRTUAL TABLE%', because a pragma # on a virtual table whose module is not loaded here can raise "no such module" (BACKLOG #6719). # The store builds none, and a test pins that, so an expected name held by a virtual table reads # as a missing table and is refused rather than skipped. -# THIS BUILD CREATES NO VIRTUAL TABLE AND NO VIEW, which tests/test_schema_verify_6719_6720.py -# pins; the other notes in this module rely on that and point here. +# THIS BUILD CREATES NO VIRTUAL TABLE, NO VIEW AND NO TRIGGER, which +# tests/test_schema_verify_6719_6720.py pins; the other notes in this module rely on that and point +# here. _ORDINARY_TABLE = "m.type = 'table' AND m.sql NOT LIKE 'CREATE VIRTUAL TABLE%'" # Each pragma is read through its table-valued form, so one statement reads every table, and the # table names travel as bound parameters rather than being spliced into SQL. Only tables the EXPECTED @@ -125,7 +135,8 @@ class SchemaMismatchError(sqlite3.DatabaseError): exits 2, the code it keeps apart from a negative finding (BACKLOG #1670). ``differences`` lists what the check found missing, one clause each. It is empty when the schema - script or a migration itself failed (BACKLOG #2101), and then ``cause`` holds that failure's text. + script, a migration or this check's own read failed (BACKLOG #2101, #6720), and then ``cause`` + holds that failure's text. Both are kept apart from the message so a caller whose remedy differs, such as a restore-verify of an old backup, can word its own refusal without parsing this one. """ @@ -338,8 +349,18 @@ async def verify_live_schema( holds a count but no store salt was last written under the DEK, so an operator shell without the service's key still gets the new-key remedy. A process that HAS a key is never overruled by the file, because a restored cell-bound store also has counts and no salt row until its first open. + + A read that fails on the store's shape is refused the same way, through + :func:`run_schema_step` (BACKLOG #6720): a virtual table whose stored SQL the + ``_ORDINARY_TABLE`` predicate does not recognise, held under an expected name, raises "no such + module" from the column read rather than reading as a difference. """ - problems = await live_schema_differences(db, schema=schema, migrate=migrate) + problems = await run_schema_step( + db, + live_schema_differences(db, schema=schema, migrate=migrate), + path=path, + counts_under_dek=counts_under_dek, + ) if problems: if counts_under_dek is None: counts_under_dek = await _counts_under_a_dek(db) @@ -393,28 +414,38 @@ def is_schema_step_error(exc: BaseException) -> bool: ) -async def run_schema_step( +async def run_schema_step[T]( db: aiosqlite.Connection, - step: Awaitable[object], + step: Awaitable[T], *, path: object, counts_under_dek: bool | None, -) -> None: - """Await the schema script or the migrations, turning a shape failure into a refusal. +) -> T: + """Await the schema script, the migrations or the verify's read, turning a shape failure into a + refusal, and return what the step returned. A failure :func:`is_schema_step_error` accepts is raised as :class:`SchemaMismatchError`, from the original so the driver's text stays in the chain (BACKLOG #2101). It carries the remedy a verify refusal carries, chosen the same way: a statement that fails on an existing object's shape is the same incompatible version the verify reports, found one step earlier. Any other - failure propagates unchanged.""" + failure propagates unchanged. + + One shape failure gets another remedy: SQLite's re-check of the schema after an ``ALTER`` + names the view or trigger it could not parse, as in "error in view V: no such module". This + build creates neither kind, so that object is another tool's, and dropping it lets the + migration run past it (BACKLOG #6719).""" try: - await step + return await step except Exception as exc: if not is_schema_step_error(exc): raise + cause = str(exc) + if cause.startswith(_FOREIGN_OBJECT_PREFIXES): + raise SchemaMismatchError( + f"store {path} {_REMEDY_FOREIGN} The schema step failed: {cause}.", cause=cause + ) from exc if counts_under_dek is None: counts_under_dek = await _counts_under_a_dek(db) - cause = str(exc) raise SchemaMismatchError( f"store {path} {_remedy(counts_under_dek)} The schema step failed: {cause}.", cause=cause, diff --git a/tests/test_schema_verify_6719_6720.py b/tests/test_schema_verify_6719_6720.py index 5e39e13b26..4ce1eb12b8 100644 --- a/tests/test_schema_verify_6719_6720.py +++ b/tests/test_schema_verify_6719_6720.py @@ -200,10 +200,10 @@ async def test_a_counted_store_whose_salt_is_a_readable_foreign_object_gets_the_ _TABLES_FLAGGED_VIRTUAL = ( f"SELECT m.name, NOT ({_ORDINARY_TABLE}) FROM sqlite_master AS m WHERE m.type = 'table'" ) -#: Every schema object with a flag saying whether it is a view, so one walk both counts what it saw -#: and finds the views (a view query alone returns nothing on the built schema, so it cannot show it -#: ran). The flag is in the SQL, so the negative control below pins the same predicate. -_OBJECTS_FLAGGED_VIEW = "SELECT name, type = 'view' FROM sqlite_master" +#: Every schema object with a flag saying whether it is a view or a trigger, so one walk both counts +#: what it saw and finds those (a query for them alone returns nothing on the built schema, so it +#: cannot show it ran). The flag is in the SQL, so the negative control below pins the same predicate. +_OBJECTS_FLAGGED_VIEW = "SELECT name, type IN ('view', 'trigger') FROM sqlite_master" async def test_the_expected_shape_holds_no_virtual_table() -> None: @@ -227,16 +227,22 @@ async def test_the_expected_shape_holds_no_virtual_table() -> None: virtual = [name for name, is_virtual in tables if is_virtual] assert virtual == [] # The reads skip views too, so a view this build created would never be verified either - # (BACKLOG #6719 item 10). + # (BACKLOG #6719 item 10). And the foreign-object remedy tells the operator to drop a view or a + # trigger that stops an upgrade, which is safe only while this build creates neither. views = [name for name, is_view in objects if is_view] assert views == [] async def test_the_virtual_table_probe_finds_one_without_fts5(tmp_path: Path) -> None: # Negative control for the pin above that needs no fts5 (BACKLOG #6719 item 8): a planted - # virtual table is flagged, an ordinary one is not, and the view flag marks a view. + # virtual table is flagged, an ordinary one is not, and the view flag marks a view and a trigger. path = tmp_path / "probe.db" - _sql(path, "CREATE TABLE plain (a)", "CREATE VIEW v AS SELECT 1") + _sql( + path, + "CREATE TABLE plain (a)", + "CREATE VIEW v AS SELECT 1", + "CREATE TRIGGER tr AFTER INSERT ON plain BEGIN SELECT 1; END", + ) _plant_unloaded_virtual_table(path, "planted") async with _connected(path) as db: async with db.execute(_TABLES_FLAGGED_VIRTUAL) as cur: @@ -244,7 +250,7 @@ async def test_the_virtual_table_probe_finds_one_without_fts5(tmp_path: Path) -> async with db.execute(_OBJECTS_FLAGGED_VIEW) as cur: views = [name for name, is_view in await cur.fetchall() if is_view] assert rows == {"plain": False, "planted": True} - assert views == ["v"] + assert views == ["v", "tr"] async def test_a_planted_ordinary_table_with_rootpage_zero_is_not_skipped(tmp_path: Path) -> None: @@ -410,3 +416,151 @@ async def test_the_open_refuses_a_name_held_by_another_kind_of_object( assert text.startswith(f"store {path} is from an incompatible version; recreate it:"), text assert info.value.cause is not None and cause in info.value.cause, info.value.cause assert isinstance(info.value.__cause__, sqlite3.OperationalError) + + +# --- BACKLOG #6719 item 3: a foreign view or trigger that stops the upgrade ------------------------ + + +def _preset_columns(path: Path) -> set[str]: + conn = sqlite3.connect(path) + try: + return {r[1] for r in conn.execute("PRAGMA table_info(search_presets)")} + finally: + conn.close() + + +@pytest.mark.parametrize( + ("kind", "dependent", "drop"), + [ + pytest.param("view", "CREATE VIEW vv AS SELECT x FROM vt", "DROP VIEW vv", id="view"), + pytest.param( + "trigger", + "CREATE TRIGGER tt AFTER INSERT ON users BEGIN SELECT x FROM vt; END", + "DROP TRIGGER tt", + id="trigger", + ), + ], +) +async def test_a_foreign_object_that_stops_a_migration_gets_the_drop_remedy( + tmp_path: Path, kind: str, dependent: str, drop: str +) -> None: + # A 0.3.2 preset table needs the RENAME COLUMN migration, and SQLite re-checks every view and + # trigger after it. One that reads an unloaded module fails that check, naming itself. The store + # is otherwise this build's, so the remedy is to drop that object, not to recreate the store. + path = tmp_path / "foreign.db" + await _fresh(path) + _sql(path, "ALTER TABLE search_presets RENAME COLUMN owner_user_id TO owner") + _plant_unloaded_virtual_table(path, "vt") + name, table = dependent.split()[2], "vv" if kind == "view" else "users" + conn = sqlite3.connect(path) + try: + conn.execute("PRAGMA writable_schema = ON") + conn.execute( + "INSERT INTO sqlite_master (type, name, tbl_name, rootpage, sql) VALUES (?, ?, ?, 0, ?)", + (kind, name, table, dependent), + ) + conn.commit() + finally: + conn.close() + with pytest.raises(SchemaMismatchError) as info: + await _fresh(path) + cause = info.value.cause + assert cause is not None and cause.startswith(f"error in {kind} {name}: no such module"), cause + text = str(info.value) + assert text.startswith(f"store {path} holds a view or trigger this build did not create"), text + assert "recreate" not in text and "NEW store key" not in text, text + # The remedy is true: with that object dropped, the same migration runs and the open succeeds. + _sql(path, drop) + await _fresh(path) + assert "owner_user_id" in _preset_columns(path) + + +# --- BACKLOG #6720 item 4: the verify's own read -------------------------------------------------- + + +async def test_a_shape_error_from_the_verify_read_is_refused_with_the_remedy( + tmp_path: Path, +) -> None: + # No statement of the script or the migrations touches shared_body, so the first read of it is + # the verify's column read. A virtual table whose stored SQL the ordinary-table predicate does + # not recognise (two spaces) is read there, and its unloaded module raises. + path = tmp_path / "read.db" + await _fresh(path) + _sql( + path, + "DROP TABLE shared_body", + "PRAGMA writable_schema = ON", + "INSERT INTO sqlite_master (type, name, tbl_name, rootpage, sql) VALUES ('table'," + " 'shared_body', 'shared_body', 0," + " 'CREATE VIRTUAL TABLE shared_body USING no_such_module(x)')", + ) + with pytest.raises(SchemaMismatchError) as info: + await _fresh(path) + text = str(info.value) + assert text.startswith(f"store {path} is from an incompatible version; recreate it:"), text + assert "The schema step failed: no such module" in text, text + assert isinstance(info.value.__cause__, sqlite3.OperationalError) + + +async def test_a_read_error_that_is_not_a_shape_keeps_its_own_error( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + # Control: a read failure that recreating the store would not fix is not given the remedy. + from messagefoundry.store import schema_verify + + async def locked(*_args: object, **_kwargs: object) -> list[str]: + raise sqlite3.OperationalError("database is locked") + + monkeypatch.setattr(schema_verify, "live_schema_differences", locked) + async with _connected(":memory:") as db: + with pytest.raises(sqlite3.OperationalError) as info: + await schema_verify.verify_live_schema( + db, + schema=_SCHEMA, + migrate=MessageStore._migrate, + path="locked.db", + counts_under_dek=False, + ) + assert not isinstance(info.value, SchemaMismatchError) + assert str(info.value) == "database is locked" + + +# --- BACKLOG #6720 item 1: a foreign view using an unloaded function or collation ---------------- + + +@pytest.mark.parametrize( + "view", + [ + pytest.param("CREATE VIEW vf AS SELECT f(name) AS n FROM search_presets", id="function"), + pytest.param( + "CREATE VIEW vf AS SELECT name FROM search_presets ORDER BY name COLLATE mycoll", + id="collation", + ), + ], +) +async def test_a_foreign_view_using_an_unloaded_function_or_collation_stops_nothing( + tmp_path: Path, view: str +) -> None: + # Measured on the local SQLite: neither the script, the RENAME COLUMN migration nor the verify + # fails on such a view, so there is no failure for the step test to classify. Reading the view + # fails, as the control below shows, and the open succeeds all the same. + path = tmp_path / "foreign-view.db" + await _fresh(path) + _sql(path, "ALTER TABLE search_presets RENAME COLUMN owner_user_id TO owner") + conn = sqlite3.connect(path) + try: + conn.create_function("f", 1, lambda x: x) + conn.create_collation("mycoll", lambda a, b: (a > b) - (a < b)) + conn.execute(view) + conn.commit() + finally: + conn.close() + # Positive control: without the function or collation loaded, reading the view does fail. + conn = sqlite3.connect(path) + try: + with pytest.raises(sqlite3.OperationalError, match="no such (function|collation)"): + conn.execute("SELECT * FROM vf").fetchall() + finally: + conn.close() + await _fresh(path) + assert "owner_user_id" in _preset_columns(path) From e4531cc233b90890e745c6c7dce853e4edbde539 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sat, 21 Nov 2026 18:26:11 -0600 Subject: [PATCH 17/74] Release tests: run each wheel smoke under its step's own flags The execution tests in section (8) ran every smoke script and tag guard under a hardcoded -I, so the intact checkout they keep present could never answer: a release.yml step that dropped -I left them all green. _run_smoke now reads the interpreter flags the workflow feeds that exact script to (_step_flags), and the positive control re-runs the same install beside the same checkout with no flags and requires the in-venv guard to refuse it, so the checkout is shown to be live. Measured: with -I removed from the engine PYSMOKE line, the old file passes these tests (22 passed) and this file fails 6. BACKLOG #1583 (open step added 2026-11-07). --- tests/test_release_pipeline.py | 58 +++++++++++++++++++++++++++++++--- 1 file changed, 53 insertions(+), 5 deletions(-) diff --git a/tests/test_release_pipeline.py b/tests/test_release_pipeline.py index b25e22d6c5..1bdb7e761a 100644 --- a/tests/test_release_pipeline.py +++ b/tests/test_release_pipeline.py @@ -2089,12 +2089,50 @@ def _clone_venv(template: Path, root: Path) -> tuple[Path, Path]: return exe, Path(purelib) +#: A heredoc fed to an interpreter on stdin, as every release smoke and tag guard is fed: +#: ``python - [args] <<'TAG'``, the body, then ``TAG`` alone at column 0 of the +#: dedented ``run:`` block. ``flags`` stops at the first word that is not a dash flag, so a flag +#: that takes a value (``-X utf8``) makes the invocation unreadable here rather than misread. +_STDIN_HEREDOC = re.compile( + r"\S*python[0-9.]*(?P(?:[ \t]+-[A-Za-z]+)*)[ \t]+-(?=[ \t])[^\n]*<<'(?P[A-Z]+)'\n" + r"(?P.*?)\n(?P=tag)\n", + re.S, +) + + +@functools.cache +def _step_flags(script: str) -> tuple[str, ...]: + """The interpreter flags release.yml passes the interpreter that ``script`` is fed to. + + Read from the workflow by the script's own text, so an execution test runs a smoke or a tag + guard under the flags the step really uses (BACKLOG #1583). Before this, ``_run_smoke`` + hardcoded ``-I``, so the intact checkout the acceptance keeps present could never answer: a + step that dropped ``-I`` would have left every execution test here green. Two steps may carry + the same script, the engine's and the toolkit's tag guards for one, so the flags of every copy + must agree, or no single answer exists. + """ + found = { + tuple(m.group("flags").split()) + for job in _jobs().values() + for step in (job.get("steps") or []) + if isinstance(step, dict) + for m in _STDIN_HEREDOC.finditer(str(step.get("run") or "")) + if m.group("body") == script + } + assert len(found) == 1, ( + f"expected the script to be fed to exactly one interpreter flag list in release.yml, found " + f"{sorted(found)}: either no step feeds it on stdin any more, or two copies are run " + f"under different flags" + ) + return next(iter(found)) + + def _run_smoke( exe: Path, script: str, workdir: Path, *, - isolated: bool = True, + flags: Sequence[str] | None = None, args: Sequence[str] = (), ) -> tuple[int, str, str]: """Run ``script`` the way the step does; return (rc, stdout, combined output). @@ -2103,11 +2141,11 @@ def _run_smoke( ``built=$(...)`` and everything else the script says goes to stderr, so a diagnostic that leaked onto stdout would silently become the version the release compares against the tag. - ``-I`` matches the workflow. The one caller that drops it is the checkout-shadow control, which - exists to prove the in-venv assertion fires rather than that the flag is spelled right. + ``flags`` defaults to the step's own, read by :func:`_step_flags`. A caller passes other flags + only as a control, to show what the same run does without the step's isolation. ``args`` follow the ``-``, as ``python -I - "$built" "$want"`` passes them to a tag guard. """ - argv = [str(exe), *(["-I"] if isolated else []), "-", *args] + argv = [str(exe), *(_step_flags(script) if flags is None else flags), "-", *args] proc = subprocess.run( # noqa: S603 # nosec B603 - fixed argv, no shell, test-local paths argv, input=script.encode("utf-8"), @@ -2175,6 +2213,16 @@ def test_a_wheel_smoke_accepts_a_correctly_built_wheel( ) assert _SHADOW_VERSION not in out, f"the intact checkout answered {job}'s smoke.\n{out}" + # THE INTACT CHECKOUT IS LIVE (BACKLOG #1583's acceptance). The run above used the step's own + # flags, so its pass shows those flags keep the checkout out only if the checkout would + # otherwise get in. The same run without them must be refused for exactly that reason. + work = tmp_path / "checkout" + rc, _stdout, out = _run_smoke(exe, script, work, flags=()) + assert rc != 0 and "OUTSIDE the smoke venv" in out, ( + f"without the step's flags ({' '.join(_step_flags(script)) or 'none'}) the intact checkout " + f"did not reach {job}'s smoke, so the pass above does not show the flags keep it out.\n{out}" + ) + def _no_package_tree(purelib: Path, dist: str, pkg: str) -> None: """The force-include produced nothing. Installs cleanly, named exactly like a good wheel.""" @@ -2288,7 +2336,7 @@ def test_a_wheel_smoke_refuses_a_module_resolved_outside_the_smoke_venv( for rel, text in _good_package(pkg, "9.9.9").items(): (shadow / pkg / rel).write_text(text, encoding="utf-8") - rc, _stdout, out = _run_smoke(exe, script, shadow, isolated=False) + rc, _stdout, out = _run_smoke(exe, script, shadow, flags=()) assert rc != 0, ( f"{job}'s smoke accepted a module resolved from the CHECKOUT instead of the smoke venv — it " f"would report on the source tree and never open the wheel.\n{out}" From 4944cf0cef969ea4524da12eb011751fd76207cf Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sat, 21 Nov 2026 18:26:38 -0600 Subject: [PATCH 18/74] Pin audit-verify's walk against the widened store shape error test BACKLOG #6720 item 2: a collision error raised by verify_audit_chain is "could not start", exit 2, not the stopped-walk FAIL line; a syntax error, the control, still gets exit 1 and the FAIL line. A mutation that drops the is_store_shape_error arm in __main__ fails nine of the new cases. No __main__.py change. BACKLOG #6720 item 5: the file's docstring now names all three callers and says "at least" without a count, and the broken wrap is joined. Proposed PR title: Store schema check: foreign view or trigger remedy, verify read refusal, audit-verify shape pin (vault BACKLOG #6719, #6720, #6686, #6687) Proposed banners: - #6686: item 2 met by PR 3033 (the two loops left iterate over haystacks, not cases); item 1 met by PR 3033. PARTIAL only if the ledger holds other items. - #6687: item 10 met by PR 3033 (_HashingReader passes a non-bytes read through); item 8 open (a shared fill loop is a design choice); item 1 and the dr_backup copy-loop half left with dr_backup.py's owner. - #6719: item 3 fixed; items 4 and 5 open (store.py, not in this brief's files). - #6720: items 1 (measured, not a failure), 2, 4, 5 met; item 3 open (kind compare in place of message text is a design choice). --- tests/test_shape_error_callers_6720.py | 63 ++++++++++++++++++++++++-- 1 file changed, 58 insertions(+), 5 deletions(-) diff --git a/tests/test_shape_error_callers_6720.py b/tests/test_shape_error_callers_6720.py index bba8972958..3ee28619de 100644 --- a/tests/test_shape_error_callers_6720.py +++ b/tests/test_shape_error_callers_6720.py @@ -1,36 +1,44 @@ # SPDX-License-Identifier: AGPL-3.0-or-later # Copyright (C) 2026 MessageFoundry Foundation, LLC and contributors -"""BACKLOG #6720: two callers of ``base.is_store_shape_error`` that the widened +"""BACKLOG #6720: callers of ``base.is_store_shape_error`` that the widened ``schema_verify._SHAPE_MESSAGES`` reaches. An expected name held by an object of another kind (a view, an index, a table) now reads as a store -shape error. At least three callers outside the schema step act on that; this file pins these two -(the ``verify-audit-chain`` walk in ``__main__`` is the third, and is not covered here): +shape error. At least these callers outside the schema step act on that, and this file pins them: * ``auth.service._is_revoke_defect``: the post-commit session revoke raises such an error at once, unretried, and records no ``auth.sessions_revoke_failed`` row, as it does for any other defect. * ``store.note_audit_chain_read``: the open no longer tags such an error as row evidence about the audit chain, so it is reported as a store this build cannot read. +* ``audit-verify``'s walk in ``__main__``: such an error raised by ``verify_audit_chain`` is + "could not start", exit 2, rather than the stopped-walk FAIL line and exit 1. Each case is a real SQLite error from every collision ``test_schema_verify_6719_6720`` measures, so the code and the text are SQLite's own and a collision added there is pinned here too. The control -is a -syntax error: the same ``SQLITE_ERROR`` code, but not a shape message, which keeps the old handling. +is a syntax error: the same ``SQLITE_ERROR`` code, but not a shape message, which keeps the old +handling. """ from __future__ import annotations +import contextlib +import io import sqlite3 +from pathlib import Path from typing import Any import pytest +from messagefoundry.__main__ import main from messagefoundry.auth import service as service_module from messagefoundry.auth.passwords import hash_password from messagefoundry.auth.service import SESSIONS_REVOKE_FAILED_ACTION, AuthService from messagefoundry.config.settings import AuthSettings from messagefoundry.store.base import is_store_shape_error +from messagefoundry.store.crypto import generate_key from messagefoundry.store.store import AUDIT_CHAIN_READ_NOTE, MessageStore, note_audit_chain_read +from tests.test_audit_keyless_chain_flagged import _AT_REST_ENV +from tests.test_keyless_chain_every_command import _keyed_chain from tests.test_schema_verify_6719_6720 import _COLLISIONS _PASSWORD = "Str0ng-Synthetic-Pass!!" @@ -142,3 +150,48 @@ def test_a_sqlite_error_that_is_not_a_shape_is_still_tagged() -> None: exc = _not_shape() note_audit_chain_read(exc) assert AUDIT_CHAIN_READ_NOTE in getattr(exc, "__notes__", ()) + + +# --- audit-verify's walk --------------------------------------------------------------------------- + + +def _audit_verify_with_a_walk_raising( + exc: Exception, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> tuple[int, str, str]: + """``audit-verify`` against a real keyed chain whose walk raises ``exc``. Returns the exit code, + stdout and stderr.""" + monkeypatch.chdir(tmp_path) + for name in _AT_REST_ENV: + monkeypatch.delenv(name, raising=False) + key = generate_key() + db = tmp_path / "keyed.db" + _keyed_chain(db, key) + monkeypatch.setenv("MEFOR_STORE_ENCRYPTION_KEY", key) + + async def raising(self: MessageStore, **kwargs: object) -> object: + raise exc + + monkeypatch.setattr(MessageStore, "verify_audit_chain", raising) + out, err = io.StringIO(), io.StringIO() + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): + rc = main(["audit-verify", "--db", str(db)]) + return rc, out.getvalue(), err.getvalue() + + +@pytest.mark.parametrize(("existing", "step"), _COLLISIONS) +def test_a_name_held_by_another_kind_of_object_stops_audit_verify_as_could_not_start( + existing: str, step: str, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + exc = _sqlite_error("CREATE TABLE other (a TEXT)", existing, step) + rc, out, err = _audit_verify_with_a_walk_raising(exc, tmp_path, monkeypatch) + assert rc == 2, (out, err) + assert "cannot open the store" in err, err + assert not out.startswith("FAIL: "), out + + +def test_a_sqlite_error_that_is_not_a_shape_still_stops_audit_verify_with_a_fail_line( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + rc, out, err = _audit_verify_with_a_walk_raising(_not_shape(), tmp_path, monkeypatch) + assert rc == 1, (out, err) + assert out.startswith("FAIL: the audit chain check stopped part way"), out From d73e72a4b5bed9e906b4e4c602cdb95122d4388a Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sat, 21 Nov 2026 18:27:35 -0600 Subject: [PATCH 19/74] Release tests: record why the short subprocess timeout stays 60 s The three hardcoded timeout=60 calls (leak gate, isolation probe, notes lines) now share one constant whose comment records the decision. Not raised: CI passes pytest a per-test --timeout (60 s ubuntu, 120 s Windows, ci.yml matrix pytest_timeout), and with --timeout-method=thread pytest-timeout ends the worker process when it fires. A larger value is never reached on ubuntu, and above 120 s on Windows it trades a named failure for a dead worker. Not measured on a windows-2025 runner. BACKLOG #3633 item 2. --- tests/test_release_pipeline.py | 26 +++++++++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/tests/test_release_pipeline.py b/tests/test_release_pipeline.py index 1bdb7e761a..1ab9e51185 100644 --- a/tests/test_release_pipeline.py +++ b/tests/test_release_pipeline.py @@ -1204,6 +1204,22 @@ def _posix_tool_env() -> dict[str, str]: return env +#: The timeout for a short subprocess here: a bash run of an extracted step, or a one-line probe. +#: It catches a hang. It does not measure speed: nothing in this file reads a duration. +#: +#: WHY IT STAYS AT 60 S (BACKLOG #3633 item 2). That row records one overrun: on engine PR 2327's +#: run 38674972250, `over-long-body[console]` took 84.5 s in notes.sh on windows-2025, and that +#: PR's CI triage comment reports the same tree passing on windows-2022 in the same run. On a +#: Windows 11 dev box the test took about 1.6 s (measured 2026-11-21). Nothing here was measured on +#: a windows-2025 runner. Raising this alone would not help. The CI test legs run pytest with a +#: per-test `--timeout`, its matrix `pytest_timeout` in ci.yml: 60 s on ubuntu, 120 s on Windows. +#: With `--timeout-method=thread`, pytest-timeout ends the whole worker process when that fires, +#: rather than failing the one test with this call's output. So on ubuntu a value above 60 s is +#: never reached, and on Windows one above 120 s trades a named failure for a dead worker. Allowing +#: a longer stall needs the per-test cap raised too, for these tests or for the leg. +_HANG_TIMEOUT_S = 60 + + def _run_leak_gate(bash: str, workdir: Path, script: Path, env: dict[str, str]) -> tuple[int, str]: """Run the extracted step from ``workdir`` the way the runner would; return (rc, combined output). @@ -1221,7 +1237,7 @@ def _run_leak_gate(bash: str, workdir: Path, script: Path, env: dict[str, str]) cwd=str(workdir), env=env, capture_output=True, - timeout=60, + timeout=_HANG_TIMEOUT_S, ) return proc.returncode, (proc.stdout + proc.stderr).decode("utf-8", "replace") @@ -3227,7 +3243,7 @@ def _run_probe( text=True, encoding="utf-8", errors="replace", - timeout=60, + timeout=_HANG_TIMEOUT_S, check=False, ) @@ -3857,7 +3873,11 @@ def _run_notes_prefix(tmp_path: Path, case: str, changelog: str, *, bounded: boo env["GITHUB_REPOSITORY"] = "MEFORORG/MessageFoundry" bash = require_bash(tmp_path, env) proc = subprocess.run( # noqa: S603 # nosec B603 - fixed argv, no shell, test-local paths - [bash, "-e", str(script)], cwd=str(work), env=env, capture_output=True, timeout=60 + [bash, "-e", str(script)], + cwd=str(work), + env=env, + capture_output=True, + timeout=_HANG_TIMEOUT_S, ) out = (proc.stdout + proc.stderr).decode("utf-8", "replace") assert proc.returncode == 0, ( From 17176933f133337aa0d386d0122311c50bd7aebd Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sat, 21 Nov 2026 18:31:01 -0600 Subject: [PATCH 20/74] Revocation census: review round 1 fixes to the exempt pin's comments and messages Vault BACKLOG #3512, steps 6 and 12, review round-20ce05f17f. The comments no longer say the pin catches a downgrade outright: a diff that edits _EXEMPT_SITES too still passes, and review is the check on it. The unlisted-site message names _EXEMPT_SITES, the pin's message says what to do, and the residual bullet reads as a hypothetical call. Correction to the previous commit's body: the current _GUARDS floors (the counts and wrappers floors) are from engine PR 2586; engine PR 2544 built the first. Proposed PR title: Revocation census pins its exempt sites and floors its membership tests; crypto residual names the via-token limit (BACKLOG #3512) Proposed banner: PARTIAL - step 6 built (exempt pin, membership floors; the _GUARDS floor was already met, by engine PRs 2544 and 2586). Step 12 declined as a design choice (via-token granularity or a sign/verify split), limit recorded in the crypto_operations residual. --- scripts/security/crypto_operations.py | 6 +++--- tests/test_revocation_guard_census.py | 21 +++++++++++++-------- 2 files changed, 16 insertions(+), 11 deletions(-) diff --git a/scripts/security/crypto_operations.py b/scripts/security/crypto_operations.py index 1d14aa0b2a..ac5b3a9bb6 100644 --- a/scripts/security/crypto_operations.py +++ b/scripts/security/crypto_operations.py @@ -31,9 +31,9 @@ * a SECOND call to a callee a file already lists. The inventory is kept per file and token, so a new ``hashlib.sha256`` call beside an existing one changes nothing; * a call to ANOTHER provider in a module a file already reaches, for a class the file already lists - through it. A ``via`` token names the module and the class, not the function, so a call from - ``pipeline/cert_expiry.py`` to ``pki.make_self_signed``, which signs, adds no token beside the - ``sign_verify:via messagefoundry.pki`` its CRL signature check already holds (vault BACKLOG #3512); + through it. A ``via`` token names the module and the class, not the function, so a new call from + ``pipeline/cert_expiry.py`` to ``pki.make_self_signed``, which signs, would add no token beside + the ``sign_verify:via messagefoundry.pki`` its CRL signature check holds (vault BACKLOG #3512); * an algorithm or TLS value held in a VARIABLE. A token carries the algorithm only when the call names it, in the callee or as a literal or named constant anywhere in its arguments; * a plain ``ctx.options = ...`` or ``setattr(ctx, "options", ...)``. ``options`` is too common a diff --git a/tests/test_revocation_guard_census.py b/tests/test_revocation_guard_census.py index 6509154fdf..3691aa4c4c 100644 --- a/tests/test_revocation_guard_census.py +++ b/tests/test_revocation_guard_census.py @@ -328,9 +328,9 @@ def __post_init__(self) -> None: } #: The sites :data:`_CENSUS` lists as Exempt, pinned exactly (vault BACKLOG #3512). A Guarded hop -#: moved to Exempt, with its guard call deleted, can pass every other check here (a relaxed -#: hop fails its own census below), so this list is the second edit such a change needs, and review sees it. A diff that -#: edits both still passes. +#: moved to Exempt, with its guard call deleted, can pass every other check here (a relaxed hop +#: fails its own census below), so this list is the second edit such a change needs. A diff that +#: edits both still passes, so review stays the check on what is added here. _EXEMPT_SITES = frozenset( { "messagefoundry/apiclient/client.py::_build_verify_context", @@ -464,7 +464,7 @@ def _scan() -> _Scan: def test_every_site_is_in_the_census() -> None: """The check that stops the next unguarded hop: a new site fails here until it is classified.""" sites = _scan().sites - # 42 sites when this floor was set (vault BACKLOG #3512), so 30 lets twelve go with no edit here. + # 42 sites when this floor was set (vault BACKLOG #3512), so 30 lets twelve go with no edit. # It fails a scan that finds nothing, over which the check below would pass. assert len(sites) >= 30, f"the scan found only {len(sites)} sites, floor 30" unlisted = sorted(sites - _CENSUS.keys()) @@ -472,7 +472,8 @@ def test_every_site_is_in_the_census() -> None: f"verifying client TLS context(s) with no census entry: {unlisted}. Add a guard " f"(RevocationHopGuard.capture, refuse_unrevoked_verified_hop for an https hop, or " f"mount_strict_reply_adapter for an hvac Vault client, which must not use " - f"RevocationHopGuard) and list the site as Guarded, or list it as Exempt with the reason. " + f"RevocationHopGuard) and list the site as Guarded, or list it as Exempt with the reason " + f"and add it to _EXEMPT_SITES. " f"See ADR 0173 and docs/DEPLOYMENT.md, 'Revocation-guard behavior'." ) @@ -491,7 +492,8 @@ def test_every_guarded_site_calls_a_guard() -> None: guarded = {site: entry for site, entry in _CENSUS.items() if isinstance(entry, Guarded)} # 15 sites were Guarded when this floor was set, so 10 lets up to five retire with no edit here. # It is a floor against a census emptied or turned all Exempt, over which the check below would - # pass on nothing. A single hop moved from Guarded to Exempt is caught by the test below. + # pass on nothing. A single hop moved from Guarded to Exempt fails the test below, unless + # _EXEMPT_SITES moves too; review is the check on that. assert len(guarded) >= 10, f"only {len(guarded)} Guarded census entries, floor 10" unguarded = [ f"{site} (guard expected in {entry.by or 'the site itself'}; {entry.note or 'no note'})" @@ -502,9 +504,12 @@ def test_every_guarded_site_calls_a_guard() -> None: def test_the_exempt_sites_are_the_pinned_list() -> None: - """A Guarded hop moved to Exempt fails here, naming it, unless :data:`_EXEMPT_SITES` moves too.""" + """A Guarded hop moved to Exempt fails here, named, unless :data:`_EXEMPT_SITES` moves too.""" exempt = {site for site, entry in _CENSUS.items() if isinstance(entry, Exempt)} - assert sorted(exempt - _EXEMPT_SITES) == [], "census sites Exempt but not in _EXEMPT_SITES" + assert sorted(exempt - _EXEMPT_SITES) == [], ( + "census sites Exempt but not in _EXEMPT_SITES. Add a site to it only once review has read " + "the exemption's reason; a hop moved here from Guarded loses its revocation guard" + ) assert sorted(_EXEMPT_SITES - exempt) == [], ( "_EXEMPT_SITES names sites the census does not exempt" ) From 939fc45d167edd50edeb637099395befc92e182c Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sat, 21 Nov 2026 18:31:27 -0600 Subject: [PATCH 21/74] Release prose and tests: one draft refusal text, step-level variable gates docs/SUPPLY-CHAIN.md, The draft: the environment-copy cause now says "not `true` in any letter case", as the refusal does (Actions compares case-insensitively). The with-upload route says an engine-tag re-run also needs the pypi-engine artifact, kept at most 30 days. The past-30- days routes say to remove any pypi environment copy first. The organization prohibition comes before the steps it constrains, the publisher re-run names its jobs, the approval sentence is split, and the 172-character line is wrapped. The PEP 740 paragraph no longer says the console and harness publishes are gated on a repository variable. tests: the two draft publishers' refusals must be identical, and each of 17 listed clauses must appear in both the refusal and the doc. No step of either draft publisher may carry a variable gate in its if:, with a planted gate as the positive control. BACKLOG #2975 items 10, 11, 12, 16, 18, 21 and the SUPPLY-CHAIN.md part of item 17. --- docs/SUPPLY-CHAIN.md | 50 +++++++++++--------- tests/test_release_pipeline.py | 85 ++++++++++++++++++++++++++++++++++ 2 files changed, 113 insertions(+), 22 deletions(-) diff --git a/docs/SUPPLY-CHAIN.md b/docs/SUPPLY-CHAIN.md index 092d67d6ca..ea37a44170 100644 --- a/docs/SUPPLY-CHAIN.md +++ b/docs/SUPPLY-CHAIN.md @@ -162,7 +162,8 @@ Facts the labels leave out: are on PyPI by then. The refusal's text names two causes, a remedy with the upload and one without, but not which cause fired, and points here for the routes left past GitHub's re-run window. At least these two can fire, alone or together: - - The `pypi` environment holds its own copy of the variable, with a value other than `true`. + - The `pypi` environment holds its own copy of the variable, with a value that is not `true` in + any letter case. Look at that environment's variables in the repository settings to see whether it holds one now; a copy removed since the run cannot be seen there. - The build job read the variable before it was set, or the upload read it while it was unset @@ -170,36 +171,40 @@ Facts the labels leave out: fires; the remedies below clear it either way, so it need not be told apart. To finish the release with the upload, remove any copy from the `pypi` environment, then re-run - the build job (`release-harness` on an engine tag, `release-webconsole` on a console tag), which - re-runs the jobs after it, so the upload asks for the `pypi` approval again, and reads the - variable afresh in each, so it clears both. While the variable still reads `true`, a "Re-run - failed jobs" reuses the upload's outcome and is refused again. + the build job (`release-harness` on an engine tag, `release-webconsole` on a console tag). That + re-runs the jobs after it, so the upload asks for the `pypi` approval again, and each of those + jobs reads the variable afresh, which clears both causes. On an engine tag the re-run upload + also downloads the `pypi-engine` artifact, which the `release` job uploaded and which is kept + for at most 30 days, so it fails once that artifact has expired. While the variable still reads + `true`, a "Re-run failed jobs" reuses the upload's outcome and is refused again. To finish it without the upload, first check that no other release run that reads the variable - is queued, waiting or in progress, and that none can start before the restore below. Note - whether the repository holds the variable and its value. Remove any copy from the `pypi` - environment, give the repository variable a value that is not `true` in any letter case, such - as `false`, and re-run the publisher. A repository variable takes precedence over an - organization variable of the same name, so this changes the value for this repository only. Do - not edit or delete an organization copy, which other repositories may read. Once that re-run - has finished, whatever its result, and before the next release, restore the repository variable - to the value you noted, deleting it if the repository had none, or that release skips its upload - too and still goes public. + is queued, waiting or in progress, and that none can start before the restore below. Do not edit + or delete an organization copy of the variable in any of the steps that follow, because other + repositories may read it. Note whether the repository holds the variable and its value. Remove + any copy from the `pypi` environment, give the repository variable a value that is not `true` + in any letter case, such as `false`, and re-run the publisher (`publish-github-release` on an + engine tag, `publish-github-release-webconsole` on a console tag). A repository variable takes + precedence over an organization variable of the same name, so this changes the value for this + repository only. Once that re-run has finished, whatever its result, and before the next + release, restore the repository variable to the value you noted, deleting it if the repository + had none, or that release skips its upload too and still goes public. GitHub allows a re-run only within 30 days of a run's first attempt, so past that no re-run finishes the release. When this refusal is what holds the draft, at least two routes are left: the publisher's own command run by hand, `gh release edit --draft=false --repo MEFORORG/MessageFoundry`, which publishes the draft without that upload; and a new version - under a new tag. Run by hand on a draft held for any other reason, such as a failed build job - or a refused approval, the same command publishes a release with an asset missing or a package - not on PyPI. + under a new tag. On either route, first remove any copy of the variable from the `pypi` + environment, or the next release can be refused the same way. Run by hand on a draft held for + any other reason, such as a failed build job or a refused approval, the same command publishes + a release with an asset missing or a package not on PyPI. - **The provenance gate.** The tagged commit must be on `main`, and for each required check, the latest run of every workflow and trigger that ran it on that commit must have passed. A red run after the merge blocks the tag even if the merge-queue run passed, and a green from another workflow or trigger does not clear it. To clear it, re-run the failed jobs of the workflow run the refusal names, or run that workflow on the same trigger again, then re-run the release. GitHub - re-runs a workflow run only within 30 days of it. A check still running is waited for. A check the server requires that never ran on the commit also - blocks it; tag a newer commit that ran it. + re-runs a workflow run only within 30 days of it. A check still running is waited for. A check + the server requires that never ran on the commit also blocks it; tag a newer commit that ran it. ## What we publish, per release @@ -220,9 +225,10 @@ has no SBOM of its own. Apart from that, every row but one covers the **engine** only. The exception is the PEP 740 row: every PyPI publish job in `release.yml` sets `attestations: true`. So the web console wheel (`messagefoundry-webconsole`) -and the harness wheel get a PyPI-side attestation whenever their PyPI publish runs. Both of those -publishes are gated on a repository variable. That is all they get: their release jobs have no -Sigstore, SBOM or SLSA step. +and the harness wheel get a PyPI-side attestation whenever their PyPI publish runs. Each of those +publishes runs only when its variable, `PUBLISH_WEBCONSOLE` or `PUBLISH_HARNESS`, reads `true`; +*The draft* above says what a copy in the `pypi` environment does. That is all they get: their +release jobs have no Sigstore, SBOM or SLSA step. Additional CycloneDX SBOMs — the **VS Code extension** (npm) and the **container image** (Debian base + system libs + installed Python) — are produced by the daily/​on-demand `security.yml` workflow and diff --git a/tests/test_release_pipeline.py b/tests/test_release_pipeline.py index 1ab9e51185..f3c20e8ab3 100644 --- a/tests/test_release_pipeline.py +++ b/tests/test_release_pipeline.py @@ -4429,6 +4429,91 @@ def test_a_draft_publisher_refuses_while_the_variable_is_set_and_the_upload_did_ assert not any("--draft=false" in c for c in calls), calls +#: The draft publishers' refusal, as each step echoes it. +_DRAFT_REFUSAL = re.compile(r'echo "(::error::\$GATE_NAME is \'true\'[^"\n]*)"') + +#: Clauses of that refusal which docs/SUPPLY-CHAIN.md, *The draft*, must carry too. Compared after +#: :func:`_flat_text`, so the doc's backticks and line wraps do not count, and with the refusal's +#: `$GATE_NAME` read as the doc's "the variable". A clause listed here and dropped from either copy, +#: the organization prohibition among them, is named by the test below (vault BACKLOG #2975 item +#: 16). The list is not every clause: the publisher re-run step, for one, is worded differently in +#: the two copies and is not compared. +_DRAFT_REFUSAL_CLAUSES = ( + "holds its own copy of the variable, with a value that is not true in any letter case", + "a copy removed since", + "the remedies below clear it either way, so it need not be told apart", + "remove any copy from the pypi environment", + "re-runs the jobs after it", + "a re-run failed jobs reuses the upload", + "is queued, waiting or in progress", + "none can start before the restore", + "note whether", + "such as false", + "for this repository only", + "do not edit or delete an organization copy", + "other repositories may read", + "whatever its result, and before the next release", + "deleting it if", + "or that release skips its upload too and still goes public", + "within 30 days of a runs first attempt", +) + + +def _flat_text(text: str) -> str: + """``text`` in lower case, with quotes and backticks dropped and whitespace runs made one space.""" + return " ".join(re.sub(r"[`'\"]", "", text).lower().split()) + + +def test_the_draft_refusal_is_one_text_and_the_doc_carries_each_clause() -> None: + """The refusal is kept by hand in three places: the two draft publishers' `::error::` strings + and docs/SUPPLY-CHAIN.md, *The draft* (vault BACKLOG #2975 item 16). The two strings must be + identical, and each clause in `_DRAFT_REFUSAL_CLAUSES` must be in both the string and the doc. + + Mutation: edit one publisher's string, or drop a clause, such as the organization prohibition, + from the string or the doc. Red here.""" + jobs = _jobs() + texts = [] + for publisher in (_PUBLISH_JOB, _CONSOLE_PUBLISH_JOB): + run = _executed_shell(str(_release_step(jobs[publisher], "--draft=false").get("run"))) + found = _DRAFT_REFUSAL.findall(run) + assert len(found) == 1, f"{publisher}: expected one draft refusal, found {len(found)}" + texts.append(found[0]) + assert texts[0] == texts[1], ( + f"{_PUBLISH_JOB} and {_CONSOLE_PUBLISH_JOB} echo different refusals; they share one text" + ) + doc = (_REPO / "docs" / "SUPPLY-CHAIN.md").read_text(encoding="utf-8") + start = doc.index("- **The draft.**") + section = _flat_text(doc[start : doc.index("- **The provenance gate.**", start)]) + refusal = _flat_text(texts[0].replace("$GATE_NAME", "the variable")) + # A floor, so an emptied clause list cannot pass vacuously. + assert len(_DRAFT_REFUSAL_CLAUSES) >= 15, _DRAFT_REFUSAL_CLAUSES + missing = [ + f"{clause!r} not in the {where}" + for clause in _DRAFT_REFUSAL_CLAUSES + for where, text in (("refusal", refusal), ("doc", section)) + if clause not in text + ] + assert not missing, "\n".join(missing) + + +@pytest.mark.parametrize("publisher", [_PUBLISH_JOB, _CONSOLE_PUBLISH_JOB]) +def test_no_step_of_a_draft_publisher_is_gated_on_a_variable(publisher: str) -> None: + """The job-level walk, `_variable_gated_jobs`, reads no step's `if:` (vault BACKLOG #2975 item + 12). A publisher step skipped by an unset variable leaves the release a draft on a green run, + so no step of either draft publisher may carry a variable gate. The planted gate is the + positive control. + + Mutation: put `if: vars.PUBLISH_HARNESS == 'true'` on a draft publisher's step. Red here.""" + jobs = copy.deepcopy(_jobs()) + steps = [s for s in jobs[publisher]["steps"] if isinstance(s, dict)] + assert steps, f"{publisher} has no steps" + gated = [s.get("name") for s in steps if _is_variable_gated(s)] + assert not gated, f"{publisher} step(s) {gated} are gated on a variable; unset, they skip" + publish = _release_step(jobs[publisher], "--draft=false") + publish["if"] = "vars.PUBLISH_HARNESS == 'true'" + assert [s.get("name") for s in steps if _is_variable_gated(s)] == [publish.get("name")] + + # --- (14) every PyPI publish runs in a publish-only job that names `pypi` (vault BACKLOG #2631) ------ # # The environment key sits on a whole job. Put on a job that also builds, an approval on the From 56c493dca92e769ba748c35b028d4f7eb1e0440c Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sat, 21 Nov 2026 18:34:00 -0600 Subject: [PATCH 22/74] Review round 2: the escape check reads each line and leaves the escape spelling to json From the xhigh review of round-db50fc15 on this branch: - _assert_escaped checks that every line is printable ASCII, so indented JSON passes; with the tests' decode-back checks that proves each character was escaped, so the hand-built, lowercase-only escape list is gone. - The control names the assert it expects, and also passes indented output. - Each CLI test reads the captured output before it asserts the exit code, and names the code by its constant. Vault BACKLOG #2891, PR 2390 note 3. This commit's banners supersede the earlier commits' on this branch. Proposed PR title: Batch 284: check-privileges --json escape tests; route-walk items already met Proposed banners: - #2891: PR 2390 note 3 met as the row's note 3 paragraph defines it: the printed --json text, result and error, is ASCII with every control and bidi character escaped, under a test that fails without ensure_ascii. The decoded value still holds the characters, so a consumer that prints it must escape it. Open, unchanged: note 2 (and item 4, the terminal_text.py docstring tied to it) waits on an owner ruling; the other PR 2390 notes as the row records them. - #3177: added items 5 to 15 read met at engine main by PR 3015 (cd0a4a2f907), checked against the code and tests: 5, 6, 11, 12 fixed with tests; 7, 10, 13, 14, 15 fixed in docstrings and tests; 8 kept as the refusal (a mount cycle raises RecursionError, pinned by a test); 9 kept because a served app nests a handful of mounts and one walk per level keeps the refusal free of shared state. PR 3015's own open findings were left for the Lander to file under R2; where they landed is not checked here. --- tests/test_store_privilege_check.py | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/tests/test_store_privilege_check.py b/tests/test_store_privilege_check.py index c6ee1e24b2..5ec9b438bf 100644 --- a/tests/test_store_privilege_check.py +++ b/tests/test_store_privilege_check.py @@ -638,17 +638,17 @@ def test_cli_json_reports_every_family_and_no_secret( def _assert_escaped(out: str) -> None: - line = out.rstrip("\n") - assert line.isascii() and line.isprintable(), f"--json output carries a raw character: {out!r}" - for ch in sorted({ch for ch in _HOSTILE if not (ch.isascii() and ch.isprintable())}): - assert f"\\u{ord(ch):04x}" in out, f"--json output lacks the escape for {ch!r}: {out!r}" + """Every line of ``out`` is printable ASCII. With the caller's check that ``out`` decodes back + to :data:`_HOSTILE`, that proves each of its characters was written as an escape.""" + raw = [line for line in out.splitlines() if not (line.isascii() and line.isprintable())] + assert not raw, f"--json output carries a raw character: {out!r}" def test_the_escape_assertion_fails_on_unescaped_json() -> None: """The control for :func:`_assert_escaped`: output written without ``ensure_ascii`` fails it.""" - with pytest.raises(AssertionError): + with pytest.raises(AssertionError, match="carries a raw character"): _assert_escaped(json.dumps({"error": _HOSTILE}, ensure_ascii=False)) - _assert_escaped(json.dumps({"error": _HOSTILE})) + _assert_escaped(json.dumps({"error": _HOSTILE}, indent=2)) def test_cli_json_result_escapes_controls_and_bidi_in_a_detail( @@ -660,9 +660,10 @@ def test_cli_json_result_escapes_controls_and_bidi_in_a_detail( ) _stub_probe(monkeypatch, report) argv = ["check-privileges", "--service-config", str(_server_toml(tmp_path)), "--json"] - assert main(argv) == 4 - out = capsys.readouterr().out + code = main(argv) + out = capsys.readouterr().out # read first, so a failing assert never echoes it raw _assert_escaped(out) + assert code == EXIT_UNOBSERVABLE store = next(h for h in json.loads(out)["hops"] if h["hop"] == "store") assert _HOSTILE in store["detail"] @@ -674,9 +675,10 @@ def test_cli_json_error_escapes_controls_and_bidi_in_the_message( monkeypatch.setattr( "messagefoundry.__main__._load_service_settings", lambda *a, **k: (None, _HOSTILE) ) - assert main(["check-privileges", "--service-config", "unused.toml", "--json"]) == 1 + code = main(["check-privileges", "--service-config", "unused.toml", "--json"]) out = capsys.readouterr().out _assert_escaped(out) + assert code == EXIT_SETTINGS assert json.loads(out) == {"error": _HOSTILE} From cc620a83b9741f7ce46be70eaecdaf5cc64c5818 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sat, 21 Nov 2026 18:34:10 -0600 Subject: [PATCH 23/74] Round 1 review fixes for the route-body refusal rows Narrow the changelog fragment to the two helpers it covers and name the route-body refusals still unrecorded; say which function decides when audit_gate_refused is written; make the failed-write test assert that its 500 comes from the refusal-row write. BACKLOG #1197. Proposed PR title: Route-body step-up refusals write an audit row (BACKLOG #1197) --- .../1197-route-body-step-up-refusal.security.md | 17 ++++++++++------- messagefoundry/auth/service.py | 6 +++--- tests/test_derived_gate_decision_audit.py | 7 ++++++- 3 files changed, 19 insertions(+), 11 deletions(-) diff --git a/changelog.d/1197-route-body-step-up-refusal.security.md b/changelog.d/1197-route-body-step-up-refusal.security.md index b74475ca6d..bd45350535 100644 --- a/changelog.d/1197-route-body-step-up-refusal.security.md +++ b/changelog.d/1197-route-body-step-up-refusal.security.md @@ -1,8 +1,11 @@ -- **A step-up refusal made in a route body after its gate admitted the request now writes - `auth.gate_refused`.** A `proof_in_route` route's gate writes `auth.permission_granted`, and the - route then spends the bound proof (`spend_step_up_action`) or checks the session window +- **The step-up refusals of `spend_step_up_action` and `refuse_unless_step_up_window_live`, made + in a route body after its gate admitted the request, now write `auth.gate_refused`.** A + `proof_in_route` route's gate writes `auth.permission_granted`, and the route then spends the + bound proof (`spend_step_up_action`) or checks the session window (`refuse_unless_step_up_window_live`). In the shipped code a refusal there left the grant row and - no row for the refusal. It now also writes an `auth.gate_refused` row naming the same permission - and a `reason` of `step_up`, only where the gate wrote its grant row. No request is allowed that - was refused before. A refusal whose row cannot be written answers with a server error instead of - the 403, as a gate's own refusal already does. (`BACKLOG #1197`) + no row for the refusal. It still follows that grant row, and now also writes an + `auth.gate_refused` row naming the same permission and a `reason` of `step_up`, only where the + gate wrote its grant row. No request is allowed that was refused before. A refusal whose row + cannot be written answers with a server error instead of the 403, as a gate's own refusal already + does. Other refusals a route body makes after its gate passed, at least the reveal and pacing + refusals, still write no refusal row. (`BACKLOG #1197`) diff --git a/messagefoundry/auth/service.py b/messagefoundry/auth/service.py index 5203deb41a..e3d87d9ad2 100644 --- a/messagefoundry/auth/service.py +++ b/messagefoundry/auth/service.py @@ -22116,9 +22116,9 @@ async def audit_gate_refused( The caller holds ``permission``, so this is not :meth:`audit_permission_denied`: that row says the permission was missing, and the denial-burst detector counts it. - ``_record_gate_refusal`` in ``api/security.py`` decides when this row is written, for a - gate's own refusals and for the step-up refusals a ``proof_in_route`` route body makes. - ``client`` is required, as for :meth:`audit_self_target_refused`.""" + ``_recorded_decision`` in ``api/security.py`` decides when this row is written for a gate's + own refusals, and ``_record_route_refusal`` for the step-up refusals a ``proof_in_route`` + route body makes. ``client`` is required, as for :meth:`audit_self_target_refused`.""" await self._audit( "auth.gate_refused", actor=identity.username, diff --git a/tests/test_derived_gate_decision_audit.py b/tests/test_derived_gate_decision_audit.py index 0842f8e28e..7c3f91efb8 100644 --- a/tests/test_derived_gate_decision_audit.py +++ b/tests/test_derived_gate_decision_audit.py @@ -527,18 +527,23 @@ async def test_a_failed_refusal_row_write_still_refuses( refused and the route body never gets past the check, as in the gate's own decision block.""" service = await _service(engine, admin_write_rate_limit_per_actor=10) + attempts: list[str] = [] + async def broken(*_: object, **__: object) -> None: + attempts.append("audit_gate_refused") raise RuntimeError("audit store down") monkeypatch.setattr(service, "audit_gate_refused", broken) ran: list[str] = [] app = _route_body_app(engine, service, check, ran) token = await _login(app) - await engine.store.mark_session_reauthed(hash_token(token), now=0.0) # lapse the window + # Lapse the window for the window check; the spend refuses anyway, with no bound proof minted. + await engine.store.mark_session_reauthed(hash_token(token), now=0.0) transport = httpx.ASGITransport(app=app, client=(_HOME, 12345), raise_app_exceptions=False) async with httpx.AsyncClient(transport=transport, base_url="http://t") as c: r = await c.post(_PROBE, headers={"Authorization": f"Bearer {token}"}) assert r.status_code == 500, r.text + assert attempts == ["audit_gate_refused"], "the 500 must come from the refusal-row write" assert ran == [] From 62ba38dbc33c4fb328cc02fa94e29ea4b4878532 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sat, 21 Nov 2026 18:35:26 -0600 Subject: [PATCH 24/74] Test 8 drive refuses an uncaused stranding; FIFO test change dropped BACKLOG #3456 (batch 453), review round 1. - A stand-in now needs a recorded contention route (claim_lock_timeouts or claim_head_skips), so a stranding with no cause still fails, as it failed the old loop. Shown with the injected arm switched to a plain EMPTY: it fails "stranded in terminal IDLE with no contention recorded". - The canonical arm claims through the store itself again; only the injected arm builds the shim. - 20 s wall ceiling, inside the 60 s per-test watchdog; the expiry report names a lane that did not stop. - tests/test_per_lane_wake.py is back to origin/main. The file source sorts by name, so the sleep was not an ordering race, and the stored-condition wait started the PROCESSED wait's deadline later, against the half-backstop pin. --- tests/test_per_lane_wake.py | 19 +++++++++++-------- tests/test_stage_dispatcher.py | 32 +++++++++++++++++++++----------- 2 files changed, 32 insertions(+), 19 deletions(-) diff --git a/tests/test_per_lane_wake.py b/tests/test_per_lane_wake.py index 7fa3b6b01e..b07692f5f0 100644 --- a/tests/test_per_lane_wake.py +++ b/tests/test_per_lane_wake.py @@ -368,14 +368,12 @@ async def test_multi_message_fifo_order_preserved_under_per_lane_wake( try: for i in range(3): (inbox / f"m{i}.hl7").write_bytes(ADT.format(cid=f"MSG{i}").encode("utf-8")) - # Arrival order: the next file is written only once this one is stored, which a fixed - # sleep did not ensure on a runner whose poll ran late (BACKLOG #3456). - await _until(lambda n=i + 1: _n_messages(store, n)) + await asyncio.sleep(0.05) # keep arrival order deterministic # Poll the ACTUAL asserted condition — all 3 messages finalized to PROCESSED — not a proxy like # "N outbound rows DONE" (each message fans out to 2, so that proxy trips at 1.5 messages; it # false-greened on a fast runner and flaked on a slow one — mf-ci-test-flakes). try: - await _until(lambda: _n_messages(store, 3, MessageStatus.PROCESSED.value)) + await _until(lambda: _n_processed(store, 3)) except AssertionError as exc: # Print how far each message got. ROUTED covers both transform and delivery, so this # separates intake from the later stages, not transform from delivery. @@ -393,10 +391,15 @@ async def test_multi_message_fifo_order_preserved_under_per_lane_wake( assert [row["control_id"] for row in await cur.fetchall()] == ["MSG0", "MSG1", "MSG2"] -async def _n_messages(store: MessageStore, n: int, status: str | None = None) -> bool: - """At least ``n`` messages on the inbound, any status when ``status`` is None.""" - msgs = await store.list_messages(channel_id="file_in", status=status, allowed_channels=None) - return len(msgs) >= n +async def _n_processed(store: MessageStore, n: int) -> bool: + return ( + len( + await store.list_messages( + channel_id="file_in", status=MessageStatus.PROCESSED.value, allowed_channels=None + ) + ) + >= n + ) # --- env-flag plumbing (AC-12) ---------------------------------------------- diff --git a/tests/test_stage_dispatcher.py b/tests/test_stage_dispatcher.py index 0bc077a841..1ce8ccbe49 100644 --- a/tests/test_stage_dispatcher.py +++ b/tests/test_stage_dispatcher.py @@ -2336,18 +2336,20 @@ async def test_adr0070_7_reload_resumes_idempotently(store: Any) -> None: async def _drive_lanes_to_stop( - d: StageDispatcher, mc: ManualClock, lanes: list[str], *, timeout: float = 30.0 + d: StageDispatcher, mc: ManualClock, lanes: list[str], *, timeout: float = 20.0 ) -> None: """Fire every due park timer until each of ``lanes`` is STOPPED, bounded by real time. The loop this replaced ran 30 rounds and never re-readied a lane, and it failed on the SQL - Server 2025 leg (BACKLOG #3456, four hits). Each captured log shows the same pattern: all four - lanes fault once, and only ``IB_OUTAGE_3`` faults again. A lane parked after its first fault + Server 2025 leg (BACKLOG #3456). The three captured logs read for this show one pattern: all + four lanes fault once, and only ``IB_OUTAGE_3`` faults again. A lane parked after its first fault whose re-claim comes back EMPTY takes T12: ``phase=IDLE`` with no timer. The sweep that would re-ready it is disabled here, so no clock advance re-claims it. That fits what `_wait_lane` stands in for (a swallowed 1222). The logs do not show it as the cause: the dispatcher's lock-timeout line is INFO and was not captured. So a stranded lane is re-readied under the same capped, warned allowance, and the loop's bound is a wall-clock ceiling, not a round count. + A stand-in needs a recorded contention route (a lock-timeout abort or a head skip), so an + EMPTY claim with no cause still fails here, as it failed the old loop. """ def all_stopped() -> bool: @@ -2362,15 +2364,21 @@ def all_stopped() -> bool: # IDLE is never a waypoint on this path (PARKED -> READY -> CLAIMING -> PROCESSING -> # PARKED or STOPPED), so an IDLE lane with no timer is a stranding. if _terminal_idle(d, ln): + if d.claim_lock_timeouts + d.claim_head_skips == 0: + raise _WaitTimeout( + f"{ln} stranded in terminal IDLE with no contention recorded\n" + + await _expiry_report(lane=ln) + ) await _stand_in_for_sweep(d, ln) mc.advance(120.0) # past every lane's capped backoff, so every armed park timer fires await _settle(rounds=4) if all_stopped(): return phases = {ln: d.phase(ln) for ln in lanes} + first = next(ln for ln in lanes if d.phase(ln) is not _LanePhase.STOPPED) raise _WaitTimeout( f"not every lane STOPPED within {timeout:g}s: {phases!r}\n" - + await _expiry_report(all_stopped) + + await _expiry_report(all_stopped, lane=first) ) @@ -2384,21 +2392,23 @@ async def _correlated_outage_rearms_all(store: Any, *, abort_second_claim: bool) lanes = [f"IB_OUTAGE_{i}" for i in range(4)] for lane in lanes: await _seed(store, lane, [100.0]) - shim = _ClaimShim( - store, lanes[0], mode="lock_timeout_once", extra_lanes=frozenset(lanes[1:]), times=0 - ) # armed by hand below - d = _make(shim, stub, set(), clock=mc, alert_sink=alert, infra_fault_stop_after=2) + shim: _ClaimShim | None = None + if abort_second_claim: + shim = _ClaimShim( + store, lanes[0], mode="lock_timeout_once", extra_lanes=frozenset(lanes[1:]), times=0 + ) # armed by hand below + d = _make(shim or store, stub, set(), clock=mc, alert_sink=alert, infra_fault_stop_after=2) await d.start() try: for lane in lanes: d.mark_ready(lane) - if abort_second_claim: + if shim is not None: for lane in lanes: await _wait_lane(d, lane, _LanePhase.PARKED) # each lane's first fault shim._remaining = 1 - # Drive every lane to STOP (stop_after=2 → two faults each). + # Drive every lane to STOP (stop_after=2 gives two faults each). await _drive_lanes_to_stop(d, mc, lanes) - if abort_second_claim: + if shim is not None: assert shim._remaining == 0, "the armed abort never reached a claim" assert d.claim_lock_timeouts >= 1 assert any(_sweep_standins(ln) for ln in lanes), ( From 11e2caa90e0f7482df6a9f619af79e1a23bcfcc0 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sat, 21 Nov 2026 18:36:27 -0600 Subject: [PATCH 25/74] Repair round 1: keep the caveats and decision times, quote removed words ADR 0019 point 4 keeps the weaker-than caveat and drops "In its place"; the first 2026-10-10 note keeps the uncounted-encrypts clause and the symbol, and the second note is back to its origin/main text. ADR 0173 keeps the decision logging times and the third limit's pointer, names the records' Central dates once beside the UTC run times, and its correction note quotes the old words. The test flattens whitespace and case and checks each refused phrase against the removed wording. Proposed PR title: ADR 0019 and ADR 0173 state each fact once Banner #1173: PARTIAL -- item 3 fixed (point 4 points to ADR 0138); item 2 true as written, still open Banner #3009: PARTIAL -- PR 2899 notes 3 and 4 fixed for the run dates and the versions --- ...019-pluggable-keyprovider-hsm-kms-vault.md | 37 +++--- ...ss-terminating-and-originating-surfaces.md | 32 +++--- tests/test_adr_0019_0173_stated_once.py | 106 +++++++++++++----- 3 files changed, 117 insertions(+), 58 deletions(-) diff --git a/docs/adr/0019-pluggable-keyprovider-hsm-kms-vault.md b/docs/adr/0019-pluggable-keyprovider-hsm-kms-vault.md index eb56428546..271d0029e6 100644 --- a/docs/adr/0019-pluggable-keyprovider-hsm-kms-vault.md +++ b/docs/adr/0019-pluggable-keyprovider-hsm-kms-vault.md @@ -660,13 +660,15 @@ lifetime is Vault's to version. The bound is a no-op there and for the identity > [ADR 0138](0138-transit-bulk-crypto-provider-dek-out-of-engine-heap-for-asvs-13-3-3-demand-gated.md)'s > 2026-09-28 amendment states the deployment precondition and cites the pages read. -> **Corrected 2026-10-10 (BACKLOG #1173).** The rotation precondition above still stands. What -> changed is the record: since BACKLOG #2337 an operator attests to the precondition, and the engine -> reads that attestation at start, so "documented" now undersells it. The R3 ruling above judged the -> precondition before that record existed. ADR 0138's 2026-10-07 amendment says what was built, what -> the check does under each enforcement level, what it does not change, and who judges the record -> against R3. *(Corrected 2026-11-21, vault BACKLOG #1173: this note also restated that amendment's -> account of the CLI command, the start call, the uncounted encrypts and the scorecard question.)* +> **Corrected 2026-10-10 (BACKLOG #1173).** The rotation precondition above still stands, and the +> engine still counts no Transit encrypts. What changed is the record. Since BACKLOG #2337, +> `Engine.start` checks for an operator's recorded attestation to the precondition through +> `enforce_transit_bound_attestation`, so "documented" now undersells it. The R3 ruling above +> judged the precondition before that record existed. ADR 0138's 2026-10-07 amendment says how the +> attestation is recorded, what the check does under each enforcement level, what it does not +> change, and how the record stands against R3. *(Corrected 2026-11-21, vault BACKLOG #1173: this +> note also named the CLI command that records the attestation, and said that whether the record +> meets R3 is a scorecard call. The 2026-10-07 amendment states both.)* **Status: 11.3.4 — the bound is persisted, aggregated, alarmed and enforced.** As before, this ADR records the build and does not itself re-score; ADR 0115 / the ASVS-L3 re-score governs the sweep. @@ -800,14 +802,14 @@ above. 4. **Volume wears out a key, not the generator.** The one value whose safety falls with volume is the 96-bit random AES-GCM nonce, and that is a limit on the key, not on the generator. The default path counts it: the 2026-07-22 amendment above, and `store/gcm_bound.py`. The `vault_transit` path - counts nothing. In its place, `Engine.start` calls `enforce_transit_bound_attestation` in - `store/transit_attestation.py` (BACKLOG #2337). - [ADR 0138](0138-transit-bulk-crypto-provider-dek-out-of-engine-heap-for-asvs-13-3-3-demand-gated.md)'s - 2026-10-07 amendment records how that gate works, what it does not catch and what it does not - change. Its 2026-09-28 amendment states the rotation precondition the operator attests to. - *(Corrected 2026-11-21, vault BACKLOG #1173: this point also restated what the gate checks, what - it does under each enforcement level, and that an attestation is weaker than the counted bound. - That amendment states each of them.)* + counts nothing. `Engine.start` calls `enforce_transit_bound_attestation` in + `store/transit_attestation.py` (BACKLOG #2337), and an attestation is still weaker than the + counted bound. [ADR 0138](0138-transit-bulk-crypto-provider-dek-out-of-engine-heap-for-asvs-13-3-3-demand-gated.md)'s + 2026-10-07 amendment records what that gate checks, what it does under each enforcement level, + and what it does not catch. Its 2026-09-28 amendment states the rotation precondition the + operator attests to. *(Corrected 2026-11-21, vault BACKLOG #1173: this point read "In its + place, `Engine.start` calls" and went on to say what the gate checks and what it does under + `enforce` and `warn`, which the 2026-10-07 amendment states.)* **What this statement does not cover.** How fast the operating system's generator runs is a property of Windows and Linux. The 2026-10-10 amendment below says what the platform pages state about @@ -816,9 +818,8 @@ blocking and failure, and where they say nothing. > **Corrected 2026-10-10 (BACKLOG #1173).** Point 2 and the paragraph above each said a page had > not been read for this amendment. They now point to the 2026-10-10 amendment, which reads them. > Point 4 described the Transit bound as a precondition the operator documents. It now names the -> shipped attestation check. *(Corrected 2026-11-21, vault BACKLOG #1173: this note also restated -> that the check counts no invocations and is weaker than the counted bound, which ADR 0138's -> 2026-10-07 amendment states.)* +> shipped attestation check. That check counts no invocations, and the +> bound stays weaker than the counted one. **What stops a weak generator coming back, and where it stops short.** Bandit B311 now runs in both the CI scan and the pre-commit hook, with each seeded non-security `random` use marked per line. B311 is a diff --git a/docs/adr/0173-tls-peer-revocation-checking-and-ocsp-stapling-across-terminating-and-originating-surfaces.md b/docs/adr/0173-tls-peer-revocation-checking-and-ocsp-stapling-across-terminating-and-originating-surfaces.md index e4fabfe2d3..0b8eb295b4 100644 --- a/docs/adr/0173-tls-peer-revocation-checking-and-ocsp-stapling-across-terminating-and-originating-surfaces.md +++ b/docs/adr/0173-tls-peer-revocation-checking-and-ocsp-stapling-across-terminating-and-originating-surfaces.md @@ -1262,8 +1262,8 @@ ruling: bullet of the 2026-10-04 reading below says. No owner answer and no planned test covers one. - **Only two runs have results, and the run on the SQL Server test box is still owed.** The test needs a SQL Server whose certificate can be revoked. A control connection to a - certificate that is not revoked shows that a refusal comes from the revocation. The amendment of - 2026-11-11 below states what the runs measured and their limits. *(Corrected 2026-11-17, vault + certificate that is not revoked shows that a refusal comes from the revocation. The amendment of 2026-11-11 below states what + the runs measured, their limits, and which run is still owed. *(Corrected 2026-11-17, vault BACKLOG #3009: this bullet's heading read "Driver 18 was tested on one build on Windows Server 2022, and other drivers were not tested", which restated the amendment's limits.)* *(Until 2026-11-11 this bullet read: "**The drivers' own revocation behaviour is still @@ -1283,7 +1283,8 @@ ruling: amendment does not change the grade. A Manager decided under the owner's delegation of 2026-11-11 that the five rows keep the grade R6 gives them, that R6's named gap stands as named, and that #2194's guard and driver-control options are not reopened now: decision - d20261112T022118464-c27c39.)* + d20261112T022118464-c27c39, logged at 02:21 UTC on 2026-11-12, the evening of 2026-11-11 in + Central time.)* *(Until 2026-10-11 this paragraph read: "**What is open on the five ODBC hops.** BACKLOG #2194 names three outcomes for a hop: a guard, a documented driver control, or an accepted gap. This note @@ -1322,9 +1323,11 @@ ODBC revocation runbook that reached a result. Their contents beyond this summar here. It changes no code. For the grade, see the limit headed *What a result would mean for the grade*, under the ruling above, and its note of 2026-11-11. -- **Where it ran.** Two runs with results. The first run's legs ran from 02:22 to 02:25 UTC on - 2026-10-17, and the second's from 05:18 to 05:19 UTC the same day. The first run's record says it ran on a disposable virtual machine built for the - test, not on the SQL Server test box, and that the runbook puts the next run there. The second +- **Where it ran.** Two runs with results. The first run's legs ran from 02:22 to 02:25 UTC and + the second's from 05:18 to 05:19 UTC, both on 2026-10-17. The records are dated in Central + time, where the first run fell on the evening of 2026-10-16. The first run's record says it ran + on a disposable virtual machine built for the test, not on the SQL Server test box, and that the + runbook puts the next run there. The second run's record says it ran inside a virtual machine, after a revert to checkpoint `post-3009-clean-2026-10-16`, a tightening of folder permissions and a new checkpoint, `post-3009-acl-2026-10-17`. It writes the machine's name as a placeholder, so it cannot show @@ -1334,7 +1337,8 @@ grade*, under the ruling above, and its note of 2026-11-11. took place on the SQL Server test box", which leaned on a name the second record had replaced with a placeholder.)* The run there is still owed, and BACKLOG #3009's step 2 stays open for it: a Manager decided so under the owner's delegation of 2026-11-11, decision - d20261112T022119877-2ccc8b. + d20261112T022119877-2ccc8b, logged at 02:21 UTC on 2026-11-12, the evening of 2026-11-11 in + Central time. - **Versions.** ODBC Driver 18 for SQL Server, 64-bit: `msodbcsql18.dll` ProductVersion 18.7, build 1, revision 1, reporting driver version `18.07.0001`. Windows Server 2022 Datacenter, build 20348, update revision 5256. SQL Server 2022 RTM, 16.0.1000.6. Both records list @@ -1370,8 +1374,9 @@ grade*, under the ruling above, and its note of 2026-11-11. the pin legs mean for the pin is the amendment of 2026-10-17 below. For the strict legs that reading is the second record's own, because the runbook's table has no row for them. - **The limits.** At least these. - - Only the versions above. Linux, macOS, other Driver 18 builds, and other drivers, which the - generic dialect and the `odbc_driver` setting can name, were not measured. + - Only the driver, Windows and SQL Server versions above. Linux, macOS, other Driver 18 builds, + and other drivers, which the generic dialect and the `odbc_driver` setting can name, were not + measured. - Only a CRL over HTTP. No OCSP responder was offered, so this does not show that the driver never checks revocation. - Only a same-machine connection: the client ran on the machine SQL Server ran on, so no @@ -1381,11 +1386,10 @@ grade*, under the ruling above, and its note of 2026-11-11. pool, so the result says nothing about how the engine builds or sends its own strings. - Only a throwaway root, with no intermediate CA. -*(Corrected 2026-11-21, vault BACKLOG #3009: this amendment gave the runs' dates in Central time -beside their UTC times, and its first limit repeated the versions. The note under the fourth limit -above and this amendment's first bullet each gave a decision's logging time in UTC and in Central -time, and the third limit above repeated which run is still owed. The UTC run times are kept; the -rest is removed.)* +*(Corrected 2026-11-21, vault BACKLOG #3009: the first bullet opened "Two runs with results, +dated 2026-10-16 and 2026-10-17 in Central time. In UTC, the first run's legs ran", and the first +limit opened "Only that driver build, only Windows Server 2022, and only SQL Server 2022 RTM.", +which repeated the versions bullet.)* *(End of the amendment of 2026-11-11. The next paragraph continues the 2026-10-04 note.)* diff --git a/tests/test_adr_0019_0173_stated_once.py b/tests/test_adr_0019_0173_stated_once.py index 84e1d4f3bb..d979d8e491 100644 --- a/tests/test_adr_0019_0173_stated_once.py +++ b/tests/test_adr_0019_0173_stated_once.py @@ -2,15 +2,20 @@ # Copyright (C) 2026 MessageFoundry Foundation, LLC and contributors """ADR 0019 and ADR 0173 point to the record that states a fact, rather than restating it. -ADR 0019's RNG amendment once restated ADR 0138's Transit start gate (vault BACKLOG #1173, item 3), -and ADR 0173's ODBC test amendment gave its times in two zones and restated its versions and -decision times (vault BACKLOG #3009, PR 2899 notes 3 and 4). SDS-3.5: a fact lives in one place. +ADR 0019's RNG amendment point 4 once restated ADR 0138's Transit start gate (vault BACKLOG #1173, +item 3). ADR 0173's ODBC test amendment gave its run dates in two zones and repeated its versions +in its limits (vault BACKLOG #3009, PR 2899 notes 3 and 4). SDS-3.5: a fact lives in one place. + +Each refused phrase is checked against the text it was removed from, so a phrase that drifts +from that wording fails here instead of passing for ever. """ from __future__ import annotations from pathlib import Path +import pytest + _ADR = Path(__file__).resolve().parent.parent / "docs" / "adr" _ADR_0019 = _ADR / "0019-pluggable-keyprovider-hsm-kms-vault.md" _ADR_0173 = ( @@ -18,40 +23,89 @@ / "0173-tls-peer-revocation-checking-and-ocsp-stapling-across-terminating-and-originating-surfaces.md" ) +# The removed wording, as it read on origin/main before the fix: the negative controls. +_OLD_0019_POINT_4 = ( + "In its place, `Engine.start` calls `enforce_transit_bound_attestation` in " + "`store/transit_attestation.py`, which checks for a recorded operator attestation naming the " + "configured Transit data key (BACKLOG #2337). Without one, the engine refuses to start under " + "`[security].enforcement = enforce` and only logs a warning under `warn`." +) +_OLD_0173_FINDINGS = ( + "Two runs with results, dated 2026-10-16 and 2026-10-17 in Central time. In UTC, the first " + "run's legs ran from 02:22 to 02:25" +) +_OLD_0173_LIMIT = "Only that driver build, only Windows Server 2022, and only SQL Server 2022 RTM." + +_REFUSED_0019 = ("in its place,", "refuses to start", "logs a warning", "naming the configured") +_REFUSED_0173_FINDINGS = ("in utc, the first run", "2026-10-17 in central time") +_REFUSED_0173_LIMIT = ("only windows server 2022", "only sql server 2022 rtm") + + +def _flat(text: str) -> str: + """Join wrapped lines and fold case, so a phrase that wraps or opens a sentence still matches.""" + return " ".join(text.split()).lower() + def _between(text: str, start: str, end: str) -> str: head = text.index(start) return text[head : text.index(end, head)] +def _body(text: str) -> str: + """Drop correction notes, which quote the removed words on purpose.""" + return text.split("*(Corrected 2026-11-21", 1)[0] + + +@pytest.mark.parametrize( + ("old", "refused"), + [ + (_OLD_0019_POINT_4, _REFUSED_0019), + (_OLD_0173_FINDINGS, _REFUSED_0173_FINDINGS), + (_OLD_0173_LIMIT, _REFUSED_0173_LIMIT), + ], +) +def test_each_refused_phrase_matches_the_removed_wording( + old: str, refused: tuple[str, ...] +) -> None: + for phrase in refused: + assert phrase in _flat(old), phrase + + def test_adr_0019_point_4_does_not_restate_the_transit_gate() -> None: text = _ADR_0019.read_text(encoding="utf-8") - point_4 = _between( - text, - "4. **Volume wears out a key, not the generator.**", - "**What this statement does not cover.**", + point_4 = _flat( + _body( + _between( + text, + "4. **Volume wears out a key, not the generator.**", + "**What this statement does not cover.**", + ) + ) ) - # Stop before any correction note, which names what was removed. - point_4 = point_4.split("*(Corrected", 1)[0] - for restated in ("refuses to start", "logs a warning", "weaker than the counted bound"): - assert restated not in point_4, restated - assert "enforce_transit_bound_attestation" in point_4 # positive control: the pointer stays + for phrase in _REFUSED_0019: + assert phrase not in point_4, phrase + # Positive controls: the pointer, the link and the caveat stay. + assert "enforce_transit_bound_attestation" in point_4 assert "0138-transit-bulk-crypto-provider" in point_4 + assert "weaker than the counted bound" in point_4 -def test_adr_0173_odbc_amendment_states_times_in_one_zone() -> None: +def test_adr_0173_odbc_amendment_states_dates_and_versions_once() -> None: text = _ADR_0173.read_text(encoding="utf-8") - amendment = _between( - text, - "**Amendment 2026-11-11 -- what the ODBC Driver 18 test measured", - "*(End of the amendment of 2026-11-11.", + amendment = _body( + _between( + text, + "**Amendment 2026-11-11 -- what the ODBC Driver 18 test measured", + "*(End of the amendment of 2026-11-11.", + ) ) - # The amendment's own body, before the limits and the correction note that names what went. - findings = amendment[: amendment.index("- **The limits.**")] - assert "Central time" not in findings - assert "logged at" not in amendment - assert amendment.count("Windows Server 2022") == 1 - assert "02:22 to 02:25 UTC" in findings # positive control: the UTC times stay - grade_note = _between(text, "*(Note 2026-11-11: two recorded results exist", ")*") - assert "logged at" not in grade_note - assert "d20261112T022118464-c27c39" in grade_note # positive control: the decision stays + head, _, limits = amendment.partition("- **The limits.**") + findings, limits = _flat(head), _flat(limits) + for phrase in _REFUSED_0173_FINDINGS: + assert phrase not in findings, phrase + for phrase in _REFUSED_0173_LIMIT: + assert phrase not in limits, phrase + # Positive controls: the UTC times and the versions are each still stated. + assert "02:22 to 02:25 utc" in findings + assert "windows server 2022 datacenter" in findings + assert limits # the limits list was found From 8053acb15f624cf6e4f928745ae0cc77ea2f1fda Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sat, 21 Nov 2026 18:36:35 -0600 Subject: [PATCH 26/74] review round 1 repairs: memo stays a per-run snapshot; truer re-proof and census docs Keying the run memo on the working directory and the environment let a leg re-resolve after a config module changed either, and grade settings the run's source tag does not name. The key goes back to the arguments alone, and _RUN_MEMO now says why. The auth.ts comment no longer claims the re-proof store can never overwrite a newer token, the tracking docs name re-proofs, and the inline-timeout census test is named for what it scans. Vault BACKLOG #2950. --- ide/src/auth.ts | 5 ++-- ide/src/signInSession.ts | 9 ++++--- ide/src/stepUp.ts | 4 ++- messagefoundry/checks.py | 30 +++++++--------------- tests/test_apiclient_sign_in_timeout.py | 5 ++-- tests/test_checks_settings_memo.py | 34 ------------------------- 6 files changed, 23 insertions(+), 64 deletions(-) diff --git a/ide/src/auth.ts b/ide/src/auth.ts index bd530ad299..2c482a3ce0 100644 --- a/ide/src/auth.ts +++ b/ide/src/auth.ts @@ -371,8 +371,9 @@ export async function withStepUpAuth( // It rotates the token and queues behind the account's re-proof lock, as the sign-in does, // so it gets the sign-in's timeout (vault BACKLOG #2950), named here rather than left to // postJson's default so the two cannot drift apart. - // Tracked in signInSession.ts as a sign-in is, and it stores the rotated token there, so - // peekToken and a later sign-in wait for it and its store cannot overwrite a newer sign-in's. + // Tracked in signInSession.ts as a sign-in is, and it stores the rotated token there, so in + // this window peekToken and a later sign-in wait for it; reproveTracked says when its store + // can still overwrite a newer sign-in's token. // A timeout after the engine finished leaves the cached token dead, as a lost sign-in reply // does: the next call gets a 401 and signs in again. return await reproveTracked(ctx.secrets, secretKey(url), async () => { diff --git a/ide/src/signInSession.ts b/ide/src/signInSession.ts index 84fa7c15e7..478cb1a8b4 100644 --- a/ide/src/signInSession.ts +++ b/ide/src/signInSession.ts @@ -63,7 +63,8 @@ export const SIGN_IN_TIMEOUT_MS = 150_000; * attempt. Point 3 above names what it does not cover. */ export const SIGN_IN_WAIT_MS = SIGN_IN_TIMEOUT_MS + 5_000; -/** Sign-ins between "request about to leave" and "new token stored", by cache key. Never rejects. */ +/** Sign-ins and re-proofs between "request about to leave" and "new token stored", by cache key. + * Never rejects. */ const inFlight = new Map>(); /** `pending`, or `ms` elapsing, whichever comes first. Never rejects. */ @@ -154,9 +155,9 @@ function tracked(key: string, waitMs: number, run: () => Promise): Promise } /** - * Resolves once no sign-in tracked for `key` is still between its request and its store, or after - * `waitMs`, whichever is first. Never rejects: a failed sign-in settles it too. Resolves at once when - * none is in flight. + * Resolves once no sign-in or re-proof tracked for `key` is still between its request and its store, + * or after `waitMs`, whichever is first. Never rejects: a failed attempt settles it too. Resolves at + * once when none is in flight. */ export function signInSettled(key: string, waitMs: number = SIGN_IN_WAIT_MS): Promise { return bounded(inFlight.get(key), waitMs); diff --git a/ide/src/stepUp.ts b/ide/src/stepUp.ts index f8e63787bb..ba075c6ba9 100644 --- a/ide/src/stepUp.ts +++ b/ide/src/stepUp.ts @@ -20,7 +20,9 @@ export interface StepUpHost { promptPassword(signal: StepUpSignal, retry: boolean): Promise; /** POST /me/reauth with `token`; resolve to the re-keyed token the engine returns, if any. */ reauth(token: string, password: string, purpose: string | undefined): Promise; - /** Keep the re-keyed token, so later calls and the sign-in cache use the live session. */ + /** Keep the re-keyed token, so later calls use the live session. The IDE's host stores it in the + * sign-in cache inside `reauth` instead (auth.ts, signInSession.ts `reproveTracked`), where the + * store is tracked, so a store added here would run untracked. */ storeToken(token: string): Promise; } diff --git a/messagefoundry/checks.py b/messagefoundry/checks.py index ee0f5d9323..d77387ad23 100644 --- a/messagefoundry/checks.py +++ b/messagefoundry/checks.py @@ -125,26 +125,16 @@ #: The settings resolutions and loads of one :func:`run_checks` call, so each runs once per run #: rather than once per settings leg (vault BACKLOG #2950 added items 6 and 13). ``None`` outside a #: run: a leg called on its own resolves and loads afresh, as it always did. +#: +#: The key is the arguments alone, not the working directory or the environment, on purpose: the +#: memo is a snapshot of the run. :func:`run_checks` resolves the source once, before the config +#: modules are imported, and tags each leg's line with it, so a leg that resolved again after a +#: module changed either would grade settings that tag does not name. _RUN_MEMO: ContextVar[dict[tuple[object, ...], object] | None] = ContextVar( "_RUN_MEMO", default=None ) -def _ambient() -> tuple[str | None, tuple[tuple[str, str], ...]]: - """The working directory and the environment, as a :data:`_RUN_MEMO` key part. Both feed the - answer as well as the arguments do: the search reads ``./messagefoundry.toml``, a relative - path resolves against the working directory, and the load reads ``MEFOR_*``. Keying on them - means a change during a run, by the caller or another thread, reads afresh rather than reusing - an answer to a different question; the whole environment, because the loader may read more than - ``MEFOR_*``. An unreadable working directory is ``None``: the uncached call then meets the same - fault itself.""" - try: - cwd: str | None = os.getcwd() - except OSError: - cwd = None - return cwd, tuple(sorted(os.environ.items())) - - def _config_modules( name: str, config_dir: str | Path, *, required: bool = False ) -> list[Path] | CheckResult: @@ -2233,15 +2223,14 @@ def _settings_source( ``(None, False)`` is the SKIP the legs have always given a bare dir. - Inside :func:`run_checks` it resolves once per distinct argument set, working directory and - environment (:data:`_RUN_MEMO`).""" + Inside :func:`run_checks` it resolves once per distinct argument set (:data:`_RUN_MEMO`).""" memo = _RUN_MEMO.get() if memo is None: return _settings_source_uncached( config_dir, service_config=service_config, suppress_search=suppress_search, env=env ) explicit = None if service_config is None else str(service_config) - key = ("source", str(config_dir), explicit, suppress_search, env, _ambient()) + key = ("source", str(config_dir), explicit, suppress_search, env) if key not in memo: memo[key] = _settings_source_uncached( config_dir, service_config=service_config, suppress_search=suppress_search, env=env @@ -2286,14 +2275,13 @@ def _load_check_settings( ``env`` is ``check --env``, applied as ``serve`` applies its own ``--env``: a CLI override of ``[ai].environment``, above the file and ``MEFOR_AI_ENVIRONMENT`` (vault BACKLOG #2355). - Inside :func:`run_checks` the load runs once per distinct argument set, working directory and - environment, a refusal of + Inside :func:`run_checks` the load runs once per distinct argument set, a refusal of :data:`_SETTINGS_LOAD_ERRORS` included, and every later leg gets that answer (:data:`_RUN_MEMO`): its own deep copy, so no leg sees another's change to the model.""" memo = _RUN_MEMO.get() if memo is None: return _load_check_settings_uncached(toml, cli=cli, env=env) - key = ("load", None if toml is None else str(toml), repr(cli), env, _ambient()) + key = ("load", None if toml is None else str(toml), repr(cli), env) if key not in memo: try: memo[key] = _load_check_settings_uncached(toml, cli=cli, env=env) diff --git a/tests/test_apiclient_sign_in_timeout.py b/tests/test_apiclient_sign_in_timeout.py index 81d639de0b..d428ec6852 100644 --- a/tests/test_apiclient_sign_in_timeout.py +++ b/tests/test_apiclient_sign_in_timeout.py @@ -227,10 +227,11 @@ def test_the_census_of_queued_calls_matches_the_client() -> None: assert _methods_calling("_adopt_rotated") == {"reauth", "verify_mfa", "confirm_mfa"} -def test_no_method_raises_its_read_timeout_inline() -> None: +def test_no_method_builds_its_own_read_keyword_timeout() -> None: """RED when: an ``EngineClient`` method builds its own ``httpx.Timeout(..., read=...)`` rather than calling ``_sign_in_timeout``, so a longer reply wait escapes the census above. Control: - the scan finds the one method that does build one, ``_sign_in_timeout`` itself.""" + the scan finds the one method that does build one, ``_sign_in_timeout`` itself. A positional + ``httpx.Timeout(n)`` or a scalar ``timeout=`` is not scanned.""" assert _methods_setting_a_read_timeout() == {"_sign_in_timeout"} diff --git a/tests/test_checks_settings_memo.py b/tests/test_checks_settings_memo.py index 1cf7dc2612..a7c6406c05 100644 --- a/tests/test_checks_settings_memo.py +++ b/tests/test_checks_settings_memo.py @@ -118,37 +118,3 @@ def test_a_leg_called_outside_a_run_reads_afresh( checks._load_check_settings(toml) assert calls["source"] == 2 assert calls["load"] == 2 - - -def test_a_change_to_the_environment_or_working_directory_during_a_run_reads_afresh( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - """RED when: the memo key leaves out the environment or the working directory, so a change to - either during a run gets the answer to the question asked before it. Control: the same call - with neither changed is answered from the memo.""" - calls = _count_reads(monkeypatch) - token = checks._RUN_MEMO.set({}) - try: - - def source() -> tuple[Path | None, bool]: - return checks._settings_source( - SAMPLES_CONFIG, service_config=None, suppress_search=False, env=None - ) - - assert source() == (None, False) - assert source() == (None, False) - assert calls["source"] == 1 - # The environment now declares an instance, which the bare dir's SKIP must not hide. - monkeypatch.setenv("MEFOR_AI_ENVIRONMENT", "dev") - assert source() == (None, True) - assert calls["source"] == 2 - # A messagefoundry.toml in the new working directory is what the search now finds. - other = tmp_path / "other" - other.mkdir() - (other / "messagefoundry.toml").write_text("", encoding="utf-8") - monkeypatch.chdir(other) - found, _ = source() - assert found is not None and found.resolve() == (other / "messagefoundry.toml").resolve() - assert calls["source"] == 3 - finally: - checks._RUN_MEMO.reset(token) From 7fc65d7508fa7b8e93a27ffd6d99015f77ca2cf4 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sat, 21 Nov 2026 18:38:24 -0600 Subject: [PATCH 27/74] NO_LOGIN receipt: count directory rows from the registry, read MISSING without a bad file Vault BACKLOG #2985 (batch 287), review round-b390b3989b repairs. - The directory-only note said "will not self-resolve", which was not established: this session's own record may simply be absent. With no unparsed file the receipt now reads MISSING and names the directory rows after it; the mixed note counts files and directories apart. - Get-SessionRecords rows carry a Directory field, so the hook reads the kind from the listing rather than a second stat. - The end-state test gains a control: the same nested layout, listing allowed, removes clean. - The bracketed-profile test asserts the transcript was found before it compares the age. Proposed PR title: Coord scripts: box-activity profile read, NO_LOGIN directory rows, remove.ps1 end-state test (BACKLOG #2985) Proposed banner #2985: PARTIAL -- added items 1 (end-state test), 2 (last listing) and 3 built; added item 4 met in code by engine PR 3027; closing step 1 waits on #1017 for items 1, 7 and 12, and item 6 beyond the caller's own config root remains. --- scripts/coord/session-registry.ps1 | 9 +++++---- scripts/hooks/announce-session.ps1 | 22 +++++++++++----------- tests/test_announce_hook.py | 13 +++++++------ tests/test_coord_box_activity.py | 4 +++- tests/test_worktree_remove_in_use.py | 7 +++++++ 5 files changed, 33 insertions(+), 22 deletions(-) diff --git a/scripts/coord/session-registry.ps1 b/scripts/coord/session-registry.ps1 index 3f7f9d7450..836d74cc4a 100644 --- a/scripts/coord/session-registry.ps1 +++ b/scripts/coord/session-registry.ps1 @@ -190,7 +190,7 @@ function Get-RecordStartedUtc($Record) { # Every registry record, with the root it came from attached. # # -IncludeUnreadable also returns a row for every file that could NOT be parsed (Record = $null, -# Unreadable = $true). A caller about to destroy something needs those: a record that is half-written +# Unreadable = $true; Directory = $true when the row is a directory named *.json). A caller about to destroy something needs those: a record that is half-written # -- i.e. a session that launched a moment ago -- fails to parse, and DROPPING it silently turns an # occupied worktree from SKIP into PRUNE while the receipt reports one fewer record than existed. # It is off by default so the read-only roster callers keep the shape they already handle. @@ -206,18 +206,19 @@ function Get-SessionRecords { # SessionStart hook, where a throw replaces the chat's whole starting context. $rec = $null $err = '' - if ($f -is [System.IO.DirectoryInfo]) { $err = 'a directory, not a file, so it cannot be read as a record' } + $isDir = $f -is [System.IO.DirectoryInfo] + if ($isDir) { $err = 'a directory, not a file, so it cannot be read as a record' } else { try { $rec = Get-Content -LiteralPath $f.FullName -Raw -EA Stop | ConvertFrom-Json -EA Stop } catch { $err = $_.Exception.Message } } if (-not $rec) { if (-not $err) { $err = 'the file parsed to nothing (empty, or being written right now)' } if ($IncludeUnreadable) { - $out += [pscustomobject]@{ Record = $null; Root = $root; File = $f.FullName; Unreadable = $true; Error = $err } + $out += [pscustomobject]@{ Record = $null; Root = $root; File = $f.FullName; Unreadable = $true; Error = $err; Directory = $isDir } } continue } - $out += [pscustomobject]@{ Record = $rec; Root = $root; File = $f.FullName; Unreadable = $false; Error = '' } + $out += [pscustomobject]@{ Record = $rec; Root = $root; File = $f.FullName; Unreadable = $false; Error = ''; Directory = $false } } } return $out diff --git a/scripts/hooks/announce-session.ps1 b/scripts/hooks/announce-session.ps1 index 669ba05c57..fc18ecabd9 100644 --- a/scripts/hooks/announce-session.ps1 +++ b/scripts/hooks/announce-session.ps1 @@ -803,15 +803,15 @@ try { # lookup started returning its match count -- sent an operator hunting for a missing file # that was in fact present TWICE, which is the one place the cause was visible. $matched = if ($lookup) { [int]$lookup.Matched } else { 0 } - # A DIRECTORY ROW IS NOT A WRITE IN PROGRESS. The registry lists a directory named *.json - # as an unreadable row, and it stays one on every prompt, so it is counted apart from the - # files and the note does not call it "maybe still being written". - $unreadable = 0 + # A DIRECTORY ROW IS NOT A RECORD BEING WRITTEN. The registry lists a directory named + # *.json as an unreadable row, so the files and the directories are counted apart, and + # only an unparsed FILE is called "maybe mid-write". With no unparsed file this is the + # MISSING case, and the directory rows are named after it. + $badFiles = 0 $dirRows = 0 if ($matched -le 1) { foreach ($u in @(Get-SessionRecords -IncludeUnreadable | Where-Object { $_.Unreadable })) { - $unreadable++ - if (Test-Path -LiteralPath $u.File -PathType Container) { $dirRows++ } + if ($u.Directory) { $dirRows++ } else { $badFiles++ } } } # LEAD WITH THE DISCRIMINATOR. Write-Receipt folds this through Get-Clean with an 80-char @@ -821,12 +821,12 @@ try { # a duplicated one, which is the failure this note exists to prevent. $why = if ($matched -gt 1) { "AMBIGUOUS: $matched config roots hold a record for this id; will not self-resolve" - } elseif ($dirRows -gt 0 -and $dirRows -eq $unreadable) { - "UNREADABLE: $dirRows registry row(s) are directories; will not self-resolve" + } elseif ($badFiles -gt 0 -and $dirRows -gt 0) { + "UNREADABLE: $badFiles record(s) unparsed, maybe mid-write; $dirRows directory row(s)" + } elseif ($badFiles -gt 0) { + "UNREADABLE: $badFiles registry record(s) unparsed, maybe still being written" } elseif ($dirRows -gt 0) { - "UNREADABLE: $unreadable registry row(s) unparsed, $dirRows directories; files maybe mid-write" - } elseif ($unreadable -gt 0) { - "UNREADABLE: $unreadable registry record(s) unparsed, maybe still being written" + "MISSING: no record matched this id; $dirRows registry row(s) are directories" } else { "MISSING: no registry record matched this session id" } diff --git a/tests/test_announce_hook.py b/tests/test_announce_hook.py index 51e7019a05..2caa3d8968 100644 --- a/tests/test_announce_hook.py +++ b/tests/test_announce_hook.py @@ -1146,9 +1146,9 @@ def test_a_duplicated_session_id_is_reported_as_ambiguous_not_missing( @pytest.mark.parametrize( ("directory", "bad_file", "want"), [ - (True, False, "1 registry row(s) are directories; will not self-resolve"), - (True, True, "2 registry row(s) unparsed, 1 directories; files maybe mid-write"), - (False, True, "1 registry record(s) unparsed, maybe still being written"), + (True, False, "MISSING: no record matched this id; 1 registry row(s) are directories"), + (True, True, "UNREADABLE: 1 record(s) unparsed, maybe mid-write; 1 directory row(s)"), + (False, True, "UNREADABLE: 1 registry record(s) unparsed, maybe still being written"), ], ids=["directory-only", "directory-and-file", "file-only"], ) @@ -1157,8 +1157,9 @@ def test_a_directory_row_is_not_called_a_record_being_written( ) -> None: """Vault BACKLOG #2985, added item 3. The registry lists a directory named *.json as an unreadable row, and the NO_LOGIN receipt called it "maybe still being written". A directory is - not a write in progress and stays on every prompt. Red before the fix: the directory cases read - as a record being written. The file-only case is the control.""" + not a record being written, so it is counted apart from the files, and with no unparsed file + the receipt reads MISSING. Red before the fix: the directory cases read as a record being + written. The file-only case is the control.""" home = _registry(tmp_path / "home", "00000000-0000-0000-0000-000000000000", ".claude") sessions = home / ".claude" / "sessions" if directory: @@ -1169,7 +1170,7 @@ def test_a_directory_row_is_not_called_a_record_being_written( run(repo, tmp_path=tmp_path, state_dir=sd, rows=[PEER, ACCT], env={"USERPROFILE": str(home)}) assert outcomes(sd) == ["NO_LOGIN"], outcomes(sd) note = " ".join(receipts(sd)) - assert f"UNREADABLE: {want}" in note, note + assert want in note, note def test_repeated_stand_downs_do_not_arm_the_kill_ladder(repo: Path, tmp_path: Path) -> None: diff --git a/tests/test_coord_box_activity.py b/tests/test_coord_box_activity.py index 535af72266..b51719ab90 100644 --- a/tests/test_coord_box_activity.py +++ b/tests/test_coord_box_activity.py @@ -478,7 +478,9 @@ def test_a_transcript_under_the_profile_is_found(self, sandbox: Path, home_name: f = d / "turn.jsonl" f.write_text('{"t":1}\n', encoding="utf-8") _back_date(f, 5) - assert float(self._age(sandbox, sandbox / home_name)) == pytest.approx(5, abs=0.1) + age = self._age(sandbox, sandbox / home_name) + assert age != "null", f"no transcript found under the profile {home_name}" + assert float(age) == pytest.approx(5, abs=0.1) def test_an_unset_profile_names_no_root(self, sandbox: Path) -> None: """No profile reads as UNEVALUABLE, not as a throw, and not as the current directory.""" diff --git a/tests/test_worktree_remove_in_use.py b/tests/test_worktree_remove_in_use.py index a289b10e32..9ca6681966 100644 --- a/tests/test_worktree_remove_in_use.py +++ b/tests/test_worktree_remove_in_use.py @@ -811,3 +811,10 @@ def test_a_removal_that_cannot_be_confirmed_gone_is_not_reported_clean(rig: Rig) assert proc.returncode != 0, _explain(wt.parent, probe, proc) assert "could not be confirmed gone" in _out(proc), _explain(wt.parent, probe, proc) assert "Removed worktree" not in _out(proc), _explain(wt.parent, probe, proc) + + # Control: the same layout, with listing allowed, is a clean removal. + other = rig.add(rig.primary.parent / "box" / "Repo-listed") + proc = rig.run("-Path", str(other)) + assert proc.returncode == 0, _out(proc) + assert "Removed worktree" in _out(proc), _out(proc) + assert not other.exists() From 8112df91d796cae718b422663e29dd54cb90c534 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sat, 21 Nov 2026 18:39:14 -0600 Subject: [PATCH 28/74] reply_replaced: wording matches when the event is sent; test state reset Round 1 review fixes. The fixed reason and PHI.md no longer say the reply was sent, since the event goes out before the drain (and, on the MLLP handler-fault path, before the write). The MLLP comment, PHI.md and the changelog no longer claim the event covers every altered reply: a frame byte turned into a space writes only its warning. encode_reply's docstring and the X12Source docstring name the reporting variant the listeners call. One new test now resets the module's warn-once set. BACKLOG #5799 item 1. Proposed PR title: Listeners record each charset-replaced reply as a connection event; X12 trailer comment corrected (BACKLOG #5799, #5807, #5812) Proposed banners: - #5799: item 1 SHIPPED (reply_replaced event per replaced reply, warn-once log kept). Items 2 and 3 open, not in this brief. - #5807: OPEN, unchanged. The separator check regresses origin/main (PR 3031 measured it; the pinned trailer tests hold it); closing needs a decision to accept a held frame for a separator-less trailer, or a not-a-bug. A false test comment is corrected. - #5812: PARTIAL, unchanged by code. Items 4/17, 5, 6, 8, 11 and 12 met on origin/main (PR 3059 and earlier); 10 kept in one line; 13 is on branch w1-264-parse-log; 1-3, 7, 9, 14-16 open. --- changelog.d/5799-reply-replaced-event.added.md | 6 +++--- docs/PHI.md | 2 +- messagefoundry/transports/framing.py | 9 +++++---- messagefoundry/transports/mllp.py | 4 +++- messagefoundry/transports/x12.py | 2 +- tests/test_mllp_handler_failure.py | 6 +++++- 6 files changed, 18 insertions(+), 11 deletions(-) diff --git a/changelog.d/5799-reply-replaced-event.added.md b/changelog.d/5799-reply-replaced-event.added.md index ed2060ae9b..3a1083a831 100644 --- a/changelog.d/5799-reply-replaced-event.added.md +++ b/changelog.d/5799-reply-replaced-event.added.md @@ -1,4 +1,4 @@ -- The MLLP, raw-TCP and X12 listeners write a `reply_replaced` connection event for each reply in - which characters the inbound's charset cannot encode were replaced before it was sent. The - WARNING log line for a replacement is still written once per connection per process. +- The MLLP, raw-TCP and X12 listeners send a `reply_replaced` connection event for each reply in + which characters the inbound's charset cannot encode were replaced. The WARNING log line for a + replacement is still written once per connection per process. [PHI.md](../docs/PHI.md) section 7 says what the event carries. (`BACKLOG #5799`) diff --git a/docs/PHI.md b/docs/PHI.md index 510ef6f4ec..1ed6ba1618 100644 --- a/docs/PHI.md +++ b/docs/PHI.md @@ -2326,7 +2326,7 @@ with materially different PHI profiles, so they get their own rows; stream 4 is | **4. Off-box syslog/SIEM forwarder** — the shared **transport** for 1–3 | a copy of every record from 1–3 | `forward_format`, default **JSON** (independent of the stdout format) | the operator's collector (`forward_host`/`_port`) | off-box evidence retention / SIEM correlation | **default-on when a collector is named.** Transport: `udp` (default) / `tcp` / **`tls`** (RFC 5425, CA-anchored, verified by default). `serve` gates the hop on the shared posture gradient before the handler is installed: verified TLS ungated; otherwise loopback / attested ALLOW, non-enforcing WARN, **enforcing REFUSE (exit 2)** — there is no synthetic arm, and [ADR 0186](adr/0186-retire-the-synthetic-data-declaration-every-instance-carries-patient-data.md) left this cell with no per-hop way to accept the risk at all | the collector's, not the engine's | the identical handler filters are installed on this handler. So the forwarded copy gets the same best-effort PHI redaction and credential scrub as stdout. A single-token identifier can survive it, as it can there. The copy also carries usernames, connection names, message ids, client addresses and the audit chain. That is the engine's own stated reason for gating the hop | | **5. `audit_log` table** (SQLite, Postgres, SQL Server) | who / what / **where-from** / when of auth + PHI *access* and admin actions — plus, while `[security].audit_all_authorization_decisions` is on (**default `true`** since BACKLOG #1277, 2026-09-02, which reversed the ADR 0118 §5 `false`; the internal field it desugars to is `audit_all_authz`, whose old `[diagnostics]` TOML spelling is **refused at load** — ADR 0118), an `authz` row for **every** authorization decision including successes. That is the shipped volume of this stream, not an opt-in addition to it: one row per authenticated request on each `require()`-gated route, and this row's retention cell records that **nothing prunes the table** — `actor`, `action`, `channel_id`, `client`, `detail`, `row_hash` | JSON `detail`; **tamper-evident hash chain** over `prev_hash` + the row (the `client` address is **inside** the chained payload — ADR 0150) | the store database | HIPAA §164.312(b) audit controls; incident response; `verify_audit_chain` integrity checks | `GET /audit` requires **`audit:read`**; `GET /audit/export` requires the separate **`audit:export`** and streams CSV with formula-injection neutralisation, recording its own `audit.export` row *before* streaming; `GET /me/security-events` is a per-user view of the same table | **`[retention].audit_days` is reserved and NOT enforced — keep-forever by design** (the audit-retention requirement, ~6 years — **not** chain-breakage; [§8](#8-retention--purge) states the position and cites its source of record) | `detail` is stored **in the clear** (it is not a cipher-covered column): its protection is that writers store at least filter shapes, counts, ids, keyed digests, bounded engine-authored text and client addresses, the `audit_log.detail` row above says which — never bodies or credentials — plus the store ACL and the volume layer. *Corrected 2026-10-16 (vault BACKLOG #3145):* this said writers "only ever store filter shapes, counts and ids" | | **6. `message_events` table** | the per-message disposition timeline — the **complete** vocabulary is `received`, `routed`, `unrouted`, `filtered`, `transformed`, `delivered`, `failed`, `dead`, `error`, `replayed`, `resent`, `reingressed`, `passthrough`, `passthrough_dropped`, `cancelled`, `edit_resend`, `edit_resubmit`, `viewed`, `not_deployed`, the ADR 0154 synchronous-reply pair `reply_returned` / `reply_timeout` (names, counts and `waited_ms` only — **never** a fragment of the partner's reply body), and `reply_dropped`, a delivery whose 2xx reply body was over the byte bound and dropped (the status and the bound only, vault BACKLOG #3040) (CI asserts this list against the engine's own `MESSAGE_EVENT_KINDS`). `[diagnostics].message_events` can thin the set, but never below the compliance floor `viewed` / `dead` / `error` / `failed` / `not_deployed` / `reply_timeout` / `reply_dropped` | rows: `message_id`, `ts`, `event`, `destination`, `detail` | the store database | operator timeline on the message-detail view; the `viewed` row is the HIPAA PHI-access record | `GET /messages/{id}` under **`messages:view_raw`** + `require_phi_read`; the read itself writes a `viewed` event **and** a `message_view` audit row | no dedicated window — `purge_message_bodies` sets `message_events.detail` to `NULL` in the same transaction that blanks the body, so it inherits `[retention].messages_days` | `detail` is `safe_text()`-scrubbed **then** cipher-encrypted (AAD `("message_events","detail",message_id,ts,event)`). Verbosity gate `[diagnostics].message_events` = `all` (default) / `errors` / `off`, with a **compliance floor that can never be thinned**: `viewed`, `dead`, `error`, `failed`, `not_deployed`, `reply_timeout`, `reply_dropped` are retained at every level (`reply_timeout` is the one row that explains a "we called you and got a 504" complaint, so an instance that thinned its logs would lose exactly the record it is later asked for; `reply_dropped` is the one row that answers "you ignored our reply", for the same reason) | -| **7. `connection_event` table — DEFAULT ON** (`[diagnostics].connection_events = true`) | transport/lifecycle events per connection: `established`, `closed` (reason `eof`, `idle_timeout` or `frame_deadline` — a fixed vocabulary chosen by the listener, never free text), `idle_timeout`, `at_capacity`, `peer_not_allowlisted`, `frame_oversize`, `framing_error`, `peer_reset`, the MLLP, raw-TCP, X12 and HTTP listeners' and the DATABASE poll source's `handler_error` (BACKLOG #1619, #5022, #5680 for the HTTP listener, which answers it `503` or `500` by the exception's type, as [CONNECTIONS.md Table B](CONNECTIONS.md#table-b--per-service-resource-strategy-asvs-1313) states -- the inbound handler faulted on a frame the listener read cleanly, such as a failed ingress commit; on the X12 listener also, BACKLOG #5971, the engine's own reply to an interchange already recorded could not be encoded in the inbound's charset, so it was not sent; on the DATABASE source, BACKLOG #4921, on a polled row, which is left unmarked and, when the source has a mark statement, stops that poll; the reason is scrubbed at the source like every other), the MLLP, raw-TCP and X12 listeners' `reply_replaced` (BACKLOG #5799 -- the engine's own reply held characters the inbound's charset cannot encode, and each was replaced before the reply was sent; one event per such reply, while the WARNING log line is written once per connection per process; the reason is fixed text that names neither the charset setting nor any part of the reply), the MLLP and HTTP listeners' `tls_handshake_failed` (vault BACKLOG #2613, #3302 and #3785 -- an inbound TLS handshake failed, on any event loop. **This is the one statement of the failed-handshake throttle, and other pages link here.** The first failure is reported at once, then at most one report per listener per minute, carrying the count since the last report. The reason is a count, an exception class name and OpenSSL's reason mnemonic, never the peer's bytes or certificate. A report names a peer only for a single failure, and only where the listener runs its own handshakes or awaits each one's outcome itself, which the MLLP and HTTP listeners do on every loop (BACKLOG #1606, #2479) and the DICOM C-STORE SCP always does. Such a listener also counts a handshake that runs past its bound. Where only the loop sees them, which is at least the API listener on every loop, the report names no peer, since the loop's hook does not read it (the module docstring of `messagefoundry/tls_handshake_failures.py` says what was measured), and a handshake that only runs past its bound is not counted. A peer that closes or resets the socket mid-handshake is not counted anywhere. That is what a load balancer's TCP health check does. The past-bound and hang-up limits stand by owner ruling 2026-10-26 (vault BACKLOG #3785 items 7 and 8), and that ruling covers only those two. Whether the API's report should name the peer is still an open owner question (vault BACKLOG #3302). The item 8 decline keeps the hang-up counting that came before #3785 and adds none. So a close_notify after the ClientHello is still counted, and the DICOM C-STORE SCP counts it too. A handshake that the listener's own stop ends is not counted. At least every listener also drops a genuine failure that lands once its stop has begun. The DICOM C-STORE SCP drops them for the whole of its server shutdown. On the MLLP and HTTP listeners, a stop that is cancelled before it finishes loses the failures its trailing report still held. The DICOM C-STORE SCP still reports them when its server shutdown raises or is cancelled. The API listener and the DICOM C-STORE SCP write the same report, throttled the same way, as a WARNING log line rather than an event: the API has no connection to carry one, and the SCP emits none (vault BACKLOG #3784)), the DATABASE poll source's `row_undecodable` (BACKLOG #1662 — a polled row the source cannot turn into a body; the reason is scrubbed at the source and names the exception type or the operator's own configured column, never a row value), the FILE poll source's quarantine kinds `file_oversize` / `file_decompress_failed` / `file_content_mismatch` / `file_scan_rejected` (BACKLOG #1621 — a drop moved to `.error`; the reason is a size, a content type or a codec or scanner message, and **that message can still name the file**. The name scrub on both the FILE and REMOTEFILE sources is `safe_exc(exc, file_name=...)`. safe_exc replaces the file name and, at least, its repr, ascii, bytes-repr and JSON-escaped forms. A scanner's `ScanRejected` message that quotes the name in at least another case, without its extension, percent-encoded, in another Unicode normalization, or escaped in a spelling those forms do not produce, such as a JSON escape with uppercase hex digits, keeps that text in the reason (`tests/test_file_source_quarantine_events.py` and `tests/test_remotefile_source_quarantine_events.py` pin this on each source's scan-reject arm), so a scan hook should leave the name out of its message; the REMOTEFILE poll source records the same kinds except `file_decompress_failed`, since it does not decompress), the inbound-HTTP intake-auth refusals `intake_auth_failed` / `auth_subject_denied` / `auth_rate_limited` (ADR 0154 D6 — peer address and mode only, plus, behind a proxy the connection lists in its trusted_proxies setting, the forwarded client address as a forwarded_for suffix on the reason and the audit detail (BACKLOG #5525); **never** the credential, a prefix of it, or its length. Each of these also writes a tamper-evident audit-log row — the copy that survives an operator turning this diagnostics stream off. The MLLP listener writes `auth_subject_denied` and `auth_rate_limited` too, with the same audit rows, when its expected-sender allowlist refuses a sender, naming the peer address and never a certificate field; BACKLOG #4907), plus the runner's `connection_lost` / `connection_restored` / `config_fault`. That is the whole vocabulary, asserted in CI against the literal emit call sites in `transports/` and the pipeline runner **and** against `CONNECTION_EVENT_KINDS` (`messagefoundry/connection_events.py`), the one set the store enforces on write and the console's filter reads (BACKLOG #1624). The MLLP, raw-TCP, X12 and HTTP listeners emit these; the **DATABASE poll source** emits `row_undecodable` and `handler_error` and nothing else (it dials out, so there is no lifecycle to report and its rows carry a **NULL peer column**); the **FILE poll source** emits only its four quarantine kinds, and the **REMOTEFILE poll source** only three of them, both with a NULL peer column; the **DICOM inbound C-STORE SCP** emits none — the runner injects the sink onto **every** source (`wiring_runner.py`, over the base-class `on_connection_event` field), so that connector *has* the wiring and simply never calls it — so this stream covers those four listeners plus those poll-source events and the runner's outbound-lane transitions — not literally every connection. A DICOM association's connects and refusals are therefore **absent** from this stream. The **`ISA`/`IEA`-framed X12 inbound** was equally absent until BACKLOG #1665 and is not any more: it emits the same kinds as the raw-TCP listener | rows: `ts`, `connection`, `transport`, `direction`, `kind`, `peer_host`, `message_id` (correlation hint), `reason` | the store database, **all three backends** | Corepoint-style transport diagnostics — "did the sender connect, and why did it drop" | `GET /events` and `GET /connections/{name}/events` under **`monitoring:read`** (**not** a PHI permission) with per-channel RBAC — an out-of-scope `connection=` is 403'd *and* audited — server-clamped to ≤1000 rows. `reason` alone is gated on `messages:view_summary` and masked as `****` until the audited per-event `reveal=` act (BACKLOG #2443; the `connection_event.reason` row of §3's PL-2 block says how) | `[retention].connection_event_retention_hours` (its own **hours** window); 0 inherits `[retention].messages_days`; both 0 = keep forever. Plain age `DELETE` | **`reason` is free text that can carry sensitive fragments.** Defended twice — `safe_exc()` at the source, `safe_text(reason, limit=200)` at the store (the bound §3's PL-2 block states) — then cipher-encrypted (AAD `("connection_event","reason",connection,ts,kind)`). Every other column is engine or config metadata except `peer_host`, and `reason` is not metadata-only: the [data-at-rest inventory](#2-where-phi-lives--data-at-rest-inventory) grades `reason` and `peer_host` in rows of their own (BACKLOG #5021). Writes are a pure side observer: a bounded in-memory queue drained by a background task outside any handoff transaction, so a flood can never block a listener or pin a message disposition | +| **7. `connection_event` table — DEFAULT ON** (`[diagnostics].connection_events = true`) | transport/lifecycle events per connection: `established`, `closed` (reason `eof`, `idle_timeout` or `frame_deadline` — a fixed vocabulary chosen by the listener, never free text), `idle_timeout`, `at_capacity`, `peer_not_allowlisted`, `frame_oversize`, `framing_error`, `peer_reset`, the MLLP, raw-TCP, X12 and HTTP listeners' and the DATABASE poll source's `handler_error` (BACKLOG #1619, #5022, #5680 for the HTTP listener, which answers it `503` or `500` by the exception's type, as [CONNECTIONS.md Table B](CONNECTIONS.md#table-b--per-service-resource-strategy-asvs-1313) states -- the inbound handler faulted on a frame the listener read cleanly, such as a failed ingress commit; on the X12 listener also, BACKLOG #5971, the engine's own reply to an interchange already recorded could not be encoded in the inbound's charset, so it was not sent; on the DATABASE source, BACKLOG #4921, on a polled row, which is left unmarked and, when the source has a mark statement, stops that poll; the reason is scrubbed at the source like every other), the MLLP, raw-TCP and X12 listeners' `reply_replaced` (BACKLOG #5799 -- the engine's own reply held characters the inbound's charset cannot encode, and each was replaced before the reply was written to the connection; at most one event per such reply, sent whether or not the write then succeeds, while the WARNING log line is written once per connection per process; a frame byte turned into a space writes no event; the reason is fixed text that names neither the charset setting nor any part of the reply), the MLLP and HTTP listeners' `tls_handshake_failed` (vault BACKLOG #2613, #3302 and #3785 -- an inbound TLS handshake failed, on any event loop. **This is the one statement of the failed-handshake throttle, and other pages link here.** The first failure is reported at once, then at most one report per listener per minute, carrying the count since the last report. The reason is a count, an exception class name and OpenSSL's reason mnemonic, never the peer's bytes or certificate. A report names a peer only for a single failure, and only where the listener runs its own handshakes or awaits each one's outcome itself, which the MLLP and HTTP listeners do on every loop (BACKLOG #1606, #2479) and the DICOM C-STORE SCP always does. Such a listener also counts a handshake that runs past its bound. Where only the loop sees them, which is at least the API listener on every loop, the report names no peer, since the loop's hook does not read it (the module docstring of `messagefoundry/tls_handshake_failures.py` says what was measured), and a handshake that only runs past its bound is not counted. A peer that closes or resets the socket mid-handshake is not counted anywhere. That is what a load balancer's TCP health check does. The past-bound and hang-up limits stand by owner ruling 2026-10-26 (vault BACKLOG #3785 items 7 and 8), and that ruling covers only those two. Whether the API's report should name the peer is still an open owner question (vault BACKLOG #3302). The item 8 decline keeps the hang-up counting that came before #3785 and adds none. So a close_notify after the ClientHello is still counted, and the DICOM C-STORE SCP counts it too. A handshake that the listener's own stop ends is not counted. At least every listener also drops a genuine failure that lands once its stop has begun. The DICOM C-STORE SCP drops them for the whole of its server shutdown. On the MLLP and HTTP listeners, a stop that is cancelled before it finishes loses the failures its trailing report still held. The DICOM C-STORE SCP still reports them when its server shutdown raises or is cancelled. The API listener and the DICOM C-STORE SCP write the same report, throttled the same way, as a WARNING log line rather than an event: the API has no connection to carry one, and the SCP emits none (vault BACKLOG #3784)), the DATABASE poll source's `row_undecodable` (BACKLOG #1662 — a polled row the source cannot turn into a body; the reason is scrubbed at the source and names the exception type or the operator's own configured column, never a row value), the FILE poll source's quarantine kinds `file_oversize` / `file_decompress_failed` / `file_content_mismatch` / `file_scan_rejected` (BACKLOG #1621 — a drop moved to `.error`; the reason is a size, a content type or a codec or scanner message, and **that message can still name the file**. The name scrub on both the FILE and REMOTEFILE sources is `safe_exc(exc, file_name=...)`. safe_exc replaces the file name and, at least, its repr, ascii, bytes-repr and JSON-escaped forms. A scanner's `ScanRejected` message that quotes the name in at least another case, without its extension, percent-encoded, in another Unicode normalization, or escaped in a spelling those forms do not produce, such as a JSON escape with uppercase hex digits, keeps that text in the reason (`tests/test_file_source_quarantine_events.py` and `tests/test_remotefile_source_quarantine_events.py` pin this on each source's scan-reject arm), so a scan hook should leave the name out of its message; the REMOTEFILE poll source records the same kinds except `file_decompress_failed`, since it does not decompress), the inbound-HTTP intake-auth refusals `intake_auth_failed` / `auth_subject_denied` / `auth_rate_limited` (ADR 0154 D6 — peer address and mode only, plus, behind a proxy the connection lists in its trusted_proxies setting, the forwarded client address as a forwarded_for suffix on the reason and the audit detail (BACKLOG #5525); **never** the credential, a prefix of it, or its length. Each of these also writes a tamper-evident audit-log row — the copy that survives an operator turning this diagnostics stream off. The MLLP listener writes `auth_subject_denied` and `auth_rate_limited` too, with the same audit rows, when its expected-sender allowlist refuses a sender, naming the peer address and never a certificate field; BACKLOG #4907), plus the runner's `connection_lost` / `connection_restored` / `config_fault`. That is the whole vocabulary, asserted in CI against the literal emit call sites in `transports/` and the pipeline runner **and** against `CONNECTION_EVENT_KINDS` (`messagefoundry/connection_events.py`), the one set the store enforces on write and the console's filter reads (BACKLOG #1624). The MLLP, raw-TCP, X12 and HTTP listeners emit these; the **DATABASE poll source** emits `row_undecodable` and `handler_error` and nothing else (it dials out, so there is no lifecycle to report and its rows carry a **NULL peer column**); the **FILE poll source** emits only its four quarantine kinds, and the **REMOTEFILE poll source** only three of them, both with a NULL peer column; the **DICOM inbound C-STORE SCP** emits none — the runner injects the sink onto **every** source (`wiring_runner.py`, over the base-class `on_connection_event` field), so that connector *has* the wiring and simply never calls it — so this stream covers those four listeners plus those poll-source events and the runner's outbound-lane transitions — not literally every connection. A DICOM association's connects and refusals are therefore **absent** from this stream. The **`ISA`/`IEA`-framed X12 inbound** was equally absent until BACKLOG #1665 and is not any more: it emits the same kinds as the raw-TCP listener | rows: `ts`, `connection`, `transport`, `direction`, `kind`, `peer_host`, `message_id` (correlation hint), `reason` | the store database, **all three backends** | Corepoint-style transport diagnostics — "did the sender connect, and why did it drop" | `GET /events` and `GET /connections/{name}/events` under **`monitoring:read`** (**not** a PHI permission) with per-channel RBAC — an out-of-scope `connection=` is 403'd *and* audited — server-clamped to ≤1000 rows. `reason` alone is gated on `messages:view_summary` and masked as `****` until the audited per-event `reveal=` act (BACKLOG #2443; the `connection_event.reason` row of §3's PL-2 block says how) | `[retention].connection_event_retention_hours` (its own **hours** window); 0 inherits `[retention].messages_days`; both 0 = keep forever. Plain age `DELETE` | **`reason` is free text that can carry sensitive fragments.** Defended twice — `safe_exc()` at the source, `safe_text(reason, limit=200)` at the store (the bound §3's PL-2 block states) — then cipher-encrypted (AAD `("connection_event","reason",connection,ts,kind)`). Every other column is engine or config metadata except `peer_host`, and `reason` is not metadata-only: the [data-at-rest inventory](#2-where-phi-lives--data-at-rest-inventory) grades `reason` and `peer_host` in rows of their own (BACKLOG #5021). Writes are a pure side observer: a bounded in-memory queue drained by a background task outside any handoff transaction, so a flood can never block a listener or pin a message disposition | | **8. `alert_instance` table — default on wherever an `[alerts]` notifier exists** | resolvable operator alerts: `connection_stopped`, `queue_buildup`, `lane_stuck`, `message_stall`, `saturation`, `connection_error`, `connection_error.config_fault`, `storage_threshold`, `cert_expiry`, `secret_rotation`, `initial_credential_expiring` (an UNCLAIMED admin-issued temporary password nearing the instant the login gate stops accepting it -- ASVS 6.4.5, BACKLOG #1141; keyed on `user:`, and the payload is the ISO deadline plus whole hours remaining, repeated in the reason column, never the password), `integrity_drift`, `update_available`, `backup_failed`, `store_privilege_warning` (the store privilege preflight found the store principal over-granted or could not read it -- BACKLOG #305; the payload is the finding, a count and the preflight's summary line, which names the login, the database and role names, never a password or message content), `vault_privilege_warning` (the Vault privilege preflight found a Vault token over-granted or could not read it -- BACKLOG #2903, ADR 0216; keyed on `vault:store` or `vault:secrets`, and the payload is the finding, a count of refusing-class grants and the hop's judgment, which names policy names, paths and capabilities, never a token, an accessor, a digest of either or message content), `leadership_acquired`, `dr_activated`, `log_write_failed` (an application-log sink was rolled after a write failure, or is UNWRITABLE and this process's connections were stopped -- BACKLOG #122, ADR 0162; the payload is the sink LABEL, the stage, a `safe_exc` reason and a count of connections stopped, never the record whose write failed), `log_forward_failed` (the off-box log forwarder is absent, losing records or not sending -- BACKLOG #2612; keyed on `forwarder:`, with `@node:` or `@shard:` appended when several engine processes share the store, and the payload is that key, fixed reason words and a count, never a record, the collector's address or an error text; an unpinned cluster node's `node_id` holds this engine's own host name and process id, so the key carries them), `gcm_invocations` (the per-key AES-GCM invocation bound crossing its 2^31 soft warn — ASVS 11.3.4; its payload carries a one-way `key_id` fingerprint plus counters, never key bytes), `approval_stale_requester` (a dual-control release refused because the requester no longer holds the authority the operation needs -- ASVS 8.3.2, BACKLOG #289; keyed on the approval id, and the payload is that id, the operation key and a closed-set reason slug, never the requester's name or the captured params), `approval_too_early` (a dual-control release refused because it arrived before `[approvals].min_dwell_seconds` -- ASVS 2.4.2, BACKLOG #287; keyed on `approval:`, and the payload is that key, the operation key and a fixed reason string, never the approver's or requester's name or the captured params), `audit_write_failed` (the approval gate could not write one of its audit rows -- vault BACKLOG #2255; keyed on `approval:`, on `approval::resolve` for a resolution's lost provenance row -- vault BACKLOG #3438, on the fixed `approval:listing` for a queue listing's lost `approval.standing_shown` row -- vault BACKLOG #3747, on `config_reload:inline` when an ungated config reload could not write its `config_reload_attempted` row -- vault BACKLOG #2254, or on `step_up_return:audit_budget:` when the IdP step-up return audit budget's backstop stopped a row -- BACKLOG #3965, or on `directory-reconciler:` when a directory reconcile pass that completed could not write a row -- BACKLOG #3018 step 2, or on `directory-sign-in:` when a directory sign-in's role-sync row was refused twice -- BACKLOG #2221; the payload is that key and the lost row's audit action name, never the row's detail, a username or the captured params; the ERROR log line beside it holds the detail on some paths and only the exception on others), `audit_offbox_copy_missing` (an approval audit row whose write the gate read back as committed, whose off-box copy was never sent -- vault BACKLOG #3193; keyed on `approval:`, and the payload is that key and the row's audit action name, never the row's detail, a username or the captured params), `ad_reconcile_aborted` (a directory reconciler pass left signed-in accounts unrevoked and needs an operator: the mass-revoke breaker tripped and nothing was revoked, or one or more probes were answered with an LDAP referral and those accounts were left unjudged while the rest of the pass was applied, BACKLOG #2538, or one or more probes raised a fault the engine could not read and those accounts were left unjudged the same way, BACKLOG #3100, or the directory refused one or more probes with a result code that points at the configuration, such as a deleted search base, and those accounts were left unjudged the same way, vault BACKLOG #3010, or an account's group search was refused for the engine's own deadline or cap, so a role or scope change in the directory does not revoke that account's sessions, though a disable or deletion still does, vault BACKLOG #3696, or every lookup failed to reach the directory for `[auth].ad_reconcile_outage_passes` passes running, BACKLOG #3709; for the breaker, a referral, a probe fault, a configuration refusal and a lasting outage the payload is a fixed source label, `directory-reconciler` for the breaker, `directory-reconciler-referral` for a referral, `directory-reconciler-probe-fault` for a probe fault, `directory-reconciler-misconfigured` for a configuration refusal and `directory-reconciler-outage` for a lasting outage so each is its own instance, the closed-set reason slug `mass_revoke_breaker`, `directory_referral`, `probe_fault`, `directory_misconfigured` or `directory_unavailable`, a count (the accounts the breaker judged, or for each of the other four the lookups the pass sent, which leaves out an id-less row -- vault BACKLOG #3170) and the latched operator explanation, or for a lasting outage a fixed sentence with the run's length, never a username; a paging refusal is instead keyed on that operator account's username, as `directory-reconciler-paging:`, so each account is its own instance, raised as the account enters that state and again after a restart while it stands, and the payload is that key, the closed-set reason slug `group_search_deadline` or `group_search_cap`, the same count as the breaker's and a fixed sentence naming the cause, never anything else about the account; an account the directory keeps failing to answer for is keyed the same way, as `directory-reconciler-unreached:`, raised as it enters that state, and its payload is that key, the closed-set reason slug `account_unreachable`, the count of lookups the pass sent and a fixed sentence with two numbers, how many probes failed and the most recent probes its window can hold (faults aside), never anything else about the account -- vault BACKLOG #3100, #3709; on a rolled-up pass, those entering page as one instance under the bare `directory-reconciler-unreached` source, with no username, and the `ad_reconcile_outage_passes` row of [CONFIGURATION.md](CONFIGURATION.md) states when), `ad_reconcile_held` (the reconciler is holding accounts whose `userAccountControl` it cannot read, ADR 0195; the payload is the same fixed source label, a closed-set reason slug, the count of undetermined accounts and the latched operator explanation, never a username), `ad_session_revoked` (the reconciler revoked a directory principal's sessions; keyed on that operator account's username, with at least a `directory_absent`, `directory_disabled`, `directory_undetermined`, `directory_object_id_missing`, `roles_changed` or `scope_changed` reason), `approval_approver_provenance` (a dual-control release, or the resolution of an interrupted one, went ahead with an approver or resolver account created, re-passworded or TOTP-enrolled after the request -- BACKLOG #315, #2125; keyed on `approval:`, or `approval::resolve` for a resolution, and the payload is the operation key and the closed-set change slugs, never a username or the captured params), `administrator_granted` (the built-in Administrator role was granted by account creation, a role change, a directory group newly mapped to it -- BACKLOG #315 --, a directory sign-in whose role sync newly gave the account the role -- vault BACKLOG #2610 -- or a directory reconcile pass whose role re-diff did -- vault BACKLOG #3141; keyed on `user:` or `ad-group:`, with the grant route and the granting administrator's username, or `` for a directory sign-in or reconcile pass), `no_enabled_administrator` (a directory sign-in's role sync or the session reconciler took Administrator from its last enabled holder -- vault BACKLOG #3229; keyed on `user:`, and the payload is `via`, `ad-sync` or `ad-reconcile`, and a fixed reason sentence, never message content), `intake_paused` (the engine paused intake because the staged backlog went over `[inbound].max_staged_depth` or the SQLite volume fell below `[retention].min_free_disk_mb` -- BACKLOG #290; keyed on `intake:staged_depth` or `intake:disk_floor`, with `@node:` or `@shard:` appended when several engine processes share the store (BACKLOG #2272), and the payload is the reason, a count or a MiB figure, its limit and the store backend's name, never message content), `config_changed` (a start's config differs from the store's baseline: the bytes it loaded, or the directory just after the load -- vault BACKLOG #2597, #3765; keyed on `config:`, and the payload is the two digests, the node and engine shard labels, the action, actor username, time and node of the row the older digest came from, and the `comparison` outcome, never the config directory, a git commit or message content), `crl_reload_refused` (the CRL reload refused a replaced CRL file, so running TLS contexts keep the copy they hold -- vault BACKLOG #2904; keyed on `crl_reload:`, with `@node:` or `@shard:` appended when several engine processes share the store, and the payload is that key, the file's path, a short class token for the remedy, a count of contexts, the engine's own fixed remedy sentence and, when a start would refuse the file too, a `start_refuses` flag, never the refusal's reason, which quotes CRL issuer names and dates; that reason is in the application log, and in the `detail` of the CRL expiry alert once the held copy nears its `nextUpdate`), `remote_debug_refused` (the engine's remote-debugging guard refused scripts that another process injected into the engine process -- vault BACKLOG #2742; keyed on `remote_debug:refused`, with `@node:` or `@shard:` appended when several engine processes share the store, and the payload is that key, the count of scripts refused since the alert was last raised, the count since the process started and a fixed sentence built from the two, never a script's file name, which the injecting process chooses; that name is in the application log, in the guard's WARNING line), `sandbox_worker_refused` (a `[sandbox].mode = "subprocess"` worker was refused because the graph it loaded differs from the engine's, most often a config file edited on disk with no reload -- vault BACKLOG #2724; keyed on the inbound's name, raised once per refusal, and the payload is that name and a fixed sentence naming the cause and the remedy, never a message body or the refusal text, which names config names and digests and is in the application log), `store_restored` (the first `serve` on a store `messagefoundry restore` placed ended every session -- BACKLOG #2614; keyed on `store:restored`, raised once per restore, and the payload is that key; a fixed sentence carrying the archive's age in days, the count of sessions ended, a pointer to `messagefoundry restore --help` and the time of the archive's newest audit row, of which the alert instance's reason column keeps the age, the count and the pointer whole and the time redacted or cut; that time again as `last_audit_at`; and the fixed notice of what a restore rolls back as `rollback_notice` (`messagefoundry/restore_notice.py`, BACKLOG #5094), fixed text the reason column never holds; never an account name or a row's content), and the seven security signals of the audit-stream rule layer -- vault BACKLOG #2613: `signin_failure_burst` (keyed on `signin:`, never the typed username), `access_denied_burst`, `body_view_burst` and `bulk_export` (each keyed on `account:`), `peer_refused_burst` (keyed on `inbound:`, never the refused peer's address), `log_level_debug` (keyed on `logging:debug`) and `posture_loosened` (keyed on `posture:start`, with `@node:` or `@shard:` appended when several engine processes share the store); the payload is a count and a fixed sentence holding a level name, switch names or a username, never a message body, a message id or an audit row's detail. The reachable **inverse** signals — `connection_restored`, `leadership_lost`, `dr_released`, `store_privilege_clean`, `vault_privilege_clean`, `intake_resumed`, `posture_restored` (it resolves `posture_loosened` under the same key, so for the same engine process, when a start records no security loosening in a row marked neither `superseded` nor `baseline_unchecked` and a live posture read then names none -- vault BACKLOG #2613; an unpinned cluster node's key changes on every start, so that node raises the inverse for its own instance as it shuts down; when that instance can still stay open is in [SECURITY.md](SECURITY.md)), `crl_reload_applied` (it resolves `crl_reload_refused` under the same key, so for the same file and the same engine identity, at least once the reload's record no longer holds the refusal, once no hop holds any CRL, and when the reload stops -- vault BACKLOG #2904; it is also raised once per held file outside a CA bundle, at the first pass that judges it with no refusal standing, whether or not an alert is open, so it can resolve nothing, and it then clears one an earlier run under that identity left open -- vault BACKLOG #3543. An alert for a file no hop holds now stays open, and so does one an unpinned cluster node raised, because that node's identity changes on every start; [CONFIGURATION.md](CONFIGURATION.md), *The alert resolves itself*, is the source of record), `ad_reconcile_breaker_cleared`, `ad_reconcile_hold_released` (the last two resolve `ad_reconcile_held` and `ad_reconcile_aborted`, the latter only under the breaker's, the referral's or the lasting outage's source: the probe fault's, the configuration refusal's, a paging refusal's and an unreached account's instances have no inverse; when they do, and where they never do, is stated once in [CONFIGURATION.md](CONFIGURATION.md#when-the-reconcilers-alerts-resolve-themselves) -- BACKLOG #2136) — are never rows here: `_record_state` routes an inverse through `_AUTO_RESOLVE` to `resolve_alert_instances_fenced` (BACKLOG #4916), or `resolve_alert_instances_for` on a store without the fence methods, never to `upsert_alert_instance`. So is `connection_started`, which resolves `connection_stopped` under the bare connection name: the runner raises it only when an operator's start or restart finds an inbound up and no cause it can see still holds the name down in either direction (BACKLOG #1741). Every other start raises nothing, at least an engine start, a committed reload, the scheduler and every alert rule's restart, so an open stop keeps its instance, ack and suspend across them. `AlertSink.connection_started` states the full contract, including the operator starts that still raise nothing. An instance raised under a prefixed stand-in such as `reference:` is never resolved by it. | rows: `event_type`, `connection`, `severity`, `status`, `first_seen`, `last_seen`, `count`, `reason`, `acked_by`, `acked_at`, `resolved_at`, `suspended_until`, `escalation_tier`, `raised_by` (a random per-process id naming the newest raise's writer, BACKLOG #4916; never a host, user or message value) | the store database, **all three backends** | the operator alert list — acknowledge / resolve / suspend. Durable state is recorded **before** any suppression or throttle return, so a muted alert still leaves a record | `GET /alerts/active` under **`monitoring:diagnose`** (**not** a PHI permission) with the same per-channel scope, and `reason` alone gated on `messages:view_summary` and masked as `****` until the audited per-alert `reveal=` act (BACKLOG #2443; the `alert_instance.reason` row of §3's PL-2 block says how); ack/resolve/suspend/**resume** are POSTs on the same tier, and the separate read-only `GET /alerts/rules` view sits on its own gate | shares the connection-event window; **only RESOLVED instances are DELETEd**, by `resolved_at` — retention never ages out an open or acknowledged condition from under an operator; a row can still close with no inverse and no operator, at least through the `intake_paused` staleness sweep (BACKLOG #3269), which resolves another engine process's open or acknowledged pause under the expiry rule in [CONFIGURATION.md](CONFIGURATION.md#alerts), after which retention treats it as any resolved row | **`reason` is free text** taken from the event's internal `_detail` (the `connection_error` reason kept off the wire, BACKLOG #5021), `detail` or `reason`: `safe_text(reason, limit=200)` (the bound §3's PL-2 block states) then cipher-encrypted (AAD `("alert_instance","reason",event_type,connection)` — the de-dup grain, so one AAD covers both the INSERT and the re-fire UPDATE). | | **9. `response` rows with `kind='ack_sent'` — DEFAULT ON** (`[diagnostics].response_sent = true`) | the ACK/NAK the engine returned to an inbound sender, under a sentinel destination `\x1fack:` | rows: `ack_code` (`AA`/`AE`/`AR`/`CA`/`CE`/`CR`), `ack_phase` (`decode`/`parse`/`strict`/`ingest`), `outcome`, `body`, `detail` | the store database | "what did we actually reply, and why" — the operator's answer to a sender disputing an ACK | `GET /messages/{id}/responses` under `messages:read` + `require_phi_read`; the `body` only for a caller who also holds `messages:view_raw` and `messages:view_summary`; every read writes a `response.read` audit row | `body`, `detail` and `resp_headers` are set to `NULL` in place by `purge_message_bodies` on the message-body window, on all three backends | **PHI fail-safe:** the ACK **body** is stored **only when the store cipher is active** — on a keyless store it is `NULL` rather than plaintext — and every NAK passes no body at all, so the offending field value is never persisted. The disposition metadata (`ack_code`/`ack_phase`/`outcome`) is non-PHI and always captured; `detail` is `safe_text`-scrubbed, held to the 200-character bound §3's PL-2 block states, and encrypted | | **10. `[alerts]` webhook transport** (off by default — `webhook_url` unset) | one HTTPS POST per alert, carrying every non-underscore event key as JSON | JSON | the operator's webhook endpoint (Slack/Teams/PagerDuty/custom) | operator notification | **`https` only** — a plaintext `http://` webhook URL is refused at construction. Redirects are refused; an optional `webhook_allowed_hosts` egress allowlist gates the host. A verifying `https` hop off this box also takes the revocation guard at build, on a host the `webhook_allowed_hosts` allowlist admits. An unset or empty allowlist admits every host, an explicit `[]` included, and so does an environment value that splits to no host, such as `""` or `","`. A host off a non-empty allowlist is refused at build, before this guard (BACKLOG #5088). A TOML list keeps its entries as written, so `[""]` or `[","]` is not empty and names no real host, and the build refuses every real host. Under an enforcing or unknown posture the guarded hop is refused unless the `[alerts].webhook_tls_revocation_attested` pair is set ([ADR 0173](adr/0173-tls-peer-revocation-checking-and-ocsp-stapling-across-terminating-and-originating-surfaces.md) states the guard and its levers) | the endpoint's | **carries the alert's `detail`/`reason` free text** for at least `connection_stopped`, `log_write_failed` and `backup_failed` (`safe_exc()`-scrubbed at the emit sites, but **not** re-run through `safe_text` on this path, and a scrubbed reason can still echo a partner's reply text). `connection_error` no longer carries its detail: in its place it sends the exception class (or the fixed token `unnamed error` for a class that is not a plain identifier), beside at least the connection and the kind, and keeps the detail under the internal `_detail` key, which the notifier pops before any transport is handed the event and which the alert instance's stored `reason` (row 8) still keeps (`NotifierAlertSink.connection_error`, BACKLOG #5021). Internal `_`-prefixed keys, at least `_detail`, `_transports`, the per-rule recipients, the rule id and the cooldown, are stripped before send, so recipient addresses never cross the wire | diff --git a/messagefoundry/transports/framing.py b/messagefoundry/transports/framing.py index 5801faad10..124a818b48 100644 --- a/messagefoundry/transports/framing.py +++ b/messagefoundry/transports/framing.py @@ -80,8 +80,7 @@ #: The ``reason`` of a ``reply_replaced`` connection event. Fixed text: it names neither the charset #: setting nor any part of the reply, which echoes the message. REPLY_REPLACED_REASON = ( - "the reply held characters the inbound charset cannot encode; each was replaced before it " - "was sent" + "the reply held characters the inbound charset cannot encode, and each was replaced" ) @@ -183,8 +182,10 @@ def frame_reply_reporting( def encode_reply(reply: str, encoding: str, *, connection: str = "") -> bytes: - """Encode a listener's post-commit reply in its declared charset, for :func:`frame_reply` and - for the X12 listener, which writes its reply unframed (BACKLOG #5958). + """Encode a listener's post-commit reply in its declared charset. The listeners call + :func:`encode_reply_reporting`, which does this and also says whether characters were replaced: + :func:`frame_reply_reporting` for the MLLP and raw-TCP listeners, and the X12 listener directly, + since it writes its reply unframed (BACKLOG #5958). A reply whose charset NAME is unusable is sent in ``utf-8`` instead: a name that names no text codec, or one that refuses every conversion, would otherwise leave the ``AE`` diff --git a/messagefoundry/transports/mllp.py b/messagefoundry/transports/mllp.py index 0db638f5b9..3a693b9460 100644 --- a/messagefoundry/transports/mllp.py +++ b/messagefoundry/transports/mllp.py @@ -3327,7 +3327,9 @@ async def _on_client( writer.write(wire) if replaced: # BACKLOG #5799: the log line is once per connection; the - # event records every reply that was altered. + # event is sent for each reply whose characters the charset + # forced a replacement of. A frame byte turned into a space + # is not one of those, and writes only its warning. await self._emit_event( "reply_replaced", peer_host=peer_host, diff --git a/messagefoundry/transports/x12.py b/messagefoundry/transports/x12.py index e9e36f7f36..4efdb3c7d2 100644 --- a/messagefoundry/transports/x12.py +++ b/messagefoundry/transports/x12.py @@ -711,7 +711,7 @@ class X12Source(SourceConnector): """Listen for inbound raw-TCP connections, reassemble each ``ISA…IEA`` interchange, and hand its **raw bytes** to the pipeline handler. No HL7/X12 ACK: if that *pipeline* handler (:data:`~messagefoundry.transports.base.InboundHandler`) returns a non-``None`` reply it is written - back on the same connection, encoded by :func:`~messagefoundry.transports.framing.encode_reply` + back on the same connection, encoded by :func:`~messagefoundry.transports.framing.encode_reply_reporting` (BACKLOG #5958); the engine's returns ``None`` for every non-HL7 content type, so an X12 intake is fire-and-forget in practice. A config **Handler**'s return never reaches here — see this module's docstring.""" diff --git a/tests/test_mllp_handler_failure.py b/tests/test_mllp_handler_failure.py index 0ce27b6733..27123be758 100644 --- a/tests/test_mllp_handler_failure.py +++ b/tests/test_mllp_handler_failure.py @@ -703,7 +703,11 @@ async def test_a_handler_fault_nak_the_charset_altered_writes_a_reply_replaced_e assert cap.kinds()[:3] == ["established", "handler_error", "reply_replaced"], cap.kinds() -def test_the_handler_fault_nak_flags_a_replacement_only_when_one_was_made() -> None: +def test_the_handler_fault_nak_flags_a_replacement_only_when_one_was_made( + monkeypatch: pytest.MonkeyPatch, +) -> None: + # The warn-once set is module state, so this test's addition is discarded after it. + monkeypatch.setattr(framing_mod, "_reply_replacement_logged", set()) source = _mllp(encoding="ascii") clean = source._handler_failure_nak(b"MSH|^~\\&|S|F|R|F|20260101||ADT^A01|C1|P|2.5\r") altered = source._handler_failure_nak(b"MSH|^~\\&|S|F|R|F|20260101||ADT^A01|C\xe91|P|2.5\r") From 32bdbb5051e0014d0dce7c893200fa48d3faa0e1 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sat, 21 Nov 2026 18:39:58 -0600 Subject: [PATCH 29/74] Schema check review fixes: classify only the live read, keep a view under an expected name Review round-4cca7dc5 on e2bff915e3..4944cf0cef: - The verify now classifies only its read of the live store. The expected shape is built outside run_schema_step, so a failure of this build's own scratch build keeps its own error rather than the recreate remedy. - A view under a table or index name this build creates holds that object's place, so it keeps the plain remedy, not the drop remedy. - The drop remedy names the object's kind and name, ahead of the cause. - Tests: the not-a-shape control is a real SQLite error; a test pins that the expected-shape build is not classified; the verify-read test checks the read raised it; the view-or-trigger pin is renamed and compares a set. - Changelog no longer says every re-check failure gets the drop remedy. BACKLOG #6719 item 3, #6720 item 4. --- .../6719-6720-foreign-view-remedy.fixed.md | 10 ++- messagefoundry/store/schema_verify.py | 66 ++++++++++----- tests/test_schema_verify_6719_6720.py | 82 ++++++++++++++----- 3 files changed, 116 insertions(+), 42 deletions(-) diff --git a/changelog.d/6719-6720-foreign-view-remedy.fixed.md b/changelog.d/6719-6720-foreign-view-remedy.fixed.md index 28db7e30f7..a8aefd14b2 100644 --- a/changelog.d/6719-6720-foreign-view-remedy.fixed.md +++ b/changelog.d/6719-6720-foreign-view-remedy.fixed.md @@ -1,6 +1,8 @@ - **A SQLite store whose upgrade is stopped by a view or trigger another tool left now names that - object.** When SQLite's re-check after a migration's `ALTER` fails on a view or trigger, the open - refuses the store with the remedy to drop that object and restart, not to recreate the store. A - failure on the store's shape raised by the check's own read, after the schema script and the - migrations, is now refused with the recreate remedy rather than escaping as SQLite's bare error. + object.** When SQLite's re-check after a migration's `ALTER` fails on such a view or trigger with + an error that names the store's shape, such as "no such module", the open refuses the store with + the remedy to drop that object and restart, not to recreate the store. A view under the name of a + table or index this build creates still gets the recreate remedy. A failure on the store's shape + raised by the check's own read of the live store, after the schema script and the migrations, is + now refused with the recreate remedy rather than escaping as SQLite's bare error. (`BACKLOG #6719`, `BACKLOG #6720`) diff --git a/messagefoundry/store/schema_verify.py b/messagefoundry/store/schema_verify.py index beef8e52af..b45aa6c15b 100644 --- a/messagefoundry/store/schema_verify.py +++ b/messagefoundry/store/schema_verify.py @@ -80,15 +80,12 @@ " so restarting under the old key would zero its AES-GCM use count, which lives in the store. If" " you set [secret_rotation].store_key_last_rotated, update it." ) -# The ALTER re-check's prefix when an object other than the altered table fails to parse. Only the -# view and trigger forms: this build creates neither (see _ORDINARY_TABLE), so the object named is -# another tool's. SQLite uses the same form for a table or an index, which may be this build's own. -_FOREIGN_OBJECT_PREFIXES = ("error in view ", "error in trigger ") -# Dropping a view or a trigger removes no row, so this remedy keeps the store and its key. -_REMEDY_FOREIGN = ( - "holds a view or trigger this build did not create, which stops its upgrade: drop that object," - " then restart." -) +# The kinds the ALTER re-check names, as "error in : ...", when an object other than +# the altered table fails to parse. Only views and triggers: this build creates neither (see +# _ORDINARY_TABLE), so the object named is another tool's. SQLite uses the same form for a table or +# an index, which may be this build's own. Dropping a view or a trigger removes no row, so that +# remedy keeps the store and its key. +_FOREIGN_KINDS = ("view", "trigger") # The reads below skip a table whose stored SQL is LIKE 'CREATE VIRTUAL TABLE%', because a pragma # on a virtual table whose module is not loaded here can raise "no such module" (BACKLOG #6719). @@ -350,17 +347,20 @@ async def verify_live_schema( service's key still gets the new-key remedy. A process that HAS a key is never overruled by the file, because a restored cell-bound store also has counts and no salt row until its first open. - A read that fails on the store's shape is refused the same way, through + A read of the live store that fails on its shape is refused the same way, through :func:`run_schema_step` (BACKLOG #6720): a virtual table whose stored SQL the ``_ORDINARY_TABLE`` predicate does not recognise, held under an expected name, raises "no such - module" from the column read rather than reading as a difference. + module" from the column read rather than reading as a difference. The expected shape is built + outside that, so a failure of this build's own script or migrations keeps its own error. """ - problems = await run_schema_step( + expected = await _expected_shape(schema, migrate) + live = await run_schema_step( db, - live_schema_differences(db, schema=schema, migrate=migrate), + read_schema_shape(db, sorted(expected.columns)), path=path, counts_under_dek=counts_under_dek, ) + problems = schema_differences(expected, live) if problems: if counts_under_dek is None: counts_under_dek = await _counts_under_a_dek(db) @@ -396,7 +396,8 @@ async def verify_live_schema( def is_schema_step_error(exc: BaseException) -> bool: - """Whether ``exc``, raised by the schema script or a migration, says the store's shape is wrong. + """Whether ``exc``, raised by the schema script, a migration or the verify's read of the live + store, says the store's shape is wrong. Two tests, both needed. The code must be SQLite's generic ``SQLITE_ERROR``: a busy or locked file, a read-only file, an I/O error, a full disk and a corrupt file each carry their own primary @@ -421,8 +422,8 @@ async def run_schema_step[T]( path: object, counts_under_dek: bool | None, ) -> T: - """Await the schema script, the migrations or the verify's read, turning a shape failure into a - refusal, and return what the step returned. + """Await the schema script, the migrations or the verify's read of the live store, turning a + shape failure into a refusal, and return what the step returned. A failure :func:`is_schema_step_error` accepts is raised as :class:`SchemaMismatchError`, from the original so the driver's text stays in the chain (BACKLOG #2101). It carries the remedy a @@ -433,16 +434,22 @@ async def run_schema_step[T]( One shape failure gets another remedy: SQLite's re-check of the schema after an ``ALTER`` names the view or trigger it could not parse, as in "error in view V: no such module". This build creates neither kind, so that object is another tool's, and dropping it lets the - migration run past it (BACKLOG #6719).""" + migration run past it (BACKLOG #6719). A view under a name this build creates is not such an + object: it holds the place of a table or index, which is the incompatible store the plain + remedy names.""" try: return await step except Exception as exc: if not is_schema_step_error(exc): raise cause = str(exc) - if cause.startswith(_FOREIGN_OBJECT_PREFIXES): + foreign = await _foreign_object(cause) + if foreign is not None: + kind, name = foreign raise SchemaMismatchError( - f"store {path} {_REMEDY_FOREIGN} The schema step failed: {cause}.", cause=cause + f"store {path} holds a {kind} {name!r} this build did not create, which stops its" + f" upgrade: drop it, then restart. The schema step failed: {cause}.", + cause=cause, ) from exc if counts_under_dek is None: counts_under_dek = await _counts_under_a_dek(db) @@ -452,6 +459,27 @@ async def run_schema_step[T]( ) from exc +async def _foreign_object(cause: str) -> tuple[str, str] | None: + """The kind and name of another tool's view or trigger that ``cause`` names, else ``None``.""" + for kind in _FOREIGN_KINDS: + prefix = f"error in {kind} " + if cause.startswith(prefix): + name = cause[len(prefix) :].split(":", 1)[0] + if kind == "view" and name.lower() in await _names_this_build_creates(): + return None + return kind, name + return None + + +async def _names_this_build_creates() -> frozenset[str]: + """Every table and named index this build's SQLite schema and migrations create.""" + # Imported here, as _expected_shape imports from store.py: store.py imports this module. + from messagefoundry.store.store import _SCHEMA, MessageStore + + shape = await _expected_shape(_SCHEMA, MessageStore._migrate) + return frozenset(shape.columns) | frozenset(shape.named_indexes) + + async def _counts_under_a_dek(db: aiosqlite.Connection) -> bool: """Whether the live file records AES-GCM use but has no store salt: it was opened keyed, and only by a writer that seals under the DEK itself (ADR 0196). A cell-bound writer mints the salt diff --git a/tests/test_schema_verify_6719_6720.py b/tests/test_schema_verify_6719_6720.py index 4ce1eb12b8..8354ec51c4 100644 --- a/tests/test_schema_verify_6719_6720.py +++ b/tests/test_schema_verify_6719_6720.py @@ -15,6 +15,7 @@ from __future__ import annotations import sqlite3 +import traceback from collections.abc import AsyncIterator from contextlib import asynccontextmanager from pathlib import Path @@ -203,7 +204,7 @@ async def test_a_counted_store_whose_salt_is_a_readable_foreign_object_gets_the_ #: Every schema object with a flag saying whether it is a view or a trigger, so one walk both counts #: what it saw and finds those (a query for them alone returns nothing on the built schema, so it #: cannot show it ran). The flag is in the SQL, so the negative control below pins the same predicate. -_OBJECTS_FLAGGED_VIEW = "SELECT name, type IN ('view', 'trigger') FROM sqlite_master" +_OBJECTS_FLAGGED_VIEW_OR_TRIGGER = "SELECT name, type IN ('view', 'trigger') FROM sqlite_master" async def test_the_expected_shape_holds_no_virtual_table() -> None: @@ -215,7 +216,7 @@ async def test_the_expected_shape_holds_no_virtual_table() -> None: await MessageStore._migrate(db) async with db.execute(_TABLES_FLAGGED_VIRTUAL) as cur: tables = [tuple(r) for r in await cur.fetchall()] - async with db.execute(_OBJECTS_FLAGGED_VIEW) as cur: + async with db.execute(_OBJECTS_FLAGGED_VIEW_OR_TRIGGER) as cur: objects = [tuple(r) for r in await cur.fetchall()] # Positive control: the walk saw the built schema (40 tables when this floor was set), so the # absence below cannot pass on an empty walk. @@ -229,8 +230,8 @@ async def test_the_expected_shape_holds_no_virtual_table() -> None: # The reads skip views too, so a view this build created would never be verified either # (BACKLOG #6719 item 10). And the foreign-object remedy tells the operator to drop a view or a # trigger that stops an upgrade, which is safe only while this build creates neither. - views = [name for name, is_view in objects if is_view] - assert views == [] + views_or_triggers = [name for name, flagged in objects if flagged] + assert views_or_triggers == [] async def test_the_virtual_table_probe_finds_one_without_fts5(tmp_path: Path) -> None: @@ -247,10 +248,10 @@ async def test_the_virtual_table_probe_finds_one_without_fts5(tmp_path: Path) -> async with _connected(path) as db: async with db.execute(_TABLES_FLAGGED_VIRTUAL) as cur: rows = {r[0]: bool(r[1]) for r in await cur.fetchall()} - async with db.execute(_OBJECTS_FLAGGED_VIEW) as cur: - views = [name for name, is_view in await cur.fetchall() if is_view] + async with db.execute(_OBJECTS_FLAGGED_VIEW_OR_TRIGGER) as cur: + flagged = {name for name, is_one in await cur.fetchall() if is_one} assert rows == {"plain": False, "planted": True} - assert views == ["v", "tr"] + assert flagged == {"v", "tr"} async def test_a_planted_ordinary_table_with_rootpage_zero_is_not_skipped(tmp_path: Path) -> None: @@ -467,7 +468,7 @@ async def test_a_foreign_object_that_stops_a_migration_gets_the_drop_remedy( cause = info.value.cause assert cause is not None and cause.startswith(f"error in {kind} {name}: no such module"), cause text = str(info.value) - assert text.startswith(f"store {path} holds a view or trigger this build did not create"), text + assert text.startswith(f"store {path} holds a {kind} '{name}' this build did not create"), text assert "recreate" not in text and "NEW store key" not in text, text # The remedy is true: with that object dropped, the same migration runs and the open succeeds. _sql(path, drop) @@ -499,30 +500,73 @@ async def test_a_shape_error_from_the_verify_read_is_refused_with_the_remedy( text = str(info.value) assert text.startswith(f"store {path} is from an incompatible version; recreate it:"), text assert "The schema step failed: no such module" in text, text - assert isinstance(info.value.__cause__, sqlite3.OperationalError) + cause = info.value.__cause__ + assert isinstance(cause, sqlite3.OperationalError) + # The verify's read raised it, not the script or a migration. + frames = {f.name for f in traceback.extract_tb(cause.__traceback__)} + assert {"run_schema_step", "read_schema_shape"} <= frames, frames -async def test_a_read_error_that_is_not_a_shape_keeps_its_own_error( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - # Control: a read failure that recreating the store would not fix is not given the remedy. +def _real_sqlite_error(statement: str) -> sqlite3.OperationalError: + conn = sqlite3.connect(":memory:") + try: + with pytest.raises(sqlite3.OperationalError) as info: + conn.execute(statement) + finally: + conn.close() + return info.value + + +async def _verify_raising( + monkeypatch: pytest.MonkeyPatch, target: str, exc: sqlite3.OperationalError +) -> BaseException: + """``verify_live_schema`` with ``target`` raising ``exc``; returns what the verify raised.""" from messagefoundry.store import schema_verify - async def locked(*_args: object, **_kwargs: object) -> list[str]: - raise sqlite3.OperationalError("database is locked") + async def raising(*_args: object, **_kwargs: object) -> object: + raise exc - monkeypatch.setattr(schema_verify, "live_schema_differences", locked) + monkeypatch.setattr(schema_verify, target, raising) async with _connected(":memory:") as db: with pytest.raises(sqlite3.OperationalError) as info: await schema_verify.verify_live_schema( db, schema=_SCHEMA, migrate=MessageStore._migrate, - path="locked.db", + path="x.db", counts_under_dek=False, ) - assert not isinstance(info.value, SchemaMismatchError) - assert str(info.value) == "database is locked" + return info.value + + +async def test_a_read_error_that_is_not_a_shape_keeps_its_own_error( + monkeypatch: pytest.MonkeyPatch, +) -> None: + # Control: a real SQLITE_ERROR whose message names no shape is not given the remedy. + exc = _real_sqlite_error("SELEC 1") + assert exc.sqlite_errorcode & 0xFF == sqlite3.SQLITE_ERROR + assert await _verify_raising(monkeypatch, "read_schema_shape", exc) is exc + + +async def test_a_failure_building_the_expected_shape_keeps_its_own_error( + monkeypatch: pytest.MonkeyPatch, +) -> None: + # A shape message from this build's own scratch build is this build's defect, which recreating + # the store would not fix, so only the live read is classified. + exc = _real_sqlite_error("SELECT missing FROM sqlite_master") + assert is_schema_step_error(exc), str(exc) + assert await _verify_raising(monkeypatch, "_expected_shape", exc) is exc + + +async def test_a_view_under_a_name_this_build_creates_is_not_another_tools_object() -> None: + from messagefoundry.store.schema_verify import _foreign_object + + assert await _foreign_object("error in view vv: no such module: m") == ("view", "vv") + assert await _foreign_object("error in trigger tt: no such module: m") == ("trigger", "tt") + # A view that holds an expected table's or index's name is the incompatible store. + assert await _foreign_object("error in view users: no such module: m") is None + assert await _foreign_object("error in view IX_QUEUE_FIFO_IN_SEQ: no such module: m") is None + assert await _foreign_object("error in table users: no such module: m") is None # --- BACKLOG #6720 item 1: a foreign view using an unloaded function or collation ---------------- From a5182fe71db321530fea35b97738336454714b54 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sat, 21 Nov 2026 18:41:11 -0600 Subject: [PATCH 30/74] PR body leak scan: step 9 blank-line carry, one hedge list, emphasis and zero-width row edges BACKLOG #3364 (batch 455), steps 8, 9 and 11. Step 9: the loose column reading no longer carries an ASVS header's columns across a blank line once that header has had a data row. This is a deliberate drop against main: the headerless pipe block below such a blank line is no longer marked. A blank line above the first data row, and a quote-marker-only line anywhere, still end nothing, as on main. _PR_STEP9_DROPPED lists the dropped bodies; the superset guards excuse exactly those hits. Step 11: one hedge list (_PR_HEDGE) feeds _PR_AUX, the _PR_MODAL chain, the has-been form and _PR_QUALIFIER (#8175 item 6); underscore emphasis no longer hides the word that ends a modal's clause; a third reading of a body with invisible characters deletes them before line kinds are read, so a zero-width character before a row's first pipe no longer hides the row. Step 8: must-fire pins for escaped pipes in header and row. Differential against origin/main db77b29597f's scanner on 3126 engine PR bodies plus tracked Markdown: 715 hits each, 0 lost, 0 gained. Proposed PR title: The PR body leak scan ends a table's ASVS mark at a blank line, reads one hedge list, and sees through emphasis and zero-width row edges (BACKLOG #3364) Proposed ledger banner #3364: PARTIAL. Step 9 fixed with quiet controls (a deliberate, listed drop against main). Step 11's underscore, zero-width and hedge-vocabulary remainder caught with must-fire tests and quiet controls. Step 8 has added must-fire pins; its false positive still fires. Still open: step 3 proposal 1, step 10, and step 11's version-lead and verdict-tail word-boundary sites, which only quiet. --- scripts/security/scan_forbidden.py | 120 ++++++++++++++++++----------- tests/test_scan_forbidden.py | 97 +++++++++++++++++++---- 2 files changed, 158 insertions(+), 59 deletions(-) diff --git a/scripts/security/scan_forbidden.py b/scripts/security/scan_forbidden.py index c4226f602e..06a9e63c53 100644 --- a/scripts/security/scan_forbidden.py +++ b/scripts/security/scan_forbidden.py @@ -498,26 +498,29 @@ r"|(?:went|goes|moves?|moved) from)" ) _PR_PLAIN_STATE_VERB = rf"(?:{_PR_STRONG_VERB}|is(?: now| still)?|was|are|reads|now|at|from)" +#: The adverbs a record sentence hedges a verdict with, one list for each place one may stand: before +#: the verb (_PR_AUX), after a modal (_PR_MODAL), between "has" and "been", and before the verdict +#: (_PR_QUALIFIER). Lists kept apart drifted, so a word one place took unbound another (BACKLOG #8175 +#: item 6): " has likely been met", " is only partial", " never stays partial". +_PR_HEDGE = r"(?:likely|probably|still|now|also|only|then|already|so|never|yet|honestly|since)" +#: "has been" with an optional negation and any hedges between ("has since been", "hasn't yet been"). +_PR_HAS_BEEN = rf"(?:has|have|had)(?: not|n['\u2019]t)?(?: {_PR_HEDGE})* been" #: The passive and negated forms ("were", "has been", "isn't", "has not been", "is no longer") bind an #: unmarked identifier only with a state verdict ending its clause (_pr_verdict_bound). _PR_STATE_VERB = ( - rf"(?:{_PR_PLAIN_STATE_VERB}|were" - # A word may stand between "has" and "been" ("has since been met", "has never been met"). - r"|(?:(?:has|have|had)(?: not|n['\u2019]t)?(?: (?:since|still|now|yet|never|already))* )?been" + rf"(?:{_PR_PLAIN_STATE_VERB}|were|(?:{_PR_HAS_BEEN}|been)" r"|(?:is|was|are|were)(?:n['\u2019]t| not| no longer))" ) -_PR_PLAIN_QUALIFIER = r"(?:(?:a|an|the|its|permanent|genuine|accepted|honest)" + _PR_SEP + r")*" +_PR_PLAIN_QUALIFIER_WORDS = r"a|an|the|its|permanent|genuine|accepted|honest" +_PR_PLAIN_QUALIFIER = rf"(?:(?:{_PR_PLAIN_QUALIFIER_WORDS}){_PR_SEP})*" _PR_QUALIFIER = ( - r"(?:(?:a|an|the|its|permanent|genuine|accepted|honest|recorded|known|interim|provisional" - r"|likely|probably|still|already|never)" + _PR_SEP + r")*" + rf"(?:(?:{_PR_PLAIN_QUALIFIER_WORDS}|recorded|known|interim|provisional|{_PR_HEDGE}){_PR_SEP})*" ) #: Words that may stand between the identifier and its verb without unbinding it: a passive auxiliary -#: (" was held at partial"), a negated one (" isn't met") and the adverbs a record sentence -#: hedges with (" likely stays"). +#: (" was held at partial"), a negated one (" isn't met") and the hedges (" likely stays"). _PR_AUX = ( - r"(?:(?:is|was|are|were|be|been|(?:has|have|had)(?: not)? been|(?:has|have|had)n['\u2019]t been" - r"|(?:is|was|are|were)n['\u2019]t|not|no longer|likely|probably|still|now|also|only|then" - r"|already|so)" + _PR_SEP + r")*" + rf"(?:(?:is|was|are|were|be|been|{_PR_HAS_BEEN}" + rf"|(?:is|was|are|were)n['\u2019]t|not|no longer|{_PR_HEDGE})" + _PR_SEP + r")*" ) #: A modal or a negation bound to a bare verdict verb: " cannot pass", " would not be met", #: " needs to pass", " will remain partial". On an identifier the text does not mark as a @@ -526,8 +529,7 @@ _PR_MODAL = ( r"(?:can(?:not)?|can['\u2019]t|could|would|will|should|may|might|must|does|do|did" r"|(?:does|did|wo|would|could|should)n['\u2019]t|needs? to|has to|is (?:un)?able to)" - rf"(?:{_PR_SEP}(?:not|now|still|yet|never|only|honestly|also|then|reach|have|be|been|stay" - r"|remain|likely|probably))*" + rf"(?:{_PR_SEP}(?:not|{_PR_HEDGE}|reach|have|be|been|stay|remain))*" ) #: Read from the end of the identifier: " stays partial", " cell to pass", " | fail". _PR_VERDICT_AFTER = re.compile( @@ -555,7 +557,8 @@ #: preposition is not one: " will fail on the strict validator" is a verb and its phrase. _PR_VERDICT_END = re.compile( rf"(?i){_PR_FMT}(?:\s*(?:$|[.,;:!?)\]|])" - r"|\s+(?:yet|today|now|either|again|until|unless|because)\b)" + # Underscore emphasis on the word ("_yet_") does not hide it, as "\b" did. + rf"|\s+_{{0,2}}(?:yet|today|now|either|again|until|unless|because){_PR_EA})" ) #: A verb that states the verdict BEFORE the identifier: "does not meet ", "satisfies ASVS ", #: and the record's idiom for a requirement that does not pass yet, "an honest pass for ". "pass" @@ -609,8 +612,9 @@ #: one deleted, inside a word or a cell as well as around one, and keeps the hits of both readings. #: The deletion reaches the text the verdict, gap and map patterns read, not the line's kind: #: _pr_units decides a row, heading, list item or empty line from the line as written, so an -#: invisible character before a row's first pipe makes it a paragraph in both readings (an open -#: evasion). A fixed table, so an import pays nothing for it. +#: invisible character before a row's first pipe makes it a paragraph in both readings. A third +#: reading deletes them before the kinds are read (_pr_scan_reading). A fixed table, so an import +#: pays nothing for it. _PR_DEFAULT_IGNORABLE = ( (0x00AD, 0x00AD), (0x034F, 0x034F), @@ -798,8 +802,8 @@ #: time; those patterns backtrack on a long run, and tests/test_scan_forbidden.py keeps them as its #: oracles and pins the two functions equal to them. Do not #: tighten any of the three: a change to one is a change to the floor. The pass runs this module's -#: table model, whose loose reading keeps a table's ASVS columns wherever main kept them -#: (_pr_loose_columns). +#: table model, whose loose reading keeps a table's ASVS columns wherever main kept them but past a +#: blank line under a header that has had a data row (_pr_loose_columns). _PR_BASE_QUOTE = re.compile(r"(?:>\s?)+") #: The lookahead class of main's full-stop split. _PR_BASE_SPLIT_LOOKAHEAD = frozenset("ABCDEFGHIJKLMNOPQRSTUVWXYZ*`[(\"'#>-") @@ -1159,6 +1163,11 @@ def _pr_is_delimiter(row: str) -> bool: return "-" in row and set(row) <= _PR_TABLE_DELIMITER_CHARS +def _pr_between(found: list[int], above: int, below: int) -> bool: + """Whether a line number in ``found``, which is sorted, lies strictly between two lines.""" + return bisect.bisect_right(found, above) < bisect.bisect_left(found, below) + + def _pr_table_starts( units: _PrUnits, blanks: list[int], quote_blanks: list[int], quoted: set[int] ) -> list[bool]: @@ -1174,10 +1183,7 @@ def _pr_table_starts( else, a lone ">" between rows does not end the run, as main read no blank line at all. These runs bound only the GFM reading (_pr_table_columns), whose columns can only add marks; the - loose reading (_pr_loose_columns), which keeps every mark main kept, does not read them.""" - - def between(found: list[int], above: int, below: int) -> bool: - return bisect.bisect_right(found, above) < bisect.bisect_left(found, below) + loose reading (_pr_loose_columns) does not read them.""" starts = [] # Whether every row since the last unit that is not a row opens with a quote marker. @@ -1191,8 +1197,8 @@ def between(found: list[int], above: int, below: int) -> bool: and ( above is None or not above[2] - or between(blanks, above[0][0][1], line) - or (block_quoted and between(quote_blanks, above[0][0][1], line)) + or _pr_between(blanks, above[0][0][1], line) + or (block_quoted and _pr_between(quote_blanks, above[0][0][1], line)) ) ) return starts @@ -1245,24 +1251,29 @@ def _pr_table_columns(units: _PrUnits, starts: list[bool]) -> list[set[int]]: return columns -def _pr_loose_columns(units: _PrUnits) -> list[set[int]]: +def _pr_loose_columns(units: _PrUnits, blanks: list[int]) -> list[set[int]]: """For each unit, the ASVS columns as main read them, united with the GFM reading above: every - row above a dash-shaped unit is re-read as a header, and its cells are split at every pipe. Only - a unit that is not a row ends this reading, as on main, so a blank line or a quote-marker-only - line between rows ends nothing here and every mark main kept is kept. Step 9, which ended this - reading at such a line, was removed; the false positive it quieted stays open on BACKLOG #3364.""" + row above a dash-shaped unit is re-read as a header, and its cells are split at every pipe. + + A unit that is not a row ends this reading, as on main. So does a blank line (``blanks``, as + _pr_lines counts one) between two rows once the header has had a data row: the pipe lines below + it are another block, which the header above does not name (BACKLOG #3364 step 9). This is the + one place the reading drops a mark main kept. A blank line above the first data row, or a + quote-marker-only line anywhere, ends nothing, as on main: a header with no rows yet is read as + heading the rows below it.""" columns: list[set[int]] = [] current: set[int] = set() - for index, (_, text, is_row) in enumerate(units): - if not is_row: - current = set() - if ( - is_row - and not _pr_is_delimiter(text) - and index + 1 < len(units) - and _pr_is_delimiter(units[index + 1][1]) - ): - current = _pr_asvs_columns(text, loose=True) + # Whether a data row has been read under the current header. + has_rows = False + for index, (marks, text, is_row) in enumerate(units): + # A data row above implies the unit above is a row, as any other unit clears it. + if not is_row or (has_rows and _pr_between(blanks, units[index - 1][0][0][1], marks[0][1])): + current, has_rows = set(), False + if is_row and not _pr_is_delimiter(text): + if index + 1 < len(units) and _pr_is_delimiter(units[index + 1][1]): + current, has_rows = _pr_asvs_columns(text, loose=True), False + elif current: + has_rows = True columns.append(current) return columns @@ -1353,6 +1364,22 @@ def scan_pr_body(body: str) -> list[str]: return [f"pr-body:{line}: {PR_BODY_REASONS[kinds[kind]]}" for line, kind in sorted(found)] +def _pr_scan_units( + units: _PrUnits, + gfm: tuple[list[int], list[int], set[int]], + sentences: Callable[[str, bool], list[tuple[int, str]]], + kinds: frozenset[str], + found: set[tuple[int, int]], +) -> tuple[list[bool], list[set[int]], list[set[int]]]: + """Scan every unit with its own runs of rows and columns; return the runs and both columns.""" + starts = _pr_table_starts(units, *gfm) + asvs = _pr_table_columns(units, starts) + loose = _pr_loose_columns(units, gfm[0]) + for unit, unit_asvs, unit_loose in zip(units, asvs, loose, strict=True): + _pr_scan_unit(unit, unit_asvs, unit_loose, found, sentences, kinds) + return starts, asvs, loose + + def _pr_scan_reading( lines: list[str], gfm: tuple[list[int], list[int], set[int]], @@ -1366,11 +1393,7 @@ def _pr_scan_reading( sentences = _pr_base_sentences if reading == _PR_BASE else _pr_sentences # Both passes of a reading share the units' kinds and lines, so they share where each run of rows # starts. - starts = _pr_table_starts(units, *gfm) - asvs = _pr_table_columns(units, starts) - loose = _pr_loose_columns(units) - for unit, unit_asvs, unit_loose in zip(units, asvs, loose, strict=True): - _pr_scan_unit(unit, unit_asvs, unit_loose, found, sentences, kinds) + starts, asvs, loose = _pr_scan_units(units, gfm, sentences, kinds, found) # Where the body holds an invisible character, it is read again with each one deleted. A unit # whose text and columns that leaves unchanged reads the same, so only the others are scanned. if invisible: @@ -1378,7 +1401,7 @@ def _pr_scan_reading( for unit, unit_asvs, unit_loose, plain, plain_asvs, plain_loose in zip( deleted, _pr_table_columns(deleted, starts), - _pr_loose_columns(deleted), + _pr_loose_columns(deleted, gfm[0]), units, asvs, loose, @@ -1386,6 +1409,13 @@ def _pr_scan_reading( ): if unit[1] != plain[1] or unit_asvs != plain_asvs or unit_loose != plain_loose: _pr_scan_unit(unit, unit_asvs, unit_loose, found, sentences, kinds) + # The passes above read each line's kind as written, so an invisible character before a + # row's first pipe makes it a paragraph there. A third pass deletes every one before the + # kinds are read, so such a line is read as a row, with its own runs of rows. It only adds + # hits; where it builds the units the second pass built, it would add none. + regrouped = _pr_units([_PR_INVISIBLE.sub("", line) for line in lines], False, reading) + if regrouped != deleted: + _pr_scan_units(regrouped, gfm, sentences, kinds, found) def _pr_scan_unit( diff --git a/tests/test_scan_forbidden.py b/tests/test_scan_forbidden.py index 1399586dba..f21c9eb098 100644 --- a/tests/test_scan_forbidden.py +++ b/tests/test_scan_forbidden.py @@ -1236,14 +1236,8 @@ def test_a_header_row_marks_only_its_own_table_and_column(sf) -> None: ), ("9", "verdict", f"> | ASVS | Note | Result |\n>\n> |---|---|---|\n> {_ROW}"), ("9", "verdict", f"> {_HEAD.replace(chr(10), chr(10) + '> ')}\n> {_ROW}"), - # Step 9 is removed: a blank line, or a quote-marker-only line in a quoted table, between data - # rows ends nothing, so the header still marks the rows below it, as main reads it. The first - # body is the one step 9 quieted; its false positive stays open on BACKLOG #3364. - *( - ("9", "verdict", f"{_HEAD}| a | b | c |\n{blank}\n{_ROW}") - for blank in ("", " ", "\n", "\r") - ), - ("9", "verdict", f"{_HEAD}| a | b | c |\r\n\r\n{_ROW}"), + # Step 9 ends the header's mark only at a blank line under a data row (_PR_STEP9_DROPPED). A + # quote-marker-only line between quoted data rows ends nothing, as main reads it. *( ( "9", @@ -1317,7 +1311,73 @@ def test_a_header_row_marks_only_its_own_table_and_column(sf) -> None: # A marked identifier is never exempt. ("10", "verdict", f"ASVS {_REQ}: the row is not failing but stays {_PARTIAL}."), ("10", "verdict", f"| ASVS {_REQ} | the parser | is never failing; the cell is failing |"), + # Step 9's must-fire controls: a blank line ends a header's mark only under a data row. A dash + # placeholder is no data row, and a block below the blank line that marks its own id or has its + # own ASVS header still binds. + ("9", "verdict", f"{_HEAD}| - | - | - |\n\n{_ROW}"), + ( + "9", + "verdict", + f"{_HEAD}| a | b | c |\n\n| ASVS {_REQ} | the limb | {_PASS.title()} (12 messages) |", + ), + ("9", "verdict", f"{_HEAD}| a | b | c |\n\n{_HEAD}{_ROW}"), + # Step 8: an escaped pipe in the header and in the row, and an escaped backslash before a real + # pipe in the header. Main flags each too; these pin the columns. + ("8", "verdict", f"| a \\| b | ASVS | Note | Result |\n|---|---|---|---|\n| a \\| b {_ROW}"), + ("8", "verdict", f"| a \\\\| ASVS | Note | Result |\n|---|---|---|---|\n| x {_ROW}"), + # Step 11, the hedge vocabularies: one list (_PR_HEDGE) for every place a hedge stands. Each of + # these missed while the lists differed. + ("11", "verdict", f"ASVS {_REQ} has likely been {_MET}."), + ("11", "verdict", f"ASVS {_REQ} is only {_PARTIAL}."), + ("11", "verdict", f"ASVS {_REQ} is also {_PARTIAL}."), + ("11", "verdict", f"ASVS {_REQ} never stays {_PARTIAL}."), + ("11", "verdict", f"ASVS {_REQ} will already stay {_PARTIAL}."), + ("11", "verdict", f"ASVS {_REQ} honestly stays {_PARTIAL}."), + ("11", "verdict", f"ASVS {_REQ} will so stay {_PARTIAL}."), + # Step 11: underscore emphasis on the word that ends a modal's clause. + ("11", "verdict", f"{_REQ} cannot {_PASS} _yet_."), + ("11", "verdict", f"{_REQ} will {_FAIL} _today_."), + # Step 11: underscore emphasis on a cell's connective and on a list's "and". Main flags each + # through the markup-deleted reading of the cell; these pin it. + ("11", "verdict", f"| ASVS {_REQ} | the limb | {_PASS.title()} _until_ the fix |"), + ("11", "verdict", f"| {_REQ} _and_ {_REQ_B} | {_PARTIAL} |"), + # Step 11: a zero-width character before the first pipe of a data row, a delimiter row or a + # header row. + ("11", "verdict", f"{_HEAD}{chr(0x200B)}{_ROW}"), + ("11", "verdict", f"| ASVS | Note | Result |\n{chr(0x200B)}|---|---|---|\n{_ROW}"), + ("11", "verdict", f"{chr(0x200B)}{_HEAD}{_ROW}"), +] +#: Step 9 (BACKLOG #3364): a blank line under an ASVS table that has had a data row ends the table, so +#: the header no longer marks the headerless pipe block below it. Main flags each body at the line +#: given; head reports nothing. Each superset guard excuses exactly the (body, hit) pairs listed here +#: and no other, and the test below checks that each listed hit is really dropped. +_PR_STEP9_DROPPED: list[tuple[str, int]] = [ + *((f"{_HEAD}| a | b | c |\n{blank}\n{_ROW}", 5) for blank in ("", " ", "\r")), + (f"{_HEAD}| a | b | c |\n\n\n{_ROW}", 6), + (f"{_HEAD}| a | b | c |\r\n\r\n{_ROW}", 5), + # Two quotes a blank line separates. + (f"> {_HEAD.replace(chr(10), chr(10) + '> ')}| a | b | c |\n\n> {_ROW}", 5), ] + + +def _step9_excused(sf, body: str) -> set[str]: + """The hits the step 9 drop excuses in one body: none, unless it is listed above.""" + return { + f"pr-body:{line}: {sf.PR_BODY_REASONS['verdict']}" + for listed, line in _PR_STEP9_DROPPED + if listed == body + } + + +@pytest.mark.parametrize(("body", "line"), _PR_STEP9_DROPPED) +def test_a_blank_line_under_a_data_row_ends_the_asvs_header( + sf, sf_frozen_main, body: str, line: int +) -> None: + """Step 9's quiet control, and the exception it is: main flags exactly the listed hit.""" + assert sf_frozen_main.scan_pr_body(body) == sorted(_step9_excused(sf, body)), body + assert sf.scan_pr_body(body) == [], body + + #: The six bodies engine PR 2893's review named as false positives: CI prose and a component row about #: HL7 v2.5.1. Main flags each. Step 10, which an earlier head of this branch built to drop them, was #: removed, because it dropped a verdict only from a body exactly equal to one of the six, which no @@ -1502,6 +1562,13 @@ def test_a_header_row_marks_only_its_own_table_and_column(sf) -> None: ("11", f"| Version (not an ASVS id) | Note | Result |\n|---|---|---|\n{_ROW}"), ("11", f"| Version (not ASVS) | Note | Result |\n|---|---|---|\n{_ROW}"), ("11", f"| Not in ASVS | Note | Result |\n|---|---|---|\n{_ROW}"), + # Step 11: the same hedges beside a version, or before a CI verdict on an unmarked id; emphasis + # on a word that starts an object; a zero-width character before a row under a header that does + # not name ASVS. + ("11", f"Python 3.9.7 has likely been {_MET}."), + ("11", "The parser on 2.5.1 is only passing locally."), + ("11", f"{_REQ} will {_FAIL} _the_ handshake."), + ("11", f"| Version | Note | Result |\n|---|---|---|\n{chr(0x200B)}{_ROW}"), ] @@ -1605,6 +1672,7 @@ def _superset_bodies() -> dict[str, str]: for i, (s, body) in enumerate(_PR_FINDINGS_MUST_STAY_QUIET) } ) + bodies.update({f"step9-dropped-{i}": body for i, (body, _) in enumerate(_PR_STEP9_DROPPED)}) marked_head = "| x | ASVS | Note | Result |\n|---|---|---|---|\n" bodies.update( { @@ -1665,11 +1733,11 @@ def test_the_head_reports_every_hit_main_reports_in_a_constructed_body( sf, sf_frozen_main, name: str ) -> None: """BACKLOG #3364: on each constructed body, head reports every hit main reports, at main's line - number, with no exception. A finite set: it pins these bodies, and a loss on a body outside it - is not caught here.""" + number, excepting only the hits _PR_STEP9_DROPPED lists. A finite set: it pins these bodies, + and a loss on a body outside it is not caught here.""" body = _SUPERSET_BODIES[name] lost = set(sf_frozen_main.scan_pr_body(body)) - set(sf.scan_pr_body(body)) - assert not lost, (name, sorted(lost)) + assert not lost - _step9_excused(sf, body), (name, sorted(lost)) def test_the_head_reports_every_hit_main_reports_in_the_tracked_markdown( @@ -2815,8 +2883,9 @@ def _generated_pr_bodies(count: int = 600) -> list[str]: def test_the_scan_reports_at_least_every_hit_origin_main_reported(sf, sf_frozen_main) -> None: """The baseline is one pass of the union, but it runs the head's table model, so this is not true - by construction. The test pins it, with no exception, against two oracles: the pre-BACKLOG #5582 - reading rebuilt here, and the vendored origin/main scanner with #5582's readings.""" + by construction. The test pins it, excepting only the hits _PR_STEP9_DROPPED lists, against two + oracles: the pre-BACKLOG #5582 reading rebuilt here, and the vendored origin/main scanner with + #5582's readings.""" harvested = set(_harvested_pr_bodies()) fired_harvested = fired_generated = 0 for body in [*harvested, *_generated_pr_bodies()]: @@ -2826,7 +2895,7 @@ def test_the_scan_reports_at_least_every_hit_origin_main_reported(sf, sf_frozen_ fired_harvested += 1 else: fired_generated += 1 - missed = main_hits - set(sf.scan_pr_body(body)) + missed = main_hits - set(sf.scan_pr_body(body)) - _step9_excused(sf, body) assert not missed, (body, sorted(missed)) # Controls: the oracle fires on many fixtures and many generated bodies, or this proves nothing. assert fired_harvested > 100 and fired_generated > 100, (fired_harvested, fired_generated) From 8fb0d893367b91b9460db58b72f73d2830d73ef4 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sat, 21 Nov 2026 18:44:48 -0600 Subject: [PATCH 31/74] Revocation census: review round 2 fixes, the pin's limits stated once Vault BACKLOG #3512, steps 6 and 12, review round-7805d9bee5. The _EXEMPT_SITES comment now also states that a Guarded entry whose by is re-pointed at another guarded function is not caught; the floor comment points there rather than restating it. The pin test is one set comparison whose message lists every site on each side. The module docstring's second-hop warning covers Exempt functions too. Proposed PR title: Revocation census pins its exempt sites and floors its membership tests; crypto residual names the via-token limit (BACKLOG #3512) Proposed banner: PARTIAL - step 6 built (exempt pin, membership floors; the _GUARDS floor was already met, by engine PRs 2544 and 2586). Step 12 declined as a design choice (via-token granularity or a sign/verify split), limit recorded in the crypto_operations residual. --- tests/test_revocation_guard_census.py | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/tests/test_revocation_guard_census.py b/tests/test_revocation_guard_census.py index 3691aa4c4c..77bf508c08 100644 --- a/tests/test_revocation_guard_census.py +++ b/tests/test_revocation_guard_census.py @@ -24,7 +24,7 @@ or that a guard checks a CRL: the behaviour tests (at least ``tests/test_revocation_guard_remaining_hops.py``, ``tests/test_hop_refusal_revocation.py`` and ``tests/test_vault_revocation_hop_guard.py``) prove that. A second hop added inside a function that -is already guarded passes here too, so read the function in review. +is already listed, Guarded or Exempt, passes here too, so read the function in review. **It goes red.** Delete the guard call from one guarded site and :func:`test_every_guarded_site_calls_a_guard` fails naming that site; measured when this file was @@ -330,7 +330,9 @@ def __post_init__(self) -> None: #: The sites :data:`_CENSUS` lists as Exempt, pinned exactly (vault BACKLOG #3512). A Guarded hop #: moved to Exempt, with its guard call deleted, can pass every other check here (a relaxed hop #: fails its own census below), so this list is the second edit such a change needs. A diff that -#: edits both still passes, so review stays the check on what is added here. +#: edits both still passes, so review stays the check on what is added here. Nor is a Guarded +#: entry caught whose ``by`` is re-pointed at another function that calls a guard, in any module, +#: after its own guard call is deleted: that is one census edit, and only review sees it. _EXEMPT_SITES = frozenset( { "messagefoundry/apiclient/client.py::_build_verify_context", @@ -492,8 +494,8 @@ def test_every_guarded_site_calls_a_guard() -> None: guarded = {site: entry for site, entry in _CENSUS.items() if isinstance(entry, Guarded)} # 15 sites were Guarded when this floor was set, so 10 lets up to five retire with no edit here. # It is a floor against a census emptied or turned all Exempt, over which the check below would - # pass on nothing. A single hop moved from Guarded to Exempt fails the test below, unless - # _EXEMPT_SITES moves too; review is the check on that. + # pass on nothing. A single hop moved from Guarded to Exempt fails the test below; what that + # test does not catch is on _EXEMPT_SITES. assert len(guarded) >= 10, f"only {len(guarded)} Guarded census entries, floor 10" unguarded = [ f"{site} (guard expected in {entry.by or 'the site itself'}; {entry.note or 'no note'})" @@ -506,12 +508,11 @@ def test_every_guarded_site_calls_a_guard() -> None: def test_the_exempt_sites_are_the_pinned_list() -> None: """A Guarded hop moved to Exempt fails here, named, unless :data:`_EXEMPT_SITES` moves too.""" exempt = {site for site, entry in _CENSUS.items() if isinstance(entry, Exempt)} - assert sorted(exempt - _EXEMPT_SITES) == [], ( - "census sites Exempt but not in _EXEMPT_SITES. Add a site to it only once review has read " - "the exemption's reason; a hop moved here from Guarded loses its revocation guard" - ) - assert sorted(_EXEMPT_SITES - exempt) == [], ( - "_EXEMPT_SITES names sites the census does not exempt" + assert exempt == _EXEMPT_SITES, ( + f"Exempt in the census, not in _EXEMPT_SITES: {sorted(exempt - _EXEMPT_SITES)}; in " + f"_EXEMPT_SITES, not Exempt in the census: {sorted(_EXEMPT_SITES - exempt)}. Add a site to " + f"_EXEMPT_SITES only once review has read the exemption's reason; a hop moved there from " + f"Guarded loses its revocation guard" ) From edd329613add9a95ab7144c2a4c3adce2b3cb8b7 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sat, 21 Nov 2026 18:45:16 -0600 Subject: [PATCH 32/74] The escape check reads every character, so a raw U+2028 fails it _assert_escaped split its input with str.splitlines, which drops U+2028 as a line break, and json.loads accepts a raw U+2028, so output that left only that character raw passed both CLI tests. The check now asserts every character but a newline is printable ASCII, and the control proves output with only U+2028 raw fails it. The docstring says what the check does. From the unrepaired xhigh review of round-293d8649 on this branch. Vault BACKLOG #2891, PR 2390 note 3. This commit's banners supersede the earlier commits' on this branch. Proposed PR title: Batch 284: check-privileges --json escape tests; route-walk items already met Proposed banners: - #2891: PR 2390 note 3 met as the row's note 3 paragraph defines it: in the printed --json text, result and error, at least ESC, DEL, CSI, U+202E and U+2028 are escaped, under a test that fails without ensure_ascii. The decoded value still holds the characters, so a consumer that prints it must escape it. Open, unchanged: note 2 (and item 4, the terminal_text.py docstring tied to it) waits on an owner ruling; the other PR 2390 notes as the row records them. - #3177: added items 5 to 15 read met at engine main by PR 3015 (cd0a4a2f907), checked against the code and tests: 5, 6, 11, 12 fixed with tests; 7, 10, 13, 14, 15 fixed in docstrings and tests; 8 kept as the refusal (a mount cycle raises RecursionError, pinned by a test); 9 kept because a served app nests a handful of mounts and one walk per level keeps the refusal free of shared state. PR 3015's own open findings were left for the Lander to file under R2; where they landed is not checked here. --- tests/test_store_privilege_check.py | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/tests/test_store_privilege_check.py b/tests/test_store_privilege_check.py index 5ec9b438bf..ba9890ec36 100644 --- a/tests/test_store_privilege_check.py +++ b/tests/test_store_privilege_check.py @@ -638,16 +638,24 @@ def test_cli_json_reports_every_family_and_no_secret( def _assert_escaped(out: str) -> None: - """Every line of ``out`` is printable ASCII. With the caller's check that ``out`` decodes back - to :data:`_HOSTILE`, that proves each of its characters was written as an escape.""" - raw = [line for line in out.splitlines() if not (line.isascii() and line.isprintable())] + """``out`` is ASCII, and every character in it but a newline is printable. ``str.splitlines`` + would drop U+2028 as a line break, so the check splits on nothing. With the caller's check + that ``out`` decodes back to :data:`_HOSTILE`, that proves each of its characters was written + as an escape.""" + raw = [ch for ch in out if ch != chr(10) and not (ch.isascii() and ch.isprintable())] assert not raw, f"--json output carries a raw character: {out!r}" def test_the_escape_assertion_fails_on_unescaped_json() -> None: - """The control for :func:`_assert_escaped`: output written without ``ensure_ascii`` fails it.""" + """The control for :func:`_assert_escaped`: output written without ``ensure_ascii`` fails it, + and so does output that leaves only U+2028 raw, which ``json.loads`` accepts.""" with pytest.raises(AssertionError, match="carries a raw character"): _assert_escaped(json.dumps({"error": _HOSTILE}, ensure_ascii=False)) + escaped_ls, raw_ls = chr(92) + "u2028", chr(0x2028) + only_line_separator_raw = json.dumps({"error": _HOSTILE}).replace(escaped_ls, raw_ls) + assert json.loads(only_line_separator_raw) == {"error": _HOSTILE} + with pytest.raises(AssertionError, match="carries a raw character"): + _assert_escaped(only_line_separator_raw) _assert_escaped(json.dumps({"error": _HOSTILE}, indent=2)) From 4bdacdd047d7aa9a863a1e89cffa6447f96bef32 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sat, 21 Nov 2026 18:48:01 -0600 Subject: [PATCH 33/74] Server schema check: repair review round 1 findings BACKLOG #5062, #4942. From review round e533316077 on 86e6bed3d59: a column rename now moves an opaque index's word, so a later DROP COLUMN of the new name still raises; an opaque index's predicate is read to its statement end, quote-aware, rather than to the first ';' or the text's end; a DROP COLUMN of a key column of an INCLUDE index drops the index; a NOT NULL table constraint with a quoted name raises; a key that opens with a cast of a column raises in its qualified and parenthesised forms; ON [PRIMARY] no longer lets the next statement's UPDATE read as a foreign key action; ADD COLUMN takes a data-statement word as the column's name; a PostgreSQL column named index is a column; USING INDEX inside a literal is text; ALTER/DROP SEQUENCE, SCHEMA, TYPE and DATABASE end a clause; the second-create message no longer claims a guard skipped it; the test module docstring names its controls; the #4942 test closes its store if a precondition fails. Proposed PR title: Server schema check reads or refuses the DDL forms it misread; pin the keyless-chain serve-before-rotate-key stamp (BACKLOG #5062, #4942) Proposed banners: #5062 PARTIAL: items 3, 4 and 5 built except as left below; item 1 partly (DROP COLUMN over an opaque index, legacy DROP INDEX table.index, PRIMARY KEY in a CHECK literal, second CREATE TABLE, Postgres 18 NOT NULL built); item 2 partly (DATABASE_DEFAULT and CATALOG_DEFAULT, bracket-aware scanners, the default docstring premise built). Remains: skip_tables built from taken, an unguarded ALTER COLUMN, DDL in a literal no EXEC runs, EXEC-string cut clauses, ADD PRIMARY KEY against SET NOT NULL, cross-type default opclass, the first parse on the event loop, multi-token DEFAULT messages, scratch-schema altitude, the lower-cased refusal, item 6, item 7's postgres.py rollback finding, the dead label branch, and test_store_schema_hash's cannot-fail assertion. #4942 PARTIAL: the open_store hook does not cover a serve start before any rotate-key run on a keyless chain; it still stamps, pinned by a test. Step 1's decision (warning alone, or refuse or hold) is the owner's. --- messagefoundry/store/server_schema_verify.py | 81 ++++++++------ tests/test_rotate_key_rotation_record.py | 24 +++-- tests/test_server_schema_verify_5062.py | 106 ++++++++++++++++++- 3 files changed, 169 insertions(+), 42 deletions(-) diff --git a/messagefoundry/store/server_schema_verify.py b/messagefoundry/store/server_schema_verify.py index 62c9aec59f..2dce948190 100644 --- a/messagefoundry/store/server_schema_verify.py +++ b/messagefoundry/store/server_schema_verify.py @@ -42,9 +42,9 @@ not match, an ``ALTER TABLE`` with more than one clause or an action it does not know, a table rename, an ``ALTER INDEX``, a second ``CREATE TABLE`` of a table no ``DROP`` removed, a ``USING`` access method, a key column or expression carrying a collation, an operator class or a ``NULLS`` order, a key -that only casts a column, a key built ``USING INDEX``, a SQL Server inline ``INDEX``, a ``NOT NULL`` -table constraint, a ``DROP COLUMN`` of a column an expression, ``INCLUDE`` or predicate of an -index on its table may name, a column type or clause it does not know, a SQL Server column that +that opens with a cast of a column, a key built ``USING INDEX``, a SQL Server inline ``INDEX``, a +``NOT NULL`` table constraint, a ``DROP COLUMN`` of a column an expression, ``INCLUDE`` or predicate +of an index on its table may name, other than one of its key columns, a column type or clause it does not know, a SQL Server column that leaves its nullability to the session, ``COLLATE CATALOG_DEFAULT``, and a ``--`` or ``/*`` inside a quoted string, which may be dynamic SQL's comment or a literal's text. A unit test reads each shipped batch, so a new form fails there before it reaches an open. Not every misread raises: at least DDL @@ -181,12 +181,11 @@ #: PostgreSQL's ``PRIMARY KEY`` or ``UNIQUE`` ``USING INDEX ``, which turns an existing index #: into the constraint. ``USING INDEX TABLESPACE`` is only a storage option. _USING_INDEX = re.compile(r"\bUSING\s+INDEX\s+(?!TABLESPACE\b)", re.I) -#: A key that is only a cast of a column, ``a::text`` or ``CAST(a AS text)``. PostgreSQL stores a -#: cast to the column's own type as the column, and any other as an expression, and the reader does -#: not know which. -_CAST_TYPE = r"\w[\w ]*?(?:\s*\(\s*\d+(?:\s*,\s*\d+)?\s*\))?(?:\s*\[\])?" +#: A key that opens with a cast of a column, ``a::text`` or ``CAST(a AS text)``. PostgreSQL stores +#: a cast to the column's own type as the column, and any other as an expression, and the reader +#: does not know which. _CAST_KEY = re.compile( - rf'^(?:"[^"]+"|\w+)\s*::\s*{_CAST_TYPE}$|^CAST\s*\(\s*(?:"[^"]+"|\w+)\s+AS\s+{_CAST_TYPE}\s*\)$', + r'^(?:\(\s*)*(?:"[^"]+"|\w+)(?:\s*\))*\s*::|^CAST\s*\(\s*\(*\s*(?:"[^"]+"|\w+)\s*\)*\s+AS\b', re.I, ) _PLAIN_KEY = re.compile(r'^(\[?[A-Za-z_][\w$]*\]?|"[^"]+")(?:\s+(ASC|DESC))?$', re.I) @@ -205,7 +204,9 @@ #: as its own). _DATA_STATEMENT = frozenset({"insert", "update", "delete", "merge", "select", "truncate"}) #: What an ``ALTER`` or ``DROP`` that starts the next statement names, after the word itself. -_DDL_OBJECT = re.compile(r"\s+(?:TABLE|INDEX|VIEW|PROC|PROCEDURE|TRIGGER|FUNCTION)\b", re.I) +_DDL_OBJECT = re.compile( + r"\s+(?:TABLE|INDEX|VIEW|PROC|PROCEDURE|TRIGGER|FUNCTION|SEQUENCE|SCHEMA|TYPE|DATABASE)\b", re.I +) _TOKEN = re.compile(r"""N?'(?:[^']|'')*'|"[^"]*"|\[[^\]]*\]|\w+|\S""") @@ -338,7 +339,8 @@ def _string_spans(text: str) -> list[tuple[int, int]]: def _quoted_end(text: str, i: int) -> int | None: """The index after the quoted run that opens at ``text[i]``: a ``'`` string, a ``"`` name or a SQL Server ``[...]`` name, in which a doubled close continues the run. ``None`` when ``text[i]`` - opens none. The scanners below share it, so a ``[a,b]`` or ``[end]`` reads as one name in each.""" + opens none. :func:`_balanced`, :func:`_top_level_items` and :func:`_clause` share it, so a + ``[a,b]`` or ``[end]`` reads as one name in each.""" ch = text[i] if ch not in "'\"[": return None @@ -408,7 +410,7 @@ def _clause(segment: str) -> str: depth, i, n, prev = 0, 0, len(segment), "" while i < n: if (end := _quoted_end(segment, i)) is not None: - i = end + i, prev = end, "" continue ch = segment[i] if ch == "(": @@ -433,10 +435,11 @@ def _clause(segment: str) -> str: ): break # A data or DDL statement starts here too. ON DELETE and ON UPDATE are a foreign - # key's actions; ALTER COLUMN and DROP COLUMN are the clause's own verbs. + # key's actions, and the word after ADD [COLUMN] [IF NOT EXISTS] is a column's + # name; ALTER COLUMN and DROP COLUMN are the clause's own verbs. if ( lower == "create" - or (lower in _DATA_STATEMENT and prev != "on") + or (lower in _DATA_STATEMENT and prev not in ("on", "add", "column", "exists")) or (lower in ("alter", "drop") and _DDL_OBJECT.match(after)) ): break @@ -824,30 +827,34 @@ def altered(self, change: Callable[[ColumnShape], ColumnShape]) -> None: def _pk_columns(text: str) -> set[str]: """The columns of a ``PRIMARY KEY (...)`` in ``text``, a table item or an ``ADD CONSTRAINT``.""" - if _USING_INDEX.search(text): - raise ValueError(f"a key built from an existing index is not compared: {text[:120]!r}") - # A string literal's text, as in a CHECK, is blanked first, so a PRIMARY KEY inside one is not - # taken for the item's own. - blanked = text + # A string literal's text, as in a CHECK, is blanked first, so a PRIMARY KEY or USING INDEX + # inside one is not taken for the item's own. + parts: list[str] = [] + last = 0 for start, end in _string_spans(text): - blanked = blanked[:start] + "'" + " " * (end - start - 2) + "'" + blanked[end:] + parts += [text[last : start + 1], " " * (end - start - 2)] + last = end - 1 + blanked = "".join([*parts, text[last:]]) + if _USING_INDEX.search(blanked): + raise ValueError(f"a key built from an existing index is not compared: {text[:120]!r}") if (pk := _TABLE_PRIMARY_KEY.search(blanked)) is None: return set() inner, _ = _balanced(text, pk.end()) return {_bare(_TOKEN.findall(k)[0]) for k in _top_level_items(inner)} -def _is_constraint(item: str) -> bool: +def _is_constraint(item: str, dialect: Dialect | None) -> bool: """Whether a table item, or what follows an ``ADD`` without ``COLUMN``, is a constraint rather than a column. A SQL Server inline ``INDEX`` raises, because it builds a named index the reader - does not model, and so do ``PERIOD`` and ``EXCLUDE`` when what follows is not their constraint's + does not model, except on PostgreSQL, where ``index`` is a column's name, and so do + ``PERIOD`` and ``EXCLUDE`` when what follows is not their constraint's own shape, because each may also be a column's name. A ``NOT NULL`` table constraint raises: the reader does not apply it.""" - if re.match(r"(?:CONSTRAINT\s+\S+\s+)?NOT\s+NULL\b", item, re.I): + if re.match(r'(?:CONSTRAINT\s+(?:"[^"]*"|\[[^\]]*\]|\w+)\s+)?NOT\s+NULL\b', item, re.I): # PostgreSQL 18's NOT NULL table constraint, perhaps NOT VALID. raise ValueError(f"a not-null constraint is not compared: {item[:120]!r}") words = [w.lower() for w in _TOKEN.findall(item)[:2]] + [""] - if words[0] not in _NOT_A_COLUMN: + if words[0] not in _NOT_A_COLUMN or (words[0] == "index" and dialect == "postgres"): return False if words[0] == "index": raise ValueError(f"an inline index the live-schema check does not compare: {item[:120]!r}") @@ -879,14 +886,17 @@ def table(self, text: str, m: re.Match[str]) -> None: table = _bare(m["name"]) if table in self.created: # A guarded second CREATE TABLE never runs: the first one built the table. - raise ValueError(f"a second create table of {table}, which its guard skips") + raise ValueError( + f"a second create table of {table}: its guard skips it, or it names a table of" + " another schema, which the reader does not tell apart" + ) self.created.add(table) cols = self.columns.setdefault(table, {}) keys: set[str] = set() pending: list[tuple[str, _Column, str]] = [] for item in _top_level_items(body): first = _TOKEN.findall(item)[0] - if _is_constraint(item): + if _is_constraint(item, self.dialect): keys |= _pk_columns(item) elif self.dialect is None: cols.setdefault(_bare(first), _Built()) @@ -923,9 +933,13 @@ def index(self, text: str, m: re.Match[str]) -> None: self.indexes[name] = shape self.opaque.pop(name, None) if include or shape.partial or any(k.startswith("") for k in shape.columns): - # To the statement's end: a predicate has no closing mark of its own. - stop = text.find(";", end) - definition = text[m.end() : len(text) if stop < 0 else stop] + # To the statement's end, found as an ALTER clause's is: a predicate has no + # closing mark of its own. + try: + tail = _clause(text[end:]) + except ValueError: # a top-level comma: read on to the end, which only raises more + tail = text[end:] + definition = text[m.end() : end] + " " + tail self.opaque[name] = frozenset(_ident(w) for w in _TOKEN.findall(definition)) def _built(self, table: str, name: str, action: str) -> _Built: @@ -952,7 +966,7 @@ def alter(self, text: str, m: re.Match[str], spans: list[tuple[int, int]]) -> No if not rest: raise ValueError(f"an add with nothing to add: {clause!r}") # After ADD COLUMN what follows is a column, whatever its name (BACKLOG #5062). - if not head.group(1) and _is_constraint(rest): + if not head.group(1) and _is_constraint(rest, self.dialect): for key in _pk_columns(rest): self._not_null(table, key) return @@ -968,7 +982,11 @@ def alter(self, text: str, m: re.Match[str], spans: list[tuple[int, int]]) -> No name = re.sub(r"^DROP\s+COLUMN\s+(?:IF\s+EXISTS\s+)?", "", clause, flags=re.I) column = _bare(_TOKEN.findall(name)[0]) for index, used in self.opaque.items(): - if index in self.indexes and self.indexes[index].table == table and column in used: + shape = self.indexes.get(index) + if shape is None or shape.table != table or column not in used: + continue + if column not in (k.split(" ", 1)[0] for k in shape.columns): + # A key column takes the index with it, as _rewrite_keys below does. raise ValueError( f"a drop column of {table}.{column}, which index {index}'s expression," " INCLUDE or predicate may use, so the reader cannot tell whether it goes" @@ -1055,6 +1073,9 @@ def _rename(self, table: str, old: str, new: str) -> None: if moved is not None: built.later |= moved.ways() self._rewrite_keys(table, old, new) + for index, used in list(self.opaque.items()): + if old in used and index in self.indexes and self.indexes[index].table == table: + self.opaque[index] = (used - {old}) | {new} def rename(self, m: re.Match[str]) -> None: if m["old"].count(".") != 1: diff --git a/tests/test_rotate_key_rotation_record.py b/tests/test_rotate_key_rotation_record.py index ceac37b7be..21ae9328e3 100644 --- a/tests/test_rotate_key_rotation_record.py +++ b/tests/test_rotate_key_rotation_record.py @@ -948,8 +948,8 @@ async def test_engine_start_before_any_run_on_a_store_with_no_keyed_chain_still_ ) -> None: """BACKLOG #4942's remainder, as the code stands. A ``serve`` start on a new key before any ``rotate-key`` run, on a store with no keyed audit chain: the store is opened through - ``open_store`` as ``serve`` opens it, with no ``before_first_write`` hook (only ``rotate-key`` - passes one, BACKLOG #4936), and a real ``Engine.start`` runs the reconcile. Nothing tells this + ``open_store`` with no ``before_first_write`` hook, as ``serve`` passes none (only + ``rotate-key`` passes one, BACKLOG #4936), and a real ``Engine.start`` runs the reconcile. Nothing tells this start from a key changed by hand after a run, so it stamps the new key and opens no record. Whether this order is to be refused or held, or left to the warning, is the row's open decision; this test pins what the code does until it is made.""" @@ -963,14 +963,18 @@ async def test_engine_start_before_any_run_on_a_store_with_no_keyed_chain_still_ StoreSettings(path=str(db), encryption_key=key_b, encryption_keys_retired=key_a), keyless_chain_refusal=None, ) - assert isinstance(store, MessageStore) - assert audit_chain_rolled(store) is None # no keyed chain to answer from - engine = Engine( - store, - secret_rotation_settings=SecretRotationSettings(), - security_enforcement=SecurityEnforcement.WARN, - egress_settings=EgressSettings(deny_by_default=False), - ) + try: + assert isinstance(store, MessageStore) + assert audit_chain_rolled(store) is None # no keyed chain to answer from + engine = Engine( + store, + secret_rotation_settings=SecretRotationSettings(), + security_enforcement=SecurityEnforcement.WARN, + egress_settings=EgressSettings(deny_by_default=False), + ) + except BaseException: + await store.close() # engine.stop() closes it otherwise + raise try: await engine.start() rows = await store.get_secret_rotation_meta() diff --git a/tests/test_server_schema_verify_5062.py b/tests/test_server_schema_verify_5062.py index f3731a67b1..d89a2f65ce 100644 --- a/tests/test_server_schema_verify_5062.py +++ b/tests/test_server_schema_verify_5062.py @@ -2,8 +2,8 @@ # Copyright (C) 2026 MessageFoundry Foundation, LLC and contributors """BACKLOG #5062: DDL forms the server-DB live schema check misread without raising. -Each test here failed before its fix: the reader either built a wrong expected shape or let a form -it cannot place through. A form the reader cannot place now raises ``ValueError``, which the unit +Each test of a fix failed before it: the reader either built a wrong expected shape or let a form it +cannot place through. The rest are controls that pin what the fixes must not change. A form the reader cannot place now raises ``ValueError``, which the unit test that reads each shipped batch would surface before an open does. The shipped batches' own expected shapes are pinned by ``tests/test_sqlserver_postgres_schema_verify_1720.py``. """ @@ -253,3 +253,105 @@ def test_the_postgres_expected_shape_holds_no_table_the_migration_drops() -> Non "messagefoundry.store.postgres", reason="requires the postgres extra (asyncpg)" ) assert "lane_leases" not in postgres._declared_schema().columns + + +# --- review round 1 ------------------------------------------------------------------------------ + + +def test_a_drop_column_after_a_rename_still_sees_the_opaque_index() -> None: + with pytest.raises(ValueError, match="drop column"): + declared_schema( + ( + "CREATE TABLE t (a INT, b INT)", + "CREATE INDEX ix ON t (lower(b))", + "ALTER TABLE t RENAME COLUMN b TO c", + "ALTER TABLE t DROP COLUMN c", + ) + ) + + +def test_a_drop_column_reads_the_predicate_to_its_statement_end_only() -> None: + with pytest.raises(ValueError, match="drop column"): + declared_schema( + ( + "CREATE TABLE t (a INT, b TEXT, c INT)", + "CREATE INDEX ix ON t (a) WHERE b <> ';' AND c IS NULL", + "ALTER TABLE t DROP COLUMN c", + ) + ) + shape = declared_schema( + ( + "CREATE TABLE t (a INT NULL, b INT NULL, c INT NULL)" + " CREATE INDEX ix ON t (a) WHERE b > 0 ALTER TABLE t DROP COLUMN c", + ), + "sqlserver", + ) + assert "ix" in shape.named_indexes + + +def test_a_drop_of_an_include_index_key_column_drops_the_index() -> None: + shape = declared_schema( + ( + "CREATE TABLE t (a INT, b INT)", + "CREATE INDEX ix ON t (a) INCLUDE (b)", + "ALTER TABLE t DROP COLUMN a", + ) + ) + assert "ix" not in shape.named_indexes + + +@pytest.mark.parametrize("item", ['CONSTRAINT "nn a" NOT NULL a', "CONSTRAINT [nn a] NOT NULL a"]) +def test_a_not_null_constraint_with_a_quoted_name_raises(item: str) -> None: + with pytest.raises(ValueError, match="not-null constraint"): + declared_schema((f"CREATE TABLE t (a INT, {item})",), "postgres") + + +@pytest.mark.parametrize( + "key", ["((a)::text)", "(a::pg_catalog.text)", '(a::"text")', "(CAST(a AS pg_catalog.text))"] +) +def test_a_key_that_opens_with_a_cast_raises(key: str) -> None: + with pytest.raises(ValueError, match="cast"): + declared_schema((f"CREATE INDEX ix ON t ({key})",)) + + +def test_a_bracketed_filegroup_does_not_hide_the_next_statement() -> None: + shape = declared_schema( + ( + "CREATE TABLE a (x INT NOT NULL)", + "CREATE TABLE b (y INT NULL, z INT NULL)", + "IF 1 = 1 ALTER TABLE a ADD CONSTRAINT pk_a PRIMARY KEY (x) ON [PRIMARY]\n" + "UPDATE b SET z = 1, y = 2", + ), + "sqlserver", + ) + assert shape.column_shapes["a"]["x"].nullable is False + + +@pytest.mark.parametrize("name", ["delete", "update", "insert", "merge", "truncate", "select"]) +def test_add_column_takes_a_data_statement_word_as_the_name(name: str) -> None: + shape = declared_schema( + ("CREATE TABLE t (a INT)", f"ALTER TABLE t ADD COLUMN {name} TEXT"), "postgres" + ) + assert name in shape.columns["t"] + + +def test_a_postgres_column_named_index_is_a_column() -> None: + shape = declared_schema(("CREATE TABLE t (index TEXT, a INT)",), "postgres") + assert shape.columns["t"] == frozenset({"index", "a"}) + + +def test_using_index_inside_a_check_literal_is_text() -> None: + shape = declared_schema(("CREATE TABLE t (a TEXT, CHECK (a <> 'USING INDEX x'))",), "postgres") + assert shape.columns["t"] == frozenset({"a"}) + + +def test_an_unterminated_add_ends_at_an_alter_database() -> None: + shape = declared_schema( + ( + "CREATE TABLE a (x INT NULL)", + "IF 1 = 1 ALTER TABLE a ADD c INT NULL\n" + "ALTER DATABASE CURRENT SET READ_COMMITTED_SNAPSHOT ON", + ), + "sqlserver", + ) + assert shape.column_shapes["a"]["c"].nullable is True From c5e3bb75ff0fb99d038178461337cecdc4e1b22e Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sat, 21 Nov 2026 18:50:23 -0600 Subject: [PATCH 34/74] Round 2 review fixes for the route-body refusal rows Narrow the _recorded_decision docstring to the two helpers that record a route-body refusal, and make the failed-write test prove the gate admitted the request before the route body refused it. BACKLOG #1197 (ASVS 16.3.2). Proposed PR title: Route-body step-up refusals write an audit row (BACKLOG #1197) Proposed ledger banner for #1197: PARTIAL, stays open. Steps 1 and 2 of the 2026-11-06 added steps are built: the refusals of spend_step_up_action (purge, reload, export, edit-resend, the four group-wide saves) and refuse_unless_step_up_window_live write auth.gate_refused after the gate's grant row, with tests. Still open: steps 3 to 6 (_admit_reveal's refusals, enforce_phi_read_pacing in a route body, the WebSocket cap after authorize_ws, the docs/SECURITY.md require_ui restatement and its step-up example sentence), console grant parity, and the refusals PR 2808 findings 1 and 5 name. --- messagefoundry/api/security.py | 6 ++++-- tests/test_derived_gate_decision_audit.py | 1 + 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/messagefoundry/api/security.py b/messagefoundry/api/security.py index 26787c97c7..f397d3e1c9 100644 --- a/messagefoundry/api/security.py +++ b/messagefoundry/api/security.py @@ -1482,8 +1482,10 @@ async def _recorded_decision( A refusal row is written exactly where the grant row would have been, so a gate writes at most one decision row per request, and a gate that wrote no grant row writes no refusal row either. That keeps the per-request volume where the shipped trail already put it while the audit chain - has no drain (BACKLOG #1421). A step-up refusal a route body makes after its gate has admitted - the request adds a second row, through :func:`_record_route_refusal`. The reason comes from the + has no drain (BACKLOG #1421). The step-up refusals of :func:`spend_step_up_action` and + :func:`refuse_unless_step_up_window_live`, made in a route body after a ``proof_in_route`` gate + admitted the request, add a second row through :func:`_record_route_refusal`; other refusals a + route body makes, at least the reveal and pacing ones, write none. The reason comes from the :class:`_GateRefusal` the check raised. Any other exception leaves the block with no decision row from it, which is right for the :func:`_mfa_refusal` 403: it wrote its own ``auth.mfa_denied`` row where it was raised. A failed refusal-row write raises in place of the diff --git a/tests/test_derived_gate_decision_audit.py b/tests/test_derived_gate_decision_audit.py index 7c3f91efb8..e99abd1580 100644 --- a/tests/test_derived_gate_decision_audit.py +++ b/tests/test_derived_gate_decision_audit.py @@ -544,6 +544,7 @@ async def broken(*_: object, **__: object) -> None: r = await c.post(_PROBE, headers={"Authorization": f"Bearer {token}"}) assert r.status_code == 500, r.text assert attempts == ["audit_gate_refused"], "the 500 must come from the refusal-row write" + assert await _decisions(engine) == [_GRANT_ROW], "the gate admitted it; the route body refused" assert ran == [] From 22e613f4bffebd0c96a8f6b5b32b542a08b8f89a Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sat, 21 Nov 2026 18:50:26 -0600 Subject: [PATCH 35/74] Revert the IDE step-up re-proof tracking Reverts the ide/ changes of 8a46f828e44, df8a8bd9532 and 8053acb15f6 and the changelog fragment, so ide/ matches origin/main. Tracking the re-proof made every peekToken caller wait behind it, and a re-proof queued behind a sign-in sent the password on a dead token. The finding stays open. Vault BACKLOG #2950. --- changelog.d/2950-ide-reauth-tracked.fixed.md | 5 -- ide/src/auth.ts | 18 +++--- ide/src/signInSession.ts | 56 ++++--------------- ide/src/stepUp.ts | 4 +- ide/src/test/suite/sign-in-supersedes.test.ts | 44 +-------------- 5 files changed, 20 insertions(+), 107 deletions(-) delete mode 100644 changelog.d/2950-ide-reauth-tracked.fixed.md diff --git a/changelog.d/2950-ide-reauth-tracked.fixed.md b/changelog.d/2950-ide-reauth-tracked.fixed.md deleted file mode 100644 index 237f4e3c5d..0000000000 --- a/changelog.d/2950-ide-reauth-tracked.fixed.md +++ /dev/null @@ -1,5 +0,0 @@ -- **The IDE's step-up re-proof is now tracked like a sign-in.** `/me/reauth` rotates the session - token, but a cache reader did not wait for it and a sign-in started meanwhile did not either, so - the sign-in could name the token the re-proof had just ended and the re-proof's late store could - then overwrite the sign-in's newer token. Both now wait for the re-proof in that VS Code window. - (`vault BACKLOG #2950`) diff --git a/ide/src/auth.ts b/ide/src/auth.ts index 2c482a3ce0..e39ffd42aa 100644 --- a/ide/src/auth.ts +++ b/ide/src/auth.ts @@ -8,7 +8,7 @@ import * as vscode from "vscode"; import { getJson, HttpError, postJson } from "./engineClient"; import { mustChangeProblem } from "./engineStatusModel"; import { assertBrowsableUrl, assertTargetAllowed, targetRefusalNotice } from "./engineTarget"; -import { SIGN_IN_TIMEOUT_MS, reproveTracked, signInSettled, signInSuperseding } from "./signInSession"; +import { SIGN_IN_TIMEOUT_MS, signInSettled, signInSuperseding } from "./signInSession"; import { type StepUpHost, withStepUp } from "./stepUp"; const SECRET_PREFIX = "messagefoundry.token:"; @@ -371,15 +371,11 @@ export async function withStepUpAuth( // It rotates the token and queues behind the account's re-proof lock, as the sign-in does, // so it gets the sign-in's timeout (vault BACKLOG #2950), named here rather than left to // postJson's default so the two cannot drift apart. - // Tracked in signInSession.ts as a sign-in is, and it stores the rotated token there, so in - // this window peekToken and a later sign-in wait for it; reproveTracked says when its store - // can still overwrite a newer sign-in's token. + // Unlike a sign-in it is not tracked in signInSession.ts, so peekToken does not wait for it. // A timeout after the engine finished leaves the cached token dead, as a lost sign-in reply // does: the next call gets a 401 and signs in again. - return await reproveTracked(ctx.secrets, secretKey(url), async () => { - const reply = await postJson<{ token?: unknown }>(url, "/me/reauth", body, token, SIGN_IN_TIMEOUT_MS); - return typeof reply.token === "string" ? reply.token : undefined; - }); + const reply = await postJson<{ token?: unknown }>(url, "/me/reauth", body, token, SIGN_IN_TIMEOUT_MS); + return typeof reply.token === "string" ? reply.token : undefined; }, }; return await withAuthAdopting(ctx, url, (token, adopt) => @@ -388,8 +384,10 @@ export async function withStepUpAuth( // The re-proof ended the token withAuthAdopting handed in, so it is told which one this call // now holds: a 401 on it is then not mistaken for a sign-in elsewhere merely because the // cache holds the rotated token (BACKLOG #5960). - // Adopt only: reauth above already stored it in the cache, inside the tracked span. - storeToken: async (rotated) => adopt(rotated), + storeToken: async (rotated) => { + adopt(rotated); + await ctx.secrets.store(secretKey(url), rotated); + }, }), ); } diff --git a/ide/src/signInSession.ts b/ide/src/signInSession.ts index 478cb1a8b4..9ab53324a9 100644 --- a/ide/src/signInSession.ts +++ b/ide/src/signInSession.ts @@ -14,9 +14,8 @@ // // THE COST IS THE ORDER ON THIS SIDE. The old token now dies inside the request, before the new one is // in the cache. Four things follow. -// 1. A reader of the cache could pick up the dead token in that span. Each sign-in, and each step-up -// re-proof (`reproveTracked`), is therefore tracked from before its request leaves until the new -// token is stored, and `peekToken` in +// 1. A reader of the cache could pick up the dead token in that span. Each sign-in is therefore +// tracked from before its request leaves until the new token is stored, and `peekToken` in // auth.ts awaits `signInSettled` before it reads. A call already sent on the old token can still // get a 401, and `withAuth` then reads the cache again through `peekToken`. // 2. Two sign-ins for one engine run one after the other. The second reads the cache only once the @@ -63,8 +62,7 @@ export const SIGN_IN_TIMEOUT_MS = 150_000; * attempt. Point 3 above names what it does not cover. */ export const SIGN_IN_WAIT_MS = SIGN_IN_TIMEOUT_MS + 5_000; -/** Sign-ins and re-proofs between "request about to leave" and "new token stored", by cache key. - * Never rejects. */ +/** Sign-ins between "request about to leave" and "new token stored", by cache key. Never rejects. */ const inFlight = new Map>(); /** `pending`, or `ms` elapsing, whichever comes first. Never rejects. */ @@ -97,49 +95,15 @@ export function signInSuperseding( post: (body: Record) => Promise, waitMs: number = SIGN_IN_WAIT_MS, ): Promise { - return tracked(key, waitMs, async () => { + const earlier = inFlight.get(key); + const attempt = (async () => { + await bounded(earlier, waitMs); const prior = await cache.get(key); const reply = await post(prior ? { ...credentials, supersedes: prior } : credentials); await cache.store(key, reply.token); return reply; - }); -} - -/** - * Send one step-up re-proof for the engine cached under `key`, and store the token it returns. - * - * `post` sends `POST /me/reauth` on the token the call holds and resolves to the rotated token, or to - * `undefined` or `""` when the engine sent none (an older engine), which leaves the cache as it was. - * The engine ends the old token when it rotates, as a sign-in does, so the re-proof is tracked the same - * way: it waits up to `waitMs` for a sign-in or re-proof already in flight for `key`, and a later one, - * and `peekToken`, wait for it in turn. So in this window its store does not land on top of a token a - * newer sign-in stored, unless a wait runs out (point 3 above) or the sign-in was in another window - * (point 4). - */ -export function reproveTracked( - cache: TokenCache, - key: string, - post: () => Promise, - waitMs: number = SIGN_IN_WAIT_MS, -): Promise { - return tracked(key, waitMs, async () => { - const rotated = await post(); - if (rotated) { - await cache.store(key, rotated); - } - return rotated; - }); -} - -/** Run `run` once any attempt already tracked for `key` settles or `waitMs` passes, tracked itself - * from before it starts until it settles. */ -function tracked(key: string, waitMs: number, run: () => Promise): Promise { - const earlier = inFlight.get(key); - const attempt = (async () => { - await bounded(earlier, waitMs); - return await run(); })(); - // The attempt waits for the earlier attempt first, so one await covers them all. Set in the same + // The attempt waits for the earlier sign-in first, so one await covers them all. Set in the same // tick the attempt starts, which is before its request can leave. const settled = attempt.then( () => undefined, @@ -155,9 +119,9 @@ function tracked(key: string, waitMs: number, run: () => Promise): Promise } /** - * Resolves once no sign-in or re-proof tracked for `key` is still between its request and its store, - * or after `waitMs`, whichever is first. Never rejects: a failed attempt settles it too. Resolves at - * once when none is in flight. + * Resolves once no sign-in tracked for `key` is still between its request and its store, or after + * `waitMs`, whichever is first. Never rejects: a failed sign-in settles it too. Resolves at once when + * none is in flight. */ export function signInSettled(key: string, waitMs: number = SIGN_IN_WAIT_MS): Promise { return bounded(inFlight.get(key), waitMs); diff --git a/ide/src/stepUp.ts b/ide/src/stepUp.ts index ba075c6ba9..f8e63787bb 100644 --- a/ide/src/stepUp.ts +++ b/ide/src/stepUp.ts @@ -20,9 +20,7 @@ export interface StepUpHost { promptPassword(signal: StepUpSignal, retry: boolean): Promise; /** POST /me/reauth with `token`; resolve to the re-keyed token the engine returns, if any. */ reauth(token: string, password: string, purpose: string | undefined): Promise; - /** Keep the re-keyed token, so later calls use the live session. The IDE's host stores it in the - * sign-in cache inside `reauth` instead (auth.ts, signInSession.ts `reproveTracked`), where the - * store is tracked, so a store added here would run untracked. */ + /** Keep the re-keyed token, so later calls and the sign-in cache use the live session. */ storeToken(token: string): Promise; } diff --git a/ide/src/test/suite/sign-in-supersedes.test.ts b/ide/src/test/suite/sign-in-supersedes.test.ts index c10d8e9fe7..51fe5d2be4 100644 --- a/ide/src/test/suite/sign-in-supersedes.test.ts +++ b/ide/src/test/suite/sign-in-supersedes.test.ts @@ -7,7 +7,7 @@ import type { AddressInfo } from "node:net"; import * as path from "node:path"; import { HttpError, postJson } from "../../engineClient"; -import { reproveTracked, signInSettled, signInSuperseding, type TokenCache } from "../../signInSession"; +import { signInSettled, signInSuperseding, type TokenCache } from "../../signInSession"; // BACKLOG #2281 (ASVS 7.2.4): a sign-in names the token it replaces as `supersedes`, so the engine ends // that session before its per-user cap counts. The IDE used to sign in and then POST /auth/logout with @@ -238,41 +238,6 @@ suite("a caller can wait out a sign-in in flight (BACKLOG #2281)", () => { hung.fail(new Error("cleanup")); // release it, so the next test starts with nothing in flight await signInSettled(key, 1000); }); - - test("a sign-in started during a step-up re-proof names the token the re-proof stored", async () => { - const cache = new MapCache(); - cache.values.set(key, "tok-old"); - const held = heldPost(); - const reproving = reproveTracked(cache, key, async () => (await held.post({})).token); - await held.sent; // the engine has rotated tok-old by now - let settled = false; - const waiting = signInSettled(key).then(() => (settled = true)); - const named: Array = []; - const signingIn = signInSuperseding(cache, key, CREDENTIALS, async (body) => { - named.push(body.supersedes); - return { token: "tok-signed-in" }; - }); - await new Promise((resolve) => setImmediate(resolve)); - // RED when: the re-proof is not tracked. The sign-in then names the dead tok-old, the re-proof's - // late store overwrites the sign-in's token, and peekToken reads tok-old meanwhile. - assert.strictEqual(settled, false, "the wait ended while the re-proof was still in flight"); - assert.deepStrictEqual(named, [], "the sign-in did not wait for the re-proof"); - held.answer("tok-rotated"); - assert.strictEqual(await reproving, "tok-rotated"); - await signingIn; - await waiting; - assert.deepStrictEqual(named, ["tok-rotated"]); - assert.strictEqual(cache.values.get(key), "tok-signed-in"); - }); - - test("a re-proof with no token in its reply leaves the cache alone", async () => { - const cache = new MapCache(); - cache.values.set(key, "tok-old"); - for (const reply of [undefined, ""]) { - assert.strictEqual(await reproveTracked(cache, key, async () => reply), reply); - assert.strictEqual(cache.values.get(key), "tok-old"); - } - }); }); suite("auth.ts routes sign-in through the superseding path (BACKLOG #2281)", () => { @@ -296,13 +261,6 @@ suite("auth.ts routes sign-in through the superseding path (BACKLOG #2281)", () const logoutSites = (text: string): string[] => text.split(/\r?\n/).filter((l) => l.includes('"/auth/logout"')); - test("the step-up re-proof posts through reproveTracked (vault BACKLOG #2950)", () => { - const text = fs.readFileSync(AUTH_TS, "utf8"); - // Control: the sign-in's own call is found by the same kind of scan. - assert.ok(text.includes("signInSuperseding(ctx.secrets, secretKey(url), body"), "signIn's call moved"); - assert.ok(text.includes("reproveTracked(ctx.secrets, secretKey(url), async () =>"), "the re-proof is untracked"); - }); - test("the step-up re-proof carries the sign-in's timeout (vault BACKLOG #2950)", () => { const text = fs.readFileSync(AUTH_TS, "utf8"); const sites = text.split(/\r?\n/).filter((l) => l.includes('"/me/reauth"') && l.includes("postJson")); From ad8e79c48a4145cda6068f5f03ce0fee031fa173 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sat, 21 Nov 2026 18:50:58 -0600 Subject: [PATCH 36/74] Coord scripts: point box-activity at the profile-read reason, rewrap the registry comment Vault BACKLOG #2985 (batch 287), review round-6d7bc166c8 repairs: comments only. box-activity.ps1 no longer restates the -LiteralPath reason Get-ClaudeConfigRoots already gives, and the Get-SessionRecords header is wrapped again. Proposed PR title: Coord scripts: box-activity profile read, NO_LOGIN directory rows, remove.ps1 end-state test (BACKLOG #2985) Proposed banner #2985: PARTIAL -- added items 1 (end-state test), 2 (last listing) and 3 built; added item 4 met in code by engine PR 3027; closing step 1 waits on #1017 for items 1, 7 and 12, and item 6 beyond the caller's own config root remains. --- scripts/coord/box-activity.ps1 | 4 +--- scripts/coord/session-registry.ps1 | 7 ++++--- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/scripts/coord/box-activity.ps1 b/scripts/coord/box-activity.ps1 index e96a6ee335..be11fbb4d2 100644 --- a/scripts/coord/box-activity.ps1 +++ b/scripts/coord/box-activity.ps1 @@ -123,9 +123,7 @@ function Get-TranscriptAgeHours { # NOT Get-ClaudeConfigRoots: that one filters to roots holding a sessions/ directory, which is the # right question for the liveness fence and the wrong one here. A root can hold transcripts and no # session registry, and dropping it would turn an evaluable signal into a missing one. - # -LiteralPath, as Get-ClaudeConfigRoots reads it: -Path takes the profile as a wildcard pattern, - # so a profile named home[1] matched only a folder named home1. No profile names no root, because - # -LiteralPath throws on a null path where -Path listed the current directory. + # Read the profile as Get-ClaudeConfigRoots does; its comment in session-registry.ps1 says why. $roots = if ($ConfigRoot) { @($ConfigRoot | Where-Object { Test-Path -LiteralPath $_ }) } elseif (-not $env:USERPROFILE) { @() } else { diff --git a/scripts/coord/session-registry.ps1 b/scripts/coord/session-registry.ps1 index 836d74cc4a..918044a308 100644 --- a/scripts/coord/session-registry.ps1 +++ b/scripts/coord/session-registry.ps1 @@ -190,9 +190,10 @@ function Get-RecordStartedUtc($Record) { # Every registry record, with the root it came from attached. # # -IncludeUnreadable also returns a row for every file that could NOT be parsed (Record = $null, -# Unreadable = $true; Directory = $true when the row is a directory named *.json). A caller about to destroy something needs those: a record that is half-written -# -- i.e. a session that launched a moment ago -- fails to parse, and DROPPING it silently turns an -# occupied worktree from SKIP into PRUNE while the receipt reports one fewer record than existed. +# Unreadable = $true; Directory = $true when the row is a directory named *.json). A caller about to +# destroy something needs those: a record that is half-written -- i.e. a session that launched a +# moment ago -- fails to parse, and DROPPING it silently turns an occupied worktree from SKIP into +# PRUNE while the receipt reports one fewer record than existed. # It is off by default so the read-only roster callers keep the shape they already handle. function Get-SessionRecords { [CmdletBinding()] From f84d453c78c9c5d045ce8e4137b35eadabe10aa3 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sat, 21 Nov 2026 18:51:10 -0600 Subject: [PATCH 37/74] reply_replaced: frame_reply names the flag it drops; frame-byte negative test Round 2 review fixes. frame_reply's docstring says it drops the replacement flag and that a listener calls frame_reply_reporting. A test pins that a frame byte turned into a space sets no flag, as PHI.md says. BACKLOG #5799 item 1. Proposed PR title: Listeners record each charset-replaced reply as a connection event; X12 trailer comment corrected (BACKLOG #5799, #5807, #5812) Proposed banners: - #5799: item 1 SHIPPED (reply_replaced event per replaced reply, warn-once log kept). Items 2 and 3 open, not in this brief. - #5807: OPEN, unchanged. The separator check regresses origin/main (PR 3031 measured it; the pinned trailer tests hold it); closing needs a decision to accept a held frame for a separator-less trailer, or a not-a-bug. A false test comment is corrected. - #5812: PARTIAL, unchanged by code. Items 4/17, 5, 6, 8, 11 and 12 met on origin/main (PR 3059 and earlier); 10 kept in one line; 13 is on branch w1-264-parse-log; 1-3, 7, 9, 14-16 open. --- messagefoundry/transports/framing.py | 4 +++- tests/test_one_frame_one_message.py | 5 +++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/messagefoundry/transports/framing.py b/messagefoundry/transports/framing.py index 124a818b48..fdbcfa5ea7 100644 --- a/messagefoundry/transports/framing.py +++ b/messagefoundry/transports/framing.py @@ -163,7 +163,9 @@ def frame_reply(codec: FrameCodec, reply: str, encoding: str, *, connection: str frame, and an echoed control id that held a frame byte simply stops matching. A space is what the ACK builder already puts in place of an echoed CR or LF. The replacement is on bytes, for the reason :func:`frame_for_delivery` checks bytes. The reply is encoded by :func:`encode_reply`, - which says what it does with a charset that cannot hold it.""" + which says what it does with a charset that cannot hold it. This drops the flag saying whether + characters were replaced, so a listener calls :func:`frame_reply_reporting` instead and writes + the ``reply_replaced`` event from it (BACKLOG #5799).""" return frame_reply_reporting(codec, reply, encoding, connection=connection)[0] diff --git a/tests/test_one_frame_one_message.py b/tests/test_one_frame_one_message.py index 5d25281c1a..d9f9d6235e 100644 --- a/tests/test_one_frame_one_message.py +++ b/tests/test_one_frame_one_message.py @@ -694,6 +694,11 @@ def test_the_reporting_variants_flag_a_replaced_reply_every_time() -> None: assert not framing_mod.frame_reply_reporting(MLLP_CODEC, CLEAN, "ascii")[1] assert not framing_mod.encode_reply_reporting(reply, "utf-8")[1] assert not framing_mod.encode_reply_reporting(reply, "not-a-real-codec")[1] + # A frame byte turned into a space is not a charset replacement, and sets no flag. + framed, replaced = framing_mod.frame_reply_reporting( + MLLP_CODEC, MSH + CR + "MSA|AA|C" + SB + "1" + CR, "ascii" + ) + assert not replaced and framed.count(b"\x0b") == 1 @pytest.mark.parametrize( From 07592a0dd551f9384125b2055f567d8bad1f600a Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sat, 21 Nov 2026 18:51:42 -0600 Subject: [PATCH 38/74] Test 8 drive stands in only while no lane is busy; the pin is named as one BACKLOG #3456 (batch 453), review round 2. - _drive_lanes_to_stop re-readies a stranded lane only while no lane is CLAIMING or PROCESSING, so the re-claim does not race a sibling's claim or re-pend. Its docstring now says the contention counters are dispatcher-wide, so only a stranding before any counted route fails on that ground. - The injected arm is test_the_outage_drive_stands_in_for_an_aborted_reclaim, a pin for the drive, built on SQLite alone by indirect parametrize. With the stand-in disabled it fails: all four lanes IDLE at 20 s. - _stand_in_for_sweep's docstring names its third caller. Proposed PR title: Stage dispatcher test 8 re-readies a lane stranded by an EMPTY claim (BACKLOG #3456) Proposed banner #3456: PARTIAL. The stage dispatcher test 8 drive bounds by wall time and stands in for the disabled sweep (cause read from three SQL Server 2025 logs, consistent with a stranding, not proven). Remains: hosted proof on the SQL Server 2025 leg (repeated runs); step 3's two step-duration gates (owner-reserved workflow edits); written causes for the hung outbound stop, per-lane wake and DR tests (none found by this pass). --- tests/test_stage_dispatcher.py | 33 +++++++++++++++++++-------------- 1 file changed, 19 insertions(+), 14 deletions(-) diff --git a/tests/test_stage_dispatcher.py b/tests/test_stage_dispatcher.py index 1ce8ccbe49..ebd258eb9a 100644 --- a/tests/test_stage_dispatcher.py +++ b/tests/test_stage_dispatcher.py @@ -1887,7 +1887,8 @@ async def _stand_in_for_sweep(d: StageDispatcher, lane: str) -> None: sweep these tests disable. The caller has already established the stranding; this counts it, caps it, and makes it loud. - Shared by `_wait_lane` (phase targets) and `_wait_lane_until` (work predicates) so the cap has ONE + Shared by `_wait_lane` (phase targets), `_wait_lane_until` (work predicates) and + `_drive_lanes_to_stop` (test 8's multi-lane drive) so the cap has ONE definition. The cap is a property of the LANE's contention rate, not of the call site: two separate budgets would let one test spend it twice and still read as within the allowance. """ @@ -2348,22 +2349,27 @@ async def _drive_lanes_to_stop( stands in for (a swallowed 1222). The logs do not show it as the cause: the dispatcher's lock-timeout line is INFO and was not captured. So a stranded lane is re-readied under the same capped, warned allowance, and the loop's bound is a wall-clock ceiling, not a round count. - A stand-in needs a recorded contention route (a lock-timeout abort or a head skip), so an - EMPTY claim with no cause still fails here, as it failed the old loop. + A stranding before any contention route is recorded (a lock-timeout abort or a head skip) + still fails here, as it failed the old loop, and names that route as unrecorded. The counters + are dispatcher-wide, so a later stranding is excused by any earlier counted one. A stand-in + waits until no lane is CLAIMING or PROCESSING, so the re-claim does not race a sibling's + claim or re-pend, which is where this test's own lanes contend. """ def all_stopped() -> bool: return all(d.phase(ln) is _LanePhase.STOPPED for ln in lanes) + busy = (_LanePhase.CLAIMING, _LanePhase.PROCESSING) loop = asyncio.get_running_loop() deadline = loop.time() + timeout while loop.time() < deadline: if all_stopped(): return + quiet = not any(d.phase(ln) in busy for ln in lanes) for ln in lanes: # IDLE is never a waypoint on this path (PARKED -> READY -> CLAIMING -> PROCESSING -> # PARKED or STOPPED), so an IDLE lane with no timer is a stranding. - if _terminal_idle(d, ln): + if quiet and _terminal_idle(d, ln): if d.claim_lock_timeouts + d.claim_head_skips == 0: raise _WaitTimeout( f"{ln} stranded in terminal IDLE with no contention recorded\n" @@ -2441,16 +2447,15 @@ async def test_adr0070_8_correlated_outage_single_reload_rearms_all(store: Any) await _correlated_outage_rearms_all(store, abort_second_claim=False) -async def test_adr0070_8_correlated_outage_survives_an_aborted_reclaim(store: Any) -> None: - """Test 8 with the claim after every lane's first fault aborted on a lock timeout, which - strands the lanes it covered in terminal IDLE. The 30-round loop `_drive_lanes_to_stop` - replaced fails this arm, because nothing re-claims a stranded lane, and each lane then shows - one fault, as three of the four did in the SQL Server 2025 logs. - - SQLite only: the abort is injected, so the backend adds nothing, and a server's own 1222 on - top of it would spend a lane's single stand-in twice.""" - if store._test_backend != "sqlite": - pytest.skip("the injected abort is backend-independent; one real 1222 more breaks the cap") +@pytest.mark.parametrize("store", ["sqlite"], indirect=True) +async def test_the_outage_drive_stands_in_for_an_aborted_reclaim(store: Any) -> None: + """The pin for `_drive_lanes_to_stop`, not an ADR 0070 guarantee: the test harness's stand-in, + not the dispatcher, re-claims the stranded lanes, because the sweep is disabled. Test 8's body + with the claim after every lane's first fault aborted on a lock timeout. The 30-round loop it + replaced fails this arm, because nothing re-claims a stranded lane. + + SQLite only: the abort is injected, so a server backend adds nothing but its own contention, + which could spend a lane's single stand-in a second time.""" with pytest.warns(UserWarning, match="sweep stand-in"): await _correlated_outage_rearms_all(store, abort_second_claim=True) From 289a141beaa25d079478ff7de9c42c759e4b39a1 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sat, 21 Nov 2026 18:52:44 -0600 Subject: [PATCH 39/74] Drop the run-memo comment; census docstring names what escapes it The _RUN_MEMO comment claimed the args-only key keeps the legs on the run's source tag, but the first load can run after the config modules are imported, so checks.py returns to origin/main. The inline read-timeout census docstring now says at least which shapes escape it. Vault BACKLOG #2950. --- messagefoundry/checks.py | 5 ----- tests/test_apiclient_sign_in_timeout.py | 6 ++++-- 2 files changed, 4 insertions(+), 7 deletions(-) diff --git a/messagefoundry/checks.py b/messagefoundry/checks.py index d77387ad23..8c023dcea7 100644 --- a/messagefoundry/checks.py +++ b/messagefoundry/checks.py @@ -125,11 +125,6 @@ #: The settings resolutions and loads of one :func:`run_checks` call, so each runs once per run #: rather than once per settings leg (vault BACKLOG #2950 added items 6 and 13). ``None`` outside a #: run: a leg called on its own resolves and loads afresh, as it always did. -#: -#: The key is the arguments alone, not the working directory or the environment, on purpose: the -#: memo is a snapshot of the run. :func:`run_checks` resolves the source once, before the config -#: modules are imported, and tags each leg's line with it, so a leg that resolved again after a -#: module changed either would grade settings that tag does not name. _RUN_MEMO: ContextVar[dict[tuple[object, ...], object] | None] = ContextVar( "_RUN_MEMO", default=None ) diff --git a/tests/test_apiclient_sign_in_timeout.py b/tests/test_apiclient_sign_in_timeout.py index d428ec6852..9a03f1f5f7 100644 --- a/tests/test_apiclient_sign_in_timeout.py +++ b/tests/test_apiclient_sign_in_timeout.py @@ -230,8 +230,10 @@ def test_the_census_of_queued_calls_matches_the_client() -> None: def test_no_method_builds_its_own_read_keyword_timeout() -> None: """RED when: an ``EngineClient`` method builds its own ``httpx.Timeout(..., read=...)`` rather than calling ``_sign_in_timeout``, so a longer reply wait escapes the census above. Control: - the scan finds the one method that does build one, ``_sign_in_timeout`` itself. A positional - ``httpx.Timeout(n)`` or a scalar ``timeout=`` is not scanned.""" + the scan finds the one method that does build one, ``_sign_in_timeout`` itself. It reads only + a ``read=`` keyword in a call inside a method body, so at least these escape it: a positional + ``httpx.Timeout(n)``, a scalar ``timeout=``, a module-level ``httpx.Timeout`` constant or helper + passed in, and ``httpx.Timeout(**kw)``.""" assert _methods_setting_a_read_timeout() == {"_sign_in_timeout"} From 4f05f9ee75104d7f3215f714b23daa37851b1c7c Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sat, 21 Nov 2026 18:53:33 -0600 Subject: [PATCH 40/74] Repair round 2: R3 pointer, both record dates, point 4 names its substitute ADR 0019's first 2026-10-10 note points to ADR 0138 for who judges the record against R3, not for a standing it declines to give, and quotes the removed words. Point 4 says Engine.start checks for a recorded attestation. ADR 0173 names both records' Central dates. The test is renamed a revert guard, strips only 2026-11-21 notes, covers the first 2026-10-10 note, and asserts the version limit is still stated. Proposed PR title: ADR 0019 and ADR 0173 drop restated facts Banner #1173: PARTIAL -- item 3 fixed (point 4 and its note point to ADR 0138); item 2 true as written, still open Banner #3009: PARTIAL -- PR 2899 notes 3 and 4 fixed for the run dates and the versions --- ...019-pluggable-keyprovider-hsm-kms-vault.md | 15 ++-- ...ss-terminating-and-originating-surfaces.md | 2 +- tests/test_adr_0019_0173_stated_once.py | 70 +++++++++++-------- 3 files changed, 50 insertions(+), 37 deletions(-) diff --git a/docs/adr/0019-pluggable-keyprovider-hsm-kms-vault.md b/docs/adr/0019-pluggable-keyprovider-hsm-kms-vault.md index 271d0029e6..1e05c1bb87 100644 --- a/docs/adr/0019-pluggable-keyprovider-hsm-kms-vault.md +++ b/docs/adr/0019-pluggable-keyprovider-hsm-kms-vault.md @@ -665,10 +665,11 @@ lifetime is Vault's to version. The bound is a no-op there and for the identity > `Engine.start` checks for an operator's recorded attestation to the precondition through > `enforce_transit_bound_attestation`, so "documented" now undersells it. The R3 ruling above > judged the precondition before that record existed. ADR 0138's 2026-10-07 amendment says how the -> attestation is recorded, what the check does under each enforcement level, what it does not -> change, and how the record stands against R3. *(Corrected 2026-11-21, vault BACKLOG #1173: this -> note also named the CLI command that records the attestation, and said that whether the record -> meets R3 is a scorecard call. The 2026-10-07 amendment states both.)* +> attestation is recorded and what the check does under each enforcement level. It also says what +> the check does not change, and who judges the record against R3. *(Corrected 2026-11-21, vault +> BACKLOG #1173: this note read "an operator attests to the precondition with `messagefoundry +> store attest-transit-bound`, and `Engine.start` reads that record" and "whether the record meets +> R3 is a scorecard call". The 2026-10-07 amendment states both.)* **Status: 11.3.4 — the bound is persisted, aggregated, alarmed and enforced.** As before, this ADR records the build and does not itself re-score; ADR 0115 / the ASVS-L3 re-score governs the sweep. @@ -802,9 +803,9 @@ above. 4. **Volume wears out a key, not the generator.** The one value whose safety falls with volume is the 96-bit random AES-GCM nonce, and that is a limit on the key, not on the generator. The default path counts it: the 2026-07-22 amendment above, and `store/gcm_bound.py`. The `vault_transit` path - counts nothing. `Engine.start` calls `enforce_transit_bound_attestation` in - `store/transit_attestation.py` (BACKLOG #2337), and an attestation is still weaker than the - counted bound. [ADR 0138](0138-transit-bulk-crypto-provider-dek-out-of-engine-heap-for-asvs-13-3-3-demand-gated.md)'s + counts nothing. `Engine.start` instead checks for an operator's recorded attestation to the + bound, through `enforce_transit_bound_attestation` in `store/transit_attestation.py` (BACKLOG + #2337). An attestation is still weaker than the counted bound. [ADR 0138](0138-transit-bulk-crypto-provider-dek-out-of-engine-heap-for-asvs-13-3-3-demand-gated.md)'s 2026-10-07 amendment records what that gate checks, what it does under each enforcement level, and what it does not catch. Its 2026-09-28 amendment states the rotation precondition the operator attests to. *(Corrected 2026-11-21, vault BACKLOG #1173: this point read "In its diff --git a/docs/adr/0173-tls-peer-revocation-checking-and-ocsp-stapling-across-terminating-and-originating-surfaces.md b/docs/adr/0173-tls-peer-revocation-checking-and-ocsp-stapling-across-terminating-and-originating-surfaces.md index 0b8eb295b4..fd3979a9d4 100644 --- a/docs/adr/0173-tls-peer-revocation-checking-and-ocsp-stapling-across-terminating-and-originating-surfaces.md +++ b/docs/adr/0173-tls-peer-revocation-checking-and-ocsp-stapling-across-terminating-and-originating-surfaces.md @@ -1325,7 +1325,7 @@ grade*, under the ruling above, and its note of 2026-11-11. - **Where it ran.** Two runs with results. The first run's legs ran from 02:22 to 02:25 UTC and the second's from 05:18 to 05:19 UTC, both on 2026-10-17. The records are dated in Central - time, where the first run fell on the evening of 2026-10-16. The first run's record says it ran + time: the first 2026-10-16, the second 2026-10-17. The first run's record says it ran on a disposable virtual machine built for the test, not on the SQL Server test box, and that the runbook puts the next run there. The second run's record says it ran inside a virtual machine, after a revert to checkpoint diff --git a/tests/test_adr_0019_0173_stated_once.py b/tests/test_adr_0019_0173_stated_once.py index d979d8e491..b2a66b0346 100644 --- a/tests/test_adr_0019_0173_stated_once.py +++ b/tests/test_adr_0019_0173_stated_once.py @@ -1,17 +1,19 @@ # SPDX-License-Identifier: AGPL-3.0-or-later # Copyright (C) 2026 MessageFoundry Foundation, LLC and contributors -"""ADR 0019 and ADR 0173 point to the record that states a fact, rather than restating it. +"""A revert guard: ADR 0019 and ADR 0173 do not take back the restatements removed from them. -ADR 0019's RNG amendment point 4 once restated ADR 0138's Transit start gate (vault BACKLOG #1173, -item 3). ADR 0173's ODBC test amendment gave its run dates in two zones and repeated its versions -in its limits (vault BACKLOG #3009, PR 2899 notes 3 and 4). SDS-3.5: a fact lives in one place. +ADR 0019's RNG amendment point 4 and its first 2026-10-10 note restated ADR 0138's Transit start +gate (vault BACKLOG #1173, item 3). ADR 0173's ODBC test amendment opened with its run dates in two +zones and repeated its versions in its limits (vault BACKLOG #3009, PR 2899 notes 3 and 4). -Each refused phrase is checked against the text it was removed from, so a phrase that drifts -from that wording fails here instead of passing for ever. +This refuses the removed phrasings only. It does not prove a fact is stated once anywhere else. +Each refused phrase is checked against the removed wording, so a phrase that drifts from that +wording fails here instead of passing for ever. """ from __future__ import annotations +import re from pathlib import Path import pytest @@ -30,6 +32,10 @@ "configured Transit data key (BACKLOG #2337). Without one, the engine refuses to start under " "`[security].enforcement = enforce` and only logs a warning under `warn`." ) +_OLD_0019_NOTE = ( + "Since BACKLOG #2337, an operator attests to the precondition with " + "`messagefoundry store attest-transit-bound`, and `Engine.start` reads that record" +) _OLD_0173_FINDINGS = ( "Two runs with results, dated 2026-10-16 and 2026-10-17 in Central time. In UTC, the first " "run's legs ran from 02:22 to 02:25" @@ -37,13 +43,17 @@ _OLD_0173_LIMIT = "Only that driver build, only Windows Server 2022, and only SQL Server 2022 RTM." _REFUSED_0019 = ("in its place,", "refuses to start", "logs a warning", "naming the configured") +_REFUSED_0019_NOTE = ("attest-transit-bound", "reads that record") _REFUSED_0173_FINDINGS = ("in utc, the first run", "2026-10-17 in central time") _REFUSED_0173_LIMIT = ("only windows server 2022", "only sql server 2022 rtm") +# A 2026-11-21 correction note quotes the removed words on purpose; strip only the note itself. +_NOTE = re.compile(r"\*\(Corrected 2026-11-21,.*?\)\*", re.DOTALL) + def _flat(text: str) -> str: - """Join wrapped lines and fold case, so a phrase that wraps or opens a sentence still matches.""" - return " ".join(text.split()).lower() + """Join wrapped lines, drop blockquote markers and fold case, so a wrapped phrase matches.""" + return " ".join(w for w in _NOTE.sub("", text).split() if w != ">").lower() def _between(text: str, start: str, end: str) -> str: @@ -51,15 +61,11 @@ def _between(text: str, start: str, end: str) -> str: return text[head : text.index(end, head)] -def _body(text: str) -> str: - """Drop correction notes, which quote the removed words on purpose.""" - return text.split("*(Corrected 2026-11-21", 1)[0] - - @pytest.mark.parametrize( ("old", "refused"), [ (_OLD_0019_POINT_4, _REFUSED_0019), + (_OLD_0019_NOTE, _REFUSED_0019_NOTE), (_OLD_0173_FINDINGS, _REFUSED_0173_FINDINGS), (_OLD_0173_LIMIT, _REFUSED_0173_LIMIT), ], @@ -71,33 +77,39 @@ def test_each_refused_phrase_matches_the_removed_wording( assert phrase in _flat(old), phrase -def test_adr_0019_point_4_does_not_restate_the_transit_gate() -> None: +def test_adr_0019_does_not_restate_the_transit_gate() -> None: text = _ADR_0019.read_text(encoding="utf-8") point_4 = _flat( - _body( - _between( - text, - "4. **Volume wears out a key, not the generator.**", - "**What this statement does not cover.**", - ) + _between( + text, + "4. **Volume wears out a key, not the generator.**", + "**What this statement does not cover.**", + ) + ) + note = _flat( + _between( + text, + "> **Corrected 2026-10-10 (BACKLOG #1173).** The rotation precondition above", + "**Status: 11.3.4", ) ) for phrase in _REFUSED_0019: assert phrase not in point_4, phrase + for phrase in _REFUSED_0019_NOTE: + assert phrase not in note, phrase # Positive controls: the pointer, the link and the caveat stay. assert "enforce_transit_bound_attestation" in point_4 assert "0138-transit-bulk-crypto-provider" in point_4 assert "weaker than the counted bound" in point_4 + assert "enforce_transit_bound_attestation" in note -def test_adr_0173_odbc_amendment_states_dates_and_versions_once() -> None: +def test_adr_0173_odbc_amendment_does_not_restate_dates_or_versions() -> None: text = _ADR_0173.read_text(encoding="utf-8") - amendment = _body( - _between( - text, - "**Amendment 2026-11-11 -- what the ODBC Driver 18 test measured", - "*(End of the amendment of 2026-11-11.", - ) + amendment = _between( + text, + "**Amendment 2026-11-11 -- what the ODBC Driver 18 test measured", + "*(End of the amendment of 2026-11-11.", ) head, _, limits = amendment.partition("- **The limits.**") findings, limits = _flat(head), _flat(limits) @@ -105,7 +117,7 @@ def test_adr_0173_odbc_amendment_states_dates_and_versions_once() -> None: assert phrase not in findings, phrase for phrase in _REFUSED_0173_LIMIT: assert phrase not in limits, phrase - # Positive controls: the UTC times and the versions are each still stated. + # Positive controls: the UTC times, the versions and the version limit are each still stated. assert "02:22 to 02:25 utc" in findings assert "windows server 2022 datacenter" in findings - assert limits # the limits list was found + assert "only the driver, windows and sql server versions above" in limits From e03dcecfba75a4638804e204797e472cb6eeb186 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sat, 21 Nov 2026 18:54:33 -0600 Subject: [PATCH 41/74] Schema check review fixes: match the foreign object against the file, lead with the drop Review round-9c162856 on origin/main..32bdbb5051: - The view or trigger a re-check error names is matched against the live file's views and triggers, never cut out of the text, so a suffix such as " after rename" or a colon in a quoted name no longer mis-names it, and the expected-name test sees the real name. A SQLite error while reading them falls back to the plain remedy, with a WARNING. - The drop remedy leads with the instruction and names the object after it. - The not-a-shape read control warms the expected shape first, so the patched error comes from the live read inside run_schema_step. - The run_schema_step docstring points at _ORDINARY_TABLE rather than restating that this build creates no view or trigger. - Changelog: the read refusal is on a writable open. BACKLOG #6719 item 3, #6720 item 4. Proposed PR title: Store schema check: foreign view or trigger remedy, verify read refusal, audit-verify shape pin (vault BACKLOG #6719, #6720, #6686, #6687) --- .../6719-6720-foreign-view-remedy.fixed.md | 4 +- messagefoundry/store/schema_verify.py | 61 +++++++++++-------- tests/test_schema_verify_6719_6720.py | 44 ++++++++++--- 3 files changed, 75 insertions(+), 34 deletions(-) diff --git a/changelog.d/6719-6720-foreign-view-remedy.fixed.md b/changelog.d/6719-6720-foreign-view-remedy.fixed.md index a8aefd14b2..271f482298 100644 --- a/changelog.d/6719-6720-foreign-view-remedy.fixed.md +++ b/changelog.d/6719-6720-foreign-view-remedy.fixed.md @@ -3,6 +3,6 @@ an error that names the store's shape, such as "no such module", the open refuses the store with the remedy to drop that object and restart, not to recreate the store. A view under the name of a table or index this build creates still gets the recreate remedy. A failure on the store's shape - raised by the check's own read of the live store, after the schema script and the migrations, is - now refused with the recreate remedy rather than escaping as SQLite's bare error. + raised by the check's own read of the live store, after the schema script and the migrations of + a writable open, is now refused with the recreate remedy rather than escaping as SQLite's bare error. (`BACKLOG #6719`, `BACKLOG #6720`) diff --git a/messagefoundry/store/schema_verify.py b/messagefoundry/store/schema_verify.py index b45aa6c15b..8374fc66f8 100644 --- a/messagefoundry/store/schema_verify.py +++ b/messagefoundry/store/schema_verify.py @@ -80,12 +80,12 @@ " so restarting under the old key would zero its AES-GCM use count, which lives in the store. If" " you set [secret_rotation].store_key_last_rotated, update it." ) -# The kinds the ALTER re-check names, as "error in : ...", when an object other than -# the altered table fails to parse. Only views and triggers: this build creates neither (see -# _ORDINARY_TABLE), so the object named is another tool's. SQLite uses the same form for a table or -# an index, which may be this build's own. Dropping a view or a trigger removes no row, so that -# remedy keeps the store and its key. -_FOREIGN_KINDS = ("view", "trigger") +# The ALTER re-check names an object other than the altered table that fails to parse as +# "error in ", then ":" or a suffix such as " after rename". Only views and triggers +# get the drop remedy (see _ORDINARY_TABLE for why they are another tool's); SQLite uses the same +# form for a table or an index, which may be this build's own. Dropping a view or a trigger removes +# no row, so that remedy keeps the store and its key. +_FOREIGN_OBJECTS_SQL = "SELECT type, name FROM sqlite_master WHERE type IN ('view', 'trigger')" # The reads below skip a table whose stored SQL is LIKE 'CREATE VIRTUAL TABLE%', because a pragma # on a virtual table whose module is not loaded here can raise "no such module" (BACKLOG #6719). @@ -432,23 +432,23 @@ async def run_schema_step[T]( failure propagates unchanged. One shape failure gets another remedy: SQLite's re-check of the schema after an ``ALTER`` - names the view or trigger it could not parse, as in "error in view V: no such module". This - build creates neither kind, so that object is another tool's, and dropping it lets the - migration run past it (BACKLOG #6719). A view under a name this build creates is not such an - object: it holds the place of a table or index, which is the incompatible store the plain - remedy names.""" + names the view or trigger it could not parse, as in "error in view V: no such module". That + object is another tool's (see ``_ORDINARY_TABLE``), and dropping it lets the migration run past + it (BACKLOG #6719). A view under a name this build creates is not such an object: it holds the + place of a table or index, which is the incompatible store the plain remedy names.""" try: return await step except Exception as exc: if not is_schema_step_error(exc): raise cause = str(exc) - foreign = await _foreign_object(cause) + foreign = await _foreign_object(db, cause) if foreign is not None: kind, name = foreign + # The instruction leads and the name follows it, so the 200-character cut keeps it. raise SchemaMismatchError( - f"store {path} holds a {kind} {name!r} this build did not create, which stops its" - f" upgrade: drop it, then restart. The schema step failed: {cause}.", + f"store {path}: drop the {kind} {name!r}, which this build did not create and which" + f" stops its upgrade, then restart. The schema step failed: {cause}.", cause=cause, ) from exc if counts_under_dek is None: @@ -459,16 +459,29 @@ async def run_schema_step[T]( ) from exc -async def _foreign_object(cause: str) -> tuple[str, str] | None: - """The kind and name of another tool's view or trigger that ``cause`` names, else ``None``.""" - for kind in _FOREIGN_KINDS: - prefix = f"error in {kind} " - if cause.startswith(prefix): - name = cause[len(prefix) :].split(":", 1)[0] - if kind == "view" and name.lower() in await _names_this_build_creates(): - return None - return kind, name - return None +async def _foreign_object(db: aiosqlite.Connection, cause: str) -> tuple[str, str] | None: + """The kind and name of another tool's view or trigger that ``cause`` names, else ``None``. + + The name is matched against the live file's views and triggers, never cut out of the text: the + text may add a suffix after the name, and a quoted name may hold a colon. A SQLite error while + telling falls back to ``None``, the plain remedy.""" + try: + async with db.execute(_FOREIGN_OBJECTS_SQL) as cur: + objects = [(str(kind), str(name)) for kind, name in await cur.fetchall()] + named = [] + for kind, name in objects: + rest = cause.removeprefix(f"error in {kind} {name}") + if rest != cause and rest[:1] in (":", " "): + named.append((kind, name)) + if not named: + return None + kind, name = max(named, key=lambda o: len(o[1])) + if kind == "view" and name.lower() in await _names_this_build_creates(): + return None + except sqlite3.Error as exc: + log.warning("could not read the views and triggers to pick the schema remedy: %s", exc) + return None + return kind, name async def _names_this_build_creates() -> frozenset[str]: diff --git a/tests/test_schema_verify_6719_6720.py b/tests/test_schema_verify_6719_6720.py index 8354ec51c4..3e6ccb4a4b 100644 --- a/tests/test_schema_verify_6719_6720.py +++ b/tests/test_schema_verify_6719_6720.py @@ -468,7 +468,7 @@ async def test_a_foreign_object_that_stops_a_migration_gets_the_drop_remedy( cause = info.value.cause assert cause is not None and cause.startswith(f"error in {kind} {name}: no such module"), cause text = str(info.value) - assert text.startswith(f"store {path} holds a {kind} '{name}' this build did not create"), text + assert text.startswith(f"store {path}: drop the {kind} '{name}', which this build"), text assert "recreate" not in text and "NEW store key" not in text, text # The remedy is true: with that object dropped, the same migration runs and the open succeeds. _sql(path, drop) @@ -523,6 +523,10 @@ async def _verify_raising( """``verify_live_schema`` with ``target`` raising ``exc``; returns what the verify raised.""" from messagefoundry.store import schema_verify + # Warm the expected shape first: its scratch build calls read_schema_shape too, and on a cold + # cache the patched error would come from there rather than from the live read. + await schema_verify._expected_shape(_SCHEMA, MessageStore._migrate) + async def raising(*_args: object, **_kwargs: object) -> object: raise exc @@ -546,6 +550,8 @@ async def test_a_read_error_that_is_not_a_shape_keeps_its_own_error( exc = _real_sqlite_error("SELEC 1") assert exc.sqlite_errorcode & 0xFF == sqlite3.SQLITE_ERROR assert await _verify_raising(monkeypatch, "read_schema_shape", exc) is exc + frames = {f.name for f in traceback.extract_tb(exc.__traceback__)} + assert "run_schema_step" in frames, frames async def test_a_failure_building_the_expected_shape_keeps_its_own_error( @@ -558,15 +564,37 @@ async def test_a_failure_building_the_expected_shape_keeps_its_own_error( assert await _verify_raising(monkeypatch, "_expected_shape", exc) is exc -async def test_a_view_under_a_name_this_build_creates_is_not_another_tools_object() -> None: +@pytest.mark.parametrize( + ("view_name", "cause", "found"), + [ + pytest.param("vv", "error in view vv: no such module: m", ("view", "vv"), id="plain"), + pytest.param( + "vv", "error in view vv after rename: no such column: c", ("view", "vv"), id="suffix" + ), + pytest.param("a:b", "error in view a:b: no such module: m", ("view", "a:b"), id="colon"), + pytest.param("users", "error in view users: no such module: m", None, id="expected-table"), + pytest.param( + "USERS", "error in view USERS after rename: no such column: c", None, id="expected-case" + ), + pytest.param( + "ix_queue_fifo_in_seq", + "error in view ix_queue_fifo_in_seq: no such module: m", + None, + id="expected-index", + ), + pytest.param("vv", "error in table vv: no such module: m", None, id="a-table"), + pytest.param("vv", "error in view other: no such module: m", None, id="not-in-the-file"), + ], +) +async def test_the_foreign_object_is_matched_against_the_file( + tmp_path: Path, view_name: str, cause: str, found: tuple[str, str] | None +) -> None: from messagefoundry.store.schema_verify import _foreign_object - assert await _foreign_object("error in view vv: no such module: m") == ("view", "vv") - assert await _foreign_object("error in trigger tt: no such module: m") == ("trigger", "tt") - # A view that holds an expected table's or index's name is the incompatible store. - assert await _foreign_object("error in view users: no such module: m") is None - assert await _foreign_object("error in view IX_QUEUE_FIFO_IN_SEQ: no such module: m") is None - assert await _foreign_object("error in table users: no such module: m") is None + path = tmp_path / "named.db" + _sql(path, f'CREATE VIEW "{view_name}" AS SELECT 1 AS a') + async with _connected(path) as db: + assert await _foreign_object(db, cause) == found # --- BACKLOG #6720 item 1: a foreign view using an unloaded function or collation ---------------- From 506cf9e7a191232de257365f65cd3f360cfd8a7f Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sat, 21 Nov 2026 18:55:05 -0600 Subject: [PATCH 42/74] Release tests: repair round 1 from review round-fbcee73b _step_flags reads both the workflow and the script through _executed_shell, so a comment quoting an invocation is not taken for one and a comment-stripped guard still matches; its docstring no longer claims two tag guards share a script. _run_smoke drops PYTHONSAFEPATH and PYTHONPATH from the child env, so the flagless controls do not depend on the caller's environment. The positive control reuses the checkout path it built. The step-level gate test also sees env and steps contexts. The timeout comment says the per-test cap covers the whole test. The clause comment says a clause the doc carries twice is named only once both are gone. SUPPLY-CHAIN.md's one-approval bullet says the harness upload runs when its variable reads true. BACKLOG #1583, #2975. --- docs/SUPPLY-CHAIN.md | 3 +- tests/test_release_pipeline.py | 61 +++++++++++++++++++++++----------- 2 files changed, 43 insertions(+), 21 deletions(-) diff --git a/docs/SUPPLY-CHAIN.md b/docs/SUPPLY-CHAIN.md index ea37a44170..f80810776f 100644 --- a/docs/SUPPLY-CHAIN.md +++ b/docs/SUPPLY-CHAIN.md @@ -149,7 +149,8 @@ Facts the labels leave out: ([ADR 0201](adr/0201-a-messagefoundry-toolkit-distribution-carries-the-authoring-and-development-tooling-out-of-the-engine-wheel.md)). - **One approval per engine tag.** The toolkit, engine and harness uploads are steps of one `publish-pypi` job, so one approval of the `pypi` environment covers all three. The harness - upload runs only when the `PUBLISH_HARNESS` repository or organization variable is set. + upload runs only when the `PUBLISH_HARNESS` variable reads `true`; *The draft* below says what + a copy in the `pypi` environment does. - **The draft.** The engine's GitHub release stays a draft until the harness wheel is on it too, and until every upload `publish-pypi` runs has succeeded. With `PUBLISH_HARNESS` unset, that is the toolkit and the engine only. A separate job publishes it last, so no diff --git a/tests/test_release_pipeline.py b/tests/test_release_pipeline.py index f3c20e8ab3..ced9385db2 100644 --- a/tests/test_release_pipeline.py +++ b/tests/test_release_pipeline.py @@ -1205,7 +1205,8 @@ def _posix_tool_env() -> dict[str, str]: #: The timeout for a short subprocess here: a bash run of an extracted step, or a one-line probe. -#: It catches a hang. It does not measure speed: nothing in this file reads a duration. +#: It bounds a hang where nothing else does first. It does not measure speed: nothing in this file +#: reads a duration. #: #: WHY IT STAYS AT 60 S (BACKLOG #3633 item 2). That row records one overrun: on engine PR 2327's #: run 38674972250, `over-long-body[console]` took 84.5 s in notes.sh on windows-2025, and that @@ -1213,10 +1214,12 @@ def _posix_tool_env() -> dict[str, str]: #: Windows 11 dev box the test took about 1.6 s (measured 2026-11-21). Nothing here was measured on #: a windows-2025 runner. Raising this alone would not help. The CI test legs run pytest with a #: per-test `--timeout`, its matrix `pytest_timeout` in ci.yml: 60 s on ubuntu, 120 s on Windows. -#: With `--timeout-method=thread`, pytest-timeout ends the whole worker process when that fires, -#: rather than failing the one test with this call's output. So on ubuntu a value above 60 s is -#: never reached, and on Windows one above 120 s trades a named failure for a dead worker. Allowing -#: a longer stall needs the per-test cap raised too, for these tests or for the leg. +#: That cap covers the whole test, its setup and every call in it, and with +#: `--timeout-method=thread` pytest-timeout ends the whole worker process when it fires, rather +#: than failing the one test with this call's output. So on ubuntu the cap fires before this +#: timeout can, and on Windows a test that makes two such calls, as `over-long-body` does, can +#: reach the cap first even at this value. Allowing a longer stall needs the per-test cap raised, for +#: these tests or for the leg; this value would follow it. _HANG_TIMEOUT_S = 60 @@ -2123,17 +2126,20 @@ def _step_flags(script: str) -> tuple[str, ...]: Read from the workflow by the script's own text, so an execution test runs a smoke or a tag guard under the flags the step really uses (BACKLOG #1583). Before this, ``_run_smoke`` hardcoded ``-I``, so the intact checkout the acceptance keeps present could never answer: a - step that dropped ``-I`` would have left every execution test here green. Two steps may carry - the same script, the engine's and the toolkit's tag guards for one, so the flags of every copy - must agree, or no single answer exists. + step that dropped ``-I`` would have left every execution test here green. If two steps ever + feed the same script, the flags of every copy must agree, or no single answer exists. + + Both sides are read through :func:`_executed_shell`, so a comment quoting an invocation is not + taken for one, and a script extracted with or without its comment lines matches either way. """ + want = _executed_shell(script) found = { tuple(m.group("flags").split()) for job in _jobs().values() for step in (job.get("steps") or []) if isinstance(step, dict) - for m in _STDIN_HEREDOC.finditer(str(step.get("run") or "")) - if m.group("body") == script + for m in _STDIN_HEREDOC.finditer(_executed_shell(str(step.get("run") or "")) + "\n") + if m.group("body") == want } assert len(found) == 1, ( f"expected the script to be fed to exactly one interpreter flag list in release.yml, found " @@ -2162,10 +2168,14 @@ def _run_smoke( ``args`` follow the ``-``, as ``python -I - "$built" "$want"`` passes them to a tag guard. """ argv = [str(exe), *(_step_flags(script) if flags is None else flags), "-", *args] + # release.yml sets neither, and either one changes what a flagless control can reach: + # PYTHONSAFEPATH keeps the cwd off sys.path, PYTHONPATH adds another tree to it. + env = {k: v for k, v in os.environ.items() if k not in ("PYTHONSAFEPATH", "PYTHONPATH")} proc = subprocess.run( # noqa: S603 # nosec B603 - fixed argv, no shell, test-local paths argv, input=script.encode("utf-8"), cwd=str(workdir), + env=env, capture_output=True, timeout=120, ) @@ -2212,7 +2222,8 @@ def test_a_wheel_smoke_accepts_a_correctly_built_wheel( purelib, dist, pkg, _SMOKE_VERSION, package_files=_good_package(pkg, _SMOKE_VERSION) ) - rc, stdout, out = _run_smoke(exe, script, _intact_checkout(tmp_path / "checkout", pkg)) + work = _intact_checkout(tmp_path / "checkout", pkg) + rc, stdout, out = _run_smoke(exe, script, work) assert rc == 0, ( f"{job}'s smoke REJECTED a well-formed install, so every rejection below is measuring a " f"broken harness rather than the smoke.\n{out}" @@ -2232,7 +2243,6 @@ def test_a_wheel_smoke_accepts_a_correctly_built_wheel( # THE INTACT CHECKOUT IS LIVE (BACKLOG #1583's acceptance). The run above used the step's own # flags, so its pass shows those flags keep the checkout out only if the checkout would # otherwise get in. The same run without them must be refused for exactly that reason. - work = tmp_path / "checkout" rc, _stdout, out = _run_smoke(exe, script, work, flags=()) assert rc != 0 and "OUTSIDE the smoke venv" in out, ( f"without the step's flags ({' '.join(_step_flags(script)) or 'none'}) the intact checkout " @@ -4434,10 +4444,11 @@ def test_a_draft_publisher_refuses_while_the_variable_is_set_and_the_upload_did_ #: Clauses of that refusal which docs/SUPPLY-CHAIN.md, *The draft*, must carry too. Compared after #: :func:`_flat_text`, so the doc's backticks and line wraps do not count, and with the refusal's -#: `$GATE_NAME` read as the doc's "the variable". A clause listed here and dropped from either copy, -#: the organization prohibition among them, is named by the test below (vault BACKLOG #2975 item -#: 16). The list is not every clause: the publisher re-run step, for one, is worded differently in -#: the two copies and is not compared. +#: `$GATE_NAME` read as the doc's "the variable". The test below names a clause listed here once it +#: is gone from either copy, the organization prohibition among them (vault BACKLOG #2975 item 16). +#: Each is matched anywhere in the copy, so a clause the doc carries twice, such as "remove any +#: copy from the pypi environment", is named only once both are gone. The list is not every clause: +#: the publisher re-run step, for one, is worded differently in the two copies and is not compared. _DRAFT_REFUSAL_CLAUSES = ( "holds its own copy of the variable, with a value that is not true in any letter case", "a copy removed since", @@ -4496,6 +4507,10 @@ def test_the_draft_refusal_is_one_text_and_the_doc_carries_each_clause() -> None assert not missing, "\n".join(missing) +#: A context a step-level `if:` can read a variable through, directly or by way of an `env:` entry. +_STEP_GATE = re.compile(r"\b(?:vars|needs|env|steps)\b", flags=re.IGNORECASE) + + @pytest.mark.parametrize("publisher", [_PUBLISH_JOB, _CONSOLE_PUBLISH_JOB]) def test_no_step_of_a_draft_publisher_is_gated_on_a_variable(publisher: str) -> None: """The job-level walk, `_variable_gated_jobs`, reads no step's `if:` (vault BACKLOG #2975 item @@ -4507,11 +4522,17 @@ def test_no_step_of_a_draft_publisher_is_gated_on_a_variable(publisher: str) -> jobs = copy.deepcopy(_jobs()) steps = [s for s in jobs[publisher]["steps"] if isinstance(s, dict)] assert steps, f"{publisher} has no steps" - gated = [s.get("name") for s in steps if _is_variable_gated(s)] - assert not gated, f"{publisher} step(s) {gated} are gated on a variable; unset, they skip" + + def gated() -> list[object]: + # Wider than the job-level pattern: a step's `if:` can also read `env` and `steps`, and + # either can carry a variable in from the job's or an earlier step's `env:`. + return [s.get("name") for s in steps if _STEP_GATE.search(str(s.get("if") or ""))] + + assert not gated(), f"{publisher} step(s) {gated()} are gated on a variable; unset, they skip" publish = _release_step(jobs[publisher], "--draft=false") - publish["if"] = "vars.PUBLISH_HARNESS == 'true'" - assert [s.get("name") for s in steps if _is_variable_gated(s)] == [publish.get("name")] + for planted in ("vars.PUBLISH_HARNESS == 'true'", "env.GATE == 'true'"): + publish["if"] = planted + assert gated() == [publish.get("name")], planted # --- (14) every PyPI publish runs in a publish-only job that names `pypi` (vault BACKLOG #2631) ------ From d2ac472e923e71a263976a9367616754a77b6c5e Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sat, 21 Nov 2026 18:59:36 -0600 Subject: [PATCH 43/74] PR body leak scan: review round-9b1de443 repairs to the has-been form and clause ends BACKLOG #3364 (batch 455), step 11. "has ... been" takes negations and hedges in any order and any markup between its words ("has still not been met", "has _never_ been met"), and any markdown emphasis on the word that ends a modal's clause ("cannot pass *yet*"). Both only add hits. Two comments that called the invisible-character regroup "a third reading" now call it a further pass, since the third reading is the link-target one. Differential against origin/main db77b29597f's scanner on 3126 engine PR bodies plus tracked Markdown: 715 hits each, 0 lost, 0 gained. Proposed PR title: The PR body leak scan ends a table's ASVS mark at a blank line, reads one hedge list, and sees through emphasis and zero-width row edges (BACKLOG #3364) Proposed ledger banner #3364: PARTIAL. Step 9 fixed with quiet controls (a deliberate, listed drop against main). Step 11's underscore, zero-width and hedge-vocabulary remainder caught with must-fire tests and quiet controls. Step 8 has added must-fire pins; its false positive still fires. Still open: step 3 proposal 1, step 10, and step 11's version-lead and verdict-tail word-boundary sites, which only quiet. --- scripts/security/scan_forbidden.py | 17 +++++++++-------- tests/test_scan_forbidden.py | 10 ++++++++++ 2 files changed, 19 insertions(+), 8 deletions(-) diff --git a/scripts/security/scan_forbidden.py b/scripts/security/scan_forbidden.py index 06a9e63c53..fa86d1f9dd 100644 --- a/scripts/security/scan_forbidden.py +++ b/scripts/security/scan_forbidden.py @@ -503,8 +503,9 @@ #: (_PR_QUALIFIER). Lists kept apart drifted, so a word one place took unbound another (BACKLOG #8175 #: item 6): " has likely been met", " is only partial", " never stays partial". _PR_HEDGE = r"(?:likely|probably|still|now|also|only|then|already|so|never|yet|honestly|since)" -#: "has been" with an optional negation and any hedges between ("has since been", "hasn't yet been"). -_PR_HAS_BEEN = rf"(?:has|have|had)(?: not|n['\u2019]t)?(?: {_PR_HEDGE})* been" +#: "has been" with any negations and hedges between, in any order and any markup ("has since been", +#: "hasn't yet been", "has still not been", "has _never_ been"). +_PR_HAS_BEEN = rf"(?:has|have|had)(?:n['\u2019]t)?(?:{_PR_SEP}(?:not|{_PR_HEDGE}))*{_PR_SEP}been" #: The passive and negated forms ("were", "has been", "isn't", "has not been", "is no longer") bind an #: unmarked identifier only with a state verdict ending its clause (_pr_verdict_bound). _PR_STATE_VERB = ( @@ -557,8 +558,8 @@ #: preposition is not one: " will fail on the strict validator" is a verb and its phrase. _PR_VERDICT_END = re.compile( rf"(?i){_PR_FMT}(?:\s*(?:$|[.,;:!?)\]|])" - # Underscore emphasis on the word ("_yet_") does not hide it, as "\b" did. - rf"|\s+_{{0,2}}(?:yet|today|now|either|again|until|unless|because){_PR_EA})" + # Emphasis on the word ("_yet_", "*yet*", "`yet`") does not hide it, as "\b" hid "_yet_". + rf"|\s+{_PR_FMT}(?:yet|today|now|either|again|until|unless|because){_PR_EA})" ) #: A verb that states the verdict BEFORE the identifier: "does not meet ", "satisfies ASVS ", #: and the record's idiom for a requirement that does not pass yet, "an honest pass for ". "pass" @@ -612,9 +613,9 @@ #: one deleted, inside a word or a cell as well as around one, and keeps the hits of both readings. #: The deletion reaches the text the verdict, gap and map patterns read, not the line's kind: #: _pr_units decides a row, heading, list item or empty line from the line as written, so an -#: invisible character before a row's first pipe makes it a paragraph in both readings. A third -#: reading deletes them before the kinds are read (_pr_scan_reading). A fixed table, so an import -#: pays nothing for it. +#: invisible character before a row's first pipe makes it a paragraph in both passes. A further +#: pass of each reading deletes them before the kinds are read (_pr_scan_reading). A fixed table, +#: so an import pays nothing for it. _PR_DEFAULT_IGNORABLE = ( (0x00AD, 0x00AD), (0x034F, 0x034F), @@ -1410,7 +1411,7 @@ def _pr_scan_reading( if unit[1] != plain[1] or unit_asvs != plain_asvs or unit_loose != plain_loose: _pr_scan_unit(unit, unit_asvs, unit_loose, found, sentences, kinds) # The passes above read each line's kind as written, so an invisible character before a - # row's first pipe makes it a paragraph there. A third pass deletes every one before the + # row's first pipe makes it a paragraph there. A further pass deletes every one before the # kinds are read, so such a line is read as a row, with its own runs of rows. It only adds # hits; where it builds the units the second pass built, it would add none. regrouped = _pr_units([_PR_INVISIBLE.sub("", line) for line in lines], False, reading) diff --git a/tests/test_scan_forbidden.py b/tests/test_scan_forbidden.py index f21c9eb098..14e7fee2cd 100644 --- a/tests/test_scan_forbidden.py +++ b/tests/test_scan_forbidden.py @@ -1337,6 +1337,16 @@ def test_a_header_row_marks_only_its_own_table_and_column(sf) -> None: # Step 11: underscore emphasis on the word that ends a modal's clause. ("11", "verdict", f"{_REQ} cannot {_PASS} _yet_."), ("11", "verdict", f"{_REQ} will {_FAIL} _today_."), + ("11", "verdict", f"{_REQ} cannot {_PASS} *yet*."), + ("11", "verdict", f"{_REQ} will {_FAIL} **today**."), + ("11", "verdict", f"{_REQ} cannot {_PASS} `yet`."), + # Step 11: a hedge before the negation, and markup or extra space inside "has ... been". + ("11", "verdict", f"ASVS {_REQ} has still not been {_MET}."), + ("11", "verdict", f"ASVS {_REQ} has likely not been {_MET}."), + ("11", "verdict", f"ASVS {_REQ} has *likely* been {_MET}."), + ("11", "verdict", f"ASVS {_REQ} has _never_ been {_MET}."), + ("11", "verdict", f"ASVS {_REQ} has **not** been {_MET}."), + ("11", "verdict", f"ASVS {_REQ} has likely been {_MET}."), # Step 11: underscore emphasis on a cell's connective and on a list's "and". Main flags each # through the markup-deleted reading of the cell; these pin it. ("11", "verdict", f"| ASVS {_REQ} | the limb | {_PASS.title()} _until_ the fix |"), From 4feff2805e4d28c6823a030e09858fd3be083b53 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sat, 21 Nov 2026 19:02:29 -0600 Subject: [PATCH 44/74] Revocation census: the floor and pin comments claim no more than the tests catch Vault BACKLOG #3512, step 6, at the Manager's request after the unrepaired round round-b7dc85eb9c. The site floor's comment says twelve can go with no edit here, and that each still needs its census entry deleted. The _EXEMPT_SITES comment lists, as at least these, the downgrades no test here catches; the Guarded floor's comment points there and drops its outdated count. Proposed PR title: Revocation census pins its exempt sites and floors its membership tests; crypto residual names the via-token limit (BACKLOG #3512) Proposed banner: PARTIAL - step 6 built (exempt pin, membership floors; the _GUARDS floor was already met, by engine PRs 2544 and 2586). Step 12 declined as a design choice (via-token granularity or a sign/verify split), limit recorded in the crypto_operations residual. --- tests/test_revocation_guard_census.py | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/tests/test_revocation_guard_census.py b/tests/test_revocation_guard_census.py index 77bf508c08..0732e77e08 100644 --- a/tests/test_revocation_guard_census.py +++ b/tests/test_revocation_guard_census.py @@ -330,9 +330,12 @@ def __post_init__(self) -> None: #: The sites :data:`_CENSUS` lists as Exempt, pinned exactly (vault BACKLOG #3512). A Guarded hop #: moved to Exempt, with its guard call deleted, can pass every other check here (a relaxed hop #: fails its own census below), so this list is the second edit such a change needs. A diff that -#: edits both still passes, so review stays the check on what is added here. Nor is a Guarded -#: entry caught whose ``by`` is re-pointed at another function that calls a guard, in any module, -#: after its own guard call is deleted: that is one census edit, and only review sees it. +#: edits both still passes, so review stays the check on what is added here. At least these +#: downgrades pass every test in this file too, and only review sees them: a Guarded entry whose +#: ``by`` is re-pointed at another function that calls a guard, in any module, after its own guard +#: call is deleted; a hop rewritten to get its context from a name outside :data:`_BUILDERS`, so it +#: stops being a site and its entry is deleted; one of two guard calls deleted in a function that +#: guards two legs; and a guard call moved onto a branch that never runs. _EXEMPT_SITES = frozenset( { "messagefoundry/apiclient/client.py::_build_verify_context", @@ -466,7 +469,8 @@ def _scan() -> _Scan: def test_every_site_is_in_the_census() -> None: """The check that stops the next unguarded hop: a new site fails here until it is classified.""" sites = _scan().sites - # 42 sites when this floor was set (vault BACKLOG #3512), so 30 lets twelve go with no edit. + # 42 sites when this floor was set (vault BACKLOG #3512), so 30 lets twelve go with no edit + # here. Each retired site still needs its census entry deleted, by the test below. # It fails a scan that finds nothing, over which the check below would pass. assert len(sites) >= 30, f"the scan found only {len(sites)} sites, floor 30" unlisted = sorted(sites - _CENSUS.keys()) @@ -492,10 +496,10 @@ def test_every_census_entry_is_still_a_site() -> None: def test_every_guarded_site_calls_a_guard() -> None: scan = _scan() guarded = {site: entry for site, entry in _CENSUS.items() if isinstance(entry, Guarded)} - # 15 sites were Guarded when this floor was set, so 10 lets up to five retire with no edit here. - # It is a floor against a census emptied or turned all Exempt, over which the check below would - # pass on nothing. A single hop moved from Guarded to Exempt fails the test below; what that - # test does not catch is on _EXEMPT_SITES. + # A floor against a census emptied or turned all Exempt, over which the check below would pass + # on nothing. A single hop moved from Guarded to Exempt fails the next test unless + # _EXEMPT_SITES moves too; at least the downgrades listed on _EXEMPT_SITES are caught by + # neither. assert len(guarded) >= 10, f"only {len(guarded)} Guarded census entries, floor 10" unguarded = [ f"{site} (guard expected in {entry.by or 'the site itself'}; {entry.note or 'no note'})" From 19ce661e4c91d21bbd5f461c7ad0d5ef93e79bc9 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sat, 21 Nov 2026 19:04:06 -0600 Subject: [PATCH 45/74] State when the route-body step-up refusal writes its audit row The spend_step_up_action and refuse_unless_step_up_window_live docstrings said flatly that the refusal writes auth.gate_refused; it does only where the admitting proof_in_route gate wrote a grant row, and logs a WARNING with no admitting gate. The tests/_bound_proof.py note said a refused first try writes its grant row; it now names the rows each refusal writes. BACKLOG #1197 (ASVS 16.3.2). Proposed PR title: Route-body step-up refusals write an audit row (BACKLOG #1197) Proposed ledger banner for #1197: unchanged from the previous commit. --- messagefoundry/api/security.py | 8 ++++++-- tests/_bound_proof.py | 7 +++++-- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/messagefoundry/api/security.py b/messagefoundry/api/security.py index f397d3e1c9..cdd37f500a 100644 --- a/messagefoundry/api/security.py +++ b/messagefoundry/api/security.py @@ -2212,7 +2212,9 @@ async def spend_step_up_action(request: Request, action: str) -> None: (owner ruling 2026-10-13, #3241 R1), other than one in ``_EDIT_RESEND_SPENDING_REFUSALS`` in ``api/app.py`` (owner ruling 2026-11-07, #3241 added item 1). With no auth service attached it does nothing, as the dependency does. Its refusal writes ``auth.gate_refused`` - (:func:`_record_route_refusal`).""" + (:func:`_record_route_refusal`) only where the admitting ``proof_in_route`` gate wrote a grant + row, that is where :func:`_audited_permission` names a permission for the request. With no + admitting gate it logs a WARNING and writes no row.""" auth = get_auth(request) if auth is None: return @@ -2245,7 +2247,9 @@ async def refuse_unless_step_up_window_live(request: Request) -> None: call that branch would take no step-up at all. The 403 carries ``X-Step-Up-Required`` and no ``X-Step-Up-Action``, so a client refreshes the window with a plain ``POST /me/reauth``. Does nothing with no auth service attached, as the dependency then checks nothing. Its refusal - writes ``auth.gate_refused`` (:func:`_record_route_refusal`).""" + writes ``auth.gate_refused`` (:func:`_record_route_refusal`) only where the admitting + ``proof_in_route`` gate wrote a grant row, that is where :func:`_audited_permission` names a + permission for the request. With no admitting gate it logs a WARNING and writes no row.""" auth = get_auth(request) if auth is None or await step_up_window_live(request): return diff --git a/tests/_bound_proof.py b/tests/_bound_proof.py index e422ab3f6f..0518f964f1 100644 --- a/tests/_bound_proof.py +++ b/tests/_bound_proof.py @@ -16,8 +16,11 @@ password, a second refusal) is returned as the engine sent it. ``tests/test_bound_step_up_injection.py`` pins the gate itself. -THE REFUSED FIRST TRY IS A REAL REQUEST. It passed the permission check, so it wrote its grant -audit row and, for a write, charged the admin-write gap. A test that counts those rows or budgets, +THE REFUSED FIRST TRY IS A REAL REQUEST. It passed the permission check, so where the trail +records the request it wrote audit rows: an ``auth.gate_refused`` row where the gate refused it, +or, on a ``proof_in_route`` route (purge, reload, export, edit-resend) whose body refused the +spend, a grant row and then an ``auth.gate_refused`` row (BACKLOG #1197). For a write it also +charged the admin-write gap. A test that counts those rows or budgets, reads the re-keyed session afterwards, or runs under a deadline a password hash outlasts should prove up front with :func:`prove` instead, and a suite whose retry would be paced turns ``admin_write_min_interval_seconds`` off. From 64b7485b8c23bc7b12c8c3b2e4f1934bf5b50163 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sat, 21 Nov 2026 19:09:40 -0600 Subject: [PATCH 46/74] ADR 0019 quotes ADR 0138 on R3; the test is named a revert guard The first 2026-10-10 note said ADR 0138's 2026-10-07 amendment says who judges the record against R3. It names no one; it says "Whether this meets R3 is a scorecard call, not this amendment's", which the note now quotes. The test file and its two file-level tests are renamed to claim only a revert guard. --- docs/adr/0019-pluggable-keyprovider-hsm-kms-vault.md | 8 ++++---- ..._stated_once.py => test_adr_0019_0173_revert_guard.py} | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) rename tests/{test_adr_0019_0173_stated_once.py => test_adr_0019_0173_revert_guard.py} (96%) diff --git a/docs/adr/0019-pluggable-keyprovider-hsm-kms-vault.md b/docs/adr/0019-pluggable-keyprovider-hsm-kms-vault.md index 1e05c1bb87..a9ef1ed19c 100644 --- a/docs/adr/0019-pluggable-keyprovider-hsm-kms-vault.md +++ b/docs/adr/0019-pluggable-keyprovider-hsm-kms-vault.md @@ -666,10 +666,10 @@ lifetime is Vault's to version. The bound is a no-op there and for the identity > `enforce_transit_bound_attestation`, so "documented" now undersells it. The R3 ruling above > judged the precondition before that record existed. ADR 0138's 2026-10-07 amendment says how the > attestation is recorded and what the check does under each enforcement level. It also says what -> the check does not change, and who judges the record against R3. *(Corrected 2026-11-21, vault -> BACKLOG #1173: this note read "an operator attests to the precondition with `messagefoundry -> store attest-transit-bound`, and `Engine.start` reads that record" and "whether the record meets -> R3 is a scorecard call". The 2026-10-07 amendment states both.)* +> the check does not change. Whether the record meets R3 is, in that amendment's words, "a +> scorecard call, not this amendment's". *(Corrected 2026-11-21, vault BACKLOG #1173: this note +> read "an operator attests to the precondition with `messagefoundry store attest-transit-bound`, +> and `Engine.start` reads that record", which the 2026-10-07 amendment states.)* **Status: 11.3.4 — the bound is persisted, aggregated, alarmed and enforced.** As before, this ADR records the build and does not itself re-score; ADR 0115 / the ASVS-L3 re-score governs the sweep. diff --git a/tests/test_adr_0019_0173_stated_once.py b/tests/test_adr_0019_0173_revert_guard.py similarity index 96% rename from tests/test_adr_0019_0173_stated_once.py rename to tests/test_adr_0019_0173_revert_guard.py index b2a66b0346..2d76b7e6e2 100644 --- a/tests/test_adr_0019_0173_stated_once.py +++ b/tests/test_adr_0019_0173_revert_guard.py @@ -77,7 +77,7 @@ def test_each_refused_phrase_matches_the_removed_wording( assert phrase in _flat(old), phrase -def test_adr_0019_does_not_restate_the_transit_gate() -> None: +def test_adr_0019_does_not_revert_the_transit_gate_wording() -> None: text = _ADR_0019.read_text(encoding="utf-8") point_4 = _flat( _between( @@ -104,7 +104,7 @@ def test_adr_0019_does_not_restate_the_transit_gate() -> None: assert "enforce_transit_bound_attestation" in note -def test_adr_0173_odbc_amendment_does_not_restate_dates_or_versions() -> None: +def test_adr_0173_odbc_amendment_does_not_revert_its_opening_or_version_limit() -> None: text = _ADR_0173.read_text(encoding="utf-8") amendment = _between( text, From b4f454b102aeb0240b0bf79ccf462a10cae4950e Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sat, 21 Nov 2026 19:12:36 -0600 Subject: [PATCH 47/74] Revocation census: drop the downgrade list from the pin comments Vault BACKLOG #3512, step 6, at the Manager's request after review round-7dbcf5c611, which found the list claimed more than the code. The _EXEMPT_SITES comment now points to the module docstring's limits, and the Guarded floor's comment no longer refers to the list. Deletion only. Proposed PR title: Revocation census pins its exempt sites and floors its membership tests; crypto residual names the via-token limit (BACKLOG #3512) Proposed banner: PARTIAL - step 6 built (exempt pin, membership floors; the _GUARDS floor was already met, by engine PRs 2544 and 2586). Step 12 declined as a design choice (via-token granularity or a sign/verify split), limit recorded in the crypto_operations residual. --- tests/test_revocation_guard_census.py | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/tests/test_revocation_guard_census.py b/tests/test_revocation_guard_census.py index 0732e77e08..394efe9c04 100644 --- a/tests/test_revocation_guard_census.py +++ b/tests/test_revocation_guard_census.py @@ -330,12 +330,8 @@ def __post_init__(self) -> None: #: The sites :data:`_CENSUS` lists as Exempt, pinned exactly (vault BACKLOG #3512). A Guarded hop #: moved to Exempt, with its guard call deleted, can pass every other check here (a relaxed hop #: fails its own census below), so this list is the second edit such a change needs. A diff that -#: edits both still passes, so review stays the check on what is added here. At least these -#: downgrades pass every test in this file too, and only review sees them: a Guarded entry whose -#: ``by`` is re-pointed at another function that calls a guard, in any module, after its own guard -#: call is deleted; a hop rewritten to get its context from a name outside :data:`_BUILDERS`, so it -#: stops being a site and its entry is deleted; one of two guard calls deleted in a function that -#: guards two legs; and a guard call moved onto a branch that never runs. +#: edits both still passes, so review stays the check on what is added here. What this census +#: does not prove is in the module docstring. _EXEMPT_SITES = frozenset( { "messagefoundry/apiclient/client.py::_build_verify_context", @@ -498,8 +494,7 @@ def test_every_guarded_site_calls_a_guard() -> None: guarded = {site: entry for site, entry in _CENSUS.items() if isinstance(entry, Guarded)} # A floor against a census emptied or turned all Exempt, over which the check below would pass # on nothing. A single hop moved from Guarded to Exempt fails the next test unless - # _EXEMPT_SITES moves too; at least the downgrades listed on _EXEMPT_SITES are caught by - # neither. + # _EXEMPT_SITES moves too. assert len(guarded) >= 10, f"only {len(guarded)} Guarded census entries, floor 10" unguarded = [ f"{site} (guard expected in {entry.by or 'the site itself'}; {entry.note or 'no note'})" From 219d3f48f6d4c7e021c23f66bed6df5f255668b9 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sat, 21 Nov 2026 19:14:17 -0600 Subject: [PATCH 48/74] Server schema check: repair review round 2 findings BACKLOG #5062. From review round b1287bdb2e on 4bdacdd047d. Regressions against main repaired: a constraint named like a data word (delete, update, insert) kept its PRIMARY KEY; USING INDEX TABLESPACE on its own line is a storage option again; a PostgreSQL nested subscript a[b[1]] is not a bracketed name. Also: an opaque index's predicate is read through CASE ... ELSE ... END to its statement's end; a T-SQL IF [NOT] EXISTS ( guard ends an unterminated ADD; ALTER TABLE IF EXISTS #t and a CREATE TABLE with a line break before #tmp are temporary tables; a NOT NULL constraint name with a doubled quote, a doubled bracket or a dollar sign raises; the docstring names the :: and CAST cast forms that raise. The lane_leases test, which could not fail, is removed. Proposed PR title: Server schema check reads or refuses the DDL forms it misread; pin the keyless-chain serve-before-rotate-key stamp (BACKLOG #5062, #4942) Proposed banners: #5062 PARTIAL: items 3, 4 and 5 built except as left below; item 1 partly (DROP COLUMN over an opaque index, legacy DROP INDEX table.index, PRIMARY KEY in a CHECK literal, second CREATE TABLE, Postgres 18 NOT NULL built); item 2 partly (DATABASE_DEFAULT and CATALOG_DEFAULT, bracket-aware scanners, the default docstring premise built). Remains: skip_tables built from taken, an unguarded ALTER COLUMN, DDL in a literal no EXEC runs, EXEC-string cut clauses, ADD PRIMARY KEY against SET NOT NULL, cross-type default opclass, the first parse on the event loop, multi-token DEFAULT messages, scratch-schema altitude, the lower-cased refusal, a function-style cast key such as text(a), a second guarded CREATE INDEX of one name, the unpinned lane_leases drop, item 6, item 7's postgres.py rollback finding, the dead label branch, and test_store_schema_hash's cannot-fail assertion. #4942 PARTIAL: the open_store hook does not cover a serve start before any rotate-key run on a keyless chain; it still stamps, pinned by a test. Step 1's decision (warning alone, or refuse or hold) is the owner's. --- messagefoundry/store/server_schema_verify.py | 76 +++++++++++++++----- tests/test_server_schema_verify_5062.py | 76 +++++++++++++++++--- 2 files changed, 125 insertions(+), 27 deletions(-) diff --git a/messagefoundry/store/server_schema_verify.py b/messagefoundry/store/server_schema_verify.py index 2dce948190..5e08fd6df2 100644 --- a/messagefoundry/store/server_schema_verify.py +++ b/messagefoundry/store/server_schema_verify.py @@ -42,7 +42,7 @@ not match, an ``ALTER TABLE`` with more than one clause or an action it does not know, a table rename, an ``ALTER INDEX``, a second ``CREATE TABLE`` of a table no ``DROP`` removed, a ``USING`` access method, a key column or expression carrying a collation, an operator class or a ``NULLS`` order, a key -that opens with a cast of a column, a key built ``USING INDEX``, a SQL Server inline ``INDEX``, a +that opens with a ``::`` or ``CAST`` cast of a column, a key built ``USING INDEX``, a SQL Server inline ``INDEX``, a ``NOT NULL`` table constraint, a ``DROP COLUMN`` of a column an expression, ``INCLUDE`` or predicate of an index on its table may name, other than one of its key columns, a column type or clause it does not know, a SQL Server column that leaves its nullability to the session, ``COLLATE CATALOG_DEFAULT``, and a ``--`` or ``/*`` inside a @@ -123,7 +123,8 @@ re.I, ) _ALTER_TABLE = re.compile( - rf"\bALTER\s+TABLE\s+(?:IF\s+EXISTS\s+)?(?:ONLY\s+)?(?P
{_NAME})(?=\s)", re.I + rf"\bALTER\s+TABLE\s+(?!(?:IF\s+EXISTS\s+)?#)(?:IF\s+EXISTS\s+)?(?:ONLY\s+)?(?P
{_NAME})(?=\s)", + re.I, ) #: What may follow a DROP's last name: the statement's end, or a word that starts the next one. Any #: other text, such as ``DROP TABLE public . t``, leaves the strict pattern unmatched, so it raises. @@ -161,10 +162,10 @@ #: patterns above miss is counted and refused rather than silently left unchecked. A ``#`` temporary #: table is not the store's, behind an ``IF [NOT] EXISTS`` guard too. _LOOSE: Final = ( - (re.compile(r"\bCREATE\s+TABLE\s+(?!(?:IF\s+NOT\s+EXISTS\s+)?#)", re.I), _CREATE_TABLE), + (re.compile(r"\bCREATE\s+TABLE\s+(?!\s|(?:IF\s+NOT\s+EXISTS\s+)?#)", re.I), _CREATE_TABLE), (re.compile(r"\bCREATE\s+(?:UNIQUE\s+)?(?:(?:NON)?CLUSTERED\s+)?INDEX\b", re.I), _CREATE_INDEX), - (re.compile(r"\bALTER\s+TABLE\s+(?!(?:IF\s+EXISTS\s+)?#)", re.I), _ALTER_TABLE), - (re.compile(r"\bDROP\s+TABLE\s+(?!(?:IF\s+EXISTS\s+)?#)", re.I), _DROP_TABLE), + (re.compile(r"\bALTER\s+TABLE\s+(?!\s|(?:IF\s+EXISTS\s+)?#)", re.I), _ALTER_TABLE), + (re.compile(r"\bDROP\s+TABLE\s+(?!\s|(?:IF\s+EXISTS\s+)?#)", re.I), _DROP_TABLE), (re.compile(r"\bDROP\s+INDEX\b", re.I), _DROP_INDEX), (re.compile(r"\bsp_rename\b", re.I), _SP_RENAME), ) @@ -180,7 +181,7 @@ _TABLE_PRIMARY_KEY = re.compile(r"\bPRIMARY\s+KEY\s*(?:(?:NON)?CLUSTERED\s*)?\(", re.I) #: PostgreSQL's ``PRIMARY KEY`` or ``UNIQUE`` ``USING INDEX ``, which turns an existing index #: into the constraint. ``USING INDEX TABLESPACE`` is only a storage option. -_USING_INDEX = re.compile(r"\bUSING\s+INDEX\s+(?!TABLESPACE\b)", re.I) +_USING_INDEX = re.compile(r"\bUSING\s+INDEX\b(?!\s*TABLESPACE\b)", re.I) #: A key that opens with a cast of a column, ``a::text`` or ``CAST(a AS text)``. PostgreSQL stores #: a cast to the column's own type as the column, and any other as an expression, and the reader #: does not know which. @@ -202,6 +203,8 @@ #: Words that start a data statement, which a clause ends at unless ``ON`` precedes them (BACKLOG #: #5062: an ``ADD CONSTRAINT`` read on into the next statement took that statement's ``PRIMARY KEY`` #: as its own). +#: The words after which a data word is a name: a column's, a constraint's or a referenced table's. +_NAME_BEFORE = frozenset({"on", "add", "column", "exists", "constraint", "references"}) _DATA_STATEMENT = frozenset({"insert", "update", "delete", "merge", "select", "truncate"}) #: What an ``ALTER`` or ``DROP`` that starts the next statement names, after the word itself. _DDL_OBJECT = re.compile( @@ -340,7 +343,8 @@ def _quoted_end(text: str, i: int) -> int | None: """The index after the quoted run that opens at ``text[i]``: a ``'`` string, a ``"`` name or a SQL Server ``[...]`` name, in which a doubled close continues the run. ``None`` when ``text[i]`` opens none. :func:`_balanced`, :func:`_top_level_items` and :func:`_clause` share it, so a - ``[a,b]`` or ``[end]`` reads as one name in each.""" + ``[a,b]`` or ``[end]`` reads as one name in each. A ``[`` that holds another ``[``, or that no + ``]`` closes, is a PostgreSQL subscript, as in ``a[b[1]]``, and opens none.""" ch = text[i] if ch not in "'\"[": return None @@ -348,8 +352,10 @@ def _quoted_end(text: str, i: int) -> int | None: j = i + 1 while (end := text.find(close, j)) >= 0: if not text.startswith(close * 2, end): - return end + 1 + return None if ch == "[" and "[" in text[i + 1 : end] else end + 1 j = end + 2 + if ch == "[": + return None raise ValueError(f"unterminated quote in DDL near {text[i : i + 40]!r}") @@ -431,7 +437,7 @@ def _clause(segment: str) -> str: lower = word.group(0).lower() after = segment[i + len(word.group(0)) :] if lower in _STATEMENT_START and not ( - lower == "if" and re.match(r"\s+(?:NOT\s+)?EXISTS\b", after, re.I) + lower == "if" and re.match(r"\s+(?:NOT\s+)?EXISTS\b(?!\s*\()", after, re.I) ): break # A data or DDL statement starts here too. ON DELETE and ON UPDATE are a foreign @@ -439,7 +445,7 @@ def _clause(segment: str) -> str: # name; ALTER COLUMN and DROP COLUMN are the clause's own verbs. if ( lower == "create" - or (lower in _DATA_STATEMENT and prev not in ("on", "add", "column", "exists")) + or (lower in _DATA_STATEMENT and prev not in _NAME_BEFORE) or (lower in ("alter", "drop") and _DDL_OBJECT.match(after)) ): break @@ -450,6 +456,41 @@ def _clause(segment: str) -> str: return segment[:i].strip() +def _statement_end(text: str, start: int) -> int: + """Where the statement that ``text[start:]`` continues ends: a top-level ``;``, an unmatched + ``)``, a word that starts the next statement, or the end. Unlike :func:`_clause` it reads on + through ``ELSE`` and ``END``, which a ``CASE`` in an index predicate holds, so it may read into a + following block; reading too far only adds words, which raises more, never fewer.""" + depth, i = 0, start + while i < len(text): + if (end := _quoted_end(text, i)) is not None: + i = end + continue + ch = text[i] + if ch == "(": + depth += 1 + elif ch == ")": + if depth == 0: + break + depth -= 1 + elif depth == 0 and ch == ";": + break + elif depth == 0 and (ch.isalpha() or ch == "_") and not text[i - 1].isalnum(): + word = re.match(r"\w+", text[i:]) + assert word is not None + lower = word.group(0).lower() + if ( + lower in ("if", "begin", "exec", "execute", "declare", "go", "create") + or lower in _DATA_STATEMENT + or (lower in ("alter", "drop") and _DDL_OBJECT.match(text, i + len(lower))) + ): + break + i += len(lower) + continue + i += 1 + return i + + # The types each catalog spells one way, keyed by every spelling the DDL may use. The live read # compares against these spellings: PostgreSQL's format_type() and SQL Server's sys.types names. _PG_TYPES: Final = MappingProxyType( @@ -850,7 +891,11 @@ def _is_constraint(item: str, dialect: Dialect | None) -> bool: ``PERIOD`` and ``EXCLUDE`` when what follows is not their constraint's own shape, because each may also be a column's name. A ``NOT NULL`` table constraint raises: the reader does not apply it.""" - if re.match(r'(?:CONSTRAINT\s+(?:"[^"]*"|\[[^\]]*\]|\w+)\s+)?NOT\s+NULL\b', item, re.I): + if re.match( + r'(?:CONSTRAINT\s+(?:"(?:[^"]|"")*"|\[(?:[^\]]|\]\])*\]|[\w$]+)\s+)?NOT\s+NULL\b', + item, + re.I, + ): # PostgreSQL 18's NOT NULL table constraint, perhaps NOT VALID. raise ValueError(f"a not-null constraint is not compared: {item[:120]!r}") words = [w.lower() for w in _TOKEN.findall(item)[:2]] + [""] @@ -933,13 +978,8 @@ def index(self, text: str, m: re.Match[str]) -> None: self.indexes[name] = shape self.opaque.pop(name, None) if include or shape.partial or any(k.startswith("") for k in shape.columns): - # To the statement's end, found as an ALTER clause's is: a predicate has no - # closing mark of its own. - try: - tail = _clause(text[end:]) - except ValueError: # a top-level comma: read on to the end, which only raises more - tail = text[end:] - definition = text[m.end() : end] + " " + tail + # To the statement's end: a predicate has no closing mark of its own. + definition = text[m.end() : _statement_end(text, end)] self.opaque[name] = frozenset(_ident(w) for w in _TOKEN.findall(definition)) def _built(self, table: str, name: str, action: str) -> _Built: diff --git a/tests/test_server_schema_verify_5062.py b/tests/test_server_schema_verify_5062.py index d89a2f65ce..1ee742b59b 100644 --- a/tests/test_server_schema_verify_5062.py +++ b/tests/test_server_schema_verify_5062.py @@ -246,15 +246,6 @@ def test_a_not_null_table_constraint_raises(statements: tuple[str, ...]) -> None declared_schema(statements, "postgres") -def test_the_postgres_expected_shape_holds_no_table_the_migration_drops() -> None: - """The migration runs ``DROP TABLE IF EXISTS lane_leases`` outside the declared batch, so the - expected shape must not hold that table, or every open would report it missing.""" - postgres = pytest.importorskip( - "messagefoundry.store.postgres", reason="requires the postgres extra (asyncpg)" - ) - assert "lane_leases" not in postgres._declared_schema().columns - - # --- review round 1 ------------------------------------------------------------------------------ @@ -355,3 +346,70 @@ def test_an_unterminated_add_ends_at_an_alter_database() -> None: "sqlserver", ) assert shape.column_shapes["a"]["c"].nullable is True + + +# --- review round 2 ------------------------------------------------------------------------------ + + +def test_a_case_in_a_predicate_does_not_end_the_opaque_index_words() -> None: + with pytest.raises(ValueError, match="drop column"): + declared_schema( + ( + "CREATE TABLE t (a INT, b INT, c INT)", + "CREATE INDEX ix ON t (a) WHERE CASE WHEN b > 0 THEN 1 ELSE 0 END = 1" + " AND c IS NULL", + "ALTER TABLE t DROP COLUMN c", + ) + ) + + +@pytest.mark.parametrize("name", ["delete", "update", "insert"]) +def test_a_constraint_named_like_a_data_word_keeps_its_key(name: str) -> None: + shape = declared_schema( + ("CREATE TABLE t (id INT)", f"ALTER TABLE t ADD CONSTRAINT {name} PRIMARY KEY (id)"), + "postgres", + ) + assert shape.column_shapes["t"]["id"].nullable is False + + +def test_using_index_tablespace_on_its_own_line_is_a_storage_option() -> None: + shape = declared_schema( + ( + "CREATE TABLE t (a INT)", + "ALTER TABLE t ADD CONSTRAINT pk_t PRIMARY KEY (a) USING INDEX\n TABLESPACE fast", + ), + "postgres", + ) + assert shape.column_shapes["t"]["a"].nullable is False + + +def test_a_t_sql_if_exists_guard_ends_an_unterminated_add() -> None: + shape = declared_schema( + ( + "CREATE TABLE t (a INT NULL)", + "IF COL_LENGTH('t','y') IS NULL ALTER TABLE t ADD y INT NULL\n" + "IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = 'ix') CREATE INDEX ix ON t (a)", + ), + "sqlserver", + ) + assert shape.column_shapes["t"]["y"].nullable is True and "ix" in shape.named_indexes + + +def test_a_nested_subscript_is_not_a_bracketed_name() -> None: + shape = declared_schema(("CREATE INDEX ix ON t ((a[b[1]]))",)) + assert shape.named_indexes["ix"].columns == ("",) + + +@pytest.mark.parametrize( + "statement", + ["ALTER TABLE IF EXISTS #t ADD x INT NULL", "CREATE TABLE\n #tmp (x INT NULL)"], +) +def test_a_temporary_table_is_not_the_stores_in_any_spacing(statement: str) -> None: + shape = declared_schema(("CREATE TABLE t (a INT NULL)", statement), "sqlserver") + assert set(shape.columns) == {"t"} + + +@pytest.mark.parametrize("name", ['"x""y"', "nn$a", "[x]]y]"]) +def test_a_not_null_constraint_with_an_escaped_or_dollar_name_raises(name: str) -> None: + with pytest.raises(ValueError, match="not-null constraint"): + declared_schema((f"CREATE TABLE t (a INT, CONSTRAINT {name} NOT NULL a)",), "postgres") From 81b72c295b5b31173f9d5b47e2799b9c8dea669a Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sat, 21 Nov 2026 19:14:30 -0600 Subject: [PATCH 49/74] State the route-body refusal row rule once (SDS-3.5) The condition for the auth.gate_refused row a route-body step-up refusal writes is now stated only in the _record_route_refusal docstring; the _recorded_decision, spend_step_up_action and refuse_unless_step_up_window_live docstrings and the changelog fragment point to it. The tests/_bound_proof.py note drops its route list. BACKLOG #1197 (ASVS 16.3.2). Proposed PR title: Route-body step-up refusals write an audit row (BACKLOG #1197) Proposed ledger banner for #1197: unchanged from commit c5e3bb75ff0. --- ...197-route-body-step-up-refusal.security.md | 14 +++------ messagefoundry/api/security.py | 29 ++++++++----------- tests/_bound_proof.py | 3 +- 3 files changed, 17 insertions(+), 29 deletions(-) diff --git a/changelog.d/1197-route-body-step-up-refusal.security.md b/changelog.d/1197-route-body-step-up-refusal.security.md index bd45350535..3f36b4fe15 100644 --- a/changelog.d/1197-route-body-step-up-refusal.security.md +++ b/changelog.d/1197-route-body-step-up-refusal.security.md @@ -1,11 +1,5 @@ - **The step-up refusals of `spend_step_up_action` and `refuse_unless_step_up_window_live`, made - in a route body after its gate admitted the request, now write `auth.gate_refused`.** A - `proof_in_route` route's gate writes `auth.permission_granted`, and the route then spends the - bound proof (`spend_step_up_action`) or checks the session window - (`refuse_unless_step_up_window_live`). In the shipped code a refusal there left the grant row and - no row for the refusal. It still follows that grant row, and now also writes an - `auth.gate_refused` row naming the same permission and a `reason` of `step_up`, only where the - gate wrote its grant row. No request is allowed that was refused before. A refusal whose row - cannot be written answers with a server error instead of the 403, as a gate's own refusal already - does. Other refusals a route body makes after its gate passed, at least the reveal and pacing - refusals, still write no refusal row. (`BACKLOG #1197`) + in a route body after its `proof_in_route` gate admitted the request, can now write an + `auth.gate_refused` row.** In the shipped code they wrote no row of their own. + `_record_route_refusal` in `messagefoundry/api/security.py` says when the row is written. No + request is allowed that was refused before. (`BACKLOG #1197`) diff --git a/messagefoundry/api/security.py b/messagefoundry/api/security.py index cdd37f500a..aaed5df36f 100644 --- a/messagefoundry/api/security.py +++ b/messagefoundry/api/security.py @@ -1482,10 +1482,8 @@ async def _recorded_decision( A refusal row is written exactly where the grant row would have been, so a gate writes at most one decision row per request, and a gate that wrote no grant row writes no refusal row either. That keeps the per-request volume where the shipped trail already put it while the audit chain - has no drain (BACKLOG #1421). The step-up refusals of :func:`spend_step_up_action` and - :func:`refuse_unless_step_up_window_live`, made in a route body after a ``proof_in_route`` gate - admitted the request, add a second row through :func:`_record_route_refusal`; other refusals a - route body makes, at least the reveal and pacing ones, write none. The reason comes from the + has no drain (BACKLOG #1421). For a refusal a route body makes after its gate admitted the + request, see :func:`_record_route_refusal`. The reason comes from the :class:`_GateRefusal` the check raised. Any other exception leaves the block with no decision row from it, which is right for the :func:`_mfa_refusal` 403: it wrote its own ``auth.mfa_denied`` row where it was raised. A failed refusal-row write raises in place of the @@ -1533,11 +1531,13 @@ class _AdmittedDecision: async def _record_route_refusal(request: Request, refusal: _GateRefusal) -> None: """Record a step-up refusal a route body makes after its ``proof_in_route`` gate admitted it. - BACKLOG #1197 (ASVS 16.3.2). The gate has already written its grant row, so without this the - refusal of :func:`spend_step_up_action` or :func:`refuse_unless_step_up_window_live` left no - row. The row names the permission the gate's grant row named, through the same writer as the - gate's own refusals. A route that reaches here without such a gate writes no row, and says so - in the log; the caller raises the refusal either way.""" + BACKLOG #1197 (ASVS 16.3.2), for the refusals of :func:`spend_step_up_action` and + :func:`refuse_unless_step_up_window_live`. This is where the rule for their row is stated. It + writes ``auth.gate_refused``, through the writer the gate's own refusals use, only where the + admitting ``proof_in_route`` gate left its decision on ``request.state`` and + :func:`_audited_permission` names a permission for the request, which is where that gate wrote + its grant row. Where the gate wrote no grant row it writes none and logs nothing. With no + admitting gate it logs a WARNING and writes none. The caller raises the refusal either way.""" admitted = getattr(request.state, _ADMITTED_DECISION_ATTR, None) if not isinstance(admitted, _AdmittedDecision): log.warning( @@ -2211,10 +2211,7 @@ async def spend_step_up_action(request: Request, action: str) -> None: ``AuthService.refund_action_step_up``, as edit-resend does for a refusal before its store write (owner ruling 2026-10-13, #3241 R1), other than one in ``_EDIT_RESEND_SPENDING_REFUSALS`` in ``api/app.py`` (owner ruling 2026-11-07, #3241 added item 1). With no auth service attached it - does nothing, as the dependency does. Its refusal writes ``auth.gate_refused`` - (:func:`_record_route_refusal`) only where the admitting ``proof_in_route`` gate wrote a grant - row, that is where :func:`_audited_permission` names a permission for the request. With no - admitting gate it logs a WARNING and writes no row.""" + does nothing, as the dependency does. :func:`_record_route_refusal` records its refusal.""" auth = get_auth(request) if auth is None: return @@ -2246,10 +2243,8 @@ async def refuse_unless_step_up_window_live(request: Request) -> None: Moving a route to ``proof_in_route=True`` drops its dependency's window check, so without this call that branch would take no step-up at all. The 403 carries ``X-Step-Up-Required`` and no ``X-Step-Up-Action``, so a client refreshes the window with a plain ``POST /me/reauth``. Does - nothing with no auth service attached, as the dependency then checks nothing. Its refusal - writes ``auth.gate_refused`` (:func:`_record_route_refusal`) only where the admitting - ``proof_in_route`` gate wrote a grant row, that is where :func:`_audited_permission` names a - permission for the request. With no admitting gate it logs a WARNING and writes no row.""" + nothing with no auth service attached, as the dependency then checks nothing. + :func:`_record_route_refusal` records its refusal.""" auth = get_auth(request) if auth is None or await step_up_window_live(request): return diff --git a/tests/_bound_proof.py b/tests/_bound_proof.py index 0518f964f1..d93668cc0e 100644 --- a/tests/_bound_proof.py +++ b/tests/_bound_proof.py @@ -18,8 +18,7 @@ THE REFUSED FIRST TRY IS A REAL REQUEST. It passed the permission check, so where the trail records the request it wrote audit rows: an ``auth.gate_refused`` row where the gate refused it, -or, on a ``proof_in_route`` route (purge, reload, export, edit-resend) whose body refused the -spend, a grant row and then an ``auth.gate_refused`` row (BACKLOG #1197). For a write it also +or, on a ``proof_in_route`` route whose body refused the spend, a grant row and then an ``auth.gate_refused`` row (BACKLOG #1197). For a write it also charged the admin-write gap. A test that counts those rows or budgets, reads the re-keyed session afterwards, or runs under a deadline a password hash outlasts should prove up front with :func:`prove` instead, and a suite whose retry would be paced turns From 496b5eb94bf8d0ac81e149d333936f4d84550f28 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sat, 21 Nov 2026 19:17:54 -0600 Subject: [PATCH 50/74] Release tests and prose: repair round 2 from review round-158a82ef _step_flags counts every heredoc carrying the script and fails when an invocation it cannot parse would drop a copy out of the comparison. _run_probe drops PYTHONSAFEPATH too, so the bare arm does not depend on the caller's environment. The step-level gate pattern is built from the job-level one plus env, steps and inputs, and the test copies one job, not the whole workflow. docs/SUPPLY-CHAIN.md: the harness and console uploads run only when the variable reads true both where the build job reads it, outside the pypi environment, and where the upload reads it again, inside it; The draft says "does not run" and "while that read is true" where it said "set" and "unset". BACKLOG #1583, #2975. Proposed PR title: Release tests: smokes run under their step's flags, one draft refusal text, and SUPPLY-CHAIN.md draft-route fixes Proposed banners: #1583 SHIPPED: the intact-checkout arm is real; the execution tests run under the step's own flags and the positive control proves the checkout live. #3633 item 2: decided, not raised; the reason is recorded in tests/test_release_pipeline.py _HANG_TIMEOUT_S. Item 1 is not this branch's. #2975 PARTIAL: items 10, 11, 12, 16, 18, 21 built, item 17's SUPPLY-CHAIN.md part built; release.yml prose (17), 13 and the owner-reserved and other items stay open. --- docs/SUPPLY-CHAIN.md | 25 ++++++++++---------- tests/test_release_pipeline.py | 42 ++++++++++++++++++++++++---------- 2 files changed, 43 insertions(+), 24 deletions(-) diff --git a/docs/SUPPLY-CHAIN.md b/docs/SUPPLY-CHAIN.md index f80810776f..61dab5c091 100644 --- a/docs/SUPPLY-CHAIN.md +++ b/docs/SUPPLY-CHAIN.md @@ -149,17 +149,18 @@ Facts the labels leave out: ([ADR 0201](adr/0201-a-messagefoundry-toolkit-distribution-carries-the-authoring-and-development-tooling-out-of-the-engine-wheel.md)). - **One approval per engine tag.** The toolkit, engine and harness uploads are steps of one `publish-pypi` job, so one approval of the `pypi` environment covers all three. The harness - upload runs only when the `PUBLISH_HARNESS` variable reads `true`; *The draft* below says what - a copy in the `pypi` environment does. + upload runs only when the `PUBLISH_HARNESS` variable reads `true` twice: where its build job + reads it, outside the `pypi` environment, and where the upload reads it again, inside that + environment. - **The draft.** The engine's GitHub release stays a draft until the harness wheel is on it - too, and until every upload `publish-pypi` runs has succeeded. With `PUBLISH_HARNESS` unset, - that is the toolkit and the engine only. A separate job publishes it last, so no + too, and until every upload `publish-pypi` runs has succeeded. When the harness upload does not + run, that is the toolkit and the engine only. A separate job publishes it last, so no job adds an asset to a published release. The console's release is a draft too, at least until - its `publish-pypi-webconsole` job has succeeded. With `PUBLISH_WEBCONSOLE` set, that job uploads - the wheel first. Unset, the console upload is skipped and the console's release is still - published once the `pypi` approval is given, as the engine's is with `PUBLISH_HARNESS` unset. - With either variable set, its draft publisher reads it again when it runs and refuses to publish - the release unless that run's upload step succeeded. On an engine tag the toolkit and engine + its `publish-pypi-webconsole` job has succeeded. The console upload runs under the same two + reads of `PUBLISH_WEBCONSOLE`. When it does not run, the console's release is still published + once the `pypi` approval is given, as the engine's is without the harness upload. Each draft + publisher reads its variable again when it runs, outside the `pypi` environment, and while that + read is `true` it refuses to publish the release unless that run's upload step succeeded. On an engine tag the toolkit and engine are on PyPI by then. The refusal's text names two causes, a remedy with the upload and one without, but not which cause fired, and points here for the routes left past GitHub's re-run window. At least these two can fire, alone or together: @@ -227,9 +228,9 @@ has no SBOM of its own. Apart from that, every row but one covers the **engine** only. The exception is the PEP 740 row: every PyPI publish job in `release.yml` sets `attestations: true`. So the web console wheel (`messagefoundry-webconsole`) and the harness wheel get a PyPI-side attestation whenever their PyPI publish runs. Each of those -publishes runs only when its variable, `PUBLISH_WEBCONSOLE` or `PUBLISH_HARNESS`, reads `true`; -*The draft* above says what a copy in the `pypi` environment does. That is all they get: their -release jobs have no Sigstore, SBOM or SLSA step. +publishes runs only when its variable, `PUBLISH_WEBCONSOLE` or `PUBLISH_HARNESS`, reads `true` +both outside and inside the `pypi` environment, as *One approval per engine tag* and *The draft* +above say. That is all they get: their release jobs have no Sigstore, SBOM or SLSA step. Additional CycloneDX SBOMs — the **VS Code extension** (npm) and the **container image** (Debian base + system libs + installed Python) — are produced by the daily/​on-demand `security.yml` workflow and diff --git a/tests/test_release_pipeline.py b/tests/test_release_pipeline.py index ced9385db2..fabf83eb53 100644 --- a/tests/test_release_pipeline.py +++ b/tests/test_release_pipeline.py @@ -2118,6 +2118,9 @@ def _clone_venv(template: Path, root: Path) -> tuple[Path, Path]: re.S, ) +#: Any such heredoc, whatever its invocation, so :func:`_step_flags` can count the copies it read. +_ANY_HEREDOC = re.compile(r"<<'(?P[A-Z]+)'\n(?P.*?)\n(?P=tag)\n", re.S) + @functools.cache def _step_flags(script: str) -> tuple[str, ...]: @@ -2131,16 +2134,28 @@ def _step_flags(script: str) -> tuple[str, ...]: Both sides are read through :func:`_executed_shell`, so a comment quoting an invocation is not taken for one, and a script extracted with or without its comment lines matches either way. + Every heredoc carrying the script must have a readable invocation, so a copy whose header this + cannot parse fails here rather than dropping out of the comparison. """ want = _executed_shell(script) - found = { - tuple(m.group("flags").split()) + shells = [ + _executed_shell(str(step.get("run") or "")) + "\n" for job in _jobs().values() for step in (job.get("steps") or []) if isinstance(step, dict) - for m in _STDIN_HEREDOC.finditer(_executed_shell(str(step.get("run") or "")) + "\n") + ] + headers = [ + tuple(m.group("flags").split()) + for shell in shells + for m in _STDIN_HEREDOC.finditer(shell) if m.group("body") == want - } + ] + copies = sum(m.group("body") == want for shell in shells for m in _ANY_HEREDOC.finditer(shell)) + assert len(headers) == copies, ( + f"release.yml carries the script in {copies} heredoc(s) but {len(headers)} invocation(s) " + f"could be read; an unreadable one would run under flags nothing here checks" + ) + found = set(headers) assert len(found) == 1, ( f"expected the script to be fed to exactly one interpreter flag list in release.yml, found " f"{sorted(found)}: either no step feeds it on stdin any more, or two copies are run " @@ -3242,6 +3257,7 @@ def _run_probe( """ env = dict(os.environ) env.pop("PYTHONPATH", None) + env.pop("PYTHONSAFEPATH", None) # it keeps the cwd off sys.path, so the bare arm would fail if pythonpath is not None: env["PYTHONPATH"] = str(pythonpath) return subprocess.run( # noqa: S603 # nosec B603 - fixed argv, no shell, test-local paths @@ -4507,8 +4523,12 @@ def test_the_draft_refusal_is_one_text_and_the_doc_carries_each_clause() -> None assert not missing, "\n".join(missing) -#: A context a step-level `if:` can read a variable through, directly or by way of an `env:` entry. -_STEP_GATE = re.compile(r"\b(?:vars|needs|env|steps)\b", flags=re.IGNORECASE) +#: The job-level pattern plus the contexts only a step-level `if:` adds: `env` and `steps`, either of +#: which can carry a variable in from an `env:` entry, and `inputs`, which is empty on a tag push. +#: Wide on purpose: a `steps.` condition that reads no variable is flagged too. +_STEP_GATE = re.compile( + rf"{_VARIABLE_GATE.pattern}|\b(?:env|steps|inputs)\b", flags=_VARIABLE_GATE.flags +) @pytest.mark.parametrize("publisher", [_PUBLISH_JOB, _CONSOLE_PUBLISH_JOB]) @@ -4519,18 +4539,16 @@ def test_no_step_of_a_draft_publisher_is_gated_on_a_variable(publisher: str) -> positive control. Mutation: put `if: vars.PUBLISH_HARNESS == 'true'` on a draft publisher's step. Red here.""" - jobs = copy.deepcopy(_jobs()) - steps = [s for s in jobs[publisher]["steps"] if isinstance(s, dict)] + job = copy.deepcopy(_jobs()[publisher]) + steps = [s for s in job["steps"] if isinstance(s, dict)] assert steps, f"{publisher} has no steps" def gated() -> list[object]: - # Wider than the job-level pattern: a step's `if:` can also read `env` and `steps`, and - # either can carry a variable in from the job's or an earlier step's `env:`. return [s.get("name") for s in steps if _STEP_GATE.search(str(s.get("if") or ""))] assert not gated(), f"{publisher} step(s) {gated()} are gated on a variable; unset, they skip" - publish = _release_step(jobs[publisher], "--draft=false") - for planted in ("vars.PUBLISH_HARNESS == 'true'", "env.GATE == 'true'"): + publish = _release_step(job, "--draft=false") + for planted in ("vars.PUBLISH_HARNESS == 'true'", "env.GATE == 'true'", "inputs.go"): publish["if"] = planted assert gated() == [publish.get("name")], planted From 3a8c2f61ed505bb0c57d9633ded9fca5848752e3 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sat, 21 Nov 2026 19:21:20 -0600 Subject: [PATCH 51/74] PR body leak scan: a hedge after "will remain" keeps the modal strong BACKLOG #3364 (batch 455), step 11. Review round-8db67a27 repair. The single hedge list let the modal group take a hedge after its record verb ("will remain already partial"), and _PR_MODAL_STRONG only looked for stay/remain at the group's end, so the earlier commits of this branch lost hits main reports. That corrects their claim that the hedge change only adds hits. _PR_MODAL_STRONG now finds stay/remain as a word anywhere in the group, which also catches "will remain only partial", missed on main. The step 9 docstring and test comment no longer claim more than the code does. Differentials against origin/main db77b29597f's scanner: 3126 engine PR bodies plus tracked Markdown, 715 hits each, 0 lost, 0 gained; 180000 generated record-shaped bodies, 0 lost. Proposed PR title: The PR body leak scan ends a table's ASVS mark at a blank line, reads one hedge list, and sees through emphasis and zero-width row edges (BACKLOG #3364) Proposed ledger banner #3364: PARTIAL. Step 9 fixed with quiet controls, a deliberate, listed drop against main that weakens the control and needs a ruling. Step 11's underscore, zero-width and hedge-vocabulary remainder caught with must-fire tests and quiet controls. Step 8 has added must-fire pins; its false positive still fires. Still open: step 3 proposal 1, step 10, and step 11's version-lead and verdict-tail word-boundary sites, which only quiet. --- scripts/security/scan_forbidden.py | 10 ++++++---- tests/test_scan_forbidden.py | 15 +++++++++++++-- 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/scripts/security/scan_forbidden.py b/scripts/security/scan_forbidden.py index fa86d1f9dd..804edd5ece 100644 --- a/scripts/security/scan_forbidden.py +++ b/scripts/security/scan_forbidden.py @@ -552,8 +552,10 @@ rf"{_PR_PLAIN_QUALIFIER}{_PR_FMT}{_PR_VERDICT}" ) _PR_VERDICT_STATE_RE = re.compile(rf"(?i){_PR_VERDICT_STATE}") -#: A modal chained into a record verb (" will remain partial") is as strong as the verb alone. -_PR_MODAL_STRONG = re.compile(r"(?i)(?:stay|remain)$") +#: A modal chained into a record verb (" will remain partial") is as strong as the verb alone, +#: with or without a hedge after the verb (" will remain only partial"): the verb is searched as +#: a word anywhere in the modal group, not only at its end. +_PR_MODAL_STRONG = re.compile(r"(?i)(? will fail on the strict validator" is a verb and its phrase. _PR_VERDICT_END = re.compile( @@ -1258,8 +1260,8 @@ def _pr_loose_columns(units: _PrUnits, blanks: list[int]) -> list[set[int]]: A unit that is not a row ends this reading, as on main. So does a blank line (``blanks``, as _pr_lines counts one) between two rows once the header has had a data row: the pipe lines below - it are another block, which the header above does not name (BACKLOG #3364 step 9). This is the - one place the reading drops a mark main kept. A blank line above the first data row, or a + it are another block, which the header above does not name (BACKLOG #3364 step 9). That drops a + mark main kept, on purpose. A blank line above the first data row, or a quote-marker-only line anywhere, ends nothing, as on main: a header with no rows yet is read as heading the rows below it.""" columns: list[set[int]] = [] diff --git a/tests/test_scan_forbidden.py b/tests/test_scan_forbidden.py index 14e7fee2cd..24fa0c10ea 100644 --- a/tests/test_scan_forbidden.py +++ b/tests/test_scan_forbidden.py @@ -1347,6 +1347,16 @@ def test_a_header_row_marks_only_its_own_table_and_column(sf) -> None: ("11", "verdict", f"ASVS {_REQ} has _never_ been {_MET}."), ("11", "verdict", f"ASVS {_REQ} has **not** been {_MET}."), ("11", "verdict", f"ASVS {_REQ} has likely been {_MET}."), + # A hedge after the modal's record verb keeps it strong, beside an unmarked id or a version. + # The "already" pair is flagged by main and was lost by an earlier head of this branch. + ("11", "verdict", f"{_REQ} will remain already {_PARTIAL} for the parser"), + ( + "11", + "verdict", + f"Applies to lxml 5.1.1, which will remain already {_PARTIAL} for the parser", + ), + ("11", "verdict", f"{_REQ} will remain only {_PARTIAL} for the parser"), + ("11", "verdict", f"{_REQ} will stay still {_PARTIAL} for the parser"), # Step 11: underscore emphasis on a cell's connective and on a list's "and". Main flags each # through the markup-deleted reading of the cell; these pin it. ("11", "verdict", f"| ASVS {_REQ} | the limb | {_PASS.title()} _until_ the fix |"), @@ -1359,8 +1369,9 @@ def test_a_header_row_marks_only_its_own_table_and_column(sf) -> None: ] #: Step 9 (BACKLOG #3364): a blank line under an ASVS table that has had a data row ends the table, so #: the header no longer marks the headerless pipe block below it. Main flags each body at the line -#: given; head reports nothing. Each superset guard excuses exactly the (body, hit) pairs listed here -#: and no other, and the test below checks that each listed hit is really dropped. +#: given; head reports nothing. The constructed-body guard and the harvested-corpus guard excuse +#: exactly the (body, hit) pairs listed here and no other; the other guards excuse nothing. The +#: test below checks that each listed hit is really dropped. _PR_STEP9_DROPPED: list[tuple[str, int]] = [ *((f"{_HEAD}| a | b | c |\n{blank}\n{_ROW}", 5) for blank in ("", " ", "\r")), (f"{_HEAD}| a | b | c |\n\n\n{_ROW}", 6), From b9885c5508804a0bd2ec4c9a35c1315297ea31d6 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sat, 21 Nov 2026 19:33:00 -0600 Subject: [PATCH 52/74] Release prose: delete two false sentences found by review round-27c1bfaf docs/SUPPLY-CHAIN.md, The draft: deleted the claim that the console's release is still published once the pypi approval is given when its upload does not run; with a non-true pypi environment copy the publisher refuses instead. The _HANG_TIMEOUT_S comment no longer says the timeout bounds a hang where nothing else does first; it says that on Windows it does not bound a grandchild still holding the pipes. BACKLOG #2975, #3633. --- docs/SUPPLY-CHAIN.md | 7 +++---- tests/test_release_pipeline.py | 4 ++-- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/docs/SUPPLY-CHAIN.md b/docs/SUPPLY-CHAIN.md index 61dab5c091..96e2287d94 100644 --- a/docs/SUPPLY-CHAIN.md +++ b/docs/SUPPLY-CHAIN.md @@ -157,10 +157,9 @@ Facts the labels leave out: run, that is the toolkit and the engine only. A separate job publishes it last, so no job adds an asset to a published release. The console's release is a draft too, at least until its `publish-pypi-webconsole` job has succeeded. The console upload runs under the same two - reads of `PUBLISH_WEBCONSOLE`. When it does not run, the console's release is still published - once the `pypi` approval is given, as the engine's is without the harness upload. Each draft - publisher reads its variable again when it runs, outside the `pypi` environment, and while that - read is `true` it refuses to publish the release unless that run's upload step succeeded. On an engine tag the toolkit and engine + reads of `PUBLISH_WEBCONSOLE`. Each draft publisher reads its variable again when it runs, + outside the `pypi` environment, and while that read is `true` it refuses to publish the + release unless that run's upload step succeeded. On an engine tag the toolkit and engine are on PyPI by then. The refusal's text names two causes, a remedy with the upload and one without, but not which cause fired, and points here for the routes left past GitHub's re-run window. At least these two can fire, alone or together: diff --git a/tests/test_release_pipeline.py b/tests/test_release_pipeline.py index fabf83eb53..68fa6f6939 100644 --- a/tests/test_release_pipeline.py +++ b/tests/test_release_pipeline.py @@ -1205,8 +1205,8 @@ def _posix_tool_env() -> dict[str, str]: #: The timeout for a short subprocess here: a bash run of an extracted step, or a one-line probe. -#: It bounds a hang where nothing else does first. It does not measure speed: nothing in this file -#: reads a duration. +#: It does not measure speed: nothing in this file reads a duration. On Windows it does not bound +#: a grandchild that still holds the pipes. #: #: WHY IT STAYS AT 60 S (BACKLOG #3633 item 2). That row records one overrun: on engine PR 2327's #: run 38674972250, `over-long-body[console]` took 84.5 s in notes.sh on windows-2025, and that From f5a2eb384593a78f887c0f8eb9ac1eae0c47cca0 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sat, 21 Nov 2026 19:36:11 -0600 Subject: [PATCH 53/74] Server schema check: repair the three round-3 regressions against main BACKLOG #5062. The unrepaired review round 70b595c736 on 219d3f48f6d found three forms origin/main read or refused that this branch broke: - DROP TABLE IF EXISTS #tmp, u matched neither pattern, so the drop of u was ignored; the loose pattern now skips only a lone temporary name, and the list raises again, as on main. - A partial or INCLUDE index inside an EXEC string raised "unterminated quote"; its tail is now read within the string, quotes undoubled. - RENAME COLUMN a TO update raised; "to" now precedes a name. The module docstring no longer lists a DROP COLUMN over an opaque index among the forms that always raise: it says the word search can miss a name. The _DATA_STATEMENT comment is moved to its constant and corrected. Proposed PR title: Server schema check reads or refuses the DDL forms it misread; pin the keyless-chain serve-before-rotate-key stamp (BACKLOG #5062, #4942) Proposed banners: as in 219d3f48f6d's body, with round 3's remaining open findings added to #5062's remainder. --- messagefoundry/store/server_schema_verify.py | 46 ++++++++++++-------- tests/test_server_schema_verify_5062.py | 29 ++++++++++++ 2 files changed, 58 insertions(+), 17 deletions(-) diff --git a/messagefoundry/store/server_schema_verify.py b/messagefoundry/store/server_schema_verify.py index 5e08fd6df2..39c758e824 100644 --- a/messagefoundry/store/server_schema_verify.py +++ b/messagefoundry/store/server_schema_verify.py @@ -42,14 +42,17 @@ not match, an ``ALTER TABLE`` with more than one clause or an action it does not know, a table rename, an ``ALTER INDEX``, a second ``CREATE TABLE`` of a table no ``DROP`` removed, a ``USING`` access method, a key column or expression carrying a collation, an operator class or a ``NULLS`` order, a key -that opens with a ``::`` or ``CAST`` cast of a column, a key built ``USING INDEX``, a SQL Server inline ``INDEX``, a -``NOT NULL`` table constraint, a ``DROP COLUMN`` of a column an expression, ``INCLUDE`` or predicate -of an index on its table may name, other than one of its key columns, a column type or clause it does not know, a SQL Server column that -leaves its nullability to the session, ``COLLATE CATALOG_DEFAULT``, and a ``--`` or ``/*`` inside a -quoted string, which may be dynamic SQL's comment or a literal's text. A unit test reads each shipped -batch, so a new form fails there before it reaches an open. Not every misread raises: at least DDL -text inside a string literal is read as run, and an ``ALTER COLUMN`` is read as reaching only an older -store, whether or not either holds (BACKLOG #5062). +that opens with a ``::`` or ``CAST`` cast of a column, a key built ``USING INDEX``, a SQL Server +inline ``INDEX``, a ``NOT NULL`` table constraint, a column type or clause it does not know, a SQL +Server column that leaves its nullability to the session, ``COLLATE CATALOG_DEFAULT``, and a ``--`` +or ``/*`` inside a quoted string, which may be dynamic SQL's comment or a literal's text. A unit test +reads each shipped batch, so a new form fails there before it reaches an open. + +Not every misread raises (BACKLOG #5062). At least: DDL text inside a string literal is read as run, +and an ``ALTER COLUMN`` is read as reaching only an older store, whether or not either holds. A +``DROP COLUMN`` raises where the reader finds the column's name among the words of an expression, +``INCLUDE`` or partial index on its table, other than as a key column, but that word search can miss +a name, so a ``DROP COLUMN`` that should raise may instead keep an index PostgreSQL drops. What is NOT compared includes at least: a column's default, other than whether PostgreSQL's is a ``nextval()`` call, which reads as numbering; a PostgreSQL column's collation; constraint indexes (a @@ -160,12 +163,13 @@ ) #: Every place a table or an index is created, dropped or renamed, read loosely, so a form the #: patterns above miss is counted and refused rather than silently left unchecked. A ``#`` temporary -#: table is not the store's, behind an ``IF [NOT] EXISTS`` guard too. +#: table is not the store's, behind an ``IF [NOT] EXISTS`` guard too, but a guarded ``DROP TABLE`` +#: whose list goes on past it is counted, as on any other list the strict pattern cannot read. _LOOSE: Final = ( (re.compile(r"\bCREATE\s+TABLE\s+(?!\s|(?:IF\s+NOT\s+EXISTS\s+)?#)", re.I), _CREATE_TABLE), (re.compile(r"\bCREATE\s+(?:UNIQUE\s+)?(?:(?:NON)?CLUSTERED\s+)?INDEX\b", re.I), _CREATE_INDEX), (re.compile(r"\bALTER\s+TABLE\s+(?!\s|(?:IF\s+EXISTS\s+)?#)", re.I), _ALTER_TABLE), - (re.compile(r"\bDROP\s+TABLE\s+(?!\s|(?:IF\s+EXISTS\s+)?#)", re.I), _DROP_TABLE), + (re.compile(r"\bDROP\s+TABLE\s+(?!\s|#|IF\s+EXISTS\s+#\w++(?!\s*,))", re.I), _DROP_TABLE), (re.compile(r"\bDROP\s+INDEX\b", re.I), _DROP_INDEX), (re.compile(r"\bsp_rename\b", re.I), _SP_RENAME), ) @@ -200,11 +204,12 @@ #: The words a statement inside a block starts with, at which an ``ALTER TABLE`` clause has ended #: when no ``;`` closes it. None can appear inside a column definition. _STATEMENT_START = frozenset({"if", "begin", "end", "exec", "execute", "else", "declare", "go"}) -#: Words that start a data statement, which a clause ends at unless ``ON`` precedes them (BACKLOG -#: #5062: an ``ADD CONSTRAINT`` read on into the next statement took that statement's ``PRIMARY KEY`` -#: as its own). -#: The words after which a data word is a name: a column's, a constraint's or a referenced table's. -_NAME_BEFORE = frozenset({"on", "add", "column", "exists", "constraint", "references"}) +#: The words after which a data word is a name: a column's, a constraint's, a referenced table's +#: or a rename's new name. After ``ON`` it is a foreign key's action. +_NAME_BEFORE = frozenset({"on", "add", "column", "exists", "constraint", "references", "to"}) +#: Words that start a data statement, which a clause ends at unless a word in ``_NAME_BEFORE`` +#: precedes them (BACKLOG #5062: an ``ADD CONSTRAINT`` read on into the next statement took that +#: statement's ``PRIMARY KEY`` as its own). _DATA_STATEMENT = frozenset({"insert", "update", "delete", "merge", "select", "truncate"}) #: What an ``ALTER`` or ``DROP`` that starts the next statement names, after the word itself. _DDL_OBJECT = re.compile( @@ -978,8 +983,15 @@ def index(self, text: str, m: re.Match[str]) -> None: self.indexes[name] = shape self.opaque.pop(name, None) if include or shape.partial or any(k.startswith("") for k in shape.columns): - # To the statement's end: a predicate has no closing mark of its own. - definition = text[m.end() : _statement_end(text, end)] + # To the statement's end: a predicate has no closing mark of its own. Inside an + # EXEC string, to the string's end, its quotes undoubled, as alter() reads one. + tail = text[end:] + for start, stop in _string_spans(text): + if start < m.start() < stop: + tail = text[end : stop - 1].replace("''", "'") + break + tail = " " + tail # so the scan never starts at index 0 + definition = text[m.end() : end] + tail[: _statement_end(tail, 1)] self.opaque[name] = frozenset(_ident(w) for w in _TOKEN.findall(definition)) def _built(self, table: str, name: str, action: str) -> _Built: diff --git a/tests/test_server_schema_verify_5062.py b/tests/test_server_schema_verify_5062.py index 1ee742b59b..b7a0355bd7 100644 --- a/tests/test_server_schema_verify_5062.py +++ b/tests/test_server_schema_verify_5062.py @@ -413,3 +413,32 @@ def test_a_temporary_table_is_not_the_stores_in_any_spacing(statement: str) -> N def test_a_not_null_constraint_with_an_escaped_or_dollar_name_raises(name: str) -> None: with pytest.raises(ValueError, match="not-null constraint"): declared_schema((f"CREATE TABLE t (a INT, CONSTRAINT {name} NOT NULL a)",), "postgres") + + +# --- review round 3 repair: regressions against main ----------------------------------------------- + + +def test_a_guarded_drop_whose_list_goes_on_past_a_temporary_table_raises() -> None: + with pytest.raises(ValueError, match="cannot read"): + declared_schema(("CREATE TABLE u (a INT NULL)", "DROP TABLE IF EXISTS #tmp, u")) + + +@pytest.mark.parametrize( + ("statement", "partial"), + [ + ("IF COL_LENGTH('t','b') IS NOT NULL EXEC('CREATE INDEX ix ON t (a) WHERE b > 0')", True), + ("EXEC('CREATE INDEX ix ON t (a) INCLUDE (b)')", False), + ("EXEC('CREATE INDEX ix ON t (a) WHERE b <> ''x''')", True), + ], +) +def test_an_opaque_index_inside_an_exec_string_is_read(statement: str, partial: bool) -> None: + shape = declared_schema(("CREATE TABLE t (a INT NULL, b INT NULL)", statement), "sqlserver") + assert shape.named_indexes["ix"].partial is partial + + +@pytest.mark.parametrize("name", ["update", "delete", "insert"]) +def test_a_rename_to_a_data_word_is_read(name: str) -> None: + shape = declared_schema( + ("CREATE TABLE t (a INT)", f"ALTER TABLE t RENAME COLUMN a TO {name}"), "postgres" + ) + assert shape.columns["t"] == frozenset({name}) From 8cb1ccf372b5d1119511e09e6ddd072ae1a05966 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sat, 21 Nov 2026 19:45:33 -0600 Subject: [PATCH 54/74] PR body leak scan: revert the step 9 blank-line reset, so no hit main reports is dropped BACKLOG #3364 (batch 455), step 9. Manager decision under the owner's standing instruction of 2026-10-22: take the strictly safer option. _pr_loose_columns is main's again, and a blank line between rows ends nothing in the loose reading. The step 9 tests, _PR_STEP9_DROPPED and the superset-guard exceptions are gone, and main's step 9 must-fire pins are back. The floor comment and the scan_pr_body docstring now say the baseline strips quote markers, reads links and splits sentences as main did, not that it reads every line as main did. Differential against origin/main's scanner (unchanged since db77b29597f): 3127 engine PR bodies, 267 hits each; 874 tracked Markdown files, 448 hits each; 0 lost, 0 gained. Proposed PR title: The PR body leak scan reads one hedge list and sees through emphasis and zero-width row edges (BACKLOG #3364) Proposed ledger banner #3364: PARTIAL. Step 11's underscore, zero-width and hedge-vocabulary remainder caught with must-fire tests and quiet controls. Step 8 has added must-fire pins; its false positive still fires. Step 9 left: blank-line carry, a fix would drop hits; needs an owner ruling. Still open: step 3 proposal 1, step 10, and step 11's version-lead and verdict-tail word-boundary sites, which only quiet. --- scripts/security/scan_forbidden.py | 58 ++++++++++++++---------------- tests/test_scan_forbidden.py | 57 ++++++++--------------------- 2 files changed, 41 insertions(+), 74 deletions(-) diff --git a/scripts/security/scan_forbidden.py b/scripts/security/scan_forbidden.py index 804edd5ece..0bd8fb034a 100644 --- a/scripts/security/scan_forbidden.py +++ b/scripts/security/scan_forbidden.py @@ -797,16 +797,16 @@ #: GitHub ``blob/8.1.8/CHANGES.rst`` link is a version and a path, never a map. #: Starts only at the first digit of a run, so a long run of digits is read once, not once per digit. _PR_TARGET_NUMBER = re.compile(r"(?\s?)+") #: The lookahead class of main's full-stop split. _PR_BASE_SPLIT_LOOKAHEAD = frozenset("ABCDEFGHIJKLMNOPQRSTUVWXYZ*`[(\"'#>-") @@ -1186,7 +1186,7 @@ def _pr_table_starts( else, a lone ">" between rows does not end the run, as main read no blank line at all. These runs bound only the GFM reading (_pr_table_columns), whose columns can only add marks; the - loose reading (_pr_loose_columns) does not read them.""" + loose reading (_pr_loose_columns), which keeps every mark main kept, does not read them.""" starts = [] # Whether every row since the last unit that is not a row opens with a quote marker. @@ -1254,29 +1254,24 @@ def _pr_table_columns(units: _PrUnits, starts: list[bool]) -> list[set[int]]: return columns -def _pr_loose_columns(units: _PrUnits, blanks: list[int]) -> list[set[int]]: +def _pr_loose_columns(units: _PrUnits) -> list[set[int]]: """For each unit, the ASVS columns as main read them, united with the GFM reading above: every - row above a dash-shaped unit is re-read as a header, and its cells are split at every pipe. - - A unit that is not a row ends this reading, as on main. So does a blank line (``blanks``, as - _pr_lines counts one) between two rows once the header has had a data row: the pipe lines below - it are another block, which the header above does not name (BACKLOG #3364 step 9). That drops a - mark main kept, on purpose. A blank line above the first data row, or a - quote-marker-only line anywhere, ends nothing, as on main: a header with no rows yet is read as - heading the rows below it.""" + row above a dash-shaped unit is re-read as a header, and its cells are split at every pipe. Only + a unit that is not a row ends this reading, as on main, so a blank line or a quote-marker-only + line between rows ends nothing here and every mark main kept is kept. Step 9, which ended this + reading at such a line, was removed; the false positive it quieted stays open on BACKLOG #3364.""" columns: list[set[int]] = [] current: set[int] = set() - # Whether a data row has been read under the current header. - has_rows = False - for index, (marks, text, is_row) in enumerate(units): - # A data row above implies the unit above is a row, as any other unit clears it. - if not is_row or (has_rows and _pr_between(blanks, units[index - 1][0][0][1], marks[0][1])): - current, has_rows = set(), False - if is_row and not _pr_is_delimiter(text): - if index + 1 < len(units) and _pr_is_delimiter(units[index + 1][1]): - current, has_rows = _pr_asvs_columns(text, loose=True), False - elif current: - has_rows = True + for index, (_, text, is_row) in enumerate(units): + if not is_row: + current = set() + if ( + is_row + and not _pr_is_delimiter(text) + and index + 1 < len(units) + and _pr_is_delimiter(units[index + 1][1]) + ): + current = _pr_asvs_columns(text, loose=True) columns.append(current) return columns @@ -1335,8 +1330,9 @@ def scan_pr_body(body: str) -> list[str]: Reasons only, never the matched text. One hit per kind per LINE: sentences of one paragraph that restate a verdict on the same line report it once, rather than storming. - Read three times, and the hits are the union (BACKLOG #5582). The baseline reads the lines as - origin/main did before BACKLOG #5582 (see ``_PR_BASE_QUOTE``). The second reads each link as its text and each inline tag as no + Read three times, and the hits are the union (BACKLOG #5582). The baseline strips quote markers, + reads links and splits sentences as origin/main did before BACKLOG #5582 (see + ``_PR_BASE_QUOTE``). The second reads each link as its text and each inline tag as no edge, and the third keeps each link's target beside it, so a code path only a target names is seen; from the third only a map counts. Each reading builds its own units from one line model (:func:`_pr_lines`), so every reading keeps each line where it was and the hits merge by (line, @@ -1377,7 +1373,7 @@ def _pr_scan_units( """Scan every unit with its own runs of rows and columns; return the runs and both columns.""" starts = _pr_table_starts(units, *gfm) asvs = _pr_table_columns(units, starts) - loose = _pr_loose_columns(units, gfm[0]) + loose = _pr_loose_columns(units) for unit, unit_asvs, unit_loose in zip(units, asvs, loose, strict=True): _pr_scan_unit(unit, unit_asvs, unit_loose, found, sentences, kinds) return starts, asvs, loose @@ -1404,7 +1400,7 @@ def _pr_scan_reading( for unit, unit_asvs, unit_loose, plain, plain_asvs, plain_loose in zip( deleted, _pr_table_columns(deleted, starts), - _pr_loose_columns(deleted, gfm[0]), + _pr_loose_columns(deleted), units, asvs, loose, diff --git a/tests/test_scan_forbidden.py b/tests/test_scan_forbidden.py index 24fa0c10ea..f09b4fd1b8 100644 --- a/tests/test_scan_forbidden.py +++ b/tests/test_scan_forbidden.py @@ -1236,8 +1236,14 @@ def test_a_header_row_marks_only_its_own_table_and_column(sf) -> None: ), ("9", "verdict", f"> | ASVS | Note | Result |\n>\n> |---|---|---|\n> {_ROW}"), ("9", "verdict", f"> {_HEAD.replace(chr(10), chr(10) + '> ')}\n> {_ROW}"), - # Step 9 ends the header's mark only at a blank line under a data row (_PR_STEP9_DROPPED). A - # quote-marker-only line between quoted data rows ends nothing, as main reads it. + # Step 9 is removed: a blank line, or a quote-marker-only line in a quoted table, between data + # rows ends nothing, so the header still marks the rows below it, as main reads it. The first + # body is the one step 9 quieted; its false positive stays open on BACKLOG #3364. + *( + ("9", "verdict", f"{_HEAD}| a | b | c |\n{blank}\n{_ROW}") + for blank in ("", " ", "\n", "\r") + ), + ("9", "verdict", f"{_HEAD}| a | b | c |\r\n\r\n{_ROW}"), *( ( "9", @@ -1311,9 +1317,7 @@ def test_a_header_row_marks_only_its_own_table_and_column(sf) -> None: # A marked identifier is never exempt. ("10", "verdict", f"ASVS {_REQ}: the row is not failing but stays {_PARTIAL}."), ("10", "verdict", f"| ASVS {_REQ} | the parser | is never failing; the cell is failing |"), - # Step 9's must-fire controls: a blank line ends a header's mark only under a data row. A dash - # placeholder is no data row, and a block below the blank line that marks its own id or has its - # own ASVS header still binds. + # A blank line after a dash placeholder row, or between ASVS tables, ends nothing either. ("9", "verdict", f"{_HEAD}| - | - | - |\n\n{_ROW}"), ( "9", @@ -1367,38 +1371,6 @@ def test_a_header_row_marks_only_its_own_table_and_column(sf) -> None: ("11", "verdict", f"| ASVS | Note | Result |\n{chr(0x200B)}|---|---|---|\n{_ROW}"), ("11", "verdict", f"{chr(0x200B)}{_HEAD}{_ROW}"), ] -#: Step 9 (BACKLOG #3364): a blank line under an ASVS table that has had a data row ends the table, so -#: the header no longer marks the headerless pipe block below it. Main flags each body at the line -#: given; head reports nothing. The constructed-body guard and the harvested-corpus guard excuse -#: exactly the (body, hit) pairs listed here and no other; the other guards excuse nothing. The -#: test below checks that each listed hit is really dropped. -_PR_STEP9_DROPPED: list[tuple[str, int]] = [ - *((f"{_HEAD}| a | b | c |\n{blank}\n{_ROW}", 5) for blank in ("", " ", "\r")), - (f"{_HEAD}| a | b | c |\n\n\n{_ROW}", 6), - (f"{_HEAD}| a | b | c |\r\n\r\n{_ROW}", 5), - # Two quotes a blank line separates. - (f"> {_HEAD.replace(chr(10), chr(10) + '> ')}| a | b | c |\n\n> {_ROW}", 5), -] - - -def _step9_excused(sf, body: str) -> set[str]: - """The hits the step 9 drop excuses in one body: none, unless it is listed above.""" - return { - f"pr-body:{line}: {sf.PR_BODY_REASONS['verdict']}" - for listed, line in _PR_STEP9_DROPPED - if listed == body - } - - -@pytest.mark.parametrize(("body", "line"), _PR_STEP9_DROPPED) -def test_a_blank_line_under_a_data_row_ends_the_asvs_header( - sf, sf_frozen_main, body: str, line: int -) -> None: - """Step 9's quiet control, and the exception it is: main flags exactly the listed hit.""" - assert sf_frozen_main.scan_pr_body(body) == sorted(_step9_excused(sf, body)), body - assert sf.scan_pr_body(body) == [], body - - #: The six bodies engine PR 2893's review named as false positives: CI prose and a component row about #: HL7 v2.5.1. Main flags each. Step 10, which an earlier head of this branch built to drop them, was #: removed, because it dropped a verdict only from a body exactly equal to one of the six, which no @@ -1693,7 +1665,6 @@ def _superset_bodies() -> dict[str, str]: for i, (s, body) in enumerate(_PR_FINDINGS_MUST_STAY_QUIET) } ) - bodies.update({f"step9-dropped-{i}": body for i, (body, _) in enumerate(_PR_STEP9_DROPPED)}) marked_head = "| x | ASVS | Note | Result |\n|---|---|---|---|\n" bodies.update( { @@ -1754,11 +1725,11 @@ def test_the_head_reports_every_hit_main_reports_in_a_constructed_body( sf, sf_frozen_main, name: str ) -> None: """BACKLOG #3364: on each constructed body, head reports every hit main reports, at main's line - number, excepting only the hits _PR_STEP9_DROPPED lists. A finite set: it pins these bodies, - and a loss on a body outside it is not caught here.""" + number, with no exception. A finite set: it pins these bodies, and a loss on a body outside it + is not caught here.""" body = _SUPERSET_BODIES[name] lost = set(sf_frozen_main.scan_pr_body(body)) - set(sf.scan_pr_body(body)) - assert not lost - _step9_excused(sf, body), (name, sorted(lost)) + assert not lost, (name, sorted(lost)) def test_the_head_reports_every_hit_main_reports_in_the_tracked_markdown( @@ -2904,7 +2875,7 @@ def _generated_pr_bodies(count: int = 600) -> list[str]: def test_the_scan_reports_at_least_every_hit_origin_main_reported(sf, sf_frozen_main) -> None: """The baseline is one pass of the union, but it runs the head's table model, so this is not true - by construction. The test pins it, excepting only the hits _PR_STEP9_DROPPED lists, against two + by construction. The test pins it, with no exception, against two oracles: the pre-BACKLOG #5582 reading rebuilt here, and the vendored origin/main scanner with #5582's readings.""" harvested = set(_harvested_pr_bodies()) @@ -2916,7 +2887,7 @@ def test_the_scan_reports_at_least_every_hit_origin_main_reported(sf, sf_frozen_ fired_harvested += 1 else: fired_generated += 1 - missed = main_hits - set(sf.scan_pr_body(body)) - _step9_excused(sf, body) + missed = main_hits - set(sf.scan_pr_body(body)) assert not missed, (body, sorted(missed)) # Controls: the oracle fires on many fixtures and many generated bodies, or this proves nothing. assert fired_harvested > 100 and fired_generated > 100, (fired_harvested, fired_generated) From aa8f78db790e0429337861703f37ea7678bef37e Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sat, 21 Nov 2026 19:49:05 -0600 Subject: [PATCH 55/74] Server schema check: repair the regressions review round b3d12f284d found BACKLOG #5062. Review round b3d12f284d on 219d3f48f6d..f5a2eb38459 found two regressions against origin/main, repaired once here: - DROP TABLE IF EXISTS #t$1, u (and #a#b, u) was ignored: the temporary name now takes $, @ and #, so the list raises as on main. The same pattern also counts an unguarded DROP TABLE #tmp, u, which main ignored, so its loose-pattern comment is now true. - A partial index in nested dynamic SQL raised "unterminated quote": a scan the nested quotes defeat now keeps the whole tail. Proposed PR title: Server schema check reads or refuses the DDL forms it misread; pin the keyless-chain serve-before-rotate-key stamp (BACKLOG #5062, #4942) Proposed banners: as in 219d3f48f6d's body, with the open review findings added to #5062's remainder. --- messagefoundry/store/server_schema_verify.py | 15 +++++++++++---- tests/test_server_schema_verify_5062.py | 20 ++++++++++++++++++++ 2 files changed, 31 insertions(+), 4 deletions(-) diff --git a/messagefoundry/store/server_schema_verify.py b/messagefoundry/store/server_schema_verify.py index 39c758e824..e33cf32aed 100644 --- a/messagefoundry/store/server_schema_verify.py +++ b/messagefoundry/store/server_schema_verify.py @@ -76,6 +76,7 @@ from __future__ import annotations +import contextlib import logging import re from collections.abc import Callable, Iterable, Mapping @@ -163,13 +164,16 @@ ) #: Every place a table or an index is created, dropped or renamed, read loosely, so a form the #: patterns above miss is counted and refused rather than silently left unchecked. A ``#`` temporary -#: table is not the store's, behind an ``IF [NOT] EXISTS`` guard too, but a guarded ``DROP TABLE`` -#: whose list goes on past it is counted, as on any other list the strict pattern cannot read. +#: table is not the store's, behind an ``IF [NOT] EXISTS`` guard too, but a ``DROP TABLE`` whose +#: list goes on past one is counted, so the strict pattern's miss raises. _LOOSE: Final = ( (re.compile(r"\bCREATE\s+TABLE\s+(?!\s|(?:IF\s+NOT\s+EXISTS\s+)?#)", re.I), _CREATE_TABLE), (re.compile(r"\bCREATE\s+(?:UNIQUE\s+)?(?:(?:NON)?CLUSTERED\s+)?INDEX\b", re.I), _CREATE_INDEX), (re.compile(r"\bALTER\s+TABLE\s+(?!\s|(?:IF\s+EXISTS\s+)?#)", re.I), _ALTER_TABLE), - (re.compile(r"\bDROP\s+TABLE\s+(?!\s|#|IF\s+EXISTS\s+#\w++(?!\s*,))", re.I), _DROP_TABLE), + ( + re.compile(r"\bDROP\s+TABLE\s+(?!\s|(?:IF\s+EXISTS\s+)?#[\w$@#]++(?!\s*,))", re.I), + _DROP_TABLE, + ), (re.compile(r"\bDROP\s+INDEX\b", re.I), _DROP_INDEX), (re.compile(r"\bsp_rename\b", re.I), _SP_RENAME), ) @@ -991,7 +995,10 @@ def index(self, text: str, m: re.Match[str]) -> None: tail = text[end : stop - 1].replace("''", "'") break tail = " " + tail # so the scan never starts at index 0 - definition = text[m.end() : end] + tail[: _statement_end(tail, 1)] + # Nested dynamic SQL's quotes can defeat the scan: keep it all, which only raises more. + with contextlib.suppress(ValueError): + tail = tail[: _statement_end(tail, 1)] + definition = text[m.end() : end] + tail self.opaque[name] = frozenset(_ident(w) for w in _TOKEN.findall(definition)) def _built(self, table: str, name: str, action: str) -> _Built: diff --git a/tests/test_server_schema_verify_5062.py b/tests/test_server_schema_verify_5062.py index b7a0355bd7..15e3ff45f2 100644 --- a/tests/test_server_schema_verify_5062.py +++ b/tests/test_server_schema_verify_5062.py @@ -442,3 +442,23 @@ def test_a_rename_to_a_data_word_is_read(name: str) -> None: ("CREATE TABLE t (a INT)", f"ALTER TABLE t RENAME COLUMN a TO {name}"), "postgres" ) assert shape.columns["t"] == frozenset({name}) + + +@pytest.mark.parametrize( + "statement", + ["DROP TABLE IF EXISTS #t$1, u", "DROP TABLE IF EXISTS #a#b, u", "DROP TABLE #tmp, u"], +) +def test_a_drop_list_that_goes_on_past_any_temporary_name_raises(statement: str) -> None: + with pytest.raises(ValueError, match="cannot read"): + declared_schema(("CREATE TABLE u (a INT NULL)", statement)) + + +def test_a_partial_index_in_nested_dynamic_sql_is_read() -> None: + shape = declared_schema( + ( + "CREATE TABLE t (a INT NULL, b NVARCHAR(9) NULL)", + "EXEC('EXEC(''CREATE INDEX ix ON t (a) WHERE b <> ''''x'''''')')", + ), + "sqlserver", + ) + assert shape.named_indexes["ix"].partial From 353847162c4dcfc79b5ffc805ed0bca0ef8b0429 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sat, 21 Nov 2026 22:05:25 -0600 Subject: [PATCH 56/74] Classify the ADR 0019/0173 revert guard in the tooling manifest It reads only docs/adr, like test_adr_index_coverage beside it. Proposed PR title: ADR 0019 and ADR 0173 drop restated facts Banner #1173: PARTIAL -- item 3 fixed (point 4 and its note point to ADR 0138); item 2 true as written, still open Banner #3009: PARTIAL -- PR 2899 notes 3 and 4 fixed for the run dates and the versions --- tests/tooling_manifest.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/tooling_manifest.txt b/tests/tooling_manifest.txt index 4f17921f43..6894ab8cb7 100644 --- a/tests/tooling_manifest.txt +++ b/tests/tooling_manifest.txt @@ -23,6 +23,7 @@ # tests/test_tooling_partition.py pins this file against the tree and fails if a new non-engine test # lands in neither this list nor its explicit stay-list. tests/test_adr0071_crossing_count.py +tests/test_adr_0019_0173_revert_guard.py tests/test_adr_index_coverage.py tests/test_afk_decision_log.py tests/test_afk_digest.py From b147a802513b6ddd4b59c20cda8787c0eb5a8f29 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sat, 21 Nov 2026 22:06:35 -0600 Subject: [PATCH 57/74] Drop two stale audit-row claims about route-body refusals docs/SECURITY.md said a route-body refusal only follows a grant row; it now points to _record_route_refusal. The _recorded_decision docstring said the per-request volume was unchanged; it now states the no-drain bound as at most two decision rows per refused route-body request. BACKLOG #1197 (ASVS 16.3.2). Proposed PR title: Route-body step-up refusals write an audit row (BACKLOG #1197) Proposed ledger banner for #1197: unchanged from commit c5e3bb75ff0, except that the docs/SECURITY.md step-up example sentence is no longer open. --- docs/SECURITY.md | 4 ++-- messagefoundry/api/security.py | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/SECURITY.md b/docs/SECURITY.md index 759d394760..6565a59ee8 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -5332,8 +5332,8 @@ flowchart TB `auth.gate_refused`, naming the same permission and a `reason` of `throttled` or `step_up`. It writes that row only where it would have written the grant row, so a gate that writes no grant row writes no refusal row either. A refused second factor writes `auth.mfa_denied`, as the base - gate's does. A refusal a route body makes after its gate has passed, such as a step-up proof the - route spends itself, still follows a grant row. + gate's does. For a refusal a route body makes after its gate has passed, + `_record_route_refusal` in `messagefoundry/api/security.py` says what it records. - Routes that act on a Connection also check the identity's connection scope. That scope starts empty for every role except Administrator. - Sensitive routes add a step-up re-check on top of this flow. See diff --git a/messagefoundry/api/security.py b/messagefoundry/api/security.py index aaed5df36f..e91a764ec3 100644 --- a/messagefoundry/api/security.py +++ b/messagefoundry/api/security.py @@ -1481,8 +1481,8 @@ async def _recorded_decision( A refusal row is written exactly where the grant row would have been, so a gate writes at most one decision row per request, and a gate that wrote no grant row writes no refusal row either. - That keeps the per-request volume where the shipped trail already put it while the audit chain - has no drain (BACKLOG #1421). For a refusal a route body makes after its gate admitted the + The audit chain has no drain (BACKLOG #1421); a refused route-body request writes at most two + decision rows. For a refusal a route body makes after its gate admitted the request, see :func:`_record_route_refusal`. The reason comes from the :class:`_GateRefusal` the check raised. Any other exception leaves the block with no decision row from it, which is right for the :func:`_mfa_refusal` 403: it wrote its own From 1d8eac17723a8dee3b18e307e6f65c6ab76ec5f5 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sat, 21 Nov 2026 22:08:05 -0600 Subject: [PATCH 58/74] reply_replaced: throttle the event per listener, with a count One event per replaced reply grew with message volume: a narrow-charset inbound under load could fill the runner's 10000-entry event queue and crowd out other kinds. ReplyReplacements now reports the first replaced reply at once, then at most one per 60 s (the tls_handshake_failed window), carrying the count since the last report. It has no trailing report, which the docstring and PHI.md say. The changelog and the warn-once comment say what the code does, and that rows are stored only when connection events are captured. BACKLOG #5799 item 1. Proposed PR title: Listeners record charset-replaced replies as a throttled connection event; X12 trailer comment corrected (BACKLOG #5799, #5807, #5812) Proposed banners: as in f84d453c78c, with #5799 item 1 SHIPPED as a throttled event. --- .../5799-reply-replaced-event.added.md | 8 ++-- docs/PHI.md | 2 +- messagefoundry/transports/framing.py | 47 +++++++++++++++---- messagefoundry/transports/mllp.py | 26 +++++----- messagefoundry/transports/tcp.py | 11 ++--- messagefoundry/transports/x12.py | 11 ++--- tests/test_mllp_handler_failure.py | 38 +++++++++++---- tests/test_tcp_x12_handler_failure.py | 7 +-- 8 files changed, 100 insertions(+), 50 deletions(-) diff --git a/changelog.d/5799-reply-replaced-event.added.md b/changelog.d/5799-reply-replaced-event.added.md index 3a1083a831..7c10e30138 100644 --- a/changelog.d/5799-reply-replaced-event.added.md +++ b/changelog.d/5799-reply-replaced-event.added.md @@ -1,4 +1,6 @@ -- The MLLP, raw-TCP and X12 listeners send a `reply_replaced` connection event for each reply in - which characters the inbound's charset cannot encode were replaced. The WARNING log line for a - replacement is still written once per connection per process. +- When connection events are captured, the MLLP, raw-TCP and X12 listeners send a + `reply_replaced` connection event when characters the inbound's charset cannot encode were + replaced in a reply: the first at once, then at most one a minute per listener, carrying the + count of replaced replies since the last one. The WARNING log line for a replacement is still + written once per connection per process. [PHI.md](../docs/PHI.md) section 7 says what the event carries. (`BACKLOG #5799`) diff --git a/docs/PHI.md b/docs/PHI.md index 1ed6ba1618..40dbfb9867 100644 --- a/docs/PHI.md +++ b/docs/PHI.md @@ -2326,7 +2326,7 @@ with materially different PHI profiles, so they get their own rows; stream 4 is | **4. Off-box syslog/SIEM forwarder** — the shared **transport** for 1–3 | a copy of every record from 1–3 | `forward_format`, default **JSON** (independent of the stdout format) | the operator's collector (`forward_host`/`_port`) | off-box evidence retention / SIEM correlation | **default-on when a collector is named.** Transport: `udp` (default) / `tcp` / **`tls`** (RFC 5425, CA-anchored, verified by default). `serve` gates the hop on the shared posture gradient before the handler is installed: verified TLS ungated; otherwise loopback / attested ALLOW, non-enforcing WARN, **enforcing REFUSE (exit 2)** — there is no synthetic arm, and [ADR 0186](adr/0186-retire-the-synthetic-data-declaration-every-instance-carries-patient-data.md) left this cell with no per-hop way to accept the risk at all | the collector's, not the engine's | the identical handler filters are installed on this handler. So the forwarded copy gets the same best-effort PHI redaction and credential scrub as stdout. A single-token identifier can survive it, as it can there. The copy also carries usernames, connection names, message ids, client addresses and the audit chain. That is the engine's own stated reason for gating the hop | | **5. `audit_log` table** (SQLite, Postgres, SQL Server) | who / what / **where-from** / when of auth + PHI *access* and admin actions — plus, while `[security].audit_all_authorization_decisions` is on (**default `true`** since BACKLOG #1277, 2026-09-02, which reversed the ADR 0118 §5 `false`; the internal field it desugars to is `audit_all_authz`, whose old `[diagnostics]` TOML spelling is **refused at load** — ADR 0118), an `authz` row for **every** authorization decision including successes. That is the shipped volume of this stream, not an opt-in addition to it: one row per authenticated request on each `require()`-gated route, and this row's retention cell records that **nothing prunes the table** — `actor`, `action`, `channel_id`, `client`, `detail`, `row_hash` | JSON `detail`; **tamper-evident hash chain** over `prev_hash` + the row (the `client` address is **inside** the chained payload — ADR 0150) | the store database | HIPAA §164.312(b) audit controls; incident response; `verify_audit_chain` integrity checks | `GET /audit` requires **`audit:read`**; `GET /audit/export` requires the separate **`audit:export`** and streams CSV with formula-injection neutralisation, recording its own `audit.export` row *before* streaming; `GET /me/security-events` is a per-user view of the same table | **`[retention].audit_days` is reserved and NOT enforced — keep-forever by design** (the audit-retention requirement, ~6 years — **not** chain-breakage; [§8](#8-retention--purge) states the position and cites its source of record) | `detail` is stored **in the clear** (it is not a cipher-covered column): its protection is that writers store at least filter shapes, counts, ids, keyed digests, bounded engine-authored text and client addresses, the `audit_log.detail` row above says which — never bodies or credentials — plus the store ACL and the volume layer. *Corrected 2026-10-16 (vault BACKLOG #3145):* this said writers "only ever store filter shapes, counts and ids" | | **6. `message_events` table** | the per-message disposition timeline — the **complete** vocabulary is `received`, `routed`, `unrouted`, `filtered`, `transformed`, `delivered`, `failed`, `dead`, `error`, `replayed`, `resent`, `reingressed`, `passthrough`, `passthrough_dropped`, `cancelled`, `edit_resend`, `edit_resubmit`, `viewed`, `not_deployed`, the ADR 0154 synchronous-reply pair `reply_returned` / `reply_timeout` (names, counts and `waited_ms` only — **never** a fragment of the partner's reply body), and `reply_dropped`, a delivery whose 2xx reply body was over the byte bound and dropped (the status and the bound only, vault BACKLOG #3040) (CI asserts this list against the engine's own `MESSAGE_EVENT_KINDS`). `[diagnostics].message_events` can thin the set, but never below the compliance floor `viewed` / `dead` / `error` / `failed` / `not_deployed` / `reply_timeout` / `reply_dropped` | rows: `message_id`, `ts`, `event`, `destination`, `detail` | the store database | operator timeline on the message-detail view; the `viewed` row is the HIPAA PHI-access record | `GET /messages/{id}` under **`messages:view_raw`** + `require_phi_read`; the read itself writes a `viewed` event **and** a `message_view` audit row | no dedicated window — `purge_message_bodies` sets `message_events.detail` to `NULL` in the same transaction that blanks the body, so it inherits `[retention].messages_days` | `detail` is `safe_text()`-scrubbed **then** cipher-encrypted (AAD `("message_events","detail",message_id,ts,event)`). Verbosity gate `[diagnostics].message_events` = `all` (default) / `errors` / `off`, with a **compliance floor that can never be thinned**: `viewed`, `dead`, `error`, `failed`, `not_deployed`, `reply_timeout`, `reply_dropped` are retained at every level (`reply_timeout` is the one row that explains a "we called you and got a 504" complaint, so an instance that thinned its logs would lose exactly the record it is later asked for; `reply_dropped` is the one row that answers "you ignored our reply", for the same reason) | -| **7. `connection_event` table — DEFAULT ON** (`[diagnostics].connection_events = true`) | transport/lifecycle events per connection: `established`, `closed` (reason `eof`, `idle_timeout` or `frame_deadline` — a fixed vocabulary chosen by the listener, never free text), `idle_timeout`, `at_capacity`, `peer_not_allowlisted`, `frame_oversize`, `framing_error`, `peer_reset`, the MLLP, raw-TCP, X12 and HTTP listeners' and the DATABASE poll source's `handler_error` (BACKLOG #1619, #5022, #5680 for the HTTP listener, which answers it `503` or `500` by the exception's type, as [CONNECTIONS.md Table B](CONNECTIONS.md#table-b--per-service-resource-strategy-asvs-1313) states -- the inbound handler faulted on a frame the listener read cleanly, such as a failed ingress commit; on the X12 listener also, BACKLOG #5971, the engine's own reply to an interchange already recorded could not be encoded in the inbound's charset, so it was not sent; on the DATABASE source, BACKLOG #4921, on a polled row, which is left unmarked and, when the source has a mark statement, stops that poll; the reason is scrubbed at the source like every other), the MLLP, raw-TCP and X12 listeners' `reply_replaced` (BACKLOG #5799 -- the engine's own reply held characters the inbound's charset cannot encode, and each was replaced before the reply was written to the connection; at most one event per such reply, sent whether or not the write then succeeds, while the WARNING log line is written once per connection per process; a frame byte turned into a space writes no event; the reason is fixed text that names neither the charset setting nor any part of the reply), the MLLP and HTTP listeners' `tls_handshake_failed` (vault BACKLOG #2613, #3302 and #3785 -- an inbound TLS handshake failed, on any event loop. **This is the one statement of the failed-handshake throttle, and other pages link here.** The first failure is reported at once, then at most one report per listener per minute, carrying the count since the last report. The reason is a count, an exception class name and OpenSSL's reason mnemonic, never the peer's bytes or certificate. A report names a peer only for a single failure, and only where the listener runs its own handshakes or awaits each one's outcome itself, which the MLLP and HTTP listeners do on every loop (BACKLOG #1606, #2479) and the DICOM C-STORE SCP always does. Such a listener also counts a handshake that runs past its bound. Where only the loop sees them, which is at least the API listener on every loop, the report names no peer, since the loop's hook does not read it (the module docstring of `messagefoundry/tls_handshake_failures.py` says what was measured), and a handshake that only runs past its bound is not counted. A peer that closes or resets the socket mid-handshake is not counted anywhere. That is what a load balancer's TCP health check does. The past-bound and hang-up limits stand by owner ruling 2026-10-26 (vault BACKLOG #3785 items 7 and 8), and that ruling covers only those two. Whether the API's report should name the peer is still an open owner question (vault BACKLOG #3302). The item 8 decline keeps the hang-up counting that came before #3785 and adds none. So a close_notify after the ClientHello is still counted, and the DICOM C-STORE SCP counts it too. A handshake that the listener's own stop ends is not counted. At least every listener also drops a genuine failure that lands once its stop has begun. The DICOM C-STORE SCP drops them for the whole of its server shutdown. On the MLLP and HTTP listeners, a stop that is cancelled before it finishes loses the failures its trailing report still held. The DICOM C-STORE SCP still reports them when its server shutdown raises or is cancelled. The API listener and the DICOM C-STORE SCP write the same report, throttled the same way, as a WARNING log line rather than an event: the API has no connection to carry one, and the SCP emits none (vault BACKLOG #3784)), the DATABASE poll source's `row_undecodable` (BACKLOG #1662 — a polled row the source cannot turn into a body; the reason is scrubbed at the source and names the exception type or the operator's own configured column, never a row value), the FILE poll source's quarantine kinds `file_oversize` / `file_decompress_failed` / `file_content_mismatch` / `file_scan_rejected` (BACKLOG #1621 — a drop moved to `.error`; the reason is a size, a content type or a codec or scanner message, and **that message can still name the file**. The name scrub on both the FILE and REMOTEFILE sources is `safe_exc(exc, file_name=...)`. safe_exc replaces the file name and, at least, its repr, ascii, bytes-repr and JSON-escaped forms. A scanner's `ScanRejected` message that quotes the name in at least another case, without its extension, percent-encoded, in another Unicode normalization, or escaped in a spelling those forms do not produce, such as a JSON escape with uppercase hex digits, keeps that text in the reason (`tests/test_file_source_quarantine_events.py` and `tests/test_remotefile_source_quarantine_events.py` pin this on each source's scan-reject arm), so a scan hook should leave the name out of its message; the REMOTEFILE poll source records the same kinds except `file_decompress_failed`, since it does not decompress), the inbound-HTTP intake-auth refusals `intake_auth_failed` / `auth_subject_denied` / `auth_rate_limited` (ADR 0154 D6 — peer address and mode only, plus, behind a proxy the connection lists in its trusted_proxies setting, the forwarded client address as a forwarded_for suffix on the reason and the audit detail (BACKLOG #5525); **never** the credential, a prefix of it, or its length. Each of these also writes a tamper-evident audit-log row — the copy that survives an operator turning this diagnostics stream off. The MLLP listener writes `auth_subject_denied` and `auth_rate_limited` too, with the same audit rows, when its expected-sender allowlist refuses a sender, naming the peer address and never a certificate field; BACKLOG #4907), plus the runner's `connection_lost` / `connection_restored` / `config_fault`. That is the whole vocabulary, asserted in CI against the literal emit call sites in `transports/` and the pipeline runner **and** against `CONNECTION_EVENT_KINDS` (`messagefoundry/connection_events.py`), the one set the store enforces on write and the console's filter reads (BACKLOG #1624). The MLLP, raw-TCP, X12 and HTTP listeners emit these; the **DATABASE poll source** emits `row_undecodable` and `handler_error` and nothing else (it dials out, so there is no lifecycle to report and its rows carry a **NULL peer column**); the **FILE poll source** emits only its four quarantine kinds, and the **REMOTEFILE poll source** only three of them, both with a NULL peer column; the **DICOM inbound C-STORE SCP** emits none — the runner injects the sink onto **every** source (`wiring_runner.py`, over the base-class `on_connection_event` field), so that connector *has* the wiring and simply never calls it — so this stream covers those four listeners plus those poll-source events and the runner's outbound-lane transitions — not literally every connection. A DICOM association's connects and refusals are therefore **absent** from this stream. The **`ISA`/`IEA`-framed X12 inbound** was equally absent until BACKLOG #1665 and is not any more: it emits the same kinds as the raw-TCP listener | rows: `ts`, `connection`, `transport`, `direction`, `kind`, `peer_host`, `message_id` (correlation hint), `reason` | the store database, **all three backends** | Corepoint-style transport diagnostics — "did the sender connect, and why did it drop" | `GET /events` and `GET /connections/{name}/events` under **`monitoring:read`** (**not** a PHI permission) with per-channel RBAC — an out-of-scope `connection=` is 403'd *and* audited — server-clamped to ≤1000 rows. `reason` alone is gated on `messages:view_summary` and masked as `****` until the audited per-event `reveal=` act (BACKLOG #2443; the `connection_event.reason` row of §3's PL-2 block says how) | `[retention].connection_event_retention_hours` (its own **hours** window); 0 inherits `[retention].messages_days`; both 0 = keep forever. Plain age `DELETE` | **`reason` is free text that can carry sensitive fragments.** Defended twice — `safe_exc()` at the source, `safe_text(reason, limit=200)` at the store (the bound §3's PL-2 block states) — then cipher-encrypted (AAD `("connection_event","reason",connection,ts,kind)`). Every other column is engine or config metadata except `peer_host`, and `reason` is not metadata-only: the [data-at-rest inventory](#2-where-phi-lives--data-at-rest-inventory) grades `reason` and `peer_host` in rows of their own (BACKLOG #5021). Writes are a pure side observer: a bounded in-memory queue drained by a background task outside any handoff transaction, so a flood can never block a listener or pin a message disposition | +| **7. `connection_event` table — DEFAULT ON** (`[diagnostics].connection_events = true`) | transport/lifecycle events per connection: `established`, `closed` (reason `eof`, `idle_timeout` or `frame_deadline` — a fixed vocabulary chosen by the listener, never free text), `idle_timeout`, `at_capacity`, `peer_not_allowlisted`, `frame_oversize`, `framing_error`, `peer_reset`, the MLLP, raw-TCP, X12 and HTTP listeners' and the DATABASE poll source's `handler_error` (BACKLOG #1619, #5022, #5680 for the HTTP listener, which answers it `503` or `500` by the exception's type, as [CONNECTIONS.md Table B](CONNECTIONS.md#table-b--per-service-resource-strategy-asvs-1313) states -- the inbound handler faulted on a frame the listener read cleanly, such as a failed ingress commit; on the X12 listener also, BACKLOG #5971, the engine's own reply to an interchange already recorded could not be encoded in the inbound's charset, so it was not sent; on the DATABASE source, BACKLOG #4921, on a polled row, which is left unmarked and, when the source has a mark statement, stops that poll; the reason is scrubbed at the source like every other), the MLLP, raw-TCP and X12 listeners' `reply_replaced` (BACKLOG #5799 -- the engine's own reply held characters the inbound's charset cannot encode, and each was replaced before the reply was written to the connection; throttled per listener: the first such reply sends one at once, then at most one a minute, sent by the first such reply past the minute and carrying the count of such replies since the last one, with no trailing report, so replies counted after the last event are not reported if no later one comes; an event is sent whether or not the write then succeeds, while the WARNING log line is written once per connection per process; a frame byte turned into a space writes no event; the reason is a count and fixed text that names neither the charset setting nor any part of the reply), the MLLP and HTTP listeners' `tls_handshake_failed` (vault BACKLOG #2613, #3302 and #3785 -- an inbound TLS handshake failed, on any event loop. **This is the one statement of the failed-handshake throttle, and other pages link here.** The first failure is reported at once, then at most one report per listener per minute, carrying the count since the last report. The reason is a count, an exception class name and OpenSSL's reason mnemonic, never the peer's bytes or certificate. A report names a peer only for a single failure, and only where the listener runs its own handshakes or awaits each one's outcome itself, which the MLLP and HTTP listeners do on every loop (BACKLOG #1606, #2479) and the DICOM C-STORE SCP always does. Such a listener also counts a handshake that runs past its bound. Where only the loop sees them, which is at least the API listener on every loop, the report names no peer, since the loop's hook does not read it (the module docstring of `messagefoundry/tls_handshake_failures.py` says what was measured), and a handshake that only runs past its bound is not counted. A peer that closes or resets the socket mid-handshake is not counted anywhere. That is what a load balancer's TCP health check does. The past-bound and hang-up limits stand by owner ruling 2026-10-26 (vault BACKLOG #3785 items 7 and 8), and that ruling covers only those two. Whether the API's report should name the peer is still an open owner question (vault BACKLOG #3302). The item 8 decline keeps the hang-up counting that came before #3785 and adds none. So a close_notify after the ClientHello is still counted, and the DICOM C-STORE SCP counts it too. A handshake that the listener's own stop ends is not counted. At least every listener also drops a genuine failure that lands once its stop has begun. The DICOM C-STORE SCP drops them for the whole of its server shutdown. On the MLLP and HTTP listeners, a stop that is cancelled before it finishes loses the failures its trailing report still held. The DICOM C-STORE SCP still reports them when its server shutdown raises or is cancelled. The API listener and the DICOM C-STORE SCP write the same report, throttled the same way, as a WARNING log line rather than an event: the API has no connection to carry one, and the SCP emits none (vault BACKLOG #3784)), the DATABASE poll source's `row_undecodable` (BACKLOG #1662 — a polled row the source cannot turn into a body; the reason is scrubbed at the source and names the exception type or the operator's own configured column, never a row value), the FILE poll source's quarantine kinds `file_oversize` / `file_decompress_failed` / `file_content_mismatch` / `file_scan_rejected` (BACKLOG #1621 — a drop moved to `.error`; the reason is a size, a content type or a codec or scanner message, and **that message can still name the file**. The name scrub on both the FILE and REMOTEFILE sources is `safe_exc(exc, file_name=...)`. safe_exc replaces the file name and, at least, its repr, ascii, bytes-repr and JSON-escaped forms. A scanner's `ScanRejected` message that quotes the name in at least another case, without its extension, percent-encoded, in another Unicode normalization, or escaped in a spelling those forms do not produce, such as a JSON escape with uppercase hex digits, keeps that text in the reason (`tests/test_file_source_quarantine_events.py` and `tests/test_remotefile_source_quarantine_events.py` pin this on each source's scan-reject arm), so a scan hook should leave the name out of its message; the REMOTEFILE poll source records the same kinds except `file_decompress_failed`, since it does not decompress), the inbound-HTTP intake-auth refusals `intake_auth_failed` / `auth_subject_denied` / `auth_rate_limited` (ADR 0154 D6 — peer address and mode only, plus, behind a proxy the connection lists in its trusted_proxies setting, the forwarded client address as a forwarded_for suffix on the reason and the audit detail (BACKLOG #5525); **never** the credential, a prefix of it, or its length. Each of these also writes a tamper-evident audit-log row — the copy that survives an operator turning this diagnostics stream off. The MLLP listener writes `auth_subject_denied` and `auth_rate_limited` too, with the same audit rows, when its expected-sender allowlist refuses a sender, naming the peer address and never a certificate field; BACKLOG #4907), plus the runner's `connection_lost` / `connection_restored` / `config_fault`. That is the whole vocabulary, asserted in CI against the literal emit call sites in `transports/` and the pipeline runner **and** against `CONNECTION_EVENT_KINDS` (`messagefoundry/connection_events.py`), the one set the store enforces on write and the console's filter reads (BACKLOG #1624). The MLLP, raw-TCP, X12 and HTTP listeners emit these; the **DATABASE poll source** emits `row_undecodable` and `handler_error` and nothing else (it dials out, so there is no lifecycle to report and its rows carry a **NULL peer column**); the **FILE poll source** emits only its four quarantine kinds, and the **REMOTEFILE poll source** only three of them, both with a NULL peer column; the **DICOM inbound C-STORE SCP** emits none — the runner injects the sink onto **every** source (`wiring_runner.py`, over the base-class `on_connection_event` field), so that connector *has* the wiring and simply never calls it — so this stream covers those four listeners plus those poll-source events and the runner's outbound-lane transitions — not literally every connection. A DICOM association's connects and refusals are therefore **absent** from this stream. The **`ISA`/`IEA`-framed X12 inbound** was equally absent until BACKLOG #1665 and is not any more: it emits the same kinds as the raw-TCP listener | rows: `ts`, `connection`, `transport`, `direction`, `kind`, `peer_host`, `message_id` (correlation hint), `reason` | the store database, **all three backends** | Corepoint-style transport diagnostics — "did the sender connect, and why did it drop" | `GET /events` and `GET /connections/{name}/events` under **`monitoring:read`** (**not** a PHI permission) with per-channel RBAC — an out-of-scope `connection=` is 403'd *and* audited — server-clamped to ≤1000 rows. `reason` alone is gated on `messages:view_summary` and masked as `****` until the audited per-event `reveal=` act (BACKLOG #2443; the `connection_event.reason` row of §3's PL-2 block says how) | `[retention].connection_event_retention_hours` (its own **hours** window); 0 inherits `[retention].messages_days`; both 0 = keep forever. Plain age `DELETE` | **`reason` is free text that can carry sensitive fragments.** Defended twice — `safe_exc()` at the source, `safe_text(reason, limit=200)` at the store (the bound §3's PL-2 block states) — then cipher-encrypted (AAD `("connection_event","reason",connection,ts,kind)`). Every other column is engine or config metadata except `peer_host`, and `reason` is not metadata-only: the [data-at-rest inventory](#2-where-phi-lives--data-at-rest-inventory) grades `reason` and `peer_host` in rows of their own (BACKLOG #5021). Writes are a pure side observer: a bounded in-memory queue drained by a background task outside any handoff transaction, so a flood can never block a listener or pin a message disposition | | **8. `alert_instance` table — default on wherever an `[alerts]` notifier exists** | resolvable operator alerts: `connection_stopped`, `queue_buildup`, `lane_stuck`, `message_stall`, `saturation`, `connection_error`, `connection_error.config_fault`, `storage_threshold`, `cert_expiry`, `secret_rotation`, `initial_credential_expiring` (an UNCLAIMED admin-issued temporary password nearing the instant the login gate stops accepting it -- ASVS 6.4.5, BACKLOG #1141; keyed on `user:`, and the payload is the ISO deadline plus whole hours remaining, repeated in the reason column, never the password), `integrity_drift`, `update_available`, `backup_failed`, `store_privilege_warning` (the store privilege preflight found the store principal over-granted or could not read it -- BACKLOG #305; the payload is the finding, a count and the preflight's summary line, which names the login, the database and role names, never a password or message content), `vault_privilege_warning` (the Vault privilege preflight found a Vault token over-granted or could not read it -- BACKLOG #2903, ADR 0216; keyed on `vault:store` or `vault:secrets`, and the payload is the finding, a count of refusing-class grants and the hop's judgment, which names policy names, paths and capabilities, never a token, an accessor, a digest of either or message content), `leadership_acquired`, `dr_activated`, `log_write_failed` (an application-log sink was rolled after a write failure, or is UNWRITABLE and this process's connections were stopped -- BACKLOG #122, ADR 0162; the payload is the sink LABEL, the stage, a `safe_exc` reason and a count of connections stopped, never the record whose write failed), `log_forward_failed` (the off-box log forwarder is absent, losing records or not sending -- BACKLOG #2612; keyed on `forwarder:`, with `@node:` or `@shard:` appended when several engine processes share the store, and the payload is that key, fixed reason words and a count, never a record, the collector's address or an error text; an unpinned cluster node's `node_id` holds this engine's own host name and process id, so the key carries them), `gcm_invocations` (the per-key AES-GCM invocation bound crossing its 2^31 soft warn — ASVS 11.3.4; its payload carries a one-way `key_id` fingerprint plus counters, never key bytes), `approval_stale_requester` (a dual-control release refused because the requester no longer holds the authority the operation needs -- ASVS 8.3.2, BACKLOG #289; keyed on the approval id, and the payload is that id, the operation key and a closed-set reason slug, never the requester's name or the captured params), `approval_too_early` (a dual-control release refused because it arrived before `[approvals].min_dwell_seconds` -- ASVS 2.4.2, BACKLOG #287; keyed on `approval:`, and the payload is that key, the operation key and a fixed reason string, never the approver's or requester's name or the captured params), `audit_write_failed` (the approval gate could not write one of its audit rows -- vault BACKLOG #2255; keyed on `approval:`, on `approval::resolve` for a resolution's lost provenance row -- vault BACKLOG #3438, on the fixed `approval:listing` for a queue listing's lost `approval.standing_shown` row -- vault BACKLOG #3747, on `config_reload:inline` when an ungated config reload could not write its `config_reload_attempted` row -- vault BACKLOG #2254, or on `step_up_return:audit_budget:` when the IdP step-up return audit budget's backstop stopped a row -- BACKLOG #3965, or on `directory-reconciler:` when a directory reconcile pass that completed could not write a row -- BACKLOG #3018 step 2, or on `directory-sign-in:` when a directory sign-in's role-sync row was refused twice -- BACKLOG #2221; the payload is that key and the lost row's audit action name, never the row's detail, a username or the captured params; the ERROR log line beside it holds the detail on some paths and only the exception on others), `audit_offbox_copy_missing` (an approval audit row whose write the gate read back as committed, whose off-box copy was never sent -- vault BACKLOG #3193; keyed on `approval:`, and the payload is that key and the row's audit action name, never the row's detail, a username or the captured params), `ad_reconcile_aborted` (a directory reconciler pass left signed-in accounts unrevoked and needs an operator: the mass-revoke breaker tripped and nothing was revoked, or one or more probes were answered with an LDAP referral and those accounts were left unjudged while the rest of the pass was applied, BACKLOG #2538, or one or more probes raised a fault the engine could not read and those accounts were left unjudged the same way, BACKLOG #3100, or the directory refused one or more probes with a result code that points at the configuration, such as a deleted search base, and those accounts were left unjudged the same way, vault BACKLOG #3010, or an account's group search was refused for the engine's own deadline or cap, so a role or scope change in the directory does not revoke that account's sessions, though a disable or deletion still does, vault BACKLOG #3696, or every lookup failed to reach the directory for `[auth].ad_reconcile_outage_passes` passes running, BACKLOG #3709; for the breaker, a referral, a probe fault, a configuration refusal and a lasting outage the payload is a fixed source label, `directory-reconciler` for the breaker, `directory-reconciler-referral` for a referral, `directory-reconciler-probe-fault` for a probe fault, `directory-reconciler-misconfigured` for a configuration refusal and `directory-reconciler-outage` for a lasting outage so each is its own instance, the closed-set reason slug `mass_revoke_breaker`, `directory_referral`, `probe_fault`, `directory_misconfigured` or `directory_unavailable`, a count (the accounts the breaker judged, or for each of the other four the lookups the pass sent, which leaves out an id-less row -- vault BACKLOG #3170) and the latched operator explanation, or for a lasting outage a fixed sentence with the run's length, never a username; a paging refusal is instead keyed on that operator account's username, as `directory-reconciler-paging:`, so each account is its own instance, raised as the account enters that state and again after a restart while it stands, and the payload is that key, the closed-set reason slug `group_search_deadline` or `group_search_cap`, the same count as the breaker's and a fixed sentence naming the cause, never anything else about the account; an account the directory keeps failing to answer for is keyed the same way, as `directory-reconciler-unreached:`, raised as it enters that state, and its payload is that key, the closed-set reason slug `account_unreachable`, the count of lookups the pass sent and a fixed sentence with two numbers, how many probes failed and the most recent probes its window can hold (faults aside), never anything else about the account -- vault BACKLOG #3100, #3709; on a rolled-up pass, those entering page as one instance under the bare `directory-reconciler-unreached` source, with no username, and the `ad_reconcile_outage_passes` row of [CONFIGURATION.md](CONFIGURATION.md) states when), `ad_reconcile_held` (the reconciler is holding accounts whose `userAccountControl` it cannot read, ADR 0195; the payload is the same fixed source label, a closed-set reason slug, the count of undetermined accounts and the latched operator explanation, never a username), `ad_session_revoked` (the reconciler revoked a directory principal's sessions; keyed on that operator account's username, with at least a `directory_absent`, `directory_disabled`, `directory_undetermined`, `directory_object_id_missing`, `roles_changed` or `scope_changed` reason), `approval_approver_provenance` (a dual-control release, or the resolution of an interrupted one, went ahead with an approver or resolver account created, re-passworded or TOTP-enrolled after the request -- BACKLOG #315, #2125; keyed on `approval:`, or `approval::resolve` for a resolution, and the payload is the operation key and the closed-set change slugs, never a username or the captured params), `administrator_granted` (the built-in Administrator role was granted by account creation, a role change, a directory group newly mapped to it -- BACKLOG #315 --, a directory sign-in whose role sync newly gave the account the role -- vault BACKLOG #2610 -- or a directory reconcile pass whose role re-diff did -- vault BACKLOG #3141; keyed on `user:` or `ad-group:`, with the grant route and the granting administrator's username, or `` for a directory sign-in or reconcile pass), `no_enabled_administrator` (a directory sign-in's role sync or the session reconciler took Administrator from its last enabled holder -- vault BACKLOG #3229; keyed on `user:`, and the payload is `via`, `ad-sync` or `ad-reconcile`, and a fixed reason sentence, never message content), `intake_paused` (the engine paused intake because the staged backlog went over `[inbound].max_staged_depth` or the SQLite volume fell below `[retention].min_free_disk_mb` -- BACKLOG #290; keyed on `intake:staged_depth` or `intake:disk_floor`, with `@node:` or `@shard:` appended when several engine processes share the store (BACKLOG #2272), and the payload is the reason, a count or a MiB figure, its limit and the store backend's name, never message content), `config_changed` (a start's config differs from the store's baseline: the bytes it loaded, or the directory just after the load -- vault BACKLOG #2597, #3765; keyed on `config:`, and the payload is the two digests, the node and engine shard labels, the action, actor username, time and node of the row the older digest came from, and the `comparison` outcome, never the config directory, a git commit or message content), `crl_reload_refused` (the CRL reload refused a replaced CRL file, so running TLS contexts keep the copy they hold -- vault BACKLOG #2904; keyed on `crl_reload:`, with `@node:` or `@shard:` appended when several engine processes share the store, and the payload is that key, the file's path, a short class token for the remedy, a count of contexts, the engine's own fixed remedy sentence and, when a start would refuse the file too, a `start_refuses` flag, never the refusal's reason, which quotes CRL issuer names and dates; that reason is in the application log, and in the `detail` of the CRL expiry alert once the held copy nears its `nextUpdate`), `remote_debug_refused` (the engine's remote-debugging guard refused scripts that another process injected into the engine process -- vault BACKLOG #2742; keyed on `remote_debug:refused`, with `@node:` or `@shard:` appended when several engine processes share the store, and the payload is that key, the count of scripts refused since the alert was last raised, the count since the process started and a fixed sentence built from the two, never a script's file name, which the injecting process chooses; that name is in the application log, in the guard's WARNING line), `sandbox_worker_refused` (a `[sandbox].mode = "subprocess"` worker was refused because the graph it loaded differs from the engine's, most often a config file edited on disk with no reload -- vault BACKLOG #2724; keyed on the inbound's name, raised once per refusal, and the payload is that name and a fixed sentence naming the cause and the remedy, never a message body or the refusal text, which names config names and digests and is in the application log), `store_restored` (the first `serve` on a store `messagefoundry restore` placed ended every session -- BACKLOG #2614; keyed on `store:restored`, raised once per restore, and the payload is that key; a fixed sentence carrying the archive's age in days, the count of sessions ended, a pointer to `messagefoundry restore --help` and the time of the archive's newest audit row, of which the alert instance's reason column keeps the age, the count and the pointer whole and the time redacted or cut; that time again as `last_audit_at`; and the fixed notice of what a restore rolls back as `rollback_notice` (`messagefoundry/restore_notice.py`, BACKLOG #5094), fixed text the reason column never holds; never an account name or a row's content), and the seven security signals of the audit-stream rule layer -- vault BACKLOG #2613: `signin_failure_burst` (keyed on `signin:`, never the typed username), `access_denied_burst`, `body_view_burst` and `bulk_export` (each keyed on `account:`), `peer_refused_burst` (keyed on `inbound:`, never the refused peer's address), `log_level_debug` (keyed on `logging:debug`) and `posture_loosened` (keyed on `posture:start`, with `@node:` or `@shard:` appended when several engine processes share the store); the payload is a count and a fixed sentence holding a level name, switch names or a username, never a message body, a message id or an audit row's detail. The reachable **inverse** signals — `connection_restored`, `leadership_lost`, `dr_released`, `store_privilege_clean`, `vault_privilege_clean`, `intake_resumed`, `posture_restored` (it resolves `posture_loosened` under the same key, so for the same engine process, when a start records no security loosening in a row marked neither `superseded` nor `baseline_unchecked` and a live posture read then names none -- vault BACKLOG #2613; an unpinned cluster node's key changes on every start, so that node raises the inverse for its own instance as it shuts down; when that instance can still stay open is in [SECURITY.md](SECURITY.md)), `crl_reload_applied` (it resolves `crl_reload_refused` under the same key, so for the same file and the same engine identity, at least once the reload's record no longer holds the refusal, once no hop holds any CRL, and when the reload stops -- vault BACKLOG #2904; it is also raised once per held file outside a CA bundle, at the first pass that judges it with no refusal standing, whether or not an alert is open, so it can resolve nothing, and it then clears one an earlier run under that identity left open -- vault BACKLOG #3543. An alert for a file no hop holds now stays open, and so does one an unpinned cluster node raised, because that node's identity changes on every start; [CONFIGURATION.md](CONFIGURATION.md), *The alert resolves itself*, is the source of record), `ad_reconcile_breaker_cleared`, `ad_reconcile_hold_released` (the last two resolve `ad_reconcile_held` and `ad_reconcile_aborted`, the latter only under the breaker's, the referral's or the lasting outage's source: the probe fault's, the configuration refusal's, a paging refusal's and an unreached account's instances have no inverse; when they do, and where they never do, is stated once in [CONFIGURATION.md](CONFIGURATION.md#when-the-reconcilers-alerts-resolve-themselves) -- BACKLOG #2136) — are never rows here: `_record_state` routes an inverse through `_AUTO_RESOLVE` to `resolve_alert_instances_fenced` (BACKLOG #4916), or `resolve_alert_instances_for` on a store without the fence methods, never to `upsert_alert_instance`. So is `connection_started`, which resolves `connection_stopped` under the bare connection name: the runner raises it only when an operator's start or restart finds an inbound up and no cause it can see still holds the name down in either direction (BACKLOG #1741). Every other start raises nothing, at least an engine start, a committed reload, the scheduler and every alert rule's restart, so an open stop keeps its instance, ack and suspend across them. `AlertSink.connection_started` states the full contract, including the operator starts that still raise nothing. An instance raised under a prefixed stand-in such as `reference:` is never resolved by it. | rows: `event_type`, `connection`, `severity`, `status`, `first_seen`, `last_seen`, `count`, `reason`, `acked_by`, `acked_at`, `resolved_at`, `suspended_until`, `escalation_tier`, `raised_by` (a random per-process id naming the newest raise's writer, BACKLOG #4916; never a host, user or message value) | the store database, **all three backends** | the operator alert list — acknowledge / resolve / suspend. Durable state is recorded **before** any suppression or throttle return, so a muted alert still leaves a record | `GET /alerts/active` under **`monitoring:diagnose`** (**not** a PHI permission) with the same per-channel scope, and `reason` alone gated on `messages:view_summary` and masked as `****` until the audited per-alert `reveal=` act (BACKLOG #2443; the `alert_instance.reason` row of §3's PL-2 block says how); ack/resolve/suspend/**resume** are POSTs on the same tier, and the separate read-only `GET /alerts/rules` view sits on its own gate | shares the connection-event window; **only RESOLVED instances are DELETEd**, by `resolved_at` — retention never ages out an open or acknowledged condition from under an operator; a row can still close with no inverse and no operator, at least through the `intake_paused` staleness sweep (BACKLOG #3269), which resolves another engine process's open or acknowledged pause under the expiry rule in [CONFIGURATION.md](CONFIGURATION.md#alerts), after which retention treats it as any resolved row | **`reason` is free text** taken from the event's internal `_detail` (the `connection_error` reason kept off the wire, BACKLOG #5021), `detail` or `reason`: `safe_text(reason, limit=200)` (the bound §3's PL-2 block states) then cipher-encrypted (AAD `("alert_instance","reason",event_type,connection)` — the de-dup grain, so one AAD covers both the INSERT and the re-fire UPDATE). | | **9. `response` rows with `kind='ack_sent'` — DEFAULT ON** (`[diagnostics].response_sent = true`) | the ACK/NAK the engine returned to an inbound sender, under a sentinel destination `\x1fack:` | rows: `ack_code` (`AA`/`AE`/`AR`/`CA`/`CE`/`CR`), `ack_phase` (`decode`/`parse`/`strict`/`ingest`), `outcome`, `body`, `detail` | the store database | "what did we actually reply, and why" — the operator's answer to a sender disputing an ACK | `GET /messages/{id}/responses` under `messages:read` + `require_phi_read`; the `body` only for a caller who also holds `messages:view_raw` and `messages:view_summary`; every read writes a `response.read` audit row | `body`, `detail` and `resp_headers` are set to `NULL` in place by `purge_message_bodies` on the message-body window, on all three backends | **PHI fail-safe:** the ACK **body** is stored **only when the store cipher is active** — on a keyless store it is `NULL` rather than plaintext — and every NAK passes no body at all, so the offending field value is never persisted. The disposition metadata (`ack_code`/`ack_phase`/`outcome`) is non-PHI and always captured; `detail` is `safe_text`-scrubbed, held to the 200-character bound §3's PL-2 block states, and encrypted | | **10. `[alerts]` webhook transport** (off by default — `webhook_url` unset) | one HTTPS POST per alert, carrying every non-underscore event key as JSON | JSON | the operator's webhook endpoint (Slack/Teams/PagerDuty/custom) | operator notification | **`https` only** — a plaintext `http://` webhook URL is refused at construction. Redirects are refused; an optional `webhook_allowed_hosts` egress allowlist gates the host. A verifying `https` hop off this box also takes the revocation guard at build, on a host the `webhook_allowed_hosts` allowlist admits. An unset or empty allowlist admits every host, an explicit `[]` included, and so does an environment value that splits to no host, such as `""` or `","`. A host off a non-empty allowlist is refused at build, before this guard (BACKLOG #5088). A TOML list keeps its entries as written, so `[""]` or `[","]` is not empty and names no real host, and the build refuses every real host. Under an enforcing or unknown posture the guarded hop is refused unless the `[alerts].webhook_tls_revocation_attested` pair is set ([ADR 0173](adr/0173-tls-peer-revocation-checking-and-ocsp-stapling-across-terminating-and-originating-surfaces.md) states the guard and its levers) | the endpoint's | **carries the alert's `detail`/`reason` free text** for at least `connection_stopped`, `log_write_failed` and `backup_failed` (`safe_exc()`-scrubbed at the emit sites, but **not** re-run through `safe_text` on this path, and a scrubbed reason can still echo a partner's reply text). `connection_error` no longer carries its detail: in its place it sends the exception class (or the fixed token `unnamed error` for a class that is not a plain identifier), beside at least the connection and the kind, and keeps the detail under the internal `_detail` key, which the notifier pops before any transport is handed the event and which the alert instance's stored `reason` (row 8) still keeps (`NotifierAlertSink.connection_error`, BACKLOG #5021). Internal `_`-prefixed keys, at least `_detail`, `_transports`, the per-rule recipients, the rule id and the cooldown, are stripped before send, so recipient addresses never cross the wire | diff --git a/messagefoundry/transports/framing.py b/messagefoundry/transports/framing.py index fdbcfa5ea7..d0680b1b36 100644 --- a/messagefoundry/transports/framing.py +++ b/messagefoundry/transports/framing.py @@ -14,6 +14,7 @@ from __future__ import annotations import logging +import time from messagefoundry.config.wiring import _is_text_codec from messagefoundry.framing import ( @@ -36,7 +37,8 @@ __all__ = [ "FRAMING_CODE", "MULTIPLE_MESSAGES_CODE", - "REPLY_REPLACED_REASON", + "REPLY_REPLACED_EVENT_SECONDS", + "ReplyReplacements", "FrameError", "FrameByteFault", "FramePayloadError", @@ -72,16 +74,43 @@ _reply_fallback_logged: set[str] = set() #: The listeners whose reply-character replacement has been logged, once per connection for the -#: same reason (BACKLOG #5799): a narrow charset meets the same characters on every message. Each -#: replaced reply still writes a ``reply_replaced`` connection event, through the listeners that call -#: :func:`frame_reply_reporting` or :func:`encode_reply_reporting`. +#: same reason (BACKLOG #5799): a narrow charset meets the same characters on every message. The +#: MLLP, raw-TCP and X12 listeners also send a ``reply_replaced`` connection event, which +#: :class:`ReplyReplacements` throttles; it is stored only when connection events are captured. _reply_replacement_logged: set[str] = set() -#: The ``reason`` of a ``reply_replaced`` connection event. Fixed text: it names neither the charset -#: setting nor any part of the reply, which echoes the message. -REPLY_REPLACED_REASON = ( - "the reply held characters the inbound charset cannot encode, and each was replaced" -) +#: The shortest gap between two ``reply_replaced`` events from one listener, the same window as the +#: ``tls_handshake_failed`` throttle. +REPLY_REPLACED_EVENT_SECONDS = 60.0 + + +class ReplyReplacements: + """One listener's throttle for its ``reply_replaced`` connection events (BACKLOG #5799). + + A narrow charset meets the same characters on every message, so one event per replaced reply + would grow with message volume and could crowd other kinds out of the runner's bounded event + queue. The first replaced reply is reported at once; after that, at most one report per + :data:`REPLY_REPLACED_EVENT_SECONDS`, made by the first replaced reply past the window and + carrying the count since the last report. Unlike the ``tls_handshake_failed`` throttle there is + no trailing report: replies counted after the last report are not reported until another reply + is replaced past the window, and not at all if none is. The reason is a count and fixed text, + never the charset setting or any part of the reply. Runs on the listener's event loop.""" + + def __init__(self) -> None: + self._unreported = 0 + self._reported_at: float | None = None + + def note(self) -> str | None: + """Count one replaced reply, and return the reason of the event due now, if one is.""" + self._unreported += 1 + now = time.monotonic() + if self._reported_at is not None and now - self._reported_at < REPLY_REPLACED_EVENT_SECONDS: + return None + count, self._unreported, self._reported_at = self._unreported, 0, now + return ( + f"{count} reply(ies) since the last report held characters the inbound charset " + "cannot encode, and each was replaced" + ) def frame_for_delivery(codec: FrameCodec, payload: str, encoding: str, *, transport: str) -> bytes: diff --git a/messagefoundry/transports/mllp.py b/messagefoundry/transports/mllp.py index 3a693b9460..13e58aad00 100644 --- a/messagefoundry/transports/mllp.py +++ b/messagefoundry/transports/mllp.py @@ -130,7 +130,7 @@ from messagefoundry.transports.base import cap_setting as _cap_setting from messagefoundry.transports.framing import ( MLLP_CODEC, - REPLY_REPLACED_REASON, + ReplyReplacements, check_frame_bytes, declared_encoding, frame_for_delivery, @@ -2373,6 +2373,7 @@ def __init__(self, config: Source) -> None: self.max_messages_per_second, self.message_burst = _pacing_settings(s) # Carried only so a pacing report can name this connection (BACKLOG #290). self._pacing_name = config.name or "" + self._reply_replacements = ReplyReplacements() # BACKLOG #5799 # Per-connection peer-IP allowlist (Tier 4 operability): when set, a connecting peer whose IP # is not listed is refused before anything reads its socket -- with TLS on, that is before # the handshake, on every loop (BACKLOG #1606; see _TLS_HANDSHAKE_TIMEOUT). Absent/empty = no @@ -2996,6 +2997,12 @@ async def stop(self) -> None: logger.warning("MLLP server.wait_closed() exceeded shutdown grace; abandoning") self._server = None + async def _note_reply_replaced(self, peer_host: str | None) -> None: + """Count one replaced reply, and send the throttled ``reply_replaced`` event if one is due.""" + reason = self._reply_replacements.note() + if reason is not None: + await self._emit_event("reply_replaced", peer_host=peer_host, reason=reason) + async def _emit_event( self, kind: str, *, peer_host: str | None = None, reason: str | None = None ) -> None: @@ -3137,9 +3144,7 @@ async def _answer_handler_failure( ) await self._emit_event("handler_error", peer_host=peer_host, reason=reason) if framed is not None and framed[1]: - await self._emit_event( - "reply_replaced", peer_host=peer_host, reason=REPLY_REPLACED_REASON - ) + await self._note_reply_replaced(peer_host) return owed, nak async def _on_client( @@ -3326,15 +3331,10 @@ async def _on_client( ) writer.write(wire) if replaced: - # BACKLOG #5799: the log line is once per connection; the - # event is sent for each reply whose characters the charset - # forced a replacement of. A frame byte turned into a space - # is not one of those, and writes only its warning. - await self._emit_event( - "reply_replaced", - peer_host=peer_host, - reason=REPLY_REPLACED_REASON, - ) + # BACKLOG #5799: a reply whose characters the charset forced + # a replacement of, throttled per listener. A frame byte + # turned into a space is not one, and writes only its warning. + await self._note_reply_replaced(peer_host) await self._drain_ack(writer) if unlisted and decoded: # BACKLOG #4907: every frame this read completed was recorded above, diff --git a/messagefoundry/transports/tcp.py b/messagefoundry/transports/tcp.py index a35786b3c5..880704ecd4 100644 --- a/messagefoundry/transports/tcp.py +++ b/messagefoundry/transports/tcp.py @@ -54,9 +54,9 @@ wait_for_intake, ) from messagefoundry.transports.framing import ( - REPLY_REPLACED_REASON, FrameCodec, FrameError, + ReplyReplacements, check_frame_bytes, codec_for, declared_encoding, @@ -539,6 +539,7 @@ def __init__(self, config: Source) -> None: ) # Carried only so a pacing report can name this connection (BACKLOG #290). self._pacing_name = config.name or "" + self._reply_replacements = ReplyReplacements() # BACKLOG #5799 # Per-connection peer-IP allowlist (Tier 4 operability): refuse a non-listed peer at accept. # Absent/empty = no restriction. Mirrors MLLPSource. sa = s.get("source_ip_allowlist") @@ -738,12 +739,10 @@ async def _on_client(self, reader: asyncio.StreamReader, writer: asyncio.StreamW connection=self._pacing_name, ) writer.write(wire) - if replaced: - # BACKLOG #5799, as the MLLP listener records it. + if replaced and (note := self._reply_replacements.note()): + # BACKLOG #5799, throttled as the MLLP listener throttles it. await self._emit_event( - "reply_replaced", - peer_host=peer_host, - reason=REPLY_REPLACED_REASON, + "reply_replaced", peer_host=peer_host, reason=note ) await self._drain_reply(writer) if failed: diff --git a/messagefoundry/transports/x12.py b/messagefoundry/transports/x12.py index 4efdb3c7d2..cf292334eb 100644 --- a/messagefoundry/transports/x12.py +++ b/messagefoundry/transports/x12.py @@ -68,7 +68,7 @@ wait_for_intake, ) from messagefoundry.transports.framing import ( - REPLY_REPLACED_REASON, + ReplyReplacements, declared_encoding, encode_reply_reporting, ) @@ -771,6 +771,7 @@ def __init__(self, config: Source) -> None: # Names this connection in a pacing report (BACKLOG #290) and in the reply-encoding warnings # (BACKLOG #5958). self._pacing_name = config.name or "" + self._reply_replacements = ReplyReplacements() # BACKLOG #5799 # Per-connection peer-IP allowlist (Tier 4 operability): refuse a non-listed peer at accept. # Absent/empty = no restriction. Mirrors TcpSource/MLLPSource. sa = s.get("source_ip_allowlist") @@ -1072,12 +1073,10 @@ async def _on_client(self, reader: asyncio.StreamReader, writer: asyncio.StreamW break continue writer.write(wire) # unframed: the interchange is the frame - if replaced: - # BACKLOG #5799, as the MLLP listener records it. + if replaced and (note := self._reply_replacements.note()): + # BACKLOG #5799, throttled as the MLLP listener throttles it. await self._emit_event( - "reply_replaced", - peer_host=peer_host, - reason=REPLY_REPLACED_REASON, + "reply_replaced", peer_host=peer_host, reason=note ) await self._drain_reply(writer) if failed: diff --git a/tests/test_mllp_handler_failure.py b/tests/test_mllp_handler_failure.py index 27123be758..bd1b6ec14b 100644 --- a/tests/test_mllp_handler_failure.py +++ b/tests/test_mllp_handler_failure.py @@ -26,6 +26,7 @@ import contextlib import logging import sys +import time from collections.abc import Callable from pathlib import Path from typing import Any, NoReturn @@ -647,18 +648,19 @@ async def narrow(raw: bytes) -> str: assert "framing_error" not in cap.kinds(), cap.kinds() -async def test_each_reply_a_narrow_charset_altered_writes_a_reply_replaced_event( +async def test_a_burst_of_altered_replies_writes_one_throttled_reply_replaced_event( monkeypatch: pytest.MonkeyPatch, ) -> None: # BACKLOG #5799 item 1: the replacement's WARNING is logged once per connection per process, so - # without an event the second altered ACK left no record at all. Each altered reply now writes - # one `reply_replaced` event with a fixed reason; a clean reply writes none. Red on the code - # before: the event list holds no `reply_replaced`. + # without an event the second altered ACK left no record at all. The event is throttled per + # listener, so a burst inside one window writes one event, not one per message, which could + # fill the runner's bounded event queue and crowd other kinds out. Red on the code before: no + # `reply_replaced`; red with an unthrottled event: twenty of them. monkeypatch.setattr(framing_mod, "_reply_replacement_logged", set()) cap = _Capture() source = _mllp(encoding="ascii") source.on_connection_event = cap - texts = iter(["café", "plain", "naïve"]) + texts = iter(["café", "plain"] + ["naïve"] * 19) async def narrow(raw: bytes) -> str: return build_ack(raw, code="AA", text=next(texts)) @@ -666,7 +668,7 @@ async def narrow(raw: bytes) -> str: await source.start(narrow) try: reader, writer = await asyncio.open_connection("127.0.0.1", source.sockport) - for _ in range(3): + for _ in range(21): writer.write(frame(_ADT)) await writer.drain() await _read_reply(reader) @@ -675,9 +677,27 @@ async def narrow(raw: bytes) -> str: finally: await asyncio.wait_for(source.stop(), timeout=5.0) replaced = [e for e in cap.events if e[0] == "reply_replaced"] - assert len(replaced) == 2, cap.events - assert all(reason == framing_mod.REPLY_REPLACED_REASON for _, _, reason in replaced) - assert all(host is not None for _, host, _ in replaced) + assert len(replaced) == 1, cap.events + assert replaced[0][1] is not None and replaced[0][2] is not None + assert replaced[0][2].startswith("1 reply(ies) since the last report") + assert "naïve" not in replaced[0][2] and "ascii" not in replaced[0][2] + + +def test_the_reply_replaced_throttle_reports_the_count_once_the_window_passes( + monkeypatch: pytest.MonkeyPatch, +) -> None: + # BACKLOG #5799 item 1: the first at once, then at most one per window, carrying the count of + # replaced replies since the last report. + clock = [1000.0] + monkeypatch.setattr(time, "monotonic", lambda: clock[0]) + throttle = framing_mod.ReplyReplacements() + first = throttle.note() + assert first is not None and first.startswith("1 reply(ies)") + assert [throttle.note() for _ in range(500)] == [None] * 500 + clock[0] += framing_mod.REPLY_REPLACED_EVENT_SECONDS + later = throttle.note() + assert later is not None and later.startswith("501 reply(ies)") + assert throttle.note() is None async def test_a_handler_fault_nak_the_charset_altered_writes_a_reply_replaced_event( diff --git a/tests/test_tcp_x12_handler_failure.py b/tests/test_tcp_x12_handler_failure.py index 2b31950b46..989f80271e 100644 --- a/tests/test_tcp_x12_handler_failure.py +++ b/tests/test_tcp_x12_handler_failure.py @@ -394,7 +394,8 @@ async def handler(raw: bytes) -> str: # BACKLOG #5799 item 1: the altered reply is recorded as an event, not only in the warn-once # log line. Red on the code before: no `reply_replaced` in the events. replaced = [e for e in events if e[0] == "reply_replaced"] - assert [reason for _, _, reason in replaced] == [framing_mod.REPLY_REPLACED_REASON], name + assert len(replaced) == 1, name + assert str(replaced[0][2]).startswith("1 reply(ies) since the last report"), name async def test_an_x12_reply_in_an_unusable_charset_name_is_sent_in_utf8( @@ -482,8 +483,8 @@ async def narrow_reply(raw: bytes) -> str: events = await _drive(source, _ThenEof(EDI * 2), writer, handler=narrow_reply) assert seen == [EDI] * 2 assert writer.written == [b"synthetic reply ?"] * 2 - # One `reply_replaced` per altered reply (BACKLOG #5799 item 1). - assert _kinds(events) == ["established", "reply_replaced", "reply_replaced", "closed"] + # One `reply_replaced` for both altered replies: the event is throttled (BACKLOG #5799 item 1). + assert _kinds(events) == ["established", "reply_replaced", "closed"] assert_capture_sees(caplog, "messagefoundry.transports.x12") assert not [r for r in caplog.records if r.levelno >= logging.ERROR] From 872daee6970f8ce8a6ec256778c365d0b95dee87 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sat, 21 Nov 2026 22:09:57 -0600 Subject: [PATCH 59/74] Server schema check: Wave 3 assembly repair BACKLOG #5062. On aa8f78db790: - tests/test_security_static.py found a nested-quantifier regex, the cast-key pattern; it is now a hand scan, _casts_a_column. - _quoted_end read the [ of ARRAY[']'] as a bracketed name, so an EXEC'd CHECK holding one raised "unterminated quote" where main read it; a [ right after a word or a ] now opens none. - _statement_end stopped at a data word such as merge or delete, and at a $-joined word, so a dropped partial index stayed in the expected shape; it now reads through them, and its docstring no longer claims reading too far can only raise more. - Opaque index words were keyed by bare index name, which on SQL Server is unique only per table; they are now keyed by table and index, with the index's key columns kept beside them. Proposed PR title: Server schema check reads or refuses the DDL forms it misread; pin the keyless-chain serve-before-rotate-key stamp (BACKLOG #5062, #4942) Proposed banners: as in 219d3f48f6d's body, with the open review findings added to #5062's remainder. --- messagefoundry/store/server_schema_verify.py | 83 +++++++++++++------- tests/test_server_schema_verify_5062.py | 42 ++++++++++ 2 files changed, 97 insertions(+), 28 deletions(-) diff --git a/messagefoundry/store/server_schema_verify.py b/messagefoundry/store/server_schema_verify.py index e33cf32aed..99e092c0df 100644 --- a/messagefoundry/store/server_schema_verify.py +++ b/messagefoundry/store/server_schema_verify.py @@ -190,13 +190,6 @@ #: PostgreSQL's ``PRIMARY KEY`` or ``UNIQUE`` ``USING INDEX ``, which turns an existing index #: into the constraint. ``USING INDEX TABLESPACE`` is only a storage option. _USING_INDEX = re.compile(r"\bUSING\s+INDEX\b(?!\s*TABLESPACE\b)", re.I) -#: A key that opens with a cast of a column, ``a::text`` or ``CAST(a AS text)``. PostgreSQL stores -#: a cast to the column's own type as the column, and any other as an expression, and the reader -#: does not know which. -_CAST_KEY = re.compile( - r'^(?:\(\s*)*(?:"[^"]+"|\w+)(?:\s*\))*\s*::|^CAST\s*\(\s*\(*\s*(?:"[^"]+"|\w+)\s*\)*\s+AS\b', - re.I, -) _PLAIN_KEY = re.compile(r'^(\[?[A-Za-z_][\w$]*\]?|"[^"]+")(?:\s+(ASC|DESC))?$', re.I) _PLAIN_NAME = re.compile(r'^(?:\[?[A-Za-z_][\w$]*\]?|"[^"]+")$') #: A key that is an expression: a call such as ``left(actor, 200)``, or a parenthesised expression. @@ -357,6 +350,8 @@ def _quoted_end(text: str, i: int) -> int | None: ch = text[i] if ch not in "'\"[": return None + if ch == "[" and i > 0 and (text[i - 1].isalnum() or text[i - 1] in "_$]"): + return None # a subscript or an ARRAY[...] literal, as in ARRAY[']'] close = "]" if ch == "[" else ch j = i + 1 while (end := text.find(close, j)) >= 0: @@ -468,8 +463,8 @@ def _clause(segment: str) -> str: def _statement_end(text: str, start: int) -> int: """Where the statement that ``text[start:]`` continues ends: a top-level ``;``, an unmatched ``)``, a word that starts the next statement, or the end. Unlike :func:`_clause` it reads on - through ``ELSE`` and ``END``, which a ``CASE`` in an index predicate holds, so it may read into a - following block; reading too far only adds words, which raises more, never fewer.""" + through ``ELSE`` and ``END``, which a ``CASE`` in an index predicate holds, and through a data + word, so it may read into a following block or statement.""" depth, i = 0, start while i < len(text): if (end := _quoted_end(text, i)) is not None: @@ -484,14 +479,17 @@ def _statement_end(text: str, start: int) -> int: depth -= 1 elif depth == 0 and ch == ";": break - elif depth == 0 and (ch.isalpha() or ch == "_") and not text[i - 1].isalnum(): - word = re.match(r"\w+", text[i:]) + elif ( + depth == 0 + and (ch.isalpha() or ch == "_") + and not (text[i - 1].isalnum() or text[i - 1] in "_$") + ): + word = re.match(r"[\w$]+", text[i:]) assert word is not None lower = word.group(0).lower() - if ( - lower in ("if", "begin", "exec", "execute", "declare", "go", "create") - or lower in _DATA_STATEMENT - or (lower in ("alter", "drop") and _DDL_OBJECT.match(text, i + len(lower))) + # A data word does not end it: PostgreSQL takes merge or delete as a column's name. + if lower in ("if", "begin", "exec", "execute", "declare", "go", "create") or ( + lower in ("alter", "drop") and _DDL_OBJECT.match(text, i + len(lower)) ): break i += len(lower) @@ -802,7 +800,7 @@ def _declared_key(text: str) -> str: inner = inner[1:-1].strip() if _PLAIN_NAME.match(inner): key = inner - elif _CAST_KEY.match(inner): + elif _casts_a_column(inner): raise ValueError(f"index key {text!r} is a cast the live-schema check cannot place") elif inner != key and re.search(r"\bCOLLATE\b", inner, re.I): # PostgreSQL stores ((col COLLATE x)) as the column with an index collation. @@ -820,6 +818,22 @@ def _declared_key(text: str) -> str: return key_column(key) +def _casts_a_column(key: str) -> bool: + """Whether ``key`` opens with a cast of a column: ``a::text``, ``(a)::text`` or + ``CAST(a AS text)``. PostgreSQL stores a cast to the column's own type as the column, and any + other as an expression, and the reader does not know which. Read by hand, not by one pattern, because the parentheses around the name + repeat and a pattern for them nests one quantifier in another.""" + cast = re.match(r"CAST\s*\(", key, re.I) + rest = (key[cast.end() :] if cast else key).lstrip("( \t\r\n") + name = re.match(r'"[^"]+"|\w+', rest) + if name is None: + return False + after = rest[name.end() :].lstrip(") \t\r\n") + if cast: + return after != rest[name.end() :] and re.match(r"AS\b", after, re.I) is not None + return after.startswith("::") + + def _expression_end(key: str) -> int | None: """Where the expression that opens ``key`` ends, or ``None`` when ``key`` does not open with one or its parentheses do not balance.""" @@ -929,9 +943,11 @@ def __init__(self, dialect: Dialect | None) -> None: self.columns: dict[str, dict[str, _Built]] = {} self.indexes: dict[str, IndexShape] = {} #: The words of each index whose key, INCLUDE list or predicate may name a column its key - #: columns do not show: an expression key, an INCLUDE or a WHERE. A DROP COLUMN of one of - #: those words raises, because PostgreSQL drops such an index and the reader cannot tell. - self.opaque: dict[str, frozenset[str]] = {} + #: columns do not show: an expression key, an INCLUDE or a WHERE, with its plain key + #: columns. A DROP COLUMN of one of those words that is not a key column raises, because + #: PostgreSQL drops such an index and the reader cannot tell. Keyed by table and index, + #: because a SQL Server index name is unique only within its table. + self.opaque: dict[tuple[str, str], tuple[frozenset[str], frozenset[str]]] = {} #: The tables a CREATE TABLE has built and no DROP TABLE has removed since. self.created: set[str] = set() @@ -985,7 +1001,7 @@ def index(self, text: str, m: re.Match[str]) -> None: text[end:].lstrip().upper().startswith("WHERE"), ) self.indexes[name] = shape - self.opaque.pop(name, None) + self.opaque.pop((shape.table, name), None) if include or shape.partial or any(k.startswith("") for k in shape.columns): # To the statement's end: a predicate has no closing mark of its own. Inside an # EXEC string, to the string's end, its quotes undoubled, as alter() reads one. @@ -999,7 +1015,10 @@ def index(self, text: str, m: re.Match[str]) -> None: with contextlib.suppress(ValueError): tail = tail[: _statement_end(tail, 1)] definition = text[m.end() : end] + tail - self.opaque[name] = frozenset(_ident(w) for w in _TOKEN.findall(definition)) + self.opaque[(shape.table, name)] = ( + frozenset(_ident(w) for w in _TOKEN.findall(definition)), + frozenset(k.split(" ", 1)[0] for k in shape.columns), + ) def _built(self, table: str, name: str, action: str) -> _Built: cols = self.columns.get(table) @@ -1040,12 +1059,13 @@ def alter(self, text: str, m: re.Match[str], spans: list[tuple[int, int]]) -> No elif verb == ["drop", "column"]: name = re.sub(r"^DROP\s+COLUMN\s+(?:IF\s+EXISTS\s+)?", "", clause, flags=re.I) column = _bare(_TOKEN.findall(name)[0]) - for index, used in self.opaque.items(): - shape = self.indexes.get(index) - if shape is None or shape.table != table or column not in used: + for (on, index), (used, keys) in list(self.opaque.items()): + if on != table or column not in used: continue - if column not in (k.split(" ", 1)[0] for k in shape.columns): + if column in keys: # A key column takes the index with it, as _rewrite_keys below does. + del self.opaque[(on, index)] + else: raise ValueError( f"a drop column of {table}.{column}, which index {index}'s expression," " INCLUDE or predicate may use, so the reader cannot tell whether it goes" @@ -1132,9 +1152,12 @@ def _rename(self, table: str, old: str, new: str) -> None: if moved is not None: built.later |= moved.ways() self._rewrite_keys(table, old, new) - for index, used in list(self.opaque.items()): - if old in used and index in self.indexes and self.indexes[index].table == table: - self.opaque[index] = (used - {old}) | {new} + for (on, index), (used, keys) in list(self.opaque.items()): + if on == table: + self.opaque[(on, index)] = ( + (used - {old}) | ({new} if old in used else set()), + (keys - {old}) | ({new} if old in keys else set()), + ) def rename(self, m: re.Match[str]) -> None: if m["old"].count(".") != 1: @@ -1149,6 +1172,8 @@ def drop_tables(self, m: re.Match[str]) -> None: self.created.discard(table) for index in [n for n, shape in self.indexes.items() if shape.table == table]: del self.indexes[index] + for key in [k for k in self.opaque if k[0] == table]: + del self.opaque[key] def drop_indexes(self, m: re.Match[str]) -> None: """Each index named, but on SQL Server only on the table its ``ON`` names: a name is unique @@ -1163,6 +1188,8 @@ def drop_indexes(self, m: re.Match[str]) -> None: shape = self.indexes.get(name) if shape is not None and (on is None or shape.table == on): del self.indexes[name] + for key in [k for k in self.opaque if k[1] == name and on in (None, k[0])]: + del self.opaque[key] def shape(self) -> ServerSchemaShape: shapes: dict[str, Mapping[str, ColumnShape]] = {} diff --git a/tests/test_server_schema_verify_5062.py b/tests/test_server_schema_verify_5062.py index 15e3ff45f2..ae5f5ad92d 100644 --- a/tests/test_server_schema_verify_5062.py +++ b/tests/test_server_schema_verify_5062.py @@ -462,3 +462,45 @@ def test_a_partial_index_in_nested_dynamic_sql_is_read() -> None: "sqlserver", ) assert shape.named_indexes["ix"].partial + + +# --- Wave 3 assembly repair -------------------------------------------------------------------- + + +def test_an_array_literal_holding_a_bracket_is_not_a_bracketed_name() -> None: + shape = declared_schema( + ( + "CREATE TABLE t (a TEXT)", + "EXEC('ALTER TABLE t ADD CONSTRAINT ck CHECK (a <> ARRAY['']''])')", + ), + "postgres", + ) + assert shape.columns["t"] == frozenset({"a"}) + + +@pytest.mark.parametrize("word", ["merge", "delete", "x$delete"]) +def test_a_data_word_in_a_predicate_does_not_end_the_opaque_words(word: str) -> None: + with pytest.raises(ValueError, match="drop column"): + declared_schema( + ( + f"CREATE TABLE t (a INT, {word} INT, c INT)", + f"CREATE INDEX ix ON t (a) WHERE {word} > 0 AND c IS NULL", + "ALTER TABLE t DROP COLUMN c", + ) + ) + + +def test_opaque_words_are_kept_per_table_on_sqlserver() -> None: + """A SQL Server index name is unique only within its table, so a plain ix on u must not hide + the partial ix on t.""" + with pytest.raises(ValueError, match="drop column"): + declared_schema( + ( + "CREATE TABLE t (a INT NULL, c INT NULL)", + "CREATE TABLE u (a INT NULL, c INT NULL)", + "CREATE INDEX ix ON t (a) WHERE c > 0", + "CREATE INDEX ix ON u (a)", + "ALTER TABLE t DROP COLUMN c", + ), + "sqlserver", + ) From bb3afd0194ca53785517a21690693494eece6268 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sat, 21 Nov 2026 22:27:14 -0600 Subject: [PATCH 60/74] Server schema check: a SQL Server data statement ends a predicate again BACKLOG #5062. Review round 11836ae401 on aa8f78db790..872daee6970 found one regression against origin/main: with the data-word stop removed, a SQL Server partial index followed by an unterminated UPDATE read the UPDATE's columns as the index's, so a valid DROP COLUMN raised. On SQL Server a data word is reserved, so it ends the scan again; off SQL Server it still reads through, as PostgreSQL takes it as a column's name. Proposed PR title: Server schema check reads or refuses the DDL forms it misread; pin the keyless-chain serve-before-rotate-key stamp (BACKLOG #5062, #4942) Proposed banners: as in 219d3f48f6d's body, with the open review findings added to #5062's remainder. --- messagefoundry/store/server_schema_verify.py | 17 ++++++++++------- tests/test_server_schema_verify_5062.py | 14 ++++++++++++++ 2 files changed, 24 insertions(+), 7 deletions(-) diff --git a/messagefoundry/store/server_schema_verify.py b/messagefoundry/store/server_schema_verify.py index 99e092c0df..1d0e3e41b8 100644 --- a/messagefoundry/store/server_schema_verify.py +++ b/messagefoundry/store/server_schema_verify.py @@ -460,11 +460,13 @@ def _clause(segment: str) -> str: return segment[:i].strip() -def _statement_end(text: str, start: int) -> int: +def _statement_end(text: str, start: int, dialect: Dialect | None) -> int: """Where the statement that ``text[start:]`` continues ends: a top-level ``;``, an unmatched ``)``, a word that starts the next statement, or the end. Unlike :func:`_clause` it reads on - through ``ELSE`` and ``END``, which a ``CASE`` in an index predicate holds, and through a data - word, so it may read into a following block or statement.""" + through ``ELSE`` and ``END``, which a ``CASE`` in an index predicate holds, so it may read into a + following block. Off SQL Server it reads through a data word too, which PostgreSQL takes as a + column's name, so it may also read into a following statement; on SQL Server a data word is + reserved and ends it.""" depth, i = 0, start while i < len(text): if (end := _quoted_end(text, i)) is not None: @@ -487,9 +489,10 @@ def _statement_end(text: str, start: int) -> int: word = re.match(r"[\w$]+", text[i:]) assert word is not None lower = word.group(0).lower() - # A data word does not end it: PostgreSQL takes merge or delete as a column's name. - if lower in ("if", "begin", "exec", "execute", "declare", "go", "create") or ( - lower in ("alter", "drop") and _DDL_OBJECT.match(text, i + len(lower)) + if ( + lower in ("if", "begin", "exec", "execute", "declare", "go", "create") + or (dialect == "sqlserver" and lower in _DATA_STATEMENT) + or (lower in ("alter", "drop") and _DDL_OBJECT.match(text, i + len(lower))) ): break i += len(lower) @@ -1013,7 +1016,7 @@ def index(self, text: str, m: re.Match[str]) -> None: tail = " " + tail # so the scan never starts at index 0 # Nested dynamic SQL's quotes can defeat the scan: keep it all, which only raises more. with contextlib.suppress(ValueError): - tail = tail[: _statement_end(tail, 1)] + tail = tail[: _statement_end(tail, 1, self.dialect)] definition = text[m.end() : end] + tail self.opaque[(shape.table, name)] = ( frozenset(_ident(w) for w in _TOKEN.findall(definition)), diff --git a/tests/test_server_schema_verify_5062.py b/tests/test_server_schema_verify_5062.py index ae5f5ad92d..f3eb84228f 100644 --- a/tests/test_server_schema_verify_5062.py +++ b/tests/test_server_schema_verify_5062.py @@ -504,3 +504,17 @@ def test_opaque_words_are_kept_per_table_on_sqlserver() -> None: ), "sqlserver", ) + + +def test_a_sqlserver_data_statement_ends_an_unterminated_predicate() -> None: + """On SQL Server UPDATE is reserved, so it starts the next statement, whose words are not the + index's.""" + shape = declared_schema( + ( + "CREATE TABLE t (a INT NULL, c INT NULL, d INT NULL)", + "CREATE INDEX ix ON t (a) WHERE c > 0\nUPDATE t SET d = 1", + "ALTER TABLE t DROP COLUMN d", + ), + "sqlserver", + ) + assert "ix" in shape.named_indexes From 1828eda4cc81c10d6fb045ad8820fe08d8943168 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sat, 21 Nov 2026 23:26:51 -0600 Subject: [PATCH 61/74] Name only the two step-up refusals _record_route_refusal covers docs/SECURITY.md and the _recorded_decision docstring read as if _record_route_refusal covers every refusal a route body makes. They now name the step-up refusals of spend_step_up_action and refuse_unless_step_up_window_live, and say other route-body refusals after the gate passed write no auth.gate_refused row. BACKLOG #1197 (ASVS 16.3.2). Proposed PR title: Route-body step-up refusals write an audit row (BACKLOG #1197) Proposed ledger banner for #1197: as in commit b147a802513. --- docs/SECURITY.md | 6 ++++-- messagefoundry/api/security.py | 6 ++++-- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/docs/SECURITY.md b/docs/SECURITY.md index 6565a59ee8..2875ad0e28 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -5332,8 +5332,10 @@ flowchart TB `auth.gate_refused`, naming the same permission and a `reason` of `throttled` or `step_up`. It writes that row only where it would have written the grant row, so a gate that writes no grant row writes no refusal row either. A refused second factor writes `auth.mfa_denied`, as the base - gate's does. For a refusal a route body makes after its gate has passed, - `_record_route_refusal` in `messagefoundry/api/security.py` says what it records. + gate's does. For the step-up refusals of `spend_step_up_action` and + `refuse_unless_step_up_window_live`, which a route body makes after its gate has passed, + `_record_route_refusal` in `messagefoundry/api/security.py` says what it records. Other refusals + a route body makes after its gate has passed write no `auth.gate_refused` row. - Routes that act on a Connection also check the identity's connection scope. That scope starts empty for every role except Administrator. - Sensitive routes add a step-up re-check on top of this flow. See diff --git a/messagefoundry/api/security.py b/messagefoundry/api/security.py index e91a764ec3..45d12d14d6 100644 --- a/messagefoundry/api/security.py +++ b/messagefoundry/api/security.py @@ -1482,8 +1482,10 @@ async def _recorded_decision( A refusal row is written exactly where the grant row would have been, so a gate writes at most one decision row per request, and a gate that wrote no grant row writes no refusal row either. The audit chain has no drain (BACKLOG #1421); a refused route-body request writes at most two - decision rows. For a refusal a route body makes after its gate admitted the - request, see :func:`_record_route_refusal`. The reason comes from the + decision rows. For the step-up refusals of :func:`spend_step_up_action` and + :func:`refuse_unless_step_up_window_live`, made in a route body after its gate admitted the + request, see :func:`_record_route_refusal`. Other refusals a route body makes after its gate + admitted the request write no ``auth.gate_refused`` row. The reason comes from the :class:`_GateRefusal` the check raised. Any other exception leaves the block with no decision row from it, which is right for the :func:`_mfa_refusal` 403: it wrote its own ``auth.mfa_denied`` row where it was raised. A failed refusal-row write raises in place of the From 384b12c5732c3d767733b1d0a5bc6a87b1a82072 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sun, 22 Nov 2026 02:25:16 -0600 Subject: [PATCH 62/74] Name the view that stopped the upgrade when one name prefixes another _foreign_object picked the longest view or trigger name that fit the error text. With views vv and "vv after", SQLite's re-check message for vv, "error in view vv after drop column: ...", fits both, so the drop remedy named "vv after", which was not the cause. The store was still refused. A candidate whose remainder starts with the colon now wins, then one whose remainder starts with " after ", then any other; within one rank the longest wins. A new test plants both views, takes each cause from SQLite's own text in both directions, with and without the suffix, and checks the object named. On the pre-fix code its vv-after-the-change case fails. Repairs the Lander hold on PR 3143, item H1. BACKLOG #6719, #6720. --- messagefoundry/store/schema_verify.py | 15 +++++-- tests/test_schema_verify_6719_6720.py | 57 +++++++++++++++++++++++++++ 2 files changed, 68 insertions(+), 4 deletions(-) diff --git a/messagefoundry/store/schema_verify.py b/messagefoundry/store/schema_verify.py index 8374fc66f8..fe702e2864 100644 --- a/messagefoundry/store/schema_verify.py +++ b/messagefoundry/store/schema_verify.py @@ -464,18 +464,25 @@ async def _foreign_object(db: aiosqlite.Connection, cause: str) -> tuple[str, st The name is matched against the live file's views and triggers, never cut out of the text: the text may add a suffix after the name, and a quoted name may hold a colon. A SQLite error while - telling falls back to ``None``, the plain remedy.""" + telling falls back to ``None``, the plain remedy. + + SQLite writes "error in view V: ..." or, on its re-check after the change, "error in view V + after drop column: ...". So when several names fit, as ``vv`` and ``vv after`` both fit "error + in view vv after drop column: ...", one whose remainder starts with the colon wins, then one + whose remainder starts with " after ", then any other; among names of one rank the longest wins. + The longest alone would name ``vv after`` there, which is not the cause.""" try: async with db.execute(_FOREIGN_OBJECTS_SQL) as cur: objects = [(str(kind), str(name)) for kind, name in await cur.fetchall()] - named = [] + named: list[tuple[int, str, str]] = [] for kind, name in objects: rest = cause.removeprefix(f"error in {kind} {name}") if rest != cause and rest[:1] in (":", " "): - named.append((kind, name)) + rank = 0 if rest.startswith(":") else 1 if rest.startswith(" after ") else 2 + named.append((rank, kind, name)) if not named: return None - kind, name = max(named, key=lambda o: len(o[1])) + _, kind, name = min(named, key=lambda o: (o[0], -len(o[2]))) if kind == "view" and name.lower() in await _names_this_build_creates(): return None except sqlite3.Error as exc: diff --git a/tests/test_schema_verify_6719_6720.py b/tests/test_schema_verify_6719_6720.py index 3e6ccb4a4b..17c7cc6389 100644 --- a/tests/test_schema_verify_6719_6720.py +++ b/tests/test_schema_verify_6719_6720.py @@ -597,6 +597,63 @@ async def test_the_foreign_object_is_matched_against_the_file( assert await _foreign_object(db, cause) == found +@pytest.mark.parametrize( + ("cause_view", "reads", "statement", "expected_cause"), + [ + pytest.param( + "vv", + "c FROM t", + "ALTER TABLE t DROP COLUMN c", + "error in view vv after drop column: no such column: c", + id="vv-after-the-change", + ), + pytest.param( + "vv after", + "c FROM t", + "ALTER TABLE t DROP COLUMN c", + "error in view vv after after drop column: no such column: c", + id="vv-after-after-the-change", + ), + pytest.param( + "vv", + "missing FROM t", + "ALTER TABLE t RENAME TO t2", + "error in view vv: no such column: missing", + id="vv-before-the-change", + ), + pytest.param( + "vv after", + "missing FROM t", + "ALTER TABLE t RENAME TO t2", + "error in view vv after: no such column: missing", + id="vv-after-before-the-change", + ), + ], +) +async def test_a_name_that_is_a_prefix_of_another_is_told_apart( + tmp_path: Path, cause_view: str, reads: str, statement: str, expected_cause: str +) -> None: + # Views "vv" and "vv after" both fit "error in view vv after ...", so the longest name alone + # would tell the operator to drop "vv after" when "vv" stopped the change. Each cause is + # SQLite's own text. A view already broken fails SQLite's first check, with no suffix; a view + # the change breaks fails its re-check after the change, with the "after drop column" suffix. + from messagefoundry.store.schema_verify import _foreign_object + + path = tmp_path / "prefix.db" + _sql(path, "CREATE TABLE t (a, c)", "CREATE TABLE u (c)") + for view in ("vv", "vv after"): + _sql(path, f'CREATE VIEW "{view}" AS SELECT {reads if view == cause_view else "c FROM u"}') + conn = sqlite3.connect(path) + try: + with pytest.raises(sqlite3.OperationalError) as info: + conn.execute(statement) + finally: + conn.close() + assert str(info.value) == expected_cause + async with _connected(path) as db: + assert await _foreign_object(db, expected_cause) == ("view", cause_view) + + # --- BACKLOG #6720 item 1: a foreign view using an unloaded function or collation ---------------- From 8caa4028a53e53215fdb0ed886b7c042d01d9788 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sun, 22 Nov 2026 02:39:30 -0600 Subject: [PATCH 63/74] Rank a colon and " after " together when telling a prefix name apart Review round one of the previous commit measured a regression: ranking the colon above " after " names the healthy view vv, not "vv: x", for "error in view vv: x after rename: ...". The longest-name rule had named the right one. A quoted name may hold a colon, so the colon and " after " now share the first rank, any other remainder ranks last, and the longest name of the first rank present wins. This departs from the hold's literal order (colon, then " after ", then longest) only where a colon name is involved, and gives the same answer in every case the hold describes. The docstring no longer lists SQLite's forms; it points to the note above _FOREIGN_OBJECTS_SQL. A new test covers the " after rename" suffix the RENAME COLUMN migration writes, a colon-named view and a trigger pair. Repairs the Lander hold on PR 3143, item H1. BACKLOG #6719, #6720. --- messagefoundry/store/schema_verify.py | 19 ++++---- tests/test_schema_verify_6719_6720.py | 66 +++++++++++++++++++++++++++ 2 files changed, 76 insertions(+), 9 deletions(-) diff --git a/messagefoundry/store/schema_verify.py b/messagefoundry/store/schema_verify.py index fe702e2864..7ccbdf9c17 100644 --- a/messagefoundry/store/schema_verify.py +++ b/messagefoundry/store/schema_verify.py @@ -466,23 +466,24 @@ async def _foreign_object(db: aiosqlite.Connection, cause: str) -> tuple[str, st text may add a suffix after the name, and a quoted name may hold a colon. A SQLite error while telling falls back to ``None``, the plain remedy. - SQLite writes "error in view V: ..." or, on its re-check after the change, "error in view V - after drop column: ...". So when several names fit, as ``vv`` and ``vv after`` both fit "error - in view vv after drop column: ...", one whose remainder starts with the colon wins, then one - whose remainder starts with " after ", then any other; among names of one rank the longest wins. - The longest alone would name ``vv after`` there, which is not the cause.""" + Several names can fit one text (the forms are in the note above ``_FOREIGN_OBJECTS_SQL``): + ``vv`` and ``vv after`` both fit "error in view vv after rename: ...". So a name whose remainder + starts with the colon or with " after " ranks first, any other name last, and the longest name + of the first rank present wins. The longest alone named ``vv after`` there, which is not the + cause. The colon and " after " share a rank because a quoted name may hold either: with ``vv`` + and ``vv: x``, "error in view vv: x after rename: ..." names ``vv: x``.""" try: async with db.execute(_FOREIGN_OBJECTS_SQL) as cur: objects = [(str(kind), str(name)) for kind, name in await cur.fetchall()] - named: list[tuple[int, str, str]] = [] + named: list[tuple[bool, str, str]] = [] for kind, name in objects: rest = cause.removeprefix(f"error in {kind} {name}") if rest != cause and rest[:1] in (":", " "): - rank = 0 if rest.startswith(":") else 1 if rest.startswith(" after ") else 2 - named.append((rank, kind, name)) + exact = rest.startswith((":", " after ")) + named.append((exact, kind, name)) if not named: return None - _, kind, name = min(named, key=lambda o: (o[0], -len(o[2]))) + _, kind, name = max(named, key=lambda o: (o[0], len(o[2]))) if kind == "view" and name.lower() in await _names_this_build_creates(): return None except sqlite3.Error as exc: diff --git a/tests/test_schema_verify_6719_6720.py b/tests/test_schema_verify_6719_6720.py index 17c7cc6389..627d7203cb 100644 --- a/tests/test_schema_verify_6719_6720.py +++ b/tests/test_schema_verify_6719_6720.py @@ -654,6 +654,72 @@ async def test_a_name_that_is_a_prefix_of_another_is_told_apart( assert await _foreign_object(db, expected_cause) == ("view", cause_view) +@pytest.mark.parametrize( + ("kind", "names", "cause", "found"), + [ + pytest.param( + "view", + ("vv", "vv after"), + "error in view vv after rename: no such module: m", + "vv", + id="vv-after-rename", + ), + pytest.param( + "view", + ("vv", "vv after"), + "error in view vv after after rename: no such module: m", + "vv after", + id="vv-after-after-rename", + ), + pytest.param( + "view", + ("vv", "vv: x"), + "error in view vv: x after rename: no such module: m", + "vv: x", + id="colon-name-after-rename", + ), + pytest.param( + "view", + ("vv", "vv: x"), + "error in view vv: no such module: m", + "vv", + id="colon-name-prefix", + ), + pytest.param( + "trigger", + ("tr", "tr after"), + "error in trigger tr after rename: no such module: m", + "tr", + id="trigger-after-rename", + ), + pytest.param( + "trigger", + ("tr", "tr after"), + "error in trigger tr after after rename: no such module: m", + "tr after", + id="trigger-after-after-rename", + ), + ], +) +async def test_a_prefix_name_is_told_apart_in_the_rename_recheck( + tmp_path: Path, kind: str, names: tuple[str, str], cause: str, found: str +) -> None: + # The RENAME COLUMN migration's re-check writes the " after rename" suffix. The causes are + # SQLite's form written out, as in the test above, because no healthy view this test can plant + # breaks under RENAME COLUMN: SQLite rewrites its reference instead. + from messagefoundry.store.schema_verify import _foreign_object + + path = tmp_path / "prefix.db" + _sql(path, "CREATE TABLE t (a)") + for name in names: + if kind == "view": + _sql(path, f'CREATE VIEW "{name}" AS SELECT a FROM t') + else: + _sql(path, f'CREATE TRIGGER "{name}" AFTER INSERT ON t BEGIN SELECT 1; END') + async with _connected(path) as db: + assert await _foreign_object(db, cause) == (kind, found) + + # --- BACKLOG #6720 item 1: a foreign view using an unloaded function or collation ---------------- From 16ab9b6a59425af2d1f13f0faa252331a59802b1 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sun, 22 Nov 2026 02:52:43 -0600 Subject: [PATCH 64/74] Pin the colon's place in the first rank and state the suffix premise Review round two found that no test needed the colon in the first rank. A case with views vv and "vv after x" and the cause "error in view vv after x: ..." now does: without the colon, vv would be named. The note above _FOREIGN_OBJECTS_SQL now names the two suffixes measured on SQLite 3.50.4, " after rename" and " after drop column", and says the ranking assumes every suffix starts " after ". The rename test's comment no longer claims a view cannot be planted to break under RENAME COLUMN. Supersedes the three-rank order the first commit of this repair described: the colon and " after " share one rank. Repairs the Lander hold on PR 3143, item H1. BACKLOG #6719, #6720. --- messagefoundry/store/schema_verify.py | 9 +++++---- tests/test_schema_verify_6719_6720.py | 13 ++++++++++--- 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/messagefoundry/store/schema_verify.py b/messagefoundry/store/schema_verify.py index 7ccbdf9c17..82a9f30287 100644 --- a/messagefoundry/store/schema_verify.py +++ b/messagefoundry/store/schema_verify.py @@ -81,10 +81,11 @@ " you set [secret_rotation].store_key_last_rotated, update it." ) # The ALTER re-check names an object other than the altered table that fails to parse as -# "error in ", then ":" or a suffix such as " after rename". Only views and triggers -# get the drop remedy (see _ORDINARY_TABLE for why they are another tool's); SQLite uses the same -# form for a table or an index, which may be this build's own. Dropping a view or a trigger removes -# no row, so that remedy keeps the store and its key. +# "error in ", then ":" or a suffix, at least " after rename" and " after drop column" +# (measured on SQLite 3.50.4). Both start " after ", and _foreign_object's ranking assumes every +# suffix does. Only views and triggers get the drop remedy (see _ORDINARY_TABLE for why they are +# another tool's); SQLite uses the same form for a table or an index, which may be this build's own. +# Dropping a view or a trigger removes no row, so that remedy keeps the store and its key. _FOREIGN_OBJECTS_SQL = "SELECT type, name FROM sqlite_master WHERE type IN ('view', 'trigger')" # The reads below skip a table whose stored SQL is LIKE 'CREATE VIRTUAL TABLE%', because a pragma diff --git a/tests/test_schema_verify_6719_6720.py b/tests/test_schema_verify_6719_6720.py index 627d7203cb..259529494a 100644 --- a/tests/test_schema_verify_6719_6720.py +++ b/tests/test_schema_verify_6719_6720.py @@ -685,6 +685,13 @@ async def test_a_name_that_is_a_prefix_of_another_is_told_apart( "vv", id="colon-name-prefix", ), + pytest.param( + "view", + ("vv", "vv after x"), + "error in view vv after x: no such module: m", + "vv after x", + id="colon-outranks-a-shorter-after", + ), pytest.param( "trigger", ("tr", "tr after"), @@ -704,9 +711,9 @@ async def test_a_name_that_is_a_prefix_of_another_is_told_apart( async def test_a_prefix_name_is_told_apart_in_the_rename_recheck( tmp_path: Path, kind: str, names: tuple[str, str], cause: str, found: str ) -> None: - # The RENAME COLUMN migration's re-check writes the " after rename" suffix. The causes are - # SQLite's form written out, as in the test above, because no healthy view this test can plant - # breaks under RENAME COLUMN: SQLite rewrites its reference instead. + # The RENAME COLUMN migration's re-check writes the " after rename" suffix. These causes are + # written out in SQLite's form rather than raised, so one test can cover a colon name and a + # trigger pair without a view or trigger built to break under each. from messagefoundry.store.schema_verify import _foreign_object path = tmp_path / "prefix.db" From fd67f781aa0cd16e1bca63d2e389091a2b89baf0 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sun, 22 Nov 2026 03:23:18 -0600 Subject: [PATCH 65/74] Name every view or trigger the error text fits when it cannot pick one SQLite's text cannot settle some pairs. A broken vv beside a healthy "vv after drop column" gives "error in view vv after drop column: ...", the same text the other view gives when it was broken already, and a broken vv beside a healthy "vv: no such column" fits both names too. The drop remedy named the longer view, so it could tell an operator to drop a healthy object alone. _foreign_object is now _foreign_objects and returns every first-rank candidate, sorted. run_schema_step keeps the single-name remedy for one candidate and names each candidate for more than one. Where any candidate is a view under a name this build creates, the plain remedy stands, as before. The last-rank-only case is unchanged. Preparing each candidate is not used: the failed ALTER is rolled back, so a view only the change broke prepares like a healthy one. The tests add both reproduced pairs from SQLite's own text and a remedy text check; cases that now fit two names expect both. The changelog fragment says the remedy names each name the text fits. Repairs the Lander's second hold on PR 3143, item H1. BACKLOG #6719, #6720. --- .../6719-6720-foreign-view-remedy.fixed.md | 4 +- messagefoundry/store/schema_verify.py | 68 ++++++++---- tests/test_schema_verify_6719_6720.py | 103 ++++++++++++++---- 3 files changed, 129 insertions(+), 46 deletions(-) diff --git a/changelog.d/6719-6720-foreign-view-remedy.fixed.md b/changelog.d/6719-6720-foreign-view-remedy.fixed.md index 271f482298..f71d31b1dd 100644 --- a/changelog.d/6719-6720-foreign-view-remedy.fixed.md +++ b/changelog.d/6719-6720-foreign-view-remedy.fixed.md @@ -1,7 +1,9 @@ - **A SQLite store whose upgrade is stopped by a view or trigger another tool left now names that object.** When SQLite's re-check after a migration's `ALTER` fails on such a view or trigger with an error that names the store's shape, such as "no such module", the open refuses the store with - the remedy to drop that object and restart, not to recreate the store. A view under the name of a + the remedy to drop that object and restart, not to recreate the store. Where the error's text fits + more than one such name, as with views `vv` and `vv after drop column`, the remedy names each of + them rather than one that may be healthy. A view under the name of a table or index this build creates still gets the recreate remedy. A failure on the store's shape raised by the check's own read of the live store, after the schema script and the migrations of a writable open, is now refused with the recreate remedy rather than escaping as SQLite's bare error. diff --git a/messagefoundry/store/schema_verify.py b/messagefoundry/store/schema_verify.py index 82a9f30287..804a9c3502 100644 --- a/messagefoundry/store/schema_verify.py +++ b/messagefoundry/store/schema_verify.py @@ -435,23 +435,35 @@ async def run_schema_step[T]( One shape failure gets another remedy: SQLite's re-check of the schema after an ``ALTER`` names the view or trigger it could not parse, as in "error in view V: no such module". That object is another tool's (see ``_ORDINARY_TABLE``), and dropping it lets the migration run past - it (BACKLOG #6719). A view under a name this build creates is not such an object: it holds the - place of a table or index, which is the incompatible store the plain remedy names.""" + it (BACKLOG #6719). Where the text fits more than one such object, the remedy names each one + (see :func:`_foreign_objects`). A view under a name this build creates is not such an object: + it holds the place of a table or index, which is the incompatible store the plain remedy names.""" try: return await step except Exception as exc: if not is_schema_step_error(exc): raise cause = str(exc) - foreign = await _foreign_object(db, cause) - if foreign is not None: - kind, name = foreign + foreign = await _foreign_objects(db, cause) + if len(foreign) == 1: + ((kind, name),) = foreign # The instruction leads and the name follows it, so the 200-character cut keeps it. raise SchemaMismatchError( f"store {path}: drop the {kind} {name!r}, which this build did not create and which" f" stops its upgrade, then restart. The schema step failed: {cause}.", cause=cause, ) from exc + if foreign: + # The text cannot tell these apart, so the remedy names them all rather than tell the + # operator to drop one that may be healthy. + listed = [f"the {kind} {name!r}" for kind, name in foreign] + either = " and ".join(listed) if len(listed) == 2 else ", ".join(listed) + raise SchemaMismatchError( + f"store {path}: drop whichever of {either} stops its upgrade, then restart. The" + f" error fits each name, and this build created none of them. The schema step" + f" failed: {cause}.", + cause=cause, + ) from exc if counts_under_dek is None: counts_under_dek = await _counts_under_a_dek(db) raise SchemaMismatchError( @@ -460,37 +472,51 @@ async def run_schema_step[T]( ) from exc -async def _foreign_object(db: aiosqlite.Connection, cause: str) -> tuple[str, str] | None: - """The kind and name of another tool's view or trigger that ``cause`` names, else ``None``. +async def _foreign_objects(db: aiosqlite.Connection, cause: str) -> tuple[tuple[str, str], ...]: + """The kind and name of each of another tool's views and triggers that ``cause`` may name, + sorted, else empty. The name is matched against the live file's views and triggers, never cut out of the text: the text may add a suffix after the name, and a quoted name may hold a colon. A SQLite error while - telling falls back to ``None``, the plain remedy. + telling falls back to empty, the plain remedy. Several names can fit one text (the forms are in the note above ``_FOREIGN_OBJECTS_SQL``): - ``vv`` and ``vv after`` both fit "error in view vv after rename: ...". So a name whose remainder - starts with the colon or with " after " ranks first, any other name last, and the longest name - of the first rank present wins. The longest alone named ``vv after`` there, which is not the - cause. The colon and " after " share a rank because a quoted name may hold either: with ``vv`` - and ``vv: x``, "error in view vv: x after rename: ..." names ``vv: x``.""" + ``vv`` and ``vv after`` both fit "error in view vv after rename: ...". A name whose remainder + starts with the colon or with " after " ranks first, and any other name last. Every name of the + first rank is returned, since no rule over the text can pick among them: SQLite writes "error in + view vv after drop column: ..." when ``vv`` breaks under the change, and the same text when a + view named ``vv after drop column`` was broken already. With ``vv`` and ``vv: no such column``, + ``vv``'s own "error in view vv: no such column: c" fits both too. So where names collide like + this the ambiguity remains, and the remedy names each candidate. With no first-rank name, the + longest last-rank name is the one returned. Where any name returned is a view under a name this + build creates, the result is empty, the plain remedy (see :func:`run_schema_step`). The colon + and " after " share a rank because a + quoted name may hold either: with ``vv`` and ``vv: x``, "error in view vv: x after rename: ..." + must not name ``vv`` alone. + + Preparing each candidate against the live file is not used to settle a tie: the failed + ``ALTER`` is rolled back, so a view that only the change broke prepares as cleanly as a healthy + one, and a trigger has no read that runs its body without a write.""" try: async with db.execute(_FOREIGN_OBJECTS_SQL) as cur: objects = [(str(kind), str(name)) for kind, name in await cur.fetchall()] - named: list[tuple[bool, str, str]] = [] + first: list[tuple[str, str]] = [] + last: list[tuple[str, str]] = [] for kind, name in objects: rest = cause.removeprefix(f"error in {kind} {name}") if rest != cause and rest[:1] in (":", " "): exact = rest.startswith((":", " after ")) - named.append((exact, kind, name)) + (first if exact else last).append((kind, name)) + named = first or ([max(last, key=lambda o: len(o[1]))] if last else []) if not named: - return None - _, kind, name = max(named, key=lambda o: (o[0], len(o[2]))) - if kind == "view" and name.lower() in await _names_this_build_creates(): - return None + return () + expected = await _names_this_build_creates() + if any(kind == "view" and name.lower() in expected for kind, name in named): + return () except sqlite3.Error as exc: log.warning("could not read the views and triggers to pick the schema remedy: %s", exc) - return None - return kind, name + return () + return tuple(sorted(named)) async def _names_this_build_creates() -> frozenset[str]: diff --git a/tests/test_schema_verify_6719_6720.py b/tests/test_schema_verify_6719_6720.py index 259529494a..39181f4014 100644 --- a/tests/test_schema_verify_6719_6720.py +++ b/tests/test_schema_verify_6719_6720.py @@ -30,6 +30,7 @@ is_schema_step_error, live_schema_differences, read_schema_shape, + run_schema_step, ) from messagefoundry.store.store import _SCHEMA, _await_connection_worker_exit @@ -589,60 +590,88 @@ async def test_a_failure_building_the_expected_shape_keeps_its_own_error( async def test_the_foreign_object_is_matched_against_the_file( tmp_path: Path, view_name: str, cause: str, found: tuple[str, str] | None ) -> None: - from messagefoundry.store.schema_verify import _foreign_object + from messagefoundry.store.schema_verify import _foreign_objects path = tmp_path / "named.db" _sql(path, f'CREATE VIEW "{view_name}" AS SELECT 1 AS a') async with _connected(path) as db: - assert await _foreign_object(db, cause) == found + assert await _foreign_objects(db, cause) == ((found,) if found else ()) @pytest.mark.parametrize( - ("cause_view", "reads", "statement", "expected_cause"), + ("views", "reads", "statement", "expected_cause", "found"), [ pytest.param( - "vv", + ("vv", "vv after"), "c FROM t", "ALTER TABLE t DROP COLUMN c", "error in view vv after drop column: no such column: c", + ("vv",), id="vv-after-the-change", ), pytest.param( - "vv after", + ("vv after", "vv"), "c FROM t", "ALTER TABLE t DROP COLUMN c", "error in view vv after after drop column: no such column: c", + ("vv", "vv after"), id="vv-after-after-the-change", ), pytest.param( - "vv", + ("vv", "vv after"), "missing FROM t", "ALTER TABLE t RENAME TO t2", "error in view vv: no such column: missing", + ("vv",), id="vv-before-the-change", ), pytest.param( - "vv after", + ("vv after", "vv"), "missing FROM t", "ALTER TABLE t RENAME TO t2", "error in view vv after: no such column: missing", + ("vv after",), id="vv-after-before-the-change", ), + pytest.param( + ("vv", "vv after drop column"), + "c FROM t", + "ALTER TABLE t DROP COLUMN c", + "error in view vv after drop column: no such column: c", + ("vv", "vv after drop column"), + id="broken-vv-beside-a-healthy-suffix-name", + ), + pytest.param( + ("vv", "vv: no such column"), + "missing FROM t", + "ALTER TABLE t RENAME TO t2", + "error in view vv: no such column: missing", + ("vv", "vv: no such column"), + id="broken-vv-beside-a-healthy-message-name", + ), ], ) async def test_a_name_that_is_a_prefix_of_another_is_told_apart( - tmp_path: Path, cause_view: str, reads: str, statement: str, expected_cause: str + tmp_path: Path, + views: tuple[str, str], + reads: str, + statement: str, + expected_cause: str, + found: tuple[str, ...], ) -> None: # Views "vv" and "vv after" both fit "error in view vv after ...", so the longest name alone # would tell the operator to drop "vv after" when "vv" stopped the change. Each cause is - # SQLite's own text. A view already broken fails SQLite's first check, with no suffix; a view - # the change breaks fails its re-check after the change, with the "after drop column" suffix. - from messagefoundry.store.schema_verify import _foreign_object + # SQLite's own text, and views[0] is the broken view. A view already broken fails SQLite's + # first check, with no suffix; a view the change breaks fails its re-check after the change, + # with the "after drop column" suffix. The last two pairs are ones the text cannot settle: the + # healthy view's own name holds the suffix or the message, so both views are named. + from messagefoundry.store.schema_verify import _foreign_objects path = tmp_path / "prefix.db" _sql(path, "CREATE TABLE t (a, c)", "CREATE TABLE u (c)") - for view in ("vv", "vv after"): - _sql(path, f'CREATE VIEW "{view}" AS SELECT {reads if view == cause_view else "c FROM u"}') + broken, healthy = views + _sql(path, f'CREATE VIEW "{broken}" AS SELECT {reads}') + _sql(path, f'CREATE VIEW "{healthy}" AS SELECT c FROM u') conn = sqlite3.connect(path) try: with pytest.raises(sqlite3.OperationalError) as info: @@ -651,7 +680,33 @@ async def test_a_name_that_is_a_prefix_of_another_is_told_apart( conn.close() assert str(info.value) == expected_cause async with _connected(path) as db: - assert await _foreign_object(db, expected_cause) == ("view", cause_view) + assert await _foreign_objects(db, expected_cause) == tuple(("view", n) for n in found) + + +async def test_names_the_text_cannot_tell_apart_are_all_named_in_the_remedy( + tmp_path: Path, +) -> None: + # A broken "vv" beside a healthy "vv after drop column": the remedy must not tell the operator + # to drop the healthy view alone, so it names both, the instruction first. + path = tmp_path / "both.db" + _sql( + path, + "CREATE TABLE t (a, c)", + "CREATE TABLE u (c)", + "CREATE VIEW vv AS SELECT c FROM t", + 'CREATE VIEW "vv after drop column" AS SELECT c FROM u', + ) + async with _connected(path) as db: + with pytest.raises(SchemaMismatchError) as info: + await run_schema_step( + db, db.execute("ALTER TABLE t DROP COLUMN c"), path=path, counts_under_dek=False + ) + text = str(info.value) + assert text.startswith( + f"store {path}: drop whichever of the view 'vv' and the view 'vv after drop column' stops" + " its upgrade, then restart." + ), text + assert "recreate" not in text, text @pytest.mark.parametrize( @@ -661,60 +716,60 @@ async def test_a_name_that_is_a_prefix_of_another_is_told_apart( "view", ("vv", "vv after"), "error in view vv after rename: no such module: m", - "vv", + ("vv",), id="vv-after-rename", ), pytest.param( "view", ("vv", "vv after"), "error in view vv after after rename: no such module: m", - "vv after", + ("vv", "vv after"), id="vv-after-after-rename", ), pytest.param( "view", ("vv", "vv: x"), "error in view vv: x after rename: no such module: m", - "vv: x", + ("vv", "vv: x"), id="colon-name-after-rename", ), pytest.param( "view", ("vv", "vv: x"), "error in view vv: no such module: m", - "vv", + ("vv",), id="colon-name-prefix", ), pytest.param( "view", ("vv", "vv after x"), "error in view vv after x: no such module: m", - "vv after x", + ("vv", "vv after x"), id="colon-outranks-a-shorter-after", ), pytest.param( "trigger", ("tr", "tr after"), "error in trigger tr after rename: no such module: m", - "tr", + ("tr",), id="trigger-after-rename", ), pytest.param( "trigger", ("tr", "tr after"), "error in trigger tr after after rename: no such module: m", - "tr after", + ("tr", "tr after"), id="trigger-after-after-rename", ), ], ) async def test_a_prefix_name_is_told_apart_in_the_rename_recheck( - tmp_path: Path, kind: str, names: tuple[str, str], cause: str, found: str + tmp_path: Path, kind: str, names: tuple[str, str], cause: str, found: tuple[str, ...] ) -> None: # The RENAME COLUMN migration's re-check writes the " after rename" suffix. These causes are # written out in SQLite's form rather than raised, so one test can cover a colon name and a # trigger pair without a view or trigger built to break under each. - from messagefoundry.store.schema_verify import _foreign_object + from messagefoundry.store.schema_verify import _foreign_objects path = tmp_path / "prefix.db" _sql(path, "CREATE TABLE t (a)") @@ -724,7 +779,7 @@ async def test_a_prefix_name_is_told_apart_in_the_rename_recheck( else: _sql(path, f'CREATE TRIGGER "{name}" AFTER INSERT ON t BEGIN SELECT 1; END') async with _connected(path) as db: - assert await _foreign_object(db, cause) == (kind, found) + assert await _foreign_objects(db, cause) == tuple((kind, n) for n in found) # --- BACKLOG #6720 item 1: a foreign view using an unloaded function or collation ---------------- From 228b54c406e1bd0008b50c2b3d512fd161651422 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sun, 22 Nov 2026 03:36:35 -0600 Subject: [PATCH 66/74] Take ": " as the separator and lead the multi-name remedy with its instruction Review round one of the multi-name change found: - A bare colon ranked first, so with views a and "a:b" the remedy named the healthy a too. SQLite writes ": " after a name, and that is now the test. - The name list came before "then restart", so a long list could push the instruction past the 200-character cut, and three names read as a run-on. The instruction now leads, then the names, joined with "and". - The expected-name check built the scratch schema for a trigger too. It now runs only when a view is among the candidates. - The docstring's reason for not preparing candidates covered one side only; it now states both, and why a failed prepare is not trusted. Tests add the a / "a:b" pair, a candidate under an expected name, a three-name remedy, and pin the remedy's full text, cause and chain. Repairs the Lander's second hold on PR 3143, item H1. BACKLOG #6719, #6720. --- messagefoundry/store/schema_verify.py | 53 +++++++++++++---------- tests/test_schema_verify_6719_6720.py | 60 +++++++++++++++++++++++---- 2 files changed, 82 insertions(+), 31 deletions(-) diff --git a/messagefoundry/store/schema_verify.py b/messagefoundry/store/schema_verify.py index 804a9c3502..d4f9811078 100644 --- a/messagefoundry/store/schema_verify.py +++ b/messagefoundry/store/schema_verify.py @@ -81,8 +81,8 @@ " you set [secret_rotation].store_key_last_rotated, update it." ) # The ALTER re-check names an object other than the altered table that fails to parse as -# "error in ", then ":" or a suffix, at least " after rename" and " after drop column" -# (measured on SQLite 3.50.4). Both start " after ", and _foreign_object's ranking assumes every +# "error in ", then ": " or a suffix, at least " after rename" and " after drop column" +# (measured on SQLite 3.50.4). Both start " after ", and _foreign_objects' ranks assume every # suffix does. Only views and triggers get the drop remedy (see _ORDINARY_TABLE for why they are # another tool's); SQLite uses the same form for a table or an index, which may be this build's own. # Dropping a view or a trigger removes no row, so that remedy keeps the store and its key. @@ -455,12 +455,13 @@ async def run_schema_step[T]( ) from exc if foreign: # The text cannot tell these apart, so the remedy names them all rather than tell the - # operator to drop one that may be healthy. + # operator to drop one that may be healthy. The instruction leads and the names follow + # it, so the 200-character cut keeps the instruction however long the names are. listed = [f"the {kind} {name!r}" for kind, name in foreign] - either = " and ".join(listed) if len(listed) == 2 else ", ".join(listed) + names = f"{', '.join(listed[:-1])} and {listed[-1]}" raise SchemaMismatchError( - f"store {path}: drop whichever of {either} stops its upgrade, then restart. The" - f" error fits each name, and this build created none of them. The schema step" + f"store {path}: drop whichever of these stops its upgrade, then restart: {names}." + f" The error fits each name, and this build created none of them. The schema step" f" failed: {cause}.", cause=cause, ) from exc @@ -482,21 +483,26 @@ async def _foreign_objects(db: aiosqlite.Connection, cause: str) -> tuple[tuple[ Several names can fit one text (the forms are in the note above ``_FOREIGN_OBJECTS_SQL``): ``vv`` and ``vv after`` both fit "error in view vv after rename: ...". A name whose remainder - starts with the colon or with " after " ranks first, and any other name last. Every name of the - first rank is returned, since no rule over the text can pick among them: SQLite writes "error in - view vv after drop column: ..." when ``vv`` breaks under the change, and the same text when a - view named ``vv after drop column`` was broken already. With ``vv`` and ``vv: no such column``, + starts with ": " or with " after " ranks first, and any other name last. Every name of the first + rank is returned, since no rule over the text can pick among them: SQLite writes "error in view + vv after drop column: ..." when ``vv`` breaks under the change, and the same text when a view + named ``vv after drop column`` was broken already. With ``vv`` and ``vv: no such column``, ``vv``'s own "error in view vv: no such column: c" fits both too. So where names collide like - this the ambiguity remains, and the remedy names each candidate. With no first-rank name, the - longest last-rank name is the one returned. Where any name returned is a view under a name this - build creates, the result is empty, the plain remedy (see :func:`run_schema_step`). The colon - and " after " share a rank because a - quoted name may hold either: with ``vv`` and ``vv: x``, "error in view vv: x after rename: ..." - must not name ``vv`` alone. - - Preparing each candidate against the live file is not used to settle a tie: the failed - ``ALTER`` is rolled back, so a view that only the change broke prepares as cleanly as a healthy - one, and a trigger has no read that runs its body without a write.""" + this the ambiguity remains, and the remedy names each candidate, a healthy one among them. With + no first-rank name, the longest last-rank name is the one returned. + + The colon and " after " share a rank because a quoted name may hold either: with ``vv`` and + ``vv: x``, "error in view vv: x after rename: ..." must not name ``vv`` alone. Where any name + returned is a view under a name this build creates, the result is empty: that view holds the + place of a table or index, so the store is the incompatible one the plain remedy names, whichever + candidate stopped the change (see :func:`run_schema_step`). + + Preparing each candidate against the live file is not used to settle a tie. A view that only + the change broke prepares as cleanly as a healthy one, since the failed ``ALTER`` is rolled + back. A failed prepare could rule out only the other reading, an object broken already, and + that rests on SQLite writing no suffix for an object it found broken before the change, which + this module has not measured for every ``ALTER``; a wrong ruling-out would name a healthy object + alone. A trigger also has no read that runs its body without a write.""" try: async with db.execute(_FOREIGN_OBJECTS_SQL) as cur: objects = [(str(kind), str(name)) for kind, name in await cur.fetchall()] @@ -505,13 +511,14 @@ async def _foreign_objects(db: aiosqlite.Connection, cause: str) -> tuple[tuple[ for kind, name in objects: rest = cause.removeprefix(f"error in {kind} {name}") if rest != cause and rest[:1] in (":", " "): - exact = rest.startswith((":", " after ")) + exact = rest.startswith((": ", " after ")) (first if exact else last).append((kind, name)) named = first or ([max(last, key=lambda o: len(o[1]))] if last else []) if not named: return () - expected = await _names_this_build_creates() - if any(kind == "view" and name.lower() in expected for kind, name in named): + views = [name.lower() for kind, name in named if kind == "view"] + # Only a view can hold an expected name's place, so a trigger needs no scratch build. + if views and not (await _names_this_build_creates()).isdisjoint(views): return () except sqlite3.Error as exc: log.warning("could not read the views and triggers to pick the schema remedy: %s", exc) diff --git a/tests/test_schema_verify_6719_6720.py b/tests/test_schema_verify_6719_6720.py index 39181f4014..90f96380cc 100644 --- a/tests/test_schema_verify_6719_6720.py +++ b/tests/test_schema_verify_6719_6720.py @@ -649,6 +649,22 @@ async def test_the_foreign_object_is_matched_against_the_file( ("vv", "vv: no such column"), id="broken-vv-beside-a-healthy-message-name", ), + pytest.param( + ("a:b", "a"), + "missing FROM t", + "ALTER TABLE t RENAME TO t2", + "error in view a:b: no such column: missing", + ("a:b",), + id="a-bare-colon-is-not-the-separator", + ), + pytest.param( + ("users after drop column", "users"), + "missing FROM t", + "ALTER TABLE t RENAME TO t2", + "error in view users after drop column: no such column: missing", + (), + id="a-candidate-under-an-expected-name", + ), ], ) async def test_a_name_that_is_a_prefix_of_another_is_told_apart( @@ -663,8 +679,11 @@ async def test_a_name_that_is_a_prefix_of_another_is_told_apart( # would tell the operator to drop "vv after" when "vv" stopped the change. Each cause is # SQLite's own text, and views[0] is the broken view. A view already broken fails SQLite's # first check, with no suffix; a view the change breaks fails its re-check after the change, - # with the "after drop column" suffix. The last two pairs are ones the text cannot settle: the - # healthy view's own name holds the suffix or the message, so both views are named. + # with the "after drop column" suffix. Where both names rank first the text cannot settle the + # pair, so both views are named: "vv after after drop column" fits both, and in the two + # broken-vv pairs the healthy view's own name holds the suffix or the message. SQLite writes + # ": " after a name, so "a" is no candidate for "a:b". A view under a name this build creates + # among the candidates gives the plain remedy, so nothing is returned. from messagefoundry.store.schema_verify import _foreign_objects path = tmp_path / "prefix.db" @@ -701,12 +720,37 @@ async def test_names_the_text_cannot_tell_apart_are_all_named_in_the_remedy( await run_schema_step( db, db.execute("ALTER TABLE t DROP COLUMN c"), path=path, counts_under_dek=False ) - text = str(info.value) - assert text.startswith( - f"store {path}: drop whichever of the view 'vv' and the view 'vv after drop column' stops" - " its upgrade, then restart." - ), text - assert "recreate" not in text, text + cause = "error in view vv after drop column: no such column: c" + assert info.value.cause == cause + assert isinstance(info.value.__cause__, sqlite3.OperationalError) + assert str(info.value) == ( + f"store {path}: drop whichever of these stops its upgrade, then restart: the view 'vv' and" + " the view 'vv after drop column'. The error fits each name, and this build created none" + f" of them. The schema step failed: {cause}." + ) + + +async def test_three_names_the_text_cannot_tell_apart_are_listed_in_the_remedy( + tmp_path: Path, +) -> None: + path = tmp_path / "three.db" + _sql( + path, + "CREATE TABLE t (a, c)", + "CREATE TABLE u (c)", + "CREATE VIEW vv AS SELECT c FROM t", + 'CREATE VIEW "vv after drop column" AS SELECT c FROM u', + 'CREATE VIEW "vv after drop column: no such column" AS SELECT c FROM u', + ) + async with _connected(path) as db: + with pytest.raises(SchemaMismatchError) as info: + await run_schema_step( + db, db.execute("ALTER TABLE t DROP COLUMN c"), path=path, counts_under_dek=False + ) + assert str(info.value).startswith( + f"store {path}: drop whichever of these stops its upgrade, then restart: the view 'vv'," + " the view 'vv after drop column' and the view 'vv after drop column: no such column'." + ), str(info.value) @pytest.mark.parametrize( From 4a7fc78fb66b81fbf0582e664ad895d0dbec73df Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sun, 22 Nov 2026 03:48:56 -0600 Subject: [PATCH 67/74] State what the multi-name remedy knows, and tell the operator to save first Review round two found the remedy's "The error fits each name" and the docstring's "no rule over the text can pick among them" too strong: a list of SQLite's suffixes could settle some pairs, such as vv against "vv after". The code keeps no such list on purpose, since only some suffixes are measured and a missing one would name a healthy object alone; the docstring now says so, and the remedy says the text "could name each of them". The remedy also tells the operator to save each object's CREATE statement before dropping it, so a healthy one can be restored. The changelog fragment now says an expected-name view among several candidates still gets the recreate remedy. Repairs the Lander's second hold on PR 3143, item H1. BACKLOG #6719, #6720. --- .../6719-6720-foreign-view-remedy.fixed.md | 3 ++- messagefoundry/store/schema_verify.py | 20 +++++++++++-------- tests/test_schema_verify_6719_6720.py | 5 +++-- 3 files changed, 17 insertions(+), 11 deletions(-) diff --git a/changelog.d/6719-6720-foreign-view-remedy.fixed.md b/changelog.d/6719-6720-foreign-view-remedy.fixed.md index f71d31b1dd..0612b3c05b 100644 --- a/changelog.d/6719-6720-foreign-view-remedy.fixed.md +++ b/changelog.d/6719-6720-foreign-view-remedy.fixed.md @@ -4,7 +4,8 @@ the remedy to drop that object and restart, not to recreate the store. Where the error's text fits more than one such name, as with views `vv` and `vv after drop column`, the remedy names each of them rather than one that may be healthy. A view under the name of a - table or index this build creates still gets the recreate remedy. A failure on the store's shape + table or index this build creates still gets the recreate remedy, also when it is one of several + names the text fits. A failure on the store's shape raised by the check's own read of the live store, after the schema script and the migrations of a writable open, is now refused with the recreate remedy rather than escaping as SQLite's bare error. (`BACKLOG #6719`, `BACKLOG #6720`) diff --git a/messagefoundry/store/schema_verify.py b/messagefoundry/store/schema_verify.py index d4f9811078..1b75bb5e6b 100644 --- a/messagefoundry/store/schema_verify.py +++ b/messagefoundry/store/schema_verify.py @@ -461,8 +461,9 @@ async def run_schema_step[T]( names = f"{', '.join(listed[:-1])} and {listed[-1]}" raise SchemaMismatchError( f"store {path}: drop whichever of these stops its upgrade, then restart: {names}." - f" The error fits each name, and this build created none of them. The schema step" - f" failed: {cause}.", + f" The error's text could name each of them, and this build created none of them." + f" Save each one's CREATE statement from sqlite_master before you drop it, so a" + f" healthy one can be restored. The schema step failed: {cause}.", cause=cause, ) from exc if counts_under_dek is None: @@ -484,12 +485,15 @@ async def _foreign_objects(db: aiosqlite.Connection, cause: str) -> tuple[tuple[ Several names can fit one text (the forms are in the note above ``_FOREIGN_OBJECTS_SQL``): ``vv`` and ``vv after`` both fit "error in view vv after rename: ...". A name whose remainder starts with ": " or with " after " ranks first, and any other name last. Every name of the first - rank is returned, since no rule over the text can pick among them: SQLite writes "error in view - vv after drop column: ..." when ``vv`` breaks under the change, and the same text when a view - named ``vv after drop column`` was broken already. With ``vv`` and ``vv: no such column``, - ``vv``'s own "error in view vv: no such column: c" fits both too. So where names collide like - this the ambiguity remains, and the remedy names each candidate, a healthy one among them. With - no first-rank name, the longest last-rank name is the one returned. + rank is returned, and the code does not pick among them. Some pairs no rule over the text can + settle: SQLite writes "error in view vv after drop column: ..." when ``vv`` breaks under the + change, and the same text when a view named ``vv after drop column`` was broken already. With + ``vv`` and ``vv: no such column``, ``vv``'s own "error in view vv: no such column: c" fits both + too. Other pairs a list of SQLite's suffixes could settle, as ``vv`` against ``vv after`` for + "error in view vv after after drop column: ...". The code keeps no such list: only some + suffixes are measured, and a suffix missing from the list would name a healthy object alone. So + where names collide the ambiguity remains, and the remedy names each candidate, which may + include a healthy one. With no first-rank name, the longest last-rank name is the one returned. The colon and " after " share a rank because a quoted name may hold either: with ``vv`` and ``vv: x``, "error in view vv: x after rename: ..." must not name ``vv`` alone. Where any name diff --git a/tests/test_schema_verify_6719_6720.py b/tests/test_schema_verify_6719_6720.py index 90f96380cc..5d71987c0f 100644 --- a/tests/test_schema_verify_6719_6720.py +++ b/tests/test_schema_verify_6719_6720.py @@ -725,8 +725,9 @@ async def test_names_the_text_cannot_tell_apart_are_all_named_in_the_remedy( assert isinstance(info.value.__cause__, sqlite3.OperationalError) assert str(info.value) == ( f"store {path}: drop whichever of these stops its upgrade, then restart: the view 'vv' and" - " the view 'vv after drop column'. The error fits each name, and this build created none" - f" of them. The schema step failed: {cause}." + " the view 'vv after drop column'. The error's text could name each of them, and this build" + " created none of them. Save each one's CREATE statement from sqlite_master before you" + f" drop it, so a healthy one can be restored. The schema step failed: {cause}." ) From 13eebdb2f3bb17ad611f1d9affc90b196a40eff2 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sun, 22 Nov 2026 04:08:32 -0600 Subject: [PATCH 68/74] Lead the multi-name remedy with the save step so the cut keeps it The save-before-drop sentence came after the name list, so safe_exc's 200-character cut removed it on a service path even with short names. The remedy now opens "save each one's CREATE statement, then drop whichever stops its upgrade, and restart:", then the names. Measured, the whole instruction survives the cut on a store path of up to 107 characters; names past the cut are lost, and the code comment now says so instead of "however long the names are". "CREATE SQL" was avoided because safe_exc redacts it. A new test renders the remedy with long names on both service paths and checks the instruction survives; it fails on both with the old order. The single-name text has no save step and is unchanged. The _foreign_objects docstring now says the " after " rank is itself a one-entry suffix assumption, with the residual that a suffix not starting " after " would name a healthy first-rank object alone. The run_schema_step comment and the test comment now agree with it. Repairs the Lander's second hold on PR 3143, item H1. BACKLOG #6719, #6720. --- messagefoundry/store/schema_verify.py | 30 +++++++++----- tests/test_schema_verify_6719_6720.py | 58 ++++++++++++++++++++++----- 2 files changed, 68 insertions(+), 20 deletions(-) diff --git a/messagefoundry/store/schema_verify.py b/messagefoundry/store/schema_verify.py index 1b75bb5e6b..08d53fd345 100644 --- a/messagefoundry/store/schema_verify.py +++ b/messagefoundry/store/schema_verify.py @@ -454,16 +454,19 @@ async def run_schema_step[T]( cause=cause, ) from exc if foreign: - # The text cannot tell these apart, so the remedy names them all rather than tell the - # operator to drop one that may be healthy. The instruction leads and the names follow - # it, so the 200-character cut keeps the instruction however long the names are. + # _foreign_objects does not pick among these, so the remedy names them all rather than + # tell the operator to drop one that may be healthy. The instruction, its save step + # included, leads and is short: safe_exc's 200-character cut keeps all of it on a store + # path of up to 107 characters (measured). The names follow it, so a long path or a + # long list loses names, and whatever follows them, to the cut. listed = [f"the {kind} {name!r}" for kind, name in foreign] names = f"{', '.join(listed[:-1])} and {listed[-1]}" raise SchemaMismatchError( - f"store {path}: drop whichever of these stops its upgrade, then restart: {names}." - f" The error's text could name each of them, and this build created none of them." - f" Save each one's CREATE statement from sqlite_master before you drop it, so a" - f" healthy one can be restored. The schema step failed: {cause}.", + f"store {path}: save each one's CREATE statement, then drop whichever stops its" + f" upgrade, and restart: {names}. Each CREATE statement is the sql column of its" + f" sqlite_master row, and saving it lets a healthy one be restored. The error's text" + f" could name each of them, and this build created none of them. The schema step" + f" failed: {cause}.", cause=cause, ) from exc if counts_under_dek is None: @@ -490,10 +493,15 @@ async def _foreign_objects(db: aiosqlite.Connection, cause: str) -> tuple[tuple[ change, and the same text when a view named ``vv after drop column`` was broken already. With ``vv`` and ``vv: no such column``, ``vv``'s own "error in view vv: no such column: c" fits both too. Other pairs a list of SQLite's suffixes could settle, as ``vv`` against ``vv after`` for - "error in view vv after after drop column: ...". The code keeps no such list: only some - suffixes are measured, and a suffix missing from the list would name a healthy object alone. So - where names collide the ambiguity remains, and the remedy names each candidate, which may - include a healthy one. With no first-rank name, the longest last-rank name is the one returned. + "error in view vv after after drop column: ...". The code keeps no such list, because only some + suffixes are measured and a list that missed one would name a healthy object alone. The " after " + rank is itself a one-entry suffix assumption, with the same residual: a suffix SQLite writes + that does not start " after " would rank the culprit last and a healthy first-rank name would be + named alone. Under a suffix " during x", for one, which no test here has measured, a healthy + ``vv during x`` beside a broken ``vv`` would be named for "error in view vv during x: ...". At + least " after rename" and " after drop column" start " after " (SQLite 3.50.4). So where names + collide the ambiguity remains, and the remedy names each candidate, which may include a healthy + one. With no first-rank name, the longest last-rank name is the one returned. The colon and " after " share a rank because a quoted name may hold either: with ``vv`` and ``vv: x``, "error in view vv: x after rename: ..." must not name ``vv`` alone. Where any name diff --git a/tests/test_schema_verify_6719_6720.py b/tests/test_schema_verify_6719_6720.py index 5d71987c0f..76fb9eca07 100644 --- a/tests/test_schema_verify_6719_6720.py +++ b/tests/test_schema_verify_6719_6720.py @@ -679,9 +679,11 @@ async def test_a_name_that_is_a_prefix_of_another_is_told_apart( # would tell the operator to drop "vv after" when "vv" stopped the change. Each cause is # SQLite's own text, and views[0] is the broken view. A view already broken fails SQLite's # first check, with no suffix; a view the change breaks fails its re-check after the change, - # with the "after drop column" suffix. Where both names rank first the text cannot settle the - # pair, so both views are named: "vv after after drop column" fits both, and in the two - # broken-vv pairs the healthy view's own name holds the suffix or the message. SQLite writes + # with the "after drop column" suffix. Where both names rank first the code does not pick + # between them, so both views are named. In the two broken-vv pairs the text itself cannot + # settle the pair, since the healthy view's own name holds the suffix or the message; "vv after + # after drop column" is one a list of SQLite's suffixes could settle, and the code keeps none + # (see _foreign_objects). SQLite writes # ": " after a name, so "a" is no candidate for "a:b". A view under a name this build creates # among the candidates gives the plain remedy, so nothing is returned. from messagefoundry.store.schema_verify import _foreign_objects @@ -724,13 +726,50 @@ async def test_names_the_text_cannot_tell_apart_are_all_named_in_the_remedy( assert info.value.cause == cause assert isinstance(info.value.__cause__, sqlite3.OperationalError) assert str(info.value) == ( - f"store {path}: drop whichever of these stops its upgrade, then restart: the view 'vv' and" - " the view 'vv after drop column'. The error's text could name each of them, and this build" - " created none of them. Save each one's CREATE statement from sqlite_master before you" - f" drop it, so a healthy one can be restored. The schema step failed: {cause}." + f"store {path}: save each one's CREATE statement, then drop whichever stops its upgrade," + " and restart: the view 'vv' and the view 'vv after drop column'. Each CREATE statement is" + " the sql column of its sqlite_master row, and saving it lets a healthy one be restored." + " The error's text could name each of them, and this build created none of them. The" + f" schema step failed: {cause}." ) +@pytest.mark.parametrize( + "service_path", + [ + r"C:\ProgramData\MessageFoundry\data\messagefoundry.db", + r"C:\ProgramData\MessageFoundry\data\stores\production\instance-a\messagefoundry.db", + ], +) +async def test_the_multi_name_instruction_survives_the_cut( + tmp_path: Path, service_path: str +) -> None: + # safe_exc cuts a rendered error at 200 characters. With long names on a service path, the whole + # instruction, the save step included, must still reach the operator; the names may not. + from messagefoundry.redaction import safe_exc + + long = "daily_census_by_unit_and_attending_for_the_weekly_report" + path = tmp_path / "cut.db" + _sql( + path, + "CREATE TABLE t (a, c)", + "CREATE TABLE u (c)", + f'CREATE VIEW "{long}" AS SELECT c FROM t', + f'CREATE VIEW "{long} after drop column" AS SELECT c FROM u', + ) + async with _connected(path) as db: + with pytest.raises(SchemaMismatchError) as info: + await run_schema_step( + db, db.execute("ALTER TABLE t DROP COLUMN c"), path=path, counts_under_dek=False + ) + text = str(info.value) + assert long in text, text + rendered = safe_exc(SchemaMismatchError(text.replace(str(path), service_path))) + assert f"store {service_path}: " in rendered, rendered + for step in ("save each one's CREATE statement", "drop whichever", "restart"): + assert step in rendered, (step, rendered) + + async def test_three_names_the_text_cannot_tell_apart_are_listed_in_the_remedy( tmp_path: Path, ) -> None: @@ -749,8 +788,9 @@ async def test_three_names_the_text_cannot_tell_apart_are_listed_in_the_remedy( db, db.execute("ALTER TABLE t DROP COLUMN c"), path=path, counts_under_dek=False ) assert str(info.value).startswith( - f"store {path}: drop whichever of these stops its upgrade, then restart: the view 'vv'," - " the view 'vv after drop column' and the view 'vv after drop column: no such column'." + f"store {path}: save each one's CREATE statement, then drop whichever stops its upgrade," + " and restart: the view 'vv', the view 'vv after drop column' and the view 'vv after drop" + " column: no such column'." ), str(info.value) From 4ae5a161c58ae5d48246e2c8bcc1a8271c1fc6a3 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sun, 22 Nov 2026 04:26:32 -0600 Subject: [PATCH 69/74] Keep each drop instruction whole under the cut and count the names Closing-round review one found: - The single-name remedy put the name before "then restart", so a 20-character name lost the restart step on the 81-character service path. It now reads "drop this view, then restart: 'NAME'. This build did not create it, and it stops its upgrade." - A cut copy of the multi-name remedy could show one name, perhaps the healthy one, alone. The lead now says "whichever of these N", so a reader of a cut copy knows more names follow. - The comment's "107 characters (measured)" counted raw path characters and ignored redaction. Re-measured with the count added: 96 raw characters, fewer where the redactor lengthens a segment. - The cut test checked loose substrings and never proved the cut ran. It now pins each lead whole, asserts the cut ran, covers the single- name remedy, and renders both service paths from one exception. - The docstring and test comment said no rule over the text could settle the message-name pair; a list of SQLite's messages could. The last-rank fallback is now named in the residual, and the suffix premise is no longer restated beside the note it points to. Repairs the Lander's second hold on PR 3143, item H1. BACKLOG #6719, #6720. --- messagefoundry/store/schema_verify.py | 49 +++++++++++---------- tests/test_schema_verify_6719_6720.py | 63 +++++++++++++++++---------- 2 files changed, 66 insertions(+), 46 deletions(-) diff --git a/messagefoundry/store/schema_verify.py b/messagefoundry/store/schema_verify.py index 08d53fd345..7da71725a1 100644 --- a/messagefoundry/store/schema_verify.py +++ b/messagefoundry/store/schema_verify.py @@ -447,23 +447,27 @@ async def run_schema_step[T]( foreign = await _foreign_objects(db, cause) if len(foreign) == 1: ((kind, name),) = foreign - # The instruction leads and the name follows it, so the 200-character cut keeps it. + # The whole instruction leads and the name follows it, so safe_exc's 200-character cut + # keeps the instruction; a long name, and the text after it, may be cut. raise SchemaMismatchError( - f"store {path}: drop the {kind} {name!r}, which this build did not create and which" - f" stops its upgrade, then restart. The schema step failed: {cause}.", + f"store {path}: drop this {kind}, then restart: {name!r}. This build did not create" + f" it, and it stops its upgrade. The schema step failed: {cause}.", cause=cause, ) from exc if foreign: # _foreign_objects does not pick among these, so the remedy names them all rather than - # tell the operator to drop one that may be healthy. The instruction, its save step - # included, leads and is short: safe_exc's 200-character cut keeps all of it on a store - # path of up to 107 characters (measured). The names follow it, so a long path or a - # long list loses names, and whatever follows them, to the cut. + # tell the operator to drop one that may be healthy. The instruction, its save step and + # the count of names included, leads and is short. safe_exc's 200-character cut keeps + # all of it on the service paths the tests pin, measured whole on paths of up to 96 + # raw characters, and fewer where the redactor lengthens a path segment. The names + # follow it, so a long path or a long list loses names, and the text after them, to + # the cut; the count tells a reader of a cut copy that more names follow. listed = [f"the {kind} {name!r}" for kind, name in foreign] names = f"{', '.join(listed[:-1])} and {listed[-1]}" raise SchemaMismatchError( - f"store {path}: save each one's CREATE statement, then drop whichever stops its" - f" upgrade, and restart: {names}. Each CREATE statement is the sql column of its" + f"store {path}: save each one's CREATE statement, then drop whichever of these" + f" {len(foreign)} stops its upgrade, and restart: {names}. Each CREATE statement is" + f" the sql column of its" f" sqlite_master row, and saving it lets a healthy one be restored. The error's text" f" could name each of them, and this build created none of them. The schema step" f" failed: {cause}.", @@ -489,19 +493,20 @@ async def _foreign_objects(db: aiosqlite.Connection, cause: str) -> tuple[tuple[ ``vv`` and ``vv after`` both fit "error in view vv after rename: ...". A name whose remainder starts with ": " or with " after " ranks first, and any other name last. Every name of the first rank is returned, and the code does not pick among them. Some pairs no rule over the text can - settle: SQLite writes "error in view vv after drop column: ..." when ``vv`` breaks under the - change, and the same text when a view named ``vv after drop column`` was broken already. With - ``vv`` and ``vv: no such column``, ``vv``'s own "error in view vv: no such column: c" fits both - too. Other pairs a list of SQLite's suffixes could settle, as ``vv`` against ``vv after`` for - "error in view vv after after drop column: ...". The code keeps no such list, because only some - suffixes are measured and a list that missed one would name a healthy object alone. The " after " - rank is itself a one-entry suffix assumption, with the same residual: a suffix SQLite writes - that does not start " after " would rank the culprit last and a healthy first-rank name would be - named alone. Under a suffix " during x", for one, which no test here has measured, a healthy - ``vv during x`` beside a broken ``vv`` would be named for "error in view vv during x: ...". At - least " after rename" and " after drop column" start " after " (SQLite 3.50.4). So where names - collide the ambiguity remains, and the remedy names each candidate, which may include a healthy - one. With no first-rank name, the longest last-rank name is the one returned. + settle: SQLite writes "error in view vv after drop column: no such column: c" when ``vv`` breaks + under the change, and the same text when a view named ``vv after drop column`` was broken + already. Other pairs a list of SQLite's suffixes or messages could settle: ``vv`` against ``vv + after`` for "error in view vv after after drop column: ...", and, with ``vv`` and ``vv: no such + column``, ``vv``'s own "error in view vv: no such column: c", which fits the other name only if + SQLite's message were the bare "c". The code keeps no such list, because only some suffixes and + messages are measured and a list that missed one would name a healthy object alone. The + " after " rank is itself a one-entry suffix assumption, with a residual of the same kind: a + suffix SQLite writes that does not start " after " would rank the culprit last, and then at + least a healthy first-rank name, or the longest last-rank name, could be named alone. Under a + suffix " during x", for one, which no test here has measured, a healthy ``vv during x`` beside + a broken ``vv`` would be named for "error in view vv during x: ...". So where names collide the + ambiguity remains, and the remedy names each candidate, which may include a healthy one. With no + first-rank name, the longest last-rank name is the one returned. The colon and " after " share a rank because a quoted name may hold either: with ``vv`` and ``vv: x``, "error in view vv: x after rename: ..." must not name ``vv`` alone. Where any name diff --git a/tests/test_schema_verify_6719_6720.py b/tests/test_schema_verify_6719_6720.py index 76fb9eca07..b6dc7b69cf 100644 --- a/tests/test_schema_verify_6719_6720.py +++ b/tests/test_schema_verify_6719_6720.py @@ -469,7 +469,9 @@ async def test_a_foreign_object_that_stops_a_migration_gets_the_drop_remedy( cause = info.value.cause assert cause is not None and cause.startswith(f"error in {kind} {name}: no such module"), cause text = str(info.value) - assert text.startswith(f"store {path}: drop the {kind} '{name}', which this build"), text + assert text.startswith(f"store {path}: drop this {kind}, then restart: '{name}'. This build"), ( + text + ) assert "recreate" not in text and "NEW store key" not in text, text # The remedy is true: with that object dropped, the same migration runs and the open succeeds. _sql(path, drop) @@ -680,11 +682,11 @@ async def test_a_name_that_is_a_prefix_of_another_is_told_apart( # SQLite's own text, and views[0] is the broken view. A view already broken fails SQLite's # first check, with no suffix; a view the change breaks fails its re-check after the change, # with the "after drop column" suffix. Where both names rank first the code does not pick - # between them, so both views are named. In the two broken-vv pairs the text itself cannot - # settle the pair, since the healthy view's own name holds the suffix or the message; "vv after - # after drop column" is one a list of SQLite's suffixes could settle, and the code keeps none - # (see _foreign_objects). SQLite writes - # ": " after a name, so "a" is no candidate for "a:b". A view under a name this build creates + # between them, so both views are named. In the suffix-name pair the text itself cannot settle + # the pair, since the healthy view's own name holds the suffix. The message-name pair and "vv + # after after drop column" are ones a list of SQLite's messages or suffixes could settle, and + # the code keeps none (see _foreign_objects). SQLite writes ": " after a name, so "a" is no + # candidate for "a:b". A view under a name this build creates # among the candidates gives the plain remedy, so nothing is returned. from messagefoundry.store.schema_verify import _foreign_objects @@ -726,26 +728,38 @@ async def test_names_the_text_cannot_tell_apart_are_all_named_in_the_remedy( assert info.value.cause == cause assert isinstance(info.value.__cause__, sqlite3.OperationalError) assert str(info.value) == ( - f"store {path}: save each one's CREATE statement, then drop whichever stops its upgrade," - " and restart: the view 'vv' and the view 'vv after drop column'. Each CREATE statement is" + f"store {path}: save each one's CREATE statement, then drop whichever of these 2 stops its" + " upgrade, and restart: the view 'vv' and the view 'vv after drop column'. Each CREATE" + " statement is" " the sql column of its sqlite_master row, and saving it lets a healthy one be restored." " The error's text could name each of them, and this build created none of them. The" f" schema step failed: {cause}." ) +_CUT_SERVICE_PATHS = ( + r"C:\ProgramData\MessageFoundry\data\messagefoundry.db", + r"C:\ProgramData\MessageFoundry\data\stores\production\instance-a\messagefoundry.db", +) + + @pytest.mark.parametrize( - "service_path", + ("healthy", "lead"), [ - r"C:\ProgramData\MessageFoundry\data\messagefoundry.db", - r"C:\ProgramData\MessageFoundry\data\stores\production\instance-a\messagefoundry.db", + pytest.param( + True, + "save each one's CREATE statement, then drop whichever of these 2 stops its upgrade, and" + " restart:", + id="two-names", + ), + pytest.param(False, "drop this view, then restart:", id="one-name"), ], ) -async def test_the_multi_name_instruction_survives_the_cut( - tmp_path: Path, service_path: str +async def test_the_drop_instruction_survives_the_cut( + tmp_path: Path, healthy: bool, lead: str ) -> None: - # safe_exc cuts a rendered error at 200 characters. With long names on a service path, the whole - # instruction, the save step included, must still reach the operator; the names may not. + # safe_exc cuts a rendered error at 200 characters. With a long name on a service path, the + # whole instruction, a save step included, must still reach the operator; the names may not. from messagefoundry.redaction import safe_exc long = "daily_census_by_unit_and_attending_for_the_weekly_report" @@ -755,19 +769,20 @@ async def test_the_multi_name_instruction_survives_the_cut( "CREATE TABLE t (a, c)", "CREATE TABLE u (c)", f'CREATE VIEW "{long}" AS SELECT c FROM t', - f'CREATE VIEW "{long} after drop column" AS SELECT c FROM u', ) + if healthy: + _sql(path, f'CREATE VIEW "{long} after drop column" AS SELECT c FROM u') async with _connected(path) as db: with pytest.raises(SchemaMismatchError) as info: await run_schema_step( db, db.execute("ALTER TABLE t DROP COLUMN c"), path=path, counts_under_dek=False ) text = str(info.value) - assert long in text, text - rendered = safe_exc(SchemaMismatchError(text.replace(str(path), service_path))) - assert f"store {service_path}: " in rendered, rendered - for step in ("save each one's CREATE statement", "drop whichever", "restart"): - assert step in rendered, (step, rendered) + assert text.startswith(f"store {path}: {lead} "), text + for service_path in _CUT_SERVICE_PATHS: + rendered = safe_exc(SchemaMismatchError(text.replace(str(path), service_path))) + assert "(+" in rendered, rendered # the cut ran + assert f"store {service_path}: {lead}" in rendered, rendered async def test_three_names_the_text_cannot_tell_apart_are_listed_in_the_remedy( @@ -788,9 +803,9 @@ async def test_three_names_the_text_cannot_tell_apart_are_listed_in_the_remedy( db, db.execute("ALTER TABLE t DROP COLUMN c"), path=path, counts_under_dek=False ) assert str(info.value).startswith( - f"store {path}: save each one's CREATE statement, then drop whichever stops its upgrade," - " and restart: the view 'vv', the view 'vv after drop column' and the view 'vv after drop" - " column: no such column'." + f"store {path}: save each one's CREATE statement, then drop whichever of these 3 stops its" + " upgrade, and restart: the view 'vv', the view 'vv after drop column' and the view 'vv" + " after drop column: no such column'." ), str(info.value) From c8f58e7195713114c86438c0d446ef12f2eb68c4 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sun, 22 Nov 2026 04:41:29 -0600 Subject: [PATCH 70/74] Bind each remedy's names to the drop, and state the measured cut bounds Closing-round review two found: - "then restart: 'NAME'" read as restarting the named object, and "it stops its upgrade" as the view's own upgrade. The texts now read "drop this view, then restart. The view: 'NAME'. ... it stops the store's upgrade" and "save each CREATE statement, then drop whichever of these N stops the upgrade, and restart. The N: ...". - The single-name comment claimed the cut always keeps the instruction. It now gives the measured bound: a store path of up to 163 raw characters for a view, 160 for a trigger. - The multi-name bound held only below 10 names. Re-measured on the new lead: 102 raw characters below 10 names, one fewer per further digit. - Placeholder-free f-string fragments split mid-phrase are rejoined. Repairs the Lander's second hold on PR 3143, item H1. BACKLOG #6719, #6720. --- messagefoundry/store/schema_verify.py | 32 +++++++++++++++------------ tests/test_schema_verify_6719_6720.py | 29 ++++++++++++------------ 2 files changed, 32 insertions(+), 29 deletions(-) diff --git a/messagefoundry/store/schema_verify.py b/messagefoundry/store/schema_verify.py index 7da71725a1..79921d8940 100644 --- a/messagefoundry/store/schema_verify.py +++ b/messagefoundry/store/schema_verify.py @@ -447,30 +447,34 @@ async def run_schema_step[T]( foreign = await _foreign_objects(db, cause) if len(foreign) == 1: ((kind, name),) = foreign - # The whole instruction leads and the name follows it, so safe_exc's 200-character cut - # keeps the instruction; a long name, and the text after it, may be cut. + # The whole instruction leads and the name follows it. safe_exc's 200-character cut + # keeps the instruction on a store path of up to 163 raw characters for a view and 160 + # for a trigger (measured), fewer where the redactor lengthens a path segment. A long + # name, and the text after it, may be cut, and a cut at a space inside a name leaves a + # shorter name; safe_exc's cut marker is then all that shows the name is incomplete. raise SchemaMismatchError( - f"store {path}: drop this {kind}, then restart: {name!r}. This build did not create" - f" it, and it stops its upgrade. The schema step failed: {cause}.", + f"store {path}: drop this {kind}, then restart. The {kind}: {name!r}. This build did" + f" not create it, and it stops the store's upgrade. The schema step failed: {cause}.", cause=cause, ) from exc if foreign: # _foreign_objects does not pick among these, so the remedy names them all rather than # tell the operator to drop one that may be healthy. The instruction, its save step and # the count of names included, leads and is short. safe_exc's 200-character cut keeps - # all of it on the service paths the tests pin, measured whole on paths of up to 96 - # raw characters, and fewer where the redactor lengthens a path segment. The names - # follow it, so a long path or a long list loses names, and the text after them, to - # the cut; the count tells a reader of a cut copy that more names follow. + # all of it on a store path of up to 102 raw characters with fewer than 10 names, one + # character fewer for each further digit of the count (measured), and fewer where the + # redactor lengthens a path segment. The names follow it, so a long path or a long list + # loses names, and the text after them, to the cut; the count tells a reader of a cut + # copy that more names follow. listed = [f"the {kind} {name!r}" for kind, name in foreign] names = f"{', '.join(listed[:-1])} and {listed[-1]}" + count = len(foreign) raise SchemaMismatchError( - f"store {path}: save each one's CREATE statement, then drop whichever of these" - f" {len(foreign)} stops its upgrade, and restart: {names}. Each CREATE statement is" - f" the sql column of its" - f" sqlite_master row, and saving it lets a healthy one be restored. The error's text" - f" could name each of them, and this build created none of them. The schema step" - f" failed: {cause}.", + f"store {path}: save each CREATE statement, then drop whichever of these {count}" + f" stops the upgrade, and restart. The {count}: {names}. Each CREATE statement is" + " the sql column of its sqlite_master row, and saving it lets a healthy one be" + " restored. The error's text could name each of them, and this build created none" + f" of them. The schema step failed: {cause}.", cause=cause, ) from exc if counts_under_dek is None: diff --git a/tests/test_schema_verify_6719_6720.py b/tests/test_schema_verify_6719_6720.py index b6dc7b69cf..c2853714f0 100644 --- a/tests/test_schema_verify_6719_6720.py +++ b/tests/test_schema_verify_6719_6720.py @@ -469,9 +469,9 @@ async def test_a_foreign_object_that_stops_a_migration_gets_the_drop_remedy( cause = info.value.cause assert cause is not None and cause.startswith(f"error in {kind} {name}: no such module"), cause text = str(info.value) - assert text.startswith(f"store {path}: drop this {kind}, then restart: '{name}'. This build"), ( - text - ) + assert text.startswith( + f"store {path}: drop this {kind}, then restart. The {kind}: '{name}'." + ), text assert "recreate" not in text and "NEW store key" not in text, text # The remedy is true: with that object dropped, the same migration runs and the open succeeds. _sql(path, drop) @@ -728,12 +728,11 @@ async def test_names_the_text_cannot_tell_apart_are_all_named_in_the_remedy( assert info.value.cause == cause assert isinstance(info.value.__cause__, sqlite3.OperationalError) assert str(info.value) == ( - f"store {path}: save each one's CREATE statement, then drop whichever of these 2 stops its" - " upgrade, and restart: the view 'vv' and the view 'vv after drop column'. Each CREATE" - " statement is" - " the sql column of its sqlite_master row, and saving it lets a healthy one be restored." - " The error's text could name each of them, and this build created none of them. The" - f" schema step failed: {cause}." + f"store {path}: save each CREATE statement, then drop whichever of these 2 stops the" + " upgrade, and restart. The 2: the view 'vv' and the view 'vv after drop column'. Each" + " CREATE statement is the sql column of its sqlite_master row, and saving it lets a healthy" + " one be restored. The error's text could name each of them, and this build created none" + f" of them. The schema step failed: {cause}." ) @@ -748,11 +747,11 @@ async def test_names_the_text_cannot_tell_apart_are_all_named_in_the_remedy( [ pytest.param( True, - "save each one's CREATE statement, then drop whichever of these 2 stops its upgrade, and" - " restart:", + "save each CREATE statement, then drop whichever of these 2 stops the upgrade, and" + " restart.", id="two-names", ), - pytest.param(False, "drop this view, then restart:", id="one-name"), + pytest.param(False, "drop this view, then restart.", id="one-name"), ], ) async def test_the_drop_instruction_survives_the_cut( @@ -803,9 +802,9 @@ async def test_three_names_the_text_cannot_tell_apart_are_listed_in_the_remedy( db, db.execute("ALTER TABLE t DROP COLUMN c"), path=path, counts_under_dek=False ) assert str(info.value).startswith( - f"store {path}: save each one's CREATE statement, then drop whichever of these 3 stops its" - " upgrade, and restart: the view 'vv', the view 'vv after drop column' and the view 'vv" - " after drop column: no such column'." + f"store {path}: save each CREATE statement, then drop whichever of these 3 stops the" + " upgrade, and restart. The 3: the view 'vv', the view 'vv after drop column' and the view" + " 'vv after drop column: no such column'." ), str(info.value) From 721c095904baf4bd319e55e7fd472b522b7c4794 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sun, 22 Nov 2026 05:03:06 -0600 Subject: [PATCH 71/74] Name the one foreign object only when its remedy survives the cut The multi-name remedy did not converge: on the default path the cut left a second name looking complete, and the save step never survived. Now an object is named only when the text fits exactly one candidate and the whole remedy, as safe_exc renders the message, survives uncut and unredacted; the code measures this with safe_exc itself. Every other case, two or more candidates or a remedy that would be cut, gets main's plain remedy, which names no object. The one-name remedy carries its save step: "store P: save the CREATE statement of the view 'X' from sqlite_master, drop it, and restart." The multi-name text and the hand-measured bound comments are gone. The changelog fragment states that rule and nothing more. Tests pin the one-name text at the real limit, the next longer name falling back with safe_exc's own cut marker shown, and both reproduced pairs falling back. Repairs the Lander's third hold on PR 3143, items H1-H3. BACKLOG #6719, #6720. --- .../6719-6720-foreign-view-remedy.fixed.md | 21 ++- messagefoundry/store/schema_verify.py | 54 +++--- tests/test_schema_verify_6719_6720.py | 170 +++++++++--------- 3 files changed, 119 insertions(+), 126 deletions(-) diff --git a/changelog.d/6719-6720-foreign-view-remedy.fixed.md b/changelog.d/6719-6720-foreign-view-remedy.fixed.md index 0612b3c05b..8b68fee02f 100644 --- a/changelog.d/6719-6720-foreign-view-remedy.fixed.md +++ b/changelog.d/6719-6720-foreign-view-remedy.fixed.md @@ -1,11 +1,10 @@ -- **A SQLite store whose upgrade is stopped by a view or trigger another tool left now names that - object.** When SQLite's re-check after a migration's `ALTER` fails on such a view or trigger with - an error that names the store's shape, such as "no such module", the open refuses the store with - the remedy to drop that object and restart, not to recreate the store. Where the error's text fits - more than one such name, as with views `vv` and `vv after drop column`, the remedy names each of - them rather than one that may be healthy. A view under the name of a - table or index this build creates still gets the recreate remedy, also when it is one of several - names the text fits. A failure on the store's shape - raised by the check's own read of the live store, after the schema script and the migrations of - a writable open, is now refused with the recreate remedy rather than escaping as SQLite's bare error. - (`BACKLOG #6719`, `BACKLOG #6720`) +- **A SQLite store whose upgrade is stopped by a view or trigger another tool left can now name + that object.** When SQLite's re-check after a migration's `ALTER` fails on such a view or trigger + with an error that names the store's shape, such as "no such module", and the error's text fits + exactly one such object, the open refuses the store with the remedy to save that object's CREATE + statement, drop it and restart, not to recreate the store. The object is named only when that + remedy fits uncut and unredacted in the 200 characters a printed error keeps; otherwise, and + whenever the text fits more than one object, the store gets the plain recreate remedy. A failure + on the store's shape raised by the check's own read of the live store, after the schema script + and the migrations of a writable open, is now refused with the recreate remedy rather than + escaping as SQLite's bare error. (`BACKLOG #6719`, `BACKLOG #6720`) diff --git a/messagefoundry/store/schema_verify.py b/messagefoundry/store/schema_verify.py index 79921d8940..2108532758 100644 --- a/messagefoundry/store/schema_verify.py +++ b/messagefoundry/store/schema_verify.py @@ -34,6 +34,8 @@ import aiosqlite +from messagefoundry.redaction import safe_exc + __all__ = [ "IndexShape", "SchemaMismatchError", @@ -435,9 +437,11 @@ async def run_schema_step[T]( One shape failure gets another remedy: SQLite's re-check of the schema after an ``ALTER`` names the view or trigger it could not parse, as in "error in view V: no such module". That object is another tool's (see ``_ORDINARY_TABLE``), and dropping it lets the migration run past - it (BACKLOG #6719). Where the text fits more than one such object, the remedy names each one - (see :func:`_foreign_objects`). A view under a name this build creates is not such an object: - it holds the place of a table or index, which is the incompatible store the plain remedy names.""" + it (BACKLOG #6719). The remedy names that object only where the text fits exactly one (see + :func:`_foreign_objects`) and the whole remedy survives :func:`~messagefoundry.redaction.safe_exc` + uncut and unredacted; otherwise it is the plain remedy. A view under a name this build creates + is not such an object: it holds the place of a table or index, which is the incompatible store + the plain remedy names.""" try: return await step except Exception as exc: @@ -447,36 +451,18 @@ async def run_schema_step[T]( foreign = await _foreign_objects(db, cause) if len(foreign) == 1: ((kind, name),) = foreign - # The whole instruction leads and the name follows it. safe_exc's 200-character cut - # keeps the instruction on a store path of up to 163 raw characters for a view and 160 - # for a trigger (measured), fewer where the redactor lengthens a path segment. A long - # name, and the text after it, may be cut, and a cut at a space inside a name leaves a - # shorter name; safe_exc's cut marker is then all that shows the name is incomplete. - raise SchemaMismatchError( - f"store {path}: drop this {kind}, then restart. The {kind}: {name!r}. This build did" - f" not create it, and it stops the store's upgrade. The schema step failed: {cause}.", - cause=cause, - ) from exc - if foreign: - # _foreign_objects does not pick among these, so the remedy names them all rather than - # tell the operator to drop one that may be healthy. The instruction, its save step and - # the count of names included, leads and is short. safe_exc's 200-character cut keeps - # all of it on a store path of up to 102 raw characters with fewer than 10 names, one - # character fewer for each further digit of the count (measured), and fewer where the - # redactor lengthens a path segment. The names follow it, so a long path or a long list - # loses names, and the text after them, to the cut; the count tells a reader of a cut - # copy that more names follow. - listed = [f"the {kind} {name!r}" for kind, name in foreign] - names = f"{', '.join(listed[:-1])} and {listed[-1]}" - count = len(foreign) - raise SchemaMismatchError( - f"store {path}: save each CREATE statement, then drop whichever of these {count}" - f" stops the upgrade, and restart. The {count}: {names}. Each CREATE statement is" - " the sql column of its sqlite_master row, and saving it lets a healthy one be" - " restored. The error's text could name each of them, and this build created none" - f" of them. The schema step failed: {cause}.", - cause=cause, - ) from exc + remedy = ( + f"store {path}: save the CREATE statement of the {kind} {name!r} from sqlite_master," + " drop it, and restart." + ) + message = ( + f"{remedy} This build did not create it, and it stops the store's upgrade. The" + f" schema step failed: {cause}." + ) + # Named only where safe_exc, which prints this error on the paths that cut it, shows + # the whole remedy unchanged: a cut or redacted name would name the wrong object. + if remedy in safe_exc(SchemaMismatchError(message)): + raise SchemaMismatchError(message, cause=cause) from exc if counts_under_dek is None: counts_under_dek = await _counts_under_a_dek(db) raise SchemaMismatchError( @@ -509,7 +495,7 @@ async def _foreign_objects(db: aiosqlite.Connection, cause: str) -> tuple[tuple[ least a healthy first-rank name, or the longest last-rank name, could be named alone. Under a suffix " during x", for one, which no test here has measured, a healthy ``vv during x`` beside a broken ``vv`` would be named for "error in view vv during x: ...". So where names collide the - ambiguity remains, and the remedy names each candidate, which may include a healthy one. With no + ambiguity remains, and more than one name is returned, which gets the plain remedy. With no first-rank name, the longest last-rank name is the one returned. The colon and " after " share a rank because a quoted name may hold either: with ``vv`` and diff --git a/tests/test_schema_verify_6719_6720.py b/tests/test_schema_verify_6719_6720.py index c2853714f0..7bf485fa66 100644 --- a/tests/test_schema_verify_6719_6720.py +++ b/tests/test_schema_verify_6719_6720.py @@ -23,10 +23,12 @@ import aiosqlite import pytest +from messagefoundry.redaction import _COUNT_OPENER, safe_exc from messagefoundry.store import MessageStore from messagefoundry.store.schema_verify import ( _ORDINARY_TABLE, SchemaMismatchError, + _remedy, is_schema_step_error, live_schema_differences, read_schema_shape, @@ -444,12 +446,14 @@ def _preset_columns(path: Path) -> set[str]: ], ) async def test_a_foreign_object_that_stops_a_migration_gets_the_drop_remedy( - tmp_path: Path, kind: str, dependent: str, drop: str + tmp_path: Path, kind: str, dependent: str, drop: str, monkeypatch: pytest.MonkeyPatch ) -> None: # A 0.3.2 preset table needs the RENAME COLUMN migration, and SQLite re-checks every view and # trigger after it. One that reads an unloaded module fails that check, naming itself. The store # is otherwise this build's, so the remedy is to drop that object, not to recreate the store. - path = tmp_path / "foreign.db" + # A short relative path keeps the remedy inside the cut whatever the runner's temp path is. + monkeypatch.chdir(tmp_path) + path = Path("foreign.db") await _fresh(path) _sql(path, "ALTER TABLE search_presets RENAME COLUMN owner_user_id TO owner") _plant_unloaded_virtual_table(path, "vt") @@ -470,7 +474,8 @@ async def test_a_foreign_object_that_stops_a_migration_gets_the_drop_remedy( assert cause is not None and cause.startswith(f"error in {kind} {name}: no such module"), cause text = str(info.value) assert text.startswith( - f"store {path}: drop this {kind}, then restart. The {kind}: '{name}'." + f"store {path}: save the CREATE statement of the {kind} '{name}' from sqlite_master, drop" + " it, and restart." ), text assert "recreate" not in text and "NEW store key" not in text, text # The remedy is true: with that object dropped, the same migration runs and the open succeeds. @@ -706,106 +711,109 @@ async def test_a_name_that_is_a_prefix_of_another_is_told_apart( assert await _foreign_objects(db, expected_cause) == tuple(("view", n) for n in found) -async def test_names_the_text_cannot_tell_apart_are_all_named_in_the_remedy( - tmp_path: Path, -) -> None: - # A broken "vv" beside a healthy "vv after drop column": the remedy must not tell the operator - # to drop the healthy view alone, so it names both, the instruction first. - path = tmp_path / "both.db" - _sql( - path, - "CREATE TABLE t (a, c)", - "CREATE TABLE u (c)", - "CREATE VIEW vv AS SELECT c FROM t", - 'CREATE VIEW "vv after drop column" AS SELECT c FROM u', +_SERVICE_PATH = r"C:\ProgramData\MessageFoundry\data\stores\production\instance-a\messagefoundry.db" +_CAUSE = "error in view {} after drop column: no such column: c" + + +def _named(name: str) -> tuple[str, str]: + """The one-name remedy for view ``name`` on _SERVICE_PATH, and the whole message.""" + remedy = ( + f"store {_SERVICE_PATH}: save the CREATE statement of the view {name!r} from sqlite_master," + " drop it, and restart." + ) + message = ( + f"{remedy} This build did not create it, and it stops the store's upgrade. The schema step" + f" failed: {_CAUSE.format(name)}." ) + return remedy, message + + +async def _refusal(path: Path, broken: str) -> SchemaMismatchError: + # The refusal for one broken view, which the DROP COLUMN re-check names. + _sql(path, "CREATE TABLE t (a, c)", f'CREATE VIEW "{broken}" AS SELECT c FROM t') async with _connected(path) as db: with pytest.raises(SchemaMismatchError) as info: await run_schema_step( - db, db.execute("ALTER TABLE t DROP COLUMN c"), path=path, counts_under_dek=False + db, + db.execute("ALTER TABLE t DROP COLUMN c"), + path=_SERVICE_PATH, + counts_under_dek=False, ) - cause = "error in view vv after drop column: no such column: c" - assert info.value.cause == cause assert isinstance(info.value.__cause__, sqlite3.OperationalError) - assert str(info.value) == ( - f"store {path}: save each CREATE statement, then drop whichever of these 2 stops the" - " upgrade, and restart. The 2: the view 'vv' and the view 'vv after drop column'. Each" - " CREATE statement is the sql column of its sqlite_master row, and saving it lets a healthy" - " one be restored. The error's text could name each of them, and this build created none" - f" of them. The schema step failed: {cause}." - ) + return info.value -_CUT_SERVICE_PATHS = ( - r"C:\ProgramData\MessageFoundry\data\messagefoundry.db", - r"C:\ProgramData\MessageFoundry\data\stores\production\instance-a\messagefoundry.db", -) +def _plain(cause: str) -> str: + return f"store {_SERVICE_PATH} {_remedy(False)} The schema step failed: {cause}." + + +async def test_one_name_is_named_only_while_its_whole_remedy_survives_the_cut( + tmp_path: Path, +) -> None: + # safe_exc cuts a printed error at 200 characters, marking the cut with _COUNT_OPENER. The + # longest name whose remedy ends before that marker is named, with the whole text pinned; one + # character more and the remedy would be cut, so the plain remedy names no object. + stem = "daily_census_by_unit_and_attending_for_the_weekly_report_of_the_quality_team" + fits = 0 + for k in range(1, len(stem) + 1): + remedy, message = _named(stem[:k]) + rendered = safe_exc(SchemaMismatchError(message)) + if not rendered.startswith(f"SchemaMismatchError: {remedy}"): + break + fits = k + assert 0 < fits < len(stem) + name, longer = stem[:fits], stem[: fits + 1] + + remedy, message = _named(name) + refusal = await _refusal(tmp_path / "fits.db", name) + assert str(refusal) == message + assert refusal.cause == _CAUSE.format(name) + rendered = safe_exc(refusal) + assert rendered.index(_COUNT_OPENER) >= len(f"SchemaMismatchError: {remedy}"), rendered + + remedy, message = _named(longer) + rendered = safe_exc(SchemaMismatchError(message)) + assert remedy not in rendered and _COUNT_OPENER in rendered, rendered + refusal = await _refusal(tmp_path / "cut.db", longer) + assert str(refusal) == _plain(_CAUSE.format(longer)) @pytest.mark.parametrize( - ("healthy", "lead"), + ("broken", "healthy", "cause"), [ pytest.param( - True, - "save each CREATE statement, then drop whichever of these 2 stops the upgrade, and" - " restart.", - id="two-names", + "vv", + "vv after drop column", + "error in view vv after drop column: no such column: c", + id="healthy-suffix-name", + ), + pytest.param( + "vv", + "vv: no such column", + "error in view vv: no such column: missing", + id="healthy-message-name", ), - pytest.param(False, "drop this view, then restart.", id="one-name"), ], ) -async def test_the_drop_instruction_survives_the_cut( - tmp_path: Path, healthy: bool, lead: str -) -> None: - # safe_exc cuts a rendered error at 200 characters. With a long name on a service path, the - # whole instruction, a save step included, must still reach the operator; the names may not. - from messagefoundry.redaction import safe_exc - - long = "daily_census_by_unit_and_attending_for_the_weekly_report" - path = tmp_path / "cut.db" - _sql( - path, - "CREATE TABLE t (a, c)", - "CREATE TABLE u (c)", - f'CREATE VIEW "{long}" AS SELECT c FROM t', - ) - if healthy: - _sql(path, f'CREATE VIEW "{long} after drop column" AS SELECT c FROM u') - async with _connected(path) as db: - with pytest.raises(SchemaMismatchError) as info: - await run_schema_step( - db, db.execute("ALTER TABLE t DROP COLUMN c"), path=path, counts_under_dek=False - ) - text = str(info.value) - assert text.startswith(f"store {path}: {lead} "), text - for service_path in _CUT_SERVICE_PATHS: - rendered = safe_exc(SchemaMismatchError(text.replace(str(path), service_path))) - assert "(+" in rendered, rendered # the cut ran - assert f"store {service_path}: {lead}" in rendered, rendered - - -async def test_three_names_the_text_cannot_tell_apart_are_listed_in_the_remedy( - tmp_path: Path, +async def test_two_candidates_get_the_plain_remedy( + tmp_path: Path, broken: str, healthy: str, cause: str ) -> None: - path = tmp_path / "three.db" - _sql( - path, - "CREATE TABLE t (a, c)", - "CREATE TABLE u (c)", - "CREATE VIEW vv AS SELECT c FROM t", - 'CREATE VIEW "vv after drop column" AS SELECT c FROM u', - 'CREATE VIEW "vv after drop column: no such column" AS SELECT c FROM u', + # The text fits both views, so naming either could tell the operator to drop the healthy one. + path = tmp_path / "both.db" + reads = "c FROM t" if "drop column" in cause else "missing FROM t" + statement = ( + "ALTER TABLE t DROP COLUMN c" if "drop column" in cause else "ALTER TABLE t RENAME TO t2" ) + _sql(path, "CREATE TABLE t (a, c)", "CREATE TABLE u (c)") + _sql(path, f'CREATE VIEW "{broken}" AS SELECT {reads}') + _sql(path, f'CREATE VIEW "{healthy}" AS SELECT c FROM u') async with _connected(path) as db: with pytest.raises(SchemaMismatchError) as info: await run_schema_step( - db, db.execute("ALTER TABLE t DROP COLUMN c"), path=path, counts_under_dek=False + db, db.execute(statement), path=_SERVICE_PATH, counts_under_dek=False ) - assert str(info.value).startswith( - f"store {path}: save each CREATE statement, then drop whichever of these 3 stops the" - " upgrade, and restart. The 3: the view 'vv', the view 'vv after drop column' and the view" - " 'vv after drop column: no such column'." - ), str(info.value) + assert info.value.cause == cause + assert str(info.value) == _plain(cause) @pytest.mark.parametrize( From 4257651204b41dc4bc276ff78c9f922fa02335d8 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sun, 22 Nov 2026 05:18:07 -0600 Subject: [PATCH 72/74] Build the one-name refusal once and narrow the changelog's cut claim Review round one of the third-hold repair found: - The changelog said a printed error keeps 200 characters; the CLI's store-open line prints it whole. It now says "where the error is printed cut to 200 characters". - The refusal was built twice, once to measure and once to raise; it is now built once and raised as measured. - The fit-arm test used str.index on the cut marker, which raises when no cut happens; it now checks the rendering starts with the remedy. - The two-candidate test derived its view body and statement from the cause; they are parameters now. A stale "both views are named" comment is corrected. Repairs the Lander's third hold on PR 3143. BACKLOG #6719, #6720. --- .../6719-6720-foreign-view-remedy.fixed.md | 10 ++++---- messagefoundry/store/schema_verify.py | 9 ++++---- tests/test_schema_verify_6719_6720.py | 23 +++++++++---------- 3 files changed, 21 insertions(+), 21 deletions(-) diff --git a/changelog.d/6719-6720-foreign-view-remedy.fixed.md b/changelog.d/6719-6720-foreign-view-remedy.fixed.md index 8b68fee02f..1e7b5c35db 100644 --- a/changelog.d/6719-6720-foreign-view-remedy.fixed.md +++ b/changelog.d/6719-6720-foreign-view-remedy.fixed.md @@ -3,8 +3,8 @@ with an error that names the store's shape, such as "no such module", and the error's text fits exactly one such object, the open refuses the store with the remedy to save that object's CREATE statement, drop it and restart, not to recreate the store. The object is named only when that - remedy fits uncut and unredacted in the 200 characters a printed error keeps; otherwise, and - whenever the text fits more than one object, the store gets the plain recreate remedy. A failure - on the store's shape raised by the check's own read of the live store, after the schema script - and the migrations of a writable open, is now refused with the recreate remedy rather than - escaping as SQLite's bare error. (`BACKLOG #6719`, `BACKLOG #6720`) + remedy survives uncut and unredacted where the error is printed cut to 200 characters; otherwise, + and whenever the text fits more than one object, the store gets the plain recreate remedy. A + failure on the store's shape raised by the check's own read of the live store, after the schema + script and the migrations of a writable open, is now refused with the recreate remedy rather + than escaping as SQLite's bare error. (`BACKLOG #6719`, `BACKLOG #6720`) diff --git a/messagefoundry/store/schema_verify.py b/messagefoundry/store/schema_verify.py index 2108532758..6a0cfec917 100644 --- a/messagefoundry/store/schema_verify.py +++ b/messagefoundry/store/schema_verify.py @@ -455,14 +455,15 @@ async def run_schema_step[T]( f"store {path}: save the CREATE statement of the {kind} {name!r} from sqlite_master," " drop it, and restart." ) - message = ( + refusal = SchemaMismatchError( f"{remedy} This build did not create it, and it stops the store's upgrade. The" - f" schema step failed: {cause}." + f" schema step failed: {cause}.", + cause=cause, ) # Named only where safe_exc, which prints this error on the paths that cut it, shows # the whole remedy unchanged: a cut or redacted name would name the wrong object. - if remedy in safe_exc(SchemaMismatchError(message)): - raise SchemaMismatchError(message, cause=cause) from exc + if remedy in safe_exc(refusal): + raise refusal from exc if counts_under_dek is None: counts_under_dek = await _counts_under_a_dek(db) raise SchemaMismatchError( diff --git a/tests/test_schema_verify_6719_6720.py b/tests/test_schema_verify_6719_6720.py index 7bf485fa66..fe756f1ee5 100644 --- a/tests/test_schema_verify_6719_6720.py +++ b/tests/test_schema_verify_6719_6720.py @@ -687,7 +687,7 @@ async def test_a_name_that_is_a_prefix_of_another_is_told_apart( # SQLite's own text, and views[0] is the broken view. A view already broken fails SQLite's # first check, with no suffix; a view the change breaks fails its re-check after the change, # with the "after drop column" suffix. Where both names rank first the code does not pick - # between them, so both views are named. In the suffix-name pair the text itself cannot settle + # between them, so both are returned and the remedy names neither. In the suffix-name pair the text itself cannot settle # the pair, since the healthy view's own name holds the suffix. The message-name pair and "vv # after after drop column" are ones a list of SQLite's messages or suffixes could settle, and # the code keeps none (see _foreign_objects). SQLite writes ": " after a name, so "a" is no @@ -769,7 +769,7 @@ async def test_one_name_is_named_only_while_its_whole_remedy_survives_the_cut( assert str(refusal) == message assert refusal.cause == _CAUSE.format(name) rendered = safe_exc(refusal) - assert rendered.index(_COUNT_OPENER) >= len(f"SchemaMismatchError: {remedy}"), rendered + assert rendered.startswith(f"SchemaMismatchError: {remedy}"), rendered remedy, message = _named(longer) rendered = safe_exc(SchemaMismatchError(message)) @@ -779,33 +779,32 @@ async def test_one_name_is_named_only_while_its_whole_remedy_survives_the_cut( @pytest.mark.parametrize( - ("broken", "healthy", "cause"), + ("healthy", "reads", "statement", "cause"), [ pytest.param( - "vv", "vv after drop column", + "c FROM t", + "ALTER TABLE t DROP COLUMN c", "error in view vv after drop column: no such column: c", id="healthy-suffix-name", ), pytest.param( - "vv", "vv: no such column", + "missing FROM t", + "ALTER TABLE t RENAME TO t2", "error in view vv: no such column: missing", id="healthy-message-name", ), ], ) async def test_two_candidates_get_the_plain_remedy( - tmp_path: Path, broken: str, healthy: str, cause: str + tmp_path: Path, healthy: str, reads: str, statement: str, cause: str ) -> None: - # The text fits both views, so naming either could tell the operator to drop the healthy one. + # A broken vv beside a healthy view. The text fits both, so naming either could tell the + # operator to drop the healthy one. path = tmp_path / "both.db" - reads = "c FROM t" if "drop column" in cause else "missing FROM t" - statement = ( - "ALTER TABLE t DROP COLUMN c" if "drop column" in cause else "ALTER TABLE t RENAME TO t2" - ) _sql(path, "CREATE TABLE t (a, c)", "CREATE TABLE u (c)") - _sql(path, f'CREATE VIEW "{broken}" AS SELECT {reads}') + _sql(path, f"CREATE VIEW vv AS SELECT {reads}") _sql(path, f'CREATE VIEW "{healthy}" AS SELECT c FROM u') async with _connected(path) as db: with pytest.raises(SchemaMismatchError) as info: From 84685477349fa956e01a52251cd69fee6be3b6f1 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sun, 22 Nov 2026 05:33:11 -0600 Subject: [PATCH 73/74] Say what the one-name check measures, and that the fallback is plain Review round two found the code comment gave a narrower reason ("a cut or redacted name") than the check applies: it needs the whole remedy, path included, to survive safe_exc unchanged. The comment now says so. The changelog said the fallback is the "recreate" remedy, but a store counted under its key gets the new-key remedy; it now says "the plain remedy", and states the cut-and-redaction rule without claiming where errors are printed. A long test-comment line is rewrapped. Repairs the Lander's third hold on PR 3143. BACKLOG #6719, #6720. --- changelog.d/6719-6720-foreign-view-remedy.fixed.md | 4 ++-- messagefoundry/store/schema_verify.py | 4 ++-- tests/test_schema_verify_6719_6720.py | 12 ++++++------ 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/changelog.d/6719-6720-foreign-view-remedy.fixed.md b/changelog.d/6719-6720-foreign-view-remedy.fixed.md index 1e7b5c35db..294d9d09cc 100644 --- a/changelog.d/6719-6720-foreign-view-remedy.fixed.md +++ b/changelog.d/6719-6720-foreign-view-remedy.fixed.md @@ -3,8 +3,8 @@ with an error that names the store's shape, such as "no such module", and the error's text fits exactly one such object, the open refuses the store with the remedy to save that object's CREATE statement, drop it and restart, not to recreate the store. The object is named only when that - remedy survives uncut and unredacted where the error is printed cut to 200 characters; otherwise, - and whenever the text fits more than one object, the store gets the plain recreate remedy. A + remedy survives the 200-character cut and the redaction of a printed error whole; otherwise, + and whenever the text fits more than one object, the store gets the plain remedy. A failure on the store's shape raised by the check's own read of the live store, after the schema script and the migrations of a writable open, is now refused with the recreate remedy rather than escaping as SQLite's bare error. (`BACKLOG #6719`, `BACKLOG #6720`) diff --git a/messagefoundry/store/schema_verify.py b/messagefoundry/store/schema_verify.py index 6a0cfec917..b24d1c7c5e 100644 --- a/messagefoundry/store/schema_verify.py +++ b/messagefoundry/store/schema_verify.py @@ -460,8 +460,8 @@ async def run_schema_step[T]( f" schema step failed: {cause}.", cause=cause, ) - # Named only where safe_exc, which prints this error on the paths that cut it, shows - # the whole remedy unchanged: a cut or redacted name would name the wrong object. + # Named only where safe_exc shows the whole remedy, path and name, unchanged; any cut + # or redaction falls back to the plain remedy. if remedy in safe_exc(refusal): raise refusal from exc if counts_under_dek is None: diff --git a/tests/test_schema_verify_6719_6720.py b/tests/test_schema_verify_6719_6720.py index fe756f1ee5..acdd530a80 100644 --- a/tests/test_schema_verify_6719_6720.py +++ b/tests/test_schema_verify_6719_6720.py @@ -687,12 +687,12 @@ async def test_a_name_that_is_a_prefix_of_another_is_told_apart( # SQLite's own text, and views[0] is the broken view. A view already broken fails SQLite's # first check, with no suffix; a view the change breaks fails its re-check after the change, # with the "after drop column" suffix. Where both names rank first the code does not pick - # between them, so both are returned and the remedy names neither. In the suffix-name pair the text itself cannot settle - # the pair, since the healthy view's own name holds the suffix. The message-name pair and "vv - # after after drop column" are ones a list of SQLite's messages or suffixes could settle, and - # the code keeps none (see _foreign_objects). SQLite writes ": " after a name, so "a" is no - # candidate for "a:b". A view under a name this build creates - # among the candidates gives the plain remedy, so nothing is returned. + # between them, so both are returned and the remedy names neither. In the suffix-name pair the + # text itself cannot settle the pair, since the healthy view's own name holds the suffix. The + # message-name pair and "vv after after drop column" are ones a list of SQLite's messages or + # suffixes could settle, and the code keeps none (see _foreign_objects). SQLite writes ": " + # after a name, so "a" is no candidate for "a:b". A view under a name this build creates among + # the candidates gives the plain remedy, so nothing is returned. from messagefoundry.store.schema_verify import _foreign_objects path = tmp_path / "prefix.db" From 662be70e230ea29518b11964c3c57d4508dea556 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sun, 22 Nov 2026 06:07:43 -0600 Subject: [PATCH 74/74] Name a foreign object from first-rank matches only With no first-rank match, _foreign_objects returned the longest last-rank name, whose remainder is no form SQLite writes after the object it names. A broken TEMP view "vv x", outside the main schema the match reads, beside a healthy "vv" then named the healthy "vv" alone. The last-rank list and that fallback are removed, so such a match gets main's plain remedy; the docstring no longer describes the branch. A new test pins the plain remedy for that case and fails with the old line restored. Repairs the Lander's fourth hold on PR 3143. BACKLOG #6719, #6720. --- messagefoundry/store/schema_verify.py | 13 +++++-------- tests/test_schema_verify_6719_6720.py | 20 ++++++++++++++++++++ 2 files changed, 25 insertions(+), 8 deletions(-) diff --git a/messagefoundry/store/schema_verify.py b/messagefoundry/store/schema_verify.py index b24d1c7c5e..1c948bae6b 100644 --- a/messagefoundry/store/schema_verify.py +++ b/messagefoundry/store/schema_verify.py @@ -493,11 +493,10 @@ async def _foreign_objects(db: aiosqlite.Connection, cause: str) -> tuple[tuple[ messages are measured and a list that missed one would name a healthy object alone. The " after " rank is itself a one-entry suffix assumption, with a residual of the same kind: a suffix SQLite writes that does not start " after " would rank the culprit last, and then at - least a healthy first-rank name, or the longest last-rank name, could be named alone. Under a + least a healthy first-rank name could be named alone. Under a suffix " during x", for one, which no test here has measured, a healthy ``vv during x`` beside a broken ``vv`` would be named for "error in view vv during x: ...". So where names collide the - ambiguity remains, and more than one name is returned, which gets the plain remedy. With no - first-rank name, the longest last-rank name is the one returned. + ambiguity remains, and more than one name is returned, which gets the plain remedy. The colon and " after " share a rank because a quoted name may hold either: with ``vv`` and ``vv: x``, "error in view vv: x after rename: ..." must not name ``vv`` alone. Where any name @@ -515,13 +514,11 @@ async def _foreign_objects(db: aiosqlite.Connection, cause: str) -> tuple[tuple[ async with db.execute(_FOREIGN_OBJECTS_SQL) as cur: objects = [(str(kind), str(name)) for kind, name in await cur.fetchall()] first: list[tuple[str, str]] = [] - last: list[tuple[str, str]] = [] for kind, name in objects: rest = cause.removeprefix(f"error in {kind} {name}") - if rest != cause and rest[:1] in (":", " "): - exact = rest.startswith((": ", " after ")) - (first if exact else last).append((kind, name)) - named = first or ([max(last, key=lambda o: len(o[1]))] if last else []) + if rest != cause and rest.startswith((": ", " after ")): + first.append((kind, name)) + named = first if not named: return () views = [name.lower() for kind, name in named if kind == "view"] diff --git a/tests/test_schema_verify_6719_6720.py b/tests/test_schema_verify_6719_6720.py index acdd530a80..5755daa9c6 100644 --- a/tests/test_schema_verify_6719_6720.py +++ b/tests/test_schema_verify_6719_6720.py @@ -815,6 +815,26 @@ async def test_two_candidates_get_the_plain_remedy( assert str(info.value) == _plain(cause) +async def test_a_last_rank_only_match_gets_the_plain_remedy(tmp_path: Path) -> None: + # A broken TEMP view "vv x" is outside the main schema the match reads, so the only name the + # text fits is the healthy "vv", with the remainder " x: ...". That is no form SQLite writes + # after the object it names, so "vv" is not named and the remedy is main's plain one. + path = tmp_path / "temp.db" + _sql(path, "CREATE TABLE t (a)", "CREATE VIEW vv AS SELECT a FROM t") + async with _connected(path) as db: + await db.execute('CREATE TEMP VIEW "vv x" AS SELECT missing FROM t') + with pytest.raises(SchemaMismatchError) as info: + await run_schema_step( + db, + db.execute("ALTER TABLE t RENAME TO t2"), + path=_SERVICE_PATH, + counts_under_dek=False, + ) + cause = "error in view vv x: no such column: missing" + assert info.value.cause == cause + assert str(info.value) == _plain(cause) + + @pytest.mark.parametrize( ("kind", "names", "cause", "found"), [