Skip to content
pi-c Artifact [86e7dc6382]
Login

Artifact [86e7dc6382]

Artifact 86e7dc6382ed3aac71b84d4eb10ae375a073f15731939aba57571c1a2739b1bf:


#!/bin/sh
# Benchmark pieces: lapse compaction (a conversation idle past the prompt
# cache's lifetime and above a floor compacts before its next request), the
# trial label and pic usage --by-trial, and the request cap per ask.
# --no-faults skips the crash cases (the release build has no crash hooks).
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
here=$(cd "$(dirname "$0")" && pwd)
T=$(mktemp -d "${TMPDIR:-/tmp}/pic-bench.XXXXXX")
export HOME="$T/home"
mkdir -p "$HOME"
spid=
cleanup() { [ -n "$spid" ] && kill "$spid" 2>/dev/null || :; [ -n "${KEEP:-}" ] && { echo "kept $T" >&2; return; }; rm -rf -- "$T"; }
trap cleanup EXIT HUP INT TERM
fail() { printf 'FAIL: %s\n' "$*" >&2; exit 1; }
unset PIC_TRIAL PIC_MAX_REQUESTS PIC_LAPSE PIC_LAPSE_SECONDS PIC_LAPSE_FLOOR PI_CACHE_RETENTION
export PIC_LAPSE_HOLDOUT=0 # no random holdouts except where a case sets one
export PIC_MODEL_CATALOG=offline PIC_PI_EXPORT=0
big() { yes "$1$1$1$1" | head -c 50000 | tr -d '\n'; } # 40000 characters: 10000 tokens by chars/4
WS="$T/ws"
mkdir "$WS" "$T/log"
printf 'text done\n' > "$T/done.txt"

# ---- lapse compaction, with the scripted provider --------------------------
DB="$T/lapse.sqlite"
pic() { "$PIC" --db "$DB" --workspace "$WS" "$@"; }
run() { pic "$@" run --script "$T/done.txt" 2>> "$T/stderr" || fail "run $*: $(tail -2 "$T/stderr")"; }
# Moves every entry SECONDS into the past: the conversation has been idle.
age() { sqlite3 "$DB" "UPDATE pic_entry SET created_ms = created_ms - $1 * 1000"; }
n=0
next() { n=$((n + 1)); pic submit "k$n" "${1:-go on}" --session "$s" > /dev/null; }
lapses() { pic dump | grep -c '^generation .* compaction reason=lapse' || :; }

pic submit k0 "$(big A)" > /dev/null
run --lapse on
s=$(pic sessions | awk '{print $1}')
next "$(big B)"
run --lapse on
next "$(big C)" # 30000 tokens: past the 20000 kept, so there is history to summarize
run --lapse on
[ "$(lapses)" = 0 ] || fail "lapse while the cache is warm"

age 400
next
run --lapse off
[ "$(lapses)" = 0 ] || fail "lapse fired while off"
printf 'PASS: lapse compaction stays off with --lapse off\n'

age 400
next
run --lapse on --lapse-floor 1000000
[ "$(lapses)" = 0 ] || fail "lapse fired under the floor"
next
(export PIC_LAPSE=on PIC_LAPSE_FLOOR=1000000; run) # a subshell: sh keeps assignments made for a function
[ "$(lapses)" = 0 ] || fail "lapse fired under the floor (env)"
printf 'PASS: lapse compaction waits for the context floor\n'

