Skip to content

feat(infra): production stacks in AWS CDK - #520

Merged
allisonmahmood merged 1 commit into
mainfrom
infra/415-cdk
Oct 4, 2026
Merged

allisonmahmood merged 1 commit into
mainfrom
infra/415-cdk

Conversation

@allisonmahmood

@allisonmahmood allisonmahmood commented Oct 4, 2026 •

Copy link
Copy Markdown
Owner

What changed

Production had no infrastructure in code. The tier 2 spike runs on a hand-built stack driven by scripts/tier2-spike.mjs, and nothing describes the network, load balancer, hosts, exec task definition, secrets or alerts that #416 will deploy.

apps/infra is a CDK app with two stacks per environment, named from context (-c environment=production), so a staging stack later is one more command. Nothing in it is deployed by this PR.

Base stack (deploys first, outlives releases): the ECR repository with immutable tags and the last 30 images kept; the GitHub OIDC provider and a deploy role trusted only for this repo's production environment; the $300 forecast budget emailing the alert addresses; the host secret, declared without a value; and the fleet management secret with two slots, a (generated once) and b (empty until a rotation writes into it). The provider and budget are account-wide, so only production declares them.

App stack (one release, pinned to an image digest):

  • VPC: two public subnets for the ALB and hosts (public IPs, no NAT), and an isolated exec subnet whose only ways out are ECR API/Docker and Logs interface endpoints and an S3 gateway endpoint. No Secrets Manager endpoint.
  • Security groups: ALB, host, exec-bootstrap, exec-sealed and endpoints, with the rules from docs/OPERATIONS.md. The endpoint group admits the hosts too, since private DNS covers the whole VPC (the prototype's live finding).
  • ALB: 443 with the existing certificate (from context), 80 redirecting, HTTP/2, 3,600 s idle timeout. The target group has app-cookie stickiness on patchy_stream_affinity, a 90 s deregistration delay and the shallow /healthz check.
  • Hosts: two tasks at 0.5 vCPU / 2 GB, rolling 100/200, circuit breaker with rollback, user 1000, stop timeout 120 s. Settings come from the host secret by key; the host task role is the fleet policy, scoped to this cluster and the exec family.
  • Exec: a CfnTaskDefinition with no task role, user 0, the spike's capability drops, port 8788, and its own execution role (ECR pull and logs only).
  • Uptime: a Route 53 HTTPS check on /healthz/deep → CloudWatch alarm → SNS email.
  • Host config: NODE_ENV=production, PATCHY_ENVIRONMENT, the public origin and authorized party, PATCHY_TRUST_PROXY set to the VPC range, fleet budget 15, the deployment revision, and the ECS_*/EXECUTION_* settings from the stack.

Tests and CI. A vitest synthesizes both stacks offline and snapshots every security group and rule. It also pins the stickiness and ALB attributes, circuit-breaker rollback, the credential-free exec definition, the previous-release mapping, and the secrets' shapes. CI's lint job and pnpm check run cdk synth with example context; it runs with no network at all (no credentials, lookups, notices or telemetry). Account ids, the certificate ARN and alert addresses come only from context.

Choices worth checking

  • The host secret is in the base stack, not the app stack. Hosts can't start until a person fills it, so an app stack that created it would fail its first deploy and roll the secret away. This matches chore(infra): the first deploy of Patchy to AWS #416's order: deploy the base stack, fill the secret, then the first release.
  • Every release names the slot its hosts read, and the promoted release as previous (its revision, exec task definition and slot). Until promotion the fleet still replenishes the promoted revision's spares, and a host that can't launch that revision would reserve tasks it can never start or stop, holding fleet budget for good. For the same reason, replaced exec task definitions are retained (UpdateReplacePolicy: Retain). The deploy role may read and write the SSM parameter where PR 3's workflow records the promoted release, and stop promote tasks a cancelled run left behind.
  • Closed egress. CDK drops its inline "no traffic" egress placeholder when every egress rule of a group names another group, which leaves AWS's default allow-all in place. The ALB and exec-bootstrap groups put it back, and the test fails if any group but the hosts' lacks inline egress.
  • exec-sealed keeps the spike's one rule (8788 from hosts) and no egress. The S3 prefix list pl-63a5400a is AWS's managed list for us-east-1, the same in every account.

Second of three stacked PRs for #415. Based on #519 (infra/415-server): the uptime check targets PR 1's /healthz/deep, and the hosts set PR 1's PATCHY_ENVIRONMENT. Part of #415.

How it was verified

  • pnpm check and pnpm verify pass locally; cdk synth runs inside a network-less namespace
  • Added apps/infra/src/stacks.test.ts (security-group snapshot and contract checks)

Release impact

  • Breaking
  • Not breaking — a new package; nothing is deployed

Made by Claude Opus 5.5 (1M context) via Claude Code, in T3 Code.

@allisonmahmood

Copy link
Copy Markdown
Owner Author

Codex review (GPT 6.1 Sol, xhigh), two rounds before the first push. Round two found nothing new in this PR. Fixes that came from reviewing #521 changed this PR too:

  • Fixed: every release now names the promoted release as previous. Before, a plain release had no previous-revision mapping. Staged housekeeping still replenishes the promoted revision's spares, and the ECS provider refuses to start a revision it has no mapping for. drainTask can then never stop those reserved rows, so they would hold fleet budget for good. AppStack now takes previous (revision, exec task definition, and the management secret's current key, or previous mid-rotation) on every release but the first. The stacks test pins the mapping, and the deploy role may read and write the parameter that records the promoted release.

