From 8d5ac3ca51a9153595bc3e6daa61edb760163e72 Mon Sep 17 00:00:00 2001 From: Chris OHearn Date: Thu, 26 Nov 2026 22:54:44 -0700 Subject: [PATCH 1/7] Add idle-only guard snapshot command --- scripts/fork/host/t3-update-guard/README.md | 10 + scripts/fork/host/t3-update-guard/guard | 377 +++++++++++++++++- .../host/t3-update-guard/t3-service-update | 2 + .../fork/host/t3-update-guard/test-guard.sh | 85 ++++ 4 files changed, 469 insertions(+), 5 deletions(-) diff --git a/scripts/fork/host/t3-update-guard/README.md b/scripts/fork/host/t3-update-guard/README.md index c31037f0a5fcb..126b5a892056f 100644 --- a/scripts/fork/host/t3-update-guard/README.md +++ b/scripts/fork/host/t3-update-guard/README.md @@ -20,6 +20,16 @@ These are the files that keep the T3 background service on Chris's Omarchy machi Installing the guard does not restart the T3 service. +## Capture a snapshot without updating + +`t3-service-update snapshot ` is the guarded stop/copy/restart entry point for a caller that needs a database snapshot without installing or selecting another release. Both identifiers must contain only letters, digits, dots, underscores, and hyphens, and start with a letter or digit. Reusing an operation ID with the same point returns its existing receipt and does not stop the service again; reusing it for a different point fails closed. + +The command takes the existing service-change lock, requires the selected release to be installed, trusted, healthy, and the exact version answering on the loopback listener owned by the systemd unit's main PID. It requires two clean activity reads, then rechecks the service identity and generation immediately before stopping: no running, starting, waiting, or queued runs; no pending requests; no active tool calls; and at least the configured 15 minutes of quiet. Unknown activity, health, listener, or systemd state refuses the stop. + +After systemd confirms the service is inactive, the guard copies the SQLite files and WAL/SHM sidecars using the existing reflink path. This one-off operation preserves earlier snapshots instead of applying the update path's three-snapshot rotation. It writes an owner-only JSON receipt under `~/.local/state/t3-update-guard/snapshot-receipts/` with the operation ID, snapshot point, stopped unit invocation and PID, quiet-window evidence, snapshot path, and each copied file's SHA-256 and size. It starts the same selected fork build and only marks the receipt complete after the new systemd invocation, listener PID, health version, and service uptime are verified. It never downloads, installs, or selects a release and never runs the T3 CLI against the live database. Once a captured receipt exists, retrying the same operation ID resumes or returns that receipt without taking another snapshot. If the process ends before that receipt is written, inspect the guard events and snapshot directory before starting another operation. + +The guard receipt proves which stopped-service files were copied and that the same fork build returned. A caller must still perform isolated readback against the retained copy; this command does not claim migration compatibility or publication of another release. + ## When updates happen - **Launch selection:** the guard prefers a build with a positive Codex shadow readiness report. It switches away from the active build only when that build positively reports a shadow conflict and another verified build reports ready. Missing or unknown shadow status keeps the active build when it can open the database. If an update launch is redirected to a compatible build because of a positive shadow conflict, the release is marked rejected on this host, not bad globally; fix the shadow conflict and retry with `t3-service-update `. diff --git a/scripts/fork/host/t3-update-guard/guard b/scripts/fork/host/t3-update-guard/guard index be0608ec1f52d..3b0a49c51809e 100755 --- a/scripts/fork/host/t3-update-guard/guard +++ b/scripts/fork/host/t3-update-guard/guard @@ -21,6 +21,7 @@ # tool calls, never stops the service while the kernel shows the exit hang, and # reports afterwards which interrupted threads continued. Verifies the new build # serves, and rolls back if not. +# snapshot Strict-idle, same-version stop/copy/restart with an owner-only idempotent receipt. # status Show what is active, trusted, healthy and blocked. # trust V Verify version V against its release and record it as trusted. # @@ -891,15 +892,28 @@ SNAPSHOTS="$T3HOME/runtime/guard-db-snapshots" # Copy-on-write snapshot of the databases (btrfs reflink: instant, shares blocks). The service # must be stopped so the copy is consistent. Prints the snapshot directory. snapshot_db() { - local label="$1" dir f + local label="$1" retain_all="${2:-}" dir f copied=0 + [[ "$label" =~ ^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$ ]] || return 1 + [[ -f "$DB" && ! -L "$DB" ]] || return 1 + mkdir -p "$SNAPSHOTS" || return 1 + chmod 700 "$SNAPSHOTS" || return 1 dir="$SNAPSHOTS/$(date +%Y%m%dT%H%M%S)-$label" - mkdir -p "$dir" || return 1 + mkdir "$dir" || return 1 + chmod 700 "$dir" || { rmdir "$dir" 2>/dev/null; return 1; } for f in "$T3HOME"/userdata/*.sqlite "$T3HOME"/userdata/*.sqlite-wal "$T3HOME"/userdata/*.sqlite-shm; do [[ -e "$f" ]] || continue - cp --reflink=always -p "$f" "$dir/" || { rm -rf "$dir"; return 1; } + [[ -f "$f" && ! -L "$f" ]] || { rm -rf "$dir"; return 1; } + cp --reflink=always -p "$f" "$dir/" && cmp -s "$f" "$dir/$(basename "$f")" || { + rm -rf "$dir" + return 1 + } + copied=$((copied + 1)) done + (( copied > 0 )) || { rm -rf "$dir"; return 1; } # Keep the newest three. - ls -1d "$SNAPSHOTS"/2* 2>/dev/null | sort | head -n -3 | xargs -r rm -rf + if [[ "$retain_all" != retain-all ]]; then + ls -1d "$SNAPSHOTS"/2* 2>/dev/null | sort | head -n -3 | xargs -r rm -rf + fi printf '%s' "$dir" } @@ -955,6 +969,358 @@ wait_inactive() { return 1 } +unit_property() { systemctl --user show -p "$1" --value "$UNIT" 2>/dev/null; } + +# The snapshot receipt binds the copy to the actual systemd invocation and the process that +# owned the loopback listener. A health endpoint alone could be answered by a stale process. +service_listener_pid() { + local output pids + [[ "$PORT" =~ ^[1-9][0-9]{0,4}$ ]] && (( 10#$PORT <= 65535 )) || return 1 + output=$(timeout --kill-after=1 5 ss -H -ltnp "sport = :$PORT" 2>/dev/null) || return 1 + pids=$(sed -nE 's/.*pid=([0-9]+).*/\1/p' <<<"$output" | sort -u) + [[ "$pids" =~ ^[0-9]+$ ]] || return 1 + printf '%s' "$pids" +} + +snapshot_service_identity() { + local expected="$1" state invocation pid listener version uptime + state=$(unit_property ActiveState) || return 1 + [[ "$state" == active ]] || return 1 + invocation=$(unit_property InvocationID) || return 1 + [[ "$invocation" =~ ^[[:xdigit:]]{32}$ ]] || return 1 + pid=$(unit_property MainPID) || return 1 + [[ "$pid" =~ ^[1-9][0-9]*$ ]] || return 1 + listener=$(service_listener_pid) || return 1 + [[ "$listener" == "$pid" ]] || return 1 + version=$(service_version) || return 1 + [[ "$version" == "$expected" ]] || return 1 + uptime=$(service_uptime) || return 1 + [[ "$uptime" =~ ^[0-9]+$ ]] && (( uptime >= 60 )) || return 1 + printf '%s|%s|%s|%s' "$invocation" "$pid" "$version" "$uptime" +} + +# A one-off snapshot has a stricter idle gate than the long-running update timer: queued runs, +# any pending request, and every active tool item hold it. The DB read is deliberately repeated +# immediately before the stop; unreadable or incomplete evidence fails closed. +snapshot_idle_evidence() { + local counts runs requests tools quiet checked_at + counts=$(timeout 10 sqlite3 -readonly -separator '|' "$DB" \ + "select + (select count(*) from orchestration_v2_projection_runs where status in ('running','starting','waiting','queued')), + (select count(*) from orchestration_v2_projection_runtime_requests where status = 'pending'), + (select count(*) from orchestration_v2_projection_runs r + cross join orchestration_v2_projection_turn_items i + on i.thread_id = r.thread_id and i.run_id = r.run_id + where r.status in ('running','starting','waiting','queued') + and i.status in ('pending','running','waiting') + and i.type in ('command_execution','dynamic_tool','file_change'));") || { + echo "snapshot: activity database is unreadable" >&2 + return 1 + } + IFS='|' read -r runs requests tools <<<"$counts" + [[ "$runs" =~ ^[0-9]+$ && "$requests" =~ ^[0-9]+$ && "$tools" =~ ^[0-9]+$ ]] || { + echo "snapshot: activity census is incomplete" >&2 + return 1 + } + (( runs == 0 && requests == 0 && tools == 0 )) || { + echo "snapshot: activity remains (runs=$runs pendingRequests=$requests activeTools=$tools)" >&2 + return 1 + } + quiet=$(quiet_seconds) || quiet="" + [[ "$quiet" =~ ^[0-9]+$ ]] && (( quiet >= IDLE_QUIET_SECONDS )) || { + echo "snapshot: idle quiet window is not verified (quietSeconds=${quiet:-unknown}, required=$IDLE_QUIET_SECONDS)" >&2 + return 1 + } + checked_at=$(date -u +%Y-%m-%dT%H:%M:%S.000Z) + jq -cn --arg checkedAt "$checked_at" --argjson runs "$runs" \ + --argjson requests "$requests" --argjson tools "$tools" --argjson quiet "$quiet" \ + '{checkedAt:$checkedAt,runs:$runs,pendingRequests:$requests,activeTools:$tools,quietSeconds:$quiet}' +} + +snapshot_manifest() { + local dir="$1" file name sha size files='[]' count=0 + [[ -f "$dir/$(basename "$DB")" && ! -L "$dir/$(basename "$DB")" ]] || return 1 + for file in "$dir"/*; do + [[ -f "$file" && ! -L "$file" ]] || continue + name=$(basename "$file") + sha=$(sha256sum "$file" 6>&- 7>&- | cut -d' ' -f1) || return 1 + [[ "$sha" =~ ^[[:xdigit:]]{64}$ ]] || return 1 + size=$(stat -c %s "$file") || return 1 + files=$(jq -cn --argjson old "$files" --arg name "$name" --arg sha "$sha" \ + --argjson size "$size" '$old + [{name:$name,sha256:$sha,sizeBytes:$size}]') || return 1 + count=$((count + 1)) + done + (( count > 0 )) || return 1 + printf '%s' "$files" +} + +write_snapshot_receipt() { + local receipt="$1" json="$2" dir="${1%/*}" + ( + umask 077 + local tmp + tmp=$(mktemp "$dir/.snapshot-receipt.XXXXXX") || exit 1 + if ! printf '%s\n' "$json" >"$tmp" || ! chmod 600 "$tmp" || ! mv -f -- "$tmp" "$receipt"; then + rm -f -- "$tmp" + exit 1 + fi + ) +} + +snapshot_receipt_matches() { + local receipt="$1" operation="$2" point="$3" status path name sha actual version invocation pid + [[ -f "$receipt" && ! -L "$receipt" ]] || return 1 + [[ "$(stat -c %a "$receipt" 2>/dev/null)" == 600 ]] || return 1 + [[ "$(stat -c %a "${receipt%/*}" 2>/dev/null)" == 700 ]] || return 1 + [[ "$(jq -r '.operationId // empty' "$receipt" 2>/dev/null)" == "$operation" ]] || return 1 + [[ "$(jq -r '.snapshotPoint // empty' "$receipt" 2>/dev/null)" == "$point" ]] || return 1 + [[ "$(jq -r '.schemaVersion // empty' "$receipt" 2>/dev/null)" == 1 ]] || return 1 + [[ "$(jq -r '.unit // empty' "$receipt" 2>/dev/null)" == "$UNIT" ]] || return 1 + [[ "$(jq -e '.files | type == "array" and length > 0' "$receipt" 2>/dev/null)" == true ]] || return 1 + status=$(jq -r '.status // empty' "$receipt" 2>/dev/null) + [[ "$status" == captured || "$status" == restart_failed || "$status" == complete ]] || return 1 + version=$(jq -r '.stoppedGeneration.version // empty' "$receipt" 2>/dev/null) + invocation=$(jq -r '.stoppedGeneration.invocationId // empty' "$receipt" 2>/dev/null) + pid=$(jq -r '.stoppedGeneration.mainPid // empty' "$receipt" 2>/dev/null) + [[ -n "$version" && "$invocation" =~ ^[[:xdigit:]]{32}$ && "$pid" =~ ^[1-9][0-9]*$ ]] || return 1 + if [[ "$status" == complete ]]; then + invocation=$(jq -r '.restart.invocationId // empty' "$receipt" 2>/dev/null) + pid=$(jq -r '.restart.mainPid // empty' "$receipt" 2>/dev/null) + [[ "$invocation" =~ ^[[:xdigit:]]{32}$ && "$pid" =~ ^[1-9][0-9]*$ && \ + "$(jq -r '.restart.servingVersion // empty' "$receipt" 2>/dev/null)" == "$version" && \ + -n "$(jq -r '.restart.verifiedAt // empty' "$receipt" 2>/dev/null)" ]] || return 1 + fi + path=$(jq -r '.snapshotPath // empty' "$receipt" 2>/dev/null) + [[ "$path" == "$SNAPSHOTS/"* && -d "$path" && \ + "$(stat -c %a "$path" 2>/dev/null)" == 700 && -f "$path/$(basename "$DB")" ]] || return 1 + while IFS=$'\t' read -r name sha; do + [[ "$name" =~ ^[A-Za-z0-9][A-Za-z0-9._-]*$ && "$sha" =~ ^[[:xdigit:]]{64}$ ]] || return 1 + [[ -f "$path/$name" && ! -L "$path/$name" ]] || return 1 + actual=$(sha256sum "$path/$name" 6>&- 7>&- | cut -d' ' -f1) || return 1 + [[ "$actual" == "$sha" ]] || return 1 + done < <(jq -r '.files[]? | [.name,.sha256] | @tsv' "$receipt" 2>/dev/null) + [[ "$(jq -r '.files | length' "$receipt" 2>/dev/null)" =~ ^[1-9][0-9]*$ ]] +} + +snapshot_wait_serving() { + local expected="$1" stopped_invocation="$2" deadline=$((SECONDS + HEALTH_WAIT_SECONDS)) identity invocation pid version uptime + while (( SECONDS <= deadline )); do + if [[ "$(active_version)" == "$expected" ]] && identity=$(snapshot_service_identity "$expected"); then + IFS='|' read -r invocation pid version uptime <<<"$identity" + if [[ "$invocation" != "$stopped_invocation" ]]; then + printf '%s|%s|%s|%s' "$invocation" "$pid" "$version" "$uptime" + return 0 + fi + fi + (( SECONDS >= deadline )) || sleep 2 + done + return 1 +} + +snapshot_start_and_verify() { + local expected="$1" stopped_invocation="$2" identity state + if ! svc start --no-block "$UNIT"; then + state=$(unit_property ActiveState) || state="unknown" + [[ "$state" == active || "$state" == activating ]] || return 1 + fi + identity=$(snapshot_wait_serving "$expected" "$stopped_invocation") || return 1 + printf '%s' "$identity" +} + +snapshot_receipt_finalize() { + local receipt="$1" identity="$2" status="$3" why="${4:-}" invocation pid version uptime verified_at updated + IFS='|' read -r invocation pid version uptime <<<"$identity" + verified_at=$(date -u +%Y-%m-%dT%H:%M:%S.000Z) + updated=$(jq -c --arg status "$status" --arg invocation "$invocation" --arg pid "$pid" \ + --arg version "$version" --arg verifiedAt "$verified_at" --arg why "$why" \ + '.status=$status | .restart={invocationId:$invocation,mainPid:($pid|tonumber),servingVersion:$version,verifiedAt:$verifiedAt} | if $why == "" then del(.restartFailure) else .restartFailure=$why end' \ + "$receipt") || return 1 + write_snapshot_receipt "$receipt" "$updated" +} + +cmd_snapshot() { + local operation="${1:-}" point="${2:-}" receipt_dir receipt status version identity stopped_invocation stopped_pid \ + activity snapshot identity_after files captured_at json generation hang state restart_invocation + [[ $# == 2 && "$operation" =~ ^[A-Za-z0-9][A-Za-z0-9._-]{0,95}$ && \ + "$point" =~ ^[A-Za-z0-9][A-Za-z0-9._-]{0,95}$ ]] || { + echo "usage: t3-service-update snapshot " >&2 + return 2 + } + manager_ready || { echo "snapshot: user service manager unavailable" >&2; return 1; } + exec 9>>"$LOCK" + flock -n 9 || { echo "Another service change holds $LOCK." >&2; return 1; } + receipt_dir="$GUARD_STATE/snapshot-receipts" + mkdir -p "$receipt_dir" && chmod 700 "$receipt_dir" || return 1 + receipt="$receipt_dir/$operation.json" + + if [[ -e "$receipt" ]]; then + snapshot_receipt_matches "$receipt" "$operation" "$point" || { + echo "snapshot: existing receipt does not match this operation or its retained files" >&2 + return 1 + } + status=$(jq -r '.status' "$receipt") + if [[ "$status" == complete ]]; then + version=$(jq -r '.stoppedGeneration.version' "$receipt") + restart_invocation=$(jq -r '.restart.invocationId' "$receipt") + state=$(unit_property ActiveState) || state="unknown" + if [[ "$state" == active && "$(active_version)" == "$version" ]] && \ + identity=$(snapshot_service_identity "$version"); then + IFS='|' read -r generation _ _ _ <<<"$identity" + [[ "$generation" != "$restart_invocation" ]] || outage_end "$version" + fi + cat "$receipt" + return + fi + version=$(jq -r '.stoppedGeneration.version // empty' "$receipt") + stopped_invocation=$(jq -r '.stoppedGeneration.invocationId // empty' "$receipt") + [[ -n "$version" && -n "$stopped_invocation" && "$(active_version)" == "$version" ]] && \ + is_trusted "$version" && is_healthy "$version" || { + echo "snapshot: captured receipt exists, but its original trusted service version is not selected" >&2 + return 1 + } + state=$(unit_property ActiveState) || state="unknown" + if [[ "$state" == active ]] && identity=$(snapshot_wait_serving "$version" "$stopped_invocation"); then + snapshot_receipt_finalize "$receipt" "$identity" complete || return 1 + outage_end "$version" + cat "$receipt" + return + fi + identity=$(snapshot_start_and_verify "$version" "$stopped_invocation") || { + snapshot_receipt_finalize "$receipt" "0|0|$version|0" restart_failed "same-version service did not pass the guarded listener health check" || true + hold_updates "snapshot operation $operation copied the database but could not verify same-version service restart" + return 1 + } + snapshot_receipt_finalize "$receipt" "$identity" complete || return 1 + outage_end "$version" + cat "$receipt" + return + fi + + version=$(active_version) + [[ -n "$version" ]] && is_trusted "$version" && is_healthy "$version" || { + echo "snapshot: active version is not both trusted and recorded healthy" >&2 + return 1 + } + [[ -f "$DB" && ! -L "$DB" ]] || { echo "snapshot: primary database is missing or not a regular file" >&2; return 1; } + identity=$(snapshot_service_identity "$version") || { + echo "snapshot: managed unit, listener PID, health version, or generation is not verified" >&2 + return 1 + } + IFS='|' read -r stopped_invocation stopped_pid _ _ <<<"$identity" + activity=$(snapshot_idle_evidence) || return 1 + + # Re-read both activity and service identity immediately before requesting the stop. + activity=$(snapshot_idle_evidence) || return 1 + identity_after=$(snapshot_service_identity "$version") || { + echo "snapshot: service identity changed before stop" >&2 + return 1 + } + IFS='|' read -r generation stopped_pid _ _ <<<"$identity_after" + [[ "$generation" == "$stopped_invocation" ]] || { + echo "snapshot: service generation changed before stop" >&2 + return 1 + } + if hang=$(kernel_hang_signs); then + echo "snapshot: refusing stop while the kernel exit-hang guard is active: $hang" >&2 + return 1 + fi + log "snapshot: operation=$operation point=$point stopping $UNIT on $version after verified idle census" + if ! svc stop --no-block "$UNIT"; then + state=$(unit_property ActiveState) || state="unknown" + if [[ "$state" == active ]] && snapshot_service_identity "$version" >/dev/null; then + : # The stop did not take effect; leave the verified serving invocation untouched. + else + outage_begin "snapshot operation $operation" + if ! identity=$(snapshot_start_and_verify "$version" "$stopped_invocation"); then + hold_updates "snapshot operation $operation stop returned failure and same-version recovery could not be verified" + return 1 + fi + outage_end "$version" + fi + echo "snapshot: stop request for $UNIT failed; no database copy attempted" >&2 + return 1 + fi + outage_begin "snapshot operation $operation" + if ! wait_inactive; then + state=$(unit_property ActiveState) || state="unknown" + if [[ "$state" == active ]] && snapshot_service_identity "$version" >/dev/null; then + outage_end "$version" + else + if ! identity=$(snapshot_start_and_verify "$version" "$stopped_invocation"); then + hold_updates "snapshot operation $operation timed out stopping $UNIT and same-version recovery could not be verified" + return 1 + fi + outage_end "$version" + fi + echo "snapshot: $UNIT did not become inactive within 120 seconds; no copy attempted" >&2 + return 1 + fi + status=$(unit_property ActiveState) || status="unknown" + if [[ "$status" != inactive && "$status" != failed ]]; then + if [[ "$status" == active ]] && snapshot_service_identity "$version" >/dev/null; then + outage_end "$version" + else + if ! identity=$(snapshot_start_and_verify "$version" "$stopped_invocation"); then + hold_updates "snapshot operation $operation could not verify $UNIT inactive or restore the same-version service" + return 1 + fi + outage_end "$version" + fi + echo "snapshot: could not confirm $UNIT remained inactive; no copy attempted" >&2 + return 1 + fi + snapshot=$(snapshot_db "snapshot-$operation-$point" retain-all) || { + if ! identity=$(snapshot_start_and_verify "$version" "$stopped_invocation"); then + hold_updates "snapshot operation $operation failed to copy the database and same-version restart could not be verified" + return 1 + fi + outage_end "$version" + echo "snapshot: stopped database copy failed; $version was restarted and verified" >&2 + return 1 + } + files=$(snapshot_manifest "$snapshot") || { + if ! identity=$(snapshot_start_and_verify "$version" "$stopped_invocation"); then + hold_updates "snapshot operation $operation created an unverifiable copy and same-version restart could not be verified" + return 1 + fi + outage_end "$version" + echo "snapshot: copied files did not produce a valid manifest; $version was restarted and verified" >&2 + return 1 + } + captured_at=$(date -u +%Y-%m-%dT%H:%M:%S.000Z) + json=$(jq -cn --arg operation "$operation" --arg point "$point" --arg unit "$UNIT" \ + --arg invocation "$stopped_invocation" --arg pid "$stopped_pid" --arg version "$version" \ + --arg path "$snapshot" --arg capturedAt "$captured_at" --argjson files "$files" \ + --argjson activity "$activity" \ + '{schemaVersion:1,operationId:$operation,snapshotPoint:$point,unit:$unit,status:"captured",snapshotPath:$path,files:$files,idleVerification:$activity,stoppedGeneration:{invocationId:$invocation,mainPid:($pid|tonumber),version:$version},capturedAt:$capturedAt}') || { + if ! identity=$(snapshot_start_and_verify "$version" "$stopped_invocation"); then + hold_updates "snapshot operation $operation could not record its receipt or verify same-version restart" + return 1 + fi + outage_end "$version" + return 1 + } + if ! write_snapshot_receipt "$receipt" "$json"; then + if ! identity=$(snapshot_start_and_verify "$version" "$stopped_invocation"); then + hold_updates "snapshot operation $operation copied the database but receipt write and same-version restart could not be verified" + return 1 + fi + outage_end "$version" + echo "snapshot: receipt could not be written; $version was restarted and verified" >&2 + return 1 + fi + log "snapshot: copied $snapshot ($(jq 'length' <<<"$files") files) for operation=$operation" + identity=$(snapshot_start_and_verify "$version" "$stopped_invocation") || { + snapshot_receipt_finalize "$receipt" "0|0|$version|0" restart_failed "same-version service did not pass the guarded listener health check" || true + hold_updates "snapshot operation $operation copied the database but could not verify same-version service restart" + return 1 + } + snapshot_receipt_finalize "$receipt" "$identity" complete || return 1 + outage_end "$version" + log "snapshot: operation=$operation restarted and verified $version" + cat "$receipt" +} + # Install the newest trusted release (or $1), verify it serves, roll back if not. cmd_update() { local now_flag="" target="" cur latest runs sha blockers="" forced="" hang deferred_epoch="" @@ -1307,7 +1673,8 @@ case "${1:-}" in update) shift; cmd_update "$@"; rc=$?; exec 9>&-; report_deferred; flush_reports; exit $rc ;; flush) flush_reports ;; status) cmd_status ;; + snapshot) shift; cmd_snapshot "$@"; rc=$?; exec 9>&-; report_deferred; flush_reports; exit $rc ;; resume) cmd_resume ;; trust) trust "${2:?version}" ;; - *) echo "usage: guard {launch|prove|prove-later|rollback|update [--now] [version]|status|resume|trust |flush}" >&2; exit 2 ;; + *) echo "usage: guard {launch|prove|prove-later|rollback|update [--now] [version]|snapshot |status|resume|trust |flush}" >&2; exit 2 ;; esac diff --git a/scripts/fork/host/t3-update-guard/t3-service-update b/scripts/fork/host/t3-update-guard/t3-service-update index 7926e6cf5048f..77647b1a04443 100755 --- a/scripts/fork/host/t3-update-guard/t3-service-update +++ b/scripts/fork/host/t3-update-guard/t3-service-update @@ -5,8 +5,10 @@ # t3-service-update [--now] [version] # t3-service-update status # t3-service-update resume lift an automatic-updates hold once its cause is fixed +# t3-service-update snapshot case "${1:-}" in status) exec "$HOME/.local/libexec/t3-update-guard/guard" status ;; resume) exec "$HOME/.local/libexec/t3-update-guard/guard" resume ;; + snapshot) shift; exec "$HOME/.local/libexec/t3-update-guard/guard" snapshot "$@" ;; esac exec "$HOME/.local/libexec/t3-update-guard/guard" update "$@" diff --git a/scripts/fork/host/t3-update-guard/test-guard.sh b/scripts/fork/host/t3-update-guard/test-guard.sh index 69190db8aeaba..c68522eb83711 100755 --- a/scripts/fork/host/t3-update-guard/test-guard.sh +++ b/scripts/fork/host/t3-update-guard/test-guard.sh @@ -600,3 +600,88 @@ timeout() { printf '%s\n' "$*" > "$root/timeout"; } systemctl --user is-active t3code.service [[ "$(cat "$root/timeout")" == '--kill-after=2 15 /usr/bin/systemctl --user is-active t3code.service' ]] || fail timeout pass 'all systemctl calls have a bounded timeout' + +# Snapshot-only path: strict activity refusal, copied SQLite sidecars, receipt privacy, same-build +# restart, preservation of older snapshots, and operation-ID idempotency. All service calls are +# simulated; no live T3 unit or database is touched. +( + exec 9>&- + unset -f timeout + T3CODE_HOME="$root/snapshot-t3" T3_GUARD_STATE_DIR="$root/snapshot-state" + export T3CODE_HOME T3_GUARD_STATE_DIR + source "$root/functions" + DB="$T3CODE_HOME/userdata/statev2.sqlite" + LOCK="$root/snapshot-service-change.lock" + mkdir -p "$T3CODE_HOME/userdata" "$SNAPSHOTS" + sqlite3 "$DB" "pragma user_version=119; + create table orchestration_v2_projection_runs (run_id text, thread_id text, status text, requested_at text, completed_at text, payload_json text); + create table orchestration_v2_projection_runtime_requests (runtime_request_id text, status text, resolved_at text); + create table orchestration_v2_projection_turn_items (turn_item_id text, thread_id text, run_id text, type text, status text, updated_at text);" + sim_version=0.1.13-preview.20261127.1 + sim_state=active sim_generation=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa sim_pid=1111 + manager_ready() { return 0; } + active_version() { echo "$sim_version"; } + is_trusted() { return 0; } + is_healthy() { return 0; } + service_version() { echo "$sim_version"; } + service_uptime() { echo 120; } + service_listener_pid() { echo "$sim_pid"; } + unit_property() { + case "$1" in + ActiveState) echo "$sim_state" ;; + InvocationID) echo "$sim_generation" ;; + MainPID) echo "$sim_pid" ;; + *) return 1 ;; + esac + } + kernel_hang_signs() { return 1; } + wait_inactive() { [[ "$sim_state" == inactive ]]; } + cp() { if [[ "${1:-}" == --reflink=always ]]; then shift; fi; command cp "$@"; } + svc() { + printf '%s\n' "$*" >>"$root/snapshot-svc" + case "$1" in + stop) + sim_state=inactive + printf 'wal bytes\n' >"$DB-wal" + printf 'shm bytes\n' >"$DB-shm" + ;; + start) sim_state=active; sim_generation=bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb; sim_pid=2222 ;; + *) return 1 ;; + esac + return 0 + } + outage_begin() { :; } + outage_end() { :; } + log() { :; } + quiet_seconds() { echo 900; } + HEALTH_WAIT_SECONDS=0 + mkdir -p "$SNAPSHOTS/20200101T000000-before" "$SNAPSHOTS/20200102T000000-before" \ + "$SNAPSHOTS/20200103T000000-before" "$SNAPSHOTS/20200104T000000-before" + quiet_seconds() { echo 899; } + if cmd_snapshot snapshot-op before-stock-switch >/dev/null 2>&1; then fail 'snapshot accepted less than 15 minutes of quiet'; fi + exec 9>&- + quiet_seconds() { echo 900; } + sqlite3 "$DB" "insert into orchestration_v2_projection_runs values ('queued','thread','queued','2026-11-27T00:00:00.000Z',null,'{}');" + if cmd_snapshot snapshot-op before-stock-switch >/dev/null 2>&1; then fail 'snapshot stopped a queued run'; fi + exec 9>&- + ! grep -q '^stop ' "$root/snapshot-svc" 2>/dev/null || fail 'snapshot stopped a busy service' + sqlite3 "$DB" "delete from orchestration_v2_projection_runs;" + out=$(cmd_snapshot snapshot-op before-stock-switch) || fail 'snapshot-only command failed in the isolated service fixture' + receipt="$GUARD_STATE/snapshot-receipts/snapshot-op.json" + [[ "$(jq -r '.status' <<<"$out")" == complete ]] || fail 'snapshot receipt did not complete' + [[ "$(jq -r '.stoppedGeneration.version' "$receipt")" == "$sim_version" ]] || fail 'receipt lost stopped version' + [[ "$(jq -r '.stoppedGeneration.invocationId' "$receipt")" == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ]] || fail 'receipt lost stopped invocation ID' + [[ "$(jq -r '.restart.invocationId' "$receipt")" == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb ]] || fail 'receipt lost restarted invocation ID' + [[ "$(jq -r '.files | map(.name) | sort | join(",")' "$receipt")" == 'statev2.sqlite,statev2.sqlite-shm,statev2.sqlite-wal' ]] || fail 'receipt omitted a SQLite file or sidecar' + [[ "$(sha256sum "$(jq -r '.snapshotPath' "$receipt")/statev2.sqlite" | cut -d' ' -f1)" == "$(sha256sum "$DB" | cut -d' ' -f1)" ]] || fail 'snapshot main database differs from the stopped source' + [[ "$(stat -c %a "$receipt")" == 600 && "$(stat -c %a "$(jq -r '.snapshotPath' "$receipt")")" == 700 ]] || fail 'snapshot receipt or files are not under owner-only directories' + [[ -d "$SNAPSHOTS/20200101T000000-before" && -d "$SNAPSHOTS/20200104T000000-before" ]] || fail 'one-off snapshot rotated away an earlier copy' + [[ "$(grep -c '^stop --no-block t3code.service$' "$root/snapshot-svc")" == 1 ]] || fail 'snapshot did not stop exactly once' + [[ "$(grep -c '^start --no-block t3code.service$' "$root/snapshot-svc")" == 1 ]] || fail 'snapshot did not restart exactly once' + out=$(cmd_snapshot snapshot-op before-stock-switch) || fail 'idempotent snapshot retry did not return its receipt' + [[ "$(grep -c '^stop --no-block t3code.service$' "$root/snapshot-svc")" == 1 ]] || fail 'idempotent retry stopped the service twice' + if cmd_snapshot snapshot-op different-point >/dev/null 2>&1; then fail 'snapshot reused an operation ID with a different point'; fi + exec 9>&- + [[ "$(grep -c '^stop --no-block t3code.service$' "$root/snapshot-svc")" == 1 ]] || fail 'mismatched receipt retry stopped the service again' +) || fail 'snapshot-only path violated its isolated activity, receipt, or restart contract' +pass 'snapshot-only path refuses activity, retains a private WAL/SHM receipt, restarts the same build, and is idempotent' From 1cb320aa59eb7d778752ca844eda2936c28c0365 Mon Sep 17 00:00:00 2001 From: Chris OHearn Date: Fri, 27 Nov 2026 00:33:49 -0700 Subject: [PATCH 2/7] Fix guard snapshot-only review findings --- scripts/fork/host/t3-update-guard/README.md | 4 +- scripts/fork/host/t3-update-guard/guard | 489 ++++++++++++------ .../fork/host/t3-update-guard/test-guard.sh | 219 +++++++- 3 files changed, 532 insertions(+), 180 deletions(-) diff --git a/scripts/fork/host/t3-update-guard/README.md b/scripts/fork/host/t3-update-guard/README.md index 126b5a892056f..87ab140a45991 100644 --- a/scripts/fork/host/t3-update-guard/README.md +++ b/scripts/fork/host/t3-update-guard/README.md @@ -24,9 +24,9 @@ Installing the guard does not restart the T3 service. `t3-service-update snapshot ` is the guarded stop/copy/restart entry point for a caller that needs a database snapshot without installing or selecting another release. Both identifiers must contain only letters, digits, dots, underscores, and hyphens, and start with a letter or digit. Reusing an operation ID with the same point returns its existing receipt and does not stop the service again; reusing it for a different point fails closed. -The command takes the existing service-change lock, requires the selected release to be installed, trusted, healthy, and the exact version answering on the loopback listener owned by the systemd unit's main PID. It requires two clean activity reads, then rechecks the service identity and generation immediately before stopping: no running, starting, waiting, or queued runs; no pending requests; no active tool calls; and at least the configured 15 minutes of quiet. Unknown activity, health, listener, or systemd state refuses the stop. +The command takes the existing service-change lock, requires the selected release to be installed, trusted, and healthy, and proves the loopback listener is a descendant of the systemd unit's launcher MainPID inside that exact unit's cgroup. It requires two clean activity reads, then rechecks the service identity and generation immediately before stopping: no preparing, queued, starting, running, or waiting runs; no pending requests; no active command, tool, file-change, subagent, or link-request items; no pending or running effect outbox jobs; no active provider subagents or persisted provider background tasks; and at least the configured 15 minutes of quiet. Unknown activity, health, listener, cgroup, or systemd state refuses the stop. -After systemd confirms the service is inactive, the guard copies the SQLite files and WAL/SHM sidecars using the existing reflink path. This one-off operation preserves earlier snapshots instead of applying the update path's three-snapshot rotation. It writes an owner-only JSON receipt under `~/.local/state/t3-update-guard/snapshot-receipts/` with the operation ID, snapshot point, stopped unit invocation and PID, quiet-window evidence, snapshot path, and each copied file's SHA-256 and size. It starts the same selected fork build and only marks the receipt complete after the new systemd invocation, listener PID, health version, and service uptime are verified. It never downloads, installs, or selects a release and never runs the T3 CLI against the live database. Once a captured receipt exists, retrying the same operation ID resumes or returns that receipt without taking another snapshot. If the process ends before that receipt is written, inspect the guard events and snapshot directory before starting another operation. +Before systemd receives a stop request, the guard fsyncs an owner-only intent receipt. It copies the SQLite files and WAL/SHM sidecars with the existing reflink path only after systemd confirms the unit is inactive, then fsyncs the copy and records that state durably. It restarts the same selected fork build before hashing the copied files, and marks the receipt complete only after the new systemd invocation, listener descendant and cgroup, health version, and service uptime are verified. The receipt includes the operation ID, snapshot point, stopped unit invocation and launcher PID, both idle censuses, snapshot path, and each copied file's SHA-256 and size. This one-off operation preserves earlier snapshots instead of applying the update path's three-snapshot rotation. It never downloads, installs, or selects a release and never runs the T3 CLI against the live database. A retry returns a complete receipt or resumes from its durable state; it never sends a second stop for the same operation ID. If a stop was recorded but the unit is active again before a copy was recorded, the guard refuses that operation ID so the caller can inspect the receipt and retained files before choosing a new one. The guard receipt proves which stopped-service files were copied and that the same fork build returned. A caller must still perform isolated readback against the retained copy; this command does not claim migration compatibility or publication of another release. diff --git a/scripts/fork/host/t3-update-guard/guard b/scripts/fork/host/t3-update-guard/guard index 3b0a49c51809e..2abb0ab6ff91a 100755 --- a/scripts/fork/host/t3-update-guard/guard +++ b/scripts/fork/host/t3-update-guard/guard @@ -892,24 +892,45 @@ SNAPSHOTS="$T3HOME/runtime/guard-db-snapshots" # Copy-on-write snapshot of the databases (btrfs reflink: instant, shares blocks). The service # must be stopped so the copy is consistent. Prints the snapshot directory. snapshot_db() { - local label="$1" retain_all="${2:-}" dir f copied=0 + local label="$1" retain_all="${2:-}" requested_dir="${3:-}" skip_compare="${4:-}" dir f copied=0 + local created_dir=0 [[ "$label" =~ ^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$ ]] || return 1 [[ -f "$DB" && ! -L "$DB" ]] || return 1 mkdir -p "$SNAPSHOTS" || return 1 chmod 700 "$SNAPSHOTS" || return 1 - dir="$SNAPSHOTS/$(date +%Y%m%dT%H%M%S)-$label" - mkdir "$dir" || return 1 - chmod 700 "$dir" || { rmdir "$dir" 2>/dev/null; return 1; } + if [[ -n "$requested_dir" ]]; then + dir="$requested_dir" + [[ "$dir" == "$SNAPSHOTS/"* && -d "$dir" && ! -L "$dir" && \ + "$(stat -c %a "$dir" 2>/dev/null)" == 700 ]] || return 1 + # A previous attempt may have ended during its copy. Replace only SQLite files in this + # operation's private directory while the service is confirmed down. + for f in "$dir"/*; do + [[ -e "$f" ]] || continue + [[ -f "$f" && ! -L "$f" && "$(basename "$f")" =~ ^[A-Za-z0-9][A-Za-z0-9._-]*\.sqlite(-wal|-shm)?$ ]] || return 1 + rm -f -- "$f" || return 1 + done + else + dir="$SNAPSHOTS/$(date +%Y%m%dT%H%M%S)-$label" + mkdir "$dir" || return 1 + created_dir=1 + chmod 700 "$dir" || { rmdir "$dir" 2>/dev/null; return 1; } + fi for f in "$T3HOME"/userdata/*.sqlite "$T3HOME"/userdata/*.sqlite-wal "$T3HOME"/userdata/*.sqlite-shm; do [[ -e "$f" ]] || continue - [[ -f "$f" && ! -L "$f" ]] || { rm -rf "$dir"; return 1; } - cp --reflink=always -p "$f" "$dir/" && cmp -s "$f" "$dir/$(basename "$f")" || { - rm -rf "$dir" + [[ -f "$f" && ! -L "$f" ]] || { [[ "$created_dir" == 0 ]] || rm -rf "$dir"; return 1; } + cp --reflink=always -p "$f" "$dir/" && \ + { [[ "$skip_compare" == skip-compare ]] || cmp -s "$f" "$dir/$(basename "$f")"; } || { + [[ "$created_dir" == 0 ]] || rm -rf "$dir" return 1 } copied=$((copied + 1)) done - (( copied > 0 )) || { rm -rf "$dir"; return 1; } + (( copied > 0 )) || { [[ "$created_dir" == 0 ]] || rm -rf "$dir"; return 1; } + if [[ "$skip_compare" == skip-compare ]]; then + local files=() + for f in "$dir"/*; do [[ -f "$f" && ! -L "$f" ]] && files+=("$f"); done + snapshot_fsync "${files[@]}" "$dir" "$SNAPSHOTS" || return 1 + fi # Keep the newest three. if [[ "$retain_all" != retain-all ]]; then ls -1d "$SNAPSHOTS"/2* 2>/dev/null | sort | head -n -3 | xargs -r rm -rf @@ -971,8 +992,8 @@ wait_inactive() { unit_property() { systemctl --user show -p "$1" --value "$UNIT" 2>/dev/null; } -# The snapshot receipt binds the copy to the actual systemd invocation and the process that -# owned the loopback listener. A health endpoint alone could be answered by a stale process. +# The service launcher is MainPID; its listener is a child. Bind the listener to that launcher +# and to the exact systemd unit cgroup, so a stale or unrelated loopback process cannot pass. service_listener_pid() { local output pids [[ "$PORT" =~ ^[1-9][0-9]{0,4}$ ]] && (( 10#$PORT <= 65535 )) || return 1 @@ -982,8 +1003,30 @@ service_listener_pid() { printf '%s' "$pids" } +process_is_descendant_of() { + local child="$1" ancestor="$2" current="$1" ppid depth=0 + [[ "$child" =~ ^[1-9][0-9]*$ && "$ancestor" =~ ^[1-9][0-9]*$ ]] || return 1 + while [[ "$current" =~ ^[1-9][0-9]*$ ]] && (( depth < 64 )); do + [[ "$current" == "$ancestor" ]] && return 0 + [[ -r "/proc/$current/status" ]] || return 1 + ppid=$(awk '/^PPid:/ { print $2; exit }' "/proc/$current/status") || return 1 + [[ "$ppid" =~ ^[0-9]+$ && "$ppid" != "$current" ]] || return 1 + current="$ppid" + depth=$((depth + 1)) + done + return 1 +} + +process_in_unit_cgroup() { + local pid="$1" unit_group="$2" process_group + [[ "$pid" =~ ^[1-9][0-9]*$ && "$unit_group" == /* && "$unit_group" != *$'\n'* ]] || return 1 + process_group=$(awk -F: '$1 == "0" { print $3; exit }' "/proc/$pid/cgroup") || return 1 + [[ "$unit_group" == "/" && "$process_group" == /* ]] || \ + [[ "$process_group" == "$unit_group" || "$process_group" == "$unit_group/"* ]] +} + snapshot_service_identity() { - local expected="$1" state invocation pid listener version uptime + local expected="$1" state invocation pid listener version uptime control_group state=$(unit_property ActiveState) || return 1 [[ "$state" == active ]] || return 1 invocation=$(unit_property InvocationID) || return 1 @@ -991,7 +1034,11 @@ snapshot_service_identity() { pid=$(unit_property MainPID) || return 1 [[ "$pid" =~ ^[1-9][0-9]*$ ]] || return 1 listener=$(service_listener_pid) || return 1 - [[ "$listener" == "$pid" ]] || return 1 + [[ "$listener" =~ ^[1-9][0-9]*$ && "$listener" != "$pid" ]] || return 1 + control_group=$(unit_property ControlGroup) || return 1 + process_is_descendant_of "$listener" "$pid" || return 1 + process_in_unit_cgroup "$pid" "$control_group" || return 1 + process_in_unit_cgroup "$listener" "$control_group" || return 1 version=$(service_version) || return 1 [[ "$version" == "$expected" ]] || return 1 uptime=$(service_uptime) || return 1 @@ -1003,27 +1050,34 @@ snapshot_service_identity() { # any pending request, and every active tool item hold it. The DB read is deliberately repeated # immediately before the stop; unreadable or incomplete evidence fails closed. snapshot_idle_evidence() { - local counts runs requests tools quiet checked_at + local counts runs requests tools subagents background effects quiet checked_at counts=$(timeout 10 sqlite3 -readonly -separator '|' "$DB" \ "select - (select count(*) from orchestration_v2_projection_runs where status in ('running','starting','waiting','queued')), + (select count(*) from orchestration_v2_projection_runs where status in ('preparing','queued','starting','running','waiting')), (select count(*) from orchestration_v2_projection_runtime_requests where status = 'pending'), - (select count(*) from orchestration_v2_projection_runs r - cross join orchestration_v2_projection_turn_items i - on i.thread_id = r.thread_id and i.run_id = r.run_id - where r.status in ('running','starting','waiting','queued') - and i.status in ('pending','running','waiting') - and i.type in ('command_execution','dynamic_tool','file_change'));") || { + (select count(*) from orchestration_v2_projection_turn_items i + where i.status in ('pending','running','waiting') + and i.type in ('command_execution','dynamic_tool','file_change','subagent','link_request') + and not exists (select 1 from orchestration_v2_projection_runs r + where r.run_id = i.run_id and r.status = 'rolled_back')), + (select count(*) from orchestration_v2_projection_subagents + where status not in ('idle','completed','failed','cancelled','interrupted')), + (select count(*) from orchestration_v2_projection_provider_threads + where not json_valid(payload_json) + or (json_type(payload_json,'$.pendingBackgroundTasks') is not null + and (json_type(payload_json,'$.pendingBackgroundTasks') != 'array' + or json_array_length(payload_json,'$.pendingBackgroundTasks') > 0))), + (select count(*) from orchestration_v2_effect_outbox where status in ('pending','running'));" ) || { echo "snapshot: activity database is unreadable" >&2 return 1 } - IFS='|' read -r runs requests tools <<<"$counts" - [[ "$runs" =~ ^[0-9]+$ && "$requests" =~ ^[0-9]+$ && "$tools" =~ ^[0-9]+$ ]] || { + IFS='|' read -r runs requests tools subagents background effects <<<"$counts" + [[ "$runs" =~ ^[0-9]+$ && "$requests" =~ ^[0-9]+$ && "$tools" =~ ^[0-9]+$ && "$subagents" =~ ^[0-9]+$ && "$background" =~ ^[0-9]+$ && "$effects" =~ ^[0-9]+$ ]] || { echo "snapshot: activity census is incomplete" >&2 return 1 } - (( runs == 0 && requests == 0 && tools == 0 )) || { - echo "snapshot: activity remains (runs=$runs pendingRequests=$requests activeTools=$tools)" >&2 + (( runs == 0 && requests == 0 && tools == 0 && subagents == 0 && background == 0 && effects == 0 )) || { + echo "snapshot: activity remains (runs=$runs pendingRequests=$requests activeItems=$tools activeSubagents=$subagents providerBackgroundTasks=$background activeEffects=$effects)" >&2 return 1 } quiet=$(quiet_seconds) || quiet="" @@ -1033,8 +1087,9 @@ snapshot_idle_evidence() { } checked_at=$(date -u +%Y-%m-%dT%H:%M:%S.000Z) jq -cn --arg checkedAt "$checked_at" --argjson runs "$runs" \ - --argjson requests "$requests" --argjson tools "$tools" --argjson quiet "$quiet" \ - '{checkedAt:$checkedAt,runs:$runs,pendingRequests:$requests,activeTools:$tools,quietSeconds:$quiet}' + --argjson requests "$requests" --argjson tools "$tools" --argjson subagents "$subagents" \ + --argjson background "$background" --argjson effects "$effects" --argjson quiet "$quiet" \ + '{checkedAt:$checkedAt,runs:$runs,pendingRequests:$requests,activeItems:$tools,activeSubagents:$subagents,providerBackgroundTasks:$background,activeEffects:$effects,quietSeconds:$quiet}' } snapshot_manifest() { @@ -1054,13 +1109,27 @@ snapshot_manifest() { printf '%s' "$files" } +snapshot_fsync() { + python3 -c 'import os, sys +for path in sys.argv[1:]: + flags = os.O_RDONLY + if os.path.isdir(path): + flags |= getattr(os, "O_DIRECTORY", 0) + fd = os.open(path, flags) + try: + os.fsync(fd) + finally: + os.close(fd)' "$@" +} + write_snapshot_receipt() { local receipt="$1" json="$2" dir="${1%/*}" ( umask 077 local tmp tmp=$(mktemp "$dir/.snapshot-receipt.XXXXXX") || exit 1 - if ! printf '%s\n' "$json" >"$tmp" || ! chmod 600 "$tmp" || ! mv -f -- "$tmp" "$receipt"; then + if ! printf '%s\n' "$json" >"$tmp" || ! chmod 600 "$tmp" || \ + ! snapshot_fsync "$tmp" || ! mv -f -- "$tmp" "$receipt" || ! snapshot_fsync "$dir"; then rm -f -- "$tmp" exit 1 fi @@ -1076,9 +1145,9 @@ snapshot_receipt_matches() { [[ "$(jq -r '.snapshotPoint // empty' "$receipt" 2>/dev/null)" == "$point" ]] || return 1 [[ "$(jq -r '.schemaVersion // empty' "$receipt" 2>/dev/null)" == 1 ]] || return 1 [[ "$(jq -r '.unit // empty' "$receipt" 2>/dev/null)" == "$UNIT" ]] || return 1 - [[ "$(jq -e '.files | type == "array" and length > 0' "$receipt" 2>/dev/null)" == true ]] || return 1 status=$(jq -r '.status // empty' "$receipt" 2>/dev/null) - [[ "$status" == captured || "$status" == restart_failed || "$status" == complete ]] || return 1 + [[ "$status" == prepared || "$status" == stop_requested || "$status" == copied || \ + "$status" == captured || "$status" == restart_failed || "$status" == complete ]] || return 1 version=$(jq -r '.stoppedGeneration.version // empty' "$receipt" 2>/dev/null) invocation=$(jq -r '.stoppedGeneration.invocationId // empty' "$receipt" 2>/dev/null) pid=$(jq -r '.stoppedGeneration.mainPid // empty' "$receipt" 2>/dev/null) @@ -1091,8 +1160,19 @@ snapshot_receipt_matches() { -n "$(jq -r '.restart.verifiedAt // empty' "$receipt" 2>/dev/null)" ]] || return 1 fi path=$(jq -r '.snapshotPath // empty' "$receipt" 2>/dev/null) - [[ "$path" == "$SNAPSHOTS/"* && -d "$path" && \ - "$(stat -c %a "$path" 2>/dev/null)" == 700 && -f "$path/$(basename "$DB")" ]] || return 1 + [[ "$path" == "$SNAPSHOTS/"* && ! -L "$path" ]] || return 1 + if [[ "$status" == prepared || "$status" == stop_requested ]]; then + [[ -d "$path" && "$(stat -c %a "$path" 2>/dev/null)" == 700 ]] || return 1 + [[ "$(jq -e '.files | type == "array" and length == 0' "$receipt" 2>/dev/null)" == true ]] + return + fi + [[ -d "$path" && "$(stat -c %a "$path" 2>/dev/null)" == 700 && \ + -f "$path/$(basename "$DB")" && ! -L "$path/$(basename "$DB")" ]] || return 1 + if [[ "$status" == copied ]]; then + [[ "$(jq -e '.files | type == "array" and length == 0' "$receipt" 2>/dev/null)" == true ]] + return + fi + [[ "$(jq -e '.files | type == "array" and length > 0' "$receipt" 2>/dev/null)" == true ]] || return 1 while IFS=$'\t' read -r name sha; do [[ "$name" =~ ^[A-Za-z0-9][A-Za-z0-9._-]*$ && "$sha" =~ ^[[:xdigit:]]{64}$ ]] || return 1 [[ -f "$path/$name" && ! -L "$path/$name" ]] || return 1 @@ -1138,19 +1218,65 @@ snapshot_receipt_finalize() { write_snapshot_receipt "$receipt" "$updated" } +snapshot_receipt_set_status() { + local receipt="$1" status="$2" updated + updated=$(jq -c --arg status "$status" '.status=$status' "$receipt") || return 1 + write_snapshot_receipt "$receipt" "$updated" +} + +snapshot_receipt_set_idle_evidence() { + local receipt="$1" first="$2" second="$3" identity="$4" updated invocation pid version uptime + IFS='|' read -r invocation pid version uptime <<<"$identity" + updated=$(jq -c --arg invocation "$invocation" --arg pid "$pid" --arg version "$version" \ + --argjson first "$first" --argjson second "$second" \ + '.idleVerification={first:$first,second:$second} | .stoppedGeneration={invocationId:$invocation,mainPid:($pid|tonumber),version:$version}' \ + "$receipt") || return 1 + write_snapshot_receipt "$receipt" "$updated" +} + +snapshot_receipt_set_copied() { + local receipt="$1" updated copied_at + copied_at=$(date -u +%Y-%m-%dT%H:%M:%S.000Z) + updated=$(jq -c --arg copiedAt "$copied_at" '.status="copied" | .files=[] | .copiedAt=$copiedAt' "$receipt") || return 1 + write_snapshot_receipt "$receipt" "$updated" +} + +snapshot_receipt_set_manifest() { + local receipt="$1" files="$2" updated captured_at + captured_at=$(date -u +%Y-%m-%dT%H:%M:%S.000Z) + updated=$(jq -c --argjson files "$files" --arg capturedAt "$captured_at" \ + '.status="captured" | .files=$files | .capturedAt=$capturedAt' "$receipt") || return 1 + write_snapshot_receipt "$receipt" "$updated" +} + cmd_snapshot() { - local operation="${1:-}" point="${2:-}" receipt_dir receipt status version identity stopped_invocation stopped_pid \ - activity snapshot identity_after files captured_at json generation hang state restart_invocation - [[ $# == 2 && "$operation" =~ ^[A-Za-z0-9][A-Za-z0-9._-]{0,95}$ && \ + local operation="" point="" label label_length receipt_dir receipt status version identity + local stopped_invocation stopped_pid first_activity second_activity snapshot identity_after + local files generation hang state restart_invocation json + + if [[ $# != 2 ]]; then + echo "usage: t3-service-update snapshot " >&2 + return 2 + fi + operation=$1 + point=$2 + [[ "$operation" =~ ^[A-Za-z0-9][A-Za-z0-9._-]{0,95}$ && \ "$point" =~ ^[A-Za-z0-9][A-Za-z0-9._-]{0,95}$ ]] || { echo "usage: t3-service-update snapshot " >&2 return 2 } + label="snapshot-$operation-$point" + label_length=$(printf '%s' "$label" | wc -c) + (( label_length <= 128 )) || { + echo "snapshot: combined operation and point label exceeds the snapshot filename limit" >&2 + return 2 + } manager_ready || { echo "snapshot: user service manager unavailable" >&2; return 1; } exec 9>>"$LOCK" flock -n 9 || { echo "Another service change holds $LOCK." >&2; return 1; } receipt_dir="$GUARD_STATE/snapshot-receipts" mkdir -p "$receipt_dir" && chmod 700 "$receipt_dir" || return 1 + snapshot_fsync "$receipt_dir" "$GUARD_STATE" || return 1 receipt="$receipt_dir/$operation.json" if [[ -e "$receipt" ]]; then @@ -1171,156 +1297,205 @@ cmd_snapshot() { cat "$receipt" return fi - version=$(jq -r '.stoppedGeneration.version // empty' "$receipt") - stopped_invocation=$(jq -r '.stoppedGeneration.invocationId // empty' "$receipt") - [[ -n "$version" && -n "$stopped_invocation" && "$(active_version)" == "$version" ]] && \ - is_trusted "$version" && is_healthy "$version" || { - echo "snapshot: captured receipt exists, but its original trusted service version is not selected" >&2 + version=$(jq -r '.stoppedGeneration.version' "$receipt") + stopped_invocation=$(jq -r '.stoppedGeneration.invocationId' "$receipt") + stopped_pid=$(jq -r '.stoppedGeneration.mainPid' "$receipt") + snapshot=$(jq -r '.snapshotPath' "$receipt") + [[ "$(active_version)" == "$version" ]] && is_trusted "$version" && is_healthy "$version" || { + echo "snapshot: receipt exists, but its original trusted service version is not selected" >&2 return 1 } - state=$(unit_property ActiveState) || state="unknown" - if [[ "$state" == active ]] && identity=$(snapshot_wait_serving "$version" "$stopped_invocation"); then - snapshot_receipt_finalize "$receipt" "$identity" complete || return 1 - outage_end "$version" - cat "$receipt" - return + else + version=$(active_version) + [[ -n "$version" ]] && is_trusted "$version" && is_healthy "$version" || { + echo "snapshot: active version is not both trusted and recorded healthy" >&2 + return 1 + } + [[ -f "$DB" && ! -L "$DB" ]] || { echo "snapshot: primary database is missing or not a regular file" >&2; return 1; } + identity=$(snapshot_service_identity "$version") || { + echo "snapshot: managed unit, listener descendant, cgroup, health version, or generation is not verified" >&2 + return 1 + } + IFS='|' read -r stopped_invocation stopped_pid _ _ <<<"$identity" + first_activity=$(snapshot_idle_evidence) || return 1 + second_activity=$(snapshot_idle_evidence) || return 1 + identity_after=$(snapshot_service_identity "$version") || { + echo "snapshot: service identity changed before stop" >&2 + return 1 + } + IFS='|' read -r generation stopped_pid _ _ <<<"$identity_after" + [[ "$generation" == "$stopped_invocation" ]] || { + echo "snapshot: service generation changed before stop" >&2 + return 1 + } + if hang=$(kernel_hang_signs); then + echo "snapshot: refusing stop while the kernel exit-hang guard is active: $hang" >&2 + return 1 fi - identity=$(snapshot_start_and_verify "$version" "$stopped_invocation") || { - snapshot_receipt_finalize "$receipt" "0|0|$version|0" restart_failed "same-version service did not pass the guarded listener health check" || true - hold_updates "snapshot operation $operation copied the database but could not verify same-version service restart" + mkdir -p "$SNAPSHOTS" && chmod 700 "$SNAPSHOTS" || return 1 + snapshot="$SNAPSHOTS/$(date +%Y%m%dT%H%M%S)-$label" + mkdir "$snapshot" && chmod 700 "$snapshot" || { + rmdir "$snapshot" 2>/dev/null || true return 1 } - snapshot_receipt_finalize "$receipt" "$identity" complete || return 1 - outage_end "$version" - cat "$receipt" - return + snapshot_fsync "$snapshot" "$SNAPSHOTS" || { + rmdir "$snapshot" 2>/dev/null || true + return 1 + } + json=$(jq -cn --arg operation "$operation" --arg point "$point" --arg unit "$UNIT" \ + --arg invocation "$stopped_invocation" --arg pid "$stopped_pid" --arg version "$version" \ + --arg path "$snapshot" --argjson first "$first_activity" --argjson second "$second_activity" \ + '{schemaVersion:1,operationId:$operation,snapshotPoint:$point,unit:$unit,status:"prepared",snapshotPath:$path,files:[],idleVerification:{first:$first,second:$second},stoppedGeneration:{invocationId:$invocation,mainPid:($pid|tonumber),version:$version}}') || { + rmdir "$snapshot" 2>/dev/null || true + return 1 + } + if ! write_snapshot_receipt "$receipt" "$json"; then + rmdir "$snapshot" 2>/dev/null || true + echo "snapshot: could not durably record the prepared operation; service was not stopped" >&2 + return 1 + fi + status=prepared fi - version=$(active_version) - [[ -n "$version" ]] && is_trusted "$version" && is_healthy "$version" || { - echo "snapshot: active version is not both trusted and recorded healthy" >&2 - return 1 - } - [[ -f "$DB" && ! -L "$DB" ]] || { echo "snapshot: primary database is missing or not a regular file" >&2; return 1; } - identity=$(snapshot_service_identity "$version") || { - echo "snapshot: managed unit, listener PID, health version, or generation is not verified" >&2 - return 1 - } - IFS='|' read -r stopped_invocation stopped_pid _ _ <<<"$identity" - activity=$(snapshot_idle_evidence) || return 1 - - # Re-read both activity and service identity immediately before requesting the stop. - activity=$(snapshot_idle_evidence) || return 1 - identity_after=$(snapshot_service_identity "$version") || { - echo "snapshot: service identity changed before stop" >&2 - return 1 - } - IFS='|' read -r generation stopped_pid _ _ <<<"$identity_after" - [[ "$generation" == "$stopped_invocation" ]] || { - echo "snapshot: service generation changed before stop" >&2 - return 1 - } - if hang=$(kernel_hang_signs); then - echo "snapshot: refusing stop while the kernel exit-hang guard is active: $hang" >&2 - return 1 - fi - log "snapshot: operation=$operation point=$point stopping $UNIT on $version after verified idle census" - if ! svc stop --no-block "$UNIT"; then - state=$(unit_property ActiveState) || state="unknown" - if [[ "$state" == active ]] && snapshot_service_identity "$version" >/dev/null; then - : # The stop did not take effect; leave the verified serving invocation untouched. - else - outage_begin "snapshot operation $operation" - if ! identity=$(snapshot_start_and_verify "$version" "$stopped_invocation"); then - hold_updates "snapshot operation $operation stop returned failure and same-version recovery could not be verified" + if [[ "$status" == prepared ]]; then + [[ "$(active_version)" == "$version" ]] && is_trusted "$version" && is_healthy "$version" || { + echo "snapshot: prepared operation no longer selects its original trusted service version" >&2 + return 1 + } + identity=$(snapshot_service_identity "$version") || { + echo "snapshot: prepared service identity is no longer verified" >&2 + return 1 + } + IFS='|' read -r generation _ _ _ <<<"$identity" + [[ "$generation" == "$stopped_invocation" ]] || { + echo "snapshot: prepared service generation changed; no stop requested" >&2 + return 1 + } + first_activity=$(snapshot_idle_evidence) || return 1 + second_activity=$(snapshot_idle_evidence) || return 1 + identity_after=$(snapshot_service_identity "$version") || { + echo "snapshot: service identity changed immediately before the stop request" >&2 + return 1 + } + IFS='|' read -r generation stopped_pid _ _ <<<"$identity_after" + [[ "$generation" == "$stopped_invocation" ]] || { + echo "snapshot: service generation changed immediately before the stop request" >&2 + return 1 + } + if hang=$(kernel_hang_signs); then + echo "snapshot: refusing stop while the kernel exit-hang guard is active: $hang" >&2 + return 1 + fi + snapshot_receipt_set_idle_evidence "$receipt" "$first_activity" "$second_activity" "$identity_after" || { + echo "snapshot: could not durably update the idle proof; service was not stopped" >&2 + return 1 + } + # This write-ahead state is fsynced before systemd receives the stop request. A retry can + # recover from an inactive unit, but it will never send a second stop for this operation ID. + snapshot_receipt_set_status "$receipt" stop_requested || { + echo "snapshot: could not durably record stop intent; service was not stopped" >&2 + return 1 + } + status=stop_requested + log "snapshot: operation=$operation point=$point stopping $UNIT on $version after fresh idle census" + if ! svc stop --no-block "$UNIT"; then + state=$(unit_property ActiveState) || state="unknown" + if [[ "$state" == inactive || "$state" == failed ]]; then + outage_begin "snapshot operation $operation" + else + hold_updates "snapshot operation $operation recorded stop intent but the unit is not confirmed stopped; retry will not issue another stop" + echo "snapshot: stop request failed or remained ambiguous; retry will not stop $UNIT again" >&2 return 1 fi - outage_end "$version" - fi - echo "snapshot: stop request for $UNIT failed; no database copy attempted" >&2 - return 1 - fi - outage_begin "snapshot operation $operation" - if ! wait_inactive; then - state=$(unit_property ActiveState) || state="unknown" - if [[ "$state" == active ]] && snapshot_service_identity "$version" >/dev/null; then - outage_end "$version" else - if ! identity=$(snapshot_start_and_verify "$version" "$stopped_invocation"); then - hold_updates "snapshot operation $operation timed out stopping $UNIT and same-version recovery could not be verified" + outage_begin "snapshot operation $operation" + if ! wait_inactive; then + hold_updates "snapshot operation $operation recorded stop intent but $UNIT did not become inactive; retry will not issue another stop" + echo "snapshot: $UNIT did not become inactive within 120 seconds; retry will not issue another stop" >&2 return 1 fi - outage_end "$version" fi - echo "snapshot: $UNIT did not become inactive within 120 seconds; no copy attempted" >&2 - return 1 fi - status=$(unit_property ActiveState) || status="unknown" - if [[ "$status" != inactive && "$status" != failed ]]; then - if [[ "$status" == active ]] && snapshot_service_identity "$version" >/dev/null; then - outage_end "$version" - else - if ! identity=$(snapshot_start_and_verify "$version" "$stopped_invocation"); then - hold_updates "snapshot operation $operation could not verify $UNIT inactive or restore the same-version service" + + if [[ "$status" == stop_requested ]]; then + state=$(unit_property ActiveState) || state="unknown" + if [[ "$state" == deactivating ]]; then + wait_inactive || { + hold_updates "snapshot operation $operation is still waiting for its already-requested stop" + echo "snapshot: existing stop request is still in progress; no second stop was sent" >&2 return 1 - fi - outage_end "$version" + } + state=$(unit_property ActiveState) || state="unknown" fi - echo "snapshot: could not confirm $UNIT remained inactive; no copy attempted" >&2 - return 1 - fi - snapshot=$(snapshot_db "snapshot-$operation-$point" retain-all) || { - if ! identity=$(snapshot_start_and_verify "$version" "$stopped_invocation"); then - hold_updates "snapshot operation $operation failed to copy the database and same-version restart could not be verified" + if [[ "$state" != inactive && "$state" != failed ]]; then + echo "snapshot: stop intent already exists while the original service invocation is active; refusing a second stop" >&2 return 1 fi - outage_end "$version" - echo "snapshot: stopped database copy failed; $version was restarted and verified" >&2 - return 1 - } - files=$(snapshot_manifest "$snapshot") || { - if ! identity=$(snapshot_start_and_verify "$version" "$stopped_invocation"); then - hold_updates "snapshot operation $operation created an unverifiable copy and same-version restart could not be verified" + outage_begin "snapshot operation $operation" + snapshot=$(snapshot_db "$label" retain-all "$snapshot" skip-compare) || { + if identity=$(snapshot_start_and_verify "$version" "$stopped_invocation"); then + outage_end "$version" + else + hold_updates "snapshot operation $operation stopped the service, could not copy its database, and same-version restart failed" + fi + echo "snapshot: stopped database copy failed; no second stop will be issued for this operation" >&2 return 1 - fi - outage_end "$version" - echo "snapshot: copied files did not produce a valid manifest; $version was restarted and verified" >&2 - return 1 - } - captured_at=$(date -u +%Y-%m-%dT%H:%M:%S.000Z) - json=$(jq -cn --arg operation "$operation" --arg point "$point" --arg unit "$UNIT" \ - --arg invocation "$stopped_invocation" --arg pid "$stopped_pid" --arg version "$version" \ - --arg path "$snapshot" --arg capturedAt "$captured_at" --argjson files "$files" \ - --argjson activity "$activity" \ - '{schemaVersion:1,operationId:$operation,snapshotPoint:$point,unit:$unit,status:"captured",snapshotPath:$path,files:$files,idleVerification:$activity,stoppedGeneration:{invocationId:$invocation,mainPid:($pid|tonumber),version:$version},capturedAt:$capturedAt}') || { - if ! identity=$(snapshot_start_and_verify "$version" "$stopped_invocation"); then - hold_updates "snapshot operation $operation could not record its receipt or verify same-version restart" + } + snapshot_receipt_set_copied "$receipt" || { + if identity=$(snapshot_start_and_verify "$version" "$stopped_invocation"); then + outage_end "$version" + else + hold_updates "snapshot operation $operation copied its database but could not durably record the copy or verify restart" + fi + echo "snapshot: copied files exist but the copied state could not be durably recorded" >&2 return 1 - fi - outage_end "$version" - return 1 - } - if ! write_snapshot_receipt "$receipt" "$json"; then - if ! identity=$(snapshot_start_and_verify "$version" "$stopped_invocation"); then - hold_updates "snapshot operation $operation copied the database but receipt write and same-version restart could not be verified" + } + status=copied + fi + + if [[ "$status" == copied || "$status" == captured || "$status" == restart_failed ]]; then + [[ "$(active_version)" == "$version" ]] && is_trusted "$version" && is_healthy "$version" || { + echo "snapshot: refusing to start anything except the original trusted service version $version" >&2 return 1 + } + state=$(unit_property ActiveState) || state="unknown" + if [[ "$state" == active || "$state" == activating || "$state" == deactivating ]]; then + identity=$(snapshot_wait_serving "$version" "$stopped_invocation") || { + hold_updates "snapshot operation $operation retained its copy but the same-version listener is not healthy" + echo "snapshot: copied database retained; same-version service health is not verified" >&2 + return 1 + } + else + identity=$(snapshot_start_and_verify "$version" "$stopped_invocation") || { + hold_updates "snapshot operation $operation copied the database but could not verify the same-version service restart" + echo "snapshot: copied database retained; same-version service health is not verified" >&2 + return 1 + } fi - outage_end "$version" - echo "snapshot: receipt could not be written; $version was restarted and verified" >&2 - return 1 + if [[ "$status" == copied ]]; then + files=$(snapshot_manifest "$snapshot") || { + hold_updates "snapshot operation $operation restarted the service but could not verify the copied files" + echo "snapshot: service restarted; copied files did not produce a valid manifest" >&2 + return 1 + } + snapshot_receipt_set_manifest "$receipt" "$files" || { + hold_updates "snapshot operation $operation restarted the service but could not durably record its file manifest" + echo "snapshot: service restarted; file manifest could not be durably recorded" >&2 + return 1 + } + status=captured + log "snapshot: operation=$operation hashed $(jq 'length' <<<"$files") copied files after same-version restart" + fi + snapshot_receipt_finalize "$receipt" "$identity" complete || { + hold_updates "snapshot operation $operation restarted the service but could not durably complete its receipt" + return 1 + } fi - log "snapshot: copied $snapshot ($(jq 'length' <<<"$files") files) for operation=$operation" - identity=$(snapshot_start_and_verify "$version" "$stopped_invocation") || { - snapshot_receipt_finalize "$receipt" "0|0|$version|0" restart_failed "same-version service did not pass the guarded listener health check" || true - hold_updates "snapshot operation $operation copied the database but could not verify same-version service restart" - return 1 - } - snapshot_receipt_finalize "$receipt" "$identity" complete || return 1 + outage_end "$version" log "snapshot: operation=$operation restarted and verified $version" cat "$receipt" } - # Install the newest trusted release (or $1), verify it serves, roll back if not. cmd_update() { local now_flag="" target="" cur latest runs sha blockers="" forced="" hang deferred_epoch="" diff --git a/scripts/fork/host/t3-update-guard/test-guard.sh b/scripts/fork/host/t3-update-guard/test-guard.sh index c68522eb83711..660da3d89da66 100755 --- a/scripts/fork/host/t3-update-guard/test-guard.sh +++ b/scripts/fork/host/t3-update-guard/test-guard.sh @@ -601,9 +601,9 @@ systemctl --user is-active t3code.service [[ "$(cat "$root/timeout")" == '--kill-after=2 15 /usr/bin/systemctl --user is-active t3code.service' ]] || fail timeout pass 'all systemctl calls have a bounded timeout' -# Snapshot-only path: strict activity refusal, copied SQLite sidecars, receipt privacy, same-build -# restart, preservation of older snapshots, and operation-ID idempotency. All service calls are -# simulated; no live T3 unit or database is touched. +# Snapshot-only path: real launcher-child listener in the current cgroup, full idle refusal, +# durable write-ahead intent, copy/restart timing, receipt privacy, and operation-ID idempotency. +# Service state and database changes are isolated; no live T3 unit or database is touched. ( exec 9>&- unset -f timeout @@ -616,36 +616,145 @@ pass 'all systemctl calls have a bounded timeout' sqlite3 "$DB" "pragma user_version=119; create table orchestration_v2_projection_runs (run_id text, thread_id text, status text, requested_at text, completed_at text, payload_json text); create table orchestration_v2_projection_runtime_requests (runtime_request_id text, status text, resolved_at text); - create table orchestration_v2_projection_turn_items (turn_item_id text, thread_id text, run_id text, type text, status text, updated_at text);" + create table orchestration_v2_projection_turn_items (turn_item_id text, thread_id text, run_id text, type text, status text, updated_at text); + create table orchestration_v2_projection_subagents (subagent_id text, status text); + create table orchestration_v2_projection_provider_threads (provider_thread_id text, payload_json text); + create table orchestration_v2_effect_outbox (effect_id text, status text);" sim_version=0.1.13-preview.20261127.1 - sim_state=active sim_generation=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa sim_pid=1111 + sim_control_group="" + PORT=$(python3 -c 'import socket; s=socket.socket(); s.bind(("127.0.0.1",0)); print(s.getsockname()[1]); s.close()') + export PORT + sim_command_fifo="$root/snapshot-command" + sim_listener_file="$root/snapshot-listener.pid" + sim_state_file="$root/snapshot-unit-state" + sim_generation_file="$root/snapshot-generation" + mkfifo "$sim_command_fifo" + printf 'inactive\n' >"$sim_state_file" + printf 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n' >"$sim_generation_file" + cat >"$root/snapshot-launcher.sh" <<'EOF' +#!/bin/bash +set -eu +command_fifo=$1 +listener_file=$2 +port=$3 +listener_pid="" +stop_listener() { + if [[ -n "$listener_pid" ]]; then + kill "$listener_pid" 2>/dev/null || true + wait "$listener_pid" 2>/dev/null || true + listener_pid="" + fi + : >"$listener_file" +} +trap stop_listener EXIT +exec 3<>"$command_fifo" +while IFS= read -r command; do + case "$command" in + start) + node -e 'const net=require("net"); const s=net.createServer(); s.listen(Number(process.argv[1]),"127.0.0.1"); setInterval(()=>{},1000)' "$port" >/dev/null 2>&1 & + listener_pid=$! + printf '%s\n' "$listener_pid" >"$listener_file" + ;; + stop) stop_listener ;; + quit) exit 0 ;; + esac +done <&3 +EOF + chmod +x "$root/snapshot-launcher.sh" + bash "$root/snapshot-launcher.sh" "$sim_command_fifo" "$sim_listener_file" "$PORT" >/dev/null 2>&1 & + sim_launcher_pid=$! + sim_pid=$sim_launcher_pid + sim_control_group=$(awk -F: '$1 == "0" { print $3; exit }' "/proc/$sim_pid/cgroup") + [[ -n "$sim_control_group" ]] || fail 'fixture launcher has no unified cgroup' + printf 'active\n' >"$sim_state_file" + printf 'start\n' >"$sim_command_fifo" + cleanup_sim_listener() { + printf 'quit\n' >"$sim_command_fifo" 2>/dev/null || true + kill "$sim_pid" 2>/dev/null || true + wait "$sim_pid" 2>/dev/null || true + } + trap cleanup_sim_listener EXIT + for ((i=0; i<50; i++)); do + service_listener_pid >/dev/null 2>&1 && break + sleep 0.05 + done + service_listener_pid >/dev/null 2>&1 || fail 'could not start the isolated launcher-child listener' manager_ready() { return 0; } active_version() { echo "$sim_version"; } is_trusted() { return 0; } is_healthy() { return 0; } service_version() { echo "$sim_version"; } service_uptime() { echo 120; } - service_listener_pid() { echo "$sim_pid"; } unit_property() { case "$1" in - ActiveState) echo "$sim_state" ;; - InvocationID) echo "$sim_generation" ;; + ActiveState) cat "$sim_state_file" ;; + InvocationID) cat "$sim_generation_file" ;; MainPID) echo "$sim_pid" ;; + ControlGroup) echo "$sim_control_group" ;; *) return 1 ;; esac } kernel_hang_signs() { return 1; } - wait_inactive() { [[ "$sim_state" == inactive ]]; } - cp() { if [[ "${1:-}" == --reflink=always ]]; then shift; fi; command cp "$@"; } + wait_inactive() { [[ "$(cat "$sim_state_file")" == inactive ]]; } + cp() { if [[ "$1" == --reflink=always ]]; then shift; fi; command cp "$@"; } + snapshot_fsync() { + local path + for path in "$@"; do + printf 'fsync:%s\n' "$path" >>"$root/snapshot-fsync" + if [[ -e "$root/fail-prepared-receipt" && "$path" == */.snapshot-receipt.* ]]; then + rm -f "$root/fail-prepared-receipt" + return 1 + fi + done + python3 -c 'import os, sys +for path in sys.argv[1:]: + flags = os.O_RDONLY + if os.path.isdir(path): + flags |= getattr(os, "O_DIRECTORY", 0) + fd = os.open(path, flags) + try: + os.fsync(fd) + finally: + os.close(fd)' "$@" + } + cmp() { + [[ "$(cat "$sim_state_file")" == active ]] || fail 'full-file comparison ran while service was stopped' + command cmp "$@" + } + sha256sum() { + [[ "$(cat "$sim_state_file")" == active ]] || fail 'manifest hashing ran while service was stopped' + printf 'hash-after-restart\n' >>"$root/snapshot-hash-order" + command sha256sum "$@" + } svc() { printf '%s\n' "$*" >>"$root/snapshot-svc" case "$1" in stop) - sim_state=inactive + [[ "$(jq -r '.status' "$GUARD_STATE/snapshot-receipts/snapshot-op.json")" == stop_requested ]] || fail 'stop ran without durable stop intent' + [[ "$(tail -n 1 "$root/snapshot-fsync")" == "fsync:$GUARD_STATE/snapshot-receipts" ]] || fail 'stop ran before the receipt directory was fsynced' + printf 'stop\n' >"$sim_command_fifo" + local i + for ((i=0; i<50; i++)); do + [[ ! -s "$sim_listener_file" ]] && break + sleep 0.05 + done + printf 'inactive\n' >"$sim_state_file" printf 'wal bytes\n' >"$DB-wal" printf 'shm bytes\n' >"$DB-shm" ;; - start) sim_state=active; sim_generation=bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb; sim_pid=2222 ;; + start) + [[ "$(jq -r '.status' "$GUARD_STATE/snapshot-receipts/snapshot-op.json")" == copied ]] || fail 'restart ran before the copied receipt was durable' + [[ "$(tail -n 1 "$root/snapshot-fsync")" == "fsync:$GUARD_STATE/snapshot-receipts" ]] || fail 'restart ran before the copied receipt directory was fsynced' + printf 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n' >"$sim_generation_file" + printf 'start\n' >"$sim_command_fifo" + local i + for ((i=0; i<50; i++)); do + service_listener_pid >/dev/null 2>&1 && break + sleep 0.05 + done + service_listener_pid >/dev/null 2>&1 || fail 'same-version child listener did not restart' + printf 'active\n' >"$sim_state_file" + ;; *) return 1 ;; esac return 0 @@ -653,20 +762,86 @@ pass 'all systemctl calls have a bounded timeout' outage_begin() { :; } outage_end() { :; } log() { :; } - quiet_seconds() { echo 900; } + QUIET_VALUE=900 + quiet_seconds() { + if [[ -e "$root/insert-after-first-idle" && ! -e "$root/inserted-during-census" ]]; then + sqlite3 "$DB" "insert into orchestration_v2_projection_runs values ('late','thread','preparing','2026-11-27T00:00:00.000Z',null,'{}');" + touch "$root/inserted-during-census" + fi + echo "$QUIET_VALUE" + } HEALTH_WAIT_SECONDS=0 mkdir -p "$SNAPSHOTS/20200101T000000-before" "$SNAPSHOTS/20200102T000000-before" \ "$SNAPSHOTS/20200103T000000-before" "$SNAPSHOTS/20200104T000000-before" - quiet_seconds() { echo 899; } + + QUIET_VALUE=899 if cmd_snapshot snapshot-op before-stock-switch >/dev/null 2>&1; then fail 'snapshot accepted less than 15 minutes of quiet'; fi exec 9>&- - quiet_seconds() { echo 900; } + QUIET_VALUE=900 + if cmd_snapshot "$(printf 'a%.0s' {1..60})" "$(printf 'b%.0s' {1..60})" >/dev/null 2>&1; then fail 'combined snapshot label over 128 characters was accepted'; fi + exec 9>&- + touch "$root/insert-after-first-idle" + if cmd_snapshot snapshot-op before-stock-switch >/dev/null 2>&1; then fail 'snapshot missed activity arriving between idle reads'; fi + exec 9>&- + rm -f "$root/insert-after-first-idle" "$root/inserted-during-census" + sqlite3 "$DB" "delete from orchestration_v2_projection_runs;" sqlite3 "$DB" "insert into orchestration_v2_projection_runs values ('queued','thread','queued','2026-11-27T00:00:00.000Z',null,'{}');" if cmd_snapshot snapshot-op before-stock-switch >/dev/null 2>&1; then fail 'snapshot stopped a queued run'; fi exec 9>&- - ! grep -q '^stop ' "$root/snapshot-svc" 2>/dev/null || fail 'snapshot stopped a busy service' - sqlite3 "$DB" "delete from orchestration_v2_projection_runs;" - out=$(cmd_snapshot snapshot-op before-stock-switch) || fail 'snapshot-only command failed in the isolated service fixture' + sqlite3 "$DB" "delete from orchestration_v2_projection_runs; insert into orchestration_v2_projection_runs values ('preparing','thread','preparing','2026-11-27T00:00:00.000Z',null,'{}');" + if cmd_snapshot snapshot-op before-stock-switch >/dev/null 2>&1; then fail 'snapshot stopped a preparing run'; fi + exec 9>&- + sqlite3 "$DB" "delete from orchestration_v2_projection_runs; + insert into orchestration_v2_projection_runs values ('active-items','thread','running','2026-11-27T00:00:00.000Z',null,'{}'); + insert into orchestration_v2_projection_turn_items values ('item-command','thread','active-items','command_execution','pending','2026-11-27T00:00:00.000Z'); + insert into orchestration_v2_projection_turn_items values ('item-tool','thread','active-items','dynamic_tool','running','2026-11-27T00:00:00.000Z'); + insert into orchestration_v2_projection_turn_items values ('item-file','thread','active-items','file_change','waiting','2026-11-27T00:00:00.000Z'); + insert into orchestration_v2_projection_turn_items values ('item-subagent','thread','active-items','subagent','running','2026-11-27T00:00:00.000Z'); + insert into orchestration_v2_projection_turn_items values ('item-link','thread','active-items','link_request','pending','2026-11-27T00:00:00.000Z'); + insert into orchestration_v2_effect_outbox values ('effect-1','running');" + if cmd_snapshot snapshot-op before-stock-switch >"$root/snapshot-reject.log" 2>&1; then fail 'snapshot ignored active command, tool, file, subagent, or link-request items'; fi + grep -q 'activeItems=5' "$root/snapshot-reject.log" || fail 'complete active-item census did not report all five work types' + grep -q 'activeEffects=1' "$root/snapshot-reject.log" || fail 'snapshot ignored a pending effect outbox job' + exec 9>&- + sqlite3 "$DB" "delete from orchestration_v2_projection_runs; delete from orchestration_v2_projection_turn_items; + insert into orchestration_v2_projection_subagents values ('provider-subagent','running'); + insert into orchestration_v2_projection_subagents values ('app-owned-subagent','pending');" + if cmd_snapshot snapshot-op before-stock-switch >/dev/null 2>&1; then fail 'snapshot stopped an active provider subagent'; fi + exec 9>&- + sqlite3 "$DB" "delete from orchestration_v2_projection_subagents; insert into orchestration_v2_projection_provider_threads values ('provider-thread','{\"pendingBackgroundTasks\":[{\"taskId\":\"task-1\"}]}');" + if cmd_snapshot snapshot-op before-stock-switch >/dev/null 2>&1; then fail 'snapshot stopped a pending provider background task'; fi + exec 9>&- + sqlite3 "$DB" "delete from orchestration_v2_projection_provider_threads; insert into orchestration_v2_projection_provider_threads values ('provider-thread','invalid json');" + if cmd_snapshot snapshot-op before-stock-switch >/dev/null 2>&1; then fail 'snapshot accepted an unreadable provider-thread payload'; fi + exec 9>&- + sqlite3 "$DB" "delete from orchestration_v2_projection_provider_threads; delete from orchestration_v2_effect_outbox;" + [[ -z "$(grep '^stop ' "$root/snapshot-svc" 2>/dev/null || true)" ]] || fail 'snapshot stopped a busy or unverified service' + + # The real listener is a child in the unit cgroup, not MainPID. Both ancestry and exact cgroup + # membership are required; an unrelated sibling in the same cgroup and a wrong cgroup fail. + sim_identity=$(snapshot_service_identity "$sim_version") || fail 'real child listener did not bind to its launcher' + sim_listener=$(service_listener_pid) + [[ "$sim_listener" == "$(cat "$sim_listener_file")" && "$sim_listener" != "$sim_pid" ]] || fail 'fixture did not prove a child listener distinct from MainPID' + sleep 100 & + sibling_pid=$! + sim_pid=$sibling_pid + if snapshot_service_identity "$sim_version" >/dev/null 2>&1; then fail 'unrelated same-cgroup listener was accepted'; fi + sim_pid=$sim_launcher_pid + kill "$sibling_pid" 2>/dev/null || true + wait "$sibling_pid" 2>/dev/null || true + real_control_group=$sim_control_group + sim_control_group=/outside-the-service-cgroup + if snapshot_service_identity "$sim_version" >/dev/null 2>&1; then fail 'listener outside the exact unit cgroup was accepted'; fi + sim_control_group=$real_control_group + pass 'snapshot identity accepts its real child listener and rejects unrelated or out-of-cgroup listeners' + + touch "$root/fail-prepared-receipt" + if cmd_snapshot snapshot-op before-stock-switch >/dev/null 2>&1; then fail 'snapshot proceeded when prepared receipt fsync failed'; fi + exec 9>&- + [[ -z "$(grep '^stop ' "$root/snapshot-svc" 2>/dev/null || true)" ]] || fail 'snapshot stopped before its prepared receipt was durable' + [[ ! -e "$GUARD_STATE/snapshot-receipts/snapshot-op.json" ]] || fail 'failed prepared receipt was published' + cmd_snapshot snapshot-op before-stock-switch >"$root/snapshot-out" || fail 'snapshot-only command failed in the isolated service fixture' + out=$(cat "$root/snapshot-out") receipt="$GUARD_STATE/snapshot-receipts/snapshot-op.json" [[ "$(jq -r '.status' <<<"$out")" == complete ]] || fail 'snapshot receipt did not complete' [[ "$(jq -r '.stoppedGeneration.version' "$receipt")" == "$sim_version" ]] || fail 'receipt lost stopped version' @@ -675,13 +850,15 @@ pass 'all systemctl calls have a bounded timeout' [[ "$(jq -r '.files | map(.name) | sort | join(",")' "$receipt")" == 'statev2.sqlite,statev2.sqlite-shm,statev2.sqlite-wal' ]] || fail 'receipt omitted a SQLite file or sidecar' [[ "$(sha256sum "$(jq -r '.snapshotPath' "$receipt")/statev2.sqlite" | cut -d' ' -f1)" == "$(sha256sum "$DB" | cut -d' ' -f1)" ]] || fail 'snapshot main database differs from the stopped source' [[ "$(stat -c %a "$receipt")" == 600 && "$(stat -c %a "$(jq -r '.snapshotPath' "$receipt")")" == 700 ]] || fail 'snapshot receipt or files are not under owner-only directories' + [[ "$(jq -r '.idleVerification.first.runs' "$receipt")" == 0 && "$(jq -r '.idleVerification.second.runs' "$receipt")" == 0 ]] || fail 'receipt did not retain both clean idle censuses' [[ -d "$SNAPSHOTS/20200101T000000-before" && -d "$SNAPSHOTS/20200104T000000-before" ]] || fail 'one-off snapshot rotated away an earlier copy' [[ "$(grep -c '^stop --no-block t3code.service$' "$root/snapshot-svc")" == 1 ]] || fail 'snapshot did not stop exactly once' [[ "$(grep -c '^start --no-block t3code.service$' "$root/snapshot-svc")" == 1 ]] || fail 'snapshot did not restart exactly once' - out=$(cmd_snapshot snapshot-op before-stock-switch) || fail 'idempotent snapshot retry did not return its receipt' + [[ -s "$root/snapshot-hash-order" ]] || fail 'copied files were not hashed after restart' + cmd_snapshot snapshot-op before-stock-switch >"$root/snapshot-out" || fail 'idempotent snapshot retry did not return its receipt' [[ "$(grep -c '^stop --no-block t3code.service$' "$root/snapshot-svc")" == 1 ]] || fail 'idempotent retry stopped the service twice' if cmd_snapshot snapshot-op different-point >/dev/null 2>&1; then fail 'snapshot reused an operation ID with a different point'; fi exec 9>&- [[ "$(grep -c '^stop --no-block t3code.service$' "$root/snapshot-svc")" == 1 ]] || fail 'mismatched receipt retry stopped the service again' -) || fail 'snapshot-only path violated its isolated activity, receipt, or restart contract' -pass 'snapshot-only path refuses activity, retains a private WAL/SHM receipt, restarts the same build, and is idempotent' +) || fail 'snapshot-only path violated its isolated activity, identity, durability, or restart contract' +pass 'snapshot-only path verifies full idle state and durable receipts, restarts before hashing, and is idempotent' From 3ee69c7dc70d599d44c0bf679dc12bb1e9970557 Mon Sep 17 00:00:00 2001 From: Chris OHearn Date: Fri, 27 Nov 2026 04:11:07 -0700 Subject: [PATCH 3/7] fix(fork): fence snapshot admission during server work --- .../src/orchestration-v2/Orchestrator.ts | 59 ++- apps/server/src/serverRuntimeStartup.test.ts | 23 +- apps/server/src/serverRuntimeStartup.ts | 12 + .../server/src/serviceChangeAdmission.test.ts | 83 +++++ apps/server/src/serviceChangeAdmission.ts | 342 ++++++++++++++++++ scripts/fork/host/t3-update-guard/README.md | 6 +- scripts/fork/host/t3-update-guard/guard | 241 +++++++++++- .../host/t3-update-guard/t3-service-update | 26 +- .../fork/host/t3-update-guard/test-guard.sh | 101 +++++- 9 files changed, 866 insertions(+), 27 deletions(-) create mode 100644 apps/server/src/serviceChangeAdmission.test.ts create mode 100644 apps/server/src/serviceChangeAdmission.ts diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 0af587e528bb0..3a334c3b7e603 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -250,6 +250,7 @@ import { import { planThreadDeletion } from "./ThreadDeletion.ts"; import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; import * as ServerSettings from "../serverSettings.ts"; +import * as ServiceChangeAdmission from "../serviceChangeAdmission.ts"; const isMessageQuestionAnswer = Schema.is( Schema.Union([TrimmedNonEmptyString, Schema.NonEmptyArray(TrimmedNonEmptyString)]), @@ -3980,7 +3981,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio left.afterRunOrdinal - right.afterRunOrdinal || left.item.ordinal - right.item.ordinal, ); for (const { run, message, steer, afterRunOrdinal } of placed) { - yield* dispatchWithReceiptEffect({ + yield* dispatchWithAdmission({ type: "message.dispatch", commandId: CommandId.make(`command:unread-steer:${run.id}:${message.id}`), threadId, @@ -16444,7 +16445,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio session.capabilities.sessions.supportsMultipleProviderThreadsPerSession ) continue; - yield* dispatchWithReceiptEffect({ + yield* dispatchWithAdmission({ type: "provider-session.detach", commandId: CommandId.make( `command:system:delegated-task-release:${resultRunId}:${session.id}`, @@ -16947,7 +16948,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio node.id === request.nodeId && node.runId !== null && resultRunIds.has(node.runId), ) ) { - yield* dispatchWithReceipt({ + yield* dispatchWithReceiptWithAdmission({ type: "thread.user-input.dismiss", commandId: CommandId.make(`command:system:delegated-task-question:${request.id}`), threadId: childThreadId, @@ -18031,6 +18032,27 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio } satisfies OrchestratorV2DispatchResult; }, withCommandMetrics); + const dispatchWithAdmission = Effect.fnUntraced(function* ( + command: OrchestrationV2ServerCommand, + sideChatIds: ReadonlyArray = [], + cancelledTask?: OrchestrationV2Subagent, + ): Effect.fn.Return { + return yield* ServiceChangeAdmission.withAdmissionAt( + config.baseDir, + dispatchWithReceiptEffect(command, sideChatIds, cancelledTask), + ).pipe( + Effect.mapError((cause) => + ServiceChangeAdmission.isServiceChangeAdmissionError(cause) + ? new OrchestratorCommandRejectedError({ + commandId: command.commandId, + commandType: command.type, + cause, + }) + : cause, + ), + ); + }); + // Follow-up intake and Stop serialize on the parent before taking the child lock. const withSubagentParentLock = (threadId: ThreadId, dispatch: Effect.Effect) => appOwnedSubagentParentThreadId(threadId).pipe( @@ -18102,6 +18124,25 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio : dispatch; }); + const dispatchWithReceiptWithAdmission = Effect.fnUntraced(function* ( + command: OrchestrationV2ServerCommand, + ): Effect.fn.Return { + return yield* ServiceChangeAdmission.withAdmissionAt( + config.baseDir, + dispatchWithReceipt(command), + ).pipe( + Effect.mapError((cause) => + ServiceChangeAdmission.isServiceChangeAdmissionError(cause) + ? new OrchestratorCommandRejectedError({ + commandId: command.commandId, + commandType: command.type, + cause, + }) + : cause, + ), + ); + }); + const parentTaskSyncRetries = yield* FiberSet.make(); const syncDelegatedParentTask = Effect.fn("Orchestrator.syncDelegatedParentTask")(function* ( childThreadId: ThreadId, @@ -18296,7 +18337,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio (left.queuePosition ?? left.ordinal) - (right.queuePosition ?? right.ordinal), ); for (const queued of pending) { - yield* dispatchWithReceiptEffect({ + yield* dispatchWithAdmission({ type: "queued-message.promote-to-steer", commandId: CommandId.make( `command:deferred-steer:${queued.id}:${run.id}:${turn.runAttemptId}`, @@ -18611,8 +18652,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio // Hold intake closed until descendants stop and this thread's Stop commits. yield* input.stopDescendants((command) => commandThreadId(command) === input.command.threadId - ? dispatchWithReceiptEffect(command) - : dispatchWithReceipt(command), + ? dispatchWithAdmission(command) + : dispatchWithReceiptWithAdmission(command), ); const child = yield* projectionStore .getThreadRecords( @@ -18639,7 +18680,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ? { ...task, cancelledRunId: cancelledRun.id, updatedAt: now } : undefined; // The marker, Stop receipt and interrupt outbox commit together under both locks. - yield* dispatchWithReceiptEffect(command, [], cancelledTask); + yield* dispatchWithAdmission(command, [], cancelledTask); }), ); yield* finalizeAppOwnedSubagent(command.threadId).pipe(mapDispatchError(command)); @@ -18664,7 +18705,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio awaitRestartContinuation: Effect.fn("OrchestratorV2.awaitRestartContinuation")(function (run) { return effectOutbox.awaitSettled(`effect:restart-continuation:${run.id}`).pipe(Effect.ignore); }), - dispatch: dispatchWithReceipt, + dispatch: dispatchWithReceiptWithAdmission, skipProviderFailover: Effect.fn("OrchestratorV2.skipProviderFailover")(function (input) { return threadDispatch.withLock( input.threadId, @@ -18702,7 +18743,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const command = { type: "thread.metadata.update", ...input } as const; // A Stop that reached the run before its limit failure landed had nothing to disarm. const stopped = yield* stopReachedRun(command, input.threadId, input.limitRecovery.runId); - yield* dispatchWithReceiptEffect( + yield* dispatchWithAdmission( stopped ? { ...command, diff --git a/apps/server/src/serverRuntimeStartup.test.ts b/apps/server/src/serverRuntimeStartup.test.ts index 8e31118188da4..bc57615f11fa7 100644 --- a/apps/server/src/serverRuntimeStartup.test.ts +++ b/apps/server/src/serverRuntimeStartup.test.ts @@ -1,5 +1,10 @@ import { assert, it } from "@effect/vitest"; import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +// @effect-diagnostics-next-line nodeBuiltinImport:off -- The test cleans its isolated startup base directory. +import * as NodeFS from "node:fs"; +import * as NodeOS from "node:os"; +// @effect-diagnostics-next-line nodeBuiltinImport:off -- The test builds and removes an isolated startup base directory. +import * as NodePath from "node:path"; import { DEFAULT_SERVER_SETTINGS, ProjectId, @@ -54,8 +59,9 @@ it.effect.each([ "launch-failure", "project-failure", "project-refused", -] as const)("keeps bootstrap launch failures separate from project failures: %s", (scenario) => - Effect.gen(function* () { +] as const)("keeps bootstrap launch failures separate from project failures: %s", (scenario) => { + const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-startup-")); + return Effect.gen(function* () { const projectId = ProjectId.make("bootstrap-project"); const instanceId = ProviderInstanceId.make( scenario === "disabled-default" ? "custom" : "codex", @@ -73,10 +79,10 @@ it.effect.each([ NodeCrypto.layer, Path.layer, Layer.mock(ServerConfig.ServerConfig)({ - ...(yield* ServerConfig.deriveServerPaths("/bootstrap-project", undefined).pipe( + ...(yield* ServerConfig.deriveServerPaths(baseDir, undefined).pipe( Effect.provide(Path.layer), )), - baseDir: "/bootstrap-project", + baseDir, logLevel: "Error", traceMinLevel: "Info", traceTimingEnabled: false, @@ -97,7 +103,7 @@ it.effect.each([ tailscaleServeEnabled: false, tailscaleServePort: 443, mode: "web", - cwd: "/bootstrap-project", + cwd: baseDir, host: "localhost", port: 3773, devUrl: undefined, @@ -167,7 +173,7 @@ it.effect.each([ project: { id: projectId, title: "Project", - workspaceRoot: "/bootstrap-project", + workspaceRoot: baseDir, repositoryIdentity: null, faviconPath: null, scripts: [], @@ -242,9 +248,10 @@ it.effect.each([ }).pipe( Effect.provide(ServerRuntimeStartup.layerWithOptions().pipe(Layer.provide(dependencies))), Effect.provideService(ServerActivation, Effect.never), + Effect.ensuring(Effect.sync(() => NodeFS.rmSync(baseDir, { recursive: true, force: true }))), ); - }), -); + }); +}); it.effect("interrupts the effect worker when awareness relay startup fails", () => Effect.gen(function* () { diff --git a/apps/server/src/serverRuntimeStartup.ts b/apps/server/src/serverRuntimeStartup.ts index 3efb659d6e130..c2b8c38254d76 100644 --- a/apps/server/src/serverRuntimeStartup.ts +++ b/apps/server/src/serverRuntimeStartup.ts @@ -30,6 +30,7 @@ import * as Schema from "effect/Schema"; import * as BackgroundPolicy from "./background/BackgroundPolicy.ts"; import * as ServerConfig from "./config.ts"; +import * as ServiceChangeAdmission from "./serviceChangeAdmission.ts"; import * as ServiceLauncherClient from "./cloud/serviceLauncherClient.ts"; import { flushCompileCache } from "./compileCache.ts"; import * as Keybindings from "./keybindings.ts"; @@ -452,6 +453,17 @@ const runOrderedV2StartupPhases = Effect.fn("serverRuntimeStartup.runOrderedV2St const make = Effect.fn("serverRuntimeStartup.make")(function* (options?: StartupOptions) { const serverConfig = yield* ServerConfig.ServerConfig; + yield* ServiceChangeAdmission.initialize(serverConfig.baseDir).pipe( + Effect.tapError((cause) => + Effect.logWarning( + "Snapshot admission capability could not be published; guarded snapshots will fail closed.", + { + cause, + }, + ), + ), + Effect.ignore, + ); const keybindings = yield* Keybindings.Keybindings; const legacyV1ThreadImporter = yield* LegacyV1ThreadImporter.LegacyV1ThreadImporter; const providerRuntimeRecovery = yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService; diff --git a/apps/server/src/serviceChangeAdmission.test.ts b/apps/server/src/serviceChangeAdmission.test.ts new file mode 100644 index 0000000000000..06196c88fb2b8 --- /dev/null +++ b/apps/server/src/serviceChangeAdmission.test.ts @@ -0,0 +1,83 @@ +import { assert, it } from "@effect/vitest"; +// @effect-diagnostics-next-line nodeBuiltinImport:off -- The test verifies the guard-compatible host file protocol. +import * as NodeFS from "node:fs"; +import * as NodeOS from "node:os"; +// @effect-diagnostics-next-line nodeBuiltinImport:off -- The test creates and removes its isolated runtime directory. +import * as NodePath from "node:path"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as Fiber from "effect/Fiber"; +import * as Layer from "effect/Layer"; +import * as ServerConfig from "./config.ts"; +import * as ServiceChangeAdmission from "./serviceChangeAdmission.ts"; + +it.effect("drains admitted commands before refusing work behind the snapshot fence", () => { + const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-snapshot-admission-")); + const root = NodePath.join(baseDir, "runtime", "service-change-admission"); + const active = NodePath.join(root, "active"); + const fence = NodePath.join(root, "snapshot-fence.json"); + const testLayer = ServerConfig.ServerConfig.layerTest(baseDir, baseDir).pipe( + Layer.provideMerge(NodeServices.layer), + ); + + return Effect.gen(function* () { + yield* ServiceChangeAdmission.initialize(baseDir); + const capability = JSON.parse( + NodeFS.readFileSync(NodePath.join(root, "capability.json"), "utf8"), + ) as { + protocolVersion: number; + pid: number; + }; + assert.equal(capability.protocolVersion, 1); + assert.equal(capability.pid, process.pid); + + const entered = yield* Deferred.make(); + const release = yield* Deferred.make(); + const admitted = ServiceChangeAdmission.withAdmission( + Effect.gen(function* () { + yield* Deferred.succeed(entered, undefined); + yield* Deferred.await(release); + }), + ); + const fiber = yield* admitted.pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(entered); + assert.equal(NodeFS.readdirSync(active).length, 1); + + NodeFS.writeFileSync(fence, JSON.stringify({ protocolVersion: 1, ownerPid: process.pid }), { + mode: 0o600, + }); + let fencedEffectRan = false; + const fenced = yield* Effect.exit( + ServiceChangeAdmission.withAdmission( + Effect.sync(() => { + fencedEffectRan = true; + }), + ), + ); + assert.isTrue(Exit.isFailure(fenced)); + assert.isFalse(fencedEffectRan); + assert.equal(NodeFS.readdirSync(active).length, 1); + + yield* Deferred.succeed(release, undefined); + yield* Fiber.join(fiber); + assert.equal(NodeFS.readdirSync(active).length, 0); + + NodeFS.writeFileSync(fence, JSON.stringify({ protocolVersion: 2, ownerPid: 2_000_000_000 }), { + mode: 0o600, + }); + const incompatible = yield* Effect.exit(ServiceChangeAdmission.withAdmission(Effect.void)); + assert.isTrue(Exit.isFailure(incompatible)); + assert.isTrue(NodeFS.existsSync(fence)); + + NodeFS.writeFileSync(fence, JSON.stringify({ protocolVersion: 1, ownerPid: 2_000_000_000 }), { + mode: 0o600, + }); + yield* ServiceChangeAdmission.withAdmission(Effect.void); + assert.isFalse(NodeFS.existsSync(fence)); + }).pipe( + Effect.provide(testLayer), + Effect.ensuring(Effect.sync(() => NodeFS.rmSync(baseDir, { recursive: true, force: true }))), + ); +}); diff --git a/apps/server/src/serviceChangeAdmission.ts b/apps/server/src/serviceChangeAdmission.ts new file mode 100644 index 0000000000000..ab4a69faf81c6 --- /dev/null +++ b/apps/server/src/serviceChangeAdmission.ts @@ -0,0 +1,342 @@ +// @effect-diagnostics-next-line nodeBuiltinImport:off -- The host guard coordinates through these owner-only runtime files. +import * as NodeCrypto from "node:crypto"; +// @effect-diagnostics-next-line nodeBuiltinImport:off -- Admission files share the guard's cross-process fence. +import * as NodeFS from "node:fs"; +// @effect-diagnostics-next-line nodeBuiltinImport:off -- Admission files share the guard's runtime path. +import * as NodePath from "node:path"; +import * as Clock from "effect/Clock"; +import * as Context from "effect/Context"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import * as ServerConfig from "./config.ts"; + +const PROTOCOL_VERSION = 1; +const MUTEX_WAIT_MS = 5_000; + +interface AdmissionLease { + readonly tokenPath: string; +} + +interface AdmissionPaths { + readonly root: string; + readonly mutex: string; + readonly active: string; + readonly fence: string; + readonly capability: string; +} + +export class ServiceChangeAdmissionError extends Schema.TaggedError< + ServiceChangeAdmissionError, + { readonly brand: unique symbol } +>()("ServiceChangeAdmissionError", { + stage: Schema.Literals(["storage", "mutex", "fence"]), + cause: Schema.optional(Schema.Defect()), +}) { + override get message(): string { + switch (this.stage) { + case "storage": + return "Snapshot admission storage is unavailable; the command was not accepted."; + case "mutex": + return "The service-change admission mutex is unavailable; the command was not accepted."; + case "fence": + return "The guarded snapshot admission fence is closed; the command was not accepted."; + } + } +} + +export const isServiceChangeAdmissionError = Schema.is(ServiceChangeAdmissionError); + +const AdmissionCapabilityFile = Schema.fromJsonString( + Schema.Struct({ + protocolVersion: Schema.Literal(PROTOCOL_VERSION), + pid: Schema.Number, + startedAt: Schema.String, + }), +); +const encodeAdmissionCapability = Schema.encodeEffect(AdmissionCapabilityFile); + +class AdmissionLeaseContext extends Context.Service()( + "t3/serviceChangeAdmission/AdmissionLeaseContext", +) {} + +const admissionPaths = (baseDir: string): AdmissionPaths => { + const root = NodePath.join(baseDir, "runtime", "service-change-admission"); + return { + root, + mutex: NodePath.join(root, "mutex"), + active: NodePath.join(root, "active"), + fence: NodePath.join(root, "snapshot-fence.json"), + capability: NodePath.join(root, "capability.json"), + }; +}; + +const pidIsAlive = (pid: number) => { + if (!Number.isSafeInteger(pid) || pid <= 0) return false; + try { + process.kill(pid, 0); + return true; + } catch (cause) { + return typeof cause === "object" && cause !== null && "code" in cause && cause.code === "EPERM"; + } +}; + +const ensureDirectories = (paths: AdmissionPaths) => { + NodeFS.mkdirSync(paths.root, { recursive: true, mode: 0o700 }); + NodeFS.mkdirSync(paths.active, { recursive: true, mode: 0o700 }); + if ( + NodeFS.lstatSync(paths.root).isSymbolicLink() || + NodeFS.lstatSync(paths.active).isSymbolicLink() + ) { + throw new Error("Snapshot admission directories must not be symbolic links."); + } + NodeFS.chmodSync(paths.root, 0o700); + NodeFS.chmodSync(paths.active, 0o700); +}; + +const releaseMutex = (paths: AdmissionPaths) => { + try { + NodeFS.unlinkSync(NodePath.join(paths.mutex, "owner")); + } catch { + // A missing owner file means an interrupted or already completed cleanup. + } + try { + NodeFS.rmdirSync(paths.mutex); + } catch { + // Leave unexpected contents in place; the next caller fails closed. + } +}; + +const removeStaleMutex = (paths: AdmissionPaths, now: number) => { + const ownerPath = NodePath.join(paths.mutex, "owner"); + let stat: NodeFS.Stats; + try { + stat = NodeFS.lstatSync(paths.mutex); + } catch (cause) { + if (typeof cause === "object" && cause !== null && "code" in cause && cause.code === "ENOENT") { + return; + } + throw cause; + } + if (!stat.isDirectory() || stat.isSymbolicLink()) + throw new Error("Admission mutex is not a real directory."); + let ownerPid: number | undefined; + try { + const ownerStat = NodeFS.lstatSync(ownerPath); + if (!ownerStat.isFile() || ownerStat.isSymbolicLink() || (ownerStat.mode & 0o777) !== 0o600) { + throw new Error("Admission mutex owner is not a private regular file."); + } + const ownerText = NodeFS.readFileSync(ownerPath, "utf8").trim(); + if (!/^[1-9][0-9]*$/.test(ownerText)) throw new Error("Admission mutex owner PID is invalid."); + ownerPid = Number(ownerText); + if (!Number.isSafeInteger(ownerPid)) throw new Error("Admission mutex owner PID is invalid."); + } catch (cause) { + if ( + !(typeof cause === "object" && cause !== null && "code" in cause && cause.code === "ENOENT") + ) { + throw cause; + } + if (now - stat.mtimeMs <= 5_000) return; + } + if (ownerPid !== undefined && pidIsAlive(ownerPid)) return; + releaseMutex(paths); +}; + +type MutexAttempt = + | { readonly tag: "acquired" } + | { readonly tag: "busy" } + | { readonly tag: "failed"; readonly cause: unknown }; + +const attemptAcquireMutex = (paths: AdmissionPaths): MutexAttempt => { + try { + NodeFS.mkdirSync(paths.mutex, { mode: 0o700 }); + } catch (cause) { + if (typeof cause === "object" && cause !== null && "code" in cause && cause.code === "EEXIST") { + return { tag: "busy" }; + } + return { tag: "failed", cause }; + } + try { + NodeFS.writeFileSync(NodePath.join(paths.mutex, "owner"), `${process.pid}\n`, { + mode: 0o600, + flag: "wx", + }); + return { tag: "acquired" }; + } catch (cause) { + try { + NodeFS.rmdirSync(paths.mutex); + } catch { + // Preserve the original failure and refuse admission. + } + return { tag: "failed", cause }; + } +}; + +const acquireMutex = Effect.fn("ServiceChangeAdmission.acquireMutex")(function* ( + paths: AdmissionPaths, +) { + const deadline = (yield* Clock.currentTimeMillis) + MUTEX_WAIT_MS; + while (true) { + const attempt = yield* Effect.sync(() => attemptAcquireMutex(paths)); + if (attempt.tag === "acquired") return; + if (attempt.tag === "failed") { + return yield* new ServiceChangeAdmissionError({ stage: "mutex", cause: attempt.cause }); + } + + const now = yield* Clock.currentTimeMillis; + yield* Effect.try({ + try: () => removeStaleMutex(paths, now), + catch: (cause) => new ServiceChangeAdmissionError({ stage: "mutex", cause }), + }); + if ((yield* Clock.currentTimeMillis) >= deadline) { + return yield* new ServiceChangeAdmissionError({ stage: "mutex" }); + } + yield* Effect.sleep("10 millis"); + } +}); + +const withMutex = ( + paths: AdmissionPaths, + operation: () => A, +): Effect.Effect => + Effect.scoped( + Effect.gen(function* () { + yield* Effect.acquireRelease(acquireMutex(paths), () => + Effect.sync(() => releaseMutex(paths)), + ); + return yield* Effect.try({ + try: operation, + catch: (cause) => + isServiceChangeAdmissionError(cause) + ? cause + : new ServiceChangeAdmissionError({ stage: "fence", cause }), + }); + }), + ); + +const removeStaleFence = (paths: AdmissionPaths) => { + let stat: NodeFS.Stats; + try { + stat = NodeFS.lstatSync(paths.fence); + } catch (cause) { + if (typeof cause === "object" && cause !== null && "code" in cause && cause.code === "ENOENT") + return; + throw cause; + } + if (!stat.isFile() || stat.isSymbolicLink() || (stat.mode & 0o777) !== 0o600) { + throw new ServiceChangeAdmissionError({ stage: "fence" }); + } + let ownerPid: number; + try { + const fence = JSON.parse(NodeFS.readFileSync(paths.fence, "utf8")) as { + protocolVersion?: unknown; + ownerPid?: unknown; + }; + if (fence.protocolVersion !== PROTOCOL_VERSION || typeof fence.ownerPid !== "number") { + throw new Error("Snapshot admission fence protocol is invalid."); + } + ownerPid = fence.ownerPid; + if (!Number.isSafeInteger(ownerPid) || ownerPid <= 0) + throw new Error("Snapshot fence owner PID is invalid."); + } catch (cause) { + throw new ServiceChangeAdmissionError({ stage: "fence", cause }); + } + if (pidIsAlive(ownerPid)) { + throw new ServiceChangeAdmissionError({ stage: "fence" }); + } + NodeFS.unlinkSync(paths.fence); +}; + +const createAdmission = (baseDir: string) => { + const paths = admissionPaths(baseDir); + return Effect.try({ + try: () => ensureDirectories(paths), + catch: (cause) => new ServiceChangeAdmissionError({ stage: "storage", cause }), + }).pipe( + Effect.andThen( + withMutex(paths, () => { + removeStaleFence(paths); + const tokenPath = NodePath.join( + paths.active, + `${process.pid}-${NodeCrypto.randomUUID()}.json`, + ); + NodeFS.writeFileSync(tokenPath, JSON.stringify({ pid: process.pid }), { + mode: 0o600, + flag: "wx", + }); + return { tokenPath } satisfies AdmissionLease; + }), + ), + ); +}; + +export const initialize = Effect.fn("ServiceChangeAdmission.initialize")(function* ( + baseDir: string, +): Effect.fn.Return { + const startedAt = DateTime.formatIso(yield* DateTime.now); + const contents = yield* encodeAdmissionCapability({ + protocolVersion: PROTOCOL_VERSION, + pid: process.pid, + startedAt, + }).pipe(Effect.mapError((cause) => new ServiceChangeAdmissionError({ stage: "storage", cause }))); + return yield* Effect.try({ + try: () => { + const paths = admissionPaths(baseDir); + ensureDirectories(paths); + const temporary = `${paths.capability}.${process.pid}.${NodeCrypto.randomUUID()}.tmp`; + const descriptor = NodeFS.openSync(temporary, "wx", 0o600); + try { + NodeFS.writeFileSync(descriptor, `${contents}\n`, "utf8"); + NodeFS.fsyncSync(descriptor); + } finally { + NodeFS.closeSync(descriptor); + } + NodeFS.renameSync(temporary, paths.capability); + const directoryDescriptor = NodeFS.openSync(paths.root, "r"); + try { + NodeFS.fsyncSync(directoryDescriptor); + } finally { + NodeFS.closeSync(directoryDescriptor); + } + }, + catch: (cause) => new ServiceChangeAdmissionError({ stage: "storage", cause }), + }); +}); + +const releaseAdmission = (lease: AdmissionLease) => + Effect.sync(() => { + try { + NodeFS.unlinkSync(lease.tokenPath); + } catch { + // The guard treats a missing token as drained. + } + }); + +const leaseIsActive = (lease: AdmissionLease) => NodeFS.existsSync(lease.tokenPath); + +export const withAdmissionAt = Effect.fn("ServiceChangeAdmission.withAdmissionAt")(function* < + A, + E, + R, +>( + baseDir: string, + effect: Effect.Effect, +): Effect.fn.Return { + const activeLease = yield* Effect.serviceOption(AdmissionLeaseContext); + if (Option.isSome(activeLease) && leaseIsActive(activeLease.value)) return yield* effect; + + return yield* Effect.scoped( + Effect.gen(function* () { + const lease = yield* Effect.acquireRelease(createAdmission(baseDir), releaseAdmission); + return yield* Effect.provideService(effect, AdmissionLeaseContext, lease); + }), + ); +}); + +export const withAdmission = Effect.fn("ServiceChangeAdmission.withAdmission")(function* ( + effect: Effect.Effect, +) { + const config = yield* ServerConfig.ServerConfig; + return yield* withAdmissionAt(config.baseDir, effect); +}); diff --git a/scripts/fork/host/t3-update-guard/README.md b/scripts/fork/host/t3-update-guard/README.md index 87ab140a45991..8432f97e2131b 100644 --- a/scripts/fork/host/t3-update-guard/README.md +++ b/scripts/fork/host/t3-update-guard/README.md @@ -22,9 +22,11 @@ Installing the guard does not restart the T3 service. ## Capture a snapshot without updating -`t3-service-update snapshot ` is the guarded stop/copy/restart entry point for a caller that needs a database snapshot without installing or selecting another release. Both identifiers must contain only letters, digits, dots, underscores, and hyphens, and start with a letter or digit. Reusing an operation ID with the same point returns its existing receipt and does not stop the service again; reusing it for a different point fails closed. +`t3-service-update snapshot ` is the guarded stop/copy/restart entry point for a caller that needs a database snapshot without installing or selecting another release. The wrapper launches the guard in a dedicated transient user service using `systemd-run --user --collect --pipe --wait`; that service has its own systemd cgroup and survives stopping `t3code.service`. Run the command from a host shell outside `t3code.service`, after the service has been quiet for the configured 15 minutes. A call made by an active T3 run is counted by the strict idle census and refuses before the stop. The caller waits outside the service and receives the durable receipt after the same trusted fork build restarts. Running from a T3 thread is not a supported invocation: its active run fails the idle census, so use an external host shell after the required quiet window. -The command takes the existing service-change lock, requires the selected release to be installed, trusted, and healthy, and proves the loopback listener is a descendant of the systemd unit's launcher MainPID inside that exact unit's cgroup. It requires two clean activity reads, then rechecks the service identity and generation immediately before stopping: no preparing, queued, starting, running, or waiting runs; no pending requests; no active command, tool, file-change, subagent, or link-request items; no pending or running effect outbox jobs; no active provider subagents or persisted provider background tasks; and at least the configured 15 minutes of quiet. Unknown activity, health, listener, cgroup, or systemd state refuses the stop. +Both identifiers must contain only letters, digits, dots, underscores, and hyphens, and start with a letter or digit. Reusing an operation ID with the same point returns its existing receipt and does not stop the service again; reusing it for a different point fails closed. + +The command takes the existing service-change lock, requires the selected release to be installed, trusted, and healthy, and proves the loopback listener is the server child identified by the capability marker, descended from the systemd unit's launcher MainPID and inside that exact unit's cgroup. The server publishes that owner-only marker during startup and holds an admission token around orchestration commands that can create or start work. The guard first checks activity, closes the shared admission fence under the coordination mutex, drains admitted commands, and then repeats the full idle census and service identity/generation checks immediately before stopping. New commands fail closed while the fence is closed. Both final censuses require no preparing, queued, starting, running, or waiting runs; no pending requests; no active command, tool, file-change, subagent, or link-request items; no pending or running effect outbox jobs; no active provider subagents or persisted provider background tasks; and at least the configured 15 minutes of quiet. Unknown activity, health, listener, cgroup, or systemd state refuses the stop. The durable receipt records the fence close/drain times and the verified child-listener PID alongside the final idle evidence. Before systemd receives a stop request, the guard fsyncs an owner-only intent receipt. It copies the SQLite files and WAL/SHM sidecars with the existing reflink path only after systemd confirms the unit is inactive, then fsyncs the copy and records that state durably. It restarts the same selected fork build before hashing the copied files, and marks the receipt complete only after the new systemd invocation, listener descendant and cgroup, health version, and service uptime are verified. The receipt includes the operation ID, snapshot point, stopped unit invocation and launcher PID, both idle censuses, snapshot path, and each copied file's SHA-256 and size. This one-off operation preserves earlier snapshots instead of applying the update path's three-snapshot rotation. It never downloads, installs, or selects a release and never runs the T3 CLI against the live database. A retry returns a complete receipt or resumes from its durable state; it never sends a second stop for the same operation ID. If a stop was recorded but the unit is active again before a copy was recorded, the guard refuses that operation ID so the caller can inspect the receipt and retained files before choosing a new one. diff --git a/scripts/fork/host/t3-update-guard/guard b/scripts/fork/host/t3-update-guard/guard index 2abb0ab6ff91a..edd81f44dd207 100755 --- a/scripts/fork/host/t3-update-guard/guard +++ b/scripts/fork/host/t3-update-guard/guard @@ -40,6 +40,17 @@ GUARD_STATE="${T3_GUARD_STATE_DIR:-${XDG_STATE_HOME:-$HOME/.local/state}/t3-upda CONFIG="${XDG_CONFIG_HOME:-$HOME/.config}/t3-update-guard/config" LOCK="$T3HOME/runtime/service-change.lock" DB="$T3HOME/userdata/statev2.sqlite" +SNAPSHOT_ADMISSION_ROOT="$T3HOME/runtime/service-change-admission" +SNAPSHOT_ADMISSION_MUTEX="$SNAPSHOT_ADMISSION_ROOT/mutex" +SNAPSHOT_ADMISSION_ACTIVE="$SNAPSHOT_ADMISSION_ROOT/active" +SNAPSHOT_ADMISSION_FENCE="$SNAPSHOT_ADMISSION_ROOT/snapshot-fence.json" +SNAPSHOT_ADMISSION_CLOSED=0 +SNAPSHOT_ADMISSION_OPERATION="" +SNAPSHOT_ADMISSION_CLOSED_AT="" +SNAPSHOT_ADMISSION_DRAINED_AT="" +SNAPSHOT_ADMISSION_CAPABILITY_PID=0 +SNAPSHOT_STOP_REQUESTED=0 +SNAPSHOT_COPY_COMPLETE=0 PORT="${T3CODE_PORT:-3773}" SELF="$(readlink -f "$0")" @@ -1025,6 +1036,190 @@ process_in_unit_cgroup() { [[ "$process_group" == "$unit_group" || "$process_group" == "$unit_group/"* ]] } +snapshot_admission_capability() { + local listener="$1" protocol pid capability="$SNAPSHOT_ADMISSION_ROOT/capability.json" + [[ -d "$SNAPSHOT_ADMISSION_ROOT" && ! -L "$SNAPSHOT_ADMISSION_ROOT" && \ + "$(stat -c %a "$SNAPSHOT_ADMISSION_ROOT" 2>/dev/null)" == 700 && \ + -d "$SNAPSHOT_ADMISSION_ACTIVE" && ! -L "$SNAPSHOT_ADMISSION_ACTIVE" && \ + "$(stat -c %a "$SNAPSHOT_ADMISSION_ACTIVE" 2>/dev/null)" == 700 ]] || return 1 + [[ -f "$capability" && ! -L "$capability" && "$(stat -c %a "$capability" 2>/dev/null)" == 600 ]] || return 1 + protocol=$(jq -er '.protocolVersion | select(type == "number")' "$capability" 2>/dev/null) || return 1 + pid=$(jq -er '.pid | select(type == "number")' "$capability" 2>/dev/null) || return 1 + [[ "$protocol" == 1 && "$pid" == "$listener" ]] +} + +snapshot_admission_lock() { + local deadline=$((SECONDS + 5)) owner_path owner_pid age + mkdir -p "$SNAPSHOT_ADMISSION_ROOT" "$SNAPSHOT_ADMISSION_ACTIVE" || return 1 + chmod 700 "$SNAPSHOT_ADMISSION_ROOT" "$SNAPSHOT_ADMISSION_ACTIVE" || return 1 + while ! mkdir "$SNAPSHOT_ADMISSION_MUTEX" 2>/dev/null; do + [[ -d "$SNAPSHOT_ADMISSION_MUTEX" && ! -L "$SNAPSHOT_ADMISSION_MUTEX" ]] || return 1 + owner_path="$SNAPSHOT_ADMISSION_MUTEX/owner" + if [[ -e "$owner_path" ]]; then + [[ -f "$owner_path" && ! -L "$owner_path" ]] || return 1 + owner_pid=$(cat "$owner_path" 2>/dev/null) || return 1 + [[ "$owner_pid" =~ ^[1-9][0-9]*$ ]] || return 1 + if ! kill -0 "$owner_pid" 2>/dev/null; then + rm -f -- "$owner_path" || return 1 + rmdir "$SNAPSHOT_ADMISSION_MUTEX" 2>/dev/null || true + continue + fi + else + age=$(( $(date +%s) - $(stat -c %Y "$SNAPSHOT_ADMISSION_MUTEX" 2>/dev/null || echo 0) )) + if (( age > 5 )); then + rmdir "$SNAPSHOT_ADMISSION_MUTEX" 2>/dev/null || true + continue + fi + fi + (( SECONDS < deadline )) || return 1 + sleep 0.01 + done + if ! printf '%s\n' "$$" >"$SNAPSHOT_ADMISSION_MUTEX/owner" || \ + ! chmod 600 "$SNAPSHOT_ADMISSION_MUTEX/owner" || \ + ! snapshot_fsync "$SNAPSHOT_ADMISSION_MUTEX/owner" "$SNAPSHOT_ADMISSION_ROOT"; then + rm -f -- "$SNAPSHOT_ADMISSION_MUTEX/owner" + rmdir "$SNAPSHOT_ADMISSION_MUTEX" 2>/dev/null || true + return 1 + fi +} + +snapshot_admission_unlock() { + rm -f -- "$SNAPSHOT_ADMISSION_MUTEX/owner" + rmdir "$SNAPSHOT_ADMISSION_MUTEX" 2>/dev/null || true +} + +snapshot_admission_clear_stale_fence() { + local owner_pid + [[ -e "$SNAPSHOT_ADMISSION_FENCE" ]] || return 0 + [[ -f "$SNAPSHOT_ADMISSION_FENCE" && ! -L "$SNAPSHOT_ADMISSION_FENCE" ]] || return 1 + owner_pid=$(jq -er '.ownerPid | select(type == "number")' "$SNAPSHOT_ADMISSION_FENCE" 2>/dev/null) || return 1 + [[ "$owner_pid" =~ ^[1-9][0-9]*$ ]] || return 1 + if kill -0 "$owner_pid" 2>/dev/null; then + [[ "$owner_pid" == "$$" ]] && return 0 + return 1 + fi + rm -f -- "$SNAPSHOT_ADMISSION_FENCE" || return 1 + snapshot_fsync "$SNAPSHOT_ADMISSION_ROOT" +} + +snapshot_admission_active_count() { + local token pid count=0 + local -a tokens=("$SNAPSHOT_ADMISSION_ACTIVE"/*.json) + for token in "${tokens[@]}"; do + [[ -e "$token" ]] || continue + [[ -f "$token" && ! -L "$token" ]] || return 1 + pid=$(jq -er '.pid | select(type == "number")' "$token" 2>/dev/null) || return 1 + [[ "$pid" =~ ^[1-9][0-9]*$ ]] || return 1 + if kill -0 "$pid" 2>/dev/null; then + count=$((count + 1)) + else + rm -f -- "$token" || return 1 + fi + done + printf '%s' "$count" +} + +snapshot_admission_close() { + local operation="$1" point="$2" listener="$3" tmp count deadline + snapshot_admission_lock || { echo "snapshot: admission coordination lock is unavailable" >&2; return 1; } + if ! snapshot_admission_clear_stale_fence; then + snapshot_admission_unlock + echo "snapshot: another guarded operation owns the admission fence" >&2 + return 1 + fi + SNAPSHOT_ADMISSION_CLOSED_AT=$(date -u +%Y-%m-%dT%H:%M:%S.000Z) + tmp=$(mktemp "$SNAPSHOT_ADMISSION_ROOT/.snapshot-fence.XXXXXX") || { + snapshot_admission_unlock + return 1 + } + if ! jq -cn --arg operation "$operation" --arg point "$point" --arg closedAt "$SNAPSHOT_ADMISSION_CLOSED_AT" \ + --arg pid "$$" '{protocolVersion:1,ownerPid:($pid|tonumber),operationId:$operation,snapshotPoint:$point,closedAt:$closedAt}' >"$tmp" || \ + ! chmod 600 "$tmp" || ! snapshot_fsync "$tmp" || \ + ! mv -f -- "$tmp" "$SNAPSHOT_ADMISSION_FENCE"; then + rm -f -- "$tmp" + snapshot_admission_unlock + echo "snapshot: admission fence could not be durably closed" >&2 + return 1 + fi + SNAPSHOT_ADMISSION_CLOSED=1 + if ! snapshot_fsync "$SNAPSHOT_ADMISSION_ROOT"; then + snapshot_admission_unlock + echo "snapshot: admission fence directory could not be durably synced" >&2 + return 1 + fi + snapshot_admission_unlock + + deadline=$((SECONDS + 120)) + while true; do + count=$(snapshot_admission_active_count) || { + echo "snapshot: admitted command tokens could not be verified" >&2 + return 1 + } + if [[ "$count" == 0 ]]; then + SNAPSHOT_ADMISSION_DRAINED_AT=$(date -u +%Y-%m-%dT%H:%M:%S.000Z) + SNAPSHOT_ADMISSION_CAPABILITY_PID="$listener" + return 0 + fi + if (( SECONDS >= deadline )); then + echo "snapshot: $count admitted command(s) did not drain within 120 seconds" >&2 + return 1 + fi + sleep 0.1 + done +} + +snapshot_admission_open() { + local version identity receipt expected_version + version=$(active_version) || return 1 + [[ -n "$version" ]] && is_trusted "$version" && is_healthy "$version" || { + echo "snapshot: admission remains fenced until the trusted service is healthy" >&2 + return 1 + } + receipt="$GUARD_STATE/snapshot-receipts/${SNAPSHOT_ADMISSION_OPERATION}.json" + if [[ -n "$SNAPSHOT_ADMISSION_OPERATION" && -f "$receipt" ]]; then + expected_version=$(jq -r '.stoppedGeneration.version // empty' "$receipt" 2>/dev/null) || return 1 + [[ -n "$expected_version" && "$version" == "$expected_version" ]] || { + echo "snapshot: admission remains fenced because the selected service is not the recorded fork version" >&2 + return 1 + } + fi + identity=$(snapshot_service_identity "$version") || { + echo "snapshot: admission remains fenced until the trusted listener identity is verified" >&2 + return 1 + } + snapshot_admission_lock || { echo "snapshot: admission coordination lock is unavailable while reopening" >&2; return 1; } + if [[ -e "$SNAPSHOT_ADMISSION_FENCE" ]]; then + local owner_pid operation_id + owner_pid=$(jq -er '.ownerPid | select(type == "number")' "$SNAPSHOT_ADMISSION_FENCE" 2>/dev/null) || { + snapshot_admission_unlock + return 1 + } + operation_id=$(jq -r '.operationId // empty' "$SNAPSHOT_ADMISSION_FENCE" 2>/dev/null) || { + snapshot_admission_unlock + return 1 + } + if [[ "$owner_pid" == "$$" ]]; then + [[ "$operation_id" == "$SNAPSHOT_ADMISSION_OPERATION" ]] || { + snapshot_admission_unlock + return 1 + } + elif kill -0 "$owner_pid" 2>/dev/null; then + snapshot_admission_unlock + return 1 + fi + rm -f -- "$SNAPSHOT_ADMISSION_FENCE" || { + snapshot_admission_unlock + return 1 + } + snapshot_fsync "$SNAPSHOT_ADMISSION_ROOT" || { + snapshot_admission_unlock + return 1 + } + fi + snapshot_admission_unlock + SNAPSHOT_ADMISSION_CLOSED=0 +} + snapshot_service_identity() { local expected="$1" state invocation pid listener version uptime control_group state=$(unit_property ActiveState) || return 1 @@ -1035,6 +1230,7 @@ snapshot_service_identity() { [[ "$pid" =~ ^[1-9][0-9]*$ ]] || return 1 listener=$(service_listener_pid) || return 1 [[ "$listener" =~ ^[1-9][0-9]*$ && "$listener" != "$pid" ]] || return 1 + snapshot_admission_capability "$listener" || return 1 control_group=$(unit_property ControlGroup) || return 1 process_is_descendant_of "$listener" "$pid" || return 1 process_in_unit_cgroup "$pid" "$control_group" || return 1 @@ -1229,7 +1425,9 @@ snapshot_receipt_set_idle_evidence() { IFS='|' read -r invocation pid version uptime <<<"$identity" updated=$(jq -c --arg invocation "$invocation" --arg pid "$pid" --arg version "$version" \ --argjson first "$first" --argjson second "$second" \ - '.idleVerification={first:$first,second:$second} | .stoppedGeneration={invocationId:$invocation,mainPid:($pid|tonumber),version:$version}' \ + --arg closedAt "$SNAPSHOT_ADMISSION_CLOSED_AT" --arg drainedAt "$SNAPSHOT_ADMISSION_DRAINED_AT" \ + --arg capabilityPid "$SNAPSHOT_ADMISSION_CAPABILITY_PID" \ + '.idleVerification={first:$first,second:$second} | .admissionBarrier={protocolVersion:1,closedAt:$closedAt,drainedAt:$drainedAt,drainedAdmissions:0,capabilityListenerPid:($capabilityPid|tonumber)} | .stoppedGeneration={invocationId:$invocation,mainPid:($pid|tonumber),version:$version}' \ "$receipt") || return 1 write_snapshot_receipt "$receipt" "$updated" } @@ -1249,7 +1447,7 @@ snapshot_receipt_set_manifest() { write_snapshot_receipt "$receipt" "$updated" } -cmd_snapshot() { +cmd_snapshot_impl() { local operation="" point="" label label_length receipt_dir receipt status version identity local stopped_invocation stopped_pid first_activity second_activity snapshot identity_after local files generation hang state restart_invocation json @@ -1297,6 +1495,8 @@ cmd_snapshot() { cat "$receipt" return fi + [[ "$status" == stop_requested ]] && SNAPSHOT_STOP_REQUESTED=1 + [[ "$status" == copied || "$status" == captured || "$status" == restart_failed ]] && SNAPSHOT_COPY_COMPLETE=1 version=$(jq -r '.stoppedGeneration.version' "$receipt") stopped_invocation=$(jq -r '.stoppedGeneration.invocationId' "$receipt") stopped_pid=$(jq -r '.stoppedGeneration.mainPid' "$receipt") @@ -1366,6 +1566,13 @@ cmd_snapshot() { echo "snapshot: prepared service identity is no longer verified" >&2 return 1 } + local listener_pid + listener_pid=$(service_listener_pid) || { + echo "snapshot: prepared listener PID is no longer verified" >&2 + return 1 + } + SNAPSHOT_ADMISSION_OPERATION="$operation" + snapshot_admission_close "$operation" "$point" "$listener_pid" || return 1 IFS='|' read -r generation _ _ _ <<<"$identity" [[ "$generation" == "$stopped_invocation" ]] || { echo "snapshot: prepared service generation changed; no stop requested" >&2 @@ -1397,6 +1604,7 @@ cmd_snapshot() { return 1 } status=stop_requested + SNAPSHOT_STOP_REQUESTED=1 log "snapshot: operation=$operation point=$point stopping $UNIT on $version after fresh idle census" if ! svc stop --no-block "$UNIT"; then state=$(unit_property ActiveState) || state="unknown" @@ -1418,6 +1626,8 @@ cmd_snapshot() { fi if [[ "$status" == stop_requested ]]; then + SNAPSHOT_ADMISSION_OPERATION="$operation" + snapshot_admission_close "$operation" "$point" "0" || return 1 state=$(unit_property ActiveState) || state="unknown" if [[ "$state" == deactivating ]]; then wait_inactive || { @@ -1451,13 +1661,16 @@ cmd_snapshot() { return 1 } status=copied + SNAPSHOT_COPY_COMPLETE=1 fi if [[ "$status" == copied || "$status" == captured || "$status" == restart_failed ]]; then + SNAPSHOT_COPY_COMPLETE=1 [[ "$(active_version)" == "$version" ]] && is_trusted "$version" && is_healthy "$version" || { echo "snapshot: refusing to start anything except the original trusted service version $version" >&2 return 1 } + SNAPSHOT_ADMISSION_OPERATION="$operation" state=$(unit_property ActiveState) || state="unknown" if [[ "$state" == active || "$state" == activating || "$state" == deactivating ]]; then identity=$(snapshot_wait_serving "$version" "$stopped_invocation") || { @@ -1472,6 +1685,10 @@ cmd_snapshot() { return 1 } fi + snapshot_admission_open || { + echo "snapshot: same-version service is healthy, but its admission fence could not be reopened" >&2 + return 1 + } if [[ "$status" == copied ]]; then files=$(snapshot_manifest "$snapshot") || { hold_updates "snapshot operation $operation restarted the service but could not verify the copied files" @@ -1496,6 +1713,26 @@ cmd_snapshot() { log "snapshot: operation=$operation restarted and verified $version" cat "$receipt" } + +cmd_snapshot() { + local status=0 + SNAPSHOT_ADMISSION_CLOSED=0 + SNAPSHOT_ADMISSION_OPERATION="${1:-}" + SNAPSHOT_ADMISSION_CLOSED_AT="" + SNAPSHOT_ADMISSION_DRAINED_AT="" + SNAPSHOT_ADMISSION_CAPABILITY_PID=0 + SNAPSHOT_STOP_REQUESTED=0 + SNAPSHOT_COPY_COMPLETE=0 + cmd_snapshot_impl "$@" || status=$? + if [[ "$SNAPSHOT_ADMISSION_CLOSED" == 1 && \ + ( "$SNAPSHOT_STOP_REQUESTED" == 0 || "$SNAPSHOT_COPY_COMPLETE" == 1 ) ]]; then + snapshot_admission_open || { + echo "snapshot: service-change admission fence remains closed" >&2 + [[ "$status" != 0 ]] || status=1 + } + fi + return "$status" +} # Install the newest trusted release (or $1), verify it serves, roll back if not. cmd_update() { local now_flag="" target="" cur latest runs sha blockers="" forced="" hang deferred_epoch="" diff --git a/scripts/fork/host/t3-update-guard/t3-service-update b/scripts/fork/host/t3-update-guard/t3-service-update index 77647b1a04443..5c554e3058a63 100755 --- a/scripts/fork/host/t3-update-guard/t3-service-update +++ b/scripts/fork/host/t3-update-guard/t3-service-update @@ -6,9 +6,27 @@ # t3-service-update status # t3-service-update resume lift an automatic-updates hold once its cause is fixed # t3-service-update snapshot +GUARD="$HOME/.local/libexec/t3-update-guard/guard" case "${1:-}" in - status) exec "$HOME/.local/libexec/t3-update-guard/guard" status ;; - resume) exec "$HOME/.local/libexec/t3-update-guard/guard" resume ;; - snapshot) shift; exec "$HOME/.local/libexec/t3-update-guard/guard" snapshot "$@" ;; + status) exec "$GUARD" status ;; + resume) exec "$GUARD" resume ;; + snapshot) + shift + if [ "$#" -ne 2 ]; then + echo "usage: t3-service-update snapshot " >&2 + exit 2 + fi + operation="$1" + point="$2" + unit="t3-update-guard-snapshot-$(date +%s%N)-$$" + set -- --user --collect --pipe --wait "--setenv=HOME=$HOME" + [ -n "${PATH:-}" ] && set -- "$@" "--setenv=PATH=$PATH" + [ -n "${T3CODE_HOME:-}" ] && set -- "$@" "--setenv=T3CODE_HOME=$T3CODE_HOME" + [ -n "${T3_GUARD_STATE_DIR:-}" ] && set -- "$@" "--setenv=T3_GUARD_STATE_DIR=$T3_GUARD_STATE_DIR" + [ -n "${XDG_CONFIG_HOME:-}" ] && set -- "$@" "--setenv=XDG_CONFIG_HOME=$XDG_CONFIG_HOME" + [ -n "${XDG_STATE_HOME:-}" ] && set -- "$@" "--setenv=XDG_STATE_HOME=$XDG_STATE_HOME" + [ -n "${T3CODE_PORT:-}" ] && set -- "$@" "--setenv=T3CODE_PORT=$T3CODE_PORT" + exec systemd-run "$@" --unit="$unit" "$GUARD" snapshot "$operation" "$point" + ;; esac -exec "$HOME/.local/libexec/t3-update-guard/guard" update "$@" +exec "$GUARD" update "$@" diff --git a/scripts/fork/host/t3-update-guard/test-guard.sh b/scripts/fork/host/t3-update-guard/test-guard.sh index 660da3d89da66..5859c6b83b9d8 100755 --- a/scripts/fork/host/t3-update-guard/test-guard.sh +++ b/scripts/fork/host/t3-update-guard/test-guard.sh @@ -2,7 +2,7 @@ set -eu original="$(cd "$(dirname "$0")" && pwd)/guard" root=$(mktemp -d) -trap 'rm -rf "$root"' EXIT +trap 'rm -r -- "$root" "$root/functions" @@ -679,6 +679,11 @@ EOF sleep 0.05 done service_listener_pid >/dev/null 2>&1 || fail 'could not start the isolated launcher-child listener' + mkdir -p "$SNAPSHOT_ADMISSION_ACTIVE" + chmod 700 "$SNAPSHOT_ADMISSION_ROOT" "$SNAPSHOT_ADMISSION_ACTIVE" + printf '{"protocolVersion":1,"pid":%s,"startedAt":"2026-11-27T00:00:00.000Z"}\n' \ + "$(service_listener_pid)" >"$SNAPSHOT_ADMISSION_ROOT/capability.json" + chmod 600 "$SNAPSHOT_ADMISSION_ROOT/capability.json" manager_ready() { return 0; } active_version() { echo "$sim_version"; } is_trusted() { return 0; } @@ -696,6 +701,16 @@ EOF } kernel_hang_signs() { return 1; } wait_inactive() { [[ "$(cat "$sim_state_file")" == inactive ]]; } + real_snapshot_admission_open=$(declare -f snapshot_admission_open) + eval "${real_snapshot_admission_open/snapshot_admission_open/snapshot_admission_open_inner}" + snapshot_admission_open() { + local version identity + version=$(active_version) || fail 'admission fence reopened without an active version' + is_trusted "$version" && is_healthy "$version" || fail 'admission fence reopened before trusted health verification' + identity=$(snapshot_service_identity "$version") || fail 'admission fence reopened before listener identity verification' + printf 'admission-open-after-verified-restart\n' >>"$root/snapshot-admission-order" + snapshot_admission_open_inner + } cp() { if [[ "$1" == --reflink=always ]]; then shift; fi; command cp "$@"; } snapshot_fsync() { local path @@ -744,7 +759,8 @@ for path in sys.argv[1:]: ;; start) [[ "$(jq -r '.status' "$GUARD_STATE/snapshot-receipts/snapshot-op.json")" == copied ]] || fail 'restart ran before the copied receipt was durable' - [[ "$(tail -n 1 "$root/snapshot-fsync")" == "fsync:$GUARD_STATE/snapshot-receipts" ]] || fail 'restart ran before the copied receipt directory was fsynced' + grep -Fqx "fsync:$GUARD_STATE/snapshot-receipts" "$root/snapshot-fsync" || fail 'restart ran before the copied receipt directory was fsynced' + [[ -f "$SNAPSHOT_ADMISSION_FENCE" ]] || fail 'admission fence opened before the restarted listener was verified' printf 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n' >"$sim_generation_file" printf 'start\n' >"$sim_command_fifo" local i @@ -753,6 +769,9 @@ for path in sys.argv[1:]: sleep 0.05 done service_listener_pid >/dev/null 2>&1 || fail 'same-version child listener did not restart' + printf '{"protocolVersion":1,"pid":%s,"startedAt":"2026-11-27T00:00:01.000Z"}\n' \ + "$(service_listener_pid)" >"$SNAPSHOT_ADMISSION_ROOT/capability.json" + chmod 600 "$SNAPSHOT_ADMISSION_ROOT/capability.json" printf 'active\n' >"$sim_state_file" ;; *) return 1 ;; @@ -822,6 +841,13 @@ for path in sys.argv[1:]: sim_identity=$(snapshot_service_identity "$sim_version") || fail 'real child listener did not bind to its launcher' sim_listener=$(service_listener_pid) [[ "$sim_listener" == "$(cat "$sim_listener_file")" && "$sim_listener" != "$sim_pid" ]] || fail 'fixture did not prove a child listener distinct from MainPID' + cp "$SNAPSHOT_ADMISSION_ROOT/capability.json" "$root/capability.json" + printf '{"protocolVersion":1,"pid":%s}\n' "$sim_pid" >"$SNAPSHOT_ADMISSION_ROOT/capability.json" + chmod 600 "$SNAPSHOT_ADMISSION_ROOT/capability.json" + if snapshot_service_identity "$sim_version" >/dev/null 2>&1; then fail 'launcher MainPID was accepted as the listener capability PID'; fi + cp "$root/capability.json" "$SNAPSHOT_ADMISSION_ROOT/capability.json" + chmod 600 "$SNAPSHOT_ADMISSION_ROOT/capability.json" + sim_identity=$(snapshot_service_identity "$sim_version") || fail 'valid listener capability marker was not restored' sleep 100 & sibling_pid=$! sim_pid=$sibling_pid @@ -840,6 +866,35 @@ for path in sys.argv[1:]: exec 9>&- [[ -z "$(grep '^stop ' "$root/snapshot-svc" 2>/dev/null || true)" ]] || fail 'snapshot stopped before its prepared receipt was durable' [[ ! -e "$GUARD_STATE/snapshot-receipts/snapshot-op.json" ]] || fail 'failed prepared receipt was published' + + # An admitted command owns a token until its commit finishes. The guard closes the fence, + # waits for that token, then takes the final census and catches the committed preparing run. + admission_release="$root/admission-release" + rm -f "$admission_release" + ( + while [[ ! -e "$admission_release" ]]; do sleep 0.01; done + ) & + admission_pid=$! + admission_token="$SNAPSHOT_ADMISSION_ACTIVE/$admission_pid-regression.json" + printf '{"pid":%s}\n' "$admission_pid" >"$admission_token" + chmod 600 "$admission_token" + (cmd_snapshot snapshot-op before-stock-switch >"$root/snapshot-fenced-census.out" 2>&1) & + snapshot_guard_pid=$! + for ((i=0; i<100; i++)); do + [[ -f "$SNAPSHOT_ADMISSION_FENCE" ]] && break + sleep 0.02 + done + [[ -f "$SNAPSHOT_ADMISSION_FENCE" ]] || fail 'snapshot did not close the admission fence before its final census' + [[ -z "$(grep '^stop ' "$root/snapshot-svc" 2>/dev/null || true)" ]] || fail 'snapshot stopped while an admitted command was draining' + sqlite3 "$DB" "insert into orchestration_v2_projection_runs values ('fenced','thread','preparing','2026-11-27T00:00:00.000Z',null,'{}');" + touch "$admission_release" + if wait "$snapshot_guard_pid"; then fail 'snapshot stopped after a command committed during admission drain'; fi + wait "$admission_pid" 2>/dev/null || true + [[ ! -e "$SNAPSHOT_ADMISSION_FENCE" ]] || fail 'pre-stop refusal left the admission fence closed' + [[ -z "$(grep '^stop ' "$root/snapshot-svc" 2>/dev/null || true)" ]] || fail 'snapshot stopped before the final post-drain census passed' + grep -q 'runs=1' "$root/snapshot-fenced-census.out" || fail 'post-drain census omitted the admitted preparing run' + sqlite3 "$DB" "delete from orchestration_v2_projection_runs;" + cmd_snapshot snapshot-op before-stock-switch >"$root/snapshot-out" || fail 'snapshot-only command failed in the isolated service fixture' out=$(cat "$root/snapshot-out") receipt="$GUARD_STATE/snapshot-receipts/snapshot-op.json" @@ -851,10 +906,14 @@ for path in sys.argv[1:]: [[ "$(sha256sum "$(jq -r '.snapshotPath' "$receipt")/statev2.sqlite" | cut -d' ' -f1)" == "$(sha256sum "$DB" | cut -d' ' -f1)" ]] || fail 'snapshot main database differs from the stopped source' [[ "$(stat -c %a "$receipt")" == 600 && "$(stat -c %a "$(jq -r '.snapshotPath' "$receipt")")" == 700 ]] || fail 'snapshot receipt or files are not under owner-only directories' [[ "$(jq -r '.idleVerification.first.runs' "$receipt")" == 0 && "$(jq -r '.idleVerification.second.runs' "$receipt")" == 0 ]] || fail 'receipt did not retain both clean idle censuses' + [[ "$(jq -r '.admissionBarrier.protocolVersion' "$receipt")" == 1 && \ + "$(jq -r '.admissionBarrier.drainedAdmissions' "$receipt")" == 0 && \ + "$(jq -r '.admissionBarrier.capabilityListenerPid' "$receipt")" =~ ^[1-9][0-9]*$ ]] || fail 'receipt did not retain the drained admission-fence proof' [[ -d "$SNAPSHOTS/20200101T000000-before" && -d "$SNAPSHOTS/20200104T000000-before" ]] || fail 'one-off snapshot rotated away an earlier copy' [[ "$(grep -c '^stop --no-block t3code.service$' "$root/snapshot-svc")" == 1 ]] || fail 'snapshot did not stop exactly once' [[ "$(grep -c '^start --no-block t3code.service$' "$root/snapshot-svc")" == 1 ]] || fail 'snapshot did not restart exactly once' [[ -s "$root/snapshot-hash-order" ]] || fail 'copied files were not hashed after restart' + [[ -s "$root/snapshot-admission-order" && ! -e "$SNAPSHOT_ADMISSION_FENCE" ]] || fail 'admission fence did not stay closed through restart verification' cmd_snapshot snapshot-op before-stock-switch >"$root/snapshot-out" || fail 'idempotent snapshot retry did not return its receipt' [[ "$(grep -c '^stop --no-block t3code.service$' "$root/snapshot-svc")" == 1 ]] || fail 'idempotent retry stopped the service twice' if cmd_snapshot snapshot-op different-point >/dev/null 2>&1; then fail 'snapshot reused an operation ID with a different point'; fi @@ -862,3 +921,41 @@ for path in sys.argv[1:]: [[ "$(grep -c '^stop --no-block t3code.service$' "$root/snapshot-svc")" == 1 ]] || fail 'mismatched receipt retry stopped the service again' ) || fail 'snapshot-only path violated its isolated activity, identity, durability, or restart contract' pass 'snapshot-only path verifies full idle state and durable receipts, restarts before hashing, and is idempotent' + +# The public wrapper runs the guard in a transient user service outside t3code.service so the +# executor itself survives the same-version stop/restart and can return the durable receipt. +wrapper_root="$root/snapshot-wrapper" +mkdir -p "$wrapper_root/home/.local/libexec/t3-update-guard" "$wrapper_root/bin" +cat >"$wrapper_root/home/.local/libexec/t3-update-guard/guard" <<'EOF' +#!/bin/sh +printf '%s\n' "$@" >"$SNAPSHOT_GUARD_ARGS" +printf '{"status":"complete"}\n' +EOF +cat >"$wrapper_root/bin/systemd-run" <<'EOF' +#!/bin/sh +printf '%s\n' "$@" >"$SNAPSHOT_SYSTEMD_RUN_ARGS" +while [ "$#" -gt 0 ]; do + case "$1" in + --*) shift ;; + *) exec "$@" ;; + esac +done +exit 2 +EOF +chmod +x "$wrapper_root/home/.local/libexec/t3-update-guard/guard" "$wrapper_root/bin/systemd-run" +SNAPSHOT_GUARD_ARGS="$wrapper_root/guard-args" \ +SNAPSHOT_SYSTEMD_RUN_ARGS="$wrapper_root/systemd-run-args" \ +HOME="$wrapper_root/home" PATH="$wrapper_root/bin:$PATH" \ + "$(dirname "$original")/t3-service-update" snapshot snapshot-op before-stock-switch >"$wrapper_root/output" || + fail 'snapshot wrapper did not return the transient unit receipt' +grep -Fxq -- '--user' "$wrapper_root/systemd-run-args" || fail 'snapshot wrapper did not use the user systemd manager' +grep -Fxq -- '--collect' "$wrapper_root/systemd-run-args" || fail 'snapshot wrapper did not collect the transient unit' +grep -Fxq -- '--pipe' "$wrapper_root/systemd-run-args" || fail 'snapshot wrapper did not return the receipt through its pipe' +grep -Fxq -- '--wait' "$wrapper_root/systemd-run-args" || fail 'snapshot wrapper returned before its transient executor finished' +grep -Eq '^--unit=t3-update-guard-snapshot-[0-9]+-[0-9]+$' "$wrapper_root/systemd-run-args" || + fail 'snapshot executor was not assigned a separate transient unit' +[[ "$(cat "$wrapper_root/guard-args")" == $'snapshot\nsnapshot-op\nbefore-stock-switch' ]] || + fail 'transient executor did not receive the snapshot-only arguments' +[[ "$(cat "$wrapper_root/output")" == '{"status":"complete"}' ]] || + fail 'snapshot wrapper did not relay the durable guard receipt' +pass 'snapshot wrapper runs the guard in a separate transient service and returns its receipt' From 7e10a76b442fecead20ac3cdf0da680d95261cc8 Mon Sep 17 00:00:00 2001 From: Chris OHearn Date: Fri, 27 Nov 2026 04:50:46 -0700 Subject: [PATCH 4/7] fix(fork): bound empty-history snapshot quiet window --- scripts/fork/host/t3-update-guard/guard | 14 ++++++++++++-- scripts/fork/host/t3-update-guard/test-guard.sh | 12 ++++++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/scripts/fork/host/t3-update-guard/guard b/scripts/fork/host/t3-update-guard/guard index edd81f44dd207..a8436814087dc 100755 --- a/scripts/fork/host/t3-update-guard/guard +++ b/scripts/fork/host/t3-update-guard/guard @@ -675,8 +675,18 @@ PRE_RESTART="$GUARD_STATE/pre-restart" CANARY_SECONDS="${CANARY_SECONDS:-300}" CANARY_FAILURES="${CANARY_FAILURES:-2}" quiet_seconds() { - timeout 10 sqlite3 -readonly "$DB" \ - "select cast((julianday('now') - julianday(max(max(coalesce(completed_at,'')), max(requested_at)))) * 86400 as int) from orchestration_v2_projection_runs;" 2>/dev/null + local history count quiet + history=$(timeout 10 sqlite3 -readonly -separator '|' "$DB" \ + "select count(*), coalesce(cast((julianday('now') - julianday(max(max(coalesce(completed_at,'')), max(requested_at)))) * 86400 as int), -1) from orchestration_v2_projection_runs;" 2>/dev/null) || return 1 + IFS='|' read -r count quiet <<<"$history" + [[ "$count" =~ ^[0-9]+$ && "$quiet" =~ ^-?[0-9]+$ ]] || return 1 + # An empty run table has no activity timestamp. Use the current server generation's + # uptime as the quiet period, so a fresh install still waits the full configured window. + if (( count == 0 )); then + service_uptime + else + echo "$quiet" + fi } # What a restart now would break in a way restart recovery cannot undo (checked 2026-11-13): diff --git a/scripts/fork/host/t3-update-guard/test-guard.sh b/scripts/fork/host/t3-update-guard/test-guard.sh index 5859c6b83b9d8..dd54fe84ce52c 100755 --- a/scripts/fork/host/t3-update-guard/test-guard.sh +++ b/scripts/fork/host/t3-update-guard/test-guard.sh @@ -690,6 +690,18 @@ EOF is_healthy() { return 0; } service_version() { echo "$sim_version"; } service_uptime() { echo 120; } + service_uptime() { echo 899; } + [[ "$(quiet_seconds)" == 899 ]] || fail 'empty run history did not use server uptime for its quiet window' + service_uptime() { echo 900; } + [[ "$(quiet_seconds)" == 900 ]] || fail 'empty run history did not qualify after a full server-uptime quiet window' + service_uptime() { return 1; } + if quiet_seconds >/dev/null 2>&1; then fail 'empty run history accepted an unverified service uptime'; fi + service_uptime() { echo 1; } + sqlite3 "$DB" "insert into orchestration_v2_projection_runs values ('quiet-history','thread','completed',strftime('%Y-%m-%dT%H:%M:%fZ','now','-1 hour'),strftime('%Y-%m-%dT%H:%M:%fZ','now','-1 hour'),'{}');" + quiet=$(quiet_seconds) + [[ "$quiet" =~ ^[0-9]+$ ]] && (( quiet >= 900 )) || fail 'existing run history stopped using its last activity timestamp' + sqlite3 "$DB" "delete from orchestration_v2_projection_runs;" + service_uptime() { echo 120; } unit_property() { case "$1" in ActiveState) cat "$sim_state_file" ;; From 85f870fb46a148476c0d19c44a51096b28fe9407 Mon Sep 17 00:00:00 2001 From: Chris OHearn Date: Fri, 27 Nov 2026 06:34:25 -0700 Subject: [PATCH 5/7] fix guarded snapshot races and cancellation cleanup --- .../ThreadLaunchService.test.ts | 36 +++- .../orchestration-v2/ThreadLaunchService.ts | 12 +- .../server/src/serviceChangeAdmission.test.ts | 21 +- apps/server/src/serviceChangeAdmission.ts | 200 ++++++++++-------- scripts/fork/host/t3-update-guard/guard | 82 ++++--- .../fork/host/t3-update-guard/test-guard.sh | 62 +++++- 6 files changed, 280 insertions(+), 133 deletions(-) diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts index 5915fb3defe6a..0259396a6ce6d 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts @@ -3521,11 +3521,30 @@ it.live.each(concurrentTaskFolderUses)("cancels task folder setup with %s", (con Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-launch-folders-" })), Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), ); - const layerTaskFolders = layerTaskFoldersWithGit(state).pipe( - Layer.provide(layerGit), - Layer.orDie, - ); return Effect.gen(function* () { + const taskFolderRemovalStarted = yield* Deferred.make(); + const allowTaskFolderRemoval = yield* Deferred.make(); + const baseTaskFolders = layerTaskFoldersWithGit(state).pipe( + Layer.provide(layerGit), + Layer.orDie, + ); + const layerTaskFolders = + concurrent === "side chat without a run" + ? Layer.effect( + TaskFolders.TaskFolders, + Effect.gen(function* () { + const folders = yield* TaskFolders.TaskFolders; + return { + ...folders, + remove: (input) => + Deferred.succeed(taskFolderRemovalStarted, undefined).pipe( + Effect.andThen(Deferred.await(allowTaskFolderRemoval)), + Effect.andThen(folders.remove(input)), + ), + }; + }), + ).pipe(Layer.provide(baseTaskFolders)) + : baseTaskFolders; const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const git = yield* GitVcsDriver.GitVcsDriver; @@ -3639,7 +3658,14 @@ it.live.each(concurrentTaskFolderUses)("cancels task folder setup with %s", (con Effect.flip, ); assert.equal(refused._tag, "OrchestratorDispatchError"); - assert.isTrue(yield* tracker.cancel(launched.threadId)); + if (concurrent === "side chat without a run") { + const cancellation = yield* tracker.cancel(launched.threadId).pipe(Effect.forkChild); + yield* Deferred.await(taskFolderRemovalStarted); + yield* Deferred.succeed(allowTaskFolderRemoval, undefined); + assert.isTrue(yield* Fiber.join(cancellation)); + } else { + assert.isTrue(yield* tracker.cancel(launched.threadId)); + } assert.isNull((yield* threads.getThreadProjection(launched.threadId)).thread.worktreePath); assert.isNull(yield* taskFolders.find(taskFolder!.root)); diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.ts index 622fe99752226..eb427c544c528 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.ts @@ -1285,7 +1285,7 @@ const make = Effect.gen(function* () { ), ), ); - yield* Effect.gen(function* () { + const cleanupWorkspace = Effect.gen(function* () { // An explicit launch can bind a repository inside a task folder during setup. if (yield* worktreeIsShared(removedTaskFolder ?? removedPath, threadId)) return; // Keep the binding if removal fails so a retry can find the checkout. @@ -1310,6 +1310,16 @@ const make = Effect.gen(function* () { }), ), ); + yield* removedTaskFolder === null + ? cleanupWorkspace + : Effect.uninterruptible(cleanupWorkspace); + } + if (cancelled && runId !== null) { + // The tracked setup fiber can be interrupted before its race parent observes the + // exit, so persist the run failure here before cancellation is acknowledged. + yield* Effect.uninterruptible( + failPreparedRun(input, threadId, runId, "Worktree setup cancelled."), + ); } }), ), diff --git a/apps/server/src/serviceChangeAdmission.test.ts b/apps/server/src/serviceChangeAdmission.test.ts index 06196c88fb2b8..cb49d074f357f 100644 --- a/apps/server/src/serviceChangeAdmission.test.ts +++ b/apps/server/src/serviceChangeAdmission.test.ts @@ -4,8 +4,8 @@ import * as NodeFS from "node:fs"; import * as NodeOS from "node:os"; // @effect-diagnostics-next-line nodeBuiltinImport:off -- The test creates and removes its isolated runtime directory. import * as NodePath from "node:path"; -import * as NodeServices from "@effect/platform-node/NodeServices"; import * as Deferred from "effect/Deferred"; +import * as NodeServices from "@effect/platform-node/NodeServices"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; @@ -81,3 +81,22 @@ it.effect("drains admitted commands before refusing work behind the snapshot fen Effect.ensuring(Effect.sync(() => NodeFS.rmSync(baseDir, { recursive: true, force: true }))), ); }); + +it.effect("serializes concurrent local admission file creation", () => { + const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-snapshot-admission-")); + const active = NodePath.join(baseDir, "runtime", "service-change-admission", "active"); + + return Effect.gen(function* () { + yield* ServiceChangeAdmission.initialize(baseDir); + const admissions = yield* Effect.all( + Array.from({ length: 16 }, () => + ServiceChangeAdmission.withAdmissionAt(baseDir, Effect.void), + ), + { concurrency: "unbounded" }, + ); + assert.lengthOf(admissions, 16); + assert.isEmpty(NodeFS.readdirSync(active)); + }).pipe( + Effect.ensuring(Effect.sync(() => NodeFS.rmSync(baseDir, { recursive: true, force: true }))), + ); +}); diff --git a/apps/server/src/serviceChangeAdmission.ts b/apps/server/src/serviceChangeAdmission.ts index ab4a69faf81c6..42203068da2cc 100644 --- a/apps/server/src/serviceChangeAdmission.ts +++ b/apps/server/src/serviceChangeAdmission.ts @@ -10,6 +10,7 @@ import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; +import * as Semaphore from "effect/Semaphore"; import * as ServerConfig from "./config.ts"; const PROTOCOL_VERSION = 1; @@ -27,6 +28,17 @@ interface AdmissionPaths { readonly capability: string; } +const admissionPathsByBaseDir = new Map(); +const admissionMutexesByBaseDir = new Map(); + +const admissionMutex = (baseDir: string) => { + const cached = admissionMutexesByBaseDir.get(baseDir); + if (cached !== undefined) return cached; + const mutex = Semaphore.makeUnsafe(1); + admissionMutexesByBaseDir.set(baseDir, mutex); + return mutex; +}; + export class ServiceChangeAdmissionError extends Schema.TaggedError< ServiceChangeAdmissionError, { readonly brand: unique symbol } @@ -62,14 +74,18 @@ class AdmissionLeaseContext extends Context.Service { + const cached = admissionPathsByBaseDir.get(baseDir); + if (cached !== undefined) return cached; const root = NodePath.join(baseDir, "runtime", "service-change-admission"); - return { + const paths = { root, mutex: NodePath.join(root, "mutex"), active: NodePath.join(root, "active"), fence: NodePath.join(root, "snapshot-fence.json"), capability: NodePath.join(root, "capability.json"), }; + admissionPathsByBaseDir.set(baseDir, paths); + return paths; }; const pidIsAlive = (pid: number) => { @@ -82,37 +98,36 @@ const pidIsAlive = (pid: number) => { } }; -const ensureDirectories = (paths: AdmissionPaths) => { - NodeFS.mkdirSync(paths.root, { recursive: true, mode: 0o700 }); - NodeFS.mkdirSync(paths.active, { recursive: true, mode: 0o700 }); - if ( - NodeFS.lstatSync(paths.root).isSymbolicLink() || - NodeFS.lstatSync(paths.active).isSymbolicLink() - ) { +const ensureDirectories = async (paths: AdmissionPaths) => { + await NodeFS.promises.mkdir(paths.root, { recursive: true, mode: 0o700 }); + await NodeFS.promises.mkdir(paths.active, { recursive: true, mode: 0o700 }); + const root = await NodeFS.promises.lstat(paths.root); + const active = await NodeFS.promises.lstat(paths.active); + if (root.isSymbolicLink() || active.isSymbolicLink()) { throw new Error("Snapshot admission directories must not be symbolic links."); } - NodeFS.chmodSync(paths.root, 0o700); - NodeFS.chmodSync(paths.active, 0o700); + await NodeFS.promises.chmod(paths.root, 0o700); + await NodeFS.promises.chmod(paths.active, 0o700); }; -const releaseMutex = (paths: AdmissionPaths) => { +const releaseMutex = async (paths: AdmissionPaths) => { try { - NodeFS.unlinkSync(NodePath.join(paths.mutex, "owner")); + await NodeFS.promises.unlink(NodePath.join(paths.mutex, "owner")); } catch { // A missing owner file means an interrupted or already completed cleanup. } try { - NodeFS.rmdirSync(paths.mutex); + await NodeFS.promises.rmdir(paths.mutex); } catch { // Leave unexpected contents in place; the next caller fails closed. } }; -const removeStaleMutex = (paths: AdmissionPaths, now: number) => { +const removeStaleMutex = async (paths: AdmissionPaths, now: number) => { const ownerPath = NodePath.join(paths.mutex, "owner"); - let stat: NodeFS.Stats; + let stat: Awaited>; try { - stat = NodeFS.lstatSync(paths.mutex); + stat = await NodeFS.promises.lstat(paths.mutex); } catch (cause) { if (typeof cause === "object" && cause !== null && "code" in cause && cause.code === "ENOENT") { return; @@ -123,11 +138,11 @@ const removeStaleMutex = (paths: AdmissionPaths, now: number) => { throw new Error("Admission mutex is not a real directory."); let ownerPid: number | undefined; try { - const ownerStat = NodeFS.lstatSync(ownerPath); + const ownerStat = await NodeFS.promises.lstat(ownerPath); if (!ownerStat.isFile() || ownerStat.isSymbolicLink() || (ownerStat.mode & 0o777) !== 0o600) { throw new Error("Admission mutex owner is not a private regular file."); } - const ownerText = NodeFS.readFileSync(ownerPath, "utf8").trim(); + const ownerText = (await NodeFS.promises.readFile(ownerPath, "utf8")).trim(); if (!/^[1-9][0-9]*$/.test(ownerText)) throw new Error("Admission mutex owner PID is invalid."); ownerPid = Number(ownerText); if (!Number.isSafeInteger(ownerPid)) throw new Error("Admission mutex owner PID is invalid."); @@ -140,7 +155,7 @@ const removeStaleMutex = (paths: AdmissionPaths, now: number) => { if (now - stat.mtimeMs <= 5_000) return; } if (ownerPid !== undefined && pidIsAlive(ownerPid)) return; - releaseMutex(paths); + await releaseMutex(paths); }; type MutexAttempt = @@ -148,9 +163,9 @@ type MutexAttempt = | { readonly tag: "busy" } | { readonly tag: "failed"; readonly cause: unknown }; -const attemptAcquireMutex = (paths: AdmissionPaths): MutexAttempt => { +const attemptAcquireMutex = async (paths: AdmissionPaths): Promise => { try { - NodeFS.mkdirSync(paths.mutex, { mode: 0o700 }); + await NodeFS.promises.mkdir(paths.mutex, { mode: 0o700 }); } catch (cause) { if (typeof cause === "object" && cause !== null && "code" in cause && cause.code === "EEXIST") { return { tag: "busy" }; @@ -158,14 +173,14 @@ const attemptAcquireMutex = (paths: AdmissionPaths): MutexAttempt => { return { tag: "failed", cause }; } try { - NodeFS.writeFileSync(NodePath.join(paths.mutex, "owner"), `${process.pid}\n`, { + await NodeFS.promises.writeFile(NodePath.join(paths.mutex, "owner"), `${process.pid}\n`, { mode: 0o600, flag: "wx", }); return { tag: "acquired" }; } catch (cause) { try { - NodeFS.rmdirSync(paths.mutex); + await NodeFS.promises.rmdir(paths.mutex); } catch { // Preserve the original failure and refuse admission. } @@ -178,14 +193,19 @@ const acquireMutex = Effect.fn("ServiceChangeAdmission.acquireMutex")(function* ) { const deadline = (yield* Clock.currentTimeMillis) + MUTEX_WAIT_MS; while (true) { - const attempt = yield* Effect.sync(() => attemptAcquireMutex(paths)); + const attempt = yield* Effect.uninterruptible( + Effect.tryPromise({ + try: () => attemptAcquireMutex(paths), + catch: (cause) => new ServiceChangeAdmissionError({ stage: "mutex", cause }), + }), + ); if (attempt.tag === "acquired") return; if (attempt.tag === "failed") { return yield* new ServiceChangeAdmissionError({ stage: "mutex", cause: attempt.cause }); } const now = yield* Clock.currentTimeMillis; - yield* Effect.try({ + yield* Effect.tryPromise({ try: () => removeStaleMutex(paths, now), catch: (cause) => new ServiceChangeAdmissionError({ stage: "mutex", cause }), }); @@ -198,27 +218,29 @@ const acquireMutex = Effect.fn("ServiceChangeAdmission.acquireMutex")(function* const withMutex = ( paths: AdmissionPaths, - operation: () => A, + operation: () => Promise, ): Effect.Effect => Effect.scoped( Effect.gen(function* () { yield* Effect.acquireRelease(acquireMutex(paths), () => - Effect.sync(() => releaseMutex(paths)), + Effect.promise(() => releaseMutex(paths)), + ); + return yield* Effect.uninterruptible( + Effect.tryPromise({ + try: operation, + catch: (cause) => + isServiceChangeAdmissionError(cause) + ? cause + : new ServiceChangeAdmissionError({ stage: "fence", cause }), + }), ); - return yield* Effect.try({ - try: operation, - catch: (cause) => - isServiceChangeAdmissionError(cause) - ? cause - : new ServiceChangeAdmissionError({ stage: "fence", cause }), - }); }), ); -const removeStaleFence = (paths: AdmissionPaths) => { - let stat: NodeFS.Stats; +const removeStaleFence = async (paths: AdmissionPaths) => { + let stat: Awaited>; try { - stat = NodeFS.lstatSync(paths.fence); + stat = await NodeFS.promises.lstat(paths.fence); } catch (cause) { if (typeof cause === "object" && cause !== null && "code" in cause && cause.code === "ENOENT") return; @@ -229,7 +251,7 @@ const removeStaleFence = (paths: AdmissionPaths) => { } let ownerPid: number; try { - const fence = JSON.parse(NodeFS.readFileSync(paths.fence, "utf8")) as { + const fence = JSON.parse(await NodeFS.promises.readFile(paths.fence, "utf8")) as { protocolVersion?: unknown; ownerPid?: unknown; }; @@ -245,28 +267,30 @@ const removeStaleFence = (paths: AdmissionPaths) => { if (pidIsAlive(ownerPid)) { throw new ServiceChangeAdmissionError({ stage: "fence" }); } - NodeFS.unlinkSync(paths.fence); + await NodeFS.promises.unlink(paths.fence); }; const createAdmission = (baseDir: string) => { const paths = admissionPaths(baseDir); - return Effect.try({ - try: () => ensureDirectories(paths), - catch: (cause) => new ServiceChangeAdmissionError({ stage: "storage", cause }), - }).pipe( - Effect.andThen( - withMutex(paths, () => { - removeStaleFence(paths); - const tokenPath = NodePath.join( - paths.active, - `${process.pid}-${NodeCrypto.randomUUID()}.json`, - ); - NodeFS.writeFileSync(tokenPath, JSON.stringify({ pid: process.pid }), { - mode: 0o600, - flag: "wx", - }); - return { tokenPath } satisfies AdmissionLease; - }), + return Semaphore.withPermit(admissionMutex(baseDir))( + Effect.tryPromise({ + try: () => ensureDirectories(paths), + catch: (cause) => new ServiceChangeAdmissionError({ stage: "storage", cause }), + }).pipe( + Effect.andThen( + withMutex(paths, async () => { + await removeStaleFence(paths); + const tokenPath = NodePath.join( + paths.active, + `${process.pid}-${NodeCrypto.randomUUID()}.json`, + ); + await NodeFS.promises.writeFile(tokenPath, JSON.stringify({ pid: process.pid }), { + mode: 0o600, + flag: "wx", + }); + return { tokenPath } satisfies AdmissionLease; + }), + ), ), ); }; @@ -280,40 +304,42 @@ export const initialize = Effect.fn("ServiceChangeAdmission.initialize")(functio pid: process.pid, startedAt, }).pipe(Effect.mapError((cause) => new ServiceChangeAdmissionError({ stage: "storage", cause }))); - return yield* Effect.try({ - try: () => { - const paths = admissionPaths(baseDir); - ensureDirectories(paths); - const temporary = `${paths.capability}.${process.pid}.${NodeCrypto.randomUUID()}.tmp`; - const descriptor = NodeFS.openSync(temporary, "wx", 0o600); - try { - NodeFS.writeFileSync(descriptor, `${contents}\n`, "utf8"); - NodeFS.fsyncSync(descriptor); - } finally { - NodeFS.closeSync(descriptor); - } - NodeFS.renameSync(temporary, paths.capability); - const directoryDescriptor = NodeFS.openSync(paths.root, "r"); - try { - NodeFS.fsyncSync(directoryDescriptor); - } finally { - NodeFS.closeSync(directoryDescriptor); - } - }, - catch: (cause) => new ServiceChangeAdmissionError({ stage: "storage", cause }), - }); + return yield* Effect.uninterruptible( + Effect.tryPromise({ + try: async () => { + const paths = admissionPaths(baseDir); + await ensureDirectories(paths); + const temporary = `${paths.capability}.${process.pid}.${NodeCrypto.randomUUID()}.tmp`; + const descriptor = await NodeFS.promises.open(temporary, "wx", 0o600); + try { + await descriptor.writeFile(`${contents}\n`, "utf8"); + await descriptor.sync(); + } finally { + await descriptor.close(); + } + await NodeFS.promises.rename(temporary, paths.capability); + const directoryDescriptor = await NodeFS.promises.open(paths.root, "r"); + try { + await directoryDescriptor.sync(); + } finally { + await directoryDescriptor.close(); + } + }, + catch: (cause) => new ServiceChangeAdmissionError({ stage: "storage", cause }), + }), + ); }); const releaseAdmission = (lease: AdmissionLease) => - Effect.sync(() => { - try { - NodeFS.unlinkSync(lease.tokenPath); - } catch { - // The guard treats a missing token as drained. - } - }); + Effect.promise(() => NodeFS.promises.unlink(lease.tokenPath).catch(() => undefined)); -const leaseIsActive = (lease: AdmissionLease) => NodeFS.existsSync(lease.tokenPath); +const leaseIsActive = (lease: AdmissionLease) => + Effect.promise(() => + NodeFS.promises.access(lease.tokenPath).then( + () => true, + () => false, + ), + ); export const withAdmissionAt = Effect.fn("ServiceChangeAdmission.withAdmissionAt")(function* < A, @@ -324,7 +350,7 @@ export const withAdmissionAt = Effect.fn("ServiceChangeAdmission.withAdmissionAt effect: Effect.Effect, ): Effect.fn.Return { const activeLease = yield* Effect.serviceOption(AdmissionLeaseContext); - if (Option.isSome(activeLease) && leaseIsActive(activeLease.value)) return yield* effect; + if (Option.isSome(activeLease) && (yield* leaseIsActive(activeLease.value))) return yield* effect; return yield* Effect.scoped( Effect.gen(function* () { diff --git a/scripts/fork/host/t3-update-guard/guard b/scripts/fork/host/t3-update-guard/guard index a8436814087dc..64964049779c9 100755 --- a/scripts/fork/host/t3-update-guard/guard +++ b/scripts/fork/host/t3-update-guard/guard @@ -1249,14 +1249,14 @@ snapshot_service_identity() { [[ "$version" == "$expected" ]] || return 1 uptime=$(service_uptime) || return 1 [[ "$uptime" =~ ^[0-9]+$ ]] && (( uptime >= 60 )) || return 1 - printf '%s|%s|%s|%s' "$invocation" "$pid" "$version" "$uptime" + printf '%s|%s|%s|%s|%s' "$invocation" "$pid" "$version" "$uptime" "$listener" } # A one-off snapshot has a stricter idle gate than the long-running update timer: queued runs, # any pending request, and every active tool item hold it. The DB read is deliberately repeated # immediately before the stop; unreadable or incomplete evidence fails closed. snapshot_idle_evidence() { - local counts runs requests tools subagents background effects quiet checked_at + local counts runs requests tools subagents deliveries background effects quiet checked_at counts=$(timeout 10 sqlite3 -readonly -separator '|' "$DB" \ "select (select count(*) from orchestration_v2_projection_runs where status in ('preparing','queued','starting','running','waiting')), @@ -1268,6 +1268,9 @@ snapshot_idle_evidence() { where r.run_id = i.run_id and r.status = 'rolled_back')), (select count(*) from orchestration_v2_projection_subagents where status not in ('idle','completed','failed','cancelled','interrupted')), + (select count(*) from orchestration_v2_projection_subagents + where status in ('completed','failed','cancelled','interrupted') + and completion_delivery_state in ('pending','claimed')), (select count(*) from orchestration_v2_projection_provider_threads where not json_valid(payload_json) or (json_type(payload_json,'$.pendingBackgroundTasks') is not null @@ -1277,13 +1280,13 @@ snapshot_idle_evidence() { echo "snapshot: activity database is unreadable" >&2 return 1 } - IFS='|' read -r runs requests tools subagents background effects <<<"$counts" - [[ "$runs" =~ ^[0-9]+$ && "$requests" =~ ^[0-9]+$ && "$tools" =~ ^[0-9]+$ && "$subagents" =~ ^[0-9]+$ && "$background" =~ ^[0-9]+$ && "$effects" =~ ^[0-9]+$ ]] || { + IFS='|' read -r runs requests tools subagents deliveries background effects <<<"$counts" + [[ "$runs" =~ ^[0-9]+$ && "$requests" =~ ^[0-9]+$ && "$tools" =~ ^[0-9]+$ && "$subagents" =~ ^[0-9]+$ && "$deliveries" =~ ^[0-9]+$ && "$background" =~ ^[0-9]+$ && "$effects" =~ ^[0-9]+$ ]] || { echo "snapshot: activity census is incomplete" >&2 return 1 } - (( runs == 0 && requests == 0 && tools == 0 && subagents == 0 && background == 0 && effects == 0 )) || { - echo "snapshot: activity remains (runs=$runs pendingRequests=$requests activeItems=$tools activeSubagents=$subagents providerBackgroundTasks=$background activeEffects=$effects)" >&2 + (( runs == 0 && requests == 0 && tools == 0 && subagents == 0 && deliveries == 0 && background == 0 && effects == 0 )) || { + echo "snapshot: activity remains (runs=$runs pendingRequests=$requests activeItems=$tools activeSubagents=$subagents pendingSubagentDeliveries=$deliveries providerBackgroundTasks=$background activeEffects=$effects)" >&2 return 1 } quiet=$(quiet_seconds) || quiet="" @@ -1294,8 +1297,9 @@ snapshot_idle_evidence() { checked_at=$(date -u +%Y-%m-%dT%H:%M:%S.000Z) jq -cn --arg checkedAt "$checked_at" --argjson runs "$runs" \ --argjson requests "$requests" --argjson tools "$tools" --argjson subagents "$subagents" \ - --argjson background "$background" --argjson effects "$effects" --argjson quiet "$quiet" \ - '{checkedAt:$checkedAt,runs:$runs,pendingRequests:$requests,activeItems:$tools,activeSubagents:$subagents,providerBackgroundTasks:$background,activeEffects:$effects,quietSeconds:$quiet}' + --argjson deliveries "$deliveries" --argjson background "$background" \ + --argjson effects "$effects" --argjson quiet "$quiet" \ + '{checkedAt:$checkedAt,runs:$runs,pendingRequests:$requests,activeItems:$tools,activeSubagents:$subagents,pendingSubagentDeliveries:$deliveries,providerBackgroundTasks:$background,activeEffects:$effects,quietSeconds:$quiet}' } snapshot_manifest() { @@ -1343,7 +1347,7 @@ write_snapshot_receipt() { } snapshot_receipt_matches() { - local receipt="$1" operation="$2" point="$3" status path name sha actual version invocation pid + local receipt="$1" operation="$2" point="$3" status path name sha actual version invocation pid listener [[ -f "$receipt" && ! -L "$receipt" ]] || return 1 [[ "$(stat -c %a "$receipt" 2>/dev/null)" == 600 ]] || return 1 [[ "$(stat -c %a "${receipt%/*}" 2>/dev/null)" == 700 ]] || return 1 @@ -1357,12 +1361,15 @@ snapshot_receipt_matches() { version=$(jq -r '.stoppedGeneration.version // empty' "$receipt" 2>/dev/null) invocation=$(jq -r '.stoppedGeneration.invocationId // empty' "$receipt" 2>/dev/null) pid=$(jq -r '.stoppedGeneration.mainPid // empty' "$receipt" 2>/dev/null) - [[ -n "$version" && "$invocation" =~ ^[[:xdigit:]]{32}$ && "$pid" =~ ^[1-9][0-9]*$ ]] || return 1 + listener=$(jq -r '.stoppedGeneration.listenerPid // empty' "$receipt" 2>/dev/null) + [[ -n "$version" && "$invocation" =~ ^[[:xdigit:]]{32}$ && "$pid" =~ ^[1-9][0-9]*$ && \ + "$listener" =~ ^[1-9][0-9]*$ ]] || return 1 if [[ "$status" == complete ]]; then invocation=$(jq -r '.restart.invocationId // empty' "$receipt" 2>/dev/null) pid=$(jq -r '.restart.mainPid // empty' "$receipt" 2>/dev/null) [[ "$invocation" =~ ^[[:xdigit:]]{32}$ && "$pid" =~ ^[1-9][0-9]*$ && \ "$(jq -r '.restart.servingVersion // empty' "$receipt" 2>/dev/null)" == "$version" && \ + "$(jq -r '.restart.listenerPid // empty' "$receipt" 2>/dev/null)" =~ ^[1-9][0-9]*$ && \ -n "$(jq -r '.restart.verifiedAt // empty' "$receipt" 2>/dev/null)" ]] || return 1 fi path=$(jq -r '.snapshotPath // empty' "$receipt" 2>/dev/null) @@ -1389,12 +1396,12 @@ snapshot_receipt_matches() { } snapshot_wait_serving() { - local expected="$1" stopped_invocation="$2" deadline=$((SECONDS + HEALTH_WAIT_SECONDS)) identity invocation pid version uptime + local expected="$1" stopped_invocation="$2" deadline=$((SECONDS + HEALTH_WAIT_SECONDS)) identity invocation pid version uptime listener while (( SECONDS <= deadline )); do if [[ "$(active_version)" == "$expected" ]] && identity=$(snapshot_service_identity "$expected"); then - IFS='|' read -r invocation pid version uptime <<<"$identity" + IFS='|' read -r invocation pid version uptime listener <<<"$identity" if [[ "$invocation" != "$stopped_invocation" ]]; then - printf '%s|%s|%s|%s' "$invocation" "$pid" "$version" "$uptime" + printf '%s|%s|%s|%s|%s' "$invocation" "$pid" "$version" "$uptime" "$listener" return 0 fi fi @@ -1414,12 +1421,12 @@ snapshot_start_and_verify() { } snapshot_receipt_finalize() { - local receipt="$1" identity="$2" status="$3" why="${4:-}" invocation pid version uptime verified_at updated - IFS='|' read -r invocation pid version uptime <<<"$identity" + local receipt="$1" identity="$2" status="$3" why="${4:-}" invocation pid version uptime listener verified_at updated + IFS='|' read -r invocation pid version uptime listener <<<"$identity" verified_at=$(date -u +%Y-%m-%dT%H:%M:%S.000Z) - updated=$(jq -c --arg status "$status" --arg invocation "$invocation" --arg pid "$pid" \ + updated=$(jq -c --arg status "$status" --arg invocation "$invocation" --arg pid "$pid" --arg listener "$listener" \ --arg version "$version" --arg verifiedAt "$verified_at" --arg why "$why" \ - '.status=$status | .restart={invocationId:$invocation,mainPid:($pid|tonumber),servingVersion:$version,verifiedAt:$verifiedAt} | if $why == "" then del(.restartFailure) else .restartFailure=$why end' \ + '.status=$status | .restart={invocationId:$invocation,mainPid:($pid|tonumber),listenerPid:($listener|tonumber),servingVersion:$version,verifiedAt:$verifiedAt} | if $why == "" then del(.restartFailure) else .restartFailure=$why end' \ "$receipt") || return 1 write_snapshot_receipt "$receipt" "$updated" } @@ -1431,13 +1438,13 @@ snapshot_receipt_set_status() { } snapshot_receipt_set_idle_evidence() { - local receipt="$1" first="$2" second="$3" identity="$4" updated invocation pid version uptime - IFS='|' read -r invocation pid version uptime <<<"$identity" - updated=$(jq -c --arg invocation "$invocation" --arg pid "$pid" --arg version "$version" \ + local receipt="$1" first="$2" second="$3" identity="$4" updated invocation pid version uptime listener + IFS='|' read -r invocation pid version uptime listener <<<"$identity" + updated=$(jq -c --arg invocation "$invocation" --arg pid "$pid" --arg listener "$listener" --arg version "$version" \ --argjson first "$first" --argjson second "$second" \ --arg closedAt "$SNAPSHOT_ADMISSION_CLOSED_AT" --arg drainedAt "$SNAPSHOT_ADMISSION_DRAINED_AT" \ --arg capabilityPid "$SNAPSHOT_ADMISSION_CAPABILITY_PID" \ - '.idleVerification={first:$first,second:$second} | .admissionBarrier={protocolVersion:1,closedAt:$closedAt,drainedAt:$drainedAt,drainedAdmissions:0,capabilityListenerPid:($capabilityPid|tonumber)} | .stoppedGeneration={invocationId:$invocation,mainPid:($pid|tonumber),version:$version}' \ + '.idleVerification={first:$first,second:$second} | .admissionBarrier={protocolVersion:1,closedAt:$closedAt,drainedAt:$drainedAt,drainedAdmissions:0,capabilityListenerPid:($capabilityPid|tonumber)} | .stoppedGeneration={invocationId:$invocation,mainPid:($pid|tonumber),listenerPid:($listener|tonumber),version:$version}' \ "$receipt") || return 1 write_snapshot_receipt "$receipt" "$updated" } @@ -1459,7 +1466,8 @@ snapshot_receipt_set_manifest() { cmd_snapshot_impl() { local operation="" point="" label label_length receipt_dir receipt status version identity - local stopped_invocation stopped_pid first_activity second_activity snapshot identity_after + local stopped_invocation stopped_pid stopped_listener_pid listener_pid identity_listener_pid + local first_activity second_activity snapshot identity_after local files generation hang state restart_invocation json if [[ $# != 2 ]]; then @@ -1510,6 +1518,7 @@ cmd_snapshot_impl() { version=$(jq -r '.stoppedGeneration.version' "$receipt") stopped_invocation=$(jq -r '.stoppedGeneration.invocationId' "$receipt") stopped_pid=$(jq -r '.stoppedGeneration.mainPid' "$receipt") + stopped_listener_pid=$(jq -r '.stoppedGeneration.listenerPid' "$receipt") snapshot=$(jq -r '.snapshotPath' "$receipt") [[ "$(active_version)" == "$version" ]] && is_trusted "$version" && is_healthy "$version" || { echo "snapshot: receipt exists, but its original trusted service version is not selected" >&2 @@ -1526,16 +1535,17 @@ cmd_snapshot_impl() { echo "snapshot: managed unit, listener descendant, cgroup, health version, or generation is not verified" >&2 return 1 } - IFS='|' read -r stopped_invocation stopped_pid _ _ <<<"$identity" + IFS='|' read -r stopped_invocation stopped_pid _ _ stopped_listener_pid <<<"$identity" first_activity=$(snapshot_idle_evidence) || return 1 second_activity=$(snapshot_idle_evidence) || return 1 identity_after=$(snapshot_service_identity "$version") || { echo "snapshot: service identity changed before stop" >&2 return 1 } - IFS='|' read -r generation stopped_pid _ _ <<<"$identity_after" - [[ "$generation" == "$stopped_invocation" ]] || { - echo "snapshot: service generation changed before stop" >&2 + IFS='|' read -r generation identity_pid _ _ identity_listener_pid <<<"$identity_after" + [[ "$generation" == "$stopped_invocation" && "$identity_pid" == "$stopped_pid" && \ + "$identity_listener_pid" == "$stopped_listener_pid" ]] || { + echo "snapshot: service generation or listener changed before stop" >&2 return 1 } if hang=$(kernel_hang_signs); then @@ -1553,9 +1563,10 @@ cmd_snapshot_impl() { return 1 } json=$(jq -cn --arg operation "$operation" --arg point "$point" --arg unit "$UNIT" \ - --arg invocation "$stopped_invocation" --arg pid "$stopped_pid" --arg version "$version" \ + --arg invocation "$stopped_invocation" --arg pid "$stopped_pid" \ + --arg listener "$stopped_listener_pid" --arg version "$version" \ --arg path "$snapshot" --argjson first "$first_activity" --argjson second "$second_activity" \ - '{schemaVersion:1,operationId:$operation,snapshotPoint:$point,unit:$unit,status:"prepared",snapshotPath:$path,files:[],idleVerification:{first:$first,second:$second},stoppedGeneration:{invocationId:$invocation,mainPid:($pid|tonumber),version:$version}}') || { + '{schemaVersion:1,operationId:$operation,snapshotPoint:$point,unit:$unit,status:"prepared",snapshotPath:$path,files:[],idleVerification:{first:$first,second:$second},stoppedGeneration:{invocationId:$invocation,mainPid:($pid|tonumber),listenerPid:($listener|tonumber),version:$version}}') || { rmdir "$snapshot" 2>/dev/null || true return 1 } @@ -1576,14 +1587,14 @@ cmd_snapshot_impl() { echo "snapshot: prepared service identity is no longer verified" >&2 return 1 } - local listener_pid - listener_pid=$(service_listener_pid) || { - echo "snapshot: prepared listener PID is no longer verified" >&2 + IFS='|' read -r generation _ _ _ listener_pid <<<"$identity" + [[ "$generation" == "$stopped_invocation" && "$listener_pid" == "$stopped_listener_pid" ]] || { + echo "snapshot: prepared listener identity changed; no stop requested" >&2 return 1 } SNAPSHOT_ADMISSION_OPERATION="$operation" snapshot_admission_close "$operation" "$point" "$listener_pid" || return 1 - IFS='|' read -r generation _ _ _ <<<"$identity" + IFS='|' read -r generation _ _ _ identity_listener_pid <<<"$identity" [[ "$generation" == "$stopped_invocation" ]] || { echo "snapshot: prepared service generation changed; no stop requested" >&2 return 1 @@ -1594,9 +1605,10 @@ cmd_snapshot_impl() { echo "snapshot: service identity changed immediately before the stop request" >&2 return 1 } - IFS='|' read -r generation stopped_pid _ _ <<<"$identity_after" - [[ "$generation" == "$stopped_invocation" ]] || { - echo "snapshot: service generation changed immediately before the stop request" >&2 + IFS='|' read -r generation identity_pid _ _ identity_listener_pid <<<"$identity_after" + [[ "$generation" == "$stopped_invocation" && "$identity_pid" == "$stopped_pid" && \ + "$identity_listener_pid" == "$listener_pid" && "$listener_pid" == "$stopped_listener_pid" ]] || { + echo "snapshot: service generation or listener changed immediately before the stop request" >&2 return 1 } if hang=$(kernel_hang_signs); then diff --git a/scripts/fork/host/t3-update-guard/test-guard.sh b/scripts/fork/host/t3-update-guard/test-guard.sh index dd54fe84ce52c..00e2e49a10af8 100755 --- a/scripts/fork/host/t3-update-guard/test-guard.sh +++ b/scripts/fork/host/t3-update-guard/test-guard.sh @@ -617,7 +617,7 @@ pass 'all systemctl calls have a bounded timeout' create table orchestration_v2_projection_runs (run_id text, thread_id text, status text, requested_at text, completed_at text, payload_json text); create table orchestration_v2_projection_runtime_requests (runtime_request_id text, status text, resolved_at text); create table orchestration_v2_projection_turn_items (turn_item_id text, thread_id text, run_id text, type text, status text, updated_at text); - create table orchestration_v2_projection_subagents (subagent_id text, status text); + create table orchestration_v2_projection_subagents (subagent_id text, status text, completion_delivery_state text); create table orchestration_v2_projection_provider_threads (provider_thread_id text, payload_json text); create table orchestration_v2_effect_outbox (effect_id text, status text);" sim_version=0.1.13-preview.20261127.1 @@ -799,6 +799,34 @@ for path in sys.argv[1:]: sqlite3 "$DB" "insert into orchestration_v2_projection_runs values ('late','thread','preparing','2026-11-27T00:00:00.000Z',null,'{}');" touch "$root/inserted-during-census" fi + if [[ -e "$root/replace-listener-after-final-census" && -f "$SNAPSHOT_ADMISSION_FENCE" ]]; then + rm -f "$root/replace-listener-after-final-census" + local previous_listener new_listener + previous_listener=$(cat "$sim_listener_file") + printf 'stop\n' >"$sim_command_fifo" + for ((i=0; i<50; i++)); do + [[ ! -s "$sim_listener_file" ]] && break + sleep 0.02 + done + printf 'start\n' >"$sim_command_fifo" + for ((i=0; i<50; i++)); do + new_listener=$(cat "$sim_listener_file") + if [[ -n "$new_listener" && "$new_listener" != "$previous_listener" ]] && \ + [[ "$(service_listener_pid 2>/dev/null)" == "$new_listener" ]]; then + break + fi + sleep 0.02 + done + [[ -n "$new_listener" && "$new_listener" != "$previous_listener" ]] || fail 'fixture did not replace the listener between final census and stop' + printf '{"protocolVersion":1,"pid":%s,"startedAt":"2026-11-27T00:00:02.000Z"}\n' \ + "$new_listener" >"$SNAPSHOT_ADMISSION_ROOT/capability.json" + chmod 600 "$SNAPSHOT_ADMISSION_ROOT/capability.json" + for ((i=0; i<50; i++)); do + snapshot_service_identity "$sim_version" >/dev/null 2>&1 && break + sleep 0.02 + done + snapshot_service_identity "$sim_version" >/dev/null || fail 'replacement child listener was not a valid same-generation identity' + fi echo "$QUIET_VALUE" } HEALTH_WAIT_SECONDS=0 @@ -835,10 +863,16 @@ for path in sys.argv[1:]: grep -q 'activeEffects=1' "$root/snapshot-reject.log" || fail 'snapshot ignored a pending effect outbox job' exec 9>&- sqlite3 "$DB" "delete from orchestration_v2_projection_runs; delete from orchestration_v2_projection_turn_items; - insert into orchestration_v2_projection_subagents values ('provider-subagent','running'); - insert into orchestration_v2_projection_subagents values ('app-owned-subagent','pending');" + insert into orchestration_v2_projection_subagents values ('provider-subagent','running',null); + insert into orchestration_v2_projection_subagents values ('app-owned-subagent','pending',null);" if cmd_snapshot snapshot-op before-stock-switch >/dev/null 2>&1; then fail 'snapshot stopped an active provider subagent'; fi exec 9>&- + sqlite3 "$DB" "delete from orchestration_v2_projection_subagents; + insert into orchestration_v2_projection_subagents values ('pending-completion','completed','pending'); + insert into orchestration_v2_projection_subagents values ('claimed-completion','cancelled','claimed');" + if cmd_snapshot snapshot-op before-stock-switch >"$root/snapshot-reject.log" 2>&1; then fail 'snapshot stopped with undelivered terminal subagent completions'; fi + grep -q 'pendingSubagentDeliveries=2' "$root/snapshot-reject.log" || fail 'snapshot census omitted pending or claimed subagent completions' + exec 9>&- sqlite3 "$DB" "delete from orchestration_v2_projection_subagents; insert into orchestration_v2_projection_provider_threads values ('provider-thread','{\"pendingBackgroundTasks\":[{\"taskId\":\"task-1\"}]}');" if cmd_snapshot snapshot-op before-stock-switch >/dev/null 2>&1; then fail 'snapshot stopped a pending provider background task'; fi exec 9>&- @@ -879,6 +913,21 @@ for path in sys.argv[1:]: [[ -z "$(grep '^stop ' "$root/snapshot-svc" 2>/dev/null || true)" ]] || fail 'snapshot stopped before its prepared receipt was durable' [[ ! -e "$GUARD_STATE/snapshot-receipts/snapshot-op.json" ]] || fail 'failed prepared receipt was published' + touch "$root/replace-listener-after-final-census" + if cmd_snapshot snapshot-listener-race before-stock-switch >"$root/listener-race.out" 2>&1; then + fail 'snapshot stopped after the server child listener changed during the final fence' + fi + [[ ! -e "$SNAPSHOT_ADMISSION_FENCE" ]] || { + cat "$root/listener-race.out" >&2 + fail 'snapshot did not reopen admission after verifying the replacement listener' + } + grep -q 'service generation or listener changed immediately before the stop request' "$root/listener-race.out" || \ + fail 'snapshot did not identify the listener-generation change' + [[ -z "$(grep '^stop ' "$root/snapshot-svc" 2>/dev/null || true)" ]] || fail 'snapshot stopped after the listener changed' + [[ "$(jq -r '.status' "$GUARD_STATE/snapshot-receipts/snapshot-listener-race.json")" == prepared ]] || \ + fail 'listener change did not leave the durable prepared receipt for safe retry' + exec 9>&- + # An admitted command owns a token until its commit finishes. The guard closes the fence, # waits for that token, then takes the final census and catches the committed preparing run. admission_release="$root/admission-release" @@ -896,7 +945,10 @@ for path in sys.argv[1:]: [[ -f "$SNAPSHOT_ADMISSION_FENCE" ]] && break sleep 0.02 done - [[ -f "$SNAPSHOT_ADMISSION_FENCE" ]] || fail 'snapshot did not close the admission fence before its final census' + [[ -f "$SNAPSHOT_ADMISSION_FENCE" ]] || { + cat "$root/snapshot-fenced-census.out" >&2 + fail 'snapshot did not close the admission fence before its final census' + } [[ -z "$(grep '^stop ' "$root/snapshot-svc" 2>/dev/null || true)" ]] || fail 'snapshot stopped while an admitted command was draining' sqlite3 "$DB" "insert into orchestration_v2_projection_runs values ('fenced','thread','preparing','2026-11-27T00:00:00.000Z',null,'{}');" touch "$admission_release" @@ -913,7 +965,9 @@ for path in sys.argv[1:]: [[ "$(jq -r '.status' <<<"$out")" == complete ]] || fail 'snapshot receipt did not complete' [[ "$(jq -r '.stoppedGeneration.version' "$receipt")" == "$sim_version" ]] || fail 'receipt lost stopped version' [[ "$(jq -r '.stoppedGeneration.invocationId' "$receipt")" == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ]] || fail 'receipt lost stopped invocation ID' + [[ "$(jq -r '.stoppedGeneration.listenerPid' "$receipt")" =~ ^[1-9][0-9]*$ ]] || fail 'receipt lost stopped listener PID' [[ "$(jq -r '.restart.invocationId' "$receipt")" == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb ]] || fail 'receipt lost restarted invocation ID' + [[ "$(jq -r '.restart.listenerPid' "$receipt")" =~ ^[1-9][0-9]*$ ]] || fail 'receipt lost restarted listener PID' [[ "$(jq -r '.files | map(.name) | sort | join(",")' "$receipt")" == 'statev2.sqlite,statev2.sqlite-shm,statev2.sqlite-wal' ]] || fail 'receipt omitted a SQLite file or sidecar' [[ "$(sha256sum "$(jq -r '.snapshotPath' "$receipt")/statev2.sqlite" | cut -d' ' -f1)" == "$(sha256sum "$DB" | cut -d' ' -f1)" ]] || fail 'snapshot main database differs from the stopped source' [[ "$(stat -c %a "$receipt")" == 600 && "$(stat -c %a "$(jq -r '.snapshotPath' "$receipt")")" == 700 ]] || fail 'snapshot receipt or files are not under owner-only directories' From ee392fa3879a28482019be4dbec6f2b44f3f5c61 Mon Sep 17 00:00:00 2001 From: Chris OHearn Date: Fri, 27 Nov 2026 08:26:50 -0700 Subject: [PATCH 6/7] fix(server): keep admission active through workspace setup --- .../DelegatedChildTerminalRetry.test.ts | 15 ++ .../ThreadFork.execution.test.ts | 6 + .../ThreadLaunchService.test.ts | 58 ++++++- .../orchestration-v2/ThreadLaunchService.ts | 28 ++-- .../testkit/ProviderReplayHarness.ts | 12 +- .../server/src/serviceChangeAdmission.test.ts | 100 +++++++++++- apps/server/src/serviceChangeAdmission.ts | 149 ++++++++++++++---- 7 files changed, 324 insertions(+), 44 deletions(-) diff --git a/apps/server/src/orchestration-v2/DelegatedChildTerminalRetry.test.ts b/apps/server/src/orchestration-v2/DelegatedChildTerminalRetry.test.ts index 7658acaa9f955..0b166bff74db8 100644 --- a/apps/server/src/orchestration-v2/DelegatedChildTerminalRetry.test.ts +++ b/apps/server/src/orchestration-v2/DelegatedChildTerminalRetry.test.ts @@ -14,6 +14,7 @@ import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; import { checkpointWorkspace } from "@t3tools/provider-testing/replayWorkspace"; import * as DateTime from "effect/DateTime"; +import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; import * as Queue from "effect/Queue"; @@ -52,6 +53,7 @@ const runDelegation = (input: { Effect.gen(function* () { const cwd = yield* checkpointWorkspace(input.name); let armed = false; + const failedRead = Deferred.makeUnsafe(); const turns: Array<{ readonly turn: ProviderAdapter.ProviderAdapterV2TurnInput; readonly events: Queue.Queue; @@ -153,6 +155,7 @@ const runDelegation = (input: { (yield* input.failRead({ store, threadId, fields, filter })) ) { armed = false; + yield* Deferred.succeed(failedRead, undefined); return yield* new ProjectionStore.ProjectionStoreReadError({ threadId }); } return yield* store.getThreadRecords(threadId, fields, filter); @@ -265,6 +268,11 @@ const runDelegation = (input: { } armed = true; + const parentWake = input.parentEndsFirst + ? yield* watch( + (event) => event.type === "message.updated" && event.threadId === parentThreadId, + ) + : undefined; const childFailed = yield* watch( (event) => event.type === "run.updated" && @@ -276,12 +284,19 @@ const runDelegation = (input: { yield* TestClock.adjust("1 second"); } yield* Fiber.join(childFailed); + if (input.parentEndsFirst && input.failRead !== undefined) { + yield* Deferred.await(failedRead); + } if (!input.parentEndsFirst) yield* endParentTurn; for (let attempt = 0; attempt < 5; attempt++) { yield* worker.drain(); yield* TestClock.adjust("30 seconds"); } + if (parentWake !== undefined) { + yield* Fiber.join(parentWake); + yield* worker.drain(); + } assert.isFalse(armed, "the injected read failed once"); const parent = yield* orchestrator.getThreadProjection(parentThreadId); diff --git a/apps/server/src/orchestration-v2/ThreadFork.execution.test.ts b/apps/server/src/orchestration-v2/ThreadFork.execution.test.ts index 457a98487c69d..b8ce80cd9ad6b 100644 --- a/apps/server/src/orchestration-v2/ThreadFork.execution.test.ts +++ b/apps/server/src/orchestration-v2/ThreadFork.execution.test.ts @@ -444,6 +444,7 @@ it.effect.each([ "a $execution fork's first /compact is rejected only when no history reaches it: $rejected", ({ execution, rejected }) => { const opened: Array = []; + const openedSession = Deferred.makeUnsafe(); const adapter = (driverName: "claudeAgent" | "codex") => { const driver = ProviderDriverKind.make(driverName); const instanceId = ProviderInstanceId.make(driverName); @@ -457,6 +458,7 @@ it.effect.each([ planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }), openSession: (input) => Effect.sync(() => opened.push(instanceId)).pipe( + Effect.tap(() => Deferred.succeed(openedSession, undefined)), Effect.andThen( new ProviderAdapter.ProviderAdapterOpenSessionError({ driver, @@ -623,6 +625,10 @@ it.effect.each([ creationSource: "web", }); yield* worker.drain(); + if (!rejected) { + yield* Deferred.await(openedSession); + yield* worker.drain(); + } const projection = yield* orchestrator.getThreadProjection(targetThreadId); if (execution === "portable_context") { diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts index 0259396a6ce6d..5bd77a3cd12ca 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts @@ -3,6 +3,10 @@ import * as Scheduler from "../scheduling/Scheduler.ts"; import * as WorktreeSetupTracker from "../project/WorktreeSetupTracker.ts"; import * as ProjectCloneTracker from "../project/ProjectCloneTracker.ts"; import * as TerminalManager from "../terminal/Manager.ts"; +// @effect-diagnostics-next-line nodeBuiltinImport:off -- The test inspects the guard-compatible admission token directory. +import * as NodeFS from "node:fs"; +// @effect-diagnostics-next-line nodeBuiltinImport:off -- The test locates the guard-compatible admission token directory. +import * as NodePath from "node:path"; import * as CheckpointStore from "../checkpointing/CheckpointStore.ts"; import * as NodeServices from "@effect/platform-node/NodeServices"; import * as FileSystem from "effect/FileSystem"; @@ -165,10 +169,18 @@ interface HarnessOptions { function makeHarness(options: HarnessOptions = {}) { const layerDatabase = SqlitePersistence.layerMemory; const layerRegistry = ProviderAdapterRegistry.layerFromAdapters(options.adapters ?? [adapter]); + const layerServerConfig = Layer.effect( + ServerConfig.ServerConfig, + ProviderReplayHarness.makeReplayServerConfig("thread-launch").pipe(Effect.orDie), + ).pipe(Layer.provide(NodeServices.layer)); const layerOrchestrator = ProviderReplayHarness.layerWithRegistry( { name: "thread-launch" }, layerRegistry, - { databaseLayer: layerDatabase, runEffectWorker: false }, + { + databaseLayer: layerDatabase, + runEffectWorker: false, + serverConfigLayer: layerServerConfig, + }, ); const layerServerSettings = ServerSettings.layerTest(options.serverSettings); const layerReceipts = CommandReceiptStore.layer.pipe(Layer.provide(layerDatabase)); @@ -293,6 +305,7 @@ function makeHarness(options: HarnessOptions = {}) { layerLaunchThreads, layerReceipts, layerOrchestrator, + layerServerConfig, ProjectionStore.layer.pipe(Layer.provide(layerDatabase)), NodeServices.layer, IdAllocator.layer, @@ -342,6 +355,7 @@ function makeHarness(options: HarnessOptions = {}) { return { layer: Layer.mergeAll( layerLaunch, + layerServerConfig, layerRegistry, layerThreadManagement, layerTitleRegeneration, @@ -480,6 +494,48 @@ it.effect.each( }, ); +it.effect("keeps admission active through a runless workspace preparation", () => { + const worktreeStarted = Deferred.makeUnsafe(); + const releaseWorktree = Deferred.makeUnsafe(); + const harness = makeHarness({ + createWorktree: (input) => + Deferred.succeed(worktreeStarted, undefined).pipe( + Effect.andThen(Deferred.await(releaseWorktree)), + Effect.as({ + worktree: { + path: "/repo-worktrees/runless-admission", + refName: input.newRefName, + headSha: "abc", + }, + } as never), + ), + }); + + return Effect.gen(function* () { + const config = yield* ServerConfig.ServerConfig; + const launches = yield* ThreadLaunch.ThreadLaunchService; + const setups = yield* WorktreeSetupTracker.WorktreeSetupTracker; + const launched = yield* launches.launch( + launchInput({ + command: "command:runless-admission", + thread: "thread:runless-admission", + workspace: worktreeStrategy, + }), + ); + yield* Deferred.await(worktreeStarted); + + const active = NodePath.join(config.baseDir, "runtime", "service-change-admission", "active"); + assert.lengthOf(NodeFS.readdirSync(active), 1); + + yield* Deferred.succeed(releaseWorktree, undefined); + yield* setups.stream(launched.threadId).pipe( + Stream.filter((snapshot) => snapshot?.phase === "done"), + Stream.runHead, + ); + assert.isEmpty(NodeFS.readdirSync(active)); + }).pipe(Effect.provide(harness.layer)); +}); + it.effect( "returns no dispatched thread when sending an automation to a missing thread fails", () => { diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.ts index eb427c544c528..760fe4aeb302e 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.ts @@ -1,5 +1,7 @@ import * as WorktreeSetupTracker from "../project/WorktreeSetupTracker.ts"; import * as ProjectCloneTracker from "../project/ProjectCloneTracker.ts"; +import * as ServerConfig from "../config.ts"; +import * as ServiceChangeAdmission from "../serviceChangeAdmission.ts"; import * as TerminalManager from "../terminal/Manager.ts"; import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; import { @@ -290,6 +292,7 @@ function failureDetail(error: unknown): string { } const make = Effect.gen(function* () { + const config = yield* ServerConfig.ServerConfig; const projects = yield* ProjectService.ProjectService; const setupTracker = yield* WorktreeSetupTracker.WorktreeSetupTracker; const cloneTracker = yield* ProjectCloneTracker.ProjectCloneTracker; @@ -1456,19 +1459,22 @@ const make = Effect.gen(function* () { ); yield* Effect.raceFirst(prepare, interruption); }); - yield* preparation.pipe( - Effect.onError((cause) => - failPreparedRun( - input, - threadId, - runId, - Cause.hasInterruptsOnly(cause) ? "Worktree setup cancelled." : Cause.squash(cause), + yield* ServiceChangeAdmission.forkInWithAdmissionAt( + config.baseDir, + preparation.pipe( + Effect.onError((cause) => + failPreparedRun( + input, + threadId, + runId, + Cause.hasInterruptsOnly(cause) ? "Worktree setup cancelled." : Cause.squash(cause), + ), ), + Effect.ignoreCause, + Effect.ensuring(releasePreparation(input.commandId)), ), - Effect.ignoreCause, - Effect.ensuring(releasePreparation(input.commandId)), - Effect.forkIn(preparationScope), - ); + preparationScope, + ).pipe(Effect.mapError(mapError(input, "update-thread", threadId))); }); const launch: ThreadLaunchService["Service"]["launch"] = Effect.fn("ThreadLaunchService.launch")( diff --git a/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts b/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts index d469a059eae87..190045cc1f5c5 100644 --- a/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts +++ b/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts @@ -305,6 +305,8 @@ export function layerWithRegistry( readonly settings?: Parameters[0]; /** Replaces `settings` with a layer the test also provides, so it can change settings live. */ readonly settingsLayer?: Layer.Layer; + /** Shares the server's runtime paths with services layered around the replay harness. */ + readonly serverConfigLayer?: Layer.Layer; /** The instances the ingestor reads snapshots from, such as an endpoint behind a hub. */ readonly providerInstances?: Partial< ProviderInstanceRegistry.ProviderInstanceRegistry["Service"] @@ -320,10 +322,12 @@ export function layerWithRegistry( | ThreadCommandExecutor.ThreadCommandExecutor, Error | MigrationError | PlatformError.PlatformError | SqlError > { - const layerServerConfig = Layer.effect( - ServerConfig.ServerConfig, - makeReplayServerConfig(scenario.name).pipe(Effect.orDie), - ).pipe(Layer.provide(NodeServices.layer)); + const layerServerConfig = + options.serverConfigLayer ?? + Layer.effect( + ServerConfig.ServerConfig, + makeReplayServerConfig(scenario.name).pipe(Effect.orDie), + ).pipe(Layer.provide(NodeServices.layer)); // A thread without a worktree would otherwise fall back to process.cwd(), so checkpoints // would run git against the checkout running the tests and race its other users. const layerScenarioWorkspacePolicy = Layer.effect( diff --git a/apps/server/src/serviceChangeAdmission.test.ts b/apps/server/src/serviceChangeAdmission.test.ts index cb49d074f357f..b5adbcc38d993 100644 --- a/apps/server/src/serviceChangeAdmission.test.ts +++ b/apps/server/src/serviceChangeAdmission.test.ts @@ -1,4 +1,4 @@ -import { assert, it } from "@effect/vitest"; +import { assert, it, vi } from "@effect/vitest"; // @effect-diagnostics-next-line nodeBuiltinImport:off -- The test verifies the guard-compatible host file protocol. import * as NodeFS from "node:fs"; import * as NodeOS from "node:os"; @@ -10,6 +10,7 @@ import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; +import * as Scope from "effect/Scope"; import * as ServerConfig from "./config.ts"; import * as ServiceChangeAdmission from "./serviceChangeAdmission.ts"; @@ -100,3 +101,100 @@ it.effect("serializes concurrent local admission file creation", () => { Effect.ensuring(Effect.sync(() => NodeFS.rmSync(baseDir, { recursive: true, force: true }))), ); }); + +it.effect("keeps admission active until forked preparation exits", () => { + const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-snapshot-admission-")); + const active = NodePath.join(baseDir, "runtime", "service-change-admission", "active"); + + return Effect.gen(function* () { + yield* ServiceChangeAdmission.initialize(baseDir); + const scope = yield* Scope.make("sequential"); + yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void)); + const entered = yield* Deferred.make(); + const release = yield* Deferred.make(); + const child = yield* ServiceChangeAdmission.withAdmissionAt( + baseDir, + ServiceChangeAdmission.forkInWithAdmissionAt( + baseDir, + Effect.gen(function* () { + yield* Deferred.succeed(entered, undefined); + yield* Deferred.await(release); + }), + scope, + ), + ); + + yield* Deferred.await(entered); + assert.lengthOf(NodeFS.readdirSync(active), 1); + yield* Deferred.succeed(release, undefined); + yield* Fiber.join(child); + assert.isEmpty(NodeFS.readdirSync(active)); + }).pipe( + Effect.ensuring(Effect.sync(() => NodeFS.rmSync(baseDir, { recursive: true, force: true }))), + ); +}); + +it.effect("retries pending admission-token cleanup on the next admission", () => { + const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-snapshot-admission-")); + const active = NodePath.join(baseDir, "runtime", "service-change-admission", "active"); + const originalUnlink = NodeFS.promises.unlink.bind(NodeFS.promises); + let tokenUnlinksToFail = 2; + vi.spyOn(NodeFS.promises, "unlink").mockImplementation((filePath) => { + if (NodePath.dirname(String(filePath)) === active && tokenUnlinksToFail > 0) { + tokenUnlinksToFail -= 1; + return Promise.reject(Object.assign(new Error("transient unlink failure"), { code: "EIO" })); + } + return originalUnlink(filePath); + }); + + return Effect.gen(function* () { + yield* ServiceChangeAdmission.initialize(baseDir); + const first = yield* Effect.exit(ServiceChangeAdmission.withAdmissionAt(baseDir, Effect.void)); + assert.isTrue(Exit.isFailure(first)); + assert.lengthOf(NodeFS.readdirSync(active), 1); + + yield* ServiceChangeAdmission.withAdmissionAt(baseDir, Effect.void); + assert.isEmpty(NodeFS.readdirSync(active)); + }).pipe( + Effect.ensuring( + Effect.sync(() => { + vi.restoreAllMocks(); + NodeFS.rmSync(baseDir, { recursive: true, force: true }); + }), + ), + ); +}); + +it.effect("reports mutex cleanup failure and reclaims the stale local mutex", () => { + const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-snapshot-admission-")); + const mutex = NodePath.join(baseDir, "runtime", "service-change-admission", "mutex"); + const mutexOwner = NodePath.join(mutex, "owner"); + const originalUnlink = NodeFS.promises.unlink.bind(NodeFS.promises); + let ownerUnlinksToFail = 2; + vi.spyOn(NodeFS.promises, "unlink").mockImplementation((filePath) => { + if (String(filePath) === mutexOwner && ownerUnlinksToFail > 0) { + ownerUnlinksToFail -= 1; + return Promise.reject( + Object.assign(new Error("transient mutex cleanup failure"), { code: "EIO" }), + ); + } + return originalUnlink(filePath); + }); + + return Effect.gen(function* () { + yield* ServiceChangeAdmission.initialize(baseDir); + const first = yield* Effect.exit(ServiceChangeAdmission.withAdmissionAt(baseDir, Effect.void)); + assert.isTrue(Exit.isFailure(first)); + assert.isTrue(NodeFS.existsSync(mutexOwner)); + + yield* ServiceChangeAdmission.withAdmissionAt(baseDir, Effect.void); + assert.isFalse(NodeFS.existsSync(mutex)); + }).pipe( + Effect.ensuring( + Effect.sync(() => { + vi.restoreAllMocks(); + NodeFS.rmSync(baseDir, { recursive: true, force: true }); + }), + ), + ); +}); diff --git a/apps/server/src/serviceChangeAdmission.ts b/apps/server/src/serviceChangeAdmission.ts index 42203068da2cc..2e9f1af35cb46 100644 --- a/apps/server/src/serviceChangeAdmission.ts +++ b/apps/server/src/serviceChangeAdmission.ts @@ -8,9 +8,11 @@ import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import * as Semaphore from "effect/Semaphore"; +import * as Scope from "effect/Scope"; import * as ServerConfig from "./config.ts"; const PROTOCOL_VERSION = 1; @@ -18,6 +20,7 @@ const MUTEX_WAIT_MS = 5_000; interface AdmissionLease { readonly tokenPath: string; + references: number; } interface AdmissionPaths { @@ -30,6 +33,7 @@ interface AdmissionPaths { const admissionPathsByBaseDir = new Map(); const admissionMutexesByBaseDir = new Map(); +const pendingAdmissionTokenCleanup = new Set(); const admissionMutex = (baseDir: string) => { const cached = admissionMutexesByBaseDir.get(baseDir); @@ -98,6 +102,37 @@ const pidIsAlive = (pid: number) => { } }; +const errorHasCode = (cause: unknown, code: string) => + typeof cause === "object" && cause !== null && "code" in cause && cause.code === code; + +const unlinkWithRetry = async (filePath: string) => { + let lastCause: unknown; + for (let attempt = 0; attempt < 2; attempt++) { + try { + await NodeFS.promises.unlink(filePath); + return; + } catch (cause) { + if (errorHasCode(cause, "ENOENT")) return; + lastCause = cause; + } + } + throw lastCause; +}; + +const rmdirWithRetry = async (directory: string) => { + let lastCause: unknown; + for (let attempt = 0; attempt < 2; attempt++) { + try { + await NodeFS.promises.rmdir(directory); + return; + } catch (cause) { + if (errorHasCode(cause, "ENOENT")) return; + lastCause = cause; + } + } + throw lastCause; +}; + const ensureDirectories = async (paths: AdmissionPaths) => { await NodeFS.promises.mkdir(paths.root, { recursive: true, mode: 0o700 }); await NodeFS.promises.mkdir(paths.active, { recursive: true, mode: 0o700 }); @@ -111,26 +146,18 @@ const ensureDirectories = async (paths: AdmissionPaths) => { }; const releaseMutex = async (paths: AdmissionPaths) => { - try { - await NodeFS.promises.unlink(NodePath.join(paths.mutex, "owner")); - } catch { - // A missing owner file means an interrupted or already completed cleanup. - } - try { - await NodeFS.promises.rmdir(paths.mutex); - } catch { - // Leave unexpected contents in place; the next caller fails closed. - } + await unlinkWithRetry(NodePath.join(paths.mutex, "owner")); + await rmdirWithRetry(paths.mutex); }; -const removeStaleMutex = async (paths: AdmissionPaths, now: number) => { +const removeStaleMutex = async (paths: AdmissionPaths, now: number): Promise => { const ownerPath = NodePath.join(paths.mutex, "owner"); let stat: Awaited>; try { stat = await NodeFS.promises.lstat(paths.mutex); } catch (cause) { if (typeof cause === "object" && cause !== null && "code" in cause && cause.code === "ENOENT") { - return; + return true; } throw cause; } @@ -147,15 +174,18 @@ const removeStaleMutex = async (paths: AdmissionPaths, now: number) => { ownerPid = Number(ownerText); if (!Number.isSafeInteger(ownerPid)) throw new Error("Admission mutex owner PID is invalid."); } catch (cause) { - if ( - !(typeof cause === "object" && cause !== null && "code" in cause && cause.code === "ENOENT") - ) { - throw cause; - } - if (now - stat.mtimeMs <= 5_000) return; + if (!errorHasCode(cause, "ENOENT")) throw cause; + if (now - stat.mtimeMs <= 5_000) return false; + } + // This caller holds the process-local semaphore, so no other local operation + // can still own a same-process mutex left behind by a failed finalizer. + if (ownerPid === process.pid) { + await releaseMutex(paths); + return true; } - if (ownerPid !== undefined && pidIsAlive(ownerPid)) return; + if (ownerPid !== undefined && pidIsAlive(ownerPid)) return false; await releaseMutex(paths); + return true; }; type MutexAttempt = @@ -205,14 +235,14 @@ const acquireMutex = Effect.fn("ServiceChangeAdmission.acquireMutex")(function* } const now = yield* Clock.currentTimeMillis; - yield* Effect.tryPromise({ + const staleMutexRemoved = yield* Effect.tryPromise({ try: () => removeStaleMutex(paths, now), catch: (cause) => new ServiceChangeAdmissionError({ stage: "mutex", cause }), }); if ((yield* Clock.currentTimeMillis) >= deadline) { return yield* new ServiceChangeAdmissionError({ stage: "mutex" }); } - yield* Effect.sleep("10 millis"); + if (!staleMutexRemoved) yield* Effect.sleep("10 millis"); } }); @@ -272,13 +302,19 @@ const removeStaleFence = async (paths: AdmissionPaths) => { const createAdmission = (baseDir: string) => { const paths = admissionPaths(baseDir); - return Semaphore.withPermit(admissionMutex(baseDir))( + let createdLease: AdmissionLease | undefined; + const acquired = Semaphore.withPermit(admissionMutex(baseDir))( Effect.tryPromise({ try: () => ensureDirectories(paths), catch: (cause) => new ServiceChangeAdmissionError({ stage: "storage", cause }), }).pipe( Effect.andThen( withMutex(paths, async () => { + for (const tokenPath of pendingAdmissionTokenCleanup) { + if (NodePath.dirname(tokenPath) !== paths.active) continue; + await unlinkWithRetry(tokenPath); + pendingAdmissionTokenCleanup.delete(tokenPath); + } await removeStaleFence(paths); const tokenPath = NodePath.join( paths.active, @@ -288,13 +324,35 @@ const createAdmission = (baseDir: string) => { mode: 0o600, flag: "wx", }); - return { tokenPath } satisfies AdmissionLease; + createdLease = { tokenPath, references: 1 } satisfies AdmissionLease; + return createdLease; }), ), ), ); + return acquired.pipe( + Effect.onExit((exit) => + Exit.isFailure(exit) && createdLease !== undefined + ? releaseAdmission(createdLease) + : Effect.void, + ), + ); }; +const releaseAdmission = (lease: AdmissionLease) => + Effect.promise(async () => { + if (lease.references <= 0) throw new Error("Admission lease released more than once."); + lease.references -= 1; + if (lease.references > 0) return; + try { + await unlinkWithRetry(lease.tokenPath); + pendingAdmissionTokenCleanup.delete(lease.tokenPath); + } catch (cause) { + pendingAdmissionTokenCleanup.add(lease.tokenPath); + throw cause; + } + }); + export const initialize = Effect.fn("ServiceChangeAdmission.initialize")(function* ( baseDir: string, ): Effect.fn.Return { @@ -330,9 +388,6 @@ export const initialize = Effect.fn("ServiceChangeAdmission.initialize")(functio ); }); -const releaseAdmission = (lease: AdmissionLease) => - Effect.promise(() => NodeFS.promises.unlink(lease.tokenPath).catch(() => undefined)); - const leaseIsActive = (lease: AdmissionLease) => Effect.promise(() => NodeFS.promises.access(lease.tokenPath).then( @@ -350,7 +405,14 @@ export const withAdmissionAt = Effect.fn("ServiceChangeAdmission.withAdmissionAt effect: Effect.Effect, ): Effect.fn.Return { const activeLease = yield* Effect.serviceOption(AdmissionLeaseContext); - if (Option.isSome(activeLease) && (yield* leaseIsActive(activeLease.value))) return yield* effect; + if ( + Option.isSome(activeLease) && + NodePath.dirname(activeLease.value.tokenPath) === admissionPaths(baseDir).active && + activeLease.value.references > 0 && + (yield* leaseIsActive(activeLease.value)) + ) { + return yield* effect; + } return yield* Effect.scoped( Effect.gen(function* () { @@ -360,6 +422,39 @@ export const withAdmissionAt = Effect.fn("ServiceChangeAdmission.withAdmissionAt ); }); +/** + * Fork background work while retaining the command's admission lease until that + * work exits. The child receives the same lease context, so nested dispatches + * reuse it and a snapshot census cannot pass between acceptance and preparation. + */ +export const forkInWithAdmissionAt = Effect.fn("ServiceChangeAdmission.forkInWithAdmissionAt")( + function* (baseDir: string, effect: Effect.Effect, scope: Scope.Scope) { + return yield* Effect.uninterruptibleMask((restore) => + Effect.gen(function* () { + const inheritedLease = yield* Effect.serviceOption(AdmissionLeaseContext); + const leaseIsReusable = + Option.isSome(inheritedLease) && + NodePath.dirname(inheritedLease.value.tokenPath) === admissionPaths(baseDir).active && + inheritedLease.value.references > 0 && + (yield* leaseIsActive(inheritedLease.value)); + const lease = leaseIsReusable + ? inheritedLease.value + : yield* restore(createAdmission(baseDir)); + if (leaseIsReusable) lease.references += 1; + + const child = Effect.provideService( + effect.pipe(Effect.ensuring(releaseAdmission(lease))), + AdmissionLeaseContext, + lease, + ).pipe(Effect.forkIn(scope)); + return yield* restore(child).pipe( + Effect.onExit((exit) => (Exit.isFailure(exit) ? releaseAdmission(lease) : Effect.void)), + ); + }), + ); + }, +); + export const withAdmission = Effect.fn("ServiceChangeAdmission.withAdmission")(function* ( effect: Effect.Effect, ) { From f41b18d064c096beeeab14652aaf8b11631b1652 Mon Sep 17 00:00:00 2001 From: Chris OHearn Date: Fri, 27 Nov 2026 09:07:44 -0700 Subject: [PATCH 7/7] fix(fork): recover stale snapshot fences and retention --- .../server/src/serviceChangeAdmission.test.ts | 74 ++++++++++-- apps/server/src/serviceChangeAdmission.ts | 59 +++++++++- scripts/fork/host/t3-update-guard/guard | 109 +++++++++++++++--- .../fork/host/t3-update-guard/test-guard.sh | 28 +++++ 4 files changed, 245 insertions(+), 25 deletions(-) diff --git a/apps/server/src/serviceChangeAdmission.test.ts b/apps/server/src/serviceChangeAdmission.test.ts index b5adbcc38d993..80f8046d79a50 100644 --- a/apps/server/src/serviceChangeAdmission.test.ts +++ b/apps/server/src/serviceChangeAdmission.test.ts @@ -14,11 +14,27 @@ import * as Scope from "effect/Scope"; import * as ServerConfig from "./config.ts"; import * as ServiceChangeAdmission from "./serviceChangeAdmission.ts"; +const linuxProcessIncarnation = (pid: number) => { + if (!NodeFS.existsSync("/proc/sys/kernel/random/boot_id")) return undefined; + const ownerBootId = NodeFS.readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim(); + const stat = NodeFS.readFileSync(`/proc/${pid}/stat`, "utf8"); + const commandEnd = stat.lastIndexOf(")"); + assert.isAtLeast(commandEnd, 0); + const fields = stat + .slice(commandEnd + 1) + .trim() + .split(/\s+/); + const ownerStartTicks = fields[19]; + assert.isDefined(ownerStartTicks); + return { ownerBootId, ownerStartTicks }; +}; + it.effect("drains admitted commands before refusing work behind the snapshot fence", () => { const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-snapshot-admission-")); const root = NodePath.join(baseDir, "runtime", "service-change-admission"); const active = NodePath.join(root, "active"); const fence = NodePath.join(root, "snapshot-fence.json"); + const processIncarnation = linuxProcessIncarnation(process.pid); const testLayer = ServerConfig.ServerConfig.layerTest(baseDir, baseDir).pipe( Layer.provideMerge(NodeServices.layer), ); @@ -46,9 +62,15 @@ it.effect("drains admitted commands before refusing work behind the snapshot fen yield* Deferred.await(entered); assert.equal(NodeFS.readdirSync(active).length, 1); - NodeFS.writeFileSync(fence, JSON.stringify({ protocolVersion: 1, ownerPid: process.pid }), { - mode: 0o600, - }); + NodeFS.writeFileSync( + fence, + JSON.stringify( + processIncarnation === undefined + ? { protocolVersion: 1, ownerPid: process.pid } + : { protocolVersion: 2, ownerPid: process.pid, ...processIncarnation }, + ), + { mode: 0o600 }, + ); let fencedEffectRan = false; const fenced = yield* Effect.exit( ServiceChangeAdmission.withAdmission( @@ -65,18 +87,52 @@ it.effect("drains admitted commands before refusing work behind the snapshot fen yield* Fiber.join(fiber); assert.equal(NodeFS.readdirSync(active).length, 0); - NodeFS.writeFileSync(fence, JSON.stringify({ protocolVersion: 2, ownerPid: 2_000_000_000 }), { + NodeFS.writeFileSync(fence, JSON.stringify({ protocolVersion: 1, ownerPid: 2_000_000_000 }), { mode: 0o600, }); const incompatible = yield* Effect.exit(ServiceChangeAdmission.withAdmission(Effect.void)); assert.isTrue(Exit.isFailure(incompatible)); assert.isTrue(NodeFS.existsSync(fence)); - NodeFS.writeFileSync(fence, JSON.stringify({ protocolVersion: 1, ownerPid: 2_000_000_000 }), { - mode: 0o600, - }); - yield* ServiceChangeAdmission.withAdmission(Effect.void); - assert.isFalse(NodeFS.existsSync(fence)); + if (processIncarnation !== undefined) { + NodeFS.writeFileSync( + fence, + JSON.stringify({ + protocolVersion: 2, + ownerPid: process.pid, + ...processIncarnation, + ownerStartTicks: "0", + }), + { mode: 0o600 }, + ); + yield* ServiceChangeAdmission.withAdmission(Effect.void); + assert.isFalse(NodeFS.existsSync(fence)); + + NodeFS.writeFileSync( + fence, + JSON.stringify({ + protocolVersion: 2, + ownerPid: 2_000_000_000, + ...processIncarnation, + }), + { mode: 0o600 }, + ); + yield* ServiceChangeAdmission.withAdmission(Effect.void); + assert.isFalse(NodeFS.existsSync(fence)); + + NodeFS.writeFileSync( + fence, + JSON.stringify({ + protocolVersion: 2, + ownerPid: process.pid, + ...processIncarnation, + ownerBootId: "00000000-0000-0000-0000-000000000000", + }), + { mode: 0o600 }, + ); + yield* ServiceChangeAdmission.withAdmission(Effect.void); + assert.isFalse(NodeFS.existsSync(fence)); + } }).pipe( Effect.provide(testLayer), Effect.ensuring(Effect.sync(() => NodeFS.rmSync(baseDir, { recursive: true, force: true }))), diff --git a/apps/server/src/serviceChangeAdmission.ts b/apps/server/src/serviceChangeAdmission.ts index 2e9f1af35cb46..7dc28c2cabbd0 100644 --- a/apps/server/src/serviceChangeAdmission.ts +++ b/apps/server/src/serviceChangeAdmission.ts @@ -16,6 +16,7 @@ import * as Scope from "effect/Scope"; import * as ServerConfig from "./config.ts"; const PROTOCOL_VERSION = 1; +const FENCE_PROTOCOL_VERSION = 2; const MUTEX_WAIT_MS = 5_000; interface AdmissionLease { @@ -102,6 +103,21 @@ const pidIsAlive = (pid: number) => { } }; +const linuxProcessStartTicks = async (pid: number): Promise => { + const stat = await NodeFS.promises.readFile(`/proc/${pid}/stat`, "utf8"); + const commandEnd = stat.lastIndexOf(")"); + if (commandEnd < 0) throw new Error("Snapshot fence owner process stat is invalid."); + const fields = stat + .slice(commandEnd + 1) + .trim() + .split(/\s+/); + const startTicks = fields[19]; + if (startTicks === undefined || !/^[0-9]+$/.test(startTicks)) { + throw new Error("Snapshot fence owner process start time is invalid."); + } + return startTicks; +}; + const errorHasCode = (cause: unknown, code: string) => typeof cause === "object" && cause !== null && "code" in cause && cause.code === code; @@ -280,22 +296,59 @@ const removeStaleFence = async (paths: AdmissionPaths) => { throw new ServiceChangeAdmissionError({ stage: "fence" }); } let ownerPid: number; + let ownerBootId: string; + let ownerStartTicks: string; try { const fence = JSON.parse(await NodeFS.promises.readFile(paths.fence, "utf8")) as { protocolVersion?: unknown; ownerPid?: unknown; + ownerBootId?: unknown; + ownerStartTicks?: unknown; }; - if (fence.protocolVersion !== PROTOCOL_VERSION || typeof fence.ownerPid !== "number") { + if ( + fence.protocolVersion !== FENCE_PROTOCOL_VERSION || + typeof fence.ownerPid !== "number" || + typeof fence.ownerBootId !== "string" || + !/^[a-f0-9-]{36}$/i.test(fence.ownerBootId) || + typeof fence.ownerStartTicks !== "string" || + !/^[0-9]+$/.test(fence.ownerStartTicks) + ) { throw new Error("Snapshot admission fence protocol is invalid."); } ownerPid = fence.ownerPid; if (!Number.isSafeInteger(ownerPid) || ownerPid <= 0) throw new Error("Snapshot fence owner PID is invalid."); + ownerBootId = fence.ownerBootId; + ownerStartTicks = fence.ownerStartTicks; } catch (cause) { throw new ServiceChangeAdmissionError({ stage: "fence", cause }); } - if (pidIsAlive(ownerPid)) { - throw new ServiceChangeAdmissionError({ stage: "fence" }); + + let currentBootId: string; + try { + currentBootId = ( + await NodeFS.promises.readFile("/proc/sys/kernel/random/boot_id", "utf8") + ).trim(); + if (!/^[a-f0-9-]{36}$/i.test(currentBootId)) { + throw new Error("Current Linux boot ID is invalid."); + } + } catch (cause) { + throw new ServiceChangeAdmissionError({ stage: "fence", cause }); + } + + if (ownerBootId === currentBootId && pidIsAlive(ownerPid)) { + let currentStartTicks: string; + try { + currentStartTicks = await linuxProcessStartTicks(ownerPid); + } catch (cause) { + if (!errorHasCode(cause, "ENOENT") || pidIsAlive(ownerPid)) { + throw new ServiceChangeAdmissionError({ stage: "fence", cause }); + } + currentStartTicks = ""; + } + if (currentStartTicks === ownerStartTicks) { + throw new ServiceChangeAdmissionError({ stage: "fence" }); + } } await NodeFS.promises.unlink(paths.fence); }; diff --git a/scripts/fork/host/t3-update-guard/guard b/scripts/fork/host/t3-update-guard/guard index 64964049779c9..bcc166b5f36e5 100755 --- a/scripts/fork/host/t3-update-guard/guard +++ b/scripts/fork/host/t3-update-guard/guard @@ -954,7 +954,8 @@ snapshot_db() { fi # Keep the newest three. if [[ "$retain_all" != retain-all ]]; then - ls -1d "$SNAPSHOTS"/2* 2>/dev/null | sort | head -n -3 | xargs -r rm -rf + find "$SNAPSHOTS" -mindepth 1 -maxdepth 1 -type d -name '2*' \ + ! -name '*-snapshot-*' -print | sort | head -n -3 | xargs -r rm -rf -- fi printf '%s' "$dir" } @@ -1098,15 +1099,40 @@ snapshot_admission_unlock() { rmdir "$SNAPSHOT_ADMISSION_MUTEX" 2>/dev/null || true } +snapshot_process_start_ticks() { + local pid="$1" stat rest + local -a fields=() + [[ "$pid" =~ ^[1-9][0-9]*$ ]] || return 1 + stat=$(<"/proc/$pid/stat") || return 1 + [[ "$stat" == *") "* ]] || return 1 + rest="${stat##*) }" + read -r -a fields <<<"$rest" + [[ "${fields[19]:-}" =~ ^[0-9]+$ ]] || return 1 + printf '%s' "${fields[19]}" +} + snapshot_admission_clear_stale_fence() { - local owner_pid + local protocol_version owner_pid owner_boot_id owner_start_ticks current_boot_id current_start_ticks self_pid [[ -e "$SNAPSHOT_ADMISSION_FENCE" ]] || return 0 [[ -f "$SNAPSHOT_ADMISSION_FENCE" && ! -L "$SNAPSHOT_ADMISSION_FENCE" ]] || return 1 + protocol_version=$(jq -er '.protocolVersion | select(type == "number")' "$SNAPSHOT_ADMISSION_FENCE" 2>/dev/null) || return 1 + [[ "$protocol_version" == 2 ]] || return 1 owner_pid=$(jq -er '.ownerPid | select(type == "number")' "$SNAPSHOT_ADMISSION_FENCE" 2>/dev/null) || return 1 [[ "$owner_pid" =~ ^[1-9][0-9]*$ ]] || return 1 - if kill -0 "$owner_pid" 2>/dev/null; then - [[ "$owner_pid" == "$$" ]] && return 0 - return 1 + owner_boot_id=$(jq -er '.ownerBootId | select(type == "string" and test("^[a-fA-F0-9-]{36}$"))' \ + "$SNAPSHOT_ADMISSION_FENCE" 2>/dev/null) || return 1 + owner_start_ticks=$(jq -er '.ownerStartTicks | select(type == "string" and test("^[0-9]+$"))' \ + "$SNAPSHOT_ADMISSION_FENCE" 2>/dev/null) || return 1 + [[ -r /proc/sys/kernel/random/boot_id ]] || return 1 + IFS= read -r current_boot_id /dev/null; then + current_start_ticks=$(snapshot_process_start_ticks "$owner_pid") || return 1 + if [[ "$current_start_ticks" == "$owner_start_ticks" ]]; then + self_pid="${BASHPID:-$$}" + [[ "$owner_pid" == "$self_pid" ]] && return 0 + return 1 + fi fi rm -f -- "$SNAPSHOT_ADMISSION_FENCE" || return 1 snapshot_fsync "$SNAPSHOT_ADMISSION_ROOT" @@ -1130,7 +1156,7 @@ snapshot_admission_active_count() { } snapshot_admission_close() { - local operation="$1" point="$2" listener="$3" tmp count deadline + local operation="$1" point="$2" listener="$3" tmp count deadline owner_pid owner_boot_id owner_start_ticks snapshot_admission_lock || { echo "snapshot: admission coordination lock is unavailable" >&2; return 1; } if ! snapshot_admission_clear_stale_fence; then snapshot_admission_unlock @@ -1138,12 +1164,30 @@ snapshot_admission_close() { return 1 fi SNAPSHOT_ADMISSION_CLOSED_AT=$(date -u +%Y-%m-%dT%H:%M:%S.000Z) + owner_pid="${BASHPID:-$$}" + [[ "$owner_pid" =~ ^[1-9][0-9]*$ ]] || { + snapshot_admission_unlock + return 1 + } + IFS= read -r owner_boot_id "$tmp" || \ + --arg pid "$owner_pid" --arg bootId "$owner_boot_id" --arg startTicks "$owner_start_ticks" \ + '{protocolVersion:2,ownerPid:($pid|tonumber),ownerBootId:$bootId,ownerStartTicks:$startTicks,operationId:$operation,snapshotPoint:$point,closedAt:$closedAt}' >"$tmp" || \ ! chmod 600 "$tmp" || ! snapshot_fsync "$tmp" || \ ! mv -f -- "$tmp" "$SNAPSHOT_ADMISSION_FENCE"; then rm -f -- "$tmp" @@ -1199,23 +1243,62 @@ snapshot_admission_open() { } snapshot_admission_lock || { echo "snapshot: admission coordination lock is unavailable while reopening" >&2; return 1; } if [[ -e "$SNAPSHOT_ADMISSION_FENCE" ]]; then - local owner_pid operation_id + local protocol_version owner_pid operation_id owner_boot_id owner_start_ticks current_boot_id current_start_ticks self_pid + protocol_version=$(jq -er '.protocolVersion | select(type == "number")' "$SNAPSHOT_ADMISSION_FENCE" 2>/dev/null) || { + snapshot_admission_unlock + return 1 + } + [[ "$protocol_version" == 2 ]] || { + snapshot_admission_unlock + return 1 + } owner_pid=$(jq -er '.ownerPid | select(type == "number")' "$SNAPSHOT_ADMISSION_FENCE" 2>/dev/null) || { snapshot_admission_unlock return 1 } + [[ "$owner_pid" =~ ^[1-9][0-9]*$ ]] || { + snapshot_admission_unlock + return 1 + } operation_id=$(jq -r '.operationId // empty' "$SNAPSHOT_ADMISSION_FENCE" 2>/dev/null) || { snapshot_admission_unlock return 1 } - if [[ "$owner_pid" == "$$" ]]; then - [[ "$operation_id" == "$SNAPSHOT_ADMISSION_OPERATION" ]] || { + owner_boot_id=$(jq -er '.ownerBootId | select(type == "string" and test("^[a-fA-F0-9-]{36}$"))' \ + "$SNAPSHOT_ADMISSION_FENCE" 2>/dev/null) || { + snapshot_admission_unlock + return 1 + } + owner_start_ticks=$(jq -er '.ownerStartTicks | select(type == "string" and test("^[0-9]+$"))' \ + "$SNAPSHOT_ADMISSION_FENCE" 2>/dev/null) || { + snapshot_admission_unlock + return 1 + } + IFS= read -r current_boot_id /dev/null; then + current_start_ticks=$(snapshot_process_start_ticks "$owner_pid") || { snapshot_admission_unlock return 1 } - elif kill -0 "$owner_pid" 2>/dev/null; then - snapshot_admission_unlock - return 1 + if [[ "$current_start_ticks" == "$owner_start_ticks" ]]; then + if [[ "$owner_pid" == "$self_pid" ]]; then + [[ "$operation_id" == "$SNAPSHOT_ADMISSION_OPERATION" ]] || { + snapshot_admission_unlock + return 1 + } + else + snapshot_admission_unlock + return 1 + fi + fi fi rm -f -- "$SNAPSHOT_ADMISSION_FENCE" || { snapshot_admission_unlock diff --git a/scripts/fork/host/t3-update-guard/test-guard.sh b/scripts/fork/host/t3-update-guard/test-guard.sh index 00e2e49a10af8..bd345ca015b38 100755 --- a/scripts/fork/host/t3-update-guard/test-guard.sh +++ b/scripts/fork/host/t3-update-guard/test-guard.sh @@ -685,6 +685,29 @@ EOF "$(service_listener_pid)" >"$SNAPSHOT_ADMISSION_ROOT/capability.json" chmod 600 "$SNAPSHOT_ADMISSION_ROOT/capability.json" manager_ready() { return 0; } + fence_owner_pid="${BASHPID:-$$}" + fence_owner_boot_id=$("$SNAPSHOT_ADMISSION_FENCE" + chmod 600 "$SNAPSHOT_ADMISSION_FENCE" + snapshot_admission_clear_stale_fence || fail 'a fence owned by the current process incarnation was cleared' + [[ -f "$SNAPSHOT_ADMISSION_FENCE" ]] || fail 'a live process-incarnation fence was removed' + jq -cn --arg pid "$fence_owner_pid" --arg bootId "$fence_owner_boot_id" \ + '{protocolVersion:2,ownerPid:($pid|tonumber),ownerBootId:$bootId,ownerStartTicks:"0"}' \ + >"$SNAPSHOT_ADMISSION_FENCE" + chmod 600 "$SNAPSHOT_ADMISSION_FENCE" + snapshot_admission_clear_stale_fence || fail 'a PID-reused stale fence was not cleared' + [[ ! -e "$SNAPSHOT_ADMISSION_FENCE" ]] || fail 'PID-reused stale fence remained closed' + jq -cn --arg pid "$fence_owner_pid" --arg bootId "$fence_owner_boot_id" --arg startTicks "$fence_owner_start_ticks" \ + '{protocolVersion:2,ownerPid:($pid|tonumber),ownerBootId:"00000000-0000-0000-0000-000000000000",ownerStartTicks:$startTicks}' \ + >"$SNAPSHOT_ADMISSION_FENCE" + chmod 600 "$SNAPSHOT_ADMISSION_FENCE" + snapshot_admission_clear_stale_fence || fail 'a previous-boot fence was not cleared' + [[ ! -e "$SNAPSHOT_ADMISSION_FENCE" ]] || fail 'previous-boot fence remained closed' + pass 'admission fence recovery distinguishes a live process incarnation from PID reuse and reboot' + active_version() { echo "$sim_version"; } is_trusted() { return 0; } is_healthy() { return 0; } @@ -976,6 +999,11 @@ for path in sys.argv[1:]: "$(jq -r '.admissionBarrier.drainedAdmissions' "$receipt")" == 0 && \ "$(jq -r '.admissionBarrier.capabilityListenerPid' "$receipt")" =~ ^[1-9][0-9]*$ ]] || fail 'receipt did not retain the drained admission-fence proof' [[ -d "$SNAPSHOTS/20200101T000000-before" && -d "$SNAPSHOTS/20200104T000000-before" ]] || fail 'one-off snapshot rotated away an earlier copy' + retained_snapshot=$(jq -r '.snapshotPath' "$receipt") + for rotation in {1..5}; do + snapshot_db "rotation-$rotation" >/dev/null || fail 'ordinary snapshot rotation fixture failed' + done + [[ -d "$retained_snapshot" ]] || fail 'ordinary snapshot rotation deleted the retained one-off capture' [[ "$(grep -c '^stop --no-block t3code.service$' "$root/snapshot-svc")" == 1 ]] || fail 'snapshot did not stop exactly once' [[ "$(grep -c '^start --no-block t3code.service$' "$root/snapshot-svc")" == 1 ]] || fail 'snapshot did not restart exactly once' [[ -s "$root/snapshot-hash-order" ]] || fail 'copied files were not hashed after restart'