pic settings cacheRetention long > /dev/null
age 400
next
run --lapse on --lapse-floor 1000
[ "$(lapses)" = 0 ] || fail "lapse fired inside the long cache's hour"
age 3700
next
pic --json --lapse on --lapse-floor 1000 run --script "$T/done.txt" > "$T/lapse.jsonl" 2>> "$T/stderr" || fail "run: $(tail -2 "$T/stderr")"
[ "$(lapses)" = 1 ] || fail "no lapse past the long cache's hour: $(pic dump | grep '^generation')"
pic settings --unset cacheRetention > /dev/null
grep -q '"type":"compaction_start","reason":"lapse"' "$T/lapse.jsonl" || fail "event: $(grep compaction "$T/lapse.jsonl")"
grep -q '"type":"compaction_end","reason":"lapse","result":{"summary":' "$T/lapse.jsonl" || fail "end event"
idle=$(sqlite3 "$DB" "SELECT idle_seconds FROM pic_generation WHERE reason = 'lapse'")
tokens=$(sqlite3 "$DB" "SELECT context_tokens FROM pic_generation WHERE reason = 'lapse'")
[ "$idle" -ge 3700 ] && [ "$idle" -lt 3800 ] || fail "idle seconds journaled: $idle"
[ "$tokens" -gt 20000 ] || fail "context tokens journaled: $tokens"
[ "$(sqlite3 "$DB" "SELECT e.kind FROM pic_generation g JOIN pic_entry e ON e.seq = g.entry_seq WHERE g.reason = 'lapse'")" = compaction ] ||
    fail "the lapse generation has no compaction entry"
pic check > /dev/null || fail "integrity"
printf 'PASS: the default lifetime follows cacheRetention (long: an hour)\n'

next "$(big D)"
run --lapse on
[ "$(lapses)" = 1 ] || fail "lapse fired again with a warm cache"
age 400
next "$(big E)" # each lapse below has new history to summarize
run --lapse on --lapse-floor 1000
[ "$(lapses)" = 2 ] || fail "no lapse past the short cache's 5 minutes"
age 100
next
run --lapse on --lapse-floor 1000
[ "$(lapses)" = 2 ] || fail "lapse fired at 100s with the 300s default"
age 100
next "$(big F)"
(export PIC_LAPSE_SECONDS=60; run --lapse on --lapse-floor 1000)
[ "$(lapses)" = 3 ] || fail "PIC_LAPSE_SECONDS did not shorten the lifetime"
age 100
next "$(big G)"
pic settings lapseCompaction on > /dev/null
pic settings lapseSeconds 60 > /dev/null
pic settings lapseFloorTokens 1000 > /dev/null
run
[ "$(lapses)" = 4 ] || fail "the lapse settings did not apply"
age 100
next
run --lapse-seconds 3600
[ "$(lapses)" = 4 ] || fail "--lapse-seconds did not override the setting"
pic settings --unset lapseCompaction > /dev/null
pic settings --unset lapseSeconds > /dev/null
pic settings --unset lapseFloorTokens > /dev/null
[ "$(pic dump | grep -c '^generation .* compaction reason=lapse idle=[0-9]* tokens=[0-9]*')" = 4 ] ||
    fail "dump: $(pic dump | grep compaction)"
pic check > /dev/null || fail "integrity"
printf 'PASS: past the lifetime and above the floor, lapse compacts; flags, env and settings set both\n'

"$PIC" --lapse maybe dump > /dev/null 2>&1 && fail "--lapse maybe accepted"
PIC_LAPSE=maybe "$PIC" --db "$DB" dump > /dev/null 2>&1 && fail "PIC_LAPSE=maybe accepted"
"$PIC" --lapse-floor -1 dump > /dev/null 2>&1 && fail "a negative floor accepted"
printf 'PASS: bad lapse values are refused\n'

# ---- on by default, the holdout and pic usage --lapse --------------------------
DB="$T/holdout.sqlite"
# Each cold cache is the context policy's journaled answer to PreRequest, with its arm.
arms() { sqlite3 "$DB" "SELECT group_concat(arm, ',') FROM (SELECT json_extract(context, '\$.arm') AS arm FROM pic_hook_run
  WHERE event = 'PreRequest' AND reason = 'lapse' ORDER BY submission_id, ref)"; }
pic submit h0 "$(big A)" > /dev/null
run --lapse off
s=$(pic sessions | awk '{print $1}')
next "$(big B)"
run --lapse off
next "$(big C)"
run --lapse off
age 400
next
run # on by default, but 30000 tokens is under the default floor of 100000
[ "$(lapses)" = 0 ] || fail "lapse fired under the default floor"
[ "$(arms)" = small ] || fail "the cold cache under the floor was not kept: $(arms)"
age 400
next "$(big D)"
(export PIC_LAPSE_HOLDOUT=1; run --lapse-floor 1000)
[ "$(lapses)" = 0 ] || fail "a held-out lapse compacted"
[ "$(arms)" = small,holdout ] || fail "arms after a holdout: $(arms)"
age 400
next "$(big E)"
run --lapse-floor 1000
[ "$(lapses)" = 1 ] || fail "no lapse by default above the floor"
[ "$(arms)" = small,holdout,compact ] || fail "arms after a compaction: $(arms)"
next
run --lapse-floor 1000
[ "$(arms)" = small,holdout,compact ] || fail "a warm cache was kept as a cold one: $(arms)"
pic usage --lapse > "$T/lapse.txt" || fail "usage --lapse"
grep -q '^cold caches: 1 compacted, 1 held out, 1 under the floor$' "$T/lapse.txt" || fail "usage --lapse: $(cat "$T/lapse.txt")"
grep -q '^trim: 1 compacted, 1 held out$' "$T/lapse.txt" || fail "usage --lapse names the mode: $(cat "$T/lapse.txt")"
grep -q '^not enough to compare yet' "$T/lapse.txt" || fail "usage --lapse compared too soon: $(cat "$T/lapse.txt")"
pic usage --lapse --json | grep -q '"modes":\[{"mode":"trim","compacted":1,"heldOut":1,.*"ratio":null,"saved":null}\]}$' ||
    fail "usage --lapse --json: $(pic usage --lapse --json)"
pic check > /dev/null || fail "integrity"
PIC_LAPSE_HOLDOUT=2 "$PIC" --db "$DB" dump > /dev/null 2>&1 && fail "PIC_LAPSE_HOLDOUT=2 accepted"
PIC_LAPSE_HOLDOUT=some "$PIC" --db "$DB" dump > /dev/null 2>&1 && fail "PIC_LAPSE_HOLDOUT=some accepted"
(unset PIC_LAPSE_HOLDOUT; pic settings lapseHoldout 0.5 > /dev/null; pic dump > /dev/null) || fail "lapseHoldout 0.5 refused"
pic settings lapseHoldout -1 > /dev/null
(unset PIC_LAPSE_HOLDOUT; pic dump > /dev/null 2>&1) && fail "lapseHoldout -1 accepted"
pic settings --unset lapseHoldout > /dev/null
printf 'PASS: lapse compaction is on by default above 100000 tokens; held-out and small cold caches are kept\n'

# The comparison: ten cold caches, five compacted whose windows cost 1 and
# five held out whose windows cost 2, and one under the floor that closes
# the last window before a request costing 7.
DB="$T/report.sqlite"
pic submit r1 one > /dev/null
run --lapse off
s=$(pic sessions | awk '{print $1}')
k=1
while [ "$k" -lt 12 ]; do next; run --lapse off; k=$((k + 1)); done
sqlite3 "$DB" "UPDATE pic_generation SET usage = json_set(coalesce(usage, '{}'), '\$.pic_cost.total',
  CASE WHEN submission_id <= 5 THEN 1 WHEN submission_id <= 10 THEN 2 ELSE 7 END) WHERE state = 'done'"
# Five compacted in trim mode and five held out, as the policy journals them.
sqlite3 "$DB" "INSERT INTO pic_hook_run(event, session_id, submission_id, ref, command, duration_ms, state, reason, context, created_ms)
  SELECT 'PreRequest', u.session_id, u.id, (SELECT min(turn) FROM pic_generation WHERE submission_id = u.id), 'pic:compact', 0, 'done', 'lapse',
  json_object('arm', CASE WHEN u.id <= 5 THEN 'compact' WHEN u.id <= 10 THEN 'holdout' ELSE 'small' END, 'mode', 'trim'), 0
  FROM pic_submission u WHERE u.id <= 11"
want='{"compacted":5,"heldOut":5,"small":1,"modes":[{"mode":"trim","compacted":5,"heldOut":5,"meanCompacted":1.000000,"meanHeldOut":2.000000,"ratio":0.5000,"ratioLow":0.5000,"ratioHigh":0.5000,"saved":5.0000,"savedLow":5.0000,"savedHigh":5.0000}]}'
[ "$(pic usage --lapse --json)" = "$want" ] || fail "usage --lapse --json: $(pic usage --lapse --json)"
pic usage --lapse | grep -q '^saved: \$5.00 over 5 compactions (95% interval \$5.00 to \$5.00)$' || fail "usage --lapse: $(pic usage --lapse)"
# A journal from before the answers were journaled keeps its pic_lapse rows: summaries.
sqlite3 "$DB" "CREATE TABLE pic_lapse(submission_id INTEGER NOT NULL, turn INTEGER NOT NULL, session_id TEXT NOT NULL,
  decided_ms INTEGER NOT NULL, idle_seconds INTEGER NOT NULL, context_tokens INTEGER NOT NULL, arm TEXT NOT NULL,
  PRIMARY KEY(submission_id, turn));
  INSERT INTO pic_lapse SELECT id, 99, session_id, 0, 400, 200000, 'compact' FROM pic_submission WHERE id = 1"
pic usage --lapse --json | grep -q '"compacted":6,"heldOut":5,"small":1,"modes":\[{"mode":"trim","compacted":5,.*},{"mode":"summary","compacted":1,"heldOut":0,' ||
    fail "usage --lapse with old rows: $(pic usage --lapse --json)"
printf 'PASS: pic usage --lapse compares the cost from each cold cache to the next, compacted against held out\n'

if [ "$FAULTS" = yes ]; then
    DB="$T/lapse-crash.sqlite"
    pic submit c0 "$(big A)" > /dev/null
    run
    s=$(pic sessions | awk '{print $1}')
    next "$(big B)"
    run
    next "$(big C)"
    run
    age 400
    next
    rc=0
    PIC_CRASH_AT=after-policy-answer:1 "$PIC" --db "$DB" --workspace "$WS" --lapse on --lapse-floor 1000 run --script "$T/done.txt" > /dev/null 2>&1 || rc=$?
    [ "$rc" = 77 ] || fail "lapse crash: expected exit 77, got $rc"
    [ "$(sqlite3 "$DB" "SELECT json_extract(context, '\$.compact') FROM pic_hook_run WHERE event = 'PreRequest' AND reason = 'lapse'")" = trim ] ||
        fail "lapse crash: the answer was not journaled"
    [ "$(lapses)" = 0 ] || fail "lapse crash: compacted before the crash"
    run --lapse off # the journaled answer stands, whatever this run's settings
    [ "$(lapses)" = 1 ] || fail "lapse crash: recovery dropped the answer"
    [ "$(pic dump | grep -c '^entry .* compaction ')" = 1 ] || fail "lapse crash: compactions"
    [ "$(sqlite3 "$DB" "SELECT count(*) FROM pic_hook_run WHERE event = 'PreRequest'")" = 1 ] || fail "lapse crash: asked again"
    [ "$(pic dump | grep -c '^submission .* answered ')" = 4 ] || fail "lapse crash: not answered"
    pic check > /dev/null || fail "lapse crash: integrity"
    # In summary mode, a crash once its summary request is journaled.
    pic settings lapseMode summary > /dev/null
    age 400
    next "$(big D)"
    rc=0
    PIC_CRASH_AT=after-compaction-started:1 "$PIC" --db "$DB" --workspace "$WS" --lapse-floor 1000 run --script "$T/done.txt" > /dev/null 2>&1 || rc=$?
    [ "$rc" = 77 ] || fail "summary lapse crash: expected exit 77, got $rc"
    run --lapse off
    [ "$(lapses)" -ge 2 ] || fail "summary lapse crash: recovery dropped the answer"
    [ "$(pic dump | grep -c '^entry .* compaction ')" = 2 ] || fail "summary lapse crash: compactions"
    [ "$(sqlite3 "$DB" "SELECT group_concat(state, ',') FROM (SELECT state FROM pic_generation WHERE reason = 'lapse'
      AND submission_id = (SELECT max(submission_id) FROM pic_generation WHERE reason = 'lapse') ORDER BY attempt)")" = failed,done ] ||
        fail "summary lapse crash: the summary request was not asked again"
    sqlite3 "$DB" "SELECT body FROM pic_entry WHERE kind = 'compaction' ORDER BY seq DESC LIMIT 1" | grep -q 'no summary was made' &&
        fail "summary lapse crash: trimmed instead of summarized"
    pic settings --unset lapseMode > /dev/null
    pic check > /dev/null || fail "summary lapse crash: integrity"
    printf 'PASS: a crash at the lapse decision recovers to one lapse compaction\n'
fi

# ---- the trial label and pic usage --by-trial, at a fake server -------------
# A reply with cache reads and writes: input 25, output 12, cacheRead 100, cacheWrite 40.
sed 's/"usage":{"input_tokens":25,"output_tokens":1}/"usage":{"input_tokens":25,"cache_read_input_tokens":100,"cache_creation_input_tokens":40,"output_tokens":1}/' \
    "$here/streams/text.sse" > "$T/cached.sse"
grep -q cache_read_input_tokens "$T/cached.sse" || fail "fixture"
"$SERVER" "$T/port" "$T/log" 120 "sse:$T/cached.sse" &
spid=$!
i=0
while [ ! -s "$T/port" ]; do i=$((i + 1)); [ "$i" -lt 600 ] || fail "server did not start"; sleep 0.05; done
printf '{"providers":{"fake":{"baseUrl":"http://127.0.0.1:%s","api":"anthropic-messages","apiKey":"k","models":[
{"id":"priced","cost":{"input":3,"output":15,"cacheRead":0.3,"cacheWrite":3.75}}]}}}' "$(cat "$T/port")" > "$T/models.json"
export PIC_MODELS_FILE="$T/models.json"
DB="$T/trial.sqlite"
pic --model fake/priced --trial arm-a ask one > /dev/null 2>> "$T/stderr" || fail "ask: $(tail -2 "$T/stderr")"
PIC_TRIAL=arm-a "$PIC" --db "$DB" --workspace "$WS" --model fake/priced ask -c two > /dev/null 2>> "$T/stderr" || fail "ask: $(tail -2 "$T/stderr")"
PIC_TRIAL=ignored "$PIC" --db "$DB" --workspace "$WS" --model fake/priced --trial 'arm b' ask three > /dev/null 2>> "$T/stderr" || fail "ask: $(tail -2 "$T/stderr")"
pic --model fake/priced ask four > /dev/null 2>> "$T/stderr" || fail "ask: $(tail -2 "$T/stderr")"
[ "$(sqlite3 "$DB" "SELECT group_concat(coalesce(trial, 'NULL'), ',') FROM (SELECT trial FROM pic_submission ORDER BY id)")" = 'arm-a,arm-a,arm b,NULL' ] ||
    fail "trial labels: $(sqlite3 "$DB" 'SELECT id, trial FROM pic_submission')"
# Each reply: 25*3 + 12*15 + 100*0.3 + 40*3.75 = 435 per million.
pic usage --by-trial --json > "$T/usage.json" || fail "usage --by-trial"
grep -qx '{"trial":"arm-a","submissions":2,"requests":2,"input":50,"output":24,"cacheRead":200,"cacheWrite":80,"cost":0.00087}' "$T/usage.json" ||
    fail "arm-a: $(cat "$T/usage.json")"
grep -qx '{"trial":"arm b","submissions":1,"requests":1,"input":25,"output":12,"cacheRead":100,"cacheWrite":40,"cost":0.000435}' "$T/usage.json" ||
    fail "arm b: $(cat "$T/usage.json")"
grep -qx '{"trial":null,"submissions":1,"requests":1,"input":25,"output":12,"cacheRead":100,"cacheWrite":40,"cost":0.000435}' "$T/usage.json" ||
    fail "unlabelled: $(cat "$T/usage.json")"
[ "$(wc -l < "$T/usage.json" | tr -d ' ')" = 3 ] || fail "arms: $(cat "$T/usage.json")"
pic usage --by-trial > "$T/usage.txt" || fail "usage --by-trial (text)"
grep -q '^arm-a  *2  *2  *50  *24  *200  *80  *0.000870$' "$T/usage.txt" || fail "text: $(cat "$T/usage.txt")"
grep -q '^(none)  *1  *1  *25 ' "$T/usage.txt" || fail "text unlabelled: $(cat "$T/usage.txt")"
"$PIC" --trial "$(printf '%065d' 0)" dump > /dev/null 2>&1 && fail "a 65-byte label accepted"
"$PIC" --trial "$(printf 'a\tb')" dump > /dev/null 2>&1 && fail "a label with a tab accepted"
PIC_TRIAL="$(printf 'a\nb')" "$PIC" --db "$DB" dump > /dev/null 2>&1 && fail "PIC_TRIAL with a newline accepted"
pic check > /dev/null || fail "integrity"
printf 'PASS: the trial label is kept per request and pic usage --by-trial sums cost and tokens by arm\n'
kill "$spid" 2>/dev/null || :
spid=

