diff --git a/.github/workflows/demo-runtime.yml b/.github/workflows/demo-runtime.yml new file mode 100644 index 0000000..c31b247 --- /dev/null +++ b/.github/workflows/demo-runtime.yml @@ -0,0 +1,32 @@ +name: Demo runtime +on: + pull_request: + push: + branches: [main] +permissions: + contents: read +jobs: + test: + runs-on: ubuntu-24.04 + timeout-minutes: 10 + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 + - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 + with: + python-version: '3.12' + - id: model + run: echo "commit=$(cat iot-digital-twin-simulator/model-commit.txt)" >> "$GITHUB_OUTPUT" + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 + with: + repository: usekarma/iot-digital-twin + ref: ${{ steps.model.outputs.commit }} + path: model-source + persist-credentials: false + - run: python -m pip install -r requirements-dev.txt + - run: make test lint test-demo package-demo MODEL_REPO=model-source RUFF=ruff + - run: PYTHONPATH=dist/iot-digital-twin-simulator.zip python -m unittest discover -s iot-digital-twin-simulator/tests -v + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 + with: + name: iot-digital-twin-simulator-${{ github.sha }} + path: dist/iot-digital-twin-simulator.zip + retention-days: 14 diff --git a/Makefile b/Makefile index f315d53..928bc07 100644 --- a/Makefile +++ b/Makefile @@ -7,8 +7,16 @@ test: PYTHONPATH=iot-digital-twin-ingest $(PYTHON) -m unittest discover -s iot-digital-twin-ingest/tests -v lint: - $(RUFF) check iot-digital-twin-ingest scripts - $(RUFF) format --check iot-digital-twin-ingest scripts + $(RUFF) check iot-digital-twin-ingest iot-digital-twin-simulator scripts + $(RUFF) format --check iot-digital-twin-ingest iot-digital-twin-simulator scripts package: $(PYTHON) scripts/package.py + +.PHONY: test-demo +test-demo: + PYTHONPATH=iot-digital-twin-simulator:$(MODEL_REPO)/src $(PYTHON) -m unittest discover -s iot-digital-twin-simulator/tests -v + +.PHONY: package-demo +package-demo: + $(PYTHON) scripts/package_demo.py --model-repo $(MODEL_REPO) --model-commit $(shell cat iot-digital-twin-simulator/model-commit.txt) diff --git a/iot-digital-twin-simulator/README.md b/iot-digital-twin-simulator/README.md new file mode 100644 index 0000000..528a9e2 --- /dev/null +++ b/iot-digital-twin-simulator/README.md @@ -0,0 +1,51 @@ +# iot-digital-twin-simulator runtime + +Consumes the existing simulator/traces rather than copying their rules. DynamoStore +uses strongly consistent reads, revision/epoch/fence conditions, atomic reset + receipt +transactions, persisted ACK budgets and five-second publication claims. Receipts precede +publication; a publish/mark-sent crash may duplicate an ACK but never repeats the reset. + +Handlers: app.start_handler (IAM-only initializer), app.runner_handler (bounded execution +and lease renewal), app.reset_handler (trusted IoT projection). No HTTP adapter added. +Required environment: STATE_TABLE, MODEL_COMMIT, ACTIVE_SESSION (fresh 32-hex ID), +EXPECTED_PRINCIPAL, REQUEST_TOPIC, ACK_TOPIC. MODEL_COMMIT must match package provenance +and persisted state. Five assets, seed 17, six ticks/epoch, 180-second session, three +resets maximum. Dynamo SDK attempts total two; IoT publication one per durable claim. + +Run make test-demo MODEL_REPO=/path/to/iot-digital-twin. Package with: +python3 scripts/package_demo.py --model-repo /path/to/iot-digital-twin --model-commit FULL_REVIEWED_SHA +ZIP includes runtime/model imports and provenance. No extra model implementation. +AWS provides boto3/botocore; clients are lazy and injected in local tests. + +Controlled integration: scripts/test_demo_integration.py refuses AWS calls unless +--execute-approved-writes, profile, region, expected account, table and model revision +are provided. Verify separate human approval for exact writes first. It checks STS, +sandbox tag and PK/SK schema, writes a new isolated session in an EXISTING table, +checks real conditional updates/reset receipts and records ACK LOCALLY (no MQTT). +Session rows are retained for approved cleanup; no resources/permissions are changed. +PYTHONPATH must point at the same reviewed simulator or extracted runtime package. + +Limits: no live AWS proof. Mock tests inspect API requests, not actual transaction +execution. Runner does not dispatch pending ACKs: reset Lambda retries or supervised +same-command redelivery recover failed publication within deadline/three-claim bounds. +No HTTP dashboard, automatic restart, device subscription or LED proof implemented. +Trust requires scoped IoT invocation and explicit principal()/topic() projection; direct +Lambda invokers must not be able to forge reset authority. SDK implementation is in +aws-lambda; Terraform/IAM in aws-iac; settings/artifacts in aws-config. + +Runner invocation: {session_id: ACTIVE_SESSION, operation: start} initializes once +then runs; {session_id: ACTIVE_SESSION} recovers an expired lease within its unchanged +deadline. These IAM-only commands are not HTTP endpoints. Artifact pin: +8e2f732127ce19936711346d3c1a50ed3b9b728a. Nine mocked-client tests passed both from +source and the built ZIP; 17 existing ingestion tests passed. Ruff 0.11.13 checks/format +and Bandit runtime scan passed. Two builds produced identical artifact SHA-256: +70c95cde1b448c6daf405ff680da06c971b30ad625270524d7752e9df7168cab. +Integration guard without execution flag exited 2 before SDK import or AWS calls. +No real DynamoDB/IoT test was executed. The companion aws-iac component provides +review-only concrete table/Lambda/IAM/rule wiring; aws-config declaration and resolved +artifact/principal/account/session bindings remain prerequisites for an approved plan. + +Naming revision: deployment component and ZIP basename are iot-digital-twin-simulator. +Project is iot-digital-twin; Experiment is atom-lite-simulator. Runtime calculations, +state/reset/ACK contracts and packaged ZIP bytes are unchanged. Rechecked all 26 +source tests, nine ZIP tests, Ruff and Bandit after renaming; no AWS calls were made. diff --git a/iot-digital-twin-simulator/app.py b/iot-digital-twin-simulator/app.py new file mode 100644 index 0000000..b248e8e --- /dev/null +++ b/iot-digital-twin-simulator/app.py @@ -0,0 +1,109 @@ +"""AWS Lambda entrypoints; construction is lazy and makes no calls during import.""" + +from __future__ import annotations + +import json +import os +from pathlib import Path +import time +from typing import Any + +from runtime import Conflict, DynamoStore, session_id + + +def clients() -> tuple[DynamoStore, Any]: + import boto3 + from botocore.config import Config + + model_commit = os.environ["MODEL_COMMIT"] + provenance = json.loads( + Path(__file__).with_name("model-provenance.json").read_text() + ) + if provenance["model_commit"] != model_commit: + raise ValueError("artifact/model revision mismatch") + config = Config(connect_timeout=2, read_timeout=3, retries={"max_attempts": 1}) + return DynamoStore( + boto3.client("dynamodb", config=config), os.environ["STATE_TABLE"], model_commit + ), boto3.client( + "iot-data", + config=Config( + connect_timeout=2, read_timeout=3, retries={"total_max_attempts": 1} + ), + ) + + +def reset_handler(event: dict[str, Any], context: Any) -> dict[str, Any]: + if set(event) != { + "session_id", + "command_id", + "expected_epoch", + "principal", + "topic", + }: + raise ValueError("invalid trusted rule projection") + if ( + event["session_id"] != os.environ["ACTIVE_SESSION"] + or event["topic"] != os.environ["REQUEST_TOPIC"] + ): + raise ValueError("inactive session/topic") + store, publisher = clients() + now = int(time.time()) + command = { + key: event[key] for key in ("session_id", "command_id", "expected_epoch") + } + store.reset(command, now, event["principal"], os.environ["EXPECTED_PRINCIPAL"]) + return store.publish_ack( + event["session_id"], + event["command_id"], + now, + publisher, + os.environ["ACK_TOPIC"], + ) + + +def start_handler(event: dict[str, Any], context: Any) -> dict[str, Any]: + """IAM-only supervised initializer; deployment must not expose it publicly.""" + if event != {"session_id": os.environ["ACTIVE_SESSION"]}: + raise ValueError("invalid supervised start") + store, _ = clients() + state = store.start(session_id(event["session_id"]), int(time.time())) + return {"session_id": state["session"], "deadline": state["deadline"]} + + +def runner_handler(event: dict[str, Any], context: Any) -> dict[str, Any]: + """Bounded runner; no automatic new session, lease takeover or indefinite retry.""" + session = session_id(os.environ["ACTIVE_SESSION"]) + if event == {"session_id": session, "operation": "start"}: + store, _ = clients() + store.start(session, int(time.time())) + event = {"session_id": session} + if event != {"session_id": session}: + raise ValueError("invalid supervised invocation") + store, _ = clients() + owner = context.aws_request_id + start = time.monotonic() + state = store.acquire(session, owner, int(time.time())) + fence = state["fence"] + while ( + time.monotonic() - start < 180 and context.get_remaining_time_in_millis() > 5000 + ): + now = int(time.time()) + state = store.read(session) + if ( + state is None + or now >= state["deadline"] + or state["fence"] != fence + or state["owner"] != owner + ): + break + if now >= state["lease_until"]: + break # Expired owner must not silently reacquire. + try: + if state["lease_until"] - now < 5: + state = store.renew(state, now) + if state["tick"] < 6 and now >= state["next_tick"]: + store.tick(state, now) + except Conflict: + pass # Reread on next bounded iteration; never replay a blind write. + time.sleep(1) + return {"status": "stopped", "session_id": session} diff --git a/iot-digital-twin-simulator/model-commit.txt b/iot-digital-twin-simulator/model-commit.txt new file mode 100644 index 0000000..4f18b8b --- /dev/null +++ b/iot-digital-twin-simulator/model-commit.txt @@ -0,0 +1 @@ +8e2f732127ce19936711346d3c1a50ed3b9b728a diff --git a/iot-digital-twin-simulator/runtime.py b/iot-digital-twin-simulator/runtime.py new file mode 100644 index 0000000..d335704 --- /dev/null +++ b/iot-digital-twin-simulator/runtime.py @@ -0,0 +1,387 @@ +"""Executable AWS adapters for the bounded synthetic demo; clients are injected.""" + +from __future__ import annotations + +import json +import re +from dataclasses import asdict, replace +from typing import Any + +from business_app.grid_simulator import GridSimulator, SimulatorConfig + +MODEL_VERSION = "karma-ring-v1" +MAX_BYTES = 65536 + + +class Conflict(Exception): + """Conditional write lost; caller must reread rather than blind retry.""" + + +def integer(value: object, name: str, low: int, high: int) -> int: + if type(value) is not int or not low <= value <= high: + raise ValueError(f"invalid {name}") + return value + + +def session_id(value: object) -> str: + if not isinstance(value, str) or not re.fullmatch("[0-9a-f]{32}", value): + raise ValueError("invalid session_id") + return value + + +def projection(epoch: int, tick: int) -> dict[str, Any]: + """Recover at most six steps using the existing model, including all trace epochs.""" + simulator = GridSimulator(SimulatorConfig()) + trace = None + for _ in range(tick): + trace = simulator.step_traced() + events = tuple(replace(e, epoch=epoch) for e in simulator.snapshot()) + if trace is not None: + trace = replace( + trace, + before=tuple(replace(e, epoch=epoch) for e in trace.before), + disturbance=replace(trace.disturbance, epoch=epoch), + effects=tuple( + replace(e, predecessor=replace(e.predecessor, epoch=epoch)) + for e in trace.effects + ), + transitions=tuple( + replace( + t, + before=replace(t.before, epoch=epoch), + after=replace(t.after, epoch=epoch), + ) + for t in trace.transitions + ), + observations=events, + ) + return { + "observations": [asdict(e) for e in events], + "trace": asdict(trace) if trace else None, + } + + +def expression(condition: str, update: str | None = None) -> dict[str, Any]: + """Alias application attributes to avoid DynamoDB reserved-word ambiguity.""" + names = {} + for field in ( + "revision", + "epoch", + "fence", + "lease_until", + "deadline", + "next_tick", + "attempts", + "ack_until", + "ack_sent", + ): + if re.search(r"\b" + field + r"\b", condition + (update or "")): + names["#" + field] = field + condition = re.sub(r"(? None: + if not re.fullmatch("[0-9a-f]{40}", model_commit): + raise ValueError("invalid model_commit") + self.model_commit = model_commit + self.client, self.table = client, table + + def key(self, session: str, suffix: str = "STATE") -> dict[str, Any]: + return {"PK": {"S": "SESSION#" + session_id(session)}, "SK": {"S": suffix}} + + def read(self, session: str, suffix: str = "STATE") -> dict[str, Any] | None: + response = self.client.get_item( + TableName=self.table, Key=self.key(session, suffix), ConsistentRead=True + ) + item = response.get("Item") + if not item: + return None + value = json.loads(item["document"]["S"]) + if suffix == "STATE": + self.validate(value) + return value + + def validate(self, state: dict[str, Any]) -> None: + if ( + state.get("model") != MODEL_VERSION + or state.get("schema") != 1 + or state.get("model_commit") != self.model_commit + ): + raise ValueError("incompatible persisted model/schema") + session_id(state["session"]) + for field, low, high in [ + ("epoch", 1, 1000000), + ("tick", 0, 6), + ("revision", 0, 1000000), + ("fence", 0, 1000000), + ("reset_count", 0, 3), + ("deadline", 1, 2**53), + ("lease_until", 0, 2**53), + ("next_tick", 0, 2**53), + ]: + integer(state[field], field, low, high) + + def item(self, value: dict[str, Any], suffix: str = "STATE") -> dict[str, Any]: + document = json.dumps( + value, sort_keys=True, separators=(",", ":"), allow_nan=False + ) + if len(document.encode()) > (MAX_BYTES if suffix == "STATE" else 2048): + raise ValueError("item size limit") + item = self.key(value["session"], suffix) | {"document": {"S": document}} + fields = ( + ("epoch", "revision", "fence", "lease_until", "deadline", "next_tick") + if suffix == "STATE" + else () + ) + return item | {key: {"N": str(value[key])} for key in fields} + + def put( + self, state: dict[str, Any], condition: str, values: dict[str, Any] + ) -> None: + try: + self.client.put_item( + TableName=self.table, + Item=self.item(state), + **expression(condition), + ExpressionAttributeValues=values, + ) + except Exception as error: + if ( + getattr(error, "response", {}).get("Error", {}).get("Code") + == "ConditionalCheckFailedException" + ): + raise Conflict from None + raise + + def start(self, session: str, now: int) -> dict[str, Any]: + integer(now, "now", 1, 2**53 - 180) + state = { + "schema": 1, + "model": MODEL_VERSION, + "model_commit": self.model_commit, + "session": session_id(session), + "epoch": 1, + "tick": 0, + "revision": 0, + "fence": 0, + "owner": "", + "lease_until": 0, + "deadline": now + 180, + "next_tick": now, + "reset_count": 0, + "history": [projection(1, 0)["observations"]], + **projection(1, 0), + } + self.client.put_item( + TableName=self.table, + Item=self.item(state), + ConditionExpression="attribute_not_exists(PK)", + ) + return state + + def acquire(self, session: str, owner: str, now: int) -> dict[str, Any]: + state = self.read(session) + if state is None or now >= state["deadline"] or now < state["lease_until"]: + raise Conflict("lease unavailable") + updated = state | { + "owner": owner, + "lease_until": min(now + 10, state["deadline"]), + "fence": state["fence"] + 1, + "revision": state["revision"] + 1, + } + self.put( + updated, + "revision = :revision AND lease_until <= :now AND deadline > :now", + {":revision": {"N": str(state["revision"])}, ":now": {"N": str(now)}}, + ) + return updated + + def renew(self, state: dict[str, Any], now: int) -> dict[str, Any]: + if now >= state["lease_until"] or now >= state["deadline"]: + raise Conflict("expired lease") + updated = state | { + "lease_until": min(now + 10, state["deadline"]), + "revision": state["revision"] + 1, + } + self.put( + updated, + "revision = :revision AND fence = :fence AND lease_until > :now AND deadline > :now", + { + ":revision": {"N": str(state["revision"])}, + ":fence": {"N": str(state["fence"])}, + ":now": {"N": str(now)}, + }, + ) + return updated + + def tick(self, state: dict[str, Any], now: int) -> dict[str, Any]: + self.validate(state) + if ( + now >= state["deadline"] + or now >= state["lease_until"] + or now < state["next_tick"] + or state["tick"] >= 6 + ): + raise Conflict("tick not eligible") + tick = state["tick"] + 1 + result = projection(state["epoch"], tick) + updated = ( + state + | result + | { + "tick": tick, + "revision": state["revision"] + 1, + "next_tick": now + 3, + "history": (state["history"] + [result["observations"]])[-12:], + } + ) + self.put( + updated, + "revision = :revision AND epoch = :epoch AND fence = :fence AND lease_until > :now AND deadline > :now AND next_tick <= :now", + { + ":revision": {"N": str(state["revision"])}, + ":epoch": {"N": str(state["epoch"])}, + ":fence": {"N": str(state["fence"])}, + ":now": {"N": str(now)}, + }, + ) + return updated + + def reset( + self, command: dict[str, Any], now: int, principal: str, expected_principal: str + ) -> dict[str, Any]: + if set(command) != {"session_id", "command_id", "expected_epoch"}: + raise ValueError("invalid command fields") + session = session_id(command["session_id"]) + command_id = command["command_id"] + if not isinstance(command_id, str) or not re.fullmatch( + "[A-Za-z0-9_-]{1,64}", command_id + ): + raise ValueError("invalid command_id") + integer(command["expected_epoch"], "expected_epoch", 1, 999999) + state = self.read(session) + if ( + not expected_principal + or principal != expected_principal + or state is None + or now >= state["deadline"] + ): + raise ValueError("inactive or unauthorized session") + receipt = self.read(session, "CMD#" + command_id) + if receipt: + if receipt["command"] != command: + raise ValueError("conflicting command identity") + return receipt + if state["epoch"] != command["expected_epoch"] or state["reset_count"] >= 3: + raise ValueError("stale epoch or reset limit") + epoch = state["epoch"] + 1 + baseline = projection(epoch, 0) + updated = ( + state + | baseline + | { + "epoch": epoch, + "tick": 0, + "revision": state["revision"] + 1, + "next_tick": now + 3, + "reset_count": state["reset_count"] + 1, + "history": [baseline["observations"]], + } + ) + receipt = { + "session": session, + "command": command, + "epoch": epoch, + "ack": { + "version": 1, + **command, + "committed_epoch": epoch, + "status": "reset_committed", + }, + } + try: + self.client.transact_write_items( + TransactItems=[ + { + "Put": { + "TableName": self.table, + "Item": self.item(updated), + **expression( + "revision = :revision AND epoch = :epoch AND deadline > :now" + ), + "ExpressionAttributeValues": { + ":revision": {"N": str(state["revision"])}, + ":epoch": {"N": str(state["epoch"])}, + ":now": {"N": str(now)}, + }, + } + }, + { + "Put": { + "TableName": self.table, + "Item": self.item(receipt, "CMD#" + command_id), + "ConditionExpression": "attribute_not_exists(PK)", + } + }, + ] + ) + except Exception as error: + if getattr(error, "response", {}).get("Error", {}).get("Code") in ( + "TransactionCanceledException", + "TransactionConflictException", + ): + raise Conflict from None + raise + return receipt + + def publish_ack( + self, session: str, command_id: str, now: int, publisher: Any, topic: str + ) -> dict[str, Any]: + state = self.read(session) + receipt = self.read(session, "CMD#" + command_id) + if not state or now >= state["deadline"] or not receipt: + raise ValueError("no active committed receipt") + # Conditional counter is separate from document; persist attempts BEFORE publication. + self.client.update_item( + TableName=self.table, + Key=self.key(session, "CMD#" + command_id), + **expression( + "attribute_exists(PK) AND (attribute_not_exists(attempts) OR attempts < :limit) AND (attribute_not_exists(ack_until) OR ack_until <= :now)", + "SET attempts = if_not_exists(attempts, :zero) + :one, ack_until = :claim", + ), + ExpressionAttributeValues={ + ":zero": {"N": "0"}, + ":one": {"N": "1"}, + ":limit": {"N": "3"}, + ":now": {"N": str(now)}, + ":claim": {"N": str(now + 5)}, + }, + ) + publisher.publish( + topic=topic, + qos=1, + retain=False, + payload=json.dumps(receipt["ack"]).encode(), + ) + self.client.update_item( + TableName=self.table, + Key=self.key(session, "CMD#" + command_id), + **expression( + "ack_until = :claim", "SET ack_sent = :sent, ack_until = :zero" + ), + ExpressionAttributeValues={ + ":sent": {"BOOL": True}, + ":zero": {"N": "0"}, + ":claim": {"N": str(now + 5)}, + }, + ) + return receipt["ack"] diff --git a/iot-digital-twin-simulator/tests/test_runtime.py b/iot-digital-twin-simulator/tests/test_runtime.py new file mode 100644 index 0000000..dca75d4 --- /dev/null +++ b/iot-digital-twin-simulator/tests/test_runtime.py @@ -0,0 +1,192 @@ +import copy +import json +import unittest +from unittest.mock import Mock + +from runtime import Conflict, DynamoStore, projection + +SESSION = "a" * 32 + + +class ConditionalError(Exception): + response = {"Error": {"Code": "ConditionalCheckFailedException"}} + + +class TransactionError(Exception): + response = {"Error": {"Code": "TransactionCanceledException"}} + + +class RuntimeTests(unittest.TestCase): + def setUp(self): + self.client = Mock() + self.store = DynamoStore(self.client, "fixture-table", "f" * 40) + self.state = self.store.start(SESSION, 100) + self.store.read = Mock(return_value=self.state) + + def test_persistence_and_consistent_read(self): + item = self.client.put_item.call_args.kwargs["Item"] + self.assertEqual(json.loads(item["document"]["S"])["deadline"], 280) + store = DynamoStore(self.client, "fixture-table", "f" * 40) + self.client.get_item.return_value = {"Item": item} + self.assertEqual(store.read(SESSION), self.state) + self.assertTrue(self.client.get_item.call_args.kwargs["ConsistentRead"]) + + def test_fenced_tick_and_recovery(self): + state = self.store.acquire(SESSION, "worker", 100) + result = self.store.tick(state, 100) + request = self.client.put_item.call_args.kwargs + self.assertIn("#epoch = :epoch", request["ConditionExpression"]) + self.assertIn("#fence = :fence", request["ConditionExpression"]) + self.assertIn("#lease_until > :now", request["ConditionExpression"]) + self.assertEqual(result["observations"], projection(1, 1)["observations"]) + self.client.put_item.side_effect = ConditionalError() + with self.assertRaises(Conflict): + self.store.tick(state, 101) + with self.assertRaises(Conflict): + self.store.tick(state, 110) + self.assertEqual(state["tick"], 0) + + def test_reset_transaction_duplicate_and_no_ack_on_failure(self): + command = {"session_id": SESSION, "command_id": "reset-1", "expected_epoch": 1} + self.store.read = Mock(side_effect=[self.state, None]) + receipt = self.store.reset(command, 101, "trusted", "trusted") + writes = self.client.transact_write_items.call_args.kwargs["TransactItems"] + self.assertEqual(len(writes), 2) + saved = json.loads(writes[0]["Put"]["Item"]["document"]["S"]) + self.assertEqual( + (saved["epoch"], saved["tick"], saved["deadline"]), (2, 0, 280) + ) + self.store.read = Mock(side_effect=[saved, receipt]) + self.client.transact_write_items.reset_mock() + self.assertEqual(self.store.reset(command, 102, "trusted", "trusted"), receipt) + self.client.transact_write_items.assert_not_called() + self.store.read = Mock(side_effect=[self.state, None]) + self.client.transact_write_items.side_effect = TransactionError() + with self.assertRaises(Conflict): + self.store.reset(command, 101, "trusted", "trusted") + + def test_ack_claim_precedes_publish_and_lost_publish_preserves_receipt(self): + command = {"session_id": SESSION, "command_id": "reset", "expected_epoch": 1} + self.store.read = Mock(side_effect=[self.state, None]) + receipt = self.store.reset(command, 101, "trusted", "trusted") + self.store.read = Mock(side_effect=[self.state, receipt] * 3) + publisher = Mock() + order = [] + self.client.update_item.side_effect = lambda **kwargs: order.append("claim") + publisher.publish.side_effect = lambda **kwargs: order.append("publish") + ack = self.store.publish_ack(SESSION, "reset", 102, publisher, "fixture/ack") + self.assertEqual(order, ["claim", "publish", "claim"]) + self.assertEqual(ack["committed_epoch"], 2) + self.assertFalse(publisher.publish.call_args.kwargs["retain"]) + publisher.publish.side_effect = TimeoutError() + with self.assertRaises(TimeoutError): + self.store.publish_ack(SESSION, "reset", 108, publisher, "fixture/ack") + self.client.update_item.side_effect = ConditionalError() + publisher.reset_mock() + with self.assertRaises(ConditionalError): + self.store.publish_ack(SESSION, "reset", 114, publisher, "fixture/ack") + publisher.publish.assert_not_called() + self.assertEqual(receipt["epoch"], 2) + + def test_stale_sessions_schema_and_limits(self): + command = {"session_id": SESSION, "command_id": "reset", "expected_epoch": 1} + with self.assertRaises(ValueError): + self.store.reset(command, 280, "trusted", "trusted") + with self.assertRaises(ValueError): + self.store.reset(command, 100, "forged", "trusted") + with self.assertRaises(ValueError): + self.store.reset( + command | {"expected_epoch": True}, 100, "trusted", "trusted" + ) + invalid = copy.deepcopy(self.state) + invalid["model"] = "future" + with self.assertRaises(ValueError): + self.store.validate(invalid) + self.assertEqual( + projection(2, 1)["trace"]["effects"][0]["predecessor"]["epoch"], 2 + ) + + def test_handler_failure_cannot_publish(self): + import app + from unittest.mock import patch + + env = { + "ACTIVE_SESSION": SESSION, + "REQUEST_TOPIC": "fixture/request", + "EXPECTED_PRINCIPAL": "trusted", + "ACK_TOPIC": "fixture/ack", + } + store, publisher = Mock(), Mock() + store.reset.side_effect = Conflict() + event = { + "session_id": SESSION, + "command_id": "reset", + "expected_epoch": 1, + "principal": "trusted", + "topic": "fixture/request", + } + with ( + patch.dict("os.environ", env), + patch.object(app, "clients", return_value=(store, publisher)), + ): + with self.assertRaises(Conflict): + app.reset_handler(event, None) + store.publish_ack.assert_not_called() + with self.assertRaises(ValueError): + app.reset_handler(event | {"session_id": "b" * 32}, None) + + def test_runner_deadline_and_expired_fence_stop(self): + import app + from unittest.mock import patch + + store = Mock() + store.acquire.return_value = self.state | { + "owner": "worker", + "fence": 1, + "lease_until": 110, + } + store.read.return_value = self.state | { + "owner": "other", + "fence": 2, + "lease_until": 110, + } + context = Mock(aws_request_id="worker") + context.get_remaining_time_in_millis.return_value = 10000 + with ( + patch.dict("os.environ", {"ACTIVE_SESSION": SESSION}), + patch.object(app, "clients", return_value=(store, Mock())), + patch.object(app.time, "monotonic", side_effect=[0, 1]), + patch.object(app.time, "time", return_value=101), + ): + self.assertEqual( + app.runner_handler({"session_id": SESSION}, context)["status"], + "stopped", + ) + store.tick.assert_not_called() + store.renew.assert_not_called() + + def test_lease_renewal_is_conditional_and_keeps_deadline(self): + state = self.store.acquire(SESSION, "worker", 100) + renewed = self.store.renew(state, 106) + self.assertEqual(renewed["deadline"], 280) + self.assertEqual(renewed["fence"], state["fence"]) + self.assertIn( + "#fence = :fence", + self.client.put_item.call_args.kwargs["ConditionExpression"], + ) + with self.assertRaises(Conflict): + self.store.renew(state, 110) + + def test_no_receipt_no_publish_and_model_revision_fails_closed(self): + self.store.read = Mock(side_effect=[self.state, None]) + publisher = Mock() + with self.assertRaises(ValueError): + self.store.publish_ack(SESSION, "absent", 100, publisher, "fixture/ack") + publisher.publish.assert_not_called() + self.client.update_item.assert_not_called() + with self.assertRaises(ValueError): + self.store.validate(self.state | {"model_commit": "e" * 40}) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/package_demo.py b/scripts/package_demo.py new file mode 100644 index 0000000..1dbfe47 --- /dev/null +++ b/scripts/package_demo.py @@ -0,0 +1,55 @@ +"""Package runtime with simulator files extracted from an exact reviewed Git revision.""" + +import argparse +import hashlib +import json +import subprocess +from pathlib import Path +from zipfile import ZIP_DEFLATED, ZipFile, ZipInfo + +parser = argparse.ArgumentParser() +parser.add_argument("--model-repo", type=Path, required=True) +parser.add_argument("--model-commit", required=True) +args = parser.parse_args() +commit = subprocess.check_output( + ["git", "-C", str(args.model_repo), "rev-parse", args.model_commit + "^{commit}"], + text=True, +).strip() +if len(args.model_commit) != 40 or commit != args.model_commit: + parser.error("supply an exact full reviewed commit SHA") +root = Path(__file__).resolve().parents[1] +files = { + p.name: p.read_bytes() for p in (root / "iot-digital-twin-simulator").glob("*.py") +} +for name in ( + "__init__.py", + "adapters.py", + "telemetry.py", + "grid_simulator.py", + "transition_trace.py", +): + files["business_app/" + name] = subprocess.check_output( + ["git", "-C", str(args.model_repo), "show", f"{commit}:src/business_app/{name}"] + ) +files["model-provenance.json"] = json.dumps( + { + "model_commit": commit, + "files": { + k: hashlib.sha256(v).hexdigest() + for k, v in files.items() + if k.startswith("business_app/") + }, + }, + sort_keys=True, +).encode() +output = root / "dist/iot-digital-twin-simulator.zip" +output.parent.mkdir(exist_ok=True) +with ZipFile(output, "w", compression=ZIP_DEFLATED, compresslevel=9) as archive: + for name, data in sorted(files.items()): + info = ZipInfo(name, date_time=(1980, 1, 1, 0, 0, 0)) + info.compress_type = ZIP_DEFLATED + info.create_system = 3 + info.external_attr = 0o100644 << 16 + archive.writestr(info, data, compresslevel=9) +print("Artifact:", output) +print("SHA-256:", hashlib.sha256(output.read_bytes()).hexdigest()) diff --git a/scripts/test_demo_integration.py b/scripts/test_demo_integration.py new file mode 100644 index 0000000..a77496a --- /dev/null +++ b/scripts/test_demo_integration.py @@ -0,0 +1,120 @@ +"""Operator-only DynamoDB integration against EXISTING sandbox resources; never MQTT.""" + +import argparse +import hashlib +import json +import sys +import time +import uuid +from pathlib import Path + +sys.path.insert( + 0, str(Path(__file__).resolve().parents[1] / "iot-digital-twin-simulator") +) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--profile", required=True) + parser.add_argument("--region", required=True) + parser.add_argument("--expected-account", required=True) + parser.add_argument("--table", required=True) + parser.add_argument("--model-commit", required=True) + parser.add_argument("--runtime-zip", type=Path, required=True) + parser.add_argument("--expected-artifact-sha256", required=True) + parser.add_argument("--execute-approved-writes", action="store_true") + args = parser.parse_args() + if not args.execute_approved_writes: + parser.error( + "requires separate human authorization of sandbox writes; no dry-run AWS calls" + ) + from zipfile import ZipFile + + artifact = args.runtime_zip.read_bytes() + if hashlib.sha256(artifact).hexdigest() != args.expected_artifact_sha256: + raise RuntimeError("artifact digest mismatch") + with ZipFile(args.runtime_zip) as archive: + provenance = json.loads(archive.read("model-provenance.json")) + if provenance["model_commit"] != args.model_commit: + raise RuntimeError("model artifact mismatch") + sys.path.insert(0, str(args.runtime_zip.resolve())) + from runtime import Conflict, DynamoStore + import boto3 + from botocore.config import Config + + sdk = boto3.Session(profile_name=args.profile, region_name=args.region) + config = Config(connect_timeout=2, read_timeout=3, retries={"max_attempts": 1}) + account = sdk.client("sts", config=config).get_caller_identity()["Account"] + if account != args.expected_account: + raise RuntimeError("account mismatch") + client = sdk.client("dynamodb", config=config) + table = client.describe_table(TableName=args.table)["Table"] + tags = sdk.client("dynamodb", config=config).list_tags_of_resource( + ResourceArn=table["TableArn"] + )["Tags"] + if {"Key": "Environment", "Value": "sandbox"} not in tags: + raise RuntimeError("sandbox tag required") + if table["KeySchema"] != [ + {"AttributeName": "PK", "KeyType": "HASH"}, + {"AttributeName": "SK", "KeyType": "RANGE"}, + ]: + raise RuntimeError("table schema mismatch") + store = DynamoStore(client, args.table, args.model_commit) + session = uuid.uuid4().hex + now = int(time.time()) + store.start(session, now) + old = store.acquire(session, "integration", now) + store.tick(old, now) + try: + store.tick(old, now) + except Conflict: + pass + else: + raise RuntimeError("obsolete tick unexpectedly accepted") + command = { + "session_id": session, + "command_id": "integration-reset", + "expected_epoch": 1, + } + receipt = store.reset(command, now, "synthetic-principal", "synthetic-principal") + if ( + store.reset(command, now, "synthetic-principal", "synthetic-principal") + != receipt + ): + raise RuntimeError("duplicate changed receipt") + try: + store.tick(old, now) + except Conflict: + pass + else: + raise RuntimeError("pre-reset tick unexpectedly accepted") + if store.read(session)["epoch"] != 2: + raise RuntimeError("reset not committed") + + class Recorder: + def publish(self, **kwargs): + self.payload = json.loads(kwargs["payload"]) + + recorder = Recorder() + store.publish_ack( + session, command["command_id"], now, recorder, "synthetic/no-network" + ) + if recorder.payload != receipt["ack"]: + raise RuntimeError("ACK mismatch") + print( + json.dumps( + { + "status": "passed", + "session_id": session, + "ack_sha256": hashlib.sha256( + json.dumps(recorder.payload, sort_keys=True).encode() + ).hexdigest(), + "mqtt": "not executed", + "cleanup": "session items retained for separately approved cleanup", + } + ) + ) + + +if __name__ == "__main__": + main()