oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

Hosted runners 1a, Task 17: live check plan (for Paul's approval)

Revision: 5 (2026-11-28), in the shape Fable's review proposed and Paul accepted, after attempt 3 stopped safely at 2.4 and was torn down (52d73c2c). Revision 4 (c5f9bc36) was the approved one. Status: draft for approval. No AWS command or SDK call of any kind was made while writing it.

What Paul approves

One run in account 640012953448 (profile kass), region eu-west-1, every call behind the account and region guard; IAM is the one global-endpoint exception (R37) and there is no billing call (R33). Every Lambda MicroVMs and Lambda core call goes through livectl, the pinned Go SDK tool (R40), which refuses any other account, region or name outside the run; EC2, IAM, S3, SNS, CloudWatch Logs and STS stay on the CLI. Every taggable resource carries purpose=equipo-hosted-dev and run=<RUN>; MicroVMs (no tag field) and the connector's Lambda-managed interfaces are recorded by ID and proven gone (R34). The code is the exact revision PIN_SHA (R35), and the controller's reaper sees only this run's image (R32). The run stops hard only for safety: the wrong account or region, spend (the run's own estimate reaching $5; $10 is the approval ceiling), a MicroVM alive outside its step, or anything not in the ledger. It also stops when a step that later steps need cannot complete (a resource that cannot be created or deleted). Everything else that differs from expectation becomes a FINDING: line in the journal and the run goes on where it safely can; the report lists every FINDING. Reads of the run's own resources never stop it. Paul also pre-approves these fallbacks: the operator role uses the AWS-managed connector policy plus a subnet-scoped delete from the start; 3.6 to 3.8 step down one base image version once; the contract runs to completion; 9.B records echoes instead of asserting them; and 10.2 drops the delete policy's managed-operator condition once if the connector cannot be deleted. Expected spend is about $0.55, worst case about $9.70, retained image storage after an early stop about $0.50 to $8.20 a month. Guarded, run-scoped, read-only calls on this run's own resources are pre-approved even where this plan does not print them; a failed observation read is a FINDING. Reads needed for identity, ownership, settlement, deletion or a named later step stay fatal. Any other change to a command, or any other AWS call, comes back to Paul first.

Changes since revision 4 (c5f9bc36)

  1. Two kinds of stop. Hard stops are for safety only: account or region, spend, a VM alive outside its step, anything not in the ledger; plus a step later steps need that cannot complete. Everything else is a FINDING: journal line (finding, fact_eq, fact_lv) and the run goes on. The report lists every FINDING.
  2. Reads of the run's own resources never stop the run; a read that errors is a FINDING.
  3. livectl for every Lambda MicroVMs and Lambda core call (R40). It is built in 0.2 and called through lv. jq now reads the SDK's Go field names, with unions under .Value. Client tokens start with the run prefix, as livectl's guard requires. A livectl guard refusal is a hard stop. 0.4's account-wide MicroVM count is dropped: livectl lists by image, and R32 makes the count irrelevant.
  4. Code pin. PIN_SHA is bdf85fb7, livectl's final commit. 0.1 checks it contains a36861a0 (livectl) and f95575c6 (R32), and runs livectl's offline tests. Every livectl call site handles its exit codes as the usage at that commit defines them (see the livectl rule).
  5. Operator role. 2.1 creates it with AWSLambdaNetworkConnectorOperatorPolicy plus the inline subnet-scoped delete, then waits 120 s for propagation (the wait before attempt 3's accepted call). 2.2 creates the connector once. The narrow policy and its retries are gone.
  6. Connector version (2.4). The version-1 qualified ARN is read back through livectl (Version 1, VersionArn, ACTIVE, this subnet and group). The unqualified read's LatestVersionArn and the version list are recorded as facts. No interfaces while ACTIVE is normal (attempt 3).
  7. Base image (3.6 to 3.8). livectl reads Status and SupportedCpuConfigurations. 3.6 picks the newest AVAILABLE x86_64 version and the next one down. If the create (3.7) or the build (3.8) fails, it steps down once.
  8. Contract (6.1). It runs to completion, and every failed subtest becomes a FINDING with its own messages. All its VMs are still settled.
  9. Facts (9). 9.B records the egress, role, idle-policy and ingress echoes as facts. The Date header comes from livectl's ResultMetadata.ServerTime. Unexpected codes in 9.A to 9.G are FINDINGs; any VM an experiment made is still ended before the next one.
  10. Controller sections. A 5.6 audit that does not pass is a FINDING, and 7 and 8 are then skipped. Driver and evidence failures in 7 and 8 are FINDINGs. An orphan alive past P+15:00 stays a hard stop.
  11. Teardown. 10.1 deletes the image (all versions) through livectl. 10.2 deletes the connector through livectl. On DELETE_FAILED, or interfaces left at the bound, 10.2 drops the delete policy's ec2:ManagedResourceOperator condition (keeping the subnet condition) and retries once; a second failure is a hard stop. Image versions are no longer separate teardown objects.
  12. Astra's round 1 on revision 5. - A hard stop inside a subshell or a poll now reaches the parent (die writes a FATAL marker, finding re-raises it), so it can never become a FINDING. ctl_ready's listener check stays a hard stop. Every block is run as its own script (bash <file>), so set -e is always in force. - A launch with an uncertain outcome (no answer, a 5xx) is replayed under the same client token and then settled by image-scoped scans before anything else runs; only a 4xx counts as a confirmed refusal. - List replies go through one validator (list_items): an object with an explicit Items that is null (read as empty) or an array; any other shape fails per the call's rules, a hard stop for collision, settlement, deletion and reconciliation decisions. - Interfaces outside the run's subnet are a hard stop. Interfaces are recorded by ID during the VM phases and before the connector delete, and 10.2 proves each one gone. - lv_wait has one outer deadline covering credentials, start-up and waiting. A late success is a timeout. - 10.2 shares one 120-minute budget across the attempt and its fallback, inside a 130-minute block limit. - Spend (R43): the fact VMs' maximum is now 600 s and the third build is counted; the worst case is about $9.70. - The read-only envelope is stated; observation reads in 1.1 to 1.3 are FINDINGs. - Stale prose in 1.1, 1.2 and 7.3 is aligned.
  13. Section 12 re-run. Settled: U3, U10, U12, U13 and the create half of U2. U11, U14, U17 and U19 are now FINDINGs. New: U21 (a qualified egress ARN on RunMicrovm) and U22 (livectl's interface after Astra).

Order of execution

| Run order | Section | Roughly | | --- | --- | --- | | 1 | 0. Guard rails, code pin, collision checks | 10 min | | 2 | 1. Network | 10 min | | 3 | 2. Connector | 10 to 15 min | | 4 | 3. Image | 30 to 45 min | | 5 | 4. SNS topic | 2 min | | 6 | 5. Keys, config, builds, and the audit-only controller run | 15 min | | 7 | 9.A to 9.F, facts through livectl (no controller running) | 40 min | | 8 | 6. Live contract | 30 min | | 9 | 7. Controller sequence and crash check | 45 min | | 10 | 8. Orphan | 25 min | | 11 | 9.G, final facts | 10 min | | 12 | 10. Teardown and verification | 45 to 75 min |

The SDK-side network audit (5.6) runs before any VM is launched, so the connector's VersionArn and Elastic IP setting are checked by the controller's own code before the first launch.

Rules for every block

  • Every block runs with the agent sandbox off. Attempt 1 showed the sandbox proxy blocks AWS (its allowlist has no *.amazonaws.com, and allowed_domains is ignored in this session), and $TMPDIR is a different path inside and outside the sandbox. Running every block the same way keeps $TMPDIR/equipo-t17 one directory and lets AWS calls through.
  • Every block runs as its own script, bash <file>. The agent writes each block's text, exactly as printed (only the <T17 printed by 0.2> path filled in), to $T17/blocks/<block>.sh and runs bash "$T17/blocks/<block>.sh" in the foreground, or detached for the long blocks below. 0.1, 0.1a and 0.2 run before the scratch exists, so they go to $TMPDIR/equipo-t17-pre/ instead, which 10.9 removes. It never pastes a block into the tool's shell: the plan writer found on 2026-11-28 that a tool's wrapper can run commands in a context where set -e is ignored, which would let a failed command pass silently. Run as a script, set -e is in force, and every hard stop also reaches the parent through die's FATAL marker.
  • One block, one Bash tool call, run by bash. Every block begins with set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh" and, if it calls AWS, guard. The environment file (0.2) defines every helper the blocks use; nothing is pasted by hand.
  • Two kinds of stop (Paul, 2026-11-28). die is kept for the hard stops: the wrong account or region (guard, livectl's own guard), spend (11.2's $5 rule; $10 is the approval ceiling), a MicroVM alive outside its step (settle_all, vm_end, the orphan bound), anything not in the ledger (collision checks, unknown resources, unresolved creations), and a step later steps need that cannot complete (a create or delete that fails, the connector's qualified ARN, the image). Everything else that differs from expectation is a finding: a FINDING line in the journal, printed with FINDING:, and the block goes on. The report lists every FINDING.
  • The read-only envelope. Guarded (guard, livectl's own guard), run-scoped, read-only calls on this run's own resources are pre-approved, including ones this plan does not print. A read that only observes, and errors or answers differently, is a FINDING (fact_eq, fact_json, fact_lv, eni_snapshot soft). A read needed for identity, ownership, settlement, deletion or a named later step stays fatal: the VM scans and vm_end, the collision checks, the connector's qualified ARN, the base image list, the default-resource lookups, the interface list before the connector delete, and every deletion check.
  • Failure is loud. A failed command that is not handled ends the block. Calls that are expected to fail run under try or lv and pass only through an explicit branch that names the accepted error codes. Every poll fails when its bound runs out.
  • livectl (R40). Every Lambda MicroVMs and Lambda core call goes through lv, which runs $T17/bin/livectl -run <RUN> (built in 0.2 from the pinned code). livectl takes only static keys (R41), and kass resolves through a credential_process, so each call first runs aws configure export-credentials --profile kass --format process and starts livectl in a subshell holding only AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY and, if one was issued, AWS_SESSION_TOKEN, with AWS_PROFILE, AWS_CONFIG_FILE and AWS_SHARED_CREDENTIALS_FILE unset (R42). The keys live only in that subshell's environment: never on disk, in the journal, in an argument list or in output. A failed or incomplete export is a hard stop (as livectl's exit 4). Its replies are the SDK's output structs with Go field names (State, VersionArn, MicrovmId) and unions under .Value; its errors are one JSON line whose code lv puts in ECODE and whose aws_message it puts in LV_MSG. Client tokens start with the run prefix, as livectl requires. Exit codes, as livectl defines them at PIN_SHA: - 4 (guard: account, region, run prefix, missing -run, or credentials that are not static keys) and 3 (usage) are hard stops, inside lv itself. - 2 (an SDK call failed; livectl makes one attempt per call, so a throttle, a 5xx or no answer within its 60 s cutoff, "error":"transport", all come back as 2). On a read, lvr tries a transient failure up to 3 times, 5 s apart; what is left is a FINDING, except where a hard stop depends on the read (the VM scans, vm_end, the collision checks, the connector's qualified ARN, the base image list). On a change it follows the block's own branches; only idempotent deletes and terminates use lvr. - 5 (a wait's bound passed, including an answer that came after it) and 6 (a failed state) are handled by each block against its bound. lv_wait gives each wait one overall bound and carries on through a transient exit 2 inside it, as a FINDING.
  • A hard stop means the safe stop (section S), then ask Paul. Nothing else runs after it.
  • Ledger. Before each create call the block writes an INTENT line (kind, run-specific name or token); after the call it records the confirmed ID with rec (checked writes, ARN checks). Every MicroVM ID that appears anywhere is added to the VM ledger with vmrec. A deletion is recorded with deleted only after a direct read shows it gone. Teardown and the safe stop work only from these records; nothing is ever adopted or deleted because its name looks right.
  • Skip-never-created rule. Teardown (section 10) and the safe stop act only on resources with a confirmed creation record, that is, a ledger variable set by rec (VPC, CONN_ARN, IMAGE_ARN, BUCKET_CREATED and so on; the names in run.env alone do not count). have sees three states. Confirmed: act. Never attempted, or the last attempt followed by a NOTCREATED record (from S.2 or a refused create): journal SKIP <variable> and skip. Unresolved (an INTENT with neither): never skipped; the block aborts, so teardown cannot complete, S.3 cannot report "never created", and 10.9 cannot remove the scratch until S.2 reconciles it.
  • Long blocks, one mechanism. These blocks can run past the Bash tool's 10-minute limit for one call: 2.1, 2.3, 3.8, 3.9, 6.1, 7.2, 7.3, 7.4, 8.2, 9.A, 9.C, 10.1 and 10.2 (bounds below). Each is written to a script file and run detached from a sandbox-off shell, and its exit status is read from a status file. Every one of them starts with the sandbox-off header, so it runs the same way detached. The agent never uses another background mechanism. 1. Write the block's text, exactly as printed here with only the <T17 printed by 0.2> path filled in, to $T17/blocks/<block>.sh (for example $T17/blocks/6.1.sh), as for every block. 2. Start it (one sandbox-off call):

``sh set -euo pipefail; T17='<T17 printed by 0.2>'; B='<block>' d="$T17/blocks"; [ -s "$d/$B.sh" ] || { echo "ABORT: no $d/$B.sh"; exit 1; } [ ! -e "$d/$B.status" ] && [ ! -e "$d/$B.pid" ] || { echo "ABORT: block $B was already started"; exit 1; } bash -n "$d/$B.sh" date +%s > "$d/$B.start" setsid nohup bash -c 'bash "$0" > "$1" 2>&1; echo $? > "$2"' "$d/$B.sh" "$d/$B.out" "$d/$B.status" </dev/null >/dev/null 2>&1 & echo $! > "$d/$B.pid"; echo "block $B started, PID $(cat "$d/$B.pid")" ``

3. Wait (repeat this sandbox-off call until it prints an exit status; each call is bounded at 9 minutes; MAXMIN is the block's bound from the table):

``sh set -euo pipefail; T17='<T17 printed by 0.2>'; B='<block>'; MAXMIN='<bound>' d="$T17/blocks"; [ -s "$d/$B.start" ] || { echo "ABORT: block $B was not started"; exit 1; } for i in $(seq 1 108); do [ -s "$d/$B.status" ] && break; sleep 5; done tail -n 60 "$d/$B.out" || true if [ -s "$d/$B.status" ]; then s=$(cat "$d/$B.status"); echo "block $B exit status $s"; [ "$s" = 0 ] || exit 1; exit 0; fi el=$(( ($(date +%s) - $(cat "$d/$B.start")) / 60 )) if [ "$el" -ge "$MAXMIN" ]; then p=$(cat "$d/$B.pid"); kill -TERM -- "-$p" 2>/dev/null || true echo "ABORT: block $B ran past its $MAXMIN-minute bound; its process group was stopped"; exit 1 fi echo "block $B still running after $el minutes" ``

An exit status other than 0, or the bound passing, is an abort (safe stop). Bounds in minutes: 2.1: 10; 2.3: 20; 3.8: 50; 3.9: 25; 6.1: 75; 7.2: 40; 7.3: 15; 7.4: 25; 8.2: 25; 9.A: 15; 9.C: 15; 10.1: 30; 10.2: 130 (its shared budget is 120).

  • The controller, with the sandbox off (R37). A sandboxed Bash call kills its child processes when it returns, so every block that starts, checks or stops the controller runs with the agent's sandbox OFF: 5.6, 6.1, 7.1, 7.2, 7.3, 7.4, 8.1, 8.2, 9.A, 9.G, 10.1, 10.9, S.1 and S.3, plus the other long blocks (2.1, 2.3, 3.8, 3.9, 9.C, 10.2), which run detached. Outside the sandbox $TMPDIR is different, so those blocks set T17 explicitly to the path 0.2 printed; their first line reads set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh", and that path is the only text the agent fills in. start_ctl starts the controller with setsid nohup, writes its PID and, when it ends, its exit status to files. ctl_alive and stop_ctl check that the PID still belongs to this run's binary (/proc/<pid>/cmdline) before anything is signalled. If the controller is gone when a block expects it, or a port stays open with no matching process, that is an abort.
  • docs-t1. The controller listens on 127.0.0.1:18443 (API) and 127.0.0.1:18444 (metrics) only, checked after every start. The hook server in the image listens on port 9000 inside the MicroVM, not on docs-t1. Scratch is $TMPDIR/equipo-t17, removed in 10.9. Go caches stay at their defaults; every Go command runs with CGO_ENABLED=0. No sudo.
  • Records. After each section, append its results to docs/superpowers/plans/HOSTED-SLICE1-PROGRESS.md under ## Task 17 live run, and commit that file locally at the end (subject under 80 characters). Never push. The report lists every FINDING line (10.9 prints them all).

---

0. Guard rails

0.1 Code pin and local tools (no AWS call)

PIN_SHA is bdf85fb7 (bdf85fb70f26094b99241de3f1285de92a76a759), livectl's final commit (static credentials only, endpoints pinned, one attempt per call, bounded calls and waits), relayed by the coordinator. It contains livectl's first commit a36861a0, R32 (f95575c6) and the earlier pre-flight work. The block also runs livectl's offline tests.

set -euo pipefail
PIN_SHA='bdf85fb70f26094b99241de3f1285de92a76a759'
case "$PIN_SHA" in *'<'*|'') echo "ABORT: PIN_SHA is not filled in"; exit 1;; esac
cd /home/paulca/amadan.net/oficina/equipo-hosted-1a
git rev-parse --verify "$PIN_SHA^{commit}"
git merge-base --is-ancestor f95575c6 "$PIN_SHA" || { echo "ABORT: $PIN_SHA does not contain R32 (f95575c6)"; exit 1; }
git merge-base --is-ancestor a36861a0 "$PIN_SHA" || { echo "ABORT: $PIN_SHA does not contain livectl (a36861a0)"; exit 1; }
git merge-base --is-ancestor "$PIN_SHA" HEAD || { echo "ABORT: HEAD does not contain $PIN_SHA"; exit 1; }
d=$(git diff "$PIN_SHA" HEAD -- . ':!docs'); [ -z "$d" ] || { echo "ABORT: code differs from $PIN_SHA outside docs/"; exit 1; }
s=$(git status --porcelain --untracked-files=all -- . ':!docs'); [ -z "$s" ] || { echo "ABORT: uncommitted changes outside docs/:"; echo "$s"; exit 1; }
git log --oneline -1
aws --version
go version
for t in jq openssl sha256sum curl ss python3 setsid nohup; do command -v "$t" >/dev/null || { echo "ABORT: missing $t"; exit 1; }; done
CGO_ENABLED=0 go test -tags hostedlive ./internal/isolatedjob/awsjob/livectl -count=1
echo "code pin ok: $PIN_SHA"
  • Expected: livectl's offline tests pass; code pin ok; aws-cli/2.36.x; go1.26.x.
  • Abort if: any check fails.

0.1a Remove attempt 1's scratch, only if it created nothing (no AWS call)

Attempt 1 left $TMPDIR/equipo-t17 with an empty ledger and no creation records. This step removes it only in exactly that state, keeping its journal as evidence; anything else stops.

set -euo pipefail
: "${TMPDIR:?TMPDIR is unset}"
S="$TMPDIR/equipo-t17"; K="$HOME/.cache/tmp/equipo-t17-attempt1"
if [ ! -e "$S" ]; then echo "no earlier scratch at $S; nothing to remove"; exit 0; fi
[ -f "$S/journal.tsv" ] || { echo "ABORT: $S has no journal.tsv"; exit 1; }
set +e; grep -qE $'\t(INTENT |CONFIRMED |VM |CONTROLLER start )' "$S/journal.tsv"; g=$?; set -e
case "$g" in
  0) echo "ABORT: the earlier journal records a creation, a VM or a controller start"; exit 1;;
  1) ;;
  *) echo "ABORT: could not check the earlier journal (grep status $g)"; exit 1;;
esac
for f in ledger.env vms.tsv; do [ -f "$S/$f" ] && [ ! -s "$S/$f" ] || { echo "ABORT: $S/$f is missing or not empty"; exit 1; }; done
[ ! -e "$S/controller.pid" ] || { echo "ABORT: $S/controller.pid exists"; exit 1; }
[ ! -e "$K" ] || { echo "ABORT: $K already exists"; exit 1; }
mkdir -p -m 700 "$K"
cp -p "$S/journal.tsv" "$K/journal.tsv"; cmp -s "$S/journal.tsv" "$K/journal.tsv" || { echo "ABORT: journal copy differs"; exit 1; }
[ -f "$S/run.env" ] && cp -p "$S/run.env" "$K/run.env"
rm -rf "$S"; [ ! -e "$S" ] || { echo "ABORT: $S still exists"; exit 1; }
echo "attempt 1 scratch removed; journal kept at $K/journal.tsv"
  • Expected: "attempt 1 scratch removed", or "nothing to remove". The executor's own helper files outside $S are not touched.

0.2 Scratch, the environment file and the run names (no AWS call)

set -euo pipefail
: "${TMPDIR:?TMPDIR is unset}"
[ ! -e "$TMPDIR/equipo-t17" ] || { echo "ABORT: $TMPDIR/equipo-t17 already exists"; exit 1; }
mkdir -m 700 "$TMPDIR/equipo-t17"
mkdir -m 700 "$TMPDIR/equipo-t17"/{out,image,iam,keys,bin,blocks}
cat > "$TMPDIR/equipo-t17/env.sh" <<'ENVEOF'
# env.sh: sourced by every block, after `set -euo pipefail`. Task 17 only.
: "${TMPDIR:?TMPDIR is unset}"
# T17 may be set by a sandbox-off block (R37); otherwise it is $TMPDIR/equipo-t17.
unset AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN AWS_SECURITY_TOKEN AWS_DEFAULT_PROFILE \
  AWS_CONFIG_FILE AWS_SHARED_CREDENTIALS_FILE AWS_ROLE_ARN AWS_ROLE_SESSION_NAME AWS_WEB_IDENTITY_TOKEN_FILE \
  AWS_CA_BUNDLE AWS_ENDPOINT_URL AWS_USE_FIPS_ENDPOINT AWS_USE_DUALSTACK_ENDPOINT
for _v in $(env | sed -n 's/^\(AWS_ENDPOINT_URL_[A-Z0-9_]*\)=.*/\1/p'); do unset "$_v"; done
export AWS_PROFILE=kass AWS_REGION=eu-west-1 AWS_DEFAULT_REGION=eu-west-1 AWS_PAGER="" \
  AWS_STS_REGIONAL_ENDPOINTS=regional AWS_RETRY_MODE=standard AWS_MAX_ATTEMPTS=3
export CGO_ENABLED=0
if [ -z "${T17:-}" ]; then T17="$TMPDIR/equipo-t17"; fi
export T17 REPO=/home/paulca/amadan.net/oficina/equipo-hosted-1a
export LIVECTL="$T17/bin/livectl"
export ACCOUNT=640012953448 TAGV=equipo-hosted-dev
export LEDGER="$T17/ledger.env" JOURNAL="$T17/journal.tsv" VMS="$T17/vms.tsv"
export NO_INGRESS=arn:aws:lambda:eu-west-1:aws:network-connector:aws-network-connector:NO_INGRESS
export API=127.0.0.1:18443 METRICS=127.0.0.1:18444
[ -d "$T17" ] || { echo "ABORT: $T17 does not exist; was TMPDIR changed?" >&2; exit 1; }
[ -f "$T17/run.env" ] && . "$T17/run.env"
[ -f "$LEDGER" ] && . "$LEDGER"

