Skip to content
pi-c Artifact [df61782c0d]
Login

Artifact [df61782c0d]

Artifact df61782c0d65b7f589a0784d765b7cb4c186c2c31de8a174326d254864b94e27:


#!/bin/sh
# Remote control under faults (docs/design/remote-protocol.md, section 3): a phone follows a
# conversation and sends one prompt after another while the relay is killed and started again,
# the network drops and comes back, the stream goes silent, pic remote is stopped for longer than
# its idle timeout and continued, and pic remote is killed and started again. Every command is
# delivered exactly once, and the phone's copy of the conversation, built as the page builds it
# (taken in at marks, synced again after a gap), is exactly what a fresh sync from the start
# gets: every event, in order, none twice. The replies stream slowly, so the phone is also sent
# live text across the faults: each value is the committed reply's text at its offset, rev rises
# within one pic remote process, and none arrives after its request's committed reply. The phone
# holds a push subscription at a loopback push service: every request that ends while pic remote
# runs is announced once (all but the two the kill and the stop may swallow), sealed, naming the
# conversation. Dev builds only (the passphrase and idle seams).
# Usage: test/pic/remote-soak.sh
# Env: PIC, RELAY, PHONE, SERVER (required), SQLITE3.
set -eu
PIC=${PIC:?set PIC to the pic binary}
SERVER=${SERVER:?set SERVER to the fake_server binary}
RELAY=${RELAY:?set RELAY to the fake_relay binary}
PHONE=${PHONE:?set PHONE to the fake_phone binary}
SQLITE3=${SQLITE3:-sqlite3}
here=$(cd "$(dirname "$0")" && pwd)
S=$here/streams
T=$(mktemp -d "${TMPDIR:-/tmp}/pic-soak.XXXXXX")
# pic keeps user state under HOME: never the real one.
export HOME="$T/home"
export PIC_ORIGIN=person PIC_TEST_RC_TEMP="$T/tmp" # a person's conversations, in workspaces pic remote lists
mkdir -p "$HOME/.pic"
unset PIC_KEY_FD
export ANTHROPIC_API_KEY=pic-soak-test-key PIC_PI_EXPORT=0 PIC_TEST_PASSPHRASE=soak-test-pass
export PIC_TEST_RC_PUSH_HTTP=1 PIC_TEST_RC_PUSH_GAP_MS=0 PIC_TEST_RC_IDLE=4 FAKE_RELAY_BEAT_MS=1000 FAKE_RELAY_STATE="$T/relay.state" FAKE_PHONE_PING_MS=2000
N=6
pids=
cleanup() {
    exec 2> /dev/null
    for p in $pids; do kill -CONT "$p" 2>/dev/null || true; kill -9 "$p" 2>/dev/null || true; done
    rm -rf -- "$T"
}
trap cleanup EXIT HUP INT TERM
# and a pic remote this run starts ends by itself (dev builds) should the run be killed before cleanup
export PIC_TEST_RC_DEADLINE_S=1800
fail() {
    printf 'FAIL: %s\n' "$*" >&2
    for f in "$T"/*.out "$T"/*.err "$T"/*.run; do [ -s "$f" ] && { printf -- '--- %s\n' "$f" >&2; tail -25 "$f" >&2; }; done
    exit 1
}
bg() { pids="$pids $1"; }
await() { # FILE PATTERN [TRIES]: the fixed string in FILE (50 ms a try, 30 s by default)
    i=0
    until grep -qF -- "$2" "$1" 2>/dev/null; do
        i=$((i + 1))
        [ "$i" -lt "${3:-600}" ] || fail "timed out waiting for $2 in $1"
        sleep 0.05
    done
}
exists() { # FILE [TRIES]
    i=0
    until [ -e "$1" ]; do
        i=$((i + 1))
        [ "$i" -lt "${2:-1200}" ] || fail "timed out waiting for $1"
        sleep 0.05
    done
}
gone() { rc=0; wait "$1" || rc=$?; }

nrelay=0
relay() { # the relay, on the port it had before once it has one; mailboxes kept in its state file
    nrelay=$((nrelay + 1))
    rm -f "$T/relay.port"
    if [ -n "${PORT:-}" ]; then
        FAKE_RELAY_PORT=$PORT "$RELAY" "$T/relay.port" 900 soak-invite > "$T/relay$nrelay.out" 2>&1 &
    else
        "$RELAY" "$T/relay.port" 900 soak-invite > "$T/relay$nrelay.out" 2>&1 &
    fi
    RLP=$!
    bg $RLP
    exists "$T/relay.port"
    PORT=$(cat "$T/relay.port")
}
relay
BASE="http://127.0.0.1:$PORT"
"$PIC" settings remote.relay "$BASE" > /dev/null
"$PIC" settings remote.invite soak-invite > /dev/null
ctl() { curl -s -X POST "$BASE/_test/$1" > /dev/null; }

# A paired phone.
mkfifo "$T/pair.in"
"$PIC" remote pair --pipe < "$T/pair.in" > "$T/pair.out" 2> "$T/pair.err" &
PP=$!
bg $PP
exec 3> "$T/pair.in"
await "$T/pair.out" '"type":"offer"'
URL=$(sed -n 's/.*"url":"\([^"]*\)".*/\1/p' "$T/pair.out" | head -1)
mkdir "$T/ph"
"$PHONE" "$T/ph" pair "$URL" "Soak Phone" > "$T/phpair.out" 2>&1 &
PH=$!
bg $PH
await "$T/pair.out" '"type":"code"'
echo y >&3
gone $PH
[ "$rc" = 0 ] || fail "pair: phone exit $rc"
gone $PP
exec 3>&-

# A conversation, and a model with a reply for each prompt.
specs=
k=1
cp "$S/text.sse" "$T/text.sse" # the word list below is split on spaces; $T has none, the checkout may
specs=sse:$T/text.sse # the first question, answered at once
# Prompt K gets "rK alpha beta gamma delta epsilon.", a word every ~300 ms: slow enough for live values
# to be sent (at most every 250 ms) across a fault, short enough for the run to stay a minute or two.
ev() { printf 'event: %s\ndata: %s\n\n' "$1" "$2"; }
delta() { ev content_block_delta "{\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"text_delta\",\"text\":\"$1\"}}"; }
while [ "$k" -le "$N" ]; do
    {
        ev message_start '{"type":"message_start","message":{"id":"msg_s","type":"message","role":"assistant","model":"m","content":[],"stop_reason":null,"usage":{"input_tokens":5,"output_tokens":1}}}'
        ev content_block_start '{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}'
        delta "r$k "
        for w in alpha beta gamma delta; do
            for p in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20; do ev ping '{"type": "ping"}'; done
            delta "$w "
        done
        for p in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20; do ev ping '{"type": "ping"}'; done
        delta 'epsilon.'
        ev content_block_stop '{"type":"content_block_stop","index":0}'
        ev message_delta '{"type":"message_delta","delta":{"stop_reason":"end_turn","stop_sequence":null},"usage":{"output_tokens":12}}'
        ev message_stop '{"type":"message_stop"}'
    } > "$T/slow$k.sse"
    specs="$specs slow:$T/slow$k.sse:40"
    k=$((k + 1))
done
mkdir "$T/log" "$T/ws" "$T/plog"
# The push service: 201 to every push (more than there are requests).
"$SERVER" "$T/pport" "$T/plog" 900 status:201:- status:201:- status:201:- status:201:- status:201:- status:201:- status:201:- status:201:- status:201:- status:201:- &
bg $!
exists "$T/pport"
EP="http://127.0.0.1:$(cat "$T/pport")/push/soak"
# shellcheck disable=SC2086
"$SERVER" "$T/sport" "$T/log" 900 $specs &
bg $!
exists "$T/sport"
printf '{"providers":{"fake":{"baseUrl":"http://127.0.0.1:%s","api":"anthropic-messages","apiKey":"$ANTHROPIC_API_KEY","models":[{"id":"m"}]}}}' \
    "$(cat "$T/sport")" > "$T/models.json"
export PIC_MODELS_FILE="$T/models.json"
DB="$T/j.sqlite"
"$PIC" --db "$DB" --workspace "$T/ws" --model fake/m ask 'the first question' > /dev/null 2> "$T/ask.err" || fail "ask: $(cat "$T/ask.err")"
q() { "$SQLITE3" "$DB" "$1"; }
SID=$(q "SELECT id FROM pic_session")
SESS="$DB/$SID"

nr=0
remote() {
    nr=$((nr + 1))
    "$PIC" remote > "$T/remote$nr.out" 2> "$T/remote$nr.err" &
    RP=$!
    bg $RP
    await "$T/remote$nr.out" 'pic remote: connected'
}
remote

# The phone: follow from the start, then each prompt; after sending one it waits for the test to
# break something, then for the prompt's answer and the request's end.
{
    printf 'send {"type":"sync","session":"%s","seq":0}\n' "$SESS"
    printf 'expect {"type":"sync","session":"%s"\n' "$SESS"
    printf 'send %s\nsend {"type":"ping"}\nexpect {"type":"pong"}\n' "$("$PHONE" "$T/ph" pushkeys "$EP")"
    k=1
    while [ "$k" -le "$N" ]; do
        key=$(printf 'soak-prompt-%07d' "$k")
        printf 'cmd %s {"type":"command","session":"%s","key":"%s","payload":{"type":"prompt","message":"soak %d"}}\n' "$key" "$SESS" "$key" "$k"
        printf 'mark sent%d\nwaitfor go%d\n' "$k" "$k"
        printf 'seen "key":"%s"\nseen %s","status":"answered"\n' "$key" "$key"
        k=$((k + 1))
    done
    printf 'sleep 3000\nreplica %s\nkeyed\n' "$T/live.rep"
} > "$T/ph.script"
"$PHONE" "$T/ph" run < "$T/ph.script" > "$T/ph.run" 2>&1 &
PR=$!
bg $PR

fault() { # K: break something while prompt K is under way
    case $1 in
    1) # the relay killed mid-stream, and started again where it was
        kill -9 "$RLP"
        gone "$RLP"
        sleep 1
        relay
        what='the relay killed and started again'
        ;;
    2) # the network drops for 3 s
        ctl 'down?3000'
        sleep 3
        what='the network dropped and restored'
        ;;
    3) # pic remote stopped for longer than its idle timeout (and the jump check), then continued
        kill -STOP "$RP"
        sleep 12
        kill -CONT "$RP"
        what='pic remote stopped for 12 s and continued'
        ;;
    4) # pic remote killed and started again
        kill -9 "$RP"
        gone "$RP"
        remote
        what='pic remote killed and started again'
        ;;
    5) # every stream goes silent, keepalive and all, for longer than the idle timeout
        ctl 'mute?7000'
        sleep 7
        what='the streams silent for 7 s'
        ;;
    6) # the relay ends every stream
        ctl cut
        what='every stream cut'
        ;;
    esac
}
k=1
while [ "$k" -le "$N" ]; do
    exists "$T/ph/sent$k"
    case $k in 4 | 5) eval "L$k=$(wc -l < "$T/ph.run" | tr -d ' ')" ;; esac # live lines before it are the first process's
    fault "$k"
    touch "$T/ph/go$k"
    printf 'fault %d: %s\n' "$k" "$what"
    k=$((k + 1))
