oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1# Hosted runners 1a, Task 17: live check plan (for Paul's approval)
2
3**Revision:** 5 (2026-11-28), in the shape Fable's review proposed and Paul accepted, after attempt
43 stopped safely at 2.4 and was torn down (`52d73c2c`). Revision 4 (`c5f9bc36`) was the approved
5one. **Status:** draft for approval. No AWS command or SDK call of any kind was made while writing
6it.
7
8## What Paul approves
9
10One run in account `640012953448` (profile `kass`), region `eu-west-1`, every call behind the
11account and region guard; IAM is the one global-endpoint exception (R37) and there is no billing
12call (R33). Every Lambda MicroVMs and Lambda core call goes through `livectl`, the pinned Go SDK
13tool (R40), which refuses any other account, region or name outside the run; EC2, IAM, S3, SNS,
14CloudWatch Logs and STS stay on the CLI. Every taggable resource carries `purpose=equipo-hosted-dev`
15and `run=<RUN>`; MicroVMs (no tag field) and the connector's Lambda-managed interfaces are recorded
16by ID and proven gone (R34). The code is the exact revision `PIN_SHA` (R35), and the controller's
17reaper sees only this run's image (R32). The run stops hard only for safety: the wrong account or
18region, spend (the run's own estimate reaching $5; $10 is the approval ceiling), a MicroVM alive
19outside its step, or anything not in the ledger. It also stops when a step that later steps need
20cannot complete (a resource that cannot be created or deleted). Everything else that differs from
21expectation becomes a `FINDING:` line in the journal and the run goes on where it safely can; the
22report lists every FINDING. Reads of the run's own resources never stop it. Paul also pre-approves
23these fallbacks: the operator role uses the AWS-managed connector policy plus a subnet-scoped
24delete from the start; 3.6 to 3.8 step down one base image version once; the contract runs to
25completion; 9.B records echoes instead of asserting them; and 10.2 drops the delete policy's
26managed-operator condition once if the connector cannot be deleted. Expected spend is about $0.55,
27worst case about $9.70, retained image storage after an early stop about $0.50 to $8.20 a month.
28Guarded, run-scoped, read-only calls on this run's own resources are pre-approved even where this
29plan does not print them; a failed observation read is a FINDING. Reads needed for identity,
30ownership, settlement, deletion or a named later step stay fatal. Any other change to a command,
31or any other AWS call, comes back to Paul first.
32
33## Changes since revision 4 (`c5f9bc36`)
34
351. **Two kinds of stop.** Hard stops are for safety only: account or region, spend, a VM alive
36 outside its step, anything not in the ledger; plus a step later steps need that cannot complete.
37 Everything else is a `FINDING:` journal line (`finding`, `fact_eq`, `fact_lv`) and the run goes
38 on. The report lists every FINDING.
392. **Reads of the run's own resources never stop the run;** a read that errors is a FINDING.
403. **livectl for every Lambda MicroVMs and Lambda core call (R40).** It is built in 0.2 and called
41 through `lv`. jq now reads the SDK's Go field names, with unions under `.Value`. Client tokens
42 start with the run prefix, as livectl's guard requires. A livectl guard refusal is a hard stop.
43 0.4's account-wide MicroVM count is dropped: livectl lists by image, and R32 makes the count
44 irrelevant.
454. **Code pin.** `PIN_SHA` is `bdf85fb7`, livectl's final commit. 0.1 checks it contains
46 `a36861a0` (livectl) and `f95575c6` (R32), and runs livectl's offline tests. Every livectl call
47 site handles its exit codes as the usage at that commit defines them (see the livectl rule).
485. **Operator role.** 2.1 creates it with `AWSLambdaNetworkConnectorOperatorPolicy` plus the inline
49 subnet-scoped delete, then waits 120 s for propagation (the wait before attempt 3's accepted
50 call). 2.2 creates the connector once. The narrow policy and its retries are gone.
516. **Connector version (2.4).** The version-1 qualified ARN is read back through livectl (`Version`
52 1, `VersionArn`, ACTIVE, this subnet and group). The unqualified read's `LatestVersionArn` and the
53 version list are recorded as facts. No interfaces while ACTIVE is normal (attempt 3).
547. **Base image (3.6 to 3.8).** livectl reads `Status` and `SupportedCpuConfigurations`. 3.6 picks
55 the newest `AVAILABLE` x86_64 version and the next one down. If the create (3.7) or the build
56 (3.8) fails, it steps down once.
578. **Contract (6.1).** It runs to completion, and every failed subtest becomes a FINDING with its
58 own messages. All its VMs are still settled.
599. **Facts (9).** 9.B records the egress, role, idle-policy and ingress echoes as facts. The Date
60 header comes from livectl's `ResultMetadata.ServerTime`. Unexpected codes in 9.A to 9.G are
61 FINDINGs; any VM an experiment made is still ended before the next one.
6210. **Controller sections.** A 5.6 audit that does not pass is a FINDING, and 7 and 8 are then
63 skipped. Driver and evidence failures in 7 and 8 are FINDINGs. An orphan alive past P+15:00
64 stays a hard stop.
6511. **Teardown.** 10.1 deletes the image (all versions) through livectl. 10.2 deletes the
66 connector through livectl. On `DELETE_FAILED`, or interfaces left at the bound, 10.2 drops the
67 delete policy's `ec2:ManagedResourceOperator` condition (keeping the subnet condition) and
68 retries once; a second failure is a hard stop. Image versions are no longer separate teardown
69 objects.
7013. **Astra's round 1 on revision 5.**
71 - A hard stop inside a subshell or a poll now reaches the parent (`die` writes a FATAL marker,
72 `finding` re-raises it), so it can never become a FINDING. `ctl_ready`'s listener check stays
73 a hard stop. Every block is run as its own script (`bash <file>`), so `set -e` is always in
74 force.
75 - A launch with an uncertain outcome (no answer, a 5xx) is replayed under the same client token
76 and then settled by image-scoped scans before anything else runs; only a 4xx counts as a
77 confirmed refusal.
78 - List replies go through one validator (`list_items`): an object with an explicit `Items` that is
79 null (read as empty) or an array; any other shape fails per the call's rules, a hard stop for
80 collision, settlement, deletion and reconciliation decisions.
81 - Interfaces outside the run's subnet are a hard stop. Interfaces are recorded by ID during the
82 VM phases and before the connector delete, and 10.2 proves each one gone.
83 - `lv_wait` has one outer deadline covering credentials, start-up and waiting. A late success
84 is a timeout.
85 - 10.2 shares one 120-minute budget across the attempt and its fallback, inside a 130-minute
86 block limit.
87 - Spend (R43): the fact VMs' maximum is now 600 s and the third build is counted; the worst case
88 is about $9.70.
89 - The read-only envelope is stated; observation reads in 1.1 to 1.3 are FINDINGs.
90 - Stale prose in 1.1, 1.2 and 7.3 is aligned.
9112. **Section 12 re-run.** Settled: U3, U10, U12, U13 and the create half of U2. U11, U14, U17 and
92 U19 are now FINDINGs. New: U21 (a qualified egress ARN on RunMicrovm) and U22 (livectl's
93 interface after Astra).
94
95## Order of execution
96
97| Run order | Section | Roughly |
98| --- | --- | --- |
99| 1 | 0. Guard rails, code pin, collision checks | 10 min |
100| 2 | 1. Network | 10 min |
101| 3 | 2. Connector | 10 to 15 min |
102| 4 | 3. Image | 30 to 45 min |
103| 5 | 4. SNS topic | 2 min |
104| 6 | 5. Keys, config, builds, and the audit-only controller run | 15 min |
105| 7 | 9.A to 9.F, facts through livectl (no controller running) | 40 min |
106| 8 | 6. Live contract | 30 min |
107| 9 | 7. Controller sequence and crash check | 45 min |
108| 10 | 8. Orphan | 25 min |
109| 11 | 9.G, final facts | 10 min |
110| 12 | 10. Teardown and verification | 45 to 75 min |
111
112The SDK-side network audit (5.6) runs before any VM is launched, so the connector's `VersionArn`
113and Elastic IP setting are checked by the controller's own code before the first launch.
114
115## Rules for every block
116
117- **Every block runs with the agent sandbox off.** Attempt 1 showed the sandbox proxy blocks AWS
118 (its allowlist has no `*.amazonaws.com`, and `allowed_domains` is ignored in this session), and
119 `$TMPDIR` is a different path inside and outside the sandbox. Running every block the same way
120 keeps `$TMPDIR/equipo-t17` one directory and lets AWS calls through.
121- **Every block runs as its own script, `bash <file>`.** The agent writes each block's text,
122 exactly as printed (only the `<T17 printed by 0.2>` path filled in), to `$T17/blocks/<block>.sh`
123 and runs `bash "$T17/blocks/<block>.sh"` in the foreground, or detached for the long blocks below.
124 0.1, 0.1a and 0.2 run before the scratch exists, so they go to `$TMPDIR/equipo-t17-pre/` instead,
125 which 10.9 removes.
126 It never pastes a block into the tool's shell: the plan writer found on 2026-11-28 that a tool's
127 wrapper can run commands in a context where `set -e` is ignored, which would let a failed command
128 pass silently. Run as a script, `set -e` is in force, and every hard stop also reaches the parent
129 through `die`'s FATAL marker.
130- **One block, one Bash tool call, run by bash.** Every block begins with
131 `set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"` and, if it calls AWS, `guard`. The
132 environment file (0.2) defines every helper the blocks use; nothing is pasted by hand.
133- **Two kinds of stop (Paul, 2026-11-28).** `die` is kept for the hard stops: the wrong account or
134 region (`guard`, livectl's own guard), spend (11.2's $5 rule; $10 is the approval ceiling), a
135 MicroVM alive outside its step (`settle_all`, `vm_end`, the orphan bound), anything not in the
136 ledger (collision checks, unknown resources, unresolved creations), and a step later steps need
137 that cannot complete (a create or delete that fails, the connector's qualified ARN, the image).
138 Everything else that differs from expectation is a `finding`: a `FINDING` line in the journal,
139 printed with `FINDING:`, and the block goes on. The report lists every FINDING.
140- **The read-only envelope.** Guarded (`guard`, livectl's own guard), run-scoped, read-only calls
141 on this run's own resources are pre-approved, including ones this plan does not print. A read
142 that only observes, and errors or answers differently, is a FINDING (`fact_eq`, `fact_json`,
143 `fact_lv`, `eni_snapshot soft`). A read needed for identity, ownership, settlement, deletion or a
144 named later step stays fatal: the VM scans and `vm_end`, the collision checks, the connector's
145 qualified ARN, the base image list, the default-resource lookups, the interface list before the
146 connector delete, and every deletion check.
147- **Failure is loud.** A failed command that is not handled ends the block. Calls that are expected
148 to fail run under `try` or `lv` and pass only through an explicit branch that names the accepted
149 error codes. Every poll fails when its bound runs out.
150- **livectl (R40).** Every Lambda MicroVMs and Lambda core call goes through `lv`, which runs
151 `$T17/bin/livectl -run <RUN>` (built in 0.2 from the pinned code). livectl takes only static keys
152 (R41), and `kass` resolves through a `credential_process`, so each call first runs
153 `aws configure export-credentials --profile kass --format process` and starts livectl in a
154 subshell holding only `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY` and, if one was issued,
155 `AWS_SESSION_TOKEN`, with `AWS_PROFILE`, `AWS_CONFIG_FILE` and `AWS_SHARED_CREDENTIALS_FILE` unset
156 (R42). The keys live only in that subshell's environment: never on disk, in the journal, in an
157 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
158 output structs with Go field names (`State`, `VersionArn`, `MicrovmId`) and unions under
159 `.Value`; its errors are one JSON line whose `code` `lv` puts in `ECODE` and whose `aws_message`
160 it puts in `LV_MSG`. Client tokens start with the run prefix, as livectl requires. Exit codes, as
161 livectl defines them at `PIN_SHA`:
162 - **4** (guard: account, region, run prefix, missing `-run`, or credentials that are not static
163 keys) and **3** (usage) are hard stops, inside `lv` itself.
164 - **2** (an SDK call failed; livectl makes one attempt per call, so a throttle, a 5xx or no answer
165 within its 60 s cutoff, `"error":"transport"`, all come back as 2). On a read, `lvr` tries a
166 transient failure up to 3 times, 5 s apart; what is left is a FINDING, except where a hard stop
167 depends on the read (the VM scans, `vm_end`, the collision checks, the connector's qualified
168 ARN, the base image list). On a change it follows the block's own branches; only idempotent
169 deletes and terminates use `lvr`.
170 - **5** (a wait's bound passed, including an answer that came after it) and **6** (a failed
171 state) are handled by each block against its bound. `lv_wait` gives each wait one overall bound
172 and carries on through a transient exit 2 inside it, as a FINDING.
173- **A hard stop means the safe stop (section S), then ask Paul.** Nothing else runs after it.
174- **Ledger.** Before each create call the block writes an `INTENT` line (kind, run-specific name or
175 token); after the call it records the confirmed ID with `rec` (checked writes, ARN checks). Every
176 MicroVM ID that appears anywhere is added to the VM ledger with `vmrec`. A deletion is recorded
177 with `deleted` only after a direct read shows it gone. Teardown and the safe stop work only from
178 these records; nothing is ever adopted or deleted because its name looks right.
179- **Skip-never-created rule.** Teardown (section 10) and the safe stop act only on resources with
180 a confirmed creation record, that is, a ledger variable set by `rec` (`VPC`, `CONN_ARN`,
181 `IMAGE_ARN`, `BUCKET_CREATED` and so on; the names in `run.env` alone do not count). `have` sees
182 three states. Confirmed: act. Never attempted, or the last attempt followed by a `NOTCREATED`
183 record (from S.2 or a refused create): journal `SKIP <variable>` and skip. Unresolved (an
184 `INTENT` with neither): never skipped; the block aborts, so teardown cannot complete, S.3 cannot
185 report "never created", and 10.9 cannot remove the scratch until S.2 reconciles it.
186- **Long blocks, one mechanism.** These blocks can run past the Bash tool's 10-minute limit for one
187 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
188 written to a script file and run detached from a sandbox-off shell, and its exit status is read
189 from a status file. Every one of them starts with the sandbox-off header, so it runs the same way
190 detached. The agent never uses another background mechanism.
191 1. Write the block's text, exactly as printed here with only the `<T17 printed by 0.2>` path filled
192 in, to `$T17/blocks/<block>.sh` (for example `$T17/blocks/6.1.sh`), as for every block.
193 2. Start it (one sandbox-off call):
194
195 ```sh
196 set -euo pipefail; T17='<T17 printed by 0.2>'; B='<block>'
197 d="$T17/blocks"; [ -s "$d/$B.sh" ] || { echo "ABORT: no $d/$B.sh"; exit 1; }
198 [ ! -e "$d/$B.status" ] && [ ! -e "$d/$B.pid" ] || { echo "ABORT: block $B was already started"; exit 1; }
199 bash -n "$d/$B.sh"
200 date +%s > "$d/$B.start"
201 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 &
202 echo $! > "$d/$B.pid"; echo "block $B started, PID $(cat "$d/$B.pid")"
203 ```
204
205 3. Wait (repeat this sandbox-off call until it prints an exit status; each call is bounded at
206 9 minutes; `MAXMIN` is the block's bound from the table):
207
208 ```sh
209 set -euo pipefail; T17='<T17 printed by 0.2>'; B='<block>'; MAXMIN='<bound>'
210 d="$T17/blocks"; [ -s "$d/$B.start" ] || { echo "ABORT: block $B was not started"; exit 1; }
211 for i in $(seq 1 108); do [ -s "$d/$B.status" ] && break; sleep 5; done
212 tail -n 60 "$d/$B.out" || true
213 if [ -s "$d/$B.status" ]; then s=$(cat "$d/$B.status"); echo "block $B exit status $s"; [ "$s" = 0 ] || exit 1; exit 0; fi
214 el=$(( ($(date +%s) - $(cat "$d/$B.start")) / 60 ))
215 if [ "$el" -ge "$MAXMIN" ]; then
216 p=$(cat "$d/$B.pid"); kill -TERM -- "-$p" 2>/dev/null || true
217 echo "ABORT: block $B ran past its $MAXMIN-minute bound; its process group was stopped"; exit 1
218 fi
219 echo "block $B still running after $el minutes"
220 ```
221
222 An exit status other than 0, or the bound passing, is an abort (safe stop). Bounds in minutes:
223 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;
224 10.1: 30; 10.2: 130 (its shared budget is 120).
225- **The controller, with the sandbox off (R37).** A sandboxed Bash call kills its child processes
226 when it returns, so every block that starts, checks or stops the controller runs with the agent's
227 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
228 the other long blocks (2.1, 2.3, 3.8, 3.9, 9.C, 10.2), which run detached. Outside
229 the sandbox `$TMPDIR` is different, so those blocks set `T17` explicitly to the path 0.2 printed;
230 their first line reads `set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"`, and that
231 path is the only text the agent fills in. `start_ctl` starts the controller with `setsid nohup`,
232 writes its PID and, when it ends, its exit status to files. `ctl_alive` and `stop_ctl` check that
233 the PID still belongs to this run's binary (`/proc/<pid>/cmdline`) before anything is signalled.
234 If the controller is gone when a block expects it, or a port stays open with no matching
235 process, that is an abort.
236- **docs-t1.** The controller listens on `127.0.0.1:18443` (API) and `127.0.0.1:18444` (metrics)
237 only, checked after every start. The hook server in the image listens on port 9000 inside the
238 MicroVM, not on docs-t1. Scratch is `$TMPDIR/equipo-t17`, removed in 10.9. Go caches stay at
239 their defaults; every Go command runs with `CGO_ENABLED=0`. No sudo.
240- **Records.** After each section, append its results to
241 `docs/superpowers/plans/HOSTED-SLICE1-PROGRESS.md` under `## Task 17 live run`, and commit that
242 file locally at the end (subject under 80 characters). Never push. The report lists every
243 `FINDING` line (10.9 prints them all).
244
245---
246
247## 0. Guard rails
248
249### 0.1 Code pin and local tools (no AWS call)
250
251`PIN_SHA` is `bdf85fb7` (`bdf85fb70f26094b99241de3f1285de92a76a759`), livectl's final commit (static
252credentials only, endpoints pinned, one attempt per call, bounded calls and waits), relayed by the
253coordinator. It contains livectl's first commit `a36861a0`, R32 (`f95575c6`) and the earlier
254pre-flight work. The block also runs livectl's offline tests.
255
256```sh
257set -euo pipefail
258PIN_SHA='bdf85fb70f26094b99241de3f1285de92a76a759'
259case "$PIN_SHA" in *'<'*|'') echo "ABORT: PIN_SHA is not filled in"; exit 1;; esac
260cd /home/paulca/amadan.net/oficina/equipo-hosted-1a
261git rev-parse --verify "$PIN_SHA^{commit}"
262git merge-base --is-ancestor f95575c6 "$PIN_SHA" || { echo "ABORT: $PIN_SHA does not contain R32 (f95575c6)"; exit 1; }
263git merge-base --is-ancestor a36861a0 "$PIN_SHA" || { echo "ABORT: $PIN_SHA does not contain livectl (a36861a0)"; exit 1; }
264git merge-base --is-ancestor "$PIN_SHA" HEAD || { echo "ABORT: HEAD does not contain $PIN_SHA"; exit 1; }
265d=$(git diff "$PIN_SHA" HEAD -- . ':!docs'); [ -z "$d" ] || { echo "ABORT: code differs from $PIN_SHA outside docs/"; exit 1; }
266s=$(git status --porcelain --untracked-files=all -- . ':!docs'); [ -z "$s" ] || { echo "ABORT: uncommitted changes outside docs/:"; echo "$s"; exit 1; }
267git log --oneline -1
268aws --version
269go version
270for t in jq openssl sha256sum curl ss python3 setsid nohup; do command -v "$t" >/dev/null || { echo "ABORT: missing $t"; exit 1; }; done
271CGO_ENABLED=0 go test -tags hostedlive ./internal/isolatedjob/awsjob/livectl -count=1
272echo "code pin ok: $PIN_SHA"
273```
274
275- Expected: livectl's offline tests pass; `code pin ok`; `aws-cli/2.36.x`; `go1.26.x`.
276- Abort if: any check fails.
277
278### 0.1a Remove attempt 1's scratch, only if it created nothing (no AWS call)
279
280Attempt 1 left `$TMPDIR/equipo-t17` with an empty ledger and no creation records. This step removes
281it only in exactly that state, keeping its journal as evidence; anything else stops.
282
283```sh
284set -euo pipefail
285: "${TMPDIR:?TMPDIR is unset}"
286S="$TMPDIR/equipo-t17"; K="$HOME/.cache/tmp/equipo-t17-attempt1"
287if [ ! -e "$S" ]; then echo "no earlier scratch at $S; nothing to remove"; exit 0; fi
288[ -f "$S/journal.tsv" ] || { echo "ABORT: $S has no journal.tsv"; exit 1; }
289set +e; grep -qE $'\t(INTENT |CONFIRMED |VM |CONTROLLER start )' "$S/journal.tsv"; g=$?; set -e
290case "$g" in
291 0) echo "ABORT: the earlier journal records a creation, a VM or a controller start"; exit 1;;
292 1) ;;
293 *) echo "ABORT: could not check the earlier journal (grep status $g)"; exit 1;;
294esac
295for 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
296[ ! -e "$S/controller.pid" ] || { echo "ABORT: $S/controller.pid exists"; exit 1; }
297[ ! -e "$K" ] || { echo "ABORT: $K already exists"; exit 1; }
298mkdir -p -m 700 "$K"
299cp -p "$S/journal.tsv" "$K/journal.tsv"; cmp -s "$S/journal.tsv" "$K/journal.tsv" || { echo "ABORT: journal copy differs"; exit 1; }
300[ -f "$S/run.env" ] && cp -p "$S/run.env" "$K/run.env"
301rm -rf "$S"; [ ! -e "$S" ] || { echo "ABORT: $S still exists"; exit 1; }
302echo "attempt 1 scratch removed; journal kept at $K/journal.tsv"
303```
304
305- Expected: "attempt 1 scratch removed", or "nothing to remove". The executor's own helper files
306 outside `$S` are not touched.
307
308### 0.2 Scratch, the environment file and the run names (no AWS call)
309
310```sh
311set -euo pipefail
312: "${TMPDIR:?TMPDIR is unset}"
313[ ! -e "$TMPDIR/equipo-t17" ] || { echo "ABORT: $TMPDIR/equipo-t17 already exists"; exit 1; }
314mkdir -m 700 "$TMPDIR/equipo-t17"
315mkdir -m 700 "$TMPDIR/equipo-t17"/{out,image,iam,keys,bin,blocks}
316cat > "$TMPDIR/equipo-t17/env.sh" <<'ENVEOF'
317# env.sh: sourced by every block, after `set -euo pipefail`. Task 17 only.
318: "${TMPDIR:?TMPDIR is unset}"
319# T17 may be set by a sandbox-off block (R37); otherwise it is $TMPDIR/equipo-t17.
320unset AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN AWS_SECURITY_TOKEN AWS_DEFAULT_PROFILE \
321 AWS_CONFIG_FILE AWS_SHARED_CREDENTIALS_FILE AWS_ROLE_ARN AWS_ROLE_SESSION_NAME AWS_WEB_IDENTITY_TOKEN_FILE \
322 AWS_CA_BUNDLE AWS_ENDPOINT_URL AWS_USE_FIPS_ENDPOINT AWS_USE_DUALSTACK_ENDPOINT
323for _v in $(env | sed -n 's/^\(AWS_ENDPOINT_URL_[A-Z0-9_]*\)=.*/\1/p'); do unset "$_v"; done
324export AWS_PROFILE=kass AWS_REGION=eu-west-1 AWS_DEFAULT_REGION=eu-west-1 AWS_PAGER="" \
325 AWS_STS_REGIONAL_ENDPOINTS=regional AWS_RETRY_MODE=standard AWS_MAX_ATTEMPTS=3
326export CGO_ENABLED=0
327if [ -z "${T17:-}" ]; then T17="$TMPDIR/equipo-t17"; fi
328export T17 REPO=/home/paulca/amadan.net/oficina/equipo-hosted-1a
329export LIVECTL="$T17/bin/livectl"
330export ACCOUNT=640012953448 TAGV=equipo-hosted-dev
331export LEDGER="$T17/ledger.env" JOURNAL="$T17/journal.tsv" VMS="$T17/vms.tsv"
332export NO_INGRESS=arn:aws:lambda:eu-west-1:aws:network-connector:aws-network-connector:NO_INGRESS
333export API=127.0.0.1:18443 METRICS=127.0.0.1:18444
334[ -d "$T17" ] || { echo "ABORT: $T17 does not exist; was TMPDIR changed?" >&2; exit 1; }
335[ -f "$T17/run.env" ] && . "$T17/run.env"
336[ -f "$LEDGER" ] && . "$LEDGER"
337
338# die: a hard stop. It also appends to $T17/FATAL, so a hard stop inside a subshell, a poll or a
339# command substitution reaches the parent: finding and fatal_check re-raise it, so it can never
340# become a FINDING. Exit status 99.
341die() { echo "ABORT: $*" >&2; jw "ABORT $*" 2>/dev/null || true; printf '%s\n' "$*" >> "$T17/FATAL" 2>/dev/null || true; exit 99; }
342# soft_fail: an ordinary failure (a poll's bound or an unexpected state) that ends the current
343# (sub)shell with status 1 without a hard stop; at a block's top level it still ends the block.
344soft_fail() { echo "FAILED: $*" >&2; jw "FAILED $*" 2>/dev/null || true; exit 1; }
345_fatal_count() { if [ -f "$T17/FATAL" ]; then wc -l < "$T17/FATAL"; else echo 0; fi; }
346_FATAL0=$(_fatal_count)
347# fatal_check: re-raise any hard stop that happened in a subshell since this block began.
348fatal_check() { [ "$(_fatal_count)" -le "$_FATAL0" ] || die "a hard stop happened inside a subshell: $(tail -n 1 "$T17/FATAL")"; }
349# need VAR...: each must be set, non-empty, and not None or null.
350need() { local v; for v; do [ -n "${!v:-}" ] && [ "${!v}" != None ] && [ "${!v}" != null ] || die "$v is unset"; done; }
351# arn_ok ARN: in this account and eu-west-1 (IAM and S3 ARNs have no region).
352arn_ok() {
353 case "$1" in
354 *149757027610*) die "ARN $1 names account 149757027610";;
355 arn:aws:*:eu-west-1:640012953448:*|arn:aws:iam::640012953448:role/*|arn:aws:s3:::*) ;;
356 *) die "ARN $1 is not in 640012953448 and eu-west-1";;
357 esac
358}
359# jw TEXT: one journal line; a failed write is an abort.
360jw() { local t="$*"; t=${t//$'\r'/}; t=${t//$'\n'/ | }; t=${t//$'\t'/ }
361 printf '%s\t%s\n' "$(date -u +%FT%T.%3NZ)" "$t" >> "$JOURNAL" || { echo "ABORT: journal write failed" >&2; exit 1; }; }
362# _kind VAR: sets K_I and K_N, the journal patterns for VAR's INTENT and NOTCREATED records ("" when
363# VAR has no creation of its own: the VPC defaults exist only with the VPC, and image versions only
364# with the image, which livectl deletes whole).
365_kind() { case "$1" in
366 VPC) K_I='^INTENT vpc( |$)'; K_N='^NOTCREATED vpc( |$)';;
367 SUBNET) K_I='^INTENT subnet( |$)'; K_N='^NOTCREATED subnet( |$)';;
368 RTB) K_I='^INTENT route-table( |$)'; K_N='^NOTCREATED route-table( |$)';;
369 RTB_ASSOC) K_I='^INTENT route-table-association( |$)'; K_N='^NOTCREATED route-table-association( |$)';;
370 SG) K_I='^INTENT security-group( |$)'; K_N='^NOTCREATED security-group( |$)';;
371 OPERATOR_ROLE_ARN) K_I="^INTENT iam-role $OPERATOR_ROLE( |\$)"; K_N="^NOTCREATED iam-role $OPERATOR_ROLE( |\$)";;
372 BUILD_ROLE_ARN) K_I="^INTENT iam-role $BUILD_ROLE( |\$)"; K_N="^NOTCREATED iam-role $BUILD_ROLE( |\$)";;
373 CONN_ARN) K_I='^INTENT connector( |$)'; K_N='^NOTCREATED connector( |$)';;
374 BUCKET_CREATED) K_I='^INTENT s3-bucket( |$)'; K_N='^NOTCREATED s3-bucket( |$)';;
375 LOG_GROUP_CREATED) K_I='^INTENT log-group( |$)'; K_N='^NOTCREATED log-group( |$)';;
376 ARTIFACT) K_I='^INTENT s3-object( |$)'; K_N='^NOTCREATED s3-object( |$)';;
377 IMAGE_ARN) K_I='^INTENT microvm-image( |$)'; K_N='^NOTCREATED (microvm-image|image attempt)( |$)';;
378 TOPIC_ARN) K_I='^INTENT sns-topic( |$)'; K_N='^NOTCREATED sns-topic( |$)';;
379 *) K_I=''; K_N='';;
380esac; }
381# creation_state VAR: sets CST to confirmed (VAR is set), none (never attempted), absent (the last
382# attempt is followed by a NOTCREATED record) or unresolved (attempted, neither confirmed nor shown absent).
383creation_state() {
384 if [ -n "${!1:-}" ]; then CST=confirmed; return 0; fi
385 _kind "$1"; if [ -z "$K_I" ]; then CST=none; return 0; fi
386 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"
387}
388# have VAR: 0 to act on a confirmed creation; 1, with a journalled SKIP, for one never attempted or
389# shown absent. An unresolved creation is never skipped: it aborts, so teardown cannot complete and
390# scratch cannot be removed until S.2 reconciles it (the skip-never-created rule).
391have() {
392 creation_state "$1"
393 case "$CST" in
394 confirmed) return 0;;
395 none|absent) jw "SKIP $1 $CST"; echo "skip: $1 ($CST: never created)"; return 1;;
396 *) jw "UNRESOLVED-TEARDOWN $1"; die "$1: a creation was attempted but is neither confirmed nor shown absent; reconcile it (S.2) first";;
397 esac
398}
399# no_unresolved: abort if any resource is still unresolved.
400no_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
401 creation_state "$v"; [ "$CST" != unresolved ] || die "$v is unresolved; reconcile it (S.2) before finishing"; done; }
402# gone0 WHAT CMD...: a list read that must succeed and count 0 (no error code is guessed).
403gone0() { local w=$1; shift; get _g "$@"; [ "$_g" = 0 ] || die "$w is still listed ($_g)"; }
404# intent KIND KEY DETAIL...: written BEFORE a create call.
405intent() { jw "INTENT $*"; }
406# rec VAR VALUE: written AFTER a create call returned the ID; checked; exported.
407rec() {
408 [ $# = 2 ] || die "rec needs a name and a value"
409 case "$2" in ""|None|null) die "rec $1: empty value";; *149757027610*) die "rec $1=$2 names account 149757027610";; esac
410 printf 'export %s=%q\n' "$1" "$2" >> "$LEDGER" || die "ledger write failed"
411 jw "CONFIRMED $1 $2"
412 export "$1=$2"
413}
414# deleted KIND ID HOW: written after a deletion is confirmed by a direct read.
415deleted() { jw "DELETED $*"; }
416# try CMD...: run CMD; never exits; sets OUT, ERR, RC and ECODE (the AWS error code, if any).
417try() {
418 local had=0 e; case $- in *e*) had=1;; esac
419 e=$(mktemp "$T17/err.XXXXXX") || { echo "ABORT: mktemp" >&2; exit 1; }
420 set +e; OUT=$("$@" 2>"$e"); RC=$?; [ "$had" = 1 ] && set -e
421 ERR=$(cat "$e"); rm -f "$e"
422 ECODE=$(printf '%s' "$ERR" | sed -n 's/.*An error occurred (\([A-Za-z0-9.]*\)).*/\1/p' | head -n 1)
423 return 0
424}
425# must: after try, the call must have succeeded.
426must() { [ "$RC" = 0 ] || die "call failed (rc $RC, ${ECODE:-no code}): $ERR"; }
427# get VAR CMD...: run a read; abort unless it succeeded; only then store its output in VAR.
428get() { local __v=$1; shift; try "$@"; must; printf -v "$__v" '%s' "$OUT"; }
429# _creds: export kass's credentials through the CLI's own resolution (its credential_process),
430# into shell variables of the calling (sub)shell only (R42). Never written to disk, the journal or
431# any argument list, and never printed. AccessKeyId and SecretAccessKey are required; a
432# SessionToken, if present, needs an Expiration. Static IAM user keys have neither.
433_creds() {
434 local j rc had=0; case $- in *e*) had=1;; esac
435 set +e; j=$(timeout 30 aws configure export-credentials --profile kass --format process 2>/dev/null); rc=$?; [ "$had" = 1 ] && set -e
436 [ "$rc" = 0 ] || return 1
437 _AK=$(jq -r '.AccessKeyId // empty' <<<"$j" 2>/dev/null || true)
438 _SK=$(jq -r '.SecretAccessKey // empty' <<<"$j" 2>/dev/null || true)
439 _ST=$(jq -r '.SessionToken // empty' <<<"$j" 2>/dev/null || true)
440 _EXP=$(jq -r '.Expiration // empty' <<<"$j" 2>/dev/null || true)
441 j=""
442 [ -n "$_AK" ] && [ -n "$_SK" ] || return 1
443 [ -z "$_ST" ] || [ -n "$_EXP" ] || return 1
444}
445# _lvx ARGS...: livectl in a subshell whose environment holds exactly the exported static keys:
446# AWS_PROFILE, AWS_CONFIG_FILE and AWS_SHARED_CREDENTIALS_FILE are unset for it, so livectl sees only
447# static environment keys. A failed export is livectl's guard exit (4): a hard stop in lv.
448_lvx() (
449 if ! _creds; then echo '{"error":"guard","message":"kass credentials could not be exported as static keys (R42)"}' >&2; exit 4; fi
450 unset AWS_PROFILE AWS_CONFIG_FILE AWS_SHARED_CREDENTIALS_FILE AWS_SESSION_TOKEN
451 export AWS_ACCESS_KEY_ID="$_AK" AWS_SECRET_ACCESS_KEY="$_SK"
452 [ -z "$_ST" ] || export AWS_SESSION_TOKEN="$_ST"
453 unset _AK _SK _ST
454 exec "$LIVECTL" -run "$RUN" "$@"
455)
456# cred_left: seconds until the exported credentials expire, or "none" for static keys without an
457# Expiration. Prints nothing secret.
458cred_left() ( _creds || exit 4; unset _AK _SK _ST
459 if [ -z "$_EXP" ]; then echo none; else echo $(( $(date -d "$_EXP" +%s) - $(date +%s) )); fi )
460# lv ARGS...: one livectl call (every Lambda MicroVMs and Lambda core call, R40). Sets OUT, ERR, RC,
461# ECODE (the smithy error code), LV_KIND (api, transport, usage, guard, timeout, failed_state, other)
462# and LV_MSG (the service's own text). A guard refusal (4) or usage error (3) is a hard stop.
463lv() {
464 [ -x "$LIVECTL" ] || die "livectl is not built at $LIVECTL"
465 need RUN
466 try _lvx "$@"
467 ECODE=""; LV_KIND=""; LV_MSG=""; LV_HTTP=""
468 if [ "$RC" != 0 ]; then
469 local e; e=$(tail -n 1 <<<"$ERR")
470 ECODE=$(jq -r '.code // empty' <<<"$e" 2>/dev/null || true)
471 LV_KIND=$(jq -r '.error // empty' <<<"$e" 2>/dev/null || true)
472 LV_MSG=$(jq -r '.aws_message // empty' <<<"$e" 2>/dev/null || true)
473 LV_HTTP=$(jq -r '.http_status // empty' <<<"$e" 2>/dev/null || true)
474 fi
475 [ "$RC" != 4 ] || die "livectl guard refusal (account, region, run prefix or -run): $ERR"
476 [ "$RC" != 3 ] || die "livectl usage error (a plan defect): $ERR"
477 return 0
478}
479# _transient: after lv, 0 if the failure is worth trying again: livectl makes one attempt per call,
480# so a throttle, a server error or no answer within its 60 s cutoff comes back as exit 2.
481_transient() { [ "$RC" = 2 ] || return 1; [ "$LV_KIND" = transport ] && return 0
482 case "$ECODE" in ThrottlingException|TooManyRequestsException|InternalServerException|ServiceException|ServiceUnavailableException) return 0;; esac; return 1; }
483# lvr ARGS...: lv with up to 3 tries, 5 s apart, on a transient failure. For reads and idempotent
484# deletes and terminates only; creates and other changes use lv once.
485lvr() { 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; }
486# lv_wait SECONDS ARGS...: a livectl wait with one outer deadline, SECONDS from now, covering the
487# credential export (bounded at 30 s), livectl's start and account check (its 60 s cutoff) and the
488# waiting itself: 90 s of each call is kept for the first two. A chunk is never longer than what is
489# left; when the exported credentials expire sooner (less a 120 s margin) the wait is split into
490# shorter calls, each with fresh credentials. A transient exit 2 is a FINDING and the wait goes on.
491# A success that comes back after the deadline counts as a timeout. Leaves RC 0, 5 (the deadline
492# passed), 6 (a failed state) or 2 (any other error). A guard failure stays a hard stop.
493lv_wait() { local end=$(( $(date +%s) + $1 )) left cl chunk; shift
494 while :; do
495 left=$(( end - $(date +%s) - 90 )); if [ "$left" -le 0 ]; then RC=5; return 0; fi
496 cl=$(cred_left) || die "kass credentials could not be exported (R42)"
497 left=$(( end - $(date +%s) - 90 )); if [ "$left" -le 0 ]; then RC=5; return 0; fi
498 chunk=$left
499 if [ "$cl" != none ] && [ $(( cl - 120 )) -lt "$chunk" ]; then
500 chunk=$(( cl - 120 )); if [ "$chunk" -lt 15 ]; then chunk=$(( left < 15 ? left : 15 )); fi
501 fi
502 lv "$@" -timeout "${chunk}s"
503 if [ "$RC" = 0 ] && [ "$(date +%s)" -gt "$end" ]; then finding "a wait answered after its deadline; counted as a timeout"; RC=5; return 0; fi
504 if _transient; then finding "transient error inside a wait (${ECODE:-$LV_KIND}); waiting on"; sleep 5; continue; fi
505 if [ "$RC" = 5 ] && [ "$chunk" -lt "$left" ]; then echo "wait split at the credentials' expiry; going on with fresh credentials"; continue; fi
506 return 0
507 done; }
508# finding TEXT: a FINDING line in the journal; the run goes on (Paul's rule 1).
509finding() { fatal_check; jw "FINDING $*"; echo "FINDING: $*"; }
510# fact_eq WHAT WANT CMD...: a read of the run's own resource; a failed read or another value is a FINDING.
511fact_eq() { local w=$1 want=$2; shift 2; try "$@"
512 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; }
513# fact_json WHAT WANT CMD...: as fact_eq, comparing compacted JSON.
514fact_json() { local w=$1 want=$2 got; shift 2; try "$@"
515 if [ "$RC" != 0 ]; then finding "$w: read failed (${ECODE:-rc$RC})"; return 0; fi
516 got=$(jq -c . <<<"$OUT" 2>/dev/null) || { finding "$w: reply is not JSON"; return 0; }
517 if [ "$got" = "$(jq -c . <<<"$want")" ]; then echo "ok: $w"; else finding "$w: got $got, want $want"; fi; }
518# fact_lv WHAT WANT JQ ARGS...: a livectl read; jq -r JQ of the reply must equal WANT, else a FINDING.
519fact_lv() { local w=$1 want=$2 q=$3 got; shift 3; lvr "$@"
520 if [ "$RC" != 0 ]; then finding "$w: read failed (${ECODE:-rc$RC})"; return 0; fi
521 got=$(jq -r "$q" <<<"$OUT" 2>/dev/null) || { finding "$w: reply unreadable"; return 0; }
522 if [ "$got" = "$want" ]; then echo "ok: $w"; else finding "$w: got [$got], want [$want]"; fi; }
523# code_in CODE...: after try, 0 if the call failed with one of CODE.
524code_in() { local c; [ "$RC" != 0 ] || return 1; for c; do [ "$ECODE" = "$c" ] && return 0; done; return 1; }
525# expect_err CODE...: after try, the call must have failed with one of CODE (an expected-failure branch).
526expect_err() { code_in "$@" || die "expected one of [$*], got rc $RC ${ECODE:-no code}: ${ERR:-$OUT}"; }
527guard() {
528 [ "$AWS_PROFILE" = kass ] && [ "$AWS_REGION" = eu-west-1 ] && [ "$AWS_DEFAULT_REGION" = eu-west-1 ] || die "profile or region changed"
529 [ -z "${AWS_ACCESS_KEY_ID:-}" ] || die "AWS_ACCESS_KEY_ID is set"
530 try aws sts get-caller-identity --query Account --output text; must
531 [ "$OUT" = "$ACCOUNT" ] || die "account is $OUT, not $ACCOUNT"
532}
533# poll SECONDS INTERVAL WHAT FN ARGS...: FN returns 0 done, 1 not yet, anything else an ordinary
534# failure (soft_fail). A hard stop inside FN (die) stays a hard stop.
535poll() {
536 local secs=$1 iv=$2 what=$3 rc had=0 end; end=$(( $(date +%s) + secs )); shift 3
537 case $- in *e*) had=1;; esac
538 while :; do
539 set +e; "$@"; rc=$?; [ "$had" = 1 ] && set -e
540 [ "$rc" = 0 ] && return 0
541 fatal_check
542 [ "$rc" = 1 ] || soft_fail "$what: unexpected state (rc $rc)"
543 [ "$(date +%s)" -lt "$end" ] || soft_fail "$what: not done within $secs s"
544 sleep "$iv"
545 done
546}
547
548# --- MicroVMs: recorded by ID (they have no tags), found by the image-scoped List ---
549# vmrec ID SOURCE START: one VM ledger line per (ID, source, start). START is the provider's
550# startedAt, or "phase:<time>" (the start of the phase that found it) when only that is known.
551vmrec() {
552 [ $# = 3 ] && [ -n "$3" ] && [ "$3" != phase: ] || die "vmrec $1: no start time"
553 [ -f "$VMS" ] || die "no VM ledger"
554 local key; printf -v key '%s\t%s\t%s\t' "$1" "$2" "$3"
555 grep -qF "$key" "$VMS" && return 0
556 printf '%s%s\n' "$key" "$(date -u +%FT%T.%3NZ)" >> "$VMS" || die "VM ledger write failed"
557 jw "VM $1 $2 $3"
558}
559# vm_ids: sets VIDS to every recorded VM ID.
560vm_ids() { [ -f "$VMS" ] || die "no VM ledger"; VIDS=$(cut -f1 "$VMS" | sort -u) || die "VM ledger unreadable"; }
561# list_items: validate a livectl list reply in OUT: a JSON object with an explicit Items key whose
562# value is null or an array. On success ITEMS holds that array, with null read as []. Anything else
563# (not JSON, not an object, no Items key, Items of another type) returns 1, and the caller fails per
564# its own rules: a hard stop where the result drives a safety decision (collision, settled, deleted,
565# reconciliation), a FINDING for an observation.
566list_items() {
567 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; }
568}
569# scan: one image-scoped List, every page, every state; records every ID; writes last_scan.tsv.
570scan() {
571 need IMAGE_ARN
572 lvr vm list -image "$IMAGE_ARN"; must
573 list_items || die "malformed VM list reply: $(head -c 200 <<<"$OUT")"
574 jq -e --arg a "$IMAGE_ARN" 'all(.[]; .ImageArn == $a)' <<<"$ITEMS" >/dev/null || die "list returned a VM of another image"
575 jq -r '.[] | [.MicrovmId, .State, .StartedAt] | @tsv' <<<"$ITEMS" > "$T17/last_scan.tsv" || die "VM list items unreadable"
576 local id st started
577 while IFS=$'\t' read -r id st started; do [ -n "$id" ] && vmrec "$id" scan "$started"; done < "$T17/last_scan.tsv"
578 LIVE=$(awk -F'\t' '$2 != "TERMINATED" {print $1}' "$T17/last_scan.tsv") || die "scan output unreadable"
579 cat "$T17/last_scan.tsv"
580}
581# After scan, LIVE holds the IDs of this image's VMs that are not TERMINATED.
582# vm_get ID: sets VST to the state, NOTFOUND, or ERROR:<code>.
583vm_get() {
584 lvr vm get -id "$1"
585 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
586}
587_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; }
588# vm_wait ID TARGET SECONDS ALLOWED...: wait for TARGET; a state outside ALLOWED is fatal.
589vm_wait() { local id=$1 t=$2 s=$3; shift 3; poll "$s" 5 "VM $id to $t" _vm_check "$id" "$t" "$*"; }
590# vm_end ID: terminate and confirm: TERMINATED, or not found twice at least 60 s apart.
591vm_end() {
592 lvr vm terminate -id "$1"
593 [ "$RC" = 0 ] || [ "$ECODE" = ResourceNotFoundException ] || die "terminate $1: ${ECODE:-rc$RC} ${LV_MSG:-$ERR}"
594 local nf=0 end=$(( $(date +%s) + 600 ))
595 while :; do
596 vm_get "$1"; echo "$(date -u +%T) $1 $VST"
597 case "$VST" in
598 TERMINATED) jw "VMGONE $1 TERMINATED"; return 0;;
599 NOTFOUND) [ "$nf" = 0 ] && nf=$(date +%s); [ $(( $(date +%s) - nf )) -ge 60 ] && { jw "VMGONE $1 NOTFOUND-TWICE"; return 0; };;
600 PENDING|RUNNING|SUSPENDING|SUSPENDED|TERMINATING|ERROR:ThrottlingException|ERROR:transport) nf=0;;
601 *) die "VM $1: $VST";;
602 esac
603 [ "$(date +%s)" -lt "$end" ] || die "VM $1 has not ended after 10 min"
604 sleep 10
605 done
606}
607# settle_all: end every recorded and every listed live VM; done only after three scans 30 s apart show none live.
608settle_all() {
609 need IMAGE_ARN; local round i clean id
610 for round in 1 2 3; do
611 scan >/dev/null
612 for id in $LIVE; do vm_end "$id"; done
613 vm_ids
614 for id in $VIDS; do grep -q "VMGONE $id " "$JOURNAL" || vm_end "$id"; done
615 clean=0
616 for i in 1 2 3; do
617 scan >/dev/null
618 [ -n "$LIVE" ] && break
619 clean=$((clean + 1)); [ "$i" -lt 3 ] && sleep 30
620 done
621 vm_ids
622 [ "$clean" = 3 ] && { jw "SETTLED $(wc -w <<<"$VIDS") recorded"; echo "settled: $(wc -w <<<"$VIDS") VMs recorded, none live in three scans"; return 0; }
623 done
624 die "VMs still live after three settle rounds"
625}
626# launch LABEL TOKEN MAXSECONDS PAYLOADFILE: one livectl vm run (Small, NO_INGRESS, the connector);
627# records any VM it returns. TOKEN must start with the run prefix. Sets L_OUTCOME:
628# created the reply names a VM (recorded);
629# rejected a confirmed refusal: an api error with a 4xx status, so AWS did not run it;
630# settled the outcome was uncertain (no answer, a 5xx, an unreadable error): the identical
631# request was replayed up to twice under the same client token; if no replay named a
632# VM, settle_all ended every live VM of this image (bounded image-scoped scans), which
633# proves nothing launched is left. If that cannot be proved, settle_all is a hard stop.
634_launch_once() {
635 lv vm run -image "$IMAGE_ARN" -version "$VER_SMALL" -connector "$CONN_QARN" -max-seconds "$3" \
636 -client-token "$2" -payload-file "$4"
637 printf '%s\n' "$OUT" > "$T17/out/launch-$1.json"; printf '%s\n' "$ERR" > "$T17/out/launch-$1.err"
638 L_RC=$RC; L_CODE=$ECODE; L_MSG=$LV_MSG; L_ID=""
639 if [ "$RC" = 0 ]; then
640 L_ID=$(printf '%s' "$OUT" | jq -r '.MicrovmId // empty')
641 [ -n "$L_ID" ] || die "launch $1 succeeded with no MicrovmId"
642 local st; st=$(printf '%s' "$OUT" | jq -r '.StartedAt // empty')
643 vmrec "$L_ID" "$1" "${st:-phase:$L_T0}"; L_OUTCOME=created
644 elif [ "$LV_KIND" = api ] && [ -n "$LV_HTTP" ] && [ "$LV_HTTP" -ge 400 ] && [ "$LV_HTTP" -lt 500 ]; then L_OUTCOME=rejected
645 else L_OUTCOME=uncertain; fi
646}
647launch() {
648 need IMAGE_ARN VER_SMALL CONN_QARN; [ -f "$4" ] || die "no payload file $4"
649 intent vm "$1" "token=$2" "max=$3"
650 L_T0=$(date -u +%FT%T.%3NZ)
651 _launch_once "$@"
652 local k
653 for k in 1 2; do
654 [ "$L_OUTCOME" = uncertain ] || break
655 jw "UNCERTAIN vm $1 token=$2 (${L_CODE:-${LV_KIND:-rc$L_RC}}): replay $k with the same client token"; sleep 5
656 _launch_once "$1-replay$k" "$2" "$3" "$4"
657 done
658 if [ "$L_OUTCOME" = uncertain ] || { [ "$L_OUTCOME" = rejected ] && grep -q $'\tUNCERTAIN vm '"$1"' ' "$JOURNAL"; }; then
659 finding "launch $1 has an uncertain outcome (${L_CODE:-${LV_KIND:-rc$L_RC}}); settling every VM of the image"
660 settle_all; L_OUTCOME=settled; L_ID=""; jw "RESOLVED vm $1 by settlement"
661 fi
662 echo "launch $1: $L_OUTCOME rc=$L_RC code=${L_CODE:-none} id=${L_ID:-none}"
663}
664# eni_snapshot MODE WHEN: list the VPC's interfaces. Any outside this run's subnet is not in the ledger:
665# a hard stop, before anything is recorded. Each one inside is recorded once as SERVICE-ENI, so 10.2
666# can prove each ID gone. MODE strict makes a failed list a hard stop (10.2 needs it); soft makes it a
667# FINDING (observations during the VM phases).
668eni_snapshot() {
669 need VPC SUBNET
670 try aws ec2 describe-network-interfaces --filters Name=vpc-id,Values="$VPC" --output json
671 if [ "$RC" != 0 ]; then
672 [ "$1" = strict ] && die "interface list failed (${ECODE:-rc$RC}); 10.2 needs it"
673 finding "interface list failed ($2): ${ECODE:-rc$RC}"; return 0
674 fi
675 printf '%s' "$OUT" | jq -e '.NetworkInterfaces | type == "array"' >/dev/null || die "interface list unreadable ($2)"
676 printf '%s' "$OUT" | jq -e --arg s "$SUBNET" 'all(.NetworkInterfaces[]; .SubnetId == $s)' >/dev/null \
677 || die "an interface outside this run's subnet is in the run's VPC ($2): not in the ledger"
678 local e n=0
679 for e in $(printf '%s' "$OUT" | jq -r '.NetworkInterfaces[].NetworkInterfaceId'); do
680 n=$((n + 1)); grep -qF "SERVICE-ENI $e" "$JOURNAL" || jw "SERVICE-ENI $e"
681 done
682 jw "FACT interfaces in the VPC ($2): $n"; echo "interfaces in the VPC ($2): $n"
683}
684# harvest LOG SOURCE PHASESTART: record every MicroVM ID a log names, with the phase start as its
685# conservative start (scans add the provider's startedAt later).
686harvest() {
687 [ -f "$1" ] && [ -n "${3:-}" ] || die "harvest: no log $1 or no phase start"
688 local ids id; ids=$(grep -oE 'mvm-[0-9A-Za-z-]+' "$1" | sort -u || true)
689 for id in $ids; do vmrec "$id" "$2" "phase:$3"; done
690}
691harvest_ctl() { local t; t=$(cat "$T17/controller.start") || die "no controller start time"; harvest "$T17/controller.log" controller "$t"; }
692
693# --- the controller process ---
694ctl_pid() { [ -s "$T17/controller.pid" ] && cat "$T17/controller.pid"; }
695# ctl_alive: 0 if this run's controller process is alive; dies if the PID is alive but is something else.
696ctl_alive() {
697 local p; p=$(ctl_pid) || return 1
698 [ -d "/proc/$p" ] || return 1
699 tr '\0' ' ' < "/proc/$p/cmdline" | grep -qF "$T17/bin/controller" || die "PID $p is alive but is not this run's controller"
700}
701# listeners: sets LST to the addresses listening on 18443 or 18444 (empty if none); aborts if ss fails.
702listeners() { 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' ' '); }
703# start_ctl BINARY LABEL [VAR=VALUE...]: start in its own session; PID and exit status go to files.
704start_ctl() {
705 local bin=$1 label=$2; shift 2
706 [ -x "$bin" ] || die "no binary $bin"
707 ! ctl_alive || die "a controller is already running"
708 listeners; [ -z "$LST" ] || die "ports 18443 or 18444 are in use: $LST"
709 rm -f "$T17/controller.pid" "$T17/controller.exit"
710 date -u +%FT%T.%3NZ > "$T17/controller.start" || die "cannot write controller.start"
711 jw "CONTROLLER start $label $bin $*"
712 setsid nohup env -u EQUIPO_HOSTED_CRASH_AFTER_LAUNCH -u EQUIPO_HOSTED_ENABLED "$@" bash -c \
713 '"$0" -config "$1" >>"$2" 2>&1 & echo $! >"$3"; wait $!; echo $? >"$4"' \
714 "$bin" "$T17/controller.json" "$T17/controller.log" "$T17/controller.pid" "$T17/controller.exit" \
715 </dev/null >/dev/null 2>&1 &
716 local i; for i in $(seq 1 50); do [ -s "$T17/controller.pid" ] && break; sleep 0.1; done
717 ctl_alive || die "the controller did not start (see controller.log)"
718 echo "controller $label started, PID $(ctl_pid)"
719}
720_ctl_ready() {
721 [ -s "$T17/controller.exit" ] && return 2
722 local m; m=$(curl -fsS "http://$METRICS/metrics" 2>/dev/null) || return 1
723 printf '%s\n' "$m" | grep -q '^equipo_hosted_network_audit_passing 0$' && return 3
724 printf '%s\n' "$m" | grep -q '^equipo_hosted_network_audit_passing 1$' || return 1
725 printf '%s\n' "$m" | grep -q '^equipo_hosted_reap_last_age_seconds ' || return 1
726 printf '%s\n' "$m" | grep -q '^equipo_hosted_reap_last_error 0$' || return 4
727 return 0
728}
729# ctl_ready: within 240 s the audit has passed and a reaper pass has finished cleanly (else soft_fail);
730# listeners are 127.0.0.1 only (else a hard stop: docs-t1's binding rule).
731ctl_ready() {
732 poll 240 5 "controller ready" _ctl_ready
733 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"
734 local m; m=$(curl -fsS "http://$METRICS/metrics") || soft_fail "metrics unreadable"
735 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"
736}
737# stop_ctl: SIGTERM, then SIGKILL after 45 s if still alive; ports must close.
738stop_ctl() {
739 local i
740 if ctl_alive; then
741 jw "CONTROLLER stop $(ctl_pid)"; kill -TERM "$(ctl_pid)"
742 for i in $(seq 1 45); do ctl_alive || break; sleep 1; done
743 if ctl_alive; then jw "CONTROLLER kill $(ctl_pid)"; kill -KILL "$(ctl_pid)"; sleep 2; fi
744 ! ctl_alive || die "the controller is still alive"
745 fi
746 for i in $(seq 1 10); do [ -s "$T17/controller.exit" ] && break; sleep 1; done
747 listeners; [ -z "$LST" ] || die "a listener is still open: $LST"
748 jw "CONTROLLER exited $(cat "$T17/controller.exit" 2>/dev/null || echo unknown)"
749 echo "controller stopped; exit status $(cat "$T17/controller.exit" 2>/dev/null || echo unknown)"
750}
751metrics() { curl -fsS "http://$METRICS/metrics" | grep -E '^equipo_hosted_' || die "metrics unreadable"; }
752# dbread SQL: read a copy of the stopped controller's database.
753dbread() {
754 ! ctl_alive || die "stop the controller before reading its database"
755 rm -rf "$T17/dbcopy"; mkdir "$T17/dbcopy"; cp "$T17"/controller.db* "$T17/dbcopy/"
756 python3 -I -c 'import sqlite3,sys
757con = sqlite3.connect(sys.argv[1])
758for 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"
759}
760# gotest LOG ARGS...: run go test with output to LOG; record VM IDs it names; return its status.
761gotest() {
762 local log=$1 rc had=0 t0; shift; case $- in *e*) had=1;; esac
763 t0=$(date -u +%FT%T.%3NZ); jw "PHASE $(basename "$log") start $t0"
764 set +e; (cd "$REPO" && CGO_ENABLED=0 go test "$@") > "$log" 2>&1; rc=$?; [ "$had" = 1 ] && set -e
765 jw "PHASE $(basename "$log") end rc=$rc"
766 harvest "$log" "$(basename "$log")" "$t0"
767 grep -E '^(=== RUN|--- (PASS|FAIL|SKIP)|PASS|FAIL|ok|panic)' "$log" | tail -n 40 || true
768 return "$rc"
769}
770true
771ENVEOF
772RUN=$(date -u +%m%d)-$(openssl rand -hex 3)
773NAME=equipo-hosted-dev-t17-$RUN
774cat > "$TMPDIR/equipo-t17/run.env" <<RUNEOF
775export PIN_SHA='bdf85fb70f26094b99241de3f1285de92a76a759'
776export RUN=$RUN NAME=$NAME
777export OPERATOR_ROLE=$NAME-conn-op BUILD_ROLE=$NAME-build CONN_NAME=$NAME-egress IMAGE_NAME=$NAME
778export BUCKET=$NAME-640012953448 LOG_GROUP=/aws/lambda-microvms/$NAME TOPIC_NAME=$NAME-alerts SG_NAME=$NAME-vm
779export TAGS_EC2="Key=purpose,Value=equipo-hosted-dev Key=run,Value=$RUN"
780RUNEOF
781touch "$TMPDIR/equipo-t17/ledger.env" "$TMPDIR/equipo-t17/journal.tsv" "$TMPDIR/equipo-t17/vms.tsv"
782. "$TMPDIR/equipo-t17/env.sh"
783case "$PIN_SHA" in *'<'*) die "PIN_SHA in run.env is not filled in";; esac
784jw "RUN $RUN start pin=$PIN_SHA"
785(cd "$REPO" && CGO_ENABLED=0 go build -tags hostedlive -o "$LIVECTL" ./internal/isolatedjob/awsjob/livectl)
786[ -x "$LIVECTL" ] || die "livectl did not build"
787echo "T17=$T17 RUN=$RUN NAME=$NAME LIVECTL=$LIVECTL"
788```
789
790- The `PIN_SHA` line in `run.env` carries the same value as 0.1. livectl is built from the
791 checked-out code, which 0.1 proved is the pinned revision.
792- Expected: one line with the scratch path, the run ID and the base name. Record the `T17=` path:
793 sandboxed blocks find it through `$TMPDIR`, and the sandbox-off blocks (R37) set it from this line.
794 The environment file refuses to load if the directory is not there.
795- Abort if: the scratch directory already exists.
796
797### 0.3 First AWS call: who am I
798
799```sh
800set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"; guard
801aws sts get-caller-identity --query '[Account,Arn]' --output text
802lvr caller; must
803[ "$(jq -r '"\(.Account) \(.Region)"' <<<"$OUT")" = "640012953448 eu-west-1" ] || die "livectl sees $(jq -c . <<<"$OUT")"
804```
805
806- Expected: `640012953448` and an ARN in that account, from the CLI and from livectl.
807- Abort if: anything else. Nothing else runs.
808
809### 0.4 Observations and collision checks
810
811Every name below contains the random run ID, so a collision is not expected; each check still reads
812the exact name and must get the "does not exist" answer.
813
814```sh
815set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"; guard
816need RUN NAME OPERATOR_ROLE BUILD_ROLE CONN_NAME IMAGE_NAME BUCKET LOG_GROUP TOPIC_NAME
817try aws resourcegroupstaggingapi get-resources --tag-filters Key=purpose,Values=$TAGV --query 'ResourceTagMappingList[].ResourceARN' --output text; must
818echo "observation: resources already tagged purpose=$TAGV (not ours, never touched): [$OUT]"
819try 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"
820for r in "$OPERATOR_ROLE" "$BUILD_ROLE"; do try aws iam get-role --role-name "$r"; expect_err NoSuchEntity; done
821lvr 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)"
822lvr image list -name "$IMAGE_NAME"; must; list_items || die "malformed image list reply (collision check)"
823[ "$(jq --arg n "$IMAGE_NAME" '[.[] | select(.Name == $n)] | length' <<<"$ITEMS")" = 0 ] || die "image name $IMAGE_NAME exists"
824get _v aws s3api list-buckets --prefix "$BUCKET" --query "length(Buckets[?Name=='$BUCKET'])" --output json; [ "$_v" = 0 ] || die "bucket $BUCKET exists in this account"
825try aws logs describe-log-groups --log-group-name-prefix "$LOG_GROUP" --query 'logGroups[].logGroupName' --output text; must; [ -z "$OUT" ] || die "log group exists: $OUT"
826get _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"
827jw "COLLISION-CHECKS clean"; echo "collision checks clean"
828```
829
830- Expected: one observation line; `collision checks clean`. A collision is "anything not in the
831 ledger", a hard stop.
832- Abort if: any name exists, or a lookup fails. The image, bucket and topic checks list and match
833 the exact name (the CLI reads every page), so they need no error code. A bucket name held by
834 another account is not listed here; `create-bucket` in 3.1 then fails before anything is created,
835 which is an abort.
836
837---
838
839## 1. Network
840
841### 1.1 VPC, DNS off, and its default resources tagged
842
843```sh
844set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"; guard
845need RUN NAME TAGS_EC2
846intent vpc "tag:run=$RUN"
847try aws ec2 create-vpc --cidr-block 10.177.0.0/16 \
848 --tag-specifications "ResourceType=vpc,Tags=[{Key=purpose,Value=$TAGV},{Key=run,Value=$RUN},{Key=Name,Value=$NAME}]" --output json; must
849printf '%s\n' "$OUT" > "$T17/out/1.1-vpc.json"
850rec VPC "$(jq -r .Vpc.VpcId "$T17/out/1.1-vpc.json")"
851aws ec2 wait vpc-available --vpc-ids "$VPC"
852aws ec2 modify-vpc-attribute --vpc-id "$VPC" --enable-dns-hostnames '{"Value":false}'
853aws ec2 modify-vpc-attribute --vpc-id "$VPC" --enable-dns-support '{"Value":false}'
854fact_eq "VPC enableDnsSupport" False aws ec2 describe-vpc-attribute --vpc-id "$VPC" --attribute enableDnsSupport --query EnableDnsSupport.Value --output text
855fact_eq "VPC enableDnsHostnames" False aws ec2 describe-vpc-attribute --vpc-id "$VPC" --attribute enableDnsHostnames --query EnableDnsHostnames.Value --output text
856get DEF aws ec2 describe-security-groups --filters Name=vpc-id,Values="$VPC" Name=group-name,Values=default --query 'SecurityGroups[].GroupId' --output text
857[ "$(wc -w <<<"$DEF")" = 1 ] || die "default groups: [$DEF]"; rec DEF_SG "$DEF"
858get DEF aws ec2 describe-route-tables --filters Name=vpc-id,Values="$VPC" Name=association.main,Values=true --query 'RouteTables[].RouteTableId' --output text
859[ "$(wc -w <<<"$DEF")" = 1 ] || die "main route tables: [$DEF]"; rec MAIN_RTB "$DEF"
860get DEF aws ec2 describe-network-acls --filters Name=vpc-id,Values="$VPC" Name=default,Values=true --query 'NetworkAcls[].NetworkAclId' --output text
861[ "$(wc -w <<<"$DEF")" = 1 ] || die "default network ACLs: [$DEF]"; rec DEF_ACL "$DEF"
862get DEF aws ec2 describe-security-group-rules --filters Name=group-id,Values="$DEF_SG" --query 'SecurityGroupRules[].SecurityGroupRuleId' --output text
863[ -n "$DEF" ] || die "the default group has no rules to tag"; rec DEF_SG_RULES "$DEF"
864aws ec2 create-tags --resources "$DEF_SG" "$MAIN_RTB" "$DEF_ACL" $DEF_SG_RULES --tags $TAGS_EC2
865try 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
866if [ "$RC" != 0 ]; then finding "purpose tag read failed: ${ECODE:-rc$RC}"
867elif [ "$OUT" != $(( 4 + $(wc -w <<<"$DEF_SG_RULES") )) ]; then finding "purpose tag read back on $OUT resources"; fi
868echo "VPC $VPC: DNS support and hostnames off; defaults tagged: $DEF_SG $MAIN_RTB $DEF_ACL $DEF_SG_RULES"
869```
870
871- Expected: the last line. The defaults go with the VPC in 10.3 and are verified gone in 10.8.
872- Abort if: the create, a default-resource lookup or the tagging fails. A differing or failed
873 readback (DNS attributes, tag count) is a FINDING.
874
875### 1.2 One VM subnet
876
877```sh
878set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"; guard
879need VPC RUN NAME
880intent subnet "tag:run=$RUN"
881try aws ec2 create-subnet --vpc-id "$VPC" --cidr-block 10.177.1.0/24 --availability-zone eu-west-1a \
882 --tag-specifications "ResourceType=subnet,Tags=[{Key=purpose,Value=$TAGV},{Key=run,Value=$RUN},{Key=Name,Value=$NAME-vm}]" --output json; must
883printf '%s\n' "$OUT" > "$T17/out/1.2-subnet.json"
884rec SUBNET "$(jq -r .Subnet.SubnetId "$T17/out/1.2-subnet.json")"
885aws ec2 wait subnet-available --subnet-ids "$SUBNET"
886fact_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
887echo "subnet $SUBNET ok"
888```
889
890- Abort if: creation fails (an unsupported zone would be a stop; U10 is settled). A readback that
891 differs or fails is a FINDING.
892
893### 1.3 The subnet's own route table, local route only
894
895```sh
896set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"; guard
897need VPC SUBNET RUN NAME
898intent route-table "tag:run=$RUN"
899try aws ec2 create-route-table --vpc-id "$VPC" \
900 --tag-specifications "ResourceType=route-table,Tags=[{Key=purpose,Value=$TAGV},{Key=run,Value=$RUN},{Key=Name,Value=$NAME-vm}]" --output json; must
901printf '%s\n' "$OUT" > "$T17/out/1.3-rtb.json"
902rec RTB "$(jq -r .RouteTable.RouteTableId "$T17/out/1.3-rtb.json")"
903intent route-table-association "" "$RTB/$SUBNET"
904try aws ec2 associate-route-table --route-table-id "$RTB" --subnet-id "$SUBNET" --query AssociationId --output text; must
905rec RTB_ASSOC "$OUT"
906fact_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
907fact_eq "the subnet's route table" "$RTB" aws ec2 describe-route-tables --filters Name=association.subnet-id,Values="$SUBNET" --query 'RouteTables[].RouteTableId' --output text
908echo "route table $RTB: local route only, associated"
909```
910
911### 1.4 Security group with no rules
912
913```sh
914set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"; guard
915need VPC RUN SG_NAME
916intent security-group "$SG_NAME"
917try aws ec2 create-security-group --group-name "$SG_NAME" --description "Task 17 VM group, no rules" --vpc-id "$VPC" \
918 --tag-specifications "ResourceType=security-group,Tags=[{Key=purpose,Value=$TAGV},{Key=run,Value=$RUN},{Key=Name,Value=$SG_NAME}]" --output json; must
919printf '%s\n' "$OUT" > "$T17/out/1.4-sg.json"
920rec SG "$(jq -r .GroupId "$T17/out/1.4-sg.json")"
921aws ec2 describe-security-group-rules --filters Name=group-id,Values="$SG" --output json > "$T17/out/1.4-rules.json"
922jq -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")"
923jq -e '[.SecurityGroupRules[] | select(.IsEgress | not)] | length == 0' "$T17/out/1.4-rules.json" >/dev/null || finding "the new group has inbound rules"
924rules=$(jq -r '.SecurityGroupRules[] | select(.IsEgress) | .SecurityGroupRuleId' "$T17/out/1.4-rules.json")
925[ -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"
926get got aws ec2 describe-security-groups --group-ids "$SG" --query 'SecurityGroups[0].[length(IpPermissions),length(IpPermissionsEgress)]' --output text
927[ "$got" = "0 0" ] || finding "rules left: [$got]"
928fact_eq "VM group rule count" 0 aws ec2 describe-security-group-rules --filters Name=group-id,Values="$SG" --query 'length(SecurityGroupRules)' --output text
929echo "security group $SG: no rules"
930```
931
932---
933
934## 2. Connector
935
936### 2.1 The connector's network-interface role
937
938The trust policy is the one AWS documents for the connector operator role (Lambda Web Functions
939networking guide: `lambda.amazonaws.com`, `sts:AssumeRole`), plus `sts:TagSession`, which only lets
940Lambda tag the session it assumes. Attempts 2 and 3 showed a narrow, scoped policy is refused when
941the connector is created, even 3.3 minutes later, while the AWS-managed
942`AWSLambdaNetworkConnectorOperatorPolicy` plus an inline delete was accepted. So, for this
943throwaway dev run (Paul, 2026-11-25 and 2026-11-28), the role gets the managed policy from the
944start, plus an inline `ec2:DeleteNetworkInterface` (the managed policy has none). The delete is
945scoped as narrowly as EC2 allows before the interfaces exist: this account and region,
946network-interface resources only, only interfaces whose `ec2:ManagedResourceOperator` is the
947Lambda connector service, and only interfaces in this run's subnet. The block then waits 120 s
948for IAM propagation, the wait that preceded attempt 3's accepted call.
949
950```sh
951set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"; guard
952need SUBNET OPERATOR_ROLE RUN
953cat > "$T17/iam/lambda-trust.json" <<'TEOF'
954{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"Service":"lambda.amazonaws.com"},"Action":["sts:AssumeRole","sts:TagSession"]}]}
955TEOF
956A=arn:aws:ec2:eu-west-1:640012953448
957cat > "$T17/iam/operator-delete.json" <<TEOF
958{"Version":"2012-10-17","Statement":[
959 {"Sid":"DeleteLambdaConnectorEniOnly","Effect":"Allow","Action":"ec2:DeleteNetworkInterface","Resource":"$A:network-interface/*",
960 "Condition":{"StringEquals":{"ec2:ManagedResourceOperator":"network-connectors.lambda.amazonaws.com"},
961 "ArnEquals":{"ec2:Subnet":"$A:subnet/$SUBNET"}}}]}
962TEOF
963jq -e . "$T17/iam/operator-delete.json" >/dev/null
964intent iam-role "$OPERATOR_ROLE"
965try aws iam create-role --role-name "$OPERATOR_ROLE" --description "Task 17 connector network interfaces, run $RUN" \
966 --assume-role-policy-document "file://$T17/iam/lambda-trust.json" \
967 --tags Key=purpose,Value=$TAGV Key=run,Value=$RUN --query Role.Arn --output text; must
968arn_ok "$OUT"; rec OPERATOR_ROLE_ARN "$OUT"
969aws iam attach-role-policy --role-name "$OPERATOR_ROLE" --policy-arn arn:aws:iam::aws:policy/AWSLambdaNetworkConnectorOperatorPolicy
970rec OPERATOR_MANAGED_POLICY arn:aws:iam::aws:policy/AWSLambdaNetworkConnectorOperatorPolicy
971aws iam put-role-policy --role-name "$OPERATOR_ROLE" --policy-name t17-connector-eni-delete --policy-document "file://$T17/iam/operator-delete.json"
972rec OPERATOR_INLINE_POLICY t17-connector-eni-delete
973aws iam wait role-exists --role-name "$OPERATOR_ROLE"
974fact_json "operator inline policies" '["t17-connector-eni-delete"]' aws iam list-role-policies --role-name "$OPERATOR_ROLE" --query 'PolicyNames' --output json
975fact_json "operator managed policies" '["AWSLambdaNetworkConnectorOperatorPolicy"]' aws iam list-attached-role-policies --role-name "$OPERATOR_ROLE" --query 'AttachedPolicies[].PolicyName' --output json
976echo "waiting 120 s for IAM propagation before Lambda assumes the operator role"; sleep 120
977echo "operator role $OPERATOR_ROLE_ARN ready"
978```
979
980- Abort if: a create, attach or put call fails (2.2 needs the role).
981- The two readbacks are facts: `fact_json` compares the compacted JSON, and a difference is a
982 FINDING.
983
984### 2.2 Create the VPC_EGRESS connector for MicroVMs (once)
985
986```sh
987set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"; guard
988need SUBNET SG OPERATOR_ROLE_ARN CONN_NAME RUN
989intent connector "$CONN_NAME" "token=$CONN_NAME-1"
990lv connector create -name "$CONN_NAME" -role "$OPERATOR_ROLE_ARN" -subnet "$SUBNET" -sg "$SG" \
991 -client-token "$CONN_NAME-1" -tag purpose=$TAGV -tag run=$RUN
992if [ "$RC" != 0 ]; then
993 if [ "$ECODE" = InvalidParameterValueException ] && grep -qF 'invalid ConnectorOperatorRole permissions' <<<"$LV_MSG"; then
994 msg=$LV_MSG
995 lvr connector get -id "$CONN_NAME"
996 if [ "$RC" != 0 ] && [ "$ECODE" = ResourceNotFoundException ]; then jw "NOTCREATED connector attempt 1"; fi
997 die "the connector was refused with the managed operator policy ($msg); 2.3 onwards needs it"
998 fi
999 die "connector create: rc $RC ${ECODE:-} ${LV_MSG:-$ERR} (uncertain: S.2 reconciles it)"
1000fi
1001printf '%s\n' "$OUT" > "$T17/out/2.2-connector.json"
1002arn_ok "$(jq -r .Arn "$T17/out/2.2-connector.json")"
1003rec CONN_ARN "$(jq -r .Arn "$T17/out/2.2-connector.json")"; rec CONN_ID "$(jq -r .Id "$T17/out/2.2-connector.json")"
1004[ "$CONN_ARN" = "arn:aws:lambda:eu-west-1:$ACCOUNT:network-connector:$CONN_ID" ] || die "connector ARN has an unexpected form: $CONN_ARN"
1005rec CONN_OPERATOR_POLICY "managed AWSLambdaNetworkConnectorOperatorPolicy plus inline delete"
1006jw "FACT connector create reply: $(jq -c '{State,Version,VersionArn,LatestVersion,LatestVersionArn}' "$T17/out/2.2-connector.json")"
1007jq -c '{Arn,Id,State,Version,VersionArn}' "$T17/out/2.2-connector.json"
1008```
1009
1010- Expected: state `PENDING`. livectl sends no `ElasticIpConfiguration`, so the connector gets none;
1011 2.4 and 5.6 confirm it.
1012- Abort if: the create fails. A refusal leaves no connector (attempt 2's evidence); anything else
1013 is uncertain and S.2 reconciles it by name.
1014
1015### 2.3 Wait for ACTIVE (spike and attempt 3: about 4.5 min; bound 15 min)
1016
1017```sh
1018set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"; guard
1019need CONN_ARN
1020lv_wait 900 connector wait-active -id "$CONN_ARN" -interval 15s
1021printf '%s\n' "$OUT" > "$T17/out/2.3-active.json"
1022jq -c '{State,StateReason,StateReasonCode}' "$T17/out/2.3-active.json" 2>/dev/null || true
1023[ "$RC" = 0 ] || die "connector not ACTIVE (rc $RC, ${ECODE:-no code}); 2.4 onwards needs it"
1024jw "TIMING connector-active"
1025```
1026
1027- Abort if: a failed state (exit 6, the reply shows `StateReason`) or the bound runs out (exit 5).
1028
1029### 2.4 The version-1 qualified ARN, facts about versions, and the interfaces
1030
1031A new connector starts at version 1 (pinned SDK, `CreateNetworkConnector`). Attempt 3's discovery
1032read `<arn>:1` and got `Version` 1, ACTIVE; the unqualified read carries only `LatestVersion` and
1033`LatestVersionArn`. The launches and the 5.6 audit need the qualified ARN, so that read is a
1034requirement; the rest are facts.
1035
1036```sh
1037set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"; guard
1038need CONN_ARN CONN_ID SUBNET SG VPC
1039lvr connector get -id "$CONN_ARN:1"; must
1040printf '%s\n' "$OUT" > "$T17/out/2.4-qualified.json"
1041jq -e --arg q "$CONN_ARN:1" --arg s "$SUBNET" --arg g "$SG" '.Version == 1 and .VersionArn == $q and .State == "ACTIVE"
1042 and .Configuration.Value.SubnetIds == [$s] and .Configuration.Value.SecurityGroupIds == [$g]
1043 and .Configuration.Value.AssociatedComputeResourceTypes == ["MicroVm"]' "$T17/out/2.4-qualified.json" >/dev/null \
1044 || 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")"
1045rec CONN_VERSION 1; rec CONN_QARN "$CONN_ARN:1"
1046fact_lv "connector Elastic IP configuration" "null" '.Configuration.Value.ElasticIpConfiguration' connector get -id "$CONN_QARN"
1047lvr connector get -id "$CONN_ARN"
1048if [ "$RC" = 0 ]; then
1049 jw "FACT unqualified read: $(jq -c '{Version,VersionArn,LatestVersion,LatestVersionArn,ServerTime:.ResultMetadata.ServerTime}' <<<"$OUT")"
1050 [ "$(jq -r .LatestVersionArn <<<"$OUT")" = "$CONN_QARN" ] || finding "unqualified read: LatestVersionArn is $(jq -r .LatestVersionArn <<<"$OUT"), not $CONN_QARN"
1051else finding "unqualified connector read failed: ${ECODE:-rc$RC}"; fi
1052lvr connector list-versions -id "$CONN_ARN"
1053if [ "$RC" = 0 ] && list_items; then jw "FACT connector versions: $(jq -c '[.[] | {Version,VersionArn,State}]' <<<"$ITEMS")"
1054elif [ "$RC" = 0 ]; then finding "connector version list reply is malformed"
1055else finding "connector version list failed: ${ECODE:-rc$RC}"; fi
1056eni_snapshot soft "2.4, connector ACTIVE"
1057echo "qualified connector ARN: $CONN_QARN"
1058```
1059
1060- Expected: the version-1 read is this run's ACTIVE connector, in this subnet with this group. No
1061 Elastic IP configuration. Attempt 3 saw no interfaces while ACTIVE, which is recorded as a fact.
1062 Interfaces Lambda creates later are recorded by ID by `eni_snapshot` in 9.B, 6.1, 7.2 and 8.1
1063 (while VMs run) and in 10.2 just before the connector is deleted; 10.2 then proves each recorded ID
1064 gone. An interface outside this run's subnet is a hard stop.
1065- Abort if: the version-1 read fails or shows another connector; everything after needs it.
1066
1067---
1068
1069## 3. Image
1070
1071The API builds an image from a zip in S3 holding a `Dockerfile` and its files, on a Lambda-managed
1072base image, with a build role that can read the zip and write build logs. Memory, x86_64 and the
1073`ALL` capability are set per image version, so Small (2048 MiB) and Large (4096 MiB) are two
1074versions: create, then one update. The image is a static Go binary that answers 200 on every hook
1075path on port 9000 inside the VM; the run hook must answer, because the adapter always sends a run
1076hook payload.
1077
1078### 3.1 S3 bucket
1079
1080```sh
1081set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"; guard
1082need BUCKET RUN
1083intent s3-bucket "$BUCKET"
1084try aws s3api create-bucket --bucket "$BUCKET" --create-bucket-configuration LocationConstraint=eu-west-1 --output json; must
1085rec BUCKET_CREATED "$BUCKET"
1086aws s3api put-public-access-block --bucket "$BUCKET" --public-access-block-configuration BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true
1087aws s3api put-bucket-tagging --bucket "$BUCKET" --tagging "TagSet=[{Key=purpose,Value=$TAGV},{Key=run,Value=$RUN}]"
1088fact_eq "bucket run tag" "$RUN" aws s3api get-bucket-tagging --bucket "$BUCKET" --query "TagSet[?Key=='run'].Value" --output text
1089echo "bucket $BUCKET ok"
1090```
1091
1092### 3.2 Log group for the build
1093
1094```sh
1095set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"; guard
1096need LOG_GROUP RUN
1097intent log-group "$LOG_GROUP"
1098try aws logs create-log-group --log-group-name "$LOG_GROUP" --tags purpose=$TAGV,run=$RUN; must
1099rec LOG_GROUP_CREATED "$LOG_GROUP"
1100aws logs put-retention-policy --log-group-name "$LOG_GROUP" --retention-in-days 1
1101fact_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
1102```
1103
1104### 3.3 Build role (least privilege)
1105
1106Same trust policy as 2.1. The current getting-started page prints `sts:AssumeRole` only; Astra's
1107review cites a version with `sts:TagSession`. Granting both satisfies either. Permissions are the
1108guide's, narrowed to the one S3 key and the one log group. It is a build role only: no VM ever gets
1109an execution role (spec §3, §15).
1110
1111```sh
1112set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"; guard
1113need BUILD_ROLE BUCKET LOG_GROUP RUN
1114L="arn:aws:logs:eu-west-1:640012953448:log-group:$LOG_GROUP"
1115cat > "$T17/iam/build.json" <<EOF
1116{"Version":"2012-10-17","Statement":[
1117 {"Sid":"ReadTheCodeArtifact","Effect":"Allow","Action":"s3:GetObject","Resource":"arn:aws:s3:::$BUCKET/t17/app.zip"},
1118 {"Sid":"WriteBuildLogsToThisGroup","Effect":"Allow","Action":["logs:CreateLogGroup","logs:CreateLogStream","logs:PutLogEvents"],"Resource":["$L","$L:*"]}]}
1119EOF
1120jq -e . "$T17/iam/build.json" >/dev/null
1121intent iam-role "$BUILD_ROLE"
1122try aws iam create-role --role-name "$BUILD_ROLE" --description "Task 17 MicroVM image build, run $RUN" \
1123 --assume-role-policy-document "file://$T17/iam/lambda-trust.json" \
1124 --tags Key=purpose,Value=$TAGV Key=run,Value=$RUN --query Role.Arn --output text; must
1125arn_ok "$OUT"; rec BUILD_ROLE_ARN "$OUT"
1126aws iam put-role-policy --role-name "$BUILD_ROLE" --policy-name t17-build --policy-document "file://$T17/iam/build.json"
1127aws iam wait role-exists --role-name "$BUILD_ROLE"
1128fact_eq "build role inline policy" t17-build aws iam list-role-policies --role-name "$BUILD_ROLE" --query 'PolicyNames' --output text
1129echo "waiting 60 s for IAM propagation before Lambda assumes the build role"; sleep 60
1130```
1131
1132### 3.4 Hook binary, Dockerfile, hooks and zip (no AWS call)
1133
1134```sh
1135set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"
1136cd "$T17/image"
1137cat > hookd.go <<'EOF'
1138// hookd answers every Lambda MicroVM lifecycle hook with 200. Task 17 only.
1139package main
1140
1141import (
1142 "io"
1143 "log"
1144 "net/http"
1145)
1146
1147func main() {
1148 http.HandleFunc("/aws/lambda-microvms/runtime/v1/", func(w http.ResponseWriter, r *http.Request) {
1149 n, _ := io.Copy(io.Discard, r.Body)
1150 log.Printf("hook %s %d bytes", r.URL.Path, n)
1151 w.WriteHeader(http.StatusOK)
1152 })
1153 log.Fatal(http.ListenAndServe(":9000", nil))
1154}
1155EOF
1156cat > Dockerfile <<'EOF'
1157FROM public.ecr.aws/lambda/microvms:al2023-minimal
1158COPY hookd /usr/local/bin/hookd
1159CMD ["/usr/local/bin/hookd"]
1160EOF
1161cat > hooks.json <<'EOF'
1162{"port":9000,
1163 "microvmHooks":{"run":"ENABLED","runTimeoutInSeconds":10,"resume":"ENABLED","resumeTimeoutInSeconds":10,
1164 "suspend":"ENABLED","suspendTimeoutInSeconds":10,"terminate":"ENABLED","terminateTimeoutInSeconds":10},
1165 "microvmImageHooks":{"ready":"ENABLED","readyTimeoutInSeconds":120,"validate":"DISABLED"}}
1166EOF
1167jq -e . hooks.json >/dev/null
1168CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -trimpath -ldflags=-s -o hookd hookd.go
1169chmod 0755 hookd
1170[ "$(head -c 4 hookd | od -An -c | tr -d ' ')" = '177ELF' ] || die "hookd is not an ELF binary"
1171python3 -I -m zipfile -c app.zip Dockerfile hookd
1172[ "$(python3 -I -c 'import zipfile;print(" ".join(sorted(zipfile.ZipFile("app.zip").namelist())))')" = "Dockerfile hookd" ] || die "zip contents differ"
1173sha256sum app.zip
1174```
1175
1176### 3.5 Digest, and the upload that proves it (object tagged)
1177
1178AWS has no content digest for a MicroVM image, so the controller's allowlist key (`sha256:` and 64
1179lower-case hex digits) is the SHA-256 of the exact zip the image is built from. S3 rejects the
1180upload if the bytes do not match the checksum sent; the read-back shows S3 holds that checksum;
11813.8 shows each version names this object.
1182
1183```sh
1184set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"; guard
1185need BUCKET RUN
1186cd "$T17/image"
1187rec DIGEST "sha256:$(sha256sum app.zip | cut -d' ' -f1)"
1188B64=$(openssl dgst -sha256 -binary app.zip | base64)
1189rec ARTIFACT_B64 "$B64"
1190intent s3-object "s3://$BUCKET/t17/app.zip"
1191try aws s3api put-object --bucket "$BUCKET" --key t17/app.zip --body app.zip --checksum-algorithm SHA256 \
1192 --checksum-sha256 "$B64" --tagging "purpose=$TAGV&run=$RUN" --query ChecksumSHA256 --output text; must
1193[ "$OUT" = "$B64" ] || finding "put-object checksum [$OUT]"
1194rec ARTIFACT "s3://$BUCKET/t17/app.zip"
1195fact_eq "S3 object checksum" "$B64" aws s3api head-object --bucket "$BUCKET" --key t17/app.zip --checksum-mode ENABLED --query ChecksumSHA256 --output text
1196fact_eq "S3 object run tag" "$RUN" aws s3api get-object-tagging --bucket "$BUCKET" --key t17/app.zip --query "TagSet[?Key=='run'].Value" --output text
1197echo "artifact $ARTIFACT digest $DIGEST"
1198```
1199
1200### 3.6 Managed base image and version
1201
1202livectl reads each base version's `Status` and `SupportedCpuConfigurations` (the CLI dropped them).
1203The block picks the newest `AVAILABLE` version that supports x86_64, and records the next one down
1204for the pre-approved step down in 3.7 and 3.8.
1205
1206```sh
1207set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"; guard
1208lvr image base-versions; must
1209printf '%s\n' "$OUT" > "$T17/out/3.6-base.json"
1210list_items || die "malformed base version list reply; the image needs a base version"
1211jq -r '.[] | [.ImageVersion, .Status, ([.SupportedCpuConfigurations[]?.Architecture] | join(","))] | @tsv' <<<"$ITEMS"
1212rec BASE_ARN "$(jq -r '.BaseImage' "$T17/out/3.6-base.json")"
1213[ "$BASE_ARN" = arn:aws:lambda:eu-west-1:aws:microvm-image:al2023-1 ] || finding "base image ARN is $BASE_ARN"
1214vs=$(jq -r '[.[] | select(.Status == "AVAILABLE" and any(.SupportedCpuConfigurations[]?; .Architecture == "X86_64"))] | .[0:2][] | .ImageVersion' <<<"$ITEMS")
1215v1=$(sed -n 1p <<<"$vs"); v2=$(sed -n 2p <<<"$vs")
1216[ -n "$v1" ] || die "no AVAILABLE base version supports x86_64; the image needs one"
1217rec BASE_VER "$v1"
1218if [ -n "$v2" ]; then rec BASE_VER_DOWN "$v2"; else finding "only one AVAILABLE x86_64 base version ($v1): no step down available"; fi
1219```
1220
1221- Expected: the newest `AVAILABLE` x86_64 version, and one below it.
1222- Abort if: the list fails, or no version is both `AVAILABLE` and x86_64.
1223
1224### 3.7 Create the image: Small version
1225
1226Two pre-approved retries, each at most once:
1227
1228- **A refusal about the build role**, which was created in 3.3, gets the propagation treatment:
1229 confirm no image exists, wait 120 s, retry with the same base version. It counts only if the
1230 code is `ValidationException`, `AccessDeniedException` or `InvalidParameterValueException`; the
1231 service's message names the build role (its name or ARN) or Lambda assuming it ("build role",
1232 "assume role"); and it is not a denial of the caller ("is not authorized to perform").
1233- **Any other refusal that leaves no image** steps down once to `BASE_VER_DOWN` (Paul,
1234 2026-11-28).
1235
1236Anything else, or a third refusal, is a stop: the image is needed.
1237
1238```sh
1239set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"; guard
1240need IMAGE_NAME ARTIFACT BASE_ARN BASE_VER BUILD_ROLE_ARN BUILD_ROLE LOG_GROUP RUN
1241# create_image BASEVERSION N: one attempt with client token $IMAGE_NAME-create-N. IMG_RC=0 created;
1242# 1 a build-role refusal; 2 another refusal; both with no image left. Anything uncertain aborts.
1243create_image() {
1244 intent microvm-image "$IMAGE_NAME" "token=$IMAGE_NAME-create-$2" "base=$1"
1245 lv image create -name "$IMAGE_NAME" -description "Task 17 minimal hook image, small, run $RUN" \
1246 -artifact "$ARTIFACT" -base "$BASE_ARN" -base-version "$1" -build-role "$BUILD_ROLE_ARN" \
1247 -hooks "$T17/image/hooks.json" -log-group "$LOG_GROUP" -memory 2048 \
1248 -client-token "$IMAGE_NAME-create-$2" -tag purpose=$TAGV -tag run=$RUN
1249 if [ "$RC" = 0 ]; then IMG_RC=0; return 0; fi
1250 [ "$LV_KIND" = api ] || die "image create attempt $2: ${LV_KIND:-rc$RC} (no answer: S.2 reconciles it)"
1251 IMG_CODE=$ECODE; IMG_MSG=$LV_MSG
1252 jw "REFUSED image attempt $2 (base $1): ${IMG_CODE} ${IMG_MSG}"
1253 lvr image list -name "$IMAGE_NAME"; must; list_items || die "malformed image list reply after a refused create"
1254 [ "$(jq --arg n "$IMAGE_NAME" '[.[] | select(.Name == $n)] | length' <<<"$ITEMS")" = 0 ] || die "a refused create left an image named $IMAGE_NAME"
1255 jw "NOTCREATED image attempt $2"
1256 case "$IMG_CODE" in ValidationException|AccessDeniedException|InvalidParameterValueException) role_code=yes;; *) role_code=no;; esac
1257 if [ "$role_code" = yes ] \
1258 && { grep -qF -e "$BUILD_ROLE_ARN" -e "$BUILD_ROLE" <<<"$IMG_MSG" || grep -qiE 'build role|assume (the )?(build )?role' <<<"$IMG_MSG"; } \
1259 && ! grep -qi 'is not authorized to perform' <<<"$IMG_MSG"; then IMG_RC=1; else IMG_RC=2; fi
1260}
1261ver=$BASE_VER; n=1; waited=no; stepped=no
1262while :; do
1263 create_image "$ver" "$n"
1264 [ "$IMG_RC" = 0 ] && break
1265 if [ "$IMG_RC" = 1 ] && [ "$waited" = no ]; then waited=yes; echo "build-role refusal: waiting 120 s, then the same version"; sleep 120
1266 elif [ "$IMG_RC" = 2 ] && [ "$stepped" = no ] && [ -n "${BASE_VER_DOWN:-}" ]; then
1267 stepped=yes; finding "image create from base $ver refused (${IMG_CODE}: ${IMG_MSG}); stepping down to $BASE_VER_DOWN"; ver=$BASE_VER_DOWN
1268 else die "image create refused (attempt $n, ${IMG_CODE}: ${IMG_MSG}); no pre-approved retry is left"; fi
1269 n=$((n + 1))
1270done
1271printf '%s\n' "$OUT" > "$T17/out/3.7-image.json"
1272arn_ok "$(jq -r .ImageArn "$T17/out/3.7-image.json")"
1273rec IMAGE_ARN "$(jq -r .ImageArn "$T17/out/3.7-image.json")"; rec VER_SMALL "$(jq -r .ImageVersion "$T17/out/3.7-image.json")"
1274rec BASE_VER_USED "$ver"; [ "$stepped" = no ] || rec BASE_STEPPED_DOWN yes
1275[ "$IMAGE_ARN" = "arn:aws:lambda:eu-west-1:$ACCOUNT:microvm-image:$IMAGE_NAME" ] || die "image ARN [$IMAGE_ARN]"
1276```
1277
1278- livectl always sends x86_64 and the `ALL` capability, and no egress connectors, so the build pulls
1279 its container base image over the default build path; running VMs get only the connector.
1280
1281### 3.8 Wait for the Small version and check it (bound 50 min with the step down)
1282
1283If the Small build fails and 3.7 has not stepped down, the block builds a new Small version from
1284`BASE_VER_DOWN` by one update (pre-approved, once), and waits again.
1285
1286```sh
1287set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"; guard
1288need IMAGE_ARN IMAGE_NAME VER_SMALL ARTIFACT BASE_ARN BUILD_ROLE_ARN LOG_GROUP RUN
1289lv_wait 1200 image wait-version -id "$IMAGE_ARN" -version "$VER_SMALL" -interval 15s
1290if [ "$RC" = 6 ] && [ -z "${BASE_STEPPED_DOWN:-}" ] && [ -n "${BASE_VER_DOWN:-}" ]; then
1291 finding "Small version $VER_SMALL failed to build from base ${BASE_VER_USED}: $(jq -r '.StateReason // empty' <<<"$OUT"); stepping down to $BASE_VER_DOWN"
1292 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
1293 rec VER_SMALL_FAILED "$VER_SMALL"
1294 intent microvm-image-version "$IMAGE_NAME" "token=$IMAGE_NAME-update-small-2" "base=$BASE_VER_DOWN"
1295 lv image update -id "$IMAGE_ARN" -description "Task 17 minimal hook image, small, run $RUN, base $BASE_VER_DOWN" \
1296 -artifact "$ARTIFACT" -base "$BASE_ARN" -base-version "$BASE_VER_DOWN" -build-role "$BUILD_ROLE_ARN" \
1297 -hooks "$T17/image/hooks.json" -log-group "$LOG_GROUP" -memory 2048 -client-token "$IMAGE_NAME-update-small-2"; must
1298 rec VER_SMALL "$(jq -r .ImageVersion <<<"$OUT")"; rec BASE_VER_USED "$BASE_VER_DOWN"; rec BASE_STEPPED_DOWN yes
1299 lv_wait 1200 image wait-version -id "$IMAGE_ARN" -version "$VER_SMALL" -interval 15s
1300fi
1301if [ "$RC" != 0 ]; then
1302 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
1303 die "the Small version did not build; the image is needed"
1304fi
1305lvr image get-version -id "$IMAGE_ARN" -version "$VER_SMALL"
1306if [ "$RC" = 0 ]; then
1307 printf '%s\n' "$OUT" > "$T17/out/3.8-small.json"
1308 jq -e --arg a "$ARTIFACT" '([.CpuConfigurations[].Architecture] == ["X86_64"]) and ([.Resources[].MinimumMemoryInMiB] == [2048])
1309 and (.AdditionalOsCapabilities == ["ALL"]) and (.CodeArtifact.Value == $a) and (.Hooks.Port == 9000)' "$T17/out/3.8-small.json" >/dev/null \
1310 || finding "the Small version differs from what the adapter checks: $(jq -c '{CpuConfigurations,Resources,AdditionalOsCapabilities,CodeArtifact,Hooks}' "$T17/out/3.8-small.json")"
1311 jw "FACT Small version: $(jq -c '{ImageVersion,State,Status,Tags}' "$T17/out/3.8-small.json")"
1312else finding "Small version read failed: ${ECODE:-rc$RC}"; fi
1313jw "TIMING image-small-built"
1314```
1315
1316- Expected: `SUCCESSFUL ACTIVE`; the fields the adapter's image check reads (`checkImageVersion`)
1317 match, or each difference is a FINDING (the adapter then refuses the version, and the contract
1318 shows it).
1319- Abort if: no Small version builds, after the one step down.
1320
1321### 3.9 Large version by one update, then both versions checked
1322
1323```sh
1324set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"; guard
1325need IMAGE_ARN IMAGE_NAME ARTIFACT BASE_ARN BASE_VER_USED BUILD_ROLE_ARN LOG_GROUP VER_SMALL RUN
1326intent microvm-image-version "$IMAGE_NAME" "token=$IMAGE_NAME-update-1"
1327lv image update -id "$IMAGE_ARN" -description "Task 17 minimal hook image, large, run $RUN" \
1328 -artifact "$ARTIFACT" -base "$BASE_ARN" -base-version "$BASE_VER_USED" -build-role "$BUILD_ROLE_ARN" \
1329 -hooks "$T17/image/hooks.json" -log-group "$LOG_GROUP" -memory 4096 -client-token "$IMAGE_NAME-update-1"; must
1330printf '%s\n' "$OUT" > "$T17/out/3.9-image.json"
1331rec VER_LARGE "$(jq -r .ImageVersion "$T17/out/3.9-image.json")"
1332[ "$VER_LARGE" != "$VER_SMALL" ] || finding "the update returned the Small version $VER_SMALL"
1333lv_wait 1200 image wait-version -id "$IMAGE_ARN" -version "$VER_LARGE" -interval 15s
1334if [ "$RC" = 0 ]; then
1335 lvr image get-version -id "$IMAGE_ARN" -version "$VER_LARGE"
1336 if [ "$RC" = 0 ]; then
1337 jq -e '([.CpuConfigurations[].Architecture] == ["X86_64"]) and ([.Resources[].MinimumMemoryInMiB] == [4096]) and (.AdditionalOsCapabilities == ["ALL"])' <<<"$OUT" >/dev/null \
1338 || finding "the Large version differs: $(jq -c '{CpuConfigurations,Resources,AdditionalOsCapabilities}' <<<"$OUT")"
1339 else finding "Large version read failed: ${ECODE:-rc$RC}"; fi
1340else finding "the Large version did not build (rc $RC, ${ECODE:-}); no Large VM is ever launched, so the run goes on"; fi
1341fact_lv "Small version after the update" "SUCCESSFUL ACTIVE" '"\(.State) \(.Status)"' image get-version -id "$IMAGE_ARN" -version "$VER_SMALL"
1342lvr image get -id "$IMAGE_ARN"
1343if [ "$RC" = 0 ]; then
1344 case "$(jq -r .State <<<"$OUT")" in CREATED|UPDATED) ;; *) finding "image state $(jq -r .State <<<"$OUT")";; esac
1345 [ "$(jq -r '.Tags.run // empty' <<<"$OUT")" = "$RUN" ] || finding "image tags: $(jq -c .Tags <<<"$OUT")"
1346else finding "image read failed: ${ECODE:-rc$RC}"; fi
1347```
1348
1349- Expected: two versions, both `SUCCESSFUL ACTIVE`, 2048 and 4096 MiB; tags present. No Large VM is
1350 launched; the Large version exists so the config maps both sizes. Every difference is a FINDING.
1351- Abort if: the update call itself fails (S.2 reconciles an uncertain reply).
1352
1353---
1354
1355## 4. SNS topic
1356
1357The controller requires `sns_topic_arn` and stops at the first startup alert it cannot deliver,
1358including on the crash restart (pre-flight concern 1); the topic exists from here to 10.7.
1359
1360```sh
1361set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"; guard
1362need TOPIC_NAME RUN
1363intent sns-topic "$TOPIC_NAME"
1364try aws sns create-topic --name "$TOPIC_NAME" --tags Key=purpose,Value=$TAGV Key=run,Value=$RUN --query TopicArn --output text; must
1365[ "$OUT" = "arn:aws:sns:eu-west-1:$ACCOUNT:$TOPIC_NAME" ] || die "topic ARN [$OUT]"
1366rec TOPIC_ARN "$OUT"
1367fact_eq "topic run tag" "$RUN" aws sns list-tags-for-resource --resource-arn "$TOPIC_ARN" --query "Tags[?Key=='run'].Value" --output text
1368fact_eq "topic subscription count" 0 aws sns list-subscriptions-by-topic --topic-arn "$TOPIC_ARN" --query 'length(Subscriptions)' --output text
1369```
1370
1371- 0.4 proved the name did not exist, so `create-topic`'s idempotent return cannot be someone else's
1372 topic. No subscription is made: alerts are read from the controller's metrics and database.
1373
1374---
1375
1376## 5. Keys, config, builds, and the audit before any launch
1377
1378### 5.1 Keys and the self-signed certificate (pre-flight helper, no AWS call)
1379
1380```sh
1381set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"
1382cd "$REPO" && EQUIPO_HOSTED_KEYGEN_DIR="$T17/keys" CGO_ENABLED=0 go test -tags hostedlive ./cmd/equipo-hosted-controller -run 'TestLiveKeygen$' -count=1 -v
1383for 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
1384for f in controller.pub verify_keys.json tls.crt; do [ -s "$T17/keys/$f" ] || die "$f missing"; done
1385openssl 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"
1386jq -r '.[] | [.id, .role] | @tsv' "$T17/keys/verify_keys.json"
1387```
1388
1389- Expected: `task17-instance instance` and `task17-operator operator`.
1390
1391### 5.2 Ports free
1392
1393```sh
1394set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"
1395listeners; [ -z "$LST" ] || die "in use: $LST"; echo "ports 18443 and 18444 free"
1396```
1397
1398### 5.3 Controller config and live contract config
1399
1400```sh
1401set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"
1402need DIGEST IMAGE_ARN VER_SMALL VER_LARGE VPC SUBNET SG CONN_QARN TOPIC_ARN
1403jq -n --slurpfile vk "$T17/keys/verify_keys.json" --arg api "$API" --arg met "$METRICS" --arg d "$T17" \
1404 --arg digest "$DIGEST" --arg arn "$IMAGE_ARN" --arg small "$VER_SMALL" --arg large "$VER_LARGE" \
1405 --arg vpc "$VPC" --arg subnet "$SUBNET" --arg sg "$SG" --arg conn "$CONN_QARN" --arg topic "$TOPIC_ARN" '{
1406 listen: $api, metrics_listen: $met,
1407 tls_cert_file: ($d + "/keys/tls.crt"), tls_key_file: ($d + "/keys/tls.key"),
1408 database: ($d + "/controller.db"), signing_key_file: ($d + "/keys/controller.key"),
1409 verify_keys: $vk[0],
1410 images: [{digest: $digest, arn: $arn, versions: {small: $small, large: $large}}],
1411 region: "eu-west-1", vpc_id: $vpc, vm_subnet_id: $subnet, vm_security_group_id: $sg,
1412 connector_arn: $conn, egress: [], sns_topic_arn: $topic}' > "$T17/controller.json"
1413jq -n --arg digest "$DIGEST" --arg arn "$IMAGE_ARN" --arg small "$VER_SMALL" --arg large "$VER_LARGE" \
1414 --arg vpc "$VPC" --arg subnet "$SUBNET" --arg sg "$SG" --arg conn "$CONN_QARN" '{
1415 region: "eu-west-1", connector_id: $conn, vpc_id: $vpc, vm_subnet_id: $subnet, vm_security_group_id: $sg,
1416 image: $digest, image_arn: $arn, versions: {small: $small, large: $large}, egress: []}' > "$T17/live.json"
1417jq -e '[.. | strings] | all(. != "" and . != "null")' "$T17/controller.json" "$T17/live.json" >/dev/null || die "an empty value in a config"
1418jq -e '.egress == []' "$T17/controller.json" "$T17/live.json" >/dev/null || die "egress is not empty (R30)"
1419cat "$T17/controller.json" "$T17/live.json"
1420```
1421
1422Filled in, `controller.json` reads (angle brackets are ledger values):
1423
1424```json
1425{
1426 "listen": "127.0.0.1:18443",
1427 "metrics_listen": "127.0.0.1:18444",
1428 "tls_cert_file": "<T17>/keys/tls.crt",
1429 "tls_key_file": "<T17>/keys/tls.key",
1430 "database": "<T17>/controller.db",
1431 "signing_key_file": "<T17>/keys/controller.key",
1432 "verify_keys": [
1433 {"id": "task17-instance", "role": "instance", "public_key": "<base64>"},
1434 {"id": "task17-operator", "role": "operator", "public_key": "<base64>"}
1435 ],
1436 "images": [{"digest": "<DIGEST>", "arn": "<IMAGE_ARN>", "versions": {"small": "<VER_SMALL>", "large": "<VER_LARGE>"}}],
1437 "region": "eu-west-1",
1438 "vpc_id": "<VPC>",
1439 "vm_subnet_id": "<SUBNET>",
1440 "vm_security_group_id": "<SG>",
1441 "connector_arn": "<CONN_ARN>:<CONN_VERSION>",
1442 "egress": [],
1443 "sns_topic_arn": "<TOPIC_ARN>"
1444}
1445```
1446
1447### 5.4 Build the two controller binaries (no AWS call)
1448
1449```sh
1450set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"
1451cd "$REPO"
1452[ -z "$(git diff "$PIN_SHA" HEAD -- . ':!docs')" ] && [ -z "$(git status --porcelain --untracked-files=all -- . ':!docs')" ] || die "code changed since 0.1"
1453CGO_ENABLED=0 go build -o "$T17/bin/controller" ./cmd/equipo-hosted-controller
1454CGO_ENABLED=0 go build -tags hostedlive -o "$T17/bin/controller-crash" ./cmd/equipo-hosted-controller
1455ls -l "$T17/bin"
1456```
1457
1458- `controller` is the normal build (no crash point); `controller-crash` is used only in 7.4.
1459
1460### 5.5 Driver environment file (no AWS call)
1461
1462```sh
1463set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"
1464need DIGEST
1465cat > "$T17/driver.env" <<EOF
1466export EQUIPO_HOSTED_LIVE_URL=https://$API
1467export EQUIPO_HOSTED_LIVE_CA_FILE=$T17/keys/tls.crt
1468export EQUIPO_HOSTED_LIVE_KEY_ID=task17-instance
1469export EQUIPO_HOSTED_LIVE_KEY_FILE=$T17/keys/instance.key
1470export EQUIPO_HOSTED_LIVE_CONTROLLER_KEY_FILE=$T17/keys/controller.pub
1471export EQUIPO_HOSTED_LIVE_IMAGE=$DIGEST
1472EOF
1473cat "$T17/driver.env"
1474```
1475
1476### 5.6 Audit-only controller run: the SDK checks the network before any VM exists
1477
1478Launches stay off (no `EQUIPO_HOSTED_ENABLED`). The reaper's first passes run the network audit
1479through the SDK: VPC DNS both off, the subnet's table local-only, the group with no rules, and the
1480connector read by its qualified ARN with `VersionArn` equal to it, `ACTIVE`, `MicroVm` only, this
1481subnet and group only, and no service-managed Elastic IPs (`network.go`). This also binds the
1482database to `aws:640012953448:eu-west-1` (R28) and proves the SNS topic takes startup alerts.
1483
1484```sh
1485set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"; guard
1486ok=yes
1487start_ctl "$T17/bin/controller" audit-only
1488if (ctl_ready); then
1489 grep -F 'launches enabled: false' "$T17/controller.log" || finding "the controller did not report launches off"
1490 if grep -F 'hosted controller: network audit failed' "$T17/controller.log"; then finding "the log shows a failed network audit"; ok=no; fi
1491else finding "the audit-only controller did not become ready (see controller.log)"; ok=no; fi
1492stop_ctl
1493dbread "select action, reason from audit where action in ('provider_bound','network_audit_passed','network_audit_failed') order by id"
1494n=$(dbread "select count(*) from audit where action='network_audit_failed'"); [ "$n" = 0 ] || { finding "$n network audit failures"; ok=no; }
1495n=$(dbread "select count(*) from audit where action='network_audit_passed'"); [ "$n" -ge 1 ] || { finding "no network audit passed"; ok=no; }
1496dbread "select namespace from provider_binding" | grep -qx "aws:$ACCOUNT:eu-west-1" || finding "database not bound to aws:$ACCOUNT:eu-west-1"
1497rec AUDIT_OK "$ok"
1498[ "$ok" = yes ] && jw "AUDIT passed before any launch" || echo "the audit did not pass: sections 7 and 8 will be skipped"
1499```
1500
1501- Expected: ready within 4 minutes with `network_audit_passing 1`, and no
1502 `hosted controller: network audit failed; launches refused` line in the log; `provider_bound` and at least one
1503 `network_audit_passed` row, no failure rows; clean stop, exit status 0.
1504- If the audit does not pass, each failed check is a FINDING (the failure row names the property)
1505 and `AUDIT_OK` is `no`: sections 7 and 8, which need a ready controller, are skipped as FINDINGs;
1506 6 and 9 do not use the controller and still run.
1507
1508---
1509
1510## 6. Live contract
1511
1512Runs after 9.A to 9.F (client-token behaviour known, facts VMs settled).
1513
1514### 6.1 Run it, then settle every VM it made
1515
1516The test runs with `go test -json`, so each line of output carries the subtest it belongs to. The
1517contract runs to completion (Paul, 2026-11-28); every VM it made is settled afterwards (a hard stop
1518if one cannot be). Each failed subtest then becomes a FINDING with its own messages, labelled
1519"known" when it is one of the two failures the adapter is expected to show, from its own output
1520only.
1521
1522```sh
1523set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"; guard
1524need IMAGE_ARN
1525! ctl_alive || die "the controller is running"
1526scan >/dev/null; [ -z "$LIVE" ] || die "live VMs of this image before the contract: $LIVE"
1527export EQUIPO_HOSTED_LIVE_CONFIG="$T17/live.json"
1528J="$T17/out/6-contract.json"
1529if gotest "$J" -tags hostedlive ./internal/isolatedjob/awsjob -run TestLiveContract -count=1 -v -json -timeout 60m; then rc=0; else rc=$?; fi
1530eni_snapshot soft "6.1, after the contract"
1531settle_all
1532[ -s "$J" ] || { finding "the contract wrote no test output (rc $rc)"; exit 0; }
1533jq -R -r 'fromjson? | select(.Action == "output") | .Output' "$J" > "$T17/out/6-contract.log"
1534if 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
1535grep -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"
1536top=$(jq -R -r 'fromjson? | select(.Test == "TestLiveContract" and (.Action == "pass" or .Action == "fail")) | .Action' "$J")
1537if [ "$rc" = 0 ] && [ "$top" = pass ]; then jw "CONTRACT pass"; echo "contract PASS"; exit 0; fi
1538[ "$top" = fail ] || finding "go test ended with rc $rc outside TestLiveContract ([$top]): build error, panic or timeout"
1539fails=$(jq -R -r 'fromjson? | select(.Action == "fail" and (.Test // "" | startswith("TestLiveContract/"))) | .Test' "$J" | sort -u)
1540sub_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; }
1541for f in $fails; do
1542 msgs=$(sub_out "$f"); n=$(grep -c . <<<"$msgs" || true); label=other
1543 case "$f" in
1544 TestLiveContract/StopUnknownRef)
1545 [ "$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)";;
1546 TestLiveContract/ChangedSpecConflicts)
1547 [ "$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";;
1548 esac
1549 finding "contract $f failed [$label]: $(tr '\n' ' ' <<<"$msgs")"
1550done
1551echo "contract finished with $(wc -w <<<"$fails") failed subtests, each recorded as a FINDING"
1552```
1553
1554- Expected: `contract PASS`, and `settled: N VMs recorded` (about 7 contract VMs, each with a
1555 15-minute maximum duration). The `visibility: Get showed new VM ...` and `list lag: List showed
1556 running VM ...` lines are the measured delays (the pre-flight's 60 s and 30 s are guesses).
1557- Known failures (each still a FINDING, for an adapter fix after the run), each only with exactly
1558 one failure line in its own output: `StopUnknownRef` with a `ValidationException` for a ref AWS
1559 never issued (U11); `ChangedSpecConflicts` where AWS refused the changed request, no VM was
1560 returned, and the adapter did not map the refusal to `ErrConflict`.
1561- Hard stop only if: a VM it made cannot be settled.
1562
1563---
1564
1565## 7. Controller on docs-t1
1566
1567### 7.1 Start with launches on, check readiness
1568
1569```sh
1570set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"; guard
1571if [ "${AUDIT_OK:-}" != yes ]; then finding "section 7 skipped: the 5.6 audit did not pass"; rec SKIP_7 yes; exit 0; fi
1572scan >/dev/null; [ -z "$LIVE" ] || die "live VMs of this image: $LIVE"
1573start_ctl "$T17/bin/controller" sequence EQUIPO_HOSTED_ENABLED=1
1574if ! (ctl_ready); then finding "the controller did not become ready; section 7 skipped"; stop_ctl; rec SKIP_7 yes; exit 0; fi
1575grep -F 'launches enabled: true' "$T17/controller.log" || finding "the controller did not report launches enabled"
1576```
1577
1578### 7.2 Driver sequence: launch Small, drain, quiescent, suspend, resume, stop with proof
1579
1580```sh
1581set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"; guard
1582if [ -n "${SKIP_7:-}" ]; then echo "section 7 skipped"; exit 0; fi
1583. "$T17/driver.env"
1584ctl_alive || die "the controller is not running"
1585jw "PHASE sequence start"
1586if gotest "$T17/out/7.2-sequence.log" -tags hostedlive ./internal/hostedclient -run 'TestLiveControllerSequence$' -count=1 -v -timeout 30m; then rc=0; else rc=$?; fi
1587jw "PHASE sequence end rc=$rc"
1588grep -E 'attempt |launch:|running:|pause:|suspended:|resume:|stop:|timings:' "$T17/out/7.2-sequence.log" || true
1589eni_snapshot soft "7.2, after the sequence"
1590harvest_ctl
1591stop_ctl
1592settle_all
1593if 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
1594[ "$rc" = 0 ] || finding "TestLiveControllerSequence failed (rc $rc); see 7.2-sequence.log"
1595att=$(grep -oE 'attempt task17-[0-9a-f]+' "$T17/out/7.2-sequence.log" | head -n 1 | cut -d' ' -f2 || true)
1596if [ -n "$att" ]; then
1597 rec SEQ_ATTEMPT "$att"
1598 dbread "select attempt_id, state, vm_ref, epoch, pause_generation, stop_proof_json from jobs where attempt_id='$SEQ_ATTEMPT'"
1599 dbread "select action, reason from audit where attempt_id='$SEQ_ATTEMPT' order by id"
1600else finding "the sequence log names no attempt"; fi
1601```
1602
1603- Expected: PASS and the `timings:` line (launch call a few seconds; `to_running` up to about a
1604 minute, since states are read once per 60 s pass; resume epoch one above the launch epoch;
1605 `stop_to_proof` about 2 to 3 minutes, R17). The job row is `stopped` with stop proof; its audit
1606 rows show launch, drain, quiescent, suspend, resume and stop in order.
1607- A FAIL, a missing attempt or odd evidence is a FINDING; the controller is stopped and every VM
1608 settled either way.
1609
1610### 7.3 Crash between the provider call and transaction 2: the launch step
1611
1612```sh
1613set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"; guard
1614if [ -n "${SKIP_7:-}" ]; then echo "section 7 skipped"; exit 0; fi
1615. "$T17/driver.env"
1616rec CRASH_ATTEMPT "task17-crash-$(openssl rand -hex 4)"
1617rec CRASH_START "$(date -u +%FT%T)"
1618start_ctl "$T17/bin/controller-crash" crash EQUIPO_HOSTED_ENABLED=1 EQUIPO_HOSTED_CRASH_AFTER_LAUNCH=1
1619if ! (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
1620grep -F 'EQUIPO_HOSTED_CRASH_AFTER_LAUNCH=1' "$T17/controller.log" || finding "the crash switch is not reported on"
1621export EQUIPO_HOSTED_LIVE_ATTEMPT="$CRASH_ATTEMPT" EQUIPO_HOSTED_LIVE_CRASH_STEP=launch
1622if gotest "$T17/out/7.3-launch.log" -tags hostedlive ./internal/hostedclient -run 'TestLiveCrashRecovery$' -count=1 -v -timeout 10m; then rc=0; else rc=$?; fi
1623[ "$rc" = 0 ] || finding "the launch step failed (rc $rc); see 7.3-launch.log"
1624_exited() { [ -s "$T17/controller.exit" ] && return 0; return 1; }
1625if ! (poll 60 2 "crash-build controller exit" _exited); then finding "the crash-build controller did not exit after the launch"; fi
1626stop_ctl
1627[ "$(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"
1628harvest_ctl
1629vm=$(grep -oE "provider launched mvm-[0-9A-Za-z-]+ for $CRASH_ATTEMPT" "$T17/controller.log" | tail -n 1 | cut -d' ' -f3 || true)
1630if [ -z "$vm" ]; then finding "the crash log names no launched VM; 7.4 skipped"; rec SKIP_74 yes; settle_all; exit 0; fi
1631rec CRASH_VM "$vm"
1632vm_get "$CRASH_VM"; echo "crash VM $CRASH_VM: $VST"
1633case "$VST" in PENDING|RUNNING) ;; *) finding "crash VM state $VST";; esac
1634jw "CRASH controller exited after launching $CRASH_VM"
1635```
1636
1637- Expected: the launch fails in transport (the test passes); exit status 137; the log line
1638 `crash point: the provider launched <vm> for <attempt>; exiting before the Ref is saved`; the VM
1639 `PENDING` or `RUNNING`. A launch refused because no audit has passed recently is a FINDING, like
1640 any other failed launch step; the controller is stopped and every VM settled.
1641- The controller answering the launch, another exit status, or no launched VM is a FINDING; 7.4
1642 is then skipped if there is no VM to recover. Every VM is settled.
1643
1644### 7.4 Restart without the crash switch; Replay claims the one VM
1645
1646`start_ctl` always clears `EQUIPO_HOSTED_CRASH_AFTER_LAUNCH` and sets only what it is given
1647(pre-flight concern 3). The readiness check comes before the recovery driver; Replay runs on the
1648second reaper pass, about 60 s after start (pre-flight concern 2).
1649
1650```sh
1651set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"; guard
1652if [ -n "${SKIP_7:-}" ] || [ -n "${SKIP_74:-}" ]; then echo "7.4 skipped"; settle_all; exit 0; fi
1653. "$T17/driver.env"
1654need CRASH_ATTEMPT CRASH_VM CRASH_START
1655start_ctl "$T17/bin/controller" recover EQUIPO_HOSTED_ENABLED=1
1656if ! (ctl_ready); then finding "the restarted controller did not become ready; 7.4 skipped"; stop_ctl; settle_all; exit 0; fi
1657if 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
1658export EQUIPO_HOSTED_LIVE_ATTEMPT="$CRASH_ATTEMPT" EQUIPO_HOSTED_LIVE_CRASH_STEP=recover \
1659 EQUIPO_HOSTED_LIVE_OPERATOR_KEY_ID=task17-operator EQUIPO_HOSTED_LIVE_OPERATOR_KEY_FILE="$T17/keys/operator.key"
1660if gotest "$T17/out/7.4-recover.log" -tags hostedlive ./internal/hostedclient -run 'TestLiveCrashRecovery$' -count=1 -v -timeout 15m; then rc=0; else rc=$?; fi
1661grep -E 'recover:|listed vm|stop:' "$T17/out/7.4-recover.log" || true
1662harvest_ctl
1663stop_ctl
1664settle_all
1665[ "$rc" = 0 ] || finding "the recover step failed (rc $rc); see 7.4-recover.log"
1666grep -q "recover: job $CRASH_ATTEMPT holds vm $CRASH_VM" "$T17/out/7.4-recover.log" || finding "the job does not hold $CRASH_VM"
1667grep -F 'restart stop requested, elapsed time unknown' "$T17/controller.log" && finding "the restart stopped a job for unknown elapsed time"
1668scan >/dev/null
1669n=$(awk -F'\t' -v t="$CRASH_START" '$3 >= t' "$T17/last_scan.tsv" | wc -l)
1670awk -F'\t' -v t="$CRASH_START" '$3 >= t' "$T17/last_scan.tsv"
1671[ "$n" = 1 ] || finding "$n VMs of this image started since the crash launch, want 1"
1672dbread "select attempt_id, state, vm_ref, stop_proof_json from jobs where attempt_id='$CRASH_ATTEMPT'"
1673dbread "select action, reason from audit where attempt_id='$CRASH_ATTEMPT' order by id"
1674```
1675
1676- 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
1677 for the attempt and no unowned live VM; stop with proof; exactly one VM of this image started
1678 since 7.3 began; audit rows show the intent, the replay, the saved Ref and the stop.
1679- Each failed check is a FINDING; the controller is stopped and every VM settled.
1680
1681---
1682
1683## 8. Orphan
1684
1685### 8.1 Start the controller (launches off: reaping works regardless) and plant a VM
1686
1687```sh
1688set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"; guard
1689if [ "${AUDIT_OK:-}" != yes ]; then finding "section 8 skipped: the 5.6 audit did not pass"; rec SKIP_8 yes; exit 0; fi
1690scan >/dev/null; [ -z "$LIVE" ] || die "live VMs of this image: $LIVE"
1691start_ctl "$T17/bin/controller" orphan
1692if ! (ctl_ready); then finding "the controller did not become ready; section 8 skipped"; stop_ctl; rec SKIP_8 yes; exit 0; fi
1693if ! 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
1694printf 'orphan' > "$T17/out/payload-orphan"
1695rec ORPHAN_TOKEN "$NAME-orphan"
1696rec ORPHAN_PLANTED "$(date -u +%FT%TZ)"
1697launch orphan "$ORPHAN_TOKEN" 1800 "$T17/out/payload-orphan"
1698if [ "$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
1699rec ORPHAN_VM "$L_ID"
1700eni_snapshot soft "8.1, orphan planted"
1701```
1702
1703- Expected: a VM ID; no job or intent names its token; its 1800 s maximum duration is the backstop.
1704
1705### 8.2 Watch the reaper stop it
1706
1707Expected timeline from the plant time P: the reaper lists every 60 s, so it first sees the VM by
1708about P+1:30; it stops an orphan on the first pass at least 10 minutes after the first sighting,
1709after rechecking ownership; so the stop lands between about P+11:00 and P+12:30, and the VM ends
1710within a minute or two after that.
1711
1712```sh
1713set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"; guard
1714if [ -n "${SKIP_8:-}" ]; then echo "section 8 skipped"; exit 0; fi
1715need ORPHAN_VM ORPHAN_PLANTED
1716P=$(date -d "$ORPHAN_PLANTED" +%s)
1717while :; do
1718 now=$(date +%s)
1719 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
1720 ctl_alive || { finding "the controller stopped while watching the orphan"; vm_end "$ORPHAN_VM"; settle_all; exit 0; }
1721 vm_get "$ORPHAN_VM"
1722 echo "P+$(( (now - P) / 60 )):$(printf %02d $(( (now - P) % 60 ))) $VST"
1723 case "$VST" in
1724 TERMINATING|TERMINATED|NOTFOUND) break;;
1725 PENDING|RUNNING) ;;
1726 *) finding "orphan read: $VST";;
1727 esac
1728 sleep 20
1729done
1730[ $(( now - P )) -ge 600 ] || finding "the orphan was stopped before the 10-minute grace (P+$(( now - P ))s)"
1731jw "ORPHAN stopped by the reaper at P+$(( now - P ))s"
1732metrics | grep -E 'orphan' || true
1733metrics | grep -qE '^equipo_hosted_alerts_total\{kind="orphan_stopped",result="sent"\} 1$' || finding "no orphan_stopped alert counted as sent"
1734grep -F 'hosted controller: orphan VM stopped' "$T17/controller.log" | grep -F "$ORPHAN_VM" || finding "no orphan-stopped log line for $ORPHAN_VM"
1735if 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
1736stop_ctl
1737vm_end "$ORPHAN_VM"
1738settle_all
1739dbread "select action, reason from audit where action like 'orphan%' order by id"
1740n=$(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"
1741```
1742
1743- Expected: `RUNNING` until about P+11:00 to P+12:30; then the alert metric, the controller's log
1744 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.
1745- Hard stop: no stop seen by P+15:00, whatever the reads returned (the deadline is checked first on
1746 every iteration); the block stops the controller and ends the VM first. A stop before P+10:00 and
1747 any missing evidence are FINDINGs.
1748
1749---
1750
1751## 9. Facts to record (R7)
1752
17539.A to 9.F run before section 6, with no controller running. Every VM here comes from the `launch`
1754helper (livectl `vm run`: Small, `NO_INGRESS`, the qualified connector, a short maximum duration as
1755AWS's backstop), which journals the intent first and records any VM ID returned. Each experiment
1756ends every VM it made, confirmed, before the next one starts. A launch whose outcome is uncertain
1757is replayed under the same client token and, failing that, settled by image-scoped scans before the
1758next experiment (the `launch` helper). The expected codes are recorded as results; any other code is
1759a FINDING and the run goes on.
1760
1761### 9.A Client token: same request, then changed request
1762
1763```sh
1764set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"; guard
1765! ctl_alive || die "the controller is running"
1766scan >/dev/null; [ -z "$LIVE" ] || die "live VMs of this image: $LIVE"
1767printf 'task17-a' > "$T17/out/payload-a"; printf 'task17-b' > "$T17/out/payload-b"
1768rec TOKEN_A "$NAME-token-a"
1769rec A1_BEFORE "$(date -u +%FT%T.%3NZ)"
1770launch A1 "$TOKEN_A" 600 "$T17/out/payload-a"
1771rec A1_AFTER "$(date -u +%FT%T.%3NZ)"
1772[ "$L_RC" = 0 ] || die "A1 failed (${L_CODE:-rc$L_RC}: ${L_MSG}); every VM step needs a launch (U21: a qualified egress ARN)"
1773rec VM_A "$L_ID"
1774jw "FIRST-VM-ID $VM_A (length ${#VM_A})"; echo "first real MicroVM ID: $VM_A (length ${#VM_A})"
1775[[ "$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)"
1776launch A2 "$TOKEN_A" 600 "$T17/out/payload-a"
1777if [ "$L_OUTCOME" = settled ]; then rec A2_RESULT uncertain-settled; rec VM_A_ENDED "$(date -u +%FT%TZ)"
1778elif [ "$L_RC" = 0 ] && [ "$L_ID" = "$VM_A" ]; then rec A2_RESULT same-vm
1779elif [ "$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)"
1780else 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
1781launch A3 "$TOKEN_A" 600 "$T17/out/payload-b"
1782if [ "$L_OUTCOME" = settled ]; then rec A3_RESULT uncertain-settled; [ -n "${VM_A_ENDED:-}" ] || rec VM_A_ENDED "$(date -u +%FT%TZ)"
1783elif [ "$L_RC" != 0 ]; then
1784 rec A3_RESULT "refused:${L_CODE:-rc$L_RC}"; jw "FACT A3 message: ${L_MSG}"
1785 case "$L_CODE" in ConflictException|ValidationException) ;; *) finding "a changed request with a used token was refused with ${L_CODE:-rc$L_RC}";; esac
1786elif [ "$L_ID" = "$VM_A" ]; then rec A3_RESULT same-vm
1787else 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
1788echo "A2=$A2_RESULT A3=$A3_RESULT"
1789```
1790
1791- Expected: A1 launches (the first test that RunMicrovm takes a qualified egress ARN, U21; a refusal
1792 stops the run, since every VM step needs it). The first real MicroVM ID is recorded with its
1793 length; outside R36's form it is a FINDING (the adapter will refuse it). A2 returns `VM_A` (one
1794 attempt, one VM). A3 is refused with `ConflictException` or
1795 `ValidationException`; the exact message is recorded.
1796- A3 answered with `VM_A` (AWS ignores the body on replay) or with a new VM (ended at once) are
1797 results; a new VM, or any code other than the two above, is also a FINDING.
1798- `VM_A` stays up for 9.B to 9.D.
1799
1800### 9.B startedAt, the echoes, the Date header
1801
1802```sh
1803set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"; guard
1804need VM_A A1_BEFORE A1_AFTER CONN_QARN
1805if [ -n "${VM_A_ENDED:-}" ]; then finding "9.B skipped: VM_A has ended"; exit 0; fi
1806echo "run call: $A1_BEFORE to $A1_AFTER; reply: $(jq -c '{State,StartedAt}' "$T17/out/launch-A1.json")"
1807_running() { lvr vm get -id "$VM_A"; [ "$RC" = 0 ] || return 1
1808 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; }
1809if ! (poll 120 1 "VM_A to RUNNING" _running); then
1810 finding "VM_A did not reach RUNNING within 120 s"; vm_end "$VM_A"; rec VM_A_ENDED "$(date -u +%FT%TZ)"; exit 0
1811fi
1812lvr vm get -id "$VM_A"
1813if [ "$RC" = 0 ]; then
1814 printf '%s\n' "$OUT" > "$T17/out/9.B-get.json"
1815 eni_snapshot soft "9.B, VM_A running"
1816 jw "FACT VM_A echoes: $(jq -c '{IngressNetworkConnectors,EgressNetworkConnectors,MaximumDurationInSeconds,ExecutionRoleArn,IdlePolicy,StartedAt}' "$T17/out/9.B-get.json")"
1817 [ "$(jq -c .IngressNetworkConnectors "$T17/out/9.B-get.json")" = "[\"$NO_INGRESS\"]" ] || finding "ingress echo is $(jq -c .IngressNetworkConnectors "$T17/out/9.B-get.json")"
1818 [ "$(jq -c .EgressNetworkConnectors "$T17/out/9.B-get.json")" = "[\"$CONN_QARN\"]" ] || finding "egress echo is $(jq -c .EgressNetworkConnectors "$T17/out/9.B-get.json")"
1819 sv=$(jq -r '.ResultMetadata.ServerTime // empty' "$T17/out/9.B-get.json")
1820 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
1821else finding "VM_A read failed: ${ECODE:-rc$RC}"; fi
1822rec DATE_HEADER_list "not measured: livectl prints no metadata for lists"
1823```
1824
1825- Expected: `StartedAt` is in the PENDING reply; record how it relates to the call window and to the
1826 first RUNNING read. The ingress, egress, maximum duration, execution role and idle policy echoes
1827 are recorded as facts (Paul, 2026-11-28); an ingress or egress echo other than what was sent is a
1828 FINDING. The Date header is livectl's `ResultMetadata.ServerTime` for GetMicrovm; livectl prints
1829 no metadata for lists, so the List header is recorded as not measured.
1830
1831### 9.C Resume on RUNNING; suspend on SUSPENDED; a second resume
1832
1833```sh
1834set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"; guard
1835need VM_A
1836if [ -n "${VM_A_ENDED:-}" ]; then finding "9.C skipped: VM_A has ended"; exit 0; fi
1837r() { lv vm "$1" -id "$VM_A"; echo "$1: rc=$RC code=${ECODE:-none} ${LV_MSG}"; }
1838res() { if [ "$RC" = 0 ]; then echo accepted; elif [ "$ECODE" = ConflictException ]; then echo ConflictException; else echo "other:${ECODE:-rc$RC}"; fi; }
1839r resume; rec RESUME_ON_RUNNING "$(res)"
1840case "$RESUME_ON_RUNNING" in other:*) finding "resume on RUNNING: $RESUME_ON_RUNNING ${LV_MSG}";; esac
1841rec SUSPEND_AT "$(date -u +%FT%T.%3NZ)"; r suspend
1842if [ "$RC" = 0 ] && (vm_wait "$VM_A" SUSPENDED 180 RUNNING SUSPENDING); then
1843 r suspend; rec SUSPEND_ON_SUSPENDED "$(res)"
1844 case "$SUSPEND_ON_SUSPENDED" in other:*) finding "suspend on SUSPENDED: $SUSPEND_ON_SUSPENDED";; esac
1845 rec RESUME_AT "$(date -u +%FT%T.%3NZ)"; r resume
1846 [ "$RC" = 0 ] || finding "resume of a SUSPENDED VM: ${ECODE:-rc$RC} ${LV_MSG}"
1847 vm_get "$VM_A"; before=$VST
1848 r resume
1849 case "$before" in SUSPENDED) when=during-first-resume;; RUNNING) when=after-first-resume;; *) when="unknown:$before";; esac
1850 rec SECOND_RESUME "$(res):$when"
1851 case "$SECOND_RESUME" in other:*) finding "second resume: $SECOND_RESUME";; esac
1852else finding "suspend of VM_A failed or it did not reach SUSPENDED (rc $RC ${ECODE:-})"; fi
1853if ! (vm_wait "$VM_A" RUNNING 180 SUSPENDED SUSPENDING); then
1854 finding "VM_A is not RUNNING after 9.C; ending it"; vm_end "$VM_A"; rec VM_A_ENDED "$(date -u +%FT%TZ)"
1855fi
1856echo "resume-on-running=$RESUME_ON_RUNNING suspend-on-suspended=${SUSPEND_ON_SUSPENDED:-not run} second-resume=${SECOND_RESUME:-not run}"
1857```
1858
1859- Expected: resume on RUNNING is a `ConflictException` (R4; if accepted, the adapter's mapping is
1860 untested and 6.1's `ResumeRunningIsNoop` result decides). Suspend reaches SUSPENDED in about 2 to
1861 4 s. The second resume's label says which state the VM was in just before it, measured by a Get;
1862 with a 200-returning hook the first resume may already be done, so "after-first-resume" is the
1863 likely label and the in-progress case may stay unmeasured.
1864
1865### 9.D Payload limit (ASCII)
1866
1867```sh
1868set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"; guard
1869probe() { local n=$1
1870 head -c "$n" /dev/zero | tr '\0' x > "$T17/out/payload-$n"; [ "$(wc -c < "$T17/out/payload-$n")" = "$n" ] || die "payload file size"
1871 launch "P$n" "$NAME-p$n" 120 "$T17/out/payload-$n"
1872 if [ "$L_OUTCOME" = settled ]; then rec "PAYLOAD_$n" uncertain-settled
1873 elif [ "$L_RC" = 0 ]; then vm_end "$L_ID"; rec "PAYLOAD_$n" accepted
1874 elif [ "$L_CODE" = ValidationException ]; then rec "PAYLOAD_$n" "refused:ValidationException"; jw "FACT payload $n message: ${L_MSG}"
1875 else rec "PAYLOAD_$n" "refused:${L_CODE:-rc$L_RC}"; finding "payload $n refused with ${L_CODE:-rc$L_RC}: ${L_MSG}"; fi; }
1876probe 4096; probe 4097
1877if [ "$PAYLOAD_4097" = accepted ]; then probe 16384; probe 16385; fi
1878echo "4096=$PAYLOAD_4096 4097=$PAYLOAD_4097 16384=${PAYLOAD_16384:-not run} 16385=${PAYLOAD_16385:-not run}"
1879```
1880
1881- Expected: 4096 accepted (ended at once); 4097 refused with a `ValidationException`. If 4097 is
1882 accepted, 16384 and 16385 are probed (the guide says 16 KB). These are ASCII payloads: they
1883 establish an ASCII boundary only, not whether AWS counts bytes or characters in general.
1884
1885### 9.E End VM_A, then replay its token
1886
1887```sh
1888set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"; guard
1889need VM_A TOKEN_A
1890vm_end "$VM_A"; [ -n "${VM_A_ENDED:-}" ] || rec VM_A_ENDED "$(date -u +%FT%TZ)"
1891lvr vm terminate -id "$VM_A"
1892if [ "$RC" = 0 ]; then rec TERMINATE_AGAIN ok; elif [ "$ECODE" = ResourceNotFoundException ]; then rec TERMINATE_AGAIN ResourceNotFoundException
1893else rec TERMINATE_AGAIN "other:${ECODE:-rc$RC}"; finding "terminate of an ended VM: ${ECODE:-rc$RC} ${LV_MSG}"; fi
1894launch E1 "$TOKEN_A" 600 "$T17/out/payload-a"
1895if [ "$L_OUTCOME" = settled ]; then rec E1_RESULT uncertain-settled
1896elif [ "$L_RC" = 0 ] && [ "$L_ID" = "$VM_A" ]; then rec E1_RESULT same-ended-vm
1897elif [ "$L_RC" = 0 ]; then vm_end "$L_ID"; rec E1_RESULT "new-vm:$L_ID"
1898else rec E1_RESULT "refused:${L_CODE:-rc$L_RC}"
1899 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
1900settle_all
1901echo "E1=$E1_RESULT"
1902```
1903
1904- Expected: both terminates succeed (documented idempotent). The replay of the original token and
1905 request after the VM ended returns the ended VM, a new VM (ended at once), or one of the listed
1906 errors; recorded. Then every facts VM is settled.
1907
1908### 9.F TERMINATED visibility (run at the end of 9.E, after 6.1, 7.4, 8.2 and before 10.1)
1909
1910```sh
1911set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"; guard
1912need VM_A VM_A_ENDED IMAGE_ARN
1913vm_get "$VM_A"; jw "VISIBILITY VM_A $VST since $VM_A_ENDED"; echo "$(date -u +%T) VM_A get: $VST (ended $VM_A_ENDED)"
1914scan >/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"
1915```
1916
1917- Expected: at each checkpoint, record whether Get still answers TERMINATED or not found, and
1918 whether List still shows `VM_A`. The last sighting and the first miss bound the visibility window.
1919
1920### 9.G Final token replay (after section 8)
1921
1922```sh
1923set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"; guard
1924need TOKEN_A VM_A A1_BEFORE
1925! ctl_alive || die "the controller is running"
1926launch G1 "$TOKEN_A" 600 "$T17/out/payload-a"
1927if [ "$L_OUTCOME" = settled ]; then rec G1_RESULT uncertain-settled
1928elif [ "$L_RC" = 0 ] && [ "$L_ID" = "$VM_A" ]; then rec G1_RESULT same-ended-vm
1929elif [ "$L_RC" = 0 ]; then vm_end "$L_ID"; rec G1_RESULT "new-vm:$L_ID"
1930else rec G1_RESULT "refused:${L_CODE:-rc$L_RC}"
1931 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
1932settle_all
1933echo "G1=$G1_RESULT, $(( ( $(date +%s) - $(date -d "$A1_BEFORE" +%s) ) / 60 )) minutes after the token's first use"
1934```
1935
1936- Expected: a result 3 to 4 hours after first use; `same-ended-vm` means the token window is at
1937 least that long. Then run 9.F once more.
1938
1939**R7 record** (one line each in the progress file): A2, A3 (with message), E1, G1 (with minutes);
1940the Date header on Get (and List: not measured); startedAt in PENDING and its relation to the
1941call and to RUNNING; resume on RUNNING; suspend on SUSPENDED; second resume with its label; payload
1942results (ASCII); the NO_INGRESS literal as echoed; TERMINATED visibility bounds; contract visibility
1943and List lag.
1944
1945---
1946
1947## 10. Teardown and verification
1948
1949Runs after 9.G, or on Paul's word after a safe stop. Dependency order. Each deletion is confirmed by
1950a direct read before the next dependency is touched, and recorded with `deleted`.
1951
1952### 10.1 No controller, no VM, then the image (all its versions)
1953
1954```sh
1955set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"; guard
1956stop_ctl
1957if have IMAGE_ARN; then
1958settle_all
1959lvr image delete -id "$IMAGE_ARN"
1960[ "$RC" = 0 ] || die "image delete: ${ECODE:-rc$RC} ${LV_MSG:-$ERR} (a ConflictException is a stop: U8)"
1961_img() { lvr image list -name "$IMAGE_NAME"; [ "$RC" = 0 ] || return 1
1962 list_items || die "malformed image list reply while proving the image deleted"
1963 OUT=$(jq -r --arg a "$IMAGE_ARN" '[.[] | select(.ImageArn == $a) | .State] | join(" ")' <<<"$ITEMS") || die "image list items unreadable"
1964 echo "$(date -u +%T) listed state: [${OUT}]"; case "$OUT" in ""|DELETED) return 0;; DELETING) return 1;; esac; return 2; }
1965poll 900 15 "image deleted" _img
1966deleted microvm-image "$IMAGE_ARN"
1967for vv in VER_SMALL_FAILED VER_SMALL VER_LARGE; do
1968 [ -n "${!vv:-}" ] || continue; v=${!vv}
1969 lvr image get-version -id "$IMAGE_ARN" -version "$v"
1970 if { [ "$RC" = 0 ] && [ "$(jq -r .State <<<"$OUT")" = DELETED ]; } || { [ "$RC" != 0 ] && [ "$ECODE" = ResourceNotFoundException ]; }; then
1971 deleted microvm-image-version "$IMAGE_ARN:$v"
1972 else finding "version $v after the image delete: rc $RC ${ECODE:-} $(jq -r '.State // empty' <<<"$OUT" 2>/dev/null || true)"; fi
1973done
1974fi
1975```
1976
1977### 10.2 Connector, then its network interfaces
1978
1979```sh
1980set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"; guard
1981if have CONN_ARN; then
1982need VPC SUBNET OPERATOR_ROLE
1983eni_snapshot strict "10.2, before the connector delete"
1984B_END=$(( $(date +%s) + 7200 ))
1985# budget N: N seconds, or what is left of 10.2's shared 120-minute budget if that is less.
1986budget() { 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 )); }
1987conn_delete() { lvr connector delete -id "$CONN_ARN"
1988 [ "$RC" = 0 ] || [ "$ECODE" = ResourceNotFoundException ] || die "connector delete: ${ECODE:-rc$RC} ${LV_MSG:-$ERR}"; }
1989conn_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
1990 echo "wait-gone: rc $CG_RC ${CG_CODE:-} $(jq -c '{State,StateReason}' <<<"$OUT" 2>/dev/null || true)"; }
1991# enis_gone SECONDS: 0 when no interface is left in the VPC within SECONDS; 1 when some are left at the bound.
1992enis_gone() { local end=$(( $(date +%s) + $1 ))
1993 while :; do
1994 try aws ec2 describe-network-interfaces --filters Name=vpc-id,Values="$VPC" --query 'length(NetworkInterfaces)' --output json
1995 [ "$RC" = 0 ] || die "interface count unreadable: ${ECODE:-rc$RC}"
1996 echo "$(date -u +%T) interfaces in VPC: $OUT"; [ "$OUT" = 0 ] && return 0
1997 [ "$(date +%s)" -lt "$end" ] || return 1
1998 sleep 30
1999 done; }
2000conn_delete; conn_gone; ok=no
2001if [ "$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
2002elif [ "$CG_RC" = 6 ] && [ "$CG_CODE" = DELETE_FAILED ]; then :
2003else die "connector wait-gone: rc $CG_RC ${CG_CODE:-}"; fi
2004if [ "$ok" = no ]; then
2005 finding "connector teardown needs the pre-approved fallback (wait-gone rc $CG_RC ${CG_CODE:-}, or interfaces left after 40 min)"
2006 have OPERATOR_ROLE_ARN || die "no operator role to change"
2007 A=arn:aws:ec2:eu-west-1:640012953448
2008 cat > "$T17/iam/operator-delete-subnet.json" <<TEOF
2009{"Version":"2012-10-17","Statement":[
2010 {"Sid":"DeleteEniInThisSubnet","Effect":"Allow","Action":"ec2:DeleteNetworkInterface","Resource":"$A:network-interface/*",
2011 "Condition":{"ArnEquals":{"ec2:Subnet":"$A:subnet/$SUBNET"}}}]}
2012TEOF
2013 jq -e . "$T17/iam/operator-delete-subnet.json" >/dev/null
2014 aws iam put-role-policy --role-name "$OPERATOR_ROLE" --policy-name t17-connector-eni-delete --policy-document "file://$T17/iam/operator-delete-subnet.json"
2015 rec OPERATOR_DELETE_FALLBACK "subnet condition only (Paul, 2026-11-28)"
2016 echo "waiting 120 s for IAM propagation, then one more connector delete"; sleep 120
2017 conn_delete; conn_gone
2018 [ "$CG_RC" = 0 ] || die "the connector delete failed again after the fallback (rc $CG_RC ${CG_CODE:-}): hard stop"
2019 grep -q $'\tDELETED connector '"$CONN_ARN"'$' "$JOURNAL" || deleted connector "$CONN_ARN"
2020 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"
2021fi
2022for e in $(awk -F'\t' '$2 ~ /^SERVICE-ENI / {split($2, a, " "); print a[2]}' "$JOURNAL"); do
2023 gone0 "interface $e" aws ec2 describe-network-interfaces --filters Name=network-interface-id,Values="$e" --query 'length(NetworkInterfaces)' --output json
2024 deleted service-eni "$e"
2025done
2026fi
2027```
2028
2029- Pre-approved fallback (Paul, 2026-11-28): on `DELETE_FAILED`, or interfaces left after 40
2030 minutes, the inline delete policy loses its `ec2:ManagedResourceOperator` condition (the subnet
2031 condition stays), and after 120 s the connector delete is retried once. A second failure, or
2032 interfaces still left, is a hard stop. Lambda's interfaces are never deleted by hand.
2033- One shared budget of 120 minutes covers the attempt and its fallback: each wait takes at most its
2034 own 40-minute bound and never more than what is left of the 120 minutes; when it is spent, that is
2035 a hard stop. The detached-block limit for 10.2 alone is 130 minutes, so the wrapper never cuts the
2036 pre-approved fallback short.
2037
2038### 10.3 Network
2039
2040```sh
2041set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"; guard
2042if have SG; then
2043 get _v aws ec2 delete-security-group --group-id "$SG" --query Return --output text; [ "$_v" = True ] || die "delete group"
2044 gone0 "group $SG" aws ec2 describe-security-groups --filters Name=group-id,Values="$SG" --query 'length(SecurityGroups)' --output json; deleted security-group "$SG"
2045fi
2046if have RTB_ASSOC; then aws ec2 disassociate-route-table --association-id "$RTB_ASSOC"; deleted route-table-association "$RTB_ASSOC"; fi
2047if have RTB; then
2048 aws ec2 delete-route-table --route-table-id "$RTB"
2049 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"
2050fi
2051if have SUBNET; then
2052 aws ec2 delete-subnet --subnet-id "$SUBNET"
2053 gone0 "subnet $SUBNET" aws ec2 describe-subnets --filters Name=subnet-id,Values="$SUBNET" --query 'length(Subnets)' --output json; deleted subnet "$SUBNET"
2054fi
2055if have VPC; then
2056 aws ec2 delete-vpc --vpc-id "$VPC"
2057 gone0 "VPC $VPC" aws ec2 describe-vpcs --filters Name=vpc-id,Values="$VPC" --query 'length(Vpcs)' --output json; deleted vpc "$VPC"
2058 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
2059 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
2060 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
2061 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
2062fi
2063```
2064
2065- Abort if: a `DependencyViolation`, a failed read, or a filtered `describe` that still lists the
2066 resource.
2067
2068### 10.4 IAM roles
2069
2070The operator role holds the managed attachment and the inline delete policy (2.1; 10.2's fallback
2071rewrites the same policy name). The old narrow policy name is still tried, so a role left by an
2072earlier revision is cleaned too. Each is removed if present; `NoSuchEntity` means it was never
2073added.
2074
2075```sh
2076set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"; guard
2077need OPERATOR_ROLE BUILD_ROLE
2078if have OPERATOR_ROLE_ARN; then
2079 for pn in t17-connector-eni t17-connector-eni-delete; do
2080 try aws iam delete-role-policy --role-name "$OPERATOR_ROLE" --policy-name "$pn"; [ "$RC" = 0 ] || expect_err NoSuchEntity
2081 done
2082 try aws iam detach-role-policy --role-name "$OPERATOR_ROLE" --policy-arn arn:aws:iam::aws:policy/AWSLambdaNetworkConnectorOperatorPolicy; [ "$RC" = 0 ] || expect_err NoSuchEntity
2083 aws iam delete-role --role-name "$OPERATOR_ROLE"
2084 try aws iam get-role --role-name "$OPERATOR_ROLE"; expect_err NoSuchEntity; deleted iam-role "$OPERATOR_ROLE_ARN"
2085 if [ -n "${OPERATOR_INLINE_POLICY:-}" ]; then deleted iam-inline-policy "$OPERATOR_INLINE_POLICY"; fi
2086 if [ -n "${OPERATOR_MANAGED_POLICY:-}" ]; then deleted iam-managed-attachment "$OPERATOR_MANAGED_POLICY"; fi
2087fi
2088if have BUILD_ROLE_ARN; then
2089 try aws iam delete-role-policy --role-name "$BUILD_ROLE" --policy-name t17-build; [ "$RC" = 0 ] || expect_err NoSuchEntity
2090 aws iam delete-role --role-name "$BUILD_ROLE"
2091 try aws iam get-role --role-name "$BUILD_ROLE"; expect_err NoSuchEntity; deleted iam-role "$BUILD_ROLE_ARN"
2092fi
2093```
2094
2095### 10.5 S3
2096
2097```sh
2098set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"; guard
2099need BUCKET
2100if have BUCKET_CREATED; then
2101if have ARTIFACT; then
2102aws s3api delete-object --bucket "$BUCKET" --key t17/app.zip
2103gone0 "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"
2104fi
2105get _v aws s3api list-object-versions --bucket "$BUCKET" --output json
2106[ "$(jq '((.Versions // []) + (.DeleteMarkers // [])) | length' <<<"$_v")" = 0 ] || die "objects left in the bucket"
2107aws s3api delete-bucket --bucket "$BUCKET"
2108_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; }
2109poll 300 10 "bucket gone from the list" _bucket; deleted s3-bucket "$BUCKET"
2110fi
2111```
2112
2113### 10.6 Log group
2114
2115```sh
2116set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"; guard
2117need LOG_GROUP
2118if have LOG_GROUP_CREATED; then
2119get got aws logs describe-log-groups --log-group-name-prefix "$LOG_GROUP" --query 'logGroups[].logGroupName' --output text
2120[ "$got" = "$LOG_GROUP" ] || die "log groups under the prefix: [$got]; any group the run did not create goes to Paul"
2121aws logs delete-log-group --log-group-name "$LOG_GROUP"
2122get got aws logs describe-log-groups --log-group-name-prefix "$LOG_GROUP" --query 'logGroups[].logGroupName' --output text
2123[ -z "$got" ] || die "log group still listed: [$got]"
2124deleted log-group "$LOG_GROUP"
2125fi
2126```
2127
2128### 10.7 SNS topic
2129
2130```sh
2131set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"; guard
2132if have TOPIC_ARN; then
2133aws sns delete-topic --topic-arn "$TOPIC_ARN"
2134_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; }
2135poll 300 10 "topic gone from the list" _topic; deleted sns-topic "$TOPIC_ARN"
2136fi
2137```
2138
2139### 10.8 Verify: every record classified, then the tag index as a cross-check
2140
2141```sh
2142set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"; guard
2143need RUN
2144echo "== confirmed creations without a confirmed deletion:"
2145awk -F'\t' '
2146 $2 ~ /^DELETED / {split($2, a, " "); d[substr($2, length("DELETED " a[2] " ") + 1)] = 1}
2147 $2 ~ /^CONFIRMED / {split($2, a, " "); c[substr($2, length("CONFIRMED " a[2] " ") + 1)] = a[2]}
2148 END {for (k in c) if (!(k in d)) print c[k], k}' "$JOURNAL" | sort
2149echo "== VMs: recorded, and how each ended:"
2150vm_ids
2151for id in $VIDS; do grep -q "VMGONE $id " "$JOURNAL" || die "VM $id has no confirmed end"; done
2152echo "$(wc -w <<<"$VIDS") VMs recorded, every one confirmed ended"
2153echo "== intents without a confirmation:"
2154awk -F'\t' '$2 ~ /^INTENT /' "$JOURNAL"
2155echo "== tag index (lags; direct reads above decide):"
2156for k in run purpose; do v=$([ "$k" = run ] && echo "$RUN" || echo "$TAGV")
2157 aws resourcegroupstaggingapi get-resources --tag-filters Key=$k,Values=$v --query 'ResourceTagMappingList[].ResourceARN' --output text | tr '\t' '\n'; done
2158```
2159
2160- Expected: the first list holds only values that are not resources (the run's settings: `DIGEST`,
2161 `VER_*`, `CONN_VERSION`, `CONN_QARN`, `BASE_*`, tokens, times, results); every resource ID has a
2162 `DELETED` line. Every recorded VM has a confirmed end. Each intent has its confirmation (or, for
2163 `vm` intents, a VM ID or a recorded refusal). The tag index lists nothing with `run=<RUN>`, or
2164 only ARNs already confirmed deleted above ("index lag"); with `purpose`, only what 0.4 already
2165 observed. An ARN that is neither goes to Paul untouched.
2166
2167### 10.9 Evidence into the progress file, then remove scratch
2168
2169```sh
2170set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"
2171! ctl_alive || die "the controller is running"; listeners; [ -z "$LST" ] || die "listeners open: $LST"
2172no_unresolved
2173cut -f2- "$JOURNAL" | grep -vE '^(INTENT|CONTROLLER) ' > "$T17/journal-for-progress.txt"
2174wc -l "$T17/journal-for-progress.txt" "$VMS"
2175echo "== every FINDING (the report lists each one):"
2176awk -F'\t' '$2 ~ /^FINDING / {print $1, substr($2, 9)}' "$JOURNAL" | tee "$T17/findings.txt"
2177```
2178
2179Paste `journal-for-progress.txt`, `vms.tsv`, the R7 lines and section 11.2's estimate into
2180`HOSTED-SLICE1-PROGRESS.md` (they hold IDs, times and results only, no keys), then:
2181
2182```sh
2183set -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"
2184```
2185
2186---
2187
2188## S. Safe stop
2189
2190Run in this order after any abort. Each part is safe to run whatever phase the run reached.
2191
2192**S.1 Controller.**
2193
2194```sh
2195set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"
2196stop_ctl
2197```
2198
2199If `stop_ctl` aborts because the PID belongs to another process, or a port stays open while `/proc`
2200hides the process, stop here and ask Paul: nothing is signalled that is not proven to be this run's
2201controller.
2202
2203**S.2 Reconcile uncertain creations (R39).** For each creation whose `INTENT` has no `CONFIRMED`
2204record, one direct, guarded read decides. A resource created with a run-unique name (the run ID,
2205proved absent by 0.4) and found by that exact name is ours: it is recorded, tagged if a separate
2206tagging call never ran, and torn down. The unnamed EC2 resources carried their tags in the create
2207call (`TagSpecifications`) and are found by a direct `describe` filtered on the `run` tag and their
2208`Name` tag, never through the tag index. Each read has exactly three outcomes: success (record),
2209an empty list or an approved not-found code (`NOTCREATED`), or anything else (`UNRESOLVED`: that resource's
2210reconciliation stops and it goes to Paul with its cost in S.4). The MicroVM intents are reconciled
2211by S.3.
2212
2213```sh
2214set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"; guard
2215need RUN NAME SG_NAME OPERATOR_ROLE BUILD_ROLE CONN_NAME IMAGE_NAME BUCKET LOG_GROUP TOPIC_NAME TAGS_EC2
2216UNRES=""
2217unresolved() { jw "UNRESOLVED $*"; UNRES="$UNRES|$*"; echo "UNRESOLVED: $*"; }
2218absent() { jw "NOTCREATED $*"; echo "not created: $*"; }
2219pending() { awk -F'\t' -v k="INTENT $1 $2" 'index($2, k) == 1 {f = 1} END {exit !f}' "$JOURNAL" && [ -z "${!3:-}" ]; }
2220# one_ec2 KIND VAR CMD...: a describe that must list 0 or 1 IDs.
2221one_ec2() { local kind=$1 var=$2; shift 2; try "$@"
2222 if [ "$RC" != 0 ]; then unresolved "$kind lookup failed: ${ECODE:-rc$RC}"; return; fi
2223 case "$(wc -w <<<"$OUT")" in 0) absent "$kind";; 1) rec "$var" "$OUT";; *) unresolved "$kind: several match: $OUT";; esac; }
2224# one_def KIND VAR CMD...: a VPC default resource; it exists whenever the VPC does, so only exactly one is an answer.
2225one_def() { local kind=$1 var=$2; shift 2; try "$@"
2226 if [ "$RC" = 0 ] && [ "$(wc -w <<<"$OUT")" = 1 ]; then rec "$var" "$OUT"; else unresolved "$kind: rc $RC ${ECODE:-} [$OUT]"; fi; }
2227
2228if 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
2229if [ -n "${VPC:-}" ] && [ -z "${DEF_SG_RULES:-}" ]; then
2230 [ -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
2231 [ -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
2232 [ -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
2233 if [ -n "${DEF_SG:-}" ] && [ -n "${MAIN_RTB:-}" ] && [ -n "${DEF_ACL:-}" ]; then
2234 try aws ec2 describe-security-group-rules --filters Name=group-id,Values="$DEF_SG" --query 'SecurityGroupRules[].SecurityGroupRuleId' --output text
2235 if [ "$RC" = 0 ] && [ -n "$OUT" ]; then rec DEF_SG_RULES "$OUT"
2236 try aws ec2 create-tags --resources "$DEF_SG" "$MAIN_RTB" "$DEF_ACL" $DEF_SG_RULES --tags $TAGS_EC2
2237 [ "$RC" = 0 ] || unresolved "vpc defaults: tagging failed: ${ECODE:-rc$RC}"
2238 else unresolved "vpc default security group rules: ${ECODE:-rc$RC}"; fi
2239 fi
2240fi
2241if 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
2242if 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
2243if pending route-table-association "" RTB_ASSOC && [ -n "${RTB:-}" ] && [ -n "${SUBNET:-}" ]; then
2244 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
2245if 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
2246for pair in "$OPERATOR_ROLE:OPERATOR_ROLE_ARN" "$BUILD_ROLE:BUILD_ROLE_ARN"; do
2247 r=${pair%%:*}; v=${pair#*:}
2248 pending iam-role "$r" "$v" || continue
2249 try aws iam get-role --role-name "$r" --output json
2250 if [ "$RC" = 0 ]; then arn=$(jq -r .Role.Arn <<<"$OUT"); arn_ok "$arn"; rec "$v" "$arn"
2251 if ! jq -e --arg r "$RUN" 'any(.Role.Tags[]?; .Key == "run" and .Value == $r)' <<<"$OUT" >/dev/null; then
2252 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
2253 elif code_in NoSuchEntity; then absent "iam-role $r"
2254 else unresolved "iam-role $r: ${ECODE:-rc$RC}"; fi
2255done
2256if pending connector "$CONN_NAME" CONN_ARN; then
2257 lvr connector get -id "$CONN_NAME"
2258 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")"
2259 elif code_in ResourceNotFoundException; then absent "connector $CONN_NAME"
2260 else unresolved "connector $CONN_NAME: ${ECODE:-rc$RC}"; fi
2261fi
2262if pending s3-bucket "$BUCKET" BUCKET_CREATED; then
2263 try aws s3api list-buckets --prefix "$BUCKET" --query "length(Buckets[?Name=='$BUCKET'])" --output json
2264 if [ "$RC" != 0 ]; then unresolved "s3-bucket $BUCKET: list failed: ${ECODE:-rc$RC}"
2265 elif [ "$OUT" = 1 ]; then rec BUCKET_CREATED "$BUCKET"
2266 try aws s3api get-bucket-tagging --bucket "$BUCKET" --query "TagSet[?Key=='run'].Value" --output text
2267 if [ "$RC" = 0 ] && [ "$OUT" = "$RUN" ]; then :
2268 elif [ "$RC" = 0 ] || code_in NoSuchTagSet; then
2269 try aws s3api put-public-access-block --bucket "$BUCKET" --public-access-block-configuration BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true
2270 [ "$RC" = 0 ] || unresolved "s3-bucket $BUCKET: public access block failed: ${ECODE:-rc$RC}"
2271 try aws s3api put-bucket-tagging --bucket "$BUCKET" --tagging "TagSet=[{Key=purpose,Value=$TAGV},{Key=run,Value=$RUN}]"
2272 [ "$RC" = 0 ] || unresolved "s3-bucket $BUCKET: tagging failed: ${ECODE:-rc$RC}"
2273 else unresolved "s3-bucket $BUCKET: tags unreadable: ${ECODE:-rc$RC}"; fi
2274 elif [ "$OUT" = 0 ]; then absent "s3-bucket $BUCKET"
2275 else unresolved "s3-bucket $BUCKET: listed $OUT times"; fi
2276fi
2277if pending log-group "$LOG_GROUP" LOG_GROUP_CREATED; then
2278 try aws logs describe-log-groups --log-group-name-prefix "$LOG_GROUP" --query 'logGroups[].logGroupName' --output text
2279 if [ "$RC" != 0 ]; then unresolved "log-group: ${ECODE:-rc$RC}"
2280 elif [ "$OUT" = "$LOG_GROUP" ]; then rec LOG_GROUP_CREATED "$LOG_GROUP"
2281 elif [ -z "$OUT" ]; then absent "log-group $LOG_GROUP"
2282 else unresolved "log-group: unexpected groups [$OUT]"; fi
2283fi
2284if pending s3-object "s3://$BUCKET/t17/app.zip" ARTIFACT; then
2285 need ARTIFACT_B64
2286 if [ -z "${BUCKET_CREATED:-}" ]; then absent "s3-object (no bucket)"; OBJ=absent; RC=0; OUT=""
2287 else try aws s3api list-objects-v2 --bucket "$BUCKET" --prefix t17/app.zip --query 'length((Contents || `[]`)[?Key==`t17/app.zip`])' --output json
2288 if [ "$RC" != 0 ]; then unresolved "s3-object: list failed: ${ECODE:-rc$RC}"; OBJ=unknown
2289 elif [ "$OUT" = 0 ]; then absent "s3-object"; OBJ=absent
2290 else OBJ=listed; try aws s3api head-object --bucket "$BUCKET" --key t17/app.zip --checksum-mode ENABLED --query ChecksumSHA256 --output text; fi
2291 fi
2292 if [ "$OBJ" != listed ]; then :
2293 elif [ "$RC" = 0 ] && [ "$OUT" = "$ARTIFACT_B64" ]; then rec ARTIFACT "s3://$BUCKET/t17/app.zip"
2294 try aws s3api get-object-tagging --bucket "$BUCKET" --key t17/app.zip --query "TagSet[?Key=='run'].Value" --output text
2295 if [ "$RC" = 0 ] && [ "$OUT" != "$RUN" ]; then
2296 try aws s3api put-object-tagging --bucket "$BUCKET" --key t17/app.zip --tagging "TagSet=[{Key=purpose,Value=$TAGV},{Key=run,Value=$RUN}]"
2297 [ "$RC" = 0 ] || unresolved "s3-object: tagging failed: ${ECODE:-rc$RC}"
2298 elif [ "$RC" != 0 ]; then unresolved "s3-object: tags unreadable: ${ECODE:-rc$RC}"; fi
2299 elif [ "$RC" = 0 ]; then unresolved "s3-object: checksum $OUT is not $ARTIFACT_B64"
2300 else unresolved "s3-object: head failed: ${ECODE:-rc$RC}"; fi
2301fi
2302if pending microvm-image "$IMAGE_NAME" IMAGE_ARN; then
2303 lvr image list -name "$IMAGE_NAME"
2304 if [ "$RC" = 0 ]; then
2305 list_items || die "malformed image list reply in reconciliation"
2306 OUT=$(jq -r --arg n "$IMAGE_NAME" '[.[] | select(.Name == $n) | .ImageArn] | join(" ")' <<<"$ITEMS") || die "image list items unreadable"
2307 fi
2308 if [ "$RC" != 0 ]; then unresolved "microvm-image $IMAGE_NAME: list failed: ${ECODE:-rc$RC}"
2309 elif [ -z "$OUT" ]; then absent "microvm-image $IMAGE_NAME"
2310 elif [ "$(wc -w <<<"$OUT")" != 1 ]; then unresolved "microvm-image $IMAGE_NAME: listed several: $OUT"
2311 else arn=$OUT
2312 [ "$arn" = "arn:aws:lambda:eu-west-1:$ACCOUNT:microvm-image:$IMAGE_NAME" ] || die "image ARN [$arn]"
2313 rec IMAGE_ARN "$arn"
2314 lvr image get -id "$IMAGE_ARN"
2315 if [ "$RC" = 0 ] && [ "$(jq -r '.Tags.run // empty' <<<"$OUT")" != "$RUN" ]; then
2316 finding "microvm-image: tags missing ($(jq -c .Tags <<<"$OUT")); livectl tags only at create"
2317 elif [ "$RC" != 0 ]; then finding "microvm-image: tags unreadable: ${ECODE:-rc$RC}"; fi
2318 fi
2319fi
2320if pending sns-topic "$TOPIC_NAME" TOPIC_ARN; then
2321 t="arn:aws:sns:eu-west-1:$ACCOUNT:$TOPIC_NAME"
2322 try aws sns list-topics --query "length(Topics[?TopicArn=='$t'])" --output json
2323 if [ "$RC" != 0 ]; then unresolved "sns-topic: list failed: ${ECODE:-rc$RC}"
2324 elif [ "$OUT" = 1 ]; then rec TOPIC_ARN "$t"
2325 try aws sns list-tags-for-resource --resource-arn "$t" --query "Tags[?Key=='run'].Value" --output text
2326 if [ "$RC" = 0 ] && [ "$OUT" != "$RUN" ]; then
2327 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}"
2328 elif [ "$RC" != 0 ]; then unresolved "sns-topic: tags unreadable: ${ECODE:-rc$RC}"; fi
2329 elif [ "$OUT" = 0 ]; then absent "sns-topic $TOPIC_NAME"
2330 else unresolved "sns-topic: listed $OUT times"; fi
2331fi
2332[ -z "$UNRES" ] && echo "reconciliation complete: nothing unresolved" || { echo "unresolved, for Paul (S.4):"; tr '|' '\n' <<<"$UNRES"; }
2333```
2334
2335The extra IAM call here (`tag-role`, only when a role exists without its tags) is one of the role
2336calls R37 covers. Image versions are not reconciled: they go with the image, which livectl deletes
2337whole.
2338
2339**S.3 VMs.** If the image was never created (no `IMAGE_ARN`, even after S.2), no VM can exist; the
2340block records the skip and ends (skip-never-created rule).
2341
2342```sh
2343set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"; guard
2344if ! have IMAGE_ARN; then echo "no image was ever created, so no VM can exist"; exit 0; fi
2345! ctl_alive || die "the controller is running"
2346settle_all
2347sleep 120
2348settle_all
2349```
2350
2351`settle_all` ends every recorded VM and every live VM an image-scoped List shows, accepts an end
2352only as `TERMINATED` or two not-found reads at least 60 s apart, and finishes only after three
2353consecutive scans 30 s apart show nothing live. The second run, at least 2 minutes after the
2354controller stopped, covers the residual R21 accepts: a launch request AWS held after the client gave
2355up can still create a VM late. A VM that appears even later is visible to any later scan of the
2356image while the image exists, and its maximum duration (at most 1 hour for the drivers, 30 minutes
2357for the orphan, 15 minutes for the contract) ends it.
2358
2359**S.4 What is left for Paul.** Everything else in the ledger stays in place, and the agent reports
2360the ledger and this exposure:
2361
2362| Left in place | Cost while it stays |
2363| --- | --- |
2364| 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 |
2365| Connector, VPC, subnet, route table, group, defaults | no listed charge (no NAT, gateway or Elastic IP) |
2366| IAM roles, log group (1-day retention), SNS topic | none |
2367| S3 bucket and one object under 10 MB | under $0.01 a month |
2368| 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 |
2369
2370Teardown (section 10) then runs only on Paul's word, for the recorded resources only.
2371
2372---
2373
2374## 11. Spend
2375
2376### 11.1 Estimate
2377
2378Rates: Ireland x86_64 compute from spec §10 ($0.155 an hour at 2 GB baseline; above-baseline use up
2379to 4x costs extra). The pricing page prints snapshot and storage rates for US East only (write
2380$0.0038 per GB, read $0.00155 per GB, storage $0.08 per GB-month, image storage with a one-week
2381minimum); the worst case adds 20 % to those for Ireland. It lists no charge for image builds or
2382connectors; the worst case still allows for builds billed as VM time.
2383
2384| Item | Basis | Expected | Worst case, every approved branch |
2385| --- | --- | --- | --- |
2386| 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 |
2387| Contract VMs (6) | about 7, 3 to 6 min each | $0.09 | 8 at their 15-min maximum: 2 h, $0.31 |
2388| 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 |
2389| Orphan VM (8) | about 12 min | $0.03 | 1800 s: 0.5 h, $0.08 |
2390| Above-baseline use | idle hook server, none expected | $0.00 | 4x on all 6.47 VM-hours: +$3.01 |
2391| 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 |
2392| Launch snapshot reads | about 22 starts at 2 GB | $0.07 | 30 starts at 40 GB, x1.2: $2.23 |
2393| 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 |
2394| Image builds | 2 builds, a few minutes | $0.05 | 3 builds (the step down adds one) of 20 min at 4 GB: $0.31 |
2395| S3, CloudWatch Logs, SNS, data transfer | tiny object, under 1 MB of logs, a few publishes, no route out | $0.02 | $0.05 |
2396| **Total** | | **about $0.55** | **about $9.70** |
2397
2398The worst case is the sum of every bound at once (every VM at its maximum, at 4x, with the largest
2399snapshots), which cannot all happen in one run; it is still under the $10 approval ceiling.
2400**Leftovers after an abort** are not in the total: retained image storage costs about $0.50 to
2401$8.20 a month until teardown (S.4).
2402
2403**Which bound changed (R43).** The third build and its retained failed version add about $0.87, so
2404the fact experiments' VM maximum duration is cut from 900 s to 600 s (A1, A2, A3, E1 and G1, which
2405must share one request body). VM_A needs about 10 minutes for 9.A to 9.C; if it reaches its maximum
2406early, that is a FINDING, not a safety issue. The pause-cycle row is also corrected to the plan's
2407real maximum of three (it counted six). The worst case is about $9.70, under the $10 ceiling.
2408
2409### 11.2 The run's own estimate (stop rule)
2410
2411Computed from the VM ledger and the journal at the end of every section, with no billing call. Each
2412VM's life starts at the provider's `startedAt` (from the launch reply or any image-scoped scan);
2413for a VM known only from a log, at the start of the phase that found it, which is earlier than its
2414real start. It ends at the time its end was confirmed (`VMGONE`), which is later than its real end,
2415or now if it has not ended. Both ends err on the long side, so the figure is an upper bound on VM
2416time at baseline. A VM whose only start is a phase start is counted and listed as such.
2417
2418```sh
2419set -euo pipefail; . "${TMPDIR:?}/equipo-t17/env.sh"
2420python3 -I - "$VMS" "$JOURNAL" <<'EOF'
2421import sys, datetime as dt
2422def p(x):
2423 t = dt.datetime.fromisoformat(x.replace("Z", "+00:00"))
2424 if t.tzinfo is None or t.utcoffset() is None: raise ValueError(f"timestamp {x!r} has no time zone")
2425 return t
2426now = dt.datetime.now(dt.timezone.utc)
2427prov, phase, end = {}, {}, {}
2428def bad(kind, n, line, why):
2429 sys.exit(f"ABORT: {kind} line {n} cannot be read ({why}): {line[:160]!r}")
2430for n, line in enumerate(open(sys.argv[1]), 1):
2431 f = line.rstrip("\n").split("\t")
2432 if len(f) != 4: bad("VM ledger", n, line, f"{len(f)} fields, want 4")
2433 vid, src, start, _ = f
2434 if not vid: bad("VM ledger", n, line, "empty VM ID")
2435 try:
2436 if start.startswith("phase:"):
2437 t = p(start[6:]); phase[vid] = min(t, phase.get(vid, t))
2438 else:
2439 t = p(start); prov[vid] = min(t, prov.get(vid, t))
2440 except ValueError as e: bad("VM ledger", n, line, e)
2441for n, line in enumerate(open(sys.argv[2]), 1):
2442 if "\t" not in line: bad("journal", n, line, "no tab")
2443 ts, msg = line.rstrip("\n").split("\t", 1)
2444 w = msg.split(" ")
2445 if w[0] == "VMGONE":
2446 if len(w) < 2 or not w[1]: bad("journal", n, line, "VMGONE without an ID")
2447 try: end[w[1]] = p(ts)
2448 except ValueError as e: bad("journal", n, line, e)
2449hours, phase_only = 0.0, []
2450for vid in set(prov) | set(phase):
2451 start = prov.get(vid) or phase[vid]
2452 if vid not in prov: phase_only.append(vid)
2453 hours += max(0.0, (end.get(vid, now) - start).total_seconds()) / 3600
2454live = [v for v in set(prov) | set(phase) if v not in end]
2455third = any("\tCONFIRMED VER_SMALL_FAILED " in l for l in open(sys.argv[2]))
2456est = hours * 0.155 + 0.11 + 0.05 + 0.02 + 0.0057 * 2 * 3 + (0.055 + 0.025 if third else 0)
2457print(f"VMs {len(prov) + len([v for v in phase if v not in prov])}, not yet ended {len(live)}, "
2458 f"started from phase only {len(phase_only)} {phase_only}, VM-hours {hours:.2f}, estimate ${est:.2f} "
2459 f"(baseline compute plus image storage, builds, small items and three pause cycles; retained storage after an abort is separate)")
2460sys.exit(3 if est >= 5 else 0)
2461EOF
2462```
2463
2464- Stop rule: exit status 3 (estimate $5 or more), or a VM live outside its step, means the safe
2465 stop. A journal or VM ledger line that cannot be read ends the block with an `ABORT:` line naming
2466 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).
2467
2468**Wall-clock:** about 4.5 to 5 hours from 0.1 to 10.9.
2469
2470---
2471
2472## 12. UNCONFIRMED items and placeholders
2473
2474### Settled by the attempts and revision 5
2475
2476- **U1, connector role trust:** `lambda.amazonaws.com` with `sts:AssumeRole` and `sts:TagSession`
2477 was accepted (attempt 3).
2478- **Build role trust:** granting both actions covers both versions of the AWS page.
2479- **U2, create half:** the narrow operator policy is refused at create time even after 3.3 minutes
2480 (attempt 3); the managed policy plus the scoped delete was accepted. 2.1 now uses it from the
2481 start. The delete half is item 1 below.
2482- **U3, old CLI model:** no Lambda call goes through the CLI any more (R40). livectl sends
2483 `X86_64` and reads `Version`, `VersionArn`, `LatestVersionArn`, `Status` and
2484 `SupportedCpuConfigurations` through the pinned SDK. Attempt 3's discovery confirmed that `<arn>:1`
2485 reads `Version` 1, and that the unqualified body carries `LatestVersion` and `LatestVersionArn`
2486 only.
2487- **U6, hooks:** documented; a runtime hook failure shows up as a FINDING or as A1's stop.
2488- **U9, connector interfaces:** connector delete took about 19 s (attempt 3). There were no
2489 interfaces while ACTIVE, so cleanup with interfaces present is still item 1.
2490- **U10, `eu-west-1a`:** accepted for the subnet (attempt 2) and the connector (attempt 3).
2491- **U12, the Date header:** livectl reports it as `ResultMetadata.ServerTime`. lambda-core sends one
2492 (attempt 3's discovery); GetMicrovm is measured in 9.B.
2493- **U13, tag index:** the index lagged by up to a day after every teardown; direct reads decide
2494 (attempts 2 and 3).
2495- **U15, billing service name:** removed with Cost Explorer (R33).
2496- **U18, part:** connector-by-name gives `ResourceNotFoundException`; IAM gives `NoSuchEntity`;
2497 `NoSuchTagSet` is documented. Guessed S3, SNS and EC2 codes were replaced by list-and-match
2498 checks.
2499- **U20, process survival:** R37 (sandbox off, PID files, identity checks).
2500- **U23, livectl and the `kass` credentials:** settled by R42. livectl stays static-only; the plan
2501 exports `kass`'s credentials per call with `aws configure export-credentials --profile kass
2502 --format process` (the format and its JSON schema are from the installed CLI's own help) and
2503 hands livectl only the static keys, as the livectl rule says. Long waits are split at the
2504 credentials' expiry. That the exported keys are accepted by livectl's account check is first
2505 shown in 0.3; a refusal there is a hard stop before anything is created.
2506- **U22, livectl's interface:** settled at `bdf85fb7`. The plan follows `livectl-usage.md` at that
2507 commit: pinned endpoints, one attempt per call, a 60 s cutoff per call, bounded waits that never
2508 read after their deadline, and static credentials only. After Astra's round 1 on revision 5, every
2509 call site handles the exits as the livectl rule says. Exit 4 and every other hard stop propagate
2510 through subshells and polls (`die` with the FATAL marker; `finding` re-raises it). Exit 2 is a
2511 FINDING on observation reads and follows the block's branches on changes, with uncertain launches
2512 settled. Exit 5 is checked against one outer deadline per wait. `"Items":null` is read as an empty
2513 list, and any other malformed list reply fails through `list_items`.
2514
2515### Still unconfirmed, 12
2516
2517Each is now either a stop only where safety or a later step depends on it, or a FINDING.
2518
25191. **U2, delete half.** It is untested whether Lambda's interface deletion passes the
2520 `ec2:ManagedResourceOperator` condition. 10.2's pre-approved fallback drops that condition
2521 (keeping the subnet condition) and retries once; a second failure is a hard stop.
25222. **U4, base image version.** livectl now reads `Status` and x86_64 support. A failed create or
2523 build steps down one version once (3.6 to 3.8). A second failure stops the run: the image is
2524 needed.
25253. **U5, container base image** `public.ecr.aws/lambda/microvms:al2023-minimal` for x86_64. A build
2526 failure takes the same step down; nothing else is substituted.
25274. **U7, build log group.** Other groups under the prefix are never deleted; 10.6 stops for Paul
2528 (not in the ledger).
25295. **U8, image deletion.** A `ConflictException` from livectl `image delete` is a stop, since
2530 teardown needs the image gone.
25316. **U11, an unknown VM ref** on terminate: now a FINDING (6.1 labels it "known").
25327. **U14, the Small version stays ACTIVE** after the update: a FINDING (3.9).
25338. **U16, Ireland rates** for snapshots, launch reads and image storage: an estimate assumption.
25349. **U17, MicroVM ID format:** 9.A records the first real ID; outside R36's form is a FINDING. The
2535 image-scoped scans are the inventory either way.
253610. **U18, the Lambda MicroVMs not-found code** (`ResourceNotFoundException` for a gone VM) is
2537 documented but not observed. It stays fail-closed only in `vm_end`, where proving a VM ended is
2538 a safety check. Everywhere else a different code is a FINDING.
253911. **U19, image version tags:** recorded as read (3.8), a fact.
254012. **U21, a qualified egress ARN on RunMicrovm.** The adapter and the audit require it. A1 in 9.A
2541 is the first launch; a refusal stops the run, since every VM step needs launches (Fable's
2542 review).
2543
2544### Placeholders
2545
2546None. `PIN_SHA` is `bdf85fb70f26094b99241de3f1285de92a76a759`.
2547