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: run Lambda functions and ECS tasks on the architecture they declare (#1561)
Jacob Schooley8c0f1d0aaf89
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a99f3b9a..d02a947d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -19,6 +19,8 @@ Versioning follows [Semantic Versioning](https://semver.org/).- **CloudFormation — a resource that cannot be deleted fails the operation** — a missing delete handler was a log warning and `DeleteStack` reported `DELETE_COMPLETE` while resources lived on; the stack now lands `DELETE_FAILED` (failed resources retained for a retry, exports kept, deleted siblings gone) and a failed rollback lands `ROLLBACK_FAILED`/`UPDATE_ROLLBACK_FAILED`, per the documented lifecycle. `AWS::Lambda::Version` gained a real delete handler (its `Ref` now returns the qualified version ARN, as on AWS) and `AWS::AppSync::GraphQLSchema` one that removes the stored schema. Contributed by @iot-rocket.- **IoT Core — an HTTP shadow write publishes the reserved-topic notifications** — `UpdateThingShadow` over the REST data plane stored state and emitted nothing, so a topic rule on `.../shadow/update/accepted` fired for MQTT updates only; an accepted HTTP update now publishes `update/accepted`/`delta`/`documents` (and a delete its `delete/accepted`) through the same emission code as the MQTT bridge, which also fixed the `documents` envelope on both transports: it now echoes the request's `clientToken` and carries `state` + `metadata` + `version` only. Contributed by @iot-rocket.- **IoT Core — device-plane job timestamps were milliseconds, 1000x off** — `iot-jobs-data` responses served epoch milliseconds where the API reference words every stamp "in seconds since the epoch"; every device-plane stamp, HTTP and MQTT alike, is now whole epoch seconds. Contributed by @iot-rocket.+- **ECS — a task runs on the architecture its task definition declares** — `runtimePlatform` was stored on the task definition and never read again, so Docker chose the host's architecture. An `ARM64` task definition on an x86_64 host started a container that could not execute its own entrypoint, and the task still reported as started, because creating the container is the part that succeeds — the failure surfaced only as a service that never answered. The declared architecture is now passed to Docker; a task definition without a `runtimePlatform` is unchanged. Contributed by @jbschooley.+- **Lambda — a function runs on the architecture it declares** — the container was created without a platform, so Docker used the host's architecture whatever `Architectures` said. An arm64 function on an x86_64 host ran as x86_64, which is invisible until a layer carries a native wheel: the handler then dies at import naming the library rather than the mismatch (`no pq wrapper available`, from psycopg loading its own binary). The declared architecture is now passed to Docker, and a cached image of the wrong architecture is re-pulled for the right one rather than failing opaquely at run. Contributed by @jbschooley.- **Step Functions — execution status changes are published to EventBridge** — real Step Functions automatically emits `source: aws.states` / `detail-type: "Step Functions Execution Status Change"` to the default bus whenever a standard execution changes status; MiniStack ran the execution and published nothing, so a rule matching those events never fired and applications waiting on them hung with no error anywhere. Every `StartExecution` now emits `RUNNING` and its completion `SUCCEEDED`, `FAILED` (with `error`/`cause` and `REDRIVABLE`) or `ABORTED` on `StopExecution`, carrying the documented detail fields with epoch-millisecond dates; payloads over 248 KiB are excluded and flagged via `inputDetails`/`outputDetails`, and `StartSyncExecution` (the express-flavored path) emits nothing, as on AWS. Reported by @moonyseven.- **ECS — a service's tasks register in its target groups** — a `loadBalancers` block was stored and never acted on, so `DescribeTargetHealth` stayed empty and every request through the load balancer fell to the listener's default action; a service now reconciles its target groups from its running tasks' addresses (awsvpc tasks carry their address as `attachments[].details[privateIPv4Address]`, where real ECS reports it), withdrawing only its own registrations so manually registered targets and a second service sharing the group survive, as on AWS. Contributed by @jbschooley.- **ECS — an `awsvpc` task no longer publishes host ports** — each `awsvpc` task has its own network namespace on AWS, so container ports never bind on the host; publishing them made two tasks sharing a container port collide with a Docker bind error that cannot happen on Fargate. Only `bridge` and `host` modes publish. Contributed by @jbschooley.diff --git a/ministack/services/ecs.py b/ministack/services/ecs.pyindex 3ad8910c..4e68a25d 100644--- a/ministack/services/ecs.py+++ b/ministack/services/ecs.py@@ -1249,6 +1249,19 @@ def _build_run_kwargs(cdef, td, env, port_bindings, ecs_network,cap_add = caps.get("Add") or caps.get("add") or []binds = _docker_binds_from_taskdef(td, cdef)+ # A task definition's runtimePlatform says which architecture its image is+ # built for, and AWS launches it on that. Docker otherwise picks the host's,+ # so an ARM64 task definition on an x86_64 host produced a container that+ # could not execute its own entrypoint — and the task still reported as+ # started, because creating the container is what succeeds.+ rp = td.get("runtimePlatform") or {}+ cpu_arch = (rp.get("cpuArchitecture") or rp.get("CpuArchitecture") or "").upper()+ docker_platform = (+ "linux/arm64" if cpu_arch == "ARM64"+ else "linux/amd64" if cpu_arch == "X86_64"+ else None+ )+kwargs = dict(detach=True,environment=env,@@ -1279,6 +1292,12 @@ def _build_run_kwargs(cdef, td, env, port_bindings, ecs_network,# Docker-Desktop fallback: when we couldn't discover Ministack's# IP on the shared network, route via host.docker.internal.kwargs["extra_hosts"] = {"host.docker.internal": "host-gateway"}++ # Only when the task definition asked for one. An absent runtimePlatform+ # means no preference was expressed, and the host default is then correct.+ if docker_platform:+ kwargs["platform"] = docker_platform+return kwargsdiff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.pyindex 75a715bb..ac5311d8 100644--- a/ministack/services/lambda_svc.py+++ b/ministack/services/lambda_svc.py@@ -3828,6 +3828,17 @@ def _spawn_lambda_container(config: dict, code_zip: bytes | None):if LAMBDA_DOCKER_NETWORK:run_kwargs["network"] = LAMBDA_DOCKER_NETWORK+ # AWS runs a function on the architecture it declares. Docker otherwise+ # picks the host's, so an arm64 function on an x86_64 host quietly ran as+ # x86_64 — fine until a layer carries a native wheel, at which point the+ # handler dies at import naming the library rather than the mismatch+ # ("no pq wrapper available" from psycopg, for instance). Set it before the+ # flags merge so an explicit --platform in LAMBDA_DOCKER_FLAGS still wins.+ declared_arch = (config.get("Architectures") or ["x86_64"])[0]+ docker_arch = "arm64" if declared_arch == "arm64" else "amd64"+ docker_platform = f"linux/{docker_arch}"+ run_kwargs["platform"] = docker_platform+# Apply LAMBDA_DOCKER_FLAGS — merge parsed kwargs into run_kwargsif LAMBDA_DOCKER_FLAGS:df_kwargs = _parse_docker_flags(LAMBDA_DOCKER_FLAGS)@@ -3854,11 +3865,16 @@ def _spawn_lambda_container(config: dict, code_zip: bytes | None):# Pull the image on first use (both Zip RIE images and user Image types)try:- client.images.get(image)+ local_image = client.images.get(image)+ # A cached image of the wrong architecture is as unusable as no image:+ # docker refuses to start it, and without this check the refusal arrives+ # as an opaque run error rather than a pull.+ if local_image.attrs.get("Architecture") not in (None, docker_arch):+ raise docker_lib.errors.ImageNotFound("cached image is the wrong architecture")except docker_lib.errors.ImageNotFound:- logger.info("Pulling Lambda image: %s", image)+ logger.info("Pulling Lambda image: %s (%s)", image, docker_platform)try:- client.images.pull(image)+ client.images.pull(image, platform=docker_platform)except Exception as exc:if tmpdir and os.path.exists(tmpdir):import shutildiff --git a/tests/test_ecs.py b/tests/test_ecs.pyindex 34d62270..13694a87 100644--- a/tests/test_ecs.py+++ b/tests/test_ecs.py@@ -1796,3 +1796,40 @@ def test_ecs_service_reconcile_spares_foreign_targets(monkeypatch):_ecs._delete_service({"cluster": "lb-shared-c", "service": "lb-shared-svc", "force": True})assert _alb._targets.get(tg_arn) == [{"Id": "10.9.9.9", "Port": 80}]+ "cpu_architecture,expected_platform",+ [+ ("ARM64", "linux/arm64"),+ ("X86_64", "linux/amd64"),+ (None, None),+ ],+)+def test_ecs_task_runs_on_its_declared_runtime_platform(cpu_architecture, expected_platform):+ """A task definition's runtimePlatform decides the container's platform.++ It was stored and never read, so Docker chose the host's architecture. An+ ARM64 task definition on an x86_64 host then started a container that could+ not execute its own entrypoint — and the task still reported as started,+ because creating the container is the part that succeeds.++ An absent runtimePlatform must stay absent rather than defaulting to the+ host explicitly, so existing single-architecture setups are untouched.+ """+ td = {"networkMode": "bridge"}+ if cpu_architecture:+ td["runtimePlatform"] = {"cpuArchitecture": cpu_architecture}++ kwargs = ecs_service._build_run_kwargs(+ {"name": "app", "image": "busybox:latest"},+ td,+ {}, # env+ {}, # port_bindings+ None, # ecs_network+ False, # host_mode+ "task1234", # task_id+ "arn:aws:ecs:us-east-1:000000000000:task/c/task1234",+ None, # ministack_net_ip+ "arn:aws:ecs:us-east-1:000000000000:cluster/c",+ )++ assert kwargs.get("platform") == expected_platformdiff --git a/tests/test_lambda.py b/tests/test_lambda.pyindex 9ff8696b..2013e50a 100644--- a/tests/test_lambda.py+++ b/tests/test_lambda.py@@ -10735,3 +10735,47 @@ def test_lambda_event_source_mapping_response_carries_its_arn(lam, sqs):assert lam.list_tags(Resource=created["EventSourceMappingArn"])["Tags"] == {"Team": "billing"}+ os.environ.get("LAMBDA_EXECUTOR", "").lower() != "docker",+ reason="requires LAMBDA_EXECUTOR=docker and Docker daemon",+)+ "declared,expected_machine",+ [("arm64", "aarch64"), ("x86_64", "x86_64")],+)+def test_lambda_runs_on_the_architecture_it_declares(lam, declared, expected_machine):+ """A function runs as the architecture it declares, not as the host's.++ The container was created without a platform, so Docker used the host's+ architecture whatever the function said. That is invisible until a layer+ carries a native wheel: an arm64 layer in an x86_64 container fails at+ import, naming the library rather than the mismatch.++ The handler reports what it is actually running on, which is the only thing+ that distinguishes the fix from the bug on a host of either architecture.+ """+ fname = f"lam-arch-{declared}-{_uuid_mod.uuid4().hex[:8]}"+ code = (+ "import platform\n"+ "def handler(event, context):\n"+ " return {'machine': platform.machine()}\n"+ )++ lam.create_function(+ FunctionName=fname,+ Runtime="python3.12",+ Role=_LAMBDA_ROLE,+ Handler="index.handler",+ Code={"ZipFile": _make_zip(code)},+ Architectures=[declared],+ )++ try:+ resp = lam.invoke(FunctionName=fname, Payload=json.dumps({}))+ payload = json.loads(resp["Payload"].read())+ if resp.get("FunctionError") and "exec format" in str(payload).lower():+ pytest.skip(f"host cannot run linux/{declared} — no binfmt handler registered")+ assert resp.get("FunctionError") is None, payload+ assert payload.get("machine") == expected_machine, payload+ finally:+ lam.delete_function(FunctionName=fname)