# die: a hard stop. It also appends to $T17/FATAL, so a hard stop inside a subshell, a poll or a
# command substitution reaches the parent: finding and fatal_check re-raise it, so it can never
# become a FINDING. Exit status 99.
die() { echo "ABORT: $*" >&2; jw "ABORT $*" 2>/dev/null || true; printf '%s\n' "$*" >> "$T17/FATAL" 2>/dev/null || true; exit 99; }
# soft_fail: an ordinary failure (a poll's bound or an unexpected state) that ends the current
# (sub)shell with status 1 without a hard stop; at a block's top level it still ends the block.
soft_fail() { echo "FAILED: $*" >&2; jw "FAILED $*" 2>/dev/null || true; exit 1; }
_fatal_count() { if [ -f "$T17/FATAL" ]; then wc -l < "$T17/FATAL"; else echo 0; fi; }
_FATAL0=$(_fatal_count)
# fatal_check: re-raise any hard stop that happened in a subshell since this block began.
fatal_check() { [ "$(_fatal_count)" -le "$_FATAL0" ] || die "a hard stop happened inside a subshell: $(tail -n 1 "$T17/FATAL")"; }
# need VAR...: each must be set, non-empty, and not None or null.
need() { local v; for v; do [ -n "${!v:-}" ] && [ "${!v}" != None ] && [ "${!v}" != null ] || die "$v is unset"; done; }
# arn_ok ARN: in this account and eu-west-1 (IAM and S3 ARNs have no region).
arn_ok() {
  case "$1" in
    *149757027610*) die "ARN $1 names account 149757027610";;
    arn:aws:*:eu-west-1:640012953448:*|arn:aws:iam::640012953448:role/*|arn:aws:s3:::*) ;;
    *) die "ARN $1 is not in 640012953448 and eu-west-1";;
  esac
}
# jw TEXT: one journal line; a failed write is an abort.
jw() { local t="$*"; t=${t//$'\r'/}; t=${t//$'\n'/ | }; t=${t//$'\t'/ }
  printf '%s\t%s\n' "$(date -u +%FT%T.%3NZ)" "$t" >> "$JOURNAL" || { echo "ABORT: journal write failed" >&2; exit 1; }; }
# _kind VAR: sets K_I and K_N, the journal patterns for VAR's INTENT and NOTCREATED records ("" when
# VAR has no creation of its own: the VPC defaults exist only with the VPC, and image versions only
# with the image, which livectl deletes whole).
_kind() { case "$1" in
  VPC) K_I='^INTENT vpc( |$)'; K_N='^NOTCREATED vpc( |$)';;
  SUBNET) K_I='^INTENT subnet( |$)'; K_N='^NOTCREATED subnet( |$)';;
  RTB) K_I='^INTENT route-table( |$)'; K_N='^NOTCREATED route-table( |$)';;
  RTB_ASSOC) K_I='^INTENT route-table-association( |$)'; K_N='^NOTCREATED route-table-association( |$)';;
  SG) K_I='^INTENT security-group( |$)'; K_N='^NOTCREATED security-group( |$)';;
  OPERATOR_ROLE_ARN) K_I="^INTENT iam-role $OPERATOR_ROLE( |\$)"; K_N="^NOTCREATED iam-role $OPERATOR_ROLE( |\$)";;
  BUILD_ROLE_ARN) K_I="^INTENT iam-role $BUILD_ROLE( |\$)"; K_N="^NOTCREATED iam-role $BUILD_ROLE( |\$)";;
  CONN_ARN) K_I='^INTENT connector( |$)'; K_N='^NOTCREATED connector( |$)';;
  BUCKET_CREATED) K_I='^INTENT s3-bucket( |$)'; K_N='^NOTCREATED s3-bucket( |$)';;
  LOG_GROUP_CREATED) K_I='^INTENT log-group( |$)'; K_N='^NOTCREATED log-group( |$)';;
  ARTIFACT) K_I='^INTENT s3-object( |$)'; K_N='^NOTCREATED s3-object( |$)';;
  IMAGE_ARN) K_I='^INTENT microvm-image( |$)'; K_N='^NOTCREATED (microvm-image|image attempt)( |$)';;
  TOPIC_ARN) K_I='^INTENT sns-topic( |$)'; K_N='^NOTCREATED sns-topic( |$)';;
  *) K_I=''; K_N='';;
esac; }
# creation_state VAR: sets CST to confirmed (VAR is set), none (never attempted), absent (the last
# attempt is followed by a NOTCREATED record) or unresolved (attempted, neither confirmed nor shown absent).
creation_state() {
  if [ -n "${!1:-}" ]; then CST=confirmed; return 0; fi
  _kind "$1"; if [ -z "$K_I" ]; then CST=none; return 0; fi
  CST=$(awk -F'\t' -v ri="$K_I" -v rn="$K_N" '$2 ~ ri {li = NR} $2 ~ rn {ln = NR} END {if (!li) print "none"; else if (ln > li) print "absent"; else print "unresolved"}' "$JOURNAL") || die "journal unreadable"
}
# have VAR: 0 to act on a confirmed creation; 1, with a journalled SKIP, for one never attempted or
# shown absent. An unresolved creation is never skipped: it aborts, so teardown cannot complete and
# scratch cannot be removed until S.2 reconciles it (the skip-never-created rule).
have() {
  creation_state "$1"
  case "$CST" in
    confirmed) return 0;;
    none|absent) jw "SKIP $1 $CST"; echo "skip: $1 ($CST: never created)"; return 1;;
    *) jw "UNRESOLVED-TEARDOWN $1"; die "$1: a creation was attempted but is neither confirmed nor shown absent; reconcile it (S.2) first";;
  esac
}
# no_unresolved: abort if any resource is still unresolved.
no_unresolved() { local v; for v in VPC SUBNET RTB RTB_ASSOC SG OPERATOR_ROLE_ARN BUILD_ROLE_ARN CONN_ARN BUCKET_CREATED LOG_GROUP_CREATED ARTIFACT IMAGE_ARN TOPIC_ARN; do
  creation_state "$v"; [ "$CST" != unresolved ] || die "$v is unresolved; reconcile it (S.2) before finishing"; done; }
# gone0 WHAT CMD...: a list read that must succeed and count 0 (no error code is guessed).
gone0() { local w=$1; shift; get _g "$@"; [ "$_g" = 0 ] || die "$w is still listed ($_g)"; }
# intent KIND KEY DETAIL...: written BEFORE a create call.
intent() { jw "INTENT $*"; }
# rec VAR VALUE: written AFTER a create call returned the ID; checked; exported.
rec() {
  [ $# = 2 ] || die "rec needs a name and a value"
  case "$2" in ""|None|null) die "rec $1: empty value";; *149757027610*) die "rec $1=$2 names account 149757027610";; esac
  printf 'export %s=%q\n' "$1" "$2" >> "$LEDGER" || die "ledger write failed"
  jw "CONFIRMED $1 $2"
  export "$1=$2"
}
# deleted KIND ID HOW: written after a deletion is confirmed by a direct read.
deleted() { jw "DELETED $*"; }
# try CMD...: run CMD; never exits; sets OUT, ERR, RC and ECODE (the AWS error code, if any).
try() {
  local had=0 e; case $- in *e*) had=1;; esac
  e=$(mktemp "$T17/err.XXXXXX") || { echo "ABORT: mktemp" >&2; exit 1; }
  set +e; OUT=$("$@" 2>"$e"); RC=$?; [ "$had" = 1 ] && set -e
  ERR=$(cat "$e"); rm -f "$e"
  ECODE=$(printf '%s' "$ERR" | sed -n 's/.*An error occurred (\([A-Za-z0-9.]*\)).*/\1/p' | head -n 1)
  return 0
}
# must: after try, the call must have succeeded.
must() { [ "$RC" = 0 ] || die "call failed (rc $RC, ${ECODE:-no code}): $ERR"; }
# get VAR CMD...: run a read; abort unless it succeeded; only then store its output in VAR.
get() { local __v=$1; shift; try "$@"; must; printf -v "$__v" '%s' "$OUT"; }
# _creds: export kass's credentials through the CLI's own resolution (its credential_process),
# into shell variables of the calling (sub)shell only (R42). Never written to disk, the journal or
# any argument list, and never printed. AccessKeyId and SecretAccessKey are required; a
# SessionToken, if present, needs an Expiration. Static IAM user keys have neither.
_creds() {
  local j rc had=0; case $- in *e*) had=1;; esac
  set +e; j=$(timeout 30 aws configure export-credentials --profile kass --format process 2>/dev/null); rc=$?; [ "$had" = 1 ] && set -e
  [ "$rc" = 0 ] || return 1
  _AK=$(jq -r '.AccessKeyId // empty' <<<"$j" 2>/dev/null || true)
  _SK=$(jq -r '.SecretAccessKey // empty' <<<"$j" 2>/dev/null || true)
  _ST=$(jq -r '.SessionToken // empty' <<<"$j" 2>/dev/null || true)
  _EXP=$(jq -r '.Expiration // empty' <<<"$j" 2>/dev/null || true)
  j=""
  [ -n "$_AK" ] && [ -n "$_SK" ] || return 1
  [ -z "$_ST" ] || [ -n "$_EXP" ] || return 1
}
# _lvx ARGS...: livectl in a subshell whose environment holds exactly the exported static keys:
# AWS_PROFILE, AWS_CONFIG_FILE and AWS_SHARED_CREDENTIALS_FILE are unset for it, so livectl sees only
# static environment keys. A failed export is livectl's guard exit (4): a hard stop in lv.
_lvx() (
  if ! _creds; then echo '{"error":"guard","message":"kass credentials could not be exported as static keys (R42)"}' >&2; exit 4; fi
  unset AWS_PROFILE AWS_CONFIG_FILE AWS_SHARED_CREDENTIALS_FILE AWS_SESSION_TOKEN
  export AWS_ACCESS_KEY_ID="$_AK" AWS_SECRET_ACCESS_KEY="$_SK"
  [ -z "$_ST" ] || export AWS_SESSION_TOKEN="$_ST"
  unset _AK _SK _ST
  exec "$LIVECTL" -run "$RUN" "$@"
)
# cred_left: seconds until the exported credentials expire, or "none" for static keys without an
# Expiration. Prints nothing secret.
cred_left() ( _creds || exit 4; unset _AK _SK _ST
  if [ -z "$_EXP" ]; then echo none; else echo $(( $(date -d "$_EXP" +%s) - $(date +%s) )); fi )
# lv ARGS...: one livectl call (every Lambda MicroVMs and Lambda core call, R40). Sets OUT, ERR, RC,
# ECODE (the smithy error code), LV_KIND (api, transport, usage, guard, timeout, failed_state, other)
# and LV_MSG (the service's own text). A guard refusal (4) or usage error (3) is a hard stop.
lv() {
  [ -x "$LIVECTL" ] || die "livectl is not built at $LIVECTL"
  need RUN
  try _lvx "$@"
  ECODE=""; LV_KIND=""; LV_MSG=""; LV_HTTP=""
  if [ "$RC" != 0 ]; then
    local e; e=$(tail -n 1 <<<"$ERR")
    ECODE=$(jq -r '.code // empty' <<<"$e" 2>/dev/null || true)
    LV_KIND=$(jq -r '.error // empty' <<<"$e" 2>/dev/null || true)
    LV_MSG=$(jq -r '.aws_message // empty' <<<"$e" 2>/dev/null || true)
    LV_HTTP=$(jq -r '.http_status // empty' <<<"$e" 2>/dev/null || true)
  fi
  [ "$RC" != 4 ] || die "livectl guard refusal (account, region, run prefix or -run): $ERR"
  [ "$RC" != 3 ] || die "livectl usage error (a plan defect): $ERR"
  return 0
}
# _transient: after lv, 0 if the failure is worth trying again: livectl makes one attempt per call,
# so a throttle, a server error or no answer within its 60 s cutoff comes back as exit 2.
_transient() { [ "$RC" = 2 ] || return 1; [ "$LV_KIND" = transport ] && return 0
  case "$ECODE" in ThrottlingException|TooManyRequestsException|InternalServerException|ServiceException|ServiceUnavailableException) return 0;; esac; return 1; }
# lvr ARGS...: lv with up to 3 tries, 5 s apart, on a transient failure. For reads and idempotent
# deletes and terminates only; creates and other changes use lv once.
lvr() { local i; for i in 1 2 3; do lv "$@"; _transient || return 0; [ "$i" = 3 ] || { echo "transient (${ECODE:-$LV_KIND}); trying again"; sleep 5; }; done; return 0; }
# lv_wait SECONDS ARGS...: a livectl wait with one outer deadline, SECONDS from now, covering the
# credential export (bounded at 30 s), livectl's start and account check (its 60 s cutoff) and the
# waiting itself: 90 s of each call is kept for the first two. A chunk is never longer than what is
# left; when the exported credentials expire sooner (less a 120 s margin) the wait is split into
# shorter calls, each with fresh credentials. A transient exit 2 is a FINDING and the wait goes on.
# A success that comes back after the deadline counts as a timeout. Leaves RC 0, 5 (the deadline
# passed), 6 (a failed state) or 2 (any other error). A guard failure stays a hard stop.
lv_wait() { local end=$(( $(date +%s) + $1 )) left cl chunk; shift
  while :; do
    left=$(( end - $(date +%s) - 90 )); if [ "$left" -le 0 ]; then RC=5; return 0; fi
    cl=$(cred_left) || die "kass credentials could not be exported (R42)"
    left=$(( end - $(date +%s) - 90 )); if [ "$left" -le 0 ]; then RC=5; return 0; fi
    chunk=$left
    if [ "$cl" != none ] && [ $(( cl - 120 )) -lt "$chunk" ]; then
      chunk=$(( cl - 120 )); if [ "$chunk" -lt 15 ]; then chunk=$(( left < 15 ? left : 15 )); fi
    fi
    lv "$@" -timeout "${chunk}s"
    if [ "$RC" = 0 ] && [ "$(date +%s)" -gt "$end" ]; then finding "a wait answered after its deadline; counted as a timeout"; RC=5; return 0; fi
    if _transient; then finding "transient error inside a wait (${ECODE:-$LV_KIND}); waiting on"; sleep 5; continue; fi
    if [ "$RC" = 5 ] && [ "$chunk" -lt "$left" ]; then echo "wait split at the credentials' expiry; going on with fresh credentials"; continue; fi
    return 0
  done; }
# finding TEXT: a FINDING line in the journal; the run goes on (Paul's rule 1).
finding() { fatal_check; jw "FINDING $*"; echo "FINDING: $*"; }
# fact_eq WHAT WANT CMD...: a read of the run's own resource; a failed read or another value is a FINDING.
fact_eq() { local w=$1 want=$2; shift 2; try "$@"
  if [ "$RC" != 0 ]; then finding "$w: read failed (${ECODE:-rc$RC})"; elif [ "$OUT" = "$want" ]; then echo "ok: $w"; else finding "$w: got [$OUT], want [$want]"; fi; }
# fact_json WHAT WANT CMD...: as fact_eq, comparing compacted JSON.
fact_json() { local w=$1 want=$2 got; shift 2; try "$@"
  if [ "$RC" != 0 ]; then finding "$w: read failed (${ECODE:-rc$RC})"; return 0; fi
  got=$(jq -c . <<<"$OUT" 2>/dev/null) || { finding "$w: reply is not JSON"; return 0; }
  if [ "$got" = "$(jq -c . <<<"$want")" ]; then echo "ok: $w"; else finding "$w: got $got, want $want"; fi; }
# fact_lv WHAT WANT JQ ARGS...: a livectl read; jq -r JQ of the reply must equal WANT, else a FINDING.
fact_lv() { local w=$1 want=$2 q=$3 got; shift 3; lvr "$@"
  if [ "$RC" != 0 ]; then finding "$w: read failed (${ECODE:-rc$RC})"; return 0; fi
  got=$(jq -r "$q" <<<"$OUT" 2>/dev/null) || { finding "$w: reply unreadable"; return 0; }
  if [ "$got" = "$want" ]; then echo "ok: $w"; else finding "$w: got [$got], want [$want]"; fi; }
# code_in CODE...: after try, 0 if the call failed with one of CODE.
code_in() { local c; [ "$RC" != 0 ] || return 1; for c; do [ "$ECODE" = "$c" ] && return 0; done; return 1; }
# expect_err CODE...: after try, the call must have failed with one of CODE (an expected-failure branch).
expect_err() { code_in "$@" || die "expected one of [$*], got rc $RC ${ECODE:-no code}: ${ERR:-$OUT}"; }
guard() {
  [ "$AWS_PROFILE" = kass ] && [ "$AWS_REGION" = eu-west-1 ] && [ "$AWS_DEFAULT_REGION" = eu-west-1 ] || die "profile or region changed"
  [ -z "${AWS_ACCESS_KEY_ID:-}" ] || die "AWS_ACCESS_KEY_ID is set"
  try aws sts get-caller-identity --query Account --output text; must
  [ "$OUT" = "$ACCOUNT" ] || die "account is $OUT, not $ACCOUNT"
}
# poll SECONDS INTERVAL WHAT FN ARGS...: FN returns 0 done, 1 not yet, anything else an ordinary
# failure (soft_fail). A hard stop inside FN (die) stays a hard stop.
poll() {
  local secs=$1 iv=$2 what=$3 rc had=0 end; end=$(( $(date +%s) + secs )); shift 3
  case $- in *e*) had=1;; esac
  while :; do
    set +e; "$@"; rc=$?; [ "$had" = 1 ] && set -e
    [ "$rc" = 0 ] && return 0
    fatal_check
    [ "$rc" = 1 ] || soft_fail "$what: unexpected state (rc $rc)"
    [ "$(date +%s)" -lt "$end" ] || soft_fail "$what: not done within $secs s"
    sleep "$iv"
  done
}

