From 4e8a1d58e0b1665157db79abaea1e66ccd1ac3d1 Mon Sep 17 00:00:00 2001 From: Irving Popovetsky Date: Wed, 25 Nov 2026 08:24:03 -0800 Subject: [PATCH 1/7] Docs: ops runbook, agent guide, SETUP.md cleanup Co-Authored-By: Claude Opus 5.5 --- .github/SETUP.md | 11 +-- AGENTS.md | 24 ++++++ OPS.md | 196 +++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 221 insertions(+), 10 deletions(-) create mode 100644 AGENTS.md create mode 100644 OPS.md diff --git a/.github/SETUP.md b/.github/SETUP.md index 6d83261..9f68c25 100644 --- a/.github/SETUP.md +++ b/.github/SETUP.md @@ -19,7 +19,6 @@ re-run of any push run --> docker-build-push environment ecr-approval - `ecr-main` can skip the wait because the org ruleset on `master` requires a pull request with code-owner review. - Image tags: `:prod` and `:latest` when the ref is `master`, and `:staging` for all other refs. All tags are in the same ECR repository, `pybot`. - Pull requests, Dependabot and forks included, never get AWS credentials. Branch and PR pushes do not publish `:staging`. A maintainer pushes `:staging` with a dispatch (see [Push a Staging Image](#push-a-staging-image-maintainers)). -- The gate is not complete until the old shared role is deleted. See [The Old Shared Role](#the-old-shared-role). ## Required Secret @@ -146,15 +145,7 @@ aws iam list-attached-role-policies --role-name GitHubActions-ECR-Push-pybot # ## The Old Shared Role -Before this change, pybot used `arn:aws:iam::633607774026:role/GitHubActions-ECR-Push`. That role is shared with `OperationCode/back-end`: -- Its trust uses `StringLike` with `repo:...:*` subjects for back-end and pybot. Any branch or pull request of either repository can assume it. -- Its policy allows push to `repository/back-end` and to `repository/pybot`. Thus a session of either repository can overwrite the images of the other. - -**The old role is not gated.** It stays open to branch workflows of both repositories until it is deleted. A writer can edit a workflow on a branch, put the old role ARN in it, and get credentials without an approval. These credentials can push `pybot:prod` and `back-end:prod`. The environments do not stop this. - -**Do not change the old role during the move.** Do not edit its trust, do not edit its permissions, and do not use "Revoke active sessions" on it. The other repository uses it until its own move is done. - -The old role is deleted one time, after both repositories have done step 6 of their move. The back-end guide owns the deletion and the CloudTrail check of ECR writes to both repositories: see "The Old Shared Role" and the steps after it in [back-end `.github/SETUP.md`](https://github.com/OperationCode/back-end/blob/main/.github/SETUP.md). Do not do those steps from this guide. +The old shared role `GitHubActions-ECR-Push` was deleted on 2026-11-23, after both repositories moved to their own roles. The CloudTrail check of its window was clean. ## Safe Change to the New Role diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..cd65a45 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,24 @@ +# Agent guide + +## Maintenance mode +- Avoid major version updates of anything, unless a security fix needs them. +- Keep up with security updates. +- Prefer the smallest change that solves the task. + +## Public repo +- Never commit or post secrets, tokens, user data, prod data or counts, internal hostnames that are not already public, or step-by-step attack-useful details. +- Account IDs and ARNs are not secrets, but do not add new sensitive detail. +- PR bodies, comments, and CI logs are public too. + +## How to work here +```bash +poetry install # setup (Python 3.14, Poetry 2+) +poetry run pytest # test +poetry run ruff check . && poetry run ruff format --check . # lint, as CI does +make ci # lint + tests with coverage + bandit +``` +- PRs build only. Images push only from `master`, or with maintainer approval (`ecr-approval`). +- One PR per change. +- The org PR reviewer blocks dependencies that are less than 72 hours old. +- Deploy, rollback, secrets, and logs: [OPS.md](OPS.md). CI and AWS security setup: [.github/SETUP.md](.github/SETUP.md). +- Never deploy, run prod commands, or change AWS or GitHub settings without an explicit human OK. diff --git a/OPS.md b/OPS.md new file mode 100644 index 0000000..5de3bb2 --- /dev/null +++ b/OPS.md @@ -0,0 +1,196 @@ +# Pybot Operations Runbook + +How pybot is built, deployed, rolled back, and debugged. Each step has a command you can copy. Run all commands from any directory. + +Set this once per shell. Every later command uses it: + +```bash +export AWS_PROFILE=operationcode AWS_REGION=us-east-2 +C=operationcode-ecs-us-east-2 +``` + +## 1. Overview + +``` + PR ---> CI: build only (no push) + merge to master ---> CI: build + push ECR pybot:prod AND pybot:latest (environment ecr-main) + | + | nothing deploys by itself + v + you: force new deployment --> pybot_prod (the task definition runs pybot:latest) +``` + +| Item | Value | +|---|---| +| Service | `pybot_prod` (the only one: there is no staging) | +| Image | `pybot:latest` (the task definition does not use `:prod`) | +| Public URL | `pybot.operationcode.org`, paths `/slack/*`, `/pybot/*`, `/airtable/*` only. There is no public health URL. | +| Health signals | target group `ecs-pybot-prod` (path `/health`), ECS task `healthStatus`, the logs | + +- Cluster: `operationcode-ecs-us-east-2`. Region: `us-east-2`. The service runs one task. +- The task definition pins a tag, not a digest. ECS resolves the tag to a digest when a task starts. +- The service is defined in [operationcode_infra](https://github.com/OperationCode/operationcode_infra) (`terraform/apps.tf`, `terraform/pybot/`). Change settings there, not by hand. +- Pybot has no database and no migrations. It calls Slack, Airtable, and other APIs. + +## 2. How images are built + +- A pull request builds the image. It pushes nothing. +- A merge to `master` pushes `pybot:prod` and `pybot:latest`. The job runs in the `ecr-main` environment and does not wait. +- A manual run (Actions > CI > "Run workflow") or a re-run of a push needs `ecr-approval`: a maintainer must approve it. A run on a branch other than `master` pushes only `:staging`, which nothing uses. The approved job runs the `ci.yml` of that branch, and its credentials can also write `:prod` and `:latest`, so read that file before you approve. +- Do not use `docker-build.sh` to deploy. It pushes from a laptop and skips the gates. +- Nothing deploys to ECS automatically. CI never calls ECS. A merge moves `:latest`, but the running task keeps its old image until a new task starts (a deploy, or any restart). +- Security setup (environments, IAM role, trust policy): [`.github/SETUP.md`](.github/SETUP.md). + +## 3. Deploy + +Deploys cause a short outage: `deployment_minimum_healthy_percent` is 0, `deployment_maximum_percent` is 100, and the deployment circuit breaker is off (all in `terraform/pybot/main.tf`). ECS stops the old task before it starts the new one. If the new task fails, nothing rolls back: you must do section 4. + +**Stop rule:** if any step or check below fails, STOP and go to section 4. A `wait services-stable` that times out (about 10 minutes, exit code 255) is a failure. + +1. Wait for the CI run on `master` to finish and succeed. This is the run that pushed `:latest`: + ```bash + gh run list -R OperationCode/operationcode-pybot --workflow ci.yml --branch master --limit 3 + ``` +2. Save the running digest in a file, and print it. You need it for a rollback. A new terminal loses shell variables, the file does not: + ```bash + export AWS_PROFILE=operationcode AWS_REGION=us-east-2 + C=operationcode-ecs-us-east-2 + D=$HOME/pybot-deploy.env + T=$(aws ecs list-tasks --cluster $C --service-name pybot_prod --query 'taskArns[0]' --output text) + G=$(aws ecs describe-tasks --cluster $C --tasks "$T" --query 'tasks[0].containers[0].imageDigest' --output text) + echo "PROD_DIGEST=$G" > $D + cat $D # copy this line to your notes. Stop if the value is empty or None. + ``` +3. Deploy: + ```bash + export AWS_PROFILE=operationcode AWS_REGION=us-east-2 + C=operationcode-ecs-us-east-2 + aws ecs update-service --cluster $C --service pybot_prod --force-new-deployment + aws ecs wait services-stable --cluster $C --services pybot_prod + ``` +4. Check. All three must pass: + ```bash + export AWS_PROFILE=operationcode AWS_REGION=us-east-2 + C=operationcode-ecs-us-east-2 + S=pybot_prod + T=$(aws ecs list-tasks --cluster $C --service-name $S --query 'taskArns[0]' --output text) + # a) task HEALTHY, and its digest equals the digest of :latest + aws ecs describe-tasks --cluster $C --tasks "$T" --query 'tasks[0].[healthStatus,containers[0].imageDigest]' --output text + aws ecr describe-images --repository-name pybot --image-ids imageTag=latest --query 'imageDetails[0].imageDigest' --output text + # b) the target is healthy (State: healthy) + TG=$(aws elbv2 describe-target-groups --names ecs-pybot-prod --query 'TargetGroups[0].TargetGroupArn' --output text) + aws elbv2 describe-target-health --target-group-arn "$TG" --query 'TargetHealthDescriptions[].[Target.Id,TargetHealth.State]' --output text + # c) no errors in the last 15 minutes (no output is good) + aws logs filter-log-events --log-group-name ecs-20221213004720404200000001 \ + --log-stream-name-prefix pybot_prod --start-time $(( ($(date +%s) - 900) * 1000 )) \ + --filter-pattern '?Traceback ?ERROR' --query 'events[].message' --output text + ``` + +## 4. Roll back + +Use the digest saved in deploy step 2 (`cat $HOME/pybot-deploy.env`). The task definition runs `:latest`, but `:prod` must match it, so retag both: + +```bash +export AWS_PROFILE=operationcode AWS_REGION=us-east-2 +C=operationcode-ecs-us-east-2 +. $HOME/pybot-deploy.env +DIGEST=$PROD_DIGEST +test -n "$DIGEST" -a "$DIGEST" != None || { echo "no saved digest: STOP"; false; } +M=$(aws ecr batch-get-image --repository-name pybot --image-ids imageDigest=$DIGEST --query 'images[0].imageManifest' --output text) +test -n "$M" -a "$M" != None || { echo "no manifest for the digest: STOP"; false; } +for TAG in latest prod; do + aws ecr put-image --repository-name pybot --image-tag $TAG --image-manifest "$M" +done +aws ecs update-service --cluster $C --service pybot_prod --force-new-deployment +aws ecs wait services-stable --cluster $C --services pybot_prod +``` + +Verify. The task digest must equal `$DIGEST` (the saved digest), the task must be HEALTHY, and the target must be healthy (deploy step 4b): + +```bash +export AWS_PROFILE=operationcode AWS_REGION=us-east-2 +C=operationcode-ecs-us-east-2 +. $HOME/pybot-deploy.env +T=$(aws ecs list-tasks --cluster $C --service-name pybot_prod --query 'taskArns[0]' --output text) +aws ecs describe-tasks --cluster $C --tasks "$T" --query 'tasks[0].[healthStatus,containers[0].imageDigest]' --output text +echo "$PROD_DIGEST" +``` + +- ECR does not keep tag history. If you did not save the digest, you cannot find the old one by tag. +- The `pybot` ECR repository has no lifecycle policy, so untagged images stay until someone deletes them. +- After a rollback, the next merge to `master` moves `:prod` and `:latest` again. The next restart then runs that new image. + +## 5. Run a command in the container (ECS Exec) + +ECS Exec is enabled on `pybot_prod` (`enable_execute_command = true`). You need the `session-manager-plugin` (`brew install --cask session-manager-plugin`). + +```bash +export AWS_PROFILE=operationcode AWS_REGION=us-east-2 +C=operationcode-ecs-us-east-2 +T=$(aws ecs list-tasks --cluster $C --service-name pybot_prod --query 'taskArns[0]' --output text) +aws ecs execute-command --cluster $C --task "$T" --container pybot_prod --interactive --command "/bin/sh" +``` + +Type `exit` to leave. The working directory is `/app`. + +**Warning:** this is a shell inside the live production container, and the secrets are in its environment. Do not print them. Prefer read-only commands. The session is recorded only in CloudTrail. + +## 6. Secrets + +Secrets are in AWS Secrets Manager, in the JSON secret `prod/pybot` (us-east-2). Terraform turns every key of that secret into a task definition secret with the upper-case key as its name. ECS reads the values when a task starts. See `terraform/pybot/main.tf`. + +- List the names, never the values: + ```bash + export AWS_PROFILE=operationcode AWS_REGION=us-east-2 + aws ecs describe-task-definition --task-definition pybot_prod --query 'taskDefinition.containerDefinitions[0].secrets[].name' --output text + ``` +- To change a value, edit the secret in Secrets Manager, then force a new deployment (deploy step 3). A new key also needs a Terraform apply, because Terraform builds the list of secrets. +- Many values are tokens of other services (Slack, Airtable, and others). Issue the new token at that service first. This runbook has no rotation procedure for them. + +## 7. Dependency updates + +Policy (see [`.github/dependabot.yml`](.github/dependabot.yml)): + +- Dependabot runs each Monday. Python and GitHub Actions: one grouped minor/patch pull request each. Docker: no group and no cooldown, and the `python` base image takes patch updates only. +- Dependabot ignores major versions. A security fix that needs a major shows only as a Dependabot alert. Apply it by hand. +- The cooldown for Python and GitHub Actions is 3 days. It matches the 72-hour supply-chain rule of the org PR reviewer: do not take a release that is less than 72 hours old. +- Never apply a major version, unless a security fix requires it. + +To update by hand: + +1. Update within the constraints of `pyproject.toml`: + ```bash + poetry update + ``` +2. Check the release date of each changed package. Put back any version that is less than 72 hours old (`poetry add "@"`, or edit `poetry.lock` back with `git checkout -p poetry.lock`). +3. Run the same checks as CI (the Makefile has them): + ```bash + make ci # ruff check, ruff format --check, pytest with coverage, bandit + ``` +4. Open one pull request with the `pyproject.toml` and `poetry.lock` changes. After the merge, deploy as in section 3. + +## 8. Logs and troubleshooting + +All containers write to one CloudWatch log group, `ecs-20221213004720404200000001`. The stream prefix is `pybot_prod`. + +```bash +export AWS_PROFILE=operationcode AWS_REGION=us-east-2 +# Follow the logs +aws logs tail ecs-20221213004720404200000001 --log-stream-name-prefix pybot_prod --follow +# Check that the group name is still correct +aws logs describe-log-groups --log-group-name-prefix ecs- +``` + +Service state and deployments. `rolloutState` must be `COMPLETED`, and `runningCount` must equal `desiredCount`: + +```bash +export AWS_PROFILE=operationcode AWS_REGION=us-east-2 +C=operationcode-ecs-us-east-2 +aws ecs describe-services --cluster $C --services pybot_prod \ + --query 'services[0].[runningCount,desiredCount,deployments[].[status,rolloutState,taskDefinition],events[:5].message]' +aws ecs list-tasks --cluster $C --service-name pybot_prod --desired-status STOPPED +``` + +If a new task keeps stopping, read the stop reason: `aws ecs describe-tasks --cluster $C --tasks --query 'tasks[0].[stoppedReason,containers[0].reason]'`. + +The container health check (`wget` to `http://localhost:5000/health`) and the target group check (path `/health`) test the same endpoint. Errors are also in Sentry (`SENTRY_DSN` is one of the secrets). From 7c8aeb2267a499d2d3110e6a182a3a77da228288 Mon Sep 17 00:00:00 2001 From: Irving Popovetsky Date: Wed, 25 Nov 2026 08:27:02 -0800 Subject: [PATCH 2/7] Docs: mark SETUP.md move as done, make OPS.md checks halt on failure Co-Authored-By: Claude Opus 5.5 --- .github/SETUP.md | 8 +-- OPS.md | 124 +++++++++++++++++++++++++++++------------------ 2 files changed, 81 insertions(+), 51 deletions(-) diff --git a/.github/SETUP.md b/.github/SETUP.md index 9f68c25..a6a5a74 100644 --- a/.github/SETUP.md +++ b/.github/SETUP.md @@ -149,9 +149,9 @@ The old shared role `GitHubActions-ECR-Push` was deleted on 2026-11-23, after bo ## Safe Change to the New Role -Use this procedure to move pybot from the old shared role to its own role. Do not change the old role during this procedure (see above). +Done on 2026-11-23. Kept as a record: do not run it again. It moved pybot from the old shared role to its own role. -1. Create the two environments, as given in [Required Environments](#required-environments). Write down the time when you start this step (S). The back-end CloudTrail check uses the earlier S of the two repositories. +1. Create the two environments, as given in [Required Environments](#required-environments). Write down the time when you start this step (S). 2. Create the new role, as given in [Create the role](#create-the-role). Get the pull request that adds the environments to `ci.yml` approved and green. Do not merge it yet. 3. Set the secret to the new role ARN, as given in [Required Secret](#required-secret). - Between step 3 and step 5, every push run of the old workflow fails at "Configure AWS credentials", because the new role does not trust its subject. Nobody must push to `master` during this time. @@ -165,7 +165,7 @@ Use this procedure to move pybot from the old shared role to its own role. Do no To cancel one run: `gh run cancel --repo OperationCode/operationcode-pybot`. Run the list again until it is empty. 5. Immediately merge the pull request. The push to `master` that the merge causes uses `ecr-main` and the new role, and pushes `:prod` and `:latest`. - If the first push fails, correct the new role (see the rules above). Then re-run the job. The re-run uses `ecr-approval`, so a maintainer must approve it. - - When the push run is complete, write down the image digest of `:prod`. Give it to the person who does the back-end CloudTrail check: + - When the push run is complete, write down the image digest of `:prod`.: `aws ecr describe-images --region us-east-2 --repository-name pybot --image-ids imageTag=prod --query 'imageDetails[0].imageDigest' --output text` 6. Confirm one successful push to `master` through the new role. Use one of these: - CloudTrail: find the `AssumeRoleWithWebIdentity` event for the new role ARN, at the time of the push run from step 5. @@ -180,7 +180,7 @@ Use this procedure to move pybot from the old shared role to its own role. Do no Expect a line with `ok` and the subject `...:environment:ecr-main`. - Run log: the push run from step 5 shows environment `ecr-main`, and the "Output image URI" step prints `Successfully pushed Production images`. - The pybot move is done after this step. Tell the back-end owner, because the old role is deleted only after both repositories finish step 6. + The pybot move is done after this step. ## Push a Staging Image (maintainers) diff --git a/OPS.md b/OPS.md index 5de3bb2..c8ada85 100644 --- a/OPS.md +++ b/OPS.md @@ -51,69 +51,99 @@ Deploys cause a short outage: `deployment_minimum_healthy_percent` is 0, `deploy ```bash gh run list -R OperationCode/operationcode-pybot --workflow ci.yml --branch master --limit 3 ``` -2. Save the running digest in a file, and print it. You need it for a rollback. A new terminal loses shell variables, the file does not: +2. Save the running digest in a file, and print it. You need it for a rollback. A new terminal loses shell variables, the file does not. Run this step one time per deploy, before step 3. It refuses to overwrite a saved digest, so a failed deploy cannot replace the good digest with a bad one. Delete the file only after a deploy that you checked and finished: ```bash - export AWS_PROFILE=operationcode AWS_REGION=us-east-2 - C=operationcode-ecs-us-east-2 - D=$HOME/pybot-deploy.env - T=$(aws ecs list-tasks --cluster $C --service-name pybot_prod --query 'taskArns[0]' --output text) - G=$(aws ecs describe-tasks --cluster $C --tasks "$T" --query 'tasks[0].containers[0].imageDigest' --output text) - echo "PROD_DIGEST=$G" > $D - cat $D # copy this line to your notes. Stop if the value is empty or None. + ( + set -euo pipefail + export AWS_PROFILE=operationcode AWS_REGION=us-east-2 + C=operationcode-ecs-us-east-2 + D=$HOME/pybot-deploy.env + test ! -s $D || { echo "$D exists: STOP. Roll back with it, or delete it after a finished deploy"; false; } + T=$(aws ecs list-tasks --cluster $C --service-name pybot_prod --query 'taskArns[0]' --output text) + G=$(aws ecs describe-tasks --cluster $C --tasks "$T" --query 'tasks[0].containers[0].imageDigest' --output text) + test -n "$G" -a "$G" != None || { echo "no running digest: STOP"; false; } + echo "PROD_DIGEST=$G" > $D + cat $D # copy this line to your notes + ) ``` 3. Deploy: ```bash - export AWS_PROFILE=operationcode AWS_REGION=us-east-2 - C=operationcode-ecs-us-east-2 - aws ecs update-service --cluster $C --service pybot_prod --force-new-deployment - aws ecs wait services-stable --cluster $C --services pybot_prod + ( + set -euo pipefail + export AWS_PROFILE=operationcode AWS_REGION=us-east-2 + C=operationcode-ecs-us-east-2 + aws ecs update-service --cluster $C --service pybot_prod --force-new-deployment >/dev/null + aws ecs wait services-stable --cluster $C --services pybot_prod || { echo "not stable: STOP, roll back (section 4)"; false; } + echo "deploy stable" + ) ``` -4. Check. All three must pass: +4. Check. The block prints `CHECKS OK` and exits at the first failed check. On any failure: STOP, and do section 4: ```bash - export AWS_PROFILE=operationcode AWS_REGION=us-east-2 - C=operationcode-ecs-us-east-2 - S=pybot_prod - T=$(aws ecs list-tasks --cluster $C --service-name $S --query 'taskArns[0]' --output text) - # a) task HEALTHY, and its digest equals the digest of :latest - aws ecs describe-tasks --cluster $C --tasks "$T" --query 'tasks[0].[healthStatus,containers[0].imageDigest]' --output text - aws ecr describe-images --repository-name pybot --image-ids imageTag=latest --query 'imageDetails[0].imageDigest' --output text - # b) the target is healthy (State: healthy) - TG=$(aws elbv2 describe-target-groups --names ecs-pybot-prod --query 'TargetGroups[0].TargetGroupArn' --output text) - aws elbv2 describe-target-health --target-group-arn "$TG" --query 'TargetHealthDescriptions[].[Target.Id,TargetHealth.State]' --output text - # c) no errors in the last 15 minutes (no output is good) - aws logs filter-log-events --log-group-name ecs-20221213004720404200000001 \ - --log-stream-name-prefix pybot_prod --start-time $(( ($(date +%s) - 900) * 1000 )) \ - --filter-pattern '?Traceback ?ERROR' --query 'events[].message' --output text + ( + set -euo pipefail + export AWS_PROFILE=operationcode AWS_REGION=us-east-2 + C=operationcode-ecs-us-east-2 + T=$(aws ecs list-tasks --cluster $C --service-name pybot_prod --query 'taskArns[0]' --output text) + # a) task HEALTHY, and its digest equals the digest of :latest + read -r H G < <(aws ecs describe-tasks --cluster $C --tasks "$T" --query 'tasks[0].[healthStatus,containers[0].imageDigest]' --output text) + L=$(aws ecr describe-images --repository-name pybot --image-ids imageTag=latest --query 'imageDetails[0].imageDigest' --output text) + test "$H" = HEALTHY || { echo "task health is $H: STOP"; false; } + test "$G" = "$L" || { echo "task digest $G is not :latest $L: STOP"; false; } + # b) the target is healthy + TG=$(aws elbv2 describe-target-groups --names ecs-pybot-prod --query 'TargetGroups[0].TargetGroupArn' --output text) + TS=$(aws elbv2 describe-target-health --target-group-arn "$TG" --query 'TargetHealthDescriptions[0].TargetHealth.State' --output text) + test "$TS" = healthy || { echo "target state is $TS: STOP"; false; } + # c) no errors in the last 15 minutes + E=$(aws logs filter-log-events --log-group-name ecs-20221213004720404200000001 \ + --log-stream-name-prefix pybot_prod --start-time $(( ($(date +%s) - 900) * 1000 )) \ + --filter-pattern '?Traceback ?ERROR' --query 'events[].message' --output text) + test -z "$E" || { echo "$E"; echo "errors in the logs: STOP"; false; } + echo "CHECKS OK" + ) ``` ## 4. Roll back -Use the digest saved in deploy step 2 (`cat $HOME/pybot-deploy.env`). The task definition runs `:latest`, but `:prod` must match it, so retag both: +Use the digest saved in deploy step 2 (`cat $HOME/pybot-deploy.env`). The task definition runs `:latest`, but `:prod` must match it, so retag both. The block stops at the first failed step: ```bash -export AWS_PROFILE=operationcode AWS_REGION=us-east-2 -C=operationcode-ecs-us-east-2 -. $HOME/pybot-deploy.env -DIGEST=$PROD_DIGEST -test -n "$DIGEST" -a "$DIGEST" != None || { echo "no saved digest: STOP"; false; } -M=$(aws ecr batch-get-image --repository-name pybot --image-ids imageDigest=$DIGEST --query 'images[0].imageManifest' --output text) -test -n "$M" -a "$M" != None || { echo "no manifest for the digest: STOP"; false; } -for TAG in latest prod; do - aws ecr put-image --repository-name pybot --image-tag $TAG --image-manifest "$M" -done -aws ecs update-service --cluster $C --service pybot_prod --force-new-deployment -aws ecs wait services-stable --cluster $C --services pybot_prod +( + set -euo pipefail + export AWS_PROFILE=operationcode AWS_REGION=us-east-2 + C=operationcode-ecs-us-east-2 + . $HOME/pybot-deploy.env + DIGEST=${PROD_DIGEST:-} + test -n "$DIGEST" -a "$DIGEST" != None || { echo "no saved digest: STOP"; false; } + M=$(aws ecr batch-get-image --repository-name pybot --image-ids imageDigest=$DIGEST --query 'images[0].imageManifest' --output text) + test -n "$M" -a "$M" != None || { echo "no manifest for the digest: STOP"; false; } + for TAG in latest prod; do + aws ecr put-image --repository-name pybot --image-tag $TAG --image-manifest "$M" >/dev/null + N=$(aws ecr describe-images --repository-name pybot --image-ids imageTag=$TAG --query 'imageDetails[0].imageDigest' --output text) + test "$N" = "$DIGEST" || { echo ":$TAG is $N, not $DIGEST: STOP"; false; } + done + aws ecs update-service --cluster $C --service pybot_prod --force-new-deployment >/dev/null + aws ecs wait services-stable --cluster $C --services pybot_prod || { echo "not stable: STOP"; false; } + echo "rollback deployed" +) ``` -Verify. The task digest must equal `$DIGEST` (the saved digest), the task must be HEALTHY, and the target must be healthy (deploy step 4b): +Verify. The block prints `ROLLBACK OK` only if the task digest equals the saved digest, the task is HEALTHY, and the target is healthy: ```bash -export AWS_PROFILE=operationcode AWS_REGION=us-east-2 -C=operationcode-ecs-us-east-2 -. $HOME/pybot-deploy.env -T=$(aws ecs list-tasks --cluster $C --service-name pybot_prod --query 'taskArns[0]' --output text) -aws ecs describe-tasks --cluster $C --tasks "$T" --query 'tasks[0].[healthStatus,containers[0].imageDigest]' --output text -echo "$PROD_DIGEST" +( + set -euo pipefail + export AWS_PROFILE=operationcode AWS_REGION=us-east-2 + C=operationcode-ecs-us-east-2 + . $HOME/pybot-deploy.env + T=$(aws ecs list-tasks --cluster $C --service-name pybot_prod --query 'taskArns[0]' --output text) + read -r H G < <(aws ecs describe-tasks --cluster $C --tasks "$T" --query 'tasks[0].[healthStatus,containers[0].imageDigest]' --output text) + test "$H" = HEALTHY || { echo "task health is $H: STOP"; false; } + test "$G" = "$PROD_DIGEST" || { echo "task digest $G is not $PROD_DIGEST: STOP"; false; } + TG=$(aws elbv2 describe-target-groups --names ecs-pybot-prod --query 'TargetGroups[0].TargetGroupArn' --output text) + TS=$(aws elbv2 describe-target-health --target-group-arn "$TG" --query 'TargetHealthDescriptions[0].TargetHealth.State' --output text) + test "$TS" = healthy || { echo "target state is $TS: STOP"; false; } + echo "ROLLBACK OK" +) ``` - ECR does not keep tag history. If you did not save the digest, you cannot find the old one by tag. From a909835ae93bc5b5eb54a4982a35981c8a435e6e Mon Sep 17 00:00:00 2001 From: Irving Popovetsky Date: Wed, 25 Nov 2026 08:29:59 -0800 Subject: [PATCH 3/7] Docs: OPS.md blocks set own variables, skip put-image when tag matches, saved-digest cleanup Co-Authored-By: Claude Opus 5.5 --- OPS.md | 43 +++++++++++++++++++++++++++++++------------ 1 file changed, 31 insertions(+), 12 deletions(-) diff --git a/OPS.md b/OPS.md index c8ada85..cdba3f7 100644 --- a/OPS.md +++ b/OPS.md @@ -2,12 +2,7 @@ How pybot is built, deployed, rolled back, and debugged. Each step has a command you can copy. Run all commands from any directory. -Set this once per shell. Every later command uses it: - -```bash -export AWS_PROFILE=operationcode AWS_REGION=us-east-2 -C=operationcode-ecs-us-east-2 -``` +Every block below sets its own variables (profile, region, cluster, task ID, saved digest). You can paste any one block alone, in a new shell. A block in `( )` with `set -euo pipefail` stops at the first failed check. ## 1. Overview @@ -51,14 +46,14 @@ Deploys cause a short outage: `deployment_minimum_healthy_percent` is 0, `deploy ```bash gh run list -R OperationCode/operationcode-pybot --workflow ci.yml --branch master --limit 3 ``` -2. Save the running digest in a file, and print it. You need it for a rollback. A new terminal loses shell variables, the file does not. Run this step one time per deploy, before step 3. It refuses to overwrite a saved digest, so a failed deploy cannot replace the good digest with a bad one. Delete the file only after a deploy that you checked and finished: +2. Save the running digest in a file, and print it. You need it for a rollback. A new terminal loses shell variables, the file does not. Run this step one time per deploy, before step 3. It refuses to overwrite a saved digest, so a failed deploy cannot replace the good digest with a bad one. The file `$HOME/pybot-deploy.env` stays until you delete it at the end of step 4 (a good deploy) or at the end of section 4 (a rollback): ```bash ( set -euo pipefail export AWS_PROFILE=operationcode AWS_REGION=us-east-2 C=operationcode-ecs-us-east-2 D=$HOME/pybot-deploy.env - test ! -s $D || { echo "$D exists: STOP. Roll back with it, or delete it after a finished deploy"; false; } + test ! -s $D || { echo "$D exists: a previous deploy or rollback was not finished. If it was finished, run: rm $D. If not, finish it (section 4) first. STOP"; false; } T=$(aws ecs list-tasks --cluster $C --service-name pybot_prod --query 'taskArns[0]' --output text) G=$(aws ecs describe-tasks --cluster $C --tasks "$T" --query 'tasks[0].containers[0].imageDigest' --output text) test -n "$G" -a "$G" != None || { echo "no running digest: STOP"; false; } @@ -77,7 +72,7 @@ Deploys cause a short outage: `deployment_minimum_healthy_percent` is 0, `deploy echo "deploy stable" ) ``` -4. Check. The block prints `CHECKS OK` and exits at the first failed check. On any failure: STOP, and do section 4: +4. Check. The block prints `CHECKS OK` and exits at the first failed check. On any failure: STOP, and do section 4 (do not run step 5): ```bash ( set -euo pipefail @@ -101,10 +96,14 @@ Deploys cause a short outage: `deployment_minimum_healthy_percent` is 0, `deploy echo "CHECKS OK" ) ``` +5. The deploy is finished and good. Delete the saved digest now, so the next deploy can save a new one: + ```bash + rm $HOME/pybot-deploy.env + ``` ## 4. Roll back -Use the digest saved in deploy step 2 (`cat $HOME/pybot-deploy.env`). The task definition runs `:latest`, but `:prod` must match it, so retag both. The block stops at the first failed step: +Use the digest saved in deploy step 2 (`cat $HOME/pybot-deploy.env`). The task definition runs `:latest`, but `:prod` must match it, so retag both. A tag that already points at the saved digest is skipped. The block stops at the first failed step: ```bash ( @@ -117,7 +116,12 @@ Use the digest saved in deploy step 2 (`cat $HOME/pybot-deploy.env`). The task d M=$(aws ecr batch-get-image --repository-name pybot --image-ids imageDigest=$DIGEST --query 'images[0].imageManifest' --output text) test -n "$M" -a "$M" != None || { echo "no manifest for the digest: STOP"; false; } for TAG in latest prod; do - aws ecr put-image --repository-name pybot --image-tag $TAG --image-manifest "$M" >/dev/null + CUR=$(aws ecr describe-images --repository-name pybot --image-ids imageTag=$TAG --query 'imageDetails[0].imageDigest' --output text 2>/dev/null || true) + if test "$CUR" = "$DIGEST"; then + echo ":$TAG already points at $DIGEST: put-image skipped" + else + aws ecr put-image --repository-name pybot --image-tag $TAG --image-manifest "$M" >/dev/null + fi N=$(aws ecr describe-images --repository-name pybot --image-ids imageTag=$TAG --query 'imageDetails[0].imageDigest' --output text) test "$N" = "$DIGEST" || { echo ":$TAG is $N, not $DIGEST: STOP"; false; } done @@ -146,6 +150,12 @@ Verify. The block prints `ROLLBACK OK` only if the task digest equals the saved ) ``` +The rollback is finished. Delete the saved digest now, so the next deploy can save a new one: + +```bash +rm $HOME/pybot-deploy.env +``` + - ECR does not keep tag history. If you did not save the digest, you cannot find the old one by tag. - The `pybot` ECR repository has no lifecycle policy, so untagged images stay until someone deletes them. - After a rollback, the next merge to `master` moves `:prod` and `:latest` again. The next restart then runs that new image. @@ -155,6 +165,7 @@ Verify. The block prints `ROLLBACK OK` only if the task digest equals the saved ECS Exec is enabled on `pybot_prod` (`enable_execute_command = true`). You need the `session-manager-plugin` (`brew install --cask session-manager-plugin`). ```bash +set -euo pipefail export AWS_PROFILE=operationcode AWS_REGION=us-east-2 C=operationcode-ecs-us-east-2 T=$(aws ecs list-tasks --cluster $C --service-name pybot_prod --query 'taskArns[0]' --output text) @@ -221,6 +232,14 @@ aws ecs describe-services --cluster $C --services pybot_prod \ aws ecs list-tasks --cluster $C --service-name pybot_prod --desired-status STOPPED ``` -If a new task keeps stopping, read the stop reason: `aws ecs describe-tasks --cluster $C --tasks --query 'tasks[0].[stoppedReason,containers[0].reason]'`. +If a new task keeps stopping, read the stop reason. This block reads the newest stopped task: + +```bash +set -euo pipefail +export AWS_PROFILE=operationcode AWS_REGION=us-east-2 +C=operationcode-ecs-us-east-2 +T=$(aws ecs list-tasks --cluster $C --service-name pybot_prod --desired-status STOPPED --query 'taskArns[0]' --output text) +aws ecs describe-tasks --cluster $C --tasks "$T" --query 'tasks[0].[stoppedReason,containers[0].reason]' +``` The container health check (`wget` to `http://localhost:5000/health`) and the target group check (path `/health`) test the same endpoint. Errors are also in Sentry (`SENTRY_DSN` is one of the secrets). From cc10606a4f4f7159fe8a5e58300c35296217aa31 Mon Sep 17 00:00:00 2001 From: Irving Popovetsky Date: Wed, 25 Nov 2026 08:30:06 -0800 Subject: [PATCH 4/7] Docs: OPS.md rollback cleanup only after ROLLBACK OK Co-Authored-By: Claude Opus 5.5 --- OPS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/OPS.md b/OPS.md index cdba3f7..7e6584e 100644 --- a/OPS.md +++ b/OPS.md @@ -150,7 +150,7 @@ Verify. The block prints `ROLLBACK OK` only if the task digest equals the saved ) ``` -The rollback is finished. Delete the saved digest now, so the next deploy can save a new one: +If `ROLLBACK OK` printed, the rollback is finished. Delete the saved digest now, so the next deploy can save a new one: ```bash rm $HOME/pybot-deploy.env From dd733754cfec3dcfcba0f843c681d76e96804e60 Mon Sep 17 00:00:00 2001 From: Irving Popovetsky Date: Wed, 25 Nov 2026 08:36:37 -0800 Subject: [PATCH 5/7] AGENTS.md: keep back-end and pybot in sync Co-Authored-By: Claude Haiku 5.5 --- AGENTS.md | 1 + 1 file changed, 1 insertion(+) diff --git a/AGENTS.md b/AGENTS.md index cd65a45..f80ce89 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -22,3 +22,4 @@ make ci # lint + tests with coverage + b - The org PR reviewer blocks dependencies that are less than 72 hours old. - Deploy, rollback, secrets, and logs: [OPS.md](OPS.md). CI and AWS security setup: [.github/SETUP.md](.github/SETUP.md). - Never deploy, run prod commands, or change AWS or GitHub settings without an explicit human OK. +- pybot and back-end share the same CI, AWS, deploy, and dependency setup. Keep changes in sync: when you improve something in one (CI, docs, runbook, deps policy, tooling), make the same change in `OperationCode/back-end`, or note why it does not apply. From 6bc4acfe7ba209186021425d9656182d513d41f6 Mon Sep 17 00:00:00 2001 From: Irving Popovetsky Date: Wed, 25 Nov 2026 08:37:19 -0800 Subject: [PATCH 6/7] AGENTS.md: point to the infra repo Co-Authored-By: Claude Haiku 5.5 --- AGENTS.md | 1 + 1 file changed, 1 insertion(+) diff --git a/AGENTS.md b/AGENTS.md index f80ce89..64111c4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -23,3 +23,4 @@ make ci # lint + tests with coverage + b - Deploy, rollback, secrets, and logs: [OPS.md](OPS.md). CI and AWS security setup: [.github/SETUP.md](.github/SETUP.md). - Never deploy, run prod commands, or change AWS or GitHub settings without an explicit human OK. - pybot and back-end share the same CI, AWS, deploy, and dependency setup. Keep changes in sync: when you improve something in one (CI, docs, runbook, deps policy, tooling), make the same change in `OperationCode/back-end`, or note why it does not apply. +- Infrastructure (ECS services, task definitions, IAM roles, ECR, load balancers) lives in `OperationCode/operationcode_infra` (Terraform). Change it there through a PR. Never hand-edit AWS. Many changes here need a matching infra change. From 1e951dca741316fec19a8582b42a1a92b2bce759 Mon Sep 17 00:00:00 2001 From: Irving Popovetsky Date: Wed, 25 Nov 2026 08:42:40 -0800 Subject: [PATCH 7/7] OPS.md: atomic digest file, log window from task start (review feedback) Co-Authored-By: Claude Opus 5.5 --- .github/SETUP.md | 2 +- OPS.md | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/.github/SETUP.md b/.github/SETUP.md index a6a5a74..ea2f6d3 100644 --- a/.github/SETUP.md +++ b/.github/SETUP.md @@ -165,7 +165,7 @@ Done on 2026-11-23. Kept as a record: do not run it again. It moved pybot from t To cancel one run: `gh run cancel --repo OperationCode/operationcode-pybot`. Run the list again until it is empty. 5. Immediately merge the pull request. The push to `master` that the merge causes uses `ecr-main` and the new role, and pushes `:prod` and `:latest`. - If the first push fails, correct the new role (see the rules above). Then re-run the job. The re-run uses `ecr-approval`, so a maintainer must approve it. - - When the push run is complete, write down the image digest of `:prod`.: + - When the push run is complete, write down the image digest of `:prod`: `aws ecr describe-images --region us-east-2 --repository-name pybot --image-ids imageTag=prod --query 'imageDetails[0].imageDigest' --output text` 6. Confirm one successful push to `master` through the new role. Use one of these: - CloudTrail: find the `AssumeRoleWithWebIdentity` event for the new role ARN, at the time of the push run from step 5. diff --git a/OPS.md b/OPS.md index 7e6584e..09b578e 100644 --- a/OPS.md +++ b/OPS.md @@ -88,9 +88,11 @@ Deploys cause a short outage: `deployment_minimum_healthy_percent` is 0, `deploy TG=$(aws elbv2 describe-target-groups --names ecs-pybot-prod --query 'TargetGroups[0].TargetGroupArn' --output text) TS=$(aws elbv2 describe-target-health --target-group-arn "$TG" --query 'TargetHealthDescriptions[0].TargetHealth.State' --output text) test "$TS" = healthy || { echo "target state is $TS: STOP"; false; } - # c) no errors in the last 15 minutes + # c) no errors since the new task started (errors of the old task do not count) + A=$(aws ecs describe-tasks --cluster $C --tasks "$T" --query 'tasks[0].startedAt' --output text) + B=$(python3 -c 'import sys,datetime as d; print(int(d.datetime.fromisoformat(sys.argv[1]).timestamp()*1000))' "$A") # ISO time to epoch ms, same on macOS and Linux E=$(aws logs filter-log-events --log-group-name ecs-20221213004720404200000001 \ - --log-stream-name-prefix pybot_prod --start-time $(( ($(date +%s) - 900) * 1000 )) \ + --log-stream-name-prefix pybot_prod --start-time $B \ --filter-pattern '?Traceback ?ERROR' --query 'events[].message' --output text) test -z "$E" || { echo "$E"; echo "errors in the logs: STOP"; false; } echo "CHECKS OK"