Skip to content
pi-c Artifact [47ff727acc]
Login

Artifact [47ff727acc]

Artifact 47ff727acceff804e39010d48e30f1687828dfa34590a5562d3b5372eadf1d19:


#!/bin/sh
# Crash at every commit and effect boundary, reopen, finish, and check that the
# journal and the outside world agree. --no-faults runs only the paths that need
# no crash hooks (the release build has none).
set -eu
PIC=${PIC:?set PIC to the pic binary}
FAULTS=yes
[ "${1:-}" = --no-faults ] && FAULTS=no
T=$(mktemp -d "${TMPDIR:-/tmp}/pic-crash.XXXXXX")
# pic keeps user state under HOME: never the real one.
export HOME="$T/home"
mkdir -p "$HOME"
trap 'rm -rf -- "$T"' EXIT HUP INT TERM
fail() { printf 'FAIL: %s\n' "$*" >&2; exit 1; }
# Timing is never assumed: a throttled machine (the CI runner is a launchd
# agent) can stretch any fixed sleep. A test's command signals with a file
# (`await` FILE, up to 60s), and holds until the test signals back: HOLD is a
# command fragment that waits for "release" in the workspace, up to 120s so a
# broken test cannot hang.
await() { i=0; while [ ! -e "$1" ]; do i=$((i + 1)); [ "$i" -lt 600 ] || fail "timed out waiting for $1"; sleep 0.1; done; }
HOLD='i=0; while [ ! -e release ] && [ $i -lt 1200 ]; do sleep 0.1; i=$((i + 1)); done'

# The exec appends one line to a ledger OUTSIDE the workspace: the external
# effect whose count proves whether a replay-unsafe tool ran twice.
cat > "$T/script" <<EOF
tool write notes.txt hello from pic
tool exec printf 'ran\n' >> "$T/ledger"
text done
EOF

fresh() { # fresh NAME: a new, empty database, workspace, and ledger
    DB="$T/$1.sqlite"
    WS="$T/$1-ws"
    mkdir "$WS"
    : > "$T/ledger"
}
pic() { "$PIC" --db "$DB" --workspace "$WS" "$@"; }
lines() { wc -l < "$T/ledger" | tr -d ' '; }

verify() { # verify CASE EXPECTED_LEDGER_LINES EXPECTED_EXEC_STATE [FAILED_GENERATIONS]
    pic check > /dev/null || fail "$1: integrity check"
    out=$(pic dump)
    [ "$(printf '%s\n' "$out" | grep -c '^submission ')" = 1 ] || fail "$1: submission count"
    printf '%s\n' "$out" | grep -q '^submission 1 job-1 answered ' || fail "$1: not answered"
    [ "$(printf '%s\n' "$out" | grep -c ' answer | \[{"type":"text","text":"done"}\]$')" = 1 ] ||
        fail "$1: answer count"
    [ "$(cat "$WS/notes.txt")" = "hello from pic" ] || fail "$1: written file"
    printf '%s\n' "$out" | grep -q "^effect 2 .* bash $3 safe=0 " || fail "$1: exec effect not $3"
    [ "$(lines)" = "$2" ] || fail "$1: ledger has $(lines) lines, expected $2"
    failed=$(printf '%s\n' "$out" | grep -c '^generation .* failed' || true)
    [ "$failed" = "${4:-0}" ] || fail "$1: $failed failed generations, expected ${4:-0}"
    [ "$(pic submit job-1 'make notes')" = "duplicate: already admitted" ] || fail "$1: resubmit"
    if pic submit job-1 'different text' 2>/dev/null; then fail "$1: key reuse accepted"; fi
    printf 'PASS: %s (ledger=%s exec=%s failed-generations=%s)\n' "$1" "$2" "$3" "${4:-0}"
}

# Clean run.
fresh clean
pic submit job-1 'make notes' > /dev/null
pic run --script "$T/script"
verify clean 1 done

# A concurrently running pic must be refused immediately, not queued.
fresh fence
pic submit job-1 'make notes' > /dev/null
printf 'tool exec touch holding; %s\ntext done\n' "$HOLD" > "$T/slow"
pic run --script "$T/slow" &
holder=$!
await "$WS/holding"
second=0
pic run --script "$T/slow" > "$T/fence.out" 2> "$T/fence.err" || second=$?
if [ "$second" -eq 0 ]; then
    # Evidence for a failure seen only under the CI runner (2026-11-19).
    {
        echo "--- fence diagnostics"
        if kill -0 "$holder" 2>/dev/null; then echo "first writer: alive (pid $holder)"; else echo "first writer: gone"; fi
        ps -o pid,ppid,pgid,stat,command -ax | grep -F "$PIC" | grep -v grep || true
        ls -la "$T" | grep -E 'fence' || true
        echo "second writer stdout:"; cat "$T/fence.out"
        echo "second writer stderr:"; cat "$T/fence.err"
        ulimit -a
    } >&2
    touch "$WS/release"
    wait "$holder" || true
    pic dump >&2 || true
    fail "second writer was admitted"
fi
touch "$WS/release"
grep -q 'owned by another pic process' "$T/fence.err" || fail "second writer error: $(cat "$T/fence.err")"
wait "$holder"
printf 'PASS: second writer refused while the first runs\n'

effect_result() { pic dump | grep '^effect 1 ' | sed 's/^[^|]*| //'; }
run_one() { # run_one NAME SCRIPT_LINE [pic options]: fresh db, run one exec, then answer
    script="$T/$1.script"
    fresh "$1"
    printf '%s\ntext done\n' "$2" > "$script"
    shift 2
    pic submit job-1 'make notes' > /dev/null
    "$PIC" --db "$DB" --workspace "$WS" "$@" run --script "$script"
}

# The deadline is enforced even though the command keeps running.
start=$(date +%s)
run_one deadline 'tool exec sleep 30' --exec-timeout 1
[ $(( $(date +%s) - start )) -lt 10 ] || fail "deadline: exec ran past its timeout"
pic dump | grep -q '^Command timed out after 1 seconds$' || fail "deadline: result $(effect_result)"
printf 'PASS: exec deadline enforced\n'

# Closing or redirecting stdout must not end (or kill) the command early.
run_one redirect 'tool exec exec >/dev/null 2>&1; sleep 1; touch finished'
[ -f "$WS/finished" ] || fail "redirect: command was cut short"
[ "$(effect_result)" = '(no output)' ] || fail "redirect: result $(effect_result)"
printf 'PASS: exec waits for the command, not its output\n'

# A background child holding the output pipe neither hangs pic nor outlives it.
# The child waits for "release", which comes only after pic has returned, so
# pic returning at all proves it did not wait for the child (perl's alarm
# bounds a regression to a minute); a surviving child would then touch bgdone.
fresh background
printf 'tool exec (%s; touch bgdone) & echo started\ntext done\n' "$HOLD" > "$T/background.script"
pic submit job-1 'make notes' > /dev/null
perl -e 'alarm 60; exec @ARGV or die' "$PIC" --db "$DB" --workspace "$WS" run --script "$T/background.script" ||
    fail "background: pic waited for a background child"
touch "$WS/release"
sleep 2
[ ! -f "$WS/bgdone" ] || fail "background: descendant outlived the command"
printf 'PASS: background descendants are killed with the command\n'

# If pic dies mid-command, the command dies too, before any restarted pic
# records its outcome as unknown.
fresh orphan
printf 'tool exec touch running; %s; touch late\ntext done\n' "$HOLD" > "$T/orphan.script"
pic submit job-1 'make notes' > /dev/null
# The binary itself, not the pic() function: $! of a backgrounded function is a
# subshell, and killing that would leave pic running.
"$PIC" --db "$DB" --workspace "$WS" run --script "$T/orphan.script" &
victim=$!
await "$WS/running"
kill -9 "$victim"
wait "$victim" 2>/dev/null || true
pic run --script "$T/orphan.script"
pic dump | grep -q '^effect 1 .* bash unknown safe=0 ' || fail "orphan: effect not unknown"
touch "$WS/release" # a command that survived would now touch late
sleep 2
[ ! -f "$WS/late" ] || fail "orphan: command outlived a crashed pic"
printf 'PASS: crashed pic takes its running command with it\n'

