Fix attended group roll return safety and session recovery
Apply B3 fix round 1 under R13 and R15-R19. Use the configured box apply verb, enforce the reader floor and fresh process publication, and hold divergent returns in Standby without restoring minimum. Journal session timeout cleanup and recover from status before other calls. Model provider capacity and replacement rules in offline tests. Validation: 55 Python tests pass, including all eight required mutation witnesses; go build ./... passes. No live cloud calls.
scripts/region-group-roll.py+248 −64scripts/region_group_roll_test.py+426 −18
Intent
<task-notification> <task-id>af5ff8a4b30d69536</task-id> <tool-use-id>toolu_01DJQZrDHeneFCWbY3iouLCP</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/e47280e8-3e59-4dc1-95d2-11de7237d34c/tasks/af5ff8a4b30d69536.output</output-file> <status>completed</status> <summary>Agent "Census review region-ha-p3b2" 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>**Census round 1 of 3 for region-ha-p3b2. Overall: APPROVED.** The branch point is `f86e9792`, confirmed as the merge-base with origin/main, and the tip is `a77d1a8c`. I found nothing to reject. `TestPlan14RootReadCensus` and `TestCensusScopeIsTheRootBinary` both pass locally. The worktree has one uncommitted change, `scripts/region_group_roll_test.py`, which is out of census scope. ### Units | unit | verdict | lines read | reason | |---|---|---|---| | group-init.sh.tftpl `external` | approve | diff 99,142-149; template 1-7; group.tf:40; scanner-init.sh.tftpl:33-37 | (d) `$AWS_REGION` comes from Terraform's `data.aws_region`. The .deb is fetched over HTTPS from AWS's bucket into the root-only 0700 `/var/lib/carlos-group-boot`. This runs at boot, before the agent, tenants or bootstrap exist, so no tenant, app or agent can write or name it. It matches scanner-host. `set -eu` makes a failed install fatal. Adding `curl` from apt is the same trust as the other packages. | | tests/fixed_state_unchanged.tftest.hcl | approve | diff 63-66 | Test only. One assert that the operator policy is empty in fixed mode. | | tests/group_user_data.tftest.hcl | approve | diff 120-129 | Test only. Asserts the install happens, and in what order. | | systemapply.go `RunSystemApply` | approve | 131-151 | `productionSystemApplier` builds the same struct literal. Only the flag assignment moved after construction. No read added. | | systemapply.go `systemApplier.Run` | approve | 307-344, 346-424 | (b) The steps before the lock are unchanged, and the lock is unchanged. The whole body after the lock moved verbatim into `runLocked`, starting with `resetGroupMaintenance` and `requireGroupMaintenance("check")`. The new `operation` hook only runs after the floor hook, guard recovery and `recoverIfNeeded`. A nil hook takes the old path. | | systemapply.go `runWithRelease` | approve | 153-162 | Same rootMoves read and participation wrapper, now generic over `run`. | | system.go `runSystem` | approve | diff 65-66 | Dispatch only. Root is required in `cmd.run` (verbs.go:94). | | system.go `systemVerb` | approve | diff 56 | Parsing only. | | new group_operator.tf `external` | approve | 1-110 | Only a policy output for the operator identity; it creates no IAM resource and the instance role is unchanged. `AmazonSSMManagedInstanceCore` was already attached (main.tf:452). Session documents are pinned by a precondition that refuses `SSM-SessionManagerRunShell`. | | new tests/group_operator.tftest.hcl | approve | 1-118, 188 | Test only: mock provider, plan runs. | | new `maintenanceUnconsumed` (Lstat) | approve | group_maintenance.go:160-168 vs old 126-133 | Moved verbatim. Lstat of a used-marker in the root 0700 maintenance directory. | | new `maintenanceReadProc` | approve | clock.go:18-97 | (e) Bounded reads of `/proc/stat` and `/proc/self/auxv`, kernel sources. The output is only displayed and grants nothing. | | new `sweepMaintenancePreparation` | approve | prepare.go:105-124 | ReadDir of root's own rootDir, under the lock. It removes only `.prepare-<decimal>` directories. `DirEntry.IsDir` comes from an lstat-type check, so it does not follow symlinks. | | new `permitStatus` | approve | verbs.go:253-296 | Read-only, using the strict `g.read(...,0600)` and the guard's own validators. `accepted` is a report, not an authorization. | | new `groupMaintenanceCommand.run` (ReadAll) | approve | verbs.go:93-192 | (c) Stdin is capped at 4097 bytes and `decodeMaintenancePermit` refuses anything over 4096. The writer then runs `validateMaintenancePermit`, `validateMaintenanceArtifact` and `maintenanceUnconsumed`, all under the apply lock and after re-reading the marker. Those are the same functions the guard calls. Only then does the exact validated byte string go through the root-only write. | | new `maintenanceBinaryDigest` | approve | verbs_linux.go:131-154 | Digest of root's `/opt` binary with `RESOLVE_NO_SYMLINKS`, a regular-file check and a size bound. Used for the report only. | | new `maintenanceEdgeProcess` | approve | verbs_linux.go:165-213 | (e) Absolute `/usr/bin/systemctl`, a fixed environment and bounded output. The `/proc/<pid>/stat` parse uses the last `") "`, so a crafted `comm` cannot shift the fields. Observational only. | | new `openMaintenanceDirectory` | approve | verbs_linux.go:24-67 | Walks by descriptor with `NO_SYMLINKS` and `BENEATH`. Ancestors must be root- or owner-owned and not group- or world-writable. The leaf must be the owner's and exactly 0700. | | new `openMaintenanceLock` | approve | verbs_linux.go:68-85 | Same `lockPath()` as `Run`, and stricter: no symlinks, regular file, one link, owned by euid, not group- or world-writable. | | new `replaceMaintenancePermit` (Read) | approve | verbs_linux.go:86-124 | O_EXCL temp file under the pinned directory fd, then chown/chmod 0600, fsync and renameat. No path the agent can name is involved. | | quiet `requireGroupMaintenance` | approve | group_maintenance.go:90-131 vs f86e9792:90-145 | The reads moved verbatim into `validateMaintenancePermit`, `validateMaintenanceArtifact` and `maintenanceUnconsumed`, which the guard still calls. The checks run in the same order: the conjunction, the action switch, alternatives and action match, permit identity and artifact hold, then the check-mode Lstat. `a.maintenance()` is memoised (line 54), so the same `g` is used. What the guard accepts is unchanged. | ### Point (a): prepare - The cache is read with `openBeneath` (`safefile`, refuses symlinks, single-link regular leaf; prepare.go:207). It is copied, capped, into root's private `MkdirTemp` scratch under rootDir. - `l.fetch` and `systemCacheHolds(cache, art.SHA256)` (lines 216-221) hash the scratch copy against the digest in the signed pointer. The pointer is verified with the release key from root's checked 0600 host.env (lines 46-82). The operator's `--sha256` must equal that signed digest (line 174). - The publish back to the data directory goes through `safefile.MkdirAll` and `safefile.Write`, so it does not follow symlinks. - The request is built from the signed pointer and written in scratch, then copied out. - Apply re-verifies the published copy on its existing path. - Prepare cannot cause an apply on its own. Every mutation still needs `requireGroupMaintenance` with consumption (systemapply.go:810-2201, group_maintenance.go:337/350). The agent could already write `requested.json` itself, so prepare grants nothing new. ### Other changed files in the envelopes - **`configureMaintenanceApplier`** clears the shell environment and sets only host.env values that pass `AssembleGroup` and refuse `CARLOS_HOST_CLAIM`, plus a fixed PATH and HOME. Root no longer takes its environment from the shell, which tightens things. `handRun` becomes true, which only adds a refusal. - **`systemLegForPreparation`** (systemleg.go:79-87): `newSystemLeg` still returns nil on group boxes, and prepare never arms observe or tick. - **The rollback verb** (prepare.go:261-347) requires a valid permit and a consumed apply marker for the same transaction. It requires `carlos.prev` to hash to OldSHA256 and `carlos` to NewSHA256, and no open journal. Inside `runLocked`, `groupTarget` consumes the rollback action before staging or running anything. It never reads the agent's request. - **`systemRollbackCompleted`** keeps the same error text, and only the rollback verb turns it into success. ### Envelopes | envelope | verdict | reason | |---|---|---| | `.` | approve | system.go's only change is the two dispatch lines above. | | `infra/modules/region-host` | approve | group-init.sh.tftpl and group_operator.tf, as above. README.md is out of scope as Markdown. | | `infra/modules/region-host/tests` | approve | Three test-only tftest files. Nothing runs on a box. | | `internal/host` | approve | I read every changed function in the five changed non-test files plus the two build-tagged verbs files (verbs_linux.go, verbs_other.go), and the three helpers they reach (`openBeneath`, `copyFileDurable`, `readRequest`). Nothing lets root open, run or follow something a tenant, app or agent can name. No check is weakened. The `_other` stubs refuse. | Overall: APPROVED Round: census round 1 for region-ha-p3b2. Record it on #280 with the reviewer (Opus) and tip `a77d1a8c`.</result> <usage><subagent_tokens>104117</subagent_tokens><tool_uses>18</tool_uses><duration_ms>180400</duration_ms></usage> </task-notification>
diff --git a/scripts/region-group-roll.py b/scripts/region-group-roll.py| index 67725d2a5..43e7f45a2 100755 |
| --- a/scripts/region-group-roll.py |
| +++ b/scripts/region-group-roll.py |
| @@ -6,7 +6,8 @@ state_dir. Keep that directory and its journals when reconnecting. A missing |
| or damaged record refuses recovery. No service, timer or cron may run this tool. |
| The JSON config has exactly these keys: deployment, account, region, group, |
| -group_arn, hook, target_groups (two ARNs), bucket, document, state_dir, profile. |
| +group_arn, hook, target_groups (two ARNs), bucket, document, state_dir, profile, |
| +min_release (the deployment's required reader release, for example v0.34.0). |
| The document must accept a command parameter and run it as root. The command |
| checks its uid; it never assumes that Session Manager preferences grant root. |
| Use an approved NonInteractiveCommands document with runAsElevated=true. |
| @@ -28,12 +29,24 @@ steps. status prints the saved transaction without contacting AWS. |
| An uncertain consumed box action stays in Standby for operator investigation. |
| The command never replays it, restarts a unit by hand, terminates a member, |
| sends ABANDON, or sets desired capacity. A Standby wait alerts after 15 minutes. |
| + |
| +Sessions can be cut during apply or rollback. Both remote commands have a |
| +15-minute transport bound, with 30 seconds for TERM before KILL. Their local |
| +session bound is 990 seconds. Prepare has a five-minute box bound and a |
| +six-minute local bound. A timeout terminates the owned session; the next box |
| +operation reads status. A consumed incomplete action needs operator recovery. |
| +Verify interruption behavior with the approved document on the live card. |
| + |
| +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. |
| """ |
| import argparse |
| import base64 |
| from contextlib import contextmanager |
| from datetime import datetime, timezone |
| import fcntl |
| +import getpass |
| import hashlib |
| import json |
| import os |
| @@ -93,6 +106,10 @@ TEXT = { |
| "process": "The expected artifact and a new edge process are required", |
| "permit": "The permit is not accepted, unconsumed and bound to this action", |
| "prepare": "Signed artifact preparation or preserved configuration verification failed", |
| + "already_applied": "The pointer was already applied", |
| + "already_rolled_back": "The pointer was already rolled back", |
| + "rollback_failed": "The pointer's previous rollback failed", |
| + "release_floor": "The pointer version is below the configured min_release", |
| "held": "The member must remain in Standby with both target groups deregistered", |
| "timeout": "The 15-minute Standby wait expired", |
| "uncertain_action": "The consumed box action has no verified completion", |
| @@ -100,19 +117,22 @@ TEXT = { |
| "return_failed": "Admission or API access was lost during a return hook", |
| "return_attempts": "The bounded return completion attempts are exhausted", |
| "return_phase": "The provider has not completed this member's return", |
| + "lost_member": "member terminated or replaced: failed probe", |
| + "unknown_phase": "The member's return phase is unknown: failed probe", |
| "activity": "The ExitStandby activity cannot be bound to this transaction", |
| "hook": "The immutable launch hook must have a 900-second ABANDON default", |
| "remote": "The Session Manager command has no successful framed result", |
| "api": "An AWS response is unavailable or invalid", |
| "rollback_refused": "Rollback requires this transaction's completed apply in Standby", |
| "unsupported": "Unsupported operation", |
| - "divergence": "The provider used a return hook. The member is safe; further rolls are blocked.", |
| + "divergence": "The provider used a return hook. The member is held in Standby; further rolls are blocked.", |
| } |
| SHA = re.compile(r"[0-9a-f]{64}\Z") |
| IID = re.compile(r"i-(?:[0-9a-f]{8}|[0-9a-f]{17})\Z") |
| TX = re.compile(r"[a-zA-Z0-9_-]{1,80}\Z") |
| WAIT = 900 |
| +SESSION_TIMEOUTS = {"prepare": 360, "apply": 990, "rollback": 990} |
| class Refusal(Exception): |
| @@ -123,6 +143,14 @@ class FailedProbe(Refusal): |
| pass |
| +class ObservationExpired(Refusal): |
| + pass |
| + |
| + |
| +class DivergenceHeld(Refusal): |
| + pass |
| + |
| + |
| class Uncertain(Exception): |
| def __init__(self, message, **details): |
| super().__init__(message) |
| @@ -166,12 +194,28 @@ def encoded(value): |
| return json.dumps(value, sort_keys=True, separators=(",", ":"), allow_nan=False).encode() |
| +def release_version(value): |
| + # release.ParseReleaseVersion/ParseSemVer: optional single v, exactly |
| + # three ASCII decimal components, no leading zeros, at most nine digits. |
| + if not isinstance(value, str): |
| + return None |
| + match = re.fullmatch(r"v?((?:0|[1-9][0-9]{0,8})\.(?:0|[1-9][0-9]{0,8})\.(?:0|[1-9][0-9]{0,8}))", value) |
| + return tuple(map(int, match[1].split("."))) if match else None |
| + |
| + |
| +def below_floor(version, floor): |
| + parsed = release_version(version) |
| + # Like release.BelowFloor, unparseable pointer versions are not below. |
| + return parsed is not None and parsed < release_version(floor) |
| + |
| + |
| def validate_config(c): |
| keys = {"deployment", "account", "region", "group", "group_arn", "hook", |
| - "target_groups", "bucket", "document", "state_dir", "profile"} |
| + "target_groups", "bucket", "document", "state_dir", "profile", "min_release"} |
| require(isinstance(c, dict) and set(c) == keys, "config_invalid") |
| for key in keys - {"target_groups"}: |
| require(isinstance(c[key], str) and 0 < len(c[key]) <= 1024, "config_invalid") |
| + require(release_version(c["min_release"]) is not None, "config_invalid") |
| for key in ("deployment", "group", "hook", "profile", "document"): |
| require(re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,127}", c[key]), "config_invalid") |
| require(re.fullmatch(r"[0-9]{12}", c["account"]), "config_invalid") |
| @@ -215,10 +259,12 @@ def private_file(path, flags, owner): |
| class Journal: |
| - def __init__(self, path, owner, create=False): |
| + def __init__(self, path, owner, create=False, readonly=False): |
| self.path, self.owner = path, owner |
| - self.fd = private_file(path, os.O_RDWR | os.O_APPEND | |
| - (os.O_CREAT | os.O_EXCL if create else 0), owner) |
| + self.readonly = readonly |
| + require(not (readonly and create), "record") |
| + flags = os.O_RDONLY if readonly else os.O_RDWR | os.O_APPEND |
| + self.fd = private_file(path, flags | (os.O_CREAT | os.O_EXCL if create else 0), owner) |
| self.events = [] |
| try: |
| with os.fdopen(os.dup(self.fd), "rb") as reader: |
| @@ -244,6 +290,7 @@ class Journal: |
| self.fd = None |
| def add(self, kind, **data): |
| + require(not self.readonly, "record") |
| row = dict(seq=len(self.events), previous=self.events[-1]["hash"] if self.events else "0" * 64, |
| kind=kind, **data) |
| row["hash"] = hashlib.sha256(encoded(row)).hexdigest() |
| @@ -260,7 +307,7 @@ class Journal: |
| class State: |
| - def __init__(self, config, owner=0): |
| + def __init__(self, config, owner=0, readonly=False): |
| self.owner, self.config = owner, config |
| root = Path(config["state_dir"]) |
| # Do not follow even an ancestor symlink. The directory is provisioned |
| @@ -273,11 +320,12 @@ class State: |
| s = root.stat() |
| require(s.st_uid == owner and stat.S_IMODE(s.st_mode) == 0o700, "unsafe_state") |
| self.directory = root / hashlib.sha256(config["group_arn"].encode()).hexdigest()[:32] |
| - try: |
| - self.directory.mkdir(mode=0o700) |
| - sync_directory(root) |
| - except FileExistsError: |
| - pass |
| + if not readonly: |
| + try: |
| + self.directory.mkdir(mode=0o700) |
| + sync_directory(root) |
| + except FileExistsError: |
| + pass |
| s = self.directory.lstat() |
| require(stat.S_ISDIR(s.st_mode) and s.st_uid == owner and |
| stat.S_IMODE(s.st_mode) == 0o700, "unsafe_state") |
| @@ -346,9 +394,9 @@ class State: |
| self.write(self.active, {"transaction": header["transaction"]}) |
| return j |
| - def load(self, tx): |
| + def load(self, tx, readonly=False): |
| require(isinstance(tx, str) and TX.fullmatch(tx), "record") |
| - j = Journal(self.directory / (tx + ".jsonl"), self.owner) |
| + j = Journal(self.directory / (tx + ".jsonl"), self.owner, readonly=readonly) |
| require(j.events[0]["config"] == self.config, "scope") |
| return j |
| @@ -363,14 +411,21 @@ class AWS: |
| def __init__(self, config): |
| self.c = config |
| self.last_session_id = None |
| + self.session_observer = None |
| + |
| + def session_started(self, session_id): |
| + self.last_session_id = session_id |
| + if self.session_observer: |
| + self.session_observer(session_id) |
| @staticmethod |
| - def session_output(command, env, timeout): |
| + def session_output(command, env, timeout, on_session=None): |
| # The Session Manager plugin can lose buffered output without a terminal. |
| # A local PTY supplies one without an external unbuffer dependency. |
| master, slave = pty.openpty() |
| proc = None |
| body = bytearray() |
| + sessions = set() |
| try: |
| tty.setraw(slave) |
| proc = subprocess.Popen(command, stdin=subprocess.DEVNULL, stdout=slave, stderr=slave, |
| @@ -389,11 +444,18 @@ class AWS: |
| break |
| body.extend(chunk) |
| require(len(body) <= 4 * 1024 * 1024, "remote") |
| + for sid in re.findall(rb"Starting session with SessionId: ([A-Za-z0-9_-]+)\r?\n", body): |
| + if sid not in sessions: |
| + sessions.add(sid) |
| + if on_session: |
| + on_session(sid.decode()) |
| if time.monotonic() >= end: |
| raise Uncertain(TEXT["remote"], timeout=True) |
| require(proc.wait(timeout=max(0.01, end - time.monotonic())) == 0, "remote") |
| return bytes(body).decode() |
| - except (subprocess.TimeoutExpired, OSError) as exc: |
| + except subprocess.TimeoutExpired as exc: |
| + raise Uncertain(TEXT["remote"], timeout=True) from exc |
| + except OSError as exc: |
| raise Uncertain(TEXT["remote"]) from exc |
| finally: |
| if proc is not None and proc.returncode is None: |
| @@ -420,7 +482,7 @@ class AWS: |
| "AWS_SECURITY_TOKEN", "AWS_PROFILE", "AWS_DEFAULT_PROFILE"}: |
| del env[key] |
| if service == "ssm" and verb == "start-session": |
| - return self.session_output(command, env, timeout) |
| + return self.session_output(command, env, timeout, on_session=self.session_started) |
| base = os.environ.get("TMPDIR") or str(Path.home() / ".cache") |
| with tempfile.TemporaryDirectory(prefix="region-roll-", dir=base) as scratch: |
| if object_body: |
| @@ -430,10 +492,12 @@ class AWS: |
| stderr=subprocess.DEVNULL, env=env, start_new_session=True) |
| try: |
| rc = proc.wait(timeout=timeout) |
| - except BaseException: |
| + except BaseException as exc: |
| os.killpg(proc.pid, signal.SIGKILL) |
| proc.wait() |
| - raise Uncertain(TEXT["api"], interrupted=True) from None |
| + if isinstance(exc, subprocess.TimeoutExpired): |
| + raise Uncertain(TEXT["api"], timeout=True) from None |
| + raise |
| out.seek(0) |
| body = out.read(4 * 1024 * 1024 + 1) |
| if rc != 0 or len(body) > 4 * 1024 * 1024: |
| @@ -457,12 +521,8 @@ class AWS: |
| payload = base64.b64encode(encoded(a["permit"])).decode() |
| command = ("printf %s " + shlex.quote(payload) + " | base64 -d | " + command + |
| " && " + binary + " system group-maintenance status") |
| - elif verb == "apply": |
| - # hostenv.Render explicitly produces shell-compatible assignments. |
| - # Prepare already checked its root ownership and configuration. Only |
| - # this fixed root path is sourced; nothing supplied by an agent is. |
| - command = ("set -a; . /etc/carlos/host.env; set +a; " |
| - "AWS_MAX_ATTEMPTS=1 " + binary + " system apply") |
| + elif verb in {"apply", "rollback"}: |
| + command = "/usr/bin/timeout --signal=TERM --kill-after=30s 900s " + command |
| # NonInteractiveCommands has no stdin. Carry only the permit in base64 |
| # and frame both output and status, independent of the plugin exit code. |
| script = ("[ \"$(id -u)\" = 0 ] || exit 77; " |
| @@ -509,9 +569,11 @@ class AWS: |
| result = [] |
| for row in rows: |
| description = row.get("Description", "") |
| - if re.search(r"\b" + re.escape(a["iid"]) + r"\b", description) and "out of Standby" in description: |
| + kind = "exit" if "out of Standby" in description else ( |
| + "enter" if "into Standby" in description 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())) |
| + result.append(dict(id=row["ActivityId"], iid=a["iid"], time=dt.timestamp(), kind=kind)) |
| return result |
| if op == "edges": |
| require(re.fullmatch(r"g-[a-z0-9-]+", a["box_ref"]), "identity") |
| @@ -521,13 +583,15 @@ class AWS: |
| return self.invoke("autoscaling", "update-auto-scaling-group", group + ["--min-size", str(a["value"])]) |
| if op == "enter": |
| require(a["decrement"] is True, "held") |
| - return self.invoke("autoscaling", "enter-standby", group + |
| - ["--instance-ids", a["iid"], "--should-decrement-desired-capacity"]) |
| + result = self.invoke("autoscaling", "enter-standby", group + |
| + ["--instance-ids", a["iid"], "--should-decrement-desired-capacity"]) |
| + return self.activity_response(result) |
| if op == "exit": |
| result = self.invoke("autoscaling", "exit-standby", group + ["--instance-ids", a["iid"]]) |
| - rows = result.get("Activities", []) |
| - require(len(rows) == 1 and rows[0].get("ActivityId"), "activity") |
| - return {"activity": rows[0]["ActivityId"]} |
| + return self.activity_response(result) |
| + if op == "terminate_session": |
| + require(re.fullmatch(r"[A-Za-z0-9_-]+", a["session_id"]), "remote") |
| + return self.invoke("ssm", "terminate-session", ["--session-id", a["session_id"]]) |
| if op == "complete": |
| require(a["hook"] == self.c["hook"] and a["result"] == "CONTINUE", "hook") |
| return self.invoke("autoscaling", "complete-lifecycle-action", group + |
| @@ -540,10 +604,11 @@ class AWS: |
| text = self.invoke("ssm", "start-session", ["--target", a["iid"], |
| "--document-name", self.c["document"], "--parameters", |
| json.dumps({"command": [command]})], |
| - timeout=300 if a["verb"] in {"apply", "prepare", "rollback"} else 15, raw=True) |
| + timeout=SESSION_TIMEOUTS.get(a["verb"], 15), raw=True) |
| session_ids = re.findall(r"Starting session with SessionId: ([A-Za-z0-9_-]+)", text) |
| if len(session_ids) == 1: |
| - self.last_session_id = session_ids[0] |
| + if self.last_session_id != session_ids[0]: |
| + self.session_started(session_ids[0]) |
| match = re.findall(re.escape(nonce) + r":BEGIN\r?\n(.*?)\r?\n" + |
| re.escape(nonce) + r":END:([0-9]+)(?:\r?\n|$)", text, re.S) |
| require(len(match) == 1 and match[0][1] == "0", "remote") |
| @@ -553,12 +618,22 @@ class AWS: |
| return {} |
| raise Refusal(TEXT["unsupported"]) |
| + @staticmethod |
| + def activity_response(result): |
| + rows = result.get("Activities", []) if isinstance(result, dict) else [] |
| + if len(rows) == 1 and isinstance(rows[0], dict) and rows[0].get("ActivityId"): |
| + return {"activity": rows[0]["ActivityId"]} |
| + # The API returned success. Preserve it even when activity extraction |
| + # fails; a describe must settle the outcome before another write. |
| + return {"outcome": "uncertain-success", "response": result} |
| + |
| class Operator: |
| def __init__(self, config, adapter, state, journal=None, clock=time.time, |
| - sleep=time.sleep, output=sys.stdout, attended_by="terminal"): |
| + sleep=time.sleep, output=sys.stdout, attended_by=None): |
| self.c, self.api, self.state, self.j = config, adapter, state, journal |
| - self.clock, self.sleep, self.output, self.attended = clock, sleep, output, attended_by |
| + self.clock, self.sleep, self.output = clock, sleep, output |
| + self.attended = attended_by or os.environ.get("SUDO_USER") or getpass.getuser() |
| self.header = journal.events[0] if journal else None |
| def say(self, phase, detail): |
| @@ -573,18 +648,35 @@ class Operator: |
| self.say(data["phase"], self.header["iid"]) |
| return self.j.add(kind, at=self.clock(), **data) |
| - def call(self, op, **args): |
| + def call(self, op, freshness=None, **args): |
| session = sum(r.get("op") == "session" and r["kind"] == "intent" for r in self.j.events) + 1 if self.j else 1 |
| intent = self.event("intent", op=op, args=args, session=session if op == "session" else None) |
| + dispatched = False |
| + if op == "session": |
| + self.api.session_observer = lambda sid: self.event( |
| + "session-opened", session_id=sid, intent=intent["seq"] if intent else None) |
| try: |
| + # Include the durable intent's fsync in the age at the write. |
| + if freshness is not None and not 0 <= self.clock() - freshness <= 5: |
| + raise ObservationExpired(TEXT["admission"]) |
| + dispatched = True |
| result = self.api.request(op, args) |
| - except Exception as exc: |
| + received_at = self.clock() |
| + except BaseException as exc: |
| self.event("error", intent=intent["seq"] if intent else None, op=op, error=type(exc).__name__, |
| - reason=str(exc), details=getattr(exc, "details", {}), |
| + reason=str(exc), details=getattr(exc, "details", {}), dispatched=dispatched, |
| session_id=getattr(self.api, "last_session_id", None) if op == "session" else None) |
| + if (op == "session" and isinstance(exc, Uncertain) and exc.details.get("timeout") and |
| + getattr(self.api, "last_session_id", None)): |
| + self.call("terminate_session", session_id=self.api.last_session_id) |
| raise |
| + finally: |
| + if op == "session": |
| + self.api.session_observer = None |
| self.event("response", intent=intent["seq"] if intent else None, op=op, result=result, |
| + received_at=received_at, |
| session_id=getattr(self.api, "last_session_id", None) if op == "session" else None) |
| + self.last_response_at = received_at |
| return result |
| def box(self, iid, verb="status", **args): |
| @@ -611,8 +703,9 @@ class Operator: |
| require(all(s.get(k) == v for k, v in self.header["identity"].items()), "identity") |
| def readiness(self, iid, maintenance=False): |
| - observed = self.clock() |
| s = self.box(iid) |
| + # Session startup before the first response is not observation age. |
| + observed = self.last_response_at |
| self.identity(s, iid) |
| e = self.call("edges", box_ref=s["box_ref"]) |
| after = self.box(iid) |
| @@ -623,8 +716,8 @@ class Operator: |
| x["health"].get("code") == 200 and x["edge"].get("state") == "known" for x in (s, after)) and |
| e.get("v") == 1 and e.get("box") == s["box_ref"] and |
| e.get("admitted") is True and e.get("box_role") == "serve" and |
| - instant(e.get("generation")) > instant(s["edge"].get("started_at")) and |
| - 0 <= self.clock() - observed <= 5, "admission") |
| + instant(e.get("generation")) >= instant(s["edge"].get("started_at")) + 2 and |
| + 0 <= self.clock() - observed <= 60, "admission") |
| if maintenance: |
| action = self.action() |
| expected = self.header["old"] if action == "rollback" else self.header["new"] |
| @@ -781,6 +874,8 @@ class Operator: |
| if failed: |
| self.state.write(self.state.blocked, dict(transaction=self.header["transaction"], reason=TEXT[key])) |
| raise FailedProbe(TEXT[key]) |
| + if key == "divergence": |
| + raise DivergenceHeld(TEXT[key]) |
| raise Refusal(TEXT[key]) |
| def wait_standby(self, check): |
| @@ -802,11 +897,42 @@ class Operator: |
| h = self.header |
| self.event("phase", phase="prepare") |
| p = self.box(h["iid"], "prepare", sha256=h["new"]) |
| + previous = p.get("previous_result") |
| + if previous is not None: |
| + raise Refusal(TEXT[{"applied": "already_applied", "rolled-back": "already_rolled_back", |
| + "rollback-failed": "rollback_failed"}.get(previous, "prepare")]) |
| require(p.get("v") == 1 and p.get("artifact_sha256") == h["new"] and |
| p.get("old_binary_sha256") == h["old"] and p.get("cache_state") == "verified" and |
| p.get("request_written") is True and p.get("config_check") == "valid", "prepare") |
| + require(isinstance(p.get("version"), str) and p["version"], "prepare") |
| + require(not below_floor(p["version"], h["config"]["min_release"]), "release_floor") |
| self.event("prepared", result=p) |
| + def verify_action(self, status): |
| + self.identity(status, self.header["iid"]) |
| + expected = self.header["old"] if self.action() == "rollback" else self.header["new"] |
| + if (status["binary_sha256"] != expected or not status["edge"].get("identity") or |
| + status["edge"]["identity"] == self.before_process()): |
| + self.alert("process") |
| + intent = self.j.last("intent", op="session") |
| + self.event("box-action-verified", action=self.action(), process=status["edge"]["identity"], |
| + binary_sha256=status["binary_sha256"], status_intent=intent["seq"]) |
| + |
| + def observe_pending_action(self): |
| + # A cut session may have consumed its permit before losing the reply. |
| + # Status is the first provider call on resume, even before ASG describes. |
| + action = self.action() |
| + intents = [r for r in self.j.events if r["kind"] == "intent" and r.get("op") == "session" |
| + and r["args"].get("verb") == action] |
| + verified = self.j.last("box-action-verified", action=action) |
| + if intents and (not verified or verified["seq"] < intents[-1]["seq"]): |
| + s = self.box(self.header["iid"]) |
| + self.identity(s, self.header["iid"]) |
| + p = s["permit"] |
| + if (p.get("transaction") == self.header["transaction"] and |
| + p.get("action") == action and p.get("consumed") is True): |
| + self.verify_action(s) |
| + |
| def mutation(self): |
| h, action = self.header, self.action() |
| g = self.snapshot() |
| @@ -819,9 +945,8 @@ class Operator: |
| s = self.box(h["iid"]) |
| self.identity(s, h["iid"]) |
| p = s["permit"] |
| - expected = h["old"] if action == "rollback" else h["new"] |
| if p.get("transaction") == h["transaction"] and p.get("action") == action and p.get("consumed") is True: |
| - require(s["binary_sha256"] == expected and s["edge"]["identity"] != self.before_process(), "uncertain_action") |
| + self.verify_action(s) |
| return |
| if action == "rollback" and p.get("state") != "absent" and p.get("action") == "apply": |
| require(p.get("transaction") == h["transaction"], "permit") |
| @@ -845,7 +970,13 @@ class Operator: |
| p.get("expires") == permit["body"]["expires"], "permit") |
| self.standby(self.snapshot()) |
| self.event("phase", phase="mutation", action=action) |
| - self.box(h["iid"], action) |
| + try: |
| + self.box(h["iid"], action) |
| + except (Uncertain, Refusal): |
| + # After timeout cleanup, make no other provider call before status. |
| + self.verify_action(self.box(h["iid"])) |
| + raise |
| + self.verify_action(self.box(h["iid"])) |
| def resume(self): |
| self.restore_header() |
| @@ -853,6 +984,7 @@ class Operator: |
| if self.j.last("done"): |
| self.state.finish() |
| return |
| + self.observe_pending_action() |
| if self.j.last("exit-intent"): |
| return self.return_member() |
| self.prepare() |
| @@ -861,6 +993,7 @@ class Operator: |
| phase = g["members"][h["iid"]] |
| if phase == "InService": |
| require(g["desired"] == h["n"] and g["minimum"] in (h["n"], h["n"] - 1), "shape") |
| + require(g["minimum"] == h["n"] or self.j.last("intent", op="minimum"), "shape") |
| # Recheck peers and identity before the first group write, including |
| # resume after preparation or an ambiguous minimum update. |
| for member in h["members"]: |
| @@ -878,7 +1011,11 @@ class Operator: |
| # straight to readback below. No desired-capacity repair exists. |
| self.event("enter-retry", observed=g) |
| self.event("phase", phase="enter-standby") |
| - self.call("enter", iid=h["iid"], decrement=True) |
| + if not self.j.last("enter-activity-baseline"): |
| + self.event("enter-activity-baseline", activities=self.call("activities", iid=h["iid"])) |
| + result = self.call("enter", iid=h["iid"], decrement=True) |
| + if result.get("activity"): |
| + self.event("enter-activity", activity=result["activity"]) |
| self.wait_standby(lambda g: self.standby(g)) |
| self.say("Standby", h["iid"]) |
| self.mutation() |
| @@ -889,6 +1026,7 @@ class Operator: |
| def rollback(self, iid): |
| self.restore_header() |
| require(iid == self.header["iid"] and not self.j.last("exit-intent"), "rollback_refused") |
| + self.observe_pending_action() |
| self.standby(self.snapshot()) |
| if not self.j.last("rollback-requested"): |
| s = self.box(iid) |
| @@ -904,9 +1042,21 @@ class Operator: |
| saved = self.j.last("exit-activity") |
| if saved: |
| return saved["activity"] |
| - intent = self.j.last("exit-intent") |
| rows = self.call("activities", iid=self.header["iid"]) |
| - matches = [r["id"] for r in rows if r["iid"] == self.header["iid"] and r["time"] >= intent["at"] - 1] |
| + entered = self.j.last("enter-activity") |
| + if not entered: |
| + baseline = self.j.last("enter-activity-baseline") |
| + require(baseline is not None, "activity") |
| + known = {r["id"] for r in baseline["activities"]} |
| + candidates = [r for r in rows if r["iid"] == self.header["iid"] and |
| + r["kind"] == "enter" and r["id"] not in known] |
| + require(len(candidates) == 1, "activity") |
| + entered = self.event("enter-activity", activity=candidates[0]["id"]) |
| + starts = [r for r in rows if r["id"] == entered["activity"] and |
| + r["kind"] == "enter" and r["iid"] == self.header["iid"]] |
| + require(len(starts) == 1, "activity") |
| + matches = [r["id"] for r in rows if r["iid"] == self.header["iid"] and |
| + r["kind"] == "exit" and r["time"] > starts[0]["time"]] |
| require(len(matches) == 1, "activity") |
| self.event("exit-activity", activity=matches[0]) |
| return matches[0] |
| @@ -914,22 +1064,40 @@ class Operator: |
| def return_member(self): |
| """The only owner of ExitStandby and defensive return CONTINUE.""" |
| self.restore_header() |
| + self.observe_pending_action() |
| h, iid = self.header, self.header["iid"] |
| self.event("phase", phase="return") |
| end = self.clock() + WAIT |
| while True: |
| if self.clock() >= end: |
| self.alert("return_phase") |
| + g, phase = None, None |
| try: |
| try: |
| g = self.snapshot() |
| except (Refusal, Uncertain): |
| - if self.j.last("exit-intent"): |
| + if self.j.last("return-hook"): |
| self.alert("return_failed", failed=True) |
| + # No observed hook: a failed read is resumable. It does |
| + # not establish an unknown lifecycle state or divergence. |
| raise |
| + exit_call = self.j.last("intent", op="exit") |
| + exit_error = self.j.last("error", op="exit") |
| + sent = exit_call and not (exit_error and exit_error["intent"] == exit_call["seq"] and |
| + exit_error.get("dispatched") is False) |
| + phase = g["members"].get(iid) |
| + if sent and (phase is None or phase.startswith("Terminat") or |
| + sorted(g["members"]) != h["members"]): |
| + self.alert("lost_member", failed=True) |
| + if sent and phase not in {"Standby", "EnteringStandby", "Pending", "PreInService", |
| + "Pending:Wait", "Pending:Proceed", "InService"}: |
| + self.alert("unknown_phase", failed=True) |
| self.invariant(g) |
| - phase = g["members"][iid] |
| intent = self.j.last("exit-intent") |
| + if self.j.last("divergence-hold") and phase in {"Standby", "EnteringStandby"}: |
| + self.wait_standby(lambda current: self.standby(current)) |
| + self.event("divergence-held", iid=iid) |
| + self.alert("divergence") |
| if phase == "Standby": |
| self.standby(g) |
| if intent: |
| @@ -938,10 +1106,10 @@ class Operator: |
| self.event("exit-intent", transaction=h["transaction"], iid=iid, |
| boot_id=h["identity"]["boot_id"], process=ready["status"]["edge"]["identity"], |
| observed=ready["observed"], generation=ready["generation"]) |
| - require(0 <= self.clock() - ready["observed"] <= 5, "admission") |
| try: |
| - result = self.call("exit", iid=iid) |
| - self.event("exit-activity", activity=result["activity"]) |
| + result = self.call("exit", iid=iid, freshness=ready["observed"]) |
| + if result.get("activity"): |
| + self.event("exit-activity", activity=result["activity"]) |
| except Uncertain: |
| pass |
| # Always describe after a response, including a lost one. |
| @@ -949,8 +1117,8 @@ class Operator: |
| require(intent is not None, "return_intent") |
| require(g["desired"] == h["n"] and g["minimum"] in (h["n"] - 1, h["n"]), "members") |
| if phase == "Pending:Wait": |
| - self.state.write(self.state.blocked, dict(transaction=h["transaction"], phase=phase)) |
| self.event("return-hook", deadline=intent["at"] + 900) |
| + self.state.write(self.state.blocked, dict(transaction=h["transaction"], phase=phase)) |
| # Leave room for the bounded status sessions and completion. |
| if self.clock() + 120 >= intent["at"] + 900: |
| self.alert("return_failed", failed=True) |
| @@ -978,9 +1146,9 @@ class Operator: |
| require(ready["status"]["edge"]["identity"] == intent["process"], "admission") |
| self.event("return-action", key=key, attempt=len(attempts) + 1, |
| deadline=intent["at"] + 900, result="CONTINUE") |
| - require(0 <= self.clock() - ready["observed"] <= 5, "admission") |
| try: |
| - self.call("complete", iid=iid, hook=self.c["hook"], result="CONTINUE") |
| + self.call("complete", iid=iid, hook=self.c["hook"], result="CONTINUE", |
| + freshness=ready["observed"]) |
| self.event("return-outcome", key=key, attempt=len(attempts) + 1, outcome="acknowledged") |
| self.event("return-acknowledged", key=key) |
| except Uncertain: |
| @@ -996,6 +1164,14 @@ class Operator: |
| ready = self.readiness(iid, maintenance=True) |
| require(ready["status"]["edge"]["identity"] == intent["process"], "admission") |
| self.event("returned", process=intent["process"]) |
| + if self.j.last("return-hook"): |
| + require(g["minimum"] == h["n"] - 1, "held") |
| + self.event("divergence-hold", iid=iid) |
| + try: |
| + self.call("enter", iid=iid, decrement=True) |
| + except Uncertain: |
| + pass |
| + continue |
| if g["minimum"] != h["n"]: |
| self.event("phase", phase="restore-minimum") |
| self.call("minimum", value=h["n"]) |
| @@ -1016,12 +1192,17 @@ class Operator: |
| self.say("ALERT", TEXT["divergence"]) |
| return |
| require(phase in {"Pending", "PreInService", "Pending:Proceed"}, "return_phase") |
| - except FailedProbe: |
| + except (FailedProbe, DivergenceHeld): |
| + raise |
| + except ObservationExpired: |
| + if self.j.last("return-hook"): |
| + self.alert("return_failed", failed=True) |
| raise |
| except (Refusal, Uncertain): |
| - if self.j.last("exit-intent") and (locals().get("phase") == "Pending:Wait" or |
| - self.j.last("return-action")): |
| + if self.j.last("return-hook"): |
| self.alert("return_failed", failed=True) |
| + if g is None or phase != "Standby": |
| + raise |
| if self.clock() >= end: |
| self.alert("timeout" if locals().get("phase") == "Standby" else "return_phase") |
| if self.clock() >= end: |
| @@ -1048,9 +1229,14 @@ def main(argv=None): |
| require(os.geteuid() == 0, "root") |
| require(sys.stdin.isatty() or bool(args.attended_by and args.attended_by.strip()), "attended_required") |
| config = validate_config(decode(Path(args.config).read_bytes())) |
| - state = State(config) |
| + state = State(config, readonly=args.command == "status") |
| + if args.command == "status": |
| + journal = state.load(args.transaction, readonly=True) |
| + op = Operator(config, None, state, journal=journal) |
| + print(json.dumps(op.saved_status(), sort_keys=True)) |
| + return 0 |
| with state.lock(): |
| - op = Operator(config, AWS(config), state, attended_by=args.attended_by or "terminal") |
| + op = Operator(config, AWS(config), state, attended_by=args.attended_by) |
| if args.command == "plan": |
| try: |
| return 0 if op.plan(args.member, args.to_sha256) else 1 |
| @@ -1064,9 +1250,7 @@ def main(argv=None): |
| else: |
| journal = state.load(args.transaction) |
| op.j = journal |
| - if args.command == "status": |
| - print(json.dumps(op.saved_status(), sort_keys=True)) |
| - elif args.command == "rollback": |
| + if args.command == "rollback": |
| op.rollback(args.member) |
| elif args.command == "return": |
| op.return_member() |
diff --git a/scripts/region_group_roll_test.py b/scripts/region_group_roll_test.py| index 5c2a6797b..3c83d848a 100644 |
| --- a/scripts/region_group_roll_test.py |
| +++ b/scripts/region_group_roll_test.py |
| @@ -26,6 +26,10 @@ class Death(BaseException): |
| pass |
| +class ValidationError(Exception): |
| + pass |
| + |
| + |
| class Fake: |
| def __init__(self, config): |
| self.c = config |
| @@ -51,6 +55,10 @@ class Fake: |
| self.used = set() |
| self.after = None |
| self.launch_receipt = True |
| + self.publication_lag = 2 |
| + self.published = {iid: self.now - 5 for iid in self.states} |
| + self.version = "v0.34.0" |
| + self.previous_result = None |
| def box(self, iid): |
| boot = "boot-" + iid |
| @@ -68,6 +76,10 @@ class Fake: |
| self.states[IID] = "Terminated" |
| self.abandons += 1 |
| self.launches += 1 |
| + replacement = "i-" + "3" * 17 |
| + self.states[replacement] = "Pending:Wait" |
| + self.tg.pop(IID, None) |
| + self.tg[replacement] = "initial" |
| self.deadline = None |
| def request(self, op, args): |
| @@ -95,7 +107,7 @@ class Fake: |
| return dict(name=self.c["group"], arn=self.c["group_arn"], |
| deployment=self.c["deployment"], region=self.c["region"], |
| minimum=self.minimum, desired=self.desired, maximum=self.maximum, |
| - members=dict(self.states), healthy={i: True for i in self.states}, |
| + members={i: v for i, v in self.states.items() if v != "Terminated"}, healthy={i: True for i in self.states}, |
| target_groups=self.c["target_groups"], |
| template={"LaunchTemplateId": "lt-example", "Version": "1"}) |
| if op == "targets": |
| @@ -111,28 +123,37 @@ class Fake: |
| if self.outage: |
| raise roll.Uncertain("edges") |
| iid = next(i for i, s in self.boxes.items() if s["box_ref"] == a["box_ref"]) |
| - return dict(v=1, box=a["box_ref"], generation=roll.stamp(self.now), |
| + started = roll.instant(self.boxes[iid]["edge"]["started_at"]) |
| + lag = self.publication_lag if iid == IID else 2 |
| + if self.now >= started + lag: |
| + self.published[iid] = started + lag |
| + return dict(v=1, box=a["box_ref"], generation=roll.stamp(self.published[iid]), |
| admitted=self.admitted, box_role="serve") |
| if op == "minimum": |
| self.minimum = a["value"] |
| + self.desired = max(self.desired, self.minimum) |
| return {} |
| if op == "desired": |
| self.desired = a["value"] |
| return {} |
| if op == "enter": |
| + if a["decrement"] and self.desired - 1 < self.minimum: |
| + raise ValidationError("desired below minimum") |
| + self.activity.append(dict(id="enter-" + str(len(self.activity)), iid=IID, |
| + time=self.now, kind="enter")) |
| self.states[IID] = "Standby" |
| self.tg[IID] = "unused" |
| if a["decrement"]: |
| self.desired -= 1 |
| else: |
| self.launches += 1 |
| - return {} |
| + return {"activity": self.activity[-1]["id"]} |
| if op == "exit": |
| self.exits += 1 |
| self.desired += 1 |
| self.states[IID] = "Pending:Wait" if self.hook else "InService" |
| self.tg[IID] = "initial" if self.hook else "healthy" |
| - self.activity = [dict(id="exit-1", iid=IID, time=self.now)] |
| + self.activity.append(dict(id="exit-1", iid=IID, time=self.now, kind="exit")) |
| if self.hook: |
| self.deadline = self.now + 900 |
| if self.loss_after_exit: |
| @@ -156,7 +177,8 @@ class Fake: |
| if verb == "prepare": |
| if self.prepare_bad: |
| raise roll.Refusal("prepare") |
| - return dict(v=1, artifact_sha256=a["sha256"], old_binary_sha256=OLD, |
| + return dict(v=1, version=self.version, previous_result=self.previous_result, |
| + artifact_sha256=a["sha256"], old_binary_sha256=OLD, |
| cache_state="verified", request_written=True, config_check="valid") |
| if verb == "permit": |
| p = a["permit"] |
| @@ -196,7 +218,7 @@ class StandbyTests(unittest.TestCase): |
| target_groups=["arn:aws:elasticloadbalancing:eu-west-1:" + "0" * 12 + |
| ":targetgroup/example-" + p + "/" + p * 16 for p in ("8", "4")], |
| bucket="example-deployment", document="AWS-StartNonInteractiveCommand", |
| - state_dir=self.tmp.name, profile="example") |
| + state_dir=self.tmp.name, profile="example", min_release="v0.34.0") |
| self.fake = Fake(self.config) |
| self.output = io.StringIO() |
| self.store = roll.State(self.config, owner=os.geteuid()) |
| @@ -301,9 +323,15 @@ class StandbyTests(unittest.TestCase): |
| def test_standby_exit_pending_wait(self): |
| self.fake.hook = True |
| - self.run_roll() |
| + with self.assertRaises(roll.Refusal): |
| + self.run_roll() |
| self.assertEqual(self.fake.continues, 1) |
| self.assertTrue(self.store.blocked.exists()) |
| + self.assertEqual(self.fake.states[IID], "Standby") |
| + self.assertEqual(self.fake.tg[IID], "unused") |
| + self.assertEqual((self.fake.minimum, self.fake.desired), (1, 1)) |
| + self.assertEqual(self.fake.writes[-1], "enter") |
| + self.assertIsNotNone(self.store.active_id()) |
| self.assert_retained() |
| with self.assertRaises(roll.Refusal): |
| self.run_roll() |
| @@ -319,7 +347,8 @@ class StandbyTests(unittest.TestCase): |
| except (Death, roll.Refusal, roll.Uncertain): |
| pass |
| if self.store.active_id(): |
| - self.resume() |
| + with self.assertRaises(roll.Refusal): |
| + self.resume() |
| self.assertEqual(self.fake.continues, 1) |
| self.assertEqual(self.fake.exits, 1) |
| self.assert_retained() |
| @@ -434,11 +463,12 @@ class StandbyTests(unittest.TestCase): |
| return result |
| self.fake.perform = delayed |
| - self.run_roll() |
| + with self.assertRaises(roll.Refusal): |
| + self.run_roll() |
| self.assertGreaterEqual(polls, 3) |
| self.assertEqual(self.fake.continues, 1) |
| - def test_rev1_receipt_suppression_reaches_default_abandon(self): |
| + def test_fake_abandon_terminates_and_replaces(self): |
| self.fake.hook = True |
| self.fake.states[IID] = "Standby" |
| self.fake.desired = self.fake.minimum = 1 |
| @@ -447,8 +477,11 @@ class StandbyTests(unittest.TestCase): |
| self.fake.sleep(901) |
| self.assertEqual(self.fake.abandons, 1) |
| self.assertEqual(self.fake.states[IID], "Terminated") |
| - # The production-path witness above starts with the same valid receipt |
| - # and must complete exactly once, instead of taking this rev-1 path. |
| + self.assertEqual(self.fake.states["i-" + "3" * 17], "Pending:Wait") |
| + self.assertNotIn(IID, self.fake.request("group", {})["members"]) |
| + self.assertEqual(self.fake.launches, 1) |
| + # Mutation 6 is the real rev-1 witness: it changes the production |
| + # return path, suppresses CONTINUE, and must fail the retention test. |
| def test_standby_completion_retry_budget_and_journal(self): |
| self.fake.hook = True |
| @@ -499,10 +532,11 @@ class StandbyTests(unittest.TestCase): |
| def test_standby_post_exit_api_loss_fails_immediately(self): |
| self.fake.hook = True |
| + self.fake.fault, self.fake.fault_at = "loss", 6 |
| request = self.fake.request |
| def fail_describe(op, a): |
| - if op == "group" and self.fake.exits: |
| + if op == "activities" and self.fake.exits: |
| raise roll.Uncertain("API unavailable") |
| return request(op, a) |
| @@ -556,7 +590,7 @@ class StandbyTests(unittest.TestCase): |
| if race == "generation": |
| result["generation"] = self.fake.boxes[IID]["edge"]["started_at"] |
| elif race == "slow": |
| - self.fake.sleep(6) |
| + self.fake.sleep(61) |
| else: |
| self.fake.boxes[IID]["edge"]["identity"] += "-restarted" |
| return result |
| @@ -610,9 +644,359 @@ class StandbyTests(unittest.TestCase): |
| self.assertIn(roll.TEXT["peer"], self.output.getvalue()) |
| +class RoundOneTests(unittest.TestCase): |
| + setUp = StandbyTests.setUp |
| + engine = StandbyTests.engine |
| + run_roll = StandbyTests.run_roll |
| + resume = StandbyTests.resume |
| + assert_retained = StandbyTests.assert_retained |
| + |
| + def pause_after_apply(self): |
| + self.fake.fault, self.fake.fault_at = "death", 5 |
| + with self.assertRaises(Death): |
| + self.run_roll() |
| + |
| + def test_prepare_previous_results_refuse_before_group_write(self): |
| + for previous, message in (("applied", "already applied"), |
| + ("rolled-back", "already rolled back"), |
| + ("rollback-failed", "rollback failed")): |
| + with self.subTest(previous=previous): |
| + self.setUp() |
| + self.fake.previous_result = previous |
| + with self.assertRaisesRegex(roll.Refusal, message): |
| + self.run_roll() |
| + self.assertEqual(self.fake.writes, ["prepare"]) |
| + |
| + def test_release_floor_matches_go(self): |
| + floor = "v0.34.0" |
| + for version, below in (("v0.33.99", True), ("0.33.0", True), ("v0.34.0", False), |
| + ("1.0.0", False), ("0.9.0", True), ("dev", False), |
| + ("v00.33.0", False), ("0.33.0-1", False), |
| + ("v0.33.0+build", False), ("v0.33.0\n", False), |
| + ("v0.33.0000000000", False), ("v0.33.١", False)): |
| + with self.subTest(version=version): |
| + self.assertEqual(roll.below_floor(version, floor), below) |
| + self.fake.version = "v0.33.0" |
| + with self.assertRaises(roll.Refusal): |
| + self.run_roll() |
| + self.assertEqual(self.fake.writes, ["prepare"]) |
| + for value in ("dev", "v0.034.0", "v0.34", "0.34.0-1", "v1000000000.0.0"): |
| + with self.assertRaises(roll.Refusal): |
| + roll.validate_config(dict(self.config, min_release=value)) |
| + c = dict(self.config) |
| + del c["min_release"] |
| + with self.assertRaises(roll.Refusal): |
| + roll.validate_config(c) |
| + |
| + def test_wrong_digest_or_unchanged_process_is_immediate(self): |
| + for action in ("apply", "rollback"): |
| + for bad in ("digest", "process"): |
| + with self.subTest(action=action, bad=bad): |
| + self.setUp() |
| + if action == "rollback": |
| + self.pause_after_apply() |
| + before = copy.deepcopy(self.fake.boxes[IID]) |
| + def damage(name): |
| + if name == action: |
| + if bad == "digest": |
| + self.fake.boxes[IID]["binary_sha256"] = "d" * 64 |
| + else: |
| + self.fake.boxes[IID]["edge"] = before["edge"] |
| + self.fake.after = damage |
| + started = self.fake.now |
| + with self.assertRaises(roll.Refusal): |
| + if action == "apply": |
| + self.run_roll() |
| + else: |
| + with self.store.lock(): |
| + op = self.engine(self.store.load(self.store.active_id())) |
| + try: |
| + op.rollback(IID) |
| + finally: |
| + op.j.close() |
| + self.assertLess(self.fake.now - started, 10) |
| + self.assertIn("ALERT", self.output.getvalue()) |
| + self.assertEqual(self.fake.states[IID], "Standby") |
| + self.assertEqual(self.fake.exits, 0) |
| + self.assertEqual(self.fake.boxes[IID]["permit"]["state"], "present") |
| + |
| + def test_publication_lag_and_two_second_margin(self): |
| + self.fake.publication_lag = 20 |
| + self.run_roll() |
| + self.assertGreaterEqual(self.fake.now, 1800000020) |
| + for lag in (0, 1, 1.999): |
| + with self.subTest(lag=lag): |
| + self.setUp() |
| + self.pause_after_apply() |
| + self.fake.publication_lag = lag |
| + with self.assertRaises(roll.Refusal): |
| + self.resume() |
| + self.assertEqual(self.fake.exits, 0) |
| + |
| + def test_readiness_clock_starts_at_first_response_and_peers_get_sixty(self): |
| + request = self.fake.request |
| + def slow_status(op, a): |
| + if op == "session" and a["verb"] == "status": |
| + self.fake.sleep(20 if a["iid"] == PEER else 3) |
| + return request(op, a) |
| + self.fake.request = slow_status |
| + self.run_roll() |
| + self.assertEqual(self.fake.exits, 1) |
| + |
| + def test_continue_checks_age_after_journal_flush(self): |
| + self.fake.hook = True |
| + original = roll.Operator.event |
| + def delayed(engine, kind, **data): |
| + result = original(engine, kind, **data) |
| + if kind == "intent" and data.get("op") == "complete": |
| + self.fake.sleep(6) |
| + return result |
| + with patch.object(roll.Operator, "event", delayed): |
| + with self.assertRaises(roll.FailedProbe): |
| + self.run_roll() |
| + self.assertEqual(self.fake.continues, 0) |
| + self.assertLess(self.fake.now, self.fake.deadline) |
| + |
| + def test_observation_age_includes_first_response_journal_flush(self): |
| + engine = self.engine() |
| + original = engine.event |
| + responses = 0 |
| + def delayed(kind, **data): |
| + nonlocal responses |
| + result = original(kind, **data) |
| + if kind == "response" and data.get("op") == "session": |
| + responses += 1 |
| + if responses == 1: |
| + self.fake.sleep(10) |
| + return result |
| + engine.event = delayed |
| + start = self.fake.now |
| + ready = engine.readiness(IID) |
| + self.assertEqual(ready["observed"], start) |
| + |
| + def test_divergence_hold_crash_and_response_loss(self): |
| + for before, fault in ((False, "death"), (True, "death"), (False, "loss")): |
| + with self.subTest(before=before, fault=fault): |
| + self.setUp() |
| + self.fake.hook = True |
| + self.fake.fail_before = before |
| + self.fake.fault, self.fake.fault_at = fault, 8 |
| + with self.assertRaises((Death, roll.Refusal)): |
| + self.run_roll() |
| + with self.assertRaises(roll.DivergenceHeld): |
| + self.resume() |
| + writes = list(self.fake.writes) |
| + with self.assertRaises(roll.DivergenceHeld): |
| + self.resume(returning=True) |
| + self.assertEqual(writes, self.fake.writes) |
| + self.assertEqual(self.fake.continues, 1) |
| + self.assertEqual(self.fake.states[IID], "Standby") |
| + self.assertEqual((self.fake.minimum, self.fake.desired), (1, 1)) |
| + self.assertEqual(self.fake.writes.count("enter"), 2) |
| + self.assert_retained() |
| + |
| + def test_cut_apply_terminates_session_then_reads_status(self): |
| + request = self.fake.request |
| + def timeout(op, a): |
| + if op == "terminate_session": |
| + self.fake.calls.append((op, a)) |
| + return {} |
| + result = request(op, a) |
| + if op == "session" and a["verb"] == "apply": |
| + self.fake.last_session_id = "owned-session" |
| + raise roll.Uncertain("timeout", timeout=True) |
| + return result |
| + self.fake.request = timeout |
| + with self.assertRaises(roll.Uncertain): |
| + self.run_roll() |
| + index = next(i for i, (op, a) in enumerate(self.fake.calls) |
| + if op == "session" and a["verb"] == "apply") |
| + self.assertEqual(self.fake.calls[index + 1:index + 3], [ |
| + ("terminate_session", {"session_id": "owned-session"}), |
| + ("session", {"iid": IID, "verb": "status"})]) |
| + |
| + def test_unexpected_exit_success_is_journaled_before_describe(self): |
| + request = self.fake.request |
| + def unexpected(op, a): |
| + result = request(op, a) |
| + return {"outcome": "uncertain-success", "response": {}} if op == "exit" else result |
| + self.fake.request = unexpected |
| + self.run_roll() |
| + path = next(self.store.directory.glob("*.jsonl")) |
| + j = roll.Journal(path, self.store.owner, readonly=True) |
| + try: |
| + response = j.last("response", op="exit") |
| + self.assertEqual(response["result"]["outcome"], "uncertain-success") |
| + following = next(r for r in j.events[response["seq"] + 1:] if r["kind"] == "intent") |
| + self.assertEqual(following["op"], "group") |
| + finally: |
| + j.close() |
| + |
| + def test_tty_operator_identity_is_recorded(self): |
| + with patch.dict(os.environ, {"SUDO_USER": "example-operator"}): |
| + engine = roll.Operator(self.config, self.fake, self.store) |
| + self.assertEqual(engine.attended, "example-operator") |
| + with patch.dict(os.environ, {"SUDO_USER": ""}), patch.object(roll.getpass, "getuser", return_value="login"): |
| + engine = roll.Operator(self.config, self.fake, self.store) |
| + self.assertEqual(engine.attended, "login") |
| + |
| + def test_expired_exit_observation_leaves_resumable_record(self): |
| + self.pause_after_apply() |
| + original = roll.Operator.event |
| + def delayed(engine, kind, **data): |
| + result = original(engine, kind, **data) |
| + if kind == "intent" and data.get("op") == "exit": |
| + self.fake.sleep(6) |
| + return result |
| + with patch.object(roll.Operator, "event", delayed): |
| + with self.assertRaises(roll.Refusal): |
| + self.resume() |
| + self.assertEqual(self.fake.exits, 0) |
| + self.assertFalse(self.store.blocked.exists()) |
| + self.resume() |
| + self.assertEqual(self.fake.exits, 1) |
| + |
| + def test_ordinary_describe_blip_and_interrupt_do_not_block(self): |
| + for failure in (roll.Uncertain("describe blip"), KeyboardInterrupt()): |
| + with self.subTest(failure=type(failure).__name__): |
| + self.setUp() |
| + request = self.fake.request |
| + def fail(op, a): |
| + if op == "group" and self.fake.exits: |
| + raise failure |
| + return request(op, a) |
| + self.fake.request = fail |
| + with self.assertRaises(type(failure)): |
| + self.run_roll() |
| + self.assertFalse(self.store.blocked.exists()) |
| + j = self.store.load(self.store.active_id()) |
| + try: |
| + self.assertIsNone(j.last("failed-probe")) |
| + self.assertEqual(j.last("error")["error"], type(failure).__name__) |
| + finally: |
| + j.close() |
| + self.fake.request = request |
| + self.resume() |
| + |
| + def test_unknown_or_replaced_member_is_explicit_failed_probe(self): |
| + for phase in ("Unknown", "Terminated", "replaced"): |
| + with self.subTest(phase=phase): |
| + self.setUp() |
| + def alter(name): |
| + if name == "exit": |
| + self.fake.states[IID] = "Terminated" if phase == "replaced" else phase |
| + if phase == "replaced": |
| + self.fake.states["i-" + "3" * 17] = "InService" |
| + self.fake.after = alter |
| + with self.assertRaises(roll.Refusal): |
| + self.run_roll() |
| + j = self.store.load(self.store.active_id()) |
| + try: |
| + self.assertIsNotNone(j.last("failed-probe")) |
| + if phase != "Unknown": |
| + self.assertIn("member terminated or replaced: failed probe", j.last("failed-probe")["reason"]) |
| + finally: |
| + j.close() |
| + |
| + def test_external_minimum_change_is_not_adopted(self): |
| + self.fake.after = lambda name: setattr(self.fake, "minimum", 1) if name == "prepare" else None |
| + with self.assertRaises(roll.Refusal): |
| + self.run_roll() |
| + self.assertEqual(self.fake.writes, ["prepare"]) |
| + |
| + def test_fake_capacity_rules(self): |
| + with self.assertRaises(ValidationError): |
| + self.fake.request("enter", dict(iid=IID, decrement=True)) |
| + self.fake.desired = self.fake.minimum = 1 |
| + self.fake.request("minimum", {"value": 2}) |
| + self.assertEqual(self.fake.desired, 2) |
| + |
| + def test_ambiguous_exit_activity_uses_enter_not_operator_clock(self): |
| + self.fake.hook = True |
| + request = self.fake.request |
| + def shifted(op, a): |
| + result = request(op, a) |
| + if op == "enter": |
| + self.fake.activity[-1]["time"] -= 100 |
| + if op == "exit": |
| + self.fake.activity[-1]["time"] -= 100 |
| + raise roll.Uncertain("lost response") |
| + return result |
| + self.fake.request = shifted |
| + with self.assertRaises(roll.Refusal): |
| + self.run_roll() |
| + self.assertEqual(self.fake.continues, 1) |
| + self.assertEqual(self.fake.states[IID], "Standby") |
| + |
| + def test_resume_reads_status_first_after_cut_apply(self): |
| + self.pause_after_apply() |
| + self.fake.calls.clear() |
| + self.resume() |
| + self.assertEqual(self.fake.calls[0], ("session", dict(iid=IID, verb="status"))) |
| + |
| + def test_status_is_lock_free_and_read_only(self): |
| + self.pause_after_apply() |
| + config = Path(self.tmp.name) / "config.json" |
| + config.write_text(json.dumps(self.config)) |
| + before = {p.name: p.read_bytes() for p in self.store.directory.iterdir()} |
| + state_class = roll.State |
| + with self.store.lock(), patch.object(roll.os, "geteuid", return_value=0), \ |
| + patch.object(roll, "State", side_effect=lambda c, **kw: state_class(c, owner=os.getuid(), **kw)), \ |
| + patch.object(roll.sys, "stdout", self.output): |
| + rc = roll.main(["--config", str(config), "--attended-by", "tester", "status", |
| + "--transaction", self.store.active_id()]) |
| + self.assertEqual(rc, 0) |
| + self.assertEqual(before, {p.name: p.read_bytes() for p in self.store.directory.iterdir()}) |
| + |
| + |
| class AdapterTests(unittest.TestCase): |
| setUp = StandbyTests.setUp |
| + def test_apply_verb_and_session_bounds(self): |
| + adapter = roll.AWS(self.config) |
| + for verb in ("prepare", "apply", "rollback"): |
| + command = adapter.remote_command(dict(verb=verb, sha256=NEW), "nonce") |
| + self.assertIn("system group-maintenance " + verb, command) |
| + self.assertNotIn(". /etc/carlos/host.env", command) |
| + self.assertNotIn(" system apply", command) |
| + with patch.object(adapter, "invoke", return_value="") as invoke: |
| + with self.assertRaises(roll.Refusal): |
| + adapter.request("session", dict(iid=IID, verb=verb, sha256=NEW)) |
| + bound = invoke.call_args.kwargs["timeout"] |
| + self.assertGreaterEqual(bound, 360) |
| + if verb != "prepare": |
| + self.assertIn("timeout", command) |
| + self.assertGreater(bound, 930) |
| + |
| + def test_timeout_session_id_and_termination_are_journaled(self): |
| + adapter = roll.AWS(self.config) |
| + def invoke(service, verb, args, **kwargs): |
| + if verb == "terminate-session": |
| + return {} |
| + return adapter.session_output( |
| + [sys.executable, "-c", "import time; print('Starting session with SessionId: owned-session', flush=True); time.sleep(10)"], |
| + dict(os.environ), 0.1, on_session=adapter.session_started) |
| + with self.store.lock(): |
| + j = self.store.create(dict(transaction="test", config=self.config, iid=IID, new=NEW)) |
| + try: |
| + op = roll.Operator(self.config, adapter, self.store, j, output=self.output) |
| + with patch.object(adapter, "invoke", side_effect=invoke) as calls: |
| + with self.assertRaises(roll.Uncertain): |
| + op.box(IID, "apply") |
| + self.assertEqual(calls.call_args.args[:3], |
| + ("ssm", "terminate-session", ["--session-id", "owned-session"])) |
| + self.assertEqual(j.last("error", op="session")["session_id"], "owned-session") |
| + self.assertEqual(j.last("intent", op="terminate_session")["args"]["session_id"], "owned-session") |
| + self.assertIsNotNone(j.last("response", op="terminate_session")) |
| + finally: |
| + j.close() |
| + |
| + def test_unexpected_exit_success_is_uncertain_success(self): |
| + adapter = roll.AWS(self.config) |
| + with patch.object(adapter, "invoke", return_value={}): |
| + result = adapter.request("exit", dict(iid=IID)) |
| + self.assertEqual(result["outcome"], "uncertain-success") |
| + |
| def test_config_strict_and_no_real_defaults(self): |
| self.assertEqual(roll.validate_config(self.config), self.config) |
| for key, value in (("account", "wrong"), ("group_arn", "arn:wrong"), |
| @@ -708,7 +1092,11 @@ class AdapterTests(unittest.TestCase): |
| return 0 |
| adapter = roll.AWS(self.config) |
| - with patch.object(roll.subprocess, "Popen", Process): |
| + config_env = dict(AWS_CA_BUNDLE="example-ca", AWS_CONFIG_FILE="example-config", |
| + AWS_SHARED_CREDENTIALS_FILE="example-credentials") |
| + ambient = dict(config_env, AWS_ACCESS_KEY_ID="fixture", AWS_SECRET_ACCESS_KEY="fixture", |
| + AWS_SESSION_TOKEN="fixture", AWS_ENDPOINT_URL="https://example.com") |
| + with patch.dict(os.environ, ambient), patch.object(roll.subprocess, "Popen", Process): |
| adapter.invoke("autoscaling", "describe-lifecycle-hooks", []) |
| command, kwargs = seen[0] |
| for flag in ("--profile", "--region", "--output", "--no-cli-pager", "--no-paginate", |
| @@ -717,6 +1105,26 @@ class AdapterTests(unittest.TestCase): |
| self.assertEqual(kwargs["env"]["AWS_MAX_ATTEMPTS"], "1") |
| self.assertTrue(kwargs["start_new_session"]) |
| self.assertEqual(kwargs["stdin"], subprocess.DEVNULL) |
| + for key, value in config_env.items(): |
| + self.assertEqual(kwargs["env"][key], value) |
| + for key in ambient.keys() - config_env.keys(): |
| + self.assertNotIn(key, kwargs["env"]) |
| + |
| + def test_api_keyboard_interrupt_propagates(self): |
| + class Process: |
| + pid = 123456 |
| + calls = 0 |
| + def wait(self, timeout=None): |
| + self.calls += 1 |
| + if self.calls == 1: |
| + raise KeyboardInterrupt() |
| + return 0 |
| + adapter = roll.AWS(self.config) |
| + with patch.object(roll.subprocess, "Popen", return_value=Process()), \ |
| + patch.object(roll.os, "killpg") as kill: |
| + with self.assertRaises(KeyboardInterrupt): |
| + adapter.invoke("autoscaling", "describe-lifecycle-hooks", []) |
| + kill.assert_called_once_with(123456, roll.signal.SIGKILL) |
| def test_session_pty_captures_noninteractive_output(self): |
| result = roll.AWS.session_output( |
| @@ -766,8 +1174,8 @@ class MutationTests(unittest.TestCase): |
| 'self.box(h["iid"], "permit", permit={})\n self.call("enter", iid=h["iid"], decrement=True)')], |
| "test_standby_roll_order"), |
| ("blind desired reset", [ |
| - ('result = self.call("exit", iid=iid)', |
| - 'result = self.call("exit", iid=iid)\n self.call("desired", value=h["n"])')], |
| + ('result = self.call("exit", iid=iid, freshness=ready["observed"])', |
| + 'result = self.call("exit", iid=iid, freshness=ready["observed"])\n self.call("desired", value=h["n"])')], |
| "test_standby_roll_order"), |
| ("exit-on-timeout", [ |
| ('self.alert("timeout")', 'self.call("exit", iid=self.header["iid"])\n self.alert("timeout")')], |
| @@ -775,7 +1183,7 @@ class MutationTests(unittest.TestCase): |
| ("ignored transaction lock", [ |
| ('fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)', 'pass')], "test_lock_refuses_second_writer"), |
| ("original receipt suppresses return completion", [ |
| - ('self.call("complete", iid=iid, hook=self.c["hook"], result="CONTINUE")', 'self.sleep(901)')], |
| + ('self.call("complete", iid=iid, hook=self.c["hook"], result="CONTINUE",\n freshness=ready["observed"])', 'self.sleep(901)')], |
| "test_standby_exit_pending_wait"), |
| ("completion before fresh admission", [ |
| ('try:\n ready = self.readiness(iid, maintenance=True)', |