Skip to content
pi-c Artifact [82c9804af5]
Login

Artifact [82c9804af5]

Artifact 82c9804af5b92f1db60da7c94275a81023cfa5bb52ed0d80d2b03fe32cd8d56f:


#!/bin/sh
# The tool calls of one reply run at the same time (Pi's toolExecution
# "parallel", the default), each still journaled intent, started, result;
# their results land in the model's call order whatever order they finish in.
# toolExecution "sequential" runs them one by one. Calls on the same file
# wait for each other. A crash mid-batch recovers each call as a lone call
# would (replay-unsafe started: unknown, never re-run; replay-safe: re-run);
# Ctrl-C aborts every running call.
set -eu
PIC=${PIC:?set PIC to the pic binary}
SERVER=${SERVER:?set SERVER to the fake_server binary}
FAULTS=yes
[ "${1:-}" = --no-faults ] && FAULTS=no
T=$(mktemp -d "${TMPDIR:-/tmp}/pic-parallel.XXXXXX")
# pic keeps user state under HOME: never the real one.
export HOME="$T/home"
mkdir -p "$HOME"
spid=
cleanup() { [ -n "$spid" ] && kill "$spid" 2>/dev/null; rm -rf -- "$T"; }
trap cleanup EXIT HUP INT TERM
fail() { printf 'FAIL: %s\n' "$*" >&2; exit 1; }
export ANTHROPIC_API_KEY=pic-parallel-test-key
SQL=${SQLITE3:-sqlite3}
now_ms() { "$SQL" :memory: "SELECT CAST(unixepoch('subsec') * 1000 AS INTEGER)"; }
await() { i=0; while [ ! -e "$1" ]; do i=$((i + 1)); [ "$i" -lt 600 ] || fail "timed out waiting for $1"; sleep 0.1; done; }
n=0
fresh() { # fresh: a new journal and workspace
    n=$((n + 1))
    DB="$T/j$n.sqlite"
    WS="$T/ws$n"
    mkdir "$WS"
}
pic() { "$PIC" --db "$DB" --workspace "$WS" "$@"; }
q() { "$SQL" "$DB" "$1"; }
# The ordinals of the tool results, in journal order.
result_order() { q "SELECT group_concat(f.ordinal, ' ') FROM (SELECT f.ordinal FROM pic_entry e JOIN pic_effect f ON f.id = e.effect_id WHERE e.kind = 'tool_result' ORDER BY e.seq) f"; }
types() { sed -n 's/^{"type":"\(tool_execution_[se][a-z]*\)".*/\1/p' "$1" | tr '\n' ' '; }
ends() { sed -n 's/^{"type":"tool_execution_end","toolCallId":"\([^"]*\)".*/\1/p' "$1" | tr '\n' ' '; }

# One reply of three calls: two one-second commands, then a write that is
# done long before either.
cat > "$T/three.sse" <<'EOF'
event: message_start
data: {"type":"message_start","message":{"id":"msg_01","type":"message","role":"assistant","model":"claude-opus-5-5","content":[],"stop_reason":null,"usage":{"input_tokens":25,"output_tokens":1}}}

event: content_block_start
data: {"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"toolu_a","name":"bash","input":{}}}

event: content_block_delta
data: {"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":"{\"command\": \"sleep 1; echo one\"}"}}

event: content_block_stop
data: {"type":"content_block_stop","index":0}

event: content_block_start
data: {"type":"content_block_start","index":1,"content_block":{"type":"tool_use","id":"toolu_b","name":"bash","input":{}}}

event: content_block_delta
data: {"type":"content_block_delta","index":1,"delta":{"type":"input_json_delta","partial_json":"{\"command\": \"sleep 1; echo two\"}"}}

event: content_block_stop
data: {"type":"content_block_stop","index":1}

event: content_block_start
data: {"type":"content_block_start","index":2,"content_block":{"type":"tool_use","id":"toolu_c","name":"write","input":{}}}

event: content_block_delta
data: {"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":"{\"path\": \"fast.txt\", \"content\": \"fast\"}"}}

event: content_block_stop
data: {"type":"content_block_stop","index":2}

