diff --git a/.agent-instructions/reference/rules/13-staging-verification-full.md b/.agent-instructions/reference/rules/13-staging-verification-full.md index 0b5a307557..4fab450970 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,73 +96,99 @@ 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. 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): ```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.** 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=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. 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 + 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..bed65a6b24 100644 --- a/.claude/commands/do.md +++ b/.claude/commands/do.md @@ -210,77 +210,81 @@ 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. - -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. 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): ```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.** 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=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`). + 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). @@ -306,6 +310,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 82e527fac1..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 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 `. 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. diff --git a/.github/workflows/deploy-staging.yml b/.github/workflows/deploy-staging.yml index 89b5192df2..d14aea45f7 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,12 @@ 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 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 @@ -92,10 +94,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 +109,8 @@ jobs: deployments: write 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 }} @@ -118,8 +125,48 @@ 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, 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' }} + runs-on: ubuntu-24.04 + environment: staging + timeout-minutes: 2 + concurrency: + group: staging-lease-${{ 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: + LEASE_TURN_CHECKED_AT: ${{ needs.queue.outputs.checked_at }} GH_TOKEN: ${{ github.token }} LEASE_ENVIRONMENT: ${{ inputs.environment || 'staging' }} LEASE_ACTION: ${{ inputs.lease_action || 'deploy' }} @@ -128,13 +175,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 +271,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 +306,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..979bf5c6fe --- /dev/null +++ b/scripts/deploy/staging-lease-queue.mjs @@ -0,0 +1,441 @@ +// 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; +// 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.'; + +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)) && + (entry.promisedEnd === undefined || validUtc(entry.promisedEnd)) + ); +} + +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, + // Held by a pre-queue workflow copy, which cannot read queue records (see runQueue). + legacyHold: held, + }; +} + +// 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. 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; + 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 && 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; + } + state.queue.push({ ...entry }); +} + +// 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 = complete; + 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); + else warnings.push(`Ignored lease record ${parsed.id} written while snapshot ${base.id} was`); + 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) { + 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; + 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; + } + // 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'; + const again = entry.lastReservedAt ? Date.parse(entry.lastReservedAt) : null; + 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, + 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, promisedEnd }) { + return { + branch, + taskId, + reservedAt, + expiresAt, + ...(lastReservedAt ? { lastReservedAt } : {}), + ...(promisedEnd ? { promisedEnd } : {}), + }; +} + +// 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 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, + 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((entry) => queueEntry({ ...entry, promisedEnd: iso(entry.end) })), + }; +} + +// 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 - ADMISSION_SLACK_GRACES * 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'; +} + +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, + turnCheckedAt = null, +}) { + 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) && + !hadTurn(state, branch, turnCheckedAt, now, graceMinutes) + ) + 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..c6de08701a --- /dev/null +++ b/scripts/deploy/staging-lease-queue.test.mjs @@ -0,0 +1,623 @@ +// 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( + (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; + 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 and never reaches the lease job. + const before = db.records.length; + 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, even by calling the lease job directly. + await dispatch(db, 'c', 'acquire', expiry + 3 * MIN); + 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 () => { + 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 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, + 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'); + // 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, + 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 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: { + 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 in the newest 500/); +}); + +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), []); +}); + +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']); +}); + +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 474cfc329d..ceff3a9c4e 100644 --- a/scripts/deploy/staging-lease.mjs +++ b/scripts/deploy/staging-lease.mjs @@ -1,9 +1,34 @@ +// 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_MAX_PAGES, + 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 +57,166 @@ 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' ); +} + +// 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; + } } - 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 { state, warnings } = await readRecords(api, environment); + return { state, warnings }; +} + +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') { + // 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 (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).` - ); + if (plan.holds) { + return { + proceed: action !== 'reserve', + warnings, + lines: [`Branch ${branch} holds ${environment} until ${plan.turns.holder.expiresAt}.`], + }; + } + 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.`, + ], + }; } - return action === 'release' ? 'released' : 'held'; + 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, + graceMinutes: timing.graceMinutes, + notice: OLD_WORKFLOW_NOTICE, + }, + }); + applyReservation(state, entry); + turns = resolveTurns(state, now, timing.graceMinutes); + } + 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, @@ -99,75 +227,176 @@ export async function runLease({ primaryOnlyAudit = false, timing, now = Date.now(), + turnCheckedAt = null, }) { - 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, + turnCheckedAt, + }); + 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 { 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; + } + }; + // 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 { + 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 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}\nchecked_at=${iso(checkedAt)}\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) }, + // 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, }); - 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..26670ba01d 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,82 @@ 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); + if ((query.get('page') ?? '1') !== '1') return []; + 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 +109,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..8cc295434c 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,69 @@ 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' }}"); + // 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: "staging-lease-${{ 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'); + 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', + '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 +393,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 +403,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 +422,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 new file mode 100644 index 0000000000..297ff73e28 --- /dev/null +++ b/tasks/active/2026-11-16-staging-lease-fair-queue.md @@ -0,0 +1,97 @@ +# 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 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. +- 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) + +- [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) +- [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 +- [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` +- [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) + +- [ ] 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).