carlos / platform Public

Add P3a ingress alarms and opted-in clock and admission metrics

Append bounded chrony and actual admission-state observations to the existing
metrics batch while preserving switch-off input and per-instance memory series.
Use regional dimensions for opt-in alarms and add a default-off queue age alarm.
Pin contracts with mock plans, real batch witnesses and bounded refusal mutations.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 9f402df43541933ed1b5ee726240f09c7054acde parent 7474bd9
17 files changed, +1,316 −25
  • docs/superpowers/notes/census-proposal-region-ha-p3a.md +7 −3
  • docs/superpowers/notes/census-region-ha-p3a-claims.tsv +7 −3
  • infra/modules/region-host/group_alarms.tf +24 −0
  • infra/modules/region-host/ingress/alarms.tf +89 −0
  • infra/modules/region-host/ingress/tests/fixed-targets/main.tf +1 −0
  • infra/modules/region-host/ingress/tests/group_ingress.tftest.hcl +73 −0
  • infra/modules/region-host/ingress/variables.tf +33 −0
  • infra/modules/region-host/tests/group_alarms.tftest.hcl +106 −0
  • internal/groupadmission/observation.go +10 −0
  • internal/host/group_metrics.go +128 −0
  • internal/host/group_metrics_test.go +229 −0
  • internal/host/memwatch.go +25 −4
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −1
  • internal/provision/testdata/plan14-root-reads-region-ha-p3a.tsv +23 −14
  • scripts/check_region_group_plan_test.py +11 −0
  • scripts/group_alarm_plan_test.py +72 −0
  • scripts/testdata/region-group-plan/regional-alarms.json +477 −0

Intent

Human

<task-notification> <task-id>brecmny40</task-id> <tool-use-id>toolu_014Y4odvwRk6P7jG93GYmh6f</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/6cb8c43c-d494-478a-8f04-1067486903df/tasks/brecmny40.output</output-file> <status>completed</status> <summary>Background command "W=/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p3/.superpowers/sdd/2026-11-03-region-ha-p3a; sleep 20; while true; do if [ -s $W/task-3-astra-a.md ]; then cat $W/task-3-astra-a.md; exit 0; fi; if ! pgrep -f "task-3-astra-a.md" &gt;/dev/null; then echo DEAD; tail -c 400 $W/task-3-astra-a.log; exit 1; fi; sleep 60; done" completed (exit code 0)</summary> </task-notification>

Human

<task-notification> <task-id>a127e0764a9540ade</task-id> <tool-use-id>toolu_01KpA654k8HW8HaaF86QcB1q</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/6cb8c43c-d494-478a-8f04-1067486903df/tasks/a127e0764a9540ade.output</output-file> <status>completed</status> <summary>Agent "Opus review P3a Task 3" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>**Verdict: READY AFTER FIXES.** P1: 0, P2: 2, P3: 8. The gate itself holds. On an opted-in box, every path I traced stays closed until admission, the four facts come from real successes, and switch-off boxes are unchanged. The two P2s are a missing witness and a lost restart behaviour, not a way to start a tenant early. - **P2-1 (I4/A1, production-wired witnesses):** the one line in `runAgent` that switches on the non-HTTP gate (`admission.bind(svc, eb)`, `agent.go:595`) has no test. Every pre-admission witness sets the callbacks by hand on a bare activator. If that line is dropped, schedules, workers, run/session and respawn start tenants before admission with every test still green; HTTP stays closed through the edge option. - **P2-2 (I4, fixed services keep their behaviour):** the worker boot pass (`agent.go:818-830`) runs once, before admission. Every worker wake is refused, and nothing re-runs it when admission opens. Always-on workers stay down after every restart of an opted-in box. The P3s cover four more areas: - **Switch-off and logging:** a small extra cost on every reconcile when the switch is off. Refusal logs come late, and there is no log naming which fact a stuck box is waiting on. - **Weak witnesses:** the shutdown-order, root-adopt and flagship-unchanged tests prove less than their names say. I verified the shutdown order by reading the code. - **Copy:** "This service is starting" is also sent by an admitted drain box, and during shutdown. - **Gaps outside P3a and one open check:** two ungated paths to list for P3b. I did not check whether schedules due during the closed window are retried. The console exemption works only if sophie's console row is marked `Unit=console.service`. An unmarked console would be unreachable while the box starts, and permanently on a refused box. That check belongs on the approval card as a hard item. Tests: the Task 3 tests pass in groupadmission, activator, edge and host. On the first run the only failure was Task 4's uncommitted metric test. A rerun of host didn't build because Task 4 is mid-edit. The full review is in `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p3/.superpowers/sdd/2026-11-03-region-ha-p3a/task-3-review-opus.md`.</result> <usage><subagent_tokens>186682</subagent_tokens><tool_uses>71</tool_uses><duration_ms>707302</duration_ms></usage> </task-notification>

