From 041735552af729db356ff7a68078c6c6aeb22e3c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Mon, 16 Nov 2026 07:21:25 +0000 Subject: [PATCH 1/9] task: add staging-lease-fair-queue Co-Authored-By: Claude Opus 5.5 --- .../2026-11-16-staging-lease-fair-queue.md | 93 +++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100644 tasks/active/2026-11-16-staging-lease-fair-queue.md diff --git a/tasks/active/2026-11-16-staging-lease-fair-queue.md b/tasks/active/2026-11-16-staging-lease-fair-queue.md new file mode 100644 index 0000000000..01f428b7df --- /dev/null +++ b/tasks/active/2026-11-16-staging-lease-fair-queue.md @@ -0,0 +1,93 @@ +# Staging lease: fair queue, and keep migration branches off primary staging + +SAM task `01M7HK7TY9GA8DTV3BGS4QYNM8`, idea `01M7FYGMEESYH3AJZJ0CT3NKCZ`. Fixes defects in the lease +approved on 2026-11-15 (PR #2762, extended by #2766). + +## Problem + +First night of use (idea notes, 2026-11-16): + +1. No queue: at release or expiry the slot goes to whoever dispatches first (task + 01M7G55K6BSR1RPMZK14CAD8KE lost three hand-offs; 01M7GY0BKP1WESE5Y82PZNN42S released early as a + favour and then lost every hand-off for hours). +2. Silent loss of place: the workflow-level concurrency group keeps one pending run, so a dispatch + made while a deploy runs can be cancelled by a later dispatch (run 43794216077). +3. A holder can release and immediately re-acquire while others wait. +4. Draft PR #2721 deployed DO migration tag v23 on primary staging (main at v22); the migration + preflight then fails closed for every main-based branch. + +## Research findings + +- `scripts/deploy/staging-lease.mjs` reads only `records[0]` (`per_page=1`) of task `staging-lease` + and fails closed unless `version === 1` and the v1 fields validate. Mutations run in job `lease` of + `.github/workflows/deploy-staging.yml`, serialized by the **workflow-level** group + `deploy-` (cancel-in-progress false). The whole deploy (~7-30 min) runs inside that group, so + any dispatch made meanwhile is a long-lived pending run that the next dispatch cancels. +- GitHub deployments have no compare-and-set; serialization needs a concurrency group, and a group + keeps at most one pending run. Appending a new deployment record needs no serialization: ids are + monotonic. +- `scripts/quality/deploy-staging-permissions.test.ts` pins: workflow-level group, only job `lease` + has `deployments: write`, every other job `needs: lease`. +- Old-workflow branches (copy of `staging-lease.mjs` from #2762/#2766) refuse any latest record that + is not v1: "Malformed lease record". Pre-#2762 branches have no lease job at all (pre-existing gap). +- DO migration tags: `apps/api/wrangler.toml` `[[migrations]]` (`tag = "vN"`), checked by + `scripts/deploy/durable-object-migrations.ts` at deploy time. + +## Design (part 1) + +- Records stay deployments with task `staging-lease`; payload `version: 2`. + - `kind: "reservation"` events are append-only (`branch`, `taskId`, `reservedAt`, `expiresAt`). + Written by a new `queue` job that has **no concurrency group**, so they can never be cancelled + or lost. + - `kind: "snapshot"` records are written only by the serialized `lease` job: `holder`, + `freeSince`, `promisedAt`, ordered `queue`, `seenThrough` (highest record id read). + - State = newest snapshot (or legacy v1 record) + reservation events with id > `seenThrough`. +- Turns: while free, queue entry 0 may take the slot from `max(freeSince, reservedAt)` until + `max(that, promisedAt) + grace` (`promisedAt` = the released holder's announced expiry, so an early + release never shortens the head's turn); each next entry gets `grace` after the previous window. + Missed windows drop the entry. Reservations older than the reservation TTL are skipped. With an + empty queue, anyone may acquire. +- `queue` job: appends a reservation unless the branch holds the lease or is already queued + (`reserve` always appends, renewing the TTL); lets the run into the `lease` job only if the branch + holds the lease or it is its turn; otherwise fails (deploy/acquire) or succeeds (reserve) with the + position in the step summary. +- `lease` job keeps group `deploy-` (same name as old workflows' group, so transition writes + serialize); deploy/storage-activation/agent-email audit move to group `staging-apply-`. +- Release removes the branch's hold and its reservation; re-acquiring means queueing at the back. +- Old workflows: any v2 record on top fails their lease job closed — no deploy, acquire, release. + Payload `notice` tells them to update from main. +- Malformed snapshot or unknown version → fail closed (as #2762). Malformed reservation event → skipped + and reported (it can only add an entry). +- `node scripts/deploy/staging-lease.mjs status `: one `gh api` call, prints holder + queue + with windows. Raw read: `gh api .../deployments?environment=&task=staging-lease&per_page=100`. + +## Checklist — Part 1 (PR 1) + +- [ ] Pure queue state + decision module with tests (empty queue, two waiters in order, head misses + grace, holder re-queues behind waiters, reservation expiry, concurrent reservations, legacy + record, malformed records, early release keeps head's turn) +- [ ] `staging-lease.mjs`: `queue` and `lease` phases, `status` command +- [ ] Workflow: `reserve` action, `queue` job outside group, `lease` job group, apply group; grace + and reservation TTL vars +- [ ] Permissions/gating test updated +- [ ] Docs: `.claude/commands/do.md`, `.agents/skills/do/SKILL.md`, `.claude/rules/13-staging-verification.md`, + `.agent-instructions/reference/rules/13-staging-verification-full.md` +- [ ] Live proof on staging2 with two branches (reserve/acquire/release, no full deploys) +- [ ] Note on idea, channel `feature.ship-faster` + +## Checklist — Part 2 (PR 2, after PR 1 merges) + +- [ ] Refuse `staging` deploys of a branch whose `apps/api/wrangler.toml` has a DO migration tag + `origin/main` lacks; fail closed if the comparison can't be made; message says use `staging2` +- [ ] Tests in the existing deploy-script test suite +- [ ] Docs: clean-up duty (teardown + redeploy main on staging2 before release) +- [ ] Tell #2721 owner (task 01M7C1SRMAWR3PYFWKF03XJ273) + +## Acceptance criteria + +- Reserve without deploying in seconds; read holder and ordered queue with one `gh api` call. +- Only the head may take a freed slot during its grace; then the next; releasing holder goes behind + existing waiters; stale reservations expire. +- No dispatch can cancel another agent's pending run or lose a reserved place. +- Old-workflow branches cannot jump the queue. +- Migration-carrying branches are refused on primary staging (part 2). From 85363ea4beea73bce79b1995401d32f58982775b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Mon, 16 Nov 2026 07:28:22 +0000 Subject: [PATCH 2/9] fix(staging): give the staging lease a fair queue Reservations are append-only deployment records written by a new queue job outside any concurrency group, so no later dispatch can cancel a waiting agent's place. Only a branch that holds the lease or whose turn it is reaches the serialized lease job. At release or expiry the head of the queue gets a configurable grace period, then the next entry; a releasing holder queues behind existing waiters; reservations expire. Records are version 2, which older workflow copies refuse. Co-Authored-By: Claude Opus 5.5 --- .../rules/13-staging-verification-full.md | 116 +++--- .agents/skills/do/SKILL.md | 2 +- .claude/commands/do.md | 111 ++--- .claude/rules/13-staging-verification.md | 6 +- .github/workflows/deploy-staging.yml | 76 +++- scripts/deploy/staging-lease-queue.mjs | 370 +++++++++++++++++ scripts/deploy/staging-lease-queue.test.mjs | 384 ++++++++++++++++++ scripts/deploy/staging-lease.mjs | 364 ++++++++++++----- scripts/deploy/staging-lease.test.mjs | 249 +++++------- .../deploy-staging-permissions.test.ts | 85 +++- .../2026-11-16-staging-lease-fair-queue.md | 10 +- 11 files changed, 1380 insertions(+), 393 deletions(-) create mode 100644 scripts/deploy/staging-lease-queue.mjs create mode 100644 scripts/deploy/staging-lease-queue.test.mjs diff --git a/.agent-instructions/reference/rules/13-staging-verification-full.md b/.agent-instructions/reference/rules/13-staging-verification-full.md index 0b5a307557..26659f427d 100644 --- a/.agent-instructions/reference/rules/13-staging-verification-full.md +++ b/.agent-instructions/reference/rules/13-staging-verification-full.md @@ -38,9 +38,10 @@ account's workers.dev subdomain and the Hetzner account. | `staging` | `https://app.sammy.party` | `https://api.sammy.party` | `sam` / `staging` | | `staging2` | `https://app.sammy2.party` | `https://api.sammy2.party` | `sam2` / `staging2` | -**Choosing one.** Read the lease of both (`task=staging-lease`, environments `staging` and -`staging2`) and take whichever is free. Each installation has its own lease, its own deploy -concurrency group and its own data, so two agents can verify at the same time. Deploy with +**Choosing one.** Read the queue of both (`node scripts/deploy/staging-lease.mjs status staging` +and `... status staging2`) and reserve the one that is free or has the shorter queue. Each +installation has its own lease and queue, its own concurrency groups and its own data, so two +agents can verify at the same time. Deploy with `gh workflow run deploy-staging.yml --ref -f environment=staging2 -f sam_task_id=` (omit `environment` for `staging`). Storage activation and the agent-email DNS audit are primary-only, and so is the signed GitHub-trigger audit (staging2 has no GitHub App). The @@ -95,57 +96,62 @@ GitHub may label some checks as informational, advisory, or not strictly require Staging deployment is **manual** — it does NOT run automatically on PRs. You must trigger it yourself: -1. **Read the environment lease** (the workflow enforces the same check atomically): +1. **Read the queue of both installations** (one `gh api` call each): ```bash - gh api --method GET repos/raphaeltm/simple-agent-manager/deployments \ - -f environment=staging -f task=staging-lease -f per_page=1 \ - --jq '.[0] | {id, payload}' + node scripts/deploy/staging-lease.mjs status staging2 # and: status staging + # Raw records, newest first (a `snapshot` plus newer `reservation` events): + gh api 'repos/raphaeltm/simple-agent-manager/deployments?environment=staging2&task=staging-lease&per_page=100' \ + --jq '[.[] | {id, payload}]' ``` - Use your selected environment name in every command. The latest `staging-lease` - deployment payload is authoritative; ordinary deployment statuses and a quiet - Actions queue do not release the slot. A held foreign branch with a future - `expiresAt` owns live verification even after its deploy finishes. Schedule a - one-time SAM wake at that exact UTC expiry (`schedules_write`, method `create`, - `message_session` action for your session), persist the accepted schedule ID, - and continue independent work or end the turn. On wake re-read once and retry - if free; if renewed, schedule a new wake. Do not poll, wait five minutes, or - negotiate the slot in chat. + `status` prints the holder, whether the slot is free, and the ordered queue + (branch, SAM task ID, reserved-at, turn window). There are two staging + installations, `staging` (`sammy.party`) and `staging2` (`sammy2.party`); pick the + one that is free or has the shorter queue and use that name in every command + below. They share the `staging` credentials but nothing else. staging2 sign-in is + workload identity only; see "Two Staging Installations" in the full reference. - No record means free (first-use bootstrap). A malformed latest record or API - error fails closed: ownership cannot be established safely. Inspect/fix the - record through the normal reviewed workflow; never delete history to bypass - another branch's lease. +2. **Reserve first, then deploy only on your turn.** Reserving takes seconds and + deploys nothing: -2. **Acquire by deploying your branch**, with your SAM task ID: + ```bash + gh workflow run deploy-staging.yml --ref \ + -f environment=staging2 -f lease_action=reserve -f sam_task_id= + ``` + + The run summary shows your position and estimated turn. When the slot is free + (holder released, or its lease expired), only the head of the queue may take it, + for `STAGING_LEASE_GRACE_MINUTES` (default 10); if it does not, the next entry + gets its own grace period and the missed one is dropped. If the holder released + early, the head's turn still lasts until the holder's announced expiry plus grace. + Schedule a one-time SAM wake (`schedules_write`, method `create`, + `message_session` for your session) at your turn start, persist the schedule ID, + and end the turn or do independent work. Do not poll, and **never dispatch a + deploy while another branch holds the lease or it is another branch's turn**: the + run is refused (your place is kept). A reservation expires after + `STAGING_LEASE_RESERVATION_MINUTES` (default 480) unless renewed by reserving + again, which keeps your place. + + On your turn, deploy (or `-f lease_action=acquire` to hold without deploying): ```bash gh workflow run deploy-staging.yml --ref \ - -f environment=staging -f sam_task_id= -f lease_hold_minutes=30 + -f environment=staging2 -f sam_task_id= -f lease_hold_minutes=30 ``` - The serialized lease job reads, acquires and reads back the lease before any - deploy/audit job. A foreign active lease fails immediately with holder branch, - task and expiry. Same-branch redeploys renew it. Expiry is acquisition time plus - expected deployment time plus live-check hold. GitHub Environment variables - `STAGING_LEASE_EXPECTED_DEPLOY_MINUTES` (default 30), - `STAGING_LEASE_DEFAULT_HOLD_MINUTES` (default 30), and - `STAGING_LEASE_MAX_HOLD_MINUTES` (default 120) configure durations; positive - integer holds above the cap are rejected. Expected deploy time may be zero. - Choose a hold covering your checks; renew before expiry if needed. Failed or - cancelled runs retain the lease until release/expiry, so failures cannot expose - checks to an overwrite. - - To reserve or renew without deploying, use `-f lease_action=acquire`. This - holds for just the requested live-check duration (no deploy allowance), and - also permits bounded lease lifecycle verification without full redeploys. - Audit-only runs acquire/renew through the same gate. Storage activation and - the agent-email DNS audit currently support only the primary `staging` slot; - unsupported combinations are rejected before lease acquisition. Lease writes must go - through this workflow; direct `gh api` writes bypass serialization. - -3. **Watch the run and verify live**, then **release early** from the holder branch: + A deploy dispatch also reserves if you are not queued yet, and goes straight + through when the slot is free and nobody is waiting. The `queue` job records + places outside any concurrency group, so no later dispatch can cancel your place; + only a branch that holds the lease or whose turn it is reaches the serialized + `lease` job. Same-branch redeploys renew the lease. Expiry is acquisition time + plus expected deployment time (`STAGING_LEASE_EXPECTED_DEPLOY_MINUTES`, default + 30; zero for `acquire`) plus the live-check hold + (`STAGING_LEASE_DEFAULT_HOLD_MINUTES`, default 30, capped by + `STAGING_LEASE_MAX_HOLD_MINUTES`, default 120). Failed or cancelled runs keep the + lease until release or expiry. + +3. **Watch the run and verify live**, then **release** and hand over: ```bash gh run list --workflow=deploy-staging.yml --branch= --limit=3 \ @@ -153,15 +159,25 @@ Staging deployment is **manual** — it does NOT run automatically on PRs. You m gh run watch # After live checks and test-resource cleanup: gh workflow run deploy-staging.yml --ref \ - -f environment=staging -f lease_action=release -f sam_task_id= + -f environment=staging2 -f lease_action=release -f sam_task_id= ``` - Confirm the release job passed and the newest payload has `state: released`. - Release shares the same environment concurrency group and refuses a foreign - holder. Expiry permits another branch to acquire automatically. Do not mistake - successful deployment completion for a release. Only the lease job receives - `deployments: write`; agents can inspect records with their existing `gh api` - read access. Leases are keyed by environment name for future staging slots. + Confirm the release run passed and `status` shows no holder. Release also + removes you from the queue if you were waiting. A branch that releases and wants + the slot again queues behind everyone already waiting. **If you release early, + message the next task in the queue** (`send_durable_message` to its SAM task ID + from `status`) so it can take its turn before its scheduled wake. Successful + deployment completion is not a release. + + Records are GitHub deployments with task `staging-lease`, keyed by installation. + A malformed snapshot or an unknown record version fails closed (no one can + change the lease until it is fixed through a reviewed change; never delete + history to get around another branch); a malformed reservation is skipped and + reported in the run. Branches whose workflow copy predates the queue are refused + by every queue record ("Malformed lease record"): they cannot reserve, deploy, + acquire or release until they update from `origin/main`. Only the `queue` and + `lease` jobs receive `deployments: write`; lease writes must go through the + workflow. For container-backed Instant verification, `wrangler deploy` success means the rollout started, not that every instance serves the new image. The shared staging diff --git a/.agents/skills/do/SKILL.md b/.agents/skills/do/SKILL.md index 17e35ea2ad..c12c10b039 100644 --- a/.agents/skills/do/SKILL.md +++ b/.agents/skills/do/SKILL.md @@ -16,7 +16,7 @@ Read the full workflow from `.claude/commands/do.md` and execute it. Use `.claud 4. **Implement** — follow checklist, push frequently, run quality checks. After the first push open the PR as a draft (`gh pr create --draft`); draft PRs run only quick CI checks. **For UI changes**: run mandatory Playwright visual audit with mock data on mobile + desktop viewports (see `.claude/rules/17-ui-visual-testing.md`) 5. **Validate** — full quality suite: lint, typecheck, test, build. As soon as the candidate is complete, mark the PR ready (`gh pr ready `), which starts the full CI suite, and request CodeRabbit at the same moment; reviews and staging then run in parallel with CI and CodeRabbit 6. **Review** — invoke local specialist skills / local subagents ($go-specialist, $cloudflare-specialist, etc.) -7. **Staging** — there are two installations, `staging` (`sammy.party`) and `staging2` (`sammy2.party`); read both leases and use whichever is free with `-f environment=` (staging2 sign-in: workload identity). Read the latest environment-keyed GitHub deployment lease (`task=staging-lease`); when held by another branch, schedule a SAM wake at `expiresAt` instead of polling or chatting. Trigger `gh workflow run deploy-staging.yml --ref -f sam_task_id=` to acquire/renew before deployment; after live checks release with the same command plus `-f lease_action=release` and confirm success. Configurable hold defaults/cap and commands: `.agent-instructions/reference/rules/13-staging-verification-full.md`. **Use `$CF_TOKEN` to query D1/KV/DNS directly** (see `.claude/rules/32-cf-api-debugging.md`) to verify migrations, data state, and feature flags — this is faster and more precise than UI-based checks. Then verify changed behavior end-to-end via Playwright. **For infrastructure changes** (cloud-init, VM agent, DNS, TLS, scripts/deploy): MUST provision a real VM and verify heartbeat arrives. +7. **Staging** — there are two installations, `staging` (`sammy.party`) and `staging2` (`sammy2.party`); read both queues with `node scripts/deploy/staging-lease.mjs status ` (one `gh api` call) and use the free or shorter one with `-f environment=` (staging2 sign-in: workload identity). Reserve first: `gh workflow run deploy-staging.yml --ref -f environment= -f lease_action=reserve -f sam_task_id=`; schedule a SAM wake at your turn start (shown in the run summary and `status`) instead of polling or chatting, and never dispatch a deploy while another branch holds the lease or has its turn. On your turn deploy with the same command minus `lease_action` (only the head of the queue may take a freed slot, for a 10-minute grace period by default). After live checks release with `-f lease_action=release`, confirm success, and if you released early message the next task in the queue. Configurable hold defaults/cap and commands: `.agent-instructions/reference/rules/13-staging-verification-full.md`. **Use `$CF_TOKEN` to query D1/KV/DNS directly** (see `.claude/rules/32-cf-api-debugging.md`) to verify migrations, data state, and feature flags — this is faster and more precise than UI-based checks. Then verify changed behavior end-to-end via Playwright. **For infrastructure changes** (cloud-init, VM agent, DNS, TLS, scripts/deploy): MUST provision a real VM and verify heartbeat arrives. 8. **PR** — the PR is already ready from step 5 (create it now if not, not as a draft). Wait for the full CI run on the ready PR (the required `Durable Object Workers` check reports only after every job finished). CodeRabbit is requested when the PR is marked ready, through the trusted GitHub Actions path: apply the `coderabbit-review` label with `gh pr edit --add-label coderabbit-review`; if the label run did not fire (it never fires on a draft PR), run `gh workflow run coderabbit-bot-review.yml --ref main -f pr_number=`. Do not post `@coderabbitai review` directly with an agent token. Then wait about 15 minutes from the request, ending at once on a `Review skipped`, rate-limit or quota reply. A CodeRabbit review is not required, but one that arrives blocks merge: implement or resolve every finding with a reason, and give incremental reviews after pushed fixes the same wait. If no review arrives (silence, `Review skipped`, rate limit), record that in the PR's CodeRabbit Review Evidence and continue. Do not re-trigger in a loop, and never add `needs-human-review` or wait for a waiver because CodeRabbit is silent (see `.claude/rules/25-review-merge-gate.md`). If the user requested draft PR / do-not-merge, do not mark it ready; get the full suite with `gh workflow run ci.yml --ref `, stop at the draft PR and do not merge. 9. **Cleanup** — remove worktree, pull main diff --git a/.claude/commands/do.md b/.claude/commands/do.md index a060f1cdeb..31863d8b68 100644 --- a/.claude/commands/do.md +++ b/.claude/commands/do.md @@ -210,61 +210,62 @@ If this PR includes **any code changes** (not just docs/tasks), deploy to stagin ### 6a. Standard Verification (All Code Changes) -1. **Read the environment lease** (the workflow enforces the same check atomically): +1. **Read the queue of both installations** (one `gh api` call each): ```bash - gh api --method GET repos/raphaeltm/simple-agent-manager/deployments \ - -f environment=staging -f task=staging-lease -f per_page=1 \ - --jq '.[0] | {id, payload}' + node scripts/deploy/staging-lease.mjs status staging2 # and: status staging + # Raw records, newest first (a `snapshot` plus newer `reservation` events): + gh api 'repos/raphaeltm/simple-agent-manager/deployments?environment=staging2&task=staging-lease&per_page=100' \ + --jq '[.[] | {id, payload}]' ``` - There are two staging installations, `staging` (`sammy.party`) and `staging2` - (`sammy2.party`). Read both leases and take whichever is free; use that name in - every command below. They share the `staging` credentials but nothing else, so - your checks cannot disturb an agent on the other one. staging2 sign-in is + `status` prints the holder, whether the slot is free, and the ordered queue + (branch, SAM task ID, reserved-at, turn window). There are two staging + installations, `staging` (`sammy.party`) and `staging2` (`sammy2.party`); pick the + one that is free or has the shorter queue and use that name in every command + below. They share the `staging` credentials but nothing else. staging2 sign-in is workload identity only; see "Two Staging Installations" in the full reference. - Use your selected environment name in every command. The latest `staging-lease` - deployment payload is authoritative; ordinary deployment statuses and a quiet - Actions queue do not release the slot. A held foreign branch with a future - `expiresAt` owns live verification even after its deploy finishes. Schedule a - one-time SAM wake at that exact UTC expiry (`schedules_write`, method `create`, - `message_session` action for your session), persist the accepted schedule ID, - and continue independent work or end the turn. On wake re-read once and retry - if free; if renewed, schedule a new wake. Do not poll, wait five minutes, or - negotiate the slot in chat. +2. **Reserve first, then deploy only on your turn.** Reserving takes seconds and + deploys nothing: - No record means free (first-use bootstrap). A malformed latest record or API - error fails closed: ownership cannot be established safely. Inspect/fix the - record through the normal reviewed workflow; never delete history to bypass - another branch's lease. + ```bash + gh workflow run deploy-staging.yml --ref \ + -f environment=staging2 -f lease_action=reserve -f sam_task_id= + ``` + + The run summary shows your position and estimated turn. When the slot is free + (holder released, or its lease expired), only the head of the queue may take it, + for `STAGING_LEASE_GRACE_MINUTES` (default 10); if it does not, the next entry + gets its own grace period and the missed one is dropped. If the holder released + early, the head's turn still lasts until the holder's announced expiry plus grace. + Schedule a one-time SAM wake (`schedules_write`, method `create`, + `message_session` for your session) at your turn start, persist the schedule ID, + and end the turn or do independent work. Do not poll, and **never dispatch a + deploy while another branch holds the lease or it is another branch's turn**: the + run is refused (your place is kept). A reservation expires after + `STAGING_LEASE_RESERVATION_MINUTES` (default 480) unless renewed by reserving + again, which keeps your place. -2. **Acquire by deploying your branch**, with your SAM task ID: + On your turn, deploy (or `-f lease_action=acquire` to hold without deploying): ```bash gh workflow run deploy-staging.yml --ref \ - -f environment=staging -f sam_task_id= -f lease_hold_minutes=30 + -f environment=staging2 -f sam_task_id= -f lease_hold_minutes=30 ``` - The serialized lease job reads, acquires and reads back the lease before any - deploy/audit job. A foreign active lease fails immediately with holder branch, - task and expiry. Same-branch redeploys renew it. Expiry is acquisition time plus - expected deployment time plus live-check hold. GitHub Environment variables - `STAGING_LEASE_EXPECTED_DEPLOY_MINUTES` (default 30), - `STAGING_LEASE_DEFAULT_HOLD_MINUTES` (default 30), and - `STAGING_LEASE_MAX_HOLD_MINUTES` (default 120) configure durations; positive - integer holds above the cap are rejected. Expected deploy time may be zero. - Choose a hold covering your checks; renew before expiry if needed. Failed or - cancelled runs retain the lease until release/expiry, so failures cannot expose - checks to an overwrite. + A deploy dispatch also reserves if you are not queued yet, and goes straight + through when the slot is free and nobody is waiting. The `queue` job records + places outside any concurrency group, so no later dispatch can cancel your place; + only a branch that holds the lease or whose turn it is reaches the serialized + `lease` job. Same-branch redeploys renew the lease. Expiry is acquisition time + plus expected deployment time (`STAGING_LEASE_EXPECTED_DEPLOY_MINUTES`, default + 30; zero for `acquire`) plus the live-check hold + (`STAGING_LEASE_DEFAULT_HOLD_MINUTES`, default 30, capped by + `STAGING_LEASE_MAX_HOLD_MINUTES`, default 120). Failed or cancelled runs keep the + lease until release or expiry. - To reserve or renew without deploying, use `-f lease_action=acquire`. This - holds for just the requested live-check duration (no deploy allowance), and - also permits bounded lease lifecycle verification without full redeploys. - Audit-only runs acquire/renew through the same gate. Lease writes must go - through this workflow; direct `gh api` writes bypass serialization. - -3. **Watch the run and verify live**, then **release early** from the holder branch: +3. **Watch the run and verify live**, then **release** and hand over: ```bash gh run list --workflow=deploy-staging.yml --branch= --limit=3 \ @@ -272,15 +273,25 @@ If this PR includes **any code changes** (not just docs/tasks), deploy to stagin gh run watch # After live checks and test-resource cleanup: gh workflow run deploy-staging.yml --ref \ - -f environment=staging -f lease_action=release -f sam_task_id= - ``` - - Confirm the release job passed and the newest payload has `state: released`. - Release shares the same environment concurrency group and refuses a foreign - holder. Expiry permits another branch to acquire automatically. Do not mistake - successful deployment completion for a release. Only the lease job receives - `deployments: write`; agents can inspect records with their existing `gh api` - read access. Leases are keyed by installation name (`staging`, `staging2`). + -f environment=staging2 -f lease_action=release -f sam_task_id= + ``` + + Confirm the release run passed and `status` shows no holder. Release also + removes you from the queue if you were waiting. A branch that releases and wants + the slot again queues behind everyone already waiting. **If you release early, + message the next task in the queue** (`send_durable_message` to its SAM task ID + from `status`) so it can take its turn before its scheduled wake. Successful + deployment completion is not a release. + + Records are GitHub deployments with task `staging-lease`, keyed by installation. + A malformed snapshot or an unknown record version fails closed (no one can + change the lease until it is fixed through a reviewed change; never delete + history to get around another branch); a malformed reservation is skipped and + reported in the run. Branches whose workflow copy predates the queue are refused + by every queue record ("Malformed lease record"): they cannot reserve, deploy, + acquire or release until they update from `origin/main`. Only the `queue` and + `lease` jobs receive `deployments: write`; lease writes must go through the + workflow. 4. **Open the live app** using Playwright — navigate to `app.sammy.party` (staging) or `app.sammy2.party` (staging2). diff --git a/.claude/rules/13-staging-verification.md b/.claude/rules/13-staging-verification.md index 82e527fac1..e478348610 100644 --- a/.claude/rules/13-staging-verification.md +++ b/.claude/rules/13-staging-verification.md @@ -4,9 +4,9 @@ Keep this root rule compact. The full procedure is preserved at `.agent-instruct - Code PRs require staging deployment and live verification unless the change is documentation-only, config-only, or task-file-only. - There are two staging installations, `staging` (`sammy.party`) and `staging2` (`sammy2.party`), each with its own lease and data. Take whichever is free and pass it as `-f environment=`; staging2 sign-in is workload identity only (full reference, "Two Staging Installations"). -- Read the latest GitHub deployment with task `staging-lease` for your environment before `deploy-staging.yml`; its serialized lease job enforces ownership. Pass `sam_task_id` and optional `lease_hold_minutes`. -- If a foreign branch holds an unexpired lease, schedule a one-time wake at `expiresAt` instead of polling or coordinating in chat. No active run plus five minutes is not a release. -- Same-branch redeploys renew; `lease_action=acquire` reserves/renews without deployment; `lease_action=release` frees the holder’s slot after live checks. Confirm release success. Expiry also frees it. Missing records bootstrap free; malformed records/API errors fail closed. Commands and configurable duration defaults/cap: full reference, section 1. +- Read both queues with `node scripts/deploy/staging-lease.mjs status ` (one `gh api` call over deployments with task `staging-lease`). Reserve first with `deploy-staging.yml` `-f lease_action=reserve`; it takes seconds, deploys nothing, and no later dispatch can cancel your place. +- When the slot frees (release or expiry) only the queue head may take it, for `STAGING_LEASE_GRACE_MINUTES` (default 10), then the next entry. Schedule a one-time wake at your turn start; never dispatch a deploy while another branch holds the lease or has its turn. A branch that releases and wants it again queues behind existing waiters. +- On your turn deploy (or `lease_action=acquire`); same-branch redeploys renew. `lease_action=release` frees your hold or place after live checks; confirm it, and message the next task in the queue when you release early. Malformed snapshots fail closed; branches whose workflow predates the queue are refused until they update from main. Details: full reference, section 1. - Authenticate Playwright against `https://api.sammy.party/api/auth/token-login` with `SAM_PLAYWRIGHT_PRIMARY_USER`; do not exchange staging tokens against production. - Alternative without a stored token: when staging trusts production (`AGENT_SIGN_IN_TRUST`), exchange your workload identity at `https://api.sammy.party/api/auth/workload-identity-login` (audience = that URL) and add the returned session cookie in Playwright. Exact values and commands: the full reference, section 2. - For VM/cloud-init/DNS/TLS infrastructure, provision a real VM, verify heartbeat and access, then clean it up. diff --git a/.github/workflows/deploy-staging.yml b/.github/workflows/deploy-staging.yml index 89b5192df2..d842f73a1b 100644 --- a/.github/workflows/deploy-staging.yml +++ b/.github/workflows/deploy-staging.yml @@ -11,9 +11,9 @@ on: description: 'SAM task holding the live verification slot (optional)' type: string lease_action: - description: 'Deploy and hold, reserve without deploying, or release from the holder branch' + description: 'deploy (queue, then deploy and hold), reserve (queue only), acquire (queue, then hold without deploying), release (give up hold or place)' type: choice - options: [deploy, acquire, release] + options: [deploy, reserve, acquire, release] default: deploy lease_hold_minutes: description: 'Live verification hold in minutes (default/cap from environment variables)' @@ -78,10 +78,11 @@ on: required: false type: string -# Only one staging deployment at a time; queue (don't cancel) concurrent requests -concurrency: - group: deploy-${{ inputs.environment || 'staging' }} - cancel-in-progress: false +# No workflow-level concurrency group: GitHub keeps one pending run per group and cancels the +# previous pending run, which silently lost waiting agents their place. The `queue` job records +# places outside any group; only runs whose turn it is enter the serialized `lease` job +# (group deploy-, the name older workflow copies also use), and mutating jobs share +# staging-apply-. See scripts/deploy/staging-lease-queue.mjs. env: PLAYWRIGHT_VERSION: 1.59.1 @@ -92,10 +93,13 @@ permissions: id-token: none jobs: - lease: + # Records this branch's place in the queue. Deliberately outside every concurrency group: a + # reservation is an append-only record, so no later dispatch can cancel it. Refuses here, with + # the queue in the run summary, when it is not this branch's turn. + queue: runs-on: ubuntu-24.04 # Every installation this workflow may target runs with the staging credentials, so the - # lease job never enters another Environment (the installation is validated in its first + # lease jobs never enter another Environment (the installation is validated in the first # step against scripts/deploy/staging-installations.mjs). environment: staging timeout-minutes: 2 @@ -104,6 +108,7 @@ jobs: deployments: write id-token: none outputs: + proceed: ${{ steps.queue.outputs.proceed }} credential_environment: ${{ steps.target.outputs.credential_environment }} installation: ${{ steps.target.outputs.installation }} base_domain: ${{ steps.target.outputs.base_domain }} @@ -118,7 +123,45 @@ jobs: INSTALLATION: ${{ inputs.environment || 'staging' }} PRIMARY_BASE_DOMAIN: ${{ vars.BASE_DOMAIN }} run: node scripts/deploy/staging-installations.mjs workflow-target - - name: Read and acquire, renew or release verification lease + - name: Reserve a place or confirm this branch's turn + id: queue + env: + GH_TOKEN: ${{ github.token }} + LEASE_ENVIRONMENT: ${{ inputs.environment || 'staging' }} + LEASE_ACTION: ${{ inputs.lease_action || 'deploy' }} + LEASE_PRIMARY_ONLY_AUDIT: ${{ inputs.activation_only || inputs.agent_email_dns_audit || inputs.github_trigger_audit }} + SAM_TASK_ID: ${{ inputs.sam_task_id }} + LEASE_HOLD_MINUTES: ${{ inputs.lease_hold_minutes }} + LEASE_DEFAULT_HOLD_MINUTES: ${{ vars.STAGING_LEASE_DEFAULT_HOLD_MINUTES || '30' }} + LEASE_MAX_HOLD_MINUTES: ${{ vars.STAGING_LEASE_MAX_HOLD_MINUTES || '120' }} + LEASE_GRACE_MINUTES: ${{ vars.STAGING_LEASE_GRACE_MINUTES || '10' }} + LEASE_RESERVATION_MINUTES: ${{ vars.STAGING_LEASE_RESERVATION_MINUTES || '480' }} + # Acquire-only holds do not need a deploy-time allowance. + LEASE_EXPECTED_DEPLOY_MINUTES: ${{ inputs.lease_action == 'acquire' && '0' || vars.STAGING_LEASE_EXPECTED_DEPLOY_MINUTES || '30' }} + run: node scripts/deploy/staging-lease.mjs queue + + # Serialized per installation. Only runs that hold the lease or whose turn it is get here, so a + # pending run in this group can only be displaced by another run of the same entitled branch. + lease: + needs: queue + if: ${{ needs.queue.outputs.proceed == 'true' }} + runs-on: ubuntu-24.04 + environment: staging + timeout-minutes: 2 + concurrency: + group: deploy-${{ inputs.environment || 'staging' }} + cancel-in-progress: false + permissions: + contents: read + deployments: write + id-token: none + outputs: + credential_environment: ${{ needs.queue.outputs.credential_environment }} + installation: ${{ needs.queue.outputs.installation }} + base_domain: ${{ needs.queue.outputs.base_domain }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - name: Acquire, renew or release the verification lease env: GH_TOKEN: ${{ github.token }} LEASE_ENVIRONMENT: ${{ inputs.environment || 'staging' }} @@ -128,13 +171,18 @@ jobs: LEASE_HOLD_MINUTES: ${{ inputs.lease_hold_minutes }} LEASE_DEFAULT_HOLD_MINUTES: ${{ vars.STAGING_LEASE_DEFAULT_HOLD_MINUTES || '30' }} LEASE_MAX_HOLD_MINUTES: ${{ vars.STAGING_LEASE_MAX_HOLD_MINUTES || '120' }} - # Reserve-only checks do not need a deploy-time allowance. + LEASE_GRACE_MINUTES: ${{ vars.STAGING_LEASE_GRACE_MINUTES || '10' }} + LEASE_RESERVATION_MINUTES: ${{ vars.STAGING_LEASE_RESERVATION_MINUTES || '480' }} + # Acquire-only holds do not need a deploy-time allowance. LEASE_EXPECTED_DEPLOY_MINUTES: ${{ inputs.lease_action == 'acquire' && '0' || vars.STAGING_LEASE_EXPECTED_DEPLOY_MINUTES || '30' }} - run: node scripts/deploy/staging-lease.mjs + run: node scripts/deploy/staging-lease.mjs lease deploy: needs: lease if: ${{ (inputs.lease_action == 'deploy' || inputs.lease_action == '') && !inputs.github_trigger_audit_send_only && !inputs.activation_only && !inputs.performance_audit_only }} + concurrency: + group: staging-apply-${{ inputs.environment || 'staging' }} + cancel-in-progress: false uses: ./.github/workflows/deploy-reusable.yml with: environment: ${{ needs.lease.outputs.credential_environment }} @@ -219,6 +267,9 @@ jobs: needs: lease # Primary installation only (also refused in the lease preflight). if: ${{ (inputs.lease_action == 'deploy' || inputs.lease_action == '') && inputs.activation_only && needs.lease.outputs.installation == '' }} + concurrency: + group: staging-apply-${{ inputs.environment || 'staging' }} + cancel-in-progress: false runs-on: ubuntu-latest environment: ${{ needs.lease.outputs.credential_environment }} steps: @@ -251,6 +302,9 @@ jobs: needs: [lease, deploy] # Primary installation only (also refused in the lease preflight). if: ${{ (inputs.lease_action == 'deploy' || inputs.lease_action == '') && inputs.agent_email_dns_audit && !inputs.dry_run && needs.lease.outputs.installation == '' }} + concurrency: + group: staging-apply-${{ inputs.environment || 'staging' }} + cancel-in-progress: false runs-on: ubuntu-latest environment: ${{ needs.lease.outputs.credential_environment }} timeout-minutes: 5 diff --git a/scripts/deploy/staging-lease-queue.mjs b/scripts/deploy/staging-lease-queue.mjs new file mode 100644 index 0000000000..b686406095 --- /dev/null +++ b/scripts/deploy/staging-lease-queue.mjs @@ -0,0 +1,370 @@ +// Pure state and decisions for the staging verification lease and its queue. +// I/O and the workflow entry points live in staging-lease.mjs. +// +// Records are GitHub deployments with task `staging-lease`, one stream per installation. +// - kind "reservation" (version 2): an append-only queue event. Written outside the workflow's +// concurrency group, so a pending-run cancellation can never lose it. +// - kind "snapshot" (version 2): the whole state (holder, ordered queue). Written only by the +// serialized lease job. `seenThrough` is the highest record id that job had read. +// - version 1: the pre-queue lease shape (#2762). Read as a base state; never written. +// State = newest snapshot (or version 1 record) + reservation events with id > seenThrough. +// Workflow copies from before the queue read only the newest record and refuse anything that is +// not version 1, so they can neither jump the queue nor drop it. + +export const LEASE_TASK = 'staging-lease'; +export const RECORD_PAGE_SIZE = 100; +export const OLD_WORKFLOW_NOTICE = + 'Staging lease queue (version 2). Update this branch from origin/main to reserve, deploy or release; workflow copies from before the queue refuse this record by design.'; + +const MINUTE = 60_000; +const SHA = /^[a-f0-9]{40}$/i; + +export function validUtc(value) { + if ( + typeof value !== 'string' || + !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?Z$/.test(value) + ) + return false; + const parsed = Date.parse(value); + const canonical = value.length === 20 ? value.replace('Z', '.000Z') : value; + return Number.isFinite(parsed) && new Date(parsed).toISOString() === canonical; +} + +const iso = (ms) => new Date(ms).toISOString(); +const text = (value) => typeof value === 'string'; +const branchName = (value) => text(value) && value.length > 0; +const utcOrNull = (value) => value === null || validUtc(value); + +function malformed(id, detail) { + return new Error( + `Malformed lease record ${id ?? '(no id)'} (${detail}); refusing to change the lease. Inspect the record with gh api.` + ); +} + +function validEntry(entry) { + return ( + branchName(entry?.branch) && + text(entry.taskId) && + validUtc(entry.reservedAt) && + validUtc(entry.expiresAt) && + (entry.lastReservedAt === undefined || validUtc(entry.lastReservedAt)) + ); +} + +function validHolder(holder) { + return ( + holder === null || + (branchName(holder?.branch) && + text(holder.taskId) && + SHA.test(holder.sha ?? '') && + validUtc(holder.acquiredAt) && + validUtc(holder.expiresAt)) + ); +} + +// Classify one deployment record. Throws (fail closed) for anything that could be the authoritative +// state and does not validate, and for unknown versions or kinds. A malformed reservation event is +// returned as `invalid`: it can only ever add a queue entry, so skipping it cannot hand anyone the slot. +export function parseRecord(record, environment) { + const id = record?.id; + if (!Number.isSafeInteger(id) || id < 1) throw malformed(id, 'missing id'); + let payload = record.payload; + if (text(payload)) { + try { + payload = JSON.parse(payload); + } catch { + throw malformed(id, 'payload is not JSON'); + } + } + if (record.environment !== environment || record.task !== LEASE_TASK || !payload) + throw malformed(id, 'wrong environment or task'); + if (payload.environment !== environment) throw malformed(id, 'payload environment'); + if (payload.version === 1) { + if ( + !['held', 'released'].includes(payload.state) || + !branchName(payload.branch) || + !SHA.test(payload.sha ?? '') || + !text(payload.taskId) || + !validUtc(payload.expiresAt) + ) + throw malformed(id, 'version 1 fields'); + return { type: 'legacy', id, lease: payload }; + } + if (payload.version !== 2) throw malformed(id, `unknown version ${payload.version}`); + if (payload.kind === 'reservation') { + if (!validEntry(payload)) return { type: 'invalid', id, reason: 'reservation fields' }; + const { branch, taskId, reservedAt, expiresAt } = payload; + return { type: 'reservation', id, entry: { branch, taskId, reservedAt, expiresAt } }; + } + if (payload.kind !== 'snapshot') throw malformed(id, `unknown kind ${payload.kind}`); + const queue = payload.queue; + if ( + !Number.isSafeInteger(payload.seenThrough) || + payload.seenThrough < 0 || + payload.seenThrough >= id || + !validHolder(payload.holder) || + !utcOrNull(payload.freeSince) || + !utcOrNull(payload.promisedAt) || + !Array.isArray(queue) || + !queue.every(validEntry) || + new Set(queue.map((entry) => entry.branch)).size !== queue.length + ) + throw malformed(id, 'snapshot fields'); + return { + type: 'snapshot', + id, + state: { + holder: payload.holder, + freeSince: payload.freeSince, + promisedAt: payload.promisedAt, + queue: queue.map((entry) => ({ ...entry })), + seenThrough: payload.seenThrough, + }, + }; +} + +function baseState(parsed) { + if (!parsed) + return { holder: null, freeSince: null, promisedAt: null, queue: [], seenThrough: 0 }; + if (parsed.type === 'snapshot') return parsed.state; + const { lease } = parsed; + const held = lease.state === 'held'; + return { + holder: held + ? { + branch: lease.branch, + taskId: lease.taskId, + sha: lease.sha, + acquiredAt: lease.expiresAt, + expiresAt: lease.expiresAt, + } + : null, + freeSince: held ? null : lease.expiresAt, + promisedAt: held ? null : lease.expiresAt, + queue: [], + seenThrough: parsed.id, + }; +} + +// A reservation by a branch already queued keeps its place and extends its expiry. It also records +// when it was made, so a branch that missed its turn and reserves again rejoins at the back. +export function applyReservation(state, entry) { + if (state.holder?.branch === entry.branch) return; + const existing = state.queue.find((queued) => queued.branch === entry.branch); + if (!existing) { + state.queue.push({ ...entry }); + return; + } + if (Date.parse(entry.expiresAt) > Date.parse(existing.expiresAt)) + existing.expiresAt = entry.expiresAt; + if (Date.parse(entry.reservedAt) > Date.parse(existing.lastReservedAt ?? existing.reservedAt)) + existing.lastReservedAt = entry.reservedAt; + if (entry.taskId) existing.taskId = entry.taskId; +} + +// records: newest first, as GitHub lists deployments. +export function foldRecords(records, environment, pageSize = RECORD_PAGE_SIZE) { + if (!Array.isArray(records)) throw new Error('Unreadable deployment list; refusing lease change'); + const events = []; + const warnings = []; + let base = null; + let covered = records.length < pageSize; // a short page is the whole history + for (const record of records) { + const parsed = parseRecord(record, environment); + if (base) { + if (parsed.id <= base.state.seenThrough) { + covered = true; + break; + } + // Older than the snapshot but unseen by it: a reservation made while it was being written. + if (parsed.type === 'reservation' || parsed.type === 'invalid') events.push(parsed); + continue; + } + if (parsed.type === 'reservation' || parsed.type === 'invalid') { + events.push(parsed); + continue; + } + base = { id: parsed.id, state: baseState(parsed) }; + if (base.state.seenThrough >= parsed.id - 1) { + covered = true; + break; + } + } + if (!covered) + throw new Error( + `Lease history does not fit in the newest ${pageSize} records; refusing lease change` + ); + const state = base ? base.state : baseState(null); + for (const event of events.sort((a, b) => a.id - b.id)) { + if (event.id <= state.seenThrough) continue; + if (event.type === 'invalid') { + warnings.push(`Skipped malformed reservation record ${event.id} (${event.reason})`); + continue; + } + applyReservation(state, event.entry); + } + state.seenThrough = records.reduce((max, record) => Math.max(max, record.id), state.seenThrough); + return { state, warnings }; +} + +// Work out, at `now`, who holds the slot and every queued branch's turn window. +// While the slot is free, the first live entry may take it from max(freeSince, reservedAt) until +// max(that, promisedAt) + grace; promisedAt is the expiry the last holder had announced, so an +// early release never shortens the waiter's turn. Each later entry gets `grace` after the one +// before it. An entry whose reservation expires before its turn starts is stale and takes no time. +export function resolveTurns(state, now, graceMinutes) { + const grace = graceMinutes * MINUTE; + let holder = state.holder; + let lastHolder = null; + let freeSince = state.freeSince ? Date.parse(state.freeSince) : 0; + let promisedAt = state.promisedAt ? Date.parse(state.promisedAt) : freeSince; + if (holder && Date.parse(holder.expiresAt) <= now) { + lastHolder = holder; + freeSince = promisedAt = Date.parse(holder.expiresAt); + holder = null; + } + if (holder) freeSince = promisedAt = Date.parse(holder.expiresAt); // estimate only + const pending = state.queue.map((entry) => ({ ...entry })); + const entries = []; + let previousEnd = null; + for (let index = 0; index < pending.length; index += 1) { + const entry = pending[index]; + const reserved = Date.parse(entry.reservedAt); + const first = previousEnd === null; + const start = first ? Math.max(freeSince, reserved) : Math.max(previousEnd, reserved); + if (Date.parse(entry.expiresAt) <= start) { + entries.push({ ...entry, status: 'stale', start, end: start }); + continue; + } + const end = (first ? Math.max(start, promisedAt) : start) + grace; + let status = 'waiting'; + if (!holder && end <= now) status = 'missed'; + else if (!holder && start <= now) status = 'turn'; + entries.push({ ...entry, status, start, end }); + previousEnd = end; + const again = entry.lastReservedAt ? Date.parse(entry.lastReservedAt) : null; + if (status === 'missed' && again !== null && again >= end) { + // Missed its turn, then reserved again: back of the queue. + pending.push({ + branch: entry.branch, + taskId: entry.taskId, + reservedAt: entry.lastReservedAt, + expiresAt: entry.expiresAt, + }); + } + } + const live = entries.filter((entry) => entry.status === 'turn' || entry.status === 'waiting'); + return { holder, lastHolder, freeSince, promisedAt, entries, live, grace }; +} + +function queueEntry({ branch, taskId, reservedAt, expiresAt, lastReservedAt }) { + return lastReservedAt + ? { branch, taskId, reservedAt, expiresAt, lastReservedAt } + : { branch, taskId, reservedAt, expiresAt }; +} + +// The state to store after a decision taken while the slot is free. Dropped (missed or stale) +// entries are removed, and freeSince/promisedAt are moved so the remaining windows are unchanged. +// If the branch whose turn it was leaves, the next one may start at once and still keeps the window +// it was promised. +function freeSnapshot(turns, keep, now) { + const remaining = turns.live.filter(keep); + if (remaining.length === 0) + return { + holder: null, + freeSince: iso(turns.freeSince), + promisedAt: iso(turns.promisedAt), + queue: [], + }; + const [first] = remaining; + return { + holder: null, + freeSince: iso(Math.min(first.start, now)), + promisedAt: iso(first.end - turns.grace), + queue: remaining.map(queueEntry), + }; +} + +export function hasTurn(turns, branch) { + return !turns.holder && turns.live[0]?.branch === branch && turns.live[0].status === 'turn'; +} + +export function position(turns, branch) { + const index = turns.live.findIndex((entry) => entry.branch === branch); + return index === -1 ? null : index + 1; +} + +export function describeTurn(entry) { + return `${entry.branch} (SAM task ${entry.taskId || 'not supplied'}) ${entry.status === 'turn' ? 'may take the slot until' : 'turn from'} ${iso(entry.status === 'turn' ? entry.end : entry.start)}`; +} + +function refusal(turns, branch, environment) { + const where = position(turns, branch); + const place = where + ? `You are number ${where} in the queue; your turn is estimated to start at ${iso(turns.live[where - 1].start)}. Schedule a wake for it.` + : 'You are not in the queue.'; + if (turns.holder) + return `Environment ${environment} held by branch ${turns.holder.branch}, SAM task ${turns.holder.taskId || '(not supplied)'}, expires ${turns.holder.expiresAt}. ${place}`; + return `Environment ${environment} is reserved for ${describeTurn(turns.live[0])}. ${place}`; +} + +// Queue phase (outside the concurrency group): should this run append a reservation? `reserve` +// always appends (renewing it); deploy/acquire append unless the branch holds the lease or waits. +export function planQueue({ state, branch, action, now, graceMinutes }) { + const turns = resolveTurns(state, now, graceMinutes); + const holds = turns.holder?.branch === branch; + if (action === 'release' || holds) return { append: false, holds, turns }; + return { append: action === 'reserve' || position(turns, branch) === null, holds, turns }; +} + +// Lease phase (serialized): the authoritative decision. Returns the snapshot state to write, or +// null when nothing changes. Throws a refusal message when the branch may not proceed. +export function decideLease({ + state, + branch, + taskId, + sha, + action, + now, + graceMinutes, + holdMinutes, + environment, +}) { + if (!['deploy', 'acquire', 'release'].includes(action)) throw new Error('Unknown lease action'); + const turns = resolveTurns(state, now, graceMinutes); + const mine = (entry) => entry.branch === branch; + if (action === 'release') { + if (turns.holder && mine(turns.holder)) { + return { + holder: null, + freeSince: iso(now), + promisedAt: turns.holder.expiresAt, + queue: state.queue.filter((entry) => !mine(entry)).map(queueEntry), + }; + } + if (!state.queue.some(mine)) { + if (turns.holder) + throw new Error(`Only holder branch ${turns.holder.branch} may release this lease.`); + return null; // Nothing held or queued by this branch: releasing is a no-op. + } + if (turns.holder) + return { ...state, queue: state.queue.filter((entry) => !mine(entry)).map(queueEntry) }; + return freeSnapshot(turns, (entry) => !mine(entry), now); + } + const expiresAt = iso(now + holdMinutes * MINUTE); + if (turns.holder) { + if (!mine(turns.holder)) throw new Error(refusal(turns, branch, environment)); + return { + ...state, + holder: { ...turns.holder, sha, taskId: taskId || turns.holder.taskId, expiresAt }, + }; + } + if (turns.live.length > 0 && !hasTurn(turns, branch)) + throw new Error(refusal(turns, branch, environment)); + return { + holder: { branch, taskId, sha, acquiredAt: iso(now), expiresAt }, + freeSince: null, + promisedAt: null, + queue: turns.live.filter((entry) => !mine(entry)).map(queueEntry), + }; +} diff --git a/scripts/deploy/staging-lease-queue.test.mjs b/scripts/deploy/staging-lease-queue.test.mjs new file mode 100644 index 0000000000..8c78636e5b --- /dev/null +++ b/scripts/deploy/staging-lease-queue.test.mjs @@ -0,0 +1,384 @@ +// Queue behaviour, driven through the workflow entry points (runQueue, then runLease when the queue +// job lets the run through) against an in-memory GitHub deployments API. +import test from 'node:test'; +import assert from 'node:assert/strict'; + +import { LEASE_TASK, leaseStatus, runLease, runQueue } from './staging-lease.mjs'; + +const MIN = 60_000; +const T0 = Date.parse('2026-11-16T08:00:00Z'); +const sha = 'b'.repeat(40); +const timing = { deploy: 30, hold: 30, graceMinutes: 10, reservationMinutes: 480 }; + +function store(initial = []) { + const records = [...initial]; // newest first + let nextId = Math.max(0, ...initial.map((r) => r.id)) + 1; + const hooks = { afterList: null }; + const api = async (method, endpoint, body) => { + if (method === 'POST') { + const record = { ...structuredClone(body), id: nextId++ }; + records.unshift(record); + return record; + } + if (endpoint.startsWith('/deployments?')) { + const query = new URLSearchParams(endpoint.split('?')[1]); + assert.equal(query.get('task'), LEASE_TASK); + const list = records + .filter((r) => r.environment === query.get('environment') && r.task === LEASE_TASK) + .slice(0, Number(query.get('per_page'))) + .map((r) => structuredClone(r)); + const hook = hooks.afterList; + hooks.afterList = null; + if (hook) await hook(); + return list; + } + return structuredClone(records.find((r) => endpoint === `/deployments/${r.id}`)); + }; + return { records, api, hooks }; +} + +// One workflow dispatch: queue job, then the serialized lease job if it was let through. +async function dispatch(db, branch, action, at, extra = {}) { + const request = { + api: db.api, + environment: 'staging2', + branch, + sha, + taskId: `task-${branch}`, + action, + timing, + now: at, + ...extra, + }; + const queued = await runQueue(request); + if (!queued.proceed) return { queued, refused: queued.refused }; + try { + return { queued, lease: await runLease(request) }; + } catch (error) { + return { queued, refused: true, error: error.message }; + } +} + +const status = (db, at) => leaseStatus({ api: db.api, environment: 'staging2', now: at }); +const order = async (db, at) => (await status(db, at)).queue.map((entry) => entry.branch); +const holder = async (db, at) => (await status(db, at)).holder?.branch ?? null; + +test('empty queue: the first dispatch reserves and takes the slot in one run', async () => { + const db = store(); + const { lease } = await dispatch(db, 'a', 'deploy', T0); + assert.equal(lease.holder.branch, 'a'); + assert.equal(lease.holder.expiresAt, new Date(T0 + 60 * MIN).toISOString()); + assert.equal(await holder(db, T0 + MIN), 'a'); + assert.deepEqual(await order(db, T0 + MIN), []); + const kinds = db.records.map((r) => r.payload.kind); + assert.deepEqual(kinds, ['snapshot', 'reservation']); + // Every record carries version 2, which workflow copies from before the queue refuse. + assert.ok(db.records.every((r) => r.payload.version === 2 && r.payload.notice)); +}); + +test('two waiters are served in order; nobody else may take a freed slot during their turns', async () => { + const db = store(); + await dispatch(db, 'a', 'deploy', T0); + const b = await dispatch(db, 'b', 'deploy', T0 + MIN); + assert.equal(b.refused, true); + assert.match(b.queued.lines.at(-1), /b is number 1/); + await dispatch(db, 'c', 'reserve', T0 + 2 * MIN); + assert.deepEqual(await order(db, T0 + 3 * MIN), ['b', 'c']); + + // A's lease expires at T0+60. Only B may take it, then only C. + const expiry = T0 + 60 * MIN; + for (const branch of ['c', 'd']) { + const early = await dispatch(db, branch, 'acquire', expiry + MIN); + assert.equal(early.refused, true, `${branch} must wait for b`); + } + assert.equal(await holder(db, expiry + MIN), null); + assert.equal((await dispatch(db, 'b', 'acquire', expiry + 2 * MIN)).lease.holder.branch, 'b'); + assert.deepEqual(await order(db, expiry + 3 * MIN), ['c', 'd']); + await dispatch(db, 'b', 'release', expiry + 5 * MIN); + assert.equal((await dispatch(db, 'd', 'deploy', expiry + 6 * MIN)).refused, true); + assert.equal((await dispatch(db, 'c', 'deploy', expiry + 6 * MIN)).lease.holder.branch, 'c'); + assert.deepEqual(await order(db, expiry + 7 * MIN), ['d']); +}); + +test('a head that misses its grace period is dropped and the next entry gets a full grace period', async () => { + const db = store(); + await dispatch(db, 'a', 'acquire', T0, { timing: { ...timing, hold: 30 } }); + await dispatch(db, 'b', 'reserve', T0 + MIN); + await dispatch(db, 'c', 'reserve', T0 + 2 * MIN); + const expiry = T0 + 30 * MIN; + const view = await status(db, expiry + MIN); + assert.equal(view.queue[0].turnEnds, new Date(expiry + 10 * MIN).toISOString()); + assert.equal(view.queue[1].turnStarts, new Date(expiry + 10 * MIN).toISOString()); + // B never comes. At expiry+10 the turn passes to C until expiry+20. + assert.equal((await dispatch(db, 'c', 'acquire', expiry + 9 * MIN)).refused, true); + assert.equal((await dispatch(db, 'd', 'acquire', expiry + 12 * MIN)).refused, true); + assert.equal((await dispatch(db, 'c', 'acquire', expiry + 19 * MIN)).lease.holder.branch, 'c'); + // B wakes late: it is behind D now. + assert.equal((await dispatch(db, 'b', 'deploy', expiry + 25 * MIN)).refused, true); + assert.deepEqual(await order(db, expiry + 26 * MIN), ['d', 'b']); +}); + +test('a missed head that reserves again rejoins at the back, even before the snapshot is rewritten', async () => { + const db = store(); + await dispatch(db, 'a', 'acquire', T0); + await dispatch(db, 'b', 'reserve', T0 + MIN); + await dispatch(db, 'c', 'reserve', T0 + 2 * MIN); + const expiry = T0 + 30 * MIN; + await dispatch(db, 'b', 'reserve', expiry + 15 * MIN); // missed [expiry, expiry+10) + assert.deepEqual(await order(db, expiry + 15 * MIN), ['c', 'b']); +}); + +test('a holder that releases goes behind everyone already queued', async () => { + const db = store(); + await dispatch(db, 'a', 'deploy', T0); + await dispatch(db, 'b', 'reserve', T0 + MIN); + const released = await dispatch(db, 'a', 'release', T0 + 20 * MIN); + assert.match(released.lease.message, /released by a/); + const again = await dispatch(db, 'a', 'deploy', T0 + 21 * MIN); + assert.equal(again.refused, true); + assert.deepEqual(await order(db, T0 + 21 * MIN), ['b', 'a']); + // Early release never shortens B's turn: it lasts until A's announced expiry plus grace. + const view = await status(db, T0 + 21 * MIN); + assert.equal(view.queue[0].turnEnds, new Date(T0 + 70 * MIN).toISOString()); + assert.equal((await dispatch(db, 'b', 'acquire', T0 + 65 * MIN)).lease.holder.branch, 'b'); +}); + +test('the branch whose turn it is can leave the queue, and the next one may start at once', async () => { + const db = store(); + await dispatch(db, 'a', 'acquire', T0); + await dispatch(db, 'b', 'reserve', T0 + MIN); + await dispatch(db, 'c', 'reserve', T0 + MIN); + const expiry = T0 + 30 * MIN; + await dispatch(db, 'b', 'release', expiry + 2 * MIN); + assert.deepEqual(await order(db, expiry + 2 * MIN), ['c']); + const view = await status(db, expiry + 2 * MIN); + assert.equal(view.queue[0].status, 'turn'); + assert.equal(view.queue[0].turnEnds, new Date(expiry + 20 * MIN).toISOString()); + // A releasing branch that holds nothing writes nothing. + const before = db.records.length; + assert.equal((await dispatch(db, 'z', 'release', expiry + 3 * MIN)).lease.written, false); + assert.equal(db.records.length, before); + // Someone else's lease cannot be released. + await dispatch(db, 'c', 'acquire', expiry + 3 * MIN); + assert.match( + (await dispatch(db, 'z', 'release', expiry + 4 * MIN)).error, + /Only holder branch c/ + ); +}); + +test('stale reservations expire and take no turn', async () => { + const db = store(); + const short = { ...timing, reservationMinutes: 45 }; + await dispatch(db, 'a', 'deploy', T0); // expires T0+60 + await dispatch(db, 'b', 'reserve', T0 + MIN, { timing: short }); // reservation expires T0+46 + assert.deepEqual(await order(db, T0 + 2 * MIN), []); + assert.equal((await dispatch(db, 'c', 'deploy', T0 + 61 * MIN)).lease.holder.branch, 'c'); + // Reserving again renews a reservation without losing the place. + const db2 = store(); + await dispatch(db2, 'a', 'deploy', T0); + await dispatch(db2, 'b', 'reserve', T0 + MIN, { timing: short }); + await dispatch(db2, 'c', 'reserve', T0 + 2 * MIN); + await dispatch(db2, 'b', 'reserve', T0 + 40 * MIN); + assert.deepEqual(await order(db2, T0 + 41 * MIN), ['b', 'c']); + assert.equal((await dispatch(db2, 'b', 'acquire', T0 + 61 * MIN)).lease.holder.branch, 'b'); +}); + +test('concurrent reservations, including one made while the lease job writes, all keep their place', async () => { + const db = store(); + await dispatch(db, 'a', 'deploy', T0); + // B and C reserve "at once": both append, ordered by record id. + await Promise.all([ + dispatch(db, 'b', 'reserve', T0 + MIN), + dispatch(db, 'c', 'reserve', T0 + MIN), + ]); + // D reserves between the lease job's read and its snapshot write. + db.hooks.afterList = () => + runQueue({ + api: db.api, + environment: 'staging2', + branch: 'd', + sha, + action: 'reserve', + timing, + now: T0 + 2 * MIN, + }); + await runLease({ + api: db.api, + environment: 'staging2', + branch: 'a', + sha, + action: 'deploy', + timing, + now: T0 + 2 * MIN, + }); + const snapshot = db.records.find((r) => r.payload.kind === 'snapshot'); + assert.ok(!snapshot.payload.queue.some((entry) => entry.branch === 'd')); + assert.deepEqual(await order(db, T0 + 3 * MIN), ['b', 'c', 'd']); +}); + +test('a version 1 record from an older workflow is honoured as the holder, and the queue forms behind it', async () => { + const legacy = { + id: 7, + task: LEASE_TASK, + environment: 'staging2', + payload: { + version: 1, + environment: 'staging2', + state: 'held', + branch: 'old', + sha, + taskId: 'task-old', + expiresAt: new Date(T0 + 30 * MIN).toISOString(), + }, + }; + const db = store([legacy]); + assert.equal(await holder(db, T0), 'old'); + assert.equal((await dispatch(db, 'b', 'deploy', T0)).refused, true); + assert.equal((await dispatch(db, 'c', 'deploy', T0 + 31 * MIN)).refused, true); + assert.equal((await dispatch(db, 'b', 'deploy', T0 + 32 * MIN)).lease.holder.branch, 'b'); + const released = store([ + { + ...legacy, + payload: { ...legacy.payload, state: 'released', expiresAt: new Date(T0).toISOString() }, + }, + ]); + assert.equal((await dispatch(released, 'c', 'deploy', T0 + MIN)).lease.holder.branch, 'c'); +}); + +// The guard from workflow copies before the queue (#2762, #2766), verbatim in effect: they read +// only the newest record and refuse it unless it is a valid version 1 lease. +function olderWorkflowReads(records) { + const lease = records[0]?.payload; + if (lease && lease.version !== 1) throw new Error('Malformed lease record'); + return lease; +} + +test('older workflow copies are refused on every record the queue writes, so they cannot jump it', async () => { + const db = store(); + await dispatch(db, 'a', 'deploy', T0); + assert.throws(() => olderWorkflowReads(db.records), /Malformed/); + await dispatch(db, 'b', 'reserve', T0 + MIN); + assert.throws(() => olderWorkflowReads(db.records), /Malformed/); + await dispatch(db, 'a', 'release', T0 + 2 * MIN); + assert.throws(() => olderWorkflowReads(db.records), /Malformed/); +}); + +test('malformed records: snapshots and unknown versions fail closed, bad reservations are skipped', async () => { + const db = store(); + await dispatch(db, 'a', 'deploy', T0); + const good = store(structuredClone(db.records)); + const snapshot = db.records[0]; + for (const payload of [ + '{bad json', + null, + { ...snapshot.payload, holder: { branch: 'x' } }, + { ...snapshot.payload, queue: 'nope' }, + { ...snapshot.payload, seenThrough: snapshot.id }, + { ...snapshot.payload, version: 3 }, + { ...snapshot.payload, kind: 'other' }, + ]) { + const bad = store([{ ...snapshot, payload }, ...db.records.slice(1)]); + const before = bad.records.length; + const result = await dispatch(bad, 'b', 'deploy', T0 + 90 * MIN).catch((error) => ({ error })); + assert.match(String(result.error?.message ?? result.error), /Malformed/); + assert.equal(bad.records.length, before, 'nothing written'); + } + good.records.unshift({ + id: 99, + task: LEASE_TASK, + environment: 'staging2', + payload: { version: 2, kind: 'reservation', environment: 'staging2', branch: '' }, + }); + await dispatch(good, 'c', 'reserve', T0 + MIN); + const view = await status(good, T0 + 2 * MIN); + assert.deepEqual( + view.queue.map((entry) => entry.branch), + ['c'] + ); + assert.match(view.warnings[0], /Skipped malformed reservation record 99/); +}); + +test('history that does not fit in one page fails closed', async () => { + const records = Array.from({ length: 100 }, (_, index) => ({ + id: 200 - index, + task: LEASE_TASK, + environment: 'staging2', + payload: { + version: 2, + kind: 'reservation', + environment: 'staging2', + branch: `b${index}`, + taskId: '', + reservedAt: new Date(T0).toISOString(), + expiresAt: new Date(T0 + 60 * MIN).toISOString(), + }, + })); + await assert.rejects(status(store(records), T0), /does not fit/); +}); + +test('installations are independent', async () => { + const db = store(); + await dispatch(db, 'a', 'deploy', T0); + const other = await runQueue({ + api: db.api, + environment: 'staging', + branch: 'b', + sha, + action: 'deploy', + timing, + now: T0, + }); + assert.equal(other.proceed, true); +}); + +test('the serialized lease job re-decides: a run let through by a stale queue read is still refused', async () => { + const db = store(); + await dispatch(db, 'a', 'acquire', T0); + await dispatch(db, 'b', 'reserve', T0 + MIN); + const expiry = T0 + 30 * MIN; + const request = { + api: db.api, + environment: 'staging2', + sha, + action: 'acquire', + timing, + now: expiry + MIN, + }; + await assert.rejects(runLease({ ...request, branch: 'c' }), /reserved for b/); + await assert.rejects(runLease({ ...request, branch: 'a' }), /reserved for b/); + assert.equal((await runLease({ ...request, branch: 'b' })).holder.branch, 'b'); +}); + +test('a reservation by the branch that takes the slot meanwhile does not queue it behind itself', async () => { + const db = store(); + await runQueue({ + api: db.api, + environment: 'staging2', + branch: 'b', + sha, + action: 'deploy', + timing, + now: T0, + }); + db.hooks.afterList = () => + runQueue({ + api: db.api, + environment: 'staging2', + branch: 'b', + sha, + action: 'reserve', + timing, + now: T0, + }); + await runLease({ + api: db.api, + environment: 'staging2', + branch: 'b', + sha, + action: 'deploy', + timing, + now: T0, + }); + assert.equal(await holder(db, T0 + MIN), 'b'); + assert.deepEqual(await order(db, T0 + MIN), []); +}); diff --git a/scripts/deploy/staging-lease.mjs b/scripts/deploy/staging-lease.mjs index 474cfc329d..c1ab01d157 100644 --- a/scripts/deploy/staging-lease.mjs +++ b/scripts/deploy/staging-lease.mjs @@ -1,9 +1,33 @@ +// Staging verification lease and queue: GitHub I/O and the deploy-staging.yml entry points. +// Decisions are pure functions in staging-lease-queue.mjs. +// +// node scripts/deploy/staging-lease.mjs queue # workflow job `queue`, outside the concurrency group +// node scripts/deploy/staging-lease.mjs lease # workflow job `lease`, serialized per installation +// node scripts/deploy/staging-lease.mjs status # read-only, one gh api call import { execFileSync } from 'node:child_process'; import { appendFileSync } from 'node:fs'; import { pathToFileURL } from 'node:url'; -// Separate from GitHub Actions' ordinary environment deployment records. -export const LEASE_TASK = 'staging-lease'; +import { + LEASE_TASK, + OLD_WORKFLOW_NOTICE, + RECORD_PAGE_SIZE, + applyReservation, + decideLease, + describeTurn, + foldRecords, + hasTurn, + parseRecord, + planQueue, + position, + resolveTurns, +} from './staging-lease-queue.mjs'; + +export { LEASE_TASK }; + +const ACTIONS = ['deploy', 'acquire', 'release', 'reserve']; +const SHA = /^[a-f0-9]{40}$/i; +const iso = (ms) => new Date(ms).toISOString(); function minutes(value, fallback, name, allowZero = false) { const number = Number(value === '' || value === undefined ? fallback : value); @@ -32,63 +56,122 @@ export function leaseTiming(env) { return { hold, deploy }; } -function validUtcExpiry(value) { - if ( - typeof value !== 'string' || - !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?Z$/.test(value) - ) - return false; - const parsed = Date.parse(value); - const canonical = value.length === 20 ? value.replace('Z', '.000Z') : value; - return Number.isFinite(parsed) && new Date(parsed).toISOString() === canonical; +export function queueTiming(env) { + return { + graceMinutes: minutes(env.LEASE_GRACE_MINUTES, 10, 'LEASE_GRACE_MINUTES'), + reservationMinutes: minutes(env.LEASE_RESERVATION_MINUTES, 480, 'LEASE_RESERVATION_MINUTES'), + }; } -export function readLease(record, environment) { - if (record === undefined) return null; // No history: bootstrap a new environment. - let lease = record.payload; - if (typeof lease === 'string') { - try { - lease = JSON.parse(lease); - } catch { - throw new Error('Malformed lease payload'); - } - } - if ( - record.environment !== environment || - record.task !== LEASE_TASK || - lease?.version !== 1 || - lease.environment !== environment || - !['held', 'released'].includes(lease.state) || - typeof lease.branch !== 'string' || - !lease.branch || - !/^[a-f0-9]{40}$/i.test(lease.sha) || - typeof lease.taskId !== 'string' || - !validUtcExpiry(lease.expiresAt) - ) { +function validateRequest({ environment, branch, sha, action, primaryOnlyAudit }) { + if (!environment || environment !== environment.toLowerCase() || /prod/i.test(environment)) + throw new Error('A lowercase, non-production environment is required'); + if (!branch || !SHA.test(sha ?? '')) throw new Error('Branch and full commit SHA are required'); + if (!ACTIONS.includes(action)) throw new Error('Unknown lease action'); + if (action === 'deploy' && primaryOnlyAudit && environment !== 'staging') throw new Error( - 'Malformed lease record; refusing to overwrite live verification. Inspect the latest deployment payload.' + 'Storage activation and agent-email DNS audit support only the staging environment' ); - } - return lease; } -export function decideLease({ lease, branch, now, action }) { - if (!['deploy', 'acquire', 'release'].includes(action)) throw new Error('Unknown lease action'); - if (lease?.state === 'held' && lease.branch !== branch && Date.parse(lease.expiresAt) > now) { - throw new Error( - `Environment ${lease.environment} held by branch ${lease.branch}, SAM task ${lease.taskId || '(not supplied)'}, expires ${lease.expiresAt}. Schedule a wake at expiry; do not poll or ask in chat.` - ); +async function readState(api, environment) { + const query = new URLSearchParams({ + environment, + task: LEASE_TASK, + per_page: String(RECORD_PAGE_SIZE), + }); + return foldRecords(await api('GET', `/deployments?${query}`), environment); +} + +async function createRecord(api, { environment, sha, description, payload }) { + const record = await api('POST', '/deployments', { + ref: sha, + task: LEASE_TASK, + environment, + auto_merge: false, + required_contexts: [], + production_environment: false, + description, + payload, + }); + if (!record?.id) throw new Error('GitHub did not create a lease deployment record'); + return record; +} + +function queueLines(turns) { + if (turns.live.length === 0) return ['Queue: empty.']; + return turns.live.map((entry, index) => `${index + 1}. ${describeTurn(entry)}`); +} + +// Job `queue`: never inside the concurrency group, so nothing it writes can be lost to a cancelled +// pending run. Records the branch's place, then lets the run into the serialized lease job only +// if the branch holds the lease or it is the branch's turn now. +export async function runQueue({ + api, + environment, + branch, + sha, + taskId = '', + action = 'deploy', + primaryOnlyAudit = false, + timing, + now = Date.now(), +}) { + validateRequest({ environment, branch, sha, action, primaryOnlyAudit }); + const { state, warnings } = await readState(api, environment); + const plan = planQueue({ state, branch, action, now, graceMinutes: timing.graceMinutes }); + if (action === 'release') return { proceed: true, warnings, lines: ['Release requested.'] }; + if (plan.holds) { + return { + proceed: action !== 'reserve', + warnings, + lines: [`Branch ${branch} holds ${environment} until ${plan.turns.holder.expiresAt}.`], + }; } - if (action === 'release' && lease?.branch !== branch && lease?.state === 'held') { - throw new Error( - `Only holder branch ${lease.branch} may release this lease (expired leases can be acquired).` - ); + let turns = plan.turns; + if (plan.append) { + const entry = { + branch, + taskId, + reservedAt: iso(now), + expiresAt: iso(now + timing.reservationMinutes * 60_000), + }; + await createRecord(api, { + environment, + sha, + description: `Staging lease reservation: ${branch}`, + payload: { + version: 2, + kind: 'reservation', + environment, + ...entry, + notice: OLD_WORKFLOW_NOTICE, + }, + }); + applyReservation(state, entry); + turns = resolveTurns(state, now, timing.graceMinutes); } - return action === 'release' ? 'released' : 'held'; + const mine = hasTurn(turns, branch); + const where = position(turns, branch); + const lines = [ + turns.holder + ? `Holder: ${turns.holder.branch} (SAM task ${turns.holder.taskId || 'not supplied'}) until ${turns.holder.expiresAt}.` + : 'Holder: none.', + ...queueLines(turns), + mine + ? `It is ${branch}'s turn${action === 'reserve' ? ': run acquire or deploy before it ends' : ''}.` + : `${branch} is number ${where} in the queue (reservation ${plan.append ? 'recorded' : 'already held'}). Schedule a wake for the turn start; do not dispatch again before it.`, + ]; + return { + proceed: action !== 'reserve' && mine, + refused: action !== 'reserve' && !mine, + warnings, + lines, + }; } -// Keep all mutations in the workflow's environment-keyed concurrency group. -// Agents read with gh api; running acquire/release locally would bypass serialization. +// Job `lease`: serialized per installation. Re-reads, decides authoritatively, writes a snapshot +// and reads it back before any deploy or audit job may start. export async function runLease({ api, environment, @@ -100,74 +183,159 @@ export async function runLease({ timing, now = Date.now(), }) { - if (!environment || environment !== environment.toLowerCase() || environment === 'production') - throw new Error('A lowercase, non-production environment is required'); - if (!branch || !/^[a-f0-9]{40}$/i.test(sha)) - throw new Error('Branch and full commit SHA are required'); - if (action === 'deploy' && primaryOnlyAudit && environment !== 'staging') - throw new Error( - 'Storage activation and agent-email DNS audit support only the staging environment' - ); - const query = new URLSearchParams({ environment, task: LEASE_TASK, per_page: '1' }); - const records = await api('GET', `/deployments?${query}`); - if (!Array.isArray(records)) - throw new Error('Unreadable deployment list; refusing lease mutation'); - const lease = readLease(records[0], environment); - const state = decideLease({ lease, branch, now, action }); - const expiresAt = new Date( - now + (state === 'released' ? 0 : timing.deploy + timing.hold) * 60_000 - ).toISOString(); - const payload = { version: 1, environment, state, branch, sha, taskId, expiresAt }; - const record = await api('POST', '/deployments', { - ref: sha, - task: LEASE_TASK, + validateRequest({ environment, branch, sha, action, primaryOnlyAudit }); + if (action === 'reserve') throw new Error('Reservations are made by the queue job'); + const { state, warnings } = await readState(api, environment); + const next = decideLease({ + state, + branch, + taskId, + sha, + action, + now, environment, - auto_merge: false, - required_contexts: [], - production_environment: false, - description: `Verification lease: ${state}`, + graceMinutes: timing.graceMinutes, + holdMinutes: (action === 'deploy' ? timing.deploy : 0) + timing.hold, + }); + if (!next) return { written: false, warnings, message: `Nothing held or queued by ${branch}.` }; + const payload = { + version: 2, + kind: 'snapshot', + environment, + seenThrough: state.seenThrough, + graceMinutes: timing.graceMinutes, + holder: next.holder, + freeSince: next.freeSince, + promisedAt: next.promisedAt, + queue: next.queue, + updatedAt: iso(now), + notice: OLD_WORKFLOW_NOTICE, + }; + const record = await createRecord(api, { + environment, + sha, + description: `Staging lease: ${next.holder ? `held by ${next.holder.branch}` : 'free'}`, payload, }); - if (!record?.id) throw new Error('GitHub did not create a lease deployment record'); - // Re-read with the same token before allowing a deployment to start. - const verified = await api('GET', `/deployments/${record.id}`); - const saved = readLease(verified, environment); - if (Object.entries(payload).some(([key, value]) => saved[key] !== value)) + const saved = parseRecord(await api('GET', `/deployments/${record.id}`), environment); + if ( + saved.type !== 'snapshot' || + JSON.stringify(saved.state.holder) !== JSON.stringify(next.holder) + ) throw new Error('Lease read-back mismatch'); - return { deploymentId: record.id, ...payload }; + const holder = next.holder; + return { + written: true, + deploymentId: record.id, + warnings, + holder, + message: holder + ? `Lease held: environment ${environment}, branch ${holder.branch}, SAM task ${holder.taskId || '(not supplied)'}, SHA ${holder.sha}, expires ${holder.expiresAt}, deployment ${record.id}` + : `Lease released by ${branch}: environment ${environment}, deployment ${record.id}. Queue: ${next.queue.map((entry) => entry.branch).join(', ') || 'empty'}.`, + }; +} + +// Read-only view for agents: one gh api call. +export async function leaseStatus({ api, environment, now = Date.now(), graceMinutes }) { + const query = new URLSearchParams({ + environment, + task: LEASE_TASK, + per_page: String(RECORD_PAGE_SIZE), + }); + const records = await api('GET', `/deployments?${query}`); + const { state, warnings } = foldRecords(records, environment); + const newest = records.find((record) => record.payload?.kind === 'snapshot'); + const grace = graceMinutes ?? newest?.payload?.graceMinutes ?? 10; + const turns = resolveTurns(state, now, grace); + return { + environment, + now: iso(now), + graceMinutes: grace, + holder: turns.holder, + free: !turns.holder && turns.live.length === 0, + queue: turns.live.map((entry, index) => ({ + position: index + 1, + branch: entry.branch, + taskId: entry.taskId, + reservedAt: entry.reservedAt, + reservationExpiresAt: entry.expiresAt, + status: entry.status, + turnStarts: iso(entry.start), + turnEnds: iso(entry.end), + })), + warnings, + }; } function githubApi(method, endpoint, body) { - const args = ['api', '--method', method, `repos/${process.env.GITHUB_REPOSITORY}${endpoint}`]; + const repo = process.env.GITHUB_REPOSITORY || '{owner}/{repo}'; + const args = ['api', '--method', method, `repos/${repo}${endpoint}`]; if (body) args.push('--input', '-'); return JSON.parse( - execFileSync('/usr/bin/gh', args, { + execFileSync(process.env.GITHUB_ACTIONS === 'true' ? '/usr/bin/gh' : 'gh', args, { encoding: 'utf8', input: body ? JSON.stringify(body) : undefined, }) ); } -if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { - try { - if (process.env.GITHUB_ACTIONS !== 'true') - throw new Error('Mutate leases only through deploy-staging.yml (serialized)'); +function report(lines) { + for (const line of lines) console.log(line); + if (process.env.GITHUB_STEP_SUMMARY) + appendFileSync(process.env.GITHUB_STEP_SUMMARY, `${lines.join('\n\n')}\n`); +} + +function workflowRequest() { + if (process.env.GITHUB_ACTIONS !== 'true') + throw new Error('Mutate leases only through deploy-staging.yml'); + return { + api: githubApi, + environment: process.env.LEASE_ENVIRONMENT, + branch: process.env.GITHUB_REF_NAME, + sha: process.env.GITHUB_SHA, + primaryOnlyAudit: process.env.LEASE_PRIMARY_ONLY_AUDIT === 'true', + taskId: process.env.SAM_TASK_ID || '', + action: process.env.LEASE_ACTION || 'deploy', + }; +} + +async function main(command, argument) { + if (command === 'status') { + console.log( + JSON.stringify( + await leaseStatus({ api: githubApi, environment: argument || 'staging' }), + null, + 2 + ) + ); + return; + } + if (command === 'queue') { + const result = await runQueue({ ...workflowRequest(), timing: queueTiming(process.env) }); + report([...result.warnings, ...result.lines]); + if (process.env.GITHUB_OUTPUT) + appendFileSync(process.env.GITHUB_OUTPUT, `proceed=${result.proceed}\n`); + if (result.refused) process.exitCode = 1; + return; + } + if (command === 'lease') { const result = await runLease({ - api: githubApi, - environment: process.env.LEASE_ENVIRONMENT, - branch: process.env.GITHUB_REF_NAME, - sha: process.env.GITHUB_SHA, - primaryOnlyAudit: process.env.LEASE_PRIMARY_ONLY_AUDIT === 'true', - taskId: process.env.SAM_TASK_ID || '', - action: process.env.LEASE_ACTION || 'deploy', - timing: leaseTiming(process.env), + ...workflowRequest(), + timing: { ...leaseTiming(process.env), ...queueTiming(process.env) }, }); - const message = `Lease ${result.state}: environment ${result.environment}, branch ${result.branch}, SAM task ${result.taskId || '(not supplied)'}, SHA ${result.sha}, expires ${result.expiresAt}, deployment ${result.deploymentId}`; - console.log(message); - if (process.env.GITHUB_STEP_SUMMARY) - appendFileSync(process.env.GITHUB_STEP_SUMMARY, `${message}\n`); + report([...result.warnings, result.message]); + return; + } + throw new Error('Usage: staging-lease.mjs queue | lease | status '); +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + try { + await main(process.argv[2], process.argv[3]); } catch (error) { console.error(`Lease refused: ${error.message}`); + if (process.env.GITHUB_STEP_SUMMARY) + appendFileSync(process.env.GITHUB_STEP_SUMMARY, `Lease refused: ${error.message}\n`); process.exitCode = 1; } } diff --git a/scripts/deploy/staging-lease.test.mjs b/scripts/deploy/staging-lease.test.mjs index d094f8fea0..32bcd00f06 100644 --- a/scripts/deploy/staging-lease.test.mjs +++ b/scripts/deploy/staging-lease.test.mjs @@ -1,81 +1,17 @@ +// I/O and validation paths of the lease entry points. Queue behaviour: staging-lease-queue.test.mjs. import test from 'node:test'; import assert from 'node:assert/strict'; -import { decideLease, leaseTiming, readLease, runLease, LEASE_TASK } from './staging-lease.mjs'; + +import { LEASE_TASK, leaseTiming, queueTiming, runLease, runQueue } from './staging-lease.mjs'; +import { validUtc } from './staging-lease-queue.mjs'; const now = Date.parse('2026-11-15T19:00:00Z'); const sha = 'a'.repeat(40); -const held = { - version: 1, - state: 'held', - environment: 'staging', - branch: 'holder', - sha, - taskId: 'task-1', - expiresAt: '2026-11-15T20:00:00Z', -}; -const record = (payload = held) => ({ - id: 1, - task: LEASE_TASK, - environment: held.environment, - payload, -}); -const decide = (lease, branch = 'other', action = 'deploy') => - decideLease({ lease, branch, now, action }); - -test('missing records bootstrap free; active foreign holders fail with owner, task and expiry', () => { - assert.equal(readLease(undefined, 'staging'), null); - assert.equal(decide(null), 'held'); - assert.throws(() => decide(held), /holder, SAM task task-1, expires 2026-11-15T20:00:00Z/); -}); - -test('expired foreign lease (including exact expiry) and same-branch lease permit acquisition', () => { - assert.equal(decide({ ...held, expiresAt: new Date(now).toISOString() }), 'held'); - assert.equal(decide({ ...held, expiresAt: new Date(now - 1).toISOString() }), 'held'); - assert.equal(decide(held, 'holder'), 'held'); - assert.equal(decide({ ...held, state: 'released' }), 'held'); -}); - -test('only holder releases, expiry permits acquisition rather than foreign release', () => { - assert.equal(decide(held, 'holder', 'release'), 'released'); - assert.throws(() => decide(held, 'other', 'release'), /held by branch holder/); - assert.throws( - () => decide({ ...held, expiresAt: new Date(now).toISOString() }, 'other', 'release'), - /Only holder/ - ); -}); +const timing = { deploy: 30, hold: 30, graceMinutes: 10, reservationMinutes: 480 }; +const options = { environment: 'staging', branch: 'holder', sha, taskId: 'task-1', timing, now }; -test('malformed records fail closed, including malformed expired and self-held records', () => { - for (const payload of [ - null, - {}, - '{bad json', - { ...held, expiresAt: 'bad' }, - { ...held, sha: '' }, - { ...held, version: 2 }, - { ...held, environment: 'second' }, - ]) { - assert.throws(() => readLease(record(payload), 'staging'), /Malformed/); - } - assert.deepEqual(readLease(record(JSON.stringify(held)), 'staging'), held); -}); - -test('hold defaults and cap are configurable; unsafe or noninteger durations rejected', () => { - assert.deepEqual(leaseTiming({}), { hold: 30, deploy: 30 }); - assert.deepEqual( - leaseTiming({ - LEASE_DEFAULT_HOLD_MINUTES: '10', - LEASE_MAX_HOLD_MINUTES: '20', - LEASE_EXPECTED_DEPLOY_MINUTES: '0', - }), - { hold: 10, deploy: 0 } - ); - assert.throws(() => leaseTiming({ LEASE_HOLD_MINUTES: '121' }), /exceeds cap/); - for (const value of ['-1', '0', '1.2', 'NaN', 'Infinity']) - assert.throws(() => leaseTiming({ LEASE_HOLD_MINUTES: value }), /integer/); -}); - -function store(initial = []) { - const records = [...initial]; +function store() { + const records = []; const calls = []; return { records, @@ -90,85 +26,81 @@ function store(initial = []) { if (endpoint.startsWith('/deployments?')) { const query = new URLSearchParams(endpoint.split('?')[1]); assert.equal(query.get('task'), LEASE_TASK); - return records - .filter((r) => r.environment === query.get('environment') && r.task === LEASE_TASK) - .slice(0, 1); + return records.filter((r) => r.environment === query.get('environment')); } return records.find((r) => endpoint === `/deployments/${r.id}`); }, }; } -const options = { - environment: 'staging', - branch: 'holder', - sha, - taskId: 'task-1', - timing: { deploy: 30, hold: 30 }, - now, -}; -test('GitHub transport flow acquires, refuses without writing, renews, releases, and takes over expiry', async () => { - const db = store(); - const run = (overrides = {}) => runLease({ ...options, api: db.api, ...overrides }); - const first = await run(); - assert.equal(first.expiresAt, '2026-11-15T20:00:00.000Z'); - assert.equal(db.calls.find((c) => c.method === 'POST').body.auto_merge, false); - assert.deepEqual(db.calls.find((c) => c.method === 'POST').body.required_contexts, []); - const writes = db.records.length; - await assert.rejects(run({ branch: 'other' }), /held by branch holder/); - assert.equal(db.records.length, writes); - const renewed = await run({ now: now + 60_000 }); - assert.equal(renewed.expiresAt, '2026-11-15T20:01:00.000Z'); - await run({ action: 'release', now: now + 120_000 }); - const takeover = await run({ branch: 'other', now: now + 120_001 }); - assert.equal(takeover.branch, 'other'); - const expired = await run({ branch: 'third', now: Date.parse(takeover.expiresAt) }); - assert.equal(expired.branch, 'third'); +test('hold, grace and reservation durations are configurable; unsafe values rejected', () => { + assert.deepEqual(leaseTiming({}), { hold: 30, deploy: 30 }); + assert.deepEqual( + leaseTiming({ + LEASE_DEFAULT_HOLD_MINUTES: '10', + LEASE_MAX_HOLD_MINUTES: '20', + LEASE_EXPECTED_DEPLOY_MINUTES: '0', + }), + { hold: 10, deploy: 0 } + ); + assert.throws(() => leaseTiming({ LEASE_HOLD_MINUTES: '121' }), /exceeds cap/); + for (const value of ['-1', '0', '1.2', 'NaN', 'Infinity']) { + assert.throws(() => leaseTiming({ LEASE_HOLD_MINUTES: value }), /integer/); + assert.throws(() => queueTiming({ LEASE_GRACE_MINUTES: value }), /integer/); + } + assert.deepEqual(queueTiming({}), { graceMinutes: 10, reservationMinutes: 480 }); + assert.deepEqual(queueTiming({ LEASE_GRACE_MINUTES: '5', LEASE_RESERVATION_MINUTES: '60' }), { + graceMinutes: 5, + reservationMinutes: 60, + }); }); -test('environment selection isolates independent slots and ignores ordinary deployments', async () => { - const db = store([{ ...record(), task: 'deploy' }, record()]); - const result = await runLease({ - ...options, - environment: 'staging-second', - branch: 'other', - api: db.api, - }); - assert.equal(result.environment, 'staging-second'); - await assert.rejects( - runLease({ ...options, branch: 'other', api: db.api }), - /held by branch holder/ - ); +test('lease records are plain deployment records the lease job reads back before deploying', async () => { + const db = store(); + await runQueue({ ...options, api: db.api }); + const result = await runLease({ ...options, api: db.api }); + assert.equal(result.holder.expiresAt, '2026-11-15T20:00:00.000Z'); + for (const call of db.calls.filter((c) => c.method === 'POST')) { + assert.equal(call.body.auto_merge, false); + assert.deepEqual(call.body.required_contexts, []); + assert.equal(call.body.production_environment, false); + assert.equal(call.body.ref, sha); + } + assert.ok(db.calls.at(-1).endpoint.startsWith('/deployments/')); + // acquire holds only for the live-check time. + const renewed = await runLease({ ...options, api: db.api, action: 'acquire', now: now + 60_000 }); + assert.equal(renewed.holder.expiresAt, '2026-11-15T19:31:00.000Z'); }); -test('API read/write errors, corrupt history, missing creation id and read-back mismatch block deploy', async () => { - const db = store([record({ ...held, version: 2 })]); - await assert.rejects(runLease({ ...options, api: db.api }), /Malformed/); - assert.equal(db.calls.length, 1); - await assert.rejects( - runLease({ - ...options, - api: async () => { - throw new Error('403'); - }, - }), - /403/ - ); +test('API errors, unreadable lists, missing creation id and read-back mismatch block the deploy', async () => { + const failing = async () => { + throw new Error('403'); + }; + await assert.rejects(runQueue({ ...options, api: failing }), /403/); + await assert.rejects(runLease({ ...options, api: failing }), /403/); for (const response of [null, {}]) { await assert.rejects(runLease({ ...options, api: async () => response }), /Unreadable/); + await assert.rejects(runQueue({ ...options, api: async () => response }), /Unreadable/); } await assert.rejects( runLease({ ...options, api: async (m) => (m === 'GET' ? [] : {}) }), /did not create/ ); + await assert.rejects( + runQueue({ ...options, api: async (m) => (m === 'GET' ? [] : {}) }), + /did not create/ + ); const bad = store(); await assert.rejects( runLease({ ...options, api: async (...args) => { const value = await bad.api(...args); - return args[1].includes('/deployments/') - ? { ...value, payload: { ...value.payload, branch: 'wrong' } } + return args[1].startsWith('/deployments/') + ? { + ...value, + payload: { ...value.payload, holder: { ...value.payload.holder, branch: 'wrong' } }, + } : value; }, }), @@ -176,56 +108,59 @@ test('API read/write errors, corrupt history, missing creation id and read-back ); }); -test('production aliases and inconsistent environment casing fail before API access', async () => { - for (const environment of ['production', 'Production', 'PRODUCTION', 'Staging', '']) { +test('production in any spelling, inconsistent casing and unknown actions fail before API access', async () => { + const noApi = async () => assert.fail('no API access'); + for (const environment of ['production', 'Production', 'prod', 'staging-prod', 'Staging', '']) { await assert.rejects( - runLease({ ...options, environment, api: async () => assert.fail('no API access') }), + runQueue({ ...options, environment, api: noApi }), + /lowercase, non-production/ + ); + await assert.rejects( + runLease({ ...options, environment, api: noApi }), /lowercase, non-production/ ); } + await assert.rejects( + runQueue({ ...options, action: 'steal', api: noApi }), + /Unknown lease action/ + ); + await assert.rejects(runLease({ ...options, action: 'reserve', api: noApi }), /queue job/); + await assert.rejects(runQueue({ ...options, sha: 'abc', api: noApi }), /full commit SHA/); }); -test('incomplete or impossible UTC expiry dates fail closed', () => { - for (const expiresAt of [ +test('incomplete or impossible UTC dates are invalid', () => { + for (const value of [ '2026', - '2026-11', '2026-11-15', '2026-11-15T19:00:00', '2026-02-30T19:00:00Z', '2026-02-29T19:00:00.000Z', '2026-11-15T24:00:00Z', - '2026-13-01T19:00:00Z', - ]) { - assert.throws(() => readLease(record({ ...held, expiresAt }), 'staging'), /Malformed/); - } - assert.equal( - readLease(record({ ...held, expiresAt: '2028-02-29T19:00:00Z' }), 'staging').state, - 'held' - ); + ]) + assert.equal(validUtc(value), false, value); + assert.equal(validUtc('2028-02-29T19:00:00Z'), true); }); -test('unsupported legacy audits reject before acquiring a secondary slot', async () => { - await assert.rejects( - runLease({ - ...options, - environment: 'staging-second', - primaryOnlyAudit: true, - api: async () => assert.fail('no lease mutation'), - }), - /support only the staging environment/ - ); +test('primary-only audits are refused on a secondary installation before any record is written', async () => { + const noApi = async () => assert.fail('no lease mutation'); + for (const run of [runQueue, runLease]) { + await assert.rejects( + run({ ...options, environment: 'staging2', primaryOnlyAudit: true, api: noApi }), + /support only the staging environment/ + ); + } const db = store(); - assert.equal((await runLease({ ...options, primaryOnlyAudit: true, api: db.api })).state, 'held'); + assert.equal((await runQueue({ ...options, primaryOnlyAudit: true, api: db.api })).proceed, true); assert.equal( ( - await runLease({ + await runQueue({ ...options, - environment: 'staging-second', + environment: 'staging2', primaryOnlyAudit: true, action: 'acquire', api: db.api, }) - ).state, - 'held' + ).proceed, + true ); }); diff --git a/scripts/quality/deploy-staging-permissions.test.ts b/scripts/quality/deploy-staging-permissions.test.ts index b6c70e19c4..7f4a49bc13 100644 --- a/scripts/quality/deploy-staging-permissions.test.ts +++ b/scripts/quality/deploy-staging-permissions.test.ts @@ -31,6 +31,9 @@ const PR_WRITE_CONSUMERS = [ /\b(?:pull-request-comment|comment-on-pr)\b/i, ] as const; +// The two jobs that read and write lease records; nothing else receives a GitHub token. +const LEASE_JOBS = ['queue', 'lease']; + type PermissionMap = Record; type YamlRecord = Record; @@ -109,14 +112,14 @@ function stagingPermissionContractErrors(staging: string, reusable: string): str const stagingJobs = asRecord(stagingConfig?.jobs) || {}; for (const [name, job] of Object.entries(stagingJobs)) { const permissions = permissionMap(asRecord(job)?.permissions); - if (name === 'lease') { + if (LEASE_JOBS.includes(name)) { if ( !isExactPermissionMap(permissions, { ...REQUIRED_STAGING_PERMISSIONS, deployments: 'write', }) ) { - errors.push('lease job must have only deployment write and checkout read authority'); + errors.push(`${name} job must have only deployment write and checkout read authority`); } } else if (Object.hasOwn(asRecord(job) || {}, 'permissions')) { errors.push('nested or reusable permission overrides are forbidden'); @@ -124,7 +127,7 @@ function stagingPermissionContractErrors(staging: string, reusable: string): str if (permissions && 'pull-requests' in permissions) errors.push(`unexpected permission grant: pull-requests: ${permissions['pull-requests']}`); } - // Only the serialized lease job receives a GitHub token. The reusable + // Only the queue and serialized lease jobs receive a GitHub token. The reusable // deployment and all audit jobs retain the root read-only permissions. const permissionValues = [stagingConfig?.permissions, ...nestedPermissionValues]; for (const value of permissionValues) { @@ -147,7 +150,15 @@ function stagingPermissionContractErrors(staging: string, reusable: string): str } } - const combinedWorkflows = `${staging.replace(block(staging, /^ {2}lease:\s*$/m, /^ {2}[a-zA-Z0-9_-]+:\s*$/m), '')}\n${reusable}`; + const withoutLeaseJobs = LEASE_JOBS.reduce( + (workflow, name) => + workflow.replace( + block(workflow, new RegExp(`^ {2}${name}:\\s*$`, 'm'), /^ {2}[a-zA-Z0-9_-]+:\s*$/m), + '' + ), + staging + ); + const combinedWorkflows = `${withoutLeaseJobs}\n${reusable}`; for (const consumer of PR_WRITE_CONSUMERS) { if (consumer.test(combinedWorkflows)) { errors.push(`pull-request write consumer is present: ${consumer.source}`); @@ -302,29 +313,65 @@ describe('staging deployment permission contract', () => { }); describe('lease workflow gating', () => { - it('serializes acquire, deploy and release per environment, and gates all consumers', () => { + it('records places outside any group, serializes lease writes, and gates all consumers', () => { const workflow = parse(stagingWorkflow); - expect(workflow.concurrency.group).toBe("deploy-${{ inputs.environment || 'staging' }}"); - expect(workflow.concurrency['cancel-in-progress']).toBe(false); - expect(workflow.jobs.lease.permissions.deployments).toBe('write'); + // A workflow-level group keeps one pending run and cancels the previous one: places were lost. + expect(workflow.concurrency).toBeUndefined(); + expect(workflow.jobs.queue.concurrency).toBeUndefined(); + expect(workflow.jobs.queue.needs).toBeUndefined(); + expect(workflow.jobs.lease.needs).toBe('queue'); + expect(workflow.jobs.lease.if).toBe("${{ needs.queue.outputs.proceed == 'true' }}"); + // Same group name as older workflow copies, so transition writes serialize with them. + expect(workflow.jobs.lease.concurrency).toEqual({ + group: "deploy-${{ inputs.environment || 'staging' }}", + 'cancel-in-progress': false, + }); + for (const name of LEASE_JOBS) + expect(workflow.jobs[name].permissions.deployments).toBe('write'); + for (const name of ['deploy', 'storage-activation', 'agent-email-dns-audit']) + expect(workflow.jobs[name].concurrency).toEqual({ + group: "staging-apply-${{ inputs.environment || 'staging' }}", + 'cancel-in-progress': false, + }); for (const [name, job] of Object.entries(workflow.jobs) as [ string, Record, ][]) { - if (name === 'lease') continue; + if (LEASE_JOBS.includes(name)) continue; expect([job.needs].flat()).toContain('lease'); expect(job.if).toContain('inputs.lease_action'); if (String(job.if).includes('always()')) expect(job.if).toContain("needs.lease.result == 'success'"); } }); + + it('runs the queue phase then the lease phase with identical lease inputs', () => { + const workflow = parse(stagingWorkflow); + const step = (job: string, run: string) => + workflow.jobs[job].steps.find((candidate: { run?: string }) => candidate.run === run); + const queue = step('queue', 'node scripts/deploy/staging-lease.mjs queue'); + const lease = step('lease', 'node scripts/deploy/staging-lease.mjs lease'); + expect(queue.id).toBe('queue'); + expect(lease.env).toEqual(queue.env); + expect(workflow.jobs.queue.outputs.proceed).toBe('${{ steps.queue.outputs.proceed }}'); + expect(workflow.on.workflow_dispatch.inputs.lease_action.options).toEqual([ + 'deploy', + 'reserve', + 'acquire', + 'release', + ]); + }); }); it('executes the lease lifecycle and failure-path tests in CI', () => { expect(() => execFileSync( process.execPath, - ['--test', fileURLToPath(new URL('../deploy/staging-lease.test.mjs', import.meta.url))], + [ + '--test', + fileURLToPath(new URL('../deploy/staging-lease.test.mjs', import.meta.url)), + fileURLToPath(new URL('../deploy/staging-lease-queue.test.mjs', import.meta.url)), + ], { stdio: 'pipe' } ) ).not.toThrow(); @@ -342,8 +389,8 @@ describe('job-level broad permission overrides', () => { }); it('wires the legacy audit compatibility check into the lease preflight', () => { const workflow = parse(stagingWorkflow); - const leaseStep = workflow.jobs.lease.steps.find( - (step: { run?: string }) => step.run === 'node scripts/deploy/staging-lease.mjs' + const leaseStep = workflow.jobs.queue.steps.find( + (step: { run?: string }) => step.run === 'node scripts/deploy/staging-lease.mjs queue' ); expect(leaseStep.env.LEASE_PRIMARY_ONLY_AUDIT).toBe( '${{ inputs.activation_only || inputs.agent_email_dns_audit || inputs.github_trigger_audit }}' @@ -352,11 +399,13 @@ describe('job-level broad permission overrides', () => { }); describe('installation targeting', () => { - it('runs the lease job in the staging Environment with no secrets, validating the target first', () => { + it('runs the lease jobs in the staging Environment with no secrets, validating the target first', () => { const workflow = parse(stagingWorkflow); - expect(workflow.jobs.lease.environment).toBe('staging'); - expect(JSON.stringify(workflow.jobs.lease)).not.toContain('secrets.'); - expect(workflow.jobs.lease.steps[1].run).toBe( + for (const name of LEASE_JOBS) { + expect(workflow.jobs[name].environment).toBe('staging'); + expect(JSON.stringify(workflow.jobs[name])).not.toContain('secrets.'); + } + expect(workflow.jobs.queue.steps[1].run).toBe( 'node scripts/deploy/staging-installations.mjs workflow-target' ); }); @@ -369,8 +418,8 @@ describe('installation targeting', () => { '${{ needs.lease.outputs.credential_environment }}' ); } - const lease = workflow.jobs.lease.steps.find( - (step: { run?: string }) => step.run === 'node scripts/deploy/staging-lease.mjs' + const lease = workflow.jobs.queue.steps.find( + (step: { run?: string }) => step.run === 'node scripts/deploy/staging-lease.mjs queue' ); expect(lease.env.LEASE_PRIMARY_ONLY_AUDIT).toContain('inputs.github_trigger_audit'); }); diff --git a/tasks/active/2026-11-16-staging-lease-fair-queue.md b/tasks/active/2026-11-16-staging-lease-fair-queue.md index 01f428b7df..bca0186b16 100644 --- a/tasks/active/2026-11-16-staging-lease-fair-queue.md +++ b/tasks/active/2026-11-16-staging-lease-fair-queue.md @@ -63,14 +63,14 @@ First night of use (idea notes, 2026-11-16): ## Checklist — Part 1 (PR 1) -- [ ] Pure queue state + decision module with tests (empty queue, two waiters in order, head misses +- [x] Pure queue state + decision module with tests (empty queue, two waiters in order, head misses grace, holder re-queues behind waiters, reservation expiry, concurrent reservations, legacy record, malformed records, early release keeps head's turn) -- [ ] `staging-lease.mjs`: `queue` and `lease` phases, `status` command -- [ ] Workflow: `reserve` action, `queue` job outside group, `lease` job group, apply group; grace +- [x] `staging-lease.mjs`: `queue` and `lease` phases, `status` command +- [x] Workflow: `reserve` action, `queue` job outside group, `lease` job group, apply group; grace and reservation TTL vars -- [ ] Permissions/gating test updated -- [ ] Docs: `.claude/commands/do.md`, `.agents/skills/do/SKILL.md`, `.claude/rules/13-staging-verification.md`, +- [x] Permissions/gating test updated +- [x] Docs: `.claude/commands/do.md`, `.agents/skills/do/SKILL.md`, `.claude/rules/13-staging-verification.md`, `.agent-instructions/reference/rules/13-staging-verification-full.md` - [ ] Live proof on staging2 with two branches (reserve/acquire/release, no full deploys) - [ ] Note on idea, channel `feature.ship-faster` From 1ffe8f840f22354bfa09e52f5f7c55fd90c9c3d7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Mon, 16 Nov 2026 09:32:28 +0000 Subject: [PATCH 3/9] fix(staging): address lease queue review findings - An expired holder's reservation is no longer dropped, so it can take the slot again or queue behind waiters. - A release enters the serialized group only when the branch holds the lease or is queued, and the lease job uses its own group (staging-lease-), so stray releases and older workflow copies cannot displace an entitled pending run. - The lease job honours the turn the queue job saw (bounded to three grace periods), so a runner or group wait cannot cost the head its turn. - History is read across up to five pages before failing closed. - status parses string payloads for the recorded grace period. - Docs: release only after your own deploy run finished. Co-Authored-By: Claude Opus 5.5 --- .../rules/13-staging-verification-full.md | 5 +- .claude/commands/do.md | 5 +- .github/workflows/deploy-staging.yml | 16 +- scripts/deploy/staging-lease-queue.mjs | 50 +++++- scripts/deploy/staging-lease-queue.test.mjs | 149 ++++++++++++++++-- scripts/deploy/staging-lease.mjs | 79 +++++++--- scripts/deploy/staging-lease.test.mjs | 1 + .../deploy-staging-permissions.test.ts | 10 +- .../2026-11-16-staging-lease-fair-queue.md | 10 +- 9 files changed, 275 insertions(+), 50 deletions(-) diff --git a/.agent-instructions/reference/rules/13-staging-verification-full.md b/.agent-instructions/reference/rules/13-staging-verification-full.md index 26659f427d..e2546496a8 100644 --- a/.agent-instructions/reference/rules/13-staging-verification-full.md +++ b/.agent-instructions/reference/rules/13-staging-verification-full.md @@ -167,7 +167,10 @@ Staging deployment is **manual** — it does NOT run automatically on PRs. You m the slot again queues behind everyone already waiting. **If you release early, message the next task in the queue** (`send_durable_message` to its SAM task ID from `status`) so it can take its turn before its scheduled wake. Successful - deployment completion is not a release. + deployment completion is not a release. Release only after your own deploy run + has finished: the next holder's deploy waits for an in-flight one in the + `staging-apply-` group, but your live checks are no longer + protected once you release. Records are GitHub deployments with task `staging-lease`, keyed by installation. A malformed snapshot or an unknown record version fails closed (no one can diff --git a/.claude/commands/do.md b/.claude/commands/do.md index 31863d8b68..8e30f2a931 100644 --- a/.claude/commands/do.md +++ b/.claude/commands/do.md @@ -281,7 +281,10 @@ If this PR includes **any code changes** (not just docs/tasks), deploy to stagin the slot again queues behind everyone already waiting. **If you release early, message the next task in the queue** (`send_durable_message` to its SAM task ID from `status`) so it can take its turn before its scheduled wake. Successful - deployment completion is not a release. + deployment completion is not a release. Release only after your own deploy run + has finished: the next holder's deploy waits for an in-flight one in the + `staging-apply-` group, but your live checks are no longer + protected once you release. Records are GitHub deployments with task `staging-lease`, keyed by installation. A malformed snapshot or an unknown record version fails closed (no one can diff --git a/.github/workflows/deploy-staging.yml b/.github/workflows/deploy-staging.yml index d842f73a1b..d14aea45f7 100644 --- a/.github/workflows/deploy-staging.yml +++ b/.github/workflows/deploy-staging.yml @@ -80,9 +80,10 @@ on: # No workflow-level concurrency group: GitHub keeps one pending run per group and cancels the # previous pending run, which silently lost waiting agents their place. The `queue` job records -# places outside any group; only runs whose turn it is enter the serialized `lease` job -# (group deploy-, the name older workflow copies also use), and mutating jobs share -# staging-apply-. See scripts/deploy/staging-lease-queue.mjs. +# places outside any group; only runs that hold the lease, have their turn, or have something to +# release enter the serialized `lease` job (group staging-lease-; deliberately not +# the deploy- name older workflow copies use, so their runs cannot displace an +# entitled pending run), and mutating jobs share staging-apply-. See scripts/deploy/staging-lease-queue.mjs. env: PLAYWRIGHT_VERSION: 1.59.1 @@ -109,6 +110,7 @@ jobs: id-token: none outputs: proceed: ${{ steps.queue.outputs.proceed }} + checked_at: ${{ steps.queue.outputs.checked_at }} credential_environment: ${{ steps.target.outputs.credential_environment }} installation: ${{ steps.target.outputs.installation }} base_domain: ${{ steps.target.outputs.base_domain }} @@ -140,8 +142,9 @@ jobs: LEASE_EXPECTED_DEPLOY_MINUTES: ${{ inputs.lease_action == 'acquire' && '0' || vars.STAGING_LEASE_EXPECTED_DEPLOY_MINUTES || '30' }} run: node scripts/deploy/staging-lease.mjs queue - # Serialized per installation. Only runs that hold the lease or whose turn it is get here, so a - # pending run in this group can only be displaced by another run of the same entitled branch. + # Serialized per installation. Only runs that hold the lease, have their turn, or have something + # to release get here, so a pending run in this group can only be displaced by another run of a + # branch that is itself the holder or in the queue. lease: needs: queue if: ${{ needs.queue.outputs.proceed == 'true' }} @@ -149,7 +152,7 @@ jobs: environment: staging timeout-minutes: 2 concurrency: - group: deploy-${{ inputs.environment || 'staging' }} + group: staging-lease-${{ inputs.environment || 'staging' }} cancel-in-progress: false permissions: contents: read @@ -163,6 +166,7 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Acquire, renew or release the verification lease env: + LEASE_TURN_CHECKED_AT: ${{ needs.queue.outputs.checked_at }} GH_TOKEN: ${{ github.token }} LEASE_ENVIRONMENT: ${{ inputs.environment || 'staging' }} LEASE_ACTION: ${{ inputs.lease_action || 'deploy' }} diff --git a/scripts/deploy/staging-lease-queue.mjs b/scripts/deploy/staging-lease-queue.mjs index b686406095..7e8c1e4e6c 100644 --- a/scripts/deploy/staging-lease-queue.mjs +++ b/scripts/deploy/staging-lease-queue.mjs @@ -13,6 +13,9 @@ export const LEASE_TASK = 'staging-lease'; export const RECORD_PAGE_SIZE = 100; +// Pages read before giving up. Only reservations accumulate between snapshots, so 500 records +// is far beyond any realistic queue; past it every call fails closed. +export const RECORD_MAX_PAGES = 5; export const OLD_WORKFLOW_NOTICE = 'Staging lease queue (version 2). Update this branch from origin/main to reserve, deploy or release; workflow copies from before the queue refuse this record by design.'; @@ -149,7 +152,13 @@ function baseState(parsed) { // A reservation by a branch already queued keeps its place and extends its expiry. It also records // when it was made, so a branch that missed its turn and reserves again rejoins at the back. export function applyReservation(state, entry) { - if (state.holder?.branch === entry.branch) return; + // Only a live hold makes the reservation redundant; a holder whose lease ran out queues again. + const holder = state.holder; + if ( + holder?.branch === entry.branch && + Date.parse(holder.expiresAt) > Date.parse(entry.reservedAt) + ) + return; const existing = state.queue.find((queued) => queued.branch === entry.branch); if (!existing) { state.queue.push({ ...entry }); @@ -162,13 +171,20 @@ export function applyReservation(state, entry) { if (entry.taskId) existing.taskId = entry.taskId; } -// records: newest first, as GitHub lists deployments. -export function foldRecords(records, environment, pageSize = RECORD_PAGE_SIZE) { +// records: newest first, as GitHub lists deployments. `complete` is true when they are the whole +// history. Throws an error with `incomplete: true` when more history is needed. +// +// Known limit: a reservation becomes visible to everyone at once in id order is assumed. If +// GitHub listed a newer record before an older one created within the same milliseconds, a +// snapshot's seenThrough could pass the older one before it was visible, and it would be skipped. +// The lease job lists seconds after its own queue job wrote, which bounds this to reservations +// created in the instant the lease job reads; the affected agent sees itself missing in `status`. +export function foldRecords(records, environment, complete = false) { if (!Array.isArray(records)) throw new Error('Unreadable deployment list; refusing lease change'); const events = []; const warnings = []; let base = null; - let covered = records.length < pageSize; // a short page is the whole history + let covered = complete; for (const record of records) { const parsed = parseRecord(record, environment); if (base) { @@ -178,6 +194,7 @@ export function foldRecords(records, environment, pageSize = RECORD_PAGE_SIZE) { } // Older than the snapshot but unseen by it: a reservation made while it was being written. if (parsed.type === 'reservation' || parsed.type === 'invalid') events.push(parsed); + else warnings.push(`Ignored lease record ${parsed.id} written while snapshot ${base.id} was`); continue; } if (parsed.type === 'reservation' || parsed.type === 'invalid') { @@ -190,10 +207,13 @@ export function foldRecords(records, environment, pageSize = RECORD_PAGE_SIZE) { break; } } - if (!covered) - throw new Error( - `Lease history does not fit in the newest ${pageSize} records; refusing lease change` + if (!covered) { + const error = new Error( + `Lease history does not fit in the newest ${records.length} records; refusing lease change` ); + error.incomplete = true; + throw error; + } const state = base ? base.state : baseState(null); for (const event of events.sort((a, b) => a.id - b.id)) { if (event.id <= state.seenThrough) continue; @@ -285,6 +305,15 @@ function freeSnapshot(turns, keep, now) { }; } +// The queue job saw the branch's turn at `checkedAt` and let the run through; waiting for a runner +// or for the concurrency group must not cost it the turn. Bounded to a few grace periods back. +function hadTurn(state, branch, checkedAt, now, graceMinutes) { + const checked = checkedAt ? Date.parse(checkedAt) : NaN; + if (!Number.isFinite(checked) || checked > now || checked < now - 3 * graceMinutes * MINUTE) + return false; + return hasTurn(resolveTurns(state, checked, graceMinutes), branch); +} + export function hasTurn(turns, branch) { return !turns.holder && turns.live[0]?.branch === branch && turns.live[0].status === 'turn'; } @@ -329,6 +358,7 @@ export function decideLease({ graceMinutes, holdMinutes, environment, + turnCheckedAt = null, }) { if (!['deploy', 'acquire', 'release'].includes(action)) throw new Error('Unknown lease action'); const turns = resolveTurns(state, now, graceMinutes); @@ -359,7 +389,11 @@ export function decideLease({ holder: { ...turns.holder, sha, taskId: taskId || turns.holder.taskId, expiresAt }, }; } - if (turns.live.length > 0 && !hasTurn(turns, branch)) + if ( + turns.live.length > 0 && + !hasTurn(turns, branch) && + !hadTurn(state, branch, turnCheckedAt, now, graceMinutes) + ) throw new Error(refusal(turns, branch, environment)); return { holder: { branch, taskId, sha, acquiredAt: iso(now), expiresAt }, diff --git a/scripts/deploy/staging-lease-queue.test.mjs b/scripts/deploy/staging-lease-queue.test.mjs index 8c78636e5b..0d4eb03a4e 100644 --- a/scripts/deploy/staging-lease-queue.test.mjs +++ b/scripts/deploy/staging-lease-queue.test.mjs @@ -25,7 +25,10 @@ function store(initial = []) { assert.equal(query.get('task'), LEASE_TASK); const list = records .filter((r) => r.environment === query.get('environment') && r.task === LEASE_TASK) - .slice(0, Number(query.get('per_page'))) + .slice( + (Number(query.get('page') ?? 1) - 1) * Number(query.get('per_page')), + Number(query.get('page') ?? 1) * Number(query.get('per_page')) + ) .map((r) => structuredClone(r)); const hook = hooks.afterList; hooks.afterList = null; @@ -154,16 +157,26 @@ test('the branch whose turn it is can leave the queue, and the next one may star const view = await status(db, expiry + 2 * MIN); assert.equal(view.queue[0].status, 'turn'); assert.equal(view.queue[0].turnEnds, new Date(expiry + 20 * MIN).toISOString()); - // A releasing branch that holds nothing writes nothing. + // A releasing branch that holds nothing writes nothing and never reaches the lease job. const before = db.records.length; - assert.equal((await dispatch(db, 'z', 'release', expiry + 3 * MIN)).lease.written, false); + const none = await dispatch(db, 'z', 'release', expiry + 3 * MIN); + assert.equal(none.queued.proceed, false); assert.equal(db.records.length, before); - // Someone else's lease cannot be released. + // Someone else's lease cannot be released, even by calling the lease job directly. await dispatch(db, 'c', 'acquire', expiry + 3 * MIN); - assert.match( - (await dispatch(db, 'z', 'release', expiry + 4 * MIN)).error, + await assert.rejects( + runLease({ + api: db.api, + environment: 'staging2', + branch: 'z', + sha, + action: 'release', + timing, + now: expiry + 4 * MIN, + }), /Only holder branch c/ ); + assert.equal(await holder(db, expiry + 5 * MIN), 'c'); }); test('stale reservations expire and take no turn', async () => { @@ -298,9 +311,27 @@ test('malformed records: snapshots and unknown versions fail closed, bad reserva assert.match(view.warnings[0], /Skipped malformed reservation record 99/); }); -test('history that does not fit in one page fails closed', async () => { - const records = Array.from({ length: 100 }, (_, index) => ({ - id: 200 - index, +test('history beyond the page limit fails closed; a second page is read when needed', async () => { + const reservation = (id, branch) => ({ + id, + task: LEASE_TASK, + environment: 'staging2', + payload: { + version: 2, + kind: 'reservation', + environment: 'staging2', + branch, + taskId: '', + reservedAt: new Date(T0).toISOString(), + expiresAt: new Date(T0 + 60 * MIN).toISOString(), + }, + }); + const twoPages = Array.from({ length: 150 }, (_, index) => + reservation(1000 - index, `b${index % 3}`) + ); + assert.deepEqual(await order(store(twoPages), T0), ['b2', 'b1', 'b0']); + const records = Array.from({ length: 501 }, (_, index) => ({ + id: 2000 - index, task: LEASE_TASK, environment: 'staging2', payload: { @@ -313,7 +344,7 @@ test('history that does not fit in one page fails closed', async () => { expiresAt: new Date(T0 + 60 * MIN).toISOString(), }, })); - await assert.rejects(status(store(records), T0), /does not fit/); + await assert.rejects(status(store(records), T0), /does not fit in the newest 500/); }); test('installations are independent', async () => { @@ -382,3 +413,101 @@ test('a reservation by the branch that takes the slot meanwhile does not queue i assert.equal(await holder(db, T0 + MIN), 'b'); assert.deepEqual(await order(db, T0 + MIN), []); }); + +test('status reads the grace period the newest snapshot recorded, with one API call', async () => { + const db = store(); + const short = { ...timing, graceMinutes: 3 }; + await dispatch(db, 'a', 'acquire', T0, { timing: short }); + await dispatch(db, 'b', 'reserve', T0 + MIN, { timing: short }); + let calls = 0; + const counted = async (...args) => { + calls += 1; + return db.api(...args); + }; + const view = await leaseStatus({ api: counted, environment: 'staging2', now: T0 + 2 * MIN }); + assert.equal(calls, 1); + assert.equal(view.graceMinutes, 3); + assert.equal(view.holder.branch, 'a'); + assert.equal(view.queue[0].turnStarts, new Date(T0 + 30 * MIN).toISOString()); + assert.equal(view.queue[0].turnEnds, new Date(T0 + 33 * MIN).toISOString()); +}); + +test('a holder whose lease ran out can take the slot again, or queues behind waiters', async () => { + const db = store(); + await dispatch(db, 'a', 'acquire', T0); // expires T0+30 + const again = await dispatch(db, 'a', 'deploy', T0 + 31 * MIN); + assert.equal(again.lease?.holder.branch, 'a', again.queued.lines.join(' ')); + const db2 = store(); + await dispatch(db2, 'a', 'acquire', T0); + await dispatch(db2, 'b', 'reserve', T0 + MIN); + assert.equal((await dispatch(db2, 'a', 'deploy', T0 + 31 * MIN)).refused, true); + assert.deepEqual(await order(db2, T0 + 31 * MIN), ['b', 'a']); + await dispatch(db2, 'b', 'acquire', T0 + 32 * MIN); + assert.deepEqual(await order(db2, T0 + 33 * MIN), ['a']); +}); + +test('a release from a branch with nothing to release never enters the serialized group', async () => { + const db = store(); + await dispatch(db, 'a', 'deploy', T0); + const stray = await runQueue({ + api: db.api, + environment: 'staging2', + branch: 'z', + sha, + action: 'release', + timing, + now: T0 + MIN, + }); + assert.equal(stray.proceed, false); + assert.equal(stray.refused, undefined); + const holderRelease = await runQueue({ + api: db.api, + environment: 'staging2', + branch: 'a', + sha, + action: 'release', + timing, + now: T0 + MIN, + }); + assert.equal(holderRelease.proceed, true); + await dispatch(db, 'q', 'reserve', T0 + MIN); + const leave = await runQueue({ + api: db.api, + environment: 'staging2', + branch: 'q', + sha, + action: 'release', + timing, + now: T0 + 2 * MIN, + }); + assert.equal(leave.proceed, true); +}); + +test('a lease job delayed past the turn keeps the turn the queue job saw, within a bound', async () => { + const db = store(); + await dispatch(db, 'a', 'acquire', T0); // expires T0+30 + for (const branch of ['b', 'c', 'd', 'e', 'f']) await dispatch(db, branch, 'reserve', T0 + MIN); + // Turns: b [30,40) c [40,50) d [50,60) e [60,70) f [70,80). + const request = { api: db.api, environment: 'staging2', sha, action: 'acquire', timing }; + const checked = new Date(T0 + 39 * MIN).toISOString(); + // A check that did not see the branch's turn cannot help it. + await assert.rejects( + runLease({ ...request, branch: 'c', now: T0 + 39 * MIN, turnCheckedAt: checked }), + /reserved for b/ + ); + // Older than three grace periods: ignored. + await assert.rejects( + runLease({ ...request, branch: 'b', now: T0 + 71 * MIN, turnCheckedAt: checked }), + /reserved for f/ + ); + // Without the check B is refused at T0+43; with it, B keeps the turn it was let through on. + await assert.rejects(runLease({ ...request, branch: 'b', now: T0 + 43 * MIN }), /reserved for c/); + const granted = await runLease({ + ...request, + branch: 'b', + now: T0 + 43 * MIN, + turnCheckedAt: checked, + }); + assert.equal(granted.holder.branch, 'b'); + assert.deepEqual(await order(db, T0 + 44 * MIN), ['c', 'd', 'e', 'f']); +}); diff --git a/scripts/deploy/staging-lease.mjs b/scripts/deploy/staging-lease.mjs index c1ab01d157..28dd025cd3 100644 --- a/scripts/deploy/staging-lease.mjs +++ b/scripts/deploy/staging-lease.mjs @@ -11,6 +11,7 @@ import { pathToFileURL } from 'node:url'; import { LEASE_TASK, OLD_WORKFLOW_NOTICE, + RECORD_MAX_PAGES, RECORD_PAGE_SIZE, applyReservation, decideLease, @@ -74,13 +75,31 @@ function validateRequest({ environment, branch, sha, action, primaryOnlyAudit }) ); } +// Reads newest-first pages until the state is covered: one gh api call in the normal case. +async function readRecords(api, environment) { + const records = []; + for (let page = 1; ; page += 1) { + const query = new URLSearchParams({ + environment, + task: LEASE_TASK, + per_page: String(RECORD_PAGE_SIZE), + page: String(page), + }); + const batch = await api('GET', `/deployments?${query}`); + if (!Array.isArray(batch)) throw new Error('Unreadable deployment list; refusing lease change'); + records.push(...batch); + const complete = batch.length < RECORD_PAGE_SIZE; + try { + return { records, ...foldRecords(records, environment, complete) }; + } catch (error) { + if (!error.incomplete || complete || page >= RECORD_MAX_PAGES) throw error; + } + } +} + async function readState(api, environment) { - const query = new URLSearchParams({ - environment, - task: LEASE_TASK, - per_page: String(RECORD_PAGE_SIZE), - }); - return foldRecords(await api('GET', `/deployments?${query}`), environment); + const { state, warnings } = await readRecords(api, environment); + return { state, warnings }; } async function createRecord(api, { environment, sha, description, payload }) { @@ -120,7 +139,18 @@ export async function runQueue({ validateRequest({ environment, branch, sha, action, primaryOnlyAudit }); const { state, warnings } = await readState(api, environment); const plan = planQueue({ state, branch, action, now, graceMinutes: timing.graceMinutes }); - if (action === 'release') return { proceed: true, warnings, lines: ['Release requested.'] }; + if (action === 'release') { + // Only a branch with something to release enters the serialized group, so a stray release + // cannot displace an entitled run waiting there. + const has = plan.holds || state.queue.some((entry) => entry.branch === branch); + return { + proceed: has, + warnings, + lines: [ + has ? 'Release requested.' : `Nothing held or queued by ${branch}; nothing to release.`, + ], + }; + } if (plan.holds) { return { proceed: action !== 'reserve', @@ -182,6 +212,7 @@ export async function runLease({ primaryOnlyAudit = false, timing, now = Date.now(), + turnCheckedAt = null, }) { validateRequest({ environment, branch, sha, action, primaryOnlyAudit }); if (action === 'reserve') throw new Error('Reservations are made by the queue job'); @@ -196,6 +227,7 @@ export async function runLease({ environment, graceMinutes: timing.graceMinutes, holdMinutes: (action === 'deploy' ? timing.deploy : 0) + timing.hold, + turnCheckedAt, }); if (!next) return { written: false, warnings, message: `Nothing held or queued by ${branch}.` }; const payload = { @@ -237,15 +269,16 @@ export async function runLease({ // Read-only view for agents: one gh api call. export async function leaseStatus({ api, environment, now = Date.now(), graceMinutes }) { - const query = new URLSearchParams({ - environment, - task: LEASE_TASK, - per_page: String(RECORD_PAGE_SIZE), - }); - const records = await api('GET', `/deployments?${query}`); - const { state, warnings } = foldRecords(records, environment); - const newest = records.find((record) => record.payload?.kind === 'snapshot'); - const grace = graceMinutes ?? newest?.payload?.graceMinutes ?? 10; + const { records, state, warnings } = await readRecords(api, environment); + const payloadOf = (record) => { + try { + return typeof record.payload === 'string' ? JSON.parse(record.payload) : record.payload; + } catch { + return null; + } + }; + const newest = records.map(payloadOf).find((payload) => payload?.kind === 'snapshot'); + const grace = graceMinutes ?? newest?.graceMinutes ?? 10; const turns = resolveTurns(state, now, grace); return { environment, @@ -311,10 +344,18 @@ async function main(command, argument) { return; } if (command === 'queue') { - const result = await runQueue({ ...workflowRequest(), timing: queueTiming(process.env) }); + const checkedAt = Date.now(); + const result = await runQueue({ + ...workflowRequest(), + timing: queueTiming(process.env), + now: checkedAt, + }); report([...result.warnings, ...result.lines]); if (process.env.GITHUB_OUTPUT) - appendFileSync(process.env.GITHUB_OUTPUT, `proceed=${result.proceed}\n`); + appendFileSync( + process.env.GITHUB_OUTPUT, + `proceed=${result.proceed}\nchecked_at=${iso(checkedAt)}\n` + ); if (result.refused) process.exitCode = 1; return; } @@ -322,6 +363,8 @@ async function main(command, argument) { const result = await runLease({ ...workflowRequest(), timing: { ...leaseTiming(process.env), ...queueTiming(process.env) }, + // When the queue job saw this branch's turn; runner or group waits must not forfeit it. + turnCheckedAt: process.env.LEASE_TURN_CHECKED_AT || null, }); report([...result.warnings, result.message]); return; diff --git a/scripts/deploy/staging-lease.test.mjs b/scripts/deploy/staging-lease.test.mjs index 32bcd00f06..26670ba01d 100644 --- a/scripts/deploy/staging-lease.test.mjs +++ b/scripts/deploy/staging-lease.test.mjs @@ -26,6 +26,7 @@ function store() { if (endpoint.startsWith('/deployments?')) { const query = new URLSearchParams(endpoint.split('?')[1]); assert.equal(query.get('task'), LEASE_TASK); + if ((query.get('page') ?? '1') !== '1') return []; return records.filter((r) => r.environment === query.get('environment')); } return records.find((r) => endpoint === `/deployments/${r.id}`); diff --git a/scripts/quality/deploy-staging-permissions.test.ts b/scripts/quality/deploy-staging-permissions.test.ts index 7f4a49bc13..8cc295434c 100644 --- a/scripts/quality/deploy-staging-permissions.test.ts +++ b/scripts/quality/deploy-staging-permissions.test.ts @@ -321,9 +321,10 @@ describe('lease workflow gating', () => { expect(workflow.jobs.queue.needs).toBeUndefined(); expect(workflow.jobs.lease.needs).toBe('queue'); expect(workflow.jobs.lease.if).toBe("${{ needs.queue.outputs.proceed == 'true' }}"); - // Same group name as older workflow copies, so transition writes serialize with them. + // Not the deploy- group older workflow copies hold for their whole run: their + // pending runs must not displace an entitled pending lease job. expect(workflow.jobs.lease.concurrency).toEqual({ - group: "deploy-${{ inputs.environment || 'staging' }}", + group: "staging-lease-${{ inputs.environment || 'staging' }}", 'cancel-in-progress': false, }); for (const name of LEASE_JOBS) @@ -352,7 +353,10 @@ describe('lease workflow gating', () => { const queue = step('queue', 'node scripts/deploy/staging-lease.mjs queue'); const lease = step('lease', 'node scripts/deploy/staging-lease.mjs lease'); expect(queue.id).toBe('queue'); - expect(lease.env).toEqual(queue.env); + const { LEASE_TURN_CHECKED_AT: checkedAt, ...leaseEnv } = lease.env; + expect(leaseEnv).toEqual(queue.env); + expect(checkedAt).toBe('${{ needs.queue.outputs.checked_at }}'); + expect(workflow.jobs.queue.outputs.checked_at).toBe('${{ steps.queue.outputs.checked_at }}'); expect(workflow.jobs.queue.outputs.proceed).toBe('${{ steps.queue.outputs.proceed }}'); expect(workflow.on.workflow_dispatch.inputs.lease_action.options).toEqual([ 'deploy', diff --git a/tasks/active/2026-11-16-staging-lease-fair-queue.md b/tasks/active/2026-11-16-staging-lease-fair-queue.md index bca0186b16..297ff73e28 100644 --- a/tasks/active/2026-11-16-staging-lease-fair-queue.md +++ b/tasks/active/2026-11-16-staging-lease-fair-queue.md @@ -51,8 +51,11 @@ First night of use (idea notes, 2026-11-16): (`reserve` always appends, renewing the TTL); lets the run into the `lease` job only if the branch holds the lease or it is its turn; otherwise fails (deploy/acquire) or succeeds (reserve) with the position in the step summary. -- `lease` job keeps group `deploy-` (same name as old workflows' group, so transition writes - serialize); deploy/storage-activation/agent-email audit move to group `staging-apply-`. +- `lease` job uses group `staging-lease-` (not the `deploy-` group old copies hold, so their + pending runs cannot displace an entitled one); deploy/storage-activation/agent-email audit move to + group `staging-apply-`. A release enters the group only if the branch holds or is queued. +- The lease job honours the turn the queue job saw (`checked_at`, bounded to 3 grace periods), so a + runner or group wait cannot cost the head its turn. An expired holder may re-reserve. - Release removes the branch's hold and its reservation; re-acquiring means queueing at the back. - Old workflows: any v2 record on top fails their lease job closed — no deploy, acquire, release. Payload `notice` tells them to update from main. @@ -72,7 +75,8 @@ First night of use (idea notes, 2026-11-16): - [x] Permissions/gating test updated - [x] Docs: `.claude/commands/do.md`, `.agents/skills/do/SKILL.md`, `.claude/rules/13-staging-verification.md`, `.agent-instructions/reference/rules/13-staging-verification-full.md` -- [ ] Live proof on staging2 with two branches (reserve/acquire/release, no full deploys) +- [x] Live proof with two branches (reserve/acquire/release, no full deploys) — on primary `staging`, staging2 was held +- [ ] One real deploy through queue → lease → deploy on staging2 (output wiring) - [ ] Note on idea, channel `feature.ship-faster` ## Checklist — Part 2 (PR 2, after PR 1 merges) From dd7096910543216f9afe277d10edfd344767ffc2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Mon, 16 Nov 2026 09:52:51 +0000 Subject: [PATCH 4/9] fix(staging): address CodeRabbit review of the lease queue - A reservation made after the branch's old one expired goes to the back. - A missed head that reserves again is placed by when it reserved, ahead of later reservations. - When a waiter ahead leaves, every remaining entry keeps the end of the turn it was told (promisedEnd), so a sleeping agent cannot miss it. - Snapshots keep recently missed entries for the admission slack, so a delayed lease job can still prove the turn it was let through on. - Reservations record the grace period, so status is right before the first snapshot. - Docs: release comes after every live check; rule 13 states the early-release turn window. Co-Authored-By: Claude Opus 5.5 --- .../rules/13-staging-verification-full.md | 9 +- .claude/commands/do.md | 33 ++++--- .claude/rules/13-staging-verification.md | 2 +- scripts/deploy/staging-lease-queue.mjs | 87 ++++++++++++----- scripts/deploy/staging-lease-queue.test.mjs | 97 +++++++++++++++++++ scripts/deploy/staging-lease.mjs | 6 +- 6 files changed, 190 insertions(+), 44 deletions(-) diff --git a/.agent-instructions/reference/rules/13-staging-verification-full.md b/.agent-instructions/reference/rules/13-staging-verification-full.md index e2546496a8..64fb0724b6 100644 --- a/.agent-instructions/reference/rules/13-staging-verification-full.md +++ b/.agent-instructions/reference/rules/13-staging-verification-full.md @@ -151,13 +151,18 @@ Staging deployment is **manual** — it does NOT run automatically on PRs. You m `STAGING_LEASE_MAX_HOLD_MINUTES`, default 120). Failed or cancelled runs keep the lease until release or expiry. -3. **Watch the run and verify live**, then **release** and hand over: +3. **Watch the run.** Keep the lease through every live check (section 2 below, and the + infrastructure checks where they apply); then **release** and hand over: ```bash gh run list --workflow=deploy-staging.yml --branch= --limit=3 \ --json databaseId,status,conclusion,headSha gh run watch - # After live checks and test-resource cleanup: + ``` + + After every live check and test-resource cleanup: + + ```bash gh workflow run deploy-staging.yml --ref \ -f environment=staging2 -f lease_action=release -f sam_task_id= ``` diff --git a/.claude/commands/do.md b/.claude/commands/do.md index 8e30f2a931..d0650163cd 100644 --- a/.claude/commands/do.md +++ b/.claude/commands/do.md @@ -265,27 +265,14 @@ If this PR includes **any code changes** (not just docs/tasks), deploy to stagin `STAGING_LEASE_MAX_HOLD_MINUTES`, default 120). Failed or cancelled runs keep the lease until release or expiry. -3. **Watch the run and verify live**, then **release** and hand over: +3. **Watch the run.** Keep the lease through every live check below; release comes last (step 9). ```bash gh run list --workflow=deploy-staging.yml --branch= --limit=3 \ --json databaseId,status,conclusion,headSha gh run watch - # After live checks and test-resource cleanup: - gh workflow run deploy-staging.yml --ref \ - -f environment=staging2 -f lease_action=release -f sam_task_id= ``` - Confirm the release run passed and `status` shows no holder. Release also - removes you from the queue if you were waiting. A branch that releases and wants - the slot again queues behind everyone already waiting. **If you release early, - message the next task in the queue** (`send_durable_message` to its SAM task ID - from `status`) so it can take its turn before its scheduled wake. Successful - deployment completion is not a release. Release only after your own deploy run - has finished: the next holder's deploy waits for an in-flight one in the - `staging-apply-` group, but your live checks are no longer - protected once you release. - Records are GitHub deployments with task `staging-lease`, keyed by installation. A malformed snapshot or an unknown record version fails closed (no one can change the lease until it is fixed through a reviewed change; never delete @@ -320,6 +307,24 @@ If this PR includes **any code changes** (not just docs/tasks), deploy to stagin 8. **If issues are found**, fix them in the branch, push, re-deploy, and re-verify. Do NOT merge with known staging failures. +9. **Release the lease only after every live check** (steps 4–8, plus Phase 6b + where it applies) and test-resource cleanup: + + ```bash + gh workflow run deploy-staging.yml --ref \ + -f environment=staging2 -f lease_action=release -f sam_task_id= + ``` + + Confirm the release run passed and `status` shows no holder. Release also + removes you from the queue if you were waiting. A branch that releases and wants + the slot again queues behind everyone already waiting. **If you release early, + message the next task in the queue** (`send_durable_message` to its SAM task ID + from `status`) so it can take its turn before its scheduled wake. Successful + deployment completion is not a release. Release only after your own deploy run + has finished: the next holder's deploy waits for an in-flight one in the + `staging-apply-` group, but your live checks are no longer + protected once you release. + ### 6b. Infrastructure Verification (MANDATORY for Infrastructure Changes) If the PR touches **any** of: `packages/cloud-init/`, `packages/vm-agent/`, `scripts/deploy/` (VM provisioning infrastructure), DNS record logic, TLS certificates, or VM agent port/protocol — you MUST complete these additional steps. **This is not optional. This is the gate that prevents catastrophic production failures.** diff --git a/.claude/rules/13-staging-verification.md b/.claude/rules/13-staging-verification.md index e478348610..5c93d36462 100644 --- a/.claude/rules/13-staging-verification.md +++ b/.claude/rules/13-staging-verification.md @@ -5,7 +5,7 @@ Keep this root rule compact. The full procedure is preserved at `.agent-instruct - Code PRs require staging deployment and live verification unless the change is documentation-only, config-only, or task-file-only. - There are two staging installations, `staging` (`sammy.party`) and `staging2` (`sammy2.party`), each with its own lease and data. Take whichever is free and pass it as `-f environment=`; staging2 sign-in is workload identity only (full reference, "Two Staging Installations"). - Read both queues with `node scripts/deploy/staging-lease.mjs status ` (one `gh api` call over deployments with task `staging-lease`). Reserve first with `deploy-staging.yml` `-f lease_action=reserve`; it takes seconds, deploys nothing, and no later dispatch can cancel your place. -- When the slot frees (release or expiry) only the queue head may take it, for `STAGING_LEASE_GRACE_MINUTES` (default 10), then the next entry. Schedule a one-time wake at your turn start; never dispatch a deploy while another branch holds the lease or has its turn. A branch that releases and wants it again queues behind existing waiters. +- When the slot frees (release or expiry) only the queue head may take it, for `STAGING_LEASE_GRACE_MINUTES` (default 10), then the next entry; after an early release the head's turn lasts until the holder's announced expiry plus grace. `status` and the run summary show each turn window. Schedule a one-time wake at your turn start (re-check `status` on waking; a waiter ahead leaving can only move your turn earlier, never shorten it); never dispatch a deploy while another branch holds the lease or has its turn. A branch that releases and wants it again queues behind existing waiters. - On your turn deploy (or `lease_action=acquire`); same-branch redeploys renew. `lease_action=release` frees your hold or place after live checks; confirm it, and message the next task in the queue when you release early. Malformed snapshots fail closed; branches whose workflow predates the queue are refused until they update from main. Details: full reference, section 1. - Authenticate Playwright against `https://api.sammy.party/api/auth/token-login` with `SAM_PLAYWRIGHT_PRIMARY_USER`; do not exchange staging tokens against production. - Alternative without a stored token: when staging trusts production (`AGENT_SIGN_IN_TRUST`), exchange your workload identity at `https://api.sammy.party/api/auth/workload-identity-login` (audience = that URL) and add the returned session cookie in Playwright. Exact values and commands: the full reference, section 2. diff --git a/scripts/deploy/staging-lease-queue.mjs b/scripts/deploy/staging-lease-queue.mjs index 7e8c1e4e6c..4f5722d669 100644 --- a/scripts/deploy/staging-lease-queue.mjs +++ b/scripts/deploy/staging-lease-queue.mjs @@ -50,7 +50,8 @@ function validEntry(entry) { text(entry.taskId) && validUtc(entry.reservedAt) && validUtc(entry.expiresAt) && - (entry.lastReservedAt === undefined || validUtc(entry.lastReservedAt)) + (entry.lastReservedAt === undefined || validUtc(entry.lastReservedAt)) && + (entry.promisedEnd === undefined || validUtc(entry.promisedEnd)) ); } @@ -150,7 +151,8 @@ function baseState(parsed) { } // A reservation by a branch already queued keeps its place and extends its expiry. It also records -// when it was made, so a branch that missed its turn and reserves again rejoins at the back. +// when it was made, so a branch that missed its turn and reserves again rejoins at the back. A +// reservation made after the old one expired is a new one: back of the queue. export function applyReservation(state, entry) { // Only a live hold makes the reservation redundant; a holder whose lease ran out queues again. const holder = state.holder; @@ -160,15 +162,17 @@ export function applyReservation(state, entry) { ) return; const existing = state.queue.find((queued) => queued.branch === entry.branch); - if (!existing) { - state.queue.push({ ...entry }); + if (existing && Date.parse(existing.expiresAt) <= Date.parse(entry.reservedAt)) + state.queue.splice(state.queue.indexOf(existing), 1); + else if (existing) { + if (Date.parse(entry.expiresAt) > Date.parse(existing.expiresAt)) + existing.expiresAt = entry.expiresAt; + if (Date.parse(entry.reservedAt) > Date.parse(existing.lastReservedAt ?? existing.reservedAt)) + existing.lastReservedAt = entry.reservedAt; + if (entry.taskId) existing.taskId = entry.taskId; return; } - if (Date.parse(entry.expiresAt) > Date.parse(existing.expiresAt)) - existing.expiresAt = entry.expiresAt; - if (Date.parse(entry.reservedAt) > Date.parse(existing.lastReservedAt ?? existing.reservedAt)) - existing.lastReservedAt = entry.reservedAt; - if (entry.taskId) existing.taskId = entry.taskId; + state.queue.push({ ...entry }); } // records: newest first, as GitHub lists deployments. `complete` is true when they are the whole @@ -256,16 +260,25 @@ export function resolveTurns(state, now, graceMinutes) { entries.push({ ...entry, status: 'stale', start, end: start }); continue; } - const end = (first ? Math.max(start, promisedAt) : start) + grace; + // A window never ends before the end already reported for it (promisedEnd), so a waiter + // that left the queue ahead of this one cannot make it miss a turn it scheduled a wake for. + const end = Math.max( + (first ? Math.max(start, promisedAt) : start) + grace, + entry.promisedEnd ? Date.parse(entry.promisedEnd) : 0 + ); let status = 'waiting'; if (!holder && end <= now) status = 'missed'; else if (!holder && start <= now) status = 'turn'; - entries.push({ ...entry, status, start, end }); - previousEnd = end; const again = entry.lastReservedAt ? Date.parse(entry.lastReservedAt) : null; - if (status === 'missed' && again !== null && again >= end) { - // Missed its turn, then reserved again: back of the queue. - pending.push({ + const requeued = status === 'missed' && again !== null && again >= end; + entries.push({ ...entry, status, start, end, requeued }); + previousEnd = end; + if (requeued) { + // Missed its turn, then reserved again: behind everyone who reserved before that, ahead + // of anyone who reserved after. + let at = index + 1; + while (at < pending.length && Date.parse(pending[at].reservedAt) <= again) at += 1; + pending.splice(at, 0, { branch: entry.branch, taskId: entry.taskId, reservedAt: entry.lastReservedAt, @@ -277,18 +290,36 @@ export function resolveTurns(state, now, graceMinutes) { return { holder, lastHolder, freeSince, promisedAt, entries, live, grace }; } -function queueEntry({ branch, taskId, reservedAt, expiresAt, lastReservedAt }) { - return lastReservedAt - ? { branch, taskId, reservedAt, expiresAt, lastReservedAt } - : { branch, taskId, reservedAt, expiresAt }; +function queueEntry({ branch, taskId, reservedAt, expiresAt, lastReservedAt, promisedEnd }) { + return { + branch, + taskId, + reservedAt, + expiresAt, + ...(lastReservedAt ? { lastReservedAt } : {}), + ...(promisedEnd ? { promisedEnd } : {}), + }; } -// The state to store after a decision taken while the slot is free. Dropped (missed or stale) -// entries are removed, and freeSince/promisedAt are moved so the remaining windows are unchanged. -// If the branch whose turn it was leaves, the next one may start at once and still keeps the window -// it was promised. +// How far back the lease job honours a turn the queue job saw (see hadTurn), in grace periods. +const ADMISSION_SLACK_GRACES = 3; + +// The state to store after a decision taken while the slot is free. Stale entries, and entries that +// missed their turn longer ago than the admission slack, are removed. freeSince/promisedAt move to +// the first remaining entry and every entry records the end it was promised, so no remaining window +// ends earlier than before. If the branch whose turn it was leaves, the next may start at once. +// Recently missed entries are kept so a delayed lease job can still prove the turn it was let +// through on (hadTurn). function freeSnapshot(turns, keep, now) { - const remaining = turns.live.filter(keep); + const slack = ADMISSION_SLACK_GRACES * turns.grace; + const remaining = turns.entries + .filter( + (entry) => + entry.status === 'turn' || + entry.status === 'waiting' || + (entry.status === 'missed' && !entry.requeued && entry.end > now - slack) + ) + .filter(keep); if (remaining.length === 0) return { holder: null, @@ -301,7 +332,7 @@ function freeSnapshot(turns, keep, now) { holder: null, freeSince: iso(Math.min(first.start, now)), promisedAt: iso(first.end - turns.grace), - queue: remaining.map(queueEntry), + queue: remaining.map((entry) => queueEntry({ ...entry, promisedEnd: iso(entry.end) })), }; } @@ -309,7 +340,11 @@ function freeSnapshot(turns, keep, now) { // or for the concurrency group must not cost it the turn. Bounded to a few grace periods back. function hadTurn(state, branch, checkedAt, now, graceMinutes) { const checked = checkedAt ? Date.parse(checkedAt) : NaN; - if (!Number.isFinite(checked) || checked > now || checked < now - 3 * graceMinutes * MINUTE) + if ( + !Number.isFinite(checked) || + checked > now || + checked < now - ADMISSION_SLACK_GRACES * graceMinutes * MINUTE + ) return false; return hasTurn(resolveTurns(state, checked, graceMinutes), branch); } diff --git a/scripts/deploy/staging-lease-queue.test.mjs b/scripts/deploy/staging-lease-queue.test.mjs index 0d4eb03a4e..9d7a03bb3a 100644 --- a/scripts/deploy/staging-lease-queue.test.mjs +++ b/scripts/deploy/staging-lease-queue.test.mjs @@ -511,3 +511,100 @@ test('a lease job delayed past the turn keeps the turn the queue job saw, within assert.equal(granted.holder.branch, 'b'); assert.deepEqual(await order(db, T0 + 44 * MIN), ['c', 'd', 'e', 'f']); }); + +test('a reservation made after the old one expired goes to the back, not to its old place', async () => { + const db = store(); + const short = { ...timing, reservationMinutes: 45 }; + await dispatch(db, 'a', 'deploy', T0); // expires T0+60 + await dispatch(db, 'b', 'reserve', T0 + MIN, { timing: short }); // expires T0+46 + await dispatch(db, 'c', 'reserve', T0 + 2 * MIN); + await dispatch(db, 'b', 'reserve', T0 + 50 * MIN); + assert.deepEqual(await order(db, T0 + 51 * MIN), ['c', 'b']); + assert.equal((await dispatch(db, 'b', 'acquire', T0 + 61 * MIN)).refused, true); + assert.equal((await dispatch(db, 'c', 'acquire', T0 + 61 * MIN)).lease.holder.branch, 'c'); +}); + +test('a missed head that reserves again is placed by when it reserved, ahead of later reservations', async () => { + const db = store(); + await dispatch(db, 'a', 'acquire', T0); // expires T0+30 + await dispatch(db, 'b', 'reserve', T0 + MIN); + await dispatch(db, 'c', 'reserve', T0 + 2 * MIN); + // B misses [30,40). B reserves again at 45, D first reserves at 46, both before any snapshot. + await dispatch(db, 'b', 'reserve', T0 + 45 * MIN); + await dispatch(db, 'd', 'reserve', T0 + 46 * MIN); + assert.deepEqual(await order(db, T0 + 47 * MIN), ['c', 'b', 'd']); +}); + +test('when a waiter ahead leaves, later waiters keep the end of the turn they were told', async () => { + const db = store(); + await dispatch(db, 'a', 'acquire', T0); // expires T0+30 + for (const branch of ['b', 'c', 'd', 'e']) await dispatch(db, branch, 'reserve', T0 + MIN); + const before = await status(db, T0 + 31 * MIN); + const promised = Object.fromEntries(before.queue.map((entry) => [entry.branch, entry.turnEnds])); + assert.equal(promised.d, new Date(T0 + 60 * MIN).toISOString()); + await dispatch(db, 'c', 'release', T0 + 31 * MIN); + const after = await status(db, T0 + 32 * MIN); + for (const entry of after.queue) + assert.ok(entry.turnEnds >= promised[entry.branch], `${entry.branch} window shrank`); + // D wakes at the start it was told (T0+50; B missed [30,40)) and still has its turn. + assert.equal(after.queue.find((entry) => entry.branch === 'd').turnEnds, promised.d); + assert.equal((await dispatch(db, 'd', 'acquire', T0 + 50 * MIN)).lease.holder.branch, 'd'); +}); + +test('a delayed lease job keeps its admission even if another snapshot was written meanwhile', async () => { + const db = store(); + await dispatch(db, 'a', 'acquire', T0); // expires T0+30 + for (const branch of ['b', 'c', 'd']) await dispatch(db, branch, 'reserve', T0 + MIN); + // B's queue job saw its turn at T0+39; its lease job starts at T0+43. In between, at T0+41, + // D leaves the queue, which writes a snapshot while B has already missed [30,40). + await dispatch(db, 'd', 'release', T0 + 41 * MIN); + const granted = await runLease({ + api: db.api, + environment: 'staging2', + branch: 'b', + sha, + action: 'acquire', + timing, + now: T0 + 43 * MIN, + turnCheckedAt: new Date(T0 + 39 * MIN).toISOString(), + }); + assert.equal(granted.holder.branch, 'b'); + assert.deepEqual(await order(db, T0 + 44 * MIN), ['c']); +}); + +test('status uses the grace period the workflow recorded, even before the first snapshot', async () => { + const db = store(); + const short = { ...timing, graceMinutes: 3 }; + await runQueue({ + api: db.api, + environment: 'staging2', + branch: 'x', + sha, + action: 'reserve', + timing: short, + now: T0, + }); + await runQueue({ + api: db.api, + environment: 'staging2', + branch: 'y', + sha, + action: 'reserve', + timing: short, + now: T0 + MIN, + }); + const view = await status(db, T0 + 2 * MIN); + assert.equal(view.graceMinutes, 3); + assert.equal(view.queue[1].turnStarts, new Date(T0 + 3 * MIN).toISOString()); +}); + +test('a missed head that reserved again is stored once when a snapshot is written soon after', async () => { + const db = store(); + await dispatch(db, 'a', 'acquire', T0); // expires T0+30 + await dispatch(db, 'b', 'reserve', T0 + MIN); + await dispatch(db, 'c', 'reserve', T0 + 2 * MIN); + await dispatch(db, 'b', 'reserve', T0 + 41 * MIN); // missed [30,40), within the admission slack + await dispatch(db, 'c', 'release', T0 + 42 * MIN); // writes a snapshot + assert.deepEqual(await order(db, T0 + 43 * MIN), ['b']); + assert.equal((await dispatch(db, 'b', 'acquire', T0 + 43 * MIN)).lease.holder.branch, 'b'); +}); diff --git a/scripts/deploy/staging-lease.mjs b/scripts/deploy/staging-lease.mjs index 28dd025cd3..cb3d5f9fb1 100644 --- a/scripts/deploy/staging-lease.mjs +++ b/scripts/deploy/staging-lease.mjs @@ -175,6 +175,7 @@ export async function runQueue({ kind: 'reservation', environment, ...entry, + graceMinutes: timing.graceMinutes, notice: OLD_WORKFLOW_NOTICE, }, }); @@ -277,7 +278,10 @@ export async function leaseStatus({ api, environment, now = Date.now(), graceMin return null; } }; - const newest = records.map(payloadOf).find((payload) => payload?.kind === 'snapshot'); + // The newest record that says which grace period the workflow used (snapshots and reservations). + const newest = records + .map(payloadOf) + .find((payload) => Number.isSafeInteger(payload?.graceMinutes) && payload.graceMinutes > 0); const grace = graceMinutes ?? newest?.graceMinutes ?? 10; const turns = resolveTurns(state, now, grace); return { From 35e1911042522f7ed23354274d259fc1f0036223 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Mon, 16 Nov 2026 09:58:41 +0000 Subject: [PATCH 5/9] docs(staging): keep root rule 13 within the launch context budget Co-Authored-By: Claude Opus 5.5 --- .claude/rules/13-staging-verification.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.claude/rules/13-staging-verification.md b/.claude/rules/13-staging-verification.md index 5c93d36462..d3947f69fd 100644 --- a/.claude/rules/13-staging-verification.md +++ b/.claude/rules/13-staging-verification.md @@ -4,9 +4,9 @@ Keep this root rule compact. The full procedure is preserved at `.agent-instruct - Code PRs require staging deployment and live verification unless the change is documentation-only, config-only, or task-file-only. - There are two staging installations, `staging` (`sammy.party`) and `staging2` (`sammy2.party`), each with its own lease and data. Take whichever is free and pass it as `-f environment=`; staging2 sign-in is workload identity only (full reference, "Two Staging Installations"). -- Read both queues with `node scripts/deploy/staging-lease.mjs status ` (one `gh api` call over deployments with task `staging-lease`). Reserve first with `deploy-staging.yml` `-f lease_action=reserve`; it takes seconds, deploys nothing, and no later dispatch can cancel your place. -- When the slot frees (release or expiry) only the queue head may take it, for `STAGING_LEASE_GRACE_MINUTES` (default 10), then the next entry; after an early release the head's turn lasts until the holder's announced expiry plus grace. `status` and the run summary show each turn window. Schedule a one-time wake at your turn start (re-check `status` on waking; a waiter ahead leaving can only move your turn earlier, never shorten it); never dispatch a deploy while another branch holds the lease or has its turn. A branch that releases and wants it again queues behind existing waiters. -- On your turn deploy (or `lease_action=acquire`); same-branch redeploys renew. `lease_action=release` frees your hold or place after live checks; confirm it, and message the next task in the queue when you release early. Malformed snapshots fail closed; branches whose workflow predates the queue are refused until they update from main. Details: full reference, section 1. +- Read both queues with `node scripts/deploy/staging-lease.mjs status `. Reserve first (`deploy-staging.yml -f lease_action=reserve`); no later dispatch can cancel your place. +- A freed slot goes to the queue head for `STAGING_LEASE_GRACE_MINUTES` (default 10; after an early release, until the holder's announced expiry plus grace), then the next. Wake at your turn start; never dispatch a deploy while another branch holds the lease or has its turn. +- On your turn deploy or `acquire`; release only after every live check, and message the next task when releasing early. Branches older than the queue must update from main. Details: full reference, section 1. - Authenticate Playwright against `https://api.sammy.party/api/auth/token-login` with `SAM_PLAYWRIGHT_PRIMARY_USER`; do not exchange staging tokens against production. - Alternative without a stored token: when staging trusts production (`AGENT_SIGN_IN_TRUST`), exchange your workload identity at `https://api.sammy.party/api/auth/workload-identity-login` (audience = that URL) and add the returned session cookie in Playwright. Exact values and commands: the full reference, section 2. - For VM/cloud-init/DNS/TLS infrastructure, provision a real VM, verify heartbeat and access, then clean it up. From 3d9fd4ea174c115878b627fccdd72d4b7ecc0b56 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Mon, 16 Nov 2026 10:09:44 +0000 Subject: [PATCH 6/9] fix(staging): never write a queue record over a live pre-queue lease A workflow copy from before the queue refuses any version-2 record, so a reservation written over its live lease locks it out of renewing or releasing. While the holder's record is version 1, the queue job writes nothing and tells the caller to wake at the legacy expiry. Co-Authored-By: Claude Opus 5.5 --- .../rules/13-staging-verification-full.md | 5 ++++- .claude/commands/do.md | 5 ++++- scripts/deploy/staging-lease-queue.mjs | 2 ++ scripts/deploy/staging-lease-queue.test.mjs | 21 +++++++++++++++---- scripts/deploy/staging-lease.mjs | 14 +++++++++++++ 5 files changed, 41 insertions(+), 6 deletions(-) diff --git a/.agent-instructions/reference/rules/13-staging-verification-full.md b/.agent-instructions/reference/rules/13-staging-verification-full.md index 64fb0724b6..4fab450970 100644 --- a/.agent-instructions/reference/rules/13-staging-verification-full.md +++ b/.agent-instructions/reference/rules/13-staging-verification-full.md @@ -131,7 +131,10 @@ Staging deployment is **manual** — it does NOT run automatically on PRs. You m deploy while another branch holds the lease or it is another branch's turn**: the run is refused (your place is kept). A reservation expires after `STAGING_LEASE_RESERVATION_MINUTES` (default 480) unless renewed by reserving - again, which keeps your place. + again, which keeps your place. While the holder is a branch whose workflow predates + the queue (its lease record is version 1), no reservation is written, because its + workflow cannot read queue records and would be locked out of its own lease: + schedule a wake at its expiry and reserve then. On your turn, deploy (or `-f lease_action=acquire` to hold without deploying): diff --git a/.claude/commands/do.md b/.claude/commands/do.md index d0650163cd..bed65a6b24 100644 --- a/.claude/commands/do.md +++ b/.claude/commands/do.md @@ -245,7 +245,10 @@ If this PR includes **any code changes** (not just docs/tasks), deploy to stagin deploy while another branch holds the lease or it is another branch's turn**: the run is refused (your place is kept). A reservation expires after `STAGING_LEASE_RESERVATION_MINUTES` (default 480) unless renewed by reserving - again, which keeps your place. + again, which keeps your place. While the holder is a branch whose workflow predates + the queue (its lease record is version 1), no reservation is written, because its + workflow cannot read queue records and would be locked out of its own lease: + schedule a wake at its expiry and reserve then. On your turn, deploy (or `-f lease_action=acquire` to hold without deploying): diff --git a/scripts/deploy/staging-lease-queue.mjs b/scripts/deploy/staging-lease-queue.mjs index 4f5722d669..979bf5c6fe 100644 --- a/scripts/deploy/staging-lease-queue.mjs +++ b/scripts/deploy/staging-lease-queue.mjs @@ -147,6 +147,8 @@ function baseState(parsed) { promisedAt: held ? null : lease.expiresAt, queue: [], seenThrough: parsed.id, + // Held by a pre-queue workflow copy, which cannot read queue records (see runQueue). + legacyHold: held, }; } diff --git a/scripts/deploy/staging-lease-queue.test.mjs b/scripts/deploy/staging-lease-queue.test.mjs index 9d7a03bb3a..c6de08701a 100644 --- a/scripts/deploy/staging-lease-queue.test.mjs +++ b/scripts/deploy/staging-lease-queue.test.mjs @@ -229,7 +229,7 @@ test('concurrent reservations, including one made while the lease job writes, al assert.deepEqual(await order(db, T0 + 3 * MIN), ['b', 'c', 'd']); }); -test('a version 1 record from an older workflow is honoured as the holder, and the queue forms behind it', async () => { +test('a live version 1 hold from an older workflow is honoured and never covered by a queue record', async () => { const legacy = { id: 7, task: LEASE_TASK, @@ -246,9 +246,22 @@ test('a version 1 record from an older workflow is honoured as the holder, and t }; const db = store([legacy]); assert.equal(await holder(db, T0), 'old'); - assert.equal((await dispatch(db, 'b', 'deploy', T0)).refused, true); - assert.equal((await dispatch(db, 'c', 'deploy', T0 + 31 * MIN)).refused, true); - assert.equal((await dispatch(db, 'b', 'deploy', T0 + 32 * MIN)).lease.holder.branch, 'b'); + // Writing a queue record now would lock the old workflow out of renewing or releasing. + for (const action of ['deploy', 'reserve']) { + const waiting = await dispatch(db, 'b', action, T0); + assert.equal(waiting.queued.proceed, false); + assert.match(waiting.queued.lines.at(-1), /No reservation written/); + } + assert.equal(db.records.length, 1, 'nothing written over the legacy hold'); + assert.equal(olderWorkflowReads(db.records).branch, 'old'); + // The holder itself, once updated from main, may renew or release through the new workflow. + assert.equal((await dispatch(db, 'old', 'acquire', T0 + MIN)).lease.holder.branch, 'old'); + const db2 = store([legacy]); + assert.equal((await dispatch(db2, 'old', 'release', T0 + MIN)).lease.written, true); + // After the legacy hold expires, the queue works normally. + assert.equal((await dispatch(db, 'c', 'deploy', T0 + 32 * MIN)).lease.holder.branch, 'c'); + assert.equal((await dispatch(db, 'b', 'deploy', T0 + 33 * MIN)).refused, true); + assert.deepEqual(await order(db, T0 + 34 * MIN), ['b']); const released = store([ { ...legacy, diff --git a/scripts/deploy/staging-lease.mjs b/scripts/deploy/staging-lease.mjs index cb3d5f9fb1..ceff3a9c4e 100644 --- a/scripts/deploy/staging-lease.mjs +++ b/scripts/deploy/staging-lease.mjs @@ -159,6 +159,20 @@ export async function runQueue({ }; } let turns = plan.turns; + const legacy = state.legacyHold && turns.holder ? turns.holder : null; + if (plan.append && legacy) { + // Transition: the holder's workflow predates the queue and refuses any queue record, so + // writing one would lock it out of renewing or releasing its own live lease. Leave it alone. + return { + proceed: false, + refused: action !== 'reserve', + warnings, + lines: [ + `Holder: ${legacy.branch} (SAM task ${legacy.taskId || 'not supplied'}) until ${legacy.expiresAt}, with a workflow from before the queue.`, + `No reservation written: that workflow cannot read queue records, so queueing behind it would lock it out of its own lease. Schedule a wake at ${legacy.expiresAt} and reserve then.`, + ], + }; + } if (plan.append) { const entry = { branch, From d091c55fd3b98ace47d63d51218303d7158e61d8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Mon, 16 Nov 2026 16:17:26 +0000 Subject: [PATCH 7/9] fix(staging): keep branches with new Durable Object migrations off primary staging Durable Object migrations only move forward, so a branch that deploys a migration tag main lacks blocks every main-based branch on that installation until it merges. deploy-staging.yml now refuses such deploys on primary staging before a place is reserved, and tells the agent to use staging2. The comparison reads apps/api/wrangler.toml on the branch and on origin/main, and fails closed when it cannot read every tag. Documents the clean-up duty: tear staging2 down and redeploy main before releasing if the branch has not merged. Co-Authored-By: Claude Opus 5.5 --- .../rules/13-staging-verification-full.md | 11 +++ .agents/skills/do/SKILL.md | 2 +- .claude/commands/do.md | 4 ++ .claude/rules/13-staging-verification.md | 2 +- .github/workflows/deploy-staging.yml | 9 +++ scripts/deploy/staging-migration-guard.mjs | 68 +++++++++++++++++++ .../deploy/staging-migration-guard.test.mjs | 50 ++++++++++++++ .../deploy-staging-permissions.test.ts | 28 ++++++++ .../2026-11-16-staging-lease-fair-queue.md | 18 +++-- 9 files changed, 184 insertions(+), 8 deletions(-) create mode 100644 scripts/deploy/staging-migration-guard.mjs create mode 100644 scripts/deploy/staging-migration-guard.test.mjs rename tasks/{active => archive}/2026-11-16-staging-lease-fair-queue.md (86%) diff --git a/.agent-instructions/reference/rules/13-staging-verification-full.md b/.agent-instructions/reference/rules/13-staging-verification-full.md index 4fab450970..bd0b601fa2 100644 --- a/.agent-instructions/reference/rules/13-staging-verification-full.md +++ b/.agent-instructions/reference/rules/13-staging-verification-full.md @@ -77,6 +77,17 @@ name (`sam2-staging2`): `GET /accounts/$CF_ACCOUNT_ID/d1/database?name=sam2-stag the `staging2` Pulumi stack and the `sammy2.party` zone's workspace and node records. Delete test workspaces and nodes first; teardown does not delete VMs. The next deploy rebuilds staging2 from nothing. +**Branches that add a Durable Object migration.** Durable Object migrations only move forward. +Once a branch deploys a tag that `origin/main` lacks (a new `[[migrations]]` entry in +`apps/api/wrangler.toml`), every main-based branch fails the migration preflight on that +installation until the branch merges. So `deploy-staging.yml` refuses such deploys on primary +`staging` before reserving a place (`scripts/deploy/staging-migration-guard.mjs`, which fails closed +when it cannot compare the two files). Use `staging2`. Clean-up duty: if your branch has not merged +when you are done on `staging2`, tear it down (Actions → Teardown → `staging2` → `DELETE`, after +deleting test workspaces and nodes) and redeploy `main` to it (`gh workflow run deploy-staging.yml +--ref main -f environment=staging2 -f sam_task_id=`) before you release. staging2 rebuilds +from nothing, so main-based branches can use it again. Nothing does this automatically. + Adding a third: one entry in `scripts/deploy/staging-installations.mjs` plus a zone in the staging Cloudflare account that the staging deploy token can edit. diff --git a/.agents/skills/do/SKILL.md b/.agents/skills/do/SKILL.md index ff3441225a..6d90eddcc7 100644 --- a/.agents/skills/do/SKILL.md +++ b/.agents/skills/do/SKILL.md @@ -16,7 +16,7 @@ Read the full workflow from `.claude/commands/do.md` and execute it. Use `.claud 4. **Implement** — follow checklist, push frequently, run quality checks. After the first push open the PR as a draft (`gh pr create --draft`); draft PRs run only quick CI checks. **For UI changes**: run mandatory Playwright visual audit with mock data on mobile + desktop viewports (see `.claude/rules/17-ui-visual-testing.md`) 5. **Validate** — full quality suite: lint, typecheck, test, build. As soon as the candidate is complete, mark the PR ready (`gh pr ready `), which starts the full CI suite, and request CodeRabbit at the same moment; reviews and staging then run in parallel with CI and CodeRabbit 6. **Review** — invoke local specialist skills / local subagents ($go-specialist, $cloudflare-specialist, etc.) -7. **Staging** — there are two installations, `staging` (`sammy.party`) and `staging2` (`sammy2.party`); read both queues with `node scripts/deploy/staging-lease.mjs status ` (one `gh api` call) and use the free or shorter one with `-f environment=` (staging2 sign-in: workload identity). Reserve first: `gh workflow run deploy-staging.yml --ref -f environment= -f lease_action=reserve -f sam_task_id=`; schedule a SAM wake at your turn start (shown in the run summary and `status`) instead of polling or chatting, and never dispatch a deploy while another branch holds the lease or has its turn. On your turn deploy with the same command minus `lease_action` (only the head of the queue may take a freed slot, for a 10-minute grace period by default). After live checks release with `-f lease_action=release`, confirm success, and if you released early message the next task in the queue. Configurable hold defaults/cap and commands: `.agent-instructions/reference/rules/13-staging-verification-full.md`. **Use `$CF_TOKEN` to query D1/KV/DNS directly** (see `.claude/rules/32-cf-api-debugging.md`) to verify migrations, data state, and feature flags — this is faster and more precise than UI-based checks. Then verify changed behavior end-to-end via Playwright. **For infrastructure changes** (cloud-init, VM agent, DNS, TLS, scripts/deploy): MUST provision a real VM and verify heartbeat arrives. +7. **Staging** — there are two installations, `staging` (`sammy.party`) and `staging2` (`sammy2.party`); read both queues with `node scripts/deploy/staging-lease.mjs status ` (one `gh api` call) and use the free or shorter one with `-f environment=` (staging2 sign-in: workload identity). A branch adding a Durable Object migration tag that main lacks must use staging2 and, if unmerged when done, tear staging2 down and redeploy main before releasing. Reserve first: `gh workflow run deploy-staging.yml --ref -f environment= -f lease_action=reserve -f sam_task_id=`; schedule a SAM wake at your turn start (shown in the run summary and `status`) instead of polling or chatting, and never dispatch a deploy while another branch holds the lease or has its turn. On your turn deploy with the same command minus `lease_action` (only the head of the queue may take a freed slot, for a 10-minute grace period by default). After live checks release with `-f lease_action=release`, confirm success, and if you released early message the next task in the queue. Configurable hold defaults/cap and commands: `.agent-instructions/reference/rules/13-staging-verification-full.md`. **Use `$CF_TOKEN` to query D1/KV/DNS directly** (see `.claude/rules/32-cf-api-debugging.md`) to verify migrations, data state, and feature flags — this is faster and more precise than UI-based checks. Then verify changed behavior end-to-end via Playwright. **For infrastructure changes** (cloud-init, VM agent, DNS, TLS, scripts/deploy): MUST provision a real VM and verify heartbeat arrives. 8. **PR** — the PR is already ready from step 5 (create it now if not, not as a draft). Wait for the full CI run on the ready PR (the required `Durable Object Workers` check reports only after every job finished). CodeRabbit is requested when the PR is marked ready, through the trusted GitHub Actions path: apply the `coderabbit-review` label with `gh pr edit --add-label coderabbit-review`; if the label run did not fire (it never fires on a draft PR), run `gh workflow run coderabbit-bot-review.yml --ref main -f pr_number=`. Do not post `@coderabbitai review` directly with an agent token. Then wait about 15 minutes from the request, ending at once on a `Review skipped`, rate-limit or quota reply. A CodeRabbit review is not required, but one that arrives blocks merge: implement or resolve every finding with a reason, and give incremental reviews after pushed fixes the same wait. If no review arrives (silence, `Review skipped`, rate limit), record that in the PR's CodeRabbit Review Evidence and continue. Do not re-trigger in a loop, and never add `needs-human-review` or wait for a waiver because CodeRabbit is silent (see `.claude/rules/25-review-merge-gate.md`). If the user requested draft PR / do-not-merge, do not mark it ready; get the full suite with `gh workflow run ci.yml --ref `, stop at the draft PR and do not merge. 9. **Cleanup** — remove worktree, pull main diff --git a/.claude/commands/do.md b/.claude/commands/do.md index 2ebc71bac7..0e8e5a8a41 100644 --- a/.claude/commands/do.md +++ b/.claude/commands/do.md @@ -225,6 +225,10 @@ If this PR includes **any code changes** (not just docs/tasks), deploy to stagin one that is free or has the shorter queue and use that name in every command below. They share the `staging` credentials but nothing else. staging2 sign-in is workload identity only; see "Two Staging Installations" in the full reference. + A branch that adds a Durable Object migration tag `origin/main` lacks is refused + on primary `staging`: use `staging2`, and if the branch has not merged when you + are done, tear `staging2` down and redeploy `main` before releasing (full + reference, "Branches that add a Durable Object migration"). 2. **Reserve first, then deploy only on your turn.** Reserving takes seconds and deploys nothing: diff --git a/.claude/rules/13-staging-verification.md b/.claude/rules/13-staging-verification.md index d3947f69fd..d4b4ca2d3c 100644 --- a/.claude/rules/13-staging-verification.md +++ b/.claude/rules/13-staging-verification.md @@ -3,7 +3,7 @@ Keep this root rule compact. The full procedure is preserved at `.agent-instructions/reference/rules/13-staging-verification-full.md`. - Code PRs require staging deployment and live verification unless the change is documentation-only, config-only, or task-file-only. -- There are two staging installations, `staging` (`sammy.party`) and `staging2` (`sammy2.party`), each with its own lease and data. Take whichever is free and pass it as `-f environment=`; staging2 sign-in is workload identity only (full reference, "Two Staging Installations"). +- There are two staging installations, `staging` (`sammy.party`) and `staging2` (`sammy2.party`), each with its own lease and data. Take whichever is free and pass it as `-f environment=`; staging2 sign-in is workload identity only (full reference, "Two Staging Installations"). Branches adding a Durable Object migration must use staging2. - Read both queues with `node scripts/deploy/staging-lease.mjs status `. Reserve first (`deploy-staging.yml -f lease_action=reserve`); no later dispatch can cancel your place. - A freed slot goes to the queue head for `STAGING_LEASE_GRACE_MINUTES` (default 10; after an early release, until the holder's announced expiry plus grace), then the next. Wake at your turn start; never dispatch a deploy while another branch holds the lease or has its turn. - On your turn deploy or `acquire`; release only after every live check, and message the next task when releasing early. Branches older than the queue must update from main. Details: full reference, section 1. diff --git a/.github/workflows/deploy-staging.yml b/.github/workflows/deploy-staging.yml index 40c0d900d5..0a23227dff 100644 --- a/.github/workflows/deploy-staging.yml +++ b/.github/workflows/deploy-staging.yml @@ -125,6 +125,15 @@ jobs: INSTALLATION: ${{ inputs.environment || 'staging' }} PRIMARY_BASE_DOMAIN: ${{ vars.BASE_DOMAIN }} run: node scripts/deploy/staging-installations.mjs workflow-target + # A branch that adds a Durable Object migration tag main lacks would leave primary staging + # ahead of main (migrations only move forward), so every main-based deploy there fails the + # migration preflight until it merges. Refused before a place is reserved; use staging2. + - name: Keep new Durable Object migrations off primary staging + if: ${{ (inputs.environment || 'staging') == 'staging' && (inputs.lease_action == 'deploy' || inputs.lease_action == '') && !inputs.github_trigger_audit_send_only && !inputs.activation_only && !inputs.performance_audit_only }} + env: + LEASE_ENVIRONMENT: ${{ inputs.environment || 'staging' }} + LEASE_ACTION: ${{ inputs.lease_action || 'deploy' }} + run: node scripts/deploy/staging-migration-guard.mjs - name: Reserve a place or confirm this branch's turn id: queue env: diff --git a/scripts/deploy/staging-migration-guard.mjs b/scripts/deploy/staging-migration-guard.mjs new file mode 100644 index 0000000000..aded4a8464 --- /dev/null +++ b/scripts/deploy/staging-migration-guard.mjs @@ -0,0 +1,68 @@ +// Keeps branches that add a Durable Object migration off the primary staging installation. +// Durable Object migrations only move forward: once a branch deploys tag vN+1 to an +// installation, every main-based branch (history ending at vN) fails the migration preflight +// there (scripts/deploy/durable-object-migrations.ts) until that branch merges. Such branches +// verify on staging2, whose holder rebuilds it from main before releasing (staging reference, +// "Branches that add a Durable Object migration"). +// +// node scripts/deploy/staging-migration-guard.mjs # deploy-staging.yml job `queue` +import { execFileSync } from 'node:child_process'; +import { readFileSync } from 'node:fs'; +import { pathToFileURL } from 'node:url'; + +export const WRANGLER_TOML = 'apps/api/wrangler.toml'; +export const PRIMARY_INSTALLATION = 'staging'; + +// Tags in [[migrations]] order. Fails closed on anything it cannot read unambiguously. +export function migrationTags(toml, source) { + if (typeof toml !== 'string' || toml.length === 0) + throw new Error(`${source}: empty wrangler.toml`); + const blocks = toml.match(/^\[\[migrations\]\][ \t]*$/gm)?.length ?? 0; + const tags = [ + ...toml.matchAll(/^\[\[migrations\]\][ \t]*\r?\n[ \t]*tag[ \t]*=[ \t]*"([^"\n]+)"/gm), + ].map((match) => match[1]); + if (blocks === 0 || tags.length !== blocks) + throw new Error( + `${source}: cannot read every [[migrations]] tag (${tags.length} of ${blocks})` + ); + return tags; +} + +export function newMigrationTags(branchToml, mainToml) { + const main = new Set(migrationTags(mainToml, 'origin/main')); + return migrationTags(branchToml, 'branch').filter((tag) => !main.has(tag)); +} + +// Returns null when the deploy may proceed, or the refusal message. +export function checkInstallation({ installation, action, branchToml, mainToml }) { + if (installation !== PRIMARY_INSTALLATION || action !== 'deploy') return null; + const added = newMigrationTags(branchToml, mainToml); + if (added.length === 0) return null; + return `This branch adds Durable Object migration tag(s) ${added.join(', ')} that origin/main does not have. Deploying it to primary staging would block every main-based branch there until it merges (migrations only move forward). Use -f environment=staging2; if the branch has not merged when you are done, tear staging2 down and redeploy main before releasing.`; +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + try { + const installation = process.env.LEASE_ENVIRONMENT || PRIMARY_INSTALLATION; + const action = process.env.LEASE_ACTION || 'deploy'; + let refusal = null; + if (installation === PRIMARY_INSTALLATION && action === 'deploy') { + execFileSync('git', ['fetch', '--quiet', '--depth=1', 'origin', 'main'], { + stdio: 'inherit', + }); + refusal = checkInstallation({ + installation, + action, + branchToml: readFileSync(WRANGLER_TOML, 'utf8'), + mainToml: execFileSync('git', ['show', `FETCH_HEAD:${WRANGLER_TOML}`], { + encoding: 'utf8', + }), + }); + } + if (refusal) throw new Error(refusal); + console.log('Durable Object migration guard: no new migration tags for primary staging.'); + } catch (error) { + console.error(`Staging deploy refused: ${error.message}`); + process.exitCode = 1; + } +} diff --git a/scripts/deploy/staging-migration-guard.test.mjs b/scripts/deploy/staging-migration-guard.test.mjs new file mode 100644 index 0000000000..2ffa2f6dcd --- /dev/null +++ b/scripts/deploy/staging-migration-guard.test.mjs @@ -0,0 +1,50 @@ +// Run in CI through scripts/quality/deploy-staging-permissions.test.ts. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; + +import { checkInstallation, migrationTags, newMigrationTags } from './staging-migration-guard.mjs'; + +const main = readFileSync(new URL('../../apps/api/wrangler.toml', import.meta.url), 'utf8'); +const tags = migrationTags(main, 'main'); +const next = `v${Number(tags.at(-1).slice(1)) + 1}`; +const withNext = `${main}\n[[migrations]]\ntag = "${next}"\nnew_sqlite_classes = ["NewThing"]\n`; +const check = (installation, action, branchToml, mainToml = main) => + checkInstallation({ installation, action, branchToml, mainToml }); + +test('reads every migration tag of the real wrangler.toml, in order', () => { + assert.ok(tags.length > 10); + assert.equal(new Set(tags).size, tags.length); + assert.equal(tags[0], 'v1'); +}); + +test('a branch adding a migration tag is refused on primary staging deploys only', () => { + assert.deepEqual(newMigrationTags(withNext, main), [next]); + assert.match(check('staging', 'deploy', withNext), new RegExp(`${next}[\\s\\S]*staging2`)); + for (const [installation, action] of [ + ['staging2', 'deploy'], + ['staging', 'acquire'], + ['staging', 'reserve'], + ['staging', 'release'], + ]) + assert.equal(check(installation, action, withNext), null, `${installation} ${action}`); +}); + +test('main-based branches, and branches behind main, may deploy to primary staging', () => { + assert.equal(check('staging', 'deploy', main), null); + assert.equal(check('staging', 'deploy', main, withNext), null); +}); + +test('anything that cannot be compared unambiguously fails closed', () => { + const tagNotFirst = main.replace( + /^\[\[migrations\]\][ \t]*\r?\n([ \t]*tag[ \t]*=[^\n]*)/m, + '[[migrations]]\nnew_classes = ["X"]\n$1' + ); + for (const [branch, base] of [ + ['', main], + [withNext, ''], + [tagNotFirst, main], + ['name = "worker"\n', main], + ]) + assert.throws(() => check('staging', 'deploy', branch, base), /wrangler\.toml|tag/); +}); diff --git a/scripts/quality/deploy-staging-permissions.test.ts b/scripts/quality/deploy-staging-permissions.test.ts index 8cc295434c..3c8c080102 100644 --- a/scripts/quality/deploy-staging-permissions.test.ts +++ b/scripts/quality/deploy-staging-permissions.test.ts @@ -375,6 +375,7 @@ it('executes the lease lifecycle and failure-path tests in CI', () => { '--test', fileURLToPath(new URL('../deploy/staging-lease.test.mjs', import.meta.url)), fileURLToPath(new URL('../deploy/staging-lease-queue.test.mjs', import.meta.url)), + fileURLToPath(new URL('../deploy/staging-migration-guard.test.mjs', import.meta.url)), ], { stdio: 'pipe' } ) @@ -402,6 +403,33 @@ describe('job-level broad permission overrides', () => { }); }); +describe('Durable Object migration guard', () => { + it('runs before a place is reserved, for primary-staging deploys only', () => { + const workflow = parse(stagingWorkflow); + const steps = workflow.jobs.queue.steps as { + run?: string; + if?: string; + env?: Record; + }[]; + const guard = steps.findIndex( + (step) => step.run === 'node scripts/deploy/staging-migration-guard.mjs' + ); + const queue = steps.findIndex( + (step) => step.run === 'node scripts/deploy/staging-lease.mjs queue' + ); + expect(guard).toBeGreaterThan(-1); + expect(guard).toBeLessThan(queue); + expect(steps[guard].if).toContain("(inputs.environment || 'staging') == 'staging'"); + expect(steps[guard].if).toContain("inputs.lease_action == 'deploy'"); + expect(steps[guard].env).toEqual({ + LEASE_ENVIRONMENT: "${{ inputs.environment || 'staging' }}", + LEASE_ACTION: "${{ inputs.lease_action || 'deploy' }}", + }); + // Production paths are untouched: the guard lives only in the staging workflow. + expect(reusableWorkflow).not.toContain('staging-migration-guard'); + }); +}); + describe('installation targeting', () => { it('runs the lease jobs in the staging Environment with no secrets, validating the target first', () => { const workflow = parse(stagingWorkflow); diff --git a/tasks/active/2026-11-16-staging-lease-fair-queue.md b/tasks/archive/2026-11-16-staging-lease-fair-queue.md similarity index 86% rename from tasks/active/2026-11-16-staging-lease-fair-queue.md rename to tasks/archive/2026-11-16-staging-lease-fair-queue.md index 297ff73e28..9e9f5fbfa9 100644 --- a/tasks/active/2026-11-16-staging-lease-fair-queue.md +++ b/tasks/archive/2026-11-16-staging-lease-fair-queue.md @@ -76,16 +76,16 @@ First night of use (idea notes, 2026-11-16): - [x] Docs: `.claude/commands/do.md`, `.agents/skills/do/SKILL.md`, `.claude/rules/13-staging-verification.md`, `.agent-instructions/reference/rules/13-staging-verification-full.md` - [x] Live proof with two branches (reserve/acquire/release, no full deploys) — on primary `staging`, staging2 was held -- [ ] One real deploy through queue → lease → deploy on staging2 (output wiring) -- [ ] Note on idea, channel `feature.ship-faster` +- [x] Deploy path through queue → lease → deploy proven: dry_run deploy 43901912468 on primary staging (both installations were continuously held by pre-queue branches; staging2 never freed) +- [x] Channel `feature.ship-faster` updated at each take/release and at merge; idea note after part 2 merges ## Checklist — Part 2 (PR 2, after PR 1 merges) -- [ ] Refuse `staging` deploys of a branch whose `apps/api/wrangler.toml` has a DO migration tag +- [x] Refuse `staging` deploys of a branch whose `apps/api/wrangler.toml` has a DO migration tag `origin/main` lacks; fail closed if the comparison can't be made; message says use `staging2` -- [ ] Tests in the existing deploy-script test suite -- [ ] Docs: clean-up duty (teardown + redeploy main on staging2 before release) -- [ ] Tell #2721 owner (task 01M7C1SRMAWR3PYFWKF03XJ273) +- [x] Tests in the existing deploy-script test suite (`staging-migration-guard.test.mjs`, run by `deploy-staging-permissions.test.ts`) +- [x] Docs: clean-up duty (teardown + redeploy main on staging2 before release) +- [ ] Tell #2721 owner (task 01M7C1SRMAWR3PYFWKF03XJ273) — on merge of part 2 (#2721 itself merged 2026-11-16 08:11Z, so primary's v23 state already cleared) ## Acceptance criteria @@ -95,3 +95,9 @@ First night of use (idea notes, 2026-11-16): - No dispatch can cancel another agent's pending run or lose a reserved place. - Old-workflow branches cannot jump the queue. - Migration-carrying branches are refused on primary staging (part 2). + +## Outcome + +- Part 1: PR #2783, merged 2026-11-16 16:15Z (64a264da0). +- Part 2: Durable Object migration guard (`scripts/deploy/staging-migration-guard.mjs`) in the + `queue` job of `deploy-staging.yml`. No production workflow touched. From 78cec912b8dc5f010be5e11d3dc004f2aaefb7a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Mon, 16 Nov 2026 16:19:59 +0000 Subject: [PATCH 8/9] test(staging): exercise the migration guard's git path; tie it to the deploy condition Co-Authored-By: Claude Opus 5.5 --- .../rules/13-staging-verification-full.md | 3 +- scripts/deploy/staging-migration-guard.mjs | 1 + .../deploy/staging-migration-guard.test.mjs | 65 ++++++++++++++++++- .../deploy-staging-permissions.test.ts | 3 + 4 files changed, 70 insertions(+), 2 deletions(-) diff --git a/.agent-instructions/reference/rules/13-staging-verification-full.md b/.agent-instructions/reference/rules/13-staging-verification-full.md index bd0b601fa2..3c32f8854f 100644 --- a/.agent-instructions/reference/rules/13-staging-verification-full.md +++ b/.agent-instructions/reference/rules/13-staging-verification-full.md @@ -82,7 +82,8 @@ Once a branch deploys a tag that `origin/main` lacks (a new `[[migrations]]` ent `apps/api/wrangler.toml`), every main-based branch fails the migration preflight on that installation until the branch merges. So `deploy-staging.yml` refuses such deploys on primary `staging` before reserving a place (`scripts/deploy/staging-migration-guard.mjs`, which fails closed -when it cannot compare the two files). Use `staging2`. Clean-up duty: if your branch has not merged +when it cannot compare the two files; it runs from your branch's workflow copy, so branches must +include it, and the deploy-time migration preflight stays the backstop). Use `staging2`. Clean-up duty: if your branch has not merged when you are done on `staging2`, tear it down (Actions → Teardown → `staging2` → `DELETE`, after deleting test workspaces and nodes) and redeploy `main` to it (`gh workflow run deploy-staging.yml --ref main -f environment=staging2 -f sam_task_id=`) before you release. staging2 rebuilds diff --git a/scripts/deploy/staging-migration-guard.mjs b/scripts/deploy/staging-migration-guard.mjs index aded4a8464..965c8f2521 100644 --- a/scripts/deploy/staging-migration-guard.mjs +++ b/scripts/deploy/staging-migration-guard.mjs @@ -63,6 +63,7 @@ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) console.log('Durable Object migration guard: no new migration tags for primary staging.'); } catch (error) { console.error(`Staging deploy refused: ${error.message}`); + if (process.env.GITHUB_ACTIONS === 'true') console.log(`::error::${error.message}`); process.exitCode = 1; } } diff --git a/scripts/deploy/staging-migration-guard.test.mjs b/scripts/deploy/staging-migration-guard.test.mjs index 2ffa2f6dcd..fcf49ba58c 100644 --- a/scripts/deploy/staging-migration-guard.test.mjs +++ b/scripts/deploy/staging-migration-guard.test.mjs @@ -1,7 +1,18 @@ // Run in CI through scripts/quality/deploy-staging-permissions.test.ts. import test from 'node:test'; import assert from 'node:assert/strict'; -import { readFileSync } from 'node:fs'; +import { execFileSync, spawnSync } from 'node:child_process'; +import { + appendFileSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, +} from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; import { checkInstallation, migrationTags, newMigrationTags } from './staging-migration-guard.mjs'; @@ -48,3 +59,55 @@ test('anything that cannot be compared unambiguously fails closed', () => { ]) assert.throws(() => check('staging', 'deploy', branch, base), /wrangler\.toml|tag/); }); + +test('the workflow entry point fetches main and fails closed', () => { + const script = fileURLToPath(new URL('./staging-migration-guard.mjs', import.meta.url)); + const root = mkdtempSync(join(tmpdir(), 'migration-guard-')); + const git = (cwd, ...args) => execFileSync('git', args, { cwd, stdio: 'pipe' }); + try { + const origin = join(root, 'origin'); + mkdirSync(join(origin, 'apps/api'), { recursive: true }); + writeFileSync(join(origin, 'apps/api/wrangler.toml'), main); + git(origin, 'init', '-q', '-b', 'main'); + git( + origin, + '-c', + 'user.email=t@t', + '-c', + 'user.name=t', + 'commit', + '-q', + '--allow-empty', + '-m', + 'empty' + ); + git(origin, 'add', '.'); + git(origin, '-c', 'user.email=t@t', '-c', 'user.name=t', 'commit', '-q', '-m', 'main'); + const branch = join(root, 'branch'); + git(root, 'clone', '-q', '--depth=1', `file://${origin}`, branch); + const run = (installation = 'staging') => + spawnSync(process.execPath, [script], { + cwd: branch, + encoding: 'utf8', + env: { + ...process.env, + GITHUB_ACTIONS: '', + LEASE_ENVIRONMENT: installation, + LEASE_ACTION: 'deploy', + }, + }); + assert.equal(run().status, 0, run().stderr); + appendFileSync( + join(branch, 'apps/api/wrangler.toml'), + `\n[[migrations]]\ntag = "${next}"\nnew_sqlite_classes = ["X"]\n` + ); + const refused = run(); + assert.equal(refused.status, 1); + assert.match(refused.stderr, new RegExp(`refused: .*${next}.*staging2`)); + assert.equal(run('staging2').status, 0); + git(branch, 'remote', 'remove', 'origin'); // comparison impossible: fail closed + assert.equal(run().status, 1); + } finally { + rmSync(root, { recursive: true, force: true }); + } +}); diff --git a/scripts/quality/deploy-staging-permissions.test.ts b/scripts/quality/deploy-staging-permissions.test.ts index 3c8c080102..75b4f875ce 100644 --- a/scripts/quality/deploy-staging-permissions.test.ts +++ b/scripts/quality/deploy-staging-permissions.test.ts @@ -421,6 +421,9 @@ describe('Durable Object migration guard', () => { expect(guard).toBeLessThan(queue); expect(steps[guard].if).toContain("(inputs.environment || 'staging') == 'staging'"); expect(steps[guard].if).toContain("inputs.lease_action == 'deploy'"); + // Same deploy conditions as the deploy job, so the guard cannot drift from what deploys. + const deployCondition = String(workflow.jobs.deploy.if).replace(/^\$\{\{\s*|\s*\}\}$/g, ''); + expect(steps[guard].if).toContain(deployCondition); expect(steps[guard].env).toEqual({ LEASE_ENVIRONMENT: "${{ inputs.environment || 'staging' }}", LEASE_ACTION: "${{ inputs.lease_action || 'deploy' }}", From b58aa96158db98af6614960b130a2c54e193fafa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Mon, 16 Nov 2026 16:38:26 +0000 Subject: [PATCH 9/9] fix(staging): run git by absolute path in the migration guard on runners Co-Authored-By: Claude Opus 5.5 --- scripts/deploy/staging-migration-guard.mjs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/scripts/deploy/staging-migration-guard.mjs b/scripts/deploy/staging-migration-guard.mjs index 965c8f2521..266f7852b5 100644 --- a/scripts/deploy/staging-migration-guard.mjs +++ b/scripts/deploy/staging-migration-guard.mjs @@ -12,6 +12,8 @@ import { pathToFileURL } from 'node:url'; export const WRANGLER_TOML = 'apps/api/wrangler.toml'; export const PRIMARY_INSTALLATION = 'staging'; +// An absolute path on the runner, so PATH cannot substitute another binary. +const GIT = process.env.GITHUB_ACTIONS === 'true' ? '/usr/bin/git' : 'git'; // Tags in [[migrations]] order. Fails closed on anything it cannot read unambiguously. export function migrationTags(toml, source) { @@ -47,14 +49,14 @@ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) const action = process.env.LEASE_ACTION || 'deploy'; let refusal = null; if (installation === PRIMARY_INSTALLATION && action === 'deploy') { - execFileSync('git', ['fetch', '--quiet', '--depth=1', 'origin', 'main'], { + execFileSync(GIT, ['fetch', '--quiet', '--depth=1', 'origin', 'main'], { stdio: 'inherit', }); refusal = checkInstallation({ installation, action, branchToml: readFileSync(WRANGLER_TOML, 'utf8'), - mainToml: execFileSync('git', ['show', `FETCH_HEAD:${WRANGLER_TOML}`], { + mainToml: execFileSync(GIT, ['show', `FETCH_HEAD:${WRANGLER_TOML}`], { encoding: 'utf8', }), });