Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions .github/workflows/demo-runtime.yml
Original file line number Diff line number Diff line change
@@ -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
12 changes: 10 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -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)
51 changes: 51 additions & 0 deletions iot-digital-twin-simulator/README.md
Original file line number Diff line number Diff line change
@@ -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.
109 changes: 109 additions & 0 deletions iot-digital-twin-simulator/app.py
Original file line number Diff line number Diff line change
@@ -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}
1 change: 1 addition & 0 deletions iot-digital-twin-simulator/model-commit.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
8e2f732127ce19936711346d3c1a50ed3b9b728a
Loading
Loading