event: message_delta
data: {"type":"message_delta","delta":{"stop_reason":"tool_use","stop_sequence":null},"usage":{"output_tokens":40}}

event: message_stop
data: {"type":"message_stop"}

EOF
cat > "$T/done.sse" <<'EOF'
event: message_start
data: {"type":"message_start","message":{"id":"msg_02","type":"message","role":"assistant","model":"claude-opus-5-5","content":[],"stop_reason":null,"usage":{"input_tokens":25,"output_tokens":1}}}

event: content_block_start
data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}

event: content_block_delta
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"done"}}

event: content_block_stop
data: {"type":"content_block_stop","index":0}

event: message_delta
data: {"type":"message_delta","delta":{"stop_reason":"end_turn","stop_sequence":null},"usage":{"output_tokens":2}}

event: message_stop
data: {"type":"message_stop"}

EOF
serve() { # a fresh server for the three calls and the answer
    [ -n "$spid" ] && kill "$spid" 2>/dev/null
    mkdir "$T/log$n"
    "$SERVER" "$T/port$n" "$T/log$n" 60 "sse:$T/three.sse" "sse:$T/done.sse" &
    spid=$!
    i=0
    while [ ! -s "$T/port$n" ]; do
        i=$((i + 1))
        [ "$i" -lt 600 ] || fail "server did not start"
        sleep 0.05
    done
    URL="http://127.0.0.1:$(cat "$T/port$n")/v1/messages"
}
three() { # three LABEL: run the reply; its wall time in ms in $ms
    fresh
    serve
    pic submit k1 'go' > /dev/null
    t0=$(now_ms)
    pic --json run --model anthropic/m --api-url "$URL" > "$T/$1.jsonl" 2> "$T/$1.err" || fail "$1: run: $(cat "$T/$1.err")"
    t1=$(now_ms)
    pic check > /dev/null || fail "$1: integrity"
    [ "$(result_order)" = "0 1 2" ] || fail "$1: results in order $(result_order)"
    [ "$(cat "$WS/fast.txt")" = fast ] || fail "$1: write"
    pic dump | grep -q ' | one$' && pic dump | grep -q ' | two$' || fail "$1: outputs: $(pic dump)"
    ms=$((t1 - t0))
}

# Parallel, the default: about one second, results in call order, every
# start before any end (Pi's order), the write finishing first. The run's
# own cost (start-up, two replies) comes on top of the calls' second.
three parallel
[ "$ms" -lt 3000 ] || fail "parallel: took ${ms}ms"
case "$(types "$T/parallel.jsonl")" in
"tool_execution_start tool_execution_start tool_execution_start "*) ;;
*) fail "parallel: event order $(types "$T/parallel.jsonl")" ;;
esac
[ "$(ends "$T/parallel.jsonl" | cut -d' ' -f1)" = toolu_c ] || fail "parallel: first end $(ends "$T/parallel.jsonl")"
printf 'PASS: parallel calls take %sms, results in call order\n' "$ms"

# Sequential: about two seconds, each call's start right before its end.
"$PIC" settings toolExecution sequential
par=$ms
three sequential
[ "$ms" -ge 2000 ] || fail "sequential: took only ${ms}ms"
[ $((ms - par)) -ge 700 ] || fail "parallel saved only $((ms - par))ms (${par}ms against ${ms}ms)"
[ "$(types "$T/sequential.jsonl")" = "tool_execution_start tool_execution_end tool_execution_start tool_execution_end tool_execution_start tool_execution_end " ] ||
    fail "sequential: event order $(types "$T/sequential.jsonl")"
[ "$(ends "$T/sequential.jsonl")" = "toolu_a toolu_b toolu_c " ] || fail "sequential: end order $(ends "$T/sequential.jsonl")"
"$PIC" settings --unset toolExecution
printf 'PASS: sequential calls take %sms\n' "$ms"