done
gone $PR
[ "$rc" = 0 ] || fail "the phone: exit $rc"

# Exactly once: one request per key, each answered, and nothing else.
k=1
while [ "$k" -le "$N" ]; do
    key=$(printf 'soak-prompt-%07d' "$k")
    [ "$(q "SELECT count(*) || ' ' || group_concat(status) FROM pic_submission WHERE request_key LIKE 'rc:%:$key'")" = "1 answered" ] ||
        fail "prompt $k: $(q "SELECT request_key, status, error FROM pic_submission WHERE request_key LIKE 'rc:%:$key'")"
    [ "$(q "SELECT count(*) FROM pic_entry WHERE kind = 'user' AND body = 'soak $k'")" = 1 ] || fail "prompt $k: entries"
    k=$((k + 1))
done
[ "$(q 'SELECT count(*) FROM pic_submission')" = $((N + 1)) ] || fail "requests: $(q 'SELECT request_key FROM pic_submission')"
"$PIC" --db "$DB" check > /dev/null || fail "integrity"
printf 'PASS: through every fault, each of %d prompts from the phone became exactly one request\n' "$N"

# In order, none missed, none twice: the live copy is what a fresh sync from the start gets.
mkdir "$T/fresh"
cp "$T/ph/pairing" "$T/fresh/pairing"
printf 'send {"type":"sync","session":"%s","seq":0}\nexpect {"type":"sync","session":"%s"\nsleep 1000\nreplica %s\nkeyed\n' \
    "$SESS" "$SESS" "$T/fresh.rep" | "$PHONE" "$T/fresh" run > "$T/fresh.run" 2>&1 || fail "fresh sync"
