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-jobs-data): AWS IoT Jobs control and data plane (#1400)
iot-rocket12928d11c18e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex da94a05a..f7324e55 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,8 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]+### Added+- **AWS IoT Jobs — control plane and device data plane** — `CreateJob` fell through to `Unsupported IoT path` and the `iot-jobs-data` endpoint did not exist, so device OTA loops could not be rehearsed locally. The `iot` service now serves the nine job operations and a new `iot-jobs-data` service the four device ones (incl. the `$next` sentinel), sharing one store and the AWS execution state machine. A `documentSource` job gets a placeholder, not the S3 object. Contributed by @iot-rocket.### Fixed- **EC2 — instance public IP and DNS reach the SDKs, and generated addresses are addresses** — `DescribeInstances` and `RunInstances` emitted the public address under `publicIpAddress` / `publicDnsName`, which are not the tags the EC2 wire schema defines (`ipAddress` / `dnsName`, per botocore's `ec2-2016-11-15` model), so every SDK dropped both fields silently and `PublicIpAddress` came back absent on instances that had one. They now ride the real tags. Fixing that exposed a second one: `_random_ip` appended two octets whatever it was given, so a one-octet prefix produced `52.55.218` — `AllocateAddress` has been handing back that shape as `PublicIp` all along, and no address parser accepts it. The generator now completes any prefix to four octets. Contributed by @iot-rocket.- **S3 — `CRC64NVME` checksums are computed instead of refused** — CRC-64/NVME is the algorithm current AWS SDKs and the CLI checksum uploads with by default, and MiniStack answered it with `InvalidRequest` ("requires optional native dependencies"), so a stock `aws s3 cp` or `aws s3api put-object` failed before it began unless the caller knew to set `AWS_REQUEST_CHECKSUM_CALCULATION=when_required`. The algorithm is plain arithmetic — the reflected form of polynomial `0xAD93D23594C93659` with all-ones init and xorout — so it is now computed from a byte-at-a-time table in the stdlib, adding no dependency: `PutObject` and `CopyObject` validate a client-supplied `x-amz-checksum-crc64nvme` (`BadDigest` on mismatch) and `GetObject` / `HeadObject` return it under `x-amz-checksum-mode: ENABLED`, typed `FULL_OBJECT`. The tests pin the implementation to the algorithm's published check value (`b"123456789"` → `0xAE8B14860A799888`) and to a bit-at-a-time reference rather than to itself. `CRC32C` still requires the native `google-crc32c` and is still refused.diff --git a/README.md b/README.mdindex ee88dbba..9952755e 100644--- a/README.md+++ b/README.md@@ -584,6 +584,7 @@ MiniStack expands AWS SAM transforms (`Transform: AWS::Serverless-2016-10-31`) i| **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; deployments complete immediately; session-based configuration retrieval with token rotation || **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 Core** | CreateThing, DescribeThing, ListThings, UpdateThing, DeleteThing, CreateThingType, CreateThingGroup, AddThingToThingGroup, ListThingsInThingGroup, CreateKeysAndCertificate, RegisterCertificate, RegisterCertificateWithoutCA, UpdateCertificate, DeleteCertificate, GetRegistrationCode, DeleteRegistrationCode, RegisterCACertificate, DescribeCACertificate, UpdateCACertificate, ListCACertificates, DeleteCACertificate, 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 | 46 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); 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}`; and `SearchIndex` answers `connectivity.connected` / `connectivity.timestamp` / `connectivity.disconnectReason` when `thingConnectivityIndexingMode` is `STATUS`, deriving `connected` from the live session registry |+| **IoT Jobs** | Control plane (`iot`): CreateJob, DescribeJob, ListJobs, GetJobDocument, CancelJob, DeleteJob, ListJobExecutionsForThing, DescribeJobExecution, CancelJobExecution; data plane (`iot-jobs-data`): GetPendingJobExecutions, StartNextPendingJobExecution, DescribeJobExecution (incl. the `$next` sentinel), UpdateJobExecution | 9 control-plane + 4 device data-plane operations sharing one store. Executions walk `QUEUED → IN_PROGRESS → {SUCCEEDED, FAILED, REJECTED, CANCELED}`; the remaining AWS terminal statuses (`TIMED_OUT`, `REMOVED`) are modeled and counted in `jobProcessDetails` but nothing sets them — there are no execution timeouts, and 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. **Timestamp units differ by plane, as on AWS**: control-plane responses use `timestamp` shapes (epoch seconds — boto3 parses them to datetimes) while `iot-jobs-data` responses carry raw epoch-**millisecond** `long`s. Job state persists with the IoT store when `PERSIST_STATE=1` || **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 || **EKS** | CreateCluster, DescribeCluster, ListClusters, DeleteCluster, CreateNodegroup, DescribeNodegroup, ListNodegroups, DeleteNodegroup, CreateAddon, DescribeAddon, ListAddons, UpdateAddon, DeleteAddon, AssociateEncryptionConfig, CreateAccessEntry, DescribeAccessEntry, ListAccessEntries, UpdateAccessEntry, DeleteAccessEntry, AssociateAccessPolicy, DisassociateAccessPolicy, ListAssociatedAccessPolicies, AssociateIdentityProviderConfig, DescribeIdentityProviderConfig, DisassociateIdentityProviderConfig, ListIdentityProviderConfigs, TagResource, UntagResource, ListTagsForResource | `CreateCluster` spawns a real **k3s** container (75 MB) with a full Kubernetes API server; `kubectl`, Helm, and any K8s tooling work out of the box; cascading delete removes nodegroups and k3s container; addon CRUD (e.g. `vpc-cni`, `coredns`, `kube-proxy`, `aws-ebs-csi-driver`) at `/clusters/{name}/addons` flips status to `ACTIVE` on create / update; `AssociateEncryptionConfig` at `/clusters/{name}/encryption-config/associate` records KMS encryption config (rejects re-association, AWS-shape `update` envelope); **Access Entries** (modern post-1.29 IAM bindings — replaces aws-auth ConfigMap) at `/clusters/{name}/access-entries[/{principalArn}[/access-policies[/{policyArn}]]]` for Crossplane / Terraform `aws_eks_access_entry` + `aws_eks_access_policy_association`; OIDC discovery + JWKS served at the cluster's `identity.oidc.issuer` URL so Terraform's `aws_iam_openid_connect_provider` (IRSA) works against ministack; **OIDC Identity Provider Config** (`AssociateIdentityProviderConfig` / `DescribeIdentityProviderConfig` / `DisassociateIdentityProviderConfig` / `ListIdentityProviderConfigs`) at `/clusters/{name}/identity-provider-configs[/{verb}]` — one OIDC IdP per cluster, issuer + clientId + claims forwarded to the k3s API server via `--kube-apiserver-arg=oidc-*` flags, tags reachable via `ListTagsForResource`; CFN `AWS::EKS::Cluster` and `AWS::EKS::Nodegroup` supported || **OpenSearch Service** | CreateDomain, DescribeDomain, DescribeDomains, DeleteDomain, ListDomainNames, UpdateDomainConfig, DescribeDomainConfig, DescribeDomainChangeProgress, ListVersions, GetCompatibleVersions, AddTags, ListTags, RemoveTags | Management plane on `/2021-01-01/*` (`boto3.client("opensearch")`, SigV4 scope `es`). Default data plane is a stub endpoint (`<domain>.ministack.local:9200`) — set `OPENSEARCH_DATAPLANE=1` to spawn one real `opensearchproject/opensearch` container per `CreateDomain` (same pattern as ElastiCache/RDS); `DescribeDomain.Endpoint` then points at that container and `_cluster/health`/`/_search` work end-to-end. Add `OPENSEARCH_DASHBOARDS=1` (with dataplane on) to also spawn a per-domain `opensearch-dashboards` sidecar; `DescribeDomain.DashboardEndpoint` is populated. ARNs follow `arn:aws:es:<region>:<account>:domain/<name>`; Terraform `aws_opensearch_domain` resource compatible. |diff --git a/ministack/app.py b/ministack/app.pyindex 47ab90b7..4623d96d 100644--- a/ministack/app.py+++ b/ministack/app.py@@ -290,6 +290,7 @@ SERVICE_REGISTRY = {"imds": {"module": "imds"},"iot": {"module": "iot"},"iot-data": {"module": "iot_data"},+ "iot-jobs-data": {"module": "iot_jobs_data"},"kinesis": {"module": "kinesis"},"kms": {"module": "kms"},"lambda": {"module": "lambda_svc"},diff --git a/ministack/core/router.py b/ministack/core/router.pyindex f123243b..d22657f4 100644--- a/ministack/core/router.py+++ b/ministack/core/router.py@@ -292,6 +292,20 @@ SERVICE_PATTERNS = {"host_patterns": [r"transfer\."],"credential_scope": "transfer",},+ # IoT Jobs data plane (iot-jobs-data API) MUST come before "iot-data" and+ # "iot": its host also matches the `iot\.` regex, so first-match-wins+ # routing would otherwise swallow it — and on the `iot` control plane+ # `GET /things/{t}/jobs` is a DIFFERENT operation (ListJobExecutionsForThing)+ # that answers with a different envelope. The pattern must cover both host+ # spellings: `DescribeEndpoint(endpointType='iot:Jobs')` hands out+ # `{prefix}.jobs.iot.{region}.{host}`, while the AWS Device SDK's jobs+ # topics document `{prefix}.data.jobs.iot.{region}.{host}`. The SDK also+ # signs with credential scope `iot-jobs-data` (botocore signingName), which+ # the scope early-return resolves via this key.+ "iot-jobs-data": {+ "host_patterns": [r"jobs\.iot\."],+ "credential_scope": "iot-jobs-data",+ },# IoT data plane (iot-data API) MUST come before "iot" because the host# `data-ats.iot.{region}.{host}` matches both `iot\.` and the more# specific `data-ats\.iot\.` regexes — first-match-wins routing indiff --git a/ministack/services/iot.py b/ministack/services/iot.pyindex f3cb5fee..b6c890ec 100644--- a/ministack/services/iot.py+++ b/ministack/services/iot.py@@ -22,6 +22,11 @@ Implements the JSON/REST APIs under ``iot.{region}.amazonaws.com``:- Fleet indexing: ``UpdateIndexingConfiguration`` /``GetIndexingConfiguration`` / ``DescribeIndex`` / ``ListIndices``, and``SearchIndex`` over the live registry, shadows and MQTT connectivity+ - Jobs (control plane): ``CreateJob``, ``DescribeJob``, ``ListJobs``,+ ``GetJobDocument``, ``CancelJob``, ``DeleteJob``,+ ``ListJobExecutionsForThing``, ``DescribeJobExecution``,+ ``CancelJobExecution`` — execution state shared with the+ ``iot-jobs-data`` device data plane (``iot_jobs_data.py``)- ``DescribeEndpoint`` returning a per-account hostnameThis is the control plane — pure HTTP/JSON, no MQTT broker@@ -98,6 +103,9 @@ _indexing_config: AccountRegionScopedDict = AccountRegionScopedDict()_ca_certificates: AccountRegionScopedDict = AccountRegionScopedDict()# JITR registration code — a single "code" key per account/region_registration_codes: AccountRegionScopedDict = AccountRegionScopedDict()+_jobs: AccountRegionScopedDict = AccountRegionScopedDict() # jobId -> Job dict+# (thingName, jobId) -> JobExecution dict — tuple keys, same pattern as _shadows+_job_executions: AccountRegionScopedDict = AccountRegionScopedDict()# Local CA state — lazily generated on first use, persisted across restarts.import threading@@ -197,6 +205,8 @@ def get_state() -> dict:"indexing_config": copy.deepcopy(_indexing_config),"ca_certificates": copy.deepcopy(_ca_certificates),"registration_codes": copy.deepcopy(_registration_codes),+ "jobs": copy.deepcopy(_jobs),+ "job_executions": copy.deepcopy(_job_executions),"ca": {"ca_cert_pem": _ca_cert_pem, "ca_key_pem": _ca_key_pem}if _ca_cert_pem and _ca_key_pemelse {},@@ -218,6 +228,8 @@ def restore_state(data: dict | None) -> None:_indexing_config.update(data.get("indexing_config", {}))_ca_certificates.update(data.get("ca_certificates", {}))_registration_codes.update(data.get("registration_codes", {}))+ _jobs.update(data.get("jobs", {}))+ _job_executions.update(data.get("job_executions", {}))ca_data = data.get("ca")if ca_data:cert = ca_data.get("ca_cert_pem")@@ -246,6 +258,8 @@ def reset() -> None:_indexing_config.clear()_ca_certificates.clear()_registration_codes.clear()+ _jobs.clear()+ _job_executions.clear()with _CA_LOCK:_ca_cert_pem = None_ca_key_pem = None@@ -334,12 +348,16 @@ def _validate_name(name: str | None, field: str) -> tuple | None:def _parse_body(body: bytes) -> dict:+ """Decode a JSON request body. Anything but a JSON object yields ``{}`` —+ every caller treats the result as a dict, so a bare array or string body+ must not reach them as one."""if not body:return {}try:- return json.loads(body.decode("utf-8"))+ parsed = json.loads(body.decode("utf-8"))except (UnicodeDecodeError, json.JSONDecodeError):return {}+ return parsed if isinstance(parsed, dict) else {}def _error_not_found(resource: str, name: str) -> tuple:@@ -398,6 +416,14 @@ async def handle_request(# Principal lives at /things/{name}/principals — must come BEFORE generic /things/{name}if path.startswith("/things/") and path.endswith("/principals"):return _handle_thing_principals(method, path, hdr, body, qp)+ # Job executions live at /things/{name}/jobs[/{jobId}[/cancel]] — 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`.+ if path.startswith("/things/"):+ _thing, _, _sub = path[len("/things/"):].partition("/")+ if _thing and (_sub == "jobs" or _sub.startswith("jobs/")):+ return _handle_thing_jobs(method, path, body, qp)if path.startswith("/things/") and method in ("POST", "GET", "PATCH", "DELETE"):return _handle_thing(method, path, body, qp)@@ -478,6 +504,13 @@ async def handle_request(return _list_indices()if path.startswith("/indices/") and method == "GET":return _describe_index(path)+ # Jobs (control plane) — CreateJob is PUT /jobs/{jobId} per the botocore+ # `iot` service model; sub-resources (/cancel, /job-document) are+ # dispatched inside _handle_job.+ if path == "/jobs" and method == "GET":+ return _list_jobs(qp)+ if path.startswith("/jobs/"):+ return _handle_job(method, path, body, qp)# Topic rulesif path == "/rules" and method == "GET":@@ -691,7 +724,15 @@ def _delete_thing(name: str) -> tuple:if group and name in group.get("things", []):group["things"].remove(name)_thing_groups[gname] = group+ # Drop the thing's job executions with it. Left behind, a live execution+ # for a thing that no longer exists holds its job out of COMPLETED forever,+ # and a later thing of the same name would inherit that stale history.+ 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)]del _things[name]+ for job_id in orphaned_jobs:+ _jobs_maybe_complete(job_id)logger.info("IoT Thing deleted: %s", name)return json_response({})@@ -3287,7 +3328,563 @@ def _list_topic_rules(qp: dict) -> tuple:# ----------------------------------------------------------------------------# Helper exports for iot_data+# IoT Jobs (control plane; execution state shared with iot_jobs_data.py)+# ---------------------------------------------------------------------------+#+# The job store and per-thing execution store live here so that the `iot`+# control plane and the `iot-jobs-data` data plane (iot_jobs_data.py, which+# imports this module directly — same pattern as iot_data.py and the shadow+# store) operate on the same records. Every rule of the state machine lives in+# this file; the data-plane module is a wire adapter over the `jobs_*` seam+# below. Transitions MiniStack can actually make:+#+# 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+# concurrency token here — an execution is created once at 1 and nothing+# re-queues it, so it never changes (AWS increments it when a job execution is+# retried, which MiniStack does not model).+#+# TIMED_OUT and REMOVED are recognized as terminal (so a restored record in+# either state behaves, and `jobProcessDetails` counts them) but nothing sets+# them: there are no execution timeouts, and deleting a thing DELETES its+# executions (see `_delete_thing`) rather than marking them REMOVED.++# 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).+# The generic thing-name pattern would let a `:` through control-side, and the+# device that has to fetch that job by id could then never reach it.+_JOB_ID_RE = re.compile(r"^[a-zA-Z0-9_-]{1,64}$")++_JOB_TARGET_SELECTIONS = {"SNAPSHOT", "CONTINUOUS"}++_JOB_EXECUTION_TERMINAL = {+ "SUCCEEDED", "FAILED", "TIMED_OUT", "CANCELED", "REJECTED", "REMOVED",+}+_JOB_EXECUTION_STATUSES = _JOB_EXECUTION_TERMINAL | {"QUEUED", "IN_PROGRESS"}++# The statuses a device may report through UpdateJobExecution, per the AWS API+# reference. The service-side statuses (CANCELED, TIMED_OUT, REMOVED) are only+# ever set by the control plane; a device sending one is rejected with+# InvalidRequestException, as on AWS.+_DEVICE_SETTABLE_STATUSES = {"IN_PROGRESS", "SUCCEEDED", "FAILED", "REJECTED"}+++def _jobs_now_ms() -> int:+ """Epoch MILLISECONDS — the unit job/execution records store internally.++ The two planes emit different units for these same instants: the `iot`+ control plane models them as `timestamp` shapes, which botocore parses+ as epoch SECONDS (so control-plane responses divide by 1000 via+ :func:`_jobs_ms_to_s`), while `iot-jobs-data` models them as raw `long`+ shapes carrying epoch MILLISECONDS (emitted as-is). Mixing the units up+ makes botocore explode while parsing ("year 58580 is out of range"), so+ every response path converts explicitly at the edge.+ """+ return int(time.time() * 1000)+++def _jobs_ms_to_s(millis: int | None) -> float | None:+ """Millisecond record stamp → epoch-seconds float for `timestamp` shapes."""+ return None if millis is None else millis / 1000.0+++def _job_arn(job_id: str) -> str:+ return f"arn:aws:iot:{get_region()}:{get_account_id()}:job/{job_id}"+++def _job_target_resolve(arn: str) -> list[str] | None:+ """Thing names one job target ARN resolves to, under the caller's scope.++ ``None`` means the ARN targets nothing this caller can reach: another+ service, another account, another region, or a thing / thing group that+ does not exist here. A thing group that exists but is empty resolves to an+ empty list — a real target with no members today.++ Group membership is read natively from `_thing_groups` — no HTTP hop.+ :func:`_create_job` gates on exactly this function, so a target it accepts+ is a target the materializer can resolve; validating creation any more+ loosely (e.g. on the ARN's resource segment alone) admits a cross-region+ target that silently resolves to zero executions, leaving a job that can+ never complete and can only be deleted with `force`.+ """+ try:+ spec = parse_arn(arn)+ except ArnParseError:+ return None+ if (+ spec.service != "iot"+ or spec.account_id != get_account_id()+ or spec.region != get_region()+ ):+ return None+ if spec.resource.startswith("thing/"):+ thing = spec.resource[len("thing/"):]+ return [thing] if thing in _things else None+ if spec.resource.startswith("thinggroup/"):+ group = _thing_groups.get(spec.resource[len("thinggroup/"):])+ return None if group is None else list(group.get("things", []))+ return None+++def _job_target_things(targets: list) -> list:+ """Resolve job targets (thing / thing-group ARNs) to thing names."""+ things: list[str] = []+ for arn in targets or []:+ things.extend(_job_target_resolve(arn) or [])+ return list(dict.fromkeys(things))+++def _jobs_materialize_executions(job_id: str) -> None:+ """Materialize QUEUED executions for a job's current targets.++ SNAPSHOT jobs resolve group membership exactly once (at creation) — the+ `snapshotted` flag latches that. CONTINUOUS jobs re-resolve lazily on+ every read, which is exactly when new membership matters and avoids+ watching group mutations.+ """+ job = _jobs.get(job_id)+ if not job or job.get("status") == "CANCELED":+ return+ if job.get("targetSelection") == "SNAPSHOT" and job.get("snapshotted"):+ return+ now = _jobs_now_ms()+ for thing in _job_target_things(job.get("targets")):+ key = (thing, job_id)+ if key in _job_executions:+ continue+ _job_executions[key] = {+ "jobId": job_id,+ "thingName": thing,+ "status": "QUEUED",+ "statusDetails": {},+ "queuedAt": now,+ "startedAt": None,+ "lastUpdatedAt": now,+ "executionNumber": 1,+ "versionNumber": 1,+ }+ if job.get("targetSelection") == "SNAPSHOT":+ job["snapshotted"] = True+++def _jobs_materialize_all() -> None:+ for job_id in list(_jobs.keys()):+ _jobs_materialize_executions(job_id)+++def _jobs_maybe_complete(job_id: str) -> None:+ """A non-CONTINUOUS job whose executions are all terminal is COMPLETED.++ "All" includes none left: every caller reaches here through a path that+ materialized the job's executions first, so an empty list means the last+ one just went away (its thing was deleted), not that the job has yet to+ start. Waiting for a non-empty list there would strand the job.+ """+ job = _jobs.get(job_id)+ if (+ not job+ or job.get("targetSelection") == "CONTINUOUS"+ or job.get("status") != "IN_PROGRESS"+ ):+ return+ executions = [e for e in _job_executions.values() if e["jobId"] == job_id]+ if all(e["status"] in _JOB_EXECUTION_TERMINAL for e in executions):+ now = _jobs_now_ms()+ job["status"] = "COMPLETED"+ job["completedAt"] = now+ job["lastUpdatedAt"] = now+++def _jobs_check_expected_version(+ execution: dict, expected, conflict_code: str+) -> 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+ `except client.exceptions.VersionConflictException` raise AttributeError+ instead of catching, because botocore only synthesizes exception classes+ for the errors its model lists.+ """+ if expected is None:+ return None+ try:+ expected = int(expected)+ except (TypeError, ValueError):+ return error_response_json(+ "InvalidRequestException", f"Invalid expectedVersion: {expected!r}", 400+ )+ if expected != execution["versionNumber"]:+ return error_response_json(+ conflict_code,+ f"Expected version {expected} does not match current version "+ f"{execution['versionNumber']} of the job execution",+ 409,+ )+ return None+++def _jobs_reject_if_terminal(execution: dict, verb: str) -> tuple | None:+ """Terminal executions are frozen — no update, no cancel."""+ if execution["status"] not in _JOB_EXECUTION_TERMINAL:+ return None+ return error_response_json(+ "InvalidStateTransitionException",+ f"Job execution is in terminal status {execution['status']} and "+ f"cannot be {verb}",+ 409,+ )+++def _handle_job(method: str, path: str, body: bytes, qp: dict) -> tuple:+ """Dispatch /jobs/{jobId}[...] control-plane routes."""+ suffix = path[len("/jobs/"):]+ if suffix.endswith("/cancel") and method == "PUT":+ return _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 "/" in suffix:+ return error_response_json(+ "InvalidRequestException", f"Unsupported IoT path: {method} {path}", 400+ )+ job_id = suffix+ if method == "PUT":+ return _create_job(job_id, _parse_body(body))+ if method == "GET":+ return _describe_job(job_id)+ if method == "DELETE":+ return _delete_job(job_id, qp)+ return error_response_json(+ "InvalidRequestException", f"Unsupported method: {method}", 400+ )+++def _create_job(job_id: str, payload: dict) -> tuple:+ if not job_id or not _JOB_ID_RE.match(job_id):+ return error_response_json(+ "InvalidRequestException",+ "Invalid jobId: must match [a-zA-Z0-9_-]{1,64}",+ 400,+ )+ if job_id in _jobs:+ return error_response_json(+ "ResourceAlreadyExistsException", f"Job {job_id} already exists", 409+ )+ # Absent means SNAPSHOT (the AWS default); present means it has to be one+ # of the two modeled values — including the empty string, which would+ # otherwise default its way to a SNAPSHOT job the caller never asked for.+ target_selection = payload.get("targetSelection")+ if target_selection is None:+ target_selection = "SNAPSHOT"+ if target_selection not in _JOB_TARGET_SELECTIONS:+ return error_response_json(+ "InvalidRequestException",+ f"Invalid targetSelection: {target_selection!r}; must be one of "+ + ", ".join(sorted(_JOB_TARGET_SELECTIONS)),+ 400,+ )+ targets = payload.get("targets")+ if not targets:+ return error_response_json(+ "InvalidRequestException", "targets must not be empty", 400+ )+ # Every target must name a thing or thing group this caller can reach, as+ # on AWS — and reach means under the SAME account and region, which is what+ # the materializer resolves against.+ for arn in targets:+ try:+ parse_arn(arn)+ except ArnParseError:+ return error_response_json(+ "InvalidRequestException", f"Invalid target arn: {arn}", 400+ )+ if _job_target_resolve(arn) is None:+ return error_response_json(+ "ResourceNotFoundException", f"Job target {arn} not found", 404+ )+ document = payload.get("document")+ if not document and payload.get("documentSource"):+ # DELIBERATE DIVERGENCE: AWS fetches the document from the S3 URL and+ # serves its CONTENT to devices. MiniStack does not fetch it — it+ # stands in a placeholder naming the source, so a `documentSource` job+ # still creates, describes, and runs its whole execution lifecycle.+ # A device that parses the document therefore sees the URL, not the+ # payload; pass `document` when the content matters.+ document = json.dumps({"documentSource": payload["documentSource"]})+ now = _jobs_now_ms()+ _jobs[job_id] = {+ "jobId": job_id,+ "jobArn": _job_arn(job_id),+ "description": payload.get("description"),+ "targets": list(targets),+ "targetSelection": target_selection,+ "document": document or "{}",+ "documentSource": payload.get("documentSource"),+ "status": "IN_PROGRESS",+ "createdAt": now,+ "lastUpdatedAt": now,+ "completedAt": None,+ "presignedUrlConfig": payload.get("presignedUrlConfig") or {},+ "jobExecutionsRolloutConfig": payload.get("jobExecutionsRolloutConfig")+ or {},+ "snapshotted": False,+ }+ _jobs_materialize_executions(job_id)+ response = {"jobArn": _job_arn(job_id), "jobId": job_id}+ if payload.get("description") is not None:+ response["description"] = payload["description"]+ return json_response(response)+++def _job_summary(job: dict) -> dict:+ summary = {+ "jobArn": job["jobArn"],+ "jobId": job["jobId"],+ "targetSelection": job["targetSelection"],+ "status": job["status"],+ "createdAt": _jobs_ms_to_s(job["createdAt"]),+ "lastUpdatedAt": _jobs_ms_to_s(job["lastUpdatedAt"]),+ }+ if job.get("completedAt") is not None:+ summary["completedAt"] = _jobs_ms_to_s(job["completedAt"])+ return summary+++def _describe_job(job_id: str) -> tuple:+ job = _jobs.get(job_id)+ if job is None:+ return _error_not_found("Job", job_id)+ _jobs_materialize_executions(job_id)+ counts = {status: 0 for status in _JOB_EXECUTION_STATUSES}+ for execution in _job_executions.values():+ if execution["jobId"] == job_id:+ counts[execution["status"]] += 1+ job_doc = {+ **_job_summary(job),+ "targets": list(job.get("targets") or []),+ "presignedUrlConfig": job.get("presignedUrlConfig") or {},+ "jobExecutionsRolloutConfig": job.get("jobExecutionsRolloutConfig") or {},+ "jobProcessDetails": {+ "numberOfQueuedThings": counts["QUEUED"],+ "numberOfInProgressThings": counts["IN_PROGRESS"],+ "numberOfSucceededThings": counts["SUCCEEDED"],+ "numberOfFailedThings": counts["FAILED"],+ "numberOfCanceledThings": counts["CANCELED"],+ "numberOfRejectedThings": counts["REJECTED"],+ "numberOfRemovedThings": counts["REMOVED"],+ "numberOfTimedOutThings": counts["TIMED_OUT"],+ },+ }+ if job.get("description") is not None:+ job_doc["description"] = job["description"]+ if job.get("comment") is not None:+ job_doc["comment"] = job["comment"]+ if job.get("reasonCode") is not None:+ job_doc["reasonCode"] = job["reasonCode"]+ response = {"job": job_doc}+ if job.get("documentSource") is not None:+ response["documentSource"] = job["documentSource"]+ return json_response(response)+++def _delete_job(job_id: str, qp: dict) -> tuple:+ job = _jobs.get(job_id)+ if job is None:+ return _error_not_found("Job", job_id)+ force = _qp_bool(qp, "force")+ if job["status"] == "IN_PROGRESS" and not force:+ return error_response_json(+ "InvalidStateTransitionException",+ f"Job {job_id} is in status IN_PROGRESS and cannot be deleted "+ "without force",+ 409,+ )+ del _jobs[job_id]+ for key in [k for k in _job_executions.keys() if k[1] == job_id]:+ del _job_executions[key]+ return json_response({})+++def _list_jobs(qp: dict) -> tuple:+ """``GET /jobs`` with ``status`` / ``targetSelection`` filters.++ ``maxResults`` / ``nextToken`` are not honored: the full list comes back+ as one page and no token is ever returned, so a paginator terminates+ after its first call (same stance as ``_list_indices``).+ """+ wanted_status = qp.get("status")+ wanted_selection = qp.get("targetSelection")+ jobs = [+ _job_summary(job)+ for job in _jobs.values()+ if (not wanted_status or job["status"] == wanted_status)+ and (not wanted_selection or job["targetSelection"] == wanted_selection)+ ]+ return json_response({"jobs": jobs})+++def _get_job_document(job_id: str) -> tuple:+ job = _jobs.get(job_id)+ if job is None:+ return _error_not_found("Job", job_id)+ return json_response({"document": job.get("document") or "{}"})+++def _cancel_job(job_id: str, payload: dict, qp: dict) -> tuple:+ job = _jobs.get(job_id)+ if job is None:+ return _error_not_found("Job", job_id)+ if job["status"] != "IN_PROGRESS":+ return error_response_json(+ "InvalidRequestException",+ f"Job {job_id} is in status {job['status']} and cannot be canceled",+ 400,+ )+ force = _qp_bool(qp, "force")+ now = _jobs_now_ms()+ job["status"] = "CANCELED"+ job["lastUpdatedAt"] = now+ job["completedAt"] = now+ if payload.get("comment") is not None:+ job["comment"] = payload["comment"]+ if payload.get("reasonCode") is not None:+ job["reasonCode"] = payload["reasonCode"]+ # QUEUED executions are always canceled with the job; IN_PROGRESS ones+ # only when force is set — as on AWS.+ for execution in _job_executions.values():+ if execution["jobId"] != job_id:+ continue+ if execution["status"] == "QUEUED" or (+ force and execution["status"] == "IN_PROGRESS"+ ):+ execution["status"] = "CANCELED"+ execution["lastUpdatedAt"] = now+ execution["versionNumber"] += 1+ response = {"jobArn": job["jobArn"], "jobId": job_id}+ if job.get("description") is not None:+ response["description"] = job["description"]+ return json_response(response)+++def _handle_thing_jobs(method: str, path: str, body: bytes, qp: dict) -> tuple:+ """Dispatch /things/{name}/jobs[...] control-plane routes."""+ rest = path[len("/things/"):]+ thing, _, sub = rest.partition("/")+ err = _validate_name(thing, "thingName")+ if err:+ return err+ if sub == "jobs":+ if method == "GET":+ return _list_job_executions_for_thing(thing, qp)+ return error_response_json(+ "InvalidRequestException", f"Unsupported method: {method}", 400+ )+ if not sub.startswith("jobs/"):+ return error_response_json(+ "InvalidRequestException", f"Unsupported IoT path: {method} {path}", 400+ )+ tail = sub[len("jobs/"):]+ if tail.endswith("/cancel") and method == "PUT":+ return _cancel_job_execution(+ thing, tail[:-len("/cancel")], _parse_body(body), qp+ )+ if "/" not in tail and method == "GET":+ return _describe_job_execution(thing, tail)+ return error_response_json(+ "InvalidRequestException", f"Unsupported IoT path: {method} {path}", 400+ )+++def _list_job_executions_for_thing(thing: str, qp: dict) -> tuple:+ """``GET /things/{thing}/jobs`` — one unbounded page, like ``_list_jobs``."""+ _jobs_materialize_all()+ wanted_status = qp.get("status")+ wanted_job = qp.get("jobId")+ # The wire shape nests the detail under `jobExecutionSummary`, with only+ # the jobId beside it (JobExecutionSummaryForThing).+ summaries = []+ for execution in _job_executions.values():+ if execution["thingName"] != thing:+ continue+ if wanted_status and execution["status"] != wanted_status:+ continue+ if 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"],+ }+ if execution.get("startedAt") is not None:+ summary["startedAt"] = _jobs_ms_to_s(execution["startedAt"])+ summaries.append(+ {"jobId": execution["jobId"], "jobExecutionSummary": summary}+ )+ return json_response({"executionSummaries": summaries})+++def _describe_job_execution(thing: str, job_id: str) -> tuple:+ _jobs_materialize_executions(job_id)+ execution = _job_executions.get((thing, job_id))+ if execution is None:+ return _error_not_found("Job execution", f"{thing}/{job_id}")+ view = {+ "jobId": execution["jobId"],+ "status": execution["status"],+ # Control-plane JobExecution nests the map under `detailsMap`+ # (JobExecutionStatusDetails); the data plane returns it flat.+ "statusDetails": {"detailsMap": execution.get("statusDetails") or {}},+ "thingArn": _thing_arn(thing),+ "queuedAt": _jobs_ms_to_s(execution["queuedAt"]),+ "lastUpdatedAt": _jobs_ms_to_s(execution["lastUpdatedAt"]),+ "executionNumber": execution["executionNumber"],+ "versionNumber": execution["versionNumber"],+ }+ if execution.get("startedAt") is not None:+ view["startedAt"] = _jobs_ms_to_s(execution["startedAt"])+ return json_response({"execution": view})+++def _cancel_job_execution(+ thing: str, job_id: str, payload: dict, qp: dict+) -> tuple:+ _jobs_materialize_executions(job_id)+ execution = _job_executions.get((thing, job_id))+ if execution is None:+ return _error_not_found("Job execution", f"{thing}/{job_id}")+ error = _jobs_check_expected_version(+ execution, payload.get("expectedVersion"), "VersionConflictException"+ )+ if error:+ return error+ error = _jobs_reject_if_terminal(execution, "canceled")+ if error:+ return error+ force = _qp_bool(qp, "force")+ if execution["status"] == "IN_PROGRESS" and not force:+ return error_response_json(+ "InvalidStateTransitionException",+ "Job execution is IN_PROGRESS and cannot be canceled without force",+ 409,+ )+ execution["status"] = "CANCELED"+ if payload.get("statusDetails"):+ execution["statusDetails"] = dict(payload["statusDetails"])+ execution["lastUpdatedAt"] = _jobs_now_ms()+ execution["versionNumber"] += 1+ _jobs_maybe_complete(job_id)+ return json_response({})+++# ---------------------------------------------------------------------------+# Helper exports for the data planes (iot_data, iot_jobs_data)# ---------------------------------------------------------------------------@@ -3296,6 +3893,138 @@ def lookup_certificate_by_id(cert_id: str, region: str) -> dict | None:return _certificates.get_scoped(get_account_id(), region, cert_id)+# The data planes share the control plane's body decoding instead of+# re-implementing it (empty, undecodable, or non-object body → {}).+parse_json_body = _parse_body+++# --- IoT Jobs seam (consumed by iot_jobs_data.py) --------------------------+#+# The device plane is a wire adapter: it parses requests, shapes responses,+# and logs — it never touches _jobs / _job_executions, so the state machine+# has exactly one home. The mutating calls return `(execution, error)`, where+# `execution` is a COPY (a caller cannot corrupt the store through it) and+# `error` is a ready-to-return response tuple.+++def jobs_pending_for_thing(thing_name: str) -> list[dict]:+ """Every non-terminal execution for a thing, oldest queued first (copies).++ Materializes first: a thing added to a CONTINUOUS job's target group after+ creation gets its execution here, on the read that first needs it.+ """+ _jobs_materialize_all()+ pending = [+ dict(execution)+ for execution in _job_executions.values()+ if execution["thingName"] == thing_name+ and execution["status"] in ("QUEUED", "IN_PROGRESS")+ ]+ pending.sort(key=lambda execution: execution["queuedAt"])+ return pending+++def jobs_start_next_execution(+ thing_name: str, *, status_details: dict | None = None, peek: bool = False+) -> dict | None:+ """Hand a thing its next pending execution, or None when it is idle.++ A QUEUED execution moves to IN_PROGRESS (stamping `startedAt`, bumping+ `versionNumber`); with `peek=True` — GET of the `$next` sentinel — the+ execution is read without being started. An already IN_PROGRESS execution+ is re-handed unchanged, so a device that restarts mid-job resumes it.+ """+ pending = jobs_pending_for_thing(thing_name)+ if not pending:+ return None+ execution = _job_executions[(thing_name, pending[0]["jobId"])]+ if not peek and execution["status"] == "QUEUED":+ now = _jobs_now_ms()+ execution["status"] = "IN_PROGRESS"+ execution["startedAt"] = now+ execution["lastUpdatedAt"] = now+ execution["versionNumber"] += 1+ if status_details:+ execution["statusDetails"] = dict(status_details)+ return dict(execution)+++def jobs_describe_execution(thing_name: str, job_id: str) -> dict | None:+ """One execution (a copy), materializing the job's targets first."""+ _jobs_materialize_executions(job_id)+ execution = _job_executions.get((thing_name, job_id))+ return None if execution is None else dict(execution)+++def jobs_job_document(job_id: str) -> str:+ """The document a device should run for a job — ``{}`` if there is none."""+ job = _jobs.get(job_id)+ return (job or {}).get("document") or "{}"+++def jobs_update_execution(+ thing_name: str,+ job_id: str,+ *,+ status,+ expected_version=None,+ status_details: dict | None = None,+) -> tuple:+ """Apply a device-reported status to an execution.++ Returns ``(execution copy, None)``, or ``(None, error)`` for every+ rejection: unknown execution (404), stale or non-numeric+ `expectedVersion`, an already-terminal execution, an unknown status, the+ illegal walk back to QUEUED, and the service-side statuses a device may+ not set. A successful update may complete the job.+ """+ _jobs_materialize_executions(job_id)+ execution = _job_executions.get((thing_name, job_id))+ if execution is None:+ return None, error_response_json(+ "ResourceNotFoundException",+ f"No job execution found for thing {thing_name} and job {job_id}",+ 404,+ )+ error = _jobs_check_expected_version(+ execution, expected_version, "InvalidStateTransitionException"+ )+ if error:+ return None, error+ error = _jobs_reject_if_terminal(execution, "updated")+ if error:+ return None, error+ if not status or status not in _JOB_EXECUTION_STATUSES:+ return None, error_response_json(+ "InvalidRequestException",+ f"Invalid job execution status: {status!r}",+ 400,+ )+ if status == "QUEUED":+ return None, error_response_json(+ "InvalidStateTransitionException",+ "A device cannot move a job execution back to QUEUED",+ 409,+ )+ if status not in _DEVICE_SETTABLE_STATUSES:+ return None, error_response_json(+ "InvalidRequestException",+ f"A device cannot set status {status} via UpdateJobExecution; "+ "allowed statuses are IN_PROGRESS, SUCCEEDED, FAILED, and REJECTED",+ 400,+ )+ now = _jobs_now_ms()+ execution["status"] = status+ if status_details:+ execution["statusDetails"] = dict(status_details)+ if status == "IN_PROGRESS" and execution.get("startedAt") is None:+ execution["startedAt"] = now+ execution["lastUpdatedAt"] = now+ execution["versionNumber"] += 1+ _jobs_maybe_complete(job_id)+ return dict(execution), None++# ---------------------------------------------------------------------------# Device Shadow (consumed by iot_data.py)# ---------------------------------------------------------------------------diff --git a/ministack/services/iot_jobs_data.py b/ministack/services/iot_jobs_data.pynew file mode 100644index 00000000..8e95c8f9--- /dev/null+++ b/ministack/services/iot_jobs_data.py@@ -0,0 +1,230 @@+"""IoT Jobs Data Plane HTTP API (``iot-jobs-data`` AWS service).++Implements the device-side REST surface of AWS IoT Jobs:+``GetPendingJobExecutions``, ``StartNextPendingJobExecution``,+``DescribeJobExecution``, and ``UpdateJobExecution``.++Routing reaches us either through credential-scope detection (the SDK signs+requests with the ``iot-jobs-data`` scope — botocore signingName) or via the+host pattern ``{prefix}.jobs.iot.{region}.{host}``, which is what+``DescribeEndpoint(endpointType='iot:Jobs')`` hands out.++This module is a wire adapter: it parses requests, shapes responses, and logs.+The job store, the execution store, and every rule of the execution state+machine live in :mod:`ministack.services.iot`, reached through its public+``jobs_*`` seam (the same way ``iot_data.py`` reaches the shadow store), so+nothing here can mutate an execution behind the control plane's back.++Timestamp contract: the shared records store epoch MILLISECONDS. This data+plane models timestamps as raw ``long`` shapes, so responses emit those+millisecond integers unchanged — unlike the ``iot`` control plane, whose+``timestamp`` shapes botocore parses as epoch SECONDS. Mixing the units up+makes botocore explode while parsing ("year 58580 is out of range"); see+``iot._jobs_now_ms``.+"""++from __future__ import annotations++import logging+from urllib.parse import unquote++from ministack.core.responses import error_response_json, json_response+from ministack.services import iot as _iot_module++logger = logging.getLogger("iot_jobs_data")+++# ---------------------------------------------------------------------------+# Persistence (no state of our own — the iot module holds it)+# ---------------------------------------------------------------------------+++def get_state() -> dict:+ return {}+++def restore_state(data: dict | None) -> None:+ return None+++def reset() -> None:+ return None+++# ---------------------------------------------------------------------------+# Dispatcher+# ---------------------------------------------------------------------------+++async def handle_request(+ method: str, path: str, headers: dict, body: bytes, query_params: dict+) -> tuple:+ qp = {k: (v[0] if isinstance(v, list) else v) for k, v in query_params.items()}++ if not path.startswith("/things/"):+ return _unsupported_path(method, path)+ rest = path[len("/things/"):]+ thing, separator, sub = rest.partition("/")+ thing = unquote(thing)+ if not separator:+ return _unsupported_path(method, path)++ if sub == "jobs":+ # GetPendingJobExecutions is the only operation on the bare+ # /things/{thingName}/jobs collection; anything else (a POST, say)+ # is not part of this API and must not fall through to the {jobId}+ # handlers with an empty job id.+ if method == "GET":+ return _get_pending(thing)+ return _unsupported_path(method, path)++ if not sub.startswith("jobs/"):+ return _unsupported_path(method, path)++ job_id = unquote(sub[len("jobs/"):])+ # `$next` is a sentinel, not a job id, so it must be matched before the+ # generic {jobId} routes.+ if job_id == "$next":+ if method == "GET":+ return _start_next(thing, {}, peek=True)+ if method == "PUT":+ return _start_next(thing, _iot_module.parse_json_body(body), peek=False)+ return _unsupported_path(method, path)+ if method == "GET":+ return _describe_execution(thing, job_id, qp)+ if method == "POST":+ return _update_execution(thing, job_id, _iot_module.parse_json_body(body))+ return _unsupported_path(method, path)+++def _unsupported_path(method: str, path: str) -> tuple:+ return error_response_json(+ "InvalidRequestException",+ f"Unsupported iot-jobs-data path: {method} {path}",+ 400,+ )+++# ---------------------------------------------------------------------------+# Handlers+# ---------------------------------------------------------------------------+++def _execution_view(execution: dict, document: str | None) -> dict:+ """Data-plane JobExecution — millisecond `long` timestamps, flat+ statusDetails map."""+ view = {+ "jobId": execution["jobId"],+ "thingName": execution["thingName"],+ "status": execution["status"],+ "statusDetails": execution.get("statusDetails") or {},+ "queuedAt": execution["queuedAt"],+ "lastUpdatedAt": execution["lastUpdatedAt"],+ "executionNumber": execution["executionNumber"],+ "versionNumber": execution["versionNumber"],+ }+ if execution.get("startedAt") is not None:+ view["startedAt"] = execution["startedAt"]+ if document is not None:+ view["jobDocument"] = document+ return view+++def _get_pending(thing: str) -> tuple:+ """GetPendingJobExecutions — queued and in-progress, split, ms stamps."""++ def summary(execution: dict) -> dict:+ entry = {+ "jobId": execution["jobId"],+ "queuedAt": execution["queuedAt"],+ "lastUpdatedAt": execution["lastUpdatedAt"],+ "versionNumber": execution["versionNumber"],+ "executionNumber": execution["executionNumber"],+ }+ if execution.get("startedAt") is not None:+ entry["startedAt"] = execution["startedAt"]+ return entry++ pending = _iot_module.jobs_pending_for_thing(thing)+ return json_response({+ "inProgressJobs": [+ summary(e) for e in pending if e["status"] == "IN_PROGRESS"+ ],+ "queuedJobs": [summary(e) for e in pending if e["status"] == "QUEUED"],+ })+++def _start_next(thing: str, payload: dict, *, peek: bool) -> tuple:+ """StartNextPendingJobExecution (PUT) / DescribeJobExecution of ``$next``+ (GET, ``peek=True`` — reads without starting)."""+ execution = _iot_module.jobs_start_next_execution(+ thing, status_details=payload.get("statusDetails"), peek=peek+ )+ if execution is None:+ # AWS returns an empty structure when nothing is pending.+ return json_response({})+ if not peek:+ logger.info(+ "IoT Jobs: handed job %s to thing %s (status %s, version %s)",+ execution["jobId"], thing, execution["status"],+ execution["versionNumber"],+ )+ document = _iot_module.jobs_job_document(execution["jobId"])+ return json_response({"execution": _execution_view(execution, document)})+++def _describe_execution(thing: str, job_id: str, qp: dict) -> tuple:+ execution = _iot_module.jobs_describe_execution(thing, job_id)+ if execution is None:+ return error_response_json(+ "ResourceNotFoundException",+ f"No job execution found for thing {thing} and job {job_id}",+ 404,+ )+ execution_number = qp.get("executionNumber")+ if execution_number is not None:+ try:+ execution_number = int(execution_number)+ except (TypeError, ValueError):+ return error_response_json(+ "InvalidRequestException",+ f"Invalid executionNumber: {execution_number!r}",+ 400,+ )+ if execution_number != execution["executionNumber"]:+ return error_response_json(+ "ResourceNotFoundException",+ f"No job execution {execution_number} found for thing {thing} "+ f"and job {job_id}",+ 404,+ )+ include_document = str(qp.get("includeJobDocument", "true")).lower() != "false"+ document = _iot_module.jobs_job_document(job_id) if include_document else None+ return json_response({"execution": _execution_view(execution, document)})+++def _update_execution(thing: str, job_id: str, payload: dict) -> tuple:+ execution, error = _iot_module.jobs_update_execution(+ thing,+ job_id,+ status=payload.get("status"),+ expected_version=payload.get("expectedVersion"),+ status_details=payload.get("statusDetails"),+ )+ if error:+ return error+ logger.info(+ "IoT Jobs: thing %s reported job %s as %s (version %s)",+ thing, job_id, execution["status"], execution["versionNumber"],+ )++ response: dict = {}+ if str(payload.get("includeJobExecutionState", "")).lower() in ("true", "1"):+ response["executionState"] = {+ "status": execution["status"],+ "statusDetails": execution.get("statusDetails") or {},+ "versionNumber": execution["versionNumber"],+ }+ if str(payload.get("includeJobDocument", "")).lower() in ("true", "1"):+ response["jobDocument"] = _iot_module.jobs_job_document(job_id)+ return json_response(response)diff --git a/tests/conftest.py b/tests/conftest.pyindex 40c17660..4ad01dc3 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -469,6 +469,11 @@ def iot_data_client():return make_client("iot-data")[email protected](scope="session")+def iot_jobs_data():+ return make_client("iot-jobs-data")++@pytest.fixture(scope="session")def wafv2():return make_client("wafv2")diff --git a/tests/test_iot.py b/tests/test_iot.pyindex e498b36e..6f0df79f 100644--- a/tests/test_iot.py+++ b/tests/test_iot.py@@ -1507,6 +1507,8 @@ def test_iot_control_plane_identity_stores_are_region_scoped():iot_module._shadows,iot_module._ca_certificates,iot_module._registration_codes,+ iot_module._jobs,+ iot_module._job_executions,)assert all(isinstance(store, AccountRegionScopedDict) for store in stores)@@ -6048,3 +6050,73 @@ def test_shadow_mqtt_get_and_delete_reject_invalid_json():finally:iot_module._shadows.clear()reset()+++def test_jobs_restored_timed_out_and_removed_executions_are_terminal():+ """The two service-side statuses nothing here sets must still behave.++ A record restored from persistence (written by a fuller implementation)+ can carry TIMED_OUT or REMOVED. The promise in the jobs header is that+ such a record is terminal: it is counted in ``jobProcessDetails`` and+ does not stop the job from completing. White-box, because only a restore+ can produce these statuses locally.+ """+ from ministack.core.responses import (+ set_request_account_id,+ set_request_region,+ )+ from ministack.services import iot as iot_module++ account_id = "123456789012"++ async def _request(method, path, payload=None):+ set_request_account_id(account_id)+ set_request_region("us-east-1")+ body = json.dumps(payload or {}).encode()+ return await iot_module.handle_request(method, path, {}, body, {})++ async def _scenario():+ set_request_account_id(account_id)+ set_request_region("us-east-1")+ job_id = f"restored-terminal-{uuid.uuid4().hex[:8]}"+ things = [f"jt-{job_id}-a", f"jt-{job_id}-b"]+ try:+ for thing in things:+ status, _headers, _body = await _request("POST", f"/things/{thing}")+ assert status == 200+ status, _headers, _body = await _request(+ "PUT",+ f"/jobs/{job_id}",+ {+ "targets": [+ f"arn:aws:iot:us-east-1:{account_id}:thing/{t}"+ for t in things+ ],+ "document": json.dumps({"op": "noop"}),+ },+ )+ assert status == 200++ iot_module._jobs_materialize_executions(job_id)+ iot_module._job_executions[(things[0], job_id)]["status"] = "TIMED_OUT"+ iot_module._job_executions[(things[1], job_id)]["status"] = "REMOVED"+ iot_module._jobs_maybe_complete(job_id)++ status, _headers, body = await _request("GET", f"/jobs/{job_id}")+ assert status == 200+ job = json.loads(body)["job"]+ details = job["jobProcessDetails"]+ assert details["numberOfTimedOutThings"] == 1+ assert details["numberOfRemovedThings"] == 1+ assert job["status"] == "COMPLETED", (+ "a job whose remaining executions are all TIMED_OUT/REMOVED "+ "must complete - the statuses are terminal even though "+ "nothing local sets them"+ )+ finally:+ iot_module._jobs.pop(job_id, None)+ for thing in things:+ iot_module._job_executions.pop((thing, job_id), None)+ await _request("DELETE", f"/things/{thing}")++ asyncio.run(_scenario())diff --git a/tests/test_iot_jobs.py b/tests/test_iot_jobs.pynew file mode 100644index 00000000..a5539990--- /dev/null+++ b/tests/test_iot_jobs.py@@ -0,0 +1,1233 @@+"""Integration tests for AWS IoT Jobs.++Covers the control plane on the `iot` client (CreateJob, DescribeJob,+ListJobs, GetJobDocument, CancelJob, DeleteJob, ListJobExecutionsForThing,+DescribeJobExecution, CancelJobExecution) and the `iot-jobs-data` device+data plane (GetPendingJobExecutions, StartNextPendingJobExecution,+DescribeJobExecution incl. the `$next` sentinel, UpdateJobExecution).++The timestamp contract is asserted explicitly: control-plane responses use+`timestamp` shapes (epoch seconds — botocore parses them to datetimes),+data-plane responses use raw `long` shapes (epoch milliseconds).+"""++import json+import os+import time+import urllib.error+import urllib.request+import uuid+from datetime import datetime, timezone+from urllib.parse import quote++import pytest+from botocore.exceptions import ClientError++ENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")++_DOCUMENT = json.dumps({"operation": "reboot", "when": "now"})++# A syntactically plausible SigV4 header whose credential scope routes the+# request to the iot-jobs-data service in the default account and region+# (signatures are not verified) — for raw-HTTP cases boto3 cannot produce.+_JOBS_DATA_AUTH = (+ "AWS4-HMAC-SHA256 "+ "Credential=test/20260811/us-east-1/iot-jobs-data/aws4_request, "+ "SignedHeaders=host, Signature=fake"+)+++_IOT_AUTH = (+ "AWS4-HMAC-SHA256 "+ "Credential=test/20260811/us-east-1/iot/aws4_request, "+ "SignedHeaders=host, Signature=fake"+)+++def _raw(auth, method, path, payload=None):+ """Raw HTTP with an explicit credential scope; returns (status, body)."""+ req = urllib.request.Request(+ f"{ENDPOINT}{path}",+ data=json.dumps(payload or {}).encode() if method != "GET" else None,+ method=method,+ headers={"Authorization": auth, "content-type": "application/json"},+ )+ try:+ with urllib.request.urlopen(req, timeout=5) as resp:+ return resp.status, json.loads(resp.read() or b"{}")+ except urllib.error.HTTPError as e:+ return e.code, json.loads(e.read() or b"{}")+++def _raw_jobs_data(method, path, payload=None):+ """Raw HTTP against the iot-jobs-data plane; returns (status, body dict)."""+ return _raw(_JOBS_DATA_AUTH, method, path, payload)+++def _swap_arn_field(arn, index, value):+ """Rewrite one top-level ARN field (3 = region, 4 = account)."""+ fields = arn.split(":", 5)+ fields[index] = value+ return ":".join(fields)+++def _account_client(service, account_id, region="us-east-1"):+ """A client whose 12-digit access key selects the MiniStack account."""+ import boto3+ from botocore.config import Config++ return boto3.client(+ service,+ endpoint_url=ENDPOINT,+ aws_access_key_id=account_id,+ aws_secret_access_key="test",+ region_name=region,+ config=Config(retries={"mode": "standard"}),+ )+++def _unique(prefix: str) -> str:+ return f"{prefix}-{uuid.uuid4().hex[:8]}"+++def _create_thing(iot_client, name):+ return iot_client.create_thing(thingName=name)["thingArn"]+++def _cleanup(iot_client, jobs=(), things=(), groups=()):+ for job_id in jobs:+ try:+ iot_client.delete_job(jobId=job_id, force=True)+ except ClientError:+ pass+ for thing in things:+ try:+ iot_client.delete_thing(thingName=thing)+ except ClientError:+ pass+ for group in groups:+ try:+ iot_client.delete_thing_group(thingGroupName=group)+ except ClientError:+ pass+++def _assert_ms_epoch(value):+ """A data-plane stamp must be an epoch-milliseconds integer (a `long` on+ the wire) — seconds here would be off by 1000x."""+ assert isinstance(value, int)+ assert abs(value - time.time() * 1000) < 5 * 60 * 1000+++# ---------------------------------------------------------------------------+# Create / describe / document — and the seconds-vs-milliseconds contract+# ---------------------------------------------------------------------------+++def test_iot_jobs_create_describe_and_pending(iot_client, iot_jobs_data):+ thing = _unique("jobs-thing")+ job_id = _unique("job")+ try:+ thing_arn = _create_thing(iot_client, thing)+ resp = iot_client.create_job(+ jobId=job_id,+ targets=[thing_arn],+ document=_DOCUMENT,+ description="reboot fleet",+ )+ assert resp["jobId"] == job_id+ assert resp["jobArn"].endswith(f":job/{job_id}")++ desc = iot_client.describe_job(jobId=job_id)["job"]+ assert desc["status"] == "IN_PROGRESS"+ assert desc["targetSelection"] == "SNAPSHOT"+ assert desc["targets"] == [thing_arn]+ assert desc["jobProcessDetails"]["numberOfQueuedThings"] == 1+ # Control plane emits `timestamp` shapes (epoch seconds): botocore+ # must parse createdAt into a datetime near now — a millisecond+ # value here would blow up as "year 58580 is out of range".+ created = desc["createdAt"]+ assert isinstance(created, datetime)+ assert abs((created - datetime.now(timezone.utc)).total_seconds()) < 300++ pending = iot_jobs_data.get_pending_job_executions(thingName=thing)+ assert pending["inProgressJobs"] == []+ queued = pending["queuedJobs"]+ assert [q["jobId"] for q in queued] == [job_id]+ assert queued[0]["versionNumber"] == 1+ assert queued[0]["executionNumber"] == 1+ # Data plane emits `long` shapes: raw epoch milliseconds.+ _assert_ms_epoch(queued[0]["queuedAt"])+ _assert_ms_epoch(queued[0]["lastUpdatedAt"])+ finally:+ _cleanup(iot_client, jobs=[job_id], things=[thing])+++def test_iot_jobs_get_job_document(iot_client):+ 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)+ assert iot_client.get_job_document(jobId=job_id)["document"] == _DOCUMENT+ finally:+ _cleanup(iot_client, jobs=[job_id], things=[thing])+++def test_iot_jobs_document_source_serves_a_placeholder_and_is_not_fetched(+ iot_client, iot_jobs_data+):+ """Documented divergence: AWS fetches `documentSource` from S3 and serves+ its CONTENT to devices. MiniStack does not fetch it — it serves a+ placeholder naming the source, so a `documentSource` job still creates,+ describes, and runs its whole execution lifecycle locally. This test pins+ that choice; changing it means changing README + CHANGELOG too."""+ thing = _unique("jobs-thing")+ job_id = _unique("job")+ source = "https://ministack-jobs.s3.us-east-1.amazonaws.com/reboot.json"+ try:+ thing_arn = _create_thing(iot_client, thing)+ iot_client.create_job(+ jobId=job_id, targets=[thing_arn], documentSource=source+ )+ # The control plane echoes the source it was handed...+ assert iot_client.describe_job(jobId=job_id)["documentSource"] == source+ # ...and both document reads serve the placeholder, never S3 content.+ assert json.loads(iot_client.get_job_document(jobId=job_id)["document"]) == {+ "documentSource": source+ }+ execution = iot_jobs_data.describe_job_execution(+ jobId=job_id, thingName=thing+ )["execution"]+ assert json.loads(execution["jobDocument"]) == {"documentSource": source}+ finally:+ _cleanup(iot_client, jobs=[job_id], things=[thing])+++def test_iot_jobs_create_duplicate_and_unknown_target_rejected(iot_client):+ 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)+ with pytest.raises(ClientError) as ei:+ iot_client.create_job(+ jobId=job_id, targets=[thing_arn], document=_DOCUMENT+ )+ assert ei.value.response["Error"]["Code"] == "ResourceAlreadyExistsException"++ ghost_arn = thing_arn.rsplit("/", 1)[0] + "/" + _unique("no-such-thing")+ with pytest.raises(ClientError) as ei:+ iot_client.create_job(+ jobId=_unique("job"), targets=[ghost_arn], document=_DOCUMENT+ )+ assert ei.value.response["Error"]["Code"] == "ResourceNotFoundException"+ finally:+ _cleanup(iot_client, jobs=[job_id], things=[thing])+++# ---------------------------------------------------------------------------+# Device lifecycle: start-next → update (optimistic concurrency) → job done+# ---------------------------------------------------------------------------+++def test_iot_jobs_start_next_update_and_auto_complete(iot_client, iot_jobs_data):+ 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)++ started = iot_jobs_data.start_next_pending_job_execution(thingName=thing)+ execution = started["execution"]+ assert execution["jobId"] == job_id+ assert execution["status"] == "IN_PROGRESS"+ assert execution["versionNumber"] == 2 # start bumped it from 1+ assert execution["jobDocument"] == _DOCUMENT+ _assert_ms_epoch(execution["startedAt"])++ pending = iot_jobs_data.get_pending_job_executions(thingName=thing)+ 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,+ # 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+ # AttributeError instead of catching. The message carries the current+ # 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+ ) 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 "current version 2" in error["Message"]++ updated = iot_jobs_data.update_job_execution(+ jobId=job_id,+ thingName=thing,+ status="SUCCEEDED",+ statusDetails={"progress": "100"},+ expectedVersion=2,+ includeJobExecutionState=True,+ )+ state = updated["executionState"]+ assert state["status"] == "SUCCEEDED"+ assert state["versionNumber"] == 3+ assert state["statusDetails"] == {"progress": "100"}++ # A terminal execution cannot be updated again.+ with pytest.raises(ClientError) as ei:+ iot_jobs_data.update_job_execution(+ jobId=job_id, thingName=thing, status="FAILED"+ )+ assert (+ ei.value.response["Error"]["Code"] == "InvalidStateTransitionException"+ )++ # All executions terminal → the (SNAPSHOT) job auto-completes.+ job = iot_client.describe_job(jobId=job_id)["job"]+ assert job["status"] == "COMPLETED"+ assert job["jobProcessDetails"]["numberOfSucceededThings"] == 1+ assert isinstance(job["completedAt"], datetime)+ finally:+ _cleanup(iot_client, jobs=[job_id], things=[thing])+++def test_iot_jobs_update_rejects_service_side_statuses(+ iot_client, iot_jobs_data+):+ """A device may only report IN_PROGRESS / SUCCEEDED / FAILED / REJECTED;+ the service-side statuses (CANCELED, TIMED_OUT, REMOVED) must be rejected+ with InvalidRequestException (400), as on AWS."""+ 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)++ for status in ("CANCELED", "TIMED_OUT", "REMOVED"):+ with pytest.raises(ClientError) as ei:+ iot_jobs_data.update_job_execution(+ jobId=job_id, thingName=thing, status=status+ )+ error = ei.value.response["Error"]+ assert error["Code"] == "InvalidRequestException", status+ assert (+ ei.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400+ ), status++ # The rejected updates must not have touched the execution.+ execution = iot_jobs_data.describe_job_execution(+ jobId=job_id, thingName=thing+ )["execution"]+ assert execution["status"] == "QUEUED"+ assert execution["versionNumber"] == 1+ finally:+ _cleanup(iot_client, jobs=[job_id], things=[thing])+++def test_iot_jobs_update_non_numeric_expected_version_is_400(iot_client):+ """A non-numeric expectedVersion (only reachable outside boto3's client-+ side typing) must be a clean InvalidRequestException, not a 500."""+ 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)++ status, body = _raw_jobs_data(+ "POST",+ f"/things/{quote(thing)}/jobs/{quote(job_id)}",+ {"status": "SUCCEEDED", "expectedVersion": "not-a-number"},+ )+ assert status == 400+ assert body["__type"] == "InvalidRequestException"+ finally:+ _cleanup(iot_client, jobs=[job_id], things=[thing])+++def test_iot_jobs_data_post_to_jobs_collection_is_unsupported(iot_client):+ """POST /things/{t}/jobs is not an iot-jobs-data operation — it must get+ the standard unsupported-path 400, not fall through to UpdateJobExecution+ with an empty job id (which used to 404)."""+ thing = _unique("jobs-thing")+ try:+ _create_thing(iot_client, thing)+ status, body = _raw_jobs_data(+ "POST", f"/things/{quote(thing)}/jobs", {"status": "SUCCEEDED"}+ )+ assert status == 400+ assert "Unsupported iot-jobs-data path" in json.dumps(body)+ finally:+ _cleanup(iot_client, things=[thing])+++def test_iot_jobs_device_cannot_move_execution_back_to_queued(+ iot_client, iot_jobs_data+):+ """QUEUED is a real execution status but not a legal device transition: a+ device rewinding its own execution gets InvalidStateTransitionException+ (409) — distinct from the 400 the service-side statuses get, because the+ status is valid and only the transition is not."""+ 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)+ started = iot_jobs_data.start_next_pending_job_execution(thingName=thing)+ assert started["execution"]["status"] == "IN_PROGRESS"++ with pytest.raises(+ iot_jobs_data.exceptions.InvalidStateTransitionException+ ) as ei:+ iot_jobs_data.update_job_execution(+ jobId=job_id, thingName=thing, status="QUEUED"+ )+ assert ei.value.response["ResponseMetadata"]["HTTPStatusCode"] == 409++ execution = iot_jobs_data.describe_job_execution(+ jobId=job_id, thingName=thing+ )["execution"]+ assert execution["status"] == "IN_PROGRESS"+ assert execution["versionNumber"] == 2 # the refusal changed nothing+ finally:+ _cleanup(iot_client, jobs=[job_id], things=[thing])+++def test_iot_jobs_fleet_completes_only_when_every_execution_is_terminal(+ iot_client, iot_jobs_data+):+ """A job over two things stays IN_PROGRESS while one execution is still+ outstanding: auto-completion keys off ALL executions being terminal, not+ the first one to report."""+ first = _unique("jobs-thing")+ second = _unique("jobs-thing")+ job_id = _unique("job")+ try:+ first_arn = _create_thing(iot_client, first)+ second_arn = _create_thing(iot_client, second)+ iot_client.create_job(+ jobId=job_id, targets=[first_arn, second_arn], document=_DOCUMENT+ )++ iot_jobs_data.update_job_execution(+ jobId=job_id, thingName=first, status="SUCCEEDED"+ )+ job = iot_client.describe_job(jobId=job_id)["job"]+ assert job["status"] == "IN_PROGRESS"+ assert "completedAt" not in job+ details = job["jobProcessDetails"]+ assert details["numberOfSucceededThings"] == 1+ assert details["numberOfQueuedThings"] == 1++ # The second device fails — either terminal status finishes the job.+ iot_jobs_data.update_job_execution(+ jobId=job_id, thingName=second, status="FAILED"+ )+ job = iot_client.describe_job(jobId=job_id)["job"]+ assert job["status"] == "COMPLETED"+ assert job["jobProcessDetails"]["numberOfFailedThings"] == 1+ assert isinstance(job["completedAt"], datetime)+ finally:+ _cleanup(iot_client, jobs=[job_id], things=[first, second])+++# ---------------------------------------------------------------------------+# Routing: the jobs routes must not shadow thing CRUD+# ---------------------------------------------------------------------------+++def test_iot_jobs_advertised_endpoint_host_reaches_the_data_plane(iot_client):+ """The documented device flow: `DescribeEndpoint(endpointType='iot:Jobs')`+ hands out `{prefix}.jobs.iot.{region}`, and a request carrying that Host+ must land on the jobs data plane. Routed to the `iot` control plane+ instead, `GET /things/{t}/jobs` is ListJobExecutionsForThing and silently+ answers a different envelope."""+ 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)++ endpoint = iot_client.describe_endpoint(endpointType="iot:Jobs")[+ "endpointAddress"+ ]+ assert ".jobs.iot." in endpoint+ request = urllib.request.Request(+ f"{ENDPOINT}/things/{quote(thing)}/jobs",+ method="GET",+ headers={"Host": endpoint},+ )+ with urllib.request.urlopen(request, timeout=5) as resp:+ body = json.loads(resp.read())++ # The GetPendingJobExecutions envelope — not `executionSummaries`.+ assert [q["jobId"] for q in body["queuedJobs"]] == [job_id]+ assert body["inProgressJobs"] == []+ finally:+ _cleanup(iot_client, jobs=[job_id], things=[thing])+++def test_iot_thing_literally_named_jobs_still_does_thing_crud(+ iot_client, iot_jobs_data+):+ """`jobs` is a legal thing name, so `/things/jobs` is thing CRUD — not the+ jobs collection. Recognizing the jobs routes by a bare `jobs` substring+ instead of the segment AFTER the thing name broke create/describe/delete+ for such a thing with an `Unsupported IoT path` 400."""+ thing = "jobs"+ job_id = _unique("job")+ try:+ thing_arn = _create_thing(iot_client, thing)+ assert iot_client.describe_thing(thingName=thing)["thingName"] == thing++ # One segment deeper, the thing's own job routes still work.+ iot_client.create_job(jobId=job_id, targets=[thing_arn], document=_DOCUMENT)+ assert [+ s["jobId"]+ for s in iot_client.list_job_executions_for_thing(thingName=thing)[+ "executionSummaries"+ ]+ ] == [job_id]+ assert [+ q["jobId"]+ for q in iot_jobs_data.get_pending_job_executions(thingName=thing)[+ "queuedJobs"+ ]+ ] == [job_id]++ _cleanup(iot_client, jobs=[job_id])+ iot_client.delete_thing(thingName=thing)+ with pytest.raises(ClientError) as ei:+ iot_client.describe_thing(thingName=thing)+ assert ei.value.response["Error"]["Code"] == "ResourceNotFoundException"+ finally:+ _cleanup(iot_client, jobs=[job_id], things=[thing])+++def test_iot_jobs_next_sentinel_peek_then_start(iot_client, iot_jobs_data):+ 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)++ # GET $next is a peek: it must not start the execution.+ peeked = iot_jobs_data.describe_job_execution(+ jobId="$next", thingName=thing+ )["execution"]+ assert peeked["jobId"] == job_id+ assert peeked["status"] == "QUEUED"+ assert peeked["versionNumber"] == 1+ assert peeked["jobDocument"] == _DOCUMENT++ # PUT $next starts it.+ started = iot_jobs_data.start_next_pending_job_execution(thingName=thing)+ assert started["execution"]["status"] == "IN_PROGRESS"++ # Nothing further queued: peeking now returns the in-progress one.+ again = iot_jobs_data.describe_job_execution(+ jobId="$next", thingName=thing+ )["execution"]+ assert again["status"] == "IN_PROGRESS"+ finally:+ _cleanup(iot_client, jobs=[job_id], things=[thing])+++def test_iot_jobs_start_next_empty_for_idle_thing(iot_client, iot_jobs_data):+ thing = _unique("jobs-thing")+ try:+ _create_thing(iot_client, thing)+ resp = iot_jobs_data.start_next_pending_job_execution(thingName=thing)+ assert "execution" not in resp+ finally:+ _cleanup(iot_client, things=[thing])+++# ---------------------------------------------------------------------------+# SNAPSHOT vs CONTINUOUS group targeting+# ---------------------------------------------------------------------------+++def test_iot_jobs_snapshot_vs_continuous_group_targets(iot_client, iot_jobs_data):+ group = _unique("jobs-group")+ early = _unique("jobs-thing")+ late = _unique("jobs-thing")+ snapshot_job = _unique("job-snap")+ continuous_job = _unique("job-cont")+ try:+ group_arn = iot_client.create_thing_group(thingGroupName=group)[+ "thingGroupArn"+ ]+ _create_thing(iot_client, early)+ iot_client.add_thing_to_thing_group(thingGroupName=group, thingName=early)++ iot_client.create_job(+ jobId=snapshot_job, targets=[group_arn], document=_DOCUMENT,+ targetSelection="SNAPSHOT",+ )+ iot_client.create_job(+ jobId=continuous_job, targets=[group_arn], document=_DOCUMENT,+ targetSelection="CONTINUOUS",+ )++ # A thing added AFTER job creation: the SNAPSHOT job resolved its+ # membership once at create time and never sees it; the CONTINUOUS+ # job re-resolves lazily and does.+ _create_thing(iot_client, late)+ iot_client.add_thing_to_thing_group(thingGroupName=group, thingName=late)++ late_jobs = {+ q["jobId"]+ for q in iot_jobs_data.get_pending_job_executions(thingName=late)[+ "queuedJobs"+ ]+ }+ assert continuous_job in late_jobs+ assert snapshot_job not in late_jobs++ early_jobs = {+ s["jobId"]+ for s in iot_client.list_job_executions_for_thing(thingName=early)[+ "executionSummaries"+ ]+ }+ assert {snapshot_job, continuous_job} <= early_jobs++ # ListJobs filters on targetSelection, not just status.+ continuous_listed = {+ j["jobId"]+ for j in iot_client.list_jobs(targetSelection="CONTINUOUS")["jobs"]+ }+ assert continuous_job in continuous_listed+ assert snapshot_job not in continuous_listed+ snapshot_listed = {+ j["jobId"]+ for j in iot_client.list_jobs(targetSelection="SNAPSHOT")["jobs"]+ }+ assert snapshot_job in snapshot_listed+ assert continuous_job not in snapshot_listed+ finally:+ _cleanup(+ iot_client,+ jobs=[snapshot_job, continuous_job],+ things=[early, late],+ groups=[group],+ )+++def test_iot_jobs_continuous_late_thing_first_call_is_update(+ iot_client, iot_jobs_data+):+ """A thing added to a CONTINUOUS job's target group after creation must+ be servable even when its very FIRST data-plane call is+ UpdateJobExecution — the execution materializes lazily on that call, like+ on every other data-plane read."""+ group = _unique("jobs-group")+ late = _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",+ )++ _create_thing(iot_client, late)+ iot_client.add_thing_to_thing_group(thingGroupName=group, thingName=late)++ updated = iot_jobs_data.update_job_execution(+ jobId=job_id,+ thingName=late,+ status="IN_PROGRESS",+ includeJobExecutionState=True,+ )+ state = updated["executionState"]+ assert state["status"] == "IN_PROGRESS"+ assert state["versionNumber"] == 2 # materialized at 1, update bumped+ finally:+ _cleanup(iot_client, jobs=[job_id], things=[late], groups=[group])+++# ---------------------------------------------------------------------------+# Listing + cancel/delete paths+# ---------------------------------------------------------------------------+++def test_iot_jobs_list_executions_and_cancel_execution(iot_client):+ 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)++ listed = iot_client.list_job_executions_for_thing(thingName=thing)+ summaries = [+ s for s in listed["executionSummaries"] if s["jobId"] == job_id+ ]+ assert len(summaries) == 1+ summary = summaries[0]["jobExecutionSummary"]+ assert summary["status"] == "QUEUED"+ assert summary["executionNumber"] == 1+ assert isinstance(summary["queuedAt"], datetime)++ iot_client.cancel_job_execution(jobId=job_id, thingName=thing)+ execution = iot_client.describe_job_execution(+ jobId=job_id, thingName=thing+ )["execution"]+ assert execution["status"] == "CANCELED"+ assert execution["versionNumber"] == 2+ assert execution["thingArn"] == thing_arn++ with pytest.raises(ClientError) as ei:+ iot_client.cancel_job_execution(jobId=job_id, thingName=thing)+ assert (+ ei.value.response["Error"]["Code"] == "InvalidStateTransitionException"+ )+ finally:+ _cleanup(iot_client, jobs=[job_id], things=[thing])+++def test_iot_jobs_cancel_job_and_delete(iot_client, iot_jobs_data):+ 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)++ # An IN_PROGRESS job cannot be deleted without force.+ with pytest.raises(ClientError) as ei:+ iot_client.delete_job(jobId=job_id)+ assert (+ ei.value.response["Error"]["Code"] == "InvalidStateTransitionException"+ )++ canceled = iot_client.cancel_job(jobId=job_id, comment="rollback")+ assert canceled["jobId"] == job_id++ job = iot_client.describe_job(jobId=job_id)["job"]+ assert job["status"] == "CANCELED"+ # Canceling the job canceled its QUEUED execution too.+ assert job["jobProcessDetails"]["numberOfCanceledThings"] == 1+ assert (+ iot_jobs_data.get_pending_job_executions(thingName=thing)["queuedJobs"]+ == []+ )++ listed = iot_client.list_jobs(status="CANCELED")+ assert job_id in {j["jobId"] for j in listed["jobs"]}++ # A canceled job deletes without force, and is then really gone.+ iot_client.delete_job(jobId=job_id)+ with pytest.raises(ClientError) as ei:+ iot_client.describe_job(jobId=job_id)+ assert ei.value.response["Error"]["Code"] == "ResourceNotFoundException"+ assert (+ iot_client.list_job_executions_for_thing(thingName=thing)[+ "executionSummaries"+ ]+ == []+ )+ finally:+ _cleanup(iot_client, things=[thing])+++# ---------------------------------------------------------------------------+# CancelJob with in-flight executions + control-plane version conflicts+# ---------------------------------------------------------------------------+++def test_iot_jobs_cancel_job_without_force_leaves_in_progress(+ iot_client, iot_jobs_data+):+ """CancelJob without force cancels the job but leaves an IN_PROGRESS+ execution untouched — only QUEUED executions are swept, as on AWS."""+ 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)+ started = iot_jobs_data.start_next_pending_job_execution(thingName=thing)+ assert started["execution"]["status"] == "IN_PROGRESS"++ iot_client.cancel_job(jobId=job_id)++ job = iot_client.describe_job(jobId=job_id)["job"]+ assert job["status"] == "CANCELED"+ execution = iot_client.describe_job_execution(+ jobId=job_id, thingName=thing+ )["execution"]+ assert execution["status"] == "IN_PROGRESS"+ assert execution["versionNumber"] == 2 # only the start bumped it+ finally:+ _cleanup(iot_client, jobs=[job_id], things=[thing])+++def test_iot_jobs_cancel_job_force_cancels_in_progress(+ iot_client, iot_jobs_data+):+ """CancelJob with force=True also cancels IN_PROGRESS executions and+ bumps their versionNumber."""+ 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)+ started = iot_jobs_data.start_next_pending_job_execution(thingName=thing)+ assert started["execution"]["versionNumber"] == 2++ iot_client.cancel_job(jobId=job_id, force=True)++ execution = iot_client.describe_job_execution(+ jobId=job_id, thingName=thing+ )["execution"]+ assert execution["status"] == "CANCELED"+ assert execution["versionNumber"] == 3 # force-cancel bumped it again+ finally:+ _cleanup(iot_client, jobs=[job_id], things=[thing])+++def test_iot_jobs_cancel_execution_wrong_expected_version(iot_client):+ """Control-plane CancelJobExecution with a stale expectedVersion is+ rejected with VersionConflictException (modeled in the `iot` service+ model, so boto3 surfaces the code) and leaves the execution untouched."""+ 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)++ with pytest.raises(ClientError) as ei:+ iot_client.cancel_job_execution(+ jobId=job_id, thingName=thing, force=True, expectedVersion=5+ )+ error = ei.value.response["Error"]+ assert error["Code"] == "VersionConflictException"+ assert "current version 1" in error["Message"]++ execution = iot_client.describe_job_execution(+ jobId=job_id, thingName=thing+ )["execution"]+ assert execution["status"] == "QUEUED"+ assert execution["versionNumber"] == 1+ finally:+ _cleanup(iot_client, jobs=[job_id], things=[thing])+++# ---------------------------------------------------------------------------+# Request validation: targets, jobId, targetSelection+# ---------------------------------------------------------------------------+++def test_iot_jobs_create_rejects_targets_outside_the_callers_scope(iot_client):+ """A thing ARN from another region or account names nothing this caller can+ target — the resolver skips it, so a job accepted on such a target+ materializes zero executions, never auto-completes, and can only be deleted+ with force. AWS answers ResourceNotFoundException; validation therefore+ gates on the same scope check the resolver applies, not on the ARN's+ resource segment alone."""+ thing = _unique("jobs-thing")+ job_id = _unique("job")+ try:+ thing_arn = _create_thing(iot_client, thing)+ foreign_arns = [+ _swap_arn_field(thing_arn, 3, "eu-central-1"), # another region+ _swap_arn_field(thing_arn, 4, "999999999999"), # another account+ ]+ for arn in foreign_arns:+ with pytest.raises(ClientError) as ei:+ iot_client.create_job(+ jobId=job_id, targets=[arn], document=_DOCUMENT+ )+ assert (+ ei.value.response["Error"]["Code"] == "ResourceNotFoundException"+ ), arn+ assert ei.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404++ # A mixed target list is rejected on the foreign member too — one bad+ # target must not create a job whose fleet is quietly short.+ with pytest.raises(ClientError) as ei:+ iot_client.create_job(+ jobId=job_id,+ targets=[thing_arn, foreign_arns[0]],+ document=_DOCUMENT,+ )+ assert ei.value.response["Error"]["Code"] == "ResourceNotFoundException"++ # Nothing was created — not even a shell of a job to get stuck.+ with pytest.raises(ClientError) as ei:+ iot_client.describe_job(jobId=job_id)+ assert ei.value.response["Error"]["Code"] == "ResourceNotFoundException"+ finally:+ _cleanup(iot_client, jobs=[job_id], things=[thing])+++def test_iot_jobs_create_rejects_job_ids_the_models_forbid(iot_client):+ """Both service models declare JobId as `[a-zA-Z0-9_-]` with max 64 —+ stricter than the thing-name pattern. A jobId containing `:` would be+ accepted control-side and then be unreachable for the device that has to+ ask for it by id."""+ thing = _unique("jobs-thing")+ accepted = "a" * 64+ try:+ thing_arn = _create_thing(iot_client, thing)+ for job_id in ("job:with:colons", "j" * 65, "job.with.dots"):+ with pytest.raises(ClientError) as ei:+ iot_client.create_job(+ jobId=job_id, targets=[thing_arn], document=_DOCUMENT+ )+ error = ei.value.response["Error"]+ assert error["Code"] == "InvalidRequestException", job_id+ assert ei.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400+ assert "jobId" in error["Message"]++ # The 64-character boundary itself is legal.+ iot_client.create_job(+ jobId=accepted, targets=[thing_arn], document=_DOCUMENT+ )+ assert iot_client.describe_job(jobId=accepted)["job"]["jobId"] == accepted+ finally:+ _cleanup(iot_client, jobs=[accepted], things=[thing])+++def test_iot_jobs_create_rejects_unknown_target_selection(iot_client):+ """targetSelection is a two-value enum (SNAPSHOT | CONTINUOUS) that botocore+ does not enforce client-side. An unrecognized value used to be stored+ verbatim, where it read as "not CONTINUOUS" — silently snapshotting a job+ the caller asked to be something else."""+ thing = _unique("jobs-thing")+ job_id = _unique("job")+ try:+ thing_arn = _create_thing(iot_client, thing)+ for selection in ("ROLLING", "snapshot", ""):+ with pytest.raises(ClientError) as ei:+ iot_client.create_job(+ jobId=job_id,+ targets=[thing_arn],+ document=_DOCUMENT,+ targetSelection=selection,+ )+ error = ei.value.response["Error"]+ assert error["Code"] == "InvalidRequestException", selection+ assert ei.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400+ with pytest.raises(ClientError):+ iot_client.describe_job(jobId=job_id)+ finally:+ _cleanup(iot_client, jobs=[job_id], things=[thing])+++# ---------------------------------------------------------------------------+# Thing deletion sweeps the thing's executions+# ---------------------------------------------------------------------------+++def test_iot_jobs_deleting_a_thing_sweeps_its_execution_and_unblocks_the_job(+ iot_client, iot_jobs_data+):+ """A job execution belongs to its thing: deleting the thing must take the+ execution with it. Left behind, the execution of a thing that no longer+ exists is a non-terminal execution nobody can ever report on, holding its+ job out of COMPLETED forever."""+ reporting = _unique("jobs-thing")+ deleted = _unique("jobs-thing")+ job_id = _unique("job")+ try:+ reporting_arn = _create_thing(iot_client, reporting)+ deleted_arn = _create_thing(iot_client, deleted)+ iot_client.create_job(+ jobId=job_id,+ targets=[reporting_arn, deleted_arn],+ document=_DOCUMENT,+ )+ iot_jobs_data.update_job_execution(+ jobId=job_id, thingName=reporting, status="SUCCEEDED"+ )+ job = iot_client.describe_job(jobId=job_id)["job"]+ assert job["status"] == "IN_PROGRESS"+ assert job["jobProcessDetails"]["numberOfQueuedThings"] == 1++ iot_client.delete_thing(thingName=deleted)++ job = iot_client.describe_job(jobId=job_id)["job"]+ assert job["status"] == "COMPLETED"+ details = job["jobProcessDetails"]+ assert details["numberOfQueuedThings"] == 0+ assert details["numberOfSucceededThings"] == 1+ with pytest.raises(ClientError) as ei:+ iot_client.describe_job_execution(jobId=job_id, thingName=deleted)+ assert ei.value.response["Error"]["Code"] == "ResourceNotFoundException"+ finally:+ _cleanup(iot_client, jobs=[job_id], things=[reporting, deleted])+++def test_iot_jobs_recreated_thing_starts_with_no_execution_history(+ iot_client, iot_jobs_data+):+ """Thing names are reusable, so a swept execution must really be gone: a+ new thing registered under a deleted one's name would otherwise inherit its+ predecessor's in-flight job and be handed a rollout it was never a target+ of."""+ 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)+ started = iot_jobs_data.start_next_pending_job_execution(thingName=thing)+ assert started["execution"]["status"] == "IN_PROGRESS"++ iot_client.delete_thing(thingName=thing)+ _create_thing(iot_client, thing)++ assert (+ iot_client.list_job_executions_for_thing(thingName=thing)[+ "executionSummaries"+ ]+ == []+ )+ pending = iot_jobs_data.get_pending_job_executions(thingName=thing)+ assert pending["queuedJobs"] == []+ assert pending["inProgressJobs"] == []+ with pytest.raises(ClientError) as ei:+ iot_jobs_data.describe_job_execution(jobId=job_id, thingName=thing)+ assert ei.value.response["Error"]["Code"] == "ResourceNotFoundException"+ finally:+ _cleanup(iot_client, jobs=[job_id], things=[thing])+++# ---------------------------------------------------------------------------+# statusDetails: nested on the control plane, flat on the device plane+# ---------------------------------------------------------------------------+++def test_iot_jobs_status_details_are_nested_on_the_control_plane_only(+ iot_client, iot_jobs_data+):+ """The same map has two shapes: the `iot` model wraps it in+ JobExecutionStatusDetails (`{"detailsMap": {...}}`) while `iot-jobs-data`+ returns it flat. Emitting the flat map on the control plane would leave+ boto3's `statusDetails["detailsMap"]` missing; emitting the nested one on+ the device plane would break every device reading its own progress keys."""+ thing = _unique("jobs-thing")+ job_id = _unique("job")+ details = {"step": "download", "percent": "40"}+ try:+ thing_arn = _create_thing(iot_client, thing)+ iot_client.create_job(jobId=job_id, targets=[thing_arn], document=_DOCUMENT)++ iot_jobs_data.update_job_execution(+ jobId=job_id,+ thingName=thing,+ status="IN_PROGRESS",+ statusDetails=details,+ )+ control = iot_client.describe_job_execution(+ jobId=job_id, thingName=thing+ )["execution"]+ assert control["statusDetails"] == {"detailsMap": details}+ device = iot_jobs_data.describe_job_execution(+ jobId=job_id, thingName=thing+ )["execution"]+ assert device["statusDetails"] == details++ # The control plane's own writer (CancelJobExecution takes a FLAT+ # statusDetails map) round-trips into the same two shapes.+ cancel_details = {"reason": "superseded"}+ iot_client.cancel_job_execution(+ jobId=job_id, thingName=thing, force=True, statusDetails=cancel_details+ )+ control = iot_client.describe_job_execution(+ jobId=job_id, thingName=thing+ )["execution"]+ assert control["status"] == "CANCELED"+ assert control["statusDetails"] == {"detailsMap": cancel_details}+ device = iot_jobs_data.describe_job_execution(+ jobId=job_id, thingName=thing+ )["execution"]+ assert device["statusDetails"] == cancel_details+ finally:+ _cleanup(iot_client, jobs=[job_id], things=[thing])+++# ---------------------------------------------------------------------------+# Not-found paths and list filters+# ---------------------------------------------------------------------------+++def test_iot_jobs_unknown_job_is_not_found_on_every_path(+ iot_client, iot_jobs_data+):+ """Every read and mutate path answers ResourceNotFoundException (404) for a+ job that does not exist — no 400s, no empty 200s, on either plane."""+ thing = _unique("jobs-thing")+ ghost = _unique("ghost-job")+ try:+ _create_thing(iot_client, thing)+ calls = {+ "DescribeJob": lambda: iot_client.describe_job(jobId=ghost),+ "GetJobDocument": lambda: iot_client.get_job_document(jobId=ghost),+ "CancelJob": lambda: iot_client.cancel_job(jobId=ghost),+ "DeleteJob": lambda: iot_client.delete_job(jobId=ghost),+ "DescribeJobExecution": lambda: iot_client.describe_job_execution(+ jobId=ghost, thingName=thing+ ),+ "CancelJobExecution": lambda: iot_client.cancel_job_execution(+ jobId=ghost, thingName=thing+ ),+ "data:DescribeJobExecution": (+ lambda: iot_jobs_data.describe_job_execution(+ jobId=ghost, thingName=thing+ )+ ),+ "data:UpdateJobExecution": (+ lambda: iot_jobs_data.update_job_execution(+ jobId=ghost, thingName=thing, status="SUCCEEDED"+ )+ ),+ }+ for label, call in calls.items():+ with pytest.raises(ClientError) as ei:+ call()+ assert (+ ei.value.response["Error"]["Code"] == "ResourceNotFoundException"+ ), label+ assert (+ ei.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404+ ), label+ finally:+ _cleanup(iot_client, things=[thing])+++def test_iot_jobs_list_executions_for_thing_filters(iot_client, iot_jobs_data):+ """ListJobExecutionsForThing narrows by `status` (modeled) and by `jobId`+ (a MiniStack convenience the `iot` model does not declare, so only raw HTTP+ can send it) — an unfiltered list must not be served for either."""+ thing = _unique("jobs-thing")+ queued_job = _unique("job-queued")+ done_job = _unique("job-done")+ try:+ thing_arn = _create_thing(iot_client, thing)+ for job_id in (queued_job, done_job):+ iot_client.create_job(+ jobId=job_id, targets=[thing_arn], document=_DOCUMENT+ )+ iot_jobs_data.update_job_execution(+ jobId=done_job, thingName=thing, status="SUCCEEDED"+ )++ def listed(**kwargs):+ return {+ s["jobId"]+ for s in iot_client.list_job_executions_for_thing(+ thingName=thing, **kwargs+ )["executionSummaries"]+ }++ assert listed() == {queued_job, done_job}+ assert listed(status="QUEUED") == {queued_job}+ assert listed(status="SUCCEEDED") == {done_job}+ assert listed(status="FAILED") == set()++ status, body = _raw(+ _IOT_AUTH, "GET", f"/things/{quote(thing)}/jobs?jobId={quote(done_job)}"+ )+ assert status == 200+ assert [s["jobId"] for s in body["executionSummaries"]] == [done_job]+ finally:+ _cleanup(iot_client, jobs=[queued_job, done_job], things=[thing])+++# ---------------------------------------------------------------------------+# Account / region isolation+# ---------------------------------------------------------------------------+++def test_iot_jobs_do_not_bleed_across_accounts_or_regions():+ """Two accounts may hold the same jobId over a same-named thing without+ seeing each other's job, document, or execution — and the same account in+ another region is a third, separate scope. Both stores are keyed by+ (account, region), and the ARNs each caller reads back must say so."""+ job_id = _unique("job")+ thing = _unique("jobs-thing")+ a = _account_client("iot", "111111111111")+ b = _account_client("iot", "222222222222")+ a_eu = _account_client("iot", "111111111111", region="eu-west-1")+ a_device = _account_client("iot-jobs-data", "111111111111")+ try:+ for client, document in ((a, '{"op": "a"}'), (b, '{"op": "b"}')):+ thing_arn = client.create_thing(thingName=thing)["thingArn"]+ client.create_job(+ jobId=job_id, targets=[thing_arn], document=document+ )++ assert a.get_job_document(jobId=job_id)["document"] == '{"op": "a"}'+ assert b.get_job_document(jobId=job_id)["document"] == '{"op": "b"}'+ assert a.describe_job(jobId=job_id)["job"]["targets"] == [+ f"arn:aws:iot:us-east-1:111111111111:thing/{thing}"+ ]+ assert b.describe_job(jobId=job_id)["job"]["jobArn"].startswith(+ "arn:aws:iot:us-east-1:222222222222:"+ )++ # Another region of account A is a scope of its own.+ with pytest.raises(ClientError) as ei:+ a_eu.describe_job(jobId=job_id)+ assert ei.value.response["Error"]["Code"] == "ResourceNotFoundException"+ assert job_id not in {j["jobId"] for j in a_eu.list_jobs()["jobs"]}++ # A's device reporting done completes A's job only.+ a_device.update_job_execution(+ jobId=job_id, thingName=thing, status="SUCCEEDED"+ )+ assert a.describe_job(jobId=job_id)["job"]["status"] == "COMPLETED"+ b_job = b.describe_job(jobId=job_id)["job"]+ assert b_job["status"] == "IN_PROGRESS"+ assert b_job["jobProcessDetails"]["numberOfQueuedThings"] == 1++ # Deleting A's job leaves B's standing.+ a.delete_job(jobId=job_id, force=True)+ assert b.describe_job(jobId=job_id)["job"]["jobId"] == job_id+ finally:+ for client in (a, b):+ _cleanup(client, jobs=[job_id], things=[thing])+++def test_iot_jobs_lists_do_not_paginate_and_return_no_token(iot_client):+ """ListJobs / ListJobExecutionsForThing serve one unbounded page.++ ``maxResults`` and ``nextToken`` are accepted (botocore validates them+ client-side) and ignored, and no ``nextToken`` is ever returned - a+ paginator terminates after one page instead of looping. Pinned so a+ future partial implementation cannot change the shape silently.+ """+ thing = _unique("jobs-thing")+ job_a = _unique("job")+ job_b = _unique("job")+ try:+ thing_arn = _create_thing(iot_client, thing)+ for job_id in (job_a, job_b):+ iot_client.create_job(+ jobId=job_id, targets=[thing_arn], document=_DOCUMENT+ )++ listed = iot_client.list_jobs(maxResults=1)+ ours = {j["jobId"] for j in listed["jobs"]} & {job_a, job_b}+ assert ours == {job_a, job_b}, "maxResults is ignored, not honored"+ assert "nextToken" not in listed++ executions = iot_client.list_job_executions_for_thing(+ thingName=thing, maxResults=1+ )+ assert len(executions["executionSummaries"]) == 2+ assert "nextToken" not in executions+ finally:+ _cleanup(iot_client, jobs=[job_a, job_b], things=[thing])diff --git a/tests/test_persistence.py b/tests/test_persistence.pyindex 69edb208..925c6c9e 100644--- a/tests/test_persistence.py+++ b/tests/test_persistence.py@@ -2422,6 +2422,61 @@ def test_eventbridge_region_scoped_stores_survive_warm_boot_in_original_scope():set_request_region(original_region)+# ── iot._jobs / iot._job_executions (tuple execution keys) ─────────────++def test_iot_jobs_and_executions_survive_warm_boot():+ """Jobs are keyed by jobId but executions by a (thingName, jobId) TUPLE —+ the on-disk JSON path must round-trip both (tuple keys ride the+ repr()/literal_eval leg of the scoped-dict encoder). A drop here would+ silently orphan every in-flight OTA rollout on restart."""+ mod = _get_module("iot")+ mod.reset()+ job_id = "persisted-job"+ thing = "persisted-thing"+ now_ms = 1700000000000+ mod._jobs[job_id] = {+ "jobId": job_id,+ "jobArn": f"arn:aws:iot:us-east-1:000000000000:job/{job_id}",+ "description": None,+ "targets": [f"arn:aws:iot:us-east-1:000000000000:thing/{thing}"],+ "targetSelection": "SNAPSHOT",+ "document": "{\"operation\": \"reboot\"}",+ "documentSource": None,+ "status": "IN_PROGRESS",+ "createdAt": now_ms,+ "lastUpdatedAt": now_ms,+ "completedAt": None,+ "presignedUrlConfig": {},+ "jobExecutionsRolloutConfig": {},+ "snapshotted": True,+ }+ mod._job_executions[(thing, job_id)] = {+ "jobId": job_id,+ "thingName": thing,+ "status": "IN_PROGRESS",+ "statusDetails": {"progress": "42"},+ "queuedAt": now_ms,+ "startedAt": now_ms,+ "lastUpdatedAt": now_ms,+ "executionNumber": 1,+ "versionNumber": 2,+ }++ _round_trip_dict(mod, "iot")++ job = mod._jobs.get(job_id)+ assert job is not None, "_jobs lost across save_state -> load_state"+ assert job["status"] == "IN_PROGRESS"+ execution = mod._job_executions.get((thing, job_id))+ assert execution is not None, (+ "_job_executions lost across save_state -> load_state — the "+ "(thingName, jobId) tuple key must survive JSON persistence."+ )+ assert execution["versionNumber"] == 2+ assert execution["statusDetails"] == {"progress": "42"}+ mod.reset()++def test_eventbridge_legacy_account_scoped_targets_restore_to_rule_region():"""Legacy target stores are scoped to the EventBridge rule region, not thetarget ARN region, when migrating from account-only persistence."""diff --git a/tests/test_router.py b/tests/test_router.pyindex 79dd8969..8cbe7423 100644--- a/tests/test_router.py+++ b/tests/test_router.py@@ -103,3 +103,44 @@ def test_unknown_opensearch_version_path_still_falls_back_to_s3():assert detect_service("POST", "/2021-01-01/not-opensearch/domain/example/config", _HEADERS, {}) == "s3"+++def _sigv4_headers(service):+ return {+ "host": "localhost:4566",+ "authorization": (+ "AWS4-HMAC-SHA256 "+ f"Credential=test/20260811/us-east-1/{service}/aws4_request, "+ "SignedHeaders=host, Signature=fake"+ ),+ }+++def test_iot_jobs_data_credential_scope_routes():+ """The SDK signs iot-jobs-data requests with the `iot-jobs-data` scope+ (botocore signingName); the same path signed with `iot` must stay on the+ control plane — GET /things/{t}/jobs is GetPendingJobExecutions on one+ client and ListJobExecutionsForThing on the other."""+ assert detect_service(+ "GET", "/things/t1/jobs", _sigv4_headers("iot-jobs-data"), {}+ ) == "iot-jobs-data"+ assert detect_service("GET", "/things/t1/jobs", _sigv4_headers("iot"), {}) == "iot"+++ "host",+ [+ # What DescribeEndpoint(endpointType="iot:Jobs") actually hands out —+ # a device following the documented flow signs against exactly this.+ "a1b2c3.jobs.iot.us-east-1.localhost:4566",+ # The spelling the AWS Device SDK's jobs documentation uses.+ "a1b2c3.data.jobs.iot.us-east-1.localhost:4566",+ ],+)+def test_iot_jobs_data_host_routes_before_iot(host):+ """Both jobs-endpoint spellings also match the `iot\\.` regex — the+ iot-jobs-data entry must win via pattern ordering, or the request lands on+ the control plane where GET /things/{t}/jobs is a different operation."""+ assert detect_service(+ "GET", "/things/t1/jobs/$next", {"host": host}, {}+ ) == "iot-jobs-data"