# --- MicroVMs: recorded by ID (they have no tags), found by the image-scoped List ---
# vmrec ID SOURCE START: one VM ledger line per (ID, source, start). START is the provider's
# startedAt, or "phase:<time>" (the start of the phase that found it) when only that is known.
vmrec() {
  [ $# = 3 ] && [ -n "$3" ] && [ "$3" != phase: ] || die "vmrec $1: no start time"
  [ -f "$VMS" ] || die "no VM ledger"
  local key; printf -v key '%s\t%s\t%s\t' "$1" "$2" "$3"
  grep -qF "$key" "$VMS" && return 0
  printf '%s%s\n' "$key" "$(date -u +%FT%T.%3NZ)" >> "$VMS" || die "VM ledger write failed"
  jw "VM $1 $2 $3"
}
# vm_ids: sets VIDS to every recorded VM ID.
vm_ids() { [ -f "$VMS" ] || die "no VM ledger"; VIDS=$(cut -f1 "$VMS" | sort -u) || die "VM ledger unreadable"; }
# list_items: validate a livectl list reply in OUT: a JSON object with an explicit Items key whose
# value is null or an array. On success ITEMS holds that array, with null read as []. Anything else
# (not JSON, not an object, no Items key, Items of another type) returns 1, and the caller fails per
# its own rules: a hard stop where the result drives a safety decision (collision, settled, deleted,
# reconciliation), a FINDING for an observation.
list_items() {
  ITEMS=$(jq -ce 'if type == "object" and has("Items") and (.Items == null or (.Items | type) == "array") then (.Items // []) else error("malformed") end' <<<"$OUT" 2>/dev/null) || { ITEMS=""; return 1; }
}
# scan: one image-scoped List, every page, every state; records every ID; writes last_scan.tsv.
scan() {
  need IMAGE_ARN
  lvr vm list -image "$IMAGE_ARN"; must
  list_items || die "malformed VM list reply: $(head -c 200 <<<"$OUT")"
  jq -e --arg a "$IMAGE_ARN" 'all(.[]; .ImageArn == $a)' <<<"$ITEMS" >/dev/null || die "list returned a VM of another image"
  jq -r '.[] | [.MicrovmId, .State, .StartedAt] | @tsv' <<<"$ITEMS" > "$T17/last_scan.tsv" || die "VM list items unreadable"
  local id st started
  while IFS=$'\t' read -r id st started; do [ -n "$id" ] && vmrec "$id" scan "$started"; done < "$T17/last_scan.tsv"
  LIVE=$(awk -F'\t' '$2 != "TERMINATED" {print $1}' "$T17/last_scan.tsv") || die "scan output unreadable"
  cat "$T17/last_scan.tsv"
}
# After scan, LIVE holds the IDs of this image's VMs that are not TERMINATED.
# vm_get ID: sets VST to the state, NOTFOUND, or ERROR:<code>.
vm_get() {
  lvr vm get -id "$1"
  if [ "$RC" = 0 ]; then VST=$(jq -r '.State // empty' <<<"$OUT"); [ -n "$VST" ] || VST="ERROR:no-state"; elif [ "$ECODE" = ResourceNotFoundException ]; then VST=NOTFOUND; else VST="ERROR:${ECODE:-${LV_KIND:-rc$RC}}"; fi
}
_vm_check() { vm_get "$1"; echo "$(date -u +%T) $1 $VST"; [ "$VST" = "$2" ] && return 0; case " $3 ThrottlingException transport " in *" ${VST#ERROR:} "*) return 1;; esac; return 2; }
# vm_wait ID TARGET SECONDS ALLOWED...: wait for TARGET; a state outside ALLOWED is fatal.
vm_wait() { local id=$1 t=$2 s=$3; shift 3; poll "$s" 5 "VM $id to $t" _vm_check "$id" "$t" "$*"; }
# vm_end ID: terminate and confirm: TERMINATED, or not found twice at least 60 s apart.
vm_end() {
  lvr vm terminate -id "$1"
  [ "$RC" = 0 ] || [ "$ECODE" = ResourceNotFoundException ] || die "terminate $1: ${ECODE:-rc$RC} ${LV_MSG:-$ERR}"
  local nf=0 end=$(( $(date +%s) + 600 ))
  while :; do
    vm_get "$1"; echo "$(date -u +%T) $1 $VST"
    case "$VST" in
      TERMINATED) jw "VMGONE $1 TERMINATED"; return 0;;
      NOTFOUND) [ "$nf" = 0 ] && nf=$(date +%s); [ $(( $(date +%s) - nf )) -ge 60 ] && { jw "VMGONE $1 NOTFOUND-TWICE"; return 0; };;
      PENDING|RUNNING|SUSPENDING|SUSPENDED|TERMINATING|ERROR:ThrottlingException|ERROR:transport) nf=0;;
      *) die "VM $1: $VST";;
    esac
    [ "$(date +%s)" -lt "$end" ] || die "VM $1 has not ended after 10 min"
    sleep 10
  done
}
# settle_all: end every recorded and every listed live VM; done only after three scans 30 s apart show none live.
settle_all() {
  need IMAGE_ARN; local round i clean id
  for round in 1 2 3; do
    scan >/dev/null
    for id in $LIVE; do vm_end "$id"; done
    vm_ids
    for id in $VIDS; do grep -q "VMGONE $id " "$JOURNAL" || vm_end "$id"; done
    clean=0
    for i in 1 2 3; do
      scan >/dev/null
      [ -n "$LIVE" ] && break
      clean=$((clean + 1)); [ "$i" -lt 3 ] && sleep 30
    done
    vm_ids
    [ "$clean" = 3 ] && { jw "SETTLED $(wc -w <<<"$VIDS") recorded"; echo "settled: $(wc -w <<<"$VIDS") VMs recorded, none live in three scans"; return 0; }
  done
  die "VMs still live after three settle rounds"
}
# launch LABEL TOKEN MAXSECONDS PAYLOADFILE: one livectl vm run (Small, NO_INGRESS, the connector);
# records any VM it returns. TOKEN must start with the run prefix. Sets L_OUTCOME:
#   created    the reply names a VM (recorded);
#   rejected   a confirmed refusal: an api error with a 4xx status, so AWS did not run it;
#   settled    the outcome was uncertain (no answer, a 5xx, an unreadable error): the identical
#              request was replayed up to twice under the same client token; if no replay named a
#              VM, settle_all ended every live VM of this image (bounded image-scoped scans), which
#              proves nothing launched is left. If that cannot be proved, settle_all is a hard stop.
_launch_once() {
  lv vm run -image "$IMAGE_ARN" -version "$VER_SMALL" -connector "$CONN_QARN" -max-seconds "$3" \
    -client-token "$2" -payload-file "$4"
  printf '%s\n' "$OUT" > "$T17/out/launch-$1.json"; printf '%s\n' "$ERR" > "$T17/out/launch-$1.err"
  L_RC=$RC; L_CODE=$ECODE; L_MSG=$LV_MSG; L_ID=""
  if [ "$RC" = 0 ]; then
    L_ID=$(printf '%s' "$OUT" | jq -r '.MicrovmId // empty')
    [ -n "$L_ID" ] || die "launch $1 succeeded with no MicrovmId"
    local st; st=$(printf '%s' "$OUT" | jq -r '.StartedAt // empty')
    vmrec "$L_ID" "$1" "${st:-phase:$L_T0}"; L_OUTCOME=created
  elif [ "$LV_KIND" = api ] && [ -n "$LV_HTTP" ] && [ "$LV_HTTP" -ge 400 ] && [ "$LV_HTTP" -lt 500 ]; then L_OUTCOME=rejected
  else L_OUTCOME=uncertain; fi
}
launch() {
  need IMAGE_ARN VER_SMALL CONN_QARN; [ -f "$4" ] || die "no payload file $4"
  intent vm "$1" "token=$2" "max=$3"
  L_T0=$(date -u +%FT%T.%3NZ)
  _launch_once "$@"
  local k
  for k in 1 2; do
    [ "$L_OUTCOME" = uncertain ] || break
    jw "UNCERTAIN vm $1 token=$2 (${L_CODE:-${LV_KIND:-rc$L_RC}}): replay $k with the same client token"; sleep 5
    _launch_once "$1-replay$k" "$2" "$3" "$4"
  done
  if [ "$L_OUTCOME" = uncertain ] || { [ "$L_OUTCOME" = rejected ] && grep -q $'\tUNCERTAIN vm '"$1"' ' "$JOURNAL"; }; then
    finding "launch $1 has an uncertain outcome (${L_CODE:-${LV_KIND:-rc$L_RC}}); settling every VM of the image"
    settle_all; L_OUTCOME=settled; L_ID=""; jw "RESOLVED vm $1 by settlement"
  fi
  echo "launch $1: $L_OUTCOME rc=$L_RC code=${L_CODE:-none} id=${L_ID:-none}"
}
# eni_snapshot MODE WHEN: list the VPC's interfaces. Any outside this run's subnet is not in the ledger:
# a hard stop, before anything is recorded. Each one inside is recorded once as SERVICE-ENI, so 10.2
# can prove each ID gone. MODE strict makes a failed list a hard stop (10.2 needs it); soft makes it a
# FINDING (observations during the VM phases).
eni_snapshot() {
  need VPC SUBNET
  try aws ec2 describe-network-interfaces --filters Name=vpc-id,Values="$VPC" --output json
  if [ "$RC" != 0 ]; then
    [ "$1" = strict ] && die "interface list failed (${ECODE:-rc$RC}); 10.2 needs it"
    finding "interface list failed ($2): ${ECODE:-rc$RC}"; return 0
  fi
  printf '%s' "$OUT" | jq -e '.NetworkInterfaces | type == "array"' >/dev/null || die "interface list unreadable ($2)"
  printf '%s' "$OUT" | jq -e --arg s "$SUBNET" 'all(.NetworkInterfaces[]; .SubnetId == $s)' >/dev/null \
    || die "an interface outside this run's subnet is in the run's VPC ($2): not in the ledger"
  local e n=0
  for e in $(printf '%s' "$OUT" | jq -r '.NetworkInterfaces[].NetworkInterfaceId'); do
    n=$((n + 1)); grep -qF "SERVICE-ENI $e" "$JOURNAL" || jw "SERVICE-ENI $e"
  done
  jw "FACT interfaces in the VPC ($2): $n"; echo "interfaces in the VPC ($2): $n"
}
# harvest LOG SOURCE PHASESTART: record every MicroVM ID a log names, with the phase start as its
# conservative start (scans add the provider's startedAt later).
harvest() {
  [ -f "$1" ] && [ -n "${3:-}" ] || die "harvest: no log $1 or no phase start"
  local ids id; ids=$(grep -oE 'mvm-[0-9A-Za-z-]+' "$1" | sort -u || true)
  for id in $ids; do vmrec "$id" "$2" "phase:$3"; done
}
harvest_ctl() { local t; t=$(cat "$T17/controller.start") || die "no controller start time"; harvest "$T17/controller.log" controller "$t"; }

# --- the controller process ---
ctl_pid() { [ -s "$T17/controller.pid" ] && cat "$T17/controller.pid"; }
# ctl_alive: 0 if this run's controller process is alive; dies if the PID is alive but is something else.
ctl_alive() {
  local p; p=$(ctl_pid) || return 1
  [ -d "/proc/$p" ] || return 1
  tr '\0' ' ' < "/proc/$p/cmdline" | grep -qF "$T17/bin/controller" || die "PID $p is alive but is not this run's controller"
}
# listeners: sets LST to the addresses listening on 18443 or 18444 (empty if none); aborts if ss fails.
listeners() { local o; o=$(ss -ltnH '( sport = :18443 or sport = :18444 )') || die "ss failed"; LST=$(printf '%s\n' "$o" | awk 'NF {print $4}' | sort -u | tr '\n' ' '); }
# start_ctl BINARY LABEL [VAR=VALUE...]: start in its own session; PID and exit status go to files.
start_ctl() {
  local bin=$1 label=$2; shift 2
  [ -x "$bin" ] || die "no binary $bin"
  ! ctl_alive || die "a controller is already running"
  listeners; [ -z "$LST" ] || die "ports 18443 or 18444 are in use: $LST"
  rm -f "$T17/controller.pid" "$T17/controller.exit"
  date -u +%FT%T.%3NZ > "$T17/controller.start" || die "cannot write controller.start"
  jw "CONTROLLER start $label $bin $*"
  setsid nohup env -u EQUIPO_HOSTED_CRASH_AFTER_LAUNCH -u EQUIPO_HOSTED_ENABLED "$@" bash -c \
    '"$0" -config "$1" >>"$2" 2>&1 & echo $! >"$3"; wait $!; echo $? >"$4"' \
    "$bin" "$T17/controller.json" "$T17/controller.log" "$T17/controller.pid" "$T17/controller.exit" \
    </dev/null >/dev/null 2>&1 &
  local i; for i in $(seq 1 50); do [ -s "$T17/controller.pid" ] && break; sleep 0.1; done
  ctl_alive || die "the controller did not start (see controller.log)"
  echo "controller $label started, PID $(ctl_pid)"
}
_ctl_ready() {
  [ -s "$T17/controller.exit" ] && return 2
  local m; m=$(curl -fsS "http://$METRICS/metrics" 2>/dev/null) || return 1
  printf '%s\n' "$m" | grep -q '^equipo_hosted_network_audit_passing 0$' && return 3
  printf '%s\n' "$m" | grep -q '^equipo_hosted_network_audit_passing 1$' || return 1
  printf '%s\n' "$m" | grep -q '^equipo_hosted_reap_last_age_seconds ' || return 1
  printf '%s\n' "$m" | grep -q '^equipo_hosted_reap_last_error 0$' || return 4
  return 0
}
# ctl_ready: within 240 s the audit has passed and a reaper pass has finished cleanly (else soft_fail);
# listeners are 127.0.0.1 only (else a hard stop: docs-t1's binding rule).
ctl_ready() {
  poll 240 5 "controller ready" _ctl_ready
  listeners; [ "$LST" = "127.0.0.1:18443 127.0.0.1:18444 " ] || die "listeners are [$LST], want 127.0.0.1:18443 and :18444 only"
  local m; m=$(curl -fsS "http://$METRICS/metrics") || soft_fail "metrics unreadable"
  echo "controller ready:"; printf '%s\n' "$m" | grep -E '^equipo_hosted_(network_audit_passing|reap_last_error|reap_last_age_seconds|store_readable) ' || soft_fail "readiness metrics missing"
}
# stop_ctl: SIGTERM, then SIGKILL after 45 s if still alive; ports must close.
stop_ctl() {
  local i
  if ctl_alive; then
    jw "CONTROLLER stop $(ctl_pid)"; kill -TERM "$(ctl_pid)"
    for i in $(seq 1 45); do ctl_alive || break; sleep 1; done
    if ctl_alive; then jw "CONTROLLER kill $(ctl_pid)"; kill -KILL "$(ctl_pid)"; sleep 2; fi
    ! ctl_alive || die "the controller is still alive"
  fi
  for i in $(seq 1 10); do [ -s "$T17/controller.exit" ] && break; sleep 1; done
  listeners; [ -z "$LST" ] || die "a listener is still open: $LST"
  jw "CONTROLLER exited $(cat "$T17/controller.exit" 2>/dev/null || echo unknown)"
  echo "controller stopped; exit status $(cat "$T17/controller.exit" 2>/dev/null || echo unknown)"
}
metrics() { curl -fsS "http://$METRICS/metrics" | grep -E '^equipo_hosted_' || die "metrics unreadable"; }
# dbread SQL: read a copy of the stopped controller's database.
dbread() {
  ! ctl_alive || die "stop the controller before reading its database"
  rm -rf "$T17/dbcopy"; mkdir "$T17/dbcopy"; cp "$T17"/controller.db* "$T17/dbcopy/"
  python3 -I -c 'import sqlite3,sys
con = sqlite3.connect(sys.argv[1])
for r in con.execute(sys.argv[2]): print("\t".join("" if c is None else str(c) for c in r))' "$T17/dbcopy/controller.db" "$1"
}
# gotest LOG ARGS...: run go test with output to LOG; record VM IDs it names; return its status.
gotest() {
  local log=$1 rc had=0 t0; shift; case $- in *e*) had=1;; esac
  t0=$(date -u +%FT%T.%3NZ); jw "PHASE $(basename "$log") start $t0"
  set +e; (cd "$REPO" && CGO_ENABLED=0 go test "$@") > "$log" 2>&1; rc=$?; [ "$had" = 1 ] && set -e
  jw "PHASE $(basename "$log") end rc=$rc"
  harvest "$log" "$(basename "$log")" "$t0"
  grep -E '^(=== RUN|--- (PASS|FAIL|SKIP)|PASS|FAIL|ok|panic)' "$log" | tail -n 40 || true
  return "$rc"
}
true
ENVEOF
RUN=$(date -u +%m%d)-$(openssl rand -hex 3)
NAME=equipo-hosted-dev-t17-$RUN
cat > "$TMPDIR/equipo-t17/run.env" <<RUNEOF
export PIN_SHA='bdf85fb70f26094b99241de3f1285de92a76a759'
export RUN=$RUN NAME=$NAME
export OPERATOR_ROLE=$NAME-conn-op BUILD_ROLE=$NAME-build CONN_NAME=$NAME-egress IMAGE_NAME=$NAME
export BUCKET=$NAME-640012953448 LOG_GROUP=/aws/lambda-microvms/$NAME TOPIC_NAME=$NAME-alerts SG_NAME=$NAME-vm
export TAGS_EC2="Key=purpose,Value=equipo-hosted-dev Key=run,Value=$RUN"
RUNEOF
touch "$TMPDIR/equipo-t17/ledger.env" "$TMPDIR/equipo-t17/journal.tsv" "$TMPDIR/equipo-t17/vms.tsv"
. "$TMPDIR/equipo-t17/env.sh"
case "$PIN_SHA" in *'<'*) die "PIN_SHA in run.env is not filled in";; esac
jw "RUN $RUN start pin=$PIN_SHA"
(cd "$REPO" && CGO_ENABLED=0 go build -tags hostedlive -o "$LIVECTL" ./internal/isolatedjob/awsjob/livectl)
[ -x "$LIVECTL" ] || die "livectl did not build"
echo "T17=$T17 RUN=$RUN NAME=$NAME LIVECTL=$LIVECTL"
  • The PIN_SHA line in run.env carries the same value as 0.1. livectl is built from the checked-out code, which 0.1 proved is the pinned revision.
  • Expected: one line with the scratch path, the run ID and the base name. Record the T17= path: sandboxed blocks find it through $TMPDIR, and the sandbox-off blocks (R37) set it from this line. The environment file refuses to load if the directory is not there.
  • Abort if: the scratch directory already exists.

0.3 First AWS call: who am I

set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"; guard
aws sts get-caller-identity --query '[Account,Arn]' --output text
lvr caller; must
[ "$(jq -r '"\(.Account) \(.Region)"' <<<"$OUT")" = "640012953448 eu-west-1" ] || die "livectl sees $(jq -c . <<<"$OUT")"
  • Expected: 640012953448 and an ARN in that account, from the CLI and from livectl.
  • Abort if: anything else. Nothing else runs.

0.4 Observations and collision checks

Every name below contains the random run ID, so a collision is not expected; each check still reads the exact name and must get the "does not exist" answer.

set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"; guard
need RUN NAME OPERATOR_ROLE BUILD_ROLE CONN_NAME IMAGE_NAME BUCKET LOG_GROUP TOPIC_NAME
try aws resourcegroupstaggingapi get-resources --tag-filters Key=purpose,Values=$TAGV --query 'ResourceTagMappingList[].ResourceARN' --output text; must
echo "observation: resources already tagged purpose=$TAGV (not ours, never touched): [$OUT]"
try aws ec2 describe-vpcs --filters Name=tag:run,Values=$RUN --query 'Vpcs[].VpcId' --output text; must; [ -z "$OUT" ] || die "a VPC already has run=$RUN"
for r in "$OPERATOR_ROLE" "$BUILD_ROLE"; do try aws iam get-role --role-name "$r"; expect_err NoSuchEntity; done
lvr connector get -id "$CONN_NAME"; { [ "$RC" != 0 ] && [ "$ECODE" = ResourceNotFoundException ]; } || die "connector name $CONN_NAME: rc $RC ${ECODE:-} (it exists, or the check could not run)"
lvr image list -name "$IMAGE_NAME"; must; list_items || die "malformed image list reply (collision check)"
[ "$(jq --arg n "$IMAGE_NAME" '[.[] | select(.Name == $n)] | length' <<<"$ITEMS")" = 0 ] || die "image name $IMAGE_NAME exists"
get _v aws s3api list-buckets --prefix "$BUCKET" --query "length(Buckets[?Name=='$BUCKET'])" --output json; [ "$_v" = 0 ] || die "bucket $BUCKET exists in this account"
try aws logs describe-log-groups --log-group-name-prefix "$LOG_GROUP" --query 'logGroups[].logGroupName' --output text; must; [ -z "$OUT" ] || die "log group exists: $OUT"
get _v aws sns list-topics --query "length(Topics[?TopicArn=='arn:aws:sns:eu-west-1:$ACCOUNT:$TOPIC_NAME'])" --output json; [ "$_v" = 0 ] || die "topic $TOPIC_NAME exists"
jw "COLLISION-CHECKS clean"; echo "collision checks clean"
  • Expected: one observation line; collision checks clean. A collision is "anything not in the ledger", a hard stop.
  • Abort if: any name exists, or a lookup fails. The image, bucket and topic checks list and match the exact name (the CLI reads every page), so they need no error code. A bucket name held by another account is not listed here; create-bucket in 3.1 then fails before anything is created, which is an abort.

---

1. Network

1.1 VPC, DNS off, and its default resources tagged

set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"; guard
need RUN NAME TAGS_EC2
intent vpc "tag:run=$RUN"
try aws ec2 create-vpc --cidr-block 10.177.0.0/16 \
  --tag-specifications "ResourceType=vpc,Tags=[{Key=purpose,Value=$TAGV},{Key=run,Value=$RUN},{Key=Name,Value=$NAME}]" --output json; must
printf '%s\n' "$OUT" > "$T17/out/1.1-vpc.json"
rec VPC "$(jq -r .Vpc.VpcId "$T17/out/1.1-vpc.json")"
aws ec2 wait vpc-available --vpc-ids "$VPC"
aws ec2 modify-vpc-attribute --vpc-id "$VPC" --enable-dns-hostnames '{"Value":false}'
aws ec2 modify-vpc-attribute --vpc-id "$VPC" --enable-dns-support '{"Value":false}'
fact_eq "VPC enableDnsSupport" False aws ec2 describe-vpc-attribute --vpc-id "$VPC" --attribute enableDnsSupport --query EnableDnsSupport.Value --output text
fact_eq "VPC enableDnsHostnames" False aws ec2 describe-vpc-attribute --vpc-id "$VPC" --attribute enableDnsHostnames --query EnableDnsHostnames.Value --output text
get DEF aws ec2 describe-security-groups --filters Name=vpc-id,Values="$VPC" Name=group-name,Values=default --query 'SecurityGroups[].GroupId' --output text
[ "$(wc -w <<<"$DEF")" = 1 ] || die "default groups: [$DEF]"; rec DEF_SG "$DEF"
get DEF aws ec2 describe-route-tables --filters Name=vpc-id,Values="$VPC" Name=association.main,Values=true --query 'RouteTables[].RouteTableId' --output text
[ "$(wc -w <<<"$DEF")" = 1 ] || die "main route tables: [$DEF]"; rec MAIN_RTB "$DEF"
get DEF aws ec2 describe-network-acls --filters Name=vpc-id,Values="$VPC" Name=default,Values=true --query 'NetworkAcls[].NetworkAclId' --output text
[ "$(wc -w <<<"$DEF")" = 1 ] || die "default network ACLs: [$DEF]"; rec DEF_ACL "$DEF"
get DEF aws ec2 describe-security-group-rules --filters Name=group-id,Values="$DEF_SG" --query 'SecurityGroupRules[].SecurityGroupRuleId' --output text
[ -n "$DEF" ] || die "the default group has no rules to tag"; rec DEF_SG_RULES "$DEF"
aws ec2 create-tags --resources "$DEF_SG" "$MAIN_RTB" "$DEF_ACL" $DEF_SG_RULES --tags $TAGS_EC2
try aws ec2 describe-tags --filters Name=resource-id,Values="$VPC,$DEF_SG,$MAIN_RTB,$DEF_ACL,$(tr '\t ' ',,' <<<"$DEF_SG_RULES")" Name=key,Values=purpose --query 'length(Tags)' --output json
if [ "$RC" != 0 ]; then finding "purpose tag read failed: ${ECODE:-rc$RC}"
elif [ "$OUT" != $(( 4 + $(wc -w <<<"$DEF_SG_RULES") )) ]; then finding "purpose tag read back on $OUT resources"; fi
echo "VPC $VPC: DNS support and hostnames off; defaults tagged: $DEF_SG $MAIN_RTB $DEF_ACL $DEF_SG_RULES"
  • Expected: the last line. The defaults go with the VPC in 10.3 and are verified gone in 10.8.
  • Abort if: the create, a default-resource lookup or the tagging fails. A differing or failed readback (DNS attributes, tag count) is a FINDING.

1.2 One VM subnet

set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"; guard
need VPC RUN NAME
intent subnet "tag:run=$RUN"
try aws ec2 create-subnet --vpc-id "$VPC" --cidr-block 10.177.1.0/24 --availability-zone eu-west-1a \
  --tag-specifications "ResourceType=subnet,Tags=[{Key=purpose,Value=$TAGV},{Key=run,Value=$RUN},{Key=Name,Value=$NAME-vm}]" --output json; must
printf '%s\n' "$OUT" > "$T17/out/1.2-subnet.json"
rec SUBNET "$(jq -r .Subnet.SubnetId "$T17/out/1.2-subnet.json")"
aws ec2 wait subnet-available --subnet-ids "$SUBNET"
fact_eq "subnet readback" "$VPC	10.177.1.0/24	eu-west-1a	False" aws ec2 describe-subnets --subnet-ids "$SUBNET" --query 'Subnets[0].[VpcId,CidrBlock,AvailabilityZone,MapPublicIpOnLaunch]' --output text
echo "subnet $SUBNET ok"
  • Abort if: creation fails (an unsupported zone would be a stop; U10 is settled). A readback that differs or fails is a FINDING.

1.3 The subnet's own route table, local route only

set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"; guard
need VPC SUBNET RUN NAME
intent route-table "tag:run=$RUN"
try aws ec2 create-route-table --vpc-id "$VPC" \
  --tag-specifications "ResourceType=route-table,Tags=[{Key=purpose,Value=$TAGV},{Key=run,Value=$RUN},{Key=Name,Value=$NAME-vm}]" --output json; must
printf '%s\n' "$OUT" > "$T17/out/1.3-rtb.json"
rec RTB "$(jq -r .RouteTable.RouteTableId "$T17/out/1.3-rtb.json")"
intent route-table-association "" "$RTB/$SUBNET"
try aws ec2 associate-route-table --route-table-id "$RTB" --subnet-id "$SUBNET" --query AssociationId --output text; must
rec RTB_ASSOC "$OUT"
fact_eq "routes" "10.177.0.0/16	local	active" aws ec2 describe-route-tables --route-table-ids "$RTB" --query 'RouteTables[0].Routes[].[DestinationCidrBlock,GatewayId,State]' --output text
fact_eq "the subnet's route table" "$RTB" aws ec2 describe-route-tables --filters Name=association.subnet-id,Values="$SUBNET" --query 'RouteTables[].RouteTableId' --output text
echo "route table $RTB: local route only, associated"

1.4 Security group with no rules

set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"; guard
need VPC RUN SG_NAME
intent security-group "$SG_NAME"
try aws ec2 create-security-group --group-name "$SG_NAME" --description "Task 17 VM group, no rules" --vpc-id "$VPC" \
  --tag-specifications "ResourceType=security-group,Tags=[{Key=purpose,Value=$TAGV},{Key=run,Value=$RUN},{Key=Name,Value=$SG_NAME}]" --output json; must