# Calls on the same file run in call order, one after the other; calls on
# other files do not wait. The bash call holds until the second write has
# landed, so it overlaps them.
fresh
TAB=$(printf '\t')
printf 'tool write same.txt one%swrite same.txt two%sraw edit {"path":"same.txt","edits":[{"oldText":"two","newText":"three"}]}%sexec i=0; while [ "$(cat same.txt 2>/dev/null)" != three ] && [ $i -lt 100 ]; do sleep 0.05; i=$((i+1)); done; cat same.txt\ntext done\n' \
    "$TAB" "$TAB" "$TAB" > "$T/same.script"
pic submit k1 'same file' > /dev/null
pic run --script "$T/same.script" || fail "same path: run"
pic check > /dev/null || fail "same path: integrity"
[ "$(cat "$WS/same.txt")" = three ] || fail "same path: content $(cat "$WS/same.txt")"
[ "$(q "SELECT result FROM pic_effect WHERE ordinal = 3")" = three ] || fail "same path: bash saw $(q "SELECT result FROM pic_effect WHERE ordinal = 3")"
[ "$(result_order)" = "0 1 2 3" ] || fail "same path: results in order $(result_order)"
printf 'PASS: calls on the same file run in call order\n'

# Two spellings of one new file are one file: the edit waits for the write.
for round in 1 2 3; do
    fresh
    mkdir "$WS/sub"
    printf 'tool write ./n.txt one%sraw edit {"path":"n.txt","edits":[{"oldText":"one","newText":"two"}]}%sraw edit {"path":"sub/../n.txt","edits":[{"oldText":"two","newText":"three"}]}\ntext done\n' \
        "$TAB" "$TAB" > "$T/spell.script"
    pic submit k1 'spellings' > /dev/null
    pic run --script "$T/spell.script" || fail "spellings: run"
    pic check > /dev/null || fail "spellings: integrity"
    [ "$(cat "$WS/n.txt")" = three ] || fail "spellings round $round: content $(cat "$WS/n.txt"): $(q "SELECT ordinal, result FROM pic_effect")"
    [ "$(q "SELECT count(*) FROM pic_effect WHERE is_error = 1")" = 0 ] || fail "spellings round $round: $(q "SELECT ordinal, result FROM pic_effect")"
done
printf 'PASS: ./n.txt, n.txt and sub/../n.txt are one file\n'

# An image read that finishes before an earlier call waits for its turn,
# then lands with its image attached to its own result.
fresh
PNG_B64='iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg=='
printf '%s' "$PNG_B64" | base64 -d > "$WS/dot.png" 2>/dev/null || printf '%s' "$PNG_B64" | base64 -D > "$WS/dot.png"
printf 'tool exec sleep 0.5; echo slow%sraw read {"path":"dot.png"}\ntext done\n' "$TAB" > "$T/img.script"
pic submit k1 'image' > /dev/null
pic run --script "$T/img.script" || fail "image: run"
pic check > /dev/null || fail "image: integrity"
[ "$(result_order)" = "0 1" ] || fail "image: results in order $(result_order)"
[ "$(q "SELECT count(*) FROM pic_attachment a JOIN pic_entry e ON e.seq = a.entry_seq JOIN pic_effect f ON f.id = e.effect_id WHERE f.ordinal = 1")" = 1 ] ||
    fail "image: attachment $(q "SELECT * FROM pic_attachment")"
printf 'PASS: an image result waits for its turn and keeps its image\n'

# Ctrl-C mid-batch aborts every running call and journals each as a lone
# call's abort does: done with "Command aborted", the request cancelled.
fresh
printf 'tool exec touch a.started; sleep 30%sexec touch b.started; sleep 30%swrite w.txt written\ntext done\n' "$TAB" "$TAB" > "$T/abort.script"
pic submit k1 'abort' > /dev/null
perl -e '$SIG{INT} = "DEFAULT"; setpgrp(0, 0); exec @ARGV or die' "$PIC" --db "$DB" --workspace "$WS" \
    run --script "$T/abort.script" 2> "$T/abort.err" &
