Skip to content

Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.

fix(lambda): not mounted in container (#818)

Nahuel Nuceraf96ccc21dca7
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 27949721..744469f8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -21,6 +21,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
- **Glue — `CreateDatabase` honors top-level `Tags`** — `CreateDatabase` previously dropped `Tags` on the floor; tags are now stored against the database ARN (`arn:aws:glue:{region}:{account}:database/{name}`) and retrievable via `GetTags`. `DeleteDatabase` cleans them up.
- **Glue — `UpdateTable` optimistic concurrency via `VersionId`** — table records now carry a monotonically-increasing `VersionId` (string, per the AWS `Table` output shape). `UpdateTable` with a stale `VersionId` returns `ConcurrentModificationException`; matching version bumps and applies. Calls without `VersionId` keep the old last-write-wins behaviour for back-compat.
- **ECS — `DeleteService` marks INACTIVE instead of removing the record** — matches the AWS contract: "Services in the `DRAINING` or `INACTIVE` status can still be viewed with the `DescribeServices` API operation." Tasks are stopped synchronously, the service stays describable with `status=INACTIVE`, and tags remain attached. Re-creating a service with the same name is allowed once the prior incarnation is `INACTIVE` (matches the AWS-documented conflict-only-on-ACTIVE/DRAINING rule).
+- **Lambda — layer `CodeSize` and post-attachment invocation** — `CreateFunction(Layers=[...])` and `UpdateFunctionConfiguration(Layers=[...])` now surface each layer's real `CodeSize` on `GetFunctionConfiguration.Layers[*].CodeSize` (looked up from the published layer version) instead of a hardcoded `0`. `UpdateFunctionConfiguration` also recycles the `$LATEST` warm worker when worker-affecting fields change (`Layers`, `Runtime`, `Handler`, `Environment`, `MemorySize`, `Architectures`, `VpcConfig`, `FileSystemConfigs`) — without this, a layer attached after the first invoke was never extracted into `/opt/layer_N` for the running worker, and `import` from the layer failed at handler entry. Reported by @omargr299.
---
diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.py
index 8149e5c2..f5ae3891 100644
--- a/ministack/services/lambda_svc.py
+++ b/ministack/services/lambda_svc.py
@@ -654,8 +654,11 @@ def _build_config(name: str, data: dict, code_zip: bytes | None = None) -> dict:
layers_cfg = []
for layer in data.get("Layers", []):
if isinstance(layer, str):
- layers_cfg.append({"Arn": layer, "CodeSize": 0})
+ layers_cfg.append({"Arn": layer, "CodeSize": _layer_codesize_for_arn(layer)})
elif isinstance(layer, dict):
+ layer = dict(layer)
+ if "CodeSize" not in layer and "Arn" in layer:
+ layer["CodeSize"] = _layer_codesize_for_arn(layer["Arn"])
layers_cfg.append(layer)
env = data.get("Environment")
@@ -1498,8 +1501,11 @@ def _update_config(name: str, data: dict):
layers_cfg = []
for layer in data["Layers"]:
if isinstance(layer, str):
- layers_cfg.append({"Arn": layer, "CodeSize": 0})
+ layers_cfg.append({"Arn": layer, "CodeSize": _layer_codesize_for_arn(layer)})
elif isinstance(layer, dict):
+ layer = dict(layer)
+ if "CodeSize" not in layer and "Arn" in layer:
+ layer["CodeSize"] = _layer_codesize_for_arn(layer["Arn"])
layers_cfg.append(layer)
config["Layers"] = layers_cfg
else:
@@ -1514,6 +1520,20 @@ def _update_config(name: str, data: dict):
config["StateReason"] = "The function is being updated."
config["StateReasonCode"] = "Updating"
config["RevisionId"] = new_uuid()
+ # AWS-match: UpdateFunctionConfiguration recycles the init container when
+ # spawn-time inputs change (Runtime/Handler/Layers/Env/MemorySize/Arch/
+ # VpcConfig/FileSystemConfigs). The ministack warm-pool key is just
+ # account:func:qualifier, so a stale worker would keep serving with the
+ # pre-update layers/env. Invalidate to force a fresh worker on next invoke,
+ # mirroring what _update_code already does. Otherwise PublishLayerVersion +
+ # UpdateFunctionConfiguration(Layers=[...]) leaves the previously-warm
+ # worker without the new layer extracted on disk (issue #816).
+ _WORKER_AFFECTING = {
+ "Runtime", "Handler", "Layers", "Environment", "MemorySize",
+ "Architectures", "VpcConfig", "FileSystemConfigs",
+ }
+ if any(k in data for k in _WORKER_AFFECTING):
+ invalidate_worker(name, qualifier="$LATEST")
_schedule_state_transition(name, _LAMBDA_STATE_TRANSITION_DELAY)
return json_response(config)
@@ -3430,6 +3450,28 @@ def _resolve_layer_zip(layer_arn_str: str) -> bytes | None:
return None
+def _layer_codesize_for_arn(layer_arn_str: str) -> int:
+ """Look up the stored layer version's CodeSize, or 0 if the layer
+ version can't be resolved. Real AWS surfaces the actual layer code size on
+ `GetFunctionConfiguration.Layers[*].CodeSize` so callers can sanity-check
+ against quotas (250 MB unzipped function + layers)."""
+ segs = layer_arn_str.split(":")
+ if len(segs) < 8:
+ return 0
+ layer_name = segs[6]
+ try:
+ version = int(segs[7])
+ except (ValueError, IndexError):
+ return 0
+ layer = _layers.get(layer_name)
+ if not layer:
+ return 0
+ for v in layer["versions"]:
+ if v["Version"] == version:
+ return v.get("Content", {}).get("CodeSize", 0)
+ return 0
+
+
# ---------------------------------------------------------------------------
# Versioning
# ---------------------------------------------------------------------------
diff --git a/tests/test_lambda.py b/tests/test_lambda.py
index 4fab56ce..2804cd81 100644
--- a/tests/test_lambda.py
+++ b/tests/test_lambda.py
@@ -1484,6 +1484,93 @@ def test_lambda_function_with_layer(lam):
fn = lam.get_function(FunctionName="fn-with-layer")
assert layer_arn in fn["Configuration"]["Layers"][0]["Arn"]
+
+def test_lambda_function_with_layer_reports_real_code_size(lam):
+ """GetFunctionConfiguration.Layers[*].CodeSize must mirror the layer's
+ actual zip size, not hardcoded 0 (issue #816)."""
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, "w") as z:
+ z.writestr("mod.py", "X = 'hello' * 1000") # non-trivial size
+ layer_zip = buf.getvalue()
+ layer_resp = lam.publish_layer_version(
+ LayerName="codesize-layer",
+ Content={"ZipFile": layer_zip},
+ )
+ layer_arn = layer_resp["LayerVersionArn"]
+ expected_size = layer_resp["Content"]["CodeSize"]
+ assert expected_size > 0
+
+ fn_zip = io.BytesIO()
+ with zipfile.ZipFile(fn_zip, "w") as z:
+ z.writestr("index.py", "def handler(e, c): return {}")
+ lam.create_function(
+ FunctionName="codesize-fn",
+ Runtime="python3.12",
+ Role="arn:aws:iam::000000000000:role/test",
+ Handler="index.handler",
+ Code={"ZipFile": fn_zip.getvalue()},
+ Layers=[layer_arn],
+ )
+ cfg = lam.get_function_configuration(FunctionName="codesize-fn")
+ assert cfg["Layers"][0]["Arn"] == layer_arn
+ assert cfg["Layers"][0]["CodeSize"] == expected_size
+
+
+def test_lambda_update_function_configuration_layer_attachment_invokes_with_layer(lam):
+ """UpdateFunctionConfiguration(Layers=[arn]) must:
+ (a) surface the layer's real CodeSize on the next GetFunctionConfiguration, and
+ (b) recycle the warm worker so the next invoke actually loads the layer.
+ Regression for issue #816 (layer not found after association)."""
+ # Layer publishes a Python module the handler imports.
+ layer_buf = io.BytesIO()
+ with zipfile.ZipFile(layer_buf, "w") as z:
+ z.writestr("python/mylayermod.py", "VALUE = 'from-layer'")
+ layer_arn = lam.publish_layer_version(
+ LayerName="late-attach-layer",
+ Content={"ZipFile": layer_buf.getvalue()},
+ CompatibleRuntimes=["python3.12"],
+ )["LayerVersionArn"]
+
+ # Function created WITHOUT the layer first — handler tolerates the absence
+ # so the initial invoke can warm a worker.
+ fn_src = (
+ "def handler(event, context):\n"
+ " try:\n"
+ " import mylayermod\n"
+ " return {'layer_value': mylayermod.VALUE}\n"
+ " except ImportError:\n"
+ " return {'layer_value': None}\n"
+ )
+ fn_buf = io.BytesIO()
+ with zipfile.ZipFile(fn_buf, "w") as z:
+ z.writestr("index.py", fn_src)
+ lam.create_function(
+ FunctionName="late-attach-fn",
+ Runtime="python3.12",
+ Role="arn:aws:iam::000000000000:role/test",
+ Handler="index.handler",
+ Code={"ZipFile": fn_buf.getvalue()},
+ )
+
+ # Pre-attach invoke warms a worker without the layer.
+ pre = lam.invoke(FunctionName="late-attach-fn", Payload=b"{}")
+ pre_body = json.loads(pre["Payload"].read())
+ assert pre_body == {"layer_value": None}
+
+ # Attach the layer via UpdateFunctionConfiguration.
+ lam.update_function_configuration(FunctionName="late-attach-fn", Layers=[layer_arn])
+
+ # (a) CodeSize on GetFunctionConfiguration matches the layer's real size.
+ cfg = lam.get_function_configuration(FunctionName="late-attach-fn")
+ assert cfg["Layers"][0]["Arn"] == layer_arn
+ assert cfg["Layers"][0]["CodeSize"] > 0
+
+ # (b) Next invoke must use a fresh worker that has the layer mounted on
+ # /opt/python — the import succeeds and the handler returns the layer value.
+ post = lam.invoke(FunctionName="late-attach-fn", Payload=b"{}")
+ post_body = json.loads(post["Payload"].read())
+ assert post_body == {"layer_value": "from-layer"}
+
def test_lambda_layer_content_location(lam):
"""Content.Location should be a non-empty URL pointing to the layer zip."""
buf = io.BytesIO()