printf '%s\n' "$OUT" > "$T17/out/1.4-sg.json"
rec SG "$(jq -r .GroupId "$T17/out/1.4-sg.json")"
aws ec2 describe-security-group-rules --filters Name=group-id,Values="$SG" --output json > "$T17/out/1.4-rules.json"
jq -e '[.SecurityGroupRules[] | select(.IsEgress)] | length == 1' "$T17/out/1.4-rules.json" >/dev/null || finding "not exactly one default egress rule: $(jq -c . "$T17/out/1.4-rules.json")"
jq -e '[.SecurityGroupRules[] | select(.IsEgress | not)] | length == 0' "$T17/out/1.4-rules.json" >/dev/null || finding "the new group has inbound rules"
rules=$(jq -r '.SecurityGroupRules[] | select(.IsEgress) | .SecurityGroupRuleId' "$T17/out/1.4-rules.json")
[ -z "$rules" ] || [ "$(aws ec2 revoke-security-group-egress --group-id "$SG" --security-group-rule-ids $rules --query Return --output text)" = True ] || die "revoking the default egress rules failed"
get got aws ec2 describe-security-groups --group-ids "$SG" --query 'SecurityGroups[0].[length(IpPermissions),length(IpPermissionsEgress)]' --output text
[ "$got" = "0	0" ] || finding "rules left: [$got]"
fact_eq "VM group rule count" 0 aws ec2 describe-security-group-rules --filters Name=group-id,Values="$SG" --query 'length(SecurityGroupRules)' --output text
echo "security group $SG: no rules"

---

2. Connector

2.1 The connector's network-interface role

The trust policy is the one AWS documents for the connector operator role (Lambda Web Functions networking guide: lambda.amazonaws.com, sts:AssumeRole), plus sts:TagSession, which only lets Lambda tag the session it assumes. Attempts 2 and 3 showed a narrow, scoped policy is refused when the connector is created, even 3.3 minutes later, while the AWS-managed AWSLambdaNetworkConnectorOperatorPolicy plus an inline delete was accepted. So, for this throwaway dev run (Paul, 2026-11-25 and 2026-11-28), the role gets the managed policy from the start, plus an inline ec2:DeleteNetworkInterface (the managed policy has none). The delete is scoped as narrowly as EC2 allows before the interfaces exist: this account and region, network-interface resources only, only interfaces whose ec2:ManagedResourceOperator is the Lambda connector service, and only interfaces in this run's subnet. The block then waits 120 s for IAM propagation, the wait that preceded attempt 3's accepted call.

set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"; guard
need SUBNET OPERATOR_ROLE RUN
cat > "$T17/iam/lambda-trust.json" <<'TEOF'
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"Service":"lambda.amazonaws.com"},"Action":["sts:AssumeRole","sts:TagSession"]}]}
TEOF
A=arn:aws:ec2:eu-west-1:640012953448
cat > "$T17/iam/operator-delete.json" <<TEOF
{"Version":"2012-10-17","Statement":[
 {"Sid":"DeleteLambdaConnectorEniOnly","Effect":"Allow","Action":"ec2:DeleteNetworkInterface","Resource":"$A:network-interface/*",
  "Condition":{"StringEquals":{"ec2:ManagedResourceOperator":"network-connectors.lambda.amazonaws.com"},
   "ArnEquals":{"ec2:Subnet":"$A:subnet/$SUBNET"}}}]}
TEOF
jq -e . "$T17/iam/operator-delete.json" >/dev/null
intent iam-role "$OPERATOR_ROLE"
try aws iam create-role --role-name "$OPERATOR_ROLE" --description "Task 17 connector network interfaces, run $RUN" \
  --assume-role-policy-document "file://$T17/iam/lambda-trust.json" \
  --tags Key=purpose,Value=$TAGV Key=run,Value=$RUN --query Role.Arn --output text; must
arn_ok "$OUT"; rec OPERATOR_ROLE_ARN "$OUT"
aws iam attach-role-policy --role-name "$OPERATOR_ROLE" --policy-arn arn:aws:iam::aws:policy/AWSLambdaNetworkConnectorOperatorPolicy
rec OPERATOR_MANAGED_POLICY arn:aws:iam::aws:policy/AWSLambdaNetworkConnectorOperatorPolicy
aws iam put-role-policy --role-name "$OPERATOR_ROLE" --policy-name t17-connector-eni-delete --policy-document "file://$T17/iam/operator-delete.json"
rec OPERATOR_INLINE_POLICY t17-connector-eni-delete
aws iam wait role-exists --role-name "$OPERATOR_ROLE"
fact_json "operator inline policies" '["t17-connector-eni-delete"]' aws iam list-role-policies --role-name "$OPERATOR_ROLE" --query 'PolicyNames' --output json
fact_json "operator managed policies" '["AWSLambdaNetworkConnectorOperatorPolicy"]' aws iam list-attached-role-policies --role-name "$OPERATOR_ROLE" --query 'AttachedPolicies[].PolicyName' --output json
echo "waiting 120 s for IAM propagation before Lambda assumes the operator role"; sleep 120
echo "operator role $OPERATOR_ROLE_ARN ready"
  • Abort if: a create, attach or put call fails (2.2 needs the role).
  • The two readbacks are facts: fact_json compares the compacted JSON, and a difference is a FINDING.

2.2 Create the VPC_EGRESS connector for MicroVMs (once)

set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"; guard
need SUBNET SG OPERATOR_ROLE_ARN CONN_NAME RUN
intent connector "$CONN_NAME" "token=$CONN_NAME-1"
lv connector create -name "$CONN_NAME" -role "$OPERATOR_ROLE_ARN" -subnet "$SUBNET" -sg "$SG" \
  -client-token "$CONN_NAME-1" -tag purpose=$TAGV -tag run=$RUN
if [ "$RC" != 0 ]; then
  if [ "$ECODE" = InvalidParameterValueException ] && grep -qF 'invalid ConnectorOperatorRole permissions' <<<"$LV_MSG"; then
    msg=$LV_MSG
    lvr connector get -id "$CONN_NAME"
    if [ "$RC" != 0 ] && [ "$ECODE" = ResourceNotFoundException ]; then jw "NOTCREATED connector attempt 1"; fi
    die "the connector was refused with the managed operator policy ($msg); 2.3 onwards needs it"
  fi
  die "connector create: rc $RC ${ECODE:-} ${LV_MSG:-$ERR} (uncertain: S.2 reconciles it)"
fi
printf '%s\n' "$OUT" > "$T17/out/2.2-connector.json"
arn_ok "$(jq -r .Arn "$T17/out/2.2-connector.json")"
rec CONN_ARN "$(jq -r .Arn "$T17/out/2.2-connector.json")"; rec CONN_ID "$(jq -r .Id "$T17/out/2.2-connector.json")"
[ "$CONN_ARN" = "arn:aws:lambda:eu-west-1:$ACCOUNT:network-connector:$CONN_ID" ] || die "connector ARN has an unexpected form: $CONN_ARN"
rec CONN_OPERATOR_POLICY "managed AWSLambdaNetworkConnectorOperatorPolicy plus inline delete"
jw "FACT connector create reply: $(jq -c '{State,Version,VersionArn,LatestVersion,LatestVersionArn}' "$T17/out/2.2-connector.json")"
jq -c '{Arn,Id,State,Version,VersionArn}' "$T17/out/2.2-connector.json"
  • Expected: state PENDING. livectl sends no ElasticIpConfiguration, so the connector gets none; 2.4 and 5.6 confirm it.
  • Abort if: the create fails. A refusal leaves no connector (attempt 2's evidence); anything else is uncertain and S.2 reconciles it by name.

2.3 Wait for ACTIVE (spike and attempt 3: about 4.5 min; bound 15 min)

set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"; guard
need CONN_ARN
lv_wait 900 connector wait-active -id "$CONN_ARN" -interval 15s
printf '%s\n' "$OUT" > "$T17/out/2.3-active.json"
jq -c '{State,StateReason,StateReasonCode}' "$T17/out/2.3-active.json" 2>/dev/null || true
[ "$RC" = 0 ] || die "connector not ACTIVE (rc $RC, ${ECODE:-no code}); 2.4 onwards needs it"
jw "TIMING connector-active"
  • Abort if: a failed state (exit 6, the reply shows StateReason) or the bound runs out (exit 5).

2.4 The version-1 qualified ARN, facts about versions, and the interfaces

A new connector starts at version 1 (pinned SDK, CreateNetworkConnector). Attempt 3's discovery read <arn>:1 and got Version 1, ACTIVE; the unqualified read carries only LatestVersion and LatestVersionArn. The launches and the 5.6 audit need the qualified ARN, so that read is a requirement; the rest are facts.

set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"; guard
need CONN_ARN CONN_ID SUBNET SG VPC
lvr connector get -id "$CONN_ARN:1"; must
printf '%s\n' "$OUT" > "$T17/out/2.4-qualified.json"
jq -e --arg q "$CONN_ARN:1" --arg s "$SUBNET" --arg g "$SG" '.Version == 1 and .VersionArn == $q and .State == "ACTIVE"
  and .Configuration.Value.SubnetIds == [$s] and .Configuration.Value.SecurityGroupIds == [$g]
  and .Configuration.Value.AssociatedComputeResourceTypes == ["MicroVm"]' "$T17/out/2.4-qualified.json" >/dev/null \
  || die "the version-1 read does not show this run's ACTIVE connector: $(jq -c '{Version,VersionArn,State,Configuration}' "$T17/out/2.4-qualified.json")"
rec CONN_VERSION 1; rec CONN_QARN "$CONN_ARN:1"
fact_lv "connector Elastic IP configuration" "null" '.Configuration.Value.ElasticIpConfiguration' connector get -id "$CONN_QARN"
lvr connector get -id "$CONN_ARN"
if [ "$RC" = 0 ]; then
  jw "FACT unqualified read: $(jq -c '{Version,VersionArn,LatestVersion,LatestVersionArn,ServerTime:.ResultMetadata.ServerTime}' <<<"$OUT")"
  [ "$(jq -r .LatestVersionArn <<<"$OUT")" = "$CONN_QARN" ] || finding "unqualified read: LatestVersionArn is $(jq -r .LatestVersionArn <<<"$OUT"), not $CONN_QARN"
else finding "unqualified connector read failed: ${ECODE:-rc$RC}"; fi
lvr connector list-versions -id "$CONN_ARN"
if [ "$RC" = 0 ] && list_items; then jw "FACT connector versions: $(jq -c '[.[] | {Version,VersionArn,State}]' <<<"$ITEMS")"
elif [ "$RC" = 0 ]; then finding "connector version list reply is malformed"
else finding "connector version list failed: ${ECODE:-rc$RC}"; fi
eni_snapshot soft "2.4, connector ACTIVE"
echo "qualified connector ARN: $CONN_QARN"
  • Expected: the version-1 read is this run's ACTIVE connector, in this subnet with this group. No Elastic IP configuration. Attempt 3 saw no interfaces while ACTIVE, which is recorded as a fact. Interfaces Lambda creates later are recorded by ID by eni_snapshot in 9.B, 6.1, 7.2 and 8.1 (while VMs run) and in 10.2 just before the connector is deleted; 10.2 then proves each recorded ID gone. An interface outside this run's subnet is a hard stop.
  • Abort if: the version-1 read fails or shows another connector; everything after needs it.

---

3. Image

The API builds an image from a zip in S3 holding a Dockerfile and its files, on a Lambda-managed base image, with a build role that can read the zip and write build logs. Memory, x86_64 and the ALL capability are set per image version, so Small (2048 MiB) and Large (4096 MiB) are two versions: create, then one update. The image is a static Go binary that answers 200 on every hook path on port 9000 inside the VM; the run hook must answer, because the adapter always sends a run hook payload.

3.1 S3 bucket

set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"; guard
need BUCKET RUN
intent s3-bucket "$BUCKET"
try aws s3api create-bucket --bucket "$BUCKET" --create-bucket-configuration LocationConstraint=eu-west-1 --output json; must
rec BUCKET_CREATED "$BUCKET"
aws s3api put-public-access-block --bucket "$BUCKET" --public-access-block-configuration BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true
aws s3api put-bucket-tagging --bucket "$BUCKET" --tagging "TagSet=[{Key=purpose,Value=$TAGV},{Key=run,Value=$RUN}]"
fact_eq "bucket run tag" "$RUN" aws s3api get-bucket-tagging --bucket "$BUCKET" --query "TagSet[?Key=='run'].Value" --output text
echo "bucket $BUCKET ok"

3.2 Log group for the build

set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"; guard
need LOG_GROUP RUN
intent log-group "$LOG_GROUP"
try aws logs create-log-group --log-group-name "$LOG_GROUP" --tags purpose=$TAGV,run=$RUN; must
rec LOG_GROUP_CREATED "$LOG_GROUP"
aws logs put-retention-policy --log-group-name "$LOG_GROUP" --retention-in-days 1
fact_eq "log group and retention" "$LOG_GROUP	1" aws logs describe-log-groups --log-group-name-prefix "$LOG_GROUP" --query 'logGroups[].[logGroupName,retentionInDays]' --output text

3.3 Build role (least privilege)

Same trust policy as 2.1. The current getting-started page prints sts:AssumeRole only; Astra's review cites a version with sts:TagSession. Granting both satisfies either. Permissions are the guide's, narrowed to the one S3 key and the one log group. It is a build role only: no VM ever gets an execution role (spec §3, §15).

set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"; guard
need BUILD_ROLE BUCKET LOG_GROUP RUN
L="arn:aws:logs:eu-west-1:640012953448:log-group:$LOG_GROUP"
cat > "$T17/iam/build.json" <<EOF
{"Version":"2012-10-17","Statement":[
 {"Sid":"ReadTheCodeArtifact","Effect":"Allow","Action":"s3:GetObject","Resource":"arn:aws:s3:::$BUCKET/t17/app.zip"},
 {"Sid":"WriteBuildLogsToThisGroup","Effect":"Allow","Action":["logs:CreateLogGroup","logs:CreateLogStream","logs:PutLogEvents"],"Resource":["$L","$L:*"]}]}
EOF
jq -e . "$T17/iam/build.json" >/dev/null
intent iam-role "$BUILD_ROLE"
try aws iam create-role --role-name "$BUILD_ROLE" --description "Task 17 MicroVM image build, run $RUN" \
  --assume-role-policy-document "file://$T17/iam/lambda-trust.json" \
  --tags Key=purpose,Value=$TAGV Key=run,Value=$RUN --query Role.Arn --output text; must
arn_ok "$OUT"; rec BUILD_ROLE_ARN "$OUT"
aws iam put-role-policy --role-name "$BUILD_ROLE" --policy-name t17-build --policy-document "file://$T17/iam/build.json"
aws iam wait role-exists --role-name "$BUILD_ROLE"
fact_eq "build role inline policy" t17-build aws iam list-role-policies --role-name "$BUILD_ROLE" --query 'PolicyNames' --output text
echo "waiting 60 s for IAM propagation before Lambda assumes the build role"; sleep 60

3.4 Hook binary, Dockerfile, hooks and zip (no AWS call)

set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"
cd "$T17/image"
cat > hookd.go <<'EOF'
// hookd answers every Lambda MicroVM lifecycle hook with 200. Task 17 only.
package main

import (
	"io"
	"log"
	"net/http"
)

func main() {
	http.HandleFunc("/aws/lambda-microvms/runtime/v1/", func(w http.ResponseWriter, r *http.Request) {
		n, _ := io.Copy(io.Discard, r.Body)
		log.Printf("hook %s %d bytes", r.URL.Path, n)
		w.WriteHeader(http.StatusOK)
	})
	log.Fatal(http.ListenAndServe(":9000", nil))
}
EOF
cat > Dockerfile <<'EOF'
FROM public.ecr.aws/lambda/microvms:al2023-minimal
COPY hookd /usr/local/bin/hookd
CMD ["/usr/local/bin/hookd"]
EOF
cat > hooks.json <<'EOF'
{"port":9000,
 "microvmHooks":{"run":"ENABLED","runTimeoutInSeconds":10,"resume":"ENABLED","resumeTimeoutInSeconds":10,
   "suspend":"ENABLED","suspendTimeoutInSeconds":10,"terminate":"ENABLED","terminateTimeoutInSeconds":10},
 "microvmImageHooks":{"ready":"ENABLED","readyTimeoutInSeconds":120,"validate":"DISABLED"}}
EOF
jq -e . hooks.json >/dev/null
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -trimpath -ldflags=-s -o hookd hookd.go
chmod 0755 hookd
[ "$(head -c 4 hookd | od -An -c | tr -d ' ')" = '177ELF' ] || die "hookd is not an ELF binary"
python3 -I -m zipfile -c app.zip Dockerfile hookd
[ "$(python3 -I -c 'import zipfile;print(" ".join(sorted(zipfile.ZipFile("app.zip").namelist())))')" = "Dockerfile hookd" ] || die "zip contents differ"
sha256sum app.zip

3.5 Digest, and the upload that proves it (object tagged)

AWS has no content digest for a MicroVM image, so the controller's allowlist key (sha256: and 64 lower-case hex digits) is the SHA-256 of the exact zip the image is built from. S3 rejects the upload if the bytes do not match the checksum sent; the read-back shows S3 holds that checksum; 3.8 shows each version names this object.

set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"; guard
need BUCKET RUN
cd "$T17/image"
rec DIGEST "sha256:$(sha256sum app.zip | cut -d' ' -f1)"
B64=$(openssl dgst -sha256 -binary app.zip | base64)
rec ARTIFACT_B64 "$B64"
intent s3-object "s3://$BUCKET/t17/app.zip"
try aws s3api put-object --bucket "$BUCKET" --key t17/app.zip --body app.zip --checksum-algorithm SHA256 \
  --checksum-sha256 "$B64" --tagging "purpose=$TAGV&run=$RUN" --query ChecksumSHA256 --output text; must
[ "$OUT" = "$B64" ] || finding "put-object checksum [$OUT]"
rec ARTIFACT "s3://$BUCKET/t17/app.zip"
fact_eq "S3 object checksum" "$B64" aws s3api head-object --bucket "$BUCKET" --key t17/app.zip --checksum-mode ENABLED --query ChecksumSHA256 --output text
fact_eq "S3 object run tag" "$RUN" aws s3api get-object-tagging --bucket "$BUCKET" --key t17/app.zip --query "TagSet[?Key=='run'].Value" --output text
echo "artifact $ARTIFACT digest $DIGEST"

3.6 Managed base image and version

livectl reads each base version's Status and SupportedCpuConfigurations (the CLI dropped them). The block picks the newest AVAILABLE version that supports x86_64, and records the next one down for the pre-approved step down in 3.7 and 3.8.

set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"; guard
lvr image base-versions; must
printf '%s\n' "$OUT" > "$T17/out/3.6-base.json"
list_items || die "malformed base version list reply; the image needs a base version"
jq -r '.[] | [.ImageVersion, .Status, ([.SupportedCpuConfigurations[]?.Architecture] | join(","))] | @tsv' <<<"$ITEMS"
rec BASE_ARN "$(jq -r '.BaseImage' "$T17/out/3.6-base.json")"
[ "$BASE_ARN" = arn:aws:lambda:eu-west-1:aws:microvm-image:al2023-1 ] || finding "base image ARN is $BASE_ARN"
vs=$(jq -r '[.[] | select(.Status == "AVAILABLE" and any(.SupportedCpuConfigurations[]?; .Architecture == "X86_64"))] | .[0:2][] | .ImageVersion' <<<"$ITEMS")
v1=$(sed -n 1p <<<"$vs"); v2=$(sed -n 2p <<<"$vs")
[ -n "$v1" ] || die "no AVAILABLE base version supports x86_64; the image needs one"
rec BASE_VER "$v1"
if [ -n "$v2" ]; then rec BASE_VER_DOWN "$v2"; else finding "only one AVAILABLE x86_64 base version ($v1): no step down available"; fi
  • Expected: the newest AVAILABLE x86_64 version, and one below it.
  • Abort if: the list fails, or no version is both AVAILABLE and x86_64.

3.7 Create the image: Small version

Two pre-approved retries, each at most once:

  • A refusal about the build role, which was created in 3.3, gets the propagation treatment: confirm no image exists, wait 120 s, retry with the same base version. It counts only if the code is ValidationException, AccessDeniedException or InvalidParameterValueException; the service's message names the build role (its name or ARN) or Lambda assuming it ("build role", "assume role"); and it is not a denial of the caller ("is not authorized to perform").
  • Any other refusal that leaves no image steps down once to BASE_VER_DOWN (Paul, 2026-11-28).

Anything else, or a third refusal, is a stop: the image is needed.

set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"; guard
need IMAGE_NAME ARTIFACT BASE_ARN BASE_VER BUILD_ROLE_ARN BUILD_ROLE LOG_GROUP RUN
# create_image BASEVERSION N: one attempt with client token $IMAGE_NAME-create-N. IMG_RC=0 created;
# 1 a build-role refusal; 2 another refusal; both with no image left. Anything uncertain aborts.
create_image() {
  intent microvm-image "$IMAGE_NAME" "token=$IMAGE_NAME-create-$2" "base=$1"
  lv image create -name "$IMAGE_NAME" -description "Task 17 minimal hook image, small, run $RUN" \
    -artifact "$ARTIFACT" -base "$BASE_ARN" -base-version "$1" -build-role "$BUILD_ROLE_ARN" \
    -hooks "$T17/image/hooks.json" -log-group "$LOG_GROUP" -memory 2048 \
    -client-token "$IMAGE_NAME-create-$2" -tag purpose=$TAGV -tag run=$RUN
  if [ "$RC" = 0 ]; then IMG_RC=0; return 0; fi
  [ "$LV_KIND" = api ] || die "image create attempt $2: ${LV_KIND:-rc$RC} (no answer: S.2 reconciles it)"
  IMG_CODE=$ECODE; IMG_MSG=$LV_MSG
  jw "REFUSED image attempt $2 (base $1): ${IMG_CODE} ${IMG_MSG}"
  lvr image list -name "$IMAGE_NAME"; must; list_items || die "malformed image list reply after a refused create"
  [ "$(jq --arg n "$IMAGE_NAME" '[.[] | select(.Name == $n)] | length' <<<"$ITEMS")" = 0 ] || die "a refused create left an image named $IMAGE_NAME"
  jw "NOTCREATED image attempt $2"
  case "$IMG_CODE" in ValidationException|AccessDeniedException|InvalidParameterValueException) role_code=yes;; *) role_code=no;; esac
  if [ "$role_code" = yes ] \
     && { grep -qF -e "$BUILD_ROLE_ARN" -e "$BUILD_ROLE" <<<"$IMG_MSG" || grep -qiE 'build role|assume (the )?(build )?role' <<<"$IMG_MSG"; } \
     && ! grep -qi 'is not authorized to perform' <<<"$IMG_MSG"; then IMG_RC=1; else IMG_RC=2; fi
}
ver=$BASE_VER; n=1; waited=no; stepped=no
while :; do
  create_image "$ver" "$n"
  [ "$IMG_RC" = 0 ] && break
  if [ "$IMG_RC" = 1 ] && [ "$waited" = no ]; then waited=yes; echo "build-role refusal: waiting 120 s, then the same version"; sleep 120
  elif [ "$IMG_RC" = 2 ] && [ "$stepped" = no ] && [ -n "${BASE_VER_DOWN:-}" ]; then
    stepped=yes; finding "image create from base $ver refused (${IMG_CODE}: ${IMG_MSG}); stepping down to $BASE_VER_DOWN"; ver=$BASE_VER_DOWN
  else die "image create refused (attempt $n, ${IMG_CODE}: ${IMG_MSG}); no pre-approved retry is left"; fi
  n=$((n + 1))
