Deployment Plan
Environments
Section titled “Environments”| Environment | Trigger | VPC | Aurora pause | Notes |
|---|---|---|---|---|
| Local | Developer-run | Docker Compose | N/A | No AWS resources; local DB replaces Aurora |
| QA | Auto on merge to main | Dedicated VPC, us-east-1 | Aggressive (0-ACU floor) | Full AWS stack; validates before Prod |
| Prod | Manual approval gate | Dedicated VPC, us-east-1 | Standard (0-ACU floor) | GitHub Environment protection rule (#28) |
What differs per environment: Aurora cluster ARN, Secrets Manager secret paths, API Gateway base URL, CloudWatch log group and alarm names, and Terraform remote state key prefix. All configuration is injected at deploy time via per-env Terraform roots; no application code branches on environment name.
Build Artifacts
Section titled “Build Artifacts”| Layer | Artifact | Tooling |
|---|---|---|
| Backend Lambda (API + authorizer) | The API and authorizer share one zip: the uv.lock export for the api extra plus the Hatchling-built project wheel, and both handlers import-smoked with the Data API environment variables set | .github/actions/build-lambda-package |
| Ingestion Lambda | Package undefined; whether this Lambda stays in target state is open in #399 | None |
| SPA bundle | Static assets (dist/) produced by Vite or equivalent React build | npm run build |
| Terraform | No artifact; plan output is ephemeral. Modules under infra/modules/; per-env roots under infra/roots/qa/ and infra/roots/prod/ | terraform plan, terraform apply |
| OpenAPI spec | backend/openapi.json committed to the app repo; regenerated in CI and diff-checked (RAG005) | make export-openapi |
The Lambda zip and the SPA bundle are built without cloud credentials. In qa-deploy.yml the build-package and build-frontend jobs declare no environment and no id-token grant, and hand the zip and dist/ to the credentialed jobs as workflow artifacts, so the package’s and bundle’s dependency installs (uv, npm ci), tsc, and Vite never run with the deploy role. The smoke job still runs uv sync --no-dev to install base dependencies after assuming the deploy role. The Workflow Checks workflow (check_credential_free_builds.py in the app repo) fails any job with id-token: write that runs npm, Vite, the Lambda zip build, or the eval scoring group.
The zip is uploaded to the Lambda-package bucket under a content-addressed key, and a deploy step after the Terraform apply points both functions at it with update-function-code, deduped by CodeSha256. The zip is byte-identical for an unchanged lock and source while the runner’s zlib is unchanged; a zlib change causes one redeploy. After that code deploy, the SPA bundle is synced to the environment-specific S3 bucket and a CloudFront invalidation is issued (deploy-frontend needs deploy), so the SPA never goes live ahead of the backend routes it calls.
Corpus Ingestion Sizing
Section titled “Corpus Ingestion Sizing”The QA/Prod corpus is neural-bridge/rag-dataset-12000, has Parquet files of ~23 MB, 12,000 documents and expand to 52,620 chunks. Chunking is single-threaded and CPU-cheap (seconds for the whole corpus). The dominant cost is embedding: every chunk is a separate Bedrock Titan call.
A single-worker local rag-ingest all against QA Aurora (embed batch size 16) took 7 hours. Sequential embedding accounted for nearly all of that wall-clock time. Treat the single-worker path as local and QA-verification only; it does not scale to a production re-ingest window.
Production-scale ingestion therefore runs as parallel out-of-VPC Lambda workers (RAG011 amendment). Each invocation is time-boxed (about 7 minutes) and claims work with FOR UPDATE SKIP LOCKED plus a lease: the ingest_pages control table for the load phase, lease columns on chunks for the embed phase. Many workers ingest concurrently, and a crashed or timed-out worker’s claim is recovered on lease expiry (600 s). Re-runs are idempotent via ON CONFLICT upserts, so an interrupted or partial load is safe to resume.
Promotion Model
Section titled “Promotion Model”merge to main | v[CI pipeline — QA branch] | vQA deploy (auto, no gate) | vManual approval (GitHub Environment — Prod) | vProd deployPer RAG001: QA deploys on every merge to main with no human step. Prod requires operator approval. The operator is the sole approver.
Until #28 lands, Prod is frozen and QA is the employer-facing demo (operator decision D-5, #384): bootstrap’s enable_prod defaults to false, and applying bootstrap with that default removes the Prod deploy role. The prod GitHub environment is not created until #28. Setting enable_prod = true and applying bootstrap is part of #28. See risks.md R13.
Pipeline Stages
Section titled “Pipeline Stages”The CI pipeline (#29) runs as a fan-out per environment after the shared test stage.
[test] run pytest (90% aggregate + 70% per-file hard-fail, [RAG006](/adr/rag006/)) run ruff lint run openapi-check diff ([RAG005](/adr/rag005/)) | v[fan-out: QA branch] [fan-out: Prod branch] terraform plan --env=qa (holds at approval gate) terraform apply --env=qa manual approval required Lambda zip upload | SPA sync + CF invalidation v terraform plan --env=prod terraform apply --env=prod Lambda zip upload SPA sync + CF invalidationInfracost posts a per-env cost breakdown as a PR comment (#32), and asserts each environment’s monthly total against a fixed-price ceiling (RAG021). That job triggers on pull_request, so neither runs in a fan-out branch; both happen before the merge that triggers any terraform apply. The apply does not block on the comment, which is informational, but a breached ceiling fails the PR, so the change never reaches a fan-out branch at all. The comment is always present before the operator approves Prod. A failed terraform plan in either branch blocks that branch’s apply; QA failure does not block the Prod gate from opening, but the operator should not approve Prod against a failing QA state.
After the QA apply and code and SPA deploys, qa-deploy.yml runs the post-deploy smoke check. Through the CloudFront URL it loads the SPA page and its entry module, calls /healthz (liveness, no database), and polls /readyz until the database answers (waking a paused Aurora cluster). The page and /readyz checks each poll for up to 180 s. /healthz polls for up to 60 s, because it only waits for an API Lambda cold start. These windows are separate from the 120 s resume wait each of the smoke check’s own Data API calls gets. It then reads the embedded-chunk count over the Data API and fails when the count is 0, and sends one /query through CloudFront with a key whose quota is one request. That call is not retried, so any non-200 fails the smoke check. Last, it sends requests that must stop at the gateway straight to the API Gateway URL. After the smoke check, qa-deploy.yml runs two informational eval jobs in sequence: the retrieval eval (eval-retrieval.yml) and the answer similarity eval (eval-answers.yml). Each uploads a JSON report to the rag-sample-eval bucket (infra/modules/eval_ci). The answers eval runs as three jobs so its scoring libraries (torch, bert-score, sentence-transformers) hold no credentials: collect (eval role) queries /query, score (no environment, no id-token) scores the answers, and upload (eval role) copies the report to S3 with the runner’s AWS CLI. The answers eval scores up to 50 questions per run by default, one question per /query request, with up to 3 attempts on a timeout, connection failure, or HTTP 500/502/503/504. A 500 from the authorizer while Aurora resumes spends no quota, because its charge does not commit. A 500 from the API Lambda comes after the charge, so its retry spends another unit; the eval key’s quota, the question count times 3 attempts (backend/eval/eval_answers.py in the app repo), covers that.
Secrets and IAM Strategy
Section titled “Secrets and IAM Strategy”per RAG009.
- Secrets (DB credentials, API Gateway details, key-store secrets) live in AWS Secrets Manager with separate secret ARNs per environment. The Lambda and eval roles, and the deploy roles’ direct grants, each read only their own environment’s secret. A deploy role can still reach the other environment’s secret through the stack-role boundary, and its
kms:*grant covers every key in the region (threat model T4, risk #504). - In the target state, each Lambda function (API, authorizer, ingestion) has a dedicated IAM role scoped to least-privilege: only the specific
rds-data:ExecuteStatement,bedrock:InvokeModel,secretsmanager:GetSecretValue, andcloudwatch:PutMetricDataactions needed for that function, and only against the ARNs in its environment. Per RAG020, the role carries no X-Ray actions. - CI/CD deploys with one IAM role per environment, assumed by GitHub Actions via OIDC (no long-lived keys in GitHub Secrets) and gated by the
qaorprodGitHub environment. Each role’s database access is limited to its own environment (infra/modules/cicd):rds:*applies torag-sample-<env>-*resources, plusrds:CreateDBInstanceandrds:ModifyDBInstanceon the AWS-ownedpg:default.*parameter groups; the Data API actions the deploy workflows use (ExecuteStatement,BatchExecuteStatement,BeginTransaction,CommitTransaction,RollbackTransaction) apply to therag-sample-<env>-*cluster; andsecretsmanager:GetSecretValue/DescribeSecretto the one RDS-managed secret named byqa_db_secret_arn/prod_db_secret_arnin bootstrap. RDS generates that secret’s name, so the role cannot name it before the cluster exists: it can create RDS-managed secrets (CreateSecret,TagResourceonrds!cluster-*, no read) and reads none until the ARN is set and bootstrap re-applied (bootstrap guide). A cluster replacement regenerates the secret and needs the same step.rds:Describe*andrds:ListTagsForResourcestay on every resource because some Describe calls accept no resource-level permission; they return metadata only. Aterraform testfails if either role gains the other environment’s resource names, a direct read of any other secret, or a database action other thanrds:Describe*/rds:ListTagsForResourceonResource "*"(Story #363, closing risk #362). - Each role’s storage, Lambda and CloudFront access is limited to its own environment (
infra/modules/cicd). In the shared state and Lambda package buckets, object reads and writes apply only underrag-sample/<env>/;ListBucketapplies to the state bucket only, because the S3 backend lists workspaces at init, and no deploy-role caller lists the packages bucket. Bucket management applies torag-sample-<env>-*buckets, and Lambda actions torag-sample-<env>-*functions. CloudFront distribution actions requireaws:ResourceTag/Environmentto equal the role’s environment andaws:ResourceTag/Projectto equalrag-sample; creating a distribution requires both as request tags. Tagging a distribution may set those two tags only to the role’s own values, and untagging may not remove them, so a role cannot hand its distribution to the other environment. Any distribution in the account with noEnvironmenttag and noProjecttag other thanrag-sample, another stack’s included, can be tagged into either environment, after which that environment’s deploy role manages it (threat model T4). Function actions apply torag-sample-<env>-*functions. Origin access controls and response headers policies stay on every resource of their type, because they take no tag condition and their ids are generated.make deploy-role-simulate ENV=<env>checks the policy logic with the IAM policy simulator against the role, expecting each probe on its own environment’s resources to be allowed and each on the other environment’s to be denied, plus one probe that retags its own distribution into the other environment, expected denied. The probes supply the tags as request context, so the check does not confirm the tags on deployed distributions, and it probes only the state, package and frontend bucket, CloudFront distribution and function, Lambda,rds,rds-dataand DB secret grants. The target first runsterraform output -rawfordb_cluster_arn,db_secret_arnanddb_nameininfra/roots/<env>, so the env root must be applied and the caller needs read access to that env’s Terraform state, plusiam:SimulatePrincipalPolicyandsts:GetCallerIdentity(Story #383). - Each deploy role manages only
rag-sample-<env>-*roles, plus creating the RDS service-linked role, and may create one of those roles or set or change its permissions only when it carries the env’s permissions boundary,rag-sample-<env>-stack-role-boundary(infra/modules/cicd). Deleting, updating and tagging those roles grant no permissions and need no boundary; trust-policy changes are not granted and are applied by an operator. The boundary allows only the services the Lambda roles call, so a policy attached to a stack role by the deploy role cannot grant more services. The boundary’s DB-secret grant covers every RDS-managed secret in the account’s us-east-1 region, the other environment’s included; the Lambda role policies narrow it to their own cluster’s secret. The deploy role cannot change the deploy roles, the eval role, or the boundary policy, and cannot remove a boundary. - Each deploy role also manages the stack’s Bedrock guardrail (
infra/modules/cicd, statementsBedrockGuardrailCreateandBedrockGuardrailManage). Terraform’s guardrail resources read the guardrail on every plan and change it on apply, so the role hasbedrock:GetGuardrail,bedrock:UpdateGuardrail,bedrock:DeleteGuardrail,bedrock:CreateGuardrailVersion,bedrock:ListTagsForResource,bedrock:TagResourceandbedrock:UntagResourceonguardrail/*in the stack’s account and region.bedrock:CreateGuardrail, called on first create, has no resource type, so it is granted onResource "*"bounded by theaws:RequestedRegioncondition, which does not bind the account. - The QA eval harness uses a second OIDC role,
rag-sample-qa-eval-role(infra/modules/eval_ci). Its trust policy exact-matches therepo:ArunskiOrg/rag-sample-app:environment:qa-evalsubject (aqa-evalGitHub environment, restricted tomainby a deployment-branch policy), which the QA deploy role does not trust, so an eval job, which imports third-party packages while holding an OIDC token, cannot assume the deploy role. The deploy role ARN is derivable in-job, so the distinct subject is the control;qa-deploy.ymlalso passes the eval workflows it calls onlyAWS_QA_EVAL_ROLE_ARNandQA_DB_SECRET_ARN, by name. Three workflows assume the eval role: the manual-dispatcheval-corpus.yml, andeval-retrieval.ymlandeval-answers.yml, whichqa-deploy.ymlcalls after the smoke check and which can also be dispatched by hand.eval-answers.ymlmints a one-day API key over that Data API grant for each run and deletes it afterwards, so it needs no stored key; the expiry bounds a key whose delete fails. No Prod equivalent exists. - The operator-side key issuance CLI (
python -m rag_sample.tools.issue_key) runs with operator credentials. Separately, two QA CI jobs mint a key over the Data API for each run and delete it at the end: the smoke check and the answers eval (RAG009 amendment). Both keys expire one day after issue, so a key whose delete fails is usable for at most a day. The smoke check’s key also has a two-request quota: its single/querycall leaves one, so the key never reaches zero, which would trip the key-exhausted alarm. Authorizationheaders are scrubbed from CloudWatch logs at the Lambda Powertools Logger layer (RAG009 consequence).
State Backend
Section titled “State Backend”Per RAG001: one S3 bucket with versioning enabled, using S3-native state locking. State files are keyed by environment:
rag-sample/qa/terraform.tfstaterag-sample/prod/terraform.tfstate
A one-time bootstrap script provisions the S3 bucket before any environment can be deployed. State is not shared between environments. S3 bucket versioning provides a point-in-time history for manual state recovery.
Rollback Story
Section titled “Rollback Story”| Layer | Rollback mechanism |
|---|---|
| Lambda (API, authorizer, ingestion) | Publish versioned Lambda on every deploy. If the new version fails, re-point the alias to the previous version (single CLI call). No Terraform involvement required for a quick rollback. |
| SPA | S3 versioning retains previous bundle. Re-sync the previous dist/ artifact and invalidate CloudFront. |
| Generation model | QA: commit the previous llm_model_id, llm_temperature and llm_effort to infra/roots/qa/terraform.tfvars.example in one edit; the merge-to-main pipeline applies QA only. Prod: commit the previous three values to infra/roots/prod/terraform.tfvars.example, then apply Prod. The other environment is unaffected (RAG007). |
| Terraform infrastructure | Revert the offending commit in the Terraform root, re-run terraform apply. For state corruption, restore from S3 version history and re-apply. |
| Database schema | Migrations follow the plain-SQL pattern (RAG002). Reversibility: each migration that cannot be made backwards-compatible must ship a paired down-migration script. The operator runs the down-migration manually before rolling back the Lambda version. Schema changes that are non-reversible (destructive column drops) require a two-phase deploy (add-column, migrate data, drop-column in a separate story). |
There is no automated rollback trigger. The operator monitors the CloudWatch alarm rag-sample-<env>-api-errors and initiates rollback manually.
Operator Notification Touchpoints
Section titled “Operator Notification Touchpoints”| Event | Channel |
|---|---|
| QA deploy started / completed / failed | GitHub Actions status check on the PR / commit |
| Prod approval required | GitHub Environment protection rule sends email to the operator |
| Prod deploy completed / failed | GitHub Actions status check |
3 or more API Lambda errors in 5 minutes (rag-sample-<env>-api-errors) | CloudWatch Alarm to SNS, email subscription (runbook) |
Account-level budget threshold reached (rag-sample-bedrock-daily, rag-sample-monthly) | AWS Budgets to SNS rag-sample-alerts, email subscription (runbook) |
| Infracost cost diff on PR | PR comment |
© 2026 Benjamin Arunski