Skip to content

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

poc(lambda): early unpacker (#1636)

Nahuel Nucerab0dea7ba7ce3
diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.py
index 9cbf85ca..1926f65c 100644
--- a/ministack/services/lambda_svc.py
+++ b/ministack/services/lambda_svc.py
@@ -389,6 +389,88 @@ def _provided_runtime_code_dir(code_zip: bytes) -> str:
return code_dir
+# Content-addressed extraction cache for the docker executor (issue #1600).
+# One shared read-only tree per distinct code zip and per distinct layer zip,
+# extracted straight from memory once under the lock — which also paces a
+# cold-start burst: concurrent first-time extractions queue instead of
+# saturating the disk, the collapse mode reported in #1600. Containers
+# receive the tree by read-only bind mount or docker cp, so nothing inside a
+# container can observe the sharing: real Lambda extracts once per execution
+# environment and mounts /var/task and /opt read-only. Directories accumulate
+# per distinct blob within ``tempfile.gettempdir()``; ``reset()`` removes
+# them, like the provided-runtime cache above.
+_DOCKER_EXTRACT_CACHE = os.path.join(tempfile.gettempdir(), "ministack-lambda-extract")
+_docker_extract_lock = threading.Lock()
+_docker_extract_dirs: dict[str, str] = {}
+
+
+def _docker_extracted_dir(blob: bytes, kind: str) -> str:
+ """Extract ``blob`` once into a shared per-sha directory and return it."""
+ key = f"{kind}-{hashlib.sha256(blob).hexdigest()}"
+ with _docker_extract_lock:
+ cached = _docker_extract_dirs.get(key)
+ if cached and os.path.isdir(cached):
+ return cached
+ target = os.path.join(_DOCKER_EXTRACT_CACHE, key)
+ if os.path.isdir(target):
+ # Leftover from a previous process — contents may be partial.
+ import shutil
+ shutil.rmtree(target, ignore_errors=True)
+ os.makedirs(target, exist_ok=True)
+ try:
+ with zipfile.ZipFile(io.BytesIO(blob)) as zf:
+ _extract_zip_preserving_mode(zf, target)
+ if kind == "code":
+ bootstrap = os.path.join(target, "bootstrap")
+ if os.path.exists(bootstrap):
+ os.chmod(bootstrap, 0o755)
+ except BaseException:
+ # A partial tree must not linger (issue #1600) nor ever be served.
+ import shutil
+ shutil.rmtree(target, ignore_errors=True)
+ raise
+ _docker_extract_dirs[key] = target
+ return target
+
+
+def _b64_sha_to_hex(b64_sha: str) -> str | None:
+ """CodeSha256 as stored on records (base64 of the digest) → the hex the
+ extraction cache keys by. Same digest, no re-hashing of blobs."""
+ try:
+ return base64.b64decode(b64_sha).hex() if b64_sha else None
+ except (ValueError, TypeError):
+ return None
+
+
+def _sweep_extract_cache() -> None:
+ """Drop cached extraction trees whose blob no longer backs any function,
+ function version, or layer version — the same reference-based policy the
+ lambda-blob persistence sweep uses. Called when references disappear
+ (function delete, code update, layer-version delete); reset() still
+ clears everything wholesale. Runs on stored CodeSha256 values only, so a
+ sweep never hashes a byte."""
+ live_code: set[str] = set()
+ live_layer: set[str] = set()
+ for func in _functions._data.values():
+ for cfg in [func.get("config") or {}] + [
+ (v or {}).get("config") or {} for v in (func.get("versions") or {}).values()]:
+ sha = _b64_sha_to_hex(cfg.get("CodeSha256", ""))
+ if sha:
+ live_code.add(sha)
+ for layer in _layers._data.values():
+ for ver in layer.get("versions", []):
+ sha = _b64_sha_to_hex((ver.get("Content") or {}).get("CodeSha256", ""))
+ if sha:
+ live_layer.add(sha)
+ with _docker_extract_lock:
+ for key in list(_docker_extract_dirs):
+ kind, _, sha = key.partition("-")
+ live = live_code if kind == "code" else live_layer
+ if sha not in live:
+ import shutil
+ shutil.rmtree(_docker_extract_dirs.pop(key), ignore_errors=True)
+
+
# ── Persistence ────────────────────────────────────────────
# Lambda code zips are stored on disk as content-addressed blob files under
@@ -2571,6 +2653,9 @@ def _delete_function(name: str, query_params: dict, path_qualifier: str | None =
# Docker pool too — otherwise the function's pooled containers leak
# until _WARM_CONTAINER_TTL eviction.
_pool_kill_function(get_account_id(), name)
+ # The deleted record may have been the last reference to its extracted
+ # code tree in the docker executor cache.
+ _sweep_extract_cache()
return 204, {}, b""
@@ -2638,6 +2723,8 @@ def _update_code(name: str, data: dict):
# Invalidate only the old $LATEST worker — published version workers stay alive
invalidate_worker(name, qualifier="$LATEST", account=get_account_id(), region=get_region())
+ # The replaced zip's extracted tree may now be unreferenced.
+ _sweep_extract_cache()
# Docker pool: the new CodeSha256 changes the pool key so new invokes
# spawn fresh containers anyway, but the old containers under the old key
# would linger until _WARM_CONTAINER_TTL. Reap them now.
@@ -3953,25 +4040,14 @@ def _declared_docker_platform(config: dict):
def _spawn_lambda_container(config: dict, code_zip: bytes | None,
_pin_platform: bool = True):
- """Create and start a Lambda container, never leaking the extraction dir.
-
- Everything between the extraction tmpdir's creation and the pool
- registration can raise — a corrupt code or layer zip, or any Docker API
- failure that is not one of the specifically-handled cases (e.g. a socket
- read timeout out of ``images.get``, which is not ``ImageNotFound``).
- Ownership of the tmpdir passes to the caller only on a successful return;
- on any exception it is removed here instead of orphaning one extraction
- per failed cold start (issue #1600).
+ """Create and start a Lambda container.
+
+ Extraction happens into the shared content-addressed cache
+ (``_docker_extracted_dir``), which owns its directories — a failure
+ anywhere in the spawn leaks nothing per cold start (issue #1600), and
+ ``reset()`` clears the cache itself.
"""
- made_tmpdirs: list[str] = []
- try:
- return _spawn_lambda_container_impl(config, code_zip, _pin_platform,
- made_tmpdirs)
- except BaseException:
- import shutil
- for d in made_tmpdirs:
- shutil.rmtree(d, ignore_errors=True)
- raise
+ return _spawn_lambda_container_impl(config, code_zip, _pin_platform)
_PY_CTX_ARN_SHIM = '''\
@@ -4046,6 +4122,15 @@ def _write_context_arn_shim(code_dir: str, runtime: str, handler: str) -> str |
return None
shim_path = os.path.join(code_dir, name)
if os.path.exists(shim_path):
+ # On a shared cached code dir an earlier cold start of the same code
+ # already wrote the shim: ours by content means use it. A same-named
+ # file that came from the user's own zip is left alone.
+ try:
+ with open(shim_path) as f:
+ if f.read() == source:
+ return shim_handler
+ except OSError:
+ pass
return None
try:
with open(shim_path, "w") as f:
@@ -4058,7 +4143,7 @@ def _write_context_arn_shim(code_dir: str, runtime: str, handler: str) -> str |
def _spawn_lambda_container_impl(config: dict, code_zip: bytes | None,
- _pin_platform: bool, _made_tmpdirs: list):
+ _pin_platform: bool):
"""Create and start a Lambda container for the given config.
A function that explicitly declared an architecture is pinned to it — but
@@ -4106,33 +4191,13 @@ def _spawn_lambda_container_impl(config: dict, code_zip: bytes | None,
if package_type == "Zip":
if not code_zip:
raise ValueError("Zip PackageType requires code_zip bytes")
- tmpdir = tempfile.mkdtemp(prefix="ministack-lambda-docker-")
- _made_tmpdirs.append(tmpdir)
- code_dir = os.path.join(tmpdir, "code")
- os.makedirs(code_dir)
- code_zip_path = os.path.join(tmpdir, "code.zip")
- with open(code_zip_path, "wb") as f:
- f.write(code_zip)
- with zipfile.ZipFile(code_zip_path) as zf:
- _extract_zip_preserving_mode(zf, code_dir)
- if is_provided:
- bootstrap = os.path.join(code_dir, "bootstrap")
- if os.path.exists(bootstrap):
- os.chmod(bootstrap, 0o755)
+ code_dir = _docker_extracted_dir(code_zip, "code")
for layer_ref in layers_list:
layer_arn_str = layer_ref if isinstance(layer_ref, str) else layer_ref.get("Arn", "")
layer_zip = _resolve_layer_zip(layer_arn_str)
if not layer_zip:
continue
- idx = len(layers_dirs)
- layer_dir = os.path.join(tmpdir, f"layer_{idx}")
- os.makedirs(layer_dir)
- layer_zip_path = os.path.join(tmpdir, f"layer_{idx}.zip")
- with open(layer_zip_path, "wb") as lf:
- lf.write(layer_zip)
- with zipfile.ZipFile(layer_zip_path) as lzf:
- _extract_zip_preserving_mode(lzf, layer_dir)
- layers_dirs.append(layer_dir)
+ layers_dirs.append(_docker_extracted_dir(layer_zip, "layer"))
# Shared environment
container_env: dict[str, str] = {
@@ -4285,9 +4350,6 @@ def _spawn_lambda_container_impl(config: dict, code_zip: bytes | None,
"running on the host architecture instead. Install a binfmt/qemu "
"handler (or Rosetta) for real cross-architecture execution.",
config.get("FunctionName"), docker_platform, reason)
- if tmpdir and os.path.exists(tmpdir):
- import shutil
- shutil.rmtree(tmpdir, ignore_errors=True)
return _spawn_lambda_container(config, code_zip, _pin_platform=False)
# Apply LAMBDA_DOCKER_FLAGS — merge parsed kwargs into run_kwargs
@@ -4331,9 +4393,6 @@ def _spawn_lambda_container_impl(config: dict, code_zip: bytes | None,
except Exception as exc:
if docker_platform:
return _platform_fallback(f"pull failed: {exc}")
- if tmpdir and os.path.exists(tmpdir):
- import shutil
- shutil.rmtree(tmpdir, ignore_errors=True)
raise RuntimeError(f"Failed to pull image {image}: {exc}")
try:
@@ -4360,9 +4419,6 @@ def _spawn_lambda_container_impl(config: dict, code_zip: bytes | None,
except Exception as exc:
if docker_platform:
return _platform_fallback(f"container create/start failed: {exc}")
- if tmpdir and os.path.exists(tmpdir):
- import shutil
- shutil.rmtree(tmpdir, ignore_errors=True)
raise
if docker_platform:
@@ -6037,6 +6093,9 @@ def _delete_layer_version(layer_name: str, version: int):
if not layer:
return 204, {}, b""
layer["versions"] = [vc for vc in layer["versions"] if vc["Version"] != version]
+ # The removed version may have been the last reference to its extracted
+ # layer tree in the docker executor cache.
+ _sweep_extract_cache()
return 204, {}, b""
@@ -7705,6 +7764,9 @@ def reset():
with _provided_code_lock:
_provided_code_dirs.clear()
shutil.rmtree(_PROVIDED_CODE_CACHE, ignore_errors=True)
+ with _docker_extract_lock:
+ _docker_extract_dirs.clear()
+ shutil.rmtree(_DOCKER_EXTRACT_CACHE, ignore_errors=True)
# ---------------------------------------------------------------------------
diff --git a/tests/test_lambda.py b/tests/test_lambda.py
index 3d4851db..51408fc5 100644
--- a/tests/test_lambda.py
+++ b/tests/test_lambda.py
@@ -8205,6 +8205,7 @@ def test_lambda_durable_chained_invoke_runs_child(lam):
"Role": _LAMBDA_ROLE,
"Handler": "index.handler",
"Code": {"ZipFile": _b64.b64encode(_make_zip(child_code)).decode()},
+ "Timeout": 30,
})
parent_code = "def handler(e,c): return {}"
_raw_durable("POST", "/2015-03-31/functions", body={
@@ -8214,6 +8215,7 @@ def test_lambda_durable_chained_invoke_runs_child(lam):
"Handler": "index.handler",
"Code": {"ZipFile": _b64.b64encode(_make_zip(parent_code)).decode()},
"DurableConfig": {"Enabled": True},
+ "Timeout": 30,
})
try:
# Invoke parent to spin up its durable execution.
@@ -8252,13 +8254,14 @@ def test_lambda_durable_chained_invoke_runs_child(lam):
# quiet so the short poll is honest. Breaking on Failed keeps a real
# child error visible instead of reading as a timeout.
import time as _time
- for _ in range(30):
- _time.sleep(0.1)
+ deadline = _time.time() + 20
+ while _time.time() < deadline:
code, history = _raw_durable("GET",
f"/2025-12-01/durable-executions/{arn_enc}/history")
if any(e["EventType"] in ("ChainedInvokeSucceeded", "ChainedInvokeFailed")
for e in history.get("Events", [])):
break
+ _time.sleep(0.2)
events = history["Events"]
assert any(e["EventType"] == "ChainedInvokeSucceeded" for e in events), \
f"expected ChainedInvokeSucceeded, got {[e['EventType'] for e in events]}"
@@ -8517,6 +8520,10 @@ def handler(event, context):
"Handler": "index.handler",
"Code": {"ZipFile": _b64.b64encode(_make_zip(code)).decode()},
"DurableConfig": {"Enabled": True},
+ # Lambda's default 3s timeout reads a loaded CI runner's slow
+ # subprocess cold start as a function timeout (no SDK fields in the
+ # error body); the budget, not the wrapping, is what varies here.
+ "Timeout": 30,
})
try:
resp = lam.invoke(FunctionName=fname, Payload=b'{"user":"data"}')
@@ -11182,7 +11189,7 @@ def test_snapstart_rejected_with_large_ephemeral_storage(lam):
lam.delete_function(FunctionName=fname)
-# ──────────────── docker executor: no extraction-dir leak ────────────────
+# ──────────── docker executor: shared extraction cache (issue #1600) ────────────
_SPAWN_LEAK_CONFIG = {
@@ -11193,51 +11200,159 @@ _SPAWN_LEAK_CONFIG = {
}
-def _capture_mkdtemp(monkeypatch):
- import tempfile as _tf
- created = []
- real = _tf.mkdtemp
+def _fresh_extract_cache(monkeypatch, tmp_path):
+ """Point the extraction cache at an empty per-test root."""
+ monkeypatch.setattr(lsvc, "_DOCKER_EXTRACT_CACHE", str(tmp_path / "extract"))
+ monkeypatch.setattr(lsvc, "_docker_extract_dirs", {})
+
+
+def _count_extractions(monkeypatch):
+ calls = []
+ real = lsvc._extract_zip_preserving_mode
- def _capture(*a, **kw):
- d = real(*a, **kw)
- created.append(d)
- return d
+ def counting(zf, dest):
+ calls.append(dest)
+ return real(zf, dest)
- monkeypatch.setattr(_tf, "mkdtemp", _capture)
- return created
+ monkeypatch.setattr(lsvc, "_extract_zip_preserving_mode", counting)
+ return calls
-def test_spawn_failure_on_corrupt_zip_leaves_no_tmpdir(monkeypatch):
- """A corrupt code zip raises out of the extraction block; the tmpdir made
- just before must not be orphaned (issue #1600)."""
+def test_spawn_failure_on_corrupt_zip_leaves_no_extraction(monkeypatch, tmp_path):
+ """A corrupt code zip raises out of the cache build; no partial tree may
+ linger on disk and nothing may be registered in the cache (issue #1600)."""
monkeypatch.setattr(lsvc, "_docker_available", True)
monkeypatch.setattr(lsvc, "_get_docker_client", lambda: object())
- created = _capture_mkdtemp(monkeypatch)
+ _fresh_extract_cache(monkeypatch, tmp_path)
with pytest.raises(zipfile.BadZipFile):
lsvc._spawn_lambda_container(dict(_SPAWN_LEAK_CONFIG), b"this is not a zip")
- assert created, "spawn never created an extraction dir"
- assert not any(os.path.exists(d) for d in created)
+ assert lsvc._docker_extract_dirs == {}
+ assert not os.path.exists(lsvc._DOCKER_EXTRACT_CACHE) or not os.listdir(
+ lsvc._DOCKER_EXTRACT_CACHE)
-def test_spawn_failure_on_docker_api_timeout_leaves_no_tmpdir(monkeypatch):
+def test_spawn_failure_after_extraction_keeps_the_cache(monkeypatch, tmp_path):
"""images.get raising anything other than ImageNotFound (the reported
- case: a socket read timeout) propagates after extraction; the tmpdir must
- be removed on the way out (issue #1600)."""
+ case: a socket read timeout) propagates after extraction. The extracted
+ tree stays in the content-addressed cache — that is the point of it — and
+ the retry reuses it without a second unpack (issue #1600)."""
monkeypatch.setattr(lsvc, "_docker_available", True)
fake_client = MagicMock()
fake_client.images.get.side_effect = TimeoutError("Read timed out.")
monkeypatch.setattr(lsvc, "_get_docker_client", lambda: fake_client)
- created = _capture_mkdtemp(monkeypatch)
+ _fresh_extract_cache(monkeypatch, tmp_path)
+ extractions = _count_extractions(monkeypatch)
+ code = _make_zip("def handler(e, c): pass")
- with pytest.raises(TimeoutError):
- lsvc._spawn_lambda_container(
- dict(_SPAWN_LEAK_CONFIG), _make_zip("def handler(e, c): pass"),
- )
-
- assert created, "spawn never created an extraction dir"
- assert not any(os.path.exists(d) for d in created)
+ for _ in range(2):
+ with pytest.raises(TimeoutError):
+ lsvc._spawn_lambda_container(dict(_SPAWN_LEAK_CONFIG), code)
+
+ assert len(extractions) == 1, "second cold start must reuse the cached tree"
+ (key,) = lsvc._docker_extract_dirs
+ assert key.startswith("code-") and os.path.isdir(lsvc._docker_extract_dirs[key])
+
+
+def test_docker_extracted_dir_is_content_addressed(monkeypatch, tmp_path):
+ """Identical blobs share one tree; different blobs and kinds get their
+ own. The dirs are what every container of that code receives (read-only
+ bind mount or docker cp), so sharing is invisible from inside."""
+ _fresh_extract_cache(monkeypatch, tmp_path)
+ extractions = _count_extractions(monkeypatch)
+ code_a = _make_zip("def handler(e, c): return 1")
+ code_b = _make_zip("def handler(e, c): return 2")
+
+ d1 = lsvc._docker_extracted_dir(code_a, "code")
+ d2 = lsvc._docker_extracted_dir(code_a, "code")
+ d3 = lsvc._docker_extracted_dir(code_b, "code")
+ d4 = lsvc._docker_extracted_dir(code_a, "layer")
+ assert d1 == d2 and len({d1, d3, d4}) == 3
+ assert len(extractions) == 3
+ assert os.path.exists(os.path.join(d1, "index.py"))
+
+
+def test_context_arn_shim_survives_a_cached_code_dir(tmp_path):
+ """On a shared cached code dir the shim file already exists from the first
+ cold start; recognizing our own content must return the shim handler
+ rather than silently running the container without the shim."""
+ code_dir = tmp_path / "code"
+ code_dir.mkdir()
+ first = lsvc._write_context_arn_shim(str(code_dir), "python3.12", "index.handler")
+ second = lsvc._write_context_arn_shim(str(code_dir), "python3.12", "index.handler")
+ assert first == second == "_msctx_shim.handler"
+ # A same-named file that came from the user's own zip is left alone.
+ (code_dir / "_msctx_shim.js").write_text("// user's own module")
+ assert lsvc._write_context_arn_shim(str(code_dir), "nodejs20.x", "index.handler") is None
+
+
+def test_extract_cache_sweep_is_reference_based(monkeypatch, tmp_path):
+ """The sweep drops extracted trees whose blob no longer backs any
+ function, version, or layer version — and only those. References are read
+ from stored CodeSha256 values (base64), never by re-hashing blobs."""
+ import base64 as _b64
+ import hashlib as _hashlib
+ from ministack.core.responses import AccountRegionScopedDict
+ _fresh_extract_cache(monkeypatch, tmp_path)
+ code_a, code_b = _make_zip("def handler(e,c): return 1"), _make_zip("def handler(e,c): return 2")
+ layer_z = _make_zip("def handler(e,c): return 3")
+ d_a = lsvc._docker_extracted_dir(code_a, "code")
+ d_b = lsvc._docker_extracted_dir(code_b, "code")
+ d_l = lsvc._docker_extracted_dir(layer_z, "layer")
+
+ def b64(blob):
+ return _b64.b64encode(_hashlib.sha256(blob).digest()).decode()
+
+ funcs = AccountRegionScopedDict()
+ funcs["fn-a"] = {"config": {"CodeSha256": b64(code_a)},
+ "versions": {"1": {"config": {"CodeSha256": b64(code_a)}}}}
+ layers = AccountRegionScopedDict()
+ layers["shared"] = {"versions": [{"Content": {"CodeSha256": b64(layer_z)}}]}
+ monkeypatch.setattr(lsvc, "_functions", funcs)
+ monkeypatch.setattr(lsvc, "_layers", layers)
+
+ lsvc._sweep_extract_cache()
+ assert os.path.isdir(d_a) and os.path.isdir(d_l)
+ assert not os.path.isdir(d_b), "unreferenced code tree must be evicted"
+ assert set(lsvc._docker_extract_dirs) == {f"code-{_hashlib.sha256(code_a).hexdigest()}",
+ f"layer-{_hashlib.sha256(layer_z).hexdigest()}"}
+
+ # Last references gone -> everything evicted.
+ del funcs["fn-a"]
+ layers["shared"]["versions"] = []
+ lsvc._sweep_extract_cache()
+ assert lsvc._docker_extract_dirs == {}
+ assert not os.path.isdir(d_a) and not os.path.isdir(d_l)
+
+
+def test_delete_and_update_paths_trigger_the_sweep(lam, monkeypatch):
+ """DeleteFunction, UpdateFunctionCode and DeleteLayerVersion are the
+ moments references disappear; each must run the cache sweep."""
+ calls = []
+ monkeypatch.setattr(lsvc, "_sweep_extract_cache", lambda: calls.append(1))
+ import base64 as _b64
+ fname = f"sweep-hooks-{_uuid_mod.uuid4().hex[:8]}"
+ lsvc._create_function({"FunctionName": fname, "Runtime": "python3.12",
+ "Role": _LAMBDA_ROLE, "Handler": "index.handler",
+ "Code": {"ZipFile": _b64.b64encode(
+ _make_zip("def handler(e,c): return 1")).decode()}})
+ lsvc._update_code(fname, {"ZipFile": _b64.b64encode(
+ _make_zip("def handler(e,c): return 2")).decode()})
+ lsvc._delete_function(fname, {})
+ lsvc._publish_layer_version("sweep-layer", {"Content": {"ZipFile": _b64.b64encode(
+ _make_zip("x = 1")).decode()}})
+ lsvc._delete_layer_version("sweep-layer", 1)
+ assert len(calls) >= 3, calls
+
+
+def test_reset_clears_the_extraction_cache(monkeypatch, tmp_path):
+ _fresh_extract_cache(monkeypatch, tmp_path)
+ lsvc._docker_extracted_dir(_make_zip("def handler(e, c): pass"), "code")
+ assert lsvc._docker_extract_dirs
+ lsvc.reset()
+ assert lsvc._docker_extract_dirs == {}
+ assert not os.path.exists(lsvc._DOCKER_EXTRACT_CACHE)
def _make_zip_multi(files: dict) -> bytes: