Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

test(e2e): add Addendum-5 host-storm gate and #827 delete-during-pass step

Alfredo Lopez3e58a72af15a
diff --git a/scripts/e2e/e2e-host-storm-gate.sh b/scripts/e2e/e2e-host-storm-gate.sh
new file mode 100644
index 000000000..095bb8c93
--- /dev/null
+++ b/scripts/e2e/e2e-host-storm-gate.sh
@@ -0,0 +1,1296 @@
+#!/usr/bin/env bash
+# ======================================================================
+# E2E — Host STORM gate (Issue #791 follow-up, plan Addendum 5)
+# ======================================================================
+#
+# Reproduces the incident's *concurrency class* at realistic fleet scale
+# against the branch HCC image: with the seeded fleet present, this gate
+# OVERLAPS four storm ingredients in time (start timestamps are recorded
+# and asserted, proving genuine concurrency rather than sequential phases):
+#
+# (a) create STORM_CREATE_COUNT (>=10) fixture Hosts, mixed
+# stateful/stateless, storm-labeled;
+# (b) delete STORM_DELETE_COUNT (>=3) pre-created fixture Hosts
+# mid-storm (supported CR deletion path — never kubectl scale);
+# (c) trigger 1 wake of a suspended stateless Host through the SUPPORTED
+# rpc-proxy user route (POST /api/v1/rpc/hosts/:hostRef/wake with a
+# per-user RPC token minted the Desktop App way — the same helper
+# pattern as e2e-stateless-suspend-wake.sh);
+# (d) kill the HCC pod once mid-storm (kubectl delete pod — a supported
+# operational event forcing LIST->WATCH recovery under load).
+#
+# Assertions (each fail-loud with diagnostics), per plan §14.1/§14.2:
+# A1 concurrency: delete/wake/kill start timestamps all fall strictly
+# inside the Host-creation span (first create .. last create).
+# Framing (for PR evidence): the interleaving is enforced by
+# construction, so A1 is primarily a RECORDING of that evidence — it
+# can only fail if the harness itself degenerates into sequential
+# phases; the load-bearing falsifiable claims are A2-A8.
+# A2 urgent queue-wait p95 <= 5s DURING the storm window, computed from
+# the clerum_hcc_host_reconcile_queue_wait_seconds{lane="urgent"}
+# histogram buckets (§14.1) across two counter windows: pre-kill pod
+# delta (scrape B - scrape A) plus post-kill pod absolute (scrape C1,
+# taken IMMEDIATELY after created-Host convergence so post-storm quiet
+# samples cannot dilute the p95 — a fresh process starts at zero, and
+# the C1 window includes replacement-pod recovery traffic). Samples in
+# flight between scrape B and process death are unrecoverable (counter
+# reset) and are recorded as a documented measurement gap, never
+# silently backfilled.
+# A3 no starvation: EVERY created Host's Deployment materializes within
+# STORM_MATERIALIZATION_BUDGET_S (20s, §14.2 "New Host
+# materialization") of that Host's OWN metadata.creationTimestamp,
+# independent of the others. All deltas are listed; worst case printed.
+# A4 watch recovery <= 15s across the HCC kill, from the new pod's
+# clerum_hcc_host_watch_recovery_seconds{phase="total"} histogram
+# (scrape C1): zero failure samples, >=1 success sample, and every
+# success sample inside the le="15" bucket.
+# A5 every deleted Host's bundle fully cleaned: ownership-label
+# (clerum.io/managed-by + clerum.io/host) leftover check across the
+# three bundle namespaces (mcp-host, channels, rpc-proxy) — the same
+# predicate measure-host-bundle-reconcile.sh teardown uses. FAIL-
+# CLOSED: a kubectl read that cannot be verified (API error without
+# positive NotFound evidence) counts as failure, never as absence.
+# A6 delete-cleanup counters consistent (zero lost deletes):
+# clerum_hcc_host_delete_cleanup_total must be REGISTERED on the
+# branch image (TYPE line present) and its outcomes must be
+# consistent: retried == 0, superseded == 0, and
+# queued == confirmed == completed. Read from scrape C2 (taken after
+# A5 cleanup convergence, so the outcome counters are settled).
+# All-zero is legitimate (deletes fully handled by the direct
+# watch-DELETE path, which by design does not touch this counter) —
+# A5 remains the falsifiable cleanup proof.
+# A7 fleet coalescing held (one active + one trailing slot), from
+# clerum_hcc_host_fleet_requests_total (scrape C2): failed == 0 in
+# both windows; on the post-kill pod started >= 1 (the recovery
+# convergence pass ran), coalesced >= 1 (the recovery-triggered
+# request landed against the active initial pass), and trailing <=
+# coalesced (every trailing drain corresponds to at least one request
+# that was queued behind the single pending slot).
+# A8 wake ingredient integrity: the woken Host leaves state=suspended and
+# reaches a Ready pod within STORM_WAKE_READY_BUDGET_S of the wake
+# POST. This is an ingredient-integrity bound (a silently no-op wake
+# would weaken the gate), NOT a §14.2 wake SLO measurement — the §14.2
+# 45s wake clock assumes a healthy controller, and this gate kills the
+# controller seconds after the wake on purpose.
+#
+# HONEST SCOPE (plan Addendum 5.3 — recorded in the evidence): local
+# minikube cannot reproduce API-server instability, which was the
+# incident's amplifier. This gate validates scheduling fairness and
+# convergence under realistic concurrency, NOT API degradation — that
+# dimension remains covered by the bounded-deadline unit contracts and
+# post-deploy telemetry.
+#
+# Fixtures are storm-labeled (e2e-storm=791 + e2e-storm-run=<run-id>) and
+# torn down fail-loud; the profile and seeded data stay. Non-clerum.io
+# label keys are used deliberately: clerum.io/* is platform-owned
+# (HCC/WRC ownership semantics) and fixtures must never squat on it.
+#
+# Binding plan:
+# .ralph/plans/2026-07-22-issue-791-hcc-priority-reconciliation-wake-plan.md
+# Addendum 5 (storm shape + assertions), §14.1 (metric names),
+# §14.2 (measurement clocks — start/end points are BINDING).
+#
+# House style: self-contained like measure-host-bundle-reconcile.sh (kctl
+# --context wrapper, strict local-profile CONTEXT guard, log/ok/fail
+# helpers, python3 for RFC3339->epoch and histogram math) with the
+# rpc-token/wake helpers of e2e-stateless-suspend-wake.sh.
+#
+# ----------------------------------------------------------------------
+# INPUTS (environment; fail-loud if missing/invalid)
+# CONTEXT kubectl context. REFUSED unless it matches
+# ^clerum-(test|codex-|detached-|claude-) — a local minikube
+# profile. Any GKE / *prod* context is rejected outright.
+#
+# OPTIONAL INPUTS
+# E2E_STORM_WAKE_HOST_REF suspended-wake target (default chatllm-stateless,
+# the seeded stateless Host — it must exist with
+# spec.lifecycle.stateless=true and be associated to the E2E
+# user; seed via scripts/e2e/seed-stateless-host.sh).
+# EXTERNAL_REST_API_BASE_URL default http://127.0.0.1:8091
+# RPC_PROXY_BASE_URL default http://127.0.0.1:8094
+# E2E_DEV_LOGIN_EMAIL default [email protected]
+# E2E_USER_PASSWORD default ${ADMIN_PASSWORD:-admin123!}
+# STORM_CONTEXT_REF Context CR fixtures reference (default context1)
+# STORM_MODEL_PROVIDER / STORM_MODEL_NAME fixture model (default zai/glm-5.1)
+# HCC_METRICS_LOCAL_PORT ephemeral scrape port (default 18082)
+# KEEP_FIXTURES set to 1 to skip teardown (diagnosis only)
+#
+# Prereqs (each a HARD FAIL with the concrete reason):
+# - branch HCC image deployed (clerum_hcc_host_delete_cleanup_total
+# registered — A6 proves it)
+# - seeded stateless Host present + E2E user associated (wake mintable)
+# - external-rest-api + rpc-proxy reachable (make minikube-pf-all)
+#
+# Usage:
+# CONTEXT=clerum-test bash scripts/e2e/e2e-host-storm-gate.sh
+#
+# EXIT CODES
+# 0 every storm assertion passed and teardown left zero fixtures
+# 1 an assertion, precondition, or teardown failed loud — never masked
+# 2 usage / input error
+# ======================================================================
+set -euo pipefail
+
+# ─── Constants mirrored from host-context-controller/src/{constants,config}.ts ──
+readonly MANAGED_BY_LABEL='clerum.io/managed-by'
+readonly MANAGED_BY_VALUE='host-context-controller'
+readonly HOST_LABEL='clerum.io/host'
+readonly OWNED_SELECTOR="${MANAGED_BY_LABEL}=${MANAGED_BY_VALUE}"
+
+readonly MCP_HOST_NS='mcp-host' # config.hostNamespace
+readonly CHANNELS_NS='channels' # config.channelsNamespace
+readonly RPC_PROXY_NS='rpc-proxy' # config.rpcProxyNamespace
+readonly CONTROL_NS='control-plane'
+readonly HCC_DEPLOY='host-context-controller'
+readonly HCC_PORT='8081' # containerPort http (deploy/base/control-plane)
+readonly HCC_METRICS_PATH='/metrics' # server.ts GET /metrics
+
+# Owned-child kinds + namespaces of a per-Host bundle (mirrors
+# measure-host-bundle-reconcile.sh — includes per-Host NetworkPolicies).
+readonly BUNDLE_KINDS='deployment service serviceaccount secret persistentvolumeclaim networkpolicy role rolebinding configmap'
+readonly BUNDLE_NAMESPACES="${MCP_HOST_NS} ${CHANNELS_NS} ${RPC_PROXY_NS}"
+
+# §14.1 metric names (host-context-controller/src/metrics.ts).
+# EXPORTED so the adjudication python reads them from the environment. They are
+# `readonly`, so passing them as same-name command-prefix assignments
+# (`QUEUE_WAIT_METRIC="$QUEUE_WAIT_METRIC" python3 …`) would fail as a readonly
+# reassignment under `set -e` — export once here and drop the inline prefixes.
+readonly QUEUE_WAIT_METRIC='clerum_hcc_host_reconcile_queue_wait_seconds'
+readonly WATCH_RECOVERY_METRIC='clerum_hcc_host_watch_recovery_seconds'
+readonly FLEET_METRIC='clerum_hcc_host_fleet_requests_total'
+readonly DELETE_CLEANUP_METRIC='clerum_hcc_host_delete_cleanup_total'
+export QUEUE_WAIT_METRIC WATCH_RECOVERY_METRIC FLEET_METRIC DELETE_CLEANUP_METRIC
+
+# ─── Storm shape + budgets (each constant states its contract) ────────
+# Addendum 5.1: ">=10" created fixture Hosts, mixed stateful/stateless.
+readonly STORM_CREATE_COUNT=10
+# Addendum 5.1: ">=3" pre-created fixture Hosts deleted mid-storm.
+readonly STORM_DELETE_COUNT=3
+# §14.2 "urgent new/wake queue wait": local hard gate <= 5s (histogram
+# bucket boundary le="5" exists in RECONCILE_LATENCY_BUCKETS).
+readonly STORM_URGENT_P95_BUDGET_S=5
+# §14.2 "New Host materialization": Host CR -> Deployment <= 20s.
+readonly STORM_MATERIALIZATION_BUDGET_S=20
+# §14.2 "Watch recovery": recovery requested -> WATCH installed <= 15s
+# (histogram bucket boundary le="15" exists).
+readonly STORM_WATCH_RECOVERY_BUDGET_S=15
+# A8 ingredient-integrity bound for the mid-storm wake: §14.2 wake budget
+# (45s) + watch-recovery budget (15s, the controller is killed after the
+# wake) + scheduling margin. NOT a §14.2 SLO measurement (see header).
+readonly STORM_WAKE_READY_BUDGET_S=90
+# Bounded discovery wait for ALL created Hosts' Deployments to exist before
+# per-host deltas are adjudicated. Expiry is a HARD FAIL with diagnostics —
+# the per-host 20s budget is judged from creationTimestamps regardless.
+readonly STORM_CONVERGENCE_DEADLINE_S=120
+# Bounded wait for a deleted Host's CR + full owned bundle to disappear.
+readonly STORM_CLEANUP_DEADLINE_S=180
+# Bounded wait for the delete-target fixtures' bundles to exist pre-storm
+# (a delete of a bundle-less Host would prove nothing).
+readonly STORM_PREP_MATERIALIZE_DEADLINE_S=90
+# Bounded wait for the replacement HCC pod after the mid-storm kill.
+readonly STORM_HCC_READY_DEADLINE_S=120
+# Idle->suspend window for the wake target when it is not already
+# suspended: emitter tick (~30s) + test idle floor (60s) + drain grace
+# (20s) + HCC poll (5s) + slack (mirrors e2e-stateless-suspend-wake.sh
+# SUSPEND_WINDOW rationale under the same shortened cadences).
+readonly STORM_SUSPEND_WINDOW_S=210
+# Bounded teardown wait before the fail-loud leftover check.
+readonly STORM_TEARDOWN_DEADLINE_S=180
+# Bounded EXTENSION for owned children that are already Terminating
+# (deletionTimestamp set) at the leftover check — e.g. a workspace PVC whose
+# kubernetes.io/pvc-protection finalizer drains for the deleting pod's
+# termination grace. A leftover with NO deletionTimestamp is never given this
+# extension (the delete was never issued → immediate fail).
+readonly STORM_TEARDOWN_CONVERGE_S=120
+
+# HCC test cadences applied ONLY when the wake target must first be driven
+# to suspension (identical values to e2e-stateless-suspend-wake.sh; saved
+# from the live deployment and restored in the cleanup trap).
+readonly TEST_IDLE_MINUTES='1'
+readonly TEST_IDLE_FLOOR_MINUTES='1'
+readonly TEST_DRAIN_GRACE_MS='20000'
+readonly TEST_POLL_MS='5000'
+
+# Fixture provenance labels. Every object this gate creates carries BOTH so
+# teardown deletes ONLY this run's fixtures. Deliberately NOT clerum.io/*
+# (platform-owned label namespace — see header).
+readonly FIXTURE_LABEL_KEY='e2e-storm'
+readonly FIXTURE_LABEL_VAL='791'
+readonly FIXTURE_RUN_KEY='e2e-storm-run'
+
+# ─── Colors (mirrors e2e-lib.sh) ──────────────────────────────────────
+RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'; CYAN='\033[0;36m'; NC='\033[0m'; BOLD='\033[1m'
+
+# ─── Counters ─────────────────────────────────────────────────────────
+g_pass=0; g_fail=0; g_total=0
+
+# ─── Logging helpers (mirrors e2e-lib.sh / measure script) ────────────
+log() { echo -e "${CYAN}[STORM]${NC} $*"; }
+ok() { g_pass=$((g_pass+1)); g_total=$((g_total+1)); echo -e "${GREEN} PASS${NC} — $*"; }
+fail() { g_fail=$((g_fail+1)); g_total=$((g_total+1)); echo -e "${RED} FAIL${NC} — $*" >&2; }
+warn() { echo -e "${YELLOW} WARN${NC} — $*" >&2; }
+header() { echo -e "\n${BOLD}=== $* ===${NC}"; }
+die() { echo -e "${RED}[STORM] FATAL${NC} — ${1}" >&2; exit "${2:-1}"; }
+
+print_results() {
+ echo -e "\n${BOLD}=== Storm gate summary (run-id ${RUN_ID:-?}) ===${NC}"
+ echo -e " ${GREEN}pass=${g_pass}${NC} ${RED}fail=${g_fail}${NC} total=${g_total}"
+ log "Honest scope (Addendum 5.3): local minikube cannot reproduce API-server"
+ log "instability (the incident's amplifier); this gate validates scheduling"
+ log "fairness and convergence under realistic concurrency, not API degradation."
+}
+
+# ─── kubectl wrapper — EVERY call carries --context (CLAUDE.md mandate) ──
+kctl() { kubectl --context "$CONTEXT" "$@"; }
+
+# ─── Portable time helper (python3; mirrors measure script) ───────────
+now_ms() { python3 -c 'import time;print(int(time.time()*1000))'; }
+
+# ─── Strict local-profile context guard (fail-loud) ───────────────────
+require_storm_context() {
+ [[ -n "${CONTEXT:-}" ]] || die "CONTEXT is required (a local minikube profile context)." 2
+ case "$CONTEXT" in
+ *gke_*|*prod*)
+ die "Refusing: CONTEXT='${CONTEXT}' looks like a GKE/production context. Local profiles only." 2 ;;
+ esac
+ if [[ ! "$CONTEXT" =~ ^clerum-(test|codex-|detached-|claude-) ]]; then
+ die "Refusing: CONTEXT='${CONTEXT}' is not an allowed local profile. Must match ^clerum-(test|codex-|detached-|claude-)." 2
+ fi
+ if ! kctl get nodes -o name >/dev/null 2>&1; then
+ die "CONTEXT='${CONTEXT}' is not reachable (kubectl get nodes failed). Start the profile and its port-forwards." 1
+ fi
+ log "context OK: ${CONTEXT}"
+}
+
+require_deps() {
+ local missing=()
+ for bin in kubectl jq python3 curl mktemp; do
+ command -v "$bin" >/dev/null 2>&1 || missing+=("$bin")
+ done
+ [[ ${#missing[@]} -eq 0 ]] || die "missing required tools: ${missing[*]}" 2
+}
+
+# ─── Bounded wait helper: poll <fn> until success or <deadline_s>; on
+# expiry dump <diag_fn> and return 1 (never silently continue) ────────
+wait_until() {
+ local deadline_s="$1" interval_s="$2" desc="$3" probe_fn="$4" diag_fn="${5:-:}"
+ local start now
+ start="$(now_ms)"
+ while :; do
+ if "$probe_fn"; then return 0; fi
+ now="$(now_ms)"
+ if (( (now - start) / 1000 >= deadline_s )); then
+ warn "deadline ${deadline_s}s expired waiting for: ${desc}"
+ "$diag_fn" || true
+ return 1
+ fi
+ sleep "$interval_s"
+ done
+}
+
+# ======================================================================
+# Run state
+# ======================================================================
+RUN_ID=''; WORK_DIR=''
+FIXTURE_SECRET=''
+STORM_CREATED_HOSTS=()
+STORM_DELETE_HOSTS=()
+WAKE_HOST_REF="${E2E_STORM_WAKE_HOST_REF:-chatllm-stateless}"
+EXT_BASE="${EXTERNAL_REST_API_BASE_URL:-http://127.0.0.1:8091}"
+RPC_BASE="${RPC_PROXY_BASE_URL:-http://127.0.0.1:8094}"
+DEV_EMAIL="${E2E_DEV_LOGIN_EMAIL:[email protected]}"
+DEV_PASSWORD="${E2E_USER_PASSWORD:-${ADMIN_PASSWORD:-admin123!}}"
+STORM_CTX_REF="${STORM_CONTEXT_REF:-context1}"
+STORM_PROVIDER="${STORM_MODEL_PROVIDER:-zai}"
+STORM_MODEL="${STORM_MODEL_NAME:-glm-5.1}"
+
+# Storm timeline (epoch-ms; A1 concurrency evidence).
+T_CREATE_FIRST_MS=''; T_DELETE_MS=''; T_WAKE_MS=''; T_KILL_MS=''; T_CREATE_LAST_MS=''
+
+# ─── Cleanup trap: best-effort fixture removal + HCC cadence restore ──
+PF_PID=''
+HCC_ENV_SAVED=''
+TEARDOWN_DONE=0
+
+cleanup_portforward() {
+ if [[ -n "$PF_PID" ]] && kill -0 "$PF_PID" 2>/dev/null; then
+ kill "$PF_PID" 2>/dev/null || true
+ wait "$PF_PID" 2>/dev/null || true
+ fi
+ PF_PID=''
+}
+
+# Build the kubectl set env restore args from HCC_ENV_SAVED into the
+# caller's `args` array (empty saved value => remove the key).
+_hcc_restore_args() {
+ args=()
+ local key val
+ while IFS='=' read -r key val; do
+ [[ -n "$key" ]] || continue
+ if [[ -n "$val" ]]; then args+=("${key}=${val}"); else args+=("${key}-"); fi
+ done <<< "$HCC_ENV_SAVED"
+}
+
+# Lenient restore — EXIT-trap path only: best-effort with warnings, so an
+# abnormal exit still attempts to undo the cadence mutation.
+# shellcheck disable=SC2329 # invoked from cleanup_on_exit (EXIT trap)
+restore_hcc_env() {
+ [[ -n "$HCC_ENV_SAVED" ]] || return 0
+ local args=()
+ _hcc_restore_args
+ [[ ${#args[@]} -gt 0 ]] || { HCC_ENV_SAVED=''; return 0; }
+ log "Restoring HCC cadence env on deployment/${HCC_DEPLOY}"
+ kctl set env "deployment/${HCC_DEPLOY}" -n "$CONTROL_NS" "${args[@]}" >/dev/null 2>&1 || \
+ warn "failed to restore HCC env (manual check advised)"
+ kctl rollout status "deployment/${HCC_DEPLOY}" -n "$CONTROL_NS" --timeout=180s >/dev/null 2>&1 || \
+ warn "HCC rollout did not settle after env restore"
+ HCC_ENV_SAVED=''
+}
+
+# Strict restore — SUCCESS path (M3): a failed cadence restore is real
+# profile damage and must flip the gate to FAIL (counted via fail());
+# HCC_ENV_SAVED is kept on failure so the EXIT trap retries best-effort.
+# Always returns 0 so the final print_results/exit-code path still runs.
+restore_hcc_env_strict() {
+ [[ -n "$HCC_ENV_SAVED" ]] || return 0
+ local args=()
+ _hcc_restore_args
+ [[ ${#args[@]} -gt 0 ]] || { HCC_ENV_SAVED=''; return 0; }
+ log "Restoring HCC cadence env on deployment/${HCC_DEPLOY} (strict)"
+ if ! kctl set env "deployment/${HCC_DEPLOY}" -n "$CONTROL_NS" "${args[@]}" >/dev/null 2>&1; then
+ fail "cadence restore FAILED — the profile is left with test cadences on deployment/${HCC_DEPLOY} (the EXIT trap retries best-effort; verify manually)"
+ return 0
+ fi
+ if ! kctl rollout status "deployment/${HCC_DEPLOY}" -n "$CONTROL_NS" --timeout=180s >/dev/null 2>&1; then
+ fail "HCC rollout did not settle after the cadence restore — verify deployment/${HCC_DEPLOY} manually"
+ return 0
+ fi
+ HCC_ENV_SAVED=''
+ ok "HCC test cadences restored and rolled out"
+}
+
+# shellcheck disable=SC2329 # invoked via the EXIT trap below
+cleanup_on_exit() {
+ local status=$?
+ set +e
+ cleanup_portforward
+ if [[ "$TEARDOWN_DONE" != '1' && -n "$RUN_ID" && "${KEEP_FIXTURES:-}" != '1' ]]; then
+ local sel="${FIXTURE_LABEL_KEY}=${FIXTURE_LABEL_VAL},${FIXTURE_RUN_KEY}=${RUN_ID}"
+ warn "abnormal exit — best-effort deletion of storm fixtures (${sel})"
+ kctl -n "$MCP_HOST_NS" delete host -l "$sel" --wait=false >/dev/null 2>&1 || \
+ warn "best-effort fixture Host deletion failed (manual check advised)"
+ kctl -n "$MCP_HOST_NS" delete secret -l "$sel" --wait=false >/dev/null 2>&1 || \
+ warn "best-effort fixture Secret deletion failed (manual check advised)"
+ fi
+ restore_hcc_env
+ exit "$status"
+}
+trap cleanup_on_exit EXIT
+
+# ======================================================================
+# Fixture + observable helpers
+# ======================================================================
+init_run() {
+ # Run discriminator: FULL epoch-ms plus a random suffix — no truncation,
+ # so there is no periodic tail-collision window between runs. Longest
+ # fixture name stays s791-<13ms>-<5rand>-c%02d = 28 chars, inside the
+ # 34-char budget that keeps host-<name>-mcp-host-runtime-tokens <= 63.
+ RUN_ID="$(now_ms)-${RANDOM}"
+ WORK_DIR="$(mktemp -d "${TMPDIR:-/tmp}/e2e-host-storm-${RUN_ID}.XXXXXX")"
+ FIXTURE_SECRET="s791-${RUN_ID}-keys"
+ local i
+ for i in $(seq 1 "$STORM_CREATE_COUNT"); do
+ STORM_CREATED_HOSTS+=("$(printf 's791-%s-c%02d' "$RUN_ID" "$i")")
+ done
+ for i in $(seq 1 "$STORM_DELETE_COUNT"); do
+ STORM_DELETE_HOSTS+=("$(printf 's791-%s-d%d' "$RUN_ID" "$i")")
+ done
+ log "run-id ${RUN_ID}; work dir ${WORK_DIR}"
+ log "create fixtures: ${STORM_CREATED_HOSTS[*]}"
+ log "delete fixtures: ${STORM_DELETE_HOSTS[*]}"
+}
+
+ensure_fixture_secret() {
+ # Throwaway placeholder Secret (mirrors measure script): the mcp-host
+ # readiness probe is an HTTP health endpoint that never validates the LLM
+ # key, so a placeholder is sufficient for materialization clocks.
+ cat <<YAML | kctl apply -f - >/dev/null
+apiVersion: v1
+kind: Secret
+metadata:
+ name: ${FIXTURE_SECRET}
+ namespace: ${MCP_HOST_NS}
+ labels:
+ ${FIXTURE_LABEL_KEY}: "${FIXTURE_LABEL_VAL}"
+ ${FIXTURE_RUN_KEY}: "${RUN_ID}"
+type: Opaque
+stringData:
+ ZAI_API_KEY: "placeholder-e2e-storm-not-a-real-key"
+ OPENAI_API_KEY: "placeholder-e2e-storm-not-a-real-key"
+YAML
+ log "created placeholder Secret ${FIXTURE_SECRET}"
+}
+
+# apply_storm_host <name> <stateless:true|false>
+apply_storm_host() {
+ local name="$1" stateless="$2" lifecycle_block=''
+ if [[ "$stateless" == 'true' ]]; then
+ lifecycle_block=$' lifecycle:\n stateless: true'
+ fi
+ cat <<YAML | kctl apply -f - >/dev/null
+apiVersion: clerum.io/v1alpha1
+kind: Host
+metadata:
+ name: ${name}
+ namespace: ${MCP_HOST_NS}
+ labels:
+ ${FIXTURE_LABEL_KEY}: "${FIXTURE_LABEL_VAL}"
+ ${FIXTURE_RUN_KEY}: "${RUN_ID}"
+spec:
+ host: ${name}
+ contextRef: ${STORM_CTX_REF}
+ secretRef: ${FIXTURE_SECRET}
+ model:
+ provider: ${STORM_PROVIDER}
+ name: ${STORM_MODEL}
+${lifecycle_block}
+YAML
+}
+
+# Collect every owned child of <host> across the bundle namespaces —
+# the authoritative HCC ownership selector (managed-by + host), same
+# predicate as measure-host-bundle-reconcile.sh / HostReconciler.
+#
+# FAIL-CLOSED (B2): prints "ns/kind/name" lines to stdout and returns 0
+# even when empty; returns 2 when ANY kubectl read FAILED (the error goes
+# to stderr). Every label-selector list of these standard kinds returns
+# exit 0 with empty output when nothing matches, so a nonzero kubectl exit
+# is a real read failure (API outage, RBAC, unknown kind) — callers MUST
+# treat rc=2 as "verification impossible" (a failure), never as "zero
+# leftovers".
+collect_children() {
+ local host="$1" ns kind out rc=0
+ for ns in $BUNDLE_NAMESPACES; do
+ for kind in $BUNDLE_KINDS; do
+ if ! out="$(kctl -n "$ns" get "$kind" \
+ -l "${OWNED_SELECTOR},${HOST_LABEL}=${host}" -o name 2>"${WORK_DIR}/collect-children.err")"; then
+ echo "collect_children: kubectl get ${kind} in ${ns} FAILED for host ${host}: $(cat "${WORK_DIR}/collect-children.err" 2>/dev/null)" >&2
+ rc=2
+ continue
+ fi
+ if [[ -n "$out" ]]; then
+ printf '%s\n' "$out" | sed "s|^|${ns}/|"
+ fi
+ done
+ done
+ return "$rc"
+}
+
+# FAIL-CLOSED absence check (B2): returns 0 ONLY when the API positively
+# answered NotFound for the Host. "Present" returns 1; any other kubectl
+# failure (outage, RBAC, timeout) returns 2 with the error on stderr —
+# absence must never be inferred from an unreadable API.
+# shellcheck disable=SC2329 # invoked from _deleted_hosts_clean_probe (runs via wait_until)
+host_absent_confirmed() {
+ local h="$1" err
+ if kctl -n "$MCP_HOST_NS" get host "$h" -o name >/dev/null 2>"${WORK_DIR}/host-absent.err"; then
+ return 1
+ fi
+ err="$(cat "${WORK_DIR}/host-absent.err" 2>/dev/null || true)"
+ # Anchored match: the API-server reason '(NotFound)' or the kubectl
+ # trailing form naming EXACTLY the requested Host. A kubeconfig-level
+ # error like `context "..." not found` must never confirm absence.
+ if printf '%s' "$err" | grep -Eq "\(NotFound\)|\"${h}\" not found\$"; then
+ return 0
+ fi
+ echo "host_absent_confirmed: kubectl get host ${h} FAILED without NotFound evidence: ${err}" >&2
+ return 2
+}
+
+hcc_pod_name() {
+ kctl -n "$CONTROL_NS" get pods -l "app=${HCC_DEPLOY}" \
+ --field-selector=status.phase=Running \
+ -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.metadata.deletionTimestamp}{"\n"}{end}' 2>/dev/null \
+ | awk -F'\t' '$1 != "" && $2 == "" {print $1; exit}'
+}
+
+storm_diagnostics() {
+ {
+ echo "----- storm diagnostics (run-id ${RUN_ID}) -----"
+ kctl -n "$MCP_HOST_NS" get host -l "${FIXTURE_LABEL_KEY}=${FIXTURE_LABEL_VAL},${FIXTURE_RUN_KEY}=${RUN_ID}" -o wide 2>&1 || true
+ kctl -n "$MCP_HOST_NS" get deploy -l "$OWNED_SELECTOR" -o wide 2>&1 | head -40 || true
+ kctl -n "$CONTROL_NS" get pods -l "app=${HCC_DEPLOY}" -o wide 2>&1 || true
+ echo "----- recent HCC logs -----"
+ kctl -n "$CONTROL_NS" logs "deploy/${HCC_DEPLOY}" --tail=60 2>&1 || true
+ } >&2
+}
+
+# ─── Metrics scrape (ephemeral port-forward; mirrors measure script) ──
+# scrape_hcc_metrics <outfile> <pod-name> — M1: the port-forward binds the
+# POD BY NAME (never deploy/) so a scrape can never silently read a
+# different pod (e.g. a terminating one during a rollout) than the one the
+# identity guard checked; cross-pod counter deltas would false-PASS A4.
+scrape_hcc_metrics() {
+ local out="$1" pod="$2" lport="${HCC_METRICS_LOCAL_PORT:-18082}"
+ local url="http://127.0.0.1:${lport}${HCC_METRICS_PATH}"
+ kctl -n "$CONTROL_NS" port-forward "pod/${pod}" "${lport}:${HCC_PORT}" >"${WORK_DIR}/pf.log" 2>&1 &
+ PF_PID=$!
+ # shellcheck disable=SC2329 # invoked by name via wait_until
+ _scrape_probe() { curl -fsS --max-time 3 "$url" -o "$out" 2>/dev/null; }
+ # shellcheck disable=SC2329 # invoked by name via wait_until
+ _scrape_diag() { { echo '----- port-forward log -----'; cat "${WORK_DIR}/pf.log" 2>/dev/null; } >&2; }
+ if ! wait_until 30 2 "HCC metrics scrape -> ${out}" _scrape_probe _scrape_diag; then
+ cleanup_portforward
+ return 1
+ fi
+ cleanup_portforward
+}
+
+# ─── Wake-target lifecycle observables ────────────────────────────────
+wake_lifecycle_state() {
+ kctl -n "$MCP_HOST_NS" get host "$WAKE_HOST_REF" -o jsonpath='{.status.lifecycle.state}' 2>/dev/null || true
+}
+
+# shellcheck disable=SC2329 # invoked from _wake_converged_probe (runs via wait_until)
+wake_ready_pod_exists() {
+ kctl -n "$MCP_HOST_NS" get pods -l "app=${WAKE_HOST_REF}" \
+ --field-selector=status.phase=Running \
+ -o jsonpath='{range .items[*]}{.status.conditions[?(@.type=="Ready")].status}{"\n"}{end}' 2>/dev/null \
+ | grep -qx 'True'
+}
+
+# ─── RPC helpers (Desktop App auth path; mirrors e2e-stateless-suspend-wake.sh) ──
+SESSION_TOKEN=''; RPC_TOKEN=''
+RPC_SCOPES_JSON='["host:message:invoke","host:approval:write","host:session:read","host:status:read","host:health:read","host:wake:write"]'
+
+mint_session_token() {
+ local resp code body
+ resp=$(curl -sS -m 30 -w '\n%{http_code}' -X POST "${EXT_BASE}/api/v1/auth/password-login" \
+ -H 'Content-Type: application/json' \
+ -d "$(jq -cn --arg e "$DEV_EMAIL" --arg p "$DEV_PASSWORD" '{email:$e,password:$p}')") || {
+ echo "password-login request failed at ${EXT_BASE}" >&2; return 1; }
+ code="$(echo "$resp" | tail -n1)"; body="$(echo "$resp" | sed '$d')"
+ [[ "$code" == '200' ]] || { echo "password-login -> HTTP ${code}: ${body}" >&2; return 1; }
+ SESSION_TOKEN="$(echo "$body" | jq -r '.token // empty')"
+ [[ -n "$SESSION_TOKEN" ]] || { echo "password-login returned no .token" >&2; return 1; }
+}
+
+mint_rpc_token() {
+ local resp code body
+ resp=$(curl -sS -m 30 -w '\n%{http_code}' -X POST "${EXT_BASE}/api/v1/rpc/token" \
+ -H "Authorization: Bearer ${SESSION_TOKEN}" -H 'Content-Type: application/json' \
+ -d "$(jq -cn --arg h "$WAKE_HOST_REF" --argjson s "$RPC_SCOPES_JSON" '{hostRefs:[$h],scopes:$s}')") || {
+ echo "rpc/token request failed at ${EXT_BASE}" >&2; return 1; }
+ code="$(echo "$resp" | tail -n1)"; body="$(echo "$resp" | sed '$d')"
+ [[ "$code" == '200' ]] || { echo "rpc/token -> HTTP ${code}: ${body}" >&2; return 1; }
+ RPC_TOKEN="$(echo "$body" | jq -r '.token // empty')"
+ [[ -n "$RPC_TOKEN" ]] || { echo "rpc/token returned no .token" >&2; return 1; }
+}
+
+# The wake route is the user-facing rpc-proxy endpoint Desktop uses;
+# rpc-proxy owns the control-api hop. Never kubectl scale.
+WAKE_STATUS=''; WAKE_BODY=''
+post_wake() {
+ local resp
+ mint_rpc_token || return 1
+ resp=$(curl -sS -m 30 -w '\n%{http_code}' -X POST \
+ "${RPC_BASE}/api/v1/rpc/hosts/${WAKE_HOST_REF}/wake" \
+ -H "Authorization: Bearer ${RPC_TOKEN}" -H 'Content-Type: application/json') || {
+ echo "wake POST failed at ${RPC_BASE}" >&2; return 1; }
+ WAKE_STATUS="$(echo "$resp" | tail -n1)"; WAKE_BODY="$(echo "$resp" | sed '$d')"
+ case "$WAKE_STATUS" in
+ 200|202|204) return 0 ;;
+ *) echo "wake POST returned HTTP ${WAKE_STATUS}: ${WAKE_BODY}" >&2; return 1 ;;
+ esac
+}
+
+# ─── HCC cadence shortening (only when the wake target must suspend) ──
+save_and_set_hcc_cadences() {
+ header "Setting HCC test cadences (idle=${TEST_IDLE_MINUTES}m, drain=${TEST_DRAIN_GRACE_MS}ms, poll=${TEST_POLL_MS}ms)"
+ local keys=(CONTEXT_MAPPER_STATELESS_IDLE_MINUTES CONTEXT_MAPPER_STATELESS_IDLE_FLOOR_MINUTES \
+ CONTEXT_MAPPER_STATELESS_DRAIN_GRACE_MS CONTEXT_MAPPER_HEARTBEAT_POLL_MS)
+ local k cur saved=''
+ for k in "${keys[@]}"; do
+ cur="$(kctl get "deployment/${HCC_DEPLOY}" -n "$CONTROL_NS" \
+ -o jsonpath="{.spec.template.spec.containers[0].env[?(@.name=='${k}')].value}" 2>/dev/null || true)"
+ saved+="${k}=${cur}"$'\n'
+ done
+ HCC_ENV_SAVED="$saved"
+ kctl set env "deployment/${HCC_DEPLOY}" -n "$CONTROL_NS" \
+ "CONTEXT_MAPPER_STATELESS_IDLE_MINUTES=${TEST_IDLE_MINUTES}" \
+ "CONTEXT_MAPPER_STATELESS_IDLE_FLOOR_MINUTES=${TEST_IDLE_FLOOR_MINUTES}" \
+ "CONTEXT_MAPPER_STATELESS_DRAIN_GRACE_MS=${TEST_DRAIN_GRACE_MS}" \
+ "CONTEXT_MAPPER_HEARTBEAT_POLL_MS=${TEST_POLL_MS}" >/dev/null 2>&1 || {
+ fail "failed to set HCC test cadences via kubectl set env"; return 1; }
+ if kctl rollout status "deployment/${HCC_DEPLOY}" -n "$CONTROL_NS" --timeout=180s >/dev/null 2>&1; then
+ ok "HCC test cadences applied and rolled out"
+ else
+ fail "HCC rollout did not settle after cadence set"; storm_diagnostics; return 1
+ fi
+}
+
+# shellcheck disable=SC2329 # invoked by name via wait_until
+_wake_target_suspended_probe() {
+ local st reps
+ st="$(wake_lifecycle_state)"
+ reps="$(kctl -n "$MCP_HOST_NS" get deployment "$WAKE_HOST_REF" -o jsonpath='{.spec.replicas}' 2>/dev/null || echo '')"
+ [[ "$st" == 'suspended' && "${reps:-1}" == '0' ]]
+}
+
+# shellcheck disable=SC2329 # invoked by name via wait_until
+_wake_target_diag() {
+ {
+ echo "----- wake target diagnostics (${WAKE_HOST_REF}) -----"
+ kctl -n "$MCP_HOST_NS" get host "$WAKE_HOST_REF" \
+ -o jsonpath='{"lifecycle="}{.status.lifecycle}{"\n"}' 2>&1 || true
+ kctl -n "$MCP_HOST_NS" get pods -l "app=${WAKE_HOST_REF}" -o wide 2>&1 || true
+ kctl -n "$CONTROL_NS" logs "deploy/${HCC_DEPLOY}" --tail=40 2>&1 || true
+ } >&2
+}
+
+# ======================================================================
+# Prerequisites
+# ======================================================================
+require_deps
+require_storm_context
+init_run
+
+header "Prerequisites"
+if kctl get deployment "$HCC_DEPLOY" -n "$CONTROL_NS" >/dev/null 2>&1; then
+ ok "HCC deployment present in ${CONTROL_NS}"
+else
+ fail "deployment/${HCC_DEPLOY} not found in ${CONTROL_NS}"; print_results; exit 1
+fi
+
+stateless_flag="$(kctl -n "$MCP_HOST_NS" get host "$WAKE_HOST_REF" -o jsonpath='{.spec.lifecycle.stateless}' 2>/dev/null || echo '')"
+if [[ "$stateless_flag" == 'true' ]]; then
+ ok "wake target '${WAKE_HOST_REF}' exists with spec.lifecycle.stateless=true"
+else
+ fail "wake target '${WAKE_HOST_REF}' missing or not stateless (got '${stateless_flag:-<absent>}'). Seed: bash scripts/e2e/seed-stateless-host.sh"
+ print_results; exit 1
+fi
+
+if kctl -n "$MCP_HOST_NS" get context.clerum.io "$STORM_CTX_REF" >/dev/null 2>&1 \
+ || kctl get context.clerum.io "$STORM_CTX_REF" -n mcp-server >/dev/null 2>&1; then
+ ok "fixture contextRef '${STORM_CTX_REF}' exists"
+else
+ fail "fixture contextRef '${STORM_CTX_REF}' not found (set STORM_CONTEXT_REF to an existing Context CR)"
+ print_results; exit 1
+fi
+
+for svc in "external-rest-api ${EXT_BASE}" "rpc-proxy ${RPC_BASE}"; do
+ name="${svc%% *}"; base="${svc##* }"
+ if curl -fsS -m 10 "${base}/health" >/dev/null 2>&1; then
+ ok "${name} reachable at ${base}"
+ else
+ fail "${name} NOT reachable at ${base} -- start port-forwards (make minikube-pf-all)"; print_results; exit 1
+ fi
+done
+
+if mint_session_token; then ok "session token minted for ${DEV_EMAIL}"; else
+ fail "cannot login as ${DEV_EMAIL} on ${EXT_BASE}"; print_results; exit 1; fi
+if mint_rpc_token; then
+ ok "user RPC token minted for hostRef=${WAKE_HOST_REF} (host:wake:write among scopes)"
+else
+ fail "cannot mint RPC token for hostRef=${WAKE_HOST_REF} -- is ${DEV_EMAIL} associated to it? Seed: bash scripts/e2e/seed-stateless-host.sh"
+ print_results; exit 1
+fi
+
+# ======================================================================
+# Prep 1 — storm fixtures that will be DELETED mid-storm (bundles must
+# exist first: deleting a bundle-less Host proves nothing)
+# ======================================================================
+header "Prep — pre-create ${STORM_DELETE_COUNT} delete-target fixture Hosts"
+ensure_fixture_secret
+for h in "${STORM_DELETE_HOSTS[@]}"; do
+ apply_storm_host "$h" false
+done
+# shellcheck disable=SC2329 # invoked by name via wait_until
+_delete_targets_materialized_probe() {
+ local h
+ for h in "${STORM_DELETE_HOSTS[@]}"; do
+ kctl -n "$MCP_HOST_NS" get deployment "$h" >/dev/null 2>&1 || return 1
+ done
+}
+if wait_until "$STORM_PREP_MATERIALIZE_DEADLINE_S" 3 \
+ "delete-target bundles (Deployments) to materialize" \
+ _delete_targets_materialized_probe storm_diagnostics; then
+ ok "all ${STORM_DELETE_COUNT} delete-target Hosts have materialized bundles"
+else
+ fail "delete-target bundles did not materialize within ${STORM_PREP_MATERIALIZE_DEADLINE_S}s — cannot run a meaningful mid-storm delete"
+ print_results; exit 1
+fi
+
+# ======================================================================
+# Prep 2 — ensure the wake target is SUSPENDED (idle-driven, supported
+# path; shortened cadences only if needed, restored in the trap)
+# ======================================================================
+header "Prep — wake target suspension (${WAKE_HOST_REF})"
+if _wake_target_suspended_probe; then
+ ok "wake target already suspended (state=suspended, replicas=0)"
+else
+ save_and_set_hcc_cadences || { print_results; exit 1; }
+ if wait_until "$STORM_SUSPEND_WINDOW_S" 5 \
+ "wake target ${WAKE_HOST_REF} to idle-suspend" \
+ _wake_target_suspended_probe _wake_target_diag; then
+ ok "wake target suspended via idle expiry (supported D8 path)"
+ else
+ fail "wake target did not suspend within ${STORM_SUSPEND_WINDOW_S}s (state=$(wake_lifecycle_state)) — cannot exercise the mid-storm wake ingredient"
+ print_results; exit 1
+ fi
+fi
+
+# ======================================================================
+# Prep 3 — metrics baseline (scrape A) + pre-storm HCC pod identity
+# ======================================================================
+header "Prep — metrics baseline (scrape A)"
+SCRAPE_A="${WORK_DIR}/metrics-A.prom"
+SCRAPE_B="${WORK_DIR}/metrics-B.prom"
+SCRAPE_C1="${WORK_DIR}/metrics-C1.prom"
+SCRAPE_C2="${WORK_DIR}/metrics-C2.prom"
+HCC_POD_A="$(hcc_pod_name)"
+if [[ -z "$HCC_POD_A" ]]; then
+ fail "no Running HCC pod found for baseline identity"; storm_diagnostics; print_results; exit 1
+fi
+if scrape_hcc_metrics "$SCRAPE_A" "$HCC_POD_A"; then
+ ok "baseline scrape A captured (pod ${HCC_POD_A})"
+else
+ fail "could not scrape HCC ${HCC_METRICS_PATH} for baseline"; print_results; exit 1
+fi
+
+# ======================================================================
+# STORM — overlapped ingredients (timestamps recorded for A1)
+# ======================================================================
+header "STORM — overlapped create/delete/wake/kill (run-id ${RUN_ID})"
+STORM_HALF=$(( STORM_CREATE_COUNT / 2 ))
+
+T_CREATE_FIRST_MS="$(now_ms)"
+i=0
+for h in "${STORM_CREATED_HOSTS[@]}"; do
+ i=$((i + 1))
+ [[ $i -gt $STORM_HALF ]] && break
+ # Mixed lifecycle: even index stateless, odd stateful (Addendum 5.1).
+ if (( i % 2 == 0 )); then apply_storm_host "$h" true; else apply_storm_host "$h" false; fi
+done
+log "storm: first ${STORM_HALF} Host creations issued"
+
+T_DELETE_MS="$(now_ms)"
+for h in "${STORM_DELETE_HOSTS[@]}"; do
+ kctl -n "$MCP_HOST_NS" delete host "$h" --wait=false >/dev/null || {
+ fail "storm: mid-storm delete of Host ${h} failed"; print_results; exit 1; }
+done
+log "storm: ${STORM_DELETE_COUNT} mid-storm Host deletions issued"
+
+T_WAKE_MS="$(now_ms)"
+if post_wake; then
+ log "storm: wake POST accepted for ${WAKE_HOST_REF} (HTTP ${WAKE_STATUS})"
+else
+ fail "storm: mid-storm wake POST failed for ${WAKE_HOST_REF}"; print_results; exit 1
+fi
+
+# Scrape B: last look at the pre-kill pod's counters, immediately before
+# the kill (samples still in flight at process death are a recorded gap).
+HCC_POD_B="$(hcc_pod_name)"
+if [[ "$HCC_POD_B" != "$HCC_POD_A" ]]; then
+ fail "storm: HCC pod changed unexpectedly before the kill (${HCC_POD_A} -> ${HCC_POD_B:-<none>}) — counter deltas would be invalid"
+ storm_diagnostics; print_results; exit 1
+fi
+if ! scrape_hcc_metrics "$SCRAPE_B" "$HCC_POD_B"; then
+ fail "storm: could not scrape HCC metrics immediately before the kill"; print_results; exit 1
+fi
+log "storm: pre-kill scrape B captured (pod ${HCC_POD_B})"
+
+T_KILL_MS="$(now_ms)"
+kctl -n "$CONTROL_NS" delete pod "$HCC_POD_B" --wait=false >/dev/null || {
+ fail "storm: could not delete HCC pod ${HCC_POD_B}"; print_results; exit 1; }
+log "storm: HCC pod ${HCC_POD_B} kill issued (forces LIST->WATCH recovery under load)"
+
+i=0
+for h in "${STORM_CREATED_HOSTS[@]}"; do
+ i=$((i + 1))
+ [[ $i -le $STORM_HALF ]] && continue
+ if (( i % 2 == 0 )); then apply_storm_host "$h" true; else apply_storm_host "$h" false; fi
+done
+T_CREATE_LAST_MS="$(now_ms)"
+log "storm: remaining $(( STORM_CREATE_COUNT - STORM_HALF )) Host creations issued"
+
+# ─── A1: concurrency evidence ─────────────────────────────────────────
+header "A1 — storm concurrency (recorded start timestamps)"
+printf ' %-28s %s\n' 'ingredient' 'start (epoch-ms)'
+printf ' %-28s %s\n' 'create[first]' "$T_CREATE_FIRST_MS"
+printf ' %-28s %s\n' 'delete[batch]' "$T_DELETE_MS"
+printf ' %-28s %s\n' 'wake[POST]' "$T_WAKE_MS"
+printf ' %-28s %s\n' 'hcc-kill' "$T_KILL_MS"
+printf ' %-28s %s\n' 'create[last]' "$T_CREATE_LAST_MS"
+if [[ "$T_CREATE_FIRST_MS" -lt "$T_DELETE_MS" && "$T_DELETE_MS" -lt "$T_WAKE_MS" \
+ && "$T_WAKE_MS" -lt "$T_KILL_MS" && "$T_KILL_MS" -lt "$T_CREATE_LAST_MS" ]]; then
+ ok "A1: deletes, wake, and HCC kill all started strictly inside the creation span (genuinely overlapped, not sequential phases)"
+else
+ fail "A1: storm ingredient timestamps are not interleaved (first=${T_CREATE_FIRST_MS} delete=${T_DELETE_MS} wake=${T_WAKE_MS} kill=${T_KILL_MS} last=${T_CREATE_LAST_MS})"
+ print_results; exit 1
+fi
+
+# ======================================================================
+# Convergence — replacement HCC pod, then all created Hosts' Deployments
+# ======================================================================
+header "Convergence — replacement HCC pod + created-Host materialization"
+# shellcheck disable=SC2329 # invoked by name via wait_until
+_new_hcc_pod_probe() {
+ local name; name="$(hcc_pod_name)"
+ [[ -n "$name" && "$name" != "$HCC_POD_B" ]]
+}
+if wait_until "$STORM_HCC_READY_DEADLINE_S" 2 "replacement HCC pod after the kill" \
+ _new_hcc_pod_probe storm_diagnostics; then
+ HCC_POD_C="$(hcc_pod_name)"
+ ok "replacement HCC pod Running: ${HCC_POD_C}"
+else
+ fail "no replacement HCC pod within ${STORM_HCC_READY_DEADLINE_S}s of the kill"
+ print_results; exit 1
+fi
+
+# shellcheck disable=SC2329 # invoked by name via wait_until
+_all_created_deploys_probe() {
+ local h
+ for h in "${STORM_CREATED_HOSTS[@]}"; do
+ kctl -n "$MCP_HOST_NS" get deployment "$h" >/dev/null 2>&1 || return 1
+ done
+}
+if wait_until "$STORM_CONVERGENCE_DEADLINE_S" 3 \
+ "all ${STORM_CREATE_COUNT} created Hosts' Deployments to exist" \
+ _all_created_deploys_probe storm_diagnostics; then
+ ok "all ${STORM_CREATE_COUNT} created Hosts have Deployments"
+else
+ fail "created-Host Deployments incomplete after ${STORM_CONVERGENCE_DEADLINE_S}s — starvation or lost events"
+ print_results; exit 1
+fi
+
+# ─── Scrape C1 (M2): taken IMMEDIATELY after created-Host convergence so
+# post-storm quiet-period samples cannot dilute the urgent p95 (A2) —
+# recovery (A4) necessarily completed before any post-kill Deployment
+# materialized. A6/A7 counters are read later from scrape C2, after the
+# A5 cleanup convergence, so their outcome counters are settled. ─────────
+header "Metrics — early post-convergence scrape C1 (replacement pod)"
+HCC_POD_C_NOW="$(hcc_pod_name)"
+if [[ -z "$HCC_POD_C_NOW" || "$HCC_POD_C_NOW" != "$HCC_POD_C" ]]; then
+ fail "replacement HCC pod changed again before scrape C1 (${HCC_POD_C} -> ${HCC_POD_C_NOW:-<none>}) — an unexpected second restart invalidates the counter windows"
+ storm_diagnostics; print_results; exit 1
+fi
+if ! scrape_hcc_metrics "$SCRAPE_C1" "$HCC_POD_C"; then
+ fail "could not scrape HCC metrics (C1) on replacement pod ${HCC_POD_C}"; print_results; exit 1
+fi
+log "scrape C1 captured (replacement pod ${HCC_POD_C})"
+
+# ─── A3: per-host materialization <= 20s from ITS OWN creation ───────
+header "A3 — per-host materialization (budget ${STORM_MATERIALIZATION_BUDGET_S}s, §14.2)"
+MAT_ROWS="${WORK_DIR}/materialization.rows"
+: >"$MAT_ROWS"
+for h in "${STORM_CREATED_HOSTS[@]}"; do
+ hc="$(kctl -n "$MCP_HOST_NS" get host "$h" -o jsonpath='{.metadata.creationTimestamp}' 2>/dev/null || true)"
+ dc="$(kctl -n "$MCP_HOST_NS" get deployment "$h" -o jsonpath='{.metadata.creationTimestamp}' 2>/dev/null || true)"
+ if [[ -z "$hc" || -z "$dc" ]]; then
+ fail "A3: missing creationTimestamp for ${h} (host='${hc}' deploy='${dc}')"
+ print_results; exit 1
+ fi
+ printf '%s %s %s\n' "$h" "$hc" "$dc" >>"$MAT_ROWS"
+done
+if MAT_ROWS="$MAT_ROWS" BUDGET_S="$STORM_MATERIALIZATION_BUDGET_S" python3 <<'PY'
+import datetime, os, sys
+
+def ms(v):
+ return int(datetime.datetime.fromisoformat(v.replace("Z", "+00:00")).timestamp() * 1000)
+
+budget = int(os.environ["BUDGET_S"])
+rows = []
+for line in open(os.environ["MAT_ROWS"], encoding="utf-8"):
+ host, host_ts, dep_ts = line.split()
+ delta = round((ms(dep_ts) - ms(host_ts)) / 1000.0, 3)
+ rows.append((host, delta))
+ print(f" {host}: Host->Deployment {delta:.1f}s ({'within' if delta <= budget else 'OVER_BUDGET'})")
+worst = max(rows, key=lambda r: r[1])
+print(f" worst case: {worst[0]} at {worst[1]:.1f}s (budget {budget}s)")
+offenders = [r for r in rows if r[1] > budget]
+if offenders:
+ print(" OVER BUDGET: " + ", ".join(f"{h}={d:.1f}s" for h, d in offenders))
+ sys.exit(1)
+PY
+then
+ ok "A3: every created Host materialized <= ${STORM_MATERIALIZATION_BUDGET_S}s from its own creation (no starvation)"
+else
+ fail "A3: at least one created Host exceeded the ${STORM_MATERIALIZATION_BUDGET_S}s materialization budget (offenders listed above)"
+ storm_diagnostics; print_results; exit 1
+fi
+
+# ─── A8: wake ingredient integrity ────────────────────────────────────
+header "A8 — mid-storm wake converges (bound ${STORM_WAKE_READY_BUDGET_S}s)"
+# shellcheck disable=SC2329 # invoked by name via wait_until
+_wake_converged_probe() {
+ local st; st="$(wake_lifecycle_state)"
+ [[ -n "$st" && "$st" != 'suspended' ]] || return 1
+ wake_ready_pod_exists
+}
+wake_elapsed_s=$(( ( $(now_ms) - T_WAKE_MS ) / 1000 ))
+wake_remaining_s=$(( STORM_WAKE_READY_BUDGET_S - wake_elapsed_s ))
+[[ "$wake_remaining_s" -lt 1 ]] && wake_remaining_s=1
+if wait_until "$wake_remaining_s" 3 "woken host ${WAKE_HOST_REF} to leave suspended + reach a Ready pod" \
+ _wake_converged_probe _wake_target_diag; then
+ ok "A8: wake converged $(( ( $(now_ms) - T_WAKE_MS ) / 1000 ))s after the wake POST (state=$(wake_lifecycle_state))"
+else
+ fail "A8: woken host did not reach Ready within ${STORM_WAKE_READY_BUDGET_S}s of the wake POST (state=$(wake_lifecycle_state)) — the wake ingredient did not complete"
+ print_results; exit 1
+fi
+
+# ─── A5: deleted bundles fully cleaned (ownership-label leftover check) ──
+header "A5 — deleted-Host bundle cleanup across ${BUNDLE_NAMESPACES}"
+# FAIL-CLOSED (B2): the probe succeeds ONLY on positive evidence — the CR
+# absence must be a confirmed NotFound and every leftover list must have
+# been readable. A kubectl error keeps the probe failing, so an API outage
+# ends in the bounded deadline FAILING (with the read errors on stderr),
+# never in a false "cleanup complete".
+# shellcheck disable=SC2329 # invoked by name via wait_until
+_deleted_hosts_clean_probe() {
+ local h leftovers
+ for h in "${STORM_DELETE_HOSTS[@]}"; do
+ host_absent_confirmed "$h" || return 1
+ leftovers="$(collect_children "$h")" || return 1
+ [[ -z "$leftovers" ]] || return 1
+ done
+}
+# shellcheck disable=SC2329 # invoked by name via wait_until
+_deleted_hosts_diag() {
+ local h
+ {
+ echo "----- deleted-host leftover diagnostics -----"
+ for h in "${STORM_DELETE_HOSTS[@]}"; do
+ echo "host ${h}:"
+ kctl -n "$MCP_HOST_NS" get host "$h" -o wide 2>&1 || true
+ collect_children "$h" 2>&1 || true
+ done
+ kctl -n "$CONTROL_NS" logs "deploy/${HCC_DEPLOY}" --tail=60 2>&1 || true
+ } >&2
+}
+if wait_until "$STORM_CLEANUP_DEADLINE_S" 3 \
+ "deleted Hosts' CRs + owned bundles to disappear" \
+ _deleted_hosts_clean_probe _deleted_hosts_diag; then
+ ok "A5: every deleted Host's CR and owned bundle fully cleaned (confirmed NotFound + zero ownership-labeled leftovers in ${BUNDLE_NAMESPACES})"
+else
+ fail "A5: deleted-Host cleanup incomplete OR unverifiable after ${STORM_CLEANUP_DEADLINE_S}s (leftovers/read failures listed above) — lost delete, cleanup regression, or an API read that could not be verified (fail-closed)"
+ print_results; exit 1
+fi
+
+# ======================================================================
+# Metrics adjudication (scrape C2 after cleanup convergence, then A2/A4/A6/A7)
+# ======================================================================
+header "Metrics — settled scrape C2 + §14.1 adjudication"
+HCC_POD_C_NOW="$(hcc_pod_name)"
+if [[ -z "$HCC_POD_C_NOW" || "$HCC_POD_C_NOW" != "$HCC_POD_C" ]]; then
+ fail "replacement HCC pod changed between scrapes C1 and C2 (${HCC_POD_C} -> ${HCC_POD_C_NOW:-<none>}) — an unexpected second restart invalidates the counter windows"
+ storm_diagnostics; print_results; exit 1
+fi
+if ! scrape_hcc_metrics "$SCRAPE_C2" "$HCC_POD_C"; then
+ fail "could not scrape HCC metrics (C2) on replacement pod ${HCC_POD_C}"; print_results; exit 1
+fi
+log "scrape C2 captured (replacement pod ${HCC_POD_C}; A6/A7 counters settled post-A5)"
+
+# One python pass performs the four metric assertions and emits one
+# VERDICT|<name>|PASS/FAIL|<detail> line each. python exits nonzero only
+# when it cannot parse its inputs (a hard failure of the gate itself).
+METRIC_VERDICTS="${WORK_DIR}/metric-verdicts.txt"
+if ! SCRAPE_A="$SCRAPE_A" SCRAPE_B="$SCRAPE_B" SCRAPE_C1="$SCRAPE_C1" SCRAPE_C2="$SCRAPE_C2" \
+ P95_BUDGET_S="$STORM_URGENT_P95_BUDGET_S" RECOVERY_BUDGET_S="$STORM_WATCH_RECOVERY_BUDGET_S" \
+ MIN_URGENT_SAMPLES="$STORM_CREATE_COUNT" \
+ python3 >"$METRIC_VERDICTS" <<'PY'
+import os, re, sys
+from collections import defaultdict
+
+LINE = re.compile(r'^([a-zA-Z_:][a-zA-Z0-9_:]*)(\{[^}]*\})?\s+(\S+)')
+LABEL = re.compile(r'(\w+)="([^"]*)"')
+
+def load(path):
+ samples, types = [], set()
+ for line in open(path, encoding="utf-8", errors="replace"):
+ if line.startswith("# TYPE "):
+ types.add(line.split()[2])
+ continue
+ if line.startswith("#"):
+ continue
+ m = LINE.match(line)
+ if not m:
+ continue
+ labels = dict(LABEL.findall(m.group(2) or ""))
+ try:
+ value = float(m.group(3))
+ except ValueError:
+ continue
+ samples.append((m.group(1), labels, value))
+ return samples, types
+
+# Two replacement-pod windows (M2): C1 is scraped immediately after
+# created-Host convergence (A2 p95 undiluted by quiet-period samples; A4
+# recovery necessarily recorded by then); C2 is scraped after the A5
+# cleanup convergence (A6/A7 outcome counters settled). Pod identity for
+# A/B and C1/C2 is guarded in bash before this adjudication runs.
+a, _ = load(os.environ["SCRAPE_A"])
+b, _ = load(os.environ["SCRAPE_B"])
+c1, _ = load(os.environ["SCRAPE_C1"])
+c2, c2_types = load(os.environ["SCRAPE_C2"])
+
+def buckets(samples, metric, match):
+ """Cumulative histogram buckets {le: count} summed over matching series."""
+ out = defaultdict(float)
+ for name, labels, value in samples:
+ if name != metric + "_bucket":
+ continue
+ if any(labels.get(k) != v for k, v in match.items()):
+ continue
+ out[labels.get("le", "")] += value
+ return out
+
+def counter(samples, metric, label, value):
+ total = 0.0
+ for name, labels, val in samples:
+ if name == metric and labels.get(label) == value:
+ total += val
+ return total
+
+def le_key(le):
+ return float("inf") if le == "+Inf" else float(le)
+
+verdicts = []
+
+# ── A2: urgent queue-wait p95 <= budget across (B-A) + C1 ─────────────
+qm = os.environ["QUEUE_WAIT_METRIC"]
+budget = float(os.environ["P95_BUDGET_S"])
+window_note = "windows: pre-kill delta (B-A) + replacement pod C1, which includes replacement-pod recovery traffic"
+pre_a = buckets(a, qm, {"lane": "urgent"})
+pre_b = buckets(b, qm, {"lane": "urgent"})
+post = buckets(c1, qm, {"lane": "urgent"})
+combined = defaultdict(float)
+reset = False
+for le in set(pre_a) | set(pre_b) | set(post):
+ delta = pre_b.get(le, 0.0) - pre_a.get(le, 0.0)
+ if delta < 0:
+ reset = True
+ combined[le] = delta + post.get(le, 0.0)
+if reset:
+ verdicts.append(("A2-urgent-queue-wait-p95", False,
+ "negative bucket delta between scrapes A and B (unexpected counter reset)"))
+else:
+ total = combined.get("+Inf", 0.0)
+ min_samples = float(os.environ["MIN_URGENT_SAMPLES"])
+ if total < min_samples:
+ verdicts.append(("A2-urgent-queue-wait-p95", False,
+ f"only {total:.0f} urgent samples in the storm window (need >= {min_samples:.0f} — "
+ "the storm did not exercise the urgent lane, cannot claim a p95)"))
+ else:
+ p95_ub = None
+ for le in sorted(combined, key=le_key):
+ if total > 0 and combined[le] / total >= 0.95:
+ p95_ub = le
+ break
+ dist = " ".join(f"le{le}={combined[le]:.0f}" for le in sorted(combined, key=le_key))
+ if p95_ub is not None and le_key(p95_ub) <= budget:
+ verdicts.append(("A2-urgent-queue-wait-p95", True,
+ f"p95 <= {p95_ub}s over {total:.0f} samples (budget {budget:.0f}s; {dist}; {window_note}; "
+ "gap: samples in flight between scrape B and process death are unrecoverable)"))
+ else:
+ verdicts.append(("A2-urgent-queue-wait-p95", False,
+ f"p95 bucket upper bound {p95_ub} exceeds {budget:.0f}s over {total:.0f} samples ({dist}; {window_note})"))
+
+# ── A4: watch recovery <= budget on the replacement pod (C1) ──────────
+wm = os.environ["WATCH_RECOVERY_METRIC"]
+rbudget = os.environ["RECOVERY_BUDGET_S"]
+succ = buckets(c1, wm, {"phase": "total", "outcome": "success"})
+failed_total = buckets(c1, wm, {"phase": "total", "outcome": "failure"}).get("+Inf", 0.0)
+succ_total = succ.get("+Inf", 0.0)
+within = succ.get(rbudget, 0.0)
+if failed_total > 0:
+ verdicts.append(("A4-watch-recovery", False,
+ f"{failed_total:.0f} failed recovery attempt(s) on the replacement pod"))
+elif succ_total < 1:
+ verdicts.append(("A4-watch-recovery", False,
+ "no successful LIST->WATCH recovery sample on the replacement pod"))
+elif within != succ_total:
+ verdicts.append(("A4-watch-recovery", False,
+ f"{succ_total - within:.0f} of {succ_total:.0f} recovery sample(s) exceeded {rbudget}s"))
+else:
+ bound = next((le for le in sorted(succ, key=le_key) if succ[le] == succ_total), "+Inf")
+ verdicts.append(("A4-watch-recovery", True,
+ f"{succ_total:.0f} recovery sample(s), all <= {bound}s (budget {rbudget}s)"))
+
+# ── A7: fleet coalescing held (settled window C2) ─────────────────────
+fm = os.environ["FLEET_METRIC"]
+pre_failed = counter(b, fm, "result", "failed") - counter(a, fm, "result", "failed")
+post_started = counter(c2, fm, "result", "started")
+post_coalesced = counter(c2, fm, "result", "coalesced")
+post_trailing = counter(c2, fm, "result", "trailing")
+post_failed = counter(c2, fm, "result", "failed")
+problems = []
+if pre_failed > 0 or post_failed > 0:
+ problems.append(f"fleet pass failures (pre={pre_failed:.0f} post={post_failed:.0f})")
+if post_started < 1:
+ problems.append("no fleet pass started on the replacement pod (recovery convergence missing)")
+if post_coalesced < 1:
+ problems.append("no coalesced fleet request on the replacement pod (recovery request should land against the active initial pass)")
+if post_trailing > post_coalesced:
+ problems.append(f"trailing={post_trailing:.0f} > coalesced={post_coalesced:.0f} (violates the single-pending-slot structure)")
+detail = (f"started={post_started:.0f} coalesced={post_coalesced:.0f} "
+ f"trailing={post_trailing:.0f} failed={post_failed:.0f} (pre-kill failed delta={pre_failed:.0f})")
+if problems:
+ verdicts.append(("A7-fleet-coalescing", False, "; ".join(problems) + f" [{detail}]"))
+else:
+ verdicts.append(("A7-fleet-coalescing", True, detail))
+
+# ── A6: delete-cleanup counters consistent (settled window C2) ────────
+dm = os.environ["DELETE_CLEANUP_METRIC"]
+if dm not in c2_types:
+ verdicts.append(("A6-delete-cleanup-counters", False,
+ f"{dm} not registered on the running image — is the branch HCC image deployed?"))
+else:
+ queued = counter(c2, dm, "outcome", "queued")
+ confirmed = counter(c2, dm, "outcome", "confirmed")
+ completed = counter(c2, dm, "outcome", "completed")
+ retried = counter(c2, dm, "outcome", "retried")
+ superseded = counter(c2, dm, "outcome", "superseded")
+ detail = (f"queued={queued:.0f} confirmed={confirmed:.0f} completed={completed:.0f} "
+ f"retried={retried:.0f} superseded={superseded:.0f}")
+ if retried == 0 and superseded == 0 and queued == confirmed == completed:
+ note = "" if queued > 0 else " (all-zero: deletes handled by the direct watch-DELETE path; A5 proved cleanup)"
+ verdicts.append(("A6-delete-cleanup-counters", True, detail + note))
+ else:
+ verdicts.append(("A6-delete-cleanup-counters", False,
+ f"inconsistent outcomes — lost or failed delete cleanup [{detail}]"))
+
+for name, passed, detail in verdicts:
+ print(f"VERDICT|{name}|{'PASS' if passed else 'FAIL'}|{detail}")
+PY
+then
+ fail "metric adjudication crashed (could not parse the §14.1 scrapes) — see ${WORK_DIR}"
+ print_results; exit 1
+fi
+
+VERDICT_COUNT=0
+while IFS='|' read -r tag name verdict detail; do
+ [[ "$tag" == 'VERDICT' ]] || continue
+ VERDICT_COUNT=$((VERDICT_COUNT + 1))
+ if [[ "$verdict" == 'PASS' ]]; then
+ ok "${name}: ${detail}"
+ else
+ fail "${name}: ${detail}"
+ fi
+done <"$METRIC_VERDICTS"
+if [[ "$VERDICT_COUNT" -ne 4 ]]; then
+ fail "metric adjudication emitted ${VERDICT_COUNT}/4 verdicts — truncated output is a failure, not a pass"
+fi
+
+# ======================================================================
+# Teardown — delete ONLY this run's fixtures; fail-loud leftover check.
+# The profile and seeded data (including the wake target) stay.
+# ======================================================================
+header "Teardown — storm fixtures (${FIXTURE_RUN_KEY}=${RUN_ID})"
+if [[ "${KEEP_FIXTURES:-}" == '1' ]]; then
+ warn "KEEP_FIXTURES=1 — leaving fixtures in place for diagnosis (run-id ${RUN_ID})"
+ TEARDOWN_DONE=1
+else
+ STORM_SEL="${FIXTURE_LABEL_KEY}=${FIXTURE_LABEL_VAL},${FIXTURE_RUN_KEY}=${RUN_ID}"
+ kctl -n "$MCP_HOST_NS" delete host -l "$STORM_SEL" --wait=false >/dev/null 2>&1 || \
+ warn "teardown: label-selector Host deletion returned nonzero (leftover check below is authoritative)"
+ kctl -n "$MCP_HOST_NS" delete secret -l "$STORM_SEL" --wait=false >/dev/null 2>&1 || \
+ warn "teardown: label-selector Secret deletion returned nonzero (leftover check below is authoritative)"
+
+ # FAIL-CLOSED (B2): a kubectl list failure must never read as "all
+ # gone" — the probe fails (with the error on stderr) until the API
+ # positively returns an empty list, and the bounded deadline then FAILS.
+ # shellcheck disable=SC2329 # invoked by name via wait_until
+ _storm_hosts_gone_probe() {
+ local out
+ if ! out="$(kctl -n "$MCP_HOST_NS" get host -l "$STORM_SEL" -o name 2>"${WORK_DIR}/hosts-gone.err")"; then
+ echo "_storm_hosts_gone_probe: kubectl list FAILED: $(cat "${WORK_DIR}/hosts-gone.err" 2>/dev/null)" >&2
+ return 1
+ fi
+ [[ -z "$out" ]]
+ }
+ if wait_until "$STORM_TEARDOWN_DEADLINE_S" 3 "storm fixture Hosts (${STORM_SEL}) deletion" \
+ _storm_hosts_gone_probe storm_diagnostics; then
+ ok "teardown: all storm fixture Hosts deleted via the supported CR path"
+ else
+ fail "teardown: storm fixture Hosts still present after ${STORM_TEARDOWN_DEADLINE_S}s (run-id ${RUN_ID})"
+ fi
+
+ # FAIL-CLOSED (B2): an unverifiable read counts as a leftover — the teardown
+ # check may only pass on positive evidence of absence. Convergence-aware: a
+ # leftover with a deletionTimestamp is CONVERGING (its delete WAS issued; a
+ # finalizer like a workspace PVC's kubernetes.io/pvc-protection is draining for
+ # the deleting pod's grace) — allow it a bounded extension. A leftover with NO
+ # deletionTimestamp means the delete was NEVER issued (a real cleanup gap) —
+ # fail immediately, no wait. An unverifiable read is fail-closed.
+ TEARDOWN_LEFTOVER=0
+ teardown_converge_deadline=$((SECONDS + STORM_TEARDOWN_CONVERGE_S))
+ while :; do
+ TEARDOWN_LEFTOVER=0; teardown_orphan=0; teardown_unverifiable=0; teardown_report=''
+ for h in "${STORM_CREATED_HOSTS[@]}" "${STORM_DELETE_HOSTS[@]}"; do
+ if ! leftovers="$(collect_children "$h")"; then
+ teardown_report+=" ${h}: kubectl read FAILED (unverifiable, fail-closed)"$'\n'
+ TEARDOWN_LEFTOVER=$((TEARDOWN_LEFTOVER + 1)); teardown_unverifiable=1
+ continue
+ fi
+ if [[ -z "$leftovers" ]]; then
+ continue
+ fi
+ while IFS= read -r res; do
+ if [[ -z "$res" ]]; then
+ continue
+ fi
+ r_ns="${res%%/*}"; r_kn="${res#*/}"
+ if dts="$(kctl -n "$r_ns" get "$r_kn" -o jsonpath='{.metadata.deletionTimestamp}' 2>/dev/null)"; then
+ if [[ -n "$dts" ]]; then
+ teardown_report+=" ${res} — Terminating since ${dts} (converging)"$'\n'
+ TEARDOWN_LEFTOVER=$((TEARDOWN_LEFTOVER + 1))
+ else
+ teardown_report+=" ${res} — NO deletionTimestamp (delete never issued — REAL cleanup gap)"$'\n'
+ TEARDOWN_LEFTOVER=$((TEARDOWN_LEFTOVER + 1)); teardown_orphan=1
+ fi
+ fi
+ # get failed (NotFound between collect and read) => converged; not a leftover
+ done <<< "$leftovers"
+ done
+ if [[ "$TEARDOWN_LEFTOVER" -eq 0 ]]; then
+ break
+ fi
+ # A never-issued delete or an unverifiable read is a hard finding — do not wait.
+ if [[ "$teardown_orphan" -eq 1 || "$teardown_unverifiable" -eq 1 ]]; then
+ break
+ fi
+ if [[ "$SECONDS" -ge "$teardown_converge_deadline" ]]; then
+ break
+ fi
+ sleep 3
+ done
+ if [[ "$TEARDOWN_LEFTOVER" -gt 0 ]]; then
+ warn "teardown: ownership-labeled leftovers after up to ${STORM_TEARDOWN_CONVERGE_S}s convergence extension:"
+ printf '%s' "$teardown_report" >&2
+ fi
+ if ! sec_out="$(kctl -n "$MCP_HOST_NS" get secret -l "$STORM_SEL" -o name 2>"${WORK_DIR}/secret-gone.err")"; then
+ warn "teardown: could not verify fixture Secret deletion: $(cat "${WORK_DIR}/secret-gone.err" 2>/dev/null) — counting as leftover"
+ TEARDOWN_LEFTOVER=$((TEARDOWN_LEFTOVER + 1))
+ elif [[ -n "$sec_out" ]]; then
+ warn "teardown: fixture Secret still present (${STORM_SEL})"
+ TEARDOWN_LEFTOVER=$((TEARDOWN_LEFTOVER + 1))
+ fi
+ if [[ "$TEARDOWN_LEFTOVER" -eq 0 ]]; then
+ ok "teardown: zero storm-fixture leftovers across ${BUNDLE_NAMESPACES} (profile and seeded data untouched)"
+ else
+ fail "teardown: ${TEARDOWN_LEFTOVER} storm fixture subject(s) left resources behind (run-id ${RUN_ID}) — investigate before trusting results"
+ fi
+ TEARDOWN_DONE=1
+fi
+
+# M3: on the success path a failed cadence restore must FAIL the gate
+# (restore_hcc_env_strict registers fail() and leaves HCC_ENV_SAVED for
+# the trap's best-effort retry); the EXIT trap keeps the lenient restore.
+restore_hcc_env_strict
+
+print_results
+if [[ "$g_fail" -gt 0 ]]; then
+ exit 1
+fi
+exit 0
diff --git a/scripts/e2e/measure-host-bundle-reconcile.sh b/scripts/e2e/measure-host-bundle-reconcile.sh
index f1e806b68..1eb66d287 100644
--- a/scripts/e2e/measure-host-bundle-reconcile.sh
+++ b/scripts/e2e/measure-host-bundle-reconcile.sh
@@ -19,6 +19,10 @@
# Addendum 1 bundle-wide measurement mandate (ALL services this PR
# touches: mcp-host bundle + channel-reader bundle + wake +
# independent admission + non-regression side-clock)
+# Addendum 4.7 delete-while-pass-active runtime evidence (#827):
+# CR deletion issued while a full fleet pass is demonstrably
+# active must converge to exactly-one complete cleanup with no
+# resurrection (see the delete-during-pass step)
#
# House style: mirrors scripts/e2e/e2e-lib.sh (kctl wrapper, log/ok/fail
# helpers, truncate_rfc1123) and scripts/e2e/stateless-cold-start-measure.sh
@@ -63,16 +67,28 @@
# ADMISSION_BLOCKER_READY (independent-admission subcommand) set to 1 to
# assert the orchestrator has engaged a deterministic
# HCC block/slow-pass. ADMISSION_BLOCKER describes it.
+# DELETE_DURING_PASS set to 1 to run the Addendum 4.7
+# delete-while-pass-active step inside `all`.
+# Opt-in because it RESTARTS the HCC pod (a
+# supported operational event) to force a
+# demonstrable full fleet pass; existing callers
+# are unaffected by default.
# KEEP_FIXTURES set to 1 to skip teardown (diagnosis).
#
# SUBCOMMANDS (default: all)
# all bundle + independent-admission(if hook ready) +
-# metrics + sideclock, then teardown.
+# metrics + sideclock + delete-during-pass(if
+# DELETE_DURING_PASS=1), then teardown.
# bundle phase 1 only (stateful control Host + stateless Host)
# wake phase 2 only (orchestrator calls after suspend+wake)
# independent-admission phase 3 only (needs ADMISSION_BLOCKER_READY=1)
# metrics phase 4 only (HCC §14.1 scrape)
# sideclock phase 5 only (Context/McpServer non-regression)
+# delete-during-pass Addendum 4.7 step only (#827): delete a fixture
+# Host WHILE a full fleet pass is demonstrably
+# active (HCC restart -> 'initial Host
+# reconciliation'); assert exactly-one complete
+# cleanup + no resurrection. Restarts the HCC pod.
# teardown delete only this run's fixtures; fail-loud on leftover
#
# EXIT CODES
@@ -122,6 +138,25 @@ readonly SLO_MATERIALIZE_S=20 # Host creation -> Deployment creation
readonly SLO_READY_S=60 # Host creation -> Pod Ready (warm local gate)
readonly SLO_WAKE_S=45 # wake accepted -> Pod Ready
+# Addendum 4.7 delete-while-pass-active budgets (each constant states its
+# contract; expiry is a hard fail with diagnostics, never a silent skip).
+readonly DELPASS_HCC_READY_DEADLINE_S=120 # replacement HCC pod Running after the restart
+readonly DELPASS_PASS_ACTIVE_DEADLINE_S=60 # initial-pass START marker observed on the new pod
+readonly DELPASS_PASS_COMPLETE_DEADLINE_S=180 # pass COMPLETED marker observed after the delete
+readonly DELPASS_CLEANUP_DEADLINE_S=180 # deleted CR + owned bundle fully gone
+readonly DELPASS_RESURRECTION_SETTLE_S=30 # quiet window before re-asserting nothing came back
+# Bounded EXTENSION for owned children already Terminating (deletionTimestamp
+# set) at the teardown leftover check — e.g. a workspace PVC whose
+# kubernetes.io/pvc-protection finalizer drains for the deleting pod's
+# termination grace. A child with NO deletionTimestamp never gets this
+# extension (the delete was never issued → immediate fail).
+readonly MEASURE_TEARDOWN_CONVERGE_S=120
+# Exact log lines emitted by host-context-controller/src/k8sClient.ts for
+# the startup full fleet pass (reason string 'initial Host reconciliation').
+readonly HCC_PASS_STARTED_MARKER='Running initial Host reconciliation'
+readonly HCC_PASS_COMPLETED_MARKER='Completed Host reconciliation after initial Host reconciliation'
+readonly HCC_PASS_FAILED_MARKER='Host reconciliation after initial Host reconciliation failed'
+
# ─── Colors (mirrors e2e-lib.sh) ──────────────────────────────────────
RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'; CYAN='\033[0;36m'; NC='\033[0m'; BOLD='\033[1m'
@@ -218,26 +253,31 @@ trap cleanup_portforward EXIT
# ======================================================================
# Populated by init_run(): unique, RFC1123-safe host names for this run.
RUN_ID=''; RUN_SLUG=''; RUN_DIR=''
-HOST_CONTROL=''; HOST_STATELESS=''; HOST_PROBE=''; FIXTURE_SECRET=''
+HOST_CONTROL=''; HOST_STATELESS=''; HOST_PROBE=''; HOST_DELPASS=''; FIXTURE_SECRET=''
init_run() {
[[ -n "${RUN_LABEL:-}" ]] || die "RUN_LABEL is required (e.g. baseline | fixed)." 2
[[ -n "${OUT_DIR:-}" ]] || die "OUT_DIR is required." 2
RUN_SLUG="$(sanitize_label "$RUN_LABEL" 15)"
[[ -n "$RUN_SLUG" ]] || die "RUN_LABEL '${RUN_LABEL}' sanitized to empty; pick an alphanumeric label." 2
- RUN_ID="$(now_ms)"; RUN_ID="${RUN_ID: -6}" # 6-digit run discriminator
+ # Run discriminator: epoch-ms tail + 3-digit random suffix. Full epoch-ms
+ # would blow the 34-char host-name budget below; the random suffix removes
+ # the 16.7-minute tail-collision window between runs instead.
+ RUN_ID="$(now_ms)"; RUN_ID="${RUN_ID: -6}$(printf '%03d' $((RANDOM % 1000)))"
RUN_DIR="${OUT_DIR%/}/${RUN_SLUG}-$(now_stamp)"
mkdir -p "$RUN_DIR"
- # Fixture names — keep host name <=35 chars so
- # host-<name>-mcp-host-runtime-tokens stays within the 63-char RFC1123 limit.
+ # Fixture names — keep host name <=34 chars so
+ # host-<name>-mcp-host-runtime-tokens (5+34+24) stays within the 63-char
+ # RFC1123 limit.
local base
base="$(truncate_rfc1123 "m791-${RUN_SLUG}-${RUN_ID}")"
HOST_CONTROL="$(truncate_rfc1123 "${base}-ctl")"
HOST_STATELESS="$(truncate_rfc1123 "${base}-sl")"
HOST_PROBE="$(truncate_rfc1123 "${base}-pr")"
+ HOST_DELPASS="$(truncate_rfc1123 "${base}-dp")"
FIXTURE_SECRET="$(truncate_rfc1123 "${base}-keys")"
log "run dir: ${RUN_DIR}"
- log "fixtures: control=${HOST_CONTROL} stateless=${HOST_STATELESS} probe=${HOST_PROBE} run-id=${RUN_ID}"
+ log "fixtures: control=${HOST_CONTROL} stateless=${HOST_STATELESS} probe=${HOST_PROBE} delpass=${HOST_DELPASS} run-id=${RUN_ID}"
}
ensure_fixture_secret() {
@@ -310,15 +350,25 @@ host_created(){ kctl -n "$MCP_HOST_NS" get host "$1" -o jsonpath='{.metadata.cre
# single JSON array [{namespace,kind,name,creationTimestamp}]. Uses the
# authoritative HCC ownership selector (managed-by + host) — the same
# predicate HostReconciler.isHccOwnedHostResource uses — so nothing is missed.
+#
+# FAIL-CLOSED (mirrors e2e-host-storm-gate.sh collect_children): emits the
+# JSON array on stdout and returns 0 only when EVERY kubectl read
+# succeeded; any read failure prints the captured stderr and flips the
+# return code to 2 ("verification impossible"). Every label-selector list
+# of these standard kinds returns exit 0 with an empty item list when
+# nothing matches, so a nonzero kubectl exit is a real read failure (API
+# outage, RBAC, unknown kind) — callers MUST treat rc=2 as failure, never
+# as "no children".
collect_children_json() {
- local host="$1" ns kind items
+ local host="$1" ns kind items rc=0
local combined='[]'
for ns in $BUNDLE_NAMESPACES; do
for kind in $BUNDLE_KINDS; do
- # -l on two labels; ignore kinds absent in a namespace (get returns []).
if ! items="$(kctl -n "$ns" get "$kind" \
-l "${OWNED_SELECTOR},${HOST_LABEL}=${host}" \
- -o json 2>/dev/null)"; then
+ -o json 2>"${RUN_DIR}/collect-children.err")"; then
+ echo "collect_children_json: kubectl get ${kind} in ${ns} FAILED for host ${host}: $(cat "${RUN_DIR}/collect-children.err" 2>/dev/null)" >&2
+ rc=2
continue
fi
combined="$(NS="$ns" KIND="$kind" ITEMS="$items" ACC="$combined" python3 -c '
@@ -335,12 +385,37 @@ for it in lst:
"kind": os.environ["KIND"],
"name": md.get("name"),
"creationTimestamp": md.get("creationTimestamp"),
+ # Additive: lets the teardown check distinguish a CONVERGING child
+ # (delete issued, finalizer draining) from one never deleted.
+ "deletionTimestamp": md.get("deletionTimestamp"),
})
print(json.dumps(acc))
')"
done
done
printf '%s' "$combined"
+ return "$rc"
+}
+
+# FAIL-CLOSED absence check (mirrors e2e-host-storm-gate.sh): returns 0
+# ONLY when the API positively answered NotFound for the Host. "Present"
+# returns 1; any other kubectl failure (outage, RBAC, timeout) returns 2
+# with the error on stderr — absence must never be inferred from an
+# unreadable API. The match is anchored on the API-server reason
+# '(NotFound)' or the kubectl trailing form naming EXACTLY the requested
+# Host, so a kubeconfig-level `context "..." not found` error can never
+# read as absence-confirmation.
+host_absent_confirmed() {
+ local h="$1" err
+ if kctl -n "$MCP_HOST_NS" get host "$h" -o name >/dev/null 2>"${RUN_DIR}/host-absent.err"; then
+ return 1
+ fi
+ err="$(cat "${RUN_DIR}/host-absent.err" 2>/dev/null || true)"
+ if printf '%s' "$err" | grep -Eq "\(NotFound\)|\"${h}\" not found\$"; then
+ return 0
+ fi
+ echo "host_absent_confirmed: kubectl get host ${h} FAILED without NotFound evidence: ${err}" >&2
+ return 2
}
# Ready-condition + phase for the mcp-host Pod of <host> (podSelector app=<host>).
@@ -375,7 +450,12 @@ pod_diagnostics() {
_emit_bundle_record() {
local host="$1" klass="$2" host_created="$3" note="$4"
local children pod_json rec="${RUN_DIR}/bundle-${host}.json"
- children="$(collect_children_json "$host")"
+ # FAIL-CLOSED: a partial child enumeration would make the bundle record
+ # silently under-report — refuse to emit it instead.
+ if ! children="$(collect_children_json "$host")"; then
+ fail "bundle[${host}]: could not enumerate owned children (kubectl read failed) — refusing to emit a partial record"
+ return 1
+ fi
pod_json="$(host_pod_json "$host")"
HOST="$host" KLASS="$klass" HOST_CREATED="$host_created" CHILDREN="$children" \
POD_JSON="$pod_json" NOTE="$note" \
@@ -483,7 +563,8 @@ measure_bundle_for() {
if ! wait_until "$materialize_deadline" 2 "first owned child of ${host}" _first_child_probe _diag_probe; then
fail "bundle[${host}]: no owned child materialized within ${materialize_deadline}s"
- _emit_bundle_record "$host" "$klass" "$host_created" "readiness=false phase=materialization_timeout" >>"${RUN_DIR}/bundle-rows.md"
+ _emit_bundle_record "$host" "$klass" "$host_created" "readiness=false phase=materialization_timeout" >>"${RUN_DIR}/bundle-rows.md" || \
+ warn "bundle[${host}]: record emission failed on the materialization-timeout path (failure already counted)"
return 1
fi
@@ -492,7 +573,9 @@ measure_bundle_for() {
ready_ok='false'
fi
- _emit_bundle_record "$host" "$klass" "$host_created" "readiness=${ready_ok}" >>"${RUN_DIR}/bundle-rows.md"
+ if ! _emit_bundle_record "$host" "$klass" "$host_created" "readiness=${ready_ok}" >>"${RUN_DIR}/bundle-rows.md"; then
+ return 1
+ fi
if [[ "$ready_ok" == 'true' ]]; then
ok "bundle[${host}]: Pod Ready; bundle materialized (${klass})"
return 0
@@ -788,6 +871,278 @@ PY
return 0
}
+# ======================================================================
+# STEP (Addendum 4.7) — delete-while-pass-active convergence (#827)
+# ======================================================================
+# Proves the #827 integration property: a Host CR deleted WHILE a full
+# fleet pass is demonstrably active converges to exactly-one complete
+# cleanup (CR gone + zero ownership-labeled leftovers across the bundle
+# namespaces — the same predicate teardown uses) and is never resurrected
+# by the in-flight pass or a stale queued reconcile.
+#
+# The full pass is triggered through a supported operational event:
+# deleting the HCC pod. The replacement pod always runs the
+# 'initial Host reconciliation' full pass on startup (k8sClient.ts), so
+# the pass window is deterministic and log-anchored:
+# ACTIVE = START marker present, COMPLETED marker absent
+# the delete is issued only inside that window; the COMPLETED marker is
+# then observed AFTER the delete.
+# Overlap is proven with TWO belts, because the pass can complete inside
+# the ~0.5-2s window between the active-probe read and the delete landing:
+# belt 1 — immediately after the delete succeeds, the logs are re-read
+# once and the step HARD-FAILS if COMPLETED is already present;
+# belt 2 — the COMPLETED line's own `kubectl logs --timestamps` stamp
+# must postdate the delete-issued epoch-ms in the final
+# adjudication.
+# A pass that completes before the delete could be issued is a HARD FAIL
+# ("overlap not established" — re-run), never silently accepted; a pass
+# that FAILS is a hard fail with the controller logs.
+phase_delete_during_pass() {
+ header "STEP — delete-while-pass-active (#827, plan Addendum 4.7)"
+ ensure_fixture_secret
+
+ # 1. Fixture Host with a real bundle (deleting a bundle-less Host would
+ # prove nothing about cleanup).
+ apply_host "$HOST_DELPASS" false
+ __cur_host="$HOST_DELPASS"
+ local materialize_deadline="${MATERIALIZE_DEADLINE_S:-60}"
+ if ! wait_until "$materialize_deadline" 2 "first owned child of ${HOST_DELPASS}" _first_child_probe _diag_probe; then
+ fail "delete-during-pass: fixture bundle did not materialize within ${materialize_deadline}s"
+ return 1
+ fi
+ # shellcheck disable=SC2329 # invoked by name via wait_until
+ _delpass_deploy_probe() { kctl -n "$MCP_HOST_NS" get deployment "$HOST_DELPASS" >/dev/null 2>&1; }
+ if ! wait_until "$materialize_deadline" 2 "Deployment ${HOST_DELPASS}" _delpass_deploy_probe _diag_probe; then
+ fail "delete-during-pass: fixture Deployment did not materialize within ${materialize_deadline}s"
+ return 1
+ fi
+ log "fixture ${HOST_DELPASS} bundle materialized"
+
+ # 2. Trigger the full fleet pass: restart HCC (supported operational
+ # event; the replacement pod runs 'initial Host reconciliation').
+ local old_pod
+ old_pod="$(kctl -n "$CONTROL_NS" get pods -l "app=${HCC_DEPLOY}" \
+ --field-selector=status.phase=Running \
+ -o jsonpath='{.items[0].metadata.name}' 2>/dev/null || true)"
+ if [[ -z "$old_pod" ]]; then
+ fail "delete-during-pass: no Running HCC pod to restart"
+ return 1
+ fi
+ local t_restart_ms; t_restart_ms="$(now_ms)"
+ if ! kctl -n "$CONTROL_NS" delete pod "$old_pod" --wait=false >/dev/null; then
+ fail "delete-during-pass: could not delete HCC pod ${old_pod}"
+ return 1
+ fi
+ log "HCC pod ${old_pod} deleted to force the full fleet pass"
+
+ local new_pod=''
+ # shellcheck disable=SC2329 # invoked by name via wait_until
+ _delpass_new_pod_probe() {
+ local name
+ name="$(kctl -n "$CONTROL_NS" get pods -l "app=${HCC_DEPLOY}" \
+ --field-selector=status.phase=Running \
+ -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.metadata.deletionTimestamp}{"\n"}{end}' 2>/dev/null \
+ | awk -F'\t' -v old="$old_pod" '$1 != "" && $1 != old && $2 == "" {print $1; exit}')"
+ [[ -n "$name" ]] && new_pod="$name"
+ }
+ # shellcheck disable=SC2329 # invoked by name via wait_until
+ _delpass_hcc_diag() {
+ { echo '----- HCC pods -----'
+ kctl -n "$CONTROL_NS" get pods -l "app=${HCC_DEPLOY}" -o wide 2>&1 || true
+ } >&2
+ }
+ if ! wait_until "$DELPASS_HCC_READY_DEADLINE_S" 2 "replacement HCC pod after restarting ${old_pod}" \
+ _delpass_new_pod_probe _delpass_hcc_diag; then
+ fail "delete-during-pass: no replacement HCC pod within ${DELPASS_HCC_READY_DEADLINE_S}s"
+ return 1
+ fi
+ log "replacement HCC pod: ${new_pod}"
+
+ # 3. Wait until the pass is demonstrably ACTIVE on the replacement pod.
+ local pass_state=''
+ # shellcheck disable=SC2329 # invoked by name via wait_until
+ _delpass_pass_active_probe() {
+ local logs
+ logs="$(kctl -n "$CONTROL_NS" logs "pod/${new_pod}" 2>/dev/null || true)"
+ if printf '%s' "$logs" | grep -Fq "$HCC_PASS_FAILED_MARKER"; then pass_state='failed'; return 0; fi
+ if printf '%s' "$logs" | grep -Fq "$HCC_PASS_COMPLETED_MARKER"; then pass_state='completed'; return 0; fi
+ if printf '%s' "$logs" | grep -Fq "$HCC_PASS_STARTED_MARKER"; then pass_state='active'; return 0; fi
+ return 1
+ }
+ # shellcheck disable=SC2329 # invoked by name via wait_until
+ _delpass_logs_diag() {
+ { echo "----- replacement HCC pod logs (${new_pod}) -----"
+ kctl -n "$CONTROL_NS" logs "pod/${new_pod}" --tail=80 2>&1 || true
+ } >&2
+ }
+ if ! wait_until "$DELPASS_PASS_ACTIVE_DEADLINE_S" 1 "initial full pass to start on ${new_pod}" \
+ _delpass_pass_active_probe _delpass_logs_diag; then
+ fail "delete-during-pass: replacement pod never logged '${HCC_PASS_STARTED_MARKER}' within ${DELPASS_PASS_ACTIVE_DEADLINE_S}s"
+ return 1
+ fi
+ local t_pass_active_ms=''
+ case "$pass_state" in
+ active)
+ t_pass_active_ms="$(now_ms)"
+ log "initial full pass ACTIVE on ${new_pod} (started, not completed)"
+ ;;
+ completed)
+ fail "delete-during-pass: the initial pass completed before the delete could be issued — pass-active overlap NOT established in this environment (fleet reconciled too fast); re-run"
+ _delpass_logs_diag
+ return 1
+ ;;
+ failed)
+ fail "delete-during-pass: the initial pass FAILED on the replacement pod — fix the controller before measuring"
+ _delpass_logs_diag
+ return 1
+ ;;
+ esac
+
+ # 4. Delete the fixture Host WHILE the pass is active.
+ local t_delete_ms; t_delete_ms="$(now_ms)"
+ if ! kctl -n "$MCP_HOST_NS" delete host "$HOST_DELPASS" --wait=false >/dev/null; then
+ fail "delete-during-pass: Host deletion failed for ${HOST_DELPASS}"
+ return 1
+ fi
+ log "Host ${HOST_DELPASS} deleted while the pass is active"
+
+ # B1 belt 1: the pass can log COMPLETED inside the ~0.5-2s window between
+ # the active-probe read and the delete landing. Re-read the logs ONCE,
+ # immediately; if COMPLETED is already present the delete cannot be
+ # proven to have landed mid-pass — hard fail, never silently accepted.
+ local post_delete_logs
+ if ! post_delete_logs="$(kctl -n "$CONTROL_NS" logs "pod/${new_pod}" 2>/dev/null)"; then
+ fail "delete-during-pass: could not re-read HCC logs immediately after the delete — overlap cannot be verified (fail-closed)"
+ return 1
+ fi
+ if printf '%s' "$post_delete_logs" | grep -Fq "$HCC_PASS_COMPLETED_MARKER"; then
+ fail "delete-during-pass: pass logged COMPLETED within the probe->delete window — overlap NOT established; re-run"
+ return 1
+ fi
+ log "belt 1: COMPLETED still absent immediately after the delete"
+
+ # 5. The pass must COMPLETE after the delete (a pass that fails instead
+ # would mask the property under test behind an unrelated error).
+ # shellcheck disable=SC2329 # invoked by name via wait_until
+ _delpass_pass_completed_probe() {
+ local logs
+ logs="$(kctl -n "$CONTROL_NS" logs "pod/${new_pod}" 2>/dev/null || true)"
+ if printf '%s' "$logs" | grep -Fq "$HCC_PASS_FAILED_MARKER"; then pass_state='failed'; return 0; fi
+ printf '%s' "$logs" | grep -Fq "$HCC_PASS_COMPLETED_MARKER" && pass_state='completed'
+ }
+ if ! wait_until "$DELPASS_PASS_COMPLETE_DEADLINE_S" 2 "initial full pass completion after the delete" \
+ _delpass_pass_completed_probe _delpass_logs_diag; then
+ fail "delete-during-pass: pass did not complete within ${DELPASS_PASS_COMPLETE_DEADLINE_S}s of the delete"
+ return 1
+ fi
+ if [[ "$pass_state" == 'failed' ]]; then
+ fail "delete-during-pass: the fleet pass FAILED after the mid-pass delete"
+ _delpass_logs_diag
+ return 1
+ fi
+ local t_pass_completed_ms; t_pass_completed_ms="$(now_ms)"
+ ok "delete-during-pass: observed sequence pass-active@${t_pass_active_ms}ms -> delete@${t_delete_ms}ms -> completed-observed@${t_pass_completed_ms}ms (belt 1 passed at the delete)"
+
+ # B1 belt 2: adjudicate overlap from the COMPLETED line's OWN log
+ # timestamp (kubectl --timestamps stamps each line at write time),
+ # closing the window the poll-granular reads cannot see. Clock note: the
+ # log stamp is the node's clock while t_delete_ms is the runner's; on
+ # minikube both derive from the host clock. A node clock ahead of the
+ # runner could only mask a completion belt 1 already catches; a lagging
+ # clock produces a LOUD false-fail, never a false-pass.
+ local completed_line completed_ts completed_ms
+ completed_line="$(kctl -n "$CONTROL_NS" logs "pod/${new_pod}" --timestamps 2>/dev/null \
+ | grep -F "$HCC_PASS_COMPLETED_MARKER" | head -n1 || true)"
+ if [[ -z "$completed_line" ]]; then
+ fail "delete-during-pass: could not re-read the COMPLETED line with --timestamps for overlap adjudication"
+ return 1
+ fi
+ completed_ts="${completed_line%% *}"
+ if ! completed_ms="$(python3 -c '
+import datetime, re, sys
+ts = re.sub(r"\.(\d{1,6})\d*", r".\1", sys.argv[1]).replace("Z", "+00:00")
+print(int(datetime.datetime.fromisoformat(ts).timestamp() * 1000))
+' "$completed_ts" 2>/dev/null)"; then
+ fail "delete-during-pass: could not parse COMPLETED log timestamp '${completed_ts}'"
+ return 1
+ fi
+ if [[ "$completed_ms" -gt "$t_delete_ms" ]]; then
+ ok "delete-during-pass: overlap established — COMPLETED log stamp postdates the delete (belt 2: completed-log=${completed_ms}ms > delete-issued=${t_delete_ms}ms)"
+ else
+ fail "delete-during-pass: COMPLETED log stamp (${completed_ms}ms) does NOT postdate the delete (${t_delete_ms}ms) — overlap NOT established; re-run"
+ return 1
+ fi
+
+ # 6. Exactly-one complete cleanup converges: CR gone + zero ownership-
+ # labeled leftovers across the bundle namespaces (teardown's predicate).
+ # FAIL-CLOSED: the probe succeeds ONLY on positive evidence — confirmed
+ # NotFound for the CR and a fully-readable, empty children enumeration.
+ # A kubectl read failure keeps the probe failing, so an API blip ends in
+ # the bounded deadline FAILING, never in a false "cleanup converged".
+ # shellcheck disable=SC2329 # invoked by name via wait_until
+ _delpass_clean_probe() {
+ host_absent_confirmed "$HOST_DELPASS" || return 1
+ local children n
+ children="$(collect_children_json "$HOST_DELPASS")" || return 1
+ n="$(printf '%s' "$children" | jq 'length' 2>/dev/null || echo -1)"
+ [[ "${n:--1}" -eq 0 ]]
+ }
+ if ! wait_until "$DELPASS_CLEANUP_DEADLINE_S" 3 "complete cleanup of ${HOST_DELPASS}" \
+ _delpass_clean_probe _diag_probe; then
+ fail "delete-during-pass: cleanup did not converge within ${DELPASS_CLEANUP_DEADLINE_S}s (lingering CR or owned leftovers)"
+ return 1
+ fi
+ local t_clean_ms; t_clean_ms="$(now_ms)"
+ ok "delete-during-pass: cleanup converged (CR gone, 0 owned children across ${BUNDLE_NAMESPACES})"
+
+ # 7. No resurrection: the completed pass (and any stale queued reconcile)
+ # must not recreate the deleted Host's resources. Quiet settle, re-assert.
+ log "resurrection settle: ${DELPASS_RESURRECTION_SETTLE_S}s"
+ sleep "$DELPASS_RESURRECTION_SETTLE_S"
+ # FAIL-CLOSED: absence must be a confirmed NotFound and the children
+ # enumeration fully readable — an unverifiable state fails exactly like
+ # a resurrection would.
+ local res_absent_rc=0 res_children children
+ host_absent_confirmed "$HOST_DELPASS" || res_absent_rc=$?
+ if children="$(collect_children_json "$HOST_DELPASS")"; then
+ res_children="$(printf '%s' "$children" | jq 'length' 2>/dev/null || echo -1)"
+ else
+ res_children=-1
+ fi
+ if [[ "$res_absent_rc" -eq 0 && "$res_children" -eq 0 ]]; then
+ ok "delete-during-pass: no resurrection after ${DELPASS_RESURRECTION_SETTLE_S}s settle (CR NotFound-confirmed, 0 owned children)"
+ else
+ fail "delete-during-pass: RESURRECTION or unverifiable state after cleanup (host_absence_rc=${res_absent_rc}: 0=confirmed-absent 1=present 2=read-failed; owned_children=${res_children}: -1=unverifiable)"
+ pod_diagnostics "$HOST_DELPASS"
+ return 1
+ fi
+
+ # 8. Machine-readable record for the report roll-up.
+ jq -n \
+ --arg host "$HOST_DELPASS" \
+ --arg old_pod "$old_pod" --arg new_pod "$new_pod" \
+ --argjson t_hcc_restart_ms "$t_restart_ms" \
+ --argjson t_pass_active_seen_ms "$t_pass_active_ms" \
+ --argjson t_delete_issued_ms "$t_delete_ms" \
+ --argjson t_pass_completed_seen_ms "$t_pass_completed_ms" \
+ --argjson t_pass_completed_log_ts_ms "$completed_ms" \
+ --argjson t_cleanup_converged_ms "$t_clean_ms" \
+ --argjson settle_s "$DELPASS_RESURRECTION_SETTLE_S" \
+ '{subject:$host, trigger:"HCC pod restart -> initial full fleet pass",
+ hcc_pod_restarted:$old_pod, hcc_pod_replacement:$new_pod,
+ t_hcc_restart_ms:$t_hcc_restart_ms,
+ t_pass_active_seen_ms:$t_pass_active_seen_ms,
+ t_delete_issued_ms:$t_delete_issued_ms,
+ t_pass_completed_seen_ms:$t_pass_completed_seen_ms,
+ t_pass_completed_log_ts_ms:$t_pass_completed_log_ts_ms,
+ t_cleanup_converged_ms:$t_cleanup_converged_ms,
+ resurrection_settle_s:$settle_s,
+ note:"overlap proven with two belts: (1) COMPLETED absent in a re-read immediately after the delete; (2) the COMPLETED line own --timestamps stamp (t_pass_completed_log_ts_ms) postdates t_delete_issued_ms; cleanup predicate = CR gone + zero ownership-labeled leftovers across the bundle namespaces; re-asserted after the settle window"}' \
+ >"${RUN_DIR}/delete-during-pass.json"
+ log "record: ${RUN_DIR}/delete-during-pass.json"
+ return 0
+}
+
# ======================================================================
# Teardown — delete ONLY this run's fixtures (by run label). Fail-loud on
# leftover after a bounded wait.
@@ -809,10 +1164,17 @@ teardown_fixtures() {
# Bounded wait for the Hosts to disappear, then verify no owned children of
# our fixture hosts linger.
+ # FAIL-CLOSED (mirrors e2e-host-storm-gate.sh): a kubectl list failure
+ # must never read as "all gone" — the probe fails (error on stderr)
+ # until the API positively returns an empty list.
# shellcheck disable=SC2329 # invoked by name via wait_until
_hosts_gone() {
- local n; n="$(kctl -n "$MCP_HOST_NS" get host -l "$sel" -o name 2>/dev/null | wc -l | tr -d ' ')"
- [[ "${n:-0}" -eq 0 ]]
+ local out
+ if ! out="$(kctl -n "$MCP_HOST_NS" get host -l "$sel" -o name 2>"${RUN_DIR}/hosts-gone.err")"; then
+ echo "_hosts_gone: kubectl list FAILED: $(cat "${RUN_DIR}/hosts-gone.err" 2>/dev/null)" >&2
+ return 1
+ fi
+ [[ -z "$out" ]]
}
if ! wait_until "${TEARDOWN_DEADLINE_S:-120}" 3 "fixture Hosts (${sel}) deletion" _hosts_gone teardown_diagnostics; then
fail "teardown: fixture Hosts still present after deadline (run-id ${RUN_ID})"
@@ -820,17 +1182,57 @@ teardown_fixtures() {
fi
# Verify no owned children of any of this run's hosts remain.
- local leftover=0 host
- for host in "$HOST_CONTROL" "$HOST_STATELESS" "$HOST_PROBE"; do
- [[ -n "$host" ]] || continue
- local n; n="$(collect_children_json "$host" | jq 'length' 2>/dev/null || echo 0)"
- if [[ "${n:-0}" -gt 0 ]]; then
- warn "teardown: ${n} owned children of ${host} still present"
- leftover=$((leftover+n))
- fi
+ # Convergence-aware (identical semantics to e2e-host-storm-gate.sh): a child
+ # carrying a deletionTimestamp is CONVERGING — its delete WAS issued and a
+ # finalizer (e.g. a workspace PVC's kubernetes.io/pvc-protection, held for the
+ # deleting pod's termination grace) is draining — so it gets a bounded
+ # extension. A child with NO deletionTimestamp means the delete was NEVER
+ # issued (a real cleanup gap) and fails immediately, no wait. An unverifiable
+ # read/parse is FAIL-CLOSED (verification impossible != "no children").
+ local leftover=0 host orphan=0 unverifiable=0 leftover_report=''
+ local converge_deadline=$(( SECONDS + MEASURE_TEARDOWN_CONVERGE_S ))
+ while :; do
+ leftover=0; orphan=0; unverifiable=0; leftover_report=''
+ for host in "$HOST_CONTROL" "$HOST_STATELESS" "$HOST_PROBE" "$HOST_DELPASS"; do
+ [[ -n "$host" ]] || continue
+ local children n_conv n_orph
+ if ! children="$(collect_children_json "$host")"; then
+ leftover_report+=" ${host}: kubectl read FAILED (unverifiable, fail-closed)"$'\n'
+ leftover=$((leftover+1)); unverifiable=1
+ continue
+ fi
+ n_conv="$(printf '%s' "$children" | jq '[.[] | select(.deletionTimestamp != null)] | length' 2>/dev/null || echo -1)"
+ n_orph="$(printf '%s' "$children" | jq '[.[] | select(.deletionTimestamp == null)] | length' 2>/dev/null || echo -1)"
+ if [[ "${n_conv:--1}" -lt 0 || "${n_orph:--1}" -lt 0 ]]; then
+ leftover_report+=" ${host}: owned-children JSON unparsable (jq failed, fail-closed)"$'\n'
+ leftover=$((leftover+1)); unverifiable=1
+ continue
+ fi
+ if [[ "$n_conv" -gt 0 ]]; then
+ leftover_report+=" ${host}: ${n_conv} owned child(ren) Terminating (converging)"$'\n'
+ leftover=$((leftover+n_conv))
+ fi
+ if [[ "$n_orph" -gt 0 ]]; then
+ leftover_report+=" ${host}: ${n_orph} owned child(ren) with NO deletionTimestamp (delete never issued — REAL cleanup gap)"$'\n'
+ leftover=$((leftover+n_orph)); orphan=1
+ fi
+ done
+ if [[ "$leftover" -eq 0 ]]; then break; fi
+ # A never-issued delete or an unverifiable read is a hard finding — do not wait.
+ if [[ "$orphan" -eq 1 || "$unverifiable" -eq 1 ]]; then break; fi
+ if [[ "$SECONDS" -ge "$converge_deadline" ]]; then break; fi
+ sleep 3
done
- # Verify our fixture Secret is gone.
- if kctl -n "$MCP_HOST_NS" get secret -l "$sel" -o name 2>/dev/null | grep -q .; then
+ if [[ "$leftover" -gt 0 ]]; then
+ warn "teardown: owned-children leftovers after up to ${MEASURE_TEARDOWN_CONVERGE_S}s convergence extension:"
+ printf '%s' "$leftover_report" >&2
+ fi
+ # Verify our fixture Secret is gone — FAIL-CLOSED on unreadable API.
+ local sec_out
+ if ! sec_out="$(kctl -n "$MCP_HOST_NS" get secret -l "$sel" -o name 2>"${RUN_DIR}/secret-gone.err")"; then
+ warn "teardown: could not verify fixture Secret deletion: $(cat "${RUN_DIR}/secret-gone.err" 2>/dev/null) — counting as leftover"
+ leftover=$((leftover+1))
+ elif [[ -n "$sec_out" ]]; then
warn "teardown: fixture Secret still present (${sel})"
leftover=$((leftover+1))
fi
@@ -886,7 +1288,15 @@ write_report() {
echo "| Independent-Host admission while blocked | phase 3 | probe-Host bundle clock under asserted blocker |"
echo "| HCC §14.1 histograms | phase 4 | /metrics scrape |"
echo "| Context/McpServer non-regression | phase 5 | read-only resourceVersion/creationTimestamp snapshot |"
+ echo "| Delete-while-pass-active convergence (#827, Addendum 4.7) | delete-during-pass step | HCC pass logs + ownership-label leftover check + resurrection settle |"
echo
+ if [[ -s "${RUN_DIR}/delete-during-pass.json" ]]; then
+ echo "## Addendum 4.7 — delete-while-pass-active (#827)"
+ echo
+ jq -r '"- subject: `\(.subject)`\n- pass active -> delete -> pass completed (epoch-ms): \(.t_pass_active_seen_ms) -> \(.t_delete_issued_ms) -> \(.t_pass_completed_seen_ms)\n- cleanup converged at (epoch-ms): \(.t_cleanup_converged_ms)\n- no resurrection after \(.resurrection_settle_s)s settle"' \
+ "${RUN_DIR}/delete-during-pass.json"
+ echo
+ fi
echo "## Caveats"
echo
echo "- K8s object timestamps have 1-second resolution; sub-second deltas are reported at that granularity."
@@ -915,6 +1325,7 @@ report={
"wake":load("wake-*.json"),
"metrics":(load("hcc-metrics.summary.json") or [None])[0],
"sideclock":(load("sideclock.json") or [None])[0],
+ "delete_during_pass":(load("delete-during-pass.json") or [None])[0],
}
json.dump(report,open(os.path.join(rd,"report.json"),"w"),indent=2)
print("report.json + report.md written to "+rd)
@@ -927,8 +1338,8 @@ PY
# Main
# ======================================================================
usage() {
- sed -n '2,120p' "$0" | sed -n '1,/^set -euo/p' >&2
- echo "Usage: CONTEXT=<clerum-...> RUN_LABEL=<label> OUT_DIR=<dir> $0 [all|bundle|wake|independent-admission|metrics|sideclock|teardown]" >&2
+ sed -n '2,160p' "$0" | sed -n '1,/^set -euo/p' >&2
+ echo "Usage: CONTEXT=<clerum-...> RUN_LABEL=<label> OUT_DIR=<dir> $0 [all|bundle|wake|independent-admission|metrics|sideclock|delete-during-pass|teardown]" >&2
}
main() {
@@ -958,6 +1369,13 @@ main() {
else
log "wake phase NOT requested in 'all' (WAKE_HOST unset). Call the 'wake' subcommand after suspending+waking a stateless Host via e2e-stateless-suspend-wake.sh."
fi
+ if [[ "${DELETE_DURING_PASS:-}" == '1' ]]; then
+ # Runs LAST among the measurement phases: it restarts the HCC pod,
+ # which resets the §14.1 counters phase 4 already scraped.
+ phase_delete_during_pass || rc=1
+ else
+ log "delete-during-pass step NOT requested in 'all' (DELETE_DURING_PASS!=1). It restarts the HCC pod to force a demonstrable full fleet pass; set DELETE_DURING_PASS=1 to opt in (Addendum 4.7)."
+ fi
write_report
teardown_fixtures || rc=1
;;
@@ -966,6 +1384,7 @@ main() {
independent-admission) phase_independent_admission || rc=1; write_report ;;
metrics) phase_metrics || rc=1; write_report ;;
sideclock) phase_sideclock || rc=1; write_report ;;
+ delete-during-pass) phase_delete_during_pass || rc=1; write_report ;;
teardown) teardown_fixtures || rc=1 ;;
*) usage; die "unknown subcommand: ${cmd}" 2 ;;
esac