Attributed to this commit: 5.21 g CO₂e (648,342 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on region-ha-p3-group, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/docs/superpowers/notes/census-proposal-region-ha-p3a.md b/docs/superpowers/notes/census-proposal-region-ha-p3a.md
index d364fd063..43ef18123 100644
--- a/docs/superpowers/notes/census-proposal-region-ha-p3a.md
+++ b/docs/superpowers/notes/census-proposal-region-ha-p3a.md
@@ -1,6 +1,6 @@
# Census approval: region-ha-p3a
-Ruling `census-ruling-region-ha-p3a`. The independent reviewer approves or rejects every change below, 24 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+Ruling `census-ruling-region-ha-p3a`. The independent reviewer approves or rejects every change below, 28 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
| unit | change | read sites | what changed |
|---|---|---|---|
@@ -35,7 +35,7 @@ Ruling `census-ruling-region-ha-p3a`. The independent reviewer approves or rejec
| `internal/activator/workerbuild.go` `Service.startWorker` | sites | +whole:Route | P3a Task 3: add/recheck the local start prohibition on generation, worker, sidecar, command or root-control launch, including retained leases; preserve existing lease/ownership checks and fixed-unit exemptions. Whole Route passes to the in-memory predicate; no new filesystem/store read. |
| `internal/edge/edge.go` `Edge.ServeHTTP` | sites | +whole:Route ×2 | Refuse a reserved exact hostname with no serving peer before a local or remote catch-all can handle it; one snapshot supplies the reservation and dial decision; no new read or forwarding authority. P3a Task 3: refuse a managed tenant before forwarding, geo/proof preparation and dispatch; recheck the route after login next-path resolution. Only the fixed platform/unit scope is exempt. Whole Route passes to a local permission check, not a new store/path read. |
-Envelopes re-pinned: `infra/modules/region-host/ingress`, `infra/modules/region-host/ingress/tests`, `infra/modules/region-host/ingress/tests/fixed-targets`, `infra/modules/region-host/ingress/tests/fixed-targets/tests`, `infra/modules/region-host/tests`, `internal/activator`, `internal/boxroles`, `internal/edge`, `internal/edgesfile`, `internal/groupadmission`, `internal/host`, `internal/hostenv`, `internal/release`.
+Envelopes re-pinned: `infra/modules/region-host`, `infra/modules/region-host/ingress`, `infra/modules/region-host/ingress/tests`, `infra/modules/region-host/ingress/tests/fixed-targets`, `infra/modules/region-host/ingress/tests/fixed-targets/tests`, `infra/modules/region-host/tests`, `internal/activator`, `internal/boxroles`, `internal/edge`, `internal/edgesfile`, `internal/groupadmission`, `internal/host`, `internal/hostenv`, `internal/release`.
Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner.
@@ -74,6 +74,8 @@ Recorded dispositions, which each change must still satisfy:
New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff:
+- new `infra/modules/region-host/group_alarms.tf:external`: reads +file:external; written legacy, accepted-legacy, frozen
+- new `infra/modules/region-host/ingress/alarms.tf:external`: reads +file:external; written legacy, accepted-legacy, frozen
- new `infra/modules/region-host/ingress/main.tf:external`: reads +file:external; written legacy, accepted-legacy, frozen
- new `infra/modules/region-host/ingress/outputs.tf:external`: reads +file:external; written legacy, accepted-legacy, frozen
- new `infra/modules/region-host/ingress/tests/fixed-targets/main.tf:external`: reads +file:external; written legacy, accepted-legacy, frozen
@@ -84,6 +86,7 @@ New dispositions, which census-propose wrote and the reviewer checks against the
- new `infra/modules/region-host/ingress/variables.tf:external`: reads +file:external; written legacy, accepted-legacy, frozen
- new `infra/modules/region-host/ingress/versions.tf:external`: reads +file:external; written legacy, accepted-legacy, frozen
- new `infra/modules/region-host/tests/fixed_state_unchanged.tftest.hcl:external`: reads +file:external; written legacy, accepted-legacy, frozen
+- new `infra/modules/region-host/tests/group_alarms.tftest.hcl:external`: reads +file:external; written legacy, accepted-legacy, frozen
- new `internal/activator/group_admission.go:ExecBackend.admissionBefore`: reads +whole:Route; written legacy, accepted-legacy, frozen
- new `internal/activator/group_admission.go:ExecBackend.admissionContext`: reads +whole:Route; written legacy, accepted-legacy, frozen
- new `internal/activator/group_admission.go:ExecBackend.tenantStartRefusal`: reads +whole:Route; written legacy, accepted-legacy, frozen
@@ -97,8 +100,9 @@ New dispositions, which census-propose wrote and the reviewer checks against the
- new `internal/host/group_admission.go:fixedAdmission.TenantAdmissionExempt`: reads +whole:Route; written legacy, accepted-legacy, frozen
- new `internal/host/group_admission.go:fixedAdmission.bind`: reads +whole:Route; written legacy, accepted-legacy, frozen
- new `internal/host/group_admission.go:fixedAdmission.exempt`: reads +registry:Backing, +registry:Platform, +registry:Unit; written legacy, accepted-legacy, frozen
+- new `internal/host/memwatch.go:memwatchLoop`: reads +file:CommandContext; written legacy, accepted-legacy, frozen
- reads `internal/activator/backend_exec.go:ExecBackend.nestedReady`: +whole:Route; keeps legacy, task accepted-legacy
-Seal: `c68e2453bfc8afaf3794eb4c08850428982fa6954269b6b99bddfda4e6242929` → `9fed85ef7ebc62c2cbed156a2c60c51d07fe6080df4a2604be0246616bbbba05`.
+Seal: `c68e2453bfc8afaf3794eb4c08850428982fa6954269b6b99bddfda4e6242929` → `620dcb9b823894efbe91acdf155318d5220a7d81cf404a49c1cc6c05010e1000`.
Overlay: `internal/provision/testdata/plan14-root-reads-region-ha-p3a.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/notes/census-region-ha-p3a-claims.tsv b/docs/superpowers/notes/census-region-ha-p3a-claims.tsv
index 40a1116f8..d7511bede 100644
--- a/docs/superpowers/notes/census-region-ha-p3a-claims.tsv
+++ b/docs/superpowers/notes/census-region-ha-p3a-claims.tsv
@@ -1,11 +1,11 @@
infra/modules/region-host/ingress/main.tf:external Add isolated IPv4 NLB, VPC/zone lookups, validated CIDR egress, protected new EIPs and TCP health-checked target groups; no fixed-resource edits or root runtime reads.
infra/modules/region-host/ingress/outputs.tf:external Expose per-zone addresses and NLB/TG identities for root attachments and Task 4 alarms; no root runtime reads.
-infra/modules/region-host/ingress/tests/fixed-targets/main.tf:external Add dev-root fixture attaching literal instance IDs to both target groups with read-only AZ lookups and target-zone precondition; no fixed-module references or root runtime reads.
+infra/modules/region-host/ingress/tests/fixed-targets/main.tf:external Add dev-root fixture attaching literal instance IDs to both target groups with read-only AZ lookups and target-zone precondition; no fixed-module references or root runtime reads. Task 4 supplies expected target count from literal fixed targets to ingress alarms; no resource ownership or root runtime read changes.
infra/modules/region-host/ingress/tests/fixed-targets/tests/targets.tftest.hcl:external Add plan-only mock witnesses for target attachments and out-of-zone refusal; no live API calls or root runtime reads.
infra/modules/region-host/ingress/tests/fixed-targets/variables.tf:external Define explicit ingress and literal target inputs for the dev-root fixture; no root runtime reads.
infra/modules/region-host/ingress/tests/fixed-targets/versions.tf:external Declare OpenTofu/AWS provider requirements for the dev-root fixture; no root runtime reads.
-infra/modules/region-host/ingress/tests/group_ingress.tftest.hcl:external Add plan-only mock tests for NLB protocol, health, zone/VPC boundary, protected allocations and restricted SG traffic; remove the duplicate empty-subnet-result test in Task 1 fix round 1; no live API calls or root runtime reads.
-infra/modules/region-host/ingress/variables.tf:external Add ingress-only inputs and topology/CIDR validation; no root runtime reads.
+infra/modules/region-host/ingress/tests/group_ingress.tftest.hcl:external Add plan-only mock tests for NLB protocol, health, zone/VPC boundary, protected allocations and restricted SG traffic; remove the duplicate empty-subnet-result test in Task 1 fix round 1; no live API calls or root runtime reads. Task 4 adds plan-only mock alarm threshold, dimension, period, missing-data, disabled-default and same-region SNS checks; no live API calls.
+infra/modules/region-host/ingress/variables.tf:external Add ingress-only inputs and topology/CIDR validation; no root runtime reads. Task 4 adds explicit expected target count, optional same-region SNS topic and opt-in regional metrics identity; no fixed-resource changes or root reads.
infra/modules/region-host/ingress/versions.tf:external Declare OpenTofu and AWS provider requirements for the isolated ingress child; no root runtime reads.
infra/modules/region-host/tests/fixed_state_unchanged.tftest.hcl:external Add mock regression for the unchanged fixed instance/profile/SG/root-volume wiring and legacy outputs; no root runtime reads.
internal/host/agent.go:fastTick Run the optional desired-role reader on the existing tick after observing the armed change index; no new root path or timer, nil reader is unchanged.
@@ -52,3 +52,7 @@ internal/host/group_admission.go:fixedAdmission.TenantAdmissionExempt P3a Task 3
internal/host/group_admission.go:fixedAdmission.bind P3a Task 3: share the in-memory admission/effective-role predicate with HTTP, service and backend checks; whole Route is used only for fixed-route classification. Refuse without acquire, restore or launch; no new filesystem/store read.
internal/host/group_admission.go:fixedAdmission.exempt P3a Task 3: classify the existing Route Platform, Unit and Backing fields for the fixed-box exemption; unsupported group mode has no exemption. Does not grant any new lease or root start authority.
internal/activator/backend_exec.go:ExecBackend.nestedReady P3a Task 3: add/recheck the local start prohibition on generation, worker, sidecar, command or root-control launch, including retained leases; preserve existing lease/ownership checks and fixed-unit exemptions. Whole Route passes to the in-memory predicate; no new filesystem/store read.
+infra/modules/region-host/group_alarms.tf:external Add default-off termination queue age alarm, using existing queue name and regional SNS topic; no IAM, queue, consumer or instance changes.
+infra/modules/region-host/ingress/alarms.tf:external Add per-TG NLB alarms and optional deployment/region clock and admission alarms, notify only; no compute actions or fixed identifiers.
+infra/modules/region-host/tests/group_alarms.tftest.hcl:external Add plan-only mock queue alarm defaults, thresholds, missing-data and regional notification assertions.
+internal/host/memwatch.go:memwatchLoop On opted-in fixed boxes only, reuse Task 2 root-owned region-config reader and Task 3 state; on existing cadence execute absolute /usr/bin/chronyc with fixed -c tracking args, one-second context and bounded 4096-byte output. No shell, tenant-named path or new timer; switch-off reads no region config and executes no clock command.
diff --git a/infra/modules/region-host/group_alarms.tf b/infra/modules/region-host/group_alarms.tf
new file mode 100644
index 000000000..60ee7b7fe
--- /dev/null
+++ b/infra/modules/region-host/group_alarms.tf
@@ -0,0 +1,24 @@
+variable "termination_queue_alarm" {
+ type = bool
+ default = false
+ nullable = false
+ description = "Enable the termination queue age alarm. Keep disabled until the termination consumer is running."
+}
+
+resource "aws_cloudwatch_metric_alarm" "termination_queue_age" {
+ count = var.termination_queue_alarm ? 1 : 0
+ alarm_name = "${var.name}-termination-queue-age"
+ alarm_description = "A termination event has waited more than ten minutes. Check the termination consumer before relying on dead-box recovery."
+ namespace = "AWS/SQS"
+ metric_name = "ApproximateAgeOfOldestMessage"
+ statistic = "Maximum"
+ period = 60
+ evaluation_periods = 1
+ datapoints_to_alarm = 1
+ threshold = 600
+ comparison_operator = "GreaterThanThreshold"
+ treat_missing_data = "notBreaching"
+ alarm_actions = var.alerts_email != "" ? [aws_sns_topic.alerts[0].arn] : []
+ ok_actions = var.alerts_email != "" ? [aws_sns_topic.alerts[0].arn] : []
+ dimensions = { QueueName = aws_sqs_queue.terminations.name }
+}
diff --git a/infra/modules/region-host/ingress/alarms.tf b/infra/modules/region-host/ingress/alarms.tf
new file mode 100644
index 000000000..38e6429c2
--- /dev/null
+++ b/infra/modules/region-host/ingress/alarms.tf
@@ -0,0 +1,89 @@
+data "aws_region" "current" {}
+
+locals {
+ alarm_actions = var.alarm_topic_arn == null ? [] : [var.alarm_topic_arn]
+}
+
+resource "aws_cloudwatch_metric_alarm" "unhealthy" {
+ for_each = aws_lb_target_group.target
+ alarm_name = "${var.name}-${each.key}-unhealthy"
+ alarm_description = "A load balancer target has been unhealthy for 10 minutes. Starting boxes and boxes not admitted yet return 503 by design. Investigate a box that remains in this state."
+ namespace = "AWS/NetworkELB"
+ metric_name = "UnHealthyHostCount"
+ statistic = "Maximum"
+ period = 60
+ evaluation_periods = 10
+ datapoints_to_alarm = 10
+ threshold = 0
+ comparison_operator = "GreaterThanThreshold"
+ treat_missing_data = "breaching"
+ alarm_actions = local.alarm_actions
+ ok_actions = local.alarm_actions
+ dimensions = {
+ LoadBalancer = aws_lb.nlb.arn_suffix
+ TargetGroup = each.value.arn_suffix
+ }
+}
+
+resource "aws_cloudwatch_metric_alarm" "healthy" {
+ for_each = aws_lb_target_group.target
+ alarm_name = "${var.name}-${each.key}-healthy"
+ alarm_description = "Fewer load balancer targets are healthy than there are boxes for 25 minutes. Investigate the unhealthy boxes and the load balancer path."
+ namespace = "AWS/NetworkELB"
+ metric_name = "HealthyHostCount"
+ statistic = "Minimum"
+ period = 60
+ evaluation_periods = 25
+ datapoints_to_alarm = 25
+ threshold = var.expected_targets
+ comparison_operator = "LessThanThreshold"
+ treat_missing_data = "breaching"
+ alarm_actions = local.alarm_actions
+ ok_actions = local.alarm_actions
+ dimensions = {
+ LoadBalancer = aws_lb.nlb.arn_suffix
+ TargetGroup = each.value.arn_suffix
+ }
+}
+
+resource "aws_cloudwatch_metric_alarm" "clock" {
+ count = var.regional_metrics == null ? 0 : 1
+ alarm_name = "${var.name}-clock"
+ alarm_description = "A box clock is more than one second off for one minute, or its reading is missing. Lease safety depends on accurate clocks."
+ namespace = "Carlos/Host"
+ metric_name = "ClockOffsetSeconds"
+ statistic = "Maximum"
+ period = 60
+ evaluation_periods = 1
+ datapoints_to_alarm = 1
+ threshold = 1
+ comparison_operator = "GreaterThanThreshold"
+ treat_missing_data = "breaching"
+ alarm_actions = local.alarm_actions
+ ok_actions = local.alarm_actions
+ dimensions = {
+ Deployment = var.regional_metrics.deployment
+ Region = var.regional_metrics.region
+ }
+}
+
+resource "aws_cloudwatch_metric_alarm" "admitted" {
+ count = var.regional_metrics == null ? 0 : 1
+ alarm_name = "${var.name}-admission"
+ alarm_description = "A box has not been admitted for one minute, or admission readings are missing. Check the box startup diagnostics."
+ namespace = "Carlos/Host"
+ metric_name = "Admitted"
+ statistic = "Minimum"
+ period = 60
+ evaluation_periods = 1
+ datapoints_to_alarm = 1
+ threshold = 1
+ comparison_operator = "LessThanThreshold"
+ treat_missing_data = "breaching"
+ alarm_actions = local.alarm_actions
+ ok_actions = local.alarm_actions
+ dimensions = {
+ Deployment = var.regional_metrics.deployment
+ Region = var.regional_metrics.region
+ }
+}
diff --git a/infra/modules/region-host/ingress/tests/fixed-targets/main.tf b/infra/modules/region-host/ingress/tests/fixed-targets/main.tf
index 9b5885369..38c947bbe 100644
--- a/infra/modules/region-host/ingress/tests/fixed-targets/main.tf
+++ b/infra/modules/region-host/ingress/tests/fixed-targets/main.tf
@@ -1,5 +1,6 @@
module "ingress" {
source = "../.."
+ expected_targets = length(var.target_ids)
name = var.name
vpc_id = var.vpc_id
zones = var.zones
diff --git a/infra/modules/region-host/ingress/tests/group_ingress.tftest.hcl b/infra/modules/region-host/ingress/tests/group_ingress.tftest.hcl
index 083d37296..2dd9545d5 100644
--- a/infra/modules/region-host/ingress/tests/group_ingress.tftest.hcl
+++ b/infra/modules/region-host/ingress/tests/group_ingress.tftest.hcl
@@ -1,4 +1,5 @@
mock_provider "aws" {
+ mock_data "aws_region" { defaults = { region = "eu-west-1" } }
mock_data "aws_subnets" {
defaults = { ids = ["subnet-0123456789abcdef0", "subnet-0123456789abcdef1"] }
}
@@ -29,6 +30,7 @@ mock_provider "aws" {
}
variables {
+ expected_targets = 2
name = "shop-probe"
vpc_id = "vpc-0123456789abcdef0"
target_vpc_cidrs = ["10.0.0.0/16"]
@@ -207,3 +209,74 @@ run "secondary_cidr_missing_refused" {
}
expect_failures = [aws_security_group.nlb]
}
+
+run "group_alarm_contract" {
+ command = plan
+ variables {
+ regional_metrics = { deployment = "shop-deployment", region = "ie" }
+ alarm_topic_arn = "arn:aws:sns:eu-west-1:123456789012:shop-alerts"
+ }
+ assert {
+ condition = length(aws_cloudwatch_metric_alarm.unhealthy) == 2 && alltrue([for port, a in aws_cloudwatch_metric_alarm.unhealthy :
+ a.namespace == "AWS/NetworkELB" && a.metric_name == "UnHealthyHostCount" && a.statistic == "Maximum" &&
+ a.threshold == 0 && a.comparison_operator == "GreaterThanThreshold" && a.period == 60 &&
+ a.evaluation_periods == 10 && a.datapoints_to_alarm == 10 && a.treat_missing_data == "breaching" &&
+ a.dimensions == tomap({ LoadBalancer = aws_lb.nlb.arn_suffix, TargetGroup = aws_lb_target_group.target[port].arn_suffix }) &&
+ length(a.metric_query) == 0 && a.alarm_actions == toset([var.alarm_topic_arn]) && a.ok_actions == a.alarm_actions
+ ])
+ error_message = "unhealthy target alarms must read each target group for ten minutes"
+ }
+ assert {
+ condition = length(aws_cloudwatch_metric_alarm.healthy) == 2 && alltrue([for port, a in aws_cloudwatch_metric_alarm.healthy :
+ a.namespace == "AWS/NetworkELB" && a.metric_name == "HealthyHostCount" && a.statistic == "Minimum" &&
+ a.threshold == var.expected_targets && a.comparison_operator == "LessThanThreshold" && a.period == 60 &&
+ a.evaluation_periods == 25 && a.datapoints_to_alarm == 25 && a.treat_missing_data == "breaching" &&
+ a.dimensions == tomap({ LoadBalancer = aws_lb.nlb.arn_suffix, TargetGroup = aws_lb_target_group.target[port].arn_suffix }) &&
+ length(a.metric_query) == 0 && a.alarm_actions == toset([var.alarm_topic_arn]) && a.ok_actions == a.alarm_actions
+ ])
+ error_message = "healthy target alarms must read each target group for twenty-five minutes"
+ }
+ assert {
+ condition = (
+ aws_cloudwatch_metric_alarm.clock[0].metric_name == "ClockOffsetSeconds" &&
+ aws_cloudwatch_metric_alarm.clock[0].statistic == "Maximum" &&
+ aws_cloudwatch_metric_alarm.clock[0].threshold == 1 &&
+ aws_cloudwatch_metric_alarm.clock[0].comparison_operator == "GreaterThanThreshold" &&
+ aws_cloudwatch_metric_alarm.admitted[0].metric_name == "Admitted" &&
+ aws_cloudwatch_metric_alarm.admitted[0].statistic == "Minimum" &&
+ aws_cloudwatch_metric_alarm.admitted[0].threshold == 1 &&
+ aws_cloudwatch_metric_alarm.admitted[0].comparison_operator == "LessThanThreshold" &&
+ alltrue([for a in [aws_cloudwatch_metric_alarm.clock[0], aws_cloudwatch_metric_alarm.admitted[0]] :
+ a.namespace == "Carlos/Host" && a.period == 60 && a.evaluation_periods == 1 && a.datapoints_to_alarm == 1 &&
+ a.treat_missing_data == "breaching" && a.dimensions == tomap({ Deployment = "shop-deployment", Region = "ie" }) &&
+ a.alarm_actions == toset([var.alarm_topic_arn]) && a.ok_actions == a.alarm_actions
+ ])
+ )
+ error_message = "clock and admission alarms must match the regional producer"
+ }
+}
+run "group_alarm_defaults" {
+ command = plan
+ assert {
+ condition = length(aws_cloudwatch_metric_alarm.clock) == 0 && length(aws_cloudwatch_metric_alarm.admitted) == 0 && alltrue([
+ for a in concat(values(aws_cloudwatch_metric_alarm.healthy), values(aws_cloudwatch_metric_alarm.unhealthy)) :
+ length(a.alarm_actions) == 0 && length(a.ok_actions) == 0
+ ])
+ error_message = "regional alarms must be opt-in and alarm actions must default to empty"
+ }
+}
+run "group_alarm_wrong_region" {
+ command = plan
+ variables { alarm_topic_arn = "arn:aws:sns:us-east-1:123456789012:shop-alerts" }
+ expect_failures = [var.alarm_topic_arn]
+}
+run "group_alarm_invalid_expected_targets" {
+ command = plan
+ variables { expected_targets = 0 }
+ expect_failures = [var.expected_targets]
+}
+run "group_alarm_missing_producer_identity" {
+ command = plan
+ variables { regional_metrics = { deployment = "", region = "ie" } }
+ expect_failures = [var.regional_metrics]
+}
diff --git a/infra/modules/region-host/ingress/variables.tf b/infra/modules/region-host/ingress/variables.tf
index 60535de29..601de6ef5 100644
--- a/infra/modules/region-host/ingress/variables.tf
+++ b/infra/modules/region-host/ingress/variables.tf
@@ -44,3 +44,36 @@ variable "target_vpc_cidrs" {
error_message = "target_vpc_cidrs must match the target VPC"
}
}
+
+variable "expected_targets" {
+ type = number
+ nullable = false
+ description = "Number of boxes expected to be healthy in each target group."
+ validation {
+ condition = var.expected_targets >= 1 && floor(var.expected_targets) == var.expected_targets
+ error_message = "expected_targets must be a positive whole number"
+ }
+}
+
+variable "alarm_topic_arn" {
+ type = string
+ default = null
+ description = "Confirmed SNS topic in this module's AWS region. Null creates alarms without notification actions."
+ validation {
+ condition = var.alarm_topic_arn == null ? true : can(regex("^arn:[a-z0-9-]+:sns:${data.aws_region.current.region}:[0-9]{12}:[A-Za-z0-9_-]+$", var.alarm_topic_arn))
+ error_message = "alarm_topic_arn must name an SNS topic in this module's AWS region"
+ }
+}
+
+variable "regional_metrics" {
+ type = object({ deployment = string, region = string })
+ default = null
+ description = "Enable clock and admission alarms only after fixed boxes publish these series. Deployment is CARLOS_DEPLOYMENT_BUCKET; region is the canonical region_code in region-config.json. Null disables both alarms."
+ validation {
+ condition = var.regional_metrics == null ? true : (
+ try(length(trimspace(var.regional_metrics.deployment)) > 0, false) &&
+ can(regex("^[a-z][a-z0-9-]{0,31}$", var.regional_metrics.region))
+ )
+ error_message = "regional_metrics must name the deployment bucket and region code used by the boxes"
+ }
+}
diff --git a/infra/modules/region-host/tests/group_alarms.tftest.hcl b/infra/modules/region-host/tests/group_alarms.tftest.hcl
new file mode 100644
index 000000000..21b09ab0c
--- /dev/null
+++ b/infra/modules/region-host/tests/group_alarms.tftest.hcl
@@ -0,0 +1,106 @@
+# Plan-time tests for the host instance's metadata service settings.
+# mock_provider means no AWS account and no credentials.
+mock_provider "aws" {}
+
+override_data {
+ target = data.aws_vpcs.default
+ values = { ids = ["vpc-0aaaaaaaaaaaaaaaa"] }
+}
+
+override_data {
+ target = data.aws_caller_identity.current
+ values = { account_id = "123456789012" }
+}
+
+# The termination queue's ARN feeds an EventBridge target, which the provider
+# validates as an ARN; the mock's random string is not one.
+override_resource {
+ target = aws_sqs_queue.terminations
+ values = { arn = "arn:aws:sqs:eu-west-1:123456789012:carlos-test-host-terminations" }
+}
+
+variables {
+ name = "carlos-test-ie"
+ sg_description = "carlos test host"
+ iam_name = "carlos-test-host"
+ instance_type = "t4g.small"
+ root_volume_size = 20
+ user_data = "#!/bin/sh\n"
+ deployment_bucket_arn = "arn:aws:s3:::carlos-test-platform"
+ data_bucket_arn = "arn:aws:s3:::carlos-test-ie"
+ ssm_parameter_arn = "arn:aws:ssm:eu-west-1:123456789012:parameter/carlos/*"
+}
+
+
+override_data {
+ target = data.aws_ami.debian_arm64
+ values = { id = "ami-0123456789abcdef0" }
+}
+override_data {
+ target = data.aws_vpc.host
+ values = { cidr_block = "10.0.0.0/16" }
+}
+override_resource {
+ target = aws_instance.host
+ values = { id = "i-0123456789abcdef0" }
+}
+override_resource {
+ target = aws_security_group.host
+ values = { id = "sg-0123456789abcdef0" }
+}
+override_resource {
+ target = aws_iam_role.host
+ values = { arn = "arn:aws:iam::123456789012:role/carlos-test-host" }
+}
+override_resource {
+ target = aws_eip.host
+ values = { public_ip = "192.0.2.10" }
+}
+
+run "termination_alarm_default_off" {
+ command = plan
+ assert {
+ condition = length(aws_cloudwatch_metric_alarm.termination_queue_age) == 0
+ error_message = "fixed plans must not gain a termination queue alarm by default"
+ }
+}
+run "termination_alarm_contract" {
+ command = plan
+ variables { termination_queue_alarm = true }
+ assert {
+ condition = (
+ aws_cloudwatch_metric_alarm.termination_queue_age[0].namespace == "AWS/SQS" &&
+ aws_cloudwatch_metric_alarm.termination_queue_age[0].metric_name == "ApproximateAgeOfOldestMessage" &&
+ aws_cloudwatch_metric_alarm.termination_queue_age[0].statistic == "Maximum" &&
+ aws_cloudwatch_metric_alarm.termination_queue_age[0].threshold == 600 &&
+ aws_cloudwatch_metric_alarm.termination_queue_age[0].comparison_operator == "GreaterThanThreshold" &&
+ aws_cloudwatch_metric_alarm.termination_queue_age[0].period == 60 &&
+ aws_cloudwatch_metric_alarm.termination_queue_age[0].evaluation_periods == 1 &&
+ aws_cloudwatch_metric_alarm.termination_queue_age[0].datapoints_to_alarm == 1 &&
+ aws_cloudwatch_metric_alarm.termination_queue_age[0].treat_missing_data == "notBreaching" &&
+ aws_cloudwatch_metric_alarm.termination_queue_age[0].dimensions == tomap({ QueueName = aws_sqs_queue.terminations.name }) &&
+ length(aws_cloudwatch_metric_alarm.termination_queue_age[0].alarm_actions) == 0
+ )
+ error_message = "termination queue alarm contract changed"
+ }
+}
+
+run "termination_alarm_regional_notifications" {
+ command = plan
+ variables {
+ termination_queue_alarm = true
+ alerts_email = "ops@example.com"
+ }
+ override_resource {
+ target = aws_sns_topic.alerts
+ values = { arn = "arn:aws:sns:eu-west-1:123456789012:shop-alerts" }
+ }
+ assert {
+ condition = (
+ aws_cloudwatch_metric_alarm.termination_queue_age[0].alarm_actions == toset([aws_sns_topic.alerts[0].arn]) &&
+ aws_cloudwatch_metric_alarm.termination_queue_age[0].ok_actions == toset([aws_sns_topic.alerts[0].arn]) &&
+ aws_sns_topic_subscription.alerts_email[0].topic_arn == aws_sns_topic.alerts[0].arn
+ )
+ error_message = "termination alerts must use the existing regional notification topic"
+ }
+}
diff --git a/internal/groupadmission/observation.go b/internal/groupadmission/observation.go
new file mode 100644
index 000000000..37d44cdc8
--- /dev/null
+++ b/internal/groupadmission/observation.go
@@ -0,0 +1,10 @@
+package groupadmission
+
+import "time"
+
+type Observation struct {
+ At time.Time
+ Deployment, Region string
+ Admitted bool
+ ClockOffset *time.Duration
+}
diff --git a/internal/host/group_metrics.go b/internal/host/group_metrics.go
new file mode 100644
index 000000000..e09d777fc
--- /dev/null
+++ b/internal/host/group_metrics.go
@@ -0,0 +1,128 @@
+package host
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "math"
+ "os/exec"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/aws/aws-sdk-go-v2/aws"
+ "github.com/aws/aws-sdk-go-v2/service/cloudwatch/types"
+ "github.com/carlosframework/platform/internal/groupadmission"
+)
+
+type admissionMetrics struct {
+ deployment, region string
+ state *groupadmission.State
+ clock func(context.Context) (time.Duration, error)
+}
+
+func admissionMetricsFromEnv(getenv func(string) string, a *fixedAdmission, readRegion func(string, string) (roleRegionConfig, error), clock func(context.Context) (time.Duration, error)) *admissionMetrics {
+ if getenv("CARLOS_GROUP_ADMISSION") != "1" || a == nil || a.group {
+ return nil
+ }
+ deployment := strings.TrimSpace(getenv("CARLOS_DEPLOYMENT_BUCKET"))
+ region, err := readRegion(roleRegionConfigPath, strings.TrimSpace(getenv("CARLOS_REGION")))
+ if deployment == "" || err != nil {
+ return nil
+ }
+ return &admissionMetrics{deployment: deployment, region: region.RegionCode, state: &a.state, clock: clock}
+}
+
+func (m *admissionMetrics) observe(ctx context.Context, now time.Time) (groupadmission.Observation, error) {
+ o := groupadmission.Observation{At: now, Deployment: m.deployment, Region: m.region, Admitted: m.state.Admitted()}
+ offset, err := m.clock(ctx)
+ if err == nil {
+ o.ClockOffset = &offset
+ }
+ return o, err
+}
+
+func admissionMetricData(o groupadmission.Observation) []types.MetricDatum {
+ dims := []types.Dimension{{Name: aws.String("Deployment"), Value: aws.String(o.Deployment)}, {Name: aws.String("Region"), Value: aws.String(o.Region)}}
+ admitted := float64(0)
+ if o.Admitted {
+ admitted = 1
+ }
+ data := []types.MetricDatum{{MetricName: aws.String("Admitted"), Dimensions: dims, Timestamp: aws.Time(o.At), Unit: types.StandardUnitCount, Value: aws.Float64(admitted)}}
+ if o.ClockOffset != nil {
+ data = append(data, types.MetricDatum{MetricName: aws.String("ClockOffsetSeconds"), Dimensions: dims, Timestamp: aws.Time(o.At), Unit: types.StandardUnitSeconds, Value: aws.Float64(o.ClockOffset.Seconds())})
+ }
+ return data
+}
+
+type chronyOutput struct {
+ data []byte
+ overflow bool
+}
+
+func (b *chronyOutput) Write(p []byte) (int, error) {
+ if len(p) > 4096-len(b.data) {
+ b.overflow = true
+ return 0, errors.New("chrony_output_limit")
+ }
+ b.data = append(b.data, p...)
+ return len(p), nil
+}
+
+func readChronyTracking(ctx context.Context, command func(context.Context, string, ...string) *exec.Cmd) (time.Duration, error) {
+ ctx, cancel := context.WithTimeout(ctx, time.Second)
+ defer cancel()
+ cmd := command(ctx, "/usr/bin/chronyc", "-c", "tracking")
+ var out chronyOutput
+ // One writer gives stdout and stderr a shared bounded, serialized buffer.
+ cmd.Stdout = &out
+ cmd.Stderr = &out
+ cmd.WaitDelay = 100 * time.Millisecond
+ if err := cmd.Run(); err != nil {
+ return 0, fmt.Errorf("chronyc tracking failed: %w", err)
+ }
+ if ctx.Err() != nil {
+ return 0, ctx.Err()
+ }
+ if out.overflow {
+ return 0, errors.New("chrony_output_limit")
+ }
+ return parseChronyTracking(string(out.data))
+}
+
+// chrony 4.4 client.c process_cmd_tracking/print_report emits 14 CSV fields.
+// Field 4 is signed system-time correction in seconds; field 13 is leap status.
+func parseChronyTracking(s string) (time.Duration, error) {
+ if len(s) > 4096 {
+ return 0, errors.New("chrony_output_limit")
+ }
+ fields := strings.Split(strings.TrimSpace(s), ",")
+ if len(fields) != 14 || strings.ContainsAny(strings.TrimSpace(s), "\r\n") {
+ return 0, errors.New("chrony_tracking_schema")
+ }
+ ref, err := strconv.ParseUint(fields[0], 16, 32)
+ if err != nil || len(fields[0]) != 8 || ref == 0 || ref == 0x7f7f0101 {
+ return 0, errors.New("chrony_tracking_reference")
+ }
+ stratum, err := strconv.Atoi(fields[2])
+ if err != nil || stratum < 1 || stratum > 15 {
+ return 0, errors.New("chrony_tracking_stratum")
+ }
+ switch fields[13] {
+ case "Normal", "Insert second", "Delete second":
+ default:
+ return 0, errors.New("chrony_tracking_unsynchronized")
+ }
+ values := make([]float64, 13)
+ for i := 3; i < 13; i++ {
+ v, e := strconv.ParseFloat(fields[i], 64)
+ if e != nil || math.IsNaN(v) || math.IsInf(v, 0) {
+ return 0, errors.New("chrony_tracking_number")
+ }
+ values[i] = v
+ }
+ if values[3] <= 0 || math.Abs(values[4]) >= float64(math.MaxInt64)/float64(time.Second) {
+ return 0, errors.New("chrony_tracking_range")
+ }
+ return time.Duration(math.Abs(values[4]) * float64(time.Second)), nil
+}
diff --git a/internal/host/group_metrics_test.go b/internal/host/group_metrics_test.go
new file mode 100644
index 000000000..92b2377b8
--- /dev/null
+++ b/internal/host/group_metrics_test.go
@@ -0,0 +1,229 @@
+package host
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "os"
+ "os/exec"
+ "reflect"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/aws/aws-sdk-go-v2/aws"
+ "github.com/aws/aws-sdk-go-v2/service/cloudwatch/types"
+ "github.com/carlosframework/platform/internal/groupadmission"
+ "github.com/carlosframework/platform/internal/lbhealth"
+)
+
+const chrony44Tracking = "A9FEA97B,169.254.169.123,3,1793745600.000000000,-1.250000000,0.000020000,0.000030000,2.500,0.001,0.010,0.001000000,0.002000000,64.0,Normal\n"
+
+func TestGroupMetricChronyCSV(t *testing.T) {
+ for _, status := range []string{"Normal", "Insert second", "Delete second"} {
+ for _, offset := range []string{"-1.250000000", "1.250000000", "0.000000000"} {
+ s := strings.Replace(strings.Replace(chrony44Tracking, "Normal", status, 1), "-1.250000000", offset, 1)
+ got, err := parseChronyTracking(s)
+ want := 1250 * time.Millisecond
+ if offset == "0.000000000" {
+ want = 0
+ }
+ if err != nil || got != want {
+ t.Fatalf("%q: %v %v", s, got, err)
+ }
+ }
+ }
+ bad := []string{"", "506 Cannot talk to daemon\n", chrony44Tracking + chrony44Tracking, strings.Replace(chrony44Tracking, "Normal", "Not synchronised", 1), strings.Replace(chrony44Tracking, "Normal", "Invalid", 1), strings.Replace(chrony44Tracking, "A9FEA97B", "7F7F0101", 1), strings.Replace(chrony44Tracking, ",3,", ",0,", 1), strings.Replace(chrony44Tracking, ",3,", ",16,", 1), strings.Repeat("x", 4097)}
+ for i := 2; i < 13; i++ {
+ for _, v := range []string{"NaN", "+Inf", "-Inf", "broken"} {
+ f := strings.Split(strings.TrimSpace(chrony44Tracking), ",")
+ f[i] = v
+ bad = append(bad, strings.Join(f, ","))
+ }
+ }
+ for _, s := range bad {
+ if got, err := parseChronyTracking(s); err == nil {
+ t.Errorf("accepted %q: %v", s, got)
+ }
+ }
+}
+
+func TestGroupMetricChronyCommand(t *testing.T) {
+ for _, mode := range []string{"ok", "failure", "large", "timeout", "missing"} {
+ t.Run(mode, func(t *testing.T) {
+ started := time.Now()
+ got, err := readChronyTracking(context.Background(), func(ctx context.Context, path string, args ...string) *exec.Cmd {
+ if path != "/usr/bin/chronyc" || !reflect.DeepEqual(args, []string{"-c", "tracking"}) {
+ t.Fatalf("command %s %v", path, args)
+ }
+ deadline, ok := ctx.Deadline()
+ if !ok || time.Until(deadline) > time.Second {
+ t.Fatal("missing one-second timeout")
+ }
+ if mode == "missing" {
+ return exec.CommandContext(ctx, "/does-not-exist/chronyc")
+ }
+ cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestGroupMetricChronyHelper$")
+ cmd.Env = append(os.Environ(), "TASK4_CHRONY_HELPER="+mode, "GORACE=atexit_sleep_ms=0")
+ cmd.Dir = t.TempDir()
+ return cmd
+ })
+ if mode == "ok" {
+ if err != nil || got != 1250*time.Millisecond {
+ t.Fatalf("%v %v", got, err)
+ }
+ } else if err == nil {
+ t.Fatal("failure fabricated a reading")
+ }
+ if time.Since(started) > 3*time.Second {
+ t.Fatal("command exceeded bound")
+ }
+ })
+ }
+}
+func TestGroupMetricChronyHelper(t *testing.T) {
+ switch os.Getenv("TASK4_CHRONY_HELPER") {
+ case "ok":
+ fmt.Print(chrony44Tracking)
+ case "failure":
+ fmt.Fprint(os.Stderr, "missing socket")
+ os.Exit(1)
+ case "large":
+ fmt.Print(chrony44Tracking + strings.Repeat(" ", 4097))
+ case "timeout":
+ time.Sleep(10 * time.Second)
+ default:
+ return
+ }
+ os.Exit(0)
+}
+
+func TestAdmissionMetricFlagshipUnchanged(t *testing.T) {
+ for _, enabled := range []bool{false, true} {
+ t.Run(fmt.Sprint(enabled), func(t *testing.T) {
+ env := map[string]string{"CARLOS_REGION": "ie", "CARLOS_DEPLOYMENT_BUCKET": "shop-deployment", "CARLOS_REGION_HA": "true"}
+ if enabled {
+ env["CARLOS_GROUP_ADMISSION"] = "1"
+ }
+ get := func(k string) string { return env[k] }
+ admission := newFixedAdmission(get, &lbhealth.State{})
+ calls := 0
+ clockErr := error(nil)
+ logs := 0
+ w := memwatch{put: &fakePutter{}, instanceID: "i-0123", mem: func() (*int64, *int64) { a, b := int64(4000), int64(1000); return &a, &b }, pressure: func() (string, error) { return "some avg60=7.5", nil }, logf: func(string, ...any) { logs++ }}
+ w.admission = admissionMetricsFromEnv(get, admission, func(path, placement string) (roleRegionConfig, error) {
+ if !enabled {
+ t.Fatal("switch-off read region config")
+ }
+ return parseRoleRegionConfig([]byte(`{"v":1,"region_code":"ie","placement":"ie"}`), placement)
+ }, func(context.Context) (time.Duration, error) { calls++; return 1250 * time.Millisecond, clockErr })
+ now := time.Unix(1793745600, 0)
+ for step := 0; step < 3; step++ {
+ if enabled && step == 1 {
+ admission.state.Observe(groupadmission.Facts{EnvLoaded: true, Reconciled: true, RolePublished: true, TerminationStarted: true})
+ if err := admission.state.Admit(context.Background(), nil, nil, func() bool { return true }); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if enabled && step == 2 {
+ admission.state.Close()
+ clockErr = errors.New("clock unavailable")
+ }
+ w.tick(context.Background(), now.Add(time.Duration(step)*time.Minute))
+ in := w.put.(*fakePutter).calls[step]
+ want := memwatchData("i-0123", 25, 7.5, true, now.Add(time.Duration(step)*time.Minute))
+ gotJSON, _ := json.Marshal(in)
+ wantJSON, _ := json.Marshal(want)
+ if !enabled {
+ if string(gotJSON) != string(wantJSON) || calls != 0 {
+ t.Fatalf("switch-off input changed or executed clock: %s / %s calls=%d", gotJSON, wantJSON, calls)
+ }
+ continue
+ }
+ if !reflect.DeepEqual(in.MetricData[:2], want.MetricData) || *in.Namespace != "Carlos/Host" {
+ t.Fatal("legacy series changed")
+ }
+ expectedLen := 4
+ if step == 2 {
+ expectedLen = 3
+ }
+ if len(in.MetricData) != expectedLen {
+ t.Fatalf("data count %d", len(in.MetricData))
+ }
+ for _, d := range in.MetricData[2:] {
+ dims := map[string]string{}
+ for _, v := range d.Dimensions {
+ dims[*v.Name] = *v.Value
+ }
+ if !reflect.DeepEqual(dims, map[string]string{"Deployment": "shop-deployment", "Region": "ie"}) || !d.Timestamp.Equal(*want.MetricData[0].Timestamp) {
+ t.Fatal("regional dimensions or timestamp", d)
+ }
+ switch *d.MetricName {
+ case "Admitted":
+ value := float64(0)
+ if step == 1 {
+ value = 1
+ }
+ if *d.Value != value || d.Unit != types.StandardUnitCount {
+ t.Fatal(d)
+ }
+ case "ClockOffsetSeconds":
+ if *d.Value != 1.25 || d.Unit != types.StandardUnitSeconds {
+ t.Fatal(d)
+ }
+ default:
+ t.Fatal("unexpected metric", d)
+ }
+ }
+ }
+ if enabled && (calls != 3 || logs != 1) {
+ t.Fatalf("calls=%d logs=%d", calls, logs)
+ }
+ })
+ }
+}
+
+func TestAdmissionMetricHomeRegion(t *testing.T) {
+ env := map[string]string{"CARLOS_GROUP_ADMISSION": "1", "CARLOS_DEPLOYMENT_BUCKET": "shop"}
+ m := admissionMetricsFromEnv(func(k string) string { return env[k] }, &fixedAdmission{}, func(path, placement string) (roleRegionConfig, error) {
+ if path != roleRegionConfigPath || placement != "" {
+ t.Fatal(path, placement)
+ }
+ return parseRoleRegionConfig([]byte(`{"v":1,"region_code":"ie","placement":""}`), placement)
+ }, nil)
+ if m == nil || m.region != "ie" {
+ t.Fatal("home metric lost canonical code")
+ }
+}
+
+func TestAdmissionMetricMissingIdentity(t *testing.T) {
+ for _, key := range []string{"CARLOS_REGION", "CARLOS_DEPLOYMENT_BUCKET"} {
+ env := map[string]string{"CARLOS_GROUP_ADMISSION": "1", "CARLOS_REGION": "ie", "CARLOS_DEPLOYMENT_BUCKET": "shop"}
+ delete(env, key)
+ if m := admissionMetricsFromEnv(func(k string) string { return env[k] }, &fixedAdmission{}, func(string, string) (roleRegionConfig, error) {
+ return roleRegionConfig{}, errors.New("missing region config")
+ }, nil); m != nil {
+ t.Fatal("accepted missing identity", key)
+ }
+ }
+}
+
+func TestAdmissionMetricSwitchOffIgnoresState(t *testing.T) {
+ m := admissionMetricsFromEnv(func(string) string { return "" }, &fixedAdmission{}, func(string, string) (roleRegionConfig, error) {
+ t.Fatal("switch-off read config")
+ return roleRegionConfig{}, nil
+ }, nil)
+ if m != nil {
+ t.Fatal("switch-off metrics enabled")
+ }
+}
+
+func TestGroupMetricAWSRegion(t *testing.T) {
+ for _, tc := range []struct{ placement, want string }{{"eu-west-2", "eu-west-2"}, {"", "eu-west-1"}} {
+ got := memwatchAWSConfig(aws.Config{Region: "eu-west-1"}, tc.placement)
+ if got.Region != tc.want {
+ t.Fatalf("metric region=%s want %s", got.Region, tc.want)
+ }
+ }
+}
diff --git a/internal/host/memwatch.go b/internal/host/memwatch.go
index 5172cbb45..9c63c7b97 100644
--- a/internal/host/memwatch.go
+++ b/internal/host/memwatch.go
@@ -6,6 +6,7 @@ import (
"log"
"net/http"
"os"
+ "os/exec"
"strconv"
"strings"
"time"
@@ -55,6 +56,7 @@ func (f putMetricFunc) PutMetricData(ctx context.Context, in *cloudwatch.PutMetr
}
type memwatch struct {
+ admission *admissionMetrics
put metricPutter
instanceID string
mem func() (*int64, *int64) // MemTotal, MemAvailable in bytes
@@ -110,9 +112,7 @@ func memwatchLoop() {
// creates each box's alarm in the box's region, so three alarms would
// have watched an empty namespace forever. IMDS placement wins; "" (not
// on EC2) keeps the chain's answer.
- if r := readPlacementRegion(); r != "" {
- cfg.Region = r
- }
+ cfg = memwatchAWSConfig(cfg, readPlacementRegion())
id, err := imdsInstanceID()
if err != nil {
log.Printf("agent: memwatch disabled: instance id: %v", err)
@@ -125,6 +125,12 @@ func memwatchLoop() {
pressure: readPressureFile,
logf: log.Printf,
}
+ w.admission = admissionMetricsFromEnv(os.Getenv, armedFixedAdmission.Load(), readRoleRegionConfig, func(ctx context.Context) (time.Duration, error) {
+ return readChronyTracking(ctx, exec.CommandContext)
+ })
+ if os.Getenv("CARLOS_GROUP_ADMISSION") == "1" && w.admission == nil {
+ log.Print("memwatch: admission metrics disabled. fixed admission, CARLOS_DEPLOYMENT_BUCKET and a valid region configuration are required")
+ }
log.Printf("agent: memwatch armed (%s in %s, every %s, instance %s)", memwatchNamespace, cfg.Region, memwatchPeriod, id)
for now := range time.Tick(memwatchPeriod) {
w.tick(ctx, now)
@@ -147,7 +153,15 @@ func (w *memwatch) tick(ctx context.Context, now time.Time) {
}
ctx, cancel := context.WithTimeout(ctx, 20*time.Second)
defer cancel()
- _, err := w.put.PutMetricData(ctx, memwatchData(w.instanceID, availPct, psi, hasPSI, now))
+ input := memwatchData(w.instanceID, availPct, psi, hasPSI, now)
+ if w.admission != nil {
+ observation, err := w.admission.observe(ctx, now)
+ if err != nil {
+ w.logf("memwatch: clock reading unavailable for instance %s: %v", w.instanceID, err)
+ }
+ input.MetricData = append(input.MetricData, admissionMetricData(observation)...)
+ }
+ _, err := w.put.PutMetricData(ctx, input)
switch {
case err != nil && err.Error() != w.lastPutErr:
w.lastPutErr = err.Error()
@@ -226,3 +240,10 @@ func parsePressureSome60(s string) (float64, bool) {
}
return 0, false
}
+
+func memwatchAWSConfig(cfg aws.Config, placement string) aws.Config {
+ if placement != "" {
+ cfg.Region = placement
+ }
+ return cfg
+}
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index e3a89e834..0e2148e58 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -75,4 +75,4 @@ plan14-root-reads-domains-check-country.tsv b0fc198c53bb0dacba33a54c3d8bf8fe5ac0
plan14-root-reads-static-stream-extract.tsv 7fb932b118e67e23b33a374c6a4020b38976667c7ec4cfb855c0f8b598b1756b
plan14-root-reads-ls284.tsv 744b16d970f22476b79982e57c326157ca5137fa96ccaee4a7ae10c25248d124
plan14-root-reads-region-ha-p1b3b-t.tsv c68e2453bfc8afaf3794eb4c08850428982fa6954269b6b99bddfda4e6242929
-plan14-root-reads-region-ha-p3a.tsv 9fed85ef7ebc62c2cbed156a2c60c51d07fe6080df4a2604be0246616bbbba05
+plan14-root-reads-region-ha-p3a.tsv 620dcb9b823894efbe91acdf155318d5220a7d81cf404a49c1cc6c05010e1000
diff --git a/internal/provision/testdata/plan14-root-reads-region-ha-p3a.tsv b/internal/provision/testdata/plan14-root-reads-region-ha-p3a.tsv
index 242dd7743..c4417e2cf 100644
--- a/internal/provision/testdata/plan14-root-reads-region-ha-p3a.tsv
+++ b/internal/provision/testdata/plan14-root-reads-region-ha-p3a.tsv
@@ -1,20 +1,23 @@
# Census overlay region-ha-p3a, written by census-propose (#369). census-ruling-region-ha-p3a, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-region-ha-p3a.md.
-# 8 body, 22 sites, 13 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
-# 24 new dispositions: 1 reads re-frozen at their disposition with the claim, 23 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other.
+# 8 body, 22 sites, 14 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+# 28 new dispositions: 1 reads re-frozen at their disposition with the claim, 27 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other.
@legacy 29c11190e0def3cd35cc9d18d9e0c6e1f2c1157d69c054085b77d72d0fe7d63d internal/activator/claimwake.go Service.doClaimWake legacy accepted-legacy accepted-legacy;rev3=J1,J4;basis=route-and-input;rev3=census-ruling-rootfs-apps-3-release;basis=rootfs Plan 3 Group R: a claim wake is refused (errWakeUnproven) while another entry's release record of the host is open, as an unproven failed wake already refuses it; the in-memory map only, no read added; adds a refusal only;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: add/recheck the local start prohibition on generation, worker, sidecar, command or root-control launch, including retained leases; preserve existing lease/ownership checks and fixed-unit exemptions. Whole Route passes to the in-memory predicate; no new filesystem/store read. file:Exec@1133,file:Prepare@2265,file:Read@140,file:Read@932,registry:Host@3329,registry:Host@3399,registry:Host@4520,registry:Host@4597,registry:Host@4723,registry:Host@5336,registry:WakeIncarnation@1464,registry:WakeIncarnation@1592,whole:Route@1466,whole:Route@1594,whole:Route@2363,whole:Route@2474,whole:Route@2529,whole:Route@2535,whole:Route@3542,whole:Route@3600,whole:Route@3606,whole:Route@4640,whole:Route@5600,whole:Route@6220,whole:Route@7584,whole:Route@7672,whole:Route@8344,whole:Route@8352 95a145f4c1985f8c88f37a135fb7ddd09cb4f52a38d9bec62c9acd3357ed1566
@legacy c44d5de2b0e229c3345b70073c526d85470960ea07766fbef0f6f5410501dd90 internal/activator/rootfsworkers.go Service.installRootfsWorkerLocked legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-3-workers;basis=rootfs Plan 3 Group W, W1.11: the one writer of a worker's proc; installs only on the host's own entry, for a worker still the entry's, while the entry is awake and owned (a resident only with its lease watch); refused, the caller stops and proves gone what it started; in-memory;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: add/recheck the local start prohibition on generation, worker, sidecar, command or root-control launch, including retained leases; preserve existing lease/ownership checks and fixed-unit exemptions. Whole Route passes to the in-memory predicate; no new filesystem/store read. whole:Route@263 4796e557b3281e2165ac8cee36361bd88b4faef56f5520e5c83a3c7fd050a535
@legacy db1aa4a54dc343855570c8d5ea22b58ec49fd812127fae04ffc7c6423ae9254f internal/edge/edge.go RunWithActivatorReady legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-certwarm-wake;basis=registers the cert warm's nudge on OnReload and on the home map's new served-hosts wake (#386); nudge only sends on a buffered channel; no read added, same 5 sites;rev3=census-ruling-edge-roll-blip;basis=the :80/:443 (and dev) listeners are bound on the calling goroutine with net.Listen via listen()/listenAddr (same empty-address defaults as ListenAndServe) before the serve goroutines, which now call Serve/ServeTLS on them, and one log line names the bound addresses; no read added, same 5 sites;rev3=census-ruling-edge-held-streams;basis=the edge in the agent (carlos-edge.service, user carlos): the inline home-map arming (newHomeMap, one boot Refresh, Store, run) moves unchanged into the new Edge.ArmHomeMap and is called here as e.ArmHomeMap(); same refresh, same timeout, same order. The reads are moved, none added.;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: invoke the local admission Close before HTTP/HTTPS draining and door shutdown in both dev and normal listeners; existing reads unchanged. data-literal@129,data-literal@148,data-literal@284,data-literal@417,file:Open@1013 58941f6f3c6726de8d9e93562a1b95de0f7f90d43b6a54107958efd95af38d78
@legacy 835af32ac1034a8c2cf1fb9241753c715eeac79cf63b917d7235d70577cd247e internal/host/agent.go fastTick legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=PROPOSED-s3-change-index;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=observes the change index before any pass (observeIndex), runs the backstop's requested full pass and a scoped pass for moved app scopes (indexTick), and arms the canary pointer gate on the sweep (canaryPointerGate) only on a tick whose own index observation succeeded; read site unchanged, offset moved;rev3=census-ruling-stateless-replicas-1;basis=Call coordinator Tick on the existing tick before convergence; client renews held terms only at the pinned interval. Existing registry read unchanged. Final review I3: signal the owned renewal worker instead of waiting for its sequential console HTTP calls. Existing convergence and record read unchanged.;rev3=census-ruling-region-ha-p3a;basis=Run the optional desired-role reader on the existing tick after observing the armed change index; no new root path or timer, nil reader is unchanged. registry:Host@4821 487aa39fc1d1a2bb188ab5b71f0ee4bc0b417c53914f74c2b55867001a2ce528
+@legacy ed545c12fbfa7f30ef3b3708cb737108e2277a342764ed7986134efb03be9e9d infra/modules/region-host/group_alarms.tf external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Add default-off termination queue age alarm, using existing queue name and regional SNS topic; no IAM, queue, consumer or instance changes. file:external@0 c12a3da2781c7a5a10855cf1f194b2b07c562c1d7972926712cf881891c87145
+@legacy 43aa324875ebb70a52a2fea730d568f553c78de97a269abde7f642f9e66d6f90 infra/modules/region-host/ingress/alarms.tf external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Add per-TG NLB alarms and optional deployment/region clock and admission alarms, notify only; no compute actions or fixed identifiers. file:external@0 a4da64aa4ccbe2ffc0618ffe7e1e6d4ca5ee616b056a938a94c9eb3041bcffbb
@legacy 377eb01304b9a5473fcef2354ef85dd2ba95785c48ff2ba1a0782778499989ef infra/modules/region-host/ingress/main.tf external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Add isolated IPv4 NLB, VPC/zone lookups, validated CIDR egress, protected new EIPs and TCP health-checked target groups; no fixed-resource edits or root runtime reads. file:external@0 103369ef62af3311ee0e01e751e23a03ca3634015841f0a9437ee7e682353d37
@legacy c1636b10d14fd359d718264048fe782d0405dde3102b72a1a8eac270c37b14f6 infra/modules/region-host/ingress/outputs.tf external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Expose per-zone addresses and NLB/TG identities for root attachments and Task 4 alarms; no root runtime reads. file:external@0 83d036fd1e80e375df647bfbb84eb9307faa97ad5511672c938a164919f246a9
-@legacy 7a49227972307af74b52e450dc5ea86547395d41192f24792c71ca21db3b474d infra/modules/region-host/ingress/tests/fixed-targets/main.tf external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Add dev-root fixture attaching literal instance IDs to both target groups with read-only AZ lookups and target-zone precondition; no fixed-module references or root runtime reads. file:external@0 98e19cac1a98259ba7f3c1e9ab95471e25afa2ae77c54bd4c575a2e094fac62e
+@legacy a0c56a1f402cb74566bc12578e4c705cb1ef290ccbf9eeb1fa732c6c1f3f661b infra/modules/region-host/ingress/tests/fixed-targets/main.tf external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Add dev-root fixture attaching literal instance IDs to both target groups with read-only AZ lookups and target-zone precondition; no fixed-module references or root runtime reads. Task 4 supplies expected target count from literal fixed targets to ingress alarms; no resource ownership or root runtime read changes. file:external@0 1a3c35d700ec33e1cd9ac101f5b99da365a0fbd1698b8d34b48d4338b3229d6c
@legacy b113d1b975dae34ecf57a2b5c98e94c8d6f89fd7476e321202c25886b866cb08 infra/modules/region-host/ingress/tests/fixed-targets/tests/targets.tftest.hcl external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Add plan-only mock witnesses for target attachments and out-of-zone refusal; no live API calls or root runtime reads. file:external@0 9fc255e828aaff0d55d156caa417e40fcf3afb8d9ef29b025f4178ca669799fb
@legacy 5d72b4a4f0a34f5cc4ef70092940738197fb5c1aa4ec382127cabdd9c82702bc infra/modules/region-host/ingress/tests/fixed-targets/variables.tf external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Define explicit ingress and literal target inputs for the dev-root fixture; no root runtime reads. file:external@0 644a067756d767c5668463eca9c1e4a45af902aacf140ef9cca437f3a24efde4
@legacy 5f2c8be4b3fe6775f9542426e5c729a4b16115dafa420b0e63040f71bd80f685 infra/modules/region-host/ingress/tests/fixed-targets/versions.tf external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Declare OpenTofu/AWS provider requirements for the dev-root fixture; no root runtime reads. file:external@0 bb3be812da255c0f031b2bfdfee462e4687de3681c742b529b55693a8875136b
-@legacy 32d1441eaf910683f882c5fa9399470814b595490b6c5bb2ef3a51dfbb62796c infra/modules/region-host/ingress/tests/group_ingress.tftest.hcl external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Add plan-only mock tests for NLB protocol, health, zone/VPC boundary, protected allocations and restricted SG traffic; remove the duplicate empty-subnet-result test in Task 1 fix round 1; no live API calls or root runtime reads. file:external@0 36665eefee5d2a298571fa56f805159eb0dab79d3bd3b0913b5bbcc07a50d42c
-@legacy 0c7e79156fc210a3460e9cbce1a7e26edbf22f0c799710f3e82e1a09a483d994 infra/modules/region-host/ingress/variables.tf external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Add ingress-only inputs and topology/CIDR validation; no root runtime reads. file:external@0 a1599da50d212d5e64f527719ee781e5a0a494185d144f0a958433741f4c9d36
+@legacy cdc76197c0736576e7f41d571bdde637f7fd334182b437b5a73d041fdbb12ad2 infra/modules/region-host/ingress/tests/group_ingress.tftest.hcl external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Add plan-only mock tests for NLB protocol, health, zone/VPC boundary, protected allocations and restricted SG traffic; remove the duplicate empty-subnet-result test in Task 1 fix round 1; no live API calls or root runtime reads. Task 4 adds plan-only mock alarm threshold, dimension, period, missing-data, disabled-default and same-region SNS checks; no live API calls. file:external@0 895a286d46ead0a3486b78de1701388a38e24a0ce4d44b8485aac142004ec64b
+@legacy b7110691bf293fec26644bcda1a5412aa9c7f82f580613413047540a275a9ef8 infra/modules/region-host/ingress/variables.tf external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Add ingress-only inputs and topology/CIDR validation; no root runtime reads. Task 4 adds explicit expected target count, optional same-region SNS topic and opt-in regional metrics identity; no fixed-resource changes or root reads. file:external@0 8c008825c6997c48b6ca140c4bb8304ceb6612b5921531a2160535539433cb8b
@legacy 134888d1b095e8268cdd1cd04df27087407ae3fee1c4742f0df5a431520783ef infra/modules/region-host/ingress/versions.tf external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Declare OpenTofu and AWS provider requirements for the isolated ingress child; no root runtime reads. file:external@0 bb3be812da255c0f031b2bfdfee462e4687de3681c742b529b55693a8875136b
@legacy 73e967bb630a74f28c53f50b63c997d086154b025cf7b59074d5b0fe2fc3bea7 infra/modules/region-host/tests/fixed_state_unchanged.tftest.hcl external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Add mock regression for the unchanged fixed instance/profile/SG/root-volume wiring and legacy outputs; no root runtime reads. file:external@0 cab0fdd9e01c4497f06a617db6c41aa9887da80bd0518c76fe8eba935be42c85
+@legacy ce2188fc0ee3585d1b85be8de0f0fb5361014b044a6670eabcd709efce7875a4 infra/modules/region-host/tests/group_alarms.tftest.hcl external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Add plan-only mock queue alarm defaults, thresholds, missing-data and regional notification assertions. file:external@0 eddcb3a71104bde85c057fd6eaa3cdc2dc50edc6f43888278dd5df9b3f2c2c96
@legacy 5ed7ecf3d8cf70162ef33f84279181fd154fe979076098038075e995d2630f01 internal/activator/group_admission.go ExecBackend.admissionBefore legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: share the in-memory admission/effective-role predicate with HTTP, service and backend checks; whole Route is used only for fixed-route classification. Refuse without acquire, restore or launch; no new filesystem/store read. whole:Route@280 53d4373724699dd3102f5b61e542d495f7798aa0bdf1da17699bc8400924285b
@legacy 9796f1fef0eb132eb7d0a7da2ce2a29ae4af8f3c94b6674181d09779364b14cf internal/activator/group_admission.go ExecBackend.admissionContext legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: share the in-memory admission/effective-role predicate with HTTP, service and backend checks; whole Route is used only for fixed-route classification. Refuse without acquire, restore or launch; no new filesystem/store read. whole:Route@223 e5b7b347c9ed9bdfd24b1ad8dea56ac6866080c3475d2c741eb54aeecf272ac9
@legacy e6cfa41642aa3a6c8328ac6517f764febb796d8fb43d3c92c4823130bc58693c internal/activator/group_admission.go ExecBackend.tenantStartRefusal legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: share the in-memory admission/effective-role predicate with HTTP, service and backend checks; whole Route is used only for fixed-route classification. Refuse without acquire, restore or launch; no new filesystem/store read. whole:Route@125 e4980c77d0c2e0c3cf7ca6814ed824e759325bdc3315fa81d31c98a5f65afabf
@@ -28,6 +31,7 @@
@legacy 70fe3feea98b7decfa8bb26bbe5d0b2ca2865aaa69a6158b4699efbf49cde66e internal/host/group_admission.go fixedAdmission.TenantAdmissionExempt legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: classify the existing Route Platform, Unit and Backing fields for the fixed-box exemption; unsupported group mode has no exemption. Does not grant any new lease or root start authority. whole:Route@89 e336ed9f48649c8c54a0eb112ff6e7ec3e4bc995e56a4abe9fb7cfe20f12d7a0
@legacy df2f3828c1db19783e73885782415db68888aeecbfccfe74ad32bddbc4dcbeca internal/host/group_admission.go fixedAdmission.bind legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: share the in-memory admission/effective-role predicate with HTTP, service and backend checks; whole Route is used only for fixed-route classification. Refuse without acquire, restore or launch; no new filesystem/store read. whole:Route@319 5ced62d5a15dc2d0230e4ee1d2765fb7adb8b8ae4a4f3a7a3425419f8dca564f
@legacy 27f21e714af11f592202e1d3d47d9ba1722fd227215a6444585f45e3649c5cf0 internal/host/group_admission.go fixedAdmission.exempt legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: classify the existing Route Platform, Unit and Backing fields for the fixed-box exemption; unsupported group mode has no exemption. Does not grant any new lease or root start authority. registry:Backing@111,registry:Platform@79,registry:Unit@94 1ff6546ebcea7c167b0819d478059b4d1e57a401a85f10bbf08cf9583e998abc
+@legacy 55d3531e0ee6ec6ba52f67445464830b683d13e853e91517c09404e13558b06d internal/host/memwatch.go memwatchLoop legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=On opted-in fixed boxes only, reuse Task 2 root-owned region-config reader and Task 3 state; on existing cadence execute absolute /usr/bin/chronyc with fixed -c tracking args, one-second context and bounded 4096-byte output. No shell, tenant-named path or new timer; switch-off reads no region config and executes no clock command. file:CommandContext@1677 fb6985996ca1c86c060605534b55a54e60b3b8f8ccacee935ae7467e36aa9ae1
@legacy da0c89025968a59a96910fe56c0f85883ee761a25b0f85e3967c03d19bee2d81 internal/activator/backend_exec.go ExecBackend.nestedReady legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-2;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=root-route (J1, as nestedGate): new (rootfs Plan 2 Task 9): nestedGate's box half, split out unchanged so rootfsGates asks it too: the control channel is configured and NestedOK passes; its two sites are the row's host in the error text; no file, no root decision;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: add/recheck the local start prohibition on generation, worker, sidecar, command or root-control launch, including retained leases; preserve existing lease/ownership checks and fixed-unit exemptions. Whole Route passes to the in-memory predicate; no new filesystem/store read. registry:Host@217,registry:Host@362,whole:Route@93 db559b77443fa7532803e9c83547482e979ebf2813706b6e9661ba7af6fa7080
@legacy b79589fbb7c726d68d4fbf285a83a77562c420af19df0dd348398215eb010681 internal/activator/activator.go Service.WakeWorker legacy accepted-legacy accepted-legacy;rev3=census-ruling-carlos-run;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): main's body; the stop now carries its reason for a run it interrupts (beginStopLocked's why argument); read sites unchanged, offsets moved;rev3=census-ruling-remote-instance-metrics;basis=the entries-map insertion goes through putEntryLocked (which also notes the route's tenant in memory for the metrics sampler); no read added;rev3=census-ruling-stateless-replicas-1;basis=Task 3a: Read serving lease health through servingError: stateless generations use local lifecycle/process supervision, while stateful generations keep the existing lease checks. No new I/O.;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: check local tenant admission and start permission before lease/restore, preserving already-awake reuse during drain and existing serialization. Whole Route passes to the local predicate; no new filesystem or store read. registry:Host@1428,registry:Host@1837,registry:Host@923,registry:Host@953,whole:Route@1012,whole:Route@108,whole:Route@1404 e35358e75b7a0af7f2f382d28328e3373a48b06cdc876dbd8649db9b3c00741a
@legacy 2d778c3a380a638e5ca85a9cdfb9bae01bc23829a43266d04a8d27cad2587ee9 internal/activator/activator.go Service.begin legacy accepted-legacy accepted-legacy;rev3=census-ruling-carlos-run;basis=Re-digested at the pre-land merge: the body includes main's own change under census ruling 292, with no further change from this branch. the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): main's body; the stop now carries its reason for a run it interrupts (beginStopLocked's why argument); read sites unchanged, offsets moved;rev3=census-ruling-edge-request-records;basis=gains a req *http.Request parameter and one edge.MarkWoke(req) call on the path that starts a wake, so the edge's request record can say which request woke the app; no read added;rev3=census-ruling-remote-instance-metrics;basis=the entries-map insertion goes through putEntryLocked (which also notes the route's tenant in memory for the metrics sampler); no read added;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Tasks 7 and 8: before an entry is made, a resident inside its backoff answers errResidentBackoff, and a rootfs row must pass the locked admission (rootfsRefusalLocked) and then the backend's rootfs gates off a.mu (rootfsStartRefusal, within the request's wait bound) before Acquire, Restore or the live link; the gate key is recorded on the entry; adds refusals before the lease only;rev3=census-ruling-stateless-replicas-1;basis=Task 3a: Read serving lease health through servingError: stateless generations use local lifecycle/process supervision, while stateful generations keep the existing lease checks. No new I/O.;rev3=census-ruling-region-ha-p1b3b-t;basis=Carry background-duty provenance into a new singleflight entry; a visitor waiting on its deferred refusal retries with ordinary visitor authority. No read added.;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: check local tenant admission and start permission before lease/restore, preserving already-awake reuse during drain and existing serialization. Whole Route passes to the local predicate; no new filesystem or store read. registry:Host@1240,registry:Host@1780,registry:Host@3836,registry:Host@3993,registry:Host@656,whole:Route@1302,whole:Route@1413,whole:Route@177,whole:Route@2334,whole:Route@2421,whole:Route@2502,whole:Route@2763,whole:Route@2873,whole:Route@3047,whole:Route@3845,whole:Route@3852 61c8318ab572a96775c0f1b11d602dd8f9115230d0f1c99e7e3da19c2e61005c
@@ -54,16 +58,19 @@ internal/edge/edge.go RunWithActivatorReady legacy accepted-legacy accepted-lega
internal/host/agent.go fastTick legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=PROPOSED-s3-change-index;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=observes the change index before any pass (observeIndex), runs the backstop's requested full pass and a scoped pass for moved app scopes (indexTick), and arms the canary pointer gate on the sweep (canaryPointerGate) only on a tick whose own index observation succeeded; read site unchanged, offset moved;rev3=census-ruling-stateless-replicas-1;basis=Call coordinator Tick on the existing tick before convergence; client renews held terms only at the pinned interval. Existing registry read unchanged. Final review I3: signal the owned renewal worker instead of waiting for its sequential console HTTP calls. Existing convergence and record read unchanged.;rev3=census-ruling-region-ha-p3a;basis=Run the optional desired-role reader on the existing tick after observing the armed change index; no new root path or timer, nil reader is unchanged. registry:Host@4821 487aa39fc1d1a2bb188ab5b71f0ee4bc0b417c53914f74c2b55867001a2ce528
internal/host/agent.go runAgent authority B,C,D,F rev3=census-ruling-self-serve-moves-1;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): builds the box's lifetime judge once (newBoxJudge, nil with host claims on) and hands it to the seed placement, the moves and runs workers and every loop it starts; read sites unchanged, offsets moved; B,C,D,F authority retained; self-serve moves 1 Task 8: derives the box's lifetimes switch from the judge once (lifetimes := boxJudge != nil) and hands it to the edges file loop; read sites unchanged, offsets moved;rev3=census-ruling-plans-4d-lapse;basis=arms two more plans hooks from the same snapshot: e.SetPlanDisabledFor(planDisabledFor) beside SetPlanGovernedFor, and svc.SetDisabledFor(planDisabledRoute) beside SetMaxRunFor (plans 4d); the reads live in those units (plans-4d-units decision); read sites unchanged, offsets moved;rev3=census-ruling-rootfs-apps-2;basis=main's body as of the merge of origin/main 9b81d97b (with main's plan rate ceiling, edge request records, regional box names, self-serve moves plan 1, plans 4d-1 lapse and its other later changes under main's own census rulings) plus the rootfs placement wiring in the activator start: an agentRootfs built from eb.NestedOK, CARLOS_DEPLOYMENT_SINGLE_TENANT, CARLOS_POOLS, the claim flag, swapArming's answer, the control client's /ready/rootfs and, on a fleet box whose identity resolved, fleetOwnerCheck over the deploy store main already opens for the fleet label (fleetStore), then arm and armedRootfs.Store; this body reads nothing new itself; the closures it wires read later, at a rootfs wake and each status tick: GET /ready/rootfs over the control socket, NestedOK's checks, and release.FleetOwnerKey for the judged row's own account and this box's fleet from the deploy store;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328 plan 2 Tasks 7 and 11, #329 plan 3 Task 7 and plan 1 Task 7's policy cache: the control client is built once and handed to eb.Control, to the status tick (egressStatus) and to a new egressNudgeLoop goroutine; armSizeSource(svc, "/sys/fs/cgroup") after the activator Service; armPolicyCache() after armChangeIndex; statusLoop takes egressStatus. The reads are those units' own (decision rows); this body reads nothing new: the same five sites, offsets moved, in the agent; B,C,D,F authority retained.;rev3=census-ruling-remote-instance-metrics;basis=builds the metrics loop's owners closure (metricsOwners over the agent's registry, the activator and cgm.Leftover) when an activator exists and hands it to metricsLoop; reads nothing new itself;rev3=census-ruling-edge-asset-cache-3;basis=adds file:Statfs. runAgent keeps its authority (B,C,D,F). The new site is assetcache.Statfs, an exported assetcache.FS interface value (var Statfs FS = statfsFS{}), not a function value and not a call in runAgent: the ready hook passes it to armEdgeAssetCache as the store's filesystem, and armEdgeAssetCache calls its Space method on the configured data directory (dataDir(): $CARLOS_DATA_DIR, else /data), which calls unix.Statfs there (statfsFS.Space, accepted legacy at census-ruling-edge-asset-cache-2). No request-supplied pathname reaches it.;rev3=census-ruling-remote-metrics-nested;basis=main's body (merged origin/main acfa4f80, under main's own census rulings) plus: snapshots the nested layout (snapshotNestedUnits over /sys/fs/cgroup/carlos.slice/carlos-instances.slice) once at start, before the activator, and hands the metrics loop a unitSources struct (stamped units, routeHostNames, that root and the snapshot); reads nothing new itself;rev3=census-ruling-region-ha-p1a;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): wires region HA P1a into the activator: cfg.Record = haRecordFacts(openDeployStore, boxJudge) (the box's lifetime judge this body already builds with newBoxJudge, nil with host claims on; CI fix) and cfg.Self = lease.CurrentSelf; eb.Lifetimes (the process's lifetime index), eb.Registry, eb.StartupSwept (seedSweptAtStart.Load), eb.FilesStore from newProductionFilesStore (now lease.NewFilesStore, rootaws-loaded, a log line on failure) and lease.SetObligationDir(<data>/.ha-owed) (logged on failure; HA acquires then refuse); this body reads nothing new itself, the same five sites; the reads are those units' own (haRecordFacts and lease's SetObligationDir are new rows on this card); merge of origin/main d7ae1d76: main's own later changes to this body are kept as main has them, under main's rulings (census-ruling-remote-instance-metrics: the metricsOwners closure for metricsLoop; census-ruling-edge-asset-cache-3: the +file:Statfs site, assetcache.Statfs handed to the asset ready hook); this branch's change is the same as above;rev3=census-ruling-region-ha-p1b1;basis=region HA P1b-1: builds one termfence.Confirmer (Self from lease.CurrentSelf at each call, EC2 DescribeInstances method only, client from rootaws.LoadDefaultConfig with retries off, built lazily on first use) and sets eb.OwnerTerminated; this body reads nothing new itself, the same six sites;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Task 7: the startup Sweep literal hands its answer to startupSwept, which logs as before and, only on a clean sweep, marks rootfs admission swept (MarkRootfsSwept); same Sweep call, no read added;rev3=census-ruling-managed-fleets-1b;basis=managed fleets 1b (controller ruling after branch review R1, and Paul's R2 ruling): sets svc.Fleet = fleetWakeFor(os.Getenv, identity, identErr, fleetStore) from the identity it already resolves once and the deployment store the fleet loops already opened, and logs an ERROR naming the identity error when the box is on a fleet with an invalid identity. fleetWakeFor reads CARLOS_REGION and CARLOS_FLEET from the same environment. Read sites unchanged (6). Agent, not root; a platform box is unchanged.;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 12: one call more beside armRunsPass, armInteractivePass(svc, reg, rolloutSink, boxJudge), in the same activator Configure hook, handing it the same box judge; fix round 1 (Astra P2, shutdown): after svc.Shutdown(ctx), shutdownInteractive(ctx) ends and joins every interactive session under the same shutdown budget; the worker's own reads are its units' (interactive.go); this body reads nothing new, the same six sites; merge of origin/main 6f1f6ca6: main's svc.Fleet = fleetWakeFor(...) and its invalid-identity ERROR line are kept as main has them (census-ruling-managed-fleets-1b); this branch's change is the same as above; read sites unchanged (6);rev3=census-ruling-fix-set-aside-exdev;basis=set-aside EXDEV fix: one field more on the agent ExecBackend literal, RawInstanceDir: layout.RawInstanceDir (a pure path join: <dataDir>/.instances/<InstanceID(host)>), so the start rule set-aside moves a copy out through the raw directory instead of through the nosymfollow bind; this body reads nothing new, the same six sites;rev3=census-ruling-durability-3a-escrow;basis=durability 3a Task 3: one more assignment beside eb.FilesStore: eb.EscrowKey = haEscrowKey(os.Getenv("CARLOS_SECRETS_KEY")), the agent's own environment parsed by appconfig.ParsePrivateKey as the moves pass parses it (unset or unparseable: a log line and nil, and HA publication refuses on the box). No path is opened or read, no read site added; the same six sites, offsets moved; B,C,D,F authority retained. Durability 3a Task 4: one more goroutine beside configSyncLoop: go escrowLoop(agentCtx, reg, svc), the escrow sweep every 30 s over the same registry and Service. This body reads nothing new itself; the same six sites, offsets moved; B,C,D,F authority retained. Durability 3a Task 5: one more call beside eb.EscrowKey: wireRawSecretPages(eb, PageOperator, metricsBoxLabel(os.Getenv, readMachineID())), which sets eb.OnRawSecret to page an operator (alerting.Page through PageOperator, LevelIncident) on its own goroutine with a 20 s timeout; metricsBoxLabel and readMachineID are the reads this body already makes for the moves refusal log; no new read site; the same six sites, offsets moved; B,C,D,F authority retained. Merge of origin/main 90c4d3aa: main's own later changes to this body are kept as main has them, under main's rulings; this branch's change is the same as above. Merge of origin/main 00bf5b8c (fleet set-aside EXDEV fix): main's change to this body is kept as main has it, under its own census ruling; this branch's change is unchanged.;rev3=census-ruling-probe-burst-limit;basis=two more sink wirings beside setAnalyticsSink: setProtectionSink(e.SetProtectionRecordOnly) and setAssetOwnersSource(e.AssetOwners), function values the telemetry pass calls; this body reads nothing new, the same six sites; authority B,C,D,F retained; no new root read or write kind;rev3=census-ruling-region-ha-p1b3a;basis=Arm HA placement exactly once on the existing Service before activatorStart and edges publication, wiring AwakeApps and the PageOperator callback; existing six read sites unchanged, no new root authority.;rev3=census-ruling-stateless-replicas-1;basis=Final review I3: start the concrete coordinator's renewal worker with agent setup; existing closeReplicaCoordinator shutdown cancels and joins it before release. No new read sites or credentials. Merge origin/main c59715e7: retain main's armHAPlacement(svc, PageOperator) wiring beside the existing activator setup; stateless coordinator and shutdown wiring remain. Same read sites; no new root read or credential.;rev3=census-ruling-edge-held-streams;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): in the edge-ready callback, calls act.SetHeldWakeHook(e.HeldWake) when act is non-nil (installing the non-blocking wake callback) and stores e.HeldStreamsForStatus in heldStreamsSource. Wiring of in-memory callbacks only; no read added.;rev3=census-ruling-region-ha-p1b3b-t;basis=Wire Service.SetDutyView to the live edge DutySnapshot in the ready callback. No new read; no new loop or cloud operation. B2 wires the registry as the persistent DutyStore before service startup; no new cloud or filesystem path. B3b: arm one journal-backed termination consumer before service startup using agentCtx and the shared confirmer; expose edge tick and join at edge shutdown. No new direct read sites.;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: install closed fixed admission before every launch source, bind activator/backend and edge, wire the real termination Started lifecycle and role reader after the change index; close before cancellation/child shutdown. Existing reads unchanged; no new cloud authority. file:Exec@18090,file:Open@1452,file:Statfs@46926,registry:App@11845,whole:Route@11837,whole:Route@30186 3d4c4e82597c801b95d940e911e020edba8d8a973ca2cae7b14a108efebcd34a
internal/host/edgesfile.go edgesFileWriteClaims authority F,J1 rev3=census-ruling-self-serve-moves-1;basis=root-route;kept=F;scope=protected-decision-only; the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): region-ha-2a's body, which with the box's lifetimes switch on also publishes each served row's lifetime pair (registry:Incarnation and registry:ServingSeq, two new sites on the rows it already lists) and an alias's or served catch-all's primary's pair, and names that primary as target_host whatever the switch; a report the edge orders unstamped entries by, not a decision; no record, /data, release or claim read added; F,J1 authority retained; self-serve moves 1 Task 8;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328 plan 2 Task 8: takes a localAddrs reader (instancectl.LocalAddresses in production, which reads /proc/net/fib_trie and /proc/net/if_inet6 in the agent) and publishes its non-loopback entries as the edges file's addrs before the write gate (boxAddrs, no read of its own), so an address change writes once. The same 44 sites, offsets moved; no record, /data, release or claim read added; a report the console's egress grant check reads, not a root decision; F,J1 authority retained.;rev3=census-ruling-edge-asset-cache-3;basis=starts with assets = assets.active(), so a policy whose box has not opened its asset store publishes no assets blocks and reads no manifests, and copies the decision's Primary (the route host the block was decided for, drift D4) into the published assets block; read sites unchanged (44); no read added. Merged onto main's #328 body, which takes the localAddrs reader: the assets.active() line sits after that signature and the loop passes pub and instancectl.LocalAddresses;rev3=census-ruling-region-ha-p1a;basis=the agent as carlos: the claims argument (*edgesClaims) becomes addrs (AddressSource) and the applyEdgesClaims(ctx, claims, routes, hosts) call is deleted with edgesclaims.go, which is the one whole:Route site removed: no host claim is read and every served row publishes as with region HA off; the box-address publication is the same code reading addrs.BoxAddresses() instead of claims.addrs; a report the edge reads, not a root decision; no read added; merge of origin/main d7ae1d76: main's edge asset cache plan 3 body is kept (census-ruling-edge-asset-cache-3): the first line is assets = assets.active(), so a policy whose store has not opened publishes no assets blocks and reads no manifests, and edgesFileLoop passes pub (assets.active() for that tick) in the assets argument; main's claims *edgesClaims argument is this branch's addrs AddressSource, and no edgesClaims, applyEdgesClaims or hostclaim reference remains;rev3=census-ruling-alias-wake-338;basis=#338 follow-up: skips publishing a platform alias edge.PlatformAliasFold refuses (and so anything attached to it); reads the same route listing;rev3=census-ruling-fleet-public-routes;basis=fleet public routes (spec 2026-10-29 rev 4, §4.2 writer rule): Task 6 and its fix rounds: publishes by FleetArmVerdict (via fleetRefusedFor): withheld rows left out; a forward host's path rows left out of its owner; no assets for forward rows; the alias loop replays Reload's alias fold from the served rows so a chained alias carries its root primary's owner; certRefused and parentRefused leave out a refused claim's wildcard parent (+registry:Alias x5, +registry:Host x4, +whole:Route, +whole:RouteAlias x2, +whole:RoutePath x7, +whole:WildcardDomain). Rows already read in the pass; keeps authority F,J1; publishes less, never more.;rev3=census-ruling-probe-burst-limit;basis=sets the constant BurstNotices=true on the box's own edges file (this build's edge answers probe-burst notices, so peers may send them); not from config or any read; the same 65 sites; a report other edges read, not a root decision; F,J1 authority retained; no new root read or write kind;rev3=census-ruling-region-ha-p3a;basis=Publish one injected role snapshot; preserve the real-route bit separately from wildcard/platform class during booting withdrawal; acknowledge the exact published role/admitted/drained tuple only after PUT; existing registry reads unchanged. registry:Account@15753,registry:Alias@10256,registry:Alias@13226,registry:Alias@13276,registry:Alias@8683,registry:Alias@8702,registry:Alias@8801,registry:Alias@8855,registry:Alias@8890,registry:Alias@8952,registry:Alias@9322,registry:Alias@9479,registry:Alias@9549,registry:Alias@9581,registry:App@15765,registry:DNSStatus@8997,registry:DNSStatus@9488,registry:Host@13129,registry:Host@13149,registry:Host@13414,registry:Host@13494,registry:Host@13529,registry:Host@13578,registry:Host@14040,registry:Host@14075,registry:Host@15183,registry:Host@3889,registry:Host@3935,registry:Host@3994,registry:Host@5109,registry:Host@6079,registry:Host@8728,registry:Host@8776,registry:Incarnation@5069,registry:Platform@4848,registry:Provisioned@4862,registry:Replica@4886,registry:ServingSeq@5084,registry:Status@2677,whole:Route@1026,whole:Route@17223,whole:Route@18041,whole:Route@18216,whole:Route@1841,whole:Route@2047,whole:Route@6164,whole:Route@750,whole:RouteAlias@13180,whole:RouteAlias@17245,whole:RouteAlias@18231,whole:RouteAlias@8566,whole:RouteAlias@8648,whole:RouteAlias@8840,whole:RoutePath@17238,whole:RoutePath@18224,whole:RoutePath@5948,whole:RoutePath@5980,whole:RoutePath@6027,whole:RoutePath@6055,whole:RoutePath@6093,whole:RoutePath@6113,whole:RoutePath@6125,whole:RoutePath@6179,whole:WildcardDomain@13107,whole:WildcardDomain@13483 623de89af2adc399601b13eb4f6a529f45f8e13def4230beb7995d19d72dfe9c
+infra/modules/region-host/group_alarms.tf external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Add default-off termination queue age alarm, using existing queue name and regional SNS topic; no IAM, queue, consumer or instance changes. file:external@0 c12a3da2781c7a5a10855cf1f194b2b07c562c1d7972926712cf881891c87145
+infra/modules/region-host/ingress/alarms.tf external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Add per-TG NLB alarms and optional deployment/region clock and admission alarms, notify only; no compute actions or fixed identifiers. file:external@0 a4da64aa4ccbe2ffc0618ffe7e1e6d4ca5ee616b056a938a94c9eb3041bcffbb
infra/modules/region-host/ingress/main.tf external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Add isolated IPv4 NLB, VPC/zone lookups, validated CIDR egress, protected new EIPs and TCP health-checked target groups; no fixed-resource edits or root runtime reads. file:external@0 103369ef62af3311ee0e01e751e23a03ca3634015841f0a9437ee7e682353d37
infra/modules/region-host/ingress/outputs.tf external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Expose per-zone addresses and NLB/TG identities for root attachments and Task 4 alarms; no root runtime reads. file:external@0 83d036fd1e80e375df647bfbb84eb9307faa97ad5511672c938a164919f246a9
-infra/modules/region-host/ingress/tests/fixed-targets/main.tf external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Add dev-root fixture attaching literal instance IDs to both target groups with read-only AZ lookups and target-zone precondition; no fixed-module references or root runtime reads. file:external@0 98e19cac1a98259ba7f3c1e9ab95471e25afa2ae77c54bd4c575a2e094fac62e
+infra/modules/region-host/ingress/tests/fixed-targets/main.tf external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Add dev-root fixture attaching literal instance IDs to both target groups with read-only AZ lookups and target-zone precondition; no fixed-module references or root runtime reads. Task 4 supplies expected target count from literal fixed targets to ingress alarms; no resource ownership or root runtime read changes. file:external@0 1a3c35d700ec33e1cd9ac101f5b99da365a0fbd1698b8d34b48d4338b3229d6c
infra/modules/region-host/ingress/tests/fixed-targets/tests/targets.tftest.hcl external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Add plan-only mock witnesses for target attachments and out-of-zone refusal; no live API calls or root runtime reads. file:external@0 9fc255e828aaff0d55d156caa417e40fcf3afb8d9ef29b025f4178ca669799fb
infra/modules/region-host/ingress/tests/fixed-targets/variables.tf external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Define explicit ingress and literal target inputs for the dev-root fixture; no root runtime reads. file:external@0 644a067756d767c5668463eca9c1e4a45af902aacf140ef9cca437f3a24efde4
infra/modules/region-host/ingress/tests/fixed-targets/versions.tf external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Declare OpenTofu/AWS provider requirements for the dev-root fixture; no root runtime reads. file:external@0 bb3be812da255c0f031b2bfdfee462e4687de3681c742b529b55693a8875136b
-infra/modules/region-host/ingress/tests/group_ingress.tftest.hcl external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Add plan-only mock tests for NLB protocol, health, zone/VPC boundary, protected allocations and restricted SG traffic; remove the duplicate empty-subnet-result test in Task 1 fix round 1; no live API calls or root runtime reads. file:external@0 36665eefee5d2a298571fa56f805159eb0dab79d3bd3b0913b5bbcc07a50d42c
-infra/modules/region-host/ingress/variables.tf external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Add ingress-only inputs and topology/CIDR validation; no root runtime reads. file:external@0 a1599da50d212d5e64f527719ee781e5a0a494185d144f0a958433741f4c9d36
+infra/modules/region-host/ingress/tests/group_ingress.tftest.hcl external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Add plan-only mock tests for NLB protocol, health, zone/VPC boundary, protected allocations and restricted SG traffic; remove the duplicate empty-subnet-result test in Task 1 fix round 1; no live API calls or root runtime reads. Task 4 adds plan-only mock alarm threshold, dimension, period, missing-data, disabled-default and same-region SNS checks; no live API calls. file:external@0 895a286d46ead0a3486b78de1701388a38e24a0ce4d44b8485aac142004ec64b
+infra/modules/region-host/ingress/variables.tf external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Add ingress-only inputs and topology/CIDR validation; no root runtime reads. Task 4 adds explicit expected target count, optional same-region SNS topic and opt-in regional metrics identity; no fixed-resource changes or root reads. file:external@0 8c008825c6997c48b6ca140c4bb8304ceb6612b5921531a2160535539433cb8b
infra/modules/region-host/ingress/versions.tf external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Declare OpenTofu and AWS provider requirements for the isolated ingress child; no root runtime reads. file:external@0 bb3be812da255c0f031b2bfdfee462e4687de3681c742b529b55693a8875136b
infra/modules/region-host/tests/fixed_state_unchanged.tftest.hcl external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Add mock regression for the unchanged fixed instance/profile/SG/root-volume wiring and legacy outputs; no root runtime reads. file:external@0 cab0fdd9e01c4497f06a617db6c41aa9887da80bd0518c76fe8eba935be42c85
+infra/modules/region-host/tests/group_alarms.tftest.hcl external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Add plan-only mock queue alarm defaults, thresholds, missing-data and regional notification assertions. file:external@0 eddcb3a71104bde85c057fd6eaa3cdc2dc50edc6f43888278dd5df9b3f2c2c96
internal/activator/group_admission.go ExecBackend.admissionBefore legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: share the in-memory admission/effective-role predicate with HTTP, service and backend checks; whole Route is used only for fixed-route classification. Refuse without acquire, restore or launch; no new filesystem/store read. whole:Route@280 53d4373724699dd3102f5b61e542d495f7798aa0bdf1da17699bc8400924285b
internal/activator/group_admission.go ExecBackend.admissionContext legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: share the in-memory admission/effective-role predicate with HTTP, service and backend checks; whole Route is used only for fixed-route classification. Refuse without acquire, restore or launch; no new filesystem/store read. whole:Route@223 e5b7b347c9ed9bdfd24b1ad8dea56ac6866080c3475d2c741eb54aeecf272ac9
internal/activator/group_admission.go ExecBackend.tenantStartRefusal legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: share the in-memory admission/effective-role predicate with HTTP, service and backend checks; whole Route is used only for fixed-route classification. Refuse without acquire, restore or launch; no new filesystem/store read. whole:Route@125 e4980c77d0c2e0c3cf7ca6814ed824e759325bdc3315fa81d31c98a5f65afabf
@@ -77,6 +84,7 @@ internal/host/boxroles_config_linux.go readRoleRegionConfig legacy accepted-lega
internal/host/group_admission.go fixedAdmission.TenantAdmissionExempt legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: classify the existing Route Platform, Unit and Backing fields for the fixed-box exemption; unsupported group mode has no exemption. Does not grant any new lease or root start authority. whole:Route@89 e336ed9f48649c8c54a0eb112ff6e7ec3e4bc995e56a4abe9fb7cfe20f12d7a0
internal/host/group_admission.go fixedAdmission.bind legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: share the in-memory admission/effective-role predicate with HTTP, service and backend checks; whole Route is used only for fixed-route classification. Refuse without acquire, restore or launch; no new filesystem/store read. whole:Route@319 5ced62d5a15dc2d0230e4ee1d2765fb7adb8b8ae4a4f3a7a3425419f8dca564f
internal/host/group_admission.go fixedAdmission.exempt legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: classify the existing Route Platform, Unit and Backing fields for the fixed-box exemption; unsupported group mode has no exemption. Does not grant any new lease or root start authority. registry:Backing@111,registry:Platform@79,registry:Unit@94 1ff6546ebcea7c167b0819d478059b4d1e57a401a85f10bbf08cf9583e998abc
+internal/host/memwatch.go memwatchLoop legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=On opted-in fixed boxes only, reuse Task 2 root-owned region-config reader and Task 3 state; on existing cadence execute absolute /usr/bin/chronyc with fixed -c tracking args, one-second context and bounded 4096-byte output. No shell, tenant-named path or new timer; switch-off reads no region config and executes no clock command. file:CommandContext@1677 fb6985996ca1c86c060605534b55a54e60b3b8f8ccacee935ae7467e36aa9ae1
internal/activator/backend_exec.go ExecBackend.nestedReady legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-2;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=root-route (J1, as nestedGate): new (rootfs Plan 2 Task 9): nestedGate's box half, split out unchanged so rootfsGates asks it too: the control channel is configured and NestedOK passes; its two sites are the row's host in the error text; no file, no root decision;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: add/recheck the local start prohibition on generation, worker, sidecar, command or root-control launch, including retained leases; preserve existing lease/ownership checks and fixed-unit exemptions. Whole Route passes to the in-memory predicate; no new filesystem/store read. registry:Host@217,registry:Host@362,whole:Route@93 db559b77443fa7532803e9c83547482e979ebf2813706b6e9661ba7af6fa7080
internal/activator/activator.go Service.WakeWorker legacy accepted-legacy accepted-legacy;rev3=census-ruling-carlos-run;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): main's body; the stop now carries its reason for a run it interrupts (beginStopLocked's why argument); read sites unchanged, offsets moved;rev3=census-ruling-remote-instance-metrics;basis=the entries-map insertion goes through putEntryLocked (which also notes the route's tenant in memory for the metrics sampler); no read added;rev3=census-ruling-stateless-replicas-1;basis=Task 3a: Read serving lease health through servingError: stateless generations use local lifecycle/process supervision, while stateful generations keep the existing lease checks. No new I/O.;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: check local tenant admission and start permission before lease/restore, preserving already-awake reuse during drain and existing serialization. Whole Route passes to the local predicate; no new filesystem or store read. registry:Host@1428,registry:Host@1837,registry:Host@923,registry:Host@953,whole:Route@1012,whole:Route@108,whole:Route@1404 e35358e75b7a0af7f2f382d28328e3373a48b06cdc876dbd8649db9b3c00741a
internal/activator/activator.go Service.begin legacy accepted-legacy accepted-legacy;rev3=census-ruling-carlos-run;basis=Re-digested at the pre-land merge: the body includes main's own change under census ruling 292, with no further change from this branch. the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): main's body; the stop now carries its reason for a run it interrupts (beginStopLocked's why argument); read sites unchanged, offsets moved;rev3=census-ruling-edge-request-records;basis=gains a req *http.Request parameter and one edge.MarkWoke(req) call on the path that starts a wake, so the edge's request record can say which request woke the app; no read added;rev3=census-ruling-remote-instance-metrics;basis=the entries-map insertion goes through putEntryLocked (which also notes the route's tenant in memory for the metrics sampler); no read added;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Tasks 7 and 8: before an entry is made, a resident inside its backoff answers errResidentBackoff, and a rootfs row must pass the locked admission (rootfsRefusalLocked) and then the backend's rootfs gates off a.mu (rootfsStartRefusal, within the request's wait bound) before Acquire, Restore or the live link; the gate key is recorded on the entry; adds refusals before the lease only;rev3=census-ruling-stateless-replicas-1;basis=Task 3a: Read serving lease health through servingError: stateless generations use local lifecycle/process supervision, while stateful generations keep the existing lease checks. No new I/O.;rev3=census-ruling-region-ha-p1b3b-t;basis=Carry background-duty provenance into a new singleflight entry; a visitor waiting on its deferred refusal retries with ordinary visitor authority. No read added.;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: check local tenant admission and start permission before lease/restore, preserving already-awake reuse during drain and existing serialization. Whole Route passes to the local predicate; no new filesystem or store read. registry:Host@1240,registry:Host@1780,registry:Host@3836,registry:Host@3993,registry:Host@656,whole:Route@1302,whole:Route@1413,whole:Route@177,whole:Route@2334,whole:Route@2421,whole:Route@2502,whole:Route@2763,whole:Route@2873,whole:Route@3047,whole:Route@3845,whole:Route@3852 61c8318ab572a96775c0f1b11d602dd8f9115230d0f1c99e7e3da19c2e61005c
@@ -100,16 +108,17 @@ internal/activator/genservice.go Service.startGenExe legacy accepted-legacy acce
internal/activator/hawake.go ExecBackend.haSpawnGate legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1a;basis=new: before every spawn of a host this backend acquired HA, re-runs haContained and refuses an uncontained row; a non-HA host passes; +registry:Host, +whole:Route; only refuses;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: add/recheck the local start prohibition on generation, worker, sidecar, command or root-control launch, including retained leases; preserve existing lease/ownership checks and fixed-unit exemptions. Whole Route passes to the in-memory predicate; no new filesystem/store read. registry:Host@153,whole:Route@210,whole:Route@93 71c81e3c5168d1a2a0fc56144828676efe2673ac52415b787e0ab3e8bf18959b
internal/activator/workerbuild.go Service.startWorker authority E2 E39: close the unsupported claimed worker path before backend entry, replacement or supervised stop. Claims-off paths remain unchanged. This is refusal coverage, not positive root-reserved worker launch support. Fixtures: TestPlan14GenerationWorkerStartBoundary, TestPlan14GenerationWorkerRealBackendRefusal, TestPlan14GenerationWorkerReplacementBoundary, TestPlan14GenerationWorkerSupervisionBoundary. Pre-flight 29 and E39 worker launch audit.;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: add/recheck the local start prohibition on generation, worker, sidecar, command or root-control launch, including retained leases; preserve existing lease/ownership checks and fixed-unit exemptions. Whole Route passes to the in-memory predicate; no new filesystem/store read. registry:Host@1301,registry:Host@1479,registry:Host@2414,whole:Route@1031,whole:Route@233,whole:Route@2520 efa454a478f289a6f63432802e63d313ba2c1f4298aae6cfb46c666e99b47654
internal/edge/edge.go Edge.ServeHTTP legacy accepted-legacy accepted-legacy;rev3=census-ruling-seeded-instances;basis=the edge inside the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): main's body with the import gate checked after the door's scope and a gated row left out of the response cache; serving only;rev3=census-ruling-edge-request-records;basis=one more call in the observer defer, observeRecords(up.route, ...), passing on the route the defer already holds; no new kind of read;rev3=census-ruling-design-edge-rate-limit-358;basis=calls rateAdmit twice, and an admitted request holds a slot on both paths: on the upgrade path before the activator or proxy (the handshake holds its slot through slotWriter, given back at the first final answer or at the reverse proxy's hijack on a 101, so an open WebSocket is not counted; released by a defer), and on the ordinary path after the response-cache check and before the activator and proxy (an admitted request holds a slot through slotWriter, released by a defer); a refusal is a 429 written there and returns; the upgrade path's comment now names slotWriter as its one wrapper; one comment on the door mark reworded; read sites unchanged (22: main's 21 plus edge-request-records' observeRecords pass of the route), offsets moved; no read added;rev3=census-ruling-plans-4c-box-throttle;basis=calls planThrottleAdmit before the response cache, and on an upgrade trackUpgrade then planUpgradeAdmit (plans 4c, Astra findings 1 and 2); the new reads live in those units (plans-4c-units decision). The same read sites here.;rev3=census-ruling-plans-4d-lapse;basis=calls planDisabledAdmit right after the import gate, passing the final upstream's route and the request host; a turned-off route gets the fixed disabled page before the meter, gate, cache and activator (plans 4d). The new read lives in that unit (plans-4d-units decision); one more whole-row pass here.;rev3=census-ruling-edge-protection-2;basis=runs the guard, a pure in-memory matcher on r.URL.Path and RawQuery (internal/edgeguard), once per request after the meter and observer defer and before the password gate, the upgrade branch, the cache and the activator, for a request that is not a door call, a backhauled door hop or a tunnel delivery; a matched block answers a 404 itself through guardDecide; the two new sites are one expression, up.route.Kind == "static" (a static route this box serves checks only the hard tier here and leaves the probe tier to serveTree), a read of the route row the edge already resolved; no new kind of read;rev3=census-ruling-edge-asset-cache-3;basis=the asset cache's three hooks (asset cache plan 3): the request's reserved asset headers are deleted at entry (the fill assertion kept only beside a verified hop); on the exact-remote and lookup-miss branches the far catch (serveAssetFar) is tried before backhaulTo and backhaul; after the observer defer and main's hard and probe checks, a verified hop with a valid fill assertion is answered by serveAssetFillForHop; after the upgrade branch and before gzip and the shared cache, the local catch (serveAssetLocal); the observer defer skips only the usage meter for an acknowledged home fill (out.unbilled); the new reads live in the new units of the edge-asset-cache-3-decisions overlay; the same route row and read sites (25); no read added;rev3=census-ruling-regional-domains-447;basis=#447 Task 5: straight after lookupUpstreamPath it calls regionalGate (regional.go), which for an entry built from a regional_domains row answers 503 to a hop or a deny entry before any arm that can leave the box (the exact-home backhaul, the far asset catch, the door dial, the miss backhaul), and lets a star match through only to the exact-home arm when ExactHome names another box for that distinct exact name; after the exact-home arm a regional deny entry the arm did not answer is refused (regionalRefuse, 503); refusals only, on the route map the edge already holds; read sites unchanged (25);rev3=census-ruling-static-headers;basis=the shared response cache is no longer looked up or filled for a static-kind route: one more read of the route row the edge already resolved (up.route.Kind == "static") in the cacheable expression; a refusal only, nothing new opened or followed;rev3=census-ruling-region-ha-p1b2;basis=region HA P1b-2 (N-HA10): one call, frontForwardHA, right after the route lookup's !ok block and before the login POST; same reads;rev3=census-ruling-fleet-public-routes;basis=fleet public routes (spec 2026-10-29 rev 4, §4.2 writer rule): Task 4: loginPost and cacheable treat a forward row as not this box's to answer (IsForward(), +whole:Route x2): no login form and no shared cache for a forward host. Serving only.;rev3=census-ruling-tunnel-websockets;basis=Deletes the Carlos-Upgrade marker header from incoming requests and puts the upgrade admission (host, path, the entry tenancy, all in hand) on a tunnel arm request. For a login POST on an ungated ArmTunnel row it reads the visitor request body (bounded by gate.MaxFormBody, 413 past it; a request body, not a file) and resolves next against the entry Reload built (Gate, Route); the bytes pass on only when loginPassesThrough holds (spec 7, Tasks 3, 5 and 6).;rev3=census-ruling-console-protection-tab;basis=one more call in the observer defer, observeGuardCount(up.route, out), beside the observeRecords call that files the guard Match: it passes on the route row the defer already holds (+whole:Route) and the request outcome to the usage meter, which counts the check in memory. Called whether or not the request was unbilled, as observeRecords is. Nothing is opened, read or followed; no new kind of read; no check, refusal or serving decision changes.;rev3=census-ruling-probe-burst-limit;basis=answers a probe-burst notice POST (serveBurstNotice) ahead of every route for a non-door caller; builds the guard state for up.route and stamps its account and app (RouteAccount, App) for the cool-down's this-app/other-app label; for a catalogue match on a non-static or tunnelled route, offers the burst rule (in-memory limiter, burstDecide: 429 or a watch verdict, never a block for a fleet or forward row); the observer defer calls noteBurst(up.route, ...); the added sites are the route value already in hand (+registry:App, +whole:Route x5); no new root read or write kind;rev3=census-ruling-edge-held-streams;basis=the edge in the agent (carlos-edge.service, user carlos): parses the request's query once (stripHoldMarker) to record the carlos_hold=1 mark in the request context; calls classifyHold on the upstream already resolved from the loaded map (the +whole:Route is that in-memory Route), including a second pass for a login POST; gives a marked request on a door-refused route the plain 404; adds the hold branch (planThrottleAdmit, rateAdmit, serveHeld) after the gate; and excludes marked requests from the shared cache. Reads only the request and the already-loaded upstream map; no registry or bucket read added.;rev3=census-ruling-region-ha-p3a;basis=Refuse a reserved exact hostname with no serving peer before a local or remote catch-all can handle it; one snapshot supplies the reservation and dial decision; no new read or forwarding authority. P3a Task 3: refuse a managed tenant before forwarding, geo/proof preparation and dispatch; recheck the route after login next-path resolution. Only the fixed platform/unit scope is exempt. Whole Route passes to a local permission check, not a new store/path read. file:ReadAll@15378,registry:App@21535,registry:Gate@14352,registry:Gate@25926,registry:Gate@25986,registry:Gate@26044,registry:Host@26029,registry:ImportGate@33429,registry:Kind@20397,registry:Kind@23835,registry:Kind@33371,registry:Kind@33400,whole:Route@14247,whole:Route@14358,whole:Route@17175,whole:Route@17959,whole:Route@18417,whole:Route@18609,whole:Route@20400,whole:Route@21461,whole:Route@21527,whole:Route@21538,whole:Route@21791,whole:Route@21886,whole:Route@21962,whole:Route@22006,whole:Route@22308,whole:Route@22338,whole:Route@23838,whole:Route@24123,whole:Route@25929,whole:Route@25989,whole:Route@26032,whole:Route@26047,whole:Route@26965,whole:Route@29028,whole:Route@33374,whole:Route@33403,whole:Route@33432,whole:Route@33464,whole:Route@35312,whole:Route@5267 9b1df28b2df18736fbfdbe25eacba988dc08c7c54f78b944f4ad7f4a4ce25bfb
-@coverage infra/modules/region-host/ingress 009777ca5464e8e6e0bfda45c00229b8924e0dc55f39d7d3036bca2b2d4f871e
-@coverage infra/modules/region-host/ingress/tests b6467c0277af3f8f58a86f9d7bb703907d44bd5216c66c97acf9e3c8c031b416
-@coverage infra/modules/region-host/ingress/tests/fixed-targets f99d9d22e9ad6820b3fcc4e5210dad538a62274005c6fdd7c4a3af292aef91cc
+@coverage infra/modules/region-host 2067bf570fe0f96da8f95c8706b80106cd22e56c2d3514394b9654aee45ad9ae
+@coverage infra/modules/region-host/ingress 6d8e6673392f649d0bdf24f24015295bb6bec0792b5f331a438b678bd36d73c2
+@coverage infra/modules/region-host/ingress/tests d914e0542c1868917e85f986e49459a10907994b3d6d5a46cb510fc35dea8301
+@coverage infra/modules/region-host/ingress/tests/fixed-targets 66fb331d8b8eb1ba67672cacb40229c6bf575bd04a33561274582beccff24c33
@coverage infra/modules/region-host/ingress/tests/fixed-targets/tests 567e4b97ac15cea31cb88aba77dccf739e58382158dba13d6b03e22935995b52
-@coverage infra/modules/region-host/tests 18abb8044924e7422d67f4266905e6da7d024426cd7846868fca55932adbb9ae
+@coverage infra/modules/region-host/tests e3b4f8199f84822455ff1624e4ba739d9aa7b4933c3fc2cb79f657ec43c21082
@coverage internal/activator 7ad287a6d6bd3a4a2e1bce9b84ac1bb6e85dae96d9f8a79ec9b4dda186a27264
@coverage internal/boxroles b8804945a8da39c3f4d1778dc977ee1a071a6c8489ace1c5a22c92b5acb85d91
@coverage internal/edge 40ff67a76c8f93dd23e69ddd76a5d5f1f0a759da73949b33daeaa75bee923250
@coverage internal/edgesfile 79ccfee3606279650719114b126a16cef92707b148d8c941e1100e21115f7283
-@coverage internal/groupadmission 6c86ef4dd91e44cec07db730c532bd975a977c0cfb27368ef61aa70e5add6b34
-@coverage internal/host 74d57191440fc9f135c2a04c6b19b6602c4305a29fa4159bf9da224a1d023f4a
+@coverage internal/groupadmission ee9dc16e43abbeca1e81cc1029f0d53fc81be13e3e36120c88b06bb3f3d73c78
+@coverage internal/host 75a9b7b6eac2a08c1617d1b64801daa863cdb63fe4972b10b7207947940959cd
@coverage internal/hostenv d9df92980cd7f97c31ad7334ee552e7f6378fdb310d8a1ca0d0d0cda983db81e
@coverage internal/release 95051eb07c6f91bdda535e8b8b45154a97c0f6869e92c32572e7f84c32677af4
diff --git a/scripts/check_region_group_plan_test.py b/scripts/check_region_group_plan_test.py
index 3efa157d3..526d204a8 100644
--- a/scripts/check_region_group_plan_test.py
+++ b/scripts/check_region_group_plan_test.py
@@ -162,6 +162,17 @@ class GateTests(unittest.TestCase):
self.assertEqual(expected, result.returncode, result.stdout + result.stderr)
return result
+ def test_regional_alarm_fixture(self):
+ document = self.fixture('regional-alarms.json')
+ self.gate(document, 0)
+ alarms = document['resource_changes']
+ self.assertEqual(6, len(alarms))
+ for row in alarms:
+ self.assertNotIn('InstanceId', row['change']['after']['dimensions'])
+ # The same create carrying a fixed InstanceId must still be refused.
+ alarms[0]['change']['after']['dimensions']['InstanceId'] = 'i-fixed'
+ self.gate(document, 1)
+
def test_saved_plan_fixtures(self):
for name, expected in [('new-ingress.json', 0), ('targeted-fixed-user-data.json', 1),
('unchanged-move.json', 0), ('fixed-eip-reassociation.json', 1)]:
diff --git a/scripts/group_alarm_plan_test.py b/scripts/group_alarm_plan_test.py
new file mode 100644
index 000000000..b71aebb40
--- /dev/null
+++ b/scripts/group_alarm_plan_test.py
@@ -0,0 +1,72 @@
+"""Check alarm windows from `tofu test -json -verbose` mock-plan events.
+
+Pass the ingress and parent module event files as arguments. This checks
+complete minute buckets; it does not emulate CloudWatch's extra-data lookback.
+"""
+import json
+from pathlib import Path
+import sys
+
+
+def alarm_at(alarm, samples, now):
+ period = alarm['period']
+ needed = alarm['datapoints_to_alarm']
+ breaching = 0
+ for ago in range(alarm['evaluation_periods']):
+ values = samples.get(now - ago * period)
+ if values is None:
+ breach = alarm['treat_missing_data'] == 'breaching'
+ else:
+ value = {'Maximum': max, 'Minimum': min}[alarm['statistic']](values)
+ if alarm['comparison_operator'] == 'GreaterThanThreshold':
+ breach = value > alarm['threshold']
+ else:
+ assert alarm['comparison_operator'] == 'LessThanThreshold'
+ breach = value < alarm['threshold']
+ breaching += breach
+ return breaching >= needed
+
+
+def check_alarm(alarm):
+ assert alarm['period'] == 60
+ n = alarm['evaluation_periods']
+ assert alarm['datapoints_to_alarm'] == n
+ good = alarm['threshold'] # Equality must not breach either strict comparison.
+ bad = good + (1 if alarm['comparison_operator'] == 'GreaterThanThreshold' else -1)
+ now = 1800000000
+ samples = {now - i * 60: [good] for i in range(n)}
+ assert not alarm_at(alarm, samples, now), 'threshold equality breached'
+ for minute in range(1, n + 1):
+ now += 60
+ samples[now] = [good, bad] # Maximum/Minimum must include the worst box.
+ assert alarm_at(alarm, samples, now) == (minute == n), 'wrong alarm window'
+ now += 60
+ samples[now] = [good]
+ assert not alarm_at(alarm, samples, now), 'recovery did not clear the N/N window'
+ assert alarm_at(alarm, {}, now) == (alarm['treat_missing_data'] == 'breaching'), 'wrong missing-data state'
+
+
+def main(paths):
+ seen = set()
+ for path in paths:
+ for line in Path(path).read_text().splitlines():
+ event = json.loads(line)
+ if event.get('@testrun') not in {'group_alarm_contract', 'termination_alarm_contract'}:
+ continue
+ plan = event.get('test_plan')
+ if plan is None:
+ continue
+ for resource in plan['planned_values']['root_module']['resources']:
+ if resource['type'] != 'aws_cloudwatch_metric_alarm':
+ continue
+ alarm = resource['values']
+ if alarm['metric_name'] not in {'UnHealthyHostCount', 'HealthyHostCount', 'ClockOffsetSeconds', 'Admitted', 'ApproximateAgeOfOldestMessage'}:
+ continue
+ check_alarm(alarm)
+ seen.add((event['@testrun'], resource['address']))
+ print(resource['address'] + ': threshold, recovery, worst sample and missing data passed')
+ assert len(seen) == 7, f'expected seven P3a alarm resources, checked {len(seen)}'
+
+
+if __name__ == '__main__':
+ main(sys.argv[1:])
diff --git a/scripts/testdata/region-group-plan/regional-alarms.json b/scripts/testdata/region-group-plan/regional-alarms.json
new file mode 100644
index 000000000..d51a58e24
--- /dev/null
+++ b/scripts/testdata/region-group-plan/regional-alarms.json
@@ -0,0 +1,477 @@
+{
+ "format_version": "1.2",
+ "resource_changes": [
+ {
+ "address": "module.dev_ingress.aws_cloudwatch_metric_alarm.admitted[0]",
+ "mode": "managed",
+ "type": "aws_cloudwatch_metric_alarm",
+ "name": "admitted",
+ "index": 0,
+ "provider_name": "registry.opentofu.org/hashicorp/aws",
+ "change": {
+ "actions": [
+ "create"
+ ],
+ "before": null,
+ "after": {
+ "actions_enabled": null,
+ "alarm_actions": [
+ "arn:aws:sns:eu-west-1:123456789012:shop-alerts"
+ ],
+ "alarm_description": "A box has not been admitted for one minute, or admission readings are missing. Check the box startup diagnostics.",
+ "alarm_name": "shop-probe-admission",
+ "arn": "4v8aqy8ZV",
+ "comparison_operator": "LessThanThreshold",
+ "datapoints_to_alarm": 1,
+ "dimensions": {
+ "Deployment": "shop-deployment",
+ "Region": "ie"
+ },
+ "evaluate_low_sample_count_percentiles": "ftpmcCTESL",
+ "evaluation_criteria": [],
+ "evaluation_interval": null,
+ "evaluation_periods": 1,
+ "extended_statistic": null,
+ "id": "rww11J47ygB",
+ "insufficient_data_actions": null,
+ "metric_name": "Admitted",
+ "metric_query": [],
+ "namespace": "Carlos/Host",
+ "ok_actions": [
+ "arn:aws:sns:eu-west-1:123456789012:shop-alerts"
+ ],
+ "period": 60,
+ "region": "4M6nOqZL",
+ "statistic": "Minimum",
+ "tags": null,
+ "tags_all": {},
+ "threshold": 1,
+ "threshold_metric_id": null,
+ "treat_missing_data": "breaching",
+ "unit": null,
+ "warm_up_configuration": []
+ },
+ "after_unknown": {},
+ "before_sensitive": false,
+ "after_sensitive": {
+ "alarm_actions": [
+ false
+ ],
+ "dimensions": {},
+ "evaluation_criteria": [],
+ "metric_query": [],
+ "ok_actions": [
+ false
+ ],
+ "tags_all": {},
+ "warm_up_configuration": []
+ }
+ }
+ },
+ {
+ "address": "module.dev_ingress.aws_cloudwatch_metric_alarm.clock[0]",
+ "mode": "managed",
+ "type": "aws_cloudwatch_metric_alarm",
+ "name": "clock",
+ "index": 0,
+ "provider_name": "registry.opentofu.org/hashicorp/aws",
+ "change": {
+ "actions": [
+ "create"
+ ],
+ "before": null,
+ "after": {
+ "actions_enabled": null,
+ "alarm_actions": [
+ "arn:aws:sns:eu-west-1:123456789012:shop-alerts"
+ ],
+ "alarm_description": "A box clock is more than one second off for one minute, or its reading is missing. Lease safety depends on accurate clocks.",
+ "alarm_name": "shop-probe-clock",
+ "arn": "4v8aqy8ZV",
+ "comparison_operator": "GreaterThanThreshold",
+ "datapoints_to_alarm": 1,
+ "dimensions": {
+ "Deployment": "shop-deployment",
+ "Region": "ie"
+ },
+ "evaluate_low_sample_count_percentiles": "ftpmcCTESL",
+ "evaluation_criteria": [],
+ "evaluation_interval": null,
+ "evaluation_periods": 1,
+ "extended_statistic": null,
+ "id": "rww11J47ygB",
+ "insufficient_data_actions": null,
+ "metric_name": "ClockOffsetSeconds",
+ "metric_query": [],
+ "namespace": "Carlos/Host",
+ "ok_actions": [
+ "arn:aws:sns:eu-west-1:123456789012:shop-alerts"
+ ],
+ "period": 60,
+ "region": "4M6nOqZL",
+ "statistic": "Maximum",
+ "tags": null,
+ "tags_all": {},
+ "threshold": 1,
+ "threshold_metric_id": null,
+ "treat_missing_data": "breaching",
+ "unit": null,
+ "warm_up_configuration": []
+ },
+ "after_unknown": {},
+ "before_sensitive": false,
+ "after_sensitive": {
+ "alarm_actions": [
+ false
+ ],
+ "dimensions": {},
+ "evaluation_criteria": [],
+ "metric_query": [],
+ "ok_actions": [
+ false
+ ],
+ "tags_all": {},
+ "warm_up_configuration": []
+ }
+ }
+ },
+ {
+ "address": "module.dev_ingress.aws_cloudwatch_metric_alarm.healthy[\"443\"]",
+ "mode": "managed",
+ "type": "aws_cloudwatch_metric_alarm",
+ "name": "healthy",
+ "index": "443",
+ "provider_name": "registry.opentofu.org/hashicorp/aws",
+ "change": {
+ "actions": [
+ "create"
+ ],
+ "before": null,
+ "after": {
+ "actions_enabled": null,
+ "alarm_actions": [
+ "arn:aws:sns:eu-west-1:123456789012:shop-alerts"
+ ],
+ "alarm_description": "Fewer load balancer targets are healthy than there are boxes for 25 minutes. Investigate the unhealthy boxes and the load balancer path.",
+ "alarm_name": "shop-probe-443-healthy",
+ "arn": "4v8aqy8ZV",
+ "comparison_operator": "LessThanThreshold",
+ "datapoints_to_alarm": 25,
+ "dimensions": {
+ "LoadBalancer": "net/shop-probe/0123456789abcdef",
+ "TargetGroup": "targetgroup/shop-probe/0123456789abcdef"
+ },
+ "evaluate_low_sample_count_percentiles": "ftpmcCTESL",
+ "evaluation_criteria": [],
+ "evaluation_interval": null,
+ "evaluation_periods": 25,
+ "extended_statistic": null,
+ "id": "rww11J47ygB",
+ "insufficient_data_actions": null,
+ "metric_name": "HealthyHostCount",
+ "metric_query": [],
+ "namespace": "AWS/NetworkELB",
+ "ok_actions": [
+ "arn:aws:sns:eu-west-1:123456789012:shop-alerts"
+ ],
+ "period": 60,
+ "region": "4M6nOqZL",
+ "statistic": "Minimum",
+ "tags": null,
+ "tags_all": {},
+ "threshold": 2,
+ "threshold_metric_id": null,
+ "treat_missing_data": "breaching",
+ "unit": null,
+ "warm_up_configuration": []
+ },
+ "after_unknown": {},
+ "before_sensitive": false,
+ "after_sensitive": {
+ "alarm_actions": [
+ false
+ ],
+ "dimensions": {},
+ "evaluation_criteria": [],
+ "metric_query": [],
+ "ok_actions": [
+ false
+ ],
+ "tags_all": {},
+ "warm_up_configuration": []
+ }
+ }
+ },
+ {
+ "address": "module.dev_ingress.aws_cloudwatch_metric_alarm.healthy[\"80\"]",
+ "mode": "managed",
+ "type": "aws_cloudwatch_metric_alarm",
+ "name": "healthy",
+ "index": "80",
+ "provider_name": "registry.opentofu.org/hashicorp/aws",
+ "change": {
+ "actions": [
+ "create"
+ ],
+ "before": null,
+ "after": {
+ "actions_enabled": null,
+ "alarm_actions": [
+ "arn:aws:sns:eu-west-1:123456789012:shop-alerts"
+ ],
+ "alarm_description": "Fewer load balancer targets are healthy than there are boxes for 25 minutes. Investigate the unhealthy boxes and the load balancer path.",
+ "alarm_name": "shop-probe-80-healthy",
+ "arn": "4v8aqy8ZV",
+ "comparison_operator": "LessThanThreshold",
+ "datapoints_to_alarm": 25,
+ "dimensions": {
+ "LoadBalancer": "net/shop-probe/0123456789abcdef",
+ "TargetGroup": "targetgroup/shop-probe/0123456789abcdef"
+ },
+ "evaluate_low_sample_count_percentiles": "ftpmcCTESL",
+ "evaluation_criteria": [],
+ "evaluation_interval": null,
+ "evaluation_periods": 25,
+ "extended_statistic": null,
+ "id": "rww11J47ygB",
+ "insufficient_data_actions": null,
+ "metric_name": "HealthyHostCount",
+ "metric_query": [],
+ "namespace": "AWS/NetworkELB",
+ "ok_actions": [
+ "arn:aws:sns:eu-west-1:123456789012:shop-alerts"
+ ],
+ "period": 60,
+ "region": "4M6nOqZL",
+ "statistic": "Minimum",
+ "tags": null,
+ "tags_all": {},
+ "threshold": 2,
+ "threshold_metric_id": null,
+ "treat_missing_data": "breaching",
+ "unit": null,
+ "warm_up_configuration": []
+ },
+ "after_unknown": {},
+ "before_sensitive": false,
+ "after_sensitive": {
+ "alarm_actions": [
+ false
+ ],
+ "dimensions": {},
+ "evaluation_criteria": [],
+ "metric_query": [],
+ "ok_actions": [
+ false
+ ],
+ "tags_all": {},
+ "warm_up_configuration": []
+ }
+ }
+ },
+ {
+ "address": "module.dev_ingress.aws_cloudwatch_metric_alarm.unhealthy[\"443\"]",
+ "mode": "managed",
+ "type": "aws_cloudwatch_metric_alarm",
+ "name": "unhealthy",
+ "index": "443",
+ "provider_name": "registry.opentofu.org/hashicorp/aws",
+ "change": {
+ "actions": [
+ "create"
+ ],
+ "before": null,
+ "after": {
+ "actions_enabled": null,
+ "alarm_actions": [
+ "arn:aws:sns:eu-west-1:123456789012:shop-alerts"
+ ],
+ "alarm_description": "A load balancer target has been unhealthy for 10 minutes. Starting boxes and boxes not admitted yet return 503 by design. Investigate a box that remains in this state.",
+ "alarm_name": "shop-probe-443-unhealthy",
+ "arn": "4v8aqy8ZV",
+ "comparison_operator": "GreaterThanThreshold",
+ "datapoints_to_alarm": 10,
+ "dimensions": {
+ "LoadBalancer": "net/shop-probe/0123456789abcdef",
+ "TargetGroup": "targetgroup/shop-probe/0123456789abcdef"
+ },
+ "evaluate_low_sample_count_percentiles": "ftpmcCTESL",
+ "evaluation_criteria": [],
+ "evaluation_interval": null,
+ "evaluation_periods": 10,
+ "extended_statistic": null,
+ "id": "rww11J47ygB",
+ "insufficient_data_actions": null,
+ "metric_name": "UnHealthyHostCount",
+ "metric_query": [],
+ "namespace": "AWS/NetworkELB",
+ "ok_actions": [
+ "arn:aws:sns:eu-west-1:123456789012:shop-alerts"
+ ],
+ "period": 60,
+ "region": "4M6nOqZL",
+ "statistic": "Maximum",
+ "tags": null,
+ "tags_all": {},
+ "threshold": 0,
+ "threshold_metric_id": null,
+ "treat_missing_data": "breaching",
+ "unit": null,
+ "warm_up_configuration": []
+ },
+ "after_unknown": {},
+ "before_sensitive": false,
+ "after_sensitive": {
+ "alarm_actions": [
+ false
+ ],
+ "dimensions": {},
+ "evaluation_criteria": [],
+ "metric_query": [],
+ "ok_actions": [
+ false
+ ],
+ "tags_all": {},
+ "warm_up_configuration": []
+ }
+ }
+ },
+ {
+ "address": "module.dev_ingress.aws_cloudwatch_metric_alarm.unhealthy[\"80\"]",
+ "mode": "managed",
+ "type": "aws_cloudwatch_metric_alarm",
+ "name": "unhealthy",
+ "index": "80",
+ "provider_name": "registry.opentofu.org/hashicorp/aws",
+ "change": {
+ "actions": [
+ "create"
+ ],
+ "before": null,
+ "after": {
+ "actions_enabled": null,
+ "alarm_actions": [
+ "arn:aws:sns:eu-west-1:123456789012:shop-alerts"
+ ],
+ "alarm_description": "A load balancer target has been unhealthy for 10 minutes. Starting boxes and boxes not admitted yet return 503 by design. Investigate a box that remains in this state.",
+ "alarm_name": "shop-probe-80-unhealthy",
+ "arn": "4v8aqy8ZV",
+ "comparison_operator": "GreaterThanThreshold",
+ "datapoints_to_alarm": 10,
+ "dimensions": {
+ "LoadBalancer": "net/shop-probe/0123456789abcdef",
+ "TargetGroup": "targetgroup/shop-probe/0123456789abcdef"
+ },
+ "evaluate_low_sample_count_percentiles": "ftpmcCTESL",
+ "evaluation_criteria": [],
+ "evaluation_interval": null,
+ "evaluation_periods": 10,
+ "extended_statistic": null,
+ "id": "rww11J47ygB",
+ "insufficient_data_actions": null,
+ "metric_name": "UnHealthyHostCount",
+ "metric_query": [],
+ "namespace": "AWS/NetworkELB",
+ "ok_actions": [
+ "arn:aws:sns:eu-west-1:123456789012:shop-alerts"
+ ],
+ "period": 60,
+ "region": "4M6nOqZL",
+ "statistic": "Maximum",
+ "tags": null,
+ "tags_all": {},
+ "threshold": 0,
+ "threshold_metric_id": null,
+ "treat_missing_data": "breaching",
+ "unit": null,
+ "warm_up_configuration": []
+ },
+ "after_unknown": {},
+ "before_sensitive": false,
+ "after_sensitive": {
+ "alarm_actions": [
+ false
+ ],
+ "dimensions": {},
+ "evaluation_criteria": [],
+ "metric_query": [],
+ "ok_actions": [
+ false
+ ],
+ "tags_all": {},
+ "warm_up_configuration": []
+ }
+ }
+ }
+ ],
+ "prior_state": {
+ "values": {
+ "root_module": {
+ "child_modules": [
+ {
+ "address": "module.ie",
+ "resources": [
+ {
+ "address": "module.ie.aws_instance.host",
+ "mode": "managed",
+ "type": "aws_instance",
+ "name": "host",
+ "values": {
+ "id": "i-fixed",
+ "primary_network_interface_id": "eni-fixed",
+ "network_interface": [
+ {
+ "network_interface_id": "eni-secondary"
+ }
+ ]
+ }
+ },
+ {
+ "address": "module.ie.aws_eip.host",
+ "mode": "managed",
+ "type": "aws_eip",
+ "name": "host",
+ "values": {
+ "id": "eipalloc-fixed",
+ "public_ip": "192.0.2.1",
+ "instance": "i-fixed"
+ }
+ },
+ {
+ "address": "module.ie.aws_security_group.host",
+ "mode": "managed",
+ "type": "aws_security_group",
+ "name": "host",
+ "values": {
+ "id": "sg-fixed"
+ }
+ },
+ {
+ "address": "module.ie.aws_iam_role.host",
+ "mode": "managed",
+ "type": "aws_iam_role",
+ "name": "host",
+ "values": {
+ "id": "role-fixed-id",
+ "name": "host-role",
+ "arn": "arn:aws:iam::123456789012:role/host-role"
+ }
+ },
+ {
+ "address": "module.ie.aws_iam_instance_profile.host",
+ "mode": "managed",
+ "type": "aws_iam_instance_profile",
+ "name": "host",
+ "values": {
+ "id": "profile-fixed-id",
+ "name": "host-profile",
+ "arn": "arn:aws:iam::123456789012:instance-profile/host-profile"
+ }
+ }
+ ]
+ }
+ ]
+ }
+ }
+ }
+}