From 278cc20a8e95a24b9d23278fdab9851fddf236ff Mon Sep 17 00:00:00 2001 From: Witness Patrol Date: Sat, 21 Nov 2026 14:07:20 -0600 Subject: [PATCH 1/9] feat(gcpsecretmanager): regional secrets validate their location A regional resource name with a location that has no regional endpoint is rejected. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01NVwMjLknMM32Xje6Qik6wY --- services/gcpsecretmanager/PARITY.md | 4 +- services/gcpsecretmanager/location_test.go | 52 ++++++++++++++++++++++ services/gcpsecretmanager/locations.go | 24 ++++++++++ services/gcpsecretmanager/store.go | 8 ++++ 4 files changed, 86 insertions(+), 2 deletions(-) create mode 100644 services/gcpsecretmanager/location_test.go create mode 100644 services/gcpsecretmanager/locations.go diff --git a/services/gcpsecretmanager/PARITY.md b/services/gcpsecretmanager/PARITY.md index 5697521be8..a04cc5feab 100644 --- a/services/gcpsecretmanager/PARITY.md +++ b/services/gcpsecretmanager/PARITY.md @@ -32,8 +32,7 @@ families: auth: {status: partial, note: "No request is authenticated or authorised; IAM policies are stored but not enforced."} observability: {status: partial, note: "One lockmetrics.RWMutex guards all state; RPC failures are logged at debug. gRPC calls are not fed to the shared telemetry operation metrics."} audit_logs: {status: ok, note: "Create/Update/Delete/Add/Enable/Disable/Destroy/SetIamPolicy are Admin Activity records and AccessSecretVersion a Data Access read (google.cloud.secretmanager.v1.SecretManagerService.*) written through pkgs/gcpaudit when a sink is set. Request and response bodies, which can hold secret payloads, are never logged."} -items_still_open: - - "Regional secret location names are not validated against Secret Manager's supported-region list: no verified catalog exists in the repo and rejecting a valid region would break working clients." +items_still_open: [] leaks: {status: clean, note: "Background resources are the grpc.Server and the expiry janitor goroutine, both stopped and joined by Shutdown."} --- @@ -44,5 +43,6 @@ Pass 2026-11-13: customer-managed keys resolve against gcpkms when wired (intern ## Emulator choices where the vendor is silent - SECRET_ROTATE delivery is a single best-effort publish per due time (no 7-day retry), failures are dropped; a one-shot rotation clears next_rotation_time (inferred, not documented); TOPIC_CONFIGURED and other event types are not sent. +- Regional secret location names are checked against the regional endpoint list in google.golang.org/api@v0.304.0 secretmanager/v1/secretmanager-api.json (52 entries, including the us/eu/ca/in/ch/sa multi-regions); an unlisted location is INVALID_ARGUMENT, a code no vendor page gives. Replica locations of user_managed replication are not checked. - Regional secrets share the one listener; the secretmanager..rep.googleapis.com authority is honoured only for the location check. - Managed rotation (EnableManagedRotation, RotateSecret) sets the Cloud SQL user password through the gcpsql emulator when wired, before the new version is added; instance_id may be a bare id or project:region:instance, and the user must already exist (FAILED_PRECONDITION otherwise). Without gcpsql only the secret version is written. diff --git a/services/gcpsecretmanager/location_test.go b/services/gcpsecretmanager/location_test.go new file mode 100644 index 0000000000..fa2d07ca5c --- /dev/null +++ b/services/gcpsecretmanager/location_test.go @@ -0,0 +1,52 @@ +package gcpsecretmanager_test + +import ( + "testing" + + "cloud.google.com/go/secretmanager/apiv1/secretmanagerpb" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +func TestRegionalLocationValidation(t *testing.T) { + t.Parallel() + + e := newEnv(t) + + for name, tc := range map[string]struct { + location string + code codes.Code + }{ + "region": {"europe-west4", codes.OK}, + "multi region": {"us", codes.OK}, + "unknown": {"mars-north1", codes.InvalidArgument}, + "global": {"global", codes.InvalidArgument}, + "uppercase": {"US-CENTRAL1", codes.InvalidArgument}, + "zone not name": {"us-central1-a", codes.InvalidArgument}, + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + + parent := proj + "/locations/" + tc.location + + _, err := e.client.CreateSecret(t.Context(), &secretmanagerpb.CreateSecretRequest{ + Parent: parent, SecretId: "loc", + }) + assert.Equal(t, tc.code, status.Code(err)) + + _, err = e.client.GetSecret(t.Context(), &secretmanagerpb.GetSecretRequest{Name: parent + "/secrets/loc"}) + if tc.code == codes.OK { + require.NoError(t, err) + } else { + assert.Equal(t, codes.InvalidArgument, status.Code(err)) + } + + _, err = e.client.ListSecrets(t.Context(), &secretmanagerpb.ListSecretsRequest{Parent: parent}).Next() + if tc.code != codes.OK { + assert.Equal(t, codes.InvalidArgument, status.Code(err)) + } + }) + } +} diff --git a/services/gcpsecretmanager/locations.go b/services/gcpsecretmanager/locations.go new file mode 100644 index 0000000000..0d9a21c7ee --- /dev/null +++ b/services/gcpsecretmanager/locations.go @@ -0,0 +1,24 @@ +package gcpsecretmanager + +// knownLocation reports whether loc has a Secret Manager regional endpoint. +// Source: google.golang.org/api@v0.304.0 secretmanager/v1/secretmanager-api.json "endpoints". +func knownLocation(loc string) bool { + switch loc { + case "africa-south1", "asia-east1", "asia-east2", "asia-northeast1", + "asia-northeast2", "asia-northeast3", "asia-south1", "asia-south2", + "asia-southeast1", "asia-southeast2", "asia-southeast3", "australia-southeast1", + "australia-southeast2", "ca", "ch", "eu", + "europe-central2", "europe-north1", "europe-north2", "europe-southwest1", + "europe-west1", "europe-west10", "europe-west12", "europe-west15", + "europe-west2", "europe-west3", "europe-west4", "europe-west6", + "europe-west8", "europe-west9", "in", "me-central1", + "me-central2", "me-west1", "northamerica-northeast1", "northamerica-northeast2", + "northamerica-south1", "sa", "southamerica-east1", "southamerica-west1", + "us", "us-central1", "us-central2", "us-east1", + "us-east4", "us-east5", "us-east7", "us-south1", + "us-west1", "us-west2", "us-west3", "us-west4": + return true + default: + return false + } +} diff --git a/services/gcpsecretmanager/store.go b/services/gcpsecretmanager/store.go index 1d9c2a07d0..baecf7f3f0 100644 --- a/services/gcpsecretmanager/store.go +++ b/services/gcpsecretmanager/store.go @@ -162,6 +162,10 @@ func parseProject(parent string) (string, error) { "Invalid parent %q. Expected projects/{project} or projects/{project}/locations/{location}.", parent) } + if regional && !knownLocation(parts[3]) { + return "", errInvalid("Location %q is not a supported Secret Manager location.", parts[3]) + } + return strings.TrimPrefix(parent, "projects/"), nil } @@ -183,6 +187,10 @@ func parseSecretName(name string) (string, error) { "projects/{project}/locations/{location}/secrets/{secret}.", name) } + if regional && !knownLocation(parts[3]) { + return "", errInvalid("Location %q is not a supported Secret Manager location.", parts[3]) + } + return name, nil } From 9492c5e7d564b4a6668bc263797956046d66c2b9 Mon Sep 17 00:00:00 2001 From: Witness Patrol Date: Sat, 21 Nov 2026 14:07:47 -0600 Subject: [PATCH 2/9] feat(connect): log the Cases attachment an upload against a case would make Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01NVwMjLknMM32Xje6Qik6wY --- services/connect/PARITY.md | 7 ++-- services/connect/attached_scan_log_test.go | 42 ++++++++++++++++++++++ services/connect/attachedfiles.go | 5 +++ 3 files changed, 52 insertions(+), 2 deletions(-) diff --git a/services/connect/PARITY.md b/services/connect/PARITY.md index 630532372f..886ff758b4 100644 --- a/services/connect/PARITY.md +++ b/services/connect/PARITY.md @@ -408,11 +408,10 @@ items_still_open: - "EvaluationForms: contact evaluations are never auto-evaluated (no AI or Contact Lens answers) and the Acknowledgement, Review and CalibrationSessionId metadata members are never set because the pinned SDK has no operation that changes them; POINTS_BASED scoring ignores per-question PointsConfiguration (bonus, min/max points) and the weighted-score formulas are unverified against the real service" - "TestCases: executions are recorded (Start/Stop/List/ListRecords/GetSummary) but never leave INITIATED on their own, because the emulator has no flow test runner: no PASSED/FAILED outcome, observations or ObservationSummary are ever produced (the test case Content grammar is not published, API_CreateTestCase only calls it a JSON string, and the VOICE_CALL and CHAT entry points need a media plane to drive a flow)" - "Notifications: push registrations are stored but no push is ever sent (nothing triggers one: there is no chat message plane); notifications from rules or the system are not generated" - - "AttachedFiles: Cases are not modeled so Cases ARNs are only shape-checked; without the S3 emulator wired the content endpoint /attached-files-content stands in for S3 pre-signed URLs" - "Contact data and participants: GetFederationToken ListRealtimeContactAnalysisSegmentsV2 SendChatIntegrationEvent UpdateParticipantAuthentication StartAssistantContact StartScreenSharing StartWebRTCContact are not routed (no chat message plane, no caller identity for federation, no Wisdom assistant, no WebRTC media plane); UpdateParticipantRoleConfig timers are stored on the contact but nothing enforces them (no chat message plane); QueuePriority and QueueTimeAdjustmentSeconds order GetContactMetrics queue positions but no routing engine assigns agents from that order, and RoutingCriteria steps are only stored" - "GetMetricDataV2: only the computed subset of metrics is available (agent-state, hold, after-contact-work, flow, campaign, evaluation, case, AI and Contact Lens metrics need signals the emulator never records), so custom metrics built on them are rejected" - "PhoneNumber import: ImportPhoneNumber needs an AWS End User Messaging (pinpoint-sms-voice-v2) phone-number inventory; the emulator has no such service and none may be added, so a number could only be fabricated" - - "SES-wired email delivery status readback and TEMPLATE outbound email (Wisdom message templates) are not modeled" + - "TEMPLATE outbound email (Wisdom message templates) is not modeled, so SendOutboundEmail and StartOutboundEmailContact accept RAW messages only" - "CloudFormation: AWS::Connect::Metric GetAtt Filters, Groupings, PrimaryEventSource, PrimaryEventSourceEffectiveTimestampType, RefreshRate and SupportedStats are not returned: the CloudFormation reference (aws-resource-connect-metric.html) names them without a value format or derivation, and the stored MetricDefinition (services/connect/metricdefs.go MetricDefinition) has no PrimaryEventSource, RefreshRate or SupportedStats; SourcePhoneNumberArn of PhoneNumber is rejected because it needs an imported number (ImportPhoneNumber item) and ClaimPhoneNumber has no source member (SDK ClaimPhoneNumberInput)" structural_gaps: - "No telephony or media plane: outbound calls are never placed, no audio flows, and contacts only change state through StopContact and UpdateContact because no agent softphone or customer endpoint exists." @@ -480,3 +479,7 @@ API_ListEvaluationFormAIVersions re-read: ContactInteractionType (AGENT|AUTOMATE ## 2026-11-20 parity pass AttachedFiles use real SigV4 pre-signed S3 URLs when S3 is wired (services/s3 PresignURL); the bucket is created on first use and signature checking follows the S3 emulator's own opt-in (PresignSecret), so size is enforced at CompleteAttachedFileUpload by HeadObject rather than by the signature when that is off. ReplicateInstance, GetCrossRegionRouting, UpdateCrossRegionRouting and TransferContact are routed; evaluation scoring applies weights, exclusions, automatic-fail targets and performance categories. + +## 2026-11-21 open-item re-check + +Attached files on a Cases ARN are recorded like any other and the emulator logs "would attach the file to the Cases case" once at upload start (no Cases service exists); standalone, the /attached-files-content endpoint serves the signed URLs and with S3 wired they are S3 pre-signed URLs. The SDK has no operation or member that returns an outbound email delivery status (the stored delivery state is internal), so no readback exists to model. diff --git a/services/connect/attached_scan_log_test.go b/services/connect/attached_scan_log_test.go index e285c7b190..64c24738e2 100644 --- a/services/connect/attached_scan_log_test.go +++ b/services/connect/attached_scan_log_test.go @@ -147,3 +147,45 @@ func TestCompleteAttachedFileUploadLogsWouldScan(t *testing.T) { }) } } + +func TestStartAttachedFileUploadLogsWouldAttachToCase(t *testing.T) { + t.Parallel() + + const caseARN = "arn:aws:cases:us-east-1:" + testAccount + ":domain/d1/case/c1" + + tests := []struct { + name string + cases bool + wantLog bool + }{ + {name: "case", cases: true, wantLog: true}, + {name: "contact"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + logs := &lockedBuf{} + e := newContactEnvOn(t, newLoggedFixture(t, logs)) + resource := caseARN + + if !tt.cases { + resource = e.contactARN(t, e.task(t)) + } + + start := e.startUpload(t, resource, "a.txt", int64(len(attachedText))) + out := logs.String() + + if !tt.wantLog { + assert.NotContains(t, out, "would attach the file") + + return + } + + assert.Equal(t, 1, strings.Count(out, "would attach the file to the Cases case")) + assert.Contains(t, out, aws.ToString(start.FileId)) + assert.Contains(t, out, caseARN) + }) + } +} diff --git a/services/connect/attachedfiles.go b/services/connect/attachedfiles.go index 7c3d24896e..c286eeffa9 100644 --- a/services/connect/attachedfiles.go +++ b/services/connect/attachedfiles.go @@ -438,6 +438,11 @@ func (b *Backend) StartAttachedFileUpload( b.attachedFiles.put(rec) + if casesARNPattern.MatchString(rec.Resource) { + logger.Load(ctx).InfoContext(ctx, "connect: would attach the file to the Cases case (no Cases service)", + "instance", inst, "file", rec.FileID, "case", rec.Resource) + } + return &AttachedFileCreated{ FileArn: rec.Arn, FileID: rec.FileID, CreationTime: rec.CreationTime, FileStatus: rec.Status, CreatedBy: rec.CreatedBy, UploadURLMetadata: upload, From 5cbee51938ac13e970d42eb09026e443bf934d41 Mon Sep 17 00:00:00 2001 From: Witness Patrol Date: Sat, 21 Nov 2026 14:08:41 -0600 Subject: [PATCH 3/9] docs(ecs): record Exec log naming as a choice the SDK and guide leave open Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01NVwMjLknMM32Xje6Qik6wY --- services/ecs/PARITY.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/services/ecs/PARITY.md b/services/ecs/PARITY.md index 265ba7e21c..209365d575 100644 --- a/services/ecs/PARITY.md +++ b/services/ecs/PARITY.md @@ -76,7 +76,7 @@ gaps: [] items_still_open: - "Docker runtime container definition: firelensConfiguration and awsfirelens log routing (a task using either fails with TaskFailedToStart instead of starting the log router) and resourceRequirements (GPU) are stored but not applied; ephemeralStorage is validated (21 to 200 GiB) and reported on the task but not enforced on disk." - "Docker runtime: Task-level cpu/memory bound every container (a container without a hard memory limit gets the task memory as its ceiling, NanoCPUs is the task vCPUs) but Docker has no task cgroup, so the sum across containers is not enforced at run time (registration rejects sums above the task values). host and none network-mode containers cannot join the link-local credentials relay, and awsvpc tasks (pause container plus task network) are never adopted after an emulator restart. Managed EBS volumes: filesystemType is not applied (the Docker volume uses the local driver), volumeInitializationRate is echo only, and StartTask and ServiceRevision do not carry volumeConfigurations." - - "ECS Exec: sessions exist only on the docker and kubernetes runtimes with the SSM service enabled (otherwise TargetNotConnectedException); the command runs as `sh -c ` through docker exec or pods/exec, and the ssmmessages IAM checks are not applied. executeCommandConfiguration logging is delivered when the session ends (CloudWatch Logs stream `ecs-execute-command-`, S3 key `/ecs-execute-command-.log`; naming from memory, unverified); KMS encryption is recorded, not performed (see External effects)." + - "ECS Exec: sessions exist only on the docker and kubernetes runtimes with the SSM service enabled (otherwise TargetNotConnectedException); the command runs as `sh -c ` through docker exec or pods/exec, and the ssmmessages IAM checks are not applied. executeCommandConfiguration logging is delivered when the session ends; KMS encryption is recorded, not performed (see External effects)." - "Kubernetes runtime (CONTAINER_RUNTIME=kubernetes, docs/kubernetes.md): one Pod per task. Refused with TaskFailedToStart: host-path/EFS/configuredAtLaunch/shared-docker volumes, networkMode host/none, pidMode/ipcMode host, privileged, devices, container restartPolicy, repositoryCredentials, FireLens, dependsOn COMPLETE/HEALTHY; ulimits/ephemeralStorage ignored; dependsOn START is not ordered; a never-ready health check stays UNKNOWN; no security-group enforcement; tasks are not adopted after a restart." structural_gaps: - "Service Connect: ServiceConnectConfiguration is stored and echoed, and ListServicesByNamespace matches on it, but Service Connect proxies and its Cloud Map instance registration are not modeled." @@ -1362,6 +1362,7 @@ awslogs-create-group (default false) is enforced on the docker runtime: a missin ## Emulator choices where the vendor is silent - RegisterTaskDefinition/RunTask: container `memory` hard limits and `cpu` reservations whose sum exceeds the task-level value are rejected (task_definition_parameters.html: totals "must be lower than" the task value; equal is accepted); the message text is not published +- ECS Exec: the CloudWatch Logs stream name (`ecs-execute-command-`) and S3 object key (`/ecs-execute-command-.log`) are not specified by ecs-exec.html or the ecs SDK (ExecuteCommandLogConfiguration carries only group/bucket/prefix/encryption fields); checked 2026-11-21 - ECS Exec: transcripts are capped at 1 MiB (first bytes kept), 10,000 lines and 8 KiB per line ## 2026-11-20 (restored launches) From 09e09bacb08e7f3ffcb4d70fe43ed80faf90048d Mon Sep 17 00:00:00 2001 From: Witness Patrol Date: Sat, 21 Nov 2026 14:16:27 -0600 Subject: [PATCH 4/9] feat(gcpbigquery): SEARCH reads logical operators inside a phrase; ST_MAKELINE nodes retraced edges Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01NVwMjLknMM32Xje6Qik6wY --- services/gcpbigquery/PARITY.md | 7 +- services/gcpbigquery/bqsql/consts.go | 1 + services/gcpbigquery/bqsql/functions_test.go | 54 ++++ services/gcpbigquery/bqsql/geo_noding.go | 274 ++++++++++++++++++ .../bqsql/geo_noding_internal_test.go | 51 ++++ services/gcpbigquery/bqsql/search.go | 30 +- services/gcpbigquery/bqsql/udf_geo.go | 10 +- services/gcpbigquery/sdk_geography_test.go | 42 +++ services/gcpbigquery/sdk_search_test.go | 34 +++ 9 files changed, 496 insertions(+), 7 deletions(-) create mode 100644 services/gcpbigquery/bqsql/geo_noding.go create mode 100644 services/gcpbigquery/bqsql/geo_noding_internal_test.go create mode 100644 services/gcpbigquery/sdk_geography_test.go create mode 100644 services/gcpbigquery/sdk_search_test.go diff --git a/services/gcpbigquery/PARITY.md b/services/gcpbigquery/PARITY.md index 9babd47683..eed0ce2ee7 100644 --- a/services/gcpbigquery/PARITY.md +++ b/services/gcpbigquery/PARITY.md @@ -58,8 +58,7 @@ items_still_open: - "Not served: models, table and dataset IAM policies (including row access policy IAM), datasets undelete, snapshots/clones as storage objects, BigLake tables and connections, data transfers, analytics hub, reservation groups, reservation failover and reservation IAM, and the Storage Read/Write gRPC APIs." - "Unsupported GoogleSQL: CAST ... FORMAT between numeric or BYTES types and STRING (date and time types are supported, with AT TIME ZONE), EXPORT DATA, JavaScript, Python and remote UDFs and CREATE AGGREGATE FUNCTION, wildcard tables (_TABLE_SUFFIX), partition pseudo columns (_PARTITIONTIME and _PARTITIONDATE need a per-row ingestion time that rows do not carry; DML rewrites whole row slices in jobs_query.go effectWrite), selecting a whole row as a STRUCT, legacy SQL." - "Unsupported functions: RANGE values, ML.*, GEOGRAPHY beyond the implemented ST_* set (use_spheroid => TRUE, make_valid => TRUE, ST_UNION, ST_BUFFER and the other constructors and aggregates), SEARCH over a table reference or a tuple, JSON constructors and mutators beyond JSON_VALUE/JSON_QUERY/PARSE_JSON/TO_JSON_STRING, FORMAT patterns beyond %s %d %i %f %g %e %t %T %x %o, collation." - - "ST_MAKELINE concatenates vertices and does not node overlapping or backtracking edges, so the documented MULTILINESTRING result for retraced segments is not reproduced." - - "SEARCH: the documented example where a phrase containing AND/OR matches plain terms is not reproduced." + - "ST_MAKELINE does not reject an edge spanning 180 degrees or more and does not snap sufficiently short edges together (both in the geography_functions ST_MAKELINE constraints)." - "Engine fidelity: NUMERIC and BIGNUMERIC are computed in float64, so values past 15 significant digits lose precision." - "Jobs: no slot or priority scheduling, no query cache, anonymous result tables are not created, script expression evaluations are not recorded as EXPRESSION child jobs, and execution holds the backend write lock (jobs_async.go runLocked), so jobs.cancel and jobTimeoutMs stop a job before it executes and a script between statements, not a plain statement in flight." - "Load: Datastore and Firestore backups, nested CSV and column-name flexibility options are not supported. External tables: GOOGLE_SHEETS, DATASTORE_BACKUP, BIGTABLE and DELTA_LAKE sources and WITH CONNECTION need services the emulator does not have. External tables and CREATE EXTERNAL TABLE read Cloud Storage while the backend lock is held (external.go readExternalRows). The NDJSON TIMESTAMP and CSV float rendering of extract have not been checked against the live service." @@ -110,6 +109,10 @@ Pass 2026-11-14: row access policies per https://docs.cloud.google.com/bigquery/ - Reservation scheduling is not simulated; capacity commitment ends are start plus the plan period (FLEX one minute) and FAILED_PRECONDITION is HTTP 400. - Script CASE evaluates the search expression once per WHEN; no match without ELSE runs nothing. - External table partition values equal to __HIVE_DEFAULT_PARTITION__ read as NULL; files are re-read on every query. +- ST_MAKELINE overlap detection is exact on meridians and the equator and uses a 1e-15 determinant bound on other great circles; it runs pairwise up to 1024 edges, beyond that only repeated identical edges collapse. Overlapping edges are cut at each other's vertices, merged, and walked into lines starting at the lowest-numbered odd-degree vertex (else lowest-numbered), taking the lowest-numbered unused neighbour first; the page does not say how a MULTILINESTRING is chained. A self-crossing line without overlap is left unchanged. +- SEARCH: a double-quoted phrase containing an upper-case AND or OR word that parses as a query is evaluated as that logical expression (the page only shows the "foo AND (bar OR baz)" example); otherwise it is a phrase. Not verified against the live page text: the fetch returned summaries, so the NO_OP_ANALYZER example `SEARCH(R'"foo bar"', R'"foo Bar"', analyzer=>'NO_OP_ANALYZER')` reported as TRUE was not adopted (NO_OP stays case-sensitive). - Extract destination URIs follow docs.cloud.google.com/bigquery/docs/exporting-data: at most one wildcard per URI, only in the file name, replaced by a 12-digit shard number; violations fail the job as invalid. +ST_MAKELINE nodes retraced and overlapping edges into the documented MULTILINESTRING (example `MULTILINESTRING((1 0, 5 0, 10 0), (5 0, 5 4))`); SEARCH reads AND/OR inside a double-quoted phrase as logical operators (documented example `SEARCH(R'foo bar', R'"foo AND (bar OR baz)"')` is TRUE). + Partitioning: PARTITION BY maps onto timePartitioning (DATE column, DATE(ts), DATE_TRUNC, DATETIME_TRUNC, TIMESTAMP_TRUNC, _PARTITIONDATE) or rangePartitioning (RANGE_BUCKET with GENERATE_ARRAY) and CLUSTER BY onto clustering.fields, with the documented "PARTITION BY expression must be ..." error; require_partition_filter and requirePartitionFilter make a query without a top-level predicate over the partition column fail (https://docs.cloud.google.com/bigquery/docs/querying-partitioned-tables). TABLESAMPLE SYSTEM (percent PERCENT) per https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax. Tables report streamingBuffer after insertAll (Table.streamingBuffer in the REST reference). diff --git a/services/gcpbigquery/bqsql/consts.go b/services/gcpbigquery/bqsql/consts.go index 86a426cd31..2a13bafc75 100644 --- a/services/gcpbigquery/bqsql/consts.go +++ b/services/gcpbigquery/bqsql/consts.go @@ -3,6 +3,7 @@ package bqsql // Repeated string literals shared across the package. const ( litAnd = "AND" + litOr = "OR" litArray = "ARRAY" litBignumeric = "BIGNUMERIC" litBool = "BOOL" diff --git a/services/gcpbigquery/bqsql/functions_test.go b/services/gcpbigquery/bqsql/functions_test.go index 5288f05d34..4321594c95 100644 --- a/services/gcpbigquery/bqsql/functions_test.go +++ b/services/gcpbigquery/bqsql/functions_test.go @@ -231,6 +231,30 @@ func TestGeographyFunctions(t *testing.T) { "ST_GEOGFROMTEXT('LINESTRING(2 3, 3 4)'), ST_GEOGPOINT(4, 5)]))", [][]any{{"LINESTRING(1 2, 2 3)", "POINT(1 2)", "LINESTRING(1 2, 2 3, 3 4, 4 5)"}}, }, + { + "makeline overlap", + "SELECT ST_ASTEXT(ST_MAKELINE([ST_MAKELINE(ST_GEOGPOINT(1, 0), ST_GEOGPOINT(10, 0)), " + + "ST_MAKELINE(ST_GEOGPOINT(10, 0), ST_GEOGPOINT(5, 0)), ST_MAKELINE(ST_GEOGPOINT(5, 0), ST_GEOGPOINT(5, 4))]))", + [][]any{{"MULTILINESTRING((1 0, 5 0, 10 0), (5 0, 5 4))"}}, + }, + { + "makeline retrace", + "SELECT ST_ASTEXT(ST_MAKELINE([ST_GEOGPOINT(0, 0), ST_GEOGPOINT(2, 0), ST_GEOGPOINT(0, 0)])), " + + "ST_ASTEXT(ST_MAKELINE([ST_GEOGPOINT(0, 0), ST_GEOGPOINT(1, 0), ST_GEOGPOINT(0, 0), ST_GEOGPOINT(0, 1)])), " + + "ST_ASTEXT(ST_MAKELINE([ST_GEOGPOINT(0, 0), ST_GEOGPOINT(0, 4), ST_GEOGPOINT(0, 2), ST_GEOGPOINT(0, 6)]))", + [][]any{{"LINESTRING(0 0, 2 0)", "LINESTRING(1 0, 0 0, 0 1)", "LINESTRING(0 0, 0 2, 0 4, 0 6)"}}, + }, + { + "makeline touch", + "SELECT ST_ASTEXT(ST_MAKELINE([ST_GEOGPOINT(0, 0), ST_GEOGPOINT(2, 0), ST_GEOGPOINT(1, 1), ST_GEOGPOINT(1, 0)]))", + [][]any{{"LINESTRING(0 0, 2 0, 1 1, 1 0)"}}, + }, + { + "makeline null", + "SELECT ST_MAKELINE(ST_GEOGPOINT(1, 2), CAST(NULL AS GEOGRAPHY)), " + + "ST_MAKELINE([ST_GEOGPOINT(1, 2), CAST(NULL AS GEOGRAPHY)])", + [][]any{{nil, nil}}, + }, { "makepolygon", "SELECT ST_ASTEXT(ST_MAKEPOLYGON(ST_GEOGFROMTEXT('LINESTRING(0 0, 1 0, 1 1, 0 0)')))", @@ -709,6 +733,36 @@ func TestSearchFunctions(t *testing.T) { "SELECT SEARCH('Please use foobar@example.com as your email.', 'foobar@example.com', " + "analyzer_options => '{\"delimiters\": [\" \", \"@\"]}')", }, + { + "true", + "phrase logical", + "SELECT SEARCH(R'foo bar', R'\"foo AND (bar OR baz)\"')", + }, + { + "false", + "phrase logical miss", + "SELECT SEARCH(R'foo', R'\"foo AND (bar OR baz)\"')", + }, + { + "true", + "phrase or", + "SELECT SEARCH(R'foo bar', R'\"zzz OR bar\"')", + }, + { + "true", + "implicit and", + "SELECT SEARCH(R'foo bar baz', R'foo bar')", + }, + { + "true", + "empty noop", + "SELECT SEARCH('', '', analyzer => 'NO_OP_ANALYZER')", + }, + { + "false", + "noop phrase", + "SELECT SEARCH(R'foo bar baz', R'\"foo bar\"', analyzer => 'NO_OP_ANALYZER')", + }, { "true", "struct", diff --git a/services/gcpbigquery/bqsql/geo_noding.go b/services/gcpbigquery/bqsql/geo_noding.go new file mode 100644 index 0000000000..b22f913a16 --- /dev/null +++ b/services/gcpbigquery/bqsql/geo_noding.go @@ -0,0 +1,274 @@ +package bqsql + +import ( + "math" + "sort" +) + +// ST_MAKELINE returns a MULTILINESTRING when the snapped input has self-overlapping lines: +// https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/geography_functions +const ( + nodingMaxEdges = 1024 + collinearBound = 1e-15 + equatorLat = 0 + nodingOddDegree = 1 + minLinePoints = 3 +) + +type edgeKey struct{ a, b lonLat } + +func orderedKey(a, b lonLat) edgeKey { + if a.lon > b.lon || a.lon == b.lon && a.lat > b.lat { + a, b = b, a + } + + return edgeKey{a, b} +} + +func onMeridian(pts ...lonLat) bool { + for _, p := range pts[1:] { + if p.lon != pts[0].lon { + return false + } + } + + return true +} + +func onEquator(pts ...lonLat) bool { + for _, p := range pts { + if p.lat != equatorLat { + return false + } + } + + return true +} + +func collinear3(a, b, c lonLat) bool { + if onMeridian(a, b, c) || onEquator(a, b, c) { + return true + } + + va, vb, vc := a.vec(), b.vec(), c.vec() + + return math.Abs(va.dot(vb.cross(vc))) <= collinearBound +} + +func between(x, a, b float64) bool { return x > math.Min(a, b) && x < math.Max(a, b) } + +// strictlyInside reports whether x lies in the open arc a-b; x must be on the great circle of a-b. +func strictlyInside(x, a, b lonLat) bool { + switch { + case x == a || x == b: + return false + case onMeridian(a, b, x) && math.Abs(a.lat) != 90 && math.Abs(b.lat) != 90: + return between(x.lat, a.lat, b.lat) + case onEquator(a, b, x) && math.Abs(a.lon-b.lon) < halfTurn: + return between(x.lon, a.lon, b.lon) + } + + va, vb, vx := a.vec(), b.vec(), x.vec() + n := va.cross(vb) + + return n.dot(va.cross(vx)) > 0 && n.dot(vx.cross(vb)) > 0 +} + +type lineEdge struct { + splits []lonLat + a, b lonLat +} + +// overlaps reports whether two edges lie on one great circle and share more than a single point. +func overlaps(e, f *lineEdge) bool { + if orderedKey(e.a, e.b) == orderedKey(f.a, f.b) { + return true + } + + if !collinear3(e.a, e.b, f.a) || !collinear3(e.a, e.b, f.b) { + return false + } + + return strictlyInside(f.a, e.a, e.b) || strictlyInside(f.b, e.a, e.b) || + strictlyInside(e.a, f.a, f.b) || strictlyInside(e.b, f.a, f.b) +} + +func (e *lineEdge) noteSplits(f *lineEdge) { + for _, p := range []lonLat{f.a, f.b} { + if strictlyInside(p, e.a, e.b) { + e.splits = append(e.splits, p) + } + } +} + +func (e *lineEdge) pieces() []edgeKey { + if len(e.splits) == 0 { + return []edgeKey{{e.a, e.b}} + } + + va := e.a.vec() + sort.Slice(e.splits, func(i, j int) bool { return angle(va, e.splits[i].vec()) < angle(va, e.splits[j].vec()) }) + + out := make([]edgeKey, 0, len(e.splits)+1) + prev := e.a + + for _, s := range e.splits { + if s == prev { + continue + } + + out = append(out, edgeKey{prev, s}) + prev = s + } + + return append(out, edgeKey{prev, e.b}) +} + +type nodeGraph struct { + index map[lonLat]int + order []lonLat + adj [][]int +} + +func newNodeGraph(pts []lonLat) *nodeGraph { + g := &nodeGraph{index: map[lonLat]int{}} + + for _, p := range pts { + if _, ok := g.index[p]; !ok { + g.index[p] = len(g.order) + g.order = append(g.order, p) + } + } + + g.adj = make([][]int, len(g.order)) + + return g +} + +func (g *nodeGraph) link(a, b lonLat) { + i, j := g.index[a], g.index[b] + g.adj[i] = append(g.adj[i], j) + g.adj[j] = append(g.adj[j], i) +} + +// startNode prefers the lowest-numbered node of odd remaining degree so that a retraced path stays one line. +func (g *nodeGraph) startNode() int { + first := -1 + + for i, nb := range g.adj { + if len(nb) == 0 { + continue + } + + if len(nb)%parityMod == nodingOddDegree { + return i + } + + if first < 0 { + first = i + } + } + + return first +} + +func (g *nodeGraph) removeEdge(i, j int) { + g.adj[i] = dropFirst(g.adj[i], j) + g.adj[j] = dropFirst(g.adj[j], i) +} + +func dropFirst(s []int, v int) []int { + for k, x := range s { + if x == v { + return append(s[:k], s[k+1:]...) + } + } + + return s +} + +func (g *nodeGraph) walks() [][]lonLat { + for _, nb := range g.adj { + sort.Ints(nb) + } + + var out [][]lonLat + + for cur := g.startNode(); cur >= 0; cur = g.startNode() { + line := []lonLat{g.order[cur]} + + for len(g.adj[cur]) > 0 { + next := g.adj[cur][0] + g.removeEdge(cur, next) + line = append(line, g.order[next]) + cur = next + } + + out = append(out, line) + } + + return out +} + +// nodeLines collapses retraced and overlapping edges of the vertex chain pts. With no overlap it returns pts unchanged. +func nodeLines(pts []lonLat) [][]lonLat { + if len(pts) < minLinePoints { + return [][]lonLat{pts} + } + + edges := make([]*lineEdge, len(pts)-1) + for i := range edges { + edges[i] = &lineEdge{a: pts[i], b: pts[i+1]} + } + + overlap := markOverlaps(edges) + + if !overlap { + return [][]lonLat{pts} + } + + g := newNodeGraph(pts) + done := make(map[edgeKey]bool, len(edges)) + + for _, e := range edges { + for _, p := range e.pieces() { + k := orderedKey(p.a, p.b) + if !done[k] { + done[k] = true + + g.link(p.a, p.b) + } + } + } + + return g.walks() +} + +// markOverlaps records split points on overlapping edges and reports whether any edge repeats or overlaps another. +func markOverlaps(edges []*lineEdge) bool { + seen := make(map[edgeKey]bool, len(edges)) + overlap := false + + for _, e := range edges { + k := orderedKey(e.a, e.b) + overlap = overlap || seen[k] + seen[k] = true + } + + if len(edges) > nodingMaxEdges { + return overlap + } + + for i, e := range edges { + for _, f := range edges[i+1:] { + if overlaps(e, f) { + overlap = true + + e.noteSplits(f) + f.noteSplits(e) + } + } + } + + return overlap +} diff --git a/services/gcpbigquery/bqsql/geo_noding_internal_test.go b/services/gcpbigquery/bqsql/geo_noding_internal_test.go new file mode 100644 index 0000000000..82ff3c39a6 --- /dev/null +++ b/services/gcpbigquery/bqsql/geo_noding_internal_test.go @@ -0,0 +1,51 @@ +package bqsql + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestNodeLines(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + want string + in []lonLat + }{ + {"no overlap", "LINESTRING(0 0, 1 1, 2 0)", []lonLat{{0, 0}, {1, 1}, {2, 0}}}, + {"self crossing kept", "LINESTRING(0 0, 2 2, 2 0, 0 2)", []lonLat{{0, 0}, {2, 2}, {2, 0}, {0, 2}}}, + {"partial overlap", "LINESTRING(0 0, 2 0, 4 0, 6 0)", []lonLat{{0, 0}, {4, 0}, {2, 0}, {6, 0}}}, + {"through pole", "LINESTRING(0 80, 180 80)", []lonLat{{0, 80}, {180, 80}, {0, 80}}}, + {"meridian opposite", "LINESTRING(0 10, 0 90, 180 80)", []lonLat{{0, 10}, {0, 90}, {180, 80}, {0, 90}}}, + {"fork", "MULTILINESTRING((0 0, 1 0, 2 0), (1 0, 1 1))", []lonLat{{0, 0}, {2, 0}, {1, 0}, {1, 1}}}, + {"same edge twice", "LINESTRING(0 0, 1 2)", []lonLat{{0, 0}, {1, 2}, {0, 0}, {1, 2}}}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + lines := nodeLines(tt.in) + + g := &geo{kind: gLine, lines: lines} + if len(lines) > 1 { + g.kind = gMultiLine + } + + assert.Equal(t, tt.want, g.wkt()) + }) + } +} + +func TestNodeLinesLargeInput(t *testing.T) { + t.Parallel() + + pts := make([]lonLat, 0, nodingMaxEdges*3) + for i := range nodingMaxEdges * 3 { + pts = append(pts, lonLat{float64(i%170) - 85, float64(i%7) * 10}) + } + + assert.NotPanics(t, func() { nodeLines(pts) }) +} diff --git a/services/gcpbigquery/bqsql/search.go b/services/gcpbigquery/bqsql/search.go index 159531f370..887ec314b4 100644 --- a/services/gcpbigquery/bqsql/search.go +++ b/services/gcpbigquery/bqsql/search.go @@ -346,12 +346,29 @@ type searchNode struct { } type searchParser struct { - src []rune - pos int + src []rune + pos int + depth int +} + +const searchMaxDepth = 16 + +func hasLogicalWord(s string) bool { + for w := range strings.FieldsSeq(s) { + if w == litAnd || w == litOr { + return true + } + } + + return false } func parseSearchQuery(q string) (*searchNode, error) { - p := &searchParser{src: []rune(q)} + return parseSearchQueryAt(q, 0) +} + +func parseSearchQueryAt(q string, depth int) (*searchNode, error) { + p := &searchParser{src: []rune(q), depth: depth} n, err := p.or() if err != nil { @@ -503,6 +520,13 @@ func (p *searchParser) quoted(q rune) (*searchNode, error) { kind = 'b' } + // search_functions example: "foo AND (bar OR baz)" matches 'foo bar', so operators in a phrase are logical. + if kind == 'p' && p.depth < searchMaxDepth && hasLogicalWord(sb.String()) { + if n, err := parseSearchQueryAt(sb.String(), p.depth+1); err == nil { + return n, nil + } + } + return &searchNode{kind: kind, text: sb.String()}, nil } diff --git a/services/gcpbigquery/bqsql/udf_geo.go b/services/gcpbigquery/bqsql/udf_geo.go index f308bbafd0..387e7eaa0e 100644 --- a/services/gcpbigquery/bqsql/udf_geo.go +++ b/services/gcpbigquery/bqsql/udf_geo.go @@ -428,7 +428,8 @@ func (g *geo) geoJSON() string { return `{ "type": "GeometryCollection", "geometries": [] }` } -// udfMakeLine concatenates the vertices of its point or linestring arguments, dropping consecutive repeats. +// udfMakeLine concatenates the vertices of its point or linestring arguments, dropping consecutive repeats and +// collapsing retraced or overlapping edges. func udfMakeLine(a []driver.Value) (driver.Value, error) { if len(a) == 1 && a[0] != nil { if arr, err := decodeJSONArray(a[0]); err == nil { @@ -471,7 +472,12 @@ func udfMakeLine(a []driver.Value) (driver.Value, error) { return (&geo{kind: gEmpty}).wkt(), nil } - return (&geo{kind: gLine, lines: [][]lonLat{pts}}).wkt(), nil + lines := nodeLines(pts) + if len(lines) > 1 { + return (&geo{kind: gMultiLine, lines: lines}).wkt(), nil + } + + return (&geo{kind: gLine, lines: lines}).wkt(), nil } func appendDistinct(dst []lonLat, add ...lonLat) []lonLat { diff --git a/services/gcpbigquery/sdk_geography_test.go b/services/gcpbigquery/sdk_geography_test.go new file mode 100644 index 0000000000..c13f7438e3 --- /dev/null +++ b/services/gcpbigquery/sdk_geography_test.go @@ -0,0 +1,42 @@ +package gcpbigquery_test + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestSDKMakeLine(t *testing.T) { + t.Parallel() + + tests := []struct { + name, sql, want string + }{ + { + "overlap", + `SELECT ST_ASTEXT(ST_MAKELINE([ST_MAKELINE(ST_GEOGPOINT(1, 0), ST_GEOGPOINT(10, 0)), + ST_MAKELINE(ST_GEOGPOINT(10, 0), ST_GEOGPOINT(5, 0)), ST_MAKELINE(ST_GEOGPOINT(5, 0), ST_GEOGPOINT(5, 4))]))`, + "MULTILINESTRING((1 0, 5 0, 10 0), (5 0, 5 4))", + }, + {"point", `SELECT ST_ASTEXT(ST_MAKELINE(ST_GEOGPOINT(1, 2), ST_GEOGPOINT(1, 2)))`, "POINT(1 2)"}, + { + "concat", + `SELECT ST_ASTEXT(ST_MAKELINE([ST_GEOGFROMTEXT('LINESTRING(1 2, 2 3)'), ST_GEOGFROMTEXT('LINESTRING(2 3, 3 4)'), + ST_GEOGPOINT(4, 5)]))`, + "LINESTRING(1 2, 2 3, 3 4, 4 5)", + }, + } + + env := newSDK(t) + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + rows := env.rows(t, tt.sql) + require.Len(t, rows, 1) + assert.Equal(t, tt.want, rows[0][0]) + }) + } +} diff --git a/services/gcpbigquery/sdk_search_test.go b/services/gcpbigquery/sdk_search_test.go new file mode 100644 index 0000000000..f1540c5727 --- /dev/null +++ b/services/gcpbigquery/sdk_search_test.go @@ -0,0 +1,34 @@ +package gcpbigquery_test + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestSDKSearchLogicalPhrase(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + sql string + want bool + }{ + {"phrase and or", `SELECT SEARCH(R'foo bar', R'"foo AND (bar OR baz)"')`, true}, + {"plain and or", `SELECT SEARCH(R'foo', R'foo AND (bar OR baz)')`, false}, + {"phrase adjacent", `SELECT SEARCH(R'foo bar baz', R'"foo bar"')`, true}, + } + + env := newSDK(t) + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + rows := env.rows(t, tt.sql) + require.Len(t, rows, 1) + assert.Equal(t, tt.want, rows[0][0]) + }) + } +} From a910f7bbcd226753d5c1f6df5534dfb09e0c3f7d Mon Sep 17 00:00:00 2001 From: Witness Patrol Date: Sat, 21 Nov 2026 14:21:48 -0600 Subject: [PATCH 5/9] fix(gcpbigquery): ST_MAKELINE overlap test scales with edge length and rejects antipodal edges The collinearity bound was on a raw determinant, so two distinct short edges close together were merged. An edge between antipodal points is an error. The parity notes list what remains unverified for SEARCH phrases and the pairwise noding limit. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01NVwMjLknMM32Xje6Qik6wY --- services/gcpbigquery/PARITY.md | 6 +-- services/gcpbigquery/bqsql/functions_test.go | 53 +++++++++++++++---- services/gcpbigquery/bqsql/geo_noding.go | 37 ++++++++++++- .../bqsql/geo_noding_internal_test.go | 5 ++ services/gcpbigquery/bqsql/udf_geo.go | 36 +++++++++---- 5 files changed, 113 insertions(+), 24 deletions(-) diff --git a/services/gcpbigquery/PARITY.md b/services/gcpbigquery/PARITY.md index eed0ce2ee7..140fc1742a 100644 --- a/services/gcpbigquery/PARITY.md +++ b/services/gcpbigquery/PARITY.md @@ -58,7 +58,8 @@ items_still_open: - "Not served: models, table and dataset IAM policies (including row access policy IAM), datasets undelete, snapshots/clones as storage objects, BigLake tables and connections, data transfers, analytics hub, reservation groups, reservation failover and reservation IAM, and the Storage Read/Write gRPC APIs." - "Unsupported GoogleSQL: CAST ... FORMAT between numeric or BYTES types and STRING (date and time types are supported, with AT TIME ZONE), EXPORT DATA, JavaScript, Python and remote UDFs and CREATE AGGREGATE FUNCTION, wildcard tables (_TABLE_SUFFIX), partition pseudo columns (_PARTITIONTIME and _PARTITIONDATE need a per-row ingestion time that rows do not carry; DML rewrites whole row slices in jobs_query.go effectWrite), selecting a whole row as a STRUCT, legacy SQL." - "Unsupported functions: RANGE values, ML.*, GEOGRAPHY beyond the implemented ST_* set (use_spheroid => TRUE, make_valid => TRUE, ST_UNION, ST_BUFFER and the other constructors and aggregates), SEARCH over a table reference or a tuple, JSON constructors and mutators beyond JSON_VALUE/JSON_QUERY/PARSE_JSON/TO_JSON_STRING, FORMAT patterns beyond %s %d %i %f %g %e %t %T %x %o, collation." - - "ST_MAKELINE does not reject an edge spanning 180 degrees or more and does not snap sufficiently short edges together (both in the geography_functions ST_MAKELINE constraints)." + - "ST_MAKELINE does not snap sufficiently short edges together (geography_functions ST_MAKELINE constraints; snap radius not stated there). Overlap detection of edges beyond the first 1024 only collapses repeated identical edges, and detection off the equator and meridians uses a floating-point tolerance, not an exact predicate. The error text for an edge of 180 degrees or more is emulator wording." + - "SEARCH NO_OP_ANALYZER: the page's example SEARCH(R'\"foo bar\"', R'\"foo Bar\"', analyzer=>'NO_OP_ANALYZER') is TRUE with the comment 'analysis is case-insensitive', while its 'Foobar' vs 'foobar' example is FALSE; the emulator keeps NO_OP case-sensitive and returns FALSE for the first. SEARCH also reads upper-case AND/OR inside a double-quoted phrase as logical operators (the page's SEARCH(R'foo bar', R'\"foo AND (bar OR baz)\"') is TRUE, commented as a logical match); the rule for phrases that really contain those words is not documented, so 'Clyde and Bonnie' matches the query \"Bonnie AND Clyde\"." - "Engine fidelity: NUMERIC and BIGNUMERIC are computed in float64, so values past 15 significant digits lose precision." - "Jobs: no slot or priority scheduling, no query cache, anonymous result tables are not created, script expression evaluations are not recorded as EXPRESSION child jobs, and execution holds the backend write lock (jobs_async.go runLocked), so jobs.cancel and jobTimeoutMs stop a job before it executes and a script between statements, not a plain statement in flight." - "Load: Datastore and Firestore backups, nested CSV and column-name flexibility options are not supported. External tables: GOOGLE_SHEETS, DATASTORE_BACKUP, BIGTABLE and DELTA_LAKE sources and WITH CONNECTION need services the emulator does not have. External tables and CREATE EXTERNAL TABLE read Cloud Storage while the backend lock is held (external.go readExternalRows). The NDJSON TIMESTAMP and CSV float rendering of extract have not been checked against the live service." @@ -109,8 +110,7 @@ Pass 2026-11-14: row access policies per https://docs.cloud.google.com/bigquery/ - Reservation scheduling is not simulated; capacity commitment ends are start plus the plan period (FLEX one minute) and FAILED_PRECONDITION is HTTP 400. - Script CASE evaluates the search expression once per WHEN; no match without ELSE runs nothing. - External table partition values equal to __HIVE_DEFAULT_PARTITION__ read as NULL; files are re-read on every query. -- ST_MAKELINE overlap detection is exact on meridians and the equator and uses a 1e-15 determinant bound on other great circles; it runs pairwise up to 1024 edges, beyond that only repeated identical edges collapse. Overlapping edges are cut at each other's vertices, merged, and walked into lines starting at the lowest-numbered odd-degree vertex (else lowest-numbered), taking the lowest-numbered unused neighbour first; the page does not say how a MULTILINESTRING is chained. A self-crossing line without overlap is left unchanged. -- SEARCH: a double-quoted phrase containing an upper-case AND or OR word that parses as a query is evaluated as that logical expression (the page only shows the "foo AND (bar OR baz)" example); otherwise it is a phrase. Not verified against the live page text: the fetch returned summaries, so the NO_OP_ANALYZER example `SEARCH(R'"foo bar"', R'"foo Bar"', analyzer=>'NO_OP_ANALYZER')` reported as TRUE was not adopted (NO_OP stays case-sensitive). +- ST_MAKELINE cuts overlapping edges at each other's vertices, merges them, and walks lines from the lowest-numbered odd-degree vertex taking the lowest-numbered unused neighbour first; a simple retrace A B A gives LINESTRING(A B). The page documents only the MULTILINESTRING example, not vertex order or chaining. A self-crossing line without overlap is unchanged. An edge spanning exactly 180 degrees (antipodal points) is rejected. - Extract destination URIs follow docs.cloud.google.com/bigquery/docs/exporting-data: at most one wildcard per URI, only in the file name, replaced by a 12-digit shard number; violations fail the job as invalid. ST_MAKELINE nodes retraced and overlapping edges into the documented MULTILINESTRING (example `MULTILINESTRING((1 0, 5 0, 10 0), (5 0, 5 4))`); SEARCH reads AND/OR inside a double-quoted phrase as logical operators (documented example `SEARCH(R'foo bar', R'"foo AND (bar OR baz)"')` is TRUE). diff --git a/services/gcpbigquery/bqsql/functions_test.go b/services/gcpbigquery/bqsql/functions_test.go index 4321594c95..4e7ef3e869 100644 --- a/services/gcpbigquery/bqsql/functions_test.go +++ b/services/gcpbigquery/bqsql/functions_test.go @@ -306,16 +306,19 @@ func TestGeographyErrors(t *testing.T) { t.Parallel() for name, sql := range map[string]string{ - "latitude": "SELECT ST_GEOGPOINT(0, 91)", - "x of line": "SELECT ST_X(ST_GEOGFROMTEXT('LINESTRING(1 2, 3 4)'))", - "x of empty": "SELECT ST_X(ST_GEOGFROMTEXT('GEOMETRYCOLLECTION EMPTY'))", - "badwkt": "SELECT ST_GEOGFROMTEXT('POINT(1)')", - "z coords": "SELECT ST_GEOGFROMTEXT('POINT Z (1 2 3)')", - "oriented": "SELECT ST_GEOGFROMTEXT('POINT(1 2)', oriented => TRUE, planar => TRUE)", - "feature": "SELECT ST_GEOGFROMGEOJSON('{\"type\":\"Feature\",\"geometry\":null}')", - "open loop": "SELECT ST_MAKEPOLYGON(ST_GEOGFROMTEXT('LINESTRING(0 0, 1 0, 1 1)'))", - "spheroid": "SELECT ST_DISTANCE(ST_GEOGPOINT(0, 0), ST_GEOGPOINT(1, 1), TRUE)", - "named other": "SELECT ABS(x => 1)", + "latitude": "SELECT ST_GEOGPOINT(0, 91)", + "x of line": "SELECT ST_X(ST_GEOGFROMTEXT('LINESTRING(1 2, 3 4)'))", + "x of empty": "SELECT ST_X(ST_GEOGFROMTEXT('GEOMETRYCOLLECTION EMPTY'))", + "badwkt": "SELECT ST_GEOGFROMTEXT('POINT(1)')", + "z coords": "SELECT ST_GEOGFROMTEXT('POINT Z (1 2 3)')", + "oriented": "SELECT ST_GEOGFROMTEXT('POINT(1 2)', oriented => TRUE, planar => TRUE)", + "feature": "SELECT ST_GEOGFROMGEOJSON('{\"type\":\"Feature\",\"geometry\":null}')", + "open loop": "SELECT ST_MAKEPOLYGON(ST_GEOGFROMTEXT('LINESTRING(0 0, 1 0, 1 1)'))", + "makeline half circle": "SELECT ST_MAKELINE(ST_GEOGPOINT(0, 0), ST_GEOGPOINT(180, 0))", + "makeline pole pair": "SELECT ST_MAKELINE(ST_GEOGPOINT(0, 90), ST_GEOGPOINT(30, -90))", + "makeline antipode": "SELECT ST_MAKELINE([ST_GEOGPOINT(1, 1), ST_GEOGPOINT(10, 20), ST_GEOGPOINT(-170, -20)])", + "spheroid": "SELECT ST_DISTANCE(ST_GEOGPOINT(0, 0), ST_GEOGPOINT(1, 1), TRUE)", + "named other": "SELECT ABS(x => 1)", } { t.Run(name, func(t *testing.T) { t.Parallel() @@ -743,6 +746,36 @@ func TestSearchFunctions(t *testing.T) { "phrase logical miss", "SELECT SEARCH(R'foo', R'\"foo AND (bar OR baz)\"')", }, + { + "true", + "phrase keeps literal and", + "SELECT SEARCH(R'Bonnie and Clyde', R'\"Bonnie AND Clyde\"')", + }, + { + "true", + "phrase keeps literal or", + "SELECT SEARCH(R'stay in or out', R'\"in OR out\"')", + }, + { + "false", + "phrase lowercase and is a term", + "SELECT SEARCH(R'foo bar', R'\"foo and bar\"')", + }, + { + "true", + "phrase unbalanced stays phrase", + "SELECT SEARCH(R'foo and bar', R'\"foo AND ( bar\"')", + }, + { + "false", + "phrase noop analyzer", + "SELECT SEARCH(R'foo bar', R'\"foo AND bar\"', analyzer => 'NO_OP_ANALYZER')", + }, + { + "false", + "phrase deep nesting", + "SELECT SEARCH(R'x', R'\"" + strings.Repeat("(", 5000) + "a AND b" + strings.Repeat(")", 5000) + "\"')", + }, { "true", "phrase or", diff --git a/services/gcpbigquery/bqsql/geo_noding.go b/services/gcpbigquery/bqsql/geo_noding.go index b22f913a16..5a59622d42 100644 --- a/services/gcpbigquery/bqsql/geo_noding.go +++ b/services/gcpbigquery/bqsql/geo_noding.go @@ -10,6 +10,9 @@ import ( const ( nodingMaxEdges = 1024 collinearBound = 1e-15 + vecNoise = 1e-16 + minPlaneNorm = 1e-12 + poleLat = 90 equatorLat = 0 nodingOddDegree = 1 minLinePoints = 3 @@ -51,8 +54,15 @@ func collinear3(a, b, c lonLat) bool { } va, vb, vc := a.vec(), b.vec(), c.vec() + n := va.cross(vb) - return math.Abs(va.dot(vb.cross(vc))) <= collinearBound + nn := n.norm() + if nn < minPlaneNorm { + return false + } + + // Distance of c from the plane of a,b; the noise term grows as the edge shrinks. + return math.Abs(n.dot(vc))/nn <= collinearBound+vecNoise/nn } func between(x, a, b float64) bool { return x > math.Min(a, b) && x < math.Max(a, b) } @@ -272,3 +282,28 @@ func markOverlaps(edges []*lineEdge) bool { return overlap } + +// antipodal reports whether a and b are exactly opposite points on the sphere. +func antipodal(a, b lonLat) bool { + if a.lat != -b.lat { + return false + } + + if math.Abs(a.lat) == poleLat { + return true + } + + d := math.Mod(math.Abs(a.lon-b.lon), fullTurn) + + return d == halfTurn +} + +func checkEdgeSpans(pts []lonLat) error { + for i := 1; i < len(pts); i++ { + if antipodal(pts[i-1], pts[i]) { + return errBQ("ST_MAKELINE: every edge must span strictly less than 180 degrees") + } + } + + return nil +} diff --git a/services/gcpbigquery/bqsql/geo_noding_internal_test.go b/services/gcpbigquery/bqsql/geo_noding_internal_test.go index 82ff3c39a6..2a6c2e8299 100644 --- a/services/gcpbigquery/bqsql/geo_noding_internal_test.go +++ b/services/gcpbigquery/bqsql/geo_noding_internal_test.go @@ -20,6 +20,11 @@ func TestNodeLines(t *testing.T) { {"through pole", "LINESTRING(0 80, 180 80)", []lonLat{{0, 80}, {180, 80}, {0, 80}}}, {"meridian opposite", "LINESTRING(0 10, 0 90, 180 80)", []lonLat{{0, 10}, {0, 90}, {180, 80}, {0, 90}}}, {"fork", "MULTILINESTRING((0 0, 1 0, 2 0), (1 0, 1 1))", []lonLat{{0, 0}, {2, 0}, {1, 0}, {1, 1}}}, + { + "short distinct edges not merged", + "LINESTRING(10 10, 10.00001 10, 10.000005 10.0000001, 10.000015 10.0000001)", + []lonLat{{10, 10}, {10.00001, 10}, {10.000005, 10.0000001}, {10.000015, 10.0000001}}, + }, {"same edge twice", "LINESTRING(0 0, 1 2)", []lonLat{{0, 0}, {1, 2}, {0, 0}, {1, 2}}}, } diff --git a/services/gcpbigquery/bqsql/udf_geo.go b/services/gcpbigquery/bqsql/udf_geo.go index 387e7eaa0e..e6bb5549cf 100644 --- a/services/gcpbigquery/bqsql/udf_geo.go +++ b/services/gcpbigquery/bqsql/udf_geo.go @@ -431,16 +431,7 @@ func (g *geo) geoJSON() string { // udfMakeLine concatenates the vertices of its point or linestring arguments, dropping consecutive repeats and // collapsing retraced or overlapping edges. func udfMakeLine(a []driver.Value) (driver.Value, error) { - if len(a) == 1 && a[0] != nil { - if arr, err := decodeJSONArray(a[0]); err == nil { - a = make([]driver.Value, len(arr)) - for i, e := range arr { - if s, ok := e.(string); ok { - a[i] = s - } - } - } - } + a = unwrapGeoArray(a) if anyNull(a) { return nil, nil //nolint:nilnil // NULL in, NULL out @@ -472,6 +463,10 @@ func udfMakeLine(a []driver.Value) (driver.Value, error) { return (&geo{kind: gEmpty}).wkt(), nil } + if err := checkEdgeSpans(pts); err != nil { + return nil, err + } + lines := nodeLines(pts) if len(lines) > 1 { return (&geo{kind: gMultiLine, lines: lines}).wkt(), nil @@ -480,6 +475,27 @@ func udfMakeLine(a []driver.Value) (driver.Value, error) { return (&geo{kind: gLine, lines: lines}).wkt(), nil } +// unwrapGeoArray turns a single ARRAY argument into its elements. +func unwrapGeoArray(a []driver.Value) []driver.Value { + if len(a) != 1 || a[0] == nil { + return a + } + + arr, err := decodeJSONArray(a[0]) + if err != nil { + return a + } + + out := make([]driver.Value, len(arr)) + for i, e := range arr { + if s, ok := e.(string); ok { + out[i] = s + } + } + + return out +} + func appendDistinct(dst []lonLat, add ...lonLat) []lonLat { for _, p := range add { if len(dst) == 0 || dst[len(dst)-1] != p { From eed14136e592c9d56ffb47dba12bfaac6649eafb Mon Sep 17 00:00:00 2001 From: Witness Patrol Date: Sat, 21 Nov 2026 14:42:21 -0600 Subject: [PATCH 6/9] feat(cloudformation): per-resource provisioning waves, UPDATE_ROLLBACK_FAILED and ContinueUpdateRollback Create, update, delete and rollback advance one dependency wave per step, with events and resource statuses visible while the stack is in progress. Update rollback reverts in-place changes and restores the template and parameters. A resource that cannot be rolled back leaves the stack in UPDATE_ROLLBACK_FAILED, and ContinueUpdateRollback retries or skips it. The backend stops its timers on reset and close. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01NVwMjLknMM32Xje6Qik6wY --- .../testdata/snapshot_inventory.json | 56 +- services/cloudformation/PARITY.md | 24 +- services/cloudformation/export_test.go | 5 +- services/cloudformation/handler_http_test.go | 2 +- services/cloudformation/handler_stacks.go | 9 +- .../handler_supplemental_test.go | 2 +- services/cloudformation/persistence.go | 33 + services/cloudformation/regions.go | 7 +- services/cloudformation/resource_update.go | 183 +--- services/cloudformation/stack_async.go | 231 ++--- services/cloudformation/stack_create_walk.go | 364 +++++++ services/cloudformation/stack_delete.go | 101 +- services/cloudformation/stack_lifecycle.go | 53 +- .../cloudformation/stack_lifecycle_test.go | 6 +- services/cloudformation/stack_resources.go | 6 +- .../cloudformation/stack_transitions_test.go | 24 +- .../cloudformation/stack_update_rollback.go | 378 ++++++++ services/cloudformation/stack_update_walk.go | 524 +++++++++++ services/cloudformation/stack_walk.go | 278 ++++++ services/cloudformation/stack_walk_test.go | 885 ++++++++++++++++++ services/cloudformation/stacks.go | 712 +------------- services/cloudformation/store.go | 63 +- services/cloudformation/store_direct_test.go | 2 +- .../cloudformation/store_supplemental_test.go | 33 +- test/integration/cloudformation_ext_test.go | 6 +- 25 files changed, 2837 insertions(+), 1150 deletions(-) create mode 100644 services/cloudformation/stack_create_walk.go create mode 100644 services/cloudformation/stack_update_rollback.go create mode 100644 services/cloudformation/stack_update_walk.go create mode 100644 services/cloudformation/stack_walk.go create mode 100644 services/cloudformation/stack_walk_test.go diff --git a/pkgs/persistence/testdata/snapshot_inventory.json b/pkgs/persistence/testdata/snapshot_inventory.json index 70c35690e6..ab59e36fe3 100644 --- a/pkgs/persistence/testdata/snapshot_inventory.json +++ b/pkgs/persistence/testdata/snapshot_inventory.json @@ -7482,6 +7482,39 @@ "StackSetOperationResult.StatusReason string `xml:\"StatusReason,omitempty\"`", "Tag.Key string `xml:\"Key\" json:\"key\"`", "Tag.Value string `xml:\"Value\" json:\"value\"`", + "Template.AWSTemplateFormatVersion string `json:\"AWSTemplateFormatVersion\" yaml:\"AWSTemplateFormatVersion\"`", + "Template.Conditions map[string]any `json:\"Conditions\" yaml:\"Conditions\"`", + "Template.Description string `json:\"Description\" yaml:\"Description\"`", + "Template.Mappings map[string]any `json:\"Mappings\" yaml:\"Mappings\"`", + "Template.Outputs map[string]TemplateOutput `json:\"Outputs\" yaml:\"Outputs\"`", + "Template.Parameters map[string]TemplateParameter `json:\"Parameters\" yaml:\"Parameters\"`", + "Template.Resources map[string]TemplateResource `json:\"Resources\" yaml:\"Resources\"`", + "Template.Rules map[string]any `json:\"Rules\" yaml:\"Rules\"`", + "Template.Transform []string `json:\"Transform\" yaml:\"Transform\"`", + "Template.{UnmarshalJSON}", + "TemplateOutput.Condition string `json:\"Condition\" yaml:\"Condition\"`", + "TemplateOutput.Description string `json:\"Description\" yaml:\"Description\"`", + "TemplateOutput.Export *TemplateOutputExport `json:\"Export\" yaml:\"Export\"`", + "TemplateOutput.Value any `json:\"Value\" yaml:\"Value\"`", + "TemplateOutputExport.Name any `json:\"Name\" yaml:\"Name\"`", + "TemplateParameter.AllowedPattern string `json:\"AllowedPattern\" yaml:\"AllowedPattern\"`", + "TemplateParameter.AllowedValues []string `json:\"AllowedValues\" yaml:\"AllowedValues\"`", + "TemplateParameter.ConstraintDescription string `json:\"ConstraintDescription\" yaml:\"ConstraintDescription\"`", + "TemplateParameter.Default any `json:\"Default\" yaml:\"Default\"`", + "TemplateParameter.Description string `json:\"Description\" yaml:\"Description\"`", + "TemplateParameter.MaxLength *int `json:\"MaxLength\" yaml:\"MaxLength\"`", + "TemplateParameter.MaxValue *float64 `json:\"MaxValue\" yaml:\"MaxValue\"`", + "TemplateParameter.MinLength *int `json:\"MinLength\" yaml:\"MinLength\"`", + "TemplateParameter.MinValue *float64 `json:\"MinValue\" yaml:\"MinValue\"`", + "TemplateParameter.NoEcho bool `json:\"NoEcho\" yaml:\"NoEcho\"`", + "TemplateParameter.Type string `json:\"Type\" yaml:\"Type\"`", + "TemplateResource.Condition string `json:\"-\" yaml:\"-\"`", + "TemplateResource.DeletionPolicy string `json:\"DeletionPolicy\" yaml:\"DeletionPolicy\"`", + "TemplateResource.DependsOn []string `json:\"-\" yaml:\"-\"`", + "TemplateResource.Properties map[string]any `json:\"Properties\" yaml:\"Properties\"`", + "TemplateResource.Type string `json:\"Type\" yaml:\"Type\"`", + "TemplateResource.UpdateReplacePolicy string `json:\"UpdateReplacePolicy\" yaml:\"UpdateReplacePolicy\"`", + "TemplateResource.{UnmarshalJSON}", "TypeRegistrationRecord.Status string", "TypeRegistrationRecord.Token string", "TypeRegistrationRecord.TypeArn string", @@ -7490,6 +7523,7 @@ "backendSnapshot.AccountID string `json:\"accountID\"`", "backendSnapshot.ChangeSets map[string]map[string]*ChangeSet `json:\"changeSets\"`", "backendSnapshot.Events map[string][]StackEvent `json:\"events\"`", + "backendSnapshot.FailedRollbacks map[string]*pendingStackOp `json:\"failedRollbacks,omitempty\"`", "backendSnapshot.HandlerProgress map[string]string `json:\"handlerProgress\"`", "backendSnapshot.PendingStackOps map[string]*pendingStackOp `json:\"pendingStackOps,omitempty\"`", "backendSnapshot.Region string `json:\"region\"`", @@ -7508,15 +7542,35 @@ "pendingStackOp.Announced []string `json:\"announced,omitempty\"`", "pendingStackOp.Created []string `json:\"created,omitempty\"`", "pendingStackOp.DisableValidation bool `json:\"disableValidation,omitempty\"`", + "pendingStackOp.Done []string `json:\"done,omitempty\"`", + "pendingStackOp.FailedReasons map[string]string `json:\"failedReasons,omitempty\"`", "pendingStackOp.ForceDelete bool `json:\"forceDelete,omitempty\"`", + "pendingStackOp.InFlight map[string]string `json:\"inFlight,omitempty\"`", "pendingStackOp.Kind string `json:\"kind\"`", "pendingStackOp.OldParams []Parameter `json:\"oldParams,omitempty\"`", "pendingStackOp.OldTemplateBody string `json:\"oldTemplateBody,omitempty\"`", "pendingStackOp.OnFailure string `json:\"onFailure,omitempty\"`", + "pendingStackOp.Phase string `json:\"phase,omitempty\"`", + "pendingStackOp.PhysicalIDs map[string]string `json:\"physicalIds,omitempty\"`", "pendingStackOp.PrevResources map[string]*StackResource `json:\"prevResources,omitempty\"`", + "pendingStackOp.Remaining []string `json:\"remaining,omitempty\"`", + "pendingStackOp.Replaced []replacedRecord `json:\"replaced,omitempty\"`", "pendingStackOp.ResourceTypes []string `json:\"resourceTypes,omitempty\"`", "pendingStackOp.RetainExceptOnCreate bool `json:\"retainExceptOnCreate,omitempty\"`", - "pendingStackOp.RetainResources []string `json:\"retainResources,omitempty\"`" + "pendingStackOp.RetainResources []string `json:\"retainResources,omitempty\"`", + "pendingStackOp.SettleLater bool `json:\"settleLater,omitempty\"`", + "pendingStackOp.TemplateBody string `json:\"templateBody,omitempty\"`", + "pendingStackOp.Updated []string `json:\"updated,omitempty\"`", + "pendingStackOp.rt *walkRuntime", + "replacedRecord.Old StackResource `json:\"old\"`", + "replacedRecord.Policy string `json:\"policy,omitempty\"`", + "updateContext.oldParams map[string]string", + "updateContext.oldPhys map[string]string", + "updateContext.oldTmpl *Template", + "updateContext.retainExceptOnCreate bool", + "walkRuntime.params map[string]string", + "walkRuntime.tmpl *Template", + "walkRuntime.uc *updateContext" ], "version": 1 }, diff --git a/services/cloudformation/PARITY.md b/services/cloudformation/PARITY.md index c3882d06a6..df26351db3 100644 --- a/services/cloudformation/PARITY.md +++ b/services/cloudformation/PARITY.md @@ -284,7 +284,7 @@ structural_gaps: - "ListResourceScanRelatedResources always returns an empty list: no cross-resource relationship graph is computed for a scan, so MaxResults/Resources have nothing to page or seed from." items_still_open: - "Resource-type strictness is by service namespace only: an AWS::Svc::Res whose Svc is unknown to the spec fixture and the provisioner fails with \"Template format error: Unrecognized resource types: [X]\" (cfn_resource_services.json, generated by cmd/cfnattrgen), but an unmodelled resource of a known service still falls through to the stub path because the committed spec fixture lists types with attributes only. Property schemas are checked only at the primitive level (nested property types are not walked) and the resource spec marks required keys per legacy spec, so registry-only conditional requirements are not modeled; Rules AWS-specific parameter types resolve only for AWS::EC2::VPC/Subnet/SecurityGroup::Id (Fn::RefAll/ValueOf/ValueOfAll attributes per the Rule functions page: DefaultNetworkAcl, DefaultSecurityGroup, AvailabilityZone, VpcId, Tags.); other AWS-specific types yield empty lists. The Parameter-constraint, Rules-assertion and Unrecognized-parameter-type wordings are best-effort recollections of CloudFormation text, not SDK-verifiable." - - "Async stack provisioning (default 300ms per step; --cloudformation-provisioning-delay / GOPHERSTACK_CFN_PROVISIONING_DELAY, 0 = instant; a bare NewInMemoryBackend stays synchronous) models whole-stack transitions, not per-resource timing: inside a step every resource is created (or deleted) at once, so only the first wave of CREATE/UPDATE/DELETE_IN_PROGRESS events is visible during the window, replaced resources are cleaned up in the first UPDATE step rather than during UPDATE_COMPLETE_CLEANUP_IN_PROGRESS, nested stacks are provisioned eagerly and merely settle on later steps, and StackSet instance child stacks are provisioned inside the unit (their StackInstanceStatus window is per batch). Update rollback does not model UPDATE_ROLLBACK_FAILED retry through ContinueUpdateRollback, and the RetainResources/DeletionMode validation wording is a best-effort recollection." + - "Async provisioning of nested stacks and StackSet instances is not per resource: a nested AWS::CloudFormation::Stack is provisioned and deleted at once inside the parent's step and only settles on later steps (the parent resource fails with \"Embedded stack was not successfully created\" from that eager run), and StackSet instance child stacks are provisioned inside the unit (their StackInstanceStatus window is per batch). ContinueUpdateRollback accepts the NestedStackName.ResourceLogicalID skip form only for an embedded stack of the target stack that is itself UPDATE_ROLLBACK_FAILED; nested-stack updates are not modelled, so no embedded stack can reach that state. The RetainResources/DeletionMode validation wording is a best-effort recollection." - "Stack policy: Replacement Conditionally is treated as Update:Replace (deliberate, not an AWS-documented rule), and AWS's separate logical-ID/resource-type default-deny note is not modeled; NotAction/NotResource follow plain inversion (gopherstack-cqy3)." - "No nested-stack change-set or public-extension version machinery exists, so these stay unmodeled: CreateChangeSet IncludeNestedStacks (no nested-stack diff machinery) and the effect of ActivateType MajorVersion/VersionBump (validated for range, enum and exclusivity, but there is no public extension version catalog to select or bump a version in) (gopherstack-xhu2t)." - "SAM transform (AWS::Serverless-2016-10-31) still unexpanded: AWS::Serverless::CapacityProvider, NetworkConnector, MicrovmImage and WebFunction (their AWS::Lambda::* target types are not modelled by the stack engine); Application with a Serverless Application Repository Location (ApplicationId + SemanticVersion; use CreateCloudFormationTemplate and a URL Location); the translator's opt-in passthrough_metadata mode; HttpApi events that target an AWS::Serverless::Api; a user resource named ServerlessRestApi being replaced by the implicit API. Expanded but not provisioned by the stack engine: AWS::ApiGateway::DomainNameV2, BasePathMappingV2 and DomainNameAccessAssociation (PRIVATE REST custom domains) and AWS::AppSync::ApiCache and DomainNameApiAssociation (GraphQLApi Cache and DomainName) fail the stack as unsupported resource types. Unsupported SAM resources fail the stack/change set with an explicit reason, never silently dropped." @@ -2720,3 +2720,25 @@ StateMachine now matches the translator fixtures: DefinitionString as a Fn::Join ## 2026-11-13 extension and rollback options UpdateStack RetainExceptOnCreate (api_op_UpdateStack.go: newly created resources are deleted on rollback, including DeletionPolicy Retain ones, only when true) now governs update rollback; by default a newly created Retain/Snapshot resource survives UPDATE_ROLLBACK. RollbackStack RoleARN is validated and recorded on the stack. ActivateType TypeNameAlias registers the extension under the alias (DescribeType reports OriginalTypeName and OriginalTypeArn), alias reuse answers CFNRegistryException; MajorVersion 1-100000, VersionBump MAJOR|MINOR and their exclusivity are validated (API_ActivateType.html). RegisteredType gains OriginalTypeName and OriginalTypeArn. + +## 2026-11-21: per-resource async provisioning and ContinueUpdateRollback + +With a provisioning delay (or scheduler) every stack operation advances one dependency wave per step (`stack_walk.go`, `stack_create_walk.go`, `stack_update_walk.go`, `stack_update_rollback.go`); resources with no dependency between them share a wave. Each step finishes the wave announced by the previous one (`*_IN_PROGRESS` event with a physical id once created, then the `_COMPLETE`/`_FAILED` event) and announces the next, so DescribeStackResources, DescribeStackResource, ListStackResources and DescribeStackEvents show per-resource state while the stack is still in progress; announced resources appear with their in-progress status and no physical id (create) or the status overlaid on the live record (update, delete). The first wave is announced when CreateStack/UpdateStack/DeleteStack returns. A bare backend without a delay runs the same waves inline, so synchronous event order equals the async order (`TestAsyncWalk_SyncEventOrderMatchesAsync`). + +- Create: a failed resource emits `CREATE_FAILED`, the stack enters `ROLLBACK_IN_PROGRESS` and only the resources already created are deleted, newest dependents first, one wave per step; DisableRollback, OnFailure DO_NOTHING/DELETE/ROLLBACK and RetainExceptOnCreate keep their previous semantics. +- Update: changed and added resources go in dependency waves (unchanged ones take no step). `UPDATE_COMPLETE_CLEANUP_IN_PROGRESS` now covers the deletion of replaced physical resources (UpdateReplacePolicy honoured) and then of resources dropped from the template, one wave per step; outputs and exports are resolved after cleanup. A failed update rolls back newly created and replaced resources (deleted) and modified resources (reverted through the same in-place updater/extensibility update with the previous properties), and the stack template and parameters are restored. CancelUpdateStack takes effect between waves: announced-but-unstarted resources get `CREATE_FAILED`/`UPDATE_FAILED` "Resource creation/update cancelled" and the applied ones roll back. +- Delete: reverse dependency waves; Retain gives `DELETE_SKIPPED`, failures leave `DELETE_FAILED` resources and stack for a retry. +- UPDATE_ROLLBACK_FAILED: a resource that cannot be rolled back (restore or delete) ends `UPDATE_FAILED` with an `UPDATE_FAILED` event; the stack ends `UPDATE_ROLLBACK_FAILED` after the remaining resources were attempted. The rollback is kept in the additive `failedRollbacks` snapshot field. +- ContinueUpdateRollback is valid only from `UPDATE_ROLLBACK_FAILED` (otherwise a ValidationError `Stack: is in state and can not be continue rolled back.`); ResourcesToSkip (only resources that failed to roll back; `NestedStackName.ResourceLogicalID` handled for embedded stacks, see items_still_open) and ForceRollback (all failed resources, mutually exclusive with ResourcesToSkip) mark resources `UPDATE_COMPLETE`, the rest is retried through `UPDATE_ROLLBACK_IN_PROGRESS` -> `UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS` -> `UPDATE_ROLLBACK_COMPLETE` or back to `UPDATE_ROLLBACK_FAILED`. RoleARN is validated and recorded like RollbackStack; ClientRequestToken is accepted and ignored like the sibling operations. +- Persistence: in-flight operations carry `physicalIds`, `inFlight`, `done`, `remaining`, `created`, `updated`, `replaced`, `failedReasons` and `phase` (additive fields). Restoring a snapshot taken mid-flight with no scheduler settles the operation inline to its final status; with a scheduler it resumes step by step from the persisted state. +- Lifecycle: `Reset` clears every stack and cancels scheduled steps, `Close`/`Shutdown` cancels them (stacks stay in their in-progress status); the handler implements Resettable and Shutdowner including regional siblings. + +Tests: `stack_walk_test.go` (manual scheduler, `testing/synctest` for Close/Reset), `stack_transitions_test.go`. + +## Emulator choices where the vendor is silent + +- Event order inside a wave: every resource of a wave gets its in-progress event first, then each completes in logical-ID order; api_op_DescribeStackEvents.go and types.StackEvent only fix the fields and statuses, not the interleaving of parallel resources. Failures in a wave do not cancel the siblings of the wave, which still complete and are rolled back with the rest. +- Cancelled in-flight resources use the reasons "Resource creation cancelled" and "Resource update cancelled" (CloudFormation User Guide wording recalled from the console; not in the SDK). +- ContinueUpdateRollback: types/errors.go and api_op_ContinueUpdateRollback.go define no stack-state error, so the invalid-state error is a ValidationError with the text recalled from the service; the texts for skipping resources that did not fail a rollback ("... cannot be skipped ...") and for ForceRollback with ResourcesToSkip ("... mutually exclusive.") are emulator wording (the doc comment only says the combination returns a validation error). A skipped resource keeps its current record with status UPDATE_COMPLETE and the event reason "Resource update skipped by ContinueUpdateRollback". +- A resource whose delete fails during an update rollback is reported `UPDATE_FAILED` (not `DELETE_FAILED`), following the ContinueUpdateRollback doc comment that skippable resources are "in the UPDATE_FAILED state because a rollback failed". +- Deleting a stack while an update is in flight is accepted as before; resources replaced but not yet cleaned up are not deleted. diff --git a/services/cloudformation/export_test.go b/services/cloudformation/export_test.go index 2ef3f91c1e..7d0c12239c 100644 --- a/services/cloudformation/export_test.go +++ b/services/cloudformation/export_test.go @@ -6,7 +6,7 @@ import ( accessanalyzerbackend "github.com/blackbirdworks/gopherstack/services/accessanalyzer" ) -// RollbackUpdateResourcesForTest exposes rollbackUpdateResources for +// RollbackUpdateResourcesForTest exposes beginUpdateRollbackLocked for // white-box testing: updateResources creates newly-added resources by // iterating a Go map, so which of two new resources is created first (and // thus whether it's in `created` when a sibling fails) isn't deterministic @@ -29,7 +29,8 @@ func (b *InMemoryBackend) RollbackUpdateResourcesForTest( prevResources[k] = &cp } - b.rollbackUpdateResources(ctx, stack, prevResources, created, true) + op := &pendingStackOp{PrevResources: prevResources, Created: created, RetainExceptOnCreate: true} + b.beginUpdateRollbackLocked(ctx, stack, op, stack.StackStatusReason) } // RegisterForTest exposes MacroRegistry.register for test-only use. diff --git a/services/cloudformation/handler_http_test.go b/services/cloudformation/handler_http_test.go index e268085ce7..770418d3de 100644 --- a/services/cloudformation/handler_http_test.go +++ b/services/cloudformation/handler_http_test.go @@ -576,7 +576,7 @@ func TestHandler_ContinueUpdateRollback_HTTP(t *testing.T) { "Action": {"ContinueUpdateRollback"}, "StackName": {"cur-http"}, }) - resp.mustOK(t) + assert.Equal(t, http.StatusBadRequest, resp.Status) } func TestHandler_CancelUpdateStack_HTTP(t *testing.T) { diff --git a/services/cloudformation/handler_stacks.go b/services/cloudformation/handler_stacks.go index 87492dc5ef..848b617bf8 100644 --- a/services/cloudformation/handler_stacks.go +++ b/services/cloudformation/handler_stacks.go @@ -407,7 +407,14 @@ func (h *Handler) handleContinueUpdateRollback(form url.Values, c *echo.Context) return h.xmlError(c, "ValidationError", "StackName is required") } - if err := h.Backend.ContinueUpdateRollback(c.Request().Context(), stackName); err != nil { + in := ContinueRollbackInput{ + ClientRequestToken: form.Get("ClientRequestToken"), + RoleARN: form.Get("RoleARN"), + ForceRollback: strings.EqualFold(form.Get("ForceRollback"), "true"), + ResourcesToSkip: parseMemberList(form, "ResourcesToSkip."), + } + + if err := h.Backend.ContinueUpdateRollback(c.Request().Context(), stackName, in); err != nil { return h.xmlError(c, "ValidationError", err.Error()) } diff --git a/services/cloudformation/handler_supplemental_test.go b/services/cloudformation/handler_supplemental_test.go index d5001a26df..27b69c6d92 100644 --- a/services/cloudformation/handler_supplemental_test.go +++ b/services/cloudformation/handler_supplemental_test.go @@ -377,7 +377,7 @@ func TestHandler_ContinueUpdateRollback(t *testing.T) { postForm(t, h, "Action=CreateStack&StackName=my-stack&TemplateBody="+simpleTemplate) rec := postForm(t, h, "Action=ContinueUpdateRollback&StackName=my-stack") - assert.Equal(t, 200, rec.Code) + assert.Equal(t, 400, rec.Code, "only UPDATE_ROLLBACK_FAILED stacks can continue a rollback") }) } } diff --git a/services/cloudformation/persistence.go b/services/cloudformation/persistence.go index 584c527c42..66d75e668d 100644 --- a/services/cloudformation/persistence.go +++ b/services/cloudformation/persistence.go @@ -45,6 +45,7 @@ type backendSnapshot struct { ResourceDriftStatus map[string]map[string]string `json:"resourceDriftStatus"` ResourceDriftDetail map[string]map[string]StackResourceDrift `json:"resourceDriftDetail"` PendingStackOps map[string]*pendingStackOp `json:"pendingStackOps,omitempty"` + FailedRollbacks map[string]*pendingStackOp `json:"failedRollbacks,omitempty"` AccountID string `json:"accountID"` Region string `json:"region"` Version int `json:"version"` @@ -85,6 +86,7 @@ func (b *InMemoryBackend) Snapshot(ctx context.Context) []byte { ResourceDriftStatus: b.resourceDriftStatus, ResourceDriftDetail: b.resourceDriftDetail, PendingStackOps: b.pendingOps, + FailedRollbacks: b.failedRollbacks, AccountID: b.accountID, Region: b.region, } @@ -206,6 +208,10 @@ func (b *InMemoryBackend) assignSnapshotFields(snap backendSnapshot) { if b.pendingOps == nil { b.pendingOps = make(map[string]*pendingStackOp) } + b.failedRollbacks = snap.FailedRollbacks + if b.failedRollbacks == nil { + b.failedRollbacks = make(map[string]*pendingStackOp) + } b.accountID = snap.AccountID b.region = snap.Region } @@ -261,3 +267,30 @@ func (h *Handler) Restore(ctx context.Context, data []byte) error { func(*Handler) {}, ) } + +// Reset implements service.Resettable: it clears every region and cancels scheduled provisioning. +func (h *Handler) Reset() { + type resetter interface{ Reset() } + + if r, ok := h.Backend.(resetter); ok { + r.Reset() + } + + for _, p := range h.peers.Drain() { + p.Reset() + p.Shutdown(context.Background()) + } +} + +// Shutdown implements service.Shutdowner: no scheduled provisioning step outlives the service. +func (h *Handler) Shutdown(context.Context) { + type closer interface{ Close() } + + if c, ok := h.Backend.(closer); ok { + c.Close() + } + + for _, p := range h.peers.All() { + p.Shutdown(context.Background()) + } +} diff --git a/services/cloudformation/regions.go b/services/cloudformation/regions.go index 27266a34d4..d9780cdfe5 100644 --- a/services/cloudformation/regions.go +++ b/services/cloudformation/regions.go @@ -87,8 +87,13 @@ func (b *InMemoryBackend) inheritWiring(home *InMemoryBackend) { defer home.mu.RUnlock() b.orgDirectory = home.orgDirectory - b.provisionSchedule = home.provisionSchedule b.provisionDelay = home.provisionDelay + b.provisionSchedule = home.provisionSchedule + + if home.provisionDelay > 0 { + b.provisionSchedule = b.delayScheduler(home.provisionDelay) + } + b.quotaGate = home.quotaGate } diff --git a/services/cloudformation/resource_update.go b/services/cloudformation/resource_update.go index 95aff2f9f1..ba926a7591 100644 --- a/services/cloudformation/resource_update.go +++ b/services/cloudformation/resource_update.go @@ -3,10 +3,8 @@ package cloudformation import ( "context" "errors" - "fmt" "maps" "reflect" - "slices" "sort" "time" ) @@ -27,12 +25,6 @@ type updateContext struct { retainExceptOnCreate bool } -// replacedResource is an old physical resource awaiting cleanup after a replacement. -type replacedResource struct { - old StackResource - policy string -} - type resourceChange struct { changed []string replace bool @@ -66,49 +58,6 @@ func customNameProperty(resourceType string) string { return "" } -// updatePass accumulates what a stack update has done so far, for rollback and cleanup. -type updatePass struct { - uc *updateContext - params map[string]string - phys map[string]string - created []string - replaced []*replacedResource -} - -// applyResourceUpdate creates, replaces or updates one resource; the error carries the stack status reason. -func (b *InMemoryBackend) applyResourceUpdate( - ctx context.Context, stack *Stack, res TemplateResource, logicalID string, pass *updatePass, -) error { - existing, exists := b.resources[stack.StackID][logicalID] - if !exists { - physicalID, err := b.createUpdateResource(ctx, stack, logicalID, res, pass.params, pass.phys) - if err != nil { - return fmt.Errorf("resource %s: %w", logicalID, err) - } - - pass.phys[logicalID] = physicalID - pass.created = append(pass.created, logicalID) - - return nil - } - - out, err := b.updateExistingResource(ctx, stack, logicalID, res, existing, pass.uc, pass.params, pass.phys) - if err != nil { - return fmt.Errorf("resource %s update: %w", logicalID, err) - } - - if out.replaced != nil { - pass.replaced = append(pass.replaced, out.replaced) - pass.created = append(pass.created, logicalID) - } - - return nil -} - -type updateOutcome struct { - replaced *replacedResource -} - func resolvedProps(props map[string]any, params, phys map[string]string) map[string]any { out, _ := resolveDeep(props, params, phys).(map[string]any) @@ -199,107 +148,24 @@ func customNameUnchanged(res TemplateResource, existing *StackResource, uc *upda return name, resolve(oldProps[key], oldParams, oldPhys) == name } -// updateExistingResource applies a template change to a resource that already -// exists: nothing for an unchanged resource, create-new for a replacement, an -// in-place update otherwise. It reports whether a replacement was started. -func (b *InMemoryBackend) updateExistingResource( - ctx context.Context, - stack *Stack, - logicalID string, - res TemplateResource, - existing *StackResource, - uc *updateContext, - params, phys map[string]string, -) (updateOutcome, error) { - if isCFNExtensibilityType(res.Type) { - return updateOutcome{}, b.updateExtensibilityResource(ctx, stack, logicalID, res, existing) - } - - change := b.planResourceUpdate(logicalID, res, existing, uc, params, phys) - if len(change.changed) == 0 { - existing.DeletionPolicy = res.DeletionPolicy - - return updateOutcome{}, nil - } - - if change.replace { - repl, err := b.replaceResource(ctx, stack, logicalID, res, existing, uc, params, phys) - - return updateOutcome{replaced: repl}, err - } - - b.addProgressEvent( - stack.StackID, stack.StackName, logicalID, existing.PhysicalID, res.Type, statusUpdateInProgress, - ) - - _, err := b.creator.UpdateInPlace(ctx, res.Type, existing.PhysicalID, res.Properties, params, phys) - if err != nil { - b.addEvent( - stack.StackID, stack.StackName, logicalID, existing.PhysicalID, res.Type, statusUpdateFailed, err.Error(), - ) - - return updateOutcome{}, err - } - - existing.Properties = res.Properties - existing.DeletionPolicy = res.DeletionPolicy - existing.Status = statusUpdateComplete - existing.Timestamp = time.Now() - b.addEvent(stack.StackID, stack.StackName, logicalID, existing.PhysicalID, res.Type, statusUpdateComplete, "") - - return updateOutcome{}, nil -} - func (b *InMemoryBackend) replaceResource( ctx context.Context, stack *Stack, logicalID string, res TemplateResource, existing *StackResource, - uc *updateContext, - params, phys map[string]string, -) (*replacedResource, error) { - if name, same := customNameUnchanged(res, existing, uc, params, phys); same { - err := fmt.Errorf("%w. Rename %s and update the stack again", ErrCustomNamedReplacement, name) - b.addEvent( - stack.StackID, stack.StackName, logicalID, existing.PhysicalID, res.Type, statusUpdateFailed, err.Error(), - ) - - return nil, err - } - - b.addEvent( - stack.StackID, stack.StackName, logicalID, existing.PhysicalID, res.Type, - statusUpdateInProgress, reasonReplacementRequired, - ) - + pass *updatePass, +) (*replacedRecord, error) { old := *existing - newPhysical, err := b.creator.Create( - parentStackIDKey.Set(ctx, stack.StackID), - logicalID, - res.Type, - res.Properties, - params, - phys, - ) + newPhysical, err := b.creator.Create(ctx, logicalID, res.Type, res.Properties, pass.params, pass.phys) if err != nil { - b.addEvent( - stack.StackID, stack.StackName, logicalID, "", res.Type, statusUpdateFailed, err.Error(), - ) + b.addResourceEvent(stack, logicalID, "", res.Type, statusUpdateFailed, err.Error()) return nil, err } - b.addEvent( - stack.StackID, - stack.StackName, - logicalID, - newPhysical, - res.Type, - statusUpdateInProgress, - reasonCreationInitiated, - ) + b.addResourceEvent(stack, logicalID, newPhysical, res.Type, statusUpdateInProgress, reasonCreationInitiated) b.resources[stack.StackID][logicalID] = &StackResource{ Timestamp: time.Now(), @@ -312,49 +178,16 @@ func (b *InMemoryBackend) replaceResource( StackName: stack.StackName, DeletionPolicy: res.DeletionPolicy, } - phys[logicalID] = newPhysical + pass.phys[logicalID] = newPhysical - b.addEvent(stack.StackID, stack.StackName, logicalID, newPhysical, res.Type, statusUpdateComplete, "") + b.addResourceEvent(stack, logicalID, newPhysical, res.Type, statusUpdateComplete, "") - return &replacedResource{old: old, policy: res.UpdateReplacePolicy}, nil -} - -// cleanupReplacedResources deletes (or, per UpdateReplacePolicy, retains) the -// old physical resources once the whole update has succeeded. -func (b *InMemoryBackend) cleanupReplacedResources(ctx context.Context, stack *Stack, replaced []*replacedResource) { - if len(replaced) == 0 { - return - } - - physIDs := b.deleteResolveContext(stack) - - for _, r := range slices.Backward(replaced) { - b.addEvent( - stack.StackID, stack.StackName, r.old.LogicalID, r.old.PhysicalID, r.old.Type, statusDeleteInProgress, "", - ) - - if r.policy != deletionPolicyRetain && r.policy != deletionPolicySnapshot { - if err := b.creator.Delete(ctx, r.old.Type, r.old.PhysicalID, r.old.Properties, physIDs); err != nil { - b.addEvent( - stack.StackID, stack.StackName, r.old.LogicalID, r.old.PhysicalID, r.old.Type, - statusDeleteFailed, err.Error(), - ) - - continue - } - } - - b.addEvent( - stack.StackID, stack.StackName, r.old.LogicalID, r.old.PhysicalID, r.old.Type, statusDeleteComplete, "", - ) - } + return &replacedRecord{Old: old, Policy: res.UpdateReplacePolicy}, nil } func (b *InMemoryBackend) updateExtensibilityResource( ctx context.Context, stack *Stack, logicalID string, res TemplateResource, existing *StackResource, ) error { - b.addEvent(stack.StackID, stack.StackName, logicalID, existing.PhysicalID, res.Type, statusUpdateInProgress, "") - err := b.creator.Update(ctx, logicalID, res.Type, existing.PhysicalID, res.Properties, existing.Properties) if err != nil { b.addEvent( diff --git a/services/cloudformation/stack_async.go b/services/cloudformation/stack_async.go index f0b36281cb..5127f2ffbe 100644 --- a/services/cloudformation/stack_async.go +++ b/services/cloudformation/stack_async.go @@ -2,13 +2,13 @@ package cloudformation import ( "context" - "slices" "strings" "time" ) const ( pendingCreate = "create" + pendingCreateWalk = "createWalk" pendingCreateSettle = "createSettle" pendingRollbackCreate = "rollbackCreate" pendingUpdate = "update" @@ -25,30 +25,28 @@ const ( // so a restored snapshot can finish it. type pendingStackOp struct { PrevResources map[string]*StackResource `json:"prevResources,omitempty"` - Kind string `json:"kind"` - OnFailure string `json:"onFailure,omitempty"` - OldTemplateBody string `json:"oldTemplateBody,omitempty"` - ResourceTypes []string `json:"resourceTypes,omitempty"` - OldParams []Parameter `json:"oldParams,omitempty"` - Created []string `json:"created,omitempty"` - Announced []string `json:"announced,omitempty"` - RetainResources []string `json:"retainResources,omitempty"` - DisableValidation bool `json:"disableValidation,omitempty"` - RetainExceptOnCreate bool `json:"retainExceptOnCreate,omitempty"` - ForceDelete bool `json:"forceDelete,omitempty"` -} - -type updateOptions struct { - resourceTypes []string - disableValidation bool - retainExceptOnCreate bool -} - -func (op *pendingStackOp) updateOptions() updateOptions { - return updateOptions{ - resourceTypes: op.ResourceTypes, disableValidation: op.DisableValidation, - retainExceptOnCreate: op.RetainExceptOnCreate, - } + PhysicalIDs map[string]string `json:"physicalIds,omitempty"` + InFlight map[string]string `json:"inFlight,omitempty"` + FailedReasons map[string]string `json:"failedReasons,omitempty"` + rt *walkRuntime + Kind string `json:"kind"` + Phase string `json:"phase,omitempty"` + OnFailure string `json:"onFailure,omitempty"` + OldTemplateBody string `json:"oldTemplateBody,omitempty"` + TemplateBody string `json:"templateBody,omitempty"` + ResourceTypes []string `json:"resourceTypes,omitempty"` + OldParams []Parameter `json:"oldParams,omitempty"` + Created []string `json:"created,omitempty"` + Updated []string `json:"updated,omitempty"` + Done []string `json:"done,omitempty"` + Remaining []string `json:"remaining,omitempty"` + Replaced []replacedRecord `json:"replaced,omitempty"` + Announced []string `json:"announced,omitempty"` + RetainResources []string `json:"retainResources,omitempty"` + DisableValidation bool `json:"disableValidation,omitempty"` + RetainExceptOnCreate bool `json:"retainExceptOnCreate,omitempty"` + ForceDelete bool `json:"forceDelete,omitempty"` + SettleLater bool `json:"settleLater,omitempty"` } // SetProvisioningScheduler makes top-level stack operations return in their @@ -74,7 +72,58 @@ func (b *InMemoryBackend) SetProvisioningDelay(d time.Duration) { return } - b.SetProvisioningScheduler(func(run func()) { time.AfterFunc(d, run) }) + b.SetProvisioningScheduler(b.delayScheduler(d)) +} + +// delayScheduler runs each step d later on a timer the backend can cancel; it is +// only called from scheduleLocked, with b.mu held. +func (b *InMemoryBackend) delayScheduler(d time.Duration) func(run func()) { + return func(run func()) { + b.timerSeq++ + id := b.timerSeq + + b.delayTimers[id] = time.AfterFunc(d, func() { + b.mu.Lock("provisioningTimer") + delete(b.delayTimers, id) + b.mu.Unlock() + + run() + }) + } +} + +// cancelProvisioningLocked drops every scheduled step without running it. +func (b *InMemoryBackend) cancelProvisioningLocked() { + for id, t := range b.delayTimers { + if t.Stop() { + b.provisionWG.Done() + } + + delete(b.delayTimers, id) + } + + clear(b.pendingOps) + b.signalSettledLocked() +} + +// Close cancels every scheduled provisioning step; stacks still in flight stay in +// their *_IN_PROGRESS status and later operations run synchronously. +func (b *InMemoryBackend) Close() { + b.mu.Lock("Close") + defer b.mu.Unlock() + + b.cancelProvisioningLocked() + b.provisionSchedule = nil +} + +// Reset cancels scheduled provisioning and clears all stacks and their state. +func (b *InMemoryBackend) Reset() { + b.mu.Lock("Reset") + defer b.mu.Unlock() + + b.cancelProvisioningLocked() + b.registry.ResetAll() + b.initState() } // WaitForStackProvisioning blocks until every scheduled stack step has run. @@ -169,16 +218,12 @@ func (b *InMemoryBackend) runPendingOpLocked(ctx context.Context, stackID string return } - b.stepAsync = true - b.announced = make(map[string]struct{}, len(op.Announced)) + op.legacyInFlight() - for _, key := range op.Announced { - b.announced[key] = struct{}{} - } + b.stepAsync = true defer func() { b.stepAsync = false - b.announced = nil b.settleChangeSetsLocked(stack) b.signalSettledLocked() }() @@ -188,13 +233,13 @@ func (b *InMemoryBackend) runPendingOpLocked(ctx context.Context, stackID string func (b *InMemoryBackend) runOpLocked(ctx context.Context, stack *Stack, op *pendingStackOp) { switch op.Kind { - case pendingCreate, pendingCreateSettle, pendingRollbackCreate: + case pendingCreate, pendingCreateWalk, pendingCreateSettle, pendingRollbackCreate: b.runCreateOpLocked(ctx, stack, op) case pendingUpdate, pendingUpdateCleanup, pendingRollbackUpdate, pendingRollbackUpdateCleanup: b.runUpdateOpLocked(ctx, stack, op) case pendingDelete: if stack.StackStatus == statusDeleteInProgress { - b.runDeleteLocked(ctx, stack, deleteSettings{retain: op.RetainResources, force: op.ForceDelete}) + b.runDeleteLocked(ctx, stack, op) } case pendingDeleteFinalize: if stack.StackStatus == statusDeleteInProgress { @@ -207,12 +252,17 @@ func (b *InMemoryBackend) runCreateOpLocked(ctx context.Context, stack *Stack, o switch op.Kind { case pendingCreate: if stack.StackStatus == statusCreateInProgress { - b.finishCreateLocked(ctx, stack, stack.Parameters, createFinish{ - onFailure: op.OnFailure, - resourceTypes: op.ResourceTypes, - disableValidation: op.DisableValidation, - retainExceptOnCreate: op.RetainExceptOnCreate, - }) + b.finishCreateLocked(ctx, stack, stack.Parameters, op.createFinish().withAnnounced(op.InFlight)) + } + case pendingCreateWalk: + if stack.StackStatus != statusCreateInProgress { + return + } + + b.walkCreateLocked(ctx, stack, op) + + if !b.createWalkPending(stack) { + b.settleCreateLocked(ctx, stack, op.createFinish()) } case pendingCreateSettle: if stack.StackStatus != statusCreateInProgress { @@ -228,10 +278,7 @@ func (b *InMemoryBackend) runCreateOpLocked(ctx context.Context, stack *Stack, o b.completeCreateLocked(stack) case pendingRollbackCreate: if stack.StackStatus == statusRollbackInProgress { - b.finishCreateRollbackLocked(ctx, stack, op.Created, createFinish{ - onFailure: op.OnFailure, - retainExceptOnCreate: op.RetainExceptOnCreate, - }) + b.runCreateRollbackLocked(ctx, stack, op) } } } @@ -243,30 +290,22 @@ func (b *InMemoryBackend) runUpdateOpLocked(ctx context.Context, stack *Stack, o return } - if !b.applyTemplateToStack(ctx, stack, op.updateOptions(), op.OldTemplateBody, op.OldParams) { - return - } - - stack.StackStatus = statusUpdateCleanupProgress - - b.stageLocked(ctx, stack.StackID, &pendingStackOp{Kind: pendingUpdateCleanup}, func() { - b.completeUpdateLocked(stack) - }) + b.runUpdateStepLocked(ctx, stack, op) case pendingUpdateCleanup: if stack.StackStatus != statusUpdateCleanupProgress { return } - if b.childrenInProgressLocked(stack) { - b.scheduleLocked(ctx, stack.StackID, op) + if op.Phase == phaseSettle { + b.settleUpdateLocked(ctx, stack) return } - b.completeUpdateLocked(stack) + b.walkUpdateCleanupLocked(ctx, stack, op) case pendingRollbackUpdate: if stack.StackStatus == statusUpdateRollbackInProgress { - b.runUpdateRollbackLocked(ctx, stack, op.PrevResources, op.Created, op.RetainExceptOnCreate) + b.runUpdateRollbackLocked(ctx, stack, op) } case pendingRollbackUpdateCleanup: if stack.StackStatus == statusUpdateRollbackCleanup { @@ -311,84 +350,6 @@ func (b *InMemoryBackend) settleChangeSetsLocked(stack *Stack) { } } -// addProgressEvent records a plain *_IN_PROGRESS resource event unless the -// operation already announced it when it started. -func (b *InMemoryBackend) addProgressEvent(stackID, stackName, logicalID, physicalID, resourceType, status string) { - key := announceKey(logicalID, status) - if _, ok := b.announced[key]; ok { - delete(b.announced, key) - - return - } - - b.addEvent(stackID, stackName, logicalID, physicalID, resourceType, status, "") -} - -func announceKey(logicalID, status string) string { return logicalID + "|" + status } - -// announceLocked emits the first wave of resource events at operation start -// and returns their keys so the later step does not repeat them. -func (b *InMemoryBackend) announceLocked( - stack *Stack, status string, ids []string, resources map[string]TemplateResource, -) []string { - keys := make([]string, 0, len(ids)) - - for _, id := range ids { - b.addEvent(stack.StackID, stack.StackName, id, "", resources[id].Type, status, "") - keys = append(keys, announceKey(id, status)) - } - - return keys -} - -// firstWave returns the sorted members of want that start first: those that -// depend on no other member (creates/updates), or that no other member -// depends on (leaves, for deletes). -func firstWave(resources map[string]TemplateResource, want []string, leaves bool) []string { - all := make(map[string]struct{}, len(resources)) - for id := range resources { - all[id] = struct{}{} - } - - inWant := make(map[string]struct{}, len(want)) - for _, id := range want { - inWant[id] = struct{}{} - } - - blocked := make(map[string]bool, len(want)) - - for _, id := range want { - res, ok := resources[id] - if !ok { - continue - } - - for _, dep := range resourceDependencies(id, res, all) { - if _, ok = inWant[dep]; !ok { - continue - } - - if leaves { - blocked[dep] = true - } else { - blocked[id] = true - } - } - } - - out := make([]string, 0, len(want)) - - for _, id := range want { - if _, ok := resources[id]; ok && !blocked[id] { - out = append(out, id) - } - } - - slices.Sort(out) - - return out -} - // resumePendingOpsLocked finishes operations a restored snapshot captured // mid-flight; with no scheduler they run inline. func (b *InMemoryBackend) resumePendingOpsLocked(ctx context.Context) { diff --git a/services/cloudformation/stack_create_walk.go b/services/cloudformation/stack_create_walk.go new file mode 100644 index 0000000000..293478d8d1 --- /dev/null +++ b/services/cloudformation/stack_create_walk.go @@ -0,0 +1,364 @@ +package cloudformation + +import ( + "context" + "fmt" + "slices" + "time" +) + +// announceCreateLocked emits CREATE_IN_PROGRESS for the resources that start +// first, so the window shows them before the first step runs. +func (b *InMemoryBackend) announceCreateLocked(stack *Stack, params []Parameter) map[string]string { + tmpl, err := ParseTemplate(stack.TemplateBody) + if err != nil { + return nil + } + + pruneConditional(tmpl, ResolveParameters(tmpl, params)) + + wave := nextWave(tmpl.Resources, sortedKeys(tmpl.Resources), false) + inFlight := make(map[string]string, len(wave)) + + for _, id := range wave { + inFlight[id] = statusCreateInProgress + b.addResourceEvent(stack, id, "", tmpl.Resources[id].Type, statusCreateInProgress, "") + } + + return inFlight +} + +func seedCreatePhysicalIDs(stack *Stack, tmpl *Template, accountID, region string) map[string]string { + phys := map[string]string{ + "_StackId": stack.StackID, + "_StackName": stack.StackName, + physIDAccountIDKey: accountID, + physIDRegionKey: region, + } + + for id, res := range tmpl.Resources { + phys[physIDResourceTypeKey(id)] = res.Type + } + + return phys +} + +func (b *InMemoryBackend) newCreateWalk( + stack *Stack, rt *walkRuntime, opts createFinish, +) *pendingStackOp { + return &pendingStackOp{ + Kind: pendingCreateWalk, + OnFailure: opts.onFailure, + ResourceTypes: opts.resourceTypes, + DisableValidation: opts.disableValidation, + RetainExceptOnCreate: opts.retainExceptOnCreate, + PhysicalIDs: seedCreatePhysicalIDs(stack, rt.tmpl, b.accountID, b.region), + InFlight: opts.announced, + rt: rt, + } +} + +func (op *pendingStackOp) createFinish() createFinish { + return createFinish{ + onFailure: op.OnFailure, + resourceTypes: op.ResourceTypes, + disableValidation: op.DisableValidation, + retainExceptOnCreate: op.RetainExceptOnCreate, + } +} + +// templateRuntime re-derives a resumed walk's template and resolved parameters. +func (b *InMemoryBackend) templateRuntime(ctx context.Context, stack *Stack) (*walkRuntime, error) { + tmpl, err := ParseTemplate(stack.TemplateBody) + if err != nil { + return nil, err + } + + if dynErr := ResolveDynamicRefsInTemplate(ctx, tmpl, b.resolver); dynErr != nil { + return nil, dynErr + } + + params := ResolveParameters(tmpl, stack.Parameters) + pruneConditional(tmpl, params) + + return &walkRuntime{tmpl: tmpl, params: params}, nil +} + +// createWalkPending reports whether a create walk has a later step scheduled. +func (b *InMemoryBackend) createWalkPending(stack *Stack) bool { + op := b.pendingOps[stack.StackID] + + return op != nil && op.Kind == pendingCreateWalk +} + +// walkCreateLocked creates the template's resources one dependency wave at a +// time: each step finishes the announced wave and announces the next. +func (b *InMemoryBackend) walkCreateLocked(ctx context.Context, stack *Stack, op *pendingStackOp) { + if op.rt == nil { + rt, err := b.templateRuntime(ctx, stack) + if err != nil { + b.failAndRollback(ctx, stack, op.createFinish(), err.Error()) + + return + } + + op.rt = rt + } + + ctx = parentStackIDKey.Set(ctx, stack.StackID) + + for { + if len(op.InFlight) > 0 { + if reason := b.executeCreateWave(ctx, stack, op); reason != "" { + b.enterCreateRollbackLocked(ctx, stack, op.Created, op.createFinish(), reason) + + return + } + } + + remaining := b.createRemaining(op) + if len(remaining) == 0 { + b.finalizeCreateLocked(ctx, stack, op) + + return + } + + wave := nextWave(op.rt.tmpl.Resources, remaining, false) + + op.InFlight = make(map[string]string, len(wave)) + + for _, id := range wave { + op.InFlight[id] = statusCreateInProgress + b.addResourceEvent(stack, id, "", op.rt.tmpl.Resources[id].Type, statusCreateInProgress, "") + } + + if b.stageWalk(ctx, stack, op) { + return + } + } +} + +func (b *InMemoryBackend) createRemaining(op *pendingStackOp) []string { + remaining := make([]string, 0, len(op.rt.tmpl.Resources)) + + for _, id := range sortedKeys(op.rt.tmpl.Resources) { + if !slices.Contains(op.Created, id) { + remaining = append(remaining, id) + } + } + + return remaining +} + +// executeCreateWave creates the announced resources and returns the failure reason, if any. +func (b *InMemoryBackend) executeCreateWave(ctx context.Context, stack *Stack, op *pendingStackOp) string { + ids := sortedKeys(op.InFlight) + op.InFlight = nil + reason := "" + + for _, id := range ids { + res, ok := op.rt.tmpl.Resources[id] + if !ok { + continue + } + + physicalID, err := b.creator.Create(ctx, id, res.Type, res.Properties, op.rt.params, op.PhysicalIDs) + if err != nil { + b.addResourceEvent(stack, id, "", res.Type, statusCreateFailed, err.Error()) + + if reason == "" { + reason = err.Error() + stack.StackStatusReason = fmt.Sprintf("resource %s: %v", id, err) + } + + continue + } + + b.addResourceEvent(stack, id, physicalID, res.Type, statusCreateInProgress, reasonCreationInitiated) + op.PhysicalIDs[id] = physicalID + b.resources[stack.StackID][id] = &StackResource{ + Timestamp: time.Now(), LogicalID: id, PhysicalID: physicalID, Type: res.Type, + Status: statusCreateComplete, Properties: res.Properties, StackID: stack.StackID, + StackName: stack.StackName, DeletionPolicy: res.DeletionPolicy, + } + b.addResourceEvent(stack, id, physicalID, res.Type, statusCreateComplete, "") + op.Created = append(op.Created, id) + } + + return reason +} + +// finalizeCreateLocked resolves outputs and registers exports once every resource exists. +func (b *InMemoryBackend) finalizeCreateLocked(_ context.Context, stack *Stack, op *pendingStackOp) { + tmpl := op.rt.tmpl + + resourceTypes := make(map[string]string, len(tmpl.Resources)) + for logicalID, res := range tmpl.Resources { + resourceTypes[logicalID] = res.Type + } + + stack.ResourceAttrs = extractAttrStash(op.PhysicalIDs, resourceTypes) + rctx := resolveCtx{ + params: op.rt.params, + physicalIDs: op.PhysicalIDs, + resourceTypes: resourceTypes, + exports: b.buildExportsMap(), + conditions: evaluateConditions(tmpl.Conditions, op.rt.params, op.PhysicalIDs), + mappings: tmpl.Mappings, + accountID: b.accountID, + region: b.region, + stackName: stack.StackName, + } + + var exportMap map[string]string + stack.Outputs, exportMap = resolveOutputsWithContext(tmpl, rctx) + + if regErr := b.registerExports(stack.StackID, exportMap); regErr != nil { + stack.StackStatus = statusCreateFailed + stack.StackStatusReason = regErr.Error() + b.addStackEvent(stack, statusCreateFailed, regErr.Error()) + } +} + +// enterCreateRollbackLocked moves a failed create to ROLLBACK_IN_PROGRESS and +// undoes created resource by resource, in the next steps when async. +func (b *InMemoryBackend) enterCreateRollbackLocked( + ctx context.Context, stack *Stack, created []string, opts createFinish, reason string, +) { + if stack.DisableRollback { + stack.StackStatus = statusCreateFailed + + return + } + + stack.StackStatus = statusRollbackInProgress + b.addStackEvent(stack, statusRollbackInProgress, reason) + + op := &pendingStackOp{ + Kind: pendingRollbackCreate, + OnFailure: opts.onFailure, + RetainExceptOnCreate: opts.retainExceptOnCreate, + Created: created, + Remaining: slices.Clone(created), + TemplateBody: stack.TemplateBody, + } + + b.announceReverseWave(stack, op, b.deleteWalk(stack, op, createRollbackRules(op))) + b.stageLocked(ctx, stack.StackID, op, func() { b.runCreateRollbackLocked(ctx, stack, op) }) +} + +func createRollbackRules(op *pendingStackOp) deleteRules { + return deleteRules{ + retainStatus: statusDeleteComplete, failStatus: statusDeleteFailed, ignorePolicy: op.RetainExceptOnCreate, + } +} + +// runCreateRollbackLocked deletes the resources a failed create made and +// settles the stack ROLLBACK_COMPLETE or ROLLBACK_FAILED. +func (b *InMemoryBackend) runCreateRollbackLocked(ctx context.Context, stack *Stack, op *pendingStackOp) { + if b.walkReverseLocked(ctx, stack, op, b.deleteWalk(stack, op, createRollbackRules(op))) { + return + } + + opts := op.createFinish() + + if len(op.FailedReasons) == 0 { + b.addStackEvent(stack, statusRollbackComplete, "") + stack.StackStatus = statusRollbackComplete + b.deleteAfterFailedCreateLocked(ctx, stack, opts) + + return + } + + b.addStackEvent(stack, statusRollbackFailed, reasonRollbackDeleteFailed) + stack.StackStatus = statusRollbackFailed + stack.StackStatusReason = reasonRollbackDeleteFailed +} + +// deleteRules says how a reverse walk treats retention policies and failures. +type deleteRules struct { + retainStatus string + failStatus string + callerRetain []string + ignorePolicy bool + forceDrop bool +} + +// deleteWalk builds the reverse walk that deletes op.Remaining from the stack's live resources. +func (b *InMemoryBackend) deleteWalk(stack *Stack, op *pendingStackOp, rules deleteRules) reverseWalk { + var deps map[string]TemplateResource + + if tmpl, err := ParseTemplate(op.TemplateBody); err == nil { + deps = tmpl.Resources + } + + live := func(id string) (*StackResource, bool) { + res, ok := b.resources[stack.StackID][id] + + return res, ok + } + + return b.deleteWalkOver(stack, deps, live, func(id string, _ *StackResource) { + delete(b.resources[stack.StackID], id) + }, rules) +} + +// deleteWalkOver is deleteWalk for any source of records; drop runs for each +// record that is gone from the stack afterwards. +func (b *InMemoryBackend) deleteWalkOver( + stack *Stack, + deps map[string]TemplateResource, + lookup func(id string) (*StackResource, bool), + drop func(id string, res *StackResource), + rules deleteRules, +) reverseWalk { + physIDs := b.deleteResolveContext(stack) + + return reverseWalk{ + deps: deps, + target: func(id string) (string, string, bool) { + res, ok := lookup(id) + if !ok { + return "", "", false + } + + return res.Type, res.PhysicalID, true + }, + progress: func(string) string { return statusDeleteInProgress }, + apply: func(ctx context.Context, id string) (string, string) { + res, _ := lookup(id) + status, reason := b.deleteOneResource(ctx, res, physIDs, id, rules) + + if !isFailedResourceStatus(status) || rules.forceDrop { + drop(id, res) + } else { + res.Status = status + } + + return status, reason + }, + } +} + +// deleteOneResource reports the event status for removing res: the retain +// status for kept resources, the failure status when the backend cannot delete it. +func (b *InMemoryBackend) deleteOneResource( + ctx context.Context, res *StackResource, physIDs map[string]string, id string, rules deleteRules, +) (string, string) { + policy := res.DeletionPolicy + + switch { + case slices.Contains(rules.callerRetain, id): + return statusDeleteSkipped, "" + case policy == deletionPolicyRetain && !rules.ignorePolicy: + return rules.retainStatus, "" + case policy == deletionPolicySnapshot && !rules.ignorePolicy: + return statusDeleteComplete, "" + } + + if err := b.creator.Delete(ctx, res.Type, res.PhysicalID, res.Properties, physIDs); err != nil { + return rules.failStatus, err.Error() + } + + return statusDeleteComplete, "" +} diff --git a/services/cloudformation/stack_delete.go b/services/cloudformation/stack_delete.go index 1d798edf64..7b588580c9 100644 --- a/services/cloudformation/stack_delete.go +++ b/services/cloudformation/stack_delete.go @@ -4,7 +4,6 @@ import ( "context" "errors" "fmt" - "slices" "strings" "time" ) @@ -13,8 +12,9 @@ import ( var ErrInvalidDeleteRequest = errors.New("invalid DeleteStack request") type deleteSettings struct { - retain []string - force bool + retain []string + force bool + settleLater bool } // DeleteStackOption customises DeleteStack. @@ -69,24 +69,26 @@ func (b *InMemoryBackend) deleteStackWithLocked( } delete(b.pendingOps, stack.StackID) + delete(b.failedRollbacks, stack.StackID) stack.StackStatus = statusDeleteInProgress stack.StackStatusReason = "" - b.addEvent( - stack.StackID, stack.StackName, stack.StackName, stack.StackID, - cfnStackType, statusDeleteInProgress, reasonUserInitiated, - ) + b.addStackEvent(stack, statusDeleteInProgress, reasonUserInitiated) + + op := &pendingStackOp{ + Kind: pendingDelete, RetainResources: s.retain, ForceDelete: s.force, SettleLater: s.settleLater, + Remaining: sortedKeys(b.resources[stack.StackID]), TemplateBody: stack.TemplateBody, + } if top && b.provisionSchedule != nil { - op := &pendingStackOp{Kind: pendingDelete, RetainResources: s.retain, ForceDelete: s.force} - op.Announced = b.announceDeleteLocked(stack) + b.announceReverseWave(stack, op, b.stackDeleteWalk(stack, op)) if b.scheduleLocked(ctx, stack.StackID, op) { return nil } } - b.runDeleteLocked(ctx, stack, s) + b.runDeleteLocked(ctx, stack, op) return nil } @@ -135,61 +137,37 @@ func (b *InMemoryBackend) missingResources(stack *Stack, ids []string) []string return missing } -// announceDeleteLocked emits DELETE_IN_PROGRESS for the resources deleted first. -func (b *InMemoryBackend) announceDeleteLocked(stack *Stack) []string { - tmpl, err := ParseTemplate(stack.TemplateBody) - if err != nil { - return nil - } - - live := sortedKeys(b.resources[stack.StackID]) - - return b.announceLocked(stack, statusDeleteInProgress, firstWave(tmpl.Resources, live, true), tmpl.Resources) +func (b *InMemoryBackend) stackDeleteWalk(stack *Stack, op *pendingStackOp) reverseWalk { + return b.deleteWalk(stack, op, deleteRules{ + retainStatus: statusDeleteSkipped, failStatus: statusDeleteFailed, + callerRetain: op.RetainResources, forceDrop: op.ForceDelete, + }) } // runDeleteLocked deletes the stack's resources in reverse dependency order, // then either settles the stack or leaves it DELETE_FAILED for a retry. -func (b *InMemoryBackend) runDeleteLocked(ctx context.Context, stack *Stack, s deleteSettings) { - live := sortedKeys(b.resources[stack.StackID]) - physIDs := b.deleteResolveContext(stack) - - var failed []string - - for _, logicalID := range reverseDependencyOrder(live, stack.TemplateBody) { - res := b.resources[stack.StackID][logicalID] - b.addProgressEvent( - stack.StackID, stack.StackName, logicalID, res.PhysicalID, res.Type, statusDeleteInProgress, - ) - - status, reason := b.deleteOneResource(ctx, res, physIDs, slices.Contains(s.retain, logicalID)) - b.addEvent(stack.StackID, stack.StackName, logicalID, res.PhysicalID, res.Type, status, reason) - - if status == statusDeleteFailed { - failed = append(failed, fmt.Sprintf("%s: %s", logicalID, reason)) - - if !s.force { - continue - } - } - - delete(b.resources[stack.StackID], logicalID) +func (b *InMemoryBackend) runDeleteLocked(ctx context.Context, stack *Stack, op *pendingStackOp) { + if b.walkReverseLocked(ctx, stack, op, b.stackDeleteWalk(stack, op)) { + return } // AWS never rolls DELETE_FAILED back to DELETE_COMPLETE: the stack, its // remaining resources, and its events all stay describable so the caller // can retry DeleteStack after fixing the underlying resource. - if len(failed) > 0 && !s.force { + if len(op.FailedReasons) > 0 && !op.ForceDelete { stack.StackStatus = statusDeleteFailed - stack.StackStatusReason = strings.Join(failed, "; ") - b.addEvent( - stack.StackID, stack.StackName, stack.StackName, stack.StackID, - cfnStackType, statusDeleteFailed, stack.StackStatusReason, - ) + stack.StackStatusReason = failedSummary(op.FailedReasons) + b.addStackEvent(stack, statusDeleteFailed, stack.StackStatusReason) return } - if b.stepAsync && (stack.ParentID != "" || b.childrenInProgressLocked(stack)) { + if op.SettleLater || b.stepAsync && (stack.ParentID != "" || b.childrenInProgressLocked(stack)) { + stepAsync := b.stepAsync + b.stepAsync = true + + defer func() { b.stepAsync = stepAsync }() + b.stageLocked(ctx, stack.StackID, &pendingStackOp{Kind: pendingDeleteFinalize}, func() { b.finishDeleteLocked(stack) }) @@ -200,26 +178,6 @@ func (b *InMemoryBackend) runDeleteLocked(ctx context.Context, stack *Stack, s d b.finishDeleteLocked(stack) } -// deleteOneResource reports the resource event status for removing res from -// a stack: DELETE_SKIPPED for retained resources, DELETE_FAILED when the -// backend cannot delete it. -func (b *InMemoryBackend) deleteOneResource( - ctx context.Context, res *StackResource, physIDs map[string]string, retainByCaller bool, -) (string, string) { - switch { - case retainByCaller || res.DeletionPolicy == deletionPolicyRetain: - return statusDeleteSkipped, "" - case res.DeletionPolicy == deletionPolicySnapshot: - return statusDeleteComplete, "" - } - - if err := b.creator.Delete(ctx, res.Type, res.PhysicalID, res.Properties, physIDs); err != nil { - return statusDeleteFailed, err.Error() - } - - return statusDeleteComplete, "" -} - // finalizeDeleteLocked waits for nested stacks to settle, then completes the delete. func (b *InMemoryBackend) finalizeDeleteLocked(ctx context.Context, stack *Stack, op *pendingStackOp) { if b.childrenInProgressLocked(stack) { @@ -245,6 +203,7 @@ func (b *InMemoryBackend) finishDeleteLocked(stack *Stack) { b.removeExports(stack.StackID) delete(b.stackPolicies, stack.StackID) delete(b.resources, stack.StackID) + delete(b.failedRollbacks, stack.StackID) delete(b.changeSets, stack.StackName) b.pruneDriftDetections(stack.StackID) b.evictDeletedStacks() diff --git a/services/cloudformation/stack_lifecycle.go b/services/cloudformation/stack_lifecycle.go index c7d114d277..e86a5c24ad 100644 --- a/services/cloudformation/stack_lifecycle.go +++ b/services/cloudformation/stack_lifecycle.go @@ -106,38 +106,10 @@ func (b *InMemoryBackend) ListAll() []*Stack { return out } -// ContinueUpdateRollback continues the rollback for a stack that is in ROLLBACK_IN_PROGRESS -// or UPDATE_ROLLBACK_IN_PROGRESS state. -func (b *InMemoryBackend) ContinueUpdateRollback(_ context.Context, nameOrID string) error { - b.mu.Lock("ContinueUpdateRollback") - defer b.mu.Unlock() - - stack, ok := b.resolveStack(nameOrID) - if !ok { - return ErrStackNotFound - } - - if stack.StackStatus == statusRollbackInProgress || stack.StackStatus == statusUpdateRollbackInProgress { - delete(b.pendingOps, stack.StackID) - } - - switch stack.StackStatus { - case statusRollbackInProgress: - stack.StackStatus = statusRollbackComplete - b.addEvent(stack.StackID, stack.StackName, stack.StackName, stack.StackID, - cfnStackType, statusRollbackComplete, "") - case statusUpdateRollbackInProgress: - stack.StackStatus = statusUpdateRollbackComplete - b.addEvent(stack.StackID, stack.StackName, stack.StackName, stack.StackID, - cfnStackType, statusUpdateRollbackComplete, "") - } - - return nil -} - // CancelUpdateStack cancels an in-progress stack update, rolling it back to // UPDATE_ROLLBACK_COMPLETE. Real AWS: "You can cancel only stacks that are -// in the UPDATE_IN_PROGRESS state". +// in the UPDATE_IN_PROGRESS state". It takes effect between resources: the +// ones already applied are rolled back, the announced wave is cancelled. func (b *InMemoryBackend) CancelUpdateStack(ctx context.Context, nameOrID string) error { b.mu.Lock("CancelUpdateStack") defer b.mu.Unlock() @@ -151,18 +123,19 @@ func (b *InMemoryBackend) CancelUpdateStack(ctx context.Context, nameOrID string return ErrCancelUpdateStackInvalidState } - if op := b.pendingOps[stack.StackID]; op != nil && op.Kind == pendingUpdate { + var op *pendingStackOp + + if pending := b.pendingOps[stack.StackID]; pending != nil && pending.Kind == pendingUpdate { delete(b.pendingOps, stack.StackID) - stack.TemplateBody = op.OldTemplateBody - stack.Parameters = op.OldParams + op = pending } b.stepAsync = true defer func() { b.stepAsync = false }() - b.beginUpdateRollbackLocked(ctx, stack, nil, nil, reasonUserInitiated, false) + b.beginUpdateRollbackLocked(ctx, stack, op, reasonUserInitiated) return nil } @@ -200,15 +173,19 @@ func (b *InMemoryBackend) RollbackStack( stack.RoleARN = roleARN } - arn, name := stack.StackID, stack.StackName - b.addEvent(arn, name, name, arn, cfnStackType, statusRollbackInProgress, reasonUserInitiated) + b.addStackEvent(stack, statusRollbackInProgress, reasonUserInitiated) stack.StackStatus = statusRollbackInProgress created := b.creationOrderLocked(stack) - op := &pendingStackOp{Kind: pendingRollbackCreate, Created: created, RetainExceptOnCreate: retainExceptOnCreate} + op := &pendingStackOp{ + Kind: pendingRollbackCreate, Created: created, Remaining: slices.Clone(created), + RetainExceptOnCreate: retainExceptOnCreate, TemplateBody: stack.TemplateBody, + } + + b.announceReverseWave(stack, op, b.deleteWalk(stack, op, createRollbackRules(op))) if !b.scheduleLocked(ctx, stack.StackID, op) { - b.finishCreateRollbackLocked(ctx, stack, created, createFinish{retainExceptOnCreate: retainExceptOnCreate}) + b.runCreateRollbackLocked(ctx, stack, op) } cp := *stack diff --git a/services/cloudformation/stack_lifecycle_test.go b/services/cloudformation/stack_lifecycle_test.go index 7346408330..35f21d57c1 100644 --- a/services/cloudformation/stack_lifecycle_test.go +++ b/services/cloudformation/stack_lifecycle_test.go @@ -1063,9 +1063,9 @@ func TestContinueUpdateRollback(t *testing.T) { ) require.NoError(t, err) - // Should not error even in non-rollback state (permissive implementation). - err = b.ContinueUpdateRollback(t.Context(), "cur-stack") - require.NoError(t, err) + err = b.ContinueUpdateRollback(t.Context(), "cur-stack", cloudformation.ContinueRollbackInput{}) + require.ErrorIs(t, err, cloudformation.ErrContinueRollback) + assert.ErrorContains(t, err, "is in CREATE_COMPLETE state and can not be continue rolled back") } func TestCancelUpdateStack(t *testing.T) { diff --git a/services/cloudformation/stack_resources.go b/services/cloudformation/stack_resources.go index 73249287ee..4840c4275d 100644 --- a/services/cloudformation/stack_resources.go +++ b/services/cloudformation/stack_resources.go @@ -19,7 +19,7 @@ func (b *InMemoryBackend) DescribeStackResource( return nil, ErrStackNotFound } - res, ok := b.resources[stack.StackID][logicalID] + res, ok := b.liveResourcesLocked(stack)[logicalID] if !ok { return nil, ErrResourceNotFound } @@ -39,7 +39,7 @@ func (b *InMemoryBackend) ListStackResources( return page.Page[StackResourceSummary]{}, ErrStackNotFound } - resMap := b.resources[stack.StackID] + resMap := b.liveResourcesLocked(stack) summaries := make([]StackResourceSummary, 0, len(resMap)) for _, res := range resMap { @@ -69,7 +69,7 @@ func (b *InMemoryBackend) DescribeStackResources(nameOrID string) ([]StackResour return nil, ErrStackNotFound } - resMap := b.resources[stack.StackID] + resMap := b.liveResourcesLocked(stack) resources := make([]StackResource, 0, len(resMap)) for _, res := range resMap { diff --git a/services/cloudformation/stack_transitions_test.go b/services/cloudformation/stack_transitions_test.go index 17240280a3..e8a7f5cee0 100644 --- a/services/cloudformation/stack_transitions_test.go +++ b/services/cloudformation/stack_transitions_test.go @@ -227,6 +227,11 @@ func TestAsyncCreate_PerResourceEvents(t *testing.T) { want := []string{"CREATE_IN_PROGRESS", initiated, "CREATE_COMPLETE"} assert.Equal(t, want, e.events(t, "per-resource", "A")) + assert.Equal(t, []string{"CREATE_IN_PROGRESS"}, e.events(t, "per-resource", "B"), "dependent starts once A is done") + assert.Equal(t, "CREATE_IN_PROGRESS", e.status(t, "per-resource")) + + e.sched.runNext(t) + assert.Equal(t, want, e.events(t, "per-resource", "B")) assert.Less(t, e.order(t, "per-resource", "A", "CREATE_COMPLETE"), e.order(t, "per-resource", "B", "CREATE_IN_PROGRESS")) @@ -273,6 +278,10 @@ func TestAsyncDelete_Sequence(t *testing.T) { require.NoError(t, e.deleteStack(t, "del-seq"), "deleting a stack that is being deleted is a no-op") assert.Len(t, e.sched.queue, 1) + e.sched.runNext(t) + assert.Equal(t, "DELETE_IN_PROGRESS", e.status(t, "del-seq"), "A is deleted in the next wave") + assert.Contains(t, e.statuses(t, "del-seq", "A"), "DELETE_IN_PROGRESS") + e.sched.runNext(t) assert.Equal(t, "DELETE_COMPLETE", e.status(t, id)) @@ -382,19 +391,19 @@ func TestAsyncCreate_Rollback(t *testing.T) { { name: "rollback", input: func(*cfnsdk.CreateStackInput) {}, - wantStatus: []string{"ROLLBACK_IN_PROGRESS", "ROLLBACK_COMPLETE"}, + wantStatus: []string{"CREATE_IN_PROGRESS", "ROLLBACK_IN_PROGRESS", "ROLLBACK_COMPLETE"}, wantStack: []string{"CREATE_IN_PROGRESS", "ROLLBACK_IN_PROGRESS", "ROLLBACK_COMPLETE"}, }, { name: "on_failure_rollback", input: func(in *cfnsdk.CreateStackInput) { in.OnFailure = cfntypes.OnFailureRollback }, - wantStatus: []string{"ROLLBACK_IN_PROGRESS", "ROLLBACK_COMPLETE"}, + wantStatus: []string{"CREATE_IN_PROGRESS", "ROLLBACK_IN_PROGRESS", "ROLLBACK_COMPLETE"}, wantStack: []string{"CREATE_IN_PROGRESS", "ROLLBACK_IN_PROGRESS", "ROLLBACK_COMPLETE"}, }, { name: "disable_rollback", input: func(in *cfnsdk.CreateStackInput) { in.DisableRollback = aws.Bool(true) }, - wantStatus: []string{"CREATE_FAILED"}, + wantStatus: []string{"CREATE_IN_PROGRESS", "CREATE_FAILED"}, wantStack: []string{"CREATE_IN_PROGRESS"}, wantRes: []string{"A"}, wantDRB: true, @@ -402,7 +411,7 @@ func TestAsyncCreate_Rollback(t *testing.T) { { name: "on_failure_do_nothing", input: func(in *cfnsdk.CreateStackInput) { in.OnFailure = cfntypes.OnFailureDoNothing }, - wantStatus: []string{"CREATE_FAILED"}, + wantStatus: []string{"CREATE_IN_PROGRESS", "CREATE_FAILED"}, wantStack: []string{"CREATE_IN_PROGRESS"}, wantRes: []string{"A"}, wantDRB: true, @@ -410,7 +419,7 @@ func TestAsyncCreate_Rollback(t *testing.T) { { name: "on_failure_delete", input: func(in *cfnsdk.CreateStackInput) { in.OnFailure = cfntypes.OnFailureDelete }, - wantStatus: []string{"ROLLBACK_IN_PROGRESS", "DELETE_IN_PROGRESS", "DELETE_COMPLETE"}, + wantStatus: []string{"CREATE_IN_PROGRESS", "ROLLBACK_IN_PROGRESS", "DELETE_IN_PROGRESS", "DELETE_COMPLETE"}, wantStack: []string{ "CREATE_IN_PROGRESS", "ROLLBACK_IN_PROGRESS", "ROLLBACK_COMPLETE", "DELETE_IN_PROGRESS", "DELETE_COMPLETE", @@ -439,7 +448,7 @@ func TestAsyncCreate_Rollback(t *testing.T) { e.sched.runNext(t) assert.Equal(t, want, e.status(t, id), "after step %d", i+1) - if i == 0 && want == "ROLLBACK_IN_PROGRESS" { + if want == "ROLLBACK_IN_PROGRESS" { assert.Equal(t, []string{"A"}, e.resourceIDs(t, id), "rollback has not deleted anything yet") assert.Contains(t, e.events(t, id, "B")[len(e.events(t, id, "B"))-1], "CREATE_FAILED|") } @@ -537,6 +546,7 @@ func TestAsyncCreate_RollbackFailed(t *testing.T) { id := aws.ToString(out.StackId) + e.sched.runNext(t) e.sched.runNext(t) assert.Equal(t, "ROLLBACK_IN_PROGRESS", e.status(t, id)) @@ -621,6 +631,7 @@ func TestAsyncUpdate_Rollback(t *testing.T) { tc.trigger(t, e) if tc.name == "failed_update" { + e.sched.runNext(t) e.sched.runNext(t) assert.Equal(t, tc.wantStatus[0], e.status(t, "upd-rb")) assert.Contains(t, e.resourceIDs(t, "upd-rb"), "C", "rollback has not deleted the new topic yet") @@ -746,6 +757,7 @@ func TestAsyncExecuteChangeSet_Sequence(t *testing.T) { }) require.NoError(t, err) + e.sched.runNext(t) e.sched.runNext(t) assert.Equal(t, cfntypes.ExecutionStatusExecuteInProgress, executionStatus(t, e, "cs-fail", "boom"), "still rolling back") diff --git a/services/cloudformation/stack_update_rollback.go b/services/cloudformation/stack_update_rollback.go new file mode 100644 index 0000000000..cb9396ff10 --- /dev/null +++ b/services/cloudformation/stack_update_rollback.go @@ -0,0 +1,378 @@ +package cloudformation + +import ( + "context" + "errors" + "slices" + "strings" +) + +// ErrContinueRollback is returned for ContinueUpdateRollback requests the stack's state does not allow. +var ErrContinueRollback = errors.New("invalid ContinueUpdateRollback request") + +// ContinueRollbackInput carries the optional members of ContinueUpdateRollback. +type ContinueRollbackInput struct { + ClientRequestToken string + RoleARN string + ResourcesToSkip []string + ForceRollback bool +} + +// updateFailAndRollback records UPDATE_FAILED then enters UPDATE_ROLLBACK_IN_PROGRESS +// for pre-flight update failures (no resources changed). +func (b *InMemoryBackend) updateFailAndRollback(ctx context.Context, stack *Stack, op *pendingStackOp, reason string) { + stack.StackStatusReason = reason + b.addStackEvent(stack, statusUpdateFailed, reason) + b.beginUpdateRollbackLocked(ctx, stack, op, reason) +} + +// cancelInFlightLocked fails the resources an update announced but did not get to. +func (b *InMemoryBackend) cancelInFlightLocked(stack *Stack, op *pendingStackOp) { + if len(op.InFlight) == 0 { + return + } + + types := b.inFlightTypes(stack) + + for _, id := range sortedKeys(op.InFlight) { + phys := "" + if res, ok := b.resources[stack.StackID][id]; ok { + phys = res.PhysicalID + } + + status, reason := statusUpdateFailed, reasonUpdateCancelled + if op.InFlight[id] == statusCreateInProgress { + status, reason = statusCreateFailed, reasonCreateCancelled + } + + b.addResourceEvent(stack, id, phys, types[id].Type, status, reason) + } + + op.InFlight = nil +} + +// beginUpdateRollbackLocked starts UPDATE_ROLLBACK_IN_PROGRESS for an update that +// applied the resources recorded on op (nil when none was touched). +func (b *InMemoryBackend) beginUpdateRollbackLocked( + ctx context.Context, stack *Stack, op *pendingStackOp, reason string, +) { + rb := &pendingStackOp{Kind: pendingRollbackUpdate, TemplateBody: stack.TemplateBody} + + if op != nil { + b.cancelInFlightLocked(stack, op) + + rb.PrevResources = op.PrevResources + rb.Created = op.Created + rb.Updated = op.Updated + rb.OldTemplateBody = op.OldTemplateBody + rb.OldParams = op.OldParams + rb.RetainExceptOnCreate = op.RetainExceptOnCreate + + for _, id := range slices.Concat(op.Created, op.Updated) { + rb.Remaining = appendUnique(rb.Remaining, id) + } + + b.restorePreviousTemplate(stack, op) + } + + stack.StackStatus = statusUpdateRollbackInProgress + b.addStackEvent(stack, statusUpdateRollbackInProgress, reason) + + b.startUpdateRollbackLocked(ctx, stack, rb) +} + +func (b *InMemoryBackend) restorePreviousTemplate(stack *Stack, op *pendingStackOp) { + if op.OldTemplateBody == "" { + return + } + + stack.TemplateBody = op.OldTemplateBody + stack.Parameters = op.OldParams + + if tmpl, err := ParseTemplate(op.OldTemplateBody); err == nil { + stack.Description = tmpl.Description + } +} + +// startUpdateRollbackLocked announces the first rollback wave and runs the rollback, +// in the following steps when async. +func (b *InMemoryBackend) startUpdateRollbackLocked(ctx context.Context, stack *Stack, op *pendingStackOp) { + b.announceReverseWave(stack, op, b.updateRollbackWalk(stack, op)) + b.stageLocked(ctx, stack.StackID, op, func() { b.runUpdateRollbackLocked(ctx, stack, op) }) +} + +// updateRollbackWalk undoes the update: new resources are deleted, modified ones +// restored; a resource that cannot be rolled back ends UPDATE_FAILED. +func (b *InMemoryBackend) updateRollbackWalk(stack *Stack, op *pendingStackOp) reverseWalk { + var deps map[string]TemplateResource + + if tmpl, err := ParseTemplate(op.TemplateBody); err == nil { + deps = tmpl.Resources + } + + uc := newUpdateContext(op.OldTemplateBody, op.OldParams, oldPhysicalIDs(op.PrevResources, stack.ResourceAttrs)) + physIDs := b.deleteResolveContext(stack) + rules := deleteRules{ + retainStatus: statusDeleteComplete, failStatus: statusUpdateFailed, ignorePolicy: op.RetainExceptOnCreate, + } + + return reverseWalk{ + deps: deps, + target: func(id string) (string, string, bool) { + res, ok := b.resources[stack.StackID][id] + if !ok { + return "", "", false + } + + return res.Type, res.PhysicalID, true + }, + progress: func(id string) string { + if slices.Contains(op.Created, id) { + return statusDeleteInProgress + } + + return statusUpdateInProgress + }, + apply: func(ctx context.Context, id string) (string, string) { + cur := b.resources[stack.StackID][id] + prev := op.PrevResources[id] + + status, reason := b.rollbackOne(ctx, cur, prev, id, op, uc, physIDs, rules) + if isFailedResourceStatus(status) { + cur.Status = statusUpdateFailed + + return statusUpdateFailed, reason + } + + if prev != nil { + restored := *prev + b.resources[stack.StackID][id] = &restored + } else { + delete(b.resources[stack.StackID], id) + } + + return status, "" + }, + } +} + +func (b *InMemoryBackend) rollbackOne( + ctx context.Context, cur, prev *StackResource, id string, op *pendingStackOp, uc *updateContext, + physIDs map[string]string, rules deleteRules, +) (string, string) { + if slices.Contains(op.Created, id) { + return b.deleteOneResource(ctx, cur, physIDs, id, rules) + } + + var err error + + if isCFNExtensibilityType(prev.Type) { + err = b.creator.Update(ctx, id, prev.Type, prev.PhysicalID, prev.Properties, cur.Properties) + } else { + _, err = b.creator.UpdateInPlace(ctx, prev.Type, prev.PhysicalID, prev.Properties, uc.oldParams, uc.oldPhys) + } + + if err != nil { + return statusUpdateFailed, err.Error() + } + + return statusUpdateComplete, "" +} + +// runUpdateRollbackLocked ends in UPDATE_ROLLBACK_FAILED when a resource cannot be +// rolled back (kept for ContinueUpdateRollback), otherwise in +// UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS. +func (b *InMemoryBackend) runUpdateRollbackLocked(ctx context.Context, stack *Stack, op *pendingStackOp) { + if b.walkReverseLocked(ctx, stack, op, b.updateRollbackWalk(stack, op)) { + return + } + + if len(op.FailedReasons) > 0 { + reason := reasonRollbackDeleteFailed + stack.StackStatus = statusUpdateRollbackFailed + stack.StackStatusReason = reason + op.Remaining = sortedKeys(op.FailedReasons) + b.failedRollbacks[stack.StackID] = op + b.addStackEvent(stack, statusUpdateRollbackFailed, reason) + + return + } + + delete(b.failedRollbacks, stack.StackID) + + stack.StackStatus = statusUpdateRollbackCleanup + b.addStackEvent(stack, statusUpdateRollbackCleanup, "") + + b.stageLocked(ctx, stack.StackID, &pendingStackOp{Kind: pendingRollbackUpdateCleanup}, func() { + b.completeUpdateRollbackLocked(stack) + }) +} + +func (b *InMemoryBackend) completeUpdateRollbackLocked(stack *Stack) { + stack.StackStatus = statusUpdateRollbackComplete + b.addStackEvent(stack, statusUpdateRollbackComplete, "") +} + +// ContinueUpdateRollback retries the rollback of a stack in UPDATE_ROLLBACK_FAILED, +// skipping the resources the caller names (or all failed ones with ForceRollback). +func (b *InMemoryBackend) ContinueUpdateRollback(ctx context.Context, nameOrID string, in ContinueRollbackInput) error { + if err := ValidateRoleARN(in.RoleARN); err != nil { + return err + } + + if in.ForceRollback && len(in.ResourcesToSkip) > 0 { + return awsErrorf(ErrContinueRollback, "ForceRollback and ResourcesToSkip are mutually exclusive.") + } + + b.mu.Lock("ContinueUpdateRollback") + defer b.mu.Unlock() + + stack, ok := b.resolveStack(nameOrID) + if !ok { + return ErrStackNotFound + } + + return b.continueRollbackLocked(ctx, stack, in) +} + +func (b *InMemoryBackend) continueRollbackLocked(ctx context.Context, stack *Stack, in ContinueRollbackInput) error { + if stack.StackStatus != statusUpdateRollbackFailed { + return awsErrorf( + ErrContinueRollback, "Stack:%s is in %s state and can not be continue rolled back.", + stack.StackID, stack.StackStatus, + ) + } + + op := b.failedRollbackOp(stack) + + skip, err := b.resolveSkips(ctx, stack, op, in) + if err != nil { + return err + } + + if in.RoleARN != "" { + stack.RoleARN = in.RoleARN + } + + for _, id := range skip { + cur := b.resources[stack.StackID][id] + cur.Status = statusUpdateComplete + b.addResourceEvent(stack, id, cur.PhysicalID, cur.Type, statusUpdateComplete, reasonUpdateSkipped) + op.Remaining = without(op.Remaining, id) + } + + delete(b.failedRollbacks, stack.StackID) + + op.FailedReasons = nil + stack.StackStatus = statusUpdateRollbackInProgress + stack.StackStatusReason = "" + b.addStackEvent(stack, statusUpdateRollbackInProgress, reasonUserInitiated) + + stepAsync := b.stepAsync + b.stepAsync = true + + defer func() { b.stepAsync = stepAsync }() + + b.startUpdateRollbackLocked(ctx, stack, op) + + return nil +} + +// failedRollbackOp returns the saved rollback of the stack, or rebuilds the +// remaining work from the resources left in UPDATE_FAILED. +func (b *InMemoryBackend) failedRollbackOp(stack *Stack) *pendingStackOp { + if op := b.failedRollbacks[stack.StackID]; op != nil { + return op + } + + op := &pendingStackOp{Kind: pendingRollbackUpdate, TemplateBody: stack.TemplateBody} + + for _, id := range sortedKeys(b.resources[stack.StackID]) { + if b.resources[stack.StackID][id].Status == statusUpdateFailed { + op.Remaining = append(op.Remaining, id) + } + } + + return op +} + +// resolveSkips validates ResourcesToSkip against the resources that failed to roll back. +func (b *InMemoryBackend) resolveSkips( + ctx context.Context, stack *Stack, op *pendingStackOp, in ContinueRollbackInput, +) ([]string, error) { + if in.ForceRollback { + return slices.Clone(op.Remaining), nil + } + + var skip, invalid []string + + for _, id := range in.ResourcesToSkip { + switch { + case slices.Contains(op.Remaining, id): + if b.embeddedStackBlocksSkip(stack, id) { + invalid = append(invalid, id) + + continue + } + + skip = appendUnique(skip, id) + case strings.Contains(id, "."): + if err := b.skipInNestedStack(ctx, stack, id, in); err != nil { + return nil, err + } + default: + invalid = append(invalid, id) + } + } + + if len(invalid) > 0 { + return nil, awsErrorf( + ErrContinueRollback, + "Resources [%s] cannot be skipped: only resources in UPDATE_FAILED because a rollback failed can be skipped.", + strings.Join(invalid, ", "), + ) + } + + return skip, nil +} + +// embeddedStackBlocksSkip reports whether id is a nested-stack resource whose +// embedded stack is not yet DELETE_IN_PROGRESS, DELETE_COMPLETE or DELETE_FAILED. +func (b *InMemoryBackend) embeddedStackBlocksSkip(stack *Stack, id string) bool { + res := b.resources[stack.StackID][id] + if res == nil || res.Type != cfnStackType { + return false + } + + child, ok := b.resolveStack(res.PhysicalID) + if !ok { + return false + } + + switch child.StackStatus { + case statusDeleteInProgress, statusDeleteComplete, statusDeleteFailed: + return false + } + + return true +} + +// skipInNestedStack continues the rollback of the embedded stack named by the +// NestedStackName.ResourceLogicalID form of a skip entry. +func (b *InMemoryBackend) skipInNestedStack( + ctx context.Context, stack *Stack, entry string, in ContinueRollbackInput, +) error { + name, logicalID, _ := strings.Cut(entry, ".") + + child, ok := b.resolveStack(name) + if !ok || child.ParentID != stack.StackID { + return awsErrorf( + ErrContinueRollback, "Stack %s is not a nested stack of %s, so %s cannot be skipped.", + name, stack.StackName, entry, + ) + } + + return b.continueRollbackLocked(ctx, child, ContinueRollbackInput{ + ResourcesToSkip: []string{logicalID}, RoleARN: in.RoleARN, + }) +} diff --git a/services/cloudformation/stack_update_walk.go b/services/cloudformation/stack_update_walk.go new file mode 100644 index 0000000000..247e99491c --- /dev/null +++ b/services/cloudformation/stack_update_walk.go @@ -0,0 +1,524 @@ +package cloudformation + +import ( + "context" + "fmt" + "maps" + "slices" + "time" +) + +type updateAction int + +const ( + actNoop updateAction = iota + actCreate + actInPlace + actReplace + actExtensibility +) + +// updatePass carries the resolved inputs of an update walk. +type updatePass struct { + uc *updateContext + params map[string]string + phys map[string]string +} + +func (b *InMemoryBackend) newUpdateOp( + opts StackOptions, oldTemplateBody string, oldParams []Parameter, +) *pendingStackOp { + return &pendingStackOp{ + Kind: pendingUpdate, + DisableValidation: opts.DisableValidation, + ResourceTypes: opts.ResourceTypes, + RetainExceptOnCreate: opts.RetainExceptOnCreate, + OldTemplateBody: oldTemplateBody, + OldParams: oldParams, + } +} + +func oldPhysicalIDs(prev map[string]*StackResource, attrs map[string]string) map[string]string { + out := stackPhysicalIDsSnapshot(prev) + maps.Copy(out, attrs) + + return out +} + +func (b *InMemoryBackend) updateSideKeys(stack *Stack, tmpl *Template, phys map[string]string) { + phys[physIDAccountIDKey] = b.accountID + phys[physIDRegionKey] = b.region + phys[physIDStackNameKey] = stack.StackName + + for logicalID, res := range tmpl.Resources { + phys[physIDResourceTypeKey(logicalID)] = res.Type + } +} + +// announceUpdateLocked emits the first wave of in-progress events when UpdateStack returns. +func (b *InMemoryBackend) announceUpdateLocked(ctx context.Context, stack *Stack, op *pendingStackOp) { + rt, err := b.templateRuntime(ctx, stack) + if err != nil { + return + } + + phys := make(map[string]string, len(b.resources[stack.StackID])) + for id, res := range b.resources[stack.StackID] { + phys[id] = res.PhysicalID + } + + maps.Copy(phys, stack.ResourceAttrs) + rt.uc = newUpdateContext(op.OldTemplateBody, op.OldParams, phys) + + pass := &updatePass{uc: rt.uc, params: rt.params, phys: phys} + _, _ = b.announceUpdateWave(stack, op, rt, pass) +} + +// runUpdateStepLocked starts or resumes the apply phase of an update. +func (b *InMemoryBackend) runUpdateStepLocked(ctx context.Context, stack *Stack, op *pendingStackOp) { + if stack.TemplateBody == "" { + b.completeUpdateLocked(stack) + + return + } + + if op.PhysicalIDs == nil && !b.beginUpdateWalkLocked(ctx, stack, op) { + return + } + + b.walkUpdateLocked(ctx, stack, op) +} + +// beginUpdateWalkLocked validates the new template and snapshots the pre-update state; +// false means the update already failed. +func (b *InMemoryBackend) beginUpdateWalkLocked(ctx context.Context, stack *Stack, op *pendingStackOp) bool { + tmpl, params := b.parseAndValidateUpdateTemplate(ctx, stack, op) + if tmpl == nil { + return false + } + + phys := make(map[string]string, len(b.resources[stack.StackID])) + for logicalID, res := range b.resources[stack.StackID] { + phys[logicalID] = res.PhysicalID + } + + maps.Copy(phys, stack.ResourceAttrs) + + uc := newUpdateContext(op.OldTemplateBody, op.OldParams, phys) + uc.retainExceptOnCreate = op.RetainExceptOnCreate + + b.updateSideKeys(stack, tmpl, phys) + + if expErr := b.validateExportsStillInUse(stack, tmpl, params, phys); expErr != nil { + b.updateFailAndRollback(ctx, stack, op, expErr.Error()) + + return false + } + + if _, ordErr := topoSortResources(tmpl.Resources); ordErr != nil { + b.updateFailAndRollback(ctx, stack, op, ordErr.Error()) + + return false + } + + op.PrevResources = make(map[string]*StackResource, len(b.resources[stack.StackID])) + for k, v := range b.resources[stack.StackID] { + cp := *v + op.PrevResources[k] = &cp + } + + op.PhysicalIDs = phys + op.rt = &walkRuntime{tmpl: tmpl, uc: uc, params: params} + + return true +} + +// updateRuntimeLocked rebuilds a resumed update walk's runtime from the persisted op. +func (b *InMemoryBackend) updateRuntimeLocked(ctx context.Context, stack *Stack, op *pendingStackOp) bool { + rt, err := b.templateRuntime(ctx, stack) + if err != nil { + b.updateFailAndRollback(ctx, stack, op, err.Error()) + + return false + } + + rt.uc = newUpdateContext(op.OldTemplateBody, op.OldParams, oldPhysicalIDs(op.PrevResources, stack.ResourceAttrs)) + rt.uc.retainExceptOnCreate = op.RetainExceptOnCreate + op.rt = rt + + return true +} + +// walkUpdateLocked applies the new template one dependency wave at a time and +// then moves to the cleanup phase. +func (b *InMemoryBackend) walkUpdateLocked(ctx context.Context, stack *Stack, op *pendingStackOp) { + if op.rt == nil && !b.updateRuntimeLocked(ctx, stack, op) { + return + } + + ctx = parentStackIDKey.Set(ctx, stack.StackID) + pass := &updatePass{uc: op.rt.uc, params: op.rt.params, phys: op.PhysicalIDs} + + for { + if len(op.InFlight) > 0 { + if reason := b.executeUpdateWave(ctx, stack, op, pass); reason != "" { + stack.StackStatusReason = reason + b.beginUpdateRollbackLocked(ctx, stack, op, reason) + + return + } + } + + wave, err := b.announceUpdateWave(stack, op, op.rt, pass) + if err != nil { + stack.StackStatusReason = err.Error() + b.beginUpdateRollbackLocked(ctx, stack, op, err.Error()) + + return + } + + if len(wave) == 0 { + b.startUpdateCleanupLocked(ctx, stack, op) + + return + } + + if b.stageWalk(ctx, stack, op) { + return + } + } +} + +// classifyUpdate decides what the update does to one template resource; an error is a +// pre-flight failure (the failure event is already recorded). +func (b *InMemoryBackend) classifyUpdate( + stack *Stack, id string, res TemplateResource, pass *updatePass, +) (updateAction, *StackResource, error) { + existing, exists := b.resources[stack.StackID][id] + + switch { + case !exists: + return actCreate, nil, nil + case isCFNExtensibilityType(res.Type): + return actExtensibility, existing, nil + } + + change := b.planResourceUpdate(id, res, existing, pass.uc, pass.params, pass.phys) + if len(change.changed) == 0 { + existing.DeletionPolicy = res.DeletionPolicy + + return actNoop, existing, nil + } + + if !change.replace { + return actInPlace, existing, nil + } + + if name, same := customNameUnchanged(res, existing, pass.uc, pass.params, pass.phys); same { + err := fmt.Errorf("%w. Rename %s and update the stack again", ErrCustomNamedReplacement, name) + b.addResourceEvent(stack, id, existing.PhysicalID, res.Type, statusUpdateFailed, err.Error()) + + return actReplace, existing, fmt.Errorf("resource %s update: %w", id, err) + } + + return actReplace, existing, nil +} + +// announceUpdateWave picks the next wave of resources that change and emits their +// in-progress events; resources the update leaves alone are skipped silently. +func (b *InMemoryBackend) announceUpdateWave( + stack *Stack, op *pendingStackOp, rt *walkRuntime, pass *updatePass, +) ([]string, error) { + remaining := without(sortedKeys(rt.tmpl.Resources), op.Done...) + + for len(remaining) > 0 { + candidates := nextWave(rt.tmpl.Resources, remaining, false) + remaining = without(remaining, candidates...) + + var wave []string + + for _, id := range candidates { + res := rt.tmpl.Resources[id] + + act, existing, err := b.classifyUpdate(stack, id, res, pass) + if err != nil { + return nil, err + } + + if act == actNoop { + op.Done = append(op.Done, id) + + continue + } + + b.announceUpdateResource(stack, op, id, res, act, existing) + wave = append(wave, id) + } + + if len(wave) > 0 { + return wave, nil + } + } + + return nil, nil +} + +func (b *InMemoryBackend) announceUpdateResource( + stack *Stack, op *pendingStackOp, id string, res TemplateResource, act updateAction, existing *StackResource, +) { + status, phys, reason := statusUpdateInProgress, "", "" + + if existing != nil { + phys = existing.PhysicalID + } + + switch act { + case actCreate: + status = statusCreateInProgress + case actReplace: + reason = reasonReplacementRequired + case actNoop, actInPlace, actExtensibility: + } + + if op.InFlight == nil { + op.InFlight = make(map[string]string) + } + + op.InFlight[id] = status + b.addResourceEvent(stack, id, phys, res.Type, status, reason) +} + +// executeUpdateWave applies the announced wave and returns the failure reason, if any. +func (b *InMemoryBackend) executeUpdateWave( + ctx context.Context, stack *Stack, op *pendingStackOp, pass *updatePass, +) string { + ids := sortedKeys(op.InFlight) + op.InFlight = nil + reason := "" + + for _, id := range ids { + res, ok := op.rt.tmpl.Resources[id] + if !ok { + continue + } + + act, existing, _ := b.classifyUpdate(stack, id, res, pass) + if err := b.applyUpdateAction(ctx, stack, op, id, res, act, existing, pass); err != nil && reason == "" { + reason = err.Error() + } + + op.Done = append(op.Done, id) + } + + return reason +} + +func (b *InMemoryBackend) applyUpdateAction( + ctx context.Context, stack *Stack, op *pendingStackOp, id string, res TemplateResource, act updateAction, + existing *StackResource, pass *updatePass, +) error { + switch act { + case actCreate: + physicalID, err := b.createUpdateResource(ctx, stack, id, res, pass.params, pass.phys) + if err != nil { + return fmt.Errorf("resource %s: %w", id, err) + } + + pass.phys[id] = physicalID + op.Created = appendUnique(op.Created, id) + case actExtensibility: + if err := b.updateExtensibilityResource(ctx, stack, id, res, existing); err != nil { + return fmt.Errorf("resource %s update: %w", id, err) + } + + op.Updated = appendUnique(op.Updated, id) + case actInPlace: + if err := b.updateInPlaceResource(ctx, stack, id, res, existing, pass); err != nil { + return fmt.Errorf("resource %s update: %w", id, err) + } + + op.Updated = appendUnique(op.Updated, id) + case actReplace: + repl, err := b.replaceResource(ctx, stack, id, res, existing, pass) + if err != nil { + return fmt.Errorf("resource %s update: %w", id, err) + } + + op.Replaced = append(op.Replaced, *repl) + op.Created = appendUnique(op.Created, id) + case actNoop: + } + + return nil +} + +func (b *InMemoryBackend) updateInPlaceResource( + ctx context.Context, stack *Stack, id string, res TemplateResource, existing *StackResource, pass *updatePass, +) error { + _, err := b.creator.UpdateInPlace(ctx, res.Type, existing.PhysicalID, res.Properties, pass.params, pass.phys) + if err != nil { + b.addResourceEvent(stack, id, existing.PhysicalID, res.Type, statusUpdateFailed, err.Error()) + + return err + } + + existing.Properties = res.Properties + existing.DeletionPolicy = res.DeletionPolicy + existing.Status = statusUpdateComplete + existing.Timestamp = time.Now() + b.addResourceEvent(stack, id, existing.PhysicalID, res.Type, statusUpdateComplete, "") + + return nil +} + +// startUpdateCleanupLocked enters UPDATE_COMPLETE_CLEANUP_IN_PROGRESS, where replaced +// and removed resources are deleted one dependency wave per step. +func (b *InMemoryBackend) startUpdateCleanupLocked(ctx context.Context, stack *Stack, op *pendingStackOp) { + stack.StackStatus = statusUpdateCleanupProgress + b.addStackEvent(stack, statusUpdateCleanupProgress, "") + + op.Kind = pendingUpdateCleanup + op.Phase = phaseReplaced + op.Done = nil + op.FailedReasons = nil + + for _, r := range slices.Backward(op.Replaced) { + op.Remaining = append(op.Remaining, r.Old.LogicalID) + } + + if b.stageWalk(ctx, stack, op) { + return + } + + b.walkUpdateCleanupLocked(ctx, stack, op) +} + +func (b *InMemoryBackend) walkUpdateCleanupLocked(ctx context.Context, stack *Stack, op *pendingStackOp) { + if op.rt == nil && !b.updateRuntimeLocked(ctx, stack, op) { + return + } + + for { + if b.walkReverseLocked(ctx, stack, op, b.cleanupWalk(stack, op)) { + return + } + + if op.Phase == phaseReplaced { + op.Phase = phaseStale + op.Remaining = b.staleResources(stack, op) + op.FailedReasons = nil + + continue + } + + break + } + + if len(op.FailedReasons) > 0 { + reason := "failed to delete one or more resources removed from the template" + stack.StackStatus = statusUpdateFailed + stack.StackStatusReason = reason + b.addStackEvent(stack, statusUpdateFailed, reason) + + return + } + + b.finalizeUpdateLocked(ctx, stack, op) +} + +func (b *InMemoryBackend) staleResources(stack *Stack, op *pendingStackOp) []string { + var stale []string + + for id := range b.resources[stack.StackID] { + if _, in := op.rt.tmpl.Resources[id]; !in { + stale = append(stale, id) + } + } + + return reverseDependencyOrder(stale, op.OldTemplateBody) +} + +// cleanupWalk deletes the old physical resources of replacements, then resources the new template dropped. +func (b *InMemoryBackend) cleanupWalk(stack *Stack, op *pendingStackOp) reverseWalk { + if op.Phase == phaseReplaced { + olds := make(map[string]*StackResource, len(op.Replaced)) + + for i := range op.Replaced { + r := &op.Replaced[i] + olds[r.Old.LogicalID] = &StackResource{ + LogicalID: r.Old.LogicalID, PhysicalID: r.Old.PhysicalID, Type: r.Old.Type, + Properties: r.Old.Properties, DeletionPolicy: r.Policy, + } + } + + return b.deleteWalkOver(stack, op.rt.tmpl.Resources, func(id string) (*StackResource, bool) { + res, ok := olds[id] + + return res, ok + }, func(string, *StackResource) {}, deleteRules{ + retainStatus: statusDeleteComplete, failStatus: statusDeleteFailed, forceDrop: true, + }) + } + + var deps map[string]TemplateResource + if op.rt.uc != nil && op.rt.uc.oldTmpl != nil { + deps = op.rt.uc.oldTmpl.Resources + } + + return b.deleteWalkOver(stack, deps, func(id string) (*StackResource, bool) { + res, ok := b.resources[stack.StackID][id] + + return res, ok + }, func(id string, _ *StackResource) { delete(b.resources[stack.StackID], id) }, deleteRules{ + retainStatus: statusDeleteComplete, failStatus: statusDeleteFailed, + }) +} + +// finalizeUpdateLocked resolves outputs and exports after the last cleanup wave, then settles. +func (b *InMemoryBackend) finalizeUpdateLocked(ctx context.Context, stack *Stack, op *pendingStackOp) { + tmpl := op.rt.tmpl + + b.removeExports(stack.StackID) + + resourceTypes := make(map[string]string, len(tmpl.Resources)) + for logicalID, res := range tmpl.Resources { + resourceTypes[logicalID] = res.Type + } + + stack.ResourceAttrs = extractAttrStash(op.PhysicalIDs, resourceTypes) + rctx := resolveCtx{ + params: op.rt.params, + physicalIDs: op.PhysicalIDs, + resourceTypes: resourceTypes, + exports: b.buildExportsMap(), + conditions: evaluateConditions(tmpl.Conditions, op.rt.params, op.PhysicalIDs), + mappings: tmpl.Mappings, + accountID: b.accountID, + region: b.region, + stackName: stack.StackName, + } + + var exportMap map[string]string + stack.Outputs, exportMap = resolveOutputsWithContext(tmpl, rctx) + + if regErr := b.registerExports(stack.StackID, exportMap); regErr != nil { + stack.StackStatus = statusUpdateFailed + stack.StackStatusReason = regErr.Error() + b.addStackEvent(stack, statusUpdateFailed, regErr.Error()) + + return + } + + b.settleUpdateLocked(ctx, stack) +} + +// settleUpdateLocked completes the update once nested stacks have settled. +func (b *InMemoryBackend) settleUpdateLocked(ctx context.Context, stack *Stack) { + if b.stepAsync && b.childrenInProgressLocked(stack) { + b.scheduleLocked(ctx, stack.StackID, &pendingStackOp{Kind: pendingUpdateCleanup, Phase: phaseSettle}) + + return + } + + b.completeUpdateLocked(stack) +} diff --git a/services/cloudformation/stack_walk.go b/services/cloudformation/stack_walk.go new file mode 100644 index 0000000000..234f12b662 --- /dev/null +++ b/services/cloudformation/stack_walk.go @@ -0,0 +1,278 @@ +package cloudformation + +import ( + "context" + "maps" + "slices" + "sort" + "strings" + "time" +) + +const ( + phaseReplaced = "replaced" + phaseStale = "stale" + phaseSettle = "settle" + + reasonCreateCancelled = "Resource creation cancelled" + reasonUpdateCancelled = "Resource update cancelled" + reasonUpdateSkipped = "Resource update skipped by ContinueUpdateRollback" +) + +// replacedRecord is the old physical resource of a replaced logical ID, kept until cleanup. +type replacedRecord struct { + Policy string `json:"policy,omitempty"` + Old StackResource `json:"old"` +} + +// walkRuntime caches what a walk re-derives from the stack when it resumes. +type walkRuntime struct { + tmpl *Template + uc *updateContext + params map[string]string +} + +func (b *InMemoryBackend) addStackEvent(stack *Stack, status, reason string) { + b.addEvent(stack.StackID, stack.StackName, stack.StackName, stack.StackID, cfnStackType, status, reason) +} + +func (b *InMemoryBackend) addResourceEvent(stack *Stack, id, phys, typ, status, reason string) { + b.addEvent(stack.StackID, stack.StackName, id, phys, typ, status, reason) +} + +// stageWalk hands op's next step to the scheduler when inside an async step; +// false means the caller keeps walking inline. +func (b *InMemoryBackend) stageWalk(ctx context.Context, stack *Stack, op *pendingStackOp) bool { + return b.stepAsync && b.scheduleLocked(ctx, stack.StackID, op) +} + +// nextWave returns the sorted members of remaining that can progress now: those +// whose in-set dependencies are all done (leaves false) or that no other member +// depends on (leaves true). IDs absent from res depend on nothing. +func nextWave(res map[string]TemplateResource, remaining []string, leaves bool) []string { + all := make(map[string]struct{}, len(res)) + for id := range res { + all[id] = struct{}{} + } + + left := make(map[string]struct{}, len(remaining)) + for _, id := range remaining { + left[id] = struct{}{} + } + + blocked := make(map[string]bool, len(remaining)) + + for _, id := range remaining { + r, ok := res[id] + if !ok { + continue + } + + for _, dep := range resourceDependencies(id, r, all) { + if _, in := left[dep]; !in { + continue + } + + if leaves { + blocked[dep] = true + } else { + blocked[id] = true + } + } + } + + out := make([]string, 0, len(remaining)) + + for _, id := range remaining { + if !blocked[id] { + out = append(out, id) + } + } + + if len(out) == 0 { + out = slices.Clone(remaining) + } + + sort.Strings(out) + + return out +} + +func without(list []string, drop ...string) []string { + out := make([]string, 0, len(list)) + + for _, id := range list { + if !slices.Contains(drop, id) { + out = append(out, id) + } + } + + return out +} + +func appendUnique(list []string, id string) []string { + if slices.Contains(list, id) { + return list + } + + return append(list, id) +} + +// legacyInFlight maps the keys of a snapshot written before in-flight tracking +// ("logical|STATUS") onto the in-flight set. +func (op *pendingStackOp) legacyInFlight() { + if len(op.InFlight) > 0 { + return + } + + for _, key := range op.Announced { + if id, status, ok := strings.Cut(key, "|"); ok { + if op.InFlight == nil { + op.InFlight = make(map[string]string) + } + + op.InFlight[id] = status + } + } + + op.Announced = nil +} + +// reverseWalk describes one backwards phase (deletion, rollback, cleanup): the +// resources of the stack leave one dependency wave per step. +type reverseWalk struct { + deps map[string]TemplateResource + target func(id string) (typ, phys string, ok bool) + progress func(id string) string + apply func(ctx context.Context, id string) (status, reason string) +} + +// walkReverseLocked runs the walk until op.Remaining is empty (false) or the next +// wave is deferred to a later step (true). +func (b *InMemoryBackend) walkReverseLocked( + ctx context.Context, stack *Stack, op *pendingStackOp, w reverseWalk, +) bool { + for { + if len(op.InFlight) > 0 { + b.executeReverseWave(ctx, stack, op, w) + } + + if !b.announceReverseWave(stack, op, w) { + return false + } + + if b.stageWalk(ctx, stack, op) { + return true + } + } +} + +func (b *InMemoryBackend) announceReverseWave(stack *Stack, op *pendingStackOp, w reverseWalk) bool { + for len(op.Remaining) > 0 { + wave := nextWave(w.deps, op.Remaining, true) + op.Remaining = without(op.Remaining, wave...) + + for _, id := range wave { + typ, phys, ok := w.target(id) + if !ok { + continue + } + + status := w.progress(id) + if op.InFlight == nil { + op.InFlight = make(map[string]string, len(wave)) + } + + op.InFlight[id] = status + b.addResourceEvent(stack, id, phys, typ, status, "") + } + + if len(op.InFlight) > 0 { + return true + } + } + + return false +} + +func (b *InMemoryBackend) executeReverseWave( + ctx context.Context, stack *Stack, op *pendingStackOp, w reverseWalk, +) { + ids := sortedKeys(op.InFlight) + op.InFlight = nil + + for _, id := range ids { + typ, phys, ok := w.target(id) + if !ok { + continue + } + + status, reason := w.apply(ctx, id) + b.addResourceEvent(stack, id, phys, typ, status, reason) + + if isFailedResourceStatus(status) { + if op.FailedReasons == nil { + op.FailedReasons = make(map[string]string) + } + + op.FailedReasons[id] = reason + } + } +} + +// failedSummary lists the failures of a walk as "id: reason", ordered by ID. +func failedSummary(reasons map[string]string) string { + parts := make([]string, 0, len(reasons)) + + for _, id := range sortedKeys(reasons) { + parts = append(parts, id+": "+reasons[id]) + } + + return strings.Join(parts, "; ") +} + +// liveResourcesLocked returns the stack's resources with the status of those an +// operation has announced but not yet finished. +func (b *InMemoryBackend) liveResourcesLocked(stack *Stack) map[string]*StackResource { + live := b.resources[stack.StackID] + op := b.pendingOps[stack.StackID] + + if op == nil || len(op.InFlight) == 0 { + return live + } + + out := make(map[string]*StackResource, len(live)+len(op.InFlight)) + maps.Copy(out, live) + + var types map[string]TemplateResource + + for id, status := range op.InFlight { + if res, ok := live[id]; ok { + cp := *res + cp.Status = status + out[id] = &cp + + continue + } + + if types == nil { + types = b.inFlightTypes(stack) + } + + out[id] = &StackResource{ + Timestamp: time.Now(), LogicalID: id, Type: types[id].Type, Status: status, + StackID: stack.StackID, StackName: stack.StackName, + } + } + + return out +} + +func (b *InMemoryBackend) inFlightTypes(stack *Stack) map[string]TemplateResource { + tmpl, err := ParseTemplate(stack.TemplateBody) + if err != nil { + return nil + } + + return tmpl.Resources +} diff --git a/services/cloudformation/stack_walk_test.go b/services/cloudformation/stack_walk_test.go new file mode 100644 index 0000000000..f807ff69a7 --- /dev/null +++ b/services/cloudformation/stack_walk_test.go @@ -0,0 +1,885 @@ +package cloudformation_test + +import ( + "context" + "slices" + "strings" + "testing" + "testing/synctest" + "time" + + "github.com/aws/aws-sdk-go-v2/aws" + cfnsdk "github.com/aws/aws-sdk-go-v2/service/cloudformation" + cfntypes "github.com/aws/aws-sdk-go-v2/service/cloudformation/types" + awss3 "github.com/aws/aws-sdk-go-v2/service/s3" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/blackbirdworks/gopherstack/services/cloudformation" + sqsbackend "github.com/blackbirdworks/gopherstack/services/sqs" +) + +const ( + waveTemplate = `{"Resources":{"A":{"Type":"AWS::SNS::Topic"},` + + `"B":{"Type":"AWS::SQS::Queue","DependsOn":"A"},` + + `"C":{"Type":"AWS::SNS::Topic","DependsOn":"B"},"D":{"Type":"AWS::SNS::Topic"}}}` + middleFailTemplate = `{"Resources":{"A":{"Type":"AWS::SNS::Topic"},` + + `"B":{"Type":"AWS::SNS::Topic","DependsOn":"A"},` + + `"M":{"Type":"AWS::SQS::Queue","DependsOn":"B"},"C":{"Type":"AWS::SNS::Topic","DependsOn":"M"}}}` + replaceV1 = `{"Resources":{"Bucket":{"Type":"AWS::S3::Bucket","Properties":{"BucketName":"walk-old"}},` + + `"T":{"Type":"AWS::SNS::Topic"}}}` + replaceV2 = `{"Resources":{"Bucket":{"Type":"AWS::S3::Bucket","Properties":{"BucketName":"walk-new"}}}}` + retainTpl = `{"Resources":{"A":{"Type":"AWS::SNS::Topic"},` + + `"B":{"Type":"AWS::SQS::Queue","DependsOn":"A","DeletionPolicy":"Retain"}}}` + cancelFrom = `{"Resources":{"A":{"Type":"AWS::SNS::Topic"}}}` + cancelTo = `{"Resources":{"A":{"Type":"AWS::SNS::Topic"},` + + `"B":{"Type":"AWS::SNS::Topic","DependsOn":"A"},"C":{"Type":"AWS::SNS::Topic","DependsOn":"B"}}}` + rollbackFailTpl = `{"Resources":{"A":{"Type":"AWS::SNS::Topic"},` + + `"Bucket":{"Type":"AWS::S3::Bucket","Properties":{"BucketName":"` + bucketName + `"}},` + + `"Q":{"Type":"AWS::SQS::Queue","DependsOn":"Bucket"}}}` +) + +func (e *transitionEnv) resourceStatuses(t *testing.T, stack string) map[string]string { + t.Helper() + + out, err := e.client.DescribeStackResources(t.Context(), &cfnsdk.DescribeStackResourcesInput{ + StackName: aws.String(stack), + }) + require.NoError(t, err) + + got := make(map[string]string, len(out.StackResources)) + for _, r := range out.StackResources { + got[aws.ToString(r.LogicalResourceId)] = string(r.ResourceStatus) + } + + return got +} + +func (e *transitionEnv) drain(t *testing.T) int { + t.Helper() + + steps := 0 + + for len(e.sched.queue) > 0 { + e.sched.runNext(t) + + steps++ + } + + return steps +} + +func (e *transitionEnv) fillBucket(t *testing.T) { + t.Helper() + + _, err := e.backends.S3.Backend.PutObject(t.Context(), &awss3.PutObjectInput{ + Bucket: aws.String(bucketName), Key: aws.String("k"), Body: strings.NewReader("x"), + }) + assert.NoError(t, err) +} + +func (e *transitionEnv) emptyBucket(t *testing.T) { + t.Helper() + + _, err := e.backends.S3.Backend.DeleteObject(t.Context(), &awss3.DeleteObjectInput{ + Bucket: aws.String(bucketName), Key: aws.String("k"), + }) + require.NoError(t, err) +} + +func TestAsyncWalk_CreateWaves(t *testing.T) { + t.Parallel() + + e := newTransitionEnv(t) + e.schedule(t) + + _, err := e.client.CreateStack(t.Context(), &cfnsdk.CreateStackInput{ + StackName: aws.String("waves"), TemplateBody: aws.String(waveTemplate), + }) + require.NoError(t, err) + + steps := []struct { + resources map[string]string + stack string + }{ + { + stack: "CREATE_IN_PROGRESS", + resources: map[string]string{"A": "CREATE_IN_PROGRESS", "D": "CREATE_IN_PROGRESS"}, + }, + { + stack: "CREATE_IN_PROGRESS", + resources: map[string]string{ + "A": "CREATE_COMPLETE", "D": "CREATE_COMPLETE", "B": "CREATE_IN_PROGRESS", + }, + }, + { + stack: "CREATE_IN_PROGRESS", + resources: map[string]string{ + "A": "CREATE_COMPLETE", "D": "CREATE_COMPLETE", "B": "CREATE_COMPLETE", "C": "CREATE_IN_PROGRESS", + }, + }, + { + stack: "CREATE_COMPLETE", + resources: map[string]string{ + "A": "CREATE_COMPLETE", "D": "CREATE_COMPLETE", "B": "CREATE_COMPLETE", "C": "CREATE_COMPLETE", + }, + }, + } + + for i, want := range steps { + if i > 0 { + e.sched.runNext(t) + } + + assert.Equal(t, want.stack, e.status(t, "waves"), "stack after step %d", i) + assert.Equal(t, want.resources, e.resourceStatuses(t, "waves"), "resources after step %d", i) + } + + assert.Empty(t, e.sched.queue) + assert.Equal(t, []string{"CREATE_IN_PROGRESS", initiated, "CREATE_COMPLETE"}, e.events(t, "waves", "C")) + assert.Less(t, e.order(t, "waves", "A", "CREATE_COMPLETE"), e.order(t, "waves", "B", "CREATE_IN_PROGRESS")) + assert.Less(t, e.order(t, "waves", "B", "CREATE_COMPLETE"), e.order(t, "waves", "C", "CREATE_IN_PROGRESS")) + assert.Less(t, e.order(t, "waves", "D", "CREATE_IN_PROGRESS"), e.order(t, "waves", "B", "CREATE_IN_PROGRESS"), + "the independent resource starts in the first wave") +} + +func TestAsyncWalk_InFlightResourceShapes(t *testing.T) { + t.Parallel() + + e := newTransitionEnv(t) + e.schedule(t) + + _, err := e.client.CreateStack(t.Context(), &cfnsdk.CreateStackInput{ + StackName: aws.String("shapes"), TemplateBody: aws.String(waveTemplate), + }) + require.NoError(t, err) + + one, err := e.client.DescribeStackResource(t.Context(), &cfnsdk.DescribeStackResourceInput{ + StackName: aws.String("shapes"), LogicalResourceId: aws.String("A"), + }) + require.NoError(t, err) + assert.Equal(t, cfntypes.ResourceStatusCreateInProgress, one.StackResourceDetail.ResourceStatus) + assert.Empty(t, aws.ToString(one.StackResourceDetail.PhysicalResourceId), "no physical id before creation") + + list, err := e.client.ListStackResources(t.Context(), &cfnsdk.ListStackResourcesInput{ + StackName: aws.String("shapes"), + }) + require.NoError(t, err) + require.Len(t, list.StackResourceSummaries, 2) + + for _, s := range list.StackResourceSummaries { + assert.Equal(t, cfntypes.ResourceStatusCreateInProgress, s.ResourceStatus) + } + + _, err = e.client.DescribeStackResource(t.Context(), &cfnsdk.DescribeStackResourceInput{ + StackName: aws.String("shapes"), LogicalResourceId: aws.String("C"), + }) + require.Error(t, err, "a resource that has not started is not listed yet") +} + +func TestAsyncWalk_MiddleFailureRollsBackCreated(t *testing.T) { + t.Parallel() + + e := newTransitionEnv(t) + e.failQueues(nil) + e.schedule(t) + + out, err := e.client.CreateStack(t.Context(), &cfnsdk.CreateStackInput{ + StackName: aws.String("middle"), TemplateBody: aws.String(middleFailTemplate), + }) + require.NoError(t, err) + + id := aws.ToString(out.StackId) + + for range 3 { + e.sched.runNext(t) + } + + assert.Equal(t, "ROLLBACK_IN_PROGRESS", e.status(t, id)) + assert.Equal(t, map[string]string{"A": "CREATE_COMPLETE", "B": "DELETE_IN_PROGRESS"}, e.resourceStatuses(t, id), + "only what was created is rolled back, newest dependents first") + assert.Empty(t, e.events(t, id, "C"), "resources after the failed one never start") + assert.Equal(t, "CREATE_FAILED", e.statuses(t, id, "M")[len(e.statuses(t, id, "M"))-1]) + + e.sched.runNext(t) + assert.Equal(t, "ROLLBACK_IN_PROGRESS", e.status(t, id)) + assert.Equal(t, map[string]string{"A": "DELETE_IN_PROGRESS"}, e.resourceStatuses(t, id)) + + e.sched.runNext(t) + assert.Equal(t, "ROLLBACK_COMPLETE", e.status(t, id)) + assert.Empty(t, e.resourceIDs(t, id)) + assert.Less(t, e.order(t, id, "B", "DELETE_COMPLETE"), e.order(t, id, "A", "DELETE_IN_PROGRESS")) + assert.Equal(t, + []string{"CREATE_IN_PROGRESS", initiated, "CREATE_COMPLETE", "DELETE_IN_PROGRESS", "DELETE_COMPLETE"}, + e.statusesWithReason(t, id, "A")) +} + +func (e *transitionEnv) statusesWithReason(t *testing.T, stack, logicalID string) []string { + t.Helper() + + got := e.events(t, stack, logicalID) + for i, entry := range got { + if entry == "CREATE_IN_PROGRESS|Resource creation Initiated" { + got[i] = initiated + } + } + + return got +} + +func TestAsyncWalk_UpdateReplacementAndCleanup(t *testing.T) { + t.Parallel() + + e := newTransitionEnv(t) + id := e.createSync(t, "replace", replaceV1) + e.schedule(t) + + _, err := e.client.UpdateStack(t.Context(), &cfnsdk.UpdateStackInput{ + StackName: aws.String("replace"), TemplateBody: aws.String(replaceV2), + }) + require.NoError(t, err) + + assert.Equal(t, "UPDATE_IN_PROGRESS", e.status(t, id)) + assert.Equal(t, "UPDATE_IN_PROGRESS", e.resourceStatuses(t, id)["Bucket"]) + + var trail []string + + for len(e.sched.queue) > 0 { + e.sched.runNext(t) + + trail = append(trail, e.status(t, id)) + } + + assert.Equal(t, []string{ + "UPDATE_COMPLETE_CLEANUP_IN_PROGRESS", "UPDATE_COMPLETE_CLEANUP_IN_PROGRESS", + "UPDATE_COMPLETE_CLEANUP_IN_PROGRESS", "UPDATE_COMPLETE", + }, trail, "replaced and removed resources are deleted during the cleanup phase, one wave per step") + + bucket := e.events(t, id, "Bucket") + assert.Equal(t, []string{ + "UPDATE_IN_PROGRESS|Requested update requires the creation of a new physical resource; " + + "hence creating one.", + "UPDATE_IN_PROGRESS|Resource creation Initiated", "UPDATE_COMPLETE", + "DELETE_IN_PROGRESS", "DELETE_COMPLETE", + }, bucket[3:]) + assert.Less(t, e.order(t, id, "Bucket", "UPDATE_COMPLETE"), e.order(t, id, "Bucket", "DELETE_IN_PROGRESS")) + assert.Less(t, e.order(t, id, "Bucket", "DELETE_COMPLETE"), e.order(t, id, "T", "DELETE_IN_PROGRESS"), + "replaced resources are cleaned up before dropped ones") + assert.Equal(t, []string{"Bucket"}, e.resourceIDs(t, id)) + assert.Equal(t, "UPDATE_COMPLETE", e.resourceStatuses(t, id)["Bucket"]) +} + +func TestAsyncWalk_DeleteOrderWithRetain(t *testing.T) { + t.Parallel() + + e := newTransitionEnv(t) + id := e.createSync(t, "retain", retainTpl) + e.schedule(t) + + require.NoError(t, e.deleteStack(t, "retain")) + assert.Equal(t, "DELETE_IN_PROGRESS", e.resourceStatuses(t, id)["B"]) + assert.Equal(t, "CREATE_COMPLETE", e.resourceStatuses(t, id)["A"]) + + e.sched.runNext(t) + assert.Equal(t, "DELETE_IN_PROGRESS", e.status(t, id)) + assert.Equal(t, map[string]string{"A": "DELETE_IN_PROGRESS"}, e.resourceStatuses(t, id), + "the retained resource leaves the stack, its dependency is next") + + e.sched.runNext(t) + assert.Equal(t, "DELETE_COMPLETE", e.status(t, id)) + assert.Equal(t, "DELETE_SKIPPED", e.statuses(t, id, "B")[len(e.statuses(t, id, "B"))-1]) + assert.Less(t, e.order(t, id, "B", "DELETE_SKIPPED"), e.order(t, id, "A", "DELETE_IN_PROGRESS")) + assert.Equal(t, "DELETE_COMPLETE", e.statuses(t, id, "A")[len(e.statuses(t, id, "A"))-1]) +} + +func TestAsyncWalk_CancelBetweenResources(t *testing.T) { + t.Parallel() + + e := newTransitionEnv(t) + id := e.createSync(t, "cancel", cancelFrom) + e.schedule(t) + + _, err := e.client.UpdateStack(t.Context(), &cfnsdk.UpdateStackInput{ + StackName: aws.String("cancel"), TemplateBody: aws.String(cancelTo), + }) + require.NoError(t, err) + + e.sched.runNext(t) + assert.Equal(t, "UPDATE_IN_PROGRESS", e.status(t, id)) + assert.Equal(t, "CREATE_COMPLETE", e.resourceStatuses(t, id)["B"]) + assert.Equal(t, "CREATE_IN_PROGRESS", e.resourceStatuses(t, id)["C"]) + + _, err = e.client.CancelUpdateStack(t.Context(), &cfnsdk.CancelUpdateStackInput{StackName: aws.String("cancel")}) + require.NoError(t, err) + + assert.Equal(t, "UPDATE_ROLLBACK_IN_PROGRESS", e.status(t, id)) + assert.Equal(t, "CREATE_FAILED|Resource creation cancelled", e.events(t, id, "C")[1]) + assert.Equal(t, map[string]string{"A": "CREATE_COMPLETE", "B": "DELETE_IN_PROGRESS"}, e.resourceStatuses(t, id)) + + e.drain(t) + + assert.Equal(t, "UPDATE_ROLLBACK_COMPLETE", e.status(t, id)) + assert.Equal(t, []string{"A"}, e.resourceIDs(t, id)) + assert.Equal(t, []string{ + "CREATE_IN_PROGRESS", "CREATE_COMPLETE", "UPDATE_IN_PROGRESS", "UPDATE_ROLLBACK_IN_PROGRESS", + "UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS", "UPDATE_ROLLBACK_COMPLETE", + }, e.stackStatuses(t, id)) + + tmpl, err := e.client.GetTemplate(t.Context(), &cfnsdk.GetTemplateInput{StackName: aws.String("cancel")}) + require.NoError(t, err) + assert.JSONEq(t, cancelFrom, aws.ToString(tmpl.TemplateBody)) +} + +func failedRollbackEnv(t *testing.T) (*transitionEnv, string) { + t.Helper() + + e := newTransitionEnv(t) + id := e.createSync(t, "ur", cancelFrom) + e.failQueues(func() { e.fillBucket(t) }) + e.schedule(t) + + _, err := e.client.UpdateStack(t.Context(), &cfnsdk.UpdateStackInput{ + StackName: aws.String("ur"), TemplateBody: aws.String(rollbackFailTpl), + }) + require.NoError(t, err) + + e.drain(t) + require.Equal(t, "UPDATE_ROLLBACK_FAILED", e.status(t, id)) + + return e, id +} + +func TestAsyncWalk_UpdateRollbackFailed(t *testing.T) { + t.Parallel() + + e, id := failedRollbackEnv(t) + + assert.Equal(t, "UPDATE_FAILED", e.resourceStatuses(t, id)["Bucket"]) + assert.Equal(t, "CREATE_COMPLETE", e.resourceStatuses(t, id)["A"]) + assert.NotContains(t, e.resourceStatuses(t, id), "Q") + + trail := e.statuses(t, id, "Bucket") + assert.Equal(t, []string{"DELETE_IN_PROGRESS", "UPDATE_FAILED"}, trail[len(trail)-2:]) + assert.Equal(t, []string{ + "CREATE_IN_PROGRESS", "CREATE_COMPLETE", "UPDATE_IN_PROGRESS", "UPDATE_ROLLBACK_IN_PROGRESS", + "UPDATE_ROLLBACK_FAILED", + }, e.stackStatuses(t, id)) +} + +func TestAsyncWalk_ContinueUpdateRollback(t *testing.T) { + t.Parallel() + + cases := []struct { + fix func(t *testing.T, e *transitionEnv) + wantRes map[string]string + in cfnsdk.ContinueUpdateRollbackInput + name string + wantErr string + wantStatus string + }{ + { + name: "retry_after_fix", + fix: func(t *testing.T, e *transitionEnv) { t.Helper(); e.emptyBucket(t) }, + wantStatus: "UPDATE_ROLLBACK_COMPLETE", + wantRes: map[string]string{"A": "CREATE_COMPLETE"}, + }, + { + name: "retry_fails_again", + wantStatus: "UPDATE_ROLLBACK_FAILED", + wantRes: map[string]string{"A": "CREATE_COMPLETE", "Bucket": "UPDATE_FAILED"}, + }, + { + name: "skip_resource", + in: cfnsdk.ContinueUpdateRollbackInput{ResourcesToSkip: []string{"Bucket"}}, + wantStatus: "UPDATE_ROLLBACK_COMPLETE", + wantRes: map[string]string{"A": "CREATE_COMPLETE", "Bucket": "UPDATE_COMPLETE"}, + }, + { + name: "force_rollback", + in: cfnsdk.ContinueUpdateRollbackInput{ForceRollback: aws.Bool(true)}, + wantStatus: "UPDATE_ROLLBACK_COMPLETE", + wantRes: map[string]string{"A": "CREATE_COMPLETE", "Bucket": "UPDATE_COMPLETE"}, + }, + { + name: "skip_healthy_resource", + in: cfnsdk.ContinueUpdateRollbackInput{ResourcesToSkip: []string{"A"}}, + wantErr: "cannot be skipped", + }, + { + name: "force_and_skip", + in: cfnsdk.ContinueUpdateRollbackInput{ + ForceRollback: aws.Bool(true), ResourcesToSkip: []string{"Bucket"}, + }, + wantErr: "mutually exclusive", + }, + { + name: "nested_entry_without_nested_stack", + in: cfnsdk.ContinueUpdateRollbackInput{ResourcesToSkip: []string{"NoSuchStack.Bucket"}}, + wantErr: "not a nested stack", + }, + { + name: "bad_role", + in: cfnsdk.ContinueUpdateRollbackInput{RoleARN: aws.String("not-an-arn")}, + wantErr: "role", + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + e, id := failedRollbackEnv(t) + + if tc.fix != nil { + tc.fix(t, e) + } + + in := tc.in + in.StackName = aws.String(id) + + _, err := e.client.ContinueUpdateRollback(t.Context(), &in) + if tc.wantErr != "" { + require.ErrorContains(t, err, tc.wantErr) + assert.Equal(t, "UPDATE_ROLLBACK_FAILED", e.status(t, id), "a rejected request changes nothing") + + return + } + + require.NoError(t, err) + assert.Equal(t, "UPDATE_ROLLBACK_IN_PROGRESS", e.status(t, id)) + + e.drain(t) + + assert.Equal(t, tc.wantStatus, e.status(t, id)) + assert.Equal(t, tc.wantRes, e.resourceStatuses(t, id)) + }) + } +} + +func TestAsyncWalk_ContinueUpdateRollbackEvents(t *testing.T) { + t.Parallel() + + e, id := failedRollbackEnv(t) + e.emptyBucket(t) + + _, err := e.client.ContinueUpdateRollback(t.Context(), &cfnsdk.ContinueUpdateRollbackInput{ + StackName: aws.String(id), RoleARN: aws.String("arn:aws:iam::000000000000:role/rb"), + }) + require.NoError(t, err) + + e.drain(t) + + assert.Equal(t, []string{ + "CREATE_IN_PROGRESS", "CREATE_COMPLETE", "UPDATE_IN_PROGRESS", "UPDATE_ROLLBACK_IN_PROGRESS", + "UPDATE_ROLLBACK_FAILED", "UPDATE_ROLLBACK_IN_PROGRESS", + "UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS", "UPDATE_ROLLBACK_COMPLETE", + }, e.stackStatuses(t, id)) + + trail := e.statuses(t, id, "Bucket") + assert.Equal(t, []string{"DELETE_IN_PROGRESS", "UPDATE_FAILED", "DELETE_IN_PROGRESS", "DELETE_COMPLETE"}, + trail[len(trail)-4:]) + assert.Equal(t, "arn:aws:iam::000000000000:role/rb", aws.ToString(describeOne(t, e.client, id).RoleARN)) + + _, err = e.client.ContinueUpdateRollback(t.Context(), &cfnsdk.ContinueUpdateRollbackInput{ + StackName: aws.String(id), + }) + require.ErrorContains(t, err, "is in UPDATE_ROLLBACK_COMPLETE state and can not be continue rolled back") +} + +func TestAsyncWalk_ContinueUpdateRollbackInvalidState(t *testing.T) { + t.Parallel() + + e := newTransitionEnv(t) + id := e.createSync(t, "valid", cancelFrom) + + _, err := e.client.ContinueUpdateRollback(t.Context(), &cfnsdk.ContinueUpdateRollbackInput{ + StackName: aws.String(id), + }) + require.ErrorContains(t, err, "is in CREATE_COMPLETE state and can not be continue rolled back") + assert.Contains(t, err.Error(), "ValidationError") + + _, err = e.client.ContinueUpdateRollback(t.Context(), &cfnsdk.ContinueUpdateRollbackInput{ + StackName: aws.String("missing"), + }) + require.Error(t, err) +} + +func TestAsyncWalk_SyncEventOrderMatchesAsync(t *testing.T) { + t.Parallel() + + signature := func(t *testing.T, e *transitionEnv, stack string) []string { + t.Helper() + + events := e.allEvents(t, stack) + out := make([]string, 0, len(events)) + + for _, ev := range events { + out = append(out, aws.ToString(ev.LogicalResourceId)+"|"+string(ev.ResourceStatus)+"|"+ + aws.ToString(ev.ResourceStatusReason)) + } + + return out + } + + run := func(t *testing.T, async bool) []string { + t.Helper() + + e := newTransitionEnv(t) + if async { + e.schedule(t) + } + + _, err := e.client.CreateStack(t.Context(), &cfnsdk.CreateStackInput{ + StackName: aws.String("order"), TemplateBody: aws.String(waveTemplate), + }) + require.NoError(t, err) + + if async { + e.drain(t) + } + + require.NoError(t, e.deleteStack(t, "order")) + + if async { + e.drain(t) + } + + return signature(t, e, "order") + } + + assert.Equal(t, run(t, false), run(t, true)) +} + +func TestAsyncWalk_CloseAndReset(t *testing.T) { + t.Parallel() + + cases := []struct { + stop func(ctx context.Context, b *cloudformation.InMemoryBackend) + name string + wantStatus string + wantGone bool + }{ + { + name: "backend_close", wantStatus: "CREATE_IN_PROGRESS", + stop: func(_ context.Context, b *cloudformation.InMemoryBackend) { b.Close() }, + }, + { + name: "backend_reset", wantGone: true, + stop: func(_ context.Context, b *cloudformation.InMemoryBackend) { b.Reset() }, + }, + { + name: "handler_shutdown", wantStatus: "CREATE_IN_PROGRESS", + stop: func(ctx context.Context, b *cloudformation.InMemoryBackend) { + cloudformation.NewHandler(b).Shutdown(ctx) + }, + }, + { + name: "handler_reset", wantGone: true, + stop: func(_ context.Context, b *cloudformation.InMemoryBackend) { cloudformation.NewHandler(b).Reset() }, + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + synctest.Test(t, func(t *testing.T) { + b, client := newTestHandlerAndClientWithBackend(t) + b.SetProvisioningDelay(time.Second) + + _, err := client.CreateStack(t.Context(), &cfnsdk.CreateStackInput{ + StackName: aws.String("stopped"), TemplateBody: aws.String(depChain), + }) + require.NoError(t, err) + + tc.stop(t.Context(), b) + b.WaitForStackProvisioning() + + time.Sleep(time.Minute) + synctest.Wait() + + out, err := client.DescribeStacks(t.Context(), &cfnsdk.DescribeStacksInput{ + StackName: aws.String("stopped"), + }) + + if tc.wantGone { + require.Error(t, err) + + return + } + + require.NoError(t, err) + require.Len(t, out.Stacks, 1) + assert.Equal(t, tc.wantStatus, string(out.Stacks[0].StackStatus), "no step ran after the stop") + }) + }) + } +} + +func TestAsyncWalk_ResetDropsQueuedSteps(t *testing.T) { + t.Parallel() + + e := newTransitionEnv(t) + e.schedule(t) + + _, err := e.client.CreateStack(t.Context(), &cfnsdk.CreateStackInput{ + StackName: aws.String("queued"), TemplateBody: aws.String(depChain), + }) + require.NoError(t, err) + + e.backend.Reset() + assert.Equal(t, 1, e.drain(t), "the queued step still runs and finds nothing to do") + + _, err = e.client.DescribeStacks(t.Context(), &cfnsdk.DescribeStacksInput{StackName: aws.String("queued")}) + require.Error(t, err) +} + +func TestAsyncWalk_SnapshotMidFlight(t *testing.T) { + t.Parallel() + + cases := []struct { + start func(t *testing.T, e *transitionEnv) string + finish func(t *testing.T, e *transitionEnv, id string) + name string + wantMid string + wantStatus string + wantRes []string + steps int + }{ + { + name: "create", + start: func(t *testing.T, e *transitionEnv) string { + t.Helper() + + e.schedule(t) + + out, err := e.client.CreateStack(t.Context(), &cfnsdk.CreateStackInput{ + StackName: aws.String("snap"), TemplateBody: aws.String(waveTemplate), + }) + require.NoError(t, err) + e.sched.runNext(t) + + return aws.ToString(out.StackId) + }, + wantMid: "CREATE_IN_PROGRESS", wantStatus: "CREATE_COMPLETE", + wantRes: []string{"A", "B", "C", "D"}, steps: 2, + }, + { + name: "update", + start: func(t *testing.T, e *transitionEnv) string { + t.Helper() + + id := e.createSync(t, "snap", cancelFrom) + e.schedule(t) + + _, err := e.client.UpdateStack(t.Context(), &cfnsdk.UpdateStackInput{ + StackName: aws.String("snap"), TemplateBody: aws.String(cancelTo), + }) + require.NoError(t, err) + e.sched.runNext(t) + + return id + }, + wantMid: "UPDATE_IN_PROGRESS", wantStatus: "UPDATE_COMPLETE", + wantRes: []string{"A", "B", "C"}, steps: 2, + }, + { + name: "delete", + start: func(t *testing.T, e *transitionEnv) string { + t.Helper() + + id := e.createSync(t, "snap", retainTpl) + e.schedule(t) + require.NoError(t, e.deleteStack(t, "snap")) + e.sched.runNext(t) + + return id + }, + wantMid: "DELETE_IN_PROGRESS", wantStatus: "DELETE_COMPLETE", steps: 1, + }, + { + name: "rollback_failed", + start: func(t *testing.T, e *transitionEnv) string { + t.Helper() + + e.failQueues(func() { e.fillBucket(t) }) + e.createSync(t, "snap", cancelFrom) + e.schedule(t) + + out, err := e.client.DescribeStacks(t.Context(), &cfnsdk.DescribeStacksInput{ + StackName: aws.String("snap"), + }) + require.NoError(t, err) + + _, err = e.client.UpdateStack(t.Context(), &cfnsdk.UpdateStackInput{ + StackName: aws.String("snap"), TemplateBody: aws.String(rollbackFailTpl), + }) + require.NoError(t, err) + e.drain(t) + + return aws.ToString(out.Stacks[0].StackId) + }, + finish: func(t *testing.T, e *transitionEnv, id string) { + t.Helper() + + _, err := e.client.ContinueUpdateRollback(t.Context(), &cfnsdk.ContinueUpdateRollbackInput{ + StackName: aws.String(id), ForceRollback: aws.Bool(true), + }) + require.NoError(t, err) + }, + wantMid: "UPDATE_ROLLBACK_FAILED", wantStatus: "UPDATE_ROLLBACK_COMPLETE", + wantRes: []string{"A", "Bucket"}, + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + src := newTransitionEnv(t) + id := tc.start(t, src) + assert.Equal(t, tc.wantMid, src.status(t, id)) + + snap := src.backend.Snapshot(t.Context()) + require.NotNil(t, snap) + + inline := newTransitionEnv(t) + require.NoError(t, inline.backend.Restore(t.Context(), snap)) + + if tc.finish == nil { + assert.Equal(t, tc.wantStatus, inline.status(t, id), "restore without a scheduler settles it") + assert.ElementsMatch(t, tc.wantRes, inline.resourceIDsIfLive(t, id)) + } else { + assert.Equal(t, tc.wantMid, inline.status(t, id)) + tc.finish(t, inline, id) + assert.Equal(t, tc.wantStatus, inline.status(t, id)) + assert.ElementsMatch(t, tc.wantRes, inline.resourceIDs(t, id)) + } + + if tc.steps == 0 { + return + } + + stepped := newTransitionEnv(t) + stepped.schedule(t) + require.NoError(t, stepped.backend.Restore(t.Context(), snap)) + assert.Equal(t, tc.wantMid, stepped.status(t, id), "restore with a scheduler resumes step by step") + assert.Equal(t, tc.steps, stepped.drain(t)) + assert.Equal(t, tc.wantStatus, stepped.status(t, id)) + }) + } +} + +func (e *transitionEnv) resourceIDsIfLive(t *testing.T, stack string) []string { + t.Helper() + + out, err := e.client.DescribeStackResources(t.Context(), &cfnsdk.DescribeStackResourcesInput{ + StackName: aws.String(stack), + }) + if err != nil { + return nil + } + + ids := make([]string, 0, len(out.StackResources)) + for _, r := range out.StackResources { + ids = append(ids, aws.ToString(r.LogicalResourceId)) + } + + slices.Sort(ids) + + return ids +} + +const ( + queueV1 = `{"Resources":{"Q1":{"Type":"AWS::SQS::Queue","Properties":{"DelaySeconds":"1"}}}}` + queueV2 = `{"Resources":{"Q1":{"Type":"AWS::SQS::Queue","Properties":{"DelaySeconds":"5"}},` + + `"Q2":{"Type":"AWS::SQS::Queue","DependsOn":"Q1"}}}` +) + +func (e *transitionEnv) queueDelay(t *testing.T, queueURL string) (string, error) { + t.Helper() + + out, err := e.backends.SQS.Backend.GetQueueAttributes(&sqsbackend.GetQueueAttributesInput{ + QueueURL: queueURL, Region: "us-east-1", AttributeNames: []string{"DelaySeconds"}, + }) + if err != nil { + return "", err + } + + return out.Attributes["DelaySeconds"], nil +} + +func TestAsyncWalk_RollbackRevertsModifiedResource(t *testing.T) { + t.Parallel() + + cases := []struct { + name string + wantStatus string + wantQ1 string + wantTrail []string + deleteQ bool + }{ + { + name: "restored", + wantStatus: "UPDATE_ROLLBACK_COMPLETE", + wantQ1: "CREATE_COMPLETE", + wantTrail: []string{"UPDATE_IN_PROGRESS", "UPDATE_COMPLETE", "UPDATE_IN_PROGRESS", "UPDATE_COMPLETE"}, + }, + { + name: "revert_fails", + deleteQ: true, + wantStatus: "UPDATE_ROLLBACK_FAILED", + wantQ1: "UPDATE_FAILED", + wantTrail: []string{"UPDATE_COMPLETE", "UPDATE_IN_PROGRESS", "UPDATE_FAILED"}, + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + e := newTransitionEnv(t) + id := e.createSync(t, "revert", queueV1) + + res, err := e.client.DescribeStackResource(t.Context(), &cfnsdk.DescribeStackResourceInput{ + StackName: aws.String(id), LogicalResourceId: aws.String("Q1"), + }) + require.NoError(t, err) + + url := aws.ToString(res.StackResourceDetail.PhysicalResourceId) + + e.failQueues(func() { + if !tc.deleteQ { + return + } + + assert.NoError(t, e.backends.SQS.Backend.DeleteQueue(&sqsbackend.DeleteQueueInput{ + QueueURL: url, Region: "us-east-1", + })) + }) + e.schedule(t) + + _, err = e.client.UpdateStack(t.Context(), &cfnsdk.UpdateStackInput{ + StackName: aws.String("revert"), TemplateBody: aws.String(queueV2), + }) + require.NoError(t, err) + + e.drain(t) + + assert.Equal(t, tc.wantStatus, e.status(t, id)) + assert.Equal(t, tc.wantQ1, e.resourceStatuses(t, id)["Q1"]) + assert.NotContains(t, e.resourceStatuses(t, id), "Q2") + + trail := e.statuses(t, id, "Q1") + assert.Equal(t, tc.wantTrail, trail[len(trail)-len(tc.wantTrail):]) + + if tc.deleteQ { + return + } + + delay, delayErr := e.queueDelay(t, url) + require.NoError(t, delayErr) + assert.Equal(t, "1", delay, "the in-place update is reverted") + }) + } +} diff --git a/services/cloudformation/stacks.go b/services/cloudformation/stacks.go index e799cc8199..e6dfeb94c8 100644 --- a/services/cloudformation/stacks.go +++ b/services/cloudformation/stacks.go @@ -2,8 +2,6 @@ package cloudformation import ( "context" - "fmt" - "maps" "slices" "sort" "time" @@ -108,10 +106,10 @@ func (b *InMemoryBackend) CreateNestedStack( } settleLater := b.stepAsync && b.provisionSchedule != nil - stepAsync, announced := b.stepAsync, b.announced - b.stepAsync, b.announced = false, nil + stepAsync := b.stepAsync + b.stepAsync = false - defer func() { b.stepAsync, b.announced = stepAsync, announced }() + defer func() { b.stepAsync = stepAsync }() // Lock already held by parent CreateStack — use the no-lock variant. stack, err := b.beginCreateLocked(name, templateBody, params, StackOptions{}, parentID) @@ -132,13 +130,15 @@ func (b *InMemoryBackend) CreateNestedStack( } // DeleteNestedStack implements NestedStackCreator. Must be called while b.mu is held by caller. +// The child is deleted at once and settles on its own later step, which the parent waits for. func (b *InMemoryBackend) DeleteNestedStack(ctx context.Context, stackID string) error { - announced := b.announced - b.announced = nil + settleLater := b.stepAsync && b.provisionSchedule != nil + stepAsync := b.stepAsync + b.stepAsync = false - defer func() { b.announced = announced }() + defer func() { b.stepAsync = stepAsync }() - return b.deleteStackLocked(ctx, stackID) + return b.deleteStackWithLocked(ctx, stackID, deleteSettings{settleLater: settleLater}, false) } // evictDeletedStacks caps the number of DELETE_COMPLETE stacks at maxDeletedStacks. @@ -258,7 +258,7 @@ func (b *InMemoryBackend) createStack( ResourceTypes: opts.ResourceTypes, RetainExceptOnCreate: opts.RetainExceptOnCreate, OnFailure: opts.OnFailure, - Announced: b.announceCreateLocked(stack, params), + InFlight: b.announceCreateLocked(stack, params), } if b.scheduleLocked(ctx, stack.StackID, op) { @@ -382,6 +382,7 @@ func (b *InMemoryBackend) beginCreateLocked( } type createFinish struct { + announced map[string]string onFailure string resourceTypes []string disableValidation bool @@ -389,6 +390,12 @@ type createFinish struct { settleLater bool } +func (f createFinish) withAnnounced(inFlight map[string]string) createFinish { + f.announced = inFlight + + return f +} + func createFinishOpts(opts StackOptions) createFinish { return createFinish{ onFailure: opts.OnFailure, @@ -407,8 +414,16 @@ func (b *InMemoryBackend) finishCreateLocked( ) { if stack.TemplateBody != "" { b.createStackFromTemplate(ctx, stack, params, opts) + + if b.createWalkPending(stack) { + return + } } + b.settleCreateLocked(ctx, stack, opts) +} + +func (b *InMemoryBackend) settleCreateLocked(ctx context.Context, stack *Stack, opts createFinish) { switch { case stack.StackStatus == statusRollbackInProgress, stack.StackStatus == statusDeleteInProgress, @@ -466,21 +481,6 @@ func (b *InMemoryBackend) deleteAfterFailedCreateLocked(ctx context.Context, sta }) } -// announceCreateLocked emits CREATE_IN_PROGRESS for the resources that start -// first, so the window shows them before the provisioning step runs. -func (b *InMemoryBackend) announceCreateLocked(stack *Stack, params []Parameter) []string { - tmpl, err := ParseTemplate(stack.TemplateBody) - if err != nil { - return nil - } - - pruneConditional(tmpl, ResolveParameters(tmpl, params)) - - return b.announceLocked( - stack, statusCreateInProgress, firstWave(tmpl.Resources, sortedKeys(tmpl.Resources), false), tmpl.Resources, - ) -} - // createStackFromTemplate parses and applies a template during CreateStack. // It updates stack.StackStatus on failure. opts carries CreateStackInput's own // DisableValidation/ResourceTypes/RetainExceptOnCreate/OnFailure (see StackOptions); @@ -556,45 +556,14 @@ func (b *InMemoryBackend) createStackFromTemplate( return } - physicalIDs := b.provisionResources(ctx, stack, tmpl, resolvedParams, opts) - if isFailedCreateStatus(stack.StackStatus) || stack.StackStatus == statusRollbackInProgress { - return - } + if _, ordErr := topoSortResources(tmpl.Resources); ordErr != nil { + b.failAndRollback(ctx, stack, opts, ordErr.Error()) - resourceTypes := make(map[string]string, len(tmpl.Resources)) - for logicalID, res := range tmpl.Resources { - resourceTypes[logicalID] = res.Type - } - stack.ResourceAttrs = extractAttrStash(physicalIDs, resourceTypes) - rctx := resolveCtx{ - params: resolvedParams, - physicalIDs: physicalIDs, - resourceTypes: resourceTypes, - exports: b.buildExportsMap(), - conditions: evaluateConditions(tmpl.Conditions, resolvedParams, physicalIDs), - mappings: tmpl.Mappings, - accountID: b.accountID, - region: b.region, - stackName: name, + return } - var exportMap map[string]string - stack.Outputs, exportMap = resolveOutputsWithContext(tmpl, rctx) - if regErr := b.registerExports(stack.StackID, exportMap); regErr != nil { - stack.StackStatus = statusCreateFailed - stack.StackStatusReason = regErr.Error() - b.addEvent(arn, name, name, arn, cfnStackType, statusCreateFailed, regErr.Error()) - } -} - -// updateFailAndRollback records UPDATE_FAILED then enters UPDATE_ROLLBACK_IN_PROGRESS -// for pre-flight update failures (no resources changed). -func (b *InMemoryBackend) updateFailAndRollback(ctx context.Context, stack *Stack, reason string) { - arn := stack.StackID - name := stack.StackName - stack.StackStatusReason = reason - b.addEvent(arn, name, name, arn, cfnStackType, statusUpdateFailed, reason) - b.beginUpdateRollbackLocked(ctx, stack, nil, nil, reason, false) + op := b.newCreateWalk(stack, &walkRuntime{tmpl: tmpl, params: resolvedParams}, opts) + b.walkCreateLocked(ctx, stack, op) } // failAndRollback records a pre-flight CREATE_FAILED then enters rollback (no @@ -610,208 +579,6 @@ func (b *InMemoryBackend) failAndRollback(ctx context.Context, stack *Stack, opt b.enterCreateRollbackLocked(ctx, stack, nil, opts, reason) } -// enterCreateRollbackLocked moves a failed create to ROLLBACK_IN_PROGRESS and -// undoes created in the same step, or in the next one when async. -func (b *InMemoryBackend) enterCreateRollbackLocked( - ctx context.Context, stack *Stack, created []string, opts createFinish, reason string, -) { - if stack.DisableRollback { - stack.StackStatus = statusCreateFailed - - return - } - - stack.StackStatus = statusRollbackInProgress - b.addEvent( - stack.StackID, stack.StackName, stack.StackName, stack.StackID, - cfnStackType, statusRollbackInProgress, reason, - ) - - op := &pendingStackOp{ - Kind: pendingRollbackCreate, - Created: created, - OnFailure: opts.onFailure, - RetainExceptOnCreate: opts.retainExceptOnCreate, - } - - b.stageLocked(ctx, stack.StackID, op, func() { b.finishCreateRollbackLocked(ctx, stack, created, opts) }) -} - -// finishCreateRollbackLocked deletes the resources a failed create made and -// settles the stack ROLLBACK_COMPLETE or ROLLBACK_FAILED. -func (b *InMemoryBackend) finishCreateRollbackLocked( - ctx context.Context, stack *Stack, created []string, opts createFinish, -) { - arn, name := stack.StackID, stack.StackName - - if b.rollbackCreateResources(ctx, stack, created, opts.retainExceptOnCreate) { - b.addEvent(arn, name, name, arn, cfnStackType, statusRollbackComplete, "") - stack.StackStatus = statusRollbackComplete - b.deleteAfterFailedCreateLocked(ctx, stack, opts) - - return - } - - reason := reasonRollbackDeleteFailed - b.addEvent(arn, name, name, arn, cfnStackType, statusRollbackFailed, reason) - stack.StackStatus = statusRollbackFailed - stack.StackStatusReason = reason -} - -// provisionResources creates all resources defined in the template. -// Returns the physicalIDs map. On resource creation failure, rollback is -// performed in reverse order (unless stack.DisableRollback -- real AWS: -// "Set to true to disable rollback of the stack if stack creation failed"; -// the stack is then left CREATE_FAILED with whatever it managed to create -// intact); stack.StackStatus is then set to statusRollbackComplete (matching -// real AWS behaviour). If the creation failure itself needs to be recorded -// separately, it is preserved in StackStatusReason. retainExceptOnCreate -// mirrors CreateStackInput.RetainExceptOnCreate (see StackOptions). -func (b *InMemoryBackend) provisionResources( - ctx context.Context, - stack *Stack, - tmpl *Template, - resolvedParams map[string]string, - opts createFinish, -) map[string]string { - arn := stack.StackID - name := stack.StackName - physicalIDs := make(map[string]string) - - // Inject stack metadata for custom resource event payloads. - physicalIDs["_StackId"] = arn - physicalIDs["_StackName"] = name - - // Side channel so property-time Fn::GetAtt (ResolveValue, called by - // strProp/resolve while a resource's own Properties are resolved at - // create time) can find a referenced resource's declared type and the - // account/region, the same way Outputs-time resolution does via - // resolveCtx.resourceTypes -- see physIDResourceTypeKey. - physicalIDs[physIDAccountIDKey] = b.accountID - physicalIDs[physIDRegionKey] = b.region - for logicalID, res := range tmpl.Resources { - physicalIDs[physIDResourceTypeKey(logicalID)] = res.Type - } - - // Lets a nested AWS::CloudFormation::Stack resource created below learn - // its ParentId (gopherstack-pbv1) without widening ResourceCreator.Create's - // signature. - ctx = parentStackIDKey.Set(ctx, stack.StackID) - - ordered, ordErr := topoSortResources(tmpl.Resources) - if ordErr != nil { - b.failAndRollback(ctx, stack, opts, ordErr.Error()) - - return physicalIDs - } - - created := make([]string, 0, len(ordered)) - - for _, logicalID := range ordered { - res := tmpl.Resources[logicalID] - b.addProgressEvent(arn, name, logicalID, "", res.Type, statusCreateInProgress) - physicalID, cerr := b.creator.Create( - ctx, - logicalID, - res.Type, - res.Properties, - resolvedParams, - physicalIDs, - ) - if cerr != nil { - stack.StackStatusReason = fmt.Sprintf("resource %s: %v", logicalID, cerr) - b.addEvent(arn, name, logicalID, "", res.Type, statusCreateFailed, cerr.Error()) - b.enterCreateRollbackLocked(ctx, stack, created, opts, cerr.Error()) - - return physicalIDs - } - - b.addEvent(arn, name, logicalID, physicalID, res.Type, statusCreateInProgress, reasonCreationInitiated) - physicalIDs[logicalID] = physicalID - b.resources[arn][logicalID] = &StackResource{ - Timestamp: time.Now(), - LogicalID: logicalID, - PhysicalID: physicalID, - Type: res.Type, - Status: statusCreateComplete, - Properties: res.Properties, - StackID: arn, - StackName: name, - DeletionPolicy: res.DeletionPolicy, - } - b.addEvent(arn, name, logicalID, physicalID, res.Type, statusCreateComplete, "") - created = append(created, logicalID) - } - - return physicalIDs -} - -// rollbackCreateResources deletes all resources that were created during a -// failed CreateStack provisioning pass, in reverse order. It reports whether -// every deletion succeeded; a resource that fails to delete is left in place -// (matching real AWS, which leaves a ROLLBACK_FAILED stack's undeleted -// resources describable for a retry) rather than being silently dropped. -// retainExceptOnCreate mirrors CreateStackInput.RetainExceptOnCreate (see -// StackOptions): by default a newly-created resource with -// DeletionPolicy=Retain/Snapshot is left in place (not deleted) during -// rollback, matching every other DeletionPolicy-honoring deletion path in -// this backend (DeleteStack, deleteStaleResources); when true, it is force- -// deleted anyway. -func (b *InMemoryBackend) rollbackCreateResources( - ctx context.Context, - stack *Stack, - created []string, - retainExceptOnCreate bool, -) bool { - ok := true - physIDs := b.deleteResolveContext(stack) - - for _, v := range slices.Backward(created) { - logicalID := v - res, exists := b.resources[stack.StackID][logicalID] - if !exists { - continue - } - - b.addEvent( - stack.StackID, - stack.StackName, - logicalID, - res.PhysicalID, - res.Type, - statusDeleteInProgress, - "", - ) - - keepsPolicy := res.DeletionPolicy == deletionPolicyRetain || res.DeletionPolicy == deletionPolicySnapshot - retained := keepsPolicy && !retainExceptOnCreate - if !retained { - if delErr := b.creator.Delete(ctx, res.Type, res.PhysicalID, res.Properties, physIDs); delErr != nil { - ok = false - b.addEvent( - stack.StackID, stack.StackName, logicalID, res.PhysicalID, res.Type, - statusDeleteFailed, delErr.Error(), - ) - - continue - } - } - - b.addEvent( - stack.StackID, - stack.StackName, - logicalID, - res.PhysicalID, - res.Type, - statusDeleteComplete, - "", - ) - delete(b.resources[stack.StackID], logicalID) - } - - return ok -} - // UpdateStack updates an existing stack. func (b *InMemoryBackend) UpdateStack( ctx context.Context, @@ -866,8 +633,6 @@ func (b *InMemoryBackend) updateStackLocked( oldTemplateBody := stack.TemplateBody oldParams := slices.Clone(stack.Parameters) - changes := b.changesIfAsync(async, templateBody, stack, params) - now := time.Now() stack.LastUpdatedTime = &now stack.StackStatus = statusUpdateInProgress @@ -896,83 +661,19 @@ func (b *InMemoryBackend) updateStackLocked( cfnStackType, statusUpdateInProgress, reasonUserInitiated, ) - op := &pendingStackOp{ - Kind: pendingUpdate, - DisableValidation: opts.DisableValidation, - ResourceTypes: opts.ResourceTypes, - RetainExceptOnCreate: opts.RetainExceptOnCreate, - OldTemplateBody: oldTemplateBody, - OldParams: oldParams, - } - - if async && b.scheduleUpdateLocked(ctx, stack, op, changes) { - return stack, nil - } - - if b.applyTemplateToStack(ctx, stack, op.updateOptions(), oldTemplateBody, oldParams) { - b.completeUpdateLocked(stack) - } + op := b.newUpdateOp(opts, oldTemplateBody, oldParams) - return stack, nil -} - -func (b *InMemoryBackend) changesIfAsync( - async bool, templateBody string, stack *Stack, params []Parameter, -) []Change { - if !async || b.provisionSchedule == nil { - return nil - } - - return b.computeChanges(templateBody, stack, params) -} - -// scheduleUpdateLocked announces the update's first wave and defers the rest; -// false means async provisioning is off. -func (b *InMemoryBackend) scheduleUpdateLocked( - ctx context.Context, stack *Stack, op *pendingStackOp, changes []Change, -) bool { - if b.provisionSchedule == nil { - return false - } - - op.Announced = b.announceUpdateLocked(stack, changes) - - return b.scheduleLocked(ctx, stack.StackID, op) -} + if async && b.provisionSchedule != nil { + b.announceUpdateLocked(ctx, stack, op) -// announceUpdateLocked emits the first wave of CREATE/UPDATE_IN_PROGRESS events -// for the resources an update adds or modifies in place. -func (b *InMemoryBackend) announceUpdateLocked(stack *Stack, changes []Change) []string { - tmpl, err := ParseTemplate(stack.TemplateBody) - if err != nil { - return nil - } - - statusOf := make(map[string]string, len(changes)) - want := make([]string, 0, len(changes)) - - for _, c := range changes { - rc := c.ResourceChange - - switch { - case rc.Action == changeActionAdd: - statusOf[rc.LogicalID] = statusCreateInProgress - case rc.Action == changeActionModify && rc.Replacement != "True": - statusOf[rc.LogicalID] = statusUpdateInProgress - default: - continue + if b.scheduleLocked(ctx, stack.StackID, op) { + return stack, nil } - - want = append(want, rc.LogicalID) } - var keys []string - - for _, id := range firstWave(tmpl.Resources, want, false) { - keys = append(keys, b.announceLocked(stack, statusOf[id], []string{id}, tmpl.Resources)...) - } + b.runUpdateStepLocked(ctx, stack, op) - return keys + return stack, nil } func (b *InMemoryBackend) completeUpdateLocked(stack *Stack) { @@ -983,10 +684,6 @@ func (b *InMemoryBackend) completeUpdateLocked(stack *Stack) { ) } -// applyTemplateToStack parses the stack's template and creates or updates -// resources. Returns true on success; on failure it sets the stack status -// and returns false. disableValidation/resourceTypes mirror UpdateStackInput's -// own DisableValidation/ResourceTypes fields (see StackOptions). // parseAndValidateUpdateTemplate parses stack.TemplateBody and runs every // pre-provisioning validation UpdateStack's own path requires (dynamic refs, // parameters, intrinsics unless disableValidation, ResourceTypes allowlist, @@ -995,8 +692,10 @@ func (b *InMemoryBackend) completeUpdateLocked(stack *Stack) { // convention). On failure it marks the stack failed/rolled-back itself and // returns a nil template. func (b *InMemoryBackend) parseAndValidateUpdateTemplate( - ctx context.Context, stack *Stack, disableValidation bool, resourceTypes []string, + ctx context.Context, stack *Stack, op *pendingStackOp, ) (*Template, map[string]string) { + disableValidation, resourceTypes := op.DisableValidation, op.ResourceTypes + tmpl, err := ParseTemplate(stack.TemplateBody) if err != nil { stack.StackStatus = statusUpdateFailed @@ -1025,7 +724,7 @@ func (b *InMemoryBackend) parseAndValidateUpdateTemplate( resolvedParams := ResolveParameters(tmpl, stack.Parameters) if valErr := ValidateParameters(tmpl, resolvedParams); valErr != nil { - b.updateFailAndRollback(ctx, stack, valErr.Error()) + b.updateFailAndRollback(ctx, stack, op, valErr.Error()) return nil, nil } @@ -1034,7 +733,7 @@ func (b *InMemoryBackend) parseAndValidateUpdateTemplate( // entirely when the caller set DisableValidation. if !disableValidation { if intErr := validateIntrinsics(tmpl); intErr != nil { - b.updateFailAndRollback(ctx, stack, intErr.Error()) + b.updateFailAndRollback(ctx, stack, op, intErr.Error()) return nil, nil } @@ -1044,14 +743,14 @@ func (b *InMemoryBackend) parseAndValidateUpdateTemplate( if !disableValidation { if propErr := b.validateProperties(tmpl); propErr != nil { - b.updateFailAndRollback(ctx, stack, propErr.Error()) + b.updateFailAndRollback(ctx, stack, op, propErr.Error()) return nil, nil } } if rtErr := validateResourceTypesAllowed(tmpl, resourceTypes); rtErr != nil { - b.updateFailAndRollback(ctx, stack, rtErr.Error()) + b.updateFailAndRollback(ctx, stack, op, rtErr.Error()) return nil, nil } @@ -1059,7 +758,7 @@ func (b *InMemoryBackend) parseAndValidateUpdateTemplate( // Validate that all Fn::ImportValue references can be satisfied before // updating any resources. if impErr := validateImportValues(tmpl, resolvedParams, b.buildExportsMap()); impErr != nil { - b.updateFailAndRollback(ctx, stack, impErr.Error()) + b.updateFailAndRollback(ctx, stack, op, impErr.Error()) return nil, nil } @@ -1067,149 +766,6 @@ func (b *InMemoryBackend) parseAndValidateUpdateTemplate( return tmpl, resolvedParams } -func (b *InMemoryBackend) applyTemplateToStack( - ctx context.Context, stack *Stack, ux updateOptions, oldTemplateBody string, oldParams []Parameter, -) bool { - if stack.TemplateBody == "" { - return true - } - - tmpl, resolvedParams := b.parseAndValidateUpdateTemplate(ctx, stack, ux.disableValidation, ux.resourceTypes) - if tmpl == nil { - return false - } - - // Pre-populate physicalIDs from existing resources. - physicalIDs := make(map[string]string, len(b.resources[stack.StackID])) - for logicalID, res := range b.resources[stack.StackID] { - physicalIDs[logicalID] = res.PhysicalID - } - - maps.Copy(physicalIDs, stack.ResourceAttrs) - - uc := newUpdateContext(oldTemplateBody, oldParams, physicalIDs) - uc.retainExceptOnCreate = ux.retainExceptOnCreate - - // Side channel for property-time Fn::GetAtt during update -- see the - // matching block in provisionResources and physIDResourceTypeKey. - physicalIDs[physIDAccountIDKey] = b.accountID - physicalIDs[physIDRegionKey] = b.region - physicalIDs[physIDStackNameKey] = stack.StackName - for logicalID, res := range tmpl.Resources { - physicalIDs[physIDResourceTypeKey(logicalID)] = res.Type - } - - // Validate that the update does not drop an export that another active - // stack still imports via Fn::ImportValue (computed against pre-update - // resource state, mirroring AWS's validate-before-apply semantics). - if expErr := b.validateExportsStillInUse(stack, tmpl, resolvedParams, physicalIDs); expErr != nil { - b.updateFailAndRollback(ctx, stack, expErr.Error()) - - return false - } - - if !b.updateResources(ctx, stack, tmpl, resolvedParams, physicalIDs, oldTemplateBody, uc) { - return false - } - - b.removeExports(stack.StackID) - - updateResourceTypes := make(map[string]string, len(tmpl.Resources)) - for logicalID, res := range tmpl.Resources { - updateResourceTypes[logicalID] = res.Type - } - stack.ResourceAttrs = extractAttrStash(physicalIDs, updateResourceTypes) - rctx := resolveCtx{ - params: resolvedParams, - physicalIDs: physicalIDs, - resourceTypes: updateResourceTypes, - exports: b.buildExportsMap(), - conditions: evaluateConditions(tmpl.Conditions, resolvedParams, physicalIDs), - mappings: tmpl.Mappings, - accountID: b.accountID, - region: b.region, - stackName: stack.StackName, - } - - var exportMap map[string]string - stack.Outputs, exportMap = resolveOutputsWithContext(tmpl, rctx) - - if regErr := b.registerExports(stack.StackID, exportMap); regErr != nil { - stack.StackStatus = statusUpdateFailed - stack.StackStatusReason = regErr.Error() - b.addEvent( - stack.StackID, stack.StackName, stack.StackName, stack.StackID, - cfnStackType, statusUpdateFailed, regErr.Error(), - ) - - return false - } - - return true -} - -// updateResources reconciles existing resources and creates newly declared ones. -// On creation failure it rolls back: newly-created resources are deleted and -// previously-existing resources are restored to their pre-update state. -// Stale resources (present in the stack but absent from the new template) are -// deleted after all new resources are created successfully. -// Returns true on success; on failure it sets stack.StackStatus to -// UPDATE_ROLLBACK_COMPLETE and returns false. -func (b *InMemoryBackend) updateResources( - ctx context.Context, - stack *Stack, - tmpl *Template, - resolvedParams map[string]string, - physicalIDs map[string]string, - oldTemplateBody string, - uc *updateContext, -) bool { - // Snapshot pre-update state for rollback. - prevResources := make(map[string]*StackResource, len(b.resources[stack.StackID])) - for k, v := range b.resources[stack.StackID] { - cp := *v - prevResources[k] = &cp - } - - ordered, ordErr := topoSortResources(tmpl.Resources) - if ordErr != nil { - b.updateFailAndRollback(ctx, stack, ordErr.Error()) - - return false - } - - pass := &updatePass{uc: uc, params: resolvedParams, phys: physicalIDs} - - for _, logicalID := range ordered { - if err := b.applyResourceUpdate(ctx, stack, tmpl.Resources[logicalID], logicalID, pass); err != nil { - stack.StackStatusReason = err.Error() - b.rollbackUpdateResources(ctx, stack, prevResources, pass.created, uc.retainExceptOnCreate) - - return false - } - } - - if !b.deleteStaleResources(ctx, stack, tmpl, oldTemplateBody) { - reason := "failed to delete one or more resources removed from the template" - stack.StackStatus = statusUpdateFailed - stack.StackStatusReason = reason - b.addEvent( - stack.StackID, stack.StackName, stack.StackName, stack.StackID, - cfnStackType, statusUpdateFailed, reason, - ) - - return false - } - - b.addEvent( - stack.StackID, stack.StackName, stack.StackName, stack.StackID, - cfnStackType, statusUpdateCleanupProgress, "", - ) - b.cleanupReplacedResources(ctx, stack, pass.replaced) - - return true -} - // createUpdateResource creates a new resource during a stack update and registers it. func (b *InMemoryBackend) createUpdateResource( ctx context.Context, @@ -1218,8 +774,6 @@ func (b *InMemoryBackend) createUpdateResource( res TemplateResource, resolvedParams, physicalIDs map[string]string, ) (string, error) { - b.addProgressEvent(stack.StackID, stack.StackName, logicalID, "", res.Type, statusCreateInProgress) - ctx = parentStackIDKey.Set(ctx, stack.StackID) physicalID, cerr := b.creator.Create( ctx, logicalID, @@ -1271,182 +825,6 @@ func (b *InMemoryBackend) createUpdateResource( return physicalID, nil } -// deleteStaleResources removes logical IDs present in the stack but absent -// from the new template. It reports whether every stale resource was -// actually deleted; a resource that fails to delete is left registered -// rather than dropped, so it stays visible via DescribeStackResources. -func (b *InMemoryBackend) deleteStaleResources( - ctx context.Context, stack *Stack, tmpl *Template, oldTemplateBody string, -) bool { - var stale []string - for logicalID := range b.resources[stack.StackID] { - if _, inTemplate := tmpl.Resources[logicalID]; !inTemplate { - stale = append(stale, logicalID) - } - } - - stale = reverseDependencyOrder(stale, oldTemplateBody) - - ok := true - physIDs := b.deleteResolveContext(stack) - - for _, logicalID := range stale { - res := b.resources[stack.StackID][logicalID] - b.addEvent( - stack.StackID, - stack.StackName, - logicalID, - res.PhysicalID, - res.Type, - statusDeleteInProgress, - "", - ) - if res.DeletionPolicy != deletionPolicyRetain && res.DeletionPolicy != deletionPolicySnapshot { - if delErr := b.creator.Delete(ctx, res.Type, res.PhysicalID, res.Properties, physIDs); delErr != nil { - ok = false - b.addEvent( - stack.StackID, stack.StackName, logicalID, res.PhysicalID, res.Type, - statusDeleteFailed, delErr.Error(), - ) - - continue - } - } - b.addEvent( - stack.StackID, - stack.StackName, - logicalID, - res.PhysicalID, - res.Type, - statusDeleteComplete, - "", - ) - delete(b.resources[stack.StackID], logicalID) - } - - return ok -} - -// rollbackUpdateResources undoes a partially-applied update: the stack goes -// UPDATE_ROLLBACK_IN_PROGRESS and, in this step or the next one when async, -// every resource the update newly created is deleted and modified resources -// are restored to their pre-update snapshots. -func (b *InMemoryBackend) rollbackUpdateResources( - ctx context.Context, - stack *Stack, - prevResources map[string]*StackResource, - created []string, - retainExceptOnCreate bool, -) { - b.beginUpdateRollbackLocked(ctx, stack, prevResources, created, stack.StackStatusReason, retainExceptOnCreate) -} - -func (b *InMemoryBackend) beginUpdateRollbackLocked( - ctx context.Context, - stack *Stack, - prevResources map[string]*StackResource, - created []string, - reason string, - retainExceptOnCreate bool, -) { - stack.StackStatus = statusUpdateRollbackInProgress - b.addEvent( - stack.StackID, stack.StackName, stack.StackName, stack.StackID, - cfnStackType, statusUpdateRollbackInProgress, reason, - ) - - op := &pendingStackOp{ - Kind: pendingRollbackUpdate, PrevResources: prevResources, Created: created, - RetainExceptOnCreate: retainExceptOnCreate, - } - - b.stageLocked(ctx, stack.StackID, op, func() { - b.runUpdateRollbackLocked(ctx, stack, prevResources, created, retainExceptOnCreate) - }) -} - -// runUpdateRollbackLocked ends in UPDATE_ROLLBACK_FAILED when a newly-created -// resource can't be deleted (it stays registered rather than being dropped), -// otherwise in UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS. -func (b *InMemoryBackend) runUpdateRollbackLocked( - ctx context.Context, - stack *Stack, - prevResources map[string]*StackResource, - created []string, - retainExceptOnCreate bool, -) { - rollbackOK := true - physIDs := b.deleteResolveContext(stack) - - for _, logicalID := range created { - res, exists := b.resources[stack.StackID][logicalID] - if !exists { - continue - } - - b.addEvent( - stack.StackID, stack.StackName, logicalID, res.PhysicalID, res.Type, statusDeleteInProgress, "", - ) - - keepsPolicy := res.DeletionPolicy == deletionPolicyRetain || res.DeletionPolicy == deletionPolicySnapshot - if keepsPolicy && !retainExceptOnCreate { - b.addEvent( - stack.StackID, stack.StackName, logicalID, res.PhysicalID, res.Type, statusDeleteComplete, "", - ) - delete(b.resources[stack.StackID], logicalID) - - continue - } - - if delErr := b.creator.Delete(ctx, res.Type, res.PhysicalID, res.Properties, physIDs); delErr != nil { - rollbackOK = false - b.addEvent( - stack.StackID, stack.StackName, logicalID, res.PhysicalID, res.Type, - statusDeleteFailed, delErr.Error(), - ) - - continue - } - - b.addEvent( - stack.StackID, stack.StackName, logicalID, res.PhysicalID, res.Type, statusDeleteComplete, "", - ) - delete(b.resources[stack.StackID], logicalID) - } - - maps.Copy(b.resources[stack.StackID], prevResources) - - if !rollbackOK { - reason := reasonRollbackDeleteFailed - stack.StackStatus = statusUpdateRollbackFailed - stack.StackStatusReason = reason - b.addEvent( - stack.StackID, stack.StackName, stack.StackName, stack.StackID, - cfnStackType, statusUpdateRollbackFailed, reason, - ) - - return - } - - stack.StackStatus = statusUpdateRollbackCleanup - b.addEvent( - stack.StackID, stack.StackName, stack.StackName, stack.StackID, - cfnStackType, statusUpdateRollbackCleanup, "", - ) - - b.stageLocked(ctx, stack.StackID, &pendingStackOp{Kind: pendingRollbackUpdateCleanup}, func() { - b.completeUpdateRollbackLocked(stack) - }) -} - -func (b *InMemoryBackend) completeUpdateRollbackLocked(stack *Stack) { - stack.StackStatus = statusUpdateRollbackComplete - b.addEvent( - stack.StackID, stack.StackName, stack.StackName, stack.StackID, - cfnStackType, statusUpdateRollbackComplete, "", - ) -} - // prepareUpdateLocked resolves the target stack and runs every synchronous // UpdateStack check; the returned params have UsePreviousValue resolved. func (b *InMemoryBackend) prepareUpdateLocked( diff --git a/services/cloudformation/store.go b/services/cloudformation/store.go index ec223b4403..66a4731880 100644 --- a/services/cloudformation/store.go +++ b/services/cloudformation/store.go @@ -65,7 +65,7 @@ type StorageBackend interface { GetTemplateSummary(templateBody, stackName string) (*TemplateSummary, error) EstimateTemplateCost(templateBody string, params []Parameter) (string, error) // Stack management - ContinueUpdateRollback(ctx context.Context, nameOrID string) error + ContinueUpdateRollback(ctx context.Context, nameOrID string, in ContinueRollbackInput) error CancelUpdateStack(ctx context.Context, nameOrID string) error DescribeAccountLimits() []AccountLimit // Stack Sets @@ -220,7 +220,8 @@ type InMemoryBackend struct { resourceDriftDetail map[string]map[string]StackResourceDrift driftByStackID map[string][]string pendingOps map[string]*pendingStackOp - announced map[string]struct{} + failedRollbacks map[string]*pendingStackOp + delayTimers map[uint64]*time.Timer settled chan struct{} provisionSchedule func(run func()) creator *ResourceCreator @@ -235,6 +236,7 @@ type InMemoryBackend struct { provisionWG sync.WaitGroup stackSetBatchDelay time.Duration provisionDelay time.Duration + timerSeq uint64 stepAsync bool orgAccessEnabled bool propertyChecksOff atomic.Bool @@ -289,33 +291,18 @@ func NewInMemoryBackendWithConfig( } b := &InMemoryBackend{ - registry: store.NewRegistry(), - quotaGate: "alimit.Gate{}, - stackIDIndex: make(map[string]string), - events: make(map[string][]StackEvent), - resources: make(map[string]map[string]*StackResource), - changeSets: make(map[string]map[string]*ChangeSet), - stackPolicies: make(map[string]string), - stackInstances: make(map[string][]StackInstance), - stackSetOperations: make(map[string]map[string]*StackSetOperation), - typeConfigs: make(map[string]string), - handlerProgress: make(map[string]string), - signals: make(map[string][]SignalRecord), - stackSetOpResults: make(map[string]map[string][]StackSetOperationResult), - typeVersions: make(map[string][]*RegisteredTypeVersion), - resourceScanItems: make(map[string][]ScannedResource), - resourceDriftStatus: make(map[string]map[string]string), - resourceDriftDetail: make(map[string]map[string]StackResourceDrift), - driftByStackID: make(map[string][]string), - pendingOps: make(map[string]*pendingStackOp), - settled: make(chan struct{}), - creator: creator, - resolver: resolver, - accountID: accountID, - region: region, - mu: lockmetrics.New("cloudformation"), + registry: store.NewRegistry(), + quotaGate: "alimit.Gate{}, + settled: make(chan struct{}), + delayTimers: make(map[uint64]*time.Timer), + creator: creator, + resolver: resolver, + accountID: accountID, + region: region, + mu: lockmetrics.New("cloudformation"), } + b.initState() registerAllTables(b) // Wire the backend as the NestedStackCreator so nested stacks can be provisioned. @@ -325,3 +312,25 @@ func NewInMemoryBackendWithConfig( return b } + +// initState gives the backend empty maps for everything not held in a registry table. +func (b *InMemoryBackend) initState() { + b.stackIDIndex = make(map[string]string) + b.events = make(map[string][]StackEvent) + b.resources = make(map[string]map[string]*StackResource) + b.changeSets = make(map[string]map[string]*ChangeSet) + b.stackPolicies = make(map[string]string) + b.stackInstances = make(map[string][]StackInstance) + b.stackSetOperations = make(map[string]map[string]*StackSetOperation) + b.typeConfigs = make(map[string]string) + b.handlerProgress = make(map[string]string) + b.signals = make(map[string][]SignalRecord) + b.stackSetOpResults = make(map[string]map[string][]StackSetOperationResult) + b.typeVersions = make(map[string][]*RegisteredTypeVersion) + b.resourceScanItems = make(map[string][]ScannedResource) + b.resourceDriftStatus = make(map[string]map[string]string) + b.resourceDriftDetail = make(map[string]map[string]StackResourceDrift) + b.driftByStackID = make(map[string][]string) + b.pendingOps = make(map[string]*pendingStackOp) + b.failedRollbacks = make(map[string]*pendingStackOp) +} diff --git a/services/cloudformation/store_direct_test.go b/services/cloudformation/store_direct_test.go index 74364d7246..e18c83c046 100644 --- a/services/cloudformation/store_direct_test.go +++ b/services/cloudformation/store_direct_test.go @@ -681,7 +681,7 @@ func TestContinueUpdateRollback_StackNotFound(t *testing.T) { t.Parallel() b := newBackend() - err := b.ContinueUpdateRollback(t.Context(), "no-such-stack") + err := b.ContinueUpdateRollback(t.Context(), "no-such-stack", cloudformation.ContinueRollbackInput{}) require.ErrorIs(t, err, cloudformation.ErrStackNotFound) } diff --git a/services/cloudformation/store_supplemental_test.go b/services/cloudformation/store_supplemental_test.go index 1b7cfee30e..4d4410b37f 100644 --- a/services/cloudformation/store_supplemental_test.go +++ b/services/cloudformation/store_supplemental_test.go @@ -421,24 +421,31 @@ func TestBackend_ContinueUpdateRollback(t *testing.T) { setup bool }{ { - name: "rollback_in_progress", + name: "rollback_failed_without_failed_resources", stackName: "my-stack", setup: true, - forceStatus: "ROLLBACK_IN_PROGRESS", - wantStatus: "ROLLBACK_COMPLETE", + forceStatus: "UPDATE_ROLLBACK_FAILED", + wantStatus: "UPDATE_ROLLBACK_COMPLETE", }, { name: "update_rollback_in_progress", stackName: "my-stack", setup: true, forceStatus: "UPDATE_ROLLBACK_IN_PROGRESS", - wantStatus: "UPDATE_ROLLBACK_COMPLETE", + wantErr: cloudformation.ErrContinueRollback, }, { - name: "no_op_when_create_complete", - stackName: "my-stack", - setup: true, - wantStatus: "CREATE_COMPLETE", + name: "create_rollback_failed", + stackName: "my-stack", + setup: true, + forceStatus: "ROLLBACK_FAILED", + wantErr: cloudformation.ErrContinueRollback, + }, + { + name: "create_complete", + stackName: "my-stack", + setup: true, + wantErr: cloudformation.ErrContinueRollback, }, { name: "stack_not_found", @@ -462,7 +469,7 @@ func TestBackend_ContinueUpdateRollback(t *testing.T) { b.ForceStackStatus(tt.stackName, tt.forceStatus) } - err := b.ContinueUpdateRollback(t.Context(), tt.stackName) + err := b.ContinueUpdateRollback(t.Context(), tt.stackName, cloudformation.ContinueRollbackInput{}) if tt.wantErr != nil { require.ErrorIs(t, err, tt.wantErr) @@ -472,11 +479,9 @@ func TestBackend_ContinueUpdateRollback(t *testing.T) { require.NoError(t, err) - if tt.wantStatus != "" { - stack, descErr := b.DescribeStack(tt.stackName) - require.NoError(t, descErr) - assert.Equal(t, tt.wantStatus, stack.StackStatus) - } + stack, descErr := b.DescribeStack(tt.stackName) + require.NoError(t, descErr) + assert.Equal(t, tt.wantStatus, stack.StackStatus) }) } } diff --git a/test/integration/cloudformation_ext_test.go b/test/integration/cloudformation_ext_test.go index 714dcf94ed..d1f7b58a95 100644 --- a/test/integration/cloudformation_ext_test.go +++ b/test/integration/cloudformation_ext_test.go @@ -200,11 +200,13 @@ func TestIntegration_CloudFormation_CancelUpdateRollback(t *testing.T) { require.ErrorAs(t, err, &apiErr) assert.Equal(t, "ValidationError", apiErr.ErrorCode()) - // ContinueUpdateRollback (no-op on CREATE_COMPLETE stack) + // ContinueUpdateRollback is only valid from UPDATE_ROLLBACK_FAILED _, err = client.ContinueUpdateRollback(ctx, &cloudformationsdk.ContinueUpdateRollbackInput{ StackName: aws.String(stackName), }) - require.NoError(t, err) + require.Error(t, err) + require.ErrorAs(t, err, &apiErr) + assert.Equal(t, "ValidationError", apiErr.ErrorCode()) // Cleanup _, err = client.DeleteStack(ctx, &cloudformationsdk.DeleteStackInput{StackName: aws.String(stackName)}) From 96dd073028d2ba8eb150c0d29425814acc77cca6 Mon Sep 17 00:00:00 2001 From: Witness Patrol Date: Sat, 21 Nov 2026 15:18:32 -0600 Subject: [PATCH 7/9] fix(cloudformation): deleting mid-update removes replaced resources, a failed wave cancels unstarted siblings, older in-flight snapshots resume fully Deleting a stack while an update was in flight left the old physical resources of replacements behind in their services. A failing resource did not stop the rest of its wave from being created. An in-flight operation saved before wave tracking only processed its announced wave on restore. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01NVwMjLknMM32Xje6Qik6wY --- services/cloudformation/PARITY.md | 7 +- services/cloudformation/stack_async.go | 2 +- services/cloudformation/stack_create_walk.go | 21 +- services/cloudformation/stack_delete.go | 77 +++++ .../cloudformation/stack_update_rollback.go | 4 + services/cloudformation/stack_update_walk.go | 19 +- services/cloudformation/stack_walk.go | 36 +++ .../cloudformation/stack_walk_cancel_test.go | 286 ++++++++++++++++++ 8 files changed, 432 insertions(+), 20 deletions(-) create mode 100644 services/cloudformation/stack_walk_cancel_test.go diff --git a/services/cloudformation/PARITY.md b/services/cloudformation/PARITY.md index df26351db3..cbadddc600 100644 --- a/services/cloudformation/PARITY.md +++ b/services/cloudformation/PARITY.md @@ -2727,18 +2727,19 @@ With a provisioning delay (or scheduler) every stack operation advances one depe - Create: a failed resource emits `CREATE_FAILED`, the stack enters `ROLLBACK_IN_PROGRESS` and only the resources already created are deleted, newest dependents first, one wave per step; DisableRollback, OnFailure DO_NOTHING/DELETE/ROLLBACK and RetainExceptOnCreate keep their previous semantics. - Update: changed and added resources go in dependency waves (unchanged ones take no step). `UPDATE_COMPLETE_CLEANUP_IN_PROGRESS` now covers the deletion of replaced physical resources (UpdateReplacePolicy honoured) and then of resources dropped from the template, one wave per step; outputs and exports are resolved after cleanup. A failed update rolls back newly created and replaced resources (deleted) and modified resources (reverted through the same in-place updater/extensibility update with the previous properties), and the stack template and parameters are restored. CancelUpdateStack takes effect between waves: announced-but-unstarted resources get `CREATE_FAILED`/`UPDATE_FAILED` "Resource creation/update cancelled" and the applied ones roll back. +- A failed wave cancels the members that had not started: they get `CREATE_FAILED`/`UPDATE_FAILED` "Resource creation/update cancelled" and are never created; siblings that completed earlier in the wave are rolled back with the rest. +- DeleteStack during an update (or its rollback / UPDATE_ROLLBACK_FAILED) also deletes the old physical resources of replacements that were not yet cleaned up or rolled back to; a failure there leaves the stack DELETE_FAILED, and a retry cannot retry that old resource. - Delete: reverse dependency waves; Retain gives `DELETE_SKIPPED`, failures leave `DELETE_FAILED` resources and stack for a retry. - UPDATE_ROLLBACK_FAILED: a resource that cannot be rolled back (restore or delete) ends `UPDATE_FAILED` with an `UPDATE_FAILED` event; the stack ends `UPDATE_ROLLBACK_FAILED` after the remaining resources were attempted. The rollback is kept in the additive `failedRollbacks` snapshot field. - ContinueUpdateRollback is valid only from `UPDATE_ROLLBACK_FAILED` (otherwise a ValidationError `Stack: is in state and can not be continue rolled back.`); ResourcesToSkip (only resources that failed to roll back; `NestedStackName.ResourceLogicalID` handled for embedded stacks, see items_still_open) and ForceRollback (all failed resources, mutually exclusive with ResourcesToSkip) mark resources `UPDATE_COMPLETE`, the rest is retried through `UPDATE_ROLLBACK_IN_PROGRESS` -> `UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS` -> `UPDATE_ROLLBACK_COMPLETE` or back to `UPDATE_ROLLBACK_FAILED`. RoleARN is validated and recorded like RollbackStack; ClientRequestToken is accepted and ignored like the sibling operations. -- Persistence: in-flight operations carry `physicalIds`, `inFlight`, `done`, `remaining`, `created`, `updated`, `replaced`, `failedReasons` and `phase` (additive fields). Restoring a snapshot taken mid-flight with no scheduler settles the operation inline to its final status; with a scheduler it resumes step by step from the persisted state. +- Persistence: in-flight operations carry `physicalIds`, `inFlight`, `done`, `remaining`, `created`, `updated`, `replaced`, `failedReasons` and `phase` (additive fields). Restoring a snapshot taken mid-flight with no scheduler settles the operation inline to its final status; with a scheduler it resumes step by step from the persisted state. An in-flight operation written before wave tracking (`announced` keys, no `remaining`/`templateBody`) is upgraded on resume: its delete/rollback work list is rebuilt from the stack's records (`TestWalk_RestoresSnapshotWrittenBeforeWaveTracking`). - Lifecycle: `Reset` clears every stack and cancels scheduled steps, `Close`/`Shutdown` cancels them (stacks stay in their in-progress status); the handler implements Resettable and Shutdowner including regional siblings. Tests: `stack_walk_test.go` (manual scheduler, `testing/synctest` for Close/Reset), `stack_transitions_test.go`. ## Emulator choices where the vendor is silent -- Event order inside a wave: every resource of a wave gets its in-progress event first, then each completes in logical-ID order; api_op_DescribeStackEvents.go and types.StackEvent only fix the fields and statuses, not the interleaving of parallel resources. Failures in a wave do not cancel the siblings of the wave, which still complete and are rolled back with the rest. +- Event order inside a wave: every resource of a wave gets its in-progress event first, then each completes in logical-ID order; api_op_DescribeStackEvents.go and types.StackEvent only fix the fields and statuses, not the interleaving of parallel resources. - Cancelled in-flight resources use the reasons "Resource creation cancelled" and "Resource update cancelled" (CloudFormation User Guide wording recalled from the console; not in the SDK). - ContinueUpdateRollback: types/errors.go and api_op_ContinueUpdateRollback.go define no stack-state error, so the invalid-state error is a ValidationError with the text recalled from the service; the texts for skipping resources that did not fail a rollback ("... cannot be skipped ...") and for ForceRollback with ResourcesToSkip ("... mutually exclusive.") are emulator wording (the doc comment only says the combination returns a validation error). A skipped resource keeps its current record with status UPDATE_COMPLETE and the event reason "Resource update skipped by ContinueUpdateRollback". - A resource whose delete fails during an update rollback is reported `UPDATE_FAILED` (not `DELETE_FAILED`), following the ContinueUpdateRollback doc comment that skippable resources are "in the UPDATE_FAILED state because a rollback failed". -- Deleting a stack while an update is in flight is accepted as before; resources replaced but not yet cleaned up are not deleted. diff --git a/services/cloudformation/stack_async.go b/services/cloudformation/stack_async.go index 5127f2ffbe..d1c7765551 100644 --- a/services/cloudformation/stack_async.go +++ b/services/cloudformation/stack_async.go @@ -218,7 +218,7 @@ func (b *InMemoryBackend) runPendingOpLocked(ctx context.Context, stackID string return } - op.legacyInFlight() + b.upgradeLegacyOp(stack, op) b.stepAsync = true diff --git a/services/cloudformation/stack_create_walk.go b/services/cloudformation/stack_create_walk.go index 293478d8d1..bb6514ee55 100644 --- a/services/cloudformation/stack_create_walk.go +++ b/services/cloudformation/stack_create_walk.go @@ -154,9 +154,8 @@ func (b *InMemoryBackend) createRemaining(op *pendingStackOp) []string { func (b *InMemoryBackend) executeCreateWave(ctx context.Context, stack *Stack, op *pendingStackOp) string { ids := sortedKeys(op.InFlight) op.InFlight = nil - reason := "" - for _, id := range ids { + for i, id := range ids { res, ok := op.rt.tmpl.Resources[id] if !ok { continue @@ -165,13 +164,10 @@ func (b *InMemoryBackend) executeCreateWave(ctx context.Context, stack *Stack, o physicalID, err := b.creator.Create(ctx, id, res.Type, res.Properties, op.rt.params, op.PhysicalIDs) if err != nil { b.addResourceEvent(stack, id, "", res.Type, statusCreateFailed, err.Error()) + stack.StackStatusReason = fmt.Sprintf("resource %s: %v", id, err) + b.cancelCreateSiblings(stack, op, ids[i+1:]) - if reason == "" { - reason = err.Error() - stack.StackStatusReason = fmt.Sprintf("resource %s: %v", id, err) - } - - continue + return err.Error() } b.addResourceEvent(stack, id, physicalID, res.Type, statusCreateInProgress, reasonCreationInitiated) @@ -185,7 +181,14 @@ func (b *InMemoryBackend) executeCreateWave(ctx context.Context, stack *Stack, o op.Created = append(op.Created, id) } - return reason + return "" +} + +// cancelCreateSiblings fails the wave members that had not started when a sibling failed. +func (b *InMemoryBackend) cancelCreateSiblings(stack *Stack, op *pendingStackOp, ids []string) { + for _, id := range ids { + b.addResourceEvent(stack, id, "", op.rt.tmpl.Resources[id].Type, statusCreateFailed, reasonCreateCancelled) + } } // finalizeCreateLocked resolves outputs and registers exports once every resource exists. diff --git a/services/cloudformation/stack_delete.go b/services/cloudformation/stack_delete.go index 7b588580c9..cad52ddde3 100644 --- a/services/cloudformation/stack_delete.go +++ b/services/cloudformation/stack_delete.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "slices" "strings" "time" ) @@ -68,6 +69,8 @@ func (b *InMemoryBackend) deleteStackWithLocked( return err } + superseded := b.supersededResourcesLocked(stack) + delete(b.pendingOps, stack.StackID) delete(b.failedRollbacks, stack.StackID) @@ -80,6 +83,8 @@ func (b *InMemoryBackend) deleteStackWithLocked( Remaining: sortedKeys(b.resources[stack.StackID]), TemplateBody: stack.TemplateBody, } + b.deleteSupersededLocked(ctx, stack, op, superseded) + if top && b.provisionSchedule != nil { b.announceReverseWave(stack, op, b.stackDeleteWalk(stack, op)) @@ -208,3 +213,75 @@ func (b *InMemoryBackend) finishDeleteLocked(stack *Stack) { b.pruneDriftDetections(stack.StackID) b.evictDeletedStacks() } + +// supersededResourcesLocked returns the old physical resources an in-flight update +// replaced and has not yet cleaned up or rolled back to: they are no longer in the +// stack's resource records but still exist. +func (b *InMemoryBackend) supersededResourcesLocked(stack *Stack) []*StackResource { + op := b.pendingOps[stack.StackID] + if op == nil { + op = b.failedRollbacks[stack.StackID] + } + + if op == nil { + return nil + } + + var out []*StackResource + + switch op.Kind { + case pendingUpdate, pendingUpdateCleanup: + if op.Kind == pendingUpdateCleanup && op.Phase != phaseReplaced { + return nil + } + + for _, r := range op.Replaced { + if op.Kind == pendingUpdateCleanup && !slices.Contains(op.Remaining, r.Old.LogicalID) && + op.InFlight[r.Old.LogicalID] == "" { + continue + } + + old := r.Old + old.DeletionPolicy = r.Policy + out = append(out, &old) + } + case pendingRollbackUpdate: + for _, id := range op.Created { + prev, cur := op.PrevResources[id], b.resources[stack.StackID][id] + if prev != nil && cur != nil && cur.PhysicalID != prev.PhysicalID { + old := *prev + out = append(out, &old) + } + } + } + + return out +} + +// deleteSupersededLocked deletes the superseded resources before the stack's own walk; +// a failure leaves the stack DELETE_FAILED. +func (b *InMemoryBackend) deleteSupersededLocked( + ctx context.Context, stack *Stack, op *pendingStackOp, olds []*StackResource, +) { + if len(olds) == 0 { + return + } + + physIDs := b.deleteResolveContext(stack) + rules := deleteRules{retainStatus: statusDeleteComplete, failStatus: statusDeleteFailed} + + for _, old := range olds { + b.addResourceEvent(stack, old.LogicalID, old.PhysicalID, old.Type, statusDeleteInProgress, "") + + status, reason := b.deleteOneResource(ctx, old, physIDs, old.LogicalID, rules) + b.addResourceEvent(stack, old.LogicalID, old.PhysicalID, old.Type, status, reason) + + if isFailedResourceStatus(status) { + if op.FailedReasons == nil { + op.FailedReasons = make(map[string]string) + } + + op.FailedReasons[old.LogicalID+" (previous physical resource)"] = reason + } + } +} diff --git a/services/cloudformation/stack_update_rollback.go b/services/cloudformation/stack_update_rollback.go index cb9396ff10..2597c8823b 100644 --- a/services/cloudformation/stack_update_rollback.go +++ b/services/cloudformation/stack_update_rollback.go @@ -164,6 +164,10 @@ func (b *InMemoryBackend) rollbackOne( return b.deleteOneResource(ctx, cur, physIDs, id, rules) } + if prev == nil { + return statusUpdateFailed, "no previous state recorded for " + id + } + var err error if isCFNExtensibilityType(prev.Type) { diff --git a/services/cloudformation/stack_update_walk.go b/services/cloudformation/stack_update_walk.go index 247e99491c..42215a8cfa 100644 --- a/services/cloudformation/stack_update_walk.go +++ b/services/cloudformation/stack_update_walk.go @@ -293,24 +293,29 @@ func (b *InMemoryBackend) executeUpdateWave( ctx context.Context, stack *Stack, op *pendingStackOp, pass *updatePass, ) string { ids := sortedKeys(op.InFlight) + announced := op.InFlight op.InFlight = nil - reason := "" - for _, id := range ids { + for i, id := range ids { res, ok := op.rt.tmpl.Resources[id] if !ok { continue } act, existing, _ := b.classifyUpdate(stack, id, res, pass) - if err := b.applyUpdateAction(ctx, stack, op, id, res, act, existing, pass); err != nil && reason == "" { - reason = err.Error() - } - op.Done = append(op.Done, id) + + if err := b.applyUpdateAction(ctx, stack, op, id, res, act, existing, pass); err != nil { + op.InFlight = make(map[string]string, len(ids)-i-1) + for _, rest := range ids[i+1:] { + op.InFlight[rest] = announced[rest] + } + + return err.Error() + } } - return reason + return "" } func (b *InMemoryBackend) applyUpdateAction( diff --git a/services/cloudformation/stack_walk.go b/services/cloudformation/stack_walk.go index 234f12b662..18e14f40e7 100644 --- a/services/cloudformation/stack_walk.go +++ b/services/cloudformation/stack_walk.go @@ -3,6 +3,7 @@ package cloudformation import ( "context" "maps" + "reflect" "slices" "sort" "strings" @@ -118,6 +119,41 @@ func appendUnique(list []string, id string) []string { return append(list, id) } +// upgradeLegacyOp fills in what a snapshot written before wave tracking lacks: the +// work each reverse walk still has to do and the phase of a cleanup settle. +func (b *InMemoryBackend) upgradeLegacyOp(stack *Stack, op *pendingStackOp) { + op.legacyInFlight() + + if op.Kind == pendingUpdateCleanup && op.Phase == "" && op.PhysicalIDs == nil { + op.Phase = phaseSettle + } + + if op.TemplateBody != "" || op.Remaining != nil { + return + } + + switch op.Kind { + case pendingDelete: + op.Remaining = sortedKeys(b.resources[stack.StackID]) + case pendingRollbackCreate: + op.Remaining = slices.Clone(op.Created) + case pendingRollbackUpdate: + op.Remaining = slices.Clone(op.Created) + + for _, id := range sortedKeys(op.PrevResources) { + cur, prev := b.resources[stack.StackID][id], op.PrevResources[id] + if cur != nil && !slices.Contains(op.Created, id) && !reflect.DeepEqual(cur.Properties, prev.Properties) { + op.Remaining = append(op.Remaining, id) + } + } + default: + return + } + + op.Remaining = without(op.Remaining, sortedKeys(op.InFlight)...) + op.TemplateBody = stack.TemplateBody +} + // legacyInFlight maps the keys of a snapshot written before in-flight tracking // ("logical|STATUS") onto the in-flight set. func (op *pendingStackOp) legacyInFlight() { diff --git a/services/cloudformation/stack_walk_cancel_test.go b/services/cloudformation/stack_walk_cancel_test.go new file mode 100644 index 0000000000..99e928bf8c --- /dev/null +++ b/services/cloudformation/stack_walk_cancel_test.go @@ -0,0 +1,286 @@ +package cloudformation_test + +import ( + jsonv2 "encoding/json/v2" + "sync/atomic" + "testing" + + "github.com/aws/aws-sdk-go-v2/aws" + cfnsdk "github.com/aws/aws-sdk-go-v2/service/cloudformation" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +const ( + siblingTemplate = `{"Resources":{"A":{"Type":"AWS::SNS::Topic"},` + + `"Q":{"Type":"AWS::SQS::Queue"},"Z":{"Type":"AWS::SNS::Topic"}}}` + siblingBase = `{"Resources":{"Base":{"Type":"AWS::SNS::Topic"}}}` + siblingUpdate = `{"Resources":{"Base":{"Type":"AWS::SNS::Topic"},"A":{"Type":"AWS::SNS::Topic"},` + + `"Q":{"Type":"AWS::SQS::Queue"},"Z":{"Type":"AWS::SNS::Topic"}}}` + + reasonCreateCancelledText = "Resource creation cancelled" +) + +func countTopics(e *transitionEnv) *atomic.Int32 { + var topics atomic.Int32 + + e.creator.InjectCreateHook(func(resourceType string) error { + switch resourceType { + case "AWS::SNS::Topic": + topics.Add(1) + case "AWS::SQS::Queue": + return errSimulatedCreate + } + + return nil + }) + + return &topics +} + +func TestWalk_FailedWaveCancelsUnstartedSiblings(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + final string + async bool + update bool + }{ + {name: "create sync", final: "ROLLBACK_COMPLETE"}, + {name: "create async", async: true, final: "ROLLBACK_COMPLETE"}, + {name: "update sync", update: true, final: "UPDATE_ROLLBACK_COMPLETE"}, + {name: "update async", update: true, async: true, final: "UPDATE_ROLLBACK_COMPLETE"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + e := newTransitionEnv(t) + + var id string + + if tt.update { + id = e.createSync(t, "sib", siblingBase) + } + + topics := countTopics(e) + + if tt.async { + e.schedule(t) + } + + if tt.update { + _, err := e.client.UpdateStack(t.Context(), &cfnsdk.UpdateStackInput{ + StackName: aws.String("sib"), TemplateBody: aws.String(siblingUpdate), + }) + require.NoError(t, err) + } else { + id = e.createSync(t, "sib", siblingTemplate) + } + + if tt.async { + e.drain(t) + } + + assert.Equal(t, tt.final, e.status(t, id)) + assert.Equal(t, int32(1), topics.Load(), "the sibling after the failed resource is never created") + + z := e.events(t, id, "Z") + require.NotEmpty(t, z) + assert.Equal(t, "CREATE_FAILED|"+reasonCreateCancelledText, z[len(z)-1]) + assert.NotContains(t, e.statuses(t, id, "Z"), "CREATE_COMPLETE") + + q := e.events(t, id, "Q") + assert.Contains(t, q[len(q)-1], "CREATE_FAILED|"+errSimulatedCreate.Error()) + assert.Contains(t, e.statuses(t, id, "A"), "DELETE_COMPLETE", "completed siblings are rolled back") + }) + } +} + +func TestWalk_DeleteDuringUpdateRemovesReplacedResources(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + steps int + }{ + {name: "replacement applied", steps: 1}, + {name: "mid cleanup", steps: 2}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + e := newTransitionEnv(t) + id := e.createSync(t, "repl", replaceV1) + e.schedule(t) + + var buckets atomic.Int32 + + e.creator.InjectDeleteHook(func(resourceType string) { + if resourceType == "AWS::S3::Bucket" { + buckets.Add(1) + } + }) + + _, err := e.client.UpdateStack(t.Context(), &cfnsdk.UpdateStackInput{ + StackName: aws.String("repl"), TemplateBody: aws.String(replaceV2), + }) + require.NoError(t, err) + + for range tt.steps { + e.sched.runNext(t) + } + + require.Equal(t, "UPDATE_COMPLETE_CLEANUP_IN_PROGRESS", e.status(t, id)) + + cleaned := buckets.Load() + + require.NoError(t, e.deleteStack(t, "repl")) + e.drain(t) + + assert.Equal(t, "DELETE_COMPLETE", e.status(t, id)) + assert.Equal(t, int32(2), buckets.Load(), "old and new buckets are both deleted (%d before)", cleaned) + }) + } +} + +// legacyOps rewrites the in-flight operations of a snapshot into the shape written before +// wave tracking: no remaining work, template or in-flight set, only "announced" keys. +func legacyOps(t *testing.T, snap []byte) []byte { + t.Helper() + + var doc map[string]any + + require.NoError(t, jsonv2.Unmarshal(snap, &doc)) + + ops, ok := doc["pendingStackOps"].(map[string]any) + require.True(t, ok, "snapshot carries an in-flight operation") + + for _, v := range ops { + op, isMap := v.(map[string]any) + require.True(t, isMap) + + if inFlight, has := op["inFlight"].(map[string]any); has { + keys := make([]any, 0, len(inFlight)) + + for id, status := range inFlight { + keys = append(keys, id+"|"+status.(string)) + } + + op["announced"] = keys + } + + for _, k := range []string{"inFlight", "remaining", "templateBody", "physicalIds", "done"} { + delete(op, k) + } + } + + out, err := jsonv2.Marshal(doc) + require.NoError(t, err) + + return out +} + +func TestWalk_RestoresSnapshotWrittenBeforeWaveTracking(t *testing.T) { + t.Parallel() + + tests := []struct { + start func(t *testing.T, e *transitionEnv) string + name string + wantStatus string + wantTopics int32 + }{ + { + name: "delete", + start: func(t *testing.T, e *transitionEnv) string { + t.Helper() + + id := e.createSync(t, "old-delete", waveTemplate) + e.schedule(t) + require.NoError(t, e.deleteStack(t, "old-delete")) + + return id + }, + wantStatus: "DELETE_COMPLETE", + wantTopics: 3, + }, + { + name: "create rollback", + start: func(t *testing.T, e *transitionEnv) string { + t.Helper() + + e.failQueues(nil) + e.schedule(t) + + out, err := e.client.CreateStack(t.Context(), &cfnsdk.CreateStackInput{ + StackName: aws.String("old-rollback"), TemplateBody: aws.String(middleFailTemplate), + }) + require.NoError(t, err) + + for range 3 { + e.sched.runNext(t) + } + + return aws.ToString(out.StackId) + }, + wantStatus: "ROLLBACK_COMPLETE", + wantTopics: 2, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + src := newTransitionEnv(t) + id := tt.start(t, src) + require.Contains(t, src.status(t, id), "_IN_PROGRESS") + + snap := legacyOps(t, src.backend.Snapshot(t.Context())) + src.backend.SetProvisioningScheduler(nil) + + var topics atomic.Int32 + + src.creator.InjectDeleteHook(func(resourceType string) { + if resourceType == "AWS::SNS::Topic" { + topics.Add(1) + } + }) + + require.NoError(t, src.backend.Restore(t.Context(), snap)) + + assert.Equal(t, tt.wantStatus, src.status(t, id)) + assert.Equal(t, tt.wantTopics, topics.Load(), "every created resource is deleted") + }) + } +} + +func TestWalk_SnapshotCarriesNoRuntimeCache(t *testing.T) { + t.Parallel() + + e := newTransitionEnv(t) + e.schedule(t) + + _, err := e.client.CreateStack(t.Context(), &cfnsdk.CreateStackInput{ + StackName: aws.String("rt"), TemplateBody: aws.String(waveTemplate), + }) + require.NoError(t, err) + e.sched.runNext(t) + + var doc struct { + Ops map[string]map[string]any `json:"pendingStackOps"` + } + + require.NoError(t, jsonv2.Unmarshal(e.backend.Snapshot(t.Context()), &doc)) + require.Len(t, doc.Ops, 1) + + for _, op := range doc.Ops { + for _, key := range []string{"rt", "tmpl", "uc", "params"} { + assert.NotContains(t, op, key) + } + } +} From ca97a0b2b170ca8e90fbda82d862fcfbc9d36918 Mon Sep 17 00:00:00 2001 From: Witness Patrol Date: Sat, 21 Nov 2026 15:49:52 -0600 Subject: [PATCH 8/9] docs: regenerate service READMEs Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01NVwMjLknMM32Xje6Qik6wY --- README.md | 4 ++-- services/cloudformation/README.md | 2 +- services/connect/README.md | 5 ++--- services/ecs/README.md | 2 +- services/gcpbigquery/README.md | 4 ++-- services/gcpsecretmanager/README.md | 6 +----- 6 files changed, 9 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index 0a22fbb680..b614d349b0 100644 --- a/README.md +++ b/README.md @@ -980,7 +980,7 @@ Every service links to its own page with a coverage breakdown — audited operat | [Google Cloud Pub/Sub](services/gcppubsub/README.md) | B | 38 | 3 gaps | | [Google Cloud Resource Manager and Service Usage](services/gcpresourcemanager/README.md) | B | 39 | 3 gaps | | [Google Cloud Storage](services/gcpstorage/README.md) | B | 39 | 4 gaps | -| [Google Secret Manager](services/gcpsecretmanager/README.md) | B | 18 | 1 gap | +| [Google Secret Manager](services/gcpsecretmanager/README.md) | B | 18 | clean | | [Identity Platform](services/gcpidentitytoolkit/README.md) | B | 1 | clean | | [Kubernetes Engine](services/gcpcontainer/README.md) | B | — | 5 families; 4 gaps | | [Memorystore for Redis](services/gcpredis/README.md) | B | 14 | 3 gaps | @@ -1028,7 +1028,7 @@ Every service links to its own page with a coverage breakdown — audited operat | [Cloudfrontkeyvaluestore](services/cloudfrontkeyvaluestore/README.md) | A | 6 | 2 structural gaps | | [Cloudhsmv2](services/cloudhsmv2/README.md) | B | 18 | 3 structural gaps | | [Codegurureviewer](services/codegurureviewer/README.md) | B | 14 | 2 structural gaps | -| [Connect](services/connect/README.md) | B | 397 | 9 gaps; 2 structural gaps | +| [Connect](services/connect/README.md) | B | 397 | 8 gaps; 2 structural gaps | | [Cur](services/cur/README.md) | B | 7 | clean | | [Directconnect](services/directconnect/README.md) | A | 73 | 8 structural gaps; 1 deferred | | [Dsql](services/dsql/README.md) | A | 16 | 7 gaps; 2 structural gaps | diff --git a/services/cloudformation/README.md b/services/cloudformation/README.md index 0ff25dfd4c..1ca1db33e0 100644 --- a/services/cloudformation/README.md +++ b/services/cloudformation/README.md @@ -17,7 +17,7 @@ ### Known gaps - Resource-type strictness is by service namespace only: an AWS::Svc::Res whose Svc is unknown to the spec fixture and the provisioner fails with "Template format error: Unrecognized resource types: [X]" (cfn_resource_services.json, generated by cmd/cfnattrgen), but an unmodelled resource of a known service still falls through to the stub path because the committed spec fixture lists types with attributes only. Property schemas are checked only at the primitive level (nested property types are not walked) and the resource spec marks required keys per legacy spec, so registry-only conditional requirements are not modeled; Rules AWS-specific parameter types resolve only for AWS::EC2::VPC/Subnet/SecurityGroup::Id (Fn::RefAll/ValueOf/ValueOfAll attributes per the Rule functions page: DefaultNetworkAcl, DefaultSecurityGroup, AvailabilityZone, VpcId, Tags.); other AWS-specific types yield empty lists. The Parameter-constraint, Rules-assertion and Unrecognized-parameter-type wordings are best-effort recollections of CloudFormation text, not SDK-verifiable. -- Async stack provisioning (default 300ms per step; --cloudformation-provisioning-delay / GOPHERSTACK_CFN_PROVISIONING_DELAY, 0 = instant; a bare NewInMemoryBackend stays synchronous) models whole-stack transitions, not per-resource timing: inside a step every resource is created (or deleted) at once, so only the first wave of CREATE/UPDATE/DELETE_IN_PROGRESS events is visible during the window, replaced resources are cleaned up in the first UPDATE step rather than during UPDATE_COMPLETE_CLEANUP_IN_PROGRESS, nested stacks are provisioned eagerly and merely settle on later steps, and StackSet instance child stacks are provisioned inside the unit (their StackInstanceStatus window is per batch). Update rollback does not model UPDATE_ROLLBACK_FAILED retry through ContinueUpdateRollback, and the RetainResources/DeletionMode validation wording is a best-effort recollection. +- Async provisioning of nested stacks and StackSet instances is not per resource: a nested AWS::CloudFormation::Stack is provisioned and deleted at once inside the parent's step and only settles on later steps (the parent resource fails with "Embedded stack was not successfully created" from that eager run), and StackSet instance child stacks are provisioned inside the unit (their StackInstanceStatus window is per batch). ContinueUpdateRollback accepts the NestedStackName.ResourceLogicalID skip form only for an embedded stack of the target stack that is itself UPDATE_ROLLBACK_FAILED; nested-stack updates are not modelled, so no embedded stack can reach that state. The RetainResources/DeletionMode validation wording is a best-effort recollection. - Stack policy: Replacement Conditionally is treated as Update:Replace (deliberate, not an AWS-documented rule), and AWS's separate logical-ID/resource-type default-deny note is not modeled; NotAction/NotResource follow plain inversion (gopherstack-cqy3). - No nested-stack change-set or public-extension version machinery exists, so these stay unmodeled: CreateChangeSet IncludeNestedStacks (no nested-stack diff machinery) and the effect of ActivateType MajorVersion/VersionBump (validated for range, enum and exclusivity, but there is no public extension version catalog to select or bump a version in) (gopherstack-xhu2t). - SAM transform (AWS::Serverless-2016-10-31) still unexpanded: AWS::Serverless::CapacityProvider, NetworkConnector, MicrovmImage and WebFunction (their AWS::Lambda::* target types are not modelled by the stack engine); Application with a Serverless Application Repository Location (ApplicationId + SemanticVersion; use CreateCloudFormationTemplate and a URL Location); the translator's opt-in passthrough_metadata mode; HttpApi events that target an AWS::Serverless::Api; a user resource named ServerlessRestApi being replaced by the implicit API. Expanded but not provisioned by the stack engine: AWS::ApiGateway::DomainNameV2, BasePathMappingV2 and DomainNameAccessAssociation (PRIVATE REST custom domains) and AWS::AppSync::ApiCache and DomainNameApiAssociation (GraphQLApi Cache and DomainName) fail the stack as unsupported resource types. Unsupported SAM resources fail the stack/change set with an explicit reason, never silently dropped. diff --git a/services/connect/README.md b/services/connect/README.md index 3364b2ea1a..2133e0723e 100644 --- a/services/connect/README.md +++ b/services/connect/README.md @@ -8,7 +8,7 @@ | Metric | Value | | --- | --- | | PARITY entries audited | 397 (397 ok) | -| Known gaps | 9 | +| Known gaps | 8 | | Structural gaps (can't be emulated) | 2 | | Deferred items | 0 | | Resource leaks | clean | @@ -18,11 +18,10 @@ - EvaluationForms: contact evaluations are never auto-evaluated (no AI or Contact Lens answers) and the Acknowledgement, Review and CalibrationSessionId metadata members are never set because the pinned SDK has no operation that changes them; POINTS_BASED scoring ignores per-question PointsConfiguration (bonus, min/max points) and the weighted-score formulas are unverified against the real service - TestCases: executions are recorded (Start/Stop/List/ListRecords/GetSummary) but never leave INITIATED on their own, because the emulator has no flow test runner: no PASSED/FAILED outcome, observations or ObservationSummary are ever produced (the test case Content grammar is not published, API_CreateTestCase only calls it a JSON string, and the VOICE_CALL and CHAT entry points need a media plane to drive a flow) - Notifications: push registrations are stored but no push is ever sent (nothing triggers one: there is no chat message plane); notifications from rules or the system are not generated -- AttachedFiles: Cases are not modeled so Cases ARNs are only shape-checked; without the S3 emulator wired the content endpoint /attached-files-content stands in for S3 pre-signed URLs - Contact data and participants: GetFederationToken ListRealtimeContactAnalysisSegmentsV2 SendChatIntegrationEvent UpdateParticipantAuthentication StartAssistantContact StartScreenSharing StartWebRTCContact are not routed (no chat message plane, no caller identity for federation, no Wisdom assistant, no WebRTC media plane); UpdateParticipantRoleConfig timers are stored on the contact but nothing enforces them (no chat message plane); QueuePriority and QueueTimeAdjustmentSeconds order GetContactMetrics queue positions but no routing engine assigns agents from that order, and RoutingCriteria steps are only stored - GetMetricDataV2: only the computed subset of metrics is available (agent-state, hold, after-contact-work, flow, campaign, evaluation, case, AI and Contact Lens metrics need signals the emulator never records), so custom metrics built on them are rejected - PhoneNumber import: ImportPhoneNumber needs an AWS End User Messaging (pinpoint-sms-voice-v2) phone-number inventory; the emulator has no such service and none may be added, so a number could only be fabricated -- SES-wired email delivery status readback and TEMPLATE outbound email (Wisdom message templates) are not modeled +- TEMPLATE outbound email (Wisdom message templates) is not modeled, so SendOutboundEmail and StartOutboundEmailContact accept RAW messages only - CloudFormation: AWS::Connect::Metric GetAtt Filters, Groupings, PrimaryEventSource, PrimaryEventSourceEffectiveTimestampType, RefreshRate and SupportedStats are not returned: the CloudFormation reference (aws-resource-connect-metric.html) names them without a value format or derivation, and the stored MetricDefinition (services/connect/metricdefs.go MetricDefinition) has no PrimaryEventSource, RefreshRate or SupportedStats; SourcePhoneNumberArn of PhoneNumber is rejected because it needs an imported number (ImportPhoneNumber item) and ClaimPhoneNumber has no source member (SDK ClaimPhoneNumberInput) ### Structural gaps diff --git a/services/ecs/README.md b/services/ecs/README.md index a8fb62c84a..b063adf4ff 100644 --- a/services/ecs/README.md +++ b/services/ecs/README.md @@ -18,7 +18,7 @@ - Docker runtime container definition: firelensConfiguration and awsfirelens log routing (a task using either fails with TaskFailedToStart instead of starting the log router) and resourceRequirements (GPU) are stored but not applied; ephemeralStorage is validated (21 to 200 GiB) and reported on the task but not enforced on disk. - Docker runtime: Task-level cpu/memory bound every container (a container without a hard memory limit gets the task memory as its ceiling, NanoCPUs is the task vCPUs) but Docker has no task cgroup, so the sum across containers is not enforced at run time (registration rejects sums above the task values). host and none network-mode containers cannot join the link-local credentials relay, and awsvpc tasks (pause container plus task network) are never adopted after an emulator restart. Managed EBS volumes: filesystemType is not applied (the Docker volume uses the local driver), volumeInitializationRate is echo only, and StartTask and ServiceRevision do not carry volumeConfigurations. -- ECS Exec: sessions exist only on the docker and kubernetes runtimes with the SSM service enabled (otherwise TargetNotConnectedException); the command runs as `sh -c ` through docker exec or pods/exec, and the ssmmessages IAM checks are not applied. executeCommandConfiguration logging is delivered when the session ends (CloudWatch Logs stream `ecs-execute-command-`, S3 key `/ecs-execute-command-.log`; naming from memory, unverified); KMS encryption is recorded, not performed (see External effects). +- ECS Exec: sessions exist only on the docker and kubernetes runtimes with the SSM service enabled (otherwise TargetNotConnectedException); the command runs as `sh -c ` through docker exec or pods/exec, and the ssmmessages IAM checks are not applied. executeCommandConfiguration logging is delivered when the session ends; KMS encryption is recorded, not performed (see External effects). - Kubernetes runtime (CONTAINER_RUNTIME=kubernetes, docs/kubernetes.md): one Pod per task. Refused with TaskFailedToStart: host-path/EFS/configuredAtLaunch/shared-docker volumes, networkMode host/none, pidMode/ipcMode host, privileged, devices, container restartPolicy, repositoryCredentials, FireLens, dependsOn COMPLETE/HEALTHY; ulimits/ephemeralStorage ignored; dependsOn START is not ordered; a never-ready health check stays UNKNOWN; no security-group enforcement; tasks are not adopted after a restart. ### Structural gaps diff --git a/services/gcpbigquery/README.md b/services/gcpbigquery/README.md index cc911294f0..c3e32bc5a5 100644 --- a/services/gcpbigquery/README.md +++ b/services/gcpbigquery/README.md @@ -18,8 +18,8 @@ - Not served: models, table and dataset IAM policies (including row access policy IAM), datasets undelete, snapshots/clones as storage objects, BigLake tables and connections, data transfers, analytics hub, reservation groups, reservation failover and reservation IAM, and the Storage Read/Write gRPC APIs. - Unsupported GoogleSQL: CAST ... FORMAT between numeric or BYTES types and STRING (date and time types are supported, with AT TIME ZONE), EXPORT DATA, JavaScript, Python and remote UDFs and CREATE AGGREGATE FUNCTION, wildcard tables (_TABLE_SUFFIX), partition pseudo columns (_PARTITIONTIME and _PARTITIONDATE need a per-row ingestion time that rows do not carry; DML rewrites whole row slices in jobs_query.go effectWrite), selecting a whole row as a STRUCT, legacy SQL. - Unsupported functions: RANGE values, ML.*, GEOGRAPHY beyond the implemented ST_* set (use_spheroid => TRUE, make_valid => TRUE, ST_UNION, ST_BUFFER and the other constructors and aggregates), SEARCH over a table reference or a tuple, JSON constructors and mutators beyond JSON_VALUE/JSON_QUERY/PARSE_JSON/TO_JSON_STRING, FORMAT patterns beyond %s %d %i %f %g %e %t %T %x %o, collation. -- ST_MAKELINE concatenates vertices and does not node overlapping or backtracking edges, so the documented MULTILINESTRING result for retraced segments is not reproduced. -- SEARCH: the documented example where a phrase containing AND/OR matches plain terms is not reproduced. +- ST_MAKELINE does not snap sufficiently short edges together (geography_functions ST_MAKELINE constraints; snap radius not stated there). Overlap detection of edges beyond the first 1024 only collapses repeated identical edges, and detection off the equator and meridians uses a floating-point tolerance, not an exact predicate. The error text for an edge of 180 degrees or more is emulator wording. +- SEARCH NO_OP_ANALYZER: the page's example SEARCH(R'"foo bar"', R'"foo Bar"', analyzer=>'NO_OP_ANALYZER') is TRUE with the comment 'analysis is case-insensitive', while its 'Foobar' vs 'foobar' example is FALSE; the emulator keeps NO_OP case-sensitive and returns FALSE for the first. SEARCH also reads upper-case AND/OR inside a double-quoted phrase as logical operators (the page's SEARCH(R'foo bar', R'"foo AND (bar OR baz)"') is TRUE, commented as a logical match); the rule for phrases that really contain those words is not documented, so 'Clyde and Bonnie' matches the query "Bonnie AND Clyde". - Engine fidelity: NUMERIC and BIGNUMERIC are computed in float64, so values past 15 significant digits lose precision. - Jobs: no slot or priority scheduling, no query cache, anonymous result tables are not created, script expression evaluations are not recorded as EXPRESSION child jobs, and execution holds the backend write lock (jobs_async.go runLocked), so jobs.cancel and jobTimeoutMs stop a job before it executes and a script between statements, not a plain statement in flight. - Load: Datastore and Firestore backups, nested CSV and column-name flexibility options are not supported. External tables: GOOGLE_SHEETS, DATASTORE_BACKUP, BIGTABLE and DELTA_LAKE sources and WITH CONNECTION need services the emulator does not have. External tables and CREATE EXTERNAL TABLE read Cloud Storage while the backend lock is held (external.go readExternalRows). The NDJSON TIMESTAMP and CSV float rendering of extract have not been checked against the live service. diff --git a/services/gcpsecretmanager/README.md b/services/gcpsecretmanager/README.md index 5dafdca853..859970f4da 100644 --- a/services/gcpsecretmanager/README.md +++ b/services/gcpsecretmanager/README.md @@ -9,14 +9,10 @@ | --- | --- | | PARITY entries audited | 18 (18 ok) | | Feature families | 6 (4 ok, 2 partial) | -| Known gaps | 1 | +| Known gaps | none | | Deferred items | 0 | | Resource leaks | clean | -### Known gaps - -- Regional secret location names are not validated against Secret Manager's supported-region list: no verified catalog exists in the repo and rejecting a valid region would break working clients. - ## More - [Full parity audit](PARITY.md) From 6a8fcf86b8183dec9afc474e43ed742b6b81ce73 Mon Sep 17 00:00:00 2001 From: Witness Patrol Date: Sat, 21 Nov 2026 16:58:30 -0600 Subject: [PATCH 9/9] test: private transports for Cognito test clients; the helm install test waits for the service to be routable The Cognito test clients ran on the default transport, and every test server's Close drops that transport's idle connections, so one test's teardown could break another's request. The helm test made a single request through the node port as soon as the deployment was ready; it now waits for a ready endpoint and a successful request, fails at once on a container restart and logs pod state, logs and events on failure. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01NVwMjLknMM32Xje6Qik6wY --- services/cognitoidp/localstack_alias_test.go | 6 +- services/cognitoidp/oauth_helpers_test.go | 4 +- services/cognitoidp/saml_federation_test.go | 6 +- test/helm/install_test.go | 185 ++++++++++++++++++- 4 files changed, 186 insertions(+), 15 deletions(-) diff --git a/services/cognitoidp/localstack_alias_test.go b/services/cognitoidp/localstack_alias_test.go index f19d41b049..eeef9ac03a 100644 --- a/services/cognitoidp/localstack_alias_test.go +++ b/services/cognitoidp/localstack_alias_test.go @@ -19,6 +19,7 @@ import ( "github.com/stretchr/testify/require" "github.com/blackbirdworks/gopherstack/pkgs/service" + "github.com/blackbirdworks/gopherstack/pkgs/testclient" "github.com/blackbirdworks/gopherstack/services/cognitoidp" ) @@ -85,9 +86,8 @@ func TestLocalStackAlias_AuthCodeFlowWithPinnedIDs(t *testing.T) { jar, err := cookiejar.New(nil) require.NoError(t, err) - hc := &http.Client{Jar: jar, CheckRedirect: func(*http.Request, []*http.Request) error { - return http.ErrUseLastResponse - }} + hc := &http.Client{Transport: testclient.New(t).Transport, Jar: jar, + CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} q := url.Values{ "response_type": {"code"}, "client_id": {"myclient123"}, "redirect_uri": {oauthRedirect}, "state": {"st8"}, diff --git a/services/cognitoidp/oauth_helpers_test.go b/services/cognitoidp/oauth_helpers_test.go index 4189694c51..5526f82787 100644 --- a/services/cognitoidp/oauth_helpers_test.go +++ b/services/cognitoidp/oauth_helpers_test.go @@ -19,6 +19,7 @@ import ( "github.com/stretchr/testify/require" "github.com/blackbirdworks/gopherstack/pkgs/jsonx" + "github.com/blackbirdworks/gopherstack/pkgs/testclient" "github.com/blackbirdworks/gopherstack/services/cognitoidp" ) @@ -71,7 +72,8 @@ func newOAuthEnvWith(t *testing.T, opts cognitoidp.UserPoolOptions, inv cognitoi require.NoError(t, err) env := &oauthEnv{backend: b, handler: h, srv: srv, client: &http.Client{ - Jar: jar, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, + Transport: testclient.New(t).Transport, Jar: jar, + CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, }} pool, err := b.CreateUserPoolWithOpts("oauth-pool", opts) diff --git a/services/cognitoidp/saml_federation_test.go b/services/cognitoidp/saml_federation_test.go index 9b74116cda..3f09ffc13b 100644 --- a/services/cognitoidp/saml_federation_test.go +++ b/services/cognitoidp/saml_federation_test.go @@ -26,6 +26,7 @@ import ( "github.com/stretchr/testify/require" "github.com/blackbirdworks/gopherstack/pkgs/jsonx" + "github.com/blackbirdworks/gopherstack/pkgs/testclient" "github.com/blackbirdworks/gopherstack/services/cognitoidp" ) @@ -568,7 +569,10 @@ func bindingCookie(resp *http.Response) *http.Cookie { func bareDo(t *testing.T, req *http.Request) *http.Response { t.Helper() - c := &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} + c := &http.Client{ + Transport: testclient.New(t).Transport, + CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, + } resp, err := c.Do(req) require.NoError(t, err) diff --git a/test/helm/install_test.go b/test/helm/install_test.go index 1a58b6e215..0d0b89bfcc 100644 --- a/test/helm/install_test.go +++ b/test/helm/install_test.go @@ -1,9 +1,9 @@ package helm_test import ( + "github.com/blackbirdworks/gopherstack/pkgs/httpclient" "github.com/blackbirdworks/gopherstack/pkgs/jsonx" "github.com/blackbirdworks/gopherstack/pkgs/portalloc/portalloctest" - "github.com/blackbirdworks/gopherstack/pkgs/testclient" "bytes" "context" @@ -45,7 +45,10 @@ const ( nonRootUID = 65532 ) -var errNotReady = errors.New("not ready") +var ( + errNotReady = errors.New("not ready") + errFatal = errors.New("fatal") +) type k8sAPI struct { client *http.Client @@ -87,6 +90,10 @@ func until(ctx context.Context, what string, fn func() (bool, error)) error { return nil } + if errors.Is(err, errFatal) { + return fmt.Errorf("%s: %w", what, err) + } + last = err select { @@ -325,8 +332,12 @@ func TestChart_InstallK3s(t *testing.T) { require.NoError(t, api.podRunsNonRoot(ctx)) + t.Cleanup(func() { api.dumpDiagnostics(t) }) + base := "http://127.0.0.1:" + strconv.Itoa(inst.LBHost[0]) - assertHealthy(ctx, t, base) + require.NoError(t, until(ctx, "service routable", func() (bool, error) { + return api.serviceRoutable(ctx, base) + })) s3c := newS3(ctx, t, base) bucket := "helm-" + uuid.NewString()[:8] @@ -354,18 +365,172 @@ func TestChart_InstallK3s(t *testing.T) { })) } -func assertHealthy(ctx context.Context, t *testing.T, base string) { - t.Helper() +// serviceRoutable is true once the Service has a ready endpoint and a health GET through the node port succeeds. +// A restarted pod is fatal; connection errors mean the node port is not programmed yet. +func (k *k8sAPI) serviceRoutable(ctx context.Context, base string) (bool, error) { + if err := k.noRestarts(ctx); err != nil { + return false, err + } - req, err := http.NewRequestWithContext(ctx, http.MethodGet, base+"/_gopherstack/health", nil) - require.NoError(t, err) + code, body, err := k.do(ctx, http.MethodGet, + "/apis/discovery.k8s.io/v1/namespaces/"+namespace+ + "/endpointslices?labelSelector=kubernetes.io/service-name%3D"+releaseName+"-gopherstack") + if err != nil { + return false, err + } - resp, err := testclient.New(t).Do(req) - require.NoError(t, err) + if code != http.StatusOK { + return false, fmt.Errorf("%w: endpointslices returned %d", errNotReady, code) + } + + var l struct { + Items []struct { + Endpoints []struct { + Conditions struct { + Ready *bool `json:"ready"` + } `json:"conditions"` + } `json:"endpoints"` + } `json:"items"` + } + if err = json.Unmarshal(body, &l, jsonx.V1()); err != nil { + return false, err + } + + ready := false + + for _, it := range l.Items { + for _, ep := range it.Endpoints { + ready = ready || (ep.Conditions.Ready != nil && *ep.Conditions.Ready) + } + } + + if !ready { + return false, fmt.Errorf("%w: no ready endpoint", errNotReady) + } + + return probeHealth(ctx, base) +} + +func probeHealth(ctx context.Context, base string) (bool, error) { + rctx, cancel := context.WithTimeout(ctx, pollEvery*5) + defer cancel() + + req, err := http.NewRequestWithContext(rctx, http.MethodGet, base+"/_gopherstack/health", nil) + if err != nil { + return false, err + } + + tr := httpclient.NewTransport() + tr.DisableKeepAlives = true + + c := &http.Client{Transport: tr} + defer c.CloseIdleConnections() + + resp, err := c.Do(req) + if err != nil { + return false, err + } defer func() { _ = resp.Body.Close() }() - assert.Equal(t, http.StatusOK, resp.StatusCode) + if resp.StatusCode != http.StatusOK { + return false, fmt.Errorf("%w: health returned %d", errNotReady, resp.StatusCode) + } + + return true, nil +} + +func (k *k8sAPI) listPods(ctx context.Context) ([]podDiag, error) { + code, body, err := k.do(ctx, http.MethodGet, + "/api/v1/namespaces/"+namespace+"/pods?labelSelector=app.kubernetes.io/instance%3D"+releaseName) + if err != nil { + return nil, err + } + + if code != http.StatusOK { + return nil, fmt.Errorf("%w: list pods returned %d", errNotReady, code) + } + + var l struct { + Items []podDiag `json:"items"` + } + if err = json.Unmarshal(body, &l, jsonx.V1()); err != nil { + return nil, err + } + + return l.Items, nil +} + +type containerDiag struct { + LastState struct { + Terminated *struct { + Reason string `json:"reason"` + ExitCode int `json:"exitCode"` + } `json:"terminated"` + } `json:"lastState"` + Name string `json:"name"` + RestartCount int `json:"restartCount"` +} + +type podDiag struct { + Metadata struct { + Name string `json:"name"` + } `json:"metadata"` + Status struct { + ContainerStatuses []containerDiag `json:"containerStatuses"` + } `json:"status"` +} + +// noRestarts fails fatally if any release container restarted since it first became ready. +func (k *k8sAPI) noRestarts(ctx context.Context) error { + pods, err := k.listPods(ctx) + if err != nil { + return err + } + + for _, p := range pods { + for _, cs := range p.Status.ContainerStatuses { + if cs.RestartCount != 0 { + return fmt.Errorf("%w: pod %s container %s restarted %d times", errFatal, + p.Metadata.Name, cs.Name, cs.RestartCount) + } + } + } + + return nil +} + +// dumpDiagnostics logs pod status, current and previous container logs and namespace events when the test failed. +func (k *k8sAPI) dumpDiagnostics(t *testing.T) { + t.Helper() + + if !t.Failed() { + return + } + + ctx, cancel := context.WithTimeout(context.WithoutCancel(t.Context()), time.Minute) + defer cancel() + + pods, err := k.listPods(ctx) + if err != nil { + t.Logf("diagnostics: list pods: %v", err) + } + + for _, p := range pods { + for _, cs := range p.Status.ContainerStatuses { + t.Logf("pod %s container %s restarts=%d lastTerminated=%+v", + p.Metadata.Name, cs.Name, cs.RestartCount, cs.LastState.Terminated) + } + + for _, prev := range []string{"false", "true"} { + code, body, lerr := k.do(ctx, http.MethodGet, + "/api/v1/namespaces/"+namespace+"/pods/"+p.Metadata.Name+"/log?previous="+prev) + t.Logf("pod %s logs previous=%s code=%d err=%v\n%s", p.Metadata.Name, prev, code, lerr, body) + } + } + + code, body, err := k.do(ctx, http.MethodGet, "/api/v1/namespaces/"+namespace+"/events") + t.Logf("events code=%d err=%v\n%s", code, err, body) } func newS3(ctx context.Context, t *testing.T, endpoint string) *s3.Client {