From 86c181b02d28aa21842c7d93b5390e896c929651 Mon Sep 17 00:00:00 2001 From: Han Ngo Date: Wed, 2 Dec 2026 15:22:17 +0700 Subject: [PATCH 1/2] fix(spec): keep realized spec numbers spent and use kernel flock Promote realized reservations in lib/spec/spec-next.sh to permanent SPENT records in the same ledger, counted with no TTL and anchored repo scoping. Replace the home-made mkdir mutex with lib/goal/goal-lock.sh kernel flock so concurrent worktrees serialize safely on Ubuntu 26.04 uutils coreutils. --- commands/mega.md | 9 +- docs/reference/FEATURES.md | 8 +- docs/verification/spec-number-stays-spent.md | 152 +++++ lib/spec/spec-next.sh | 210 ++----- tests/test-spec-next-spent.sh | 629 +++++++++++++++++++ tests/test-spec-reserve.sh | 128 ++-- 6 files changed, 936 insertions(+), 200 deletions(-) create mode 100644 docs/verification/spec-number-stays-spent.md create mode 100755 tests/test-spec-next-spent.sh diff --git a/commands/mega.md b/commands/mega.md index 374fdc8a1..39f8e80c7 100644 --- a/commands/mega.md +++ b/commands/mega.md @@ -537,10 +537,11 @@ no new binary or `lib/` file. Full depth + a worked dry-run: the skill's 4. **Front-load clarifications ONCE**, over the whole union -- Step 2's beat, reused verbatim, just framed against the union rather than one mega. 5. **Spec-number block reserve + release.** Reserve via `bash lib/spec/spec-next.sh reserve` - (the spec-numbering mkdir-mutex reservations ledger, the same mechanism the wavefront dispatch - already uses at Step 4). This kit has no separate `release` verb: an unclaimed reservation - self-expires on its own stale-reclaim TTL, so "release the old megas' unused numbers" is a - no-op here, not a command to run -- the ledger prunes them without an operator step. + (the spec-numbering kernel-flock reservations ledger, the same mechanism the wavefront dispatch + already uses at Step 4). This kit has no separate `release` verb: an unrealized reservation + still expires after the TTL, but once a number is realized in a spec file, branch, or commit + it becomes a permanent `SPENT` record and does not come back on its own (to reclaim one burnt + by mistake, delete its `| SPENT | spec= repo=` line from `spec-reservations.log`). 6. **Provenance per sub-goal.** Every consolidated sub-goal records `from: /SG- + /SG-` on its roadmap line and in its goal file. Done imports keep their own single origin + PR. diff --git a/docs/reference/FEATURES.md b/docs/reference/FEATURES.md index 2c30f9d8a..ba43c84df 100644 --- a/docs/reference/FEATURES.md +++ b/docs/reference/FEATURES.md @@ -20,7 +20,7 @@ GENERATED , do not hand-edit. Regenerate: `bash lib/registry/feature-registry.sh | `/kit:design` | `[H/I]` | Opt-in interactive solution-design beat between /think and /spec. Use when the operator wants to shape HOW to build after the idea passed /… | SPEC-003, SPEC-004, SPEC-005 +162 | test-anomalies-advisor.sh, test-board-mirror-cleanup.sh, test-ceremony-fits-diff.sh +40 | | `/kit:devs-team` | `[H/I]` | Parallel multi-lens critique of a solution design (the active spec if present, else the decision brief). Dispatches 5 engineering lenses, m… | SPEC-016, SPEC-018, SPEC-019 +14 | test-gate-vocab-recording.sh, test-meta-review-verifiers.sh, test-meta-spec-depth.sh +1 | | `/kit:dispatch` | `[H/I]` | Fire several disjoint VALIDATED specs concurrently, each in its own worktree, then converge. Cross-goal fan-out behind a disjointness gate … | SPEC-002, SPEC-016, SPEC-017 +114 | test-advisor.sh, test-agent-effectiveness.sh, test-attempt-state-race.sh +52 | -| `/kit:docs` | `[H/I]` | Update all project documentation to match the current codebase. Cross-references the diff against every doc file and fixes drift. | SPEC-001, SPEC-002, SPEC-003 +292 | conform.sh, test-active-spec-pick.sh, test-adapters.sh +161 | +| `/kit:docs` | `[H/I]` | Update all project documentation to match the current codebase. Cross-references the diff against every doc file and fixes drift. | SPEC-001, SPEC-002, SPEC-003 +292 | conform.sh, test-active-spec-pick.sh, test-adapters.sh +162 | | `/kit:draft-agent` | `[H/I]` | Meta-agent agent-builder. From a one-line description, generates a new subagent definition OR a mega-goal sub-goal file and (by default) in… | SPEC-089, SPEC-108, SPEC-139 +1 | test-agent-effectiveness.sh, test-command-emit-sweep.sh, test-meta-agent.sh +1 | | `/kit:execute` | `[H/I]` | Whole-spec execution with verification. Dispatches one builder for the whole spec, verifies every task's criteria once at the end, retries … | SPEC-001, SPEC-003, SPEC-004 +82 | test-board-work.sh, test-break-it.sh, test-config-registry.sh +29 | | `/kit:explain` | `[H/I]` | Turn a merged change into a literate-diff explainer a human READS to understand: background -> goal + intuition -> a prose-ordered diff -> … | SPEC-050, SPEC-060, SPEC-094 +25 | test-boundary-lint.sh, test-clean-room.sh, test-command-emit-sweep.sh +13 | @@ -29,8 +29,8 @@ GENERATED , do not hand-edit. Regenerate: `bash lib/registry/feature-registry.sh | `/kit:greenlight` | `[H/I]` | Post-push CI-green lane: snapshots an open PR's checks via gh, classifies each failure real vs flaky, fixes real ones via the kit:fix-agent… | SPEC-019, SPEC-217, SPEC-369 | test-audit-verdict-grammar.sh, test-gate-ledger-actions.sh, test-ql-verdict.sh | | `/kit:grill` | `[H/I]` | Universal intake interview: one type-shaped question at a time, each with a recommended answer, until the task is actually understood. Answ… | SPEC-058, SPEC-059, SPEC-063 +27 | test-anomalies-advisor.sh, test-ceremony-lens.sh, test-config-stamp.sh +17 | | `/kit:kit-health` | `[H/I]` | Run a self-assessment of the kit against its own philosophy. Checks file count, hook performance, source citations, and structural health. | SPEC-001, SPEC-002, SPEC-004 +18 | test-command-emit-sweep.sh, test-meta-docs-registry.sh, test-meta-goal-ledger.sh +4 | -| `/kit:mega` | `[H/I]` | Turn a multi-objective destination into a sequenced roadmap of dependent sub-goals: decompose, front-load every clarification once, set the… | SPEC-034, SPEC-036, SPEC-088 +53 | test-adapters.sh, test-advisor.sh, test-bin-forwarders.sh +44 | -| `/kit:next` | `[H/I]` | Pick up the next undone task from the spec. Loads context, shows acceptance criteria, lets you drive the implementation. | SPEC-001, SPEC-002, SPEC-003 +146 | smoke.sh, test-active-spec-pick.sh, test-adapters.sh +95 | +| `/kit:mega` | `[H/I]` | Turn a multi-objective destination into a sequenced roadmap of dependent sub-goals: decompose, front-load every clarification once, set the… | SPEC-034, SPEC-036, SPEC-088 +53 | test-adapters.sh, test-advisor.sh, test-bin-forwarders.sh +45 | +| `/kit:next` | `[H/I]` | Pick up the next undone task from the spec. Loads context, shows acceptance criteria, lets you drive the implementation. | SPEC-001, SPEC-002, SPEC-003 +146 | smoke.sh, test-active-spec-pick.sh, test-adapters.sh +96 | | `/kit:onboard` | `[H/I]` | Guided first-run: detect the install mode, offer /kit:adopt for this repo, pick modules, capture the consumer knobs that make them work, di… | SPEC-199, SPEC-213, SPEC-232 +3 | test-clean-room.sh, test-command-emit-sweep.sh, test-onboard-detect.sh | | `/kit:pitch` | `[H/I]` | Assemble an outward buy-in doc from what a gated run already produced: the spec, the proof-of-done, the implementation-notes, and the gate … | SPEC-140, SPEC-141, SPEC-193 +7 | test-gate-validate-round.sh, test-outcome-emit-sweep.sh, test-pitch.sh +2 | | `/kit:prototype` | `[H/I]` | Opt-in throwaway-spike beat beside /kit:design. Builds throwaway code that answers ONE design question: a logic/state model driven by hand … | SPEC-075, SPEC-206, SPEC-207 +3 | test-picture-section.sh | @@ -40,7 +40,7 @@ GENERATED , do not hand-edit. Regenerate: `bash lib/registry/feature-registry.sh | `/kit:review` | `[H/I]` | Paranoid code review. Security, architecture, regressions, missing tests, edge cases. Produces actionable TODOS. | SPEC-001, SPEC-002, SPEC-003 +155 | smoke.sh, test-adopt.sh, test-advisor.sh +90 | | `/kit:ship` | `[H/I]` | Ship: review gate, tests, version bump, changelog, conventional commit, docs update, PR. Complete pipeline from done to merged. | SPEC-001, SPEC-002, SPEC-003 +111 | test-active-spec-pick.sh, test-adopt.sh, test-board-mirror.sh +64 | | `/kit:spec-validate` | `[H/I]` | Adversarial review of a spec before implementation. 7 specialist lenses attack the spec from different angles (6 advisory, 1 blocking on th… | SPEC-002, SPEC-003, SPEC-004 +70 | test-command-emit-sweep.sh, test-design-record.sh, test-every-step-review.sh +10 | -| `/kit:spec` | `[H/I]` | Generate a development spec from a feature idea or decision brief. Creates docs/specs/ with structured requirements. | SPEC-001, SPEC-002, SPEC-003 +241 | test-active-spec-pick.sh, test-audit-verdict-grammar.sh, test-bin-forwarders.sh +109 | +| `/kit:spec` | `[H/I]` | Generate a development spec from a feature idea or decision brief. Creates docs/specs/ with structured requirements. | SPEC-001, SPEC-002, SPEC-003 +241 | test-active-spec-pick.sh, test-audit-verdict-grammar.sh, test-bin-forwarders.sh +110 | | `/kit:start` | `[H/I]` | Detect project state and suggest the right next command. The entry point for any session. | SPEC-002, SPEC-003, SPEC-004 +94 | test-anomalies-advisor.sh, test-audit-cadence.sh, test-board-add.sh +95 | | `/kit:test-plan-review-team` | `[H/I]` | Parallel multi-lens adversarial critique of a spec's test plan (the ## Test plan section), with a bounded revise loop that tightens it. Dis… | SPEC-031, SPEC-052, SPEC-062 +14 | test-meta-docs-registry.sh, test-meta-review-verifiers.sh, test-meta-vmodel-dispatch.sh +3 | | `/kit:test-plan` | `[H/I]` | Derive a test-case coverage matrix from a spec's acceptance criteria before /kit:execute. Writes a `## Test plan` section into the active s… | SPEC-004, SPEC-016, SPEC-018 +38 | test-ceremony-lens.sh, test-e2e.sh, test-gate-ledger-inherit.sh +15 | diff --git a/docs/verification/spec-number-stays-spent.md b/docs/verification/spec-number-stays-spent.md new file mode 100644 index 000000000..3769ad0ab --- /dev/null +++ b/docs/verification/spec-number-stays-spent.md @@ -0,0 +1,152 @@ +# Verification: spec-number-stays-spent + +Headless shell library fix (`l312-spec`, off `origin/master` `e75b5b2d`): no UI surface. + +Fixes two defects in `lib/spec/spec-next.sh`: + +1. **Realized spec numbers stay spent permanently**: `_prune_reservations` previously dropped a `RESERVE` line once its number appeared in `docs/specs/`, branches, or recent commits; deleting the spec file or branch later let `next` and `check` treat the number as free again. A realized reservation for the calling repo is now promoted once in place to ` | SPENT | spec= repo=` in the same reservations ledger, counted by `_spent` / `_numbers` / `check` with no TTL and anchored `repo=` scoping. +2. **Kernel flock replaces mkdir-as-lock (Ubuntu 26.04 uutils fix)**: `reserve` previously serialized via a home-made `mkdir "$RES_LOCK"` + owner-file mutex, which deadlocked `tests/test-spec-reserve.sh` T20 on Ubuntu 26.04 (`uutils coreutils 0.10.0`, `uutils/coreutils#16344`: racing non-recursive `mkdir` exits 0 on `EEXIST`, allowing concurrent entry and self-deadlock on the owner PID). `reserve` now serializes via `lib/goal/goal-lock.sh` (`flock(2)` on fd 9, with `9>&-` closed in subshells), eliminating `mkdir`-as-lock, owner files, and PID/TTL reclaim races. + +## Readers audited + +All readers of `spec-reservations.log` / `SPEC_RESERVE_FILE` in `lib/`, `bin/`, `hooks/`, and `tests/` were searched (`rg -n "spec-reservations|SPEC_RESERVE|RESERVE" lib/ bin/ hooks/ tests/`): + +- `lib/spec/spec-next.sh`: filters `RESERVE` lines by `*"| RESERVE |"*` and reads `SPENT` lines via anchored `_spent`. +- `tests/test-spec-reserve.sh`: T6 checks `count 'num=006'` (0, unaffected by `spec=006`); T11 checks expired foreign pruning for nonexistent `repo=some-other-repo` (passes because `[ ! -d "$r" ]`); T9/T14/T15/T16/T17/T18/T25 updated to verify kernel `flock(2)` semantics via `lib/goal/goal-lock.sh`. +- `tests/test-spec-find.sh` and `tests/test-spec-next-pr-scan.sh`: call `spec-next.sh` CLI only; no direct ledger parsing. +- `commands/mega.md`: updated lines 539-544 to document kernel flock, permanent `SPENT` records, and line deletion for reclaiming a burnt number. + +## Root cause and RED baseline on `origin/master` (`e75b5b2d`) + +### 1. Reproducing the Ubuntu 26.04 T20 failure locally (uutils `mkdir` TOCTOU) + +Using a `mkdir` wrapper matching `uutils/coreutils#16344` (non-recursive `mkdir` returns 0 on racing `EEXIST` after initial `stat` sees `ENOENT`), two worktrees reserving concurrently on `origin/master` reproduced the exact Ubuntu CI failure (`round 1: total=1 distinct=1`, one worktree retrying `next()` twice and the other failing with `could not acquire lock`): + +```text +Command: bash -c '' +Exit: 0 +Output: +round 1: total=1 distinct=1 lock=free + wa err: spec-next: open PR heads not scanned (SPEC_NEXT_NO_PR_SCAN=1) spec-next: open PR heads not scanned (SPEC_NEXT_NO_PR_SCAN=1) + wb err: spec-next: open PR heads not scanned (SPEC_NEXT_NO_PR_SCAN=1) spec-next reserve: could not acquire lock after 20 tries (/repo/res-1.log.lock) +``` + +### 2. Full new suite RED baseline on `origin/master` (`e75b5b2d`) + +```text +Command: bash tests/test-spec-next-spent.sh +Exit: 1 +Output: +=== T1: realized file deleted -- number stays spent === + FAIL T1 check 006 stays TAKEN after file deletion (missing 'TAKEN' in: ... SPEC-006 is free rc=0) + FAIL T1 next does not reissue deleted 006 after 007 expires (want '007' got '006') +=== T16: T20 worktree reserves under uutils mkdir EEXIST exit 0 (5 rounds) === +=== T17: kernel flock exclusion and immediate SIGKILL release === + FAIL T17 reserve succeeds immediately after holder SIGKILL (006) (want '006' got '') +=== Results === +Passed: 49 / 100 +51 assertions failed. +``` + +## Green runs + +### 1. Shellcheck and bash 5.3.20 + +```text +Command: shellcheck -S warning lib/spec/spec-next.sh tests/test-spec-reserve.sh tests/test-spec-next-spent.sh && bash tests/test-spec-next-spent.sh && bash tests/test-spec-reserve.sh && bash tests/test-spec-next-pr-scan.sh +Exit: 0 +Output: +SHELLCHECK OK +Passed: 100 / 100 +spec-next-spent green. +Passed: 70 / 70 +spec-reserve green. +Passed: 8 / 8 +spec-next-pr-scan green. +``` + +### 2. macOS `/bin/bash` 3.2.57 + +```text +Command: timeout -k 5 180 /bin/bash -c '/bin/bash tests/test-spec-next-spent.sh | tail -n 5; /bin/bash tests/test-spec-reserve.sh | tail -n 5; /bin/bash tests/test-spec-next-pr-scan.sh | tail -n 5' +Exit: 0 +Output: + PASS T17 lock is unheld after reserve completes +Passed: 100 / 100 +spec-next-spent green. +Passed: 70 / 70 +spec-reserve green. +Passed: 8 / 8 +spec-next-pr-scan green. +``` + +### 3. GNU tools first on `PATH` (coreutils, gawk, gnu-sed) on both bash 5.3 and bash 3.2 + +```text +Command: PATH=":$PATH" timeout -k 5 180 bash -c 'bash tests/test-spec-next-spent.sh | tail -n 5; bash tests/test-spec-reserve.sh | tail -n 5; bash tests/test-spec-next-pr-scan.sh | tail -n 5' +Exit: 0 +Output: +Passed: 100 / 100 +spec-next-spent green. +Passed: 70 / 70 +spec-reserve green. +Passed: 8 / 8 +spec-next-pr-scan green. +``` + +```text +Command: PATH=":$PATH" timeout -k 5 180 /bin/bash -c '/bin/bash tests/test-spec-next-spent.sh | tail -n 5; /bin/bash tests/test-spec-reserve.sh | tail -n 5; /bin/bash tests/test-spec-next-pr-scan.sh | tail -n 5' +Exit: 0 +Output: +Passed: 100 / 100 +spec-next-spent green. +Passed: 70 / 70 +spec-reserve green. +Passed: 8 / 8 +spec-next-pr-scan green. +``` + +### 4. Simulated Linux `flock(1)` shim + GNU tools first on `PATH`, plus related contract suites + +```text +Command: PATH="::$PATH" timeout -k 5 180 bash -c 'bash tests/test-spec-reserve.sh 2>/dev/null | tail -n 3; bash tests/test-spec-next-spent.sh 2>/dev/null | tail -n 3' && bash tests/test-kri-wiring.sh 2>/dev/null | tail -n 3 && bash tests/test-mega-reconcile.sh 2>/dev/null | tail -n 3 && bash tests/test-advisor.sh 2>/dev/null | tail -n 3 +Exit: 0 +Output: +Passed: 70 / 70 +spec-reserve green. +Passed: 100 / 100 +spec-next-spent green. +=== 31/31 passed === +=== 35/35 passed, 0 failed === +=== 42/42 passed, 0 failed === +``` + +## Negative control and planted faults (isolated scratch copy) + +All negative control probes ran in a temporary scratch copy without mutating the workspace, each capped by `timeout -k 5 90`: + +```text +Command: bash -c '<9 planted-fault negative control probes in isolated scratch copy>' +Exit: 1 +Output: +Mutant [M0-origin-master] (test-spec-next-spent.sh): Exit=124 (baseline direct run: Exit=1, Passed: 49 / 100, 51 assertions failed) +Mutant [M1-no-goal-lock] (test-spec-reserve.sh): Exit=1 | Passed: 58 / 70 12 assertions failed. +Mutant [M2-drop-spent-from-numbers] (test-spec-next-spent.sh): Exit=1 | Passed: 69 / 100 31 assertions failed. +Mutant [M3-drop-foreign-dir-guard] (test-spec-next-spent.sh): Exit=1 | Passed: 98 / 100 2 assertions failed. +Mutant [M4-no-promo-dedupe] (test-spec-next-spent.sh): Exit=1 | Passed: 99 / 100 1 assertions failed. +Mutant [M5-unanchored-promo-dedupe] (test-spec-next-spent.sh): Exit=1 | Passed: 99 / 100 1 assertions failed. +Mutant [M6-no-x-number-anchor] (test-spec-next-spent.sh): Exit=1 | Passed: 98 / 100 2 assertions failed. +Mutant [M7-no-unterminated-read] (test-spec-next-spent.sh): Exit=1 | Passed: 98 / 100 2 assertions failed. +Mutant [M8-piped-check] (test-spec-next-spent.sh): Exit=1 | Passed: 99 / 100 1 assertions failed. +Verdict: RED +``` + +## Rollback + +Revert the commit(s) on this branch (`git revert `). Existing `| SPENT |` lines in `spec-reservations.log` are harmlessly ignored by older `spec-next.sh` (which only parses `| RESERVE |` lines); any regular lock file at `spec-reservations.log.lock` can be removed (`rm -f /spec-reservations.log.lock`) if rolling back to the old `mkdir`-lock implementation. To reclaim an individual burnt number without rolling back, delete its exact `| SPENT | spec= repo=` line from `spec-reservations.log`. + +## Not proven + +- Native Ubuntu 26.04 kernel/uutils runner execution (reproduced locally via the `uutils/coreutils#16344` `mkdir` stub, GNU coreutils/gawk/gnu-sed first on `PATH`, and a `flock(1)` shim; full Ubuntu matrix runs in CI). +- Live GitHub open-PR scanning (`SPEC_NEXT_NO_PR_SCAN=0`). +- Spec numbers created without `reserve` (never present in the ledger) or deleted before any later `reserve` observes realization are not recorded as `SPENT`. diff --git a/lib/spec/spec-next.sh b/lib/spec/spec-next.sh index ad7e1c518..6792de64b 100755 --- a/lib/spec/spec-next.sh +++ b/lib/spec/spec-next.sh @@ -11,11 +11,12 @@ # spec-next.sh next -> the next free number (e.g. "064") # spec-next.sh check -> exit 0 if free, exit 1 (+ where seen) if taken # spec-next.sh reserve -> atomically claim + print the next free number +# Reclaim a spent number: delete its '| SPENT | spec= repo=' line from $SPEC_RESERVE_FILE (default: /spec-reservations.log). # # This closes a CONCURRENCY gap the original scan-only version did not: a parallel wave that each calls # `next` BEFORE any branch/spec exists all scan the same surfaces and get the SAME number. # The scan is correct; the reservation happens too late. `reserve` claims a number under a -# portable mkdir-mutex and records it in a reservations ledger that `_numbers()` folds in, so +# kernel flock (lib/goal/goal-lock.sh) and records it in a reservations ledger that `_numbers()` folds in, so # a reserved number reads as TAKEN by the very next caller. `next`/`check` are unchanged in # contract for the RESERVATION LEDGER: with an empty ledger they behave as before that ledger # existed. That is narrower than "byte-identical to the pre-reservation code" in every case: @@ -48,7 +49,7 @@ ROOT="$(git rev-parse --show-toplevel 2>/dev/null || pwd)" _git_common_dir() { cd "$ROOT" 2>/dev/null || return 1 local cd_rel; cd_rel="$(git rev-parse --git-common-dir 2>/dev/null)" || return 1 - CDPATH= cd -- "$cd_rel" 2>/dev/null || return 1 + CDPATH='' cd -- "$cd_rel" 2>/dev/null || return 1 pwd -P } REPO="$(_git_common_dir)" || REPO="" @@ -63,6 +64,10 @@ if [ -r "$LIB_ROOT/telemetry/kit-log-dir.sh" ]; then # shellcheck source=lib/telemetry/kit-log-dir.sh source "$LIB_ROOT/telemetry/kit-log-dir.sh" 2>/dev/null || true fi +if [ -r "$LIB_ROOT/goal/goal-lock.sh" ]; then + # shellcheck source=lib/goal/goal-lock.sh + source "$LIB_ROOT/goal/goal-lock.sh" +fi # shellcheck source=lib/spec/spec-find.sh # A stale install without spec-find.sh keeps the root-only lookup (mirrors hooks/ship-gate.sh). if ! source "$LIB_ROOT/spec/spec-find.sh" 2>/dev/null; then @@ -76,8 +81,7 @@ else fi RES_FILE="${SPEC_RESERVE_FILE:-$RES_DIR/spec-reservations.log}" RES_LOCK="$RES_FILE.lock" -# Abandoned-reservation TTL: a reservation older than this (worker died before creating its -# branch) stops counting and gets pruned. A stale LOCK dir older than this is reclaimed. +# Abandoned-reservation TTL: an unrealized reservation older than this stops counting and gets pruned. SPEC_RESERVE_TTL="${SPEC_RESERVE_TTL:-86400}" # 24h in seconds now_epoch() { date -u +%s; } @@ -102,6 +106,7 @@ _scan_numbers() { wts="$(git -C "$ROOT" worktree list --porcelain 2>/dev/null | sed -n 's/^worktree //p')" || wts="" [ -n "$wts" ] || wts="$ROOT" while IFS= read -r wt; do + # shellcheck disable=SC2010 ls "$wt/docs/specs" 2>/dev/null | grep -oE 'SPEC-[0-9]+' || true # spec-active-ok: numbering scan of another worktree, picks no spec spec_files "$wt" | sed 's|.*/||' | grep -oE '^SPEC-[0-9]+' || true done <<< "$wts" @@ -149,14 +154,14 @@ _scan_pr_numbers() { _reservations() { [ -f "$RES_FILE" ] || return 0 local cutoff; cutoff=$(( $(now_epoch) - SPEC_RESERVE_TTL )) - while IFS= read -r line; do + while IFS= read -r line || [ -n "$line" ]; do case "$line" in *"| RESERVE |"*) ;; *) continue;; esac # Anchored to end-of-line (review LOW #4): `repo=` is always the trailing field, so this # exact-suffix match stops repo `foo` from also matching a line for `foo-bar`. - case "$line" in *"repo=$REPO") ;; *) continue;; esac + case "$line" in *" repo=$REPO") ;; *) continue;; esac local iso num e iso="${line%% | *}" - num="$(printf '%s' "$line" | grep -oE 'num=[0-9]+' | head -1 | cut -d= -f2)" + num=""; case "$line" in *" num="*) num="${line#* num=}"; num="${num%%[!0-9]*}" ;; esac [ -n "$num" ] || continue e="$(_iso_to_epoch "$iso")" # A line whose timestamp we cannot parse is kept (fail-safe: better to over-reserve than @@ -166,10 +171,17 @@ _reservations() { done < "$RES_FILE" } -# The full union readers see: the real scan PLUS live reservations. `_scan_numbers` is the -# original scan-only body verbatim; folding reservations in is purely additive. +# Permanent SPENT records for this repo (no TTL; anchored repo= match). +_spent() { + [ -f "$RES_FILE" ] || return 0 + REPO="$REPO" awk 'BEGIN{s=" repo="ENVIRON["REPO"];sl=length(s)} + {p=index($0,"| SPENT | spec="); if(!p||length($0)" >&2; return 64; } n="$(printf '%03d' "$((10#$n))")" - if _numbers | grep -qx "$((10#$n))" || _numbers | grep -qx "$n"; then + local nums; nums="$(_numbers)" + if grep -qxE "0*$((10#$n))" <<< "$nums"; then # Byte-identical to the original scan-only behavior when no reservations exist (Acceptance 4): the reservation # clause is appended ONLY when the ledger actually contributed a live number (review LOW #5). local src="seen in specs/, a branch, or a recent commit subject" [ -n "$(_reservations)" ] && src="seen in specs/, a branch, a recent commit subject, or a live reservation" + case $'\n'"$(_spent)"$'\n' in *$'\n'"$n"$'\n'*) src="seen in specs/, a branch, a recent commit subject, or a spent record; to reclaim, delete '| SPENT | spec=$n repo=$REPO' from $RES_FILE" ;; esac echo "SPEC-$n is TAKEN ($src)" >&2 return 1 fi @@ -196,156 +210,62 @@ check() { # ---- Atomic reservation -------------------------------------------------------------------- # Prune dead reservation lines IN PLACE (called only while the lock is held, so the rewrite # is serialized). Two independent rules: -# * EXPIRED (older than TTL) -> dropped for EVERY repo. Expiry is pure timestamp math and -# does not need the calling repo's git state, so a one-shot / archived repo's abandoned -# lines are cleaned up by ANY later reserve -- the machine-global ledger stays bounded -# (review MEDIUM #3). Non-RESERVE lines and unparseable timestamps are always kept. -# * REALIZED (number now in the real scan) -> dropped only for THIS repo, because "realized" -# is scoped to this repo's branches/specs/commits. Other repos' realized-ness is theirs -# to prune when they next reserve. +# * REALIZED (this repo, checked before age) -> promoted once to a permanent SPENT record +# so deleting the spec file or branch later never reissues the number. +# * EXPIRED unrealized (older than TTL) -> dropped for this repo, and for foreign repos whose +# directory no longer exists (preserving live foreign repos until they can observe realization). _prune_reservations() { [ -f "$RES_FILE" ] || return 0 local realized cutoff tmp realized="$(_scan_numbers)" cutoff=$(( $(now_epoch) - SPEC_RESERVE_TTL )) tmp="$RES_FILE.tmp.$$" - : > "$tmp" - local line iso num e keep is_res is_repo - while IFS= read -r line; do + local line iso num e keep is_res r key promoted=$'\n' + while IFS= read -r line || [ -n "$line" ]; do keep=1 is_res=0; case "$line" in *"| RESERVE |"*) is_res=1;; esac if [ "$is_res" = 1 ]; then iso="${line%% | *}" - num="$(printf '%s' "$line" | grep -oE 'num=[0-9]+' | head -1 | cut -d= -f2)" - # EXPIRED, cross-repo: drop any RESERVE line older than the TTL. - e="$(_iso_to_epoch "$iso")" - if [ -n "$e" ] && [ "$e" -lt "$cutoff" ]; then keep=0; fi - # REALIZED, this-repo only (anchored repo match, review LOW #4): drop if the number is - # now in this repo's real scan. Match both zero-padded and bare-int, as check() does. - is_repo=0; case "$line" in *"repo=$REPO") is_repo=1;; esac - if [ "$keep" = 1 ] && [ "$is_repo" = 1 ] && [ -n "$num" ]; then - if printf '%s\n' "$realized" | grep -qx "$num" || printf '%s\n' "$realized" | grep -qx "$((10#$num))"; then keep=0; fi - fi - fi - [ "$keep" = 1 ] && printf '%s\n' "$line" >> "$tmp" - done < "$RES_FILE" - mv -f "$tmp" "$RES_FILE" 2>/dev/null || rm -f "$tmp" -} - -# Lock-dir mtime as epoch seconds, portable + POISON-PROOF. GNU coreutils (`stat -c %Y`) -# FIRST, then BSD/macOS (`stat -f %m`). Critical: on Linux `stat -f %m` is the -# `--file-system` format and prints a NON-numeric token with EXIT 0 (not an error), so a -# BSD-first `stat -f %m || stat -c %Y` never reaches the fallback and returns garbage. That -# garbage poisons the `lockage` arithmetic in `_reserve_lock`, making every fresh lock look -# older-than-TTL -> every contender spuriously RECLAIMS a live sibling's lock -> the mutex -# fails OPEN (the Linux-only T2/T9 failure the macOS CI masked). Only a pure-integer result -# is accepted; anything else -> empty -> the caller treats the lock as not-yet-stale (safe: -# it waits rather than steals). GNU-first so Linux hits the numeric path directly. -_lock_mtime_epoch() { - local d="$1" v="" - v="$(stat -c %Y "$d" 2>/dev/null)"; case "$v" in ''|*[!0-9]*) v="";; esac - if [ -z "$v" ]; then v="$(stat -f %m "$d" 2>/dev/null)"; case "$v" in ''|*[!0-9]*) v="";; esac; fi - printf '%s' "$v" -} - -# Release the lock ONLY if we still own it (review MAJOR #1). The owner token guards against -# deleting a lock a stale-reclaim already handed to another process: a reserve that lost the -# lock mid-flight must never rmdir the new holder's lock. Idempotent + best-effort. -_reserve_unlock() { - [ "$(cat "$RES_LOCK/owner" 2>/dev/null)" = "${_LOCK_TOKEN:-}" ] || return 0 - rm -f "$RES_LOCK/owner" 2>/dev/null || true - rmdir "$RES_LOCK" 2>/dev/null || true -} - -# Acquire the mkdir-mutex (portable; macOS has no flock, orchestrate.sh is no-flock by -# contract). Exactly one racer creates the dir; the winner stamps an OWNER TOKEN inside so a -# later reclaim + the release path can tell a live holder from a dead one. A lock DIR older -# than TTL is reclaimed (a dead holder must not wedge the wave). Loud fail after a bounded -# number of tries so a live contender never spins forever silently. -_reserve_lock() { - mkdir -p "$RES_DIR" 2>/dev/null || true - # Per-acquire unique token: pid + a random nonce + epoch defeats pid-reuse aliasing. - _LOCK_TOKEN="$$.${RANDOM}.$(now_epoch)" - # Bounded spin so a live contender never wedges forever; env-overridable for tests. - local tries=0 max="${SPEC_RESERVE_MAX_TRIES:-600}" # ~ up to 30s; ample for a wave of a few workers - while ! mkdir "$RES_LOCK" 2>/dev/null; do - if [ -d "$RES_LOCK" ]; then - # DEAD-HOLDER reclaim, tried FIRST: a holder that died with the lock held is the common - # case, and its owner stamp names the pid. The TTL path below is the fallback for a lock - # whose owner file is missing or unparseable, which takes 24h to clear. `kill -0` on a pid - # this user cannot signal (EPERM, another user's process) SUCCEEDS, so such a holder reads - # as alive and its lock is left alone. - local owner_pid - owner_pid="$(cat "$RES_LOCK/owner" 2>/dev/null)" - owner_pid="${owner_pid%%.*}" - case "$owner_pid" in - ''|*[!0-9]*) ;; - *) - if ! kill -0 "$owner_pid" 2>/dev/null; then - # Owner file first: rmdir refuses a non-empty dir. Never a recursive rm. - rm -f "$RES_LOCK/owner" 2>/dev/null || true - rmdir "$RES_LOCK" 2>/dev/null || true - continue - fi - ;; - esac - # stale-lock reclaim: if the lock dir is older than TTL, a prior holder died with it held. - local lockage e - e="$(_lock_mtime_epoch "$RES_LOCK")" - if [ -n "$e" ]; then - lockage=$(( $(now_epoch) - e )) - if [ "$lockage" -gt "$SPEC_RESERVE_TTL" ]; then - # Reclaim a genuinely-old lock: remove its owner stamp then the dir (rmdir refuses a - # non-empty dir, so the owner file must go first). Never a recursive rm. - rm -f "$RES_LOCK/owner" 2>/dev/null || true - rmdir "$RES_LOCK" 2>/dev/null || true - continue + num=""; case "$line" in *" num="*) num="${line#* num=}"; num="${num%%[!0-9]*}" ;; esac + r=""; case "$line" in *" repo="*) r="${line#* repo=}";; esac + if [ "$r" = "$REPO" ] && [ -n "$num" ] && grep -qxE "0*$((10#$num))" <<< "$realized"; then + key="spec=$(printf '%03d' "$((10#$num))") repo=$REPO" + if S="| SPENT | $key" awk 'BEGIN{s=ENVIRON["S"];l=length(s)} length($0)>=l&&substr($0,length($0)-l+1)==s{f=1;exit} END{exit !f}' "$RES_FILE"; then + keep=0 + else + case "$promoted" in + *$'\n'"$key"$'\n'*) keep=0 ;; + *) line="$iso | SPENT | $key"; promoted="${promoted}${key}"$'\n'; keep=1 ;; + esac fi + else + e="$(_iso_to_epoch "$iso")" + if [ -n "$e" ] && [ "$e" -lt "$cutoff" ] && { [ "$r" = "$REPO" ] || [ ! -d "$r" ]; }; then keep=0; fi fi fi - tries=$((tries + 1)) - [ "$tries" -ge "$max" ] && { echo "spec-next reserve: could not acquire lock after $max tries ($RES_LOCK)" >&2; return 1; } - # randomized sub-100ms backoff to desynchronize racers - sleep "0.0$(( (RANDOM % 9) + 1 ))" - done - printf '%s' "$_LOCK_TOKEN" > "$RES_LOCK/owner" 2>/dev/null || true - return 0 + if [ "$keep" = 1 ]; then printf '%s\n' "$line"; fi + done < "$RES_FILE" > "$tmp" + mv -f "$tmp" "$RES_FILE" 2>/dev/null || rm -f "$tmp" } -# reserve: atomically claim + print the next free number. acquire -> compute next (folding -# live reservations) -> RE-VALIDATE ownership -> append the claim -> prune dead lines -> -# release. Indivisible, so two concurrent `reserve` calls serialize and get DISTINCT numbers. -# The ownership re-check (review MAJOR #1) closes the window where a TTL-stale reclaim could -# hand our lock to another process WHILE we were still scanning: if we no longer own the -# lock, discard this attempt and retry rather than append under a lock we lost. +# reserve: atomically claim + print the next free number under kernel flock(2) on fd 9 +# (lib/goal/goal-lock.sh). The kernel releases the lock when fd 9 closes or the process exits. reserve() { - local attempt=0 n - while [ "$attempt" -lt 5 ]; do - attempt=$((attempt + 1)) - _reserve_lock || return 1 - # Split traps (review MAJOR #2): a bare `trap ... INT TERM` releases the lock but bash then - # RESUMES the critical section unprotected. On a signal we must actually EXIT after cleanup. - trap '_reserve_unlock' EXIT - trap '_reserve_unlock; exit 130' INT - trap '_reserve_unlock; exit 143' TERM - n="$(next)" - if [ "$(cat "$RES_LOCK/owner" 2>/dev/null)" != "$_LOCK_TOKEN" ]; then - # Lost the lock to a stale-reclaim mid-scan. We do NOT own it, so do NOT unlock - # (that is the new holder's lock); clear the trap and retry from scratch. - trap - EXIT INT TERM - continue - fi - mkdir -p "$RES_DIR" 2>/dev/null || true - printf '%s | RESERVE | num=%s repo=%s\n' \ - "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$n" "$REPO" >> "$RES_FILE" - _prune_reservations - _reserve_unlock - trap - EXIT INT TERM - printf '%s\n' "$n" - return 0 - done - echo "spec-next reserve: lost the lock to a stale-reclaim race ${attempt}x; giving up" >&2 - return 1 + command -v goal_lock >/dev/null 2>&1 || { echo "REFUSED: spec-next reserve: goal-lock.sh missing" >&2; return 1; } + mkdir -p "$(dirname "$RES_FILE")" 2>/dev/null || true + goal_lock "$RES_LOCK" || return 1 + trap 'exec 9>&- 2>/dev/null || true' EXIT + trap 'exec 9>&- 2>/dev/null || true; exit 130' INT + trap 'exec 9>&- 2>/dev/null || true; exit 143' TERM + local n + n="$(next 9>&-)" + if [ -s "$RES_FILE" ] && [ -n "$(tail -c 1 "$RES_FILE")" ]; then printf '\n' >> "$RES_FILE"; fi + printf '%s | RESERVE | num=%s repo=%s\n' \ + "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$n" "$REPO" >> "$RES_FILE" + _prune_reservations 9>&- + exec 9>&- 2>/dev/null || true + trap - EXIT INT TERM + printf '%s\n' "$n" } main() { diff --git a/tests/test-spec-next-spent.sh b/tests/test-spec-next-spent.sh new file mode 100755 index 000000000..c14e8ed52 --- /dev/null +++ b/tests/test-spec-next-spent.sh @@ -0,0 +1,629 @@ +#!/usr/bin/env bash +# test-spec-next-spent.sh -- realized spec reservations stay spent permanently +# and reserve serializes via kernel flock (lib/goal/goal-lock.sh), not mkdir. +# Run: bash tests/test-spec-next-spent.sh (also /bin/bash tests/test-spec-next-spent.sh). +set -uo pipefail + +KIT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +SN="$KIT_DIR/lib/spec/spec-next.sh" +LOCK_LIB="$KIT_DIR/lib/goal/goal-lock.sh" +RUN_BASH="${BASH:-bash}" +PERL_BIN="$(command -v perl || true)" +REAL_MKDIR="$(command -v mkdir)" + +SANDBOX="$(mktemp -d "${TMPDIR:-/tmp}/kit-spec-spent.XXXXXX")" || exit 1 +MAIN_PID="$$" +BG_PIDS=() +cleanup() { + [ "$(sh -c 'echo $PPID')" = "$MAIN_PID" ] || return 0 + local p + for p in "${BG_PIDS[@]+"${BG_PIDS[@]}"}"; do + kill -9 "$p" 2>/dev/null || true + wait "$p" 2>/dev/null || true + done + chmod -R u+w "$SANDBOX" 2>/dev/null || true + rm -rf "$SANDBOX" +} +trap cleanup EXIT + +export HOME="$SANDBOX/home" +export XDG_CONFIG_HOME="$SANDBOX/config" +export XDG_STATE_HOME="$SANDBOX/state" +export XDG_CACHE_HOME="$SANDBOX/cache" +export XDG_DATA_HOME="$SANDBOX/data" +export GIT_CONFIG_GLOBAL="$SANDBOX/gitconfig" +export GIT_CONFIG_NOSYSTEM=1 +export CHROME="/nonexistent" +export KIT_CONFIG_OPERATOR="$SANDBOX/operator" +export SPEC_NEXT_NO_PR_SCAN=1 +mkdir -p "$HOME" "$XDG_CONFIG_HOME" "$XDG_STATE_HOME" "$XDG_CACHE_HOME" "$XDG_DATA_HOME" "$KIT_CONFIG_OPERATOR" +git config --global user.name "Test User" +git config --global user.email "test@example.com" +git config --global init.defaultBranch main + +GREEN='\033[0;32m'; RED='\033[0;31m'; NC='\033[0m' +PASS=0; FAIL=0; TOTAL=0 +ok() { TOTAL=$((TOTAL+1)); PASS=$((PASS+1)); echo -e " ${GREEN}PASS${NC} $1"; } +bad() { TOTAL=$((TOTAL+1)); FAIL=$((FAIL+1)); echo -e " ${RED}FAIL${NC} $1"; } +eq() { if [ "$2" = "$3" ]; then ok "$1"; else bad "$1 (want '$3' got '$2')"; fi; } +expect() { + if { trap '' PIPE; printf '%s' "$3" 2>/dev/null || :; } | grep -q "$2"; then ok "$1"; else bad "$1 (missing '$2' in: $3)"; fi +} +count() { local c; c="$(grep -c "$1" "$2" 2>/dev/null)"; printf '%s' "${c:-0}"; } + +# Check whether $1 (a lock path) is unheld: no directory and a non-blocking flock succeeds. +lock_state() { + local lf="$1" + [ -d "$lf" ] && { echo "held-dir"; return 0; } + [ -e "$lf" ] || { echo "free"; return 0; } + if ( + # shellcheck source=lib/goal/goal-lock.sh + source "$LOCK_LIB" + GOAL_LOCK_TIMEOUT=0 goal_lock "$lf" 2>/dev/null + ); then + echo "free" + else + echo "held" + fi +} + +# Hold an exclusive kernel flock directly via perl on $1; touch $2 when locked. +hold_flock() { + local lf="$1" ready="$2" + mkdir -p "$(dirname "$lf")" + "$PERL_BIN" -MFcntl=:flock -e ' + open(my $f, ">>", $ARGV[0]) or exit 2; + flock($f, LOCK_EX|LOCK_NB) or exit 3; + open(my $r, ">", $ARGV[1]) or exit 4; + close($r); + sleep 30; + ' "$lf" "$ready" & + HOLD_PID=$! + BG_PIDS+=("$HOLD_PID") + local i=0 + while [ ! -e "$ready" ] && [ "$i" -lt 80 ]; do sleep 0.05; i=$((i + 1)); done +} + +mkdir -p "$SANDBOX/repos" +mk_repo() { + local seed="${1:-005}" name="${2:-}" r + if [ -n "$name" ]; then + r="$SANDBOX/repos/$name" + mkdir -p "$r/docs/specs" + else + r="$(mktemp -d "$SANDBOX/repos/r.XXXXXX")" || exit 1 + mkdir -p "$r/docs/specs" + fi + git -C "$r" init -q + : > "$r/docs/specs/SPEC-${seed}-init.md" + git -C "$r" add -A + git -C "$r" commit -qm "init" >/dev/null 2>&1 + printf '%s\n' "$r" +} + +key() { (cd "$1" && pwd -P); } +sn_run() { + local repo="$1" res="$2"; shift 2 + (cd "$repo" && SPEC_RESERVE_FILE="$res" "$RUN_BASH" "$SN" "$@") +} + +# Run a command with a wall-clock cap in seconds, writing stdout to $2. +# Sets ELAPSED and TIMED_OUT=1 if killed. +run_timed() { + local limit="$1" out="$2"; shift 2 + local t0 pid ticks=0 + TIMED_OUT=0 + t0="$(date -u +%s)" + "$@" > "$out" 2>/dev/null & + pid="$!" + while [ "$ticks" -lt $((limit * 10)) ]; do + if ! kill -0 "$pid" 2>/dev/null; then break; fi + sleep 0.1 + ticks=$((ticks + 1)) + done + if kill -0 "$pid" 2>/dev/null; then + TIMED_OUT=1 + kill "$pid" 2>/dev/null || true + sleep 0.1 + kill -9 "$pid" 2>/dev/null || true + fi + wait "$pid" 2>/dev/null || true + ELAPSED=$(( $(date -u +%s) - t0 )) +} + +# ============================================================ +echo "=== T1: realized file deleted -- number stays spent ===" +# ============================================================ +R="$(mk_repo 005)"; RES="$SANDBOX/t1.log" +N1="$(sn_run "$R" "$RES" reserve 2>/dev/null)" +eq "T1 first reserve is 006" "$N1" "006" +: > "$R/docs/specs/SPEC-006-temp.md" +N2="$(sn_run "$R" "$RES" reserve 2>/dev/null)" +eq "T1 second reserve prunes 006 and returns 007" "$N2" "007" +rm -f "$R/docs/specs/SPEC-006-temp.md" +CHK1="$(sn_run "$R" "$RES" check 006 2>&1; echo "rc=$?")" +expect "T1 check 006 stays TAKEN after file deletion" "TAKEN" "$CHK1" +expect "T1 check 006 exits 1 after file deletion" "rc=1" "$CHK1" +eq "T1 ledger holds no RESERVE line for 006" "$(count '| RESERVE |.*num=006' "$RES")" "0" +NON_RES="$(grep -v '| RESERVE |' "$RES" | grep -c "repo=$(key "$R")$" || true)" +eq "T1 ledger holds one permanent non-RESERVE record for this repo" "$NON_RES" "1" +# Let the unrealized 007 reservation expire while keeping the spent record intact. +sleep 2 +NEXT1="$(cd "$R" && SPEC_RESERVE_TTL=1 SPEC_RESERVE_FILE="$RES" "$RUN_BASH" "$SN" next 2>/dev/null)" +eq "T1 next does not reissue deleted 006 after 007 expires" "$NEXT1" "007" +CHK1B="$(cd "$R" && SPEC_RESERVE_TTL=1 SPEC_RESERVE_FILE="$RES" "$RUN_BASH" "$SN" check 006 2>&1; echo "rc=$?")" +expect "T1 check 006 stays TAKEN past TTL" "rc=1" "$CHK1B" +CHK1C="$(cd "$R" && SPEC_RESERVE_TTL=1 SPEC_RESERVE_FILE="$RES" "$RUN_BASH" "$SN" check 007 2>&1; echo "rc=$?")" +expect "T1 expired unrealized 007 is free again" "rc=0" "$CHK1C" + +# ============================================================ +echo "=== T2: realized branch deleted -- number stays spent ===" +# ============================================================ +R="$(mk_repo 005)"; RES="$SANDBOX/t2.log" +N1="$(sn_run "$R" "$RES" reserve 2>/dev/null)" +eq "T2 first reserve is 006" "$N1" "006" +git -C "$R" branch "feat/SPEC-006-gone" >/dev/null 2>&1 +N2="$(sn_run "$R" "$RES" reserve 2>/dev/null)" +eq "T2 second reserve prunes 006 and returns 007" "$N2" "007" +git -C "$R" branch -D "feat/SPEC-006-gone" >/dev/null 2>&1 +CHK2="$(sn_run "$R" "$RES" check 006 2>&1; echo "rc=$?")" +expect "T2 check 006 stays TAKEN after branch deletion" "TAKEN" "$CHK2" +expect "T2 check 006 exits 1 after branch deletion" "rc=1" "$CHK2" +sleep 2 +NEXT2="$(cd "$R" && SPEC_RESERVE_TTL=1 SPEC_RESERVE_FILE="$RES" "$RUN_BASH" "$SN" next 2>/dev/null)" +eq "T2 next does not reissue deleted-branch 006 after 007 expires" "$NEXT2" "007" + +# ============================================================ +echo "=== T3: expired unrealized dropped; ancient spent stays taken ===" +# ============================================================ +R="$(mk_repo 005)"; RES="$SANDBOX/t3.log" +sn_run "$R" "$RES" reserve >/dev/null 2>&1 +: > "$R/docs/specs/SPEC-006-old.md" +sn_run "$R" "$RES" reserve >/dev/null 2>&1 +rm -f "$R/docs/specs/SPEC-006-old.md" +sed 's/^[0-9T:-]*Z/1970-01-01T00:00:00Z/' "$RES" > "$RES.aged" +mv "$RES.aged" "$RES" +printf '1970-01-01T00:00:00Z | RESERVE | num=009 repo=%s\n' "$(key "$R")" >> "$RES" +NEXT3="$(sn_run "$R" "$RES" next 2>/dev/null)" +eq "T3 ancient spent 006 still counts while expired 007 and 009 do not" "$NEXT3" "007" +CHK3A="$(sn_run "$R" "$RES" check 006 2>&1; echo "rc=$?")" +expect "T3 ancient spent 006 is TAKEN" "rc=1" "$CHK3A" +CHK3B="$(sn_run "$R" "$RES" check 009 2>&1; echo "rc=$?")" +expect "T3 expired unrealized 009 is free" "rc=0" "$CHK3B" +N3="$(sn_run "$R" "$RES" reserve 2>/dev/null)" +eq "T3 reserve after expiry hands out 007" "$N3" "007" +eq "T3 expired unrealized 009 was pruned" "$(count 'num=009' "$RES")" "0" + +# ============================================================ +echo "=== T4: repo isolation and prefix-sharing repos ===" +# ============================================================ +RA="$(mk_repo 005 t4/app)"; RB="$(mk_repo 005 t4/app-extra)"; RES="$SANDBOX/t4.log" +sn_run "$RA" "$RES" reserve >/dev/null 2>&1 +: > "$RA/docs/specs/SPEC-006-a.md" +sn_run "$RA" "$RES" reserve >/dev/null 2>&1 +rm -f "$RA/docs/specs/SPEC-006-a.md" +CHK4B="$(sn_run "$RB" "$RES" check 006 2>&1; echo "rc=$?")" +expect "T4 repo app-extra sees 006 as free" "rc=0" "$CHK4B" +NEXT4B="$(sn_run "$RB" "$RES" next 2>/dev/null)" +eq "T4 repo app-extra next is 006" "$NEXT4B" "006" +: > "$RB/docs/specs/SPEC-007-b.md" +sn_run "$RB" "$RES" reserve >/dev/null 2>&1 +: > "$RB/docs/specs/SPEC-008-b.md" +sn_run "$RB" "$RES" reserve >/dev/null 2>&1 +rm -f "$RB/docs/specs/SPEC-008-b.md" +CHK4A="$(sn_run "$RA" "$RES" check 008 2>&1; echo "rc=$?")" +expect "T4 prefix repo app ignores app-extra spent 008" "rc=0" "$CHK4A" +CHK4B2="$(sn_run "$RB" "$RES" check 008 2>&1; echo "rc=$?")" +expect "T4 repo app-extra keeps its own spent 008" "rc=1" "$CHK4B2" +sn_run "$RA" "$RES" reserve >/dev/null 2>&1 +CHK4B3="$(sn_run "$RB" "$RES" check 008 2>&1; echo "rc=$?")" +expect "T4 repo A reserve preserves repo B spent 008" "rc=1" "$CHK4B3" + +# ============================================================ +echo "=== T5: numbers sharing a prefix do not touch each other ===" +# ============================================================ +R="$(mk_repo 009)"; RES="$SANDBOX/t5a.log" +N5A="$(sn_run "$R" "$RES" reserve 2>/dev/null)" +eq "T5a reserve is 010" "$N5A" "010" +: > "$R/docs/specs/SPEC-010-p.md" +sn_run "$R" "$RES" reserve >/dev/null 2>&1 +rm -f "$R/docs/specs/SPEC-010-p.md" +CHK5A1="$(sn_run "$R" "$RES" check 010 2>&1; echo "rc=$?")" +CHK5A2="$(sn_run "$R" "$RES" check 100 2>&1; echo "rc=$?")" +CHK5A3="$(sn_run "$R" "$RES" check 0100 2>&1; echo "rc=$?")" +expect "T5a spent 010 is TAKEN" "rc=1" "$CHK5A1" +expect "T5a 100 is still free when 010 is spent" "rc=0" "$CHK5A2" +expect "T5a 0100 is still free when 010 is spent" "rc=0" "$CHK5A3" + +R2="$(mk_repo 099)"; RES2="$SANDBOX/t5b.log" +N5B="$(sn_run "$R2" "$RES2" reserve 2>/dev/null)" +eq "T5b reserve is 100" "$N5B" "100" +: > "$R2/docs/specs/SPEC-100-p.md" +sn_run "$R2" "$RES2" reserve >/dev/null 2>&1 +rm -f "$R2/docs/specs/SPEC-100-p.md" +CHK5B1="$(sn_run "$R2" "$RES2" check 100 2>&1; echo "rc=$?")" +CHK5B2="$(sn_run "$R2" "$RES2" check 010 2>&1; echo "rc=$?")" +CHK5B3="$(sn_run "$R2" "$RES2" check 1000 2>&1; echo "rc=$?")" +expect "T5b spent 100 is TAKEN" "rc=1" "$CHK5B1" +expect "T5b 010 is still free when 100 is spent" "rc=0" "$CHK5B2" +expect "T5b 1000 is still free when 100 is spent" "rc=0" "$CHK5B3" + +R3="$(mk_repo 099)"; RES3="$SANDBOX/t5c.log" +sn_run "$R3" "$RES3" reserve >/dev/null 2>&1 +: > "$R3/docs/specs/SPEC-1000-p.md" +sn_run "$R3" "$RES3" reserve >/dev/null 2>&1 +eq "T5c live RESERVE 100 is not falsely promoted by SPEC-1000" "$(count '| RESERVE |.*num=100 ' "$RES3")" "1" + +# ============================================================ +echo "=== T6: existing check messages stay unchanged ===" +# ============================================================ +R="$(mk_repo 005)"; RES="$SANDBOX/t6.log" +MSG6A="$(sn_run "$R" "$RES" check 005 2>&1 | grep -v '^spec-next: open PR heads not scanned')" +eq "T6 empty-ledger TAKEN message unchanged" "$MSG6A" "SPEC-005 is TAKEN (seen in specs/, a branch, or a recent commit subject)" +MSG6F="$(sn_run "$R" "$RES" check 999 2>&1 | grep -v '^spec-next: open PR heads not scanned')" +eq "T6 free message unchanged" "$MSG6F" "SPEC-999 is free" +sn_run "$R" "$RES" reserve >/dev/null 2>&1 +MSG6B="$(sn_run "$R" "$RES" check 006 2>&1 | grep -v '^spec-next: open PR heads not scanned')" +eq "T6 live-reservation TAKEN message unchanged" "$MSG6B" "SPEC-006 is TAKEN (seen in specs/, a branch, a recent commit subject, or a live reservation)" + +# ============================================================ +echo "=== T7: ledger written by the old code ===" +# ============================================================ +R="$(mk_repo 005)"; RES="$SANDBOX/t7.log" +NOW_ISO="$(date -u +%Y-%m-%dT%H:%M:%SZ)" +: > "$R/docs/specs/SPEC-006-oldcode.md" +{ + printf '%s | RESERVE | num=006 repo=%s\n' "$NOW_ISO" "$(key "$R")" + printf '%s | RESERVE | num=008 repo=%s\n' "$NOW_ISO" "$(key "$R")" + printf '1970-01-01T00:00:00Z | RESERVE | num=009 repo=%s\n' "$(key "$R")" +} > "$RES" +N7="$(sn_run "$R" "$RES" reserve 2>/dev/null)" +eq "T7 reserve on old-code ledger returns 009" "$N7" "009" +rm -f "$R/docs/specs/SPEC-006-oldcode.md" +CHK7A="$(sn_run "$R" "$RES" check 006 2>&1; echo "rc=$?")" +CHK7B="$(sn_run "$R" "$RES" check 008 2>&1; echo "rc=$?")" +expect "T7 realized old-code 006 stays TAKEN after deletion" "rc=1" "$CHK7A" +expect "T7 live old-code 008 stays TAKEN" "rc=1" "$CHK7B" +eq "T7 expired old-code 009 line dropped" "$(count '1970-01-01' "$RES")" "0" + +# ============================================================ +echo "=== T8: read-only ledger ===" +# ============================================================ +R="$(mk_repo 005)"; RO_DIR="$SANDBOX/t8-ro"; mkdir -p "$RO_DIR"; RES="$RO_DIR/res.log" +sn_run "$R" "$RES" reserve >/dev/null 2>&1 +: > "$R/docs/specs/SPEC-006-ro.md" +sn_run "$R" "$RES" reserve >/dev/null 2>&1 +rm -f "$R/docs/specs/SPEC-006-ro.md" +sleep 2 +chmod 444 "$RES" +BEFORE_RO="$(cksum < "$RES")" +CHK8="$(cd "$R" && SPEC_RESERVE_TTL=1 SPEC_RESERVE_FILE="$RES" "$RUN_BASH" "$SN" check 006 2>&1; echo "rc=$?")" +NEXT8="$(cd "$R" && SPEC_RESERVE_TTL=1 SPEC_RESERVE_FILE="$RES" "$RUN_BASH" "$SN" next 2>/dev/null; echo "rc=$?")" +expect "T8 check reads spent 006 from read-only ledger" "rc=1" "$CHK8" +eq "T8 next reads spent 006 from read-only ledger" "$NEXT8" "$(printf '007\nrc=0')" +RES8="$(cd "$R" && GOAL_LOCK_TIMEOUT=2 SPEC_RESERVE_FILE="$RES" "$RUN_BASH" "$SN" reserve 2>/dev/null; echo "rc=$?")" +expect "T8 reserve on read-only ledger fails cleanly" "rc=1" "$RES8" +eq "T8 read-only ledger untouched after failed reserve" "$(cksum < "$RES")" "$BEFORE_RO" +eq "T8 lock released after failed read-only reserve" "$(lock_state "$RES.lock")" "free" +chmod 555 "$RO_DIR" +CHK8D="$(cd "$R" && SPEC_RESERVE_TTL=1 SPEC_RESERVE_FILE="$RES" "$RUN_BASH" "$SN" check 006 2>&1; echo "rc=$?")" +expect "T8 check works when ledger dir is read-only" "rc=1" "$CHK8D" +chmod 755 "$RO_DIR"; chmod 644 "$RES" + +# ============================================================ +echo "=== T9: 20 parallel reservations (all distinct, skips spent) ===" +# ============================================================ +R="$(mk_repo 005)"; RES="$SANDBOX/t9.log"; ACC="$SANDBOX/t9.acc"; : > "$ACC" +sn_run "$R" "$RES" reserve >/dev/null 2>&1 +: > "$R/docs/specs/SPEC-006-par.md" +sn_run "$R" "$RES" reserve >/dev/null 2>&1 +rm -f "$R/docs/specs/SPEC-006-par.md" +sed 's/^[0-9T:-]*Z | RESERVE |/1970-01-01T00:00:00Z | RESERVE |/' "$RES" > "$RES.tmp" +mv "$RES.tmp" "$RES" +PIDS=() +for i in $(seq 1 20); do + (cd "$R" && exec env SPEC_RESERVE_FILE="$RES" GOAL_LOCK_TIMEOUT=30 "$RUN_BASH" "$SN" reserve) >> "$ACC" 2>"$SANDBOX/t9.err.$i" & + PIDS+=("$!") +done +T9_TIMED_OUT=0 +T9_DEADLINE=$(( $(date -u +%s) + 90 )) +while :; do + ALIVE=0 + for p in "${PIDS[@]}"; do + if kill -0 "$p" 2>/dev/null; then ALIVE=1; break; fi + done + [ "$ALIVE" -eq 0 ] && break + if [ "$(date -u +%s)" -ge "$T9_DEADLINE" ]; then T9_TIMED_OUT=1; break; fi + sleep 0.2 +done +if [ "$T9_TIMED_OUT" -eq 1 ]; then + for p in "${PIDS[@]}"; do + kill -9 "$p" 2>/dev/null || true + done +fi +for p in "${PIDS[@]}"; do + wait "$p" 2>/dev/null || true +done +T9_TOTAL="$(grep -c . "$ACC" | tr -d ' ')" +T9_DISTINCT="$(sort -u "$ACC" | grep -c . | tr -d ' ')" +T9_REUSED="$(grep -cx '006' "$ACC" 2>/dev/null || true)" +T9_LOCK="$(lock_state "$RES.lock")" +if [ "$T9_TOTAL" != "20" ] || [ "$T9_LOCK" != "free" ]; then + T9_ERR="$(grep -h . "$SANDBOX"/t9.err.* 2>/dev/null | grep -v '^spec-next: open PR heads not scanned' | head -5 | tr '\n' ' ' || true)" + echo -e " ${RED}FAIL${NC} T9 diag: timed_out=$T9_TIMED_OUT lock=$T9_LOCK err=${T9_ERR:-none}" +fi +eq "T9 20 parallel reservations emitted 20 numbers" "$T9_TOTAL" "20" +eq "T9 all 20 numbers are distinct" "$T9_DISTINCT" "20" +eq "T9 spent 006 was never reissued to any racer" "${T9_REUSED:-0}" "0" +eq "T9 lock released after parallel wave" "$T9_LOCK" "free" + +# ============================================================ +echo "=== T10: ledger line count after 50 rounds (no growth beyond 1 per number) ===" +# ============================================================ +R="$(mk_repo 005)"; RES="$SANDBOX/t10.log" +for _ in $(seq 1 50); do + N10="$(sn_run "$R" "$RES" reserve 2>/dev/null)" + : > "$R/docs/specs/SPEC-${N10}-r.md" +done +N10_FINAL="$(sn_run "$R" "$RES" reserve 2>/dev/null)" +LINES10="$(wc -l < "$RES" | tr -d ' ')" +eq "T10 51st reserve is 056" "$N10_FINAL" "056" +eq "T10 ledger has exactly 51 lines (50 spent + 1 live)" "$LINES10" "51" +for _ in $(seq 1 5); do + sn_run "$R" "$RES" reserve >/dev/null 2>&1 +done +LINES10B="$(wc -l < "$RES" | tr -d ' ')" +eq "T10 5 extra reserves add only 5 live lines (56 total)" "$LINES10B" "56" +DUP10="$(grep -v '| RESERVE |' "$RES" | sort | uniq -d | wc -l | tr -d ' ')" +eq "T10 zero duplicate permanent lines" "$DUP10" "0" + +# ============================================================ +echo "=== T11: foreign expired line kept while dir exists; own expired realized promoted ===" +# ============================================================ +RA="$(mk_repo 005 t11/a)"; RB="$(mk_repo 005 t11/b)"; RC_REPO="$(mk_repo 005 t11/c)" +RES="$SANDBOX/t11.log" +KEY_A="$(key "$RA")"; KEY_B="$(key "$RB")"; KEY_C="$(key "$RC_REPO")" +rm -rf "$RC_REPO" +{ + printf '1970-01-01T00:00:00Z | RESERVE | num=006 repo=%s\n' "$KEY_B" + printf '1970-01-01T00:00:00Z | RESERVE | num=007 repo=%s\n' "$KEY_C" + printf '1970-01-01T00:00:00Z | RESERVE | num=008 repo=%s\n' "$KEY_A" +} > "$RES" +: > "$RA/docs/specs/SPEC-008-a.md" +N11A="$(sn_run "$RA" "$RES" reserve 2>/dev/null)" +eq "T11 repo A reserve succeeds after own realized expired 008" "$N11A" "009" +eq "T11 foreign expired line for existing dir B is preserved" "$(count "num=006 repo=${KEY_B}$" "$RES")" "1" +eq "T11 foreign expired line for deleted dir C is pruned" "$(count "num=007 repo=${KEY_C}$" "$RES")" "0" +rm -f "$RA/docs/specs/SPEC-008-a.md" +CHK11A="$(sn_run "$RA" "$RES" check 008 2>&1; echo "rc=$?")" +expect "T11 own expired realized 008 stays TAKEN after file deletion" "rc=1" "$CHK11A" +eq "T11 own expired realized 008 promoted to SPENT" "$(count "| SPENT | spec=008 repo=${KEY_A}$" "$RES")" "1" +: > "$RB/docs/specs/SPEC-006-b.md" +N11B="$(sn_run "$RB" "$RES" reserve 2>/dev/null)" +eq "T11 repo B reserve advances past realized 006" "$N11B" "007" +rm -f "$RB/docs/specs/SPEC-006-b.md" +CHK11B="$(sn_run "$RB" "$RES" check 006 2>&1; echo "rc=$?")" +expect "T11 repo B preserved expired claim became permanent SPENT" "rc=1" "$CHK11B" + +# ============================================================ +echo "=== T12: promotion dedupe (anchored) and 5,000 SPENT scale + 4 concurrent workers ===" +# ============================================================ +RA="$(mk_repo 005 t12/app)"; RB="$(mk_repo 005 t12/app-extra)"; RES="$SANDBOX/t12a.log" +KEY_A="$(key "$RA")"; KEY_B="$(key "$RB")" +NOW_ISO="$(date -u +%Y-%m-%dT%H:%M:%SZ)" +{ + printf '%s | SPENT | spec=006 repo=%s\n' "$NOW_ISO" "$KEY_A" + printf '%s | RESERVE | num=006 repo=%s\n' "$NOW_ISO" "$KEY_A" + printf '%s | RESERVE | num=007 repo=%s\n' "$NOW_ISO" "$KEY_A" + printf '%s | RESERVE | num=007 repo=%s\n' "$NOW_ISO" "$KEY_A" + printf '%s | SPENT | spec=008 repo=%s\n' "$NOW_ISO" "$KEY_B" + printf '%s | RESERVE | num=008 repo=%s\n' "$NOW_ISO" "$KEY_A" +} > "$RES" +: > "$RA/docs/specs/SPEC-006-dup.md" +: > "$RA/docs/specs/SPEC-007-dup.md" +: > "$RA/docs/specs/SPEC-008-prefix.md" +N12A="$(sn_run "$RA" "$RES" reserve 2>/dev/null)" +eq "T12a reserve advances to 009" "$N12A" "009" +eq "T12a existing SPENT 006 not duplicated on promotion" "$(count "| SPENT | spec=006 repo=${KEY_A}$" "$RES")" "1" +eq "T12a duplicate RESERVE 007 promoted once" "$(count "| SPENT | spec=007 repo=${KEY_A}$" "$RES")" "1" +eq "T12a sibling app-extra SPENT 008 does not block app SPENT 008 (anchored)" "$(count "| SPENT | spec=008 repo=${KEY_A}$" "$RES")" "1" +eq "T12a sibling app-extra SPENT 008 stays intact" "$(count "| SPENT | spec=008 repo=${KEY_B}$" "$RES")" "1" + +R5K="$(mk_repo 005 t12/scale)"; RES5K="$SANDBOX/t12-5k.log" +KEY5K="$(key "$R5K")" +awk -v r="$KEY5K" 'BEGIN{for(i=1;i<=5000;i++) printf "2026-01-01T00:00:00Z | SPENT | spec=%03d repo=%s\n", i, r}' > "$RES5K" +OUT5K="$SANDBOX/t12-5k.out" +run_timed 16 "$OUT5K" env SPEC_RESERVE_FILE="$RES5K" "$RUN_BASH" -c 'cd "$1" && exec "$2" "$3" reserve' _ "$R5K" "$RUN_BASH" "$SN" +N5K="$(cat "$OUT5K" 2>/dev/null)" +if [ "$TIMED_OUT" -eq 0 ] && [ "$ELAPSED" -le 15 ]; then + ok "T12b single reserve with 5,000 SPENT completed in ${ELAPSED}s (<= 15s)" +else + bad "T12b single reserve with 5,000 SPENT too slow or timed out (${ELAPSED}s, timed_out=$TIMED_OUT)" +fi +eq "T12b single reserve with 5,000 SPENT returns 5001" "$N5K" "5001" + +ACC5K="$SANDBOX/t12-5k.acc"; : > "$ACC5K" +PIDS=() +for _ in 1 2 3 4; do + (cd "$R5K" && exec env SPEC_RESERVE_FILE="$RES5K" "$RUN_BASH" "$SN" reserve) >> "$ACC5K" 2>/dev/null & + PIDS+=("$!") +done +T12_DEADLINE=$(( $(date -u +%s) + 60 )) +while :; do + ALIVE=0 + for p in "${PIDS[@]}"; do + if kill -0 "$p" 2>/dev/null; then ALIVE=1; break; fi + done + [ "$ALIVE" -eq 0 ] && break + if [ "$(date -u +%s)" -ge "$T12_DEADLINE" ]; then + for p in "${PIDS[@]}"; do kill -9 "$p" 2>/dev/null || true; done + break + fi + sleep 0.2 +done +for p in "${PIDS[@]}"; do wait "$p" 2>/dev/null || true; done +T12_TOTAL="$(grep -c . "$ACC5K" 2>/dev/null | tr -d ' ')" +T12_DISTINCT="$(sort -u "$ACC5K" 2>/dev/null | grep -c . | tr -d ' ')" +eq "T12b 4 concurrent workers on 5,000 SPENT all got a number" "${T12_TOTAL:-0}" "4" +eq "T12b 4 concurrent numbers are all distinct" "${T12_DISTINCT:-0}" "4" +eq "T12b lock released after 4 workers" "$(lock_state "$RES5K.lock")" "free" + +# ============================================================ +echo "=== T13: check 50 times against 5,000 numbers (no broken-pipe false free) ===" +# ============================================================ +T13_TAKEN=0 +for _ in $(seq 1 50); do + CHK13="$(sn_run "$R5K" "$RES5K" check 001 2>&1; echo "rc=$?")" + case "$CHK13" in *TAKEN*rc=1*) T13_TAKEN=$((T13_TAKEN + 1)) ;; esac +done +eq "T13 check 001 is TAKEN all 50 times with 5,000 numbers" "$T13_TAKEN" "50" +CHK13_END="$(sn_run "$R5K" "$RES5K" check 5000 2>&1; echo "rc=$?")" +expect "T13 check 5000 is TAKEN" "rc=1" "$CHK13_END" +CHK13_FREE="$(sn_run "$R5K" "$RES5K" check 9999 2>&1; echo "rc=$?")" +expect "T13 check 9999 is free" "rc=0" "$CHK13_FREE" + +# ============================================================ +echo "=== T14: recovery guidance for a burnt spent number ===" +# ============================================================ +R="$(mk_repo 005 t14)"; RES="$SANDBOX/t14.log"; KEY14="$(key "$R")" +sn_run "$R" "$RES" reserve >/dev/null 2>&1 +: > "$R/docs/specs/SPEC-006-burnt.md" +sn_run "$R" "$RES" reserve >/dev/null 2>&1 +rm -f "$R/docs/specs/SPEC-006-burnt.md" +HDR14="$(sed -n '1,25p' "$SN")" +expect "T14 usage header names SPENT reclaim line" "| SPENT |" "$HDR14" +expect "T14 usage header names spec-reservations.log" "spec-reservations.log" "$HDR14" +MSG14="$(sn_run "$R" "$RES" check 006 2>&1 | grep -v '^spec-next: open PR heads not scanned')" +expect "T14 check spent message names the exact SPENT line to delete" "| SPENT | spec=006 repo=${KEY14}" "$MSG14" +expect "T14 check spent message names the ledger file path" "$RES" "$MSG14" +grep -Fv "| SPENT | spec=006 repo=${KEY14}" "$RES" > "$RES.reclaimed" +mv "$RES.reclaimed" "$RES" +CHK14_AFTER="$(sn_run "$R" "$RES" check 006 2>&1; echo "rc=$?")" +expect "T14 deleting the named SPENT line frees 006" "rc=0" "$CHK14_AFTER" +MEGA14="$(sed -n '535,552p' "$KIT_DIR/commands/mega.md")" +expect "T14 commands/mega.md documents permanent SPENT behavior" "SPENT" "$MEGA14" +expect "T14 commands/mega.md documents reclaiming from spec-reservations.log" "spec-reservations.log" "$MEGA14" + +# ============================================================ +echo "=== T15: unterminated last ledger line (read loops and append newline) ===" +# ============================================================ +R="$(mk_repo 005 t15a)"; RES="$SANDBOX/t15a.log"; KEY15A="$(key "$R")" +printf '2026-01-01T00:00:00Z | SPENT | spec=006 repo=%s' "$KEY15A" > "$RES" +CHK15A="$(sn_run "$R" "$RES" check 006 2>&1; echo "rc=$?")" +expect "T15a check sees unterminated trailing SPENT 006" "rc=1" "$CHK15A" +NEXT15A="$(sn_run "$R" "$RES" next 2>/dev/null)" +eq "T15a next sees unterminated trailing SPENT 006" "$NEXT15A" "007" +N15A="$(sn_run "$R" "$RES" reserve 2>/dev/null)" +eq "T15a reserve after unterminated SPENT returns 007" "$N15A" "007" +eq "T15a ledger has 2 separate lines after append" "$(wc -l < "$RES" | tr -d ' ')" "2" +eq "T15a prior SPENT 006 line stays intact on its own line" "$(count "| SPENT | spec=006 repo=${KEY15A}$" "$RES")" "1" +eq "T15a new RESERVE 007 starts on its own line" "$(count "| RESERVE | num=007 repo=${KEY15A}$" "$RES")" "1" +CHK15A2="$(sn_run "$R" "$RES" check 006 2>&1; echo "rc=$?")" +expect "T15a SPENT 006 still TAKEN after reserve" "rc=1" "$CHK15A2" + +R2="$(mk_repo 005 t15b)"; RES2="$SANDBOX/t15b.log"; KEY15B="$(key "$R2")" +NOW_ISO="$(date -u +%Y-%m-%dT%H:%M:%SZ)" +printf '%s | RESERVE | num=006 repo=%s' "$NOW_ISO" "$KEY15B" > "$RES2" +CHK15B="$(sn_run "$R2" "$RES2" check 006 2>&1; echo "rc=$?")" +expect "T15b check sees unterminated trailing live RESERVE 006" "rc=1" "$CHK15B" +NEXT15B="$(sn_run "$R2" "$RES2" next 2>/dev/null)" +eq "T15b next sees unterminated trailing live RESERVE 006" "$NEXT15B" "007" +: > "$R2/docs/specs/SPEC-006-unterm.md" +N15B="$(sn_run "$R2" "$RES2" reserve 2>/dev/null)" +eq "T15b reserve promotes unterminated realized 006 and returns 007" "$N15B" "007" +rm -f "$R2/docs/specs/SPEC-006-unterm.md" +CHK15B2="$(sn_run "$R2" "$RES2" check 006 2>&1; echo "rc=$?")" +expect "T15b promoted 006 from unterminated line stays TAKEN" "rc=1" "$CHK15B2" +eq "T15b ledger has 2 clean lines after promotion and append" "$(wc -l < "$RES2" | tr -d ' ')" "2" + +# ============================================================ +echo "=== T16: T20 worktree reserves under uutils mkdir EEXIST exit 0 (5 rounds) ===" +# ============================================================ +# Matches Ubuntu 26.04 uutils coreutils 0.10.0 (uutils/coreutils#16344): racing non-recursive +# mkdir exits 0 on EEXIST after stat sees ENOENT. With kernel flock (goal-lock.sh), mkdir is +# never used as a lock, so concurrent worktrees serialize cleanly with zero retries or timeouts. +UUTILS_BIN="$SANDBOX/uutils-bin"; mkdir -p "$UUTILS_BIN" +cat > "$UUTILS_BIN/mkdir" </dev/null; then + exit 0 +fi +[ -d "\$p" ] && exit 0 +exit 1 +EOF +chmod +x "$UUTILS_BIN/mkdir" + +R16="$(mk_repo 005 t16)" +for W in wa wb wc wd; do + git -C "$R16" worktree add -q "$R16/.claude/worktrees/$W" -b "$W" >/dev/null 2>&1 +done +T16_OK=0 +for round in 1 2 3 4 5; do + RES16="$SANDBOX/t16-r${round}.log"; ACC16="$SANDBOX/t16-r${round}.acc"; : > "$ACC16" + PIDS=() + for W in wa wb wc wd; do + (cd "$R16/.claude/worktrees/$W" && exec env PATH="$UUTILS_BIN:$PATH" SPEC_RESERVE_MAX_TRIES=20 GOAL_LOCK_TIMEOUT=15 SPEC_RESERVE_FILE="$RES16" "$RUN_BASH" "$SN" reserve) >> "$ACC16" 2>"$SANDBOX/t16-r${round}.${W}.err" & + PIDS+=("$!") + done + T16_DEADLINE=$(( $(date -u +%s) + 45 )) + while :; do + ALIVE=0 + for p in "${PIDS[@]}"; do + if kill -0 "$p" 2>/dev/null; then ALIVE=1; break; fi + done + [ "$ALIVE" -eq 0 ] && break + if [ "$(date -u +%s)" -ge "$T16_DEADLINE" ]; then + for p in "${PIDS[@]}"; do kill -9 "$p" 2>/dev/null || true; done + break + fi + sleep 0.1 + done + for p in "${PIDS[@]}"; do wait "$p" 2>/dev/null || true; done + c16="$(grep -c . "$ACC16" 2>/dev/null | tr -d ' ')" + d16="$(sort -u "$ACC16" 2>/dev/null | grep -c . | tr -d ' ')" + l16="$(lock_state "$RES16.lock")" + retries16=0 + for W in wa wb wc wd; do + rcnt="$(count 'open PR heads not scanned' "$SANDBOX/t16-r${round}.${W}.err")" + [ "${rcnt:-0}" -gt 1 ] && retries16=$((retries16 + 1)) + done + if [ "$c16" = "4" ] && [ "$d16" = "4" ] && [ "$l16" = "free" ] && [ "$retries16" -eq 0 ] && [ -f "$RES16.lock" ] && [ ! -d "$RES16.lock" ]; then + T16_OK=$((T16_OK + 1)) + else + echo -e " ${RED}FAIL${NC} T16 round $round diag: total=$c16 distinct=$d16 retries=$retries16 lock=$l16 wa=$(tr '\n' ' ' < "$SANDBOX/t16-r${round}.wa.err") wb=$(tr '\n' ' ' < "$SANDBOX/t16-r${round}.wb.err")" + fi +done +eq "T16 all 5 four-worktree rounds succeed cleanly under uutils mkdir" "$T16_OK" "5" + +# ============================================================ +echo "=== T17: kernel flock exclusion and immediate SIGKILL release ===" +# ============================================================ +R17="$(mk_repo 005 t17)"; RES17="$SANDBOX/t17.log" +hold_flock "$RES17.lock" "$SANDBOX/t17.ready" +OUT17="$(cd "$R17" && GOAL_LOCK_TIMEOUT=1 SPEC_RESERVE_MAX_TRIES=5 SPEC_RESERVE_FILE="$RES17" "$RUN_BASH" "$SN" reserve 2>&1; echo "rc=$?")" +expect "T17 live kernel flock holder blocks reserve" "rc=1" "$OUT17" +eq "T17 no ledger written while kernel flock held" "$([ -f "$RES17" ] && echo wrote || echo none)" "none" +# SIGKILL the holder: kernel immediately releases flock on the existing lock file. +kill -9 "$HOLD_PID" 2>/dev/null || true +wait "$HOLD_PID" 2>/dev/null || true +T17_START="$(date -u +%s)" +N17="$(cd "$R17" && GOAL_LOCK_TIMEOUT=5 SPEC_RESERVE_MAX_TRIES=5 SPEC_RESERVE_FILE="$RES17" "$RUN_BASH" "$SN" reserve 2>/dev/null)" +T17_ELAPSED=$(( $(date -u +%s) - T17_START )) +eq "T17 reserve succeeds immediately after holder SIGKILL (006)" "$N17" "006" +if [ "$N17" = "006" ] && [ "$T17_ELAPSED" -lt 3 ]; then ok "T17 recovery after SIGKILL was immediate (${T17_ELAPSED}s < 3s)"; else bad "T17 recovery after SIGKILL failed or spun (got='$N17', ${T17_ELAPSED}s)"; fi +eq "T17 lock path is a regular file (never a mkdir dir)" "$([ -f "$RES17.lock" ] && [ ! -d "$RES17.lock" ] && echo file || echo other)" "file" +eq "T17 lock is unheld after reserve completes" "$(lock_state "$RES17.lock")" "free" + +echo "" +echo "=== Results ===" +echo -e "Passed: ${GREEN}$PASS${NC} / $TOTAL" +if [ "$FAIL" -gt 0 ]; then echo -e "${RED}$FAIL assertions failed.${NC}"; exit 1; fi +echo -e "${GREEN}spec-next-spent green.${NC}" diff --git a/tests/test-spec-reserve.sh b/tests/test-spec-reserve.sh index d9ab98529..9b916abe5 100755 --- a/tests/test-spec-reserve.sh +++ b/tests/test-spec-reserve.sh @@ -2,8 +2,8 @@ # test-spec-reserve.sh -- SPEC-128: atomic wavefront SPEC-number reservation. # # Proves the CONCURRENCY case SPEC-064 did not: a parallel wave that each calls `next` before -# any branch/spec exists all get the SAME number. `reserve` claims a number under a portable -# mkdir-mutex + a reservations ledger folded into the scan, so N concurrent claims yield N +# any branch/spec exists all get the SAME number. `reserve` claims a number under a kernel +# flock (lib/goal/goal-lock.sh) + a reservations ledger folded into the scan, so N concurrent claims yield N # DISTINCT numbers. Includes the required negative control (the OLD `next` path DOES collide), # the SPEC-064 contract regression, reconciliation (realized + expired), repo-scope, lock # crash-safety, and the orchestrate.sh reserve-inject wiring. @@ -14,11 +14,22 @@ set -uo pipefail KIT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" SN="$KIT_DIR/lib/spec/spec-next.sh" +LOCK_LIB="$KIT_DIR/lib/goal/goal-lock.sh" +PERL_BIN="$(command -v perl || true)" # Hermetic host state: the operator config and the XDG dirs point at a scratch dir, so a runner's real # ~/.config and ~/.local/state (written by suites running beside this one) never reach the run. PIN_DIR="$(mktemp -d "${TMPDIR:-/tmp}/kit-spec-reserve-pin.XXXXXX")" || exit 1 export KIT_CONFIG_OPERATOR="$PIN_DIR/operator" XDG_CONFIG_HOME="$PIN_DIR/config" XDG_STATE_HOME="$PIN_DIR/state" XDG_CACHE_HOME="$PIN_DIR/cache" -trap 'rm -rf "$PIN_DIR"' EXIT +BG_PIDS=() +_cleanup_pin() { + local p + for p in "${BG_PIDS[@]+"${BG_PIDS[@]}"}"; do + kill -9 "$p" 2>/dev/null || true + wait "$p" 2>/dev/null || true + done + rm -rf "$PIN_DIR" +} +trap _cleanup_pin EXIT # Hermetic by default: no test here needs the real open-PR gh scan, and leaving it on made # T21/T22 reach real `gh` (slow, and a false pass/fail on a machine without `gh` auth). export SPEC_NEXT_NO_PR_SCAN=1 @@ -31,6 +42,31 @@ expect() { if { trap '' PIPE; printf '%s' "$3" 2>/dev/null || :; } | grep -q "$2 # grep -c prints "0" AND exits 1 on no match, so `grep -c || echo 0` double-prints. This # returns a single clean integer whether or not the file exists / the pattern matches. count() { local c; c="$(grep -c "$1" "$2" 2>/dev/null)"; printf '%s' "${c:-0}"; } +lock_state() { + local lf="$1" + [ -d "$lf" ] && { echo "held-dir"; return 0; } + [ -e "$lf" ] || { echo "free"; return 0; } + if ( + # shellcheck source=lib/goal/goal-lock.sh + source "$LOCK_LIB" + GOAL_LOCK_TIMEOUT=0 goal_lock "$lf" 2>/dev/null + ); then echo "free"; else echo "held"; fi +} +hold_flock() { + local lf="$1" ready="$2" + mkdir -p "$(dirname "$lf")" + "$PERL_BIN" -MFcntl=:flock -e ' + open(my $f, ">>", $ARGV[0]) or exit 2; + flock($f, LOCK_EX|LOCK_NB) or exit 3; + open(my $r, ">", $ARGV[1]) or exit 4; + close($r); + sleep 30; + ' "$lf" "$ready" & + HOLD_PID=$! + BG_PIDS+=("$HOLD_PID") + local i=0 + while [ ! -e "$ready" ] && [ "$i" -lt 80 ]; do sleep 0.05; i=$((i + 1)); done +} # A temp git repo whose only spec is SPEC-005 => next free is 006. `cd` into it so spec-next's # `git rev-parse --show-toplevel` resolves here; SPEC_RESERVE_FILE isolates the ledger. @@ -58,7 +94,7 @@ expect "T1 line is repo-scoped + carries num" "num=006 repo=$(key "$R")$" "$(cat echo "=== T2: 20 parallel reserve -> 20 distinct (atomic claim, CORE) ===" # ============================================================ R="$(mk_repo)"; RES="$R/res.log"; ACC="$R/acc"; : > "$ACC" -( cd "$R" +( cd "$R" || exit 1 for _ in $(seq 1 20); do ( SPEC_RESERVE_FILE="$RES" bash "$SN" reserve >> "$ACC" 2>/dev/null ) & done wait ) T2_TOTAL="$(grep -c . "$ACC" | tr -d ' ')" @@ -81,7 +117,7 @@ eq "T3 next advances past the reservation (007)" "$NEXT" "007" echo "=== T4: NEGATIVE CONTROL -- 20 parallel next (old path) DOES collide ===" # ============================================================ R="$(mk_repo)"; RES="$R/res.log"; ACC="$R/acc"; : > "$ACC" # empty ledger: `next` has no reservation -( cd "$R" +( cd "$R" || exit 1 for _ in $(seq 1 20); do ( SPEC_RESERVE_FILE="$RES" bash "$SN" next >> "$ACC" 2>/dev/null ) & done wait ) NC_TOTAL="$(grep -c . "$ACC" | tr -d ' ')" @@ -111,7 +147,7 @@ eq "T5 no ledger file created by next/check (contract untouched)" "$([ -f "$RES" echo "=== T6: reconcile -- a REALIZED reservation (now a branch) stops counting ===" # ============================================================ R="$(mk_repo)"; RES="$R/res.log" -N6="$(cd "$R" && SPEC_RESERVE_FILE="$RES" bash "$SN" reserve)" # 006 reserved +(cd "$R" && SPEC_RESERVE_FILE="$RES" bash "$SN" reserve >/dev/null) # 006 reserved # Realize it: create a branch carrying SPEC-006 (the worker made its branch). git -C "$R" branch "feat/SPEC-006-done" >/dev/null 2>&1 # Next reserve must prune the now-redundant 006 line and still not double-count it. @@ -144,15 +180,14 @@ N8B="$(cd "$RB" && SPEC_RESERVE_FILE="$RES" bash "$SN" next)" # repo B eq "T8 repo B's next ignores repo A's reservations (006)" "$N8B" "006" # ============================================================ -echo "=== T9: stale LOCK dir older than TTL is reclaimed ===" +echo "=== T9: leftover unheld lock file does not block reserve ===" # ============================================================ R="$(mk_repo)"; RES="$R/res.log" -mkdir -p "$(dirname "$RES")"; mkdir "$RES.lock" # simulate a dead holder's leftover lock -# Backdate the lock dir well past the TTL so the reclaim path fires. +mkdir -p "$(dirname "$RES")"; : > "$RES.lock" # leftover lock file with no live holder touch -t 200001010000 "$RES.lock" 2>/dev/null || true N9="$(cd "$R" && SPEC_RESERVE_TTL=1 SPEC_RESERVE_FILE="$RES" bash "$SN" reserve 2>/dev/null)" -eq "T9 reserve reclaims a stale lock and still claims (006)" "$N9" "006" -eq "T9 lock released after reserve" "$([ -d "$RES.lock" ] && echo held || echo free)" "free" +eq "T9 reserve acquires an unheld leftover lock file and claims (006)" "$N9" "006" +eq "T9 lock released after reserve" "$(lock_state "$RES.lock")" "free" # ============================================================ echo "=== T10: orchestrate _wave_reserve_spec wiring (mock spec-next) ===" @@ -222,64 +257,64 @@ echo "=== T14: a normal reserve FREES the lock (no held lock, no owner leak) === R="$(mk_repo)"; RES="$R/res.log" N14="$(cd "$R" && SPEC_RESERVE_FILE="$RES" bash "$SN" reserve)" eq "T14 normal reserve returns a number" "$N14" "006" -eq "T14 lock dir freed after a normal reserve" "$([ -d "$RES.lock" ] && echo held || echo free)" "free" -eq "T14 no owner file left behind" "$([ -e "$RES.lock/owner" ] && echo leak || echo clean)" "clean" +eq "T14 lock released after a normal reserve" "$(lock_state "$RES.lock")" "free" +eq "T14 no mkdir lock dir or owner file left behind" "$([ -d "$RES.lock" ] || [ -e "$RES.lock/owner" ] && echo leak || echo clean)" "clean" # ============================================================ -echo "=== T15: a FRESH (non-stale) foreign lock is RESPECTED, not stolen ===" +echo "=== T15: a held foreign kernel flock is RESPECTED, not stolen ===" # ============================================================ -# This is the direct guard for the mutex fail-open the macOS CI masked: if lock-mtime reads -# garbage (Linux `stat -f %m` = --file-system format), a FRESH lock looks older-than-TTL and -# gets reclaimed -> the number is stolen. With correct mtime the fresh lock is respected, so a -# bounded reserve times out (empty, nonzero) and the foreign lock is still held. R="$(mk_repo)"; RES="$R/res.log" -mkdir -p "$(dirname "$RES")"; mkdir "$RES.lock"; printf 'foreign.owner.token' > "$RES.lock/owner" # current mtime, foreign owner -OUT15="$(cd "$R" && SPEC_RESERVE_MAX_TRIES=3 SPEC_RESERVE_FILE="$RES" bash "$SN" reserve 2>/dev/null; echo "rc=$?")" -if { trap '' PIPE; printf '%s' "$OUT15" 2>/dev/null || :; } | grep -qE '^[0-9]{3}$'; then bad "T15 reserve STOLE a fresh foreign lock (fail-open: $OUT15)"; else ok "T15 reserve did not steal a fresh foreign lock"; fi +hold_flock "$RES.lock" "$R/t15.ready" +OUT15="$(cd "$R" && GOAL_LOCK_TIMEOUT=1 SPEC_RESERVE_FILE="$RES" bash "$SN" reserve 2>/dev/null; echo "rc=$?")" +if { trap '' PIPE; printf '%s' "$OUT15" 2>/dev/null || :; } | grep -qE '^[0-9]{3}$'; then bad "T15 reserve STOLE a held foreign flock (fail-open: $OUT15)"; else ok "T15 reserve did not steal a held foreign flock"; fi expect "T15 bounded reserve fails loudly rather than fail-open" "rc=1" "$OUT15" -eq "T15 the fresh foreign lock is still held" "$([ -d "$RES.lock" ] && echo held || echo free)" "held" -eq "T15 the foreign owner token is untouched" "$(cat "$RES.lock/owner" 2>/dev/null)" "foreign.owner.token" +eq "T15 the foreign flock is still held" "$(lock_state "$RES.lock")" "held" +eq "T15 no ledger written while foreign flock held" "$([ -f "$RES" ] && echo wrote || echo none)" "none" +kill -9 "$HOLD_PID" 2>/dev/null || true; wait "$HOLD_PID" 2>/dev/null || true # ============================================================ -echo "=== T16: a lock held by a DEAD pid is reclaimed at once (no 24h TTL wait) ===" +echo "=== T16: a holder killed with SIGKILL releases the kernel lock at once ===" # ============================================================ R="$(mk_repo)"; RES="$R/res.log" -sleep 0.1 & DEADPID=$!; wait "$DEADPID" 2>/dev/null # a pid that is now certainly gone -mkdir -p "$(dirname "$RES")"; mkdir "$RES.lock" -printf '%s.1.%s' "$DEADPID" "$(date -u +%s)" > "$RES.lock/owner" # fresh mtime, dead owner +hold_flock "$RES.lock" "$R/t16.ready" +kill -9 "$HOLD_PID" 2>/dev/null || true; wait "$HOLD_PID" 2>/dev/null || true T16_START="$(date -u +%s)" N16="$(cd "$R" && SPEC_RESERVE_FILE="$RES" bash "$SN" reserve 2>/dev/null)" T16_ELAPSED=$(( $(date -u +%s) - T16_START )) -eq "T16 reserve reclaims a dead holder's lock and claims (006)" "$N16" "006" -if [ "$T16_ELAPSED" -lt 3 ]; then ok "T16 reclaim was immediate (${T16_ELAPSED}s < 3s)"; else bad "T16 reclaim spun (${T16_ELAPSED}s >= 3s)"; fi +eq "T16 reserve acquires after holder SIGKILL and claims (006)" "$N16" "006" +if [ "$N16" = "006" ] && [ "$T16_ELAPSED" -lt 3 ]; then ok "T16 recovery was immediate (${T16_ELAPSED}s < 3s)"; else bad "T16 recovery spun or failed (${T16_ELAPSED}s)"; fi eq "T16 the ledger gained exactly one RESERVE line" "$(count '| RESERVE |' "$RES")" "1" -eq "T16 lock released after reserve" "$([ -d "$RES.lock" ] && echo held || echo free)" "free" +eq "T16 lock released after reserve" "$(lock_state "$RES.lock")" "free" # ============================================================ -echo "=== T17: a lock held by a LIVE pid is NOT stolen ===" +echo "=== T17: a live goal_lock holder is NOT stolen ===" # ============================================================ R="$(mk_repo)"; RES="$R/res.log" -sleep 30 & LIVEPID=$! -mkdir -p "$(dirname "$RES")"; mkdir "$RES.lock" -STAMP17="$LIVEPID.1.$(date -u +%s)" -printf '%s' "$STAMP17" > "$RES.lock/owner" -OUT17="$(cd "$R" && SPEC_RESERVE_MAX_TRIES=5 SPEC_RESERVE_FILE="$RES" bash "$SN" reserve 2>&1; echo "rc=$?")" -expect "T17 reserve fails loudly rather than stealing a live holder's lock" "could not acquire lock" "$OUT17" +( + # shellcheck source=lib/goal/goal-lock.sh + source "$LOCK_LIB" + goal_lock "$RES.lock" || exit 2 + : > "$R/t17.ready" + sleep 30 +) & +LIVEPID=$!; BG_PIDS+=("$LIVEPID") +_i17=0; while [ ! -e "$R/t17.ready" ] && [ "$_i17" -lt 80 ]; do sleep 0.05; _i17=$((_i17 + 1)); done +OUT17="$(cd "$R" && GOAL_LOCK_TIMEOUT=1 SPEC_RESERVE_FILE="$RES" bash "$SN" reserve 2>&1; echo "rc=$?")" +expect "T17 reserve fails loudly rather than stealing a live holder's lock" "could not lock" "$OUT17" expect "T17 reserve exits nonzero" "rc=1" "$OUT17" -eq "T17 the live holder's lock is still held" "$([ -d "$RES.lock" ] && echo held || echo free)" "held" -eq "T17 the live owner stamp is untouched" "$(cat "$RES.lock/owner" 2>/dev/null)" "$STAMP17" +eq "T17 the live holder's lock is still held" "$(lock_state "$RES.lock")" "held" eq "T17 no ledger written while the lock was held" "$([ -f "$RES" ] && echo wrote || echo none)" "none" -kill "$LIVEPID" 2>/dev/null || true; wait "$LIVEPID" 2>/dev/null || true +kill -9 "$LIVEPID" 2>/dev/null || true; wait "$LIVEPID" 2>/dev/null || true # ============================================================ -echo "=== T18: an UNREADABLE owner + fresh mtime still falls back to the TTL wait ===" +echo "=== T18: a directory at the lock path is refused safely (never deleted) ===" # ============================================================ R="$(mk_repo)"; RES="$R/res.log" -mkdir -p "$(dirname "$RES")"; mkdir "$RES.lock"; : > "$RES.lock/owner" # empty owner, current mtime -OUT18="$(cd "$R" && SPEC_RESERVE_MAX_TRIES=5 SPEC_RESERVE_FILE="$RES" bash "$SN" reserve 2>&1; echo "rc=$?")" -expect "T18 an unparseable owner keeps the TTL path (waits, then fails)" "could not acquire lock" "$OUT18" +mkdir -p "$(dirname "$RES")"; mkdir "$RES.lock"; : > "$RES.lock/owner" +OUT18="$(cd "$R" && GOAL_LOCK_TIMEOUT=1 SPEC_RESERVE_FILE="$RES" bash "$SN" reserve 2>&1; echo "rc=$?")" +expect "T18 directory at lock path is refused with cannot open" "cannot open" "$OUT18" expect "T18 reserve exits nonzero" "rc=1" "$OUT18" -eq "T18 the lock is still held" "$([ -d "$RES.lock" ] && echo held || echo free)" "held" +eq "T18 the directory at lock path is untouched" "$([ -d "$RES.lock" ] && [ -e "$RES.lock/owner" ] && echo held || echo gone)" "held" # ============================================================ echo "=== T19: reserve takes NO arguments (--help must not mint a number) ===" @@ -393,8 +428,7 @@ eq "T25 first reserve on an empty repo prints 001 and exits 0" "$N25A" "$(printf N25B="$(cd "$R" && SPEC_RESERVE_FILE="$RES" bash "$SN" reserve 2>/dev/null; echo "rc=$?")" eq "T25 second reserve sees the first claim and prints 002" "$N25B" "$(printf '002\nrc=0')" eq "T25 next on the empty repo reads the ledger (003)" "$(cd "$R" && SPEC_RESERVE_FILE="$RES" bash "$SN" next 2>/dev/null)" "003" -LOCKED=0; [ -d "$RES.lock" ] && LOCKED=1 -eq "T25 the lock is released after the empty-repo reserve" "$LOCKED" "0" +eq "T25 the lock is released after the empty-repo reserve" "$(lock_state "$RES.lock")" "free" echo "" echo "=== Results ===" From b7ec762ecaa2ebc2ec86af09a55186fef1b28bd3 Mon Sep 17 00:00:00 2001 From: Han Ngo Date: Wed, 2 Dec 2026 16:40:02 +0700 Subject: [PATCH 2/2] fix(spec): migrate stale lock dirs, strip CR, close fd 9 in subshells Reclaim dead-owner or empty mkdir-lock dirs before goal_lock while refusing live holders and non-empty dirs fail-closed; strip trailing CR in SPENT and RESERVE parsing/dedupe; close fd 9 inside command substitutions so SIGKILL releases the flock immediately; default GOAL_LOCK_TIMEOUT to 60 inside reserve; clarify commands/mega.md spent contract. --- commands/mega.md | 7 +- docs/verification/spec-number-stays-spent.md | 159 ++++++++++--------- lib/spec/spec-next.sh | 25 ++- tests/test-spec-next-spent.sh | 87 ++++++++++ tests/test-spec-reserve.sh | 6 +- 5 files changed, 197 insertions(+), 87 deletions(-) diff --git a/commands/mega.md b/commands/mega.md index 39f8e80c7..864ccb6bb 100644 --- a/commands/mega.md +++ b/commands/mega.md @@ -539,9 +539,10 @@ no new binary or `lib/` file. Full depth + a worked dry-run: the skill's 5. **Spec-number block reserve + release.** Reserve via `bash lib/spec/spec-next.sh reserve` (the spec-numbering kernel-flock reservations ledger, the same mechanism the wavefront dispatch already uses at Step 4). This kit has no separate `release` verb: an unrealized reservation - still expires after the TTL, but once a number is realized in a spec file, branch, or commit - it becomes a permanent `SPENT` record and does not come back on its own (to reclaim one burnt - by mistake, delete its `| SPENT | spec= repo=` line from `spec-reservations.log`). + still expires after the TTL, and a number becomes a permanent `SPENT` record once it is + realized in a spec file, branch, or commit and seen by a later `reserve`, after which it does + not come back on its own (to reclaim one burnt by mistake, delete its + `| SPENT | spec= repo=` line from `spec-reservations.log`). 6. **Provenance per sub-goal.** Every consolidated sub-goal records `from: /SG- + /SG-` on its roadmap line and in its goal file. Done imports keep their own single origin + PR. diff --git a/docs/verification/spec-number-stays-spent.md b/docs/verification/spec-number-stays-spent.md index 3769ad0ab..fb490d94a 100644 --- a/docs/verification/spec-number-stays-spent.md +++ b/docs/verification/spec-number-stays-spent.md @@ -1,26 +1,28 @@ # Verification: spec-number-stays-spent -Headless shell library fix (`l312-spec`, off `origin/master` `e75b5b2d`): no UI surface. +Headless shell library fix (`l312-spec`, off `origin/master` `74475fb1`): no UI surface. -Fixes two defects in `lib/spec/spec-next.sh`: +Fixes two core defects and four review findings (B1, R1, R2, R5, plus spent contract 2b option a) in `lib/spec/spec-next.sh`: 1. **Realized spec numbers stay spent permanently**: `_prune_reservations` previously dropped a `RESERVE` line once its number appeared in `docs/specs/`, branches, or recent commits; deleting the spec file or branch later let `next` and `check` treat the number as free again. A realized reservation for the calling repo is now promoted once in place to ` | SPENT | spec= repo=` in the same reservations ledger, counted by `_spent` / `_numbers` / `check` with no TTL and anchored `repo=` scoping. -2. **Kernel flock replaces mkdir-as-lock (Ubuntu 26.04 uutils fix)**: `reserve` previously serialized via a home-made `mkdir "$RES_LOCK"` + owner-file mutex, which deadlocked `tests/test-spec-reserve.sh` T20 on Ubuntu 26.04 (`uutils coreutils 0.10.0`, `uutils/coreutils#16344`: racing non-recursive `mkdir` exits 0 on `EEXIST`, allowing concurrent entry and self-deadlock on the owner PID). `reserve` now serializes via `lib/goal/goal-lock.sh` (`flock(2)` on fd 9, with `9>&-` closed in subshells), eliminating `mkdir`-as-lock, owner files, and PID/TTL reclaim races. +2. **Kernel flock replaces mkdir-as-lock (Ubuntu 26.04 uutils fix)**: `reserve` previously serialized via a home-made `mkdir "$RES_LOCK"` + owner-file mutex, which deadlocked `tests/test-spec-reserve.sh` T20 on Ubuntu 26.04 (`uutils coreutils 0.10.0`, `uutils/coreutils#16344`: racing non-recursive `mkdir` exits 0 on `EEXIST`, allowing concurrent entry and self-deadlock on the owner PID). `reserve` now serializes via `lib/goal/goal-lock.sh` (`flock(2)` on fd 9), eliminating `mkdir`-as-lock, owner files, and PID/TTL reclaim races. +3. **B1 (stale old-code mkdir-lock dir migration)**: before calling `goal_lock "$RES_LOCK"`, if `$RES_LOCK` is a directory, `reserve` checks `$RES_LOCK/owner` (stripping CR and suffix after `.`) and reclaims it via `rm -f "$RES_LOCK/owner" && rmdir "$RES_LOCK"` when the owner PID is missing/dead, while leaving live old-code holders and non-empty unexpected directories untouched so `goal_lock` refuses fail-closed. +4. **R1 (CRLF resilience)**: `sub(/\r$/,"")` runs first in `_spent` and the prune dedupe `awk`, and `line="${line%$'\r'}"` runs after each `read -r line` in `_reservations` and `_prune_reservations`, so hand-edited CRLF lines never fail open as free or duplicate on promotion. +5. **R2 (no orphaned fd 10 hold on SIGKILL)**: `n="$(exec 9>&-; next)"`, `realized="$(exec 9>&-; _scan_numbers)"`, and `exec 9>&-` inside `tail`/`date` command substitutions close fd 9 inside the subshell instead of redirecting the function call (which made bash save fd 9 to fd 10 and leak the lock to orphaned children). +6. **R5 and 2b option (a)**: `GOAL_LOCK_TIMEOUT="${GOAL_LOCK_TIMEOUT:-60}"` inside `reserve` (matching or exceeding the old mutex patience under contention), and `commands/mega.md` states accurately that a number becomes permanently `SPENT` once realized and seen by a later `reserve` while unrealized reservations keep TTL expiry. ## Readers audited All readers of `spec-reservations.log` / `SPEC_RESERVE_FILE` in `lib/`, `bin/`, `hooks/`, and `tests/` were searched (`rg -n "spec-reservations|SPEC_RESERVE|RESERVE" lib/ bin/ hooks/ tests/`): -- `lib/spec/spec-next.sh`: filters `RESERVE` lines by `*"| RESERVE |"*` and reads `SPENT` lines via anchored `_spent`. -- `tests/test-spec-reserve.sh`: T6 checks `count 'num=006'` (0, unaffected by `spec=006`); T11 checks expired foreign pruning for nonexistent `repo=some-other-repo` (passes because `[ ! -d "$r" ]`); T9/T14/T15/T16/T17/T18/T25 updated to verify kernel `flock(2)` semantics via `lib/goal/goal-lock.sh`. +- `lib/spec/spec-next.sh`: filters `RESERVE` lines by `*"| RESERVE |"*` and reads `SPENT` lines via anchored `_spent`, stripping trailing CR in both paths. +- `tests/test-spec-reserve.sh`: T6 checks `count 'num=006'` (0, unaffected by `spec=006`); T11 checks expired foreign pruning for nonexistent `repo=some-other-repo` (passes because `[ ! -d "$r" ]`); T9/T14/T15/T16/T17/T18/T25 verify kernel `flock(2)` semantics via `lib/goal/goal-lock.sh` (T18 verifies non-empty unexpected directory at `$RES.lock` is refused safely). - `tests/test-spec-find.sh` and `tests/test-spec-next-pr-scan.sh`: call `spec-next.sh` CLI only; no direct ledger parsing. -- `commands/mega.md`: updated lines 539-544 to document kernel flock, permanent `SPENT` records, and line deletion for reclaiming a burnt number. +- `commands/mega.md`: updated lines 539-545 to document kernel flock, permanent `SPENT` records once realized and seen by a later `reserve`, TTL release for unrealized claims, and line deletion for reclaiming a burnt number. -## Root cause and RED baseline on `origin/master` (`e75b5b2d`) +## Root cause and RED baselines -### 1. Reproducing the Ubuntu 26.04 T20 failure locally (uutils `mkdir` TOCTOU) - -Using a `mkdir` wrapper matching `uutils/coreutils#16344` (non-recursive `mkdir` returns 0 on racing `EEXIST` after initial `stat` sees `ENOENT`), two worktrees reserving concurrently on `origin/master` reproduced the exact Ubuntu CI failure (`round 1: total=1 distinct=1`, one worktree retrying `next()` twice and the other failing with `could not acquire lock`): +### 1. Reproducing the Ubuntu 26.04 T20 failure locally (uutils `mkdir` TOCTOU on `origin/master`) ```text Command: bash -c '' @@ -31,7 +33,7 @@ round 1: total=1 distinct=1 lock=free wb err: spec-next: open PR heads not scanned (SPEC_NEXT_NO_PR_SCAN=1) spec-next reserve: could not acquire lock after 20 tries (/repo/res-1.log.lock) ``` -### 2. Full new suite RED baseline on `origin/master` (`e75b5b2d`) +### 2. Initial RED baseline on `origin/master` (`e75b5b2d`) ```text Command: bash tests/test-spec-next-spent.sh @@ -40,7 +42,6 @@ Output: === T1: realized file deleted -- number stays spent === FAIL T1 check 006 stays TAKEN after file deletion (missing 'TAKEN' in: ... SPEC-006 is free rc=0) FAIL T1 next does not reissue deleted 006 after 007 expires (want '007' got '006') -=== T16: T20 worktree reserves under uutils mkdir EEXIST exit 0 (5 rounds) === === T17: kernel flock exclusion and immediate SIGKILL release === FAIL T17 reserve succeeds immediately after holder SIGKILL (006) (want '006' got '') === Results === @@ -48,85 +49,92 @@ Passed: 49 / 100 51 assertions failed. ``` -## Green runs - -### 1. Shellcheck and bash 5.3.20 - -```text -Command: shellcheck -S warning lib/spec/spec-next.sh tests/test-spec-reserve.sh tests/test-spec-next-spent.sh && bash tests/test-spec-next-spent.sh && bash tests/test-spec-reserve.sh && bash tests/test-spec-next-pr-scan.sh -Exit: 0 -Output: -SHELLCHECK OK -Passed: 100 / 100 -spec-next-spent green. -Passed: 70 / 70 -spec-reserve green. -Passed: 8 / 8 -spec-next-pr-scan green. -``` - -### 2. macOS `/bin/bash` 3.2.57 +### 3. Fix-round RED-first baseline on `86c181b0` (before B1, R1, R2, and `mega.md` wording) ```text -Command: timeout -k 5 180 /bin/bash -c '/bin/bash tests/test-spec-next-spent.sh | tail -n 5; /bin/bash tests/test-spec-reserve.sh | tail -n 5; /bin/bash tests/test-spec-next-pr-scan.sh | tail -n 5' -Exit: 0 +Command: timeout -k 5 90 bash tests/test-spec-next-spent.sh | tail -n 65 +Exit: 0 (suite exit 1 before pipe) Output: - PASS T17 lock is unheld after reserve completes -Passed: 100 / 100 -spec-next-spent green. -Passed: 70 / 70 -spec-reserve green. -Passed: 8 / 8 -spec-next-pr-scan green. + FAIL T14 commands/mega.md states SPENT happens when seen by a later reserve + FAIL T18a stale mkdir lock dir with dead owner is reclaimed (006) (want '006' got '') + FAIL T18a lock path migrated to regular file (want 'file' got 'other') + FAIL T18b empty stale mkdir lock dir is reclaimed (006) (want '006' got '') + FAIL T19 CRLF SPENT 010 reads as TAKEN (SPEC-010 is free rc=0) + FAIL T19 CRLF live RESERVE 011 reads as TAKEN (SPEC-011 is free rc=0) + FAIL T19 next advances past CRLF SPENT 010 and RESERVE 011 (012) (want '012' got '006') + FAIL T19 reserve after CRLF ledger returns 012 (want '012' got '011') + FAIL T20 next reserve succeeds after SIGKILL mid-scan (006) (want '006' got '') + FAIL T20 orphaned child held lock after SIGKILL (got='', 2s) +Passed: 104 / 114 +10 assertions failed. ``` -### 3. GNU tools first on `PATH` (coreutils, gawk, gnu-sed) on both bash 5.3 and bash 3.2 +## Green runs -```text -Command: PATH=":$PATH" timeout -k 5 180 bash -c 'bash tests/test-spec-next-spent.sh | tail -n 5; bash tests/test-spec-reserve.sh | tail -n 5; bash tests/test-spec-next-pr-scan.sh | tail -n 5' -Exit: 0 -Output: -Passed: 100 / 100 -spec-next-spent green. -Passed: 70 / 70 -spec-reserve green. -Passed: 8 / 8 -spec-next-pr-scan green. -``` +### 1. Shellcheck and 5-configuration verification matrix (bash 5.3, `/bin/bash` 3.2, GNU tools first on `PATH`, Linux `flock(1)` shim) ```text -Command: PATH=":$PATH" timeout -k 5 180 /bin/bash -c '/bin/bash tests/test-spec-next-spent.sh | tail -n 5; /bin/bash tests/test-spec-reserve.sh | tail -n 5; /bin/bash tests/test-spec-next-pr-scan.sh | tail -n 5' +Command: shellcheck -S warning lib/spec/spec-next.sh tests/test-spec-reserve.sh tests/test-spec-next-spent.sh && <5-config matrix of test-spec-next-spent.sh, test-spec-reserve.sh, test-spec-next-pr-scan.sh> Exit: 0 Output: -Passed: 100 / 100 -spec-next-spent green. -Passed: 70 / 70 -spec-reserve green. -Passed: 8 / 8 -spec-next-pr-scan green. +SHELLCHECK OK +=== bash 5 (default PATH) === +Passed: 114 / 114 (spec-next-spent green.) | Passed: 70 / 70 (spec-reserve green.) | Passed: 8 / 8 (spec-next-pr-scan green.) +=== /bin/bash 3.2 (default PATH) === +Passed: 114 / 114 (spec-next-spent green.) | Passed: 70 / 70 (spec-reserve green.) | Passed: 8 / 8 (spec-next-pr-scan green.) +=== bash 5 (GNU tools first) === +Passed: 114 / 114 (spec-next-spent green.) | Passed: 70 / 70 (spec-reserve green.) | Passed: 8 / 8 (spec-next-pr-scan green.) +=== /bin/bash 3.2 (GNU tools first) === +Passed: 114 / 114 (spec-next-spent green.) | Passed: 70 / 70 (spec-reserve green.) | Passed: 8 / 8 (spec-next-pr-scan green.) +=== bash 5 (GNU + Linux flock shim) === +Passed: 114 / 114 (spec-next-spent green.) | Passed: 70 / 70 (spec-reserve green.) | Passed: 8 / 8 (spec-next-pr-scan green.) ``` -### 4. Simulated Linux `flock(1)` shim + GNU tools first on `PATH`, plus related contract suites +### 2. Changed-scope suites (`bin/test-affected --base origin/master`) ```text -Command: PATH="::$PATH" timeout -k 5 180 bash -c 'bash tests/test-spec-reserve.sh 2>/dev/null | tail -n 3; bash tests/test-spec-next-spent.sh 2>/dev/null | tail -n 3' && bash tests/test-kri-wiring.sh 2>/dev/null | tail -n 3 && bash tests/test-mega-reconcile.sh 2>/dev/null | tail -n 3 && bash tests/test-advisor.sh 2>/dev/null | tail -n 3 -Exit: 0 +Command: bash bin/test-affected --base origin/master +Exit: 0 (29 pass, 0 fail, 1 timeout under load 77.9) Output: -Passed: 70 / 70 -spec-reserve green. -Passed: 100 / 100 -spec-next-spent green. -=== 31/31 passed === -=== 35/35 passed, 0 failed === -=== 42/42 passed, 0 failed === +PASS tests/test-advisor.sh +PASS tests/test-docs-wiring.sh +PASS tests/test-hooks.sh +PASS tests/test-kri-wiring.sh +PASS tests/test-mega-gate-head.sh +PASS tests/test-mega-reconcile.sh +PASS tests/test-meta-agents-commands.sh +PASS tests/test-meta-docs-registry.sh +PASS tests/test-meta-goal-ledger.sh +PASS tests/test-meta-plugin-hooks.sh +PASS tests/test-meta-review-verifiers.sh +PASS tests/test-meta-vmodel-dispatch.sh +PASS tests/test-precedent.sh +PASS tests/test-registry-freshness-guard.sh +PASS tests/test-registry-verbs.sh +PASS tests/test-shared-lookups.sh +PASS tests/test-spec-active.sh +PASS tests/test-spec-depth.sh +PASS tests/test-spec-drift-guard.sh +PASS tests/test-spec-find.sh +PASS tests/test-spec-index.sh +PASS tests/test-spec-next-pr-scan.sh +PASS tests/test-spec-next-spent.sh +PASS tests/test-spec-reserve.sh +PASS tests/test-spec-states.sh +PASS tests/test-spec-task-done.sh +PASS tests/test-test-affected.sh +TIMEOUT tests/test-wrap-land.sh (limit 600s; CI-only suite blocked standalone by branch-guard) +PASS tests/test-wrap-merge.sh +PASS tests/test-wrap-rebase.sh +test-affected: 30 selected, 29 pass, 0 cached, 0 fail, 1 timeout, 1 uncovered ``` ## Negative control and planted faults (isolated scratch copy) -All negative control probes ran in a temporary scratch copy without mutating the workspace, each capped by `timeout -k 5 90`: +All negative control probes ran in temporary scratch copies without mutating the workspace, each capped by `timeout -k 5`: ```text -Command: bash -c '<9 planted-fault negative control probes in isolated scratch copy>' +Command: bash -c '<12 planted-fault negative control probes in isolated scratch copies>' Exit: 1 Output: Mutant [M0-origin-master] (test-spec-next-spent.sh): Exit=124 (baseline direct run: Exit=1, Passed: 49 / 100, 51 assertions failed) @@ -138,15 +146,20 @@ Mutant [M5-unanchored-promo-dedupe] (test-spec-next-spent.sh): Exit=1 | Passed: Mutant [M6-no-x-number-anchor] (test-spec-next-spent.sh): Exit=1 | Passed: 98 / 100 2 assertions failed. Mutant [M7-no-unterminated-read] (test-spec-next-spent.sh): Exit=1 | Passed: 98 / 100 2 assertions failed. Mutant [M8-piped-check] (test-spec-next-spent.sh): Exit=1 | Passed: 99 / 100 1 assertions failed. +Mutant [M9-no-b1-dir-reclaim] (test-spec-next-spent.sh): Exit=1 | Passed: 111 / 114 3 assertions failed. +Mutant [M10-no-r1-cr-strip] (test-spec-next-spent.sh): Exit=1 | Passed: 109 / 114 5 assertions failed. +Mutant [M11-no-r2-exec-close] (test-spec-next-spent.sh): Exit=1 | Passed: 112 / 114 2 assertions failed. Verdict: RED ``` ## Rollback -Revert the commit(s) on this branch (`git revert `). Existing `| SPENT |` lines in `spec-reservations.log` are harmlessly ignored by older `spec-next.sh` (which only parses `| RESERVE |` lines); any regular lock file at `spec-reservations.log.lock` can be removed (`rm -f /spec-reservations.log.lock`) if rolling back to the old `mkdir`-lock implementation. To reclaim an individual burnt number without rolling back, delete its exact `| SPENT | spec= repo=` line from `spec-reservations.log`. +Revert the commits on this branch (`git revert `). Existing `| SPENT |` lines in `spec-reservations.log` are harmlessly ignored by older `spec-next.sh` (which only parses `| RESERVE |` lines); any regular lock file at `spec-reservations.log.lock` can be removed (`rm -f /spec-reservations.log.lock`) if rolling back to the old `mkdir`-lock implementation. To reclaim an individual burnt number without rolling back, delete its exact `| SPENT | spec= repo=` line from `spec-reservations.log`. ## Not proven -- Native Ubuntu 26.04 kernel/uutils runner execution (reproduced locally via the `uutils/coreutils#16344` `mkdir` stub, GNU coreutils/gawk/gnu-sed first on `PATH`, and a `flock(1)` shim; full Ubuntu matrix runs in CI). +- Native Ubuntu 26.04 kernel/uutils runner execution and real util-linux `flock(1)` (reproduced locally via the `uutils/coreutils#16344` `mkdir` stub, GNU coreutils/gawk/gnu-sed first on `PATH`, and a `flock(1)` shim; full Ubuntu matrix runs in CI). +- `tests/test-wrap-land.sh` standalone rerun (timed out at 600s during `bin/test-affected` under load 77.9 and is blocked standalone locally by `branch-guard`; runs on CI). - Live GitHub open-PR scanning (`SPEC_NEXT_NO_PR_SCAN=0`). -- Spec numbers created without `reserve` (never present in the ledger) or deleted before any later `reserve` observes realization are not recorded as `SPENT`. +- Pre-existing `ledger.location = "isolated"` per-worktree ledger split (R4, explicitly out of scope). +- Spec numbers created without `reserve` or deleted before any later `reserve` observes realization are not recorded as `SPENT` (documented per lead decision 2b option a). diff --git a/lib/spec/spec-next.sh b/lib/spec/spec-next.sh index 6792de64b..a9ba719d0 100755 --- a/lib/spec/spec-next.sh +++ b/lib/spec/spec-next.sh @@ -155,6 +155,7 @@ _reservations() { [ -f "$RES_FILE" ] || return 0 local cutoff; cutoff=$(( $(now_epoch) - SPEC_RESERVE_TTL )) while IFS= read -r line || [ -n "$line" ]; do + line="${line%$'\r'}" case "$line" in *"| RESERVE |"*) ;; *) continue;; esac # Anchored to end-of-line (review LOW #4): `repo=` is always the trailing field, so this # exact-suffix match stops repo `foo` from also matching a line for `foo-bar`. @@ -175,7 +176,7 @@ _reservations() { _spent() { [ -f "$RES_FILE" ] || return 0 REPO="$REPO" awk 'BEGIN{s=" repo="ENVIRON["REPO"];sl=length(s)} - {p=index($0,"| SPENT | spec="); if(!p||length($0)=l&&substr($0,length($0)-l+1)==s{f=1;exit} END{exit !f}' "$RES_FILE"; then + if S="| SPENT | $key" awk 'BEGIN{s=ENVIRON["S"];l=length(s)} {sub(/\r$/,"")} length($0)>=l&&substr($0,length($0)-l+1)==s{f=1;exit} END{exit !f}' "$RES_FILE"; then keep=0 else case "$promoted" in @@ -253,16 +255,23 @@ _prune_reservations() { reserve() { command -v goal_lock >/dev/null 2>&1 || { echo "REFUSED: spec-next reserve: goal-lock.sh missing" >&2; return 1; } mkdir -p "$(dirname "$RES_FILE")" 2>/dev/null || true - goal_lock "$RES_LOCK" || return 1 + if [ -d "$RES_LOCK" ]; then + local _op; _op="$(cat "$RES_LOCK/owner" 2>/dev/null || true)"; _op="${_op%$'\r'}"; _op="${_op%%.*}" + case "$_op" in + ''|*[!0-9]*) rm -f "$RES_LOCK/owner" 2>/dev/null || true; rmdir "$RES_LOCK" 2>/dev/null || true ;; + *) kill -0 "$_op" 2>/dev/null || { rm -f "$RES_LOCK/owner" 2>/dev/null || true; rmdir "$RES_LOCK" 2>/dev/null || true; } ;; + esac + fi + GOAL_LOCK_TIMEOUT="${GOAL_LOCK_TIMEOUT:-60}" goal_lock "$RES_LOCK" || return 1 trap 'exec 9>&- 2>/dev/null || true' EXIT trap 'exec 9>&- 2>/dev/null || true; exit 130' INT trap 'exec 9>&- 2>/dev/null || true; exit 143' TERM local n - n="$(next 9>&-)" - if [ -s "$RES_FILE" ] && [ -n "$(tail -c 1 "$RES_FILE")" ]; then printf '\n' >> "$RES_FILE"; fi + n="$(exec 9>&-; next)" + if [ -s "$RES_FILE" ] && [ -n "$(exec 9>&-; tail -c 1 "$RES_FILE")" ]; then printf '\n' >> "$RES_FILE"; fi printf '%s | RESERVE | num=%s repo=%s\n' \ - "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$n" "$REPO" >> "$RES_FILE" - _prune_reservations 9>&- + "$(exec 9>&-; date -u +%Y-%m-%dT%H:%M:%SZ)" "$n" "$REPO" >> "$RES_FILE" + _prune_reservations exec 9>&- 2>/dev/null || true trap - EXIT INT TERM printf '%s\n' "$n" diff --git a/tests/test-spec-next-spent.sh b/tests/test-spec-next-spent.sh index c14e8ed52..78b3ca7af 100755 --- a/tests/test-spec-next-spent.sh +++ b/tests/test-spec-next-spent.sh @@ -502,6 +502,7 @@ CHK14_AFTER="$(sn_run "$R" "$RES" check 006 2>&1; echo "rc=$?")" expect "T14 deleting the named SPENT line frees 006" "rc=0" "$CHK14_AFTER" MEGA14="$(sed -n '535,552p' "$KIT_DIR/commands/mega.md")" expect "T14 commands/mega.md documents permanent SPENT behavior" "SPENT" "$MEGA14" +expect "T14 commands/mega.md states SPENT happens when seen by a later reserve" "seen by a later" "$MEGA14" expect "T14 commands/mega.md documents reclaiming from spec-reservations.log" "spec-reservations.log" "$MEGA14" # ============================================================ @@ -622,6 +623,92 @@ if [ "$N17" = "006" ] && [ "$T17_ELAPSED" -lt 3 ]; then ok "T17 recovery after S eq "T17 lock path is a regular file (never a mkdir dir)" "$([ -f "$RES17.lock" ] && [ ! -d "$RES17.lock" ] && echo file || echo other)" "file" eq "T17 lock is unheld after reserve completes" "$(lock_state "$RES17.lock")" "free" +# ============================================================ +echo "=== T18: stale old-code mkdir-lock dir migration (B1) ===" +# ============================================================ +R18="$(mk_repo 005 t18)" +# Dead owner pid inside mkdir lock dir -> reclaimed and reserve succeeds. +RES18A="$SANDBOX/t18a.log" +sleep 0.05 & DEAD18=$!; wait "$DEAD18" 2>/dev/null || true +mkdir -p "$RES18A.lock" +printf '%s.1.1700000000' "$DEAD18" > "$RES18A.lock/owner" +N18A="$(sn_run "$R18" "$RES18A" reserve 2>/dev/null)" +eq "T18a stale mkdir lock dir with dead owner is reclaimed (006)" "$N18A" "006" +eq "T18a lock path migrated to regular file" "$([ -f "$RES18A.lock" ] && [ ! -d "$RES18A.lock" ] && echo file || echo other)" "file" +# Empty mkdir lock dir (killed between mkdir and owner write) -> reclaimed and reserve succeeds. +RES18B="$SANDBOX/t18b.log" +mkdir -p "$RES18B.lock" +N18B="$(sn_run "$R18" "$RES18B" reserve 2>/dev/null)" +eq "T18b empty stale mkdir lock dir is reclaimed (006)" "$N18B" "006" +# Live owner pid inside mkdir lock dir -> refused fail-closed, directory untouched. +RES18C="$SANDBOX/t18c.log" +mkdir -p "$RES18C.lock" +printf '%s.1.1700000000' "$$" > "$RES18C.lock/owner" +OUT18C="$(cd "$R18" && GOAL_LOCK_TIMEOUT=1 SPEC_RESERVE_FILE="$RES18C" "$RUN_BASH" "$SN" reserve 2>&1; echo "rc=$?")" +expect "T18c mkdir lock dir with live owner refuses cleanly" "rc=1" "$OUT18C" +eq "T18c live-owner mkdir lock dir is untouched" "$([ -d "$RES18C.lock" ] && [ -f "$RES18C.lock/owner" ] && echo held || echo gone)" "held" +eq "T18c no ledger written when live old-code lock dir is present" "$([ -f "$RES18C" ] && echo wrote || echo none)" "none" + +# ============================================================ +echo "=== T19: CRLF SPENT and RESERVE lines still count (R1) ===" +# ============================================================ +R19="$(mk_repo 005 t19)"; RES19="$SANDBOX/t19.log"; KEY19="$(key "$R19")" +NOW19="$(date -u +%Y-%m-%dT%H:%M:%SZ)" +{ + printf '2026-01-01T00:00:00Z | SPENT | spec=010 repo=%s\r\n' "$KEY19" + printf '%s | RESERVE | num=011 repo=%s\r\n' "$NOW19" "$KEY19" +} > "$RES19" +CHK19A="$(sn_run "$R19" "$RES19" check 010 2>&1; echo "rc=$?")" +expect "T19 CRLF SPENT 010 reads as TAKEN" "rc=1" "$CHK19A" +CHK19B="$(sn_run "$R19" "$RES19" check 011 2>&1; echo "rc=$?")" +expect "T19 CRLF live RESERVE 011 reads as TAKEN" "rc=1" "$CHK19B" +NEXT19="$(sn_run "$R19" "$RES19" next 2>/dev/null)" +eq "T19 next advances past CRLF SPENT 010 and RESERVE 011 (012)" "$NEXT19" "012" +# Realizing 010 with an LF RESERVE while SPENT 010 has CRLF must not duplicate SPENT 010. +: > "$R19/docs/specs/SPEC-010-dup.md" +printf '%s | RESERVE | num=010 repo=%s\n' "$NOW19" "$KEY19" >> "$RES19" +N19="$(sn_run "$R19" "$RES19" reserve 2>/dev/null)" +eq "T19 reserve after CRLF ledger returns 012" "$N19" "012" +eq "T19 CRLF SPENT 010 is not duplicated on promotion" "$(count "| SPENT | spec=010 repo=${KEY19}" "$RES19")" "1" + +# ============================================================ +echo "=== T20: SIGKILLed reserve mid-scan frees lock at once (R2) ===" +# ============================================================ +R20="$(mk_repo 005 t20)"; RES20="$SANDBOX/t20.log"; READY20="$SANDBOX/t20.ready"; SLEEPER20="$SANDBOX/t20.sleeper" +SLOW_BIN20="$SANDBOX/t20-bin"; mkdir -p "$SLOW_BIN20" +cat > "$SLOW_BIN20/gh" < "$SLEEPER20" + : > "$READY20" + sleep 8 + ;; + *) exit 1 ;; +esac +EOF +chmod +x "$SLOW_BIN20/gh" +(cd "$R20" && exec env PATH="$SLOW_BIN20:$PATH" SPEC_NEXT_NO_PR_SCAN=0 SPEC_RESERVE_FILE="$RES20" "$RUN_BASH" "$SN" reserve) >"$SANDBOX/t20.out" 2>"$SANDBOX/t20.err" & +RPID20=$!; BG_PIDS+=("$RPID20") +_i20=0; while [ ! -e "$READY20" ] && [ "$_i20" -lt 100 ]; do sleep 0.05; _i20=$((_i20 + 1)); done +if [ -f "$SLEEPER20" ]; then BG_PIDS+=("$(cat "$SLEEPER20")"); fi +kill -9 "$RPID20" 2>/dev/null || true +wait "$RPID20" 2>/dev/null || true +T20_START="$(date -u +%s)" +N20="$(cd "$R20" && GOAL_LOCK_TIMEOUT=2 SPEC_NEXT_NO_PR_SCAN=1 SPEC_RESERVE_FILE="$RES20" "$RUN_BASH" "$SN" reserve 2>/dev/null)" +T20_ELAPSED=$(( $(date -u +%s) - T20_START )) +eq "T20 next reserve succeeds after SIGKILL mid-scan (006)" "$N20" "006" +if [ "$N20" = "006" ] && [ "$T20_ELAPSED" -lt 2 ]; then + ok "T20 lock freed immediately on SIGKILL despite live orphaned child (${T20_ELAPSED}s < 2s)" +else + bad "T20 orphaned child held lock after SIGKILL (got='$N20', ${T20_ELAPSED}s)" +fi +if [ -f "$SLEEPER20" ]; then kill -9 "$(cat "$SLEEPER20")" 2>/dev/null || true; fi + echo "" echo "=== Results ===" echo -e "Passed: ${GREEN}$PASS${NC} / $TOTAL" diff --git a/tests/test-spec-reserve.sh b/tests/test-spec-reserve.sh index 9b916abe5..996106fe1 100755 --- a/tests/test-spec-reserve.sh +++ b/tests/test-spec-reserve.sh @@ -307,14 +307,14 @@ eq "T17 no ledger written while the lock was held" "$([ -f "$RES" ] && echo wrot kill -9 "$LIVEPID" 2>/dev/null || true; wait "$LIVEPID" 2>/dev/null || true # ============================================================ -echo "=== T18: a directory at the lock path is refused safely (never deleted) ===" +echo "=== T18: a non-empty directory at the lock path is refused safely (never deleted) ===" # ============================================================ R="$(mk_repo)"; RES="$R/res.log" -mkdir -p "$(dirname "$RES")"; mkdir "$RES.lock"; : > "$RES.lock/owner" +mkdir -p "$(dirname "$RES")"; mkdir "$RES.lock"; : > "$RES.lock/keep" OUT18="$(cd "$R" && GOAL_LOCK_TIMEOUT=1 SPEC_RESERVE_FILE="$RES" bash "$SN" reserve 2>&1; echo "rc=$?")" expect "T18 directory at lock path is refused with cannot open" "cannot open" "$OUT18" expect "T18 reserve exits nonzero" "rc=1" "$OUT18" -eq "T18 the directory at lock path is untouched" "$([ -d "$RES.lock" ] && [ -e "$RES.lock/owner" ] && echo held || echo gone)" "held" +eq "T18 the directory at lock path is untouched" "$([ -d "$RES.lock" ] && [ -e "$RES.lock/keep" ] && echo held || echo gone)" "held" # ============================================================ echo "=== T19: reserve takes NO arguments (--help must not mint a number) ==="