region HA P3b T6: add group metrics, alarms and simulation
Append group and per-instance clock evidence to the existing metrics batch. Add producer-backed regional alarms, pool isolation and request-budget witnesses, and group admission and maintenance simulation scenarios. Validate with local mocks and one serial 3,000-seed sweep.
Co-Authored-By: GPT-6 Astra (codex) <noreply@openai.com>
12 files changed,
+1,412
−12
infra/modules/region-host/group_alarms.tf+134 −0infra/modules/region-host/tests/group_alarms.tftest.hcl+143 −6internal/host/group_boot_budget_test.go+406 −0internal/host/group_metrics.go+52 −2internal/host/group_metrics_test.go+145 −0internal/host/group_pool_test.go+109 −0internal/host/memwatch.go+5 −2internal/sim/regionha/actions_test.go+7 −0internal/sim/regionha/duties_model_test.go+19 −2internal/sim/regionha/group_admission_test.go+387 −0internal/sim/regionha/invariants_test.go+3 −0internal/sim/regionha/world_test.go+2 −0
diff --git a/infra/modules/region-host/group_alarms.tf b/infra/modules/region-host/group_alarms.tf| index ef0c33c16..b2ed29a87 100644 |
| --- a/infra/modules/region-host/group_alarms.tf |
| +++ b/infra/modules/region-host/group_alarms.tf |
| @@ -22,3 +22,137 @@ resource "aws_cloudwatch_metric_alarm" "termination_queue_age" { |
| ok_actions = var.alerts_email != "" ? [aws_sns_topic.alerts[0].arn] : [] |
| dimensions = { QueueName = aws_sqs_queue.terminations.name } |
| } |
| + |
| +# Producers: AWS/AutoScaling's enabled one-minute group metrics; the existing |
| +# memwatch batch (Carlos/Host); and Auto Scaling launch-failure events. |
| +# EligibleBoxes stays unarmed until P2b supplies its real producer. NLB alarms |
| +# belong to ingress. All actions notify; none replaces or scales a member. |
| +locals { |
| + group_alarm_actions = var.alerts_email != "" ? [aws_sns_topic.alerts[0].arn] : [] |
| +} |
| + |
| +resource "aws_cloudwatch_metric_alarm" "group_capacity" { |
| + count = var.mode == "group" ? 1 : 0 |
| + alarm_name = "${var.name}-group-capacity" |
| + alarm_description = "Fewer group members are in service than the current desired capacity. Check launch failures and member health." |
| + comparison_operator = "LessThanThreshold" |
| + threshold = 0 |
| + evaluation_periods = 1 |
| + datapoints_to_alarm = 1 |
| + treat_missing_data = "breaching" |
| + alarm_actions = local.group_alarm_actions |
| + ok_actions = local.group_alarm_actions |
| + metric_query { |
| + id = "deficit" |
| + # Arithmetic alone treats a missing operand as zero. Explicitly fail |
| + # either missing input, including desired=unknown during Standby. |
| + expression = "IF(FILL(desired, -1) < 0, -1, FILL(inservice, -1) - desired)" |
| + return_data = true |
| + } |
| + metric_query { |
| + id = "inservice" |
| + metric { |
| + namespace = "AWS/AutoScaling" |
| + metric_name = "GroupInServiceInstances" |
| + period = 60 |
| + stat = "Minimum" |
| + dimensions = { AutoScalingGroupName = aws_autoscaling_group.group[0].name } |
| + } |
| + } |
| + metric_query { |
| + id = "desired" |
| + metric { |
| + namespace = "AWS/AutoScaling" |
| + metric_name = "GroupDesiredCapacity" |
| + period = 60 |
| + stat = "Maximum" |
| + dimensions = { AutoScalingGroupName = aws_autoscaling_group.group[0].name } |
| + } |
| + } |
| +} |
| + |
| +resource "aws_cloudwatch_metric_alarm" "group_memory" { |
| + count = var.mode == "group" ? 1 : 0 |
| + alarm_name = "${var.name}-group-memory" |
| + alarm_description = "A group member has less than 15 percent available memory for three minutes, or memory readings are missing." |
| + namespace = "Carlos/Host" |
| + metric_name = "MemAvailablePercent" |
| + statistic = "Minimum" |
| + period = 60 |
| + evaluation_periods = 3 |
| + datapoints_to_alarm = 3 |
| + threshold = 15 |
| + comparison_operator = "LessThanThreshold" |
| + treat_missing_data = "breaching" |
| + alarm_actions = local.group_alarm_actions |
| + ok_actions = local.group_alarm_actions |
| + dimensions = { AutoScalingGroupName = aws_autoscaling_group.group[0].name } |
| +} |
| + |
| +resource "aws_cloudwatch_metric_alarm" "group_clock" { |
| + count = var.mode == "group" ? 1 : 0 |
| + alarm_name = "${var.name}-group-clock" |
| + alarm_description = "A group clock is more than one second off, or clock readings are missing. Check each member's clock evidence." |
| + 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.group_alarm_actions |
| + ok_actions = local.group_alarm_actions |
| + dimensions = { AutoScalingGroupName = aws_autoscaling_group.group[0].name } |
| +} |
| + |
| +resource "aws_cloudwatch_metric_alarm" "group_clock_missing" { |
| + count = var.mode == "group" ? 1 : 0 |
| + alarm_name = "${var.name}-group-clock-missing" |
| + alarm_description = "A member could not read its clock, or clock presence readings are missing. Check the per-instance samples against the group membership." |
| + namespace = "Carlos/Host" |
| + metric_name = "ClockSamplePresent" |
| + statistic = "Minimum" |
| + period = 60 |
| + evaluation_periods = 1 |
| + datapoints_to_alarm = 1 |
| + threshold = 1 |
| + comparison_operator = "LessThanThreshold" |
| + treat_missing_data = "breaching" |
| + alarm_actions = local.group_alarm_actions |
| + ok_actions = local.group_alarm_actions |
| + dimensions = { AutoScalingGroupName = aws_autoscaling_group.group[0].name } |
| +} |
| + |
| +resource "aws_cloudwatch_event_rule" "group_launch_failed" { |
| + count = var.mode == "group" ? 1 : 0 |
| + name = "${var.name}-launch-failed" |
| + description = "Notify when this group fails to launch a member." |
| + event_pattern = jsonencode({ |
| + source = ["aws.autoscaling"] |
| + "detail-type" = ["EC2 Instance Launch Unsuccessful"] |
| + detail = { AutoScalingGroupName = [aws_autoscaling_group.group[0].name] } |
| + }) |
| +} |
| + |
| +resource "aws_cloudwatch_event_target" "group_launch_failed" { |
| + count = var.mode == "group" && var.alerts_email != "" ? 1 : 0 |
| + rule = aws_cloudwatch_event_rule.group_launch_failed[0].name |
| + arn = aws_sns_topic.alerts[0].arn |
| +} |
| + |
| +resource "aws_sns_topic_policy" "group_launch_failed" { |
| + count = var.mode == "group" && var.alerts_email != "" ? 1 : 0 |
| + arn = aws_sns_topic.alerts[0].arn |
| + policy = jsonencode({ |
| + Version = "2012-10-17" |
| + Statement = [{ |
| + Sid = "GroupLaunchFailure" |
| + Effect = "Allow" |
| + Principal = { Service = "events.amazonaws.com" } |
| + Action = "sns:Publish" |
| + Resource = aws_sns_topic.alerts[0].arn |
| + }] |
| + }) |
| +} |
diff --git a/infra/modules/region-host/tests/group_alarms.tftest.hcl b/infra/modules/region-host/tests/group_alarms.tftest.hcl| index 21b09ab0c..69db294b3 100644 |
| --- a/infra/modules/region-host/tests/group_alarms.tftest.hcl |
| +++ b/infra/modules/region-host/tests/group_alarms.tftest.hcl |
| @@ -1,6 +1,8 @@ |
| # Plan-time tests for the host instance's metadata service settings. |
| # mock_provider means no AWS account and no credentials. |
| -mock_provider "aws" {} |
| +mock_provider "aws" { |
| + mock_resource "aws_launch_template" { defaults = { id = "lt-0123456789abcdef0" } } |
| +} |
| override_data { |
| target = data.aws_vpcs.default |
| @@ -60,7 +62,7 @@ override_resource { |
| run "termination_alarm_default_off" { |
| command = plan |
| assert { |
| - condition = length(aws_cloudwatch_metric_alarm.termination_queue_age) == 0 |
| + condition = length(aws_cloudwatch_metric_alarm.termination_queue_age) == 0 && length(aws_cloudwatch_metric_alarm.group_capacity) == 0 && length(aws_cloudwatch_metric_alarm.group_memory) == 0 && length(aws_cloudwatch_metric_alarm.group_clock) == 0 && length(aws_cloudwatch_metric_alarm.group_clock_missing) == 0 && length(aws_cloudwatch_event_rule.group_launch_failed) == 0 |
| error_message = "fixed plans must not gain a termination queue alarm by default" |
| } |
| } |
| @@ -91,10 +93,6 @@ run "termination_alarm_regional_notifications" { |
| 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]) && |
| @@ -104,3 +102,142 @@ run "termination_alarm_regional_notifications" { |
| error_message = "termination alerts must use the existing regional notification topic" |
| } |
| } |
| + |
| +override_data { |
| + target = data.aws_region.current |
| + values = { region = "eu-west-1" } |
| +} |
| + |
| +override_data { |
| + target = data.aws_partition.current |
| + values = { partition = "aws", dns_suffix = "amazonaws.com" } |
| +} |
| + |
| +override_data { |
| + target = data.aws_subnets.group |
| + values = { ids = ["subnet-00000000000000001", "subnet-00000000000000002"] } |
| +} |
| + |
| +override_data { |
| + target = data.aws_route_table.group |
| + values = { routes = [{ cidr_block = "0.0.0.0/0", gateway_id = "igw-0123456789abcdef0", carrier_gateway_id = "", core_network_arn = "", destination_prefix_list_id = "", egress_only_gateway_id = "", instance_id = "", ipv6_cidr_block = "", local_gateway_id = "", nat_gateway_id = "", network_interface_id = "", odb_network_arn = "", transit_gateway_id = "", vpc_endpoint_id = "", vpc_peering_connection_id = "" }] } |
| +} |
| + |
| +override_data { |
| + target = data.aws_lb.group |
| + values = { |
| + vpc_id = "vpc-0123456789abcdef0" |
| + internal = false |
| + load_balancer_type = "network" |
| + ip_address_type = "ipv4" |
| + enable_cross_zone_load_balancing = true |
| + security_groups = ["sg-0123456789abcdef0"] |
| + subnet_mapping = [ |
| + { subnet_id = "subnet-00000000000000001", allocation_id = "eipalloc-00000000000000001", ipv6_address = "", outpost_id = "", private_ipv4_address = "" }, |
| + { subnet_id = "subnet-00000000000000002", allocation_id = "eipalloc-00000000000000002", ipv6_address = "", outpost_id = "", private_ipv4_address = "" } |
| + ] |
| + } |
| +} |
| + |
| +override_data { |
| + target = data.aws_lb_target_group.group_http |
| + values = { vpc_id = "vpc-0123456789abcdef0", port = 80, protocol = "TCP", target_type = "instance", load_balancer_arns = ["arn:aws:elasticloadbalancing:eu-west-1:123456789012:loadbalancer/net/test/1234"], preserve_client_ip = "true" } |
| +} |
| + |
| +override_data { |
| + target = data.aws_lb_target_group.group_https |
| + values = { vpc_id = "vpc-0123456789abcdef0", port = 443, protocol = "TCP", target_type = "instance", load_balancer_arns = ["arn:aws:elasticloadbalancing:eu-west-1:123456789012:loadbalancer/net/test/1234"], preserve_client_ip = "true" } |
| +} |
| + |
| +override_data { |
| + target = data.aws_eip.group["eu-west-1a"] |
| + values = { public_ip = "198.51.100.10" } |
| +} |
| + |
| +override_data { |
| + target = data.aws_eip.group["eu-west-1b"] |
| + values = { public_ip = "198.51.100.11" } |
| +} |
| + |
| +override_resource { |
| + target = aws_sns_topic.alerts |
| + values = { arn = "arn:aws:sns:eu-west-1:123456789012:carlos-dev-ie-group-alerts" } |
| +} |
| +override_resource { |
| + target = aws_cloudwatch_event_rule.group_launch_failed |
| + values = { arn = "arn:aws:events:eu-west-1:123456789012:rule/carlos-dev-ie-group-launch-failed" } |
| +} |
| +run "group_alarm_producers" { |
| + command = plan |
| + variables { |
| + alerts_email = "ops@example.com" |
| + termination_queue_alarm = true |
| + mode = "group" |
| + name = "carlos-dev-ie-group" |
| + iam_name = "carlos-dev-ie-group" |
| + sg_description = "test group" |
| + instance_type = "t4g.micro" |
| + root_volume_size = 20 |
| + user_data = "" |
| + deployment_bucket_arn = "arn:aws:s3:::carlos-dev-platform" |
| + data_bucket_arn = "arn:aws:s3:::carlos-dev-ie" |
| + ssm_parameter_arn = "" |
| + vpc_id = "vpc-0123456789abcdef0" |
| + box_count = 2 |
| + group_config = { |
| + deployment = "dev" |
| + region = "ie" |
| + placement_region = "ie" |
| + pools = ["default"] |
| + ami_id = "ami-0123456789abcdef0" |
| + release = "v0.100.0" |
| + configuration_kms_key_arn = "arn:aws:kms:eu-west-1:123456789012:key/00000000-0000-0000-0000-000000000001" |
| + } |
| + group_zones = { |
| + eu-west-1a = { subnet_id = "subnet-00000000000000001", allocation_id = "eipalloc-00000000000000001" } |
| + eu-west-1b = { subnet_id = "subnet-00000000000000002", allocation_id = "eipalloc-00000000000000002" } |
| + } |
| + group_ingress = { |
| + nlb_arn = "arn:aws:elasticloadbalancing:eu-west-1:123456789012:loadbalancer/net/test/1234" |
| + nlb_security_group_id = "sg-0123456789abcdef0" |
| + target_group_arns = { |
| + "80" = "arn:aws:elasticloadbalancing:eu-west-1:123456789012:targetgroup/test-80/1234" |
| + "443" = "arn:aws:elasticloadbalancing:eu-west-1:123456789012:targetgroup/test-443/1234" |
| + } |
| + public_ips = { eu-west-1a = "198.51.100.10", eu-west-1b = "198.51.100.11" } |
| + } |
| + } |
| + assert { |
| + condition = aws_autoscaling_group.group[0].enabled_metrics == toset(["GroupInServiceInstances", "GroupDesiredCapacity"]) && aws_autoscaling_group.group[0].metrics_granularity == "1Minute" |
| + error_message = "capacity alarms require both real one-minute ASG producers" |
| + } |
| + assert { |
| + condition = alltrue([for a in [aws_cloudwatch_metric_alarm.group_capacity[0], aws_cloudwatch_metric_alarm.group_memory[0], aws_cloudwatch_metric_alarm.group_clock[0], aws_cloudwatch_metric_alarm.group_clock_missing[0]] : a.treat_missing_data == "breaching" && a.alarm_actions == toset([aws_sns_topic.alerts[0].arn]) && a.ok_actions == a.alarm_actions]) |
| + error_message = "missing group data must breach and notify the regional topic" |
| + } |
| + assert { |
| + condition = aws_cloudwatch_metric_alarm.group_capacity[0].threshold == 0 && aws_cloudwatch_metric_alarm.group_capacity[0].comparison_operator == "LessThanThreshold" && aws_cloudwatch_metric_alarm.group_capacity[0].evaluation_periods == 1 && aws_cloudwatch_metric_alarm.group_capacity[0].datapoints_to_alarm == 1 && one([for q in aws_cloudwatch_metric_alarm.group_capacity[0].metric_query : q.expression if q.id == "deficit"]) == "IF(FILL(desired, -1) < 0, -1, FILL(inservice, -1) - desired)" && alltrue([for q in aws_cloudwatch_metric_alarm.group_capacity[0].metric_query : length(q.metric) == 0 ? true : q.metric[0].period == 60 && q.metric[0].namespace == "AWS/AutoScaling" && q.metric[0].dimensions == tomap({ AutoScalingGroupName = aws_autoscaling_group.group[0].name })]) |
| + error_message = "capacity uses actual desired membership including approved Standby" |
| + } |
| + assert { |
| + condition = aws_cloudwatch_metric_alarm.group_memory[0].metric_name == "MemAvailablePercent" && aws_cloudwatch_metric_alarm.group_memory[0].statistic == "Minimum" && aws_cloudwatch_metric_alarm.group_memory[0].period == 60 && aws_cloudwatch_metric_alarm.group_memory[0].threshold == 15 && aws_cloudwatch_metric_alarm.group_memory[0].evaluation_periods == 3 && aws_cloudwatch_metric_alarm.group_memory[0].datapoints_to_alarm == 3 && aws_cloudwatch_metric_alarm.group_memory[0].comparison_operator == "LessThanThreshold" |
| + error_message = "one low-memory member must breach for three consecutive minutes" |
| + } |
| + assert { |
| + condition = aws_cloudwatch_metric_alarm.group_clock[0].metric_name == "ClockOffsetSeconds" && aws_cloudwatch_metric_alarm.group_clock[0].statistic == "Maximum" && aws_cloudwatch_metric_alarm.group_clock[0].period == 60 && aws_cloudwatch_metric_alarm.group_clock[0].threshold == 1 && aws_cloudwatch_metric_alarm.group_clock[0].evaluation_periods == 1 && aws_cloudwatch_metric_alarm.group_clock[0].datapoints_to_alarm == 1 && aws_cloudwatch_metric_alarm.group_clock[0].comparison_operator == "GreaterThanThreshold" && aws_cloudwatch_metric_alarm.group_clock_missing[0].metric_name == "ClockSamplePresent" && aws_cloudwatch_metric_alarm.group_clock_missing[0].statistic == "Minimum" && aws_cloudwatch_metric_alarm.group_clock_missing[0].threshold == 1 |
| + error_message = "unknown clock is not a zero offset" |
| + } |
| + assert { |
| + condition = one([for q in aws_cloudwatch_metric_alarm.group_capacity[0].metric_query : q.metric[0].metric_name if q.id == "inservice"]) == "GroupInServiceInstances" && one([for q in aws_cloudwatch_metric_alarm.group_capacity[0].metric_query : q.metric[0].metric_name if q.id == "desired"]) == "GroupDesiredCapacity" && alltrue([for a in [aws_cloudwatch_metric_alarm.group_memory[0], aws_cloudwatch_metric_alarm.group_clock[0], aws_cloudwatch_metric_alarm.group_clock_missing[0]] : a.namespace == "Carlos/Host" && a.dimensions == tomap({ AutoScalingGroupName = aws_autoscaling_group.group[0].name })]) |
| + error_message = "alarm dimensions and metric names must match the actual producers" |
| + } |
| + assert { |
| + condition = split(":", aws_sns_topic.alerts[0].arn)[3] == data.aws_region.current.region && jsondecode(aws_cloudwatch_event_rule.group_launch_failed[0].event_pattern) == { source = ["aws.autoscaling"], "detail-type" = ["EC2 Instance Launch Unsuccessful"], detail = { AutoScalingGroupName = [aws_autoscaling_group.group[0].name] } } && aws_cloudwatch_event_target.group_launch_failed[0].arn == aws_sns_topic.alerts[0].arn && jsondecode(aws_sns_topic_policy.group_launch_failed[0].policy).Statement[0].Principal.Service == "events.amazonaws.com" |
| + error_message = "launch failures must notify without filtering provider Cause text" |
| + } |
| +} |
| + |
| +override_data { |
| + target = data.aws_ami.group |
| + values = { id = "ami-0123456789abcdef0", root_device_name = "/dev/xvda", root_device_type = "ebs" } |
| +} |
diff --git a/internal/host/group_boot_budget_test.go b/internal/host/group_boot_budget_test.go| new file mode 100644 |
| index 000000000..f823f2ad9 |
| --- /dev/null |
| +++ b/internal/host/group_boot_budget_test.go |
| @@ -0,0 +1,406 @@ |
| +package host |
| + |
| +import ( |
| + "context" |
| + "crypto/ed25519" |
| + "encoding/json" |
| + "fmt" |
| + "github.com/carlosframework/platform/internal/hadeparture" |
| + "github.com/carlosframework/platform/internal/lease/locktest" |
| + "io" |
| + "net/http/httptest" |
| + "os" |
| + "os/exec" |
| + "strings" |
| + "sync/atomic" |
| + _ "unsafe" |
| + |
| + "github.com/aws/aws-sdk-go-v2/credentials" |
| + "github.com/carlosframework/platform/internal/awsregiongroup" |
| + "github.com/carlosframework/platform/internal/boxid" |
| + "github.com/carlosframework/platform/internal/boxid/boxidtest" |
| + "github.com/carlosframework/platform/internal/hostenv" |
| + "github.com/carlosframework/platform/internal/release" |
| + "net/http" |
| + "testing" |
| + "time" |
| + |
| + "github.com/aws/aws-sdk-go-v2/aws" |
| + "github.com/aws/aws-sdk-go-v2/service/cloudwatch" |
| +) |
| + |
| +type groupBudgetTransport struct{ calls int } |
| + |
| +func (t *groupBudgetTransport) Do(r *http.Request) (*http.Response, error) { |
| + t.calls++ |
| + return &http.Response{StatusCode: 503, Header: http.Header{}, Body: http.NoBody, Request: r}, nil |
| +} |
| + |
| +func TestGroupBootRequestBudget(t *testing.T) { |
| + t.Run("SSM-pages-and-decryptions", groupSSMBudget) |
| + t.Run("bootstrap-SSM-S3-IMDS", groupBootstrapBudget) |
| + t.Run("install", groupInstallBudget) |
| + t.Run("closed-member-redelivery", groupClosedBudget) |
| + t.Run("runtime-S3-retry-bound", groupRuntimeS3Budget) |
| + t.Run("role-noop-absence-error", groupRoleBudget) |
| + t.Run("publication-conflicts-and-failed-CAS", testColdPlacementPublicationS3Budget) |
| + t.Run("lifecycle-wire-restart-exhaustion", groupLifecycleBudget) |
| + t.Run("operator-return-resume", groupReturnBudget) |
| + |
| + t.Run("metrics-wire-attempts", func(t *testing.T) { |
| + transport := &groupBudgetTransport{} |
| + cfg := aws.Config{Region: "eu-west-1", HTTPClient: transport, Credentials: aws.CredentialsProviderFunc(func(context.Context) (aws.Credentials, error) { |
| + return aws.Credentials{AccessKeyID: "test", SecretAccessKey: "test"}, nil |
| + })} |
| + cfg = groupMetricsAWSConfig(cfg, "eu-west-2", true) |
| + c := cloudwatch.NewFromConfig(cfg) |
| + _, _ = c.PutMetricData(t.Context(), memwatchData("i-test", 20, 0, false, time.Now())) |
| + if transport.calls != 1 || c.Options().Region != "eu-west-2" { |
| + t.Fatalf("wire attempts=%d region=%s", transport.calls, c.Options().Region) |
| + } |
| + fixed := groupMetricsAWSConfig(aws.Config{Region: "eu-west-1", RetryMaxAttempts: 7}, "eu-west-2", false) |
| + if fixed.RetryMaxAttempts != 7 { |
| + t.Fatal("fixed retry policy changed") |
| + } |
| + }) |
| +} |
| + |
| +// Test-only access to the production SSM adapter; no replacement pagination. |
| +// |
| +//go:linkname groupBudgetOpenSSM github.com/carlosframework/platform/internal/hostenv.openSSMParamsMode |
| +func groupBudgetOpenSSM(context.Context, string, string, bool) (hostenv.Params, error) |
| + |
| +func groupSSMBudget(t *testing.T) { |
| + for _, mode := range []string{"success", "empty-pages", "duplicate", "failure"} { |
| + t.Run(mode, func(t *testing.T) { |
| + calls, values := 0, 0 |
| + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + calls++ |
| + var in struct { |
| + Path string |
| + MaxResults int |
| + Recursive, WithDecryption bool |
| + NextToken string |
| + } |
| + if err := json.NewDecoder(r.Body).Decode(&in); err != nil { |
| + t.Error(err) |
| + } |
| + if r.Header.Get("X-Amz-Target") != "AmazonSSM.GetParametersByPath" || in.MaxResults != 10 || in.Recursive || !in.WithDecryption { |
| + t.Error("unexpected request", in) |
| + } |
| + w.Header().Set("Content-Type", "application/x-amz-json-1.1") |
| + if mode == "failure" { |
| + w.WriteHeader(500) |
| + fmt.Fprint(w, `{"__type":"InternalServerError"}`) |
| + return |
| + } |
| + out := map[string]any{"NextToken": fmt.Sprint(calls)} |
| + ps := []map[string]string{} |
| + if mode != "empty-pages" { |
| + for i := 0; i < 5; i++ { |
| + name := fmt.Sprintf("K%d_%d", calls, i) |
| + if mode == "duplicate" { |
| + name = "duplicate" |
| + } |
| + ps = append(ps, map[string]string{"Name": in.Path + "/" + name, "Type": "SecureString", "Value": "value"}) |
| + values++ |
| + } |
| + } |
| + out["Parameters"] = ps |
| + if mode == "success" && (calls == 10 || calls == 20) { |
| + delete(out, "NextToken") |
| + } |
| + _ = json.NewEncoder(w).Encode(out) |
| + })) |
| + defer server.Close() |
| + for k, v := range map[string]string{"AWS_ENDPOINT_URL_SSM": server.URL, "AWS_ACCESS_KEY_ID": "test", "AWS_SECRET_ACCESS_KEY": "test", "AWS_SESSION_TOKEN": "", "AWS_PROFILE": "", "AWS_DEFAULT_PROFILE": "", "AWS_CONFIG_FILE": os.DevNull, "AWS_SHARED_CREDENTIALS_FILE": os.DevNull, "AWS_EC2_METADATA_DISABLED": "true"} { |
| + t.Setenv(k, v) |
| + } |
| + p, err := groupBudgetOpenSSM(t.Context(), "eu-west-2", "", true) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + _, err = p.ByPath(t.Context(), "/carlos/dev/shared/") |
| + if err == nil { |
| + _, err = p.ByPath(t.Context(), "/carlos/dev/uk/") |
| + } |
| + if mode == "success" { |
| + if err != nil || calls != 20 || values != 100 || calls+2 != 22 || values+3+1 != 104 { |
| + t.Fatalf("calls=%d decryptions=%d err=%v", calls, values, err) |
| + } |
| + } else if err == nil || calls > 20 || mode == "empty-pages" && calls != 20 || mode == "failure" && calls != 1 { |
| + t.Fatalf("%s calls=%d values=%d err=%v", mode, calls, values, err) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func groupInstallBudget(t *testing.T) { |
| + for _, floor := range []string{"", "v1.2.0"} { |
| + t.Run(floor, func(t *testing.T) { |
| + f := newChannelFixture(t, floor) |
| + f.in.group = true |
| + s := &coldBudgetStore{Store: f.store} |
| + f.a.openStore = func(context.Context) (release.Store, ed25519.PublicKey, error) { return s, f.pub, nil } |
| + if _, err := f.in.run(t.Context()); err != nil { |
| + t.Fatal(err) |
| + } |
| + want := 4 |
| + if floor != "" { |
| + want = 5 |
| + } |
| + if s.g != want || s.p+s.l+s.d != 0 { |
| + t.Fatalf("G/P/L/D=%d/%d/%d/%d", s.g, s.p, s.l, s.d) |
| + } |
| + }) |
| + } |
| +} |
| +func groupRoleBudget(t *testing.T) { |
| + r, s, _, _, _ := roleReaderFixture(t) |
| + now := time.Now() |
| + r.pass(t.Context(), now) |
| + if s.gets != 2 { |
| + t.Fatal("absence", s.gets) |
| + } |
| + for i := 1; i < int(r.gate.MaxAge()/time.Second); i++ { |
| + r.pass(t.Context(), now.Add(time.Duration(i)*time.Second)) |
| + } |
| + if s.gets != 2 { |
| + t.Fatal("noop", s.gets) |
| + } |
| + r, s, _, _, _ = roleReaderFixture(t) |
| + s.fail = "control/box-roles/@region-ie.json" |
| + for i := 0; i < 3600; i++ { |
| + r.pass(t.Context(), now.Add(time.Duration(i)*time.Second)) |
| + } |
| + if s.gets > 128 { |
| + t.Fatal("error budget", s.gets) |
| + } |
| +} |
| + |
| +type groupWireFunc func(*http.Request) (*http.Response, error) |
| + |
| +func (f groupWireFunc) Do(r *http.Request) (*http.Response, error) { return f(r) } |
| +func groupLifecycleBudget(t *testing.T) { |
| + signer := boxidtest.NewSigner(t) |
| + _, raw := signer.Record(t, "self", "123456789012", "eu-west-1", "i-0123456789abcdef0") |
| + for _, mode := range []string{"success", "lost", "rejected"} { |
| + t.Run(mode, func(t *testing.T) { |
| + calls := 0 |
| + c := groupLaunchFixture(t, nil) |
| + cfg := aws.Config{Region: "eu-west-1", Credentials: credentials.NewStaticCredentialsProvider("test", "test", ""), HTTPClient: groupWireFunc(func(r *http.Request) (*http.Response, error) { |
| + calls++ |
| + if deadline, ok := r.Context().Deadline(); !ok || time.Until(deadline) > 2*time.Second { |
| + t.Error("missing completion timeout") |
| + } |
| + body, _ := io.ReadAll(r.Body) |
| + if !strings.Contains(string(body), "LifecycleActionResult=CONTINUE") || strings.Contains(string(body), "LifecycleActionToken") { |
| + t.Error("unexpected completion", string(body)) |
| + } |
| + code := 200 |
| + reply := `<CompleteLifecycleActionResponse><CompleteLifecycleActionResult/></CompleteLifecycleActionResponse>` |
| + if mode == "lost" { |
| + code = 503 |
| + reply = `<ErrorResponse><Error><Code>ServiceUnavailable</Code></Error></ErrorResponse>` |
| + } |
| + if mode == "rejected" { |
| + code = 400 |
| + reply = `<ErrorResponse><Error><Code>Throttling</Code></Error></ErrorResponse>` |
| + } |
| + return &http.Response{StatusCode: code, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(reply)), Request: r}, nil |
| + })} |
| + adapter, err := awsregiongroup.New(cfg, raw, boxid.Verifier{Account: "123456789012", Certs: signer.Certs()}, boxid.Expect{Box: "self", AWSRegion: "eu-west-1", TofuInstanceID: c.binding.Instance}, c.binding.launch()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + c.complete = adapter |
| + clock := time.Now().Truncate(time.Second) |
| + c.now = func() time.Time { return clock } |
| + waits := []time.Duration{} |
| + c.wait = func(_ context.Context, d time.Duration) error { |
| + waits = append(waits, d) |
| + clock = clock.Add(d) |
| + return nil |
| + } |
| + err = c.Complete(t.Context(), c.binding.launch()) |
| + if (err == nil) != (mode == "success") { |
| + t.Fatal(mode, err) |
| + } |
| + fresh := &groupReceiptCompleter{dir: c.dir, binding: c.binding, bootID: c.bootID, complete: adapter, now: c.now, wait: c.wait} |
| + _ = fresh.Complete(t.Context(), c.binding.launch()) |
| + want := 1 |
| + if mode == "rejected" { |
| + want = 4 |
| + } |
| + if calls != want { |
| + t.Fatalf("wire attempts %d want %d", calls, want) |
| + } |
| + if mode == "rejected" && fmt.Sprint(waits) != "[1s 2s 4s]" { |
| + t.Fatal("backoff", waits) |
| + } |
| + }) |
| + } |
| +} |
| +func groupReturnBudget(t *testing.T) { |
| + for _, hook := range []bool{false, true} { |
| + o := heldTransaction(t) |
| + o.c.hook = hook |
| + o.c.loseExit = true |
| + finishLocal(o) |
| + if err := o.observeReady(); err != nil { |
| + t.Fatal(err) |
| + } |
| + _ = o.returnMember() |
| + o = &fakeMaintenanceOperator{c: o.c, j: o.j} |
| + if err := o.returnMember(); err != nil { |
| + t.Fatal(err) |
| + } |
| + want := 0 |
| + if hook { |
| + want = 1 |
| + } |
| + if len(o.c.writes) != 4+want || o.c.operatorCompletions != want || o.c.reads > 1440 { |
| + t.Fatalf("writes %v completion=%d reads=%d", o.c.writes, o.c.operatorCompletions, o.c.reads) |
| + } |
| + } |
| +} |
| + |
| +func groupBootstrapBudget(t *testing.T) { |
| + raw, err := os.ReadFile("../../infra/modules/region-host/group-init.sh.tftpl") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + start := strings.Index(string(raw), "import base64, datetime, hashlib") |
| + end := strings.Index(string(raw)[start:], "\nPY\n") |
| + if start < 0 || end < 0 { |
| + t.Fatal("boot fragment missing") |
| + } |
| + program := ` |
| +import ast, builtins, io, json, os, subprocess, hashlib, urllib.request, datetime |
| +source = SOURCE |
| +root='/carlos/dev/ie/boot/' |
| +os.environ.update(dict(CARLOS_DEPLOYMENT='dev',CARLOS_REGION='ie',AWS_REGION='eu-west-1',CARLOS_BOOTSTRAP_OBJECT_KEY=root+'bootstrap-object',CARLOS_BOOTSTRAP_HASH_KEY=root+'bootstrap-sha256',CARLOS_TERMINATION_QUEUE_URL='queue',CARLOS_DEPLOYMENT_BUCKET='deploy',CARLOS_GROUP_ACCOUNT='123456789012',CARLOS_PLACEMENT_REGION='ie',CARLOS_INGRESS_KEY=root+'ingress',CARLOS_GROUP_DATA_BUCKET='data',CARLOS_GROUP_NAME='dev-ie',CARLOS_LAUNCH_HOOK_NAME='carlos-initial-launch',CARLOS_POOLS='hapair',CARLOS_RELEASE='v1.2.3')) |
| +calls=[];decryptions=0;metadata=[] |
| +def run(args,timeout): |
| + global decryptions |
| + assert timeout==90 and args[0]=='aws' and args[1:3]==['--region','eu-west-1'] |
| + calls.append(args) |
| + if 'get-parameters' in args: |
| + names=args[args.index('--names')+1:args.index('--with-decryption')] |
| + vals=[json.dumps(dict(key='bootstrap/dev/ie/one',version='1',known_readers=[],deployment_aws_region='eu-west-1')),hashlib.sha256(b'bootstrap').hexdigest(),'queue'] |
| + assert len(names)==3 |
| + decryptions+=3 |
| + return json.dumps(dict(Parameters=[dict(Name=n,Value=v) for n,v in zip(names,vals)])).encode() |
| + if 'get-parameter' in args: |
| + decryptions+=1 |
| + return json.dumps(dict(Parameter=dict(Name=root+'ingress',Value='["8.8.8.8"]'))).encode() |
| + assert 'get-object' in args and '--version-id' in args |
| + return b'{}' |
| +subprocess.check_output=run |
| +def urlopen(request,timeout): |
| + assert timeout==2 |
| + path=request.full_url.removeprefix('http://169.254.169.254') |
| + metadata.append(path) |
| + if path.endswith('/token'): return io.BytesIO(b'token') |
| + if path.endswith('/signature'):return io.BytesIO(b'signature') |
| + assert path.endswith('/document') |
| + return io.BytesIO(json.dumps(dict(accountId='123456789012',region='eu-west-1',instanceId='i-0123456789abcdef0',pendingTime=datetime.datetime.now(datetime.timezone.utc).isoformat())).encode()) |
| +urllib.request.urlopen=urlopen |
| +realopen=builtins.open |
| +def fakeopen(path,*args,**kwargs): |
| + if path=='/run/carlos-group-boot/bootstrap':return io.BytesIO(b'bootstrap') |
| + if path=='/proc/sys/kernel/random/boot_id':return io.StringIO('boot') |
| + raise AssertionError('unexpected file '+path) |
| +builtins.open=fakeopen |
| +os.chmod=lambda *args:None |
| +writes=[] |
| +def write(path,body,mode=0o644):writes.append(path) |
| +tree=ast.parse(source) |
| +tree.body=[n for n in tree.body if not isinstance(n,ast.FunctionDef) or n.name!='write'] |
| +exec(compile(tree,'group-init.sh.tftpl','exec')) |
| +assert len(calls)==3 and decryptions==4 and len(metadata)==3,(calls,decryptions,metadata) |
| +assert len(writes)==4,writes |
| +print('boot: 2 SSM calls, 4 decrypted values, 1 versioned S3 GET, 3 IMDS requests') |
| +` |
| + source, _ := json.Marshal(string(raw)[start : start+end]) |
| + program = strings.Replace(program, "SOURCE", string(source), 1) |
| + cmd := exec.Command("python3", "-c", program) |
| + cmd.Dir = t.TempDir() |
| + out, err := cmd.CombinedOutput() |
| + if err != nil { |
| + t.Fatalf("boot budget: %v %s", err, out) |
| + } |
| + t.Log(strings.TrimSpace(string(out))) |
| +} |
| + |
| +func groupRuntimeS3Budget(t *testing.T) { |
| + f := locktest.NewLockFixture(t) |
| + s, err := release.NewDeploymentS3StoreIn(t.Context(), f.Bucket, "eu-west-1") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + r := s.Client.Options().Retryer.MaxAttempts() |
| + if r != 3 { |
| + t.Fatalf("runtime retry bound r=%d, expected 3", r) |
| + } |
| + for i := 0; i < r; i++ { |
| + f.FailNextMatching("GET", 503, func(key string, _ []byte) bool { return key == "budget/absent" }) |
| + } |
| + start := len(f.Requests()) |
| + if _, _, err = s.Get(t.Context(), "budget/absent"); err == nil { |
| + t.Fatal("failed transport succeeded") |
| + } |
| + if n := len(f.Requests()) - start; n != r { |
| + t.Fatalf("logical=1 wire=%d r=%d", n, r) |
| + } |
| + t.Logf("runtime S3: logical=1 wire=%d r=%d; publication ceiling 7G+7P logical, at most r times on the wire", r, r) |
| +} |
| + |
| +type groupBudgetQueue struct { |
| + receives, deletes atomic.Int32 |
| + done chan struct{} |
| +} |
| + |
| +func (q *groupBudgetQueue) Receive(ctx context.Context, _ time.Duration) ([]hadeparture.Message, error) { |
| + n := q.receives.Add(1) |
| + if n <= 3 { |
| + return []hadeparture.Message{{ID: "event", Receipt: fmt.Sprint(n), Body: terminationHint("i-1123456789abcdef0")}}, nil |
| + } |
| + close(q.done) |
| + <-ctx.Done() |
| + return nil, ctx.Err() |
| +} |
| +func (q *groupBudgetQueue) Delete(context.Context, string) error { q.deletes.Add(1); return nil } |
| +func groupClosedBudget(t *testing.T) { |
| + cfg, _, _ := departureArmFixture(t) |
| + a := readyGroupAdmission(t) |
| + cfg.Admitted = a.startAllowed |
| + cfg.BeginWork = a.beginDepartureWork |
| + q := &groupBudgetQueue{done: make(chan struct{})} |
| + cfg.MakeQueue = func(context.Context) (hadeparture.Queue, error) { return q, nil } |
| + c, life, err := armHADepartures(t.Context(), cfg) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer life.Stop(context.Background()) |
| + select { |
| + case <-q.done: |
| + case <-time.After(3 * time.Second): |
| + t.Fatal("redelivery stalled") |
| + } |
| + for _, failed := range []bool{false, true} { |
| + if failed { |
| + a.Close() |
| + } |
| + if _, err = c.ScanPass(t.Context()); err != nil { |
| + t.Fatal(err) |
| + } |
| + _ = c.ackIID(t.Context(), "i-1123456789abcdef0") |
| + if q.deletes.Load() != 0 { |
| + t.Fatal("closed member acknowledged redelivery") |
| + } |
| + } |
| + if q.receives.Load() != 4 { |
| + t.Fatal("unexpected receive loop", q.receives.Load()) |
| + } |
| +} |
diff --git a/internal/host/group_metrics.go b/internal/host/group_metrics.go| index e09d777fc..fbc3f2e26 100644 |
| --- a/internal/host/group_metrics.go |
| +++ b/internal/host/group_metrics.go |
| @@ -17,12 +17,13 @@ import ( |
| type admissionMetrics struct { |
| deployment, region string |
| + group 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 { |
| + if getenv("CARLOS_GROUP_ADMISSION") != "1" || a == nil { |
| return nil |
| } |
| deployment := strings.TrimSpace(getenv("CARLOS_DEPLOYMENT_BUCKET")) |
| @@ -30,7 +31,20 @@ func admissionMetricsFromEnv(getenv func(string) string, a *fixedAdmission, read |
| if deployment == "" || err != nil { |
| return nil |
| } |
| - return &admissionMetrics{deployment: deployment, region: region.RegionCode, state: &a.state, clock: clock} |
| + m := &admissionMetrics{deployment: deployment, region: region.RegionCode, state: &a.state, clock: clock} |
| + if a.group { |
| + // The launch binding was verified against the root marker. The boot |
| + // shell's CARLOS_GROUP_NAME is not part of the service environment. |
| + a.mu.Lock() |
| + if a.launch != nil { |
| + m.group = a.launch.Group |
| + } |
| + a.mu.Unlock() |
| + if m.group == "" { |
| + return nil |
| + } |
| + } |
| + return m |
| } |
| func (m *admissionMetrics) observe(ctx context.Context, now time.Time) (groupadmission.Observation, error) { |
| @@ -126,3 +140,39 @@ func parseChronyTracking(s string) (time.Duration, error) { |
| } |
| return time.Duration(math.Abs(values[4]) * float64(time.Second)), nil |
| } |
| + |
| +func groupMetricsAWSConfig(cfg aws.Config, placement string, group bool) aws.Config { |
| + cfg = memwatchAWSConfig(cfg, placement) |
| + if group { |
| + cfg.Retryer = nil |
| + cfg.RetryMaxAttempts = 1 |
| + } |
| + return cfg |
| +} |
| + |
| +// Group samples share the existing minute batch. Presence is separate from |
| +// offset: a failed clock read must never become a zero-second offset. |
| +func groupMetricData(o groupadmission.Observation, group, iid string, memory float64) []types.MetricDatum { |
| + dims := []types.Dimension{{Name: aws.String("AutoScalingGroupName"), Value: aws.String(group)}} |
| + member := append(append([]types.Dimension{}, dims...), types.Dimension{Name: aws.String("InstanceId"), Value: aws.String(iid)}) |
| + datum := func(name string, value float64, unit types.StandardUnit, dimensions []types.Dimension) types.MetricDatum { |
| + return types.MetricDatum{MetricName: aws.String(name), Value: aws.Float64(value), Unit: unit, Dimensions: dimensions, Timestamp: aws.Time(o.At)} |
| + } |
| + admitted, present := float64(0), float64(0) |
| + if o.Admitted { |
| + admitted = 1 |
| + } |
| + if o.ClockOffset != nil { |
| + present = 1 |
| + } |
| + data := []types.MetricDatum{ |
| + datum("MemAvailablePercent", memory, types.StandardUnitPercent, dims), |
| + datum("Admitted", admitted, types.StandardUnitCount, dims), |
| + datum("ClockSamplePresent", present, types.StandardUnitCount, dims), |
| + datum("ClockSamplePresent", present, types.StandardUnitCount, member), |
| + } |
| + if o.ClockOffset != nil { |
| + data = append(data, datum("ClockOffsetSeconds", o.ClockOffset.Seconds(), types.StandardUnitSeconds, dims), datum("ClockOffsetSeconds", o.ClockOffset.Seconds(), types.StandardUnitSeconds, member)) |
| + } |
| + return data |
| +} |
diff --git a/internal/host/group_metrics_test.go b/internal/host/group_metrics_test.go| index 2f89b331c..de9543510 100644 |
| --- a/internal/host/group_metrics_test.go |
| +++ b/internal/host/group_metrics_test.go |
| @@ -232,3 +232,148 @@ func TestGroupMetricAWSRegion(t *testing.T) { |
| } |
| } |
| } |
| + |
| +func TestGroupMetricsBatch(t *testing.T) { testGroupMetricsBatch(t) } |
| + |
| +func testGroupMetricsBatch(t *testing.T) { |
| + env := map[string]string{"CARLOS_GROUP_ADMISSION": "1", "CARLOS_BOX_REFERENCE": "group", "CARLOS_DEPLOYMENT_BUCKET": "dev-platform", "CARLOS_REGION": "uk"} |
| + a := &fixedAdmission{group: true, launch: &groupadmission.Launch{Group: "carlos-dev-uk-group"}} |
| + calls := 0 |
| + clockErr := error(nil) |
| + m := admissionMetricsFromEnv(func(k string) string { return env[k] }, a, func(string, string) (roleRegionConfig, error) { return roleRegionConfig{RegionCode: "uk"}, nil }, func(context.Context) (time.Duration, error) { calls++; return 1250 * time.Millisecond, clockErr }) |
| + if m == nil { |
| + t.Fatal("group metrics were not armed") |
| + } |
| + put := &fakePutter{} |
| + w := memwatch{admission: m, put: put, instanceID: "i-group", mem: func() (*int64, *int64) { a, b := int64(1000), int64(140); return &a, &b }, pressure: func() (string, error) { return "some avg60=7.5", nil }, logf: func(string, ...any) {}} |
| + now := time.Unix(1793745600, 0) |
| + for step := 0; step < 4; step++ { |
| + if step == 1 { |
| + a.state.Observe(groupadmission.Facts{EnvLoaded: true, Reconciled: true, RolePublished: true, TerminationStarted: true}) |
| + if err := a.state.Admit(t.Context(), nil, nil, func() bool { return true }); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if step == 2 { |
| + clockErr = errors.New("clock unavailable") |
| + } |
| + if step == 3 { |
| + clockErr = nil |
| + } |
| + w.tick(t.Context(), now) |
| + in := put.calls[step] |
| + memory := float64(140) |
| + memory = memory / 1000 * 100 |
| + legacy := memwatchData("i-group", memory, 7.5, true, now) |
| + if !reflect.DeepEqual(in.MetricData[:2], legacy.MetricData) { |
| + t.Fatal("InstanceId metric bytes changed") |
| + } |
| + seen := map[string]float64{} |
| + for _, d := range in.MetricData[2:] { |
| + var ds []string |
| + for _, v := range d.Dimensions { |
| + ds = append(ds, *v.Name+"="+*v.Value) |
| + } |
| + seen[*d.MetricName+":"+strings.Join(ds, ",")] = *d.Value |
| + if !d.Timestamp.Equal(now) { |
| + t.Fatal("timestamp changed") |
| + } |
| + } |
| + admitted := float64(0) |
| + if step > 0 { |
| + admitted = 1 |
| + } |
| + want := map[string]float64{ |
| + "Admitted:Deployment=dev-platform,Region=uk": admitted, |
| + "MemAvailablePercent:AutoScalingGroupName=carlos-dev-uk-group": memory, |
| + "Admitted:AutoScalingGroupName=carlos-dev-uk-group": admitted, |
| + "ClockSamplePresent:AutoScalingGroupName=carlos-dev-uk-group": 1, |
| + "ClockSamplePresent:AutoScalingGroupName=carlos-dev-uk-group,InstanceId=i-group": 1, |
| + } |
| + if step == 2 { |
| + want["ClockSamplePresent:AutoScalingGroupName=carlos-dev-uk-group"] = 0 |
| + want["ClockSamplePresent:AutoScalingGroupName=carlos-dev-uk-group,InstanceId=i-group"] = 0 |
| + } else { |
| + want["ClockOffsetSeconds:Deployment=dev-platform,Region=uk"] = 1.25 |
| + want["ClockOffsetSeconds:AutoScalingGroupName=carlos-dev-uk-group"] = 1.25 |
| + want["ClockOffsetSeconds:AutoScalingGroupName=carlos-dev-uk-group,InstanceId=i-group"] = 1.25 |
| + } |
| + if !reflect.DeepEqual(seen, want) { |
| + t.Fatalf("step %d metrics=%v want=%v", step, seen, want) |
| + } |
| + } |
| + if len(put.calls) != 4 || calls != 4 { |
| + t.Fatalf("puts=%d clock=%d", len(put.calls), calls) |
| + } |
| +} |
| + |
| +func TestGroupAlarmProducers(t *testing.T) { |
| + b, err := os.ReadFile("../../infra/modules/region-host/group_alarms.tf") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, name := range []string{`"group_capacity"`, `"group_memory"`, `"group_clock"`, `"group_clock_missing"`, `"group_launch_failed"`} { |
| + if !strings.Contains(string(b), name) { |
| + t.Errorf("missing producer-backed alarm %s", name) |
| + } |
| + } |
| + if strings.Contains(string(b), `metric_name = "EligibleBoxes"`) { |
| + t.Fatal("P2b has no producer yet") |
| + } |
| + testGroupMetricsBatch(t) |
| +} |
| + |
| +func TestGroupMetricsRequireVerifiedLaunch(t *testing.T) { |
| + env := map[string]string{"CARLOS_GROUP_ADMISSION": "1", "CARLOS_GROUP_NAME": "untrusted-shell-name", "CARLOS_DEPLOYMENT_BUCKET": "dev-platform"} |
| + if m := admissionMetricsFromEnv(func(k string) string { return env[k] }, &fixedAdmission{group: true}, func(string, string) (roleRegionConfig, error) { return roleRegionConfig{RegionCode: "ie"}, nil }, nil); m != nil { |
| + t.Fatal("environment name replaced missing verified launch") |
| + } |
| +} |
| +func TestGroupMemberDiagnosticEvidence(t *testing.T) { |
| + now := time.Now() |
| + offset := 100 * time.Millisecond |
| + low := groupadmission.Observation{At: now, Admitted: true} |
| + healthy := groupadmission.Observation{At: now, Admitted: true, ClockOffset: &offset} |
| + for _, recovered := range []bool{false, true} { |
| + if recovered { |
| + low.ClockOffset = &offset |
| + } |
| + samples := append(groupMetricData(low, "g", "i-low", 14), groupMetricData(healthy, "g", "i-high", 90)...) |
| + minMemory, minPresent := 100.0, 1.0 |
| + memberPresence := map[string]float64{} |
| + offsets := map[string]bool{} |
| + for _, d := range samples { |
| + if len(d.Dimensions) == 1 { |
| + switch *d.MetricName { |
| + case "MemAvailablePercent": |
| + minMemory = min(minMemory, *d.Value) |
| + case "ClockSamplePresent": |
| + minPresent = min(minPresent, *d.Value) |
| + } |
| + } else { |
| + iid := *d.Dimensions[1].Value |
| + switch *d.MetricName { |
| + case "ClockSamplePresent": |
| + memberPresence[iid] = *d.Value |
| + case "ClockOffsetSeconds": |
| + offsets[iid] = true |
| + } |
| + } |
| + } |
| + if minMemory != 14 || memberPresence["i-high"] != 1 || offsets["i-low"] != recovered { |
| + t.Fatal("lost member evidence", memberPresence, offsets) |
| + } |
| + want := 0.0 |
| + if recovered { |
| + want = 1 |
| + } |
| + if minPresent != want || memberPresence["i-low"] != want { |
| + t.Fatal("clock recovery/unknown", minPresent, memberPresence) |
| + } |
| + // An entirely absent iid has no evidence. A healthy aggregate cannot |
| + // establish this check: the operator must compare actual membership. |
| + if _, exists := memberPresence["i-silent"]; exists { |
| + t.Fatal("fabricated silent member evidence") |
| + } |
| + } |
| +} |
diff --git a/internal/host/group_pool_test.go b/internal/host/group_pool_test.go| new file mode 100644 |
| index 000000000..1fd006d28 |
| --- /dev/null |
| +++ b/internal/host/group_pool_test.go |
| @@ -0,0 +1,109 @@ |
| +package host |
| + |
| +import ( |
| + "crypto/ed25519" |
| + "encoding/json" |
| + "fmt" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/domains" |
| + "github.com/carlosframework/platform/internal/edge" |
| + "github.com/carlosframework/platform/internal/hadeparture" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +func TestGroupPoolIsolation(t *testing.T) { |
| + t.Setenv("CARLOS_REGION_HA", "1") |
| + store := release.NewDirStore(t.TempDir()) |
| + acct := domains.Sqid(2) |
| + body, _ := json.Marshal(map[string]any{"id": 2, "sqid": acct, "name": "fixture", "created_at": time.Now()}) |
| + if _, err := store.Put(t.Context(), "accounts/"+acct+"/account.json", body, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := provision.PutManifest(t.Context(), store, acct, "shop", provision.Manifest{Schema: 1, App: "shop", Domain: "example.com"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + records := []provision.Record{} |
| + for i, pool := range []string{"", "hapair"} { |
| + r := provision.Record{Schema: 1, Host: fmt.Sprintf("host%d.example.com", i), Slug: fmt.Sprintf("host%d", i), Account: acct, App: "shop", Channel: "stable", Pool: pool, Region: "ie", HA: true, Incarnation: 1, CreatedAt: time.Now()} |
| + if err := provision.CreateRecord(t.Context(), store, r); err != nil { |
| + t.Fatal(err) |
| + } |
| + records = append(records, r) |
| + } |
| + regs := map[string]*registry.Registry{} |
| + peers := []struct { |
| + name string |
| + pools []string |
| + }{{"shared", []string{""}}, {"hapair", []string{"hapair"}}, {"combined", []string{"", "hapair"}}} |
| + for _, peer := range peers { |
| + reg := edgesTestRegistry(t) |
| + t.Run(peer.name, func(t *testing.T) { |
| + regs[peer.name] = reg |
| + if err := provision.Reconcile(t.Context(), store, reg, provision.ReconcileConfig{Region: "ie", Pools: peer.pools, DataDir: t.TempDir()}); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, r := range records { |
| + want := peer.name == "combined" || (peer.name == "shared") == (r.Pool == "") |
| + row, err := reg.Get(r.Host) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if (row != nil) != want { |
| + t.Fatalf("reconcile %s/%q row=%v", peer.name, r.Pool, row) |
| + } |
| + if got := CanAdopt(provision.DepartureHost{Host: r.Host, Kind: "instance", HA: true, Lifetime: "life", Placement: "ie", Pool: r.Pool}, LocalPolicy{Scope: hadeparture.Scope{Placement: "ie"}, Pools: peer.pools}); got != want { |
| + t.Fatalf("CanAdopt %s/%q=%v", peer.name, r.Pool, got) |
| + } |
| + } |
| + var last []byte |
| + yes, no := true, false |
| + |
| + ident := edgesFile{Box: peer.name, Region: "eu-west-1", Placement: "ie", DataBucket: "data", SecretsKeyFP: "shared", HibernationConfigured: true, Capabilities: []string{capRegionHA1}, BoxRole: "serve", Admitted: &yes, Drained: &no, Headroom: &edgeHeadroom{MemFreeMiB: 300, MemTotalMiB: 1000, DiskFreeMiB: 300, DiskTotalMiB: 1000}} |
| + if err := edgesFileWrite(t.Context(), store, reg, ident, "127.0.0.1", &last, true); err != nil { |
| + t.Fatal(err) |
| + } |
| + }) |
| + } |
| + if _, err := store.Put(t.Context(), "control/edge-mesh-key", []byte(strings.Repeat("a", 64)), ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + // A combined reader must see both pools without letting one pool's peers |
| + // become candidates for the other. The fold uses real published records. |
| + reg := regs["combined"] |
| + e, err := edge.New(reg, nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + edge.WithBoxLabel("combined")(e) |
| + e.EnableStatic(store, ed25519.NewKeyFromSeed(make([]byte, 32)).Public().(ed25519.PublicKey), t.TempDir()) |
| + m := coldEdgeHomeMap(e) |
| + if m == nil { |
| + t.Fatal("map not armed") |
| + } |
| + if err := coldHomeRefresh(m, t.Context()); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, r := range records { |
| + row, err := reg.Get(r.Host) |
| + if err != nil || row == nil { |
| + t.Fatal(row, err) |
| + } |
| + snap := coldHomeSnapshot(m, *row, time.Now()) |
| + names := map[string]bool{} |
| + for _, c := range snap.Serving { |
| + names[c.BoxID] = true |
| + } |
| + want := "shared" |
| + if r.Pool != "" { |
| + want = "hapair" |
| + } |
| + if !snap.Usable || len(names) != 2 || !names["combined"] || !names[want] { |
| + t.Fatalf("wakeSnapshot %q: %+v", r.Pool, snap) |
| + } |
| + } |
| +} |
diff --git a/internal/host/memwatch.go b/internal/host/memwatch.go| index 79979fd53..9dde5fa21 100644 |
| --- a/internal/host/memwatch.go |
| +++ b/internal/host/memwatch.go |
| @@ -112,7 +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. |
| - cfg = memwatchAWSConfig(cfg, readPlacementRegion()) |
| + cfg = groupMetricsAWSConfig(cfg, readPlacementRegion(), groupReferenced(os.Getenv)) |
| id, err := imdsInstanceID() |
| if err != nil { |
| log.Printf("agent: memwatch disabled: instance id: %v", err) |
| @@ -129,7 +129,7 @@ func memwatchLoop() { |
| return readChronyTracking(ctx, exec.CommandContext) |
| }) |
| if os.Getenv("CARLOS_GROUP_ADMISSION") == "1" && w.admission == nil { |
| - log.Print("memwatch: admission metrics are disabled. fixed admission, CARLOS_DEPLOYMENT_BUCKET and a valid region configuration are required") |
| + log.Print("memwatch: admission metrics are disabled. Admission state, deployment bucket, region configuration and a verified launch binding for group boxes 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) { |
| @@ -160,6 +160,9 @@ func (w *memwatch) tick(ctx context.Context, now time.Time) { |
| w.logf("memwatch: clock reading unavailable for this box: %v", err) |
| } |
| input.MetricData = append(input.MetricData, admissionMetricData(observation)...) |
| + if w.admission.group != "" { |
| + input.MetricData = append(input.MetricData, groupMetricData(observation, w.admission.group, w.instanceID, availPct)...) |
| + } |
| } |
| _, err := w.put.PutMetricData(ctx, input) |
| switch { |
diff --git a/internal/sim/regionha/actions_test.go b/internal/sim/regionha/actions_test.go| index 43f864cf1..8180914b1 100644 |
| --- a/internal/sim/regionha/actions_test.go |
| +++ b/internal/sim/regionha/actions_test.go |
| @@ -153,6 +153,10 @@ type wakeOpts struct { |
| // wake is a request's wake of h at b, which has no entry for it. pre is a |
| // round 0 the box already read (wake-begin). It reports what happened. |
| func (w *world) wake(b *box, h string, o wakeOpts, pre *pending) string { |
| + if on("group-pre-admission-service") && !w.groupAllowed(b) { |
| + w.event("group-start-refused") |
| + return "admission" |
| + } |
| if pre == nil && w.consultsStaleIndex(b, h) { |
| // The box's index says legacy: the legacy acquire classifies the |
| // lock first (takeLegacy over a present lock, createLease over an |
| @@ -743,6 +747,9 @@ func (w *world) crash(b *box) { |
| // die is every death of b's agent process: the uploads it had in flight |
| // are left to land (inFlight), and its memory goes. |
| func (w *world) die(b *box) { |
| + if b.Group != nil { |
| + b.Group.state.Close() |
| + } |
| w.inFlight(b) |
| w.landLate() |
| b.Agent = agentDown |
diff --git a/internal/sim/regionha/duties_model_test.go b/internal/sim/regionha/duties_model_test.go| index edd8ccc49..e08bdf7ee 100644 |
| --- a/internal/sim/regionha/duties_model_test.go |
| +++ b/internal/sim/regionha/duties_model_test.go |
| @@ -7,6 +7,7 @@ import ( |
| "github.com/carlosframework/platform/internal/activator" |
| "github.com/carlosframework/platform/internal/boxid" |
| + "github.com/carlosframework/platform/internal/groupadmission" |
| "github.com/carlosframework/platform/internal/hadeparture" |
| "github.com/carlosframework/platform/internal/hafresh" |
| hostpkg "github.com/carlosframework/platform/internal/host" |
| @@ -44,6 +45,9 @@ type dutyScan struct { |
| receiptUntil int |
| } |
| type dutyBox struct { |
| + hints map[int]int |
| + receipts int |
| + admission *groupadmission.State |
| self hafresh.Self |
| alive, running bool |
| pools []string |
| @@ -162,6 +166,19 @@ func (d *dutyWorld) tick() { |
| continue |
| } |
| d.refresh(b) |
| + if b.admission != nil && !b.admission.Admitted() { |
| + if b.hints == nil { |
| + b.hints = map[int]int{} |
| + } |
| + for _, dead := range d.order { |
| + if !d.lostEvent && d.now >= b.hints[dead] { |
| + b.hints[dead] = d.now + 4 |
| + b.receipts++ |
| + d.parent.event("group-closed-receive") |
| + } |
| + } |
| + continue |
| + } |
| for _, dead := range d.order { |
| age := d.now-d.dead[dead] >= 31 |
| event := !d.lostEvent && on("ignore-termination-event") |
| @@ -172,7 +189,7 @@ func (d *dutyWorld) tick() { |
| d.enroll(b, dead) |
| } |
| } |
| - if !b.running { |
| + if !b.running || b.admission != nil && !b.admission.Admitted() { |
| continue |
| } |
| // Rotate fairly, including permanently blocked departures. |
| @@ -645,7 +662,7 @@ func runDutyScenario(w *world, scenario string, seed int64) { |
| if scenario == "coverage" { |
| for _, b := range d.boxes { |
| if b.alive { |
| - if !b.running { |
| + if !b.running || b.admission != nil && !b.admission.Admitted() { |
| d.fail("coverage stopped consumer") |
| } |
| if peer := b.scans[1]; peer == nil || peer.scanned == 0 { |
diff --git a/internal/sim/regionha/group_admission_test.go b/internal/sim/regionha/group_admission_test.go| new file mode 100644 |
| index 000000000..a9d94bdb0 |
| --- /dev/null |
| +++ b/internal/sim/regionha/group_admission_test.go |
| @@ -0,0 +1,387 @@ |
| +package regionha |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "math/rand" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/groupadmission" |
| + "github.com/carlosframework/platform/internal/lbhealth" |
| +) |
| + |
| +// The receipt and attempt fields survive process replacement. They model the |
| +// Task 3 journal, not an extra authority source for root or lease takeover. |
| +type groupMember struct { |
| + state *groupadmission.State |
| + health *lbhealth.State |
| + phase string |
| + deadline time.Time |
| + inServiceAt time.Time |
| + receipt, unknown, failed bool |
| + attempts, returns int |
| + firstDirect bool |
| + maintenance string |
| + writes int |
| + desired, minimum, maximum, total int |
| +} |
| + |
| +func (w *world) groupBoot(b *box) { |
| + b.Group = &groupMember{state: &groupadmission.State{}, health: &lbhealth.State{}, phase: "Pending:Wait", deadline: w.now().Add(900 * time.Second), desired: len(w.boxes), minimum: len(w.boxes), maximum: len(w.boxes), total: len(w.boxes)} |
| + w.event("group-boot") |
| +} |
| +func (w *world) groupFacts(b *box) { |
| + g := b.Group |
| + g.state.Observe(groupadmission.Facts{EnvLoaded: true, Reconciled: true, RolePublished: true, TerminationStarted: true}) |
| + g.health.SetHosting(true) |
| + g.health.MapLoaded() |
| + g.health.KeyLoaded() |
| + g.health.CertsLoaded() |
| + w.groupBeat(b) |
| +} |
| +func (w *world) groupBeat(b *box) { |
| + g := b.Group |
| + g.health.EdgeBeat(w.now()) |
| + g.health.RefreshAttempted(w.now()) |
| + at := w.now() |
| + g.health.SetActivator(func() time.Time { return at }) |
| +} |
| +func (w *world) groupHealthy(b *box) bool { |
| + return b.Agent == agentUp && len(b.Group.health.Failing(w.now())) == 0 |
| +} |
| + |
| +type groupCompletion func(context.Context, groupadmission.Launch) error |
| + |
| +func (f groupCompletion) Complete(c context.Context, l groupadmission.Launch) error { return f(c, l) } |
| + |
| +func (w *world) groupAdmit(b *box, outcome string) { |
| + g := b.Group |
| + if g.failed || g.unknown || !w.now().Before(g.deadline) && !g.receipt { |
| + return |
| + } |
| + complete := groupCompletion(func(context.Context, groupadmission.Launch) error { |
| + if !w.groupHealthy(b) { |
| + w.fail("A1", "completion while local health failed") |
| + } |
| + if g.receipt { |
| + return nil |
| + } |
| + if g.attempts == 4 { |
| + return errors.New("exhausted") |
| + } |
| + g.attempts++ |
| + switch outcome { |
| + case "rejected": |
| + w.event("group-hook-rejected") |
| + return errors.New("rejected") |
| + case "lost": |
| + g.unknown = true |
| + g.phase = "InService" |
| + g.inServiceAt = w.now() |
| + w.event("group-response-lost") |
| + return errors.New("unknown") |
| + } |
| + g.receipt = true |
| + g.phase = "InService" |
| + g.inServiceAt = w.now() |
| + w.event("group-hook-completed") |
| + return nil |
| + }) |
| + _ = g.state.Admit(context.Background(), &groupadmission.Launch{Group: "group", Hook: "launch", Instance: b.Self.IID}, complete, func() bool { return !on("group-failed-health-completion") || w.groupHealthy(b) }) |
| + if g.state.Admitted() { |
| + w.event("group-admitted") |
| + } |
| +} |
| +func (w *world) groupAllowed(b *box) bool { return b.Group == nil || b.Group.state.Admitted() } |
| + |
| +// Maintenance has fixed total/max membership and a separate return action. |
| +// No drain is modeled: entry requires no local work, then an explicit operator |
| +// Standby/deregistration readback before mutation and a fresh process check. |
| +func (w *world) groupStandby(b *box) bool { |
| + g := b.Group |
| + if g == nil || !g.state.Admitted() || g.phase != "InService" || len(b.Entries) != 0 { |
| + return false |
| + } |
| + peerReady := false |
| + for _, peer := range w.boxes { |
| + if peer != b && peer.Group != nil && peer.Group.state.Admitted() && w.groupHealthy(peer) { |
| + peerReady = true |
| + } |
| + if peer != b && peer.Group != nil && peer.Group.maintenance != "" { |
| + return false |
| + } |
| + } |
| + if !peerReady { |
| + return false |
| + } |
| + g.minimum-- |
| + g.desired-- |
| + g.writes += 2 |
| + g.phase = "Standby" |
| + g.maintenance = "mutation" |
| + g.state.Close() |
| + g.state = &groupadmission.State{} |
| + g.health = &lbhealth.State{} |
| + b.PID = w.newPID() |
| + w.event("group-maintenance-mutation") |
| + return true |
| +} |
| +func (w *world) groupReturn(b *box, pending, lose bool) { |
| + g := b.Group |
| + if g.maintenance == "mutation" { |
| + if !g.state.Admitted() || !w.groupHealthy(b) { |
| + return |
| + } |
| + g.maintenance = "verify" |
| + } |
| + if g.maintenance == "verify" { |
| + g.desired++ |
| + g.writes++ |
| + g.maintenance = "return" |
| + g.phase = "InService" |
| + if pending { |
| + g.phase = "Pending:Wait" |
| + } |
| + if lose { |
| + w.event("group-exit-response-lost") |
| + return |
| + } |
| + } |
| + if g.maintenance != "return" { |
| + return |
| + } |
| + if !g.state.Admitted() || !w.groupHealthy(b) { |
| + g.maintenance = "failed" |
| + w.event("group-return-failed") |
| + return |
| + } |
| + if g.phase == "Pending:Wait" { |
| + // Receipt only suppresses the ORIGINAL box completion. Task 7 owns this. |
| + g.returns++ |
| + g.phase = "InService" |
| + w.event("group-return-continue") |
| + } else { |
| + w.event("group-return-no-hook") |
| + } |
| + g.minimum++ |
| + g.writes++ |
| + g.maintenance = "revoked" |
| + if g.total != len(w.boxes) || g.maximum != g.total || g.minimum != g.total || g.desired != g.total || g.writes != 4 { |
| + w.fail("T1", "maintenance changed membership or replayed a write") |
| + } |
| +} |
| + |
| +func groupAdmissionWitness(t *testing.T, w *world) { |
| + b := w.boxes[0] |
| + w.groupBoot(b) |
| + w.wake(b, w.hosts[0], wakeOpts{}, nil) |
| + w.check() |
| +} |
| +func groupHealthWitness(t *testing.T, w *world) { |
| + b := w.boxes[0] |
| + w.groupBoot(b) |
| + w.groupFacts(b) |
| + b.Group.health.SetActivator(nil) |
| + w.groupAdmit(b, "") |
| +} |
| +func TestGroupAdmissionModel(t *testing.T) { |
| + for _, tc := range []struct { |
| + name string |
| + run func(*testing.T, *world) |
| + }{{"pre-admission-service", groupAdmissionWitness}, {"failed-health-completion", groupHealthWitness}} { |
| + t.Run(tc.name, func(t *testing.T) { |
| + w := newWitness() |
| + tc.run(t, w) |
| + if len(w.violations) > 0 { |
| + t.Fatal(w.violations) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func runGroupScenario(parent *world, seed int64) { |
| + w := newWorldN(seed, rand.New(rand.NewSource(seed)), 2+int(seed%4), []string{"group-host"}) |
| + w.scripted = true |
| + a, b := w.boxes[0], w.boxes[1] |
| + w.groupBoot(a) |
| + w.groupBoot(b) |
| + // Deliver to the existing duty model before admission; Started is not |
| + // permission to import, deliver or acknowledge. |
| + d := newDutyWorld(w, seed) |
| + d.chaos = false |
| + if len(d.boxes) < 3 { |
| + d.addBox(2) |
| + } |
| + d.boxes[1].admission = a.Group.state |
| + d.terminate(0) |
| + for i := 0; i < 5; i++ { |
| + d.tick() |
| + } |
| + s := d.boxes[1].scans[0] |
| + if s != nil || d.boxes[1].receipts != 2 { |
| + w.fail("I6", "closed member imported or acknowledged departure") |
| + } |
| + w.event("group-pre-admission-departure") |
| + // Shuffle startup facts; no partial prefix can serve or complete. |
| + facts := []groupadmission.Facts{{EnvLoaded: true}, {Reconciled: true}, {RolePublished: true}, {TerminationStarted: true}} |
| + for _, i := range w.rng.Perm(len(facts)) { |
| + a.Group.state.Observe(facts[i]) |
| + w.groupAdmit(a, "") |
| + w.wake(a, w.hosts[0], wakeOpts{}, nil) |
| + w.advance(1) |
| + } |
| + w.groupFacts(a) |
| + outcome := "" |
| + switch seed % 4 { |
| + case 0: |
| + outcome = "lost" |
| + case 1: |
| + outcome = "rejected" |
| + } |
| + for i := 0; i < 4; i++ { |
| + w.groupAdmit(a, outcome) |
| + } |
| + if outcome != "" { |
| + attempts := a.Group.attempts |
| + // New process retains ambiguous/exhausted journal state. |
| + a.Group.state = &groupadmission.State{} |
| + d.boxes[1].admission = a.Group.state |
| + w.groupFacts(a) |
| + w.groupAdmit(a, outcome) |
| + if a.Group.attempts != attempts { |
| + w.fail("A1", "restart reset hook attempt journal") |
| + } |
| + if a.Group.state.Admitted() { |
| + w.fail("A1", "failed boot admitted") |
| + } |
| + for i := 0; i < 5; i++ { |
| + d.tick() |
| + } |
| + if d.boxes[1].receipts < 3 || d.boxes[1].scans[0] != nil { |
| + w.fail("I6", "closed redelivery gained duty authority") |
| + } |
| + w.event("group-closed-redelivery") |
| + w.advance(16) |
| + w.groupProviderStep(a) |
| + if !w.isTerminated(a) { |
| + w.fail("A1", "failed boot was not replaced after deadline/health grace") |
| + } |
| + d.terminate(1) |
| + } else { |
| + // First actual service is direct, before any NLB observation. A hang |
| + // doesn't grant takeover; confirmation still waits out the existing lease. |
| + w.wake(a, w.hosts[0], wakeOpts{}, nil) |
| + if a.Entries[w.hosts[0]] == nil { |
| + w.fail("I5", "admitted direct service did not start") |
| + } |
| + a.Group.firstDirect = true |
| + w.event("group-first-direct-service") |
| + w.hang(a, ttlTicks+10) |
| + w.groupFacts(b) |
| + w.groupAdmit(b, "") |
| + w.advance(3) |
| + w.groupProviderStep(a) |
| + if !w.isTerminated(a) { |
| + w.fail("I5", "hung first service was not replaced after health grace") |
| + } |
| + if w.wake(b, w.hosts[0], wakeOpts{}, nil) == "served" { |
| + w.fail("I3", "termination skipped remaining lease") |
| + } |
| + w.advance(ttlTicks + 12) |
| + w.groupBeat(b) |
| + w.wake(b, w.hosts[0], wakeOpts{}, nil) |
| + if b.Entries[w.hosts[0]] == nil { |
| + w.fail("I5", "first-service hang did not recover after lease and confirmation") |
| + } |
| + w.event("group-first-direct-hang-recovered") |
| + } |
| + // Existing I6 model finishes the retained journal, using real CanAdopt, |
| + // DecideDuty and CanCompleteDeparture. A failed recipient does not ack it. |
| + // Every surviving group recipient either admitted above or retains its |
| + // closed gate. The other eligible fixed recipient can finish a failed boot's work. |
| + for i := 0; i < 260; i++ { |
| + d.tick() |
| + } |
| + d.checkDelivered() |
| + // Separate idle same-iid transaction; no simulated drain completion. |
| + m := newWorldN(seed, rand.New(rand.NewSource(seed)), 2, []string{"maintenance"}) |
| + m.scripted = true |
| + member := m.boxes[0] |
| + m.groupBoot(m.boxes[1]) |
| + m.groupFacts(m.boxes[1]) |
| + m.groupAdmit(m.boxes[1], "") |
| + m.groupBoot(member) |
| + m.groupFacts(member) |
| + m.groupAdmit(member, "") |
| + if !m.groupStandby(member) { |
| + m.fail("T1", "could not enter maintenance") |
| + } |
| + m.advance(16) |
| + m.groupProviderStep(member) |
| + if member.Group.phase != "Standby" { |
| + m.fail("T1", "unready timeout left Standby") |
| + } |
| + m.groupFacts(member) |
| + m.groupAdmit(member, "") |
| + pending := seed%2 == 0 |
| + m.groupReturn(member, pending, true) |
| + m.groupBeat(member) |
| + m.groupReturn(member, pending, false) |
| + if member.Group.attempts != 1 || member.Group.returns != map[bool]int{false: 0, true: 1}[pending] { |
| + m.fail("T1", "original receipt suppressed return or repeated boot completion") |
| + } |
| + for _, x := range []*world{w, m} { |
| + for k, v := range x.events { |
| + parent.events[k] += v |
| + } |
| + for _, v := range x.violations { |
| + parent.violations = append(parent.violations, v) |
| + } |
| + parent.trace = append(parent.trace, x.trace...) |
| + } |
| +} |
| + |
| +func init() { |
| + allRules = append(allRules, "group-pre-admission-service", "group-failed-health-completion") |
| + witnesses = append(witnesses, witness{rule: "group-pre-admission-service", needs: "group-pre-admission-service", want: "A1", run: groupAdmissionWitness}, witness{rule: "group-failed-health-completion", needs: "group-failed-health-completion", want: "A1", run: groupHealthWitness}) |
| +} |
| +func TestGroupSimulationScenarios(t *testing.T) { |
| + events := map[string]int{} |
| + for seed := int64(1); seed <= 16; seed++ { |
| + w := newWitness() |
| + runGroupScenario(w, seed) |
| + for k, v := range w.events { |
| + events[k] += v |
| + } |
| + if len(w.violations) > 0 { |
| + t.Errorf("seed %d: %v", seed, w.violations) |
| + } |
| + } |
| + for _, event := range []string{"group-boot", "group-pre-admission-departure", "group-closed-receive", "group-closed-redelivery", "group-hook-rejected", "group-response-lost", "group-default-abandon", "group-admitted", "group-first-direct-service", "group-first-direct-hang-recovered", "group-unhealthy-replacement", "group-maintenance-mutation", "group-return-no-hook", "group-return-continue", "group-exit-response-lost"} { |
| + if events[event] == 0 { |
| + t.Errorf("scenario never reached %s", event) |
| + } |
| + } |
| +} |
| + |
| +// Provider timing is model time, not a claim about measured AWS replacement. |
| +// Lost success is already InService: replacement follows failed health, not |
| +// a fictitious default ABANDON of a completed hook. S3 is never an input. |
| +func (w *world) groupProviderStep(b *box) { |
| + g := b.Group |
| + if g.phase == "Standby" || w.isTerminated(b) { |
| + return |
| + } |
| + if g.phase == "Pending:Wait" && !w.now().Before(g.deadline) { |
| + g.failed = true |
| + w.terminate(b) |
| + w.event("group-default-abandon") |
| + return |
| + } |
| + if g.phase == "InService" && w.now().Sub(g.inServiceAt) >= 80*time.Second && (!g.state.Admitted() || !w.groupHealthy(b)) { |
| + g.failed = true |
| + w.terminate(b) |
| + w.event("group-unhealthy-replacement") |
| + } |
| +} |
diff --git a/internal/sim/regionha/invariants_test.go b/internal/sim/regionha/invariants_test.go| index da0a9ed9a..903c22e0a 100644 |
| --- a/internal/sim/regionha/invariants_test.go |
| +++ b/internal/sim/regionha/invariants_test.go |
| @@ -93,6 +93,9 @@ func (w *world) checkHolder(b *box, pid int, h, what string) { |
| // checkServe is I2, as b starts serving h. |
| func (w *world) checkServe(b *box, h string) { |
| + if !w.groupAllowed(b) { |
| + w.fail("A1", "tenant served before group admission") |
| + } |
| l, p := b.Local[h], w.s3[h] |
| if l.TXID != p.MaxTXID || l.Ver != p.HeadVer || l.Files != p.Files { |
| w.fail("I2", "box%d serves %s from txid %d (content %d, files %+v), but S3 holds txid %d (content %d, files %+v) (lock %s)", |
diff --git a/internal/sim/regionha/world_test.go b/internal/sim/regionha/world_test.go| index af10cd8ee..cb3057978 100644 |
| --- a/internal/sim/regionha/world_test.go |
| +++ b/internal/sim/regionha/world_test.go |
| @@ -194,6 +194,7 @@ func (a agentState) String() string { |
| // host legacy. Owed is the obligation store in memory, Disk what of it is |
| // on disk. |
| type box struct { |
| + Group *groupMember |
| Placement *placementState |
| ID int |
| Self hafresh.Self |
| @@ -714,6 +715,7 @@ func runSeed(seed int64, verbose bool) *world { |
| w.final() |
| scenarios := []string{"held", "released", "scanner-death", "duplicate-import", "lost-event", "unsynced", "future", "sequential", "coverage", "pool", "missing-edges", "interim", "delete-denied", "inventory", "fixed", "early"} |
| runDutyScenario(w, scenarios[int(seed)%len(scenarios)], seed) |
| + runGroupScenario(w, seed) |
| return w |
| } |