leader=$!
await "$WS/a.started"
await "$WS/b.started"
t0=$(now_ms)
kill -INT -"$leader"
wait "$leader" 2>/dev/null && fail "abort: exit status 0 after a cancel"
t1=$(now_ms)
[ $((t1 - t0)) -lt 5000 ] || fail "abort: took $((t1 - t0))ms to stop"
pic check > /dev/null || fail "abort: integrity"
[ "$(q "SELECT count(*) FROM pic_effect WHERE tool = 'bash' AND state = 'done' AND is_error = 1 AND result LIKE '%Command aborted'")" = 2 ] ||
    fail "abort: $(q "SELECT ordinal, state, result FROM pic_effect")"
q "SELECT status, error FROM pic_submission" | grep -q '^failed|cancelled$' || fail "abort: $(q "SELECT status, error FROM pic_submission")"
[ "$(result_order)" = "0 1 2" ] || fail "abort: results in order $(result_order)"
printf 'PASS: Ctrl-C aborts every running call\n'

# Every tool_execution_start has its end: Ctrl-C ends a read stuck in open,
# and a write waiting for it on the same file, which never runs, ends as
# cancelled, as Pi ends calls an abort kept from running.
fresh
mkfifo "$WS/pipe"
printf 'tool raw read {"path":"pipe"}%swrite pipe never%sexec touch running; sleep 30\ntext done\n' "$TAB" "$TAB" > "$T/pair.script"
pic submit k1 'pairs' > /dev/null
perl -e '$SIG{INT} = "DEFAULT"; setpgrp(0, 0); exec @ARGV or die' "$PIC" --db "$DB" --workspace "$WS" --json \
    run --script "$T/pair.script" > "$T/pair.jsonl" 2> "$T/pair.err" &
leader=$!
await "$WS/running"
sleep 0.3
kill -INT -"$leader"
wait "$leader" 2>/dev/null && fail "pairs: exit status 0 after a cancel"
pic check > /dev/null || fail "pairs: integrity"
[ "$(grep -c '^{"type":"tool_execution_start"' "$T/pair.jsonl")" = 3 ] && [ "$(grep -c '^{"type":"tool_execution_end"' "$T/pair.jsonl")" = 3 ] ||
    fail "pairs: $(types "$T/pair.jsonl")"
grep '^{"type":"tool_execution_end","toolCallId":"toolu_fake_0_1"' "$T/pair.jsonl" | grep -q 'cancelled before it ran' ||
    fail "pairs: waiting write's end: $(grep toolu_fake_0_1 "$T/pair.jsonl")"
[ "$(q "SELECT state FROM pic_effect WHERE ordinal = 1")" = skipped ] || fail "pairs: write $(q "SELECT state FROM pic_effect WHERE ordinal = 1")"
[ -p "$WS/pipe" ] || fail "pairs: the write ran"
printf 'PASS: every start has its end when Ctrl-C keeps a call from running\n'

# An abort command (Pi's RPC abort, here on --commands) does the same.
fresh
pic submit k1 'abort' > /dev/null
rm -f "$T/in"
mkfifo "$T/in"
"$PIC" --db "$DB" --workspace "$WS" --json --commands run --script "$T/abort.script" < "$T/in" > "$T/abort.ev" 2>/dev/null &
cpid=$!
exec 3> "$T/in"
await "$WS/a.started"
await "$WS/b.started"
printf '%s\n' '{"type":"abort"}' >&3
wait "$cpid" 2>/dev/null && fail "abort command: exit status 0 after a cancel"
exec 3>&-
pic check > /dev/null || fail "abort command: integrity"
[ "$(q "SELECT count(*) FROM pic_effect WHERE tool = 'bash' AND state = 'done' AND result LIKE '%Command aborted'")" = 2 ] ||
    fail "abort command: $(q "SELECT ordinal, state, result FROM pic_effect")"
grep -q '"command":"abort","success":true' "$T/abort.ev" || fail "abort command: no response"
printf 'PASS: an abort command aborts every running call\n'

