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
Preserve ECS region scope (#1099)
Ian Oberst51ae5e16443d
diff --git a/ministack/core/persistence.py b/ministack/core/persistence.pyindex fbef038a..ce75aa76 100644--- a/ministack/core/persistence.py+++ b/ministack/core/persistence.py@@ -17,13 +17,19 @@ logger = logging.getLogger("persistence")PERSIST_STATE = os.environ.get("PERSIST_STATE", "0") == "1"STATE_DIR = os.environ.get("STATE_DIR", "/tmp/ministack-state")-# On-disk state format version. Files are wrapped as+# On-disk state format versions. Files are wrapped as# {"__ministack_format__": N, "payload": <service state>}# load_state refuses a file whose version is NEWER than this binary understands-# rather than mis-parsing it (the downgrade-corruption guard). Version 2-# introduced region-scoped (AccountRegionScopedDict) stores; legacy unwrapped+# rather than mis-parsing it (the downgrade-corruption guard). Version 2 is the+# default and introduced region-scoped (AccountRegionScopedDict) stores. ECS+# uses version 3 because its service state was regionalized. Legacy unwrapped# files (implicit v1, account-scoped) still load and migrate. (U4)STATE_FORMAT_VERSION = 2+SERVICE_STATE_FORMAT_VERSIONS = {"ecs": 3}+++def _state_format_version(service: str) -> int:+ return SERVICE_STATE_FORMAT_VERSIONS.get(service, STATE_FORMAT_VERSION)def _json_default(obj):@@ -95,7 +101,7 @@ def save_state(service: str, data: dict) -> None:try:with open(tmp, "w") as f:json.dump(- {"__ministack_format__": STATE_FORMAT_VERSION, "payload": data},+ {"__ministack_format__": _state_format_version(service), "payload": data},f, default=_json_default,)os.replace(tmp, path)@@ -126,11 +132,12 @@ def load_state(service: str) -> dict | None:# it would corrupt state on downgrade. (U4)if isinstance(data, dict) and "__ministack_format__" in data:version = data.get("__ministack_format__")- if isinstance(version, int) and version > STATE_FORMAT_VERSION:+ supported_version = _state_format_version(service)+ if isinstance(version, int) and version > supported_version:logger.error("Persistence: %s state is format v%s but this MiniStack only ""understands v%s — refusing to load (downgrade not supported)",- service, version, STATE_FORMAT_VERSION,+ service, version, supported_version,)return Nonedata = data.get("payload")diff --git a/ministack/services/ecs.py b/ministack/services/ecs.pyindex d766908e..373a2b78 100644--- a/ministack/services/ecs.py+++ b/ministack/services/ecs.py@@ -34,6 +34,7 @@ import timefrom ministack.core.arn import ArnParseError, parse_arnfrom ministack.core.persistence import load_statefrom ministack.core.responses import (+ AccountRegionScopedDict,AccountScopedDict,error_response_json,get_account_id,@@ -50,20 +51,21 @@ REGION = os.environ.get("MINISTACK_REGION", "us-east-1")_MINISTACK_HOST = os.environ.get("MINISTACK_HOST", "localhost")_GATEWAY_PORT = os.environ.get("GATEWAY_PORT", "4566")-_clusters = AccountScopedDict()-_task_defs = AccountScopedDict()-_task_def_latest = AccountScopedDict()-_services = AccountScopedDict()-_tasks = AccountScopedDict()+_clusters = AccountRegionScopedDict()+_task_defs = AccountRegionScopedDict()+_task_def_latest = AccountRegionScopedDict()+_services = AccountRegionScopedDict()+_tasks = AccountRegionScopedDict()+# Account-scoped is deliberate: keys are region-embedding resource ARNs._tags = AccountScopedDict()-_account_settings = AccountScopedDict()-_capacity_providers = AccountScopedDict()+_account_settings = AccountRegionScopedDict()+_capacity_providers = AccountRegionScopedDict()# `_attributes` was originally declared next to its handler block much# further down the file. Moved up here so the import-time `load_state`# block (which calls `restore_state` and references `_attributes`) sees# it defined; otherwise warm-boot fires NameError, the surrounding# try/except swallows it, and ALL ECS state silently fails to restore.-_attributes = AccountScopedDict()+_attributes = AccountRegionScopedDict()_docker = None@@ -122,9 +124,8 @@ def get_state():"attributes": copy.deepcopy(_attributes),}# Save tasks but strip Docker container IDs.- # Iterate _data directly to capture ALL accounts.- from ministack.core.responses import AccountScopedDict- tasks = AccountScopedDict()+ # Iterate _data directly to capture ALL accounts and regions.+ tasks = AccountRegionScopedDict()for scoped_key, task in _tasks._data.items():t = copy.deepcopy(task)t.pop("_docker_ids", None)@@ -134,29 +135,89 @@ def get_state():return state+def _restore_task_def_latest(latest_data):+ if isinstance(latest_data, AccountRegionScopedDict):+ _task_def_latest.update(latest_data)+ return++ task_defs = _task_defs.all_items()+ for (account_id, region, _key), task_def in task_defs:+ if not isinstance(task_def, dict):+ continue+ family = task_def.get("family")+ revision = task_def.get("revision")+ if not family or not isinstance(revision, int):+ continue+ current_revision = _task_def_latest.get_scoped(+ account_id, region, family+ )+ if current_revision is None or revision > current_revision:+ _task_def_latest.set_scoped(account_id, region, family, revision)++ if not latest_data:+ return++ if isinstance(latest_data, AccountScopedDict):+ latest_items = latest_data._data.items()+ else:+ latest_items = (+ ((get_account_id(), family), revision)+ for family, revision in latest_data.items()+ )++ for (account_id, family), revision in latest_items:+ exact_key = f"{family}:{revision}"+ exact_regions = {+ region+ for (candidate_account, region, key), _task_def in task_defs+ if candidate_account == account_id and key == exact_key+ }+ family_regions = {+ region+ for (candidate_account, region, _key), task_def in task_defs+ if candidate_account == account_id+ and isinstance(task_def, dict)+ and task_def.get("family") == family+ }+ matching_regions = exact_regions or family_regions+ region = next(iter(matching_regions)) if len(matching_regions) == 1 else get_region()+ current_revision = _task_def_latest.get_scoped(account_id, region, family)+ if current_revision is None or revision > current_revision:+ _task_def_latest.set_scoped(account_id, region, family, revision)++def restore_state(data):if not data:return_clusters.update(data.get("clusters", {}))_task_defs.update(data.get("task_defs", {}))- _task_def_latest.update(data.get("task_def_latest", {}))+ _restore_task_def_latest(data.get("task_def_latest", {}))_services.update(data.get("services", {}))_tags.update(data.get("tags", {}))_account_settings.update(data.get("account_settings", {}))_capacity_providers.update(data.get("capacity_providers", {}))_attributes.update(data.get("attributes", {}))- from ministack.core.responses import AccountScopedDicttasks_data = data.get("tasks", {})- if isinstance(tasks_data, AccountScopedDict):+ if isinstance(tasks_data, AccountRegionScopedDict):for scoped_key, task in tasks_data._data.items():- task["_docker_ids"] = []- task["lastStatus"] = "STOPPED"- _tasks._data[scoped_key] = task+ restored_task = copy.deepcopy(task)+ restored_task["_docker_ids"] = []+ restored_task["lastStatus"] = "STOPPED"+ _tasks._data[scoped_key] = restored_task+ elif isinstance(tasks_data, AccountScopedDict):+ for (account_id, arn), task in tasks_data._data.items():+ restored_task = copy.deepcopy(task)+ restored_task["_docker_ids"] = []+ restored_task["lastStatus"] = "STOPPED"+ region = _tasks._region_for_legacy_value(arn, restored_task)+ _tasks.set_scoped(account_id, region, arn, restored_task)else:for arn, task in tasks_data.items():- task["_docker_ids"] = []- task["lastStatus"] = "STOPPED"- _tasks[arn] = task+ restored_task = copy.deepcopy(task)+ restored_task["_docker_ids"] = []+ restored_task["lastStatus"] = "STOPPED"+ region = _tasks._region_for_legacy_value(arn, restored_task)+ _tasks.set_scoped(get_account_id(), region, arn, restored_task)try:diff --git a/tests/test_ecs.py b/tests/test_ecs.pyindex b14509b8..af2f2008 100644--- a/tests/test_ecs.py+++ b/tests/test_ecs.py@@ -1,3 +1,4 @@+import copyimport ioimport jsonimport os@@ -1188,3 +1189,178 @@ def test_ecs_container_secret_ssm_valuefrom_is_region_scoped():ssm_service.reset()set_request_account_id(original_account)set_request_region(original_region)+++def test_ecs_resource_state_is_region_scoped(monkeypatch):+ """Same-named ECS resources coexist without leaking across regions."""+ from ministack.core.responses import (+ get_account_id,+ get_region,+ set_request_account_id,+ set_request_region,+ )++ original_account = get_account_id()+ original_region = get_region()+ account_id = "000000000000"+ cluster_name = f"scope-cluster-{_uuid_mod.uuid4().hex[:8]}"+ family = f"scope-family-{_uuid_mod.uuid4().hex[:8]}"+ service_name = f"scope-service-{_uuid_mod.uuid4().hex[:8]}"+ capacity_provider = f"scope-cp-{_uuid_mod.uuid4().hex[:8]}"+ attribute_key = "i-scope:zone"+ task_definition = {+ "family": family,+ "containerDefinitions": [{"name": "app", "image": "busybox"}],+ }++ monkeypatch.setattr(ecs_service, "_get_docker", lambda: None)+ ecs_service.reset()+ try:+ set_request_account_id(account_id)+ set_request_region("us-east-1")+ east_cluster = json.loads(ecs_service._create_cluster({+ "clusterName": cluster_name,+ "tags": [{"key": "region", "value": "east"}],+ })[2])["cluster"]+ ecs_service._register_task_definition(copy.deepcopy(task_definition))+ east_td = json.loads(ecs_service._register_task_definition(+ copy.deepcopy(task_definition)+ )[2])["taskDefinition"]+ east_service = json.loads(ecs_service._create_service({+ "cluster": cluster_name,+ "serviceName": service_name,+ "taskDefinition": family,+ "desiredCount": 0,+ })[2])["service"]+ east_task = json.loads(ecs_service._run_task({+ "cluster": cluster_name,+ "taskDefinition": family,+ })[2])["tasks"][0]+ east_cp = json.loads(ecs_service._create_capacity_provider({+ "name": capacity_provider,+ })[2])["capacityProvider"]+ ecs_service._put_attributes({"attributes": [{+ "targetId": "i-scope",+ "name": "zone",+ "value": "east",+ "targetType": "container-instance",+ }]})+ ecs_service._put_account_setting({"name": "containerInsights", "value": "east"})++ set_request_region("us-west-2")+ assert cluster_name not in ecs_service._clusters+ assert family not in ecs_service._task_def_latest+ assert f"{cluster_name}/{service_name}" not in ecs_service._services+ assert capacity_provider not in ecs_service._capacity_providers+ assert attribute_key not in ecs_service._attributes+ assert "containerInsights" not in ecs_service._account_settings+ assert json.loads(ecs_service._list_tasks({"cluster": cluster_name})[2])["taskArns"] == []++ west_cluster = json.loads(ecs_service._create_cluster({+ "clusterName": cluster_name,+ "tags": [{"key": "region", "value": "west"}],+ })[2])["cluster"]+ west_td = json.loads(ecs_service._register_task_definition(+ copy.deepcopy(task_definition)+ )[2])["taskDefinition"]+ west_service = json.loads(ecs_service._create_service({+ "cluster": cluster_name,+ "serviceName": service_name,+ "taskDefinition": family,+ "desiredCount": 0,+ })[2])["service"]+ west_task = json.loads(ecs_service._run_task({+ "cluster": cluster_name,+ "taskDefinition": family,+ })[2])["tasks"][0]+ west_cp = json.loads(ecs_service._create_capacity_provider({+ "name": capacity_provider,+ })[2])["capacityProvider"]+ ecs_service._put_attributes({"attributes": [{+ "targetId": "i-scope",+ "name": "zone",+ "value": "west",+ "targetType": "container-instance",+ }]})+ ecs_service._put_account_setting({"name": "containerInsights", "value": "west"})++ assert west_cluster["clusterArn"] != east_cluster["clusterArn"]+ assert west_td["revision"] == 1+ assert east_td["revision"] == 2+ assert west_service["serviceArn"] != east_service["serviceArn"]+ assert west_task["taskArn"] != east_task["taskArn"]+ assert west_cp["capacityProviderArn"] != east_cp["capacityProviderArn"]+ assert ecs_service._attributes[attribute_key]["value"] == "west"+ assert ecs_service._account_settings["containerInsights"] == "west"+ assert json.loads(ecs_service._list_tasks({"cluster": cluster_name})[2])["taskArns"] == [+ west_task["taskArn"]+ ]++ # Tags remain account-scoped because their keys are region-bearing ARNs.+ assert json.loads(ecs_service._list_tags_for_resource({+ "resourceArn": east_cluster["clusterArn"],+ })[2])["tags"] == [{"key": "region", "value": "east"}]+ ecs_service._untag_resource({+ "resourceArn": east_cluster["clusterArn"],+ "tagKeys": ["region"],+ })+ assert json.loads(ecs_service._list_tags_for_resource({+ "resourceArn": west_cluster["clusterArn"],+ })[2])["tags"] == [{"key": "region", "value": "west"}]++ set_request_region("us-east-1")+ assert ecs_service._task_def_latest[family] == 2+ assert ecs_service._attributes[attribute_key]["value"] == "east"+ assert ecs_service._account_settings["containerInsights"] == "east"+ assert json.loads(ecs_service._list_tasks({"cluster": cluster_name})[2])["taskArns"] == [+ east_task["taskArn"]+ ]+ assert json.loads(ecs_service._list_tags_for_resource({+ "resourceArn": east_cluster["clusterArn"],+ })[2])["tags"] == []+ finally:+ ecs_service.reset()+ set_request_account_id(original_account)+ set_request_region(original_region)+++def test_ecs_container_secret_arn_selects_the_requested_region():+ """Full secret ARNs select their embedded region without same-name leaks."""+ from ministack.core.responses import (+ get_account_id,+ get_region,+ set_request_account_id,+ set_request_region,+ )+ from ministack.services import secretsmanager as sm_service++ original_account = get_account_id()+ original_region = get_region()+ account_id = "000000000000"+ name = f"ecs-secret-scope-{_uuid_mod.uuid4().hex[:8]}"++ sm_service.reset()+ try:+ set_request_account_id(account_id)+ set_request_region("us-east-1")+ east_arn = json.loads(sm_service._create_secret({+ "Name": name,+ "SecretString": "east-secret",+ })[2])["ARN"]++ set_request_region("us-west-2")+ west_arn = json.loads(sm_service._create_secret({+ "Name": name,+ "SecretString": "west-secret",+ })[2])["ARN"]++ assert ecs_service._resolve_container_secrets({+ "secrets": [{"name": "DB_PASS", "valueFrom": west_arn}],+ }) == {"DB_PASS": "west-secret"}+ assert ecs_service._resolve_container_secrets({+ "secrets": [{"name": "DB_PASS", "valueFrom": east_arn}],+ }) == {"DB_PASS": "east-secret"}+ finally:+ sm_service.reset()+ set_request_account_id(original_account)+ set_request_region(original_region)diff --git a/tests/test_persistence.py b/tests/test_persistence.pyindex 515ca545..29a6f93a 100644--- a/tests/test_persistence.py+++ b/tests/test_persistence.py@@ -836,6 +836,364 @@ def test_ecs_attributes_survive_warm_boot():mod.reset()+def test_ecs_region_scoped_state_survives_warm_boot(monkeypatch):+ """ECS v2 persistence retains every resource's account and region scope."""+ from ministack.core.responses import (+ get_account_id,+ get_region,+ set_request_account_id,+ set_request_region,+ )++ mod = _get_module("ecs")+ original_account = get_account_id()+ original_region = get_region()+ account_id = "111111111111"+ cluster_name = "warm-boot-cluster"+ family = "warm-boot-family"++ monkeypatch.setattr(mod, "_get_docker", lambda: None)+ mod.reset()+ try:+ set_request_account_id(account_id)+ for region, revision in (("us-east-1", 2), ("us-west-2", 1)):+ set_request_region(region)+ cluster_arn = f"arn:aws:ecs:{region}:{account_id}:cluster/{cluster_name}"+ td_key = f"{family}:{revision}"+ td_arn = f"arn:aws:ecs:{region}:{account_id}:task-definition/{td_key}"+ service_key = f"{cluster_name}/warm-boot-service"+ service_arn = (+ f"arn:aws:ecs:{region}:{account_id}:service/"+ f"{cluster_name}/warm-boot-service"+ )+ task_arn = f"arn:aws:ecs:{region}:{account_id}:task/{cluster_name}/{region}"+ cp_arn = f"arn:aws:ecs:{region}:{account_id}:capacity-provider/warm-boot-cp"++ mod._clusters[cluster_name] = {+ "clusterArn": cluster_arn,+ "clusterName": cluster_name,+ "status": "ACTIVE",+ }+ mod._task_defs[td_key] = {+ "taskDefinitionArn": td_arn,+ "family": family,+ "revision": revision,+ }+ mod._task_def_latest[family] = revision+ mod._services[service_key] = {+ "serviceArn": service_arn,+ "serviceName": "warm-boot-service",+ "clusterArn": cluster_arn,+ }+ mod._tasks[task_arn] = {+ "taskArn": task_arn,+ "clusterArn": cluster_arn,+ "lastStatus": "RUNNING",+ "_docker_ids": [f"stale-{region}"],+ }+ mod._capacity_providers["warm-boot-cp"] = {+ "capacityProviderArn": cp_arn,+ "name": "warm-boot-cp",+ }+ mod._attributes["i-warm:zone"] = {+ "targetId": "i-warm",+ "name": "zone",+ "value": region,+ }+ mod._account_settings["containerInsights"] = region+ mod._tags[cluster_arn] = [{"key": "region", "value": region}]++ _round_trip_dict(mod, "ecs")++ for region, revision in (("us-east-1", 2), ("us-west-2", 1)):+ cluster_arn = f"arn:aws:ecs:{region}:{account_id}:cluster/{cluster_name}"+ task_arn = f"arn:aws:ecs:{region}:{account_id}:task/{cluster_name}/{region}"+ assert mod._clusters.get_scoped(account_id, region, cluster_name)["clusterArn"] == (+ cluster_arn+ )+ assert mod._task_def_latest.get_scoped(account_id, region, family) == revision+ assert mod._account_settings.get_scoped(+ account_id, region, "containerInsights"+ ) == region+ assert mod._attributes.get_scoped(account_id, region, "i-warm:zone")["value"] == (+ region+ )+ restored_task = mod._tasks.get_scoped(account_id, region, task_arn)+ assert restored_task["lastStatus"] == "STOPPED"+ assert restored_task["_docker_ids"] == []+ assert mod._tags.get_scoped(account_id, region, cluster_arn) == [+ {"key": "region", "value": region}+ ]+ finally:+ mod.reset()+ set_request_account_id(original_account)+ set_request_region(original_region)+++def test_ecs_legacy_account_scoped_state_migrates_by_arn(monkeypatch, tmp_path):+ """Legacy ECS state adopts ARN regions and boot-scopes ARN-less stores."""+ import json as _json++ from ministack.core.responses import (+ AccountScopedDict,+ get_account_id,+ get_region,+ set_request_account_id,+ set_request_region,+ )++ mod = _get_module("ecs")+ original_account = get_account_id()+ original_region = get_region()+ account_id = "111111111111"+ boot_region = "us-east-1"+ resource_region = "us-west-2"+ cluster_name = "legacy-cluster"+ family = "legacy-family"+ cluster_arn = f"arn:aws:ecs:{resource_region}:{account_id}:cluster/{cluster_name}"+ service_key = f"{cluster_name}/legacy-service"+ service_arn = (+ f"arn:aws:ecs:{resource_region}:{account_id}:service/"+ f"{cluster_name}/legacy-service"+ )+ task_arn = (+ f"arn:aws:ecs:{resource_region}:{account_id}:task/"+ f"{cluster_name}/legacy-task"+ )++ def scoped(key, value):+ store = AccountScopedDict()+ store._data[(account_id, key)] = value+ return store++ legacy_payload = {+ "clusters": scoped(cluster_name, {+ "clusterArn": cluster_arn,+ "clusterName": cluster_name,+ "status": "ACTIVE",+ }),+ "task_defs": scoped(family + ":3", {+ "taskDefinitionArn": (+ f"arn:aws:ecs:{resource_region}:{account_id}:"+ f"task-definition/{family}:3"+ ),+ "family": family,+ "revision": 3,+ }),+ "task_def_latest": scoped(family, 3),+ "services": scoped(service_key, {+ "serviceArn": service_arn,+ "serviceName": "legacy-service",+ "clusterArn": cluster_arn,+ }),+ "tasks": scoped(task_arn, {+ "taskArn": task_arn,+ "clusterArn": cluster_arn,+ "lastStatus": "RUNNING",+ "_docker_ids": ["stale-container"],+ }),+ "account_settings": scoped("containerInsights", "enabled"),+ "attributes": scoped("i-legacy:zone", {+ "targetId": "i-legacy",+ "name": "zone",+ "value": "legacy",+ }),+ }++ monkeypatch.setattr(mod, "_get_docker", lambda: None)+ monkeypatch.setattr(persistence, "PERSIST_STATE", True)+ monkeypatch.setattr(persistence, "STATE_DIR", str(tmp_path))+ mod.reset()+ try:+ set_request_account_id(account_id)+ set_request_region(boot_region)+ with open(tmp_path / "ecs.json", "w") as f:+ _json.dump(legacy_payload, f, default=persistence._json_default)++ loaded = persistence.load_state("ecs")+ assert isinstance(loaded["tasks"], AccountScopedDict)+ mod.restore_state(loaded)++ assert mod._clusters.get_scoped(account_id, resource_region, cluster_name)[+ "clusterArn"+ ] == cluster_arn+ assert mod._services.get_scoped(account_id, resource_region, service_key)[+ "serviceArn"+ ] == service_arn+ restored_task = mod._tasks.get_scoped(account_id, resource_region, task_arn)+ assert restored_task["lastStatus"] == "STOPPED"+ assert restored_task["_docker_ids"] == []++ assert mod._task_def_latest.get_scoped(account_id, boot_region, family) is None+ assert mod._task_def_latest.get_scoped(account_id, resource_region, family) == 3++ set_request_region(resource_region)+ described = _json.loads(+ mod._describe_task_definition({"taskDefinition": family})[2]+ )["taskDefinition"]+ assert described["taskDefinitionArn"].endswith(+ f"task-definition/{family}:3"+ )++ registered = _json.loads(mod._register_task_definition({+ "family": family,+ "containerDefinitions": [{"name": "app", "image": "busybox"}],+ })[2])["taskDefinition"]+ assert registered["revision"] == 4+ assert mod._task_defs.get_scoped(+ account_id, resource_region, family + ":3"+ )["taskDefinitionArn"] == described["taskDefinitionArn"]+ assert mod._task_defs.get_scoped(+ account_id, resource_region, family + ":4"+ )["taskDefinitionArn"] == registered["taskDefinitionArn"]++ # Other ARN-less legacy stores intentionally adopt the boot region.+ assert mod._account_settings.get_scoped(+ account_id, boot_region, "containerInsights"+ ) == "enabled"+ assert mod._attributes.get_scoped(account_id, boot_region, "i-legacy:zone")[+ "value"+ ] == "legacy"+ finally:+ mod.reset()+ set_request_account_id(original_account)+ set_request_region(original_region)+++def test_ecs_legacy_task_revision_migration_reconstructs_each_region(monkeypatch):+ """Legacy shared counters do not reset revisions in other ARN regions."""+ import json as _json++ from ministack.core.responses import (+ AccountScopedDict,+ get_account_id,+ get_region,+ set_request_account_id,+ set_request_region,+ )++ mod = _get_module("ecs")+ original_account = get_account_id()+ original_region = get_region()+ account_id = "111111111111"+ boot_region = "us-east-1"+ other_region = "us-west-2"+ family = "multi-region-legacy-family"++ legacy_task_defs = AccountScopedDict()+ for region, revision, marker in (+ (boot_region, 1, "east-original"),+ (other_region, 2, "west-original"),+ ):+ key = f"{family}:{revision}"+ legacy_task_defs._data[(account_id, key)] = {+ "taskDefinitionArn": (+ f"arn:aws:ecs:{region}:{account_id}:task-definition/{key}"+ ),+ "family": family,+ "revision": revision,+ "status": "ACTIVE",+ "marker": marker,+ }++ legacy_latest = AccountScopedDict()+ legacy_latest._data[(account_id, family)] = 2++ monkeypatch.setattr(mod, "_get_docker", lambda: None)+ mod.reset()+ try:+ set_request_account_id(account_id)+ set_request_region(boot_region)+ mod.restore_state({+ "task_defs": legacy_task_defs,+ "task_def_latest": legacy_latest,+ })++ assert mod._task_def_latest.get_scoped(+ account_id, boot_region, family+ ) == 1+ assert mod._task_def_latest.get_scoped(+ account_id, other_region, family+ ) == 2++ for region, restored_revision, next_revision in (+ (boot_region, 1, 2),+ (other_region, 2, 3),+ ):+ set_request_region(region)+ status, _, body = mod._describe_task_definition({+ "taskDefinition": family,+ })+ assert status == 200+ described = _json.loads(body)["taskDefinition"]+ assert described["revision"] == restored_revision+ assert described["taskDefinitionArn"].startswith(+ f"arn:aws:ecs:{region}:{account_id}:"+ )++ status, _, body = mod._register_task_definition({+ "family": family,+ "containerDefinitions": [{"name": "app", "image": "busybox"}],+ })+ assert status == 200+ assert _json.loads(body)["taskDefinition"]["revision"] == next_revision++ assert mod._task_defs.get_scoped(+ account_id, boot_region, f"{family}:1"+ )["marker"] == "east-original"+ assert mod._task_defs.get_scoped(+ account_id, other_region, f"{family}:2"+ )["marker"] == "west-original"+ finally:+ mod.reset()+ set_request_account_id(original_account)+ set_request_region(original_region)+++def test_ecs_plain_dict_tasks_migrate_to_arn_region(monkeypatch):+ """Oldest bare-dict task state restores under the task ARN region."""+ from ministack.core.responses import (+ get_account_id,+ get_region,+ set_request_account_id,+ set_request_region,+ )++ mod = _get_module("ecs")+ original_account = get_account_id()+ original_region = get_region()+ account_id = "111111111111"+ boot_region = "us-east-1"+ resource_region = "us-west-2"+ task_arn = f"arn:aws:ecs:{resource_region}:{account_id}:task/legacy-cluster/legacy-task"++ monkeypatch.setattr(mod, "_get_docker", lambda: None)+ mod.reset()+ try:+ set_request_account_id(account_id)+ set_request_region(boot_region)+ mod.restore_state(+ {+ "tasks": {+ task_arn: {+ "taskArn": task_arn,+ "lastStatus": "RUNNING",+ "_docker_ids": ["stale-container"],+ },+ },+ }+ )++ restored_task = mod._tasks.get_scoped(account_id, resource_region, task_arn)+ assert restored_task["lastStatus"] == "STOPPED"+ assert restored_task["_docker_ids"] == []+ assert mod._tasks.get_scoped(account_id, boot_region, task_arn) is None+ finally:+ mod.reset()+ set_request_account_id(original_account)+ set_request_region(original_region)++# ── sns._platform_applications + sns._platform_endpoints ──────────────def test_sns_platform_applications_survive_warm_boot():@@ -1348,22 +1706,52 @@ def test_legacy_unwrapped_state_file_loads_and_migrates_region(monkeypatch, tmp_assert region_store["res-1"]["Arn"].startswith("arn:aws:appconfig:eu-west-1")-def test_state_format_version_stamp_round_trips_and_refuses_newer(monkeypatch, tmp_path):- """U4: save_state stamps the on-disk format version and load_state unwraps- it; a file written by a NEWER binary is refused rather than mis-parsed."""+def test_default_state_format_version_stays_v2_and_refuses_newer(monkeypatch, tmp_path):+ """U4: unchanged services stay on v2 and refuse newer state files."""import json as _jsonmonkeypatch.setattr(persistence, "PERSIST_STATE", True)monkeypatch.setattr(persistence, "STATE_DIR", str(tmp_path))- persistence.save_state("ver", {"k": "v"})- raw = _json.loads((tmp_path / "ver.json").read_text())- assert raw["__ministack_format__"] == persistence.STATE_FORMAT_VERSION+ persistence.save_state("sqs", {"k": "v"})+ raw = _json.loads((tmp_path / "sqs.json").read_text())+ assert raw["__ministack_format__"] == persistence.STATE_FORMAT_VERSION == 2assert raw["payload"] == {"k": "v"}- assert persistence.load_state("ver") == {"k": "v"}+ assert persistence.load_state("sqs") == {"k": "v"}(tmp_path / "future.json").write_text(_json.dumps({"__ministack_format__": persistence.STATE_FORMAT_VERSION + 1,"payload": {"k": "v"},}))assert persistence.load_state("future") is None+++def test_ecs_region_scoped_state_is_rejected_by_v2_reader(monkeypatch, tmp_path):+ """A rollback binary must reject ECS's regional schema instead of+ accepting it as v2 and silently dropping every regional store."""+ import json as _json++ from ministack.core.responses import AccountRegionScopedDict++ monkeypatch.setattr(persistence, "PERSIST_STATE", True)+ monkeypatch.setattr(persistence, "STATE_DIR", str(tmp_path))++ clusters = AccountRegionScopedDict()+ clusters.set_scoped(+ "000000000000",+ "us-west-2",+ "regional-cluster",+ {"clusterArn": "arn:aws:ecs:us-west-2:000000000000:cluster/regional-cluster"},+ )+ persistence.save_state("ecs", {"clusters": clusters})++ raw = _json.loads((tmp_path / "ecs.json").read_text())+ assert raw["__ministack_format__"] == 3+ loaded_clusters = persistence.load_state("ecs")["clusters"]+ assert loaded_clusters.get_scoped(+ "000000000000", "us-west-2", "regional-cluster"+ )["clusterArn"].endswith("cluster/regional-cluster")++ # Simulate the previous binary, whose highest understood format is v2.+ monkeypatch.setattr(persistence, "SERVICE_STATE_FORMAT_VERSIONS", {})+ assert persistence.load_state("ecs") is None