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
feat(iot): add DeleteJobExecution and ListJobExecutionsForJob (#2140)
iot-rocketc19c4059495f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 683cca21..251adb82 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,10 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]+### Added++- **IoT — `ListJobExecutionsForJob`** — `GET /jobs/{jobId}/things` answered 400 `Unsupported IoT path`; it now lists every execution of the job, earlier ones of a rejoined thing included, most recently updated first, with the `status` filter and `maxResults` / `nextToken` paging. Contributed by @iot-rocket.+- **IoT — `DeleteJobExecution`** — `DELETE /things/{thingName}/jobs/{jobId}/executionNumber/{executionNumber}` answered 400 `Unsupported IoT path`; it now deletes the execution (an `IN_PROGRESS` one only with `force`), drops it from the job's lists and counts, completes the job when only finished executions are left, and publishes the `deleted` job execution event and the thing's `jobs/notify` topics; a `CONTINUOUS` job's thing left with no execution gets none back until it leaves the group, which leaves a `REMOVED` execution 1. Contributed by @iot-rocket.### Fixed- **CloudFormation — `AWS::Logs::LogGroup` delete** — a stack delete or a `LogGroupName` replacement removed only the group record, so a metric filter or resource policy added through the Logs API stayed and came back with a new group of the same name; the group is now deleted through `DeleteLogGroup`. Contributed by @iot-rocket.diff --git a/README.md b/README.mdindex e4b9f26b..de61e205 100644--- a/README.md+++ b/README.md@@ -646,7 +646,7 @@ MiniStack expands AWS SAM transforms (`Transform: AWS::Serverless-2016-10-31`) i| **CodeBuild** | CreateProject, BatchGetProjects, ListProjects, UpdateProject, DeleteProject, StartBuild, BatchGetBuilds, StopBuild, ListBuilds, ListBuildsForProject, BatchDeleteBuilds | 11 actions; project and build metadata stored in-memory; builds complete immediately with SUCCEEDED status by default. Set `MINISTACK_CODEBUILD_EXECUTE=1` and mount the Docker socket to **really run them**: the project's inline buildspec goes to the official AWS CodeBuild local agent, which runs the phases in `environment.image`, and `BatchGetBuilds` reports live `phases` with a real `SUCCEEDED`/`FAILED` outcome. Execution needs the workspace shared with the host at the **same path** (`-v /tmp/ministack-codebuild:/tmp/ministack-codebuild`), because the agent bind-mounts it into the build container; a build gets `AWS_ENDPOINT_URL` pointing back at MiniStack, honours `timeoutInMinutes`, and is stopped by `StopBuild`. An executed build streams the agent output into its `logs.groupName` / `logs.streamName`, so `aws logs tail` reads the build log back || **AppConfig** | CreateApplication, GetApplication, ListApplications, UpdateApplication, DeleteApplication, CreateEnvironment, GetEnvironment, ListEnvironments, UpdateEnvironment, DeleteEnvironment, CreateConfigurationProfile, GetConfigurationProfile, ListConfigurationProfiles, UpdateConfigurationProfile, DeleteConfigurationProfile, CreateHostedConfigurationVersion, GetHostedConfigurationVersion, ListHostedConfigurationVersions, DeleteHostedConfigurationVersion, CreateDeploymentStrategy, GetDeploymentStrategy, ListDeploymentStrategies, UpdateDeploymentStrategy, DeleteDeploymentStrategy, StartDeployment, GetDeployment, ListDeployments, StopDeployment, TagResource, UntagResource, ListTagsForResource, StartConfigurationSession, GetLatestConfiguration | 33 operations; control plane + data plane; hosted configuration versions; the AWS-predefined deployment strategies (4) are listed and immutable; deployments move through `DEPLOYING`, `BAKING` and `COMPLETE` on the strategy's schedule (`LINEAR` or `EXPONENTIAL` steps, then the bake time), with `PercentageComplete`, the event log and the environment `State` reported along the way; a `Monitors` alarm that goes to `ALARM` before the bake ends rolls the deployment back; one deployment per environment at a time (`ConflictException`, also for a stale `LatestDeploymentNumber`); `StopDeployment` rolls back a `DEPLOYING` deployment, and with `AllowRevert` also a `BAKING` one, or reverts a completed one within 72 hours; during a rollout a session gets the new version once the rollout reaches its fixed slot (MiniStack's choice, since AWS does not document how it picks targets); `GetLatestConfiguration` returns an empty body when the session already has the latest version, plus `Version-Label`, and uses `RequiredMinimumPollIntervalInSeconds` as the poll interval || **Transfer Family** | CreateServer, DescribeServer, DeleteServer, ListServers, StartServer, StopServer, CreateUser, DescribeUser, DeleteUser, ListUsers, ImportSshPublicKey, DeleteSshPublicKey | 12 operations; **real SFTP listener** on `:2222` (override with `SFTP_PORT`) backed by S3 — `ls`, `put`, `get`, `mkdir`, `rename` work end-to-end against the local S3 emulator; `SFTP_PORT_PER_SERVER=1` allocates one port per `CreateServer` from `SFTP_BASE_PORT` (default 2300); SSH key auth scans every user across every server and account; `LOGICAL` and `PATH` home-directory mappings; host key persists across restarts when `PERSIST_STATE=1` |-| **IoT Jobs** | Control plane (`iot`): CreateJob, UpdateJob, DescribeJob, ListJobs, GetJobDocument, CancelJob, DeleteJob, ListJobExecutionsForThing, DescribeJobExecution, CancelJobExecution, CreateJobTemplate, DescribeJobTemplate, ListJobTemplates, DeleteJobTemplate; data plane (`iot-jobs-data`): GetPendingJobExecutions, StartNextPendingJobExecution, DescribeJobExecution (incl. the `$next` sentinel), UpdateJobExecution | 14 control-plane + 4 device data-plane operations sharing one store. A job created with a `jobTemplateArn` takes the template's document, configuration and maintenance windows, and a request member replaces the template's. Executions walk `QUEUED → IN_PROGRESS → {SUCCEEDED, FAILED, REJECTED, CANCELED, TIMED_OUT}`; an execution past its `timeoutConfig.inProgressTimeoutInMinutes`, or past the `stepTimeoutInMinutes` the device reported, becomes `TIMED_OUT`, and the device plane reports `approximateSecondsBeforeTimedOut` while it runs. `REMOVED` is modeled and counted in `jobProcessDetails` but nothing sets it: deleting a thing DELETES its executions (freeing a job that was only waiting on that thing) rather than marking them `REMOVED`. `versionNumber` gives optimistic concurrency: every transition bumps it and a stale `expectedVersion` is rejected with a 409 whose message carries the current version — coded `VersionConflictException` on the control plane and `InvalidStateTransitionException` on the device plane, each as its own service model declares. `executionNumber` is write-once (always 1: an execution is never re-queued). Devices may only report `IN_PROGRESS` / `SUCCEEDED` / `FAILED` / `REJECTED` via `UpdateJobExecution`; targets are thing or thing-group ARNs — `SNAPSHOT` jobs resolve group membership once at creation, `CONTINUOUS` jobs also pick up things added to a target group later, and a target must name a thing or thing group in the caller's own account and region (anything else is `ResourceNotFoundException`, since it would resolve to no devices at all); a non-continuous job auto-`COMPLETED`s (with `jobProcessDetails` counts) once every execution is terminal. **`documentSource` is not fetched**: a job created with an S3 `documentSource` serves a `{"documentSource": "<url>"}` placeholder as its document rather than the object's content, so the lifecycle still runs — pass `document` when the content matters; a job template with a `documentSource` stores the same placeholder. **Timestamps are epoch seconds on every plane, as AWS documents**: control-plane responses use `timestamp` shapes (boto3 parses them to datetimes) while `iot-jobs-data` responses carry whole-second integer `long`s. **Jobs over MQTT**: the reserved `$aws/things/<thing>/jobs/#` request topics (`get`, `start-next`, `<jobId>/get` incl. `$next`, `<jobId>/update`) answer on their `accepted`/`rejected` topics from the same store as the HTTP plane (`jobDocument` as a JSON object over MQTT, a string over HTTP, as on AWS; rejections carry the string `ErrorCode` values and the execution's state on version and state-transition conflicts); `notify` fires when the pending set changes and `notify-next` when the queue front changes; `stepTimeoutInMinutes` and `executionNumber` are accepted but ignored. Job state persists with the IoT store when `PERSIST_STATE=1` |+| **IoT Jobs** | Control plane (`iot`): CreateJob, UpdateJob, DescribeJob, ListJobs, GetJobDocument, CancelJob, DeleteJob, ListJobExecutionsForThing, ListJobExecutionsForJob, DescribeJobExecution, CancelJobExecution, DeleteJobExecution, CreateJobTemplate, DescribeJobTemplate, ListJobTemplates, DeleteJobTemplate; data plane (`iot-jobs-data`): GetPendingJobExecutions, StartNextPendingJobExecution, DescribeJobExecution (incl. the `$next` sentinel), UpdateJobExecution | 16 control-plane + 4 device data-plane operations sharing one store. A job created with a `jobTemplateArn` takes the template's document, configuration and maintenance windows, and a request member replaces the template's. Executions walk `QUEUED → IN_PROGRESS → {SUCCEEDED, FAILED, REJECTED, CANCELED, TIMED_OUT}`; an execution past its `timeoutConfig.inProgressTimeoutInMinutes`, or past the `stepTimeoutInMinutes` the device reported, becomes `TIMED_OUT`, and the device plane reports `approximateSecondsBeforeTimedOut` while it runs. `REMOVED` is counted in `jobProcessDetails`; a thing that leaves every target group of a `CONTINUOUS` job turns its `QUEUED` execution `REMOVED`, or gets a `REMOVED` execution 1 (without an event) if all its executions were deleted; deleting a thing DELETES its executions (freeing a job that was only waiting on that thing) rather than marking them `REMOVED`. `versionNumber` gives optimistic concurrency: every transition bumps it and a stale `expectedVersion` is rejected with a 409 whose message carries the current version — coded `VersionConflictException` on the control plane and `InvalidStateTransitionException` on the device plane, each as its own service model declares. `executionNumber` is 1 for a thing's first execution of a job and one more each time the thing rejoins a `CONTINUOUS` job's target group after its execution finished. Devices may only report `IN_PROGRESS` / `SUCCEEDED` / `FAILED` / `REJECTED` via `UpdateJobExecution`; targets are thing or thing-group ARNs — `SNAPSHOT` jobs resolve group membership once at creation, `CONTINUOUS` jobs also pick up things added to a target group later, and a target must name a thing or thing group in the caller's own account and region (anything else is `ResourceNotFoundException`, since it would resolve to no devices at all); a non-continuous job auto-`COMPLETED`s (with `jobProcessDetails` counts) once every execution is terminal. **`documentSource` is not fetched**: a job created with an S3 `documentSource` serves a `{"documentSource": "<url>"}` placeholder as its document rather than the object's content, so the lifecycle still runs — pass `document` when the content matters; a job template with a `documentSource` stores the same placeholder. **Timestamps are epoch seconds on every plane, as AWS documents**: control-plane responses use `timestamp` shapes (boto3 parses them to datetimes) while `iot-jobs-data` responses carry whole-second integer `long`s. **Jobs over MQTT**: the reserved `$aws/things/<thing>/jobs/#` request topics (`get`, `start-next`, `<jobId>/get` incl. `$next`, `<jobId>/update`) answer on their `accepted`/`rejected` topics from the same store as the HTTP plane (`jobDocument` as a JSON object over MQTT, a string over HTTP, as on AWS; rejections carry the string `ErrorCode` values and the execution's state on version and state-transition conflicts); `notify` fires when the pending set changes and `notify-next` when the queue front changes; `stepTimeoutInMinutes` and `executionNumber` are accepted but ignored. Job state persists with the IoT store when `PERSIST_STATE=1` || **IoT Core** | CreateThing, DescribeThing, ListThings, UpdateThing, DeleteThing, CreateThingType, CreateThingGroup, AddThingToThingGroup, ListThingsInThingGroup, ListThingGroupsForThing, CreateKeysAndCertificate, RegisterCertificate, RegisterCertificateWithoutCA, CreateCertificateFromCsr, UpdateCertificate, DeleteCertificate, GetRegistrationCode, DeleteRegistrationCode, RegisterCACertificate, DescribeCACertificate, UpdateCACertificate, ListCACertificates, DeleteCACertificate, ListCertificatesByCA, CreateProvisioningTemplate, DescribeProvisioningTemplate, ListProvisioningTemplates, UpdateProvisioningTemplate, DeleteProvisioningTemplate, AttachThingPrincipal, DetachThingPrincipal, ListThingPrincipals, ListPrincipalThings, CreatePolicy, CreatePolicyVersion, AttachPolicy, DetachPolicy, ListAttachedPolicies, ListTargetsForPolicy, AttachPrincipalPolicy, DetachPrincipalPolicy, ListPrincipalPolicies, ListPolicyPrincipals, CreateTopicRule, GetTopicRule, ReplaceTopicRule, DeleteTopicRule, ListTopicRules, UpdateIndexingConfiguration, GetIndexingConfiguration, DescribeIndex, ListIndices, SearchIndex, DescribeEndpoint, Publish (HTTP), MQTT-over-WebSocket pub/sub, DescribeEventConfigurations, UpdateEventConfigurations, CreateDomainConfiguration, DescribeDomainConfiguration, ListDomainConfigurations, UpdateDomainConfiguration, DeleteDomainConfiguration | 63 operations + **MQTT 3.1.1 and 5.0 over WebSocket** (negotiated per connection) on the gateway port — clients use the address returned by `DescribeEndpoint`; local CA signs `CreateKeysAndCertificate` certificates (CA persists across restarts when `PERSIST_STATE=1`); multi-tenancy via transparent topic prefixing (same pattern as Transfer Family's shared SFTP listener); no plain TCP 1883 (real AWS IoT requires TLS or SigV4 on every connection), but a **native mTLS MQTT listener on 8883** serves device SDK binaries by default — the client certificate is optional (no certificate means the default account, like an unsigned WebSocket upgrade) and, when presented, must be registered `ACTIVE` in exactly one account, which then serves the session; unknown, inactive or doubly-registered certificates get a "not authorized" CONNACK (see `IOT_MTLS_PORT` in the environment table); local CA cert available at `GET /_ministack/iot/ca.pem` for SDK trust configuration; IoT policies are stored but **not enforced** on the data plane; **fleet indexing** works the way it does on AWS — `UpdateIndexingConfiguration` turns the `AWS_Things` index on (Terraform `aws_iot_indexing_configuration`), and searching while `thingIndexingMode` is `OFF` answers `ResourceNotFoundException`; `SearchIndex` then queries the live registry + classic shadows with `AND`-separated `thingName` / `thingTypeName` / `thingGroupNames` / `attributes.*` / `shadow.reported.*` / `shadow.desired.*` terms (`*` / `?` wildcards, `maxResults` / `nextToken` paging) — there is no projection to build, so hits are always current; the deprecated principal-policy family (`AttachPrincipalPolicy` / `DetachPrincipalPolicy` / `ListPrincipalPolicies` / `ListPolicyPrincipals`) maps 1:1 onto the modern policy-target store; **topic rules fire on matching publishes** (incl. Basic Ingest `$aws/rules/<name>`) with SQL SELECT projection (`topic()`, `timestamp()`, `encode()`, `newuuid()`, `replace()`, `clientid()`, `isUndefined()`), **WHERE-clause evaluation** (comparisons, `IN`, `LIKE`, `BETWEEN`, `IS NULL`, `regexp_matches`, bare boolean attributes, composed with `AND` / `OR` and parenthesised grouping; missing attributes fail closed as on AWS; unparseable SQL → `SqlParseException`), and `lambda` / `republish` / `dynamoDBv2` / `sns` / `sqs` actions dispatched in-process with the rule's `errorAction` on failure; **device shadows over MQTT** — the `$aws/things/<thing>/shadow[/name/<name>]/{get,update,delete}` reserved topics drive the shadow store and reply on `accepted` / `rejected` (with `delta` and `documents` on update); a **CA-certificate registry** (`RegisterCACertificate` and friends) with the just-in-time-registration `registered` event on `$aws/events/certificates/registered/{caCertificateId}`; a **provisioning-template registry** (`CreateProvisioningTemplate` and friends) — storage + CRUD only, so `provisioningRoleArn` is presence-checked but not resolved and the fleet-provisioning MQTT workflow (`$aws/provisioning-templates/...`) is not implemented; and `SearchIndex` answers `connectivity.connected` / `connectivity.timestamp` / `connectivity.disconnectReason` when `thingConnectivityIndexingMode` is `STATUS`, deriving `connected` from the live session registry; the broker publishes the presence and subscription lifecycle events (`$aws/events/presence/connected\|disconnected/{clientId}`, `$aws/events/subscriptions/subscribed\|unsubscribed/{clientId}`) || **IoT Wireless** | GetPositionEstimate | Single operation (`POST /position-estimate`, SigV4 scope `iotwireless`, endpoint prefix `api.iotwireless`). **The response is the raw GeoJSON blob** — the output shape's `payload` trait — so boto3 hands back a `StreamingBody` under `GeoJsonPayload`, not a JSON envelope. Resolves from `Ip` only: `WiFiAccessPoints` / `CellTowers` / `Gnss` are accepted and ignored, `Timestamp` and `AdvancedConfiguration` only reach `properties`, and the estimate is synthetic + deterministic — the canonical IP (an IPv4-mapped IPv6 address counts as its IPv4 form) hashes onto lon [-180, 180) / lat [-60, 60), 4 decimals — so the same address always answers the same estimate and consumer tests can assert on it. `properties` carry `horizontalAccuracy` 1000000 (the value of one live call) and `horizontalConfidenceLevel` 0.68 (the default the AWS IoT Core Device Location guide documents — `AdvancedConfiguration.WiFiCellular.ConfidencePercent` overrides it, divided by 100, within the 50 to 99 the model allows) plus `timestamp`, which is always there: AWS documents the request's `Timestamp` as the resolve time and the receive time as its substitute when the caller sends none, so send a `Timestamp` and the whole blob is byte-identical. The real payload's `country` and city/state/postal properties are omitted for that determinism. An input with no resolver hint and an `IpAddress` that `ipaddress.ip_address()` refuses answer `ValidationException` (those two wordings are recorded from the live service; every other message in this service is MiniStack's own, since none is documented); a `Timestamp` that is not a Unix timestamp, and a `ConfidencePercent` outside the model's range, are `ValidationException` too; a valid address that is **not globally routable or is multicast** (private, loopback, TEST-NET, multicast groups, ...) answers `ResourceNotFoundException` `Cannot find position for the IP address <ip>`, mirroring the real service's refusal when its geo database has no entry. A well-formed request whose only measurements are WLAN/cell/GNSS is `ResourceNotFoundException` too — the developer guide documents 404 for exactly that ("no location information was found or solved ... The MAC address or cellular tower information is not sufficient ... The GNSS payload is not sufficient"), and 400 for measurement data formatted incorrectly. Stateless — nothing persists || **EventBridge Scheduler** | CreateSchedule, GetSchedule, UpdateSchedule, DeleteSchedule, ListSchedules, CreateScheduleGroup, GetScheduleGroup, DeleteScheduleGroup, ListScheduleGroups, TagResource, UntagResource, ListTagsForResource | 12 actions; schedules **fire their targets** — a background sweep invokes each enabled schedule's target (Lambda, SQS, SNS, Step Functions) when due, honoring `State`, `StartDate`/`EndDate`, and `ActionAfterCompletion: DELETE`; schedule groups with cascading deletes; `rate()`, `cron()`, `at()` expressions; group/prefix/state filters on list; default group auto-created; CFN `AWS::Scheduler::Schedule` and `AWS::Scheduler::ScheduleGroup` supported |diff --git a/ministack/services/iot.py b/ministack/services/iot.pyindex f8b02a2e..5ea26b4e 100644--- a/ministack/services/iot.py+++ b/ministack/services/iot.py@@ -37,8 +37,9 @@ Implements the JSON/REST APIs under ``iot.{region}.amazonaws.com``:``UpdateEventConfigurations``- Jobs (control plane): ``CreateJob``, ``UpdateJob``, ``DescribeJob``,``ListJobs``, ``GetJobDocument``, ``CancelJob``, ``DeleteJob``,- ``ListJobExecutionsForThing``, ``DescribeJobExecution``,- ``CancelJobExecution`` — execution state shared with the+ ``ListJobExecutionsForThing``, ``ListJobExecutionsForJob``,+ ``DescribeJobExecution``, ``CancelJobExecution``,+ ``DeleteJobExecution`` — execution state shared with the``iot-jobs-data`` device data plane (``iot_jobs_data.py``)- Job templates: ``CreateJobTemplate``, ``DescribeJobTemplate``,``ListJobTemplates``, ``DeleteJobTemplate``; ``CreateJob`` with a@@ -526,7 +527,8 @@ async def _route_request(# must come BEFORE the generic /things/{name} branch.if path.startswith("/things/") and path.endswith("/thing-groups") and method == "GET":return _list_thing_groups_for_thing(path)- # Job executions live at /things/{name}/jobs[/{jobId}[/cancel]] — like+ # Job executions live at /things/{name}/jobs[/{jobId}[/cancel]] and+ # /things/{name}/jobs/{jobId}/executionNumber/{n} — like# /principals, must come BEFORE the generic /things/{name} branch. The# `jobs` segment only counts when a thing name precedes it: `/things/jobs`# is thing CRUD for a thing that happens to be named `jobs`.@@ -1396,6 +1398,9 @@ def _delete_thing(name: str) -> tuple:orphaned_jobs = [key[1] for key in _job_executions.keys() if key[0] == name]for job_id in orphaned_jobs:del _job_executions[(name, job_id)]+ for job in _jobs.values():+ if name in (job.get("executionsDeletedFor") or ()):+ job["executionsDeletedFor"].remove(name)del _things[name]for job_id in orphaned_jobs:_jobs_maybe_complete(job_id)@@ -1797,14 +1802,15 @@ async def _remove_thing_from_group(payload: dict) -> tuple:if thing is None:return _error_not_found("Thing", tname or "")prev_next = jobs_first_pending_job_id(tname)- if tname in group.get("things", []):+ left = tname in group.get("things", [])+ if left:group["things"].remove(tname)_thing_groups[gname] = group_membership_event("REMOVED", group, thing)if gname in thing.get("thingGroupNames", []):thing["thingGroupNames"].remove(gname)_things[tname] = thing- if _jobs_thing_left_group(tname):+ if _jobs_thing_left_group(tname, _thing_group_arn(gname) if left else None):await jobs_notify_thing(get_account_id(), get_region(), tname, prev_next)return json_response({})@@ -4844,6 +4850,9 @@ def _list_topic_rules(qp: dict) -> tuple:# A thing leaving every target of a CONTINUOUS job moves its QUEUED execution# to REMOVED (see `_jobs_thing_left_group`). Deleting a thing DELETES its# executions (see `_delete_thing`) rather than marking them REMOVED.+# DeleteJobExecution removes one execution; a CONTINUOUS job's thing that+# lost all of them is listed under the job's `executionsDeletedFor`, so that+# reads do not queue a new one until the thing joins a target group again.# Job ids are stricter than thing names, and identically so in both service# models (`iot` and `iot-jobs-data` declare JobId as [a-zA-Z0-9_-], max 64).@@ -4959,9 +4968,10 @@ def _jobs_materialize_executions(job_id: str) -> None:if job.get("targetSelection") == "SNAPSHOT" and job.get("snapshotted"):returnnow = _jobs_now_ms()+ deleted = job.get("executionsDeletedFor") or ()for thing in _job_target_things(job.get("targets")):key = (thing, job_id)- if key in _job_executions:+ if key in _job_executions or thing in deleted:continue_jobs_queue_execution(thing, job_id, now)if job.get("targetSelection") == "SNAPSHOT":@@ -4993,6 +5003,9 @@ def _jobs_queue_execution(thing: str, job_id: str, now: int) -> None:*previous.get("history", []),]_job_executions[(thing, job_id)] = execution+ deleted = (_jobs.get(job_id) or {}).get("executionsDeletedFor")+ if deleted and thing in deleted:+ deleted.remove(thing)def _jobs_thing_joined_group(thing: str, group_arn: str) -> bool:@@ -5022,10 +5035,11 @@ def _jobs_thing_joined_group(thing: str, group_arn: str) -> bool:return queued-def _jobs_thing_left_group(thing: str) -> bool:+def _jobs_thing_left_group(thing: str, group_arn: str | None) -> bool:"""Retire a thing's QUEUED CONTINUOUS executions after it left a group.- Call after the membership change. For every CONTINUOUS job the thing no+ Call after the membership change, with the ARN of the group the thing+ left (None when it was not a member). For every CONTINUOUS job the thing nolonger resolves into, a QUEUED execution becomes REMOVED with its`versionNumber` unchanged. IN_PROGRESS, SUCCEEDED and FAILED executionskeep their status (measured eu-central-1 2026-10-05). Returns whether a@@ -5035,6 +5049,17 @@ def _jobs_thing_left_group(thing: str) -> bool:removed = Falsefor job_id, job in _jobs.items():execution = _job_executions.get((thing, job_id))+ if (+ execution is None+ and thing in (job.get("executionsDeletedFor") or ())+ and group_arn in (job.get("targets") or [])+ and job.get("status") != "CANCELED"+ and thing not in _job_target_things(job.get("targets"))+ ):+ # All its executions were deleted: it gets a REMOVED one, without an event.+ _jobs_queue_execution(thing, job_id, now)+ _job_executions[(thing, job_id)]["status"] = "REMOVED"+ continueif (execution is Noneor execution["status"] != "QUEUED"@@ -5273,6 +5298,8 @@ async def _handle_job(method: str, path: str, body: bytes, qp: dict) -> tuple:return await _cancel_job(suffix[:-len("/cancel")], _parse_body(body), qp)if suffix.endswith("/job-document") and method == "GET":return _get_job_document(suffix[:-len("/job-document")])+ if suffix.endswith("/things") and method == "GET":+ return _list_job_executions_for_job(suffix[:-len("/things")], qp)if "/" in suffix:return error_response_json("InvalidRequestException", f"Unsupported IoT path: {method} {path}", 400@@ -5789,7 +5816,7 @@ _JOB_TEMPLATE_CONFIG_MEMBERS = ("presignedUrlConfig", "jobExecutionsRolloutConfig", "abortConfig","timeoutConfig", "jobExecutionsRetryConfig",)-_JOB_TEMPLATE_PAGE_MAX = 250+_JOB_PAGE_MAX = 250def _job_template_arn(template_id: str) -> str:@@ -5975,43 +6002,51 @@ def _describe_job_template(template_id: str) -> tuple:})-def _list_job_templates(qp: dict) -> tuple:- """``GET /job-templates``, newest first, paged by ``maxResults`` /- ``nextToken``; the token carries an offset into that order."""+def _jobs_page(items: list, qp: dict, kind: str) -> tuple[list, str | None, tuple | None]:+ """The ``maxResults`` / ``nextToken`` page of ``items`` as (page, token, error); a token is an offset."""raw = qp.get("maxResults")try:- limit = _JOB_TEMPLATE_PAGE_MAX if raw in (None, "") else int(raw)+ limit = _JOB_PAGE_MAX if raw in (None, "") else int(raw)except (TypeError, ValueError):limit = 0- if not 1 <= limit <= _JOB_TEMPLATE_PAGE_MAX:+ if not 1 <= limit <= _JOB_PAGE_MAX:bound = ("greater than or equal to 1" if limit < 1- else f"less than or equal to {_JOB_TEMPLATE_PAGE_MAX}")- return _job_template_validation_error(+ else f"less than or equal to {_JOB_PAGE_MAX}")+ return [], None, _job_validation_error([_job_validation_clause(raw, "maxResults", f"Member must have value {bound}"- )+ )])start = 0token = qp.get("nextToken")if token:try:raw_token = base64.urlsafe_b64decode(token + "=" * (-len(token) % 4)).decode()prefix, _, offset = raw_token.partition(":")- start = int(offset) if prefix == "jobtemplates" else -1+ start = int(offset) if prefix == kind else -1except ValueError: # binascii.Error and UnicodeDecodeError includedstart = -1if start < 0:- return error_response_json(+ return [], None, error_response_json("InvalidRequestException", "Next token is invalid.", 400)+ if start + limit >= len(items):+ return items[start:], None, None+ token = base64.urlsafe_b64encode(f"{kind}:{start + limit}".encode()).decode().rstrip("=")+ return items[start:start + limit], token, None+++def _list_job_templates(qp: dict) -> tuple:+ """``GET /job-templates``, newest first, paged by ``maxResults`` /+ ``nextToken``; the token carries an offset into that order."""ordered = sorted(_job_templates.values(), key=lambda t: t["createdAt"], reverse=True)- page = ordered[start:start + limit]+ page, token, error = _jobs_page(ordered, qp, "jobtemplates")+ if error:+ return errorresponse = {"jobTemplates": [{k: t[k] for k in ("jobTemplateArn", "jobTemplateId", "description", "createdAt")}for t in page]}- if start + limit < len(ordered):- response["nextToken"] = base64.urlsafe_b64encode(- f"jobtemplates:{start + limit}".encode()- ).decode().rstrip("=")+ if token:+ response["nextToken"] = tokenreturn json_response(response)@@ -6132,7 +6167,8 @@ async def _cancel_job(job_id: str, payload: dict, qp: dict) -> tuple:async def _handle_thing_jobs(method: str, path: str, body: bytes, qp: dict) -> tuple:"""Dispatch /things/{name}/jobs[...] control-plane routes.- Async because CancelJobExecution publishes jobs/notify(-next)."""+ Async because CancelJobExecution and DeleteJobExecution publish+ jobs/notify(-next)."""rest = path[len("/things/"):]thing, _, sub = rest.partition("/")err = _validate_name(thing, "thingName")@@ -6155,6 +6191,9 @@ async def _handle_thing_jobs(method: str, path: str, body: bytes, qp: dict) -> t)if "/" not in tail and method == "GET":return _describe_job_execution(thing, tail, qp)+ job_id, _, number = tail.partition("/executionNumber/")+ if number and "/" not in job_id and method == "DELETE":+ return await _delete_job_execution(thing, job_id, number, qp)return error_response_json("InvalidRequestException", f"Unsupported IoT path: {method} {path}", 400)@@ -6181,21 +6220,70 @@ def _list_job_executions_for_thing(thing: str, qp: dict) -> tuple:continueif wanted_job and execution["jobId"] != wanted_job:continue- summary = {- "status": execution["status"],- "queuedAt": _jobs_ms_to_s(execution["queuedAt"]),- "lastUpdatedAt": _jobs_ms_to_s(execution["lastUpdatedAt"]),- "executionNumber": execution["executionNumber"],- "retryAttempt": execution.get("retryAttempt", 0),- }- if execution.get("startedAt") is not None:- summary["startedAt"] = _jobs_ms_to_s(execution["startedAt"])- summaries.append(- {"jobId": execution["jobId"], "jobExecutionSummary": summary}- )+ summaries.append({+ "jobId": execution["jobId"],+ "jobExecutionSummary": _job_execution_summary(execution),+ })return json_response({"executionSummaries": summaries})+def _job_execution_summary(execution: dict) -> dict:+ """Control-plane JobExecutionSummary, as both execution lists nest it."""+ summary = {+ "status": execution["status"],+ "queuedAt": _jobs_ms_to_s(execution["queuedAt"]),+ "lastUpdatedAt": _jobs_ms_to_s(execution["lastUpdatedAt"]),+ "executionNumber": execution["executionNumber"],+ "retryAttempt": execution.get("retryAttempt", 0),+ }+ if execution.get("startedAt") is not None:+ summary["startedAt"] = _jobs_ms_to_s(execution["startedAt"])+ return summary+++def _list_job_executions_for_job(job_id: str, qp: dict) -> tuple:+ """``GET /jobs/{jobId}/things``, most recently updated first, paged like ``ListJobTemplates``."""+ clauses = []+ if not re.fullmatch(r"[a-zA-Z0-9_-]+", job_id):+ clauses.append(_job_validation_clause(+ job_id, "jobId", "Member must satisfy regular expression pattern: [a-zA-Z0-9_-]+"+ ))+ status = qp.get("status")+ if status is not None and status not in _JOB_EXECUTION_STATUSES:+ clauses.append(_job_validation_clause(+ status, "status", "Member must satisfy enum value set: [REMOVED, SUCCEEDED, "+ "TIMED_OUT, IN_PROGRESS, QUEUED, CANCELED, FAILED, REJECTED]"+ ))+ if clauses:+ return _job_validation_error(clauses)+ _, _, error = _jobs_page([], qp, "jobexecutions")+ if error:+ return error+ if job_id not in _jobs:+ return error_response_json(+ "ResourceNotFoundException", f"Job {job_id} cannot be found.", 404+ )+ _jobs_materialize_executions(job_id)+ executions = [+ execution+ for latest in _job_executions.values()+ if latest["jobId"] == job_id+ for execution in _jobs_with_history(latest)+ if status is None or execution["status"] == status+ ]+ executions.sort(key=lambda e: e["lastUpdatedAt"], reverse=True)+ page, token, error = _jobs_page(executions, qp, "jobexecutions")+ if error:+ return error+ response = {"executionSummaries": [+ {"thingArn": _thing_arn(e["thingName"]), "jobExecutionSummary": _job_execution_summary(e)}+ for e in page+ ]}+ if token:+ response["nextToken"] = token+ return json_response(response)++def _describe_job_execution(thing: str, job_id: str, qp: dict) -> tuple:"""Without `executionNumber` the newest execution, with it that one."""_jobs_materialize_executions(job_id)@@ -6265,6 +6353,65 @@ async def _cancel_job_execution(return json_response({})+async def _delete_job_execution(thing: str, job_id: str, number: str, qp: dict) -> tuple:+ """Delete one of a thing's executions of a job; an IN_PROGRESS one only with force."""+ try:+ number = int(number)+ except ValueError:+ return error_response_json(+ "SerializationException", f"'{number}' can not be converted to Long", 400+ )+ if number < 1:+ return error_response_json(+ "InvalidRequestException", "Execution number is invalid.", 400+ )+ job = _jobs.get(job_id)+ if job is None:+ return error_response_json(+ "ResourceNotFoundException",+ f"Job execution cannot be found as the Job {job_id} does not exist.",+ 404,+ )+ _jobs_materialize_executions(job_id)+ latest = _job_executions.get((thing, job_id))+ executions = _jobs_with_history(_jobs_apply_timeout(latest)) if latest else []+ execution = next((e for e in executions if e["executionNumber"] == number), None)+ if execution is None:+ return error_response_json(+ "ResourceNotFoundException",+ f"Job execution for thing {thing} cannot be found within job {job_id}.",+ 404,+ )+ if execution["status"] == "IN_PROGRESS" and not _qp_bool(qp, "force"):+ return error_response_json(+ "InvalidStateTransitionException",+ f"Job execution for thing {thing} within job {job_id} in status "+ "IN_PROGRESS cannot be deleted without force flag.",+ 409,+ )+ pending = execution["status"] in ("QUEUED", "IN_PROGRESS")+ prev_next = jobs_first_pending_job_id(thing) if pending else None+ # The next newest execution, if any, becomes the thing's current one.+ rest = [+ {k: v for k, v in e.items() if k != "history"}+ for e in executions+ if e is not execution+ ]+ if rest:+ if len(rest) > 1:+ rest[0]["history"] = rest[1:]+ _job_executions[(thing, job_id)] = rest[0]+ else:+ del _job_executions[(thing, job_id)]+ if job.get("targetSelection") == "CONTINUOUS":+ job.setdefault("executionsDeletedFor", []).append(thing)+ _job_execution_event(execution, "DELETED")+ _jobs_maybe_complete(job_id)+ if pending:+ await jobs_notify_thing(get_account_id(), get_region(), thing, prev_next)+ return 200, {}, b""++# ---------------------------------------------------------------------------# Helper exports for the data planes (iot_data, iot_jobs_data)# ---------------------------------------------------------------------------diff --git a/tests/test_iot.py b/tests/test_iot.pyindex a009b249..74485870 100644--- a/tests/test_iot.py+++ b/tests/test_iot.py@@ -6984,6 +6984,34 @@ def test_iot_job_removed_timed_out_and_deleted_events():assert events[8][1]["targetSelection"] == "CONTINUOUS"+def test_iot_job_execution_deleted_events():+ async def calls(call):+ for thing in ("ev-t1", "ev-t2"):+ await call("POST", f"/things/{thing}")+ await _create_job(call, "ev-del", ["ev-t1", "ev-t2"])+ await call("POST", "/things/ev-t2/jobs/ev-del",+ {"status": "IN_PROGRESS", "statusDetails": {"p": "2"}}, device=True)+ await call("DELETE", "/things/ev-t1/jobs/ev-del/executionNumber/1")+ await call("DELETE", "/things/ev-t2/jobs/ev-del/executionNumber/1",+ query={"force": "true"})++ events = _registry_events(calls, enable=("JOB", "JOB_EXECUTION"))+ assert [t for t, _e in events] == [+ "$aws/events/jobExecution/ev-del/deleted",+ "$aws/events/jobExecution/ev-del/deleted",+ "$aws/events/job/ev-del/completed",+ ]+ for _t, e in events:+ e.pop("eventId")+ _job_stamps(e)+ deleted = {"eventType": "JOB_EXECUTION", "operation": "deleted", "jobId": "ev-del",+ "status": "DELETED", "executionNumber": 1}+ assert events[0][1] == {**deleted, "thingArn": f"{_JOB_ARN}:thing/ev-t1"}+ assert events[1][1] == {**deleted, "thingArn": f"{_JOB_ARN}:thing/ev-t2",+ "statusDetails": {"p": "2"}}+ assert events[2][1]["jobProcessDetails"] == _job_counts()++@pytest.mark.parametrize("enable", [("JOB",), ("JOB_EXECUTION",), ()])def test_iot_job_events_follow_the_event_configuration(enable):async def calls(call):diff --git a/tests/test_iot_jobs_data.py b/tests/test_iot_jobs_data.pyindex 99fe2b2f..00112b4c 100644--- a/tests/test_iot_jobs_data.py+++ b/tests/test_iot_jobs_data.py@@ -1401,6 +1401,210 @@ def test_iot_jobs_cancel_job_and_delete(iot_client, iot_jobs_data):_cleanup(iot_client, things=[thing])+def test_iot_jobs_delete_job_execution(iot_client, iot_jobs_data):+ """An IN_PROGRESS execution needs force; a deleted one leaves both planes and the counts."""+ queued, running, failed = (_unique("jobs-thing") for _ in range(3))+ job_id = _unique("job")+ try:+ arns = [_create_thing(iot_client, t) for t in (queued, running, failed)]+ iot_client.create_job(jobId=job_id, targets=arns, document=_DOCUMENT)+ _drive(iot_jobs_data, running, job_id, "IN_PROGRESS")+ _drive(iot_jobs_data, failed, job_id, "FAILED")++ def refused(**kwargs):+ with pytest.raises(ClientError) as ei:+ iot_client.delete_job_execution(+ **{"jobId": job_id, "executionNumber": 1, **kwargs}+ )+ response = ei.value.response+ return (+ response["ResponseMetadata"]["HTTPStatusCode"],+ response["Error"]["Code"],+ response["Error"]["Message"],+ )++ assert refused(thingName=running) == (+ 409, "InvalidStateTransitionException",+ f"Job execution for thing {running} within job {job_id} in status "+ "IN_PROGRESS cannot be deleted without force flag.",+ )+ assert refused(thingName=running, force=False)[:2] == (+ 409, "InvalidStateTransitionException",+ )+ assert refused(thingName=failed, executionNumber=2) == (+ 404, "ResourceNotFoundException",+ f"Job execution for thing {failed} cannot be found within job {job_id}.",+ )+ assert refused(thingName=failed, executionNumber=0) == (+ 400, "InvalidRequestException", "Execution number is invalid.",+ )+ assert refused(thingName=failed, jobId="no-such-job") == (+ 404, "ResourceNotFoundException",+ "Job execution cannot be found as the Job no-such-job does not exist.",+ )+ status, body = _raw(+ _IOT_AUTH, "DELETE", f"/things/{failed}/jobs/{job_id}/executionNumber/x"+ )+ assert (status, body["__type"]) == (400, "SerializationException")++ iot_client.delete_job_execution(+ jobId=job_id, thingName=queued, executionNumber=1+ )+ assert refused(thingName=queued, force=True)[0] == 404+ assert _executions_for(iot_client, queued, job_id) == []+ assert (+ iot_jobs_data.get_pending_job_executions(thingName=queued)["queuedJobs"]+ == []+ )++ iot_client.delete_job_execution(+ jobId=job_id, thingName=running, executionNumber=1, force=True+ )+ for call in (+ lambda: iot_jobs_data.describe_job_execution(+ jobId=job_id, thingName=running+ ),+ lambda: iot_jobs_data.update_job_execution(+ jobId=job_id, thingName=running, status="SUCCEEDED"+ ),+ ):+ with pytest.raises(ClientError) as ei:+ call()+ assert ei.value.response["Error"]["Code"] == "ResourceNotFoundException"+ job = iot_client.describe_job(jobId=job_id)["job"]+ assert job["status"] == "COMPLETED"+ details = job["jobProcessDetails"]+ assert (+ details["numberOfQueuedThings"],+ details["numberOfInProgressThings"],+ details["numberOfFailedThings"],+ ) == (0, 0, 1)++ iot_client.delete_job_execution(+ jobId=job_id, thingName=failed, executionNumber=1+ )+ details = iot_client.describe_job(jobId=job_id)["job"]["jobProcessDetails"]+ assert details["numberOfFailedThings"] == 0+ finally:+ _cleanup(iot_client, jobs=[job_id], things=[queued, running, failed])+++def test_iot_jobs_delete_continuous_job_executions(iot_client, iot_jobs_data):+ """A thing's older or newer execution goes; one left with none gets REMOVED 1 on leaving."""+ group, other = _unique("jobs-group"), _unique("jobs-other")+ job_id = _unique("job-cont")+ emptied, kept = _unique("jobs-emptied"), _unique("jobs-kept")+ try:+ group_arn = iot_client.create_thing_group(thingGroupName=group)[+ "thingGroupArn"+ ]+ iot_client.create_job(+ jobId=job_id, targets=[group_arn], document=_DOCUMENT,+ targetSelection="CONTINUOUS",+ )+ for thing in (emptied, kept):+ _create_thing(iot_client, thing)+ iot_client.add_thing_to_thing_group(thingGroupName=group, thingName=thing)+ _drive(iot_jobs_data, thing, job_id, "SUCCEEDED")+ iot_client.remove_thing_from_thing_group(+ thingGroupName=group, thingName=thing+ )+ iot_client.add_thing_to_thing_group(thingGroupName=group, thingName=thing)+ assert _executions_for(iot_client, thing, job_id) == [+ (2, "QUEUED"), (1, "SUCCEEDED"),+ ]++ iot_client.delete_job_execution(+ jobId=job_id, thingName=emptied, executionNumber=1+ )+ assert _executions_for(iot_client, emptied, job_id) == [(2, "QUEUED")]+ iot_client.delete_job_execution(+ jobId=job_id, thingName=emptied, executionNumber=2+ )+ iot_client.delete_job_execution(jobId=job_id, thingName=kept, executionNumber=2)+ assert _executions_for(iot_client, kept, job_id) == [(1, "SUCCEEDED")]+ execution = iot_client.describe_job_execution(jobId=job_id, thingName=kept)+ assert execution["execution"]["executionNumber"] == 1+ pending = iot_jobs_data.get_pending_job_executions(thingName=emptied)+ assert (pending["inProgressJobs"], pending["queuedJobs"]) == ([], [])+ assert _executions_for(iot_client, emptied, job_id) == []++ for thing in (emptied, kept):+ iot_client.remove_thing_from_thing_group(+ thingGroupName=group, thingName=thing+ )+ assert _executions_for(iot_client, emptied, job_id) == [(1, "REMOVED")]+ assert _executions_for(iot_client, kept, job_id) == [(1, "SUCCEEDED")]+ for thing in (emptied, kept):+ iot_client.add_thing_to_thing_group(thingGroupName=group, thingName=thing)+ assert _executions_for(iot_client, emptied, job_id) == [+ (2, "QUEUED"), (1, "REMOVED"),+ ]+ assert _executions_for(iot_client, kept, job_id) == [+ (2, "QUEUED"), (1, "SUCCEEDED"),+ ]++ # Leaving a group the job does not target adds nothing, and neither+ # does a removal from a group the thing is not in, also for a later+ # thing of the same name.+ iot_client.create_thing_group(thingGroupName=other)+ iot_client.add_thing_to_thing_group(thingGroupName=other, thingName=emptied)+ for number in (2, 1):+ iot_client.delete_job_execution(+ jobId=job_id, thingName=emptied, executionNumber=number+ )+ iot_client.remove_thing_from_thing_group(thingGroupName=group, thingName=emptied)+ assert _executions_for(iot_client, emptied, job_id) == [(1, "REMOVED")]+ iot_client.delete_job_execution(+ jobId=job_id, thingName=emptied, executionNumber=1+ )+ iot_client.remove_thing_from_thing_group(thingGroupName=other, thingName=emptied)+ iot_client.remove_thing_from_thing_group(thingGroupName=group, thingName=emptied)+ assert _executions_for(iot_client, emptied, job_id) == []+ iot_client.delete_thing(thingName=emptied)+ _create_thing(iot_client, emptied)+ iot_client.add_thing_to_thing_group(thingGroupName=other, thingName=emptied)+ iot_client.remove_thing_from_thing_group(thingGroupName=other, thingName=emptied)+ iot_client.remove_thing_from_thing_group(thingGroupName=group, thingName=emptied)+ assert _executions_for(iot_client, emptied, job_id) == []+ finally:+ _cleanup(+ iot_client, jobs=[job_id], things=[emptied, kept], groups=[group, other]+ )+++def test_iot_jobs_deleted_continuous_executions_survive_persistence():+ """A thing whose CONTINUOUS executions were all deleted gets none back after a restore."""+ import asyncio++ from ministack.core.responses import request_scope+ from ministack.services import iot as iot_module++ iot_module.reset()+ try:+ with request_scope("123456789012", "us-east-1"):+ iot_module._things["t1"] = {"thingName": "t1"}+ iot_module._jobs["j1"] = {+ "jobId": "j1", "targets": [iot_module._thing_arn("t1")],+ "targetSelection": "CONTINUOUS", "status": "IN_PROGRESS",+ "document": "{}",+ }+ assert [e["jobId"] for e in iot_module.jobs_pending_for_thing("t1")] == [+ "j1"+ ]+ status, _, _ = asyncio.run(+ iot_module._delete_job_execution("t1", "j1", "1", {})+ )+ assert status == 200+ state = iot_module.get_state()+ iot_module.reset()+ iot_module.load_persisted_state(state)+ assert iot_module.jobs_pending_for_thing("t1") == []+ assert ("t1", "j1") not in iot_module._job_executions+ finally:+ iot_module.reset()++# ---------------------------------------------------------------------------# UpdateJob# ---------------------------------------------------------------------------@@ -2198,6 +2402,133 @@ def test_iot_jobs_list_executions_for_thing_filters(iot_client, iot_jobs_data):_cleanup(iot_client, jobs=[queued_job, done_job], things=[thing])+def test_iot_jobs_list_executions_for_job(iot_client, iot_jobs_data):+ """Newest update first, narrowed by status, paged with no token after the last page."""+ queued, running, done, failed = (_unique("jobs-thing") for _ in range(4))+ job_id = _unique("job")+ try:+ arns = {t: _create_thing(iot_client, t) for t in (queued, running, done, failed)}+ iot_client.create_job(jobId=job_id, targets=list(arns.values()), document=_DOCUMENT)+ for thing, status in ((failed, "FAILED"), (done, "SUCCEEDED"), (running, "IN_PROGRESS")):+ time.sleep(0.01)+ _drive(iot_jobs_data, thing, job_id, status)++ listed = iot_client.list_job_executions_for_job(jobId=job_id)+ assert "nextToken" not in listed+ entries = listed["executionSummaries"]+ newest_first = [arns[t] for t in (running, done, failed, queued)]+ assert [e["thingArn"] for e in entries] == newest_first+ assert set(entries[0]) == {"thingArn", "jobExecutionSummary"}+ summary = entries[0]["jobExecutionSummary"]+ assert set(summary) == {+ "status", "queuedAt", "startedAt", "lastUpdatedAt", "executionNumber",+ "retryAttempt",+ }+ assert (summary["status"], summary["executionNumber"], summary["retryAttempt"]) == (+ "IN_PROGRESS", 1, 0,+ )+ assert isinstance(summary["lastUpdatedAt"], datetime)+ assert "startedAt" not in entries[3]["jobExecutionSummary"]++ def arns_of(**kwargs):+ page = iot_client.list_job_executions_for_job(jobId=job_id, **kwargs)+ return [e["thingArn"] for e in page["executionSummaries"]], page.get("nextToken")++ assert arns_of(status="SUCCEEDED") == ([arns[done]], None)+ assert arns_of(status="CANCELED") == ([], None)+ first, token = arns_of(maxResults=3)+ assert first == newest_first[:3] and token+ assert arns_of(maxResults=3, nextToken=token) == (newest_first[3:], None)+ assert arns_of(maxResults=4) == (newest_first, None)+ assert arns_of(maxResults=1, status="QUEUED") == ([arns[queued]], None)+ finally:+ _cleanup(iot_client, jobs=[job_id], things=[queued, running, done, failed])+++def test_iot_jobs_list_executions_for_job_includes_earlier_executions(+ iot_client, iot_jobs_data+):+ """A thing that rejoined a CONTINUOUS job's group is listed once per execution."""+ group = _unique("jobs-group")+ thing = _unique("jobs-thing")+ job_id = _unique("job-cont")+ try:+ group_arn = iot_client.create_thing_group(thingGroupName=group)[+ "thingGroupArn"+ ]+ iot_client.create_job(+ jobId=job_id, targets=[group_arn], document=_DOCUMENT,+ targetSelection="CONTINUOUS",+ )+ thing_arn = _create_thing(iot_client, thing)+ iot_client.add_thing_to_thing_group(thingGroupName=group, thingName=thing)+ _drive(iot_jobs_data, thing, job_id, "SUCCEEDED")+ iot_client.remove_thing_from_thing_group(thingGroupName=group, thingName=thing)+ iot_client.add_thing_to_thing_group(thingGroupName=group, thingName=thing)++ entries = iot_client.list_job_executions_for_job(jobId=job_id)[+ "executionSummaries"+ ]+ assert [+ (+ e["thingArn"],+ e["jobExecutionSummary"]["executionNumber"],+ e["jobExecutionSummary"]["status"],+ )+ for e in entries+ ] == [(thing_arn, 2, "QUEUED"), (thing_arn, 1, "SUCCEEDED")]+ finally:+ _cleanup(iot_client, jobs=[job_id], things=[thing], groups=[group])+++def test_iot_jobs_list_executions_for_job_refusals(iot_client):+ """An unknown job and a bad job id, status, maxResults or nextToken are refused."""+ thing = _unique("jobs-thing")+ job_id = _unique("job")+ invalid = "1 validation error detected: Value '{}' at '{}' failed to satisfy constraint: "+ try:+ thing_arn = _create_thing(iot_client, thing)+ iot_client.create_job(jobId=job_id, targets=[thing_arn], document=_DOCUMENT)+ cases = {+ "/jobs/no-such-job/things": (+ 404, "ResourceNotFoundException", "Job no-such-job cannot be found.",+ ),+ f"/jobs/{job_id}/things?status=queued": (+ 400, "InvalidRequestException",+ invalid.format("queued", "status") + "Member must satisfy enum value set: "+ "[REMOVED, SUCCEEDED, TIMED_OUT, IN_PROGRESS, QUEUED, CANCELED, FAILED, REJECTED]",+ ),+ f"/jobs/{job_id}/things?maxResults=0": (+ 400, "InvalidRequestException",+ invalid.format("0", "maxResults")+ + "Member must have value greater than or equal to 1",+ ),+ "/jobs/no-such-job/things?maxResults=0": (+ 400, "InvalidRequestException",+ invalid.format("0", "maxResults")+ + "Member must have value greater than or equal to 1",+ ),+ f"/jobs/{job_id}/things?maxResults=251": (+ 400, "InvalidRequestException",+ invalid.format("251", "maxResults")+ + "Member must have value less than or equal to 250",+ ),+ f"/jobs/{job_id}/things?nextToken=bogus": (+ 400, "InvalidRequestException", "Next token is invalid.",+ ),+ "/jobs/a%20b/things": (+ 400, "InvalidRequestException",+ invalid.format("a b", "jobId")+ + "Member must satisfy regular expression pattern: [a-zA-Z0-9_-]+",+ ),+ }+ for path, expected in cases.items():+ status, body = _raw(_IOT_AUTH, "GET", path)+ assert (status, body.get("__type"), body.get("message")) == expected, path+ finally:+ _cleanup(iot_client, jobs=[job_id], things=[thing])++# ---------------------------------------------------------------------------# Account / region isolation# ---------------------------------------------------------------------------@@ -2607,6 +2938,43 @@ def test_jobs_mqtt_rejoining_continuous_job_group_notifies(_cleanup(iot_client, jobs=[job_id], things=[thing], groups=[group])+def test_jobs_mqtt_deleting_a_pending_execution_notifies(+ iot_client, iot_data_client, iot_jobs_data+):+ """Deleting a QUEUED execution publishes notify and notify-next; a finished one neither."""+ thing = _unique("jobs-mqtt-del")+ done_job, job_id = _unique("job-done"), _unique("job")+ base = f"$aws/things/{thing}/jobs"+ try:+ thing_arn = _create_thing(iot_client, thing)+ iot_client.create_job(jobId=done_job, targets=[thing_arn], document=_DOCUMENT)+ _drive(iot_jobs_data, thing, done_job, "SUCCEEDED")+ iot_client.create_job(jobId=job_id, targets=[thing_arn], document=_DOCUMENT)++ received = _collect_shadow_frames(+ f"{base}/#",+ lambda: iot_client.delete_job_execution(+ jobId=job_id, thingName=thing, executionNumber=1+ ),+ want=2,+ )+ frames = _frames_by_topic(received)+ assert frames[f"{base}/notify"]["jobs"] == {}+ assert set(frames[f"{base}/notify-next"]) == {"timestamp"}++ received = _collect_shadow_frames(+ f"{base}/#",+ lambda: iot_client.delete_job_execution(+ jobId=done_job, thingName=thing, executionNumber=1+ ),+ want=1,+ timeout=2.0,+ )+ assert received == []+ finally:+ _cleanup(iot_client, jobs=[done_job, job_id], things=[thing])++def test_jobs_mqtt_version_mismatch_rejected(iot_client, iot_data_client):"""A stale expectedVersion answers update/rejected with the stringVersionMismatch code, the captured message wording, and the execution's