[ -s "$T/live.rep" ] || fail "the phone holds nothing"
cmp -s "$T/live.rep" "$T/fresh.rep" || fail "the phone's copy differs from a fresh sync: $(diff "$T/live.rep" "$T/fresh.rep" | head -20)"
sort -s -n -k1,1 "$T/live.rep" | cmp -s - "$T/live.rep" || fail "events out of seq order"
[ "$(grep -c '"type":"agent_end"' "$T/live.rep")" = $((N + 1)) ] || fail "agent_end count: $(grep -c agent_end "$T/live.rep")"
grep -q '^gap$' "$T/ph.run" || grep -q '^session$' "$T/ph.run" || fail "no fault was seen by the phone"
printf 'PASS: the phone'"'"'s copy has every event in order and none twice, each with its sync'"'"'s key (%s events, %s sessions)\n' \
    "$(wc -l < "$T/live.rep" | tr -d ' ')" "$(grep -c '^session$' "$T/ph.run")"
grep -qF 'back after' "$T/remote$nr.out" "$T"/remote*.out || fail "pic remote did not notice the stop"
printf 'PASS: pic remote noticed the stop and reconnected at once\n'

# Live text: values were sent across the faults, each the committed reply's text from its offset,
# one head seq per request, rev rising within one pic remote process, none behind its committed reply.
grep -n '^<- {"type":"live"' "$T/ph.run" | sed 's/^\([0-9]*\):<- /{"n":\1,"m":/; s/$/}/' > "$T/live.lines"
{ printf '['; paste -sd, "$T/live.lines"; printf ']'; } > "$T/live.json"
lq() { "$SQLITE3" :memory: "WITH l(k, v) AS (SELECT key, value FROM json_each(readfile('$T/live.json'))) $1"; }
[ "$(lq "SELECT count(*) FROM l WHERE json_extract(v, '\$.m.session') != '$SESS'")" = 0 ] || fail "live: a value for another conversation"
livereqs=0
k=1
while [ "$k" -le "$N" ]; do
    q "SELECT json_extract(body, '\$[0].text') FROM pic_entry WHERE kind IN ('answer', 'assistant') AND json_extract(body, '\$[0].text') LIKE 'r$k %'" | tr -d '\n' > "$T/final$k.txt"
    [ "$(cat "$T/final$k.txt")" = "r$k alpha beta gamma delta epsilon." ] || fail "live: reply $k: $(cat "$T/final$k.txt") / $(q "SELECT seq, kind, substr(body, 1, 70) FROM pic_entry ORDER BY seq DESC LIMIT 4")"
    mine="json_extract(v, '\$.m.payload.text') LIKE 'r$k %'"
    [ "$(lq "SELECT count(*) FROM l WHERE $mine AND substr(CAST(readfile('$T/final$k.txt') AS TEXT), json_extract(v, '\$.m.payload.offset') + 1,
        length(json_extract(v, '\$.m.payload.text'))) != json_extract(v, '\$.m.payload.text')")" = 0 ] || fail "live: a value of request $k is not its reply's text"
    n=$(lq "SELECT count(*) FROM l WHERE $mine")
    if [ "$n" -gt 0 ]; then
        livereqs=$((livereqs + 1))
        [ "$(lq "SELECT count(DISTINCT json_extract(v, '\$.m.seq')) FROM l WHERE $mine")" = 1 ] || fail "live: request $k: more than one head seq"
        mend=$(grep -n '"type":"message_end"' "$T/ph.run" | grep -F "r$k alpha beta gamma delta epsilon." | head -1 | cut -d: -f1)
        [ -n "$mend" ] || fail "live: the phone never got reply $k"
        [ "$(lq "SELECT count(*) FROM l WHERE $mine AND json_extract(v, '\$.n') > $mend")" = 0 ] || fail "live: a value of request $k after its committed reply"
    fi
    k=$((k + 1))
