From 363ad14285c1e4a6f1167f641c8ef1e9af72a880 Mon Sep 17 00:00:00 2001 From: Zachary Lowden Date: Thu, 3 Dec 2026 18:50:11 -0600 Subject: [PATCH 01/15] conformance: freeze the oracle-recorded corpus and read routes from the Go server The Python oracle is being retired, so the 128 goldens recorded from it become a FIXED corpus: pinned by count and content digest (suite.check_frozen_corpus), never re-recorded (that would certify Go against itself). A future golden is recorded only from the Go server with `run_go.sh record `, stamped `recorded_from: cmd/cairn-server`, and hand-reviewed; the README says so and names the freeze commit. - fold the go_only mark (routes, rows and goldens stay; only the mark goes), and refuse any unread row key so a retired mark cannot linger - cases.declared_routes reads `cairn-server -routes` out of the built binary; `suite.py run`/`record` require --server-binary, which run_go.sh passes - oracle.py split: the world/token half moves to fixture.py, the boot half and mutate.py go with the oracle - internal/api's route ledger test loses the go-only branch, keeps grow/shrink Measured: run_go.sh 211 PASS / 0 FAIL / 5 SKIP; with one Go-recorded golden's status changed, exactly `FAIL sessions-authorized`. Co-Authored-By: Claude Opus 5.5 (1M context) --- internal/api/api_test.go | 83 +- internal/api/routes.go | 34 +- tests/conformance/README.md | 324 ++++---- tests/conformance/cases.py | 262 ++---- tests/conformance/{oracle.py => fixture.py} | 193 +---- tests/conformance/mutate.py | 71 -- tests/conformance/requests.json | 198 ++--- tests/conformance/run_go.sh | 38 +- tests/conformance/suite.py | 484 +++++------ tests/conformance/wire.py | 13 +- tests/test_conformance_suite.py | 861 ++++++-------------- 11 files changed, 821 insertions(+), 1740 deletions(-) rename tests/conformance/{oracle.py => fixture.py} (56%) delete mode 100644 tests/conformance/mutate.py diff --git a/internal/api/api_test.go b/internal/api/api_test.go index ec423707..b86a1226 100644 --- a/internal/api/api_test.go +++ b/internal/api/api_test.go @@ -53,24 +53,18 @@ type corpusRow struct { Method string `json:"method"` Target string `json:"target"` NegativeRoute bool `json:"negative_route"` - // GoOnly is the corpus's DECLARATION that only this server serves the row's - // route (decision 3 of the arcs/sessions plan: new surfaces are Go-only, and the - // oracle is not extended). The Python validator refuses the mark for a route the - // oracle declares; this side refuses it for a route THIS server does not - // dispatch. See `checkRouteLedger`. - GoOnly bool `json:"go_only"` } // corpusRows reads the conformance request list's rows. // -// 🔴 THIS FUNCTION IS THE GO SIDE OF A LEDGER THE SUITE CANNOT BUILD ITSELF. -// `tests/conformance/cases.declared_routes` reads the ORACLE's two dispatch tables by -// AST and fails when the declared set grows or shrinks against what the corpus -// addresses — and `tests/conformance/README.md` states plainly that this closure is -// "not closed for a non-Python implementation … so P1 has to add the equivalent ledger -// on the Go side". This is it, and it reads the SAME data file rather than a copy of -// it: a suite that replays a recorded list is structurally blind to a route added after -// the list was written, in either language. +// 🔴 THIS FUNCTION IS ONE OF TWO READERS OF ONE LEDGER, AND IT IS THE ONE THAT NEEDS NO +// BINARY. `tests/conformance/cases.declared_routes` asks the built server +// (`cairn-server -routes`) for the same set and `suite.py run` refuses to start without +// it; this test reads `DeclaredRoutes()` in-process. Both read the SAME data file rather +// than a copy of it: a suite that replays a recorded list is structurally blind to a +// route added after the list was written. (Until the Python oracle was retired, the +// suite's half read THAT server's dispatch tables by AST, and this side existed because +// that reader could not see a compiled program.) func corpusRows(t *testing.T) []corpusRow { t.Helper() path := filepath.Join(repoRoot(t), "tests", "conformance", "requests.json") @@ -113,25 +107,16 @@ func routeOf(c corpusRow) (string, bool) { // checkRouteLedger compares the routes this server declares against the routes the // corpus addresses. It is a pure function of its two operands so the guard can be fed -// a SYNTHETIC Go-only route — none exists yet — and watched to go red and green. +// a SYNTHETIC route and watched to go red and green. // // 🔴 IT FAILS WHEN THE SET GROWS **AND** WHEN IT SHRINKS. A route the corpus never // addresses is a public, internet-reachable endpoint nothing replays; a corpus row for // a route this server no longer serves records a 404 as if it were the contract. -// -// 🔴 `go_only` ROWS COUNT AS COVERAGE HERE, AND THAT IS THE WHOLE OF WHAT "HONOURED" -// MEANS ON THIS SIDE. Every route a `go_only` row addresses is one THIS server must -// dispatch, so a Go-only route needs a row like any other; what this side cannot know -// is whether the ORACLE serves it, and that edge is the Python validator's (it refuses -// the mark for a route `server.py` declares). Together: Go's routes minus the oracle's -// equals the routes `go_only` rows address — and `tests/test_go_client_ledgers.py` -// checks that equation directly, out of the running binary. func checkRouteLedger(declared []string, rows []corpusRow) error { if len(declared) == 0 { return fmt.Errorf("this server declares no route at all") } addressed := map[string]bool{} - goOnly := map[string]bool{} for _, c := range rows { // A `negative_route` row exists to pin what a NON-route answers, so it // contributes no coverage — the same exclusion the Python side makes, and for @@ -144,17 +129,14 @@ func checkRouteLedger(declared []string, rows []corpusRow) error { continue } addressed[name] = true - if c.GoOnly { - goOnly[name] = true - } } for _, name := range declared { if !addressed[name] { return fmt.Errorf("this server declares %q and the conformance request list "+ "never addresses it. A suite that replays a recorded list is STRUCTURALLY "+ "BLIND to a route added after the list was written — add a row per "+ - "principal shape (marked `go_only` if the oracle does not serve it), then "+ - "regenerate", name) + "principal shape, then record its golden from this server "+ + "(`tests/conformance/run_go.sh record`)", name) } } names := make([]string, 0, len(addressed)) @@ -166,14 +148,6 @@ func checkRouteLedger(declared []string, rows []corpusRow) error { if slices.Contains(declared, name) { continue } - // The specific diagnosis FIRST: a stale Go-only declaration is a different - // mistake from a stale shared row, and the fix differs (drop the mark and the - // rows, or wire the route), so it gets its own sentence. - if goOnly[name] { - return fmt.Errorf("the conformance request list marks %q `go_only` and this "+ - "server does not dispatch it. A Go-only declaration for a route Go does "+ - "not serve is STALE — it would record a 404 as the Go-only contract", name) - } return fmt.Errorf("the conformance request list addresses %q and this server does "+ "not dispatch it. The ledger fails when the set SHRINKS as well as when it "+ "grows", name) @@ -187,21 +161,19 @@ func TestTheRouteLedgerMatchesTheConformanceCorpus(t *testing.T) { } } -func TestTheRouteLedgerHonoursADeclaredGoOnlyRouteAndOnlyThat(t *testing.T) { - // 🔴 NO GO-ONLY ROUTE EXISTS YET, so the machinery is proved on a SYNTHETIC one - // rather than by adding a public endpoint. The real corpus and the real ledger are - // the base; `synthetic-go-only` is a head nothing serves. +func TestTheRouteLedgerRefusesAGrownOrAShrunkRouteSet(t *testing.T) { + // The machinery is proved on a SYNTHETIC route rather than by adding a public + // endpoint. The real corpus and the real ledger are the base; `synthetic-route` is + // a head nothing serves. rows := corpusRows(t) declared := DeclaredRoutes() - const head = "synthetic-go-only" + const head = "synthetic-route" withRoute := append(slices.Clone(declared), "GET "+head) row := corpusRow{ID: "synthetic", Method: "GET", Target: APIPrefix + head + "/alpha-notes"} - // GREEN: a declared Go route with a `go_only` row addressing it. - marked := row - marked.GoOnly = true - if err := checkRouteLedger(withRoute, append(slices.Clone(rows), marked)); err != nil { - t.Fatalf("a Go-only route WITH its go_only row must pass: %v", err) + // GREEN: a declared route with a row addressing it. + if err := checkRouteLedger(withRoute, append(slices.Clone(rows), row)); err != nil { + t.Fatalf("a declared route WITH its row must pass: %v", err) } // RED: the same route with NO row — the grow direction, with its own sentence. err := checkRouteLedger(withRoute, rows) @@ -209,20 +181,11 @@ func TestTheRouteLedgerHonoursADeclaredGoOnlyRouteAndOnlyThat(t *testing.T) { !strings.Contains(err.Error(), head) { t.Fatalf("a Go route with no corpus row must be refused by the GROW check, got %v", err) } - // RED: a `go_only` row for a route this server does NOT dispatch — the stale - // declaration, refused with the go-only sentence rather than the generic one. - err = checkRouteLedger(declared, append(slices.Clone(rows), marked)) - if err == nil || !strings.Contains(err.Error(), "is STALE") || - !strings.Contains(err.Error(), head) { - t.Fatalf("a go_only row for an undispatched route must be refused as STALE, got %v", err) - } - // …and the CONTROL on that branch: the same row UNmarked gets the generic - // shrink sentence, so the STALE text above is chosen by the mark and not by - // accident. + // RED: a row for a route this server does NOT dispatch — the shrink direction. err = checkRouteLedger(declared, append(slices.Clone(rows), row)) - if err == nil || strings.Contains(err.Error(), "is STALE") || - !strings.Contains(err.Error(), "SHRINKS") { - t.Fatalf("an unmarked row for an undispatched route must get the SHRINK sentence, got %v", err) + if err == nil || !strings.Contains(err.Error(), "SHRINKS") || + !strings.Contains(err.Error(), head) { + t.Fatalf("a row for an undispatched route must get the SHRINK sentence, got %v", err) } // The positive control on the base: the unmodified pair passes, so every red above // is the synthetic change and not the harness. diff --git a/internal/api/routes.go b/internal/api/routes.go index 323d7b37..c96f704f 100644 --- a/internal/api/routes.go +++ b/internal/api/routes.go @@ -16,13 +16,12 @@ import ( // `head = parts[0]` — so the guard moved from "what does the source look like" to // "what does the code dispatch from". // -// 🔴 AND FOR A NON-PYTHON IMPLEMENTATION THAT GUARD HAD TO BE REBUILT. The -// conformance suite reads the ORACLE's two dict literals by AST to prove the corpus -// addresses every declared route; there is no source for that reader to read here, -// and `tests/conformance/README.md` says so under "what this suite cannot see". What -// closes it on this side is `DeclaredRoutes` below, plus the Go test that compares its -// output against `tests/conformance/requests.json` — the same ledger claim, made from -// the same data file, failing when the set GROWS or SHRINKS. +// 🔴 `DeclaredRoutes` BELOW IS THE ONE DECLARATION OF THE ROUTE SET. The Go test that +// compares it against `tests/conformance/requests.json`, and the conformance suite (which +// reads it out of the built binary through `cairn-server -routes`), make the same ledger +// claim from the same data file, failing when the set GROWS or SHRINKS. (The suite once +// read the retired Python oracle's two dict literals by AST instead; that reader could +// not see a compiled program, which is why this side has its own.) // readArity counts the path components a read route takes INCLUDING the route name // itself, so `recall/` is 2 and `snapshot` is 1. @@ -64,21 +63,12 @@ type writeKey struct { // method on the server. The KEYS are declared here as the ledger, so the set is // readable without reading the wiring. // -// ⚠ `sessions`, `arcs`, `arc` AND `PUT arc` ARE GO-ONLY BY DECISION (decision 3 of the -// arcs/sessions plan): `server/server.py` does not serve them, and every row addressing them in -// `tests/conformance/requests.json` is marked `go_only`. The four places a head moves together are -// this table, those rows, the `go_only` rows of `tests/testlib/capability_ledger.LEDGER`, and -// `flake.nix`'s `want-go-only.txt`. -// -// ⚠ `sources` IS GO-ONLY ON THE SAME PRECEDENT (decision 10 of the scope-refs plan): the read of a -// scope's declared code sources, from a journal the browser surface writes and this pod only READS. -// Its derived `HEAD` is the ledger's one rule, kept (the plan's Q16). The dual-run gate discovers -// routes from the oracle, so it is BLIND to this head — a named gap, not a fifth ledger. -// -// ⚠ `whoami` IS GO-ONLY ON THE SAME PRECEDENT: the caller's own authority as JSON, built from -// the federation report and the read set (`whoami.go`). The oracle has no control plane and no -// group federation to report, so extending it would serve a view of nothing. Same four places, -// and the dual-run gate is blind to it for the same reason as `sources`. +// ⚠ A HEAD MOVES TOGETHER IN THREE PLACES: this table, the rows addressing it in +// `tests/conformance/requests.json` (each with a golden recorded from this server, see that +// directory's README), and `flake.nix`'s `want.txt` for `checks.go-server-declares-its-routes`. +// `sessions`, `arcs`, `arc`, `PUT arc`, `sources` and `whoami` were added after the Python oracle +// stopped being extended and were declared "Go-only" until it was retired; the decisions behind +// them are in the arcs/sessions and scope-refs plans. var readHeads = []string{"recall", "search", "snapshot", "sessions", "arcs", "arc", "sources", "whoami"} var writeKeys = []writeKey{ diff --git a/tests/conformance/README.md b/tests/conformance/README.md index b5d3b934..25ac14d3 100644 --- a/tests/conformance/README.md +++ b/tests/conformance/README.md @@ -1,54 +1,106 @@ # The HTTP conformance suite -This is the instrument that turns "we ported it carefully" into a measurement. It -records the store API's contract as **HTTP-level golden fixtures** generated from -the Python server, and replays the same declared requests against any -implementation — the oracle today, an unmodified Go binary at P1. +This is the instrument that turned "we ported it carefully" into a measurement. It holds +the store API's contract as **HTTP-level golden fixtures** and replays the same declared +requests against the Go server (`cmd/cairn-server`, the deployed pod). -It speaks HTTP and nothing else. `cases.py` and `wire.py` import no part of -`server.py` and no part of the client; `oracle.py` is the one module that knows -the oracle is Python, and it knows only how to build the fixture store and start -a subprocess. +It speaks HTTP and nothing else. `cases.py` and `wire.py` import no part of any server +and no part of the client; `fixture.py` knows only how to build the fixture store and +mint the token file. ```bash -python3 tests/conformance/suite.py generate # re-record every golden -python3 tests/conformance/suite.py run # replay against the oracle -python3 tests/conformance/suite.py run --base-url http://127.0.0.1:8102 \ - --token-file /path/to/tokens -python3 tests/conformance/suite.py normalizations # the declared licences to differ -python3 tests/conformance/suite.py build-store DIR # materialise the world +tests/conformance/run_go.sh # build cmd/cairn-server, boot it, replay (the gate) +tests/conformance/run_go.sh record ... # record goldens for NEW rows — then REVIEW them +python3 tests/conformance/suite.py normalizations # the declared licences to differ +python3 tests/conformance/suite.py build-store DIR # materialise the world ``` -`tests/test_conformance_suite.py` runs the whole thing under pytest, including -the negative controls. +`tests/test_conformance_suite.py` tests the instrument (the corpus guards, the frozen-corpus +check, the recorder's refusals) under pytest, in the tier with no Go toolchain; the `go` CI +job runs the replay itself, with a positive and a negative control. + +## 🔴 The frozen corpus + +**The goldens with no `recorded_from` field are a FIXED corpus, recorded from the retired +Python oracle (`server/server.py`) — the reference implementation the Go server was ported +from — and frozen as they stood at `ec1b756b15ea37469124c635d0d82f6e10d57899`, the last commit that had the oracle.** There are +128 of them (124 replayed, 4 kept as `oracle_only` records — see below). They are CONTRACT +WITNESSES: each says what the server must answer, and it was recorded from an implementation +other than the one it now tests. + +🔴 **NONE OF THEM IS EVER RE-RECORDED.** The server that produced them is deleted, and +re-recording one from the Go server would certify Go against itself — a green that measures +nothing. `suite.check_frozen_corpus` pins the unstamped set by count (`FROZEN_ORACLE_GOLDENS`) +and by a digest over every file's bytes (`FROZEN_ORACLE_DIGEST`), and `run` fails before it +compares anything if a frozen golden was edited, deleted or added. If a frozen golden +disagrees with the Go server, that is a finding about the server (or a deliberate contract +change that must be argued in review and recorded here), never a reason to regenerate. + +**`recorded_from: cmd/cairn-server`** marks a golden recorded from the Go server itself. It is +a **CHANGE DETECTOR, not a contract witness**: it can only say the served bytes did not MOVE, +never that they are right, because an expectation derived from the implementation it tests +proves nothing about that implementation. 48 goldens carry it today — the `sessions`, `arcs`, +`arc`, `PUT arc`, `sources` and `whoami` rows, routes added after the oracle stopped being +extended. Their contract witnesses are the Go tests with literal expected bodies (for +`sessions`: `internal/report/sessions_test.go`, `internal/api/sessions_test.go`; for the arc +registry: `internal/report/arcs_test.go`, `internal/api/arcs_test.go`, +`internal/arcs/arcs_test.go`; `internal/api/sources_test.go`; `internal/api/whoami_test.go`) +and the relations here, which every one of those read heads joins. + +### Adding a golden from now on + +A FUTURE row gets its golden in exactly one way: + +```bash +tests/conformance/run_go.sh record ... +``` + +It boots the Go server exactly as a `run` does, issues the WHOLE corpus in order (so the +golden is recorded under the arithmetic it is replayed under), and writes ONLY the named rows, +stamped `recorded_from: cmd/cairn-server`. It refuses — writing nothing — if no id is named, +if a named row already has a golden (frozen or not), if a named row is `oracle_only`, if a +relation fails over the server's answers, if a declared normalization fires on nothing, or if +a body names this machine. To change a Go-recorded golden, delete it in a reviewed commit +first, so the diff shows the old bytes and the new. + +🔴 **AND A RECORDED GOLDEN MUST BE HAND-REVIEWED BEFORE IT IS COMMITTED.** The recorder cannot +tell a right answer from a wrong one; a reviewer reads the status, every header and the body +against what the route is documented to do, and states in the commit which Go test pins the +same behaviour with a LITERAL expectation. A golden nobody read is a snapshot of whatever the +server happened to do. + +(History: until the oracle was retired, every golden was written by `suite.py generate` from +the oracle, and routes the oracle did not serve carried a "Go-only" mark and were recorded +by `run_go.sh record-go-only`. That mark was FOLDED, not dropped, when the oracle went: the rows, +routes and goldens all stayed, and only the mark — which said "this surface has no Python +twin" — carries nothing with one implementation. The `recorded_from` stamp it introduced is +what still distinguishes the two kinds of golden.) ## The pieces | path | what | |---|---| -| `world.json` | the fixture store: files, **mtimes**, the seed stamp, a scope's `.git/HEAD`, and the principals | +| `world.json` | the fixture store: files, **mtimes**, the seed stamp, a scope's `.git/HEAD`, the principals, and the seeded arc and code-sources journals | | `requests.json` | the declared request list — one row per case, plus the three relations | -| `golden/.json` | one recorded response per case | +| `golden/.json` | one recorded response per case — frozen, or stamped `recorded_from` | | `cases.py` | loads and VALIDATES the list; holds the route ledger | | `wire.py` | issues a case, normalizes the answer, records or reads a golden | -| `oracle.py` | builds the world, mints the tokens, boots `server/server.py` | -| `suite.py` | the generator, the runner, the relational assertions, the leak guard | -| `mutate.py` | puts a deliberately wrong server behind the suite | +| `fixture.py` | builds the world, mints the tokens, declares the server configuration | +| `suite.py` | the runner, the recorder, the relational assertions, the frozen-corpus check, the leak guard | +| `run_go.sh` | builds `cmd/cairn-server` from this tree, boots it over the world, runs `suite.py` | -## Fixtures are GENERATED, never hand-written +## Goldens are RECORDED, never hand-written A hand-edited golden asserts what somebody believed. Three things enforce that: -1. **Regeneration is one command** — `suite.py generate`. -2. **Every golden records `body.sha256`**, and `read_golden` refuses a file whose - recorded lines do not hash to it. A partial hand edit is a loud error naming - the regeneration command. -3. **A test regenerates the whole set and diffs it against what is committed** - (`TestTheGoldensAreGenerated`). If the two disagree, the committed goldens are - not what the generator produces, and the test says so. +1. **Every golden records `body.sha256`**, and `read_golden` refuses a file whose recorded + lines do not hash to it. A partial hand edit is a loud error. +2. **The frozen set is pinned by digest** (above), so even a consistent hand edit of a frozen + golden fails the run. +3. **A new golden comes only from `run_go.sh record`**, which refuses to overwrite anything. -Bodies are stored as **lines**, so a golden that moves moves one line in the -diff rather than rewriting a single escaped string. +Bodies are stored as **lines**, so a golden that moves moves one line in the diff rather than +rewriting a single escaped string. ### The store cannot be checked in @@ -63,7 +115,7 @@ normalized tar destroys. A real-looking 58-character credential committed to a public repository is a finding whether or not it ever authenticated anything, and `tests/leakscan.py` -refuses one on sight. `world.json` declares **principals**; `oracle.py` mints a +refuses one on sight. `world.json` declares **principals**; `fixture.py` mints a fresh token per principal per run and writes the token file. The request list names principals symbolically, and the runner maps a name back to whatever token the server under test was configured with by reading the same token file the @@ -71,13 +123,15 @@ server reads. No response in this contract contains a token. ## The server under test must be configured like this -The goldens do not apply to a server started any other way: +The goldens do not apply to a server started any other way. This is +`fixture.SERVER_ENV`, and it is part of the freeze — the oracle was booted with exactly +this table when the frozen goldens were recorded: | env | value | why | |---|---|---| | `CAIRN_TRUSTED_PROXIES` | `127.0.0.1/32` | the suite connects over loopback, so loopback is the trusted proxy and `CF-Connecting-IP` is honoured | | `CAIRN_MAX_FAILURES` | a large number | **see below** | -| `CAIRN_HOST` | `conformance-oracle` | keeps the real hostname out of a report body. Defence in depth only — the normalization is what makes a golden host-independent | +| `CAIRN_HOST` | `conformance-oracle` | keeps the real hostname out of a report body. Defence in depth only — the normalization is what makes a golden host-independent. The label is frozen with the corpus; it does not claim which server is running | 🔴 **`MAX_FAILURES` is the one that would silently destroy a run.** The lockout answers the *same uniform 401* a bad token does — that is the design — so once it @@ -91,117 +145,82 @@ authenticated, touches no store state, and is re-issued as the last request of every run. If it stops matching its golden, either a lockout tripped or the run mutated state a read depends on, and nothing after that point can be trusted. -## Four rows are asserted against the ORACLE ONLY +🔴 **The route ledger needs the server's own declaration.** `suite.py run` and `record` +REFUSE to start without `--server-binary`; the corpus is validated against what that binary +prints for `cairn-server -routes` (`api.DeclaredRoutes()`), failing when the server declares a +route no row addresses or a row addresses a route the server does not declare. `run_go.sh` +passes the binary it built. The same relation is checked in-process by `internal/api`'s +`TestTheRouteLedgerMatchesTheConformanceCorpus`. -🔴 **Some recorded behaviour is CPython or `http.server` ARTIFACT, not designed -contract**, and the corpus has to be able to say which. A row marked `oracle_only` -is asserted against the Python server and **skipped — by id, with its reason, counted -in the summary — for any other implementation**. `cases.py` refuses a mark with no -reason, and refuses a reason with no mark. +## Four FROZEN rows are never compared (`oracle_only`) -⚠ **IT IS THE LAST RESORT AND NOT THE FIRST.** A response differing in ONE FIELD -belongs in `wire.NORMALIZATIONS`, which keeps every other byte pinned for both -implementations. This mark stops the whole case being compared, so whatever the row was -covering has to be covered somewhere else and the reason must say where. +🔴 **Some recorded behaviour was CPython or `http.server` ARTIFACT, not designed contract**, +and the corpus has to be able to say which. A row marked `oracle_only` holds a frozen golden +of the oracle's own shape; with the oracle retired it is **skipped on every run — by id, with +its reason, counted in the summary**. It is kept as the RECORD of what the reference server +said, not deleted. `cases.py` refuses a mark with no reason, and refuses a reason with no mark; +`record` refuses to record one. No new row may carry it: a new golden is recorded from the Go +server, so it cannot differ from it. + +⚠ **IT WAS THE LAST RESORT AND NOT THE FIRST.** A response differing in ONE FIELD +belongs in `wire.NORMALIZATIONS`, which keeps every other byte pinned. | row | the artifact | where the contract half is covered | |---|---|---| -| `raw-malformed-request-line` | HTTP/0.9: `parse_request` never established a version, so `send_response_only` suppresses the status line and every header | nowhere else — the property is "it does not crash", and a framed 400 from a port satisfies it | -| `raw-malformed-absolute-target` | the request line never reaches a handler in a server whose framework parses it first; Go's `net/http` answers its own 400 in `readRequest` | **nowhere** — the answer comes from the framework's parser before any port code runs, so there is nothing to test; the security property holds because a framed 400 names no scope | +| `raw-malformed-request-line` | HTTP/0.9: `parse_request` never established a version, so `send_response_only` suppresses the status line and every header | nowhere else — the property is "it does not crash", and the Go server's framed 400 satisfies it | +| `raw-malformed-absolute-target` | the request line never reaches a handler in a server whose framework parses it first; Go's `net/http` answers its own 400 in `readRequest` | **nowhere** — the answer comes from the framework's parser before any server code runs, so there is nothing to test; the security property holds because a framed 400 names no scope | | `post-bullets-not-json` | the body quotes CPython's `json` diagnostic (`Expecting property name enclosed in double quotes: line 1 column 2 (char 1)`) | `write.TestDecodeBulletBodyRefusesRatherThanCrashing` and `api.TestAMalformedBodyIsAnsweredAndNotDropped` pin the 400, the `X-Store-Status`, the message prefix, and that the connection survives | | `post-bullets-deeply-nested-json` | the same, plus a defect (`RecursionError` out of `json.loads`) that a parser returning an error instead of unwinding the stack cannot reproduce | the same two Go tests | Both raw rows were ALREADY excluded from the uniform-401 relation for the first row's reason ("it reveals nothing about the store, so this is recorded rather than called a -defect"); the second now carries the same reasoning. When a member of a relation is +defect"); the second carries the same reasoning. When a member of a relation is skipped the runner says so on its own line and names how many members are left, and a relation left with NO members is a **failure** rather than a pass. -```bash -python3 tests/conformance/suite.py run --base-url … --token-file … # skips them, loudly -python3 tests/conformance/suite.py run --base-url … --token-file … --oracle-specific assert -``` +## The journals: the arc and code-sources rows -The second form is for a `--base-url` pointing at a hand-started **oracle**. Omitting -`--base-url` boots the oracle and always asserts. - -## …and the mirror: rows asserted against the GO SERVER ONLY (`sessions/` and the arc registry, 33 rows) - -🔴 **Before this mark, a route only the Go server serves had no legal spelling here** — its -rows were refused by the shrink half of the route ledger ("addresses routes the server no -longer declares"), so the only options were to extend the oracle or to diverge silently. -Decision 3 of `claudedocs/plan-cairn-arcs-sessions.md` puts the arcs/sessions routes in -`cmd/cairn-server` only, so a row addressing one carries **`go_only: true` + `go_only_why`**. -Against the oracle it is **skipped — by id, with its reason, counted** (`SKIP (go-only: -…)`); against any other server it is compared. `generate` records no golden for it from the -oracle, whose only answer would be its no-route 404. - -The mark cannot become a licence, because both edges are checked: `cases.validate_corpus` -refuses a `go_only` row for a route `server.py` DECLARES (and checks that before coverage, -so the diagnosis is reachable), and `internal/api`'s `checkRouteLedger` refuses one for a -route Go does NOT dispatch. `tests/test_go_client_ledgers.py` reads `cairn-server -routes` -and checks the whole equation — Go's routes minus the oracle's equals the `go_only` routes -here AND in `testlib/capability_ledger` — out of the running binary. - -🔴 **A `go_only` GOLDEN IS A CHANGE DETECTOR, NOT A CONTRACT WITNESS — and it says so in the -file.** Every other golden here is recorded from the oracle and states what ANY implementation -must answer. A `go_only` row has no second implementation, so its golden is recorded from the Go -server under test and carries `"recorded_from": "cmd/cairn-server"`; it can only say the served -bytes did not MOVE, never that they are right, because an expectation derived from the -implementation it tests proves nothing about that implementation. The contract witnesses for a -Go-only route are the Go tests with literal expected bodies (for `sessions`: -`internal/report/sessions_test.go`, `internal/api/sessions_test.go`) and the relations here, -which every go-only read head joins (refused-equals-absent, head-matches-get, uniform-401). -For the arc registry: `internal/report/arcs_test.go`, `internal/api/arcs_test.go` and -`internal/arcs/arcs_test.go`. - -🔴 **THE ARC ROWS NEED A SEEDED JOURNAL, AND ONLY `run_go.sh` PASSES ONE.** The routes answer +🔴 **THE ARC ROWS NEED A SEEDED JOURNAL, AND `run_go.sh` PASSES ONE.** The routes answer `registrations-unconfigured` unless the server is started with `-arc-journal`, so `build-store` writes the world's `arc_journal.records` to a file BESIDE the token file — outside the store tree, because the Go server refuses to start with a journal inside it — and prints -`arc-journal=`; `run_go.sh` hands that to the server for both `run` and `record-go-only`. -The `sources-*` rows (S2 of the scope-refs plan) follow the same arrangement with one difference: -`build-store` prints `source-journal=`, and `run_go.sh` hands it over as the ENVIRONMENT -variable `CAIRN_SOURCE_JOURNAL`, because the pod has no flag for it by decision. Each seeded -record's `revision` is computed by `write_source_journal` rather than written into `world.json` -(a 64-hex run is a credential-shaped literal there). ⚠ Two different checks, neither of which is the -other: `internal/codesrc`'s `TestTheRevisionIsALiteralDigest` pins Go's `Revision` against a LITERAL -digest; the cross-check that Python's spelling equals Go's is the `sources-authorized` golden, which -would read `sources-undeclared` if the fold skipped a seeded line for a wrong revision. The -corpus boots ONE server with ONE journal, so the unconfigured 200 and the unreadable-journal 503 -are NOT rows: their witnesses are the literal-body tests in `internal/api/sources_test.go`. -The `whoami-*` rows need no journal at all, and they can send only NON-federated callers: the -corpus boots on a token file with no OIDC verifier, so every row answers `not-federated`. The -three federated bodies (`mapped`, `groups-unmapped`, `no-groups`) are NOT rows; their witnesses -are the literal-body tests in `internal/api/whoami_test.go`, over a real journal and a real -signed token. -The oracle is never told. The seed holds an EARLIER and a LATER registration of one arc, so the -latest-wins fold is on the wire, and an arc homed in `alpha-notes` that DECLARES `beta-notes`, so -`arcs-hidden-home` (narrow-reader, which cannot read alpha) pins the home-scope visibility rule -beside `arcs-declared-elsewhere` (wide-reader), its positive control. The `PUT arc` rows run in -the write phase; `put-arc-unchanged` pins that an identical retry appends nothing. The pair -`put-arc` is keyed on the HOME scope because `validate_corpus` requires a pair's scope in the -TARGET; the declared-scope refusal (`put-arc-refused-declared`) is a standalone row, and its -byte-identity with an absent declared scope is pinned in `internal/api/arcs_test.go` instead. - -**The orphan check (S5) is a `?check=1` MODE of the `arcs` head, not a new head**, so no route -ledger moved; its four `arcs-check-*` rows are `go_only` like the head's, with their own -`arcs-check` refused-equals-absent pair. ⚠ The seeded journal holds no orphan, so every row here -answers `arcs-check-clean`: the corpus pins the served SHAPE and the authorisation relation, and -the findings (exit 9) are witnessed by `internal/report/arcscheck_test.go` and `tests/arcs/e2e.sh`. -The dual-run gate reads the parameter (`flagParam`) and declares it go-only rather than sending it. - -```bash -tests/conformance/run_go.sh record-go-only # the ONLY way a go_only golden is written -``` - -It boots the Go server exactly as a `run` does, issues the WHOLE corpus in order (so the goldens -are recorded under the arithmetic they are replayed under), writes ONLY the `go_only` rows, and -refuses — writing nothing — if a go-only route got no 2xx (the oracle's uniform 401 passed a -first, "anything but the no-route 404" draft of that floor, measured), if a relation fails, or -if a body names this machine. `run` refuses a golden whose stamp disagrees with its row's mark, -in either direction, so an oracle golden cannot become a change detector by accident nor the -reverse. `generate` still records none of these rows and leaves their goldens alone. +`arc-journal=`; `run_go.sh` hands that to the server for both `run` and `record`. +The `sources-*` rows follow the same arrangement with one difference: `build-store` prints +`source-journal=`, and `run_go.sh` hands it over as the ENVIRONMENT variable +`CAIRN_SOURCE_JOURNAL`, because the pod has no flag for it by decision. Each seeded record's +`revision` is computed by `write_source_journal` rather than written into `world.json` (a 64-hex +run is a credential-shaped literal there). ⚠ Two different checks, neither of which is the +other: `internal/codesrc`'s `TestTheRevisionIsALiteralDigest` pins Go's `Revision` against a +LITERAL digest; the cross-check that the Python spelling here equals Go's is the +`sources-authorized` golden, which would read `sources-undeclared` if the fold skipped a seeded +line for a wrong revision. The corpus boots ONE server with ONE journal, so the unconfigured 200 +and the unreadable-journal 503 are NOT rows: their witnesses are the literal-body tests in +`internal/api/sources_test.go`. The `whoami-*` rows need no journal at all, and they can send +only NON-federated callers: the corpus boots on a token file with no OIDC verifier, so every row +answers `not-federated`. The three federated bodies (`mapped`, `groups-unmapped`, `no-groups`) +are NOT rows; their witnesses are the literal-body tests in `internal/api/whoami_test.go`. +The seed holds an EARLIER and a LATER registration of one arc, so the latest-wins fold is on the +wire, and an arc homed in `alpha-notes` that DECLARES `beta-notes`, so `arcs-hidden-home` +(narrow-reader, which cannot read alpha) pins the home-scope visibility rule beside +`arcs-declared-elsewhere` (wide-reader), its positive control. The `PUT arc` rows run in the +write phase; `put-arc-unchanged` pins that an identical retry appends nothing. The pair `put-arc` +is keyed on the HOME scope because `validate_corpus` requires a pair's scope in the TARGET; the +declared-scope refusal (`put-arc-refused-declared`) is a standalone row, and its byte-identity +with an absent declared scope is pinned in `internal/api/arcs_test.go` instead. + +**The orphan check is a `?check=1` MODE of the `arcs` head, not a new head**, so no route ledger +moved; its four `arcs-check-*` rows have their own `arcs-check` refused-equals-absent pair. ⚠ The +seeded journal holds no orphan, so every row here answers `arcs-check-clean`: the corpus pins the +served SHAPE and the authorisation relation, and the findings (exit 9) are witnessed by +`internal/report/arcscheck_test.go` and `tests/arcs/e2e.sh`. + +--- + +📄 **Everything below this line is the RECORD of the oracle era** — how the corpus was built, +what it found, the rounds that hardened it — kept because several guards exist only because a +plausible theory was measured wrong. Where it says `generate`, `the oracle`, `mutate.py` or +"both implementations", it describes the state before `ec1b756`'s successor retired the +oracle; the binding rules are the sections above. ## Three cases send literal request bytes @@ -323,6 +342,9 @@ reason and prove nothing about this guard. ## Determinism is proven, on the dimensions that move +(Oracle-era record: this measured the generator, which no longer exists. What survives is +the host-label finding, whose fix lives in the normalizations every replay still applies.) + `generate` was run twice against a freshly-built world and the 98 goldens were byte-identical, to each other and to what is committed. That check is permanent (`TestTheGoldensAreGenerated`) — but on its own it is **structurally blind to @@ -341,23 +363,21 @@ So the dimensions were measured at a second point as well: Named rather than omitted, because a green run is a claim about the cases it encodes: -- **A route added after the fixtures were generated.** This is the structural - blind spot of anything that replays a recorded list. It is **closed for the - Python oracle**: `cases.declared_routes` reads `API_ROUTES` and `WRITE_ROUTES` - out of `server/server.py` by AST, and `validate_corpus` fails when the declared - set grows *or* shrinks against what the list addresses. There is no source for - that function to read in a compiled binary, so the Go side carries its own - ledger instead — `api.DeclaredRoutes()`, checked against `requests.json`, against - the wiring at construction, and against its own spelling by - `checks.go-server-declares-its-routes`, which reads it out of the RUNNING binary. - (This paragraph said "P1 has to add the equivalent ledger"; P1a added it, and a - future tense left on a finished thing reads as an open gap.) The AST reader is - still blind to a route dispatched from anywhere other than those two - module-level dict literals. -- **A Go-only route's CONTRACT.** A `go_only` row (see "…and the mirror" above) is never - compared against a second implementation, by decision. The corpus can tell you - the Go server still answers what was recorded; it cannot tell you that answer is - right. That is the Go tests' job, with literal expectations. +- **A route added after the fixtures were recorded.** This is the structural + blind spot of anything that replays a recorded list. It is **closed** by the route + ledger: `cases.declared_routes` reads `cairn-server -routes` out of the built binary + and `validate_corpus` fails when the declared set grows *or* shrinks against what the + list addresses; `api.DeclaredRoutes()` is also checked against `requests.json` in + process, against the wiring at construction, and against its own spelling by + `checks.go-server-declares-its-routes`. (Until the oracle was retired the suite read + `server/server.py`'s dispatch tables by AST instead, and the Go side's ledger existed + because that reader could not see a compiled program.) Still blind to a route + dispatched from anywhere other than the two tables `DeclaredRoutes` is built from. +- **The CONTRACT of any row whose golden was recorded from the Go server.** A golden + stamped `recorded_from: cmd/cairn-server` was never compared against a second + implementation. The corpus can tell you the Go server still answers what was + recorded; it cannot tell you that answer is right. That is the Go tests' job, with + literal expectations — and the reviewer's, when the golden is recorded. - **Three arc-registry states, by construction of this world.** The `registrations-unconfigured` off state (every Go run here HAS a journal), an `inferred` arc (the world's bullets carry no write trailer, and the write phase that appends one runs after every read), and a DAMAGED @@ -376,9 +396,9 @@ encodes: scope, or an EMPTY allowlist. Every one is a branch, and **measured**: with only the corpus-driven tests, 13 of 40 mutations to the Go renderer SURVIVED. `internal/report/testdata/reader_fixtures.json` is where that is covered — the - oracle's own rendered bytes over 50 such cases, generated by - `tests/reader_fixtures.py`. It is a sibling instrument, not part of this corpus: - it compares one function's output and knows nothing about HTTP. + oracle's own rendered bytes over such cases, recorded before the oracle was retired + and FROZEN with it, exactly like this corpus. It is a sibling instrument, not part of + this corpus: it compares one function's output and knows nothing about HTTP. - **Concurrency.** Every case is one request at a time, in a declared order. The commutativity and idempotency of two writers appending to one entry, the entry lock, the audit lock, and the listen backlog are all invisible here; @@ -671,6 +691,14 @@ hardcodes the default, and would survive a fully green suite. A reassuring zero is indistinguishable from a harness wired to nothing. +**Now:** the `go` CI job runs `run_go.sh` twice — over the committed goldens, where the PASS +floor is the positive control, and over a copy with ONE Go-recorded golden's status changed, +where exactly that case must FAIL (the negative control: the comparator can go red against the +real server). `tests/test_conformance_suite.py` proves the frozen-corpus check refuses an +edited, deleted and added golden, and that `record` refuses to overwrite one. + +**Until the oracle was retired** (the record below), the controls were these: + - **Negative control** — `mutate.py` copies `server/server.py`, applies one realistic mutation, and the suite must go red. Covered in `TestTheSuiteGoesRedOnARealMutation`: a status code moved, a header dropped, diff --git a/tests/conformance/cases.py b/tests/conformance/cases.py index 29fc1e09..e64e49b8 100644 --- a/tests/conformance/cases.py +++ b/tests/conformance/cases.py @@ -19,17 +19,14 @@ store. * EVERY DECLARED ROUTE IS ADDRESSED — see `declared_routes` for what this can and cannot see. This is the one guard that turns the list into a LEDGER. - * A ROUTE ONLY THE GO SERVER SERVES IS DECLARED, NEVER SILENT — its rows carry - `go_only`, and the mark is refused for a route the oracle declares. See - `Case.go_only`. * EVERY RELATION NAMES CASES THAT EXIST, and every case in a relation is actually issued. """ from __future__ import annotations -import ast import json +import subprocess from dataclasses import dataclass from pathlib import Path from typing import Any @@ -37,7 +34,14 @@ SUITE_DIR = Path(__file__).resolve().parent REPO_ROOT = SUITE_DIR.parents[1] REQUESTS_PATH = SUITE_DIR / "requests.json" -SERVER_SOURCE = REPO_ROOT / "server" / "server.py" + +#: Every key a row may carry. A row carrying any other (`_`-prefixed comments aside) is +#: refused by `load_corpus`, so a retired mark cannot linger in the file reading as live. +ROW_KEYS = frozenset({ + "id", "phase", "why", "method", "target", "principal", "token_literal", "client_ip", + "headers", "body", "raw_request", "normalize", "body_kind", "canary", "negative_route", + "oracle_only", "oracle_only_why", +}) #: The two phases, in the only order they may appear in. PHASES = ("read", "write") @@ -63,42 +67,22 @@ class Case: normalize: tuple[str, ...] = () body_kind: str = "auto" canary: bool = False - #: 🔴 THIS ROW RECORDS AN ANSWER THAT IS THE ORACLE'S OWN SHAPE RATHER THAN A - #: CONTRACT A PORT CAN HONOUR, so it is asserted against the Python server and - #: SKIPPED — by id, with its reason, reported in the summary — for any other - #: implementation. `oracle_only_why` states which artifact, and - #: `validate_corpus` refuses a mark with no reason: a licence to differ that - #: nobody can read is the same defect as an unused normalization one level up. + #: 🔴 THIS ROW'S FROZEN GOLDEN RECORDS AN ANSWER THAT WAS THE RETIRED ORACLE'S OWN + #: SHAPE (`http.server`'s or CPython's) RATHER THAN A CONTRACT THE GO SERVER HONOURS, + #: so it is SKIPPED — by id, with its reason, reported in the summary — on every run. + #: The oracle that could answer it is gone (`README.md`, "The frozen corpus"), so the + #: row is a RECORD of what that server said, kept beside the corpus rather than + #: deleted, and `oracle_only_why` must say where the part that IS a contract is + #: covered instead. `validate_corpus` refuses a mark with no reason: a licence to + #: differ that nobody can read is the same defect as an unused normalization one + #: level up. #: #: ⚠ IT IS THE LAST RESORT, NOT THE FIRST. A response that differs only in ONE - #: FIELD belongs in `wire.NORMALIZATIONS`, which keeps every other byte pinned - #: for both implementations; this mark stops the whole case being compared, so - #: whatever the row was covering has to be covered somewhere else and the - #: reason must say where. Four rows carry it today. + #: FIELD belongs in `wire.NORMALIZATIONS`, which keeps every other byte pinned. + #: ⚠ AND NO NEW ROW MAY CARRY IT: a new row's golden is recorded FROM the Go server + #: (`suite.record`), so it cannot differ from it. Four rows carry it, all frozen. oracle_only: bool = False oracle_only_why: str = "" - #: 🔴 THE MIRROR OF `oracle_only`: THIS ROW ADDRESSES A ROUTE ONLY THE GO SERVER - #: SERVES. The arcs/sessions phase extends `cmd/cairn-server` and NOT the oracle - #: (decision 3 of `claudedocs/plan-cairn-arcs-sessions.md`), so such a route is a - #: DECLARED divergence rather than a drifted one. The row is asserted against the - #: Go server and SKIPPED — by id, with its reason, counted — against the oracle, - #: which has no answer to record but its no-route 404. - #: - #: 🔴 THE MARK IS CHECKED AGAINST THE ORACLE'S TABLES IN BOTH DIRECTIONS, so it - #: cannot become a licence: a `go_only` row whose route the oracle DOES declare is - #: refused (the oracle grew it and the mark is now a lie), and an UNmarked row for - #: a route the oracle lacks is refused by the shrink half of the ledger below, - #: exactly as before. The Go side's `TestTheRouteLedgerMatchesTheConformanceCorpus` - #: closes the third edge — a `go_only` row for a route Go does not dispatch — so - #: between the two validators "Go's routes minus the oracle's" equals "the routes - #: `go_only` rows address", and `tests/test_go_client_ledgers.py` checks that - #: equation out of the running binary. ⚠ `suite.py generate` records goldens FROM - #: THE ORACLE and therefore records none for these rows; they are recorded from the - #: Go server by `run_go.sh record-go-only` and stamped `recorded_from: - #: cmd/cairn-server` — change detectors, not oracle witnesses (`suite.record_go_only`, - #: `suite.check_golden_provenance`). - go_only: bool = False - go_only_why: str = "" #: 🔴 THIS ROW DELIBERATELY ADDRESSES A METHOD/HEAD THE SERVER HAS NO ROUTE #: FOR — a `PATCH` at the entry noun, a `GET` at it, a `POST` at a read #: route. Such a row must NOT count as coverage of a route (its answer is a @@ -161,8 +145,17 @@ def by_id(self, case_id: str) -> Case: raise CorpusError(f"no case with id {case_id!r}") -def load_corpus(path: Path | None = None) -> Corpus: +def load_corpus(path: Path | None = None, *, routes: set[str] | None = None) -> Corpus: + """Load and validate the corpus. `routes`: see `validate_corpus`.""" raw = json.loads((path or REQUESTS_PATH).read_text(encoding="utf-8")) + for row in raw["cases"]: + unknown = sorted(k for k in row if not k.startswith("_") and k not in ROW_KEYS) + if unknown: + raise CorpusError( + f"case {row.get('id')!r} carries {unknown}, which this loader does not " + f"read. An unread key is a mark that changes nothing while looking like " + f"it does — refused rather than ignored." + ) cases: list[Case] = [] for row in raw["cases"]: row = {k: v for k, v in row.items() if not k.startswith("_")} @@ -187,8 +180,6 @@ def load_corpus(path: Path | None = None) -> Corpus: negative_route=bool(row.get("negative_route", False)), oracle_only=bool(row.get("oracle_only", False)), oracle_only_why=row.get("oracle_only_why", ""), - go_only=bool(row.get("go_only", False)), - go_only_why=row.get("go_only_why", ""), ) ) corpus = Corpus( @@ -209,18 +200,27 @@ def load_corpus(path: Path | None = None) -> Corpus: for p in raw["relations"]["head_matches_get"] ), ) - validate_corpus(corpus) + validate_corpus(corpus, routes=routes) return corpus def validate_corpus(corpus: Corpus, *, routes: set[str] | None = None) -> None: """Every structural property the corpus must hold. Raises `CorpusError`. - `routes` overrides what the oracle's source declares. It exists so a test - can mutation-test the ledger guard — add a route, remove one, mark a real - route negative — without editing `server/server.py`. Default: the real set. + `routes` is the set of ` ` routes the server under test DECLARES — + in a real run, `declared_routes()`, read out of the Go server itself. + + 🔴 WITH `routes=None` THE ROUTE-LEDGER HALF (the last three checks below) DOES NOT + RUN, AND THAT IS STATED RATHER THAN HIDDEN. The only declaration of the route set is + the compiled server (`api.DeclaredRoutes()`, printed by `cairn-server -routes`), and + the tier that loads this module without arguments — the `tests` job, and every + pytest that exercises the structural guards — has no Go toolchain. The ledger is + enforced in the tier that HAS one, twice: `suite.py run`/`record` REFUSE to start + without `--server-binary` (so `run_go.sh`, the gate, always checks it), and + `internal/api`'s `TestTheRouteLedgerMatchesTheConformanceCorpus` reads the same + `requests.json`. Tests pass a synthetic set to mutation-test the guard itself. """ - declared = declared_routes() if routes is None else routes + declared = routes seen: set[str] = set() for case in corpus.cases: if case.id in seen: @@ -250,8 +250,8 @@ def validate_corpus(corpus: Corpus, *, routes: set[str] | None = None) -> None: if case.oracle_only and not case.oracle_only_why.strip(): raise CorpusError( f"case {case.id!r} is marked oracle_only and states no reason. The " - f"mark stops the WHOLE case being compared for every implementation " - f"but the Python one, so it has to say which artifact it is excusing " + f"mark stops the WHOLE case being compared on every run, so it has to " + f"say which artifact of the retired oracle it is excusing " f"and where the part that IS a contract is covered instead. An " f"unexplained licence to differ is the defect `wire.py`'s " f"anti-widening guard exists to prevent, one level up." @@ -260,40 +260,9 @@ def validate_corpus(corpus: Corpus, *, routes: set[str] | None = None) -> None: raise CorpusError( f"case {case.id!r} states an oracle_only reason but is not marked " f"oracle_only, so the reason describes nothing and the row IS " - f"compared against every implementation. Set the mark, or delete " + f"compared on every run. Set the mark, or delete " f"the reason." ) - if case.go_only and not case.go_only_why.strip(): - raise CorpusError( - f"case {case.id!r} is marked go_only and states no reason. The mark " - f"stops the case being compared against the oracle at all, so it has " - f"to say why only the Go server serves this route — a licence to " - f"differ nobody can read is the defect `oracle_only` refuses too." - ) - if case.go_only_why.strip() and not case.go_only: - raise CorpusError( - f"case {case.id!r} states a go_only reason but is not marked go_only, " - f"so the reason describes nothing and the row IS compared against the " - f"oracle. Set the mark, or delete the reason." - ) - if case.go_only and case.oracle_only: - raise CorpusError( - f"case {case.id!r} is marked BOTH go_only and oracle_only, so it would " - f"be compared against neither server and cover nothing." - ) - if case.go_only and case.negative_route: - raise CorpusError( - f"case {case.id!r} is marked go_only AND negative_route. A negative row " - f"pins what a NON-route answers and is checked against the ORACLE's " - f"tables; there is no Go-only negative ledger, so the pair would be " - f"checked against nothing. Drop one mark." - ) - if case.go_only and _route_of(case) is None: - raise CorpusError( - f"case {case.id!r} is marked go_only but addresses no /api/v1/ route, " - f"so the mark names no route for either ledger to check and claims " - f"nothing." - ) # 🔴 READS BEFORE WRITES. See this module's docstring: the freshness fields a # report carries move the instant anything is written, so a read recorded @@ -374,6 +343,8 @@ def validate_corpus(corpus: Corpus, *, routes: set[str] | None = None) -> None: f"case {case.id!r} is marked negative_route but addresses no " f"/api/v1/ route at all, so the mark claims nothing" ) + if declared is None: + continue if named in declared: raise CorpusError( f"case {case.id!r} is marked negative_route for {named!r}, and the " @@ -382,23 +353,8 @@ def validate_corpus(corpus: Corpus, *, routes: set[str] | None = None) -> None: f"behind a row that looks deliberate." ) - # 🔴 THE GO-ONLY MARK IS CHECKED **BEFORE** COVERAGE, FOR THE REASON THE NEGATIVE - # SET IS: `addressed_routes` excludes `go_only` rows, so on the day the oracle - # grows a route that only `go_only` rows address, the coverage check below would - # fire first with "you never address it" — the wrong sentence for a corpus that - # addresses it and calls it Go-only. The specific diagnosis has to come first or - # it is unreachable. - grown = sorted(go_only_routes(corpus) & declared) - if grown: - raise CorpusError( - "rows marked go_only address routes the ORACLE declares: " - + ", ".join(grown) - + ". The mark says only the Go server serves the route, and it stops the " - "row being compared against the oracle — so for a route the oracle DOES " - "serve, the mark is now a lie that hides a comparison. Remove go_only " - "from those rows and regenerate their goldens from the oracle." - ) - + if declared is None: + return uncovered = sorted(declared - addressed_routes(corpus)) if uncovered: raise CorpusError( @@ -415,10 +371,7 @@ def validate_corpus(corpus: Corpus, *, routes: set[str] | None = None) -> None: "the request list addresses routes the server no longer declares: " + ", ".join(stale) + ". The ledger fails when the set SHRINKS as well as when it grows; a " - "row for a deleted route records a 404 as if it were the contract. If " - "the route is one ONLY the Go server serves, mark every row addressing " - "it `go_only` with a `go_only_why` — a declared divergence, never a " - "silent one." + "row for a deleted route records a 404 as if it were the contract." ) @@ -434,64 +387,37 @@ def validate_corpus(corpus: Corpus, *, routes: set[str] | None = None) -> None: # without a second spelling of "is this a write". -def declared_routes(source: Path | None = None) -> set[str]: - """Every ` ` the oracle's source declares a route for. - - 🔴 READ BY AST FROM `server/server.py`, NOT BY IMPORTING IT. Importing would - put the implementation inside the suite that exists to measure it from - outside; `tests/testlib/cairn_source.py` reads the client's constants the - same way, for the same reason. - - ⚠ WHAT THIS CANNOT SEE, stated rather than assumed away, because the guard - that reads it is the corpus's only defence against a route added tomorrow: - - * a route dispatched from anywhere OTHER than a module-level - `API_ROUTES = {...}` / `WRITE_ROUTES = {...}` dict literal. The server - documents those two tables as the only dispatch, and a test in - `tests/test_subsystem_store_api.py` pins `set(API_ROUTES)` against its - own ledger — but an `if path == "/api/v1/x"` added beside them would be - invisible here. - * a route added to a NON-PYTHON implementation. There is no source for - this function to read, so for the Go server this blind spot re-opens and - is closed on that side (`api.DeclaredRoutes()` against every row, - `go_only` ones included). `README.md` says so under "what this suite - cannot see". - * the non-API paths: `/healthz` and the uniform-401 catch-all are not - rows in either table and are covered by ordinary cases instead. +def declared_routes(binary: Path) -> set[str]: + """Every ` ` the GO SERVER declares, read out of the RUNNING binary. + + 🔴 `cairn-server -routes` PRINTS `api.DeclaredRoutes()`, which is built from the same + two tables the handler dispatches from — so this is the server's own declaration, not + a second spelling of it. It replaced an AST read of the retired Python oracle's + dispatch tables; with that source gone the binary is the only declaration left, and + asking it is the same shape `tests/test_go_client_ledgers.py` uses for `cairn -verbs`. + + ⚠ WHAT THIS CANNOT SEE: a route dispatched from anywhere OTHER than those two tables. + `internal/api`'s `TestEveryAPIPathReachesATable` is what keeps the handler free of + such a branch. The non-API paths (`/healthz`, the uniform-401 catch-all) are not + routes in this vocabulary and are covered by ordinary cases. + + Refuses on an empty answer: a ledger that discovers NOTHING reports full coverage + over an empty set, which is the reassuring zero this guard exists to avoid. """ - tree = ast.parse((source or SERVER_SOURCE).read_text(encoding="utf-8")) - read_heads: set[str] = set() - write_routes: set[str] = set() - for node in tree.body: - targets: list[ast.expr] = [] - if isinstance(node, ast.AnnAssign): - targets = [node.target] - elif isinstance(node, ast.Assign): - targets = list(node.targets) - if not targets or not isinstance(node.value, ast.Dict): - continue - names = {t.id for t in targets if isinstance(t, ast.Name)} - if "API_ROUTES" in names: - for key in node.value.keys: - if isinstance(key, ast.Constant) and isinstance(key.value, str): - read_heads.add(key.value) - if "WRITE_ROUTES" in names: - for key in node.value.keys: - if isinstance(key, ast.Tuple) and len(key.elts) == 2: - method, head = key.elts - if ( - isinstance(method, ast.Constant) - and isinstance(head, ast.Constant) - ): - write_routes.add(f"{method.value} {head.value}") - if not read_heads: + proc = subprocess.run( + [str(binary), "-routes"], capture_output=True, text=True, timeout=60, check=False + ) + if proc.returncode != 0: raise CorpusError( - f"no API_ROUTES dict literal found in {source or SERVER_SOURCE}. A " - f"route ledger that discovers NOTHING reports full coverage over an " - f"empty set, which is the reassuring zero this guard exists to avoid." + f"`{binary} -routes` exited {proc.returncode}: {proc.stderr.strip()[:400]}" ) - # Every read head is reachable by both safe methods the server allows. - return {f"{verb} {head}" for head in read_heads for verb in ("GET", "HEAD")} | write_routes + found = {line.strip() for line in proc.stdout.splitlines() if line.strip()} + if not found: + raise CorpusError( + f"`{binary} -routes` printed no routes. A route ledger that discovers NOTHING " + f"reports full coverage over an empty set." + ) + return found def _route_of(case: Case) -> str | None: @@ -507,35 +433,17 @@ def _route_of(case: Case) -> str | None: def addressed_routes(corpus: Corpus) -> set[str]: - """` ` for every case that addresses an ORACLE `/api/v1/` route. + """` ` for every case that addresses an `/api/v1/` route. Derived from the declared target, so a row cannot claim coverage it does not exercise. Cases aimed at `/healthz`, at a non-API path, or at a path with no head contribute nothing — which is correct: they cover no route. So do rows - marked `negative_route`, which exist to pin what a NON-route answers, and rows - marked `go_only`, whose route is the GO server's alone and is ledgered by - `go_only_routes` instead. ⚠ The Go side's `corpusRoutes` counts BOTH sets, - because every route here and every `go_only` route is one Go dispatches. - """ - out: set[str] = set() - for case in corpus.cases: - if case.negative_route or case.go_only: - continue - named = _route_of(case) - if named is not None: - out.add(named) - return out - - -def go_only_routes(corpus: Corpus) -> set[str]: - """` ` for every row marked `go_only` — the DECLARED divergence. - - `validate_corpus` refuses one the oracle declares; the Go side refuses one Go - does not dispatch. Empty until the first Go-only route lands. + marked `negative_route`, which exist to pin what a NON-route answers. The Go + side's `corpusRoutes` computes the same set from the same file. """ out: set[str] = set() for case in corpus.cases: - if not case.go_only: + if case.negative_route: continue named = _route_of(case) if named is not None: diff --git a/tests/conformance/oracle.py b/tests/conformance/fixture.py similarity index 56% rename from tests/conformance/oracle.py rename to tests/conformance/fixture.py index 30c9716d..4b2db479 100644 --- a/tests/conformance/oracle.py +++ b/tests/conformance/fixture.py @@ -1,17 +1,19 @@ -"""Build the fixture world, and boot the PYTHON server over it. +"""Build the fixture world the conformance corpus is replayed over. -🔴 THIS IS THE ONLY MODULE IN THE SUITE THAT KNOWS THE ORACLE IS PYTHON, AND -THAT IS THE WHOLE POINT OF SPLITTING IT OUT. `cases.py` and `wire.py` speak -HTTP and nothing else, so the runner can be pointed at a Go binary — or at a -pod — without a line of this file being involved. What lives here is exactly -the two things a language-agnostic suite cannot avoid owning: +🔴 THIS IS THE ONLY MODULE IN THE SUITE THAT KNOWS WHAT THE WORLD LOOKS LIKE ON +DISK. `cases.py` and `wire.py` speak HTTP and nothing else, so the runner can be +pointed at any server — the Go binary `run_go.sh` builds, or a pod — without a +line of this file being involved. What lives here is the one thing an HTTP suite +cannot avoid owning: * BUILDING THE WORLD. The store cannot be checked into git, because git stores no mtime and this contract depends on mtimes (see `world.json`). So - the store is materialised from a declaration, and any implementation under - test is served the same bytes with the same timestamps. - * LAUNCHING THE ORACLE. Only the generator needs this; the runner takes a - base URL. + the store is materialised from a declaration, and the server under test is + served the same bytes with the same timestamps the goldens were recorded + over. + +(This module was split out of the one that also BOOTED the Python oracle; that +half was deleted with the oracle. `README.md`, "The frozen corpus".) 🔴 THE TOKENS ARE GENERATED, NEVER CHECKED IN. A real-looking 58-character credential committed to a PUBLIC repository is a finding whether or not it ever @@ -28,28 +30,24 @@ import json import os import secrets -import socket -import subprocess -import sys -import time -import urllib.error -import urllib.request from dataclasses import dataclass from pathlib import Path -#: `/tests/conformance/oracle.py` -> ``. +#: `/tests/conformance/fixture.py` -> ``. REPO_ROOT = Path(__file__).resolve().parents[2] SUITE_DIR = Path(__file__).resolve().parent WORLD_PATH = SUITE_DIR / "world.json" -SERVER_PY = REPO_ROOT / "server" / "server.py" #: The principal name a bare (legacy) token row is addressed by. A bare row has #: no identity field in the file, so the suite needs one agreed word for it. LEGACY_PRINCIPAL = "legacy" # 🔴 THE SERVER CONFIGURATION IS PART OF THE CONTRACT THIS SUITE RECORDS, SO IT -# IS DECLARED RATHER THAN DEFAULTED, and an implementation under test MUST be -# started with the same values or the goldens do not apply to it. +# IS DECLARED RATHER THAN DEFAULTED, and the server under test MUST be started +# with the same values or the goldens do not apply to it. These are the values the +# frozen corpus was recorded under (the retired oracle was booted with exactly this +# table), so they are part of the freeze: change one and the frozen goldens stop +# describing the configuration they are replayed under. # # 🔴 `MAX_FAILURES` IS THE ONE THAT WOULD SILENTLY DESTROY A RUN. The lockout # answers the SAME uniform 401 a bad token does — that is the design — so once @@ -57,9 +55,8 @@ # golden except by accident. This corpus issues 15 deliberate refusals from one # client address, and the six that carry a WRONG-OR-ABSENT CREDENTIAL are the # ones the limiter counts — over the production default of 5 per minute, which -# `_count_failure` would turn into a lockout partway through the read phase. -# (A non-API path and a missing client IP are deliberately NOT counted; see the -# rate-limit note in `_handle`.) Raising the ceiling is not a convenience: without +# the limiter would turn into a lockout partway through the read phase. +# (A non-API path and a missing client IP are deliberately NOT counted.) Raising the ceiling is not a convenience: without # it the suite cannot pass twice, and with it the LOCKOUT ITSELF becomes # something the suite cannot see (`README.md` names it under that heading). # `wire.py`'s canary is what keeps the raised ceiling honest rather than assumed. @@ -71,24 +68,18 @@ # repository; the `report-host-identity` normalization is what actually makes a # golden host-independent, because the machine-id prefix is appended regardless. # `suite.check_no_host_leak` is what proves both worked instead of assuming it. -ORACLE_ENV = { - # 🔴 THE **CURRENT** SPELLINGS, AND THAT IS PART OF WHAT THE CORPUS MEASURES. - # `SUBSYSTEM_STORE_*` still resolves on both servers through `internal/envalias` / - # `lib/env_aliases.py`, but this world is replayed against BOTH implementations, so - # naming the new spelling here is the one place a corpus run would notice if only one - # of them had learned it. The alias direction is covered by `tests/test_env_aliases.py` - # and, byte-for-byte across two languages, by `tests/parity/harness.py`. +SERVER_ENV = { + # 🔴 THE **CURRENT** SPELLINGS. `SUBSYSTEM_STORE_*` still resolves through + # `internal/envalias`, whose own tests cover the alias direction. + # ⚠ `conformance-oracle` IS A FROZEN LABEL, NOT A CLAIM ABOUT WHICH SERVER RUNS: it is + # the host label the corpus was recorded under, normalised out of every body. "CAIRN_TRUSTED_PROXIES": "127.0.0.1/32", "CAIRN_MAX_FAILURES": "1000000", "CAIRN_HOST": "conformance-oracle", } -#: How long to wait for the oracle to answer `/healthz` after exec. -BOOT_TIMEOUT_S = 30.0 - - -class OracleError(RuntimeError): - """The oracle could not be built, started, or reached.""" +class FixtureError(RuntimeError): + """The fixture world or its token file is not what the corpus needs.""" def load_world(path: Path | None = None) -> dict: @@ -179,7 +170,7 @@ def write_token_file(path: Path, tokens: dict[str, str], world: dict | None = No elif spec["kind"] == "mapped": rows.append(f"{token} {spec['identity']} {','.join(spec['scopes'])}") else: - raise OracleError(f"unknown principal kind {spec['kind']!r}") + raise FixtureError(f"unknown principal kind {spec['kind']!r}") path.write_text("\n".join(rows) + "\n", encoding="utf-8") path.chmod(0o600) return path @@ -194,7 +185,7 @@ def principals_from_token_file(path: Path, world: dict | None = None) -> dict[st is the legacy principal — that is the file format's own rule, not a convention invented here. - Raises `OracleError` when a principal the request list needs is absent, + Raises `FixtureError` when a principal the request list needs is absent, because the alternative is a run that silently sends no credential and records a corpus of 401s as if it were the contract. """ @@ -215,134 +206,10 @@ def principals_from_token_file(path: Path, world: dict | None = None) -> dict[st for spec in world["principals"]: key = LEGACY_PRINCIPAL if spec["kind"] == "legacy" else spec["identity"] if key not in found: - raise OracleError( + raise FixtureError( f"the token file {path} has no row for principal {spec['name']!r} " f"(looked for {'a bare row' if spec['kind'] == 'legacy' else key!r}). " f"The server under test is not configured for this corpus." ) out[spec["name"]] = found[key] return out - - -def _free_port() -> int: - """A port nothing is listening on right now. - - ⚠ RACY BY CONSTRUCTION and there is no non-racy alternative here: the - oracle is a separate process, so it cannot inherit a socket this one bound. - The window is microseconds and a collision presents as a loud bind failure - in `boot_oracle`, never as a wrong answer. - """ - with socket.socket() as s: - s.bind(("127.0.0.1", 0)) - return int(s.getsockname()[1]) - - -@dataclass -class Oracle: - base_url: str - store_root: Path - token_file: Path - principals: dict[str, Principal] - process: subprocess.Popen - log: Path - - -def boot_oracle( - workdir: Path, - world: dict | None = None, - *, - server_py: Path | None = None, - extra_env: dict[str, str] | None = None, -) -> Oracle: - """Build the world under `workdir` and start `server/server.py` over it. - - 🔴 A SUBPROCESS, NOT AN IN-PROCESS `build_server`. Two reasons, and the - second is the one that matters: an in-process server would make the - generator depend on importing the implementation it is recording, which is - exactly the coupling this suite exists to remove; and `main()` is where the - env, the argv and the token-file parsing live, so booting any other way - would record a contract nobody deploys. - """ - world = world if world is not None else load_world() - store = build_store(workdir / "store", world) - tokens = mint_tokens(world) - token_file = write_token_file(workdir / "tokens", tokens, world) - port = _free_port() - log = workdir / "oracle.log" - env = dict(os.environ) - env.update(ORACLE_ENV) - env.update(extra_env or {}) - # The audit stream is the server's stdout. It is kept for diagnosis and is - # deliberately NOT part of the contract this suite records — see README.md. - handle = log.open("wb") - proc = subprocess.Popen( - [ - sys.executable, - str(server_py or SERVER_PY), - "--store", str(store), - "--host", "127.0.0.1", - "--port", str(port), - "--token-file", str(token_file), - ], - stdout=handle, - stderr=subprocess.STDOUT, - env=env, - ) - base = f"http://127.0.0.1:{port}" - deadline = time.monotonic() + BOOT_TIMEOUT_S - while True: - if proc.poll() is not None: - handle.close() - raise OracleError( - f"the oracle exited {proc.returncode} before answering /healthz:\n" - + log.read_text(encoding="utf-8", errors="replace") - ) - try: - with urllib.request.urlopen(base + "/healthz", timeout=1.0) as resp: - if resp.status == 200: - break - except (urllib.error.URLError, OSError, TimeoutError): - pass - if time.monotonic() > deadline: - proc.kill() - handle.close() - raise OracleError( - f"the oracle did not answer /healthz within {BOOT_TIMEOUT_S}s:\n" - + log.read_text(encoding="utf-8", errors="replace") - ) - time.sleep(0.02) - return Oracle( - base_url=base, - store_root=store, - token_file=token_file, - principals=principals_from_token_file(token_file, world), - process=proc, - log=log, - ) - - -def stop_oracle(oracle: Oracle) -> None: - oracle.process.terminate() - try: - oracle.process.wait(timeout=10) - except subprocess.TimeoutExpired: # pragma: no cover - belt and braces - oracle.process.kill() - oracle.process.wait(timeout=10) - - -class running_oracle: # noqa: N801 - a context manager used as `with running_oracle(...)` - """`with running_oracle(tmp) as oracle:` — boot, yield, always terminate.""" - - def __init__(self, workdir: Path, world: dict | None = None, **kwargs) -> None: - self._workdir = workdir - self._world = world - self._kwargs = kwargs - self._oracle: Oracle | None = None - - def __enter__(self) -> Oracle: - self._oracle = boot_oracle(self._workdir, self._world, **self._kwargs) - return self._oracle - - def __exit__(self, *_exc) -> None: - if self._oracle is not None: - stop_oracle(self._oracle) diff --git a/tests/conformance/mutate.py b/tests/conformance/mutate.py deleted file mode 100644 index da18e070..00000000 --- a/tests/conformance/mutate.py +++ /dev/null @@ -1,71 +0,0 @@ -"""Put a DELIBERATELY WRONG server behind the suite, so its green means something. - -🔴 A REASSURING ZERO IS INDISTINGUISHABLE FROM A HARNESS WIRED TO NOTHING. This -module exists so the conformance suite's own verdict can be validated the way -`tests/leakscan.py` validates its own: by feeding it a case it MUST fail. - - * NEGATIVE CONTROL — `mutated_server` copies `server/server.py`, applies one - textual mutation, and returns a path `oracle.boot_oracle(server_py=...)` can - start. The mutations the tests use are REALISTIC — a status code moved, a - header dropped, a preserved mtime truncated to whole seconds, a refusal made - distinguishable from an absence — not textbook edits the suite could only - ever recognise in the form it was written for. - * POSITIVE CONTROL — `unmutated_server` does the same copy with NO edit. It - has to pass. Without it, "the mutant was caught" cannot be told apart from - "the copied tree never booted", which is the same green-for-the-wrong-reason - the mutation is meant to expose. - -🔴 THE COPY IS A TREE, NOT A FILE. `server.py` finds its modules with -`Path(__file__).resolve().parents[1] / "lib"`, so a lone copy in `/tmp` imports -nothing. The mutant tree is `/server/server.py` beside a SYMLINK to the -real `lib/` — read-only, shared, and never written to. -""" - -from __future__ import annotations - -from pathlib import Path - -REPO_ROOT = Path(__file__).resolve().parents[2] -SERVER_PY = REPO_ROOT / "server" / "server.py" -LIB = REPO_ROOT / "lib" - - -class MutationError(AssertionError): - """The mutation did not apply, so the control would have proven nothing.""" - - -def _tree(dest: Path) -> Path: - (dest / "server").mkdir(parents=True, exist_ok=True) - link = dest / "lib" - if not link.exists(): - link.symlink_to(LIB) - return dest / "server" / "server.py" - - -def unmutated_server(dest: Path) -> Path: - """The POSITIVE control: the same copy mechanics, no edit.""" - target = _tree(dest) - target.write_text(SERVER_PY.read_text(encoding="utf-8"), encoding="utf-8") - return target - - -def mutated_server(dest: Path, old: str, new: str, *, count: int = 1) -> Path: - """Copy the server with exactly `count` occurrences of `old` replaced. - - 🔴 THE OCCURRENCE COUNT IS ASSERTED, because a `replace` that matched - NOTHING would produce an unmutated server that the suite then passes — and - the run would be reported as `this mutation was not caught`. That is the - mutation sweep's classic false SURVIVED, and it is the one failure mode a - negative control cannot afford. - """ - source = SERVER_PY.read_text(encoding="utf-8") - found = source.count(old) - if found != count: - raise MutationError( - f"the mutation pattern occurs {found} time(s) in server.py, not " - f"{count}. A pattern that matches nothing yields an UNMUTATED server " - f"and the control would report the mutant as survived.\n pattern: {old!r}" - ) - target = _tree(dest) - target.write_text(source.replace(old, new, count), encoding="utf-8") - return target diff --git a/tests/conformance/requests.json b/tests/conformance/requests.json index f5f7a76e..8747160c 100644 --- a/tests/conformance/requests.json +++ b/tests/conformance/requests.json @@ -10,9 +10,9 @@ "the two cases whose request line cannot be expressed by an HTTP client at", "all), `normalize` (declared licences to differ - see suite.py normalizations),", "`body_kind` (`snapshot` records the extracted tree instead of the bytes),", - "`canary`, `negative_route`, `oracle_only` + `oracle_only_why` (asserted against", - "the oracle only), `go_only` + `go_only_why` (a route ONLY the Go server serves:", - "skipped against the oracle, asserted against Go - see cases.Case.go_only).", + "`canary`, `negative_route`, `oracle_only` + `oracle_only_why` (a FROZEN row whose", + "golden is the retired oracle's own shape: skipped on every run - see", + "cases.Case.oracle_only). Any other key is refused by cases.load_corpus.", "", "PHASE is `write` for a case that MAY CHANGE THE STORE, and `read` for every", "case that cannot. cases.py refuses a `read` row placed after the first", @@ -1224,9 +1224,7 @@ "method": "GET", "target": "/api/v1/sessions/alpha-notes", "principal": "wide-reader", - "why": "the ordinary read over a scope whose bullets carry NO write trailer: `no-attributed-writes`, with `attributed: 0 of N` printed rather than an empty list that reads as 'nobody wrote here'. No `normalize` key: the body names no host and no store path, so every byte is deterministic.", - "go_only": true, - "go_only_why": "`sessions/` is served by the Go server only - decision 3 of the arcs/sessions plan extends `cmd/cairn-server` and not the oracle. Its golden is recorded from the Go server (`recorded_from: cmd/cairn-server`), a CHANGE DETECTOR rather than an oracle witness; the literal-body contract lives in `internal/report/sessions_test.go`." + "why": "the ordinary read over a scope whose bullets carry NO write trailer: `no-attributed-writes`, with `attributed: 0 of N` printed rather than an empty list that reads as 'nobody wrote here'. No `normalize` key: the body names no host and no store path, so every byte is deterministic." }, { "id": "sessions-authorized-head", @@ -1234,9 +1232,7 @@ "method": "HEAD", "target": "/api/v1/sessions/alpha-notes", "principal": "wide-reader", - "why": "HEAD keeps every header and sends no body; the head_matches_get relation pins its Content-Length against the GET's.", - "go_only": true, - "go_only_why": "`sessions/` is served by the Go server only - decision 3 of the arcs/sessions plan extends `cmd/cairn-server` and not the oracle. Its golden is recorded from the Go server (`recorded_from: cmd/cairn-server`), a CHANGE DETECTOR rather than an oracle witness; the literal-body contract lives in `internal/report/sessions_test.go`." + "why": "HEAD keeps every header and sends no body; the head_matches_get relation pins its Content-Length against the GET's." }, { "id": "sessions-legacy-token", @@ -1244,9 +1240,7 @@ "method": "GET", "target": "/api/v1/sessions/alpha-notes", "principal": "legacy", - "why": "a bare row is UNRESTRICTED for reads, so it reads a scope no allowlist names - the same rule `recall-legacy-token` pins.", - "go_only": true, - "go_only_why": "`sessions/` is served by the Go server only - decision 3 of the arcs/sessions plan extends `cmd/cairn-server` and not the oracle. Its golden is recorded from the Go server (`recorded_from: cmd/cairn-server`), a CHANGE DETECTOR rather than an oracle witness; the literal-body contract lives in `internal/report/sessions_test.go`." + "why": "a bare row is UNRESTRICTED for reads, so it reads a scope no allowlist names - the same rule `recall-legacy-token` pins." }, { "id": "sessions-refused-scope", @@ -1254,9 +1248,7 @@ "method": "GET", "target": "/api/v1/sessions/alpha-notes", "principal": "narrow-reader", - "why": "alpha-notes EXISTS and this caller may not read it. Authorised by the SAME `rq.visible` recall uses, so it must answer what the absent half below answers - the refused half of the `sessions` pair.", - "go_only": true, - "go_only_why": "`sessions/` is served by the Go server only - decision 3 of the arcs/sessions plan extends `cmd/cairn-server` and not the oracle. Its golden is recorded from the Go server (`recorded_from: cmd/cairn-server`), a CHANGE DETECTOR rather than an oracle witness; the literal-body contract lives in `internal/report/sessions_test.go`." + "why": "alpha-notes EXISTS and this caller may not read it. Authorised by the SAME `rq.visible` recall uses, so it must answer what the absent half below answers - the refused half of the `sessions` pair." }, { "id": "sessions-absent-scope", @@ -1264,9 +1256,7 @@ "method": "GET", "target": "/api/v1/sessions/ghost-void", "principal": "narrow-reader", - "why": "a scope that has never existed, asked by the same caller. The absent half of the pair.", - "go_only": true, - "go_only_why": "`sessions/` is served by the Go server only - decision 3 of the arcs/sessions plan extends `cmd/cairn-server` and not the oracle. Its golden is recorded from the Go server (`recorded_from: cmd/cairn-server`), a CHANGE DETECTOR rather than an oracle witness; the literal-body contract lives in `internal/report/sessions_test.go`." + "why": "a scope that has never existed, asked by the same caller. The absent half of the pair." }, { "id": "sessions-empty-scope", @@ -1274,9 +1264,7 @@ "method": "GET", "target": "/api/v1/sessions/hollow-set", "principal": "wide-reader", - "why": "a directory holding no entry: `scope-empty`, which must read differently from `no-attributed-writes` (entries exist, no trailer) and from `scope-unreadable`.", - "go_only": true, - "go_only_why": "`sessions/` is served by the Go server only - decision 3 of the arcs/sessions plan extends `cmd/cairn-server` and not the oracle. Its golden is recorded from the Go server (`recorded_from: cmd/cairn-server`), a CHANGE DETECTOR rather than an oracle witness; the literal-body contract lives in `internal/report/sessions_test.go`." + "why": "a directory holding no entry: `scope-empty`, which must read differently from `no-attributed-writes` (entries exist, no trailer) and from `scope-unreadable`." }, { "id": "sessions-unreadable-scope", @@ -1284,9 +1272,7 @@ "method": "GET", "target": "/api/v1/sessions/rubble-heap", "principal": "wide-reader", - "why": "every entry file is malformed, so NOTHING was scanned: `scope-unreadable`, X-Store-Exit 3, on a 200. Zero bullets scanned must never read as `no-attributed-writes`.", - "go_only": true, - "go_only_why": "`sessions/` is served by the Go server only - decision 3 of the arcs/sessions plan extends `cmd/cairn-server` and not the oracle. Its golden is recorded from the Go server (`recorded_from: cmd/cairn-server`), a CHANGE DETECTOR rather than an oracle witness; the literal-body contract lives in `internal/report/sessions_test.go`." + "why": "every entry file is malformed, so NOTHING was scanned: `scope-unreadable`, X-Store-Exit 3, on a 200. Zero bullets scanned must never read as `no-attributed-writes`." }, { "id": "sessions-unauthenticated", @@ -1294,9 +1280,7 @@ "method": "GET", "target": "/api/v1/sessions/alpha-notes", "principal": null, - "why": "no Authorization header: the uniform 401, a member of that relation, so the new head cannot grow a distinguishing refusal.", - "go_only": true, - "go_only_why": "`sessions/` is served by the Go server only - decision 3 of the arcs/sessions plan extends `cmd/cairn-server` and not the oracle. Its golden is recorded from the Go server (`recorded_from: cmd/cairn-server`), a CHANGE DETECTOR rather than an oracle witness; the literal-body contract lives in `internal/report/sessions_test.go`." + "why": "no Authorization header: the uniform 401, a member of that relation, so the new head cannot grow a distinguishing refusal." }, { "id": "sessions-arity-too-long", @@ -1304,9 +1288,7 @@ "method": "GET", "target": "/api/v1/sessions/alpha-notes/extra", "principal": "wide-reader", - "why": "the route table names arity 2; a third component does not dispatch and answers the no-route 404.", - "go_only": true, - "go_only_why": "`sessions/` is served by the Go server only - decision 3 of the arcs/sessions plan extends `cmd/cairn-server` and not the oracle. Its golden is recorded from the Go server (`recorded_from: cmd/cairn-server`), a CHANGE DETECTOR rather than an oracle witness; the literal-body contract lives in `internal/report/sessions_test.go`." + "why": "the route table names arity 2; a third component does not dispatch and answers the no-route 404." }, { "id": "arcs-authorized", @@ -1314,9 +1296,7 @@ "method": "GET", "target": "/api/v1/arcs/alpha-notes", "principal": "wide-reader", - "why": "the ordinary listing: gadget-rollout is homed in alpha-notes and DECLARES it, so it is listed `declared`, and its LATER registration (status open) is the one shown - the latest-wins fold over the seeded journal. No `normalize` key: the body names no host and no store path.", - "go_only": true, - "go_only_why": "`arcs/`, `arc//` and `PUT arc//` are served by the Go server only - decision 3 of the arcs/sessions plan extends `cmd/cairn-server` and not the oracle. The golden is recorded from the Go server (`recorded_from: cmd/cairn-server`) over the world's SEEDED arc journal (`run_go.sh` passes it; the oracle is never told), a CHANGE DETECTOR rather than an oracle witness; the literal-body contract lives in `internal/report/arcs_test.go` and `internal/api/arcs_test.go`." + "why": "the ordinary listing: gadget-rollout is homed in alpha-notes and DECLARES it, so it is listed `declared`, and its LATER registration (status open) is the one shown - the latest-wins fold over the seeded journal. No `normalize` key: the body names no host and no store path." }, { "id": "arcs-authorized-head", @@ -1324,9 +1304,7 @@ "method": "HEAD", "target": "/api/v1/arcs/alpha-notes", "principal": "wide-reader", - "why": "HEAD keeps every header and sends no body; head_matches_get pins its Content-Length against the GET's.", - "go_only": true, - "go_only_why": "`arcs/`, `arc//` and `PUT arc//` are served by the Go server only - decision 3 of the arcs/sessions plan extends `cmd/cairn-server` and not the oracle. The golden is recorded from the Go server (`recorded_from: cmd/cairn-server`) over the world's SEEDED arc journal (`run_go.sh` passes it; the oracle is never told), a CHANGE DETECTOR rather than an oracle witness; the literal-body contract lives in `internal/report/arcs_test.go` and `internal/api/arcs_test.go`." + "why": "HEAD keeps every header and sends no body; head_matches_get pins its Content-Length against the GET's." }, { "id": "arcs-declared-elsewhere", @@ -1334,9 +1312,7 @@ "method": "GET", "target": "/api/v1/arcs/beta-notes", "principal": "wide-reader", - "why": "beta-notes is declared by TWO arcs with different homes: gadget-rollout (homed in alpha-notes, open) and widget-fix (homed here, no status - so `unknown`, counted apart from open). Both are visible to this caller.", - "go_only": true, - "go_only_why": "`arcs/`, `arc//` and `PUT arc//` are served by the Go server only - decision 3 of the arcs/sessions plan extends `cmd/cairn-server` and not the oracle. The golden is recorded from the Go server (`recorded_from: cmd/cairn-server`) over the world's SEEDED arc journal (`run_go.sh` passes it; the oracle is never told), a CHANGE DETECTOR rather than an oracle witness; the literal-body contract lives in `internal/report/arcs_test.go` and `internal/api/arcs_test.go`." + "why": "beta-notes is declared by TWO arcs with different homes: gadget-rollout (homed in alpha-notes, open) and widget-fix (homed here, no status - so `unknown`, counted apart from open). Both are visible to this caller." }, { "id": "arcs-hidden-home", @@ -1344,9 +1320,7 @@ "method": "GET", "target": "/api/v1/arcs/beta-notes", "principal": "narrow-reader", - "why": "the SAME scope for a caller who cannot read alpha-notes: gadget-rollout declares beta-notes but is homed in alpha-notes, so it is NOT listed (operator decision Q1) - only widget-fix is. The positive control is `arcs-declared-elsewhere`, where the same arc IS listed.", - "go_only": true, - "go_only_why": "`arcs/`, `arc//` and `PUT arc//` are served by the Go server only - decision 3 of the arcs/sessions plan extends `cmd/cairn-server` and not the oracle. The golden is recorded from the Go server (`recorded_from: cmd/cairn-server`) over the world's SEEDED arc journal (`run_go.sh` passes it; the oracle is never told), a CHANGE DETECTOR rather than an oracle witness; the literal-body contract lives in `internal/report/arcs_test.go` and `internal/api/arcs_test.go`." + "why": "the SAME scope for a caller who cannot read alpha-notes: gadget-rollout declares beta-notes but is homed in alpha-notes, so it is NOT listed (operator decision Q1) - only widget-fix is. The positive control is `arcs-declared-elsewhere`, where the same arc IS listed." }, { "id": "arcs-legacy-token", @@ -1354,9 +1328,7 @@ "method": "GET", "target": "/api/v1/arcs/alpha-notes", "principal": "legacy", - "why": "a bare row reads every enumerated scope, so it may READ arcs; it may not register one (`put-arc-legacy`).", - "go_only": true, - "go_only_why": "`arcs/`, `arc//` and `PUT arc//` are served by the Go server only - decision 3 of the arcs/sessions plan extends `cmd/cairn-server` and not the oracle. The golden is recorded from the Go server (`recorded_from: cmd/cairn-server`) over the world's SEEDED arc journal (`run_go.sh` passes it; the oracle is never told), a CHANGE DETECTOR rather than an oracle witness; the literal-body contract lives in `internal/report/arcs_test.go` and `internal/api/arcs_test.go`." + "why": "a bare row reads every enumerated scope, so it may READ arcs; it may not register one (`put-arc-legacy`)." }, { "id": "arcs-refused-scope", @@ -1364,9 +1336,7 @@ "method": "GET", "target": "/api/v1/arcs/alpha-notes", "principal": "narrow-reader", - "why": "alpha-notes EXISTS and this caller may not read it: authorised by the SAME `rq.visible` recall uses, so it answers what the absent half answers - the refused half of the `arcs` pair.", - "go_only": true, - "go_only_why": "`arcs/`, `arc//` and `PUT arc//` are served by the Go server only - decision 3 of the arcs/sessions plan extends `cmd/cairn-server` and not the oracle. The golden is recorded from the Go server (`recorded_from: cmd/cairn-server`) over the world's SEEDED arc journal (`run_go.sh` passes it; the oracle is never told), a CHANGE DETECTOR rather than an oracle witness; the literal-body contract lives in `internal/report/arcs_test.go` and `internal/api/arcs_test.go`." + "why": "alpha-notes EXISTS and this caller may not read it: authorised by the SAME `rq.visible` recall uses, so it answers what the absent half answers - the refused half of the `arcs` pair." }, { "id": "arcs-absent-scope", @@ -1374,9 +1344,7 @@ "method": "GET", "target": "/api/v1/arcs/ghost-void", "principal": "narrow-reader", - "why": "a scope that has never existed, asked by the same caller. The absent half of the pair.", - "go_only": true, - "go_only_why": "`arcs/`, `arc//` and `PUT arc//` are served by the Go server only - decision 3 of the arcs/sessions plan extends `cmd/cairn-server` and not the oracle. The golden is recorded from the Go server (`recorded_from: cmd/cairn-server`) over the world's SEEDED arc journal (`run_go.sh` passes it; the oracle is never told), a CHANGE DETECTOR rather than an oracle witness; the literal-body contract lives in `internal/report/arcs_test.go` and `internal/api/arcs_test.go`." + "why": "a scope that has never existed, asked by the same caller. The absent half of the pair." }, { "id": "arcs-no-arc", @@ -1384,9 +1352,7 @@ "method": "GET", "target": "/api/v1/arcs/hollow-set", "principal": "wide-reader", - "why": "a readable scope no registered arc declares or wrote in: `no-arc-registered`, which must read differently from `scope-absent` and from `registrations-unconfigured`.", - "go_only": true, - "go_only_why": "`arcs/`, `arc//` and `PUT arc//` are served by the Go server only - decision 3 of the arcs/sessions plan extends `cmd/cairn-server` and not the oracle. The golden is recorded from the Go server (`recorded_from: cmd/cairn-server`) over the world's SEEDED arc journal (`run_go.sh` passes it; the oracle is never told), a CHANGE DETECTOR rather than an oracle witness; the literal-body contract lives in `internal/report/arcs_test.go` and `internal/api/arcs_test.go`." + "why": "a readable scope no registered arc declares or wrote in: `no-arc-registered`, which must read differently from `scope-absent` and from `registrations-unconfigured`." }, { "id": "arcs-unauthenticated", @@ -1394,9 +1360,7 @@ "method": "GET", "target": "/api/v1/arcs/alpha-notes", "principal": null, - "why": "no Authorization header: the uniform 401, a member of that relation.", - "go_only": true, - "go_only_why": "`arcs/`, `arc//` and `PUT arc//` are served by the Go server only - decision 3 of the arcs/sessions plan extends `cmd/cairn-server` and not the oracle. The golden is recorded from the Go server (`recorded_from: cmd/cairn-server`) over the world's SEEDED arc journal (`run_go.sh` passes it; the oracle is never told), a CHANGE DETECTOR rather than an oracle witness; the literal-body contract lives in `internal/report/arcs_test.go` and `internal/api/arcs_test.go`." + "why": "no Authorization header: the uniform 401, a member of that relation." }, { "id": "sources-authorized", @@ -1404,9 +1368,7 @@ "method": "GET", "target": "/api/v1/sources/alpha-notes", "principal": "wide-reader", - "why": "the ordinary read: alpha-notes' LATEST declaration (two sources, in declaration order, the first the primary) supersedes its earlier one-source record - the latest-wins fold on the wire.", - "go_only": true, - "go_only_why": "`sources/` is served by the Go server only - decision 10 of the scope-refs plan extends `cmd/cairn-server` and not the oracle, on the arcs precedent. The golden is recorded from the Go server (`recorded_from: cmd/cairn-server`) over the world's SEEDED sources journal (`run_go.sh` passes it as $CAIRN_SOURCE_JOURNAL; the oracle is never told), a CHANGE DETECTOR rather than an oracle witness; the literal-body contract lives in `internal/api/sources_test.go`, which also pins the two states this one-boot corpus cannot send (unconfigured, and the 503)." + "why": "the ordinary read: alpha-notes' LATEST declaration (two sources, in declaration order, the first the primary) supersedes its earlier one-source record - the latest-wins fold on the wire." }, { "id": "sources-authorized-head", @@ -1414,9 +1376,7 @@ "method": "HEAD", "target": "/api/v1/sources/alpha-notes", "principal": "wide-reader", - "why": "HEAD keeps every header and sends no body; head_matches_get pins its Content-Length against the GET's.", - "go_only": true, - "go_only_why": "`sources/` is served by the Go server only - decision 10 of the scope-refs plan extends `cmd/cairn-server` and not the oracle, on the arcs precedent. The golden is recorded from the Go server (`recorded_from: cmd/cairn-server`) over the world's SEEDED sources journal (`run_go.sh` passes it as $CAIRN_SOURCE_JOURNAL; the oracle is never told), a CHANGE DETECTOR rather than an oracle witness; the literal-body contract lives in `internal/api/sources_test.go`, which also pins the two states this one-boot corpus cannot send (unconfigured, and the 503)." + "why": "HEAD keeps every header and sends no body; head_matches_get pins its Content-Length against the GET's." }, { "id": "sources-undeclared", @@ -1424,9 +1384,7 @@ "method": "GET", "target": "/api/v1/sources/beta-notes", "principal": "narrow-reader", - "why": "beta-notes is readable to this caller and has NO record: `sources=undeclared`, over a journal that exists (`journal=present`). Also the positive control for the narrow reader: it gets a real answer for the scope it may read.", - "go_only": true, - "go_only_why": "`sources/` is served by the Go server only - decision 10 of the scope-refs plan extends `cmd/cairn-server` and not the oracle, on the arcs precedent. The golden is recorded from the Go server (`recorded_from: cmd/cairn-server`) over the world's SEEDED sources journal (`run_go.sh` passes it as $CAIRN_SOURCE_JOURNAL; the oracle is never told), a CHANGE DETECTOR rather than an oracle witness; the literal-body contract lives in `internal/api/sources_test.go`, which also pins the two states this one-boot corpus cannot send (unconfigured, and the 503)." + "why": "beta-notes is readable to this caller and has NO record: `sources=undeclared`, over a journal that exists (`journal=present`). Also the positive control for the narrow reader: it gets a real answer for the scope it may read." }, { "id": "sources-refused-scope", @@ -1434,9 +1392,7 @@ "method": "GET", "target": "/api/v1/sources/alpha-notes", "principal": "narrow-reader", - "why": "alpha-notes EXISTS, carries a declaration, and this caller may not read it: it answers what the absent half answers - the refused half of the `sources` pair.", - "go_only": true, - "go_only_why": "`sources/` is served by the Go server only - decision 10 of the scope-refs plan extends `cmd/cairn-server` and not the oracle, on the arcs precedent. The golden is recorded from the Go server (`recorded_from: cmd/cairn-server`) over the world's SEEDED sources journal (`run_go.sh` passes it as $CAIRN_SOURCE_JOURNAL; the oracle is never told), a CHANGE DETECTOR rather than an oracle witness; the literal-body contract lives in `internal/api/sources_test.go`, which also pins the two states this one-boot corpus cannot send (unconfigured, and the 503)." + "why": "alpha-notes EXISTS, carries a declaration, and this caller may not read it: it answers what the absent half answers - the refused half of the `sources` pair." }, { "id": "sources-absent-scope", @@ -1444,9 +1400,7 @@ "method": "GET", "target": "/api/v1/sources/ghost-void", "principal": "narrow-reader", - "why": "a scope that has never existed, asked by the same caller. The absent half of the pair.", - "go_only": true, - "go_only_why": "`sources/` is served by the Go server only - decision 10 of the scope-refs plan extends `cmd/cairn-server` and not the oracle, on the arcs precedent. The golden is recorded from the Go server (`recorded_from: cmd/cairn-server`) over the world's SEEDED sources journal (`run_go.sh` passes it as $CAIRN_SOURCE_JOURNAL; the oracle is never told), a CHANGE DETECTOR rather than an oracle witness; the literal-body contract lives in `internal/api/sources_test.go`, which also pins the two states this one-boot corpus cannot send (unconfigured, and the 503)." + "why": "a scope that has never existed, asked by the same caller. The absent half of the pair." }, { "id": "sources-unauthenticated", @@ -1454,9 +1408,7 @@ "method": "GET", "target": "/api/v1/sources/alpha-notes", "principal": null, - "why": "no Authorization header: the uniform 401, a member of that relation.", - "go_only": true, - "go_only_why": "`sources/` is served by the Go server only - decision 10 of the scope-refs plan extends `cmd/cairn-server` and not the oracle, on the arcs precedent. The golden is recorded from the Go server (`recorded_from: cmd/cairn-server`) over the world's SEEDED sources journal (`run_go.sh` passes it as $CAIRN_SOURCE_JOURNAL; the oracle is never told), a CHANGE DETECTOR rather than an oracle witness; the literal-body contract lives in `internal/api/sources_test.go`, which also pins the two states this one-boot corpus cannot send (unconfigured, and the 503)." + "why": "no Authorization header: the uniform 401, a member of that relation." }, { "id": "whoami-authorized", @@ -1464,9 +1416,7 @@ "method": "GET", "target": "/api/v1/whoami", "principal": "wide-reader", - "why": "the ordinary self-view of a mapped token row: `not-federated`, no groups, and the six scopes it reads, as names, sorted - exactly the set `recall` would answer for.", - "go_only": true, - "go_only_why": "`whoami` is served by the Go server only, on the arcs/sources precedent: it reports the caller's own authority from the control plane's federation report and read set, and the oracle has neither. The golden is recorded from the Go server (`recorded_from: cmd/cairn-server`), a CHANGE DETECTOR rather than an oracle witness; this one-boot corpus runs on a token file, so it can send only NON-federated callers. The federated bodies (`mapped`, `groups-unmapped`, `no-groups`) are pinned as literal bytes in `internal/api/whoami_test.go`." + "why": "the ordinary self-view of a mapped token row: `not-federated`, no groups, and the six scopes it reads, as names, sorted - exactly the set `recall` would answer for." }, { "id": "whoami-authorized-head", @@ -1474,9 +1424,7 @@ "method": "HEAD", "target": "/api/v1/whoami", "principal": "wide-reader", - "why": "HEAD keeps every header and sends no body; head_matches_get pins its Content-Length against the GET's.", - "go_only": true, - "go_only_why": "`whoami` is served by the Go server only, on the arcs/sources precedent: it reports the caller's own authority from the control plane's federation report and read set, and the oracle has neither. The golden is recorded from the Go server (`recorded_from: cmd/cairn-server`), a CHANGE DETECTOR rather than an oracle witness; this one-boot corpus runs on a token file, so it can send only NON-federated callers. The federated bodies (`mapped`, `groups-unmapped`, `no-groups`) are pinned as literal bytes in `internal/api/whoami_test.go`." + "why": "HEAD keeps every header and sends no body; head_matches_get pins its Content-Length against the GET's." }, { "id": "whoami-narrow-reader", @@ -1484,9 +1432,7 @@ "method": "GET", "target": "/api/v1/whoami", "principal": "narrow-reader", - "why": "a caller that reads ONE scope sees exactly that one: alpha-notes exists and is absent from its view, so the route is a self-view and not an enumeration of the store.", - "go_only": true, - "go_only_why": "`whoami` is served by the Go server only, on the arcs/sources precedent: it reports the caller's own authority from the control plane's federation report and read set, and the oracle has neither. The golden is recorded from the Go server (`recorded_from: cmd/cairn-server`), a CHANGE DETECTOR rather than an oracle witness; this one-boot corpus runs on a token file, so it can send only NON-federated callers. The federated bodies (`mapped`, `groups-unmapped`, `no-groups`) are pinned as literal bytes in `internal/api/whoami_test.go`." + "why": "a caller that reads ONE scope sees exactly that one: alpha-notes exists and is absent from its view, so the route is a self-view and not an enumeration of the store." }, { "id": "whoami-legacy-token", @@ -1494,9 +1440,7 @@ "method": "GET", "target": "/api/v1/whoami", "principal": "legacy", - "why": "a bare row is unrestricted for reads, and its view ENUMERATES the scopes the model holds rather than claiming a wildcard - the same set its reads are narrowed with.", - "go_only": true, - "go_only_why": "`whoami` is served by the Go server only, on the arcs/sources precedent: it reports the caller's own authority from the control plane's federation report and read set, and the oracle has neither. The golden is recorded from the Go server (`recorded_from: cmd/cairn-server`), a CHANGE DETECTOR rather than an oracle witness; this one-boot corpus runs on a token file, so it can send only NON-federated callers. The federated bodies (`mapped`, `groups-unmapped`, `no-groups`) are pinned as literal bytes in `internal/api/whoami_test.go`." + "why": "a bare row is unrestricted for reads, and its view ENUMERATES the scopes the model holds rather than claiming a wildcard - the same set its reads are narrowed with." }, { "id": "whoami-unauthenticated", @@ -1504,9 +1448,7 @@ "method": "GET", "target": "/api/v1/whoami", "principal": null, - "why": "no Authorization header: the uniform 401, a member of that relation. The route adds no refusal of its own.", - "go_only": true, - "go_only_why": "`whoami` is served by the Go server only, on the arcs/sources precedent: it reports the caller's own authority from the control plane's federation report and read set, and the oracle has neither. The golden is recorded from the Go server (`recorded_from: cmd/cairn-server`), a CHANGE DETECTOR rather than an oracle witness; this one-boot corpus runs on a token file, so it can send only NON-federated callers. The federated bodies (`mapped`, `groups-unmapped`, `no-groups`) are pinned as literal bytes in `internal/api/whoami_test.go`." + "why": "no Authorization header: the uniform 401, a member of that relation. The route adds no refusal of its own." }, { "id": "arcs-check-all-scopes", @@ -1514,9 +1456,7 @@ "method": "GET", "target": "/api/v1/arcs/alpha-notes?check=1&all_scopes=1", "principal": "wide-reader", - "why": "the orphan check over every arc this caller can see: both seeded arcs are homed in readable scopes that exist, so the answer is `arcs-check-clean` with `X-Store-Exit: 0` - doctor's legend (operator decision Q5) - and the coverage lines say how many members and writing sessions it could join.", - "go_only": true, - "go_only_why": "`arcs/?check=1` is the arc orphan check (S5 of the arcs/sessions plan), a mode of the Go-only `arcs` head - decision 3 extends `cmd/cairn-server` and not the oracle. The golden is recorded from the Go server (`recorded_from: cmd/cairn-server`) over the world's SEEDED arc journal, a CHANGE DETECTOR rather than an oracle witness; the literal-body contract lives in `internal/report/arcscheck_test.go` and `internal/api/arcs_test.go`." + "why": "the orphan check over every arc this caller can see: both seeded arcs are homed in readable scopes that exist, so the answer is `arcs-check-clean` with `X-Store-Exit: 0` - doctor's legend (operator decision Q5) - and the coverage lines say how many members and writing sessions it could join." }, { "id": "arcs-check-scoped", @@ -1524,9 +1464,7 @@ "method": "GET", "target": "/api/v1/arcs/beta-notes?check=1", "principal": "narrow-reader", - "why": "without `all_scopes` only arcs HOMED in the path scope are checked: widget-fix, homed in beta-notes. gadget-rollout DECLARES beta-notes but is homed in alpha-notes, which this caller cannot read, so it is neither checked nor named.", - "go_only": true, - "go_only_why": "`arcs/?check=1` is the arc orphan check (S5 of the arcs/sessions plan), a mode of the Go-only `arcs` head - decision 3 extends `cmd/cairn-server` and not the oracle. The golden is recorded from the Go server (`recorded_from: cmd/cairn-server`) over the world's SEEDED arc journal, a CHANGE DETECTOR rather than an oracle witness; the literal-body contract lives in `internal/report/arcscheck_test.go` and `internal/api/arcs_test.go`." + "why": "without `all_scopes` only arcs HOMED in the path scope are checked: widget-fix, homed in beta-notes. gadget-rollout DECLARES beta-notes but is homed in alpha-notes, which this caller cannot read, so it is neither checked nor named." }, { "id": "arcs-check-refused-scope", @@ -1534,9 +1472,7 @@ "method": "GET", "target": "/api/v1/arcs/alpha-notes?check=1", "principal": "narrow-reader", - "why": "alpha-notes EXISTS, holds a registered arc, and this caller may not read it: the check must answer what the absent half answers - the refused half of the `arcs-check` pair.", - "go_only": true, - "go_only_why": "`arcs/?check=1` is the arc orphan check (S5 of the arcs/sessions plan), a mode of the Go-only `arcs` head - decision 3 extends `cmd/cairn-server` and not the oracle. The golden is recorded from the Go server (`recorded_from: cmd/cairn-server`) over the world's SEEDED arc journal, a CHANGE DETECTOR rather than an oracle witness; the literal-body contract lives in `internal/report/arcscheck_test.go` and `internal/api/arcs_test.go`." + "why": "alpha-notes EXISTS, holds a registered arc, and this caller may not read it: the check must answer what the absent half answers - the refused half of the `arcs-check` pair." }, { "id": "arcs-check-absent-scope", @@ -1544,9 +1480,7 @@ "method": "GET", "target": "/api/v1/arcs/ghost-void?check=1", "principal": "narrow-reader", - "why": "a scope that has never existed, checked by the same caller. The absent half of the pair.", - "go_only": true, - "go_only_why": "`arcs/?check=1` is the arc orphan check (S5 of the arcs/sessions plan), a mode of the Go-only `arcs` head - decision 3 extends `cmd/cairn-server` and not the oracle. The golden is recorded from the Go server (`recorded_from: cmd/cairn-server`) over the world's SEEDED arc journal, a CHANGE DETECTOR rather than an oracle witness; the literal-body contract lives in `internal/report/arcscheck_test.go` and `internal/api/arcs_test.go`." + "why": "a scope that has never existed, checked by the same caller. The absent half of the pair." }, { "id": "arc-authorized", @@ -1554,9 +1488,7 @@ "method": "GET", "target": "/api/v1/arc/alpha-notes/gadget-rollout", "principal": "wide-reader", - "why": "one arc, shown: its LATEST registration, its tooling coverage, its declared scopes narrowed to this caller, and its members each with the readable scopes they wrote in (none: the world's bullets carry no trailer).", - "go_only": true, - "go_only_why": "`arcs/`, `arc//` and `PUT arc//` are served by the Go server only - decision 3 of the arcs/sessions plan extends `cmd/cairn-server` and not the oracle. The golden is recorded from the Go server (`recorded_from: cmd/cairn-server`) over the world's SEEDED arc journal (`run_go.sh` passes it; the oracle is never told), a CHANGE DETECTOR rather than an oracle witness; the literal-body contract lives in `internal/report/arcs_test.go` and `internal/api/arcs_test.go`." + "why": "one arc, shown: its LATEST registration, its tooling coverage, its declared scopes narrowed to this caller, and its members each with the readable scopes they wrote in (none: the world's bullets carry no trailer)." }, { "id": "arc-authorized-head", @@ -1564,9 +1496,7 @@ "method": "HEAD", "target": "/api/v1/arc/alpha-notes/gadget-rollout", "principal": "wide-reader", - "why": "HEAD keeps every header and sends no body; head_matches_get pins its Content-Length against the GET's.", - "go_only": true, - "go_only_why": "`arcs/`, `arc//` and `PUT arc//` are served by the Go server only - decision 3 of the arcs/sessions plan extends `cmd/cairn-server` and not the oracle. The golden is recorded from the Go server (`recorded_from: cmd/cairn-server`) over the world's SEEDED arc journal (`run_go.sh` passes it; the oracle is never told), a CHANGE DETECTOR rather than an oracle witness; the literal-body contract lives in `internal/report/arcs_test.go` and `internal/api/arcs_test.go`." + "why": "HEAD keeps every header and sends no body; head_matches_get pins its Content-Length against the GET's." }, { "id": "arc-unregistered-slug", @@ -1574,9 +1504,7 @@ "method": "GET", "target": "/api/v1/arc/alpha-notes/never-filed", "principal": "wide-reader", - "why": "a readable home and a slug nobody registered: `arc-unregistered`, naming neither the home nor the slug.", - "go_only": true, - "go_only_why": "`arcs/`, `arc//` and `PUT arc//` are served by the Go server only - decision 3 of the arcs/sessions plan extends `cmd/cairn-server` and not the oracle. The golden is recorded from the Go server (`recorded_from: cmd/cairn-server`) over the world's SEEDED arc journal (`run_go.sh` passes it; the oracle is never told), a CHANGE DETECTOR rather than an oracle witness; the literal-body contract lives in `internal/report/arcs_test.go` and `internal/api/arcs_test.go`." + "why": "a readable home and a slug nobody registered: `arc-unregistered`, naming neither the home nor the slug." }, { "id": "arc-refused-home", @@ -1584,9 +1512,7 @@ "method": "GET", "target": "/api/v1/arc/alpha-notes/gadget-rollout", "principal": "narrow-reader", - "why": "a REGISTERED arc homed in a scope this caller may not read answers exactly what a never-registered key under an absent home answers - the refused half of the `arc` pair (Q1). X-Store-Revision is gated by the same visible set, so alpha-notes' .git/HEAD cannot tell the two apart.", - "go_only": true, - "go_only_why": "`arcs/`, `arc//` and `PUT arc//` are served by the Go server only - decision 3 of the arcs/sessions plan extends `cmd/cairn-server` and not the oracle. The golden is recorded from the Go server (`recorded_from: cmd/cairn-server`) over the world's SEEDED arc journal (`run_go.sh` passes it; the oracle is never told), a CHANGE DETECTOR rather than an oracle witness; the literal-body contract lives in `internal/report/arcs_test.go` and `internal/api/arcs_test.go`." + "why": "a REGISTERED arc homed in a scope this caller may not read answers exactly what a never-registered key under an absent home answers - the refused half of the `arc` pair (Q1). X-Store-Revision is gated by the same visible set, so alpha-notes' .git/HEAD cannot tell the two apart." }, { "id": "arc-absent-home", @@ -1594,9 +1520,7 @@ "method": "GET", "target": "/api/v1/arc/ghost-void/gadget-rollout", "principal": "narrow-reader", - "why": "the same slug under a home that has never existed, asked by the same caller. The absent half.", - "go_only": true, - "go_only_why": "`arcs/`, `arc//` and `PUT arc//` are served by the Go server only - decision 3 of the arcs/sessions plan extends `cmd/cairn-server` and not the oracle. The golden is recorded from the Go server (`recorded_from: cmd/cairn-server`) over the world's SEEDED arc journal (`run_go.sh` passes it; the oracle is never told), a CHANGE DETECTOR rather than an oracle witness; the literal-body contract lives in `internal/report/arcs_test.go` and `internal/api/arcs_test.go`." + "why": "the same slug under a home that has never existed, asked by the same caller. The absent half." }, { "id": "arc-unauthenticated", @@ -1604,9 +1528,7 @@ "method": "GET", "target": "/api/v1/arc/alpha-notes/gadget-rollout", "principal": null, - "why": "no Authorization header: the uniform 401.", - "go_only": true, - "go_only_why": "`arcs/`, `arc//` and `PUT arc//` are served by the Go server only - decision 3 of the arcs/sessions plan extends `cmd/cairn-server` and not the oracle. The golden is recorded from the Go server (`recorded_from: cmd/cairn-server`) over the world's SEEDED arc journal (`run_go.sh` passes it; the oracle is never told), a CHANGE DETECTOR rather than an oracle witness; the literal-body contract lives in `internal/report/arcs_test.go` and `internal/api/arcs_test.go`." + "why": "no Authorization header: the uniform 401." }, { "id": "arc-arity-too-short", @@ -1614,9 +1536,7 @@ "method": "GET", "target": "/api/v1/arc/alpha-notes", "principal": "wide-reader", - "why": "the route table names arity 3; two components do not dispatch and answer the no-route 404.", - "go_only": true, - "go_only_why": "`arcs/`, `arc//` and `PUT arc//` are served by the Go server only - decision 3 of the arcs/sessions plan extends `cmd/cairn-server` and not the oracle. The golden is recorded from the Go server (`recorded_from: cmd/cairn-server`) over the world's SEEDED arc journal (`run_go.sh` passes it; the oracle is never told), a CHANGE DETECTOR rather than an oracle witness; the literal-body contract lives in `internal/report/arcs_test.go` and `internal/api/arcs_test.go`." + "why": "the route table names arity 3; two components do not dispatch and answer the no-route 404." }, { "id": "post-bullets-duplicate", @@ -1835,9 +1755,7 @@ ] } }, - "why": "a new registration by a caller holding write on the home scope AND the declared one: 200 `arc-registered`. The member whose id `write.SessionComponent` refuses is NOT stored and is COUNTED (`unjoinable=1`).", - "go_only": true, - "go_only_why": "`arcs/`, `arc//` and `PUT arc//` are served by the Go server only - decision 3 of the arcs/sessions plan extends `cmd/cairn-server` and not the oracle. The golden is recorded from the Go server (`recorded_from: cmd/cairn-server`) over the world's SEEDED arc journal (`run_go.sh` passes it; the oracle is never told), a CHANGE DETECTOR rather than an oracle witness; the literal-body contract lives in `internal/report/arcs_test.go` and `internal/api/arcs_test.go`." + "why": "a new registration by a caller holding write on the home scope AND the declared one: 200 `arc-registered`. The member whose id `write.SessionComponent` refuses is NOT stored and is COUNTED (`unjoinable=1`)." }, { "id": "put-arc-unchanged", @@ -1872,9 +1790,7 @@ ] } }, - "why": "the byte-identical retry: 200 `arc-unchanged`, and nothing appended - a retried PUT after a timeout cannot grow the append-only journal.", - "go_only": true, - "go_only_why": "`arcs/`, `arc//` and `PUT arc//` are served by the Go server only - decision 3 of the arcs/sessions plan extends `cmd/cairn-server` and not the oracle. The golden is recorded from the Go server (`recorded_from: cmd/cairn-server`) over the world's SEEDED arc journal (`run_go.sh` passes it; the oracle is never told), a CHANGE DETECTOR rather than an oracle witness; the literal-body contract lives in `internal/report/arcs_test.go` and `internal/api/arcs_test.go`." + "why": "the byte-identical retry: 200 `arc-unchanged`, and nothing appended - a retried PUT after a timeout cannot grow the append-only journal." }, { "id": "put-arc-malformed", @@ -1888,9 +1804,7 @@ "status": "maybe" } }, - "why": "a status outside open|closed|unknown is a 400 naming the field; nothing is written.", - "go_only": true, - "go_only_why": "`arcs/`, `arc//` and `PUT arc//` are served by the Go server only - decision 3 of the arcs/sessions plan extends `cmd/cairn-server` and not the oracle. The golden is recorded from the Go server (`recorded_from: cmd/cairn-server`) over the world's SEEDED arc journal (`run_go.sh` passes it; the oracle is never told), a CHANGE DETECTOR rather than an oracle witness; the literal-body contract lives in `internal/report/arcs_test.go` and `internal/api/arcs_test.go`." + "why": "a status outside open|closed|unknown is a 400 naming the field; nothing is written." }, { "id": "put-arc-refused-declared", @@ -1906,9 +1820,7 @@ ] } }, - "why": "narrow-reader may write beta-notes but NOT alpha-notes: declaring alpha-notes answers the uniform write 404 and nothing is written - the refused half of the `put-arc` pair.", - "go_only": true, - "go_only_why": "`arcs/`, `arc//` and `PUT arc//` are served by the Go server only - decision 3 of the arcs/sessions plan extends `cmd/cairn-server` and not the oracle. The golden is recorded from the Go server (`recorded_from: cmd/cairn-server`) over the world's SEEDED arc journal (`run_go.sh` passes it; the oracle is never told), a CHANGE DETECTOR rather than an oracle witness; the literal-body contract lives in `internal/report/arcs_test.go` and `internal/api/arcs_test.go`." + "why": "narrow-reader may write beta-notes but NOT alpha-notes: declaring alpha-notes answers the uniform write 404 and nothing is written - the refused half of the `put-arc` pair." }, { "id": "put-arc-refused-home", @@ -1921,9 +1833,7 @@ "schema": 1 } }, - "why": "narrow-reader may write beta-notes and NOT alpha-notes, so registering an arc HOMED in alpha-notes answers the uniform write 404 and nothing is written - the refused half of the `put-arc` pair (the home scope is always declared, so it needs write there too).", - "go_only": true, - "go_only_why": "`arcs/`, `arc//` and `PUT arc//` are served by the Go server only - decision 3 of the arcs/sessions plan extends `cmd/cairn-server` and not the oracle. The golden is recorded from the Go server (`recorded_from: cmd/cairn-server`) over the world's SEEDED arc journal (`run_go.sh` passes it; the oracle is never told), a CHANGE DETECTOR rather than an oracle witness; the literal-body contract lives in `internal/report/arcs_test.go` and `internal/api/arcs_test.go`." + "why": "narrow-reader may write beta-notes and NOT alpha-notes, so registering an arc HOMED in alpha-notes answers the uniform write 404 and nothing is written - the refused half of the `put-arc` pair (the home scope is always declared, so it needs write there too)." }, { "id": "put-arc-absent-home", @@ -1936,9 +1846,7 @@ "schema": 1 } }, - "why": "the same caller registering under a HOME scope that has never existed: the absent half of the `put-arc` pair - byte-identical to `put-arc-refused-home`.", - "go_only": true, - "go_only_why": "`arcs/`, `arc//` and `PUT arc//` are served by the Go server only - decision 3 of the arcs/sessions plan extends `cmd/cairn-server` and not the oracle. The golden is recorded from the Go server (`recorded_from: cmd/cairn-server`) over the world's SEEDED arc journal (`run_go.sh` passes it; the oracle is never told), a CHANGE DETECTOR rather than an oracle witness; the literal-body contract lives in `internal/report/arcs_test.go` and `internal/api/arcs_test.go`." + "why": "the same caller registering under a HOME scope that has never existed: the absent half of the `put-arc` pair - byte-identical to `put-arc-refused-home`." }, { "id": "put-arc-legacy", @@ -1951,9 +1859,7 @@ "schema": 1 } }, - "why": "a bare row holds the write verb nowhere: the existing credential-level 403, before any scope is named.", - "go_only": true, - "go_only_why": "`arcs/`, `arc//` and `PUT arc//` are served by the Go server only - decision 3 of the arcs/sessions plan extends `cmd/cairn-server` and not the oracle. The golden is recorded from the Go server (`recorded_from: cmd/cairn-server`) over the world's SEEDED arc journal (`run_go.sh` passes it; the oracle is never told), a CHANGE DETECTOR rather than an oracle witness; the literal-body contract lives in `internal/report/arcs_test.go` and `internal/api/arcs_test.go`." + "why": "a bare row holds the write verb nowhere: the existing credential-level 403, before any scope is named." }, { "id": "put-arc-unauthenticated", @@ -1966,9 +1872,7 @@ "schema": 1 } }, - "why": "no Authorization header on a write: the uniform 401.", - "go_only": true, - "go_only_why": "`arcs/`, `arc//` and `PUT arc//` are served by the Go server only - decision 3 of the arcs/sessions plan extends `cmd/cairn-server` and not the oracle. The golden is recorded from the Go server (`recorded_from: cmd/cairn-server`) over the world's SEEDED arc journal (`run_go.sh` passes it; the oracle is never told), a CHANGE DETECTOR rather than an oracle witness; the literal-body contract lives in `internal/report/arcs_test.go` and `internal/api/arcs_test.go`." + "why": "no Authorization header on a write: the uniform 401." } ], "relations": { diff --git a/tests/conformance/run_go.sh b/tests/conformance/run_go.sh index b3da68d0..72c944ee 100755 --- a/tests/conformance/run_go.sh +++ b/tests/conformance/run_go.sh @@ -2,7 +2,7 @@ # Replay the conformance corpus against the GO server. # # 🔴 THE SERVER UNDER TEST MUST BE CONFIGURED THE WAY THE GOLDENS WERE RECORDED, and -# that configuration is `oracle.ORACLE_ENV` — not a guess made here. This script asks +# that configuration is `fixture.SERVER_ENV` — not a guess made here. This script asks # `suite.py build-store` for the store, the token file AND the env, and exports what it # is told rather than restating it, because a second copy of that table is a second # thing that can drift from the goldens. @@ -14,30 +14,28 @@ # of which the limiter counts, over a production default of five per minute. # # usage: tests/conformance/run_go.sh [extra suite.py run arguments] -# tests/conformance/run_go.sh record-go-only +# tests/conformance/run_go.sh record ... # -# 🔴 `record-go-only` IS THE ONE WAY A `go_only` GOLDEN IS WRITTEN. The oracle's -# `suite.py generate` records from `server/server.py`, which serves no Go-only route, so -# those rows' goldens are recorded from the Go server this script builds and are stamped -# `recorded_from: cmd/cairn-server` — CHANGE DETECTORS, not oracle witnesses. It boots the -# server exactly as a `run` does, so the goldens are recorded under the configuration they -# are replayed under. See `suite.record_go_only` for what makes it refuse. +# 🔴 `record` IS THE ONE WAY A GOLDEN IS WRITTEN NOW. The corpus recorded from the retired +# Python oracle is FROZEN (`tests/conformance/README.md`); a NEW row's golden is recorded +# from the Go server this script builds, stamped `recorded_from: cmd/cairn-server` — a +# CHANGE DETECTOR until a human has reviewed it, never an oracle witness. It boots the +# server exactly as a `run` does, so the golden is recorded under the configuration it is +# replayed under. See `suite.record` for what makes it refuse. set -euo pipefail command="run" -if [[ "${1:-}" == "record-go-only" ]]; then - command="record-go-only" +if [[ "${1:-}" == "record" ]]; then + command="record" shift fi -# 🔴 `CDPATH= cd --`, WHICH IS WHAT THE OTHER TWO SCRIPTS IN THIS REPO ALREADY DO -# (`server/build-push.sh`, `server/verify-byte-identity.sh`). A plain `cd ` +# 🔴 `CDPATH= cd --`. A plain `cd ` # PRINTS the resolved directory whenever it reached it through `CDPATH` — so with # `CDPATH` exported (`.` as its first entry is a common spelling) this command # substitution captured the path TWICE, `$repo` became `"\n"`, and the # build failed with `go: chdir \n: no such file or directory`. Measured in -# an environment with `CDPATH=.:…` set; the failure is invisible in one without it, -# which is why this script was the last of the three to be hardened. +# an environment with `CDPATH=.:…` set; the failure is invisible in one without it. repo="$(CDPATH= cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd)" work="$(mktemp -d "${TMPDIR:-/tmp}/cairn-go-conformance-XXXXXX")" trap 'rm -rf "$work"' EXIT @@ -45,14 +43,14 @@ trap 'rm -rf "$work"' EXIT binary="$work/cairn-server" go build -C "$repo" -o "$binary" ./cmd/cairn-server -# `build-store` prints `store=`, `token-file=` and `env:` — the same three facts the -# generator uses. Parsed rather than reinvented. +# `build-store` prints `store=`, `token-file=` and `env:` — the facts the frozen corpus +# was recorded under. Parsed rather than reinvented. declaration="$(python3 "$repo/tests/conformance/suite.py" build-store "$work/world")" store="$(sed -n 's/^store=//p' <<<"$declaration")" tokens="$(sed -n 's/^token-file=//p' <<<"$declaration")" -# The seeded arc-registry journal, OUTSIDE the store tree (the server refuses one inside it). Only -# this script passes it: the oracle serves no arc route, and the `go_only` arc rows are recorded -# (`record-go-only`) and replayed against a server holding exactly the world's seeded records. +# The seeded arc-registry journal, OUTSIDE the store tree (the server refuses one inside it). The +# arc rows' goldens were recorded and are replayed against a server holding exactly the world's +# seeded records. arc_journal="$(sed -n 's/^arc-journal=//p' <<<"$declaration")" # The seeded code-sources journal, the same arrangement — but handed over as the ENVIRONMENT # variable the pod reads ($CAIRN_SOURCE_JOURNAL has no flag, by decision), so it rides `env`. @@ -85,7 +83,7 @@ done set +e python3 "$repo/tests/conformance/suite.py" "$command" \ - --base-url "http://127.0.0.1:$port" --token-file "$tokens" "$@" + --base-url "http://127.0.0.1:$port" --token-file "$tokens" --server-binary "$binary" "$@" rc=$? set -e diff --git a/tests/conformance/suite.py b/tests/conformance/suite.py index f57df003..a9901361 100644 --- a/tests/conformance/suite.py +++ b/tests/conformance/suite.py @@ -1,19 +1,20 @@ #!/usr/bin/env python3 -"""The HTTP conformance suite: generate the goldens, or replay them. +"""The HTTP conformance suite: replay the goldens against a running Go server. - python3 tests/conformance/suite.py generate # re-record every golden - python3 tests/conformance/suite.py run # replay against the oracle - python3 tests/conformance/suite.py run --base-url http://host:8102 \\ - --token-file /path/to/tokens - python3 tests/conformance/suite.py normalizations # print the declared table + tests/conformance/run_go.sh # build, boot, replay (the gate) + tests/conformance/run_go.sh record ... # record NEW goldens from Go + python3 tests/conformance/suite.py normalizations # print the declared table python3 tests/conformance/suite.py build-store DIR # materialise the world -🔴 `generate` IS THE ONLY WAY AN ORACLE GOLDEN IS EVER WRITTEN, and -`record-go-only` (via `run_go.sh record-go-only`) the only way a `go_only` one is — -stamped `recorded_from: cmd/cairn-server`, a change detector rather than a contract -witness (see `record_go_only`). There is no flag that edits one, and `read_golden` -refuses a file whose recorded body does not hash to its recorded digest — a -hand-edited golden is a golden that asserts what somebody believed. +🔴 THE CORPUS IS FROZEN AT THE RETIRED ORACLE, AND `record` IS THE ONLY WAY A GOLDEN +IS EVER WRITTEN NOW. The goldens with no `recorded_from` stamp were recorded from the +Python reference server before it was deleted (`README.md`, "The frozen corpus"); none +of them can be re-recorded, because re-recording from the Go server would certify Go +against itself. `record` writes a golden only for a row that has NONE, stamps it +`recorded_from: cmd/cairn-server`, and refuses to overwrite any existing golden. There +is no flag that edits one, and `read_golden` refuses a file whose recorded body does +not hash to its recorded digest — a hand-edited golden is a golden that asserts what +somebody believed. 🔴 `run` MAKES FIVE KINDS OF CLAIM, AND THREE OF THEM NO GOLDEN FILE CAN HOLD: @@ -34,9 +35,9 @@ and the store path), so neither can live in a golden; they can still be compared to each other. -`generate` checks 3, 4 and 5 as well, and refuses to record a corpus that -violates any of them. Otherwise the first divergence would be baked in and the -suite would then defend it. +`record` checks 3, 4 and 5 as well, and refuses to record while the server violates +any of them. Otherwise the first divergence would be baked in and the suite would +then defend it. """ from __future__ import annotations @@ -47,7 +48,6 @@ import json import socket import sys -import tempfile from dataclasses import dataclass from pathlib import Path from typing import Any @@ -57,7 +57,7 @@ __package__ = "conformance" from . import cases as cases_mod # noqa: E402 -from . import oracle, wire # noqa: E402 +from . import fixture, wire # noqa: E402 SUITE_DIR = Path(__file__).resolve().parent GOLDEN_DIR = SUITE_DIR / "golden" @@ -75,9 +75,9 @@ class Outcome: assertions: int = 0 failures: list[str] = None # type: ignore[assignment] lines: list[str] = None # type: ignore[assignment] - #: Cases NOT compared on this run because they are marked `oracle_only` and the - #: server under test is not the oracle, or marked `go_only` and it IS (see - #: `skipped_on`). 🔴 REPORTED BY ID IN THE SUMMARY AND + #: Cases NOT compared on this run because they are marked `oracle_only` — frozen + #: records of the retired oracle's own shape (see `skipped_on`). 🔴 REPORTED BY ID + #: IN THE SUMMARY AND #: NAMED WITH ITS REASON ON ITS OWN LINE, because a skip nobody can see is #: indistinguishable from a pass — which is the whole failure mode this suite is #: built against, arriving through the one mechanism that is allowed to skip. @@ -189,7 +189,7 @@ def check_declared_normalizations( if case.id in skipped: # The case is not being compared at all, so a normalization that did not # fire on it carries no licence to differ — there is nothing left to - # widen. Asserting here would turn every oracle-specific row into a + # widen. Asserting here would turn every frozen oracle-specific row into a # failure about a field nobody is reading. continue _resp, fired = answers[case.id] @@ -209,33 +209,18 @@ def check_declared_normalizations( # --------------------------------------------------------------------------- -def skip_label(corpus: cases_mod.Corpus, case_id: str) -> str: - """The word a SKIP line carries: which of the two marks excused this row. +def skipped_on(corpus: cases_mod.Corpus) -> set[str]: + """The ids NOT compared on any run: the rows marked `oracle_only`. - Two marks, two opposite directions, so the line has to say which — a reader - counting `oracle-specific` skips against a Go run must not find a go-only row - folded into that number. + Each is a FROZEN record of an answer that was the retired oracle's own shape + (`cases.Case.oracle_only`). The server that could reproduce it is gone, so the row is + skipped — by id, with its reason, counted — and never silently. ⚠ It is never dropped + from the REQUESTS — see `run`: its request still reaches the server, so a crash it + provokes is still seen. """ - return "go-only" if corpus.by_id(case_id).go_only else "oracle-specific" - - -def skipped_on(corpus: cases_mod.Corpus, *, server_is_oracle: bool) -> set[str]: - """The ids NOT compared against this server. 🔴 THE TWO MARKS ARE MIRRORS. - - Against the ORACLE, a `go_only` row has nothing to answer but the no-route 404, - so it is skipped; every `oracle_only` row is asserted. Against anything else - (the Go server), every `go_only` row is asserted and every `oracle_only` row is - skipped. ⚠ Neither set is ever dropped from the REQUESTS — see `run`. - """ - if server_is_oracle: - return {c.id for c in corpus.cases if c.go_only} return {c.id for c in corpus.cases if c.oracle_only} -def _why(case: cases_mod.Case) -> str: - return case.go_only_why if case.go_only else case.oracle_only_why - - # --------------------------------------------------------------------------- # The relational assertions # --------------------------------------------------------------------------- @@ -298,14 +283,14 @@ def check_uniform_401( # row's own `oracle_only_why` has to say where that is covered instead. outcome.line( f"SKIP relation uniform-401 {case_id} " - f"({skip_label(corpus, case_id)}; the relation is asserted over the " + f"(oracle-specific; the relation is asserted over the " f"remaining {len(ids)} members)" ) if not ids: outcome.fail( "uniform-401", "every member of the uniform-401 relation is skipped on this run " - "(oracle-specific or go-only), so the relation asserts nothing at all", + "(oracle-specific), so the relation asserts nothing at all", ) outcome.line("FAIL relation uniform-401 (no members left to compare)") return @@ -356,7 +341,7 @@ def check_scope_pairs( member = pair.refused if pair.refused in skipped else pair.absent outcome.line( f"SKIP relation refused-equals-absent {pair.name} " - f"({skip_label(corpus, member)})" + f"(oracle-specific: {member})" ) continue outcome.assertions += 1 @@ -423,7 +408,7 @@ def check_head_pairs( member = pair.head if pair.head in skipped else pair.get outcome.line( f"SKIP relation head-matches-get {pair.name} " - f"({skip_label(corpus, member)})" + f"(oracle-specific: {member})" ) continue outcome.assertions += 1 @@ -533,7 +518,7 @@ def _diff(left: list[str], right: list[str], left_name: str, right_name: str) -> def _host_secrets() -> list[str]: """Strings that identify THIS machine and must never reach a golden. - 🔴 THE REPORT NAMES THE MACHINE ON PURPOSE, so the generator runs on a host + 🔴 THE REPORT NAMES THE MACHINE ON PURPOSE, so the recorder runs on a host whose hostname and machine-id are in the bytes it is about to write to a PUBLIC repository. Two normalizations remove them; this guard is what proves the normalizations worked, rather than assuming they did. @@ -543,7 +528,7 @@ def _host_secrets() -> list[str]: would fire on every golden, so the short case is uncovered rather than wrongly covered. The direction of the residual error is stated because it is a choice: a legitimate golden containing the hostname as a substring fails - the generator and a human decides, which is the right way round for a public + the recorder and a human decides, which is the right way round for a public repository. """ out = [socket.gethostname()] @@ -553,8 +538,7 @@ def _host_secrets() -> list[str]: except OSError: continue if len(value) >= 12: - # The display form is a 12-character prefix; see - # `host_identity.MACHINE_ID_DISPLAY_CHARS`. + # The display form is a 12-character prefix; see `internal/hostid`. out.append(value[:12]) out.append(value) return [s for s in out if s and len(s) >= _MIN_SECRET_CHARS] @@ -572,85 +556,7 @@ def check_no_host_leak(text: str, where: str) -> list[str]: # --------------------------------------------------------------------------- -# generate -# --------------------------------------------------------------------------- - - -def generate( - golden_dir: Path = GOLDEN_DIR, - corpus: cases_mod.Corpus | None = None, - **oracle_kwargs, -) -> Outcome: - """Boot the oracle over a freshly-built world and re-record every golden. - - `oracle_kwargs` reaches `boot_oracle` — `server_py=` in particular, which is - how `tests/test_conformance_suite.py` points the GENERATOR at a deliberately - wrong server and proves it refuses to record the divergence. - """ - corpus = corpus or cases_mod.load_corpus() - outcome = Outcome() - with tempfile.TemporaryDirectory(prefix="cairn-conformance-") as td: - with oracle.running_oracle(Path(td), **oracle_kwargs) as ora: - answers = execute(ora.base_url, ora.principals, corpus, outcome) - # 🔴 A `go_only` ROW'S GOLDEN IS NEVER THE ORACLE'S TO RECORD: the oracle - # serves no such route, so what it would write is its no-route 404, filed - # as the contract. The request is still ISSUED (the run's arithmetic is - # the same on every server — see `run`); nothing is written for it, and an - # existing golden for it is left alone, since its id is still declared. - go_only = skipped_on(corpus, server_is_oracle=True) - problems = check_declared_normalizations(corpus, answers, go_only) - texts: dict[str, str] = {} - records: dict[str, dict[str, Any]] = {} - for case in corpus.cases: - if case.id in go_only: - outcome.line( - f"SKIP {case.id} (go-only: {case.go_only_why}; its golden is " - f"not recorded from the oracle)" - ) - continue - resp, _fired = answers[case.id] - rec = wire.record(case, resp) - text = wire.dumps(rec) - problems += check_no_host_leak(text, f"the golden for {case.id!r}") - records[case.id] = rec - texts[case.id] = text - check_uniform_401(corpus, records, outcome, go_only) - check_scope_pairs(corpus, records, outcome, go_only) - check_head_pairs(corpus, records, outcome, go_only) - if outcome.failures: - raise SuiteError( - "refusing to record goldens: the ORACLE itself violates a " - "relational property, so recording would bake the violation in " - "and the suite would then defend it.\n " - + "\n ".join(outcome.failures) - ) - if problems: - raise SuiteError( - "refusing to record goldens:\n " + "\n ".join(problems) - ) - written = 0 - for case_id, text in texts.items(): - path = wire.golden_path(golden_dir, case_id) - path.parent.mkdir(parents=True, exist_ok=True) - path.write_text(text, encoding="utf-8") - written += 1 - outcome.line(f"WROTE {case_id}") - # A golden nothing declares any more is a golden the runner will - # never read: it would sit there looking like coverage. - declared = {c.id for c in corpus.cases} - for stale in sorted(golden_dir.glob("*.json")): - if stale.stem not in declared: - stale.unlink() - outcome.line(f"REMOVED {stale.stem}") - outcome.line( - f"GENERATED cases={written} requests={outcome.requests} " - f"assertions={outcome.assertions}" - ) - return outcome - - -# --------------------------------------------------------------------------- -# the arc journal (Go-only) +# the arc and code-sources journals # --------------------------------------------------------------------------- @@ -659,13 +565,12 @@ def write_arc_journal(path: Path, world: dict | None = None) -> Path: 🔴 OUTSIDE THE STORE TREE, AND THAT IS NOT A CONVENIENCE: `cairn-server -arc-journal` refuses to start when the path resolves inside the store root (operator decision Q2 of - the arcs/sessions plan), so `build-store` puts it beside the token file. The ORACLE is - never handed this file — it serves no arc route — so only `run_go.sh` passes it, and the - `go_only` arc rows are recorded and replayed against a server holding exactly these + the arcs/sessions plan), so `build-store` puts it beside the token file and `run_go.sh` + passes it; the arc rows are recorded and replayed against a server holding exactly these records. Written with a trailing newline per record: a missing final newline is a TORN TAIL to the Go reader and would be ignored. """ - world = world if world is not None else oracle.load_world() + world = world if world is not None else fixture.load_world() path.parent.mkdir(parents=True, exist_ok=True) lines = [json.dumps(r, separators=(",", ":")) for r in world["arc_journal"]["records"]] path.write_text("".join(line + "\n" for line in lines), encoding="utf-8") @@ -676,12 +581,12 @@ def write_source_journal(path: Path, world: dict | None = None) -> Path: """Write the world's seeded code-sources journal to `path`, one record per line. The arc journal's rule, for the arc journal's reasons: OUTSIDE the store tree (the Go - server refuses $CAIRN_SOURCE_JOURNAL inside it), handed only to the Go server by - `run_go.sh` (the oracle serves no sources route), and one trailing newline per record so - the Go reader never sees a torn tail. It is an ENVIRONMENT VARIABLE on the Go server, not a - flag (decision 1 of the scope-refs plan), so `run_go.sh` exports it rather than passing it. + server refuses $CAIRN_SOURCE_JOURNAL inside it), handed to the server by `run_go.sh`, and + one trailing newline per record so the Go reader never sees a torn tail. It is an + ENVIRONMENT VARIABLE on the Go server, not a flag (decision 1 of the scope-refs plan), so + `run_go.sh` exports it rather than passing it. """ - world = world if world is not None else oracle.load_world() + world = world if world is not None else fixture.load_world() path.parent.mkdir(parents=True, exist_ok=True) lines = [] for record in world["source_journal"]["records"]: @@ -699,95 +604,132 @@ def write_source_journal(path: Path, world: dict | None = None) -> Path: # --------------------------------------------------------------------------- -# record-go-only +# provenance: the frozen corpus, and goldens recorded from the Go server # --------------------------------------------------------------------------- -#: 🔴 THE PROVENANCE STAMP A `go_only` GOLDEN CARRIES, AND THE ONLY GOLDENS THAT CARRY ONE. -#: An oracle golden is a CONTRACT WITNESS: recorded from the reference implementation, it -#: says what any implementation must answer. A `go_only` golden cannot be that — there is no -#: second implementation — so it is recorded from the Go server under test and is a CHANGE -#: DETECTOR: it pins that the served bytes did not move, never that they are right. The -#: house rule is that an expectation is never derived from the implementation it tests; -#: this stamp is what keeps a reader from mistaking one for the other, and `run` refuses a -#: golden whose stamp disagrees with its row's mark. The contract witnesses for a Go-only -#: route are the Go tests with literal expected bodies, and the relations below. -GO_ONLY_RECORDED_FROM = "cmd/cairn-server" +#: 🔴 THE PROVENANCE STAMP A GOLDEN RECORDED FROM THE GO SERVER CARRIES. A golden with NO +#: stamp was recorded from the retired Python oracle — the reference implementation — and +#: is a CONTRACT WITNESS: it says what the server must answer, independently of the server. +#: A stamped golden cannot be that: it was recorded from the implementation it now tests, +#: so it is a CHANGE DETECTOR — it pins that the served bytes did not move, never that they +#: are right — and it is admitted only after a human has read it (`README.md`). The house +#: rule is that an expectation is never derived from the implementation it tests; this +#: stamp is what keeps a reader from mistaking one for the other. +RECORDED_FROM_GO = "cmd/cairn-server" + +#: 🔴 THE FROZEN CORPUS, PINNED BY COUNT AND BY CONTENT. Every unstamped golden was +#: recorded from the oracle at the last commit that had it (`README.md` names it); nothing +#: can regenerate one now, so the set must neither grow, shrink, nor change a byte. The +#: digest is sha256 over each unstamped golden's `\0\0`, in sorted +#: filename order. A NEW unstamped golden moves both numbers, an edited one moves the +#: digest, and a deleted one moves both — each is refused by `check_frozen_corpus`. +FROZEN_ORACLE_GOLDENS = 128 +FROZEN_ORACLE_DIGEST = "f6489e42fe8b3508a06bc5208169c1d44914384de50359b2af1fdfcfe339b88d" + + +def frozen_corpus_digest(golden_dir: Path = GOLDEN_DIR) -> tuple[int, str]: + """(count, digest) over the UNSTAMPED goldens in `golden_dir`. See the constants.""" + h = hashlib.sha256() + count = 0 + for path in sorted(golden_dir.glob("*.json")): + raw = path.read_bytes() + if "recorded_from" in json.loads(raw): + continue + count += 1 + h.update(path.name.encode("utf-8") + b"\0" + raw + b"\0") + return count, h.hexdigest() + + +def check_frozen_corpus(golden_dir: Path = GOLDEN_DIR) -> list[str]: + """The frozen oracle corpus is exactly what it was frozen as. Returns the problems.""" + count, digest = frozen_corpus_digest(golden_dir) + problems = [] + if count != FROZEN_ORACLE_GOLDENS: + problems.append( + f"{count} unstamped golden(s), not the {FROZEN_ORACLE_GOLDENS} frozen from the " + f"retired oracle. A golden with no `recorded_from` claims it was recorded from the " + f"reference implementation, and nothing can do that any more: record a new golden " + f"with `run_go.sh record ` (it stamps `recorded_from: {RECORDED_FROM_GO}`), and " + f"never delete a frozen one to make room." + ) + elif digest != FROZEN_ORACLE_DIGEST: + problems.append( + f"the frozen oracle goldens' digest is {digest}, not {FROZEN_ORACLE_DIGEST}: one " + f"of them was edited. They are a FIXED corpus recorded from a server that no " + f"longer exists; re-recording one from the Go server would certify Go against " + f"itself. Restore it from git." + ) + return problems def check_golden_provenance(case: cases_mod.Case, golden: dict[str, Any]) -> str | None: - """A golden's `recorded_from` must match its row's mark. Returns the problem, or None. + """A golden is either FROZEN (no stamp) or recorded from Go. Returns the problem, or None. - `go_only` ⇒ stamped `cmd/cairn-server`; every other row ⇒ no stamp at all (the - oracle's `generate` writes none). A stamp on an oracle golden would claim a contract - witness was a change detector, and a missing one on a go-only golden the reverse. + Which unstamped goldens exist is `check_frozen_corpus`'s question; this one refuses a + stamp that names anything else, since it would claim a provenance nothing can produce. """ stamp = golden.get("recorded_from") - if case.go_only and stamp != GO_ONLY_RECORDED_FROM: + if stamp is not None and stamp != RECORDED_FROM_GO: return ( - f"the golden for go_only row {case.id!r} carries recorded_from={stamp!r}, " - f"not {GO_ONLY_RECORDED_FROM!r}. A go_only golden is recorded from the Go " - f"server by `run_go.sh record-go-only` — never by the oracle's `generate`." - ) - if not case.go_only and stamp is not None: - return ( - f"the golden for row {case.id!r} carries recorded_from={stamp!r}, but the " - f"row is not go_only: its golden is the ORACLE's, recorded by `generate`." + f"the golden for row {case.id!r} carries recorded_from={stamp!r}. A golden is " + f"either frozen from the retired oracle (no stamp) or recorded from the Go " + f"server by `run_go.sh record` (stamped {RECORDED_FROM_GO!r}); nothing else " + f"records one." ) return None -def record_go_only( +def record( base_url: str, token_file: Path, + ids: list[str], golden_dir: Path = GOLDEN_DIR, corpus: cases_mod.Corpus | None = None, ) -> Outcome: - """Record the goldens of the `go_only` rows — and ONLY those — from a running Go server. + """Record goldens for the NAMED rows — and only those — from a running Go server. 🔴 THE WHOLE CORPUS IS ISSUED, IN ORDER, exactly as `run` issues it: the run's arithmetic (the limiter's view, the write phase) must be the one the goldens are - replayed under, so a recorder that sent only the go-only rows would record answers - from a different world. Only `go_only` rows are WRITTEN; an oracle golden is never - touched, which is the other half of the provenance rule. - - 🔴 IT REFUSES TO RECORD, the way `generate` does, when: - * no row is `go_only` (nothing to record is a mistake, not a success); - * a go-only ROUTE got only the no-route 404 from every row addressing it — the - signature of pointing this at a server that does not serve it (the oracle, - or a stale binary), whose 404 would otherwise be filed as the contract; + replayed under, so a recorder that sent only the new rows would record answers from a + different world. Only the named rows are WRITTEN. + + 🔴 IT REFUSES TO RECORD when: + * no id is named (nothing to record is a mistake, not a success); + * a named id is not a declared row, is marked `oracle_only`, or ALREADY HAS A + GOLDEN — a frozen one must never be re-recorded (it would certify Go against + itself), and a Go-recorded one is changed by deleting it in a reviewed commit + first, so the diff shows both the old and the new bytes; * a relation fails over this server's answers (refused-equals-absent, head-matches-get, uniform-401 — `oracle_only` rows skipped, as in `run`); - * a recorded body names this machine. + * a declared normalization fires on nothing, or a recorded body names this + machine. + + ⚠ A RECORDED GOLDEN IS A CHANGE DETECTOR UNTIL A HUMAN HAS READ IT. Nothing here can + tell a right answer from a wrong one; `README.md` says what the review must check. """ corpus = corpus or cases_mod.load_corpus() - go_only = [c for c in corpus.cases if c.go_only] - if not go_only: - raise SuiteError("refusing to record: no row is marked go_only") - principals = oracle.principals_from_token_file(token_file) - outcome = Outcome() - answers = execute(base_url, principals, corpus, outcome) - skipped = skipped_on(corpus, server_is_oracle=False) - problems = check_declared_normalizations(corpus, answers, skipped) - - # 🔴 A 2xx, NOT "ANYTHING BUT THE NO-ROUTE 404": the first draft of this floor counted - # any other answer as served, and the ORACLE passed it — its uniform 401 to the - # unauthenticated go-only row is not a 404. Measured by pointing the recorder at the - # oracle; `test_the_recorder_REFUSES_a_server_that_does_not_serve_the_route` pins it. - served: dict[str, bool] = {} - for case in go_only: - resp, _fired = answers[case.id] - route = cases_mod._route_of(case) or case.id - real = resp.status is not None and 200 <= resp.status < 300 - served[route] = served.get(route, False) or real - for route, ok in sorted(served.items()): - if not ok: + if not ids: + raise SuiteError("refusing to record: no case id named") + problems: list[str] = [] + for case_id in ids: + case = corpus.by_id(case_id) + if case.oracle_only: + problems.append(f"{case_id} is marked oracle_only: a frozen record, never re-recorded") + if wire.golden_path(golden_dir, case_id).exists(): problems.append( - f"no go_only row addressing {route} got a 2xx — the rows a real server " - f"answers got the no-route 404 or a refusal, so this server does not serve " - f"it. Is --base-url the Go server built from this tree? Recording would " - f"file a refusal as the Go-only contract." + f"{case_id} already has a golden. A frozen one is never re-recorded; a " + f"Go-recorded one is changed by deleting it in a reviewed commit first." ) - + if problems: + raise SuiteError("refusing to record:\n " + "\n ".join(problems)) + principals = fixture.principals_from_token_file(token_file) + outcome = Outcome() + answers = execute(base_url, principals, corpus, outcome) + skipped = skipped_on(corpus) + problems += [ + p for p in check_declared_normalizations(corpus, answers, skipped) + if p.split(":", 1)[0] in ids + ] records = { c.id: wire.record(c, answers[c.id][0]) for c in corpus.cases if c.id not in skipped } @@ -796,26 +738,26 @@ def record_go_only( check_head_pairs(corpus, records, outcome, skipped) if outcome.failures: raise SuiteError( - "refusing to record go_only goldens: the Go server violates a relational " + "refusing to record goldens: the Go server violates a relational " "property, so recording would bake the violation in.\n " + "\n ".join(outcome.failures) ) texts: dict[str, str] = {} - for case in go_only: - rec = dict(records[case.id]) - rec["recorded_from"] = GO_ONLY_RECORDED_FROM + for case_id in ids: + rec = dict(records[case_id]) + rec["recorded_from"] = RECORDED_FROM_GO text = wire.dumps(rec) - problems += check_no_host_leak(text, f"the go_only golden for {case.id!r}") - texts[case.id] = text + problems += check_no_host_leak(text, f"the golden for {case_id!r}") + texts[case_id] = text if problems: - raise SuiteError("refusing to record go_only goldens:\n " + "\n ".join(problems)) + raise SuiteError("refusing to record goldens:\n " + "\n ".join(problems)) for case_id, text in texts.items(): path = wire.golden_path(golden_dir, case_id) path.parent.mkdir(parents=True, exist_ok=True) path.write_text(text, encoding="utf-8") - outcome.line(f"WROTE {case_id} (recorded_from: {GO_ONLY_RECORDED_FROM})") + outcome.line(f"WROTE {case_id} (recorded_from: {RECORDED_FROM_GO}) — REVIEW IT") outcome.line( - f"RECORDED go_only={len(texts)} requests={outcome.requests} " + f"RECORDED cases={len(texts)} requests={outcome.requests} " f"assertions={outcome.assertions}" ) return outcome @@ -875,35 +817,26 @@ def run( token_file: Path, golden_dir: Path = GOLDEN_DIR, corpus: cases_mod.Corpus | None = None, - *, - assert_oracle_specific: bool = True, ) -> Outcome: - """Replay the corpus against any server and diff against the goldens. - - 🔴 `assert_oracle_specific` DEFAULTS TO **TRUE**, WHICH IS THE STRICT - DIRECTION FOR `oracle_only`, AND THAT IS DELIBERATE. It is also the statement - "this server is the oracle", so it SKIPS every `go_only` row — the one thing the - oracle cannot answer — and turning it off asserts them. A row marked `oracle_only` records an answer - that is the Python server's own shape rather than a contract any implementation - can honour (see `cases.Case.oracle_only`). Asserting it against a port fails; - skipping it against the ORACLE would silently stop covering the oracle's real - behaviour, which is the worse of the two, so a caller that does not say gets the - assertion. The CLI turns it off for `--base-url` and REPORTS every skip by id. + """Replay the corpus against a running server and diff against the goldens. + + Every row is compared except those marked `oracle_only` — frozen records of the + retired oracle's own shape — which are SKIPPED, named with their reason, and counted + in the SUMMARY. The frozen corpus itself is checked first (`check_frozen_corpus`). """ corpus = corpus or cases_mod.load_corpus() - principals = oracle.principals_from_token_file(token_file) + principals = fixture.principals_from_token_file(token_file) outcome = Outcome() + for problem in check_frozen_corpus(golden_dir): + outcome.failures.append(problem) + outcome.line("FAIL frozen-corpus") answers = execute(base_url, principals, corpus, outcome) # 🔴 THE CASE IS STILL ISSUED. Only the COMPARISON is skipped — because the # request itself is part of the run's arithmetic: the corpus issues fifteen # deliberate refusals from one client address and the canary at the end is what # proves no lockout tripped. Dropping a request would change what the limiter # saw, so a skipped row would quietly alter the answers of the rows around it. - # - # `assert_oracle_specific=True` IS THE STATEMENT "THIS SERVER IS THE ORACLE", so it - # also decides the mirror mark: `go_only` rows are skipped exactly when - # `oracle_only` rows are asserted. See `skipped_on`. - skipped = skipped_on(corpus, server_is_oracle=assert_oracle_specific) + skipped = skipped_on(corpus) for problem in check_declared_normalizations(corpus, answers, skipped): outcome.failures.append(problem) outcome.line("FAIL normalization " + problem.split(":")[0]) @@ -913,9 +846,7 @@ def run( resp, _fired = answers[case.id] if case.id in skipped: outcome.skipped.append(case.id) - outcome.line( - f"SKIP {case.id} ({skip_label(corpus, case.id)}: {_why(case)})" - ) + outcome.line(f"SKIP {case.id} (oracle-specific: {case.oracle_only_why})") continue records[case.id] = wire.record(case, resp) golden = wire.read_golden(golden_dir, case.id) @@ -965,23 +896,6 @@ def run( return outcome -def run_against_oracle(golden_dir: Path = GOLDEN_DIR, corpus: cases_mod.Corpus | None = None, - **oracle_kwargs) -> Outcome: - """Boot the Python oracle over a fresh world and replay against it. - - Every `oracle_only` row is ASSERTED here — this function is the one place that - knows the server it is talking to IS `server/server.py` — and every `go_only` - row is SKIPPED, reported by id and counted, because the oracle serves no such - route. - """ - with tempfile.TemporaryDirectory(prefix="cairn-conformance-") as td: - with oracle.running_oracle(Path(td), **oracle_kwargs) as ora: - return run( - ora.base_url, ora.token_file, golden_dir, corpus, - assert_oracle_specific=True, - ) - - # --------------------------------------------------------------------------- # CLI # --------------------------------------------------------------------------- @@ -1005,39 +919,21 @@ def main(argv: list[str] | None = None) -> int: p = argparse.ArgumentParser(prog="conformance", description=__doc__) sub = p.add_subparsers(dest="command", required=True) - g = sub.add_parser("generate", help="re-record every golden from the oracle") - g.add_argument("--golden-dir", type=Path, default=GOLDEN_DIR) - + # 🔴 `--server-binary` IS REQUIRED, AND THAT IS WHAT KEEPS THE ROUTE LEDGER IN THE GATE: + # the corpus is validated against the routes that binary declares (`cairn-server + # -routes`), so `run_go.sh` cannot replay a corpus that misses a declared route. r = sub.add_parser("run", help="replay the corpus and diff against the goldens") - r.add_argument("--base-url", default=None, help="default: boot the Python oracle") - r.add_argument("--token-file", type=Path, default=None) - r.add_argument("--golden-dir", type=Path, default=GOLDEN_DIR) - r.add_argument( - "--oracle-specific", - choices=("skip", "assert"), - default="skip", - help=( - "what to do with a row marked `oracle_only` — a response whose shape is " - "the Python server's own artifact rather than a contract (see " - "`cases.Case.oracle_only`). `skip` (the default for --base-url) does NOT " - "compare it and names every skipped id with its reason in the output and " - "in the SUMMARY; `assert` compares it, which is what you want when " - "--base-url points at a hand-started ORACLE rather than at a port. " - "`assert` also SKIPS every `go_only` row (a route only the Go server " - "serves) and `skip` compares them — the mirror mark, decided by the same " - "statement about which server this is. " - "Omitting --base-url boots the oracle and always asserts." - ), + rec = sub.add_parser( + "record", + help="record goldens for NEW rows from a running Go server " + "(use `tests/conformance/run_go.sh record ...`)", ) - - rg = sub.add_parser( - "record-go-only", - help="record the go_only rows' goldens from a running GO server " - "(use `tests/conformance/run_go.sh record-go-only`)", - ) - rg.add_argument("--base-url", required=True) - rg.add_argument("--token-file", type=Path, required=True) - rg.add_argument("--golden-dir", type=Path, default=GOLDEN_DIR) + rec.add_argument("ids", nargs="+", metavar="case-id") + for q in (r, rec): + q.add_argument("--base-url", required=True) + q.add_argument("--token-file", type=Path, required=True) + q.add_argument("--server-binary", type=Path, required=True) + q.add_argument("--golden-dir", type=Path, default=GOLDEN_DIR) sub.add_parser("normalizations", help="print the declared normalization table") @@ -1049,36 +945,24 @@ def main(argv: list[str] | None = None) -> int: _print_normalizations() return 0 if args.command == "build-store": - root = oracle.build_store(args.dest) - tokens = oracle.mint_tokens() - token_file = oracle.write_token_file(args.dest.parent / "tokens", tokens) + root = fixture.build_store(args.dest) + tokens = fixture.mint_tokens() + token_file = fixture.write_token_file(args.dest.parent / "tokens", tokens) journal = write_arc_journal(args.dest.parent / "arcs" / "journal.jsonl") print(f"store={root}") print(f"token-file={token_file}") print(f"arc-journal={journal}") sources = write_source_journal(args.dest.parent / "sources" / "sources.jsonl") print(f"source-journal={sources}") - print("env: " + " ".join(f"{k}={v}" for k, v in oracle.ORACLE_ENV.items())) + print("env: " + " ".join(f"{k}={v}" for k, v in fixture.SERVER_ENV.items())) return 0 - if args.command == "generate": - outcome = generate(args.golden_dir) + corpus = cases_mod.load_corpus(routes=cases_mod.declared_routes(args.server_binary)) + if args.command == "record": + outcome = record(args.base_url, args.token_file, args.ids, args.golden_dir, corpus) for line in outcome.lines: print(line) return 0 - if args.command == "record-go-only": - outcome = record_go_only(args.base_url, args.token_file, args.golden_dir) - for line in outcome.lines: - print(line) - return 0 - if args.base_url is None: - outcome = run_against_oracle(args.golden_dir) - else: - if args.token_file is None: - p.error("--token-file is required with --base-url") - outcome = run( - args.base_url, args.token_file, args.golden_dir, - assert_oracle_specific=args.oracle_specific == "assert", - ) + outcome = run(args.base_url, args.token_file, args.golden_dir, corpus) for line in outcome.lines: print(line) if outcome.failures: diff --git a/tests/conformance/wire.py b/tests/conformance/wire.py index 90021da2..6fac5bc7 100644 --- a/tests/conformance/wire.py +++ b/tests/conformance/wire.py @@ -2,8 +2,8 @@ 🔴 THIS MODULE SPEAKS HTTP AND NOTHING ELSE. It imports no part of the server and no part of the client. Everything it knows about the implementation under -test arrives as a base URL and a token file, which is what makes the same corpus -runnable against the Python oracle today and an unmodified Go binary later. +test arrives as a base URL and a token file, which is what let the same corpus be +recorded from the Python oracle and replayed, unmodified, against the Go binary. 🔴 EVERY NORMALIZATION IS A NAMED ROW IN `NORMALIZATIONS`, WITH A REASON, AND A CASE DECLARES THE ONES THAT APPLY TO IT. There is deliberately no "ignore @@ -497,7 +497,7 @@ def issue(base_url: str, case: cases_mod.Case, principals: dict[str, Any]) -> Re #: A raw request line may need the run's own credential, and the tokens are -#: minted per run (see `oracle.py`). `{{}}` is substituted with that +#: minted per run (see `fixture.py`). `{{}}` is substituted with that #: principal's token — the same indirection `principal:` gives an ordinary row, #: spelled so it survives inside a literal header line. #: @@ -657,7 +657,8 @@ def body_from_record(rec: dict[str, Any]) -> bytes: raise WireError( f"golden for case {rec['case']!r} is INTERNALLY INCONSISTENT: its body " f"hashes to {digest} but the file records {body['sha256']}. A golden is " - f"generated, never hand-written — regenerate it instead of editing it." + f"generated, never hand-written — restore it from git, or (for a golden recorded " + f"from the Go server) delete it and re-record it with `run_go.sh record`." ) return data @@ -682,8 +683,8 @@ def read_golden(directory: Path, case_id: str) -> dict[str, Any]: path = golden_path(directory, case_id) if not path.is_file(): raise WireError( - f"no golden for case {case_id!r} at {path}. Regenerate the fixtures: " - f"`python3 tests/conformance/suite.py generate`" + f"no golden for case {case_id!r} at {path}. Record it from the Go server and " + f"review it: `tests/conformance/run_go.sh record {case_id}`" ) rec = json.loads(path.read_text(encoding="utf-8")) if rec["body"]["kind"] != "tar_gz_manifest": diff --git a/tests/test_conformance_suite.py b/tests/test_conformance_suite.py index f7140654..fa0dfd70 100644 --- a/tests/test_conformance_suite.py +++ b/tests/test_conformance_suite.py @@ -2,30 +2,30 @@ 🔴 WHAT THIS FILE IS FOR, STATED UP FRONT BECAUSE IT IS EASY TO CONFUSE WITH THE SUITE ITSELF. `tests/conformance/` measures the SERVER. This file measures the -MEASURING INSTRUMENT, and the two claims it makes about it are: - - * NEGATIVE CONTROL — put a deliberately wrong server behind the suite and - watch it fail. `TestTheSuiteGoesRedOnARealMutation` does that with realistic - mutations (a status code moved, a header dropped, preserved mtimes truncated - to whole seconds, a refusal made distinguishable from an absence), and pairs - every one with the POSITIVE control: an unmutated copy of the same tree, - booted the same way, which has to pass. Without that pair, `the mutant was - caught` cannot be told from `the copied tree never booted`. +MEASURING INSTRUMENT, and the claims it makes about it are: + * EVERY GUARD IN THE SUITE IS REACHABLE AND FAILS WITH ITS OWN MESSAGE. Each `TestCorpusGuards` case breaks one thing on purpose and asserts on the sentence THAT guard raises, never merely that something raised — a test satisfied by any exception is green when a neighbour's error arrives first. + * THE FROZEN CORPUS CANNOT MOVE. The goldens recorded from the retired Python + oracle are a fixed corpus (`tests/conformance/README.md`); `TestTheFrozenCorpus` + proves the check refuses an edited, added or deleted one, and that `record` + refuses to overwrite any golden. + +⚠ WHAT THIS FILE NO LONGER DOES, AND WHERE IT WENT. Until the oracle was retired, +this file booted it to put a deliberately wrong server behind the suite (a negative +control) and an unmutated copy beside it (the positive one). This tier has no Go +toolchain, so it cannot boot the server that replaced it; the end-to-end controls +are the `go` CI job's: `run_go.sh` against the real server (the positive control, +with its PASS floor) and against a corpus with one golden deliberately broken (the +negative control, which must report exactly that case as FAIL). ⚠ WHICH OF THESE ARE INVARIANT GUARDS, labelled rather than counted as -regression coverage: `TestTheCorpusIsWellFormed`, and every part of -`TestTheGoldensAreGenerated` EXCEPT -`test_a_different_host_label_produces_the_same_goldens` — that one is regression -coverage, because the defect it pins was live in this branch and it is what -found it (the goldens were host-specific through `Content-Length`). +regression coverage: `TestTheCorpusIsWellFormed`. `TestTheFramingClaim::test_it_is_NOT_asserted_where_it_could_not_fail` is -regression coverage too, for a VACUOUS guard in an earlier version of this -suite. Everything under `TestCorpusGuards`, `TestNormalizations`, -`TestTheSuiteGoesRedOnARealMutation` and `TestTheRelationsCannotBeRegeneratedAway` +regression coverage, for a VACUOUS guard in an earlier version of this suite. +Everything under `TestCorpusGuards`, `TestNormalizations` and `TestTheFrozenCorpus` was watched to fail: each was run against the broken input before its assertion was written. """ @@ -33,9 +33,9 @@ from __future__ import annotations import json +import os import re import sys -import tempfile from pathlib import Path import pytest @@ -43,22 +43,28 @@ sys.path.insert(0, str(Path(__file__).resolve().parent)) from conformance import cases as cases_mod # noqa: E402 -from conformance import mutate, oracle, suite, wire # noqa: E402 +from conformance import fixture, suite, wire # noqa: E402 ROOT = Path(__file__).resolve().parents[1] GOLDEN = ROOT / "tests" / "conformance" / "golden" # 🔴 SPELLED OUT BY HAND, NEVER IMPORTED FROM THE THING UNDER TEST. These are the -# routes `server/server.py` declares today. `declared_routes` reads them by AST; -# if it ever silently discovered NOTHING it would report full coverage over an -# empty set, and comparing against an imported copy of the same dict would be -# `x == x`. +# routes `cmd/cairn-server` declares today (`api.DeclaredRoutes()`). This tier has no +# Go toolchain to ask the binary, so the set the corpus addresses is checked against +# this literal here, and against the binary itself by `run_go.sh` and by +# `internal/api`'s `TestTheRouteLedgerMatchesTheConformanceCorpus`. EXPECTED_ROUTES = { "GET recall", "HEAD recall", "GET search", "HEAD search", "GET snapshot", "HEAD snapshot", + "GET sessions", "HEAD sessions", + "GET arcs", "HEAD arcs", + "GET arc", "HEAD arc", + "GET sources", "HEAD sources", + "GET whoami", "HEAD whoami", "POST entry", "PUT entry", + "PUT arc", } @@ -77,56 +83,18 @@ def _raw_corpus() -> dict: return json.loads(cases_mod.REQUESTS_PATH.read_text(encoding="utf-8")) -#: 🔴 THE REAL `go_only` ROWS, SPELLED BY HAND — never derived from the corpus under test, -#: so a row that lost (or gained) its mark moves the assertions that read this. The -#: arcs/sessions S2 slice added the `sessions-*` rows, S3 the arc registry's, and S5 the four -#: `arcs-check-*` rows (the orphan check, a `?check=1` mode of the `arcs` head), and S2 of the -#: scope-refs plan the six `sources-*` rows, and the `whoami` self-view route its five; the next -#: Go-only route moves this set in its commit. -GO_ONLY_IDS = ( - "sessions-authorized", "sessions-authorized-head", "sessions-legacy-token", - "sessions-refused-scope", "sessions-absent-scope", "sessions-empty-scope", - "sessions-unreadable-scope", "sessions-unauthenticated", "sessions-arity-too-long", - "arcs-authorized", "arcs-authorized-head", "arcs-declared-elsewhere", "arcs-hidden-home", - "arcs-legacy-token", "arcs-refused-scope", "arcs-absent-scope", "arcs-no-arc", - "arcs-unauthenticated", - "sources-authorized", "sources-authorized-head", "sources-undeclared", - "sources-refused-scope", "sources-absent-scope", "sources-unauthenticated", - "whoami-authorized", "whoami-authorized-head", "whoami-narrow-reader", - "whoami-legacy-token", "whoami-unauthenticated", - "arcs-check-all-scopes", "arcs-check-scoped", - "arcs-check-refused-scope", "arcs-check-absent-scope", - "arc-authorized", "arc-authorized-head", "arc-unregistered-slug", - "arc-refused-home", "arc-absent-home", "arc-unauthenticated", "arc-arity-too-short", - "put-arc-registered", "put-arc-unchanged", "put-arc-malformed", "put-arc-refused-declared", - "put-arc-refused-home", "put-arc-absent-home", "put-arc-legacy", "put-arc-unauthenticated", -) - -#: The relation-level skips those rows cause against the oracle, spelled by hand: four -#: uniform-401 members, five refused-equals-absent pairs (S5 added `arcs-check`) and three -#: head-matches-get pairs — plus, from S2 of the scope-refs plan, the `sources` route's one -#: uniform-401 member, one refused-equals-absent pair and one head-matches-get pair — and from -#: the `whoami` self-view route, one uniform-401 member and one head-matches-get pair (it takes -#: no scope, so it has no refused-equals-absent pair). -GO_ONLY_RELATION_SKIPS = 17 - - -def _raw_corpus_without_go_only() -> dict: - """The real corpus with every `go_only` row (and every relation naming one) removed. - - For the tests that stand the ORACLE in for "a port" (`assert_oracle_specific=False`): - such a run COMPARES go_only rows, and the oracle's only answer to a Go-only route is its - no-route 404 — so those rows would fail for a reason unrelated to what the test measures. - """ - raw = _raw_corpus() - gone = {c["id"] for c in raw["cases"] if c.get("go_only")} - raw["cases"] = [c for c in raw["cases"] if c["id"] not in gone] - rel = raw["relations"] - rel["uniform_401"] = [i for i in rel["uniform_401"] if i not in gone] - for key, members in (("refused_equals_absent", ("refused", "absent")), - ("head_matches_get", ("head", "get"))): - rel[key] = [p for p in rel[key] if not any(p[m] in gone for m in members)] - return raw +def _fake_binary(tmp_path: Path, stdout: str, rc: int = 0) -> Path: + """An executable standing in for `cairn-server -routes`: prints `stdout`, exits `rc`.""" + path = tmp_path / "fake-cairn-server" + path.write_text( + "#!/bin/sh\n" + f"[ \"$1\" = -routes ] || exit 64\n" + f"printf '%b' {json.dumps(stdout)}\n" + f"exit {rc}\n", + encoding="utf-8", + ) + path.chmod(0o755) + return path def _records_answering(corpus: cases_mod.Corpus, status: int) -> dict: @@ -164,9 +132,6 @@ def test_it_loads(self, corpus): assert corpus.uniform_401 assert corpus.scope_pairs - def test_the_route_ledger_finds_exactly_the_routes_that_exist(self): - assert cases_mod.declared_routes() == EXPECTED_ROUTES - def test_every_declared_route_is_addressed_by_a_row(self, corpus): assert cases_mod.addressed_routes(corpus) == EXPECTED_ROUTES @@ -265,45 +230,55 @@ def test_a_row_with_no_stated_reason_is_refused(self, tmp_path): _corpus_from(raw, tmp_path) assert "states why it is here" in str(exc.value) - def test_the_route_ledger_refuses_a_source_it_found_no_table_in(self, tmp_path): + def test_the_route_ledger_refuses_a_binary_that_declares_nothing(self, tmp_path): """🔴 THE LEDGER'S OWN POSITIVE CONTROL. A discovery function that finds nothing reports FULL COVERAGE over an empty set — the reassuring zero. - It must refuse instead.""" - empty = tmp_path / "server.py" - empty.write_text("X = 1\n", encoding="utf-8") + It must refuse instead. A stand-in executable prints no routes.""" + binary = _fake_binary(tmp_path, "") with pytest.raises(cases_mod.CorpusError) as exc: - cases_mod.declared_routes(empty) - assert "no API_ROUTES dict literal" in str(exc.value) - - def test_the_route_ledger_reads_a_synthetic_table(self, tmp_path): - """…and the matching NEGATIVE control: it can see a table that is there, - including a write row, so a green above is not `it never parses`.""" - src = tmp_path / "server.py" - src.write_text( - 'API_ROUTES: dict[str, tuple[str, int]] = {"alpha": ("_a", 2)}\n' - 'WRITE_ROUTES: dict = {("POST", "beta"): ("_b", 3, ())}\n', - encoding="utf-8", - ) - assert cases_mod.declared_routes(src) == { - "GET alpha", "HEAD alpha", "POST beta", - } + cases_mod.declared_routes(binary) + assert "printed no routes" in str(exc.value) + + def test_the_route_ledger_reads_what_the_binary_prints(self, tmp_path): + """…and the matching NEGATIVE control: it reads the lines that are there, + so a green above is not `it never parses`.""" + binary = _fake_binary(tmp_path, "GET alpha\nHEAD alpha\nPOST beta\n") + assert cases_mod.declared_routes(binary) == {"GET alpha", "HEAD alpha", "POST beta"} + + def test_the_route_ledger_refuses_a_binary_that_fails(self, tmp_path): + binary = _fake_binary(tmp_path, "GET alpha\n", rc=78) + with pytest.raises(cases_mod.CorpusError) as exc: + cases_mod.declared_routes(binary) + assert "exited 78" in str(exc.value) + + def test_a_row_carrying_an_unknown_key_is_refused(self, tmp_path): + """A retired or misspelt mark must not linger reading as live: an unread key + changes nothing while looking like it does.""" + raw = _raw_corpus() + raw["cases"][0]["a_retired_mark"] = True + with pytest.raises(cases_mod.CorpusError) as exc: + _corpus_from(raw, tmp_path) + assert "which this loader does not read" in str(exc.value) class TestTheOracleSpecificMark: """🔴 THE ONE MECHANISM THAT IS ALLOWED TO SKIP A CASE, AND EVERY GUARD ON IT. - A row marked `oracle_only` records an answer that is `http.server`'s or CPython's - own shape rather than a contract any implementation can honour — an HTTP/0.9 - response with no status line, a request line the framework rejects before a handler - exists, a body quoting the `json` module's diagnostic. It is asserted against the - oracle and SKIPPED, by id and with its reason, for anything else. + A row marked `oracle_only` holds a FROZEN golden recording an answer that was + `http.server`'s or CPython's own shape rather than a contract the Go server honours — + an HTTP/0.9 response with no status line, a request line the framework rejects before + a handler exists, a body quoting the `json` module's diagnostic. The oracle that could + answer it is retired, so it is SKIPPED on every run, by id and with its reason. ⚠ IT IS THE LAST RESORT AND NOT THE FIRST. A response differing in ONE FIELD - belongs in `wire.NORMALIZATIONS`, which keeps every other byte pinned for both - implementations; this mark stops the whole case being compared, so the guards below - exist to make sure it cannot be used quietly. + belongs in `wire.NORMALIZATIONS`, which keeps every other byte pinned; this mark + stops the whole case being compared, so the guards below exist to make sure it + cannot be used quietly. """ + def test_skipped_on_is_exactly_the_marked_set(self, corpus): + assert suite.skipped_on(corpus) == {c.id for c in corpus.cases if c.oracle_only} + def test_the_marked_set_is_exactly_the_four_rows_that_carry_a_reason(self, corpus): """An INVARIANT GUARD on today's set, spelled by hand: four rows carry the mark, and the list is written out so a fifth cannot appear unreviewed.""" @@ -338,76 +313,6 @@ def test_a_reason_with_no_mark_is_refused(self, tmp_path): _corpus_from(raw, tmp_path) assert "is not marked oracle_only" in str(exc.value) - def test_the_oracle_run_SKIPS_NOTHING(self): - """🔴 THE PROPERTY THAT MAKES THE MARK SAFE. Skipping against the oracle would - silently stop covering the oracle's real behaviour, which is worse than - asserting it against a port — so `run_against_oracle` asserts every marked row - and `run`'s default is the strict direction. - - ⚠ The oracle run DOES skip `go_only` rows (see `TestTheGoOnlyMark`) — and since - the arcs/sessions S2 slice the real corpus has some (33 since S3), so "nothing" became "exactly - the go_only ids, spelled by hand": every `oracle_only` row is still ASSERTED, and - no skip line names an oracle-specific row.""" - outcome = suite.run_against_oracle() - assert outcome.failures == [] - assert sorted(outcome.skipped) == sorted(GO_ONLY_IDS) - skips = [ln for ln in outcome.lines if ln.startswith("SKIP")] - assert skips, "the positive control: the go_only rows ARE skipped, and say so" - assert not [ln for ln in skips if "oracle-specific" in ln] - - def test_skipping_is_REPORTED_by_id_and_by_reason(self, tmp_path): - """A skip nobody can see is indistinguishable from a pass, which is the whole - failure mode this suite is built against — so the run names every skipped id on - its own line, with the row's reason, and counts them in the summary. - - The oracle stands in for a port here, so the corpus is the real one MINUS its - `go_only` rows, which a non-oracle run compares and the oracle cannot answer.""" - corpus = _corpus_from(_raw_corpus_without_go_only(), tmp_path) - with tempfile.TemporaryDirectory(prefix="cairn-conformance-") as td: - with oracle.running_oracle(Path(td)) as ora: - outcome = suite.run( - ora.base_url, ora.token_file, GOLDEN, corpus, - assert_oracle_specific=False, - ) - assert sorted(outcome.skipped) == sorted( - [ - "post-bullets-deeply-nested-json", - "post-bullets-not-json", - "raw-malformed-absolute-target", - "raw-malformed-request-line", - ] - ) - # Per-CASE skip lines only: the relation lines below are their own claim and - # are counted separately, because "a case was not compared" and "a relation - # lost a member" are different facts and folding them would make the count - # agree with either. - skip_lines = [ - ln for ln in outcome.lines - if ln.startswith("SKIP ") and not ln.startswith("SKIP relation ") - ] - assert len(skip_lines) == len(outcome.skipped) - for line in skip_lines: - assert "oracle-specific: " in line - # …and the reason is the ROW's, not a constant this runner invented. - assert len(line.split("oracle-specific: ", 1)[1]) > 80 - summary = [ln for ln in outcome.lines if ln.startswith("SUMMARY")][0] - assert "skipped=4" in summary - assert "raw-malformed-request-line" in summary - # 🔴 THE REQUEST IS STILL ISSUED. Only the comparison is skipped, because the - # request itself is part of the run's arithmetic: fifteen deliberate refusals - # from one client address, and a canary at the end that proves no lockout - # tripped. Dropping a request would change what the limiter saw. - assert outcome.requests == len(corpus.cases) + 1 - # The oracle answers every one of them correctly, so a skip must not turn into - # a failure — and the relation whose member was skipped must still be asserted - # over what is left. - assert outcome.failures == [] - relation_skips = [ - ln for ln in outcome.lines if ln.startswith("SKIP relation uniform-401") - ] - assert len(relation_skips) == 1 - assert "asserted over the remaining 14 members" in relation_skips[0] - def test_a_relation_whose_every_member_is_skipped_FAILS(self, tmp_path): """🔴 THE ANTI-VACUITY GUARD ON THE MECHANISM. A relation left with no members asserts nothing at all, and reporting that as a pass is exactly the reassuring @@ -415,9 +320,7 @@ def test_a_relation_whose_every_member_is_skipped_FAILS(self, tmp_path): raw = _raw_corpus() members = set(raw["relations"]["uniform_401"]) for row in raw["cases"]: - # A go_only member is already excused by its own mark (and may not carry - # both); `skipped=members` below is what removes every member either way. - if row["id"] in members and not row.get("go_only"): + if row["id"] in members: row["oracle_only"] = True row["oracle_only_why"] = ( "a synthetic mark, used only to prove the relation refuses to " @@ -471,217 +374,6 @@ def test_a_relation_between_two_FAILING_answers_says_so(self, tmp_path): ), caveated.lines -#: A head NO server dispatches, standing in for the first real Go-only route. The -#: `go_only` machinery has to be proved before any such route exists, so it is proved -#: on this one — never by adding a public endpoint to make a test pass. -SYNTHETIC_GO_ONLY_HEAD = "synthetic-go-only" -SYNTHETIC_GO_ONLY_ROUTE = f"GET {SYNTHETIC_GO_ONLY_HEAD}" -SYNTHETIC_GO_ONLY_WHY = ( - "a synthetic Go-only route used only to prove the go_only declaration is " - "honoured by the oracle-side validator and the runner" -) - - -def _go_only_row(**overrides) -> dict: - row = { - "id": "synthetic-go-only-read", - "phase": "read", - "method": "GET", - "target": f"/api/v1/{SYNTHETIC_GO_ONLY_HEAD}/alpha-notes", - "principal": "wide-reader", - "why": "a synthetic row for the go_only machinery's own tests", - "go_only": True, - "go_only_why": SYNTHETIC_GO_ONLY_WHY, - } - row.update(overrides) - return {k: v for k, v in row.items() if v is not None} - - -def _raw_with(row: dict) -> dict: - """The real corpus with `row` inserted at the head of the READ phase.""" - raw = _raw_corpus() - raw["cases"].insert(0, row) - return raw - - -class TestTheGoOnlyMark: - """🔴 THE MIRROR OF `oracle_only`: A ROUTE ONLY THE GO SERVER SERVES, DECLARED. - - Decision 3 of the arcs/sessions plan puts new routes in `cmd/cairn-server` and not - in the oracle. Before this mark, such a route's rows were refused by the shrink half - of the ledger ("addresses routes the server no longer declares") with no way to say - the divergence was intended. Each guard below is shown RED on the case it must - refuse, asserting on ITS OWN message, beside the GREEN declared case. - """ - - def test_GREEN_a_go_only_row_for_a_route_the_oracle_lacks_is_accepted(self, tmp_path): - corpus = _corpus_from(_raw_with(_go_only_row()), tmp_path) - # The real corpus's own go_only routes, spelled by hand, plus the synthetic one. - assert cases_mod.go_only_routes(corpus) == { - SYNTHETIC_GO_ONLY_ROUTE, "GET sessions", "HEAD sessions", "GET arcs", "HEAD arcs", - "GET arc", "HEAD arc", "PUT arc", "GET sources", "HEAD sources", - "GET whoami", "HEAD whoami", - } - # …and it is NOT counted as oracle coverage, so the oracle's ledger is unmoved. - assert cases_mod.addressed_routes(corpus) == EXPECTED_ROUTES - - def test_RED_the_same_row_UNMARKED_is_refused_as_a_route_the_oracle_lacks(self, tmp_path): - """The behaviour this slice exists to make declarable, unchanged for an - undeclared row: an unmarked row for a route the oracle does not serve is the - silent-divergence case, and it still fails.""" - row = _go_only_row(go_only=None, go_only_why=None) - with pytest.raises(cases_mod.CorpusError) as exc: - _corpus_from(_raw_with(row), tmp_path) - assert "addresses routes the server no longer declares" in str(exc.value) - assert SYNTHETIC_GO_ONLY_ROUTE in str(exc.value) - - def test_RED_a_go_only_mark_on_a_route_the_ORACLE_declares_is_refused(self, tmp_path): - """The stale-declaration direction: the oracle grew the route (here: it always - had it), so the mark hides a comparison.""" - row = _go_only_row(target="/api/v1/recall/alpha-notes") - with pytest.raises(cases_mod.CorpusError) as exc: - _corpus_from(_raw_with(row), tmp_path) - assert "rows marked go_only address routes the ORACLE declares" in str(exc.value) - assert "GET recall" in str(exc.value) - - def test_the_oracle_grew_check_is_REACHABLE_before_the_coverage_check(self, corpus, tmp_path): - """🔴 ORDER. The only rows for the synthetic route are `go_only`, so when the - oracle starts declaring it the coverage check ("never addresses") would fire - first with the wrong diagnosis if it ran first. Measured by asserting on THIS - message with the coverage condition also true.""" - marked = _corpus_from(_raw_with(_go_only_row()), tmp_path) - with pytest.raises(cases_mod.CorpusError) as exc: - cases_mod.validate_corpus( - marked, routes=EXPECTED_ROUTES | {SYNTHETIC_GO_ONLY_ROUTE} - ) - assert "address routes the ORACLE declares" in str(exc.value) - assert "never addresses" not in str(exc.value) - - def test_RED_a_mark_with_no_reason_is_refused(self, tmp_path): - with pytest.raises(cases_mod.CorpusError) as exc: - _corpus_from(_raw_with(_go_only_row(go_only_why=" ")), tmp_path) - assert "is marked go_only and states no reason" in str(exc.value) - - def test_RED_a_reason_with_no_mark_is_refused(self, tmp_path): - with pytest.raises(cases_mod.CorpusError) as exc: - _corpus_from(_raw_with(_go_only_row(go_only=None)), tmp_path) - assert "states a go_only reason but is not marked go_only" in str(exc.value) - - def test_RED_both_marks_on_one_row_is_refused(self, tmp_path): - row = _go_only_row(oracle_only=True, oracle_only_why="synthetic") - with pytest.raises(cases_mod.CorpusError) as exc: - _corpus_from(_raw_with(row), tmp_path) - assert "BOTH go_only and oracle_only" in str(exc.value) - - def test_RED_go_only_on_a_negative_route_row_is_refused(self, tmp_path): - with pytest.raises(cases_mod.CorpusError) as exc: - _corpus_from(_raw_with(_go_only_row(negative_route=True)), tmp_path) - assert "go_only AND negative_route" in str(exc.value) - - def test_RED_go_only_on_a_row_addressing_no_api_route_is_refused(self, tmp_path): - with pytest.raises(cases_mod.CorpusError) as exc: - _corpus_from(_raw_with(_go_only_row(target="/healthz")), tmp_path) - assert "is marked go_only but addresses no /api/v1/ route" in str(exc.value) - - def test_the_ORACLE_run_skips_a_go_only_row_and_REPORTS_it(self, tmp_path): - """A go-only row is skipped against the oracle — declared, counted, printed — - and the rest of the run is untouched: 0 failures. The request is still - ISSUED, which is why `requests` grows by one.""" - corpus = _corpus_from(_raw_with(_go_only_row()), tmp_path) - outcome = suite.run_against_oracle(corpus=corpus) - assert outcome.failures == [] - assert sorted(outcome.skipped) == sorted( - ("synthetic-go-only-read",) + GO_ONLY_IDS - ) - line = f"SKIP synthetic-go-only-read (go-only: {SYNTHETIC_GO_ONLY_WHY})" - assert line in outcome.lines - summary = [ln for ln in outcome.lines if ln.startswith("SUMMARY")][0] - assert f"skipped={1 + len(GO_ONLY_IDS)} [synthetic-go-only-read," in summary - assert outcome.requests == len(cases_mod.load_corpus().cases) + 1 + 1 - - def test_a_NON_oracle_run_COMPARES_a_go_only_row(self, tmp_path): - """…and the mirror: against anything that is not the oracle the row is - compared, not skipped. The oracle stands in for "a port" here, so the - comparison reaches `read_golden` for a row nobody recorded and refuses — which - is the observable proof the row was not skipped.""" - corpus = _corpus_from(_raw_with(_go_only_row()), tmp_path) - with tempfile.TemporaryDirectory(prefix="cairn-conformance-") as td: - with oracle.running_oracle(Path(td)) as ora: - with pytest.raises(wire.WireError) as exc: - suite.run( - ora.base_url, ora.token_file, GOLDEN, corpus, - assert_oracle_specific=False, - ) - assert "no golden for case 'synthetic-go-only-read'" in str(exc.value) - - def test_a_skipped_go_only_relation_member_is_labelled_go_only(self, tmp_path): - corpus = _corpus_from(_raw_with(_go_only_row()), tmp_path) - assert suite.skip_label(corpus, "synthetic-go-only-read") == "go-only" - assert suite.skip_label(corpus, "post-bullets-not-json") == "oracle-specific" - - def test_generate_records_NO_golden_for_a_go_only_row(self, tmp_path): - """The oracle's only answer to a Go-only route is its no-route 404; recording - it would file that as the contract. Generated into a scratch directory, so the - committed goldens are untouched.""" - corpus = _corpus_from(_raw_with(_go_only_row()), tmp_path) - out = tmp_path / "golden" - outcome = suite.generate(out, corpus) - assert not (out / "synthetic-go-only-read.json").exists() - assert any( - ln.startswith("SKIP synthetic-go-only-read (go-only: ") for ln in outcome.lines - ) - # The positive control: generate DID record the rest — every row but the real - # go_only ones, which the oracle does not record either. - assert len(list(out.glob("*.json"))) == ( - len(cases_mod.load_corpus().cases) - len(GO_ONLY_IDS) - ) - assert not [p for p in out.glob("*.json") if p.stem in GO_ONLY_IDS] - - -class TestTheGoOnlyGoldensAreRecordedFromGoAndSaySo: - """🔴 THE RECORDER S0 LEFT OPEN (the plan's ledger item 4). A `go_only` golden is - recorded from the Go server by `run_go.sh record-go-only` and stamped - `recorded_from: cmd/cairn-server` — a CHANGE DETECTOR, never an oracle witness — and - `run` refuses a golden whose stamp disagrees with its row's mark.""" - - def test_every_committed_golden_carries_the_provenance_its_row_declares(self, corpus): - stamped = [] - for case in corpus.cases: - golden = wire.read_golden(GOLDEN, case.id) - assert suite.check_golden_provenance(case, golden) is None, case.id - if "recorded_from" in golden: - stamped.append(case.id) - # The positive control, spelled by hand: exactly the go_only rows are stamped. - assert sorted(stamped) == sorted(GO_ONLY_IDS) - - def test_RED_a_go_only_golden_without_the_stamp_is_refused(self, corpus): - case = corpus.by_id("sessions-authorized") - golden = {k: v for k, v in wire.read_golden(GOLDEN, case.id).items() - if k != "recorded_from"} - problem = suite.check_golden_provenance(case, golden) - assert problem and "carries recorded_from=None" in problem - - def test_RED_an_oracle_golden_WITH_the_stamp_is_refused(self, corpus): - case = corpus.by_id("recall-authorized") - golden = dict(wire.read_golden(GOLDEN, case.id)) - golden["recorded_from"] = suite.GO_ONLY_RECORDED_FROM - problem = suite.check_golden_provenance(case, golden) - assert problem and "its golden is the ORACLE's" in problem - - def test_the_recorder_REFUSES_a_server_that_does_not_serve_the_route(self, tmp_path): - """Pointed at the ORACLE — which answers every Go-only row with its no-route 404 - — the recorder must refuse rather than file that 404 as the contract, and must - write nothing.""" - out = tmp_path / "golden" - with tempfile.TemporaryDirectory(prefix="cairn-conformance-") as td: - with oracle.running_oracle(Path(td)) as ora: - with pytest.raises(suite.SuiteError) as exc: - suite.record_go_only(ora.base_url, ora.token_file, out) - assert "no go_only row addressing GET sessions got a 2xx" in str( - exc.value) - assert not out.exists() or not list(out.glob("*.json")) - - class TestARelationCannotBeSatisfiedByTwoSERVERERRORS: """🔴 THE CAVEAT ABOVE ANNOTATES A PASS; IT DOES NOT WITHHOLD ONE — so the two report relations really did report a property over four members that all answered @@ -884,21 +576,6 @@ def test_it_is_NOT_asserted_where_it_could_not_fail(self, corpus): assert outcome.assertions == 0 assert got == 99 - def test_a_server_that_understates_every_length_is_caught(self, tmp_path): - """The live negative control for the framing claim, and the measurement - that made the read-to-EOF case necessary: with only the malformed-target - raw case in the corpus, this mutation failed exactly ONE framing check and - no report at all.""" - server_py = mutate.mutated_server( - tmp_path / "tree", - 'self.send_header("Content-Length", str(len(body)))', - 'self.send_header("Content-Length", str(max(0, len(body) - 1)))', - ) - outcome = suite.run_against_oracle(server_py=server_py) - framing = [f for f in outcome.failures if "smuggling primitive" in f] - assert len(framing) >= 2, framing - assert any(f.startswith("raw-recall-read-to-eof") for f in framing) - def test_a_head_with_a_shorter_length_than_its_get_is_caught(self, corpus): outcome = suite.Outcome() outcome.raw_lengths = { @@ -940,10 +617,10 @@ def test_a_hand_edited_golden_is_refused(self, tmp_path): assert "INTERNALLY INCONSISTENT" in str(exc.value) assert "generated, never hand-written" in str(exc.value) - def test_a_missing_golden_names_the_regeneration_command(self, tmp_path): + def test_a_missing_golden_names_the_record_command(self, tmp_path): with pytest.raises(wire.WireError) as exc: wire.read_golden(tmp_path, "health-unauthenticated") - assert "suite.py generate" in str(exc.value) + assert "run_go.sh record health-unauthenticated" in str(exc.value) class TestTheLeakGuard: @@ -969,8 +646,8 @@ def test_mtimes_are_set_from_the_declaration(self, tmp_path): """🔴 THE ONE THING GIT CANNOT STORE. The snapshot contract depends on entry mtimes to sub-second precision, so a build that forgot to set them would produce a store whose order is whatever order the loop ran in.""" - world = oracle.load_world() - root = oracle.build_store(tmp_path / "store", world) + world = fixture.load_world() + root = fixture.build_store(tmp_path / "store", world) for entry in world["entries"]: declared = entry["mtime"] actual = (root / entry["path"]).stat().st_mtime @@ -980,17 +657,17 @@ def test_two_entries_share_a_whole_second_and_differ_in_the_fraction(self): """The fixture shape that a normalized tar destroys. If this ever stops holding, the snapshot ordering assertion loses the only input it can be wrong about.""" - world = oracle.load_world() + world = fixture.load_world() mtimes = [e["mtime"] for e in world["entries"]] same_second = [m for m in mtimes if int(m) == int(mtimes[0])] assert len(same_second) >= 2 assert len(set(same_second)) == len(same_second) def test_the_token_file_round_trips_every_declared_principal(self, tmp_path): - world = oracle.load_world() - tokens = oracle.mint_tokens(world) - path = oracle.write_token_file(tmp_path / "tokens", tokens, world) - found = oracle.principals_from_token_file(path, world) + world = fixture.load_world() + tokens = fixture.mint_tokens(world) + path = fixture.write_token_file(tmp_path / "tokens", tokens, world) + found = fixture.principals_from_token_file(path, world) assert set(found) == {p["name"] for p in world["principals"]} assert found["legacy"].identity is None assert found["narrow-reader"].scopes == ("beta-notes",) @@ -1000,243 +677,175 @@ def test_a_token_file_missing_a_principal_is_refused(self, tmp_path): as if it were the contract.""" path = tmp_path / "tokens" path.write_text("a" * 50 + " wide-reader alpha-notes\n", encoding="utf-8") - with pytest.raises(oracle.OracleError) as exc: - oracle.principals_from_token_file(path) + with pytest.raises(fixture.FixtureError) as exc: + fixture.principals_from_token_file(path) assert "not configured for this corpus" in str(exc.value) def test_no_declared_token_is_a_literal(self): """🔴 A REAL-LOOKING CREDENTIAL IS A FINDING IN A PUBLIC REPO whether or not it ever authenticated anything. The world declares principals, never tokens; the tokens are minted per run.""" - world = oracle.load_world() + world = fixture.load_world() for spec in world["principals"]: assert "token" not in spec, spec["name"] # Nothing in the declaration is long enough to BE a credential: the # server's floor is 43 characters of `[A-Za-z0-9_-]`. text = (ROOT / "tests" / "conformance" / "world.json").read_text("utf-8") assert re.search(r"[A-Za-z0-9_-]{43,}", text) is None - first = oracle.mint_tokens() - second = oracle.mint_tokens() + first = fixture.mint_tokens() + second = fixture.mint_tokens() assert set(first.values()) & set(second.values()) == set() assert all(len(t) >= 43 for t in first.values()) # --------------------------------------------------------------------------- -# The instrument, validated end to end. +# The frozen corpus, and the goldens recorded from the Go server. # --------------------------------------------------------------------------- -class TestTheSuitePassesAgainstTheOracle: - def test_it_passes_and_it_issued_something(self): - """🔴 THE POSITIVE CONTROL, AND THE COUNTS ARE REPORTED. `0 failures` - over 0 requests is the failure mode this asserts against.""" - outcome = suite.run_against_oracle() - assert outcome.failures == [] - assert outcome.requests == len(cases_mod.load_corpus().cases) + 1 # + canary - assert outcome.assertions > 300 - result_lines = [ - ln for ln in outcome.lines if ln.startswith(("PASS ", "FAIL ")) - ] - skip_lines = [ln for ln in outcome.lines if ln.startswith("SKIP ")] - # Read the CONTENT, not an exit code: count the runner's own lines. Every line - # but SUMMARY is a verdict or a declared go-only skip — one per go_only case and - # one per relation entry naming such a case. - assert len(skip_lines) == len(GO_ONLY_IDS) + GO_ONLY_RELATION_SKIPS - assert all("go-only" in ln for ln in skip_lines) - assert len(result_lines) == len(outcome.lines) - 1 - len(skip_lines) - assert not [ln for ln in result_lines if ln.startswith("FAIL")] - - def test_adding_a_case_moves_the_numbers(self, tmp_path): - """…and the count is not a constant somebody typed: a corpus with one - row removed issues one fewer request and makes fewer assertions.""" - raw = _raw_corpus() - full = cases_mod.load_corpus() - # Drop a row nothing else references. - raw["cases"] = [c for c in raw["cases"] if c["id"] != "recall-mode-full"] - smaller = _corpus_from(raw, tmp_path) - assert len(smaller.cases) == len(full.cases) - 1 - outcome = suite.run_against_oracle(corpus=smaller) - assert outcome.failures == [] - assert outcome.requests == len(full.cases) # one fewer case, plus the canary - - -class TestTheSuiteGoesRedOnARealMutation: - """🔴 THE NEGATIVE CONTROL. Realistic mutations, not textbook ones.""" - - #: `(label, old, new, at_least)` — `at_least` is the smallest number of - #: failures the mutation must produce. Deliberately not the exact count: the - #: claim is `this is caught`, and pinning the blast radius would make every - #: new case in the corpus a change to this table. - MUTATIONS = [ - pytest.param( - '404, b"not found\\n", headers={"X-Store-Status": "not-found"}', - '403, b"not found\\n", headers={"X-Store-Status": "not-found"}', - id="one-status-code-moved", - ), - pytest.param( - ' "X-Store-Exit": str(code),\n', - "", - id="one-header-dropped", - ), - pytest.param( - "info.mtime = st.st_mtime", - "info.mtime = int(st.st_mtime)", - id="snapshot-mtimes-truncated-to-whole-seconds", - ), - pytest.param( - 'selected.append((entry, f"{scope.name}/{entry.name}"))', - 'selected.insert(0, (entry, f"{scope.name}/{entry.name}"))', - id="snapshot-members-reordered", - ), - pytest.param( - "raise ValueError(f\"{name} must be an integer, got {values[-1]!r}\") from None", - "return None", - id="a-bad-query-parameter-silently-defaults", - ), - ] - - def test_the_unmutated_copy_passes(self, tmp_path): - """🔴 THE PAIR THE NEGATIVE CONTROLS NEED. Same copy mechanics, same - symlinked `lib/`, no edit — so a red below is the MUTATION and not the - harness.""" - server_py = mutate.unmutated_server(tmp_path / "tree") - outcome = suite.run_against_oracle(server_py=server_py) - assert outcome.failures == [] - assert outcome.requests > 50 - - @pytest.mark.parametrize("old,new", MUTATIONS) - def test_a_mutation_is_caught(self, tmp_path, old, new): - server_py = mutate.mutated_server(tmp_path / "tree", old, new) - outcome = suite.run_against_oracle(server_py=server_py) - assert outcome.failures, "the mutation was NOT caught" - assert [ln for ln in outcome.lines if ln.startswith("FAIL")] - - def test_a_mutation_pattern_that_matches_nothing_is_refused(self, tmp_path): - """🔴 THE MUTATION SWEEP'S OWN FALSE SURVIVED. A pattern that matched - nothing yields an UNMUTATED server, which passes — and the run would be - reported as `this mutation was not caught`.""" - with pytest.raises(mutate.MutationError) as exc: - mutate.mutated_server(tmp_path / "tree", "this text is not in server.py", "x") - assert "occurs 0 time(s)" in str(exc.value) - - -class TestTheRelationsCannotBeRegeneratedAway: - """🔴 THE CLAIM A PER-RESPONSE GOLDEN CANNOT MAKE. - - Each of these mutations is one a fresh set of goldens would ABSORB: record - the divergent responses, compare each to its own file, and the suite is green - over a server that now discriminates. The relational assertions are the only - thing standing in the way, so the test is that `generate` REFUSES. - """ +#: 🔴 THE ROWS WHOSE GOLDENS WERE RECORDED FROM THE GO SERVER, SPELLED BY HAND — never +#: derived from the goldens under test, so a golden that lost (or gained) its stamp moves +#: the assertion that reads this. They are the routes added after the oracle stopped +#: being extended (sessions, the arc registry, code sources, whoami). A new row's golden +#: is recorded with `run_go.sh record` and moves this set in its commit. +GO_RECORDED_IDS = ( + "sessions-authorized", "sessions-authorized-head", "sessions-legacy-token", + "sessions-refused-scope", "sessions-absent-scope", "sessions-empty-scope", + "sessions-unreadable-scope", "sessions-unauthenticated", "sessions-arity-too-long", + "arcs-authorized", "arcs-authorized-head", "arcs-declared-elsewhere", "arcs-hidden-home", + "arcs-legacy-token", "arcs-refused-scope", "arcs-absent-scope", "arcs-no-arc", + "arcs-unauthenticated", + "sources-authorized", "sources-authorized-head", "sources-undeclared", + "sources-refused-scope", "sources-absent-scope", "sources-unauthenticated", + "whoami-authorized", "whoami-authorized-head", "whoami-narrow-reader", + "whoami-legacy-token", "whoami-unauthenticated", + "arcs-check-all-scopes", "arcs-check-scoped", + "arcs-check-refused-scope", "arcs-check-absent-scope", + "arc-authorized", "arc-authorized-head", "arc-unregistered-slug", + "arc-refused-home", "arc-absent-home", "arc-unauthenticated", "arc-arity-too-short", + "put-arc-registered", "put-arc-unchanged", "put-arc-malformed", "put-arc-refused-declared", + "put-arc-refused-home", "put-arc-absent-home", "put-arc-legacy", "put-arc-unauthenticated", +) - def test_a_refused_scope_that_leaks_the_scope_revision_is_refused(self, tmp_path): - server_py = mutate.mutated_server( - tmp_path / "tree", - "if visible_scopes is not None and rc.normalize_ref(scope) not in {", - "if False and rc.normalize_ref(scope) not in {", - ) - outcome = suite.run_against_oracle(server_py=server_py) - red = [ln for ln in outcome.lines if ln.startswith("FAIL relation refused")] - assert red, "the refused-equals-absent relation did not fire" - with pytest.raises(suite.SuiteError) as exc: - suite.generate(tmp_path / "golden", server_py=server_py) - assert "violates a relational property" in str(exc.value) - assert "enumeration API" in str(exc.value) - - def test_a_head_that_reports_a_length_of_zero_is_refused(self, tmp_path): - """The classic naive-HEAD bug: no body, so report no length. The goldens - CANNOT see it on the report routes — `Content-Length` is normalized away - there, because its value is host-dependent — so the HEAD/GET relation is - the only thing that does.""" - server_py = mutate.mutated_server( - tmp_path / "tree", - 'self.send_header("Content-Length", str(len(body)))', - 'self.send_header("Content-Length", ' - 'str(0 if self.command == "HEAD" else len(body)))', + +class TestTheFrozenCorpus: + """🔴 THE GOLDENS RECORDED FROM THE RETIRED ORACLE ARE A FIXED CORPUS. + + Nothing can re-record one: the reference server is deleted, and re-recording from the + Go server would certify Go against itself. So the unstamped set is pinned by count + and content, a stamp may name only `cmd/cairn-server`, and `record` refuses to + overwrite anything.""" + + def test_the_committed_corpus_is_the_frozen_one(self): + assert suite.check_frozen_corpus(GOLDEN) == [] + assert suite.frozen_corpus_digest(GOLDEN) == ( + suite.FROZEN_ORACLE_GOLDENS, suite.FROZEN_ORACLE_DIGEST ) - outcome = suite.run_against_oracle(server_py=server_py) - red = [ln for ln in outcome.lines if ln.startswith("FAIL relation head")] - assert red, "the head-matches-get relation did not fire" + + def test_the_frozen_count_is_the_literal_128(self): + """The constant spelled by hand once more, so an edit to it is a visible diff + here as well as in `suite.py`.""" + assert suite.FROZEN_ORACLE_GOLDENS == 128 + + def test_exactly_the_go_recorded_rows_are_stamped(self, corpus): + stamped = [] + for case in corpus.cases: + golden = wire.read_golden(GOLDEN, case.id) + assert suite.check_golden_provenance(case, golden) is None, case.id + if "recorded_from" in golden: + assert golden["recorded_from"] == "cmd/cairn-server", case.id + stamped.append(case.id) + assert sorted(stamped) == sorted(GO_RECORDED_IDS) + assert len(corpus.cases) == len(GO_RECORDED_IDS) + suite.FROZEN_ORACLE_GOLDENS + + def _copy(self, tmp_path: Path) -> Path: + dest = tmp_path / "golden" + dest.mkdir() + for path in GOLDEN.glob("*.json"): + (dest / path.name).write_bytes(path.read_bytes()) + return dest + + def test_RED_an_edited_frozen_golden_is_refused(self, tmp_path): + golden = self._copy(tmp_path) + path = golden / "recall-authorized.json" + path.write_text(path.read_text("utf-8").replace('"status"', '"status" ', 1), "utf-8") + problems = suite.check_frozen_corpus(golden) + assert len(problems) == 1 and "one of them was edited" in problems[0] + + def test_RED_a_deleted_frozen_golden_is_refused(self, tmp_path): + golden = self._copy(tmp_path) + (golden / "recall-authorized.json").unlink() + problems = suite.check_frozen_corpus(golden) + assert len(problems) == 1 and "127 unstamped golden(s)" in problems[0] + + def test_RED_a_NEW_unstamped_golden_is_refused(self, tmp_path): + """A golden added without a stamp would claim the reference implementation + recorded it — which nothing can do any more.""" + golden = self._copy(tmp_path) + rec = json.loads((golden / "sessions-authorized.json").read_text("utf-8")) + del rec["recorded_from"] + rec["case"] = "synthetic-new-row" + (golden / "synthetic-new-row.json").write_text(wire.dumps(rec), "utf-8") + problems = suite.check_frozen_corpus(golden) + assert len(problems) == 1 and "129 unstamped golden(s)" in problems[0] + + def test_a_stamped_golden_moves_neither_number(self, tmp_path): + """The control on the three REDs: a Go-recorded golden is outside the freeze, so + adding one is not refused — the count is of the frozen set and nothing else.""" + golden = self._copy(tmp_path) + rec = json.loads((golden / "sessions-authorized.json").read_text("utf-8")) + rec["case"] = "synthetic-new-row" + (golden / "synthetic-new-row.json").write_text(wire.dumps(rec), "utf-8") + assert suite.check_frozen_corpus(golden) == [] + + def test_RED_a_stamp_naming_anything_else_is_refused(self, corpus): + case = corpus.by_id("recall-authorized") + golden = dict(wire.read_golden(GOLDEN, case.id)) + golden["recorded_from"] = "server/server.py" + problem = suite.check_golden_provenance(case, golden) + assert problem and "nothing else records one" in problem + + def test_record_REFUSES_to_overwrite_a_frozen_golden(self, tmp_path): + """🔴 THE ONE THING `record` MUST NEVER DO. It refuses before it sends a single + request, so no server is needed to prove it.""" with pytest.raises(suite.SuiteError) as exc: - suite.generate(tmp_path / "golden", server_py=server_py) - assert "violates a relational property" in str(exc.value) - - def test_a_401_that_says_why_is_refused(self, tmp_path): - server_py = mutate.mutated_server( - tmp_path / "tree", - " self._audit(path, 401, status)\n self._unauthorized()", - " self._audit(path, 401, status)\n" - " self._respond(401, UNAUTHORIZED_BODY, headers={" - "\"WWW-Authenticate\": 'Bearer realm=\"subsystem-store\"', " - '"X-Store-Status": status})', - ) - outcome = suite.run_against_oracle(server_py=server_py) - red = [ln for ln in outcome.lines if ln.startswith("FAIL relation uniform-401")] - assert red, "the uniform-401 relation did not fire" + suite.record("http://127.0.0.1:9", tmp_path / "tokens", + ["recall-authorized"], GOLDEN) + assert "already has a golden" in str(exc.value) + assert "never re-recorded" in str(exc.value) + + def test_record_REFUSES_an_oracle_only_row(self, tmp_path): with pytest.raises(suite.SuiteError) as exc: - suite.generate(tmp_path / "golden", server_py=server_py) - assert "violates a relational property" in str(exc.value) - - -class TestTheGoldensAreGenerated: - """INVARIANT GUARDS, and the determinism proof made permanent.""" - - def test_two_generator_runs_agree_and_match_what_is_committed(self, tmp_path): - """🔴 DETERMINISM IS PROVEN, NOT ASSUMED, AND THE SAME RUN PROVES THE - GOLDENS ON DISK ARE GENERATED. Two independent runs — fresh world, fresh - oracle, fresh tokens, a later wall clock — must agree with each other AND - with the committed set. Any instability that survives the declared - normalizations is a defect in the suite, not noise to retry past.""" - first = tmp_path / "one" - second = tmp_path / "two" - suite.generate(first) - suite.generate(second) - names = sorted(p.name for p in first.glob("*.json")) - assert names == sorted(p.name for p in second.glob("*.json")) - # The committed set is the oracle's PLUS the go_only goldens, which the oracle - # never records (`run_go.sh record-go-only` does, from the Go server). - go_only = {f"{i}.json" for i in GO_ONLY_IDS} - committed = sorted(p.name for p in GOLDEN.glob("*.json")) - assert go_only <= set(committed) - assert names == [n for n in committed if n not in go_only] - unstable, uncommitted = [], [] - for name in names: - a = (first / name).read_text(encoding="utf-8") - b = (second / name).read_text(encoding="utf-8") - c = (GOLDEN / name).read_text(encoding="utf-8") - if a != b: - unstable.append(name) - if a != c: - uncommitted.append(name) - assert unstable == [] - assert uncommitted == [], ( - "the committed goldens are not what the generator produces. Run " - "`python3 tests/conformance/suite.py generate` and commit the diff." - ) + suite.record("http://127.0.0.1:9", tmp_path / "tokens", + ["post-bullets-not-json"], tmp_path / "empty") + assert "marked oracle_only" in str(exc.value) - def test_a_different_host_label_produces_the_same_goldens(self, tmp_path): - """🔴 THE SECOND POINT ON THE DIMENSION THAT ACTUALLY MOVED, and this is - the check that found a real defect rather than confirming an assumption. - - Two generator runs on ONE host agree even when a field depends on the - host, so a same-host determinism check is STRUCTURALLY BLIND to - host-dependence. Changing only `CAIRN_HOST` moved 21 goldens: the body - normalizations had removed the machine identity from the BODY, but - `Content-Length` counts the bytes the server sent — and the identity - varies in LENGTH, not merely in value. `report-content-length` plus - `check_framing` is the fix; this test is what would have caught it. - """ - out = tmp_path / "other-host" - suite.generate( - out, extra_env={"CAIRN_HOST": "a-completely-different-and-longer-label"} - ) - differing = [ - p.name - for p in sorted(out.glob("*.json")) - if p.read_text(encoding="utf-8") - != (GOLDEN / p.name).read_text(encoding="utf-8") - ] - assert differing == [], ( - "these goldens depend on the machine that generated them, so CI — or " - "anyone else's checkout — cannot reproduce them" - ) + def test_record_REFUSES_an_empty_request(self, tmp_path): + with pytest.raises(suite.SuiteError) as exc: + suite.record("http://127.0.0.1:9", tmp_path / "tokens", [], GOLDEN) + assert "no case id named" in str(exc.value) + + def test_run_and_record_REQUIRE_the_server_binary(self, capsys): + """🔴 `--server-binary` is what keeps the route ledger inside the gate: without + it the corpus would be replayed unvalidated against the routes the server + declares.""" + for command in ("run", "record"): + argv = [command, "--base-url", "http://127.0.0.1:9", "--token-file", "t"] + if command == "record": + argv.append("recall-authorized") + with pytest.raises(SystemExit) as exc: + suite.main(argv) + assert exc.value.code == 2 + assert "--server-binary" in capsys.readouterr().err + + +def test_the_suite_does_not_import_a_deleted_module(): + """The oracle-booting module and the mutation helper went with the oracle; a + stale import would make the suite unusable rather than wrong, but say so here.""" + root = ROOT / "tests" / "conformance" + assert not (root / "oracle.py").exists() + assert not (root / "mutate.py").exists() + for path in root.glob("*.py"): + text = path.read_text("utf-8") + assert "import oracle" not in text and "oracle import" not in text, path.name + assert os.access(root / "run_go.sh", os.X_OK) From 190fd3eee32ff16ea1d3e627761ff2b9007607e3 Mon Sep 17 00:00:00 2001 From: Zachary Lowden Date: Thu, 3 Dec 2026 18:50:27 -0600 Subject: [PATCH 02/15] retire the Python oracle: delete the client, lib/, server.py and their gates Phase 5 of the v1 event-log plan (P8): the Go pod is deployed and the Go client is the default, so the Python implementation and everything that compared it with the Go one is deleted. Deleted: the `cairn` script, lib/, server/server.py + Dockerfile + build-push.sh + verify-byte-identity.sh, tests/parity/, tests/dualrun/, and every Python test whose subject was those (store API, CLI, write, instances, doctor, read store/recall/resolver, read ledger, entry shape, requirements, trailer strip, marker oracle sweep), plus the generators that recorded from them (citation_ids.py, marker_corpus.py) and the env_pin sanitizer, which no longer has a consumer. flake.nix drops packages.cairn, apps.cairn, packages.server-image and checks.client-resolves-its-lib; serverEnv is emptied (its three names were the Python pod's), so the Go image's Env is `serverEnv // { PATH; SSL_CERT_FILE; }`. Split, not dropped: - test_flake_image_matches_dockerfile.py: its live half (cmd/cairn-server defaults vs a Deployment, the image-env absence rule, the uid VALUE, the flake readers) is tests/test_server_deployment_defaults.py - the seed.sh tests (seed.sh is kept) are tests/test_seed.py - the CPython re.I folding-rune sweep is tests/test_cpython_re_folding_runes.py - test_env_aliases / test_tag_vocabulary / test_nuance_bullet_ceiling / test_citation_render: the Go side is now pinned against LITERALS Re-pointed, not deleted: test_go_client_ledgers and testlib/capability_ledger compare `cairn -verbs` / `cairn-server -routes` with the capability ledger; the flake's want-*.txt lists are folded and pinned to the same ledger. Frozen as contracts (recorded from the oracle at ec1b756): the reader fixture, the citation-id fixture (option (a)), the marker sweep fixture; each pinned by digest. reader_fixtures.py now only materialises the frozen world, byte-identical (125 files, bytes and mtimes) to the old builder's. Env aliases keep working; their removal anchor moved from "packages.cairn is retired" (now met) to a CHANGELOG-announced release, and the rendered warning is pinned as a whole sentence (mutation-tested: an argument swap goes red). memeval's synthetic world answers its l0 arm with the Go client (18/18). routing_mutants loses its Python rows; its positive control is a Go row. Co-Authored-By: Claude Opus 5.5 (1M context) --- cairn | 2950 -- flake.nix | 789 +- internal/envalias/envalias.go | 64 +- internal/envalias/envalias_test.go | 29 +- internal/report/reader_fixtures_test.go | 21 +- internal/report/testdata/reader_fixtures.json | 17 +- internal/store/citationid_test.go | 45 +- internal/store/marker.go | 8 +- internal/store/markersweep_test.go | 22 +- internal/store/openness.go | 4 +- internal/write/tagvocab.go | 12 +- internal/write/tagvocab_test.go | 12 +- lib/README.md | 295 - lib/cairn_doctor.py | 709 - lib/cairn_instances.py | 568 - lib/entry_shape.py | 1414 - lib/env_aliases.py | 316 - lib/host_identity.py | 125 - lib/read_ledger.py | 167 - lib/subsystem_read_store.py | 279 - lib/subsystem_recall.py | 4827 ---- lib/subsystem_resolver.py | 3720 --- lib/timeouts.py | 36 - server/Dockerfile | 97 - server/Dockerfile.dockerignore | 8 - server/build-push.sh | 76 - server/server.py | 6002 ---- server/verify-byte-identity.sh | 701 - tests/citation_ids.py | 214 - tests/dualrun/README.md | 636 - tests/dualrun/genstore.py | 358 - tests/dualrun/harness.py | 1971 -- tests/dualrun/mutants.py | 282 - tests/marker_corpus.py | 274 - tests/memeval/world.py | 48 +- tests/parity/README.md | 744 - tests/parity/harness.py | 2207 -- tests/parity/hostile.py | 109 - tests/parity/world.py | 488 - tests/pytext_decode_replace.py | 7 +- tests/reader_fixtures.py | 1114 +- tests/routing_mutants.py | 236 +- tests/test_bullet_trailer_strip.py | 560 - tests/test_cairn_cli.py | 2800 -- tests/test_cairn_doctor.py | 1301 - tests/test_cairn_instances.py | 965 - tests/test_cairn_write.py | 1185 - tests/test_capability_ledger.py | 644 +- tests/test_citation_ids.py | 287 +- tests/test_citation_render.py | 653 +- tests/test_cpython_re_folding_runes.py | 79 + tests/test_dualrun_harness.py | 575 - tests/test_entry_shape_validate.py | 1248 - tests/test_env_aliases.py | 805 +- tests/test_env_pin.py | 393 - tests/test_flake_go_image_runtime_contract.py | 563 +- tests/test_flake_image_matches_dockerfile.py | 953 - tests/test_flake_ui_image_runtime_contract.py | 17 +- tests/test_go_client_ledgers.py | 326 +- tests/test_marker_oracle_sweep.py | 332 - tests/test_memeval_world.py | 24 +- tests/test_nuance_bullet_ceiling.py | 176 +- tests/test_parity_harness.py | 524 - tests/test_pytext_decode_replace.py | 6 +- tests/test_read_ledger.py | 232 - tests/test_reader_fixtures.py | 202 +- tests/test_requirements_provenance.py | 126 - tests/test_seed.py | 1143 + tests/test_server_deployment_defaults.py | 340 + tests/test_subsystem_read_store.py | 1064 - tests/test_subsystem_recall.py | 7239 ----- tests/test_subsystem_resolver.py | 3269 --- tests/test_subsystem_store_api.py | 23849 ---------------- tests/test_tag_vocabulary.py | 456 +- tests/testlib/cairn_source.py | 209 - tests/testlib/capability_ledger.py | 479 +- tests/testlib/env_pin.py | 194 - tests/testlib/envalias_go.py | 74 + tests/unchanged_output_capture.py | 526 - 79 files changed, 2757 insertions(+), 83062 deletions(-) delete mode 100755 cairn delete mode 100644 lib/README.md delete mode 100644 lib/cairn_doctor.py delete mode 100644 lib/cairn_instances.py delete mode 100644 lib/entry_shape.py delete mode 100644 lib/env_aliases.py delete mode 100644 lib/host_identity.py delete mode 100644 lib/read_ledger.py delete mode 100644 lib/subsystem_read_store.py delete mode 100644 lib/subsystem_recall.py delete mode 100644 lib/subsystem_resolver.py delete mode 100644 lib/timeouts.py delete mode 100644 server/Dockerfile delete mode 100644 server/Dockerfile.dockerignore delete mode 100755 server/build-push.sh delete mode 100755 server/server.py delete mode 100755 server/verify-byte-identity.sh delete mode 100644 tests/citation_ids.py delete mode 100644 tests/dualrun/README.md delete mode 100644 tests/dualrun/genstore.py delete mode 100644 tests/dualrun/harness.py delete mode 100644 tests/dualrun/mutants.py delete mode 100644 tests/marker_corpus.py delete mode 100644 tests/parity/README.md delete mode 100644 tests/parity/harness.py delete mode 100644 tests/parity/hostile.py delete mode 100644 tests/parity/world.py delete mode 100644 tests/test_bullet_trailer_strip.py delete mode 100644 tests/test_cairn_cli.py delete mode 100644 tests/test_cairn_doctor.py delete mode 100644 tests/test_cairn_instances.py delete mode 100644 tests/test_cairn_write.py create mode 100644 tests/test_cpython_re_folding_runes.py delete mode 100644 tests/test_dualrun_harness.py delete mode 100644 tests/test_entry_shape_validate.py delete mode 100644 tests/test_env_pin.py delete mode 100644 tests/test_flake_image_matches_dockerfile.py delete mode 100644 tests/test_marker_oracle_sweep.py delete mode 100644 tests/test_parity_harness.py delete mode 100644 tests/test_read_ledger.py delete mode 100644 tests/test_requirements_provenance.py create mode 100644 tests/test_seed.py create mode 100644 tests/test_server_deployment_defaults.py delete mode 100644 tests/test_subsystem_read_store.py delete mode 100644 tests/test_subsystem_recall.py delete mode 100644 tests/test_subsystem_resolver.py delete mode 100644 tests/test_subsystem_store_api.py delete mode 100644 tests/testlib/cairn_source.py delete mode 100644 tests/testlib/env_pin.py create mode 100644 tests/testlib/envalias_go.py delete mode 100644 tests/unchanged_output_capture.py diff --git a/cairn b/cairn deleted file mode 100755 index ceb4ae57..00000000 --- a/cairn +++ /dev/null @@ -1,2950 +0,0 @@ -#!/usr/bin/env python3 -"""`cairn` — the read-through client for the hosted subsystem store (phase 2). - -WHAT THIS IS FOR. The pod serves a read-only API; for a long time every request -it logged came from the session that built it, because **no client was ever -written**. This is that client. - -🔴 THE READER KEEPS ITS NO-NETWORK PROPERTY; THIS WRAPPER OWNS THE NETWORK. -`subsystem_recall.py` documents itself "READ-ONLY. No clock, no network, no git, -no prompt" and runs on the `/resume` hot path. Proposal §2d is explicit that a -recall must not become a live HTTP call: a DNS blip, a suspended laptop or a -cluster reconcile would turn "orient me" into an error, or — worse — into an -empty screen that reads like "nothing recorded". So `cairn` syncs the store into -a local cache and runs the **unmodified** reader against it. Nothing in -`lib/` is imported-and-patched, monkeypatched or forked here. - -🔴 WHY A STATE LINE IS PRINTED BEFORE EVERY REPORT, AND WHY IT IS NOT OPTIONAL. -The server prepends a provenance banner to every response for a measured reason -(`server.py::snapshot_freshness`): the public endpoint answered -`ALL 5 entries in alpha-toolkit/, none omitted` while the source held 9, and one served -entry was a 40-day-old copy of a file edited that morning. Nothing was wrong; -nothing was current either. Running the reader locally against a cache would -DROP that banner and reintroduce exactly that confusion, because the reader's -"none omitted" is a truthful claim about whatever bytes it was pointed at. So -this client states, in the output itself, which of four states produced it: - - live fetched just now exit 0 - cached (stale ) pod unreachable, served from cache exit 0 - scope-empty reached the store, genuinely nothing exit 0 - store-unreachable, no cache nothing was read at all exit 3 - -🔴 The fourth is the one that must never be collapsed into the third. `scope-empty` -and `store-unreachable` both "print no entries", and one of them is a lie. That is -the silent-zero class `obs-read` and `drift-check.sh` exist to defend against. - -Two codes sit outside that table because they are not READ outcomes: -`sync` returns 4 when it could not refresh though a cache survived (a refresh -that exits 0 on an outage is how a timer reports success forever), and any -command returns 5 when the server's archive is REFUSED — a link, a traversal -member, a duplicate, or a count disagreeing with the server's own header. 5 is -never absorbed into "served from cache"; an outage is benign and that is not. -Beyond those, a report exits with the READER's own code, so a scope whose -entries are all malformed still exits non-zero as it always did. - -🔴 AND THE WRITE VERBS ARE THE MIRROR IMAGE — `append`, `put` and `create` DO -NOT DEGRADE. The table above exists because a read must never report an outage as -an empty store. A write has the opposite obligation: there is no cache to answer -from and no such thing as a stale write, so an unreachable store is a REFUSED -write at exit 7, never a queued one and never a local one. Codes 6/7/8/9 -(refused / unreachable / precondition-failed / already-exists) are disjoint from -every read code precisely so a caller cannot read "nothing was displayed" as "the -bullet landed". The pod is the authority; this cache has none. See the WRITE PATH -block below the readers. - -🔴 `create` IS THE VERB THAT MAKES A NEW ENTRY, AND IT WAS ADDED LATE. -`append` and `put` both resolve an EXISTING ref, so the store had no -create primitive at all and the write protocol told sessions to write a -brand-new entry into the local `~/.claude//` tree. That was -correct while that tree WAS the store; after the read path moved to the pod -cache it meant the entry was dark to every reader. Measured: five -whole entries existed only on one host. `create` sends `If-None-Match: *`, so it -creates only if absent and REFUSES (exit 9) rather than overwriting. - -CONFIG: `~/.config/subsystem-store/env` (mode 0600) — `CAIRN_URL`, `CAIRN_TOKEN` -(`ENV_URL`/`ENV_TOKEN` below). Environment variables of the same name win, so a -test can point this at a throwaway server without touching the file. See -SECRETS.md. - -🔴 THE `SUBSYSTEM_STORE_*` SPELLINGS STILL WORK, IN BOTH PLACES. `env_aliases` -resolves `SUBSYSTEM_STORE_URL`/`SUBSYSTEM_STORE_TOKEN` as deprecated aliases — -as exported variables AND as keys of the file above — with the NEW name winning -and one stderr warning per process naming the replacement. The ledger, the -precedence rule and the removal anchor (`packages.cairn` retiring, at P8) are -`lib/env_aliases.py`; do not open-code a fallback here. - -🔴 MORE THAN ONE INSTANCE, AND NOTHING CHANGES UNTIL THERE IS ONE. The file -above is the `personal` instance; additional instances are ADDITIVE files at -`~/.config/subsystem-store/instances/.env`, each with its own cache root -and its own `.sync-stamp`. A scope is routed to an instance by a table the -OPERATOR supplies (`~/.config/subsystem-store/routes.json`, or `$CAIRN_ROUTES`) -— never by anything checked in here, because this program knows how to route -and nothing about who routes where. - -🔴 AN UNREGISTERED SCOPE REFUSES AT EXIT 11, NAMING THE SCOPE, ONCE THERE IS -MORE THAN ONE INSTANCE. It never falls back to one of several. A default would -silently recreate the failure this whole tool exists to close — a write landing -in a store nobody reads — and that one is found days later, by accident, if at -all. With ONE instance configured there is no second place a scope could go, so -nothing is labelled and every byte of output is what it was before any of this -existed — a routing TABLE being present does not change that, because a table -says where scopes live and not how many stores this host can reach. - -🔴 ONE EXCEPTION AT EVERY INSTANCE COUNT: a table entry naming an alias this -host has no config for REFUSES. That entry is a statement that the scope lives -somewhere this machine cannot reach, so resolving it to the sole instance would -be the misroute in its purest form. See `cairn_instances.Routing.alias_for`. -""" - -from __future__ import annotations - -import argparse -import fcntl -import hashlib -import io -import json -import os -import shutil -import sys -import tarfile -import tempfile -import time -import urllib.error -import urllib.request -import zlib -from pathlib import Path -from typing import Sequence -from urllib.parse import quote - -sys.path.insert(0, str(Path(__file__).resolve().parent / "lib")) - -from timeouts import unbounded_timeout_reason # noqa: E402 - - -def _mirror_root() -> "Path | None": - """The frozen pre-cutover store, if this deployment has one. - - 🔴 UNSET IS THE DEFAULT, and `doctor` reports NOT-OBSERVABLE rather than OK - for it. A deployment that migrated from a local store points this at the old - root so `doctor` can confirm its entry files are read-only; one that never - had a local store has nothing to name, and claiming "it does not exist" - about a path nobody configured would be a statement about the operator's - disk that this code cannot support. - """ - raw = os.environ.get("CAIRN_MIRROR_ROOT", "").strip() - return Path(raw).expanduser() if raw else None -import subsystem_recall as rc # noqa: E402 -import entry_shape # noqa: E402 -from entry_shape import scope_for_repo # noqa: E402 - -# 🔴 THE CACHE PATH AND THE STAMP NAME ARE IMPORTED, NOT DECLARED. They used to -# live here, which made this file the only thing that knew where a host reads the -# store from — and the readers (`subsystem_recall.py`'s CLI, `service_recon.py`) -# went on pointing at the FROZEN pre-cutover mirror for a day because nothing -# they imported could tell them otherwise. One definition, in -# `subsystem_read_store`; the writer and every reader now move together. -# 🔴 THE MODULE, NOT `from … import DEFAULT_CACHE_ROOT`. That spelling is the one -# `read_store_root`'s own docstring names as defeating a test's repointing: it -# binds the value at IMPORT, so a later `monkeypatch.setattr(rs, -# "DEFAULT_CACHE_ROOT", …)` moves the reader and leaves this WRITER pointed at -# the operator's real cache. Nothing depended on that yet — which is exactly when -# it is cheap to fix. `build_parser` calls the accessor instead. -import subsystem_read_store as _read_store # noqa: E402 -import subsystem_resolver # noqa: E402 -from subsystem_read_store import SYNC_STAMP # noqa: E402 -# 🔴 THE MODULE, FOR THE SAME REASON AS `_read_store` ABOVE. `cairn_instances` -# resolves paths from `Path.home()` and the environment at CALL time, so a -# `from … import config_path` here would bind the function but a -# `from … import DEFAULT_*` would bind a value — and the config path is exactly -# the kind of fact a test repoints. One import style for both. -import cairn_instances # noqa: E402 -import env_aliases # noqa: E402 -import read_ledger # noqa: E402 - -# The two names that configure the default instance, in their current spelling. Each -# reads from an exported variable OR from a key of the config file, and each has a -# deprecated `SUBSYSTEM_STORE_*` alias `env_aliases` resolves. They are constants rather -# than literals because the "config incomplete" refusal interpolates them, and that -# refusal is compared byte-for-byte against the GO client by `tests/parity/harness.py`. -ENV_URL = "CAIRN_URL" -ENV_TOKEN = "CAIRN_TOKEN" -DEFAULT_TIMEOUT = 20 -# Ceiling on what a snapshot may unpack to. The whole store measured ~63 KB of -# markdown across 305 entries in 2026-08; 256 MB is ~4000x that, so it bounds a -# decompression bomb without being reachable by real growth for years. -MAX_UNPACKED_BYTES = 256 * 1024 * 1024 -# Companion ceiling on MEMBER COUNT. The live store held 305 entries in 2026-08; -# 50,000 is ~160x that and bounds an inode bomb, which the byte ceiling alone -# cannot see because empty members declare size 0. -MAX_MEMBERS = 50_000 - -# Whether this interpreter's `TarFile.extract` takes `filter=`. -# -# 🔴 FEATURE-DETECTED, NEVER A VERSION COMPARISON. The extraction filters landed -# in 3.12 and were BACKPORTED to 3.11.4, 3.10.12, 3.9.17 and 3.8.17, so the -# predicate "has filters" is not an interval on version_info and any `>=` spelling -# of it is wrong for some supported interpreter. `hasattr(tarfile, "data_filter")` -# is what CPython's own documentation tells a caller to branch on, and it is true -# exactly when the kwarg exists. -# -# 🔴 THIS EXISTS BECAUSE THE CLIENT CARRIED AN UNDECLARED 3.12 FLOOR AND NOTHING -# SAID SO. `tar.extract(..., filter="data")` is a TypeError on 3.11.2 — not a -# degraded extraction, a crash on the sync path, so `recall` dies with a traceback -# rather than any of this client's exit codes. It went unseen because every host -# that runs the client interactively is on 3.12; it surfaces the moment the client -# is installed into an image that is not. A client whose whole job is to be fetched -# by sha and run on someone else's interpreter must not assume the newest one. -HAS_TAR_FILTERS = hasattr(tarfile, "data_filter") - -# Exit codes. 0/3 are the contract §3 pins; the reader's own non-zero codes pass -# through unchanged so a malformed entry still reports what it always did. -EXIT_OK = 0 -EXIT_UNREACHABLE_NO_CACHE = 3 -EXIT_USAGE = 2 -# `sync` only: the store was not reached, but a usable cache survived. Distinct -# from 3 so a caller can tell "stale but serviceable" from "nothing at all". -EXIT_REFRESH_FAILED = 4 -# The server answered with something we refuse to install. Distinct from every -# other code so it can never be read as an outage or as a clean run. -EXIT_CORRUPT = 5 - -# --- WRITE codes. Deliberately distinct from every READ code above. ---------- -# -# 🔴 A WRITE HAS NO CACHE TO FALL BACK ON, AND THAT ASYMMETRY IS THE CONTRACT. -# `recall`'s job is to answer, so an outage degrades to a stale answer that says -# it is stale, at exit 0. A write's job is to make a durable record; there is no -# such thing as a stale write, and a queued one is a write the caller believes -# landed. So `append`/`put`/`create` FAIL LOUDLY when the store cannot be reached — the -# accepted cost of decision 8 in `claudedocs/plan-cairn-integration.md`, stated -# there and stated again here so a future reader cannot mistake it for an -# oversight and "fix" it by adding a spool. -# -# 6 = the STORE refused the request and the caller must change it (4xx that is -# not a precondition failure): a malformed bullet, an unknown ref, a scope -# this credential may not see. Retrying byte-for-byte cannot help. -EXIT_WRITE_REFUSED = 6 -# 7 = the write did NOT happen and the reason is not the caller's request — the -# host was unreachable, or the server could not read its own store (503). -# Distinct from 6 because a retry is exactly the right response to this one -# and exactly the wrong response to that one. -EXIT_WRITE_UNREACHABLE = 7 -# 8 = the precondition failed (412): the entry moved under the revision this -# write was based on. Its own code because the remedy is unique — re-sync, -# re-derive the revision, re-apply the edit — and because collapsing it into -# 6 would invite a blind retry that either 412s forever or, with `If-Match` -# dropped, silently overwrites somebody else's change. -EXIT_WRITE_PRECONDITION = 8 -# 9 = `create` only: the entry ALREADY EXISTS, so nothing was created and -# nothing was overwritten. 🔴 ITS OWN CODE EVEN THOUGH THE SERVER ANSWERS -# THE SAME 412 AS 8, because the two remedies are opposites: 8 means "the -# entry moved under you — re-sync, re-derive, re-apply, put again", and a -# retry is right; 9 means "you asked to create something that is there — -# use `append` or `put`", and the identical retry loops forever. They are -# told apart by `X-Store-Status` (`precondition-failed` vs `already-exists`), -# which is the only place on the wire the difference exists. -EXIT_WRITE_EXISTS = 9 - -# --- ROUTING. Neither a read code nor a write code, deliberately. --------- -# 11 = this client could not decide WHICH INSTANCE a scope belongs to, so it did -# nothing. Either the routing table does not name the scope, or the table -# itself cannot be read. 🔴 ITS OWN CODE, AND IT IS A READ/WRITE-NEUTRAL -# ONE: the refusal happens BEFORE either path, and collapsing it into 3 -# ("nothing was displayed") or 7 ("the write did not happen") would tell a -# caller the store was unreachable when the store was never chosen. The -# remedy is a line in a table, not a retry. -EXIT_UNROUTED = 11 - -STATE_LIVE = "live" -STATE_CACHED = "cached" -STATE_EMPTY = "scope-empty" -STATE_NO_CACHE = "store-unreachable, no cache" - - -class StoreUnreachable(Exception): - """The pod could not be read. Carries the reason, never a bare failure. - - 🔴 The reason is mandatory: criterion 5 of the card this implements is that - an unreachable host is reported as UNMEASURED **with a reason**, never as a - silent success or a zero. - - 🔴 `http_status` IS THE STRUCTURAL DISCRIMINATOR, AND IT EXISTS BECAUSE THE - MESSAGE IS NOT ONE. "the host never answered" and "the host answered 401" - are both raised here — deliberately, since a read degrades to the cache - either way — but they are NOT the same fact to a human: one is an outage and - the other is a credential that has to be replaced. The only thing that told - them apart was the phrasing of `str(exc)`, and a caller that greps a message - for `HTTP 401` has pinned an f-string. `None` means there was no answer at - all; an int is the status the server sent. `resolve_state` reads neither, so - nothing about the read path changes. - """ - - def __init__(self, *args: object, http_status: int | None = None) -> None: - super().__init__(*args) - self.http_status = http_status - - -class StoreCorrupt(Exception): - """The server answered, and what it sent is not a store we will accept. - - 🔴 DELIBERATELY NOT A SUBCLASS OF `StoreUnreachable`. An outage is absorbed - into "serving from cache" at exit 0, which is right for an outage and wrong - for this: a server shipping a traversal member, a link, a duplicate, or a - count that disagrees with its own header is the one case that has to be - LOUD. Collapsing the two would let a hostile or broken archive render as a - reassuring `⚠ SERVED FROM CACHE`. - """ - - -def _warn_deprecations(lines: list[str]) -> None: - """Emit `env_aliases` warnings on stderr, at most once per process per line. - - 🔴 THE PREFIX AND THE STREAM ARE PART OF THE CONTRACT, NOT A PRESENTATION CHOICE. - `tests/parity/harness.py` diffs this client's stderr against the Go client's - BYTE-FOR-BYTE, so `cairn: ` and `file=sys.stderr` here have to match - `internal/client.Run`'s sink exactly. `env_aliases.warn_once` owns the "at most - once" rule for both languages, so neither side counts for itself. - """ - env_aliases.warn_once(lines, lambda line: print(f"cairn: {line}", file=sys.stderr)) - - -def load_config(path: Path | None = None, *, instance: str | None = None) -> tuple[str, str]: - """`(url, token)` from the env file, with real environment taking priority. - - A missing file is not fatal on its own — the caller may have exported both - values — but a missing VALUE is, and it says which one. "No token" must not - degrade into an unauthenticated request that comes back 401 and gets read as - "the store is down". - - 🔴 THE ENVIRONMENT OVERRIDES THE DEFAULT INSTANCE ONLY, AND THE ASYMMETRY IS - THE WHOLE REASON A SECOND INSTANCE IS SAFE TO ADD. `SUBSYSTEM_STORE_URL` has - always pointed this client at a throwaway server, and letting it win for - EVERY alias would point them all at one store: a `doctor` that walks three - instances would then measure one three times and report agreement it never - observed, and a routed write would land somewhere the table did not name. - A non-default alias reads its own file and nothing else. - """ - alias = instance or _read_store.DEFAULT_ALIAS - is_default = alias == _read_store.DEFAULT_ALIAS - if path is None: - path = ( - cairn_instances.config_path() - if is_default - else cairn_instances.instance_dir() - / f"{alias}{cairn_instances.INSTANCE_SUFFIX}" - ) - from_file: dict[str, str] = {} - try: - for line in path.read_text(encoding="utf-8").splitlines(): - line = line.strip() - if not line or line.startswith("#") or "=" not in line: - continue - key, _, value = line.partition("=") - from_file[key.strip()] = value.strip() - except OSError: - pass - - # 🔴 THE FILE IS AS MUCH AN ALIAS SURFACE AS THE ENVIRONMENT IS. `SUBSYSTEM_STORE_URL=` - # is a KEY inside `~/.config/subsystem-store/env` as well as an exported variable, and - # an operator who renamed only one of the two would get a silent half-migration — the - # file key ignored, the environment honoured. Its warning NAMES THE FILE rather than - # `$VAR`, because the string lives somewhere they have to edit. - _warn_deprecations(env_aliases.file_deprecations(from_file, str(path))) - - if is_default: - url = env_aliases.value(os.environ, ENV_URL) or env_aliases.value(from_file, ENV_URL) - token = env_aliases.value(os.environ, ENV_TOKEN) or env_aliases.value( - from_file, ENV_TOKEN - ) - where = f"(looked in {path} and the environment)" - else: - url = env_aliases.value(from_file, ENV_URL) - token = env_aliases.value(from_file, ENV_TOKEN) - where = ( - f"(looked in {path}; the environment is NOT consulted for a " - f"non-default instance, so a `{alias}` instance is configured by " - f"that file alone)" - ) - missing = [ - n - for n, v in ((ENV_URL, url), (ENV_TOKEN, token)) - if not v - ] - if missing: - raise StoreUnreachable( - f"config incomplete: {', '.join(missing)} not set {where}" - ) - return url.rstrip("/"), token # type: ignore[union-attr,return-value] - - -# --- INSTANCES AND ROUTING -------------------------------------------------- -# -# 🔴 TWO PREDICATES, NOT ONE, AND KNOWING WHICH YOU WANT IS THE WHOLE TRAP. -# -# * `Routing.multi_instance` — "is there more than one PLACE on this host?". -# Every site that LABELS output asks this and nothing else: the banner -# label, the write label, `doctor`'s per-instance sections, `ls-entries`' -# prefix, the search fan-out and the caveat's extra clause. Six copies of -# `len(instances) > 1` would be six chances to disagree, and the symptom of -# disagreeing is output that names an instance the next line does not. -# * `Routing.alias_for` — "WHERE does this scope live?". It consults the -# routing TABLE first, so a one-instance host with a table still refuses a -# scope routed to an alias it has no config for. -# -# 🔴 THEY WERE ONE BOOLEAN AND THAT WAS A DEFECT, recorded here because the -# collapse is the obvious simplification and it is wrong in both directions. -# `active = routes is not None or len(instances) > 1` made a table's PRESENCE -# switch labelling on, so the first operator to write a table on a one-instance -# host got "with more than one instance configured …" on every recall — false on -# that host — and every scope not yet in the table refused at exit 11. Deleting -# the `routes is not None` disjunct fixes those and opens a SILENT MISROUTE: a -# table entry naming an unconfigured alias would then resolve to the sole -# instance. The three-row table in `cairn_instances.Routing.alias_for` is the -# measurement; do not re-collapse these. - - -def _routing() -> "cairn_instances.Routing": - """What is configured, read fresh. NOT cached in a module global. - - A cache would be read once per process and then be wrong for any test that - repoints `$HOME` between calls — and it would buy a few `stat`s on a command - that is about to open a socket. - """ - return cairn_instances.discover() - - -def _instance_cache(args: argparse.Namespace, alias: str) -> Path: - """The cache root for `alias`, honouring an explicit `--cache`. - - 🔴 AN EXPLICIT `--cache` WINS, AND THE DEFAULT IS RESOLVED PER INSTANCE. The - parser's default is still the DEFAULT instance's root — unchanged, printed - in `--help`, and what a single-instance host uses — but a second instance - must not share one directory with the first: two stores unpacked over each - other would interleave scopes, and `.sync-stamp` would date whichever synced - last while the entries came from both. - """ - if getattr(args, "cache_explicit", False): - return args.cache - return _read_store.cache_root_for(alias) - - -def _instance_for(args: argparse.Namespace, scope: str) -> tuple[str, str | None, Path]: - """`(alias, label, cache)` for a scope. Raises `UnroutedScope` — never guesses. - - `label` is the alias when this host has MORE THAN ONE INSTANCE and `None` - when it has one. 🔴 THAT `None` IS THE COMPATIBILITY GUARANTEE, not a - formatting nicety: it is what keeps a one-instance host's output - byte-for-byte what it was, so the LABELLING half of the routing machinery - can ship and be proven inert before any data moves. - - ⚠ THE *ROUTING* HALF IS NOT INERT AT ONE INSTANCE, AND THIS SENTENCE USED - TO BE READ AS COVERING BOTH. `routing.alias_for` is consulted whatever - `multi_instance` says, and its row 3 — a table routing this scope to an - alias the host has no config for — REFUSES at exit 11 with one instance - exactly as with many. Measured on a one-instance host with - `routes.json = {"alpha-notes": "nowhere"}`: `recall`, `search` and - `validate` all exit 11 here, and the Go client agrees (it answered 0 with - a digest at `d8b858a`, before its reads routed). `sync`, `ls-entries` and - `doctor` are untouched — they ROUTE NOTHING. - - 🔴 "THEY TAKE NO SCOPE" IS WHAT THAT LAST CLAUSE USED TO SAY, AND `--help` - FALSIFIES IT FOR TWO OF THE THREE. `cairn sync` and `cairn ls-entries` both - declare `--scope`; only `doctor` has no such flag. What makes them untouched - is that they pass `scope=None`/`""` regardless and walk EVERY instance — see - `cmd_sync` for the measured reason this cache may never be narrowed. The - conclusion is unchanged and re-measured on the same world: `sync --scope - alpha-notes` exits 4 and `ls-entries --scope alpha-notes` exits 0, on both - clients, byte-identical to the unscoped runs. 🔴 THE REASON IS LOAD-BEARING - RATHER THAN PEDANTIC: a later change that routed `ls-entries --scope` - through `alias_for` would falsify the conclusion while the old reason still - read as covering it. - - 🔴 AND IT IS GATED ON THE INSTANCE COUNT, NEVER ON THE TABLE. A one-instance - host that has written a routing table is still a host with one place an - answer can come from, so it is still unlabelled — while `alias_for` above - has already consulted that table and may have refused. The two questions are - separate; see the header comment. - """ - routing = _routing() - alias = routing.alias_for(scope) - return alias, (alias if routing.multi_instance else None), _instance_cache(args, alias) - - -def _repo_scope(args: argparse.Namespace) -> str: - """The scope `--repo` derives, or `""` when it cannot be derived. - - Swallows the error ON PURPOSE and only where the CALLER has a real answer - for the empty case — `validate` falls back to the default instance, because - "which cache am I checking" has one sensible answer outside a repo and - "where does this write land" does not. - """ - try: - return scope_for_repo(args.repo) or "" - except Exception: # GitError and anything else the resolver raises - return "" - - -def _default_instance(args: argparse.Namespace) -> tuple[str, str | None, Path]: - """The default instance, LABELLED when this host has more than one. - - Used where there is no scope to route. The label still appears, because - "which of my instances did that read" is exactly as pressing when the - command picked one as when a table did. - """ - routing = _routing() - alias = _read_store.DEFAULT_ALIAS - return alias, (alias if routing.multi_instance else None), _instance_cache(args, alias) - - -def _refuse_shared_cache( - args: argparse.Namespace, routing: "cairn_instances.Routing", verb: str -) -> int | None: - """Refuse an explicit `--cache` that would make N instances share one directory. - - 🔴 THE DAMAGE IS SILENT AND IT IS TO THE CACHE, NOT TO THE OUTPUT. Two - snapshots unpacked into one root interleave their scopes, and `.sync-stamp` - then dates whichever synced last while the entries beneath it came from - both — a store that can neither say what it holds nor how old it is. The - refusal costs an error message; the alternative is a cache nobody can - trust and no way to notice. - """ - if len(routing.instances) > 1 and getattr(args, "cache_explicit", False): - print( - f"cairn: `{verb}` walks all {len(routing.instances)} configured " - f"instances ({', '.join(routing.aliases)}), so an explicit --cache " - f"would make them share one directory and overwrite each other. " - f"Drop --cache, or name one instance's scope.", - file=sys.stderr, - ) - return EXIT_USAGE - return None - - -def _search_every_instance( - args: argparse.Namespace, routing: "cairn_instances.Routing", query: str -) -> int: - """`search --all-scopes` across every configured instance. - - 🔴 A PARTIAL RESULT IS A LIE, SO AN UNREAD INSTANCE IS LOUD AND NON-ZERO. - "No matches" from a fan-out that silently skipped a store is the same - silent zero this client was built to prevent, one layer up: the caller - concludes the thing is not recorded anywhere. Hits that WERE found are - still printed — throwing away real answers to report a defect is its own - harm — but the run exits non-zero and names the instance it could not read. - - 🔴 AND EACH SECTION NAMES ITS INSTANCE. Without that, two hits with the - same ref from two stores are indistinguishable, which is the question a - second instance creates. - """ - refusal = _refuse_shared_cache(args, routing, "search --all-scopes") - if refusal is not None: - return refusal - worst = EXIT_OK - unread: list[str] = [] - for instance in routing.instances: - cache = _instance_cache(args, instance.alias) - state, detail, hint = resolve_state( - cache, no_sync=args.no_sync, scope=None, timeout=_store_timeout(args), - instance=instance.alias, - ) - if hint is not None: - print(banner(state, detail, instance.alias), file=sys.stderr) - unread.append(instance.alias) - worst = max(worst, hint) - continue - report = rc.search( - str(cache), - "", - query, - context=rc.CONTEXT_BULLET, - threshold=rc.DEFAULT_SEARCH_THRESHOLD, - max_hits=rc.DEFAULT_MAX_HITS, - all_scopes=True, - ) - read_ledger.record(instance.alias, read_ledger.ALL_SCOPES) - print(banner(state, detail, instance.alias)) - print() - print(rc.render_search(report, instance=instance.alias)) - print() - worst = max(worst, rc._exit_for(report.status, report.label, report.malformed)) - if unread: - print( - f"🔴 cairn: PARTIAL — {len(unread)} of {len(routing.instances)} " - f"instance(s) could not be read ({', '.join(unread)}). Anything " - f"printed above is what the instances that ANSWERED hold; it is NOT " - f"an answer about the ones that did not, and 'no matches' above does " - f"not mean the query matches nothing.", - file=sys.stderr, - ) - return worst - - -def _unrouted(exc: "cairn_instances.UnroutedScope") -> int: - """Print the refusal and return its code. ONE spelling, four call sites.""" - print(f"🔴 cairn: REFUSING — {exc.detail}", file=sys.stderr) - return EXIT_UNROUTED - - -def _apply_standard_headers(req: "urllib.request.Request", token: str) -> None: - """The two headers EVERY request to this host must carry, in ONE place. - - 🔴 A User-Agent IS REQUIRED, and urllib's default is actively refused. - MEASURED against the live host, same token, same path, three - requests differing ONLY in this header: - curl's default UA -> 200 - `Python-urllib/3.12` -> 403 <-- urllib's default - empty UA -> 200 - The 403 comes from the edge, not the app, so it is NOT a token rejection and - NOT the store being down — but it arrives looking like both. - - 🔴 THIS EXISTS AS A FUNCTION BECAUSE THE WRITE PATH WOULD OTHERWISE HAVE TO - RE-LEARN IT. When `fetch_snapshot` was the only caller the header was a line - inside it; adding `append`/`put` made that line a rule with two more sites, - and a rule at three sites is the shape `claude/RULES.md` says regenerates - the same bug at N-1 of them. - - 🔴 THE GUARD IS `test_cairn_write.py::TestTheRequestItself:: - test_no_request_builder_ANYWHERE_bypasses_this_helper` — an AST scan over - this file AND `cairn-cutover.py`, asserting every function that constructs a - `urllib.request.Request` also calls this helper. An earlier version of this - sentence named a test that **did not exist**, which is worse than naming - none: it reads as coverage and stops anyone looking. It was written while - the only real check was a behavioural one on the append path, so a new read - verb building its own request was unguarded by the very line claiming to - guard it. - """ - req.add_header("Authorization", f"Bearer {token}") - req.add_header("User-Agent", "subsystem-store-client/1") - - -SYNC_ETAG = ".sync-etag" - -#: An entity-tag longer than this is already pathological. The cap is here so a -#: hostile server cannot make this client write an unbounded file or emit an -#: unbounded request header. -MAX_ETAG_BYTES = 128 - - -def storable_etag(value: str | None) -> str: - """`value` if it is safe to write to disk and send back, else `""`. - - 🔴 THE VALIDATOR COMES FROM THE SERVER, WHICH IS THE PARTY THIS CLIENT - ALREADY DOES NOT FULLY TRUST — the same threat model as the link, traversal, - duplicate and size guards in `install_snapshot`. The rule is the RFC 9110 - `etagc` character set plus the quotes: every byte printable ASCII and none of - them a space. That is exactly what makes the value round-trip as ONE line of - a file and as ONE header, so a server cannot use it to inject a second - header or a second stamp field. - - ⚠ IT IS A FILTER, NOT A REFUSAL. An unusable tag means "this cache has no - validator", never "this response is corrupt": the content arrived fine and - the only cost is that the next sync cannot be conditional. Refusing here - would let a malformed header break a sync that otherwise worked. - """ - if not value or len(value) > MAX_ETAG_BYTES: - return "" - return value if all("\x21" <= ch <= "\x7e" for ch in value) else "" - - -def stored_etag(cache: Path) -> str: - """The validator recorded beside `cache`, or `""` for "there is none". - - 🔴 IT DOES **NOT** FILTER, AND THE FILTER IS AT THE POINT OF USE INSTEAD — - `fetch_snapshot`, which is where the value becomes a header. A filter here - as WELL was written first and then deleted: it was a second copy of one - predicate, and a mutation sweep measured the consequence — removing it - changed nothing observable, because the surviving copy caught the same - value, so the guard could not be watched to fail and read as coverage it - did not provide. One rule, one place, at the boundary that is actually - crossed. - """ - try: - return (cache / SYNC_ETAG).read_text(encoding="utf-8").rstrip("\n") - except (OSError, UnicodeDecodeError): - return "" - - -def fetch_snapshot( - url: str, token: str, *, scope: str | None, timeout: int, etag: str = "" -) -> tuple[bytes | None, dict[str, str], bool]: - """GET the tar. Every failure becomes a StoreUnreachable NAMING the host. - - 🔴 THE THIRD ELEMENT IS `not_modified`, AND IT IS A RETURN VALUE RATHER THAN - AN EXCEPTION SO NO CALLER CAN FORGET IT. A 304 is a SUCCESS with no body, - and the shape that loses it is the one where it travels as a - `StoreUnreachable`: every caller here already has an arm that degrades to - the cache on that exception, so a 304 raised would have rendered as an - OUTAGE on the one path whose whole purpose is to say the cache is CURRENT. - As a widened tuple it breaks any caller that has not been updated, loudly, - at the unpack. - - `etag` is the validator this host already holds, or `""` for "ask for the - whole thing". When it is sent and matches, `body` is `None`. - """ - # 🔴 `timeout=None` REACHES `urlopen` AS *NO* TIMEOUT, NOT AS A DEFAULT, so - # this refuses it rather than trusting the annotation above — `timeout: int` - # is a type hint, and a hint is not a code path. The sibling `who` side of - # this CLI has refused it for a long time; the store side did not, - # and mutating either `fetch_snapshot`'s or `urlopen`'s argument to `None` - # survived the whole suite. The asymmetry was the defect: one half of one - # program failing closed. - bad = unbounded_timeout_reason(timeout) - if bad: - raise StoreUnreachable(f"refusing to fetch {url}: {bad}") - target = f"{url}/api/v1/snapshot" + (f"?scope={scope}" if scope else "") - req = urllib.request.Request(target, method="GET") - # Auth + the mandatory User-Agent. See `_apply_standard_headers` for the - # measurement that makes the UA load-bearing; without it every Python client - # of this host is blocked, which is exactly the shape of bug that gets - # diagnosed as "the store is broken". - _apply_standard_headers(req, token) - # 🔴 THE ONE PLACE THE VALUE IS FILTERED ON ITS WAY OUT, and it is here - # because here is where it becomes a header. `etag` reaches this function - # from a FILE — which anything can edit — so it is not the same trust - # boundary as the response that produced it, and without this line a stored - # value carrying a newline makes `http.client` raise `ValueError` out of - # every handler in this program: an unusable validator taking down a sync - # that would otherwise have worked. - validator = storable_etag(etag) - if validator: - req.add_header("If-None-Match", validator) - try: - with urllib.request.urlopen(req, timeout=timeout) as resp: - # 🔴 RETURN THE MESSAGE, NEVER A DICT BUILT FROM IT. - # `resp.headers` is an `email.message.Message` and its `.get()` is - # already case-insensitive; `dict(resp.headers)` throws that away. - # HTTP/2 lowercases every header name and this host is behind - # Cloudflare, so in PRODUCTION the keys arrive lowercased while the - # code asked for the mixed-case spelling. MEASURED against the live - # pod on the first real call after deploying 0.4.0: - # dict(resp.headers).get("X-Store-Entries") -> None - # dict(resp.headers).get("x-store-entries") -> 75 - # Silent consequences: `snapshot=UNSTAMPED`, `revision=unknown`, and - # — worst — the count cross-check against `X-Store-Entries` NEVER - # FIRED, so the guard against a truncated transfer was inert in the - # only environment that matters. 358 tests and seven audit rounds - # missed it: the test shim reproduced production's TOPOLOGY but not - # its NORMALISATION. - # - # ⚠ A `{k.lower(): v}` comprehension fixes the case and introduces a - # SECOND bug: on a duplicated header a dict keeps the LAST value - # where `Message.get` returns the FIRST (measured: 1 vs 99). This - # repo has `sole_header` (server.py:422) precisely because "a bare - # .get() silently takes the FIRST value" was a real smuggling bug, - # and its rule is REFUSE a duplicate, not quietly pick the other - # end. Handing back the Message keeps ONE semantics rather than - # inventing a second — caught in review, not shipped. - return resp.read(), resp.headers, False - except urllib.error.HTTPError as exc: - # 🔴 CHECKED BEFORE THE REASON IS BUILT, BECAUSE `urllib` ROUTES A 304 - # HERE. `HTTPErrorProcessor` raises for everything outside 2xx, so the - # one non-200 on this route that means the fetch SUCCEEDED arrives as an - # exception — and the arm below would turn it into "answered HTTP 304", - # degrading a healthy, confirmed-current cache into `⚠ SERVED FROM - # CACHE` with a scary reason attached. `exc.headers` is the same - # `email.message.Message` the success path returns, so the caller reads - # `ETag` and `X-Store-Snapshot` off it identically. - if exc.code == 304: - return None, exc.headers, True - # 🔴 CARRY THE BODY. The server's 503 names WHICH scope it could not - # read; reporting only "answered HTTP 503" throws that away and leaves - # the operator with a code and no cause — the opposite of "UNMEASURED - # with a reason". Truncated because this is a one-line reason, not a page. - try: - detail = exc.read().decode("utf-8", "replace").strip().replace("\n", "; ") - except Exception: - detail = "" - detail = f" — {detail[:300]}" if detail else "" - raise StoreUnreachable( - f"{url} answered HTTP {exc.code}{detail}", http_status=exc.code - ) from exc - except urllib.error.URLError as exc: - raise StoreUnreachable(f"{url} unreachable: {exc.reason}") from exc - except OSError as exc: # socket timeouts and friends - raise StoreUnreachable(f"{url} unreachable: {exc}") from exc - - -def _safe_member_name(name: str) -> bool: - """True when `name` stays inside the extraction root. - - 🔴 NOT `".." in name`. That was the first version and it is over-broad: a - legitimate entry called `widget-cfg/a..b.md` contains `..` as a SUBSTRING - and aborted the entire sync, which then rendered as an outage. The server - puts no constraint on entry filenames, so this is reachable with an ordinary - file. Decide on path COMPONENTS, which is the actual property. - """ - if not name or name.startswith("/") or os.path.isabs(name): - return False - parts = Path(name).parts - return bool(parts) and not any(p in ("..", "") for p in parts) - - -ORPHAN_GRACE_SECONDS = 3600 - - -def _reap_orphans(cache: Path) -> int: - """Remove stale `.new-*` / `.old-*` trees. Returns how many. - - 🔴 THE PER-RUN STAGING NAME TRADED ONE BUG FOR A LEAK. The pre-fix version - used a FIXED staging name and `rmtree`d it at the top of every run, which - raced (that was the truncation bug) but was self-healing. Unique names fixed - the race and removed the healing: an audit SIGKILLed three syncs mid-run and - the orphaned trees were still there afterwards, with a later clean sync - leaving them alone. `finally` covers exceptions; it does not cover SIGKILL, - a power cut, or an OOM — and with the planned sync timer these accumulate in - `~/.cache` without bound. - - The grace period is why this is safe to run at the START of a sync: a - directory younger than an hour may belong to a CONCURRENT sync, and deleting - it would reintroduce the very race the unique names removed. Anything older - than that cannot be live — the whole operation takes well under a second. - """ - cutoff = time.time() - ORPHAN_GRACE_SECONDS - reaped = 0 - for prefix in (f"{cache.name}.new-", f"{cache.name}.old-"): - for path in cache.parent.glob(f"{prefix}*"): - try: - # `lstat`, not `stat`: a SYMLINK named like a staging dir - # dereferences under `is_dir()`/`stat()`, and `rmtree` on a - # symlink is a silent no-op — so it would be counted as reaped - # while never being removed, and the miscount is invisible - # because the count is the only evidence. - if path.lstat().st_mtime >= cutoff: - continue - if path.is_symlink(): - path.unlink() - elif path.is_dir(): - shutil.rmtree(path, ignore_errors=True) - else: - continue - reaped += 1 - except OSError: - continue # someone else's, or vanished under us; not our problem - return reaped - - -def install_snapshot(body: bytes, cache: Path, headers: dict[str, str]) -> int: - """Replace the cache with the tar's contents. - - 🔴 CONCURRENT SYNCS USED TO SILENTLY TRUNCATE THIS CACHE, and the previous - docstring claimed the opposite. The staging directory had a FIXED name and - was `rmtree`d at the top of every run, so two syncs shared it: measured over - 10 trials on a 305-entry store, 3 left a SHORT cache (183, 256, 292 entries) - with no error, and further runs died with `FileExistsError` / - `Directory not empty`. The reader then rendered that partial tree under its - own "none omitted" header — the completeness lie, arriving by the one route - this function exists to close. This repo's AGENTS.md says concurrent - sessions are normal, and a timer is planned, so it was not a corner case. - - Two changes make it safe: a PER-RUN staging directory (so runs cannot share - one), and an exclusive LOCK around the swap (so the rename pair cannot - interleave). The lock is advisory and held only for the swap, so a slow - download never blocks another reader. - """ - cache.parent.mkdir(parents=True, exist_ok=True) - _reap_orphans(cache) - staging = Path(tempfile.mkdtemp(dir=cache.parent, prefix=f"{cache.name}.new-")) - - try: - count = 0 - seen: set[str] = set() - with tarfile.open(fileobj=io.BytesIO(body), mode="r") as tar: - members = tar.getmembers() - # 🔴 A DECOMPRESSED-SIZE CAP. Gzip removed the natural bound: before - # it, the response body limited what could be extracted. An audit - # MEASURED a 203,934-byte body expanding to 209,715,200 bytes on - # disk — 1028x — and the client reported `live … 1 entries`, exit 0. - # Every other hostile-archive guard here (links, traversal, - # duplicates, count mismatch) exists for a server we do not fully - # trust; a size bomb is the same threat model and was the one hole. - # 🔴 TWO CEILINGS, BECAUSE BYTES ALONE BOUND NOTHING. `m.size` is 0 - # for an empty member, so a byte ceiling never fires on an INODE - # bomb: measured against the previous commit, a 282,282-byte body - # carrying 60,000 zero-length `*.md` members wrote 60,000 files into - # the cache in 3.7 s and reported `live … 60000 entries`, exit 0. - # Same threat model as the byte bomb closed last round, one axis - # over — and `X-Store-Entries` cannot help, since the same hostile - # server sets it. - # - # `sum`, not `max`: a `max`-based ceiling passes a 1000 x 250 MB - # archive, and the single-member bomb fixture cannot tell the two - # apart (that mutant survived the previous round's suite). - declared_bytes = sum(m.size for m in members) - if declared_bytes > MAX_UNPACKED_BYTES: - raise StoreCorrupt( - f"archive unpacks to {declared_bytes} bytes, over the " - f"{MAX_UNPACKED_BYTES}-byte ceiling " - f"({len(body)} bytes on the wire)" - ) - if len(members) > MAX_MEMBERS: - raise StoreCorrupt( - f"archive holds {len(members)} members, over the " - f"{MAX_MEMBERS}-member ceiling " - f"({len(body)} bytes on the wire)" - ) - for member in members: - name = member.name - # 🔴 A HOSTILE OR CORRUPT ARCHIVE IS NOT AN OUTAGE. This raises - # StoreCorrupt, not StoreUnreachable, so it can never be quietly - # absorbed into "serving from cache" — a server shipping a - # traversal member is the one case that must be loud. - if member.issym() or member.islnk(): - raise StoreCorrupt(f"tar member is a link: {name!r}") - if not member.isfile(): - raise StoreCorrupt(f"tar member is not a regular file: {name!r}") - if not _safe_member_name(name): - raise StoreCorrupt(f"tar member escapes the root: {name!r}") - if name in seen: - raise StoreCorrupt(f"duplicate tar member: {name!r}") - seen.add(name) - # `filter="data"` is the safe extractor AND silences the - # DeprecationWarning that 3.14 prints on every unfiltered extract - # — which would otherwise land on stderr on the /resume hot path. - # - # 🔴 THE FALLBACK IS NOT "THE SAME CALL WITHOUT THE GUARD", AND - # SAYING SO WOULD BE THE COMMENT THIS FILE WARNS ABOUT. By the time - # a member reaches here the four guards above have already refused - # every link, every non-regular member, every traversal name and - # every duplicate — which is most of what the data filter rejects, - # and all of it refused LOUDER (StoreCorrupt, not a silent skip). - # What the filter still contributes on this path is MODE: it drops - # setuid/setgid/sticky and clamps the permission bits, so a hostile - # archive cannot land a setuid-bit file in the cache. The fallback - # therefore sets the mode itself rather than trusting the - # archive's. 0o644 is not a clamp of `member.mode` but a - # replacement for it: every member here is a regular file in a - # read-through cache, nothing in the tree is executed, and a - # constant cannot be walked by a crafted mode the way a mask can. - if HAS_TAR_FILTERS: - tar.extract(member, staging, filter="data") - else: - member.mode = 0o644 - tar.extract(member, staging) - if name.endswith(".md"): - count += 1 - - # 🔴 The server's own count, checked. The header comment on the server - # side claims a truncated transfer is "visible as a disagreement"; it is - # only visible if somebody compares, so this is that comparison. - declared = headers.get("x-store-entries") - if declared is not None and declared.isdigit() and int(declared) != count: - raise StoreCorrupt( - f"server declared {declared} entries, archive held {count}" - ) - - (staging / SYNC_STAMP).write_text( - "\n".join( - [ - f"synced={int(time.time())}", - f"revision={headers.get('x-store-revision', 'unknown')}", - f"snapshot={headers.get('x-store-snapshot', 'UNSTAMPED')}", - f"entries={count}", - # Recorded so a filtered cache can never be mistaken for a - # complete one. Today the CLI only ever writes ALL. - "coverage=ALL", - ] - ) - + "\n", - encoding="utf-8", - ) - - # 🔴 ITS OWN FILE, BESIDE `.sync-stamp` RATHER THAN A LINE INSIDE IT, AND - # THE REASON IS THE READER. Every non-blank line of `.sync-stamp` is - # RENDERED, as ` stamp: `, in the header of every report both - # clients print — so an `etag=` field there would put a 78-character - # digest on every recall, search and validate a human or an agent ever - # reads, for a value neither of them can act on. The two files cannot - # disagree: both are written into this staging directory and installed - # by the same atomic swap below, so a cache has both or has neither. - # - # ⚠ AND ITS ABSENCE IS NOT AN ERROR. A cache written by an older client, - # or by a pod that sends no `ETag`, simply has no validator: the next - # sync sends no `If-None-Match` and is answered the full 200 it always - # was. - validator = storable_etag(headers.get("etag")) - if validator: - (staging / SYNC_ETAG).write_text(validator + "\n", encoding="utf-8") - - lock_path = cache.parent / f"{cache.name}.lock" - with open(lock_path, "w") as lock: - fcntl.flock(lock, fcntl.LOCK_EX) - retired = None - try: - if cache.exists(): - retired = Path( - tempfile.mkdtemp(dir=cache.parent, prefix=f"{cache.name}.old-") - ) - retired.rmdir() # mkdtemp reserved the name; rename needs it free - cache.rename(retired) - staging.rename(cache) - staging = None # type: ignore[assignment] # ownership transferred - finally: - fcntl.flock(lock, fcntl.LOCK_UN) - if retired is not None: - shutil.rmtree(retired, ignore_errors=True) - return count - finally: - if staging is not None: - shutil.rmtree(staging, ignore_errors=True) - - -def cache_age(cache: Path) -> tuple[int | None, dict[str, str]]: - """`(age_seconds, stamp_fields)`; age is None when the stamp is unreadable. - - An unreadable stamp is NOT reported as age 0. "Fresh" is the one answer a - broken clock must never produce here. - """ - fields: dict[str, str] = {} - try: - for line in (cache / SYNC_STAMP).read_text(encoding="utf-8").splitlines(): - key, _, value = line.partition("=") - fields[key.strip()] = value.strip() - age = int(time.time()) - int(fields["synced"]) - # 🔴 A FUTURE-DATED STAMP IS UNKNOWN, NOT FRESH. The previous `max(0, …)` - # clamped it to `0s`, i.e. "just synced" — which is precisely the answer - # this function's docstring says a broken clock must never produce, and - # a suspending laptop (the case §2d is written for) is where clock jumps - # actually happen. - return (age if age >= 0 else None), fields - except (OSError, KeyError, ValueError): - return None, fields - - -def _age_phrase(seconds: int | None) -> str: - """"cache 3h old" / "cache age UNKNOWN" — never "cache age UNKNOWN old".""" - return "cache age UNKNOWN" if seconds is None else f"cache {human_age(seconds)} old" - - -def human_age(seconds: int | None) -> str: - if seconds is None: - return "age UNKNOWN" # callers phrase this as "cache old" - if seconds < 90: - return f"{seconds}s" - if seconds < 5400: - return f"{seconds // 60}m" - if seconds < 172800: - return f"{seconds // 3600}h" - return f"{seconds // 86400}d" - - -def resolve_state( - cache: Path, - *, - no_sync: bool, - scope: str | None, - timeout: int, - instance: str | None = None, -) -> tuple[str, str, int | None]: - """`(state, detail, exit_hint)` — the four-state decision, in ONE place. - - Every caller reads its state from here so the four cannot drift apart per - subcommand, which is how three of them end up rendering alike. - - `instance` names which configured instance to read. `None` is the default - instance, which is what a single-instance host has and is the only path the - environment override applies to — see `load_config`. - """ - if no_sync: - age, fields = cache_age(cache) - if not (cache / SYNC_STAMP).exists(): - return STATE_NO_CACHE, "--no-sync given and no cache exists", ( - EXIT_UNREACHABLE_NO_CACHE - ) - return ( - STATE_CACHED, - f"--no-sync given; cache {_age_phrase(age)}, " - f"revision {fields.get('revision', 'unknown')}", - None, - ) - - try: - url, token = load_config(instance=instance) - # 🔴 THE VALIDATOR IS OFFERED ONLY WHEN THERE IS A CACHE TO VALIDATE. A - # 304 answered to a host holding nothing would be a confirmation of an - # absence, and this client would have no content and no error — the one - # outcome the four-state design exists to make impossible. The file is - # written into the cache by the install that produced it, so it cannot - # outlive its tree; the stamp check is the belt to that braces, covering - # a cache root half-deleted by hand. - validator = stored_etag(cache) if (cache / SYNC_STAMP).exists() else "" - body, headers, not_modified = fetch_snapshot( - url, token, scope=scope, timeout=timeout, etag=validator - ) - if not_modified: - # 🔴 A 304 IS A FOURTH THING AND IT SAYS SO. The cache is not merely - # being served — it has just been CONFIRMED CURRENT against the pod, - # which is a stronger claim than `⚠ cached` (the pod could not be - # reached) and a different one from `live — fetched … just now` - # (bytes arrived). Both are `live` because every consumer of that - # name is asking "did we reach the store", and the answer is yes; - # the DETAIL is where what happened lives, exactly as it already - # distinguishes `--no-sync given` from `SERVED FROM CACHE` within - # `cached`. A fifth state name would have to be handled at each of - # the call sites that compare against STATE_LIVE, and the one missed - # would report a successful sync as a failure. - # - # ⚠ NOTHING IS WRITTEN. The cache is not touched, so `synced=` still - # dates the last DOWNLOAD rather than this confirmation — which - # makes a later offline banner say the cache is older than it has - # been proven to be. That is the safe direction (freshness may never - # be OVER-claimed here) and it is stated rather than fixed, because - # re-stamping means writing into a live cache that a concurrent sync - # may be renaming out from under it. - return ( - STATE_LIVE, - f"already current at {url} — not modified, " - f"snapshot {headers.get('x-store-snapshot', 'UNSTAMPED')}", - None, - ) - try: - count = install_snapshot(body, cache, headers) - except (EOFError, zlib.error) as exc: - # 🔴 THE GZIP SWITCH REOPENED THIS IN A NEW SHAPE. Before gzip a - # short body raised `tarfile.ReadError`, handled below. Compressed, - # a truncated body raises `EOFError: Compressed file ended before - # the end-of-stream marker was reached` — which was NOT caught, so - # it escaped as a traceback at exit 1 with a healthy cache unused: - # exactly the defect the ReadError arm was added to fix, one - # exception type over. Measured by an audit against this client. - raise StoreUnreachable(f"{url} sent a truncated archive: {exc}") from exc - except tarfile.ReadError as exc: - # 🔴 A 200 THAT IS NOT A TAR. Realistic in production precisely - # because this host's edge answers 200 with HTML for some clients - # (see `fetch_snapshot`'s User-Agent note). Previously this escaped - # every handler as an unhandled traceback at exit 1 — with a healthy - # cache sitting right there, unused. It is "we did not receive a - # store", i.e. the unreachable family, so the cache is served. - raise StoreUnreachable(f"{url} did not return an archive: {exc}") from exc - except OSError as exc: - # Disk full / permission denied while extracting. Same family: we - # have no new store, and the old one is still good. - raise StoreUnreachable(f"could not write the cache: {exc}") from exc - return ( - STATE_LIVE, - f"fetched from {url} just now — {count} entries, " - f"snapshot {headers.get('x-store-snapshot', 'UNSTAMPED')}", - None, - ) - except StoreUnreachable as exc: - age, fields = cache_age(cache) - if not (cache / SYNC_STAMP).exists(): - # 🔴 NOTHING WAS READ. Not an empty digest, not "nothing recorded". - return STATE_NO_CACHE, str(exc), EXIT_UNREACHABLE_NO_CACHE - return ( - STATE_CACHED, - f"{exc} — SERVED FROM CACHE, {_age_phrase(age)}, " - f"revision {fields.get('revision', 'unknown')}", - None, - ) - - -def banner(state: str, detail: str, instance: str | None = None) -> str: - """The state line. 🔴 NAMES THE INSTANCE WHENEVER THERE IS MORE THAN ONE. - - `instance=None` is the single-instance host and renders exactly what this - client has always rendered — which is what makes the multi-instance - machinery's LABELLING half provably inert before an operator configures a - second store. ⚠ Its ROUTING half is not: see `_instance_for`. - Given an alias, every state line carries it, because "where did that come - from" is the question a second instance creates and a banner is the only - line every read prints. - """ - marker = "🔴" if state == STATE_NO_CACHE else ("⚠" if state == STATE_CACHED else "") - name = "cairn" if instance is None else f"cairn[{instance}]" - return f"{marker} {name}: {state} — {detail}".strip() - - -def cmd_sync(args: argparse.Namespace) -> int: - """🔴 `sync` FAILS when it could not refresh, even though a cache survives. - - This is deliberately different from `recall`, and the difference is the - whole contract. `recall`'s job is to answer, so a stale answer is a success - that says it is stale (exit 0). `sync`'s job is to REFRESH, so "I did not - reach the store" is a failed operation no matter how good the cache is — - exit non-zero, naming the host. A `sync` that exited 0 on an outage is how a - timer reports success forever while the cache silently ages out. - """ - # 🔴 `scope=None`, ALWAYS. `--scope` used to be threaded through here, which - # REPLACED THE SHARED CACHE with a one-scope copy: measured, `validate - # --scope widget-cfg` took the cache from 305 entries to 2, after which an - # offline recall of any other scope printed "the store has no - # 'other-scope/' directory" at exit 0 — a claim about the STORE derived from - # a filtered cache. `_report` carried a comment warning about exactly this - # and the fix had been applied at ONE of three call sites. One rule, one - # place: the CLI's shared cache is now always the whole store, and - # `.sync-stamp` records `coverage=ALL` so a future filtered mode cannot - # silently inherit the completeness claim. The server keeps `?scope=` — it - # is a legitimate API capability with its own tests; it is just not - # something that may narrow this cache. - # 🔴 EVERY CONFIGURED INSTANCE, NOT THE ROUTED ONE. `sync` DOES declare - # `--scope` and passes `scope=None` regardless (see above), so it has - # nothing to route — and refreshing one of two instances while - # reporting success would leave the other silently ageing, which is the - # failure this command's own docstring exists to prevent, one instance over. - routing = _routing() - refusal = _refuse_shared_cache(args, routing, "sync") - if refusal is not None: - return refusal - worst = EXIT_OK - for instance in routing.instances: - label = instance.alias if routing.multi_instance else None - state, detail, hint = resolve_state( - _instance_cache(args, instance.alias), - no_sync=False, - scope=None, - timeout=_store_timeout(args), - instance=instance.alias, - ) - if state == STATE_LIVE: - print(banner(state, detail, label)) - continue - print(banner(state, detail, label), file=sys.stderr) - worst = max(worst, hint if hint is not None else EXIT_REFRESH_FAILED) - return worst - - -def cmd_ls_entries(args: argparse.Namespace) -> int: - """One `/.md` per line — per instance when there is more than one. - - 🔴 THE INSTANCE PREFIX IS A `[alias] ` ON THE LINE, NOT A THIRD PATH - SEGMENT. A consumer splits these on `/` expecting exactly two parts; making - it `alias/scope/entry.md` would silently re-point every such split at the - wrong field. The prefix is absent entirely on a single-instance host. - """ - routing = _routing() - refusal = _refuse_shared_cache(args, routing, "ls-entries") - if refusal is not None: - return refusal - worst = EXIT_OK - for instance in routing.instances: - label = instance.alias if routing.multi_instance else None - cache = _instance_cache(args, instance.alias) - state, detail, hint = resolve_state( - cache, - no_sync=args.no_sync, - scope=None, - timeout=_store_timeout(args), - instance=instance.alias, - ) - print(banner(state, detail, label), file=sys.stderr) - if hint is not None: - worst = max(worst, hint) - continue - prefix = "" if label is None else f"[{label}] " - listed: list[str] = [] - scopes: set[str] = set() - # ⚠ THIS `glob` SWALLOWS `EACCES` ON A SCOPE DIRECTORY, AND IS NOT CHANGED - # HERE — SAID PLAINLY SO IT IS NOT MISTAKEN FOR COVERED. `Path.glob("*/*.md")` - # skips a mode-000 child and lists its siblings, so this verb answers **0** - # and says nothing for a directory `recall`, `search` and `validate` each - # answer **3** on with `index entry unreadable`. Both clients AGREE at 0 — - # `internal/client.LsEntries` discards the same error on purpose — so it is an - # inconsistency inside each client, not a divergence between them. NOT closed: - # it would move a verb's stdout and exit code on both clients, and - # `ls-entries` fans out over every configured instance, so failing closed - # first has to decide whether one unreadable scope refuses the whole listing - # or only that instance's. - for path in sorted(cache.glob("*/*.md")): - # 🔴 A SCOPE'S `README.md` IS ITS POLICY SHEET, NOT AN ENTRY — AND - # THIS VERB IS THE ONE THAT ADVERTISES ITSELF AS "what the cache - # actually holds". The glob above is the bare `*.md` walk `load_index` - # deliberately does NOT use, so until this line existed `ls-entries` - # listed every scope's sheet as `/README.md` — measured twelve - # of them on a populated cache, under a banner naming the store they - # came from. The predicate is the LOADER'S, imported rather than - # respelled, because respelling it is how the two answers came apart. - # - # ⚠ FILTERED AFTER THE GLOB RATHER THAN BY WALKING SCOPE DIRECTORIES, - # AND THE ORDER IS THE REASON — BUT NOT THE ONE AN EARLIER FORM OF - # THIS COMMENT GAVE, WHICH HAD IT BACKWARDS. `sorted()` over `Path` - # OBJECTS compares component by component, so this client prints - # `a/y.md` BEFORE `a-b/x.md`; a per-scope walk whose joined - # `scope/name` strings are sorted compares BYTES, where `-` (0x2d) - # sorts below `/` (0x2f), and would print `a-b/x.md` first. So the - # glob IS load-bearing here — it just orders the opposite way round - # from what was written. MEASURED end to end on this client. - # - # ⚠ THE VISITED SET IS NOT A REASON: measured over a cache holding a - # dot-named scope directory and a symlinked one, `cache.glob("*/*.md")` - # and a per-scope `iterdir()`+`is_dir()` walk return the SAME files. - # - # 🔴 AND THE GO CLIENT PRINTS THE OTHER ORDER ON SOME PREFIXED SCOPE - # NAMES — BUT NOT ON ALL OF THEM, AND THIS COMMENT SAID "any cache - # where one scope name is a prefix of another", WHICH IS MEASURABLY - # FALSE. The mechanism is BYTE-WISE vs COMPONENT-WISE: the Go client - # sorts the joined `scope/name` byte by byte, while `sorted()` here - # compares `Path._parts_normcase`, a tuple, component by component - # (CPython 3.12.14). Where scope `S` is a proper prefix of scope `T`, - # this client always puts all of `S`'s files first (`S` < `T` as - # strings); Go compares `/` (0x2f) against `T`'s first byte PAST the - # prefix, so it AGREES when that byte sorts above `/` and DIVERGES - # when it sorts below. MEASURED end to end on both clients over a - # two-scope cache: `a`/`a0` (`0`, 0x30), `a`/`a_b` (`_`, 0x5f) and - # `a`/`aZ` (`Z`, 0x5a) AGREE; `a`/`a-b` (`-`, 0x2d), `a`/`a.b` (`.`, - # 0x2e) and `a`/`a+b` (`+`, 0x2b) DIVERGE. A non-prefixed pair cannot - # diverge at all — the first differing byte then lies inside both - # scope names, where the two comparisons agree. Seeding `a`/`a0`, - # which the old sentence invites, yields a GREEN and leaves the gate - # exactly as blind. No parity-corpus scope name is a prefix of - # another, so the gate has never been handed the discriminating - # input. PRE-EXISTING (both sorts predate this change) and - # deliberately NOT fixed here: it needs a corpus pair and a decided - # direction, which is a behaviour change to a verb's stdout. - if not subsystem_resolver.is_entry_filename(path.name): - continue - listed.append(f"{prefix}{path.parent.name}/{path.name}") - scopes.add(path.parent.name) - # The read ledger: one record per scope LISTED, sorted — the Go client's `listedScopes`. - read_ledger.record_all(instance.alias, sorted(scopes)) - for line in listed: - print(line) - return worst - - -def _report(args: argparse.Namespace, *, search: str | None) -> int: - routing = _routing() - # 🔴 `--all-scopes` NAMES NO SCOPE, SO IT IS NOT ROUTED — IT FANS OUT. Asking - # the routing table about this repo's scope here would refuse a fleet-wide - # search because the scope the caller did not name is unregistered, which is - # a refusal about a question nobody asked. - if search is not None and getattr(args, "all_scopes", False) and routing.multi_instance: - return _search_every_instance(args, routing, search) - - # 🔴 THE SCOPE IS DERIVED BEFORE THE SYNC, BECAUSE IT DECIDES WHICH STORE TO - # SYNC. The failure ORDER is preserved deliberately: a store that cannot be - # read is still reported before a scope that cannot be derived, because that - # is what this command has always done and the two are independent. - scope: str | None = None - scope_error: str | None = None - try: - # `scope_for_repo` raises GitError outside a git repo — previously - # uncaught, so `cairn recall` in a plain directory exited 1 with a - # traceback and the EXIT_USAGE path below was unreachable for the - # commonest way to hit it. - scope = args.scope or scope_for_repo(args.repo) - except Exception as exc: # GitError and anything else the resolver raises - scope_error = ( - f"cairn: could not derive a scope from {args.repo!r}: {exc}\n" - f" pass --scope explicitly." - ) - if scope_error is None and not scope: - scope_error = "cairn: --scope is required (no scope could be derived)" - - if scope_error is None: - try: - alias, label, cache = _instance_for(args, scope) - except cairn_instances.UnroutedScope as exc: - # 🔴 BEFORE THE NETWORK. Nothing is fetched, nothing is written, and - # no cache is touched: the client does not know where this scope - # lives, so any store it contacted would be a guess. - return _unrouted(exc) - else: - # No scope means nothing to route; the default instance is the one this - # host has always read, and the usage error below is the real answer. - alias, label, cache = _read_store.DEFAULT_ALIAS, None, args.cache - - # 🔴 SYNC THE WHOLE STORE, NEVER `scope=args.scope`. A scope-filtered cache - # makes the reader answer `scope-absent` for every scope that was simply not - # fetched — indistinguishable, in the output, from a scope the store has - # never held. That is the silent-zero this file exists to prevent, and the - # first draft of this function had it. - state, detail, hint = resolve_state( - cache, no_sync=args.no_sync, scope=None, timeout=_store_timeout(args), - instance=alias, - ) - if hint is not None: - print(banner(state, detail, label), file=sys.stderr) - return hint - if scope_error is not None: - print(scope_error, file=sys.stderr) - return EXIT_USAGE - - if search is not None: - # 🔴 WRAPPED FOR THE REASON THE RECALL BRANCH'S OWN `try` GIVES, AND IT BECAME - # REACHABLE WITH `--ref-to`. Every other operand this branch passes is a module - # constant, so `rc.search` could not raise `ValueError` here and the bare call was - # correct; `--ref-to` is the first caller-supplied one, and a malformed operand - # would traceback at rc 1 where the recall branch answers 2 with the message - # alone. A wrapper that tracebacks where the module it wraps explains itself is - # worse than not offering the flag. - try: - report = rc.search( - str(cache), - scope, - search, - context=rc.CONTEXT_BULLET, - threshold=rc.DEFAULT_SEARCH_THRESHOLD, - max_hits=rc.DEFAULT_MAX_HITS, - all_scopes=args.all_scopes, - ref_to=args.ref_to, - tag=args.tag, - ) - except ValueError as exc: - print(f"cairn: {exc}", file=sys.stderr) - return EXIT_USAGE - read_ledger.record(alias, read_ledger.ALL_SCOPES if args.all_scopes else scope) - read_ledger.record_named(alias, report) - text = rc.render_search(report, instance=label) - else: - # 🔴 THE DIGEST'S OWN FOOTER PRESCRIBES THESE FLAGS, so the client has to - # have them. It told readers "`--ref ` prints any one of them in - # full; `--limit N` prints them all" while this subcommand exited 2 on - # both — documentation naming a drill-down the shipped binary lacked, - # which sends a reader to a dead end and then to the raw module. - # The mapping and the refusals are `rc`'s, NOT re-derived here: a second - # copy of either is the shape that ends up wrong on one side. - refusal = rc.reject_recall_flags( - ref=args.ref, listing=args.listing, limit=args.limit, page=args.page - ) - if refusal is not None: - print(f"cairn: {refusal}", file=sys.stderr) - return EXIT_USAGE - selection = rc.recall_selection( - listing=args.listing, limit=args.limit, page=args.page - ) - # `--mode` stays authoritative when the caller passed it explicitly: - # it predates these flags and something may already drive it. - mode = args.mode if args.mode != rc.DEFAULT_MODE else selection.mode - # 🔴 THE FEATURED-ENTRY PICK NEEDS A FOCUS WINDOW, AND THIS CLIENT NEVER - # BUILT ONE — so the digest it printed could ONLY ever say - # `most-recent fallback`, whatever was actually relevant. Measured on a - # real store, same repo and same moment: - # client -> "most-recent fallback ... (no handoff doc to read a - # path window from)" - # the module -> "resolved via claudedocs/handoff-.md — 11 of - # 48 quoted path(s) name it" - # The parenthetical was the tell and it was WRONG about the world: there - # was a handoff doc, this client just never looked. That inverted the - # advice everything gives — the wrapper readers are told to run was - # strictly worse than the raw module they are told not to. - # The condition mirrors the module's own: a window is a claim about - # THIS repo's newest handoff doc, so it is meaningless once the caller - # names a scope directly or asks for a non-default mode. - window = ( - rc.focus_window(args.repo) - if mode == rc.DEFAULT_MODE and args.scope is None - else rc.FocusWindow() - ) - # 🔴 REACHABLE ONLY BECAUSE THIS COMMIT EXPOSED `--limit`/`--page`, and - # it was watched: before this guard, `cairn recall --limit 0` raised - # `ValueError: limit must be an int >= 1` as an UNCAUGHT traceback at - # rc 1. The module's own CLI entrypoint has always caught it and - # answered 2 with the message alone; a wrapper that tracebacks where - # the module it wraps explains itself is worse than not offering the - # flag. (Spelled without the callee's name on purpose: a ledger in - # `tests/test_subsystem_read_store.py` greps this file's TEXT to prove - # the client reaches the library and never that entrypoint, and a - # comment quoting it is indistinguishable from a call.) - try: - report = rc.recall( - str(cache), - scope, - ref=args.ref, - ref_to=args.ref_to, - tag=args.tag, - limit=selection.limit, - mode=mode, - page=selection.page, - focus_paths=window.paths, - focus_source=window.source, - ) - except ValueError as exc: - print(f"cairn: {exc}", file=sys.stderr) - return EXIT_USAGE - read_ledger.record(alias, scope) - read_ledger.record_named(alias, report) - text = rc.render_text(report, instance=label) - - # An empty scope reached through a LIVE fetch is `scope-empty`; the same - # emptiness behind a cache stays `cached`, because we did not reach the - # store and cannot claim the emptiness is the store's. - if state == STATE_LIVE and getattr(report, "status", "") in ( - "scope-empty", - "scope-absent", - ): - # 🔴 KEEP `detail`, DO NOT REPLACE IT. The previous version overwrote it - # wholesale, which threw away the server's freshness stamp exactly when - # it mattered most: if the pod could not read a scope, that stamp is - # where `newest=UNREADABLE` appears, and discarding it turned an - # unreadable scope into a confident "nothing recorded". The server now - # 503s on an unreadable scope so this should be unreachable for THAT - # cause — but the evidence stays attached regardless, because "should be - # unreachable" is not a property to bet the silent-zero on. - state = STATE_EMPTY - detail = f"reached the store; nothing recorded for this scope — {detail}" - - print(banner(state, detail, label)) - print() - print(text) - # 🔴 THE READER'S OWN EXIT CODE, PASSED THROUGH. The module docstring - # promised this ("the reader's own non-zero codes pass through unchanged so - # a malformed entry still reports what it always did") while the code - # hardcoded 0. Measured on an all-malformed scope: `subsystem_recall.py` - # exited 3, `cairn recall` exited 0. The stdout text was loud either way, so - # a human was not deceived — but `/resume` step 4 branches on the CODE, and - # a machine consumer was. `_exit_for` is the reader's own decision, reused - # rather than re-derived, exactly as the server does in `_serve_report`. - # `label` is DERIVED, not an attribute — `RecallReport` has no `.label`, and - # assuming it did was an AttributeError that took every recall to exit 1. - # Derived exactly as the server does in `_recall`, so the two agree. - # 🔴 SEARCH USES ITS OWN LABEL. `SearchReport.label` is a property naming the - # scopes SEARCHED; passing the query instead made the reader's failure - # sentence say "`lease` holds 1 entry file" — naming the search term as if it - # were a scope path. The server passes `report.label` for search and derives - # `f"{scope}/"` only for recall; this now matches both. - label = report.label if search is not None else f"{report.scope}/" - return rc._exit_for(report.status, label, report.malformed) - - -def cmd_recall(args: argparse.Namespace) -> int: - return _report(args, search=None) - - -def cmd_search(args: argparse.Namespace) -> int: - return _report(args, search=args.query) - - -def cmd_validate(args: argparse.Namespace) -> int: - """Validate the CACHE with the writer's own parser. - - 🔴 THIS COMMAND NEVER WORKED. It shelled `subsystem_recall.main` with - `--validate`, which is a WRITER-half flag — the reader has no such - option, so every invocation exited 2 with `unrecognized arguments: - --validate`. Worse, the test written to close the "no validate coverage" - gap asserted only that the cache directory was unchanged, so it passed - green over a command that failed on every input. A test that cannot - distinguish "worked" from "exited 2" is not coverage. - - The docstring also claimed "`subsystem_recall.py --validate` already answers - that one", which was the same false belief stated as justification. - """ - # 🔴 ONE INSTANCE, ROUTED BY `--scope`/`--repo` LIKE A READ. Validation is a - # claim about the bytes of a particular cache, so it names which one rather - # than merging several — a merged verdict could not say where the malformed - # file is. - scope = args.scope or _repo_scope(args) - try: - alias, label, cache = ( - _instance_for(args, scope) if scope else _default_instance(args) - ) - except cairn_instances.UnroutedScope as exc: - return _unrouted(exc) - # `scope=None` — see the note in `cmd_sync`. `--scope` still narrows what is - # VALIDATED (below); it must never narrow what is CACHED. - state, detail, hint = resolve_state( - cache, no_sync=args.no_sync, scope=None, timeout=_store_timeout(args), - instance=alias, - ) - if hint is not None: - print(banner(state, detail, label), file=sys.stderr) - return hint - print(banner(state, detail, label), file=sys.stderr) - # 🔴 THE CACHE IS A MULTI-SCOPE STORE; `--validate` IS SCOPE-BOUND. With no - # `--scope` the writer derives one from the REPO, so `cairn validate` in any - # checkout validated a scope the cache does not hold and printed "NOTHING - # WAS CHECKED — a zero here is NOT a clean bill of health" while exiting 0. - # That is the silent zero this command exists to detect, committed by the - # command itself. With no --scope we validate EVERY scope in the cache. - # - # ⚠ THIS READ OF THE CACHE ROOT IS UNWRAPPED, AND THAT IS NOT CLOSED HERE — - # STATED SO A READER DOES NOT TAKE THE TWO CASES BELOW AS COVERING IT. It is the - # cache ROOT, one level above the scope directories `load_store` walks, so its - # `OSError` is not the `EntryUnreadableError` `main()`'s reader-error arm - # catches. MEASURED at `8ddbb6f`, `--no-sync`, one cache holding one readable - # scope, `chmod` on the ROOT: at mode 0111 (searchable, not readable — the stamp - # `stat` in `resolve_state` succeeds, so execution reaches here) this verb exits - # **1** with a `PermissionError` traceback while the Go client exits **3** - # printing its own raw `open : permission denied`; at 0000/0444 the stamp - # `stat` raises first and every verb is 1 against 3. Both are the cache-ROOT - # depth of `tests/parity/README.md` row 4, which carries them with a closing - # condition. UNGATED. - held = sorted(p.name for p in cache.iterdir() if p.is_dir()) - if args.scope: - # 🔴 THE SILENT ZERO THIS FUNCTION WAS REWRITTEN TO CLOSE, STILL OPEN ON - # THIS BRANCH. The no-scope path was fixed to enumerate the cache; the - # explicit `--scope` path passed the value straight through, so - # `cairn validate --scope no-such-scope` printed the writer's own - # "NOTHING WAS CHECKED — a zero here is NOT a clean bill of health" and - # exited 0. The docstring above names that failure mode verbatim while - # the branch that commits it went unguarded — the fix covered the case - # it was looking at, not the predicate. - if args.scope not in held: - if held: - # The refusal LISTS every scope the cache holds: `*` (Go: `Validate`). - read_ledger.record(alias, read_ledger.ALL_SCOPES) - print( - f"cairn: cache holds no scope {args.scope!r} — " - f"nothing was validated. Held: {', '.join(held) or '(none)'}", - file=sys.stderr, - ) - return EXIT_USAGE - scopes = [args.scope] - else: - scopes = held - if not scopes: - print( - f"cairn: nothing to validate — {cache} holds no scopes", - file=sys.stderr, - ) - return EXIT_UNREACHABLE_NO_CACHE - worst = EXIT_OK - for scope in scopes: - # 🔴 THE RESOLVER IS THE PARSER, so `validate` and `recall` cannot - # disagree about what "malformed" means. This used to shell into a - # separate authoring tool's `--validate`, which was a second - # implementation of the same predicate — exactly the shape that lets a - # file validate clean and then fail to render. - # - # 🔴 AND IT READS THROUGH `load_store`, NOT `load_index` DIRECTLY — A POLICY - # SITE, NOT A SPELLING. `load_index`'s RESIDUAL LEDGER says a `TAKE` kind - # whose `read_text` raises "fails closed into a store-wide - # `EntryUnreadableError`"; that wrap lives in `load_store`, and this line - # used to bypass it, so the ledger's sentence was simply not true of this - # verb. A `chmod 000` entry left a raw `PermissionError` escaping - # `cmd_validate` as a TRACEBACK at exit 1. MEASURED over one scope holding - # one mode-000 entry: `subsystem_recall.py --store ` → 3 with the - # named sentence, `cairn validate` → 1 with a stack trace, the Go client → - # 3. Reading through the ONE function that owns the policy is what makes - # the ledger true here too, instead of a second `except OSError` at this - # site. #111. - _store, index = rc.load_store( - cache, - verb="validated", - visible_scopes=[scope], - ) - read_ledger.record(alias, scope) - malformed = index.malformed - for entry in malformed: - print(f"cairn: {scope}: malformed: {entry}", file=sys.stderr) - # 🔴 REPORT WHAT WAS CHECKED, NOT ONLY WHAT WAS WRONG. Until this line - # a CLEAN scope printed NOTHING and exited 0, which is byte-identical - # to a validate that parsed no files at all — and this command is the - # post-write check the index-write protocol MANDATES, so that zero was - # being read as "the entry I just wrote is fine". The docstring above - # says this command was rewritten to close "the silent zero"; it then - # committed a different one, on the success path instead of the empty - # one. A count that MOVES with the store is what makes the zero mean - # something: parse one entry and it says 1, parse none and it says 0 - # and you can see that it did nothing. - # - # 🔴 `cache`, NOT `args.cache` — AND THIS IS AN AUTHORISED CHANGE TO THE ORACLE. - # P1's rule is that `server/server.py` and this client are the golden source and are - # not edited to make the port agree; the standing exception is a defect the contract - # cannot contain, and it is granted by the OPERATOR, per site, in writing. The - # precedent is `seeded=UNREADABLE` — recorded because "a contract cannot include - # 'sometimes truncate the response mid-stream'". The same sentence applies here: a - # contract cannot include "sometimes print a NEGATIVE count". - # - # `_instance_for` above, `cache.iterdir()` and `load_index(cache, …)` all read the - # ROUTED instance; this one line globbed `args.cache`, the DEFAULT instance's root. - # On a host where `--scope` routes elsewhere the numerator and the denominator came - # from two different stores, so the command whose entire job is to make a zero mean - # something printed `0 of 0 entry file(s) parse, 0 malformed` over a scope holding a - # readable entry — and, with a malformed file in the routed store, `-1 of 0 … 1 - # malformed`, a count below zero. Measured against the Go client over one world: - # `0 of 0` vs `1 of 1` at exit 0, and `-1 of 0` vs `1 of 2` at exit 5. - # - # ⚠ THE EXCEPTION IS THIS LINE AND NOTHING ELSE. It does not license changing the - # oracle to match the port anywhere else, and the scope of it is written down in - # `tests/parity/README.md` beside the `seeded=UNREADABLE` precedent. - # - # 🔴 AND AN EXIT-CODE-ONLY PARITY ROW WOULD HAVE SEEN NEITHER SYMPTOM: both clients - # exit 0 on the clean store and 5 on the malformed one. The count lives on stdout, so - # `validate-routed-to-a-NON-DEFAULT-instance` compares stdout, stderr AND the code. - # - # 🔴 `README.md` IS NOT AN ENTRY, AND THE NUMERATOR ALREADY KNEW THAT. The - # rejections come from `load_index`, which skips `README.md` in every scope - # ("each scope dir carries one as its store-policy sheet"); this count came - # from a bare `*.md` glob that did not. Two walks, one line — and `/snapshot` - # ships those READMEs, so this fired against the real store: a scope holding - # two entries beside its policy sheet printed `3 of 3`, a scope holding ONLY - # a policy sheet printed `1 of 1`, and — the direction that misleads — one - # BROKEN entry beside a README printed `1 of 2 … 1 malformed`, asserting that - # a file parsed when none had. This is the command whose whole job is making - # a zero mean something. - # - # 🔴 THE DENOMINATOR NOW APPLIES THE LOADER'S OWN RULE FOR WHAT AN ENTRY IS, - # THROUGH THE LOADER'S OWN WALK FUNCTION — AND THAT IS ALL IT IS. The first - # fix filtered a `*.md` glob with an open-coded `p.name != "README.md"`, - # which closed the symptom and left the mechanism — two spellings of one - # rule behind one line — intact. `entry_files_in` is the function - # `load_index` enumerates with, so the numerator and the denominator cannot - # come to disagree about what an ENTRY is. - # - # 🔴 THEY CAN STILL DISAGREE ABOUT WHICH DIRECTORIES TO COUNT, AND AN EARLIER - # FORM OF THIS COMMENT CLAIMED OTHERWISE — IT SAID "THE DENOMINATOR IS NOW - # THE LOADER'S OWN WALK", WHICH IS FALSE. It is the loader's RULE over a - # DIFFERENT DIRECTORY SET: `load_index` selects scope directories through - # `visible_scope_set`, which compares `normalize_ref(name)` — FOLDED — so - # every directory whose name normalizes to `--scope`'s value feeds the - # numerator, while this line walks the ONE LITERAL `/` - # directory. MEASURED at this commit on both clients over a cache holding - # `kelp-forest/a.md` and `Kelp_Forest/b.md`, both unparseable: - # - # cairn --cache validate --scope kelp-forest --no-sync - # → cairn: kelp-forest: -1 of 1 entry file(s) parse, 2 malformed (exit 5) - # - # A NEGATIVE count — exactly what the block above calls the thing a contract - # cannot include. PRE-EXISTING and IDENTICAL in both clients, so the parity - # gate is structurally blind to it. Deliberately NOT closed here: deciding - # whether `--scope kelp-forest` means the folded set or the literal directory - # changes a verb's stdout and needs its own change. CLOSING CONDITION — a - # merged PR carrying a test per client that seeds those two directories and - # asserts the printed line, shown RED at this commit; mechanically, - # `python3 -m pytest tests -q -p no:randomly -k fold_vs_literal` and - # `go test ./internal/client/ -run FoldVsLiteral -count=1 -v` each SELECT at - # least one test and exit 0. - # - # ⚠ THIS IS THE SECOND READ OF THE SCOPE DIRECTORY IN THIS LOOP, AND IT IS - # OUTSIDE EVERY WRAP — NOT CLOSED, SO SAID HERE. `load_store` above already - # walked the same directory INSIDE the wrap that produces the named - # `index entry unreadable` sentence, which is why no `chmod` and no static - # world reaches this line: an unreadable or absent directory fails that first - # walk closed and this one is never evaluated. What DOES reach it is the world - # changing mid-run — a concurrent `cairn sync` whose `install_snapshot` - # renames the cache root aside and `rmtree`s the retired one. `entry_files_in` - # now walks with `iterdir()`, so that raises `FileNotFoundError` past - # `main()`'s `(StoreMissingError, ResolverError)` arm as a TRACEBACK at exit - # 1, where the Go client's `EntryFileNames` error is discarded and it prints - # `0 of 0 entry file(s) parse, 0 malformed` at exit 0 (MEASURED at `e162746` - # over one cache holding two scopes, the second removed after the first - # scope's line was printed). UNGATED, and declared in - # `tests/parity/README.md` → "What the gate structurally cannot see". - entry_paths = subsystem_resolver.entry_files_in(cache / scope) - checked = len(entry_paths) - print( - f"cairn: {scope}: {checked - len(malformed)} of {checked} " - f"entry file(s) parse, {len(malformed)} malformed" - ) - # 🔴 THE PARSE COUNT IS NOT THE WRITE-PROTOCOL CHECK, AND UNTIL THESE - # BLOCKS IT WAS THE WHOLE OF WHAT THIS COMMAND REPORTED. "Would the loader - # accept this file?" is answered by the line above; an entry can pass it - # while holding text NO reader will ever surface. `dropped lines:` is the - # half that means content is ALREADY LOST — the file holds it, the store - # holds it, and `--ref`, `--search`, the digest and every openness count - # skip it. A post-write check that cannot see that is checking the parser, - # not the write. - # - # 🔴 THEY SCAN THE MALFORMED FILES TOO, and that is not an oversight: every - # scanner is tolerant by construction (an unreadable file or a missing - # nuance section contributes nothing), and a file the loader rejected can - # still hold lost content that a later fix to its front matter would not - # restore. The rejection above is still the finding that matters, which is - # why these print BELOW it and change no verdict. - # - # 🔴 NEITHER MOVES `worst`. The write protocol branches on this command's - # EXIT CODE to mean "write NOTHING", so failing here would stop a session - # recording anything into an entry whose only defect is that an OLDER - # write lost a line — which makes the store lossier, not safer. A gate an - # author cannot turn green by fixing the file they are writing is worse - # than no gate. - # 🔴 THE ADVISORIES' DENOMINATOR IS `scanned_entry_count`, NOT `checked`, - # AND THAT IS A THIRD SET. `checked` is the LISTING — every `*.md` name in - # the scope directory — which is right for the parse line above, because - # the loader tries every one of them. The scanners do not: they read only - # the kinds the loader's table TAKES, refusing a FIFO, a device, a - # directory or a dangling link before `open()`. Handing them `checked` - # printed a zero over files nothing opened — MEASURED on a scope holding - # one entry beside a FIFO: `dropped lines: 0 across 2 entry file(s)`, one - # of them never read. The FIFO is not lost from the output; the line above - # reports it malformed and drives the exit to 5. - # - # 🔴 FOUR BLOCKS, AND `entry shape:` PRINTS FIRST FOR A REASON THE OTHER - # THREE CANNOT STATE FOR THEMSELVES. All three of the others read only - # `## Nuance / work-history`, so an entry whose heading is RENAMED - # contributes zero to every one of them — `open actions: 0 declared` over a - # section no parser ever reached. The shape block is the one that says why, - # and it has to be ABOVE them to be read as the reason rather than as an - # afterthought. None of the four moves `worst`. - for line in entry_shape.validation_advisory_lines( - n_scanned=entry_shape.scanned_entry_count(entry_paths), - shape=entry_shape.scan_entry_shape(entry_paths), - dropped=entry_shape.scan_dropped_lines(entry_paths), - open_actions=entry_shape.scan_open_actions(entry_paths), - unreachable=entry_shape.scan_unreachable_markers(entry_paths), - ): - # A blank separator stays blank — prefixing it would print a trailing - # `cairn: : ` with nothing after it, and the parity gate would - # then pin that noise in both clients forever. - print(f"cairn: {scope}: {line}" if line else "") - worst = max(worst, EXIT_CORRUPT if malformed else EXIT_OK) - return worst - - -# ============================================================================= -# THE WRITE PATH (criterion 9). Everything above this line reads. -# ============================================================================= -# -# 🔴 WRITE-THROUGH, NO SPOOL, NO CACHE FALLBACK. The pod is the authority; the -# local cache is a read-through copy with no authority of its own. A write that -# cannot reach the pod is REFUSED, loudly, at a non-zero exit — it is never -# queued, never written to the cache, and never reported as done. `/resume` and -# every other READ keeps working offline off the cache; only writes stop. That -# asymmetry is decision 8 in `claudedocs/plan-cairn-integration.md` and the -# reason it is acceptable is that a refused write costs one retry while a -# silently-local write costs the bullet the next `seed.sh` overwrites. -# -# 🔴 THE ACTOR IS NOT SENT AND CANNOT BE. `server._append_bullet` derives it -# from the token that authenticated and DISCARDS any `actor` key in the body. -# This client therefore does not have an `--actor` flag: offering one would -# imply a control the caller does not have. - - -class WriteRefused(Exception): - """The store answered, and the answer is a refusal. Carries its own code. - - 🔴 SEPARATE FROM `StoreUnreachable` FOR THE SAME REASON `StoreCorrupt` IS. - "I could not ask" and "I asked and was told no" have different remedies — - retry vs change the request — and a client that collapses them turns a - permanently-malformed bullet into an infinite retry, or a transient outage - into "the store rejected this, give up". - """ - - def __init__(self, exit_code: int, status: str, detail: str) -> None: - super().__init__(detail) - self.exit_code = exit_code - self.status = status - self.detail = detail - - -# HTTP status -> (our exit code, whether the caller should retry unchanged). -# 🔴 A TABLE, NOT AN `if` LADDER, so `test_every_documented_server_status_maps` -# can walk it against the statuses `server.py` actually emits on a write route. -# An unmapped code is NOT silently treated as success: `_classify` falls through -# to EXIT_WRITE_REFUSED and says the code was unrecognised, which is loud and -# wrong-in-the-safe-direction (the caller is told the write did not land). -_WRITE_STATUS_EXITS: dict[int, int] = { - 400: EXIT_WRITE_REFUSED, # malformed body / ambiguous ref - 401: EXIT_WRITE_REFUSED, # no or bad credential - 403: EXIT_WRITE_REFUSED, # edge refusal (see the User-Agent note) - 404: EXIT_WRITE_REFUSED, # scope-unknown or ref-unknown - 405: EXIT_WRITE_REFUSED, # read-only image: the write path is NOT deployed - 412: EXIT_WRITE_PRECONDITION, # If-Match named a revision the entry no longer has - 422: EXIT_WRITE_REFUSED, # entry-shape: no `## Nuance / work-history` - 428: EXIT_WRITE_REFUSED, # precondition required (a PUT with no If-Match) - 429: EXIT_WRITE_UNREACHABLE, # rate limited — a retry IS the right response - # 🔴 500 IS A RETRY, NOT A "FIX YOUR REQUEST". `server._backstop` turns any - # unhandled handler exception into a 500, so it IS reachable on a write - # route. It was absent here and fell through to `_classify`'s "unrecognised" - # arm, which is EXIT_WRITE_REFUSED — telling the caller to change a - # byte-identical request that would very likely succeed on a retry. The - # fallthrough was labelled "wrong-in-the-safe-direction", and that is true - # for landed/not-landed and FALSE for retry/don't-retry, which is the exact - # distinction 6 and 7 exist to carry. - 500: EXIT_WRITE_UNREACHABLE, - 502: EXIT_WRITE_UNREACHABLE, # a bad gateway is the edge, not the request - 503: EXIT_WRITE_UNREACHABLE, # the server could not read its own store - 504: EXIT_WRITE_UNREACHABLE, -} - - -# 🔴 A SECOND TABLE, KEYED ON THE SERVER'S `X-Store-Status` TOKEN, CONSULTED -# FIRST. It exists because one HTTP status can carry two outcomes with opposite -# remedies: `412` is `precondition-failed` (the entry moved — retry after a -# re-sync) on a `put`, and `already-exists` (it is there — do not retry) on a -# `create`. The code table above cannot express that, and collapsing the two -# would give a `create` caller an exit that says "re-derive and try again" for a -# condition no retry can change. -# -# 🔴 A TOKEN NOT IN THIS TABLE FALLS THROUGH TO THE CODE TABLE, never to a pass. -# The token is advisory routing, not the verdict. -_WRITE_STATUS_TOKEN_EXITS: dict[str, int] = { - "already-exists": EXIT_WRITE_EXISTS, -} - - -def _classify(code: int, status: str, detail: str) -> WriteRefused: - by_token = _WRITE_STATUS_TOKEN_EXITS.get(status) - if by_token is not None: - return WriteRefused(by_token, status, detail) - exit_code = _WRITE_STATUS_EXITS.get(code) - if exit_code is None: - return WriteRefused( - EXIT_WRITE_REFUSED, - status or f"http-{code}", - f"unrecognised HTTP {code} on a write route — treating the write as " - f"NOT LANDED: {detail}", - ) - return WriteRefused(exit_code, status or f"http-{code}", detail) - - -def send_write( - url: str, - token: str, - *, - method: str, - path: str, - body: bytes, - timeout: int, - extra_headers: dict[str, str] | None = None, -) -> tuple[dict[str, str], bytes]: - """One request against a write route. Returns `(headers, body)` on 200. - - Raises `WriteRefused` on any non-200 the server produced, and - `StoreUnreachable` when there was no answer at all. Nothing else escapes. - """ - bad = unbounded_timeout_reason(timeout) - if bad: - # 🔴 THE SAME REFUSAL THE READ PATH MAKES, FOR THE SAME REASON. A - # `timeout=None` reaches `urlopen` as NO timeout, and an unbounded WRITE - # is strictly worse than an unbounded read: the request may already have - # been applied, so a caller that eventually gives up cannot tell whether - # it landed. - raise StoreUnreachable(f"refusing to write to {url}: {bad}") - target = f"{url}{path}" - req = urllib.request.Request(target, data=body, method=method) - _apply_standard_headers(req, token) - req.add_header("Content-Type", "application/json") - for name, value in (extra_headers or {}).items(): - req.add_header(name, value) - try: - with urllib.request.urlopen(req, timeout=timeout) as resp: - # `resp.headers` returned as the Message, never `dict(...)` — see - # `fetch_snapshot` for the measured case-folding incident. - return resp.headers, resp.read() - except urllib.error.HTTPError as exc: - try: - detail = exc.read().decode("utf-8", "replace").strip().replace("\n", "; ") - except Exception: - detail = "" - status = exc.headers.get("X-Store-Status", "") if exc.headers else "" - raise _classify(exc.code, status, detail[:400] or f"HTTP {exc.code}") from exc - except urllib.error.URLError as exc: - raise StoreUnreachable(f"{url} unreachable: {exc.reason}") from exc - except OSError as exc: - raise StoreUnreachable(f"{url} unreachable: {exc}") from exc - - -def _write_scope(args: argparse.Namespace) -> str | None: - """The scope a write targets, or None having already printed why.""" - try: - scope = args.scope or scope_for_repo(args.repo) - except Exception as exc: - print( - f"cairn: could not derive a scope from {args.repo!r}: {exc}\n" - f" pass --scope explicitly.", - file=sys.stderr, - ) - return None - if not scope: - print("cairn: --scope is required (no scope could be derived)", file=sys.stderr) - return None - return scope - - -def cmd_append(args: argparse.Namespace) -> int: - """`POST /api/v1/entry///bullets` — append ONE dated bullet. - - 🔴 THIS IS THE VERB CRITERION 9 ROUTES `subsystem-index` THROUGH. Before it - existed the skill's append was an `Edit` against `~/.claude/analyze-service- - index//.md`, which is local-only: the bullet lived on one host - and the next `seed.sh` from any host replaced the served copy with a file - that never had it. This makes the append land where the authority is. - - 🔴 DO NOT DATE-PREFIX `--text`. The server prepends `- : ` itself; the - first production append through this route reads `- 2026-08-29: 2026-08-29: - …` because a caller did. - """ - scope = _write_scope(args) - if scope is None: - return EXIT_USAGE - # 🔴 REFUSE LOCALLY, BEFORE THE NETWORK, AND SAY THE OVERAGE. The server - # enforces this cap and always did; what it could not do is tell a caller the - # limit before they had composed something over it. Measured cost of that - # asymmetry: one bullet took three full recompose-and-retry cycles because - # the only way to learn the bound was to exceed it, and nothing was written - # on any of the three. - # - # 🔴 SAME CONSTANT AS THE SERVER'S, IMPORTED — not a second 2000 typed here. - # A client-side copy that drifted LOW would refuse writes the store would - # have accepted, which is worse than the round trip it saves, and it would - # fail exactly the way this repo's other two-copy hazards do: silently, with - # both numbers looking deliberate. - # - # ⚠ THIS IS A CONVENIENCE, NOT AN AUTHORITY. The server re-checks; a client - # that skipped the check could not widen what the store accepts. Do not let a - # later refactor read this as the enforcement point. - if len(args.text) > entry_shape.BULLET_TEXT_MAX: - over = len(args.text) - entry_shape.BULLET_TEXT_MAX - print( - f"cairn: refusing to send — `--text` is {len(args.text)} characters, " - f"max {entry_shape.BULLET_TEXT_MAX} — {over} over. Nothing was " - f"written, and the store was not contacted.", - file=sys.stderr, - ) - return EXIT_USAGE - try: - alias, _, _ = _instance_for(args, scope) - except cairn_instances.UnroutedScope as exc: - return _unrouted(exc) - url, token = load_config(instance=alias) - payload = json.dumps({"text": args.text, "session": args.session}).encode("utf-8") - quoted = f"/api/v1/entry/{quote(scope, safe='')}/{quote(args.ref, safe='')}/bullets" - headers, body = send_write( - url, token, method="POST", path=quoted, body=payload, - timeout=_store_timeout(args), - ) - read_ledger.record(alias, scope) - status = headers.get("X-Store-Status", "unknown") - revision = (headers.get("ETag") or "").strip('"') - # 🔴 `duplicate` IS PRINTED, NOT SWALLOWED, and it exits 0. The server - # recognises a bullet by CONTENT HASH, so a re-POST after a timeout is - # idempotent — which is the property that makes a retry safe. But a caller - # told nothing would read "appended" into a run that wrote nothing, and the - # store's own idempotency note says a genuinely new bullet whose text is - # byte-identical to an existing one is silently NOT appended. Saying which - # of the two happened is the whole difference. - # 🔴 A WRITE ALWAYS NAMES THE INSTANCE IT LANDED ON — unconditionally, where - # a READ names it only when there is more than one. The asymmetry is the - # same one this file already makes everywhere else: a read that degrades is - # recoverable by reading again, while "where did that bullet go" is a - # question about a DURABLE record, asked later, by someone who no longer has - # this terminal. It costs one field and it is the cheap permanent answer. - print( - f"cairn: {status} instance={alias} scope={scope} ref={args.ref} " - f"revision={revision or 'unknown'}" - ) - sys.stdout.write(body.decode("utf-8", "replace")) - return EXIT_OK - - -def cmd_put(args: argparse.Namespace) -> int: - """`PUT /api/v1/entry//` — whole-file replace behind `If-Match`. - - 🔴 WHY A WHOLE-FILE VERB EXISTS AT ALL, given that `append` is the safe one: - the `subsystem-index` protocol also mandates rewriting an existing bullet's - `OPEN:` marker to `RESOLVED :` **in the same edit**, and updating - `## Pointers`. Neither is an append. Without this verb, freezing the local - store read-only would make those two operations impossible rather than - merely relocated — the cutover would REGRESS a documented protocol step. - - 🔴 THE REVISION IS DERIVED FROM A **LIVE** SYNC, NEVER FROM `--no-sync`. - `server.entry_revision` is `sha256(file bytes)[:16]`, so the cache can - compute it offline — which is exactly what makes a stale cache dangerous - here in a way it is not for a read: an edit based on bytes that moved is a - lost update, and the `If-Match` is what turns that into a 412 instead of a - silent overwrite. Deriving it from a cache we did not just refresh would - still be *correct* (the server compares against its own copy) but it wastes - the operator's edit on a guaranteed 412. `--if-match` is accepted for the - case where the caller already holds the value. - """ - scope = _write_scope(args) - if scope is None: - return EXIT_USAGE - # 🔴 READ THE FILE BEFORE THE NETWORK — AND "BEFORE THE NETWORK" MEANS ABOVE - # `resolve_state`, NOT ABOVE `load_config`. The first attempt at this fix - # moved the read up only as far as the config load, which is a local file - # read, so the full snapshot download still ran first: a missing `--file` - # went on reporting the STORE AS UNREACHABLE (rc 7) instead of "cannot read - # --file" (rc 2). The comment claimed the ordering, and the test that - # asserted it did so in its NAME while its body checked only the exit code - # and the sentence — both of which held with the read left where it was. A - # guard's description claiming coverage its body does not provide is the - # shape that stops anyone looking. - try: - payload = args.file.read_bytes() - except OSError as exc: - print(f"cairn: cannot read --file {args.file}: {exc}", file=sys.stderr) - return EXIT_USAGE - revision = args.if_match - try: - alias, _, cache = _instance_for(args, scope) - except cairn_instances.UnroutedScope as exc: - return _unrouted(exc) - if not revision: - state, detail, hint = resolve_state( - cache, no_sync=False, scope=None, timeout=_store_timeout(args), - instance=alias, - ) - if state != STATE_LIVE: - # 🔴 NOT "served from cache". A read may degrade; deriving a - # precondition from bytes we could not confirm is the one case where - # the cache is worse than nothing. - # - # 🔴 AND NOT `hint`. This returned `hint if hint is not None else - # EXIT_WRITE_UNREACHABLE`, and `resolve_state` sets `hint` to - # EXIT_UNREACHABLE_NO_CACHE (3) exactly when there is NO cache — - # which is the FIRST run on a fresh host, i.e. the commonest way to - # get here. So the one code this whole file insists a write must - # never return was returned by a write, on its likeliest path, while - # four separate comments and the design doc said it could not - # happen. `hint` is a READ verdict — "this is what a reader should - # exit with" — and it has no meaning for a write. Measured before - # the fix: put with no cache -> 3, put with a cache -> 7, append - # with no cache -> 7. - print( - f"🔴 cairn: refusing to PUT — could not refresh the cache, so the " - f"revision would be derived from bytes that may have moved " - f"({detail}). Nothing was queued and nothing was written locally. " - f"Pass --if-match explicitly if you already hold it.", - file=sys.stderr, - ) - return EXIT_WRITE_UNREACHABLE - matches = sorted(cache.glob(f"{scope}/{args.ref}.md")) or sorted( - cache.glob(f"{scope}/{args.ref}.*.md") - ) - if len(matches) != 1: - print( - f"cairn: cannot derive a revision — {len(matches)} cached file(s) " - f"match {scope}/{args.ref}. Pass --if-match, or use the entry's " - f"exact filename stem as --ref.", - file=sys.stderr, - ) - return EXIT_USAGE - revision = hashlib.sha256(matches[0].read_bytes()).hexdigest()[:16] - print(f"cairn: derived If-Match {revision} from the live snapshot", file=sys.stderr) - url, token = load_config(instance=alias) - quoted = f"/api/v1/entry/{quote(scope, safe='')}/{quote(args.ref, safe='')}" - headers, body = send_write( - url, token, method="PUT", path=quoted, body=payload, - timeout=_store_timeout(args), - extra_headers={"If-Match": f'"{revision}"'}, - ) - read_ledger.record(alias, scope) - new_rev = (headers.get("ETag") or "").strip('"') - # The instance is named unconditionally — see `cmd_append`. - print( - f"cairn: {headers.get('X-Store-Status', 'unknown')} instance={alias} " - f"scope={scope} ref={args.ref} revision={new_rev or 'unknown'}" - ) - sys.stdout.write(body.decode("utf-8", "replace")) - return EXIT_OK - - -def cmd_create(args: argparse.Namespace) -> int: - """`PUT /api/v1/entry//` with `If-None-Match: *` — a NEW entry. - - 🔴 WHY THIS VERB EXISTS, since `append` and `put` already write. Neither can - make an entry that is not there: both resolve an EXISTING ref and 404 when it - is absent. So the protocol told a session to write a brand-new entry into - `~/.claude//` directly — which was true and safe while - that tree WAS the store, and became content loss the moment reads moved to - the pod cache: measured, five whole entries existed only on one - host and were dark to every reader. This is the verb that closes it. - - 🔴 NO `--if-match`, AND NO SYNC. `put` derives a precondition from a LIVE - snapshot because it is editing bytes that may have moved; a create has no - prior bytes, and its precondition is the constant `*`. The server decides - absence under its own lock, so there is nothing a local cache read could add - except a stale answer and a wasted round trip. - - 🔴 EXIT 9 IS NOT A FAILURE TO RETRY. It means the entry already exists and - NOTHING was written — the remedy is `cairn append` (a bullet) or `cairn put` - (a rewrite), never the same `create` again. - """ - scope = _write_scope(args) - if scope is None: - return EXIT_USAGE - # 🔴 READ THE FILE BEFORE THE NETWORK, for the reason `cmd_put`'s comment - # gives at length: an unreadable `--file` must report itself (rc 2) and not - # be reported as the store being unreachable. - try: - payload = args.file.read_bytes() - except OSError as exc: - print(f"cairn: cannot read --file {args.file}: {exc}", file=sys.stderr) - return EXIT_USAGE - try: - alias, _, _ = _instance_for(args, scope) - except cairn_instances.UnroutedScope as exc: - return _unrouted(exc) - url, token = load_config(instance=alias) - quoted = f"/api/v1/entry/{quote(scope, safe='')}/{quote(args.ref, safe='')}" - headers, body = send_write( - url, token, method="PUT", path=quoted, body=payload, - timeout=_store_timeout(args), - extra_headers={"If-None-Match": "*"}, - ) - read_ledger.record(alias, scope) - revision = (headers.get("ETag") or "").strip('"') - # The instance is named unconditionally — see `cmd_append`. - print( - f"cairn: {headers.get('X-Store-Status', 'unknown')} instance={alias} " - f"scope={scope} ref={args.ref} revision={revision or 'unknown'}" - ) - sys.stdout.write(body.decode("utf-8", "replace")) - return EXIT_OK -# ============================================================================= -# DOCTOR. Reads everything, installs nothing. -# ============================================================================= - - -def _cairn_doctor(): - """The `doctor` module, imported inside a function — see `_doctor_epilog`. - - ⚠ NOT "lazily", in effect. `build_parser` calls `_doctor_epilog()` to build - the help text, so this runs on EVERY invocation of every subcommand. Saying - otherwise is a cost model a maintainer would reason from and be wrong. - """ - lib = str(Path(__file__).resolve().parent / "lib") - if lib not in sys.path: - sys.path.insert(0, lib) - import cairn_doctor # noqa: PLC0415 - - return cairn_doctor - - -#: How an operator reads the identity and the DECLARED allowlist behind a token. -#: Spelled once, printed by `doctor`, and pinned by -#: `test_cairn_doctor.py::test_the_identity_remedy_names_the_pods_own_token_file` -#: against `server.DEFAULT_TOKEN_FILE`, so it cannot drift from the path the pod -#: actually mounts. 🔴 It is a REMEDY, not a step this command takes: `doctor` -#: never reads a secret and never shells `kubectl`. -IDENTITY_REMEDY = ( - "`kubectl -n subsystem-store exec deploy/subsystem-store-api -- " - "cut -d' ' -f2,3 /run/secrets/subsystem-store/token` " - "(fields 2 and 3 are the identity and the allowlist; field 1 is the secret)" -) - - -def probe_store(url: str, token: str, *, timeout: int): - """ONE snapshot fetch, read for facts and THROWN AWAY. Never installed. - - 🔴 IT REUSES `fetch_snapshot` RATHER THAN BUILDING A SECOND REQUEST. That - keeps `_apply_standard_headers` — and the measured User-Agent requirement - behind it — on this path without a second site to forget it at, and it is - what `test_cairn_write.py::test_no_request_builder_ANYWHERE_bypasses_this_ - helper` would otherwise have to grow a case for. - - 🔴 IT NEVER CALLS `install_snapshot`. A diagnostic that repaired the cache - would destroy the staleness it was run to measure. - """ - doctor = _cairn_doctor() - try: - # 🔴 IT SENDS NO VALIDATOR, AND THE OMISSION IS THE WHOLE STATEMENT. A - # conditional probe could be answered 304, and this function's entire - # job is to COUNT WHAT THE POD WOULD SEND — visible scopes and visible - # entries, read out of the archive itself. A diagnostic that accepted - # "nothing changed" would report the cache's contents as the pod's and - # call the two in agreement by construction, which is the shape of check - # that agrees with itself. - body, headers, _not_modified = fetch_snapshot( - url, token, scope=None, timeout=timeout - ) - except StoreUnreachable as exc: - return doctor.PodFacts( - reached=False, reason=str(exc), http_status=exc.http_status - ) - - visible = headers.get("x-store-entries") - snapshot = headers.get("x-store-snapshot", "") - scopes: set[str] = set() - try: - with tarfile.open(fileobj=io.BytesIO(body), mode="r") as tar: - for member in tar.getmembers(): - if not member.isfile(): - continue - parts = Path(member.name).parts - if len(parts) == 2 and parts[1].endswith(".md"): - scopes.add(parts[0]) - except (tarfile.ReadError, EOFError, zlib.error) as exc: - return doctor.PodFacts( - reached=False, - reason=f"{url} answered, but the archive could not be read: {exc}", - ) - - # 🔴 `entry-files=` OUT OF THE STORE-WIDE HEADER, and the store-wide-ness is - # the point. `server.snapshot_freshness` counts the WHOLE served store, not - # the caller's slice — a documented, deliberate residual count leak — so the - # gap between it and `X-Store-Entries` is the only client-side evidence that - # entries exist which this credential cannot reach. - store_wide = None - for field in snapshot.split(): - key, _, value = field.partition("=") - if key == "entry-files" and value.isdigit(): - store_wide = int(value) - - # 🔴 NO FALLBACK TO THE ARCHIVE'S OWN COUNT. Without `X-Store-Entries` the - # only number available is how many members ARRIVED, which is exactly the - # side of the comparison a truncated transfer moves — substituting it would - # make the cache-vs-pod check agree with itself and report OK over a short - # answer. `install_snapshot` cross-checks against this header for the same - # reason. Absent header => the count is UNMEASURED, with that as the stated - # reason. - return doctor.PodFacts( - reached=True, - visible_entries=int(visible) if visible and visible.isdigit() else None, - store_wide_entries=store_wide, - visible_scopes=tuple(sorted(scopes)), - snapshot_header=snapshot, - ) - - -def cmd_doctor(args: argparse.Namespace) -> int: - """One call for every fact a reader otherwise assembles by hand. - - 🔴 EVERY CONFIGURED INSTANCE, CHECKED SEPARATELY, SO A HEALTHY ONE CANNOT - MASK A BROKEN ONE. The checks are per-instance rows rather than a merged - verdict, and the exit code is the WORST of them: one reachable store must - never make a second one that is down look measured. On a host with one - instance the rows are exactly what they always were — no prefix, no extra - section — because there is nothing to disambiguate. - """ - doctor = _cairn_doctor() - routing = _routing() - refusal = _refuse_shared_cache(args, routing, "doctor") - if refusal is not None: - return refusal - # `*`: per-scope visibility and counts name every scope (decision 3a). - read_ledger.record("", read_ledger.ALL_SCOPES) - checks: list = [] - for instance in routing.instances: - checks.extend(_doctor_instance(args, doctor, routing, instance)) - if args.json: - print(json.dumps(doctor.to_dict(checks), indent=2)) - else: - print(doctor.render(checks)) - return doctor.exit_code(checks) - - -def _doctor_instance(args, doctor, routing, instance) -> list: - """The checks for ONE instance, named after it when this host is routing. - - 🔴 THE NAME CARRIES THE ALIAS, NOT THE DETAIL TEXT. `doctor --json` is - consumed by machine and `render` aligns on the name column, so an alias - buried in prose would be unreadable to both. `/` keeps every - row addressable and sorts together. - """ - resolved = _read_store.resolve_read_store( - None if instance.is_default else _read_store.cache_root_for(instance.alias) - ) - - # 🔴 THE CONFIG LOAD HAPPENS EVEN UNDER `--no-sync`, AND THAT IS A FIX. It is - # a local file read, so "is a credential configured on this host" is - # answerable with the network switched off — and the first version skipped it, - # which made `doctor --no-sync` report `token PROBLEM: no token is configured` - # on a host whose token was sitting in `~/.config/subsystem-store/env` - # unread. A check that says PROBLEM about something it never looked at is the - # same defect as one that says OK about it. - token: str | None = None - token_reason = "" - try: - url, token = load_config(instance=instance.alias) - except StoreUnreachable as exc: - token_reason = str(exc) - config_error: str | None = str(exc) - else: - config_error = None - - if args.no_sync: - pod = doctor.PodFacts( - reached=False, - reason="--no-sync was given, so the store was never contacted", - ) - elif config_error is not None: - pod = doctor.PodFacts(reached=False, reason=config_error) - else: - pod = probe_store(url, token, timeout=_store_timeout(args)) - - checks = doctor.collect( - resolved_root=resolved.root, - stamp_lines=resolved.stamp, - stamp_reason=resolved.reason, - cache_root=_instance_cache(args, instance.alias), - # 🔴 THE FROZEN MIRROR BELONGS TO THE DEFAULT INSTANCE ALONE. It is the - # pre-cutover local store this host migrated FROM, so there is exactly - # one of it however many instances are configured; reporting it under - # each would state one fact N times and make N-1 of the rows a claim - # about a directory that instance has nothing to do with. - mirror_root=_mirror_root() if instance.is_default else None, - pod=pod, - token=token, - token_reason=token_reason, - identity_remedy=IDENTITY_REMEDY, - ) - if not routing.multi_instance: - return checks - return [ - type(check)(f"{instance.alias}/{check.name}", check.state, check.detail) - for check in checks - ] - - - - -def _store_timeout(args: argparse.Namespace) -> int: - """The store commands' bound, resolved in ONE place. - - 🔴 THE SENTINEL CREATED FOUR CHANCES TO FORGET. Making the top-level - `--timeout` default to `None` (so `who` can tell "not given" from an - explicit value) meant every store call site had to resolve it, and mutating - all four to pass the raw `None` through kept the whole suite green — a - `None` reaches `urllib` as NO timeout, the same unbounded wait `_run` - already refuses on the other side of this file. One resolver, four callers, - and `test_no_call_site_passes_the_RAW_sentinel_attribute` pins that no - fifth caller open-codes it, while - `test_every_STORE_subcommand_reaches_the_network_with_a_POSITIVE_bound` - covers the spellings an AST scan cannot see. `fetch_snapshot` refuses a - non-positive bound outright, so a future caller that bypasses both - fails closed rather than waiting forever. - """ - return int(args.timeout) if getattr(args, "timeout", None) is not None else DEFAULT_TIMEOUT - - - - - - - - -def _doctor_epilog() -> str: - """`doctor --help`'s exit-code legend, read from the module that owns it. - - 🔴 READ, NEVER RESTATED. A second copy of the legend in this file — or in a - SKILL.md — is a second thing to keep true, and the numbers are the part a - caller branches on. `cairn_doctor.EXIT_LEGEND` is the one definition; both - `--help` and every run's own output render it from there. - - ⚠ CALLED EAGERLY FROM `build_parser`, AND THE COMMENT THAT SAID OTHERWISE WAS - FALSE IN EFFECT. `argparse` wants `epilog` as a string, so `cairn_doctor` is - imported on EVERY invocation — the same trap the lazy-import docstring - records for `_who_default_timeout`. The import stays function-scoped for - honesty about what this file needs to START, not as an optimisation. - - 🔴 AND IT FAILS SOFT — FOR AN `ImportError`, WHICH IS NOT THE SAME AS "FOR A - BROKEN `cairn_doctor`". With `cairn_doctor.py` missing, an eager unguarded - import took `cairn ls-entries` — a subcommand that has nothing to do with - doctor — down with `ModuleNotFoundError` at exit 1, traceback and all. - `cmd_doctor` still fails LOUDLY, because that is the caller who asked for it; - an unrelated verb must not inherit the blast radius of a help string. - - ⚠ AND THE GUARANTEE STOPS AT THE `except` CLAUSE BELOW, so do not read the - paragraph above as "any broken doctor module is contained". A module that is - PRESENT but UNPARSEABLE raises `SyntaxError`, which is not an `ImportError`: - nothing here catches it, it propagates out of `build_parser`, and every verb - dies with it. Measured on a tree with `lib/cairn_doctor.py` replaced by - `def broken(` — `cairn doctor`, `cairn ls-entries`, `cairn ls-entries --help` - and `cairn --help` are ALL exit 1 with `SyntaxError`. Control on the - `ImportError` path, same tree with the file merely absent: the same four are - 1 / 3 / 0 / 0, and that 3 is the ordinary no-cache read outcome an untouched - tree gives for `ls-entries`, so the soft-fail is real — it is just narrower - than "fails soft". The epilog STRING below is accurate about this because it - only ever renders on the `ImportError` path; on the `SyntaxError` path there - is no parser to attach an epilog to. - - 🔴 WIDENING THIS `except` IS NOT THE OBVIOUS FIX. Catching `SyntaxError` here - would make `--help` render for every verb over a module that `cmd_doctor` is - about to die on, and the loud failure is the point of the design. This is - recorded, deliberately, rather than closed. - """ - try: - doctor = _cairn_doctor() - except ImportError as exc: - return ( - f"exit codes: UNAVAILABLE — `cairn_doctor` could not be imported " - f"({exc}). `cairn doctor` itself will fail with this; every other " - f"subcommand is unaffected." - ) - lines = ["exit codes:"] - lines += [f" {code} {why}" for code, why in doctor.EXIT_LEGEND] - lines.append("") - lines.append( - "check states: " - + ", ".join(doctor.STATES) - + " — UNMEASURED means the check could not look and says why; " - "NOT-OBSERVABLE means no client can answer it at all and names who can." - ) - return "\n".join(lines) - - -def cmd_routes(args: argparse.Namespace) -> int: - """Print the routing table, and grade it against what is actually there. - - 🔴 THE TABLE IS AN INPUT, NOT A CONSTANT IN THIS REPOSITORY, AND THAT IS A - DELIBERATE SEPARATION. A client that shipped somebody's scope->instance map - would be publishing their taxonomy; this program knows how to route and - nothing about who routes where. So the mechanism lives here and the table - lives wherever the operator keeps it — which makes THIS command the only - place the two meet, and the reason it grades rather than merely prints. - - 🔴 IT GRADES IN BOTH DIRECTIONS. A scope with no entry refuses its next - write — loud. An entry naming a scope that exists nowhere is the silent one: - it reads as coverage and survives a rename. See `Routing.check`, which asks - `Routing.alias_for` for the third direction rather than re-deriving it. - """ - routing = _routing() - # `*`: the table names every routed scope (decision 3a). - read_ledger.record("", read_ledger.ALL_SCOPES) - print(f"instances: {', '.join(routing.aliases)}") - if routing.routes is None: - print( - "routes: NONE configured — every scope resolves to " - f"`{_read_store.DEFAULT_ALIAS}`" - if not routing.multi_instance - else "routes: NONE configured, and this host has more than one " - "instance, so EVERY scope refuses until a table exists" - ) - if not args.check: - return EXIT_OK - return EXIT_OK if not routing.multi_instance else EXIT_UNROUTED - print(f"routes: {routing.routes_source}") - for scope in sorted(routing.routes): - print(f" {scope} -> {routing.routes[scope]}") - if not args.check: - return EXIT_OK - - refusal = _refuse_shared_cache(args, routing, "routes --check") - if refusal is not None: - return refusal - # 🔴 THE SCOPE SET IS READ FROM THE INSTANCES THEMSELVES, REFRESHED FIRST. - # Grading a table against a stale cache invents both kinds of finding: a - # scope added elsewhere reads as "the table does not name it", and a scope - # deleted elsewhere reads as "the table names a scope that does not exist". - # An instance that cannot be refreshed is therefore named, and the check - # REFUSES rather than grading against what happens to be on this disk. - # - # 🔴 AND THE BANNER IS LABELLED ONLY WHEN THERE IS MORE THAN ONE INSTANCE, - # like every other read in this file. This loop used to pass the alias - # unconditionally, which made `routes --check` the ONE command that printed - # `cairn[personal]:` on a host with a single store — found by diffing this - # verb against its Go port rather than by any test, because no test asserted - # the banner here at all. - scopes: set[str] = set() - for instance in routing.instances: - label = instance.alias if routing.multi_instance else None - cache = _instance_cache(args, instance.alias) - state, detail, hint = resolve_state( - cache, no_sync=args.no_sync, scope=None, timeout=_store_timeout(args), - instance=instance.alias, - ) - print(banner(state, detail, label), file=sys.stderr) - if hint is not None or state != STATE_LIVE: - print( - f"🔴 cairn: REFUSING to grade the table — instance " - f"`{instance.alias}` was not read LIVE, and a table graded " - f"against a stale or absent cache reports findings in both " - f"directions that are facts about this disk rather than about " - f"the table.", - file=sys.stderr, - ) - return EXIT_UNROUTED - # ⚠ THIS CACHE-ROOT LISTING IS UNWRAPPED, like `cmd_validate`'s `held` — its - # `OSError` escapes `main()`'s `(StoreMissingError, ResolverError)` arm as a - # traceback rather than the reader's named sentence. `--no-sync` cannot reach it - # (the `state != STATE_LIVE` guard above returns first), but a **304 Not - # Modified** does: `resolve_state` returns `STATE_LIVE` and writes nothing, so - # the root listed here is the pre-existing one, mode bits and all. MEASURED - # against a stub pod answering 304, cache root at 0111: this client exits **1** - # with a `PermissionError` traceback, the Go client **3** with its own raw - # `open : permission denied`. UNGATED, and the cache-ROOT depth of - # `tests/parity/README.md` row 4. - scopes.update(p.name for p in cache.iterdir() if p.is_dir()) - problems, notes = routing.check(scopes) - for problem in problems: - print(f"🔴 cairn: {problem}", file=sys.stderr) - # ⚠ NOTES CARRY A DIFFERENT MARKER AND DO NOT MOVE THE EXIT CODE. A finding - # the available evidence cannot decide must not fail a gate: `Routing.check` - # names the one direction that is undecidable from a snapshot, and printing - # it at 🔴 exit 11 is what made `routes --check` refuse every table that - # pre-registered a scope — which is the two-way registry this verb exists - # for. Printed AFTER the problems so a real finding is never buried. - for note in notes: - print(f"⚠ cairn: {note}", file=sys.stderr) - print( - f"routes: {len(routing.routes)} entr" - f"{'y' if len(routing.routes) == 1 else 'ies'}, {len(scopes)} scope(s) " - f"across {len(routing.instances)} instance(s), {len(problems)} problem(s), " - f"{len(notes)} note(s)" - ) - return EXIT_UNROUTED if problems else EXIT_OK - - -class _ExplicitCache(argparse.Action): - """Record that `--cache` was GIVEN, not merely defaulted. - - 🔴 THE DEFAULT AND AN EXPLICIT VALUE EQUAL TO IT ARE DIFFERENT FACTS, and - comparing the value against the default cannot tell them apart. With more - than one instance the default must be resolved PER INSTANCE while an - explicit `--cache` pins one directory, so the difference decides whether a - fan-out is allowed at all. - """ - - def __call__(self, parser, namespace, values, option_string=None): # noqa: D102 - setattr(namespace, self.dest, values) - namespace.cache_explicit = True - - -def build_parser() -> argparse.ArgumentParser: - p = argparse.ArgumentParser( - prog="cairn", - description=( - "Read-through client for the hosted subsystem store. Syncs a local " - "cache and runs the UNMODIFIED local reader against it, so a recall " - "never depends on the network and never reports an unreachable " - "store as an empty one." - ), - ) - # Resolved at parser-BUILD time through the accessor, so the module global - # stays the single point of truth and a test can repoint reader and writer - # together with one assignment. - p.add_argument( - "--cache", type=Path, default=_read_store.read_store_root(), - action=_ExplicitCache, - ) - # The flag's own default lives here rather than on the action, because an - # Action only runs when the option APPEARS. - p.set_defaults(cache_explicit=False) - # `None` = not given, resolved to `DEFAULT_TIMEOUT` by `_store_timeout`, - # which is the ONLY resolver — there is no second, longer default. - # (This comment used to promise one, naming a subcommand and a helper that - # were both removed before this repo was published — two symbols that have - # never existed here. A comment is a claim, and one pointing at absent - # symbols sends a reader hunting a timeout path that is not there. The - # removed names are deliberately not repeated: the closing condition for - # this fix is that they grep to zero in this file.) - p.add_argument("--timeout", type=int, default=None) - sub = p.add_subparsers(dest="cmd", required=True) - - def common(sp): - sp.add_argument("--scope", default=None) - sp.add_argument("--repo", default=".") - sp.add_argument( - "--no-sync", - action="store_true", - help="skip the network entirely and read the cache as it stands", - ) - return sp - - s = sub.add_parser("sync", help="refresh the local cache from the pod") - s.add_argument("--scope", default=None) - s.set_defaults(func=cmd_sync) - - r = common(sub.add_parser("recall", help="the scope's digest")) - r.add_argument("--mode", default=rc.DEFAULT_MODE) - # The digest's footer names `--ref` and `--limit` by hand; `--list` and - # `--page` are the other two the reader has always had. All four are - # forwarded to `rc`, never re-implemented — see `cmd_recall`. - r.add_argument( - "--ref", - default=None, - help="surface ONE entry by ref instead of the whole scope", - ) - # 🔴 `--ref-to`, AND THE SPELLING IS THE POINT. `--ref` names an ENTRY; this names - # something an entry POINTS AT, and the two compose. The pod's parameter is `?ref-to=` - # — the same spelling — because `?ref=` already means `--ref` there and redefining it - # would break a pinned contract. Both clients carry this flag or `tests/parity/` reds. - r.add_argument( - "--ref-to", - default=None, - metavar=":", - help="only entries whose `refs:` carries this ref (the REVERSE lookup)", - ) - # 🔴 SCALAR, AND LAST-WINS LIKE EVERY OTHER VALUE-BEARING FLAG HERE — an OPERATOR DECISION - # rather than a gate. A repeatable `--tag` with AND semantics shipped first; nobody had - # asked for the repetition, and the choice between AND and OR had no author of record, so - # the surface is one tag. `default=None` and not `""`: `rc.recall` refuses an operand that - # folds away, and `--tag ''` must reach that refusal rather than read as "no filter" — so - # absent and empty have to stay distinguishable all the way into the option ladder. - r.add_argument( - "--tag", - default=None, - metavar="", - help="only entries whose `tags:` carries this tag", - ) - r.add_argument( - "--list", - action="store_true", - dest="listing", - help="the INDEX ONLY: one line per entry, never a body, never truncated", - ) - r.add_argument( - "--limit", - type=int, - default=None, - help="print up to N entry BODIES instead of the default digest", - ) - r.add_argument( - "--page", - type=int, - default=None, - help="which page of the INDEX to list, 1-based", - ) - r.set_defaults(func=cmd_recall) - - q = common(sub.add_parser("search", help="search the scope for hunks")) - q.add_argument("query") - q.add_argument("--all-scopes", action="store_true") - # The same flag `recall` carries, for the same reason. Searching within the entries - # that reference one task is the narrowing a reverse lookup is usually wanted for. - q.add_argument( - "--ref-to", - default=None, - metavar=":", - help="only entries whose `refs:` carries this ref (the REVERSE lookup)", - ) - # The same scalar `--tag` `recall` carries, for the same reason. Searching within one - # category is the narrowing the key exists for. - q.add_argument( - "--tag", - default=None, - metavar="", - help="only entries whose `tags:` carries this tag", - ) - q.set_defaults(func=cmd_search) - - v = common(sub.add_parser("validate", help="the post-write check: parse, dropped lines, marker reachability")) - v.set_defaults(func=cmd_validate) - - e = common(sub.add_parser("ls-entries", help="one `/.md` per line")) - e.set_defaults(func=cmd_ls_entries) - - # 🔴 `doctor` TAKES NO `--scope`/`--repo` AND IS NOT `common()`. It asks about - # THIS HOST and THIS CREDENTIAL, not about a scope, and a `--scope` here would - # invite the filtered-cache mistake `cmd_sync` documents. `--no-sync` it does - # take: "diagnose without touching the network" is a real mode, and it turns - # every pod-dependent check UNMEASURED with that as the stated reason rather - # than reporting a zero. - # - # 🔴 ITS EXIT CODES ARE DOCUMENTED BY THE COMMAND. `cairn_doctor.EXIT_LEGEND` - # is printed at the foot of every human-readable run and carried in `--json`, - # so no skill has to restate them and none can restate them wrongly. - d = sub.add_parser( - "doctor", - help="one call: pod reachability, credential, cache stamp, counts, " - "scope visibility, and which store this host's reader resolves", - epilog=_doctor_epilog(), - formatter_class=argparse.RawDescriptionHelpFormatter, - ) - d.add_argument("--json", action="store_true") - d.add_argument( - "--no-sync", - action="store_true", - help="do not contact the store; pod-dependent checks report UNMEASURED", - ) - d.set_defaults(func=cmd_doctor) - - ro = sub.add_parser( - "routes", - help="print the scope->instance table, and grade it against reality", - ) - ro.add_argument( - "--check", action="store_true", - help="grade the table BOTH ways and exit non-zero on any problem", - ) - ro.add_argument( - "--no-sync", action="store_true", - help="do not refresh first (--check then refuses: see cmd_routes)", - ) - ro.set_defaults(func=cmd_routes) - - # --- the write verbs ----------------------------------------------------- - # 🔴 `writes=True` IS NOT DECORATION. `main` maps a `StoreUnreachable` to - # exit 3 ("store-unreachable, no cache"), which is a READ verdict and reads - # as "nothing was shown". For a write the honest code is 7 — the record was - # NOT made — and the two must not share a number, because the whole point of - # write-through is that a caller can tell a failed write from a stale read. - # 🔴 NEITHER TAKES `--no-sync`. It would be meaningless on `append` and - # actively harmful on `put` (see that function on deriving a precondition - # from bytes we did not confirm), so it is absent rather than refused. - ap = sub.add_parser( - "append", - help="append ONE dated, attributed bullet to an entry (writes to the pod)", - ) - ap.add_argument("--scope", default=None) - ap.add_argument("--repo", default=".") - ap.add_argument("--ref", required=True, help="the entry: a filename stem or an alias") - # 🔴 THE LIMIT IS IN THE HELP because the only other way to learn it was to - # exceed it. Interpolated from the shared constant, never typed — a help - # string quoting a stale number is the same drift as a second copy of the - # constant, and harder to notice because nothing tests prose. - ap.add_argument( - "--text", required=True, - help="the bullet, ONE line, with NO leading `- ` and NO leading date — " - "the server adds both; max " - f"{entry_shape.BULLET_TEXT_MAX} characters", - ) - # 🔴 REQUIRED, WITH NO DEFAULT AND NO ENV FALLBACK. The server refuses a - # request without it (400), and criterion 4 is that every appended bullet - # records the actor AND the session. A default would be a value nobody - # chose, attached to a durable record; an env fallback would silently - # attribute one agent's bullet to whatever the shell last exported. - ap.add_argument("--session", required=True, help="the writing session's id") - ap.set_defaults(func=cmd_append, writes=True) - - pu = sub.add_parser( - "put", help="replace a whole entry behind an If-Match precondition" - ) - pu.add_argument("--scope", default=None) - pu.add_argument("--repo", default=".") - pu.add_argument("--ref", required=True) - pu.add_argument("--file", type=Path, required=True, help="the new entry bytes") - pu.add_argument( - "--if-match", default=None, dest="if_match", - help="the entry revision this edit is based on; derived from a LIVE " - "sync when omitted", - ) - pu.set_defaults(func=cmd_put, writes=True) - - # 🔴 `create` IS THE THIRD WRITE VERB AND THE ONLY ONE THAT CAN MAKE AN - # ENTRY. `append` and `put` both resolve an existing ref; before this the - # protocol's only route to a new entry was a local write into the frozen - # mirror, which no reader sees. It takes no `--if-match` (there are no prior - # bytes) and no `--no-sync` (it reads no cache at all). - cr = sub.add_parser( - "create", - help="create a NEW entry that does not exist yet (refuses to overwrite)", - ) - cr.add_argument("--scope", default=None) - cr.add_argument("--repo", default=".") - cr.add_argument( - "--ref", required=True, - help="the new entry's filename stem — it becomes `.md` in the scope", - ) - cr.add_argument("--file", type=Path, required=True, help="the new entry bytes") - cr.set_defaults(func=cmd_create, writes=True) - - return p - - -def main(argv: Sequence[str] | None = None) -> int: - # 🔴 BEFORE `parse_args`, SO `--help` WARNS TOO, AND BECAUSE THE POSITION IS COMPARED. - # `tests/parity/harness.py` diffs this client's stderr against the Go client's - # byte-for-byte, and `internal/client.Run` emits the same sweep before ITS `Parse`. - # After `parse_args` the notice would land after argparse's usage error on this side - # and before the Go client's on the other. - # - # The FILE-key half cannot happen here — the config path is not known until an alias - # has been resolved — so `load_config` emits that half through the same sink. - _warn_deprecations(env_aliases.deprecations(os.environ)) - - args = build_parser().parse_args(argv) - if not hasattr(args, "no_sync"): - args.no_sync = False - # 🔴 AFTER `parse_args`, so a usage refusal (argparse exits 2 above) cannot record. - read_ledger.begin(args.cmd) - try: - return args.func(args) - except cairn_instances.UnroutedScope as exc: - # A backstop, not the primary path: every call site that can raise this - # catches it where the remedy is clearest. Here so a future verb that - # forgets cannot turn a routing refusal into a traceback at exit 1. - return _unrouted(exc) - except cairn_instances.RoutingConfigError as exc: - # 🔴 THE SAME CODE AS AN UNROUTED SCOPE, DELIBERATELY. Both mean "this - # client could not decide which instance to use and did nothing"; the - # remedy for both is a file the operator owns. A second code would ask - # every consumer to learn a distinction neither of them can act on - # differently. - print(f"🔴 cairn: REFUSING — {exc}", file=sys.stderr) - return EXIT_UNROUTED - except WriteRefused as exc: - # 🔴 THE STORE ANSWERED, AND THE ANSWER IS NO. Printed with the server's - # own `X-Store-Status`, because that token is what distinguishes the four - # 404s from each other (`scope-unknown` vs `ref-unknown`) and a 405 - # (`read-only`) — which is the one that means "the write path is not - # deployed on the running image", i.e. an operator problem and not a - # caller problem, and which reads exactly like a wrong URL. - print( - f"🔴 cairn: the store REFUSED the write [{exc.status}] — {exc.detail}", - file=sys.stderr, - ) - return exc.exit_code - except StoreCorrupt as exc: - # 🔴 LOUD, and never absorbed into "served from cache". A server that - # ships a link, a traversal member, a duplicate, or a count disagreeing - # with its own header is not an outage — it is the case that must stop - # the run, cache or no cache. - print(f"🔴 cairn: REFUSED the archive — {exc}", file=sys.stderr) - return EXIT_CORRUPT - except StoreUnreachable as exc: - # 🔴 A WRITE AND A READ DO NOT SHARE A CODE HERE. Exit 3 is - # "store-unreachable, no cache" — a statement about what was DISPLAYED. - # On a write nothing was displayed and, more importantly, nothing was - # RECORDED; a caller that reads 3 as "the read came back empty" would - # carry on believing the bullet landed. `writes` is set by the write - # subparsers only, so this cannot drift with a new read verb. - if getattr(args, "writes", False): - print( - f"🔴 cairn: the write did NOT happen — {exc}\n" - f" Nothing was queued and nothing was written locally. " - f"Re-run when the store is reachable.", - file=sys.stderr, - ) - return EXIT_WRITE_UNREACHABLE - # Reached only by a config failure outside `resolve_state`; still named. - print(f"🔴 cairn: {STATE_NO_CACHE} — {exc}", file=sys.stderr) - return EXIT_UNREACHABLE_NO_CACHE - except (rc.StoreMissingError, subsystem_resolver.ResolverError) as exc: - # 🔴 THE READER-ERROR RUNG THIS LADDER WAS MISSING, AND ITS ABSENCE WAS A - # DIVERGENCE (#111). `internal/client/cli.go`'s ladder ends with exactly - # this arm — "EVERYTHING ELSE IS A READER ERROR — a missing store root, an - # unreadable entry — and it exits 3" — and this one simply stopped, so the - # SAME condition printed a Python traceback at exit 1 here and a named line - # at exit 3 there. MEASURED on one scope holding one `chmod 000` entry - # before this arm existed: `cairn validate` → 1, `cairn recall` → 1, the Go - # client → 3 for both. - # - # 🔴 3, AND IT IS THE ORACLE'S OWN NUMBER RATHER THAN THE PORT'S. - # `subsystem_recall.main` — the reader this client wraps — has always - # answered `except (TouchError, ResolverError) … return 3` for this exact - # condition, and `_exit_for`'s docstring states the rule it rests on: "3 is - # already 'the store is broken' for this CLI (`StoreMissingError`, - # `EntryUnreadableError`)". Measured directly: `subsystem_recall.py --store - # --scope ` over that store exits 3, and 0 with the same entry - # readable. So the wrapper was the only thing in the system that did not - # already agree. - # - # 🔴 NOT `EXIT_CORRUPT` (5), WHICH IS THE OTHER CANDIDATE AND IS WRONG. - # 5 is a MALFORMED entry — one that was READ and rejected — and the whole - # of `load_index`'s residual ledger rests on "could not interpret this - # file" and "could not READ the store" being different facts, only the - # first of which has an honest degraded form. Routing an unreadable entry - # to 5 means collecting it as a `MalformedEntry`, which would make `recall` - # serve the readable entries at exit 0 for a store it did not fully read, - # and make `validate` print `N-1 of N parse, 1 malformed` about a file - # nothing opened. That trades a fail-closed read for a partial one. - # - # ⚠ NAMED CLASSES, NOT A BARE `except OSError`, AND THE DIFFERENCE IS - # DELIBERATE. Go reaches its arm with raw OS errors too, because its verbs - # return them as values; catching `OSError` at this boundary would turn any - # unexpected I/O bug anywhere in the client into a confident "the store is - # broken, exit 3". - # - # 🔴 IT DOES NOT CATCH EVERY UNREADABLE-STORE CONDITION, AND THE RESIDUAL IS - # NAMED RATHER THAN DECLARED CLOSED. Only the reads that go through - # `load_store` raise `EntryUnreadableError` and so land here by class; a - # LISTING read outside it raises a raw `OSError`, which this tuple - # deliberately does not catch. Still unwrapped, by name: `cmd_validate`'s - # `held` and `cmd_routes`' cache-ROOT listings (traceback at exit 1 against - # the Go client's 3 — `tests/parity/README.md` row 4's cache-root depth), - # `cmd_validate`'s per-scope DENOMINATOR (reachable only by the world changing - # mid-run; see the comment at that line), and `cmd_ls_entries`' `glob`, which - # swallows the error instead of raising it. A cache root with no `x` bit never - # reaches any verb at all — it raises out of `resolve_state` first, which is - # the same row 4. ⚠ Nothing enumerates that set mechanically, so re-derive it - # rather than trusting this list: `grep -n 'iterdir()\|glob(' cairn`. - # - # 🔴 THE `ResolverError` HALF IS WIDER THAN THE TWO CLASSES JUSTIFIED ABOVE, - # AND THAT IS A DECISION, NOT AN OVERSIGHT. `ResolverError` has five - # subclasses; the paragraphs above argue `StoreMissingError` and - # `EntryUnreadableError`. The other three — `UnknownScopeError`, - # `AmbiguousRefError`, `InvalidPathError` — would report here as - # `3 = store-unreachable, no cache`, which is the WRONG sentence for each of - # them. Kept wide anyway, for three reasons, in order of weight: - # - # 1. NARROWING WOULD CREATE A DIVERGENCE IN THE TRACEBACK DIRECTION. - # `internal/client/cli.go`'s equivalent arm is the FALLBACK for every - # error the verbs return ("EVERYTHING ELSE IS A READER ERROR"), so it is - # already wider than this tuple. A narrower oracle means any future - # `ResolverError` on a read path is exit 3 with a named line there and a - # Python TRACEBACK at exit 1 here — which is #111, re-opened, and is - # strictly worse than a wrong-but-named sentence. - # 2. MEASURED LATENT, not merely argued: all three are STATUSES on this - # reader, not raises. Over one cache, `recall --scope no-such-scope` → - # exit 0 `status=scope-absent`, `recall --ref ` → exit 0 - # `status=ref-ambiguous`, both with no traceback; `load_store` loads with - # `ON_MALFORMED_COLLECT`, so `MalformedEntryError` cannot escape it - # either (its docstring says so). `InvalidPathError` is reached only from - # `associate_paths` on writer-validated input. - # 3. `subsystem_recall.main` — the reader this client wraps — catches - # `(TouchError, ResolverError)` wholesale for the same condition, so a - # narrower tuple HERE would also disagree with the module it fronts. - # - # ⚠ WHAT WOULD CHANGE THIS: a `ResolverError` subclass becoming reachable - # from a read path with a code of its own (a 2 or a 5). Then this arm must - # list its classes, and `cli.go`'s fallback needs the same split in the same - # commit — not one side. - print(f"🔴 cairn: {exc}", file=sys.stderr) - return EXIT_UNREACHABLE_NO_CACHE - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/flake.nix b/flake.nix index fa9a4bcb..a01d6ee3 100644 --- a/flake.nix +++ b/flake.nix @@ -7,8 +7,8 @@ outputs = { self, nixpkgs }: let - # Darwin is listed because the CLIENT is stdlib Python and has no reason - # not to build there. The IMAGE is Linux-only, and is exposed only on + # Darwin is listed because the CLIENT is a static Go binary and has no + # reason not to build there. The IMAGE is Linux-only, and is exposed only on # Linux rather than failing at evaluation with a `dockerTools` error. # 🔴 `x86_64-darwin` IS DELIBERATELY ABSENT, AND ITS ABSENCE IS LOAD-BEARING. # nixpkgs 26.11 — which `flake.lock` pins — DROPPED that platform, so @@ -33,78 +33,50 @@ # tree, which is itself the fact a reader of the tag most wants. version = self.shortRev or self.dirtyShortRev or "unknown"; - # 🔴 THE RUNTIME CONTRACT, IN ONE PLACE, BECAUSE THERE ARE NOW TWO BUILDS. - # ⚠ This read "`server/Dockerfile` is what is deployed today" until the Go - # cutover. NEITHER Python image is deployed now — the cluster pulls - # `cairn-store-go`. The pin below still earns its place, because both - # builds state the contract and can still disagree. - # The image below is a - # second way to produce the same pod, and two build paths that can - # disagree about env/port/user is the whole hazard of adding one. These - # values are the single nix-side authority for it, and - # `tests/test_flake_image_matches_dockerfile.py` pins them against the - # Dockerfile so neither can move alone. + # 🔴 THE POD'S RUNTIME CONTRACT, IN ONE PLACE. `serverEnv`, `serverUid` and `serverPort` + # are the single nix-side statement of it; `mkGoServerImage` DERIVES its env, uid, port + # and exposed port from them, and `tests/test_flake_go_image_runtime_contract.py` pins + # that it stays derived rather than copied. # - # HOME is not decoration: `lib/subsystem_read_store.py` evaluates - # `Path.home() / ".cache" / …` at IMPORT time, and `Path.home()` raises - # when it can resolve neither $HOME nor a passwd entry — the ordinary - # state of a numeric-UID container. The value is never used by the server - # (every call passes `--store`), but the import would fail before - # anything could say so. + # 🔴 `serverEnv` IS EMPTY, AND THAT IS A FACT ABOUT TODAY, NOT ABOUT THE MECHANISM. The + # image's `Env` is `serverEnv // { PATH; SSL_CERT_FILE; }`, so a variable added here + # reaches the pod and cannot be forgotten on it. It held `HOME` and two CPython knobs + # for the retired Python pod (whose reader evaluated `Path.home()` at import time), all + # subtracted from the Go pod by name; with that pod deleted the subtraction had nothing + # left to subtract from, so the binding was emptied rather than the mechanism removed. + # Nothing in `go list -deps ./cmd/cairn-server` reads `$HOME` (every such call is under + # `internal/client`, which the server does not import) — re-run that before adding one. # - # 🔴 NEITHER IMAGE SETS A STORE VARIABLE IN EITHER SPELLING, AND THAT IS A DECISION - # RATHER THAN AN OMISSION. `SUBSYSTEM_STORE_ROOT=/data`, - # `SUBSYSTEM_STORE_PORT=8102` and - # `SUBSYSTEM_STORE_TOKEN_FILE=/run/secrets/subsystem-store/token` were here, and are - # gone. Two measurements decided it: + # 🔴 THE IMAGE SETS NO STORE VARIABLE IN EITHER SPELLING, AND THAT IS A DECISION RATHER + # THAN AN OMISSION. `SUBSYSTEM_STORE_ROOT=/data`, `SUBSYSTEM_STORE_PORT=8102` and + # `SUBSYSTEM_STORE_TOKEN_FILE=/run/secrets/subsystem-store/token` were here, and are gone. + # Two measurements decided it: # # * THEY CONFIGURED NOTHING. Each value was byte-identical to the code default the - # server falls back to with the variable unset — `server/server.py`'s - # `DEFAULT_STORE`/`DEFAULT_PORT`/`DEFAULT_TOKEN_FILE` and - # `cmd/cairn-server/main.go`'s `defaultStore`/`defaultPort`/`defaultTokenFile`. - # Measured on both by running each with `env -i`: the oracle prints - # `listening on 0.0.0.0:8102 store=/data`, and the Go server names - # `/run/secrets/subsystem-store/token` in its token-file refusal. So removing - # them moves no resolved value. `tests/test_flake_image_matches_dockerfile.py` - # pins that agreement against BOTH implementations now that the image no longer - # states it. - # * THEY COST THREE DEPRECATION WARNINGS AT EVERY POD START. The resolver sweeps - # the WHOLE process environment, and the image's own `ENV` is part of it — so the - # pod emitted three unactionable lines nobody could clear from a manifest. - # Measured: `deprecations(image_env)` is 3, and it is still 3 after a Deployment - # migrates its own `env:` to `CAIRN_*`, because the image half is still there. - # With the image setting nothing, that same migrated Deployment measures 0. + # server falls back to with the variable unset — `cmd/cairn-server/main.go`'s + # `defaultStore`/`defaultPort`/`defaultTokenFile` (and, while it existed, the Python + # server's). Measured with `env -i`: the server names + # `/run/secrets/subsystem-store/token` in its token-file refusal. So removing them + # moved no resolved value; `tests/test_server_deployment_defaults.py` pins those + # defaults against what a Deployment assumes now that the image does not state them. + # * THEY COST THREE DEPRECATION WARNINGS AT EVERY POD START. The resolver sweeps the + # WHOLE process environment, and the image's own `ENV` is part of it — so the pod + # emitted three unactionable lines nobody could clear from a manifest. # - # 🔴 AND IT CLOSES THE SHADOWING HAZARD AT THE ROOT RATHER THAN DEFERRING IT TO P8. - # The note that used to sit here explained why the image had to keep the OLD spelling: - # an image `ENV` is a DEFAULT present whether or not the manifest mentions it, and - # new-name-wins would have let a `CAIRN_STORE_ROOT` baked here outrank a Deployment - # that explicitly set `SUBSYSTEM_STORE_ROOT`. That reasoning was correct and is now - # moot: with no image default there is nothing to outrank a manifest, in either - # spelling, so the images could adopt `CAIRN_*` later with no window at all. + # 🔴 AND IT CLOSES THE SHADOWING HAZARD AT THE ROOT. An image `ENV` is a DEFAULT present + # whether or not the manifest mentions it, and new-name-wins would let a + # `CAIRN_STORE_ROOT` baked here outrank a Deployment that explicitly set + # `SUBSYSTEM_STORE_ROOT`. With no image default there is nothing to outrank a manifest, + # in either spelling. # # ⚠ THE ACCEPTED COST, STATED SO IT IS NOT REDISCOVERED AS A BUG. `docker inspect` and # this file no longer show where the store lives, which port it binds or where the - # token is read from. The operator took that trade knowingly. What replaced the - # env-based assertion is a pin on the CODE defaults in both implementations — - # `STORE_DEFAULTS` in `tests/test_flake_image_matches_dockerfile.py`, ONE declared - # constant holding all THREE values, spelled by hand and checked against each - # implementation's own constants. (`DEPLOY_CONTRACT` in - # `tests/test_flake_go_image_runtime_contract.py` is an alias for it, `= STORE_DEFAULTS`, - # so the sibling module's assertions read in the same vocabulary; the declaration has - # one home and this is not it.) - # - # ⚠ AND THE STARTUP LINE COVERS TWO OF THE THREE, NOT THREE — a sentence here used to - # say it printed all of them. Both pods print - # `listening on : store= token-ids=…`; `token-ids=` is the credential - # FINGERPRINTS, and neither implementation's startup line prints the token PATH. The Go - # server's `-h` prints it as a flag default, the oracle's `--help` does not, and both - # emit it on stderr only in the `token file absent` fallback notice. - serverEnv = { - HOME = "/home/nonroot"; - PYTHONDONTWRITEBYTECODE = "1"; - PYTHONUNBUFFERED = "1"; - }; + # token is read from. The operator took that trade knowingly; `STORE_DEFAULTS` in + # `tests/test_server_deployment_defaults.py` is the one declared constant holding all + # three values. The startup line prints `listening on : store= + # token-ids=…` — two of the three; the token PATH appears as `-h`'s flag default and in + # the `token file absent` notice only. + serverEnv = { }; serverUid = 65532; serverPort = 8102; @@ -132,69 +104,13 @@ uiPort = 8103; uiSessionDir = "/var/lib/cairn-ui"; - # 🔴 THE GO POD'S ENV IS `serverEnv` MINUS A NAMED SET — A SUBTRACTION, NEVER - # A SECOND LITERAL. There are now THREE builds of a pod and only ONE statement - # of the contract: `serverEnv` above. Deriving the Go image's env from it means - # a variable added there reaches BOTH pods and cannot be forgotten on one. - # A second attrset holding copies would invert that — the drift would be silent - # and in the direction that matters, a pod missing an env its Deployment sets. - # - # 🔴 IT NOW SUBTRACTS EVERYTHING, SO `serverEnvGo` IS `{ }`, AND THE MECHANISM IS - # KEPT ANYWAY RATHER THAN COLLAPSED TO A LITERAL. Dropping the three store variables - # from `serverEnv` left it holding only CPython knobs and a `HOME` for them, all - # three of which are Python-only — so the Go image's `Env` is its `//` override - # alone (`PATH`, `SSL_CERT_FILE`). Replacing this with a hardcoded two-element env - # would read as a simplification and would silently stop the NEXT shared variable - # from reaching the Go pod, which is the exact drift the subtraction exists for. The - # empty result is a fact about today's `serverEnv`, not about the derivation. - # - # WHY EACH NAME LEAVES, READ OUT OF THE CODE RATHER THAN ASSUMED: - # * `PYTHONDONTWRITEBYTECODE` / `PYTHONUNBUFFERED` are CPython knobs. A Go - # binary never reads either; carrying them would assert the image runs an - # interpreter, which is the one thing this image is for NOT doing. - # * `HOME` is in `serverEnv` because `lib/subsystem_read_store.py` evaluates - # `Path.home()` at IMPORT time and it raises in a numeric-UID container. - # MEASURED on the Go side rather than inferred, and stated as the METHOD - # rather than a count that would rot: nothing in `go list -deps - # ./cmd/cairn-server` calls `os.UserHomeDir` or reads `$HOME` — every such - # call lives under `internal/client`, which the server does not import, and - # `internal/hostid` reads only `CAIRN_HOST`/`ASIB_HOST`/`ACTIVITY_HOST`. Re-run - # that pair before moving a name out of this list. So there is no - # import-time home to resolve, and an env var nothing reads in an image - # whose env IS the deploy contract is a claim about the pod that is false. - # - # ⚠ WHAT THIS DOES NOT CLAIM: that `$HOME` is unreachable in the container. - # `kubectl exec … -- sh` lands in a shell with no `HOME`. busybox `ash` does not - # need one, and both documented procedures name absolute paths (`tar -xf -` into - # `/data`, `kill -HUP 1`). If a procedure ever needs `~`, it goes in `serverEnv` - # and both pods get it — which is the point of the subtraction. - # - # ⚠ KEEPING `HOME` AND DROPPING ONLY THE TWO `PYTHON*` KNOBS WAS PROPOSED IN REVIEW - # AND DECLINED; RECORDED SO IT IS NOT RE-LITIGATED FROM SCRATCH. The proposal's cost - # argument is real — this comment, and a standing obligation to re-run `go list -deps` - # whenever the server's imports change. Three things decided it the other way. - # (1) The failure mode of a WRONG drop is LOUD, not silent: `os.UserHomeDir` returns - # an explicit "$HOME is not defined" error. The silent-drift class the subtraction - # exists to prevent is the OTHER direction — a variable that never reaches the Go - # pod at all — and that one is closed structurally by `removeAttrs`. - # (2) Keeping it is MORE derivation, not less: `mkServerImage` creates and chowns - # `/home/nonroot` in `fakeRootCommands` precisely because it sets `HOME`. A `HOME` - # naming a directory the image does not contain is false in two ways instead of - # one, so "keep" means restoring that mkdir here too. - # (3) The image's `Env` IS the deploy contract, and the next operator debugging a - # buffering or home-directory question reads it as one. - serverEnvPythonOnly = [ "HOME" "PYTHONDONTWRITEBYTECODE" "PYTHONUNBUFFERED" ]; - serverEnvGo = builtins.removeAttrs serverEnv serverEnvPythonOnly; - # 🔴 THE INTERPRETER IS PINNED TO THE ONE THE SUITE ACTUALLY RUNS UNDER. - # `pkgs.python3` follows nixpkgs and was 3.14 here, while - # `server/Dockerfile` is `python:3.12-slim` and CI pins `python-version: - # "3.12"` — so the packaged client and the flake image shipped an - # interpreter NOTHING in this repo had ever run the suite against, and a - # lock bump could move it again silently. The suite already emits a 3.14 - # tar-extraction DeprecationWarning, so the gap is behaviourally live, - # not theoretical. Change this in the same commit as the Dockerfile and - # the CI matrix, never alone. + # `pkgs.python3` follows nixpkgs and was 3.14 here, while CI pins + # `python-version: "3.12"` — so a check built on it ran an interpreter + # NOTHING in this repo had ever run the suite against, and a lock bump could + # move it again silently. Nothing SHIPPED uses it any more (the Python + # client and pod are retired); the devShell and the Python-driven checks do. + # Change this in the same commit as the CI matrix, never alone. python = pkgs: pkgs.python312; # 🔴 THE POD IS OPERATED THROUGH `kubectl exec`, SO THE IMAGE MUST CARRY A @@ -213,9 +129,9 @@ # those applets in ~2 MB, and the procedures use only POSIX spellings. # # 🔴 `serverPath` MUST NAME A DIRECTORY THE APPLETS ACTUALLY LAND IN, and - # `serverTools` MUST REACH `contents`. Both are asserted by - # `tests/test_flake_image_matches_dockerfile.py`, and BOTH assertions - # exist because their absence was measured: with the guard pinning only + # `serverTools` MUST REACH `contents`. Both are asserted for the pod by + # `tests/test_flake_go_image_runtime_contract.py`, and BOTH assertions + # exist because their absence was measured (on the retired Python image): with the guard pinning only # the two bindings, a mutant that reverted `contents` to `[ tree ]` and a # mutant that set `serverPath = "/nonexistent"` EACH SURVIVED the whole # suite while restoring the exact defect the guard was written for — a @@ -229,10 +145,9 @@ serverTools = pkgs: [ pkgs.busybox ]; # 🔴 THE GO POD CARRIES `serverTools` PLUS CA ROOTS, AND THE EXTRA IS NOT - # DECORATION. `mkServerImage` ships no `/etc`, so a container built from it has - # NO CA bundle at any path Go's `crypto/x509` searches. That costs the Python pod - # nothing — it makes no outbound TLS connection — but `internal/identity/jwks.go` - # fetches a JWKS over `https` for the Supabase backend, and without roots that + # DECORATION. `serverTools` alone ships no `/etc`, so a container built from it has + # NO CA bundle at any path Go's `crypto/x509` searches — and `internal/identity/jwks.go` + # fetches a JWKS over `https` for the OIDC backend, so without roots that # fetch fails certificate verification on an image that otherwise starts, passes # health checks and serves. Same shape as the missing-`sh` defect `serverTools` # exists for: four pinned values agreeing over a pod that cannot do its documented @@ -245,10 +160,6 @@ # JWKS fetch against a real issuer is NOT verified by anything in this repository — # it needs a pod, a network and an issuer, none of which a nix build has. # - # ⚠ AND IT IS GO-ONLY ON PURPOSE. Adding `cacert` to `serverTools` would change - # `packages.server-image`'s layer contents, which is the one thing - # `tests/test_flake_image_matches_dockerfile.py` is written against, for a pod - # that has no use for it. goServerTools = pkgs: serverTools pkgs ++ [ pkgs.cacert ]; # 🔴 NAMED BY ABSOLUTE STORE PATH, AND `SSL_CERT_FILE` IS *NOT* WHAT MAKES THE @@ -293,54 +204,27 @@ # anything arranged a filesystem layout around it. goServerCaBundle = pkgs: "${pkgs.cacert}/etc/ssl/certs/ca-bundle.crt"; - # 🔴 AN ALLOWLIST, NOT AN EXCLUDE LIST, FOR THE SAME REASON - # `server/Dockerfile.dockerignore` is one: a working tree of this repo - # holds store CONTENT (entry files) and caches that must never reach a - # build artefact, and an exclude list ships whatever nobody thought to - # name. Flake source is already git-filtered — untracked files are not - # copied — but that is a property of how the source was FETCHED, not of - # this derivation, and it does not hold for `nix build path:.`. Stating - # the filter here makes the property true of the derivation itself. - onlyCode = pkgs: pkgs.lib.cleanSourceWith { - src = ./.; - name = "cairn-source"; - filter = path: type: - let rel = pkgs.lib.removePrefix (toString ./. + "/") (toString path); - in - (type == "directory" && (rel == "lib" || rel == "server")) - || (rel == "cairn") - || (pkgs.lib.hasPrefix "lib/" rel && pkgs.lib.hasSuffix ".py" rel) - || (rel == "server/server.py"); - }; - - # 🔴 A SECOND ALLOWLIST FOR THE GO TREE, AND IT IS SEPARATE FROM - # `onlyCode` ON PURPOSE. `onlyCode` feeds the PYTHON artefacts — the - # packaged client and the pod image — and widening it to carry `go.mod`, - # `cmd/` and `internal/` would put the Go sources into both of those - # closures for nothing, and would change the `server-image` layer contents - # that `tests/test_flake_image_matches_dockerfile.py` is written against. - # Two filters is the honest shape while two implementations are alive; the - # day Python is retired, one of them goes away rather than being widened. - # - # An allowlist rather than an exclude list, for the same reason as - # `onlyCode`: a working tree of this repo holds store CONTENT and caches - # that must never reach a build artefact, and an exclude list ships - # whatever nobody thought to name. + # 🔴 AN ALLOWLIST FOR THE GO TREE, NOT AN EXCLUDE LIST: a working tree of this + # repo holds store CONTENT (entry files) and caches that must never reach a + # build artefact, and an exclude list ships whatever nobody thought to name. + # Flake source is already git-filtered — untracked files are not copied — but + # that is a property of how the source was FETCHED, not of this derivation, and + # it does not hold for `nix build path:.`. (There were two filters while the + # Python client and pod existed; theirs went with them.) # # 🔴 `tests/conformance/requests.json` IS IN THIS FILTER ON PURPOSE, AND IT # IS THE ONE NON-GO FILE HERE. `TestTheRouteLedgerMatchesTheConformance # Corpus` reads that list and compares it against the routes this server - # dispatches, in BOTH directions — it is the guard that closes the - # "a route added after the fixtures were generated" blind spot for a - # non-Python implementation, which `tests/conformance/README.md` names as - # explicitly open on this side. Leaving the file out would make the + # dispatches, in BOTH directions — it is the in-process half of the guard + # that closes the "a route added after the fixtures were recorded" blind + # spot (`tests/conformance/README.md`). Leaving the file out would make the # package's own test run skip its most load-bearing guard, in a sandbox, # silently. A sandbox that pins a dimension cannot be read as coverage of # it — so the dimension is supplied instead. # # 🔴 AND `internal/report/testdata/reader_fixtures.json` IS HERE FOR EXACTLY THE - # SAME REASON, WHICH IS WHY THE TWO SIT TOGETHER. That file is the ORACLE'S OWN - # rendered bytes for fifty report shapes the HTTP corpus cannot send — every + # SAME REASON, WHICH IS WHY THE TWO SIT TOGETHER. That file is the retired ORACLE'S + # OWN rendered bytes, FROZEN, for the report shapes the HTTP corpus cannot send — every # badge, the pagination branches, the search rungs, the difflib ratios — and # `TestTheRenderedBytesMatchTheORACLE…` is the differential gate over it. # Leaving it out would not skip quietly: the test calls `t.Fatalf`, so the @@ -389,8 +273,8 @@ # 🔴 AND A THIRD ONE, FOUND BY A RED SANDBOX BUILD RATHER THAN BY ANYONE # READING THE PARAGRAPH ABOVE. `internal/store/markersweep_test.go` is the # differential sweep behind `marker.go`'s narrowing ledger: it replays the - # ORACLE's verdicts for every generated line against two hand-rolled - # transcriptions of CPython regexes. Its fixture was first written to + # retired ORACLE's verdicts (FROZEN in that fixture) for every generated line + # against two hand-rolled transcriptions of CPython regexes. Its fixture was first written to # `tests/fixtures/`, which this allowlist does not carry — so the sweep was # green on the dev host and RED here, which is the two-tier split the # comment above describes, arriving one commit after it was written. Moved @@ -399,9 +283,9 @@ || (rel == "internal/store/testdata/marker_oracle_sweep.json") # 🔴 AND A FOURTH, ADDED WITHOUT WAITING FOR THE RED BUILD THIS TIME — the # paragraph above is what made it predictable. `internal/store`'s - # citation-id test replays `tests/citation_ids.py`'s PYTHON answers, so the - # two implementations of `CitationID` / `citation_id` cannot drift without - # one of them going red. 🔴 THE ALLOWLIST IS FILE-BY-FILE FOR FIXTURES: the + # citation-id test replays the citation ids FROZEN at the retirement of the + # Python implementation that recorded them — a contract pin, so a derivation + # change that would orphan every id already printed goes red. 🔴 THE ALLOWLIST IS FILE-BY-FILE FOR FIXTURES: the # `hasPrefix "internal/"` row above is inside the `type == "directory"` # clause, so it carries the DIRECTORY and not the JSON inside it. A reader # who assumes a directory row covers its files gets the two-tier split the @@ -663,7 +547,7 @@ moduleTests = mkGoModuleTests pkgs; meta = with pkgs.lib; { - description = "The Go port of the cairn store API (P1: dual-run against the Python oracle)"; + description = "The cairn store API server"; homepage = "https://github.com/ZacxDev/cairn"; license = licenses.mit; mainProgram = "cairn-server"; @@ -671,10 +555,9 @@ }; }; - # 🔴 THE GO CLIENT IS NOW `packages.default`/`apps.default`, AND THE PYTHON ONE IS STILL - # SHIPPED AS `packages.cairn`. That is a DEFAULT CUTOVER, not a deletion: the oracle, its - # `lib/`, `checks.client-resolves-its-lib` and the parity gate are all untouched, and - # Python is retired at P8. + # 🔴 THE GO CLIENT IS `packages.default`/`apps.default` — AND SINCE THE PYTHON CLIENT WAS + # RETIRED, THE ONLY CLIENT. The cutover came first (below) and the retirement later, as + # two separate decisions. # # 🔴 WHAT LICENSED THE FLIP WAS AN OPERATOR DECISION, NOT A GREEN GATE — RECORDED HERE # SO NOBODY RE-DERIVES IT FROM THE GATE. An earlier draft took the flip on exactly that @@ -686,14 +569,11 @@ # The read verbs route now and that guard is deleted. That closure is a PRECONDITION, # not the licence. # - # ⚠ THE FLIP WIDENS THE CLI CONTRACT, AND THAT IS ITS COST RATHER THAN A SIDE EFFECT - # (`tests/parity/README.md` residual 7). `cairn -verbs` and `cairn -exit-codes` exit 0 - # with a table on stdout here where the oracle's argparse exits 2 with `usage:`, so a - # single-dash token `nix run github:…/cairn` refused BEFORE this commit answers 0 AFTER - # it, for every consumer who does not name `#cairn`. `README.md` carries the - # announcement; measured at both points on the flip's branch. + # ⚠ THE FLIP WIDENED THE CLI CONTRACT: `cairn -verbs` and `cairn -exit-codes` exit 0 with a + # table on stdout here where the retired Python client's argparse exited 2 with `usage:`. + # `README.md` documents both flags as public surface. # - # 🔴 `gitMinimal` ON THE WRAPPER'S PATH, FOR THE SAME REASON THE PYTHON PACKAGE HAS IT. + # 🔴 `gitMinimal` ON THE WRAPPER'S PATH. # The client invokes `git` by BARE NAME to derive a repo's scope # (`internal/client/reposcope.go`), so a package that did not carry its own answer # would inherit whatever the caller's PATH holds — and `cairn recall` with no `--scope` @@ -720,7 +600,7 @@ ''; meta = with pkgs.lib; { - description = "The Go port of the cairn client (P2: parity-gated against the Python one)"; + description = "The cairn client"; homepage = "https://github.com/ZacxDev/cairn"; license = licenses.mit; mainProgram = "cairn"; @@ -1043,33 +923,30 @@ doCheck = false; }; - # The screenshot generator's data input: `tests/reader_fixtures.py`, the `lib/` it imports and - # the `server/server.py` it parses at import — text, scanned by `tests/leakscan.py`, and NOTHING - # else from the tree. + # The screenshot generator's data input: `tests/reader_fixtures.py` (a builder with no imports + # beyond the standard library) and the FROZEN fixture file whose `scopes`/`entries` it + # materialises — text, scanned by `tests/leakscan.py`, and NOTHING else from the tree. (Until + # the Python oracle was retired the builder DEFINED the world itself and needed `lib/` and + # `server/server.py` beside it; the world was carried over byte-for-byte into the fixture.) # # 🔴 `renameScope` IS THE PROVENANCE CONTROL'S HOOK, NOT A FEATURE: it renames one fixture scope - # in the builder, and `checks.ui-screenshots-are-current` requires the render to CHANGE under it — - # so "the committed bytes equal the derivation" is a claim about the fixture world rather than - # about a picture that would look the same whatever the fixture said. + # in the copied fixture, and `checks.ui-screenshots-are-current` requires the render to CHANGE + # under it — so "the committed bytes equal the derivation" is a claim about the fixture world + # rather than about a picture that would look the same whatever the fixture said. uiScreenshotFixture = pkgs: renameScope: pkgs.runCommand "cairn-ui-screenshot-fixture" { nativeBuildInputs = [ pkgs.gnused pkgs.gnugrep ]; } '' - mkdir -p "$out/tests" "$out/server" - cp ${./server/server.py} "$out/server/server.py" - cp -r ${pkgs.lib.cleanSourceWith { - src = ./lib; - name = "cairn-fixture-lib"; - filter = path: type: !(pkgs.lib.hasSuffix ".pyc" (toString path)) - && baseNameOf path != "__pycache__"; - }} "$out/lib" + mkdir -p "$out/tests" "$out/internal/report/testdata" cp ${./tests/reader_fixtures.py} "$out/tests/reader_fixtures.py" + cp ${./internal/report/testdata/reader_fixtures.json} "$out/internal/report/testdata/reader_fixtures.json" chmod -R u+w "$out" ${pkgs.lib.optionalString renameScope '' - n=$(grep -c 'alpha-notes' "$out/tests/reader_fixtures.py" || true) + f="$out/internal/report/testdata/reader_fixtures.json" + n=$(grep -c 'alpha-notes' "$f" || true) if [ "$n" = 0 ]; then echo "FAIL (could not vouch): the provenance control's scope 'alpha-notes' is not in the fixture" >&2 exit 2 fi - sed -i 's/alpha-notes/alpha-renamed/g' "$out/tests/reader_fixtures.py" + sed -i 's/alpha-notes/alpha-renamed/g' "$f" ''} ''; @@ -1155,165 +1032,26 @@ ''; }; - mkCairn = pkgs: pkgs.stdenv.mkDerivation { - pname = "cairn"; - inherit version; - src = onlyCode pkgs; - - strictDeps = true; - nativeBuildInputs = [ pkgs.makeWrapper ]; - dontBuild = true; - - # 🔴 `lib/` MUST SIT BESIDE THE REAL SCRIPT, AND PYTHONPATH IS NOT A - # SUBSTITUTE. The client finds its siblings with - # `Path(__file__).resolve().parent / "lib"`, and `.resolve()` follows - # symlinks — so the directory that must contain `lib/` is the one - # holding the REAL file, never the one holding whatever was invoked. - # Hence real script and `lib/` together under `libexec`, with `bin/` - # holding a wrapper that execs it. Exporting PYTHONPATH instead would - # make the modules reachable by a SECOND mechanism shadowing the first, - # leaving the file's own stated one silently dead — so the next person - # to move this layout would see nothing break until they also dropped - # the wrapper. - installPhase = '' - runHook preInstall - - install -Dm755 cairn $out/libexec/cairn/cairn - install -Dm644 -t $out/libexec/cairn/lib lib/*.py - - # `--replace-fail`, never `--replace`: a substitution that matches - # nothing must be an error. A silently-unmatched shebang rewrite - # leaves `/usr/bin/env python3` in a store path, which then works on - # the machine that built it and fails on one with no system python — - # a failure landing nowhere near its cause. - substituteInPlace $out/libexec/cairn/cairn \ - --replace-fail '#!/usr/bin/env python3' '#!${(python pkgs)}/bin/python3' - - # `git` is invoked by BARE NAME (`lib/entry_shape.py::_git`) to derive - # a repo's scope. Prefixed rather than suffixed so the package carries - # its own answer instead of inheriting whatever the caller's PATH holds. - # - # `gitMinimal`, not `git`: the only invocations are `rev-parse` and - # `merge-base`, and full `git` drags perl's CGI/libwww stack — 385 MiB - # of a 386 MiB closure, paid on every consumer's switch, for an 800 KB - # stdlib script. gitMinimal supplies both and closes at 159 MiB. - makeWrapper $out/libexec/cairn/cairn $out/bin/cairn \ - --prefix PATH : ${pkgs.lib.makeBinPath [ pkgs.gitMinimal ]} - - runHook postInstall - ''; - - # 🔴 WITHOUT THIS THE DERIVATION IS NOT REPRODUCIBLE, and `nix build - # --rebuild` says so: the install check below IMPORTS the whole closure, - # CPython writes `lib/__pycache__/*.pyc` into `$out` before the daemon - # seals it, and each `.pyc` header records the source mtime as build - # WALL-CLOCK while the installed `.py` are normalised to mtime 1. Two - # builds of one input then differ in exactly those seven files. - # Worse, that bytecode is permanently INVALID and never used — the - # recorded mtime never matches the sealed source, so every invocation - # recompiles anyway and the files are dead weight in the closure. - PYTHONDONTWRITEBYTECODE = "1"; - - # 🔴 AT BUILD TIME, NOT ONLY IN `checks`. A consumer pinning this flake - # builds the PACKAGE and never runs `nix flake check`, so a - # sibling-import break would otherwise reach a machine and be found by - # the operator at the moment they wanted to read a note. - # - # ⚠ `--help` IS SUFFICIENT FOR THAT BREAK — an earlier version of this - # comment claimed the opposite ("argparse is built before any subcommand - # imports anything, so `--help` alone is not evidence") and it was - # MEASURED FALSE: the imports are at module scope, so removing `lib/` - # kills `--help` at line 91 with `ModuleNotFoundError: timeouts`, right - # here, before `checks.client-resolves-its-lib` can even be built. - # `checks.client-resolves-its-lib` therefore earns its place on the - # POSITIVE side — it runs a real subcommand to completion against a real - # cache root — not as a deeper detector of a missing `lib/`. - doInstallCheck = true; - installCheckPhase = '' - runHook preInstallCheck - $out/bin/cairn --help > /dev/null - runHook postInstallCheck - ''; - - meta = with pkgs.lib; { - description = "Read-through client for the cairn subsystem-note store"; - homepage = "https://github.com/ZacxDev/cairn"; - license = licenses.mit; - mainProgram = "cairn"; - platforms = platforms.unix; - }; - }; - - mkServerImage = pkgs: - let - # ALL of `lib/`, not an enumeration. The Dockerfile enumerates because - # a docker build context is a directory it must not slurp wholesale, - # and `test_the_image_copies_every_module_it_needs` exists to keep - # that hand-written list honest. Here the source filter has already - # excluded everything that is not code, so there is no list to keep - # honest and no closure for it to get wrong — the module set cannot - # drift from the imports because it is not stated separately. - tree = pkgs.runCommand "cairn-server-tree" { } '' - mkdir -p $out/app/lib $out/app/server - cp ${onlyCode pkgs}/lib/*.py $out/app/lib/ - cp ${onlyCode pkgs}/server/server.py $out/app/server/ - ''; - in - pkgs.dockerTools.buildLayeredImage { - name = "cairn-store"; - tag = version; - contents = [ tree ] ++ serverTools pkgs; - - # `/data` is where the PVC mounts and `/home/nonroot` is what HOME - # names; both are created and owned here so the image is runnable - # without a mount. ⚠ UNGUARDED: nothing in this repo checks either - # line. `publish-image.yml`'s smoke run starts this image with no - # token source and expects a NON-ZERO exit, and `server/server.py` - # returns on the missing token before it opens the store root. - fakeRootCommands = '' - mkdir -p ./data ./home/nonroot - chown -R ${toString serverUid}:${toString serverUid} ./data ./home/nonroot - ''; - enableFakechroot = true; - - config = { - Cmd = [ "${(python pkgs)}/bin/python3" "/app/server/server.py" ]; - # 🔴 `PATH` IS DECLARED, and its absence was not cosmetic. Without - # it `kubectl exec … -- tar` resolves nothing even once busybox is - # in the image, so the seed path fails with `executable file not - # found in $PATH` rather than anything naming the real cause. - Env = pkgs.lib.mapAttrsToList (k: v: "${k}=${v}") - (serverEnv // { PATH = serverPath; }); - User = "${toString serverUid}:${toString serverUid}"; - ExposedPorts = { "${toString serverPort}/tcp" = { }; }; - WorkingDir = "/app"; - }; - }; - # 🔴 THE GO POD'S IMAGE. IT IS AN ADDITION, AND UNTIL IT LANDED THERE WAS NO # GO SERVER IMAGE AT ALL — `packages.cairn-server-go` is a bare binary package. - # ⚠ IT IS NOW PUBLISHED: `.github/workflows/publish-image.yml` pushes this output - # to the `cairn-store-go` ghcr package beside the Python pod's `cairn-store`, - # under the same `sha-<40-hex>` tag scheme. 🔴 AND IT IS NOW DEPLOYED: the + # ⚠ IT IS PUBLISHED: `.github/workflows/publish-image.yml` pushes this output + # to the `cairn-store-go` ghcr package under a `sha-<40-hex>` tag. (The retired + # Python pod was published beside it as `cairn-store`; that leg was deleted with it.) + # 🔴 AND IT IS NOW DEPLOYED: the # cluster pulls `cairn-store-go`. ⚠ This read "PUBLISHED IS NOT DEPLOYED — no # manifest references it, and the cutover is a separate decision"; the cutover # was taken and both halves went false. It is the site an earlier draft of the # sweep MISSED while editing this very file — and then cited, from # `publish-image.yml`, as proof `flake.nix` had never made the claim. # - # 🔴 A THIRD BUILD, NOT A THIRD STATEMENT OF THE CONTRACT, AND THAT DISTINCTION - # IS THE WHOLE DESIGN. `server/README.md` says "do not add a third way to produce - # this pod: a third statement of the runtime contract would be outside that pin, - # and it would be the one that actually ships". The hazard it names is a COPY. - # This derivation states nothing: uid, port, exposed port and every environment - # variable come from `serverUid`/`serverPort`/`serverEnvGo`, which are the same - # bindings `tests/test_flake_image_matches_dockerfile.py` pins against - # `server/Dockerfile`. `tests/test_flake_go_image_runtime_contract.py` is what - # closes the loop on this side, because being DERIVED is a property of today's - # source and a copy is one edit away. + # 🔴 IT STATES NOTHING OF THE CONTRACT ITSELF. Uid, port, exposed port and every + # environment variable come from `serverUid`/`serverPort`/`serverEnv` above; + # `tests/test_flake_go_image_runtime_contract.py` closes the loop, because being + # DERIVED is a property of today's source and a copy is one edit away. (It was once + # a THIRD build of the pod beside the Python image and `server/Dockerfile`, which is + # why that test exists; both are retired.) # - # 🔴 IT CARRIES BUSYBOX AND DECLARES `PATH` FOR EXACTLY THE REASON `mkServerImage` - # DOES — see the 🔴 above `serverPath`. The operational procedures are the pod's, + # 🔴 IT CARRIES BUSYBOX AND DECLARES `PATH` — see the 🔴 above `serverPath`. The operational procedures are the pod's, # not the interpreter's: `server/seed.sh` pushes the store through # `kubectl exec … -- tar -xf -` and runs its containment guard through `sh -c`, # and `server/README.md`'s credential revocation is @@ -1322,16 +1060,13 @@ # verdict — so an image without a shell would take away a revocation path that # the binary itself still implements. # - # ⚠ `Cmd` NAMES THE BINARY BY ABSOLUTE STORE PATH, like `mkServerImage` names its - # interpreter. `/bin/cairn-server` would also resolve, and that is the reason not + # ⚠ `Cmd` NAMES THE BINARY BY ABSOLUTE STORE PATH. `/bin/cairn-server` would also resolve, and that is the reason not # to use it: the entrypoint would then depend on `contents` placing the package's # `bin/` at the image root AND on `PATH`, so a change to either would turn a # wiring mistake into a container that does not start. # - # ⚠ `WorkingDir = "/"`, not `/app`: there is no `/app`. The Python pod's `/app` is - # where its SOURCE is copied, and a single binary has no source tree. `/` matches - # what `server/Dockerfile` leaves the Python pod at, and every path the server - # touches — the store, the token file — is absolute. + # ⚠ `WorkingDir = "/"`: a single binary has no source tree to sit in, and every + # path the server touches — the store, the token file — is absolute. mkGoServerImage = pkgs: let goServer = mkGoServer pkgs; in @@ -1342,7 +1077,7 @@ # `/data` is where the PVC mounts; created and owned here so the image is # runnable without a mount. No `/home/nonroot`: this pod has no `HOME` — see - # `serverEnvPythonOnly`. + # `serverEnv`. # # ⚠ THE `chown` IS UNGUARDED, AND THE RETRACTED CLAIM WAS THAT A SMOKE TEST # WOULD CATCH IT. The sentence that used to carry this — "nothing runs this @@ -1371,7 +1106,7 @@ config = { Cmd = [ "${pkgs.lib.getExe goServer}" ]; - Env = pkgs.lib.mapAttrsToList (k: v: "${k}=${v}") (serverEnvGo // { + Env = pkgs.lib.mapAttrsToList (k: v: "${k}=${v}") (serverEnv // { PATH = serverPath; SSL_CERT_FILE = goServerCaBundle pkgs; }); @@ -1448,12 +1183,9 @@ { packages = forAll (pkgs: { - cairn = mkCairn pkgs; - # 🔴 `default` IS THE GO CLIENT, AND `cairn` IS STILL THE PYTHON ONE. The - # cutover was an OPERATOR DECISION taken after residual 8 closed — never a - # gate outcome; see the block above `mkGoClient` for the reverted draft that - # read it the other way. `packages.cairn` is NOT deleted here: it is still - # the oracle the parity gate measures against, and it goes at P8. + # 🔴 `default` IS THE GO CLIENT — the only client. The cutover was an OPERATOR + # DECISION, never a gate outcome; the Python client (`packages.cairn`, `apps.cairn`) + # was retired afterwards and there is no `#cairn` attribute any more. # # 🔴 THIS LINE AND `apps.default` MOVE TOGETHER OR NOT AT ALL — see the block # above `apps` for why one alone gives two clients under one name. @@ -1474,27 +1206,21 @@ cairn-clickup = mkClickupPlugin pkgs; } // nixpkgs.lib.optionalAttrs (builtins.elem pkgs.stdenv.hostPlatform.system linuxSystems) { - server-image = mkServerImage pkgs; - # 🔴 THE PYTHON POD KEEPS THE UNSUFFIXED NAME, and that is not inertia: - # `.github/workflows/publish-image.yml` builds `packages.server-image` by - # name, `server/README.md` documents it, and consumers pin it. Renaming it to - # make room for this one would change what gets PUBLISHED, which is a deploy - # decision and not a build. `server-image-go` is published under its OWN - # package name (`cairn-store-go`), which is what keeps that true. + # ⚠ `server-image-go` KEEPS ITS SUFFIX although the Python `server-image` it was + # distinguished from is retired: `publish-image.yml` builds it by name and + # consumers pin the `cairn-store-go` package it publishes to. Renaming either is a + # deploy decision, not a cleanup. server-image-go = mkGoServerImage pkgs; - # 🔴 `ui-image`, NOT `ui-image-go`. The `-go` suffix on the pod distinguishes - # it from a PYTHON sibling that exists and is still published; this surface has - # no second implementation and never had one, so a suffix would imply a - # counterpart a reader would then go looking for. + # 🔴 `ui-image`, NOT `ui-image-go`. This surface never had a second + # implementation, so a suffix would imply a counterpart a reader would then go + # looking for. # # ⚠ IT IS PUBLISHED, AND THE CLAIM THAT IT WAS NOT IS RETRACTED — the wording # here has now been wrong in BOTH directions, which is why the record is kept. # It first read "It publishes to its own ghcr package", present tense, for a leg # the same change deliberately excluded. It was then corrected to "NOTHING - # PUBLISHES IT YET — `publish-image.yml` pushes `server-image` and - # `server-image-go` and no third leg exists", which is the sentence that went - # stale: that workflow now builds this derivation, pushes it under the OCI name + # PUBLISHES IT YET", which is the sentence that went stale: that workflow now builds this derivation, pushes it under the OCI name # below, and PROVES the result pullable with no credentials. So the name below # is a package anybody can pull. ui-image = mkGoUIImage pkgs; @@ -1507,23 +1233,14 @@ # `nix profile install` and every flake input got the other — one name, two # clients, differing by which command the consumer happened to use. # - # 🔴 `apps.cairn` DELIBERATELY DID NOT MOVE, AND IT IS PINNED RATHER THAN LEFT TO - # PROSE. It is the escape hatch the announcement names: `nix run - # github:…/cairn#cairn` is still the Python client, which is what makes residual - # 7's widening opt-out-able rather than forced. Because `README.md` now PROMISES - # that, repointing this one line at `mkGoClient` would defeat the promise while - # `packages.default`/`apps.default`/`packages.cairn` all stayed exactly right — - # the half-flip class one attribute over. `default-is-the-go-client` asserts it. + # ⚠ THERE IS NO `apps.cairn` ANY MORE. It was the opt-out to the retired Python + # client, kept while that client shipped; it went with `packages.cairn`. # # ⚠ THERE IS NO `apps.cairn-go`, DELIBERATELY. `nix run .#cairn-go` already # resolves through `packages.cairn-go`'s `mainProgram = "cairn"` — measured, not - # assumed — so an entry here would be a third name for one binary with nothing to - # buy, and `apps.default` above is now a fourth. + # assumed — so an entry here would be a second name for one binary with nothing to + # buy. apps = forAll (pkgs: { - cairn = { - type = "app"; - program = "${nixpkgs.lib.getExe (mkCairn pkgs)}"; - }; default = { type = "app"; program = "${nixpkgs.lib.getExe (mkGoClient pkgs)}"; @@ -1531,7 +1248,7 @@ # ⚠ A DEVELOPER COMMAND, NOT A CLIENT, AND IT IS THE ONE APP HERE THAT WRITES TO # THE WORKING TREE. `nix run .#build-ui-stylesheet` regenerates # `internal/ui/app.css` from `internal/ui/tailwind.css`. It is not part of the - # default/`cairn` wiring the check below pins, and adding it changes neither. + # default wiring the check below pins, and adding it changes nothing there. build-ui-stylesheet = { type = "app"; program = "${nixpkgs.lib.getExe (buildUIStylesheet pkgs)}"; @@ -1551,7 +1268,6 @@ }); checks = forAll (pkgs: { - cairn = mkCairn pkgs; # Each module's suite, once; every Go package below depends on its module's entry. go-module-tests = mkGoModuleTests pkgs; plugins-module-tests = mkPluginModuleTests pkgs; @@ -1747,10 +1463,8 @@ # 🔴 WHICH CLIENT THE UNQUALIFIED NAMES RESOLVE TO, PINNED AS A RELATIONSHIP # BETWEEN RESOLVED DERIVATIONS. Before this check, NOTHING in the repository # asserted it: `packages.default`/`apps.default` appeared in `flake.nix` and in no - # test, the two other `checks.*` entries name `mkCairn`/`mkGoClient` explicitly, - # every CI job builds by explicit attribute, and the parity harness builds with - # `go build ./cmd/cairn` and runs the oracle script directly. The wiring was pinned - # by PROSE, and prose is walkable three ways: + # test, and every CI job builds by explicit attribute. The wiring was pinned by + # PROSE, and prose is walkable: # # • a flip taken on the wrong licence, REVERTED once already, could land fully # green — nothing here would have noticed either the flip or the revert; @@ -1759,11 +1473,9 @@ # resolves `apps.default` FIRST and only falls back to `packages.default`'s # `mainProgram`, so the run path and the build path would serve two different # clients under ONE name, differing by which command the consumer used; - # • a later accidental revert of either line would be invisible; - # • and the SAME half-flip one attribute over: repointing `apps.cairn` at the Go - # client leaves all three of the assertions above green — `packages.cairn` is - # untouched by it — while the ESCAPE HATCH `README.md` promises silently - # becomes the Go client. That is why `apps.cairn` is compared here too. + # • a later accidental revert of either line would be invisible. + # (While the Python client shipped this also pinned `apps.cairn`/`packages.cairn` as + # the documented opt-out; both were retired with it.) # # 🔴 IT COMPARES RESOLVED DERIVATIONS, NOT SPELLINGS. A guard matching the string # `mkGoClient` in this file is walkable by renaming the binding while the wiring @@ -1789,11 +1501,8 @@ # says nothing about `mainProgram`, and no CI job runs `.#` bare. The NAME check # below is the second, independent reading. # - # ⚠ WHAT IT DOES NOT CLAIM: nothing about either client's BEHAVIOUR; and the name - # check is insensitive on the PYTHON side, where `pname` is already `cairn`, so a - # `mainProgram` removed from `mkCairn` would leave it green. That is a real gap, - # named rather than papered over — the hazard it exists for is `mkGoClient`, whose - # pname and mainProgram DIFFER. + # ⚠ WHAT IT DOES NOT CLAIM: anything about the client's BEHAVIOUR. The name check + # exists for `mkGoClient`, whose pname (`cairn-go`) and mainProgram (`cairn`) DIFFER. default-is-the-go-client = let system = pkgs.stdenv.hostPlatform.system; @@ -1803,14 +1512,10 @@ exe = drv: builtins.unsafeDiscardStringContext (nixpkgs.lib.getExe drv); defaultPkg = path self.packages.${system}.default; goPkg = path self.packages.${system}.cairn-go; - pyPkg = path self.packages.${system}.cairn; defaultExe = exe self.packages.${system}.default; - pyExe = exe self.packages.${system}.cairn; appProgram = builtins.unsafeDiscardStringContext self.apps.${system}.default.program; - pyAppProgram = - builtins.unsafeDiscardStringContext self.apps.${system}.cairn.program; - # Both clients declare `mainProgram = "cairn"`, which is the single name every + # The client declares `mainProgram = "cairn"`, which is the single name every # documented invocation uses. `mkGoClient`'s pname is `cairn-go`, so this is # the one operand where the fallback is DISTINGUISHABLE from the intent. wantExeName = "cairn"; @@ -1826,8 +1531,7 @@ # the floor every equality below rests on — two empty strings compare equal, # so the comparisons are only as good as their operands being store paths. # Keep it, and do not count it as coverage of a defect anyone has observed. - for p in '${defaultPkg}' '${goPkg}' '${pyPkg}' '${defaultExe}' '${pyExe}' \ - '${appProgram}' '${pyAppProgram}'; do + for p in '${defaultPkg}' '${goPkg}' '${defaultExe}' '${appProgram}'; do case "$p" in /nix/store/?*) ;; *) @@ -1859,33 +1563,6 @@ failed=1 fi - if [ "${pyPkg}" = "${defaultPkg}" ]; then - echo "FAIL: packages.cairn and packages.default are the SAME derivation." - echo " packages.cairn = packages.default = ${pyPkg}" - echo " \`#cairn\` is the opt-out README.md announces, and this state points" - echo " it at the Go client. It would NOT redden the parity gate —" - echo " tests/parity/harness.py runs the oracle SCRIPT directly and never" - echo " builds this package — which is exactly why it is asserted here." - failed=1 - fi - - # 🔴 THE ESCAPE HATCH'S `nix run` SPELLING, WHICH THE THREE ABOVE LEAVE FREE. - # `nix run github:…/cairn#cairn` resolves `apps.cairn` FIRST, the same - # precedence that makes `apps.default` load-bearing. README.md now PROMISES - # this spelling opts out, and a flake input taking `apps.${system}.cairn` gets - # the same attribute, so a repoint here is a silent flip of the documented - # escape hatch with every other assertion in this file still green. - if [ "${pyAppProgram}" != "${pyExe}" ]; then - echo "FAIL: apps.cairn does NOT point at packages.cairn — the announced opt-out" - echo " resolves to something else." - echo " apps.cairn.program = ${pyAppProgram}" - echo " getExe packages.cairn = ${pyExe}" - echo " README.md names \`#cairn\` as the opt-out from the default flip, in" - echo " both the CLI and the flake-input spelling. If this pair disagrees," - echo " the opt-out is a promise the tree does not keep." - failed=1 - fi - # 🔴 THE NAME, NOT ANOTHER EQUALITY — the common-mode reading. See the block # above: a removed `meta.mainProgram` moves BOTH sides of an equality at once, # so the equalities cannot see it. `getExe` falls back to the pname with only a @@ -1893,9 +1570,7 @@ # and breaks every documented invocation while the comparisons stay green. for spec in \ 'getExe packages.default|${builtins.baseNameOf defaultExe}' \ - 'apps.default.program|${builtins.baseNameOf appProgram}' \ - 'getExe packages.cairn|${builtins.baseNameOf pyExe}' \ - 'apps.cairn.program|${builtins.baseNameOf pyAppProgram}'; do + 'apps.default.program|${builtins.baseNameOf appProgram}'; do label="''${spec%%|*}" name="''${spec##*|}" if [ "$name" != '${wantExeName}' ]; then @@ -1913,15 +1588,11 @@ echo "ok: packages.default == packages.cairn-go == ${defaultPkg}" echo " apps.default.program == ${appProgram}" - echo " packages.cairn is distinct == ${pyPkg}" - echo " apps.cairn.program == getExe packages.cairn == ${pyAppProgram}" - echo " all four resolved programs are named '${wantExeName}'" + echo " both resolved programs are named '${wantExeName}'" { echo "packages.default ${defaultPkg}" echo "packages.cairn-go ${goPkg}" - echo "packages.cairn ${pyPkg}" echo "apps.default.program ${appProgram}" - echo "apps.cairn.program ${pyAppProgram}" echo "exe-name ${wantExeName}" } > $out ''; @@ -1951,22 +1622,20 @@ ''; # 🔴 THE GO CLIENT'S OWN LEDGER, READ OUT OF THE RUNNING BINARY — the one claim a - # compile cannot make, and the one the PYTHON-side gates are structurally blind to. - # `capability_ledger.cli_verbs_from_parser` asks the PYTHON argparse parser what - # subcommands it has and has no equivalent for a compiled program, so a Go client - # that GAINED a verb or silently LOST one leaves that gate green. + # compile cannot make: a client that GAINED a verb or silently LOST one, or whose exit + # codes moved, is a red check here rather than a surprise for a caller. # # 🔴 AND IT IS A PAIR, NOT A ZERO. A check that asserted only "the command exited 0" # would pass for a binary that printed nothing. The exact set is pinned by hand here - # — the same verbs `tests/test_capability_ledger.py` discovers from the Python parser, - # which is what makes the two implementations comparable at all. 🔴 THE SET IS THE + # — and `tests/test_capability_ledger.py` pins that hand list against the capability + # ledger, so it is not free text. 🔴 THE SET IS THE # HEREDOC BELOW AND THE COUNT IS NOT WRITTEN DOWN ANYWHERE IN THIS COMMENT: a number # here would be a hand list one word long, which is the thing the heredoc replaced. # # ⚠ WHAT THIS SANDBOX CANNOT HAVE: no store, no token, no network and no HOME with a - # cache root, so it exercises the LEDGERS and nothing about reading or writing. The - # parity harness is what measures behaviour, and it needs a running pod that a nix - # sandbox is the wrong place for. + # cache root, so it exercises the LEDGERS and nothing about reading or writing. The Go + # client's own tests (against an in-process pod) and the end-to-end scripts under + # `tests/` are what measure behaviour. go-client-declares-its-verbs = pkgs.runCommand "cairn-go-client-declares-its-verbs" { nativeBuildInputs = [ (mkGoClient pkgs) ]; } '' set -o pipefail @@ -1979,49 +1648,40 @@ exit 1 fi - cat > want-verbs.txt <<'EOF' + # 🔴 ONE LIST, SORTED, AND NOT FREE TEXT: `tests/test_capability_ledger.py` pins it + # against `testlib/capability_ledger.LEDGER`'s verbs, so a verb cannot be added + # here alone without a red test. (Until the Python client was retired this was two + # lists — the verbs both clients had, and the Go-only ones; the split was FOLDED, + # not dropped, when there stopped being a second client to differ from.) + cat > want-all-verbs.txt <<'EOF' append writes - create writes - doctor reads - ls-entries reads - put writes - recall reads - routes reads - search reads - sync reads - validate reads - EOF - # 🔴 THE GO-ONLY VERBS, DECLARED APART FROM THE SHARED SET ABOVE. Decision 3 of - # the arcs/sessions plan puts new verbs in the Go client only, so a verb here has - # NO Python twin. Neither list is free text: `tests/test_capability_ledger.py` - # pins the one above against the PYTHON parser and this one against - # `capability_ledger.GO_ONLY_VERBS` (the `go_only` rows), so a verb cannot be - # moved between them, or declared Go-only here alone, without a red test. The - # first, `sessions`, is the arcs/sessions S2 slice; the arc registry is S3; the four - # `memo-*` verbs are scope mail's S3 (decision 8 of the scope-mail plan); `sources` - # is the scope-refs plan's S3 and `audit-refs` its S5; `transcript` is the transcripts - # plan's S8 (its decision 17); `log` is Phase 1 of the v1 event-log plan; `associate`, `refs`, `parse` - # and `fold` are its Phase 5 (the Python client's last consumers move to the Go one). - cat > want-go-only-verbs.txt <<'EOF' arc-register writes - associate reads arc-show reads arcs reads + associate reads audit-refs reads + create writes + doctor reads + fold reads log reads + ls-entries reads memo-check reads memo-read reads memo-retract writes memo-send writes - fold reads parse reads + put writes + recall reads refs reads + routes reads + search reads sessions reads sources reads + sync reads transcript reads + validate reads EOF - sed -i 's/^ *//; /^$/d' want-verbs.txt want-go-only-verbs.txt - sort -u want-verbs.txt want-go-only-verbs.txt > want-all-verbs.txt + sed -i 's/^ *//; /^$/d' want-all-verbs.txt if ! diff -u want-all-verbs.txt verbs.txt; then echo "FAIL: the Go client's declared verb set is not the set this check names." @@ -2039,10 +1699,8 @@ exit 1 fi - # 🔴 THE SHARED EXIT-CODE SET, COMPUTED FROM THE BINARY'S OWN TWO TABLES. The Python - # ledger computes its intersection over the PYTHON client's nine codes, so a Go-only - # code colliding with `doctor`'s 10 leaves it green. `{0, 9}` is the documented set - # and this is where the Go side's version of it is checked. + # 🔴 THE SHARED EXIT-CODE SET, COMPUTED FROM THE BINARY'S OWN TWO TABLES. `{0, 9}` is + # the documented set; a client code colliding with `doctor`'s 10 would move it. grep '^client ' codes.txt | awk '{print $3}' | sort -u > client-values.txt grep '^doctor ' codes.txt | awk '{print $3}' | sort -u > doctor-values.txt comm -12 client-values.txt doctor-values.txt > shared.txt @@ -2070,14 +1728,13 @@ # command exited 0" would pass for a binary that printed nothing, which # is the reassuring zero this repository keeps finding. So the exact # route set is pinned, spelled out by hand — the same set - # `tests/test_conformance_suite.py` spells for the oracle, which is what - # makes the two implementations comparable at all. + # `tests/test_conformance_suite.py` spells as `EXPECTED_ROUTES`. # # ⚠ WHAT THIS SANDBOX CANNOT HAVE, stated rather than assumed away: no # store, no token file and no network, so it exercises the LEDGER and # nothing about serving. The conformance corpus is what measures the - # served behaviour, and it needs a running pair of servers that a nix - # sandbox is the wrong place for. + # served behaviour, and it needs a running server that a nix sandbox is + # the wrong place for. go-server-declares-its-routes = pkgs.runCommand "cairn-go-server-declares-its-routes" { nativeBuildInputs = [ (mkGoServer pkgs) ]; } '' set -o pipefail @@ -2089,46 +1746,37 @@ exit 1 fi - cat > want.txt <<'EOF' - GET recall - GET search - GET snapshot - HEAD recall - HEAD search - HEAD snapshot - POST entry - PUT entry - EOF - # 🔴 THE GO-ONLY ROUTES, DECLARED APART FROM THE ORACLE-SHARED SET ABOVE — - # routes the deployed pod serves and `server/server.py` does not (decision 3 of - # the arcs/sessions plan). `tests/test_capability_ledger.py` pins the list above - # against the oracle's tables and this one against the `go_only` rows of - # `tests/conformance/requests.json` AND of the capability ledger. The first, - # `sessions/`, is the arcs/sessions S2 slice; `arcs`/`arc` are S3's; - # `sources/` is S2 of the scope-refs plan; `whoami` is the caller's own - # self-view. - cat > want-go-only.txt <<'EOF' + # One list, sorted. `tests/test_capability_ledger.py` pins it against the ledger's + # routes (the old Go-only half was folded in when the oracle was retired). + cat > want-all.txt <<'EOF' GET arc GET arcs + GET recall + GET search GET sessions + GET snapshot GET sources GET whoami HEAD arc HEAD arcs + HEAD recall + HEAD search HEAD sessions + HEAD snapshot HEAD sources HEAD whoami + POST entry PUT arc + PUT entry EOF - sed -i 's/^ *//; /^$/d' want.txt want-go-only.txt - sort -u want.txt want-go-only.txt > want-all.txt + sed -i 's/^ *//; /^$/d' want-all.txt if ! diff -u want-all.txt routes.txt; then echo "FAIL: the Go server's declared route set is not the set this check" echo " names. Adding a row to a dispatch table is adding a public," echo " internet-reachable endpoint, and this is where somebody has" echo " to think about it — update the conformance request list and" - echo " regenerate in the same change." + echo " record its goldens (run_go.sh record) in the same change." exit 1 fi @@ -2175,9 +1823,8 @@ # DECISION RATHER THAN A GAP — a draft of this file carried one, modelled on # `go-server-declares-its-routes` above. That check earns its place because # the pod's route set is the SERVED CONTRACT `tests/conformance/requests.json` - # replays and the corpus builder is Python, blind to a compiled binary: the - # ledger read out of the running program is a genuinely second instrument in - # a second environment. The UI has neither — `ui.DeclaredRoutes()` derives + # replays, and the ledger read out of the running program is a genuinely second + # instrument in a second environment. The UI has neither — `ui.DeclaredRoutes()` derives # from the same map its dispatcher reads, and the only expectation anywhere # is a hand-written list. A check that ran the binary to print that list and # diffed it against a third hand-written copy would restate one claim down a @@ -2188,79 +1835,14 @@ # it. When a later phase gives this surface an external corpus, the second # tier comes back with it. - # 🔴 THIS CHECK IS THE POSITIVE HALF, AND IT IS *NOT* THE DETECTOR FOR A - # MISSING `lib/` — `doInstallCheck` above is, and it fires first. - # - # An earlier version of this comment claimed the opposite: that dropping - # `lib/` would leave `cairn` with a working `--help` because "argparse is - # built before any subcommand imports anything". MEASURED FALSE — the - # imports are at MODULE SCOPE (`cairn:91`), so `--help` dies with - # `ModuleNotFoundError: timeouts` during the package's own install check, - # and this derivation never gets built. The sentence is deleted rather - # than reworded because a maintainer who believed it would conclude - # `doInstallCheck` proves nothing and delete the only build-time gate - # standing between a broken client and a consumer's `home-manager switch`. - # - # What this check adds is DEPTH THE INSTALL CHECK DOES NOT REACH: it runs - # a real subcommand to completion against a real cache root, driving - # `cairn_doctor`, `subsystem_read_store` and `entry_shape` through their - # logic rather than merely importing them. - # - # Its EXIT CODE is deliberately not asserted. `doctor` reports on an - # operator's configuration, and in a build sandbox there is no store, no - # token and no pod — a non-zero verdict is the CORRECT answer here, and - # demanding zero would either pin a wrong expectation or push the check - # into faking an environment. What is asserted is the thing that - # distinguishes a working package from a broken one: it ran far enough - # to produce its own report rather than dying in an import. - client-resolves-its-lib = pkgs.runCommand "cairn-client-resolves-its-lib" - { nativeBuildInputs = [ (mkCairn pkgs) ]; } '' - set -o pipefail - # HOME is unset in the sandbox and `Path.home()` is evaluated at - # import time by `subsystem_read_store` — the same reason the image - # sets it. Without this the check would fail for a reason that has - # nothing to do with what it is testing. - export HOME=$TMPDIR - - if ! cairn doctor > out.txt 2> err.txt; then - echo "note: doctor exited non-zero, which is expected with no store configured" - fi - - # 🔴 NEGATIVE-CONTROL-SHAPED ASSERTION: an ImportError is exactly what - # a lost `lib/` produces, and it is what this check exists to catch. - # Asserting its ABSENCE is only meaningful alongside the positive - # assertion below — "no error appeared" is also what a command that - # never ran produces. - if grep -qE 'ModuleNotFoundError|ImportError' err.txt; then - echo "FAIL: the packaged client could not import its own lib/:" - cat err.txt - exit 1 - fi - - # Positive: the report was actually produced. `doctor` prints one - # check line per subject, so a run that imported and executed says - # something; a run that did nothing says nothing, and that is the - # zero this pair exists to tell apart. - if ! grep -q . out.txt; then - echo "FAIL: doctor produced NO output — it cannot have run." - echo "--- stderr ---"; cat err.txt - exit 1 - fi - - echo "ok: packaged client imported its own lib/ and produced a report" - cp out.txt $out - ''; }); devShells = forAll (pkgs: { default = pkgs.mkShell ({ - # 🔴 THE SAME PIN AS THE ARTEFACTS, AND THIS WAS THE FOURTH THING. - # `pkgs.python3` here resolved to 3.14 while the package shebang, the - # image `Cmd`, `server/Dockerfile` and the CI matrix were all 3.12 — - # so the shell `shellHook` tells you to run the suite in was on a - # DIFFERENT interpreter from the one shipped, and a lock bump would - # move it again silently. That is precisely what pinning the other - # three was supposed to close. + # 🔴 THE SAME PIN AS CI. `pkgs.python3` here resolved to 3.14 while the + # CI matrix was 3.12 — so the shell `shellHook` tells you to run the suite + # in was on a DIFFERENT interpreter from the one CI runs, and a lock bump + # would move it again silently. packages = [ ((python pkgs).withPackages (ps: [ ps.pytest ])) pkgs.git @@ -2282,14 +1864,13 @@ # today. If you move one, move the other. pkgs.postgresql_18 # `server/seed.sh` stages the store with `rsync -a --delete`, and the - # seed tests in `tests/test_subsystem_store_api.py` run it for real. + # seed tests in `tests/test_seed.py` run it for real. # stdenv does not provide rsync, so without this the shell only passes # those tests on a host that happens to carry its own (workbench gets # one from `~/.nix-profile`); the remote-run workspace pod has none. pkgs.rsync - # `verify-byte-identity.sh` fetches with curl, and the byte-identity - # verifier tests run it; like rsync, the shell only passed them on a - # host that carries its own. + # `tests/conformance/run_go.sh` polls the server's `/healthz` with curl; + # like rsync, a shell without it only works on a host that carries its own. pkgs.curl ]; shellHook = '' @@ -2297,7 +1878,7 @@ echo " python3 -m pytest tests -q -p no:randomly" echo "the Go port's own tests:" echo " go test ./... && go vet ./..." - echo "the conformance corpus against the Go server (the P1 gate):" + echo "the conformance corpus against the Go server:" echo " tests/conformance/run_go.sh" echo "and the leak gate, which must pass before any push:" echo " python3 tests/leakscan.py --self-test && python3 tests/leakscan.py" diff --git a/internal/envalias/envalias.go b/internal/envalias/envalias.go index c9969692..0c9ab28e 100644 --- a/internal/envalias/envalias.go +++ b/internal/envalias/envalias.go @@ -3,22 +3,24 @@ // renames: `SUBSYSTEM_STORE_*` → `CAIRN_*`, and `CAIRN_SUPABASE_*` → `CAIRN_OIDC_*` for // the JWT verifier's settings (see the section on it below). // -// 🔴 THERE ARE TWO SPELLINGS OF THIS LEDGER AND THAT IS PACKAGING, NOT DUPLICATION. -// `packages.cairn` installs the Python client script and `lib/` under `libexec` and -// nothing else, so the Python side CANNOT import a file under `internal/`. The second -// spelling is `lib/env_aliases.py`, and `tests/test_env_aliases.py` pins the two against -// each other — failing when the pair set GROWS *or* SHRINKS, and comparing the rendered -// warnings as WHOLE NORMALISED STRINGS rather than by keyword, because a guard on words -// is walkable by rewording. That two-spellings-plus-a-gate shape is the precedent -// `AGENTS.md` already blesses for `server/Dockerfile` against `flake.nix`'s `serverEnv`. +// 🔴 THIS IS THE ONLY SPELLING OF THE LEDGER NOW. Until the Python client was retired it +// had a twin, `lib/env_aliases.py` (that client could not import `internal/`), pinned +// against this file by `tests/test_env_aliases.py`. The twin went with the client; that +// test now pins THIS file's pair set, anchor and warning texts against literals. // // # What the window is anchored to // -// The old names keep working until the PYTHON CLIENT (`packages.cairn`) is retired — -// the arc's P8 milestone. That is an anchor a reader can CHECK: `packages.cairn` either -// exists in `flake.nix` or it does not. A date could not be checked, there is no semver -// here to hang it on (`flake.nix`: `version = self.shortRev`), and `tests/leakscan.py` -// refuses a dated stamp in this tree anyway. +// 🔴 THE FIRST ANCHOR IS MET, AND THE OLD NAMES STILL WORK — DELIBERATELY. The window was +// "until the Python client (`packages.cairn`) is retired", the arc's P8 milestone, and the +// change that retired that client did NOT also remove the aliases: removing them is a +// BREAKING change for every deployment still exporting a `SUBSYSTEM_STORE_*` or +// `CAIRN_SUPABASE_*` name, and it gets its own change, announced in `CHANGELOG.md`, so an +// operator can read it before it lands. So the anchor moved to that announcement — still a +// thing a reader can CHECK (the entry exists or it does not), never a date: there is no +// semver here to hang one on (`flake.nix`: `version = self.shortRev`), and +// `tests/leakscan.py` refuses a dated stamp in this tree anyway. The next step is that +// change: delete every `Pair` here, the `Deprecations`/`WarnOnce` call sites, and this +// package's warning texts, together, with the CHANGELOG row. // // # 🔴 TWO PAIRS ARE NOT THE MECHANICAL PREFIX SWAP, AND ONE OF THEM WAS A LIVE COLLISION // @@ -63,11 +65,11 @@ // that refusal into a working alias. // // 🔴 ONE `RemovalAnchor` FOR THE WHOLE LEDGER, WHICH IS A WIDER PROMISE THAN THE OIDC PAIRS -// NEED AND IS NOT A CLAIM THAT THE PYTHON CLIENT READS THEM. The anchor is a single -// constant, so those pairs inherit "until `packages.cairn` is retired" — a milestone that -// has nothing to do with a pod-side verifier. Per-pair anchors were the honest alternative -// and were DECLINED: they would change `Pair`, both warning formats, the Python twin and the -// cross-language gate, in order to SHORTEN a deprecation window nobody has asked to shorten. +// NEED. The anchor is a single constant, so those pairs inherit the same one. Per-pair +// anchors were the honest alternative and were DECLINED (when the anchor was still the +// Python client's retirement, a milestone unrelated to a pod-side verifier): they would +// change `Pair`, both warning formats and their pinning test, in order to SHORTEN a +// deprecation window nobody has asked to shorten. // The cost is a warning that names a milestone some readers will find unrelated; what it buys // is one window, one sentence, and no mechanism change. // @@ -110,7 +112,7 @@ // decides between them — and the image half is a DEFAULT that is present whether or not the // manifest mentions it. An image setting `CAIRN_STORE_ROOT` would therefore outrank a // Deployment that explicitly sets `SUBSYSTEM_STORE_ROOT`, and for those variables the old -// name would stop working the day the image shipped rather than at P8. +// name would stop working the day the image shipped rather than at the announced removal. // // The images used to answer that by staying on `SUBSYSTEM_STORE_*`. They now answer it by // setting NEITHER spelling: the three values they baked were byte-identical to the code @@ -118,8 +120,8 @@ // lines per pod start that no manifest could clear — rule 2 sweeps the whole environment and // does not care who put a variable there. With no image default there is nothing to // outrank a manifest in either direction, which closes this consequence at the root rather -// than deferring it to P8. `flake.nix`'s `serverEnv`, `server/Dockerfile` and -// `tests/test_flake_image_matches_dockerfile.py` carry the measurement; this note exists so +// than deferring it. `flake.nix`'s `serverEnv` and `tests/test_server_deployment_defaults.py` +// carry the measurement; this note exists so // a reader who arrives at rule 1 first does not "restore" an image default here. // // 🔴 ONE BEHAVIOUR CHANGE, AND IT IS AN AUTHORISED EXCEPTION TO "DO NOT CHANGE THE @@ -185,8 +187,9 @@ var Ledger = []Pair{ } // RemovalAnchor is WHEN the old names stop being read, in the only terms this repo can -// state it: a milestone a reader can check, never a date. -const RemovalAnchor = "the Python client (packages.cairn) is retired" +// state it: a milestone a reader can check, never a date. (It read "the Python client +// (packages.cairn) is retired" until that happened; see the package doc.) +const RemovalAnchor = "a release whose CHANGELOG.md entry announces their removal" // envWarningFormat and fileWarningFormat are the two pinned warning texts. // @@ -219,9 +222,9 @@ const RemovalAnchor = "the Python client (packages.cairn) is retired" // double the ways the two spellings can drift. // // 🔴 `tests/test_env_aliases.py` EXTRACTS THESE TWO CONSTANTS FROM THIS FILE BY TEXT and -// compares the rendered result against `lib/env_aliases.py`'s. Editing one of them alone -// is a red test, which is the whole reason they are named constants rather than inline -// format strings at the two call sites below. +// compares the rendered result against WHOLE LITERAL SENTENCES. Editing one is a red test, +// which is the point: they are printed to operators. (Until the Python client was retired +// the comparison was against `lib/env_aliases.py`'s rendering instead.) const ( envWarningFormat = "$%s is a deprecated alias for $%s. Where both are set in the " + "environment, $%s is the one that is read. Both are accepted until " + RemovalAnchor + "." @@ -264,9 +267,8 @@ var news = func() map[string]string { // down. See the seam paragraph in the package doc for why that package keeps its own // predicate rather than taking this one's. // -// `lib/env_aliases.py`'s `old_name` was public throughout: Python has no unexport, and the -// cross-language gate pins the LEDGER, the anchor and the warning text, not the function -// set, so the two spellings never had to match here. +// (The retired Python twin's `old_name` was public too; the gate that pinned the two +// spellings compared the LEDGER, the anchor and the warning text, not the function set.) func OldName(newName string) string { return news[newName] } // Value is the resolved value of `newName` over `env`: the new name if it is present and @@ -305,8 +307,8 @@ func ValueFrom(get func(string) string, newName string) string { // spellings. // // 🔴 IT IS A NAMED FUNCTION BECAUSE THE TWO HALVES OF THE RULE DISAGREED WHILE BOTH WERE -// SPELLED INLINE, AND THE DISAGREEMENT WAS INVISIBLE TO THE PARITY GATE BECAUSE -// `lib/env_aliases.py` HAD THE SAME ONE. `Deprecations` tested `TrimSpace(env[old]) != ""`; +// SPELLED INLINE, AND THE DISAGREEMENT WAS INVISIBLE TO THE (since retired) PARITY GATE +// BECAUSE THE PYTHON TWIN HAD THE SAME ONE. `Deprecations` tested `TrimSpace(env[old]) != ""`; // `ValueFrom` returned the old name's value raw. So `SUBSYSTEM_STORE_ROOT=" "` resolved to // `" "` — a pod would have taken a whitespace store root — and warned about nothing, while // the package doc said a blank value "changes no resolution, so it is not a deprecation". diff --git a/internal/envalias/envalias_test.go b/internal/envalias/envalias_test.go index e172168c..063f9b76 100644 --- a/internal/envalias/envalias_test.go +++ b/internal/envalias/envalias_test.go @@ -20,12 +20,11 @@ import ( // once-per-process rule — each of which is a property the parity harness can only observe // as "the bytes differed", after the fact and without saying which rule broke. // -// The behavioural claim — that the two languages emit the SAME BYTES in the SAME ORDER — -// is NOT made here and cannot be. `tests/test_env_aliases.py` pins the ledger and the -// warning TEXT across the two spellings; `tests/parity/harness.py` runs both real clients -// with a deprecated name exported and diffs their stderr byte-for-byte, which is the only -// instrument that can see a Go-side argument-ORDER mistake that still renders well-formed -// English. +// `tests/test_env_aliases.py` pins the ledger and the warning TEMPLATES against literals, +// reading this package as text. A Go-side argument-ORDER mistake that still renders +// well-formed English is invisible to a template read — it was caught by the retired parity +// harness diffing two real clients' stderr — so `TestTheRenderedWarningsAreTheWholeSentence` +// pins the RENDERED sentence for one pair, which is what an operator reads. func TestTheLedgerIsSortedByNewName(t *testing.T) { // 🔴 NOT COSMETIC. `Deprecations` sorts by new name so that two clients emitting the @@ -475,3 +474,21 @@ func TestTheScanIgnoresANestedCheckoutOfThisRepository(t *testing.T) { "a fact about the scan rather than about the tree.", old, len(offenders), offenders) } } + +func TestTheRenderedWarningsAreTheWholeSentence(t *testing.T) { + // 🔴 THE WHOLE NORMALISED STRING, NOT KEYWORDS: a guard on words is walkable by rewording, + // and an argument-order swap (`New, Old, Old`) renders well-formed English that a keyword + // guard and a template read both pass. The pair's two names are distinct, so every swap + // moves the sentence. + p := Pair{New: "CAIRN_URL", Old: "SUBSYSTEM_STORE_URL"} + if got, want := EnvWarning(p), "$SUBSYSTEM_STORE_URL is a deprecated alias for $CAIRN_URL. "+ + "Where both are set in the environment, $CAIRN_URL is the one that is read. Both are "+ + "accepted until a release whose CHANGELOG.md entry announces their removal."; got != want { + t.Fatalf("EnvWarning:\n got %q\nwant %q", got, want) + } + if got, want := FileWarning(p, "/x/config"), "SUBSYSTEM_STORE_URL in /x/config is a deprecated "+ + "alias for CAIRN_URL. Where both appear in that file, CAIRN_URL is the one that is read. "+ + "Both are accepted until a release whose CHANGELOG.md entry announces their removal."; got != want { + t.Fatalf("FileWarning:\n got %q\nwant %q", got, want) + } +} diff --git a/internal/report/reader_fixtures_test.go b/internal/report/reader_fixtures_test.go index d5983c26..600bc3dd 100644 --- a/internal/report/reader_fixtures_test.go +++ b/internal/report/reader_fixtures_test.go @@ -21,9 +21,16 @@ import ( // term, a `--max-hits` truncation, a malformed entry BESIDE readable ones, or a // `search-unreadable` scope. Every one is a branch here. // -// So the expectations are the ORACLE's own rendered bytes, generated by -// `tests/reader_fixtures.py` and replayed against this port. A hand-written expectation -// would assert what somebody believed the oracle does; these assert what it did. +// So the expectations are the ORACLE's own rendered bytes, recorded by the retired Python +// reader and replayed against this port. A hand-written expectation would assert what +// somebody believed the oracle does; these assert what it did. +// +// 🔴 THE FIXTURE IS NOW A FROZEN CONTRACT. The oracle was deleted, so nothing can regenerate +// `testdata/reader_fixtures.json`; it is frozen as recorded at +// ec1b756b15ea37469124c635d0d82f6e10d57899, the last commit that had the oracle — the same +// rule as `tests/conformance/README.md`'s frozen corpus. A renderer change that moves an +// expectation is a CONTRACT change, argued in review; never re-record it from this renderer, +// which would make the test agree with itself. // // 🔴 THE TWO THINGS THAT CANNOT BE COMPARED LITERALLY ARE PINNED RATHER THAN IGNORED. The // store path differs per run, so both sides substitute a placeholder for it; the host @@ -31,10 +38,10 @@ import ( // sides are handed the same synthetic literal. Nothing else is normalized — no header set, // no "ignore whitespace", no per-case exemptions. // -// ⚠ AND THE FIXTURE CANNOT GO STALE UNNOTICED: `tests/test_reader_fixtures.py` regenerates -// it and diffs against what is committed, so a reader change that moves the oracle's bytes -// fails there rather than leaving this test comparing against a snapshot of an older -// implementation. +// ⚠ IT CAN NO LONGER GO STALE IN THE OLD SENSE: there is no oracle left to drift from. Until +// the retirement, `tests/test_reader_fixtures.py` regenerated it from the oracle and diffed; +// that test now pins only that the committed file is the frozen one, and that its world is +// synthetic. type fixtureFile struct { Host string `json:"host"` diff --git a/internal/report/testdata/reader_fixtures.json b/internal/report/testdata/reader_fixtures.json index 9f982d7e..f97f7d2f 100644 --- a/internal/report/testdata/reader_fixtures.json +++ b/internal/report/testdata/reader_fixtures.json @@ -1,15 +1,14 @@ { "_comment": [ - "GENERATED BY tests/reader_fixtures.py -- DO NOT EDIT.", + "FROZEN CONTRACT -- DO NOT EDIT. Recorded by the retired Python oracle's reader, frozen", + "at ec1b756b15ea37469124c635d0d82f6e10d57899 (the last commit that had the oracle).", "", - "Every `expect` below is the ORACLE's own rendered bytes, so the Go test that", - "replays this file is a DIFFERENTIAL measurement against the implementation it", - "is a port of. The shapes here are the ones the HTTP conformance corpus cannot", - "send; see the module docstring for the list.", - "", - "Regenerate with `python3 tests/reader_fixtures.py generate`.", - "`tests/test_reader_fixtures.py` regenerates and diffs, so a stale fixture is a", - "test failure rather than a silently weaker comparison." + "Every `expect` below is the ORACLE's own rendered bytes over the synthetic world in", + "`scopes`/`entries`, so the Go test that replays this file measures the renderer", + "against the implementation it was ported from. The shapes here are the ones the HTTP", + "conformance corpus cannot send. Nothing can regenerate them now; a renderer change", + "that moves one is a contract change, argued in review, never a regeneration.", + "`tests/reader_fixtures.py build-store` materialises the world for uiaudit." ], "host": "fixture-host-000000000000", "store_placeholder": "", diff --git a/internal/store/citationid_test.go b/internal/store/citationid_test.go index 38a8bd54..216a693a 100644 --- a/internal/store/citationid_test.go +++ b/internal/store/citationid_test.go @@ -8,24 +8,21 @@ import ( "testing" ) -// The citation-id seam, replayed against the PYTHON implementation's answers. +// The citation id, replayed against a FROZEN CONTRACT. // -// WHAT IT MEASURES. `JournalBullet.CitationID` exists twice — here and in -// `lib/subsystem_resolver.py` — because `packages.cairn` installs the Python client and -// its `lib/` under `libexec` and nothing else, so `lib/` CANNOT import `internal/`. -// That is packaging, not a choice anyone may undo here, and it is the shape `AGENTS.md` -// already blesses for `server/Dockerfile` against `flake.nix`'s `serverEnv`. -// -// Two independent implementations of a hash must agree FOREVER or the id stops being a -// shared name for a bullet and silently becomes two. Nothing about that agreement is -// checked by a compiler, and it cannot be checked by reading either source: the only -// instrument is running both over the same bodies and comparing strings. -// -// 🔴 THE FIXTURE IS THE ORACLE'S OUTPUT, NOT A SNAPSHOT OF THIS PACKAGE. It records what -// CPython answers, so nothing here can agree with itself. `tests/citation_ids.py` writes -// it and `tests/test_citation_ids.py` REGENERATES it from the live Python -// implementation on every pytest run, so the fixture cannot drift away from the code it -// claims to record — the same two-sided arrangement `markersweep_test.go` uses. +// 🔴 OPTION (a) OF THE RETIREMENT LEDGER WAS TAKEN: KEEP THE FIXTURE, RELABEL IT. The fixture +// `testdata/citation_ids.json` was generated from the PYTHON implementation of `citation_id` +// (`lib/subsystem_resolver.py`, by `tests/citation_ids.py`) while that twin existed — the +// retired Python client could not import `internal/` — and this test was the differential +// that kept the two equal. The Python client and its generator are retired. The fixture is +// therefore NOT a snapshot of this package and NOT an oracle any more: it is a FROZEN +// CONTRACT, recorded by CPython and frozen at ec1b756b15ea37469124c635d0d82f6e10d57899 (the +// last commit that had the generator; the file was last regenerated at d7e1fec). Every id +// ever printed into a report (` [cb:]`) is a name an agent may hand back later; if the +// derivation moves, those names stop resolving, and this test is what makes that red. +// `tests/test_citation_ids.py` pins the fixture's bytes, so it cannot be "fixed" by +// regenerating it from this package — that would be (c), a self-snapshot, and was declined; +// (b), deleting it, was declined because then only a consumer printing an id would notice. // // 🔴 AND IT COMPARES THE DECODE, NOT ONLY THE HASH. Each case carries the entry BYTES as // hex beside their `errors="replace"` decode, and this side decodes the hex with @@ -35,15 +32,9 @@ import ( // CPython emits one per maximal SUBPART, so one entry file produced two citation ids. // // ⚠ WHAT IT CANNOT SEE. The bodies are hand-written, so this says nothing about the LIVE -// corpus, and nothing about RENDERING. ⚠ THE SECOND HALF OF THAT SENTENCE USED TO READ "no -// surface prints an id yet", AND THAT IS NO LONGER TRUE: both text renderers now append -// ` [cb:]` to every surfaced section line that opens a bullet, so a rendered byte -// depends on this function. What measures that is still not here — -// `internal/report/testdata/reader_fixtures.json` compares the two renderers' bytes (138 -// of its lines carry a token), `internal/report/citationtoken_test.go` pins the POSITION -// and the verbatim body, and `tests/parity/harness.py` compares the two real clients. Said -// here rather than left to be discovered, because a reader who took this file for full -// coverage would stop looking. +// corpus, and nothing about RENDERING: `internal/report/citationtoken_test.go` pins the +// POSITION and the verbatim body, and the frozen `internal/report/testdata/ +// reader_fixtures.json` holds rendered bytes carrying tokens. type citationCase struct { Name string `json:"name"` @@ -96,7 +87,7 @@ func loadCitationFixture(t *testing.T) citationFixture { return fx } -func TestTheCitationIDAgreesWithThePythonOracle(t *testing.T) { +func TestTheCitationIDAgreesWithTheFrozenPythonContract(t *testing.T) { fx := loadCitationFixture(t) compared := 0 decoded := 0 diff --git a/internal/store/marker.go b/internal/store/marker.go index 48be3546..836b2d8a 100644 --- a/internal/store/marker.go +++ b/internal/store/marker.go @@ -166,10 +166,10 @@ func LineOpenness(line string) (openness, resolvedBy string) { // "the sweep below reports 0 divergences across all three populations" and there was no // sweep below — not in this file, not anywhere in the tree, and the figures it quoted // were unreproducible. The sweep is now -// `internal/store/markersweep_test.go`, over the corpus `tests/marker_corpus.py` -// generates and `internal/store/testdata/marker_oracle_sweep.json` carries; the -// oracle's side of it is re-derived from the LIVE patterns by -// `tests/test_marker_oracle_sweep.py` on every pytest run. +// `internal/store/markersweep_test.go`, over the corpus whose axes and CPython verdicts +// `internal/store/testdata/marker_oracle_sweep.json` carries — FROZEN since the Python +// reader that produced the verdicts was retired (it was re-derived from the live patterns +// on every pytest run until then). // // So, MECHANICALLY: widen `hasFoldedPrefix` to fold the four runes `foldsToASCIILetter` // names — `unicode.SimpleFold` alone will NOT do it, U+0130 and U+0131 have no simple diff --git a/internal/store/markersweep_test.go b/internal/store/markersweep_test.go index d3f4436a..82357d51 100644 --- a/internal/store/markersweep_test.go +++ b/internal/store/markersweep_test.go @@ -27,10 +27,13 @@ import ( // HOW THE ORACLE'S ANSWERS GET HERE. `internal/store/testdata/marker_oracle_sweep.json` // carries // the corpus AXES, the SHA-256 of the assembled corpus and the oracle's verdicts as two -// bit-strings. `tests/marker_corpus.py` writes it and `tests/test_marker_oracle_sweep.py` -// re-derives every one of those verdicts from the LIVE `lib/subsystem_resolver` patterns -// on every pytest run — so the fixture cannot drift away from the regexes it claims to -// record. This side assembles the SAME corpus from the SAME axes and checks the SHA-256 +// bit-strings. 🔴 IT IS A FROZEN CONTRACT NOW: it was written by `tests/marker_corpus.py` +// from the retired Python reader's patterns (and re-derived from them on every pytest run +// while they existed); both went with the Python client, and the fixture is frozen as it +// stood at ec1b756b15ea37469124c635d0d82f6e10d57899. The verdicts are still CPython's +// answers, which is what a hand-rolled transcription of a CPython regex must keep +// matching — so a mismatch here is a narrowing in THIS package, never a reason to +// re-record the fixture from it. This side assembles the SAME corpus from the SAME axes and checks the SHA-256 // before reading a single verdict: two assemblers in two languages is the seam that // drifts silently, and without the hash a comfortable zero here would be a zero over a // corpus the Python side never saw. @@ -55,7 +58,8 @@ type markerSweepFixture struct { } // loadMarkerSweep reads the fixture and rebuilds the corpus from its axes, in the ONE -// order `tests/marker_corpus.py` documents. The nesting is load-bearing: change it and +// order the retired Python generator (`tests/marker_corpus.py`, deleted with the client; +// read it at ec1b756) assembled it in. The nesting is load-bearing: change it and // the SHA-256 check below fires, which is the point of having one. func loadMarkerSweep(t *testing.T) (markerSweepFixture, []string) { t.Helper() @@ -93,7 +97,7 @@ func loadMarkerSweep(t *testing.T) (markerSweepFixture, []string) { " go sha256 %s over %d lines\n"+ " python sha256 %s over %d lines\n"+ "Every verdict below would then be compared against lines nobody ran. "+ - "Re-read the assembly order in tests/marker_corpus.py.", + "Re-read the assembly order in tests/marker_corpus.py at ec1b756.", got, len(lines), fx.CorpusSHA256, fx.CorpusLines) } if len(fx.Anywhere) != len(lines) || len(fx.NearMiss) != len(lines) { @@ -206,8 +210,8 @@ func hasFoldingRune(line string) bool { // over-guarding is never another guard, and its unique coverage was six mutations that // are inert by construction. What it did NOT uniquely cover, and what still guards every // consequential case: a fifth folding rune, or a moved target, fails -// `tests/test_marker_oracle_sweep.py::test_the_re_I_folding_runes_are_exactly_the_four_ -// the_code_names`, which sweeps the whole codepoint space; the U+017F entry — the only +// `tests/test_cpython_re_folding_runes.py::test_the_re_I_folding_runes_are_exactly_the_four_ +// the_code_names`, which sweeps the whole codepoint space against CPython's `re.I`; the U+017F entry — the only // reachable one — fails the Go sweep in this file; and the PRODUCTION enumeration // `foldsToASCIILetter` is killed on all four runes by that same sweep. #109's own F2 // body offers this paragraph as the sufficient alternative ("state plainly that three @@ -301,7 +305,7 @@ func reIFoldedPrefix(rs []rune, want string) bool { // divergence whose only cause WAS the declared fold stopped vanishing and got reported as // `1 divergence(s) outside the ONE declared residual` — a false alarm on the one clause // that exists to catch a real narrowing. MEASURED on `- Reſolved ſ: …`, now a corpus row -// (`tests/marker_corpus.py`): oracle True, walk false, whole-line respelling false, +// (in the frozen fixture's axes): oracle True, walk false, whole-line respelling false, // attributed UNDECLARED, the Go sweep RED. No row of that shape existed before, which is // why `210 / 0` held over a broken attribution. // diff --git a/internal/store/openness.go b/internal/store/openness.go index 242eb386..2505f3ab 100644 --- a/internal/store/openness.go +++ b/internal/store/openness.go @@ -284,8 +284,8 @@ func hasFoldedPrefix(rs []rune, want string) bool { // corpus, while the comment one function over read as though it were closed. Read a // convergence claim as being about the RUN it was measured on, never about a caller. // -// The ledger, measured by `internal/store/markersweep_test.go` over the corpus -// `tests/marker_corpus.py` generates: +// The ledger, measured by `internal/store/markersweep_test.go` over the frozen corpus in +// `testdata/marker_oracle_sweep.json`: // // `\d` in the date prefix (`looksISODate`) CLOSED — `unicode.IsDigit` // `\d` in the ref atoms (`refAtomEnds`) CLOSED — `unicode.IsDigit` diff --git a/internal/write/tagvocab.go b/internal/write/tagvocab.go index ee406e55..ac3c66ad 100644 --- a/internal/write/tagvocab.go +++ b/internal/write/tagvocab.go @@ -35,15 +35,13 @@ import "slices" // later edit can wire into `parseTagsField`, and the refusal that edit produces is the // outage above. It is also unexported, so no consumer of this package can grow a second // copy of the check — `internal/client` imports `write.BulletTextMax` and could -// otherwise have grown a client-side pre-check, which `tests/parity/` would then need -// in BOTH clients to stay green. +// otherwise have grown a client-side pre-check, a second spelling of the refusal. // // ⚠ SORTED, AND THAT IS PART OF THE REFUSAL'S CONTRACT RATHER THAN TIDINESS. The -// refusal message joins this slice with `|`; `lib/entry_shape.py`'s `TAG_VOCABULARY` -// joins its own tuple the same way; `tests/conformance/` compares the two servers' -// response bytes for a `PUT` carrying an off-vocabulary tag. Reordering or extending -// one side alone is a RED corpus, not a review comment — -// `tests/test_tag_vocabulary.py` is the cheaper red that says which side moved. +// refusal message joins this slice with `|`, and `tests/conformance/` replays a `PUT` +// carrying an off-vocabulary tag against its frozen golden (recorded from the retired +// Python oracle, which joined its own copy the same way). Reordering or extending it is a +// RED corpus, not a review comment — `tests/test_tag_vocabulary.py` is the cheaper red. // // ⚠ AND THE BROWSER IS NOT A WRITER, WHICH IS WHY NO BROWSER-SIDE GATE EXISTS. Measured // rather than assumed: every state-changing route in `internal/ui/routes.go`'s dispatch diff --git a/internal/write/tagvocab_test.go b/internal/write/tagvocab_test.go index e9188368..0ece0419 100644 --- a/internal/write/tagvocab_test.go +++ b/internal/write/tagvocab_test.go @@ -40,7 +40,7 @@ func taggedEntry(tagsFlow string) string { // 🔴 A LITERAL, BECAUSE AN EXPECTATION DERIVED FROM THE IMPLEMENTATION ASSERTS NOTHING. // Interpolating `strings.Join(tagVocabulary, "|")` here would make this test pass under // a mutant that reorders the vocabulary, drops a term, or changes the separator — the -// exact three edits the conformance corpus would then catch on the oracle instead, one +// exact three edits the conformance corpus would then catch against its frozen goldens, one // gate and several minutes later. const wantRefusal = "tag 'marketing' is not one of infra|product|tooling — " + "the tag vocabulary is CLOSED on the WRITE path, so widening it is a code change. " + @@ -293,12 +293,10 @@ func TestAppendingToAnEntryCarryingAnOffVocabularyTagStillWorks(t *testing.T) { // TestTheVocabularyIsExactlyTheDeclaredThreeTerms pins the set and its ORDER. // // 🔴 THE ORDER IS PART OF THE WIRE CONTRACT, NOT TIDINESS. The refusal joins this slice -// with `|`, the oracle joins its own tuple the same way, and `tests/conformance/` -// compares the two servers' bytes. +// with `|`, and `tests/conformance/` replays it against a frozen golden. // // ⚠ AN INVARIANT GUARD, NOT REGRESSION COVERAGE: no defect ever reordered this slice. -// It is here so a term added on one side alone is red in this package rather than three -// gates away. +// It is here so a term added is red in this package rather than three gates away. // // 🔴 IT DELIBERATELY DOES **NOT** ALSO ASSERT SORTEDNESS AND UNIQUENESS, AND DELETING // THOSE TWO ASSERTIONS IS THE POINT RATHER THAN A TRIM. They stood here for one round @@ -315,8 +313,8 @@ func TestTheVocabularyIsExactlyTheDeclaredThreeTerms(t *testing.T) { want := []string{"infra", "product", "tooling"} if !slices.Equal(tagVocabulary, want) { t.Fatalf("tagVocabulary=%q, want %q — if a term was added or removed on purpose, "+ - "move `lib/entry_shape.py`'s TAG_VOCABULARY in the same commit, regenerate the "+ - "`tests/conformance/` goldens, and move the other hand-typed expectations "+ + "argue the contract change against the frozen `tests/conformance/` goldens, and "+ + "move the other hand-typed expectations "+ "`README.md` enumerates — this literal is only one of them", tagVocabulary, want) } } diff --git a/lib/README.md b/lib/README.md deleted file mode 100644 index 40842e08..00000000 --- a/lib/README.md +++ /dev/null @@ -1,295 +0,0 @@ -# `lib/` — the reader, and where a scope LIVES - -The Python client's library half: cache resolution, recall and search rendering, scope and ref -resolution, `doctor`, and the multi-instance routing this file exists for. - -🔴 **THIS FILE IS THE EVICTION TARGET FOR ROUTING, AND THAT IS WHY IT EXISTS.** `AGENTS.md` is -loaded by every session in this repository before any work starts — it is measured and ceilinged -by `tests/test_agent_instructions_weight.py` — so a rule that binds only the people editing -`lib/cairn_instances.py`, `cairn`'s routing helpers and `internal/client/instances.go` is paid by -everyone and read by almost nobody. It lives here, where it costs nothing until somebody opens it, -and `AGENTS.md` carries one line pointing at it. **Moved, not deleted: every claim below was in -`AGENTS.md` and is reproduced verbatim.** - -## 🔴 THE CLIENT CAN BE POINTED AT SEVERAL INSTANCES, AND AN UNROUTED SCOPE REFUSES - -`lib/cairn_instances.py` owns three questions: what is configured, which -instance a scope belongs to, and whether the two agree. The rules that bind -anyone editing that path: - -- **The routing table is an INPUT, never a constant here.** A scope→alias map - lives in the operator's own configuration (`~/.config/subsystem-store/routes.json` - or `$CAIRN_ROUTES`). This repository is public: shipping a table would publish - somebody's taxonomy. Aliases only — never a hostname — in anything this repo - reads, prints or stores. -- **An unregistered scope REFUSES (exit 11) and names the scope — once there is - more than one instance to choose between.** No fallback to the default - instance, the first instance, or the one that answers. The failure a default - recreates is a write landing in a store nobody reads, which is found days - later by accident if at all. -- 🔴 **"IS THIS HOST ROUTING?" IS TWO QUESTIONS, AND COLLAPSING THEM INTO ONE - BOOLEAN IS A MEASURED DEFECT.** `Routing.multi_instance` (`len(instances) > 1`) - decides what is LABELLED — the banner label, the write label, `doctor`'s - per-instance rows, `ls-entries`' prefix, the `--all-scopes` fan-out and the - caveat's extra clause all ask it, so they cannot disagree. `Routing.alias_for` - decides WHERE a scope lives, and it consults the TABLE first, whatever the - instance count is. Three rows share one configuration — **one instance with a - table present**, which is what an operator has the moment they write their - first table — and two of them need opposite answers: - - | table state for this scope | `routes is not None or len>1` | `len>1` alone | correct | - |---|---|---|---| - | no table at all | sole instance | sole instance | sole instance | - | a table, scope ABSENT from it | **REFUSE** | sole instance | sole instance | - | a table entry naming an UNCONFIGURED alias | REFUSE | **sole instance** | REFUSE | - - Column 2 was shipped: a table's presence switched labelling on, so every - recall on a one-instance host asserted *"with more than one instance - configured…"* — false on that host, on every call — and every scope not yet in - the table refused at exit 11. Column 3 is the obvious fix and it opens a - **silent misroute**: a write landing in a store nobody decided on. Do not - re-collapse these; the table above is reproduced at `Routing.alias_for` and - guarded by `TestOneInstanceWithATablePresent`. -- **One rule, one place: `Routing.check` asks `Routing.alias_for`.** The grader's - "the table names an alias no instance provides" finding, and its "a write to - it will REFUSE" finding, are both predictions about what the resolver does — - so they ask it rather than re-deriving from the same two inputs. That is also - what keeps the grader honest on a one-instance host, where an unnamed scope - does *not* refuse. -- **The default instance's cache root does not move.** `cache_root_for` returns - `DEFAULT_CACHE_ROOT` unchanged for `personal` and a SIBLING directory for every - other alias. A child directory would look exactly like a SCOPE to every reader - that enumerates `/`. -- 🔴 **`STORE_IS_PER_HOST` IS BYTE-MIRRORED INTO TENS OF TRACKED FILES, NOT FOUR - PLACES.** The kinds are what matter and they are stable — - `internal/hostid/hostid.go`, - `internal/report/testdata/reader_fixtures.json` (the bulk of them), **20 of the - 98** `tests/conformance/golden/*.json` (24), `lib/entry_shape.py`, - `server/README.md` and `tests/test_subsystem_recall.py`. Two are - regenerate-and-diff gates; `server/README.md` is prose no gate covers. That is - why the multi-instance caveat is a clause `entry_shape.store_caveat` ADDS at - render time rather than an edit to the constant. ⚠ **The earliest wording here - was "a four-place change", wrong by 2× in the direction that makes the edit - look cheap** — it counted mirror KINDS and read as a count of SITES. - - 🔴 **AND THE TOTALS THAT REPLACED IT WENT STALE TOO, WHICH IS WHY NO TOTAL IS - QUOTED HERE ANY MORE.** This bullet carried "25 files, 92 occurrences"; measured - later, the tree held **29 and 105**. The prose even named the wrong cause — it - said the number moves when a golden is regenerated, and the golden figures above - are still exact to the file; what moved was the **reader fixture**. A count that - drifts and explains its own drift wrongly is worse than no count, because it - reads as maintained. Re-derive when you need a total, and do not write the answer - down: - - ```bash - python3 - <<'PY' - import pathlib, subprocess, sys - sys.path.insert(0, "lib") - from entry_shape import STORE_IS_PER_HOST # the needle, never a literal - files = subprocess.run(["git", "ls-files"], capture_output=True, - text=True, check=True).stdout.split() - hits = {f: pathlib.Path(f).read_text(errors="replace").count(STORE_IS_PER_HOST) - for f in files if pathlib.Path(f).is_file()} - hits = {f: n for f, n in hits.items() if n} - print(len(hits), "files,", sum(hits.values()), "occurrences") - PY - ``` - - 🔴 **THE NEEDLE IS IMPORTED, NOT SPELLED, AND THAT IS THE WHOLE POINT.** The - recipe this replaces grepped the 14-character fragment `PER-HOST CACHE` out of a - ~130-character constant. Reword the constant anywhere outside that fragment and - the count does not move; reword the fragment itself and the count collapses - toward zero — which reads as *few mirrors, cheap edit*, the exact direction this - bullet already records being wrong in once. Importing the constant means the - needle changes when the mirrored text does. - - ⚠ **THE IMPORTED VERSION ALSO PRINTS ZERO WHEN YOU REWORD THE CONSTANT, AND - THERE ZERO IS THE ANSWER YOU WANT** — measured: rewording one word of - `STORE_IS_PER_HOST` takes the count from 22/96 to **0/0**, because every mirror - still holds the old text. That is the tree telling you what the edit costs. The - fragment grep answered the same edit by drifting quietly from 92 to 105. - - ⚠ **ITS LIMIT, SO NOBODY READS IT AS EXHAUSTIVE:** it is an exact-substring - count, so it undercounts any site that WRAPS the constant across lines or escapes - it. That is a narrower blindness than the fragment grep's, not the absence of - one. -- **A read is labelled only when there is more than one instance; a WRITE names - its instance always.** "Where did that bullet go" is a question about a durable - record, asked later, by someone who no longer has the terminal. -- **Two harnesses carry the claims a suite cannot make, and they are RUNNABLE rather than - written down.** `tests/unchanged_output_capture.py` runs six READ shapes and three WRITE - shapes against TWO TREES — `origin/main` and this one — in BOTH configurations (no table, and - a table present on a one-instance host) and diffs the bytes. `tests/routing_mutants.py` breaks - each routing guard on purpose and requires each mutant to die **to its own test's name** - (`kills`), with a deliberately-fatal row as its positive control and a - `PYTHONDONTWRITEBYTECODE=1` + `__pycache__` sweep so a same-length edit cannot be scored - SURVIVED without having run. - 🔴 **AND IT REFUSES (exit 2) WHEN A RUN COLLECTED ZERO TESTS, which it did not until the - round-2 audit read the variable that was measuring it.** `run_suites` computed `collected` - and `main` never looked, so a shell without pytest produced no `FAILED` lines, - `failing_tests` returned `[]`, and the `positive-control` row — which declares no `kills` — - was scored `KILLED … by []` at **rc 0**: a fully green battery over nothing. Measured on a - pytest-less interpreter: `KILLED positive-control by []` / `killed=1` / rc 0 before, and - `REFUSING TO VOUCH … ran ZERO tests` / rc 2 after. The Go arm counts its own result lines for - the same reason. - 🔴 **AND THE PARENTHESIS THAT USED TO END THAT SENTENCE IS RETRACTED: "there it reported - `KILLED-BY-THE-WRONG-TEST`, which blames a guard for a missing runner".** Measured with `go` - absent, both before and after the count was added: `subprocess.run(["go", …])` raises - `FileNotFoundError`, so the battery never reaches the count, never reaches a verdict, and - printed a traceback at **exit 1** — which is also its "a mutant SURVIVED" code, leaving a - missing toolchain indistinguishable from a finding. The count was the right fix for the - case it covers (a runner that IS present and reports nothing) and was never the fix for - this one. It is closed separately: `_run` raises `ToolchainMissing` and `main` refuses at - **exit 2**, the same "could not vouch" the zero-collected case makes. ⚠ Nothing in - `.github/` or `flake.nix` runs this battery, so neither state was ever a CI hole. - ⚠ **THE CAPTURE HAS BEEN BLIND TWICE, IN THE SAME SHAPE, AND BOTH ARE WORTH KNOWING.** Its - first version ran only the no-table configuration — the one state in which the old predicate - was `False` by construction — so it measured green over the defect above; re-run it with - `--base 2301876` — this branch's first commit — to watch it report the 77 diff lines it - could not see. ⚠ A SHA in prose is rebase-fragile: that reference has been rewritten - twice by rebases onto a moving `main`, so if it does not resolve, use the commit whose - subject is "route a scope to an INSTANCE, and refuse when nobody said which". Its second version ran - only READS, so it could not see that `append`/`put`/`create` print `instance=personal` - unconditionally — which is the one place a one-instance host's bytes really did move, and - `README.md` was promising they had not. - 🔴 **SO IT CARRIES ONE POSITIVE CONTROL PER HALF, AND REFUSES (exit 2) IF EITHER FAILS TO - MOVE.** A control licenses a conclusion about the dimension it was built to test and not a - neighbouring one: the caveat perturbation moves every read and NO write, because a write - prints no caveat. The write half's control is a one-character edit to `DEFAULT_ALIAS`, which - is the value the `instance=` field carries. A write shape that exits non-zero also refuses to - vouch — a refused write never reaches the `instance=` line, so it would contribute a - reassuring "identical" while measuring nothing. -- ⚠ **EVERY VERB OF THE GO CLIENT ROUTES, AND THIS BULLET HAS BEEN WRONG TWICE — - SO IT STATES THE MECHANISM RATHER THAN A STATUS.** It first read "what it does - **not** do is consult the table on `recall`/`search`/`append`/`put`/`create`", - which was false of the three write verbs on the commit that introduced it; it - then read that the read verbs refused a multi-instance host outright, which - stopped being true when declared difference 8 closed. What is true: - - `cmd/cairn` declares `routes` and `EXIT_UNROUTED = 11` and implements both — - the ledgers and the parity gate would otherwise be green over a client that - had silently lost a verb and a code. - - `append`, `put` and `create` consult the table and **always print the - alias**: `writeInstance` calls `Routing.AliasFor`, loads the ROUTED - instance's credentials, syncs the ROUTED instance's cache (which is what - `put` derives its `If-Match` from) and prints `instance=` at one - instance and at many. A durable record is read later, by someone who no - longer has the terminal. - - `recall`/`search` and `validate` consult it too, and `sync`, `ls-entries` - and `doctor` route NOTHING so they walk EVERY configured instance. ⚠ Not - because none of them takes a scope — only `doctor` has no `--scope`; - `sync` and `ls-entries` declare one and pass `scope=""` regardless. All six - print the alias — in the banner, in the caveat's multi-instance clause, as - `ls-entries`' `[alias] ` line prefix, and as `doctor`'s `/` - **row names**, which is the one of the four a machine consumer of - `doctor --json` parses — **only when more than one instance is configured**. - That emptiness is the compatibility guarantee: a one-instance host's bytes - are unchanged, which the reader fixture measures (regenerating with the - clause added 225 lines and changed none). - - 🔴 **AND THAT GUARANTEE IS ABOUT *LABELLING*, NOT ABOUT *ROUTING* — the - sentence above is echoed at SEVERAL sites, and the number is deliberately - not written here — `tests/test_narrowing_echo_sites.py` holds the set.** They - are: here, `internal/client/instances.go`, `tests/parity/README.md`, `cairn`'s - `_instance_for` docstring, `internal/client/routes.go`'s `readInstance`, - `internal/client/state.go`'s `BannerNamed`, `tests/test_cairn_instances.py`, - and `tests/unchanged_output_capture.py`, the harness that measures the claim. - Every one of them reads wider than it is, and every one carries this - narrowing. ✅ **THE SET IS NOW ASSERTED, AND THE RE-COUNT RECIPE THAT STOOD - HERE IS DELETED RATHER THAN CORRECTED** — it matched two literal phrases, so - it could not see a REWORDED echo, which is what #48's ladder filed against it. - The ledger fails on GROW *or* SHRINK, and matches over whitespace-NORMALISED - text because this file states the claim across a line break and the old - line-based recipe therefore missed the very file it was written in. Do not - re-add a recipe here: a second, weaker instrument beside the assertion is how - the count went stale the first time. - ⚠ **AND THE TOTAL IS DELIBERATELY ABSENT, BECAUSE FOUR DRAFTS OF IT WERE - WRONG** — "all three", then "FIVE", then six, then seven. The ledger's GROW arm - caught one of those **in the same PR that added the ledger**; two audits caught - two more, both sites phrased differently from birth and therefore invisible to - the first version's spellings. A list a guard asserts cannot drift; a total in - prose always has. - The - scope-taking reads did not consult the table at all before; - they do now, and `alias_for` row 3 REFUSES at ONE instance as well as at - many. So exactly one single-instance case moved: a host whose table routes - the scope to an alias it has no config for — a stale or typo'd entry, the - case `routes --check` exists to find. Measured over one world with the - packaged Go client and `routes.json = {"alpha-notes": "nowhere"}`: - `recall`, `search` and `validate` each answered **exit 0**, off the default - instance's cache, at `d8b858a`, and each answers **exit 11, refusing**, at - HEAD. HEAD is the right - answer — the old one read a store the table said was elsewhere — but it is - a behaviour change on a one-instance host. 🔴 **This used to add "and it - belongs in whatever announcement the `packages.default` flip carries", and - that clause is RETRACTED by measurement**: it is a change to the GO client, - not to the DEFAULT — the default was the Python oracle, this routing was - ported FROM the oracle, and both packaged clients now exit 11 on all three - verbs over the same world, so the flip changes nothing here. `README.md`'s - announcement **drops** it — this bullet once said it *recorded* it, and the - draft paragraph was cut: a consumer cannot act on a non-change. The record - is here, on `internal/client/instances.go`'s header and in - `tests/parity/README.md`. `sync`, `ls-entries` and - `doctor` route NOTHING, so none of it reaches them. - - 🔴 **AND THAT LAST CLAUSE USED TO READ "take no scope, so none of it - reaches them", WHICH `--help` FALSIFIES FOR TWO OF THE THREE.** `cairn - sync` and `cairn ls-entries` both declare `--scope`; only `doctor` has - none. What makes them untouched is that they pass `scope=""` and fan out - over every instance, not that there is no scope to route. Re-measured over - the same `{"alpha-notes": "nowhere"}` world: `sync --scope alpha-notes` - exits 4 and `ls-entries --scope alpha-notes` exits 0 on BOTH clients, - byte-identical to the unscoped runs — the CONCLUSION stands and only the - reason moved. The reason is load-bearing: a later change that routed - `ls-entries --scope` through `alias_for` would falsify the conclusion while - the old reason still read as covering it. - - 🔴 `routes` reports rather than routes, and it must keep working before any - table is right: it is the verb an operator runs *while standing up* a second - instance. -- 🔴 **`routes --check` MUST THREAD THE ALIAS INTO THE STATE RESOLVER, NOT JUST THE - CACHE PATH.** `resolve_state`/`ResolveState` FETCHES as well as unpacks, so a - caller that hands it instance `N`'s cache root while it loads the DEFAULT - instance's credentials fetches `personal` N times and unpacks it over every - other instance's cache — the exact damage the sibling-directory layout exists to - prevent, arriving through the code path instead of through `--cache`. The - grader then reads one store's scope set and reports the others' scopes as - missing. Measured on a two-instance host before the fix: `cairn[secondary]` - banner naming `personal`'s URL, `secondary`'s cache holding `personal`'s - scopes, and a false "exists on no configured instance" at exit 11. -- 🔴 **DIRECTION TWO OF `Routing.check` IS A NOTE, NOT A VERDICT.** It subtracts the - cache's DIRECTORY LISTING from the table's keys, and a snapshot ships entry - FILES — so a scope holding no entries is missing from that set whether it is - stale, pre-registered before its first write, or pruned back to empty. Grading - it at exit 11 made the check refuse exactly the two-way-pinned registry it - exists to be, and the remedy its wording implied — delete the line — makes the - next write to that scope REFUSE. The discriminator exists and is simply not in - the snapshot (the server answers `scope-empty` vs `scope-absent` on - `GET /api/v1/recall/`); promoting it back is gated on probing the ROUTED - instance per table entry, identically in both clients, with a parity row. -- 🔴 **NAME RULES ARE SEPARATE FROM TYPE RULES IN `instances/`.** A file whose name - begins with **`.#`** is skipped rather than refused. Emacs' lock file for - `secondary.env` is `.#secondary.env` — it ends in `.env`, its stem is not a - usable alias, and it is a dangling symlink — so it reached the hard - `RoutingConfigError` and took **every** verb on that host to exit 11 while one - buffer was open. The refusal's stated intent ("a file the operator wrote and - would otherwise get no message about") is untouched: any other file that - cannot be an alias is still an error. - 🔴 **`.#`, AND THE FIRST CUT WAS `.` — WHICH WAS WIDER THAN ITS OWN STATED - RATIONALE AND OPENED THE HOLE THE REFUSAL EXISTS FOR.** `instances/.env` is a - dotted name, so it was skipped; its stem is the EMPTY string, so it is exactly - the file the refusal would otherwise name. Measured with a complete, valid - `instances/.env` on both clients: **before, `instances: personal` at exit 0 - with no message at all; after, exit 11 naming the file.** Parity held in both - directions, so no gate could see it — the two clients agreed on being wrong. - `.#` is the only in-suffix name a TOOL writes: a vim swapfile is - `.secondary.env.swp` and an Emacs autosave is `#secondary.env#`, and both fail - the `.env` suffix test before the name test is reached. So every other dotted - name is one a human could have chosen, and stays an error. ⚠ **The `internal/snapshot` - and `doctor` scanners skip EVERY dotfile, and that asymmetry is correct rather - than drift**: there is no operator-wrote-this refusal on those paths to leave a - dotted name silently unread, so a wide skip costs nothing there and costs the - whole refusal here. Do not "unify" them. ⚠ Both arms are - pinned in both languages — the skip arm alone passes while the hole is open — - by `test_an_EDITOR_LOCK_FILE_does_not_take_every_verb_to_exit_11` / - `test_a_DOTTED_file_that_is_not_an_editor_lock_is_STILL_an_ERROR` and - `TestAnEDITORLockFileDoesNotTakeEveryVerbToExit11` / - `TestADottedFileThatIsNotAnEditorLockIsStillAnError`, with a mutant per - direction per client in `tests/routing_mutants.py`. - diff --git a/lib/cairn_doctor.py b/lib/cairn_doctor.py deleted file mode 100644 index d55112de..00000000 --- a/lib/cairn_doctor.py +++ /dev/null @@ -1,709 +0,0 @@ -#!/usr/bin/env python3 -"""`cairn doctor` — one call that answers what a reader otherwise checks by hand. - -🔴 WHY THIS EXISTS. Every fact below was previously established by a human -running four or five commands and holding the results in their head: is the pod -up, is my token any good, is my cache stamped, does my cache agree with the pod, -is anything on this disk invisible to my credential, and does this host's READER -resolve to the synced cache or to the frozen pre-cutover mirror. Nothing joined -them, so the answers were assembled differently every time and the joins that -matter — cache count vs pod count, local scopes vs visible scopes — were the -ones nobody made. - -🔴 FOUR STATES, AND THE FOURTH IS THE WHOLE POINT. This subsystem's recurring -defect is a reassuring zero: an output that cannot distinguish "there is nothing -there" from "I could not look". So every check reports one of - - OK measured, and the answer is fine - PROBLEM measured, and the answer is not fine - UNMEASURED I tried and could not — the reason is mandatory - NOT-OBSERVABLE this cannot be answered from a client AT ALL, structurally, - and the detail names who can answer it and how - -`NOT-OBSERVABLE` is separate from `UNMEASURED` on purpose. Folding the two would -make the exit code permanently non-zero — the deployed API exposes no identity -route and never will from here — and `claude/RULES.md` says a permanently-red -gate is worse than no gate because it trains everyone to click through. - -🔴 DOCTOR NEVER INSTALLS A SNAPSHOT. It fetches, reads the headers and the member -list, and throws the bytes away. A diagnostic that repaired the cache as a side -effect would destroy the staleness it was run to measure — and it would be the -one command you must not run twice. - -🔴 THE HOLE IT CANNOT CLOSE, STATED RATHER THAN LEFT TO BE FOUND. A scope this -host holds but the pod's snapshot does not contain is EITHER a scope the store -has never held OR a scope outside this token's allowlist. The API answers those -two identically **by design** — `server.py` closes an enumeration oracle by -making a refused scope byte-identical to an absent one — so no client can tell -them apart, and this module does not pretend to. It reports the set and names -both readings. -""" - -from __future__ import annotations - -import hashlib -from collections.abc import Callable, Iterable -from dataclasses import dataclass, field -from pathlib import Path - -__all__ = [ - "OK", - "PROBLEM", - "UNMEASURED", - "NOT_OBSERVABLE", - "STATES", - "TOKEN_FINGERPRINT_CHARS", - "Check", - "PodFacts", - "token_fingerprint", - "store_entry_files", - "store_scopes", - "writable_entry_files", - "collect", - "render", - "exit_code", -] - -#: The four verdicts a check may carry. Written out once; `render` and -#: `exit_code` both read this tuple rather than restating the list. -OK = "OK" -PROBLEM = "PROBLEM" -UNMEASURED = "UNMEASURED" -NOT_OBSERVABLE = "NOT-OBSERVABLE" -STATES: tuple[str, ...] = (OK, PROBLEM, UNMEASURED, NOT_OBSERVABLE) - -#: How many hex characters of `sha256(token)` identify a credential. -#: -#: 🔴 THIS MIRRORS `subsystem-store-api/server.py::token_id`, WHICH IS WHAT THE -#: POD'S AUDIT LOG CARRIES. The value is what makes the fingerprint printed here -#: matchable against a `token=` line in the pod's log, so the two agreeing is -#: a wire fact and not an implementation detail. `cairn` cannot import -#: `server.py` — that module inserts paths, pulls in the whole reader and exists -#: to be run as a daemon — so the rule is spelled twice and pinned once: -#: `test_cairn_doctor.py::test_the_fingerprint_is_the_SERVERS_token_id` imports -#: both and requires they agree on a fixture whose expected digest is written out -#: as a literal in the test. -TOKEN_FINGERPRINT_CHARS = 12 - - -def token_fingerprint(token: str) -> str: - """A stable, non-reversible handle for a credential. NEVER the token.""" - return hashlib.sha256(token.encode("utf-8")).hexdigest()[:TOKEN_FINGERPRINT_CHARS] - - -@dataclass(frozen=True) -class Check: - """One diagnosed fact. - - `detail` is mandatory and is not decoration: for `UNMEASURED` it carries the - reason, and for `NOT-OBSERVABLE` it carries the command that CAN answer it. - A state with an empty detail is refused at construction, because a bare - `UNMEASURED` is the reassuring zero wearing a different word. - """ - - name: str - state: str - detail: str - - def __post_init__(self) -> None: - if self.state not in STATES: - raise ValueError(f"unknown check state {self.state!r}; expected one of {STATES}") - if not self.detail.strip(): - raise ValueError( - f"check {self.name!r} has an empty detail — a state with no " - f"reason cannot be acted on" - ) - - -@dataclass(frozen=True) -class PodFacts: - """What one non-installing snapshot fetch established, or why it did not. - - 🔴 `reached` IS NOT DERIVED FROM THE COUNTS. A store that genuinely holds - zero entries and a fetch that never happened both leave the counts at 0, so - the counts may only be read when `reached` is True — and every consumer below - branches on `reached` first. - """ - - reached: bool - #: Set when `reached` is False. Mandatory in that case. - reason: str = "" - #: The HTTP status when the server ANSWERED but refused. `None` when there - #: was no answer at all, which is what separates unauthorised from - #: unreachable without parsing a message. - http_status: int | None = None - #: `X-Store-Entries` — what THIS token's snapshot contained. - visible_entries: int | None = None - #: `entry-files=` out of `X-Store-Snapshot` — the STORE-WIDE total, which the - #: server emits unfiltered (a documented, deliberate residual count leak). - store_wide_entries: int | None = None - #: Scope directory names present in the fetched archive. - visible_scopes: tuple[str, ...] = () - #: The raw `X-Store-Snapshot` header, relayed verbatim. - snapshot_header: str = "" - - def __post_init__(self) -> None: - """🔴 THE MANDATORY REASON, ENFORCED — it was only DOCUMENTED before. - - `Check` refuses an empty detail at construction; this dataclass said - "Mandatory in that case" about `reason` and checked nothing. The - asymmetry is the defect, in the module whose whole thesis is that a bare - UNMEASURED is the reassuring zero wearing a new word: a future - `PodFacts(reached=False)` renders `the store's state could not be - established — .` and walks straight past `Check`'s guard, because the - empty string is wrapped in literal f-string text before it gets there. - Not reachable from today's three call sites; that is what makes now the - cheap time to close it. - """ - if not self.reached and not self.reason.strip(): - raise ValueError( - "PodFacts(reached=False) requires a reason — an unmeasured " - "store with no stated cause is the silent zero this module " - "exists to prevent" - ) - - -# --------------------------------------------------------------------------- # -# Disk facts. Each one is a plain function so a test can drive it directly. -# --------------------------------------------------------------------------- # - -def _scope_dirs(root: Path) -> list[Path]: - """`//` directories, dot-directories excluded. - - Raises `OSError` rather than returning `[]` on an unreadable root: an empty - list and an unreadable directory are the two things this whole module exists - to keep apart, so the failure has to reach a caller that can name it. - """ - return sorted(p for p in root.iterdir() if p.is_dir() and not p.name.startswith(".")) - - -def store_scopes(root: Path) -> tuple[str, ...]: - """The scope names a store root holds.""" - return tuple(p.name for p in _scope_dirs(root)) - - -def store_entry_files(root: Path) -> int: - """`/.md` files under a store root. - - The SAME shape `server.snapshot_freshness` counts — depth 2, `*.md`, no - dot-directories and no dot-files — so this number and the pod's - `entry-files=` are answers to one question rather than two. - """ - total = 0 - for scope in _scope_dirs(root): - for entry in scope.iterdir(): - if entry.is_file() and entry.name.endswith(".md") and not entry.name.startswith("."): - total += 1 - return total - - -def writable_entry_files(root: Path) -> tuple[str, ...]: - """Entry files under `root` that any mode bit still allows WRITING. - - 🔴 THE FREEZE IS A PROPERTY OF EVERY FILE, NOT OF THE DIRECTORY. The cutover - chmods the pre-cutover mirror read-only so nothing can write to a store that - no longer feeds anybody. A partially-frozen mirror still accepts a write, - and that write then lives on one host and is invisible to the pod — the - exact stranding the cutover exists to prevent. So this counts FILES, and a - non-empty answer is a PROBLEM even when the directory looks frozen. - """ - loose: list[str] = [] - for scope in _scope_dirs(root): - for entry in sorted(scope.iterdir()): - if not (entry.is_file() and entry.name.endswith(".md")): - continue - if entry.stat().st_mode & 0o222: - loose.append(f"{scope.name}/{entry.name}") - return tuple(loose) - - -@dataclass(frozen=True) -class Reading: - """One disk fact, or the structured reason there is none. - - 🔴 `absent` IS A FLAG, NOT A SENTENCE. The first version had callers ask - `reason.endswith("does not exist")` to tell a missing directory from an - unreadable one — a guard SPELLED rather than STRUCTURAL, which `claude/RULES.md` - names directly: reword the message and the branch silently stops firing, with - an unreadable mirror then reported as "nothing pre-cutover on this host". - """ - - value: object | None - reason: str - absent: bool - - @property - def ok(self) -> bool: - return self.reason == "" - - -def _describe(root: Path, what: Callable[[Path], object]) -> Reading: - """Read one fact off disk, or say why not. Never a silent zero. - - 🔴 `absent` MEANS THE ROOT IS ABSENT — it is re-checked, not inferred from - the exception type. Mapping ANY `FileNotFoundError` to `absent=True` is wrong - in a way that produces a confident OK: a file vanishing MID-WALK raises the - same exception, and this store has two writers that do exactly that — the - hourly `analyze-service-index-commit.service`, and `cairn sync`, which - replaces the cache root by rename. The report would have read - `frozen-mirror OK … does not exist` for a directory that was right there, - with a false reason attached. Same shape as the defect `dd8411ca` fixed, one - level in: a state derived from a proxy instead of from the thing itself. - """ - try: - return Reading(what(root), "", absent=False) - except FileNotFoundError as exc: - if not root.exists(): - return Reading(None, f"{root} does not exist", absent=True) - return Reading( - None, - f"{root} exists but something under it vanished while it was being " - f"read ({exc}) — a concurrent writer, not an absent store", - absent=False, - ) - except OSError as exc: - return Reading(None, f"{root} could not be read: {exc}", absent=False) - - -# --------------------------------------------------------------------------- # -# The checks -# --------------------------------------------------------------------------- # - -def collect( - *, - resolved_root: Path, - stamp_lines: Iterable[str] | None, - stamp_reason: str | None, - cache_root: Path, - mirror_root: Path | None, - pod: PodFacts, - token: str | None, - token_reason: str = "", - identity_remedy: str, -) -> list[Check]: - """Every check, in the order a reader should read them. - - Takes FACTS, not sources: the caller does the network and the config load, so - every branch here is reachable from a test with no server, no `$HOME` and no - clock. - """ - checks: list[Check] = [] - - # 1. WHICH DIRECTORY does this host's reader resolve, and can it date itself? - # This is `subsystem_read_store`'s question, asked out loud. - if stamp_lines is not None: - checks.append(Check( - "reader-resolution", - OK, - f"the reader resolves {resolved_root}, which carries a sync stamp", - )) - else: - checks.append(Check( - "reader-resolution", - PROBLEM, - f"the reader resolves {resolved_root}, which cannot date itself — " - f"{stamp_reason}. A read against it refuses (exit 4, the READER's " - f"EXIT_UNSTAMPED_READ_STORE). Fix: `cairn sync`.", - )) - - # 2. THE STAMP'S OWN FIELDS, relayed unparsed. - if stamp_lines is None: - checks.append(Check( - "cache-stamp", PROBLEM, - f"no readable stamp in {resolved_root} — {stamp_reason}", - )) - else: - rendered = "; ".join(stamp_lines) - checks.append(Check("cache-stamp", OK, rendered or "(the stamp is empty)")) - - # 3. THE FROZEN MIRROR. Absent is fine — a fresh host never had one. Present - # and fully read-only is fine. Present with a WRITABLE entry is not. - # - # 🔴 OPTIONAL, AND `None` IS NOT THE SAME AS ABSENT. A migrating deployment - # freezes its old local store and points this at it; a deployment that never - # had one has nothing to name. Saying "does not exist" about a path the - # operator never configured would be a claim about their disk that this code - # cannot support — so an unconfigured mirror is NOT-OBSERVABLE, not OK. - mirror = None if mirror_root is None else _describe(mirror_root, writable_entry_files) - loose = None if mirror is None else mirror.value - if mirror is None: - checks.append(Check( - "frozen-mirror", NOT_OBSERVABLE, - "no mirror is configured, so there is nothing to check. Set " - "CAIRN_MIRROR_ROOT if you migrated from a local store and want its " - "entry files confirmed read-only.", - )) - elif not mirror.ok: - if mirror.absent: - checks.append(Check( - "frozen-mirror", OK, - f"{mirror_root} does not exist — nothing pre-cutover on this host", - )) - else: - checks.append(Check("frozen-mirror", UNMEASURED, mirror.reason)) - elif loose: - shown = ", ".join(list(loose)[:5]) + ("…" if len(loose) > 5 else "") - checks.append(Check( - "frozen-mirror", PROBLEM, - f"{len(loose)} entry file(s) under {mirror_root} are still WRITABLE " - f"({shown}). The mirror is frozen so nothing writes to a store the " - f"pod does not read; a write to one of these lives on this host " - f"only. Re-run `cairn-cutover.py --freeze --apply`.", - )) - else: - checks.append(Check( - "frozen-mirror", OK, - f"every entry file under {mirror_root} is read-only", - )) - - # 4. THE POD. Unreachable, unauthorised and refused are three answers. - if pod.reached: - checks.append(Check( - "pod", OK, f"answered a snapshot request — {pod.snapshot_header or 'no stamp header'}", - )) - elif pod.http_status in (401, 403): - checks.append(Check( - "pod", PROBLEM, - f"the store ANSWERED and refused this credential (HTTP " - f"{pod.http_status}) — {pod.reason}. This is NOT an outage: the host " - f"is up. A 403 can also be the edge refusing the User-Agent rather " - f"than the token being wrong.", - )) - elif pod.http_status is not None: - checks.append(Check( - "pod", PROBLEM, - f"the store ANSWERED HTTP {pod.http_status} — {pod.reason}", - )) - else: - # 🔴 THE PREFIX IS NEUTRAL ON PURPOSE. It used to read "no answer from the - # store", which CONTRADICTS one of the reasons that arrives here: a - # snapshot the pod served and the client could not unpack is an answer. - # A heading that argues with the reason beneath it is a comment the code - # falsifies, which is the same defect class one layer up. - checks.append(Check( - "pod", UNMEASURED, - f"the store's state could not be established — {pod.reason}. Nothing " - f"below that needs the pod could be measured.", - )) - - # 5. CACHE vs POD. Only readable once the pod answered; otherwise UNMEASURED - # with the reason, never a zero. - cache = _describe(cache_root, store_entry_files) - cached = cache.value - if not pod.reached: - checks.append(Check( - "cache-vs-pod", UNMEASURED, - f"the pod was not reached ({pod.reason}), so the cache's " - f"{cached if cache.ok else 'unreadable'} entry file(s) " - f"could not be compared against anything", - )) - elif not cache.ok: - checks.append(Check("cache-vs-pod", UNMEASURED, cache.reason)) - elif pod.visible_entries is None: - checks.append(Check( - "cache-vs-pod", UNMEASURED, - "the store answered without an `X-Store-Entries` header, so its own " - "count of what it sent is unknown", - )) - elif cached == pod.visible_entries: - checks.append(Check( - "cache-vs-pod", OK, - f"{cached} entry file(s) here, {pod.visible_entries} in the store's " - f"answer to this token — they agree", - )) - else: - checks.append(Check( - "cache-vs-pod", PROBLEM, - f"{cached} entry file(s) here but {pod.visible_entries} in the " - f"store's answer to this token. Fix: `cairn sync`.", - )) - - # 6. WHAT THIS TOKEN CANNOT SEE. Two independent readings, both reported. - checks.append(_visibility_check(pod, cache_root, mirror_root)) - - # 7. THE CREDENTIAL. A fingerprint is measurable here; the IDENTITY behind it - # is not, from any client, and says so rather than going quiet. - if token is None: - checks.append(Check( - "token", PROBLEM, - token_reason or "no token is configured, so no request can be authenticated", - )) - else: - checks.append(Check( - "token", NOT_OBSERVABLE, - f"fingerprint {token_fingerprint(token)} (sha256[:{TOKEN_FINGERPRINT_CHARS}], " - f"the handle the pod's audit log carries). The IDENTITY and the " - f"declared scope allowlist behind it live in the pod's token file and " - f"the API exposes no route that returns them — see the scope check " - f"above for what this credential can actually reach. To read the " - f"declared row: {identity_remedy}", - )) - - return checks - - -def _visibility_check(pod: PodFacts, cache_root: Path, mirror_root: Path | None) -> Check: - """Scopes and entries on this disk that the store's answer did not carry. - - 🔴 `mirror_root` IS OPTIONAL AND UNSET IS THE DEFAULT. When the mirror - became configurable this signature was not widened with it, so `_describe` - was handed `None` and `doctor` died with `AttributeError: 'NoneType' object - has no attribute 'iterdir'` — zero stdout, exit 1 — for every deployment - that had never set `CAIRN_MIRROR_ROOT` and had a synced cache, which is the - ordinary state of a new one. The `frozen-mirror` check above had already - been widened; this one had not, and nothing joined the two. - - 🔴 AN UNCONFIGURED MIRROR IS NOT AN UNREADABLE ROOT. It contributes no - scopes and it is not a hole in this check's coverage, so it must NOT land in - `unread` — doing so would downgrade a complete answer to UNMEASURED on every - default deployment, which is the same false-alarm-forever failure in the - opposite direction. - """ - if not pod.reached: - return Check( - "token-scopes", UNMEASURED, - f"the pod was not reached ({pod.reason}), so nothing is known about " - f"which scopes this credential can reach", - ) - - # 🔴 PROVENANCE PER SCOPE, NOT ONE MERGED SET. The two roots mean different - # things and lead to different actions: a scope in the SYNCED CACHE that the - # pod no longer sends is a credential or a deletion; a scope in the FROZEN - # MIRROR only is a pre-cutover leftover that may never have reached the pod - # at all. The first version merged them and said "N scope(s) exist on this - # disk", offering two remedies that were both about the live store — so an - # operator could not tell which they were looking at. Measured: the two it - # named on the workbench were mirror-only. - where: dict[str, list[str]] = {} - unread: list[str] = [] - roots = [("cache", cache_root)] + ([] if mirror_root is None else [("mirror", mirror_root)]) - for label, root in roots: - reading = _describe(root, store_scopes) - if not reading.ok: - # An ABSENT root contributes nothing and is not a failure; an - # UNREADABLE one is a hole in this check's own coverage and is named - # in the detail, so a clean-looking answer cannot come from a walk - # that could not see half its input. - if not reading.absent: - unread.append(reading.reason) - continue - for name in reading.value: # type: ignore[union-attr] - where.setdefault(name, []).append(label) - - local = set(where) - visible = set(pod.visible_scopes) - missing = sorted(local - visible) - - hidden_entries = "" - if pod.store_wide_entries is not None and pod.visible_entries is not None: - gap = pod.store_wide_entries - pod.visible_entries - if gap > 0: - hidden_entries = ( - f" The store reports {pod.store_wide_entries} entry file(s) " - f"store-wide but sent this token {pod.visible_entries}, so " - f"{gap} live in scopes this credential cannot reach." - ) - - unread_note = (" Some local roots were unreadable: " + "; ".join(unread)) if unread else "" - - if not missing and not hidden_entries: - # 🔴 AN UNREADABLE LOCAL ROOT MAKES THIS UNMEASURED, NOT OK-WITH-A-NOTE. - # "every scope on this disk is among them" is a claim about a set this - # walk could not finish building, and an OK carrying a caveat in its tail - # is exactly how a partial answer gets read as a clean one. The note - # alone was the first version; it stated the hole and still graded the - # check green. - if unread: - return Check( - "token-scopes", UNMEASURED, - f"the {len(visible)} scope(s) the store sent are all reachable, but " - f"this host's own scope set could not be fully read, so nothing is " - f"established about scopes present locally.{unread_note}", - ) - return Check( - "token-scopes", OK, - f"this credential reaches all {len(visible)} scope(s) the store sent, " - f"and every scope on this disk is among them.", - ) - if not missing: - return Check("token-scopes", PROBLEM, hidden_entries.strip() + unread_note) - named = ", ".join(f"{s} [{'+'.join(where[s])}]" for s in missing) - mirror_only = [s for s in missing if where[s] == ["mirror"]] - leftover_note = ( - f" 🔴 {len(mirror_only)} of them exist ONLY in the frozen pre-cutover " - f"mirror ({', '.join(mirror_only)}) — those may never have reached the " - f"pod, so the question is whether they were ever seeded, NOT whether " - f"access was lost." - if mirror_only else "" - ) - return Check( - "token-scopes", PROBLEM, - f"{len(missing)} scope(s) exist on this disk and are NOT in the store's " - f"answer to this token, each tagged with WHERE it was found: {named}. " - f"For a scope the store should hold, the API cannot tell you which of " - f"two things you are seeing — a refused scope is byte-identical to one " - f"the store has never held, deliberately, so that an error cannot " - f"enumerate the store. Both readings are actionable: seed the scope, or " - f"add it to this token's allowlist.{leftover_note}" - f"{hidden_entries}{unread_note}", - ) - - -# --------------------------------------------------------------------------- # -# Rendering and the verdict -# --------------------------------------------------------------------------- # - -#: 🔴 THE EXIT CODES, OWNED BY THE COMMAND AND DOCUMENTED BY IT. `render` prints -#: the legend below on every run, so a caller never has to find a skill to learn -#: what a number meant. -#: -#: 🔴 THEY ARE SCOPED PER COMMAND, NOT GLOBALLY UNIQUE, AND 9 IS SHARED ON -#: PURPOSE. `doctor` returns 0/9/10. The client returns 0/3/4/5 for read outcomes, -#: 6/7/8/9 for write outcomes, and 2 for USAGE — which is a third bucket, not a -#: read outcome. An earlier draft of this sentence folded 2 in with the reads, and -#: the argparse bullet further down this same comment says the opposite, so the -#: block contradicted itself; the distinction is the point of that bullet. -#: So two numbers are shared: 0, which -#: means success in both because that is what 0 means, and 9, which is this -#: command's "a check MEASURED a problem" and `create`'s `EXIT_WRITE_EXISTS`. -#: Neither is ambiguous where a code is actually read — at ONE call site, which -#: already knows the verb it invoked. `doctor` never creates an entry and -#: `create` never runs diagnostics, so no caller can receive a 9 whose meaning is -#: in doubt. Nor is 9 the first such overlap: `cairn`'s `EXIT_REFRESH_FAILED` and -#: the reader's `lib/subsystem_read_store.EXIT_UNSTAMPED_READ_STORE` are both 4, -#: across two tools, for the same reason. Globally unique numbers were never the -#: design. -#: -#: 🔴 WHAT THE PER-COMMAND SCOPING DOES NOT COVER IS THE ONLY THING TO PROTECT -#: HERE: a code that a `doctor` invocation can return ALONGSIDE these. TWO more -#: are returned deliberately, so the codes a `doctor` caller may be handed BY -#: DESIGN are 0/1/2/9/10. 🔴 THAT IS A LIST OF WHAT THIS CLI CHOOSES TO RETURN, -#: NOT AN EXHAUSTIVE LIST OF WHAT A CALLER CAN OBSERVE — two earlier drafts -#: claimed exhaustiveness and were wrong, each time for a member nobody had -#: measured (0/2/9/10, then 0/1/2/9/10 with the 120 below missing). Treat any -#: future "the set is" here as a claim needing a measurement: -#: -#: - **2 — usage.** argparse exits 2 on a bad flag for every subcommand -#: (measured: `cairn doctor --bogus-flag` -> 2). -#: - **1 — an uncaught exception.** 1 is the interpreter's own code for any -#: traceback that reaches the top, so this is not one mechanism but a class. -#: One route is reachable BY DESIGN: `cairn`'s lazy `_cairn_doctor()` import -#: is deliberately unguarded at its `cmd_doctor` call site — see the docstring -#: at `cairn:_doctor_epilog`, which states that the help-string import fails -#: soft FOR AN `ImportError` ONLY while `cmd_doctor` still fails LOUDLY — so -#: with `lib/cairn_doctor.py` absent, `cairn doctor` exits 1 with -#: `ModuleNotFoundError` from `cairn:cmd_doctor`. Measured at a second point -#: too: a module present but unparseable raises `SyntaxError`, which is not an -#: `ImportError`, so `_doctor_epilog`'s `except ImportError` does not catch it -#: and it takes `build_parser` — and therefore EVERY verb — down at exit 1 -#: (measured on a tree with this file replaced by `def broken(`: -#: `cairn doctor`, `cairn ls-entries`, `cairn ls-entries --help` and -#: `cairn --help` all 1, all `SyntaxError`; with the file merely ABSENT the -#: same four are 1 / 3 / 0 / 0, and the 3 is the ordinary no-cache read -#: outcome an untouched tree gives). And the `AttributeError` recorded in -#: `AGENTS.md` under `checks.client-resolves-its-lib` was a third. -#: -#: ⚠ AND ONE MORE THE INTERPRETER RETURNS, WHICH IS WHY THE LIST IS NO LONGER -#: CLAIMED EXHAUSTIVE: **120**, CPython's code for a stdout it could not FLUSH at -#: shutdown. `cairn doctor | ` is an ordinary -#: invocation; the departed reader turns the final flush into a `BrokenPipeError`, -#: printed as `Exception ignored in: <_io.TextIOWrapper name='' …>` and -#: exited 120. 🔴 THE MECHANISM IS A PIPE WHOSE READER LEFT, NOT "NO STDOUT", and -#: the two read differently — measured at four points rather than one, because the -#: first draft of this note named the wrong one: `| true` -> **120** (5/5 runs); -#: `--json | true` -> 120; stdout genuinely CLOSED with `1>&-` -> **9** (5/5), -#: because `sys.stdout` is then `None`, nothing is written and so nothing can fail -#: to flush; `| head -1` -> **9** (5/5), because doctor's 2,016 bytes fit the -#: 64 KiB pipe buffer and the write lands before `head` exits — that point would -#: INVERT for an output larger than the buffer, so it is a fact about this output -#: size, not a general one. Nor is it doctor-specific: `cairn --help | true` is -#: 120 as well. 120 stays OUT of the operative instruction below because no doctor -#: code could be chosen to avoid it and it cannot collide with a plausible one; it -#: is recorded so the enumeration above stops reading as a claim about everything -#: a caller can see. -#: -#: 1 and 2 are both clear of this block today because doctor's own codes are -#: 0/9/10, and BOTH must stay clear: a doctor code of 1 would be indistinguishable -#: from a crash, exactly as a doctor code of 2 would be from a usage error. 1 is -#: the more insidious of the two, because it is not any `cairn` constant — nothing -#: in the client's nine codes is 1 — so a set-intersection ledger against the -#: client cannot see it and it is asserted separately. The write codes cannot -#: reach this call site at all. -#: -#: 🔴 SO DO NOT RENUMBER THE 9 TO MAKE IT UNIQUE, and do not read the overlap as -#: licence to add another. Renumbering changes a contract this command PRINTS, to -#: remove a collision that was never a defect. A NEW overlap is safe only if it -#: too is unreachable from any one call site, which is a fact about the dispatcher -#: and not about which numbers happen to look free. -#: `tests/test_cairn_doctor.py` pins the shared set as a ledger: it DISCOVERS both -#: operands — doctor's `EXIT_DOCTOR_*` ∪ `EXIT_LEGEND`, and the client's `EXIT_*` -#: read out of `cairn` — so it goes red when the shared set GROWS from EITHER side -#: and when it SHRINKS. 🔴 IT WAS NOT THAT WHILE IT HAND-LISTED BOTH OPERANDS, and -#: the first version of this sentence called it "the authority on which codes -#: overlap" anyway. Nine client names and three doctor ones were written out, so a -#: TENTH client code colliding with the 10 left the intersection at {0, 9} and the -#: file green at 60 passed — the exact case the failure message advertised -#: catching. What discovery still does not see is named in that file: a code -#: spelled without the `EXIT_`/`EXIT_DOCTOR_` prefix, and — on the client side, -#: which is read by AST — one whose value is computed rather than an integer -#: literal; the second is cross-checked against the exec'd module's own namespace -#: rather than assumed away. It carries a second, separate assertion that 1 is not -#: one of doctor's codes, because the ledger structurally cannot: 1 is not in the -#: client's set, so an `EXIT_DOCTOR_* = 1` leaves the intersection at {0, 9} and -#: the ledger green. -EXIT_DOCTOR_OK = 0 -EXIT_DOCTOR_PROBLEM = 9 -EXIT_DOCTOR_UNMEASURED = 10 - -EXIT_LEGEND: tuple[tuple[int, str], ...] = ( - (EXIT_DOCTOR_OK, "every check measured, and every answer is fine"), - (EXIT_DOCTOR_PROBLEM, "at least one check MEASURED a problem"), - (EXIT_DOCTOR_UNMEASURED, - "no problem measured, but at least one check COULD NOT LOOK — " - "this is not a clean bill of health"), -) - - -def exit_code(checks: Iterable[Check]) -> int: - """PROBLEM outranks UNMEASURED outranks OK. - - 🔴 `NOT-OBSERVABLE` CONTRIBUTES NOTHING, and that is deliberate. It marks a - fact no client can reach, so escalating on it would make this command - non-zero on every healthy run forever — the permanently-red gate - `claude/RULES.md` says trains everyone to click through. - """ - states = {c.state for c in checks} - if PROBLEM in states: - return EXIT_DOCTOR_PROBLEM - if UNMEASURED in states: - return EXIT_DOCTOR_UNMEASURED - return EXIT_DOCTOR_OK - - -_MARKER = {OK: " ", PROBLEM: "🔴", UNMEASURED: "⚠ ", NOT_OBSERVABLE: "· "} - - -def render(checks: list[Check]) -> str: - """The report, plus the exit legend, plus a one-line verdict.""" - width = max((len(c.name) for c in checks), default=0) - lines = [f"{_MARKER[c.state]} {c.name.ljust(width)} {c.state:<14} {c.detail}" - for c in checks] - code = exit_code(checks) - counts = {s: sum(1 for c in checks if c.state == s) for s in STATES} - lines.append("") - lines.append( - "checks: " - + " ".join(f"{s}={counts[s]}" for s in STATES) - + f" -> exit {code}" - ) - lines.append("exit codes: " + "; ".join(f"{n} = {why}" for n, why in EXIT_LEGEND)) - return "\n".join(lines) - - -def to_dict(checks: list[Check]) -> dict: - return { - "checks": [{"name": c.name, "state": c.state, "detail": c.detail} for c in checks], - "counts": {s: sum(1 for c in checks if c.state == s) for s in STATES}, - "exit": exit_code(checks), - "exit_legend": {str(n): why for n, why in EXIT_LEGEND}, - } diff --git a/lib/cairn_instances.py b/lib/cairn_instances.py deleted file mode 100644 index 3ce08250..00000000 --- a/lib/cairn_instances.py +++ /dev/null @@ -1,568 +0,0 @@ -#!/usr/bin/env python3 -"""WHICH INSTANCE does a scope live on, and where is each instance configured? - -A deployment may point one client at more than one cairn. This module owns the -three questions that creates — what is configured, which instance a scope -belongs to, and whether the two agree — and it owns them for a client that -knows NOTHING about who routes where: the scope->alias table is an INPUT (a -file), never a constant in this repository. A public tool that shipped somebody's -taxonomy would be publishing their org chart. - -🔴 AN UNROUTED SCOPE REFUSES. It does not fall back to the first instance, the -default instance, or the one that happens to answer. A default silently -recreates the shape that has already cost entries in this system's history — -writes landing in a store nobody reads, discovered days later by a diagnostic -built for something else. A refusal costs one error message, and it names the -scope so the remedy is a single line in the table. - -🔴 ONE INSTANCE IS NOT ROUTING, AND THAT IS THE WHOLE COMPATIBILITY STORY. -With a single configured instance there is no second place a scope could go, -so an unregistered scope answers with it and NOTHING about the single-instance -client changes — no label, no table, no refusal. The alternative — refusing -until a table exists — would break every existing deployment on upgrade in -exchange for a guarantee nobody needs while there is one store. - -🔴 AND "IS THIS HOST ROUTING?" IS NOT ONE QUESTION, WHICH IS THE CORRECTION -THIS MODULE CARRIES. It used to be, and the single boolean was -`routes is not None or len(instances) > 1` — table presence counted as routing. -That is wrong in both directions on a ONE-instance host that has a table, which -is the state an operator reaches the moment they write one: - - case (ONE instance configured) | what must happen - ----------------------------------------|------------------------------------ - no table at all | resolve to the sole instance - a table, and the scope is NOT in it | resolve to the sole instance - a table entry naming an UNCONFIGURED | REFUSE — the table names where the - alias | scope lives and this host cannot - | reach it - -Rows 2 and 3 need OPPOSITE answers from the same configuration, so no single -`active` flag can decide both: with the old predicate row 2 refused (a scope -nobody had added to the table yet became unreadable), and simply deleting the -`routes is not None` disjunct makes row 3 resolve to the sole instance — a -SILENT MISROUTE, a write landing in a store nobody decided on, which is worse -than the refusal it replaces. So there are two predicates: `multi_instance` -decides what is LABELLED, and `alias_for` consults the TABLE FIRST and falls -back to the sole instance only when the table said nothing at all. - -🔴 THE DEFAULT INSTANCE IS THE EXISTING CONFIG FILE, UNMOVED. `~/.config/ -subsystem-store/env` keeps its name, its contents and its environment-variable -precedence, and becomes the alias `personal`. Additional instances are ADDITIVE -files under `instances/.env` beside it. Nothing migrates; an upgrade -that adds no file changes nothing. - -🔴 THE ENVIRONMENT OVERRIDES THE DEFAULT INSTANCE ONLY. `CAIRN_URL` / -`CAIRN_TOKEN` — and their deprecated `SUBSYSTEM_STORE_*` aliases, which -`env_aliases` resolves — have always pointed the client at a throwaway server, -and every test relies on it. Applying them to EVERY instance would point all of -them at one store — a fan-out that reads N instances and measures one, reporting -agreement it never observed. A non-default alias reads its own file and nothing -else. -""" - -from __future__ import annotations - -import json -import os -from dataclasses import dataclass -from pathlib import Path -from typing import Mapping - -import env_aliases -from subsystem_read_store import DEFAULT_ALIAS, valid_alias - -__all__ = [ - "CONFIG_ENV", - "ROUTES_ENV", - "INSTANCE_DIR_NAME", - "INSTANCE_SUFFIX", - "ROUTES_FILE_NAME", - "Instance", - "Routing", - "RoutingConfigError", - "UnroutedScope", - "config_path", - "discover", - "instance_dir", - "load_routes", - "routes_file", - "routing_for", -] - -#: The environment variable naming the DEFAULT instance's config file. It -#: predates instances and keeps its meaning exactly. `SUBSYSTEM_STORE_CONFIG` -#: still resolves to it through `env_aliases`; this module never spells the old -#: name, which is what keeps the ledger in one place. -CONFIG_ENV = "CAIRN_CONFIG" - -#: The environment variable naming the routing table. Set it and the table is -#: MANDATORY — a missing file is an error, never "routing is off". An operator -#: who named a table meant to use one, and silently ignoring the name is how a -#: typo'd path turns a fail-loud design into a fail-open one. -ROUTES_ENV = "CAIRN_ROUTES" - -#: Additional instances live beside the default config file, one file each. -INSTANCE_DIR_NAME = "instances" -INSTANCE_SUFFIX = ".env" - -#: The table's default name, beside the config file. Absent => no routing. -ROUTES_FILE_NAME = "routes.json" - - -class RoutingConfigError(Exception): - """The instance configuration or the routing table cannot be read. - - Separate from `UnroutedScope` because the remedies differ: this one means a - FILE is wrong (malformed JSON, an alias that cannot be a directory name, two - sources claiming one alias), and no scope is involved. - """ - - -class UnroutedScope(Exception): - """This scope cannot be resolved to an instance, and nothing was guessed. - - 🔴 THE SCOPE IS AN ATTRIBUTE, NOT ONLY A SUBSTRING OF THE MESSAGE. A caller - that has to grep an f-string to learn which scope failed has pinned prose; - the structural fact is carried so a consumer can act on it and a test can - assert it without pinning a sentence. - """ - - def __init__(self, scope: str, detail: str) -> None: - super().__init__(detail) - self.scope = scope - self.detail = detail - - -@dataclass(frozen=True) -class Instance: - """One configured cairn: its alias and the file its URL and token come from. - - 🔴 NO URL AND NO TOKEN HERE. This module enumerates and routes; it never - reads a credential. Keeping the secret out of the object that gets printed, - logged and rendered is what stops it being printed, logged and rendered. - """ - - alias: str - config_path: Path - - @property - def is_default(self) -> bool: - return self.alias == DEFAULT_ALIAS - - -def config_path(env: Mapping[str, str] | None = None) -> Path: - """The DEFAULT instance's config file — `$CAIRN_CONFIG` or the long-standing - `~/.config/subsystem-store/env`.""" - env = os.environ if env is None else env - raw = env_aliases.value(env, CONFIG_ENV).strip() - if raw: - return Path(raw).expanduser() - return Path.home() / ".config" / "subsystem-store" / "env" - - -def instance_dir(env: Mapping[str, str] | None = None) -> Path: - """Where additional instances live: `instances/` beside the config file. - - 🔴 DERIVED FROM THE CONFIG PATH, NOT A SECOND ENVIRONMENT VARIABLE. One - variable moves the whole configuration — which is what a test needs, and - what keeps `$CAIRN_CONFIG` pointing somewhere while the instances - it should sit beside are read from the operator's real home directory. - """ - return config_path(env).parent / INSTANCE_DIR_NAME - - -def routes_file(env: Mapping[str, str] | None = None) -> tuple[Path, bool]: - """`(path, explicitly_configured)` for the routing table. - - The second element is the difference between "the operator named this file" - and "this is where a table would live if there were one". An explicit path - that does not exist is an ERROR; a default path that does not exist means - there is no routing table, which is the ordinary single-instance state. - """ - env = os.environ if env is None else env - raw = env.get(ROUTES_ENV, "").strip() - if raw: - return Path(raw).expanduser(), True - return config_path(env).parent / ROUTES_FILE_NAME, False - - -def load_routes(path: Path) -> dict[str, str]: - """The scope->alias table, as a flat JSON object of strings. - - 🔴 ONE SHAPE, AND EVERYTHING ELSE IS REFUSED. A table is read by a machine - to decide where a durable write lands, so "we accepted something odd and did - our best with it" is the wrong failure mode: a nested object, a list, a - non-string value or a non-object document each raise rather than silently - contributing zero routes. A table that parsed to nothing would leave every - scope unrouted, which LOOKS like a deliberate refusal and is not. - """ - try: - raw = path.read_text(encoding="utf-8") - except OSError as exc: - raise RoutingConfigError(f"the routing table `{path}` could not be read: {exc}") from exc - try: - parsed = json.loads(raw) - except ValueError as exc: - raise RoutingConfigError(f"the routing table `{path}` is not valid JSON: {exc}") from exc - if not isinstance(parsed, dict): - raise RoutingConfigError( - f"the routing table `{path}` must be a JSON object mapping each scope " - f"to an instance alias, e.g. {{\"alpha-notes\": \"personal\"}} — got " - f"{type(parsed).__name__}" - ) - table: dict[str, str] = {} - for scope, alias in parsed.items(): - if not isinstance(alias, str) or not scope: - raise RoutingConfigError( - f"the routing table `{path}` maps scope `{scope}` to " - f"{alias!r}, which is not an instance alias. Every value must be " - f"the alias of a configured instance." - ) - if not valid_alias(alias): - raise RoutingConfigError( - f"the routing table `{path}` maps scope `{scope}` to the alias " - f"`{alias}`, which is not a usable alias. An alias becomes a " - f"directory name under the cache root, so it is lowercase " - f"letters, digits and hyphens only." - ) - table[scope] = alias - return table - - -@dataclass(frozen=True) -class Routing: - """What is configured on this host, and the routing decision it supports.""" - - instances: tuple[Instance, ...] - routes: Mapping[str, str] | None - routes_source: Path | None - - @property - def aliases(self) -> tuple[str, ...]: - return tuple(i.alias for i in self.instances) - - @property - def multi_instance(self) -> bool: - """Is there more than one PLACE on this host an answer could come from? - - 🔴 THE LABELLING PREDICATE, AND IT IS DELIBERATELY NOT THE ROUTING ONE. - Every place the client says WHICH instance it read — the banner label, - `doctor`'s per-instance rows, `ls-entries`' prefix, the `--all-scopes` - fan-out, the caveat's extra clause — asks THIS, so they cannot drift - into disagreeing about whether this host has more than one store. - - 🔴 IT ASKS THE INSTANCE COUNT AND NOT THE TABLE, AND THAT IS THE FIX. - The predicate used to be `routes is not None or len(instances) > 1`, so - writing a routing table on a ONE-instance host switched every label on: - each recall then asserted "with more than one instance configured, an - absence here is also explainable by the scope living on another - instance" — a sentence that is FALSE on that host, printed on every - call, which is precisely the always-false caveat the caveat rewrite - exists to eliminate. A table is a statement about where scopes live, - not about how many stores this machine can reach. - - ⚠ IT IS NOT THE ROUTING DECISION EITHER — see `alias_for`, which - consults the table whatever this returns. A one-instance host with a - table still REFUSES a scope routed to an alias it has no config for. - """ - return len(self.instances) > 1 - - def get(self, alias: str) -> Instance: - for instance in self.instances: - if instance.alias == alias: - return instance - raise RoutingConfigError( - f"no instance `{alias}` is configured on this host " - f"(configured: {', '.join(self.aliases)})" - ) - - def alias_for(self, scope: str) -> str: - """The instance `scope` belongs to, or raise. NEVER a guess. - - 🔴 THE TABLE IS CONSULTED FIRST, WHATEVER `multi_instance` SAYS, AND THE - ORDER IS THE WHOLE POINT. Three cases share one configuration — a - one-instance host with a table — and two of them must answer - DIFFERENTLY, so a single "is this host routing" boolean cannot decide - them. Measured, on a host with ONE instance configured: - - table state for this scope | today | `active = len(instances)>1` - -----------------------------|--------|---------------------------- - (1) no table at all | sole | sole - (2) table, scope ABSENT | sole | sole - (3) table -> UNCONFIGURED | REFUSE | sole <- SILENT MISROUTE - alias | | - - Row 3 is a table explicitly routing a scope to an alias this host has no - config for. Resolving it to the sole instance is a write landing in a - store nobody decided on — the exact failure the refusal exists to - prevent — so it refuses at ONE instance and at many. Rows 1 and 2 are - the opposite: the table said nothing about this scope, and with one - instance there is exactly one answer to "where did that go?", which is - the same reasoning the no-table case has always used. - - The refusals, each reachable by an input no earlier one rejects: - 1. a table naming an alias this host has no config for (any count) - 2. two or more instances and no table -> nothing can decide - 3. two or more instances and a table without `scope` - - 🔴 THE COMPARISON IS EXACT. The table's keys are scope names exactly as - `entry_shape.derive_scope` produces them. A case or spelling mismatch - therefore falls through to the rows above rather than resolving to - something adjacent, which is the safe direction for a value that decides - where a write lands. - """ - alias = None if self.routes is None else self.routes.get(scope) - if alias is not None: - if alias not in self.aliases: - raise UnroutedScope( - scope, - f"the routing table `{self.routes_source}` routes scope " - f"`{scope}` to instance `{alias}`, which is not configured on " - f"this host (configured: {', '.join(self.aliases)}). REFUSING " - f"rather than falling back: the table names where this scope " - f"lives, and this host cannot reach it. Add " - f"`{instance_dir()}/{alias}{INSTANCE_SUFFIX}`.", - ) - return alias - # The table decided NOTHING about this scope — it has no entry, or there - # is no table. With one instance that has exactly one answer. - if not self.multi_instance: - return DEFAULT_ALIAS - if self.routes is None: - raise UnroutedScope( - scope, - f"{len(self.instances)} instances are configured " - f"({', '.join(self.aliases)}) and no routing table says which one " - f"scope `{scope}` belongs to. REFUSING rather than picking one: a " - f"write to the wrong instance lands in a store nobody reads. " - f"Write a scope->alias table to " - f"`{routes_file()[0]}`, or set ${ROUTES_ENV} to one.", - ) - raise UnroutedScope( - scope, - f"scope `{scope}` is not in the routing table " - f"`{self.routes_source}`. REFUSING rather than defaulting to an " - f"instance: an unregistered scope is a scope nobody decided about, " - f"and guessing is how a write lands in a store nobody reads. Add " - f"`\"{scope}\": \"\"` to that table (configured instances: " - f"{', '.join(self.aliases)}).", - ) - - def check(self, scopes: Mapping[str, str] | set[str] | tuple[str, ...] | list[str] - ) -> tuple[tuple[str, ...], tuple[str, ...]]: - """Grade this host's routing table against reality, IN BOTH DIRECTIONS. - - Returns `(problems, notes)`, each a tuple of strings in a stable order. - A PROBLEM is a defect this check can actually decide, and it is what - takes `routes --check` to exit 11. A NOTE is something worth printing - that the available evidence CANNOT decide; it never changes the exit - code. Callers must not read a truthy/falsy bare return, which is why - both halves are strings rather than a bool. - - 🔴 BOTH DIRECTIONS, BECAUSE EACH MISSES A DIFFERENT DEFECT. A scope with - no entry is a scope whose next write REFUSES — annoying but loud. An - entry naming a scope that does not exist is the silent one: it reads as - coverage, survives the scope being renamed or retired, and is exactly - what a table accumulates when it is edited by hand. A one-way check - would report a clean table over either. - - A third direction is graded here too because it is the same class: an - entry naming an alias no instance provides. 🔴 IT IS NOT RE-DERIVED — it - ASKS `alias_for`, which already owns that refusal. This method used to - recompute `alias not in aliases` from the same two inputs, so the rule - had two implementations and the second one could have drifted without - any test noticing; one rule, one place. - - 🔴 AND DIRECTION TWO IS A **NOTE**, NOT A PROBLEM, BECAUSE THE SCOPE SET - IT SUBTRACTS FROM CANNOT SEE AN EMPTY SCOPE. The caller's scope set is a - cache's DIRECTORY LISTING, and a snapshot ships entry FILES — no - directory member — so a scope holding no entries is absent from the - cache whether it has been retired, pre-registered before its first - write, or simply pruned back to nothing. Measured, one instance, a table - naming `hollow-set`: - - routes --check rc=11 "…exists on no configured instance" - recall --scope hollow-set rc=0 "scope-empty — reached the store" - - Grading that at exit 11 makes the check unusable as the TWO-WAY REGISTRY - it exists to be — a table is supposed to name a scope BEFORE the first - write lands — and the remedy the sentence implies (delete the line) is - actively wrong: with more than one instance the next write to that scope - then REFUSES. So the observation is kept and the verdict is dropped. - - ⚠ THIS COSTS REAL TEETH AND SAYING SO IS THE POINT: a genuinely stale - entry now reads as a note. **Closing condition** — the discriminator - exists, it is just not in the snapshot: the SERVER reads the real store, - where `subsystem_resolver.build_index` registers a scope directory it - found empty (`extra_scopes`), so `GET /api/v1/recall/` answers - `scope-empty` - for a live-but-empty scope and `scope-absent` for one that does not - exist. When this check probes the ROUTED instance per table entry and - both clients do it identically with a parity row over it, direction two - can become a problem again. It is not done here because it turns a - two-request command into an O(table) one and that is a separate decision - from the one this fixes. - """ - if self.routes is None: - raise RoutingConfigError( - "there is no routing table on this host to grade. A caller that " - "reached here read an absent table as an empty one, which would " - "report every scope as unrouted." - ) - scope_set = set(scopes) - problems: list[str] = [] - notes: list[str] = [] - # 🔴 DIRECTION ONE ASKS THE RESOLVER, IT DOES NOT SUBTRACT KEY SETS. The - # finding this raises is "a write to it will REFUSE", which is a claim - # about what `alias_for` does — and on a ONE-instance host it does not - # refuse: an unnamed scope resolves to the sole instance. Grading by the - # table's keys alone printed that refusal warning on every unnamed scope - # of every one-instance host, which is a confident statement about - # behaviour that will not happen. - for scope in sorted(scope_set - set(self.routes)): - try: - self.alias_for(scope) - except UnroutedScope: - problems.append( - f"scope `{scope}` exists but the routing table does not name " - f"it — a write to it will REFUSE" - ) - # ⚠ DIRECTION TWO IS NOT A RESOLVER QUESTION, DELIBERATELY. `alias_for` - # resolves a stale entry perfectly well — it names a configured alias — - # so asking it here would grade this direction clean. What the resolver - # cannot see is whether the scope EXISTS; what the SCOPE SET cannot see - # is whether it exists but holds nothing. Hence a NOTE: see the - # docstring for the measurement and the closing condition. - for scope in sorted(set(self.routes) - scope_set): - notes.append( - f"the routing table names scope `{scope}`, which holds no entry " - f"on any configured instance — a stale entry reads as coverage, " - f"but a scope pre-registered before its first write or pruned " - f"back to nothing looks IDENTICAL here, because a snapshot ships " - f"entry files and not directories. Check it rather than deleting " - f"the line: with more than one instance, deleting it makes the " - f"next write to `{scope}` REFUSE." - ) - for scope in sorted(self.routes): - try: - self.alias_for(scope) - except UnroutedScope: - # 🔴 THE ONLY REFUSAL `alias_for` CAN RAISE FOR A SCOPE THE TABLE - # NAMES is the unconfigured-alias one: the other two arms are - # reached only when the table said nothing about the scope, and - # this loop iterates the table's own keys. The short line here is - # the FINDING's wording; the PREDICATE is `alias_for`'s. - problems.append( - f"the routing table routes `{scope}` to instance " - f"`{self.routes[scope]}`, which is not configured on this host" - ) - return tuple(problems), tuple(notes) - - -def discover(env: Mapping[str, str] | None = None) -> Routing: - """Everything configured on this host: instances first, then the table. - - 🔴 THE DEFAULT INSTANCE ALWAYS EXISTS, FILE OR NO FILE. `load_config` has - always accepted a URL and token from the environment with no file at all, - and every test in this repository does exactly that. Making the default - instance conditional on a file would have deleted that path — the client - would have reported "no instances configured" on a host that is perfectly - well configured, which is a statement about a file rather than about the - store. - """ - env = os.environ if env is None else env - instances = [Instance(alias=DEFAULT_ALIAS, config_path=config_path(env))] - - directory = instance_dir(env) - extra: list[Instance] = [] - try: - entries = sorted(directory.iterdir()) - except FileNotFoundError: - entries = [] - except OSError as exc: - raise RoutingConfigError( - f"the instance directory `{directory}` could not be read: {exc}. It is " - f"not the same fact as 'no extra instances are configured', so this " - f"refuses rather than reporting one instance." - ) from exc - for path in entries: - if not path.name.endswith(INSTANCE_SUFFIX) or path.is_dir(): - continue - # 🔴 AN EDITOR LOCK FILE IS NOT A FILE THE OPERATOR WROTE, AND THE - # REFUSAL BELOW TOOK EVERY VERB TO EXIT 11 WHILE ONE WAS OPEN. Emacs' - # lock file for `secondary.env` is `.#secondary.env`: it ends in `.env`, - # its stem `.#secondary` is not a usable alias, and it is a DANGLING - # SYMLINK, so `is_dir()` is False and it reached the hard error — so - # every `cairn` invocation on that host refused to run until the buffer - # was closed. The snapshot builder already learned this one suffix over - # (`.#entry.md` 503'd the whole store); the rule there is the rule - # here — NAME rules are separate from TYPE rules. - # - # 🔴 `.#`, NOT `.` — AND THE WIDER PREDICATE WAS SHIPPED AND MEASURED - # WRONG. Skipping every dotted name also skipped `instances/.env`, - # whose stem is the EMPTY string: an operator who wrote that file got - # `instances: personal` at exit 0 and no message anywhere, which is - # precisely the outcome the refusal below exists to prevent. `.#` is - # the only in-suffix name a TOOL writes (a vim swapfile is - # `.secondary.env.swp` and an Emacs autosave is `#secondary.env#` — - # both fail the `.env` suffix test above and never reach here), so - # every other dotted name is one a human could have chosen and stays - # an ERROR. The refusal's stated intent — "a file the operator wrote - # and would otherwise get no message about" — is what picks the - # boundary, and the `.` version did not honour it. - if path.name.startswith(".#"): - continue - alias = path.name[: -len(INSTANCE_SUFFIX)] - # 🔴 A FILE THAT CANNOT BE AN INSTANCE IS AN ERROR, NOT A SKIP. Skipping - # it would leave the operator with a file they wrote, a store they think - # is configured, and no message anywhere — and the scopes they routed to - # it would refuse later, naming the ALIAS, which points at the table - # rather than at the file that was ignored. - if not valid_alias(alias) or alias == DEFAULT_ALIAS: - raise RoutingConfigError( - f"`{path}` does not name a usable instance alias. An alias becomes " - f"a directory name under the cache root, so it is lowercase " - f"letters, digits and hyphens only, and `{DEFAULT_ALIAS}` is " - f"reserved for the default instance's own config file — one alias " - f"with two config sources is a store nobody can point at." - ) - extra.append(Instance(alias=alias, config_path=path)) - - instances.extend(extra) - - path, explicit = routes_file(env) - routes: dict[str, str] | None = None - source: Path | None = None - if path.exists(): - routes = load_routes(path) - source = path - elif explicit: - raise RoutingConfigError( - f"${ROUTES_ENV} names `{path}`, which does not exist. A configured " - f"table that cannot be read is an error, not an absence of routing — " - f"treating it as 'no table' would silently turn a fail-loud " - f"configuration into a fail-open one." - ) - return Routing(instances=tuple(instances), routes=routes, routes_source=source) - - -def routing_for( - routes: Mapping[str, str], - aliases: tuple[str, ...] | set[str] | list[str], -) -> Routing: - """A `Routing` over an alias list and a table, with no filesystem involved. - - 🔴 IT EXISTS SO THE GRADER AND THE RESOLVER CANNOT BE TESTED SEPARATELY. - `Routing.check` asks `Routing.alias_for` for the unconfigured-alias - direction, so a test that wanted to grade a table without discovering a host - would otherwise have had to re-implement one of them. The config paths are - the placeholders they are because nothing on either path reads them: an - `Instance` carries an alias and the file its credentials come from, and - routing never opens that file. - """ - return Routing( - instances=tuple(Instance(alias=a, config_path=Path(os.devnull)) - for a in sorted(set(aliases))), - routes=dict(routes), - routes_source=None, - ) diff --git a/lib/entry_shape.py b/lib/entry_shape.py deleted file mode 100644 index ec32a9aa..00000000 --- a/lib/entry_shape.py +++ /dev/null @@ -1,1414 +0,0 @@ -#!/usr/bin/env python3 -"""The vocabulary a cairn READER and any WRITER must agree on. - -🔴 THIS MODULE EXISTS SO THERE IS ONE SPELLING, NOT TWO. A reader and a writer -that disagree about which scope directory they mean is a silent, total failure: -the writer accrues entries under one name and the reader surfaces an empty scope -under another, which renders as "nothing recorded yet" and is indistinguishable -from the ordinary case. Everything here is imported by both halves rather than -re-typed in each. - -It holds the scope-derivation rule, the per-host caveat, the entry headings, and -the error taxonomy. It deliberately holds no I/O policy and no store layout: a -writer decides where it writes, and this module only decides what things are -called. -""" -from __future__ import annotations - -import os -import re -import subprocess -from dataclasses import dataclass -from pathlib import Path -from typing import Iterable, Sequence - -from host_identity import this_host -from subsystem_resolver import ( - NUANCE_HEADING, - POINTERS_HEADING, - TAKE, - UNREACHABLE_MARKER, - WHAT_HEADING, - action_for, - classify_path, - extract_sections, - line_mentions_marker, - line_openness, - normalize_ref, - parse_journal_bullets, - scan_headings, -) -# 🔴 THE LOADER'S OWN ACTION TABLE, IMPORTED PRIVATE RATHER THAN RE-DECIDED — see -# `_nuance_body`. The advisories must read EXACTLY the set of paths `load_index` -# reads: narrower and they print a zero over a file the loader counted, wider and -# they `open()` a fifo the loader refused. Either way the second copy of the rule -# is what drifts, so there is no second copy. -from subsystem_resolver import _LOADER_ENTRY_ACTIONS # noqa: E402 -# 🔴 THE READER'S OWN FENCE PREDICATE, IMPORTED PRIVATE RATHER THAN RE-SPELLED. -# `_is_fence` knows both ``` and ~~~; a hand-spelled copy that knew only the -# first would report a ~~~-fenced sample line as lost content, and the -# scanners below would then disagree with `parse_journal_bullets`, which is the -# function that decides what a reader can actually see. Importing an underscore -# name across modules is deliberate here: a second copy of this predicate is the -# duplicated rule, and the Go port makes the same call (`store.IsFence`). -from subsystem_resolver import _is_fence # noqa: E402 - -__all__ = [ - "CairnError", "GitError", "RepoPathMissingError", "StoreMissingError", - "BULLET_TEXT_MAX", "SHAPE_HEADINGS", "STORE_IS_PER_HOST", - "STORE_IS_ONE_INSTANCE", - "TAG_VOCABULARY", "tag_outside_vocabulary", - "DROPPED_LINE", "UNREACHABLE_MARKER", - "SHAPE_ABSENT", "SHAPE_RENAMED", "SHAPE_DUPLICATED", "SHAPE_EMPTY", - "SHAPE_INVENTORY_SHOWN", - "DroppedLineFinding", "UnreachableMarkerFinding", "ShapeFinding", "OpenAction", - "derive_scope", "repo_path_missing_message", "scope_for_repo", - "store_caveat", "store_host", "store_host_line", - "line_carries_marker", "scan_dropped_lines", "scan_unreachable_markers", - "scan_entry_shape", "scan_open_actions", - "validation_advisory_lines", -] - - -# -------------------------------------------------------------------------- -# Errors -# -------------------------------------------------------------------------- - -class CairnError(Exception): - """Base for every error this module raises.""" - - -#: Kept as an alias because the writer half historically raised `TouchError` and -#: callers match on the class. Renaming without an alias would be a silent -#: behaviour change for any `except` clause naming the old spelling. -TouchError = CairnError - - -class GitError(CairnError): - """A git invocation failed. Sentinel: 'git command failed'. - - 🔴 `stderr` IS CARRIED AS AN ATTRIBUTE, NOT ONLY INSIDE THE MESSAGE, so a - WRAPPING error can quote git's own words WITHOUT embedding this class's - sentinel in its own text. Without that, a wrapper's message carries two - sentinels at once and "which guard fired" stops being measurable. - """ - - def __init__(self, message: str, *, stderr: str = "") -> None: - super().__init__(message) - self.stderr = stderr - - -class StoreMissingError(CairnError): - """The store root does not exist. Sentinel: 'store root not found'.""" - - -class RepoPathMissingError(CairnError): - """`--repo` names something that is not a directory. - - Sentinels: 'repo path does not exist' when nothing is there, 'repo path is - not a directory' when something is. TWO, because they are two mistakes with - two next moves — see `repo_path_missing_message`. - - 🔴 ITS OWN SENTINEL, NOT `git command failed`. "The repo path does not exist" - is a first-class READING the caller can act on, while `GitError`'s sentinel - is a true statement about the subprocess and a useless one about the - argument. `--repo` takes a PATH resolved against the cwd, so a bare repo NAME - silently becomes `$PWD/` — and a raw git error names neither that rule - nor the way out. It matters more than wording usually does: this is the - store's primary read surface, and a prescribed first command that answers - with a git internals dump is how a store goes unread. - """ - - -# -------------------------------------------------------------------------- -# Entry shape -# -------------------------------------------------------------------------- - -#: The two headings every entry is built from. Re-exported here so a writer does -#: not import them from the renderer, and pinned as a tuple so a reader can -#: assert the set rather than two separate strings. -SHAPE_HEADINGS: tuple[str, ...] = (POINTERS_HEADING, NUANCE_HEADING) - -#: The longest `text` an append may carry, in characters. -#: -#: 🔴 WHAT THIS IS **NOT**, BECAUSE BOTH READINGS ARE AVAILABLE AND BOTH ARE -#: WRONG — AND THE VALUE SAT HERE UNJUSTIFIED LONG ENOUGH THAT "RAISE IT" READ AS -#: THE OBVIOUS FIX: -#: -#: * NOT an integrity constraint. Nothing about a long `text` can corrupt the -#: bullet or its attribution trailer; that hazard is one bullet becoming two, -#: or a trailer that reads as somebody else's, and it is closed by the -#: line-break and character-category predicates in the server — measured -#: failures, each with its own comment. Length breaks nothing. -#: * NOT a resource bound. The request body is already capped (1 MiB) and -#: bounded in time by the server's drain deadline, and this value is three -#: orders of magnitude below that cap. Deleting it would not widen the -#: server's exposure by one byte. -#: * NOT a bound on what a READ costs, which is the plausible one. A recall -#: prints an entry's nuance bullets in FULL and the bullet COUNT is STILL -#: uncapped — re-measured on one live store of 331 entries: median 5, p90 21, -#: **one entry holds 151** — so worst-case read cost is count × this value and -#: the count is the free variable. Capping the text cannot bound a product -#: whose other factor is unbounded. -#: ⚠ THAT FREE VARIABLE IS NOW SURFACED BUT STILL NOT BOUND, AND THE -#: DISTINCTION IS THE WHOLE POINT. `subsystem_recall.NUANCE_BULLET_CEILING` -#: (30) renders an ADVISORY index badge on an entry over it — it refuses -#: nothing, rewrites nothing and caps nothing, so every sentence above stays -#: true. What changed is only that a reader can SEE the count is extreme; the -#: product is as unbounded as it was. The earlier `111` is kept nowhere: it -#: was a measurement of the same class and the store grew past it, which is -#: itself the argument against treating either number as a bound. -#: -#: 🔴 WHAT IT IS: an EDITORIAL tripwire on the tail, and the number is the p99 of -#: the corpus the store already holds. Measured over 2,211 dated bullets: median -#: 629, p90 1,418, p95 1,746, **p99 2,049**, longest 4,015. So this value fires -#: on roughly the densest 1% and on nothing else, and what it says to a writer is -#: "a bullet this long is a document, and a document belongs in an entry's prose -#: or its own entry, not in one line of work-history". That is a curation -#: judgement rather than a safety property — which is exactly why it has to be -#: WRITTEN DOWN as one. An unexplained constant invites being raised to a second -#: unexplained constant. -#: -#: ⚠ THE UNIT IS THE CALLER'S `text`, AND MEASURING THE STORED BULLET INSTEAD -#: OVERSTATES THE TAIL BY ~2×. The server prepends `- : ` and appends the -#: attribution trailer, so a stored line is longer than the `text` that produced -#: it: over this same corpus, 27 bullets (1.2%) exceed 2,000 characters measured -#: as `text`, against 48 (2.2%) measured as stored bytes. A reading of "how many -#: existing bullets would this cap reject" must use the former; the latter counts -#: characters no caller ever sent. -#: -#: Existing over-cap bullets are GRANDFATHERED, deliberately and permanently: -#: this value gates WRITES only, nothing in the API rewrites a bullet that is -#: already stored, and those bullets are the densest records in the store. -#: Shortening them to satisfy a constant would be the cap deciding the content. -#: -#: To justify a DIFFERENT number, the thing to measure is not the corpus again — -#: it is whether a reader's comprehension actually falls off somewhere, or a -#: per-entry read budget with the bullet count capped alongside. Re-measuring the -#: same distribution can only ever re-derive a percentile. -#: ⚠ HALF OF THAT SECOND OPTION NOW HAS A MEASUREMENT AND THE OTHER HALF DOES -#: NOT. The bullet-count distribution is measured, and the cost curve it implies -#: is written at `subsystem_recall.NUANCE_BULLET_CEILING` / `report.NuanceBulletCeiling` -#: — read it there rather than re-deriving it. What is still unmeasured is the -#: READ BUDGET itself: nothing bounds a digest, which prints the whole index plus -#: ONE featured body in full, and on a real store that single body measured 97.6% -#: of the read. So "a per-entry read budget with the bullet count capped -#: alongside" remains OPEN as stated; only the distribution behind it is settled. -BULLET_TEXT_MAX = 2000 - -#: The CLOSED set of `tags:` front-matter values a WRITE may land. The axis is the -#: technical DOMAIN an entry belongs to, which is deliberately a different question -#: from `KINDS` (service/process/org/doc — what SHAPE of thing the entry describes); -#: an entry carries one value from each, and neither set refines the other. -#: -#: 🔴 IT WAS FOUR TERMS FOR ONE ROUND, AND THE FOURTH FALSIFIED THE SENTENCE ABOVE. -#: `client-work` shipped in the first draft beside these three and is REMOVED: `infra`, -#: `product` and `tooling` all answer "what KIND of work is this", while `client-work` -#: answers "WHO is it for" — a second axis. Under the one-tag-per-entry rule -#: (`entry_has_tag`'s scalar operand) a set mixing two axes makes both unassertable, -#: which is the identical objection this repository already records against putting the -#: category axis into `kind:`. The "who" question was also already answered elsewhere: -#: the SCOPE name carries it, so the fourth term largely restated the directory an entry -#: lives in. Dropping a term is the direction that can refuse a write somebody used to -#: be able to make, so it was taken on an operator decision with the live store -#: re-tagged first. -#: -#: 🔴 IT LIVES IN THE WRITER'S MODULE AND NOT IN `subsystem_resolver`, AND THE REASON -#: IS A MEASURED OUTAGE RATHER THAN TASTE. `SubsystemEntry.from_mapping` is the READER. -#: A refusal there makes the entry MALFORMED, and a malformed entry is out of the -#: index, out of `--ref`, out of `--search` AND UNWRITABLE — every write route resolves -#: its target THROUGH the index, so `PUT` and `POST .../bullets` answer 404 for it. A -#: vocabulary check in the reader would therefore take every entry already carrying an -#: off-vocabulary tag and make it unreadable and unrepairable in the same stroke: a -#: store-wide outage caused by the guard, not by the data. -#: -#: 🔴 AND THE SPLIT IS ENFORCED BY THE IMPORT GRAPH RATHER THAN BY THIS COMMENT. This -#: module imports `subsystem_resolver` at module scope, so a back-import is a CYCLE and -#: the reader cannot reach this tuple. That is the whole reason it is not a sibling of -#: `KINDS`: a constant the reader can see is a constant a later edit can wire into -#: `from_mapping`, and the refusal that edit produces is the outage above. -#: -#: ⚠ SORTED, AND THAT IS PART OF THE REFUSAL'S CONTRACT RATHER THAN TIDINESS. The -#: message joins this tuple with `|`; `internal/write`'s `tagVocabulary` joins its own -#: slice the same way; `tests/conformance/` compares the two servers' response bytes -#: for a `PUT` carrying an off-vocabulary tag. Reordering or extending one side alone is -#: a RED corpus, not a review comment — `tests/test_tag_vocabulary.py` is the cheaper -#: red that says which side moved. -TAG_VOCABULARY: tuple[str, ...] = ("infra", "product", "tooling") - - -def tag_outside_vocabulary(tags: "Sequence[str]") -> str | None: - """The FIRST tag not in `TAG_VOCABULARY`, or `None` if every tag is in it. - - 🔴 IT TAKES THE FOLDED SET, NEVER THE RAW FRONT MATTER, so `tags: [Infra]` and - `tags: [infra]` are the same write. `SubsystemEntry.from_mapping` has already - lowercased, folded through `normalize_ref`, deduped and SORTED by the time this - sees it — which is also what makes "the first offender" deterministic: one body - cannot name one tag on this run and a different one on the next, and the two - servers handed one body name the same tag. There is no separate operand normaliser - here for the same reason `entry_has_tag` has none: one fold, applied once, on the - side that owns the spelling. - - ⚠ ONE TAG REPORTED, NOT THE SET. An operator fixes the front matter one line at a - time and the next write re-runs this check, so a list adds bytes to the refusal - without adding a decision to it. - """ - for tag in tags: - if tag not in TAG_VOCABULARY: - return tag - return None - -#: 🔴 PRINTED UNDER EVERY `store:` LINE, AND IT IS LOAD-BEARING. The CACHE is -#: per-host: two machines can hold the same scope with different entries in it -#: at any given instant, because each converges on the hosted store only when -#: `cairn sync` runs there. A verdict printed without naming the host it read is -#: therefore not a smaller claim than the truth — it is a different, false one -#: ("the store has no X" instead of "this disk has no X, as of its last sync"). -#: -#: 🔴 THE FIRST CLAUSE USED TO READ "PER-HOST AND UNREPLICATED", AND THAT IS THE -#: DEFECT THIS WORDING EXISTS TO CORRECT. Since the Cairn cutover the hosted pod -#: is the canonical datastore and `~/.cache/subsystem-store` is a SYNCED -#: READ-THROUGH CACHE of it, so content written on one machine does reach the -#: other. Observed, not inferred from config: within one session that wrote -#: nothing, the pod's own snapshot moved `entry-files=232` -> `239` between two -#: reads about an hour apart. "Unreplicated" told readers an absence here was an -#: absence everywhere, and that false sentence propagated into a downstream -#: handoff doc before it was caught. -#: -#: The SECOND clause is untouched and still exactly true: the reader is offline -#: against the local cache and contacts no pod and no peer. What bounds it is -#: FRESHNESS, not isolation — an entry written elsewhere and not yet synced here -#: is invisible, and that is the honest caveat to print. -#: -#: 🔴 THE MULTI-INSTANCE CASE IS NOW HANDLED, AND IT IS HANDLED BY -#: `store_caveat`, NOT BY EDITING THIS STRING. The warning that used to sit here -#: said "whoever adds multi-instance routing must rewrite this string in the -#: same change", and the FIRST half of that is right: with several instances -#: configured an absence is also explainable by "that scope lives on another -#: instance", and a reader told only that the cache is per-host draws the wrong -#: conclusion. The second half — rewrite THIS constant — is what the code -#: measured wrong, and the reason is worth keeping because it is not obvious: -#: -#: * this sentence is BYTE-MIRRORED across the tree, and the count is bigger -#: than it looks. Enumerated over `git ls-files` at `38b358d`: **25 files, -#: 92 occurrences** — the Go port (`internal/hostid/hostid.go`), the reader -#: fixture the Go renderer is compared against -#: (`internal/report/testdata/reader_fixtures.json`, 64 of those -#: occurrences), **20 of the 98** `tests/conformance/golden/*.json` (24), -#: this file, `server/README.md` and `tests/test_subsystem_recall.py`. Two -#: of those are regenerate-and-diff gates and one is prose in an operator -#: README, which no gate covers at all. -#: -#: ⚠ THIS COMMENT SAID "a four-place change" AND THAT WAS WRONG BY 2×, in -#: the direction that makes the change look cheap: it counted the four -#: mirror KINDS and read as a count of SITES. Re-derive rather than trusting -#: the number — it moves whenever a golden is regenerated: -#: git ls-files | xargs grep -c 'PER-HOST CACHE' 2>/dev/null | grep -v ':0$' -#: (use a real `grep` binary; a `.gitignore`-aware wrapper is blind to -#: generated trees, and `git ls-files` is what makes the population the -#: TRACKED one rather than whatever is on disk); -#: * and it would change the bytes of every SINGLE-instance recall, on every -#: host, to warn about a second instance that does not exist there. -#: -#: So the caveat became a FUNCTION of the instance context: unchanged where -#: there is one instance (the server, the goldens, every existing host), and -#: extended — at the point of rendering — where there is more than one. The -#: clause below is the extension. -STORE_IS_PER_HOST = ( - "the store is read through a PER-HOST CACHE, only as fresh as its last sync; " - "this run read THIS machine's disk and consulted no other" -) - -#: The clause the caveat gains when this host is configured with more than one -#: instance. `{instance}` is the alias this run read. -#: -#: 🔴 IT NAMES THE INSTANCE, NOT JUST THE FACT OF ROUTING. "several instances -#: exist" leaves the reader with the same question they started with; the alias -#: is what makes an absence actionable — it says which store was consulted, so -#: "look on the other one" is a command they can type. -STORE_IS_ONE_INSTANCE = ( - "and this run read the `{instance}` instance ONLY — with more than one " - "instance configured, an absence here is also explainable by the scope " - "living on another instance, so it is NOT an absence from the fleet" -) - - -def store_host() -> str: - """THIS machine's identity — the ONE call site of `host_identity.this_host`. - - 🔴 A SINGLE SEAM FOR EVERY CONSUMER. Callers import THIS rather than - `this_host` itself, so the name is looked up in this module's globals - wherever it is called from: one injection point makes reader and writer - agree, and a test needing byte-stable output patches one thing instead of - two that can drift apart. - """ - return this_host() - - -def store_caveat(instance: str | None = None) -> str: - """The per-host caveat, extended when this host reads more than one instance. - - 🔴 `None` IS THE SINGLE-INSTANCE CASE AND MUST STAY BYTE-IDENTICAL. The - server renders with no instance context, and so does every client on a host - with one instance configured; both produce exactly the sentence this - module's readers, its Go port and two generated corpora already agree on. - A caller passes an alias only when there IS more than one place the answer - could have come from. - """ - if instance is None: - return STORE_IS_PER_HOST - return f"{STORE_IS_PER_HOST}, {STORE_IS_ONE_INSTANCE.format(instance=instance)}" - - -def store_host_line(indent: str = " ", *, instance: str | None = None) -> str: - """`host: ()` — printed under every `store:` line.""" - return f"{indent}host: {store_host()} ({store_caveat(instance)})" - - -# -------------------------------------------------------------------------- -# Scope derivation -# -------------------------------------------------------------------------- - -def _git(repo: Path, args: Sequence[str]) -> str: - argv = ["git", "-C", str(repo), *args] - env = dict(os.environ) - # Read-only invocations must not take the index lock: another process in the - # same checkout is a normal case, and a helper that can block someone else's - # commit is not read-only in the way that matters. - env["GIT_OPTIONAL_LOCKS"] = "0" - proc = subprocess.run(argv, capture_output=True, text=True, env=env) - if proc.returncode != 0: - raise GitError( - f"git command failed ({' '.join(argv)}): exit {proc.returncode}: " - f"{proc.stderr.strip() or '(no stderr)'}", - stderr=proc.stderr.strip(), - ) - return proc.stdout - - -def _toplevel(repo: str | Path) -> Path: - """The repo ROOT for a directory that may be anywhere inside it. Runs git. - - 🔴 ONE FRAME, ONE CALL SITE. Open-coding this is how two callers end up with - two different path frames in one path set: `diff`/`diff-tree` are always - repo-root-relative while `ls-files --others` is cwd-relative AND cwd-scoped, - so a caller passing a subdirectory gets components both manufactured and lost. - """ - return Path(_git(Path(repo), ["rev-parse", "--show-toplevel"]).strip()) - - -def derive_scope(repo_root: str | Path, git_common_dir: str | Path) -> str: - """The store scope for a repo, normalized. Worktree-stable. - - `git_common_dir` is `git rev-parse --path-format=absolute --git-common-dir`: - for BOTH a base clone and any worktree of it that is the base clone's `.git`, - so its parent is the repo everyone means. `--show-toplevel` is not used for - this because in a worktree it is the worktree's own directory. - - Fallback: when the common dir is not literally named `.git` — a bare repo, or - a submodule whose common dir is `/.git/modules/` — the parent - basename would be meaningless (`modules`), so the repo root's basename is - used instead. Stated because the fallback is otherwise silent. - """ - common = Path(git_common_dir) - if common.name == ".git": - return normalize_ref(common.parent.name) - return normalize_ref(Path(repo_root).name) - - -def repo_path_missing_message( - given: str | Path | None, - resolved: str | Path, - *, - store_root: str | Path | None = None, -) -> str: - """The ONE spelling of "that `--repo` value is not a directory". READ-ONLY. - - 🔴 ONE PLACE, EVERY CLI — the same reason the scope RULE lives in one - function: a reader and a writer that disagree here send two operators to two - different remedies for one mistake. - - `given` is the RAW value the caller typed and `resolved` is what it became. - Both are printed when they differ, because the cwd-join is the whole defect: - seeing only the resolved path leaves "where did that prefix come from?" - unanswered, and that is the question the reader actually has. `given` is None - for internal callers that never had a raw string. - """ - given_s = str(given) if given is not None else str(resolved) - resolved_s = str(resolved) - # 🔴 TWO SPELLINGS, because they are two different mistakes. A path that is - # absent and a path that exists as a FILE need different next moves, and - # telling someone their `notes.md` "does not exist" while they are looking at - # it is the kind of confidently-wrong line that makes a reader distrust the - # rest of the message. - lead = ( - "repo path does not exist" if not Path(resolved_s).exists() - else "repo path is not a directory" - ) - # 🔴 THE PARENTHETICAL IS ABOUT A *RELATIVE* INPUT — not about the two strings - # merely differing. They also differ when an ABSOLUTE path resolves through a - # SYMLINK, and telling that caller their absolute path "is resolved against - # the current directory" is a false statement in the one message whose entire - # job is to be accurate about their mistake. - joined_from_cwd = not Path(given_s).is_absolute() - if given_s == resolved_s: - head = f"{lead}: '{resolved_s}'." - elif joined_from_cwd: - head = ( - f"{lead}: '{given_s}' → '{resolved_s}' " - f"(a bare name is resolved against the current directory)." - ) - else: - head = f"{lead}: '{given_s}' → '{resolved_s}'." - remedy = ( - "--repo takes a PATH, not a repo NAME. Pass an absolute path, or " - "--scope , which names the store directory directly and runs no " - "git at all." - ) - hint = "" - if store_root is not None: - candidate = normalize_ref(Path(given_s).name) - if (Path(store_root) / candidate).is_dir(): - hint = f" Did you mean --scope {candidate}?" - return f"{head} {remedy}{hint}" - - -def scope_for_repo( - repo: str | Path, - *, - store_root: str | Path | None = None, - given: str | Path | None = None, -) -> str: - """Ask git where `repo` really lives, then `derive_scope` it. Runs git. - - 🔴 ONE SCOPE-DERIVATION CALL SITE, not two. The READ half and any WRITE half - need exactly the same answer; see this module's docstring for what disagreeing - costs. - - 🔴 THE NON-DIRECTORY CASE IS CHECKED BEFORE GIT RUNS, and belongs HERE for the - same reason the scope rule does — this is the one seam both halves cross, so a - guard placed in the reader alone would leave the writer answering the identical - mistake with an identical git dump. `store_root` and `given` exist only for the - message: `given` carries the raw pre-`resolve()` string so the cwd-join is - visible, and `store_root` is what lets the refusal name the scope the caller - probably wanted. Both default to None so every call site keeps working, at a - slightly poorer message rather than a TypeError. - """ - repo = Path(repo) - if not repo.is_dir(): - raise RepoPathMissingError( - repo_path_missing_message(given, repo, store_root=store_root) - ) - common = _git( - repo, ["rev-parse", "--path-format=absolute", "--git-common-dir"] - ).strip() - return derive_scope(_toplevel(repo), common) - - -# -------------------------------------------------------------------------- -# The WRITE-PROTOCOL advisories: content a reader cannot reach -# -------------------------------------------------------------------------- -# -# 🔴 THESE CHECKS ARE WHY `validate` IS THE POST-WRITE CHECK AND NOT ONLY A -# PARSE CHECK. The count line above them answers "would the loader accept these -# files?", and a file can pass that while holding text NO reader will ever -# surface. `dropped lines:` is the half that means content is ALREADY LOST. -# -# 🔴 NOT ONE OF THEM MOVES THE VERDICT, AND THAT IS NOT TIMIDITY. `validate` -# answers one question and the write protocol branches on its EXIT CODE to mean "write -# NOTHING". Failing here would stop a session recording anything into an entry -# whose only defect is that an OLDER write lost a line — which makes the store -# lossier, not safer. They are reported loudly and change no code. - -DROPPED_LINE = "dropped-line" -"""The reason token for a nuance line that reaches NO bullet. - -A population of its own, and the one furthest from every other: the openness -shapes are all readings OF a bullet, so each is about content a reader can at -least see. This is content the file HOLDS and no reader can reach at all — -`parse_journal_bullets` drops text that precedes the first bullet, so those lines -are in the entry, in the store, in the backup, and in no consumer's output. -""" - - -@dataclass(frozen=True) -class UnreachableMarkerFinding: - """One bullet carrying a correctly-spelled marker where no parser looks. - - 🔴 DELIBERATELY NOT AN OPENNESS POPULATION. `JournalBullet.openness_population` - partitions bullets by a reading of their OPENING line; this is a fact about - lines 2..n, and the bullet it is about is usually `none` — a bullet that - declared nothing. Carried in its own field, counted in its own key and - rendered in its own block, so there is no place it could be added to a - near-miss total: a near-miss is a marker MIS-SPELLED where the parser looks - and is fixed by editing that line, this is a marker spelled CORRECTLY where - the parser never looks and is fixed by promoting it to a bullet of its own. - One count covering both would send half the readers to the wrong remedy. - """ - - filename: str - bullet_first_line: str - """The bullet's OPENING line — what a reader will search the file for.""" - - offset: int - """1-based line index WITHIN the bullet. Always >= 2.""" - - line: str - """The continuation line carrying the marker, verbatim.""" - - openness: str - """`open` | `resolved` — what it would have declared at a bullet's head.""" - - -@dataclass(frozen=True) -class DroppedLineFinding: - """One `## Nuance / work-history` line that belongs to no parsed bullet. - - 🔴 THE SHAPE, AND WHY IT IS NOT `UnreachableMarkerFinding`. That one is a - marker on a line that IS inside a bullet — the bullet is read, the marker is - not. This is a line inside NO bullet: nothing about it is read, marker or - otherwise. The remedies differ for the same reason the populations do — an - unreachable marker is fixed by PROMOTING one line, a dropped line by - restoring the bullet opening that used to sit above it. - - 🔴 MEASURED IN THE FIELD, NOT HYPOTHETICAL. Over every committed version of - every entry file in a live store of several hundred entries, seven versions - carried dropped lines — two entries whose whole bullet block had been - indented, each broken for days. One of them held a `OPEN:` that raised no - badge for the whole of that window, and would still raise none, because every - marker reader here anchors at position 0; see `line_carries_marker`. - """ - - filename: str - offset: int - """1-based line index within the `## Nuance / work-history` section body.""" - - line: str - """The dropped line, verbatim.""" - - carries_marker: bool = False - """The line looks like it declared `OPEN:`/`RESOLVED:`. - - Recorded because it changes the URGENCY and nothing else: a dropped line is - lost content either way, but a dropped DECLARATION is an open action the - store is actively failing to report. It is never counted as an open action — - the bullet it belonged to no longer exists, so there is nothing to declare - it ON. - """ - - -def line_carries_marker(line: str) -> bool: - """Does this dropped line carry an `OPEN:`/`RESOLVED:` declaration? - - 🔴 IT RESTATES NO GRAMMAR. It asks `line_openness` — which runs the same - `_bullet_openness` that `parse_journal_bullets` calls for a bullet's line 1 — - and falls back to `line_mentions_marker` for a declaration sitting mid-line. - A hand-spelled copy could not stay in step with the real pattern: the - pre-extraction original WAS one, and measured against all seven historical dropped-line - blobs in a live store it was `False` on every one of them, including the - `OPEN:` this feature's own motivating incident cites — while returning True - for the prose `resolved upstream in 1.2.3.`. - - ⚠ `line_mentions_marker` IS THE ONLY PLACE IN EITHER CLIENT THAT LOOKS FOR A - MARKER MID-LINE, and that is deliberate rather than a gap elsewhere: every - marker READER anchors at position 0, so a mid-line `OPEN:` declares nothing - anywhere and did not declare anything while its bullet was intact either. - Widening a reader to match would make this one flag disagree with every - other surface. It may ONLY rank urgency — a dropped line is a finding on its - own and this flag never gates reporting, so a miss costs a word of emphasis, - never a silent pass. - """ - openness, _sha = line_openness(line) - return openness is not None or line_mentions_marker(line) - - -def _scanner_reads_path(path: Path) -> bool: - """Will the advisory scanners OPEN this path? Every one of them, through - `_entry_text`. - - 🔴 THE GATE AND THE DENOMINATOR, SPELLED ONCE, BECAUSE AS TWO THINGS THEY - DISAGREED. `_nuance_body` has always asked the loader's own table before - `open()`; the printed denominator was `len(entry_files_in(...))`, an - unfiltered listing, so the advisories counted files they never read. - """ - return action_for(classify_path(path), _LOADER_ENTRY_ACTIONS) == TAKE - - -def scanned_entry_count(paths: Iterable[str | Path]) -> int: - """How many of `paths` the advisory scanners actually open. - - ⚠ NOT `len(paths)`, AND THE GAP IS THE POINT. A FIFO, a dangling symlink, a - directory or a device inside a scope directory is listed as an entry file and - REFUSED before `open()`. It belongs in the parse line's denominator — the - loader really did try it, and really did report it malformed — and it must - not appear in a denominator that claims text was read. - """ - return sum(1 for path in paths if _scanner_reads_path(Path(path))) - - -def _nuance_body(path: Path) -> str | None: - """The `## Nuance / work-history` body of one entry file, or None. - - 🔴 THE PATH'S KIND IS DECIDED BEFORE IT IS OPENED, THROUGH THE LOADER'S OWN - TABLE. `try: read_text` is NOT tolerance for a path that is not a regular - file, and measuring it was the point: `except OSError` cannot catch a FIFO, - because reading one does not raise — it BLOCKS until somebody writes, and - `validate` never returns. A character device does not raise either; it - streams until the process dies of `MemoryError`, which is not an `OSError` - and propagates. Measured on this tree at the CLI, both clients, against a - cache holding one such path: the FIFO wedged until a `timeout 20` killed it - (124), and a symlink to `/dev/zero` under an address-space limit exited 1 - (Python, bare traceback) and 2 (Go, runtime out-of-memory) — in each case - abandoning every scope after the bad one, where the same tree one commit - earlier reported the file as malformed and exited 5. - - `load_index` never had that exposure: it refuses `other`, `link-to-other`, - `broken-link`, `directory` and `link-to-dir` before `open()`, for exactly - this reason (a fifo measured wedging a request thread for 25s). This gate is - that same table — `_LOADER_ENTRY_ACTIONS`, not a fresh predicate — so the - advisories read precisely the paths the loader reads and no others. - - ⚠ THAT SENTENCE IS ABOUT THE SCANNERS, AND IT USED TO BE READ AS COVERING THE - PRINTED DENOMINATOR TOO. It did not: the clients passed the unfiltered - listing to `validation_advisory_lines`, so a scope holding one entry beside a - FIFO printed `0 across 2 entry file(s)` over a file nothing opened. - `scanned_entry_count` is the denominator now, built from this same predicate. - - ⚠ AND THE UNMAPPED-KIND BRANCH DIVERGES FROM THE GO CLIENT. `action_for` - RAISES `AssertionError` here, uncaught; `internal/store.nuanceBody` folds the - same condition into "no nuance section". UNREACHABLE in both — - `TestClassifierIsTotal` and Go's `TestTheActionTablesAreTotal` pin the kind - set against the table two-way — so it is recorded rather than closed. - - ⚠ THE RESIDUAL IS THE LOADER'S RESIDUAL, AND IT IS NOT EMPTY. The kinds the - table TAKES are `regular-file`, `link-to-file`, `indeterminate` and `absent`; - on the last three the read can still fail, and `except OSError` is what turns - that into "contributes nothing". What it does NOT cover is a REGULAR file - whose read is unbounded — a `/proc` file reached through a symlink, say. That - is the loader's own residual ledger (`load_index`), unchanged here and not - widened: this function is now exactly as exposed as the reader beside it, - which is the property worth having. It is not a claim that nothing can raise. - - Deliberately tolerant otherwise: a file with no nuance section yields None. - Every scanner runs BESIDE the parse check, never in front of it — a malformed - file's own rejection is the finding that matters, and an advisory computed - from its half-parsed body would bury it. - - ⚠ EACH ENTRY IS READ FIVE TIMES PER `validate` — once by `load_index` and - once by each of the FOUR scanners — AND THAT IS A DECISION, NOT AN OVERSIGHT. - It was THREE until the shape and open-action scanners landed, and this - comment said so for as long as it took an audit to read it; the DECISION - survived the re-measurement and the numbers did not. - - RE-MEASURED over the same shape of corpus — a synthetic cache of 300 entries - carrying 30 bullets apiece, `validate --no-sync` over one scope, medians of - 27 runs per client interleaved on one loaded dev host:: - - reads/entry 3.00 -> 5.00 (strace `openat`, both clients, identical) - oracle 155.7 ms -> 190.1 ms (+22%) - Go client 39.8 ms -> 62.5 ms - - The earlier figures (118 ms here, 36 ms for the Go client) did NOT reproduce - as absolute numbers — this host is slower and busier than whatever measured - them — so they are replaced rather than adjusted. Caching the body would put - mutable state into functions whose whole contract is READ-ONLY and - independent, to save a few tens of milliseconds on a store an order of - magnitude larger than any real one. The re-read also has one honest property - a cache would remove: each scanner sees the file as it is when IT runs, so a - body that changed mid-command cannot be reported under offsets taken from an - earlier read. - """ - text = _entry_text(path) - if text is None: - return None - return extract_sections(text, (NUANCE_HEADING,)).get(NUANCE_HEADING) or None - - -def _entry_text(path: Path) -> str | None: - """The WHOLE entry file, or None when no scanner may open this path. - - 🔴 THE GATE AND THE READ, SPELLED ONCE FOR EVERY SCANNER. `_nuance_body` - carried both inline until a scanner appeared that needs the whole file rather - than one section (`scan_entry_shape`, which has to see headings the nuance - body cannot contain). A second copy of the gate is the shape this module - already refuses everywhere else: the FIFO and character-device hazards - `_nuance_body` documents are properties of the OPEN, not of the section - extraction, so a scanner that reads the file by a different route inherits - none of the protection. Read `_nuance_body`'s docstring for the measurements - — they apply verbatim to every caller of this function. - """ - if not _scanner_reads_path(path): - return None - try: - return path.read_text(encoding="utf-8", errors="replace") - except OSError: - return None - - -def scan_unreachable_markers( - paths: Iterable[str | Path], -) -> tuple[UnreachableMarkerFinding, ...]: - """Markers typed into a bullet's BODY, where the marker parser never reads. - - 🔴 IT IS A SEPARATE WALK FROM ANY OPEN-ACTION SCAN BY CHOICE. Merging them - would mean deciding what to do with a bullet that declared nothing on its - opening line, and the answer there is "report it, but never as an open - action" — a second population inside a function whose whole contract is a - one-branch precedence. - """ - out: list[UnreachableMarkerFinding] = [] - for p in paths: - path = Path(p) - body = _nuance_body(path) - if body is None: - continue - for b in parse_journal_bullets(body): - for m in b.unreachable_markers: - out.append( - UnreachableMarkerFinding( - filename=path.name, - bullet_first_line=b.first_line, - offset=m.offset, - line=m.line, - openness=m.openness, - ) - ) - return tuple(out) - - -def scan_dropped_lines( - paths: Iterable[str | Path], -) -> tuple[DroppedLineFinding, ...]: - """Nuance lines present on disk that reach no bullet. READ-ONLY. - - 🔴 IT ASKS THE READER'S OWN PARSER AND DERIVES NOTHING ITSELF. The set of - reachable lines is taken from `parse_journal_bullets`' output rather than - re-deduced from a bullet pattern here, so this check cannot drift away from - what consumers actually see. Re-deriving it would be a duplicated predicate - with the checker's worst failure mode: blessing lines the reader drops. - - 🔴 WHAT IT STRUCTURALLY CANNOT SEE — THREE CASES, NOT ONE, and an earlier - version of this paragraph named only the first. The printed zero names all - three (`_dropped_lines_block`), because a caveat the operator never reads is - not a caveat. Each is pinned by an invariant guard in - `tests/test_entry_shape_validate.py` and its Go twin. - - 1. ABSORBED TAIL. A bullet that loses its opening line while ANOTHER - bullet sits above it is not detectable — `parse_journal_bullets` appends - every non-bullet line to the bullet above, so the orphaned tail is - absorbed into it and inherits its date, and the resulting file is - BYTE-IDENTICAL to one where that bullet legitimately wrapped. No check - can separate the two. - 2. UNCLOSED FENCE. `_is_fence` toggles, so an odd count leaves everything - after the last fence marked fenced — and fenced lines are deliberately - skipped as sample text (see below). A bullet swallowed that way yields - NO dropped-line finding and NO bullet, so its `OPEN:` is reported by - nothing at all. This is the one case where the zero is actively - misleading rather than merely partial, which is why it is named first - in the printed caveat's remedy order. - 3. DUPLICATED `## Nuance / work-history` HEADING. `extract_sections` - concatenates same-named sections into one body, so an orphan under the - SECOND heading is absorbed by a bullet from the FIRST, and the offsets - this function reports index the concatenation rather than the file. - - What it DOES cover is the case where the drop is decidable — text before the - first bullet, which includes every entry whose NEWEST bullet lost its head, - the store being newest-first. - """ - out: list[DroppedLineFinding] = [] - for p in paths: - path = Path(p) - body = _nuance_body(path) - if body is None: - continue - # 🔴 REACHABILITY IS KEYED ON (OFFSET, LINE), NOT ON THE LINE ALONE. A - # `set[str]` masks an orphan whose text is byte-identical to any line - # inside any bullet of the same file — and a read-modify-write race, - # which is the shape that produces a decapitated bullet in the first - # place, is exactly what duplicates a block. - reachable: set[tuple[int, str]] = set() - lines = body.splitlines() - cursor = 0 - for b in parse_journal_bullets(body): - for ln in b.lines: - # `parse_journal_bullets` preserves order and never reorders or - # rewrites a line, so a forward scan re-attaches each bullet line - # to its own offset. Trailing blanks it stripped are simply not - # looked for; the skip below treats them as reachable anyway. - while cursor < len(lines) and lines[cursor] != ln: - cursor += 1 - if cursor < len(lines): - reachable.add((cursor + 1, ln)) - cursor += 1 - in_fence = False - for i, line in enumerate(lines, 1): - # 🔴 FENCES ARE SKIPPED, as in the sibling scanner and in - # `parse_journal_bullets` itself. A fenced snippet BEFORE the first - # bullet is sample text, and reporting it would hand the operator the - # remedy "restore the bullet opening line" for content that never had - # one. - if _is_fence(line): - in_fence = not in_fence - continue - if in_fence or not line.strip() or (i, line) in reachable: - continue - out.append( - DroppedLineFinding( - filename=path.name, - offset=i, - line=line, - carries_marker=line_carries_marker(line), - ) - ) - return tuple(out) - - -# -------------------------------------------------------------------------- -# The entry's SHAPE, as opposed to whether its front matter parses -# -------------------------------------------------------------------------- -# -# 🔴 WHY A SHAPE CHECK EXISTS AT ALL. `validate` returned `OK` at exit 0 for an -# entry with all three spine headings renamed, for one with no headings at all, -# and for one whose sections were all empty. Only a missing `service:` went red. -# So the spine every consumer depends on was enforced by NOTHING: it held because -# two skills happen to describe it and one template happens to emit it. -# -# 🔴 AND IT IS NOT COSMETIC. `subsystem_recall` computes an entry's bullet count -# and its `🔴 N OPEN` badge from `extract_sections(...)[NUANCE_HEADING]`, so a -# heading that is renamed — or given a trailing colon, or shifted off column 0 — -# yields an empty body, and the index row a resume consumes renders an entry with -# genuine open actions as a well-formed empty one. The reader names a missing -# heading ON READ; this catches the same thing ON WRITE, in the turn that wrote -# it, which is the difference between "someone eventually notices" and "the -# writer is told". -# -# 🔴 WHICH HEADINGS, AND WHY STILL NOT `## What it is`. The checked set is -# `SHAPE_HEADINGS` — the set whose absence makes a NUMBER wrong. `## What it is` -# IS read: `subsystem_recall` surfaces it in every printed body. But it feeds no -# bullet count and no index badge, so a missing one cannot turn a parse failure -# into a well-formed empty entry the way a missing `## Nuance / work-history` -# can. Flagging it would report a convention with no numeric consequence beside -# two whose consequence is measured, and a writer cannot tell those apart in a -# list. The reader names its absence under the entry's own body, where the person -# reading that entry is already looking. - -SHAPE_ABSENT = "absent" -SHAPE_RENAMED = "renamed" -SHAPE_DUPLICATED = "duplicated" -SHAPE_EMPTY = "empty" - -#: Cap on the heading inventory printed beside an ABSENT finding. A bound, not a -#: filter — the remainder is always counted in the line. -SHAPE_INVENTORY_SHOWN = 6 - - -def _heading_key(heading: str) -> str: - """The LOOSE form, used ONLY to pair a heading with the schema one it missed. - - 🔴 IT NEVER ACCEPTS A HEADING. `extract_sections` matches the exact string and - keeps doing so; folding `## Pointers` and `## pointers` together there would - quietly widen what the store is allowed to look like, which is the opposite of - what this check is for. This exists so the report can say "you wrote - `## pointers`" instead of "the section is absent" — the difference between a - finding a writer can act on in one edit and one that sends them looking for - prose that is already on disk. - - Folds exactly three near-misses: the `#` level, the case and surrounding - whitespace, and a trailing colon. - """ - return re.sub(r"\s+", " ", heading.lstrip("#").strip().rstrip(":").strip()).lower() - - -@dataclass(frozen=True) -class ShapeFinding: - """One way an entry's spine departs from the schema. FOUR DISJOINT KINDS. - - 🔴 THEY ARE NEVER SUMMED, for the same reason `OpenAction`'s populations are - not: they are different facts with different remedies. `renamed` and `absent` - are the same missing section reported at different resolutions — the writer - typed something we can show them, or they did not — and collapsing them would - throw away the only half that is actionable. `duplicated` is a section that IS - parsed, twice, silently merged. `empty` is a section present and unfilled, - which `extract_sections` tracks separately from absent precisely so this can. - - 🔴 `duplicated` AND `empty` ARE NOT MUTUALLY EXCLUSIVE, and neither branch in - `scan_entry_shape` excludes the other: a heading written twice whose merged - body is still blank is BOTH, and reporting one of the two would hand the - writer half a remedy. - """ - - filename: str - heading: str - """The SCHEMA heading this finding is about, always — never the typo.""" - - kind: str - found: tuple[str, ...] = () - """For `renamed`, the near-miss heading(s) actually written; for `absent`, the - file's whole heading inventory, so the writer sees what they wrote instead.""" - - count: int = 0 - """For `duplicated`, how many times the exact heading appears.""" - - -def scan_entry_shape(paths: Iterable[str | Path]) -> tuple[ShapeFinding, ...]: - """Report each entry's spine against `SHAPE_HEADINGS`. READ-ONLY. - - Tolerant in exactly the way the sibling scanners are, and gated the same way: - a path the loader's own table refuses is never opened (`_entry_text`), and a - file that cannot be read contributes nothing rather than raising, because this - runs BESIDE the parse check and never in front of it — a malformed file's own - rejection is the finding that matters. - - 🔴 IT REUSES `extract_sections` AND `scan_headings` AND PARSES NOTHING ITSELF. - Both are views over one walker in `subsystem_resolver`, so this cannot come to - a different conclusion about what a heading is than the reader does — which - would be the worst possible defect in a checker whose entire job is to predict - what the reader will see. - """ - out: list[ShapeFinding] = [] - for p in paths: - path = Path(p) - text = _entry_text(path) - if text is None: - continue - present = extract_sections(text, SHAPE_HEADINGS) - headings = scan_headings(text) - for h in SHAPE_HEADINGS: - if h not in present: - near = tuple(x for x in headings if _heading_key(x) == _heading_key(h)) - out.append( - ShapeFinding( - filename=path.name, - heading=h, - kind=SHAPE_RENAMED if near else SHAPE_ABSENT, - found=near or headings, - ) - ) - continue - # 🔴 BOTH REMAINING KINDS CAN BE TRUE OF ONE HEADING AT ONCE — a - # duplicated heading whose merged body is still empty — so neither - # branch excludes the other and neither is an `elif`. - n = sum(1 for x in headings if x == h) - if n > 1: - out.append( - ShapeFinding( - filename=path.name, heading=h, kind=SHAPE_DUPLICATED, count=n - ) - ) - if not present[h].strip(): - out.append(ShapeFinding(filename=path.name, heading=h, kind=SHAPE_EMPTY)) - return tuple(out) - - -# -------------------------------------------------------------------------- -# Unfinished business: the four openness populations, as a writer sees them -# -------------------------------------------------------------------------- - -@dataclass(frozen=True) -class OpenAction: - """One bullet `validate` is reporting as unfinished business. - - 🔴 FOUR POPULATIONS, AND THEY MUST NEVER BE ADDED TOGETHER INTO ONE NUMBER. - A `OPEN:` bullet is a claim the WRITER made and is exact, while an unmarked - one is this tool's guess from two measured phrasings and has unknown recall. - Merging them would let a floor masquerade as a count. - """ - - filename: str - declared: bool - """The writer typed `OPEN:`. Exact — not a guess about the prose.""" - - date: str | None - first_line: str - near_miss: bool = False - """The bullet tried to declare a marker and missed the grammar. - - A THIRD population, never folded into either other one: it is not an open - action and not a guess about one, it is a write that did not land. - """ - - unverifiable_closure: bool = False - """A `RESOLVED:` that names no sha, so its claim cannot be checked. - - A FOURTH population. Not a problem — closing an action is the outcome this - whole design wants — but the sha is what separates "closed, and here is the - commit" from an assertion, and only a branch on `resolved_by` makes the field - mean anything. - """ - - -def scan_open_actions(paths: Iterable[str | Path]) -> tuple[OpenAction, ...]: - """Read each entry's journal and collect its unfinished business. READ-ONLY. - - Deliberately tolerant, exactly as the sibling scanners are: a file no scanner - may open, one that cannot be read, or one with no `## Nuance / work-history` - section contributes nothing rather than raising. This runs BESIDE the parse - check, never in front of it. - """ - out: list[OpenAction] = [] - for p in paths: - path = Path(p) - body = _nuance_body(path) - if body is None: - continue - for b in parse_journal_bullets(body): - # 🔴 ONE BRANCH, ON THE RESOLVER'S SINGLE PRECEDENCE SOURCE. - # Re-deriving membership from the individual predicates here is what - # let a bullet be both a near-miss and an unmarked action on one - # surface while being one thing on another — the duplicated predicate - # `openness_population` exists to remove. - pop = b.openness_population - if pop in ("none", "resolved"): - continue - out.append( - OpenAction( - filename=path.name, - declared=pop == "open", - near_miss=pop == "near-miss", - unverifiable_closure=pop == "unverifiable", - date=b.date, - first_line=b.first_line, - ) - ) - return tuple(out) - - -#: The longest a quoted line runs before it is cut. A finding names a FILE and a -#: LINE NUMBER; the quote is there to recognise it by, and an entry may hold a -#: 4,000-character bullet. -ADVISORY_QUOTE_MAX = 120 - - -def validation_advisory_lines( - *, - n_scanned: int, - shape: Sequence[ShapeFinding], - dropped: Sequence[DroppedLineFinding], - open_actions: Sequence[OpenAction], - unreachable: Sequence[UnreachableMarkerFinding], -) -> tuple[str, ...]: - """The four write-protocol advisory blocks, as lines. UNPREFIXED. - - Each client prefixes every line with its own `cairn: : `, because - `validate` with no `--scope` walks every scope the cache holds and an - unprefixed block would not say which one it is about. - - 🔴 EVERY FINDING SET IS A REQUIRED KEYWORD, NOT A DEFAULT, and that is the - point of the signature. A defaulted `shape=()` would let a client that never - wired the scanner print a confident `entry shape: … each present exactly once` - over files nothing examined — the reassuring zero from an instrument wired to - nothing, arriving through a forgotten argument instead of an empty directory. - Required, a missed call site is a `TypeError` here and a compile error in the - Go port. - - 🔴 THE ORDER IS LOAD-BEARING, IN BOTH ADJACENT PAIRS: - - * `entry shape:` COMES FIRST OF ALL. A renamed `## Nuance / work-history` - makes every one of the three blocks below read an empty section, so their - zeros are facts about a section the parser never reached. Read in the - other order, `open actions: 0 declared` is simply false. - * `dropped lines:` COMES BEFORE `open actions` AND `marker reachability:`. - A dropped line is content NO reader reaches, so neither of those scans - ever sees it — a zero printed above a `🔴 N DROPPED LINE(S)` reads as a - reassurance it cannot support. - - 🔴 EVERY BLOCK PRINTS ITS DENOMINATOR EVEN WHEN IT FINDS NOTHING. A bare zero - is indistinguishable from a scanner wired to nothing, and three of these four - have a SECOND way to be vacuous that the zero must not hide: they read only - `## Nuance / work-history`, so an entry whose heading is renamed contributes - zero to all three for a reason only the SHAPE block can state. The shape - block's own zero carries the SET it checked for the mirror-image reason — a - reader who assumes the third spine heading was checked would take it as a - claim about a heading nothing examined. - - 🔴 AND WHEN NOTHING WAS CHECKED THE BLOCKS DO NOT PRINT AT ALL — one - `NOT CHECKED` line prints instead, naming all four. "0 across 0 entry - file(s)" is the reassuring zero from an instrument that walked nothing, and it - must not render anywhere near a clean-looking count. - """ - if n_scanned == 0: - return ( - f"write-protocol advisories: NOT CHECKED — 0 entry file(s) scanned, so " - f"a zero here would be a zero over nothing. This withholds ALL FOUR " - f"blocks — entry shape, dropped lines, open actions and marker " - f"reachability. [{DROPPED_LINE}] [{UNREACHABLE_MARKER}]", - ) - return tuple( - _entry_shape_block(n_scanned, shape) - + _dropped_lines_block(n_scanned, dropped) - + _open_actions_block(n_scanned, open_actions) - + _reachability_block(n_scanned, unreachable) - ) - - -def _entry_shape_block( - n_scanned: int, shape: Sequence[ShapeFinding] -) -> list[str]: - """The SHAPE advisory. Prints on every path that SCANNED something. - - 🔴 IT PRINTS ITS DENOMINATOR EVEN WHEN IT FINDS NOTHING, AND IT PRINTS WHICH - HEADINGS IT LOOKED FOR. A reassuring zero is indistinguishable from an - instrument wired to nothing unless it carries the size of what it looked at — - and here it must also carry the SET it looked at, because a reader who assumes - the third spine heading was checked would take this zero as a claim about a - heading nothing examined. - - 🔴 THE FOUR KINDS ARE RENDERED SEPARATELY AND NEVER SUMMED — see - `ShapeFinding`. Each KIND names its own remedy, and `renamed`'s ("you wrote - this, the schema says that") is the only one a writer can act on in a single - edit. - """ - spine = ", ".join(f"`{h}`" for h in SHAPE_HEADINGS) - absent = [s for s in shape if s.kind == SHAPE_ABSENT] - renamed = [s for s in shape if s.kind == SHAPE_RENAMED] - duplicated = [s for s in shape if s.kind == SHAPE_DUPLICATED] - empty = [s for s in shape if s.kind == SHAPE_EMPTY] - if not shape: - return [ - "", - f"entry shape: {n_scanned} entry file(s) checked for {spine} — each " - f"present exactly once and non-empty. 🔴 `{WHAT_HEADING}` is NOT checked " - f"here: the reader DOES surface it, but it feeds no count and no badge, " - f"so its absence changes nothing this zero is about — `subsystem_recall` " - f"names a missing one under that entry's own body instead." - ] - out = [ - "", - f"entry shape across {n_scanned} entry file(s), checked for {spine} " - f"(NOT `{WHAT_HEADING}`, which feeds no count and no badge):" - ] - if renamed: - out.append( - f" 🔴 {len(renamed)} section(s) RENAMED — the heading is close but not " - f"exact, so NO reader reaches the section. Matching is exact-string after " - f"a right-strip, case-sensitive, at column 0. On that entry's index row " - f"this reads as `0 nuance` with no `OPEN` badge: PARSE FAILURE, not an " - f"empty entry." - ) - for s in renamed: - wrote = ", ".join(f"`{h}`" for h in s.found) - out.append(f" {s.filename}: `{s.heading}` is written as {wrote}") - if absent: - out.append( - f" 🔴 {len(absent)} section(s) ABSENT — the heading is not in the file at " - f"all, under any spelling this tool can pair with it. Whatever the entry " - f"says on that subject is invisible to every default read. Read the " - f"inventory below against the schema heading: a section retitled far " - f"enough that no folding pairs it lands here rather than under RENAMED." - ) - for s in absent: - shown = list(s.found[:SHAPE_INVENTORY_SHOWN]) - rest = len(s.found) - len(shown) - inventory = ", ".join(f"`{h}`" for h in shown) if shown else "(none at all)" - if rest > 0: - inventory += f", … {rest} more" - out.append( - f" {s.filename}: no `{s.heading}`; the file's headings are {inventory}" - ) - if duplicated: - out.append( - f" 🔴 {len(duplicated)} heading(s) DUPLICATED — the sections silently " - f"MERGE into one body and anything written under a heading BETWEEN them is " - f"dropped from the read entirely. Fold them into one section." - ) - for s in duplicated: - out.append(f" {s.filename}: `{s.heading}` appears {s.count} times") - if empty: - out.append( - f" ⚠ {len(empty)} section(s) PRESENT AND EMPTY — the heading is there " - f"with nothing under it. Not a parse failure and not the same as absent: " - f"the reader finds the section and prints a blank." - ) - for s in empty: - out.append(f" {s.filename}: `{s.heading}`") - out.append( - " (Advisory, and it changes no verdict: the loader accepts a file whose " - "sections it cannot find, which is precisely the silent failure this block " - "exists to make loud. Fix the heading, not the exit code.)" - ) - return out - - -def _open_actions_block( - n_scanned: int, open_actions: Sequence[OpenAction] -) -> list[str]: - """The UNFINISHED-BUSINESS advisory. Prints on every path that SCANNED something. - - 🔴 IT PRINTS ITS DENOMINATOR EVEN WHEN IT FINDS NOTHING, like every sibling. - "0 declared across 29 entry file(s)" is a reading; a blank space is not. - - 🔴 THE FOUR POPULATIONS ARE RENDERED SEPARATELY AND NEVER SUMMED — see - `OpenAction`. `declared` is exact and the unmarked guess is a FLOOR with - unknown recall; one total over both would let the floor masquerade as a count. - """ - declared = [a for a in open_actions if a.declared] - near = [a for a in open_actions if a.near_miss] - unverifiable = [a for a in open_actions if a.unverifiable_closure] - guessed = [ - a for a in open_actions - if not a.declared and not a.near_miss and not a.unverifiable_closure - ] - if not open_actions: - return [ - "", - f"open actions: 0 declared across {n_scanned} entry file(s), 0 " - f"attempted-but-unparsed, 0 `RESOLVED:` naming no sha, and 0 unmarked " - f"bullets matched the two phrasings this tool can recognise. 🔴 The last " - f"of those is a FLOOR with unknown recall, not a clean bill of health — " - f"an unfinished action phrased any other way is invisible here.", - ] - out = ["", f"open actions across {n_scanned} entry file(s):"] - if declared: - out.append( - f" 🔴 {len(declared)} declared `OPEN:` — exact, the writer said so. " - f"Re-check against the repo; if it landed, rewrite as `RESOLVED :`." - ) - for a in declared: - out.append(f" {a.filename}: {a.first_line[:ADVISORY_QUOTE_MAX]}") - if near: - out.append( - f" 🔴 {len(near)} bullet(s) look like an ATTEMPTED marker that did not " - f"parse — they declare nothing and show no badge. Fix the line: the " - f"marker follows `YYYY-MM-DD: `, is upper-case, carries no emphasis or " - f"parenthetical, and ends in `:`." - ) - for a in near: - out.append(f" {a.filename}: {a.first_line[:ADVISORY_QUOTE_MAX]}") - if guessed: - out.append( - f" ⚠ {len(guessed)} unmarked bullet(s) that READ like an open action. " - f"AT LEAST this many — two measured phrasings, unknown recall." - ) - for a in guessed: - out.append(f" {a.filename}: {a.first_line[:ADVISORY_QUOTE_MAX]}") - if unverifiable: - out.append( - f" ⚠ {len(unverifiable)} `RESOLVED:` bullet(s) name no sha, so the " - f"closure cannot be checked. Not a defect — closing is the point — but " - f"`RESOLVED :` is what makes it verifiable rather than asserted." - ) - for a in unverifiable: - out.append(f" {a.filename}: {a.first_line[:ADVISORY_QUOTE_MAX]}") - out.append( - " (Advisory. None of this changes the verdict: an entry with unfinished " - "business is still well-formed, and failing it here would be a red gate " - "nobody could turn green by fixing the file.)" - ) - return out - - -def _dropped_lines_block( - n_scanned: int, dropped: Sequence[DroppedLineFinding] -) -> list[str]: - """The DROPPED-LINE advisory — the half that means content is ALREADY LOST. - - 🔴 THE ZERO CARRIES ITS OWN BLIND SPOT IN WORDS. This check is knowingly - PARTIAL — the absorbed-tail case is undecidable, see `scan_dropped_lines` — - so a bare "0 dropped" would read as "no bullet has lost its head", which is a - claim it cannot make. Saying which half was checked is the difference between - a measurement and a reassurance. - """ - if not dropped: - return [ - "", - f"dropped lines: 0 across {n_scanned} entry file(s) scanned " - f"[{DROPPED_LINE}] — every non-blank `{NUANCE_HEADING}` line reaches a bullet some reader " - f"will surface. 🔴 PARTIAL BY CONSTRUCTION, IN THREE WAYS, and this " - f"zero is a claim about none of them: (1) ABSORBED TAIL — a bullet that " - f"lost its opening line while another bullet sat above it is absorbed " - f"into that one and is byte-identical to a legitimate wrap, so no check " - f"can separate them; (2) UNCLOSED FENCE — an odd number of ``` or ~~~ " - f"makes every line after it fenced, and fenced lines are skipped as " - f"sample text, so a whole bullet can be swallowed with its `OPEN:` and " - f"reported nowhere; (3) DUPLICATED `{NUANCE_HEADING}` HEADING — the " - f"sections are concatenated into one body, so text under the second is " - f"absorbed by a bullet from the first and any offset printed here would " - f"index the concatenation rather than the file." - ] - n = len(dropped) - marked = sum(1 for d in dropped if d.carries_marker) - out = [ - "", - f"🔴 {n} DROPPED LINE(S) across {n_scanned} entry file(s) scanned " - f"[{DROPPED_LINE}] — present in the file, inside NO bullet, so EVERY " - f"reader skips them: " - f"`--ref`, `--search`, the digest and every openness count. " - f"`parse_journal_bullets` drops text that precedes the first bullet. The " - f"cause is almost always a lost or indented bullet OPENING line; the fix " - f"is to restore it, NOT to delete the text." - ] - if marked: - out.append( - f" 🔴 {marked} of them look{'s' if marked == 1 else ''} like a " - f"`OPEN:`/`RESOLVED:` DECLARATION. " - f"That is an open action the store is actively failing to report — it " - f"raises no badge and is counted in no openness total, because the " - f"bullet that would carry it no longer exists." - ) - for d in dropped: - flag = " ← looks like a DECLARATION" if d.carries_marker else "" - out.append(f" {d.filename}: nuance line {d.offset}{flag}") - out.append(f" {d.line.strip()[:ADVISORY_QUOTE_MAX]}") - out.append( - " 🔴 RESTORE FROM HISTORY, NOT FROM MEMORY. The entry's previous version " - "is one `git log -p -- ` away in the store's own history. " - "Reconstructing the opening line by hand invents a date and an author the " - "store never had." - ) - out.append( - " (Advisory. It changes no verdict: the loader accepts the file, and the " - "write protocol branches on this command's exit code to mean 'write " - "NOTHING'.)" - ) - return out - - -def _reachability_block( - n_scanned: int, unreachable: Sequence[UnreachableMarkerFinding] -) -> list[str]: - """The MARKER-REACHABILITY advisory. - - 🔴 ITS OWN BLOCK, BECAUSE IT IS ITS OWN SHAPE. Every remedy a near-miss - advisory names — "fix the LINE", "rewrite as `RESOLVED :`" — is wrong - here. A marker on a continuation line is spelled correctly; the edit it needs - is to be PROMOTED to a bullet of its own. - """ - if not unreachable: - return [ - "", - f"marker reachability: 0 out-of-reach marker(s) across {n_scanned} entry " - f"file(s) scanned [{UNREACHABLE_MARKER}] — every `OPEN:`/`RESOLVED:` " - f"found is " - f"on a bullet's OPENING line, where the parser reads.", - ] - n = len(unreachable) - out = [ - "", - f"🔴 {n} MARKER(S) OUT OF REACH across {n_scanned} entry file(s) scanned " - f"[{UNREACHABLE_MARKER}] — spelled CORRECTLY, on a bullet's CONTINUATION " - f"line, where NO reader looks. The marker pattern is anchored at position " - f"0 of a bullet's OPENING line, so this declares NOTHING: it raises " - f"neither the `OPEN` badge nor `NEAR-MISS`. 🔴 It is NOT a near-miss and " - f"is NOT counted as one — a near-miss is mis-spelled where the parser " - f"looks and is fixed by editing the line; this is fixed by PROMOTING the " - f"line to a top-level bullet of its own.", - ] - for u in unreachable: - out.append(f" {u.filename}: line {u.offset} of the bullet opening") - out.append(f" bullet: {u.bullet_first_line[:ADVISORY_QUOTE_MAX]}") - out.append( - f" marker: {u.line.strip()[:ADVISORY_QUOTE_MAX]} " - f"(would declare `{u.openness}`)" - ) - out.append( - " 🔴 BEFORE FIXING ANY MARKER ABOVE IT IN THE SAME SECTION, re-check this " - "one against the store's history. Such a bullet can have raised its badge " - "only BY ACCIDENT, through a broken `RESOLVED —` sitting above it — so " - "repairing that line would SILENCE a still-open action." - ) - out.append( - " (Advisory. It changes no verdict: the loader accepts the file, and the " - "write protocol branches on this command's exit code to mean 'write " - "NOTHING'.)" - ) - return out diff --git a/lib/env_aliases.py b/lib/env_aliases.py deleted file mode 100644 index a2d7496e..00000000 --- a/lib/env_aliases.py +++ /dev/null @@ -1,316 +0,0 @@ -"""THE one definition of every environment-variable RENAME — Python side. - -There are two: `SUBSYSTEM_STORE_*` → `CAIRN_*`, and `CAIRN_SUPABASE_*` → `CAIRN_OIDC_*` -over the seven settings of the JWT verifier in `internal/identity` (see below). - -🔴 THERE ARE TWO SPELLINGS OF THIS LEDGER AND THAT IS PACKAGING, NOT DUPLICATION. -`packages.cairn` installs the client script and `lib/` under `libexec` and nothing -else, so this side CANNOT import `internal/envalias`. That Go package is the other -spelling, and `tests/test_env_aliases.py` pins the two against each other — failing -when the pair set GROWS *or* SHRINKS, and comparing the rendered warnings as WHOLE -NORMALISED STRINGS rather than by keyword, because a guard on words is walkable by -rewording. Two spellings plus a gate is the shape `AGENTS.md` already blesses for -`server/Dockerfile` against `flake.nix`'s `serverEnv`. - -Read `internal/envalias/envalias.go`'s package doc for the reasoning in full — the -`CAIRN_HOST` collision, the removal anchor, and the one behaviour change. -The short form, because a reader editing THIS file should not have to open that one: - -* **The new name wins WITHIN ONE SOURCE** — one environment, or one config file. - The old name is read only when the new one is absent or blank *there*. Which - SOURCE supplies the value composes the other way round (environment before file, - and for the default instance only); `README.md` owns that, and it is why the two - warning texts below each speak about one source. -* 🔴 **A PRESENT BUT EMPTY VALUE COUNTS AS ABSENT, AND THAT IS AN AUTHORISED CHANGE - TO THE ORACLE** — decision: the operator, on PR #69. `server.py`'s `main()` used to - hand argparse `""` for `--store` and to raise `ValueError` on a blank `--port`; - every Go call site and this client's `load_config` already treated blank as absent, - so the rule removes a divergence rather than creating one. 🔴 The conformance corpus - is structurally blind to it — no row sends an empty value and none can, the corpus - describing REQUESTS while this decides STARTUP — so a green corpus says nothing - about this rule. The declaration, the accepted cost and the two guards that stand in - the corpus's place are in `tests/conformance/README.md`. -* **An old name that is present and non-blank warns once per process**, including - when the new name shadows it. A blank value is how a caller UNSETS an alias — it - changes no resolution, so it is not a deprecation and does not warn. 🔴 **"Blank" is - ONE predicate** — `_blank`, below — **read by both halves.** Spelled inline on each - side, the two disagreed: a whitespace-only old value resolved *and* did not warn, - which is the one combination that sentence rules out. -* **Warnings are sorted by NEW name.** `tests/parity/harness.py` compares the two - clients' stderr BYTE-FOR-BYTE, so the order has to be a property of the ledger - rather than of whatever order the lookups happened in. - -🔴 TWO PAIRS ARE NOT THE MECHANICAL PREFIX SWAP. `SUBSYSTEM_STORE_HOST` is the pod's -LISTEN ADDRESS, while `CAIRN_HOST` already exists and is the machine LABEL -(`host_identity.HOST_LABEL_ENV[0]`, rendered into client output) — so the mechanical -swap would make a pod bind to an operator's machine label AND let a listen address -hijack the label in rendered output. Hence `CAIRN_LISTEN_HOST`. And `CAIRN_ROOT` -would read as a sibling of the client-side `*_ROOT` names when it is the POD's store -root and belongs to none of them. Hence `CAIRN_STORE_ROOT`. ⚠ The live one is -`CAIRN_MIRROR_ROOT` alone: nothing in either language reads `CAIRN_CACHE_ROOT`, which -an earlier draft of this paragraph named as live. - -⚠ `SUBSYSTEM_STORE_ROUTES_ISH`, in `tests/test_env_pin.py`, is a negative-control -FIXTURE and not a variable anything reads. It is deliberately not in this ledger. - -🔴 THE SECOND RENAME IS NOT A PREFIX SWAP AT ALL, which is why `LEDGER` is pairs and not -a rule: `CAIRN_SUPABASE_*` → `CAIRN_OIDC_*`, over the seven settings of the JWT verifier -in `internal/identity`. That verifier is a generic RFC 7519 one (non-empty issuer and -audience required, a CLOSED asymmetric algorithm set, keys from a JWKS URL) and nothing -in it is specific to one vendor, so the old name asserted a dependency the code never -had. ⚠ `CAIRN_SUPABASE_REDIRECT_URL` is deliberately NOT renamed — it configures the -GoTrue PKCE sign-in flow and is honestly named for what it talks to — and -`CAIRN_SUPABASE_JWT_SECRET`/`_JWT_SECRET_FILE` are RETIRED rather than renamed: a pair -here would turn a startup refusal into a working alias. - -⚠ NOTHING ON THIS SIDE READS THE OIDC NAMES; the verifier is pod-side and Go-only. They -are here because `tests/test_env_aliases.py` pins the two spellings of the ledger as ONE -set — a pair present in one language and absent in the other is the half-migration that -gate exists to catch — and because `deprecations` sweeps the whole environment, so a -client run in a shell that still exports an old spelling warns about it in BOTH clients -and the parity harness's byte-for-byte stderr diff stays meaningful. The single -`REMOVAL_ANCHOR` therefore covers these pairs too, which is a wider promise than they -need and NOT a claim that this client reads them; per-pair anchors were declined as a -mechanism change (see `internal/envalias/envalias.go`'s package doc). -""" - -from __future__ import annotations - -from typing import Iterable, Mapping - -__all__ = [ - "LEDGER", - "REMOVAL_ANCHOR", - "deprecations", - "env_warning", - "file_deprecations", - "file_warning", - "old_name", - "reset_warned_for_test", - "value", - "value_or", - "warn_once", -] - -#: Every renamed variable as `(new, old)`, SORTED BY NEW NAME. -#: -#: 🔴 THE ORDER IS LOAD-BEARING, NOT COSMETIC — see the third bullet above. -#: `tests/test_env_aliases.py` pins it, so a pair appended in the wrong place is a -#: red test rather than a stderr diff the parity harness discovers later. -LEDGER: tuple[tuple[str, str], ...] = ( - ("CAIRN_CONFIG", "SUBSYSTEM_STORE_CONFIG"), - ("CAIRN_FAILURE_WINDOW_S", "SUBSYSTEM_STORE_FAILURE_WINDOW_S"), - ("CAIRN_LISTEN_HOST", "SUBSYSTEM_STORE_HOST"), - ("CAIRN_LOCKOUT_S", "SUBSYSTEM_STORE_LOCKOUT_S"), - ("CAIRN_MAX_FAILURES", "SUBSYSTEM_STORE_MAX_FAILURES"), - # The JWT verifier's settings. 🔴 THEY SORT INTO THE MIDDLE, so this is not an - # append; the order is load-bearing (third bullet above). - ("CAIRN_OIDC_AUDIENCE", "CAIRN_SUPABASE_AUDIENCE"), - ("CAIRN_OIDC_ISSUER", "CAIRN_SUPABASE_ISSUER"), - ("CAIRN_OIDC_JWKS_URL", "CAIRN_SUPABASE_JWKS_URL"), - ("CAIRN_OIDC_LEEWAY", "CAIRN_SUPABASE_LEEWAY"), - ("CAIRN_OIDC_MAX_AGE", "CAIRN_SUPABASE_MAX_AGE"), - ("CAIRN_OIDC_PROVIDER", "CAIRN_SUPABASE_PROVIDER"), - ("CAIRN_OIDC_REQUIRE_ROLE", "CAIRN_SUPABASE_REQUIRE_ROLE"), - ("CAIRN_PORT", "SUBSYSTEM_STORE_PORT"), - ("CAIRN_STORE_ROOT", "SUBSYSTEM_STORE_ROOT"), - ("CAIRN_TOKEN", "SUBSYSTEM_STORE_TOKEN"), - ("CAIRN_TOKEN_FILE", "SUBSYSTEM_STORE_TOKEN_FILE"), - ("CAIRN_TRUSTED_PROXIES", "SUBSYSTEM_STORE_TRUSTED_PROXIES"), - ("CAIRN_URL", "SUBSYSTEM_STORE_URL"), -) - -#: WHEN the old names stop being read, in the only terms this repo can state it: a -#: milestone a reader can CHECK — `packages.cairn` either exists in `flake.nix` or it -#: does not. A date could not be checked, there is no semver here to hang one on -#: (`flake.nix`: `version = self.shortRev`), and `tests/leakscan.py` refuses a dated -#: stamp in this tree anyway. -REMOVAL_ANCHOR = "the Python client (packages.cairn) is retired" - -#: The two pinned warning texts. -#: -#: 🔴 EACH LINE SPEAKS ONLY ABOUT ITS OWN SOURCE, AND THE EARLIER WORDING DID NOT — -#: measured false on both real clients. They used to end "…is read only when ${new} is -#: unset" / "…absent from that file", which reads as a claim about the whole -#: configuration; it is not one, because precedence COMPOSES. A config file holding -#: `CAIRN_URL=…:19001` — what README.md's quickstart tells you to write — plus an -#: exported `SUBSYSTEM_STORE_URL=…:19002` sends both clients to 19002, while the line -#: said the old name is read "only when $CAIRN_URL is unset" and it was set. The mirror -#: case misleads identically. An operator who had just migrated would read either line -#: as "my migration is live" and be wrong. -#: -#: 🔴 SO THE LINES STATE THE WITHIN-SOURCE RULE, the only rule a warning can know: no -#: cross-source sentence is truthful here, because the environment beats the file for the -#: DEFAULT instance and is not consulted at all for a non-default one (see -#: `load_config`'s own `where` text). The composition, with that caveat, is in -#: `README.md`. -#: -#: 🔴 STILL ONE TEXT PER DESTINATION, USED WHETHER OR NOT THE NEW NAME SHADOWS THE OLD -#: ONE, and now for a reason that holds: the sentence states the RULE rather than this -#: run's outcome, so it is true in both cases. A second "…and it is being ignored -#: because you also set X" wording would double the strings the cross-language gate has -#: to pin and double the ways the two spellings can drift. -#: -#: 🔴 `tests/test_env_aliases.py` READS THESE TWO CONSTANTS AND THEIR GO TWINS and -#: compares the rendered results. Editing one alone is a red test, which is why they -#: are named constants rather than inline literals at the call sites. -ENV_WARNING_FORMAT = ( - "${old} is a deprecated alias for ${new}. Where both are set in the environment, " - "${new} is the one that is read. Both are accepted until {anchor}." -) -FILE_WARNING_FORMAT = ( - "{old} in {path} is a deprecated alias for {new}. Where both appear in that file, " - "{new} is the one that is read. Both are accepted until {anchor}." -) - -#: The ONE lookup direction this side builds: new name → old name, read by `old_name` -#: and by `value`'s fallback. -#: -#: ⚠ THE OTHER DIRECTION (old → new) WAS BUILT BESIDE THIS ONE AND HAD ZERO READERS -#: TREE-WIDE — the declared-but-unread shape this repository refuses, the same ruling as -#: `Claims.Email` in `internal/identity/jws.go`. `deprecations`/`file_deprecations` walk -#: `LEDGER` through `_present` instead, which is where the sort order comes from, so the -#: map was dead from the commit that added it. -#: -#: 🔴 ITS GO TWIN IS NOT DEAD, AND THAT ASYMMETRY IS THE POINT RATHER THAN AN OVERSIGHT: -#: `envalias.olds` IS read, by `Deprecations` and `FileDeprecations`, because those two -#: range over a map where these two comprehend a list. So "the two spellings are one -#: ledger" is a claim about the PAIRS, never about the helpers — -#: `tests/test_env_aliases.py` compares ledger CONTENTS and is structurally blind to -#: helper SURFACE, which is why an unread helper here could sit beside a read one there -#: with every gate green. Reintroduce this direction only with a caller. -_NEW_TO_OLD = {new: old for new, old in LEDGER} - -#: The once-per-process-per-LINE set behind `warn_once`. -#: -#: Keyed on the WHOLE LINE rather than on the old name, so the same variable -#: deprecated in the environment AND named as a key in a config file produces both -#: warnings — they say different things and send the operator to different places — -#: while two lookups of the same variable produce one. -_WARNED: set[str] = set() - - -def old_name(new: str) -> str: - """The deprecated spelling of `new`, or `""` if there is not one. - - `""` rather than a `KeyError` so a caller naming something that was never renamed - — `CAIRN_ROUTES`, `CAIRN_UI_PORT` — gets plain single-name behaviour out of - `value` instead of a crash. - """ - return _NEW_TO_OLD.get(new, "") - - -def _blank(v: str) -> bool: - """The ONE definition of "this variable is not set", applied to BOTH spellings. - - 🔴 A NAMED FUNCTION BECAUSE THE TWO HALVES OF THE RULE DISAGREED WHILE BOTH WERE - SPELLED INLINE, AND `tests/parity/` WAS BLIND TO IT BECAUSE `internal/envalias` HAD - THE SAME DISAGREEMENT. `_present` tested `.strip()`; `value` returned the old name's - value RAW. So `SUBSYSTEM_STORE_ROOT=" "` resolved to `" "` — a pod would have taken - a whitespace store root — and warned about nothing, while the module docstring said a - blank value "changes no resolution, so it is not a deprecation". Two clients failing - identically compare equal; only reading the two halves against each other found it. - - ⚠ WHICH HALF WAS WRONG IS A DECISION, AND THIS IS IT: the RESOLUTION half. The - alternative — warn whenever an old name holds any non-empty string — keeps a resolved - value no operator can have meant. Treating it as absent makes the old name behave - exactly like the new one, which has been `.strip()`-tested since this module was - written, and lets `value_or`'s fallback (the code default) run. - - ⚠ IT TESTS BLANKNESS AND DOES NOT TRIM: a non-blank value comes back RAW, because - trimming a real value is the caller's business and would silently rewrite a store root - that legitimately ends in a space. - """ - return not v.strip() - - -def value(env: Mapping[str, str], new: str) -> str: - """`new` if present and non-blank, else its old spelling, else `""`. - - The ONLY place the precedence rule is written. Every call site goes through this; - none open-codes a fallback, because a predicate duplicated across call sites - regenerates the same bug at every site. - """ - direct = env.get(new, "") - if not _blank(direct): - return direct - old = _NEW_TO_OLD.get(new, "") - if old: - fallback = env.get(old, "") - if not _blank(fallback): - return fallback - return "" - - -def value_or(env: Mapping[str, str], new: str, fallback: str) -> str: - """`value`, with a default for "neither name is set".""" - return value(env, new) or fallback - - -def env_warning(new: str, old: str) -> str: - """The pinned text for an environment variable.""" - return ENV_WARNING_FORMAT.format(old=old, new=new, anchor=REMOVAL_ANCHOR) - - -def file_warning(new: str, old: str, path: str) -> str: - """The pinned text for a config-FILE key. - - 🔴 IT NAMES THE FILE, NOT `$VAR`. `SUBSYSTEM_STORE_URL=` inside - `~/.config/subsystem-store/env` is not an exported variable, and telling an - operator to "unset $SUBSYSTEM_STORE_URL" when the string lives in a file they have - to EDIT sends them looking in the wrong place. - """ - return FILE_WARNING_FORMAT.format(old=old, new=new, path=path, anchor=REMOVAL_ANCHOR) - - -def _present(mapping: Mapping[str, str]) -> list[tuple[str, str]]: - """Every `(new, old)` whose OLD name is present and non-blank, sorted by new. - - Blankness through `_blank`, the SAME predicate `value` resolves with. Spelled inline - on both sides once, the two disagreed; see `_blank`. - """ - return sorted( - ((new, old) for new, old in LEDGER if not _blank(mapping.get(old, ""))), - key=lambda pair: pair[0], - ) - - -def deprecations(env: Mapping[str, str]) -> list[str]: - """One warning line per old name present in `env`, sorted by NEW name. - - A pure function of `env`: no process state, no emission. `warn_once` adds the - once-per-process rule, and keeping them apart is what lets a test assert the ORDER - without reaching into module state. - """ - return [env_warning(new, old) for new, old in _present(env)] - - -def file_deprecations(from_file: Mapping[str, str], path: str) -> list[str]: - """`deprecations` for the keys of one config file.""" - return [file_warning(new, old, path) for new, old in _present(from_file)] - - -def warn_once(lines: Iterable[str], emit) -> None: - """Emit each line through `emit`, at most once per process. - - The caller supplies `emit` because the destination differs and the format differs - with it: the CLI writes bare lines to stderr, the pod writes - `subsystem-store-api: ` through `reload_safe`. A module that wrote to - `sys.stderr` itself would need a knob for the prefix, and the prefix would then be - a second thing to keep in step across two languages. - """ - for line in lines: - if line in _WARNED: - continue - _WARNED.add(line) - emit(line) - - -def reset_warned_for_test() -> None: - """Clear the once-per-process set. - - Public because `warn_once`'s whole contract is module-global state, and a test that - could not clear it would be order-dependent: the second test to assert an emission - would see nothing and pass for the wrong reason. - """ - _WARNED.clear() diff --git a/lib/host_identity.py b/lib/host_identity.py deleted file mode 100644 index ea3dfb52..00000000 --- a/lib/host_identity.py +++ /dev/null @@ -1,125 +0,0 @@ -#!/usr/bin/env python3 -"""WHICH MACHINE am I — one implementation, every consumer. - -🔴 A HOSTNAME IS NOT AN IDENTITY. Machines provisioned from one image commonly -report the SAME hostname, and cairn's local cache is PER-HOST and independently -STALE: two machines holding the same scope can hold different entries in it at -any given instant. - -⚠ NOT "UNREPLICATED", WHICH IS WHAT THIS SAID AND IS NO LONGER TRUE. Since the -Cairn cutover the hosted pod is the canonical datastore and each machine's -`~/.cache/subsystem-store` is a SYNCED READ-THROUGH CACHE of it, so the two -caches CONVERGE — eventually, via the pod, whenever `cairn sync` runs on each. -What survives is the divergence at an instant, and that is enough: nothing makes -the two caches agree at the moment a tool reads one of them. - -So the module's thesis is UNCHANGED, only its reason is. A tool that reads such -a cache and reports a GLOBAL fact ("the store has no `billing/` scope") is -stating one machine's disk as though it were the fleet's — it is now wrong by -STALENESS rather than by isolation, which is the same wrong answer to the reader. -That is the defect this module exists to make un-writable: every consumer prints -the identity of the machine it actually read. - -WHY THE LABEL ALONE IS NOT ENOUGH ---------------------------------- -`host_label()` reads an operator-set environment variable and falls back to the -hostname. Under a systemd unit that variable is typically set to something -machine-specific; in an INTERACTIVE shell it is usually unset and the label -degrades to the hostname — which is exactly the value that may be shared. - -So a header printing `host_label()` alone would read as coverage while providing -none: identical on the very machines it is supposed to distinguish. `this_host()` -joins the readable label to the machine id, which is distinct per host by -construction and needs no systemd. -""" -from __future__ import annotations - -import os -import re -import socket -from pathlib import Path - -#: Where the machine id is read from. A module-level tuple so a test can point a -#: reader at synthetic files and exercise the REAL function, rather than -#: re-implementing its shape check in the test — which would only ever prove the -#: test agrees with itself. -MACHINE_ID_FILES: tuple[str, ...] = ("/etc/machine-id", "/var/lib/dbus/machine-id") - -#: What `/etc/machine-id` is defined to hold: 32 lowercase hex digits. -_MACHINE_ID_SHAPE = re.compile(r"[0-9a-f]{32}") - -#: Printed instead of an id when no file could be read or none had the right -#: shape. A SENTENCE, not an empty string: the whole point of this module is that -#: a host claim is never silently unqualified. -MACHINE_ID_UNREADABLE = "machine-id-unreadable" - -#: Environment variables consulted for a readable label, in precedence order. -#: A tuple rather than a hardcoded pair so a deployment can add its own without -#: editing the function. -HOST_LABEL_ENV: tuple[str, ...] = ("CAIRN_HOST", "ASIB_HOST", "ACTIVITY_HOST") - - -def machine_id(files: "tuple[str, ...] | None" = None) -> str | None: - """The only reliable "which machine am I" signal available without config. - - 🔴 SHAPE-CHECKED, NOT JUST NON-EMPTY. Returning whatever junk a file happened - to hold would make a caller's "does this prefix belong to this host" answer - True for any prefix containing it — an error in the FALSE DATA-LOSS - direction, which is the one that gets someone to act destructively. - - Returns `None` when no candidate file is readable or none parses. The caller - decides what an unknown machine means; this never guesses. - """ - for p in (MACHINE_ID_FILES if files is None else files): - try: - v = Path(p).read_text(encoding="utf-8").strip() - except OSError: - continue - if _MACHINE_ID_SHAPE.fullmatch(v): - return v - return None - - -def host_label() -> str: - """The READABLE name of this machine, for a human reading a key or a header. - - 🔴 The fallback is the hostname, which may be SHARED across machines — that - is precisely why `this_host()` exists and why nothing should print this value - on its own as a per-host claim. - """ - for var in HOST_LABEL_ENV: - v = os.environ.get(var) - if v and v.strip(): - return re.sub(r"[^A-Za-z0-9._-]", "-", v.strip()) - return re.sub(r"[^A-Za-z0-9._-]", "-", socket.gethostname() or "unknown") - - -#: How much of the machine id `this_host()` prints. -#: 🔴 A PREFIX, NEVER THE WHOLE ID. `/etc/machine-id` is a stable, unique -#: installation identifier, and `this_host()` is a DISPLAY value: it lands in -#: rendered headers and JSON payloads, and tool output gets pasted into issues -#: and pull requests routinely. A dozen hex characters separate machines with -#: room to spare; the job is to tell a fleet apart, not to identify hardware. -#: 🔴 THIS DOES NOT TOUCH `machine_id()` OR `host_label()`. A caller that builds -#: a storage key from the full id must keep doing so — truncating a key prefix -#: would repoint every future object, which is a data-loss shape, not a privacy -#: fix. -MACHINE_ID_DISPLAY_CHARS = 12 - - -def this_host() -> str: - """An identity that DIFFERS between machines even on a hand-run. - - `