Dismissed:

  1. Minor: pl-63a5400a is a hardcoded resource id in a public repo. Dismissed. It is AWS's managed S3 prefix list for us-east-1: the same public id in every account, not a Patchy resource, and it reveals nothing about this deployment.
  2. Nit: the Co-Authored-By trailer's address. Dismissed. This is the repo's attribution convention, carried by every commit on main.

@github-actions github-actions Bot added area:ci CI, shared testing infrastructure, development scripts and tooling area:docs Touches the docs area size:xl Over 1,000 changed lines; review in multiple passes labels Oct 4, 2026
@allisonmahmood
allisonmahmood force-pushed the infra/415-cdk branch 2 times, most recently from ed438c6 to 54bf960 Compare October 4, 2026 15:32
Base automatically changed from infra/415-server to main October 4, 2026 19:22
Production had no infrastructure in code: the tier 2 spike ran on a
hand-built stack driven by a script.

apps/infra is a CDK app with two stacks per environment, named by
context so staging is one more command. The base stack holds what
outlives a release: the ECR repository (immutable tags, 30 images
kept), the GitHub OIDC provider and a deploy role trusted only for the
repo's environment of the same name, the $300 forecast budget, the
host secret declared without a value, and the fleet management secret
with two slots, `a` generated once and `b` empty until a rotation writes
into it. The provider and budget are account-wide, so only
production declares them. The secrets live here rather than in the app
stack because a host cannot start until a person has filled the host
secret.

The app stack is a release pinned to an image digest: the VPC with
public subnets for the ALB and hosts and an isolated exec subnet with
ECR, logs and S3 endpoints; the ALB on 443 with the existing
certificate, 80 redirecting, HTTP/2, a 3,600 s idle timeout and
patchy_stream_affinity stickiness; two hosts at 0.5 vCPU / 2 GB with a
rolling update and circuit-breaker rollback; the exec task definition
with no task role, retained across releases; the host role's fleet
policy; and a Route 53 check on /healthz/deep that emails through SNS.
Each release names the slot its hosts read, and the release the fleet
is promoted to as its previous revision, exec task definition and slot:
until promotion the fleet still replenishes that revision's spares, and
a host that cannot launch them would strand the tasks it reserved. The
deploy role may read and write the parameter that records the promoted
release, and stop promote tasks a cancelled run left behind.

Every security group closes its egress inline except the hosts': CDK
drops its placeholder when a group's egress rules all name other
groups, which would leave AWS's default allow-all in place.

A vitest synthesizes both stacks offline and snapshots every security
group and rule; CI and pnpm check also run cdk synth with example
context, with no credentials, lookups, notices or telemetry. Account
ids, the certificate and alert addresses come only from context.