# ---- the request cap ----------------------------------------------------------
rm -f "$T/port" "$T"/log/*
"$SERVER" "$T/port" "$T/log" 120 "sse:$here/streams/tool_use.sse" "sse:$here/streams/tool_use.sse" \
    "sse:$here/streams/tool_use.sse" "sse:$here/streams/text.sse" &
spid=$!
i=0
while [ ! -s "$T/port" ]; do i=$((i + 1)); [ "$i" -lt 600 ] || fail "server did not start"; sleep 0.05; done
printf '{"providers":{"fake":{"baseUrl":"http://127.0.0.1:%s","api":"anthropic-messages","apiKey":"k","models":[{"id":"m"}]}}}' \
    "$(cat "$T/port")" > "$T/models.json"
DB="$T/cap.sqlite"
pic --json --model fake/m --max-requests 2 ask 'write notes' > "$T/cap.jsonl" 2> "$T/stderr" || fail "capped ask: $(tail -2 "$T/stderr")"
[ "$(ls "$T/log" | grep -c '\.req$')" = 2 ] || fail "cap: $(ls "$T/log" | grep -c '\.req$') requests sent"
[ "$(sqlite3 "$DB" "SELECT status || ' ' || stop_reason || ' ' || max_requests FROM pic_submission")" = 'stopped request_cap 2' ] ||
    fail "cap: $(sqlite3 "$DB" 'SELECT * FROM pic_submission')"
grep -q '"type":"agent_end",.*"status":"stopped","stopReason":"request_cap"' "$T/cap.jsonl" || fail "cap event: $(grep agent_end "$T/cap.jsonl")"
grep -q '"errorMessage"' "$T/cap.jsonl" && fail "cap: reported as an error"
pic dump | grep -q '^submission .* stopped stop=request_cap ' || fail "cap dump: $(pic dump | grep '^submission')"
pic log | grep -q 'request stopped: request_cap' || fail "cap log: $(pic log)"
pic check > /dev/null || fail "cap: integrity"
PIC_MAX_REQUESTS=1 "$PIC" --db "$DB" --workspace "$WS" --model fake/m ask -c 'go on' > "$T/out" 2>> "$T/stderr" || fail "continue: $(tail -2 "$T/stderr")"
[ "$(ls "$T/log" | grep -c '\.req$')" = 3 ] || fail "continue: requests sent"
[ "$(sqlite3 "$DB" "SELECT status || ' ' || coalesce(stop_reason, '-') FROM pic_submission ORDER BY id DESC LIMIT 1")" = 'stopped request_cap' ] ||
    fail "PIC_MAX_REQUESTS: $(sqlite3 "$DB" 'SELECT * FROM pic_submission')"
pic --model fake/m ask -c 'finish' > "$T/out" 2>> "$T/stderr" || fail "continue: $(tail -2 "$T/stderr")"
grep -q 'Hello' "$T/out" || fail "continue: no answer: $(cat "$T/out")"
grep -q '"text":"finish"' "$T/log/4.req" || fail "continue: the new message was not sent"
grep -q '"tool_result"' "$T/log/4.req" || fail "continue: the capped turn's tool results were not sent"
[ "$(sqlite3 "$DB" "SELECT group_concat(status, ',') FROM (SELECT status FROM pic_submission ORDER BY id)")" = 'stopped,stopped,answered' ] ||
    fail "continue: statuses"
pic check > /dev/null || fail "continue: integrity"
printf 'PASS: --max-requests stops before request N+1, as request_cap, and ask -c continues\n'
kill "$spid" 2>/dev/null || :
spid=

if [ "$FAULTS" = yes ]; then
    # A crash with the first request in flight: its retry counts as the same
    # request, so the cap of 1 still stops before a second.
    for point in after-generation-started:1 after-request-cap:1; do
        rm -f "$T/port" "$T"/log/*
        "$SERVER" "$T/port" "$T/log" 120 "sse:$here/streams/tool_use.sse" &
        spid=$!
        i=0
        while [ ! -s "$T/port" ]; do i=$((i + 1)); [ "$i" -lt 600 ] || fail "server did not start"; sleep 0.05; done
        printf '{"providers":{"fake":{"baseUrl":"http://127.0.0.1:%s","api":"anthropic-messages","apiKey":"k","models":[{"id":"m"}]}}}' \
            "$(cat "$T/port")" > "$T/models.json"
        DB="$T/cap-crash-${point%%:*}.sqlite"
        rc=0
        PIC_CRASH_AT=$point "$PIC" --db "$DB" --workspace "$WS" --model fake/m --max-requests 1 ask 'write notes' > /dev/null 2>&1 || rc=$?
        [ "$rc" = 77 ] || fail "cap crash $point: expected exit 77, got $rc"
        sent=$(ls "$T/log" | grep -c '\.req$' || :)
        pic --model fake/m run 2>> "$T/stderr" || fail "cap crash $point: recovery: $(tail -2 "$T/stderr")"
        [ "$(sqlite3 "$DB" "SELECT status || ' ' || stop_reason FROM pic_submission")" = 'stopped request_cap' ] ||
            fail "cap crash $point: $(sqlite3 "$DB" 'SELECT * FROM pic_submission')"
        [ "$(sqlite3 "$DB" "SELECT count(*) FROM pic_generation WHERE state = 'done'")" = 1 ] || fail "cap crash $point: replies"
        case $point in
        after-generation-started:*) [ "$(ls "$T/log" | grep -c '\.req$')" = $((sent + 1)) ] || fail "cap crash $point: not retried once" ;;
        *) [ "$(ls "$T/log" | grep -c '\.req$')" = "$sent" ] || fail "cap crash $point: a request after the cap" ;;
        esac
        pic check > /dev/null || fail "cap crash $point: integrity"
        kill "$spid" 2>/dev/null || :
        spid=
    done
    printf 'PASS: a crash in flight or at the cap keeps the count from the journal\n'
fi