Skip to content

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

fix(iot): align job execution versions, details, numbers and timeouts (#2257)

iot-rocket2561b41d063a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index adaf7d8a..3e0e3667 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,9 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
### Fixed
+- **IoT — job execution versions, `statusDetails`, execution numbers and timeouts** — `UpdateJobExecution` answered a stale `expectedVersion` with 409 `InvalidStateTransitionException` and now answers 400 `InvalidRequestException` (`VersionMismatch` over MQTT, as before); an execution has no `statusDetails` until a device reports some, and a reported empty map replaces the previous one; the MQTT `get` and `update` topics answer `ResourceNotFound` for an `executionNumber` other than the execution's; and `DescribeJobExecution`, `ListJobExecutionsForJob`, `ListJobExecutionsForThing` and `DescribeJob` time out an expired `IN_PROGRESS` execution as the device reads do. Contributed by @iot-rocket.
+- **IoT — Jobs MQTT messages are written as AWS writes them** — the `$aws/things/<thing>/jobs` messages were spaced, ASCII-escaped JSON with `clientToken` last, a `thingName` and an empty `statusDetails` in the `get` and `start-next` executions and no `jobDocument` in an execution whose document is `null`; they are now compact UTF-8 in AWS's member order with `clientToken` first, the job document as the HTTP plane sends it, characters outside the BMP escaped in `statusDetails` and in the update and rejected responses, and `"jobDocument":null` kept. Contributed by @iot-rocket.
+- **IoT Jobs — a status a device may not set is refused first** — `UpdateJobExecution` (HTTP and the MQTT `update` topic) to QUEUED, CANCELED or TIMED_OUT answered `ResourceNotFoundException` for an unknown job or thing and the version error for a stale `expectedVersion`; it now refuses the status first with `InvalidStateTransitionException` (over MQTT `InvalidStateTransition` without `executionState`), as AWS does. Contributed by @iot-rocket.
- **IoT — Jobs MQTT messages are written as AWS writes them** — the `$aws/things/<thing>/jobs` messages were spaced, ASCII-escaped JSON with `clientToken` last, a `thingName` and an empty `statusDetails` in the `get` and `start-next` executions and no `jobDocument` in an execution whose document is `null`; they are now compact UTF-8 in AWS's member order with `clientToken` first, the job document as the HTTP plane sends it, characters outside the BMP escaped in `statusDetails` and in the update and rejected responses, and `"jobDocument":null` kept. Contributed by @iot-rocket.
- **IoT Jobs — a status a device may not set is refused first** — `UpdateJobExecution` (HTTP and the MQTT `update` topic) to QUEUED, CANCELED or TIMED_OUT answered `ResourceNotFoundException` for an unknown job or thing and the version error for a stale `expectedVersion`; it now refuses the status first with `InvalidStateTransitionException` (over MQTT `InvalidStateTransition` without `executionState`), as AWS does. Contributed by @iot-rocket.
- **IoT Jobs — a status a device may not set is refused first** — `UpdateJobExecution` (HTTP and the MQTT `update` topic) to QUEUED, CANCELED or TIMED_OUT answered `ResourceNotFoundException` for an unknown job or thing and the version error for a stale `expectedVersion`; it now refuses the status first with `InvalidStateTransitionException` (over MQTT `InvalidStateTransition` without `executionState`), as AWS does. Contributed by @iot-rocket.
diff --git a/README.md b/README.md
index 33ee58bb..9bc933b8 100644
--- a/README.md
+++ b/README.md
@@ -654,7 +654,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, 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 read from MiniStack's S3**: a job or job template created with an `s3://` or S3 object URL keeps the object's content as its document, read once at creation; a missing bucket or object, a non-JSON object or one over 32 KB is refused, and so is a URL whose host is not S3. **Presigned URLs**: a `${aws:iot:s3-presigned-url:<url>}` or `-v2` placeholder needs `presignedUrlConfig.roleArn`, and what devices receive (HTTP and MQTT) carries a SigV4 presigned GET URL of MiniStack's S3 instead, signed with a session of that role. The URL is path style on the host the device used, and an IoT endpoint host drops everything up to and including its region label. **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 message that carries the current version — a 409 `VersionConflictException` on the control plane and a 400 `InvalidRequestException` 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 read from MiniStack's S3**: a job or job template created with an `s3://` or S3 object URL keeps the object's content as its document, read once at creation; a missing bucket or object, a non-JSON object or one over 32 KB is refused, and so is a URL whose host is not S3. **Presigned URLs**: a `${aws:iot:s3-presigned-url:<url>}` or `-v2` placeholder needs `presignedUrlConfig.roleArn`, and what devices receive (HTTP and MQTT) carries a SigV4 presigned GET URL of MiniStack's S3 instead, signed with a session of that role. The URL is path style on the host the device used, and an IoT endpoint host drops everything up to and including its region label. **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` is 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, CreateProvisioningTemplateVersion, ListProvisioningTemplateVersions, DescribeProvisioningTemplateVersion, DeleteProvisioningTemplateVersion, CreateProvisioningClaim, AttachThingPrincipal, DetachThingPrincipal, ListThingPrincipals, ListPrincipalThings, CreatePolicy, CreatePolicyVersion, SetDefaultPolicyVersion, AttachPolicy, DetachPolicy, ListAttachedPolicies, ListTargetsForPolicy, AttachPrincipalPolicy, DetachPrincipalPolicy, ListPrincipalPolicies, ListPolicyPrincipals, CreateTopicRule, GetTopicRule, ReplaceTopicRule, DeleteTopicRule, ListTopicRules, EnableTopicRule, DisableTopicRule, UpdateIndexingConfiguration, GetIndexingConfiguration, DescribeIndex, ListIndices, SearchIndex, DescribeEndpoint, Publish (HTTP), GetRetainedMessage, ListRetainedMessages, MQTT-over-WebSocket pub/sub, DescribeEventConfigurations, UpdateEventConfigurations, CreateDomainConfiguration, DescribeDomainConfiguration, ListDomainConfigurations, UpdateDomainConfiguration, DeleteDomainConfiguration, TagResource, UntagResource, ListTagsForResource | 76 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 or be an unexpired provisioning claim, which then serves the session; unknown, inactive or doubly-registered certificates get a "not authorized" CONNACK, or with `AUTH=true` a close without one as on AWS (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, except on mTLS MQTT connections with `AUTH=true`; **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()`, `principal()`, `traceid()`, `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) with **fleet provisioning by claim**: `CreateProvisioningClaim`, then `CreateKeysAndCertificate` and `RegisterThing` over MQTT on the JSON topics (`$aws/certificates/create/json`, `$aws/provisioning-templates/<name>/provision/json`), answered on the requesting connection, and with `AUTH=true` a claim connection may use only the certificate topics and its own template's `provision` topics; `provisioningRoleArn` is presence-checked but not resolved and the pre-provisioning hook Lambda is invoked before the template is applied; 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.py
index 02cad4ad..5b2cf492 100644
--- a/ministack/services/iot.py
+++ b/ministack/services/iot.py
@@ -6077,7 +6077,7 @@ def _list_tags_for_resource(qp: dict) -> tuple:
# QUEUED → IN_PROGRESS → {SUCCEEDED, FAILED, REJECTED, CANCELED}
#
# `versionNumber` gives optimistic concurrency: every transition bumps it, and
-# a stale `expectedVersion` is rejected with a 409. `executionNumber` is NOT a
+# a stale `expectedVersion` is rejected. `executionNumber` is NOT a
# concurrency token here. It counts a thing's executions of one job: 1 for the
# first, one more each time the thing joins a CONTINUOUS job's target group
# again after its last execution finished (AWS also increments it when a job
@@ -6235,7 +6235,6 @@ def _jobs_queue_execution(thing: str, job_id: str, now: int) -> None:
"jobId": job_id,
"thingName": thing,
"status": "QUEUED",
- "statusDetails": {},
"queuedAt": now,
"startedAt": None,
"lastUpdatedAt": now,
@@ -6620,16 +6619,16 @@ def _jobs_abort(job_id: str) -> dict:
def _jobs_check_expected_version(
- execution: dict, expected, conflict_code: str
+ execution: dict, expected, conflict_code: str, status: int = 409
) -> tuple | None:
"""Optimistic-concurrency gate, shared by the two update paths.
The rejection message carries the current version so a device can resync
- without a separate describe. `conflict_code` differs by plane and is NOT
- cosmetic: the `iot` model declares VersionConflictException for
- CancelJobExecution, while the `iot-jobs-data` model declares only
- InvalidStateTransitionException for UpdateJobExecution — returning the
- unmodeled code there makes a device's
+ without a separate describe. `conflict_code` and `status` differ by plane
+ and are NOT cosmetic: the `iot` model declares VersionConflictException
+ for CancelJobExecution, while UpdateJobExecution in the `iot-jobs-data`
+ model answers 400 InvalidRequestException — returning the unmodeled code
+ there makes a device's
`except client.exceptions.VersionConflictException` raise AttributeError
instead of catching, because botocore only synthesizes exception classes
for the errors its model lists.
@@ -6647,7 +6646,7 @@ def _jobs_check_expected_version(
conflict_code,
f"Expected version {expected} but found version "
f"{execution['versionNumber']}",
- 409,
+ status,
)
return None
@@ -7228,6 +7227,9 @@ def _describe_job(job_id: str) -> tuple:
if job is None:
return _error_not_found("Job", job_id)
_jobs_materialize_executions(job_id)
+ for latest in _job_executions.values():
+ if latest["jobId"] == job_id:
+ _jobs_apply_timeout(latest)
# Every execution counts, a rejoined thing's earlier ones included
# (measured eu-central-1 2026-10-05).
counts = _jobs_status_counts(job_id)
@@ -7762,7 +7764,7 @@ def _list_job_executions_for_thing(thing: str, qp: dict) -> tuple:
executions = [
execution
for latest in _job_executions.values()
- for execution in _jobs_with_history(latest)
+ for execution in _jobs_with_history(_jobs_apply_timeout(latest))
]
for execution in executions:
if execution["thingName"] != thing:
@@ -7819,7 +7821,7 @@ def _list_job_executions_for_job(job_id: str, qp: dict) -> tuple:
execution
for latest in _job_executions.values()
if latest["jobId"] == job_id
- for execution in _jobs_with_history(latest)
+ for execution in _jobs_with_history(_jobs_apply_timeout(latest))
if status is None or execution["status"] == status
]
executions.sort(key=lambda e: e["lastUpdatedAt"], reverse=True)
@@ -7839,6 +7841,8 @@ 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)
execution = _job_executions.get((thing, job_id))
+ if execution is not None:
+ _jobs_apply_timeout(execution)
number = qp.get("executionNumber")
if execution is not None and number is not None:
try:
@@ -7858,7 +7862,9 @@ def _describe_job_execution(thing: str, job_id: str, qp: dict) -> tuple:
"status": execution["status"],
# Control-plane JobExecution nests the map under `detailsMap`
# (JobExecutionStatusDetails); the data plane returns it flat.
- "statusDetails": {"detailsMap": execution.get("statusDetails") or {}},
+ "statusDetails": (
+ {"detailsMap": execution["statusDetails"]} if execution.get("statusDetails") is not None else {}
+ ),
"thingArn": _thing_arn(thing),
"queuedAt": _jobs_ms_to_s(execution["queuedAt"]),
"lastUpdatedAt": _jobs_ms_to_s(execution["lastUpdatedAt"]),
@@ -8262,12 +8268,9 @@ _JOBS_MQTT_EXECUTION_MEMBERS = (
def _jobs_mqtt_execution(execution: dict, document) -> dict:
- """A JobExecution as Jobs MQTT messages carry it: AWS's member order, no thingName, no empty statusDetails."""
+ """A JobExecution as Jobs MQTT messages carry it: AWS's member order, no thingName."""
view = jobs_execution_view(execution, document)
- return {
- key: view[key] for key in _JOBS_MQTT_EXECUTION_MEMBERS
- if key in view and (key != "statusDetails" or view[key])
- }
+ return {key: view[key] for key in _JOBS_MQTT_EXECUTION_MEMBERS if key in view}
def _jobs_mqtt_head(client_token, timestamp: int) -> dict:
@@ -8277,10 +8280,10 @@ def _jobs_mqtt_head(client_token, timestamp: int) -> dict:
return head
-def _jobs_execution_state(execution: dict) -> dict:
- """The executionState of a Jobs MQTT response: statusDetails only when set."""
+def jobs_execution_state(execution: dict) -> dict:
+ """The executionState of an update or a Jobs MQTT rejection: statusDetails only when set."""
state = {"status": execution["status"]}
- if execution.get("statusDetails"):
+ if execution.get("statusDetails") is not None:
state["statusDetails"] = execution["statusDetails"]
state["versionNumber"] = execution["versionNumber"]
return state
@@ -8309,14 +8312,15 @@ def jobs_update_execution(
expected_version=None,
status_details: dict | None = None,
step_timeout_minutes=None,
+ execution_number=None,
) -> tuple:
"""Apply a device-reported status to an execution.
Returns ``(execution copy, None)``, or ``(None, error)`` for every
rejection, in this order: an unknown status or one a device may not set
- (QUEUED and the service-side statuses), unknown execution (404), stale or
- non-numeric `expectedVersion`, and an already-terminal execution. A
- successful update may complete the job.
+ (QUEUED and the service-side statuses), unknown execution or
+ `execution_number` (404), stale or non-numeric `expectedVersion`, and an
+ already-terminal execution. A successful update may complete the job.
"""
if not status or status not in _JOB_EXECUTION_STATUSES:
return None, error_response_json(
@@ -8334,6 +8338,8 @@ def jobs_update_execution(
)
_jobs_materialize_executions(job_id)
execution = _job_executions.get((thing_name, job_id))
+ if execution_number is not None and execution and execution_number != execution["executionNumber"]:
+ execution = None
if execution is None:
return None, error_response_json(
"ResourceNotFoundException",
@@ -8341,7 +8347,7 @@ def jobs_update_execution(
404,
)
error = _jobs_check_expected_version(
- execution, expected_version, "InvalidStateTransitionException"
+ execution, expected_version, "InvalidRequestException", 400
)
if error:
return None, error
@@ -8353,7 +8359,7 @@ def jobs_update_execution(
return None, error
now = _jobs_now_ms()
execution["status"] = status
- if status_details:
+ if status_details is not None:
execution["statusDetails"] = dict(status_details)
# The first report starts the execution, unless the device rejects the job.
if status != "REJECTED" and execution.get("startedAt") is None:
@@ -8390,12 +8396,13 @@ def jobs_execution_view(execution: dict, document: str | dict | None) -> dict:
"jobId": execution["jobId"],
"thingName": execution["thingName"],
"status": execution["status"],
- "statusDetails": execution.get("statusDetails") or {},
"queuedAt": _jobs_ms_to_long_s(execution["queuedAt"]),
"lastUpdatedAt": _jobs_ms_to_long_s(execution["lastUpdatedAt"]),
"executionNumber": execution["executionNumber"],
"versionNumber": execution["versionNumber"],
}
+ if execution.get("statusDetails") is not None:
+ view["statusDetails"] = dict(execution["statusDetails"])
if execution.get("startedAt") is not None:
view["startedAt"] = _jobs_ms_to_long_s(execution["startedAt"])
remaining = _jobs_seconds_before_timeout(execution)
@@ -9545,9 +9552,10 @@ def _jobs_error_tuple_to_rejected(
"""Map a jobs_* seam error (a ready HTTP response tuple) onto the MQTT
rejected document.
- The HTTP status folds onto the string ErrorCode enum; the three 409s all
- share one HTTP ``__type`` (InvalidStateTransitionException), so the
- specific code is read off the message sentence — every candidate
+ The HTTP status folds onto the string ErrorCode enum; the 409s share one
+ HTTP ``__type`` (InvalidStateTransitionException) and the version mismatch
+ shares the 400 with a bad request, so the specific code is read off the
+ message sentence — every candidate
sentence is authored in this module (_jobs_check_expected_version,
_jobs_reject_if_terminal, jobs_update_execution), so the match cannot
drift silently. ``execution`` is the execution's current state, when it
@@ -9561,7 +9569,7 @@ def _jobs_error_tuple_to_rejected(
message = ""
if status == 404:
code = "ResourceNotFound"
- elif status == 400:
+ elif status == 400 and not message.startswith("Expected version"):
code = "InvalidRequest"
elif status == 410:
code = "TerminalStateReached"
@@ -9573,7 +9581,7 @@ def _jobs_error_tuple_to_rejected(
# A refused status carries no executionState.
refused_status = message.startswith("The status of job execution cannot be changed")
if code in ("VersionMismatch", "InvalidStateTransition") and execution is not None and not refused_status:
- execution_state = _jobs_execution_state(execution)
+ execution_state = jobs_execution_state(execution)
return _jobs_rejected(code, message, client_token, execution_state)
@@ -9590,12 +9598,10 @@ async def _handle_jobs_publish(
``accepted`` / ``rejected`` responses back through the broker.
Payload members (`statusDetails`, `expectedVersion`,
- `includeJobExecutionState`, `includeJobDocument`, `clientToken`) follow
- the device SDK contract and mirror the HTTP plane's handling; the request
- members `stepTimeoutInMinutes` and `executionNumber` are accepted but
- ignored — MiniStack has no execution timeouts, and `executionNumber` is
- write-once so there is never more than one execution to address. Every
- ``timestamp`` and execution stamp is epoch seconds; ``jobDocument`` is
+ `includeJobExecutionState`, `includeJobDocument`, `clientToken`,
+ `executionNumber`) follow the device SDK contract and mirror the HTTP
+ plane's handling; the request member `stepTimeoutInMinutes` is accepted
+ but ignored. Every ``timestamp`` and execution stamp is epoch seconds; ``jobDocument`` is
served as a JSON object here (over HTTP it stays a string, as on AWS)."""
base = f"{SHADOW_TOPIC_PREFIX}{thing}/jobs"
suffix_base = f"{job_id}/{verb}" if job_id is not None else verb
@@ -9670,6 +9676,9 @@ async def _handle_jobs_publish(
execution = jobs_start_next_execution(thing, peek=True)
else:
execution = jobs_describe_execution(thing, job_id)
+ number = request.get("executionNumber")
+ if number is not None and execution and number != execution["executionNumber"]:
+ execution = None
include_document = request.get("includeJobDocument", True)
document = (
_jobs_job_document_object(execution["jobId"])
@@ -9705,6 +9714,7 @@ async def _handle_jobs_publish(
status=request.get("status"),
expected_version=request.get("expectedVersion"),
status_details=request.get("statusDetails"),
+ execution_number=request.get("executionNumber"),
)
current = jobs_describe_execution(thing, job_id) if error else None
if error:
@@ -9714,7 +9724,7 @@ async def _handle_jobs_publish(
return
doc = _jobs_mqtt_head(client_token, ts)
if request.get("includeJobExecutionState"):
- doc["executionState"] = _jobs_execution_state(execution)
+ doc["executionState"] = jobs_execution_state(execution)
if request.get("includeJobDocument"):
with request_scope(account_id, region):
doc["jobDocument"] = _jobs_job_document_object(job_id, escape_non_bmp=True)
diff --git a/ministack/services/iot_jobs_data.py b/ministack/services/iot_jobs_data.py
index 992ff8f2..79984261 100644
--- a/ministack/services/iot_jobs_data.py
+++ b/ministack/services/iot_jobs_data.py
@@ -243,11 +243,7 @@ async def _update_execution(thing: str, job_id: str, payload: dict) -> tuple:
response: dict = {}
if str(payload.get("includeJobExecutionState", "")).lower() in ("true", "1"):
- response["executionState"] = {
- "status": execution["status"],
- "statusDetails": execution.get("statusDetails") or {},
- "versionNumber": execution["versionNumber"],
- }
+ response["executionState"] = _iot_module.jobs_execution_state(execution)
if str(payload.get("includeJobDocument", "")).lower() in ("true", "1"):
response["jobDocument"] = _iot_module.jobs_job_document(job_id)
if execution["status"] in ("SUCCEEDED", "FAILED", "REJECTED"):
diff --git a/tests/test_iot.py b/tests/test_iot.py
index 49c95e70..2db668f2 100644
--- a/tests/test_iot.py
+++ b/tests/test_iot.py
@@ -7934,6 +7934,42 @@ def test_iot_jobs_in_progress_timeout_reaches_timed_out():
reset()
+def test_iot_jobs_in_progress_timeout_reaches_control_plane_reads():
+ """DescribeJobExecution, both execution lists and DescribeJob each report the timed-out execution."""
+ from ministack.core.responses import request_scope
+ from ministack.services import iot as iot_module
+
+ def read_after_the_timeout(read):
+ reset()
+ with request_scope("123456789012", _TEST_REGION):
+ started = iot_module._jobs_now_ms() - 61_000
+ iot_module._jobs["j1"] = {
+ "jobId": "j1", "jobArn": iot_module._job_arn("j1"), "targets": [],
+ "targetSelection": "SNAPSHOT", "status": "IN_PROGRESS", "document": "{}",
+ "snapshotted": True, "createdAt": started, "lastUpdatedAt": started,
+ "timeoutConfig": {"inProgressTimeoutInMinutes": 1},
+ }
+ iot_module._job_executions[("t1", "j1")] = {
+ "jobId": "j1", "thingName": "t1", "status": "IN_PROGRESS",
+ "queuedAt": started, "startedAt": started, "lastUpdatedAt": started,
+ "executionNumber": 1, "versionNumber": 2,
+ }
+ status, _, body = read()
+ assert status == 200
+ return json.loads(body)
+
+ execution = read_after_the_timeout(
+ lambda: iot_module._describe_job_execution("t1", "j1", {}))["execution"]
+ assert (execution["status"], execution["versionNumber"]) == ("TIMED_OUT", 3)
+ for read in (lambda: iot_module._list_job_executions_for_job("j1", {}),
+ lambda: iot_module._list_job_executions_for_thing("t1", {})):
+ (summary,) = read_after_the_timeout(read)["executionSummaries"]
+ assert summary["jobExecutionSummary"]["status"] == "TIMED_OUT"
+ details = read_after_the_timeout(lambda: iot_module._describe_job("j1"))["job"]["jobProcessDetails"]
+ assert (details["numberOfTimedOutThings"], details["numberOfInProgressThings"]) == (1, 0)
+ reset()
+
+
def test_rule_error_action_runs_when_an_action_fails(monkeypatch):
"""AWS invokes the rule's errorAction when an action fails, with the failure
document — without it the only trace of a broken pipeline is a local log
diff --git a/tests/test_iot_jobs_data.py b/tests/test_iot_jobs_data.py
index 5435fd90..d753f4bc 100644
--- a/tests/test_iot_jobs_data.py
+++ b/tests/test_iot_jobs_data.py
@@ -1297,8 +1297,8 @@ def test_iot_jobs_start_next_update_and_auto_complete(iot_client, iot_jobs_data)
assert [e["jobId"] for e in pending["inProgressJobs"]] == [job_id]
assert pending["queuedJobs"] == []
- # A wrong expectedVersion is rejected with the code the iot-jobs-data
- # model declares for UpdateJobExecution — InvalidStateTransitionException,
+ # A wrong expectedVersion is rejected with a code the iot-jobs-data
+ # model declares for UpdateJobExecution — InvalidRequestException (400),
# NOT the VersionConflictException the control plane uses. botocore only
# synthesizes exception classes for modeled errors, so an unmodeled code
# would make the device's `except client.exceptions.…` raise
@@ -1306,16 +1306,16 @@ def test_iot_jobs_start_next_update_and_auto_complete(iot_client, iot_jobs_data)
# version so the device can resync without a separate describe.
assert not hasattr(iot_jobs_data.exceptions, "VersionConflictException")
with pytest.raises(
- iot_jobs_data.exceptions.InvalidStateTransitionException
+ iot_jobs_data.exceptions.InvalidRequestException
) as ei:
iot_jobs_data.update_job_execution(
jobId=job_id, thingName=thing, status="SUCCEEDED",
expectedVersion=1,
)
error = ei.value.response["Error"]
- assert error["Code"] == "InvalidStateTransitionException"
- assert ei.value.response["ResponseMetadata"]["HTTPStatusCode"] == 409
- assert "found version 2" in error["Message"]
+ assert error["Code"] == "InvalidRequestException"
+ assert ei.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
+ assert error["Message"] == "Expected version 1 but found version 2"
updated = iot_jobs_data.update_job_execution(
jobId=job_id,
@@ -3396,6 +3396,40 @@ def test_iot_jobs_recreated_thing_starts_with_no_execution_history(
# ---------------------------------------------------------------------------
+def test_iot_jobs_status_details_are_left_out_until_a_device_reports_them(
+ iot_client, iot_jobs_data
+):
+ """No statusDetails member until a device reports some; a reported empty map replaces the old one."""
+ thing = _unique("jobs-thing")
+ job_id = _unique("job")
+ try:
+ thing_arn = _create_thing(iot_client, thing)
+ iot_client.create_job(jobId=job_id, targets=[thing_arn], document=_DOCUMENT)
+
+ def update(**kwargs):
+ return iot_jobs_data.update_job_execution(
+ jobId=job_id, thingName=thing, status="IN_PROGRESS",
+ includeJobExecutionState=True, **kwargs,
+ )["executionState"]
+
+ def device():
+ return iot_jobs_data.describe_job_execution(jobId=job_id, thingName=thing)["execution"]
+
+ def control():
+ return iot_client.describe_job_execution(jobId=job_id, thingName=thing)["execution"]
+
+ assert "statusDetails" not in device()
+ assert update() == {"status": "IN_PROGRESS", "versionNumber": 2}
+ assert "statusDetails" not in device()
+ assert control()["statusDetails"] == {}
+ assert update(statusDetails={"step": "1"})["statusDetails"] == {"step": "1"}
+ assert update()["statusDetails"] == {"step": "1"}
+ assert update(statusDetails={}) == {"status": "IN_PROGRESS", "statusDetails": {}, "versionNumber": 5}
+ assert device()["statusDetails"] == {}
+ finally:
+ _cleanup(iot_client, jobs=[job_id], things=[thing])
+
+
def test_iot_jobs_status_details_are_nested_on_the_control_plane_only(
iot_client, iot_jobs_data
):
@@ -4469,6 +4503,36 @@ def test_jobs_mqtt_next_sentinel_get(iot_client, iot_data_client):
assert doc["inProgressJobs"] == []
+def test_jobs_mqtt_unknown_execution_number_rejected(iot_client, iot_data_client):
+ """get and update with another executionNumber than the execution's answer ResourceNotFound."""
+ thing = _unique("jobs-mqtt-num")
+ job_id = _unique("job")
+ thing_arn = _create_thing(iot_client, thing)
+ iot_client.create_job(jobId=job_id, targets=[thing_arn], document=_DOCUMENT)
+ base = f"$aws/things/{thing}/jobs"
+
+ def answer(verb, request):
+ received = _collect_shadow_frames(
+ f"{base}/{job_id}/{verb}/+",
+ lambda: _mqtt_publish(topic=f"{base}/{job_id}/{verb}", payload=json.dumps(request).encode()),
+ want=1,
+ )
+ ((topic, payload),) = received
+ return topic.rsplit("/", 1)[1], json.loads(payload)
+
+ kind, doc = answer("get", {"executionNumber": 9, "clientToken": "n1"})
+ assert (kind, doc["code"], doc["clientToken"]) == ("rejected", "ResourceNotFound", "n1")
+ kind, doc = answer("update", {"status": "IN_PROGRESS", "executionNumber": 9})
+ assert (kind, doc["code"]) == ("rejected", "ResourceNotFound")
+ execution = iot_client.describe_job_execution(jobId=job_id, thingName=thing)["execution"]
+ assert (execution["status"], execution["versionNumber"]) == ("QUEUED", 1)
+
+ kind, doc = answer("get", {"executionNumber": 1})
+ assert (kind, doc["execution"]["executionNumber"]) == ("accepted", 1)
+ kind, _ = answer("update", {"status": "IN_PROGRESS", "executionNumber": 1})
+ assert kind == "accepted"
+
+
def test_jobs_mqtt_job_document_leaves_out_null_members(iot_client, iot_data_client):
"""The jobDocument object over MQTT is the device's document: no null members, Infinity as a string."""
thing = _unique("jobs-mqtt-doc")