# A Ctrl-C (SIGINT to pic's whole process group, as a terminal sends it) must
# not orphan the command either. perl starts pic as its own group leader so the
# signal does not also hit this script, and restores SIGINT: a non-interactive
# shell starts background jobs with SIGINT ignored.
fresh interrupt
printf 'tool exec touch running; %s; touch late\ntext done\n' "$HOLD" > "$T/interrupt.script"
pic submit job-1 'make notes' > /dev/null
perl -e '$SIG{INT} = "DEFAULT"; setpgrp(0, 0); exec @ARGV or die' "$PIC" --db "$DB" --workspace "$WS" \
    run --script "$T/interrupt.script" 2>/dev/null &
leader=$!
await "$WS/running"
kill -INT -"$leader"
wait "$leader" 2>/dev/null || true
pic run --script "$T/interrupt.script"
# The first Ctrl-C cancels the request: the command is aborted and recorded.
pic dump | grep -q '^effect 1 .* bash done safe=0 ' && pic dump | grep -q '^Command aborted$' ||
    fail "interrupt: command not recorded as aborted"
pic dump | grep -q '^submission 1 job-1 failed | .* error=cancelled' || fail "interrupt: request not cancelled"
pic check > /dev/null || fail "interrupt: integrity"
touch "$WS/release" # a command that survived would now touch late
sleep 2
[ ! -f "$WS/late" ] || fail "interrupt: command outlived a Ctrl-C"
printf 'PASS: Ctrl-C to the group aborts the running command and cancels the request\n'

# A symlink to a running pic's database is the same database: refused at once.
printf 'tool exec touch holding; %s\ntext done\n' "$HOLD" > "$T/slower"
fresh alias
pic submit job-1 'make notes' > /dev/null
ln -s "$DB" "$T/alias-link.sqlite"
pic run --script "$T/slower" &
holder=$!
await "$WS/holding"
if "$PIC" --db "$T/alias-link.sqlite" --workspace "$WS" run --script "$T/slower" 2> "$T/alias.err"; then
    touch "$WS/release"
    fail "alias: second writer through a symlink was admitted"
fi
touch "$WS/release"
grep -q 'owned by another pic process' "$T/alias.err" || fail "alias error: $(cat "$T/alias.err")"
wait "$holder"
printf 'PASS: second writer refused through a symlinked path\n'

# Provider failures: transient ones are retried as new journaled attempts, up
# to three per turn; others fail the submission at once with the error kept.
outcome() { # outcome NAME SCRIPT_LINE WANT: run one turn; check status and failed generations
    fresh "$1"
    printf '%s\n' "$2" > "$T/$1.script"
    pic submit job-1 'make notes' > /dev/null
    pic run --script "$T/$1.script" 2> "$T/$1.err" || true
    pic check > /dev/null || fail "$1: integrity check"
    got="$(pic dump | sed -n 's/^submission 1 job-1 \([a-z]*\) .*/\1/p') $(pic dump | grep -c '^generation .* failed' || true)"
    [ "$got" = "$3" ] || fail "$1: got $got, expected $3"
}
outcome flaky 'flaky 2 text done' 'answered 2'
outcome exhausted 'flaky 9 text done' 'failed 3'
grep -q 'gave up after 3 provider attempts' "$T/exhausted.err" || fail "exhausted: $(cat "$T/exhausted.err")"
outcome reject 'reject bad request' 'failed 1'
pic dump | grep -q '^submission 1 job-1 failed .* error=scripted rejection: bad request$' || fail "reject: error lost"
outcome refuse 'refuse' 'failed 0'
pic dump | grep -q '^entry 2 1 assistant | \[\]$' || fail "refuse: refusal not journaled"
printf 'PASS: provider failures are retried, capped and recorded\n'

# Several tool calls in one assistant turn run in call order, once each.
printf 'tool write notes.txt hello from pic\texec printf '"'"'ran\\n'"'"' >> "%s/ledger"\ntext done\n' "$T" \
    > "$T/parallel.script"
fresh parallel
pic submit job-1 'make notes' > /dev/null
pic run --script "$T/parallel.script"
pic dump | grep -q '^effect 1 2\.0 write done' || fail "parallel: first call"
pic dump | grep -q '^effect 2 2\.1 bash done' || fail "parallel: second call"
verify parallel 1 done

[ "$FAULTS" = yes ] || exit 0

