region HA: Task 6 fix round 1 for replace, remove and roll
Astra: - EnteringStandby is waited for, with capacity checked, before the settled Standby check. - A hard cut after the terminate intent resumes: an unanswered intent is sent again unless the provider's activities show it arrived. - Failed-drain recovery returns a restarted agent (same binary and boot); the fence keeps it from starting anything. - Operator policy: terminate in this group only, launch-template version read, ListBucket with prefix conditions, GetObject on lock.json keys; new group_operator_lock_prefix variable; tofu test asserts the scope. - cancel-drain subcommand and its bounded document form; the result is proven by status (fence absent, drain ended). - R3.1 witness delays the provider call and restarts the agent after the final check; the fenced start is refused. - Drained roll prints and journals the drain summary. Fable: - A floor that cannot be read refuses; only definite findings use DR-4. - The lock sweep uses the configured data_bucket (new key), refuses a member naming another bucket, and requires every moved host's lock. - Locks are re-read after every edge stop; fence-clear bound 60 s.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
infra/modules/region-group-operator-document/README.md+4 −2infra/modules/region-group-operator-document/tool-pattern.txt+1 −1infra/modules/region-host/group_operator.tf+48 −1infra/modules/region-host/tests/group_operator.tftest.hcl+73 −4scripts/region-group-roll.py+160 −67scripts/region_group_document_test.py+9 −2scripts/region_group_held_test.py+303 −22
Intent
<task-notification> <task-id>a8303ed4bc3147d03</task-id> <tool-use-id>toolu_016dhgwsr5VT44xR78ib59Lx</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/283be278-5c6a-4a71-a8d6-b3d32c668985/tasks/a8303ed4bc3147d03.output</output-file> <status>completed</status> <summary>Agent "Implement Task 6: roll tool" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>Status: DONE_WITH_CONCERNS Commits (not pushed): `5157c05e` region HA: replace and remove transactions; roll drains first; `81877223` census: re-propose held-requests after Task 6 Tests: all 268 Python tests pass (roll, probe, new held, document and contract tests), against an OK baseline. The provision census and Python-guard Go tests pass. 19 of 19 mutations were caught. Concerns: 1. **IAM blocks the live call.** The operator policy lacks the terminate, launch-template read and S3 list/get grants on control/edges/ and the data bucket's locks. I left them out because they are an IAM boundary change; this needs a ruling. 2. **No in-band `drain --cancel`.** The tool prints the instruction as ruled, but the operator document doesn't admit `drain --cancel`. Recommend admitting it and adding a tool subcommand. 3. **Operator document widened.** Without it, real boxes would refuse the three new commands (drain, fence-clear, edge stop), so I added exactly those to tool-pattern.txt and re-proposed the census. The census entry's basis text needs restating. 4. **AWS docs imply but don't state** that terminating a Standby member without decrement leaves desired unchanged. That's a live-check item; the tool FAILs if desired or membership moves. 5. About 30 new operator strings await the copy pass. Owed: the attended live call on dev (needs item 1 first) and the runbook on its own docs branch. Report: /home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-held-build/.superpowers/sdd/2026-11-08-region-ha-held-requests/task-6-report.md</result> <usage><subagent_tokens>322203</subagent_tokens><tool_uses>113</tool_uses><duration_ms>2818462</duration_ms></usage> </task-notification>
<task-notification> <task-id>bwudt5609</task-id> <tool-use-id>toolu_014JsEdXFVoCoAnF3zispY36</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/283be278-5c6a-4a71-a8d6-b3d32c668985/tasks/bwudt5609.output</output-file> <status>completed</status> <summary>Background command "Wait for Astra Task 6 review" completed (exit code 0)</summary> </task-notification>
<task-notification> <task-id>a34186f1615228cac</task-id> <tool-use-id>toolu_01UDTJEZ8ophJWEhMKseZhUC</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/283be278-5c6a-4a71-a8d6-b3d32c668985/tasks/a34186f1615228cac.output</output-file> <status>completed</status> <summary>Agent "Fable review of Task 6" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>Verdict: Needs fixes (review at `.superpowers/sdd/2026-11-08-region-ha-held-requests/task-6-review-fable.md`). Critical 0, Important 2, Minor 6. Important: floor API errors downgrade a roll to DR-4 instead of refusing; the H5 lock sweep's bucket is taken from A's own edges file.</result> <usage><subagent_tokens>193735</subagent_tokens><tool_uses>46</tool_uses><duration_ms>666317</duration_ms></usage> </task-notification>
diff --git a/infra/modules/region-group-operator-document/README.md b/infra/modules/region-group-operator-document/README.md| index 0d90fb467..3e0829112 100644 |
| --- a/infra/modules/region-group-operator-document/README.md |
| +++ b/infra/modules/region-group-operator-document/README.md |
| @@ -60,13 +60,15 @@ printf %s B64 | base64 -d | /opt/carlos/carlos system group-maintenance permit & |
| /usr/bin/timeout --signal=TERM --kill-after=30s 900s /opt/carlos/carlos system group-maintenance apply |
| /usr/bin/timeout --signal=TERM --kill-after=30s 900s /opt/carlos/carlos system group-maintenance rollback |
| /usr/bin/timeout --signal=TERM --kill-after=30s 3600s /opt/carlos/carlos system group-maintenance drain TX |
| +/usr/bin/timeout --signal=TERM --kill-after=30s 300s /opt/carlos/carlos system group-maintenance drain --cancel TX && /opt/carlos/carlos system group-maintenance status |
| /opt/carlos/carlos system group-maintenance fence-clear TX && /opt/carlos/carlos system group-maintenance status |
| /usr/bin/timeout --signal=TERM --kill-after=10s 120s /usr/bin/systemctl stop carlos-edge.service; /usr/bin/systemctl show --property=MainPID --property=ActiveState carlos-edge.service |
| ``` |
| `TX` is a transaction ID: 1 to 80 letters, digits, underscores or hyphens, |
| -not starting with a hyphen. The last three forms serve planned handovers |
| -(region HA spec section 25): `replace`, `remove` and the drained `roll`. |
| +not starting with a hyphen. The last four forms serve planned handovers |
| +(region HA spec section 25): `replace`, `remove`, the drained `roll`, and |
| +`cancel-drain` after a failed drain. |
| Branch H is test apparatus for an attended dev witness. It is absent unless |
| `harness_bundle_sha256` is set to the approved bundle's 64-character lowercase |
diff --git a/infra/modules/region-group-operator-document/tool-pattern.txt b/infra/modules/region-group-operator-document/tool-pattern.txt| index 465a605d0..cfbd1c7b1 100644 |
| --- a/infra/modules/region-group-operator-document/tool-pattern.txt |
| +++ b/infra/modules/region-group-operator-document/tool-pattern.txt |
| @@ -1 +1 @@ |
| -/usr/bin/env -i PATH=/usr/sbin:/usr/bin:/sbin:/bin HOME=/root /bin/sh -c '\[ "\$\(id -u\)" = 0 \] \|\| exit 77; printf '"'"'\\n[0-9a-f]{32}:BEGIN\\n'"'"'; \((/opt/carlos/carlos system group-maintenance (status|revoke)|/opt/carlos/carlos system group-maintenance prepare --sha256 [0-9a-f]{64}|printf %s [A-Za-z0-9+/=]+ \| base64 -d \| /opt/carlos/carlos system group-maintenance permit && /opt/carlos/carlos system group-maintenance status|/usr/bin/timeout --signal=TERM --kill-after=30s 900s /opt/carlos/carlos system group-maintenance (apply|rollback)|/usr/bin/timeout --signal=TERM --kill-after=30s 3600s /opt/carlos/carlos system group-maintenance drain [A-Za-z0-9_][A-Za-z0-9_-]{0,79}|/opt/carlos/carlos system group-maintenance fence-clear [A-Za-z0-9_][A-Za-z0-9_-]{0,79} && /opt/carlos/carlos system group-maintenance status|/usr/bin/timeout --signal=TERM --kill-after=10s 120s /usr/bin/systemctl stop carlos-edge\.service; /usr/bin/systemctl show --property=MainPID --property=ActiveState carlos-edge\.service)\); result=\$\?; printf '"'"'\\n[0-9a-f]{32}:END:%s\\n'"'"' "\$result"' |
| +/usr/bin/env -i PATH=/usr/sbin:/usr/bin:/sbin:/bin HOME=/root /bin/sh -c '\[ "\$\(id -u\)" = 0 \] \|\| exit 77; printf '"'"'\\n[0-9a-f]{32}:BEGIN\\n'"'"'; \((/opt/carlos/carlos system group-maintenance (status|revoke)|/opt/carlos/carlos system group-maintenance prepare --sha256 [0-9a-f]{64}|printf %s [A-Za-z0-9+/=]+ \| base64 -d \| /opt/carlos/carlos system group-maintenance permit && /opt/carlos/carlos system group-maintenance status|/usr/bin/timeout --signal=TERM --kill-after=30s 900s /opt/carlos/carlos system group-maintenance (apply|rollback)|/usr/bin/timeout --signal=TERM --kill-after=30s 3600s /opt/carlos/carlos system group-maintenance drain [A-Za-z0-9_][A-Za-z0-9_-]{0,79}|/usr/bin/timeout --signal=TERM --kill-after=30s 300s /opt/carlos/carlos system group-maintenance drain --cancel [A-Za-z0-9_][A-Za-z0-9_-]{0,79} && /opt/carlos/carlos system group-maintenance status|/opt/carlos/carlos system group-maintenance fence-clear [A-Za-z0-9_][A-Za-z0-9_-]{0,79} && /opt/carlos/carlos system group-maintenance status|/usr/bin/timeout --signal=TERM --kill-after=10s 120s /usr/bin/systemctl stop carlos-edge\.service; /usr/bin/systemctl show --property=MainPID --property=ActiveState carlos-edge\.service)\); result=\$\?; printf '"'"'\\n[0-9a-f]{32}:END:%s\\n'"'"' "\$result"' |
diff --git a/infra/modules/region-host/group_operator.tf b/infra/modules/region-host/group_operator.tf| index 686fd971e..54fc07857 100644 |
| --- a/infra/modules/region-host/group_operator.tf |
| +++ b/infra/modules/region-host/group_operator.tf |
| @@ -11,6 +11,16 @@ variable "group_operator_session_document_arn" { |
| } |
| } |
| +variable "group_operator_lock_prefix" { |
| + description = "The region's CARLOS_HIBERNATE_PREFIX, under which each host's lock.json lives. The attended operator may list and read only those locks (region HA planned handovers)." |
| + type = string |
| + default = "instances" |
| + validation { |
| + condition = can(regex("^[A-Za-z0-9._-]+(/[A-Za-z0-9._-]+)*$", var.group_operator_lock_prefix)) && !contains(split("/", var.group_operator_lock_prefix), "..") |
| + error_message = "group_operator_lock_prefix must be a non-empty relative S3 prefix without a leading or trailing slash or a .. segment." |
| + } |
| +} |
| + |
| locals { |
| group_operator_ssm_arn = local.group_enabled ? "arn:${data.aws_partition.current[0].partition}:ssm:${data.aws_region.current.region}:" : "" |
| group_operator_document = local.group_enabled ? coalesce( |
| @@ -38,10 +48,24 @@ output "group_operator_policy_json" { |
| "aws:ResourceTag/carlos:region" = var.group_config.region |
| } } |
| }, |
| + { |
| + # Planned handovers (region HA section 25.6): replace and remove |
| + # terminate the drained Standby member in this group only. The tool's |
| + # adapter never decrements desired here (H4). |
| + Sid = "GroupTerminateDrainedMember" |
| + Effect = "Allow" |
| + Action = ["autoscaling:TerminateInstanceInAutoScalingGroup"] |
| + Resource = aws_autoscaling_group.group[0].arn |
| + Condition = { StringEquals = { |
| + "aws:ResourceTag/carlos:deployment" = var.group_config.deployment |
| + "aws:ResourceTag/carlos:region" = var.group_config.region |
| + } } |
| + }, |
| { |
| Sid = "ObserveMaintenance" |
| Effect = "Allow" |
| - Action = ["autoscaling:DescribeAutoScalingGroups", "autoscaling:DescribeAutoScalingInstances", "autoscaling:DescribeLifecycleHooks", "autoscaling:DescribeScalingActivities", "elasticloadbalancing:DescribeTargetHealth", "ec2:DescribeInstances", "ssm:DescribeInstanceInformation"] |
| + # DescribeLaunchTemplateVersions reads the pinned release for the floor. |
| + Action = ["autoscaling:DescribeAutoScalingGroups", "autoscaling:DescribeAutoScalingInstances", "autoscaling:DescribeLifecycleHooks", "autoscaling:DescribeScalingActivities", "elasticloadbalancing:DescribeTargetHealth", "ec2:DescribeInstances", "ec2:DescribeLaunchTemplateVersions", "ssm:DescribeInstanceInformation"] |
| # These describe actions do not support resource scoping. Only they |
| # receive Resource "*"; requests still stay in the group's AWS region. |
| Resource = "*" |
| @@ -85,6 +109,29 @@ output "group_operator_policy_json" { |
| Action = ["s3:GetObject"] |
| Resource = "${var.deployment_bucket_arn}/control/edges/*" |
| }, |
| + { |
| + # The floor (section 25.9) lists every edges file. Only that prefix. |
| + Sid = "ListMemberEdges" |
| + Effect = "Allow" |
| + Action = ["s3:ListBucket"] |
| + Resource = var.deployment_bucket_arn |
| + Condition = { StringEquals = { "s3:prefix" = "control/edges/" } } |
| + }, |
| + { |
| + # The H5 lock sweep: list the hosts under the prefix, then each |
| + # host's exact lock.json key, and read only lock.json objects. |
| + Sid = "ListRegionLocks" |
| + Effect = "Allow" |
| + Action = ["s3:ListBucket"] |
| + Resource = var.data_bucket_arn |
| + Condition = { StringLike = { "s3:prefix" = ["${var.group_operator_lock_prefix}/", "${var.group_operator_lock_prefix}/*/lock.json"] } } |
| + }, |
| + { |
| + Sid = "ReadRegionLocks" |
| + Effect = "Allow" |
| + Action = ["s3:GetObject"] |
| + Resource = "${var.data_bucket_arn}/${var.group_operator_lock_prefix}/*/lock.json" |
| + }, |
| { |
| # StartSession, gated by the group tag and approved document, creates |
| # sessions. Opening a data channel requires the session token AWS |
diff --git a/infra/modules/region-host/tests/group_operator.tftest.hcl b/infra/modules/region-host/tests/group_operator.tftest.hcl| index b787b2c4f..0cd43de38 100644 |
| --- a/infra/modules/region-host/tests/group_operator.tftest.hcl |
| +++ b/infra/modules/region-host/tests/group_operator.tftest.hcl |
| @@ -131,10 +131,20 @@ run "operator_policy" { |
| "aws:ResourceTag/carlos:region" = "ie" |
| } } |
| }, |
| + { |
| + Sid = "GroupTerminateDrainedMember" |
| + Effect = "Allow" |
| + Action = ["autoscaling:TerminateInstanceInAutoScalingGroup"] |
| + Resource = aws_autoscaling_group.group[0].arn |
| + Condition = { StringEquals = { |
| + "aws:ResourceTag/carlos:deployment" = "dev" |
| + "aws:ResourceTag/carlos:region" = "ie" |
| + } } |
| + }, |
| { |
| Sid = "ObserveMaintenance" |
| Effect = "Allow" |
| - Action = ["autoscaling:DescribeAutoScalingGroups", "autoscaling:DescribeAutoScalingInstances", "autoscaling:DescribeLifecycleHooks", "autoscaling:DescribeScalingActivities", "elasticloadbalancing:DescribeTargetHealth", "ec2:DescribeInstances", "ssm:DescribeInstanceInformation"] |
| + Action = ["autoscaling:DescribeAutoScalingGroups", "autoscaling:DescribeAutoScalingInstances", "autoscaling:DescribeLifecycleHooks", "autoscaling:DescribeScalingActivities", "elasticloadbalancing:DescribeTargetHealth", "ec2:DescribeInstances", "ec2:DescribeLaunchTemplateVersions", "ssm:DescribeInstanceInformation"] |
| Resource = "*" |
| Condition = { StringEquals = { "aws:RequestedRegion" = "eu-west-1" } } |
| }, |
| @@ -167,6 +177,26 @@ run "operator_policy" { |
| Action = ["s3:GetObject"] |
| Resource = "arn:aws:s3:::carlos-dev-platform/control/edges/*" |
| }, |
| + { |
| + Sid = "ListMemberEdges" |
| + Effect = "Allow" |
| + Action = ["s3:ListBucket"] |
| + Resource = "arn:aws:s3:::carlos-dev-platform" |
| + Condition = { StringEquals = { "s3:prefix" = "control/edges/" } } |
| + }, |
| + { |
| + Sid = "ListRegionLocks" |
| + Effect = "Allow" |
| + Action = ["s3:ListBucket"] |
| + Resource = "arn:aws:s3:::carlos-dev-ie" |
| + Condition = { StringLike = { "s3:prefix" = ["instances/", "instances/*/lock.json"] } } |
| + }, |
| + { |
| + Sid = "ReadRegionLocks" |
| + Effect = "Allow" |
| + Action = ["s3:GetObject"] |
| + Resource = "arn:aws:s3:::carlos-dev-ie/instances/*/lock.json" |
| + }, |
| { |
| Sid = "OwnSessionDataChannel" |
| Effect = "Allow" |
| @@ -179,17 +209,56 @@ run "operator_policy" { |
| } |
| assert { |
| condition = !anytrue([for s in jsondecode(output.group_operator_policy_json).Statement : |
| - anytrue([for a in s.Action : contains(["autoscaling:CompleteLifecycleAction", "ec2:TerminateInstances", "autoscaling:TerminateInstanceInAutoScalingGroup", "autoscaling:SetDesiredCapacity", "autoscaling:SetInstanceHealth", "ssm:SendCommand"], a) || startswith(a, "ssm:GetParameter")]) |
| + anytrue([for a in s.Action : contains(["autoscaling:CompleteLifecycleAction", "ec2:TerminateInstances", "autoscaling:SetDesiredCapacity", "autoscaling:SetInstanceHealth", "ssm:SendCommand", "s3:PutObject", "s3:DeleteObject"], a) || startswith(a, "ssm:GetParameter")]) |
| ]) |
| - error_message = "the roll policy must not grant lifecycle completion, termination, direct capacity or health changes, Run Command or parameter reads" |
| + error_message = "the roll policy must not grant lifecycle completion, EC2 termination, direct capacity or health changes, Run Command, S3 writes or parameter reads" |
| + } |
| + assert { |
| + # Group termination is scoped to this group's ARN, with its tags, in one statement. |
| + condition = alltrue([for s in jsondecode(output.group_operator_policy_json).Statement : |
| + !contains(s.Action, "autoscaling:TerminateInstanceInAutoScalingGroup") || ( |
| + s.Action == ["autoscaling:TerminateInstanceInAutoScalingGroup"] && |
| + s.Resource == aws_autoscaling_group.group[0].arn && length(s.Condition.StringEquals) == 2) |
| + ]) && length([for s in jsondecode(output.group_operator_policy_json).Statement : s if contains(s.Action, "autoscaling:TerminateInstanceInAutoScalingGroup")]) == 1 |
| + error_message = "termination in the group must be granted once, on this group's ARN only, with the deployment and region tag conditions" |
| } |
| + assert { |
| + # Every S3 grant names an exact prefix or lock.json keys; no bucket-wide list or read. |
| + condition = alltrue([for s in jsondecode(output.group_operator_policy_json).Statement : |
| + s.Action != ["s3:ListBucket"] || can(s.Condition.StringEquals["s3:prefix"]) || can(s.Condition.StringLike["s3:prefix"]) |
| + ]) && alltrue([for s in jsondecode(output.group_operator_policy_json).Statement : |
| + s.Action != ["s3:GetObject"] || endswith(s.Resource, "/control/edges/*") || endswith(s.Resource, "/*/lock.json") |
| + ]) |
| + error_message = "S3 list grants must carry a prefix condition and reads must be limited to edges files and lock.json keys" |
| + } |
| +} |
| + |
| +run "custom_lock_prefix" { |
| + command = plan |
| + variables { group_operator_lock_prefix = "shop/instances" } |
| + assert { |
| + condition = [for s in jsondecode(output.group_operator_policy_json).Statement : s.Resource if s.Sid == "ReadRegionLocks"] == ["arn:aws:s3:::carlos-dev-ie/shop/instances/*/lock.json"] |
| + error_message = "the lock read must follow the configured prefix" |
| + } |
| +} |
| + |
| +run "invalid_lock_prefix" { |
| + command = plan |
| + variables { group_operator_lock_prefix = "instances/" } |
| + expect_failures = [var.group_operator_lock_prefix] |
| +} |
| + |
| +run "invalid_lock_prefix_dotdot" { |
| + command = plan |
| + variables { group_operator_lock_prefix = "a/../b" } |
| + expect_failures = [var.group_operator_lock_prefix] |
| } |
| run "custom_session_document" { |
| command = plan |
| variables { group_operator_session_document_arn = "arn:aws:ssm:eu-west-1:123456789012:document/shop-maintenance" } |
| assert { |
| - condition = jsondecode(output.group_operator_policy_json).Statement[3].Resource == var.group_operator_session_document_arn |
| + condition = [for s in jsondecode(output.group_operator_policy_json).Statement : s.Resource if s.Sid == "ApprovedSessionDocument"] == [var.group_operator_session_document_arn] |
| error_message = "only the configured session document may be authorized" |
| } |
| } |
diff --git a/scripts/region-group-roll.py b/scripts/region-group-roll.py| index fbe3df269..18437cc2a 100755 |
| --- a/scripts/region-group-roll.py |
| +++ b/scripts/region-group-roll.py |
| @@ -52,9 +52,11 @@ The operator's AWS_CONFIG_FILE, AWS_SHARED_CREDENTIALS_FILE and AWS_CA_BUNDLE |
| pass through for profile and trust configuration. Ambient access keys, profile |
| selection and AWS_ENDPOINT_URL overrides are removed. --profile is explicit. |
| -Planned handovers (region HA spec section 25). Two optional config keys enable |
| -them: ha_floor, the first release with held requests, and data_prefix, the |
| -region's CARLOS_HIBERNATE_PREFIX ("" for none). replace and remove share one |
| +Planned handovers (region HA spec section 25). Three optional config keys enable |
| +them: ha_floor, the first release with held requests; data_bucket, the region's |
| +data bucket (CARLOS_HIBERNATE_BUCKET); and data_prefix, the region's |
| +CARLOS_HIBERNATE_PREFIX ("" for none). The H5 lock sweep reads only these, |
| +never the member's own edges file. replace and remove share one |
| shape: preflight and the floor, lower minimum, EnterStandby with decrement, |
| verify deregistration, drain, re-read every lock that names the member, check |
| the start fence and the agent's incarnation, stop carlos-edge.service and prove |
| @@ -66,7 +68,8 @@ fence with fence-clear, then restores minimum. Without the floor, roll uses |
| DR-4's lock-free rule and says so; replace and remove refuse. Desired capacity |
| is lowered only by the member's EnterStandby with decrement (H4). A failed |
| drain returns the member and restores the shape; the member stays fenced and |
| -draining until the operator runs drain --cancel on it. |
| +draining until the operator runs cancel-drain with the member and transaction. |
| +A floor that cannot be read refuses the transaction; it never falls back to DR-4. |
| """ |
| import argparse |
| import base64 |
| @@ -172,13 +175,20 @@ TEXT = { |
| "rule_drain": "Floor met: drain before the provider action (section 25).", |
| "rule_dr4": "Floor not met: DR-4's lock-free rule applies. Replace only lock-free members.", |
| "floor_refused": "The held-requests floor is not met, so this member cannot be drained. DR-4's lock-free rule applies", |
| - "floor_config": "The config has no ha_floor or data_prefix", |
| + "floor_config": "The config has no ha_floor, data_bucket or data_prefix", |
| + "floor_error": "The held-requests floor could not be read, so the rule cannot be chosen. Nothing was changed", |
| + "lock_sweep_missed": "The lock sweep did not find the lock of moved host {host}", |
| + "data_bucket_mismatch": "The member's edges file names data bucket {bucket}, not the configured one", |
| + "cancel_drain": "End a failed drain of this member: drain --cancel on the box, which lifts the fence.", |
| + "cancel_refused": "cancel-drain needs this member's transaction, closed after a failed drain", |
| + "cancel_failed": "drain --cancel did not finish. The fence stays: {detail}", |
| + "cancelled": "The drain was cancelled and the start fence removed.", |
| "floor_box": "Live box {box} does not publish ha_take: 1", |
| "floor_unreadable": "The edges file {key} cannot be read", |
| "floor_template": "The pinned launch template boots release {release}, below ha_floor", |
| "floor_version": "The roll's release {release} is below ha_floor", |
| "drain_failed": "The drain failed. The member was returned to service and the group shape restored", |
| - "drain_cancel": "The member stays fenced and draining. To end it, run on {iid}: carlos system group-maintenance drain --cancel {transaction}", |
| + "drain_cancel": "The member stays fenced and draining. To end it, run: region-group-roll.py cancel-drain --member {iid} --transaction {transaction}", |
| "drain_reason": "drain: {reason}", |
| "drain_report": "The drain printed no valid report for this transaction", |
| "fence_missing": "The start fence of this transaction is not in place", |
| @@ -193,7 +203,7 @@ TEXT = { |
| "remove_pools": "The survivors would leave pool {pool} with no server", |
| "remove_pools_unknown": "The member's served_pools are unknown", |
| "watch_timeout": "The replacement or the departure did not finish in time", |
| - "lock_held_resume": "A lock still names the member after its edge stopped. The member is held in Standby", |
| + "lock_held_after_stop": "A lock still names the member after its edge stopped. The member is held in Standby", |
| "fence_moot": "The member is gone, so its start fence went with it. No fence-clear is needed.", |
| "replaced": "Member replaced.", |
| "removed": "Member removed. Set box_count to {n} in the region's tofu and apply; the plan should show no instance change.", |
| @@ -207,8 +217,10 @@ WAIT = 900 |
| # covers 900 awake hosts. The local bound adds the 30 s TERM grace and a margin. |
| DRAIN_BOUND = 3600 |
| EDGE_STOP_BOUND = 120 |
| +CANCEL_BOUND = 300 |
| SESSION_TIMEOUTS = {"prepare": 360, "apply": 990, "rollback": 990, |
| - "drain": DRAIN_BOUND + 90, "edge-stop": EDGE_STOP_BOUND + 90, "fence-clear": 30} |
| + "drain": DRAIN_BOUND + 90, "edge-stop": EDGE_STOP_BOUND + 90, "fence-clear": 60, |
| + "drain-cancel": CANCEL_BOUND + 90} |
| DEPART_KINDS = ("replace", "remove") |
| # boxchoice.MaxEdgesAge and maxEdgesSkew: an edges file is live while its |
| # generation is at most 15 minutes old and at most 1 minute in the future. |
| @@ -423,10 +435,12 @@ def validate_config(c): |
| keys = {"deployment", "account", "region", "group", "group_arn", "hook", |
| "target_groups", "bucket", "document", "state_dir", "profile", "min_release"} |
| # Optional: the held-requests floor release and the hibernate prefix. |
| - optional = {"ha_floor", "data_prefix"} |
| + optional = {"ha_floor", "data_prefix", "data_bucket"} |
| require(isinstance(c, dict) and keys <= set(c) <= keys | optional, "config_invalid") |
| if "ha_floor" in c: |
| require(release_version(c["ha_floor"]) is not None, "config_invalid") |
| + if "data_bucket" in c: |
| + require(isinstance(c["data_bucket"], str) and BUCKET.fullmatch(c["data_bucket"]), "config_invalid") |
| if "data_prefix" in c: |
| require(isinstance(c["data_prefix"], str) and len(c["data_prefix"]) <= 1024 and |
| (c["data_prefix"] == "" or |
| @@ -739,15 +753,20 @@ class AWS: |
| def remote_command(a, nonce): |
| verb = a["verb"] |
| require(verb in {"status", "prepare", "permit", "revoke", "apply", "rollback", |
| - "drain", "fence-clear", "edge-stop"}, "unsupported") |
| + "drain", "drain-cancel", "fence-clear", "edge-stop"}, "unsupported") |
| binary = "/opt/carlos/carlos" |
| command = binary + " system group-maintenance " + verb |
| - if verb in {"drain", "fence-clear"}: |
| + if verb in {"drain", "drain-cancel", "fence-clear"}: |
| # groupTransactionID, and never a leading "-" (the verb's own rule). |
| tx = a["transaction"] |
| require(isinstance(tx, str) and TX.fullmatch(tx) and not tx.startswith("-"), "record") |
| command += " " + tx |
| - if verb == "drain": |
| + if verb == "drain-cancel": |
| + # The root verb removes the fence only on a confirmed stop |
| + # (internal/host/group_maintenance_drain.go); status shows it. |
| + command = ("/usr/bin/timeout --signal=TERM --kill-after=30s %ds %s system group-maintenance " |
| + "drain --cancel %s && %s system group-maintenance status" % (CANCEL_BOUND, binary, tx, binary)) |
| + elif verb == "drain": |
| command = "/usr/bin/timeout --signal=TERM --kill-after=30s %ds %s" % (DRAIN_BOUND, command) |
| else: |
| command += " && " + binary + " system group-maintenance status" |
| @@ -842,7 +861,8 @@ class AWS: |
| description = row.get("Description", "") |
| # AWS documents "to Standby"; keep accepting "into Standby" too. |
| kind = "exit" if "out of Standby" in description else ( |
| - "enter" if any(s in description for s in ("to Standby", "into Standby")) else None) |
| + "enter" if any(s in description for s in ("to Standby", "into Standby")) else |
| + "terminate" if description.startswith("Terminating EC2 instance") else None) |
| if re.search(r"\b" + re.escape(a["iid"]) + r"\b", description) and kind: |
| dt = datetime.fromisoformat(row["StartTime"].replace("Z", "+00:00")) |
| result.append(dict(id=row["ActivityId"], iid=a["iid"], time=dt.timestamp(), kind=kind)) |
| @@ -881,10 +901,13 @@ class AWS: |
| require(len(match) == 1, "remote") |
| if a["verb"] == "drain": |
| return self.drain_output(*match[0]) |
| + if a["verb"] == "drain-cancel" and match[0][1] == "1": |
| + # A refused cancel keeps the fence; carry the verb's reason. |
| + return dict(exit=1, detail=match[0][0].strip()[-512:]) |
| require(match[0][1] == "0", "remote") |
| if a["verb"] == "edge-stop": |
| return self.edge_stop_output(match[0][0]) |
| - if a["verb"] in {"status", "prepare", "permit", "fence-clear"}: |
| + if a["verb"] in {"status", "prepare", "permit", "fence-clear", "drain-cancel"}: |
| require(len(match[0][0].encode()) <= 8192, "remote") |
| return decode(match[0][0]) |
| return {} |
| @@ -1147,9 +1170,11 @@ class Operator: |
| instant(e.get("generation")) >= instant(s["edge"].get("started_at")) + 2 and |
| 0 <= self.clock() - observed <= 60, "admission") |
| if maintenance and self.unchanged(): |
| - # A failed drain returns the member it found: no action ran. |
| - require(s["binary_sha256"] == self.header["old"] and |
| - s["edge"]["identity"] == self.header["original_process"], "process") |
| + # A failed drain returns the member with no action run: the same |
| + # binary on the same boot (identity() checks it). The process may |
| + # be a restarted agent, which is why the drain failed; the fence |
| + # keeps it from starting anything until cancel-drain. |
| + require(s["binary_sha256"] == self.header["old"], "process") |
| elif maintenance: |
| action = self.action() |
| restored = self.j.last("rollback-requested", already_restored=True) |
| @@ -1716,6 +1741,8 @@ class Operator: |
| self.box(iid, "revoke") |
| require(self.box(iid)["permit"].get("state") == "absent", "permit") |
| failed_drain = self.unchanged() |
| + if self.j.last("drained") and not failed_drain: |
| + self.drain_summary() |
| self.event("done", outcome="drain-failed" if failed_drain else |
| "failed-probe-recovered" if self.j.last("failed-probe") else "returned", |
| provider_divergence=self.state.blocked.exists()) |
| @@ -1738,9 +1765,11 @@ class Operator: |
| def floor(self, kind, version=None): |
| """Section 25.9. Drain only if every live box publishes ha_take: 1 and |
| the release the transaction leaves running is at or above ha_floor.""" |
| - reasons, live = [], [] |
| + # reasons are definite findings below the floor, so DR-4 applies. |
| + # errors mean the floor could not be read: refuse, never fall back. |
| + reasons, errors, live = [], [], [] |
| floor = self.c.get("ha_floor") |
| - if floor is None or "data_prefix" not in self.c: |
| + if floor is None or "data_prefix" not in self.c or "data_bucket" not in self.c: |
| reasons.append(TEXT["floor_config"]) |
| else: |
| try: |
| @@ -1751,7 +1780,7 @@ class Operator: |
| try: |
| e = self.call("edges_key", key=key) |
| except (Refusal, Uncertain): |
| - reasons.append(TEXT["floor_unreadable"].format(key=key)) |
| + errors.append(TEXT["floor_unreadable"].format(key=key)) |
| continue |
| try: |
| age = self.clock() - instant(e.get("generation") if isinstance(e, dict) else None) |
| @@ -1766,12 +1795,23 @@ class Operator: |
| reasons.append(TEXT["floor_box"].format(box=match[1])) |
| if kind == "replace": |
| release = self.call("template_release", template=self.header["template"]) |
| - if release_version(release) is None or below_floor(release, floor): |
| + if release_version(release) is None: |
| + # A SHA or suffixed release cannot be compared. |
| + errors.append(TEXT["floor_template"].format(release=release)) |
| + elif below_floor(release, floor): |
| reasons.append(TEXT["floor_template"].format(release=release)) |
| - if kind == "roll" and (release_version(version) is None or below_floor(version, floor)): |
| - reasons.append(TEXT["floor_version"].format(release=version)) |
| + if kind == "roll": |
| + if release_version(version) is None: |
| + errors.append(TEXT["floor_version"].format(release=version)) |
| + elif below_floor(version, floor): |
| + reasons.append(TEXT["floor_version"].format(release=version)) |
| except (Refusal, Uncertain) as exc: |
| - reasons.append(str(exc)) |
| + errors.append(str(exc)) |
| + if errors: |
| + self.event("floor-error", errors=errors, reasons=reasons) |
| + for reason in errors: |
| + self.say("floor", reason) |
| + raise Refusal(TEXT["floor_error"]) |
| rule = "dr4" if reasons else "drain" |
| self.event("floor", rule=rule, reasons=reasons, live=live, ha_floor=floor) |
| self.say("rule", TEXT["rule_drain"] if rule == "drain" else TEXT["rule_dr4"]) |
| @@ -1810,21 +1850,28 @@ class Operator: |
| def locks_naming_member(self): |
| """Every lock in the region's data bucket that names the member and is |
| - neither a release marker nor another box's (section 25.6 step 4).""" |
| + neither a release marker nor another box's (section 25.6 step 4). |
| + The bucket and prefix are the tool's own config, never the member's |
| + word. Each host the drain moved must be found with a lock, or the |
| + sweep looked in the wrong place.""" |
| ident = self.header["identity"] |
| ref, iid = ident["box_ref"], self.header["iid"] |
| + bucket, prefix = self.c["data_bucket"], self.c["data_prefix"] |
| + # A cross-check only: a member naming another bucket is misconfigured. |
| e = self.call("edges", box_ref=ref) |
| - bucket = e.get("data_bucket") if isinstance(e, dict) else None |
| - require(isinstance(bucket, str) and BUCKET.fullmatch(bucket) and |
| - e.get("data_bucket_region") == self.c["region"], "data_bucket") |
| - prefix = self.c["data_prefix"] |
| - held = [] |
| + named = e.get("data_bucket") if isinstance(e, dict) else None |
| + if named != bucket: |
| + raise Refusal(TEXT["data_bucket_mismatch"].format(bucket=named)) |
| + report = (self.j.last("drained") or {}).get("report") or {} |
| + moved = {m.get("host") for m in report.get("moved") or [] if isinstance(m, dict)} |
| + held, seen = [], set() |
| for host in self.call("lock_hosts", bucket=bucket, prefix=prefix): |
| if not HOST_NAME.fullmatch(host): |
| continue |
| v = self.call("lock", bucket=bucket, prefix=prefix, host=host) |
| if v.get("absent") is True: |
| continue |
| + seen.add(host) |
| lock = v.get("lock") |
| owner = lock.get("owner") if isinstance(lock, dict) else None |
| if isinstance(lock, dict) and (lock.get("carlos_release") is not None or |
| @@ -1838,6 +1885,8 @@ class Operator: |
| held.append(host) |
| elif ref in owner or iid in owner: |
| held.append(host) |
| + for host in sorted(moved - seen): |
| + raise Refusal(TEXT["lock_sweep_missed"].format(host=host)) |
| return held |
| def pre_action(self): |
| @@ -1948,8 +1997,7 @@ class Operator: |
| require(self.rule() == "drain", "record") |
| # The H5 check passed before the first edge-stop was sent. A stopped |
| # agent cannot answer it again, so after a cut re-prove the stop and |
| - # read the locks again instead. |
| - resumed_stop = self.stop_sent() |
| + # read the locks again instead (stop_and_terminate). |
| end = self.clock() + WAIT |
| peers_checked = False |
| while not self.j.last("intent", op="terminate"): |
| @@ -1983,10 +2031,13 @@ class Operator: |
| continue |
| if phase not in {"Standby", "EnteringStandby"}: |
| self.alert("members") |
| - self.standby(g, deregistered=False) |
| + # EnterStandby is asynchronous: while entry is pending check the |
| + # capacity only, then wait for the settled Standby state. |
| + require(g["minimum"] == g["desired"] == n - 1, "held") |
| if phase != "Standby" or not all(t.get(iid, "unused") == "unused" for t in g["targets"]): |
| self.sleep(max(0, min(5, end - self.clock()))) |
| continue |
| + self.standby(g) |
| for member in h["members"]: |
| if member != iid: |
| require(g["members"][member] == "InService" and g["healthy"].get(member) is True and |
| @@ -1998,22 +2049,24 @@ class Operator: |
| self.pre_action() |
| except DrainFailed: |
| return self.return_member() |
| - self.stop_edge() |
| - if resumed_stop: |
| - # The edge may have been restarted since the last proof. It ran |
| - # fenced, but read the locks again after this stop. |
| - held = self.locks_naming_member() |
| - if held: |
| - self.alert("lock_held_resume") |
| - self.event("phase", phase="terminate") |
| - try: |
| - result = self.call("terminate", iid=iid, decrement=False) |
| - if result.get("activity"): |
| - self.event("terminate-activity", activity=result["activity"]) |
| - except Uncertain: |
| - pass |
| + self.stop_and_terminate() |
| return self.depart_watch() |
| + def stop_and_terminate(self): |
| + """Prove the edge stopped, read the locks once more now that the |
| + member can change nothing, then make the provider call.""" |
| + iid = self.header["iid"] |
| + self.stop_edge() |
| + if self.locks_naming_member(): |
| + self.alert("lock_held_after_stop") |
| + self.event("phase", phase="terminate") |
| + try: |
| + result = self.call("terminate", iid=iid, decrement=False) |
| + if result.get("activity"): |
| + self.event("terminate-activity", activity=result["activity"]) |
| + except Uncertain: |
| + pass |
| + |
| def stop_sent(self): |
| return any(r["kind"] == "intent" and r.get("op") == "session" and |
| r["args"].get("verb") == "edge-stop" for r in self.j.events) |
| @@ -2031,17 +2084,18 @@ class Operator: |
| require(g["maximum"] == n and g["template"] == h["template"], "members") |
| phase = g["members"].get(iid) |
| if phase is not None and not phase.startswith("Terminat"): |
| - # Still a member: retry only a terminate that got no answer. |
| + # Still a member. A terminate the provider never answered (an |
| + # error, or a hard cut after the durable intent that left no |
| + # row at all) is sent again, unless the provider's activities |
| + # show it arrived; a received one is waited for. |
| require(phase == "Standby", "members") |
| - if self.j.last("error", op="terminate") and ( |
| - self.j.last("error", op="terminate")["seq"] > |
| - (self.j.last("response", op="terminate") or {}).get("seq", -1)): |
| - self.stop_edge() |
| - self.event("phase", phase="terminate") |
| - try: |
| - self.call("terminate", iid=iid, decrement=False) |
| - except Uncertain: |
| - pass |
| + intent = self.j.last("intent", op="terminate") |
| + answered = any(r["kind"] == "response" and r.get("intent") == intent["seq"] |
| + for r in self.j.events) |
| + if not answered and not any( |
| + a.get("kind") == "terminate" and a.get("time", 0) >= intent["at"] - 5 |
| + for a in self.call("activities", iid=iid)): |
| + self.stop_and_terminate() |
| continue |
| self.sleep(max(0, min(5, end - self.clock()))) |
| continue |
| @@ -2089,21 +2143,51 @@ class Operator: |
| return self.finish_depart(start, departed_at, replacement) |
| self.sleep(max(0, min(5, end - self.clock()))) |
| - def finish_depart(self, start, departed_at, replacement): |
| - h, kind, n = self.header, self.kind(), self.header["n"] |
| - # R3.1: the fence lived in the member's /run, which went with it. |
| - self.event("fence-moot", reason=TEXT["fence_moot"]) |
| - self.say("fence", TEXT["fence_moot"]) |
| + def drain_summary(self, **extra): |
| + """The drain's outcome for the operator: one JSON line, journaled.""" |
| + h = self.header |
| report = (self.j.last("drained") or {}).get("report") or {} |
| holds = report.get("holds") if isinstance(report.get("holds"), dict) else {} |
| - summary = dict(transaction=h["transaction"], transaction_kind=kind, member=h["iid"], replacement=replacement, |
| + summary = dict(transaction=h["transaction"], transaction_kind=self.kind(), member=h["iid"], |
| hosts_moved=len(report.get("moved") or []), |
| hosts_released=len(report.get("released") or []), |
| longest_hold_ms=holds.get("longest_ms"), todays_answer=holds.get("todays_answer"), |
| - connections_closed_at_bound=report.get("connections_closed_at_bound"), |
| - departure_seconds=departed_at - start) |
| + connections_closed_at_bound=report.get("connections_closed_at_bound"), **extra) |
| self.event("report", **summary) |
| print(json.dumps(summary, sort_keys=True), file=self.output, flush=True) |
| + |
| + def cancel_drain(self, iid, transaction): |
| + """drain --cancel for a transaction closed after a failed drain. The |
| + root verb removes the fence only on a confirmed stop; status proves it.""" |
| + require(self.state.held and isinstance(transaction, str) and TX.fullmatch(transaction) and |
| + not transaction.startswith("-"), "record") |
| + self.j = self.state.load(transaction) |
| + self.header = self.j.events[0] |
| + done = self.j.last("done") |
| + require(self.kind() in (self.journal_kind,) + DEPART_KINDS and self.header["iid"] == iid and |
| + done and done.get("outcome") == "drain-failed" and self.j.last("drain-failed"), |
| + "cancel_refused") |
| + self.header = dict(self.header, **{k: v for k, v in (self.j.last("validated") or {}).items() |
| + if k not in {"seq", "previous", "hash", "kind", "at"}}) |
| + r = self.box(iid, "drain-cancel", transaction=transaction) |
| + if r.get("exit") == 1: |
| + self.event("drain-cancel-failed", detail=r.get("detail")) |
| + raise Refusal(TEXT["cancel_failed"].format(detail=r.get("detail"))) |
| + self.identity(r, iid) |
| + fence = r.get("fence") or {} |
| + drain = r.get("drain") or {} |
| + if fence.get("state") != "absent" or drain.get("transaction") == transaction: |
| + self.event("drain-cancel-failed", fence=fence, drain=drain) |
| + raise Refusal(TEXT["cancel_failed"].format(detail=json.dumps(dict(fence=fence, drain=drain)))) |
| + self.event("drain-cancelled", fence=fence, drain=drain, attended_by=self.attended) |
| + self.say("cancel-drain", TEXT["cancelled"]) |
| + |
| + def finish_depart(self, start, departed_at, replacement): |
| + h, kind, n = self.header, self.kind(), self.header["n"] |
| + # R3.1: the fence lived in the member's /run, which went with it. |
| + self.event("fence-moot", reason=TEXT["fence_moot"]) |
| + self.say("fence", TEXT["fence_moot"]) |
| + self.drain_summary(replacement=replacement, departure_seconds=departed_at - start) |
| self.event("done", outcome="replaced" if kind == "replace" else "removed") |
| self.state.finish() |
| self.say("done", TEXT["replaced"] if kind == "replace" else TEXT["removed"].format(n=n - 1)) |
| @@ -2116,8 +2200,12 @@ def main(argv=None): |
| parser.add_argument("--attended-by", help=TEXT["attended"]) |
| sub = parser.add_subparsers(dest="command", required=True) |
| for verb in ("plan", "roll", "replace", "remove", "rollback", "resume", "status", "return", "abandon", |
| - "close-lost"): |
| - p = sub.add_parser(verb, help=TEXT[verb]) |
| + "close-lost", "cancel-drain"): |
| + p = sub.add_parser(verb, help=TEXT["cancel_drain" if verb == "cancel-drain" else verb]) |
| + if verb == "cancel-drain": |
| + p.add_argument("--member", required=True, help=TEXT["member"]) |
| + p.add_argument("--transaction", required=True, help=TEXT["transaction"]) |
| + continue |
| if verb in {"replace", "remove"}: |
| p.add_argument("--member", required=True, help=TEXT["member"]) |
| p.add_argument("--transaction", help=TEXT["depart_transaction"]) |
| @@ -2161,6 +2249,11 @@ def main(argv=None): |
| op.start_depart(args.member, args.command, transaction=args.transaction) |
| finally: |
| journal = op.j |
| + elif args.command == "cancel-drain": |
| + try: |
| + op.cancel_drain(args.member, args.transaction) |
| + finally: |
| + journal = op.j |
| else: |
| journal = state.load(args.transaction) |
| op.j = journal |
diff --git a/scripts/region_group_document_test.py b/scripts/region_group_document_test.py| index 27bf8aeb4..92da3ec7e 100644 |
| --- a/scripts/region_group_document_test.py |
| +++ b/scripts/region_group_document_test.py |
| @@ -55,7 +55,7 @@ class DocumentPatternTests(unittest.TestCase): |
| # Region HA section 25: drain, fence-clear and the edge stop the roll |
| # tool sends for replace, remove and the drained roll. |
| for transaction in ("a", "t6_held-1", "A_9-" * 20): |
| - for verb in ("drain", "fence-clear"): |
| + for verb in ("drain", "drain-cancel", "fence-clear"): |
| command = frames.roll.AWS.remote_command(dict(verb=verb, transaction=transaction), NONCE) |
| with self.subTest(verb=verb, transaction=transaction): |
| self.assertAccepted(command) |
| @@ -63,10 +63,17 @@ class DocumentPatternTests(unittest.TestCase): |
| self.assertAccepted(frames.roll.AWS.remote_command({"verb": "edge-stop"}, NONCE)) |
| drain = frames.roll.AWS.remote_command(dict(verb="drain", transaction="t6"), NONCE) |
| clear = frames.roll.AWS.remote_command(dict(verb="fence-clear", transaction="t6"), NONCE) |
| + cancel = frames.roll.AWS.remote_command(dict(verb="drain-cancel", transaction="t6"), NONCE) |
| stop = frames.roll.AWS.remote_command({"verb": "edge-stop"}, NONCE) |
| bad = { |
| "leading dash": drain.replace("drain t6", "drain -t6"), |
| - "cancel": drain.replace("drain t6", "drain --cancel t6"), |
| + "cancel without bound": drain.replace( |
| + "/usr/bin/timeout --signal=TERM --kill-after=30s 3600s /opt/carlos/carlos system group-maintenance drain t6", |
| + "/opt/carlos/carlos system group-maintenance drain --cancel t6 && " + STATUS), |
| + "cancel under the drain bound": drain.replace("drain t6", "drain --cancel t6 && " + STATUS), |
| + "cancel without status": cancel.replace(" && " + STATUS, ""), |
| + "cancel dash": cancel.replace("--cancel t6", "--cancel -t6"), |
| + "cancel two transactions": cancel.replace("--cancel t6", "--cancel t6 t7"), |
| "two transactions": drain.replace("drain t6", "drain t6 t7"), |
| "long transaction": drain.replace("drain t6", "drain " + "a" * 81), |
| "drain without timeout": drain.replace("/usr/bin/timeout --signal=TERM --kill-after=30s 3600s ", ""), |
diff --git a/scripts/region_group_held_test.py b/scripts/region_group_held_test.py| index 8b0f5919c..7b5e4c1e5 100644 |
| --- a/scripts/region_group_held_test.py |
| +++ b/scripts/region_group_held_test.py |
| @@ -27,7 +27,7 @@ DATA_BUCKET = "example-bucket" |
| def held_config(state_dir): |
| config = base.test_config(state_dir) |
| - config.update(ha_floor="v0.35.0", data_prefix="instances") |
| + config.update(ha_floor="v0.35.0", data_prefix="instances", data_bucket=DATA_BUCKET) |
| return config |
| @@ -77,6 +77,9 @@ class HeldFake(base.Fake): |
| self.launch_delay = 60 |
| self.launched_at = None |
| self.s3 = Counter() |
| + self.entering_polls = 0 |
| + self.cancel_ok = True |
| + self.starts = [] |
| def add_member(self, iid, state): |
| self.states[iid] = state |
| @@ -84,6 +87,23 @@ class HeldFake(base.Fake): |
| self.boxes[iid] = self.box(iid) |
| self.published[iid] = self.now - 5 |
| + def restart_agent(self): |
| + """A restarted edge: a new process and incarnation, not draining.""" |
| + s = self.boxes[IID] |
| + s["edge"].update(state="known", pid=s["edge"]["pid"] + 1 if s["edge"]["pid"] else 300, |
| + identity="restarted-%d" % len(self.starts), started_at=roll.stamp(self.now)) |
| + s["health"].update(state="healthy", code=200) |
| + self.incarnation = RESTARTED |
| + self.drain_state = dict(state="known", incarnation=RESTARTED, transaction=None, step=None, |
| + result="none", error=None) |
| + |
| + def tenant_start(self): |
| + """The agent's start gate (Task 5: fixedAdmission.startAllowed reads |
| + the fence at every start decision).""" |
| + allowed = self.fence is None |
| + self.starts.append(allowed) |
| + return allowed |
| + |
| def violate(self, how): |
| self.h4_violations.append(how) |
| self.states[PEER] = "Terminated" |
| @@ -128,6 +148,15 @@ class HeldFake(base.Fake): |
| if self.after_drain: |
| self.after_drain() |
| return dict(exit=0 if ok else 1, report=report) |
| + if verb == "drain-cancel": |
| + if not self.cancel_ok: |
| + return dict(exit=1, detail="group-maintenance: the edge runs but its drain socket does not answer; the fence stays") |
| + assert self.fence in (None, a["transaction"]) |
| + if self.cancel_ok != "status-disagrees": |
| + self.fence = None |
| + self.drain_state = dict(state="known", incarnation=self.incarnation, transaction=None, step=None, |
| + result="none", error=None) |
| + return self.session(dict(a, verb="status")) |
| if verb == "fence-clear": |
| assert self.fence in (None, a["transaction"]) |
| self.fence = None |
| @@ -228,6 +257,10 @@ class HeldFake(base.Fake): |
| decrement = "--should-decrement-desired-capacity" in args |
| assert iid == IID |
| result = super().perform("enter", dict(iid=iid, decrement=decrement)) |
| + if self.entering_polls: |
| + # Entry is asynchronous: still registered while it settles. |
| + self.states[IID] = "EnteringStandby" |
| + self.tg[IID] = "draining" |
| return dict(Activities=[dict(ActivityId=result["activity"])]) |
| if verb == "exit-standby": |
| result = super().perform("exit", dict(iid=value("--instance-ids"))) |
| @@ -242,6 +275,12 @@ class HeldFake(base.Fake): |
| self.terminated_at = self.now |
| self.departure_at = self.now + self.departure_delay |
| return dict(Activity=dict(ActivityId="terminate-1")) |
| + if verb == "describe-scaling-activities": |
| + result = super().invoke(service, verb, args, **kwargs) |
| + for row, a in zip(result["Activities"], self.activity): |
| + if a["kind"] == "terminate": |
| + row["Description"] = "Terminating EC2 instance: " + a["iid"] |
| + return result |
| if verb == "describe-instance-information": |
| iid = json.loads(value("--filters"))[0]["Values"][0] |
| if iid in (THIRD, REPLACEMENT): |
| @@ -254,6 +293,16 @@ class HeldFake(base.Fake): |
| def sleep(self, seconds): |
| super().sleep(seconds) |
| + if self.states.get(IID) == "EnteringStandby": |
| + self.entering_polls -= 1 |
| + if self.entering_polls <= 0: |
| + self.states[IID], self.tg[IID] = "Standby", "unused" |
| + if getattr(self, "lagging_until", None) is not None and self.now >= self.lagging_until: |
| + # The provider's view catches up with a terminate it received. |
| + self.lagging_until = None |
| + self.states[IID] = "Terminating" |
| + self.terminated_at = self.now |
| + self.departure_at = self.now + self.departure_delay |
| if self.terminated_at is not None and self.now >= self.terminated_at + 30: |
| self.states[IID] = "Terminated" |
| if self.departure_at is not None and self.now >= self.departure_at: |
| @@ -378,11 +427,12 @@ class ReplaceTests(HeldBase): |
| self.assertEqual(journal.last("done")["outcome"], "replaced") |
| self.assertIn(roll.TEXT["rule_drain"], self.output.getvalue()) |
| self.assertIn(roll.TEXT["fence_moot"], self.output.getvalue()) |
| - # Store calls, counted: the lock re-read is one listing page per host |
| + # Store calls, counted: each lock sweep is one listing page per host |
| # (3 here), one exact-key listing per host and one GET per lock that |
| - # exists (idle has none). It runs once per transaction, never on a timer. |
| - self.assertEqual(self.fake.s3[("list-objects-v2", "data")], 3 + 3) |
| - self.assertEqual(self.fake.s3[("get-object", "data")], 2) |
| + # exists (idle has none). It runs twice per transaction, before and |
| + # after the edge stop, never on a timer. |
| + self.assertEqual(self.fake.s3[("list-objects-v2", "data")], 2 * (3 + 3)) |
| + self.assertEqual(self.fake.s3[("get-object", "data")], 2 * 2) |
| def test_replace_resumes_after_every_write(self): |
| for before in (False, True): |
| @@ -455,6 +505,46 @@ class ReplaceTests(HeldBase): |
| with self.journal() as journal: |
| self.assertEqual(journal.last("drain-failed")["reasons"], [roll.TEXT["drain_void"]]) |
| + def test_failed_drain_after_agent_restart_still_returns(self): |
| + # The drain fails because the agent restarted: a new process and |
| + # incarnation. Recovery must still return the member (fenced). |
| + self.fake.after_drain = self.fake.restart_agent |
| + with self.assertRaises(roll.Refusal): |
| + self.depart() |
| + self.assert_returned() |
| + self.assertNotEqual(self.fake.boxes[IID]["edge"]["identity"], "boot-" + IID + ":100:100") |
| + self.assertFalse(self.fake.tenant_start()) |
| + |
| + def test_lock_sweep_bucket_is_the_config(self): |
| + # The member's edges file names another bucket: refuse, never sweep it. |
| + edges_body = self.fake.edges_body |
| + |
| + def other(ref): |
| + body = edges_body(ref) |
| + if ref == REF: |
| + body["data_bucket"] = "other-bucket" |
| + return body |
| + |
| + self.fake.edges_body = other |
| + with self.assertRaises(roll.Refusal): |
| + self.depart() |
| + self.assert_returned() |
| + self.assertEqual(self.fake.s3[("list-objects-v2", "data")], 0) |
| + with self.journal() as journal: |
| + self.assertEqual(journal.last("drain-failed")["reasons"], |
| + [roll.TEXT["data_bucket_mismatch"].format(bucket="other-bucket")]) |
| + |
| + def test_lock_sweep_must_see_moved_hosts(self): |
| + # The drain moved blog; a sweep that finds no blog lock looked in the |
| + # wrong place and must not pass vacuously. |
| + self.fake.locks["blog"] = None |
| + with self.assertRaises(roll.Refusal): |
| + self.depart() |
| + self.assert_returned() |
| + with self.journal() as journal: |
| + self.assertEqual(journal.last("drain-failed")["reasons"], |
| + [roll.TEXT["lock_sweep_missed"].format(host="blog")]) |
| + |
| def test_changed_incarnation_with_finished_drain_refuses(self): |
| # A second agent that reports the same finished drain is still void. |
| def restart(): |
| @@ -496,24 +586,103 @@ class ReplaceTests(HeldBase): |
| self.assert_h4() |
| def test_restart_after_last_check_is_fenced_and_stopped(self): |
| - # R3.1 witness, offline: the agent restarts after the tool's last H5 |
| - # check, while the provider call is still to come. The tool stops the |
| - # edge and proves MainPID 0, and the fence is still in place. |
| + # R3.1 witness, offline. The provider call is delayed by 30 s, and the |
| + # agent restarts after the tool's final check (the stop proof and the |
| + # fence read). The restarted agent tries a tenant start, which the |
| + # fence refuses, and the fence is still this transaction's when the |
| + # provider acts. The Go start gate itself is witnessed by Task 5's |
| + # TestStartFenceRefusesStartsAcrossRestart and |
| + # TestDrainAgentRestartVoidsTheReport (internal/host). |
| request = self.fake.request |
| + seen = {} |
| - def restart_then(op, a): |
| - if op == "session" and a["verb"] == "edge-stop": |
| - self.fake.drain_state = dict(state="known", incarnation=RESTARTED, transaction=None, |
| - step=None, result="none", error=None) |
| - self.assertEqual(self.fake.fence, "t6-held") |
| + def delayed(op, a): |
| if op == "terminate": |
| - self.assertEqual(self.fake.boxes[IID]["edge"]["pid"], None) |
| - self.assertEqual(self.fake.fence, "t6-held") |
| + with self.journal() as journal: |
| + seen["final_check"] = journal.last("edge-stopped")["seq"] |
| + self.fake.sleep(30) |
| + self.fake.restart_agent() |
| + seen["start"] = self.fake.tenant_start() |
| + seen["fence"] = self.fake.fence |
| return request(op, a) |
| - self.fake.request = restart_then |
| + self.fake.request = delayed |
| + self.depart() |
| + self.assertIsNotNone(seen["final_check"]) |
| + self.assertFalse(seen["start"]) |
| + self.assertEqual(seen["fence"], "t6-held") |
| + self.assertEqual(self.fake.states[IID], "Terminated") |
| + self.assert_h4() |
| + |
| + def test_entering_standby_is_waited_for(self): |
| + self.fake.entering_polls = 3 |
| + polls = [] |
| + request = self.fake.request |
| + |
| + def observe(op, a): |
| + result = request(op, a) |
| + if op == "group": |
| + polls.append(result["members"].get(IID)) |
| + return result |
| + |
| + self.fake.request = observe |
| self.depart() |
| + self.assertIn("EnteringStandby", polls) |
| + self.assertEqual(self.fake.states[IID], "Terminated") |
| + # Nothing ran against the member before the settled Standby state. |
| + self.assertEqual(self.verbs(), ["minimum", "enter", "drain", "edge-stop", "terminate", |
| + "desired", "minimum"]) |
| + |
| + def test_hard_cut_after_terminate_intent_resumes(self): |
| + # The process dies after the durable terminate intent and before any |
| + # error or response row: the journal holds only the intent. |
| + self.fake.fail_before, self.fake.fault, self.fake.fault_at = True, "death", 5 |
| + add = roll.Journal.add |
| + |
| + def cut(journal, kind, **data): |
| + if kind == "error" and data.get("op") == "terminate": |
| + raise base.Death("cut") |
| + return add(journal, kind, **data) |
| + |
| + with patch.object(roll.Journal, "add", cut): |
| + with self.assertRaises(base.Death): |
| + self.depart() |
| + with self.journal() as journal: |
| + self.assertIsNotNone(journal.last("intent", op="terminate")) |
| + self.assertIsNone(journal.last("error", op="terminate")) |
| + self.assertIsNone(journal.last("response", op="terminate")) |
| + self.assertEqual(self.fake.states[IID], "Standby") |
| + self.resume() |
| + self.assertEqual(self.fake.writes.count("terminate"), 1) |
| + self.assertEqual(self.fake.states[IID], "Terminated") |
| + self.assertEqual((self.fake.minimum, self.fake.desired), (2, 2)) |
| + self.assertIsNone(self.store.active_id()) |
| + self.assert_h4() |
| + |
| + def test_sent_terminate_is_not_repeated(self): |
| + # A cut after the provider received the terminate, before any row: |
| + # the member still reads Standby for a while, but the provider's |
| + # activity shows the terminate, so resume waits instead of resending. |
| + self.fake.fault, self.fake.fault_at = "death", 5 |
| + add = roll.Journal.add |
| + |
| + def cut(journal, kind, **data): |
| + if kind == "error" and data.get("op") == "terminate": |
| + raise base.Death("cut") |
| + return add(journal, kind, **data) |
| + |
| + with patch.object(roll.Journal, "add", cut): |
| + with self.assertRaises(base.Death): |
| + self.depart() |
| + self.assertEqual(self.fake.writes.count("terminate"), 1) |
| + self.fake.states[IID] = "Standby" |
| + self.fake.terminated_at = None |
| + self.fake.activity.append(dict(id="terminate-1", iid=IID, time=self.fake.now, kind="terminate")) |
| + self.fake.lagging_until = self.fake.now + 20 |
| + self.resume() |
| + self.assertEqual(self.fake.writes.count("terminate"), 1) |
| self.assertEqual(self.fake.states[IID], "Terminated") |
| + self.assertIsNone(self.store.active_id()) |
| def test_provider_changing_desired_on_terminate_fails(self): |
| invoke = self.fake.invoke |
| @@ -531,6 +700,66 @@ class ReplaceTests(HeldBase): |
| self.assertNotIn("desired", self.verbs()) |
| +class CancelDrainTests(HeldBase): |
| + def cancel(self, tx="t6-held", iid=IID): |
| + with self.store.lock(): |
| + op = self.engine() |
| + try: |
| + return op.cancel_drain(iid, tx) |
| + finally: |
| + if op.j: |
| + op.j.close() |
| + |
| + def failed(self): |
| + self.fake.drain_mode = "fail" |
| + with self.assertRaises(roll.Refusal): |
| + self.depart() |
| + self.assertEqual(self.fake.fence, "t6-held") |
| + |
| + def test_cancel_lifts_fence_after_failed_drain(self): |
| + self.failed() |
| + self.cancel() |
| + self.assertIsNone(self.fake.fence) |
| + self.assertTrue(self.fake.tenant_start()) |
| + self.assertIn(roll.TEXT["cancelled"], self.output.getvalue()) |
| + with self.journal() as journal: |
| + self.assertIsNotNone(journal.last("drain-cancelled")) |
| + self.assertEqual(journal.last("intent", op="session")["args"], |
| + dict(iid=IID, verb="drain-cancel", transaction="t6-held")) |
| + self.assertIsNone(self.store.active_id()) |
| + |
| + def test_refused_cancel_keeps_fence(self): |
| + self.failed() |
| + self.fake.cancel_ok = False |
| + with self.assertRaises(roll.Refusal) as caught: |
| + self.cancel() |
| + self.assertIn("the fence stays", str(caught.exception)) |
| + self.assertEqual(self.fake.fence, "t6-held") |
| + |
| + def test_cancel_proven_by_status(self): |
| + # The verb exits 0 but status still shows the fence: not cancelled. |
| + self.failed() |
| + self.fake.cancel_ok = "status-disagrees" |
| + with self.assertRaises(roll.Refusal): |
| + self.cancel() |
| + self.assertNotIn(roll.TEXT["cancelled"], self.output.getvalue()) |
| + with self.journal() as journal: |
| + self.assertIsNone(journal.last("drain-cancelled")) |
| + |
| + def test_cancel_only_for_a_failed_drain_of_this_member(self): |
| + self.failed() |
| + for tx, iid in (("t6-held", PEER), ("missing", IID)): |
| + with self.subTest(tx=tx, iid=iid): |
| + with self.assertRaises((roll.Refusal, OSError)): |
| + self.cancel(tx, iid) |
| + self.setUp() |
| + self.depart() |
| + with self.assertRaises(roll.Refusal) as caught: |
| + self.cancel() |
| + self.assertEqual(str(caught.exception), roll.TEXT["cancel_refused"]) |
| + self.assertNotIn("drain-cancel", self.verbs()) |
| + |
| + |
| class FloorTests(HeldBase): |
| def assert_floor_refused(self, reason): |
| with self.assertRaises(roll.Refusal) as caught: |
| @@ -567,15 +796,32 @@ class FloorTests(HeldBase): |
| with self.journal() as journal: |
| self.assertNotIn("old", journal.last("floor")["live"]) |
| + def assert_floor_error(self, reason): |
| + """A floor that cannot be read refuses the transaction before any |
| + write and records no rule: never a fallback to DR-4.""" |
| + with self.assertRaises(roll.Refusal) as caught: |
| + self.depart() |
| + self.assertEqual(str(caught.exception), roll.TEXT["floor_error"]) |
| + self.assertEqual(self.verbs(), []) |
| + self.assertNotIn(roll.TEXT["rule_dr4"], self.output.getvalue()) |
| + self.assertIn(reason, self.output.getvalue()) |
| + with self.journal() as journal: |
| + self.assertIsNone(journal.last("floor")) |
| + self.assertIsNotNone(journal.last("floor-error")) |
| + |
| def test_old_pinned_template(self): |
| - for release in ("v0.34.9", "v0.35.0-rc1", "a" * 64): |
| + self.fake.template_rel = "v0.34.9" |
| + self.assert_floor_refused(roll.TEXT["floor_template"].format(release="v0.34.9")) |
| + |
| + def test_uncomparable_pinned_template_is_an_error(self): |
| + for release in ("v0.35.0-rc1", "a" * 64): |
| with self.subTest(release=release): |
| self.setUp() |
| self.fake.template_rel = release |
| - self.assert_floor_refused(roll.TEXT["floor_template"].format(release=release)) |
| + self.assert_floor_error(roll.TEXT["floor_template"].format(release=release)) |
| def test_no_floor_config(self): |
| - for key in ("ha_floor", "data_prefix"): |
| + for key in ("ha_floor", "data_prefix", "data_bucket"): |
| with self.subTest(key=key): |
| self.setUp() |
| del self.config[key] |
| @@ -590,7 +836,29 @@ class FloorTests(HeldBase): |
| return invoke(service, verb, args, **kwargs) |
| self.fake.invoke = failing |
| - self.assert_floor_refused(roll.TEXT["floor_unreadable"].format(key="control/edges/adi.json")) |
| + self.assert_floor_error(roll.TEXT["floor_unreadable"].format(key="control/edges/adi.json")) |
| + |
| + def test_listing_error_refuses_roll_without_dr4(self): |
| + invoke = self.fake.invoke |
| + |
| + def failing(service, verb, args, **kwargs): |
| + if verb == "list-objects-v2": |
| + raise roll.Uncertain(roll.TEXT["api"]) |
| + return invoke(service, verb, args, **kwargs) |
| + |
| + self.fake.invoke = failing |
| + with self.assertRaises((roll.Refusal, roll.Uncertain)): |
| + self.run_roll() |
| + self.assertEqual(self.fake.writes, ["prepare"]) |
| + self.assertNotIn(roll.TEXT["rule_dr4"], self.output.getvalue()) |
| + self.assertEqual(self.store.active_id(), "t6-roll") |
| + with self.journal("t6-roll") as journal: |
| + self.assertIsNone(journal.last("floor")) |
| + # Once the store answers, resume chooses the rule and drains. |
| + self.fake.invoke = invoke |
| + self.resume() |
| + self.assertIn("drain", self.fake.writes) |
| + self.assertIsNone(self.store.active_id()) |
| class RemoveTests(HeldBase): |
| @@ -657,7 +925,12 @@ class DrainedRollTests(HeldBase): |
| self.assertEqual((self.fake.minimum, self.fake.desired, self.fake.maximum), (2, 2, 2)) |
| self.assertEqual(self.fake.boxes[IID]["binary_sha256"], NEW) |
| self.assertIsNone(self.store.active_id()) |
| + summary = json.loads(next(line for line in self.output.getvalue().splitlines() if line.startswith("{"))) |
| + self.assertEqual(summary, dict(transaction="t6-roll", transaction_kind="roll", member=IID, hosts_moved=1, |
| + hosts_released=0, longest_hold_ms=1500, todays_answer=0, |
| + connections_closed_at_bound=0)) |
| with self.journal("t6-roll") as journal: |
| + self.assertEqual(journal.last("report")["hosts_moved"], 1) |
| self.assertEqual(journal.last("floor")["rule"], "drain") |
| self.assertLess(journal.last("pre-action-checked")["seq"], |
| journal.last("intent", op="session", args=dict(iid=IID, verb="apply"))["seq"]) |
| @@ -787,6 +1060,10 @@ class RemoteCommandTests(unittest.TestCase): |
| clear = roll.AWS.remote_command(dict(verb="fence-clear", transaction="t6"), "n" * 32) |
| self.assertIn("group-maintenance fence-clear t6 && /opt/carlos/carlos system group-maintenance status", |
| clear) |
| + cancel = roll.AWS.remote_command(dict(verb="drain-cancel", transaction="t6"), "n" * 32) |
| + self.assertIn("/usr/bin/timeout --signal=TERM --kill-after=30s 300s /opt/carlos/carlos system " |
| + "group-maintenance drain --cancel t6 && /opt/carlos/carlos system group-maintenance status", |
| + cancel) |
| stop = roll.AWS.remote_command(dict(verb="edge-stop"), "n" * 32) |
| self.assertIn("systemctl stop carlos-edge.service; /usr/bin/systemctl show --property=MainPID " |
| "--property=ActiveState carlos-edge.service", stop) |
| @@ -795,7 +1072,7 @@ class RemoteCommandTests(unittest.TestCase): |
| with self.assertRaises(roll.Refusal): |
| roll.AWS.remote_command(dict(verb="drain", transaction=tx), "n" * 32) |
| with self.assertRaises(roll.Refusal): |
| - roll.AWS.remote_command(dict(verb="drain-cancel", transaction="t6"), "n" * 32) |
| + roll.AWS.remote_command(dict(verb="drain-cancel", transaction="-t6"), "n" * 32) |
| def test_drain_output(self): |
| report = dict(v=1, transaction="t6", result="ok") |
| @@ -827,7 +1104,7 @@ class ConfigTests(unittest.TestCase): |
| base_config = base.test_config("/state") |
| self.assertEqual(roll.validate_config(dict(base_config)), base_config) |
| for bad in (dict(ha_floor="next"), dict(data_prefix="/x"), dict(data_prefix="a/../b"), |
| - dict(data_prefix="a/"), dict(other="x")): |
| + dict(data_prefix="a/"), dict(data_bucket="Bad_Bucket"), dict(other="x")): |
| with self.subTest(bad=bad): |
| with self.assertRaises(roll.Refusal): |
| roll.validate_config(dict(config, **bad)) |
| @@ -858,6 +1135,10 @@ class DepartArgvTests(base.CLIHarness, unittest.TestCase): |
| self.assertEqual(self.cli("remove", "--member", IID), 1) |
| self.assert_refusal("remove_minimum") |
| + def test_cancel_drain_without_journal_refuses(self): |
| + self.assertEqual(self.cli("cancel-drain", "--member", IID, "--transaction", "nothing-here"), 1) |
| + self.assertFalse(any(verb == "start-session" for _, verb, _, _ in self.calls)) |
| + |
| def test_transaction_ids(self): |
| for tx in ("-leading", "probe-x"): |
| with self.subTest(tx=tx): |