# Calls die with pic: kill -9 it while a read is stuck (opening a FIFO with
# no writer) and a command runs, and a pic started at once gets the journal;
# the read, a replay-safe call, runs again, the command is unknown.
fresh
mkfifo "$WS/stuck"
printf 'tool raw read {"path":"stuck"}%sexec touch running; sleep 30\ntext done\n' "$TAB" > "$T/orphan.script"
pic submit k1 'orphan' > /dev/null
"$PIC" --db "$DB" --workspace "$WS" run --script "$T/orphan.script" 2>/dev/null &
victim=$!
await "$WS/running"
sleep 0.5 # the read, started alongside, is blocked in open by now (the journal is pic's while it runs)
kill -9 "$victim"
wait "$victim" 2>/dev/null || true
rm "$WS/stuck"
printf 'unstuck\n' > "$WS/stuck"
pic run --script "$T/orphan.script" 2> "$T/orphan.err" || fail "orphan: restart: $(cat "$T/orphan.err")"
pic check > /dev/null || fail "orphan: integrity"
[ "$(q "SELECT state FROM pic_effect WHERE ordinal = 0")" = done ] && q "SELECT result FROM pic_effect WHERE ordinal = 0" | grep -q unstuck ||
    fail "orphan: read $(q "SELECT state, result FROM pic_effect WHERE ordinal = 0")"
[ "$(q "SELECT state FROM pic_effect WHERE ordinal = 1")" = unknown ] || fail "orphan: command $(q "SELECT state FROM pic_effect WHERE ordinal = 1")"
printf 'PASS: calls die with a killed pic, and a restart gets the journal at once\n'

# Hooks still fire per call: every PreToolUse before any call runs, in call
# order (Pi prepares calls before running them), a deny skipping only its
# call, and PostToolUse for each call that ran.
fresh
mkdir -p "$HOME/.pic" "$T/h"
cat > "$T/h/hook.sh" <<'SH'
input=$(cat)
id=$(printf '%s' "$input" | sed 's/.*"tool_use_id":"\([^"]*\)".*/\1/')
printf '%s %s\n' "$1" "$id" >> "$(dirname "$0")/order"
case "$1:$input" in
pre:*'"tool_name":"Write"'*) printf '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"no writes"}}\n' ;;
esac
exit 0
SH
cat > "$HOME/.pic/hooks.json" <<EOF
{"hooks": {
 "PreToolUse": [{"matcher": "*", "hooks": [{"type":"command","command":"sh $T/h/hook.sh pre"}]}],
 "PostToolUse": [{"matcher": "*", "hooks": [{"type":"command","command":"sh $T/h/hook.sh post"}]}]
}}
EOF
printf 'tool exec sleep 0.5; echo a%swrite denied.txt x%sexec echo b\ntext done\n' "$TAB" "$TAB" > "$T/hooks.script"
pic submit k1 'hooks' > /dev/null
pic run --script "$T/hooks.script" || fail "hooks: run"
pic check > /dev/null || fail "hooks: integrity"
[ ! -e "$WS/denied.txt" ] || fail "hooks: denied write ran"
[ "$(head -3 "$T/h/order" | tr '\n' ' ')" = "pre toolu_fake_0_0 pre toolu_fake_0_1 pre toolu_fake_0_2 " ] || fail "hooks: order $(cat "$T/h/order")"
[ "$(tail -n +4 "$T/h/order" | sort | tr '\n' ' ')" = "post toolu_fake_0_0 post toolu_fake_0_2 " ] || fail "hooks: post $(cat "$T/h/order")"
[ "$(q "SELECT state FROM pic_effect WHERE ordinal = 1")" = skipped ] || fail "hooks: write $(q "SELECT state FROM pic_effect WHERE ordinal = 1")"
[ "$(result_order)" = "0 1 2" ] || fail "hooks: results in order $(result_order)"
rm -f "$HOME/.pic/hooks.json"
printf 'PASS: hooks fire per call around a parallel batch\n'

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