done
printf '%s\n' "$OUT" > "$T17/out/3.7-image.json"
arn_ok "$(jq -r .ImageArn "$T17/out/3.7-image.json")"
rec IMAGE_ARN "$(jq -r .ImageArn "$T17/out/3.7-image.json")"; rec VER_SMALL "$(jq -r .ImageVersion "$T17/out/3.7-image.json")"
rec BASE_VER_USED "$ver"; [ "$stepped" = no ] || rec BASE_STEPPED_DOWN yes
[ "$IMAGE_ARN" = "arn:aws:lambda:eu-west-1:$ACCOUNT:microvm-image:$IMAGE_NAME" ] || die "image ARN [$IMAGE_ARN]"
  • livectl always sends x86_64 and the ALL capability, and no egress connectors, so the build pulls its container base image over the default build path; running VMs get only the connector.

3.8 Wait for the Small version and check it (bound 50 min with the step down)

If the Small build fails and 3.7 has not stepped down, the block builds a new Small version from BASE_VER_DOWN by one update (pre-approved, once), and waits again.

set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"; guard
need IMAGE_ARN IMAGE_NAME VER_SMALL ARTIFACT BASE_ARN BUILD_ROLE_ARN LOG_GROUP RUN
lv_wait 1200 image wait-version -id "$IMAGE_ARN" -version "$VER_SMALL" -interval 15s
if [ "$RC" = 6 ] && [ -z "${BASE_STEPPED_DOWN:-}" ] && [ -n "${BASE_VER_DOWN:-}" ]; then
  finding "Small version $VER_SMALL failed to build from base ${BASE_VER_USED}: $(jq -r '.StateReason // empty' <<<"$OUT"); stepping down to $BASE_VER_DOWN"
  try aws logs filter-log-events --log-group-name "$LOG_GROUP" --limit 50 --query 'events[].message' --output text; [ "$RC" = 0 ] && printf '%s\n' "$OUT" | tail -n 20
  rec VER_SMALL_FAILED "$VER_SMALL"
  intent microvm-image-version "$IMAGE_NAME" "token=$IMAGE_NAME-update-small-2" "base=$BASE_VER_DOWN"
  lv image update -id "$IMAGE_ARN" -description "Task 17 minimal hook image, small, run $RUN, base $BASE_VER_DOWN" \
    -artifact "$ARTIFACT" -base "$BASE_ARN" -base-version "$BASE_VER_DOWN" -build-role "$BUILD_ROLE_ARN" \
    -hooks "$T17/image/hooks.json" -log-group "$LOG_GROUP" -memory 2048 -client-token "$IMAGE_NAME-update-small-2"; must
  rec VER_SMALL "$(jq -r .ImageVersion <<<"$OUT")"; rec BASE_VER_USED "$BASE_VER_DOWN"; rec BASE_STEPPED_DOWN yes
  lv_wait 1200 image wait-version -id "$IMAGE_ARN" -version "$VER_SMALL" -interval 15s
fi
if [ "$RC" != 0 ]; then
  try aws logs filter-log-events --log-group-name "$LOG_GROUP" --limit 50 --query 'events[].message' --output text; [ "$RC" = 0 ] && printf '%s\n' "$OUT" | tail -n 20
  die "the Small version did not build; the image is needed"
fi
lvr image get-version -id "$IMAGE_ARN" -version "$VER_SMALL"
if [ "$RC" = 0 ]; then
  printf '%s\n' "$OUT" > "$T17/out/3.8-small.json"
  jq -e --arg a "$ARTIFACT" '([.CpuConfigurations[].Architecture] == ["X86_64"]) and ([.Resources[].MinimumMemoryInMiB] == [2048])
    and (.AdditionalOsCapabilities == ["ALL"]) and (.CodeArtifact.Value == $a) and (.Hooks.Port == 9000)' "$T17/out/3.8-small.json" >/dev/null \
    || finding "the Small version differs from what the adapter checks: $(jq -c '{CpuConfigurations,Resources,AdditionalOsCapabilities,CodeArtifact,Hooks}' "$T17/out/3.8-small.json")"
  jw "FACT Small version: $(jq -c '{ImageVersion,State,Status,Tags}' "$T17/out/3.8-small.json")"
else finding "Small version read failed: ${ECODE:-rc$RC}"; fi
jw "TIMING image-small-built"
  • Expected: SUCCESSFUL ACTIVE; the fields the adapter's image check reads (checkImageVersion) match, or each difference is a FINDING (the adapter then refuses the version, and the contract shows it).
  • Abort if: no Small version builds, after the one step down.

3.9 Large version by one update, then both versions checked

set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"; guard
need IMAGE_ARN IMAGE_NAME ARTIFACT BASE_ARN BASE_VER_USED BUILD_ROLE_ARN LOG_GROUP VER_SMALL RUN
intent microvm-image-version "$IMAGE_NAME" "token=$IMAGE_NAME-update-1"
lv image update -id "$IMAGE_ARN" -description "Task 17 minimal hook image, large, run $RUN" \
  -artifact "$ARTIFACT" -base "$BASE_ARN" -base-version "$BASE_VER_USED" -build-role "$BUILD_ROLE_ARN" \
  -hooks "$T17/image/hooks.json" -log-group "$LOG_GROUP" -memory 4096 -client-token "$IMAGE_NAME-update-1"; must
printf '%s\n' "$OUT" > "$T17/out/3.9-image.json"
rec VER_LARGE "$(jq -r .ImageVersion "$T17/out/3.9-image.json")"
[ "$VER_LARGE" != "$VER_SMALL" ] || finding "the update returned the Small version $VER_SMALL"
lv_wait 1200 image wait-version -id "$IMAGE_ARN" -version "$VER_LARGE" -interval 15s
if [ "$RC" = 0 ]; then
  lvr image get-version -id "$IMAGE_ARN" -version "$VER_LARGE"
  if [ "$RC" = 0 ]; then
    jq -e '([.CpuConfigurations[].Architecture] == ["X86_64"]) and ([.Resources[].MinimumMemoryInMiB] == [4096]) and (.AdditionalOsCapabilities == ["ALL"])' <<<"$OUT" >/dev/null \
      || finding "the Large version differs: $(jq -c '{CpuConfigurations,Resources,AdditionalOsCapabilities}' <<<"$OUT")"
  else finding "Large version read failed: ${ECODE:-rc$RC}"; fi
else finding "the Large version did not build (rc $RC, ${ECODE:-}); no Large VM is ever launched, so the run goes on"; fi
fact_lv "Small version after the update" "SUCCESSFUL ACTIVE" '"\(.State) \(.Status)"' image get-version -id "$IMAGE_ARN" -version "$VER_SMALL"
lvr image get -id "$IMAGE_ARN"
if [ "$RC" = 0 ]; then
  case "$(jq -r .State <<<"$OUT")" in CREATED|UPDATED) ;; *) finding "image state $(jq -r .State <<<"$OUT")";; esac
  [ "$(jq -r '.Tags.run // empty' <<<"$OUT")" = "$RUN" ] || finding "image tags: $(jq -c .Tags <<<"$OUT")"
else finding "image read failed: ${ECODE:-rc$RC}"; fi
  • Expected: two versions, both SUCCESSFUL ACTIVE, 2048 and 4096 MiB; tags present. No Large VM is launched; the Large version exists so the config maps both sizes. Every difference is a FINDING.
  • Abort if: the update call itself fails (S.2 reconciles an uncertain reply).

---

4. SNS topic

The controller requires sns_topic_arn and stops at the first startup alert it cannot deliver, including on the crash restart (pre-flight concern 1); the topic exists from here to 10.7.

set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"; guard
need TOPIC_NAME RUN
intent sns-topic "$TOPIC_NAME"
try aws sns create-topic --name "$TOPIC_NAME" --tags Key=purpose,Value=$TAGV Key=run,Value=$RUN --query TopicArn --output text; must
[ "$OUT" = "arn:aws:sns:eu-west-1:$ACCOUNT:$TOPIC_NAME" ] || die "topic ARN [$OUT]"
rec TOPIC_ARN "$OUT"
fact_eq "topic run tag" "$RUN" aws sns list-tags-for-resource --resource-arn "$TOPIC_ARN" --query "Tags[?Key=='run'].Value" --output text
fact_eq "topic subscription count" 0 aws sns list-subscriptions-by-topic --topic-arn "$TOPIC_ARN" --query 'length(Subscriptions)' --output text
  • 0.4 proved the name did not exist, so create-topic's idempotent return cannot be someone else's topic. No subscription is made: alerts are read from the controller's metrics and database.

---

5. Keys, config, builds, and the audit before any launch

5.1 Keys and the self-signed certificate (pre-flight helper, no AWS call)

set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"
cd "$REPO" && EQUIPO_HOSTED_KEYGEN_DIR="$T17/keys" CGO_ENABLED=0 go test -tags hostedlive ./cmd/equipo-hosted-controller -run 'TestLiveKeygen$' -count=1 -v
for f in controller.key instance.key operator.key tls.key; do [ "$(stat -c %a "$T17/keys/$f")" = 600 ] || die "$f is not mode 600"; done
for f in controller.pub verify_keys.json tls.crt; do [ -s "$T17/keys/$f" ] || die "$f missing"; done
openssl x509 -in "$T17/keys/tls.crt" -noout -ext subjectAltName | grep -q 'IP Address:127.0.0.1' || die "certificate SAN is not 127.0.0.1"
jq -r '.[] | [.id, .role] | @tsv' "$T17/keys/verify_keys.json"
  • Expected: task17-instance instance and task17-operator operator.

5.2 Ports free

set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"
listeners; [ -z "$LST" ] || die "in use: $LST"; echo "ports 18443 and 18444 free"

5.3 Controller config and live contract config

set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"
need DIGEST IMAGE_ARN VER_SMALL VER_LARGE VPC SUBNET SG CONN_QARN TOPIC_ARN
jq -n --slurpfile vk "$T17/keys/verify_keys.json" --arg api "$API" --arg met "$METRICS" --arg d "$T17" \
  --arg digest "$DIGEST" --arg arn "$IMAGE_ARN" --arg small "$VER_SMALL" --arg large "$VER_LARGE" \
  --arg vpc "$VPC" --arg subnet "$SUBNET" --arg sg "$SG" --arg conn "$CONN_QARN" --arg topic "$TOPIC_ARN" '{
  listen: $api, metrics_listen: $met,
  tls_cert_file: ($d + "/keys/tls.crt"), tls_key_file: ($d + "/keys/tls.key"),
  database: ($d + "/controller.db"), signing_key_file: ($d + "/keys/controller.key"),
  verify_keys: $vk[0],
  images: [{digest: $digest, arn: $arn, versions: {small: $small, large: $large}}],
  region: "eu-west-1", vpc_id: $vpc, vm_subnet_id: $subnet, vm_security_group_id: $sg,
  connector_arn: $conn, egress: [], sns_topic_arn: $topic}' > "$T17/controller.json"
jq -n --arg digest "$DIGEST" --arg arn "$IMAGE_ARN" --arg small "$VER_SMALL" --arg large "$VER_LARGE" \
  --arg vpc "$VPC" --arg subnet "$SUBNET" --arg sg "$SG" --arg conn "$CONN_QARN" '{
  region: "eu-west-1", connector_id: $conn, vpc_id: $vpc, vm_subnet_id: $subnet, vm_security_group_id: $sg,
  image: $digest, image_arn: $arn, versions: {small: $small, large: $large}, egress: []}' > "$T17/live.json"
jq -e '[.. | strings] | all(. != "" and . != "null")' "$T17/controller.json" "$T17/live.json" >/dev/null || die "an empty value in a config"
jq -e '.egress == []' "$T17/controller.json" "$T17/live.json" >/dev/null || die "egress is not empty (R30)"
cat "$T17/controller.json" "$T17/live.json"

Filled in, controller.json reads (angle brackets are ledger values):

{
  "listen": "127.0.0.1:18443",
  "metrics_listen": "127.0.0.1:18444",
  "tls_cert_file": "<T17>/keys/tls.crt",
  "tls_key_file": "<T17>/keys/tls.key",
  "database": "<T17>/controller.db",
  "signing_key_file": "<T17>/keys/controller.key",
  "verify_keys": [
    {"id": "task17-instance", "role": "instance", "public_key": "<base64>"},
    {"id": "task17-operator", "role": "operator", "public_key": "<base64>"}
  ],
  "images": [{"digest": "<DIGEST>", "arn": "<IMAGE_ARN>", "versions": {"small": "<VER_SMALL>", "large": "<VER_LARGE>"}}],
  "region": "eu-west-1",
  "vpc_id": "<VPC>",
  "vm_subnet_id": "<SUBNET>",
  "vm_security_group_id": "<SG>",
  "connector_arn": "<CONN_ARN>:<CONN_VERSION>",
  "egress": [],
  "sns_topic_arn": "<TOPIC_ARN>"
}

5.4 Build the two controller binaries (no AWS call)

set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"
cd "$REPO"
[ -z "$(git diff "$PIN_SHA" HEAD -- . ':!docs')" ] && [ -z "$(git status --porcelain --untracked-files=all -- . ':!docs')" ] || die "code changed since 0.1"
CGO_ENABLED=0 go build -o "$T17/bin/controller" ./cmd/equipo-hosted-controller
CGO_ENABLED=0 go build -tags hostedlive -o "$T17/bin/controller-crash" ./cmd/equipo-hosted-controller
ls -l "$T17/bin"
  • controller is the normal build (no crash point); controller-crash is used only in 7.4.

5.5 Driver environment file (no AWS call)

set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"
need DIGEST
cat > "$T17/driver.env" <<EOF
export EQUIPO_HOSTED_LIVE_URL=https://$API
export EQUIPO_HOSTED_LIVE_CA_FILE=$T17/keys/tls.crt
export EQUIPO_HOSTED_LIVE_KEY_ID=task17-instance
export EQUIPO_HOSTED_LIVE_KEY_FILE=$T17/keys/instance.key
export EQUIPO_HOSTED_LIVE_CONTROLLER_KEY_FILE=$T17/keys/controller.pub
export EQUIPO_HOSTED_LIVE_IMAGE=$DIGEST
EOF
cat "$T17/driver.env"

5.6 Audit-only controller run: the SDK checks the network before any VM exists

Launches stay off (no EQUIPO_HOSTED_ENABLED). The reaper's first passes run the network audit through the SDK: VPC DNS both off, the subnet's table local-only, the group with no rules, and the connector read by its qualified ARN with VersionArn equal to it, ACTIVE, MicroVm only, this subnet and group only, and no service-managed Elastic IPs (network.go). This also binds the database to aws:640012953448:eu-west-1 (R28) and proves the SNS topic takes startup alerts.

set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"; guard
ok=yes
start_ctl "$T17/bin/controller" audit-only
if (ctl_ready); then
  grep -F 'launches enabled: false' "$T17/controller.log" || finding "the controller did not report launches off"
  if grep -F 'hosted controller: network audit failed' "$T17/controller.log"; then finding "the log shows a failed network audit"; ok=no; fi
else finding "the audit-only controller did not become ready (see controller.log)"; ok=no; fi
stop_ctl
dbread "select action, reason from audit where action in ('provider_bound','network_audit_passed','network_audit_failed') order by id"
n=$(dbread "select count(*) from audit where action='network_audit_failed'"); [ "$n" = 0 ] || { finding "$n network audit failures"; ok=no; }
n=$(dbread "select count(*) from audit where action='network_audit_passed'"); [ "$n" -ge 1 ] || { finding "no network audit passed"; ok=no; }
dbread "select namespace from provider_binding" | grep -qx "aws:$ACCOUNT:eu-west-1" || finding "database not bound to aws:$ACCOUNT:eu-west-1"
rec AUDIT_OK "$ok"
[ "$ok" = yes ] && jw "AUDIT passed before any launch" || echo "the audit did not pass: sections 7 and 8 will be skipped"
  • Expected: ready within 4 minutes with network_audit_passing 1, and no hosted controller: network audit failed; launches refused line in the log; provider_bound and at least one network_audit_passed row, no failure rows; clean stop, exit status 0.
  • If the audit does not pass, each failed check is a FINDING (the failure row names the property) and AUDIT_OK is no: sections 7 and 8, which need a ready controller, are skipped as FINDINGs; 6 and 9 do not use the controller and still run.

---

6. Live contract

Runs after 9.A to 9.F (client-token behaviour known, facts VMs settled).

6.1 Run it, then settle every VM it made

The test runs with go test -json, so each line of output carries the subtest it belongs to. The contract runs to completion (Paul, 2026-11-28); every VM it made is settled afterwards (a hard stop if one cannot be). Each failed subtest then becomes a FINDING with its own messages, labelled "known" when it is one of the two failures the adapter is expected to show, from its own output only.

set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"; guard
need IMAGE_ARN
! ctl_alive || die "the controller is running"
scan >/dev/null; [ -z "$LIVE" ] || die "live VMs of this image before the contract: $LIVE"
export EQUIPO_HOSTED_LIVE_CONFIG="$T17/live.json"
J="$T17/out/6-contract.json"
if gotest "$J" -tags hostedlive ./internal/isolatedjob/awsjob -run TestLiveContract -count=1 -v -json -timeout 60m; then rc=0; else rc=$?; fi
eni_snapshot soft "6.1, after the contract"
settle_all
[ -s "$J" ] || { finding "the contract wrote no test output (rc $rc)"; exit 0; }
jq -R -r 'fromjson? | select(.Action == "output") | .Output' "$J" > "$T17/out/6-contract.log"
if grep -E "microvm id is missing or malformed|microvm id is malformed|empty or malformed ref" "$T17/out/6-contract.log"; then finding "the adapter refused a MicroVM ID as malformed (R36)"; fi
grep -E 'visibility: Get showed new VM |list lag: List showed running VM ' "$T17/out/6-contract.log" || finding "the contract logged no visibility or list-lag lines"
top=$(jq -R -r 'fromjson? | select(.Test == "TestLiveContract" and (.Action == "pass" or .Action == "fail")) | .Action' "$J")
if [ "$rc" = 0 ] && [ "$top" = pass ]; then jw "CONTRACT pass"; echo "contract PASS"; exit 0; fi
[ "$top" = fail ] || finding "go test ended with rc $rc outside TestLiveContract ([$top]): build error, panic or timeout"
fails=$(jq -R -r 'fromjson? | select(.Action == "fail" and (.Test // "" | startswith("TestLiveContract/"))) | .Test' "$J" | sort -u)
sub_out() { jq -R -r --arg t "$1" 'fromjson? | select(.Test == $t and .Action == "output") | .Output' "$J" | grep -E '^\s+contract\.go:[0-9]+: ' | grep -vE 'contract\.go:[0-9]+: (visibility|list lag): ' || true; }
for f in $fails; do
  msgs=$(sub_out "$f"); n=$(grep -c . <<<"$msgs" || true); label=other
  case "$f" in
    TestLiveContract/StopUnknownRef)
      [ "$n" = 1 ] && grep -qE 'Stop\(contract-never-launched-[0-9a-f]+\) of a ref the provider never held = .*ValidationException.*, want nil$' <<<"$msgs" && label="known: ValidationException for an unknown ref (U11)";;
    TestLiveContract/ChangedSpecConflicts)
      [ "$n" = 1 ] && grep -qE 'Launch with the same attempt and a new bootstrap = \("", .*(ConflictException|ValidationException).*\), want ErrConflict$' <<<"$msgs" && label="known: refusal not mapped to ErrConflict";;
  esac
  finding "contract $f failed [$label]: $(tr '\n' ' ' <<<"$msgs")"
