Multiplayer agent harness for work.
Make AWS RDS instance class configurable (#1532)
Sina Matian9f88e327c03c
diff --git a/.github/workflows/cicd.yml b/.github/workflows/cicd.ymlindex 1d0f2c8f0..b63bbef42 100644--- a/.github/workflows/cicd.yml+++ b/.github/workflows/cicd.yml@@ -78,8 +78,15 @@ jobs:cache-dependency-path: |cli/package-lock.jsonpackage-lock.json+ - uses: hashicorp/setup-terraform@b9cd54a3c349d3f38e8881555d616ced269862dd+ with:+ terraform_version: 1.15.8+ terraform_wrapper: false- name: Install, typecheck, unit + packaged-artifact + e2e testsworking-directory: cli+ env:+ QM_TERRAFORM_BIN: terraform+ QM_TEST_TERRAFORM: terraformrun: |npm cinpm run typecheckdiff --git a/cli/src/config.ts b/cli/src/config.tsindex 5ba969f86..03a8c2b2c 100644--- a/cli/src/config.ts+++ b/cli/src/config.ts@@ -93,6 +93,7 @@ export interface AwsConfig {sharedAlb?: boolean;backgroundWorkControl?: boolean;rdsInstance?: string;+ dbInstanceClass?: string;predeployDbSnapshot?: boolean;dbRetentionMinDays?: number;deployBranch?: string;@@ -1195,6 +1196,13 @@ function validateAws(}}let predeployDbSnapshot: boolean | undefined;+ let dbInstanceClass: string | undefined;+ if (raw["dbInstanceClass"] !== undefined) {+ dbInstanceClass = requiredString(raw["dbInstanceClass"], "dbInstanceClass");+ if (!/^db\.[a-z0-9]+\.[a-z0-9]+$/.test(dbInstanceClass)) {+ throw new CliError(`${path}: "aws.dbInstanceClass" must be a valid RDS DB instance class such as db.t4g.small`);+ }+ }if (raw["predeployDbSnapshot"] !== undefined) {if (typeof raw["predeployDbSnapshot"] !== "boolean") {throw new CliError(@@ -1486,6 +1494,7 @@ function validateAws(`${path}: controlled core service names must leave room for a unique deployment identity (maximum 219 characters)`,);if (rdsInstance) out.rdsInstance = rdsInstance;+ if (dbInstanceClass) out.dbInstanceClass = dbInstanceClass;if (predeployDbSnapshot !== undefined) out.predeployDbSnapshot = predeployDbSnapshot;if (dbRetentionMinDays !== undefined) out.dbRetentionMinDays = dbRetentionMinDays;if (deployBranch) out.deployBranch = deployBranch;diff --git a/cli/src/terraform.ts b/cli/src/terraform.tsindex 2172f8baf..98525ed10 100644--- a/cli/src/terraform.ts+++ b/cli/src/terraform.ts@@ -23,6 +23,7 @@ const DERIVED_VARS = new Set(["transfer_lifecycle_prefix","deploy_microvm_image","deploy_microvm_execution_role_arn",+ "db_instance_class","services","secret_names",]);@@ -202,6 +203,9 @@ function derivedValues(deploy_microvm_image: config.env.core?.AWS_DEPLOY_IMAGE?.trim() || config.orgId,deploy_microvm_execution_role_arn:config.env.core?.AWS_DEPLOY_EXEC_ROLE_ARN ?? `arn:aws:iam::${aws.accountId}:role/${aws.cluster}-microvm-exec`,+ ...(declared.includes("db_instance_class") && aws.dbInstanceClass+ ? { db_instance_class: aws.dbInstanceClass }+ : {}),},json: {...(declared.includes("core_public_hosts") ? { core_public_hosts: [...new Set(corePublicHosts)].sort() } : {}),@@ -232,6 +236,10 @@ export function terraformVars(const { strings, json } = derivedValues(config, declared, managedTaskRoles(existing));const line = (name: string, value: string): string => `${name.padEnd(19)} = ${value}`;const lines = Object.entries(strings).map(([name, value]) => line(name, JSON.stringify(value)));+ if (!config.aws?.dbInstanceClass && declared.includes("db_instance_class")) {+ const preserved = hclAssignment(existing, "db_instance_class");+ if (preserved !== undefined) lines.push(preserved);+ }for (const name of new Set([...Object.keys(OPERATOR_DEFAULTS), ...declared])) {if (DERIVED_VARS.has(name)) continue;const preserved = hclAssignment(existing, name);@@ -271,13 +279,22 @@ export function assertTerraformScaffoldSupportsConfig(config: QmConfig, configDiconst services = Object.values(config.aws?.services ?? {});const hasPublicPaths = services.some((service) => service?.publicPaths?.length);const hasAssumeRoles = services.some((service) => service?.assumeRoleArns !== undefined);- if (!hasPublicPaths && !hasAssumeRoles) return;+ const hasDatabaseOverrides = config.aws?.dbInstanceClass !== undefined;+ if (!hasPublicPaths && !hasAssumeRoles && !hasDatabaseOverrides) return;const tfvarsPath = join(configDir, "infra", "terraform.tfvars");if (!existsSync(tfvarsPath)) return;const variablesPath = join(configDir, "infra", "variables.tf");const mainPath = join(configDir, "infra", "main.tf");const variables = existsSync(variablesPath) ? readFileSync(variablesPath, "utf8") : "";const main = existsSync(mainPath) ? readFileSync(mainPath, "utf8") : "";+ if (+ hasDatabaseOverrides &&+ (!/variable\s+"db_instance_class"/.test(variables) || !/instance_class\s*=\s*var\.db_instance_class/.test(main))+ ) {+ throw new CliError(+ "the vendored AWS scaffold predates aws.dbInstanceClass; update infra/variables.tf and infra/main.tf from the current scaffold before configuring it",+ );+ }if (hasPublicPaths && (!/public_paths\s*=\s*optional/.test(variables) || !/public_path_services\s*=/.test(main))) {throw new CliError("the vendored AWS scaffold predates aws.services.*.publicPaths; update infra/variables.tf and infra/main.tf before exposing plugins",diff --git a/cli/templates/aws/main.tf b/cli/templates/aws/main.tfindex 7ff85f3bd..ad1557434 100644--- a/cli/templates/aws/main.tf+++ b/cli/templates/aws/main.tf@@ -610,7 +610,7 @@ resource "aws_db_instance" "this" {identifier = "${var.cluster_name}-core"engine = "postgres"engine_version = "16"- instance_class = "db.t4g.small"+ instance_class = var.db_instance_classallocated_storage = 20db_name = var.db_nameusername = var.db_usernamediff --git a/cli/templates/aws/variables.tf b/cli/templates/aws/variables.tfindex f457d3410..23a55d1fb 100644--- a/cli/templates/aws/variables.tf+++ b/cli/templates/aws/variables.tf@@ -85,6 +85,14 @@ variable "db_username" {type = stringdefault = "qm"}+variable "db_instance_class" {+ type = string+ default = "db.t4g.small"+ validation {+ condition = can(regex("^db\\.[a-z0-9]+\\.[a-z0-9]+$", var.db_instance_class))+ error_message = "db_instance_class must be a valid RDS DB instance class such as db.t4g.small"+ }+}variable "db_backup_retention_days" {type = numberdefault = 35diff --git a/cli/templates/deployment/references/aws.md b/cli/templates/deployment/references/aws.mdindex c46067ac9..99cf5bc82 100644--- a/cli/templates/deployment/references/aws.md+++ b/cli/templates/deployment/references/aws.md@@ -22,6 +22,34 @@ the account, region, service coordinates, and an operator-owned GitHubrepository and exact branch in the generated config and Terraform variables.Never trust the upstream QM repository.+The account must permit the selected RDS class and backup retention in the+configured region and account plan. Set `aws.dbInstanceClass` before+`qm infra render` to override the `db.t4g.small` default. Set+`db_backup_retention_days` in `infra/terraform.tfvars` to override the 35-day+retention default. `aws.dbRetentionMinDays` only sets the minimum that `qm up`+accepts during its restore-point check and does not configure RDS.+Confirm all other billable AWS resources separately; this deployment does not+promise whole-stack free-tier compatibility.++Upgrading the CLI does not update an existing deployment's vendored Terraform.+Before setting `aws.dbInstanceClass`, preserve all local Terraform and tfvars+customizations, add this variable to `infra/variables.tf`, and change only the+RDS `instance_class` assignment in `infra/main.tf` to+`instance_class = var.db_instance_class`:++```hcl+variable "db_instance_class" {+ type = string+ default = "db.t4g.small"+ validation {+ condition = can(regex("^db\\.[a-z0-9]+\\.[a-z0-9]+$", var.db_instance_class))+ error_message = "db_instance_class must be a valid RDS DB instance class such as db.t4g.small"+ }+}+```++Then run `qm infra render` and review the Terraform plan before applying.+Configure a private encrypted Terraform backend, then:```bashdiff --git a/cli/test/config.test.ts b/cli/test/config.test.tsindex 13db9480b..4ff9db475 100644--- a/cli/test/config.test.ts+++ b/cli/test/config.test.ts@@ -675,6 +675,14 @@ test("AWS validates release labels, unique coordinates, Fargate sizes, and ownedassert.throws(() => loadConfigAt(path), /aws\.rdsInstance/);});}+ withConfig({ target: "aws", aws: { ...aws, dbInstanceClass: "db.t4g.micro" } }, ({ path }) => {+ assert.equal(loadConfigAt(path).config.aws!.dbInstanceClass, "db.t4g.micro");+ });+ for (const dbInstanceClass of ["", "t4g.micro", "db.T4g.micro", "db.t4g", "db..micro", "db.t4g.nano.micro"]) {+ withConfig({ target: "aws", aws: { ...aws, dbInstanceClass } }, ({ path }) => {+ assert.throws(() => loadConfigAt(path), /aws\.dbInstanceClass/);+ });+ }for (const objectStoreBucket of ["legacy-bucket", "assets.acme.example", "192.168.5.bucket"]) {withConfig({ target: "aws", aws: { ...aws, objectStoreBucket } }, ({ path }) => {assert.equal(loadConfigAt(path).config.aws!.objectStoreBucket, objectStoreBucket);diff --git a/cli/test/e2e/aws-rds-config.e2e.test.ts b/cli/test/e2e/aws-rds-config.e2e.test.tsnew file mode 100644index 000000000..f57e0d30d--- /dev/null+++ b/cli/test/e2e/aws-rds-config.e2e.test.ts@@ -0,0 +1,167 @@+import { test } from "node:test";+import assert from "node:assert/strict";+import { readFileSync, writeFileSync } from "node:fs";+import { join } from "node:path";+import { spawnSync } from "node:child_process";+import { rmDir, runCli, tmp } from "./harness.ts";++function terraformExecutable(): string | undefined {+ const configured = process.env.QM_TEST_TERRAFORM;+ const executable = configured === undefined ? "terraform" : configured;+ const result = spawnSync(executable, ["version"], { stdio: "ignore" });+ return result.status === 0 ? executable : undefined;+}++function configureClass(dir: string, value: string): void {+ const path = join(dir, "qm.config.jsonc");+ const source = readFileSync(path, "utf8");+ writeFileSync(+ path,+ source.replace(' "imageLabel": "latest",', ` "imageLabel": "latest",\n "dbInstanceClass": "${value}",`),+ );+}++function configureAwsCoordinates(dir: string): void {+ const path = join(dir, "qm.config.jsonc");+ writeFileSync(path, readFileSync(path, "utf8").replaceAll("000000000000", "123456789012"));+}++function configureTerraform(dir: string, retention?: number): void {+ const path = join(dir, "infra", "terraform.tfvars");+ const source = readFileSync(path, "utf8").replace(+ 'github_repository = "replace-me/repository"',+ 'github_repository = "example/deployment"',+ );+ writeFileSync(path, retention === undefined ? source : `${source}db_backup_retention_days = ${retention}\n`);+}++function writeTerraformTest(dir: string, instanceClass: string, retention: number): void {+ writeFileSync(+ join(dir, "infra", "database.tftest.hcl"),+ `mock_provider "aws" {+ mock_data "aws_availability_zones" {+ defaults = { names = ["us-west-2a", "us-west-2b"] }+ }+}+mock_provider "random" {}+run "plan" {+ command = plan+ assert {+ condition = aws_db_instance.this.instance_class == "${instanceClass}" && aws_db_instance.this.backup_retention_period == ${retention}+ error_message = "planned RDS configuration did not match"+ }+}+`,+ );+}++function terraform(dir: string, executable: string, args: string[]): string {+ const result = spawnSync(executable, [`-chdir=${join(dir, "infra")}`, ...args], {+ encoding: "utf8",+ timeout: 180_000,+ });+ const output = `${result.stdout ?? ""}${result.stderr ?? ""}`;+ assert.equal(result.status, 0, output);+ return output;+}++const terraformBin = terraformExecutable();+const terraformRequested = process.env.QM_TEST_TERRAFORM !== undefined;++test("AWS init and render validate RDS class config and preserve operator Terraform values", () => {+ const defaultDir = tmp("aws-rds-render-default");+ const overrideDir = tmp("aws-rds-render-override");+ const invalidDir = tmp("aws-rds-render-invalid");+ try {+ for (const [dir, org] of [+ [defaultDir, "rds-render-default"],+ [overrideDir, "rds-render-override"],+ [invalidDir, "rds-render-invalid"],+ ] as const) {+ const initialized = runCli(["init", dir, "--org", org, "--target", "aws", "--model-provider", "anthropic"]);+ assert.equal(initialized.code, 0, initialized.out);+ configureAwsCoordinates(dir);+ }++ configureTerraform(defaultDir);+ const defaultRendered = runCli(["infra", "render", "--config", join(defaultDir, "qm.config.jsonc")]);+ assert.equal(defaultRendered.code, 0, defaultRendered.out);+ assert.doesNotMatch(readFileSync(join(defaultDir, "infra", "terraform.tfvars"), "utf8"), /db_instance_class/);++ configureClass(overrideDir, "db.t4g.micro");+ configureTerraform(overrideDir, 7);+ const overridden = runCli(["infra", "render", "--config", join(overrideDir, "qm.config.jsonc")]);+ assert.equal(overridden.code, 0, overridden.out);+ const tfvars = readFileSync(join(overrideDir, "infra", "terraform.tfvars"), "utf8");+ assert.match(tfvars, /db_instance_class\s*= "db\.t4g\.micro"/);+ assert.match(tfvars, /db_backup_retention_days = 7/);++ configureClass(invalidDir, "t4g.micro");+ const rejected = runCli(["infra", "render", "--config", join(invalidDir, "qm.config.jsonc")]);+ assert.equal(rejected.code, 1, rejected.out);+ assert.match(rejected.out, /aws\.dbInstanceClass/);+ } finally {+ rmDir(defaultDir);+ rmDir(overrideDir);+ rmDir(invalidDir);+ }+});++test(+ "AWS init renders validated RDS class config into a local Terraform resource plan",+ { skip: !terraformRequested && !terraformBin ? "Terraform is unavailable" : false },+ () => {+ assert.ok(terraformBin, `QM_TEST_TERRAFORM is not executable: ${process.env.QM_TEST_TERRAFORM}`);+ const defaultDir = tmp("aws-rds-default");+ const overrideDir = tmp("aws-rds-override");+ try {+ for (const [dir, org] of [+ [defaultDir, "rds-default"],+ [overrideDir, "rds-override"],+ ] as const) {+ const initialized = runCli(["init", dir, "--org", org, "--target", "aws", "--model-provider", "anthropic"]);+ assert.equal(initialized.code, 0, initialized.out);+ configureAwsCoordinates(dir);+ }++ configureTerraform(defaultDir);+ const defaultRendered = runCli(["infra", "render", "--config", join(defaultDir, "qm.config.jsonc")]);+ assert.equal(defaultRendered.code, 0, defaultRendered.out);+ writeTerraformTest(defaultDir, "db.t4g.small", 35);++ configureClass(overrideDir, "db.t4g.micro");+ configureTerraform(overrideDir, 7);+ const rendered = runCli(["infra", "render", "--config", join(overrideDir, "qm.config.jsonc")]);+ assert.equal(rendered.code, 0, rendered.out);+ const tfvars = readFileSync(join(overrideDir, "infra", "terraform.tfvars"), "utf8");+ assert.match(tfvars, /db_instance_class\s*= "db\.t4g\.micro"/);+ assert.match(tfvars, /db_backup_retention_days = 7/);+ writeTerraformTest(overrideDir, "db.t4g.micro", 7);++ for (const dir of [defaultDir, overrideDir]) {+ terraform(dir, terraformBin, ["init", "-backend=false"]);+ const plan = terraform(dir, terraformBin, ["test", "-verbose"]);+ assert.match(plan, /Success!.*1 passed, 0 failed/s);+ }++ const overrideTfvars = join(overrideDir, "infra", "terraform.tfvars");+ writeFileSync(+ overrideTfvars,+ readFileSync(overrideTfvars, "utf8").replace(+ /db_instance_class\s*=\s*"db\.t4g\.micro"/,+ 'db_instance_class = "t4g.micro"',+ ),+ );+ const invalidPlan = spawnSync(terraformBin, [`-chdir=${join(overrideDir, "infra")}`, "test", "-verbose"], {+ encoding: "utf8",+ timeout: 180_000,+ });+ const invalidOutput = `${invalidPlan.stdout ?? ""}${invalidPlan.stderr ?? ""}`;+ assert.notEqual(invalidPlan.status, 0, invalidOutput);+ assert.match(invalidOutput, /db_instance_class must be a valid RDS DB instance class/);+ } finally {+ rmDir(defaultDir);+ rmDir(overrideDir);+ }+ },+);diff --git a/cli/test/init.test.ts b/cli/test/init.test.tsindex 249b42b4a..70639e754 100644--- a/cli/test/init.test.ts+++ b/cli/test/init.test.ts@@ -257,6 +257,7 @@ test("init --target aws scaffolds the full hosted topology, Terraform, and the oassert.match(tfvars, /github_repository\s*= "replace-me\/repository"/);assert.match(tfvars, /deploy_microvm_image\s*= "acme-qm-sandbox"/);assert.match(tfvars, /certificate_arn\s*= ""/);+ assert.doesNotMatch(tfvars, /db_instance_class/);assert.match(readFileSync(join(dir, "infra", "main.tf"), "utf8"), /desired_count\s*= 0/);const env = readFileSync(join(dir, ".env.example"), "utf8").split("\n");for (const name of ["ADMIN_GRANTS=", "PUBLIC_API_URL=", "AUTH_ALLOWED_EMAILS=", "ANTHROPIC_API_KEY="]) {diff --git a/cli/test/terraform.test.ts b/cli/test/terraform.test.tsindex 902f2db8a..08ba5d47f 100644--- a/cli/test/terraform.test.ts+++ b/cli/test/terraform.test.ts@@ -50,6 +50,7 @@ test("declaredVariables reads the scaffolded variables.tf", () => {"core_public_hosts","db_name","db_username",+ "db_instance_class","github_repository","github_subject_prefix","github_oidc_provider_arn",@@ -64,6 +65,27 @@ test("declaredVariables reads the scaffolded variables.tf", () => {}});+test("database class config renders only an explicit override", () => {+ const defaults = terraformVars(config, "", declared);+ assert.doesNotMatch(defaults, /db_instance_class/);++ const overridden = terraformVars(+ {+ ...config,+ aws: { ...config.aws!, dbInstanceClass: "db.t4g.micro" },+ },+ defaults,+ declared,+ );+ assert.match(overridden, /db_instance_class\s*= "db\.t4g\.micro"/);++ const upgraded = terraformVars(config, "db_backup_retention_days = 7\n", declared);+ assert.match(upgraded, /db_backup_retention_days = 7/);++ const operatorClass = terraformVars(config, 'db_instance_class = "db.m7g.large"\n', declared);+ assert.match(operatorClass, /db_instance_class = "db\.m7g\.large"/);+});+test("the ECS execution role can read every declared contract secret independent of Terraform state", () => {const policy = mainTf.match(/resource "aws_iam_role_policy" "task_secrets" \{([\s\S]*?)\n\}/)?.[1] ?? "";assert.match(policy, /secretsmanager:GetSecretValue/);@@ -305,6 +327,23 @@ test("assume-role config rejects vendored AWS scaffolds that predate workload ro}});+test("database class overrides reject vendored AWS scaffolds that cannot render them", () => {+ const dir = mkdtempSync(join(tmpdir(), "qm-legacy-database-"));+ try {+ const infra = join(dir, "infra");+ mkdirSync(infra);+ writeFileSync(join(infra, "terraform.tfvars"), "services = {}\n");+ writeFileSync(join(infra, "variables.tf"), 'variable "services" { type = map(any) }\n');+ writeFileSync(join(infra, "main.tf"), "");+ assert.throws(+ () => renderTerraformVars({ ...config, aws: { ...config.aws!, dbInstanceClass: "db.t4g.micro" } }, dir),+ /AWS scaffold predates aws\.dbInstanceClass/,+ );+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+});+test("the deploy role registers task definitions only for configured ECS families", () => {const policy = mainTf.match(/resource "aws_iam_role_policy" "github_deploy" \{([\s\S]*?)\n\}/)?.[1] ?? "";const management = policy.match(/Sid\s*= "ManageStackTaskDefinitions"([\s\S]*?)\n\s*\},/)?.[1] ?? "";@@ -697,6 +736,7 @@ test("AWS module provisions durable encrypted object storage and configurable samainTf,/id\s*= "qm-transfer-expiry"[\s\S]*?abort_incomplete_multipart_upload\s*\{\s*days_after_initiation\s*= 1\s*\}/,);+ assert.match(mainTf, /instance_class\s*= var\.db_instance_class/);assert.match(mainTf, /backup_retention_period\s*= var\.db_backup_retention_days/);assert.match(mainTf, /multi_az\s*= var\.db_multi_az/);assert.match(mainTf, /skip_final_snapshot\s*= var\.db_skip_final_snapshot/);diff --git a/docs/deploy-directory.md b/docs/deploy-directory.mdindex ad7b4d5d5..4987a46aa 100644--- a/docs/deploy-directory.md+++ b/docs/deploy-directory.md@@ -121,6 +121,10 @@ Postgres stores create their tables lazily with idempotent DDL through the shareThe normal gate order is `check`, `doctor`, `plan`, `up --yes`, then `check --live`. On AWS with MicroVM sandboxes, `infra build-image` precedes `plan`. First-party services come from the package's matching image manifest; `--build-from` explicitly builds modified services from a source fork or contributor checkout; use the checkout's CLI when changing deployment logic too. `check` is static and has JSON output keyed to clause ids. `doctor` makes read-only external checks. `plan` renders without mutation. On AWS, rollback restores the prior recorded deployment manifest as one unit under the deployment lease; `--to` selects another complete manifest by manifest id or recorded release label. Because rollback restores code and configuration but never data, it prints the pre-deploy database point-in-time restore timestamp recorded on the deployment it rolls back (or the legacy snapshot for older manifests). Fly and Docker do not claim rollback.+AWS `aws.dbInstanceClass` selects the RDS class rendered as `db_instance_class` and defaults to `db.t4g.small`. Operators set `db_backup_retention_days` in `infra/terraform.tfvars` to override its 35-day default. `aws.dbRetentionMinDays` is separate: it is the minimum retention that `qm up` accepts for its restore-point safety check and does not configure RDS. Before applying, the account must permit the chosen class and retention in the selected region and account plan; AWS availability and plan restrictions vary, and the rest of the deployment is not guaranteed to fit any free tier.++Upgrading the CLI alone does not update vendored Terraform. Existing deployments must preserve their customized Terraform and tfvars, copy only the validated `db_instance_class` variable (including its `db.t4g.small` default) from the current `infra/variables.tf` scaffold, and change only the RDS assignment to `instance_class = var.db_instance_class` before setting `aws.dbInstanceClass`; then run `qm infra render` and review the Terraform plan before applying.+AWS `up` is mutually excluded by a DynamoDB lease, verifies RDS continuous backups and records the exact pre-mutation restore point, registers digest-pinned task definitions, enables the ECS circuit breaker, updates services, and waits stable. AWS `check --live` compares environment, secret routing, task definitions, and the configured release label in both directions. Fly `check --live` verifies every configured workload has a live image-bearing machine and the public health endpoint responds. `qm conformance` remains the later cross-check between the static contract and core's resolved deployment-layer descriptors.The semver-stable `@yc-software/qm/contract` export contains only config loading, layer validation/parsing, env derivation, approval compilation, and the contract version; AWS task rendering joins it with the AWS backend. A new incompatible directory shape increments the contract major. A CLI may add optional fields within a major.