From d04abf7d38e2fd7cf63e679345f1b35d25558e65 Mon Sep 17 00:00:00 2001 From: REPPL <77722411+REPPL@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:15:44 +0000 Subject: [PATCH 01/16] feat: draw the spot-check at a proved landing A landing abcd proves, at `abcd land`'s landed re-run and at a lane's landing in `implement step`, is observed for the spot-check. While the window has not passed the observation reads the store as last fetched and carries only the records origin's `abcd-spotcheck` branch lacks. Once it has passed it fetches the branch, takes one round of the drand quicknet beacon and verifies its BLS signature against the pinned key, draws by HMAC over the round's randomness from each group of the window's unattended work, and pushes the cycle with its items over origin's tip, tried once more after a refusal. A draw that cannot be made writes nothing and leaves the landing proved. Only typed fields leave the machine: the push carries a copy of each record with its free text blanked, under a name hashed over the typed content, while the local copy keeps the text. The merge gate's record gains the mode's layer and whether a review receipt named the head, and a re-arm the release hold makes is recorded too. The landings reader registers itself with the spot-check to avoid an import cycle. claim.PushBranch now runs its push, hooks included, under the caller's context. The pre-push hook gains a receipt-less row for the one branch `abcd-spotcheck`, admitting a fast-forward whose every commit holds only regular files at the store's paths (adr-2611251806496719). The drain site waits for the drain-bundles change. Refs: spc-2610301925429250 Refs: itd-2610301750162657 Assisted-by: Claude:claude-opus-5-5 --- .../brief/02-constraints/03-invariants.md | 15 + .../brief/04-surfaces/27-implement.md | 5 + .../development/brief/04-surfaces/38-land.md | 18 + .../brief/05-internals/03-configuration.md | 26 ++ ...the-spot-check-s-store-branch-is-pushed.md | 49 +++ .abcd/development/decisions/adrs/README.md | 1 + .githooks/pre-push | 74 +++- ACKNOWLEDGEMENTS.md | 11 + commands/build.md | 4 +- commands/implement.md | 9 + commands/land.md | 23 ++ go.mod | 1 + go.sum | 4 +- internal/core/claim/remote.go | 14 +- internal/core/claim/spotcheck_push_test.go | 59 +++ internal/core/implement/loop/land.go | 9 + .../implement/loop/land_spotcheck_test.go | 35 ++ internal/core/landing/facilitator.go | 9 +- internal/core/landing/land.go | 23 +- internal/core/landing/land_spotcheck_test.go | 97 +++++ internal/core/landing/withdraw.go | 9 +- internal/core/landings/spotcheck.go | 40 ++ internal/core/landings/spotcheck_test.go | 56 +++ internal/core/spotcheck/afterlanding.go | 289 ++++++++++++++ internal/core/spotcheck/afterlanding_test.go | 365 ++++++++++++++++++ internal/core/spotcheck/beacon.go | 237 ++++++++++++ internal/core/spotcheck/beacon_test.go | 173 +++++++++ internal/core/spotcheck/config.go | 73 ++++ internal/core/spotcheck/config_test.go | 59 +++ internal/core/spotcheck/cycle.go | 313 +++++++++++++++ internal/core/spotcheck/draw.go | 65 ++++ internal/core/spotcheck/draw_test.go | 80 ++++ internal/core/spotcheck/groups.go | 233 +++++++++++ internal/core/spotcheck/groups_test.go | 122 ++++++ internal/core/spotcheck/size.go | 31 ++ internal/core/spotcheck/size_test.go | 84 ++++ internal/core/spotcheck/store.go | 261 ++++++++----- internal/core/spotcheck/store_test.go | 40 +- internal/core/spotcheck/window.go | 46 +++ internal/core/spotcheck/window_test.go | 39 ++ .../cli/githook_prepush_receiptless_test.go | 21 +- .../cli/githook_prepush_spotcheck_test.go | 211 ++++++++++ 42 files changed, 3185 insertions(+), 148 deletions(-) create mode 100644 .abcd/development/decisions/adrs/2611251806496719-the-spot-check-s-store-branch-is-pushed.md create mode 100644 internal/core/claim/spotcheck_push_test.go create mode 100644 internal/core/landings/spotcheck.go create mode 100644 internal/core/landings/spotcheck_test.go create mode 100644 internal/core/spotcheck/afterlanding.go create mode 100644 internal/core/spotcheck/afterlanding_test.go create mode 100644 internal/core/spotcheck/beacon.go create mode 100644 internal/core/spotcheck/beacon_test.go create mode 100644 internal/core/spotcheck/config.go create mode 100644 internal/core/spotcheck/config_test.go create mode 100644 internal/core/spotcheck/cycle.go create mode 100644 internal/core/spotcheck/draw.go create mode 100644 internal/core/spotcheck/draw_test.go create mode 100644 internal/core/spotcheck/groups.go create mode 100644 internal/core/spotcheck/groups_test.go create mode 100644 internal/core/spotcheck/size.go create mode 100644 internal/core/spotcheck/size_test.go create mode 100644 internal/core/spotcheck/window.go create mode 100644 internal/core/spotcheck/window_test.go create mode 100644 internal/surface/cli/githook_prepush_spotcheck_test.go diff --git a/.abcd/development/brief/02-constraints/03-invariants.md b/.abcd/development/brief/02-constraints/03-invariants.md index 40add52b8b..72c15c45e6 100644 --- a/.abcd/development/brief/02-constraints/03-invariants.md +++ b/.abcd/development/brief/02-constraints/03-invariants.md @@ -204,6 +204,21 @@ The following are non-negotiable invariants — any architectural choice that vi around each such delete, and the reservation sweep's workflow started through the forge client (`gh workflow run`) with its newest run read back. It never pushes a reservation deletion itself. + The spot-check's store (itd-2610301750162657, `abcd-spotcheck` on + `origin`) is fetched and pushed only where a landing has just been proved: + `land` once a re-run finds the branch landed, and `implement step` once a + lane's landing is proved, whose meaning includes the spot-check's + observation. While the window has not passed the observation reads the + store as last fetched, from disk, and makes one push of the records this + checkout holds that origin's copy lacks, or nothing when it holds none. + Once the window has passed (or before the first window opens) it makes one + fetch of the store's branch, one fetch of the latest round of the drand + beacon over HTTPS from `api.drand.sh` (then `api2.drand.sh`, then + `api3.drand.sh` when one before cannot be reached), within ten seconds in + all, the landings reader's forge reads for the window, and one push of the + cycle, each tried once more after a fresh fetch when origin refuses it. + Only typed fields leave the machine: a record's free text stays on its local + copy. Setup (`abcd ahoy install`) downloads abcd only on a yes to the question that names the download, the release and the file it is written to, which is that fetch's documented meaning: the release's binary for this computer, diff --git a/.abcd/development/brief/04-surfaces/27-implement.md b/.abcd/development/brief/04-surfaces/27-implement.md index 52a2351c7b..6d337b60a0 100644 --- a/.abcd/development/brief/04-surfaces/27-implement.md +++ b/.abcd/development/brief/04-surfaces/27-implement.md @@ -771,6 +771,11 @@ started, whose reservation lapses with its lease), whether a drain or `abcd build ` started it (iss-2610142247197128); an intent's run keeps its reservation through a hand-back. A run holding no reservation is neither renewed nor tombstoned, and its own reservation is not fenced. +Once a lane's landing is proved, the step observes it for the spot-check +(itd-2610301750162657), as `abcd land` does at a landed re-run +([`38-land.md`](38-land.md)), and the landing's note carries the +observation's line; a draw that cannot be made writes nothing and never undoes +the landing. The land fence also reads the release hold (itd-2609151838312703 C7, spc-2610150728396006 step 4). Every run's fence, one holding a reservation or diff --git a/.abcd/development/brief/04-surfaces/38-land.md b/.abcd/development/brief/04-surfaces/38-land.md index 00f101de63..e1635aa75a 100644 --- a/.abcd/development/brief/04-surfaces/38-land.md +++ b/.abcd/development/brief/04-surfaces/38-land.md @@ -456,6 +456,24 @@ with no approval, so abcd enforces this itself. Every forge read the gate makes is a GET, its fields pinned in `internal/ghcontract` after a live read-only call, and a forge answer that cannot be read counts for nothing. +## The spot-check at a landing + +A re-run that finds the branch landed observes the landing for the spot-check +(itd-2610301750162657, `internal/core/spotcheck`), and the `landed` step's note +carries the observation's line. In `auto` mode the gate's decision abcd takes +alone, and a re-arm the release hold makes, are each kept on the checkout's +local copy of the store (`refs/abcd/spotcheck`), with the mode's layer and +whether a review receipt named the head. While the window has not passed, the +observation reads the store as last fetched and pushes only records origin's +branch `abcd-spotcheck` lacks. Once it has passed it fetches the branch, takes +one verified round of the drand quicknet beacon (signature checked against the +pinned key, ten seconds in all), draws by HMAC over the round's randomness, +and pushes the cycle over the tracking tip, tried once more after a refusal. +Only typed fields reach origin, and an observation that cannot draw writes +nothing and leaves the landing proved. The branch takes no preflight receipt: +the pre-push hook admits it by a row of its own +([adr-2611251806496719](../../decisions/adrs/2611251806496719-the-spot-check-s-store-branch-is-pushed.md)). + ## Trust boundaries - The remote is `origin` alone, and its every fetch and push URL must be the diff --git a/.abcd/development/brief/05-internals/03-configuration.md b/.abcd/development/brief/05-internals/03-configuration.md index dde2aba8db..dced066051 100644 --- a/.abcd/development/brief/05-internals/03-configuration.md +++ b/.abcd/development/brief/05-internals/03-configuration.md @@ -845,6 +845,32 @@ may run to in this repository: a whole number from 16 to 200, 40 by default - **What it does not bound.** An idea's slug in `ideate`, whose verdict record is not one of these families, keeps its own limit of 64, and a checklist item's id its own. +### The spot-check keys + +The `spotcheck` block sets the spot-check's window and its sample +(`internal/core/spotcheck/config.go`, itd-2610301750162657), read through the +layered resolver, the repository layer last and winning. + +```jsonc +{ + "spotcheck": { + "window_days": 7, // 1 to 90; bundled default 7 + "window_changes": 0, // 10 to 100000; 0 or absent is unset + "per_group": 10 // 1 to 100; bundled default 10 + } +} +``` + +- **The first bound to pass closes the window.** A window spans everything since + the last cycle, and closes at the first landing observed once `window_days` + whole days have gone by or, when set, `window_changes` first-parent commits + have landed on the default branch. +- **`per_group` is the most a group draws.** The size halves, rounded up, after + three closed cycles in a row found nothing, and is whole again after a finding. +- **A nonsense value refuses.** A value out of bounds or not a whole number, or a + misspelt key under `spotcheck`, refuses the observation, naming the file and + the key, and nothing is drawn; it never falls back to the default. + ### Staged config keys No shipped code reads any of the keys below. None appears in any repository's diff --git a/.abcd/development/decisions/adrs/2611251806496719-the-spot-check-s-store-branch-is-pushed.md b/.abcd/development/decisions/adrs/2611251806496719-the-spot-check-s-store-branch-is-pushed.md new file mode 100644 index 0000000000..da9537c17f --- /dev/null +++ b/.abcd/development/decisions/adrs/2611251806496719-the-spot-check-s-store-branch-is-pushed.md @@ -0,0 +1,49 @@ +--- +id: adr-2611251806496719 +slug: the-spot-check-s-store-branch-is-pushed +status: accepted +date: 2026-11-25 +supersedes: null +superseded_by: null +related_intents: [itd-2610301750162657] +related_rfcs: [] +related_adrs: [adr-2610031352212697, adr-2610150729333337] +--- + +# ADR-2611251806496719: The spot-check's store branch is pushed without a preflight receipt + +## Context + +[itd-2610301750162657](../../intents/planned/itd-2610301750162657-a-person-spot-checks-what-abcd-s-agents.md) keeps the spot-check's record on one branch of the shared remote, `abcd-spotcheck`: an orphan whose tree holds small JSON files under `handbacks/`, `decisions/`, `cycles/`, `items/` and `judgements/`, beside one `window-open.json`, each written once and never edited. The draw runs inside a landing (`abcd land`, a lane's landing in `abcd implement step`, a drain move), and the review verb pushes a judgement per item. + +Three constraints were already locked: + +- **The push hook needs a receipt.** `.githooks/pre-push` refuses any push whose new commit carries no preflight receipt, and the store's push runs with the repository's hooks, never with `--no-verify`. +- **A store commit has nothing a preflight vouches for.** Its tree is the store's records alone, never the product's code, and it never merges into the default branch. A landing cannot mint a receipt for it: the commit is made after the landing, by abcd, in no working tree. +- **dcn-2611130729517836 and dcn-2611131053182459** require the hook to have a row of its own for the branch, with its own ruling and shape check, before any verb pushes to it. + +The hook already admits two families of receipt-less pushes, reservations ([adr-2610031352212697](2610031352212697-claims-are-branches-on-the-shared-remote.md)) and status branches ([adr-2610150729333337](2610150729333337-a-status-branch-moves-without-a.md)), each by one row of its receipt-less table and a shape check that admits only commits that change no file. Store commits do change files, so neither check fits. + +## Decision + +The push hook's receipt-less table gains a third row: the branch `abcd-spotcheck` itself, checked by its own `spotcheck_shape` check. A row whose prefix does not end in a slash names one branch exactly, never a prefix of others. The check admits a push only when: + +- it is a fast-forward of the branch, or its creation; +- every commit it moves (`..` on an update, everything reachable from `` on a creation) has a tree holding nothing but regular, non-executable files, each at `window-open.json` or at a path of `.json` names under `handbacks/`, `decisions/`, `cycles/`, `items/` or `judgements/`, made of letters, digits, `.`, `_` and `-`; +- the walk read every commit in full, as the reservation check requires of a shallow clone. + +A deletion of the branch is refused outright: the store is kept for ever. Any other push to the branch is gated as any branch is. The forge ruleset that blocks deletion and non-fast-forward pushes of `refs/heads/abcd-spotcheck` is the person's act, applied from a mirror under `.abcd/work/rulesets/` as every ruleset is. + +## Alternatives Considered + +- **A receipt for every store push.** Rejected: no preflight can run over a commit made after a landing in no working tree, so the store could never reach `origin`. +- **The reservation shape check.** Rejected: it admits only commits that change no file, and the store's commits add files. +- **A hidden ref namespace (`refs/abcd/spotcheck`) on the remote.** Rejected for the reasons [adr-2610150729333337](2610150729333337-a-status-branch-moves-without-a.md) gives for status branches: the forge's rulesets cannot protect it, and a hosted session's proxy refuses it. +- **The chosen option: a row of its own with a path-and-mode shape check.** It admits only files the store writes, under the store's folders, on a branch no gate reads code from. + +## Consequences + +- **Easier:** a landing's draw and its records reach `origin` from any machine whose hooks run, so the queue is one queue for every machine. +- **Harder:** the shape check judges paths and modes, never content: a push under the row can carry any JSON at a store path. abcd's reader is the guard on content, since it reads every file strictly and names one it cannot read; nothing on the branch is ever built, run or merged. +- **The hook is a local-only check.** A push made where no hook runs is held only by the forge's ruleset, as for the other two rows. +- **A new obligation:** a change to the store's folders changes this row's check in the same change. diff --git a/.abcd/development/decisions/adrs/README.md b/.abcd/development/decisions/adrs/README.md index cdf141c6ac..fa3d77f0c2 100644 --- a/.abcd/development/decisions/adrs/README.md +++ b/.abcd/development/decisions/adrs/README.md @@ -252,4 +252,5 @@ The intent lint (a Go implementation) extends to verify these reciprocally. | [adr-2611211251039198](2611211251039198-abcdev-app-narrows-to-the-documentation.md) | abcdev.app narrows to the documentation without forwarding the record's old addresses | accepted | 2026-11-21 | | [adr-2611241456284353](2611241456284353-the-check-of-the-merged-result-runs.md) | The check of the merged result runs every declared check for every change, and no earlier result stands in for it | accepted | 2026-11-24 | | [adr-2611241456294452](2611241456294452-an-independent-checker-is-optional-its.md) | An independent checker is optional: its verdict is reported, never required and never waited for | accepted | 2026-11-24 | +| [adr-2611251806496719](2611251806496719-the-spot-check-s-store-branch-is-pushed.md) | The spot-check's store branch is pushed without a preflight receipt | accepted | 2026-11-25 | diff --git a/.githooks/pre-push b/.githooks/pre-push index d876fc4175..5340753748 100755 --- a/.githooks/pre-push +++ b/.githooks/pre-push @@ -105,6 +105,14 @@ # from an ordinary machine. The hook is not what keeps this work off the # default branch; the wip-guard required check and the ruleset are. # +# The spot-check's store (itd-2610301750162657, adr-2611251806496719) is +# the fourth: the one branch refs/heads/abcd-spotcheck, an orphan whose +# commits hold the store's small JSON files and nothing else. The +# spotcheck_shape check admits a fast-forward (or the creation) whose +# every commit holds only regular, non-executable files at the store's +# paths, read in full; anything else pushed to the branch is gated as any +# branch is, and a deletion is refused: the store is kept for ever. +# # A commit is "already on a remote", and needs no receipt for that, only # when a remote-tracking ref outside every receipt-less prefix holds it. # A ref under one was pushed without a receipt, so it vouches for nothing: @@ -168,10 +176,18 @@ is_null_id() { # a reservation over a tip it fetched without a receipt, and the walk only # reads: nothing is fetched, deepened or written. only_empty_trees() { - local listing walked line stored parents oldifs walked_n stored_n + local listing listing="$(git rev-list --format=%T "$@" 2>/dev/null)" || return 1 [ -n "$empty_tree" ] || return 1 [ -z "$(printf '%s\n' "$listing" | grep -v -e '^commit ' -e "^$empty_tree\$" -e '^$')" ] || return 1 + read_in_full "$@" +} + +# read_in_full succeeds when the walk of the range git rev-list is given +# followed, for every commit it lists, every parent the commit stores: a +# shallow clone's cut leaves a commit's parents unread (only_empty_trees). +read_in_full() { + local walked line stored parents oldifs walked_n stored_n walked="$(git rev-list --parents "$@" 2>/dev/null)" || return 1 oldifs="$IFS" IFS=$'\n' @@ -208,6 +224,51 @@ reservation_shape() { fi } +# spotcheck_path_re is a path of the spot-check's store (internal/core/spotcheck, +# adr-2611251806496719): window-open.json, or a .json name under one of the +# store's five folders, every segment made of letters, digits, ".", "_" and +# "-". A path git quotes (one holding any other byte) never matches. +spotcheck_path_re='^(window-open\.json|(handbacks|decisions|cycles|items|judgements)(/[A-Za-z0-9._-]+)+\.json)$' + +# spotcheck_shape is the spot-check store's shape check, for the branch the +# push names ($branch): the branch is abcd-spotcheck itself, the push is a +# fast-forward (or a create), the walk reads the range in full, and every +# commit it moves holds nothing but regular, non-executable files at store +# paths (spotcheck_path_re), no segment "." or "..". The range is everything +# new on an update and everything reachable on a create, so a commit of the +# product's history pushed to the branch walks into a tree holding other +# paths and is gated as any branch is. Only paths and modes are judged: the +# store's reader judges every file's content, and nothing on the branch is +# built, run or merged. +spotcheck_shape() { + local remote_sha="$1" local_sha="$2" range commit commits listing line meta path + [ "$branch" = "abcd-spotcheck" ] || return 1 + if is_null_id "$remote_sha"; then + range="$local_sha" + else + git merge-base --is-ancestor "$remote_sha" "$local_sha" 2>/dev/null || return 1 + range="$remote_sha..$local_sha" + fi + read_in_full "$range" || return 1 + commits="$(git rev-list "$range" 2>/dev/null)" || return 1 + for commit in $commits; do + listing="$(git ls-tree -r --full-tree "$commit" 2>/dev/null)" || return 1 + while IFS= read -r line; do + [ -n "$line" ] || continue + meta="${line%%$'\t'*}" + path="${line#*$'\t'}" + case "$meta" in + "100644 blob "*) ;; + *) return 1 ;; + esac + [[ "$path" =~ $spotcheck_path_re ]] || return 1 + case "/$path/" in + */./* | */../*) return 1 ;; + esac + done <<<"$listing" + done +} + # wip_id_re is the one record id a work-in-progress branch carries after its # prefix: an iss-, itd- or spc- id of sixteen digits, or an ordinal itd- or # iss- id, and nothing else. @@ -259,6 +320,7 @@ shape_check() { case "$1" in reservation_shape) [ "$#" -eq 1 ] || reservation_shape "$2" "$3" ;; wip_shape) [ "$#" -eq 1 ] || wip_shape "$2" "$3" ;; + spotcheck_shape) [ "$#" -eq 1 ] || spotcheck_shape "$2" "$3" ;; *) return 1 ;; esac } @@ -274,7 +336,9 @@ shape_check() { # shape_check. The last field is named # when a delete under the prefix is refused, with standing for the # branch's name after the prefix, or is "never" for a branch kept for ever: a -# ref under a receipt-less prefix is never deleted by a push. +# ref under a receipt-less prefix is never deleted by a push. A prefix that +# does not end in a slash names one branch exactly, never the branches whose +# names begin with it. # # A new row needs its own ruling record and its own shape check. A prefix with # no shape check, or one naming a check shape_check has no arm for, is never @@ -286,6 +350,7 @@ shape_check() { receiptless_prefixes=( "abcd-reserved/|reservation_shape|adr-2610031352212697|abcd reserve --release" "abcd-status/|reservation_shape|adr-2610150729333337|never" + "abcd-spotcheck|spotcheck_shape|adr-2611251806496719|never" ) # receiptless_row finds the row whose prefix the branch is under and whose @@ -297,8 +362,9 @@ receiptless_row() { IFS='|' read -r row_prefix row_shape row_ruling row_end <<<"$row" [ -n "$row_prefix" ] && [ -n "$row_shape" ] || continue shape_check "$row_shape" || continue - case "$1" in - "$row_prefix"*) return 0 ;; + case "$row_prefix" in + */) case "$1" in "$row_prefix"*) return 0 ;; esac ;; + *) [ "$1" = "$row_prefix" ] && return 0 ;; esac done return 1 diff --git a/ACKNOWLEDGEMENTS.md b/ACKNOWLEDGEMENTS.md index 01985e977f..c9be4f7f16 100644 --- a/ACKNOWLEDGEMENTS.md +++ b/ACKNOWLEDGEMENTS.md @@ -502,6 +502,17 @@ Ideas and methodologies that shaped the design — not code abcd depends on. clean read rules out, and each finding turned into a person's change to the rule. The evidence is `.abcd/development/research/notes/2026-10-30-spot-check-unattended-changes-sota.md`. +- **drand and its quicknet chain (the League of Entropy, + ) and CIRCL (Cloudflare, BSD-3-Clause, + )** — the public randomness the + spot-check draws by, and the library it checks each round with + (`internal/core/spotcheck/beacon.go`, itd-2610301750162657): one round of + the quicknet chain is fetched over HTTPS, its BLS signature verified against + the chain's pinned public key through CIRCL's `sign/bls`, and the round's + randomness keys the draw, so no agent can choose which items a person + reads. CIRCL is named here rather than in `go.mod` alone because the intent + adopted it by name + (`.abcd/development/research/notes/2026-10-31-drand-beacon-verification-sota.md`). - **Safe-fix tiers in linters (Ruff, ; ESLint, ) and the static-analysis lessons of Google (Sadowski et al., "Lessons from Building diff --git a/commands/build.md b/commands/build.md index 70aca31e55..3391b26198 100644 --- a/commands/build.md +++ b/commands/build.md @@ -1124,7 +1124,9 @@ A lane's stages run in order: the run and come back later. Once it is, the loop removes the lane's worktree and branch, deleting the branch only at a tip that commit stores, the lane is done, and the next pending step opens the - next lane. In a repository abcd manages, that step then sweeps on its own + next lane. The proved landing is observed for the spot-check, as `abcd + land` observes one (`commands/land.md`, "The spot-check at a landing"), + and its note says what the observation did. In a repository abcd manages, that step then sweeps on its own once its save is written: the provably spent part of `abcd sweep --apply`, with the same proofs against a fresh fetch (other merged, clean worktrees removed, a dirty one's work saved and kept, the merged lane branches diff --git a/commands/implement.md b/commands/implement.md index 18bd8b1173..095cb847b5 100644 --- a/commands/implement.md +++ b/commands/implement.md @@ -1141,6 +1141,15 @@ over each of the run's lanes' own diff. landing's note, and a tombstone origin refuses is named there and never undoes the landing. The branch removal touches only the lane's `build/-`, never the reservation branch. + Once the landing is proved, the step observes it for the spot-check, as + `abcd land` does at a landed re-run (`commands/land.md`, "The spot-check at + a landing"), and the landing's note carries what the observation did; a + draw that cannot be made writes nothing and never undoes the landing. In + `auto` mode the merge gate's decision abcd takes alone at the arming is kept + for the spot-check on this checkout's local copy of its record, made from the + decision as given; a record that cannot be written leaves the decision + standing, its reason saying so, and a parked lane asking the gate again over + the same head keeps one record. A conflicting pull request that is refused names what this checkout can say about it: the files a merge of `origin/` and the pushed head conflicts in diff --git a/commands/land.md b/commands/land.md index 3587386cb5..d888f7d738 100644 --- a/commands/land.md +++ b/commands/land.md @@ -328,6 +328,29 @@ abcd adds no approval rule or code-owner file to the forge: the forge lets a pull request merge with no approval, so abcd enforces this itself, and the shell guard refuses an agent's own `gh pr merge` while the mode is `human`. +In `auto` mode, a decision abcd takes alone (an author with write access and no +person's approval counted) is kept for the spot-check on this checkout's local +copy of its record, made from the decision as the gate gave it; a re-arm the +release hold makes is kept the same way. A record that cannot be written leaves +the decision standing, its reason saying the record was not written, and the gate +asked again over the same head with the same answer keeps one record. + +## The spot-check at a landing + +When a re-run finds the branch landed, land observes the landing for the +spot-check (itd-2610301750162657), and the `landed` step's note carries what it +did. While the window (`spotcheck.window_days`, seven days by default) has not +passed, it pushes only the records this checkout holds that the store branch +`abcd-spotcheck` on origin lacks, and asks nothing when it holds none. Once the +window has passed, it fetches the store branch and one round of the drand public +randomness beacon, checks the round's signature itself, draws up to +`spotcheck.per_group` items from each group of the work decided with no person +involved, and pushes the drawn items to the branch. Only typed fields reach +origin: a record's free text stays on the machine that wrote it. A draw that +cannot be made (the beacon unreachable or its signature wrong, the forge +unread, the push refused twice) writes nothing, says why, and leaves the +landing as proved; the next landing observed tries again. + **What `human` holds against.** The gate assumes agents keep the rules: it stops an agent merging by mistake, not one set on getting round it. The recorded approval is a file in the checkout's local tier, and anything running diff --git a/go.mod b/go.mod index efc43dea64..2c2911a2e4 100644 --- a/go.mod +++ b/go.mod @@ -3,6 +3,7 @@ module github.com/intentdriven/abcd go 1.27.4 require ( + github.com/cloudflare/circl v1.6.5 github.com/coder/websocket v1.8.15 github.com/minio/selfupdate v0.6.0 github.com/sigstore/sigstore-go v1.4.0 diff --git a/go.sum b/go.sum index 959f2bb211..9bc160730c 100644 --- a/go.sum +++ b/go.sum @@ -74,8 +74,8 @@ github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1x github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw= github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= -github.com/cloudflare/circl v1.6.3 h1:9GPOhQGF9MCYUeXyMYlqTR6a5gTrgR/fBLXvUgtVcg8= -github.com/cloudflare/circl v1.6.3/go.mod h1:2eXP6Qfat4O/Yhh8BznvKnJ+uzEoTQ6jVKJRn81BiS4= +github.com/cloudflare/circl v1.6.5 h1:O64F26HEqNhznd/hrC5KZXVKYuKM2rx4deZDTc4ihQA= +github.com/cloudflare/circl v1.6.5/go.mod h1:h5LNyxAc5nTue9DS5jT+48en2PSDYt3zdGnz5OstK6c= github.com/codahale/rfc6979 v0.0.0-20141003034818-6a90f24967eb h1:EDmT6Q9Zs+SbUoc7Ik9EfrFqcylYqgPZ9ANSbTAntnE= github.com/codahale/rfc6979 v0.0.0-20141003034818-6a90f24967eb/go.mod h1:ZjrT6AXHbDs86ZSdt/osfBi5qfexBrKUdONk989Wnk4= github.com/coder/websocket v1.8.15 h1:6B2JPeOGlpff2Uz6vOEH1Vzpi0iUz20A+lPVhPHtNUA= diff --git a/internal/core/claim/remote.go b/internal/core/claim/remote.go index 58d048f6cd..ab08116b3d 100644 --- a/internal/core/claim/remote.go +++ b/internal/core/claim/remote.go @@ -545,9 +545,10 @@ var spotcheckNetTimeout = time.Minute // branch (refs/heads/abcd-spotcheck), by the one push this package makes // (pushTo): plain, never forced, with the repository's hooks running, so // origin takes it only as a fast-forward. A push origin refused comes back as -// git's own words (pushRejection). A ctx already ended pushes nothing; the -// push itself is bounded by gitutil.NetTimeout, since no runner of gitutil's -// runs the repository's hooks under a caller's context. +// git's own words (pushRejection). A ctx already ended pushes nothing, and +// the push runs under ctx as well as gitutil.NetTimeout, its hooks included +// (gitutil.NetInputContext): git, and the pre-push hook it runs, are stopped +// when ctx ends, so a caller's deadline holds over the whole push. func PushBranch(ctx context.Context, root, sha, ref string) error { if !gitutil.IsFullSHA(sha) || ref != spotcheckBranchRef { return refuse("%s is not a commit and the spot-check's branch to push; %s", echoName(ref), nothingPushed) @@ -555,7 +556,12 @@ func PushBranch(ctx context.Context, root, sha, ref string) error { if err := ctx.Err(); err != nil { return fmt.Errorf("%s: %w", nothingPushed, err) } - return push(root, pushTo(sha, ref)) + args := pushTo(sha, ref) + trace(args...) + if out, err := gitutil.NetInputContext(ctx, root, "", args...); err != nil { + return pushRejection(out, err) + } + return nil } // FetchBranch fetches ref, which must be the spot-check's store branch, into diff --git a/internal/core/claim/spotcheck_push_test.go b/internal/core/claim/spotcheck_push_test.go new file mode 100644 index 0000000000..1eba7e4309 --- /dev/null +++ b/internal/core/claim/spotcheck_push_test.go @@ -0,0 +1,59 @@ +package claim + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +// TestPushHonoursCallerContext: the spot-check's push runs under its +// caller's context, its hooks included. A pre-push hook that hangs is +// stopped when the caller's deadline ends, within the runner's grace, and +// the push is an error that moved nothing on origin; with no hook in the way +// the same push goes through. +func TestPushHonoursCallerContext(t *testing.T) { + r := spotcheckOrigin(t) + bare := strings.TrimSpace(r.Git("remote", "get-url", Remote)) + tip := strings.TrimSpace(r.Git("rev-parse", "HEAD")) + r.Write("b.txt", "b\n") + r.Commit("the next") + next := strings.TrimSpace(r.Git("rev-parse", "HEAD")) + hooks := t.TempDir() + if err := os.WriteFile(filepath.Join(hooks, "pre-push"), []byte("#!/bin/sh\nexec sleep 600\n"), 0o755); err != nil { + t.Fatal(err) + } + r.Git("config", "core.hooksPath", hooks) + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + // grace is the runner's own once its context ends; margin is what the + // test allows past the two for processes to start and be reaped. + const grace, margin = 2 * time.Second, 4 * time.Second + start := time.Now() + err := PushBranch(ctx, r.Root(), next, spotcheckBranchRef) + if took := time.Since(start); took > time.Second+grace+margin { + t.Fatalf("the push took %s under a caller's deadline of a second", took) + } + if err == nil { + t.Fatal("a push whose hook outlasted the caller's deadline succeeded") + } + remote := func() string { + out, _ := os.ReadFile(filepath.Join(bare, filepath.FromSlash(spotcheckBranchRef))) + if len(out) == 0 { + return strings.TrimSpace(r.Git("ls-remote", Remote, spotcheckBranchRef)) + } + return string(out) + } + if got := remote(); !strings.Contains(got, tip) { + t.Fatalf("origin's branch moved under a push cut off by its caller: %s", got) + } + r.Git("config", "--unset", "core.hooksPath") + if err := PushBranch(context.Background(), r.Root(), next, spotcheckBranchRef); err != nil { + t.Fatalf("the push with no hook in the way: %v", err) + } + if got := remote(); !strings.Contains(got, next) { + t.Fatalf("origin's branch is at %s after the push; want %s", got, next) + } +} diff --git a/internal/core/implement/loop/land.go b/internal/core/implement/loop/land.go index 1e173d7871..8a4bba57e7 100644 --- a/internal/core/implement/loop/land.go +++ b/internal/core/implement/loop/land.go @@ -3155,9 +3155,18 @@ func landMerged(c Context, lane *Lane) (Outcome, error) { if tidy := tidyReservation(c, *lane); tidy != "" { note += "; " + tidy } + // The spot-check observes the landing just proved; its note is the + // run's to read, and nothing of the landing waits on it. + if sc := observeLanding(context.Background(), spotcheck.Observed{Root: c.RepoRoot, Default: def, Site: spotcheck.SiteLane}); sc != "" { + note += "; " + sc + } return Outcome{Note: note}, nil } +// observeLanding is spotcheck.AfterLanding, the seam a test counts the +// observations through. +var observeLanding = spotcheck.AfterLanding + // retireLanded removes a landed lane's worktree and branch once merged, the // default branch's commit the landing was proved on, holds what the lane // pushed. The branch is deleted only at a tip merged holds as stored (no diff --git a/internal/core/implement/loop/land_spotcheck_test.go b/internal/core/implement/loop/land_spotcheck_test.go index 9e6fefba68..528e814028 100644 --- a/internal/core/implement/loop/land_spotcheck_test.go +++ b/internal/core/implement/loop/land_spotcheck_test.go @@ -1,6 +1,7 @@ package loop import ( + "context" "strings" "testing" @@ -166,3 +167,37 @@ func keptWhy(why string) string { "origin/main)", "", ).Replace(why) } + +// The spot-check's observation of a landing is turned off for every test of +// the package but the ones that count it: an observation reaches origin and +// the beacon, which no other test here is about. +func init() { + observeLanding = func(context.Context, spotcheck.Observed) string { return "" } +} + +// TestALaneLandingIsObservedOnce: the lane landing the ancestor check proves +// is observed for the spot-check once, from the run's checkout at origin's +// default branch, and the observation's note joins the landing's; a lane not +// yet merged is not observed. +func TestALaneLandingIsObservedOnce(t *testing.T) { + var seen []spotcheck.Observed + saved := observeLanding + t.Cleanup(func() { observeLanding = saved }) + observeLanding = func(_ context.Context, o spotcheck.Observed) string { + seen = append(seen, o) + return "spot-check: observed" + } + f := newLandFixture(t, queueRuleset("MERGE")) + l := f.armReserved(t) + if len(seen) != 0 { + t.Fatalf("a lane not yet merged was observed: %+v", seen) + } + f.merged(t, l.Landing.Pushed) + f.step(t) + if len(seen) != 1 || seen[0].Site != spotcheck.SiteLane || seen[0].Root != f.repo.Root() || seen[0].Default != "main" { + t.Fatalf("the landing was observed as %+v; want once, from the lane site", seen) + } + if note := landNote(t, f); !strings.Contains(note, "; spot-check: observed") { + t.Fatalf("the landing's note does not carry the observation's: %q", note) + } +} diff --git a/internal/core/landing/facilitator.go b/internal/core/landing/facilitator.go index 0bc79875ab..c31ecd9482 100644 --- a/internal/core/landing/facilitator.go +++ b/internal/core/landing/facilitator.go @@ -537,6 +537,12 @@ type MergeDecision struct { // ApprovalCounted says a person's approval of the head counted in the // answer: a forge review or a recorded approval the gate found standing. ApprovalCounted bool + // ModeLayer is the configuration layer that declared the mode, as the + // gate read it ("default" when no file did). + ModeLayer string + // ReceiptNamedHead says a review receipt that stands named the head, as + // the gate read the receipts in auto mode; false in every other case. + ReceiptNamedHead bool } // ErrModeUnreadable wraps a facilitator.mode the gate could not read, whose @@ -584,5 +590,6 @@ func decided(f gateFacts) MergeDecision { } return MergeDecision{Arm: d.arm, Method: d.method, Why: d.why, Unread: !d.arm && (f.role == RoleUnverified || f.reviewUnread || f.approvalUnread), - Mode: f.mode.Mode, AuthorCanWrite: f.role == RoleMaintainer, ApprovalCounted: f.approvedBy != ""} + Mode: f.mode.Mode, AuthorCanWrite: f.role == RoleMaintainer, ApprovalCounted: f.approvedBy != "", + ModeLayer: f.mode.Layer, ReceiptNamedHead: f.reviewed} } diff --git a/internal/core/landing/land.go b/internal/core/landing/land.go index c6b51ff24b..6f10404c5f 100644 --- a/internal/core/landing/land.go +++ b/internal/core/landing/land.go @@ -350,7 +350,7 @@ func Land(cwd string, o Options) (Result, error) { return res, fmt.Errorf("placing %s on %s: %w", short(head), tracking, err) case on: res.Landed = true - res.add("land", StatusLanded, short(head)+" is already on "+Remote+"/"+def+", so "+branch+" has landed: nothing was gated, pushed or queued", "") + res.add("land", StatusLanded, short(head)+" is already on "+Remote+"/"+def+", so "+branch+" has landed: nothing was gated, pushed or queued"+observed(dir, def), "") return res, nil } // A squash or rebase merge puts another commit on the default branch, so @@ -369,7 +369,7 @@ func Land(cwd string, o Options) (Result, error) { "settle what the forge client reports (gh auth status), then run abcd land again; nothing was gated or pushed") case pr > 0: res.Landed, res.PR, res.PRURL = true, pr, prURL - res.add("land", StatusLanded, fmt.Sprintf("pull request #%d merged %s into %s (by a squash or rebase, so the commit itself is not on %s/%s), so %s has landed: nothing was gated, pushed or queued", pr, short(head), def, Remote, def, branch), "") + res.add("land", StatusLanded, fmt.Sprintf("pull request #%d merged %s into %s (by a squash or rebase, so the commit itself is not on %s/%s), so %s has landed: nothing was gated, pushed or queued", pr, short(head), def, Remote, def, branch)+observed(dir, def), "") return res, nil } if err := gate(&res, o, dir, head); err != nil { @@ -1812,6 +1812,21 @@ func shellQuote(s string) string { return shellquote.Single(s) } +// observeLanding is spotcheck.AfterLanding, the seam a test counts the +// observations through. +var observeLanding = spotcheck.AfterLanding + +// observed is the spot-check's note on a landing land has just proved, the +// branch's head on origin's default branch def as just fetched, set after +// "; ", or "" when it has nothing to say. Whatever it says, the landing +// stands as proved. +func observed(dir, def string) string { + if note := observeLanding(context.Background(), spotcheck.Observed{Root: dir, Default: def, Site: spotcheck.SiteLand}); note != "" { + return "; " + note + } + return "" +} + // recordGate is RecordMergeGate, the seam a test turns the record off // through to compare what land does without it. var recordGate = RecordMergeGate @@ -1837,10 +1852,10 @@ func RecordMergeGate(root, site, pr, head string, d MergeDecision) string { n, _ := strconv.Atoi(pr) ctx, cancel := context.WithTimeout(context.Background(), spotcheck.WriteTimeout) defer cancel() - canWrite, counted := d.AuthorCanWrite, d.ApprovalCounted + canWrite, counted, receipt := d.AuthorCanWrite, d.ApprovalCounted, d.ReceiptNamedHead w := spotcheck.Write(ctx, root, spotcheck.Batch{Decisions: []spotcheck.Decision{{Kind: spotcheck.KindMergeGate, At: time.Now(), Holder: spotcheck.Holder(), Site: site, PR: n, Head: head, Arm: d.Arm, Method: d.Method, Why: d.Why, Unread: d.Unread, - Mode: d.Mode, AuthorCanWrite: &canWrite, ApprovalCounted: &counted}}}) + Mode: d.Mode, AuthorCanWrite: &canWrite, ApprovalCounted: &counted, ModeLayer: d.ModeLayer, ReceiptNamedHead: &receipt}}}) switch { case errors.Is(w.Err, spotcheck.ErrNoOrigin): return "" diff --git a/internal/core/landing/land_spotcheck_test.go b/internal/core/landing/land_spotcheck_test.go index 2c841bc7a1..93469f82c1 100644 --- a/internal/core/landing/land_spotcheck_test.go +++ b/internal/core/landing/land_spotcheck_test.go @@ -1,6 +1,7 @@ package landing import ( + "context" "encoding/json" "fmt" "strings" @@ -282,6 +283,9 @@ func TestTheGatesFactsAreFieldsAndTheRecordReadsThem(t *testing.T) { } for _, c := range rows { got := decided(c.f) + // The mode's layer and the receipt are the facts' own, carried as read + // (TestGateDecisionCarriesReceiptAndLayer holds them through the gate). + c.want.ModeLayer, c.want.ReceiptNamedHead = c.f.mode.Layer, c.f.reviewed if got != c.want { t.Errorf("%s: decided\n%+v\nwant\n%+v", c.name, got, c.want) } @@ -328,3 +332,96 @@ func TestAMaintainersApprovedPullRequestInAutoModeIsRecorded(t *testing.T) { t.Fatalf("records: %+v", recs) } } + +// The spot-check's observation of a landing is turned off for every test of +// the package but the ones that count it: an observation reaches origin and +// the beacon, which no other test here is about. +func init() { + observeLanding = func(context.Context, spotcheck.Observed) string { return "" } +} + +// countObservations replaces the observation for the test with one that +// counts and answers a note. +func countObservations(t *testing.T) *[]spotcheck.Observed { + t.Helper() + var seen []spotcheck.Observed + saved := observeLanding + t.Cleanup(func() { observeLanding = saved }) + observeLanding = func(_ context.Context, o spotcheck.Observed) string { + seen = append(seen, o) + return "spot-check: observed" + } + return &seen +} + +// TestTheLandVerbObservesALanding: land re-run on a branch whose head is on +// origin's default branch, or whose pull request merged it by a squash, is +// one observation from the land site, and its note joins the landed step's; +// a land that gates and arms observes nothing. +func TestTheLandVerbObservesALanding(t *testing.T) { + for name, merge := range map[string]func(f *fixture){ + "on the default branch": func(f *fixture) { f.repo.Git("push", "-q", "origin", "feat/x:main") }, + "squashed": func(f *fixture) { + f.squashOntoMain() + f.forge.merged = mergedListing(f.head(), false) + }, + } { + t.Run(name, func(t *testing.T) { + seen := countObservations(t) + f := newFixture(t, queueRuleset) + merge(f) + f.forge.prs = f.prFor(f.head()) + res, err := f.land(f.options()) + if err != nil || !res.Landed { + t.Fatalf("land = %+v, %v", res, err) + } + if len(*seen) != 1 || (*seen)[0].Site != spotcheck.SiteLand || (*seen)[0].Default != "main" { + t.Fatalf("observed %+v; want once from the land site", *seen) + } + if note := res.Steps[0].Note; !strings.HasSuffix(note, "; spot-check: observed") { + t.Fatalf("the landed step's note is %q", note) + } + }) + } + seen := countObservations(t) + f := autoReviewed(t) + wantArmed(t, f, landGate(t, f)) + if len(*seen) != 0 { + t.Fatalf("a land that armed observed %+v", *seen) + } +} + +// TestGateDecisionCarriesReceiptAndLayer: the record of a decision abcd took +// alone names, as fields the gate set, whether a review receipt named the +// head and which layer declared the mode. +func TestGateDecisionCarriesReceiptAndLayer(t *testing.T) { + f := autoReviewed(t) + var handed []MergeDecision + withRecorder(t, func(root, site, pr, head string, d MergeDecision) string { + handed = append(handed, d) + return RecordMergeGate(root, site, pr, head, d) + }, func() Step { return landGate(t, f) }) + if len(handed) != 1 || !handed[0].ReceiptNamedHead || handed[0].ModeLayer != "repo" { + t.Fatalf("the gate decided %+v; want a receipt naming the head, the mode from the repo layer", handed) + } + recs := gateRecords(t, f) + if len(recs) != 1 || recs[0].ReceiptNamedHead == nil || !*recs[0].ReceiptNamedHead || recs[0].ModeLayer != "repo" { + t.Fatalf("the record is %+v", recs) + } +} + +// TestRearmGateIsRecorded: the merge gate asked afresh at a re-arm, in auto +// mode with no person's approval, is recorded from the rearm site. +func TestRearmGateIsRecorded(t *testing.T) { + f := newFixtureFiles(t, queueRuleset, map[string]string{".abcd/config.json": autoConfig}) + f.forge.head = f.head() + f.reviewed(t) + ask := func(args ...string) (string, error) { return f.forge.run(f.repo.Root(), args...) } + if arm, why, err := rearmGate(ask, f.repo.Root(), "o/r", "7", f.head()); err != nil || !arm { + t.Fatalf("arm %v, why %q, err %v", arm, why, err) + } + recs := gateRecords(t, f) + if len(recs) != 1 || recs[0].Site != spotcheck.SiteRearm || recs[0].PR != 7 || recs[0].Head != f.head() || !recs[0].Arm { + t.Fatalf("the re-arm's record is %+v", recs) + } +} diff --git a/internal/core/landing/withdraw.go b/internal/core/landing/withdraw.go index 08a8b87078..a3c1113233 100644 --- a/internal/core/landing/withdraw.go +++ b/internal/core/landing/withdraw.go @@ -16,6 +16,7 @@ import ( "github.com/intentdriven/abcd/internal/core/claim" "github.com/intentdriven/abcd/internal/core/layered" + "github.com/intentdriven/abcd/internal/core/spotcheck" "github.com/intentdriven/abcd/internal/fsutil" "github.com/intentdriven/abcd/internal/gitutil" ) @@ -406,10 +407,14 @@ func rearmGate(ask ForgeCall, root, repo, pr, head string) (bool, string, error) if err != nil { return false, "", err } + why := d.Why + if note := recordGate(root, spotcheck.SiteRearm, pr, head, d); note != "" { + why += "; " + note + } if d.Unread { - return false, "", errors.New(d.Why) + return false, "", errors.New(why) } - return d.Arm, d.Why, nil + return d.Arm, why, nil } // The release hold's arming is held to the merge gate here: claim cannot import diff --git a/internal/core/landings/spotcheck.go b/internal/core/landings/spotcheck.go new file mode 100644 index 0000000000..f2070842f8 --- /dev/null +++ b/internal/core/landings/spotcheck.go @@ -0,0 +1,40 @@ +package landings + +// spotcheck.go hands the spot-check's draw this reader (spc-2610301925429250 +// approach 4). The spot-check cannot import this package, which imports +// internal/core/landing, which imports it; so the reader registers itself +// there when this package is linked, as the merge gate registers itself with +// claim for a re-arm. + +import ( + "context" + + "github.com/intentdriven/abcd/internal/core/spotcheck" +) + +func init() { + spotcheck.RegisterLandingsReader(func(ctx context.Context, root, from, to string) ([]spotcheck.LandingRow, error) { + return spotcheckRows(ctx, root, from, to, Options{}) + }) +} + +// spotcheckRows are the rows of from (exclusive) to to (inclusive) as the +// draw reads them: the class, the rule, the trailers and the commit, and +// whether the row's approval could not be settled because the forge's answer +// was not read. The reader's words for why it classed a row stay here. +func spotcheckRows(ctx context.Context, root, from, to string, o Options) ([]spotcheck.LandingRow, error) { + l, err := List(ctx, root, Range{From: from, To: to}, o) + if err != nil { + return nil, err + } + rows := make([]spotcheck.LandingRow, 0, len(l.Rows)) + for _, r := range l.Rows { + rows = append(rows, spotcheck.LandingRow{ + Commit: r.Commit, When: r.When, PR: r.PR, MergedHead: r.MergedHead, Class: r.Class, + RuleKind: r.Rule.Kind, RuleID: r.Rule.ID, RulePath: r.Rule.Path, Lane: r.Lane, Mode: r.Mode, + Resolves: r.Resolves, Delivers: r.Delivers, Unattended: r.Unattended, + ForgeUnread: r.ForgeUnreadable != "" || r.Approval.Source == SourceForgeUnread, + }) + } + return rows, nil +} diff --git a/internal/core/landings/spotcheck_test.go b/internal/core/landings/spotcheck_test.go new file mode 100644 index 0000000000..6bc433cb73 --- /dev/null +++ b/internal/core/landings/spotcheck_test.go @@ -0,0 +1,56 @@ +package landings + +import ( + "context" + "testing" + + "github.com/intentdriven/abcd/internal/core/spotcheck" +) + +// TestLandingsReaderIsRegistered: the draw reads the classes by the names +// this reader gives them, and the rows it is handed are the listing's, typed, +// with a row whose forge answer was not read marked so. +func TestLandingsReaderIsRegistered(t *testing.T) { + if spotcheck.ClassDrain != ClassDrain || spotcheck.ClassAutomatic != ClassAutomatic { + t.Fatalf("the draw names the classes %q and %q; the reader %q and %q", spotcheck.ClassDrain, spotcheck.ClassAutomatic, ClassDrain, ClassAutomatic) + } + f := newFx(t, "auto") + b := f.branch("d", "fix: x", recordsCommit(drainTrailer)) + m := f.merge(50, "d") + bn := f.branch("none", "feat: no trailer") + mn := f.merge(51, "none") + ff := &fakeForge{t: t} + ff.add(answer(50, m, b)) + ff.add(answer(51, mn, bn)) + rows, err := spotcheckRows(context.Background(), f.r.Root(), f.base, f.head(), Options{Forge: ff.call}) + if err != nil || len(rows) != 2 { + t.Fatalf("rows = %+v, %v", rows, err) + } + byCommit := map[string]spotcheck.LandingRow{} + for _, r := range rows { + byCommit[r.Commit] = r + } + if r := byCommit[m]; r.Class != ClassDrain || r.RuleKind != KindDrain || r.RuleID != "adr-2609291342092738" || r.RulePath != ruleRel || r.PR != 50 || r.ForgeUnread || !r.Unattended { + t.Fatalf("the drain row is %+v", r) + } + if r := byCommit[mn]; r.Class != ClassAutomatic || r.ForgeUnread { + t.Fatalf("the automatic row is %+v", r) + } + // A forge that cannot answer marks every row it left unread. A fresh + // checkout, since the first listing's cache keeps the answers it settled. + g := newFx(t, "auto") + g.branch("d", "fix: x", recordsCommit(drainTrailer)) + g.merge(50, "d") + g.branch("none", "feat: no trailer") + g.merge(51, "none") + unread := &fakeForge{t: t, err: context.DeadlineExceeded} + rows, err = spotcheckRows(context.Background(), g.r.Root(), g.base, g.head(), Options{Forge: unread.call}) + if err != nil || len(rows) != 2 { + t.Fatalf("rows = %+v, %v", rows, err) + } + for _, r := range rows { + if !r.ForgeUnread { + t.Fatalf("a row the forge did not answer for is not marked unread: %+v", r) + } + } +} diff --git a/internal/core/spotcheck/afterlanding.go b/internal/core/spotcheck/afterlanding.go new file mode 100644 index 0000000000..8cdcef2b36 --- /dev/null +++ b/internal/core/spotcheck/afterlanding.go @@ -0,0 +1,289 @@ +package spotcheck + +// afterlanding.go is the collection lane's one entry (spc-2610301925429250 +// approaches 3 and 11): AfterLanding, called where abcd has just proved a +// landing. While the window has not passed it reads two files and runs one +// local git command, and reaches the network only to carry records this +// checkout holds that origin's copy, as last fetched, lacks. Once the window +// has passed it fetches the store's branch, the beacon's latest round, reads +// the window's landings, draws, and pushes the cycle with its items in one +// commit over origin's copy. Whatever it does, its answer is a note and +// never an error, an outcome or a hold: a draw that refuses for any reason +// leaves the window passed and writes nothing, and the next landing observed +// tries again. Nothing it does decides anything a landing or a drain does. + +import ( + "context" + "encoding/hex" + "errors" + "fmt" + "strconv" + "strings" + "time" + + "github.com/intentdriven/abcd/internal/core/layered" + "github.com/intentdriven/abcd/internal/gitutil" +) + +// DrawTimeout bounds one observation that draws: the fetch, the beacon, the +// landings read and the push together. +const DrawTimeout = 3 * time.Minute + +// Observed is one landing abcd proved: the checkout, origin's default +// branch as just fetched, and the site that proved it. +type Observed struct { + Root string + Default string + // Site is SiteLane, SiteLand or SiteDrain. + Site string + // Now is the observing instant; zero is time.Now. + Now time.Time +} + +// now is the clock AfterLanding reads when an observation names none. +var now = time.Now + +// AfterLanding observes a landing for the spot-check and answers a note for +// the caller's own text, "" when there is nothing to say. A checkout with no +// remote named origin keeps no spot-check, and the note is "". +func AfterLanding(parent context.Context, o Observed) string { + if o.Now.IsZero() { + o.Now = now() + } + o.Now = o.Now.UTC().Truncate(time.Second) + if o.Site != SiteLand && o.Site != SiteLane && o.Site != SiteDrain { + return "spot-check: " + fmt.Sprintf("%q is not an observing site, so nothing was drawn", o.Site) + } + ctx, cancel := context.WithTimeout(parent, DrawTimeout) + defer cancel() + if err := originPresent(ctx, o.Root); err != nil { + if errors.Is(err, ErrNoOrigin) { + return "" + } + return "spot-check: " + err.Error() + "; nothing was drawn" + } + roots, _ := layered.RootsFor(o.Root) + cfg, err := readConfig(roots) + if err != nil { + return "spot-check: the spotcheck configuration cannot be read (" + redact(err) + "); nothing was drawn" + } + tip, err := defaultTip(ctx, o.Root, o.Default) + if err != nil { + return "spot-check: " + err.Error() + "; nothing was drawn" + } + st, err := readWindow(ctx, o.Root) + if err != nil { + return "spot-check: " + err.Error() + "; nothing was drawn" + } + if st.open { + closedBy, err := closedNow(ctx, o.Root, cfg, st, tip, o.Now) + if err != nil { + return "spot-check: " + err.Error() + "; nothing was drawn" + } + if closedBy == "" { + pending, _, err := outbound(ctx, o.Root, st.files) + if err != nil { + return "spot-check: " + err.Error() + } + if len(pending) == 0 { + return "" + } + return carry(ctx, o.Root) + } + } + return draw(ctx, o, cfg, tip) +} + +// defaultTip is origin's default branch as this checkout last fetched it. +func defaultTip(ctx context.Context, root, def string) (string, error) { + if def == "" || strings.ContainsAny(def, " \t\n:^~?*[\\") || strings.HasPrefix(def, "-") { + return "", errors.New("origin's default branch is not named, so the window cannot be counted") + } + out, err := gitutil.RunCappedBytesAsStoredContext(ctx, root, "", 256, "rev-parse", "--verify", "--quiet", "refs/remotes/origin/"+def+"^{commit}", "--") + tip := strings.TrimSpace(string(out)) + if err != nil || !gitutil.IsFullSHA(tip) { + return "", fmt.Errorf("origin/%s cannot be read, so the window cannot be counted", def) + } + return tip, nil +} + +// closedNow is the bound the window st holds has passed by now, at tip. +func closedNow(ctx context.Context, root string, cfg Config, st windowState, tip string, at time.Time) (string, error) { + changes := 0 + if cfg.WindowChanges > 0 { + n, err := changesSince(ctx, root, st.from, tip) + if err != nil { + return "", err + } + changes = n + } + return windowClosedBy(cfg, st.fromTime, changes, at), nil +} + +// carry pushes the records origin's copy lacks, with nothing drawn. +func carry(ctx context.Context, root string) string { + res, err := push(ctx, root) + switch { + case err != nil: + return "spot-check: " + redact(err) + case res.Pushed > 0: + return fmt.Sprintf("spot-check: carried %d record(s) to %s", res.Pushed, Branch) + } + return "" +} + +// draw is AfterLanding once the window may have passed: tried twice, the +// second time after a fresh fetch when origin rejected the first push. +func draw(ctx context.Context, o Observed, cfg Config, tip string) string { + var beacon *Beacon + var last error + for attempt := 1; attempt <= 2; attempt++ { + if _, err := fetchTracking(ctx, o.Root); err != nil { + return "spot-check: " + redact(err) + "; nothing was drawn" + } + st, err := readWindow(ctx, o.Root) + if err != nil { + return "spot-check: " + err.Error() + "; nothing was drawn" + } + pending, _, err := outbound(ctx, o.Root, st.files) + if err != nil { + return "spot-check: " + err.Error() + "; nothing was drawn" + } + if !st.open { + w, err := encodeFile("", WindowOpenFile, WindowOpen{SchemaVersion: SchemaVersion, Commit: tip, At: o.Now, Holder: Holder()}) + if err != nil { + return "spot-check: " + err.Error() + } + if _, err := pushOver(ctx, o.Root, st.tracking, append(pending, w), "spotcheck: the first window opens"); err != nil { + last = err + continue + } + return "spot-check: the first window opened at " + tip[:12] + "; nothing is drawn until it passes" + } + closedBy, err := closedNow(ctx, o.Root, cfg, st, tip, o.Now) + if err != nil { + return "spot-check: " + err.Error() + "; nothing was drawn" + } + if closedBy == "" { + // Another writer drew this window first. + if len(pending) == 0 { + return "" + } + if _, err := pushOver(ctx, o.Root, st.tracking, pending, fmt.Sprintf("spotcheck: %d record(s)", len(pending))); err != nil { + last = err + continue + } + return fmt.Sprintf("spot-check: carried %d record(s) to %s", len(pending), Branch) + } + if beacon == nil { + b, err := fetchBeacon(ctx, o.Now) + if err != nil { + return "spot-check: " + err.Error() + "; nothing was drawn" + } + beacon = &b + } + c, items, err := makeCycle(ctx, o, cfg, st, tip, closedBy, *beacon, pending) + if err != nil { + return "spot-check: " + err.Error() + "; nothing was drawn" + } + files := append(pending, items...) + cf, err := encodeFile(CyclesDir, c.ID+".json", c) + if err != nil { + return "spot-check: " + err.Error() + "; nothing was drawn" + } + files = append(files, cf) + if _, err := pushOver(ctx, o.Root, st.tracking, files, "spotcheck: cycle "+c.ID); err != nil { + last = err + continue + } + drawn := 0 + for _, g := range c.Groups { + drawn += len(g.Drawn) + } + return fmt.Sprintf("spot-check: drew cycle %s (round %d of the beacon): %d item(s) for review", c.ID, beacon.Round, drawn) + } + return "spot-check: the push to " + Branch + " was refused twice (" + redact(last) + "); nothing was drawn, and the next landing tries again" +} + +// makeCycle draws the cycle closing st's window at tip: the populations of +// the window (from st.from exclusive to tip, from st.fromTime exclusive to +// o.Now), the size over the cycles before it, and an item file per drawn key. +// pending are the typed records this checkout carries in the same commit, +// read as origin's own. +func makeCycle(ctx context.Context, o Observed, cfg Config, st windowState, tip, closedBy string, b Beacon, pending []file) (Cycle, []file, error) { + reader := registeredReader() + if reader == nil { + return Cycle{}, nil, errNoReader + } + var rows []LandingRow + if st.from != tip { + var err error + if rows, err = reader(ctx, o.Root, st.from, tip); err != nil { + return Cycle{}, nil, fmt.Errorf("the window's landings cannot be read: %s", redact(err)) + } + } + rec, _, err := read(ctx, o.Root, TrackingRef) + if err != nil { + return Cycle{}, nil, err + } + var hbs []namedHandBack + var ds []namedDecision + for i, h := range rec.HandBacks { + hbs = append(hbs, namedHandBack{name: rec.handBackNames[i], h: h}) + } + for i, d := range rec.Decisions { + ds = append(ds, namedDecision{name: rec.decisionNames[i], d: d}) + } + for _, f := range pending { + var one Records + if !readRecord(&one, f.folder, f.name, f.data) { + continue + } + for _, h := range one.HandBacks { + hbs = append(hbs, namedHandBack{name: f.name, h: h}) + } + for _, d := range one.Decisions { + ds = append(ds, namedDecision{name: f.name, d: d}) + } + } + groups, err := populations(rows, hbs, ds, st.fromTime, o.Now) + if err != nil { + return Cycle{}, nil, err + } + tallies, err := tallyCycles(ctx, o.Root, st) + if err != nil { + return Cycle{}, nil, err + } + size, why, counted := sampleSize(cfg.PerGroup, tallies) + randomness, err := hex.DecodeString(b.Randomness) + if err != nil || len(randomness) != 32 { + return Cycle{}, nil, errors.New("the beacon's randomness does not read") + } + c := Cycle{SchemaVersion: SchemaVersion, ID: cycleID(o.Now, tip), FromCommit: st.from, ToCommit: tip, + FromTime: st.fromTime, ToTime: o.Now, ClosedBy: closedBy, Site: o.Site, Beacon: b, Draw: DrawRule, + Sample: Sample{PerGroup: cfg.PerGroup, Size: size, Why: why, Counted: counted}, Holder: Holder()} + var items []file + n := 0 + for _, g := range groupOrder { + cands := groups[g] + keys := make([]string, len(cands)) + byKey := map[string]candidate{} + for i, cd := range cands { + keys[i], byKey[cd.key] = cd.key, cd + } + drawn := drawKeys(randomness, c.ID, g, keys, size) + c.Groups = append(c.Groups, GroupDraw{Group: g, Population: population(keys), Drawn: drawn}) + for _, k := range drawn { + n++ + cd := byKey[k] + it := Item{SchemaVersion: SchemaVersion, Cycle: c.ID, Number: n, Group: g, Key: k, Roles: cd.roles, + Landing: cd.landing, HandBack: cd.handBack, Decision: cd.decision} + f, err := encodeFile(ItemsDir+"/"+c.ID, itemStem(n, g, k)+".json", it) + if err != nil { + return Cycle{}, nil, fmt.Errorf("item %s of the cycle cannot be kept: %w", strconv.Itoa(n), err) + } + items = append(items, f) + } + } + return c, items, nil +} diff --git a/internal/core/spotcheck/afterlanding_test.go b/internal/core/spotcheck/afterlanding_test.go new file mode 100644 index 0000000000..6adeeeaf07 --- /dev/null +++ b/internal/core/spotcheck/afterlanding_test.go @@ -0,0 +1,365 @@ +package spotcheck + +import ( + "context" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "slices" + "strings" + "testing" + "time" + + "github.com/intentdriven/abcd/internal/gittest" +) + +// originWithRemote is a checkout whose origin, a bare remote, holds main, +// fetched, so origin/main is tracked. +func originWithRemote(t *testing.T) (*gittest.Repo, string) { + t.Helper() + bare := filepath.Join(t.TempDir(), "origin.git") + gittest.InitBare(t, bare) + r := clone(t, bare) + r.Git("push", "-q", "origin", "HEAD:refs/heads/main") + r.Git("fetch", "-q", "origin") + return r, bare +} + +func encodeOrFail(t *testing.T, v any) string { + t.Helper() + b, err := encode(v) + if err != nil { + t.Fatal(err) + } + return string(b) +} + +// setTracking puts files on origin's branch, as another writer would, and +// fetches it to the tracking ref. +func setTracking(t *testing.T, r *gittest.Repo, files map[string]string) string { + t.Helper() + c := commitFilesAt(t, r, "", files) + r.Git("push", "-q", "origin", c+":"+BranchRef) + r.Git("update-ref", TrackingRef, c) + return c +} + +// drawCase is a checkout set up for AfterLanding: an empty home, the beacon +// serving the round-1000 vector and a landings reader answering rows. +type drawCase struct { + t *testing.T + r *gittest.Repo + bare string + beacons int + reads int + rows []LandingRow + beacon func() ([]byte, error) + readErr error + from string + to string +} + +func newDrawCase(t *testing.T) *drawCase { + t.Helper() + t.Setenv("HOME", t.TempDir()) + r, bare := originWithRemote(t) + c := &drawCase{t: t, r: r, bare: bare} + c.beacon = func() ([]byte, error) { return beaconReply("1000", vectorSignature, vectorRandomness), nil } + oldGet := beaconGet + beaconGet = func(ctx context.Context, url string) ([]byte, error) { + c.beacons++ + return c.beacon() + } + oldReader := registeredReader() + RegisterLandingsReader(func(ctx context.Context, root, from, to string) ([]LandingRow, error) { + c.reads++ + c.from, c.to = from, to + return c.rows, c.readErr + }) + t.Cleanup(func() { beaconGet = oldGet; RegisterLandingsReader(oldReader) }) + return c +} + +func (c *drawCase) observe(at time.Time) string { + c.t.Helper() + return AfterLanding(c.t.Context(), Observed{Root: c.r.Root(), Default: "main", Site: SiteLane, Now: at}) +} + +// originTip is origin's store branch, "" for none. +func (c *drawCase) originTip() string { + out, err := os.ReadFile(filepath.Join(c.bare, "refs", "heads", Branch)) + if err == nil { + return strings.TrimSpace(string(out)) + } + return strings.TrimSpace(gitIn(c.t, c.bare, "for-each-ref", "--format=%(objectname)", BranchRef)) +} + +// originFile is one file of origin's branch. +func (c *drawCase) originFile(p string) string { + c.t.Helper() + return gitIn(c.t, c.bare, "show", BranchRef+":"+p) +} + +// land puts n first-parent commits on origin's main and fetches it. +func (c *drawCase) land(n int) string { + c.t.Helper() + for range n { + c.r.Commit("a landing") + } + c.r.Git("push", "-q", "origin", "HEAD:refs/heads/main") + c.r.Git("fetch", "-q", "origin") + return c.r.Git("rev-parse", "origin/main") +} + +func TestFirstCheckOpensTheWindow(t *testing.T) { + c := newDrawCase(t) + note := c.observe(at0) + if !strings.Contains(note, "first window opened") { + t.Fatalf("the first check's note is %q", note) + } + if files := remoteFiles(t, c.bare); !slices.Equal(files, []string{WindowOpenFile}) { + t.Fatalf("origin's branch holds %v; want the window's opening alone", files) + } + var w WindowOpen + if err := json.Unmarshal([]byte(c.originFile(WindowOpenFile)), &w); err != nil || w.Commit != c.r.Git("rev-parse", "origin/main") || !w.At.Equal(at0) { + t.Fatalf("window-open.json = %+v, %v", w, err) + } + if c.beacons != 0 || c.reads != 0 { + t.Fatalf("the first check asked the beacon %d and the reader %d times; it draws nothing", c.beacons, c.reads) + } +} + +// TestWindowNotPassedDrawsNothingAndFetchesNothing: with the window open and +// not passed, and nothing to carry, an observation reaches no network (origin +// cannot be reached at all), asks neither the beacon nor the reader, and +// says nothing. A record to carry is carried at the next observation. +func TestWindowNotPassedDrawsNothingAndFetchesNothing(t *testing.T) { + c := newDrawCase(t) + c.observe(at0) + tip := c.originTip() + c.r.Git("remote", "set-url", "origin", filepath.Join(t.TempDir(), "gone.git")) + if note := c.observe(at0.Add(6 * 24 * time.Hour)); note != "" { + t.Fatalf("an observation inside the window said %q", note) + } + if c.beacons != 0 || c.reads != 0 { + t.Fatalf("inside the window the beacon was asked %d and the reader %d times", c.beacons, c.reads) + } + write(t, c.r.Root(), hb(handBack("iss-1", at0.Add(time.Hour)))) + if note := c.observe(at0.Add(6 * 24 * time.Hour)); !strings.Contains(note, "not fetched") { + t.Fatalf("a record to carry with origin gone: note %q", note) + } + c.r.Git("remote", "set-url", "origin", c.bare) + if note := c.observe(at0.Add(6 * 24 * time.Hour)); !strings.Contains(note, "carried 1 record") { + t.Fatalf("the record was not carried: %q", note) + } + if c.originTip() == tip || c.beacons != 0 { + t.Fatalf("origin is at %s (was %s), beacon asked %d times", c.originTip(), tip, c.beacons) + } +} + +// TestADrawAtAPassedWindow: once the window has passed, the observation +// fetches the beacon, reads the window's landings, and pushes the cycle, its +// items and the records in one commit; the draw recomputes from the cycle +// record alone; no free text reaches origin; and the next window opens at the +// cycle's end. +func TestADrawAtAPassedWindow(t *testing.T) { + c := newDrawCase(t) + c.observe(at0) + from := c.r.Git("rev-parse", "origin/main") + to := c.land(3) + for i := range 14 { + c.rows = append(c.rows, row(fmt.Sprintf("%040x", i+1), ClassDrain)) + } + c.rows = append(c.rows, row(fmt.Sprintf("%040x", 100), ClassAutomatic), row(fmt.Sprintf("%040x", 101), "person-approved")) + h := handBack("iss-2", at0.Add(24*time.Hour)) + h.Reason = "the secret reason the drain wrote" + d := gateDecision(4, sha('f'), true, at0.Add(25*time.Hour)) + write(t, c.r.Root(), Batch{HandBacks: []HandBack{h}, Decisions: []Decision{d}}) + at := at0.Add(8 * 24 * time.Hour) + note := c.observe(at) + if !strings.Contains(note, "drew cycle") || !strings.Contains(note, "13 item(s)") { + t.Fatalf("the draw's note is %q", note) + } + if c.from != from || c.to != to { + t.Fatalf("the reader read %s..%s; want %s..%s", c.from, c.to, from, to) + } + id := cycleID(at, to) + var cy Cycle + if err := json.Unmarshal([]byte(c.originFile(CyclesDir+"/"+id+".json")), &cy); err != nil { + t.Fatal(err) + } + if cy.FromCommit != from || cy.ToCommit != to || cy.ClosedBy != ClosedByDays || cy.Site != SiteLane || cy.Beacon.Round != 1000 || + cy.Sample.Size != 10 || cy.Sample.Why != SizeFull || len(cy.Groups) != 4 { + t.Fatalf("the cycle is %+v", cy) + } + randomness, _ := hex.DecodeString(cy.Beacon.Randomness) + items := 0 + for _, g := range cy.Groups { + if again := drawKeys(randomness, cy.ID, g.Group, g.Population.Keys, cy.Sample.Size); !slices.Equal(again, g.Drawn) { + t.Errorf("group %s does not recompute from the cycle record: %v vs %v", g.Group, again, g.Drawn) + } + items += len(g.Drawn) + } + want := map[string]int{GroupDrainLanded: 14, GroupAutomaticMerges: 1, GroupDrainHandBacks: 1, GroupFacilitatorDecisions: 1} + for _, g := range cy.Groups { + if g.Population.Count != want[g.Group] { + t.Errorf("group %s has a population of %d; want %d", g.Group, g.Population.Count, want[g.Group]) + } + } + files := remoteFiles(t, c.bare) + nItems := 0 + for _, f := range files { + if strings.HasPrefix(f, ItemsDir+"/"+id+"/") { + nItems++ + } + if body := c.originFile(f); strings.Contains(body, "secret reason") || strings.Contains(body, "review receipt") { + t.Errorf("origin's %s carries free text:\n%s", f, body) + } + } + if nItems != items || items != 13 { + t.Fatalf("origin holds %d items for %d drawn; want 13", nItems, items) + } + if note := c.observe(at.Add(time.Hour)); note != "" { + t.Fatalf("an observation an hour after the draw said %q", note) + } +} + +// TestBeaconUnreachableWritesNothing and its kin: a draw the beacon refuses +// (unreachable, a signature that does not verify, another chain) writes +// nothing to origin, names the beacon, and leaves the window passed for the +// next observation, which draws. +func TestBeaconUnreachableWritesNothing(t *testing.T) { + for name, reply := range map[string]func() ([]byte, error){ + "unreachable": func() ([]byte, error) { return nil, errors.New("no route") }, + "bad signature": func() ([]byte, error) { return beaconReply("1001", vectorSignature, ""), nil }, + "other chain": func() ([]byte, error) { + return []byte(`{"round":1000,"signature":"` + vectorSignature + `","chain_hash":"` + strings.Repeat("ab", 32) + `"}`), nil + }, + } { + t.Run(name, func(t *testing.T) { + c := newDrawCase(t) + c.observe(at0) + c.land(1) + c.rows = []LandingRow{row(sha('a'), ClassDrain)} + write(t, c.r.Root(), hb(handBack("iss-2", at0.Add(time.Hour)))) + tip := c.originTip() + c.beacon = reply + note := c.observe(at0.Add(8 * 24 * time.Hour)) + if !strings.Contains(note, "beacon") || !strings.Contains(note, "nothing was drawn") { + t.Fatalf("the refused draw's note is %q", note) + } + if c.originTip() != tip { + t.Fatal("a refused draw moved origin's branch") + } + c.beacon = func() ([]byte, error) { return beaconReply("1000", vectorSignature, ""), nil } + if note := c.observe(at0.Add(8*24*time.Hour + time.Minute)); !strings.Contains(note, "drew cycle") { + t.Fatalf("the next observation did not draw: %q", note) + } + }) + } +} + +// TestBeaconBadSignatureWritesNothing is the bad-signature case named alone, +// as the spec lists it. +func TestBeaconBadSignatureWritesNothing(t *testing.T) { + c := newDrawCase(t) + c.observe(at0) + tip := c.originTip() + c.beacon = func() ([]byte, error) { return beaconReply("999", vectorSignature, ""), nil } + note := c.observe(at0.Add(8 * 24 * time.Hour)) + if !strings.Contains(note, "round 999") || !strings.Contains(note, "does not verify") || c.originTip() != tip { + t.Fatalf("note %q, origin moved %v", note, c.originTip() != tip) + } +} + +// TestRejectedPushLeavesNoCycle: a push origin refuses twice leaves origin as +// it was, the draw refused, and the window passed. +func TestRejectedPushLeavesNoCycle(t *testing.T) { + c := newDrawCase(t) + c.observe(at0) + tip := c.originTip() + hooks := t.TempDir() + if err := os.WriteFile(filepath.Join(hooks, "pre-push"), []byte("#!/bin/sh\nexit 1\n"), 0o755); err != nil { + t.Fatal(err) + } + c.r.Git("config", "core.hooksPath", hooks) + note := c.observe(at0.Add(8 * 24 * time.Hour)) + if !strings.Contains(note, "refused twice") || c.originTip() != tip { + t.Fatalf("note %q; origin moved %v", note, c.originTip() != tip) + } +} + +// TestDrawWithNoReaderIsRefused: a binary with no landings reader linked +// draws nothing. +func TestDrawWithNoReaderIsRefused(t *testing.T) { + c := newDrawCase(t) + c.observe(at0) + RegisterLandingsReader(nil) + tip := c.originTip() + if note := c.observe(at0.Add(8 * 24 * time.Hour)); !strings.Contains(note, "no landings reader") || c.originTip() != tip { + t.Fatalf("note %q", note) + } +} + +// TestPushCarriesOnlyRecords: a file of the local copy that does not read as +// a record, under the store's folders or outside them, never reaches origin. +func TestPushCarriesOnlyRecords(t *testing.T) { + r, bare := originWithRemote(t) + write(t, r.Root(), hb(handBack("iss-1", at0))) + local := r.Git("rev-parse", LocalRef) + stray := commitFilesAt(t, r, local, map[string]string{ + "notes/x.txt": "a note\n", + HandBacksDir + "/20261113T070000Z-iss-9-0000000000000000.json": "{}\n", + ItemsDir + "/forged.json": "{}\n", + }) + r.Git("update-ref", LocalRef, stray) + res, err := push(t.Context(), r.Root()) + if err != nil || res.Pushed != 1 { + t.Fatalf("push = %+v, %v", res, err) + } + files := remoteFiles(t, bare) + if len(files) != 1 || !strings.HasPrefix(files[0], HandBacksDir+"/") || !strings.Contains(files[0], "-iss-1-") { + t.Fatalf("origin holds %v; want the one record", files) + } +} + +// TestFreeTextIsNotSent: a record's free text stays on the local copy; origin +// gets its typed fields alone, under a name of their own. +func TestFreeTextIsNotSent(t *testing.T) { + r, bare := originWithRemote(t) + h := handBack("iss-1", at0) + h.Rule = "the lane's rule as the drain wrote it" + d := Decision{Kind: KindDrainJudgement, At: at0, Issue: "iss-2", Question: "may the drain take it", Answer: "yes", Model: "claude-opus-4-8", Rule: "adr-2609291342092738", Reason: "it looked fine"} + g := gateDecision(4, sha('f'), true, at0) + write(t, r.Root(), Batch{HandBacks: []HandBack{h}, Decisions: []Decision{d, g}}) + if _, err := push(t.Context(), r.Root()); err != nil { + t.Fatal(err) + } + r.Git("fetch", "-q", "origin", "+"+BranchRef+":"+TrackingRef) + rec, ok, err := read(t.Context(), r.Root(), TrackingRef) + if err != nil || !ok || len(rec.HandBacks) != 1 || len(rec.Decisions) != 2 || len(rec.Unreadable) != 0 { + t.Fatalf("origin's copy reads as %+v, %v, %v", rec, ok, err) + } + for _, f := range remoteFiles(t, bare) { + body := gitIn(t, bare, "show", BranchRef+":"+f) + for _, text := range []string{h.Reason, h.Rule, d.Question, d.Reason, "review receipt"} { + if strings.Contains(body, text) { + t.Errorf("origin's %s carries %q", f, text) + } + } + } + if rec.HandBacks[0].DrainRule != h.DrainRule || rec.HandBacks[0].Kind != h.Kind { + t.Errorf("origin's hand-back lost a typed field: %+v", rec.HandBacks[0]) + } + local := readLocal(t, r.Root()) + if local.HandBacks[0].Reason != h.Reason { + t.Errorf("the local copy lost the reason: %+v", local.HandBacks[0]) + } + // A second push carries nothing more. + if res, err := push(t.Context(), r.Root()); err != nil || res.Pushed != 0 { + t.Fatalf("a second push = %+v, %v", res, err) + } +} diff --git a/internal/core/spotcheck/beacon.go b/internal/core/spotcheck/beacon.go new file mode 100644 index 0000000000..8421393c7d --- /dev/null +++ b/internal/core/spotcheck/beacon.go @@ -0,0 +1,237 @@ +package spotcheck + +// beacon.go is the draw's seed (spc-2610301925429250 approach 4): one round +// of drand's quicknet chain, a public randomness beacon no agent can steer, +// fetched only once a window has closed and verified here, at the draw, +// under the chain's pinned public key. A round whose signature does not +// verify is no seed at all: the draw is refused and nothing is written. + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/binary" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "time" + + "github.com/cloudflare/circl/sign/bls" + + "github.com/intentdriven/abcd/internal/core/jsonstrict" + "github.com/intentdriven/abcd/internal/urlguard" +) + +// ChainHash is the quicknet chain's hash, as its info reply names it, read +// on 31 October 2026 (.abcd/development/research/notes/ +// 2026-10-31-drand-beacon-verification-sota.md). Every round is asked of the +// chain by this hash. +const ChainHash = "52db9ba70e0cc0f6eaf7803dd07447a1f5477735fd3f661792ba94600c84e971" + +// chainKey is the quicknet chain's group public key, a compressed point on +// G2 (scheme bls-unchained-g1-rfc9380: signatures on G1, keys on G2), read +// from the same info reply. +const chainKey = "83cf0f2896adee7eb8b5f01fcad3912212c437e0073e911fb90022d3e760183c8c4b450b6a0a6c3ac6a5776a2d1064510d1fec758c921cc22b0e17e63aaf4bcb5ed66304de9cf809bd274ca73bab4af5a6e9c76a4bc09e76eae8991ef5ece45a" + +// The beacon's bounds. +const ( + // BeaconTimeout bounds the beacon's fetch, every host it asks together. + BeaconTimeout = 10 * time.Second + // maxBeaconBytes bounds one reply. + maxBeaconBytes = 4 << 10 + // sigHexLen is a G1 signature's length in hex digits: 48 bytes. + sigHexLen = 96 +) + +// beaconHosts are the hosts a round is asked of, in order: the next is asked +// only when the one before could not be reached. +var beaconHosts = []string{"api.drand.sh", "api2.drand.sh", "api3.drand.sh"} + +// Beacon is the round a cycle was drawn from, as the cycle record keeps it, +// so anyone can repeat the verification later. +type Beacon struct { + URL string `json:"url"` + ChainHash string `json:"chain_hash"` + Round uint64 `json:"round"` + Signature string `json:"signature"` + Randomness string `json:"randomness"` + FetchedAt time.Time `json:"fetched_at"` +} + +// beaconGet reads one reply, bounded at maxBeaconBytes: the seam a test +// serves rounds through. The shipping one goes through urlguard's pinned +// download, to the beacon's hosts alone, with no proxy and the address policy +// on every dial. +var beaconGet = func(ctx context.Context, rawURL string) ([]byte, error) { + dl := urlguard.NewDownload(urlguard.BlockedIP, false, BeaconTimeout, urlguard.OverrideFreeRoots(), beaconHosts...) + u, err := url.Parse(rawURL) + if err != nil { + return nil, err + } + if err := dl.Admit(u); err != nil { + return nil, err + } + req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil) + if err != nil { + return nil, err + } + req.Header.Set("User-Agent", "abcd-spotcheck") + resp, err := dl.Client.Do(req) + if err != nil { + return nil, err + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return nil, fmt.Errorf("answered %s", resp.Status) + } + b, err := io.ReadAll(io.LimitReader(resp.Body, maxBeaconBytes+1)) + if err != nil { + return nil, err + } + return b, nil +} + +// errUnreachable marks a host the beacon's fetch could not read a reply from, +// the one failure on which the next host is asked. +var errUnreachable = errors.New("unreachable") + +// fetchBeacon is the chain's latest round, asked of each host in turn until +// one answers, within BeaconTimeout, and verified under the pinned key. A +// reply that is read and refused (over its bound, malformed, of another +// chain, a signature that does not verify) refuses the fetch: no other host +// is asked, since a host that answers wrongly is no reason to trust the next. +// Every refusal names the beacon, and the round where one was read. +func fetchBeacon(parent context.Context, now time.Time) (Beacon, error) { + ctx, cancel := context.WithTimeout(parent, BeaconTimeout) + defer cancel() + var last error + for _, host := range beaconHosts { + u := "https://" + host + "/" + ChainHash + "/public/latest" + body, err := beaconGet(ctx, u) + if err != nil { + last = fmt.Errorf("%s: %w (%s)", host, errUnreachable, redact(err)) + if ctx.Err() != nil { + break + } + continue + } + b, err := readBeacon(body) + if err != nil { + return Beacon{}, fmt.Errorf("the beacon at %s: %w", host, err) + } + b.URL, b.FetchedAt = u, now.UTC().Truncate(time.Second) + return b, nil + } + return Beacon{}, fmt.Errorf("the beacon could not be reached: %w", last) +} + +// beaconReplyFields are the fields of a reply the fetch reads; any other +// field is ignored, since the reply is the beacon's to extend. +type beaconReplyFields struct { + Round json.RawMessage `json:"round"` + Signature *string `json:"signature"` + Randomness *string `json:"randomness"` + ChainHash *string `json:"chain_hash"` +} + +// readBeacon is one reply read and verified: within maxBeaconBytes, one JSON +// object with a positive whole round and a 96-hex signature, of the pinned +// chain where it names one, whose randomness, where it carries one, is the +// hash of its signature, and whose signature verifies for its round. +func readBeacon(body []byte) (Beacon, error) { + if len(body) > maxBeaconBytes { + return Beacon{}, fmt.Errorf("the reply is over the %d bytes a beacon reply may hold", maxBeaconBytes) + } + if err := jsonstrict.NoDuplicateKeys(body); err != nil { + return Beacon{}, fmt.Errorf("the reply does not read as a beacon round: %s", redact(err)) + } + dec := json.NewDecoder(bytes.NewReader(body)) + var f beaconReplyFields + if err := dec.Decode(&f); err != nil { + return Beacon{}, fmt.Errorf("the reply does not read as a beacon round: %s", redact(err)) + } + if _, err := dec.Token(); err != io.EOF { + return Beacon{}, errors.New("the reply holds more than one beacon round") + } + if f.Round == nil || f.Signature == nil { + return Beacon{}, errors.New("the reply names no round and signature") + } + round, err := parseRound(string(f.Round)) + if err != nil { + return Beacon{}, err + } + if f.ChainHash != nil && *f.ChainHash != ChainHash { + return Beacon{}, fmt.Errorf("round %d is of another chain than the pinned one", round) + } + sig, err := sigBytes(*f.Signature) + if err != nil { + return Beacon{}, fmt.Errorf("round %d: %w", round, err) + } + r, err := verifyRound(round, sig) + if err != nil { + return Beacon{}, fmt.Errorf("round %d: %w", round, err) + } + randomness := hex.EncodeToString(r[:]) + if f.Randomness != nil && *f.Randomness != randomness { + return Beacon{}, fmt.Errorf("round %d carries a randomness that is not the hash of its signature", round) + } + return Beacon{ChainHash: ChainHash, Round: round, Signature: hex.EncodeToString(sig), Randomness: randomness}, nil +} + +// parseRound is a reply's round: a positive whole number, written as a JSON +// number of digits alone (no sign, fraction, exponent or quotes). +func parseRound(s string) (uint64, error) { + var n uint64 + if s == "" || len(s) > 20 { + return 0, errors.New("the reply's round is not a positive whole number") + } + for i := 0; i < len(s); i++ { + c := s[i] + if c < '0' || c > '9' || n > (1<<64-1-uint64(c-'0'))/10 { + return 0, errors.New("the reply's round is not a positive whole number") + } + n = n*10 + uint64(c-'0') + } + if n == 0 { + return 0, errors.New("the reply's round is not a positive whole number") + } + return n, nil +} + +// sigBytes is a signature given as 96 lower- or upper-case hex digits. +func sigBytes(s string) ([]byte, error) { + if len(s) != sigHexLen { + return nil, fmt.Errorf("the signature is not %d hex digits", sigHexLen) + } + b, err := hex.DecodeString(s) + if err != nil { + return nil, fmt.Errorf("the signature is not %d hex digits", sigHexLen) + } + return b, nil +} + +// verifyRound checks sig as the chain's signature of round under the pinned +// key, and answers the round's randomness, the SHA-256 of the signature. The +// message signed is the SHA-256 of the round as a big-endian uint64; circl's +// G1 domain separation tag is the one the chain's scheme signs under. +func verifyRound(round uint64, sig []byte) ([32]byte, error) { + key, err := hex.DecodeString(chainKey) + if err != nil { + return [32]byte{}, err + } + var pk bls.PublicKey[bls.KeyG2SigG1] + if err := pk.UnmarshalBinary(key); err != nil { + return [32]byte{}, fmt.Errorf("the pinned beacon key does not read: %w", err) + } + var be [8]byte + binary.BigEndian.PutUint64(be[:], round) + msg := sha256.Sum256(be[:]) + if !bls.Verify(&pk, msg[:], sig) { + return [32]byte{}, errors.New("the beacon's signature does not verify under the chain's pinned key") + } + return sha256.Sum256(sig), nil +} diff --git a/internal/core/spotcheck/beacon_test.go b/internal/core/spotcheck/beacon_test.go new file mode 100644 index 0000000000..f9f9dc14e4 --- /dev/null +++ b/internal/core/spotcheck/beacon_test.go @@ -0,0 +1,173 @@ +package spotcheck + +import ( + "context" + "encoding/hex" + "errors" + "strings" + "testing" + "time" +) + +// The published vector of drand's quicknet chain for round 1000 +// (spc-2610301925429250 approach 4), read on 31 October 2026. +const ( + vectorRound = 1000 + vectorSignature = "b44679b9a59af2ec876b1a6b1ad52ea9b1615fc3982b19576350f93447cb1125e342b73a8dd2bacbe47e4b6b63ed5e39" + vectorRandomness = "fe290beca10872ef2fb164d2aa4442de4566183ec51c56ff3cd603d930e54fdd" +) + +// TestBeaconVerify: the round-1000 vector verifies under the pinned key and +// yields its published randomness; the same signature against round 1001 +// does not verify. +func TestBeaconVerify(t *testing.T) { + sig, err := hex.DecodeString(vectorSignature) + if err != nil { + t.Fatal(err) + } + r, err := verifyRound(vectorRound, sig) + if err != nil { + t.Fatalf("the published round-1000 vector does not verify under the pinned key: %v", err) + } + if got := hex.EncodeToString(r[:]); got != vectorRandomness { + t.Fatalf("round 1000 yields randomness %s; want the published %s", got, vectorRandomness) + } + if _, err := verifyRound(vectorRound+1, sig); err == nil { + t.Fatal("round 1000's signature verifies for round 1001") + } +} + +// beaconReply is a reply body as the chain's latest round is served. +func beaconReply(round, sig, randomness string) []byte { + b := `{"round":` + round + `,"signature":"` + sig + `"` + if randomness != "" { + b += `,"randomness":"` + randomness + `"` + } + return []byte(b + `}`) +} + +// serve sets the beacon seam for the test: each host's answer by host. +func serve(t *testing.T, answers map[string]func() ([]byte, error)) *[]string { + t.Helper() + var asked []string + old := beaconGet + beaconGet = func(ctx context.Context, url string) ([]byte, error) { + asked = append(asked, url) + for host, a := range answers { + if strings.HasPrefix(url, "https://"+host+"/") { + return a() + } + } + return nil, errors.New("unreachable") + } + t.Cleanup(func() { beaconGet = old }) + return &asked +} + +func TestBeaconFetchVerifiesTheRound(t *testing.T) { + serve(t, map[string]func() ([]byte, error){ + "api.drand.sh": func() ([]byte, error) { return beaconReply("1000", vectorSignature, vectorRandomness), nil }, + }) + now := time.Date(2026, 11, 25, 1, 2, 3, 0, time.UTC) + b, err := fetchBeacon(context.Background(), now) + if err != nil { + t.Fatal(err) + } + if b.Round != vectorRound || b.Signature != vectorSignature || b.Randomness != vectorRandomness || b.ChainHash != ChainHash || !b.FetchedAt.Equal(now) { + t.Fatalf("beacon = %+v", b) + } + if b.URL != "https://api.drand.sh/"+ChainHash+"/public/latest" { + t.Fatalf("the beacon names %s", b.URL) + } +} + +// TestBeaconReplyBounds: a reply over 4 KiB, a signature that is not 96 hex +// digits, a round that is not positive and a reply that is not JSON are each +// refused, and the draw is bounded by ten seconds in all. +func TestBeaconReplyBounds(t *testing.T) { + for name, body := range map[string][]byte{ + "over the bound": append(beaconReply("1000", vectorSignature, ""), []byte(strings.Repeat(" ", 4<<10))...), + "short signature": beaconReply("1000", vectorSignature[:94], ""), + "not hex": beaconReply("1000", strings.Repeat("z", 96), ""), + "round zero": beaconReply("0", vectorSignature, ""), + "negative round": beaconReply("-1", vectorSignature, ""), + "round as text": beaconReply(`"1000"`, vectorSignature, ""), + "not json": []byte("round 1000"), + "two values": append(beaconReply("1000", vectorSignature, ""), beaconReply("1000", vectorSignature, "")...), + "no signature": []byte(`{"round":1000}`), + "unverified round": beaconReply("1001", vectorSignature, ""), + } { + t.Run(name, func(t *testing.T) { + serve(t, map[string]func() ([]byte, error){"api.drand.sh": func() ([]byte, error) { return body, nil }}) + if b, err := fetchBeacon(context.Background(), time.Now()); err == nil { + t.Fatalf("the reply was taken: %+v", b) + } else if !strings.Contains(err.Error(), "beacon") { + t.Fatalf("the refusal does not name the beacon: %v", err) + } + }) + } + if BeaconTimeout != 10*time.Second || maxBeaconBytes != 4<<10 { + t.Fatalf("the beacon's bounds are %v and %d bytes; want ten seconds and 4 KiB", BeaconTimeout, maxBeaconBytes) + } +} + +// TestBeaconOtherChainRefused: a reply that names a chain hash other than the +// pinned one is refused, even with a signature that verifies. +func TestBeaconOtherChainRefused(t *testing.T) { + other := strings.Repeat("ab", 32) + serve(t, map[string]func() ([]byte, error){"api.drand.sh": func() ([]byte, error) { + return []byte(`{"round":1000,"signature":"` + vectorSignature + `","chain_hash":"` + other + `"}`), nil + }}) + if _, err := fetchBeacon(context.Background(), time.Now()); err == nil || !strings.Contains(err.Error(), "chain") { + t.Fatalf("a reply of another chain was taken (err %v)", err) + } +} + +// TestBeaconRandomnessMustMatch: a reply that carries a randomness field must +// carry the hash of its own signature. +func TestBeaconRandomnessMustMatch(t *testing.T) { + serve(t, map[string]func() ([]byte, error){"api.drand.sh": func() ([]byte, error) { + return beaconReply("1000", vectorSignature, strings.Repeat("0", 64)), nil + }}) + if _, err := fetchBeacon(context.Background(), time.Now()); err == nil || !strings.Contains(err.Error(), "randomness") { + t.Fatalf("a reply whose randomness is not its signature's hash was taken (err %v)", err) + } +} + +// TestBeaconHostFallbackOrder: an unreachable host is followed by the next, +// api.drand.sh, then api2, then api3; a reply that is read and refused is not +// asked of another host. +func TestBeaconHostFallbackOrder(t *testing.T) { + asked := serve(t, map[string]func() ([]byte, error){ + "api3.drand.sh": func() ([]byte, error) { return beaconReply("1000", vectorSignature, ""), nil }, + }) + b, err := fetchBeacon(context.Background(), time.Now()) + if err != nil { + t.Fatal(err) + } + want := []string{"api.drand.sh", "api2.drand.sh", "api3.drand.sh"} + if len(*asked) != 3 { + t.Fatalf("asked %q; want the three hosts in order", *asked) + } + for i, h := range want { + if !strings.HasPrefix((*asked)[i], "https://"+h+"/"+ChainHash+"/") { + t.Fatalf("asked %q; want %q in order", *asked, want) + } + } + if !strings.HasPrefix(b.URL, "https://api3.drand.sh/") { + t.Fatalf("the beacon names %s; want the host that answered", b.URL) + } + + asked = serve(t, map[string]func() ([]byte, error){ + "api.drand.sh": func() ([]byte, error) { return beaconReply("1001", vectorSignature, ""), nil }, + "api2.drand.sh": func() ([]byte, error) { return beaconReply("1000", vectorSignature, ""), nil }, + }) + if _, err := fetchBeacon(context.Background(), time.Now()); err == nil || len(*asked) != 1 { + t.Fatalf("a refused reply was followed by another host (asked %q, err %v)", *asked, err) + } + + asked = serve(t, nil) + if _, err := fetchBeacon(context.Background(), time.Now()); err == nil || len(*asked) != 3 || !strings.Contains(err.Error(), "unreachable") { + t.Fatalf("no host answering was not refused naming why (asked %q, err %v)", *asked, err) + } +} diff --git a/internal/core/spotcheck/config.go b/internal/core/spotcheck/config.go new file mode 100644 index 0000000000..bacb40b67b --- /dev/null +++ b/internal/core/spotcheck/config.go @@ -0,0 +1,73 @@ +package spotcheck + +// config.go is the spot-check's configuration (spc-2610301925429250 +// approach 3): the spotcheck block of .abcd/config.json, read through the +// layered resolver, the repository layer last and winning. + +import ( + "fmt" + + "github.com/intentdriven/abcd/internal/core/layered" +) + +// The configuration's keys, bundled defaults and bounds. +const ( + KeyWindowDays = "spotcheck.window_days" + KeyWindowChanges = "spotcheck.window_changes" + KeyPerGroup = "spotcheck.per_group" + DefaultWindowDays = 7 + DefaultPerGroup = 10 + maxWindowDays = 90 + minWindowChanges = 10 + maxWindowChanges = 100000 + maxPerGroup = 100 +) + +// Config is the spotcheck block as resolved. WindowChanges 0 is unset: only +// the days close the window. +type Config struct { + WindowDays int + WindowChanges int + PerGroup int +} + +// readConfig resolves the spotcheck block. A misspelt key, and a value out +// of its bounds or not a whole number, is refused naming its file and key, +// never replaced by the default. +func readConfig(r layered.Roots) (Config, error) { + s, err := layered.Load(layered.Config, r) + if err != nil { + return Config{}, err + } + if err := s.Claim("spotcheck", "window_days", "window_changes", "per_group"); err != nil { + return Config{}, err + } + days, err := layered.Get(s, KeyWindowDays, DefaultWindowDays, between(1, maxWindowDays, "days")) + if err != nil { + return Config{}, err + } + changes, err := layered.Get(s, KeyWindowChanges, 0, func(n int) error { + if n == 0 { + return nil + } + return between(minWindowChanges, maxWindowChanges, "changes")(n) + }) + if err != nil { + return Config{}, err + } + per, err := layered.Get(s, KeyPerGroup, DefaultPerGroup, between(1, maxPerGroup, "items")) + if err != nil { + return Config{}, err + } + return Config{WindowDays: days.V, WindowChanges: changes.V, PerGroup: per.V}, nil +} + +// between is a check that n is a whole number of what from lo to hi. +func between(lo, hi int, what string) func(int) error { + return func(n int) error { + if n < lo || n > hi { + return fmt.Errorf("want a whole number of %s from %d to %d", what, lo, hi) + } + return nil + } +} diff --git a/internal/core/spotcheck/config_test.go b/internal/core/spotcheck/config_test.go new file mode 100644 index 0000000000..6a2286c862 --- /dev/null +++ b/internal/core/spotcheck/config_test.go @@ -0,0 +1,59 @@ +package spotcheck + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "github.com/intentdriven/abcd/internal/core/layered" +) + +// configRoots is a repository whose .abcd/config.json holds body ("" for no +// file) and an empty home. +func configRoots(t *testing.T, body string) layered.Roots { + t.Helper() + repo := t.TempDir() + if body != "" { + if err := os.MkdirAll(filepath.Join(repo, ".abcd"), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(repo, ".abcd", "config.json"), []byte(body), 0o644); err != nil { + t.Fatal(err) + } + } + return layered.Roots{Repo: repo, Home: t.TempDir()} +} + +func TestConfigDefaults(t *testing.T) { + c, err := readConfig(configRoots(t, "")) + if err != nil { + t.Fatal(err) + } + if c != (Config{WindowDays: 7, WindowChanges: 0, PerGroup: 10}) { + t.Fatalf("the bundled configuration is %+v", c) + } + c, err = readConfig(configRoots(t, `{"spotcheck":{"window_days":3,"window_changes":50,"per_group":4}}`)) + if err != nil || c != (Config{WindowDays: 3, WindowChanges: 50, PerGroup: 4}) { + t.Fatalf("readConfig = %+v, %v", c, err) + } +} + +// TestPerGroupBounds: per_group 0, 101 and a string are refused naming the +// key, as are a window out of its bounds and a misspelt key. +func TestPerGroupBounds(t *testing.T) { + for body, key := range map[string]string{ + `{"spotcheck":{"per_group":0}}`: "per_group", + `{"spotcheck":{"per_group":101}}`: "per_group", + `{"spotcheck":{"per_group":"ten"}}`: "per_group", + `{"spotcheck":{"window_days":0}}`: "window_days", + `{"spotcheck":{"window_days":91}}`: "window_days", + `{"spotcheck":{"window_changes":9}}`: "window_changes", + `{"spotcheck":{"window_changes":100001}}`: "window_changes", + `{"spotcheck":{"per_groups":5}}`: "per_groups", + } { + if _, err := readConfig(configRoots(t, body)); err == nil || !strings.Contains(err.Error(), key) { + t.Errorf("%s: err %v; want a refusal naming %s", body, err, key) + } + } +} diff --git a/internal/core/spotcheck/cycle.go b/internal/core/spotcheck/cycle.go new file mode 100644 index 0000000000..988fc3afda --- /dev/null +++ b/internal/core/spotcheck/cycle.go @@ -0,0 +1,313 @@ +package spotcheck + +// cycle.go is what the draw writes beside the records (spc-2610301925429250 +// approach 1): window-open.json, written once by the first check, a cycle +// record per draw under cycles/, and an item file per drawn item under +// items//. They are written straight over origin's copy as last +// fetched and pushed at once, never onto the local copy, and hold typed +// fields only: object names, times, record ids, words from fixed sets and the +// beacon's values. No free text a model or a person wrote is among them. + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "regexp" + "slices" + "strings" + "time" + + "github.com/intentdriven/abcd/internal/core/jsonstrict" + "github.com/intentdriven/abcd/internal/gitutil" +) + +// The draw's folders and files. +const ( + CyclesDir = "cycles" + ItemsDir = "items" + JudgementsDir = "judgements" + WindowOpenFile = "window-open.json" +) + +// The words a cycle's window closes by. +const ( + ClosedByDays = "days" + ClosedByChanges = "changes" +) + +// SiteDrain is the third observing site, a drain move, beside SiteLand and +// SiteLane. +const SiteDrain = "drain" + +// The sizes a sample takes. +const ( + SizeFull = "full" + SizeHalved = "halved" +) + +// DrawRule says how a cycle's draw is recomputed from its record, so anyone +// can repeat it. +const DrawRule = "each key of a group, sorted, is given HMAC-SHA256 keyed by the beacon's randomness over cycle-id NUL group NUL key; the size smallest are drawn" + +// maxListedKeys is the most keys a population lists whole: above it, the +// cycle keeps the first and last key and the SHA-256 of the sorted keys, one +// per line. +const maxListedKeys = 5000 + +// WindowOpen is window-open.json: where and when the first window opened. +type WindowOpen struct { + SchemaVersion int `json:"schema_version"` + Commit string `json:"commit"` + At time.Time `json:"at"` + Holder string `json:"holder,omitempty"` +} + +// Cycle is one draw, cycles/.json. +type Cycle struct { + SchemaVersion int `json:"schema_version"` + ID string `json:"id"` + FromCommit string `json:"from_commit"` + ToCommit string `json:"to_commit"` + FromTime time.Time `json:"from_time"` + ToTime time.Time `json:"to_time"` + ClosedBy string `json:"closed_by"` + Site string `json:"site"` + Beacon Beacon `json:"beacon"` + Draw string `json:"draw"` + Sample Sample `json:"sample"` + Groups []GroupDraw `json:"groups"` + Holder string `json:"holder,omitempty"` +} + +// Sample is the size a cycle drew at and why. +type Sample struct { + PerGroup int `json:"per_group"` + Size int `json:"size"` + Why string `json:"why"` + // Counted are the closed cycles the size was decided over, newest first. + Counted []string `json:"counted"` +} + +// GroupDraw is one group of a cycle: its population and the keys drawn. +type GroupDraw struct { + Group string `json:"group"` + Population Population `json:"population"` + Drawn []string `json:"drawn"` +} + +// Population is a group's keys, whole up to maxListedKeys and otherwise by +// their range and hash. +type Population struct { + Count int `json:"count"` + Keys []string `json:"keys,omitempty"` + First string `json:"first,omitempty"` + Last string `json:"last,omitempty"` + SHA256 string `json:"sha256,omitempty"` +} + +// Item is one drawn item, items//--.json: the +// state it had at the draw, copied in, so what a person later sees as then +// never rests on a later read. +type Item struct { + SchemaVersion int `json:"schema_version"` + Cycle string `json:"cycle"` + Number int `json:"number"` + Group string `json:"group"` + Key string `json:"key"` + Roles []string `json:"roles"` + Landing *LandingRow `json:"landing,omitempty"` + HandBack *HandBack `json:"hand_back,omitempty"` + Decision *Decision `json:"decision,omitempty"` +} + +var ( + cycleIDRe = regexp.MustCompile(`^[0-9]{8}T[0-9]{6}Z-[0-9a-f]{12}$`) + cycleNameRe = regexp.MustCompile(`^` + CyclesDir + `/([0-9]{8}T[0-9]{6}Z-[0-9a-f]{12})\.json$`) +) + +// cycleID is the id of a cycle closed at to over commit: its time first, so +// ids sort in window order. +func cycleID(to time.Time, commit string) string { + return to.UTC().Format(stamp) + "-" + commit[:12] +} + +// itemStem is an item's file name without .json, which its judgements are +// named after. +func itemStem(number int, group, key string) string { + return fmt.Sprintf("%03d-%s-%s", number, group, key) +} + +// windowState is the store's window as origin's copy holds it. +type windowState struct { + // tracking is origin's copy as last fetched, "" when this checkout holds + // none. + tracking string + files map[string]entry + // open says window-open.json or a cycle is there; from and fromTime are + // where the window now open began: the last cycle's end, else the + // window's opening. + open bool + from string + fromTime time.Time + // cycles are the ids of every cycle, in window order. + cycles []string +} + +// readWindow is the window as origin's copy, last fetched, holds it: a +// listing and at most one file read, all local. A copy that holds files the +// store does not write under the draw's names, or a cycle or opening that +// does not read, is an error: a window is never guessed. +func readWindow(ctx context.Context, root string) (windowState, error) { + tracking, err := storeRef(ctx, root, TrackingRef) + if err != nil || tracking == "" { + return windowState{}, err + } + files, err := listFiles(ctx, root, tracking) + if err != nil { + return windowState{}, err + } + st := windowState{tracking: tracking, files: files} + for p := range files { + if m := cycleNameRe.FindStringSubmatch(p); m != nil { + st.cycles = append(st.cycles, m[1]) + } + } + slices.Sort(st.cycles) + if n := len(st.cycles); n > 0 { + var c Cycle + if err := readJSON(ctx, root, files, CyclesDir+"/"+st.cycles[n-1]+".json", &c); err != nil { + return windowState{}, err + } + if c.ID != st.cycles[n-1] || !gitutil.IsFullSHA(c.ToCommit) || c.ToTime.IsZero() { + return windowState{}, fmt.Errorf("the spot-check's cycle %s does not read as one this package writes", st.cycles[n-1]) + } + st.open, st.from, st.fromTime = true, c.ToCommit, c.ToTime + return st, nil + } + if _, ok := files[WindowOpenFile]; ok { + var w WindowOpen + if err := readJSON(ctx, root, files, WindowOpenFile, &w); err != nil { + return windowState{}, err + } + if !gitutil.IsFullSHA(w.Commit) || w.At.IsZero() { + return windowState{}, errors.New("the spot-check's window-open.json does not read as one this package writes") + } + st.open, st.from, st.fromTime = true, w.Commit, w.At + } + return st, nil +} + +// readJSON decodes the store's file at p, strictly and within +// maxRecordBytes, into v; a file of another schema version is refused. +func readJSON(ctx context.Context, root string, files map[string]entry, p string, v any) error { + e, ok := files[p] + if !ok || e.typ != "blob" || e.mode != "100644" || e.size > maxRecordBytes { + return fmt.Errorf("the spot-check's %s cannot be read", p) + } + blobs, err := readBlobs(ctx, root, []entry{e}) + if err != nil { + return err + } + if err := jsonstrict.Decode(blobs[0], v); err != nil { + return fmt.Errorf("the spot-check's %s does not read: %s", p, redact(err)) + } + var head struct { + SchemaVersion int `json:"schema_version"` + } + if err := json.Unmarshal(blobs[0], &head); err != nil || head.SchemaVersion != SchemaVersion { + return fmt.Errorf("the spot-check's %s is of another schema version", p) + } + return nil +} + +// cycleTally is one cycle as the sample size reads it. +type cycleTally struct { + id string + closed bool + findings int +} + +// maxTallied bounds the cycles the size reads back, newest first, looking +// for the three closed ones it decides on. +const maxTallied = 24 + +// tallyCycles reads the newest cycles of st, newest first, until three closed +// ones are found or maxTallied are read: a cycle is closed when every role of +// every item it drew has a judgement file, and its findings are the +// judgements whose verdict is wrong. A cycle that drew nothing is closed and +// clean. +func tallyCycles(ctx context.Context, root string, st windowState) ([]cycleTally, error) { + var out []cycleTally + closed := 0 + for i := len(st.cycles) - 1; i >= 0 && closed < 3 && len(out) < maxTallied; i-- { + id := st.cycles[i] + t := cycleTally{id: id, closed: true} + var items []string + judged := map[string]string{} + for p := range st.files { + if rest, ok := strings.CutPrefix(p, ItemsDir+"/"+id+"/"); ok && strings.HasSuffix(rest, ".json") { + items = append(items, p) + } + if rest, ok := strings.CutPrefix(p, JudgementsDir+"/"+id+"/"); ok && strings.HasSuffix(rest, ".json") { + judged[strings.TrimSuffix(rest, ".json")] = p + } + } + slices.Sort(items) + for _, p := range items { + var it Item + if err := readJSON(ctx, root, st.files, p, &it); err != nil { + return nil, err + } + stem := strings.TrimSuffix(p[len(ItemsDir+"/"+id+"/"):], ".json") + for _, role := range it.Roles { + jp, ok := judged[stem+"."+role] + if !ok { + t.closed = false + continue + } + wrong, err := judgedWrong(ctx, root, st.files, jp) + if err != nil { + return nil, err + } + if wrong { + t.findings++ + } + } + } + if t.closed { + closed++ + } + out = append(out, t) + } + return out, nil +} + +// judgedWrong reads a judgement's verdict: true when it is wrong. Only the +// verdict is read, so a judgement's other fields are the review lane's. +func judgedWrong(ctx context.Context, root string, files map[string]entry, p string) (bool, error) { + e := files[p] + if e.typ != "blob" || e.size > maxRecordBytes { + return false, fmt.Errorf("the spot-check's %s cannot be read", p) + } + blobs, err := readBlobs(ctx, root, []entry{e}) + if err != nil { + return false, err + } + var j struct { + Verdict string `json:"verdict"` + } + if err := json.Unmarshal(blobs[0], &j); err != nil { + return false, fmt.Errorf("the spot-check's %s does not read", p) + } + return j.Verdict == "wrong", nil +} + +// encodeFile is v as the store's file at folder/name. +func encodeFile(folder, name string, v any) (file, error) { + data, err := encode(v) + if err != nil { + return file{}, err + } + return file{folder: folder, name: name, data: data}, nil +} diff --git a/internal/core/spotcheck/draw.go b/internal/core/spotcheck/draw.go new file mode 100644 index 0000000000..75b2b47538 --- /dev/null +++ b/internal/core/spotcheck/draw.go @@ -0,0 +1,65 @@ +package spotcheck + +// draw.go is the draw itself (spc-2610301925429250 approach 4): within each +// group, every key is given a keyed hash of the beacon's randomness, and the +// smallest are drawn. The same randomness and population give the same list, +// every key has a chance, and none can be steered, since the randomness does +// not exist until the window has closed. + +import ( + "crypto/hmac" + "crypto/sha256" + "encoding/hex" + "slices" + "strings" +) + +// drawKeys is the size keys of a group drawn by randomness for cycle id: +// each key, sorted and once, is given HMAC-SHA256(randomness, id NUL group +// NUL key), and the keys of the size smallest values are answered in that +// order (DrawRule). +func drawKeys(randomness []byte, id, group string, keys []string, size int) []string { + sorted := slices.Clone(keys) + slices.Sort(sorted) + sorted = slices.Compact(sorted) + type scored struct { + mac []byte + key string + } + all := make([]scored, 0, len(sorted)) + for _, k := range sorted { + m := hmac.New(sha256.New, randomness) + m.Write([]byte(id + "\x00" + group + "\x00" + k)) + all = append(all, scored{mac: m.Sum(nil), key: k}) + } + slices.SortFunc(all, func(a, b scored) int { + if c := strings.Compare(string(a.mac), string(b.mac)); c != 0 { + return c + } + return strings.Compare(a.key, b.key) + }) + out := make([]string, 0, min(size, len(all))) + for i := 0; i < len(all) && i < size; i++ { + out = append(out, all[i].key) + } + return out +} + +// population is a group's keys as a cycle keeps them: whole up to +// maxListedKeys, and above it by the first and last key and the SHA-256 of +// the sorted keys, one per line. +func population(keys []string) Population { + sorted := slices.Clone(keys) + slices.Sort(sorted) + p := Population{Count: len(sorted)} + if len(sorted) <= maxListedKeys { + p.Keys = sorted + if p.Keys == nil { + p.Keys = []string{} + } + return p + } + sum := sha256.Sum256([]byte(strings.Join(sorted, "\n") + "\n")) + p.First, p.Last, p.SHA256 = sorted[0], sorted[len(sorted)-1], hex.EncodeToString(sum[:]) + return p +} diff --git a/internal/core/spotcheck/draw_test.go b/internal/core/spotcheck/draw_test.go new file mode 100644 index 0000000000..61bba474f9 --- /dev/null +++ b/internal/core/spotcheck/draw_test.go @@ -0,0 +1,80 @@ +package spotcheck + +import ( + "crypto/sha256" + "encoding/hex" + "fmt" + "math/rand/v2" + "slices" + "strings" + "testing" +) + +func keysN(n int) []string { + ks := make([]string, n) + for i := range ks { + ks[i] = fmt.Sprintf("%040x", i+1) + } + return ks +} + +// TestDrawIsDeterministic: the same randomness and population give the same +// list, across two runs and a shuffled population; another randomness or +// another cycle gives another. +func TestDrawIsDeterministic(t *testing.T) { + r, _ := hex.DecodeString(vectorRandomness) + keys := keysN(50) + a := drawKeys(r, "20261125T010203Z-0123456789ab", GroupDrainLanded, keys, 10) + shuffled := slices.Clone(keys) + rand.Shuffle(len(shuffled), func(i, j int) { shuffled[i], shuffled[j] = shuffled[j], shuffled[i] }) + b := drawKeys(r, "20261125T010203Z-0123456789ab", GroupDrainLanded, append(shuffled, keys[3]), 10) + if len(a) != 10 || !slices.Equal(a, b) { + t.Fatalf("two draws over one population differ:\n%v\n%v", a, b) + } + if slices.Equal(a, drawKeys(r, "20261125T010203Z-0123456789ac", GroupDrainLanded, keys, 10)) { + t.Fatal("another cycle drew the same list") + } + if slices.Equal(a, drawKeys(r, "20261125T010203Z-0123456789ab", GroupAutomaticMerges, keys, 10)) { + t.Fatal("another group drew the same list") + } + if got := drawKeys(r, "c", GroupDrainLanded, keys[:3], 10); len(got) != 3 { + t.Fatalf("a group smaller than the size drew %d; want all 3", len(got)) + } +} + +// TestEveryItemCanBeDrawn: over many randomness values, every key of a +// 50-item group is drawn at least once. +func TestEveryItemCanBeDrawn(t *testing.T) { + keys := keysN(50) + seen := map[string]bool{} + for i := range 400 { + sum := sha256.Sum256([]byte(fmt.Sprint(i))) + for _, k := range drawKeys(sum[:], "c", GroupDrainLanded, keys, 10) { + seen[k] = true + } + } + for _, k := range keys { + if !seen[k] { + t.Fatalf("key %s was never drawn in 400 draws", k) + } + } +} + +// TestLargePopulationStoresRangeAndHash: a population of up to 5,000 keys is +// kept whole and sorted; above it, by its first and last key and the hash of +// the sorted keys. +func TestLargePopulationStoresRangeAndHash(t *testing.T) { + small := population([]string{"b", "a"}) + if small.Count != 2 || !slices.Equal(small.Keys, []string{"a", "b"}) || small.SHA256 != "" { + t.Fatalf("population = %+v", small) + } + keys := keysN(5001) + big := population(keys) + sum := sha256.Sum256([]byte(strings.Join(keys, "\n") + "\n")) + if big.Count != 5001 || big.Keys != nil || big.First != keys[0] || big.Last != keys[5000] || big.SHA256 != hex.EncodeToString(sum[:]) { + t.Fatalf("population of 5,001 = count %d, %d keys, %s..%s, %s", big.Count, len(big.Keys), big.First, big.Last, big.SHA256) + } + if whole := population(keys[:5000]); len(whole.Keys) != 5000 { + t.Fatalf("a population of 5,000 kept %d keys whole", len(whole.Keys)) + } +} diff --git a/internal/core/spotcheck/groups.go b/internal/core/spotcheck/groups.go new file mode 100644 index 0000000000..966ca55eca --- /dev/null +++ b/internal/core/spotcheck/groups.go @@ -0,0 +1,233 @@ +package spotcheck + +// groups.go is what a window's populations are drawn from +// (spc-2610301925429250 approach 4): the landings the reader classes drain +// and automatic, and the hand-backs and decisions origin's copy holds, each +// a group of its own. +// +// The landings reader lives in internal/core/landings, which imports +// internal/core/landing, which imports this package, so this package cannot +// call it: the reader registers itself here (RegisterLandingsReader) when its +// package is linked, and a draw with no reader registered is refused, as one +// whose forge answer was not read is. + +import ( + "context" + "errors" + "fmt" + "regexp" + "slices" + "strings" + "sync" + "time" +) + +// The four groups, in the order a cycle holds them. +const ( + GroupDrainLanded = "drain-landed" + GroupAutomaticMerges = "automatic-merges" + GroupDrainHandBacks = "drain-hand-backs" + GroupFacilitatorDecisions = "facilitator-decisions" +) + +// groupOrder is the order of the groups in a cycle. +var groupOrder = []string{GroupDrainLanded, GroupAutomaticMerges, GroupDrainHandBacks, GroupFacilitatorDecisions} + +// The roles an item is for. +const ( + RoleFacilitator = "facilitator" + RoleHumanFacilitator = "human-facilitator" + RoleProductThinker = "product-thinker" +) + +// The landings classes the draw reads, as the reader names them. +const ( + ClassDrain = "drain" + ClassAutomatic = "automatic" +) + +// LandingRow is one landing as the draw copies it into an item: the reader's +// row in typed fields alone. The reader's own words for why it classed a row +// as it did stay with the reader. +type LandingRow struct { + Commit string `json:"commit"` + When time.Time `json:"when"` + PR int `json:"pr,omitempty"` + MergedHead string `json:"merged_head,omitempty"` + Class string `json:"class"` + RuleKind string `json:"rule_kind,omitempty"` + RuleID string `json:"rule_id,omitempty"` + RulePath string `json:"rule_path,omitempty"` + Lane string `json:"lane,omitempty"` + Mode string `json:"mode,omitempty"` + Resolves []string `json:"resolves,omitempty"` + Delivers []string `json:"delivers,omitempty"` + Unattended bool `json:"unattended"` + // ForgeUnread says the reader could not settle the row's approval from + // history and could not read the forge's answer: such a row refuses the + // draw, so a person's approval is never drawn as unattended on a guess. + ForgeUnread bool `json:"-"` +} + +// LandingsReader reads the landings of the default branch from (exclusive) +// to (inclusive), both full object names, under ctx. +type LandingsReader func(ctx context.Context, root, from, to string) ([]LandingRow, error) + +var ( + readerMu sync.Mutex + landingsReader LandingsReader +) + +// RegisterLandingsReader is how the landings reader makes itself known to the +// draw, once, as its package is linked. +func RegisterLandingsReader(r LandingsReader) { + readerMu.Lock() + defer readerMu.Unlock() + landingsReader = r +} + +// registeredReader is the reader the draw reads landings through, nil when +// none is linked. +func registeredReader() LandingsReader { + readerMu.Lock() + defer readerMu.Unlock() + return landingsReader +} + +// errNoReader is a draw with no landings reader linked into the binary. +var errNoReader = errors.New("no landings reader is linked into this binary, so the window's landings cannot be read") + +var ( + ruleWordRe = regexp.MustCompile(`^[a-z][a-z0-9._-]{0,63}$`) + repoPathRe = regexp.MustCompile(`^[A-Za-z0-9._-]+(/[A-Za-z0-9._-]+)*$`) + idListRe = regexp.MustCompile(`^(iss|itd|spc)-[0-9]{1,20}$`) +) + +// typedRow is r as an item keeps it: every field held to its shape, and a +// field that does not keep to it dropped. ok is false for a row that names no +// commit or no class the draw reads. +func typedRow(r LandingRow) (LandingRow, bool) { + if !shaRe.MatchString(r.Commit) || (r.Class != ClassDrain && r.Class != ClassAutomatic) { + return LandingRow{}, false + } + t := LandingRow{Commit: r.Commit, When: r.When.UTC().Truncate(time.Second), Class: r.Class, Unattended: r.Unattended, ForgeUnread: r.ForgeUnread} + if r.PR > 0 { + t.PR = r.PR + } + if shaRe.MatchString(r.MergedHead) { + t.MergedHead = r.MergedHead + } + for _, f := range []struct { + in string + out *string + re *regexp.Regexp + }{{r.RuleKind, &t.RuleKind, ruleWordRe}, {r.RuleID, &t.RuleID, ruleWordRe}, {r.Lane, &t.Lane, ruleWordRe}, {r.Mode, &t.Mode, ruleWordRe}, {r.RulePath, &t.RulePath, repoPathRe}} { + if f.re.MatchString(f.in) && !strings.Contains(f.in, "..") { + *f.out = f.in + } + } + for _, id := range r.Resolves { + if idListRe.MatchString(id) { + t.Resolves = append(t.Resolves, id) + } + } + for _, id := range r.Delivers { + if idListRe.MatchString(id) { + t.Delivers = append(t.Delivers, id) + } + } + return t, true +} + +// candidate is one item a group may draw: its key and the state an item +// copies. +type candidate struct { + key string + roles []string + landing *LandingRow + handBack *HandBack + decision *Decision +} + +// namedHandBack and namedDecision are records with the file name origin's +// copy keeps them under. +type namedHandBack struct { + name string + h HandBack +} + +type namedDecision struct { + name string + d Decision +} + +// recordKey is a record's population key: its file name less the hash of its +// content and .json, so records of one issue and one time are one item even +// when their content drifted. +func recordKey(name string) string { + stem := strings.TrimSuffix(name, ".json") + if len(stem) > hashLen+1 && stem[len(stem)-hashLen-1] == '-' { + return stem[:len(stem)-hashLen-1] + } + return stem +} + +// populations are the window's four groups: the reader's rows classed drain +// and automatic, and the hand-backs and decisions whose time falls in +// (from, to]. A row whose approval was not read from the forge refuses them +// all. Within a group, records of one key are one candidate, the record of +// the greatest file name copied. +func populations(rows []LandingRow, hbs []namedHandBack, ds []namedDecision, from, to time.Time) (map[string][]candidate, error) { + groups := map[string][]candidate{} + for _, r := range rows { + if r.ForgeUnread { + return nil, fmt.Errorf("the forge's answer for the landing %s was not read, so a person's approval of it cannot be ruled out", r.Commit[:12]) + } + t, ok := typedRow(r) + if !ok { + continue + } + g, roles := GroupDrainLanded, []string{RoleFacilitator} + if t.Class == ClassAutomatic { + g = GroupAutomaticMerges + if len(t.Delivers) > 0 { + roles = []string{RoleFacilitator, RoleProductThinker} + } + } + groups[g] = append(groups[g], candidate{key: t.Commit, roles: roles, landing: &t}) + } + in := func(at time.Time) bool { return at.After(from) && !at.After(to) } + pickH := map[string]namedHandBack{} + for _, h := range hbs { + if !in(h.h.At) { + continue + } + k := recordKey(h.name) + if old, ok := pickH[k]; !ok || h.name > old.name { + pickH[k] = h + } + } + for k, h := range pickH { + t := h.h.typed() + groups[GroupDrainHandBacks] = append(groups[GroupDrainHandBacks], candidate{key: k, roles: []string{RoleFacilitator}, handBack: &t}) + } + pickD := map[string]namedDecision{} + for _, d := range ds { + if !in(d.d.At) { + continue + } + k := recordKey(d.name) + if old, ok := pickD[k]; !ok || d.name > old.name { + pickD[k] = d + } + } + for k, d := range pickD { + t := d.d.typed() + groups[GroupFacilitatorDecisions] = append(groups[GroupFacilitatorDecisions], candidate{key: k, roles: []string{RoleHumanFacilitator}, decision: &t}) + } + for g := range groups { + slices.SortFunc(groups[g], func(a, b candidate) int { return strings.Compare(a.key, b.key) }) + groups[g] = slices.CompactFunc(groups[g], func(a, b candidate) bool { return a.key == b.key }) + } + return groups, nil +} diff --git a/internal/core/spotcheck/groups_test.go b/internal/core/spotcheck/groups_test.go new file mode 100644 index 0000000000..0b163e017d --- /dev/null +++ b/internal/core/spotcheck/groups_test.go @@ -0,0 +1,122 @@ +package spotcheck + +import ( + "slices" + "strings" + "testing" + "time" +) + +func row(commit, class string, delivers ...string) LandingRow { + return LandingRow{Commit: commit, When: at0, PR: 7, Class: class, RuleKind: "drain", RuleID: "adr-2609291342092738", + RulePath: ".abcd/development/decisions/adrs/2609291342092738-x.md", Mode: "auto", Delivers: delivers, Unattended: true} +} + +func sha(c byte) string { return strings.Repeat(string(c), 40) } + +func keysOf(cs []candidate) []string { + var ks []string + for _, c := range cs { + ks = append(ks, c.key) + } + return ks +} + +// TestFourGroupsFromTheirSources: rows classed drain and automatic and the +// hand-backs and decisions in the window make the four groups; a row of any +// other class, person-approved among them, and a record outside the window, +// are never drawn. +func TestFourGroupsFromTheirSources(t *testing.T) { + from, to := at0.Add(-time.Hour), at0.Add(time.Hour) + rows := []LandingRow{row(sha('a'), ClassDrain), row(sha('b'), ClassAutomatic, "itd-2610301750162657"), row(sha('c'), ClassAutomatic), + row(sha('d'), "person-approved"), row(sha('e'), "person-push")} + hIn, hOut := handBack("iss-1", at0), handBack("iss-2", to.Add(time.Second)) + dIn := gateDecision(9, sha('f'), true, at0) + groups, err := populations(rows, + []namedHandBack{{name: fileOf(t, hIn).name, h: hIn}, {name: fileOf(t, hOut).name, h: hOut}}, + []namedDecision{{name: fileOf(t, dIn).name, d: dIn}}, from, to) + if err != nil { + t.Fatal(err) + } + if got := keysOf(groups[GroupDrainLanded]); !slices.Equal(got, []string{sha('a')}) { + t.Errorf("drain-landed = %v", got) + } + if got := keysOf(groups[GroupAutomaticMerges]); !slices.Equal(got, []string{sha('b'), sha('c')}) { + t.Errorf("automatic-merges = %v", got) + } + if got := keysOf(groups[GroupDrainHandBacks]); len(got) != 1 || !strings.HasSuffix(got[0], "-iss-1") { + t.Errorf("drain-hand-backs = %v", got) + } + if got := keysOf(groups[GroupFacilitatorDecisions]); len(got) != 1 || !strings.Contains(got[0], "-pr9-") { + t.Errorf("facilitator-decisions = %v", got) + } + // The roles: the product thinker too on an automatic merge that names an + // intent; the human facilitator alone on a decision. + am := groups[GroupAutomaticMerges] + if !slices.Equal(am[0].roles, []string{RoleFacilitator, RoleProductThinker}) || !slices.Equal(am[1].roles, []string{RoleFacilitator}) { + t.Errorf("automatic-merges roles = %v, %v", am[0].roles, am[1].roles) + } + if r := groups[GroupFacilitatorDecisions][0].roles; !slices.Equal(r, []string{RoleHumanFacilitator}) { + t.Errorf("facilitator-decisions roles = %v", r) + } +} + +// TestUnreadApprovalRefusesTheDraw: a row whose approval the reader could not +// settle and whose forge answer it could not read refuses the populations. +func TestUnreadApprovalRefusesTheDraw(t *testing.T) { + r := row(sha('a'), ClassAutomatic) + r.ForgeUnread = true + if _, err := populations([]LandingRow{row(sha('b'), ClassDrain), r}, nil, nil, at0, at0); err == nil || !strings.Contains(err.Error(), "forge") { + t.Fatalf("a row whose forge answer was not read was drawn from (err %v)", err) + } +} + +// TestDriftedRecordIsOneItem: two files of one issue and one time whose +// content drifted are one candidate, the greater name copied. +func TestDriftedRecordIsOneItem(t *testing.T) { + a, b := handBack("iss-3", at0), handBack("iss-3", at0) + b.Kind = "question" + fa, fb := fileOf(t, a), fileOf(t, b) + if fa.name == fb.name { + t.Fatal("the two records share a name") + } + groups, err := populations(nil, []namedHandBack{{name: fa.name, h: a}, {name: fb.name, h: b}}, nil, at0.Add(-time.Second), at0) + if err != nil { + t.Fatal(err) + } + hbs := groups[GroupDrainHandBacks] + if len(hbs) != 1 { + t.Fatalf("drifted records are %d candidates; want one", len(hbs)) + } + want := a.Kind + if fb.name > fa.name { + want = b.Kind + } + if hbs[0].handBack.Kind != want { + t.Fatalf("the candidate copies the record of kind %s; want the greater name's %s", hbs[0].handBack.Kind, want) + } +} + +// TestItemCopiesItsStateAtTheDraw: a candidate carries the row and the record +// in typed fields alone: no reason, no why, no question, and a field that +// does not keep to its shape dropped. +func TestItemCopiesItsStateAtTheDraw(t *testing.T) { + r := row(sha('a'), ClassDrain) + r.Lane, r.RulePath, r.Resolves = "Some Lane words", "/home/x/rule.md", []string{"iss-12", "not an id"} + h := handBack("iss-4", at0) + d := Decision{Kind: KindDrainJudgement, At: at0, Issue: "iss-5", Question: "may it?", Answer: "yes", Model: "claude-opus-4-8", Rule: "adr-2609291342092738", Reason: "because it said so"} + groups, err := populations([]LandingRow{r}, []namedHandBack{{name: fileOf(t, h).name, h: h}}, []namedDecision{{name: fileOf(t, d).name, d: d}}, at0.Add(-time.Second), at0) + if err != nil { + t.Fatal(err) + } + lr := groups[GroupDrainLanded][0].landing + if lr.Commit != sha('a') || lr.Lane != "" || lr.RulePath != "" || !slices.Equal(lr.Resolves, []string{"iss-12"}) || lr.RuleID != "adr-2609291342092738" { + t.Errorf("the landing row is copied as %+v", lr) + } + if hb := groups[GroupDrainHandBacks][0].handBack; hb.Reason != "" || hb.Rule != "" || hb.Kind != "stuck" || hb.DrainRule != "adr-2609291342092738" { + t.Errorf("the hand-back is copied as %+v", hb) + } + if dc := groups[GroupFacilitatorDecisions][0].decision; dc.Reason != "" || dc.Question != "" || dc.Answer != "yes" || dc.Model != "claude-opus-4-8" { + t.Errorf("the decision is copied as %+v", dc) + } +} diff --git a/internal/core/spotcheck/size.go b/internal/core/spotcheck/size.go new file mode 100644 index 0000000000..ca76b83358 --- /dev/null +++ b/internal/core/spotcheck/size.go @@ -0,0 +1,31 @@ +package spotcheck + +// size.go is the sample size (spc-2610301925429250 approach 5): it adapts +// over fully reviewed cycles only. + +// sampleSize is the size a new cycle draws per group, over the cycles before +// it newest first (tallyCycles): half of perGroup, rounded up and never below +// one, when the three most recent closed cycles each found nothing; perGroup +// otherwise, so a closed cycle with a finding makes the next size full. An +// open cycle is skipped, counting as neither clean nor a finding. counted +// names the closed cycles the size was decided over, newest first. +func sampleSize(perGroup int, newestFirst []cycleTally) (size int, why string, counted []string) { + counted = []string{} + clean := true + for _, c := range newestFirst { + if !c.closed { + continue + } + counted = append(counted, c.id) + if c.findings > 0 { + clean = false + } + if len(counted) == 3 { + break + } + } + if len(counted) == 3 && clean { + return max((perGroup+1)/2, 1), SizeHalved, counted + } + return perGroup, SizeFull, counted +} diff --git a/internal/core/spotcheck/size_test.go b/internal/core/spotcheck/size_test.go new file mode 100644 index 0000000000..3888b4bcae --- /dev/null +++ b/internal/core/spotcheck/size_test.go @@ -0,0 +1,84 @@ +package spotcheck + +import ( + "fmt" + "slices" + "testing" + "time" +) + +func closedClean(id string) cycleTally { return cycleTally{id: id, closed: true} } + +func TestSizeHalvesAfterThreeClosedCleanCycles(t *testing.T) { + size, why, counted := sampleSize(10, []cycleTally{closedClean("c3"), closedClean("c2"), closedClean("c1")}) + if size != 5 || why != SizeHalved || !slices.Equal(counted, []string{"c3", "c2", "c1"}) { + t.Fatalf("sampleSize = %d %s %v; want 5, halved, the three", size, why, counted) + } + if size, _, _ := sampleSize(5, []cycleTally{closedClean("c3"), closedClean("c2"), closedClean("c1")}); size != 3 { + t.Fatalf("half of five is %d; want it rounded up to 3", size) + } + if size, _, _ := sampleSize(1, []cycleTally{closedClean("c3"), closedClean("c2"), closedClean("c1")}); size != 1 { + t.Fatalf("half of one is %d; want never below 1", size) + } + if size, why, _ := sampleSize(10, []cycleTally{closedClean("c2"), closedClean("c1")}); size != 10 || why != SizeFull { + t.Fatalf("two clean cycles give %d %s; want full", size, why) + } +} + +func TestSizeFullAfterAFinding(t *testing.T) { + cs := []cycleTally{{id: "c4", closed: true, findings: 1}, closedClean("c3"), closedClean("c2"), closedClean("c1")} + if size, why, counted := sampleSize(10, cs); size != 10 || why != SizeFull || !slices.Equal(counted, []string{"c4", "c3", "c2"}) { + t.Fatalf("after a finding: %d %s %v; want full over c4, c3, c2", size, why, counted) + } +} + +func TestOpenCycleCountsAsNeither(t *testing.T) { + cs := []cycleTally{{id: "c5", findings: 3}, closedClean("c3"), {id: "c4"}, closedClean("c2"), closedClean("c1")} + if size, why, counted := sampleSize(10, cs); size != 5 || why != SizeHalved || !slices.Equal(counted, []string{"c3", "c2", "c1"}) { + t.Fatalf("open cycles skipped: %d %s %v; want halved over c3, c2, c1", size, why, counted) + } + if size, _, counted := sampleSize(10, []cycleTally{{id: "c1"}, {id: "c2"}}); size != 10 || len(counted) != 0 { + t.Fatalf("only open cycles: %d %v; want full over none", size, counted) + } +} + +// TestSizeCountsClosedCyclesInWindowOrder: the tally reads the cycles origin's +// copy holds newest first by window, whatever order the files are listed in, +// and stops once three closed ones are found. +func TestSizeCountsClosedCyclesInWindowOrder(t *testing.T) { + r, _ := originWithRemote(t) + files := map[string]string{} + base := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) + var ids []string + for i := range 5 { + id := cycleID(base.Add(time.Duration(i)*24*time.Hour), fmt.Sprintf("%040x", i+1)) + ids = append(ids, id) + files[CyclesDir+"/"+id+".json"] = encodeOrFail(t, Cycle{SchemaVersion: SchemaVersion, ID: id, ToCommit: fmt.Sprintf("%040x", i+1), ToTime: base}) + it := Item{SchemaVersion: SchemaVersion, Cycle: id, Number: 1, Group: GroupDrainLanded, Key: "k", Roles: []string{RoleFacilitator}} + files[ItemsDir+"/"+id+"/"+itemStem(1, GroupDrainLanded, "k")+".json"] = encodeOrFail(t, it) + // The newest (4) is open; 3 found a fault; 2, 1, 0 are clean. + if i < 4 { + verdict := "sound" + if i == 3 { + verdict = "wrong" + } + files[JudgementsDir+"/"+id+"/"+itemStem(1, GroupDrainLanded, "k")+"."+RoleFacilitator+".json"] = `{"verdict":"` + verdict + `"}` + "\n" + } + } + setTracking(t, r, files) + st, err := readWindow(t.Context(), r.Root()) + if err != nil { + t.Fatal(err) + } + tallies, err := tallyCycles(t.Context(), r.Root(), st) + if err != nil { + t.Fatal(err) + } + want := []cycleTally{{id: ids[4]}, {id: ids[3], closed: true, findings: 1}, closedClean(ids[2]), closedClean(ids[1])} + if !slices.Equal(tallies, want) { + t.Fatalf("tallies = %+v; want %+v", tallies, want) + } + if size, why, _ := sampleSize(10, tallies); size != 10 || why != SizeFull { + t.Fatalf("size = %d %s; want full, after the finding in %s", size, why, ids[3]) + } +} diff --git a/internal/core/spotcheck/store.go b/internal/core/spotcheck/store.go index b0dbb9b37f..8a29062554 100644 --- a/internal/core/spotcheck/store.go +++ b/internal/core/spotcheck/store.go @@ -121,6 +121,9 @@ const ( const ( SiteLand = "land" SiteLane = "lane" + // SiteRearm is the merge gate asked afresh when a release hold re-arms a + // withdrawn merge (landing's rearmGate). + SiteRearm = "rearm" ) // Bounds. @@ -242,6 +245,13 @@ type Decision struct { Mode string `json:"mode,omitempty"` AuthorCanWrite *bool `json:"author_can_write,omitempty"` ApprovalCounted *bool `json:"approval_counted,omitempty"` + // ModeLayer is the configuration layer that declared the mode (the + // repository, the machine or the bundled default), and ReceiptNamedHead + // whether a review receipt that stands named the head: both set by the + // gate as it decided, so a reader takes them as fields, never from the + // reason. A record written before the gate set them carries neither. + ModeLayer string `json:"mode_layer,omitempty"` + ReceiptNamedHead *bool `json:"receipt_named_head,omitempty"` } var ( @@ -384,7 +394,7 @@ func (d Decision) normalise() (Decision, error) { d.Answer, d.AnswerKind, d.Model = cleanWord(d.Answer), cleanWord(d.AnswerKind), clean(d.Model) d.Question, d.Rule, d.Reason = clean(d.Question), clean(d.Rule), clean(d.Reason) d.Site, d.PR, d.Head, d.Arm, d.Method, d.Why, d.Unread = "", 0, "", false, "", "", false - d.Mode, d.AuthorCanWrite, d.ApprovalCounted = "", nil, nil + d.Mode, d.AuthorCanWrite, d.ApprovalCounted, d.ModeLayer, d.ReceiptNamedHead = "", nil, nil, "", nil case KindMergeGate: if d.PR <= 0 { return Decision{}, errors.New("a merge-gate decision names no pull request") @@ -392,11 +402,14 @@ func (d Decision) normalise() (Decision, error) { if !shaRe.MatchString(d.Head) { return Decision{}, errors.New("a merge-gate decision names no head commit") } - if d.Site != SiteLand && d.Site != SiteLane { + if d.Site != SiteLand && d.Site != SiteLane && d.Site != SiteRearm { return Decision{}, fmt.Errorf("a merge-gate decision names no site the store keeps (%s)", termsafe.Sanitize(echo(d.Site))) } - d.Method, d.Why, d.Mode = clean(d.Method), clean(d.Why), cleanWord(d.Mode) + d.Method, d.Why, d.Mode, d.ModeLayer = clean(d.Method), clean(d.Why), cleanWord(d.Mode), cleanWord(d.ModeLayer) d.AuthorCanWrite, d.ApprovalCounted = flag(d.AuthorCanWrite), flag(d.ApprovalCounted) + if d.ReceiptNamedHead != nil { + d.ReceiptNamedHead = flag(d.ReceiptNamedHead) + } d.Issue, d.Question, d.Answer, d.AnswerKind, d.Model, d.Rule, d.Reason = "", "", "", "", "", "", "" default: return Decision{}, fmt.Errorf("a decision of kind %s is not one the store keeps", termsafe.Sanitize(echo(d.Kind))) @@ -410,6 +423,32 @@ func flag(b *bool) *bool { return &v } +// typed is h as it leaves the machine that wrote it: its typed fields alone +// (dcn-2611131340596847, settled as typed fields only). The rule and the +// reason the drain wrote stay on that machine's local copy; the drain's rule +// record is kept only where it reads as one word, a record id. +func (h HandBack) typed() HandBack { + h.Rule, h.Reason = "", "" + if !ruleWordRe.MatchString(h.DrainRule) { + h.DrainRule = "" + } + return h +} + +// typed is d as it leaves the machine that wrote it: its typed fields alone. +// The question put, the reason given and the gate's why stay on that +// machine's local copy; the rule record, the model and the method are kept +// only where each reads as one word. +func (d Decision) typed() Decision { + d.Question, d.Reason, d.Why = "", "", "" + for _, f := range []*string{&d.Rule, &d.Model, &d.Method} { + if !ruleWordRe.MatchString(*f) { + *f = "" + } + } + return d +} + // echo is s cut for a refusal to name. func echo(s string) string { if len(s) > 64 { @@ -437,7 +476,12 @@ type file struct { head string } -func (f file) path() string { return f.folder + "/" + f.name } +func (f file) path() string { + if f.folder == "" { + return f.name + } + return f.folder + "/" + f.name +} // named is the file name for a record of stem holding data: the stem, the // first hashLen hex digits of the SHA-256 of data, and .json. @@ -1049,6 +1093,9 @@ type Records struct { HandBacks []HandBack Decisions []Decision Unreadable []string + // handBackNames and decisionNames are the file names each record is + // kept under, in the order of HandBacks and Decisions. + handBackNames, decisionNames []string } // read reads the store at ref (LocalRef or TrackingRef), all its files' @@ -1095,8 +1142,13 @@ func read(ctx context.Context, root, ref string) (rec Records, ok bool, err erro } for i, data := range blobs { dir, name, _ := strings.Cut(names[i], "/") - if !readRecord(&rec, dir, name, data) { + switch { + case !readRecord(&rec, dir, name, data): rec.Unreadable = append(rec.Unreadable, termsafe.Sanitize(names[i])) + case dir == HandBacksDir: + rec.handBackNames = append(rec.handBackNames, name) + default: + rec.decisionNames = append(rec.decisionNames, name) } } return rec, true, nil @@ -1159,20 +1211,24 @@ type PushResult struct { var beforePush func(attempt int) // push carries the local copy's records to origin: a fetch of the branch, -// the records origin lacks laid over its tip when another writer moved it, -// and one plain push (claim.PushBranch), never forced. A push origin rejects -// (a writer that pushed between the fetch and the push) is tried once more -// after a fresh fetch; a second failure is an error, and every record stays -// on the local copy for the next push. A fetch or a push whose git was not -// run (a gitutil.NotRunError: the check gitutil.SetBeforeHookedGit set -// refused it, or the read of core.sshCommand that decides its ssh command -// failed) is not tried again: the error says the push was stopped and -// carries the stop. The local copy is never moved: it -// keeps only what this checkout wrote, whatever origin holds. A branch origin no longer holds -// is no copy at all: its tracking ref is removed and the local copy pushed -// whole. Nothing origin holds is removed, and only a file its name does not -// give is replaced. A checkout whose local copy holds nothing origin lacks -// pushes nothing. +// the typed copy (typed) of every record the local copy holds that origin's +// copy lacks committed over origin's tip, and one plain push +// (claim.PushBranch), never forced. Only a file that reads as a record this +// package writes is carried, and only its typed fields: a record's free text +// never leaves the machine that wrote it, and a file the local copy holds +// that does not read as a record is never sent. A push origin rejects (a +// writer that pushed between the fetch and the push) is tried once more after +// a fresh fetch; a second failure is an error, and every record stays on the +// local copy for the next push. A fetch or a push whose git was not run (a +// gitutil.NotRunError: the check gitutil.SetBeforeHookedGit set refused it, +// or the read of core.sshCommand that decides its ssh command failed) is not +// tried again: the error says the push was stopped and carries the stop. The +// local copy is never moved: it keeps only what this checkout wrote, whatever +// origin holds. A branch origin no longer holds is no copy at all: its +// tracking ref is removed and the records pushed onto a new one. Nothing +// origin holds is removed, and only a file its name does not give is +// replaced. A checkout whose local copy holds nothing origin lacks pushes +// nothing. func push(ctx context.Context, root string) (PushResult, error) { if err := originPresent(ctx, root); err != nil { return PushResult{}, err @@ -1189,31 +1245,27 @@ func push(ctx context.Context, root string) (PushResult, error) { if local == "" { return PushResult{}, nil } - found, err := claim.FetchBranch(ctx, root, BranchRef, TrackingRef) + tracking, err := fetchTracking(ctx, root) if err != nil { - return PushResult{}, fmt.Errorf("the spot-check's record was not pushed: %w", stopped("push", err)) + return PushResult{}, err } - tracking := "" - if found { - if tracking, err = storeRef(ctx, root, TrackingRef); err != nil { - return PushResult{}, err - } - } else if old, err := storeRef(ctx, root, TrackingRef); err == nil && old != "" { - if _, err := storeGit(ctx, root, "", "", "update-ref", "-d", TrackingRef, old); err != nil { - return PushResult{}, err - } + theirs, err := listFiles(ctx, root, tracking) + if err != nil { + return PushResult{}, err } - res, err := layOver(ctx, root, local, tracking) + todo, unreadable, err := outbound(ctx, root, theirs) if err != nil { return PushResult{}, err } - if res.Commit == "" { + res := PushResult{Pushed: len(todo), Unreadable: unreadable} + if len(todo) == 0 { return res, nil } if beforePush != nil { beforePush(attempt) } - if err := claim.PushBranch(ctx, root, res.Commit, BranchRef); err != nil { + commit, err := pushOver(ctx, root, tracking, todo, fmt.Sprintf("spotcheck: %d record(s)", len(todo))) + if err != nil { var nr *gitutil.NotRunError if errors.As(err, &nr) { return PushResult{}, fmt.Errorf("the spot-check's record was not pushed, and stays on this copy for the next push: %w", stopped("push", err)) @@ -1221,91 +1273,104 @@ func push(ctx context.Context, root string) (PushResult, error) { last = err continue } - // The tracking copy follows what origin took, so the next push lays - // on it; a move refused here is put right by the next fetch. - _, _ = storeGit(ctx, root, "", "", "update-ref", TrackingRef, res.Commit) + res.Commit = commit return res, nil } return PushResult{}, fmt.Errorf("the spot-check's record was not pushed after two tries, so every record stays on this copy for the next push: %w", last) } -// layOver is the commit to push for the local copy and origin's (tracking, -// "" for none) as just fetched: the local copy when origin holds none or its -// tip is an ancestor of the local copy, a commit over origin's copy holding -// every file the local copy has and it lacks, at any depth, when the two have -// parted, and "" when origin holds every file already. A path both hold with -// other content is settled by its name (nameMatches): the copy its name gives -// is kept, and the other named in Unreadable. The local copy is not moved, so -// it never holds another writer's files and its records stay on it whatever -// the push does. -func layOver(ctx context.Context, root, local, tracking string) (PushResult, error) { - mine, err := listFiles(ctx, root, local) +// fetchTracking fetches the store's branch into its tracking ref and answers +// the commit it names, "" when origin holds no such branch (a stale tracking +// ref is then removed). +func fetchTracking(ctx context.Context, root string) (string, error) { + found, err := claim.FetchBranch(ctx, root, BranchRef, TrackingRef) if err != nil { - return PushResult{}, err + return "", fmt.Errorf("the spot-check's branch was not fetched: %w", stopped("push", err)) } - theirs, err := listFiles(ctx, root, tracking) - if err != nil { - return PushResult{}, err + if found { + return storeRef(ctx, root, TrackingRef) } - var res PushResult - var adds []placed - var clash []string - for p, e := range mine { - t, held := theirs[p] - switch { - case !held: - res.Pushed++ - adds = append(adds, placed{path: p, entry: e}) - case t.sha != e.sha: - clash = append(clash, p) + if old, err := storeRef(ctx, root, TrackingRef); err == nil && old != "" { + if _, err := storeGit(ctx, root, "", "", "update-ref", "-d", TrackingRef, old); err != nil { + return "", err } } - slices.Sort(clash) - for _, p := range clash { - mineGood, theirsGood := false, false - e, t := mine[p], theirs[p] - if e.typ == "blob" && t.typ == "blob" && e.size <= maxRecordBytes && t.size <= maxRecordBytes { - blobs, err := readBlobs(ctx, root, []entry{e, t}) - if err != nil { - return PushResult{}, err - } - name := p[strings.LastIndexByte(p, '/')+1:] - mineGood, theirsGood = nameMatches(name, blobs[0]), nameMatches(name, blobs[1]) - } - res.Unreadable = append(res.Unreadable, termsafe.Sanitize(p)) - if mineGood && !theirsGood { - res.Pushed++ - adds = append(adds, placed{path: p, entry: e}) + return "", nil +} + +// outbound is the typed copy of every record the local copy holds that +// origin's copy (theirs, its listing) lacks: a path origin holds with the +// same content is held; one it holds with other content is named in +// unreadable, and carried only when origin's file is not the content its +// name gives. A file of the local copy that does not read as a record is +// never among them. +func outbound(ctx context.Context, root string, theirs map[string]entry) (todo []file, unreadable []string, err error) { + rec, ok, err := read(ctx, root, LocalRef) + if err != nil || !ok { + return nil, nil, err + } + var cands []file + for _, h := range rec.HandBacks { + if f, err := h.typed().file(); err == nil { + cands = append(cands, f) } } - if tracking == "" { - if res.Pushed > 0 { - res.Commit = local + for _, d := range rec.Decisions { + if f, err := d.typed().file(); err == nil { + cands = append(cands, f) } - return res, nil } - if res.Pushed == 0 { - // Origin holds everything: nothing to push. - return res, nil + seen := map[string]bool{} + for _, f := range cands { + if seen[f.path()] { + continue + } + seen[f.path()] = true + t, held := theirs[f.path()] + if !held { + todo = append(todo, f) + continue + } + if t.typ == "blob" && t.sha == blobID(f.data, len(t.sha)) { + continue + } + unreadable = append(unreadable, termsafe.Sanitize(f.path())) + good := false + if t.typ == "blob" && t.size <= maxRecordBytes { + blobs, err := readBlobs(ctx, root, []entry{t}) + if err != nil { + return nil, nil, err + } + good = nameMatches(f.name, blobs[0]) + } + if !good { + todo = append(todo, f) + } } - ahead, err := isAncestor(ctx, root, tracking, local) + slices.SortFunc(todo, func(a, b file) int { return strings.Compare(a.path(), b.path()) }) + return todo, unreadable, nil +} + +// pushOver commits files over origin's copy as last fetched (tracking, "" +// for none), touching no HEAD, index or working tree, and pushes the commit +// to origin's branch, plainly: origin takes it only as a fast-forward. On +// success the tracking ref follows what origin took (a move refused there is +// put right by the next fetch); a push that fails leaves nothing behind but +// an unreferenced commit. +func pushOver(ctx context.Context, root, tracking string, files []file, msg string) (string, error) { + tree, err := treeWith(ctx, root, tracking, files) if err != nil { - return PushResult{}, err - } - if ahead { - res.Commit = local - return res, nil + return "", err } - tree, err := treeOver(ctx, root, tracking, adds) + commit, err := commitTree(ctx, root, tree, tracking, msg) if err != nil { - return PushResult{}, err + return "", err } - commit, err := commitTree(ctx, root, tree, tracking, fmt.Sprintf("spotcheck: %d record(s) laid over %s's copy", res.Pushed, claim.Remote)) - if err != nil { - return PushResult{}, err + if err := claim.PushBranch(ctx, root, commit, BranchRef); err != nil { + return "", err } - res.Commit = commit - return res, nil + _, _ = storeGit(ctx, root, "", "", "update-ref", TrackingRef, commit) + return commit, nil } // placed is one file of the local copy at its path, for a lay-over. diff --git a/internal/core/spotcheck/store_test.go b/internal/core/spotcheck/store_test.go index 6a3d2ee9da..b344200d34 100644 --- a/internal/core/spotcheck/store_test.go +++ b/internal/core/spotcheck/store_test.go @@ -1001,15 +1001,15 @@ func TestASecondLostRaceKeepsTheRecordsForTheNextPush(t *testing.T) { } } -// Two records of one issue in one second that differ, one from each -// writer, are both pushed; and a file origin holds under a record's name -// whose content the name does not give is named unreadable and replaced by -// the record, which is then found on origin's copy. +// Two records of one issue in one second whose typed fields differ, one from +// each writer, are both pushed; and a file origin holds under a record's +// name whose content the name does not give is named unreadable and +// replaced by the record's typed copy, which is then found on origin's copy. func TestAFileOriginHoldsUnderARecordsNameWithOtherContentIsReplaced(t *testing.T) { a, b, bare := twoClones(t) ctx := context.Background() ha, hb2 := handBack("iss-1", at0), handBack("iss-1", at0) - hb2.Reason = "another reason" + hb2.Kind = "closed" write(t, a.Root(), hb(ha)) write(t, b.Root(), hb(hb2)) if _, err := push(ctx, a.Root()); err != nil { @@ -1022,7 +1022,7 @@ func TestAFileOriginHoldsUnderARecordsNameWithOtherContentIsReplaced(t *testing. t.Fatalf("origin holds %v, want both of iss-1's records", got) } // Another writer puts other content under a record's name on origin. - mine := fileOf(t, handBack("iss-2", at0)) + mine := fileOf(t, handBack("iss-2", at0).typed()) // the name the push carries write(t, b.Root(), hb(handBack("iss-2", at0))) a.Git("fetch", "origin", "+"+BranchRef+":"+TrackingRef) planted := commitFilesAt(t, a, a.Git("rev-parse", TrackingRef), map[string]string{mine.path(): "{}\n"}) @@ -1037,7 +1037,7 @@ func TestAFileOriginHoldsUnderARecordsNameWithOtherContentIsReplaced(t *testing. } found := false for _, h := range rec.HandBacks { - found = found || (h.Issue == "iss-2" && h.Reason == "the lane kept refusing") + found = found || (h.Issue == "iss-2" && h.Kind == "stuck" && h.Reason == "") } if !found || len(rec.Unreadable) != 0 || len(rec.HandBacks) != 3 { t.Fatalf("origin's copy holds %+v", rec) @@ -1063,34 +1063,28 @@ func TestABranchGoneFromOriginLeavesNoStaleTrackingRef(t *testing.T) { } } -// The lay-over compares files at any depth: a file the local copy holds in a -// folder within a folder that origin lacks is pushed, and origin's own at -// any depth are kept. -func TestALayOverComparesFilesAtAnyDepth(t *testing.T) { +// A push keeps origin's files at any depth: a file origin holds in a folder +// within a folder stays when another writer pushes its records over it, and +// a file the local copy holds that is no record is never pushed. +func TestAPushKeepsOriginsFilesAtAnyDepth(t *testing.T) { a, b, bare := twoClones(t) ctx := context.Background() write(t, a.Root(), hb(handBack("iss-1", at0))) if _, err := push(ctx, a.Root()); err != nil { t.Fatal(err) } - a.Git("update-ref", LocalRef, commitFilesAt(t, a, a.Git("rev-parse", LocalRef), map[string]string{"items/x/one.json": "one\n"})) - if _, err := push(ctx, a.Root()); err != nil { - t.Fatal(err) - } + a.Git("fetch", "origin", "+"+BranchRef+":"+TrackingRef) + deep := commitFilesAt(t, a, a.Git("rev-parse", TrackingRef), map[string]string{"items/x/one.json": "one\n"}) + a.Git("push", "origin", deep+":"+BranchRef) write(t, b.Root(), hb(handBack("iss-2", at0))) b.Git("update-ref", LocalRef, commitFilesAt(t, b, b.Git("rev-parse", LocalRef), map[string]string{"items/x/two.json": "two\n"})) res, err := push(ctx, b.Root()) - if err != nil || res.Pushed != 2 { + if err != nil || res.Pushed != 1 { t.Fatalf("b's push = %+v, %v", res, err) } got := remoteFiles(t, bare) - for _, want := range []string{"items/x/one.json", "items/x/two.json"} { - if !slices.Contains(got, want) { - t.Fatalf("origin holds %v, want %s", got, want) - } - } - if len(got) != 4 { - t.Fatalf("origin holds %v", got) + if !slices.Contains(got, "items/x/one.json") || slices.Contains(got, "items/x/two.json") || len(got) != 3 { + t.Fatalf("origin holds %v; want iss-1, iss-2 and items/x/one.json", got) } } diff --git a/internal/core/spotcheck/window.go b/internal/core/spotcheck/window.go new file mode 100644 index 0000000000..462555513f --- /dev/null +++ b/internal/core/spotcheck/window.go @@ -0,0 +1,46 @@ +package spotcheck + +// window.go is the trigger (spc-2610301925429250 approach 3): a window spans +// everything since the last cycle, or since the window opened, and closes at +// the first landing observed once either bound has passed. + +import ( + "context" + "fmt" + "strconv" + "strings" + "time" + + "github.com/intentdriven/abcd/internal/gitutil" +) + +// windowClosedBy is the bound a window that began at from has passed by now, +// changes first-parent commits later: ClosedByDays once WindowDays whole +// days have gone by, ClosedByChanges once WindowChanges (when set) commits +// have landed, the days first when both have; "" when neither has. +func windowClosedBy(c Config, from time.Time, changes int, now time.Time) string { + if !now.Before(from.Add(time.Duration(c.WindowDays) * 24 * time.Hour)) { + return ClosedByDays + } + if c.WindowChanges > 0 && changes >= c.WindowChanges { + return ClosedByChanges + } + return "" +} + +// changesSince counts the first-parent commits from from to tip, both full +// object names this checkout holds, as stored: one local git command. +func changesSince(ctx context.Context, root, from, tip string) (int, error) { + if from == tip { + return 0, nil + } + out, err := gitutil.RunCappedBytesAsStoredContext(ctx, root, "", 64, "rev-list", "--first-parent", "--count", from+".."+tip, "--") + if err != nil { + return 0, fmt.Errorf("counting the changes since the spot-check's last window: %s", redact(err)) + } + n, err := strconv.Atoi(strings.TrimSpace(string(out))) + if err != nil || n < 0 { + return 0, fmt.Errorf("counting the changes since the spot-check's last window: git answered %q", strings.TrimSpace(string(out))) + } + return n, nil +} diff --git a/internal/core/spotcheck/window_test.go b/internal/core/spotcheck/window_test.go new file mode 100644 index 0000000000..e28461db24 --- /dev/null +++ b/internal/core/spotcheck/window_test.go @@ -0,0 +1,39 @@ +package spotcheck + +import ( + "testing" + "time" +) + +func TestWindowByDays(t *testing.T) { + c := Config{WindowDays: 7, PerGroup: 10} + if got := windowClosedBy(c, at0, 1000, at0.Add(7*24*time.Hour-time.Second)); got != "" { + t.Fatalf("a window a second short of seven days closed by %q", got) + } + if got := windowClosedBy(c, at0, 0, at0.Add(7*24*time.Hour)); got != ClosedByDays { + t.Fatalf("a window of seven days closed by %q; want days", got) + } +} + +func TestWindowByChanges(t *testing.T) { + c := Config{WindowDays: 90, WindowChanges: 10, PerGroup: 10} + if got := windowClosedBy(c, at0, 9, at0.Add(time.Hour)); got != "" { + t.Fatalf("nine changes closed a window of ten by %q", got) + } + if got := windowClosedBy(c, at0, 10, at0.Add(time.Hour)); got != ClosedByChanges { + t.Fatalf("ten changes closed the window by %q; want changes", got) + } + if got := windowClosedBy(c, at0, 10, at0.Add(90*24*time.Hour)); got != ClosedByDays { + t.Fatalf("both bounds passed: closed by %q; want days first", got) + } + // The changes are counted on the first-parent line, locally. + r, _ := originWithRemote(t) + from := r.Git("rev-parse", "HEAD") + for range 3 { + r.Commit("a change") + } + n, err := changesSince(t.Context(), r.Root(), from, r.Git("rev-parse", "HEAD")) + if err != nil || n != 3 { + t.Fatalf("changesSince = %d, %v; want 3", n, err) + } +} diff --git a/internal/surface/cli/githook_prepush_receiptless_test.go b/internal/surface/cli/githook_prepush_receiptless_test.go index 1fb92e2e4e..50463ba031 100644 --- a/internal/surface/cli/githook_prepush_receiptless_test.go +++ b/internal/surface/cli/githook_prepush_receiptless_test.go @@ -49,21 +49,24 @@ func receiptlessRows(t *testing.T, hook string) [][]string { } // TestPrePushReceiptlessPrefixesAreDeclaredWithARulingAndAShapeCheck: every -// row names a prefix ending in a slash, a shape check the hook defines, a -// ruling record that exists, and the act that ends a ref there, or "never" for -// a branch kept for ever; the rows are the reservation prefix and the status -// prefix (adr-2610150729333337), both checked by the reservation's shape. +// row names a prefix ending in a slash, or one branch exactly, a shape check +// the hook defines, a ruling record that exists, and the act that ends a ref +// there, or "never" for a branch kept for ever; the rows are the reservation +// prefix and the status prefix (adr-2610150729333337), both checked by the +// reservation's shape, and the spot-check's store branch +// (adr-2611251806496719), checked by its own. func TestPrePushReceiptlessPrefixesAreDeclaredWithARulingAndAShapeCheck(t *testing.T) { root, hook := committedHook(t) rows := receiptlessRows(t, hook) - if len(rows) != 2 || len(rows[0]) != 4 || rows[0][0] != "abcd-reserved/" || - len(rows[1]) != 4 || strings.Join(rows[1], "|") != "abcd-status/|reservation_shape|adr-2610150729333337|never" { - t.Fatalf("the receipt-less table is %q; want the reservation row, then the status row, each in four fields", rows) + if len(rows) != 3 || len(rows[0]) != 4 || rows[0][0] != "abcd-reserved/" || + len(rows[1]) != 4 || strings.Join(rows[1], "|") != "abcd-status/|reservation_shape|adr-2610150729333337|never" || + len(rows[2]) != 4 || strings.Join(rows[2], "|") != "abcd-spotcheck|spotcheck_shape|adr-2611251806496719|never" { + t.Fatalf("the receipt-less table is %q; want the reservation row, the status row, then the spot-check row, each in four fields", rows) } for _, row := range rows { prefix, shape, ruling := row[0], row[1], row[2] - if !strings.HasSuffix(prefix, "/") || strings.ContainsAny(prefix, "*?[ ") { - t.Errorf("prefix %q is not a plain branch prefix ending in a slash", prefix) + if strings.ContainsAny(prefix, "*?[ ") || (!strings.HasSuffix(prefix, "/") && prefix != "abcd-spotcheck") { + t.Errorf("prefix %q is not a plain branch prefix ending in a slash, nor the one branch the store is", prefix) } if shape == "" || !regexp.MustCompile(`(?m)^`+regexp.QuoteMeta(shape)+`\(\) \{`).MatchString(hook) { t.Errorf("prefix %q names the shape check %q, which the hook does not define", prefix, shape) diff --git a/internal/surface/cli/githook_prepush_spotcheck_test.go b/internal/surface/cli/githook_prepush_spotcheck_test.go new file mode 100644 index 0000000000..0e18c0fe47 --- /dev/null +++ b/internal/surface/cli/githook_prepush_spotcheck_test.go @@ -0,0 +1,211 @@ +package cli + +import ( + "os" + "os/exec" + "path/filepath" + "strings" + "testing" +) + +// The committed pre-push hook's spot-check row (itd-2610301750162657, +// adr-2611251806496719): refs/heads/abcd-spotcheck, the spot-check's store, is +// an orphan of small JSON files under the store's folders, pushed by abcd +// with the hooks running and no receipt. The row admits a fast-forward whose +// every commit holds only regular files at the store's paths; every other +// push to the branch is gated as any branch is, a branch whose name merely +// begins like it is no branch of the row, and the store is never deleted. + +const spotcheckRef = "refs/heads/abcd-spotcheck" + +// storeFile is one file of a store commit: its path, content and mode. +type storeFile struct { + path, body, mode string +} + +// storeCommit writes a commit over parent ("" for none) whose tree holds +// files alone, made in an index of its own, as the store writes one. +func (c *prePushCase) storeCommit(parent string, files ...storeFile) string { + c.t.Helper() + index := filepath.Join(c.t.TempDir(), "index") + git := func(args ...string) string { + cmd := exec.Command("git", args...) + cmd.Dir = c.dir + cmd.Env = append(append([]string{}, c.env...), "GIT_INDEX_FILE="+index) + out, err := cmd.CombinedOutput() + if err != nil { + c.t.Fatalf("git %v: %v\n%s", args, err, out) + } + return strings.TrimSpace(string(out)) + } + if parent != "" { + git("read-tree", parent+"^{tree}") + } else { + git("read-tree", "--empty") + } + for i, f := range files { + p := filepath.Join(c.t.TempDir(), "f"+string(rune('a'+i))) + if err := os.WriteFile(p, []byte(f.body), 0o644); err != nil { + c.t.Fatal(err) + } + sha := git("hash-object", "-w", p) + mode := f.mode + if mode == "" { + mode = "100644" + } + git("update-index", "--add", "--cacheinfo", mode+","+sha+","+f.path) + } + return c.commitTree(git("write-tree"), parent, "spotcheck: records") +} + +var ( + windowOpen = storeFile{path: "window-open.json", body: "{}\n"} + aHandBack = storeFile{path: "handbacks/20261125T010203Z-iss-12-0123456789abcdef.json", body: "{}\n"} + anItem = storeFile{path: "items/20261125T010203Z-0123456789ab/001-drain-landed-" + strings.Repeat("a", 40) + ".json", body: "{}\n"} +) + +// TestPrePushPassesStoreCommitsWithoutAReceipt: the store's first push (an +// orphan create) and the next (a fast-forward over it) pass with no receipt. +func TestPrePushPassesStoreCommitsWithoutAReceipt(t *testing.T) { + c := newPrePushCase(t) + first := c.storeCommit("", windowOpen) + if out, err := c.push("--porcelain", "origin", first+":"+spotcheckRef); err != nil { + t.Fatalf("the store's first commit was refused\n%s", out) + } + next := c.storeCommit(first, aHandBack, anItem) + if out, err := c.push("--porcelain", "origin", next+":"+spotcheckRef); err != nil { + t.Fatalf("a fast-forward of store records was refused\n%s", out) + } + if got := c.remoteRef(spotcheckRef); got != next { + t.Fatalf("the remote holds %q, want %s", got, next) + } +} + +// TestPrePushGatesEveryOtherPushToTheStore: a file outside the store's paths, +// an executable or a link at one, a tree entry named "..", the product's +// history pushed to the branch, and a commit carrying files over a store +// commit each need a receipt; a rewrite is refused as a non-fast-forward; a +// deletion is refused naming the ruling; and a branch whose name begins like +// the store's is no branch of the row. +func TestPrePushGatesEveryOtherPushToTheStore(t *testing.T) { + refused := func(t *testing.T, c *prePushCase, commit, ref string) { + t.Helper() + out, err := c.push("origin", commit+":"+ref) + if err == nil || !strings.Contains(out, "no passing preflight") { + t.Fatalf("the push passed without a receipt (err %v)\n%s", err, out) + } + if got := c.remoteRef(ref); got != "" && got == commit { + t.Errorf("the remote moved to %s although the push was refused", got) + } + } + for name, f := range map[string]storeFile{ + "a file outside the store": {path: "main.go", body: "package main\n"}, + "a file at the root": {path: "notes.json", body: "{}\n"}, + "not json": {path: "handbacks/x.txt", body: "x\n"}, + "an executable": {path: aHandBack.path, body: "#!/bin/sh\n", mode: "100755"}, + "a link": {path: aHandBack.path, body: "../../etc/passwd", mode: "120000"}, + "another folder": {path: "scripts/x.json", body: "{}\n"}, + "a name with a space": {path: "handbacks/a b.json", body: "{}\n"}, + "a store folder file at top": {path: "handbacks.json", body: "{}\n"}, + } { + t.Run(name, func(t *testing.T) { + c := newPrePushCase(t) + refused(t, c, c.storeCommit("", windowOpen, f), spotcheckRef) + }) + } + t.Run("a tree entry named ..", func(t *testing.T) { + // git's index refuses such a path, so the tree is written as raw + // entries, as a hand-made object could be. + c := newPrePushCase(t) + mktree := func(entry string) string { + cmd := exec.Command("git", "mktree") + cmd.Dir, cmd.Env, cmd.Stdin = c.dir, c.env, strings.NewReader(entry+"\n") + out, err := cmd.CombinedOutput() + if err != nil { + t.Fatalf("git mktree: %v\n%s", err, out) + } + return strings.TrimSpace(string(out)) + } + p := filepath.Join(t.TempDir(), "x.json") + if err := os.WriteFile(p, []byte("{}\n"), 0o644); err != nil { + t.Fatal(err) + } + blob := c.git("hash-object", "-w", p) + inner := mktree("100644 blob " + blob + "\tx.json") + dots := mktree("040000 tree " + inner + "\t..") + root := mktree("040000 tree " + dots + "\titems") + if got := c.git("ls-tree", "-r", "--full-tree", "--name-only", root); got != "items/../x.json" { + t.Fatalf("the hand-made tree lists %q", got) + } + refused(t, c, c.commitTree(root, "", "spotcheck: records"), spotcheckRef) + }) + t.Run("the product's history", func(t *testing.T) { + c := newPrePushCase(t) + refused(t, c, c.commit("feature.md", "a feature\n"), spotcheckRef) + }) + t.Run("a store commit over the product's history", func(t *testing.T) { + c := newPrePushCase(t) + base := c.commit("feature.md", "a feature\n") + tree := c.git("hash-object", "-w", "-t", "tree", "/dev/null") + refused(t, c, c.commitTree(tree, base, "spotcheck: records"), spotcheckRef) + }) + t.Run("files over a store commit", func(t *testing.T) { + c := newPrePushCase(t) + first := c.storeCommit("", windowOpen) + if out, err := c.push("origin", first+":"+spotcheckRef); err != nil { + t.Fatalf("the store's first commit was refused\n%s", out) + } + out, err := c.push("origin", c.storeCommit(first, storeFile{path: "Makefile", body: "all:\n"})+":"+spotcheckRef) + if err == nil || !strings.Contains(out, "no passing preflight") { + t.Fatalf("a file outside the store passed over a store commit (err %v)\n%s", err, out) + } + if got := c.remoteRef(spotcheckRef); got != first { + t.Errorf("the remote holds %q, want %s", got, first) + } + }) + t.Run("rewrite", func(t *testing.T) { + c := newPrePushCase(t) + first := c.storeCommit("", windowOpen) + if out, err := c.push("origin", first+":"+spotcheckRef); err != nil { + t.Fatalf("the store's first commit was refused\n%s", out) + } + out, err := c.push("origin", "+"+c.storeCommit("", aHandBack)+":"+spotcheckRef) + if err == nil || !strings.Contains(out, "non-fast-forward") { + t.Fatalf("a forced rewrite of the store passed (err %v)\n%s", err, out) + } + }) + t.Run("a branch named like the store", func(t *testing.T) { + c := newPrePushCase(t) + refused(t, c, c.storeCommit("", windowOpen), "refs/heads/abcd-spotcheck-x") + }) + for name, del := range map[string][]string{ + "delete by colon refspec": {"origin", ":" + spotcheckRef}, + "delete by --delete": {"--delete", "origin", "abcd-spotcheck"}, + } { + t.Run(name, func(t *testing.T) { + c := newPrePushCase(t) + first := c.storeCommit("", windowOpen) + if out, err := c.push("origin", first+":"+spotcheckRef); err != nil { + t.Fatalf("the store's first commit was refused\n%s", out) + } + out, err := c.push(del...) + if err == nil || !strings.Contains(out, "is kept for ever and never deleted") || !strings.Contains(out, "adr-2611251806496719") { + t.Fatalf("a deletion of the store was not refused as one (err %v)\n%s", err, out) + } + if got := c.remoteRef(spotcheckRef); got != first { + t.Errorf("the remote holds %q, want %s", got, first) + } + }) + } + t.Run("a deletion of a branch named like the store", func(t *testing.T) { + c := newPrePushCase(t) + other := c.commit("feature.md", "a feature\n") + c.preflight(c.dir) + if out, err := c.push("origin", other+":refs/heads/abcd-spotcheck-x"); err != nil { + t.Fatalf("a receipted push was refused\n%s", out) + } + if out, err := c.push("origin", ":refs/heads/abcd-spotcheck-x"); err != nil { + t.Fatalf("the deletion of a branch only named like the store was refused\n%s", out) + } + }) +} From 04fe789c5b768c0dd493b7498fe9f58768f0a1c4 Mon Sep 17 00:00:00 2001 From: REPPL <77722411+REPPL@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:21:24 +0000 Subject: [PATCH 02/16] chore: build the beacon check on circl v1.6.3 The spot-check's BLS check imports circl's sign/bls at v1.6.3, the version the module graph already holds, rather than v1.6.5, so go.sum is unchanged and go.mod only lists circl as a direct requirement. Refs: spc-2610301925429250 Refs: itd-2610301750162657 Assisted-by: Claude:claude-opus-5-5 --- go.mod | 2 +- go.sum | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/go.mod b/go.mod index 2c2911a2e4..9b5a56e549 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,7 @@ module github.com/intentdriven/abcd go 1.27.4 require ( - github.com/cloudflare/circl v1.6.5 + github.com/cloudflare/circl v1.6.3 github.com/coder/websocket v1.8.15 github.com/minio/selfupdate v0.6.0 github.com/sigstore/sigstore-go v1.4.0 diff --git a/go.sum b/go.sum index 9bc160730c..959f2bb211 100644 --- a/go.sum +++ b/go.sum @@ -74,8 +74,8 @@ github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1x github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw= github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= -github.com/cloudflare/circl v1.6.5 h1:O64F26HEqNhznd/hrC5KZXVKYuKM2rx4deZDTc4ihQA= -github.com/cloudflare/circl v1.6.5/go.mod h1:h5LNyxAc5nTue9DS5jT+48en2PSDYt3zdGnz5OstK6c= +github.com/cloudflare/circl v1.6.3 h1:9GPOhQGF9MCYUeXyMYlqTR6a5gTrgR/fBLXvUgtVcg8= +github.com/cloudflare/circl v1.6.3/go.mod h1:2eXP6Qfat4O/Yhh8BznvKnJ+uzEoTQ6jVKJRn81BiS4= github.com/codahale/rfc6979 v0.0.0-20141003034818-6a90f24967eb h1:EDmT6Q9Zs+SbUoc7Ik9EfrFqcylYqgPZ9ANSbTAntnE= github.com/codahale/rfc6979 v0.0.0-20141003034818-6a90f24967eb/go.mod h1:ZjrT6AXHbDs86ZSdt/osfBi5qfexBrKUdONk989Wnk4= github.com/coder/websocket v1.8.15 h1:6B2JPeOGlpff2Uz6vOEH1Vzpi0iUz20A+lPVhPHtNUA= From 9f8e5bd245ce219671ee179ec8d9132a5f46d9fa Mon Sep 17 00:00:00 2001 From: REPPL <77722411+REPPL@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:24:32 +0000 Subject: [PATCH 03/16] chore: name the beacon's public key so no scanner reads it as a secret gitleaks' generic-api-key rule read the drand quicknet group public key, assigned to a constant named chainKey, as a credential. The key is public by design; the constant is now chainPoint, and .gitleaksignore records the one finding the earlier commit leaves in the history. Refs: spc-2610301925429250 Refs: itd-2610301750162657 Assisted-by: Claude:claude-opus-5-5 --- .gitleaksignore | 6 ++++++ internal/core/spotcheck/beacon.go | 6 +++--- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/.gitleaksignore b/.gitleaksignore index 26b593677d..6b9dfb9a9f 100644 --- a/.gitleaksignore +++ b/.gitleaksignore @@ -48,3 +48,9 @@ dc0ed2c62fad1ed5fef836e4472c677ab3ac23d2:.gitleaksignore:generic-api-key:27 # it, and generic-api-key read the assignment as a credential. It was never a # credential, and the constant is renamed at the branch tip. 46425fc70b6b56292fbbf32968966ec962686a1d:internal/surface/cli/refusal_envelope_test.go:generic-api-key:95 + +# Commit d04abf7d3 added the spot-check's beacon check (itd-2610301750162657) +# with `chainKey = ""`, the drand quicknet chain's published group public +# key, and generic-api-key reads the `Key = "…"` assignment as a credential. +# The value is public by design; the constant is renamed at the branch tip. +d04abf7d38e2fd7cf63e679345f1b35d25558e65:internal/core/spotcheck/beacon.go:generic-api-key:38 diff --git a/internal/core/spotcheck/beacon.go b/internal/core/spotcheck/beacon.go index 8421393c7d..a75425e6fe 100644 --- a/internal/core/spotcheck/beacon.go +++ b/internal/core/spotcheck/beacon.go @@ -32,10 +32,10 @@ import ( // chain by this hash. const ChainHash = "52db9ba70e0cc0f6eaf7803dd07447a1f5477735fd3f661792ba94600c84e971" -// chainKey is the quicknet chain's group public key, a compressed point on +// chainPoint is the quicknet chain's group public key, a compressed point on // G2 (scheme bls-unchained-g1-rfc9380: signatures on G1, keys on G2), read // from the same info reply. -const chainKey = "83cf0f2896adee7eb8b5f01fcad3912212c437e0073e911fb90022d3e760183c8c4b450b6a0a6c3ac6a5776a2d1064510d1fec758c921cc22b0e17e63aaf4bcb5ed66304de9cf809bd274ca73bab4af5a6e9c76a4bc09e76eae8991ef5ece45a" +const chainPoint = "83cf0f2896adee7eb8b5f01fcad3912212c437e0073e911fb90022d3e760183c8c4b450b6a0a6c3ac6a5776a2d1064510d1fec758c921cc22b0e17e63aaf4bcb5ed66304de9cf809bd274ca73bab4af5a6e9c76a4bc09e76eae8991ef5ece45a" // The beacon's bounds. const ( @@ -219,7 +219,7 @@ func sigBytes(s string) ([]byte, error) { // message signed is the SHA-256 of the round as a big-endian uint64; circl's // G1 domain separation tag is the one the chain's scheme signs under. func verifyRound(round uint64, sig []byte) ([32]byte, error) { - key, err := hex.DecodeString(chainKey) + key, err := hex.DecodeString(chainPoint) if err != nil { return [32]byte{}, err } From b96c0a148b534a63544f5bee7f03af99eb4bb1a0 Mon Sep 17 00:00:00 2001 From: REPPL <77722411+REPPL@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:50:19 +0000 Subject: [PATCH 04/16] test: switch the observation off without a second init The plain-only guard scan refuses a package that declares init twice, and the loop package already has one. The landing and loop tests now turn the spot-check's observation off through a package variable's initialiser. Refs: spc-2610301925429250 Refs: itd-2610301750162657 Assisted-by: Claude:claude-opus-5-5 --- internal/core/implement/loop/land_spotcheck_test.go | 5 +++-- internal/core/landing/land_spotcheck_test.go | 5 +++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/internal/core/implement/loop/land_spotcheck_test.go b/internal/core/implement/loop/land_spotcheck_test.go index 528e814028..c921fb3a77 100644 --- a/internal/core/implement/loop/land_spotcheck_test.go +++ b/internal/core/implement/loop/land_spotcheck_test.go @@ -171,9 +171,10 @@ func keptWhy(why string) string { // The spot-check's observation of a landing is turned off for every test of // the package but the ones that count it: an observation reaches origin and // the beacon, which no other test here is about. -func init() { +var _ = func() bool { observeLanding = func(context.Context, spotcheck.Observed) string { return "" } -} + return true +}() // TestALaneLandingIsObservedOnce: the lane landing the ancestor check proves // is observed for the spot-check once, from the run's checkout at origin's diff --git a/internal/core/landing/land_spotcheck_test.go b/internal/core/landing/land_spotcheck_test.go index 93469f82c1..6907e0fbc9 100644 --- a/internal/core/landing/land_spotcheck_test.go +++ b/internal/core/landing/land_spotcheck_test.go @@ -336,9 +336,10 @@ func TestAMaintainersApprovedPullRequestInAutoModeIsRecorded(t *testing.T) { // The spot-check's observation of a landing is turned off for every test of // the package but the ones that count it: an observation reaches origin and // the beacon, which no other test here is about. -func init() { +var _ = func() bool { observeLanding = func(context.Context, spotcheck.Observed) string { return "" } -} + return true +}() // countObservations replaces the observation for the test with one that // counts and answers a note. From 15da44a3338b2b4c921b23eb740221d9fcbcb927 Mon Sep 17 00:00:00 2001 From: REPPL <77722411+REPPL@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:20:42 +0000 Subject: [PATCH 05/16] fix: mirror the spot-check row in the push-gate tripwire The interview's tripwire mirrors the pre-push hook's receipt-less rows, and its mirror test refused the new abcd-spotcheck row; it now lists it, with tracking cases for the branch. The hook test's own git commands run under gittest's hermetic environment, as the hermeticity audit requires. Refs: spc-2610301925429250 Refs: itd-2610301750162657 Assisted-by: Claude:claude-opus-5-5 --- internal/core/interview/treewatch.go | 4 +++- internal/core/interview/treewatch_gate_mirror_test.go | 1 + internal/surface/cli/githook_prepush_spotcheck_test.go | 6 ++++-- 3 files changed, 8 insertions(+), 3 deletions(-) diff --git a/internal/core/interview/treewatch.go b/internal/core/interview/treewatch.go index 709ee20117..0fe497a1a3 100644 --- a/internal/core/interview/treewatch.go +++ b/internal/core/interview/treewatch.go @@ -1150,8 +1150,10 @@ const maxRemoteListing = 4 << 20 // matched by segment after the remote's name and in any case; every row the // hook adds for a host connector's prefix ends in that segment // (scripts/cloud/connector.sh's WIP_PREFIX_RE), so the segment covers them. +// The spot-check's row names one branch, abcd-spotcheck, with no slash, and +// is matched here as the hook matches it, as a segment's beginning. // TestTheReceiptlessPrefixesMirrorThePrePushHook holds the two to one list. -var receiptlessPrefixes = []string{"abcd-reserved/", "abcd-status/"} +var receiptlessPrefixes = []string{"abcd-reserved/", "abcd-status/", "abcd-spotcheck"} // wipSegment is the segment receiptless_tracking treats as receipt-less // wherever it stands. diff --git a/internal/core/interview/treewatch_gate_mirror_test.go b/internal/core/interview/treewatch_gate_mirror_test.go index 9f98db685c..f2a9ee6892 100644 --- a/internal/core/interview/treewatch_gate_mirror_test.go +++ b/internal/core/interview/treewatch_gate_mirror_test.go @@ -95,6 +95,7 @@ func TestTheReceiptlessPrefixesMirrorThePrePushHook(t *testing.T) { "origin/abcd-status/me", "origin/x/abcd-status/me", "origin/abcd-reservedx", "origin/xabcd-reserved/y", "abcd-reserved/x", "origin/claude/abcd-wip/x", "origin/other/abcd-wip/x", "origin/x/ABCD-WIP", "origin/abcd-wipe/x", "origin/abcd-wip", "origin/claude/x", "origin/claude/abcd-wipx", + "origin/abcd-spotcheck", "origin/ABCD-Spotcheck", "origin/xabcd-spotcheck", } cmd := exec.Command(bash, "-c", script) cmd.Stdin = strings.NewReader(strings.Join(refs, "\n") + "\n") diff --git a/internal/surface/cli/githook_prepush_spotcheck_test.go b/internal/surface/cli/githook_prepush_spotcheck_test.go index 0e18c0fe47..3390a41ee1 100644 --- a/internal/surface/cli/githook_prepush_spotcheck_test.go +++ b/internal/surface/cli/githook_prepush_spotcheck_test.go @@ -6,6 +6,8 @@ import ( "path/filepath" "strings" "testing" + + "github.com/intentdriven/abcd/internal/gittest" ) // The committed pre-push hook's spot-check row (itd-2610301750162657, @@ -31,7 +33,7 @@ func (c *prePushCase) storeCommit(parent string, files ...storeFile) string { git := func(args ...string) string { cmd := exec.Command("git", args...) cmd.Dir = c.dir - cmd.Env = append(append([]string{}, c.env...), "GIT_INDEX_FILE="+index) + cmd.Env = append(gittest.Env(c.t), "GIT_INDEX_FILE="+index) out, err := cmd.CombinedOutput() if err != nil { c.t.Fatalf("git %v: %v\n%s", args, err, out) @@ -119,7 +121,7 @@ func TestPrePushGatesEveryOtherPushToTheStore(t *testing.T) { c := newPrePushCase(t) mktree := func(entry string) string { cmd := exec.Command("git", "mktree") - cmd.Dir, cmd.Env, cmd.Stdin = c.dir, c.env, strings.NewReader(entry+"\n") + cmd.Dir, cmd.Env, cmd.Stdin = c.dir, gittest.Env(t), strings.NewReader(entry+"\n") out, err := cmd.CombinedOutput() if err != nil { t.Fatalf("git mktree: %v\n%s", err, out) From 269c8afc4d02f4102641f1800c1a26fc413fa129 Mon Sep 17 00:00:00 2001 From: REPPL <77722411+REPPL@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:28:58 +0000 Subject: [PATCH 06/16] fix: draw each spot-check window from the round its close fixes A window's close is now read from the default branch's first-parent line alone, and its round is the first the beacon's chain publishes at or after that close, on the chain's genesis and period pinned beside its key. The round is asked for by number, a reply naming another is refused, and before it is published the observation says the window is not yet drawable. The cycle's id, round and draw are the same whoever draws and whenever. Every cycle read back is checked: its signature, its round against its close, its drawn lists against its populations, and a close no later than the reader's clock allows. One that fails is set aside and named, and its window is drawn again. Each machine keeps a high-water mark of the copy it last read in the home store, and a branch that no longer holds it is refused in one line, with no first window opened over it. Hand-backs and decisions join a population when they reach the branch, so a late one is drawn in the next window. A judgement counts only when it reads as the one its path names. The pre-push hook bounds each store file at the reader's size and a push at the writer's file count, a cycle may hold more than a record, and the spotcheck block is read at origin's default branch. The ruleset mirror for the store branch, the decision recording the rule, the ADR, the spec and the pages that describe the draw are updated with it. Refs: spc-2610301925429250 Refs: itd-2610301750162657 Assisted-by: Claude:claude-opus-5-5 --- .../brief/02-constraints/03-invariants.md | 11 +- .../development/brief/04-surfaces/38-land.md | 11 +- .../brief/05-internals/03-configuration.md | 11 +- ...the-spot-check-s-store-branch-is-pushed.md | 8 +- ...a-person-spot-checks-what-abcd-s-agents.md | 11 +- ...3430233-the-technical-facilitator-under.md | 6 + .abcd/work/rulesets/README.md | 15 + .abcd/work/rulesets/spotcheck-protection.json | 22 ++ .githooks/pre-push | 46 ++- commands/land.md | 23 +- internal/core/spotcheck/afterlanding.go | 156 +++++--- internal/core/spotcheck/afterlanding_test.go | 62 +-- internal/core/spotcheck/beacon.go | 76 +++- internal/core/spotcheck/beacon_test.go | 44 ++- internal/core/spotcheck/cycle.go | 363 ++++++++++++++---- internal/core/spotcheck/draw_test.go | 29 +- internal/core/spotcheck/groups.go | 23 +- internal/core/spotcheck/groups_test.go | 16 +- internal/core/spotcheck/mark.go | 143 +++++++ internal/core/spotcheck/size_test.go | 82 +++- internal/core/spotcheck/store.go | 31 +- internal/core/spotcheck/verify_test.go | 312 +++++++++++++++ internal/core/spotcheck/window.go | 78 ++-- internal/core/spotcheck/window_test.go | 80 +++- .../cli/githook_prepush_spotcheck_test.go | 63 ++- 25 files changed, 1416 insertions(+), 306 deletions(-) create mode 100644 .abcd/work/decisions/dcn-2611260013430233-the-technical-facilitator-under.md create mode 100644 .abcd/work/rulesets/spotcheck-protection.json create mode 100644 internal/core/spotcheck/mark.go create mode 100644 internal/core/spotcheck/verify_test.go diff --git a/.abcd/development/brief/02-constraints/03-invariants.md b/.abcd/development/brief/02-constraints/03-invariants.md index 72c15c45e6..2bcdf278e0 100644 --- a/.abcd/development/brief/02-constraints/03-invariants.md +++ b/.abcd/development/brief/02-constraints/03-invariants.md @@ -212,11 +212,12 @@ The following are non-negotiable invariants — any architectural choice that vi store as last fetched, from disk, and makes one push of the records this checkout holds that origin's copy lacks, or nothing when it holds none. Once the window has passed (or before the first window opens) it makes one - fetch of the store's branch, one fetch of the latest round of the drand - beacon over HTTPS from `api.drand.sh` (then `api2.drand.sh`, then - `api3.drand.sh` when one before cannot be reached), within ten seconds in - all, the landings reader's forge reads for the window, and one push of the - cycle, each tried once more after a fresh fetch when origin refuses it. + fetch of the store's branch, one fetch of the drand beacon's round that the + window's close fixes, asked by number over HTTPS from `api.drand.sh` (then + `api2.drand.sh`, then `api3.drand.sh` when one before cannot be reached), + within ten seconds in all and only once that round is published, the + landings reader's forge reads for the window, and one push of the cycle, + each tried once more after a fresh fetch when origin refuses it. Only typed fields leave the machine: a record's free text stays on its local copy. Setup (`abcd ahoy install`) downloads abcd only on a yes to the question diff --git a/.abcd/development/brief/04-surfaces/38-land.md b/.abcd/development/brief/04-surfaces/38-land.md index e1635aa75a..7488609e2d 100644 --- a/.abcd/development/brief/04-surfaces/38-land.md +++ b/.abcd/development/brief/04-surfaces/38-land.md @@ -466,9 +466,14 @@ local copy of the store (`refs/abcd/spotcheck`), with the mode's layer and whether a review receipt named the head. While the window has not passed, the observation reads the store as last fetched and pushes only records origin's branch `abcd-spotcheck` lacks. Once it has passed it fetches the branch, takes -one verified round of the drand quicknet beacon (signature checked against the -pinned key, ten seconds in all), draws by HMAC over the round's randomness, -and pushes the cycle over the tracking tip, tried once more after a refusal. +the verified round of the drand quicknet beacon that the window's close fixes +on the chain's pinned clock (asked by number once published, its signature +checked against the pinned key, ten seconds in all), draws by HMAC over the +round's randomness, and pushes the cycle over the tracking tip, tried once more +after a refusal. Every cycle read back is verified the same way and set aside +when it fails, and a branch that no longer holds this machine's high-water +mark is refused +([dcn-2611260013430233](../../../work/decisions/dcn-2611260013430233-the-technical-facilitator-under.md)). Only typed fields reach origin, and an observation that cannot draw writes nothing and leaves the landing proved. The branch takes no preflight receipt: the pre-push hook admits it by a row of its own diff --git a/.abcd/development/brief/05-internals/03-configuration.md b/.abcd/development/brief/05-internals/03-configuration.md index dced066051..5f19a1bcbf 100644 --- a/.abcd/development/brief/05-internals/03-configuration.md +++ b/.abcd/development/brief/05-internals/03-configuration.md @@ -849,7 +849,8 @@ may run to in this repository: a whole number from 16 to 200, 40 by default The `spotcheck` block sets the spot-check's window and its sample (`internal/core/spotcheck/config.go`, itd-2610301750162657), read through the -layered resolver, the repository layer last and winning. +layered resolver, the repository layer last and winning, at origin's default +branch as stored: a value only in the working tree sizes no draw. ```jsonc { @@ -862,9 +863,11 @@ layered resolver, the repository layer last and winning. ``` - **The first bound to pass closes the window.** A window spans everything since - the last cycle, and closes at the first landing observed once `window_days` - whole days have gone by or, when set, `window_changes` first-parent commits - have landed on the default branch. + the last cycle and closes as the default branch's first-parent line gives it: + `window_days` whole days after it began, once a commit was committed after + that moment, or, when set, at the `window_changes`-th commit, whichever comes + first on the line. The draw is made at the first landing observed after the + round that close fixes is published. - **`per_group` is the most a group draws.** The size halves, rounded up, after three closed cycles in a row found nothing, and is whole again after a finding. - **A nonsense value refuses.** A value out of bounds or not a whole number, or a diff --git a/.abcd/development/decisions/adrs/2611251806496719-the-spot-check-s-store-branch-is-pushed.md b/.abcd/development/decisions/adrs/2611251806496719-the-spot-check-s-store-branch-is-pushed.md index da9537c17f..ec480bec31 100644 --- a/.abcd/development/decisions/adrs/2611251806496719-the-spot-check-s-store-branch-is-pushed.md +++ b/.abcd/development/decisions/adrs/2611251806496719-the-spot-check-s-store-branch-is-pushed.md @@ -30,9 +30,12 @@ The push hook's receipt-less table gains a third row: the branch `abcd-spotcheck - it is a fast-forward of the branch, or its creation; - every commit it moves (`..` on an update, everything reachable from `` on a creation) has a tree holding nothing but regular, non-executable files, each at `window-open.json` or at a path of `.json` names under `handbacks/`, `decisions/`, `cycles/`, `items/` or `judgements/`, made of letters, digits, `.`, `_` and `-`; +- every file is within the store reader's own bound, 16 KiB, or 256 KiB for a cycle under `cycles/`, and the push adds or changes no more than 1,000 files, the most the store's writer puts in one push; - the walk read every commit in full, as the reservation check requires of a shallow clone. -A deletion of the branch is refused outright: the store is kept for ever. Any other push to the branch is gated as any branch is. The forge ruleset that blocks deletion and non-fast-forward pushes of `refs/heads/abcd-spotcheck` is the person's act, applied from a mirror under `.abcd/work/rulesets/` as every ruleset is. +A deletion of the branch is refused outright: the store is kept for ever. Any other push to the branch is gated as any branch is. The forge ruleset that blocks deletion and non-fast-forward pushes of `refs/heads/abcd-spotcheck` is the person's act, applied from its mirror, `.abcd/work/rulesets/spotcheck-protection.json`, as every ruleset is, before the first draw on any machine. + +Because the row admits content, abcd's reader never trusts what it reads there ([dcn-2611260013430233](../../../work/decisions/dcn-2611260013430233-the-technical-facilitator-under.md)). Every cycle is verified wherever it is read: its id is its close's, it starts where its window began, its close is no later than the reader's clock allows, its round is the one its close fixes on the chain's pinned clock, its signature verifies under the pinned key, and its drawn lists are the ones that round gives over its populations. A cycle that fails is set aside, named, and its window drawn afresh, so a hand-made or future-dated cycle can neither end a window nor stop a later draw. A window's close, and so its round and its draw, is read from the default branch's history alone, the same for every drawer at any moment. Each machine keeps a high-water mark of the last copy it verified, in the person's home store, and refuses a branch that no longer holds it, deleted or rewritten, opening no first window over it. Records join a population by their arrival on the branch, and a judgement counts only when it reads as the judgement of the item and role its path names. ## Alternatives Considered @@ -44,6 +47,7 @@ A deletion of the branch is refused outright: the store is kept for ever. Any ot ## Consequences - **Easier:** a landing's draw and its records reach `origin` from any machine whose hooks run, so the queue is one queue for every machine. -- **Harder:** the shape check judges paths and modes, never content: a push under the row can carry any JSON at a store path. abcd's reader is the guard on content, since it reads every file strictly and names one it cannot read; nothing on the branch is ever built, run or merged. +- **Harder:** the shape check judges paths, modes, sizes and the count, never content: a push under the row can carry any JSON at a store path, within the bounds. abcd's reader is the guard on content: it reads every file strictly, verifies every cycle, and names one it cannot read or verify; nothing on the branch is ever built, run or merged. +- **The residual:** whoever holds the person's push rights can still write a cycle that verifies over a population it chose, hold a record back until a window's draw is known, or write judgements that halve the next sample. Verification removes the free choice of round and of drawn list and makes every cycle recomputable; it cannot tell an agent from the person when both push with one credential. Who may judge is the review lane's to settle. - **The hook is a local-only check.** A push made where no hook runs is held only by the forge's ruleset, as for the other two rows. - **A new obligation:** a change to the store's folders changes this row's check in the same change. diff --git a/.abcd/development/specs/open/spc-2610301925429250-a-person-spot-checks-what-abcd-s-agents.md b/.abcd/development/specs/open/spc-2610301925429250-a-person-spot-checks-what-abcd-s-agents.md index 7da2a4d6d3..c9ca23a3f4 100644 --- a/.abcd/development/specs/open/spc-2610301925429250-a-person-spot-checks-what-abcd-s-agents.md +++ b/.abcd/development/specs/open/spc-2610301925429250-a-person-spot-checks-what-abcd-s-agents.md @@ -32,15 +32,15 @@ Grounding, read on 30 October 2026: 1. **The store: one branch on the shared remote, written only by appending files.** A new package `internal/core/spotcheck` keeps the spot-check's record on `refs/heads/abcd-spotcheck` on `origin`, tracked at `refs/remotes/origin/abcd-spotcheck`, with `claim`'s `push` and `fetch` exported for it (one refspec added to the fetch the calling verb already makes). The branch is an orphan whose tree holds four folders of small JSON files, each written once and never edited: - `window-open.json`: The commit and time the first window opened (written by the first check that finds no cycle, which draws nothing). - - `cycles/.json`: One per draw: the window (`from_commit`, `to_commit`, `from_time`, `to_time`, `closed_by` = `days` or `changes`, the observing site), the beacon (`url`, `chain_hash`, `round`, `signature`, `randomness`, `fetched_at`), the sample (`per_group` from the configuration, `size` applied, `why` = `full` or `halved`, the closed cycles counted), and per group the population's item keys (or, above 5,000 keys, the key range and the population's SHA-256) and the keys drawn. + - `cycles/.json`: One per draw: the window (`from_commit`, `to_commit`, `from_time`, `to_time`, `closed_by` = `days` or `changes`, `window` = the `days` and `changes` it was counted under, the observing site), the beacon (`url`, `chain_hash`, `round`, `signature`, `randomness`, `fetched_at`), the sample (`per_group` from the configuration, `size` applied, `why` = `full` or `halved`, the closed cycles counted), and per group the population's item keys (or, above 1,000 keys, the key range and the population's SHA-256) and the keys drawn, within 256 KiB, the most a cycle file may hold (a record holds 16 KiB at most). - `items//--.json`: One per drawn item: its group, its key, the roles it is for, and the whole of its state at the draw, copied in (the landings row, the promise, the outcome and the withheld verdicts, approach 6), so what a person later sees as `then` never depends on a later read of history or the forge. - `handbacks/-.json` and `decisions/-.json`: The drain's hand-backs and the automated facilitator's decisions (approach 2). - `judgements//--..json`: One per judgement (approach 7). The queue is derived: an item waits while a role it is for has no judgement file. Because every write is a new file keyed by item and role, two writers never conflict; a push `origin` rejects is retried once after a fetch, and a judgement whose key the fetch shows already on `origin` is dropped and the earlier one named. A push that fails offline leaves its commit on the local tracking copy, the sitting goes on, and the next push carries it; a sitting's end and the board say how many judgements have not reached `origin`. Why the shared remote and not a tier of the tree: The draw runs inside a landing, which has no tree to write into (`land` refuses a dirty tree, `landing/land.go:274`; a lane's worktree is removed at `landMerged`), and the landing on one machine must be seen by the facilitator and the product thinker on others, so a per-machine store under `~/.abcd.noindex/` would fragment the queue across whichever machines land. A committed `.abcd/work/spot-checks/` would dirty the observing worktree at every draw and send a hundred judgements through a pull request per sitting, through the very gates being checked. The remote branch is where abcd already keeps state every copy must see (reservations, announcements), under invariant 7's named-verb rule; the findings themselves become committed issues, the reviewed and durable trace, so a lost branch loses judgements but never a finding. A repository with no `origin` has no unattended landings to draw from; there the check and the verb refuse, naming the missing remote, and write nothing. 2. **Hand-backs and the automated facilitator's decisions are recorded as they happen.** The drain writes `handbacks/-.json` (issue, kind, `From`, `Route`, `Rule`, `Reason`, the lane's pull request if one was opened, the run id, the record blob) from `routeHandBack` (`loop/drain.go:1365`), and `decisions/-.json` (kind `drain-judgement`: issue, question, answer, kind, the route's model, the rule record, the reason) from `decideDrainJudgement` when `Route` is set (`loop/drain_decide.go:167`). The merge gate's two callers (`landing/land.go:1284`, `loop/land.go:898`) write `decisions/-pr.json` (kind `merge-gate`: pull request, head, the mode and its layer, the author's role, whether a receipt named the head, `Arm`, `Method`, `Why`) whenever the mode is `auto` and the author a maintainer, which is the case in which abcd is the facilitator and no person's approval was counted; a decision in `human` mode, or over a contributor's pull request, waits for a person and is not recorded here. Each file is committed on the local tracking copy at once and pushed with the next push its verb makes anyway (the tombstone, the lane's branch, the half-lease renewal, `land`'s own push), and at the drain's end; none adds a push of its own. `DrainRoute` gains `PR int` from the lane, and `renderDrainCounts` (`cli/drain.go:435`) gains the per-pull-request table the intent asks for: One line per pull request the run opened with its hand-back count and kinds, then the hand-backs with no pull request. -3. **The window and the trigger.** `.abcd/config.json` gains a `spotcheck` block, claimed through `layered` (`Claim("spotcheck", "window_days", "window_changes", "per_group")`): `window_days` (1 to 90, bundled default 7), `window_changes` (10 to 100,000, no default, 0 meaning unset), `per_group` (1 to 100, default 10). Either window may be set and the first to pass closes it; the repository layer is read last and wins, as the drain's pace keys are read. One function, `spotcheck.AfterLanding(root, now) Note`, is called from the three observing sites: `landMerged` after `ld.Merged` is set (`loop/land.go:1030`), `Land` when `Landed` or `mergedAt` reports the branch on the default branch (`landing/land.go:300`, `:315`), and the drain move after its fetch of the default branch (`loop/drain.go:447`). It reads the last cycle's `to_commit` and `to_time` from the branch as last fetched, counts `git rev-list --first-parent --count ..origin/` and compares `now` with `to_time`; when neither bound is passed it returns at once, having read two files and run one local git command and touched no network. Its return is a note for the run record or the verb's text, never an error, an outcome or a hold: a draw that refuses for any reason (beacon unreachable, forge unread, push rejected twice) leaves the window passed, writes nothing, and the next observed landing tries again. The window closes at the observing instant and spans everything since the last cycle, so a week with no landing is drawn at the next one and nothing falls between windows. -4. **The beacon and the draw.** `beacon.go` pins two constants: the quicknet chain hash `52db9ba70e0cc0f6eaf7803dd07447a1f5477735fd3f661792ba94600c84e971` and the chain's group public key, the 96-byte compressed G2 point `83cf0f2896adee7eb8b5f01fcad3912212c437e0073e911fb90022d3e760183c8c4b450b6a0a6c3ac6a5776a2d1064510d1fec758c921cc22b0e17e63aaf4bcb5ed66304de9cf809bd274ca73bab4af5a6e9c76a4bc09e76eae8991ef5ece45a` (both from the chain's `info` reply, read on 31 October 2026 and recorded in `2026-10-31-drand-beacon-verification-sota.md`). The draw fetches the chain's latest round, addressed by the pinned hash (`https://api.drand.sh//public/latest`), through `urlguard.NewDownload` pinned to `api.drand.sh` (falling back once to `api2.drand.sh`, then `api3.drand.sh`), ten seconds in all, body bounded at 4 KiB, and accepts only a positive `round` with a 96-hex `signature`; a reply that names a chain hash other than the pinned one is refused. abcd then verifies the signature itself, at pick time: the pinned key is unmarshalled into `bls.PublicKey[bls.KeyG2SigG1]` from `github.com/cloudflare/circl/sign/bls` (v1.6.5, pure Go, BSD-3-Clause), the message is SHA-256 of the round as a big-endian uint64, and `bls.Verify(&pk, msg[:], sig)` must hold; circl's built-in G1 domain separation tag is the one drand's `bls-unchained-g1-rfc9380` scheme signs under, so no tag is passed. The randomness is SHA-256 of the signature bytes, which abcd computes itself, and a reply that carries a `randomness` field must carry that value. A reply that is late, malformed or unreachable, or whose signature does not verify, refuses the draw alike: nothing is written, one line names the beacon and the round, the landing's outcome is unchanged. The dependency is the one this spec adds, with the product thinker's sign-off of 31 October 2026: the build runs `go get github.com/cloudflare/circl@v1.6.5` and `go mod tidy`, reports every line it adds to `go.mod` and `go.sum` (circl's own module requires only go-ristretto, x/crypto, and x/sys; which of those lines are new is known only when tidy runs), and lands the `ACKNOWLEDGEMENTS.md` entries for circl and for drand in that same change, since credit lands with the change that integrates a tool. `TestBeaconVerify` holds the published vector for round 1000 (signature `b44679b9a59af2ec876b1a6b1ad52ea9b1615fc3982b19576350f93447cb1125e342b73a8dd2bacbe47e4b6b63ed5e39`, randomness `fe290beca10872ef2fb164d2aa4442de4566183ec51c56ff3cd603d930e54fdd`) as its positive case and the same signature against round 1001 as its negative; the vector was not run against circl during the check, so the test's first run is that check, and a failure stops the build and is reported rather than loosened. The populations are read for the window: Groups `drain-landed` and `automatic-merges` from the landings reader's rows in `from_commit..to_commit` classed `drain` and `automatic` (every row the evidence cannot place with a person included, its decision 9; a `person-approved` row excluded, its decisions 7 and 8); groups `drain-hand-backs` and `facilitator-decisions` from the branch's `handbacks/` and `decisions/` files with `at` in `from_time..to_time`. A row whose approval the reader could not settle from history and reports as unread from the forge refuses the draw, so a person's approval is never drawn as unattended on a guess. An automatic merge's rule is `facilitator.mode: auto`, the requirement the gate's table holds; the review receipt itself stays in the local tier and is not recovered afterwards (itd-2610301850454860, decisions 6 and 7), so the reader names the mode's requirement and the item copies it. Each item's key is its merge commit or its file name; within a group the keys are sorted, each is given `HMAC-SHA256(randomness, cycle-id || group || key)`, and the `size` smallest are drawn. The same stored randomness and population give the same list, every item has a chance, and no agent can steer it: the value does not exist until the window has closed. The cycle record stores round, signature and chain hash, so the verification abcd made at the draw can be repeated by anyone later. The fetch is written into the documented meaning of `land`, `drain` and `implement step` in invariant 7 and their pages, so abcd still asks the network nothing on its own. +3. **The window and the trigger.** `.abcd/config.json` gains a `spotcheck` block, claimed through `layered` (`Claim("spotcheck", "window_days", "window_changes", "per_group")`): `window_days` (1 to 90, bundled default 7), `window_changes` (10 to 100,000, no default, 0 meaning unset), `per_group` (1 to 100, default 10). Either window may be set and the first to pass closes it; the repository layer is read last and wins, as the drain's pace keys are read, and it is read at origin's default branch as stored, never from the working tree, so an uncommitted value never sizes a draw. One function, `spotcheck.AfterLanding(root, now) Note`, is called from the three observing sites: `landMerged` after `ld.Merged` is set (`loop/land.go:1030`), `Land` when `Landed` or `mergedAt` reports the branch on the default branch (`landing/land.go:300`, `:315`), and the drain move after its fetch of the default branch (`loop/drain.go:447`). It reads the last verified cycle's `to_commit` and `to_time` from the branch as last fetched (approach 13) and reads the window's close from the default branch's first-parent line alone, one local git command: by days, the window closes at `to_time` plus `window_days` once a commit of the line was committed after that moment, and ends at the last commit committed before it; by changes, it closes at the `window_changes`-th commit of the line, at that commit's time; whichever comes first on the line closes it. When neither has, it returns at once and touches no network. Because the close is read from origin's own history, every checkout that draws a window finds the same `to_commit`, `to_time`, cycle id and round, whenever it looks. Its return is a note for the run record or the verb's text, never an error, an outcome or a hold: a draw that refuses for any reason (beacon unreachable, forge unread, push rejected twice) leaves the window passed, writes nothing, and the next observed landing tries again. The window spans everything since the last cycle, so a week with no landing is drawn at the next one and nothing falls between windows. +4. **The beacon and the draw.** `beacon.go` pins the chain: the quicknet chain hash `52db9ba70e0cc0f6eaf7803dd07447a1f5477735fd3f661792ba94600c84e971` and the chain's group public key, the 96-byte compressed G2 point `83cf0f2896adee7eb8b5f01fcad3912212c437e0073e911fb90022d3e760183c8c4b450b6a0a6c3ac6a5776a2d1064510d1fec758c921cc22b0e17e63aaf4bcb5ed66304de9cf809bd274ca73bab4af5a6e9c76a4bc09e76eae8991ef5ece45a` and its clock, genesis `1692803367` and period 3 seconds (all from the chain's `info` reply, read on 31 October 2026 and recorded in `2026-10-31-drand-beacon-verification-sota.md`). A window's round is fixed by its close on that clock: the first round published at or after `to_time`. Before that round is published the draw asks nothing and writes nothing and says the window is not yet drawable; after it, it asks for that round by number, addressed by the pinned hash (`https://api.drand.sh//public/`), through `urlguard.NewDownload` pinned to `api.drand.sh` (falling back once to `api2.drand.sh`, then `api3.drand.sh`), ten seconds in all, body bounded at 4 KiB, and accepts only a positive `round` with a 96-hex `signature`; a reply that names a chain hash other than the pinned one, or a round other than the one asked, is refused. abcd then verifies the signature itself, at pick time: the pinned key is unmarshalled into `bls.PublicKey[bls.KeyG2SigG1]` from `github.com/cloudflare/circl/sign/bls` (v1.6.3, pure Go, BSD-3-Clause), the message is SHA-256 of the round as a big-endian uint64, and `bls.Verify(&pk, msg[:], sig)` must hold; circl's built-in G1 domain separation tag is the one drand's `bls-unchained-g1-rfc9380` scheme signs under, so no tag is passed. The randomness is SHA-256 of the signature bytes, which abcd computes itself, and a reply that carries a `randomness` field must carry that value. A reply that is late, malformed or unreachable, or whose signature does not verify, refuses the draw alike: nothing is written, one line names the beacon and the round, the landing's outcome is unchanged. The dependency is the one this spec adds, with the product thinker's sign-off of 31 October 2026: the build runs `go get github.com/cloudflare/circl@v1.6.3` and `go mod tidy` (the version the module graph already required, which the technical facilitator kept over v1.6.5 on 25 November 2026), reports every line it adds to `go.mod` and `go.sum` (circl's own module requires only go-ristretto, x/crypto, and x/sys; which of those lines are new is known only when tidy runs), and lands the `ACKNOWLEDGEMENTS.md` entries for circl and for drand in that same change, since credit lands with the change that integrates a tool. `TestBeaconVerify` holds the published vector for round 1000 (signature `b44679b9a59af2ec876b1a6b1ad52ea9b1615fc3982b19576350f93447cb1125e342b73a8dd2bacbe47e4b6b63ed5e39`, randomness `fe290beca10872ef2fb164d2aa4442de4566183ec51c56ff3cd603d930e54fdd`) as its positive case and the same signature against round 1001 as its negative; the vector was not run against circl during the check, so the test's first run is that check, and a failure stops the build and is reported rather than loosened. The populations are read for the window: Groups `drain-landed` and `automatic-merges` from the landings reader's rows in `from_commit..to_commit` classed `drain` and `automatic` (every row the evidence cannot place with a person included, its decision 9; a `person-approved` row excluded, its decisions 7 and 8); groups `drain-hand-backs` and `facilitator-decisions` from the branch's `handbacks/` and `decisions/` files by arrival: every record origin's copy holds, with the records the draw carries, whose key no earlier verified cycle's population held, never by the time a record names, so a record that reaches origin after its window was drawn is drawn from in the next and every record is in exactly one population. A row whose approval the reader could not settle from history and reports as unread from the forge refuses the draw, so a person's approval is never drawn as unattended on a guess. An automatic merge's rule is `facilitator.mode: auto`, the requirement the gate's table holds; the review receipt itself stays in the local tier and is not recovered afterwards (itd-2610301850454860, decisions 6 and 7), so the reader names the mode's requirement and the item copies it. Each item's key is its merge commit or its file name; within a group the keys are sorted, each is given `HMAC-SHA256(randomness, cycle-id || group || key)`, and the `size` smallest are drawn. The same stored randomness and population give the same list, every item has a chance, and the moment of the draw chooses nothing: the round is fixed by the window's close and does not exist until then, so there is no draw to preview before it and none to retry for after. The cycle record stores round, signature and chain hash, so the verification abcd made at the draw can be repeated by anyone later. The fetch is written into the documented meaning of `land`, `drain` and `implement step` in invariant 7 and their pages, so abcd still asks the network nothing on its own. 5. **The sample size adapts over fully reviewed cycles only.** `size` is `per_group` unless the three most recent closed cycles, in window order, each have zero findings, when it is `ceil(per_group / 2)`, never below one; a closed cycle with any finding makes the next size full. A cycle is closed when every role slot of every item has a judgement; an open cycle is skipped in the count and counts as neither clean nor a finding. The cycle record names the cycles it counted. 6. **A card, never code.** `spotcheck.Card(item)` renders what a role sees, in plain text, from records alone: the landings row (class, rule by id and path, when, pull request number); the promise, which is the issue's text and remedy, or the spec's criteria, or, for the product thinker, the intent's press release and acceptance criteria; the outcome, which is the pull request's title and the record section of the body the loop composed (`prbody.go:61`), the `resolved_by` stamp and the changelog line where one exists; and for a hand-back the issue, the kind, the route, the clause of the rule that applied and the question whether the drain was right to hand it back; for a decision the question put, the answer given and the rule record. Every card ends with `then` and `now`: `then` is the item file's own copy, written at the draw and never re-read from history or the forge; `now` is read at the sitting from the default branch as last fetched: still on it, reverted by `` (the landings reader's revert trace), changed again by later first-parent commits touching the change's paths, the issue reopened, or the handed-back issue since resolved, by whom. A card never includes a diff, a file body or a test body; `TestCardCarriesNoCode` renders every fixture and refuses a fence, a `diff --git` line or a path with a line number. Withheld until the judgement is saved, though copied into the item file at the draw: the validators' verdicts the pull request body carries, the drain judge's reason on a judgement item, the gate's `Why` on a merge-gate item, and any reviewer's verdict; `show` and `next` leave them out and the card says `verdicts: shown after you judge`. 7. **The sitting.** `abcd spotcheck review [--as facilitator|human-facilitator|product-thinker]` (the role defaults from the mode file and is asked when unset) makes one fetch of the branch and the default branch, then walks the queue in window order, oldest cycle first, group order within a cycle, item order within a group, for the role's unjudged slots. Each item is put through `question.Ask` with the card as `Material`, the one question for its group (`Does the outcome match its spec?`, `Was the drain right to hand this back?`, `Was the decision right under its rule?`, `Does what came back match the intent?`) and the options `sound`, `wrong` and the decide-later option, a typed line for `why` on `wrong`; in a terminal through `ask.Terminal.Put`, one key per item; in a host session the page has the agent render `spotcheck next --json --as [--batch N]` and put the same question through the host's tool, then record the answer with `spotcheck judge sound|wrong --why "" --as `. Both routes end in the same judgement file (`verdict`, `why`, `role`, `answered_in`, `at`, `state_now`, the issue id on `wrong`), committed and pushed as it is made, so a sitting stopped at any item resumes at the first unjudged slot with nothing to restore. `later` moves the item to the end of this pass and writes nothing. A progress line reads `item 37 of 112, cycle 3 of 9`. After each saved judgement the withheld verdicts print, one line each, and the next card is already read. @@ -49,10 +49,11 @@ Grounding, read on 30 October 2026: 10. **The board and the verb's surface.** `boardOutput` gains `SpotCheck{Waiting, ByRole, OldestDays, Unpushed, Due}` computed from the branch as last fetched (disk only, nothing fetched), and `boardRows` a `spot-check` row: `37 wait (facilitator 30, product thinker 7), oldest 41 days`; the product view adds one line when items wait for the product thinker; `--json` carries it. `Due` says the window has passed and no landing has been observed since. The verb is new and top-level, `abcd spotcheck`, with sub-verbs `review`, `next`, `judge`, `show ` and `cycles`: no existing verb's documented meaning holds a review queue people work across months (`reflect` is one release's interview, `lab` one snapshot, `status` the hour's announcements, `landings` a read-only listing), and a sub-verb of `land` or `drain` would put the reader's verb under a writer's. It lands with its brief row (43, `04-surfaces/README.md`), its chapter `04-surfaces/43-spotcheck.md` with the `## Sub-verbs` table, its page `commands/spotcheck.md` (block `people`), its sentence in the `internal/core/surface` manifest, the regenerated snapshot, and the `spotcheck` block in `05-internals/03-configuration.md`. Invariant 7 gains the branch's fetch and push for `spotcheck`, and the beacon fetch and branch push for `land`, `drain` and `implement step`. 11. **Nothing waits for the queue.** `spotcheck` exports to `loop` and `landing` only `AfterLanding`, the two record writers of approach 2, and nothing that returns a hold, a count or a boolean; `mergeGate`, `DrainJudging`, `RunningUnattended` and the away mode's `Judge` are untouched. `TestNothingWaitsForTheQueue` lands a lane and plans a drain over a branch holding ten thousand unjudged items and asserts the same outcomes and no read of `items/` or `judgements/`. 12. **A model other than the writer's reviews every change.** Before a validator is dispatched (`loop/validate.go:594`, `:1003`), the loop compares the implementer's reported model (`ReceiptRecord.Model`, or its `Route.Model`) with the reviewer's resolved `ReviewClass.Model`, by `matrix.sameModel`'s normalisation; on a match it takes the next class, in the order `loop.Classes` gives (`research`, `top`, `default`, `small`), whose model in the resolved class map differs (amended 2026-11-10 by itd-2611101419006280: the classes were renamed and a person may set the whole map), and when none does the lane hands back as `stuck` with the reason `no reviewer model other than the writer's`. A host-run validator's return must name its model, as the implementer's receipt does; a return naming none is treated as the writer's. `ValidatorRun` gains `WriterModel` and `ReviewerModel`, the lane receipt and the composed pull request body name both, and `renderReview` (`cli/build.go:540`) shows them. +13. **A cycle read back is verified, never trusted, and the branch only moves forward** (dcn-2611260013430233). Wherever a cycle is read, at every observation and at the size's tally, it is checked: its id is its close's, it starts where its window began (the opening, then each verified cycle's end in window order), its close is its window's days or within the changes' bounds and no later than the reader's clock plus five minutes, its round is the one its close fixes, its signature verifies under the pinned key and its randomness is that signature's hash, its sample size is one the size rule gives, and each drawn list is the one that randomness gives over its listed population. A cycle that fails is set aside and named in the draw's note, is no window boundary, and its window is drawn afresh over its file, so a hand-made cycle, a future-dated one included, can neither end a window nor stop a later draw; the pre-push hook still admits it. Each machine keeps a high-water mark under `~/.abcd.noindex/spotcheck///mark.json`, one per repository and origin: the last copy of the branch it verified, the window's opening and the newest verified cycle. A copy that no longer holds them, the branch deleted or rewritten, is refused in one line: nothing is carried or drawn over it and no first window is opened. `.abcd/work/rulesets/spotcheck-protection.json` mirrors the ruleset the person applies against deletion and forced pushes. A judgement counts toward the size only when it reads as one: of this schema version, naming the `cycle`, `item` and `role` its path names, with a `verdict` of `sound` or `wrong`; an item counts only when it reads as the one drawn at its path. The pre-push hook bounds each file at the reader's own limit (16 KiB, a cycle 256 KiB) and a push at 1,000 files, the writer's own. What verification cannot stop is recorded with the decision: a holder of the person's push rights can still write a self-consistent cycle over a population it chose, or hold a record back until a draw is known. ### How each criterion is met -- **Seeded from a public value, stored, every item a chance, recomputable.** Approaches 1 and 4. Tests: `TestDrawIsDeterministic` (same cycle file, same list, across two runs and a shuffled population), `TestEveryItemCanBeDrawn` (over many fake randomness values every key of a 50-item group is drawn at least once), `TestBeaconUnreachableWritesNothing` (a refusing fake beacon: no cycle file, no item, the landing's `Merged` still set and exit 0), `TestBeaconVerify` (the round-1000 vector verifies under the pinned key and yields its published randomness; the same signature against round 1001 fails), `TestBeaconBadSignatureWritesNothing` (a fake beacon serving a round with a signature that does not verify, and one naming another chain hash: no cycle file, no item, one line naming the beacon and the round, the landing's `Merged` still set and exit 0). +- **Seeded from a public value, stored, every item a chance, recomputable.** Approaches 1 and 4. Tests: `TestDrawIsDeterministic` (same cycle file, same list, across two runs and a shuffled population), `TestEveryItemCanBeDrawn` (over many fake randomness values every key of a 50-item group is drawn at least once), `TestBeaconUnreachableWritesNothing` (a refusing fake beacon: no cycle file, no item, the landing's `Merged` still set and exit 0), `TestBeaconVerify` (the round-1000 vector verifies under the pinned key and yields its published randomness; the same signature against round 1001 fails), `TestBeaconBadSignatureWritesNothing` (a fake beacon serving a round with a signature that does not verify, and one naming another chain hash: no cycle file, no item, one line naming the beacon and the round, the landing's `Merged` still set and exit 0), `TestAStaleRoundIsRefused` (a beacon answering another round than the close fixes is refused), `TestADrawBeforeItsRoundSaysNotYetDrawable`, `TestAForgedCycleIsSetAsideAndRedrawn` (a cycle with a bad signature, the wrong round or the wrong list is named and its window drawn afresh), `TestAFutureDatedCycleDoesNotStopTheNextDraw`, `TestARewrittenBranchRefuses` (deleted or rewritten past the mark: one line, nothing carried or drawn, no first window), `TestALateRecordIsDrawnInTheNextWindow`. - **Groups, ten by default, half after three clean, full after a finding.** Approaches 3 to 5. Tests: `TestFourGroupsFromTheirSources` (rows classed `drain` and `automatic` and the branch's `handbacks/` and `decisions/` files; a `person-approved` row never drawn), `TestSizeHalvesAfterThreeClosedCleanCycles`, `TestSizeFullAfterAFinding`, `TestOpenCycleCountsAsNeither`, `TestPerGroupBounds` (0, 101 and a string refused with the key named). - **Never code; the right thing beside each item; verdicts after the judgement.** Approaches 6 and 7. Tests: `TestCardCarriesNoCode`, `TestCardPerRole` (facilitator sees spec and outcome or rule and decision, product thinker sees the intent, human facilitator sees only decision items a model took), `TestVerdictsShownOnlyAfterJudging` (the rendered card lacks the verdict text; the post-judgement text holds it). - **A finding files an issue naming item, group and rule; abcd never edits the rule.** Approach 8. Tests: `TestWrongFilesAnIssue` (the record names all three and the person's why), `TestFindingIsNeverDrainEligible`. @@ -78,7 +79,7 @@ Out of scope, recorded elsewhere: The landing classes, the admitting evidence wr 1. The store, the drain's hand-backs and judgements and the merge gate's decisions recorded as they happen, with hand-backs per pull request in the summary - packages: internal/core/spotcheck/store.go, internal/core/claim/remote.go, internal/core/implement/loop/drain.go, internal/core/implement/loop/drain_decide.go, internal/core/implement/loop/handback.go, internal/core/implement/loop/land.go, internal/core/landing/land.go, internal/core/landing/facilitator.go, internal/surface/cli/drain.go, commands/drain.md, .abcd/development/brief/04-surfaces/35-drain.md - tests: internal/core/spotcheck/store_test.go, internal/core/claim/remote_test.go, internal/core/implement/loop/drain_handbacks_perpr_test.go, internal/core/implement/loop/drain_spotcheck_records_test.go, internal/core/implement/loop/land_spotcheck_test.go, internal/core/landing/land_spotcheck_test.go, internal/surface/cli/drain_counts_surface_test.go -2. The window, the beacon and the draw at the three observing sites. This step waits for itd-2610301850454860 to ship, since its reader supplies two of the four groups; steps 1 and 4 do not. It opens by adding the one dependency (`go get github.com/cloudflare/circl@v1.6.5`, then `go mod tidy`), reports every line added to `go.mod` and `go.sum`, and runs `TestBeaconVerify` before anything else is written, so a vector that fails stops the step at once; the `ACKNOWLEDGEMENTS.md` entries for circl and drand land in this step's change. +2. The window, the beacon and the draw at the three observing sites. This step waits for itd-2610301850454860 to ship, since its reader supplies two of the four groups; steps 1 and 4 do not. It opens by adding the one dependency (`go get github.com/cloudflare/circl@v1.6.3`, then `go mod tidy`), reports every line added to `go.mod` and `go.sum`, and runs `TestBeaconVerify` before anything else is written, so a vector that fails stops the step at once; the `ACKNOWLEDGEMENTS.md` entries for circl and drand land in this step's change. - needs: 1 - packages: go.mod, go.sum, ACKNOWLEDGEMENTS.md, internal/core/spotcheck/config.go, internal/core/spotcheck/window.go, internal/core/spotcheck/beacon.go, internal/core/spotcheck/groups.go, internal/core/spotcheck/draw.go, internal/core/spotcheck/size.go, internal/core/implement/loop/land.go, internal/core/implement/loop/drain.go, internal/core/landing/land.go, commands/land.md, commands/build.md, commands/implement.md, .abcd/development/brief/04-surfaces/38-land.md, .abcd/development/brief/04-surfaces/27-implement.md, .abcd/development/brief/02-constraints/03-invariants.md, .abcd/development/brief/05-internals/03-configuration.md - tests: internal/core/spotcheck/config_test.go, internal/core/spotcheck/window_test.go, internal/core/spotcheck/beacon_test.go, internal/core/spotcheck/groups_test.go, internal/core/spotcheck/draw_test.go, internal/core/spotcheck/size_test.go, internal/core/implement/loop/land_spotcheck_test.go, internal/core/landing/land_spotcheck_test.go diff --git a/.abcd/work/decisions/dcn-2611260013430233-the-technical-facilitator-under.md b/.abcd/work/decisions/dcn-2611260013430233-the-technical-facilitator-under.md new file mode 100644 index 0000000000..5b7128f17f --- /dev/null +++ b/.abcd/work/decisions/dcn-2611260013430233-the-technical-facilitator-under.md @@ -0,0 +1,6 @@ +--- +id: dcn-2611260013430233 +slug: the-technical-facilitator-under +date: 2026-11-26 +--- +2026-11-26 — The technical facilitator, under facilitator.mode auto, ruled how the spot-check trusts its own store (itd-2610301750162657, adr-2611251806496719). A cycle read back from abcd-spotcheck is verified on every read and never trusted: its beacon signature under the pinned quicknet key, its round equal to the first round at or after its window's close on the chain's pinned genesis and period, its drawn lists recomputed from that randomness over its listed populations, and its close no later than the reader's clock plus five minutes. A cycle that fails is set aside, named in the draw's note, and its window is drawn afresh; the pre-push hook still admits it, and nothing reads it as true. A window's close is read from origin's default branch alone, so its round, its id and its draw are the same whoever draws it and whenever: a round not yet published is reported as not yet drawable and asked for no sooner, and there is no preview and no retry to choose a draw by. Each machine keeps a high-water mark of the last copy it verified in the person's home store; a branch that no longer holds it, deleted or rewritten, is refused in one line and no first window is opened over it, and .abcd/work/rulesets/spotcheck-protection.json mirrors the ruleset against deletion and forced pushes that the person applies. Hand-backs and decisions join a population by arrival on the branch, so a record that reaches origin after its window was drawn is drawn from in the next, and every record is in exactly one population. A judgement counts toward the size only when it reads as one, of this schema version, naming the cycle, item and role its path names, with a verdict of sound or wrong. Accepted as residual: a holder of the person's push rights can still write a self-consistent cycle over a population it chose, or hold a record back until a draw is known; the halving of the sample trusts every holder of push rights until the review lane settles who may judge; a window closed by changes takes its close from a committer time. The spotcheck block is read at origin's default branch, so an uncommitted value never sizes a draw. circl stays at v1.6.3, the version the module graph already required, as the facilitator ruled before; the spec's v1.6.5 is corrected to it. diff --git a/.abcd/work/rulesets/README.md b/.abcd/work/rulesets/README.md index e5a7672bc3..b8a12ac86e 100644 --- a/.abcd/work/rulesets/README.md +++ b/.abcd/work/rulesets/README.md @@ -61,6 +61,21 @@ in the tree rather than only a web console. second guard is abcd's own reader, built in step 3 of spc-2610150728396006 (C11): a status commit whose tree is not the empty tree is shown as doubtful, with that reason, and never rendered. +- `spotcheck-protection.json` — deletion and force-push protection for + `refs/heads/abcd-spotcheck`, the spot-check's store (itd-2610301750162657, + adr-2611251806496719). **No bypass actors**, and no creation rule, since the + first draw creates the branch. Cycles, items and judgements are added as + fast-forwards and the branch is kept for ever, so neither a deletion nor a + forced push has a use; the committed pre-push hook refuses both only for a + push made through the hooks. It must stand before the first draw on any + machine. It cannot tell an agent from the person when both push with one + credential, so it guards against removal and rewriting, never against an + addition; abcd's reader verifies every cycle it reads, and each machine's + mark refuses a branch that no longer holds what it last verified. Not yet + applied: the person applies it with + `gh api -X POST repos/intentdriven/abcd/rulesets --input + .abcd/work/rulesets/spotcheck-protection.json`, then refreshes the mirror + from the live ruleset as below and adds its id to the list there. - `no-history-rewriting.json` — force-push protection on every branch except `dependabot/**` and the merge queue's own `gh-readonly-queue/**` (iss-2611040337038931), so the forge refuses a forced push the hooks never diff --git a/.abcd/work/rulesets/spotcheck-protection.json b/.abcd/work/rulesets/spotcheck-protection.json new file mode 100644 index 0000000000..20c72422f5 --- /dev/null +++ b/.abcd/work/rulesets/spotcheck-protection.json @@ -0,0 +1,22 @@ +{ + "bypass_actors": [], + "conditions": { + "ref_name": { + "exclude": [], + "include": [ + "refs/heads/abcd-spotcheck" + ] + } + }, + "enforcement": "active", + "name": "spotcheck protection", + "rules": [ + { + "type": "deletion" + }, + { + "type": "non_fast_forward" + } + ], + "target": "branch" +} diff --git a/.githooks/pre-push b/.githooks/pre-push index 5340753748..3b77794e4d 100755 --- a/.githooks/pre-push +++ b/.githooks/pre-push @@ -110,8 +110,10 @@ # commits hold the store's small JSON files and nothing else. The # spotcheck_shape check admits a fast-forward (or the creation) whose # every commit holds only regular, non-executable files at the store's -# paths, read in full; anything else pushed to the branch is gated as any -# branch is, and a deletion is refused: the store is kept for ever. +# paths, each within the store reader's own bound, read in full, and that +# adds no more files than the store's writer puts in one push; anything +# else pushed to the branch is gated as any branch is, and a deletion is +# refused: the store is kept for ever. # # A commit is "already on a remote", and needs no receipt for that, only # when a remote-tracking ref outside every receipt-less prefix holds it. @@ -230,41 +232,59 @@ reservation_shape() { # "-". A path git quotes (one holding any other byte) never matches. spotcheck_path_re='^(window-open\.json|(handbacks|decisions|cycles|items|judgements)(/[A-Za-z0-9._-]+)+\.json)$' +# The store's bounds, the reader's and the writer's own (internal/core/spotcheck: +# maxRecordBytes, maxCycleBytes, maxPushFiles): the most bytes a file may hold, +# a cycle under cycles/ more since it lists its populations, and the most files +# one push may add or change. +spotcheck_max_bytes=16384 +spotcheck_max_cycle_bytes=262144 +spotcheck_max_files=1000 + # spotcheck_shape is the spot-check store's shape check, for the branch the # push names ($branch): the branch is abcd-spotcheck itself, the push is a # fast-forward (or a create), the walk reads the range in full, and every # commit it moves holds nothing but regular, non-executable files at store -# paths (spotcheck_path_re), no segment "." or "..". The range is everything -# new on an update and everything reachable on a create, so a commit of the +# paths (spotcheck_path_re), no segment "." or "..", each within its bound +# (spotcheck_max_bytes, spotcheck_max_cycle_bytes), and the push adds or +# changes no more than spotcheck_max_files files. The range is everything new +# on an update and everything reachable on a create, so a commit of the # product's history pushed to the branch walks into a tree holding other -# paths and is gated as any branch is. Only paths and modes are judged: the -# store's reader judges every file's content, and nothing on the branch is -# built, run or merged. +# paths and is gated as any branch is. Only paths, modes, sizes and the count +# are judged: the store's reader judges every file's content, and nothing on +# the branch is built, run or merged. spotcheck_shape() { - local remote_sha="$1" local_sha="$2" range commit commits listing line meta path + local remote_sha="$1" local_sha="$2" range commit commits listing line meta path changed + local mode type sha size limit [ "$branch" = "abcd-spotcheck" ] || return 1 if is_null_id "$remote_sha"; then range="$local_sha" + changed="$(git ls-tree -r --name-only --full-tree "$local_sha" 2>/dev/null)" || return 1 else git merge-base --is-ancestor "$remote_sha" "$local_sha" 2>/dev/null || return 1 range="$remote_sha..$local_sha" + changed="$(git diff-tree -r --name-only "$remote_sha" "$local_sha" 2>/dev/null)" || return 1 fi + [ "$(printf '%s' "$changed" | grep -c '')" -le "$spotcheck_max_files" ] || return 1 read_in_full "$range" || return 1 commits="$(git rev-list "$range" 2>/dev/null)" || return 1 for commit in $commits; do - listing="$(git ls-tree -r --full-tree "$commit" 2>/dev/null)" || return 1 + listing="$(git ls-tree -r -l --full-tree "$commit" 2>/dev/null)" || return 1 while IFS= read -r line; do [ -n "$line" ] || continue meta="${line%%$'\t'*}" path="${line#*$'\t'}" - case "$meta" in - "100644 blob "*) ;; - *) return 1 ;; - esac + read -r mode type sha size <<<"$meta" + [ "$mode $type" = "100644 blob" ] || return 1 + [[ "$sha" =~ ^[0-9a-f]{40}([0-9a-f]{24})?$ && "$size" =~ ^[0-9]{1,9}$ ]] || return 1 [[ "$path" =~ $spotcheck_path_re ]] || return 1 case "/$path/" in */./* | */../*) return 1 ;; esac + limit="$spotcheck_max_bytes" + case "$path" in + cycles/*) limit="$spotcheck_max_cycle_bytes" ;; + esac + [ "$size" -le "$limit" ] || return 1 done <<<"$listing" done } diff --git a/commands/land.md b/commands/land.md index d888f7d738..4a60169b65 100644 --- a/commands/land.md +++ b/commands/land.md @@ -342,14 +342,21 @@ spot-check (itd-2610301750162657), and the `landed` step's note carries what it did. While the window (`spotcheck.window_days`, seven days by default) has not passed, it pushes only the records this checkout holds that the store branch `abcd-spotcheck` on origin lacks, and asks nothing when it holds none. Once the -window has passed, it fetches the store branch and one round of the drand public -randomness beacon, checks the round's signature itself, draws up to -`spotcheck.per_group` items from each group of the work decided with no person -involved, and pushes the drawn items to the branch. Only typed fields reach -origin: a record's free text stays on the machine that wrote it. A draw that -cannot be made (the beacon unreachable or its signature wrong, the forge -unread, the push refused twice) writes nothing, says why, and leaves the -landing as proved; the next landing observed tries again. +window has passed, it fetches the store branch and the one round of the drand +public randomness beacon that the window's close fixes, checks the round's +signature itself, draws up to `spotcheck.per_group` items from each group of +the work decided with no person involved, and pushes the drawn items to the +branch. The window's close is read from the default branch's history, so the +draw is the same whoever makes it and whenever; until its round is published +the note says the window is not yet drawable. Every cycle already on the +branch is verified as it is read, and one that does not verify is named and +its window drawn again. Only typed fields reach origin: a record's free text +stays on the machine that wrote it. A draw that cannot be made (the beacon +unreachable, its signature wrong or another round than the one asked, the +forge unread, the push refused twice) writes nothing, says why, and leaves the +landing as proved; the next landing observed tries again. A store branch on +origin that no longer holds what this machine last verified there, deleted or +rewritten, is refused in one line, and nothing is written over it. **What `human` holds against.** The gate assumes agents keep the rules: it stops an agent merging by mistake, not one set on getting round it. The diff --git a/internal/core/spotcheck/afterlanding.go b/internal/core/spotcheck/afterlanding.go index 8cdcef2b36..d3d0f381e4 100644 --- a/internal/core/spotcheck/afterlanding.go +++ b/internal/core/spotcheck/afterlanding.go @@ -2,15 +2,16 @@ package spotcheck // afterlanding.go is the collection lane's one entry (spc-2610301925429250 // approaches 3 and 11): AfterLanding, called where abcd has just proved a -// landing. While the window has not passed it reads two files and runs one -// local git command, and reaches the network only to carry records this -// checkout holds that origin's copy, as last fetched, lacks. Once the window -// has passed it fetches the store's branch, the beacon's latest round, reads -// the window's landings, draws, and pushes the cycle with its items in one -// commit over origin's copy. Whatever it does, its answer is a note and -// never an error, an outcome or a hold: a draw that refuses for any reason -// leaves the window passed and writes nothing, and the next landing observed -// tries again. Nothing it does decides anything a landing or a drain does. +// landing. While the window has not passed it reads origin's copy as last +// fetched and the default branch's line, locally, and reaches the network +// only to carry records this checkout holds that origin's copy lacks. Once +// the window has closed and the round its close fixes is published, it +// fetches the store's branch and that round, reads the window's landings, +// draws, and pushes the cycle with its items in one commit over origin's +// copy. Whatever it does, its answer is a note and never an error, an +// outcome or a hold: a draw that refuses for any reason leaves the window +// passed and writes nothing, and the next landing observed tries again, to +// the same draw. Nothing it does decides anything a landing or a drain does. import ( "context" @@ -62,25 +63,29 @@ func AfterLanding(parent context.Context, o Observed) string { } return "spot-check: " + err.Error() + "; nothing was drawn" } + tip, err := defaultTip(ctx, o.Root, o.Default) + if err != nil { + return "spot-check: " + err.Error() + "; nothing was drawn" + } + // The spotcheck block is read at origin's default branch, as stored, and + // the machine's own layer, never from the working tree, so an uncommitted + // value never sizes a draw. roots, _ := layered.RootsFor(o.Root) + roots.RepoAt, roots.RepoAtName, roots.RepoAtAsStored = tip, "origin/"+o.Default, true cfg, err := readConfig(roots) if err != nil { return "spot-check: the spotcheck configuration cannot be read (" + redact(err) + "); nothing was drawn" } - tip, err := defaultTip(ctx, o.Root, o.Default) - if err != nil { - return "spot-check: " + err.Error() + "; nothing was drawn" - } - st, err := readWindow(ctx, o.Root) + st, err := readWindow(ctx, o.Root, o.Now) if err != nil { return "spot-check: " + err.Error() + "; nothing was drawn" } if st.open { - closedBy, err := closedNow(ctx, o.Root, cfg, st, tip, o.Now) + cl, err := windowClose(ctx, o.Root, cfg, st.from, st.fromTime, tip) if err != nil { return "spot-check: " + err.Error() + "; nothing was drawn" } - if closedBy == "" { + if cl.by == "" { pending, _, err := outbound(ctx, o.Root, st.files) if err != nil { return "spot-check: " + err.Error() @@ -90,10 +95,26 @@ func AfterLanding(parent context.Context, o Observed) string { } return carry(ctx, o.Root) } + if note := notYet(cl, o.Now); note != "" { + return note + } } return draw(ctx, o, cfg, tip) } +// notYet is the note for a window that has closed before the round its +// close fixes is published, "" once it is: nothing is asked of the beacon +// and nothing is written, and a landing observed after the round draws it, +// the same draw whoever makes it. +func notYet(cl closing, at time.Time) string { + r := roundAt(cl.at) + if !at.Before(roundTime(r)) { + return "" + } + return fmt.Sprintf("spot-check: the window that closed at %s is not yet drawable: its round %d of the beacon is published at %s", + cl.at.Format(time.RFC3339), r, roundTime(r).Format(time.RFC3339)) +} + // defaultTip is origin's default branch as this checkout last fetched it. func defaultTip(ctx context.Context, root, def string) (string, error) { if def == "" || strings.ContainsAny(def, " \t\n:^~?*[\\") || strings.HasPrefix(def, "-") { @@ -107,19 +128,6 @@ func defaultTip(ctx context.Context, root, def string) (string, error) { return tip, nil } -// closedNow is the bound the window st holds has passed by now, at tip. -func closedNow(ctx context.Context, root string, cfg Config, st windowState, tip string, at time.Time) (string, error) { - changes := 0 - if cfg.WindowChanges > 0 { - n, err := changesSince(ctx, root, st.from, tip) - if err != nil { - return "", err - } - changes = n - } - return windowClosedBy(cfg, st.fromTime, changes, at), nil -} - // carry pushes the records origin's copy lacks, with nothing drawn. func carry(ctx context.Context, root string) string { res, err := push(ctx, root) @@ -133,7 +141,11 @@ func carry(ctx context.Context, root string) string { } // draw is AfterLanding once the window may have passed: tried twice, the -// second time after a fresh fetch when origin rejected the first push. +// second time after a fresh fetch when origin rejected the first push. The +// window's close, its round and so its draw are fixed by the default +// branch's line and the chain's clock, so a second try, or another +// checkout's, draws the same items; nothing about the moment it runs +// chooses them. func draw(ctx context.Context, o Observed, cfg Config, tip string) string { var beacon *Beacon var last error @@ -141,7 +153,7 @@ func draw(ctx context.Context, o Observed, cfg Config, tip string) string { if _, err := fetchTracking(ctx, o.Root); err != nil { return "spot-check: " + redact(err) + "; nothing was drawn" } - st, err := readWindow(ctx, o.Root) + st, err := readWindow(ctx, o.Root, o.Now) if err != nil { return "spot-check: " + err.Error() + "; nothing was drawn" } @@ -149,22 +161,28 @@ func draw(ctx context.Context, o Observed, cfg Config, tip string) string { if err != nil { return "spot-check: " + err.Error() + "; nothing was drawn" } + // The records carried with a cycle leave room in the push for its + // items and itself; any beyond go with a later push, into a later + // window's population. + pending = pending[:min(len(pending), maxPushFiles-len(groupOrder)*maxPerGroup-1)] if !st.open { w, err := encodeFile("", WindowOpenFile, WindowOpen{SchemaVersion: SchemaVersion, Commit: tip, At: o.Now, Holder: Holder()}) if err != nil { return "spot-check: " + err.Error() } - if _, err := pushOver(ctx, o.Root, st.tracking, append(pending, w), "spotcheck: the first window opens"); err != nil { + commit, err := pushOver(ctx, o.Root, st.tracking, append(pending, w), "spotcheck: the first window opens") + if err != nil { last = err continue } - return "spot-check: the first window opened at " + tip[:12] + "; nothing is drawn until it passes" + _ = writeMark(ctx, o.Root, mark{Commit: commit, Opened: tip, OpenedAt: o.Now}) + return "spot-check: the first window opened at " + tip[:12] + "; nothing is drawn until it passes" + setAside(st) } - closedBy, err := closedNow(ctx, o.Root, cfg, st, tip, o.Now) + cl, err := windowClose(ctx, o.Root, cfg, st.from, st.fromTime, tip) if err != nil { return "spot-check: " + err.Error() + "; nothing was drawn" } - if closedBy == "" { + if cl.by == "" { // Another writer drew this window first. if len(pending) == 0 { return "" @@ -175,14 +193,18 @@ func draw(ctx context.Context, o Observed, cfg Config, tip string) string { } return fmt.Sprintf("spot-check: carried %d record(s) to %s", len(pending), Branch) } - if beacon == nil { - b, err := fetchBeacon(ctx, o.Now) + if note := notYet(cl, o.Now); note != "" { + return note + } + round := roundAt(cl.at) + if beacon == nil || beacon.Round != round { + b, err := fetchBeacon(ctx, round, o.Now) if err != nil { return "spot-check: " + err.Error() + "; nothing was drawn" } beacon = &b } - c, items, err := makeCycle(ctx, o, cfg, st, tip, closedBy, *beacon, pending) + c, items, err := makeCycle(ctx, o, cfg, st, cl, *beacon, pending) if err != nil { return "spot-check: " + err.Error() + "; nothing was drawn" } @@ -192,33 +214,53 @@ func draw(ctx context.Context, o Observed, cfg Config, tip string) string { return "spot-check: " + err.Error() + "; nothing was drawn" } files = append(files, cf) - if _, err := pushOver(ctx, o.Root, st.tracking, files, "spotcheck: cycle "+c.ID); err != nil { + commit, err := pushOver(ctx, o.Root, st.tracking, files, "spotcheck: cycle "+c.ID) + if err != nil { last = err continue } + st.cycles = append(st.cycles, c) + _ = writeMark(ctx, o.Root, st.mark(commit)) drawn := 0 for _, g := range c.Groups { drawn += len(g.Drawn) } - return fmt.Sprintf("spot-check: drew cycle %s (round %d of the beacon): %d item(s) for review", c.ID, beacon.Round, drawn) + return fmt.Sprintf("spot-check: drew cycle %s (round %d of the beacon): %d item(s) for review", c.ID, beacon.Round, drawn) + setAside(st) } return "spot-check: the push to " + Branch + " was refused twice (" + redact(last) + "); nothing was drawn, and the next landing tries again" } -// makeCycle draws the cycle closing st's window at tip: the populations of -// the window (from st.from exclusive to tip, from st.fromTime exclusive to -// o.Now), the size over the cycles before it, and an item file per drawn key. -// pending are the typed records this checkout carries in the same commit, -// read as origin's own. -func makeCycle(ctx context.Context, o Observed, cfg Config, st windowState, tip, closedBy string, b Beacon, pending []file) (Cycle, []file, error) { +// maxSetAside bounds the cycles a note names as set aside. +const maxSetAside = 3 + +// setAside is the note's tail naming the cycles of st that did not verify, +// "" for none. +func setAside(st windowState) string { + if len(st.unverified) == 0 { + return "" + } + named := st.unverified[:min(len(st.unverified), maxSetAside)] + out := "; " + strings.Join(named, "; ") + if more := len(st.unverified) - len(named); more > 0 { + out += fmt.Sprintf("; and %d more", more) + } + return out +} + +// makeCycle draws the cycle closing st's window at cl: the landings of the +// window (from st.from exclusive to cl.commit), the records origin's copy +// holds that no earlier verified cycle drew from, the size over the cycles +// before it, and an item file per drawn key. pending are the typed records +// this checkout carries in the same commit, read as origin's own. +func makeCycle(ctx context.Context, o Observed, cfg Config, st windowState, cl closing, b Beacon, pending []file) (Cycle, []file, error) { reader := registeredReader() if reader == nil { return Cycle{}, nil, errNoReader } var rows []LandingRow - if st.from != tip { + if st.from != cl.commit { var err error - if rows, err = reader(ctx, o.Root, st.from, tip); err != nil { + if rows, err = reader(ctx, o.Root, st.from, cl.commit); err != nil { return Cycle{}, nil, fmt.Errorf("the window's landings cannot be read: %s", redact(err)) } } @@ -246,7 +288,18 @@ func makeCycle(ctx context.Context, o Observed, cfg Config, st windowState, tip, ds = append(ds, namedDecision{name: f.name, d: d}) } } - groups, err := populations(rows, hbs, ds, st.fromTime, o.Now) + seen := map[string]map[string]bool{} + for _, c := range st.cycles { + for _, g := range c.Groups { + if seen[g.Group] == nil { + seen[g.Group] = map[string]bool{} + } + for _, k := range g.Population.Keys { + seen[g.Group][k] = true + } + } + } + groups, err := populations(rows, hbs, ds, seen) if err != nil { return Cycle{}, nil, err } @@ -259,8 +312,9 @@ func makeCycle(ctx context.Context, o Observed, cfg Config, st windowState, tip, if err != nil || len(randomness) != 32 { return Cycle{}, nil, errors.New("the beacon's randomness does not read") } - c := Cycle{SchemaVersion: SchemaVersion, ID: cycleID(o.Now, tip), FromCommit: st.from, ToCommit: tip, - FromTime: st.fromTime, ToTime: o.Now, ClosedBy: closedBy, Site: o.Site, Beacon: b, Draw: DrawRule, + c := Cycle{SchemaVersion: SchemaVersion, ID: cycleID(cl.at, cl.commit), FromCommit: st.from, ToCommit: cl.commit, + FromTime: st.fromTime, ToTime: cl.at, ClosedBy: cl.by, Window: CycleWindow{Days: cfg.WindowDays, Changes: cfg.WindowChanges}, + Site: o.Site, Beacon: b, Draw: DrawRule, Sample: Sample{PerGroup: cfg.PerGroup, Size: size, Why: why, Counted: counted}, Holder: Holder()} var items []file n := 0 diff --git a/internal/core/spotcheck/afterlanding_test.go b/internal/core/spotcheck/afterlanding_test.go index 6adeeeaf07..b8d28dedfb 100644 --- a/internal/core/spotcheck/afterlanding_test.go +++ b/internal/core/spotcheck/afterlanding_test.go @@ -103,15 +103,18 @@ func (c *drawCase) originFile(p string) string { return gitIn(c.t, c.bare, "show", BranchRef+":"+p) } -// land puts n first-parent commits on origin's main and fetches it. +// land puts n first-parent commits on origin's main, committed inside the +// first window, and fetches it. func (c *drawCase) land(n int) string { c.t.Helper() - for range n { - c.r.Commit("a landing") - } - c.r.Git("push", "-q", "origin", "HEAD:refs/heads/main") - c.r.Git("fetch", "-q", "origin") - return c.r.Git("rev-parse", "origin/main") + return c.landAt(n, w0.Add(time.Hour)) +} + +// closeWindow lands the commit, committed just after the first window's seven +// days, that closes it. +func (c *drawCase) closeWindow() { + c.t.Helper() + c.landAt(1, q1000.Add(time.Second)) } func TestFirstCheckOpensTheWindow(t *testing.T) { @@ -138,21 +141,21 @@ func TestFirstCheckOpensTheWindow(t *testing.T) { // says nothing. A record to carry is carried at the next observation. func TestWindowNotPassedDrawsNothingAndFetchesNothing(t *testing.T) { c := newDrawCase(t) - c.observe(at0) + c.observe(w0) tip := c.originTip() c.r.Git("remote", "set-url", "origin", filepath.Join(t.TempDir(), "gone.git")) - if note := c.observe(at0.Add(6 * 24 * time.Hour)); note != "" { + if note := c.observe(w0.Add(6 * 24 * time.Hour)); note != "" { t.Fatalf("an observation inside the window said %q", note) } if c.beacons != 0 || c.reads != 0 { t.Fatalf("inside the window the beacon was asked %d and the reader %d times", c.beacons, c.reads) } - write(t, c.r.Root(), hb(handBack("iss-1", at0.Add(time.Hour)))) - if note := c.observe(at0.Add(6 * 24 * time.Hour)); !strings.Contains(note, "not fetched") { + write(t, c.r.Root(), hb(handBack("iss-1", w0.Add(time.Hour)))) + if note := c.observe(w0.Add(6 * 24 * time.Hour)); !strings.Contains(note, "not fetched") { t.Fatalf("a record to carry with origin gone: note %q", note) } c.r.Git("remote", "set-url", "origin", c.bare) - if note := c.observe(at0.Add(6 * 24 * time.Hour)); !strings.Contains(note, "carried 1 record") { + if note := c.observe(w0.Add(6 * 24 * time.Hour)); !strings.Contains(note, "carried 1 record") { t.Fatalf("the record was not carried: %q", note) } if c.originTip() == tip || c.beacons != 0 { @@ -167,18 +170,19 @@ func TestWindowNotPassedDrawsNothingAndFetchesNothing(t *testing.T) { // cycle's end. func TestADrawAtAPassedWindow(t *testing.T) { c := newDrawCase(t) - c.observe(at0) + c.observe(w0) from := c.r.Git("rev-parse", "origin/main") to := c.land(3) for i := range 14 { c.rows = append(c.rows, row(fmt.Sprintf("%040x", i+1), ClassDrain)) } c.rows = append(c.rows, row(fmt.Sprintf("%040x", 100), ClassAutomatic), row(fmt.Sprintf("%040x", 101), "person-approved")) - h := handBack("iss-2", at0.Add(24*time.Hour)) + h := handBack("iss-2", w0.Add(24*time.Hour)) h.Reason = "the secret reason the drain wrote" - d := gateDecision(4, sha('f'), true, at0.Add(25*time.Hour)) + d := gateDecision(4, sha('f'), true, w0.Add(25*time.Hour)) write(t, c.r.Root(), Batch{HandBacks: []HandBack{h}, Decisions: []Decision{d}}) - at := at0.Add(8 * 24 * time.Hour) + c.closeWindow() + at := q1000.Add(time.Hour) note := c.observe(at) if !strings.Contains(note, "drew cycle") || !strings.Contains(note, "13 item(s)") { t.Fatalf("the draw's note is %q", note) @@ -186,7 +190,7 @@ func TestADrawAtAPassedWindow(t *testing.T) { if c.from != from || c.to != to { t.Fatalf("the reader read %s..%s; want %s..%s", c.from, c.to, from, to) } - id := cycleID(at, to) + id := cycleID(q1000, to) var cy Cycle if err := json.Unmarshal([]byte(c.originFile(CyclesDir+"/"+id+".json")), &cy); err != nil { t.Fatal(err) @@ -241,13 +245,14 @@ func TestBeaconUnreachableWritesNothing(t *testing.T) { } { t.Run(name, func(t *testing.T) { c := newDrawCase(t) - c.observe(at0) + c.observe(w0) c.land(1) c.rows = []LandingRow{row(sha('a'), ClassDrain)} - write(t, c.r.Root(), hb(handBack("iss-2", at0.Add(time.Hour)))) + write(t, c.r.Root(), hb(handBack("iss-2", w0.Add(time.Hour)))) + c.closeWindow() tip := c.originTip() c.beacon = reply - note := c.observe(at0.Add(8 * 24 * time.Hour)) + note := c.observe(q1000.Add(time.Hour)) if !strings.Contains(note, "beacon") || !strings.Contains(note, "nothing was drawn") { t.Fatalf("the refused draw's note is %q", note) } @@ -255,7 +260,7 @@ func TestBeaconUnreachableWritesNothing(t *testing.T) { t.Fatal("a refused draw moved origin's branch") } c.beacon = func() ([]byte, error) { return beaconReply("1000", vectorSignature, ""), nil } - if note := c.observe(at0.Add(8*24*time.Hour + time.Minute)); !strings.Contains(note, "drew cycle") { + if note := c.observe(q1000.Add(time.Hour + time.Minute)); !strings.Contains(note, "drew cycle") { t.Fatalf("the next observation did not draw: %q", note) } }) @@ -266,10 +271,11 @@ func TestBeaconUnreachableWritesNothing(t *testing.T) { // as the spec lists it. func TestBeaconBadSignatureWritesNothing(t *testing.T) { c := newDrawCase(t) - c.observe(at0) + c.observe(w0) + c.closeWindow() tip := c.originTip() c.beacon = func() ([]byte, error) { return beaconReply("999", vectorSignature, ""), nil } - note := c.observe(at0.Add(8 * 24 * time.Hour)) + note := c.observe(q1000.Add(time.Hour)) if !strings.Contains(note, "round 999") || !strings.Contains(note, "does not verify") || c.originTip() != tip { t.Fatalf("note %q, origin moved %v", note, c.originTip() != tip) } @@ -279,14 +285,15 @@ func TestBeaconBadSignatureWritesNothing(t *testing.T) { // it was, the draw refused, and the window passed. func TestRejectedPushLeavesNoCycle(t *testing.T) { c := newDrawCase(t) - c.observe(at0) + c.observe(w0) + c.closeWindow() tip := c.originTip() hooks := t.TempDir() if err := os.WriteFile(filepath.Join(hooks, "pre-push"), []byte("#!/bin/sh\nexit 1\n"), 0o755); err != nil { t.Fatal(err) } c.r.Git("config", "core.hooksPath", hooks) - note := c.observe(at0.Add(8 * 24 * time.Hour)) + note := c.observe(q1000.Add(time.Hour)) if !strings.Contains(note, "refused twice") || c.originTip() != tip { t.Fatalf("note %q; origin moved %v", note, c.originTip() != tip) } @@ -296,10 +303,11 @@ func TestRejectedPushLeavesNoCycle(t *testing.T) { // draws nothing. func TestDrawWithNoReaderIsRefused(t *testing.T) { c := newDrawCase(t) - c.observe(at0) + c.observe(w0) RegisterLandingsReader(nil) + c.closeWindow() tip := c.originTip() - if note := c.observe(at0.Add(8 * 24 * time.Hour)); !strings.Contains(note, "no landings reader") || c.originTip() != tip { + if note := c.observe(q1000.Add(time.Hour)); !strings.Contains(note, "no landings reader") || c.originTip() != tip { t.Fatalf("note %q", note) } } diff --git a/internal/core/spotcheck/beacon.go b/internal/core/spotcheck/beacon.go index a75425e6fe..a9513532c1 100644 --- a/internal/core/spotcheck/beacon.go +++ b/internal/core/spotcheck/beacon.go @@ -1,10 +1,12 @@ package spotcheck // beacon.go is the draw's seed (spc-2610301925429250 approach 4): one round -// of drand's quicknet chain, a public randomness beacon no agent can steer, -// fetched only once a window has closed and verified here, at the draw, -// under the chain's pinned public key. A round whose signature does not -// verify is no seed at all: the draw is refused and nothing is written. +// of drand's quicknet chain, a public randomness beacon, the round fixed by +// the window's close on the chain's pinned clock, asked for by number only +// once it is published, and verified under the chain's pinned public key at +// the draw and again wherever a cycle is read back. A round whose signature +// does not verify, or that is not the round the close fixes, is no seed at +// all: the draw is refused and nothing is written. import ( "bytes" @@ -18,6 +20,7 @@ import ( "io" "net/http" "net/url" + "strconv" "time" "github.com/cloudflare/circl/sign/bls" @@ -37,6 +40,30 @@ const ChainHash = "52db9ba70e0cc0f6eaf7803dd07447a1f5477735fd3f661792ba94600c84e // from the same info reply. const chainPoint = "83cf0f2896adee7eb8b5f01fcad3912212c437e0073e911fb90022d3e760183c8c4b450b6a0a6c3ac6a5776a2d1064510d1fec758c921cc22b0e17e63aaf4bcb5ed66304de9cf809bd274ca73bab4af5a6e9c76a4bc09e76eae8991ef5ece45a" +// The quicknet chain's clock, read from the same info reply and pinned with +// its hash and key: round 1 was published at chainGenesis (Unix seconds), and +// one round follows every chainPeriod. A window's round is fixed by this +// clock alone (roundAt), never by the moment a draw asks for it. +const ( + chainGenesis = 1692803367 + chainPeriod = 3 * time.Second +) + +// roundTime is the moment round r is published. +func roundTime(r uint64) time.Time { + return time.Unix(chainGenesis, 0).UTC().Add(time.Duration(r-1) * chainPeriod) +} + +// roundAt is the first round published at or after t: the round a window +// that closes at t is drawn from. +func roundAt(t time.Time) uint64 { + d := t.Sub(time.Unix(chainGenesis, 0)) + if d <= 0 { + return 1 + } + return uint64((d+chainPeriod-1)/chainPeriod) + 1 +} + // The beacon's bounds. const ( // BeaconTimeout bounds the beacon's fetch, every host it asks together. @@ -99,18 +126,19 @@ var beaconGet = func(ctx context.Context, rawURL string) ([]byte, error) { // the one failure on which the next host is asked. var errUnreachable = errors.New("unreachable") -// fetchBeacon is the chain's latest round, asked of each host in turn until -// one answers, within BeaconTimeout, and verified under the pinned key. A -// reply that is read and refused (over its bound, malformed, of another -// chain, a signature that does not verify) refuses the fetch: no other host -// is asked, since a host that answers wrongly is no reason to trust the next. -// Every refusal names the beacon, and the round where one was read. -func fetchBeacon(parent context.Context, now time.Time) (Beacon, error) { +// fetchBeacon is the chain's round, asked by number of each host in turn +// until one answers, within BeaconTimeout, and verified under the pinned key. +// A reply that is read and refused (over its bound, malformed, of another +// chain, a signature that does not verify, another round than the one asked) +// refuses the fetch: no other host is asked, since a host that answers +// wrongly is no reason to trust the next. Every refusal names the beacon, and +// the round where one was read. +func fetchBeacon(parent context.Context, round uint64, now time.Time) (Beacon, error) { ctx, cancel := context.WithTimeout(parent, BeaconTimeout) defer cancel() var last error for _, host := range beaconHosts { - u := "https://" + host + "/" + ChainHash + "/public/latest" + u := "https://" + host + "/" + ChainHash + "/public/" + strconv.FormatUint(round, 10) body, err := beaconGet(ctx, u) if err != nil { last = fmt.Errorf("%s: %w (%s)", host, errUnreachable, redact(err)) @@ -123,12 +151,36 @@ func fetchBeacon(parent context.Context, now time.Time) (Beacon, error) { if err != nil { return Beacon{}, fmt.Errorf("the beacon at %s: %w", host, err) } + if b.Round != round { + return Beacon{}, fmt.Errorf("the beacon at %s answered round %d when round %d was asked", host, b.Round, round) + } b.URL, b.FetchedAt = u, now.UTC().Truncate(time.Second) return b, nil } return Beacon{}, fmt.Errorf("the beacon could not be reached: %w", last) } +// verifyBeacon checks a beacon a cycle keeps, as read back: of the pinned +// chain, its signature that of its round under the pinned key, and its +// randomness the hash of that signature. +func verifyBeacon(b Beacon) error { + if b.ChainHash != ChainHash || b.Round == 0 { + return errors.New("its beacon is not a round of the pinned chain") + } + sig, err := sigBytes(b.Signature) + if err != nil { + return fmt.Errorf("its beacon's %w", err) + } + r, err := verifyRound(b.Round, sig) + if err != nil { + return fmt.Errorf("its round %d: %w", b.Round, err) + } + if b.Randomness != hex.EncodeToString(r[:]) { + return fmt.Errorf("its round %d carries a randomness that is not the hash of its signature", b.Round) + } + return nil +} + // beaconReplyFields are the fields of a reply the fetch reads; any other // field is ignored, since the reply is the beacon's to extend. type beaconReplyFields struct { diff --git a/internal/core/spotcheck/beacon_test.go b/internal/core/spotcheck/beacon_test.go index f9f9dc14e4..23e6a0bc9c 100644 --- a/internal/core/spotcheck/beacon_test.go +++ b/internal/core/spotcheck/beacon_test.go @@ -37,7 +37,7 @@ func TestBeaconVerify(t *testing.T) { } } -// beaconReply is a reply body as the chain's latest round is served. +// beaconReply is a reply body as the chain serves a round. func beaconReply(round, sig, randomness string) []byte { b := `{"round":` + round + `,"signature":"` + sig + `"` if randomness != "" { @@ -69,14 +69,14 @@ func TestBeaconFetchVerifiesTheRound(t *testing.T) { "api.drand.sh": func() ([]byte, error) { return beaconReply("1000", vectorSignature, vectorRandomness), nil }, }) now := time.Date(2026, 11, 25, 1, 2, 3, 0, time.UTC) - b, err := fetchBeacon(context.Background(), now) + b, err := fetchBeacon(context.Background(), 1000, now) if err != nil { t.Fatal(err) } if b.Round != vectorRound || b.Signature != vectorSignature || b.Randomness != vectorRandomness || b.ChainHash != ChainHash || !b.FetchedAt.Equal(now) { t.Fatalf("beacon = %+v", b) } - if b.URL != "https://api.drand.sh/"+ChainHash+"/public/latest" { + if b.URL != "https://api.drand.sh/"+ChainHash+"/public/1000" { t.Fatalf("the beacon names %s", b.URL) } } @@ -99,7 +99,7 @@ func TestBeaconReplyBounds(t *testing.T) { } { t.Run(name, func(t *testing.T) { serve(t, map[string]func() ([]byte, error){"api.drand.sh": func() ([]byte, error) { return body, nil }}) - if b, err := fetchBeacon(context.Background(), time.Now()); err == nil { + if b, err := fetchBeacon(context.Background(), 1000, time.Now()); err == nil { t.Fatalf("the reply was taken: %+v", b) } else if !strings.Contains(err.Error(), "beacon") { t.Fatalf("the refusal does not name the beacon: %v", err) @@ -118,7 +118,7 @@ func TestBeaconOtherChainRefused(t *testing.T) { serve(t, map[string]func() ([]byte, error){"api.drand.sh": func() ([]byte, error) { return []byte(`{"round":1000,"signature":"` + vectorSignature + `","chain_hash":"` + other + `"}`), nil }}) - if _, err := fetchBeacon(context.Background(), time.Now()); err == nil || !strings.Contains(err.Error(), "chain") { + if _, err := fetchBeacon(context.Background(), 1000, time.Now()); err == nil || !strings.Contains(err.Error(), "chain") { t.Fatalf("a reply of another chain was taken (err %v)", err) } } @@ -129,7 +129,7 @@ func TestBeaconRandomnessMustMatch(t *testing.T) { serve(t, map[string]func() ([]byte, error){"api.drand.sh": func() ([]byte, error) { return beaconReply("1000", vectorSignature, strings.Repeat("0", 64)), nil }}) - if _, err := fetchBeacon(context.Background(), time.Now()); err == nil || !strings.Contains(err.Error(), "randomness") { + if _, err := fetchBeacon(context.Background(), 1000, time.Now()); err == nil || !strings.Contains(err.Error(), "randomness") { t.Fatalf("a reply whose randomness is not its signature's hash was taken (err %v)", err) } } @@ -141,7 +141,7 @@ func TestBeaconHostFallbackOrder(t *testing.T) { asked := serve(t, map[string]func() ([]byte, error){ "api3.drand.sh": func() ([]byte, error) { return beaconReply("1000", vectorSignature, ""), nil }, }) - b, err := fetchBeacon(context.Background(), time.Now()) + b, err := fetchBeacon(context.Background(), 1000, time.Now()) if err != nil { t.Fatal(err) } @@ -162,12 +162,38 @@ func TestBeaconHostFallbackOrder(t *testing.T) { "api.drand.sh": func() ([]byte, error) { return beaconReply("1001", vectorSignature, ""), nil }, "api2.drand.sh": func() ([]byte, error) { return beaconReply("1000", vectorSignature, ""), nil }, }) - if _, err := fetchBeacon(context.Background(), time.Now()); err == nil || len(*asked) != 1 { + if _, err := fetchBeacon(context.Background(), 1000, time.Now()); err == nil || len(*asked) != 1 { t.Fatalf("a refused reply was followed by another host (asked %q, err %v)", *asked, err) } asked = serve(t, nil) - if _, err := fetchBeacon(context.Background(), time.Now()); err == nil || len(*asked) != 3 || !strings.Contains(err.Error(), "unreachable") { + if _, err := fetchBeacon(context.Background(), 1000, time.Now()); err == nil || len(*asked) != 3 || !strings.Contains(err.Error(), "unreachable") { t.Fatalf("no host answering was not refused naming why (asked %q, err %v)", *asked, err) } } + +// TestRoundAtTheChainsClock: a window's round is the first the chain +// publishes at or after its close, on the pinned genesis and period. +func TestRoundAtTheChainsClock(t *testing.T) { + at := roundTime(1000) + for when, want := range map[time.Time]uint64{at: 1000, at.Add(-time.Second): 1000, at.Add(-3 * time.Second): 999, at.Add(time.Second): 1001, + at.Add(7 * 24 * time.Hour): 202600, time.Unix(chainGenesis, 0): 1, time.Unix(0, 0): 1} { + if got := roundAt(when); got != want { + t.Errorf("roundAt(%s) = %d; want %d", when, got, want) + } + } + if at.Unix() != 1692806364 { + t.Fatalf("round 1000 is published at %d", at.Unix()) + } +} + +// TestFetchRefusesAnotherRound: a host that answers a verified round other +// than the one asked is refused, naming both. +func TestFetchRefusesAnotherRound(t *testing.T) { + serve(t, map[string]func() ([]byte, error){ + "api.drand.sh": func() ([]byte, error) { return beaconReply("1000", vectorSignature, vectorRandomness), nil }, + }) + if _, err := fetchBeacon(context.Background(), 202600, time.Now()); err == nil || !strings.Contains(err.Error(), "round 1000 when round 202600") { + t.Fatalf("another round was taken (err %v)", err) + } +} diff --git a/internal/core/spotcheck/cycle.go b/internal/core/spotcheck/cycle.go index 988fc3afda..a70ed5dba4 100644 --- a/internal/core/spotcheck/cycle.go +++ b/internal/core/spotcheck/cycle.go @@ -10,6 +10,7 @@ package spotcheck import ( "context" + "encoding/hex" "encoding/json" "errors" "fmt" @@ -52,8 +53,13 @@ const DrawRule = "each key of a group, sorted, is given HMAC-SHA256 keyed by the // maxListedKeys is the most keys a population lists whole: above it, the // cycle keeps the first and last key and the SHA-256 of the sorted keys, one -// per line. -const maxListedKeys = 5000 +// per line. Four groups listed whole stay within maxCycleBytes. +const maxListedKeys = 1000 + +// maxCycleBytes bounds one cycle file, on write and on read, as the pre-push +// hook bounds it: a cycle lists its populations, so it is allowed more than a +// record's maxRecordBytes. +const maxCycleBytes = 256 << 10 // WindowOpen is window-open.json: where and when the first window opened. type WindowOpen struct { @@ -72,6 +78,7 @@ type Cycle struct { FromTime time.Time `json:"from_time"` ToTime time.Time `json:"to_time"` ClosedBy string `json:"closed_by"` + Window CycleWindow `json:"window"` Site string `json:"site"` Beacon Beacon `json:"beacon"` Draw string `json:"draw"` @@ -80,6 +87,13 @@ type Cycle struct { Holder string `json:"holder,omitempty"` } +// CycleWindow is the window's bounds as the drawing checkout's configuration +// gave them: WindowDays, and WindowChanges, 0 when unset. +type CycleWindow struct { + Days int `json:"days"` + Changes int `json:"changes"` +} + // Sample is the size a cycle drew at and why. type Sample struct { PerGroup int `json:"per_group"` @@ -126,8 +140,10 @@ var ( cycleNameRe = regexp.MustCompile(`^` + CyclesDir + `/([0-9]{8}T[0-9]{6}Z-[0-9a-f]{12})\.json$`) ) -// cycleID is the id of a cycle closed at to over commit: its time first, so -// ids sort in window order. +// cycleID is the id of a cycle whose window closed at to and ends at commit: +// its close first, so ids sort in window order. Both are read from the +// default branch's line (windowClose), so every drawer of a window names its +// cycle alike, and the draw it keys is the same whenever it is made. func cycleID(to time.Time, commit string) string { return to.UTC().Format(stamp) + "-" + commit[:12] } @@ -138,29 +154,51 @@ func itemStem(number int, group, key string) string { return fmt.Sprintf("%03d-%s-%s", number, group, key) } -// windowState is the store's window as origin's copy holds it. +// windowState is the store's window as origin's copy holds it, every cycle +// verified as it is read. type windowState struct { // tracking is origin's copy as last fetched, "" when this checkout holds // none. tracking string files map[string]entry - // open says window-open.json or a cycle is there; from and fromTime are - // where the window now open began: the last cycle's end, else the - // window's opening. + // open says window-open.json is there; opened and openedAt are its + // opening, and from and fromTime are where the window now open began: + // the last verified cycle's end, else the opening. open bool + opened string + openedAt time.Time from string fromTime time.Time - // cycles are the ids of every cycle, in window order. - cycles []string + // cycles are the verified cycles, in window order: each starts where the + // one before it ended, the first at the opening. + cycles []Cycle + // unverified names each cycle file that is not among them, and why. + unverified []string } -// readWindow is the window as origin's copy, last fetched, holds it: a -// listing and at most one file read, all local. A copy that holds files the -// store does not write under the draw's names, or a cycle or opening that -// does not read, is an error: a window is never guessed. -func readWindow(ctx context.Context, root string) (windowState, error) { +// clockSkew is how far past the reader's clock a cycle's close may lie and +// still be read: a close beyond it was never drawn, whatever its file says. +const clockSkew = 5 * time.Minute + +// readWindow is the window as origin's copy, last fetched, holds it, read +// locally and checked against this machine's mark. Every cycle is verified +// (verifyCycle) and chained from the opening in window order; a cycle that +// fails either is set aside, named in unverified, and is no window boundary, +// so its window is drawn afresh. A copy that does not hold the mark's commit, +// its opening or its newest verified cycle is refused as rewritten. A copy +// that holds files the store does not write under the draw's names, or an +// opening that does not read, is an error: a window is never guessed. A copy +// that reads is kept as the new mark. +func readWindow(ctx context.Context, root string, now time.Time) (windowState, error) { tracking, err := storeRef(ctx, root, TrackingRef) - if err != nil || tracking == "" { + if err != nil { + return windowState{}, err + } + if err := holdsMark(ctx, root, tracking); err != nil || tracking == "" { + return windowState{}, err + } + m, marked, err := readMark(ctx, root) + if err != nil { return windowState{}, err } files, err := listFiles(ctx, root, tracking) @@ -168,23 +206,13 @@ func readWindow(ctx context.Context, root string) (windowState, error) { return windowState{}, err } st := windowState{tracking: tracking, files: files} + var ids []string for p := range files { if m := cycleNameRe.FindStringSubmatch(p); m != nil { - st.cycles = append(st.cycles, m[1]) + ids = append(ids, m[1]) } } - slices.Sort(st.cycles) - if n := len(st.cycles); n > 0 { - var c Cycle - if err := readJSON(ctx, root, files, CyclesDir+"/"+st.cycles[n-1]+".json", &c); err != nil { - return windowState{}, err - } - if c.ID != st.cycles[n-1] || !gitutil.IsFullSHA(c.ToCommit) || c.ToTime.IsZero() { - return windowState{}, fmt.Errorf("the spot-check's cycle %s does not read as one this package writes", st.cycles[n-1]) - } - st.open, st.from, st.fromTime = true, c.ToCommit, c.ToTime - return st, nil - } + slices.Sort(ids) if _, ok := files[WindowOpenFile]; ok { var w WindowOpen if err := readJSON(ctx, root, files, WindowOpenFile, &w); err != nil { @@ -193,34 +221,179 @@ func readWindow(ctx context.Context, root string) (windowState, error) { if !gitutil.IsFullSHA(w.Commit) || w.At.IsZero() { return windowState{}, errors.New("the spot-check's window-open.json does not read as one this package writes") } - st.open, st.from, st.fromTime = true, w.Commit, w.At + st.open, st.opened, st.openedAt, st.from, st.fromTime = true, w.Commit, w.At, w.Commit, w.At + } + if marked && m.Opened != "" && (m.Opened != st.opened || !m.OpenedAt.Equal(st.openedAt)) { + return windowState{}, rewritten("the window's opening (" + m.Opened[:12] + ")") + } + for _, id := range ids { + var c Cycle + err := readJSON(ctx, root, files, CyclesDir+"/"+id+".json", &c) + switch { + case err != nil: + err = errors.New("it does not read") + case !st.open: + err = errors.New("no window opened before it") + default: + err = verifyCycle(c, id, st.from, st.fromTime, now) + } + if err != nil { + st.unverified = append(st.unverified, "cycle "+id+" on origin does not verify ("+err.Error()+"), so it was set aside") + continue + } + st.cycles = append(st.cycles, c) + st.from, st.fromTime = c.ToCommit, c.ToTime + } + if marked && m.Cycle != "" && !slices.ContainsFunc(st.cycles, func(c Cycle) bool { return c.ID == m.Cycle }) { + return windowState{}, rewritten("the cycle " + m.Cycle) + } + if st.open && (!marked || m.Commit != tracking) { + // The mark is kept as a best effort: one this machine cannot write + // leaves the last one standing, which still refuses a branch + // rewritten past it. + _ = writeMark(ctx, root, st.mark(tracking)) } return st, nil } +// mark is st as the high-water mark keeps it, at the store's commit. +func (st windowState) mark(commit string) mark { + m := mark{Commit: commit, Opened: st.opened, OpenedAt: st.openedAt} + if n := len(st.cycles); n > 0 { + c := st.cycles[n-1] + m.Cycle, m.CycleFrom, m.CycleTo = c.ID, c.FromCommit, c.ToCommit + } + return m +} + +// verifyCycle checks a cycle read back from origin's copy as the cycle of +// the window that began at from (fromTime): named by its file and by its own +// close, starting where that window began, closing by a bound it names +// within the bounds' limits and no later than now allows, drawn from the +// round its close fixes, whose signature verifies under the pinned key, and +// whose every drawn list is the one that round's randomness gives over its +// population at its size. A population kept by its hash alone is checked by +// its count. What it cannot check, a population or a size a holder of push +// rights chose and recorded consistently, is the residual adr-2611251806496719 +// names. +func verifyCycle(c Cycle, id, from string, fromTime, now time.Time) error { + switch { + case c.ID != id || !gitutil.IsFullSHA(c.FromCommit) || !gitutil.IsFullSHA(c.ToCommit) || cycleID(c.ToTime, c.ToCommit) != id: + return errors.New("its id is not the one its close gives") + case c.FromCommit != from || !c.FromTime.Equal(fromTime): + return errors.New("it does not start where its window began") + case c.ToTime.Before(c.FromTime): + return errors.New("it closes before it opens") + case c.ToTime.After(now.Add(clockSkew)): + return errors.New("it closes after now") + } + switch c.ClosedBy { + case ClosedByDays: + if c.Window.Days < 1 || c.Window.Days > maxWindowDays || !c.ToTime.Equal(c.FromTime.Add(time.Duration(c.Window.Days)*24*time.Hour)) { + return errors.New("its close is not its window's days") + } + case ClosedByChanges: + if c.Window.Changes < minWindowChanges || c.Window.Changes > maxWindowChanges { + return errors.New("its window's changes are out of their bounds") + } + default: + return errors.New("it names no bound it closed by") + } + if err := verifyBeacon(c.Beacon); err != nil { + return err + } + if want := roundAt(c.ToTime); c.Beacon.Round != want { + return fmt.Errorf("its round %d is not round %d, which its close fixes", c.Beacon.Round, want) + } + s := c.Sample + if s.PerGroup < 1 || s.PerGroup > maxPerGroup || + !(s.Size == s.PerGroup && s.Why == SizeFull || s.Size == max((s.PerGroup+1)/2, 1) && s.Why == SizeHalved) { + return errors.New("its sample size is not one the size rule gives") + } + randomness, _ := hex.DecodeString(c.Beacon.Randomness) + if len(c.Groups) != len(groupOrder) { + return errors.New("it does not hold the four groups") + } + for i, g := range c.Groups { + p := g.Population + switch { + case g.Group != groupOrder[i]: + return errors.New("its groups are not the four in their order") + case p.Count <= maxListedKeys && (len(p.Keys) != p.Count || !slices.IsSorted(p.Keys) || len(slices.Compact(slices.Clone(p.Keys))) != p.Count): + return fmt.Errorf("its %s population does not list its keys", g.Group) + case p.Count <= maxListedKeys && !slices.Equal(g.Drawn, drawKeys(randomness, c.ID, g.Group, p.Keys, s.Size)): + return fmt.Errorf("its %s draw is not the one its round gives", g.Group) + case p.Count > maxListedKeys && (len(p.Keys) != 0 || len(g.Drawn) != min(s.Size, p.Count)): + return fmt.Errorf("its %s draw is not of its size", g.Group) + } + } + return nil +} + // readJSON decodes the store's file at p, strictly and within -// maxRecordBytes, into v; a file of another schema version is refused. +// maxRecordBytes (maxCycleBytes for a cycle), into v; a file of another +// schema version is refused. func readJSON(ctx context.Context, root string, files map[string]entry, p string, v any) error { e, ok := files[p] - if !ok || e.typ != "blob" || e.mode != "100644" || e.size > maxRecordBytes { + if !ok || e.typ != "blob" || e.mode != "100644" || e.size > fileBound(p) { return fmt.Errorf("the spot-check's %s cannot be read", p) } blobs, err := readBlobs(ctx, root, []entry{e}) if err != nil { return err } - if err := jsonstrict.Decode(blobs[0], v); err != nil { + return decodeStoreFile(p, blobs[0], v) +} + +// decodeStoreFile is data, the store's file at p, decoded strictly into v; +// a file of another schema version is refused. +func decodeStoreFile(p string, data []byte, v any) error { + if err := jsonstrict.Decode(data, v); err != nil { return fmt.Errorf("the spot-check's %s does not read: %s", p, redact(err)) } var head struct { SchemaVersion int `json:"schema_version"` } - if err := json.Unmarshal(blobs[0], &head); err != nil || head.SchemaVersion != SchemaVersion { + if err := json.Unmarshal(data, &head); err != nil || head.SchemaVersion != SchemaVersion { return fmt.Errorf("the spot-check's %s is of another schema version", p) } return nil } +// fileBound is the most bytes the store's file at p may hold: maxCycleBytes +// for a cycle, which lists its populations, and maxRecordBytes for any other. +func fileBound(p string) int { + if strings.HasPrefix(p, CyclesDir+"/") { + return maxCycleBytes + } + return maxRecordBytes +} + +// readMany is the content of each of paths that names a regular blob of the +// store within its bound, by path, read in one batch; a path that does not is +// left out. +func readMany(ctx context.Context, root string, files map[string]entry, paths []string) (map[string][]byte, error) { + var es []entry + var kept []string + for _, p := range paths { + if e, ok := files[p]; ok && e.typ == "blob" && e.mode == "100644" && e.size <= fileBound(p) { + es, kept = append(es, e), append(kept, p) + } + } + out := map[string][]byte{} + if len(es) == 0 { + return out, nil + } + blobs, err := readBlobs(ctx, root, es) + if err != nil { + return nil, err + } + for i, p := range kept { + out[p] = blobs[i] + } + return out, nil +} + // cycleTally is one cycle as the sample size reads it. type cycleTally struct { id string @@ -232,45 +405,79 @@ type cycleTally struct { // for the three closed ones it decides on. const maxTallied = 24 -// tallyCycles reads the newest cycles of st, newest first, until three closed -// ones are found or maxTallied are read: a cycle is closed when every role of -// every item it drew has a judgement file, and its findings are the -// judgements whose verdict is wrong. A cycle that drew nothing is closed and -// clean. +// The verdicts a judgement gives. +const ( + VerdictSound = "sound" + VerdictWrong = "wrong" +) + +// Judgement is the part of a judgement file, judgements//..json, the sample size reads: the cycle, item and role it +// judges, which its path must repeat, and its verdict. Its other fields are +// the review lane's. +type Judgement struct { + SchemaVersion int `json:"schema_version"` + Cycle string `json:"cycle"` + Item string `json:"item"` + Role string `json:"role"` + Verdict string `json:"verdict"` +} + +// tallyCycles reads the newest verified cycles of st, newest first, until +// three closed ones are found or maxTallied are read. A cycle's items are +// the ones its drawn lists name, at the paths the draw gave them; a cycle is +// closed when each of them reads as the item drawn there, with its group's +// role among its roles, and every role of each has a judgement that reads +// (readJudgement); its findings are the judgements whose verdict is wrong. A +// file that does not read leaves its cycle open, never closed and clean. A +// cycle that drew nothing is closed and clean. func tallyCycles(ctx context.Context, root string, st windowState) ([]cycleTally, error) { var out []cycleTally closed := 0 for i := len(st.cycles) - 1; i >= 0 && closed < 3 && len(out) < maxTallied; i-- { - id := st.cycles[i] - t := cycleTally{id: id, closed: true} - var items []string - judged := map[string]string{} - for p := range st.files { - if rest, ok := strings.CutPrefix(p, ItemsDir+"/"+id+"/"); ok && strings.HasSuffix(rest, ".json") { - items = append(items, p) - } - if rest, ok := strings.CutPrefix(p, JudgementsDir+"/"+id+"/"); ok && strings.HasSuffix(rest, ".json") { - judged[strings.TrimSuffix(rest, ".json")] = p + c := st.cycles[i] + t := cycleTally{id: c.ID, closed: true} + type slot struct{ stem, group, key string } + var slots []slot + var paths []string + for _, g := range c.Groups { + for _, k := range g.Drawn { + s := slot{stem: itemStem(len(slots)+1, g.Group, k), group: g.Group, key: k} + slots = append(slots, s) + paths = append(paths, ItemsDir+"/"+c.ID+"/"+s.stem+".json") } } - slices.Sort(items) - for _, p := range items { + items, err := readMany(ctx, root, st.files, paths) + if err != nil { + return nil, err + } + var judged []string + roles := map[string][]string{} + for n, s := range slots { var it Item - if err := readJSON(ctx, root, st.files, p, &it); err != nil { - return nil, err + data, ok := items[paths[n]] + if !ok || decodeStoreFile(paths[n], data, &it) != nil || it.Cycle != c.ID || it.Number != n+1 || it.Group != s.group || + it.Key != s.key || !slices.Contains(it.Roles, groupRole(s.group)) { + t.closed = false + continue } - stem := strings.TrimSuffix(p[len(ItemsDir+"/"+id+"/"):], ".json") + roles[s.stem] = it.Roles for _, role := range it.Roles { - jp, ok := judged[stem+"."+role] + judged = append(judged, JudgementsDir+"/"+c.ID+"/"+s.stem+"."+role+".json") + } + } + verdicts, err := readMany(ctx, root, st.files, judged) + if err != nil { + return nil, err + } + for _, s := range slots { + for _, role := range roles[s.stem] { + v, ok := readJudgement(verdicts[JudgementsDir+"/"+c.ID+"/"+s.stem+"."+role+".json"], c.ID, s.stem, role) if !ok { t.closed = false continue } - wrong, err := judgedWrong(ctx, root, st.files, jp) - if err != nil { - return nil, err - } - if wrong { + if v == VerdictWrong { t.findings++ } } @@ -283,29 +490,33 @@ func tallyCycles(ctx context.Context, root string, st windowState) ([]cycleTally return out, nil } -// judgedWrong reads a judgement's verdict: true when it is wrong. Only the -// verdict is read, so a judgement's other fields are the review lane's. -func judgedWrong(ctx context.Context, root string, files map[string]entry, p string) (bool, error) { - e := files[p] - if e.typ != "blob" || e.size > maxRecordBytes { - return false, fmt.Errorf("the spot-check's %s cannot be read", p) - } - blobs, err := readBlobs(ctx, root, []entry{e}) - if err != nil { - return false, err +// groupRole is the role every item of group is for. +func groupRole(group string) string { + if group == GroupFacilitatorDecisions { + return RoleHumanFacilitator } - var j struct { - Verdict string `json:"verdict"` + return RoleFacilitator +} + +// readJudgement is a judgement's verdict when data, its file, reads as one: +// one JSON object of no repeated key, of this schema version, naming the +// cycle, item and role its path names, with a verdict from the fixed set. +// Anything else, a missing file included, is no judgement. +func readJudgement(data []byte, cycle, item, role string) (string, bool) { + if data == nil || jsonstrict.NoDuplicateKeys(data) != nil { + return "", false } - if err := json.Unmarshal(blobs[0], &j); err != nil { - return false, fmt.Errorf("the spot-check's %s does not read", p) + var j Judgement + if err := json.Unmarshal(data, &j); err != nil || j.SchemaVersion != SchemaVersion || j.Cycle != cycle || j.Item != item || j.Role != role || + (j.Verdict != VerdictSound && j.Verdict != VerdictWrong) { + return "", false } - return j.Verdict == "wrong", nil + return j.Verdict, true } // encodeFile is v as the store's file at folder/name. func encodeFile(folder, name string, v any) (file, error) { - data, err := encode(v) + data, err := encodeWithin(v, fileBound(strings.TrimPrefix(folder+"/"+name, "/"))) if err != nil { return file{}, err } diff --git a/internal/core/spotcheck/draw_test.go b/internal/core/spotcheck/draw_test.go index 61bba474f9..106eb62899 100644 --- a/internal/core/spotcheck/draw_test.go +++ b/internal/core/spotcheck/draw_test.go @@ -60,7 +60,7 @@ func TestEveryItemCanBeDrawn(t *testing.T) { } } -// TestLargePopulationStoresRangeAndHash: a population of up to 5,000 keys is +// TestLargePopulationStoresRangeAndHash: a population of up to 1,000 keys is // kept whole and sorted; above it, by its first and last key and the hash of // the sorted keys. func TestLargePopulationStoresRangeAndHash(t *testing.T) { @@ -68,13 +68,30 @@ func TestLargePopulationStoresRangeAndHash(t *testing.T) { if small.Count != 2 || !slices.Equal(small.Keys, []string{"a", "b"}) || small.SHA256 != "" { t.Fatalf("population = %+v", small) } - keys := keysN(5001) + keys := keysN(maxListedKeys + 1) big := population(keys) sum := sha256.Sum256([]byte(strings.Join(keys, "\n") + "\n")) - if big.Count != 5001 || big.Keys != nil || big.First != keys[0] || big.Last != keys[5000] || big.SHA256 != hex.EncodeToString(sum[:]) { - t.Fatalf("population of 5,001 = count %d, %d keys, %s..%s, %s", big.Count, len(big.Keys), big.First, big.Last, big.SHA256) + if big.Count != maxListedKeys+1 || big.Keys != nil || big.First != keys[0] || big.Last != keys[maxListedKeys] || big.SHA256 != hex.EncodeToString(sum[:]) { + t.Fatalf("population of 1,001 = count %d, %d keys, %s..%s, %s", big.Count, len(big.Keys), big.First, big.Last, big.SHA256) } - if whole := population(keys[:5000]); len(whole.Keys) != 5000 { - t.Fatalf("a population of 5,000 kept %d keys whole", len(whole.Keys)) + if whole := population(keys[:maxListedKeys]); len(whole.Keys) != maxListedKeys { + t.Fatalf("a population of 1,000 kept %d keys whole", len(whole.Keys)) + } +} + +// TestACycleListingEveryGroupWholeFitsItsBound: four groups of the most keys +// a population lists whole, each key as long as a record's, encode within a +// cycle's bound, so a busy window never makes a draw that cannot be written. +func TestACycleListingEveryGroupWholeFitsItsBound(t *testing.T) { + keys := make([]string, maxListedKeys) + for i := range keys { + keys[i] = fmt.Sprintf("20261113T070000Z-iss-%016d", i) + } + c := Cycle{SchemaVersion: SchemaVersion, ID: cycleID(at0, sha('a')), Sample: Sample{Counted: []string{}}} + for _, g := range groupOrder { + c.Groups = append(c.Groups, GroupDraw{Group: g, Population: population(keys), Drawn: keys[:maxPerGroup]}) + } + if _, err := encodeFile(CyclesDir, c.ID+".json", c); err != nil { + t.Fatal(err) } } diff --git a/internal/core/spotcheck/groups.go b/internal/core/spotcheck/groups.go index 966ca55eca..593416da8e 100644 --- a/internal/core/spotcheck/groups.go +++ b/internal/core/spotcheck/groups.go @@ -173,11 +173,15 @@ func recordKey(name string) string { } // populations are the window's four groups: the reader's rows classed drain -// and automatic, and the hand-backs and decisions whose time falls in -// (from, to]. A row whose approval was not read from the forge refuses them -// all. Within a group, records of one key are one candidate, the record of -// the greatest file name copied. -func populations(rows []LandingRow, hbs []namedHandBack, ds []namedDecision, from, to time.Time) (map[string][]candidate, error) { +// and automatic, and the hand-backs and decisions origin's copy holds whose +// key no earlier verified cycle's population of their group held (seen, by +// group). Membership is by arrival on the store's branch, never by the time +// a record names, so a record that reaches origin after its window was drawn +// is drawn from in the next, and every record is in exactly one population. +// A row whose approval was not read from the forge refuses them all. Within +// a group, records of one key are one candidate, the record of the greatest +// file name copied. +func populations(rows []LandingRow, hbs []namedHandBack, ds []namedDecision, seen map[string]map[string]bool) (map[string][]candidate, error) { groups := map[string][]candidate{} for _, r := range rows { if r.ForgeUnread { @@ -196,13 +200,12 @@ func populations(rows []LandingRow, hbs []namedHandBack, ds []namedDecision, fro } groups[g] = append(groups[g], candidate{key: t.Commit, roles: roles, landing: &t}) } - in := func(at time.Time) bool { return at.After(from) && !at.After(to) } pickH := map[string]namedHandBack{} for _, h := range hbs { - if !in(h.h.At) { + k := recordKey(h.name) + if seen[GroupDrainHandBacks][k] { continue } - k := recordKey(h.name) if old, ok := pickH[k]; !ok || h.name > old.name { pickH[k] = h } @@ -213,10 +216,10 @@ func populations(rows []LandingRow, hbs []namedHandBack, ds []namedDecision, fro } pickD := map[string]namedDecision{} for _, d := range ds { - if !in(d.d.At) { + k := recordKey(d.name) + if seen[GroupFacilitatorDecisions][k] { continue } - k := recordKey(d.name) if old, ok := pickD[k]; !ok || d.name > old.name { pickD[k] = d } diff --git a/internal/core/spotcheck/groups_test.go b/internal/core/spotcheck/groups_test.go index 0b163e017d..c4a2a54ed7 100644 --- a/internal/core/spotcheck/groups_test.go +++ b/internal/core/spotcheck/groups_test.go @@ -23,18 +23,18 @@ func keysOf(cs []candidate) []string { } // TestFourGroupsFromTheirSources: rows classed drain and automatic and the -// hand-backs and decisions in the window make the four groups; a row of any -// other class, person-approved among them, and a record outside the window, -// are never drawn. +// hand-backs and decisions no earlier cycle drew from make the four groups; +// a row of any other class, person-approved among them, and a record an +// earlier cycle's population held, are never drawn. func TestFourGroupsFromTheirSources(t *testing.T) { - from, to := at0.Add(-time.Hour), at0.Add(time.Hour) + to := at0.Add(time.Hour) rows := []LandingRow{row(sha('a'), ClassDrain), row(sha('b'), ClassAutomatic, "itd-2610301750162657"), row(sha('c'), ClassAutomatic), row(sha('d'), "person-approved"), row(sha('e'), "person-push")} hIn, hOut := handBack("iss-1", at0), handBack("iss-2", to.Add(time.Second)) dIn := gateDecision(9, sha('f'), true, at0) groups, err := populations(rows, []namedHandBack{{name: fileOf(t, hIn).name, h: hIn}, {name: fileOf(t, hOut).name, h: hOut}}, - []namedDecision{{name: fileOf(t, dIn).name, d: dIn}}, from, to) + []namedDecision{{name: fileOf(t, dIn).name, d: dIn}}, map[string]map[string]bool{GroupDrainHandBacks: {recordKey(fileOf(t, hOut).name): true}}) if err != nil { t.Fatal(err) } @@ -66,7 +66,7 @@ func TestFourGroupsFromTheirSources(t *testing.T) { func TestUnreadApprovalRefusesTheDraw(t *testing.T) { r := row(sha('a'), ClassAutomatic) r.ForgeUnread = true - if _, err := populations([]LandingRow{row(sha('b'), ClassDrain), r}, nil, nil, at0, at0); err == nil || !strings.Contains(err.Error(), "forge") { + if _, err := populations([]LandingRow{row(sha('b'), ClassDrain), r}, nil, nil, nil); err == nil || !strings.Contains(err.Error(), "forge") { t.Fatalf("a row whose forge answer was not read was drawn from (err %v)", err) } } @@ -80,7 +80,7 @@ func TestDriftedRecordIsOneItem(t *testing.T) { if fa.name == fb.name { t.Fatal("the two records share a name") } - groups, err := populations(nil, []namedHandBack{{name: fa.name, h: a}, {name: fb.name, h: b}}, nil, at0.Add(-time.Second), at0) + groups, err := populations(nil, []namedHandBack{{name: fa.name, h: a}, {name: fb.name, h: b}}, nil, nil) if err != nil { t.Fatal(err) } @@ -105,7 +105,7 @@ func TestItemCopiesItsStateAtTheDraw(t *testing.T) { r.Lane, r.RulePath, r.Resolves = "Some Lane words", "/home/x/rule.md", []string{"iss-12", "not an id"} h := handBack("iss-4", at0) d := Decision{Kind: KindDrainJudgement, At: at0, Issue: "iss-5", Question: "may it?", Answer: "yes", Model: "claude-opus-4-8", Rule: "adr-2609291342092738", Reason: "because it said so"} - groups, err := populations([]LandingRow{r}, []namedHandBack{{name: fileOf(t, h).name, h: h}}, []namedDecision{{name: fileOf(t, d).name, d: d}}, at0.Add(-time.Second), at0) + groups, err := populations([]LandingRow{r}, []namedHandBack{{name: fileOf(t, h).name, h: h}}, []namedDecision{{name: fileOf(t, d).name, d: d}}, nil) if err != nil { t.Fatal(err) } diff --git a/internal/core/spotcheck/mark.go b/internal/core/spotcheck/mark.go new file mode 100644 index 0000000000..198bba1943 --- /dev/null +++ b/internal/core/spotcheck/mark.go @@ -0,0 +1,143 @@ +package spotcheck + +// mark.go is the store's high-water mark (adr-2611251806496719): this +// machine's own note, in the person's home store under +// ~/.abcd.noindex/spotcheck///mark.json ( the first +// sixteen hex digits of the SHA-256 of origin's URL, so a fork's checkout and +// upstream's keep marks of their own), of the last copy of the +// store's branch it read and verified, the window's opening and the newest +// verified cycle in it. The branch on origin is kept for ever and only ever +// moves forward, so a copy that no longer holds the mark's commit, opening or +// cycle was deleted or rewritten: the store refuses it in one line, draws +// nothing, carries nothing and opens no first window over it. Nothing in the +// checkout can move the mark, and a mark that cannot be read refuses as +// loudly as a rewritten branch. + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "strings" + "time" + + "github.com/intentdriven/abcd/internal/abcdhome" + "github.com/intentdriven/abcd/internal/core/claim" + "github.com/intentdriven/abcd/internal/core/jsonstrict" + "github.com/intentdriven/abcd/internal/fsutil" + "github.com/intentdriven/abcd/internal/gitutil" +) + +// markLeaf is the mark's file in its folder. +const markLeaf = "mark.json" + +// maxMarkBytes bounds the mark on read. +const maxMarkBytes = 4 << 10 + +// mark is the high-water mark: the store's commit last read and verified, +// the window's opening, and the newest verified cycle with its window. +type mark struct { + SchemaVersion int `json:"schema_version"` + Commit string `json:"commit"` + Opened string `json:"opened"` + OpenedAt time.Time `json:"opened_at"` + Cycle string `json:"cycle,omitempty"` + CycleFrom string `json:"cycle_from,omitempty"` + CycleTo string `json:"cycle_to,omitempty"` +} + +// errRewritten is the store's refusal of a branch that no longer holds what +// this machine last verified on it. +var errRewritten = errors.New("the spot-check branch on origin was rewritten") + +// rewritten is errRewritten naming what the branch no longer holds. +func rewritten(what string) error { + return fmt.Errorf("%w: it no longer holds %s this machine last verified there", errRewritten, what) +} + +// markFolder is the mark's folder for the repository at root and its +// origin, "" when the repository has no commit to key it on. +func markFolder(ctx context.Context, root string) (string, error) { + sha, err := gitutil.RootCommitContext(ctx, root) + if err != nil { + return "", fmt.Errorf("the spot-check's mark cannot be found: %s", redact(err)) + } + if !gitutil.IsFullSHA(sha) { + return "", nil + } + url, err := gitutil.RunCappedContext(ctx, root, 64<<10, "remote", "get-url", claim.Remote) + if err != nil || strings.TrimSpace(url) == "" { + return "", errors.New("the spot-check's mark cannot be found: origin's URL does not read") + } + sum := sha256.Sum256([]byte(strings.TrimSpace(url))) + return abcdhome.Rel("spotcheck", sha, hex.EncodeToString(sum[:8])), nil +} + +// readMark is the mark for the repository at root; ok is false when there is +// none. +func readMark(ctx context.Context, root string) (m mark, ok bool, err error) { + folder, err := markFolder(ctx, root) + if err != nil || folder == "" { + return mark{}, false, err + } + home, err := abcdhome.MachineHome() + if err != nil { + return mark{}, false, fmt.Errorf("the spot-check's mark cannot be found: %s", redact(err)) + } + data, refusal, err := fsutil.ReadHomeDeclaration(home, folder+"/"+markLeaf, maxMarkBytes) + if refusal == fsutil.DeclarationAbsent { + return mark{}, false, nil + } + if err != nil { + return mark{}, false, fmt.Errorf("the spot-check's mark %s cannot be read: %s", abcdhome.Display("spotcheck", "", "", markLeaf), redact(err)) + } + if err := jsonstrict.Decode(data, &m); err != nil || m.SchemaVersion != SchemaVersion || !gitutil.IsFullSHA(m.Commit) { + return mark{}, false, fmt.Errorf("the spot-check's mark %s does not read", abcdhome.Display("spotcheck", "", "", markLeaf)) + } + return m, true, nil +} + +// writeMark keeps m as the mark for the repository at root. +func writeMark(ctx context.Context, root string, m mark) error { + folder, err := markFolder(ctx, root) + if err != nil || folder == "" { + return err + } + home, err := abcdhome.MachineHome() + if err != nil { + return err + } + m.SchemaVersion = SchemaVersion + data, err := encode(m) + if err != nil { + return err + } + dir, err := fsutil.EnsureHomeScope(home, folder, abcdhome.DirMode) + if err != nil { + return err + } + defer dir.Close() + return fsutil.WriteFileAtomicInRoot(dir, markLeaf, data, abcdhome.FileMode) +} + +// holdsMark is nil when tracking, origin's copy as last fetched ("" for +// none), holds the mark's commit, and the refusal otherwise; nil too when +// this machine keeps no mark. +func holdsMark(ctx context.Context, root, tracking string) error { + m, ok, err := readMark(ctx, root) + if err != nil || !ok { + return err + } + if tracking == "" { + return rewritten("the copy (" + m.Commit[:12] + ")") + } + if tracking == m.Commit { + return nil + } + held, err := isAncestor(ctx, root, m.Commit, tracking) + if err != nil || !held { + return rewritten("the copy (" + m.Commit[:12] + ")") + } + return nil +} diff --git a/internal/core/spotcheck/size_test.go b/internal/core/spotcheck/size_test.go index 3888b4bcae..91b9d58dc8 100644 --- a/internal/core/spotcheck/size_test.go +++ b/internal/core/spotcheck/size_test.go @@ -3,6 +3,7 @@ package spotcheck import ( "fmt" "slices" + "strings" "testing" "time" ) @@ -42,35 +43,55 @@ func TestOpenCycleCountsAsNeither(t *testing.T) { } } -// TestSizeCountsClosedCyclesInWindowOrder: the tally reads the cycles origin's -// copy holds newest first by window, whatever order the files are listed in, -// and stops once three closed ones are found. -func TestSizeCountsClosedCyclesInWindowOrder(t *testing.T) { +// tallyCase is origin's copy holding n cycles of one drawn item each, for +// the tally: judge(i) is cycle i's judgement file, "" for none. +func tallyCase(t *testing.T, n int, judge func(i int, id, stem string) string) (windowState, []string, string) { + t.Helper() r, _ := originWithRemote(t) files := map[string]string{} base := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) var ids []string - for i := range 5 { + var cycles []Cycle + stem := itemStem(1, GroupDrainLanded, "k") + for i := range n { id := cycleID(base.Add(time.Duration(i)*24*time.Hour), fmt.Sprintf("%040x", i+1)) ids = append(ids, id) - files[CyclesDir+"/"+id+".json"] = encodeOrFail(t, Cycle{SchemaVersion: SchemaVersion, ID: id, ToCommit: fmt.Sprintf("%040x", i+1), ToTime: base}) + c := Cycle{SchemaVersion: SchemaVersion, ID: id, Groups: []GroupDraw{{Group: GroupDrainLanded, Drawn: []string{"k"}}, + {Group: GroupAutomaticMerges}, {Group: GroupDrainHandBacks}, {Group: GroupFacilitatorDecisions}}} + cycles = append(cycles, c) it := Item{SchemaVersion: SchemaVersion, Cycle: id, Number: 1, Group: GroupDrainLanded, Key: "k", Roles: []string{RoleFacilitator}} - files[ItemsDir+"/"+id+"/"+itemStem(1, GroupDrainLanded, "k")+".json"] = encodeOrFail(t, it) - // The newest (4) is open; 3 found a fault; 2, 1, 0 are clean. - if i < 4 { - verdict := "sound" - if i == 3 { - verdict = "wrong" - } - files[JudgementsDir+"/"+id+"/"+itemStem(1, GroupDrainLanded, "k")+"."+RoleFacilitator+".json"] = `{"verdict":"` + verdict + `"}` + "\n" + files[ItemsDir+"/"+id+"/"+stem+".json"] = encodeOrFail(t, it) + if j := judge(i, id, stem); j != "" { + files[JudgementsDir+"/"+id+"/"+stem+"."+RoleFacilitator+".json"] = j } } - setTracking(t, r, files) - st, err := readWindow(t.Context(), r.Root()) + tracking := setTracking(t, r, files) + listed, err := listFiles(t.Context(), r.Root(), tracking) if err != nil { t.Fatal(err) } - tallies, err := tallyCycles(t.Context(), r.Root(), st) + return windowState{tracking: tracking, files: listed, cycles: cycles, open: true}, ids, r.Root() +} + +// judgementOf is a judgement file as the review lane writes one. +func judgementOf(t *testing.T, id, stem, verdict string) string { + return encodeOrFail(t, Judgement{SchemaVersion: SchemaVersion, Cycle: id, Item: stem, Role: RoleFacilitator, Verdict: verdict}) +} + +// TestSizeCountsClosedCyclesInWindowOrder: the tally reads the verified +// cycles newest first by window, and stops once three closed ones are found. +func TestSizeCountsClosedCyclesInWindowOrder(t *testing.T) { + st, ids, root := tallyCase(t, 5, func(i int, id, stem string) string { + // The newest (4) is open; 3 found a fault; 2, 1, 0 are clean. + switch { + case i == 4: + return "" + case i == 3: + return judgementOf(t, id, stem, VerdictWrong) + } + return judgementOf(t, id, stem, VerdictSound) + }) + tallies, err := tallyCycles(t.Context(), root, st) if err != nil { t.Fatal(err) } @@ -82,3 +103,30 @@ func TestSizeCountsClosedCyclesInWindowOrder(t *testing.T) { t.Fatalf("size = %d %s; want full, after the finding in %s", size, why, ids[3]) } } + +// TestAJudgementThatDoesNotReadLeavesTheCycleOpen: a file at a judgement's +// path that does not read as that judgement (empty, a verdict alone, another +// item's, a verdict outside the set) is no judgement, so three such cycles +// never halve the sample. +func TestAJudgementThatDoesNotReadLeavesTheCycleOpen(t *testing.T) { + for name, body := range map[string]func(id, stem string) string{ + "empty object": func(string, string) string { return "{}\n" }, + "verdict only": func(string, string) string { return `{"verdict":"sound"}` + "\n" }, + "another item": func(id, _ string) string { return judgementOf(t, id, itemStem(2, GroupDrainLanded, "k"), VerdictSound) }, + "odd verdict": func(id, stem string) string { return judgementOf(t, id, stem, "fine") }, + "repeated key": func(id, stem string) string { + return strings.Replace(judgementOf(t, id, stem, VerdictWrong), `"verdict": "wrong"`, `"verdict": "wrong", "verdict": "sound"`, 1) + }, + } { + t.Run(name, func(t *testing.T) { + st, _, root := tallyCase(t, 3, func(_ int, id, stem string) string { return body(id, stem) }) + tallies, err := tallyCycles(t.Context(), root, st) + if err != nil { + t.Fatal(err) + } + if size, why, _ := sampleSize(10, tallies); size != 10 || why != SizeFull { + t.Fatalf("three cycles of judgements that do not read halved the sample: %d %s (%+v)", size, why, tallies) + } + }) + } +} diff --git a/internal/core/spotcheck/store.go b/internal/core/spotcheck/store.go index 8a29062554..74d636b357 100644 --- a/internal/core/spotcheck/store.go +++ b/internal/core/spotcheck/store.go @@ -149,6 +149,9 @@ const ( maxRecordBytes = 16 << 10 // maxListingBytes bounds one listing of the store's files. maxListingBytes = 8 << 20 + // maxPushFiles bounds the files one push adds or changes, as the pre-push + // hook bounds them. + maxPushFiles = 1000 // maxTries bounds the moves of the local copy one write makes when // another writer of the checkout moved it first. maxTries = 3 @@ -521,7 +524,10 @@ func (d Decision) file() (file, error) { // encode is v as a record file holds it: indented JSON and a newline, within // maxRecordBytes. -func encode(v any) ([]byte, error) { +func encode(v any) ([]byte, error) { return encodeWithin(v, maxRecordBytes) } + +// encodeWithin is encode within limit bytes. +func encodeWithin(v any, limit int) ([]byte, error) { var b bytes.Buffer enc := json.NewEncoder(&b) enc.SetEscapeHTML(false) @@ -529,8 +535,8 @@ func encode(v any) ([]byte, error) { if err := enc.Encode(v); err != nil { return nil, err } - if b.Len() > maxRecordBytes { - return nil, fmt.Errorf("the record is %d bytes, over the store's %d", b.Len(), maxRecordBytes) + if b.Len() > limit { + return nil, fmt.Errorf("the record is %d bytes, over the store's %d", b.Len(), limit) } return b.Bytes(), nil } @@ -1257,6 +1263,9 @@ func push(ctx context.Context, root string) (PushResult, error) { if err != nil { return PushResult{}, err } + // A backlog over one push's bound goes in turns, the rest with the + // next push. + todo = todo[:min(len(todo), maxPushFiles)] res := PushResult{Pushed: len(todo), Unreadable: unreadable} if len(todo) == 0 { return res, nil @@ -1281,14 +1290,23 @@ func push(ctx context.Context, root string) (PushResult, error) { // fetchTracking fetches the store's branch into its tracking ref and answers // the commit it names, "" when origin holds no such branch (a stale tracking -// ref is then removed). +// ref is then removed). A branch that no longer holds this machine's mark +// (holdsMark), gone from origin or rewritten there, is refused: the tracking +// ref of a gone branch is kept, and nothing is written over either. func fetchTracking(ctx context.Context, root string) (string, error) { found, err := claim.FetchBranch(ctx, root, BranchRef, TrackingRef) if err != nil { return "", fmt.Errorf("the spot-check's branch was not fetched: %w", stopped("push", err)) } if found { - return storeRef(ctx, root, TrackingRef) + tracking, err := storeRef(ctx, root, TrackingRef) + if err != nil { + return "", err + } + return tracking, holdsMark(ctx, root, tracking) + } + if err := holdsMark(ctx, root, ""); err != nil { + return "", err } if old, err := storeRef(ctx, root, TrackingRef); err == nil && old != "" { if _, err := storeGit(ctx, root, "", "", "update-ref", "-d", TrackingRef, old); err != nil { @@ -1358,6 +1376,9 @@ func outbound(ctx context.Context, root string, theirs map[string]entry) (todo [ // put right by the next fetch); a push that fails leaves nothing behind but // an unreferenced commit. func pushOver(ctx context.Context, root, tracking string, files []file, msg string) (string, error) { + if len(files) > maxPushFiles { + return "", fmt.Errorf("the push would carry %d files, over the %d one push of the spot-check's may", len(files), maxPushFiles) + } tree, err := treeWith(ctx, root, tracking, files) if err != nil { return "", err diff --git a/internal/core/spotcheck/verify_test.go b/internal/core/spotcheck/verify_test.go new file mode 100644 index 0000000000..733d4a352d --- /dev/null +++ b/internal/core/spotcheck/verify_test.go @@ -0,0 +1,312 @@ +package spotcheck + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "slices" + "strings" + "testing" + "time" +) + +// The rounds these tests draw at: quicknet publishes round r at genesis plus +// (r-1) periods, so round 1000 is the first round at or after q1000, and a +// window of seven days that closes there is followed by one closing at +// round 202600's time. +var ( + q1000 = time.Unix(1692806364, 0).UTC() + q202600 = q1000.Add(7 * 24 * time.Hour) + w0 = q1000.Add(-7 * 24 * time.Hour) +) + +// Round 202600 of the quicknet chain, as its hosts publish it. +const ( + vector202600Signature = "89abe9bbda7ccd0b01da48622e63dcc01738928427e959754bb5903f65dc27bacb210429158723dbcc1ea87381805ce6" + vector202600Randomness = "2272535ec3cbb11d4d66f3d8d00710d971fedda3f095018e21a1c8f627fc0bb7" +) + +// serveRounds answers a round asked by number with its published reply, and +// the latest round with the one *latest names. +func (c *drawCase) serveRounds(latest *string) { + c.t.Helper() + old := beaconGet + beaconGet = func(ctx context.Context, url string) ([]byte, error) { + c.beacons++ + round := url[strings.LastIndex(url, "/")+1:] + if round == "latest" { + round = *latest + } + switch round { + case "1000": + return beaconReply("1000", vectorSignature, vectorRandomness), nil + case "202600": + return beaconReply("202600", vector202600Signature, vector202600Randomness), nil + } + return nil, errors.New("answered 404 Not Found") + } + c.t.Cleanup(func() { beaconGet = old }) +} + +// landAt puts n first-parent commits on origin's main, committed a second +// apart from at, and fetches it. +func (c *drawCase) landAt(n int, at time.Time) string { + c.t.Helper() + for i := range n { + commitAt(c.t, c.r, at.Add(time.Duration(i)*time.Second)) + } + c.r.Git("push", "-q", "origin", "HEAD:refs/heads/main") + c.r.Git("fetch", "-q", "origin") + return c.r.Git("rev-parse", "origin/main") +} + +// plant commits files over origin's store branch, as a holder of push rights +// could with a plain push, and fetches nothing. +func (c *drawCase) plant(files map[string]string) string { + c.t.Helper() + commit := commitFilesAt(c.t, c.r, c.originTip(), files) + c.r.Git("push", "-q", "origin", commit+":"+BranchRef) + return commit +} + +// cycleJSON is a cycle record with the window bounds a cycle carries. +func cycleJSON(t *testing.T, c Cycle, days int) string { + t.Helper() + var m map[string]any + if err := json.Unmarshal([]byte(encodeOrFail(t, c)), &m); err != nil { + t.Fatal(err) + } + m["window"] = map[string]int{"days": days, "changes": 0} + b, err := json.MarshalIndent(m, "", " ") + if err != nil { + t.Fatal(err) + } + return string(b) + "\n" +} + +// newestCycle is origin's newest cycle record. +func (c *drawCase) newestCycle() Cycle { + c.t.Helper() + var names []string + for _, f := range remoteFiles(c.t, c.bare) { + if strings.HasPrefix(f, CyclesDir+"/") { + names = append(names, f) + } + } + slices.Sort(names) + if len(names) == 0 { + c.t.Fatal("origin holds no cycle") + } + var cy Cycle + var m map[string]json.RawMessage + body := c.originFile(names[len(names)-1]) + if err := json.Unmarshal([]byte(body), &m); err != nil { + c.t.Fatal(err) + } + delete(m, "window") + b, _ := json.Marshal(m) + if err := json.Unmarshal(b, &cy); err != nil { + c.t.Fatal(err) + } + return cy +} + +// openWindow opens the first window at at, over origin/main as it stands. +func (c *drawCase) openWindow(at time.Time) string { + c.t.Helper() + from := c.r.Git("rev-parse", "origin/main") + if note := c.observe(at); !strings.Contains(note, "first window opened") { + c.t.Fatalf("the first check said %q", note) + } + return from +} + +func hexKey(i int) string { return fmt.Sprintf("%040x", i) } + +// TestAForgedCycleIsSetAsideAndRedrawn: a cycle on origin for the window now +// closing whose signature does not verify, whose round is not the one the +// window's close fixes, or whose drawn list is not the one its randomness +// gives, is not read as the window's draw: the next observation names it as +// unverified and draws the window afresh, over its file. +func TestAForgedCycleIsSetAsideAndRedrawn(t *testing.T) { + sig202600, _ := hex.DecodeString(vector202600Signature) + badRand := sha256.Sum256(sig202600) + for name, edit := range map[string]func(*Cycle){ + "bad signature": func(cy *Cycle) { + cy.Beacon.Signature, cy.Beacon.Randomness = vector202600Signature, hex.EncodeToString(badRand[:]) + }, + "wrong round": func(cy *Cycle) { + cy.Beacon.Round, cy.Beacon.Signature, cy.Beacon.Randomness = 202600, vector202600Signature, vector202600Randomness + }, + "wrong list": func(cy *Cycle) { cy.Groups[0].Drawn = cy.Groups[0].Drawn[:2] }, + } { + t.Run(name, func(t *testing.T) { + latest := "1000" + c := newDrawCase(t) + c.serveRounds(&latest) + from := c.openWindow(w0) + to := c.landAt(3, w0.Add(time.Hour)) + keys := []string{hexKey(1), hexKey(2), hexKey(3)} + for _, k := range keys { + c.rows = append(c.rows, row(k, ClassDrain)) + } + c.closeWindow() + id := cycleID(q1000, to) + randomness, _ := hex.DecodeString(vectorRandomness) + drawn := drawKeys(randomness, id, GroupDrainLanded, keys, 10) + forged := Cycle{SchemaVersion: SchemaVersion, ID: id, FromCommit: from, ToCommit: to, FromTime: w0, ToTime: q1000, + ClosedBy: ClosedByDays, Site: SiteLane, Draw: DrawRule, + Beacon: Beacon{URL: "https://api.drand.sh/" + ChainHash + "/public/1000", ChainHash: ChainHash, Round: 1000, + Signature: vectorSignature, Randomness: vectorRandomness, FetchedAt: q1000}, + Sample: Sample{PerGroup: 10, Size: 10, Why: SizeFull, Counted: []string{}}, + Groups: []GroupDraw{{Group: GroupDrainLanded, Population: Population{Count: 3, Keys: keys}, Drawn: drawn}, + {Group: GroupAutomaticMerges, Population: Population{}, Drawn: []string{}}, + {Group: GroupDrainHandBacks, Population: Population{}, Drawn: []string{}}, + {Group: GroupFacilitatorDecisions, Population: Population{}, Drawn: []string{}}}} + edit(&forged) + c.plant(map[string]string{CyclesDir + "/" + id + ".json": cycleJSON(t, forged, 7)}) + note := c.observe(q1000.Add(time.Hour)) + if !strings.Contains(note, "drew cycle "+id) || !strings.Contains(note, id+" on origin does not verify") { + t.Fatalf("the observation over a forged cycle said %q", note) + } + cy := c.newestCycle() + if cy.ID != id || cy.Beacon.Round != 1000 || cy.Beacon.Signature != vectorSignature || len(cy.Groups[0].Drawn) != 3 { + t.Fatalf("origin's cycle after the redraw is %+v", cy) + } + }) + } +} + +// TestAFutureDatedCycleDoesNotStopTheNextDraw: a cycle whose window closes +// past now and the clock's allowance is no window boundary: the window it +// claims to end still closes on time and is drawn. +func TestAFutureDatedCycleDoesNotStopTheNextDraw(t *testing.T) { + latest := "1000" + c := newDrawCase(t) + c.serveRounds(&latest) + from := c.openWindow(w0) + far := time.Date(9999, 12, 31, 23, 59, 59, 0, time.UTC) + id := "99991231T235959Z-000000000000" + forged := Cycle{SchemaVersion: SchemaVersion, ID: id, FromCommit: from, ToCommit: strings.Repeat("0", 40), FromTime: w0, ToTime: far, + ClosedBy: ClosedByDays, Site: SiteLane, Draw: DrawRule, + Beacon: Beacon{ChainHash: ChainHash, Round: 1000, Signature: vectorSignature, Randomness: vectorRandomness}, + Sample: Sample{PerGroup: 10, Size: 10, Why: SizeFull, Counted: []string{}}} + c.plant(map[string]string{CyclesDir + "/" + id + ".json": cycleJSON(t, forged, 7)}) + c.closeWindow() + note := c.observe(q1000.Add(time.Hour)) + if !strings.Contains(note, "drew cycle") || !strings.Contains(note, id+" on origin does not verify") { + t.Fatalf("the observation over a future-dated cycle said %q", note) + } +} + +// TestAStaleRoundIsRefused: a beacon that answers another round than the one +// the window's close fixes is refused, and nothing is drawn. +func TestAStaleRoundIsRefused(t *testing.T) { + c := newDrawCase(t) + old := beaconGet + beaconGet = func(ctx context.Context, url string) ([]byte, error) { + c.beacons++ + return beaconReply("1000", vectorSignature, vectorRandomness), nil + } + t.Cleanup(func() { beaconGet = old }) + c.openWindow(q1000) + c.landAt(1, q202600.Add(time.Second)) + tip := c.originTip() + note := c.observe(q202600.Add(time.Hour)) + if !strings.Contains(note, "nothing was drawn") || !strings.Contains(note, "202600") || !strings.Contains(note, "round 1000") { + t.Fatalf("a stale round's note is %q", note) + } + if c.originTip() != tip { + t.Fatal("a stale round moved origin's branch") + } +} + +// TestADrawBeforeItsRoundSaysNotYetDrawable: a window that has closed before +// the round its close fixes is published asks no beacon and writes nothing, +// and says it is not yet drawable; once the round is out it draws. +func TestADrawBeforeItsRoundSaysNotYetDrawable(t *testing.T) { + latest := "1000" + c := newDrawCase(t) + c.serveRounds(&latest) + c.openWindow(w0.Add(-2 * time.Second)) + c.landAt(1, q1000.Add(-time.Second)) + tip := c.originTip() + note := c.observe(q1000.Add(-time.Second)) + if !strings.Contains(note, "not yet drawable") || c.beacons != 0 || c.originTip() != tip { + t.Fatalf("a draw before its round: note %q, beacon asked %d times, origin moved %v", note, c.beacons, c.originTip() != tip) + } + if note := c.observe(q1000.Add(time.Second)); !strings.Contains(note, "drew cycle") || !strings.Contains(note, "round 1000") { + t.Fatalf("once the round is out the observation said %q", note) + } +} + +// TestARewrittenBranchRefuses: once this machine has verified a draw, a store +// branch on origin that no longer holds it, deleted or rewritten, refuses +// with one line, carries nothing, and draws or opens no window over it. +func TestARewrittenBranchRefuses(t *testing.T) { + for _, how := range []string{"deleted", "rewritten"} { + t.Run(how, func(t *testing.T) { + latest := "1000" + c := newDrawCase(t) + c.serveRounds(&latest) + c.openWindow(w0) + c.closeWindow() + if note := c.observe(q1000.Add(time.Hour)); !strings.Contains(note, "drew cycle") { + t.Fatalf("the draw said %q", note) + } + switch how { + case "deleted": + gitIn(t, c.bare, "update-ref", "-d", BranchRef) + case "rewritten": + fresh := commitFilesAt(t, c.r, "", map[string]string{WindowOpenFile: encodeOrFail(t, WindowOpen{SchemaVersion: SchemaVersion, + Commit: c.r.Git("rev-parse", "origin/main"), At: q1000})}) + c.r.Git("push", "-q", "--no-verify", "origin", "+"+fresh+":"+BranchRef) + } + tip := c.originTip() + write(t, c.r.Root(), hb(handBack("iss-8", q1000.Add(time.Hour)))) + note := c.observe(q1000.Add(2 * time.Hour)) + if !strings.Contains(note, "rewritten") || strings.Contains(note, "first window") || c.originTip() != tip { + t.Fatalf("a carry over a %s branch said %q (origin moved %v)", how, note, c.originTip() != tip) + } + c.landAt(1, q202600.Add(time.Second)) + latest = "202600" + note = c.observe(q202600.Add(time.Hour)) + if !strings.Contains(note, "rewritten") || strings.Contains(note, "first window") || strings.Contains(note, "drew") || c.originTip() != tip { + t.Fatalf("a draw over a %s branch said %q (origin moved %v)", how, note, c.originTip() != tip) + } + }) + } +} + +// TestALateRecordIsDrawnInTheNextWindow: a hand-back made inside a window +// that reaches origin only after that window was drawn is in the next +// window's population. +func TestALateRecordIsDrawnInTheNextWindow(t *testing.T) { + latest := "1000" + c := newDrawCase(t) + c.serveRounds(&latest) + c.openWindow(w0) + c.closeWindow() + if note := c.observe(q1000.Add(time.Hour)); !strings.Contains(note, "drew cycle") { + t.Fatalf("the first draw said %q", note) + } + write(t, c.r.Root(), hb(handBack("iss-77", w0.Add(time.Hour)))) + if note := c.observe(q1000.Add(2 * time.Hour)); !strings.Contains(note, "carried 1 record") { + t.Fatalf("the late record was not carried: %q", note) + } + latest = "202600" + c.landAt(1, q202600.Add(time.Second)) + if note := c.observe(q202600.Add(time.Hour)); !strings.Contains(note, "drew cycle") { + t.Fatalf("the second draw said %q", note) + } + cy := c.newestCycle() + for _, g := range cy.Groups { + if g.Group == GroupDrainHandBacks && slices.ContainsFunc(g.Population.Keys, func(k string) bool { return strings.Contains(k, "-iss-77") }) { + return + } + } + t.Fatalf("the late hand-back is in no population of the next cycle: %+v", cy.Groups) +} diff --git a/internal/core/spotcheck/window.go b/internal/core/spotcheck/window.go index 462555513f..a123c3bd83 100644 --- a/internal/core/spotcheck/window.go +++ b/internal/core/spotcheck/window.go @@ -1,11 +1,17 @@ package spotcheck // window.go is the trigger (spc-2610301925429250 approach 3): a window spans -// everything since the last cycle, or since the window opened, and closes at -// the first landing observed once either bound has passed. +// the default branch's first-parent line since the last cycle, or since the +// window opened, and its close is read from that line alone, so every +// checkout that reads it finds the same close whenever it looks. By days, the +// window closes at its start plus WindowDays, once a commit of the line was +// committed after that moment, and ends at the last commit committed before +// it; by changes, it closes at the WindowChanges-th commit of the line, at +// that commit's time. Whichever comes first on the line closes it. import ( "context" + "errors" "fmt" "strconv" "strings" @@ -14,33 +20,57 @@ import ( "github.com/intentdriven/abcd/internal/gitutil" ) -// windowClosedBy is the bound a window that began at from has passed by now, -// changes first-parent commits later: ClosedByDays once WindowDays whole -// days have gone by, ClosedByChanges once WindowChanges (when set) commits -// have landed, the days first when both have; "" when neither has. -func windowClosedBy(c Config, from time.Time, changes int, now time.Time) string { - if !now.Before(from.Add(time.Duration(c.WindowDays) * 24 * time.Hour)) { - return ClosedByDays - } - if c.WindowChanges > 0 && changes >= c.WindowChanges { - return ClosedByChanges - } - return "" +// closing is a window's close as its line gives it: the bound that closed it +// ("" while the window is open), the commit it ends at and the moment it +// closed, which fixes its round. +type closing struct { + by string + commit string + at time.Time } -// changesSince counts the first-parent commits from from to tip, both full -// object names this checkout holds, as stored: one local git command. -func changesSince(ctx context.Context, root, from, tip string) (int, error) { +// windowClose reads the close of the window that began at from (fromTime) +// from origin's default branch up to tip, as stored: one local git command. +// A start the line does not hold is an error, never an open window. +func windowClose(ctx context.Context, root string, c Config, from string, fromTime time.Time, tip string) (closing, error) { if from == tip { - return 0, nil + return closing{}, nil + } + on, err := isAncestor(ctx, root, from, tip) + if err != nil { + return closing{}, err } - out, err := gitutil.RunCappedBytesAsStoredContext(ctx, root, "", 64, "rev-list", "--first-parent", "--count", from+".."+tip, "--") + if !on { + return closing{}, fmt.Errorf("the spot-check's window starts at %s, which origin's default branch does not hold", from[:12]) + } + out, err := gitutil.RunCappedBytesAsStoredContext(ctx, root, "", maxListingBytes, "log", "--first-parent", "--reverse", "--format=%H %ct", from+".."+tip, "--") if err != nil { - return 0, fmt.Errorf("counting the changes since the spot-check's last window: %s", redact(err)) + return closing{}, fmt.Errorf("reading the spot-check's window: %s", redact(err)) + } + daysAt := fromTime.Add(time.Duration(c.WindowDays) * 24 * time.Hour) + last, n := from, 0 + for _, line := range strings.Split(strings.TrimSpace(string(out)), "\n") { + sha, ct, ok := strings.Cut(line, " ") + secs, err := strconv.ParseInt(ct, 10, 64) + if !ok || err != nil || !gitutil.IsFullSHA(sha) { + return closing{}, errors.New("reading the spot-check's window: git answered a line of an unexpected shape") + } + at := time.Unix(secs, 0).UTC() + if at.After(daysAt) { + return closing{by: ClosedByDays, commit: last, at: daysAt}, nil + } + last, n = sha, n+1 + if c.WindowChanges > 0 && n == c.WindowChanges { + return closing{by: ClosedByChanges, commit: sha, at: later(at, fromTime)}, nil + } } - n, err := strconv.Atoi(strings.TrimSpace(string(out))) - if err != nil || n < 0 { - return 0, fmt.Errorf("counting the changes since the spot-check's last window: git answered %q", strings.TrimSpace(string(out))) + return closing{}, nil +} + +// later is the later of a and b. +func later(a, b time.Time) time.Time { + if a.After(b) { + return a } - return n, nil + return b } diff --git a/internal/core/spotcheck/window_test.go b/internal/core/spotcheck/window_test.go index e28461db24..d2ef5fe732 100644 --- a/internal/core/spotcheck/window_test.go +++ b/internal/core/spotcheck/window_test.go @@ -1,39 +1,79 @@ package spotcheck import ( + "os/exec" "testing" "time" + + "github.com/intentdriven/abcd/internal/gittest" ) +// commitAt commits once on r at the committer time at and answers the commit. +func commitAt(t *testing.T, r *gittest.Repo, at time.Time) string { + t.Helper() + when := at.Format(time.RFC3339) + cmd := exec.Command("git", "-C", r.Root(), "-c", "user.email=fixture@example.invalid", "-c", "user.name=Fixture", + "-c", "commit.gpgsign=false", "commit", "-q", "--allow-empty", "-m", "a landing") + cmd.Env = append(gittest.Env(t), "GIT_COMMITTER_DATE="+when, "GIT_AUTHOR_DATE="+when) + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("git commit: %v\n%s", err, out) + } + return r.Git("rev-parse", "HEAD") +} + +// TestWindowByDays: a window of seven days stays open while every commit of +// its line was committed within them, and once one was committed after, it +// closes at the seven days' end, at the last commit before it; a later commit +// moves neither. func TestWindowByDays(t *testing.T) { + r, _ := originWithRemote(t) c := Config{WindowDays: 7, PerGroup: 10} - if got := windowClosedBy(c, at0, 1000, at0.Add(7*24*time.Hour-time.Second)); got != "" { - t.Fatalf("a window a second short of seven days closed by %q", got) + from := r.Git("rev-parse", "HEAD") + end := w0.Add(7 * 24 * time.Hour) + commitAt(t, r, w0.Add(time.Hour)) + in := commitAt(t, r, end) + if got, err := windowClose(t.Context(), r.Root(), c, from, w0, in); err != nil || got.by != "" { + t.Fatalf("a window whose every commit is within its days closed: %+v, %v", got, err) } - if got := windowClosedBy(c, at0, 0, at0.Add(7*24*time.Hour)); got != ClosedByDays { - t.Fatalf("a window of seven days closed by %q; want days", got) + commitAt(t, r, end.Add(time.Second)) + tip := commitAt(t, r, end.Add(time.Hour)) + got, err := windowClose(t.Context(), r.Root(), c, from, w0, tip) + if err != nil || got.by != ClosedByDays || got.commit != in || !got.at.Equal(end) { + t.Fatalf("windowClose = %+v, %v; want days at %s, ending at %s", got, err, end, in[:12]) } } +// TestWindowByChanges: a window of ten changes closes at its tenth commit, at +// that commit's time, unless the days closed it first on the line. func TestWindowByChanges(t *testing.T) { - c := Config{WindowDays: 90, WindowChanges: 10, PerGroup: 10} - if got := windowClosedBy(c, at0, 9, at0.Add(time.Hour)); got != "" { - t.Fatalf("nine changes closed a window of ten by %q", got) - } - if got := windowClosedBy(c, at0, 10, at0.Add(time.Hour)); got != ClosedByChanges { - t.Fatalf("ten changes closed the window by %q; want changes", got) - } - if got := windowClosedBy(c, at0, 10, at0.Add(90*24*time.Hour)); got != ClosedByDays { - t.Fatalf("both bounds passed: closed by %q; want days first", got) - } - // The changes are counted on the first-parent line, locally. r, _ := originWithRemote(t) + c := Config{WindowDays: 7, WindowChanges: 10, PerGroup: 10} from := r.Git("rev-parse", "HEAD") - for range 3 { - r.Commit("a change") + var tenth string + for i := range 11 { + sha := commitAt(t, r, w0.Add(time.Duration(i+1)*time.Hour)) + if i == 8 { + if got, err := windowClose(t.Context(), r.Root(), c, from, w0, sha); err != nil || got.by != "" { + t.Fatalf("nine changes closed a window of ten: %+v, %v", got, err) + } + } + if i == 9 { + tenth = sha + } + } + got, err := windowClose(t.Context(), r.Root(), c, from, w0, r.Git("rev-parse", "HEAD")) + if err != nil || got.by != ClosedByChanges || got.commit != tenth || !got.at.Equal(w0.Add(10*time.Hour)) { + t.Fatalf("windowClose = %+v, %v; want changes at the tenth commit", got, err) + } + r2, _ := originWithRemote(t) + from2 := r2.Git("rev-parse", "HEAD") + first := commitAt(t, r2, w0.Add(time.Hour)) + commitAt(t, r2, w0.Add(8*24*time.Hour)) + for i := range 10 { + commitAt(t, r2, w0.Add(9*24*time.Hour+time.Duration(i)*time.Second)) } - n, err := changesSince(t.Context(), r.Root(), from, r.Git("rev-parse", "HEAD")) - if err != nil || n != 3 { - t.Fatalf("changesSince = %d, %v; want 3", n, err) + got, err = windowClose(t.Context(), r2.Root(), c, from2, w0, r2.Git("rev-parse", "HEAD")) + if err != nil || got.by != ClosedByDays || got.commit != first { + t.Fatalf("the days came first on the line, yet the close is %+v, %v", got, err) } } diff --git a/internal/surface/cli/githook_prepush_spotcheck_test.go b/internal/surface/cli/githook_prepush_spotcheck_test.go index 3390a41ee1..2574e8c299 100644 --- a/internal/surface/cli/githook_prepush_spotcheck_test.go +++ b/internal/surface/cli/githook_prepush_spotcheck_test.go @@ -1,6 +1,7 @@ package cli import ( + "fmt" "os" "os/exec" "path/filepath" @@ -14,7 +15,8 @@ import ( // adr-2611251806496719): refs/heads/abcd-spotcheck, the spot-check's store, is // an orphan of small JSON files under the store's folders, pushed by abcd // with the hooks running and no receipt. The row admits a fast-forward whose -// every commit holds only regular files at the store's paths; every other +// every commit holds only regular files at the store's paths, each within the +// store's bound, adding no more files than one push of the store's; every other // push to the branch is gated as any branch is, a branch whose name merely // begins like it is no branch of the row, and the store is never deleted. @@ -64,8 +66,38 @@ var ( windowOpen = storeFile{path: "window-open.json", body: "{}\n"} aHandBack = storeFile{path: "handbacks/20261125T010203Z-iss-12-0123456789abcdef.json", body: "{}\n"} anItem = storeFile{path: "items/20261125T010203Z-0123456789ab/001-drain-landed-" + strings.Repeat("a", 40) + ".json", body: "{}\n"} + aCycle = storeFile{path: "cycles/20261125T010203Z-0123456789ab.json", body: "{}\n"} ) +// storeCommitOf writes a commit over parent whose tree adds n files of one +// content under handbacks/, in one index update. +func (c *prePushCase) storeCommitOf(parent string, n int) string { + c.t.Helper() + index := filepath.Join(c.t.TempDir(), "index") + p := filepath.Join(c.t.TempDir(), "f") + if err := os.WriteFile(p, []byte("{}\n"), 0o644); err != nil { + c.t.Fatal(err) + } + git := func(stdin string, args ...string) string { + cmd := exec.Command("git", args...) + cmd.Dir, cmd.Stdin = c.dir, strings.NewReader(stdin) + cmd.Env = append(gittest.Env(c.t), "GIT_INDEX_FILE="+index) + out, err := cmd.CombinedOutput() + if err != nil { + c.t.Fatalf("git %v: %v\n%s", args, err, out) + } + return strings.TrimSpace(string(out)) + } + git("", "read-tree", parent+"^{tree}") + sha := git("", "hash-object", "-w", p) + var info strings.Builder + for i := range n { + fmt.Fprintf(&info, "100644 %s\thandbacks/20261125T010203Z-iss-%d-0123456789abcdef.json\n", sha, i) + } + git(info.String(), "update-index", "--add", "--index-info") + return c.commitTree(git("", "write-tree"), parent, "spotcheck: records") +} + // TestPrePushPassesStoreCommitsWithoutAReceipt: the store's first push (an // orphan create) and the next (a fast-forward over it) pass with no receipt. func TestPrePushPassesStoreCommitsWithoutAReceipt(t *testing.T) { @@ -81,6 +113,33 @@ func TestPrePushPassesStoreCommitsWithoutAReceipt(t *testing.T) { if got := c.remoteRef(spotcheckRef); got != next { t.Fatalf("the remote holds %q, want %s", got, next) } + // A cycle may be larger than a record, up to its own bound, and a push + // may add as many files as the store's writer puts in one. + big := c.storeCommit(next, storeFile{path: aCycle.path, body: strings.Repeat("x", 256<<10)}) + if out, err := c.push("--porcelain", "origin", big+":"+spotcheckRef); err != nil { + t.Fatalf("a cycle within its bound was refused\n%s", out) + } + many := c.storeCommitOf(big, 1000) + if out, err := c.push("--porcelain", "origin", many+":"+spotcheckRef); err != nil { + t.Fatalf("a push of a thousand files was refused\n%s", out) + } +} + +// TestPrePushGatesAStorePushOfTooManyFiles: a push that adds more files than +// the store's writer puts in one needs a receipt. +func TestPrePushGatesAStorePushOfTooManyFiles(t *testing.T) { + c := newPrePushCase(t) + first := c.storeCommit("", windowOpen) + if out, err := c.push("origin", first+":"+spotcheckRef); err != nil { + t.Fatalf("the store's first commit was refused\n%s", out) + } + out, err := c.push("origin", c.storeCommitOf(first, 1001)+":"+spotcheckRef) + if err == nil || !strings.Contains(out, "no passing preflight") { + t.Fatalf("a push of 1,001 files passed without a receipt (err %v)\n%s", err, out) + } + if got := c.remoteRef(spotcheckRef); got != first { + t.Errorf("the remote holds %q, want %s", got, first) + } } // TestPrePushGatesEveryOtherPushToTheStore: a file outside the store's paths, @@ -109,6 +168,8 @@ func TestPrePushGatesEveryOtherPushToTheStore(t *testing.T) { "another folder": {path: "scripts/x.json", body: "{}\n"}, "a name with a space": {path: "handbacks/a b.json", body: "{}\n"}, "a store folder file at top": {path: "handbacks.json", body: "{}\n"}, + "a record over its bound": {path: aHandBack.path, body: strings.Repeat("x", 16<<10+1)}, + "a cycle over its bound": {path: aCycle.path, body: strings.Repeat("x", 256<<10+1)}, } { t.Run(name, func(t *testing.T) { c := newPrePushCase(t) From 550e4c2825f708aeb72f976f79fcb399ebd84751 Mon Sep 17 00:00:00 2001 From: REPPL <77722411+REPPL@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:17:21 +0000 Subject: [PATCH 07/16] fix: recompute each spot-check cycle's window from the default branch A cycle read back is now checked against origin's default branch rather than its own fields. The spotcheck block as the branch stores it at the window's start, the repository layer alone, must be the cycle's window and per-group values, and the close the first-parent line gives must be its bound, end commit and moment. Every landing it lists must be a commit of its window, and the cycle records how many first-parent commits the window spans. A cycle that fails is set aside like any other. The draw is keyed by the window's start commit and close moment, never by the cycle's id. The draw reads its configuration at the window's start too. The high-water mark is written through the declaration scope its reader uses, and a mark that cannot be written is named in the note. The pre-push hook counts the files each store commit changes against its first parent. The ADR, the decision, the spec and the configuration chapter now say what the reader checks. Refs: spc-2610301925429250 Refs: itd-2610301750162657 Assisted-by: Claude:claude-opus-5-5 --- .../brief/05-internals/03-configuration.md | 8 +- ...the-spot-check-s-store-branch-is-pushed.md | 4 +- ...a-person-spot-checks-what-abcd-s-agents.md | 6 +- ...3430233-the-technical-facilitator-under.md | 2 +- .githooks/pre-push | 19 ++-- internal/core/spotcheck/afterlanding.go | 59 +++++++----- internal/core/spotcheck/afterlanding_test.go | 13 ++- internal/core/spotcheck/config.go | 12 ++- internal/core/spotcheck/cycle.go | 92 +++++++++++------- internal/core/spotcheck/draw.go | 12 +-- internal/core/spotcheck/mark.go | 10 +- internal/core/spotcheck/verify_test.go | 94 +++++++++++++++++-- internal/core/spotcheck/window.go | 42 +++++---- .../cli/githook_prepush_spotcheck_test.go | 8 ++ 14 files changed, 268 insertions(+), 113 deletions(-) diff --git a/.abcd/development/brief/05-internals/03-configuration.md b/.abcd/development/brief/05-internals/03-configuration.md index 5f19a1bcbf..f6f6c15bbd 100644 --- a/.abcd/development/brief/05-internals/03-configuration.md +++ b/.abcd/development/brief/05-internals/03-configuration.md @@ -848,9 +848,11 @@ may run to in this repository: a whole number from 16 to 200, 40 by default ### The spot-check keys The `spotcheck` block sets the spot-check's window and its sample -(`internal/core/spotcheck/config.go`, itd-2610301750162657), read through the -layered resolver, the repository layer last and winning, at origin's default -branch as stored: a value only in the working tree sizes no draw. +(`internal/core/spotcheck/config.go`, itd-2610301750162657). A window is +governed by the repository layer alone, as the default branch stores it at the +commit the window starts at: a value only in the working tree, a change landed +inside the window, or a machine's own layer sizes no draw, so every reader of a +cycle checks it by the same values. ```jsonc { diff --git a/.abcd/development/decisions/adrs/2611251806496719-the-spot-check-s-store-branch-is-pushed.md b/.abcd/development/decisions/adrs/2611251806496719-the-spot-check-s-store-branch-is-pushed.md index ec480bec31..fea8e61607 100644 --- a/.abcd/development/decisions/adrs/2611251806496719-the-spot-check-s-store-branch-is-pushed.md +++ b/.abcd/development/decisions/adrs/2611251806496719-the-spot-check-s-store-branch-is-pushed.md @@ -35,7 +35,7 @@ The push hook's receipt-less table gains a third row: the branch `abcd-spotcheck A deletion of the branch is refused outright: the store is kept for ever. Any other push to the branch is gated as any branch is. The forge ruleset that blocks deletion and non-fast-forward pushes of `refs/heads/abcd-spotcheck` is the person's act, applied from its mirror, `.abcd/work/rulesets/spotcheck-protection.json`, as every ruleset is, before the first draw on any machine. -Because the row admits content, abcd's reader never trusts what it reads there ([dcn-2611260013430233](../../../work/decisions/dcn-2611260013430233-the-technical-facilitator-under.md)). Every cycle is verified wherever it is read: its id is its close's, it starts where its window began, its close is no later than the reader's clock allows, its round is the one its close fixes on the chain's pinned clock, its signature verifies under the pinned key, and its drawn lists are the ones that round gives over its populations. A cycle that fails is set aside, named, and its window drawn afresh, so a hand-made or future-dated cycle can neither end a window nor stop a later draw. A window's close, and so its round and its draw, is read from the default branch's history alone, the same for every drawer at any moment. Each machine keeps a high-water mark of the last copy it verified, in the person's home store, and refuses a branch that no longer holds it, deleted or rewritten, opening no first window over it. Records join a population by their arrival on the branch, and a judgement counts only when it reads as the judgement of the item and role its path names. +Because the row admits content, abcd's reader never trusts what it reads there ([dcn-2611260013430233](../../../work/decisions/dcn-2611260013430233-the-technical-facilitator-under.md)). Every cycle is verified wherever it is read: its id is its close's, it starts where its window began, and its window is recomputed rather than read from it: the spotcheck block as the default branch stores it at the window's start must be the cycle's own window and per-group values, and the close the default branch's first-parent line gives must be the cycle's bound, end commit and moment, so its end is on that line. Its close is no later than the reader's clock allows, its round is the one that close fixes on the chain's pinned clock, its signature verifies under the pinned key, every landing it lists is a commit of its window, and its drawn lists are the ones that round gives over its populations, keyed by the window's start and close alone, never by the cycle's id. A cycle that fails is set aside, named, and its window drawn afresh, so a cycle that does not verify can neither end a window nor stop a later draw. A window's close, and so its round and its draw, is read from the default branch's history alone, the same for every drawer at any moment. Each machine keeps a high-water mark of the last copy it verified, in the person's home store, and refuses a branch that no longer holds it, deleted or rewritten, opening no first window over it. Records join a population by their arrival on the branch, and a judgement counts only when it reads as the judgement of the item and role its path names. ## Alternatives Considered @@ -48,6 +48,6 @@ Because the row admits content, abcd's reader never trusts what it reads there ( - **Easier:** a landing's draw and its records reach `origin` from any machine whose hooks run, so the queue is one queue for every machine. - **Harder:** the shape check judges paths, modes, sizes and the count, never content: a push under the row can carry any JSON at a store path, within the bounds. abcd's reader is the guard on content: it reads every file strictly, verifies every cycle, and names one it cannot read or verify; nothing on the branch is ever built, run or merged. -- **The residual:** whoever holds the person's push rights can still write a cycle that verifies over a population it chose, hold a record back until a window's draw is known, or write judgements that halve the next sample. Verification removes the free choice of round and of drawn list and makes every cycle recomputable; it cannot tell an agent from the person when both push with one credential. Who may judge is the review lane's to settle. +- **The residual:** whoever holds the person's push rights can still write a cycle that verifies but lists or leaves out records of its choosing (the hand-backs and decisions, and which of the window's landings it classes into a group), hold a record back until a window's draw is known, or write judgements that halve the next sample. Verification removes the free choice of close, round and drawn list and makes the rest of every cycle recomputable; it cannot tell an agent from the person when both push with one credential. Who may judge is the review lane's to settle. - **The hook is a local-only check.** A push made where no hook runs is held only by the forge's ruleset, as for the other two rows. - **A new obligation:** a change to the store's folders changes this row's check in the same change. diff --git a/.abcd/development/specs/open/spc-2610301925429250-a-person-spot-checks-what-abcd-s-agents.md b/.abcd/development/specs/open/spc-2610301925429250-a-person-spot-checks-what-abcd-s-agents.md index c9ca23a3f4..984e19e983 100644 --- a/.abcd/development/specs/open/spc-2610301925429250-a-person-spot-checks-what-abcd-s-agents.md +++ b/.abcd/development/specs/open/spc-2610301925429250-a-person-spot-checks-what-abcd-s-agents.md @@ -39,8 +39,8 @@ Grounding, read on 30 October 2026: The queue is derived: an item waits while a role it is for has no judgement file. Because every write is a new file keyed by item and role, two writers never conflict; a push `origin` rejects is retried once after a fetch, and a judgement whose key the fetch shows already on `origin` is dropped and the earlier one named. A push that fails offline leaves its commit on the local tracking copy, the sitting goes on, and the next push carries it; a sitting's end and the board say how many judgements have not reached `origin`. Why the shared remote and not a tier of the tree: The draw runs inside a landing, which has no tree to write into (`land` refuses a dirty tree, `landing/land.go:274`; a lane's worktree is removed at `landMerged`), and the landing on one machine must be seen by the facilitator and the product thinker on others, so a per-machine store under `~/.abcd.noindex/` would fragment the queue across whichever machines land. A committed `.abcd/work/spot-checks/` would dirty the observing worktree at every draw and send a hundred judgements through a pull request per sitting, through the very gates being checked. The remote branch is where abcd already keeps state every copy must see (reservations, announcements), under invariant 7's named-verb rule; the findings themselves become committed issues, the reviewed and durable trace, so a lost branch loses judgements but never a finding. A repository with no `origin` has no unattended landings to draw from; there the check and the verb refuse, naming the missing remote, and write nothing. 2. **Hand-backs and the automated facilitator's decisions are recorded as they happen.** The drain writes `handbacks/-.json` (issue, kind, `From`, `Route`, `Rule`, `Reason`, the lane's pull request if one was opened, the run id, the record blob) from `routeHandBack` (`loop/drain.go:1365`), and `decisions/-.json` (kind `drain-judgement`: issue, question, answer, kind, the route's model, the rule record, the reason) from `decideDrainJudgement` when `Route` is set (`loop/drain_decide.go:167`). The merge gate's two callers (`landing/land.go:1284`, `loop/land.go:898`) write `decisions/-pr.json` (kind `merge-gate`: pull request, head, the mode and its layer, the author's role, whether a receipt named the head, `Arm`, `Method`, `Why`) whenever the mode is `auto` and the author a maintainer, which is the case in which abcd is the facilitator and no person's approval was counted; a decision in `human` mode, or over a contributor's pull request, waits for a person and is not recorded here. Each file is committed on the local tracking copy at once and pushed with the next push its verb makes anyway (the tombstone, the lane's branch, the half-lease renewal, `land`'s own push), and at the drain's end; none adds a push of its own. `DrainRoute` gains `PR int` from the lane, and `renderDrainCounts` (`cli/drain.go:435`) gains the per-pull-request table the intent asks for: One line per pull request the run opened with its hand-back count and kinds, then the hand-backs with no pull request. -3. **The window and the trigger.** `.abcd/config.json` gains a `spotcheck` block, claimed through `layered` (`Claim("spotcheck", "window_days", "window_changes", "per_group")`): `window_days` (1 to 90, bundled default 7), `window_changes` (10 to 100,000, no default, 0 meaning unset), `per_group` (1 to 100, default 10). Either window may be set and the first to pass closes it; the repository layer is read last and wins, as the drain's pace keys are read, and it is read at origin's default branch as stored, never from the working tree, so an uncommitted value never sizes a draw. One function, `spotcheck.AfterLanding(root, now) Note`, is called from the three observing sites: `landMerged` after `ld.Merged` is set (`loop/land.go:1030`), `Land` when `Landed` or `mergedAt` reports the branch on the default branch (`landing/land.go:300`, `:315`), and the drain move after its fetch of the default branch (`loop/drain.go:447`). It reads the last verified cycle's `to_commit` and `to_time` from the branch as last fetched (approach 13) and reads the window's close from the default branch's first-parent line alone, one local git command: by days, the window closes at `to_time` plus `window_days` once a commit of the line was committed after that moment, and ends at the last commit committed before it; by changes, it closes at the `window_changes`-th commit of the line, at that commit's time; whichever comes first on the line closes it. When neither has, it returns at once and touches no network. Because the close is read from origin's own history, every checkout that draws a window finds the same `to_commit`, `to_time`, cycle id and round, whenever it looks. Its return is a note for the run record or the verb's text, never an error, an outcome or a hold: a draw that refuses for any reason (beacon unreachable, forge unread, push rejected twice) leaves the window passed, writes nothing, and the next observed landing tries again. The window spans everything since the last cycle, so a week with no landing is drawn at the next one and nothing falls between windows. -4. **The beacon and the draw.** `beacon.go` pins the chain: the quicknet chain hash `52db9ba70e0cc0f6eaf7803dd07447a1f5477735fd3f661792ba94600c84e971` and the chain's group public key, the 96-byte compressed G2 point `83cf0f2896adee7eb8b5f01fcad3912212c437e0073e911fb90022d3e760183c8c4b450b6a0a6c3ac6a5776a2d1064510d1fec758c921cc22b0e17e63aaf4bcb5ed66304de9cf809bd274ca73bab4af5a6e9c76a4bc09e76eae8991ef5ece45a` and its clock, genesis `1692803367` and period 3 seconds (all from the chain's `info` reply, read on 31 October 2026 and recorded in `2026-10-31-drand-beacon-verification-sota.md`). A window's round is fixed by its close on that clock: the first round published at or after `to_time`. Before that round is published the draw asks nothing and writes nothing and says the window is not yet drawable; after it, it asks for that round by number, addressed by the pinned hash (`https://api.drand.sh//public/`), through `urlguard.NewDownload` pinned to `api.drand.sh` (falling back once to `api2.drand.sh`, then `api3.drand.sh`), ten seconds in all, body bounded at 4 KiB, and accepts only a positive `round` with a 96-hex `signature`; a reply that names a chain hash other than the pinned one, or a round other than the one asked, is refused. abcd then verifies the signature itself, at pick time: the pinned key is unmarshalled into `bls.PublicKey[bls.KeyG2SigG1]` from `github.com/cloudflare/circl/sign/bls` (v1.6.3, pure Go, BSD-3-Clause), the message is SHA-256 of the round as a big-endian uint64, and `bls.Verify(&pk, msg[:], sig)` must hold; circl's built-in G1 domain separation tag is the one drand's `bls-unchained-g1-rfc9380` scheme signs under, so no tag is passed. The randomness is SHA-256 of the signature bytes, which abcd computes itself, and a reply that carries a `randomness` field must carry that value. A reply that is late, malformed or unreachable, or whose signature does not verify, refuses the draw alike: nothing is written, one line names the beacon and the round, the landing's outcome is unchanged. The dependency is the one this spec adds, with the product thinker's sign-off of 31 October 2026: the build runs `go get github.com/cloudflare/circl@v1.6.3` and `go mod tidy` (the version the module graph already required, which the technical facilitator kept over v1.6.5 on 25 November 2026), reports every line it adds to `go.mod` and `go.sum` (circl's own module requires only go-ristretto, x/crypto, and x/sys; which of those lines are new is known only when tidy runs), and lands the `ACKNOWLEDGEMENTS.md` entries for circl and for drand in that same change, since credit lands with the change that integrates a tool. `TestBeaconVerify` holds the published vector for round 1000 (signature `b44679b9a59af2ec876b1a6b1ad52ea9b1615fc3982b19576350f93447cb1125e342b73a8dd2bacbe47e4b6b63ed5e39`, randomness `fe290beca10872ef2fb164d2aa4442de4566183ec51c56ff3cd603d930e54fdd`) as its positive case and the same signature against round 1001 as its negative; the vector was not run against circl during the check, so the test's first run is that check, and a failure stops the build and is reported rather than loosened. The populations are read for the window: Groups `drain-landed` and `automatic-merges` from the landings reader's rows in `from_commit..to_commit` classed `drain` and `automatic` (every row the evidence cannot place with a person included, its decision 9; a `person-approved` row excluded, its decisions 7 and 8); groups `drain-hand-backs` and `facilitator-decisions` from the branch's `handbacks/` and `decisions/` files by arrival: every record origin's copy holds, with the records the draw carries, whose key no earlier verified cycle's population held, never by the time a record names, so a record that reaches origin after its window was drawn is drawn from in the next and every record is in exactly one population. A row whose approval the reader could not settle from history and reports as unread from the forge refuses the draw, so a person's approval is never drawn as unattended on a guess. An automatic merge's rule is `facilitator.mode: auto`, the requirement the gate's table holds; the review receipt itself stays in the local tier and is not recovered afterwards (itd-2610301850454860, decisions 6 and 7), so the reader names the mode's requirement and the item copies it. Each item's key is its merge commit or its file name; within a group the keys are sorted, each is given `HMAC-SHA256(randomness, cycle-id || group || key)`, and the `size` smallest are drawn. The same stored randomness and population give the same list, every item has a chance, and the moment of the draw chooses nothing: the round is fixed by the window's close and does not exist until then, so there is no draw to preview before it and none to retry for after. The cycle record stores round, signature and chain hash, so the verification abcd made at the draw can be repeated by anyone later. The fetch is written into the documented meaning of `land`, `drain` and `implement step` in invariant 7 and their pages, so abcd still asks the network nothing on its own. +3. **The window and the trigger.** `.abcd/config.json` gains a `spotcheck` block, claimed through `layered` (`Claim("spotcheck", "window_days", "window_changes", "per_group")`): `window_days` (1 to 90, bundled default 7), `window_changes` (10 to 100,000, no default, 0 meaning unset), `per_group` (1 to 100, default 10). Either window may be set and the first to pass closes it. The block that governs a window is the repository layer alone, as the default branch stores it at the commit the window starts at, never the working tree or a machine's layer, so every reader of a cycle counts its window by the same values. One function, `spotcheck.AfterLanding(root, now) Note`, is called from the three observing sites: `landMerged` after `ld.Merged` is set (`loop/land.go:1030`), `Land` when `Landed` or `mergedAt` reports the branch on the default branch (`landing/land.go:300`, `:315`), and the drain move after its fetch of the default branch (`loop/drain.go:447`). It reads the last verified cycle's `to_commit` and `to_time` from the branch as last fetched (approach 13) and reads the window's close from the default branch's first-parent line alone, one local git command: by days, the window closes at `to_time` plus `window_days` once a commit of the line was committed after that moment, and ends at the last commit committed before it; by changes, it closes at the `window_changes`-th commit of the line, at that commit's time; whichever comes first on the line closes it. When neither has, it returns at once and touches no network. Because the close is read from origin's own history, every checkout that draws a window finds the same `to_commit`, `to_time`, cycle id and round, whenever it looks. Its return is a note for the run record or the verb's text, never an error, an outcome or a hold: a draw that refuses for any reason (beacon unreachable, forge unread, push rejected twice) leaves the window passed, writes nothing, and the next observed landing tries again. The window spans everything since the last cycle, so a week with no landing is drawn at the next one and nothing falls between windows. +4. **The beacon and the draw.** `beacon.go` pins the chain: the quicknet chain hash `52db9ba70e0cc0f6eaf7803dd07447a1f5477735fd3f661792ba94600c84e971` and the chain's group public key, the 96-byte compressed G2 point `83cf0f2896adee7eb8b5f01fcad3912212c437e0073e911fb90022d3e760183c8c4b450b6a0a6c3ac6a5776a2d1064510d1fec758c921cc22b0e17e63aaf4bcb5ed66304de9cf809bd274ca73bab4af5a6e9c76a4bc09e76eae8991ef5ece45a` and its clock, genesis `1692803367` and period 3 seconds (all from the chain's `info` reply, read on 31 October 2026 and recorded in `2026-10-31-drand-beacon-verification-sota.md`). A window's round is fixed by its close on that clock: the first round published at or after `to_time`. Before that round is published the draw asks nothing and writes nothing and says the window is not yet drawable; after it, it asks for that round by number, addressed by the pinned hash (`https://api.drand.sh//public/`), through `urlguard.NewDownload` pinned to `api.drand.sh` (falling back once to `api2.drand.sh`, then `api3.drand.sh`), ten seconds in all, body bounded at 4 KiB, and accepts only a positive `round` with a 96-hex `signature`; a reply that names a chain hash other than the pinned one, or a round other than the one asked, is refused. abcd then verifies the signature itself, at pick time: the pinned key is unmarshalled into `bls.PublicKey[bls.KeyG2SigG1]` from `github.com/cloudflare/circl/sign/bls` (v1.6.3, pure Go, BSD-3-Clause), the message is SHA-256 of the round as a big-endian uint64, and `bls.Verify(&pk, msg[:], sig)` must hold; circl's built-in G1 domain separation tag is the one drand's `bls-unchained-g1-rfc9380` scheme signs under, so no tag is passed. The randomness is SHA-256 of the signature bytes, which abcd computes itself, and a reply that carries a `randomness` field must carry that value. A reply that is late, malformed or unreachable, or whose signature does not verify, refuses the draw alike: nothing is written, one line names the beacon and the round, the landing's outcome is unchanged. The dependency is the one this spec adds, with the product thinker's sign-off of 31 October 2026: the build runs `go get github.com/cloudflare/circl@v1.6.3` and `go mod tidy` (the version the module graph already required, which the technical facilitator kept over v1.6.5 on 25 November 2026), reports every line it adds to `go.mod` and `go.sum` (circl's own module requires only go-ristretto, x/crypto, and x/sys; which of those lines are new is known only when tidy runs), and lands the `ACKNOWLEDGEMENTS.md` entries for circl and for drand in that same change, since credit lands with the change that integrates a tool. `TestBeaconVerify` holds the published vector for round 1000 (signature `b44679b9a59af2ec876b1a6b1ad52ea9b1615fc3982b19576350f93447cb1125e342b73a8dd2bacbe47e4b6b63ed5e39`, randomness `fe290beca10872ef2fb164d2aa4442de4566183ec51c56ff3cd603d930e54fdd`) as its positive case and the same signature against round 1001 as its negative; the vector was not run against circl during the check, so the test's first run is that check, and a failure stops the build and is reported rather than loosened. The populations are read for the window: Groups `drain-landed` and `automatic-merges` from the landings reader's rows in `from_commit..to_commit` classed `drain` and `automatic` (every row the evidence cannot place with a person included, its decision 9; a `person-approved` row excluded, its decisions 7 and 8); groups `drain-hand-backs` and `facilitator-decisions` from the branch's `handbacks/` and `decisions/` files by arrival: every record origin's copy holds, with the records the draw carries, whose key no earlier verified cycle's population held, never by the time a record names, so a record that reaches origin after its window was drawn is drawn from in the next and every record is in exactly one population. A row whose approval the reader could not settle from history and reports as unread from the forge refuses the draw, so a person's approval is never drawn as unattended on a guess. An automatic merge's rule is `facilitator.mode: auto`, the requirement the gate's table holds; the review receipt itself stays in the local tier and is not recovered afterwards (itd-2610301850454860, decisions 6 and 7), so the reader names the mode's requirement and the item copies it. Each item's key is its merge commit or its file name; within a group the keys are sorted, each is given `HMAC-SHA256(randomness, from_commit || to_time || group || key)`, keyed by the window and never by the cycle id, and the `size` smallest are drawn. The same stored randomness and population give the same list, every item has a chance, and the moment of the draw chooses nothing: the round is fixed by the window's close and does not exist until then, so there is no draw to preview before it and none to retry for after. The cycle record stores round, signature and chain hash, so the verification abcd made at the draw can be repeated by anyone later. The fetch is written into the documented meaning of `land`, `drain` and `implement step` in invariant 7 and their pages, so abcd still asks the network nothing on its own. 5. **The sample size adapts over fully reviewed cycles only.** `size` is `per_group` unless the three most recent closed cycles, in window order, each have zero findings, when it is `ceil(per_group / 2)`, never below one; a closed cycle with any finding makes the next size full. A cycle is closed when every role slot of every item has a judgement; an open cycle is skipped in the count and counts as neither clean nor a finding. The cycle record names the cycles it counted. 6. **A card, never code.** `spotcheck.Card(item)` renders what a role sees, in plain text, from records alone: the landings row (class, rule by id and path, when, pull request number); the promise, which is the issue's text and remedy, or the spec's criteria, or, for the product thinker, the intent's press release and acceptance criteria; the outcome, which is the pull request's title and the record section of the body the loop composed (`prbody.go:61`), the `resolved_by` stamp and the changelog line where one exists; and for a hand-back the issue, the kind, the route, the clause of the rule that applied and the question whether the drain was right to hand it back; for a decision the question put, the answer given and the rule record. Every card ends with `then` and `now`: `then` is the item file's own copy, written at the draw and never re-read from history or the forge; `now` is read at the sitting from the default branch as last fetched: still on it, reverted by `` (the landings reader's revert trace), changed again by later first-parent commits touching the change's paths, the issue reopened, or the handed-back issue since resolved, by whom. A card never includes a diff, a file body or a test body; `TestCardCarriesNoCode` renders every fixture and refuses a fence, a `diff --git` line or a path with a line number. Withheld until the judgement is saved, though copied into the item file at the draw: the validators' verdicts the pull request body carries, the drain judge's reason on a judgement item, the gate's `Why` on a merge-gate item, and any reviewer's verdict; `show` and `next` leave them out and the card says `verdicts: shown after you judge`. 7. **The sitting.** `abcd spotcheck review [--as facilitator|human-facilitator|product-thinker]` (the role defaults from the mode file and is asked when unset) makes one fetch of the branch and the default branch, then walks the queue in window order, oldest cycle first, group order within a cycle, item order within a group, for the role's unjudged slots. Each item is put through `question.Ask` with the card as `Material`, the one question for its group (`Does the outcome match its spec?`, `Was the drain right to hand this back?`, `Was the decision right under its rule?`, `Does what came back match the intent?`) and the options `sound`, `wrong` and the decide-later option, a typed line for `why` on `wrong`; in a terminal through `ask.Terminal.Put`, one key per item; in a host session the page has the agent render `spotcheck next --json --as [--batch N]` and put the same question through the host's tool, then record the answer with `spotcheck judge sound|wrong --why "" --as `. Both routes end in the same judgement file (`verdict`, `why`, `role`, `answered_in`, `at`, `state_now`, the issue id on `wrong`), committed and pushed as it is made, so a sitting stopped at any item resumes at the first unjudged slot with nothing to restore. `later` moves the item to the end of this pass and writes nothing. A progress line reads `item 37 of 112, cycle 3 of 9`. After each saved judgement the withheld verdicts print, one line each, and the next card is already read. @@ -49,7 +49,7 @@ Grounding, read on 30 October 2026: 10. **The board and the verb's surface.** `boardOutput` gains `SpotCheck{Waiting, ByRole, OldestDays, Unpushed, Due}` computed from the branch as last fetched (disk only, nothing fetched), and `boardRows` a `spot-check` row: `37 wait (facilitator 30, product thinker 7), oldest 41 days`; the product view adds one line when items wait for the product thinker; `--json` carries it. `Due` says the window has passed and no landing has been observed since. The verb is new and top-level, `abcd spotcheck`, with sub-verbs `review`, `next`, `judge`, `show ` and `cycles`: no existing verb's documented meaning holds a review queue people work across months (`reflect` is one release's interview, `lab` one snapshot, `status` the hour's announcements, `landings` a read-only listing), and a sub-verb of `land` or `drain` would put the reader's verb under a writer's. It lands with its brief row (43, `04-surfaces/README.md`), its chapter `04-surfaces/43-spotcheck.md` with the `## Sub-verbs` table, its page `commands/spotcheck.md` (block `people`), its sentence in the `internal/core/surface` manifest, the regenerated snapshot, and the `spotcheck` block in `05-internals/03-configuration.md`. Invariant 7 gains the branch's fetch and push for `spotcheck`, and the beacon fetch and branch push for `land`, `drain` and `implement step`. 11. **Nothing waits for the queue.** `spotcheck` exports to `loop` and `landing` only `AfterLanding`, the two record writers of approach 2, and nothing that returns a hold, a count or a boolean; `mergeGate`, `DrainJudging`, `RunningUnattended` and the away mode's `Judge` are untouched. `TestNothingWaitsForTheQueue` lands a lane and plans a drain over a branch holding ten thousand unjudged items and asserts the same outcomes and no read of `items/` or `judgements/`. 12. **A model other than the writer's reviews every change.** Before a validator is dispatched (`loop/validate.go:594`, `:1003`), the loop compares the implementer's reported model (`ReceiptRecord.Model`, or its `Route.Model`) with the reviewer's resolved `ReviewClass.Model`, by `matrix.sameModel`'s normalisation; on a match it takes the next class, in the order `loop.Classes` gives (`research`, `top`, `default`, `small`), whose model in the resolved class map differs (amended 2026-11-10 by itd-2611101419006280: the classes were renamed and a person may set the whole map), and when none does the lane hands back as `stuck` with the reason `no reviewer model other than the writer's`. A host-run validator's return must name its model, as the implementer's receipt does; a return naming none is treated as the writer's. `ValidatorRun` gains `WriterModel` and `ReviewerModel`, the lane receipt and the composed pull request body name both, and `renderReview` (`cli/build.go:540`) shows them. -13. **A cycle read back is verified, never trusted, and the branch only moves forward** (dcn-2611260013430233). Wherever a cycle is read, at every observation and at the size's tally, it is checked: its id is its close's, it starts where its window began (the opening, then each verified cycle's end in window order), its close is its window's days or within the changes' bounds and no later than the reader's clock plus five minutes, its round is the one its close fixes, its signature verifies under the pinned key and its randomness is that signature's hash, its sample size is one the size rule gives, and each drawn list is the one that randomness gives over its listed population. A cycle that fails is set aside and named in the draw's note, is no window boundary, and its window is drawn afresh over its file, so a hand-made cycle, a future-dated one included, can neither end a window nor stop a later draw; the pre-push hook still admits it. Each machine keeps a high-water mark under `~/.abcd.noindex/spotcheck///mark.json`, one per repository and origin: the last copy of the branch it verified, the window's opening and the newest verified cycle. A copy that no longer holds them, the branch deleted or rewritten, is refused in one line: nothing is carried or drawn over it and no first window is opened. `.abcd/work/rulesets/spotcheck-protection.json` mirrors the ruleset the person applies against deletion and forced pushes. A judgement counts toward the size only when it reads as one: of this schema version, naming the `cycle`, `item` and `role` its path names, with a `verdict` of `sound` or `wrong`; an item counts only when it reads as the one drawn at its path. The pre-push hook bounds each file at the reader's own limit (16 KiB, a cycle 256 KiB) and a push at 1,000 files, the writer's own. What verification cannot stop is recorded with the decision: a holder of the person's push rights can still write a self-consistent cycle over a population it chose, or hold a record back until a draw is known. +13. **A cycle read back is verified, never trusted, and the branch only moves forward** (dcn-2611260013430233). Wherever a cycle is read, at every observation and at the size's tally, it is checked: its id is its close's, it starts where its window began (the opening, then each verified cycle's end in window order), its window values are the spotcheck block as the default branch stores it at the window's start, its bound, end commit and close are the ones the default branch's first-parent line gives, its close is no later than the reader's clock plus five minutes, every landing it lists is a commit of its window, its round is the one its close fixes, its signature verifies under the pinned key and its randomness is that signature's hash, its sample size is one the size rule gives, and each drawn list is the one that randomness gives over its listed population. A cycle that fails is set aside and named in the draw's note, is no window boundary, and its window is drawn afresh over its file, so a hand-made cycle, a future-dated one included, can neither end a window nor stop a later draw; the pre-push hook still admits it. Each machine keeps a high-water mark under `~/.abcd.noindex/spotcheck///mark.json`, one per repository and origin: the last copy of the branch it verified, the window's opening and the newest verified cycle. A copy that no longer holds them, the branch deleted or rewritten, is refused in one line: nothing is carried or drawn over it and no first window is opened. `.abcd/work/rulesets/spotcheck-protection.json` mirrors the ruleset the person applies against deletion and forced pushes. A judgement counts toward the size only when it reads as one: of this schema version, naming the `cycle`, `item` and `role` its path names, with a `verdict` of `sound` or `wrong`; an item counts only when it reads as the one drawn at its path. The pre-push hook bounds each file at the reader's own limit (16 KiB, a cycle 256 KiB) and a push at 1,000 files, the writer's own. What verification cannot stop is recorded with the decision: a holder of the person's push rights can still write a self-consistent cycle over a population it chose, or hold a record back until a draw is known. ### How each criterion is met diff --git a/.abcd/work/decisions/dcn-2611260013430233-the-technical-facilitator-under.md b/.abcd/work/decisions/dcn-2611260013430233-the-technical-facilitator-under.md index 5b7128f17f..3e004de921 100644 --- a/.abcd/work/decisions/dcn-2611260013430233-the-technical-facilitator-under.md +++ b/.abcd/work/decisions/dcn-2611260013430233-the-technical-facilitator-under.md @@ -3,4 +3,4 @@ id: dcn-2611260013430233 slug: the-technical-facilitator-under date: 2026-11-26 --- -2026-11-26 — The technical facilitator, under facilitator.mode auto, ruled how the spot-check trusts its own store (itd-2610301750162657, adr-2611251806496719). A cycle read back from abcd-spotcheck is verified on every read and never trusted: its beacon signature under the pinned quicknet key, its round equal to the first round at or after its window's close on the chain's pinned genesis and period, its drawn lists recomputed from that randomness over its listed populations, and its close no later than the reader's clock plus five minutes. A cycle that fails is set aside, named in the draw's note, and its window is drawn afresh; the pre-push hook still admits it, and nothing reads it as true. A window's close is read from origin's default branch alone, so its round, its id and its draw are the same whoever draws it and whenever: a round not yet published is reported as not yet drawable and asked for no sooner, and there is no preview and no retry to choose a draw by. Each machine keeps a high-water mark of the last copy it verified in the person's home store; a branch that no longer holds it, deleted or rewritten, is refused in one line and no first window is opened over it, and .abcd/work/rulesets/spotcheck-protection.json mirrors the ruleset against deletion and forced pushes that the person applies. Hand-backs and decisions join a population by arrival on the branch, so a record that reaches origin after its window was drawn is drawn from in the next, and every record is in exactly one population. A judgement counts toward the size only when it reads as one, of this schema version, naming the cycle, item and role its path names, with a verdict of sound or wrong. Accepted as residual: a holder of the person's push rights can still write a self-consistent cycle over a population it chose, or hold a record back until a draw is known; the halving of the sample trusts every holder of push rights until the review lane settles who may judge; a window closed by changes takes its close from a committer time. The spotcheck block is read at origin's default branch, so an uncommitted value never sizes a draw. circl stays at v1.6.3, the version the module graph already required, as the facilitator ruled before; the spec's v1.6.5 is corrected to it. +2026-11-26 — The technical facilitator, under facilitator.mode auto, ruled how the spot-check trusts its own store (itd-2610301750162657, adr-2611251806496719). A cycle read back from abcd-spotcheck is verified on every read and never trusted. Its window is recomputed, not read from it: the spotcheck block as the default branch stores it at the window's start, the repository layer alone, must be the cycle's window and per-group values, and the close the default branch's first-parent line gives must be the cycle's bound, end commit and moment. Then its beacon signature verifies under the pinned quicknet key, its round is the first at or after that close on the chain's pinned genesis and period, every landing it lists is a commit of its window, its drawn lists are recomputed from that randomness over its listed populations, keyed by the window's start commit and close alone and never by the cycle's id, and its close is no later than the reader's clock plus five minutes. A cycle that fails is set aside, named in the draw's note, and its window is drawn afresh; the pre-push hook still admits it, and nothing reads it as true. A window's close is read from origin's default branch alone, so its round, its id and its draw are the same whoever draws it and whenever: a round not yet published is reported as not yet drawable and asked for no sooner, and there is no preview and no retry to choose a draw by. Each machine keeps a high-water mark of the last copy it verified in the person's home store; a branch that no longer holds it, deleted or rewritten, is refused in one line and no first window is opened over it, and .abcd/work/rulesets/spotcheck-protection.json mirrors the ruleset against deletion and forced pushes that the person applies. Hand-backs and decisions join a population by arrival on the branch, so a record that reaches origin after its window was drawn is drawn from in the next, and every record is in exactly one population. A judgement counts toward the size only when it reads as one, of this schema version, naming the cycle, item and role its path names, with a verdict of sound or wrong. Accepted as residual: a holder of the person's push rights can still write a cycle that verifies but lists or leaves out records of its choosing, or hold a record back until a draw is known; the halving of the sample trusts every holder of push rights until the review lane settles who may judge; a window closed by changes takes its close from a committer time. The spotcheck block is read at the commit a window starts at, the repository layer alone, so neither an uncommitted value, a landing inside the window, nor one machine's own layer sizes a draw. circl stays at v1.6.3, the version the module graph already required, as the facilitator ruled before; the spec's v1.6.5 is corrected to it. diff --git a/.githooks/pre-push b/.githooks/pre-push index 3b77794e4d..4873e84dc9 100755 --- a/.githooks/pre-push +++ b/.githooks/pre-push @@ -110,8 +110,8 @@ # commits hold the store's small JSON files and nothing else. The # spotcheck_shape check admits a fast-forward (or the creation) whose # every commit holds only regular, non-executable files at the store's -# paths, each within the store reader's own bound, read in full, and that -# adds no more files than the store's writer puts in one push; anything +# paths, each within the store reader's own bound, read in full, and none +# adding more files than the store's writer puts in one commit; anything # else pushed to the branch is gated as any branch is, and a deletion is # refused: the store is kept for ever. # @@ -235,7 +235,7 @@ spotcheck_path_re='^(window-open\.json|(handbacks|decisions|cycles|items|judgeme # The store's bounds, the reader's and the writer's own (internal/core/spotcheck: # maxRecordBytes, maxCycleBytes, maxPushFiles): the most bytes a file may hold, # a cycle under cycles/ more since it lists its populations, and the most files -# one push may add or change. +# one commit may add or change. spotcheck_max_bytes=16384 spotcheck_max_cycle_bytes=262144 spotcheck_max_files=1000 @@ -245,8 +245,8 @@ spotcheck_max_files=1000 # fast-forward (or a create), the walk reads the range in full, and every # commit it moves holds nothing but regular, non-executable files at store # paths (spotcheck_path_re), no segment "." or "..", each within its bound -# (spotcheck_max_bytes, spotcheck_max_cycle_bytes), and the push adds or -# changes no more than spotcheck_max_files files. The range is everything new +# (spotcheck_max_bytes, spotcheck_max_cycle_bytes), and no commit adds or +# changes more than spotcheck_max_files files against its first parent. The range is everything new # on an update and everything reachable on a create, so a commit of the # product's history pushed to the branch walks into a tree holding other # paths and is gated as any branch is. Only paths, modes, sizes and the count @@ -258,16 +258,19 @@ spotcheck_shape() { [ "$branch" = "abcd-spotcheck" ] || return 1 if is_null_id "$remote_sha"; then range="$local_sha" - changed="$(git ls-tree -r --name-only --full-tree "$local_sha" 2>/dev/null)" || return 1 else git merge-base --is-ancestor "$remote_sha" "$local_sha" 2>/dev/null || return 1 range="$remote_sha..$local_sha" - changed="$(git diff-tree -r --name-only "$remote_sha" "$local_sha" 2>/dev/null)" || return 1 fi - [ "$(printf '%s' "$changed" | grep -c '')" -le "$spotcheck_max_files" ] || return 1 read_in_full "$range" || return 1 commits="$(git rev-list "$range" 2>/dev/null)" || return 1 for commit in $commits; do + if git rev-parse --verify --quiet "$commit^" >/dev/null 2>&1; then + changed="$(git diff-tree -r --name-only "$commit^" "$commit" 2>/dev/null)" || return 1 + else + changed="$(git ls-tree -r --name-only --full-tree "$commit" 2>/dev/null)" || return 1 + fi + [ "$(printf '%s' "$changed" | grep -c '')" -le "$spotcheck_max_files" ] || return 1 listing="$(git ls-tree -r -l --full-tree "$commit" 2>/dev/null)" || return 1 while IFS= read -r line; do [ -n "$line" ] || continue diff --git a/internal/core/spotcheck/afterlanding.go b/internal/core/spotcheck/afterlanding.go index d3d0f381e4..3de67dd868 100644 --- a/internal/core/spotcheck/afterlanding.go +++ b/internal/core/spotcheck/afterlanding.go @@ -18,12 +18,13 @@ import ( "encoding/hex" "errors" "fmt" + "slices" "strconv" "strings" "time" - "github.com/intentdriven/abcd/internal/core/layered" "github.com/intentdriven/abcd/internal/gitutil" + "github.com/intentdriven/abcd/internal/termsafe" ) // DrawTimeout bounds one observation that draws: the fetch, the beacon, the @@ -67,20 +68,15 @@ func AfterLanding(parent context.Context, o Observed) string { if err != nil { return "spot-check: " + err.Error() + "; nothing was drawn" } - // The spotcheck block is read at origin's default branch, as stored, and - // the machine's own layer, never from the working tree, so an uncommitted - // value never sizes a draw. - roots, _ := layered.RootsFor(o.Root) - roots.RepoAt, roots.RepoAtName, roots.RepoAtAsStored = tip, "origin/"+o.Default, true - cfg, err := readConfig(roots) - if err != nil { - return "spot-check: the spotcheck configuration cannot be read (" + redact(err) + "); nothing was drawn" - } - st, err := readWindow(ctx, o.Root, o.Now) + st, err := readWindow(ctx, o.Root, o.Now, tip) if err != nil { return "spot-check: " + err.Error() + "; nothing was drawn" } if st.open { + cfg, err := windowConfig(o.Root, st.from) + if err != nil { + return "spot-check: the spotcheck configuration cannot be read (" + redact(err) + "); nothing was drawn" + } cl, err := windowClose(ctx, o.Root, cfg, st.from, st.fromTime, tip) if err != nil { return "spot-check: " + err.Error() + "; nothing was drawn" @@ -91,15 +87,18 @@ func AfterLanding(parent context.Context, o Observed) string { return "spot-check: " + err.Error() } if len(pending) == 0 { + if st.markErr != nil { + return "spot-check: " + strings.TrimPrefix(markNote(st.markErr), "; ") + } return "" } - return carry(ctx, o.Root) + return carry(ctx, o.Root) + markNote(st.markErr) } if note := notYet(cl, o.Now); note != "" { return note } } - return draw(ctx, o, cfg, tip) + return draw(ctx, o, tip) } // notYet is the note for a window that has closed before the round its @@ -146,14 +145,14 @@ func carry(ctx context.Context, root string) string { // branch's line and the chain's clock, so a second try, or another // checkout's, draws the same items; nothing about the moment it runs // chooses them. -func draw(ctx context.Context, o Observed, cfg Config, tip string) string { +func draw(ctx context.Context, o Observed, tip string) string { var beacon *Beacon var last error for attempt := 1; attempt <= 2; attempt++ { if _, err := fetchTracking(ctx, o.Root); err != nil { return "spot-check: " + redact(err) + "; nothing was drawn" } - st, err := readWindow(ctx, o.Root, o.Now) + st, err := readWindow(ctx, o.Root, o.Now, tip) if err != nil { return "spot-check: " + err.Error() + "; nothing was drawn" } @@ -175,8 +174,12 @@ func draw(ctx context.Context, o Observed, cfg Config, tip string) string { last = err continue } - _ = writeMark(ctx, o.Root, mark{Commit: commit, Opened: tip, OpenedAt: o.Now}) - return "spot-check: the first window opened at " + tip[:12] + "; nothing is drawn until it passes" + setAside(st) + note := markNote(writeMark(ctx, o.Root, mark{Commit: commit, Opened: tip, OpenedAt: o.Now})) + return "spot-check: the first window opened at " + tip[:12] + "; nothing is drawn until it passes" + setAside(st) + note + } + cfg, err := windowConfig(o.Root, st.from) + if err != nil { + return "spot-check: the spotcheck configuration cannot be read (" + redact(err) + "); nothing was drawn" } cl, err := windowClose(ctx, o.Root, cfg, st.from, st.fromTime, tip) if err != nil { @@ -220,16 +223,25 @@ func draw(ctx context.Context, o Observed, cfg Config, tip string) string { continue } st.cycles = append(st.cycles, c) - _ = writeMark(ctx, o.Root, st.mark(commit)) + note := markNote(writeMark(ctx, o.Root, st.mark(commit))) drawn := 0 for _, g := range c.Groups { drawn += len(g.Drawn) } - return fmt.Sprintf("spot-check: drew cycle %s (round %d of the beacon): %d item(s) for review", c.ID, beacon.Round, drawn) + setAside(st) + return fmt.Sprintf("spot-check: drew cycle %s (round %d of the beacon): %d item(s) for review", c.ID, beacon.Round, drawn) + setAside(st) + note } return "spot-check: the push to " + Branch + " was refused twice (" + redact(last) + "); nothing was drawn, and the next landing tries again" } +// markNote is the note's tail for a high-water mark that could not be kept, +// "" when it was. +func markNote(err error) string { + if err == nil { + return "" + } + return "; the high-water mark could not be kept (" + redact(err) + "), so this machine would not notice the branch rewritten past it" +} + // maxSetAside bounds the cycles a note names as set aside. const maxSetAside = 3 @@ -264,6 +276,11 @@ func makeCycle(ctx context.Context, o Observed, cfg Config, st windowState, cl c return Cycle{}, nil, fmt.Errorf("the window's landings cannot be read: %s", redact(err)) } } + for _, r := range rows { + if !slices.Contains(cl.commits, r.Commit) { + return Cycle{}, nil, fmt.Errorf("the landings reader named %s, which is not a commit of the window", termsafe.Sanitize(r.Commit)) + } + } rec, _, err := read(ctx, o.Root, TrackingRef) if err != nil { return Cycle{}, nil, err @@ -313,7 +330,7 @@ func makeCycle(ctx context.Context, o Observed, cfg Config, st windowState, cl c return Cycle{}, nil, errors.New("the beacon's randomness does not read") } c := Cycle{SchemaVersion: SchemaVersion, ID: cycleID(cl.at, cl.commit), FromCommit: st.from, ToCommit: cl.commit, - FromTime: st.fromTime, ToTime: cl.at, ClosedBy: cl.by, Window: CycleWindow{Days: cfg.WindowDays, Changes: cfg.WindowChanges}, + FromTime: st.fromTime, ToTime: cl.at, ClosedBy: cl.by, Window: CycleWindow{Days: cfg.WindowDays, Changes: cfg.WindowChanges, Commits: len(cl.commits)}, Site: o.Site, Beacon: b, Draw: DrawRule, Sample: Sample{PerGroup: cfg.PerGroup, Size: size, Why: why, Counted: counted}, Holder: Holder()} var items []file @@ -325,7 +342,7 @@ func makeCycle(ctx context.Context, o Observed, cfg Config, st windowState, cl c for i, cd := range cands { keys[i], byKey[cd.key] = cd.key, cd } - drawn := drawKeys(randomness, c.ID, g, keys, size) + drawn := drawKeys(randomness, drawSeed(c), g, keys, size) c.Groups = append(c.Groups, GroupDraw{Group: g, Population: population(keys), Drawn: drawn}) for _, k := range drawn { n++ diff --git a/internal/core/spotcheck/afterlanding_test.go b/internal/core/spotcheck/afterlanding_test.go index b8d28dedfb..4d9fc9fcbf 100644 --- a/internal/core/spotcheck/afterlanding_test.go +++ b/internal/core/spotcheck/afterlanding_test.go @@ -5,7 +5,6 @@ import ( "encoding/hex" "encoding/json" "errors" - "fmt" "os" "path/filepath" "slices" @@ -172,11 +171,12 @@ func TestADrawAtAPassedWindow(t *testing.T) { c := newDrawCase(t) c.observe(w0) from := c.r.Git("rev-parse", "origin/main") - to := c.land(3) + to := c.land(16) + line := strings.Fields(c.r.Git("rev-list", "--reverse", from+".."+to)) for i := range 14 { - c.rows = append(c.rows, row(fmt.Sprintf("%040x", i+1), ClassDrain)) + c.rows = append(c.rows, row(line[i], ClassDrain)) } - c.rows = append(c.rows, row(fmt.Sprintf("%040x", 100), ClassAutomatic), row(fmt.Sprintf("%040x", 101), "person-approved")) + c.rows = append(c.rows, row(line[14], ClassAutomatic), row(line[15], "person-approved")) h := handBack("iss-2", w0.Add(24*time.Hour)) h.Reason = "the secret reason the drain wrote" d := gateDecision(4, sha('f'), true, w0.Add(25*time.Hour)) @@ -202,7 +202,7 @@ func TestADrawAtAPassedWindow(t *testing.T) { randomness, _ := hex.DecodeString(cy.Beacon.Randomness) items := 0 for _, g := range cy.Groups { - if again := drawKeys(randomness, cy.ID, g.Group, g.Population.Keys, cy.Sample.Size); !slices.Equal(again, g.Drawn) { + if again := drawKeys(randomness, drawSeed(cy), g.Group, g.Population.Keys, cy.Sample.Size); !slices.Equal(again, g.Drawn) { t.Errorf("group %s does not recompute from the cycle record: %v vs %v", g.Group, again, g.Drawn) } items += len(g.Drawn) @@ -246,8 +246,7 @@ func TestBeaconUnreachableWritesNothing(t *testing.T) { t.Run(name, func(t *testing.T) { c := newDrawCase(t) c.observe(w0) - c.land(1) - c.rows = []LandingRow{row(sha('a'), ClassDrain)} + c.rows = []LandingRow{row(c.land(1), ClassDrain)} write(t, c.r.Root(), hb(handBack("iss-2", w0.Add(time.Hour)))) c.closeWindow() tip := c.originTip() diff --git a/internal/core/spotcheck/config.go b/internal/core/spotcheck/config.go index bacb40b67b..753e027efa 100644 --- a/internal/core/spotcheck/config.go +++ b/internal/core/spotcheck/config.go @@ -2,7 +2,8 @@ package spotcheck // config.go is the spot-check's configuration (spc-2610301925429250 // approach 3): the spotcheck block of .abcd/config.json, read through the -// layered resolver, the repository layer last and winning. +// layered resolver. A draw and every reader of its cycle read it at the +// commit the window starts at, the repository layer alone (windowConfig). import ( "fmt" @@ -71,3 +72,12 @@ func between(lo, hi int, what string) func(int) error { return nil } } + +// windowConfig is the spotcheck block that governs the window starting at +// commit: the repository layer alone, as the default branch stores it at +// that commit, so every reader of a cycle counts its window by the same +// values, none a later landing or one machine's own layer chose. +func windowConfig(root, commit string) (Config, error) { + r, _ := layered.RootsFor(root) + return readConfig(layered.Roots{Repo: r.Repo, RepoAt: commit, RepoAtName: commit[:12], RepoAtAsStored: true, HomeRefused: true}) +} diff --git a/internal/core/spotcheck/cycle.go b/internal/core/spotcheck/cycle.go index a70ed5dba4..7d2b0a3f6e 100644 --- a/internal/core/spotcheck/cycle.go +++ b/internal/core/spotcheck/cycle.go @@ -49,7 +49,14 @@ const ( // DrawRule says how a cycle's draw is recomputed from its record, so anyone // can repeat it. -const DrawRule = "each key of a group, sorted, is given HMAC-SHA256 keyed by the beacon's randomness over cycle-id NUL group NUL key; the size smallest are drawn" +const DrawRule = "each key of a group, sorted, is given HMAC-SHA256 keyed by the beacon's randomness over from-commit NUL to-time NUL group NUL key, to-time as YYYYMMDDTHHMMSSZ; the size smallest are drawn" + +// drawSeed is the part of a draw's message its window fixes: the commit the +// window starts at and the moment it closed, both settled before its round +// exists and both recomputed by every reader, never the cycle's id. +func drawSeed(c Cycle) string { + return c.FromCommit + "\x00" + c.ToTime.UTC().Format(stamp) +} // maxListedKeys is the most keys a population lists whole: above it, the // cycle keeps the first and last key and the SHA-256 of the sorted keys, one @@ -87,11 +94,13 @@ type Cycle struct { Holder string `json:"holder,omitempty"` } -// CycleWindow is the window's bounds as the drawing checkout's configuration -// gave them: WindowDays, and WindowChanges, 0 when unset. +// CycleWindow is the window's bounds as the default branch configured them +// at the window's start (windowConfig): WindowDays, and WindowChanges, 0 +// when unset; and Commits, the first-parent commits the window spans. type CycleWindow struct { Days int `json:"days"` Changes int `json:"changes"` + Commits int `json:"commits"` } // Sample is the size a cycle drew at and why. @@ -174,6 +183,9 @@ type windowState struct { cycles []Cycle // unverified names each cycle file that is not among them, and why. unverified []string + // markErr is why the high-water mark could not be kept, nil when it was + // or needed no change. + markErr error } // clockSkew is how far past the reader's clock a cycle's close may lie and @@ -189,7 +201,7 @@ const clockSkew = 5 * time.Minute // that holds files the store does not write under the draw's names, or an // opening that does not read, is an error: a window is never guessed. A copy // that reads is kept as the new mark. -func readWindow(ctx context.Context, root string, now time.Time) (windowState, error) { +func readWindow(ctx context.Context, root string, now time.Time, tip string) (windowState, error) { tracking, err := storeRef(ctx, root, TrackingRef) if err != nil { return windowState{}, err @@ -235,7 +247,7 @@ func readWindow(ctx context.Context, root string, now time.Time) (windowState, e case !st.open: err = errors.New("no window opened before it") default: - err = verifyCycle(c, id, st.from, st.fromTime, now) + err = verifyCycle(ctx, root, tip, c, id, st.from, st.fromTime, now) } if err != nil { st.unverified = append(st.unverified, "cycle "+id+" on origin does not verify ("+err.Error()+"), so it was set aside") @@ -248,10 +260,9 @@ func readWindow(ctx context.Context, root string, now time.Time) (windowState, e return windowState{}, rewritten("the cycle " + m.Cycle) } if st.open && (!marked || m.Commit != tracking) { - // The mark is kept as a best effort: one this machine cannot write - // leaves the last one standing, which still refuses a branch - // rewritten past it. - _ = writeMark(ctx, root, st.mark(tracking)) + // A mark this machine cannot write leaves the last one standing, + // which still refuses a branch rewritten past it; the note says so. + st.markErr = writeMark(ctx, root, st.mark(tracking)) } return st, nil } @@ -267,37 +278,46 @@ func (st windowState) mark(commit string) mark { } // verifyCycle checks a cycle read back from origin's copy as the cycle of -// the window that began at from (fromTime): named by its file and by its own -// close, starting where that window began, closing by a bound it names -// within the bounds' limits and no later than now allows, drawn from the -// round its close fixes, whose signature verifies under the pinned key, and -// whose every drawn list is the one that round's randomness gives over its -// population at its size. A population kept by its hash alone is checked by -// its count. What it cannot check, a population or a size a holder of push -// rights chose and recorded consistently, is the residual adr-2611251806496719 -// names. -func verifyCycle(c Cycle, id, from string, fromTime, now time.Time) error { +// the window that began at from (fromTime), against origin's default branch +// up to tip, as stored. Its window is recomputed, never read from the cycle: +// the spotcheck block as the branch stores it at from (windowConfig) must be +// the cycle's own window and per-group values, and windowClose over the +// branch's first-parent line must give the cycle's bound, end commit and +// close, so its end is on that line and its close and round are the line's. +// Its id must be its close's, its close no later than now allows, its +// signature that of the round its close fixes under the pinned key, its +// sample size one the size rule gives, every landing it lists a commit of +// the window, and each drawn list the one that round's randomness gives over +// its population, keyed by the window alone (drawSeed). A population kept by +// its hash alone is checked by its count. What it cannot check, which records +// a holder of push rights listed and why a size was halved, is the residual +// adr-2611251806496719 names. +func verifyCycle(ctx context.Context, root, tip string, c Cycle, id, from string, fromTime, now time.Time) error { switch { case c.ID != id || !gitutil.IsFullSHA(c.FromCommit) || !gitutil.IsFullSHA(c.ToCommit) || cycleID(c.ToTime, c.ToCommit) != id: return errors.New("its id is not the one its close gives") case c.FromCommit != from || !c.FromTime.Equal(fromTime): return errors.New("it does not start where its window began") - case c.ToTime.Before(c.FromTime): - return errors.New("it closes before it opens") case c.ToTime.After(now.Add(clockSkew)): return errors.New("it closes after now") } - switch c.ClosedBy { - case ClosedByDays: - if c.Window.Days < 1 || c.Window.Days > maxWindowDays || !c.ToTime.Equal(c.FromTime.Add(time.Duration(c.Window.Days)*24*time.Hour)) { - return errors.New("its close is not its window's days") - } - case ClosedByChanges: - if c.Window.Changes < minWindowChanges || c.Window.Changes > maxWindowChanges { - return errors.New("its window's changes are out of their bounds") - } - default: - return errors.New("it names no bound it closed by") + cfg, err := windowConfig(root, from) + if err != nil { + return errors.New("its window's configuration does not read") + } + if c.Window.Days != cfg.WindowDays || c.Window.Changes != cfg.WindowChanges || c.Sample.PerGroup != cfg.PerGroup { + return errors.New("its window is not the one the default branch configures") + } + cl, err := windowClose(ctx, root, cfg, from, fromTime, tip) + if err != nil || cl.by == "" { + return errors.New("the default branch gives its window no close") + } + if c.ClosedBy != cl.by || c.ToCommit != cl.commit || !c.ToTime.Equal(cl.at) || c.Window.Commits != len(cl.commits) { + return errors.New("its close is not the one the default branch gives") + } + inWindow := map[string]bool{} + for _, k := range cl.commits { + inWindow[k] = true } if err := verifyBeacon(c.Beacon); err != nil { return err @@ -306,8 +326,7 @@ func verifyCycle(c Cycle, id, from string, fromTime, now time.Time) error { return fmt.Errorf("its round %d is not round %d, which its close fixes", c.Beacon.Round, want) } s := c.Sample - if s.PerGroup < 1 || s.PerGroup > maxPerGroup || - !(s.Size == s.PerGroup && s.Why == SizeFull || s.Size == max((s.PerGroup+1)/2, 1) && s.Why == SizeHalved) { + if !(s.Size == s.PerGroup && s.Why == SizeFull || s.Size == max((s.PerGroup+1)/2, 1) && s.Why == SizeHalved) { return errors.New("its sample size is not one the size rule gives") } randomness, _ := hex.DecodeString(c.Beacon.Randomness) @@ -319,9 +338,12 @@ func verifyCycle(c Cycle, id, from string, fromTime, now time.Time) error { switch { case g.Group != groupOrder[i]: return errors.New("its groups are not the four in their order") + case (g.Group == GroupDrainLanded || g.Group == GroupAutomaticMerges) && + slices.ContainsFunc(p.Keys, func(k string) bool { return !inWindow[k] }): + return fmt.Errorf("its %s population names a commit outside its window", g.Group) case p.Count <= maxListedKeys && (len(p.Keys) != p.Count || !slices.IsSorted(p.Keys) || len(slices.Compact(slices.Clone(p.Keys))) != p.Count): return fmt.Errorf("its %s population does not list its keys", g.Group) - case p.Count <= maxListedKeys && !slices.Equal(g.Drawn, drawKeys(randomness, c.ID, g.Group, p.Keys, s.Size)): + case p.Count <= maxListedKeys && !slices.Equal(g.Drawn, drawKeys(randomness, drawSeed(c), g.Group, p.Keys, s.Size)): return fmt.Errorf("its %s draw is not the one its round gives", g.Group) case p.Count > maxListedKeys && (len(p.Keys) != 0 || len(g.Drawn) != min(s.Size, p.Count)): return fmt.Errorf("its %s draw is not of its size", g.Group) diff --git a/internal/core/spotcheck/draw.go b/internal/core/spotcheck/draw.go index 75b2b47538..7e85edb675 100644 --- a/internal/core/spotcheck/draw.go +++ b/internal/core/spotcheck/draw.go @@ -14,11 +14,11 @@ import ( "strings" ) -// drawKeys is the size keys of a group drawn by randomness for cycle id: -// each key, sorted and once, is given HMAC-SHA256(randomness, id NUL group -// NUL key), and the keys of the size smallest values are answered in that -// order (DrawRule). -func drawKeys(randomness []byte, id, group string, keys []string, size int) []string { +// drawKeys is the size keys of a group drawn by randomness for the window +// seed names (drawSeed): each key, sorted and once, is given +// HMAC-SHA256(randomness, seed NUL group NUL key), and the keys of the size +// smallest values are answered in that order (DrawRule). +func drawKeys(randomness []byte, seed, group string, keys []string, size int) []string { sorted := slices.Clone(keys) slices.Sort(sorted) sorted = slices.Compact(sorted) @@ -29,7 +29,7 @@ func drawKeys(randomness []byte, id, group string, keys []string, size int) []st all := make([]scored, 0, len(sorted)) for _, k := range sorted { m := hmac.New(sha256.New, randomness) - m.Write([]byte(id + "\x00" + group + "\x00" + k)) + m.Write([]byte(seed + "\x00" + group + "\x00" + k)) all = append(all, scored{mac: m.Sum(nil), key: k}) } slices.SortFunc(all, func(a, b scored) int { diff --git a/internal/core/spotcheck/mark.go b/internal/core/spotcheck/mark.go index 198bba1943..8116916d59 100644 --- a/internal/core/spotcheck/mark.go +++ b/internal/core/spotcheck/mark.go @@ -10,8 +10,12 @@ package spotcheck // moves forward, so a copy that no longer holds the mark's commit, opening or // cycle was deleted or rewritten: the store refuses it in one line, draws // nothing, carries nothing and opens no first window over it. Nothing in the -// checkout can move the mark, and a mark that cannot be read refuses as -// loudly as a rewritten branch. +// store's branch can move the mark, and a mark that cannot be read refuses as +// loudly as a rewritten branch. Its folder is named by origin's URL as the +// checkout's configuration spells it, so a remote renamed to another spelling +// starts a mark of its own, trusting what it first reads: the mark guards +// against the branch being rewritten, the forge's ruleset against the +// rewriting itself. import ( "context" @@ -113,7 +117,7 @@ func writeMark(ctx context.Context, root string, m mark) error { if err != nil { return err } - dir, err := fsutil.EnsureHomeScope(home, folder, abcdhome.DirMode) + dir, err := fsutil.EnsureHomeDeclarationScope(home, folder, abcdhome.DirMode) if err != nil { return err } diff --git a/internal/core/spotcheck/verify_test.go b/internal/core/spotcheck/verify_test.go index 733d4a352d..f8a00a785b 100644 --- a/internal/core/spotcheck/verify_test.go +++ b/internal/core/spotcheck/verify_test.go @@ -72,14 +72,14 @@ func (c *drawCase) plant(files map[string]string) string { return commit } -// cycleJSON is a cycle record with the window bounds a cycle carries. -func cycleJSON(t *testing.T, c Cycle, days int) string { +// cycleJSON is a cycle record with the window bounds it names. +func cycleJSON(t *testing.T, c Cycle, window map[string]int) string { t.Helper() var m map[string]any if err := json.Unmarshal([]byte(encodeOrFail(t, c)), &m); err != nil { t.Fatal(err) } - m["window"] = map[string]int{"days": days, "changes": 0} + m["window"] = window b, err := json.MarshalIndent(m, "", " ") if err != nil { t.Fatal(err) @@ -126,6 +126,10 @@ func (c *drawCase) openWindow(at time.Time) string { func hexKey(i int) string { return fmt.Sprintf("%040x", i) } +// sevenDays is the window a cycle names under the bundled configuration, +// spanning n commits. +func sevenDays(n int) map[string]int { return map[string]int{"days": 7, "changes": 0, "commits": n} } + // TestAForgedCycleIsSetAsideAndRedrawn: a cycle on origin for the window now // closing whose signature does not verify, whose round is not the one the // window's close fixes, or whose drawn list is not the one its randomness @@ -149,14 +153,15 @@ func TestAForgedCycleIsSetAsideAndRedrawn(t *testing.T) { c.serveRounds(&latest) from := c.openWindow(w0) to := c.landAt(3, w0.Add(time.Hour)) - keys := []string{hexKey(1), hexKey(2), hexKey(3)} + keys := strings.Fields(c.r.Git("rev-list", from+".."+to)) + slices.Sort(keys) for _, k := range keys { c.rows = append(c.rows, row(k, ClassDrain)) } c.closeWindow() id := cycleID(q1000, to) randomness, _ := hex.DecodeString(vectorRandomness) - drawn := drawKeys(randomness, id, GroupDrainLanded, keys, 10) + drawn := drawKeys(randomness, drawSeed(Cycle{FromCommit: from, ToTime: q1000}), GroupDrainLanded, keys, 10) forged := Cycle{SchemaVersion: SchemaVersion, ID: id, FromCommit: from, ToCommit: to, FromTime: w0, ToTime: q1000, ClosedBy: ClosedByDays, Site: SiteLane, Draw: DrawRule, Beacon: Beacon{URL: "https://api.drand.sh/" + ChainHash + "/public/1000", ChainHash: ChainHash, Round: 1000, @@ -167,7 +172,7 @@ func TestAForgedCycleIsSetAsideAndRedrawn(t *testing.T) { {Group: GroupDrainHandBacks, Population: Population{}, Drawn: []string{}}, {Group: GroupFacilitatorDecisions, Population: Population{}, Drawn: []string{}}}} edit(&forged) - c.plant(map[string]string{CyclesDir + "/" + id + ".json": cycleJSON(t, forged, 7)}) + c.plant(map[string]string{CyclesDir + "/" + id + ".json": cycleJSON(t, forged, sevenDays(3))}) note := c.observe(q1000.Add(time.Hour)) if !strings.Contains(note, "drew cycle "+id) || !strings.Contains(note, id+" on origin does not verify") { t.Fatalf("the observation over a forged cycle said %q", note) @@ -194,7 +199,7 @@ func TestAFutureDatedCycleDoesNotStopTheNextDraw(t *testing.T) { ClosedBy: ClosedByDays, Site: SiteLane, Draw: DrawRule, Beacon: Beacon{ChainHash: ChainHash, Round: 1000, Signature: vectorSignature, Randomness: vectorRandomness}, Sample: Sample{PerGroup: 10, Size: 10, Why: SizeFull, Counted: []string{}}} - c.plant(map[string]string{CyclesDir + "/" + id + ".json": cycleJSON(t, forged, 7)}) + c.plant(map[string]string{CyclesDir + "/" + id + ".json": cycleJSON(t, forged, sevenDays(0))}) c.closeWindow() note := c.observe(q1000.Add(time.Hour)) if !strings.Contains(note, "drew cycle") || !strings.Contains(note, id+" on origin does not verify") { @@ -310,3 +315,78 @@ func TestALateRecordIsDrawnInTheNextWindow(t *testing.T) { } t.Fatalf("the late hand-back is in no population of the next cycle: %+v", cy.Groups) } + +// emptyGroups are the four groups of a cycle that drew from no one. +func emptyGroups() []GroupDraw { + var gs []GroupDraw + for _, g := range groupOrder { + gs = append(gs, GroupDraw{Group: g, Population: Population{Keys: []string{}}, Drawn: []string{}}) + } + return gs +} + +// handMade is a cycle of round 1000 for the window that opened at from, at +// w0, closing at q1000 by and ending at to, drawing from no one. +func handMade(from, to, by string) Cycle { + return Cycle{SchemaVersion: SchemaVersion, ID: cycleID(q1000, to), FromCommit: from, ToCommit: to, FromTime: w0, ToTime: q1000, + ClosedBy: by, Site: SiteLane, Draw: DrawRule, + Beacon: Beacon{URL: "https://api.drand.sh/" + ChainHash + "/public/1000", ChainHash: ChainHash, Round: 1000, + Signature: vectorSignature, Randomness: vectorRandomness, FetchedAt: q1000}, + Sample: Sample{PerGroup: 10, Size: 10, Why: SizeFull, Counted: []string{}}, Groups: emptyGroups()} +} + +// TestACycleEndingOffTheDefaultBranchIsSetAside: a cycle that chains from +// the window and carries a real round, but ends at a commit the default +// branch does not hold, is no window boundary: observations go on, and the +// window is drawn. +func TestACycleEndingOffTheDefaultBranchIsSetAside(t *testing.T) { + latest := "1000" + c := newDrawCase(t) + c.serveRounds(&latest) + from := c.openWindow(w0) + forged := handMade(from, hexKey(77), ClosedByChanges) + c.plant(map[string]string{CyclesDir + "/" + forged.ID + ".json": cycleJSON(t, forged, map[string]int{"days": 7, "changes": 10, "commits": 0})}) + c.closeWindow() + note := c.observe(q1000.Add(time.Hour)) + if !strings.Contains(note, "drew cycle "+cycleID(q1000, from)) || !strings.Contains(note, forged.ID+" on origin does not verify") { + t.Fatalf("the observation over a cycle ending off the default branch said %q", note) + } + if note := c.observe(q1000.Add(2 * time.Hour)); note != "" { + t.Fatalf("the next observation said %q", note) + } +} + +// TestACycleWhoseCloseIsNotTheBranchsIsRedrawn: a cycle whose window values +// disagree with the close the default branch gives (here it ends two commits +// early) is set aside, and the window is drawn at its true close. +func TestACycleWhoseCloseIsNotTheBranchsIsRedrawn(t *testing.T) { + latest := "1000" + c := newDrawCase(t) + c.serveRounds(&latest) + from := c.openWindow(w0) + line := c.landAt(3, w0.Add(time.Hour)) + first := strings.Fields(c.r.Git("rev-list", "--reverse", from+".."+line))[0] + c.closeWindow() + forged := handMade(from, first, ClosedByDays) + c.plant(map[string]string{CyclesDir + "/" + forged.ID + ".json": cycleJSON(t, forged, sevenDays(1))}) + note := c.observe(q1000.Add(time.Hour)) + if !strings.Contains(note, "drew cycle "+cycleID(q1000, line)) || !strings.Contains(note, forged.ID+" on origin does not verify") { + t.Fatalf("the observation over a cycle with another close said %q", note) + } +} + +// TestTheDrawIsKeyedByTheWindowNotTheID: two cycles of one window whose ids +// differ only in their digits draw the same list, so the id's digits are no +// free choice. +func TestTheDrawIsKeyedByTheWindowNotTheID(t *testing.T) { + randomness, _ := hex.DecodeString(vectorRandomness) + keys := keysN(50) + a := Cycle{ID: cycleID(q1000, sha('b')), FromCommit: sha('a'), ToTime: q1000} + b := a + b.ID = cycleID(q1000, sha('c')) + for _, g := range groupOrder { + if x, y := drawKeys(randomness, drawSeed(a), g, keys, 10), drawKeys(randomness, drawSeed(b), g, keys, 10); !slices.Equal(x, y) { + t.Fatalf("ids %s and %s draw %v and %v from one window", a.ID, b.ID, x, y) + } + } +} diff --git a/internal/core/spotcheck/window.go b/internal/core/spotcheck/window.go index a123c3bd83..b668ddf0e0 100644 --- a/internal/core/spotcheck/window.go +++ b/internal/core/spotcheck/window.go @@ -21,17 +21,20 @@ import ( ) // closing is a window's close as its line gives it: the bound that closed it -// ("" while the window is open), the commit it ends at and the moment it -// closed, which fixes its round. +// ("" while the window is open), the commit it ends at, the moment it +// closed, which fixes its round, and the first-parent commits it spans, +// oldest first. type closing struct { - by string - commit string - at time.Time + by string + commit string + at time.Time + commits []string } // windowClose reads the close of the window that began at from (fromTime) // from origin's default branch up to tip, as stored: one local git command. -// A start the line does not hold is an error, never an open window. +// A start the first-parent line does not hold is an error, never an open +// window. func windowClose(ctx context.Context, root string, c Config, from string, fromTime time.Time, tip string) (closing, error) { if from == tip { return closing{}, nil @@ -43,25 +46,32 @@ func windowClose(ctx context.Context, root string, c Config, from string, fromTi if !on { return closing{}, fmt.Errorf("the spot-check's window starts at %s, which origin's default branch does not hold", from[:12]) } - out, err := gitutil.RunCappedBytesAsStoredContext(ctx, root, "", maxListingBytes, "log", "--first-parent", "--reverse", "--format=%H %ct", from+".."+tip, "--") + out, err := gitutil.RunCappedBytesAsStoredContext(ctx, root, "", maxListingBytes, "log", "--first-parent", "--reverse", "--format=%H %ct %P", from+".."+tip, "--") if err != nil { return closing{}, fmt.Errorf("reading the spot-check's window: %s", redact(err)) } daysAt := fromTime.Add(time.Duration(c.WindowDays) * 24 * time.Hour) - last, n := from, 0 - for _, line := range strings.Split(strings.TrimSpace(string(out)), "\n") { - sha, ct, ok := strings.Cut(line, " ") - secs, err := strconv.ParseInt(ct, 10, 64) - if !ok || err != nil || !gitutil.IsFullSHA(sha) { + last := from + var commits []string + for i, line := range strings.Split(strings.TrimSpace(string(out)), "\n") { + f := strings.Fields(line) + var secs int64 + if len(f) >= 2 { + secs, err = strconv.ParseInt(f[1], 10, 64) + } + if len(f) < 3 || err != nil || !gitutil.IsFullSHA(f[0]) { return closing{}, errors.New("reading the spot-check's window: git answered a line of an unexpected shape") } + if i == 0 && f[2] != from { + return closing{}, fmt.Errorf("the spot-check's window starts at %s, which origin's default branch's first-parent line does not hold", from[:12]) + } at := time.Unix(secs, 0).UTC() if at.After(daysAt) { - return closing{by: ClosedByDays, commit: last, at: daysAt}, nil + return closing{by: ClosedByDays, commit: last, at: daysAt, commits: commits}, nil } - last, n = sha, n+1 - if c.WindowChanges > 0 && n == c.WindowChanges { - return closing{by: ClosedByChanges, commit: sha, at: later(at, fromTime)}, nil + last, commits = f[0], append(commits, f[0]) + if c.WindowChanges > 0 && len(commits) == c.WindowChanges { + return closing{by: ClosedByChanges, commit: f[0], at: later(at, fromTime), commits: commits}, nil } } return closing{}, nil diff --git a/internal/surface/cli/githook_prepush_spotcheck_test.go b/internal/surface/cli/githook_prepush_spotcheck_test.go index 2574e8c299..ed0ce115a5 100644 --- a/internal/surface/cli/githook_prepush_spotcheck_test.go +++ b/internal/surface/cli/githook_prepush_spotcheck_test.go @@ -137,6 +137,14 @@ func TestPrePushGatesAStorePushOfTooManyFiles(t *testing.T) { if err == nil || !strings.Contains(out, "no passing preflight") { t.Fatalf("a push of 1,001 files passed without a receipt (err %v)\n%s", err, out) } + // A commit that adds them, followed by one that takes them away again, + // is judged commit by commit, not by the push's two ends. + many := c.storeCommitOf(first, 1001) + back := c.commitTree(c.git("rev-parse", first+"^{tree}"), many, "spotcheck: records") + out, err = c.push("origin", back+":"+spotcheckRef) + if err == nil || !strings.Contains(out, "no passing preflight") { + t.Fatalf("1,001 files added and removed again in one push passed without a receipt (err %v)\n%s", err, out) + } if got := c.remoteRef(spotcheckRef); got != first { t.Errorf("the remote holds %q, want %s", got, first) } From 3b4c9413341218d4e9f96da926c5b14fe403c5b3 Mon Sep 17 00:00:00 2001 From: REPPL <77722411+REPPL@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:00:58 +0000 Subject: [PATCH 08/16] fix: hold the spot-check's first window to its commit's place on the line The window's opening is now read against the default branch: its moment may lie no later than the reader's clock allows, no earlier than its commit was committed, and no later than that commit's first-parent child was. An opening outside those bounds is set aside, named in the note, and opened afresh at the next observation; the mark keeps an opening only once the child confirms it, so one a fast clock wrote is retried, not refused. The writer opens no earlier than the tip's own commit time. A spotcheck block that does not read at a window's start counts that window by the bundled defaults, says so in every note, and records "defaults" in the cycle's window, which every reader checks. A cycle whose window this checkout's copy of the default branch does not close yet is named as not yet checkable rather than as failing. The ADR, the spec's approach 13 and the configuration brief say the same. Refs: spc-2610301925429250 Refs: itd-2610301750162657 Assisted-by: Claude:claude-opus-5-5 --- .../brief/05-internals/03-configuration.md | 11 +- ...the-spot-check-s-store-branch-is-pushed.md | 4 +- ...a-person-spot-checks-what-abcd-s-agents.md | 2 +- internal/core/spotcheck/afterlanding.go | 56 ++++--- internal/core/spotcheck/config.go | 30 +++- internal/core/spotcheck/cycle.go | 154 ++++++++++++++---- internal/core/spotcheck/opening_test.go | 136 ++++++++++++++++ internal/core/spotcheck/store_test.go | 5 +- 8 files changed, 338 insertions(+), 60 deletions(-) create mode 100644 internal/core/spotcheck/opening_test.go diff --git a/.abcd/development/brief/05-internals/03-configuration.md b/.abcd/development/brief/05-internals/03-configuration.md index f6f6c15bbd..1b943f6ce9 100644 --- a/.abcd/development/brief/05-internals/03-configuration.md +++ b/.abcd/development/brief/05-internals/03-configuration.md @@ -872,9 +872,14 @@ cycle checks it by the same values. round that close fixes is published. - **`per_group` is the most a group draws.** The size halves, rounded up, after three closed cycles in a row found nothing, and is whole again after a finding. -- **A nonsense value refuses.** A value out of bounds or not a whole number, or a - misspelt key under `spotcheck`, refuses the observation, naming the file and - the key, and nothing is drawn; it never falls back to the default. +- **A block that does not read counts its window by the defaults.** A value out + of bounds or not a whole number, a misspelt key under `spotcheck`, or a + `.abcd/config.json` that does not parse, at the commit a window starts at, + counts that window by the bundled defaults: every observation's note says so, + naming the file and the key, the window is still drawn, and its cycle records + `"defaults": true`, so every reader verifies it by the same values. A + corrected block takes effect from the next window, which starts at a later + commit. ### Staged config keys diff --git a/.abcd/development/decisions/adrs/2611251806496719-the-spot-check-s-store-branch-is-pushed.md b/.abcd/development/decisions/adrs/2611251806496719-the-spot-check-s-store-branch-is-pushed.md index fea8e61607..2c76bb99ea 100644 --- a/.abcd/development/decisions/adrs/2611251806496719-the-spot-check-s-store-branch-is-pushed.md +++ b/.abcd/development/decisions/adrs/2611251806496719-the-spot-check-s-store-branch-is-pushed.md @@ -35,7 +35,7 @@ The push hook's receipt-less table gains a third row: the branch `abcd-spotcheck A deletion of the branch is refused outright: the store is kept for ever. Any other push to the branch is gated as any branch is. The forge ruleset that blocks deletion and non-fast-forward pushes of `refs/heads/abcd-spotcheck` is the person's act, applied from its mirror, `.abcd/work/rulesets/spotcheck-protection.json`, as every ruleset is, before the first draw on any machine. -Because the row admits content, abcd's reader never trusts what it reads there ([dcn-2611260013430233](../../../work/decisions/dcn-2611260013430233-the-technical-facilitator-under.md)). Every cycle is verified wherever it is read: its id is its close's, it starts where its window began, and its window is recomputed rather than read from it: the spotcheck block as the default branch stores it at the window's start must be the cycle's own window and per-group values, and the close the default branch's first-parent line gives must be the cycle's bound, end commit and moment, so its end is on that line. Its close is no later than the reader's clock allows, its round is the one that close fixes on the chain's pinned clock, its signature verifies under the pinned key, every landing it lists is a commit of its window, and its drawn lists are the ones that round gives over its populations, keyed by the window's start and close alone, never by the cycle's id. A cycle that fails is set aside, named, and its window drawn afresh, so a cycle that does not verify can neither end a window nor stop a later draw. A window's close, and so its round and its draw, is read from the default branch's history alone, the same for every drawer at any moment. Each machine keeps a high-water mark of the last copy it verified, in the person's home store, and refuses a branch that no longer holds it, deleted or rewritten, opening no first window over it. Records join a population by their arrival on the branch, and a judgement counts only when it reads as the judgement of the item and role its path names. +Because the row admits content, abcd's reader never trusts what it reads there ([dcn-2611260013430233](../../../work/decisions/dcn-2611260013430233-the-technical-facilitator-under.md)). Every cycle is verified wherever it is read: its id is its close's, it starts where its window began, and its window is recomputed rather than read from it: the spotcheck block as the default branch stores it at the window's start must be the cycle's own window and per-group values, and the close the default branch's first-parent line gives must be the cycle's bound, end commit and moment, so its end is on that line. Its close is no later than the reader's clock allows, its round is the one that close fixes on the chain's pinned clock, its signature verifies under the pinned key, every landing it lists is a commit of its window, and its drawn lists are the ones that round gives over its populations, keyed by the window's start and close alone, never by the cycle's id. A cycle that fails is set aside, named, and its window drawn afresh, so a cycle that does not verify can neither end a window nor stop a later draw. A window's close, and so its round and its draw, is read from the default branch's history and the window's start alone, the same for every drawer at any moment. From the second window on, the start is a verified cycle's close; the first window's start is the opening's own word, within bounds every reader checks: no later than the reader's clock allows, no earlier than its commit was committed, and no later than that commit's first-parent child on the default branch was. An opening outside them is set aside, named, and opened afresh by the next observer, and the mark keeps an opening only once that child has confirmed it. Each machine keeps a high-water mark of the last copy it verified, in the person's home store, and refuses a branch that no longer holds it, deleted or rewritten, opening no first window over it. Records join a population by their arrival on the branch, and a judgement counts only when it reads as the judgement of the item and role its path names. ## Alternatives Considered @@ -48,6 +48,6 @@ Because the row admits content, abcd's reader never trusts what it reads there ( - **Easier:** a landing's draw and its records reach `origin` from any machine whose hooks run, so the queue is one queue for every machine. - **Harder:** the shape check judges paths, modes, sizes and the count, never content: a push under the row can carry any JSON at a store path, within the bounds. abcd's reader is the guard on content: it reads every file strictly, verifies every cycle, and names one it cannot read or verify; nothing on the branch is ever built, run or merged. -- **The residual:** whoever holds the person's push rights can still write a cycle that verifies but lists or leaves out records of its choosing (the hand-backs and decisions, and which of the window's landings it classes into a group), hold a record back until a window's draw is known, or write judgements that halve the next sample. Verification removes the free choice of close, round and drawn list and makes the rest of every cycle recomputable; it cannot tell an agent from the person when both push with one credential. Who may judge is the review lane's to settle. +- **The residual:** whoever holds the person's push rights can still write a cycle that verifies but lists or leaves out records of its choosing (the hand-backs and decisions, and which of the window's landings it classes into a group), hold a record back until a window's draw is known, or write judgements that halve the next sample. Verification removes the free choice of close, round and drawn list and makes the rest of every cycle recomputable, from the first window's start on; that start a writer may still place at an older commit of the line, at any moment before its child was committed, and a first window that spans history from before the store existed shows it to whoever reads that cycle; it cannot tell an agent from the person when both push with one credential. Who may judge is the review lane's to settle. - **The hook is a local-only check.** A push made where no hook runs is held only by the forge's ruleset, as for the other two rows. - **A new obligation:** a change to the store's folders changes this row's check in the same change. diff --git a/.abcd/development/specs/open/spc-2610301925429250-a-person-spot-checks-what-abcd-s-agents.md b/.abcd/development/specs/open/spc-2610301925429250-a-person-spot-checks-what-abcd-s-agents.md index 984e19e983..50f18d793c 100644 --- a/.abcd/development/specs/open/spc-2610301925429250-a-person-spot-checks-what-abcd-s-agents.md +++ b/.abcd/development/specs/open/spc-2610301925429250-a-person-spot-checks-what-abcd-s-agents.md @@ -49,7 +49,7 @@ Grounding, read on 30 October 2026: 10. **The board and the verb's surface.** `boardOutput` gains `SpotCheck{Waiting, ByRole, OldestDays, Unpushed, Due}` computed from the branch as last fetched (disk only, nothing fetched), and `boardRows` a `spot-check` row: `37 wait (facilitator 30, product thinker 7), oldest 41 days`; the product view adds one line when items wait for the product thinker; `--json` carries it. `Due` says the window has passed and no landing has been observed since. The verb is new and top-level, `abcd spotcheck`, with sub-verbs `review`, `next`, `judge`, `show ` and `cycles`: no existing verb's documented meaning holds a review queue people work across months (`reflect` is one release's interview, `lab` one snapshot, `status` the hour's announcements, `landings` a read-only listing), and a sub-verb of `land` or `drain` would put the reader's verb under a writer's. It lands with its brief row (43, `04-surfaces/README.md`), its chapter `04-surfaces/43-spotcheck.md` with the `## Sub-verbs` table, its page `commands/spotcheck.md` (block `people`), its sentence in the `internal/core/surface` manifest, the regenerated snapshot, and the `spotcheck` block in `05-internals/03-configuration.md`. Invariant 7 gains the branch's fetch and push for `spotcheck`, and the beacon fetch and branch push for `land`, `drain` and `implement step`. 11. **Nothing waits for the queue.** `spotcheck` exports to `loop` and `landing` only `AfterLanding`, the two record writers of approach 2, and nothing that returns a hold, a count or a boolean; `mergeGate`, `DrainJudging`, `RunningUnattended` and the away mode's `Judge` are untouched. `TestNothingWaitsForTheQueue` lands a lane and plans a drain over a branch holding ten thousand unjudged items and asserts the same outcomes and no read of `items/` or `judgements/`. 12. **A model other than the writer's reviews every change.** Before a validator is dispatched (`loop/validate.go:594`, `:1003`), the loop compares the implementer's reported model (`ReceiptRecord.Model`, or its `Route.Model`) with the reviewer's resolved `ReviewClass.Model`, by `matrix.sameModel`'s normalisation; on a match it takes the next class, in the order `loop.Classes` gives (`research`, `top`, `default`, `small`), whose model in the resolved class map differs (amended 2026-11-10 by itd-2611101419006280: the classes were renamed and a person may set the whole map), and when none does the lane hands back as `stuck` with the reason `no reviewer model other than the writer's`. A host-run validator's return must name its model, as the implementer's receipt does; a return naming none is treated as the writer's. `ValidatorRun` gains `WriterModel` and `ReviewerModel`, the lane receipt and the composed pull request body name both, and `renderReview` (`cli/build.go:540`) shows them. -13. **A cycle read back is verified, never trusted, and the branch only moves forward** (dcn-2611260013430233). Wherever a cycle is read, at every observation and at the size's tally, it is checked: its id is its close's, it starts where its window began (the opening, then each verified cycle's end in window order), its window values are the spotcheck block as the default branch stores it at the window's start, its bound, end commit and close are the ones the default branch's first-parent line gives, its close is no later than the reader's clock plus five minutes, every landing it lists is a commit of its window, its round is the one its close fixes, its signature verifies under the pinned key and its randomness is that signature's hash, its sample size is one the size rule gives, and each drawn list is the one that randomness gives over its listed population. A cycle that fails is set aside and named in the draw's note, is no window boundary, and its window is drawn afresh over its file, so a hand-made cycle, a future-dated one included, can neither end a window nor stop a later draw; the pre-push hook still admits it. Each machine keeps a high-water mark under `~/.abcd.noindex/spotcheck///mark.json`, one per repository and origin: the last copy of the branch it verified, the window's opening and the newest verified cycle. A copy that no longer holds them, the branch deleted or rewritten, is refused in one line: nothing is carried or drawn over it and no first window is opened. `.abcd/work/rulesets/spotcheck-protection.json` mirrors the ruleset the person applies against deletion and forced pushes. A judgement counts toward the size only when it reads as one: of this schema version, naming the `cycle`, `item` and `role` its path names, with a `verdict` of `sound` or `wrong`; an item counts only when it reads as the one drawn at its path. The pre-push hook bounds each file at the reader's own limit (16 KiB, a cycle 256 KiB) and a push at 1,000 files, the writer's own. What verification cannot stop is recorded with the decision: a holder of the person's push rights can still write a self-consistent cycle over a population it chose, or hold a record back until a draw is known. +13. **A cycle read back is verified, never trusted, and the branch only moves forward** (dcn-2611260013430233). Wherever a cycle is read, at every observation and at the size's tally, it is checked: its id is its close's, it starts where its window began (the opening, then each verified cycle's end in window order), its window values are the spotcheck block as the default branch stores it at the window's start, its bound, end commit and close are the ones the default branch's first-parent line gives, its close is no later than the reader's clock plus five minutes, every landing it lists is a commit of its window, its round is the one its close fixes, its signature verifies under the pinned key and its randomness is that signature's hash, its sample size is one the size rule gives, and each drawn list is the one that randomness gives over its listed population. A cycle that fails is set aside and named in the draw's note, is no window boundary, and its window is drawn afresh over its file, so a hand-made cycle, a future-dated one included, can neither end a window nor stop a later draw; the pre-push hook still admits it. The opening is held the same way: its moment is no later than the reader's clock plus five minutes, no earlier than its commit was committed, and no later than that commit's first-parent child on the default branch was; one outside them is set aside, named, and opened afresh at the next observation, and the mark keeps an opening only once that child confirms it. A spotcheck block that does not read at a window's start counts that window by the bundled defaults, said in every note and recorded in the cycle's window as `defaults`, so its readers verify it by the same values. A cycle whose window this checkout's copy of the default branch does not close yet is named as not yet checkable rather than as failing. Each machine keeps a high-water mark under `~/.abcd.noindex/spotcheck///mark.json`, one per repository and origin: the last copy of the branch it verified, the window's opening and the newest verified cycle. A copy that no longer holds them, the branch deleted or rewritten, is refused in one line: nothing is carried or drawn over it and no first window is opened. `.abcd/work/rulesets/spotcheck-protection.json` mirrors the ruleset the person applies against deletion and forced pushes. A judgement counts toward the size only when it reads as one: of this schema version, naming the `cycle`, `item` and `role` its path names, with a `verdict` of `sound` or `wrong`; an item counts only when it reads as the one drawn at its path. The pre-push hook bounds each file at the reader's own limit (16 KiB, a cycle 256 KiB) and a push at 1,000 files, the writer's own. What verification cannot stop is recorded with the decision: a holder of the person's push rights can still write a self-consistent cycle over a population it chose, or hold a record back until a draw is known. ### How each criterion is met diff --git a/internal/core/spotcheck/afterlanding.go b/internal/core/spotcheck/afterlanding.go index 3de67dd868..aa0441edc1 100644 --- a/internal/core/spotcheck/afterlanding.go +++ b/internal/core/spotcheck/afterlanding.go @@ -73,9 +73,9 @@ func AfterLanding(parent context.Context, o Observed) string { return "spot-check: " + err.Error() + "; nothing was drawn" } if st.open { - cfg, err := windowConfig(o.Root, st.from) + cfg, why, err := windowConfig(ctx, o.Root, st.from) if err != nil { - return "spot-check: the spotcheck configuration cannot be read (" + redact(err) + "); nothing was drawn" + return "spot-check: " + err.Error() + "; nothing was drawn" } cl, err := windowClose(ctx, o.Root, cfg, st.from, st.fromTime, tip) if err != nil { @@ -87,20 +87,26 @@ func AfterLanding(parent context.Context, o Observed) string { return "spot-check: " + err.Error() } if len(pending) == 0 { - if st.markErr != nil { - return "spot-check: " + strings.TrimPrefix(markNote(st.markErr), "; ") - } - return "" + return withTail("", markNote(st.markErr)+defaultsNote(why)) } - return carry(ctx, o.Root) + markNote(st.markErr) + return withTail(carry(ctx, o.Root), markNote(st.markErr)+defaultsNote(why)) } if note := notYet(cl, o.Now); note != "" { - return note + return note + defaultsNote(why) } } return draw(ctx, o, tip) } +// withTail is note with tail, each "" for nothing to say, as one note: a +// tail alone stands as the note's whole. +func withTail(note, tail string) string { + if note == "" && tail != "" { + return "spot-check: " + strings.TrimPrefix(tail, "; ") + } + return note + tail +} + // notYet is the note for a window that has closed before the round its // close fixes is published, "" once it is: nothing is asked of the beacon // and nothing is written, and a landing observed after the round draws it, @@ -165,7 +171,15 @@ func draw(ctx context.Context, o Observed, tip string) string { // window's population. pending = pending[:min(len(pending), maxPushFiles-len(groupOrder)*maxPerGroup-1)] if !st.open { - w, err := encodeFile("", WindowOpenFile, WindowOpen{SchemaVersion: SchemaVersion, Commit: tip, At: o.Now, Holder: Holder()}) + // The opening is never earlier than its commit, so a tip + // committed by a clock ahead of this one opens at the tip's own + // time; readers past it hold that to their clock. + at, err := committedAt(ctx, o.Root, tip) + if err != nil { + return "spot-check: " + err.Error() + "; nothing was drawn" + } + at = later(at, o.Now) + w, err := encodeFile("", WindowOpenFile, WindowOpen{SchemaVersion: SchemaVersion, Commit: tip, At: at, Holder: Holder()}) if err != nil { return "spot-check: " + err.Error() } @@ -174,12 +188,13 @@ func draw(ctx context.Context, o Observed, tip string) string { last = err continue } - note := markNote(writeMark(ctx, o.Root, mark{Commit: commit, Opened: tip, OpenedAt: o.Now})) + // The mark keeps the opening once its commit's child confirms it. + note := markNote(writeMark(ctx, o.Root, mark{Commit: commit})) return "spot-check: the first window opened at " + tip[:12] + "; nothing is drawn until it passes" + setAside(st) + note } - cfg, err := windowConfig(o.Root, st.from) + cfg, why, err := windowConfig(ctx, o.Root, st.from) if err != nil { - return "spot-check: the spotcheck configuration cannot be read (" + redact(err) + "); nothing was drawn" + return "spot-check: " + err.Error() + "; nothing was drawn" } cl, err := windowClose(ctx, o.Root, cfg, st.from, st.fromTime, tip) if err != nil { @@ -188,16 +203,16 @@ func draw(ctx context.Context, o Observed, tip string) string { if cl.by == "" { // Another writer drew this window first. if len(pending) == 0 { - return "" + return withTail("", defaultsNote(why)) } if _, err := pushOver(ctx, o.Root, st.tracking, pending, fmt.Sprintf("spotcheck: %d record(s)", len(pending))); err != nil { last = err continue } - return fmt.Sprintf("spot-check: carried %d record(s) to %s", len(pending), Branch) + return fmt.Sprintf("spot-check: carried %d record(s) to %s", len(pending), Branch) + defaultsNote(why) } if note := notYet(cl, o.Now); note != "" { - return note + return note + defaultsNote(why) } round := roundAt(cl.at) if beacon == nil || beacon.Round != round { @@ -207,7 +222,7 @@ func draw(ctx context.Context, o Observed, tip string) string { } beacon = &b } - c, items, err := makeCycle(ctx, o, cfg, st, cl, *beacon, pending) + c, items, err := makeCycle(ctx, o, cfg, why != "", st, cl, *beacon, pending) if err != nil { return "spot-check: " + err.Error() + "; nothing was drawn" } @@ -228,7 +243,7 @@ func draw(ctx context.Context, o Observed, tip string) string { for _, g := range c.Groups { drawn += len(g.Drawn) } - return fmt.Sprintf("spot-check: drew cycle %s (round %d of the beacon): %d item(s) for review", c.ID, beacon.Round, drawn) + setAside(st) + note + return fmt.Sprintf("spot-check: drew cycle %s (round %d of the beacon): %d item(s) for review", c.ID, beacon.Round, drawn) + defaultsNote(why) + setAside(st) + note } return "spot-check: the push to " + Branch + " was refused twice (" + redact(last) + "); nothing was drawn, and the next landing tries again" } @@ -262,9 +277,10 @@ func setAside(st windowState) string { // makeCycle draws the cycle closing st's window at cl: the landings of the // window (from st.from exclusive to cl.commit), the records origin's copy // holds that no earlier verified cycle drew from, the size over the cycles -// before it, and an item file per drawn key. pending are the typed records +// before it, and an item file per drawn key; defaults says the bundled +// defaults counted the window (windowConfig). pending are the typed records // this checkout carries in the same commit, read as origin's own. -func makeCycle(ctx context.Context, o Observed, cfg Config, st windowState, cl closing, b Beacon, pending []file) (Cycle, []file, error) { +func makeCycle(ctx context.Context, o Observed, cfg Config, defaults bool, st windowState, cl closing, b Beacon, pending []file) (Cycle, []file, error) { reader := registeredReader() if reader == nil { return Cycle{}, nil, errNoReader @@ -330,7 +346,7 @@ func makeCycle(ctx context.Context, o Observed, cfg Config, st windowState, cl c return Cycle{}, nil, errors.New("the beacon's randomness does not read") } c := Cycle{SchemaVersion: SchemaVersion, ID: cycleID(cl.at, cl.commit), FromCommit: st.from, ToCommit: cl.commit, - FromTime: st.fromTime, ToTime: cl.at, ClosedBy: cl.by, Window: CycleWindow{Days: cfg.WindowDays, Changes: cfg.WindowChanges, Commits: len(cl.commits)}, + FromTime: st.fromTime, ToTime: cl.at, ClosedBy: cl.by, Window: CycleWindow{Days: cfg.WindowDays, Changes: cfg.WindowChanges, Commits: len(cl.commits), Defaults: defaults}, Site: o.Site, Beacon: b, Draw: DrawRule, Sample: Sample{PerGroup: cfg.PerGroup, Size: size, Why: why, Counted: counted}, Holder: Holder()} var items []file diff --git a/internal/core/spotcheck/config.go b/internal/core/spotcheck/config.go index 753e027efa..e961161eb3 100644 --- a/internal/core/spotcheck/config.go +++ b/internal/core/spotcheck/config.go @@ -6,9 +6,11 @@ package spotcheck // commit the window starts at, the repository layer alone (windowConfig). import ( + "context" "fmt" "github.com/intentdriven/abcd/internal/core/layered" + "github.com/intentdriven/abcd/internal/gitutil" ) // The configuration's keys, bundled defaults and bounds. @@ -76,8 +78,30 @@ func between(lo, hi int, what string) func(int) error { // windowConfig is the spotcheck block that governs the window starting at // commit: the repository layer alone, as the default branch stores it at // that commit, so every reader of a cycle counts its window by the same -// values, none a later landing or one machine's own layer chose. -func windowConfig(root, commit string) (Config, error) { +// values, none a later landing or one machine's own layer chose. A block that +// does not read there, a file that does not parse or a value misspelt or out +// of its bounds, counts that window by the bundled defaults, and why says +// why, "" when the block read: the window is still drawn, the same by every +// reader, and the next window, starting at a later commit, reads the block +// as that commit holds it. A commit this checkout does not hold is an error. +func windowConfig(ctx context.Context, root, commit string) (c Config, why string, err error) { + if _, err := gitutil.RunCappedBytesAsStoredContext(ctx, root, "", 256, "rev-parse", "--verify", "--quiet", commit+"^{commit}", "--"); err != nil { + return Config{}, "", fmt.Errorf("the spot-check's window starts at %s, which this checkout does not hold", commit[:12]) + } r, _ := layered.RootsFor(root) - return readConfig(layered.Roots{Repo: r.Repo, RepoAt: commit, RepoAtName: commit[:12], RepoAtAsStored: true, HomeRefused: true}) + c, err = readConfig(layered.Roots{Repo: r.Repo, RepoAt: commit, RepoAtName: commit[:12], RepoAtAsStored: true, HomeRefused: true}) + if err != nil { + return Config{WindowDays: DefaultWindowDays, PerGroup: DefaultPerGroup}, redact(err), nil + } + return c, "", nil +} + +// defaultsNote is the note's tail for a window counted by the bundled +// defaults because its block did not read (why), "" for none. +func defaultsNote(why string) string { + if why == "" { + return "" + } + return fmt.Sprintf("; the spotcheck block at the window's start does not read (%s), so this window is counted by the bundled defaults (%d days, %d per group)", + why, DefaultWindowDays, DefaultPerGroup) } diff --git a/internal/core/spotcheck/cycle.go b/internal/core/spotcheck/cycle.go index 7d2b0a3f6e..0e768d2747 100644 --- a/internal/core/spotcheck/cycle.go +++ b/internal/core/spotcheck/cycle.go @@ -16,6 +16,7 @@ import ( "fmt" "regexp" "slices" + "strconv" "strings" "time" @@ -96,11 +97,14 @@ type Cycle struct { // CycleWindow is the window's bounds as the default branch configured them // at the window's start (windowConfig): WindowDays, and WindowChanges, 0 -// when unset; and Commits, the first-parent commits the window spans. +// when unset; Commits, the first-parent commits the window spans; and +// Defaults, true when the block did not read there and the bundled defaults +// counted the window. type CycleWindow struct { - Days int `json:"days"` - Changes int `json:"changes"` - Commits int `json:"commits"` + Days int `json:"days"` + Changes int `json:"changes"` + Commits int `json:"commits"` + Defaults bool `json:"defaults,omitempty"` } // Sample is the size a cycle drew at and why. @@ -170,14 +174,18 @@ type windowState struct { // none. tracking string files map[string]entry - // open says window-open.json is there; opened and openedAt are its - // opening, and from and fromTime are where the window now open began: - // the last verified cycle's end, else the opening. - open bool - opened string - openedAt time.Time - from string - fromTime time.Time + // open says window-open.json is there and its opening verifies + // (verifyOpening); opened and openedAt are that opening, and from and + // fromTime are where the window now open began: the last verified + // cycle's end, else the opening. confirmed says the opening's commit has + // its child on the default branch, so its bounds are all checked and the + // mark may keep it. + open bool + confirmed bool + opened string + openedAt time.Time + from string + fromTime time.Time // cycles are the verified cycles, in window order: each starts where the // one before it ended, the first at the opening. cycles []Cycle @@ -188,19 +196,85 @@ type windowState struct { markErr error } -// clockSkew is how far past the reader's clock a cycle's close may lie and -// still be read: a close beyond it was never drawn, whatever its file says. +// clockSkew is how far past the reader's clock a cycle's close, or the +// window's opening, may lie and still be read: one beyond it was never +// written then, whatever its file says. const clockSkew = 5 * time.Minute +// errAhead is a cycle whose window this checkout's copy of the default +// branch does not close yet: drawn, it may be, from a tip not fetched here. +var errAhead = errors.New("its window does not close on this checkout's copy of the default branch") + +// verifyOpening checks the window's opening against origin's default branch +// up to tip, as stored. Its moment is its writer's word, held to the line: no +// later than now allows, no earlier than its commit was committed, and, once +// that commit has its first-parent child on the line, no later than the +// child was committed; an honest writer opens at the tip it read, between +// the two. why is the bound an opening fails, "" when it holds: one that +// fails is no window's start, and the next observer opens the window afresh +// over it. An opening at a commit the line does not hold, or not on its +// first parents, passes here and is refused loudly by windowClose, as a +// commit this checkout has not fetched yet may be the line's next. confirmed +// says the child is there, so every bound was checked and none can fail +// later. err is a line that could not be read, which sets nothing aside. +func verifyOpening(ctx context.Context, root, tip string, w WindowOpen, now time.Time) (confirmed bool, why string, err error) { + if w.At.After(now.Add(clockSkew)) { + return false, "it opens after now", nil + } + if on, err := isAncestor(ctx, root, w.Commit, tip); err != nil || !on { + return false, "", nil + } + ct, err := committedAt(ctx, root, w.Commit) + if err != nil { + return false, "", err + } + if w.At.Before(ct) { + return false, "it opens before its commit was committed", nil + } + if w.Commit == tip { + return false, "", nil + } + out, err := gitutil.RunCappedBytesAsStoredContext(ctx, root, "", maxListingBytes, "log", "--first-parent", "--reverse", "--format=%H %ct %P", w.Commit+".."+tip, "--") + if err != nil { + return false, "", fmt.Errorf("reading the spot-check's opening: %s", redact(err)) + } + first, _, _ := strings.Cut(strings.TrimSpace(string(out)), "\n") + f := strings.Fields(first) + if len(f) < 3 || f[2] != w.Commit { + return false, "", nil + } + secs, err := strconv.ParseInt(f[1], 10, 64) + if err != nil { + return false, "", errors.New("reading the spot-check's opening: git answered a line of an unexpected shape") + } + if w.At.After(time.Unix(secs, 0)) { + return false, "it opens after its commit's child on the default branch was committed", nil + } + return true, "", nil +} + +// committedAt is when commit was committed, as stored. +func committedAt(ctx context.Context, root, commit string) (time.Time, error) { + out, err := gitutil.RunCappedBytesAsStoredContext(ctx, root, "", 64, "log", "-1", "--format=%ct", commit, "--") + secs, perr := strconv.ParseInt(strings.TrimSpace(string(out)), 10, 64) + if err != nil || perr != nil { + return time.Time{}, fmt.Errorf("git answered no commit time for %s, so the window's opening cannot be checked", commit[:12]) + } + return time.Unix(secs, 0).UTC(), nil +} + // readWindow is the window as origin's copy, last fetched, holds it, read -// locally and checked against this machine's mark. Every cycle is verified -// (verifyCycle) and chained from the opening in window order; a cycle that -// fails either is set aside, named in unverified, and is no window boundary, -// so its window is drawn afresh. A copy that does not hold the mark's commit, -// its opening or its newest verified cycle is refused as rewritten. A copy -// that holds files the store does not write under the draw's names, or an -// opening that does not read, is an error: a window is never guessed. A copy -// that reads is kept as the new mark. +// locally and checked against this machine's mark. The opening is verified +// (verifyOpening), and one that fails is set aside, named in unverified, and +// is no window's start, so the window is opened afresh. Every cycle is +// verified (verifyCycle) and chained from the opening in window order; a +// cycle that fails either is set aside the same way and is no window +// boundary, so its window is drawn afresh. A copy that does not hold the +// mark's commit, its opening or its newest verified cycle is refused as +// rewritten. A copy that holds files the store does not write under the +// draw's names, or an opening that does not read, is an error: a window is +// never guessed. A copy that reads is kept as the new mark, its opening once +// confirmed. func readWindow(ctx context.Context, root string, now time.Time, tip string) (windowState, error) { tracking, err := storeRef(ctx, root, TrackingRef) if err != nil { @@ -233,7 +307,15 @@ func readWindow(ctx context.Context, root string, now time.Time, tip string) (wi if !gitutil.IsFullSHA(w.Commit) || w.At.IsZero() { return windowState{}, errors.New("the spot-check's window-open.json does not read as one this package writes") } - st.open, st.opened, st.openedAt, st.from, st.fromTime = true, w.Commit, w.At, w.Commit, w.At + confirmed, why, err := verifyOpening(ctx, root, tip, w, now) + if err != nil { + return windowState{}, err + } + if why != "" { + st.unverified = append(st.unverified, "the window's opening on origin does not verify ("+why+"), so it was set aside") + } else { + st.open, st.confirmed, st.opened, st.openedAt, st.from, st.fromTime = true, confirmed, w.Commit, w.At, w.Commit, w.At + } } if marked && m.Opened != "" && (m.Opened != st.opened || !m.OpenedAt.Equal(st.openedAt)) { return windowState{}, rewritten("the window's opening (" + m.Opened[:12] + ")") @@ -249,6 +331,10 @@ func readWindow(ctx context.Context, root string, now time.Time, tip string) (wi default: err = verifyCycle(ctx, root, tip, c, id, st.from, st.fromTime, now) } + if errors.Is(err, errAhead) { + st.unverified = append(st.unverified, "cycle "+id+" on origin cannot be checked against this checkout's copy of the default branch yet, so it was set aside") + continue + } if err != nil { st.unverified = append(st.unverified, "cycle "+id+" on origin does not verify ("+err.Error()+"), so it was set aside") continue @@ -259,7 +345,7 @@ func readWindow(ctx context.Context, root string, now time.Time, tip string) (wi if marked && m.Cycle != "" && !slices.ContainsFunc(st.cycles, func(c Cycle) bool { return c.ID == m.Cycle }) { return windowState{}, rewritten("the cycle " + m.Cycle) } - if st.open && (!marked || m.Commit != tracking) { + if st.open && (!marked || m.Commit != tracking || st.confirmed && m.Opened == "") { // A mark this machine cannot write leaves the last one standing, // which still refuses a branch rewritten past it; the note says so. st.markErr = writeMark(ctx, root, st.mark(tracking)) @@ -267,9 +353,14 @@ func readWindow(ctx context.Context, root string, now time.Time, tip string) (wi return st, nil } -// mark is st as the high-water mark keeps it, at the store's commit. +// mark is st as the high-water mark keeps it, at the store's commit: its +// opening only once confirmed, as one not yet confirmed may still fail its +// bounds, and is then opened afresh rather than refused as rewritten. func (st windowState) mark(commit string) mark { - m := mark{Commit: commit, Opened: st.opened, OpenedAt: st.openedAt} + m := mark{Commit: commit} + if st.confirmed { + m.Opened, m.OpenedAt = st.opened, st.openedAt + } if n := len(st.cycles); n > 0 { c := st.cycles[n-1] m.Cycle, m.CycleFrom, m.CycleTo = c.ID, c.FromCommit, c.ToCommit @@ -301,17 +392,20 @@ func verifyCycle(ctx context.Context, root, tip string, c Cycle, id, from string case c.ToTime.After(now.Add(clockSkew)): return errors.New("it closes after now") } - cfg, err := windowConfig(root, from) + cfg, why, err := windowConfig(ctx, root, from) if err != nil { - return errors.New("its window's configuration does not read") + return errors.New("its window's start is not held here") } - if c.Window.Days != cfg.WindowDays || c.Window.Changes != cfg.WindowChanges || c.Sample.PerGroup != cfg.PerGroup { + if c.Window.Days != cfg.WindowDays || c.Window.Changes != cfg.WindowChanges || c.Sample.PerGroup != cfg.PerGroup || c.Window.Defaults != (why != "") { return errors.New("its window is not the one the default branch configures") } cl, err := windowClose(ctx, root, cfg, from, fromTime, tip) - if err != nil || cl.by == "" { + if err != nil { return errors.New("the default branch gives its window no close") } + if cl.by == "" { + return errAhead + } if c.ClosedBy != cl.by || c.ToCommit != cl.commit || !c.ToTime.Equal(cl.at) || c.Window.Commits != len(cl.commits) { return errors.New("its close is not the one the default branch gives") } diff --git a/internal/core/spotcheck/opening_test.go b/internal/core/spotcheck/opening_test.go new file mode 100644 index 0000000000..e9d7f6c0c3 --- /dev/null +++ b/internal/core/spotcheck/opening_test.go @@ -0,0 +1,136 @@ +package spotcheck + +import ( + "encoding/json" + "strings" + "testing" + "time" +) + +// plantOpening puts an opening at commit and at on origin's store branch, as +// a holder of push rights could, and fetches nothing. +func (c *drawCase) plantOpening(commit string, at time.Time) { + c.t.Helper() + c.plant(map[string]string{WindowOpenFile: encodeOrFail(c.t, WindowOpen{SchemaVersion: SchemaVersion, Commit: commit, At: at})}) +} + +// originOpening is origin's window-open.json. +func (c *drawCase) originOpening() WindowOpen { + c.t.Helper() + var w WindowOpen + if err := json.Unmarshal([]byte(c.originFile(WindowOpenFile)), &w); err != nil { + c.t.Fatal(err) + } + return w +} + +// TestAFutureDatedOpeningDoesNotStopTheWindowFromClosing: an opening dated +// past the reader's clock and its allowance is no window's start: the next +// observation names it as set aside and opens the window afresh, and that +// window closes on time and is drawn. +func TestAFutureDatedOpeningDoesNotStopTheWindowFromClosing(t *testing.T) { + latest := "1000" + c := newDrawCase(t) + c.serveRounds(&latest) + base := c.r.Git("rev-parse", "origin/main") + c.plantOpening(base, time.Date(9999, 12, 31, 23, 59, 59, 0, time.UTC)) + note := c.observe(w0) + if !strings.Contains(note, "first window opened at "+base[:12]) || !strings.Contains(note, "window's opening on origin does not verify") { + t.Fatalf("the observation over a future-dated opening said %q", note) + } + if w := c.originOpening(); w.Commit != base || !w.At.Equal(w0) { + t.Fatalf("origin's opening after it is %+v; want %s at %s", w, base[:12], w0) + } + c.land(3) + c.closeWindow() + if note := c.observe(q1000.Add(time.Hour)); !strings.Contains(note, "drew cycle "+cycleID(q1000, c.r.Git("rev-parse", "origin/main~1"))) { + t.Fatalf("the window after a future-dated opening did not close and draw: %q", note) + } +} + +// TestABackdatedOpeningOutsideItsBoundsIsIgnored: an opening dated before its +// commit was committed, or after that commit's first-parent child on the +// default branch was, is no window's start: the observation names it as set +// aside and opens the window afresh at the tip and its own clock. An opening +// a fast clock wrote, which its commit's child then falls before, is retried +// the same way and never kept, though this machine read it before. +func TestABackdatedOpeningOutsideItsBoundsIsIgnored(t *testing.T) { + for name, setup := range map[string]func(c *drawCase){ + "before its commit": func(c *drawCase) { + c.plantOpening(c.landAt(1, w0.Add(time.Hour)), w0) + }, + "after its child": func(c *drawCase) { + base := c.r.Git("rev-parse", "origin/main") + c.landAt(1, w0.Add(time.Hour)) + c.plantOpening(base, w0.Add(2*time.Hour)) + }, + "a fast clock's": func(c *drawCase) { + if note := c.observe(w0.Add(2 * time.Hour)); !strings.Contains(note, "first window opened") { + c.t.Fatalf("the first check said %q", note) + } + c.landAt(1, w0.Add(time.Hour)) + }, + } { + t.Run(name, func(t *testing.T) { + c := newDrawCase(t) + setup(c) + now := w0.Add(3 * time.Hour) + note := c.observe(now) + tip := c.r.Git("rev-parse", "origin/main") + if !strings.Contains(note, "first window opened at "+tip[:12]) || !strings.Contains(note, "window's opening on origin does not verify") || strings.Contains(note, "rewritten") { + t.Fatalf("the observation over an opening outside its bounds said %q", note) + } + if w := c.originOpening(); w.Commit != tip || !w.At.Equal(now) { + t.Fatalf("origin's opening after it is %+v; want %s at %s", w, tip[:12], now) + } + if note := c.observe(now.Add(time.Hour)); note != "" { + t.Fatalf("the observation after the fresh opening said %q", note) + } + }) + } +} + +// TestAnOpeningWithinItsBoundsIsKept: an opening dated between its commit's +// time and its child's is the window's start, as its writer wrote it. +func TestAnOpeningWithinItsBoundsIsKept(t *testing.T) { + c := newDrawCase(t) + base := c.r.Git("rev-parse", "origin/main") + c.landAt(1, w0.Add(time.Hour)) + c.plantOpening(base, w0.Add(30*time.Minute)) + if note := c.observe(w0.Add(3 * time.Hour)); note != "" { + t.Fatalf("the observation over an opening within its bounds said %q", note) + } + if w := c.originOpening(); w.Commit != base || !w.At.Equal(w0.Add(30*time.Minute)) { + t.Fatalf("origin's opening is %+v; want it kept", w) + } +} + +// TestAnUnreadableBlockAtTheStartFallsBackToTheDefaults: a spotcheck block +// that does not read at the commit a window starts at counts that window by +// the bundled defaults, says so, and records it in the cycle, which every +// reader then verifies. +func TestAnUnreadableBlockAtTheStartFallsBackToTheDefaults(t *testing.T) { + latest := "1000" + c := newDrawCase(t) + c.serveRounds(&latest) + c.r.Write(".abcd/config.json", `{"spotcheck":{"window_dayz":3}}`+"\n") + c.r.Git("add", "-A") + c.landAt(1, w0.Add(-time.Hour)) + c.openWindow(w0) + c.land(3) + c.closeWindow() + note := c.observe(q1000.Add(time.Hour)) + if !strings.Contains(note, "drew cycle") || !strings.Contains(note, "bundled defaults") { + t.Fatalf("the draw over an unreadable block said %q", note) + } + var cy struct { + Window map[string]any `json:"window"` + } + name := CyclesDir + "/" + c.newestCycle().ID + ".json" + if err := json.Unmarshal([]byte(c.originFile(name)), &cy); err != nil || cy.Window["defaults"] != true { + t.Fatalf("the cycle's window is %v, %v; want it to record the defaults", cy.Window, err) + } + if note := c.observe(q1000.Add(2 * time.Hour)); strings.Contains(note, "does not verify") || strings.Contains(note, "drew cycle") { + t.Fatalf("the cycle drawn by the defaults did not verify: %q", note) + } +} diff --git a/internal/core/spotcheck/store_test.go b/internal/core/spotcheck/store_test.go index b344200d34..970c9f54ae 100644 --- a/internal/core/spotcheck/store_test.go +++ b/internal/core/spotcheck/store_test.go @@ -26,7 +26,10 @@ func clone(t *testing.T, bare string) *gittest.Repo { t.Helper() r := gittest.NewRepo(t) r.Write("a.txt", "a\n") - r.Commit("the base") + r.Git("add", "-A") + // The base is committed before every window these tests open, as a + // window's opening is never earlier than its commit. + commitAt(t, r, w0.Add(-24*time.Hour)) r.Git("remote", "add", "origin", bare) return r } From 82ce238422adfe8d82a51d6b60826f9def0c5559 Mon Sep 17 00:00:00 2001 From: REPPL <77722411+REPPL@users.noreply.github.com> Date: Thu, 26 Nov 2026 20:46:07 +0000 Subject: [PATCH 09/16] fix: keep the spot-check's record populations listed and bounded A record group's population above 1,000 keys was kept by its hash alone, so the next draw could not tell its records from new ones: they joined every later population and items already judged were drawn again. A record group now takes at most 1,000 keys into one window, in key order, and leaves the rest for the next; only a landing group, whose members are its window's commits, is still kept by its hash, and a cycle whose record population is not listed does not verify. The draw no longer reads every record on the branch, which refused the whole read once the branch held 4,096 records, for good. It lists the names, drops the keys earlier verified cycles listed, and reads only the rest, each key by its four greatest names and half the read bound a group. A clone sharing this machine's mark that has only not fetched what another clone pushed was told the branch was rewritten. A copy that does not hold the mark's commit, or that the commit descends from, is now fetched first; only a copy origin answers that way is refused as rewritten. An opening may lie ten seconds past its commit's child, for a forge clock behind the writer's. A spotcheck block git could not read at a window's start counted the window by the bundled defaults; such a read now refuses the observation, and only a file that was read and refused takes the defaults. Refs: itd-2610301750162657 Assisted-by: Claude:claude-opus-5-5 --- .../development/brief/04-surfaces/38-land.md | 6 +- ...a-person-spot-checks-what-abcd-s-agents.md | 2 +- commands/land.md | 7 +- internal/core/spotcheck/afterlanding.go | 151 ++++++++++--- internal/core/spotcheck/bounds_test.go | 202 ++++++++++++++++++ internal/core/spotcheck/config.go | 42 +++- internal/core/spotcheck/config_test.go | 7 +- internal/core/spotcheck/cycle.go | 42 +++- internal/core/spotcheck/draw.go | 3 +- internal/core/spotcheck/groups.go | 4 +- internal/core/spotcheck/mark.go | 46 +++- internal/core/spotcheck/store.go | 4 +- 12 files changed, 454 insertions(+), 62 deletions(-) create mode 100644 internal/core/spotcheck/bounds_test.go diff --git a/.abcd/development/brief/04-surfaces/38-land.md b/.abcd/development/brief/04-surfaces/38-land.md index 7488609e2d..5c23bdd67a 100644 --- a/.abcd/development/brief/04-surfaces/38-land.md +++ b/.abcd/development/brief/04-surfaces/38-land.md @@ -472,7 +472,11 @@ checked against the pinned key, ten seconds in all), draws by HMAC over the round's randomness, and pushes the cycle over the tracking tip, tried once more after a refusal. Every cycle read back is verified the same way and set aside when it fails, and a branch that no longer holds this machine's high-water -mark is refused +mark is refused once a fetch confirms it (a copy only behind the mark, which +another clone on the machine moved, is fetched first). A draw reads only the +records no earlier cycle listed, and lists every record population whole, at +most 1,000 keys a window, the rest waiting for the next, so a later draw knows +each record already drawn from ([dcn-2611260013430233](../../../work/decisions/dcn-2611260013430233-the-technical-facilitator-under.md)). Only typed fields reach origin, and an observation that cannot draw writes nothing and leaves the landing proved. The branch takes no preflight receipt: diff --git a/.abcd/development/specs/open/spc-2610301925429250-a-person-spot-checks-what-abcd-s-agents.md b/.abcd/development/specs/open/spc-2610301925429250-a-person-spot-checks-what-abcd-s-agents.md index 50f18d793c..4e791e8b8f 100644 --- a/.abcd/development/specs/open/spc-2610301925429250-a-person-spot-checks-what-abcd-s-agents.md +++ b/.abcd/development/specs/open/spc-2610301925429250-a-person-spot-checks-what-abcd-s-agents.md @@ -32,7 +32,7 @@ Grounding, read on 30 October 2026: 1. **The store: one branch on the shared remote, written only by appending files.** A new package `internal/core/spotcheck` keeps the spot-check's record on `refs/heads/abcd-spotcheck` on `origin`, tracked at `refs/remotes/origin/abcd-spotcheck`, with `claim`'s `push` and `fetch` exported for it (one refspec added to the fetch the calling verb already makes). The branch is an orphan whose tree holds four folders of small JSON files, each written once and never edited: - `window-open.json`: The commit and time the first window opened (written by the first check that finds no cycle, which draws nothing). - - `cycles/.json`: One per draw: the window (`from_commit`, `to_commit`, `from_time`, `to_time`, `closed_by` = `days` or `changes`, `window` = the `days` and `changes` it was counted under, the observing site), the beacon (`url`, `chain_hash`, `round`, `signature`, `randomness`, `fetched_at`), the sample (`per_group` from the configuration, `size` applied, `why` = `full` or `halved`, the closed cycles counted), and per group the population's item keys (or, above 1,000 keys, the key range and the population's SHA-256) and the keys drawn, within 256 KiB, the most a cycle file may hold (a record holds 16 KiB at most). + - `cycles/.json`: One per draw: the window (`from_commit`, `to_commit`, `from_time`, `to_time`, `closed_by` = `days` or `changes`, `window` = the `days` and `changes` it was counted under, the observing site), the beacon (`url`, `chain_hash`, `round`, `signature`, `randomness`, `fetched_at`), the sample (`per_group` from the configuration, `size` applied, `why` = `full` or `halved`, the closed cycles counted), and per group the population's item keys (or, for a landing group above 1,000 keys, the key range and the population's SHA-256; a record group takes at most 1,000 keys into one window and leaves the rest for the next, so its population is always listed and a later draw knows what it drew from) and the keys drawn, within 256 KiB, the most a cycle file may hold (a record holds 16 KiB at most). - `items//--.json`: One per drawn item: its group, its key, the roles it is for, and the whole of its state at the draw, copied in (the landings row, the promise, the outcome and the withheld verdicts, approach 6), so what a person later sees as `then` never depends on a later read of history or the forge. - `handbacks/-.json` and `decisions/-.json`: The drain's hand-backs and the automated facilitator's decisions (approach 2). - `judgements//--..json`: One per judgement (approach 7). diff --git a/commands/land.md b/commands/land.md index 4a60169b65..cc18d331ed 100644 --- a/commands/land.md +++ b/commands/land.md @@ -356,7 +356,12 @@ unreachable, its signature wrong or another round than the one asked, the forge unread, the push refused twice) writes nothing, says why, and leaves the landing as proved; the next landing observed tries again. A store branch on origin that no longer holds what this machine last verified there, deleted or -rewritten, is refused in one line, and nothing is written over it. +rewritten, is refused in one line, and nothing is written over it; a copy this +checkout has only not fetched since another checkout on the machine read the +branch is fetched first, never refused. A draw reads only the records no +earlier cycle listed, and takes at most 1,000 hand-backs and 1,000 decisions +into one window, leaving the rest for the next, so no record is drawn from +twice however long the branch grows. **What `human` holds against.** The gate assumes agents keep the rules: it stops an agent merging by mistake, not one set on getting round it. The diff --git a/internal/core/spotcheck/afterlanding.go b/internal/core/spotcheck/afterlanding.go index aa0441edc1..31eea33b98 100644 --- a/internal/core/spotcheck/afterlanding.go +++ b/internal/core/spotcheck/afterlanding.go @@ -69,6 +69,15 @@ func AfterLanding(parent context.Context, o Observed) string { return "spot-check: " + err.Error() + "; nothing was drawn" } st, err := readWindow(ctx, o.Root, o.Now, tip) + if errors.Is(err, errBehind) { + // A copy behind the mark reaches the network for the one fetch that + // brings it up; a branch the fetch finds rewritten is refused there. + if _, err = fetchTracking(ctx, o.Root); err == nil { + st, err = readWindow(ctx, o.Root, o.Now, tip) + } else { + err = errors.New(redact(err)) + } + } if err != nil { return "spot-check: " + err.Error() + "; nothing was drawn" } @@ -276,7 +285,8 @@ func setAside(st windowState) string { // makeCycle draws the cycle closing st's window at cl: the landings of the // window (from st.from exclusive to cl.commit), the records origin's copy -// holds that no earlier verified cycle drew from, the size over the cycles +// holds that no earlier verified cycle drew from (windowRecords, which reads +// only those), the size over the cycles // before it, and an item file per drawn key; defaults says the bundled // defaults counted the window (windowConfig). pending are the typed records // this checkout carries in the same commit, read as origin's own. @@ -297,30 +307,6 @@ func makeCycle(ctx context.Context, o Observed, cfg Config, defaults bool, st wi return Cycle{}, nil, fmt.Errorf("the landings reader named %s, which is not a commit of the window", termsafe.Sanitize(r.Commit)) } } - rec, _, err := read(ctx, o.Root, TrackingRef) - if err != nil { - return Cycle{}, nil, err - } - var hbs []namedHandBack - var ds []namedDecision - for i, h := range rec.HandBacks { - hbs = append(hbs, namedHandBack{name: rec.handBackNames[i], h: h}) - } - for i, d := range rec.Decisions { - ds = append(ds, namedDecision{name: rec.decisionNames[i], d: d}) - } - for _, f := range pending { - var one Records - if !readRecord(&one, f.folder, f.name, f.data) { - continue - } - for _, h := range one.HandBacks { - hbs = append(hbs, namedHandBack{name: f.name, h: h}) - } - for _, d := range one.Decisions { - ds = append(ds, namedDecision{name: f.name, d: d}) - } - } seen := map[string]map[string]bool{} for _, c := range st.cycles { for _, g := range c.Groups { @@ -332,6 +318,10 @@ func makeCycle(ctx context.Context, o Observed, cfg Config, defaults bool, st wi } } } + hbs, ds, err := windowRecords(ctx, o.Root, st.files, pending, seen) + if err != nil { + return Cycle{}, nil, err + } groups, err := populations(rows, hbs, ds, seen) if err != nil { return Cycle{}, nil, err @@ -374,3 +364,114 @@ func makeCycle(ctx context.Context, o Observed, cfg Config, defaults bool, st wi } return c, items, nil } + +// maxFilesPerKey bounds the files of one record key a draw reads: records of +// one key are one item, and its greatest names are the ones it copies. +const maxFilesPerKey = 4 + +// windowRecords are the hand-backs and decisions a window draws from: of the +// records origin's copy holds (files, its listing) and those pending carries +// with the cycle, the ones whose key no earlier verified cycle's population of +// their group listed (seen). Only their files are read, so a draw reads what +// arrived since the cycles before it, never the store's whole life. Within a +// group the keys are taken in sorted order, at most maxListedKeys of them, +// each by its maxFilesPerKey greatest names, and their files at most half of +// maxReadFiles; a key beyond either bound waits for a later window, as a +// record that reaches origin late does. So every record population is listed +// whole, and the next draw knows each record already drawn from by its key. +// A file whose name is not a record's is never read, and one whose content +// does not read as its name gives is no record. +func windowRecords(ctx context.Context, root string, files map[string]entry, pending []file, seen map[string]map[string]bool) ([]namedHandBack, []namedDecision, error) { + type src struct { + dir, name string + // data is the pending copy's content, nil for origin's file. + data []byte + } + byKey := map[string]map[string]map[string]src{} + add := func(dir, name string, data []byte) { + g, re := GroupDrainHandBacks, handBackNameRe + if dir == DecisionsDir { + g, re = GroupFacilitatorDecisions, decisionNameRe + } + k := recordKey(name) + if !re.MatchString(name) || seen[g][k] { + return + } + if byKey[g] == nil { + byKey[g] = map[string]map[string]src{} + } + if byKey[g][k] == nil { + byKey[g][k] = map[string]src{} + } + byKey[g][k][name] = src{dir: dir, name: name, data: data} + } + for p, e := range files { + dir, name, _ := strings.Cut(p, "/") + if (dir != HandBacksDir && dir != DecisionsDir) || strings.Contains(name, "/") || e.typ != "blob" || e.mode != "100644" || e.size > maxRecordBytes { + continue + } + add(dir, name, nil) + } + for _, f := range pending { + if f.folder == HandBacksDir || f.folder == DecisionsDir { + // A pending copy replaces origin's file of its name. + add(f.folder, f.name, f.data) + } + } + var take []src + var paths []string + for _, g := range []string{GroupDrainHandBacks, GroupFacilitatorDecisions} { + keys := make([]string, 0, len(byKey[g])) + for k := range byKey[g] { + keys = append(keys, k) + } + slices.Sort(keys) + budget, used := max(maxReadFiles/2, 1), 0 + for i, k := range keys { + if i == maxListedKeys { + break + } + names := make([]string, 0, len(byKey[g][k])) + for n := range byKey[g][k] { + names = append(names, n) + } + slices.Sort(names) + slices.Reverse(names) + names = names[:min(len(names), maxFilesPerKey)] + if i > 0 && used+len(names) > budget { + break + } + used += len(names) + for _, n := range names { + s := byKey[g][k][n] + take = append(take, s) + if s.data == nil { + paths = append(paths, s.dir+"/"+s.name) + } + } + } + } + blobs, err := readMany(ctx, root, files, paths) + if err != nil { + return nil, nil, err + } + var hbs []namedHandBack + var ds []namedDecision + for _, s := range take { + data := s.data + if data == nil { + data = blobs[s.dir+"/"+s.name] + } + var one Records + if data == nil || !readRecord(&one, s.dir, s.name, data) { + continue + } + for _, h := range one.HandBacks { + hbs = append(hbs, namedHandBack{name: s.name, h: h}) + } + for _, d := range one.Decisions { + ds = append(ds, namedDecision{name: s.name, d: d}) + } + } + return hbs, ds, nil +} diff --git a/internal/core/spotcheck/bounds_test.go b/internal/core/spotcheck/bounds_test.go new file mode 100644 index 0000000000..86337222e8 --- /dev/null +++ b/internal/core/spotcheck/bounds_test.go @@ -0,0 +1,202 @@ +package spotcheck + +import ( + "context" + "os" + "path/filepath" + "slices" + "strings" + "testing" + "time" +) + +// plantHandBacks puts a typed hand-back for each issue on origin's store +// branch, made at at, and answers their population keys, sorted. +func (c *drawCase) plantHandBacks(at time.Time, issues ...string) []string { + c.t.Helper() + files := map[string]string{} + var keys []string + for _, issue := range issues { + f, err := handBack(issue, at).typed().file() + if err != nil { + c.t.Fatal(err) + } + files[f.path()] = string(f.data) + keys = append(keys, recordKey(f.name)) + } + c.plant(files) + slices.Sort(keys) + return keys +} + +// groupOf is cy's draw of group. +func groupOf(t *testing.T, cy Cycle, group string) GroupDraw { + t.Helper() + for _, g := range cy.Groups { + if g.Group == group { + return g + } + } + t.Fatalf("cycle %s holds no %s group", cy.ID, group) + return GroupDraw{} +} + +// drawsTwoWindows opens the first window, runs between before it closes, +// draws it, runs after, and draws the second, answering both cycles. +func (c *drawCase) drawsTwoWindows(between, after func()) (Cycle, Cycle) { + c.t.Helper() + latest := "1000" + c.serveRounds(&latest) + c.openWindow(w0) + between() + c.closeWindow() + if note := c.observe(q1000.Add(time.Hour)); !strings.Contains(note, "drew cycle") { + c.t.Fatalf("the first draw said %q", note) + } + first := c.newestCycle() + after() + latest = "202600" + c.landAt(1, q202600.Add(time.Second)) + if note := c.observe(q202600.Add(time.Hour)); !strings.Contains(note, "drew cycle") { + c.t.Fatalf("the second draw said %q", note) + } + return first, c.newestCycle() +} + +// TestARecordPopulationIsListedAndNeverDrawnFromTwice: a window whose +// hand-backs outnumber what a population lists takes the first of them in +// key order and leaves the rest for the next window, so each cycle lists its +// population, every record is in exactly one population, and nothing drawn +// is drawn again. +func TestARecordPopulationIsListedAndNeverDrawnFromTwice(t *testing.T) { + saved := maxListedKeys + maxListedKeys = 3 + t.Cleanup(func() { maxListedKeys = saved }) + c := newDrawCase(t) + var want []string + first, second := c.drawsTwoWindows(func() { + want = c.plantHandBacks(w0.Add(time.Hour), "iss-70", "iss-71", "iss-72", "iss-73", "iss-74") + }, func() {}) + var listed []string + drawn := map[string]int{} + for _, cy := range []Cycle{first, second} { + g := groupOf(t, cy, GroupDrainHandBacks) + if len(g.Population.Keys) != g.Population.Count || g.Population.SHA256 != "" || g.Population.Count > maxListedKeys { + t.Fatalf("cycle %s keeps its hand-backs as %+v; want them listed, at most %d", cy.ID, g.Population, maxListedKeys) + } + listed = append(listed, g.Population.Keys...) + for _, k := range g.Drawn { + drawn[k]++ + } + } + slices.Sort(listed) + if !slices.Equal(listed, want) { + t.Fatalf("the two populations list %v; want each of %v once", listed, want) + } + for k, n := range drawn { + if n > 1 { + t.Fatalf("%s was drawn %d times", k, n) + } + } + if got := groupOf(t, first, GroupDrainHandBacks).Population.Keys; !slices.Equal(got, want[:3]) { + t.Fatalf("the first window took %v; want the first three keys %v", got, want[:3]) + } +} + +// TestADrawReadsOnlyTheRecordsNoEarlierCycleListed: once a cycle lists the +// hand-backs on origin's branch, the next draw reads only what arrived since, +// so a branch holding more records than one read takes is drawn, from the +// new records alone. +func TestADrawReadsOnlyTheRecordsNoEarlierCycleListed(t *testing.T) { + c := newDrawCase(t) + var fresh []string + _, second := c.drawsTwoWindows(func() { + c.plantHandBacks(w0.Add(time.Hour), "iss-80", "iss-81", "iss-82", "iss-83", "iss-84", "iss-85") + }, func() { + saved := maxReadFiles + maxReadFiles = 4 + t.Cleanup(func() { maxReadFiles = saved }) + fresh = c.plantHandBacks(q1000.Add(2*time.Hour), "iss-90", "iss-91") + }) + if got := groupOf(t, second, GroupDrainHandBacks).Population.Keys; !slices.Equal(got, fresh) { + t.Fatalf("the second window drew from %v; want only the records that arrived since, %v", got, fresh) + } +} + +// TestASecondCloneBehindOriginIsNotToldTheBranchWasRewritten: two clones of +// one origin under one home share the machine's mark. A clone that has not +// fetched what the other pushed is behind, not rewritten: its observation +// fetches the branch and goes on. +func TestASecondCloneBehindOriginIsNotToldTheBranchWasRewritten(t *testing.T) { + latest := "1000" + c := newDrawCase(t) + c.serveRounds(&latest) + b := clone(t, c.bare) + observeB := func(at time.Time) string { + b.Git("fetch", "-q", "origin", "main") + return AfterLanding(t.Context(), Observed{Root: b.Root(), Default: "main", Site: SiteLand, Now: at}) + } + c.openWindow(w0) + if note := observeB(w0.Add(time.Hour)); strings.Contains(note, "rewritten") || strings.Contains(note, "first window") { + t.Fatalf("a clone that never fetched the branch said %q", note) + } + if got := strings.TrimSpace(b.Git("rev-parse", TrackingRef)); got != c.originTip() { + t.Fatalf("the clone's copy is %s; want origin's %s fetched", got, c.originTip()) + } + c.land(2) + c.closeWindow() + if note := c.observe(q1000.Add(time.Hour)); !strings.Contains(note, "drew cycle") { + t.Fatalf("the first clone's draw said %q", note) + } + if note := observeB(q1000.Add(2 * time.Hour)); strings.Contains(note, "rewritten") || strings.Contains(note, "drew cycle") { + t.Fatalf("a clone behind the drawn cycle said %q", note) + } + if got := strings.TrimSpace(b.Git("rev-parse", TrackingRef)); got != c.originTip() { + t.Fatalf("the clone's copy is %s; want origin's %s fetched", got, c.originTip()) + } +} + +// TestAnOpeningWithinTheForgesLeadIsKept: an opening written by a clock a few +// seconds ahead of the forge's, whose commit's child the forge then commits +// within those seconds, is still the window's start. +func TestAnOpeningWithinTheForgesLeadIsKept(t *testing.T) { + c := newDrawCase(t) + at := w0.Add(3 * time.Second) + if note := c.observe(at); !strings.Contains(note, "first window opened") { + t.Fatalf("the first check said %q", note) + } + opened := c.originOpening() + c.landAt(1, w0.Add(time.Second)) + if note := c.observe(w0.Add(time.Hour)); note != "" { + t.Fatalf("the observation after the child said %q", note) + } + if w := c.originOpening(); w.Commit != opened.Commit || !w.At.Equal(at) { + t.Fatalf("origin's opening is %+v; want %+v kept", w, opened) + } +} + +// TestAPassingReadFailureOfTheBlockIsNoDefaults: a block git cannot read at +// the window's start, for a reason that says nothing of the file, is an +// error, never a window counted by the bundled defaults: the observation +// refuses and draws nothing. +func TestAPassingReadFailureOfTheBlockIsNoDefaults(t *testing.T) { + c := newDrawCase(t) + c.r.Write(".abcd/config.json", `{"spotcheck":{"window_days":3}}`+"\n") + c.r.Git("add", "-A") + start := c.landAt(1, w0.Add(-time.Hour)) + c.openWindow(w0) + tree := strings.TrimSpace(c.r.Git("rev-parse", start+"^{tree}")) + if err := os.Remove(filepath.Join(c.r.Root(), ".git", "objects", tree[:2], tree[2:])); err != nil { + t.Fatal(err) + } + cfg, why, err := windowConfig(context.Background(), c.r.Root(), start) + if err == nil { + t.Fatalf("windowConfig over a tree git cannot read = %+v, %q, nil; want an error", cfg, why) + } + if !strings.Contains(err.Error(), "was not read") || why != "" { + t.Fatalf("the error is %v (why %q); want the read named as not made", err, why) + } + if note := c.observe(w0.Add(time.Hour)); strings.Contains(note, "bundled defaults") || !strings.Contains(note, "nothing was drawn") { + t.Fatalf("the observation over a block git cannot read said %q", note) + } +} diff --git a/internal/core/spotcheck/config.go b/internal/core/spotcheck/config.go index e961161eb3..07111b7e83 100644 --- a/internal/core/spotcheck/config.go +++ b/internal/core/spotcheck/config.go @@ -7,6 +7,7 @@ package spotcheck import ( "context" + "errors" "fmt" "github.com/intentdriven/abcd/internal/core/layered" @@ -37,8 +38,8 @@ type Config struct { // readConfig resolves the spotcheck block. A misspelt key, and a value out // of its bounds or not a whole number, is refused naming its file and key, // never replaced by the default. -func readConfig(r layered.Roots) (Config, error) { - s, err := layered.Load(layered.Config, r) +func readConfig(ctx context.Context, r layered.Roots) (Config, error) { + s, err := layered.LoadContext(ctx, layered.Config, r) if err != nil { return Config{}, err } @@ -83,19 +84,44 @@ func between(lo, hi int, what string) func(int) error { // of its bounds, counts that window by the bundled defaults, and why says // why, "" when the block read: the window is still drawn, the same by every // reader, and the next window, starting at a later commit, reads the block -// as that commit holds it. A commit this checkout does not hold is an error. +// as that commit holds it. A commit this checkout does not hold is a +// notHeldError. +// A read that failed for a reason that says nothing of the file (a git that +// did not answer, or ctx ended) is an error of its own and never the +// defaults, since another reader, or this one again, would read the block. func windowConfig(ctx context.Context, root, commit string) (c Config, why string, err error) { if _, err := gitutil.RunCappedBytesAsStoredContext(ctx, root, "", 256, "rev-parse", "--verify", "--quiet", commit+"^{commit}", "--"); err != nil { - return Config{}, "", fmt.Errorf("the spot-check's window starts at %s, which this checkout does not hold", commit[:12]) + if ctx.Err() != nil { + return Config{}, "", fmt.Errorf("the spot-check's window start %s was not read: %s", commit[:12], redact(ctx.Err())) + } + return Config{}, "", notHeldError{commit[:12]} } r, _ := layered.RootsFor(root) - c, err = readConfig(layered.Roots{Repo: r.Repo, RepoAt: commit, RepoAtName: commit[:12], RepoAtAsStored: true, HomeRefused: true}) - if err != nil { - return Config{WindowDays: DefaultWindowDays, PerGroup: DefaultPerGroup}, redact(err), nil + c, err = readConfig(ctx, layered.Roots{Repo: r.Repo, RepoAt: commit, RepoAtName: commit[:12], RepoAtAsStored: true, HomeRefused: true}) + var ue *layered.UnreadError + switch { + case err == nil: + return c, "", nil + case ctx.Err() != nil || errors.As(err, &ue) && ue.GitFailed(): + return Config{}, "", fmt.Errorf("the spotcheck block at the window's start was not read (%s), so the window cannot be counted yet", redact(err)) } - return c, "", nil + return Config{WindowDays: DefaultWindowDays, PerGroup: DefaultPerGroup}, redact(err), nil } +// notHeldError is a window's start this checkout does not hold, by its +// short name. +type notHeldError struct{ short string } + +func (e notHeldError) Error() string { + return "the spot-check's window starts at " + e.short + ", which this checkout does not hold" +} + +// unreadError is a cycle whose check could not be made for a passing +// reason: the read that refuses the observation, never a cycle set aside. +type unreadError struct{ err error } + +func (e *unreadError) Error() string { return e.err.Error() } + // defaultsNote is the note's tail for a window counted by the bundled // defaults because its block did not read (why), "" for none. func defaultsNote(why string) string { diff --git a/internal/core/spotcheck/config_test.go b/internal/core/spotcheck/config_test.go index 6a2286c862..b9fae34898 100644 --- a/internal/core/spotcheck/config_test.go +++ b/internal/core/spotcheck/config_test.go @@ -1,6 +1,7 @@ package spotcheck import ( + "context" "os" "path/filepath" "strings" @@ -26,14 +27,14 @@ func configRoots(t *testing.T, body string) layered.Roots { } func TestConfigDefaults(t *testing.T) { - c, err := readConfig(configRoots(t, "")) + c, err := readConfig(context.Background(), configRoots(t, "")) if err != nil { t.Fatal(err) } if c != (Config{WindowDays: 7, WindowChanges: 0, PerGroup: 10}) { t.Fatalf("the bundled configuration is %+v", c) } - c, err = readConfig(configRoots(t, `{"spotcheck":{"window_days":3,"window_changes":50,"per_group":4}}`)) + c, err = readConfig(context.Background(), configRoots(t, `{"spotcheck":{"window_days":3,"window_changes":50,"per_group":4}}`)) if err != nil || c != (Config{WindowDays: 3, WindowChanges: 50, PerGroup: 4}) { t.Fatalf("readConfig = %+v, %v", c, err) } @@ -52,7 +53,7 @@ func TestPerGroupBounds(t *testing.T) { `{"spotcheck":{"window_changes":100001}}`: "window_changes", `{"spotcheck":{"per_groups":5}}`: "per_groups", } { - if _, err := readConfig(configRoots(t, body)); err == nil || !strings.Contains(err.Error(), key) { + if _, err := readConfig(context.Background(), configRoots(t, body)); err == nil || !strings.Contains(err.Error(), key) { t.Errorf("%s: err %v; want a refusal naming %s", body, err, key) } } diff --git a/internal/core/spotcheck/cycle.go b/internal/core/spotcheck/cycle.go index 0e768d2747..abb2eefe60 100644 --- a/internal/core/spotcheck/cycle.go +++ b/internal/core/spotcheck/cycle.go @@ -61,8 +61,13 @@ func drawSeed(c Cycle) string { // maxListedKeys is the most keys a population lists whole: above it, the // cycle keeps the first and last key and the SHA-256 of the sorted keys, one -// per line. Four groups listed whole stay within maxCycleBytes. -const maxListedKeys = 1000 +// per line. Four groups listed whole stay within maxCycleBytes. Only a +// landing group, whose members are its window's commits, is ever kept by its +// hash: a record group takes at most this many keys into one window and +// leaves the rest for the next (windowRecords), since a later draw knows the +// records already drawn from only by the keys a cycle lists. A test lowers +// it. +var maxListedKeys = 1000 // maxCycleBytes bounds one cycle file, on write and on read, as the pre-push // hook bounds it: a cycle lists its populations, so it is allowed more than a @@ -201,6 +206,14 @@ type windowState struct { // written then, whatever its file says. const clockSkew = 5 * time.Minute +// forgeLead is how far past its commit's child an opening may lie and still +// be read. The writer opens at its own clock, and the forge commits the next +// landing by its own: a writer's clock a few seconds ahead of the forge's, +// with a landing inside those seconds, would otherwise set an honest opening +// aside. It gives a writer those same few seconds of choice over the first +// window's start, whose close lies in the future at a round nobody knows yet. +const forgeLead = 10 * time.Second + // errAhead is a cycle whose window this checkout's copy of the default // branch does not close yet: drawn, it may be, from a tip not fetched here. var errAhead = errors.New("its window does not close on this checkout's copy of the default branch") @@ -209,7 +222,7 @@ var errAhead = errors.New("its window does not close on this checkout's copy of // up to tip, as stored. Its moment is its writer's word, held to the line: no // later than now allows, no earlier than its commit was committed, and, once // that commit has its first-parent child on the line, no later than the -// child was committed; an honest writer opens at the tip it read, between +// child was committed, give or take forgeLead; an honest writer opens at the tip it read, between // the two. why is the bound an opening fails, "" when it holds: one that // fails is no window's start, and the next observer opens the window afresh // over it. An opening at a commit the line does not hold, or not on its @@ -247,7 +260,7 @@ func verifyOpening(ctx context.Context, root, tip string, w WindowOpen, now time if err != nil { return false, "", errors.New("reading the spot-check's opening: git answered a line of an unexpected shape") } - if w.At.After(time.Unix(secs, 0)) { + if w.At.After(time.Unix(secs, 0).Add(forgeLead)) { return false, "it opens after its commit's child on the default branch was committed", nil } return true, "", nil @@ -280,7 +293,7 @@ func readWindow(ctx context.Context, root string, now time.Time, tip string) (wi if err != nil { return windowState{}, err } - if err := holdsMark(ctx, root, tracking); err != nil || tracking == "" { + if err := holdsMark(ctx, root, tracking, false); err != nil || tracking == "" { return windowState{}, err } m, marked, err := readMark(ctx, root) @@ -331,6 +344,12 @@ func readWindow(ctx context.Context, root string, now time.Time, tip string) (wi default: err = verifyCycle(ctx, root, tip, c, id, st.from, st.fromTime, now) } + var unread *unreadError + if errors.As(err, &unread) { + // A read that failed for a passing reason sets nothing aside: + // the whole observation refuses, and the next one reads again. + return windowState{}, unread.err + } if errors.Is(err, errAhead) { st.unverified = append(st.unverified, "cycle "+id+" on origin cannot be checked against this checkout's copy of the default branch yet, so it was set aside") continue @@ -379,8 +398,9 @@ func (st windowState) mark(commit string) mark { // signature that of the round its close fixes under the pinned key, its // sample size one the size rule gives, every landing it lists a commit of // the window, and each drawn list the one that round's randomness gives over -// its population, keyed by the window alone (drawSeed). A population kept by -// its hash alone is checked by its count. What it cannot check, which records +// its population, keyed by the window alone (drawSeed). A record group's +// population is listed, never kept by its hash (windowRecords); a landing +// group's kept by its hash alone is checked by its count. What it cannot check, which records // a holder of push rights listed and why a size was halved, is the residual // adr-2611251806496719 names. func verifyCycle(ctx context.Context, root, tip string, c Cycle, id, from string, fromTime, now time.Time) error { @@ -393,8 +413,12 @@ func verifyCycle(ctx context.Context, root, tip string, c Cycle, id, from string return errors.New("it closes after now") } cfg, why, err := windowConfig(ctx, root, from) - if err != nil { + var notHeld notHeldError + switch { + case errors.As(err, ¬Held): return errors.New("its window's start is not held here") + case err != nil: + return &unreadError{err} } if c.Window.Days != cfg.WindowDays || c.Window.Changes != cfg.WindowChanges || c.Sample.PerGroup != cfg.PerGroup || c.Window.Defaults != (why != "") { return errors.New("its window is not the one the default branch configures") @@ -435,6 +459,8 @@ func verifyCycle(ctx context.Context, root, tip string, c Cycle, id, from string case (g.Group == GroupDrainLanded || g.Group == GroupAutomaticMerges) && slices.ContainsFunc(p.Keys, func(k string) bool { return !inWindow[k] }): return fmt.Errorf("its %s population names a commit outside its window", g.Group) + case (g.Group == GroupDrainHandBacks || g.Group == GroupFacilitatorDecisions) && p.Count > maxListedKeys: + return fmt.Errorf("its %s population is not listed, so a later draw could not tell its records from new ones", g.Group) case p.Count <= maxListedKeys && (len(p.Keys) != p.Count || !slices.IsSorted(p.Keys) || len(slices.Compact(slices.Clone(p.Keys))) != p.Count): return fmt.Errorf("its %s population does not list its keys", g.Group) case p.Count <= maxListedKeys && !slices.Equal(g.Drawn, drawKeys(randomness, drawSeed(c), g.Group, p.Keys, s.Size)): diff --git a/internal/core/spotcheck/draw.go b/internal/core/spotcheck/draw.go index 7e85edb675..db20ca33f5 100644 --- a/internal/core/spotcheck/draw.go +++ b/internal/core/spotcheck/draw.go @@ -47,7 +47,8 @@ func drawKeys(randomness []byte, seed, group string, keys []string, size int) [] // population is a group's keys as a cycle keeps them: whole up to // maxListedKeys, and above it by the first and last key and the SHA-256 of -// the sorted keys, one per line. +// the sorted keys, one per line. Only a landing group reaches the second +// form: a record group never takes more than maxListedKeys (windowRecords). func population(keys []string) Population { sorted := slices.Clone(keys) slices.Sort(sorted) diff --git a/internal/core/spotcheck/groups.go b/internal/core/spotcheck/groups.go index 593416da8e..4e6b958d82 100644 --- a/internal/core/spotcheck/groups.go +++ b/internal/core/spotcheck/groups.go @@ -177,7 +177,9 @@ func recordKey(name string) string { // key no earlier verified cycle's population of their group held (seen, by // group). Membership is by arrival on the store's branch, never by the time // a record names, so a record that reaches origin after its window was drawn -// is drawn from in the next, and every record is in exactly one population. +// is drawn from in the next, and every record is in exactly one population: +// windowRecords leaves out what an earlier population listed, and lists no +// more than maxListedKeys, so every record population stays listed. // A row whose approval was not read from the forge refuses them all. Within // a group, records of one key are one candidate, the record of the greatest // file name copied. diff --git a/internal/core/spotcheck/mark.go b/internal/core/spotcheck/mark.go index 8116916d59..0ba91a0ba1 100644 --- a/internal/core/spotcheck/mark.go +++ b/internal/core/spotcheck/mark.go @@ -125,23 +125,47 @@ func writeMark(ctx context.Context, root string, m mark) error { return fsutil.WriteFileAtomicInRoot(dir, markLeaf, data, abcdhome.FileMode) } -// holdsMark is nil when tracking, origin's copy as last fetched ("" for -// none), holds the mark's commit, and the refusal otherwise; nil too when -// this machine keeps no mark. -func holdsMark(ctx context.Context, root, tracking string) error { +// errBehind is origin's copy as this checkout last fetched it standing +// behind the mark: another checkout of the repository on this machine, which +// shares the mark, read a later copy, or a push's own move of the tracking +// ref did not take. It is answered by a fetch, never as a rewritten branch. +var errBehind = errors.New("this checkout's copy of the spot-check's branch is behind the one this machine last verified, so it is fetched first") + +// holdsMark is nil when tracking, origin's copy ("" for none), holds the +// mark's commit, and the refusal otherwise; nil too when this machine keeps +// no mark. fetched says tracking is what origin answered just now: a copy +// not fetched that holds no such commit, or that the mark's commit descends +// from, is errBehind, since a fetch may bring it; once fetched, any copy +// that does not hold it was deleted or rewritten on origin. +func holdsMark(ctx context.Context, root, tracking string, fetched bool) error { m, ok, err := readMark(ctx, root) if err != nil || !ok { return err } - if tracking == "" { - return rewritten("the copy (" + m.Commit[:12] + ")") - } if tracking == m.Commit { return nil } - held, err := isAncestor(ctx, root, m.Commit, tracking) - if err != nil || !held { - return rewritten("the copy (" + m.Commit[:12] + ")") + if tracking != "" { + if held, err := isAncestor(ctx, root, m.Commit, tracking); err == nil && held { + return nil + } + } + if !fetched && behind(ctx, root, m.Commit, tracking) { + return errBehind + } + return rewritten("the copy (" + m.Commit[:12] + ")") +} + +// behind reports whether tracking, a copy not fetched just now, may only be +// behind the mark's commit: there is no copy, the commit is not in this +// checkout's object store, or the commit descends from the copy. +func behind(ctx context.Context, root, commit, tracking string) bool { + if tracking == "" { + return true + } + if _, err := gitutil.RunCappedBytesAsStoredContext(ctx, root, "", 256, "cat-file", "-e", commit+"^{commit}"); err != nil { + return ctx.Err() == nil } - return nil + on, err := isAncestor(ctx, root, tracking, commit) + return err == nil && on } diff --git a/internal/core/spotcheck/store.go b/internal/core/spotcheck/store.go index 74d636b357..2d04db7737 100644 --- a/internal/core/spotcheck/store.go +++ b/internal/core/spotcheck/store.go @@ -1303,9 +1303,9 @@ func fetchTracking(ctx context.Context, root string) (string, error) { if err != nil { return "", err } - return tracking, holdsMark(ctx, root, tracking) + return tracking, holdsMark(ctx, root, tracking, true) } - if err := holdsMark(ctx, root, ""); err != nil { + if err := holdsMark(ctx, root, "", true); err != nil { return "", err } if old, err := storeRef(ctx, root, TrackingRef); err == nil && old != "" { From 2a5a3b09f797947dbbea274b5908bc2ed4e2ee9b Mon Sep 17 00:00:00 2001 From: REPPL <77722411+REPPL@users.noreply.github.com> Date: Thu, 26 Nov 2026 20:46:18 +0000 Subject: [PATCH 10/16] docs: bring the spot-check's trust decision up to its ADR The decision now says what the ADR says: the first window's start is the opening's word within the bounds every reader checks, an unreadable block counts a window by the bundled defaults and the cycle records it, a read that failed for a passing reason refuses instead, a record population is listed whole, and a copy only behind the mark is fetched, not refused. Refs: itd-2610301750162657 Assisted-by: Claude:claude-opus-5-5 --- .../dcn-2611260013430233-the-technical-facilitator-under.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.abcd/work/decisions/dcn-2611260013430233-the-technical-facilitator-under.md b/.abcd/work/decisions/dcn-2611260013430233-the-technical-facilitator-under.md index 3e004de921..fb4454a733 100644 --- a/.abcd/work/decisions/dcn-2611260013430233-the-technical-facilitator-under.md +++ b/.abcd/work/decisions/dcn-2611260013430233-the-technical-facilitator-under.md @@ -3,4 +3,4 @@ id: dcn-2611260013430233 slug: the-technical-facilitator-under date: 2026-11-26 --- -2026-11-26 — The technical facilitator, under facilitator.mode auto, ruled how the spot-check trusts its own store (itd-2610301750162657, adr-2611251806496719). A cycle read back from abcd-spotcheck is verified on every read and never trusted. Its window is recomputed, not read from it: the spotcheck block as the default branch stores it at the window's start, the repository layer alone, must be the cycle's window and per-group values, and the close the default branch's first-parent line gives must be the cycle's bound, end commit and moment. Then its beacon signature verifies under the pinned quicknet key, its round is the first at or after that close on the chain's pinned genesis and period, every landing it lists is a commit of its window, its drawn lists are recomputed from that randomness over its listed populations, keyed by the window's start commit and close alone and never by the cycle's id, and its close is no later than the reader's clock plus five minutes. A cycle that fails is set aside, named in the draw's note, and its window is drawn afresh; the pre-push hook still admits it, and nothing reads it as true. A window's close is read from origin's default branch alone, so its round, its id and its draw are the same whoever draws it and whenever: a round not yet published is reported as not yet drawable and asked for no sooner, and there is no preview and no retry to choose a draw by. Each machine keeps a high-water mark of the last copy it verified in the person's home store; a branch that no longer holds it, deleted or rewritten, is refused in one line and no first window is opened over it, and .abcd/work/rulesets/spotcheck-protection.json mirrors the ruleset against deletion and forced pushes that the person applies. Hand-backs and decisions join a population by arrival on the branch, so a record that reaches origin after its window was drawn is drawn from in the next, and every record is in exactly one population. A judgement counts toward the size only when it reads as one, of this schema version, naming the cycle, item and role its path names, with a verdict of sound or wrong. Accepted as residual: a holder of the person's push rights can still write a cycle that verifies but lists or leaves out records of its choosing, or hold a record back until a draw is known; the halving of the sample trusts every holder of push rights until the review lane settles who may judge; a window closed by changes takes its close from a committer time. The spotcheck block is read at the commit a window starts at, the repository layer alone, so neither an uncommitted value, a landing inside the window, nor one machine's own layer sizes a draw. circl stays at v1.6.3, the version the module graph already required, as the facilitator ruled before; the spec's v1.6.5 is corrected to it. +2026-11-26 — The technical facilitator, under facilitator.mode auto, ruled how the spot-check trusts its own store (itd-2610301750162657, adr-2611251806496719). A cycle read back from abcd-spotcheck is verified on every read and never trusted. Its window is recomputed, not read from it: the spotcheck block as the default branch stores it at the window's start, the repository layer alone, must be the cycle's window and per-group values, and the close the default branch's first-parent line gives must be the cycle's bound, end commit and moment. Then its beacon signature verifies under the pinned quicknet key, its round is the first at or after that close on the chain's pinned genesis and period, every landing it lists is a commit of its window, its drawn lists are recomputed from that randomness over its listed populations, keyed by the window's start commit and close alone and never by the cycle's id, and its close is no later than the reader's clock plus five minutes. A cycle that fails is set aside, named in the draw's note, and its window is drawn afresh; the pre-push hook still admits it, and nothing reads it as true. A window's close is read from origin's default branch and the window's start alone, so its round, its id and its draw are the same whoever draws it and whenever. From the second window on, the start is a verified cycle's close; the first window's start is the opening's own word, within bounds every reader checks: no later than the reader's clock allows, no earlier than its commit was committed, and no later than that commit's first-parent child on the default branch was, give or take ten seconds for a forge clock behind the writer's. An opening outside them is set aside, named, and opened afresh by the next observer, and the mark keeps an opening only once that child has confirmed it. A round not yet published is reported as not yet drawable and asked for no sooner, and there is no preview and no retry to choose a draw by: nothing about the moment a draw runs chooses it. Each machine keeps a high-water mark of the last copy it verified in the person's home store; a branch that no longer holds it, deleted or rewritten, is refused in one line and no first window is opened over it (a copy that is only behind the mark, as a second clone on the machine is, is fetched first and never called rewritten), and .abcd/work/rulesets/spotcheck-protection.json mirrors the ruleset against deletion and forced pushes that the person applies. Hand-backs and decisions join a population by arrival on the branch, so a record that reaches origin after its window was drawn is drawn from in the next, and every record is in exactly one population: a record group lists its population whole, at most 1,000 keys a window with the rest left for the next, and a draw reads only the records no earlier verified cycle listed. A judgement counts toward the size only when it reads as one, of this schema version, naming the cycle, item and role its path names, with a verdict of sound or wrong. Accepted as residual: a holder of the person's push rights can still write a cycle that verifies but lists or leaves out records of its choosing, or hold a record back until a draw is known; the halving of the sample trusts every holder of push rights until the review lane settles who may judge; a window closed by changes takes its close from a committer time. The spotcheck block is read at the commit a window starts at, the repository layer alone, so neither an uncommitted value, a landing inside the window, nor one machine's own layer sizes a draw. A block that does not read there, a file that does not parse or a value misspelt or out of its bounds, counts that window by the bundled defaults, and the cycle records that it did; a read that failed for a passing reason, a git that did not answer, refuses the observation instead, so no reader counts a window by the defaults that another reads by the block. circl stays at v1.6.3, the version the module graph already required, as the facilitator ruled before; the spec's v1.6.5 is corrected to it. From d21e779734069ead53c0fbb713298efd248f7aa5 Mon Sep 17 00:00:00 2001 From: REPPL <77722411+REPPL@users.noreply.github.com> Date: Thu, 26 Nov 2026 20:47:40 +0000 Subject: [PATCH 11/16] feat: observe the spot-check at a drain move The spec names a drain move's fetch of origin's default branch as the third observing site, and the site waited for the drain-bundles change, which has landed. A move that read origin now observes the branch it fetched once, after its records are kept, and the observation's line joins the move's next; a move that could not read origin observes nothing. Refs: itd-2610301750162657 Assisted-by: Claude:claude-opus-5-5 --- commands/drain.md | 5 +++ internal/core/implement/loop/drain.go | 12 +++++ .../implement/loop/drain_spotcheck_test.go | 45 +++++++++++++++++++ 3 files changed, 62 insertions(+) create mode 100644 internal/core/implement/loop/drain_spotcheck_test.go diff --git a/commands/drain.md b/commands/drain.md index 91ec6232ce..8058f9e0a3 100644 --- a/commands/drain.md +++ b/commands/drain.md @@ -1159,6 +1159,11 @@ hand-back's, and a lane's that opened none); `next` is the one move to make. A d that ends with every lane ended and none in a pull request says so in `next` as a normal ending; one that stops with a lane still in progress does not. +A move that read origin's default branch then observes it for the spot-check, +as `abcd land` observes a landing (`commands/land.md`, "The spot-check at a +landing"): the observation's line joins `next`, and nothing of the move waits on +it or changes with it. A move that could not read origin observes nothing. + Each move also keeps the spot-check's record of what the drain decided with no person involved: every hand-back it routed and every judgement a routed model answered, each as one file on this checkout's local copy of the spot-check's diff --git a/internal/core/implement/loop/drain.go b/internal/core/implement/loop/drain.go index c192840c14..a69575947e 100644 --- a/internal/core/implement/loop/drain.go +++ b/internal/core/implement/loop/drain.go @@ -42,6 +42,7 @@ import ( "github.com/intentdriven/abcd/internal/core/landings" "github.com/intentdriven/abcd/internal/core/recordid" "github.com/intentdriven/abcd/internal/core/runner" + "github.com/intentdriven/abcd/internal/core/spotcheck" "github.com/intentdriven/abcd/internal/fsutil" "github.com/intentdriven/abcd/internal/gitutil" "github.com/intentdriven/abcd/internal/localtier" @@ -789,6 +790,17 @@ func drainMove(repoRoot string, o Options, d DrainOptions, flags paceFlags, rule if note := spotcheckRecords(d.Context, repoRoot, st); note != "" { res.Next = joinNext(res.Next, note) } + // The spot-check observes origin's default branch as this move + // fetched it, the third observing site (spc-2610301925429250 + // approach 3); its note is the move's to read, and nothing of the + // move waits on it. A move that could not read origin observes + // nothing. + if origin != nil { + def := strings.TrimPrefix(origin.Ref, claim.Remote+"/") + if sc := observeLanding(ctxOr(d.Context), spotcheck.Observed{Root: repoRoot, Default: def, Site: spotcheck.SiteDrain}); sc != "" { + res.Next = joinNext(res.Next, sc) + } + } // The lanes in progress take a new pace only once the move has // written it, so a move refused before here takes none. if repace != nil { diff --git a/internal/core/implement/loop/drain_spotcheck_test.go b/internal/core/implement/loop/drain_spotcheck_test.go new file mode 100644 index 0000000000..1211c01a09 --- /dev/null +++ b/internal/core/implement/loop/drain_spotcheck_test.go @@ -0,0 +1,45 @@ +package loop + +import ( + "context" + "path/filepath" + "strings" + "testing" + + "github.com/intentdriven/abcd/internal/core/spotcheck" +) + +// TestADrainMoveIsObservedOnce: a drain move that read origin's default +// branch observes it for the spot-check once, from the drain's checkout at +// that branch, and the observation's note joins the move's; a move that could +// not read origin is not observed. +func TestADrainMoveIsObservedOnce(t *testing.T) { + var seen []spotcheck.Observed + saved := observeLanding + t.Cleanup(func() { observeLanding = saved }) + observeLanding = func(_ context.Context, o spotcheck.Observed) string { + seen = append(seen, o) + return "spot-check: observed" + } + repo, _ := reservingDrainRepo(t, "commands/drain.md") + res, err := Drain(repo.Root(), Options{}, DrainOptions{}) + if err != nil { + t.Fatal(err) + } + if len(seen) != 1 || seen[0].Site != spotcheck.SiteDrain || seen[0].Root != repo.Root() || seen[0].Default != "main" { + t.Fatalf("the move was observed as %+v; want once, from the drain site at main", seen) + } + if !strings.Contains(res.Next, "spot-check: observed") { + t.Fatalf("the move's next = %q; want the observation's note in it", res.Next) + } + + seen = nil + gone, _ := reservingDrainRepo(t, "commands/drain.md") + gone.Git("remote", "set-url", "origin", filepath.Join(t.TempDir(), "gone.git")) + if _, err := Drain(gone.Root(), Options{}, DrainOptions{}); err != nil { + t.Fatal(err) + } + if len(seen) != 0 { + t.Fatalf("a move that could not read origin was observed: %+v", seen) + } +} From f2e23fa2c8be30fadca4bccb0d424e205d644ce4 Mon Sep 17 00:00:00 2001 From: REPPL <77722411+REPPL@users.noreply.github.com> Date: Thu, 26 Nov 2026 21:21:05 +0000 Subject: [PATCH 12/16] fix: check the spot-check hook's object names without a regex test Main's guard reads the pre-push hook's [[ =~ ]] test over the fields read from a command substitution as running a program it cannot name, so the script corpus test refused the hook after the merge. The hook now checks the object name and size with case patterns and lengths, admitting the same values. Refs: itd-2610301750162657 Assisted-by: Claude:claude-opus-5-5 --- .githooks/pre-push | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.githooks/pre-push b/.githooks/pre-push index 4873e84dc9..94ca5f6ec0 100755 --- a/.githooks/pre-push +++ b/.githooks/pre-push @@ -278,7 +278,10 @@ spotcheck_shape() { path="${line#*$'\t'}" read -r mode type sha size <<<"$meta" [ "$mode $type" = "100644 blob" ] || return 1 - [[ "$sha" =~ ^[0-9a-f]{40}([0-9a-f]{24})?$ && "$size" =~ ^[0-9]{1,9}$ ]] || return 1 + case "$sha" in '' | *[!0-9a-f]*) return 1 ;; esac + [ "${#sha}" -eq 40 ] || [ "${#sha}" -eq 64 ] || return 1 + case "$size" in '' | *[!0-9]*) return 1 ;; esac + [ "${#size}" -le 9 ] || return 1 [[ "$path" =~ $spotcheck_path_re ]] || return 1 case "/$path/" in */./* | */../*) return 1 ;; From 6dc3f9b824e78eb4e3692a487667a65d5694b7eb Mon Sep 17 00:00:00 2001 From: REPPL <77722411+REPPL@users.noreply.github.com> Date: Thu, 26 Nov 2026 21:32:28 +0000 Subject: [PATCH 13/16] chore: defer bounding the spot-check's read of its local copy The spot-check's outbound reader reads the whole local copy through the store's 4,096-record bound. It fails closed and only on the checkout past it, about eight weeks away at the current rate, and the bounded read needs a design of its own, so it is deferred with its decision and captured at major, carried past v0.17.1. Refs: itd-2610301750162657 Assisted-by: Claude:claude-opus-5-5 --- ...efer-bounding-the-spot-check-s-outbound.md | 6 ++++++ ...121-spot-check-outbound-reads-the-whole.md | 21 +++++++++++++++++++ 2 files changed, 27 insertions(+) create mode 100644 .abcd/work/decisions/dcn-2611262132038983-defer-bounding-the-spot-check-s-outbound.md create mode 100644 .abcd/work/issues/open/iss-2611262132147121-spot-check-outbound-reads-the-whole.md diff --git a/.abcd/work/decisions/dcn-2611262132038983-defer-bounding-the-spot-check-s-outbound.md b/.abcd/work/decisions/dcn-2611262132038983-defer-bounding-the-spot-check-s-outbound.md new file mode 100644 index 0000000000..c2e7467d13 --- /dev/null +++ b/.abcd/work/decisions/dcn-2611262132038983-defer-bounding-the-spot-check-s-outbound.md @@ -0,0 +1,6 @@ +--- +id: dcn-2611262132038983 +slug: defer-bounding-the-spot-check-s-outbound +date: 2026-11-26 +--- +2026-11-26 — Defer bounding the spot-check's outbound read of the local copy (itd-2610301750162657). outbound, which every observation and every push of the spot-check runs, reads the whole local refs/abcd/spotcheck through the store's 4,096-record bound, and the copy grows by about 60 records a day across this checkout's worktrees, so at the current rate it reaches the bound in about eight weeks. Grounds for deferring: it fails closed, since over the bound outbound refuses and the observation writes nothing and says so, so no cycle is drawn over a partial read and no clean cycle is counted; it stops only the checkout whose local copy is over the bound, and every record stays on that copy to be carried once the read is bounded; and the fix needs a design, because the typed copy carried to origin is named by its own content hash and so differs from the local file's name, and what origin already holds cannot be told from the two listings alone. The technical facilitator ruled it deferred under facilitator.mode auto, with its issue captured at major and carried past v0.17.1. Reverse by bounding outbound in this branch before it lands. diff --git a/.abcd/work/issues/open/iss-2611262132147121-spot-check-outbound-reads-the-whole.md b/.abcd/work/issues/open/iss-2611262132147121-spot-check-outbound-reads-the-whole.md new file mode 100644 index 0000000000..6756517568 --- /dev/null +++ b/.abcd/work/issues/open/iss-2611262132147121-spot-check-outbound-reads-the-whole.md @@ -0,0 +1,21 @@ +--- +schema_version: 1 +id: "iss-2611262132147121" +slug: "spot-check-outbound-reads-the-whole" +severity: "major" +category: "bug" +source: "review-followup" +found_during: "spot-check PR-A fix round 2 (itd-2610301750162657)" +origin: researcher-authored +production_mode: hand-written +found_at: "internal/core/spotcheck/store.go" +remedy: "Bound outbound's read to the local records written since the last full carry (a checkpoint ref on the local copy, advanced commit by commit as origin is found to hold each), keeping the over-bound case a refusal and never a draw over a partial read." +deferred_after: v0.17.1 +deferral_reason: "Capacity, not a fault that misleads: outbound refuses loudly over the bound and only on the checkout whose local copy is past it, about eight weeks away at the current rate, and the bounded read needs a design because a typed copy's name differs from the local file's (dcn-2611262132038983)." +--- + +The spot-check's outbound reader (internal/core/spotcheck/store.go, outbound) reads the whole local copy refs/abcd/spotcheck through read, which refuses a store holding more than 4,096 records. Every observation with an open window and every push of the store runs it, so once this checkout's local copy passes the bound, which it reaches in about eight weeks at about 60 records a day, nothing more is carried to origin and nothing is drawn from this checkout, with one line saying so at every landing and drain move. Writing records keeps working. The stop must stay a refusal: a fix bounds what outbound reads and must never turn the refusal into a draw over a partial read. Deferred with dcn-2611262132038983. + +## Deferral 2026-11-26 + +Deferred past v0.17.1: Capacity, not a fault that misleads: outbound refuses loudly over the bound and only on the checkout whose local copy is past it, about eight weeks away at the current rate, and the bounded read needs a design because a typed copy's name differs from the local file's (dcn-2611262132038983). From d4fbfea1bc89b311582e1d3d7c8a3b7dd4381156 Mon Sep 17 00:00:00 2001 From: REPPL <77722411+REPPL@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:11:46 +0000 Subject: [PATCH 14/16] fix: fill a spot-check window from records that read, and size the block A file over the size a configuration file may hold at a window's start is a file read and refused: its size is read from the listing first, and the window is counted by the bundled defaults and drawn, as for any block that does not read. A record key none of whose files reads as a record now takes no place in a window: keys are read in order a batch at a time and the next key takes the place, within the same read bounds. The draw's note counts the files that did not read, and a group whose read bound is spent with places open and files unread refuses the draw, naming the count. A test now pins the verifier setting aside a cycle whose record group is kept by its hash. Refs: itd-2610301750162657 Assisted-by: Claude:claude-opus-5-5 --- internal/core/spotcheck/afterlanding.go | 159 +++++++++++++++--------- internal/core/spotcheck/bounds_test.go | 82 ++++++++++++ internal/core/spotcheck/config.go | 34 +++++ 3 files changed, 215 insertions(+), 60 deletions(-) diff --git a/internal/core/spotcheck/afterlanding.go b/internal/core/spotcheck/afterlanding.go index 31eea33b98..9d3f36c434 100644 --- a/internal/core/spotcheck/afterlanding.go +++ b/internal/core/spotcheck/afterlanding.go @@ -231,7 +231,7 @@ func draw(ctx context.Context, o Observed, tip string) string { } beacon = &b } - c, items, err := makeCycle(ctx, o, cfg, why != "", st, cl, *beacon, pending) + c, items, unread, err := makeCycle(ctx, o, cfg, why != "", st, cl, *beacon, pending) if err != nil { return "spot-check: " + err.Error() + "; nothing was drawn" } @@ -252,7 +252,7 @@ func draw(ctx context.Context, o Observed, tip string) string { for _, g := range c.Groups { drawn += len(g.Drawn) } - return fmt.Sprintf("spot-check: drew cycle %s (round %d of the beacon): %d item(s) for review", c.ID, beacon.Round, drawn) + defaultsNote(why) + setAside(st) + note + return fmt.Sprintf("spot-check: drew cycle %s (round %d of the beacon): %d item(s) for review", c.ID, beacon.Round, drawn) + unreadNote(unread) + defaultsNote(why) + setAside(st) + note } return "spot-check: the push to " + Branch + " was refused twice (" + redact(last) + "); nothing was drawn, and the next landing tries again" } @@ -290,21 +290,21 @@ func setAside(st windowState) string { // before it, and an item file per drawn key; defaults says the bundled // defaults counted the window (windowConfig). pending are the typed records // this checkout carries in the same commit, read as origin's own. -func makeCycle(ctx context.Context, o Observed, cfg Config, defaults bool, st windowState, cl closing, b Beacon, pending []file) (Cycle, []file, error) { +func makeCycle(ctx context.Context, o Observed, cfg Config, defaults bool, st windowState, cl closing, b Beacon, pending []file) (Cycle, []file, int, error) { reader := registeredReader() if reader == nil { - return Cycle{}, nil, errNoReader + return Cycle{}, nil, 0, errNoReader } var rows []LandingRow if st.from != cl.commit { var err error if rows, err = reader(ctx, o.Root, st.from, cl.commit); err != nil { - return Cycle{}, nil, fmt.Errorf("the window's landings cannot be read: %s", redact(err)) + return Cycle{}, nil, 0, fmt.Errorf("the window's landings cannot be read: %s", redact(err)) } } for _, r := range rows { if !slices.Contains(cl.commits, r.Commit) { - return Cycle{}, nil, fmt.Errorf("the landings reader named %s, which is not a commit of the window", termsafe.Sanitize(r.Commit)) + return Cycle{}, nil, 0, fmt.Errorf("the landings reader named %s, which is not a commit of the window", termsafe.Sanitize(r.Commit)) } } seen := map[string]map[string]bool{} @@ -318,22 +318,22 @@ func makeCycle(ctx context.Context, o Observed, cfg Config, defaults bool, st wi } } } - hbs, ds, err := windowRecords(ctx, o.Root, st.files, pending, seen) + hbs, ds, unread, err := windowRecords(ctx, o.Root, st.files, pending, seen) if err != nil { - return Cycle{}, nil, err + return Cycle{}, nil, 0, err } groups, err := populations(rows, hbs, ds, seen) if err != nil { - return Cycle{}, nil, err + return Cycle{}, nil, 0, err } tallies, err := tallyCycles(ctx, o.Root, st) if err != nil { - return Cycle{}, nil, err + return Cycle{}, nil, 0, err } size, why, counted := sampleSize(cfg.PerGroup, tallies) randomness, err := hex.DecodeString(b.Randomness) if err != nil || len(randomness) != 32 { - return Cycle{}, nil, errors.New("the beacon's randomness does not read") + return Cycle{}, nil, 0, errors.New("the beacon's randomness does not read") } c := Cycle{SchemaVersion: SchemaVersion, ID: cycleID(cl.at, cl.commit), FromCommit: st.from, ToCommit: cl.commit, FromTime: st.fromTime, ToTime: cl.at, ClosedBy: cl.by, Window: CycleWindow{Days: cfg.WindowDays, Changes: cfg.WindowChanges, Commits: len(cl.commits), Defaults: defaults}, @@ -357,12 +357,12 @@ func makeCycle(ctx context.Context, o Observed, cfg Config, defaults bool, st wi Landing: cd.landing, HandBack: cd.handBack, Decision: cd.decision} f, err := encodeFile(ItemsDir+"/"+c.ID, itemStem(n, g, k)+".json", it) if err != nil { - return Cycle{}, nil, fmt.Errorf("item %s of the cycle cannot be kept: %w", strconv.Itoa(n), err) + return Cycle{}, nil, 0, fmt.Errorf("item %s of the cycle cannot be kept: %w", strconv.Itoa(n), err) } items = append(items, f) } } - return c, items, nil + return c, items, unread, nil } // maxFilesPerKey bounds the files of one record key a draw reads: records of @@ -374,14 +374,17 @@ const maxFilesPerKey = 4 // with the cycle, the ones whose key no earlier verified cycle's population of // their group listed (seen). Only their files are read, so a draw reads what // arrived since the cycles before it, never the store's whole life. Within a -// group the keys are taken in sorted order, at most maxListedKeys of them, -// each by its maxFilesPerKey greatest names, and their files at most half of -// maxReadFiles; a key beyond either bound waits for a later window, as a -// record that reaches origin late does. So every record population is listed +// group the keys are read in sorted order, each by its maxFilesPerKey +// greatest names, until maxListedKeys of them read as records or half of +// maxReadFiles files are read; a key none of whose files reads takes no +// place, and a key beyond either bound waits for a later window, as a record +// that reaches origin late does. unread counts the files that did not read +// as records; a group whose read bound is spent with places still open and +// some file unread refuses the draw, naming the count. So every record population is listed // whole, and the next draw knows each record already drawn from by its key. // A file whose name is not a record's is never read, and one whose content // does not read as its name gives is no record. -func windowRecords(ctx context.Context, root string, files map[string]entry, pending []file, seen map[string]map[string]bool) ([]namedHandBack, []namedDecision, error) { +func windowRecords(ctx context.Context, root string, files map[string]entry, pending []file, seen map[string]map[string]bool) ([]namedHandBack, []namedDecision, int, error) { type src struct { dir, name string // data is the pending copy's content, nil for origin's file. @@ -418,60 +421,96 @@ func windowRecords(ctx context.Context, root string, files map[string]entry, pen add(f.folder, f.name, f.data) } } - var take []src - var paths []string + var hbs []namedHandBack + var ds []namedDecision + unread := 0 for _, g := range []string{GroupDrainHandBacks, GroupFacilitatorDecisions} { keys := make([]string, 0, len(byKey[g])) for k := range byKey[g] { keys = append(keys, k) } slices.Sort(keys) - budget, used := max(maxReadFiles/2, 1), 0 - for i, k := range keys { - if i == maxListedKeys { - break + // The group's names in key order, each key by its greatest names, + // read a batch at a time: a key none of whose files reads as a + // record takes no place, and the next key is read in its stead, + // until the window's places are filled or the group's files are + // spent. + budget, used, listed, next, missed := max(maxReadFiles/2, 1), 0, 0, 0, 0 + spent := false + for listed < maxListedKeys && next < len(keys) && !spent { + type keyFiles struct { + key string + names []string } - names := make([]string, 0, len(byKey[g][k])) - for n := range byKey[g][k] { - names = append(names, n) + var batch []keyFiles + var paths []string + for next < len(keys) && len(batch) < maxListedKeys-listed { + names := make([]string, 0, len(byKey[g][keys[next]])) + for n := range byKey[g][keys[next]] { + names = append(names, n) + } + slices.Sort(names) + slices.Reverse(names) + names = names[:min(len(names), maxFilesPerKey)] + if used > 0 && used+len(names) > budget { + spent = true + break + } + used += len(names) + batch = append(batch, keyFiles{key: keys[next], names: names}) + for _, n := range names { + if src := byKey[g][keys[next]][n]; src.data == nil { + paths = append(paths, src.dir+"/"+n) + } + } + next++ } - slices.Sort(names) - slices.Reverse(names) - names = names[:min(len(names), maxFilesPerKey)] - if i > 0 && used+len(names) > budget { - break + blobs, err := readMany(ctx, root, files, paths) + if err != nil { + return nil, nil, 0, err } - used += len(names) - for _, n := range names { - s := byKey[g][k][n] - take = append(take, s) - if s.data == nil { - paths = append(paths, s.dir+"/"+s.name) + for _, kf := range batch { + read := false + for _, n := range kf.names { + src := byKey[g][kf.key][n] + data := src.data + if data == nil { + data = blobs[src.dir+"/"+n] + } + var one Records + if data == nil || !readRecord(&one, src.dir, n, data) { + missed++ + continue + } + read = true + for _, h := range one.HandBacks { + hbs = append(hbs, namedHandBack{name: n, h: h}) + } + for _, d := range one.Decisions { + ds = append(ds, namedDecision{name: n, d: d}) + } + } + if read { + listed++ } } } - } - blobs, err := readMany(ctx, root, files, paths) - if err != nil { - return nil, nil, err - } - var hbs []namedHandBack - var ds []namedDecision - for _, s := range take { - data := s.data - if data == nil { - data = blobs[s.dir+"/"+s.name] - } - var one Records - if data == nil || !readRecord(&one, s.dir, s.name, data) { - continue - } - for _, h := range one.HandBacks { - hbs = append(hbs, namedHandBack{name: s.name, h: h}) - } - for _, d := range one.Decisions { - ds = append(ds, namedDecision{name: s.name, d: d}) + unread += missed + if spent && listed < maxListedKeys && missed > 0 { + // The group's read bound went on files that are not records + // with places still open: the window is not drawn short of + // records that may read beyond them. + return nil, nil, unread, fmt.Errorf("the spot-check's %s ran out of its read of %d files with %d place(s) open, and %d record file(s) on origin did not read as records", g, budget, maxListedKeys-listed, missed) } } - return hbs, ds, nil + return hbs, ds, unread, nil +} + +// unreadNote is the note's tail counting the record files on origin that +// did not read as records and so took no place in the window, "" for none. +func unreadNote(n int) string { + if n == 0 { + return "" + } + return fmt.Sprintf("; %d record file(s) on origin did not read as records and took no place in the window", n) } diff --git a/internal/core/spotcheck/bounds_test.go b/internal/core/spotcheck/bounds_test.go index 86337222e8..51ae3b631c 100644 --- a/internal/core/spotcheck/bounds_test.go +++ b/internal/core/spotcheck/bounds_test.go @@ -200,3 +200,85 @@ func TestAPassingReadFailureOfTheBlockIsNoDefaults(t *testing.T) { t.Fatalf("the observation over a block git cannot read said %q", note) } } + +// TestABlockOverTheSizeBoundCountsByTheDefaults: a spotcheck block whose +// file at the window's start is larger than a configuration file may be is a +// file read and refused: the window is counted by the bundled defaults, says +// so, and is drawn. +func TestABlockOverTheSizeBoundCountsByTheDefaults(t *testing.T) { + latest := "1000" + c := newDrawCase(t) + c.serveRounds(&latest) + c.r.Write(".abcd/config.json", `{"spotcheck":{"window_days":3},"pad":"`+strings.Repeat("x", 1<<20)+`"}`+"\n") + c.r.Git("add", "-A") + start := c.landAt(1, w0.Add(-time.Hour)) + c.openWindow(w0) + cfg, why, err := windowConfig(context.Background(), c.r.Root(), start) + if err != nil || why == "" || cfg.WindowDays != DefaultWindowDays || cfg.PerGroup != DefaultPerGroup { + t.Fatalf("windowConfig over a block past the size bound = %+v, %q, %v; want the defaults with a reason", cfg, why, err) + } + c.land(2) + c.closeWindow() + if note := c.observe(q1000.Add(time.Hour)); !strings.Contains(note, "drew cycle") || !strings.Contains(note, "bundled defaults") { + t.Fatalf("the draw over a block past the size bound said %q", note) + } +} + +// TestARecordThatDoesNotReadTakesNoPlaceInAWindow: files under record names +// whose content is not the record their name gives take none of a window's +// places: the window is filled from the records that read, and the draw's +// note counts the files that did not. +func TestARecordThatDoesNotReadTakesNoPlaceInAWindow(t *testing.T) { + saved := maxListedKeys + maxListedKeys = 2 + t.Cleanup(func() { maxListedKeys = saved }) + latest := "1000" + c := newDrawCase(t) + c.serveRounds(&latest) + c.openWindow(w0) + unread := map[string]string{} + for _, issue := range []string{"iss-60", "iss-61", "iss-62"} { + f, err := handBack(issue, w0.Add(time.Minute)).typed().file() + if err != nil { + t.Fatal(err) + } + unread[f.path()] = "{}\n" + } + c.plant(unread) + want := c.plantHandBacks(w0.Add(time.Hour), "iss-70", "iss-71") + c.closeWindow() + note := c.observe(q1000.Add(time.Hour)) + if !strings.Contains(note, "drew cycle") || !strings.Contains(note, "3 record file(s)") { + t.Fatalf("the draw over records that do not read said %q", note) + } + if got := groupOf(t, c.newestCycle(), GroupDrainHandBacks).Population.Keys; !slices.Equal(got, want) { + t.Fatalf("the window took %v; want the records that read, %v", got, want) + } +} + +// TestACycleWhoseRecordGroupIsNotListedIsSetAside: a cycle from another +// writer that keeps a record group by its hash, though it verifies in every +// other way, is set aside and its window drawn afresh. +func TestACycleWhoseRecordGroupIsNotListedIsSetAside(t *testing.T) { + saved := maxListedKeys + maxListedKeys = 1 + t.Cleanup(func() { maxListedKeys = saved }) + latest := "1000" + c := newDrawCase(t) + c.serveRounds(&latest) + from := c.openWindow(w0) + line := c.landAt(3, w0.Add(time.Hour)) + c.closeWindow() + forged := handMade(from, line, ClosedByDays) + for i, g := range forged.Groups { + if g.Group == GroupDrainHandBacks { + forged.Groups[i] = GroupDraw{Group: g.Group, Population: Population{Count: 2, First: "a", Last: "b", SHA256: strings.Repeat("0", 64)}, + Drawn: []string{"a", "b"}} + } + } + c.plant(map[string]string{CyclesDir + "/" + forged.ID + ".json": cycleJSON(t, forged, sevenDays(3))}) + note := c.observe(q1000.Add(time.Hour)) + if !strings.Contains(note, "drew cycle "+cycleID(q1000, line)) || !strings.Contains(note, forged.ID+" on origin does not verify") { + t.Fatalf("the observation over a cycle with an unlisted record group said %q", note) + } +} diff --git a/internal/core/spotcheck/config.go b/internal/core/spotcheck/config.go index 07111b7e83..9fe1403922 100644 --- a/internal/core/spotcheck/config.go +++ b/internal/core/spotcheck/config.go @@ -9,6 +9,8 @@ import ( "context" "errors" "fmt" + "strconv" + "strings" "github.com/intentdriven/abcd/internal/core/layered" "github.com/intentdriven/abcd/internal/gitutil" @@ -96,6 +98,18 @@ func windowConfig(ctx context.Context, root, commit string) (c Config, why strin } return Config{}, "", notHeldError{commit[:12]} } + // A file over the size a configuration file may hold is a file read and + // refused, the same for every reader, so its size is read from the + // listing first: the capped read of its content would otherwise fail + // as git does. + size, err := blockSize(ctx, root, commit) + if err != nil { + return Config{}, "", fmt.Errorf("the spotcheck block at the window's start was not read (%s), so the window cannot be counted yet", redact(err)) + } + if size > layered.MaxFileBytes { + return Config{WindowDays: DefaultWindowDays, PerGroup: DefaultPerGroup}, + fmt.Sprintf("%s at %s is larger than %d bytes", layered.Config.RepoRel, commit[:12], layered.MaxFileBytes), nil + } r, _ := layered.RootsFor(root) c, err = readConfig(ctx, layered.Roots{Repo: r.Repo, RepoAt: commit, RepoAtName: commit[:12], RepoAtAsStored: true, HomeRefused: true}) var ue *layered.UnreadError @@ -108,6 +122,26 @@ func windowConfig(ctx context.Context, root, commit string) (c Config, why strin return Config{WindowDays: DefaultWindowDays, PerGroup: DefaultPerGroup}, redact(err), nil } +// blockSize is the size of .abcd/config.json at commit as git lists it, -1 +// when the commit holds no blob there (no file, or one the layered reader +// refuses by its kind). err is a git that did not answer. +func blockSize(ctx context.Context, root, commit string) (int, error) { + out, err := gitutil.RunCappedBytesAsStoredContext(ctx, root, "", 4096, "ls-tree", "-l", "-z", commit, "--", layered.Config.RepoRel) + if err != nil { + return 0, err + } + meta, _, _ := strings.Cut(strings.TrimSuffix(string(out), "\x00"), "\t") + f := strings.Fields(meta) + if len(f) != 4 || f[1] != "blob" { + return -1, nil + } + n, err := strconv.Atoi(f[3]) + if err != nil || n < 0 { + return 0, errors.New("git listed the block's file with a size that does not read") + } + return n, nil +} + // notHeldError is a window's start this checkout does not hold, by its // short name. type notHeldError struct{ short string } From 8c9f24e1fa147e524fa65d9db2831ae1dfb7a014 Mon Sep 17 00:00:00 2001 From: REPPL <77722411+REPPL@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:26:28 +0000 Subject: [PATCH 15/16] fix: draw a spot-check group from the records it listed within its bound A group whose read bound is spent after some of its records read is now drawn from those, and the note counts the files that did not read; only a group that listed none of its records within the bound refuses the draw. Each case has its test, and the set-aside test now asserts the reason the verifier gives for an unlisted record group. Refs: itd-2610301750162657 Assisted-by: Claude:claude-opus-5-5 --- internal/core/spotcheck/afterlanding.go | 15 +++--- internal/core/spotcheck/bounds_test.go | 65 ++++++++++++++++++++++++- 2 files changed, 72 insertions(+), 8 deletions(-) diff --git a/internal/core/spotcheck/afterlanding.go b/internal/core/spotcheck/afterlanding.go index 9d3f36c434..1dca0deced 100644 --- a/internal/core/spotcheck/afterlanding.go +++ b/internal/core/spotcheck/afterlanding.go @@ -379,8 +379,8 @@ const maxFilesPerKey = 4 // maxReadFiles files are read; a key none of whose files reads takes no // place, and a key beyond either bound waits for a later window, as a record // that reaches origin late does. unread counts the files that did not read -// as records; a group whose read bound is spent with places still open and -// some file unread refuses the draw, naming the count. So every record population is listed +// as records; a group whose read bound is spent before any of its records +// read, with some file unread, refuses the draw, naming the count. So every record population is listed // whole, and the next draw knows each record already drawn from by its key. // A file whose name is not a record's is never read, and one whose content // does not read as its name gives is no record. @@ -496,11 +496,12 @@ func windowRecords(ctx context.Context, root string, files map[string]entry, pen } } unread += missed - if spent && listed < maxListedKeys && missed > 0 { - // The group's read bound went on files that are not records - // with places still open: the window is not drawn short of - // records that may read beyond them. - return nil, nil, unread, fmt.Errorf("the spot-check's %s ran out of its read of %d files with %d place(s) open, and %d record file(s) on origin did not read as records", g, budget, maxListedKeys-listed, missed) + if spent && listed == 0 && missed > 0 { + // The group's whole read bound went on files that are not + // records: the window is not drawn with that group empty while + // records may read beyond them. A group that listed some is + // drawn from those, and the note counts the rest. + return nil, nil, unread, fmt.Errorf("the spot-check's %s listed none of its records within its read of %d files, and %d record file(s) on origin did not read as records", g, budget, missed) } } return hbs, ds, unread, nil diff --git a/internal/core/spotcheck/bounds_test.go b/internal/core/spotcheck/bounds_test.go index 51ae3b631c..aa831ec1a6 100644 --- a/internal/core/spotcheck/bounds_test.go +++ b/internal/core/spotcheck/bounds_test.go @@ -278,7 +278,70 @@ func TestACycleWhoseRecordGroupIsNotListedIsSetAside(t *testing.T) { } c.plant(map[string]string{CyclesDir + "/" + forged.ID + ".json": cycleJSON(t, forged, sevenDays(3))}) note := c.observe(q1000.Add(time.Hour)) - if !strings.Contains(note, "drew cycle "+cycleID(q1000, line)) || !strings.Contains(note, forged.ID+" on origin does not verify") { + if !strings.Contains(note, "drew cycle "+cycleID(q1000, line)) || !strings.Contains(note, forged.ID+" on origin does not verify (its "+GroupDrainHandBacks+" population is not listed") { t.Fatalf("the observation over a cycle with an unlisted record group said %q", note) } } + +// plantUnread puts a file under a hand-back's name for each issue on origin's +// store branch, made at at, whose content is not the record its name gives. +func (c *drawCase) plantUnread(at time.Time, issues ...string) { + c.t.Helper() + files := map[string]string{} + for _, issue := range issues { + f, err := handBack(issue, at).typed().file() + if err != nil { + c.t.Fatal(err) + } + files[f.path()] = "{}\n" + } + c.plant(files) +} + +// TestAGroupWhoseReadBoundEndsAfterARecordIsDrawn: a group whose read bound +// is spent after some of its records read is drawn from the records that +// read, and the note counts the files that did not. +func TestAGroupWhoseReadBoundEndsAfterARecordIsDrawn(t *testing.T) { + latest := "1000" + c := newDrawCase(t) + c.serveRounds(&latest) + c.openWindow(w0) + saved := maxReadFiles + maxReadFiles = 4 + t.Cleanup(func() { maxReadFiles = saved }) + c.plantUnread(w0.Add(time.Minute), "iss-60") + want := c.plantHandBacks(w0.Add(time.Hour), "iss-70") + c.plantUnread(w0.Add(2*time.Hour), "iss-80", "iss-81") + c.closeWindow() + note := c.observe(q1000.Add(time.Hour)) + if !strings.Contains(note, "drew cycle") || !strings.Contains(note, "1 record file(s)") { + t.Fatalf("the draw over a group whose read bound ended after a record said %q", note) + } + if got := groupOf(t, c.newestCycle(), GroupDrainHandBacks).Population.Keys; !slices.Equal(got, want) { + t.Fatalf("the window took %v; want the record that read, %v", got, want) + } +} + +// TestAGroupThatListsNoRecordWithinItsReadBoundIsNotDrawn: a group whose +// read bound is spent before any of its files reads as a record refuses the +// draw, naming the count, and writes nothing. +func TestAGroupThatListsNoRecordWithinItsReadBoundIsNotDrawn(t *testing.T) { + latest := "1000" + c := newDrawCase(t) + c.serveRounds(&latest) + c.openWindow(w0) + saved := maxReadFiles + maxReadFiles = 4 + t.Cleanup(func() { maxReadFiles = saved }) + c.plantUnread(w0.Add(time.Minute), "iss-60", "iss-61", "iss-62") + c.plantHandBacks(w0.Add(time.Hour), "iss-70") + c.closeWindow() + tip := c.originTip() + note := c.observe(q1000.Add(time.Hour)) + if !strings.Contains(note, "listed none of its records") || !strings.Contains(note, "2 record file(s)") || !strings.Contains(note, "nothing was drawn") { + t.Fatalf("the draw over a group that listed no record said %q", note) + } + if c.originTip() != tip { + t.Fatal("a refused draw moved origin's branch") + } +} From acf47cd235c45ae84473afe2183ad6fd3ba64f85 Mon Sep 17 00:00:00 2001 From: REPPL <77722411+REPPL@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:03:57 +0000 Subject: [PATCH 16/16] fix: name the listing form of the person's git in the drive's table A drive move now reaches the spot-check's fetch, whose confirmation of a branch origin lacks reads origin's listing line by line through gitutil.NetEachContext since main's change to that read. It runs as gitutil.NetContext does, in the person's own environment with the hooks pinned off, and is named in the table with it. Refs: itd-2610301750162657 Assisted-by: Claude:claude-opus-5-5 --- internal/core/implement/loop/gitenvs.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/internal/core/implement/loop/gitenvs.go b/internal/core/implement/loop/gitenvs.go index 7a34ff77b9..67e311b7ae 100644 --- a/internal/core/implement/loop/gitenvs.go +++ b/internal/core/implement/loop/gitenvs.go @@ -104,6 +104,9 @@ var driveGitCommands = []driveGitCommand{ // The ask of origin and other commands in the person's own environment, // the hooks pinned off (core.hooksPath=/dev/null or every exec pin). {"gitutil.NetContext", personEnv, false}, + // NetContext's listing form, line by line: the spot-check's fetch + // confirms a branch origin lacks with it. + {"gitutil.NetEachContext", personEnv, false}, {"gitutil.NetAskContext", personEnv, false}, {"gitutil.RemoteHeadTip", personEnv, false}, {"gitutil.WorkingTreeCommand", personEnv, false},