done
echo "contract finished with $(wc -w <<<"$fails") failed subtests, each recorded as a FINDING"
  • Expected: contract PASS, and settled: N VMs recorded (about 7 contract VMs, each with a 15-minute maximum duration). The visibility: Get showed new VM ... and list lag: List showed running VM ... lines are the measured delays (the pre-flight's 60 s and 30 s are guesses).
  • Known failures (each still a FINDING, for an adapter fix after the run), each only with exactly one failure line in its own output: StopUnknownRef with a ValidationException for a ref AWS never issued (U11); ChangedSpecConflicts where AWS refused the changed request, no VM was returned, and the adapter did not map the refusal to ErrConflict.
  • Hard stop only if: a VM it made cannot be settled.

---

7. Controller on docs-t1

7.1 Start with launches on, check readiness

set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"; guard
if [ "${AUDIT_OK:-}" != yes ]; then finding "section 7 skipped: the 5.6 audit did not pass"; rec SKIP_7 yes; exit 0; fi
scan >/dev/null; [ -z "$LIVE" ] || die "live VMs of this image: $LIVE"
start_ctl "$T17/bin/controller" sequence EQUIPO_HOSTED_ENABLED=1
if ! (ctl_ready); then finding "the controller did not become ready; section 7 skipped"; stop_ctl; rec SKIP_7 yes; exit 0; fi
grep -F 'launches enabled: true' "$T17/controller.log" || finding "the controller did not report launches enabled"

7.2 Driver sequence: launch Small, drain, quiescent, suspend, resume, stop with proof

set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"; guard
if [ -n "${SKIP_7:-}" ]; then echo "section 7 skipped"; exit 0; fi
. "$T17/driver.env"
ctl_alive || die "the controller is not running"
jw "PHASE sequence start"
if gotest "$T17/out/7.2-sequence.log" -tags hostedlive ./internal/hostedclient -run 'TestLiveControllerSequence$' -count=1 -v -timeout 30m; then rc=0; else rc=$?; fi
jw "PHASE sequence end rc=$rc"
grep -E 'attempt |launch:|running:|pause:|suspended:|resume:|stop:|timings:' "$T17/out/7.2-sequence.log" || true
eni_snapshot soft "7.2, after the sequence"
harvest_ctl
stop_ctl
settle_all
if grep -hE "microvm id is missing or malformed|microvm id is malformed|empty or malformed ref" "$T17/out/7.2-sequence.log" "$T17/controller.log"; then finding "a MicroVM ID was refused as malformed (R36)"; fi
[ "$rc" = 0 ] || finding "TestLiveControllerSequence failed (rc $rc); see 7.2-sequence.log"
att=$(grep -oE 'attempt task17-[0-9a-f]+' "$T17/out/7.2-sequence.log" | head -n 1 | cut -d' ' -f2 || true)
if [ -n "$att" ]; then
  rec SEQ_ATTEMPT "$att"
  dbread "select attempt_id, state, vm_ref, epoch, pause_generation, stop_proof_json from jobs where attempt_id='$SEQ_ATTEMPT'"
  dbread "select action, reason from audit where attempt_id='$SEQ_ATTEMPT' order by id"
else finding "the sequence log names no attempt"; fi
  • Expected: PASS and the timings: line (launch call a few seconds; to_running up to about a minute, since states are read once per 60 s pass; resume epoch one above the launch epoch; stop_to_proof about 2 to 3 minutes, R17). The job row is stopped with stop proof; its audit rows show launch, drain, quiescent, suspend, resume and stop in order.
  • A FAIL, a missing attempt or odd evidence is a FINDING; the controller is stopped and every VM settled either way.

7.3 Crash between the provider call and transaction 2: the launch step

set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"; guard
if [ -n "${SKIP_7:-}" ]; then echo "section 7 skipped"; exit 0; fi
. "$T17/driver.env"
rec CRASH_ATTEMPT "task17-crash-$(openssl rand -hex 4)"
rec CRASH_START "$(date -u +%FT%T)"
start_ctl "$T17/bin/controller-crash" crash EQUIPO_HOSTED_ENABLED=1 EQUIPO_HOSTED_CRASH_AFTER_LAUNCH=1
if ! (ctl_ready); then finding "the crash-build controller did not become ready; 7.3 and 7.4 skipped"; stop_ctl; rec SKIP_74 yes; exit 0; fi
grep -F 'EQUIPO_HOSTED_CRASH_AFTER_LAUNCH=1' "$T17/controller.log" || finding "the crash switch is not reported on"
export EQUIPO_HOSTED_LIVE_ATTEMPT="$CRASH_ATTEMPT" EQUIPO_HOSTED_LIVE_CRASH_STEP=launch
if gotest "$T17/out/7.3-launch.log" -tags hostedlive ./internal/hostedclient -run 'TestLiveCrashRecovery$' -count=1 -v -timeout 10m; then rc=0; else rc=$?; fi
[ "$rc" = 0 ] || finding "the launch step failed (rc $rc); see 7.3-launch.log"
_exited() { [ -s "$T17/controller.exit" ] && return 0; return 1; }
if ! (poll 60 2 "crash-build controller exit" _exited); then finding "the crash-build controller did not exit after the launch"; fi
stop_ctl
[ "$(cat "$T17/controller.exit" 2>/dev/null || true)" = 137 ] || finding "crash-build exit status $(cat "$T17/controller.exit" 2>/dev/null || echo unknown), want 137"
harvest_ctl
vm=$(grep -oE "provider launched mvm-[0-9A-Za-z-]+ for $CRASH_ATTEMPT" "$T17/controller.log" | tail -n 1 | cut -d' ' -f3 || true)
if [ -z "$vm" ]; then finding "the crash log names no launched VM; 7.4 skipped"; rec SKIP_74 yes; settle_all; exit 0; fi
rec CRASH_VM "$vm"
vm_get "$CRASH_VM"; echo "crash VM $CRASH_VM: $VST"
case "$VST" in PENDING|RUNNING) ;; *) finding "crash VM state $VST";; esac
jw "CRASH controller exited after launching $CRASH_VM"
  • Expected: the launch fails in transport (the test passes); exit status 137; the log line crash point: the provider launched <vm> for <attempt>; exiting before the Ref is saved; the VM PENDING or RUNNING. A launch refused because no audit has passed recently is a FINDING, like any other failed launch step; the controller is stopped and every VM settled.
  • The controller answering the launch, another exit status, or no launched VM is a FINDING; 7.4 is then skipped if there is no VM to recover. Every VM is settled.

7.4 Restart without the crash switch; Replay claims the one VM

start_ctl always clears EQUIPO_HOSTED_CRASH_AFTER_LAUNCH and sets only what it is given (pre-flight concern 3). The readiness check comes before the recovery driver; Replay runs on the second reaper pass, about 60 s after start (pre-flight concern 2).

set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"; guard
if [ -n "${SKIP_7:-}" ] || [ -n "${SKIP_74:-}" ]; then echo "7.4 skipped"; settle_all; exit 0; fi
. "$T17/driver.env"
need CRASH_ATTEMPT CRASH_VM CRASH_START
start_ctl "$T17/bin/controller" recover EQUIPO_HOSTED_ENABLED=1
if ! (ctl_ready); then finding "the restarted controller did not become ready; 7.4 skipped"; stop_ctl; settle_all; exit 0; fi
if tr '\0' '\n' < "/proc/$(ctl_pid)/environ" | grep -q '^EQUIPO_HOSTED_CRASH_AFTER_LAUNCH='; then finding "the crash switch is set on the restart; 7.4 skipped"; stop_ctl; settle_all; exit 0; fi
export EQUIPO_HOSTED_LIVE_ATTEMPT="$CRASH_ATTEMPT" EQUIPO_HOSTED_LIVE_CRASH_STEP=recover \
  EQUIPO_HOSTED_LIVE_OPERATOR_KEY_ID=task17-operator EQUIPO_HOSTED_LIVE_OPERATOR_KEY_FILE="$T17/keys/operator.key"
if gotest "$T17/out/7.4-recover.log" -tags hostedlive ./internal/hostedclient -run 'TestLiveCrashRecovery$' -count=1 -v -timeout 15m; then rc=0; else rc=$?; fi
grep -E 'recover:|listed vm|stop:' "$T17/out/7.4-recover.log" || true
harvest_ctl
stop_ctl
settle_all
[ "$rc" = 0 ] || finding "the recover step failed (rc $rc); see 7.4-recover.log"
grep -q "recover: job $CRASH_ATTEMPT holds vm $CRASH_VM" "$T17/out/7.4-recover.log" || finding "the job does not hold $CRASH_VM"
grep -F 'restart stop requested, elapsed time unknown' "$T17/controller.log" && finding "the restart stopped a job for unknown elapsed time"
scan >/dev/null
n=$(awk -F'\t' -v t="$CRASH_START" '$3 >= t' "$T17/last_scan.tsv" | wc -l)
awk -F'\t' -v t="$CRASH_START" '$3 >= t' "$T17/last_scan.tsv"
[ "$n" = 1 ] || finding "$n VMs of this image started since the crash launch, want 1"
dbread "select attempt_id, state, vm_ref, stop_proof_json from jobs where attempt_id='$CRASH_ATTEMPT'"
dbread "select action, reason from audit where attempt_id='$CRASH_ATTEMPT' order by id"
  • Expected: PASS; no restart stop requested, elapsed time unknown line in the log; the job holds $CRASH_VM, the same ID the crashed controller launched; one VM for the attempt and no unowned live VM; stop with proof; exactly one VM of this image started since 7.3 began; audit rows show the intent, the replay, the saved Ref and the stop.
  • Each failed check is a FINDING; the controller is stopped and every VM settled.

---

8. Orphan

8.1 Start the controller (launches off: reaping works regardless) and plant a VM

set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"; guard
if [ "${AUDIT_OK:-}" != yes ]; then finding "section 8 skipped: the 5.6 audit did not pass"; rec SKIP_8 yes; exit 0; fi
scan >/dev/null; [ -z "$LIVE" ] || die "live VMs of this image: $LIVE"
start_ctl "$T17/bin/controller" orphan
if ! (ctl_ready); then finding "the controller did not become ready; section 8 skipped"; stop_ctl; rec SKIP_8 yes; exit 0; fi
if ! metrics | grep -qE '^equipo_hosted_jobs\{state="waiting"\} 0$'; then finding "a waiting intent exists, so R22 would defer the orphan; section 8 skipped"; stop_ctl; rec SKIP_8 yes; exit 0; fi
printf 'orphan' > "$T17/out/payload-orphan"
rec ORPHAN_TOKEN "$NAME-orphan"
rec ORPHAN_PLANTED "$(date -u +%FT%TZ)"
launch orphan "$ORPHAN_TOKEN" 1800 "$T17/out/payload-orphan"
if [ "$L_OUTCOME" != created ]; then finding "the orphan launch was $L_OUTCOME (${L_CODE:-rc$L_RC} ${L_MSG}); section 8 skipped"; stop_ctl; settle_all; rec SKIP_8 yes; exit 0; fi
rec ORPHAN_VM "$L_ID"
eni_snapshot soft "8.1, orphan planted"
  • Expected: a VM ID; no job or intent names its token; its 1800 s maximum duration is the backstop.

8.2 Watch the reaper stop it

Expected timeline from the plant time P: the reaper lists every 60 s, so it first sees the VM by about P+1:30; it stops an orphan on the first pass at least 10 minutes after the first sighting, after rechecking ownership; so the stop lands between about P+11:00 and P+12:30, and the VM ends within a minute or two after that.

set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"; guard
if [ -n "${SKIP_8:-}" ]; then echo "section 8 skipped"; exit 0; fi
need ORPHAN_VM ORPHAN_PLANTED
P=$(date -d "$ORPHAN_PLANTED" +%s)
while :; do
  now=$(date +%s)
  if [ $(( now - P )) -ge 900 ]; then stop_ctl; vm_end "$ORPHAN_VM"; die "the orphan was not stopped by P+15:00 (last state ${VST:-none}): a VM alive outside its step"; fi
  ctl_alive || { finding "the controller stopped while watching the orphan"; vm_end "$ORPHAN_VM"; settle_all; exit 0; }
  vm_get "$ORPHAN_VM"
  echo "P+$(( (now - P) / 60 )):$(printf %02d $(( (now - P) % 60 ))) $VST"
  case "$VST" in
    TERMINATING|TERMINATED|NOTFOUND) break;;
    PENDING|RUNNING) ;;
    *) finding "orphan read: $VST";;
  esac
  sleep 20
done
[ $(( now - P )) -ge 600 ] || finding "the orphan was stopped before the 10-minute grace (P+$(( now - P ))s)"
jw "ORPHAN stopped by the reaper at P+$(( now - P ))s"
metrics | grep -E 'orphan' || true
metrics | grep -qE '^equipo_hosted_alerts_total\{kind="orphan_stopped",result="sent"\} 1$' || finding "no orphan_stopped alert counted as sent"
grep -F 'hosted controller: orphan VM stopped' "$T17/controller.log" | grep -F "$ORPHAN_VM" || finding "no orphan-stopped log line for $ORPHAN_VM"
if grep -F 'hosted controller: orphan VM left running for a dispatched launch intent' "$T17/controller.log" | grep -qF "$ORPHAN_VM"; then finding "the orphan was deferred (R22)"; fi
stop_ctl
vm_end "$ORPHAN_VM"
settle_all
dbread "select action, reason from audit where action like 'orphan%' order by id"
n=$(dbread "select count(*) from audit where action='orphan_stopped' and reason like '%$ORPHAN_VM%'"); [ "$n" = 1 ] || finding "$n orphan_stopped audit rows for $ORPHAN_VM"
  • Expected: RUNNING until about P+11:00 to P+12:30; then the alert metric, the controller's log line hosted controller: orphan VM stopped naming the VM (no deferral line), one orphan_seen and one orphan_stopped audit row for it; the VM ends.
  • Hard stop: no stop seen by P+15:00, whatever the reads returned (the deadline is checked first on every iteration); the block stops the controller and ends the VM first. A stop before P+10:00 and any missing evidence are FINDINGs.

---

9. Facts to record (R7)

9.A to 9.F run before section 6, with no controller running. Every VM here comes from the launch helper (livectl vm run: Small, NO_INGRESS, the qualified connector, a short maximum duration as AWS's backstop), which journals the intent first and records any VM ID returned. Each experiment ends every VM it made, confirmed, before the next one starts. A launch whose outcome is uncertain is replayed under the same client token and, failing that, settled by image-scoped scans before the next experiment (the launch helper). The expected codes are recorded as results; any other code is a FINDING and the run goes on.

9.A Client token: same request, then changed request

set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"; guard
! ctl_alive || die "the controller is running"
scan >/dev/null; [ -z "$LIVE" ] || die "live VMs of this image: $LIVE"
printf 'task17-a' > "$T17/out/payload-a"; printf 'task17-b' > "$T17/out/payload-b"
rec TOKEN_A "$NAME-token-a"
rec A1_BEFORE "$(date -u +%FT%T.%3NZ)"
launch A1 "$TOKEN_A" 600 "$T17/out/payload-a"
rec A1_AFTER "$(date -u +%FT%T.%3NZ)"
[ "$L_RC" = 0 ] || die "A1 failed (${L_CODE:-rc$L_RC}: ${L_MSG}); every VM step needs a launch (U21: a qualified egress ARN)"
rec VM_A "$L_ID"
jw "FIRST-VM-ID $VM_A (length ${#VM_A})"; echo "first real MicroVM ID: $VM_A (length ${#VM_A})"
[[ "$VM_A" =~ ^[A-Za-z0-9-]{1,128}$ ]] || finding "MicroVM ID [$VM_A] is outside R36's form; the adapter will refuse it (fails closed)"
launch A2 "$TOKEN_A" 600 "$T17/out/payload-a"
if [ "$L_OUTCOME" = settled ]; then rec A2_RESULT uncertain-settled; rec VM_A_ENDED "$(date -u +%FT%TZ)"
elif [ "$L_RC" = 0 ] && [ "$L_ID" = "$VM_A" ]; then rec A2_RESULT same-vm
elif [ "$L_RC" = 0 ]; then vm_end "$L_ID"; rec A2_RESULT "new-vm:$L_ID"; finding "a replay of the same request made a second VM ($L_ID, ended)"
else rec A2_RESULT "refused:${L_CODE:-rc$L_RC}"; finding "a replay of the same request was refused: ${L_CODE:-rc$L_RC} ${L_MSG}"; fi
launch A3 "$TOKEN_A" 600 "$T17/out/payload-b"
if [ "$L_OUTCOME" = settled ]; then rec A3_RESULT uncertain-settled; [ -n "${VM_A_ENDED:-}" ] || rec VM_A_ENDED "$(date -u +%FT%TZ)"
elif [ "$L_RC" != 0 ]; then
  rec A3_RESULT "refused:${L_CODE:-rc$L_RC}"; jw "FACT A3 message: ${L_MSG}"
  case "$L_CODE" in ConflictException|ValidationException) ;; *) finding "a changed request with a used token was refused with ${L_CODE:-rc$L_RC}";; esac
elif [ "$L_ID" = "$VM_A" ]; then rec A3_RESULT same-vm
else vm_end "$L_ID"; rec A3_RESULT "new-vm:$L_ID"; finding "a changed request with a used token made a second VM ($L_ID, ended)"; fi
echo "A2=$A2_RESULT A3=$A3_RESULT"
  • Expected: A1 launches (the first test that RunMicrovm takes a qualified egress ARN, U21; a refusal stops the run, since every VM step needs it). The first real MicroVM ID is recorded with its length; outside R36's form it is a FINDING (the adapter will refuse it). A2 returns VM_A (one attempt, one VM). A3 is refused with ConflictException or ValidationException; the exact message is recorded.
  • A3 answered with VM_A (AWS ignores the body on replay) or with a new VM (ended at once) are results; a new VM, or any code other than the two above, is also a FINDING.
  • VM_A stays up for 9.B to 9.D.

9.B startedAt, the echoes, the Date header

set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"; guard
need VM_A A1_BEFORE A1_AFTER CONN_QARN
if [ -n "${VM_A_ENDED:-}" ]; then finding "9.B skipped: VM_A has ended"; exit 0; fi
echo "run call: $A1_BEFORE to $A1_AFTER; reply: $(jq -c '{State,StartedAt}' "$T17/out/launch-A1.json")"
_running() { lvr vm get -id "$VM_A"; [ "$RC" = 0 ] || return 1
  echo "$(date -u +%T.%3N) $(jq -r '"\(.State) \(.StartedAt)"' <<<"$OUT")"; case "$(jq -r .State <<<"$OUT")" in RUNNING) return 0;; PENDING) return 1;; esac; return 2; }
if ! (poll 120 1 "VM_A to RUNNING" _running); then
  finding "VM_A did not reach RUNNING within 120 s"; vm_end "$VM_A"; rec VM_A_ENDED "$(date -u +%FT%TZ)"; exit 0
fi
lvr vm get -id "$VM_A"
if [ "$RC" = 0 ]; then
  printf '%s\n' "$OUT" > "$T17/out/9.B-get.json"
  eni_snapshot soft "9.B, VM_A running"
  jw "FACT VM_A echoes: $(jq -c '{IngressNetworkConnectors,EgressNetworkConnectors,MaximumDurationInSeconds,ExecutionRoleArn,IdlePolicy,StartedAt}' "$T17/out/9.B-get.json")"
  [ "$(jq -c .IngressNetworkConnectors "$T17/out/9.B-get.json")" = "[\"$NO_INGRESS\"]" ] || finding "ingress echo is $(jq -c .IngressNetworkConnectors "$T17/out/9.B-get.json")"
  [ "$(jq -c .EgressNetworkConnectors "$T17/out/9.B-get.json")" = "[\"$CONN_QARN\"]" ] || finding "egress echo is $(jq -c .EgressNetworkConnectors "$T17/out/9.B-get.json")"
  sv=$(jq -r '.ResultMetadata.ServerTime // empty' "$T17/out/9.B-get.json")
  if [ -n "$sv" ]; then rec DATE_HEADER_get present; jw "FACT GetMicrovm Date header: $sv"; else rec DATE_HEADER_get absent; finding "GetMicrovm reply has no Date header (provider age unknown)"; fi
else finding "VM_A read failed: ${ECODE:-rc$RC}"; fi
rec DATE_HEADER_list "not measured: livectl prints no metadata for lists"
  • Expected: StartedAt is in the PENDING reply; record how it relates to the call window and to the first RUNNING read. The ingress, egress, maximum duration, execution role and idle policy echoes are recorded as facts (Paul, 2026-11-28); an ingress or egress echo other than what was sent is a FINDING. The Date header is livectl's ResultMetadata.ServerTime for GetMicrovm; livectl prints no metadata for lists, so the List header is recorded as not measured.

9.C Resume on RUNNING; suspend on SUSPENDED; a second resume

set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"; guard
need VM_A
if [ -n "${VM_A_ENDED:-}" ]; then finding "9.C skipped: VM_A has ended"; exit 0; fi
r() { lv vm "$1" -id "$VM_A"; echo "$1: rc=$RC code=${ECODE:-none} ${LV_MSG}"; }
res() { if [ "$RC" = 0 ]; then echo accepted; elif [ "$ECODE" = ConflictException ]; then echo ConflictException; else echo "other:${ECODE:-rc$RC}"; fi; }
r resume; rec RESUME_ON_RUNNING "$(res)"
case "$RESUME_ON_RUNNING" in other:*) finding "resume on RUNNING: $RESUME_ON_RUNNING ${LV_MSG}";; esac
rec SUSPEND_AT "$(date -u +%FT%T.%3NZ)"; r suspend
if [ "$RC" = 0 ] && (vm_wait "$VM_A" SUSPENDED 180 RUNNING SUSPENDING); then
  r suspend; rec SUSPEND_ON_SUSPENDED "$(res)"
  case "$SUSPEND_ON_SUSPENDED" in other:*) finding "suspend on SUSPENDED: $SUSPEND_ON_SUSPENDED";; esac
  rec RESUME_AT "$(date -u +%FT%T.%3NZ)"; r resume
  [ "$RC" = 0 ] || finding "resume of a SUSPENDED VM: ${ECODE:-rc$RC} ${LV_MSG}"
  vm_get "$VM_A"; before=$VST
  r resume
  case "$before" in SUSPENDED) when=during-first-resume;; RUNNING) when=after-first-resume;; *) when="unknown:$before";; esac
  rec SECOND_RESUME "$(res):$when"
  case "$SECOND_RESUME" in other:*) finding "second resume: $SECOND_RESUME";; esac
else finding "suspend of VM_A failed or it did not reach SUSPENDED (rc $RC ${ECODE:-})"; fi
if ! (vm_wait "$VM_A" RUNNING 180 SUSPENDED SUSPENDING); then
  finding "VM_A is not RUNNING after 9.C; ending it"; vm_end "$VM_A"; rec VM_A_ENDED "$(date -u +%FT%TZ)"
fi
echo "resume-on-running=$RESUME_ON_RUNNING suspend-on-suspended=${SUSPEND_ON_SUSPENDED:-not run} second-resume=${SECOND_RESUME:-not run}"
  • Expected: resume on RUNNING is a ConflictException (R4; if accepted, the adapter's mapping is untested and 6.1's ResumeRunningIsNoop result decides). Suspend reaches SUSPENDED in about 2 to 4 s. The second resume's label says which state the VM was in just before it, measured by a Get; with a 200-returning hook the first resume may already be done, so "after-first-resume" is the likely label and the in-progress case may stay unmeasured.

9.D Payload limit (ASCII)

set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"; guard
probe() { local n=$1
  head -c "$n" /dev/zero | tr '\0' x > "$T17/out/payload-$n"; [ "$(wc -c < "$T17/out/payload-$n")" = "$n" ] || die "payload file size"
  launch "P$n" "$NAME-p$n" 120 "$T17/out/payload-$n"
  if [ "$L_OUTCOME" = settled ]; then rec "PAYLOAD_$n" uncertain-settled
  elif [ "$L_RC" = 0 ]; then vm_end "$L_ID"; rec "PAYLOAD_$n" accepted
  elif [ "$L_CODE" = ValidationException ]; then rec "PAYLOAD_$n" "refused:ValidationException"; jw "FACT payload $n message: ${L_MSG}"
  else rec "PAYLOAD_$n" "refused:${L_CODE:-rc$L_RC}"; finding "payload $n refused with ${L_CODE:-rc$L_RC}: ${L_MSG}"; fi; }
probe 4096; probe 4097
if [ "$PAYLOAD_4097" = accepted ]; then probe 16384; probe 16385; fi
echo "4096=$PAYLOAD_4096 4097=$PAYLOAD_4097 16384=${PAYLOAD_16384:-not run} 16385=${PAYLOAD_16385:-not run}"
  • Expected: 4096 accepted (ended at once); 4097 refused with a ValidationException. If 4097 is accepted, 16384 and 16385 are probed (the guide says 16 KB). These are ASCII payloads: they establish an ASCII boundary only, not whether AWS counts bytes or characters in general.

9.E End VM_A, then replay its token

set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"; guard
need VM_A TOKEN_A
vm_end "$VM_A"; [ -n "${VM_A_ENDED:-}" ] || rec VM_A_ENDED "$(date -u +%FT%TZ)"
lvr vm terminate -id "$VM_A"
if [ "$RC" = 0 ]; then rec TERMINATE_AGAIN ok; elif [ "$ECODE" = ResourceNotFoundException ]; then rec TERMINATE_AGAIN ResourceNotFoundException
else rec TERMINATE_AGAIN "other:${ECODE:-rc$RC}"; finding "terminate of an ended VM: ${ECODE:-rc$RC} ${LV_MSG}"; fi
launch E1 "$TOKEN_A" 600 "$T17/out/payload-a"
if [ "$L_OUTCOME" = settled ]; then rec E1_RESULT uncertain-settled
elif [ "$L_RC" = 0 ] && [ "$L_ID" = "$VM_A" ]; then rec E1_RESULT same-ended-vm
elif [ "$L_RC" = 0 ]; then vm_end "$L_ID"; rec E1_RESULT "new-vm:$L_ID"
else rec E1_RESULT "refused:${L_CODE:-rc$L_RC}"
  case "$L_CODE" in ConflictException|ValidationException|ResourceNotFoundException) jw "FACT E1 message: ${L_MSG}";; *) finding "E1 replay refused with ${L_CODE:-rc$L_RC}: ${L_MSG}";; esac; fi
