Skip to content

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

feat(iot): create job executions at the rollout rate (#2185)

iot-rocket8a2833195d8a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1ab11cda..4246ef17 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -27,9 +27,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
### Added
-- **IoT — job abort criteria** — a job's `abortConfig` was stored but never acted on; once a device report, a `CancelJobExecution`, a `DeleteJobExecution` or a timeout meets one of its criteria, the job is now canceled with reasonCode `ABORT_CANCEL` and AWS's comment, together with its `QUEUED` executions. `CreateJob` and `CreateJobTemplate` stored any `abortConfig`; they now refuse what `UpdateJob` refuses, and all three refuse a missing criterion member, a threshold of 0 or less or with more than two decimals, and a failure type given twice. A `CancelJob` without `force` now reports `forceCanceled` as false. Contributed by @iot-rocket.
-- **CloudFormation — SES configuration set updates** — `AWS::SES::ConfigurationSet` and `AWS::SES::ConfigurationSetEventDestination` stored none of their options, tags or destinations, and a change re-ran the create; both now provision through the SES v2 calls and update in place, a removed option goes back to its default as on AWS, and only a `Name` or `ConfigurationSetName` change replaces them. Contributed by @iot-rocket.
-- **SES v2 — configuration set options and event destinations** — `GetConfigurationSet` returned only the name and the tags given at creation; it now returns the tracking, delivery, reputation, sending, suppression, VDM and archiving options that `CreateConfigurationSet` and the seven `PutConfigurationSet*Options` calls set, and a call clears the members it leaves out, as on AWS. `CreateConfigurationSetEventDestination`, `GetConfigurationSetEventDestinations`, `UpdateConfigurationSetEventDestination` and `DeleteConfigurationSetEventDestination` are new. `CreateConfigurationSet` with a name already in use is refused with `AlreadyExistsException` instead of replacing the set. Contributed by @iot-rocket.
+- **IoT — job rollout rates** — `jobExecutionsRolloutConfig` was stored but every execution was created at once; a job now creates `maximumPerMinute` executions a minute, or a rate that starts at `baseRatePerMinute` and grows by `incrementFactor` for every `rateIncreaseCriteria` step of notified or succeeded things, notifies each thing when its execution is created, reports `isConcurrent` until the last batch and stops when the job is canceled or deleted. Contributed by @iot-rocket.
- **IoT — MQTT publish, subscribe and receive evaluate IoT policies under `AUTH=true`** — after the CONNECT a certificate session could publish, subscribe and receive on any topic; it now needs `iot:Publish` on the topic (and `iot:RetainPublish` for a retained message or will), `iot:Subscribe` per topic filter and `iot:Receive` per delivered message. A refused PUBLISH or SUBSCRIBE closes an MQTT 3.1.1 connection (disconnect reason `CLIENT_ERROR`), MQTT 5 answers PUBACK 0x87, DISCONNECT 0x87 at QoS 0 (`AUTH_ERROR`) or 0x87 for the refused filter, which the `subscribed` event leaves out (no event when none is granted), a refused will refuses the CONNECT, and a message the subscriber may not receive is dropped. Contributed by @iot-rocket.
- **IoT — MQTT connections evaluate `iot:Connect` under `AUTH=true`** — a device certificate on the mTLS listener connected under any client id, with or without a policy; with `AUTH=true` the CONNECT now needs an attached policy that allows `iot:Connect` on `client/<client id>` and none that denies it, with `${iot:ClientId}`, `${iot:Connection.Thing.ThingName}`, `iot:Connection.Thing.IsAttached` and `${iot:Certificate.Subject.CommonName}` resolved. A refusal closes an MQTT 3.1.1 connection without a CONNACK, answers MQTT 5 with CONNACK 0x87 and publishes `$aws/events/presence/connect_failed/{clientId}`. Contributed by @iot-rocket.
### Fixed
diff --git a/ministack/services/iot.py b/ministack/services/iot.py
index 54c65f44..7ec917d1 100644
--- a/ministack/services/iot.py
+++ b/ministack/services/iot.py
@@ -346,6 +346,9 @@ def _restore_state(data: dict | None) -> None:
if legacy and not _tags.contains_scoped(account, region, record[arn_key]):
_tags.set_scoped(account, region, record[arn_key],
{t["Key"]: t.get("Value", "") for t in legacy})
+ for (account_id, region, _), job in _jobs.all_items():
+ if job.get("rolloutQueue"):
+ _jobs_rollout_start(account_id, region, job)
ca_data = data.get("ca")
if ca_data:
cert = ca_data.get("ca_cert_pem")
@@ -5995,7 +5998,8 @@ def _jobs_materialize_executions(job_id: str) -> None:
SNAPSHOT jobs resolve group membership exactly once (at creation) — the
`snapshotted` flag latches that. CONTINUOUS jobs re-resolve lazily on
every read, which is exactly when new membership matters and avoids
- watching group mutations.
+ watching group mutations. Things in the job's `rolloutQueue` wait for
+ their rollout batch.
"""
job = _jobs.get(job_id)
if not job or job.get("status") == "CANCELED":
@@ -6004,9 +6008,10 @@ def _jobs_materialize_executions(job_id: str) -> None:
return
now = _jobs_now_ms()
deleted = job.get("executionsDeletedFor") or ()
+ waiting = set(job.get("rolloutQueue") or ())
for thing in _job_target_things(job.get("targets")):
key = (thing, job_id)
- if key in _job_executions or thing in deleted:
+ if key in _job_executions or thing in deleted or thing in waiting:
continue
_jobs_queue_execution(thing, job_id, now)
if job.get("targetSelection") == "SNAPSHOT":
@@ -6043,6 +6048,97 @@ def _jobs_queue_execution(thing: str, job_id: str, now: int) -> None:
deleted.remove(thing)
+# A job with jobExecutionsRolloutConfig creates its executions in batches, one
+# batch per this interval; the things still waiting are in its `rolloutQueue`.
+_JOB_ROLLOUT_INTERVAL_MS = 60_000
+# The running rollout tasks, kept here because the event loop holds only weak references.
+_rollout_tasks: set[asyncio.Task] = set()
+
+
+def _jobs_rollout_batch_size(job: dict, waiting: int) -> int:
+ """How many of `waiting` things a job notifies in its next batch."""
+ config = job.get("jobExecutionsRolloutConfig")
+ config = config if isinstance(config, dict) else {}
+ maximum = config.get("maximumPerMinute")
+ size = maximum if isinstance(maximum, int) and maximum > 0 else waiting
+ rate = config.get("exponentialRate")
+ rate = rate if isinstance(rate, dict) else {}
+ criteria = rate.get("rateIncreaseCriteria")
+ criteria = criteria if isinstance(criteria, dict) else {}
+ if criteria.get("numberOfSucceededThings") is not None:
+ step = criteria["numberOfSucceededThings"]
+ done = _jobs_status_counts(job["jobId"])["SUCCEEDED"]
+ else:
+ step = criteria.get("numberOfNotifiedThings")
+ done = sum(1 for e in _job_executions.values() if e["jobId"] == job["jobId"])
+ base, factor = rate.get("baseRatePerMinute"), rate.get("incrementFactor")
+ if not (
+ isinstance(base, int) and base > 0 and isinstance(step, int) and step > 0
+ and isinstance(factor, (int, float)) and factor > 1
+ ):
+ return size
+ # The rate grows by incrementFactor for every full step of notified (or
+ # succeeded) things, and maximumPerMinute caps it.
+ per_minute = base
+ for _ in range(done // step):
+ if per_minute >= size:
+ break
+ per_minute *= factor
+ return min(size, int(per_minute))
+
+
+def _jobs_rollout_release(job: dict) -> list[tuple[str, str | None]]:
+ """Queue the next batch of a job's waiting things; returns (thing, previous queue front) pairs."""
+ job_id, waiting = job["jobId"], job["rolloutQueue"]
+ batch = waiting[:_jobs_rollout_batch_size(job, len(waiting))]
+ job["rolloutQueue"] = waiting[len(batch):]
+ now = _jobs_now_ms()
+ job["rolloutBatchAt"] = now
+ # A thing deleted meanwhile is skipped, and so is one a CONTINUOUS job no longer targets.
+ targeted = (
+ set(_job_target_things(job.get("targets")))
+ if job.get("targetSelection") == "CONTINUOUS" else _things
+ )
+ released = []
+ for thing in batch:
+ if thing in targeted and (thing, job_id) not in _job_executions:
+ released.append((thing, jobs_first_pending_job_id(thing)))
+ _jobs_queue_execution(thing, job_id, now)
+ _jobs_maybe_complete(job_id)
+ return released
+
+
+async def _jobs_rollout(account_id: str, region: str, job: dict) -> None:
+ """Release a job's waiting things batch by batch until none is left or the job stops."""
+ while True:
+ with request_scope(account_id, region):
+ if (
+ _jobs.get(job["jobId"]) is not job
+ or job["status"] != "IN_PROGRESS"
+ or not job.get("rolloutQueue")
+ ):
+ return
+ wait = job["rolloutBatchAt"] + _JOB_ROLLOUT_INTERVAL_MS - _jobs_now_ms()
+ if wait > 0:
+ await asyncio.sleep(wait / 1000)
+ continue
+ async with publishing_events():
+ with request_scope(account_id, region):
+ released = _jobs_rollout_release(job)
+ for thing, prev_next in released:
+ await jobs_notify_thing(account_id, region, thing, prev_next)
+
+
+def _jobs_rollout_start(account_id: str, region: str, job: dict) -> None:
+ """Run a job's rollout on the running event loop, if there is one."""
+ try:
+ task = asyncio.get_running_loop().create_task(_jobs_rollout(account_id, region, job))
+ except RuntimeError:
+ return
+ _rollout_tasks.add(task)
+ task.add_done_callback(_rollout_tasks.discard)
+
+
def _jobs_thing_joined_group(thing: str, group_arn: str) -> bool:
"""Run every CONTINUOUS job targeting a group for a thing that just
joined it.
@@ -6268,6 +6364,7 @@ def _jobs_maybe_complete(job_id: str) -> None:
not job
or job.get("targetSelection") == "CONTINUOUS"
or job.get("status") != "IN_PROGRESS"
+ or job.get("rolloutQueue")
):
return
executions = [e for e in _job_executions.values() if e["jobId"] == job_id]
@@ -6630,6 +6727,12 @@ async def _create_job(job_id: str, payload: dict) -> tuple:
"snapshotted": False,
}
_set_created_tags(_job_arn(job_id), payload.get("tags"))
+ things = _job_target_things(targets)
+ batch = _jobs_rollout_batch_size(_jobs[job_id], len(things))
+ if batch < len(things):
+ # The other things wait for later batches of the rollout.
+ _jobs[job_id].update(rolloutQueue=things[batch:], rolloutBatchAt=now)
+ _jobs_rollout_start(get_account_id(), get_region(), _jobs[job_id])
_jobs_materialize_executions(job_id)
# New QUEUED executions joined each target's pending set — notify, as AWS
# does (notify-next only reaches the things whose queue front changed).
@@ -6954,10 +7057,10 @@ def _describe_job(job_id: str) -> tuple:
job_doc["schedulingConfig"] = job.get("schedulingConfig") or {}
# isConcurrent is false in every steady state (captured eu-north-1
# 2026-09-19 with a QUEUED, an IN_PROGRESS and a SUCCEEDED execution). It is
- # true only inside the rollout/cancel window the reference describes, which
- # this emulator does not model. processingTargets is null throughout the same
+ # true while a rollout still has things to notify; the cancel window the
+ # reference also describes is not modeled. processingTargets is null throughout the same
# capture, so it stays omitted rather than echoing the target ARNs.
- job_doc["isConcurrent"] = False
+ job_doc["isConcurrent"] = job["status"] == "IN_PROGRESS" and bool(job.get("rolloutQueue"))
response = {"job": job_doc}
if job.get("documentSource") is not None:
response["documentSource"] = job["documentSource"]
diff --git a/tests/test_iot_jobs_data.py b/tests/test_iot_jobs_data.py
index 2527662a..b986504b 100644
--- a/tests/test_iot_jobs_data.py
+++ b/tests/test_iot_jobs_data.py
@@ -626,6 +626,201 @@ def test_iot_jobs_create_duplicate_and_unknown_target_rejected(iot_client):
_cleanup(iot_client, jobs=[job_id], things=[thing])
+def test_iot_jobs_rollout_rate_creates_the_first_batch_only(iot_client, iot_jobs_data):
+ """CreateJob creates the first batch only; the job stays IN_PROGRESS and isConcurrent after it finishes."""
+ things = [_unique("jobs-roll") for _ in range(3)]
+ jobs = {}
+ exponential = {"baseRatePerMinute": 1, "incrementFactor": 2,
+ "rateIncreaseCriteria": {"numberOfNotifiedThings": 1}}
+ try:
+ arns = [_create_thing(iot_client, thing) for thing in things]
+ for name, config in (
+ ("one", {"maximumPerMinute": 1}),
+ ("two", {"maximumPerMinute": 2}),
+ ("exponential", {"maximumPerMinute": 1000, "exponentialRate": exponential}),
+ ("all", {"maximumPerMinute": 3}),
+ ):
+ jobs[name] = _unique("job")
+ iot_client.create_job(jobId=jobs[name], targets=arns, document=_DOCUMENT,
+ jobExecutionsRolloutConfig=config)
+
+ def created(job_id):
+ found = []
+ for thing in things:
+ try:
+ iot_client.describe_job_execution(jobId=job_id, thingName=thing)
+ found.append(thing)
+ except ClientError as e:
+ assert e.response["Error"]["Code"] == "ResourceNotFoundException"
+ return found
+
+ assert created(jobs["one"]) == things[:1]
+ assert created(jobs["two"]) == things[:2]
+ assert created(jobs["exponential"]) == things[:1]
+ assert created(jobs["all"]) == things
+ pending = iot_jobs_data.get_pending_job_executions(thingName=things[2])
+ assert [e["jobId"] for e in pending["queuedJobs"]] == [jobs["all"]]
+
+ iot_jobs_data.update_job_execution(jobId=jobs["one"], thingName=things[0],
+ status="SUCCEEDED")
+ job = iot_client.describe_job(jobId=jobs["one"])["job"]
+ assert (job["status"], job["isConcurrent"]) == ("IN_PROGRESS", True)
+ assert job["jobProcessDetails"]["numberOfSucceededThings"] == 1
+ assert job["jobProcessDetails"]["numberOfQueuedThings"] == 0
+ assert iot_client.describe_job(jobId=jobs["all"])["job"]["isConcurrent"] is False
+ iot_client.cancel_job(jobId=jobs["two"])
+ assert iot_client.describe_job(jobId=jobs["two"])["job"]["isConcurrent"] is False
+ finally:
+ _cleanup(iot_client, jobs=list(jobs.values()), things=things)
+
+
+def _rollout_run(monkeypatch, body):
+ """Run `body(iot_module, created, published)` on a new event loop with batches 0.5 s apart."""
+ import asyncio
+
+ from ministack.services import iot as iot_module
+
+ published = []
+
+ async def publish(account_id, region, topic, payload, qos=0, retain=False, **_):
+ published.append((topic, json.loads(payload)))
+
+ monkeypatch.setattr(iot_module, "broker_publish", publish)
+ monkeypatch.setattr(iot_module, "_JOB_ROLLOUT_INTERVAL_MS", 500)
+
+ def created(job_id):
+ return sorted(t for t, j in iot_module._job_executions.keys() if j == job_id)
+
+ iot_module.reset()
+ try:
+ asyncio.run(body(iot_module, created, published))
+ finally:
+ iot_module.reset()
+
+
+async def _rollout_wait(predicate, timeout=5.0):
+ import asyncio
+
+ deadline = time.monotonic() + timeout
+ while not predicate():
+ assert time.monotonic() < deadline, "timed out"
+ await asyncio.sleep(0.02)
+
+
+async def _rollout_create(iot_module, job_id, things, **payload):
+ """Create the things that are missing and a job with a document."""
+ from ministack.core.responses import get_account_id, get_region
+
+ for thing in things:
+ iot_module._things.setdefault(thing, {"thingName": thing})
+ arns = [f"arn:aws:iot:{get_region()}:{get_account_id()}:thing/{t}" for t in things]
+ status, _, _ = await iot_module._create_job(
+ job_id, {"targets": arns, "document": "{}", **payload})
+ assert status == 200
+
+
+def test_iot_jobs_rollout_notifies_a_batch_per_interval(monkeypatch):
+ """Each batch is created and notified one interval after the last; CancelJob and DeleteJob stop the rest."""
+ from ministack.core.responses import request_scope
+
+ things = ["t1", "t2", "t3"]
+ rate = {"jobExecutionsRolloutConfig": {"maximumPerMinute": 1}}
+
+ async def body(iot_module, created, published):
+ with request_scope("111111111111", "eu-central-1"):
+ for job_id in ("roll", "cancel", "delete"):
+ await _rollout_create(iot_module, job_id, things, **rate)
+ await iot_module._cancel_job("cancel", {}, {})
+ await iot_module._delete_job("delete", {"force": "true"})
+ assert created("roll") == ["t1"]
+ assert not any(topic.startswith("$aws/things/t2/") for topic, _ in published)
+ await _rollout_wait(lambda: created("roll") == ["t1", "t2"])
+ await _rollout_wait(lambda: "$aws/things/t2/jobs/notify-next" in dict(published))
+ assert dict(published)["$aws/things/t2/jobs/notify-next"]["execution"]["jobId"] == "roll"
+ assert created("roll") == ["t1", "t2"]
+ assert iot_module._jobs["roll"]["rolloutQueue"] == ["t3"]
+ await _rollout_wait(lambda: created("roll") == things)
+ await _rollout_wait(lambda: not iot_module._rollout_tasks)
+ assert json.loads(iot_module._describe_job("roll")[2])["job"]["isConcurrent"] is False
+ assert created("cancel") == ["t1"]
+ assert created("delete") == []
+
+ _rollout_run(monkeypatch, body)
+
+
+def test_iot_jobs_rollout_exponential_rate_grows_by_step():
+ """The rate grows by incrementFactor per full step, rounds down per batch and stops at maximumPerMinute."""
+ from ministack.core.responses import request_scope
+ from ministack.services import iot as iot_module
+
+ def batches(count, maximum, rate=None, succeed_first=False):
+ iot_module.reset()
+ things = [f"t{i}" for i in range(count)]
+ config = {"maximumPerMinute": maximum}
+ if rate:
+ config["exponentialRate"] = {"baseRatePerMinute": 1, **rate}
+ with request_scope("111111111111", "eu-central-1"):
+ for thing in things:
+ iot_module._things[thing] = {"thingName": thing}
+ job = iot_module._jobs["j"] = {
+ "jobId": "j", "targets": [], "targetSelection": "SNAPSHOT",
+ "status": "IN_PROGRESS", "jobExecutionsRolloutConfig": config,
+ "rolloutQueue": things, "rolloutBatchAt": 0,
+ }
+ sizes = []
+ while job["rolloutQueue"]:
+ sizes.append(len(iot_module._jobs_rollout_release(job)))
+ if succeed_first:
+ iot_module._job_executions[("t0", "j")]["status"] = "SUCCEEDED"
+ return sizes
+
+ notified = {"rateIncreaseCriteria": {"numberOfNotifiedThings": 1}}
+ try:
+ assert batches(4, 2) == [2, 2]
+ assert batches(8, 1000, {"incrementFactor": 2, **notified}) == [1, 2, 5]
+ assert batches(7, 1000, {"incrementFactor": 1.5, **notified}) == [1, 1, 2, 3]
+ assert batches(7, 2, {"incrementFactor": 4, **notified}) == [1, 2, 2, 2]
+ succeeded = {"incrementFactor": 2,
+ "rateIncreaseCriteria": {"numberOfSucceededThings": 1}}
+ assert batches(7, 1000, succeeded, succeed_first=True) == [1, 2, 2, 2]
+ finally:
+ iot_module.reset()
+
+
+def test_iot_jobs_rollout_survives_persistence_in_each_scope_and_stops_on_reset(monkeypatch):
+ """A restored job resumes in its own account and region; reset ends every rollout."""
+ from ministack.core.responses import request_scope
+
+ scopes = [("111111111111", "eu-central-1"), ("222222222222", "us-east-1")]
+
+ async def body(iot_module, created, published):
+ for scope in scopes:
+ with request_scope(*scope):
+ await _rollout_create(iot_module, "roll", ["t1", "t2", "t3"],
+ jobExecutionsRolloutConfig={"maximumPerMinute": 2})
+ state = iot_module.get_state()
+ iot_module.reset()
+ iot_module.load_persisted_state(state)
+ for scope in scopes:
+ with request_scope(*scope):
+ assert created("roll") == ["t1", "t2"]
+ assert iot_module._jobs["roll"]["rolloutQueue"] == ["t3"]
+ for scope in scopes:
+ with request_scope(*scope):
+ await _rollout_wait(lambda: created("roll") == ["t1", "t2", "t3"])
+ await _rollout_wait(lambda: not iot_module._rollout_tasks)
+
+ with request_scope(*scopes[0]):
+ await _rollout_create(iot_module, "again", ["t1", "t2"],
+ jobExecutionsRolloutConfig={"maximumPerMinute": 1})
+ iot_module.reset()
+ await _rollout_wait(lambda: not iot_module._rollout_tasks)
+ assert "again" not in iot_module._jobs
+ assert created("again") == []
+
+ _rollout_run(monkeypatch, body)
+
+
# ---------------------------------------------------------------------------
# Job templates — shapes and messages measured on AWS (eu-central-1,
# 2026-10-05)