Skip to content

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

fix(glue): account-scope on-disk script resolution and crawler completion for non-default accounts (#827) (#828)

Akhil Adigaebaf8167fa35
diff --git a/ministack/services/glue.py b/ministack/services/glue.py
index 5545e468..8f70ccf3 100644
--- a/ministack/services/glue.py
+++ b/ministack/services/glue.py
@@ -11,6 +11,7 @@ scripts or when Docker is unavailable.
Crawlers transition through RUNNING state with a configurable timer.
"""
+import contextvars
import copy
import fnmatch
import json
@@ -724,7 +725,12 @@ def _start_crawler(data):
}
logger.info("Glue: Crawler %s finished after %ss", name, CRAWLER_RUN_SECONDS)
- timer = threading.Timer(CRAWLER_RUN_SECONDS, _finish_crawl)
+ # threading.Timer (like threading.Thread) does NOT copy contextvars, so
+ # without this snapshot _finish_crawl runs under the default account and the
+ # account-scoped _crawlers guard never matches — the crawler would hang in
+ # RUNNING forever for non-default accounts. See issue #639 / stepfunctions.
+ ctx = contextvars.copy_context()
+ timer = threading.Timer(CRAWLER_RUN_SECONDS, lambda: ctx.run(_finish_crawl))
timer.daemon = True
timer.start()
@@ -844,8 +850,10 @@ def _resolve_script(script_location):
parts = stripped.split("/", 1)
bucket = parts[0]
key = parts[1] if len(parts) > 1 else ""
- # Check on-disk first
- local_path = os.path.join(S3_DATA_DIR, bucket, key)
+ # Check on-disk first. Objects are persisted account-scoped at
+ # DATA_DIR/<account>/<bucket>/<key> (see s3._object_disk_path), so the
+ # account id MUST be part of the lookup path or it never matches.
+ local_path = os.path.join(S3_DATA_DIR, get_account_id(), bucket, key)
if os.path.exists(local_path):
return local_path
# Fetch from in-memory S3
@@ -934,7 +942,12 @@ def _start_job_run(data):
run["ExecutionTime"] = int(run["CompletedOn"] - run["StartedOn"])
run["LastModifiedOn"] = int(time.time())
- thread = threading.Thread(target=_execute, daemon=True)
+ # threading.Thread does NOT copy contextvars, so without this snapshot the
+ # worker would run under the default account and fail to resolve the
+ # account-scoped on-disk script (and AccountScopedDict lookups). Carry the
+ # request's account/region into the thread. See issue #639 / stepfunctions.
+ ctx = contextvars.copy_context()
+ thread = threading.Thread(target=ctx.run, args=(_execute,), daemon=True)
thread.start()
return json_response({"JobRunId": run_id})
diff --git a/tests/test_glue.py b/tests/test_glue.py
index ee346557..0230daee 100644
--- a/tests/test_glue.py
+++ b/tests/test_glue.py
@@ -1,6 +1,7 @@
import io
import json
import os
+import threading
import time
import uuid as _uuid_mod
import zipfile
@@ -1209,3 +1210,171 @@ def test_glue_user_defined_function_crud(glue):
with pytest.raises(ClientError) as exc2:
glue.get_user_defined_function(DatabaseName="udf_db", FunctionName="upper_clean")
assert exc2.value.response["Error"]["Code"] == "EntityNotFoundException"
+
+
+def test_glue_resolve_script_account_scoped(tmp_path, monkeypatch):
+ """_resolve_script finds an s3:// script persisted under the account-scoped
+ on-disk layout DATA_DIR/<account>/<bucket>/<key> (#827).
+
+ Regression: the on-disk lookup omitted the account id, so it could never
+ match an object written by the canonical account-scoped writer.
+ """
+ from ministack.core import responses as respmod
+ from ministack.services import s3 as s3mod
+ from ministack.services import glue as gluemod
+
+ monkeypatch.setattr(s3mod, "DATA_DIR", str(tmp_path))
+ monkeypatch.setattr(s3mod, "S3_PERSIST", True)
+ monkeypatch.setattr(gluemod, "S3_DATA_DIR", str(tmp_path))
+
+ # A non-default account also pins that the account segment is honoured,
+ # not just the hardcoded default.
+ token = respmod._request_account_id.set("111111111111")
+ try:
+ s3mod._persist_object("scripts-bucket", "jobs/etl.py", b"print('ok')\n")
+ persisted = s3mod._object_disk_path("scripts-bucket", "jobs/etl.py")
+ assert os.path.isfile(persisted)
+
+ resolved = gluemod._resolve_script("s3://scripts-bucket/jobs/etl.py")
+ assert resolved is not None, "script not resolved — on-disk path is unscoped"
+ assert "111111111111" in resolved
+ assert os.path.samefile(resolved, persisted)
+ finally:
+ respmod._request_account_id.reset(token)
+
+
+def test_glue_start_job_run_resolves_script_in_worker_thread(tmp_path, monkeypatch):
+ """StartJobRun's worker thread resolves the account-scoped script under the
+ caller's account, not the default (#827, cf. #639).
+
+ Regression: _execute runs on a bare threading.Thread, which does not copy
+ contextvars, so get_account_id() inside _resolve_script reverted to the
+ default account and a non-default account's script was never found.
+ """
+ from ministack.core import responses as respmod
+ from ministack.services import s3 as s3mod
+ from ministack.services import glue as gluemod
+
+ monkeypatch.setattr(s3mod, "DATA_DIR", str(tmp_path))
+ monkeypatch.setattr(s3mod, "S3_PERSIST", True)
+ monkeypatch.setattr(gluemod, "S3_DATA_DIR", str(tmp_path))
+
+ account = "210987654321"
+ captured = {}
+ done = threading.Event()
+
+ real_resolve = gluemod._resolve_script
+
+ def spy_resolve(location):
+ # Capture the account the worker thread actually runs under, then defer
+ # to the real resolver so the on-disk lookup is genuinely exercised.
+ captured["account"] = respmod.get_account_id()
+ captured["resolved"] = real_resolve(location)
+ done.set()
+ return captured["resolved"]
+
+ def noop_subprocess(run, job, args, resolved):
+ run["JobRunState"] = "SUCCEEDED"
+
+ monkeypatch.setattr(gluemod, "_resolve_script", spy_resolve)
+ monkeypatch.setattr(gluemod, "_execute_subprocess", noop_subprocess)
+
+ token = respmod._request_account_id.set(account)
+ try:
+ s3mod._persist_object("glue-scripts", "etl/main.py", b"print('ok')\n")
+ persisted = s3mod._object_disk_path("glue-scripts", "etl/main.py")
+
+ gluemod._create_job({
+ "Name": "ctx-job",
+ "Command": {"Name": "pythonshell", "ScriptLocation": "s3://glue-scripts/etl/main.py"},
+ })
+ gluemod._start_job_run({"JobName": "ctx-job"})
+
+ assert done.wait(5), "worker thread never invoked _resolve_script"
+ assert captured["account"] == account, (
+ f"worker ran under {captured.get('account')!r}, not caller account {account!r}"
+ )
+ assert captured["resolved"] is not None
+ assert os.path.samefile(captured["resolved"], persisted)
+ finally:
+ respmod._request_account_id.reset(token)
+ gluemod._jobs._data.pop((account, "ctx-job"), None)
+ gluemod._job_runs._data.pop((account, "ctx-job"), None)
+
+
+def test_glue_crawler_completes_for_non_default_account(monkeypatch):
+ """StartCrawler's finish timer returns the crawler to READY under the
+ caller's account, not the default (#827, cf. #639).
+
+ Regression: _finish_crawl runs on a bare threading.Timer, which does not
+ copy contextvars, so for a non-default account the `name in _crawlers`
+ guard (evaluated under the default account) was False and the crawler hung
+ in RUNNING forever with LastCrawl never recorded.
+ """
+ from ministack.core import responses as respmod
+ from ministack.services import glue as gluemod
+
+ # Shrink the 5s finish timer so the test is fast.
+ monkeypatch.setattr(gluemod, "CRAWLER_RUN_SECONDS", 0.2)
+
+ account = "555555555555"
+ name = "ctx-crawler"
+ token = respmod._request_account_id.set(account)
+ try:
+ gluemod._crawlers._data.pop((account, name), None)
+ gluemod._create_crawler({
+ "Name": name,
+ "Role": "arn:aws:iam::555555555555:role/GlueRole",
+ "Targets": {"S3Targets": [{"Path": "s3://b/data/"}]},
+ })
+ gluemod._start_crawler({"Name": name})
+ assert gluemod._crawlers[name]["State"] == "RUNNING"
+
+ # Wait for the finish timer (0.2s) to fire.
+ deadline = time.time() + 3
+ while time.time() < deadline and gluemod._crawlers[name]["State"] != "READY":
+ time.sleep(0.05)
+
+ assert gluemod._crawlers[name]["State"] == "READY", (
+ "crawler stuck in RUNNING — finish timer ran under the wrong account"
+ )
+ last_crawl = gluemod._crawlers[name]["LastCrawl"]
+ assert last_crawl is not None and last_crawl["Status"] == "SUCCEEDED"
+ finally:
+ respmod._request_account_id.reset(token)
+ gluemod._crawlers._data.pop((account, name), None)
+
+
+def test_glue_resolve_script_isolated_per_account(tmp_path, monkeypatch):
+ """A script persisted under one account is not resolvable from another (#827).
+
+ Guards the core multi-tenancy property: account-scoped resolution must not
+ leak one tenant's on-disk objects to another.
+ """
+ from ministack.core import responses as respmod
+ from ministack.services import s3 as s3mod
+ from ministack.services import glue as gluemod
+
+ monkeypatch.setattr(s3mod, "DATA_DIR", str(tmp_path))
+ monkeypatch.setattr(s3mod, "S3_PERSIST", True)
+ monkeypatch.setattr(gluemod, "S3_DATA_DIR", str(tmp_path))
+
+ owner = "111111111111"
+ other = "222222222222"
+ uri = "s3://scripts-bucket/jobs/etl.py"
+
+ tok_owner = respmod._request_account_id.set(owner)
+ try:
+ s3mod._persist_object("scripts-bucket", "jobs/etl.py", b"print('ok')\n")
+ owner_path = gluemod._resolve_script(uri)
+ assert owner_path is not None and owner in owner_path
+ finally:
+ respmod._request_account_id.reset(tok_owner)
+
+ tok_other = respmod._request_account_id.set(other)
+ try:
+ # 'other' has no such object on disk (scoped under its own account) or
+ # in memory, so the lookup must not surface 'owner's script.
+ assert gluemod._resolve_script(uri) is None
+ finally:
+ respmod._request_account_id.reset(tok_other)