settle_all
echo "E1=$E1_RESULT"
  • Expected: both terminates succeed (documented idempotent). The replay of the original token and request after the VM ended returns the ended VM, a new VM (ended at once), or one of the listed errors; recorded. Then every facts VM is settled.

9.F TERMINATED visibility (run at the end of 9.E, after 6.1, 7.4, 8.2 and before 10.1)

set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"; guard
need VM_A VM_A_ENDED IMAGE_ARN
vm_get "$VM_A"; jw "VISIBILITY VM_A $VST since $VM_A_ENDED"; echo "$(date -u +%T) VM_A get: $VST (ended $VM_A_ENDED)"
scan >/dev/null; echo "image list: $(wc -l < "$T17/last_scan.tsv") VMs, $(grep -c "^$VM_A	" "$T17/last_scan.tsv" || true) of them VM_A"
  • Expected: at each checkpoint, record whether Get still answers TERMINATED or not found, and whether List still shows VM_A. The last sighting and the first miss bound the visibility window.

9.G Final token replay (after section 8)

set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"; guard
need TOKEN_A VM_A A1_BEFORE
! ctl_alive || die "the controller is running"
launch G1 "$TOKEN_A" 600 "$T17/out/payload-a"
if [ "$L_OUTCOME" = settled ]; then rec G1_RESULT uncertain-settled
elif [ "$L_RC" = 0 ] && [ "$L_ID" = "$VM_A" ]; then rec G1_RESULT same-ended-vm
elif [ "$L_RC" = 0 ]; then vm_end "$L_ID"; rec G1_RESULT "new-vm:$L_ID"
else rec G1_RESULT "refused:${L_CODE:-rc$L_RC}"
  case "$L_CODE" in ConflictException|ValidationException|ResourceNotFoundException) jw "FACT G1 message: ${L_MSG}";; *) finding "G1 replay refused with ${L_CODE:-rc$L_RC}: ${L_MSG}";; esac; fi
settle_all
echo "G1=$G1_RESULT, $(( ( $(date +%s) - $(date -d "$A1_BEFORE" +%s) ) / 60 )) minutes after the token's first use"
  • Expected: a result 3 to 4 hours after first use; same-ended-vm means the token window is at least that long. Then run 9.F once more.

R7 record (one line each in the progress file): A2, A3 (with message), E1, G1 (with minutes); the Date header on Get (and List: not measured); startedAt in PENDING and its relation to the call and to RUNNING; resume on RUNNING; suspend on SUSPENDED; second resume with its label; payload results (ASCII); the NO_INGRESS literal as echoed; TERMINATED visibility bounds; contract visibility and List lag.

---

10. Teardown and verification

Runs after 9.G, or on Paul's word after a safe stop. Dependency order. Each deletion is confirmed by a direct read before the next dependency is touched, and recorded with deleted.

10.1 No controller, no VM, then the image (all its versions)

set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"; guard
stop_ctl
if have IMAGE_ARN; then
settle_all
lvr image delete -id "$IMAGE_ARN"
[ "$RC" = 0 ] || die "image delete: ${ECODE:-rc$RC} ${LV_MSG:-$ERR} (a ConflictException is a stop: U8)"
_img() { lvr image list -name "$IMAGE_NAME"; [ "$RC" = 0 ] || return 1
  list_items || die "malformed image list reply while proving the image deleted"
  OUT=$(jq -r --arg a "$IMAGE_ARN" '[.[] | select(.ImageArn == $a) | .State] | join(" ")' <<<"$ITEMS") || die "image list items unreadable"
  echo "$(date -u +%T) listed state: [${OUT}]"; case "$OUT" in ""|DELETED) return 0;; DELETING) return 1;; esac; return 2; }
poll 900 15 "image deleted" _img
deleted microvm-image "$IMAGE_ARN"
for vv in VER_SMALL_FAILED VER_SMALL VER_LARGE; do
  [ -n "${!vv:-}" ] || continue; v=${!vv}
  lvr image get-version -id "$IMAGE_ARN" -version "$v"
  if { [ "$RC" = 0 ] && [ "$(jq -r .State <<<"$OUT")" = DELETED ]; } || { [ "$RC" != 0 ] && [ "$ECODE" = ResourceNotFoundException ]; }; then
    deleted microvm-image-version "$IMAGE_ARN:$v"
  else finding "version $v after the image delete: rc $RC ${ECODE:-} $(jq -r '.State // empty' <<<"$OUT" 2>/dev/null || true)"; fi
done
fi

10.2 Connector, then its network interfaces

set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"; guard
if have CONN_ARN; then
need VPC SUBNET OPERATOR_ROLE
eni_snapshot strict "10.2, before the connector delete"
B_END=$(( $(date +%s) + 7200 ))
# budget N: N seconds, or what is left of 10.2's shared 120-minute budget if that is less.
budget() { local r=$(( B_END - $(date +%s) )); [ "$r" -gt 0 ] || die "10.2's shared 120-minute budget is spent: hard stop"; echo $(( r < $1 ? r : $1 )); }
conn_delete() { lvr connector delete -id "$CONN_ARN"
  [ "$RC" = 0 ] || [ "$ECODE" = ResourceNotFoundException ] || die "connector delete: ${ECODE:-rc$RC} ${LV_MSG:-$ERR}"; }
conn_gone() { local b; b=$(budget 2400) || die "10.2's shared budget is spent: hard stop"; lv_wait "$b" connector wait-gone -id "$CONN_ARN" -interval 15s; CG_RC=$RC; CG_CODE=$ECODE
  echo "wait-gone: rc $CG_RC ${CG_CODE:-} $(jq -c '{State,StateReason}' <<<"$OUT" 2>/dev/null || true)"; }
# enis_gone SECONDS: 0 when no interface is left in the VPC within SECONDS; 1 when some are left at the bound.
enis_gone() { local end=$(( $(date +%s) + $1 ))
  while :; do
    try aws ec2 describe-network-interfaces --filters Name=vpc-id,Values="$VPC" --query 'length(NetworkInterfaces)' --output json
    [ "$RC" = 0 ] || die "interface count unreadable: ${ECODE:-rc$RC}"
    echo "$(date -u +%T) interfaces in VPC: $OUT"; [ "$OUT" = 0 ] && return 0
    [ "$(date +%s)" -lt "$end" ] || return 1
    sleep 30
  done; }
conn_delete; conn_gone; ok=no
if [ "$CG_RC" = 0 ]; then deleted connector "$CONN_ARN"; eb=$(budget 2400) || die "10.2's shared budget is spent: hard stop"; enis_gone "$eb" && ok=yes
elif [ "$CG_RC" = 6 ] && [ "$CG_CODE" = DELETE_FAILED ]; then :
else die "connector wait-gone: rc $CG_RC ${CG_CODE:-}"; fi
if [ "$ok" = no ]; then
  finding "connector teardown needs the pre-approved fallback (wait-gone rc $CG_RC ${CG_CODE:-}, or interfaces left after 40 min)"
  have OPERATOR_ROLE_ARN || die "no operator role to change"
  A=arn:aws:ec2:eu-west-1:640012953448
  cat > "$T17/iam/operator-delete-subnet.json" <<TEOF
{"Version":"2012-10-17","Statement":[
 {"Sid":"DeleteEniInThisSubnet","Effect":"Allow","Action":"ec2:DeleteNetworkInterface","Resource":"$A:network-interface/*",
  "Condition":{"ArnEquals":{"ec2:Subnet":"$A:subnet/$SUBNET"}}}]}
TEOF
  jq -e . "$T17/iam/operator-delete-subnet.json" >/dev/null
  aws iam put-role-policy --role-name "$OPERATOR_ROLE" --policy-name t17-connector-eni-delete --policy-document "file://$T17/iam/operator-delete-subnet.json"
  rec OPERATOR_DELETE_FALLBACK "subnet condition only (Paul, 2026-11-28)"
  echo "waiting 120 s for IAM propagation, then one more connector delete"; sleep 120
  conn_delete; conn_gone
  [ "$CG_RC" = 0 ] || die "the connector delete failed again after the fallback (rc $CG_RC ${CG_CODE:-}): hard stop"
  grep -q $'\tDELETED connector '"$CONN_ARN"'$' "$JOURNAL" || deleted connector "$CONN_ARN"
  eb=$(budget 2400) || die "10.2's shared budget is spent: hard stop"; enis_gone "$eb" || die "interfaces are still in the VPC after the fallback: hard stop"
fi
for e in $(awk -F'\t' '$2 ~ /^SERVICE-ENI / {split($2, a, " "); print a[2]}' "$JOURNAL"); do
  gone0 "interface $e" aws ec2 describe-network-interfaces --filters Name=network-interface-id,Values="$e" --query 'length(NetworkInterfaces)' --output json
  deleted service-eni "$e"
done
fi
  • Pre-approved fallback (Paul, 2026-11-28): on DELETE_FAILED, or interfaces left after 40 minutes, the inline delete policy loses its ec2:ManagedResourceOperator condition (the subnet condition stays), and after 120 s the connector delete is retried once. A second failure, or interfaces still left, is a hard stop. Lambda's interfaces are never deleted by hand.
  • One shared budget of 120 minutes covers the attempt and its fallback: each wait takes at most its own 40-minute bound and never more than what is left of the 120 minutes; when it is spent, that is a hard stop. The detached-block limit for 10.2 alone is 130 minutes, so the wrapper never cuts the pre-approved fallback short.

10.3 Network

set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"; guard
if have SG; then
  get _v aws ec2 delete-security-group --group-id "$SG" --query Return --output text; [ "$_v" = True ] || die "delete group"
  gone0 "group $SG" aws ec2 describe-security-groups --filters Name=group-id,Values="$SG" --query 'length(SecurityGroups)' --output json; deleted security-group "$SG"
fi
if have RTB_ASSOC; then aws ec2 disassociate-route-table --association-id "$RTB_ASSOC"; deleted route-table-association "$RTB_ASSOC"; fi
if have RTB; then
  aws ec2 delete-route-table --route-table-id "$RTB"
  gone0 "route table $RTB" aws ec2 describe-route-tables --filters Name=route-table-id,Values="$RTB" --query 'length(RouteTables)' --output json; deleted route-table "$RTB"
fi
if have SUBNET; then
  aws ec2 delete-subnet --subnet-id "$SUBNET"
  gone0 "subnet $SUBNET" aws ec2 describe-subnets --filters Name=subnet-id,Values="$SUBNET" --query 'length(Subnets)' --output json; deleted subnet "$SUBNET"
fi
if have VPC; then
  aws ec2 delete-vpc --vpc-id "$VPC"
  gone0 "VPC $VPC" aws ec2 describe-vpcs --filters Name=vpc-id,Values="$VPC" --query 'length(Vpcs)' --output json; deleted vpc "$VPC"
  if have DEF_SG_RULES; then gone0 "default group rules $DEF_SG_RULES" aws ec2 describe-security-group-rules --filters Name=security-group-rule-id,Values="$(tr '\t ' ',,' <<<"$DEF_SG_RULES")" --query 'length(SecurityGroupRules)' --output json; deleted vpc-default-security-group-rules "$DEF_SG_RULES"; fi
  if have DEF_SG; then gone0 "default group $DEF_SG" aws ec2 describe-security-groups --filters Name=group-id,Values="$DEF_SG" --query 'length(SecurityGroups)' --output json; deleted vpc-default-security-group "$DEF_SG"; fi
  if have MAIN_RTB; then gone0 "main route table $MAIN_RTB" aws ec2 describe-route-tables --filters Name=route-table-id,Values="$MAIN_RTB" --query 'length(RouteTables)' --output json; deleted vpc-main-route-table "$MAIN_RTB"; fi
  if have DEF_ACL; then gone0 "default network ACL $DEF_ACL" aws ec2 describe-network-acls --filters Name=network-acl-id,Values="$DEF_ACL" --query 'length(NetworkAcls)' --output json; deleted vpc-default-network-acl "$DEF_ACL"; fi
fi
  • Abort if: a DependencyViolation, a failed read, or a filtered describe that still lists the resource.

10.4 IAM roles

The operator role holds the managed attachment and the inline delete policy (2.1; 10.2's fallback rewrites the same policy name). The old narrow policy name is still tried, so a role left by an earlier revision is cleaned too. Each is removed if present; NoSuchEntity means it was never added.

set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"; guard
need OPERATOR_ROLE BUILD_ROLE
if have OPERATOR_ROLE_ARN; then
  for pn in t17-connector-eni t17-connector-eni-delete; do
    try aws iam delete-role-policy --role-name "$OPERATOR_ROLE" --policy-name "$pn"; [ "$RC" = 0 ] || expect_err NoSuchEntity
  done
  try aws iam detach-role-policy --role-name "$OPERATOR_ROLE" --policy-arn arn:aws:iam::aws:policy/AWSLambdaNetworkConnectorOperatorPolicy; [ "$RC" = 0 ] || expect_err NoSuchEntity
  aws iam delete-role --role-name "$OPERATOR_ROLE"
  try aws iam get-role --role-name "$OPERATOR_ROLE"; expect_err NoSuchEntity; deleted iam-role "$OPERATOR_ROLE_ARN"
  if [ -n "${OPERATOR_INLINE_POLICY:-}" ]; then deleted iam-inline-policy "$OPERATOR_INLINE_POLICY"; fi
  if [ -n "${OPERATOR_MANAGED_POLICY:-}" ]; then deleted iam-managed-attachment "$OPERATOR_MANAGED_POLICY"; fi
fi
if have BUILD_ROLE_ARN; then
  try aws iam delete-role-policy --role-name "$BUILD_ROLE" --policy-name t17-build; [ "$RC" = 0 ] || expect_err NoSuchEntity
  aws iam delete-role --role-name "$BUILD_ROLE"
  try aws iam get-role --role-name "$BUILD_ROLE"; expect_err NoSuchEntity; deleted iam-role "$BUILD_ROLE_ARN"
fi

10.5 S3

set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"; guard
need BUCKET
if have BUCKET_CREATED; then
if have ARTIFACT; then
aws s3api delete-object --bucket "$BUCKET" --key t17/app.zip
gone0 "object t17/app.zip" aws s3api list-objects-v2 --bucket "$BUCKET" --prefix t17/app.zip --query 'length((Contents || `[]`)[?Key==`t17/app.zip`])' --output json; deleted s3-object "s3://$BUCKET/t17/app.zip"
fi
get _v aws s3api list-object-versions --bucket "$BUCKET" --output json
[ "$(jq '((.Versions // []) + (.DeleteMarkers // [])) | length' <<<"$_v")" = 0 ] || die "objects left in the bucket"
aws s3api delete-bucket --bucket "$BUCKET"
_bucket() { try aws s3api list-buckets --prefix "$BUCKET" --query "length(Buckets[?Name=='$BUCKET'])" --output json; [ "$RC" = 0 ] || return 3; echo "$(date -u +%T) listed: $OUT"; [ "$OUT" = 0 ] && return 0; return 1; }
poll 300 10 "bucket gone from the list" _bucket; deleted s3-bucket "$BUCKET"
fi

10.6 Log group

set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"; guard
need LOG_GROUP
if have LOG_GROUP_CREATED; then
get got aws logs describe-log-groups --log-group-name-prefix "$LOG_GROUP" --query 'logGroups[].logGroupName' --output text
[ "$got" = "$LOG_GROUP" ] || die "log groups under the prefix: [$got]; any group the run did not create goes to Paul"
aws logs delete-log-group --log-group-name "$LOG_GROUP"
get got aws logs describe-log-groups --log-group-name-prefix "$LOG_GROUP" --query 'logGroups[].logGroupName' --output text
[ -z "$got" ] || die "log group still listed: [$got]"
deleted log-group "$LOG_GROUP"
fi

10.7 SNS topic

set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"; guard
if have TOPIC_ARN; then
aws sns delete-topic --topic-arn "$TOPIC_ARN"
_topic() { try aws sns list-topics --query "length(Topics[?TopicArn=='$TOPIC_ARN'])" --output json; [ "$RC" = 0 ] || return 3; echo "$(date -u +%T) listed: $OUT"; [ "$OUT" = 0 ] && return 0; return 1; }
poll 300 10 "topic gone from the list" _topic; deleted sns-topic "$TOPIC_ARN"
fi

10.8 Verify: every record classified, then the tag index as a cross-check

set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"; guard
need RUN
echo "== confirmed creations without a confirmed deletion:"
awk -F'\t' '
  $2 ~ /^DELETED / {split($2, a, " "); d[substr($2, length("DELETED " a[2] " ") + 1)] = 1}
  $2 ~ /^CONFIRMED / {split($2, a, " "); c[substr($2, length("CONFIRMED " a[2] " ") + 1)] = a[2]}
  END {for (k in c) if (!(k in d)) print c[k], k}' "$JOURNAL" | sort
echo "== VMs: recorded, and how each ended:"
vm_ids
for id in $VIDS; do grep -q "VMGONE $id " "$JOURNAL" || die "VM $id has no confirmed end"; done
echo "$(wc -w <<<"$VIDS") VMs recorded, every one confirmed ended"
echo "== intents without a confirmation:"
awk -F'\t' '$2 ~ /^INTENT /' "$JOURNAL"
echo "== tag index (lags; direct reads above decide):"
for k in run purpose; do v=$([ "$k" = run ] && echo "$RUN" || echo "$TAGV")
  aws resourcegroupstaggingapi get-resources --tag-filters Key=$k,Values=$v --query 'ResourceTagMappingList[].ResourceARN' --output text | tr '\t' '\n'; done
  • Expected: the first list holds only values that are not resources (the run's settings: DIGEST, VER_*, CONN_VERSION, CONN_QARN, BASE_*, tokens, times, results); every resource ID has a DELETED line. Every recorded VM has a confirmed end. Each intent has its confirmation (or, for vm intents, a VM ID or a recorded refusal). The tag index lists nothing with run=<RUN>, or only ARNs already confirmed deleted above ("index lag"); with purpose, only what 0.4 already observed. An ARN that is neither goes to Paul untouched.

10.9 Evidence into the progress file, then remove scratch

set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"
! ctl_alive || die "the controller is running"; listeners; [ -z "$LST" ] || die "listeners open: $LST"
no_unresolved
cut -f2- "$JOURNAL" | grep -vE '^(INTENT|CONTROLLER) ' > "$T17/journal-for-progress.txt"
wc -l "$T17/journal-for-progress.txt" "$VMS"
echo "== every FINDING (the report lists each one):"
awk -F'\t' '$2 ~ /^FINDING / {print $1, substr($2, 9)}' "$JOURNAL" | tee "$T17/findings.txt"

Paste journal-for-progress.txt, vms.tsv, the R7 lines and section 11.2's estimate into HOSTED-SLICE1-PROGRESS.md (they hold IDs, times and results only, no keys), then:

set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"; no_unresolved; rm -rf "$TMPDIR/equipo-t17" "$TMPDIR/equipo-t17-pre"; [ ! -e "$TMPDIR/equipo-t17" ] && echo "scratch removed"

---

S. Safe stop

Run in this order after any abort. Each part is safe to run whatever phase the run reached.

S.1 Controller.

set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"
stop_ctl

If stop_ctl aborts because the PID belongs to another process, or a port stays open while /proc hides the process, stop here and ask Paul: nothing is signalled that is not proven to be this run's controller.

S.2 Reconcile uncertain creations (R39). For each creation whose INTENT has no CONFIRMED record, one direct, guarded read decides. A resource created with a run-unique name (the run ID, proved absent by 0.4) and found by that exact name is ours: it is recorded, tagged if a separate tagging call never ran, and torn down. The unnamed EC2 resources carried their tags in the create call (TagSpecifications) and are found by a direct describe filtered on the run tag and their Name tag, never through the tag index. Each read has exactly three outcomes: success (record), an empty list or an approved not-found code (NOTCREATED), or anything else (UNRESOLVED: that resource's reconciliation stops and it goes to Paul with its cost in S.4). The MicroVM intents are reconciled by S.3.

set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"; guard
need RUN NAME SG_NAME OPERATOR_ROLE BUILD_ROLE CONN_NAME IMAGE_NAME BUCKET LOG_GROUP TOPIC_NAME TAGS_EC2
UNRES=""
unresolved() { jw "UNRESOLVED $*"; UNRES="$UNRES|$*"; echo "UNRESOLVED: $*"; }
absent() { jw "NOTCREATED $*"; echo "not created: $*"; }
pending() { awk -F'\t' -v k="INTENT $1 $2" 'index($2, k) == 1 {f = 1} END {exit !f}' "$JOURNAL" && [ -z "${!3:-}" ]; }
# one_ec2 KIND VAR CMD...: a describe that must list 0 or 1 IDs.
one_ec2() { local kind=$1 var=$2; shift 2; try "$@"
  if [ "$RC" != 0 ]; then unresolved "$kind lookup failed: ${ECODE:-rc$RC}"; return; fi
  case "$(wc -w <<<"$OUT")" in 0) absent "$kind";; 1) rec "$var" "$OUT";; *) unresolved "$kind: several match: $OUT";; esac; }
# one_def KIND VAR CMD...: a VPC default resource; it exists whenever the VPC does, so only exactly one is an answer.
one_def() { local kind=$1 var=$2; shift 2; try "$@"
  if [ "$RC" = 0 ] && [ "$(wc -w <<<"$OUT")" = 1 ]; then rec "$var" "$OUT"; else unresolved "$kind: rc $RC ${ECODE:-} [$OUT]"; fi; }

if pending vpc "tag:run=$RUN" VPC; then one_ec2 vpc VPC aws ec2 describe-vpcs --filters Name=tag:run,Values="$RUN" Name=tag:Name,Values="$NAME" --query 'Vpcs[].VpcId' --output text; fi
if [ -n "${VPC:-}" ] && [ -z "${DEF_SG_RULES:-}" ]; then
  [ -n "${DEF_SG:-}" ] || one_def vpc-default-security-group DEF_SG aws ec2 describe-security-groups --filters Name=vpc-id,Values="$VPC" Name=group-name,Values=default --query 'SecurityGroups[].GroupId' --output text
  [ -n "${MAIN_RTB:-}" ] || one_def vpc-main-route-table MAIN_RTB aws ec2 describe-route-tables --filters Name=vpc-id,Values="$VPC" Name=association.main,Values=true --query 'RouteTables[].RouteTableId' --output text
  [ -n "${DEF_ACL:-}" ] || one_def vpc-default-network-acl DEF_ACL aws ec2 describe-network-acls --filters Name=vpc-id,Values="$VPC" Name=default,Values=true --query 'NetworkAcls[].NetworkAclId' --output text
  if [ -n "${DEF_SG:-}" ] && [ -n "${MAIN_RTB:-}" ] && [ -n "${DEF_ACL:-}" ]; then
    try aws ec2 describe-security-group-rules --filters Name=group-id,Values="$DEF_SG" --query 'SecurityGroupRules[].SecurityGroupRuleId' --output text
    if [ "$RC" = 0 ] && [ -n "$OUT" ]; then rec DEF_SG_RULES "$OUT"
      try aws ec2 create-tags --resources "$DEF_SG" "$MAIN_RTB" "$DEF_ACL" $DEF_SG_RULES --tags $TAGS_EC2
      [ "$RC" = 0 ] || unresolved "vpc defaults: tagging failed: ${ECODE:-rc$RC}"
    else unresolved "vpc default security group rules: ${ECODE:-rc$RC}"; fi
  fi
