"""Observe an existing authorized task until a durable UTC deadline; no task creation. Requires boto3 and AWS credentials outside the untrusted task. A durable external reconciler must invoke this again if the process or host dies. """ import argparse import datetime as dt import time import boto3 from botocore.config import Config def watch(ecs, cluster, arn, expires_at, max_polls=120): stopping = False for _ in range(max_polls): response = ecs.describe_tasks(cluster=cluster, tasks=[arn]) if response.get("failures") or not response.get("tasks"): raise RuntimeError("Task not resolved; preserve ledger slot for reconciliation") task = response["tasks"][0] if task["lastStatus"] == "STOPPED": codes = [item.get("exitCode") for item in task.get("containers", [])] print({"taskArn": arn, "status": "STOPPED", "exitCodes": codes, "stoppedReason": task.get("stoppedReason")}) return codes if dt.datetime.now(dt.timezone.utc) >= expires_at and not stopping: ecs.stop_task(cluster=cluster, task=arn, reason="Job deadline reached") stopping = True # Read and stop failures propagate: do not mark the job finished on API failure. time.sleep(5) raise RuntimeError("Observation budget exhausted; reconcile from original deadline") if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--cluster", required=True) parser.add_argument("--task", required=True) parser.add_argument("--expires-at", required=True, help="Persisted ISO 8601 UTC timestamp") args = parser.parse_args() deadline = dt.datetime.fromisoformat(args.expires_at.replace("Z", "+00:00")) if deadline.tzinfo is None or deadline.utcoffset() != dt.timedelta(0): parser.error("Use an explicit UTC deadline") client = boto3.client("ecs", config=Config(connect_timeout=5, read_timeout=10, retries={"mode": "standard", "max_attempts": 2})) watch(client, args.cluster, args.task, deadline)