# point:n  expected-ledger-lines  expected-exec-state  failed-generations
# A crash after the exec is marked started but before its result commits leaves
# its outcome unknown: it is never run again (ledger 0 or 1, never 2). A crash
# while a generation is outstanding fails that attempt; the turn is asked again.
crash_matrix() { # crash_matrix SCRIPT LABEL < cases
    while read -r point ledger state generations; do
        name=$(printf '%s-%s' "$2" "$point" | tr ':' '-')
        fresh "$name"
        if [ "$point" = after-admit:1 ]; then
            # env, not a prefix assignment: POSIX lets an assignment before a shell
            # function persist, which would crash every later command.
            if env PIC_CRASH_AT="$point" "$PIC" --db "$DB" --workspace "$WS" submit job-1 'make notes' \
                > /dev/null 2>&1; then fail "$point: no crash"; fi
        else
            pic submit job-1 'make notes' > /dev/null
            if env PIC_CRASH_AT="$point" "$PIC" --db "$DB" --workspace "$WS" run --script "$1" \
                2>/dev/null; then fail "$name: no crash"; fi
        fi
        pic submit job-1 'make notes' > /dev/null
        pic run --script "$1"
        verify "$name" "$ledger" "$state" "$generations"
    done
}
crash_matrix "$T/script" serial <<'EOF'
after-admit:1 1 done 0
after-generation-started:1 1 done 1
after-generation-started:2 1 done 1
after-generation-started:3 1 done 1
after-reply:1 1 done 1
after-reply:2 1 done 1
after-reply:3 1 done 1
after-assistant:1 1 done 0
after-assistant:2 1 done 0
after-started:1 1 done 0
after-started:2 0 unknown 0
after-exec:1 1 done 0
after-exec:2 1 unknown 0
after-result:1 1 done 0
after-result:2 1 done 0
after-answer:1 1 done 0
EOF
crash_matrix "$T/parallel.script" parallel <<'EOF'
after-reply:1 1 done 1
after-assistant:1 1 done 0
after-started:1 1 done 0
after-started:2 0 unknown 0
after-exec:2 1 unknown 0
after-result:1 1 done 0
after-result:2 1 done 0
EOF

# A truncated command that crashes after it ran, before its result commits:
# its outcome is unknown, nothing of its output is journaled, and no temp file
# is left (the full output lives only in the journal).
fresh trunc
mkdir "$T/trunc-tmp"
printf 'tool bash seq 1 3000\ntext done\n' > "$T/trunc.script"
pic submit job-1 'make notes' > /dev/null
if TMPDIR="$T/trunc-tmp" PIC_CRASH_AT=after-exec:1 "$PIC" --db "$DB" --workspace "$WS" run --script "$T/trunc.script" 2>/dev/null; then
    fail 'trunc: no crash'
fi
TMPDIR="$T/trunc-tmp" pic run --script "$T/trunc.script"
pic check > /dev/null || fail 'trunc: integrity check'
pic dump | grep -q '^effect 1 .* bash unknown ' || fail 'trunc: effect not unknown'
[ -z "$(ls -A "$T/trunc-tmp")" ] || fail "trunc: temp files left: $(ls "$T/trunc-tmp")"
if command -v sqlite3 > /dev/null 2>&1; then
    [ "$(sqlite3 "$DB" 'SELECT count(*) FROM pic_output')" = 0 ] || fail 'trunc: output journaled without its result'
fi
printf 'PASS: trunc: crash after a truncated exec leaves it unknown and no temp file\n'