fi
if pending subnet "tag:run=$RUN" SUBNET; then one_ec2 subnet SUBNET aws ec2 describe-subnets --filters Name=tag:run,Values="$RUN" Name=tag:Name,Values="$NAME-vm" --query 'Subnets[].SubnetId' --output text; fi
if pending route-table "tag:run=$RUN" RTB; then one_ec2 route-table RTB aws ec2 describe-route-tables --filters Name=tag:run,Values="$RUN" Name=tag:Name,Values="$NAME-vm" --query 'RouteTables[].RouteTableId' --output text; fi
if pending route-table-association "" RTB_ASSOC && [ -n "${RTB:-}" ] && [ -n "${SUBNET:-}" ]; then
  one_ec2 route-table-association RTB_ASSOC aws ec2 describe-route-tables --route-table-ids "$RTB" --query "RouteTables[0].Associations[?SubnetId=='$SUBNET'].RouteTableAssociationId" --output text; fi
if pending security-group "$SG_NAME" SG; then one_ec2 security-group SG aws ec2 describe-security-groups --filters Name=tag:run,Values="$RUN" Name=group-name,Values="$SG_NAME" --query 'SecurityGroups[].GroupId' --output text; fi
for pair in "$OPERATOR_ROLE:OPERATOR_ROLE_ARN" "$BUILD_ROLE:BUILD_ROLE_ARN"; do
  r=${pair%%:*}; v=${pair#*:}
  pending iam-role "$r" "$v" || continue
  try aws iam get-role --role-name "$r" --output json
  if [ "$RC" = 0 ]; then arn=$(jq -r .Role.Arn <<<"$OUT"); arn_ok "$arn"; rec "$v" "$arn"
    if ! jq -e --arg r "$RUN" 'any(.Role.Tags[]?; .Key == "run" and .Value == $r)' <<<"$OUT" >/dev/null; then
      try aws iam tag-role --role-name "$r" --tags Key=purpose,Value=$TAGV Key=run,Value=$RUN; [ "$RC" = 0 ] || unresolved "iam-role $r: tagging failed: ${ECODE:-rc$RC}"; fi
  elif code_in NoSuchEntity; then absent "iam-role $r"
  else unresolved "iam-role $r: ${ECODE:-rc$RC}"; fi
done
if pending connector "$CONN_NAME" CONN_ARN; then
  lvr connector get -id "$CONN_NAME"
  if [ "$RC" = 0 ] && [ "$(jq -r .Name <<<"$OUT")" = "$CONN_NAME" ]; then arn=$(jq -r .Arn <<<"$OUT"); arn_ok "$arn"; rec CONN_ARN "$arn"; rec CONN_ID "$(jq -r .Id <<<"$OUT")"
  elif code_in ResourceNotFoundException; then absent "connector $CONN_NAME"
  else unresolved "connector $CONN_NAME: ${ECODE:-rc$RC}"; fi
fi
if pending s3-bucket "$BUCKET" BUCKET_CREATED; then
  try aws s3api list-buckets --prefix "$BUCKET" --query "length(Buckets[?Name=='$BUCKET'])" --output json
  if [ "$RC" != 0 ]; then unresolved "s3-bucket $BUCKET: list failed: ${ECODE:-rc$RC}"
  elif [ "$OUT" = 1 ]; then rec BUCKET_CREATED "$BUCKET"
    try aws s3api get-bucket-tagging --bucket "$BUCKET" --query "TagSet[?Key=='run'].Value" --output text
    if [ "$RC" = 0 ] && [ "$OUT" = "$RUN" ]; then :
    elif [ "$RC" = 0 ] || code_in NoSuchTagSet; then
      try aws s3api put-public-access-block --bucket "$BUCKET" --public-access-block-configuration BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true
      [ "$RC" = 0 ] || unresolved "s3-bucket $BUCKET: public access block failed: ${ECODE:-rc$RC}"
      try aws s3api put-bucket-tagging --bucket "$BUCKET" --tagging "TagSet=[{Key=purpose,Value=$TAGV},{Key=run,Value=$RUN}]"
      [ "$RC" = 0 ] || unresolved "s3-bucket $BUCKET: tagging failed: ${ECODE:-rc$RC}"
    else unresolved "s3-bucket $BUCKET: tags unreadable: ${ECODE:-rc$RC}"; fi
  elif [ "$OUT" = 0 ]; then absent "s3-bucket $BUCKET"
  else unresolved "s3-bucket $BUCKET: listed $OUT times"; fi
fi
if pending log-group "$LOG_GROUP" LOG_GROUP_CREATED; then
  try aws logs describe-log-groups --log-group-name-prefix "$LOG_GROUP" --query 'logGroups[].logGroupName' --output text
  if [ "$RC" != 0 ]; then unresolved "log-group: ${ECODE:-rc$RC}"
  elif [ "$OUT" = "$LOG_GROUP" ]; then rec LOG_GROUP_CREATED "$LOG_GROUP"
  elif [ -z "$OUT" ]; then absent "log-group $LOG_GROUP"
  else unresolved "log-group: unexpected groups [$OUT]"; fi
fi
if pending s3-object "s3://$BUCKET/t17/app.zip" ARTIFACT; then
  need ARTIFACT_B64
  if [ -z "${BUCKET_CREATED:-}" ]; then absent "s3-object (no bucket)"; OBJ=absent; RC=0; OUT=""
  else try aws s3api list-objects-v2 --bucket "$BUCKET" --prefix t17/app.zip --query 'length((Contents || `[]`)[?Key==`t17/app.zip`])' --output json
  if [ "$RC" != 0 ]; then unresolved "s3-object: list failed: ${ECODE:-rc$RC}"; OBJ=unknown
  elif [ "$OUT" = 0 ]; then absent "s3-object"; OBJ=absent
  else OBJ=listed; try aws s3api head-object --bucket "$BUCKET" --key t17/app.zip --checksum-mode ENABLED --query ChecksumSHA256 --output text; fi
  fi
  if [ "$OBJ" != listed ]; then :
  elif [ "$RC" = 0 ] && [ "$OUT" = "$ARTIFACT_B64" ]; then rec ARTIFACT "s3://$BUCKET/t17/app.zip"
    try aws s3api get-object-tagging --bucket "$BUCKET" --key t17/app.zip --query "TagSet[?Key=='run'].Value" --output text
    if [ "$RC" = 0 ] && [ "$OUT" != "$RUN" ]; then
      try aws s3api put-object-tagging --bucket "$BUCKET" --key t17/app.zip --tagging "TagSet=[{Key=purpose,Value=$TAGV},{Key=run,Value=$RUN}]"
      [ "$RC" = 0 ] || unresolved "s3-object: tagging failed: ${ECODE:-rc$RC}"
    elif [ "$RC" != 0 ]; then unresolved "s3-object: tags unreadable: ${ECODE:-rc$RC}"; fi
  elif [ "$RC" = 0 ]; then unresolved "s3-object: checksum $OUT is not $ARTIFACT_B64"
  else unresolved "s3-object: head failed: ${ECODE:-rc$RC}"; fi
fi
if pending microvm-image "$IMAGE_NAME" IMAGE_ARN; then
  lvr image list -name "$IMAGE_NAME"
  if [ "$RC" = 0 ]; then
    list_items || die "malformed image list reply in reconciliation"
    OUT=$(jq -r --arg n "$IMAGE_NAME" '[.[] | select(.Name == $n) | .ImageArn] | join(" ")' <<<"$ITEMS") || die "image list items unreadable"
  fi
  if [ "$RC" != 0 ]; then unresolved "microvm-image $IMAGE_NAME: list failed: ${ECODE:-rc$RC}"
  elif [ -z "$OUT" ]; then absent "microvm-image $IMAGE_NAME"
  elif [ "$(wc -w <<<"$OUT")" != 1 ]; then unresolved "microvm-image $IMAGE_NAME: listed several: $OUT"
  else arn=$OUT
    [ "$arn" = "arn:aws:lambda:eu-west-1:$ACCOUNT:microvm-image:$IMAGE_NAME" ] || die "image ARN [$arn]"
    rec IMAGE_ARN "$arn"
    lvr image get -id "$IMAGE_ARN"
    if [ "$RC" = 0 ] && [ "$(jq -r '.Tags.run // empty' <<<"$OUT")" != "$RUN" ]; then
      finding "microvm-image: tags missing ($(jq -c .Tags <<<"$OUT")); livectl tags only at create"
    elif [ "$RC" != 0 ]; then finding "microvm-image: tags unreadable: ${ECODE:-rc$RC}"; fi
  fi
fi
if pending sns-topic "$TOPIC_NAME" TOPIC_ARN; then
  t="arn:aws:sns:eu-west-1:$ACCOUNT:$TOPIC_NAME"
  try aws sns list-topics --query "length(Topics[?TopicArn=='$t'])" --output json
  if [ "$RC" != 0 ]; then unresolved "sns-topic: list failed: ${ECODE:-rc$RC}"
  elif [ "$OUT" = 1 ]; then rec TOPIC_ARN "$t"
    try aws sns list-tags-for-resource --resource-arn "$t" --query "Tags[?Key=='run'].Value" --output text
    if [ "$RC" = 0 ] && [ "$OUT" != "$RUN" ]; then
      try aws sns tag-resource --resource-arn "$t" --tags Key=purpose,Value=$TAGV Key=run,Value=$RUN; [ "$RC" = 0 ] || unresolved "sns-topic: tagging failed: ${ECODE:-rc$RC}"
    elif [ "$RC" != 0 ]; then unresolved "sns-topic: tags unreadable: ${ECODE:-rc$RC}"; fi
  elif [ "$OUT" = 0 ]; then absent "sns-topic $TOPIC_NAME"
  else unresolved "sns-topic: listed $OUT times"; fi
fi
[ -z "$UNRES" ] && echo "reconciliation complete: nothing unresolved" || { echo "unresolved, for Paul (S.4):"; tr '|' '\n' <<<"$UNRES"; }

The extra IAM call here (tag-role, only when a role exists without its tags) is one of the role calls R37 covers. Image versions are not reconciled: they go with the image, which livectl deletes whole.

S.3 VMs. If the image was never created (no IMAGE_ARN, even after S.2), no VM can exist; the block records the skip and ends (skip-never-created rule).

set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"; guard
if ! have IMAGE_ARN; then echo "no image was ever created, so no VM can exist"; exit 0; fi
! ctl_alive || die "the controller is running"
settle_all
sleep 120
settle_all

settle_all ends every recorded VM and every live VM an image-scoped List shows, accepts an end only as TERMINATED or two not-found reads at least 60 s apart, and finishes only after three consecutive scans 30 s apart show nothing live. The second run, at least 2 minutes after the controller stopped, covers the residual R21 accepts: a launch request AWS held after the client gave up can still create a VM late. A VM that appears even later is visible to any later scan of the image while the image exists, and its maximum duration (at most 1 hour for the drivers, 30 minutes for the orphan, 15 minutes for the contract) ends it.

S.4 What is left for Paul. Everything else in the ledger stays in place, and the agent reports the ledger and this exposure:

| Left in place | Cost while it stays | | --- | --- | | MicroVM image (two or three versions) | about $0.08 per GB-month (Ireland rate not printed), assumed 6 GB: about $0.50 a month; worst case 102 GB: about $8.20 a month; one-week minimum already paid | | Connector, VPC, subnet, route table, group, defaults | no listed charge (no NAT, gateway or Elastic IP) | | IAM roles, log group (1-day retention), SNS topic | none | | S3 bucket and one object under 10 MB | under $0.01 a month | | Anything S.2 marked UNRESOLVED | its row above; an unresolved image is the only one with a cost (storage), an unresolved MicroVM intent is covered by S.3's scans |

Teardown (section 10) then runs only on Paul's word, for the recorded resources only.

---

11. Spend

11.1 Estimate

Rates: Ireland x86_64 compute from spec §10 ($0.155 an hour at 2 GB baseline; above-baseline use up to 4x costs extra). The pricing page prints snapshot and storage rates for US East only (write $0.0038 per GB, read $0.00155 per GB, storage $0.08 per GB-month, image storage with a one-week minimum); the worst case adds 20 % to those for Ireland. It lists no charge for image builds or connectors; the worst case still allows for builds billed as VM time.

| Item | Basis | Expected | Worst case, every approved branch | | --- | --- | --- | --- | | Facts VMs (9) | A1 about 10 min; payload VMs ended at once | $0.04 | A1, A2, A3, E1, G1 at 600 s each (was 900 s, R43), 4 payload VMs at 120 s: 0.97 h, $0.15 | | Contract VMs (6) | about 7, 3 to 6 min each | $0.09 | 8 at their 15-min maximum: 2 h, $0.31 | | Controller VMs (7) | 2, about 10 min each | $0.05 | 2 at the 1-h maximum, plus one late R21 VM at 1 h: 3 h, $0.47 | | Orphan VM (8) | about 12 min | $0.03 | 1800 s: 0.5 h, $0.08 | | Above-baseline use | idle hook server, none expected | $0.00 | 4x on all 6.47 VM-hours: +$3.01 | | Pause and resume | 3 cycles at about 2 GB | $0.03 | 3 cycles at 40 GB (8 GB memory, 32 GB disk), x1.2: $0.82. Three is the plan's maximum: one suspend each in 9.C, the contract and the driver | | Launch snapshot reads | about 22 starts at 2 GB | $0.07 | 30 starts at 40 GB, x1.2: $2.23 | | Image storage | 2 versions, assumed 3 GB each, one-week minimum | $0.11 | 3 versions (Small, a failed Small after the step down, Large) at 34 GB: 102 GB, one-week minimum, x1.2: $2.28 | | Image builds | 2 builds, a few minutes | $0.05 | 3 builds (the step down adds one) of 20 min at 4 GB: $0.31 | | S3, CloudWatch Logs, SNS, data transfer | tiny object, under 1 MB of logs, a few publishes, no route out | $0.02 | $0.05 | | Total | | about $0.55 | about $9.70 |

The worst case is the sum of every bound at once (every VM at its maximum, at 4x, with the largest snapshots), which cannot all happen in one run; it is still under the $10 approval ceiling. Leftovers after an abort are not in the total: retained image storage costs about $0.50 to $8.20 a month until teardown (S.4).

Which bound changed (R43). The third build and its retained failed version add about $0.87, so the fact experiments' VM maximum duration is cut from 900 s to 600 s (A1, A2, A3, E1 and G1, which must share one request body). VM_A needs about 10 minutes for 9.A to 9.C; if it reaches its maximum early, that is a FINDING, not a safety issue. The pause-cycle row is also corrected to the plan's real maximum of three (it counted six). The worst case is about $9.70, under the $10 ceiling.

11.2 The run's own estimate (stop rule)

Computed from the VM ledger and the journal at the end of every section, with no billing call. Each VM's life starts at the provider's startedAt (from the launch reply or any image-scoped scan); for a VM known only from a log, at the start of the phase that found it, which is earlier than its real start. It ends at the time its end was confirmed (VMGONE), which is later than its real end, or now if it has not ended. Both ends err on the long side, so the figure is an upper bound on VM time at baseline. A VM whose only start is a phase start is counted and listed as such.

set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"
python3 -I - "$VMS" "$JOURNAL" <<'EOF'
import sys, datetime as dt
def p(x):
    t = dt.datetime.fromisoformat(x.replace("Z", "+00:00"))
    if t.tzinfo is None or t.utcoffset() is None: raise ValueError(f"timestamp {x!r} has no time zone")
    return t
now = dt.datetime.now(dt.timezone.utc)
prov, phase, end = {}, {}, {}
def bad(kind, n, line, why):
    sys.exit(f"ABORT: {kind} line {n} cannot be read ({why}): {line[:160]!r}")
for n, line in enumerate(open(sys.argv[1]), 1):
    f = line.rstrip("\n").split("\t")
    if len(f) != 4: bad("VM ledger", n, line, f"{len(f)} fields, want 4")
    vid, src, start, _ = f
    if not vid: bad("VM ledger", n, line, "empty VM ID")
    try:
        if start.startswith("phase:"):
            t = p(start[6:]); phase[vid] = min(t, phase.get(vid, t))
        else:
            t = p(start); prov[vid] = min(t, prov.get(vid, t))
    except ValueError as e: bad("VM ledger", n, line, e)
for n, line in enumerate(open(sys.argv[2]), 1):
    if "\t" not in line: bad("journal", n, line, "no tab")
    ts, msg = line.rstrip("\n").split("\t", 1)
    w = msg.split(" ")
    if w[0] == "VMGONE":
        if len(w) < 2 or not w[1]: bad("journal", n, line, "VMGONE without an ID")
        try: end[w[1]] = p(ts)
        except ValueError as e: bad("journal", n, line, e)
hours, phase_only = 0.0, []
for vid in set(prov) | set(phase):
    start = prov.get(vid) or phase[vid]
    if vid not in prov: phase_only.append(vid)
    hours += max(0.0, (end.get(vid, now) - start).total_seconds()) / 3600
live = [v for v in set(prov) | set(phase) if v not in end]
third = any("\tCONFIRMED VER_SMALL_FAILED " in l for l in open(sys.argv[2]))
est = hours * 0.155 + 0.11 + 0.05 + 0.02 + 0.0057 * 2 * 3 + (0.055 + 0.025 if third else 0)
print(f"VMs {len(prov) + len([v for v in phase if v not in prov])}, not yet ended {len(live)}, "
      f"started from phase only {len(phase_only)} {phase_only}, VM-hours {hours:.2f}, estimate ${est:.2f} "
      f"(baseline compute plus image storage, builds, small items and three pause cycles; retained storage after an abort is separate)")
sys.exit(3 if est >= 5 else 0)
EOF
  • Stop rule: exit status 3 (estimate $5 or more), or a VM live outside its step, means the safe stop. A journal or VM ledger line that cannot be read ends the block with an ABORT: line naming it (exit status 1); the estimate is then made by hand from the ledger and reported as such. Paul reads the real bill himself (R33).

Wall-clock: about 4.5 to 5 hours from 0.1 to 10.9.

---

12. UNCONFIRMED items and placeholders

Settled by the attempts and revision 5

  • U1, connector role trust: lambda.amazonaws.com with sts:AssumeRole and sts:TagSession was accepted (attempt 3).
  • Build role trust: granting both actions covers both versions of the AWS page.
  • U2, create half: the narrow operator policy is refused at create time even after 3.3 minutes (attempt 3); the managed policy plus the scoped delete was accepted. 2.1 now uses it from the start. The delete half is item 1 below.
  • U3, old CLI model: no Lambda call goes through the CLI any more (R40). livectl sends X86_64 and reads Version, VersionArn, LatestVersionArn, Status and SupportedCpuConfigurations through the pinned SDK. Attempt 3's discovery confirmed that <arn>:1 reads Version 1, and that the unqualified body carries LatestVersion and LatestVersionArn only.
  • U6, hooks: documented; a runtime hook failure shows up as a FINDING or as A1's stop.
  • U9, connector interfaces: connector delete took about 19 s (attempt 3). There were no interfaces while ACTIVE, so cleanup with interfaces present is still item 1.
  • U10, eu-west-1a: accepted for the subnet (attempt 2) and the connector (attempt 3).
  • U12, the Date header: livectl reports it as ResultMetadata.ServerTime. lambda-core sends one (attempt 3's discovery); GetMicrovm is measured in 9.B.
  • U13, tag index: the index lagged by up to a day after every teardown; direct reads decide (attempts 2 and 3).
  • U15, billing service name: removed with Cost Explorer (R33).
  • U18, part: connector-by-name gives ResourceNotFoundException; IAM gives NoSuchEntity; NoSuchTagSet is documented. Guessed S3, SNS and EC2 codes were replaced by list-and-match checks.
  • U20, process survival: R37 (sandbox off, PID files, identity checks).
  • U23, livectl and the kass credentials: settled by R42. livectl stays static-only; the plan exports kass's credentials per call with aws configure export-credentials --profile kass --format process (the format and its JSON schema are from the installed CLI's own help) and hands livectl only the static keys, as the livectl rule says. Long waits are split at the credentials' expiry. That the exported keys are accepted by livectl's account check is first shown in 0.3; a refusal there is a hard stop before anything is created.
  • U22, livectl's interface: settled at bdf85fb7. The plan follows livectl-usage.md at that commit: pinned endpoints, one attempt per call, a 60 s cutoff per call, bounded waits that never read after their deadline, and static credentials only. After Astra's round 1 on revision 5, every call site handles the exits as the livectl rule says. Exit 4 and every other hard stop propagate through subshells and polls (die with the FATAL marker; finding re-raises it). Exit 2 is a FINDING on observation reads and follows the block's branches on changes, with uncertain launches settled. Exit 5 is checked against one outer deadline per wait. "Items":null is read as an empty list, and any other malformed list reply fails through list_items.

Still unconfirmed, 12

Each is now either a stop only where safety or a later step depends on it, or a FINDING.

  1. U2, delete half. It is untested whether Lambda's interface deletion passes the ec2:ManagedResourceOperator condition. 10.2's pre-approved fallback drops that condition (keeping the subnet condition) and retries once; a second failure is a hard stop.
  2. U4, base image version. livectl now reads Status and x86_64 support. A failed create or build steps down one version once (3.6 to 3.8). A second failure stops the run: the image is needed.
  3. U5, container base image public.ecr.aws/lambda/microvms:al2023-minimal for x86_64. A build failure takes the same step down; nothing else is substituted.
  4. U7, build log group. Other groups under the prefix are never deleted; 10.6 stops for Paul (not in the ledger).
  5. U8, image deletion. A ConflictException from livectl image delete is a stop, since teardown needs the image gone.
  6. U11, an unknown VM ref on terminate: now a FINDING (6.1 labels it "known").
  7. U14, the Small version stays ACTIVE after the update: a FINDING (3.9).
  8. U16, Ireland rates for snapshots, launch reads and image storage: an estimate assumption.
  9. U17, MicroVM ID format: 9.A records the first real ID; outside R36's form is a FINDING. The image-scoped scans are the inventory either way.
  10. U18, the Lambda MicroVMs not-found code (ResourceNotFoundException for a gone VM) is documented but not observed. It stays fail-closed only in vm_end, where proving a VM ended is a safety check. Everywhere else a different code is a FINDING.
  11. U19, image version tags: recorded as read (3.8), a fact.
  12. U21, a qualified egress ARN on RunMicrovm. The adapter and the audit require it. A1 in 9.A is the first launch; a refusal stops the run, since every VM step needs launches (Fable's review).

Placeholders

None. PIN_SHA is bdf85fb70f26094b99241de3f1285de92a76a759.