# Crashes mid-batch. Three replay-unsafe commands, each appending to its own
# ledger outside the workspace, and a replay-safe write. Whatever had
# started when pic died is settled by the journal alone: an unsafe call
# becomes unknown and is never run again (its ledger never grows), a safe
# call runs again, a done call keeps its one result.
cat > "$T/crash.script" <<EOF
tool exec printf 'a\\n' >> "$T/ledger-0"${TAB}exec sleep 0.3; printf 'b\\n' >> "$T/ledger-1"${TAB}write w.txt written${TAB}exec printf 'd\\n' >> "$T/ledger-3"; sleep 0.6
text done
EOF
lines() { if [ -f "$T/ledger-$1" ]; then wc -l < "$T/ledger-$1" | tr -d ' '; else echo 0; fi; }
state() { q "SELECT state FROM pic_effect WHERE ordinal = $1"; }
crashed=0 deferred=0
for point in after-started:1 after-started:2 after-started:3 after-started:4 after-exec:1 after-exec:2 after-exec:3 \
    after-exec:4 after-result:1 after-result:2 after-result:3 after-result:4; do
    fresh
    rm -f "$T"/ledger-*
    pic submit k1 'crash' > /dev/null
    if env PIC_CRASH_AT="$point" "$PIC" --db "$DB" --workspace "$WS" run --script "$T/crash.script" 2> "$T/crash.err"; then
        fail "$point: no crash"
    fi
    grep -q "injected crash at $point" "$T/crash.err" || fail "$point: $(cat "$T/crash.err")"
    # The orphaned calls see pic gone and stop (forked, they carry its command
    # line); only then is the outside world what recovery will find.
    i=0
    while ps -ax -o command | grep -F -- "$DB" | grep -v grep > /dev/null; do
        i=$((i + 1)); [ "$i" -lt 200 ] || fail "$point: orphaned calls still running"; sleep 0.05
    done
    # What the journal holds now decides what recovery may do.
    before=""
    for o in 0 1 2 3; do before="$before $(state $o):$(lines $o)"; done
    # A call done before an earlier one, its result held back for its turn.
    [ "$(q "SELECT count(*) FROM pic_effect f WHERE f.state = 'done' AND NOT EXISTS (SELECT 1 FROM pic_entry e WHERE e.effect_id = f.id)")" = 0 ] ||
        deferred=1
    pic run --script "$T/crash.script" 2> "$T/rerun.err" || fail "$point: rerun: $(cat "$T/rerun.err")"
    pic check > /dev/null || fail "$point: integrity"
    q "SELECT status FROM pic_submission" | grep -q '^answered$' || fail "$point: not answered"
    [ "$(result_order)" = "0 1 2 3" ] || fail "$point: results in order $(result_order)"
    [ "$(q "SELECT count(*) FROM pic_entry WHERE kind = 'tool_result'")" = 4 ] || fail "$point: result count"
    [ "$(cat "$WS/w.txt")" = written ] || fail "$point: write"
    set -- $before
    for o in 0 1 3; do
        was=$1
        [ "$o" = 1 ] && was=$2
        [ "$o" = 3 ] && was=$4
        st=${was%%:*} had=${was##*:}
        case "$st" in
        started)
            crashed=1
            [ "$(state $o)" = unknown ] || fail "$point: call $o was started, now $(state $o)"
            [ "$(lines $o)" = "$had" ] || fail "$point: call $o ran again ($had -> $(lines $o))" ;;
        done)
            [ "$(state $o)" = done ] && [ "$(lines $o)" = 1 ] || fail "$point: call $o done: $(state $o) $(lines $o)" ;;
        intent)
            [ "$(state $o)" = done ] && [ "$(lines $o)" = 1 ] || fail "$point: call $o not run once: $(state $o) $(lines $o)" ;;
        *) fail "$point: call $o in state $st" ;;
        esac
    done
    case "$3" in
    started:* | intent:* | done:*) [ "$(state 2)" = done ] || fail "$point: write left $(state 2)" ;;
    *) fail "$point: write in state $3" ;;
    esac
    for o in 0 1 3; do [ "$(lines $o)" -le 1 ] || fail "$point: call $o ran twice"; done
    printf 'PASS: crash at %s (%s ) recovered\n' "$point" "$before"
done
[ "$crashed" = 1 ] || fail "no crash left an unsafe call started"
[ "$deferred" = 1 ] || fail "no crash left a done call waiting for its entry"