# Steering and follow-ups (--commands) are journaled as they arrive and
# delivered exactly once: a crash after one is queued, after a steer becomes
# a user entry, or after a follow-up becomes the next request loses nothing
# and repeats nothing when the run resumes (without --commands).
printf 'tool exec touch started; %s\ntext done\n' "$HOLD" > "$T/steer.script"
steer_crash() { # steer_crash POINT SUBMISSIONS
    fresh "steer-$(printf '%s' "$1" | tr ':' '-')"
    pic submit job-1 'make notes' > /dev/null
    rm -f "$T/in"
    mkfifo "$T/in"
    env PIC_CRASH_AT="$1" "$PIC" --db "$DB" --workspace "$WS" --json --commands run --script "$T/steer.script" \
        < "$T/in" > "$T/steer.ev" 2>/dev/null &
    spid=$!
    exec 3> "$T/in"
    await "$WS/started"
    printf '%s\n' '{"type":"steer","message":"steer now"}' >&3
    if [ "$1" != after-enqueue:1 ]; then
        i=0
        until grep -q '"command":"steer","success":true' "$T/steer.ev"; do
            i=$((i + 1)); [ "$i" -lt 600 ] || fail "$1: no steer response"; sleep 0.1
        done
        printf '%s\n' '{"type":"follow_up","message":"and then"}' >&3
        if [ "$1" != after-enqueue:2 ]; then
            i=0
            until grep -q '"command":"follow_up","success":true' "$T/steer.ev"; do
                i=$((i + 1)); [ "$i" -lt 600 ] || fail "$1: no follow_up response"; sleep 0.1
            done
            touch "$WS/release"
        fi
    fi
    rc=0
    wait "$spid" || rc=$?
    exec 3>&-
    [ "$rc" = 77 ] || fail "$1: expected a crash, got $rc"
    touch "$WS/release"
    pic run --script "$T/steer.script" > /dev/null
    pic check > /dev/null || fail "$1: integrity check"
    out=$(pic dump)
    [ "$(printf '%s\n' "$out" | grep -c ' user | steer now$')" = 1 ] || fail "$1: steer entries: $(printf '%s\n' "$out" | grep '^entry')"
    [ "$(printf '%s\n' "$out" | grep -c '^submission .* answered ')" = "$2" ] || fail "$1: submissions: $(printf '%s\n' "$out" | grep '^submission')"
    [ "$(printf '%s\n' "$out" | grep -c '^queued .* delivered entry=')" = "$2" ] || fail "$1: queued: $(printf '%s\n' "$out" | grep '^queued')"
    [ "$(printf '%s\n' "$out" | grep -c '^queued .* queued |')" = 0 ] || fail "$1: left queued"
    if [ "$2" = 2 ]; then
        [ "$(printf '%s\n' "$out" | grep -c ' user | and then$')" = 1 ] || fail "$1: follow-up entries"
    fi
    printf 'PASS: steer: crash at %s, resumed: delivered once (%s requests)\n' "$1" "$2"
}
steer_crash after-enqueue:1 1
steer_crash after-enqueue:2 2
steer_crash after-steer:1 2
steer_crash after-answer:1 2

# Steer mode all, crashing right after both steers became entries together:
# the resumed run delivers neither again.
fresh steer-all
pic submit job-1 'make notes' > /dev/null
rm -f "$T/in"
mkfifo "$T/in"
env PIC_CRASH_AT=after-steer:1 "$PIC" --db "$DB" --workspace "$WS" --json --commands run --script "$T/steer.script" \
    < "$T/in" > "$T/steer.ev" 2>/dev/null &
spid=$!
exec 3> "$T/in"
await "$WS/started"
printf '%s\n' '{"type":"set_steering_mode","mode":"all"}' '{"type":"steer","message":"one"}' '{"type":"steer","message":"two"}' >&3
i=0
until grep -q '"steering":\["one","two"\]' "$T/steer.ev"; do
    i=$((i + 1)); [ "$i" -lt 600 ] || fail "steer-all: not queued"; sleep 0.1
done
touch "$WS/release"
rc=0
wait "$spid" || rc=$?
exec 3>&-
[ "$rc" = 77 ] || fail "steer-all: expected a crash, got $rc"
pic run --script "$T/steer.script" > /dev/null
pic check > /dev/null || fail "steer-all: integrity check"
pic dump > "$T/steer.dump"
[ "$(grep -c '^entry .* 1 user | one$' "$T/steer.dump")" = 1 ] && [ "$(grep -c '^entry .* 1 user | two$' "$T/steer.dump")" = 1 ] ||
    fail "steer-all: $(grep '^entry' "$T/steer.dump")"
[ "$(grep -c '^submission ' "$T/steer.dump")" = 1 ] || fail "steer-all: an extra request"
grep -q '^submission 1 job-1 answered' "$T/steer.dump" || fail "steer-all: not answered"
printf 'PASS: steer: mode all, crash after delivery, resumed: each delivered once\n'