Skip to content

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

fix(EC, EB, SQS): add timeout in sqs, respawned redis, eb anyhthing but prefix (#858)

Nahuel Nucera91a5435709f8
diff --git a/ministack/services/elasticache.py b/ministack/services/elasticache.py
index a6e172a0..69707e64 100644
--- a/ministack/services/elasticache.py
+++ b/ministack/services/elasticache.py
@@ -100,12 +100,27 @@ def get_state():
return state
+# Issue #853: after restart the persisted Docker container ids reference
+# containers that no longer exist. Metadata says "available" but no Redis
+# is running, so Terraform / SDKs see a healthy cluster they can't connect
+# to. We can't respawn at restore_state time because that runs during
+# module-import (before _spawn_redis_container is defined). Instead, mark
+# resources as pending and respawn lazily on the first dispatcher call —
+# Terraform's typical flow is DescribeCacheClusters → connect, so the
+# container is healthy by the time the SDK reaches the endpoint.
+_pending_cluster_respawn: set = set()
+_pending_rg_respawn: set = set()
+
+
def restore_state(data):
if not data:
return
for name, rg in data.get("replication_groups", {}).items():
- rg.setdefault("_docker_container_ids", [])
+ # Wipe stale container ids — the old Docker containers are dead.
+ # _ensure_live_containers will refill this list lazily.
+ rg["_docker_container_ids"] = []
_replication_groups[name] = rg
+ _pending_rg_respawn.add(name)
_subnet_groups.update(data.get("subnet_groups", {}))
_param_groups.update(data.get("param_groups", {}))
_param_group_params.update(data.get("param_group_params", {}))
@@ -119,6 +134,70 @@ def restore_state(data):
cl["_docker_container_id"] = None
cl["CacheClusterStatus"] = "available"
_clusters[name] = cl
+ _pending_cluster_respawn.add(name)
+
+
+def _ensure_live_containers():
+ """Lazy respawn of containers for clusters/replication-groups restored
+ from disk. Called from the top of handle_request, runs once per pending
+ resource. Failures are logged and the pending flag is cleared so we
+ don't retry on every request — the cluster's metadata is still served
+ but the endpoint won't be reachable (matches the old behavior, just no
+ longer silent)."""
+ if not (_pending_cluster_respawn or _pending_rg_respawn):
+ return
+ import logging
+ log = logging.getLogger(__name__)
+ for name in list(_pending_cluster_respawn):
+ _pending_cluster_respawn.discard(name)
+ cl = _clusters.get(name)
+ if cl is None:
+ continue
+ try:
+ engine = cl.get("Engine", "redis")
+ version = cl.get("EngineVersion", "7.1")
+ host, port, cid = _spawn_redis_container(
+ name=f"ministack-elasticache-{name}",
+ engine=engine, engine_version=version,
+ labels={"ministack": "elasticache", "cluster_id": name},
+ )
+ cl["_docker_container_id"] = cid
+ for node in cl.get("CacheNodes") or []:
+ node["Endpoint"] = {"Address": host, "Port": port}
+ if cl.get("ConfigurationEndpoint"):
+ cl["ConfigurationEndpoint"] = {"Address": host, "Port": port}
+ log.info("elasticache: respawned container for cluster %s after restart", name)
+ except Exception:
+ log.warning(
+ "elasticache: failed to respawn container for cluster %s on restart; "
+ "endpoint will be unreachable", name, exc_info=True)
+ for rg_id in list(_pending_rg_respawn):
+ _pending_rg_respawn.discard(rg_id)
+ rg = _replication_groups.get(rg_id)
+ if rg is None:
+ continue
+ try:
+ engine = rg.get("Engine", "redis")
+ engine_version = rg.get("EngineVersion") or rg.get("CacheNodeType") or "7.1"
+ account_id = get_account_id()
+ node_groups = rg.get("NodeGroups") or []
+ for ng in node_groups:
+ ng_id = ng.get("NodeGroupId", "0001")
+ _, _, cid = _spawn_redis_container(
+ name=f"ministack-elasticache-rg-{account_id}-{rg_id}-{ng_id}",
+ engine=engine, engine_version=engine_version,
+ labels={
+ "ministack": "elasticache", "rg_id": rg_id,
+ "node_group": ng_id, "account_id": account_id,
+ },
+ )
+ if cid:
+ rg["_docker_container_ids"].append(cid)
+ log.info("elasticache: respawned containers for replication group %s after restart", rg_id)
+ except Exception:
+ log.warning(
+ "elasticache: failed to respawn containers for replication group %s "
+ "on restart; endpoint will be unreachable", rg_id, exc_info=True)
try:
@@ -476,6 +555,9 @@ def _record_event(source_id, source_type, message):
async def handle_request(method, path, headers, body, query_params):
+ # Lazy-respawn any clusters / replication groups that were restored
+ # from disk (issue #853). Cheap fast-path when nothing's pending.
+ _ensure_live_containers()
params = dict(query_params)
if method == "POST" and body:
form_params = parse_qs(body.decode("utf-8", errors="replace"))
diff --git a/ministack/services/eventbridge.py b/ministack/services/eventbridge.py
index 99343c87..da9536de 100644
--- a/ministack/services/eventbridge.py
+++ b/ministack/services/eventbridge.py
@@ -871,6 +871,13 @@ def _matches_content_filter(value, filter_rule):
return isinstance(value, str) and value.endswith(filter_rule["suffix"])
if "anything-but" in filter_rule:
excluded = filter_rule["anything-but"]
+ # Per AWS EventBridge docs, anything-but supports either a literal
+ # / list-of-literals OR a single nested content matcher (prefix,
+ # suffix, wildcard, equals-ignore-case). Mixing literals and nested
+ # matchers in a list is explicitly rejected by AWS at rule
+ # creation, so we match the strict form only.
+ if isinstance(excluded, dict):
+ return not _matches_content_filter(value, excluded)
if isinstance(excluded, list):
return value not in excluded
return value != excluded
diff --git a/ministack/services/sqs.py b/ministack/services/sqs.py
index a87bb901..d81f6f6c 100644
--- a/ministack/services/sqs.py
+++ b/ministack/services/sqs.py
@@ -200,6 +200,35 @@ def _validate_redrive_policy(rp_str: str) -> None:
raise _Err("InvalidAttributeValue", err_msg, 400)
+# Numeric attribute ranges per the SQS botocore service-2.json
+# (sqs-2012-11-05). Real AWS rejects out-of-range values at
+# CreateQueue/SetQueueAttributes time with InvalidAttributeValue (400).
+_NUMERIC_ATTR_RANGES = {
+ "VisibilityTimeout": (0, 43200), # 0 .. 12 h
+ "MaximumMessageSize": (1024, 262144), # 1 KB .. 256 KB
+ "MessageRetentionPeriod": (60, 1209600), # 1 min .. 14 days
+ "DelaySeconds": (0, 900), # 0 .. 15 min
+ "ReceiveMessageWaitTimeSeconds":(0, 20), # 0 .. 20 s
+ "KmsDataKeyReusePeriodSeconds": (60, 86400), # 1 min .. 24 h
+}
+
+
+def _validate_numeric_attrs(attrs: dict) -> None:
+ for key, (lo, hi) in _NUMERIC_ATTR_RANGES.items():
+ if key not in attrs:
+ continue
+ raw = attrs[key]
+ try:
+ n = int(str(raw))
+ except (TypeError, ValueError):
+ raise _Err("InvalidAttributeValue",
+ f"Invalid value for the parameter {key}.", 400)
+ if n < lo or n > hi:
+ raise _Err("InvalidAttributeValue",
+ f"Invalid value for the parameter {key}. "
+ f"Value must be between {lo} and {hi}.", 400)
+
+
def _act_create_queue(data: dict, _u: str) -> dict:
name = data.get("QueueName", "")
if not name:
@@ -209,6 +238,7 @@ def _act_create_queue(data: dict, _u: str) -> dict:
attrs = data.get("Attributes") or {}
if "RedrivePolicy" in attrs:
_validate_redrive_policy(str(attrs["RedrivePolicy"]))
+ _validate_numeric_attrs(attrs)
is_fifo = name.endswith(".fifo") or attrs.get("FifoQueue") == "true"
if is_fifo and not name.endswith(".fifo"):
@@ -547,6 +577,7 @@ def _act_set_queue_attributes(data: dict, qurl: str) -> dict:
incoming = data.get("Attributes") or {}
if "RedrivePolicy" in incoming:
_validate_redrive_policy(str(incoming["RedrivePolicy"]))
+ _validate_numeric_attrs(incoming)
for k, v in incoming.items():
q["attributes"][k] = str(v)
q["attributes"]["LastModifiedTimestamp"] = str(int(time.time()))
diff --git a/tests/test_elasticache.py b/tests/test_elasticache.py
index 665bf44f..067a9631 100644
--- a/tests/test_elasticache.py
+++ b/tests/test_elasticache.py
@@ -11,7 +11,16 @@ from botocore.exceptions import ClientError
ENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
+# Most ElastiCache tests need a live Docker network because CreateCacheCluster
+# spawns a real Redis container. Mark them with @requires_docker so they skip
+# cleanly in CI without docker, while unit-style tests (e.g. the #853 respawn
+# tests at the bottom of this file) still run.
+requires_docker = pytest.mark.skipif(
+ not os.environ.get("DOCKER_NETWORK"),
+ reason="DOCKER_NETWORK not set - skipping network connectivity test",
+)
+@requires_docker
def test_elasticache_create(ec):
ec.create_cache_cluster(
CacheClusterId="test-redis",
@@ -25,6 +34,7 @@ def test_elasticache_create(ec):
assert clusters[0]["CacheClusterId"] == "test-redis"
assert clusters[0]["Engine"] == "redis"
+@requires_docker
def test_elasticache_cache_node_full_fields(ec):
"""terraform-provider-aws v6 derefs CacheNodeCreateTime / ParameterGroupStatus /
CustomerAvailabilityZone without nil checks. Issue #675."""
@@ -43,6 +53,7 @@ def test_elasticache_cache_node_full_fields(ec):
assert node["CacheNodeStatus"] == "available"
+@requires_docker
def test_elasticache_replication_group(ec):
ec.create_replication_group(
ReplicationGroupId="test-rg",
@@ -52,10 +63,12 @@ def test_elasticache_replication_group(ec):
resp = ec.describe_replication_groups(ReplicationGroupId="test-rg")
assert resp["ReplicationGroups"][0]["ReplicationGroupId"] == "test-rg"
+@requires_docker
def test_elasticache_engines(ec):
resp = ec.describe_cache_engine_versions(Engine="redis")
assert len(resp["CacheEngineVersions"]) > 0
+@requires_docker
def test_elasticache_modify_subnet_group(ec):
ec.create_cache_subnet_group(
CacheSubnetGroupName="test-mod-ecsg",
@@ -70,6 +83,7 @@ def test_elasticache_modify_subnet_group(ec):
resp = ec.describe_cache_subnet_groups(CacheSubnetGroupName="test-mod-ecsg")
assert resp["CacheSubnetGroups"][0]["CacheSubnetGroupDescription"] == "Updated EC SG"
+@requires_docker
def test_elasticache_user_crud(ec):
ec.create_user(
UserId="test-user-1",
@@ -84,6 +98,7 @@ def test_elasticache_user_crud(ec):
ec.modify_user(UserId="test-user-1", AccessString="on ~keys:* +get")
ec.delete_user(UserId="test-user-1")
+@requires_docker
def test_elasticache_user_group_crud(ec):
ec.create_user(
UserId="ug-usr-1",
@@ -99,6 +114,7 @@ def test_elasticache_user_group_crud(ec):
ec.delete_user_group(UserGroupId="test-ug-1")
ec.delete_user(UserId="ug-usr-1")
+@requires_docker
def test_elasticache_reset_clears_param_groups():
"""ElastiCache reset clears _param_group_params and resets port counter."""
from ministack.services import elasticache as _ec
@@ -108,6 +124,7 @@ def test_elasticache_reset_clears_param_groups():
assert not _ec._param_group_params
assert _ec._port_counter[0] == _ec.BASE_PORT
+@requires_docker
def test_elasticache_parameter_group_crud(ec):
"""CreateCacheParameterGroup / DescribeCacheParameterGroups / DeleteCacheParameterGroup."""
ec.create_cache_parameter_group(
@@ -122,6 +139,7 @@ def test_elasticache_parameter_group_crud(ec):
assert groups[0]["CacheParameterGroupFamily"] == "redis7"
ec.delete_cache_parameter_group(CacheParameterGroupName="test-pg-v39")
+@requires_docker
def test_elasticache_snapshot_crud(ec):
"""CreateSnapshot / DescribeSnapshots / DeleteSnapshot."""
ec.create_cache_cluster(
@@ -136,6 +154,7 @@ def test_elasticache_snapshot_crud(ec):
assert desc["Snapshots"][0]["SnapshotName"] == "test-snap-v39"
ec.delete_snapshot(SnapshotName="test-snap-v39")
+@requires_docker
def test_elasticache_tags(ec):
"""AddTagsToResource / ListTagsForResource / RemoveTagsFromResource."""
ec.create_cache_cluster(
@@ -160,6 +179,7 @@ def test_elasticache_tags(ec):
assert "team" not in tag_keys
# Migrated from test_ec.py
+@requires_docker
def test_elasticache_create_cluster_v2(ec):
resp = ec.create_cache_cluster(
CacheClusterId="ec-cc-v2",
@@ -173,6 +193,7 @@ def test_elasticache_create_cluster_v2(ec):
assert c["CacheClusterStatus"] == "available"
assert len(c["CacheNodes"]) == 1
+@requires_docker
def test_elasticache_describe_clusters_v2(ec):
ec.create_cache_cluster(
CacheClusterId="ec-dc-v2a",
@@ -194,6 +215,7 @@ def test_elasticache_describe_clusters_v2(ec):
resp2 = ec.describe_cache_clusters(CacheClusterId="ec-dc-v2b")
assert resp2["CacheClusters"][0]["Engine"] == "memcached"
+@requires_docker
def test_elasticache_replication_group_v2(ec):
resp = ec.create_replication_group(
ReplicationGroupId="ec-rg-v2",
@@ -211,6 +233,7 @@ def test_elasticache_replication_group_v2(ec):
desc = ec.describe_replication_groups(ReplicationGroupId="ec-rg-v2")
assert desc["ReplicationGroups"][0]["ReplicationGroupId"] == "ec-rg-v2"
+@requires_docker
def test_elasticache_engine_versions_v2(ec):
redis = ec.describe_cache_engine_versions(Engine="redis")
assert len(redis["CacheEngineVersions"]) > 0
@@ -219,6 +242,7 @@ def test_elasticache_engine_versions_v2(ec):
mc = ec.describe_cache_engine_versions(Engine="memcached")
assert len(mc["CacheEngineVersions"]) > 0
+@requires_docker
def test_elasticache_tags_v2(ec):
ec.create_cache_cluster(
CacheClusterId="ec-tag-v2",
@@ -245,6 +269,7 @@ def test_elasticache_tags_v2(ec):
assert not any(t["Key"] == "env" for t in tags2)
assert any(t["Key"] == "tier" for t in tags2)
+@requires_docker
def test_elasticache_snapshot_v2(ec):
ec.create_cache_cluster(
CacheClusterId="ec-snap-v2",
@@ -260,6 +285,7 @@ def test_elasticache_snapshot_v2(ec):
assert len(desc["Snapshots"]) == 1
assert desc["Snapshots"][0]["SnapshotName"] == "ec-snap-v2-s1"
+@requires_docker
def test_elasticache_describe_cache_parameters(ec):
"""DescribeCacheParameters returns parameters for a parameter group."""
ec.create_cache_parameter_group(
@@ -271,6 +297,7 @@ def test_elasticache_describe_cache_parameters(ec):
assert "Parameters" in resp
assert len(resp["Parameters"]) > 0
+@requires_docker
def test_elasticache_modify_cache_parameter_group(ec):
"""ModifyCacheParameterGroup updates parameter values."""
ec.create_cache_parameter_group(
@@ -296,6 +323,7 @@ def _uid():
# 1. ModifyCacheCluster
# ---------------------------------------------------------------------------
+@requires_docker
def test_modify_cache_cluster_num_nodes(ec):
"""ModifyCacheCluster: scale NumCacheNodes up and down."""
cid = f"mod-cc-{_uid()}"
@@ -320,6 +348,7 @@ def test_modify_cache_cluster_num_nodes(ec):
ec.delete_cache_cluster(CacheClusterId=cid)
+@requires_docker
def test_modify_cache_cluster_node_type_and_engine(ec):
"""ModifyCacheCluster: update CacheNodeType and EngineVersion."""
cid = f"mod-nt-{_uid()}"
@@ -345,6 +374,7 @@ def test_modify_cache_cluster_node_type_and_engine(ec):
# 2. RebootCacheCluster
# ---------------------------------------------------------------------------
+@requires_docker
def test_reboot_cache_cluster(ec):
"""RebootCacheCluster: reboot and verify cluster stays available."""
cid = f"reboot-{_uid()}"
@@ -369,6 +399,7 @@ def test_reboot_cache_cluster(ec):
# 3. DeleteReplicationGroup
# ---------------------------------------------------------------------------
+@requires_docker
def test_delete_replication_group(ec):
"""DeleteReplicationGroup: create then delete, verify gone."""
rg_id = f"del-rg-{_uid()}"
@@ -394,6 +425,7 @@ def test_delete_replication_group(ec):
# 4. ModifyReplicationGroup
# ---------------------------------------------------------------------------
+@requires_docker
def test_modify_replication_group(ec):
"""ModifyReplicationGroup: update description and CacheNodeType."""
rg_id = f"mod-rg-{_uid()}"
@@ -418,6 +450,7 @@ def test_modify_replication_group(ec):
# 5. IncreaseReplicaCount
# ---------------------------------------------------------------------------
+@requires_docker
def test_increase_replica_count(ec):
"""IncreaseReplicaCount: scale replicas up from 1 to 3."""
rg_id = f"inc-rep-{_uid()}"
@@ -449,6 +482,7 @@ def test_increase_replica_count(ec):
# 6. DecreaseReplicaCount
# ---------------------------------------------------------------------------
+@requires_docker
def test_decrease_replica_count(ec):
"""DecreaseReplicaCount: scale replicas down from 3 to 1."""
rg_id = f"dec-rep-{_uid()}"
@@ -479,6 +513,7 @@ def test_decrease_replica_count(ec):
# 7. DeleteCacheSubnetGroup
# ---------------------------------------------------------------------------
+@requires_docker
def test_delete_cache_subnet_group(ec):
"""DeleteCacheSubnetGroup: create then delete, verify gone."""
name = f"del-sg-{_uid()}"
@@ -504,6 +539,7 @@ def test_delete_cache_subnet_group(ec):
# 8. ResetCacheParameterGroup
# ---------------------------------------------------------------------------
+@requires_docker
def test_reset_cache_parameter_group_full(ec):
"""ResetCacheParameterGroup: full reset restores defaults."""
pg = f"reset-full-{_uid()}"
@@ -533,6 +569,7 @@ def test_reset_cache_parameter_group_full(ec):
ec.delete_cache_parameter_group(CacheParameterGroupName=pg)
+@requires_docker
def test_reset_cache_parameter_group_selective(ec):
"""ResetCacheParameterGroup: selective reset of specific parameter."""
pg = f"reset-sel-{_uid()}"
@@ -570,6 +607,7 @@ def test_reset_cache_parameter_group_selective(ec):
# 9. DeleteSnapshot (explicit)
# ---------------------------------------------------------------------------
+@requires_docker
def test_delete_snapshot_explicit(ec):
"""DeleteSnapshot: create snapshot, delete it, verify gone."""
cid = f"snap-del-{_uid()}"
@@ -601,6 +639,7 @@ def test_delete_snapshot_explicit(ec):
# 10. DescribeEvents
# ---------------------------------------------------------------------------
+@requires_docker
def test_describe_events_all(ec):
"""DescribeEvents: listing all events returns results."""
# create a cluster to generate at least one event
@@ -618,6 +657,7 @@ def test_describe_events_all(ec):
ec.delete_cache_cluster(CacheClusterId=cid)
+@requires_docker
def test_describe_events_filter_source_type(ec):
"""DescribeEvents: filter by SourceType."""
rg_id = f"evt-rg-{_uid()}"
@@ -635,6 +675,7 @@ def test_describe_events_filter_source_type(ec):
ec.delete_replication_group(ReplicationGroupId=rg_id)
+@requires_docker
def test_describe_events_filter_source_id(ec):
"""DescribeEvents: filter by SourceIdentifier."""
cid = f"evt-src-{_uid()}"
@@ -656,6 +697,7 @@ def test_describe_events_filter_source_id(ec):
# 11. Serverless cache operations — not implemented in MiniStack
# ---------------------------------------------------------------------------
+@requires_docker
def test_serverless_cache_not_implemented(ec):
"""Serverless cache operations are not yet implemented; verify graceful error."""
with pytest.raises(ClientError):
@@ -676,10 +718,6 @@ import zipfile
import pytest
-pytestmark = pytest.mark.skipif(
- not os.environ.get("DOCKER_NETWORK"),
- reason="DOCKER_NETWORK not set — skipping network connectivity test",
-)
_LAMBDA_ROLE = "arn:aws:iam::000000000000:role/lambda-role"
@@ -698,6 +736,7 @@ def _make_zip_js(code: str) -> bytes:
return buf.getvalue()
+@requires_docker
def test_elasticache_lambda_network_connectivity(ec, lam):
"""Prove that Lambda containers can TCP-connect to an ElastiCache container."""
cluster_id = "net-test-redis"
@@ -806,3 +845,104 @@ exports.handler = async (event) => {{
ec.delete_cache_cluster(CacheClusterId=cluster_id)
except Exception:
pass
+
+
+
+
+# ── Container respawn on restore (#853) — unit-style, no Docker ──────
+
+
+def test_elasticache_restore_state_marks_clusters_for_respawn(monkeypatch):
+ """Issue #853: restoring persisted cluster state must re-spawn the
+ Redis Docker container — the persisted container id is dead after
+ restart. Verifies the lazy-respawn path is triggered."""
+ from ministack.services import elasticache as _ec
+ _ec.reset()
+
+ spawned = []
+
+ def fake_spawn(name, engine, engine_version, labels):
+ spawned.append({"name": name, "engine": engine,
+ "engine_version": engine_version, "labels": labels})
+ return ("ministack-elasticache", 6379, f"cid-{name}")
+
+ monkeypatch.setattr(_ec, "_spawn_redis_container", fake_spawn)
+
+ _ec.restore_state({
+ "clusters": {
+ "clustertest": {
+ "CacheClusterId": "clustertest",
+ "Engine": "redis", "EngineVersion": "7.1",
+ "CacheNodes": [{"CacheNodeId": "0001",
+ "Endpoint": {"Address": "stale", "Port": 1}}],
+ "_docker_container_id": "old-dead-cid",
+ "CacheClusterStatus": "available",
+ },
+ },
+ })
+
+ assert spawned == [] # respawn deferred — _spawn_redis_container not yet bound at import time
+ assert "clustertest" in _ec._pending_cluster_respawn
+
+ _ec._ensure_live_containers()
+
+ assert any(s["name"] == "ministack-elasticache-clustertest" for s in spawned)
+ cl = _ec._clusters["clustertest"]
+ assert cl["_docker_container_id"] == "cid-ministack-elasticache-clustertest"
+ assert cl["CacheNodes"][0]["Endpoint"]["Address"] == "ministack-elasticache"
+ assert cl["CacheNodes"][0]["Endpoint"]["Port"] == 6379
+ assert "clustertest" not in _ec._pending_cluster_respawn
+
+ spawned.clear()
+ _ec._ensure_live_containers()
+ assert spawned == [] # idempotent — no second respawn
+
+
+def test_elasticache_restore_state_wipes_stale_replication_group_container_ids(monkeypatch):
+ from ministack.services import elasticache as _ec
+ _ec.reset()
+ monkeypatch.setattr(_ec, "_spawn_redis_container",
+ lambda name, engine, engine_version, labels: ("rg-host", 6379, f"cid-{name}"))
+
+ _ec.restore_state({
+ "replication_groups": {
+ "rg-1": {
+ "ReplicationGroupId": "rg-1",
+ "Engine": "redis", "EngineVersion": "7.1",
+ "NodeGroups": [{"NodeGroupId": "0001"}],
+ "_docker_container_ids": ["dead-cid-1", "dead-cid-2"],
+ },
+ },
+ })
+ assert _ec._replication_groups["rg-1"]["_docker_container_ids"] == []
+ assert "rg-1" in _ec._pending_rg_respawn
+
+ _ec._ensure_live_containers()
+ cids = _ec._replication_groups["rg-1"]["_docker_container_ids"]
+ assert cids == ["cid-ministack-elasticache-rg-000000000000-rg-1-0001"]
+ assert "rg-1" not in _ec._pending_rg_respawn
+
+
+def test_elasticache_respawn_failure_is_logged_and_does_not_block_requests(monkeypatch, caplog):
+ import logging
+ from ministack.services import elasticache as _ec
+ _ec.reset()
+
+ def boom(*a, **kw):
+ raise RuntimeError("docker daemon unreachable")
+
+ monkeypatch.setattr(_ec, "_spawn_redis_container", boom)
+
+ _ec.restore_state({
+ "clusters": {
+ "c1": {
+ "CacheClusterId": "c1", "Engine": "redis", "EngineVersion": "7.1",
+ "CacheNodes": [], "_docker_container_id": "old",
+ "CacheClusterStatus": "available",
+ },
+ },
+ })
+ with caplog.at_level(logging.WARNING):
+ _ec._ensure_live_containers()
+ assert "c1" not in _ec._pending_cluster_respawn # cleared even on failure (no retry storm)
+ assert any("failed to respawn" in r.message for r in caplog.records)
diff --git a/tests/test_eventbridge.py b/tests/test_eventbridge.py
index 16b1d126..ff7e816c 100644
--- a/tests/test_eventbridge.py
+++ b/tests/test_eventbridge.py
@@ -1680,3 +1680,68 @@ def test_eventbridge_dispatch_to_fifo_sqs_stamps_message_group_id(eb, sqs):
assert msgs, "FIFO queue received no messages from EventBridge"
attrs = msgs[0].get("Attributes", {})
assert attrs.get("MessageGroupId") == "orders"
+
+
+# ── anything-but with nested content filters (#849) ──────────────────
+
+
+def _eb_setup_anybut_rule(eb, sqs, suffix, pattern_value):
+ """Helper: create bus + queue + rule with a given anything-but pattern."""
+ bus = f"qa-eb-anybut-{suffix}-bus"
+ eb.create_event_bus(Name=bus)
+ q_url = sqs.create_queue(QueueName=f"qa-eb-anybut-{suffix}-q")["QueueUrl"]
+ q_arn = sqs.get_queue_attributes(
+ QueueUrl=q_url, AttributeNames=["QueueArn"])["Attributes"]["QueueArn"]
+ eb.put_rule(
+ Name=f"qa-eb-anybut-{suffix}-rule",
+ EventBusName=bus,
+ EventPattern=json.dumps({
+ "source": ["myapp"],
+ "detail": {"id": [{"anything-but": pattern_value}]},
+ }),
+ State="ENABLED",
+ )
+ eb.put_targets(
+ Rule=f"qa-eb-anybut-{suffix}-rule",
+ EventBusName=bus,
+ Targets=[{"Id": "t1", "Arn": q_arn}],
+ )
+ return bus, q_url
+
+
+def _eb_send(eb, bus, id_value):
+ eb.put_events(Entries=[{
+ "Source": "myapp", "DetailType": "t",
+ "Detail": json.dumps({"id": id_value}),
+ "EventBusName": bus,
+ }])
+
+
+def test_eventbridge_anything_but_prefix_excludes_matching(eb, sqs):
+ bus, q_url = _eb_setup_anybut_rule(eb, sqs, "prefix", {"prefix": "TEST-"})
+ _eb_send(eb, bus, "PROD-42") # does not start with TEST- → should deliver
+ _eb_send(eb, bus, "TEST-99") # excluded by prefix → should NOT deliver
+ msgs = sqs.receive_message(
+ QueueUrl=q_url, MaxNumberOfMessages=10, WaitTimeSeconds=1)["Messages"]
+ ids = [json.loads(m["Body"])["detail"]["id"] for m in msgs]
+ assert ids == ["PROD-42"]
+
+
+def test_eventbridge_anything_but_suffix_excludes_matching(eb, sqs):
+ bus, q_url = _eb_setup_anybut_rule(eb, sqs, "suffix", {"suffix": "-OLD"})
+ _eb_send(eb, bus, "ITEM-NEW") # no -OLD suffix → deliver
+ _eb_send(eb, bus, "ITEM-OLD") # excluded by suffix → skip
+ msgs = sqs.receive_message(
+ QueueUrl=q_url, MaxNumberOfMessages=10, WaitTimeSeconds=1)["Messages"]
+ ids = [json.loads(m["Body"])["detail"]["id"] for m in msgs]
+ assert ids == ["ITEM-NEW"]
+
+
+def test_eventbridge_anything_but_wildcard_excludes_matching(eb, sqs):
+ bus, q_url = _eb_setup_anybut_rule(eb, sqs, "wildcard", {"wildcard": "*-test-*"})
+ _eb_send(eb, bus, "prod-app-1") # no -test- → deliver
+ _eb_send(eb, bus, "abc-test-xyz") # matches wildcard → skip
+ msgs = sqs.receive_message(
+ QueueUrl=q_url, MaxNumberOfMessages=10, WaitTimeSeconds=1)["Messages"]
+ ids = [json.loads(m["Body"])["detail"]["id"] for m in msgs]
+ assert ids == ["prod-app-1"]
diff --git a/tests/test_sqs.py b/tests/test_sqs.py
index f2e0d613..bcfedd0a 100644
--- a/tests/test_sqs.py
+++ b/tests/test_sqs.py
@@ -993,3 +993,94 @@ def test_sqs_messages_endpoint_invalid_account_rejected(sqs):
assert e.code == 400
body = json.loads(e.read())
assert body["__type"] == "InvalidAccountID"
+
+
+# ── Numeric attribute range validation (#841) ────────────────────────
+
+
+def test_sqs_create_queue_rejects_visibility_timeout_too_high(sqs):
+ import botocore.exceptions
+ try:
+ sqs.create_queue(QueueName="q-vt-high", Attributes={"VisibilityTimeout": "99999"})
+ except botocore.exceptions.ClientError as exc:
+ assert exc.response["Error"]["Code"] == "InvalidAttributeValue"
+ else:
+ sqs.delete_queue(QueueUrl=sqs.get_queue_url(QueueName="q-vt-high")["QueueUrl"])
+ raise AssertionError("expected InvalidAttributeValue for VisibilityTimeout=99999")
+
+
+def test_sqs_create_queue_rejects_visibility_timeout_negative(sqs):
+ import botocore.exceptions
+ try:
+ sqs.create_queue(QueueName="q-vt-neg", Attributes={"VisibilityTimeout": "-1"})
+ except botocore.exceptions.ClientError as exc:
+ assert exc.response["Error"]["Code"] == "InvalidAttributeValue"
+ else:
+ raise AssertionError("expected InvalidAttributeValue for VisibilityTimeout=-1")
+
+
+def test_sqs_create_queue_rejects_delay_seconds_out_of_range(sqs):
+ import botocore.exceptions
+ try:
+ sqs.create_queue(QueueName="q-ds-bad", Attributes={"DelaySeconds": "901"})
+ except botocore.exceptions.ClientError as exc:
+ assert exc.response["Error"]["Code"] == "InvalidAttributeValue"
+ else:
+ raise AssertionError("expected InvalidAttributeValue for DelaySeconds=901")
+
+
+def test_sqs_create_queue_rejects_maximum_message_size_below_min(sqs):
+ import botocore.exceptions
+ try:
+ sqs.create_queue(QueueName="q-mms-low", Attributes={"MaximumMessageSize": "512"})
+ except botocore.exceptions.ClientError as exc:
+ assert exc.response["Error"]["Code"] == "InvalidAttributeValue"
+ else:
+ raise AssertionError("expected InvalidAttributeValue for MaximumMessageSize=512")
+
+
+def test_sqs_create_queue_rejects_receive_wait_too_long(sqs):
+ import botocore.exceptions
+ try:
+ sqs.create_queue(QueueName="q-rwt-bad",
+ Attributes={"ReceiveMessageWaitTimeSeconds": "21"})
+ except botocore.exceptions.ClientError as exc:
+ assert exc.response["Error"]["Code"] == "InvalidAttributeValue"
+ else:
+ raise AssertionError("expected InvalidAttributeValue for ReceiveMessageWaitTimeSeconds=21")
+
+
+def test_sqs_set_queue_attributes_rejects_visibility_timeout_too_high(sqs):
+ import botocore.exceptions
+ url = sqs.create_queue(QueueName="q-set-vt-bad")["QueueUrl"]
+ try:
+ try:
+ sqs.set_queue_attributes(QueueUrl=url, Attributes={"VisibilityTimeout": "100000"})
+ except botocore.exceptions.ClientError as exc:
+ assert exc.response["Error"]["Code"] == "InvalidAttributeValue"
+ else:
+ raise AssertionError("expected InvalidAttributeValue on SetQueueAttributes")
+ finally:
+ sqs.delete_queue(QueueUrl=url)
+
+
+def test_sqs_set_queue_attributes_accepts_valid_visibility_timeout(sqs):
+ # Regression guard — must NOT reject in-range values.
+ url = sqs.create_queue(QueueName="q-set-vt-ok")["QueueUrl"]
+ try:
+ sqs.set_queue_attributes(QueueUrl=url, Attributes={"VisibilityTimeout": "120"})
+ attrs = sqs.get_queue_attributes(
+ QueueUrl=url, AttributeNames=["VisibilityTimeout"])["Attributes"]
+ assert attrs["VisibilityTimeout"] == "120"
+ finally:
+ sqs.delete_queue(QueueUrl=url)
+
+
+def test_sqs_create_queue_rejects_non_numeric_visibility_timeout(sqs):
+ import botocore.exceptions
+ try:
+ sqs.create_queue(QueueName="q-vt-nan", Attributes={"VisibilityTimeout": "abc"})
+ except botocore.exceptions.ClientError as exc:
+ assert exc.response["Error"]["Code"] == "InvalidAttributeValue"
+ else:
+ raise AssertionError("expected InvalidAttributeValue for non-numeric")