recover_wait() { # the orphans of a crashed run gone
    i=0
    while ps -ax -o command | grep -F -- "$DB" | grep -v grep > /dev/null; do
        i=$((i + 1)); [ "$i" -lt 200 ] || fail "$1: orphaned calls still running"; sleep 0.05
    done
}

# A crash while an image result waits in memory for an earlier call: the
# read (replay-safe) runs again and keeps its image; the command is unknown.
fresh
printf '%s' "$PNG_B64" | base64 -d > "$WS/dot.png" 2>/dev/null || printf '%s' "$PNG_B64" | base64 -D > "$WS/dot.png"
printf 'tool exec sleep 0.5; printf x >> "%s/ledger-img"%sraw read {"path":"dot.png"}\ntext done\n' "$T" "$TAB" > "$T/heldimg.script"
pic submit k1 'held image' > /dev/null
# after-exec:1 is the read's result arriving; :2 the command's, the image held meanwhile.
if env PIC_CRASH_AT=after-exec:2 "$PIC" --db "$DB" --workspace "$WS" run --script "$T/heldimg.script" 2> "$T/crash.err"; then
    fail "held image: no crash"
fi
recover_wait "held image"
[ "$(state 0) $(state 1)" = "started started" ] || fail "held image: before recovery $(state 0) $(state 1)"
pic run --script "$T/heldimg.script" 2> "$T/rerun.err" || fail "held image: rerun: $(cat "$T/rerun.err")"
pic check > /dev/null || fail "held image: integrity"
[ "$(state 0) $(state 1)" = "unknown done" ] || fail "held image: after recovery $(state 0) $(state 1)"
[ "$(result_order)" = "0 1" ] || fail "held image: results in order $(result_order)"
[ "$(q "SELECT count(*) FROM pic_attachment a JOIN pic_entry e ON e.seq = a.entry_seq JOIN pic_effect f ON f.id = e.effect_id WHERE f.ordinal = 1")" = 1 ] ||
    fail "held image: attachment lost"
[ "$(wc -c < "$T/ledger-img" | tr -d ' ')" = 1 ] || fail "held image: command ran again"
printf 'PASS: a crash with an image result held in memory recovers
'

# An earlier call left to run again (a read stuck in open, replay-safe)
# while a later command finished: recovery leaves the done call waiting
# behind the intent, and both results land in call order once it runs.
fresh
mkfifo "$WS/slow"
printf 'tool raw read {"path":"slow"}%sexec printf y >> "%s/ledger-late"\ntext done\n' "$TAB" "$T" > "$T/late.script"
pic submit k1 'late' > /dev/null
if env PIC_CRASH_AT=after-result:1 "$PIC" --db "$DB" --workspace "$WS" run --script "$T/late.script" 2> "$T/crash.err"; then
    fail "intent first: no crash"
fi
recover_wait "intent first"
[ "$(state 0) $(state 1)" = "started done" ] || fail "intent first: before recovery $(state 0) $(state 1)"
rm "$WS/slow"
printf 'arrived\n' > "$WS/slow"
pic check > /dev/null || fail "intent first: recovered journal fails pic check" # opens, recovers, checks
[ "$(state 0) $(state 1)" = "intent done" ] || fail "intent first: after recovery $(state 0) $(state 1)"
[ "$(q "SELECT count(*) FROM pic_entry WHERE kind = 'tool_result'")" = 0 ] || fail "intent first: an entry jumped the queue"
pic run --script "$T/late.script" 2> "$T/rerun.err" || fail "intent first: rerun: $(cat "$T/rerun.err")"
pic check > /dev/null || fail "intent first: integrity"
[ "$(state 0) $(state 1)" = "done done" ] || fail "intent first: $(state 0) $(state 1)"
[ "$(result_order)" = "0 1" ] || fail "intent first: results in order $(result_order)"
q "SELECT result FROM pic_effect WHERE ordinal = 0" | grep -q arrived || fail "intent first: read $(q "SELECT result FROM pic_effect WHERE ordinal = 0")"
[ "$(wc -c < "$T/ledger-late" | tr -d ' ')" = 1 ] || fail "intent first: command ran again"
printf 'PASS: an earlier intent and a later done call recover in call order\n'