done
[ "$(lq 'SELECT count(*) FROM l')" -ge "$N" ] && [ "$livereqs" -ge 3 ] || fail "live: $(lq 'SELECT count(*) FROM l') values for $livereqs requests"
[ "$(lq "SELECT count(DISTINCT json_extract(v, '\$.m.seq')) FROM l")" = "$livereqs" ] || fail "live: two requests share a head seq"
revrise() { # N-RANGE: rev strictly rises over the live values whose line number meets it
    lq "SELECT count(*) FROM (SELECT json_extract(v, '\$.m.payload.rev') r, lag(json_extract(v, '\$.m.payload.rev')) OVER (ORDER BY json_extract(v, '\$.n')) p
        FROM l WHERE $1) WHERE p IS NOT NULL AND r <= p"
}
[ "$(revrise "json_extract(v, '\$.n') <= $L4")" = 0 ] || fail "live: rev fell in the first pic remote"
[ "$(revrise "json_extract(v, '\$.n') > $L5")" = 0 ] || fail "live: rev fell in the second pic remote"
printf 'PASS: the replies streamed as live values (%s, for %d requests): each its reply'"'"'s text, a head seq a request, rev rising in a process, none after its reply\n' \
    "$(lq 'SELECT count(*) FROM l')" "$livereqs"

