Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
fix/feat: ddb parity + mit license per file (#1632)
Nahuel Nucera4004c014cda2
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 02630c1d..7f0c5d95 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -44,6 +44,9 @@ Versioning follows [Semantic Versioning](https://semver.org/).- **RDS — Aurora MySQL global writer switchover foundations** — deadline-bounded helpers for writer fencing, GTID convergence, replication-channel management and verified write enablement, plus lifecycle guards reserving clusters mid-switchover. No user-visible behavior changes; dormant until an orchestrator calls them. Contributed by @Areson.### Fixed+- **CloudFormation — stack updates stop destroying resources** — a changed property on a type without an update handler fell through to a re-create: generated-identity types (Cognito pools and clients, Secrets Manager secrets) came back empty under a new id with the old resource orphaned, name-keyed ones wiped their data (Kinesis records, ECR images, group members), and others failed the stack outright (any Route53 record edit, any EventBus property change). Twelve types now update in place — `AWS::Cognito::UserPool`/`UserPoolClient`/`IdentityPool`/`UserPoolGroup`, `AWS::SecretsManager::Secret` (a changed value becomes the new `AWSCURRENT`, same ARN, history kept), `AWS::Kinesis::Stream`, `AWS::ECR::Repository`, `AWS::DynamoDB::GlobalTable`, `AWS::Events::EventBus`, `AWS::CodeBuild::Project`, `AWS::Route53::RecordSet` and `AWS::Scheduler::Schedule` — and the engine gains real replacement semantics: when an update returns a new physical id, the predecessor is deleted in a cleanup phase, as CloudFormation does after `UPDATE_COMPLETE`.+- **Cognito — the PreSignUp trigger fires on plain `SignUp`** — only federated sign-ups invoked it; a pool's `LambdaConfig.PreSignUp` now runs before the user is persisted, fail-closed: `autoConfirmUser` confirms the account (no code delivery), `autoVerifyEmail`/`autoVerifyPhone` mark the attributes, and a rejecting or failing trigger blocks the sign-up with `UserLambdaValidationException`, per the trigger's documented contract.+- **STS — sessions expire and the store stops growing** — `GetCallerIdentity` with expired temporary credentials answers `403 ExpiredToken` ("The security token included in the request is expired", the documented STS error), and expired sessions are evicted as new ones register — previously every AssumeRole and vended identity-pool credential lived in memory forever.- **Lambda — a Docker-executed function sees its real ARN in `context.invoked_function_arn`** — the RIE inside the official images hardcodes `arn:aws:lambda:us-east-1:012345678912:function:{name}`, account and region, so a handler self-registering its own ARN (the standard pattern for wiring a Cognito trigger) stored a scope where nothing exists and the trigger never fired. Python and Node.js zip functions run through a shim handing user code the control-plane ARN; for `provided` and Image-type functions, where MiniStack owns no code path, an ARN carrying exactly the RIE's hardcoded scope resolves as the caller's own function, so a stored trigger still fires. Reported by @TomaszKupka.- **Cognito — TOTP codes verify** — `VerifySoftwareToken` answered `SUCCESS` for any six digits and the `SOFTWARE_TOKEN_MFA` challenge issued tokens for any code. The `AssociateSoftwareToken` secret is now stored and verified with RFC 6238 (HMAC-SHA1, 30-second step, ±1 step): a wrong code answers `EnableSoftwareTokenMFAException` on verify and `CodeMismatchException` on the challenge, both in the operations' botocore error models, and success promotes the secret and enrolls the user. The CloudFormation provisioner maps `EnabledMfas: [SOFTWARE_TOKEN_MFA]` (what CDK emits) onto `GetUserPoolMfaConfig`. Tests sending a fixed code must derive one from the `SecretCode` they receive; users enrolled before this release keep the old behavior until re-enrolment. Reported by @iot-rocket.- **RDS — the Aurora reader endpoint is a name that resolves** — `CreateDBCluster` handed out an AWS-shaped `cluster-ro-` name that nothing registered, so a consumer that stored it (Terraform reads `reader_endpoint` during the creating apply) held an unresolvable endpoint, hanging until client timeout. The reader name is registered as a Docker network alias alongside the writer name, and `DescribeDBClusters` reports it whenever the writer reports its stable name — per the Aurora documentation, a cluster with no replicas resolves its reader endpoint to the primary. With PG streaming replication on, the name stays off the writer so a standby can carry it. Outside alias mode everything behaves as before. Reported by @jbschooley.diff --git a/ministack/__init__.py b/ministack/__init__.pyindex e69de29b..ba40f66e 100644--- a/ministack/__init__.py+++ b/ministack/__init__.py@@ -0,0 +1,2 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE).diff --git a/ministack/__main__.py b/ministack/__main__.pyindex 2f2c21f0..4d1aba4d 100644--- a/ministack/__main__.py+++ b/ministack/__main__.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE).from ministack.app import mainmain()diff --git a/ministack/app.py b/ministack/app.pyindex c65213d6..c7636b99 100644--- a/ministack/app.py+++ b/ministack/app.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""MiniStack — Local AWS Service Emulator.Single-port ASGI application on port 4566 (configurable via GATEWAY_PORT).diff --git a/ministack/core/__init__.py b/ministack/core/__init__.pyindex e69de29b..ba40f66e 100644--- a/ministack/core/__init__.py+++ b/ministack/core/__init__.py@@ -0,0 +1,2 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE).diff --git a/ministack/core/appsync_graphql.py b/ministack/core/appsync_graphql.pyindex 2e33fe1e..a3c97901 100644--- a/ministack/core/appsync_graphql.py+++ b/ministack/core/appsync_graphql.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""GraphQL execution for AppSync.The data plane used to match the query with a regex and split the body with morediff --git a/ministack/core/appsync_js.py b/ministack/core/appsync_js.pyindex ed49ff2d..f90ed788 100644--- a/ministack/core/appsync_js.py+++ b/ministack/core/appsync_js.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""APPSYNC_JS resolver evaluation.AppSync resolvers are ES modules exporting `request(ctx)` and `response(ctx)`.diff --git a/ministack/core/arn.py b/ministack/core/arn.pyindex 04b46c5f..d067fdb3 100644--- a/ministack/core/arn.py+++ b/ministack/core/arn.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""Small Amazon Resource Name parsing helpers.The top-level ARN shape is service-agnostic:diff --git a/ministack/core/concurrency.py b/ministack/core/concurrency.pyindex a04b79e5..46a79550 100644--- a/ministack/core/concurrency.py+++ b/ministack/core/concurrency.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""Off-loop execution primitives.MiniStack is a single ASGI process, so every blocking call has to be placeddiff --git a/ministack/core/container_reaper.py b/ministack/core/container_reaper.pyindex 2a91682b..08334368 100644--- a/ministack/core/container_reaper.py+++ b/ministack/core/container_reaper.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""Periodic reclamation of MiniStack's Docker containers.Without this, a long-running MiniStack accumulates containers — and thediff --git a/ministack/core/hypercorn_compat.py b/ministack/core/hypercorn_compat.pyindex e31e13f8..4310f05b 100644--- a/ministack/core/hypercorn_compat.py+++ b/ministack/core/hypercorn_compat.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""Compatibility shims for the hypercorn/h11 stack.h11 serialises ``InformationalResponse`` with an empty reason phrase bydiff --git a/ministack/core/hypercorn_conf.py b/ministack/core/hypercorn_conf.pyindex 2265d0d6..21c3c50e 100644--- a/ministack/core/hypercorn_conf.py+++ b/ministack/core/hypercorn_conf.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""Hypercorn config — applied via `-c file:` in the Dockerfile ENTRYPOINT.Hypercorn's `from_pyfile` collects every non-module, non-dunderdiff --git a/ministack/core/iam_actions.py b/ministack/core/iam_actions.pyindex d9036d89..030ad868 100644--- a/ministack/core/iam_actions.py+++ b/ministack/core/iam_actions.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""IAM action extraction and AccessDenied response formatting.Maps MiniStack's internal service names to IAM namespaces, extracts thediff --git a/ministack/core/iam_evaluator.py b/ministack/core/iam_evaluator.pyindex 01bbb03f..6d6bfddd 100644--- a/ministack/core/iam_evaluator.py+++ b/ministack/core/iam_evaluator.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""IAM policy evaluation engine.Implements the AWS IAM policy evaluation algorithm (single-account,diff --git a/ministack/core/lambda_runtime.py b/ministack/core/lambda_runtime.pyindex 113e16e7..015baa48 100644--- a/ministack/core/lambda_runtime.py+++ b/ministack/core/lambda_runtime.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""Lambda warm/cold start worker pool.Each function gets a persistent worker process (Python or Node.js) that importsdiff --git a/ministack/core/persistence.py b/ministack/core/persistence.pyindex 3ccac0e6..948d7227 100644--- a/ministack/core/persistence.py+++ b/ministack/core/persistence.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""State persistence for MiniStack services.When PERSIST_STATE=1, service state is saved to STATE_DIR on shutdowndiff --git a/ministack/core/pgproxy.py b/ministack/core/pgproxy.pyindex cc218c92..226ed074 100644--- a/ministack/core/pgproxy.py+++ b/ministack/core/pgproxy.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""Asyncio Postgres wire-protocol proxy with Aurora DSQL validation.diff --git a/ministack/core/responses.py b/ministack/core/responses.pyindex beca43d5..d806effb 100644--- a/ministack/core/responses.py+++ b/ministack/core/responses.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""AWS Response formatting utilities.Handles XML responses (S3, SQS, SNS, IAM, STS, CloudWatch) anddiff --git a/ministack/core/router.py b/ministack/core/router.pyindex 7d956f0d..34fd508d 100644--- a/ministack/core/router.py+++ b/ministack/core/router.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""AWS API Request Router.Routes incoming requests to the correct service handler based on:diff --git a/ministack/core/tls.py b/ministack/core/tls.pyindex c5116e5d..cefc7462 100644--- a/ministack/core/tls.py+++ b/ministack/core/tls.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""TLS material helpers — env-driven cert/key resolution for the gateway.`USE_SSL=1` enables HTTPS (LocalStack-compatible). Self-signed certdiff --git a/ministack/core/x509_utils.py b/ministack/core/x509_utils.pyindex c6ed8b62..9e98d50e 100644--- a/ministack/core/x509_utils.py+++ b/ministack/core/x509_utils.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""X.509 certificate utilities for Ministack.Generic crypto helpers for generating self-signed CAs, signing leafdiff --git a/ministack/services/__init__.py b/ministack/services/__init__.pyindex e69de29b..ba40f66e 100644--- a/ministack/services/__init__.py+++ b/ministack/services/__init__.py@@ -0,0 +1,2 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE).diff --git a/ministack/services/_dynamodb_keywords.py b/ministack/services/_dynamodb_keywords.pyindex 373538c8..41588e04 100644--- a/ministack/services/_dynamodb_keywords.py+++ b/ministack/services/_dynamodb_keywords.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""DynamoDB AWS system keyword list.These names must be escaped with `#alias` in ConditionExpression,diff --git a/ministack/services/account.py b/ministack/services/account.pyindex 6a534258..28403208 100644--- a/ministack/services/account.py+++ b/ministack/services/account.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""AWS Account service stub (rest-json).diff --git a/ministack/services/acm.py b/ministack/services/acm.pyindex cf3efb91..92142810 100644--- a/ministack/services/acm.py+++ b/ministack/services/acm.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""ACM (Certificate Manager) Service Emulator.JSON-based API via X-Amz-Target.diff --git a/ministack/services/alb.py b/ministack/services/alb.pyindex f527799b..5654b71f 100644--- a/ministack/services/alb.py+++ b/ministack/services/alb.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""ALB / ELBv2 (Elastic Load Balancing v2) Service Emulator.Query API (Action=...) with XML responses. In-memory only.diff --git a/ministack/services/apigateway.py b/ministack/services/apigateway.pyindex 0aa4838c..427c2330 100644--- a/ministack/services/apigateway.py+++ b/ministack/services/apigateway.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""API Gateway HTTP API v2 Emulator.diff --git a/ministack/services/apigateway_v1.py b/ministack/services/apigateway_v1.pyindex 620ef6a4..3bdbe765 100644--- a/ministack/services/apigateway_v1.py+++ b/ministack/services/apigateway_v1.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""API Gateway REST API v1 Emulator.diff --git a/ministack/services/appconfig.py b/ministack/services/appconfig.pyindex 9987e050..299cfb2c 100644--- a/ministack/services/appconfig.py+++ b/ministack/services/appconfig.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""AppConfig Service Emulator.REST/JSON protocol — path-based routing.diff --git a/ministack/services/appsync.py b/ministack/services/appsync.pyindex d66d7a19..ee9fc84a 100644--- a/ministack/services/appsync.py+++ b/ministack/services/appsync.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""AWS AppSync Service Emulator.diff --git a/ministack/services/appsync_events.py b/ministack/services/appsync_events.pyindex e6ade3b8..ba3ff0d4 100644--- a/ministack/services/appsync_events.py+++ b/ministack/services/appsync_events.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""AWS AppSync Events emulator.diff --git a/ministack/services/athena.py b/ministack/services/athena.pyindex f5d8a57c..733dc54c 100644--- a/ministack/services/athena.py+++ b/ministack/services/athena.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""Athena Service Emulator.JSON-based API via X-Amz-Target (AmazonAthena).diff --git a/ministack/services/autoscaling.py b/ministack/services/autoscaling.pyindex bfbb0cdc..e5fede91 100644--- a/ministack/services/autoscaling.py+++ b/ministack/services/autoscaling.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""AutoScaling Service Emulator.Query API (Action=...) — groups, launch configs, policies, hooks, scheduled actions.diff --git a/ministack/services/backup.py b/ministack/services/backup.pyindex abbc2b9c..a22c0f36 100644--- a/ministack/services/backup.py+++ b/ministack/services/backup.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""AWS Backup Service Emulator.REST/JSON protocol — /backup-vaults/*, /backup/plans/*, /backup-jobs/*, /tags/* paths.diff --git a/ministack/services/batch.py b/ministack/services/batch.pyindex 9c8bdf80..4673ddcd 100644--- a/ministack/services/batch.py+++ b/ministack/services/batch.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""AWS Batch stub (rest-json).diff --git a/ministack/services/bedrock.py b/ministack/services/bedrock.pyindex 12966ca0..ef870b41 100644--- a/ministack/services/bedrock.py+++ b/ministack/services/bedrock.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""Bedrock Control-Plane Service Emulator.JSON REST API — signing name: bedrock. Endpoint prefix: bedrock.diff --git a/ministack/services/bedrock_agent.py b/ministack/services/bedrock_agent.pyindex cb2b6955..9a667301 100644--- a/ministack/services/bedrock_agent.py+++ b/ministack/services/bedrock_agent.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""Bedrock Agent Service Emulator.JSON REST API — signing name: bedrock. Endpoint prefix: bedrock-agent.diff --git a/ministack/services/bedrock_agent_runtime.py b/ministack/services/bedrock_agent_runtime.pyindex 509990f8..7e1df470 100644--- a/ministack/services/bedrock_agent_runtime.py+++ b/ministack/services/bedrock_agent_runtime.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""Bedrock Agent Runtime Service Emulator.JSON REST API + eventstream — signing name: bedrock. Endpoint prefix: bedrock-agent-runtime.diff --git a/ministack/services/bedrock_agentcore.py b/ministack/services/bedrock_agentcore.pyindex 56240cc0..a3b470b8 100644--- a/ministack/services/bedrock_agentcore.py+++ b/ministack/services/bedrock_agentcore.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""Amazon Bedrock AgentCore emulator.Covers the two AgentCore services, which both sign as ``bedrock-agentcore``:diff --git a/ministack/services/bedrock_runtime.py b/ministack/services/bedrock_runtime.pyindex 8ae9df46..8548df78 100644--- a/ministack/services/bedrock_runtime.py+++ b/ministack/services/bedrock_runtime.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""Bedrock Runtime Service Emulator.JSON REST API — signing name: bedrock-runtime.diff --git a/ministack/services/cloudcontrol.py b/ministack/services/cloudcontrol.pyindex 8eed1db2..91324114 100644--- a/ministack/services/cloudcontrol.py+++ b/ministack/services/cloudcontrol.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""AWS Cloud Control API Emulator.JSON-based API via X-Amz-Target (prefix: CloudApiService).diff --git a/ministack/services/cloudformation/__init__.py b/ministack/services/cloudformation/__init__.pyindex e7fb7cbe..2e250301 100644--- a/ministack/services/cloudformation/__init__.py+++ b/ministack/services/cloudformation/__init__.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""CloudFormation Service Emulator -- AWS-compatible.Supports: CreateStack, UpdateStack, DeleteStack, DescribeStacks, ListStacks,diff --git a/ministack/services/cloudformation/changesets.py b/ministack/services/cloudformation/changesets.pyindex fc7edff3..c4267639 100644--- a/ministack/services/cloudformation/changesets.py+++ b/ministack/services/cloudformation/changesets.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""CloudFormation change set handlers — Create, Describe, Execute, Delete, List change sets."""diff --git a/ministack/services/cloudformation/custom_resource.py b/ministack/services/cloudformation/custom_resource.pyindex ac2b52d2..60fa2141 100644--- a/ministack/services/cloudformation/custom_resource.py+++ b/ministack/services/cloudformation/custom_resource.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""CloudFormation Custom Resource — ResponseURL intercept and Lambda invocation."""diff --git a/ministack/services/cloudformation/engine.py b/ministack/services/cloudformation/engine.pyindex 97e4d43e..8e85e154 100644--- a/ministack/services/cloudformation/engine.py+++ b/ministack/services/cloudformation/engine.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""CloudFormation engine — pure functions for template parsing, parameter resolution,condition evaluation, intrinsic function resolution, and topological sorting.diff --git a/ministack/services/cloudformation/handlers.py b/ministack/services/cloudformation/handlers.pyindex 91e76049..ff8d7440 100644--- a/ministack/services/cloudformation/handlers.py+++ b/ministack/services/cloudformation/handlers.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""CloudFormation handlers — API action handlers for all supported CloudFormation actions."""diff --git a/ministack/services/cloudformation/helpers.py b/ministack/services/cloudformation/helpers.pyindex 2a833c0c..6bed9b03 100644--- a/ministack/services/cloudformation/helpers.py+++ b/ministack/services/cloudformation/helpers.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""CloudFormation helpers — XML response formatting and parameter extraction utilities."""diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.pyindex e9fb0158..705f069f 100644--- a/ministack/services/cloudformation/provisioners.py+++ b/ministack/services/cloudformation/provisioners.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""CloudFormation provisioners — resource create/delete handlers for each AWS resource type."""@@ -7922,6 +7924,216 @@ def _cognito_identity_pool_principal_tag_delete(physical_id, props):pool.get("_principal_tags", {}).pop(provider, None)++# ---------------------------------------------------------------------------+# In-place update handlers for the types whose create-fallback destroyed data+# (generated identities, wiped children) or failed loudly. Each mutates the+# existing service record; a genuinely create-only property returns the+# resource to the engine as a replacement (new physical id), whose predecessor+# the engine now deletes in its cleanup phase.+# ---------------------------------------------------------------------------++def _cognito_user_pool_update(physical_id, old_props, new_props, stack_name):+ pool = _cognito._user_pools.get(physical_id)+ if pool is None:+ return _cognito_user_pool_create(physical_id, new_props, stack_name)+ if "PoolName" in new_props:+ pool["Name"] = new_props["PoolName"]+ for prop, key in (("Policies", "Policies"),+ ("AutoVerifiedAttributes", "AutoVerifiedAttributes"),+ ("AliasAttributes", "AliasAttributes"),+ ("UsernameAttributes", "UsernameAttributes"),+ ("MfaConfiguration", "MfaConfiguration"),+ ("UserPoolTags", "UserPoolTags"),+ ("AdminCreateUserConfig", "AdminCreateUserConfig"),+ ("LambdaConfig", "LambdaConfig")):+ if prop in new_props:+ pool[key] = new_props[prop]+ if "SOFTWARE_TOKEN_MFA" in (new_props.get("EnabledMfas") or []):+ pool["SoftwareTokenMfaConfiguration"] = {"Enabled": True}+ elif "EnabledMfas" in new_props:+ pool.pop("SoftwareTokenMfaConfiguration", None)+ pool["LastModifiedDate"] = _cognito._now_epoch()+ provider_name = f"cognito-idp.{get_region()}.amazonaws.com/{physical_id}"+ return physical_id, {"Arn": pool["Arn"], "ProviderName": provider_name}+++def _cognito_user_pool_client_update(physical_id, old_props, new_props, stack_name):+ pid = new_props.get("UserPoolId", old_props.get("UserPoolId", ""))+ pool = _cognito._user_pools.get(pid)+ client = (pool or {}).get("_clients", {}).get(physical_id)+ if client is None:+ return _cognito_user_pool_client_create(physical_id, new_props, stack_name)+ for prop, key in (("ClientName", "ClientName"),+ ("ExplicitAuthFlows", "ExplicitAuthFlows"),+ ("AllowedOAuthFlows", "AllowedOAuthFlows"),+ ("AllowedOAuthScopes", "AllowedOAuthScopes"),+ ("CallbackURLs", "CallbackURLs"),+ ("LogoutURLs", "LogoutURLs"),+ ("SupportedIdentityProviders", "SupportedIdentityProviders")):+ if prop in new_props:+ client[key] = new_props[prop]+ client["LastModifiedDate"] = _cognito._now_epoch()+ return physical_id, {}+++def _cognito_identity_pool_update(physical_id, old_props, new_props, stack_name):+ pool = _cognito._identity_pools.get(physical_id)+ if pool is None:+ return _cognito_identity_pool_create(physical_id, new_props, stack_name)+ for prop in ("IdentityPoolName", "AllowUnauthenticatedIdentities",+ "AllowClassicFlow", "SupportedLoginProviders",+ "DeveloperProviderName", "OpenIdConnectProviderARNs",+ "CognitoIdentityProviders", "SamlProviderARNs",+ "IdentityPoolTags"):+ if prop in new_props:+ pool[prop] = new_props[prop]+ return physical_id, {}+++def _cognito_user_pool_group_update(physical_id, old_props, new_props, stack_name):+ pid = new_props.get("UserPoolId", old_props.get("UserPoolId", ""))+ pool = _cognito._user_pools.get(pid)+ group = (pool or {}).get("_groups", {}).get(physical_id)+ new_name = new_props.get("GroupName") or physical_id+ if group is None or new_name != physical_id:+ # Name change is a replacement; the engine deletes the old group.+ return _cognito_user_pool_group_create(physical_id, new_props, stack_name)+ for prop in ("Description", "RoleArn", "Precedence"):+ if prop in new_props:+ group[prop] = new_props[prop]+ group["LastModifiedDate"] = _cognito._now_epoch()+ return physical_id, {}+++def _sm_secret_update(physical_id, old_props, new_props, stack_name):+ secret = _sm._secrets.get(physical_id)+ new_name = new_props.get("Name") or _physical_name(stack_name, physical_id)+ if secret is None or (old_props.get("Name") or physical_id) != new_name and "Name" in new_props:+ # Name is create-only: replacement, predecessor cleaned by the engine.+ return _sm_secret_create(physical_id, new_props, stack_name)+ for prop in ("Description", "KmsKeyId"):+ if prop in new_props:+ secret[prop] = new_props[prop]+ if "Tags" in new_props:+ secret["Tags"] = new_props["Tags"]+ if "SecretString" in new_props and new_props["SecretString"] != old_props.get("SecretString"):+ # A changed value becomes the new AWSCURRENT version; history is kept.+ import time as _time+ for version in secret.get("Versions", {}).values():+ version["Stages"] = [s for s in version.get("Stages", []) if s != "AWSCURRENT"]+ secret["Versions"][new_uuid()] = {+ "SecretString": new_props["SecretString"],+ "SecretBinary": None,+ "CreatedDate": int(_time.time()),+ "Stages": ["AWSCURRENT"],+ }+ secret["LastChangedDate"] = int(_time.time())+ return physical_id, {"Arn": secret["ARN"]}+++def _kinesis_stream_update(physical_id, old_props, new_props, stack_name):+ stream = _kinesis._streams.get(physical_id)+ new_name = new_props.get("Name")+ if stream is None or (new_name and new_name != physical_id):+ return _kinesis_stream_create(physical_id, new_props, stack_name)+ if "RetentionPeriodHours" in new_props:+ stream["RetentionPeriodHours"] = max(24, min(8760, int(new_props["RetentionPeriodHours"])))+ smd = new_props.get("StreamModeDetails")+ if isinstance(smd, dict) and smd.get("StreamMode"):+ stream["StreamModeDetails"] = {"StreamMode": smd["StreamMode"]}+ # ShardCount changes keep the existing shards — records live in them.+ return physical_id, {"Arn": stream["StreamARN"]}+++def _ecr_repo_update(physical_id, old_props, new_props, stack_name):+ repo = _ecr._repositories.get(physical_id)+ new_name = new_props.get("RepositoryName")+ if repo is None or (new_name and new_name != physical_id):+ return _ecr_repo_create(physical_id, new_props, stack_name)+ for prop, key in (("ImageTagMutability", "imageTagMutability"),+ ("ImageScanningConfiguration", "imageScanningConfiguration")):+ if prop in new_props:+ repo[key] = new_props[prop]+ return physical_id, {"Arn": repo["repositoryArn"], "RepositoryUri": repo["repositoryUri"]}+++def _ddb_global_table_update(physical_id, old_props, new_props, stack_name):+ # Same property translation as create, then the Table update handler —+ # the create-fallback rebuilt the table record and dropped every item.+ translated = dict(new_props)+ for prop in ("Replicas", "MultiRegionConsistency", "GlobalTableWitnesses",+ "GlobalTableSourceArn", "WarmThroughput",+ "WriteOnDemandThroughputSettings", "ReadOnDemandThroughputSettings",+ "WriteProvisionedThroughputSettings", "ReadProvisionedThroughputSettings"):+ translated.pop(prop, None)+ return _ddb_update(physical_id, old_props, translated, stack_name)+++def _eb_event_bus_update(physical_id, old_props, new_props, stack_name):+ new_name = new_props.get("Name")+ if new_name and new_name != physical_id:+ # Name is create-only: replacement (the fallback used to fail the+ # stack with "EventBus already exists" on ANY property change).+ return _eb_event_bus_create(physical_id, new_props, stack_name)+ bus = _eb._event_buses.get(physical_id)+ if bus is not None and isinstance(bus, dict):+ if "Description" in new_props:+ bus["Description"] = new_props["Description"]+ return physical_id, {"Arn": f"arn:aws:events:{get_region()}:{get_account_id()}:event-bus/{physical_id}", "Name": physical_id}+++def _codebuild_project_update(physical_id, old_props, new_props, stack_name):+ project = _codebuild._projects.get(physical_id)+ new_name = new_props.get("Name")+ if project is None or (new_name and new_name != physical_id):+ return _codebuild_project_create(physical_id, new_props, stack_name)+ for prop, key in (("Description", "description"), ("Source", "source"),+ ("SourceVersion", "sourceVersion"), ("Artifacts", "artifacts"),+ ("Environment", "environment"), ("ServiceRole", "serviceRole")):+ if prop in new_props:+ project[key] = new_props[prop]+ if "TimeoutInMinutes" in new_props:+ project["timeoutInMinutes"] = int(new_props["TimeoutInMinutes"])+ return physical_id, {"Arn": _codebuild._project_arn(physical_id)}+++def _r53_record_set_update(physical_id, old_props, new_props, stack_name):+ # Same name+type: the values update in place (the fallback raised+ # "record already exists", so EVERY record edit rolled the stack back).+ zone_id = _r53_resolve_hosted_zone_id(new_props)+ new_rs = _r53_record_set_build_rs(new_props)+ old_zone_id = _r53_resolve_hosted_zone_id(old_props)+ old_rs = _r53_record_set_build_rs(old_props)+ if zone_id != old_zone_id or _r53._rs_key(new_rs) != _r53._rs_key(old_rs):+ # Different record identity: create the new one; the engine deletes+ # the predecessor through the delete handler.+ return _r53_record_set_create(physical_id, new_props, stack_name)+ with _r53._lock:+ records = list(_r53._records.get(zone_id, []))+ key = _r53._rs_key(new_rs)+ records = [r for r in records if _r53._rs_key(r) != key]+ records.append(new_rs)+ _r53._records[zone_id] = records+ return new_rs["Name"], {"Name": new_rs["Name"]}+++def _scheduler_schedule_update(physical_id, old_props, new_props, stack_name):+ import ministack.services.scheduler as _sched+ new_name = new_props.get("Name")+ if new_name and new_name != physical_id:+ return _scheduler_schedule_create(physical_id, new_props, stack_name)+ group = new_props.get("GroupName", old_props.get("GroupName", "default"))+ key = f"{group}/{physical_id}"+ schedule = _sched._schedules.get(key)+ if schedule is None:+ return _scheduler_schedule_create(physical_id, new_props, stack_name)+ for prop in ("ScheduleExpression", "FlexibleTimeWindow", "Target",+ "State", "Description"):+ if prop in new_props:+ schedule[prop] = new_props[prop]+ return physical_id, {"Arn": _sched._schedule_arn(group, physical_id)}+_RESOURCE_HANDLERS = {"AWS::OpenSearchService::Domain": {"create": _opensearch_domain_create,@@ -7963,7 +8175,7 @@ _RESOURCE_HANDLERS = {# comes from WriteProvisionedThroughputSettings; Replicas is required and# ignored locally), so it gets a dedicated provisioner that translates# before delegating to the Table engine.- "AWS::DynamoDB::GlobalTable": {"create": _ddb_global_table_create, "delete": _ddb_global_table_delete},+ "AWS::DynamoDB::GlobalTable": {"create": _ddb_global_table_create, "update": _ddb_global_table_update, "delete": _ddb_global_table_delete},"AWS::Lambda::Function": {"create": _lambda_create,"update": _lambda_update,@@ -8025,14 +8237,14 @@ _RESOURCE_HANDLERS = {"delete": _cwlogs_resource_policy_delete,},"AWS::Logs::SubscriptionFilter": {"create": _cwlogs_subfilter_create, "delete": _cwlogs_subfilter_delete},+ "AWS::Events::EventBus": {"create": _eb_event_bus_create, "update": _eb_event_bus_update, "delete": _eb_event_bus_delete},+ "AWS::Kinesis::Stream": {"create": _kinesis_stream_create, "update": _kinesis_stream_update, "delete": _kinesis_stream_delete},"AWS::Events::Rule": {"create": _eb_rule_create,"update": _eb_rule_update,"update_with_logical_id": True,"delete": _eb_rule_delete,},- "AWS::Events::EventBus": {"create": _eb_event_bus_create, "delete": _eb_event_bus_delete},- "AWS::Kinesis::Stream": {"create": _kinesis_stream_create, "delete": _kinesis_stream_delete},"AWS::KinesisFirehose::DeliveryStream": {"create": _firehose_delivery_stream_create,"update": _firehose_delivery_stream_update,@@ -8185,11 +8397,11 @@ _RESOURCE_HANDLERS = {"delete": _cognito_identity_pool_delete,},"AWS::Cognito::UserPoolDomain": {"create": _cognito_user_pool_domain_create, "delete": _cognito_user_pool_domain_delete},- "AWS::ECR::Repository": {"create": _ecr_repo_create, "delete": _ecr_repo_delete},+ "AWS::ECR::Repository": {"create": _ecr_repo_create, "update": _ecr_repo_update, "delete": _ecr_repo_delete},"AWS::CertificateManager::Certificate": {"create": _acm_certificate_create, "delete": _acm_certificate_delete},"AWS::ElasticLoadBalancingV2::TargetGroup": {"create": _elbv2_target_group_create, "delete": _elbv2_target_group_delete},"AWS::ElasticLoadBalancingV2::ListenerRule": {"create": _elbv2_listener_rule_create, "delete": _elbv2_listener_rule_delete},- "AWS::CodeBuild::Project": {"create": _codebuild_project_create, "delete": _codebuild_project_delete},+ "AWS::CodeBuild::Project": {"create": _codebuild_project_create, "update": _codebuild_project_update, "delete": _codebuild_project_delete},"AWS::IAM::ManagedPolicy": {"create": _iam_managed_policy_create,"update": _iam_managed_policy_update,@@ -8233,7 +8445,7 @@ _RESOURCE_HANDLERS = {"delete": _sfn_state_machine_delete,},"AWS::Route53::HostedZone": {"create": _r53_hosted_zone_create, "delete": _r53_hosted_zone_delete},- "AWS::Route53::RecordSet": {"create": _r53_record_set_create, "delete": _r53_record_set_delete},+ "AWS::Route53::RecordSet": {"create": _r53_record_set_create, "update": _r53_record_set_update, "delete": _r53_record_set_delete},"AWS::ApiGatewayV2::Api": {"create": _apigw_v2_api_create, "delete": _apigw_v2_api_delete},"AWS::ApiGatewayV2::Stage": {"create": _apigw_v2_stage_create, "delete": _apigw_v2_stage_delete},"AWS::ApiGatewayV2::Integration": {"create": _apigw_v2_integration_create, "delete": _apigw_v2_integration_delete},@@ -8302,7 +8514,7 @@ _RESOURCE_HANDLERS = {"delete": _cognito_identity_pool_principal_tag_delete,},# EventBridge Scheduler- "AWS::Scheduler::Schedule": {"create": _scheduler_schedule_create, "delete": _scheduler_schedule_delete},+ "AWS::Scheduler::Schedule": {"create": _scheduler_schedule_create, "update": _scheduler_schedule_update, "delete": _scheduler_schedule_delete},"AWS::Scheduler::ScheduleGroup": {"create": _scheduler_group_create, "delete": _scheduler_group_delete},# EKS"AWS::EKS::Cluster": {"create": _eks_cluster_create, "delete": _eks_cluster_delete},diff --git a/ministack/services/cloudformation/stacks.py b/ministack/services/cloudformation/stacks.pyindex 047c2b09..a97f96cd 100644--- a/ministack/services/cloudformation/stacks.py+++ b/ministack/services/cloudformation/stacks.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""CloudFormation stacks — async stack lifecycle (deploy, delete, update, diff)."""@@ -162,6 +164,7 @@ async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,failed = Falsefail_reason = ""+ replaced_resources = []for logical_id in ordered:res_def = resources_defs[logical_id]@@ -208,6 +211,13 @@ async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,resource_type, old_pid, old_props, resolved_props,stack_name, logical_id, old_attrs)+ if physical_id != old_pid:+ # A changed physical id is a replacement. Real+ # CloudFormation deletes the predecessor in the+ # UPDATE_COMPLETE_CLEANUP phase; without this the old+ # resource leaked forever, still holding its data.+ replaced_resources.append(+ (logical_id, resource_type, old_pid, old_props))else:if _is_custom_resource(resource_type):physical_id, attrs = await run_reentrant(@@ -240,6 +250,24 @@ async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,_add_event(stack_id, stack_name, logical_id, resource_type,f"{status_prefix}_COMPLETE", physical_id=physical_id)+ # Replacement cleanup (update case): delete each replaced resource's+ # predecessor, as real CloudFormation does after UPDATE_COMPLETE.+ if not failed and replaced_resources:+ for logical_id, rtype, old_pid, old_props in replaced_resources:+ try:+ if _is_custom_resource(rtype):+ await run_reentrant(+ _delete_resource, rtype, old_pid, old_props,+ stack_name, logical_id+ )+ else:+ _delete_resource(rtype, old_pid, old_props, stack_name, logical_id)+ except Exception as exc:+ logger.error("Failed to delete replaced resource %s (%s): %s",+ logical_id, old_pid, exc)+ _add_event(stack_id, stack_name, logical_id, rtype,+ "DELETE_FAILED", str(exc), old_pid)+# Delete removed resources (update case)if not failed and to_remove:old_resources = previous_stack.get("_resources", {})diff --git a/ministack/services/cloudfront.py b/ministack/services/cloudfront.pyindex c2b77536..16cf0fd8 100644--- a/ministack/services/cloudfront.py+++ b/ministack/services/cloudfront.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""CloudFront Service Emulator.REST/XML API — service credential scope: cloudfront.diff --git a/ministack/services/cloudfront_keyvaluestore.py b/ministack/services/cloudfront_keyvaluestore.pyindex b79261f2..01f73a8f 100644--- a/ministack/services/cloudfront_keyvaluestore.py+++ b/ministack/services/cloudfront_keyvaluestore.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""CloudFront KeyValueStore Data-Plane Service Emulator.JSON REST API — signing name: cloudfront-keyvaluestore.diff --git a/ministack/services/cloudtrail.py b/ministack/services/cloudtrail.pyindex 0771a2bd..e5241b56 100644--- a/ministack/services/cloudtrail.py+++ b/ministack/services/cloudtrail.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""AWS CloudTrail Service Emulator.In-memory audit log — records all API calls and exposes LookupEvents for test assertions.diff --git a/ministack/services/cloudwatch.py b/ministack/services/cloudwatch.pyindex 72948cf7..50c3e044 100644--- a/ministack/services/cloudwatch.py+++ b/ministack/services/cloudwatch.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""CloudWatch Metrics Service Emulator.Supports legacy Query API (form-encoded), smithy-rpc-v2-cbor (botocore 1.42+),diff --git a/ministack/services/cloudwatch_logs.py b/ministack/services/cloudwatch_logs.pyindex 264d0250..d1ccc9c6 100644--- a/ministack/services/cloudwatch_logs.py+++ b/ministack/services/cloudwatch_logs.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""CloudWatch Logs Service Emulator.JSON-based API via X-Amz-Target (Logs_20140328).diff --git a/ministack/services/codebuild.py b/ministack/services/codebuild.pyindex ff622f21..32fef79b 100644--- a/ministack/services/codebuild.py+++ b/ministack/services/codebuild.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""CodeBuild Service Emulator.JSON-based API via X-Amz-Target: CodeBuild_20161006.<Operation>.diff --git a/ministack/services/cognito.py b/ministack/services/cognito.pyindex 36cb4a1a..80c81964 100644--- a/ministack/services/cognito.py+++ b/ministack/services/cognito.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""Amazon Cognito Service Emulator.@@ -4017,10 +4019,26 @@ def _sign_up(data):attr_dict["sub"] = new_uuid()attrs = _dict_to_attr_list(attr_dict)- # SignUp always creates UNCONFIRMED — ConfirmSignUp (or AdminConfirmSignUp) confirms the account.- # AutoVerifiedAttributes only auto-verifies those attributes (e.g. email), not the account itself.- # Auto-confirming accounts requires a pre-signup Lambda trigger, which we don't emulate.+ # SignUp creates UNCONFIRMED unless the pool's PreSignUp Lambda trigger+ # auto-confirms — invoked before the user is persisted, fail-closed, as on+ # AWS (a rejecting or failing trigger blocks the sign-up with+ # UserLambdaValidationException).status = "UNCONFIRMED"+ try:+ presignup = _apply_presignup_trigger(+ pid, cid, username, dict(attr_dict),+ trigger_source="PreSignUp_SignUp",+ )+ except _PreSignUpRejected as e:+ logger.info("Cognito: PreSignUp Lambda rejected sign-up for %s: %s", username, e)+ return error_response_json("UserLambdaValidationException", str(e), 400)+ if presignup["autoConfirmUser"]:+ status = "CONFIRMED"+ if presignup["autoVerifyEmail"] and "email" in attr_dict:+ attr_dict["email_verified"] = "true"+ if presignup["autoVerifyPhone"] and "phone_number" in attr_dict:+ attr_dict["phone_number_verified"] = "true"+ attrs = _dict_to_attr_list(attr_dict)user = {"Username": username,@@ -4042,7 +4060,8 @@ def _sign_up(data):"UserConfirmed": status == "CONFIRMED","UserSub": attr_dict["sub"],}- if "email" in attr_dict:+ if "email" in attr_dict and status != "CONFIRMED":+ # An auto-confirmed user has nothing to verify — no code is delivered.resp["CodeDeliveryDetails"] = {"Destination": attr_dict["email"],"DeliveryMedium": "EMAIL",@@ -6544,7 +6563,7 @@ def _get_credentials_for_identity(data):provider_parts.append(provider_name)from ministack.services import sts as sts_svc- sts_svc._sessions[access_key] = {+ sts_svc.register_session(access_key, {"Arn": (f"arn:aws:sts::{get_account_id()}:assumed-role/"f"{role_name}/CognitoIdentityCredentials"),"UserId": f"{role_id}:CognitoIdentityCredentials",@@ -6556,7 +6575,7 @@ def _get_credentials_for_identity(data):"_cognito_auth_type": "authenticated" if logins else "unauthenticated","_cognito_auth_provider": ",".join(provider_parts) or None,"_cognito_amr": amr,- }+ })return json_response({"IdentityId": identity_id,diff --git a/ministack/services/config.py b/ministack/services/config.pyindex 1db9c0f5..52d7436b 100644--- a/ministack/services/config.py+++ b/ministack/services/config.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""AWS Config Service Emulator.JSON-based API via X-Amz-Target (prefix: StarlingDoveService).diff --git a/ministack/services/cur.py b/ministack/services/cur.pyindex a8440c94..43a2beb0 100644--- a/ministack/services/cur.py+++ b/ministack/services/cur.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""AWS Cost and Usage Report (CUR) service emulator.diff --git a/ministack/services/dsql.py b/ministack/services/dsql.pyindex 0b3bc273..573967b4 100644--- a/ministack/services/dsql.py+++ b/ministack/services/dsql.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""Amazon Aurora DSQL Emulator (control plane + data plane wiring).diff --git a/ministack/services/dynamodb.py b/ministack/services/dynamodb.pyindex 6cd6a391..a202f260 100644--- a/ministack/services/dynamodb.py+++ b/ministack/services/dynamodb.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""DynamoDB Service Emulator.Supports: CreateTable, DeleteTable, DescribeTable, ListTables, UpdateTable,@@ -1338,10 +1340,12 @@ def _update_table(data):table["ProvisionedThroughput"] = {"ReadCapacityUnits": 0, "WriteCapacityUnits": 0}if "AttributeDefinitions" in data:# Merge incoming AttributeDefinitions with existing ones (union by name).- # New definitions override existing ones with the same name.+ # A redeclaration of an existing attribute — even with a conflicting+ # type — is accepted and the STORED type wins; real DynamoDB neither+ # rejects nor overwrites (measured eu-west-2, 2026-07-12, paritysuite).existing_ad = {ad["AttributeName"]: ad for ad in table.get("AttributeDefinitions", [])}for ad in data["AttributeDefinitions"]:- existing_ad[ad["AttributeName"]] = ad+ existing_ad.setdefault(ad["AttributeName"], ad)table["AttributeDefinitions"] = list(existing_ad.values())if "StreamSpecification" in data:stream_spec = data["StreamSpecification"]@@ -1375,7 +1379,10 @@ def _update_table(data):}existing_idx_names = {g["IndexName"] for g in table.get("GlobalSecondaryIndexes", [])}- defined_attrs = {a["AttributeName"] for a in table.get("AttributeDefinitions", [])}+ # A new index's key attributes must all appear in the REQUEST's own+ # AttributeDefinitions — stored definitions do not satisfy the check+ # (measured eu-west-2, 2026-07-12, paritysuite).+ defined_attrs = {a["AttributeName"] for a in data.get("AttributeDefinitions", [])}for update in data.get("GlobalSecondaryIndexUpdates", []):if "Create" in update:gsi_def = copy.deepcopy(update["Create"])@@ -1684,7 +1691,7 @@ def _put_item(data):result = {}if data.get("ReturnValues") == "ALL_OLD" and old_item:result["Attributes"] = old_item- _add_consumed_capacity(result, data, name, write=True)+ _add_consumed_capacity(result, data, name, write=True, old_item=old_item, new_item=item)_add_item_collection_metrics(result, data, table, item, None)return json_response(result)@@ -1774,15 +1781,16 @@ def _delete_item(data):result = {}if data.get("ReturnValues") == "ALL_OLD" and old_item:result["Attributes"] = old_item- _add_consumed_capacity(result, data, name, write=True)+ _add_consumed_capacity(result, data, name, write=True, old_item=old_item)_add_item_collection_metrics(result, data, table, None, key)return json_response(result)def _key_attribute_update_error(table, updated_attrs):"""AWS error for an update whose targets include a hash or range key."""+ tops = {p[0] if isinstance(p, tuple) else p for p in updated_attrs}for key_name in (table.get("pk_name"), table.get("sk_name")):- if key_name and key_name in updated_attrs:+ if key_name and key_name in tops:return error_response_json("ValidationException",f"One or more parameter values were invalid: Cannot update attribute {key_name}. This attribute is part of the key", 400)return None@@ -1896,7 +1904,7 @@ def _update_item(data):if err:return err# Validate GSI/LSI key attribute types and values after the update is applied.- err = _validate_index_key_values(table, item)+ err = _validate_index_key_values(table, item, update_expr=bool(data.get("UpdateExpression")))if err:return err@@ -1920,7 +1928,7 @@ def _update_item(data):new_attrs = _diff_attributes(old_item or {}, item, updated_attrs, return_old=False)if new_attrs:result["Attributes"] = new_attrs- _add_consumed_capacity(result, data, name, write=True)+ _add_consumed_capacity(result, data, name, write=True, old_item=old_item, new_item=item)_add_item_collection_metrics(result, data, table, item, key)return json_response(result)@@ -2013,24 +2021,25 @@ def _query(data):if limit is not None and int(limit) <= 0:return error_response_json("ValidationException","1 validation error detected: Value at 'Limit' failed to satisfy constraint: Member must have value greater than or equal to 1", 400)- # Select validation per AWS: ALL_PROJECTED_ATTRIBUTES is only valid on an- # index; SPECIFIC_ATTRIBUTES requires a ProjectionExpression / AttributesToGet.+ # Select validation per AWS (messages measured against real DynamoDB by+ # paritysuite). A ProjectionExpression with a non-SPECIFIC Select is+ # reported first, even when the IndexName rule is also broken.+ if "Select" in data and data.get("ProjectionExpression"):+ if select == "ALL_ATTRIBUTES":+ return error_response_json("ValidationException",+ "Cannot specify the ProjectionExpression when choosing to get ALL_ATTRIBUTES", 400)+ if select == "COUNT":+ return error_response_json("ValidationException",+ "Cannot specify the ProjectionExpression when choosing to get only the Count", 400)+ if select == "ALL_PROJECTED_ATTRIBUTES":+ return error_response_json("ValidationException",+ "Cannot specify the ProjectionExpression when choosing to get ALL_PROJECTED_ATTRIBUTES", 400)if select == "ALL_PROJECTED_ATTRIBUTES" and not index_name:return error_response_json("ValidationException",- "ALL_PROJECTED_ATTRIBUTES can be used only when Querying an index", 400)+ "ALL_PROJECTED_ATTRIBUTES can be used only when Querying using an IndexName", 400)if select == "SPECIFIC_ATTRIBUTES" and not data.get("ProjectionExpression") and not data.get("AttributesToGet"):return error_response_json("ValidationException","1 validation error detected: Must specify either a ProjectionExpression or non-empty AttributesToGet when Select is SPECIFIC_ATTRIBUTES", 400)- # ALL_ATTRIBUTES or COUNT cannot be combined with ProjectionExpression.- if select in ("ALL_ATTRIBUTES", "COUNT") and data.get("ProjectionExpression"):- return error_response_json("ValidationException",- f"One or more parameter values were invalid: Select value {select} is not compatible with ProjectionExpression", 400)- if select == "ALL_PROJECTED_ATTRIBUTES" and data.get("ProjectionExpression") and not index_name:- return error_response_json("ValidationException",- "Cannot specify the ProjectionExpression when ALL_PROJECTED_ATTRIBUTES Select is used without an index", 400)- if select == "ALL_PROJECTED_ATTRIBUTES" and data.get("ProjectionExpression") and index_name:- return error_response_json("ValidationException",- "Cannot specify the ProjectionExpression when ALL_PROJECTED_ATTRIBUTES Select is used", 400)pk_name, sk_name, is_gsi = _resolve_index_keys(table, index_name)# ConsistentRead on a GSI is invalid (only LSIs support strongly-consistent reads).@@ -2085,6 +2094,10 @@ def _query(data):allowed = {pk_name}if sk_name:allowed.add(sk_name)+ # A document path on a key attribute is rejected up front (AWS).+ if any(tok[0] == "DOT" for tok in kce_tokens):+ return error_response_json("ValidationException",+ "KeyConditionExpressions cannot have conditions on nested attributes", 400)for tok in kce_tokens:if tok[0] == "IDENT":name_ = tok[1]@@ -2219,7 +2232,7 @@ def _query(data):lek.setdefault(k, v)result["LastEvaluatedKey"] = lek- _add_consumed_capacity(result, data, name)+ _add_consumed_capacity(result, data, name, index_name=data.get("IndexName"))return json_response(result)@@ -2314,23 +2327,24 @@ def _scan(data):if seg >= ts:return error_response_json("ValidationException",f"The Segment parameter is zero-based and must be less than parameter TotalSegments: Segment: {seg} is not less than TotalSegments: {ts}", 400)- # Select validation.+ # Select validation per AWS (messages measured against real DynamoDB by+ # paritysuite — Scan reuses the Query-worded IndexName message verbatim).+ if "Select" in data and data.get("ProjectionExpression"):+ if select == "ALL_ATTRIBUTES":+ return error_response_json("ValidationException",+ "Cannot specify the ProjectionExpression when choosing to get ALL_ATTRIBUTES", 400)+ if select == "COUNT":+ return error_response_json("ValidationException",+ "Cannot specify the ProjectionExpression when choosing to get only the Count", 400)+ if select == "ALL_PROJECTED_ATTRIBUTES":+ return error_response_json("ValidationException",+ "Cannot specify the ProjectionExpression when choosing to get ALL_PROJECTED_ATTRIBUTES", 400)if select == "ALL_PROJECTED_ATTRIBUTES" and not index_name:return error_response_json("ValidationException",- "ALL_PROJECTED_ATTRIBUTES can be used only when Scanning an index", 400)+ "ALL_PROJECTED_ATTRIBUTES can be used only when Querying using an IndexName", 400)if select == "SPECIFIC_ATTRIBUTES" and not data.get("ProjectionExpression") and not data.get("AttributesToGet"):return error_response_json("ValidationException","1 validation error detected: Must specify either a ProjectionExpression or non-empty AttributesToGet when Select is SPECIFIC_ATTRIBUTES", 400)- # ALL_ATTRIBUTES or COUNT cannot be combined with ProjectionExpression.- if select in ("ALL_ATTRIBUTES", "COUNT") and data.get("ProjectionExpression"):- return error_response_json("ValidationException",- f"One or more parameter values were invalid: Select value {select} is not compatible with ProjectionExpression", 400)- if select == "ALL_PROJECTED_ATTRIBUTES" and data.get("ProjectionExpression") and not index_name:- return error_response_json("ValidationException",- "ALL_PROJECTED_ATTRIBUTES can be used only when Scanning an index. Cannot specify the ProjectionExpression when ALL_PROJECTED_ATTRIBUTES Select is used without an index", 400)- if select == "ALL_PROJECTED_ATTRIBUTES" and data.get("ProjectionExpression") and index_name:- return error_response_json("ValidationException",- "Cannot specify the ProjectionExpression when ALL_PROJECTED_ATTRIBUTES Select is used", 400)# ConsistentRead on a GSI is invalid.if index_name and data.get("ConsistentRead"):_, _, is_gsi_scan = _resolve_index_keys(table, index_name)@@ -2347,9 +2361,9 @@ def _scan(data):if index_name:pk_name_idx, sk_name_idx, is_gsi = _resolve_index_keys(table, index_name)if is_gsi:- # Sparse GSI semantics: items lacking the index's HASH attribute- # don't appear in the index.- all_items = [it for it in all_items if pk_name_idx in it]+ # Sparse GSI semantics: items lacking ANY of the index's key+ # attributes (hash, or range on a composite GSI) don't appear.+ all_items = [it for it in all_items if pk_name_idx in it and (not sk_name_idx or sk_name_idx in it)]else:# LSI: items lacking the index's RANGE attribute don't appear.if sk_name_idx:@@ -2439,7 +2453,7 @@ def _scan(data):lek.setdefault(k, v)result["LastEvaluatedKey"] = lek- _add_consumed_capacity(result, data, name)+ _add_consumed_capacity(result, data, name, index_name=data.get("IndexName"))return json_response(result)@@ -2467,7 +2481,10 @@ def _execute_statement(data):f"Requested resource not found: Table: {table_name} not found", 400)if op == "SELECT":- status, headers, body = _partiql_select(table, parsed)+ if parsed.get("index"):+ status, headers, body = _partiql_select_index(table, parsed, data)+ else:+ status, headers, body = _partiql_select(table, parsed)elif op == "INSERT":status, headers, body = _partiql_insert(table, parsed)elif op == "UPDATE":@@ -2483,7 +2500,7 @@ def _execute_statement(data):payload = json.loads(body)except (TypeError, ValueError):payload = None- if isinstance(payload, dict):+ if isinstance(payload, dict) and "ConsumedCapacity" not in payload:units = max(1.0, float(len(payload.get("Items", []) or [1])))payload["ConsumedCapacity"] = {"TableName": table_name, "CapacityUnits": units}new_body = json.dumps(payload, ensure_ascii=False).encode("utf-8")@@ -2491,6 +2508,138 @@ def _execute_statement(data):return status, headers, body+def _partiql_select_index(table, parsed, data):+ """Serve SELECT ... FROM "table"."index" per real DynamoDB (paritysuite):+ membership and projection follow the index; an LSI reaches back to the+ base table for unprojected attributes (charged on the table arm per row+ walked) while a GSI rejects them; a keyed read refuses filters on+ unprojected attributes; capacity lands on the index arm; NextTokens are+ bound to the index that minted them."""+ index_name = parsed["index"]+ gsis = {i.get("IndexName"): (i, True) for i in table.get("GlobalSecondaryIndexes", []) or []}+ lsis = {i.get("IndexName"): (i, False) for i in table.get("LocalSecondaryIndexes", []) or []}+ idx, is_gsi = (gsis.get(index_name) or lsis.get(index_name) or (None, None))+ if idx is None:+ return error_response_json("ValidationException",+ f"The table does not have the specified index: {index_name}", 400)++ consistent = bool(data.get("ConsistentRead"))+ if consistent and is_gsi:+ return error_response_json("ValidationException",+ "Consistent reads are not supported on global secondary indexes", 400)+ rate = 1.0 if consistent else 0.5++ key_names = [ks.get("AttributeName") for ks in idx.get("KeySchema", []) or []]+ table_keys = [table.get("pk_name")] + ([table.get("sk_name")] if table.get("sk_name") else [])+ proj = idx.get("Projection") or {}+ ptype = proj.get("ProjectionType", "ALL")+ view_attrs = None # None == ALL+ if ptype != "ALL":+ view_attrs = set(key_names) | set(table_keys)+ if ptype == "INCLUDE":+ view_attrs |= set(proj.get("NonKeyAttributes") or [])++ conditions = parsed.get("conditions") or []+ keyed = any(attr in key_names for attr, _op, _v in conditions)+ if keyed and view_attrs is not None:+ for attr, _op, _v in conditions:+ if attr not in view_attrs:+ return error_response_json("ValidationException",+ f"One or more parameter values were invalid: Filter expression can only contain non-primary key attributes projected into the index: {attr}", 400)++ projections = parsed.get("projections")+ reach_back = False+ if projections and view_attrs is not None:+ unprojected = [a for a in projections if a not in view_attrs]+ if unprojected:+ if is_gsi:+ return error_response_json("ValidationException",+ f"One or more parameter values were invalid: Global secondary index {index_name} does not project {unprojected}", 400)+ reach_back = True++ def _index_view(item):+ if view_attrs is None:+ return dict(item)+ return {k: v for k, v in item.items() if k in view_attrs}++ # Membership + index ordering.+ members = []+ for pk in table["items"]:+ for sk in table["items"][pk]:+ it = table["items"][pk][sk]+ if all(k in it for k in key_names):+ members.append(it)+ def _order_key(it):+ return tuple(json.dumps(it.get(k), sort_keys=True) for k in key_names + table_keys)+ members.sort(key=_order_key)++ # Rows walked = rows matching the key conditions (filters apply later).+ key_conds = [(a, o, v) for a, o, v in conditions if a in key_names]+ walked = [it for it in members+ if all(_eval_partiql_pred(_index_view(it), a, o, v) for a, o, v in key_conds)]++ # Pagination: tokens are bound to the index that minted them.+ offset = 0+ token = data.get("NextToken")+ if token:+ try:+ import base64 as _b64+ tk = json.loads(_b64.b64decode(token).decode("utf-8"))+ assert tk.get("t") == table.get("TableName") and tk.get("i") == index_name+ offset = int(tk.get("o", 0))+ except Exception:+ return error_response_json("ValidationException",+ "The provided NextToken is invalid", 400)+ limit = data.get("Limit")+ page = walked[offset:]+ next_token = None+ if limit is not None and int(limit) < len(page):+ page = page[: int(limit)]+ import base64 as _b64+ next_token = _b64.b64encode(json.dumps(+ {"t": table.get("TableName"), "i": index_name, "o": offset + len(page)}+ ).encode("utf-8")).decode("ascii")++ where_fn = parsed.get("where_fn")+ kept = [it for it in page if (where_fn is None or where_fn(_index_view(it)))]++ items = []+ for it in kept:+ if projections:+ src = it if reach_back else _index_view(it)+ row = {}+ for attr in projections:+ if attr in src:+ row[attr] = src[attr]+ elif ("." in attr or "[" in attr):+ try:+ parts = _partiql_parse_path(attr)+ except ValueError:+ continue+ leaf = _partiql_get_path(src, parts)+ if leaf is not None:+ key = next((seg for seg in reversed(parts) if isinstance(seg, str)), attr)+ row[key] = leaf+ items.append(row)+ else:+ items.append(_index_view(it))++ payload = {"Items": items}+ if next_token:+ payload["NextToken"] = next_token+ rc = data.get("ReturnConsumedCapacity", "NONE")+ if rc != "NONE":+ table_units = rate * len(page) if reach_back else 0.0+ total = rate + table_units+ cap = {"TableName": table.get("TableName"), "CapacityUnits": total}+ if rc == "INDEXES":+ cap["Table"] = {"CapacityUnits": table_units}+ arm = {"GlobalSecondaryIndexes" if is_gsi else "LocalSecondaryIndexes": {index_name: {"CapacityUnits": rate}}}+ cap.update(arm)+ payload["ConsumedCapacity"] = cap+ return 200, {"Content-Type": "application/x-amz-json-1.0"}, json.dumps(payload, ensure_ascii=False).encode("utf-8")++def _partiql_select(table, parsed):all_items = []for pk in sorted(table["items"].keys()):@@ -2510,6 +2659,17 @@ def _partiql_select(table, parsed):for attr in projections:if attr in it:proj[attr] = it[attr]+ elif "." in attr or "[" in attr:+ # Document path: the result column is named by the final+ # path segment (SELECT mymap.nested -> {nested: ...}).+ try:+ parts = _partiql_parse_path(attr)+ except ValueError:+ continue+ leaf = _partiql_get_path(it, parts)+ if leaf is not None:+ key = next((seg for seg in reversed(parts) if isinstance(seg, str)), attr)+ proj[key] = leafprojected.append(proj)filtered = projected@@ -2602,6 +2762,141 @@ def _partiql_key_target(table, parsed):return pk_key, sk_key, non_key_fn, None+def _partiql_parse_path(raw):+ """Parse a PartiQL document path: 'profile.sub' -> ["profile", "sub"],+ 'tags[0]' -> ["tags", 0]. Attribute names may be double-quoted."""+ import re as _re+ parts = []+ for seg in raw.split('.'):+ seg = seg.strip().strip('"')+ m = _re.match(r'^([^\[\]]+)((?:\[\d+\])*)$', seg)+ if not m:+ raise ValueError(f"Invalid document path: {raw}")+ parts.append(m.group(1))+ for idx in _re.findall(r'\[(\d+)\]', m.group(2)):+ parts.append(int(idx))+ return parts+++def _partiql_get_path(item, parts):+ if item is None:+ return None+ node = item.get(parts[0])+ for part in parts[1:]:+ if node is None:+ return None+ if isinstance(part, str):+ node = node.get("M", {}).get(part) if isinstance(node, dict) else None+ else:+ lst = node.get("L") if isinstance(node, dict) else None+ node = lst[part] if lst is not None and part < len(lst) else None+ return node+++def _partiql_walk_parent(item, parts):+ """The AV container holding the leaf of `parts`, or None if the path's+ ancestors don't exist / have the wrong shape."""+ node = None+ for i, part in enumerate(parts[:-1]):+ if i == 0:+ node = item.get(part)+ elif isinstance(part, str):+ node = node["M"].get(part) if (isinstance(node, dict) and "M" in node) else None+ else:+ lst = node.get("L") if isinstance(node, dict) else None+ node = lst[part] if lst is not None and part < len(lst) else None+ if node is None:+ return None+ return node+++_PARTIQL_BAD_PATH = "The document path provided in the update expression is invalid for update"+++def _partiql_set_path(item, parts, val):+ """Apply a SET along a document path. Returns an error message or None.+ A list index at or past the end appends (AWS clamps); a missing ancestor+ (including SET tags[0] on an absent attribute) is rejected, not created."""+ if len(parts) == 1:+ item[parts[0]] = val+ return None+ parent = _partiql_walk_parent(item, parts)+ if parent is None:+ return _PARTIQL_BAD_PATH+ leaf = parts[-1]+ if isinstance(leaf, str):+ if not (isinstance(parent, dict) and "M" in parent):+ return _PARTIQL_BAD_PATH+ parent["M"][leaf] = val+ else:+ if not (isinstance(parent, dict) and "L" in parent):+ return _PARTIQL_BAD_PATH+ lst = parent["L"]+ if leaf < len(lst):+ lst[leaf] = val+ else:+ lst.append(val)+ return None+++def _partiql_remove_path(item, parts):+ """Apply a REMOVE along a document path (missing paths are no-ops)."""+ if len(parts) == 1:+ item.pop(parts[0], None)+ return None+ parent = _partiql_walk_parent(item, parts)+ if parent is None:+ return None+ leaf = parts[-1]+ if isinstance(leaf, str):+ if isinstance(parent, dict) and "M" in parent:+ parent["M"].pop(leaf, None)+ else:+ if isinstance(parent, dict) and "L" in parent and leaf < len(parent["L"]):+ del parent["L"][leaf]+ return None+++def _partiql_modified_items(item_before, item_after, paths, want_old):+ """RETURNING MODIFIED OLD/NEW * per real DynamoDB: only the changed leaf+ comes back — nested map paths as a one-leaf fragment, list indices packed+ densely in ascending index order (measured by paritysuite). Reading the+ post-image at the written path naturally yields the shifted element after+ a list REMOVE and nothing for a clamped out-of-range append."""+ frag = {}+ list_packs = {}+ for parts in paths:+ top = parts[0]+ old_leaf = _partiql_get_path(item_before, parts)+ new_leaf = _partiql_get_path(item_after, parts)+ if old_leaf == new_leaf:+ continue+ leaf = old_leaf if want_old else new_leaf+ if leaf is None:+ continue+ if len(parts) == 1:+ frag[top] = leaf+ elif len(parts) == 2 and isinstance(parts[1], int):+ list_packs.setdefault(top, []).append((parts[1], leaf))+ elif all(isinstance(part, str) for part in parts):+ node = frag.setdefault(top, {"M": {}})+ if not (isinstance(node, dict) and set(node.keys()) == {"M"}):+ continue+ cur = node+ for part in parts[1:-1]:+ cur = cur["M"].setdefault(part, {"M": {}})+ cur["M"][parts[-1]] = leaf+ else:+ src = item_before if want_old else item_after+ v = (src or {}).get(top)+ if v is not None:+ frag[top] = v+ for top, pairs in list_packs.items():+ pairs.sort(key=lambda x: x[0])+ frag[top] = {"L": [leaf for _, leaf in pairs]}+ return [frag] if frag else []++def _build_partiql_returning(item_before, item_after, returning_clause):"""Build the Items list for a RETURNING clause response.@@ -2661,7 +2956,9 @@ def _partiql_update(table, parsed):if not non_key_fn(item):return _conditional_check_failed({}, item)- item_before = copy.deepcopy(item) if returning else None+ item_before = copy.deepcopy(item)+ work = copy.deepcopy(item)+ applied_paths = []for attr, val in set_attrs.items():# Handle arithmetic: {"__partiql_arith": {"attr": "n", "op": "+", "val": {"N": "1"}}}if isinstance(val, dict) and "__partiql_arith" in val:@@ -2669,23 +2966,44 @@ def _partiql_update(table, parsed):src_attr = arith["attr"]op = arith["op"]operand = arith["val"]- cur = item.get(src_attr)+ cur = work.get(src_attr)if cur and "N" in cur and "N" in operand:from decimal import Decimalresult_n = Decimal(cur["N"]) + Decimal(operand["N"]) if op == "+" else Decimal(cur["N"]) - Decimal(operand["N"])- item[attr] = {"N": str(result_n)}+ work[attr] = {"N": str(result_n)}else:- item[attr] = operand # fallback: just set to operand- else:- item[attr] = val+ work[attr] = operand # fallback: just set to operand+ applied_paths.append([attr])+ continue+ try:+ parts = _partiql_parse_path(attr)+ except ValueError as exc:+ return error_response_json("ValidationException", str(exc), 400)+ err_msg = _partiql_set_path(work, parts, val)+ if err_msg:+ return error_response_json("ValidationException", err_msg, 400)+ applied_paths.append(parts)for attr in remove_attrs:- item.pop(attr, None)+ try:+ parts = _partiql_parse_path(attr)+ except ValueError as exc:+ return error_response_json("ValidationException", str(exc), 400)+ _partiql_remove_path(work, parts)+ applied_paths.append(parts)+ # Nothing failed — commit the working copy.+ item.clear()+ item.update(work)item_after = itemif returning:- items_list, ret_err = _build_partiql_returning(item_before, item_after, returning)- if ret_err:- return error_response_json("ValidationException", ret_err, 400)+ r = returning.upper().strip()+ if r in ("MODIFIED OLD *", "MODIFIED NEW *"):+ items_list = _partiql_modified_items(item_before, item_after, applied_paths,+ want_old=(r == "MODIFIED OLD *"))+ elif r == "ALL OLD *":+ items_list = [item_before] if item_before else []+ else:+ items_list = [copy.deepcopy(item_after)]return json_response({"Items": items_list})return json_response({"Items": []})@@ -2701,7 +3019,7 @@ def _partiql_delete(table, parsed):r = returning.upper().strip()if r not in ("ALL OLD *",):return error_response_json("ValidationException",- f"Only RETURNING ALL OLD * is allowed on DELETE statements; got: RETURNING {returning}", 400)+ "Only RETURNING ALL OLD * is allowed in DELETE statements", 400)pk_key, sk_key, non_key_fn, err = _partiql_key_target(table, parsed)if err:@@ -2755,33 +3073,60 @@ def _batch_execute_statement(data):import re as _re_ret_match = _re.search(r'\s+RETURNING\s+', raw_stmt, _re.IGNORECASE)if _ret_match:- # Check if it's a valid RETURNING variant — invalid ones get ValidationError.- _ret_clause = raw_stmt[_ret_match.end():].strip().rstrip(';').strip().upper()+ _ret_orig = raw_stmt[_ret_match.end():].strip().rstrip(';').strip()+ _ret_clause = _ret_orig.upper()_valid_ret = {"ALL OLD *", "ALL NEW *", "MODIFIED OLD *", "MODIFIED NEW *"}- # For DELETE, only ALL OLD * is valid.+ # For DELETE, only ALL OLD * is valid (verbatim AWS message,+ # measured by paritysuite)._is_delete = raw_stmt.strip().upper().startswith("DELETE")if _is_delete and _ret_clause not in ("ALL OLD *",):responses.append({"Error": {"Code": "ValidationError",- "Message": "Only RETURNING ALL OLD * is allowed on DELETE statements"}})+ "Message": f"Invalid returning clause: RETURNING {_ret_orig}. Only RETURNING ALL OLD * is allowed in DELETE statements."}})continueif _ret_clause not in _valid_ret:responses.append({"Error": {"Code": "ValidationError","Message": f"Invalid RETURNING clause: {_ret_clause}"}})continue+ # Parse up front — parse failures and batch-only SELECT constraints are+ # per-member rejections that never reach a table (no TableName echoed,+ # no capacity charged).+ try:+ parsed = _parse_partiql(raw_stmt, stmt.get("Parameters", []))+ except ValueError as exc:+ msg = str(exc)+ if msg.startswith(("Unsupported PartiQL statement", "Could not parse")):+ msg = "Statement wasn't well formed, can't be processed: Expected data manipulation"+ responses.append({"Error": {"Code": "ValidationError", "Message": msg}})+ continue+ if parsed["op"] == "SELECT":+ # A batch SELECT must name the full table primary key with equality,+ # and an index-qualified read is not reachable from a batch at all.+ key_err = None+ tbl = _tables.get(parsed["table"])+ if parsed.get("index"):+ key_err = True+ elif tbl is not None:+ eq_attrs = {attr for attr, op_, _ in (parsed.get("conditions") or []) if op_ == "="}+ need = {tbl.get("pk_name")} | ({tbl.get("sk_name")} if tbl.get("sk_name") else set())+ key_err = not need.issubset(eq_attrs)+ if key_err:+ responses.append({"Error": {"Code": "ValidationError",+ "Message": "Select statements within BatchExecuteStatement must specify the primary key in the where clause"}})+ continuesub = {"Statement": raw_stmt, "Parameters": stmt.get("Parameters", [])}status, _, body = _execute_statement(sub)try:payload = json.loads(body)except (TypeError, ValueError):payload = {}+ ran = Falseif status == 200:- entry: dict = {}+ entry: dict = {"TableName": parsed["table"]}items = payload.get("Items")- if items is not None:- # RETURNING responses: include the item if present- if items:- entry["Item"] = items[0]+ if items:+ entry["Item"] = items[0]responses.append(entry)+ ran = Trueelse:err_code = payload.get("__type", "ValidationException")err_msg = payload.get("message", "")@@ -2792,13 +3137,20 @@ def _batch_execute_statement(data):short = "ValidationError"elif short.endswith("Exception"):short = short[: -len("Exception")]- responses.append({"Error": {"Code": short, "Message": err_msg}})- # Per-table unit attribution.- try:- parsed = _parse_partiql(raw_stmt, stmt.get("Parameters", []))- per_table_units[parsed["table"]] = per_table_units.get(parsed["table"], 0.0) + 1.0- except Exception:- pass+ err_entry: dict = {"Error": {"Code": short, "Message": err_msg}}+ # TableName is echoed only on a member that ran and failed during+ # execution — not on one rejected before it reached its table.+ if short in ("ConditionalCheckFailed", "DuplicateItem"):+ err_entry["TableName"] = parsed["table"]+ ran = True+ responses.append(err_entry)+ if ran:+ # Reads rate by the member's own ConsistentRead; writes cost 1 WCU.+ if parsed["op"] == "SELECT":+ units = 1.0 if stmt.get("ConsistentRead") else 0.5+ else:+ units = 1.0+ per_table_units[parsed["table"]] = per_table_units.get(parsed["table"], 0.0) + unitsresult = {"Responses": responses}if rc != "NONE":result["ConsumedCapacity"] = [@@ -2832,7 +3184,16 @@ def _execute_transaction(data):signature = {k: v for k, v in data.items() if k != "ClientRequestToken"}if prior is not None:if prior.get("signature") == signature:- return json_response(prior.get("response", {}))+ replay = {k: v for k, v in prior.get("response", {}).items() if k != "ConsumedCapacity"}+ if data.get("ReturnConsumedCapacity", "NONE") != "NONE":+ consumed = []+ for tname, sizes in (prior.get("sizes") or {}).items():+ read_units = sum(2.0 * max(1.0, float(-(-sz // 4096))) for sz in sizes)+ consumed.append({"TableName": tname, "CapacityUnits": read_units,+ "ReadCapacityUnits": read_units})+ if consumed:+ replay["ConsumedCapacity"] = consumed+ return json_response(replay)return error_response_json("IdempotentParameterMismatchException","Request token already in use for another request with a different payload", 400)@@ -2846,11 +3207,14 @@ def _execute_transaction(data):import re as _re2if _re2.search(r'\s+RETURNING\s+', statement, _re2.IGNORECASE):return error_response_json("ValidationException",- "RETURNING clause is not supported in TransactStatement", 400)+ "RETURNING clause is not supported in ExecuteTransaction", 400)try:parsed = _parse_partiql(statement, parameters)except ValueError as e:return error_response_json("ValidationException", str(e), 400)+ if parsed.get("op") == "SELECT" and parsed.get("index"):+ return error_response_json("ValidationException",+ "Reads on indices are not supported within transactions", 400)table = _tables.get(parsed["table"])if not table:return error_response_json("ResourceNotFoundException",@@ -2914,15 +3278,31 @@ def _execute_transaction(data):return 400, {"Content-Type": "application/x-amz-json-1.0", "x-amzn-errortype": "TransactionCanceledException"}, bodyresult = {"Responses": responses}+ # Per-table item sizes: a transactional write costs 2 x ceil(size/1KB) WCU,+ # a same-token replay 2 x ceil(size/4KB) RCU (measured, paritysuite).+ txn_sizes: dict = {}+ for parsed, _ in parsed_list:+ tname = parsed["table"]+ tbl = _tables.get(tname)+ sz = 0+ if tbl is not None and parsed["op"] != "SELECT":+ try:+ pk_key, sk_key, _fn, _err = _partiql_key_target(tbl, parsed)+ if _err is None:+ it = tbl["items"].get(pk_key, {}).get(sk_key)+ sz = _item_size_bytes(it) if it else 0+ except Exception:+ sz = 0+ txn_sizes.setdefault(tname, []).append(sz)if rc != "NONE":- per_table: dict[str, float] = {}- for parsed, _ in parsed_list:- per_table[parsed["table"]] = per_table.get(parsed["table"], 0.0) + 2.0- result["ConsumedCapacity"] = [- {"TableName": t, "CapacityUnits": u} for t, u in per_table.items()- ]+ consumed = []+ for tname, sizes in txn_sizes.items():+ write_units = sum(2.0 * _capacity_kb(sz) for sz in sizes)+ consumed.append({"TableName": tname, "CapacityUnits": write_units,+ "WriteCapacityUnits": write_units})+ result["ConsumedCapacity"] = consumedif crt:- _txn_idempotency[crt] = {"signature": signature, "response": result}+ _txn_idempotency[crt] = {"signature": signature, "response": result, "sizes": txn_sizes}return json_response(result)@@ -2947,15 +3327,24 @@ def _parse_partiql_select(s, parameters):import re# SELECT <projections> FROM <table> [WHERE <condition>]m = re.match(- r'SELECT\s+(.*?)\s+FROM\s+"?([A-Za-z0-9_.\-]+)"?(?:\s+WHERE\s+(.+))?$',+ r'SELECT\s+(.*?)\s+FROM\s+("?[A-Za-z0-9_.\-]+"?(?:\s*\.\s*"[A-Za-z0-9_.\-]+")?)(?:\s+WHERE\s+(.+))?$',s, re.IGNORECASE | re.DOTALL,)if not m:raise ValueError(f"Could not parse SELECT statement: {s}")proj_str = m.group(1).strip()- table_name = m.group(2).strip()+ from_str = m.group(2).strip()where_str = m.group(3)+ # FROM "table"."index" — the index qualifier must be quoted, so a plain+ # table name containing dots keeps its existing meaning.+ index_name = None+ qm = re.match(r'^"?([A-Za-z0-9_.\-]+?)"?\s*\.\s*"([A-Za-z0-9_.\-]+)"$', from_str)+ if '"' in from_str and qm:+ table_name = qm.group(1)+ index_name = qm.group(2)+ else:+ table_name = from_str.strip('"')projections = Noneif proj_str != "*":@@ -2964,13 +3353,16 @@ def _parse_partiql_select(s, parameters):where_fn, conditions = (_build_partiql_where(where_str, parameters)if where_str else (None, []))- return {"op": "SELECT", "table": table_name, "projections": projections,- "where_fn": where_fn, "conditions": conditions}+ return {"op": "SELECT", "table": table_name, "index": index_name,+ "projections": projections, "where_fn": where_fn, "conditions": conditions}def _parse_partiql_insert(s, parameters):import re# INSERT INTO <table> VALUE { ... }+ if re.search(r'INTO\s+"[^"]+"\s*\.\s*"', s, re.IGNORECASE):+ raise ValueError(+ "Statement wasn't well formed, can't be processed: FROM clause may only contain a single table name")m = re.match(r"INSERT\s+INTO\s+\"?([A-Za-z0-9_.\-]+)\"?\s+VALUE\s+(.+)$",s, re.IGNORECASE | re.DOTALL,@@ -2996,6 +3388,8 @@ def _parse_partiql_update(s, parameters):returning = ret_match.group(1).strip()s = s[:ret_match.start()].strip()+ if re.match(r'UPDATE\s+"[^"]+"\s*\.\s*"', s, re.IGNORECASE):+ raise ValueError("This operation is not supported on an index")# Try SET ... WHERE form first.m = re.match(r"UPDATE\s+\"?([A-Za-z0-9_.\-]+)\"?\s+SET\s+(.+?)\s+WHERE\s+(.+)$",@@ -3052,6 +3446,8 @@ def _parse_partiql_delete(s, parameters):returning = ret_match.group(1).strip()s = s[:ret_match.start()].strip()+ if re.match(r'DELETE\s+FROM\s+"[^"]+"\s*\.\s*"', s, re.IGNORECASE):+ raise ValueError("This operation is not supported on an index")# DELETE FROM <table> WHERE <condition>m = re.match(r"DELETE\s+FROM\s+\"?([A-Za-z0-9_.\-]+)\"?\s+WHERE\s+(.+)$",@@ -3066,50 +3462,111 @@ def _parse_partiql_delete(s, parameters):"conditions": conditions, "returning": returning}+def _eval_partiql_pred(item, attr, op, val):+ """Evaluate one PartiQL predicate against an item. `op` may carry a+ "NOT:" prefix for a negated comparison."""+ if isinstance(op, str) and op.startswith("NOT:"):+ return not _eval_partiql_pred(item, attr, op[4:], val)+ item_val = item.get(attr)+ if op == "begins_with":+ if item_val is None or not isinstance(item_val, dict) or "S" not in item_val:+ return False+ prefix = val.get("S", "") if isinstance(val, dict) else str(val)+ return item_val["S"].startswith(prefix)+ if op == "not_begins_with":+ if item_val is not None and isinstance(item_val, dict) and "S" in item_val:+ prefix = val.get("S", "") if isinstance(val, dict) else str(val)+ return not item_val["S"].startswith(prefix)+ return True+ if op == "is_missing":+ return item_val is None+ if op == "is_not_missing":+ return item_val is not None+ if op == "IN":+ return item_val is not None and any(_ddb_equals(item_val, v) for v in val)+ return _compare_ddb(item_val, op, val)++def _build_partiql_where(where_str, parameters, param_idx=None):- """Build a predicate function + structural conditions list for a PartiQL WHERE."""+ """Build a predicate function + structural conditions list for a PartiQL+ WHERE. Top-level OR splits into branches (DNF); the conditions list is+ only populated for the single-branch form, which is what key targeting+ and batch key validation consume."""if not where_str or not where_str.strip():return None, []if param_idx is None:param_idx = [0]- conditions = _parse_partiql_conditions(where_str, parameters, param_idx)+ branches = []+ for branch_str in _split_top_level_by_or(where_str):+ b = branch_str.strip()+ # Strip one pair of parens wrapping the whole branch.+ if b.startswith("(") and b.endswith(")"):+ depth = 0+ wraps = True+ for k, ch in enumerate(b):+ if ch == "(":+ depth += 1+ elif ch == ")":+ depth -= 1+ if depth == 0 and k != len(b) - 1:+ wraps = False+ break+ if wraps:+ b = b[1:-1].strip()+ branches.append(_parse_partiql_conditions(b, parameters, param_idx))++ conditions = branches[0] if len(branches) == 1 else []def where_fn(item):- # Fail-fast per predicate (see non_key_fn): a passing condition falls- # through to the next one instead of returning, so every predicate in a- # multi-condition WHERE is evaluated regardless of order.- for attr, op, val in conditions:- item_val = item.get(attr)- if op == "begins_with":- if item_val is None or not isinstance(item_val, dict) or "S" not in item_val:- return False- prefix = val.get("S", "") if isinstance(val, dict) else str(val)- if not item_val["S"].startswith(prefix):- return False- elif op == "not_begins_with":- # missing attribute / non-string → NOT begins_with is True (pass)- if item_val is not None and isinstance(item_val, dict) and "S" in item_val:- prefix = val.get("S", "") if isinstance(val, dict) else str(val)- if item_val["S"].startswith(prefix):- return False- elif op == "is_missing":- if item_val is not None:- return False- elif op == "is_not_missing":- if item_val is None:- return False- elif op == "IN":- if item_val is None or not any(_ddb_equals(item_val, v) for v in val):- return False- else:- if not _compare_ddb(item_val, op, val):- return False- return True+ return any(all(_eval_partiql_pred(item, attr, op, val) for attr, op, val in branch)+ for branch in branches)return where_fn, conditions+def _split_top_level_by_or(s):+ """Split a WHERE string on OR at the top level (respecting parens/quotes)."""+ parts = []+ depth = 0+ in_str = None+ current = []+ i = 0+ s_up = s.upper()+ while i < len(s):+ ch = s[i]+ if in_str:+ current.append(ch)+ if ch == in_str:+ in_str = None+ i += 1+ continue+ if ch in ("'", '"'):+ in_str = ch+ current.append(ch)+ i += 1+ continue+ if ch in ('(', '[', '{'):+ depth += 1+ current.append(ch)+ i += 1+ continue+ if ch in (')', ']', '}'):+ depth -= 1+ current.append(ch)+ i += 1+ continue+ if depth == 0 and s_up[i:i+3] == ' OR' and (i + 3 >= len(s) or s[i+3] == ' '):+ parts.append("".join(current))+ current = []+ i += 3+ continue+ current.append(ch)+ i += 1+ if current:+ parts.append("".join(current))+ return [p.strip() for p in parts if p.strip()]+def _parse_partiql_conditions(where_str, parameters, param_idx):"""Parse WHERE conditions joined by AND. Returns list of (attr, op, ddb_value)."""import re@@ -3152,6 +3609,27 @@ def _parse_partiql_conditions(where_str, parameters, param_idx):for v in _split_top_level(m.group(2), ',')]conditions.append((attr, "IN", vals))continue+ # NOT <comparison> — negated predicate (begins_with has its own form).+ mnot = re.match(r'NOT\s+("?[A-Za-z0-9_.\-]+"?\s*(?:=|<>|!=|<=|>=|<|>).+)$', part, re.IGNORECASE)+ if mnot and not re.match(r'NOT\s+begins_with', part, re.IGNORECASE):+ inner = _parse_partiql_conditions(mnot.group(1), parameters, param_idx)+ for attr_i, op_i, val_i in inner:+ conditions.append((attr_i, f"NOT:{op_i}", val_i))+ continue+ # attr BETWEEN lo AND hi (the inner AND is re-joined by the splitter)+ m = re.match(r'"?([A-Za-z0-9_.\-]+)"?\s+BETWEEN\s+(.+?)\s+AND\s+(.+)$', part, re.IGNORECASE)+ if m:+ attr = m.group(1)+ lo = _parse_partiql_literal(m.group(2).strip(), parameters, param_idx)+ hi = _parse_partiql_literal(m.group(3).strip(), parameters, param_idx)+ for bound in (lo, hi):+ bt = _ddb_type(bound)+ if bt and bt not in ("S", "N", "B"):+ raise ValueError(+ f"Incorrect operand type for operator or function; operator or function: BETWEEN, operand type: {bt}")+ conditions.append((attr, ">=", lo))+ conditions.append((attr, "<=", hi))+ continue# Standard comparisonm = re.match(r'"?([A-Za-z0-9_.\-]+)"?\s*(=|<>|!=|<=|>=|<|>)\s*(.+)$', part)if not m:@@ -3162,6 +3640,13 @@ def _parse_partiql_conditions(where_str, parameters, param_idx):op = '<>'val_str = m.group(3).strip()val = _parse_partiql_literal(val_str, parameters, param_idx)+ if op in ("<", "<=", ">", ">="):+ # Ordering only exists for S / N / B operands; AWS rejects the+ # statement naming the operator as written (measured, paritysuite).+ vt = _ddb_type(val)+ if vt and vt not in ("S", "N", "B"):+ raise ValueError(+ f"Incorrect operand type for operator or function; operator or function: {op}, operand type: {vt}")conditions.append((attr, op, val))return conditions@@ -3198,12 +3683,17 @@ def _split_top_level_by_and(s):current.append(ch)i += 1continue- # Check for AND keyword at depth 0+ # Check for AND keyword at depth 0 — but the AND that separates a+ # BETWEEN's bounds belongs to the BETWEEN, not the conjunction.if depth == 0 and s_up[i:i+4] == ' AND' and (i + 4 >= len(s) or s[i+4] == ' '):- parts.append("".join(current))- current = []- i += 4 # skip " AND"- continue+ cur_up = "".join(current).upper()+ between_pending = (' BETWEEN ' in cur_up+ and ' AND ' not in cur_up.split(' BETWEEN ', 1)[1] + ' ')+ if not between_pending:+ parts.append("".join(current))+ current = []+ i += 4 # skip " AND"+ continuecurrent.append(ch)i += 1if current:@@ -3324,7 +3814,20 @@ def _split_top_level(s, delimiter):# Batch operations# ---------------------------------------------------------------------------+def _accumulate_write_capacity(cap, table, old_item, new_item):+ """Fold one write's table + per-index units into a batch accumulator."""+ old_size = _item_size_bytes(old_item) if old_item else 0+ new_size = _item_size_bytes(new_item) if new_item else 0+ cap["table"] += _capacity_kb(max(old_size, new_size))+ for kind, key in (("GlobalSecondaryIndexes", "gsi"), ("LocalSecondaryIndexes", "lsi")):+ for idx in table.get(kind, []) or []:+ u = _index_write_units(table, idx, old_item, new_item)+ if u:+ cap[key][idx["IndexName"]] = cap[key].get(idx["IndexName"], 0.0) + u++def _batch_write_item(data):+ _batch_capacity: dict = {}request_items = data.get("RequestItems")if not request_items:return error_response_json("ValidationException",@@ -3390,6 +3893,7 @@ def _batch_write_item(data):"Requested resource not found",400,)+ cap = _batch_capacity.setdefault(table_name, {"table": 0.0, "gsi": {}, "lsi": {}})for req in requests:if "PutRequest" in req:item = req["PutRequest"]["Item"]@@ -3402,6 +3906,7 @@ def _batch_write_item(data):old_item = table["items"].get(pk_val, {}).get(sk_val)table["items"][pk_val][sk_val] = item_emit_stream_event(table_name, "MODIFY" if old_item else "INSERT", old_item, item)+ _accumulate_write_capacity(cap, table, old_item, item)elif "DeleteRequest" in req:key = req["DeleteRequest"]["Key"]pk_val, sk_val, key_err = _resolve_table_key_values(table, key, allow_extra=False)@@ -3411,22 +3916,24 @@ def _batch_write_item(data):table["items"].get(pk_val, {}).pop(sk_val, None)if old_item:_emit_stream_event(table_name, "REMOVE", old_item, None)+ _accumulate_write_capacity(cap, table, old_item, None)_update_counts(table)result = {"UnprocessedItems": unprocessed}rc = data.get("ReturnConsumedCapacity", "NONE")if rc != "NONE":consumed = []- for t, reqs in request_items.items():- if t not in _tables:+ for t in request_items:+ cap = _batch_capacity.get(t)+ if cap is None:continue- gsi_count = len(_tables[t].get("GlobalSecondaryIndexes", []))- units = len(reqs) * (1.0 + gsi_count)- entry = {"TableName": t, "CapacityUnits": units}- if rc == "INDEXES" and gsi_count:- entry["GlobalSecondaryIndexes"] = {- gsi["IndexName"]: {"CapacityUnits": float(len(reqs))}- for gsi in _tables[t].get("GlobalSecondaryIndexes", [])- }+ total = cap["table"] + sum(cap["gsi"].values()) + sum(cap["lsi"].values())+ entry = {"TableName": t, "CapacityUnits": total}+ if rc == "INDEXES":+ entry["Table"] = {"CapacityUnits": cap["table"]}+ if cap["gsi"]:+ entry["GlobalSecondaryIndexes"] = {n: {"CapacityUnits": u} for n, u in cap["gsi"].items()}+ if cap["lsi"]:+ entry["LocalSecondaryIndexes"] = {n: {"CapacityUnits": u} for n, u in cap["lsi"].items()}consumed.append(entry)result["ConsumedCapacity"] = consumedreturn json_response(result)@@ -3519,7 +4026,21 @@ def _transact_write_items(data):signature = {k: v for k, v in data.items() if k != "ClientRequestToken"}if prior is not None:if prior.get("signature") == signature:- return json_response(prior.get("response", {}))+ # A same-token replay does not re-apply the writes; AWS reports+ # a transactional READ of the stored result, recomputed against+ # the item sizes (2 x ceil(size/4KB) per item) — measured+ # against real DynamoDB (eu-west-2) by paritysuite.+ replay = {k: v for k, v in prior.get("response", {}).items() if k != "ConsumedCapacity"}+ rc_replay = data.get("ReturnConsumedCapacity", "NONE")+ if rc_replay != "NONE":+ consumed = []+ for tname, sizes in (prior.get("sizes") or {}).items():+ read_units = sum(2.0 * max(1.0, float(-(-sz // 4096))) for sz in sizes)+ consumed.append({"TableName": tname, "CapacityUnits": read_units,+ "ReadCapacityUnits": read_units})+ if consumed:+ replay["ConsumedCapacity"] = consumed+ return json_response(replay)return error_response_json("IdempotentParameterMismatchException","Request token already in use for another request with a different payload", 400)# Member validation across the transaction. AWS validates every member@@ -3553,6 +4074,27 @@ def _transact_write_items(data):item_err = _validate_item(key_src, tbl.get("pk_name"), tbl.get("sk_name"))if item_err:return item_err+ # Empty-string/binary secondary-index key -> top-level+ # ValidationException; wrong-typed index keys instead cancel in+ # Phase 1 (measured against real DynamoDB by paritysuite).+ msg = _index_key_empty_reason(tbl, key_src)+ if msg:+ return error_response_json("ValidationException", msg, 400)+ elif op_type == "Update" and op.get("UpdateExpression"):+ pk_val = _extract_key_val(key_src.get(tbl["pk_name"]))+ sk_val = _extract_key_val(key_src.get(tbl["sk_name"])) if tbl["sk_name"] else "__no_sort__"+ existing = tbl["items"].get(pk_val, {}).get(sk_val)+ probe = copy.deepcopy(existing) if existing else dict(key_src)+ try:+ probe, _ = _apply_update_expression(probe, op.get("UpdateExpression", ""),+ op.get("ExpressionAttributeValues", {}),+ op.get("ExpressionAttributeNames", {}))+ except ValueError:+ probe = None # type errors surface in Phase 1 as cancellations+ if probe is not None:+ msg = _index_key_empty_reason(tbl, probe, update_expr=True)+ if msg:+ return error_response_json("ValidationException", msg, 400)target = (tn,_extract_key_val(key_src.get(tbl.get("pk_name") or "")),_extract_key_val(key_src.get(tbl.get("sk_name") or "")) if tbl.get("sk_name") else None)@@ -3576,6 +4118,11 @@ def _transact_write_items(data):if type_msg:val_reasons[idx] = type_msgcontinue+ if op_type == "Put":+ imsg = _index_key_type_reason(tbl, key_src)+ if imsg:+ val_reasons[idx] = imsg+ continueif op_type == "Update":ue = op.get("UpdateExpression", "")if ue:@@ -3584,9 +4131,13 @@ def _transact_write_items(data):existing = tbl["items"].get(pk_val, {}).get(sk_val)probe = copy.deepcopy(existing) if existing else dict(key_src)try:- _apply_update_expression(probe, ue, op.get("ExpressionAttributeValues", {}), op.get("ExpressionAttributeNames", {}))+ probe, _ = _apply_update_expression(probe, ue, op.get("ExpressionAttributeValues", {}), op.get("ExpressionAttributeNames", {}))except ValueError as exc:val_reasons[idx] = str(exc)+ else:+ imsg = _index_key_type_reason(tbl, probe)+ if imsg:+ val_reasons[idx] = imsgif val_reasons:return _transact_validation_cancel_response(len(items_list), val_reasons)@@ -3613,9 +4164,21 @@ def _transact_write_items(data):if failures:return _transact_cancel_response(len(items_list), failures)+ _txn_write_effects: dict = {}+for transact in items_list:op_type, op = _extract_transact_op(transact)if op is None or op_type == "ConditionCheck":+ # A ConditionCheck writes nothing but still consumes transactional+ # write capacity (2 x ceil(size/1KB), measured by paritysuite).+ if op_type == "ConditionCheck" and op is not None:+ cc_tbl = _tables.get(op.get("TableName", ""))+ if cc_tbl:+ cc_key = op.get("Key", {})+ cc_pk = _extract_key_val(cc_key.get(cc_tbl["pk_name"]))+ cc_sk = _extract_key_val(cc_key.get(cc_tbl["sk_name"])) if cc_tbl["sk_name"] else "__no_sort__"+ cc_ref = cc_tbl["items"].get(cc_pk, {}).get(cc_sk) or cc_key+ _txn_write_effects.setdefault(op.get("TableName", ""), []).append((cc_ref, cc_ref))continuetable_name = op.get("TableName", "")tbl = _tables.get(table_name)@@ -3628,6 +4191,7 @@ def _transact_write_items(data):old_item = tbl["items"].get(pk_val, {}).get(sk_val)tbl["items"][pk_val][sk_val] = item_emit_stream_event(table_name, "MODIFY" if old_item else "INSERT", old_item, item)+ _txn_write_effects.setdefault(table_name, []).append((old_item, item))elif op_type == "Delete":key = op["Key"]pk_val = _extract_key_val(key.get(tbl["pk_name"]))@@ -3636,6 +4200,7 @@ def _transact_write_items(data):tbl["items"].get(pk_val, {}).pop(sk_val, None)if old_item:_emit_stream_event(table_name, "REMOVE", old_item, None)+ _txn_write_effects.setdefault(table_name, []).append((old_item, None))elif op_type == "Update":key = op["Key"]pk_val = _extract_key_val(key.get(tbl["pk_name"]))@@ -3647,31 +4212,47 @@ def _transact_write_items(data):item, _ = _apply_update_expression(item, ue, op.get("ExpressionAttributeValues", {}), op.get("ExpressionAttributeNames", {}))tbl["items"][pk_val][sk_val] = item_emit_stream_event(table_name, "MODIFY" if old_item else "INSERT", old_item, item)+ _txn_write_effects.setdefault(table_name, []).append((old_item, item))_update_counts(tbl)- # ConsumedCapacity (2 units per item for transactions).+ # ConsumedCapacity: a transactional write costs 2 x ceil(size/1KB) WCU per+ # item on the table (measured against real DynamoDB, eu-west-2, by+ # paritysuite); index replication is asynchronous, so index arms carry the+ # standard 1x units.result = {}+ txn_sizes: dict = {}rc = data.get("ReturnConsumedCapacity", "NONE")- if rc != "NONE":- per_table_units: dict[str, float] = {}- for transact in items_list:- op_type, op = _extract_transact_op(transact)- if op is None:- continue- tname = op.get("TableName", "")- per_table_units[tname] = per_table_units.get(tname, 0.0) + 2.0- consumed = []- for tname, units in per_table_units.items():- entry = {"TableName": tname, "CapacityUnits": units, "WriteCapacityUnits": units}- if rc == "INDEXES" and _tables.get(tname, {}).get("GlobalSecondaryIndexes"):- entry["GlobalSecondaryIndexes"] = {- gsi["IndexName"]: {"CapacityUnits": units, "WriteCapacityUnits": units}- for gsi in _tables[tname].get("GlobalSecondaryIndexes", [])- }+ consumed = []+ for tname, effects in _txn_write_effects.items():+ tbl = _tables.get(tname, {})+ sizes = []+ write_units = 0.0+ gsi_units: dict = {}+ lsi_units: dict = {}+ for old_it, new_it in effects:+ sz = max(_item_size_bytes(old_it) if old_it else 0,+ _item_size_bytes(new_it) if new_it else 0)+ sizes.append(sz)+ write_units += 2.0 * _capacity_kb(sz)+ for kind, acc in (("GlobalSecondaryIndexes", gsi_units), ("LocalSecondaryIndexes", lsi_units)):+ for idx in tbl.get(kind, []) or []:+ u = _index_write_units(tbl, idx, old_it, new_it)+ if u:+ acc[idx["IndexName"]] = acc.get(idx["IndexName"], 0.0) + u+ txn_sizes[tname] = sizes+ if rc != "NONE":+ total = write_units + sum(gsi_units.values()) + sum(lsi_units.values())+ entry = {"TableName": tname, "CapacityUnits": total, "WriteCapacityUnits": write_units}+ if rc == "INDEXES":+ if gsi_units:+ entry["GlobalSecondaryIndexes"] = {n: {"CapacityUnits": u, "WriteCapacityUnits": u} for n, u in gsi_units.items()}+ if lsi_units:+ entry["LocalSecondaryIndexes"] = {n: {"CapacityUnits": u, "WriteCapacityUnits": u} for n, u in lsi_units.items()}consumed.append(entry)+ if rc != "NONE" and consumed:result["ConsumedCapacity"] = consumedif crt:- _txn_idempotency[crt] = {"signature": signature, "response": result}+ _txn_idempotency[crt] = {"signature": signature, "response": result, "sizes": txn_sizes}return json_response(result)@@ -5334,7 +5915,7 @@ def _apply_set(item, tokens, attr_values, attr_names, updated_attrs):f"The document path provided in the update expression is invalid for update: {'.'.join(str(p) for p in path_parts[:-1])}")pending.append((path_parts, value))- updated_attrs.add(path_parts[0])+ updated_attrs.add(tuple(path_parts))for path_parts, value in pending:_set_at_path(item, path_parts, value)@@ -5424,7 +6005,7 @@ def _apply_remove(item, tokens, attr_names, updated_attrs):for path_tokens in _split_by_comma(tokens):path = _parse_path_from_tokens(path_tokens, attr_names)if path:- updated_attrs.add(path[0])+ updated_attrs.add(tuple(path))_remove_at_path(item, path)@@ -5454,7 +6035,7 @@ def _apply_add(item, tokens, attr_values, attr_names, updated_attrs):add_val = attr_values.get(part[val_idx][1])if not path or add_val is None:continue- updated_attrs.add(path[0])+ updated_attrs.add(tuple(path))# ADD only accepts Number and set operands (parse-time in AWS), and the# existing attribute must carry the same type (runtime in AWS).@@ -5495,7 +6076,7 @@ def _apply_delete(item, tokens, attr_values, attr_names, updated_attrs):del_val = attr_values.get(part[val_idx][1])if not path or del_val is None:continue- updated_attrs.add(path[0])+ updated_attrs.add(tuple(path))# DELETE only accepts set operands (parse-time in AWS), and the# existing attribute must be a set of the same type (runtime in AWS).@@ -5729,10 +6310,33 @@ def _ddb_comparable(val):if "SS" in val:return ("SS", frozenset(val["SS"]))if "NS" in val:- return ("NS", frozenset(val["NS"]))+ return ("NS", frozenset(_canonical_number(n) for n in val["NS"]))if "BS" in val:- return ("BS", frozenset(val["BS"]))- return ("UNKNOWN", None)+ return ("BS", frozenset(_canonical_binary(b) for b in val["BS"]))+ if "L" in val:+ # Lists compare element-wise, in order.+ return ("L", tuple(_ddb_comparable(el) for el in val["L"]))+ if "M" in val:+ # Maps compare by content, not key arrival order.+ return ("M", tuple(sorted((k, _ddb_comparable(v)) for k, v in val["M"].items())))+ return ("UNKNOWN", object())+++def _canonical_number(n):+ try:+ return Decimal(n)+ except (InvalidOperation, TypeError, ValueError):+ return Decimal(0)+++def _canonical_binary(b):+ if isinstance(b, bytes):+ return b+ try:+ import base64+ return base64.b64decode(b)+ except Exception:+ return b if isinstance(b, str) else b""def _ddb_equals(a, b):@@ -5821,42 +6425,72 @@ def _key_schema_validation_error():return error_response_json("ValidationException", "The provided key element does not match the schema", 400)-def _validate_index_key_values(table: dict, item: dict) -> tuple | None:- """Validate that any GSI/LSI key attributes present in `item` have the- correct type and are not empty. AWS rejects puts/updates that would write- a wrong-typed, non-scalar, or empty-string/binary value into a secondary- index key attribute. Items missing a GSI key attribute entirely are fine —- they just won't appear in that sparse GSI."""+def _index_key_type_reason(table: dict, item: dict) -> str | None:+ """AWS's type-mismatch message for a wrong-typed / non-scalar secondary+ index key attribute in `item`, or None. Used both as a top-level+ ValidationException (single writes) and as a per-item TransactionCanceled+ ValidationError reason (transactions)."""attr_defs = {ad["AttributeName"]: ad["AttributeType"]for ad in (table.get("AttributeDefinitions") or [])}for idx in (table.get("GlobalSecondaryIndexes") or []) + (table.get("LocalSecondaryIndexes") or []):+ idx_name = idx.get("IndexName")for ks in (idx.get("KeySchema") or []):key_name = ks.get("AttributeName")if not key_name or key_name not in item:- continue # sparse index — item simply won't appear in this index+ continueexpected_type = attr_defs.get(key_name)if not expected_type:continueraw = item[key_name]if not isinstance(raw, dict) or len(raw) != 1:- return error_response_json("ValidationException",- f"One or more parameter values were invalid: Type mismatch for Index Key {key_name} Expected: {expected_type} Actual: map", 400)+ return f"One or more parameter values were invalid: Type mismatch for Index Key {key_name} Expected: {expected_type} Actual: map IndexName: {idx_name}"actual_type = next(iter(raw))- # Must be a scalar type (S, N, B) — not SS, NS, BS, L, M, BOOL, NULL- if actual_type not in ("S", "N", "B"):- return error_response_json("ValidationException",- f"One or more parameter values were invalid: Type mismatch for Index Key {key_name} Expected: {expected_type} Actual: {actual_type}", 400)if actual_type != expected_type:- return error_response_json("ValidationException",- f"One or more parameter values were invalid: Type mismatch for Index Key {key_name} Expected: {expected_type} Actual: {actual_type}", 400)- # Reject empty string/binary for index keys- err = _empty_key_value_error(key_name, raw)- if err:- return error_response_json("ValidationException",- "One or more parameter values were invalid: Condition parameter type does not match schema type", 400)+ return f"One or more parameter values were invalid: Type mismatch for Index Key {key_name} Expected: {expected_type} Actual: {actual_type} IndexName: {idx_name}"return None+def _index_key_empty_reason(table: dict, item: dict, update_expr: bool = False) -> str | None:+ """AWS's empty-value message for a secondary index key attribute in `item`+ holding an empty string/binary, or None. UpdateItem words it differently+ and omits the index name (measured by paritysuite, 2026-06-23)."""+ attr_defs = {ad["AttributeName"]: ad["AttributeType"]+ for ad in (table.get("AttributeDefinitions") or [])}+ for idx in (table.get("GlobalSecondaryIndexes") or []) + (table.get("LocalSecondaryIndexes") or []):+ idx_name = idx.get("IndexName")+ for ks in (idx.get("KeySchema") or []):+ key_name = ks.get("AttributeName")+ if not key_name or key_name not in item:+ continue+ expected_type = attr_defs.get(key_name)+ raw = item[key_name]+ if not isinstance(raw, dict) or len(raw) != 1:+ continue+ actual_type = next(iter(raw))+ if actual_type != expected_type:+ continue+ if (actual_type == "S" and raw.get("S") == "") or (actual_type == "B" and not raw.get("B")):+ kind = "string" if actual_type == "S" else "binary"+ if update_expr:+ return f"One or more parameter values are not valid. The update expression attempted to update a secondary index key to a value that is not supported. The AttributeValue for a key attribute cannot contain an empty {kind} value."+ return f"One or more parameter values are not valid. A value specified for a secondary index key is not supported. The AttributeValue for a key attribute cannot contain an empty {kind} value. IndexName: {idx_name}, IndexKey: {key_name}"+ return None+++def _validate_index_key_values(table: dict, item: dict, update_expr: bool = False) -> tuple | None:+ """Validate that any GSI/LSI key attributes present in `item` have the+ correct type and are not empty. AWS rejects puts/updates that would write+ a wrong-typed, non-scalar, or empty-string/binary value into a secondary+ index key attribute. Items missing a GSI key attribute entirely are fine —+ they just won't appear in that sparse GSI."""+ msg = _index_key_type_reason(table, item)+ if msg:+ return error_response_json("ValidationException", msg, 400)+ msg = _index_key_empty_reason(table, item, update_expr=update_expr)+ if msg:+ return error_response_json("ValidationException", msg, 400)+ return None+def _key_type_mismatch_reason(table, attrs):"""Return the AWS message for a key attribute present with the wrong type,else None. Unlike an empty key value (which real AWS rejects up front with a@@ -6626,27 +7260,100 @@ def _evaluate_key_conditions_item(item, key_conditions, pk_name):return True-def _add_consumed_capacity(result, data, table_name, write=False):+def _capacity_kb(nbytes: int) -> float:+ """Write units for an entry of `nbytes` bytes: 1 WCU per started KB."""+ return max(1.0, float(-(-nbytes // 1024)))+++def _index_write_view(table, idx, item):+ """The (key signature, projected view) of `item` in index `idx`, or None+ when the item is absent from the index (missing an index key attribute)."""+ if not item:+ return None+ key_names = [ks.get("AttributeName") for ks in idx.get("KeySchema", []) or []]+ for k in key_names:+ if k not in item:+ return None+ proj = idx.get("Projection") or {}+ ptype = proj.get("ProjectionType", "ALL")+ if ptype == "ALL":+ view = dict(item)+ else:+ view = {}+ table_keys = [table.get("pk_name")] + ([table.get("sk_name")] if table.get("sk_name") else [])+ for k in list(key_names) + table_keys:+ if k and k in item:+ view[k] = item[k]+ if ptype == "INCLUDE":+ for k in proj.get("NonKeyAttributes") or []:+ if k in item:+ view[k] = item[k]+ key_sig = json.dumps([item.get(k) for k in key_names], sort_keys=True)+ return key_sig, view+++def _index_write_units(table, idx, old_item, new_item):+ """Write units a Put/Update/Delete costs one index, per real DynamoDB:+ nothing when the index's stored view is unchanged, one write to insert or+ delete an entry or rewrite it in place, two (delete + insert) when the+ index key changes so the entry moves."""+ ov = _index_write_view(table, idx, old_item)+ nv = _index_write_view(table, idx, new_item)+ if ov is None and nv is None:+ return 0.0+ if ov is None:+ return _capacity_kb(_item_size_bytes(nv[1]))+ if nv is None:+ return _capacity_kb(_item_size_bytes(ov[1]))+ if ov[0] != nv[0]:+ return _capacity_kb(_item_size_bytes(ov[1])) + _capacity_kb(_item_size_bytes(nv[1]))+ if ov[1] == nv[1]:+ return 0.0+ return max(_capacity_kb(_item_size_bytes(ov[1])), _capacity_kb(_item_size_bytes(nv[1])))+++def _add_consumed_capacity(result, data, table_name, write=False, old_item=None,+ new_item=None, index_name=None):rc = data.get("ReturnConsumedCapacity", "NONE")if rc == "NONE":returntable = _tables.get(table_name, {})- gsi_count = len(table.get("GlobalSecondaryIndexes", [])) if write else 0- # Eventually-consistent reads (ConsistentRead not set or False) cost 0.5 RCU;- # strongly-consistent reads cost 1.0 RCU. Writes always cost 1.0 WCU.+ gsi_units: dict = {}+ lsi_units: dict = {}if write:- units = 1.0 + gsi_count+ old_size = _item_size_bytes(old_item) if old_item else 0+ new_size = _item_size_bytes(new_item) if new_item else 0+ table_units = _capacity_kb(max(old_size, new_size))+ for idx in table.get("GlobalSecondaryIndexes", []) or []:+ u = _index_write_units(table, idx, old_item, new_item)+ if u:+ gsi_units[idx["IndexName"]] = u+ for idx in table.get("LocalSecondaryIndexes", []) or []:+ u = _index_write_units(table, idx, old_item, new_item)+ if u:+ lsi_units[idx["IndexName"]] = uelse:+ # Eventually-consistent reads cost 0.5 RCU; strongly-consistent 1.0.consistent = data.get("ConsistentRead", False)- units = 1.0 if consistent else 0.5- cap = {"TableName": table_name, "CapacityUnits": units}+ table_units = 1.0 if consistent else 0.5+ if index_name:+ # The index carries the read; the base table's share is 0.+ names_gsi = {i.get("IndexName") for i in table.get("GlobalSecondaryIndexes", []) or []}+ names_lsi = {i.get("IndexName") for i in table.get("LocalSecondaryIndexes", []) or []}+ if index_name in names_gsi:+ gsi_units[index_name] = table_units+ table_units = 0.0+ elif index_name in names_lsi:+ lsi_units[index_name] = table_units+ table_units = 0.0+ total = table_units + sum(gsi_units.values()) + sum(lsi_units.values())+ cap = {"TableName": table_name, "CapacityUnits": total}if rc == "INDEXES":- cap["Table"] = {"CapacityUnits": units}- if write and gsi_count:- cap["GlobalSecondaryIndexes"] = {- gsi["IndexName"]: {"CapacityUnits": 1.0}- for gsi in table.get("GlobalSecondaryIndexes", [])- }+ cap["Table"] = {"CapacityUnits": table_units}+ if gsi_units:+ cap["GlobalSecondaryIndexes"] = {n: {"CapacityUnits": u} for n, u in gsi_units.items()}+ if lsi_units:+ cap["LocalSecondaryIndexes"] = {n: {"CapacityUnits": u} for n, u in lsi_units.items()}result["ConsumedCapacity"] = cap@@ -6674,16 +7381,31 @@ def _diff_attributes(old_item, new_item, updated_attrs, return_old=True):removals where there is no new value (per AWS, REMOVE-only updates withUPDATED_NEW omit Attributes entirely)."""+ src = old_item if return_old else new_itemresult = {}- for k in updated_attrs:- if return_old:- v = old_item.get(k)+ for path in updated_attrs:+ if isinstance(path, str):+ path = (path,)+ top = path[0]+ # Whole-attribute update, or a path with list indices: return the+ # top-level attribute (AWS only fragments plain map paths).+ if len(path) == 1 or not all(isinstance(part, str) for part in path):+ v = src.get(top)if v is not None:- result[k] = v- else:- v = new_item.get(k)- if v is not None:- result[k] = v+ result[top] = v+ continue+ # Nested map path: AWS returns only the changed fragment, e.g.+ # SET parent.child = :v with UPDATED_NEW -> {parent: {M: {child: v}}}.+ v = _get_at_path(src, list(path))+ if v is None:+ continue+ node = result.setdefault(top, {"M": {}})+ if not (isinstance(node, dict) and set(node.keys()) == {"M"}):+ continue # whole attribute already reported+ cur = node+ for part in path[1:-1]:+ cur = cur["M"].setdefault(part, {"M": {}})+ cur["M"][path[-1]] = vreturn resultdiff --git a/ministack/services/dynamodb_streams.py b/ministack/services/dynamodb_streams.pyindex 3edaf46e..7f315155 100644--- a/ministack/services/dynamodb_streams.py+++ b/ministack/services/dynamodb_streams.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""DynamoDB Streams Emulator.Supports: ListStreams, DescribeStream, GetShardIterator, GetRecords.diff --git a/ministack/services/ec2.py b/ministack/services/ec2.pyindex 1116be0b..a99dbc3f 100644--- a/ministack/services/ec2.py+++ b/ministack/services/ec2.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""EC2 Service Emulator.Query API (Action=...) — instances exist in memory only, no real VMs launched.diff --git a/ministack/services/ecr.py b/ministack/services/ecr.pyindex 73beafa5..12fabb0a 100644--- a/ministack/services/ecr.py+++ b/ministack/services/ecr.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""ECR (Elastic Container Registry) Emulator.JSON-based API via X-Amz-Target (prefix: AmazonEC2ContainerRegistry_V20150921).diff --git a/ministack/services/ecs.py b/ministack/services/ecs.pyindex ca7e8879..fb957661 100644--- a/ministack/services/ecs.py+++ b/ministack/services/ecs.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""ECS (Elastic Container Service) Emulator.REST JSON API — X-Amz-Target header routing with path-based fallback.diff --git a/ministack/services/ecs_metadata.py b/ministack/services/ecs_metadata.pyindex 1867a6bb..25ca2259 100644--- a/ministack/services/ecs_metadata.py+++ b/ministack/services/ecs_metadata.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""ECS Task Metadata V4 emulator.Real ECS injects ECS_CONTAINER_METADATA_URI_V4=http://169.254.170.2/v4/<token>diff --git a/ministack/services/efs.py b/ministack/services/efs.pyindex 17244197..e98bb96f 100644--- a/ministack/services/efs.py+++ b/ministack/services/efs.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""EFS (Elastic File System) Service Emulator.REST/JSON protocol — /2015-02-01/* paths.diff --git a/ministack/services/eks.py b/ministack/services/eks.pyindex d56ddfa3..4f8cf0a0 100644--- a/ministack/services/eks.py+++ b/ministack/services/eks.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""EKS Service Emulator.REST/JSON protocol — /clusters/* and /clusters/*/node-groups/* paths.diff --git a/ministack/services/elasticache.py b/ministack/services/elasticache.pyindex 8d83e8a7..fb50c3df 100644--- a/ministack/services/elasticache.py+++ b/ministack/services/elasticache.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""ElastiCache Service Emulator.Query API (Action=...) for control plane.diff --git a/ministack/services/emr.py b/ministack/services/emr.pyindex f8f67941..5d830e40 100644--- a/ministack/services/emr.py+++ b/ministack/services/emr.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""EMR (Elastic MapReduce) Service Emulator.JSON protocol via X-Amz-Target: ElasticMapReduce.{Operation}diff --git a/ministack/services/eventbridge.py b/ministack/services/eventbridge.pyindex ead12f68..6e329996 100644--- a/ministack/services/eventbridge.py+++ b/ministack/services/eventbridge.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""EventBridge Service Emulator.JSON-based API via X-Amz-Target (AmazonEventBridge / AWSEvents).diff --git a/ministack/services/firehose.py b/ministack/services/firehose.pyindex 1ff682b3..090757f2 100644--- a/ministack/services/firehose.py+++ b/ministack/services/firehose.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""Amazon Data Firehose (formerly Kinesis Data Firehose) Emulator.JSON-based API via X-Amz-Target (Firehose_20150804).diff --git a/ministack/services/glue.py b/ministack/services/glue.pyindex 7ee52bdc..b7012819 100644--- a/ministack/services/glue.py+++ b/ministack/services/glue.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""Glue Service Emulator.JSON-based API via X-Amz-Target (AWSGlue).diff --git a/ministack/services/iam.py b/ministack/services/iam.pyindex 953143a1..5a1553d6 100644--- a/ministack/services/iam.py+++ b/ministack/services/iam.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""IAM Service Emulator (AWS-compatible).diff --git a/ministack/services/imds.py b/ministack/services/imds.pyindex 8c694246..24f95ee9 100644--- a/ministack/services/imds.py+++ b/ministack/services/imds.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""EC2 Instance Metadata Service (IMDS) emulator.diff --git a/ministack/services/inspector2.py b/ministack/services/inspector2.pyindex f440172c..34ab1114 100644--- a/ministack/services/inspector2.py+++ b/ministack/services/inspector2.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""Amazon Inspector2 Emulator.REST-JSON API with deterministic stub vulnerability findings.diff --git a/ministack/services/iot.py b/ministack/services/iot.pyindex d9840c5a..8b5bf06c 100644--- a/ministack/services/iot.py+++ b/ministack/services/iot.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""AWS IoT Core control plane emulator.Implements the JSON/REST APIs under ``iot.{region}.amazonaws.com``:diff --git a/ministack/services/iot_data.py b/ministack/services/iot_data.pyindex bf82249b..9a6b10f8 100644--- a/ministack/services/iot_data.py+++ b/ministack/services/iot_data.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""IoT Data Plane HTTP API (``iot-data`` AWS service).Implements the HTTP-side of the AWS IoT Data Plane. The data plane mirrorsdiff --git a/ministack/services/iot_jobs_data.py b/ministack/services/iot_jobs_data.pyindex d35e55d5..359bc4e7 100644--- a/ministack/services/iot_jobs_data.py+++ b/ministack/services/iot_jobs_data.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""IoT Jobs Data Plane HTTP API (``iot-jobs-data`` AWS service).Implements the device-side REST surface of AWS IoT Jobs:diff --git a/ministack/services/kinesis.py b/ministack/services/kinesis.pyindex ba367a3d..d9e2ceda 100644--- a/ministack/services/kinesis.py+++ b/ministack/services/kinesis.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""Kinesis Data Streams Emulator.JSON-based API via X-Amz-Target (Kinesis_20131202).diff --git a/ministack/services/kms.py b/ministack/services/kms.pyindex 599f4246..746e415e 100644--- a/ministack/services/kms.py+++ b/ministack/services/kms.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""KMS (Key Management Service) Emulator.JSON-based API via X-Amz-Target (prefix: TrentService).diff --git a/ministack/services/lambda_durable.py b/ministack/services/lambda_durable.pyindex 3baaa74a..ee92f614 100644--- a/ministack/services/lambda_durable.py+++ b/ministack/services/lambda_durable.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""AWS Lambda Durable Functions / Durable Execution emulator.Implements the seven management-plane operations of the Lambda Durable Executiondiff --git a/ministack/services/lambda_microvms.py b/ministack/services/lambda_microvms.pyindex 04453358..795d5c9d 100644--- a/ministack/services/lambda_microvms.py+++ b/ministack/services/lambda_microvms.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""AWS Lambda MicroVMs emulation (REST-JSON, API version 2025-09-09).Control-plane emulation of the Lambda MicroVM API: build images, run MicroVMs,diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.pyindex 0942fc1e..be78e8b5 100644--- a/ministack/services/lambda_svc.py+++ b/ministack/services/lambda_svc.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""Lambda Service Emulator.Supports: CreateFunction, DeleteFunction, GetFunction, GetFunctionConfiguration,diff --git a/ministack/services/mediaconnect.py b/ministack/services/mediaconnect.pyindex c4299417..ed14bab4 100644--- a/ministack/services/mediaconnect.py+++ b/ministack/services/mediaconnect.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""AWS Elemental MediaConnect service emulator.REST/JSON protocol — /v1/flows/* and /tags/* paths.diff --git a/ministack/services/mq.py b/ministack/services/mq.pyindex 927248c9..0e6f81e6 100644--- a/ministack/services/mq.py+++ b/ministack/services/mq.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""AmazonMQ Service Emulator.This module provides a mock implementation of AWS MQ (Message Broker) service,diff --git a/ministack/services/msk.py b/ministack/services/msk.pyindex a26d1058..f48b0018 100644--- a/ministack/services/msk.py+++ b/ministack/services/msk.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""Amazon MSK (Managed Streaming for Apache Kafka) Service Emulator.REST/JSON protocol — signing name: kafka. Endpoint prefix: kafka.diff --git a/ministack/services/mwaa.py b/ministack/services/mwaa.pyindex 8f432f0f..cd4bb49e 100644--- a/ministack/services/mwaa.py+++ b/ministack/services/mwaa.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""MWAA (Managed Workflows for Apache Airflow) Service Emulator.REST API (path-based routing) for the MWAA control plane.diff --git a/ministack/services/opensearch.py b/ministack/services/opensearch.pyindex af90e718..563c33ea 100644--- a/ministack/services/opensearch.py+++ b/ministack/services/opensearch.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""Amazon OpenSearch Service emulator.diff --git a/ministack/services/organizations.py b/ministack/services/organizations.pyindex 4f3021f7..9568122a 100644--- a/ministack/services/organizations.py+++ b/ministack/services/organizations.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""AWS Organizations stub.diff --git a/ministack/services/pipes.py b/ministack/services/pipes.pyindex 0be90b96..f75a3b76 100644--- a/ministack/services/pipes.py+++ b/ministack/services/pipes.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""EventBridge Pipes service emulator.diff --git a/ministack/services/rds.py b/ministack/services/rds.pyindex 6c0eff8e..654d14c0 100644--- a/ministack/services/rds.py+++ b/ministack/services/rds.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""RDS Service Emulator.Query API (Action=...) for control plane + optional Docker-based real Postgres/MySQL.diff --git a/ministack/services/rds_data.py b/ministack/services/rds_data.pyindex f881f837..95d0ccc7 100644--- a/ministack/services/rds_data.py+++ b/ministack/services/rds_data.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""RDS Data API Service Emulator.REST-style JSON API (POST /Execute, /BeginTransaction, etc.)diff --git a/ministack/services/rds_iam_plugin.py b/ministack/services/rds_iam_plugin.pyindex 65a55494..5ce84397 100644--- a/ministack/services/rds_iam_plugin.py+++ b/ministack/services/rds_iam_plugin.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""Best-effort delivery of MiniStack's Aurora MySQL IAM auth plugin."""import iodiff --git a/ministack/services/rds_mysql_compat.py b/ministack/services/rds_mysql_compat.pyindex b086f8d3..227ada4b 100644--- a/ministack/services/rds_mysql_compat.py+++ b/ministack/services/rds_mysql_compat.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""Aurora MySQL compatibility objects installed on MiniStack compute."""import loggingdiff --git a/ministack/services/resource_groups.py b/ministack/services/resource_groups.pyindex 905cfe1b..3c0910b5 100644--- a/ministack/services/resource_groups.py+++ b/ministack/services/resource_groups.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""AWS Resource Groups (resource-groups, apiVersion 2017-11-27) emulator.REST/JSON. Routes, methods, and shapes match the AWS spec.diff --git a/ministack/services/route53.py b/ministack/services/route53.pyindex 785bbf63..93ea7d13 100644--- a/ministack/services/route53.py+++ b/ministack/services/route53.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""Amazon Route 53 Emulator.REST/XML API — service credential scope: route53.diff --git a/ministack/services/s3.py b/ministack/services/s3.pyindex 45c8e421..bb85fc19 100644--- a/ministack/services/s3.py+++ b/ministack/services/s3.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""S3 Service Emulator – AWS-compatible.Supports: CreateBucket, DeleteBucket, ListBuckets, HeadBucket,diff --git a/ministack/services/s3files.py b/ministack/services/s3files.pyindex 0a0cad46..bb8dfea7 100644--- a/ministack/services/s3files.py+++ b/ministack/services/s3files.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""Amazon S3 Files Service Emulator (s3files-2025-05-05).REST/JSON API. Routes, payloads, and response shapes match the AWS spec.diff --git a/ministack/services/s3tables.py b/ministack/services/s3tables.pyindex f46dea3a..c41ef84a 100644--- a/ministack/services/s3tables.py+++ b/ministack/services/s3tables.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""S3 Tables Service Emulator.diff --git a/ministack/services/scheduler.py b/ministack/services/scheduler.pyindex 59315d51..22638860 100644--- a/ministack/services/scheduler.py+++ b/ministack/services/scheduler.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""EventBridge Scheduler Service Emulator.REST/JSON protocol — /schedules/* and /schedule-groups/* paths.diff --git a/ministack/services/secretsmanager.py b/ministack/services/secretsmanager.pyindex 75fefa70..72efcca0 100644--- a/ministack/services/secretsmanager.py+++ b/ministack/services/secretsmanager.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""SecretsManager Service Emulator.JSON-based API via X-Amz-Target.diff --git a/ministack/services/servicediscovery.py b/ministack/services/servicediscovery.pyindex 0faeafe7..62dc2b8e 100644--- a/ministack/services/servicediscovery.py+++ b/ministack/services/servicediscovery.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""AWS Cloud Map (Service Discovery) emulator.JSON-based API via X-Amz-Target: Route53AutoNaming_v20170314.diff --git a/ministack/services/ses.py b/ministack/services/ses.pyindex 52617dc8..02484956 100644--- a/ministack/services/ses.py+++ b/ministack/services/ses.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""SES (Simple Email Service) Emulator — v1 Query API + v2 REST/JSON API.diff --git a/ministack/services/ses_v2.py b/ministack/services/ses_v2.pyindex 945c3a79..9f1a5d7c 100644--- a/ministack/services/ses_v2.py+++ b/ministack/services/ses_v2.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""SES v2 Service Emulator.REST/JSON API via path /v2/email/...diff --git a/ministack/services/sns.py b/ministack/services/sns.pyindex b9fc5590..1b855d8e 100644--- a/ministack/services/sns.py+++ b/ministack/services/sns.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""SNS Service Emulator — AWS-compatible.Supports: CreateTopic, DeleteTopic, ListTopics, GetTopicAttributes, SetTopicAttributes,diff --git a/ministack/services/sqs.py b/ministack/services/sqs.pyindex 973b6f59..870323dc 100644--- a/ministack/services/sqs.py+++ b/ministack/services/sqs.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""SQS Service Emulator — Full AWS-compatible implementation.diff --git a/ministack/services/ssm.py b/ministack/services/ssm.pyindex ba6b3159..a311993c 100644--- a/ministack/services/ssm.py+++ b/ministack/services/ssm.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""SSM Parameter Store and Run Command Emulator.JSON-based API via X-Amz-Target (AmazonSSM).diff --git a/ministack/services/stepfunctions.py b/ministack/services/stepfunctions.pyindex d857f1b7..5e5f9702 100644--- a/ministack/services/stepfunctions.py+++ b/ministack/services/stepfunctions.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""Step Functions Service Emulator with ASL execution engine.JSON-based API via X-Amz-Target (AWSStepFunctions).diff --git a/ministack/services/sts.py b/ministack/services/sts.pyindex 72fa4183..8fe9ecd7 100644--- a/ministack/services/sts.py+++ b/ministack/services/sts.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""STS Service Emulator (AWS-compatible).@@ -24,6 +26,28 @@ from ministack.services.iam import _error, _future, _gen_secret, _gen_session_ac_sessions: dict[str, dict] = {}+def _evict_expired_sessions():+ """Drop sessions past their Expiration — the store otherwise grows with+ every AssumeRole and every vended identity-pool credential, forever.+ Called on each insert; entries without an Expiration are kept."""+ now = time.time()+ for key in [k for k, s in _sessions.items()+ if isinstance(s.get("Expiration"), (int, float))+ and now > s["Expiration"]]:+ _sessions.pop(key, None)+++def _session_expired(session) -> bool:+ exp = session.get("Expiration")+ return isinstance(exp, (int, float)) and time.time() > exp+++def register_session(access_key: str, session: dict) -> None:+ """Register a temporary-credential session (AssumeRole, identity pools)."""+ _evict_expired_sessions()+ _sessions[access_key] = session++def reset():_sessions.clear()@@ -86,8 +110,13 @@ async def handle_request(method, path, headers, body, query_params):try:access_key = auth.split("Credential=")[1].split("/")[0]if access_key in _sessions:- caller_arn = _sessions[access_key]["Arn"]- caller_user_id = _sessions[access_key]["UserId"]+ session = _sessions[access_key]+ if _session_expired(session):+ return _error(403, "ExpiredToken",+ "The security token included in the request is expired",+ ns="sts")+ caller_arn = session["Arn"]+ caller_user_id = session["UserId"]except Exception:passif use_json:@@ -158,12 +187,12 @@ async def handle_request(method, path, headers, body, query_params):secret_key = _gen_secret()session_token = _gen_session_token()role_id = "AROA" + new_uuid().replace("-", "")[:17].upper()- _sessions[access_key] = {+ register_session(access_key, {"Arn": assumed_arn,"UserId": f"{role_id}:{session_name}","SecretAccessKey": secret_key,"Expiration": time.time() + duration,- }+ })if use_json:return json_response({"Credentials": {"AccessKeyId": access_key, "SecretAccessKey": secret_key, "SessionToken": session_token, "Expiration": int(time.time() + duration)},@@ -197,12 +226,12 @@ async def handle_request(method, path, headers, body, query_params):secret_key = _gen_secret()session_token = _gen_session_token()role_id = "AROA" + new_uuid().replace("-", "")[:17].upper()- _sessions[access_key] = {+ register_session(access_key, {"Arn": assumed_arn,"UserId": f"{role_id}:{session}","SecretAccessKey": secret_key,"Expiration": time.time() + duration,- }+ })provider = _p(params, "ProviderId") or "sts.amazonaws.com"if use_json:return json_response({diff --git a/ministack/services/tagging.py b/ministack/services/tagging.pyindex d00bf00d..5cc22fa9 100644--- a/ministack/services/tagging.py+++ b/ministack/services/tagging.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""Resource Groups Tagging API emulator.diff --git a/ministack/services/transcribe.py b/ministack/services/transcribe.pyindex 5d190440..3a2f635b 100644--- a/ministack/services/transcribe.py+++ b/ministack/services/transcribe.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""Amazon Transcribe emulator.diff --git a/ministack/services/transfer.py b/ministack/services/transfer.pyindex 4275f195..f5862515 100644--- a/ministack/services/transfer.py+++ b/ministack/services/transfer.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""AWS Transfer Family Service Emulator.diff --git a/ministack/services/waf.py b/ministack/services/waf.pyindex 924fdc87..74b771ec 100644--- a/ministack/services/waf.py+++ b/ministack/services/waf.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""WAF v2 Service Emulator.JSON-based API via X-Amz-Target: AWSWAF_20190729.diff --git a/ministack/services/waf_v1.py b/ministack/services/waf_v1.pyindex 1fa5eeeb..2e5e0602 100644--- a/ministack/services/waf_v1.py+++ b/ministack/services/waf_v1.py@@ -1,3 +1,5 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""WAF Classic + WAF Regional (v1) stub.diff --git a/tests/test_cfn.py b/tests/test_cfn.pyindex b1a99978..adf964a2 100644--- a/tests/test_cfn.py+++ b/tests/test_cfn.py@@ -11156,6 +11156,100 @@ def test_cfn_cognito_user_pool_enabled_mfas(cfn, cognito_idp):_wait_stack(cfn, "cfn-enabled-mfas")+def test_cfn_cognito_user_pool_update_preserves_users(cfn, cognito_idp):+ """A property change on AWS::Cognito::UserPool updates in place: the pool+ keeps its id and its users (the create-fallback minted a new empty pool)."""+ def template(mfa):+ return {+ "AWSTemplateFormatVersion": "2010-09-09",+ "Resources": {"Pool": {"Type": "AWS::Cognito::UserPool", "Properties": {+ "UserPoolName": "cfn-upd-pool", "MfaConfiguration": mfa}}},+ "Outputs": {"Id": {"Value": {"Ref": "Pool"}}},+ }+ cfn.create_stack(StackName="cfn-pool-upd", TemplateBody=json.dumps(template("OFF")))+ stack = _wait_stack(cfn, "cfn-pool-upd")+ assert stack["StackStatus"] == "CREATE_COMPLETE"+ pool_id = {o["OutputKey"]: o["OutputValue"] for o in stack["Outputs"]}["Id"]+ cognito_idp.admin_create_user(UserPoolId=pool_id, Username="alice", MessageAction="SUPPRESS")++ cfn.update_stack(StackName="cfn-pool-upd", TemplateBody=json.dumps(template("OPTIONAL")))+ stack = _wait_stack(cfn, "cfn-pool-upd")+ assert stack["StackStatus"] == "UPDATE_COMPLETE"+ new_id = {o["OutputKey"]: o["OutputValue"] for o in stack["Outputs"]}["Id"]+ assert new_id == pool_id+ pool = cognito_idp.describe_user_pool(UserPoolId=pool_id)["UserPool"]+ assert pool["MfaConfiguration"] == "OPTIONAL"+ users = cognito_idp.list_users(UserPoolId=pool_id)["Users"]+ assert [u["Username"] for u in users] == ["alice"]++ cfn.delete_stack(StackName="cfn-pool-upd")+ _wait_stack(cfn, "cfn-pool-upd")+++def test_cfn_secret_update_keeps_arn_and_versions(cfn):+ """A changed SecretString becomes the new AWSCURRENT on the same secret —+ same ARN, history kept (the fallback minted a new ARN and dropped it all)."""+ import boto3+ sm = boto3.client("secretsmanager", endpoint_url=os.environ.get(+ "MINISTACK_ENDPOINT", "http://localhost:4566"), region_name="us-east-1",+ aws_access_key_id="test", aws_secret_access_key="test")++ def template(value):+ return {+ "AWSTemplateFormatVersion": "2010-09-09",+ "Resources": {"S": {"Type": "AWS::SecretsManager::Secret", "Properties": {+ "Name": "cfn-upd-secret", "SecretString": value}}},+ }+ cfn.create_stack(StackName="cfn-secret-upd", TemplateBody=json.dumps(template("v1")))+ assert _wait_stack(cfn, "cfn-secret-upd")["StackStatus"] == "CREATE_COMPLETE"+ arn1 = sm.describe_secret(SecretId="cfn-upd-secret")["ARN"]++ cfn.update_stack(StackName="cfn-secret-upd", TemplateBody=json.dumps(template("v2")))+ assert _wait_stack(cfn, "cfn-secret-upd")["StackStatus"] == "UPDATE_COMPLETE"+ desc = sm.describe_secret(SecretId="cfn-upd-secret")+ assert desc["ARN"] == arn1+ assert sm.get_secret_value(SecretId="cfn-upd-secret")["SecretString"] == "v2"++ cfn.delete_stack(StackName="cfn-secret-upd")+ _wait_stack(cfn, "cfn-secret-upd")+++def test_cfn_event_bus_and_record_set_update_in_place(cfn):+ """An EventBus property change no longer fails the stack with "already+ exists", and a RecordSet value change updates instead of raising."""+ import boto3+ endpoint = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")+ r53 = boto3.client("route53", endpoint_url=endpoint, region_name="us-east-1",+ aws_access_key_id="test", aws_secret_access_key="test")++ def template(ttl):+ return {+ "AWSTemplateFormatVersion": "2010-09-09",+ "Resources": {+ "Bus": {"Type": "AWS::Events::EventBus", "Properties": {+ "Name": "cfn-upd-bus", "Description": f"ttl-{ttl}"}},+ "Zone": {"Type": "AWS::Route53::HostedZone", "Properties": {+ "Name": "cfn-upd.example.com"}},+ "Rec": {"Type": "AWS::Route53::RecordSet", "Properties": {+ "HostedZoneId": {"Ref": "Zone"},+ "Name": "api.cfn-upd.example.com", "Type": "A",+ "TTL": str(ttl), "ResourceRecords": ["192.0.2.7"]}},+ },+ "Outputs": {"ZoneId": {"Value": {"Ref": "Zone"}}},+ }+ cfn.create_stack(StackName="cfn-bus-rec", TemplateBody=json.dumps(template(60)))+ stack = _wait_stack(cfn, "cfn-bus-rec")+ assert stack["StackStatus"] == "CREATE_COMPLETE"+ zone_id = {o["OutputKey"]: o["OutputValue"] for o in stack["Outputs"]}["ZoneId"]++ cfn.update_stack(StackName="cfn-bus-rec", TemplateBody=json.dumps(template(300)))+ assert _wait_stack(cfn, "cfn-bus-rec")["StackStatus"] == "UPDATE_COMPLETE"+ recs = r53.list_resource_record_sets(HostedZoneId=zone_id)["ResourceRecordSets"]+ rec = next(r for r in recs if r["Name"].startswith("api."))+ assert rec["TTL"] == 300++ cfn.delete_stack(StackName="cfn-bus-rec")+ _wait_stack(cfn, "cfn-bus-rec")# -- Template pre-flight and Fn::GetAtt strictness ---------------------------# Measured on a real account (eu-central-1, 2026-09-02): CreateStack,# UpdateStack, CreateChangeSet and ValidateTemplate reject an unrecognizeddiff --git a/tests/test_cognito.py b/tests/test_cognito.pyindex e8bc0583..c3bf50b9 100644--- a/tests/test_cognito.py+++ b/tests/test_cognito.py@@ -8202,3 +8202,56 @@ def test_cognito_identity_pool_credentials_are_sts_sessions(cognito_identity):assert ident["Arn"] == ("arn:aws:sts::000000000000:assumed-role/UnauthPoolRole/CognitoIdentityCredentials")assert ident["UserId"].endswith(":CognitoIdentityCredentials")+++def test_cognito_presignup_trigger_fires_on_plain_signup(cognito_idp, lam):+ """A pool's PreSignUp Lambda runs on ordinary SignUp: autoConfirmUser+ confirms the account (no code delivery), and a rejecting trigger blocks+ the sign-up with UserLambdaValidationException, as on AWS."""+ import io+ import zipfile++ fname = f"presignup-{_uuid_mod.uuid4().hex[:8]}"+ code = (+ "def handler(event, context):\n"+ " if event['userName'].startswith('deny'):\n"+ " raise Exception('no room for you')\n"+ " event['response']['autoConfirmUser'] = True\n"+ " event['response']['autoVerifyEmail'] = True\n"+ " return event\n"+ )+ buf = io.BytesIO()+ with zipfile.ZipFile(buf, "w") as zf:+ zf.writestr("index.py", code)+ lam.create_function(+ FunctionName=fname, Runtime="python3.12",+ Role="arn:aws:iam::000000000000:role/test-role",+ Handler="index.handler", Code={"ZipFile": buf.getvalue()},+ )+ fn_arn = f"arn:aws:lambda:us-east-1:000000000000:function:{fname}"++ pid = cognito_idp.create_user_pool(+ PoolName=f"presignup-{fname}",+ LambdaConfig={"PreSignUp": fn_arn},+ )["UserPool"]["Id"]+ cid = cognito_idp.create_user_pool_client(+ UserPoolId=pid, ClientName="c")["UserPoolClient"]["ClientId"]++ resp = cognito_idp.sign_up(+ ClientId=cid, Username="alice", Password="Passw0rd!x",+ UserAttributes=[{"Name": "email", "Value": "[email protected]"}])+ assert resp["UserConfirmed"] is True+ assert "CodeDeliveryDetails" not in resp+ user = cognito_idp.admin_get_user(UserPoolId=pid, Username="alice")+ assert user["UserStatus"] == "CONFIRMED"+ attrs = {a["Name"]: a["Value"] for a in user["UserAttributes"]}+ assert attrs.get("email_verified") == "true"++ with pytest.raises(ClientError) as exc:+ cognito_idp.sign_up(ClientId=cid, Username="deny-bob", Password="Passw0rd!x")+ assert exc.value.response["Error"]["Code"] == "UserLambdaValidationException"+ with pytest.raises(ClientError):+ cognito_idp.admin_get_user(UserPoolId=pid, Username="deny-bob")++ cognito_idp.delete_user_pool(UserPoolId=pid)+ lam.delete_function(FunctionName=fname)diff --git a/tests/test_dynamodb.py b/tests/test_dynamodb.pyindex 0cf635c6..bc773275 100644--- a/tests/test_dynamodb.py+++ b/tests/test_dynamodb.py@@ -1288,7 +1288,7 @@ def test_dynamodb_scan_projection_expression_without_select(ddb):with pytest.raises(ClientError) as exc:ddb.scan(TableName="t_pe_no_select", ProjectionExpression="pk", Select="ALL_ATTRIBUTES")assert exc.value.response["Error"]["Code"] == "ValidationException"- assert "Select value ALL_ATTRIBUTES is not compatible with ProjectionExpression" in exc.value.response["Error"]["Message"]+ assert "Cannot specify the ProjectionExpression when choosing to get ALL_ATTRIBUTES" in exc.value.response["Error"]["Message"]def test_dynamodb_batch_write(ddb):ddb.create_table(