From f2c0f9006ddf22b4797dcb02cda05175e0aa8245 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Fri, 27 Nov 2026 17:10:05 -0500 Subject: [PATCH 1/2] A released beta reaches a self-hosted install by itself, and a broken install is noticed A beta never installed without a person, and a broken install went unnoticed (incident vu): - Permission changes are real ones. CloudFormation reports a Modify for every policy that names another part's output, since that value is known only after apply, even when the documents are byte for byte the same. permission_changes now compares each such Modify with the running release: both sides resolved the way the template resolves them (the running stack's parameter values, the change set's, an import keeping its running value when the parent feeds it the same way and its source output is the same), policy documents as IAM reads them. Only a difference in actions, resources or conditions counts; an Add, a real widening and anything that can't be compared still hold. - The release notes list the permission changes against the previous release, with the same comparison (.github/scripts/iam_diff.py, a step in release.yml). - The beta channel's window can be day "any": the hourly check installs each new beta, at least gap_hours (default 2) after the last install. Stable keeps its window; "any" is refused on stable. - The watch after an update probes Chat: the streaming function answers a direct invoke of /api/stream/probe by making Chat's own calls (the member check every stream runs, one call per DynamoDB grant in infra/streaming-dynamodb.json, changing nothing). A refusal rolls the release back like a failed worker probe. The updater may invoke the streaming function (ProbeChatAfterUpdate). - Alarms that can fire: log metric filters on ERROR lines (gateway, worker, streaming, updater), on a new structured GitHub rate-limit line, and on a new structured Chat answer line, each alarmed as a share of the traffic with metric math, into the alerts topic. --- .github/scripts/iam_diff.py | 133 ++++ .github/scripts/test_iam_diff.py | 97 +++ .github/workflows/release.yml | 31 + .../vu_unattended_beta_and_alarms.md | 5 + docs/self-host/troubleshooting.md | 8 + docs/self-host/updates.md | 10 +- infra/lib/app.ts | 2 + infra/lib/monitoring-stack.ts | 101 +++ infra/lib/updates-stack.ts | 9 + infra/test/fixtures/legacy-update-path.json | 6 + infra/test/fixtures/updater-role.json | 6 + infra/test/log-alarms.test.ts | 118 ++++ lambda/tests/test_updater_beta_window.py | 106 ++++ lambda/tests/test_updater_chat_probe.py | 132 ++++ lambda/tests/test_updater_iam.py | 2 + lambda/tests/test_updater_real_permissions.py | 265 ++++++++ lambda/updater/handler.py | 594 +++++++++++++++++- services/common/src/github_budget.rs | 6 + services/gateway/src/main.rs | 6 + services/gateway/src/routes/brain.rs | 33 + services/gateway/src/routes/mod.rs | 1 + services/gateway/src/routes/plans.rs | 7 +- services/gateway/src/routes/stream_probe.rs | 452 +++++++++++++ services/gateway/src/routes/system.rs | 10 +- services/worker/src/clients/github.rs | 25 +- .../vu_unattended_beta_and_alarms.rs | 112 ++++ 26 files changed, 2245 insertions(+), 32 deletions(-) create mode 100644 .github/scripts/iam_diff.py create mode 100644 .github/scripts/test_iam_diff.py create mode 100644 docs/incidents/vu_unattended_beta_and_alarms.md create mode 100644 infra/test/log-alarms.test.ts create mode 100644 lambda/tests/test_updater_beta_window.py create mode 100644 lambda/tests/test_updater_chat_probe.py create mode 100644 lambda/tests/test_updater_real_permissions.py create mode 100644 services/gateway/src/routes/stream_probe.rs create mode 100644 services/worker/src/passes/incidents/vu_unattended_beta_and_alarms.rs diff --git a/.github/scripts/iam_diff.py b/.github/scripts/iam_diff.py new file mode 100644 index 000000000..0cd647fc1 --- /dev/null +++ b/.github/scripts/iam_diff.py @@ -0,0 +1,133 @@ +"""The permission changes of a release, for its release notes. + +Every role, policy and resource policy of the native templates (the parent, +access.json and each part) is compared with the previous release's, both +resolved the way the install's updater compares them before an update +(lambda/updater/handler.py, resource_on and resource_difference): policy +documents as IAM means them, order ignored, so only a real difference in +actions, resources or conditions is listed. Here no install's values are +known, so each parameter stays its own name on both sides and both branches +of a condition are kept. + + iam_diff.py previous TAG < releases.json + The release a TAG install moves from: the newest published release + below TAG (any for a beta, a stable one for a stable TAG). releases.json + is `gh release list --json tagName,isPrerelease,isDraft`. + iam_diff.py diff OLD_DIR NEW_DIR [FROM_TAG] + Markdown for the release notes. Each DIR holds coderhelm.json, + access.json and stacks/*.json, as the release's native files do. +""" + +import importlib.util +import json +import pathlib +import sys + +HANDLER = pathlib.Path(__file__).resolve().parents[2] / "lambda" / "updater" / "handler.py" +_spec = importlib.util.spec_from_file_location("iam_diff_updater", HANDLER) +u = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(u) + +PSEUDO = ("AWS::AccountId", "AWS::Region", "AWS::Partition", "AWS::URLSuffix", "AWS::StackName", "AWS::StackId", + "AWS::NotificationARNs") + + +def previous(tag, releases): + """The tag of the release an install of `tag` moves from, or None.""" + beta = bool(u.parse_version(tag) and u.parse_version(tag)[3]) + best = None + for r in releases or []: + t = r.get("tagName") or "" + p = u.parse_version(t) + if not p or r.get("isDraft") or t == tag: + continue + if not beta and (p[3] or r.get("isPrerelease")): + continue + if u.compare(t, tag) >= 0: + continue + if best is None or u.compare(t, best) > 0: + best = t + return best + + +def templates(root): + root = pathlib.Path(root) + out = {} + for rel in ["coderhelm.json", "access.json"] + sorted(f"stacks/{p.name}" for p in (root / "stacks").glob("*.json")): + f = root / rel + if f.is_file(): + out[rel] = json.loads(f.read_text()) + return out + + +def side(t): + values = {name: "${" + name + "}" for name in (t.get("Parameters") or {})} + values.update({p: "${" + p + "}" for p in PSEUDO}) + return {"t": t, "values": values, "symbolic": True} + + +def is_permission(res): + t = res.get("Type") or "" + if t.startswith("AWS::IAM::") or t in u.POLICY_TYPES: + return True + return any(k in (res.get("Properties") or {}) for k in u.POLICY_PROPERTIES) + + +def diff(old_dir, new_dir): + """[(file, resource, type, what changes)].""" + old, new = templates(old_dir), templates(new_dir) + out = [] + for rel in sorted(set(old) | set(new)): + a, b = old.get(rel) or {}, new.get(rel) or {} + ra, rb = a.get("Resources") or {}, b.get("Resources") or {} + sa, sb = side(a), side(b) + for lid in sorted(set(ra) | set(rb)): + if not (is_permission(ra.get(lid) or {}) or is_permission(rb.get(lid) or {})): + continue + kind = (rb.get(lid) or ra.get(lid) or {}).get("Type") or "" + if lid not in ra: + out.append((rel, lid, kind, "added")) + continue + if lid not in rb: + out.append((rel, lid, kind, "removed")) + continue + try: + what = u.resource_difference(u.resource_on(sa, lid), u.resource_on(sb, lid)) + except u.Unknown as e: + what = f"couldn't be compared ({e})" + if what: + out.append((rel, lid, kind, what)) + for name in sorted(set(a.get("Conditions") or {}) | set(b.get("Conditions") or {})): + ca, cb = (a.get("Conditions") or {}).get(name), (b.get("Conditions") or {}).get(name) + if json.dumps(ca, sort_keys=True) != json.dumps(cb, sort_keys=True): + out.append((rel, name, "Condition", "added" if ca is None else "removed" if cb is None else "changes")) + return out + + +def markdown(changes, from_tag): + since = f"since {from_tag}" if from_tag else "since the previous release" + if not changes: + return (f"## Permission changes {since}\n\nNone: every role, policy and resource policy grants exactly what " + f"{from_tag or 'the previous release'}'s does (compared as the updater compares them).\n") + lines = [f"## Permission changes {since}", "", + "An update with these waits for an admin's OK; nothing else about permissions changes.", ""] + for rel, lid, kind, what in changes: + lines.append(f"- `{rel}` {lid} ({kind}): {what}") + return "\n".join(lines) + "\n" + + +def main(argv): + if len(argv) >= 2 and argv[0] == "previous": + found = previous(argv[1], json.load(sys.stdin)) + if found: + print(found) + return 0 + if len(argv) >= 3 and argv[0] == "diff": + print(markdown(diff(argv[1], argv[2]), argv[3] if len(argv) > 3 else ""), end="") + return 0 + print(__doc__, file=sys.stderr) + return 2 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/.github/scripts/test_iam_diff.py b/.github/scripts/test_iam_diff.py new file mode 100644 index 000000000..57260acb3 --- /dev/null +++ b/.github/scripts/test_iam_diff.py @@ -0,0 +1,97 @@ +"""The release notes' permission changes: only a real difference in a role's +or a policy's actions, resources or conditions is listed, compared the way +the install's updater compares them. + +Run: python3 -m unittest discover -s .github/scripts +""" + +import copy +import json +import pathlib +import sys +import tempfile +import unittest + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) +import iam_diff # noqa: E402 + +IMP = "Imp0123456789ab" +POLICY = {"Type": "AWS::IAM::Policy", "Properties": { + "PolicyName": "WorkerRoleDefaultPolicy", "Roles": [{"Ref": "WorkerRole"}], + "PolicyDocument": {"Version": "2012-10-17", "Statement": [ + {"Effect": "Allow", "Action": ["dynamodb:GetItem", "dynamodb:Query"], "Resource": [{"Ref": IMP}]}, + {"Effect": "Allow", "Action": "s3:GetObject", + "Resource": {"Fn::If": ["HasBucket", {"Fn::Sub": "arn:${AWS::Partition}:s3:::${Bucket}/*"}, {"Ref": "AWS::NoValue"}]}}, + ]}}} + + +def release(root, policy, conditions=None): + worker = {"Parameters": {IMP: {"Type": "String"}, "Bucket": {"Type": "String"}}, + "Conditions": conditions or {"HasBucket": {"Fn::Not": [{"Fn::Equals": [{"Ref": "Bucket"}, ""]}]}}, + "Resources": {"WorkerRole": {"Type": "AWS::IAM::Role", "Properties": {}}, "WorkerRoleDefaultPolicy": policy, + "Queue": {"Type": "AWS::SQS::Queue", "Properties": {"VisibilityTimeout": 30}}}} + (root / "stacks").mkdir(parents=True) + (root / "stacks" / "Worker.json").write_text(json.dumps(worker)) + (root / "coderhelm.json").write_text(json.dumps({"Resources": {}})) + + +class Diff(unittest.TestCase): + def setUp(self): + self.tmp = pathlib.Path(tempfile.mkdtemp()) + + def run_diff(self, old, new, **kw): + release(self.tmp / "old", old) + release(self.tmp / "new", new, **kw) + return iam_diff.diff(self.tmp / "old", self.tmp / "new") + + def test_the_same_policy_in_another_order_is_no_change(self): + p = copy.deepcopy(POLICY) + p["Properties"]["PolicyDocument"]["Statement"].reverse() + p["Properties"]["PolicyDocument"]["Statement"][1]["Action"].reverse() + self.assertEqual(self.run_diff(POLICY, p), []) + self.assertIn("None: every role", iam_diff.markdown([], "v1.0.0")) + + def test_an_added_action_is_listed(self): + p = copy.deepcopy(POLICY) + p["Properties"]["PolicyDocument"]["Statement"][0]["Action"].append("dynamodb:PutItem") + (change,) = self.run_diff(POLICY, p) + self.assertEqual(change[:3], ("stacks/Worker.json", "WorkerRoleDefaultPolicy", "AWS::IAM::Policy")) + self.assertIn("allows dynamodb:PutItem", change[3]) + md = iam_diff.markdown([change], "v1.0.0") + self.assertIn("## Permission changes since v1.0.0", md) + self.assertIn("dynamodb:PutItem", md) + + def test_a_change_in_a_branch_no_value_takes_is_listed(self): + p = copy.deepcopy(POLICY) + p["Properties"]["PolicyDocument"]["Statement"][1]["Resource"]["Fn::If"][1] = "*" + self.assertEqual(len(self.run_diff(POLICY, p)), 1) + + def test_a_changed_condition_is_listed(self): + out = self.run_diff(POLICY, POLICY, conditions={"HasBucket": {"Fn::Equals": ["a", "a"]}}) + self.assertEqual([(c[1], c[2]) for c in out], [("HasBucket", "Condition")]) + + def test_added_and_removed_resources(self): + release(self.tmp / "old", POLICY) + release(self.tmp / "new", POLICY) + t = json.loads((self.tmp / "new" / "stacks" / "Worker.json").read_text()) + t["Resources"]["Extra"] = {"Type": "AWS::Lambda::Permission", "Properties": {"Principal": "s3.amazonaws.com"}} + (self.tmp / "new" / "stacks" / "Worker.json").write_text(json.dumps(t)) + self.assertEqual([c[1:] for c in iam_diff.diff(self.tmp / "old", self.tmp / "new")], + [("Extra", "AWS::Lambda::Permission", "added")]) + + +class Previous(unittest.TestCase): + RELEASES = [{"tagName": "v1.3.0-beta.20261102", "isPrerelease": True}, {"tagName": "v1.2.0", "isPrerelease": False}, + {"tagName": "v1.3.0-beta.20261101", "isPrerelease": True}, {"tagName": "v1.4.0", "isDraft": True}, + {"tagName": "v1.1.0", "isPrerelease": False}] + + def test_a_beta_moves_from_the_newest_release_below_it(self): + self.assertEqual(iam_diff.previous("v1.3.0-beta.20261103", self.RELEASES), "v1.3.0-beta.20261102") + + def test_a_stable_release_moves_from_the_last_stable(self): + self.assertEqual(iam_diff.previous("v1.3.0", self.RELEASES), "v1.2.0") + self.assertIsNone(iam_diff.previous("v1.0.0", self.RELEASES)) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 98812e391..ff7636f7e 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -347,6 +347,31 @@ jobs: cfn-lint -i W3005 -i W2531 -- "$RUNNER_TEMP/native/coderhelm.json" "$RUNNER_TEMP/native/access.json" "$RUNNER_TEMP/native"/stacks/*.json cp "$RUNNER_TEMP/native/coderhelm.json" ../dist/coderhelm.json tar -czf ../dist/coderhelm-native.tar.gz -C "$RUNNER_TEMP/native" access.json stacks assets + # The release notes say what this release changes about permissions: + # every role, policy and resource policy of the native templates against + # the release an install moves from, compared as the install's updater + # compares them before an update (.github/scripts/iam_diff.py), so only + # a real difference in actions, resources or conditions is listed. + - name: Permission changes since the previous release + env: + GH_TOKEN: ${{ github.token }} + run: | + NOTE="$RUNNER_TEMP/notes/permission-changes.md" + mkdir -p "$RUNNER_TEMP/notes" "$RUNNER_TEMP/prev" + PREV="$(gh release list -R "$GITHUB_REPOSITORY" --limit 100 --json tagName,isPrerelease,isDraft | python3 .github/scripts/iam_diff.py previous "$TAG")" + if [ -n "$PREV" ] && gh release download "$PREV" -R "$GITHUB_REPOSITORY" -p coderhelm.json -p coderhelm-native.tar.gz -D "$RUNNER_TEMP/prev"; then + tar -xzf "$RUNNER_TEMP/prev/coderhelm-native.tar.gz" -C "$RUNNER_TEMP/prev" access.json stacks + python3 .github/scripts/iam_diff.py diff "$RUNNER_TEMP/prev" "$RUNNER_TEMP/native" "$PREV" > "$NOTE" + else + printf '## Permission changes\n\nNo earlier release with native templates to compare with.\n' > "$NOTE" + fi + cat "$NOTE" | tee -a "$GITHUB_STEP_SUMMARY" + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: release-notes + path: ${{ runner.temp }}/notes/ + if-no-files-found: error + retention-days: 3 - name: Checksums run: | (cd dist && sha256sum gateway.zip worker.zip mcp-proxy.zip dashboard.tar.gz source.tar.gz coderhelm-selfhost.tgz install.sh coderhelm.json coderhelm-native.tar.gz models.json coderhelm-log-reader.yaml coderhelm-log-reader-update.yaml coderhelm-bedrock-export.yaml > SHA256SUMS) @@ -383,6 +408,11 @@ jobs: with: name: release-dist path: dist + # Kept beside dist/, never in it: dist holds exactly what SHA256SUMS lists. + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: release-notes + path: notes - name: The files are the ones the build listed run: | cd dist @@ -437,6 +467,7 @@ jobs: pre=false case "$TAG" in *-*) pre=true ;; esac NOTES="Self-host release ${TAG}. Install: npx -y github:${GITHUB_REPOSITORY}#${TAG} init, then deploy. Update: npx -y github:${GITHUB_REPOSITORY}#${TAG} update --to ${TAG}. Check an install: npx -y github:${GITHUB_REPOSITORY} doctor. Verify it yourself: docs/self-host/updates-security.md." + NOTES="${NOTES}"$'\n\n'"$(cat notes/permission-changes.md)" if DRAFT=$(gh api "repos/${GITHUB_REPOSITORY}/releases/tags/${TAG}" --jq .draft 2>/dev/null); then mkdir -p "$RUNNER_TEMP/old" if gh release download "$TAG" -R "$GITHUB_REPOSITORY" -p SHA256SUMS -D "$RUNNER_TEMP/old"; then diff --git a/docs/incidents/vu_unattended_beta_and_alarms.md b/docs/incidents/vu_unattended_beta_and_alarms.md new file mode 100644 index 000000000..963d57d6e --- /dev/null +++ b/docs/incidents/vu_unattended_beta_and_alarms.md @@ -0,0 +1,5 @@ +# vu. `vu_unattended_beta_and_alarms` + +**What happened:** A self-hosted install on the beta channel never took a beta by itself, and a broken install went unnoticed. Every release looked like a permission change: CloudFormation reports a Modify for each policy that names another part's output, because that value is known only after apply, even when the policy documents are byte for byte the same. The updater counted any IAM Modify, and a scheduled update that changes permissions waits for a person, so the hourly check never applied one. The maintenance window was one hour a week (or a day), so at most one of several daily betas could install. After an update the watch probed only the worker and the gateway; Chat runs in its own function with its own role, lost a grant, and refused every question for about a day while both stayed healthy. The alarms counted Lambda Errors, which stay at 0 because the services catch and log every error, so none moved. + +**The guarantee:** A Modify counts as a permission change only when the resource differs once both sides are resolved the way the template resolves them: the running stack's parameter values before, the change set's after, and an import known only after apply keeps its running value when the parent feeds it the same way and its source output is the same. An Add, a real widening, and anything that can't be compared still wait for a person, as before. The release notes list the same comparison against the previous release. On the beta channel, `day: "any"` installs at any hour, at least `gap_hours` after the last install; the stable channel keeps its window. The watch asks the streaming function to make Chat's own calls (the member check every stream runs and each DynamoDB action its role is granted), and a refusal rolls the release back like a failed worker probe. Every install alarms on ERROR lines per function, GitHub rate-limit lines and Chat answers that failed, each as a share of the traffic, into the alerts topic. diff --git a/docs/self-host/troubleshooting.md b/docs/self-host/troubleshooting.md index bc2f7e132..4e31daf9e 100644 --- a/docs/self-host/troubleshooting.md +++ b/docs/self-host/troubleshooting.md @@ -99,6 +99,14 @@ Each step checks what you did before it moves on. When a check fails, fix it and **`update` says there isn't enough space.** Releases are kept in `~/.coderhelm/releases`. Delete old ones (keep the one you run), or set `CODERHELM_HOME` to a bigger disk. +## The install's own alarms + +Every install alarms into its alerts topic (`-alerts`; subscribe an email or a chat channel to it). The services catch and log their errors, so Lambda's own `Errors` metric stays at 0 even when they fail; these alarms read the log lines instead, each as a share of the traffic over most of an hour, never a count: + +- **`-gateway-error-lines`, `-worker-error-lines`, `-streaming-error-lines`, `-updater-error-lines`**: that function logged an ERROR line on 10% or more of its invocations. Read the ERROR lines in its log group. +- **`-github-rate-limited`**: GitHub refused or held back requests on 20% or more of the worker's invocations. The installation's hourly budget is spent; runs, reviews and checks wait for the next hour. +- **`-chat-answer-failed`**: Chat couldn't answer 20% or more of the questions asked (its sign-in check or the model failed). Read the "Chat couldn't answer" lines in the streaming function's log group. + ## Links point to localhost Links in comments and emails come from the public URL. Without a domain it is read from SSM (`/coderhelm-/public-url`) when a function starts; if a function started before the first deploy finished, it retries every 30 seconds. Check the parameter exists, then send a request (any page) to refresh it. diff --git a/docs/self-host/updates.md b/docs/self-host/updates.md index 09cb2c057..012e0e740 100644 --- a/docs/self-host/updates.md +++ b/docs/self-host/updates.md @@ -81,7 +81,9 @@ npx -y github:CoderHelm/coderhelm-platform auto-update on --window "Sun 03:00" - - **Auto-update** *default off*\ On, off. - **Window** *default Sun 03:00*\ - A day (or `daily`) and an hour. + A day (or `daily`) and an hour. On the beta channel it can also be **Any hour** (`day: "any"`): each new beta installs at the next hourly check, at least **Hours between installs** after the last install. +- **Hours between installs** *default 2*\ + With **Any hour** only: 1 to 168. - **Time zone** *default UTC*\ Any IANA name. - **Channel** *default stable*\ @@ -91,7 +93,7 @@ npx -y github:CoderHelm/coderhelm-platform auto-update on --window "Sun 03:00" - The settings in **Settings, then System** take effect at once (no deploy). The launch parameters, or the same values in `coderhelm.config.json` under `updates`, are the starting point of a new install. -An automatic update starts only when all of these hold: auto-update is on, the hour is the window's hour in your time zone, the release is on your channel, it isn't a major release while majors are `ask`, no update is running, that version hasn't already failed (an admin can still start it by hand), and every model the release calls answers a test call through your provider. +An automatic update starts only when all of these hold: auto-update is on, the hour is the window's hour in your time zone (or, with **Any hour** on the beta channel, the last install was at least **Hours between installs** ago), the release is on your channel, it isn't a major release while majors are `ask`, no update is running, that version hasn't already failed (an admin can still start it by hand), and every model the release calls answers a test call through your provider. ## The model check @@ -211,6 +213,7 @@ On an install made with Launch Stack, an update is a stack update of `coderhelm- 4. **Applies it, through the deploy role.** **Settings, then System** shows the change set's summary while it runs: how many resources are added, changed and removed, which ones are replaced, which parts it touches, and a link to it in the CloudFormation console if you want to look. - **You pressed Update:** it applies as soon as it is prepared. The card says next to the button that one press includes any change to what CoderHelm's own roles may do; those always stay inside the install's permissions boundary, and the deploy role can't change itself or the boundary. When it would replace or remove data, it stops: the card lists what it replaces or removes, in words, and **Replace the data and apply** applies exactly those changes (if they changed since the page showed them, it asks again). The raw CloudFormation list is under **Technical details**. - **The maintenance window started it (auto-update on):** it applies by itself, except when it would replace or remove data or change permissions: then it waits, admins get an email, and you confirm it on the page the same way. If auto-update was turned off before it ran, it waits for you to press **Apply**. + - **What counts as a permission change.** CloudFormation reports a policy that names another part's output as changed on every update, because that value is known only once the update runs. So the updater compares each such policy, role or resource policy with the running release's: both resolved the way the template resolves them, policy documents as IAM reads them (order doesn't matter). Only a difference in what it allows, on which resources or under which conditions, counts. A new role or policy, and one that can't be compared, always counts. Each release's notes list its permission changes against the release before it, compared the same way. - **The deploy role and the permissions boundaries never change in an update.** The deploy role can't change itself or a boundary (that is what keeps it from giving itself more), and executing the change set in the AWS console doesn't get around it: the stack's service role is the deploy role, so AWS runs it as that role whoever presses **Execute**. So every update keeps your install's own deploy role and boundaries exactly as they are, and the rest of the release installs. A release that needs newer ones lists them under [Permissions](#permissions), as a separate step. - **Before it runs**, the updater checks every IAM call the change set needs against the deploy role's own policy and boundary, as IAM has them now. If one would be refused, the update stops before anything changes and says which call and which rule refused it. 5. **Follows it.** The updater reads the change set and the stack every 5 minutes until the update ends, and again each time **Settings, then System** asks, so the page never shows an older state than CloudFormation's. An update executed outside the app (in the AWS console or the AWS CLI) is followed the same way, and the history records it as applied in the AWS console. Before it calls the update a success, it checks that the stack reports the new release. When the stack update starts, the install's own copy step checks every file of the release against the sha256 that `coderhelm.json` lists before any part changes. If a part fails, CloudFormation rolls the whole stack back to the previous release by itself. @@ -243,7 +246,8 @@ A try that didn't succeed never holds up the next release: automatic updates ski An update that finishes can still be broken in a way the address check misses: a worker that crashes on every job while the site answers. So for 10 minutes after every update, CoderHelm watches the new release: - **The worker's health check.** The updater asks the worker for `{"health": {}}`, which goes through the same start-up and entry path as every job but calls no model, GitHub or queue. It fails after 4 failed answers in a row, 30 seconds apart (about 2 minutes); one answer passes it. A call AWS refused or throttled says nothing about the release and never counts. -- **Errors.** CloudWatch's `Errors` against `Invocations` for the worker and the gateway since the update, against the hour before. It trips when at least 5 calls ran since the update, at least half of them failed, and the failure rate is at least 25 points above the hour before (an install that already failed often isn't rolled back for that). +- **Chat's health check.** Chat runs in its own function with its own role, so the worker answering says nothing about it. The updater asks that function to make Chat's own calls: the sign-in check every question starts with, for a member that doesn't exist, and one call for each table access Chat's role is granted, on a key no record has (nothing is written). A refusal fails it the same way as a failed worker check; a release from before this check, or AWS being busy, never counts. +- **Errors.** CloudWatch's `Errors` against `Invocations` for the worker, the gateway and Chat's function since the update, against the hour before. It trips when at least 5 calls ran since the update, at least half of them failed, and the failure rate is at least 25 points above the hour before (an install that already failed often isn't rolled back for that). If either one fails, CoderHelm rolls the install back by itself to the release it came from, with no review: a change to what CoderHelm's own roles may do is applied as for your **Update** press. Only a rollback that would replace or remove data waits for you (admins get an urgent email). Admins get an email naming the release, what was seen, and that it went back. The update's history entry reads **Rolled back**, and automatic updates skip that release. If the rollback can't start or AWS can't finish it, admins get an urgent email, the install stays on the new release, and CoderHelm doesn't try again: press **Roll back**. diff --git a/infra/lib/app.ts b/infra/lib/app.ts index 97df95bca..737db98a8 100644 --- a/infra/lib/app.ts +++ b/infra/lib/app.ts @@ -153,6 +153,8 @@ export function buildApp(app: cdk.App, cfg: ResolvedConfig, opts: { accessStack? cfg, gatewayFunction: api.gatewayFunction, workerFunction: worker.workerFunction, + streamingFunction: streaming.streamingFunction, + updaterFunction: updates?.updaterFunction, table: database.table, ticketQueue: api.ticketQueue, }); diff --git a/infra/lib/monitoring-stack.ts b/infra/lib/monitoring-stack.ts index 9a8ea993e..48e173071 100644 --- a/infra/lib/monitoring-stack.ts +++ b/infra/lib/monitoring-stack.ts @@ -9,11 +9,41 @@ import * as logs from "aws-cdk-lib/aws-logs"; import { Construct } from "constructs"; import { ResolvedConfig } from "./config"; +/** + * The structured lines the services write for these alarms + * (services/common/src/github_budget.rs RATE_LIMITED_EVENT, + * services/gateway/src/routes/brain.rs CHAT_ANSWER_EVENT). The services catch + * and log every error, so Lambda's own Errors metric stays at 0 while they + * fail: these alarms read the log lines instead. + */ +export const LOG_EVENTS = { rateLimited: "github_rate_limited", chatAnswer: "chat_answer" } as const; + +/** + * Each alarm is a share of the traffic, never a count: an install with ten + * questions a day and one with ten thousand alarm on the same failing share. + * The share is held over most of an hour, so one bad minute doesn't page. + */ +export const LOG_ALARMS = { + period: cdk.Duration.minutes(15), + evaluationPeriods: 4, + datapointsToAlarm: 3, + /** ERROR lines per 100 invocations of the function. */ + errorLinesPercent: 10, + /** GitHub rate-limit lines per 100 worker invocations. */ + rateLimitedPercent: 20, + /** Chat questions that failed, of every question asked. */ + chatFailedPercent: 20, +} as const; + interface MonitoringStackProps extends cdk.StackProps { stage: string; cfg: ResolvedConfig; gatewayFunction: lambda.Function; workerFunction: lambda.Function; + /** Chat's streams (infra/lib/streaming-stack.ts). */ + streamingFunction: lambda.Function; + /** The self-host updater, when the install has one. */ + updaterFunction?: lambda.Function; table: dynamodb.TableV2; ticketQueue: sqs.Queue; } @@ -246,6 +276,77 @@ export class MonitoringStack extends cdk.Stack { } } + // ── Alarms on what the services log, as a share of their traffic ────── + const logsOf = (id: string, fn: lambda.Function) => + logs.LogGroup.fromLogGroupName(this, `${id}LogGroup`, cdk.Fn.join("", ["/aws/lambda/", fn.functionName])); + const count = (id: string, logGroup: logs.ILogGroup, pattern: logs.IFilterPattern, metricName: string) => + new logs.MetricFilter(this, id, { + logGroup, + filterPattern: pattern, + metricNamespace: "CoderHelm/Logs", + metricName, + metricValue: "1", + defaultValue: 0, + }).metric({ period: LOG_ALARMS.period, statistic: "Sum" }); + const shareAlarm = (id: string, name: string, description: string, expression: string, usingMetrics: Record, percent: number) => { + const alarm = new cloudwatch.Alarm(this, id, { + alarmName: `${prefix}-${name}`, + alarmDescription: description, + metric: new cloudwatch.MathExpression({ expression, usingMetrics, period: LOG_ALARMS.period, label: name }), + threshold: percent, + evaluationPeriods: LOG_ALARMS.evaluationPeriods, + datapointsToAlarm: LOG_ALARMS.datapointsToAlarm, + comparisonOperator: cloudwatch.ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD, + treatMissingData: cloudwatch.TreatMissingData.NOT_BREACHING, + }); + alarm.addAlarmAction(new actions.SnsAction(alertTopic)); + return alarm; + }; + // The Rust services log JSON (tracing, `level` at the top); the Python + // updater logs Lambda's text lines ("[ERROR]\t