# Notifications: each push opens, names the conversation, is one request's and a request is announced once;
# a request that ended while pic remote was killed or stopped may be missed, so all but two.
pushes() { ls "$T/plog" | grep -c '\.req$' || true; }
i=0
until [ "$(pushes)" -ge "$((N - 2))" ]; do i=$((i + 1)); [ "$i" -lt 200 ] || fail "push: $(pushes) pushes for $N requests"; sleep 0.05; done
sleep 1
np=$(pushes)
[ "$np" -le "$N" ] || fail "push: $np pushes for $N requests"
: > "$T/push.seqs"
: > "$T/push.bodies"
for f in "$T"/plog/*.req; do
    "$PHONE" "$T/ph" pushread "$f" > "$T/push.json" || fail "push: $f does not open"
    [ "$("$SQLITE3" :memory: "SELECT json_extract(readfile('$T/push.json'), '\$.session')")" = "$SESS" ] || fail "push: names $(cat "$T/push.json")"
    "$SQLITE3" :memory: "SELECT json_extract(readfile('$T/push.json'), '\$.seq')" >> "$T/push.seqs"
    "$SQLITE3" :memory: "SELECT json_extract(readfile('$T/push.json'), '\$.body')" >> "$T/push.bodies"
done
[ "$(sort -u "$T/push.seqs" | wc -l | tr -d ' ')" = "$np" ] || fail "push: a request announced twice: $(tr '\n' ' ' < "$T/push.seqs")"
[ "$(grep -c '^r[1-6] alpha' "$T/push.bodies")" = "$np" ] || fail "push: bodies: $(cat "$T/push.bodies")"
[ "$(sort -u "$T/push.bodies" | wc -l | tr -d ' ')" = "$np" ] || fail "push: a reply announced twice: $(cat "$T/push.bodies")"
printf 'PASS: %d of %d phone requests announced by a sealed push naming the conversation, none twice\n' "$np" "$N"

# The relay stops answering with no word (stopped, its connections left open): the stream is dropped
# at the idle timeout (4 s here), so within that and the status file's 5 s pic remote status says
# reconnecting, not connected; once the relay answers again pic remote is back on its own, and the
# phone is answered.
sst() { "$PIC" remote status --json | sed -n 's/.*"state":"\([^"]*\)".*/\1/p'; }
i=0; until [ "$(sst)" = connected ]; do i=$((i + 1)); [ "$i" -lt 300 ] || fail "silent: not connected first: $("$PIC" remote status)"; sleep 0.1; done
kill -STOP "$RLP"
t0=$(date +%s)
i=0; while [ "$(sst)" = connected ]; do i=$((i + 1)); [ "$i" -lt 300 ] || { kill -CONT "$RLP"; fail "silent: still connected after 30 s: $("$PIC" remote status)"; }; sleep 0.1; done
t1=$(date +%s)
"$PIC" remote status > "$T/silent.out"
kill -CONT "$RLP"
grep -qF ': reconnecting to ' "$T/silent.out" || fail "silent: $(cat "$T/silent.out")"
i=0; until [ "$(sst)" = connected ]; do i=$((i + 1)); [ "$i" -lt 900 ] || fail "silent: not back: $("$PIC" remote status)"; sleep 0.1; done
printf 'send {"type":"ping"}\nexpect {"type":"pong"}\n' | "$PHONE" "$T/ph" run > "$T/silent.run" 2>&1 || fail "silent: the phone after: $(cat "$T/silent.run")"
printf 'PASS: a relay that goes silent is reported within %d s (%s) and pic remote is back when it answers\n' "$((t1 - t0))" \
    "$(head -1 "$T/silent.out" | sed 's/^pic remote is running (pid [0-9]*): //; s/;.*//')"
kill "$RP"
gone "$RP"
[ "$rc" = 0 ] || fail "stop: exit $rc"