Skip to content

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

refactor(persistence): derive state map from registry (#1726)

Johannes Grumböck768e75e8b0de
diff --git a/ministack/app.py b/ministack/app.py
index f5a6a44b..59052094 100644
--- a/ministack/app.py
+++ b/ministack/app.py
@@ -348,7 +348,11 @@ SERVICE_REGISTRY = {
"acm": {"module": "acm"},
"backup": {"module": "backup"},
"batch": {"module": "batch"},
- "apigateway": {"module": "apigateway", "aliases": ("execute-api", "apigatewayv2")},
+ "apigateway": {
+ "module": "apigateway",
+ "aliases": ("execute-api", "apigatewayv2"),
+ "sub_modules": ("apigateway_v1",),
+ },
"appconfig": {"module": "appconfig"},
"appconfigdata": {"module": "appconfig"},
"appsync": {"module": "appsync"},
@@ -387,7 +391,14 @@ SERVICE_REGISTRY = {
"iotwireless": {"module": "iotwireless"},
"kinesis": {"module": "kinesis"},
"kms": {"module": "kms"},
- "lambda": {"module": "lambda_svc"},
+ # ``lambda`` is a Python keyword, so the implementation module is named
+ # ``lambda_svc``. Keep ``lambda`` as the persistence key to preserve the
+ # long-standing ``lambda.json`` state-file contract across warm boots.
+ "lambda": {
+ "module": "lambda_svc",
+ "state_key": "lambda",
+ "sub_modules": ("lambda_durable",),
+ },
"lambda-core": {"module": "lambda_core"},
"lambda-microvms": {"module": "lambda_microvms"},
"location": {"module": "location"},
@@ -406,7 +417,7 @@ SERVICE_REGISTRY = {
"scheduler": {"module": "scheduler"},
"secretsmanager": {"module": "secretsmanager"},
"servicediscovery": {"module": "servicediscovery"},
- "ses": {"module": "ses"},
+ "ses": {"module": "ses", "sub_modules": ("ses_v2",)},
"signer": {"module": "signer"},
"sns": {"module": "sns"},
"sqs": {"module": "sqs"},
@@ -437,86 +448,33 @@ SERVICE_HANDLERS = {
service_name: _lazy_handler(service_config["module"]) for service_name, service_config in SERVICE_REGISTRY.items()
}
-# Maps the on-disk persistence key to the service module name. `save_all`
-# (lifespan.shutdown) consumes this. Restore happens at module import time
-# in each service via its own `load_state()` call (see e.g. services/sqs.py);
-# a small allow-list is also restored centrally by `_load_persisted_state`
-# below. Symmetry between save and restore is enforced by
-# tests/test_persistence.py.
-_state_map = {
- "apigateway": "apigateway",
- "apigateway_v1": "apigateway_v1",
- "cloudformation": "cloudformation",
- "sqs": "sqs",
- "sns": "sns",
- "ssm": "ssm",
- "secretsmanager": "secretsmanager",
- "iam": "iam",
- "dynamodb": "dynamodb",
- "kms": "kms",
- "eventbridge": "eventbridge",
- "cloudwatch_logs": "cloudwatch_logs",
- "kinesis": "kinesis",
- "ec2": "ec2",
- "route53": "route53",
- "cognito": "cognito",
- "ecr": "ecr",
- "cloudwatch": "cloudwatch",
- "s3": "s3",
- "lambda": "lambda_svc",
- "lambda_core": "lambda_core",
- "lambda_microvms": "lambda_microvms",
- "rds": "rds",
- "ecs": "ecs",
- "elasticache": "elasticache",
- "appsync": "appsync",
- "appsync_events": "appsync_events",
- "stepfunctions": "stepfunctions",
- "alb": "alb",
- "glue": "glue",
- "mwaa": "mwaa",
- "efs": "efs",
- "waf": "waf",
- "athena": "athena",
- "emr": "emr",
- "cloudfront": "cloudfront",
- "codebuild": "codebuild",
- "batch": "batch",
- "acm": "acm",
- "firehose": "firehose",
- "ses": "ses",
- "ses_v2": "ses_v2",
- "servicediscovery": "servicediscovery",
- "s3files": "s3files",
- "appconfig": "appconfig",
- "transfer": "transfer",
- "scheduler": "scheduler",
- "autoscaling": "autoscaling",
- "eks": "eks",
- "backup": "backup",
- "pipes": "pipes",
- "cloudfront_keyvaluestore": "cloudfront_keyvaluestore",
- "resource_groups": "resource_groups",
- "cloudtrail": "cloudtrail",
- "iot": "iot",
- "inspector2": "inspector2",
- "dsql": "dsql",
- "location": "location",
- "mediaconnect": "mediaconnect",
- "mq": "mq",
- "signer": "signer",
- "opensearch": "opensearch",
- "s3tables": "s3tables",
- "lambda_durable": "lambda_durable",
- "bedrock": "bedrock",
- "bedrock_runtime": "bedrock_runtime",
- "bedrock_agent": "bedrock_agent",
- "bedrock_agent_runtime": "bedrock_agent_runtime",
- "bedrock_agentcore": "bedrock_agentcore",
- "msk": "msk",
- "transcribe": "transcribe",
- "translate": "translate",
-}
+def _registry_module_names():
+ """Return every primary and dispatched module declared by the registry."""
+ return {
+ module
+ for config in SERVICE_REGISTRY.values()
+ for module in (config["module"], *config.get("sub_modules", ()))
+ }
+
+
+def _registry_state_map():
+ """Map persistence-file keys to modules declared by ``SERVICE_REGISTRY``.
+
+ A primary module normally uses its module name for the filename. Lambda
+ retains its long-standing ``lambda.json`` filename through ``state_key``;
+ sub-modules always use their own names.
+ """
+ state_map = {}
+ for config in SERVICE_REGISTRY.values():
+ module = config["module"]
+ state_map[config.get("state_key", module)] = module
+ state_map.update({sub_module: sub_module for sub_module in config.get("sub_modules", ())})
+ return state_map
+
+
+# Maps on-disk persistence keys to service modules. The registry is the sole
+# declaration point, including modules reached through a service's dispatcher.
+_state_map = _registry_state_map()
SERVICE_NAME_ALIASES = {
alias: service_name
@@ -2729,12 +2687,14 @@ def _load_persisted_state():
_get_module(svc_key).load_persisted_state(data)
logger.info("Loaded persisted state for %s", svc_key)
- # Eagerly import persisted services whose restore path depends on
- # a module-level `load_state()` side-effect, but which would not
- # otherwise be imported during startup. The lazy router does not
- # pull them in early enough in any of these cases:
+ # Eagerly import persisted services whose restore path depends on a
+ # module-level `load_state()` side-effect, but which would not otherwise
+ # be imported during startup. Their registry declarations ensure they are
+ # saved and reset; the lazy router still does not pull them in early enough
+ # in these cases:
# - `ses_v2` is reached via the `/v2/email/*` path-prefix shortcut.
- # - `pipes` is created only via CloudFormation provisioners.
+ # - `pipes` is commonly created via CloudFormation provisioners, without
+ # a preceding Pipes API request.
# - `appsync_events` is routable (SERVICE_REGISTRY has
# "appsync-events") but real traffic arrives under the
# `appsync` credential scope at `/v2/apis`, so the
@@ -2961,16 +2921,7 @@ def _reset_all_state():
from ministack.core.persistence import PERSIST_STATE, STATE_DIR
- # Stateful modules that don't have a routing entry in SERVICE_REGISTRY but
- # still need reset() — REST API v1 (served via the apigateway module),
- # SES v2 (served via the ses module), and EventBridge Pipes (CFN-only
- # provisioner with a background poller thread that reset() must stop).
- # Kept for documentation / safety even though the `sys.modules` fallback
- # below catches every imported module regardless.
- _extra_reset_modules = ("apigateway_v1", "ses_v2", "pipes")
-
- module_names = {cfg["module"] for cfg in SERVICE_REGISTRY.values()}
- module_names.update(_extra_reset_modules)
+ module_names = _registry_module_names()
for mod_name in module_names:
# Same class fix as the shutdown save loop: a module reached only via
diff --git a/tests/test_persistence.py b/tests/test_persistence.py
index 0b375224..92e637a7 100644
--- a/tests/test_persistence.py
+++ b/tests/test_persistence.py
@@ -3,18 +3,12 @@ Regression tests for the persistence-symmetry architectural bug.
Background
----------
-When PERSIST_STATE=1, every service that participates in `_state_map`
-(see `ministack/app.py`) is saved on shutdown via `save_all()`. State is
-restored on startup either by a service's own `load_state()` call at
-module import time, OR by `_load_persisted_state()` which calls a
-`load_persisted_state()` method on the service module.
-
-For five services (autoscaling, backup, eks, scheduler, pipes), the
-shutdown path persists the state to disk but no restore path runs at
-startup, so the next boot starts with an empty store. `pipes` is
-additionally missing from `_state_map`, so its state is never even saved.
-
-These tests assert the round-trip works for every persisted service.
+When PERSIST_STATE=1, the registry-derived `_state_map` in
+`ministack/app.py` supplies each loaded service's `get_state()` function
+to `save_all()` at shutdown. State is currently restored either by a
+service's import-time `load_state()` call or by `_load_persisted_state()`.
+
+These tests protect persistence round trips and the registry contract.
"""
import ast
import importlib
@@ -25,11 +19,6 @@ import pytest
from ministack.app import _state_map # noqa: E402 (intentional internal import)
from ministack.core import persistence
-# Services that MUST be persistence-round-trippable. Every entry of
-# `_state_map` qualifies. The set is materialised here so an addition to
-# `_state_map` automatically gets coverage.
-ALL_PERSISTED_SERVICES = sorted(_state_map.items())
-
def _module(mod_name):
return importlib.import_module(f"ministack.services.{mod_name}")
@@ -452,45 +441,8 @@ def test_appsync_events_v2_region_scoped_state_round_trip(monkeypatch, tmp_path)
set_request_region(original_region)
[email protected]("svc_key,mod_name", ALL_PERSISTED_SERVICES)
-def test_service_has_restore_path(svc_key, mod_name):
- """Every service in `_state_map` must expose a way to restore its own state.
-
- Either:
- (a) the module calls `load_state()` itself at import time, OR
- (b) the module exposes `load_persisted_state(data)` AND is wired into
- `_load_persisted_state()` in app.py.
- """
- mod = _module(mod_name)
- src = Path(mod.__file__).read_text()
-
- # (a) self-restore at import: must import load_state AND call it.
- self_restoring = (
- "from ministack.core.persistence import" in src
- and "load_state" in src
- and "load_state(" in src
- )
-
- # (b) centrally restored: must define load_persisted_state and be in
- # the explicit allow-list in app.py's `_load_persisted_state()`.
- has_central_method = hasattr(mod, "load_persisted_state")
- centrally_restored = has_central_method and svc_key in {
- "apigateway", "apigateway_v1", "servicediscovery",
- }
-
- assert self_restoring or centrally_restored, (
- f"Service `{svc_key}` (module `{mod_name}`) is in `_state_map` and "
- f"will be saved on shutdown, but has no restore path on startup. "
- f"Either add `load_state()` at module top, or define "
- f"`load_persisted_state(data)` and add it to "
- f"`_load_persisted_state()` in app.py."
- )
-
-
def test_pipes_is_in_state_map():
- """`pipes` defines `get_state()` so it expects to be persisted, but it
- is missing from `_state_map`. Without this, pipe definitions evaporate
- on every restart even before considering restore-path coverage."""
+ """The registry-derived map includes the Pipes service contract."""
pipes = _module("pipes")
assert hasattr(pipes, "get_state"), "pipes module no longer has get_state — update this test"
assert "pipes" in _state_map, (
@@ -499,44 +451,19 @@ def test_pipes_is_in_state_map():
)
-def test_state_map_services_without_endpoint_are_eagerly_imported():
- """Services in `_state_map` but NOT in `SERVICE_REGISTRY` have no
- AWS endpoint, so the lazy router never imports them. Their
- import-time `load_state()` block therefore never fires unless
- `_load_persisted_state()` eagerly imports them at startup.
-
- Without this, persisted RUNNING pipes don't resume their poller
- after warm-boot until something else happens to import the
- module (e.g. a new CFN pipe registration) — silently breaking
- event forwarding for the entire window between restart and the
- next pipe-related API call."""
- import inspect
-
- from ministack.app import SERVICE_REGISTRY, _load_persisted_state
-
- # Find services that need eager import.
- routable_modules = {cfg["module"] for cfg in SERVICE_REGISTRY.values()}
- needs_eager_import = [
- mod_name for _, mod_name in _state_map.items()
- if mod_name not in routable_modules
- ]
- assert needs_eager_import, (
- "Test premise broken: every persisted module is now also routable, "
- "so this test would never catch the bug it's guarding against. "
- "Update it or delete it."
- )
+def test_state_map_is_derived_from_service_registry():
+ """The registry is the only declaration point for persisted modules."""
+ from ministack.app import SERVICE_REGISTRY, _registry_module_names, _registry_state_map
- # The eager-import section in _load_persisted_state must reference each
- # such module by name, otherwise it stays unimported and its restore
- # never runs.
- src = inspect.getsource(_load_persisted_state)
- for mod_name in needs_eager_import:
- assert f'"{mod_name}"' in src or f"'{mod_name}'" in src, (
- f"Service `{mod_name}` is in `_state_map` but not in "
- f"`SERVICE_REGISTRY`, and `_load_persisted_state()` doesn't "
- f"eagerly import it. With PERSIST_STATE=1, its persisted "
- f"state will be silently ignored on warm-boot."
- )
+ expected = {}
+ for config in SERVICE_REGISTRY.values():
+ module = config["module"]
+ expected[config.get("state_key", module)] = module
+ expected.update({sub_module: sub_module for sub_module in config.get("sub_modules", ())})
+
+ assert _state_map == expected
+ assert _registry_state_map() == expected
+ assert _registry_module_names() == set(expected.values())
def test_save_dict_includes_sibling_imported_modules():
@@ -584,27 +511,28 @@ def test_save_dict_includes_sibling_imported_modules():
_loaded_modules["appsync_events"] = saved
-def test_save_dict_skips_modules_never_imported():
+def test_save_dict_skips_modules_never_imported(monkeypatch):
"""The sys.modules fallback must NOT save state for modules that
were never imported at all — there's no state to capture and any
`get_state()` call on a non-imported module would attribute-error.
Defensive guard: ensure the fallback path's `hasattr` check works."""
- from ministack.app import _build_persistence_save_dict, _state_map
+ import sys
- # Pick any persisted module and ensure it's truly absent from both
- # `_loaded_modules` and `sys.modules`. `cur` is an obscure one that
- # most test sessions won't have touched.
- target = "ecs_metadata" # not in _state_map → guaranteed absent from save_dict
- assert target not in {v for v in _state_map.values()}, (
- "test premise broken — pick a module not in _state_map"
- )
+ from ministack.app import _build_persistence_save_dict, _loaded_modules, _state_map
+
+ # Every registered module is now represented in `_state_map`, so force a
+ # known entry absent from both sources instead of relying on an exclusion.
+ target = "account"
+ assert target in _state_map.values(), "test premise broken — account must be registry-derived"
+ monkeypatch.delitem(_loaded_modules, target, raising=False)
+ monkeypatch.delitem(sys.modules, f"ministack.services.{target}", raising=False)
- # Even after the fallback path runs, ecs_metadata must not appear.
+ # Even after the fallback path runs, an unloaded module must not appear.
save_dict = _build_persistence_save_dict()
- assert "ecs_metadata" not in save_dict, (
- "save_dict picked up a module that isn't even in _state_map — "
- "the loop's key-membership check is broken."
+ assert target not in save_dict, (
+ "save_dict picked up a module that was absent from both module caches — "
+ "the fallback's unloaded-module guard is broken."
)