Part of #415.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@allisonmahmood
allisonmahmood merged commit 237eb3e into main Oct 4, 2026
13 checks passed
@allisonmahmood
allisonmahmood deleted the infra/415-cdk branch October 4, 2026 19:31
allisonmahmood added a commit that referenced this pull request Oct 4, 2026
…oduction runbooks (#521)

# What changed

Nothing could deploy the CDK stacks. The spike promoted the fleet with an inline `node -e` script, and the docs still said production was unbuilt.

**`.github/workflows/deploy.yml`** runs on `workflow_dispatch` from `main` only. It is gated by the `production` environment's reviewer and runs one at a time (concurrency group). It:
1. refuses commits that are not on `main`, and assumes the deploy role through OIDC;
2. stops any promote task a cancelled run left behind;
3. decides, from the release record, the secret slot this release reads and the release it rolls out beside, and records it as pending;
4. builds the reproducible server image (the `server-image.yml` steps);
5. deploys the base stack;
6. pushes the image to ECR with `crane`, tagged with the commit. On a rollback the tag already exists, and the run checks the rebuilt digest matches it;
7. deploys the app stack, pinned to the digest, with the promoted release as its previous revision. CloudFormation waits for ECS; a host that can't start trips the circuit breaker, and the update rolls back;
8. runs `node dist/fleet.js promote <revision>` as a one-off task from the host task definition, after ECS has settled, and records the release as promoted;
9. confirms the service's primary deployment is on the new task definition.

**The release record.** The SSM parameter `/patchy/production/promoted-release` is written only by the workflow, never by CloudFormation. It holds the promoted release and, while one is unfinished, the release being promoted, each with the management secret slot it reads and the previous release it was deployed beside. A release is pending from before anything deploys until its promotion. A release is marked pending before promotion and promoted after. Each release takes its previous settings from this record, not from the deployed stack: a run that deployed hosts but didn't promote leaves the fleet on the release before it. A re-run reuses its release's recorded settings. While a promotion is unfinished (failed, timed out or cancelled), the workflow refuses any other release until that run is re-run or the promoted commit is released again.

**Fleet promote.** `Fleet.promote` (in `packages/execution`) stages the revision, waits up to five minutes for its hosts to warm spares, and promotes it. It only moves rollout rows, so it needs no task provider (the spike's script built a whole ECS provider with hand-fed callback URLs). It refuses a revision no host has registered, and returns at once for one already promoted. `apps/server/src/fleet.ts` is the `dist/fleet.js` entrypoint; the image build now requires it.

**Docs.** `docs/OPERATIONS.md` gains Production: setup, deploy, rollback, restore and secret-rotation runbooks, and names the host log group. ADR-0012 gains the production topology. README, AGENTS, product, ADR-0004/0010 and the API docs now say production is written but not yet deployed.

**Choices worth checking**
- **Rotation.** The management secret stays constant across releases, as the issue decided. It has two slots, and a release reads one. Rotation writes the new secret into the idle slot, where no running host looks. The overlap deploy moves to that slot and reaches the old release's tasks through the old one, and the seal stays on the new slot. So a failure or rollback at any step leaves both slots readable, and no step writes back an old value. Each rotation deploy needs a revision different from the running one, or the ECS provider refuses to start, so the `rotation` input (release / overlap / seal) names those runs `<commit>-overlap-<run>` and `<commit>-seal-<run>`. Rotation needs no new commits.
- **Public run logs.** The account id, certificate ARN and alert addresses are **environment secrets**, not variables. None is secret, but GitHub prints each step's environment in this public repo's logs and masks only secrets. CDK's stack outputs and resource ids are filtered out of the log, and the promote task's output stays in CloudWatch.

**What a restore can't do.** Neon's branch restore does not revert Object Storage ([Neon](https://neon.com/docs/postgres/backup-restore/branch-restore)), so the runbook says which bytes a restore can't bring back. It also says that fleet rows for tasks ECS has forgotten keep holding fleet budget: the controller never treats a missing task as stopped, and nothing clears such rows yet.

The workflow deploys #520's stacks and reads their outputs. Closes #415.

## How it was verified

- [x] `pnpm check` and `pnpm verify` pass locally; actionlint and shellcheck pass on the workflow
- [x] Added a `Fleet.promote` case to `packages/execution/src/Fleet.test.ts`: it refuses an unregistered revision, promotes once spares are warm, and returns at once on a rerun

Nothing has been deployed: the workflow can't run until #416's setup is done.

## Release impact

- [ ] **Breaking**
- [x] **Not breaking** — a new workflow and entrypoint; nothing runs until someone dispatches it

Made by Claude Opus 5.5 (1M context) via Claude Code, in T3 Code.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:ci CI, shared testing infrastructure, development scripts and tooling area:docs Touches the docs area size:xl Over 1,000 changed lines; review in multiple passes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant