#!/usr/bin/env bash set -uo pipefail # CASAN Plan-16 SEC-19 (ARCH-05) — atomic + locked control-plane writes. # # The control-plane store did an unlocked, non-atomic load→modify→save, so two # concurrent `set`/`rollback` runs could lose a write or fork the audit hash chain. # Now the critical section holds a POSIX flock and the store is written atomically # (tmp + rename). Proves concurrent writes on distinct keys all survive and the # chain still verifies, with no torn/partial store file. # # Deterministic; hermetic (temp store + temp keys). SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" source "$SCRIPT_DIR/../scripts/bash/casan-paths.sh" PROJECT_ROOT="$CASAN_APP_ROOT" CP="$CASAN_HARNESS_ROOT/scripts/bash/control-plane-settings.py" WORK="$(mktemp -d)" trap 'rm -rf "$WORK"' EXIT export CASAN_CP_STORE_FILE="$WORK/store.json" export CASAN_CP_KEY_DIR="$WORK/keys" export CASAN_CP_PUB="$WORK/pub.pem" PASS=0; FAIL=0 pass() { echo "PASS: $1"; PASS=$((PASS + 1)); } fail() { echo "FAIL: $1"; FAIL=$((FAIL + 1)); } echo "===== Plan-16 SEC-19: atomic + locked control-plane writes =====" # Fire four concurrent writers on distinct non-sensitive keys. python3 "$CP" set compression.enabled true --actor a --reason r >/dev/null 2>&1 & python3 "$CP" set compression.mode structural --actor a --reason r >/dev/null 2>&1 & python3 "$CP" set cost.absolute_cap_usd 5 --actor a --reason r >/dev/null 2>&1 & python3 "$CP" set model.primary "ollama:ornith" --actor a --reason r >/dev/null 2>&1 & wait COUNT="$(python3 "$CP" get-all | python3 -c 'import json,sys; print(len(json.load(sys.stdin)))' 2>/dev/null)" [[ "$COUNT" == "4" ]] \ && pass "all 4 concurrent writes survived (no lost update)" \ || fail "lost update under concurrency (only $COUNT/4 keys present)" python3 "$CP" verify-audit >/dev/null 2>&1 \ && pass "audit chain intact after concurrent writes" \ || fail "audit chain forked/broken under concurrency" # The store must always be valid JSON (atomic rename ⇒ never torn) and no tmp left. python3 -c "import json; json.load(open('$CASAN_CP_STORE_FILE'))" 2>/dev/null \ && pass "store file is valid JSON (atomic write, not torn)" \ || fail "store file torn / invalid JSON" if ls "$WORK"/*.tmp >/dev/null 2>&1; then fail "leftover .tmp file (atomic rename incomplete)" else pass "no leftover .tmp file" fi echo "" echo "===== SEC-19 SUMMARY: PASS=$PASS FAIL=$FAIL =====" [[ "$FAIL" -eq 0 ]] || exit 1