Skip to content
pi-c Artifact [d261150e07]
Login

Artifact [d261150e07]

Artifact d261150e070d98be5717adbe917c995762a009fb7d11c96e2e594e1aaa681271:


#!/bin/sh
# Remote control stream lifecycle (recycle, ghost, deaf, lost), journal yield, and long paging.
# Usage: test/pic/remote_stream.sh [--no-faults]
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}
FAULTS=1
[ "${1:-}" = --no-faults ] && FAULTS=0
here=$(cd "$(dirname "$0")" && pwd)
S=$here/streams
T=$(mktemp -d "${TMPDIR:-/tmp}/pic-remote-stream.XXXXXX")
export HOME="$T/home"
. "$here/remote_lib.sh"

init_paired 2

serve "sse:$S/text.sse"
pic ask 'first question' > /dev/null 2> "$T/ask.err" || fail "ask: $(cat "$T/ask.err")"
SID=$(q "SELECT id FROM pic_session ORDER BY updated_ms DESC LIMIT 1")
SESS="$DB/$SID"
remote

# A newer pic waiting to migrate a journal pic remote has open (an older pic remote: the seam
# PIC_TEST_HOLDER_SCHEMA): it lets go of the journal, the migration goes ahead instead of failing,
# and it serves the workspace again after.
kill "$RP"
gone "$RP"
nr=$((nr + 1))
RO="$T/remote$nr.out"
PIC_TEST_HOLDER_SCHEMA=18 "$PIC" remote > "$RO" 2> "$T/remote$nr.err" &
RP=$!
bg $RP
await "$RO" 'pic remote: connected'
cur=$(q "SELECT value FROM pic_meta WHERE key='schema_version'")
q "DROP TABLE pic_verdict; UPDATE pic_meta SET value='18' WHERE key='schema_version'"
# A phone pinging all along over a slow link keeps a post on its way to the relay at every tick:
# that holds no journal, so it does not hold up the yield.
{
    printf 'send {"type":"ping"}\nexpect {"type":"pong"}\nmark yield-go\n'
    k=0
    while [ $k -lt 300 ]; do printf 'send {"type":"ping"}\nsleep 50\n'; k=$((k + 1)); done
} > "$T/yieldping.script"
rm -f "$T/ph1/yield-go"
script "$T/ph1" < "$T/yieldping.script"
YP=$PR
i=0; until [ -e "$T/ph1/yield-go" ]; do i=$((i + 1)); [ "$i" -lt $TRIES ] || fail "yield: the phone did not start"; sleep 0.05; done
ctl "slow?500"
pic check > /dev/null 2> "$T/yield.err" || { ctl "slow?0"; fail "yield: not migrated: $(cat "$T/yield.err")"; }
ctl "slow?0"
done_ok $YP "yield: the pinging phone"
[ "$(q "SELECT value FROM pic_meta WHERE key='schema_version'")" = "$cur" ] || fail "yield: version not $cur"
await "$RO" "pic remote: let go of "
await "$RO" "pic remote: serving "
script "$T/ph1" <<EOS
send {"type":"sessions"}
expect "session":"$SESS"
EOS
done_ok $PR "after the migration"
kill "$RP"
gone "$RP"
remote
printf 'PASS: pic remote lets go of a journal a newer pic waits to migrate, and serves it again after\n'

# The relay ends every stream after a while: a clean end of one that lasted (30 s; the seam makes it
# 1 s here, and the relay ends them after 1.5 s) is a recycle, reconnected at once with no line and
# no attempt counted, and pic remote status says when the stream opened and how many recycles. A
# stream that comes back after more than 10 s is logged.
kill "$RP"
gone "$RP"
export PIC_TEST_RC_RECYCLE_MS=1000
remote
unset PIC_TEST_RC_RECYCLE_MS
ctl 'life?1500'
i=0
until "$PIC" remote status --json > "$T/recycle.json" && [ "$("$SQLITE3" :memory: "SELECT json_extract(readfile('$T/recycle.json'), '\$.recycles') >= 2")" = 1 ]; do
    i=$((i + 1)); [ "$i" -lt 300 ] || fail "recycle: $(cat "$T/recycle.json")"; sleep 0.1
done
ctl 'life?0'
grep -qF 'the stream ended' "$RO" && fail "recycle: logged: $(grep -F 'the stream ended' "$RO")"
[ "$("$SQLITE3" :memory: "SELECT json_extract(readfile('$T/recycle.json'), '\$.attempts')")" = 0 ] || fail "recycle: attempts: $(cat "$T/recycle.json")"
await "$HOME/.pic/remote.status" '"state":"connected"'
"$PIC" remote status --json | grep -qE '"streamOpenedAt":"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z"' || fail "recycle: opened: $("$PIC" remote status --json)"
"$PIC" remote status | grep -qE 'connected to .*, stream open since [0-9]{2}:[0-9]{2}:[0-9]{2}, [0-9]+ recycles, last heard from it [0-9]+ s ago, (last record [0-9]+ s ago|no record yet);' || fail "recycle: status: $("$PIC" remote status)"
script "$T/ph1" <<EOS
send {"type":"sessions"}
expect "session":"$SESS"
EOS
done_ok $PR "recycle: the phone"
ctl 'down?11000'
await "$RO" 'the stream reopened '
grep -E '^[0-9]{4}-[0-9]{2}-[0-9]{2}.*pic remote: the stream reopened [0-9.]+ s after it ended' "$RO" > /dev/null || fail "recycle: slow: $(grep -F 'reopened' "$RO")"
grep -qF 'the stream ended' "$RO" || fail "recycle: the cut stream was not logged"
kill "$RP"
gone "$RP"
remote
printf 'PASS: a stream the relay ends after it lasted is reconnected quietly and counted; a slow way back is logged\n'

# A ghost stream (keepalives, every 300 ms here, and no records, as after a relay deploy): status
# says the relay was heard just now but tells the last record apart, so it does not read as a
# stream that works.
kill "$RP"
gone "$RP"
remote
ctl "beat?300"
script "$T/ph1" <<EOS
send {"type":"ping"}
expect {"type":"pong"}
EOS
done_ok $PR "ghost: a ping first"
ctl deaf
i=0
until "$PIC" remote status > "$T/ghost.out" && grep -qE 'connected to .*, last heard from it [0-5] s ago, last record ([7-9]|[1-9][0-9]) s ago;' "$T/ghost.out"; do
    i=$((i + 1)); [ "$i" -lt 300 ] || fail "ghost: status: $(cat "$T/ghost.out")"; sleep 0.1
done
"$PIC" remote status --json > "$T/ghost.json"
[ "$("$SQLITE3" :memory: "SELECT json_extract(readfile('$T/ghost.json'), '\$.recordAt') < json_extract(readfile('$T/ghost.json'), '\$.heardAt')")" = 1 ] ||
    fail "ghost: json: $(cat "$T/ghost.json")"
printf 'PASS: a stream bringing keepalives and no records reads as heard but with an old last record (%s)\n' \
    "$(head -1 "$T/ghost.out" | sed 's/.*last heard/last heard/; s/;.*//')"

# The same ghost with no phone on screen to notice: once it has brought no record for
# PIC_TEST_RC_QUIET_MS, however many keepalives came, pic remote opens it again quietly, so a phone
# that comes to it afterwards is heard; it is counted as a recycle and not logged.
kill "$RP"
gone "$RP"
export PIC_TEST_RC_QUIET_MS=1500
remote
unset PIC_TEST_RC_QUIET_MS
i=0
until "$PIC" remote status > "$T/heard.out" && grep -qE 'connected to .*, last heard from it [0-9]+ s ago, no record yet;' "$T/heard.out"; do
    i=$((i + 1)); [ "$i" -lt 300 ] || fail "heard: status: $(cat "$T/heard.out")"; sleep 0.1
done
"$PIC" remote status --json | grep -qE '"heardAt":"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z"' || fail "heard: json: $("$PIC" remote status --json)"
ctl deaf
script "$T/ph1" <<EOS
send {"type":"ping"}
expect {"type":"pong"}
EOS
done_ok $PR "deaf, no phone on screen"
grep -qF 'the stream ended' "$RO" && fail "deaf, no phone: logged: $(grep -F 'the stream ended' "$RO")"
ctl "beat?15000"
printf 'PASS: a stream that brings keepalives and no records is reopened quietly with no phone on screen\n'

# A path that dies both ways at once (pic's stream brings nothing more, not even a keepalive, and
# a post gets no answer): the failed post ends the stream's read at once, so the next ping is heard
# in seconds rather than after the 45 s idle timeout.
kill "$RP"
gone "$RP"
remote
ctl lost
script "$T/ph1" <<EOS
send {"type":"ping"}
expect {"type":"pong"}
mark go-lost
send {"type":"ping"}
expect {"type":"pong"}
EOS
i=0; until [ -e "$T/ph1/go-lost" ]; do i=$((i + 1)); [ "$i" -lt $TRIES ] || fail "lost: $(cat "$T/ph1.run")"; sleep 0.05; done
t0=$(date +%s)
done_ok $PR "lost: a ping after a lost post"
t1=$(date +%s)
[ $((t1 - t0)) -lt 15 ] || fail "lost: the second ping took $((t1 - t0)) s"
grep -qF 'a post to the relay got no answer; reconnecting' "$RO" || fail "lost: no line: $(cat "$RO")"
grep -qF 'the stream ended (asked to reconnect)' "$RO" || fail "lost: the stream was not reopened: $(cat "$RO")"
kill "$RP"
gone "$RP"
remote
printf 'PASS: a post with no answer reopens a dead stream at once: the next ping answered in %d s\n' "$((t1 - t0))"

# Paging back a long thread (5,000 entries) over a slow link to the relay: an earlier page is a
# fetch of at most 200 entries before the phone's first, ended by a fetch message that says
# whether there is more; the old sync from earlier still replays to the end. Posting is off the
# loop, so a second phone's ping is answered within a second throughout, its small post not
# waiting behind the first phone's large ones.
kill "$RP"
gone "$RP"
mkdir "$T/longws"
LONG="$T/long.sqlite"
"$PIC" --db "$LONG" --workspace "$T/longws" check > /dev/null 2>&1 || fail "long: check"
lpad=$(head -c 2000 /dev/zero | tr '\0' y)
"$SQLITE3" "$LONG" "BEGIN;
  INSERT INTO pic_session(id, created_ms, updated_ms) VALUES('l0001', 1, 1);
  INSERT INTO pic_submission(id, request_key, content, status, session_id)
    SELECT value, 'long-' || value, 'question ' || value, 'answered', 'l0001' FROM generate_series(1, 500);
  INSERT INTO pic_entry(submission_id, kind, body) SELECT 1 + (value - 1) / 10, iif((value - 1) % 10 = 0, 'user', 'assistant'),
    iif((value - 1) % 10 = 0, 'asked ' || value || ' $lpad', json_array(json_object('type', 'text', 'text', 'said ' || value || ' $lpad')))
    FROM generate_series(1, 5000);
  COMMIT" || fail "long: rows"
LS="$LONG/l0001"
lseq() { "$SQLITE3" "$LONG" "$1"; }
LMIN=$(lseq "SELECT min(seq) FROM pic_entry")
LTOP=$(lseq "SELECT max(seq) FROM pic_entry")
LLAST=$(lseq "SELECT min(seq) FROM pic_entry WHERE submission_id = 500")
LMID=$(lseq "SELECT min(seq) - 1 FROM pic_entry WHERE submission_id = 481")
[ "$((LTOP - LMIN))" = 4999 ] || fail "long: seqs $LMIN..$LTOP"
nr=$((nr + 1))
RO="$T/remote$nr.out"
"$PIC" remote > "$RO" 2> "$T/remote$nr.err" &
RP=$!
bg $RP
await "$RO" 'pic remote: connected'
ctl "slow?32768"
ping_ms=1000
if [ "${FAULTS:-1}" = 1 ] && { [ -n "${ASAN_OPTIONS:-}" ] || [ "${PIC_TEST_SLOW:-}" = 1 ]; }; then
    case "$PIC" in */release/*) ;; *) ping_ms=2500 ;; esac
fi
{
    printf 'send {"type":"ping"}\nexpect {"type":"pong"}\nmark ping-go\n'
    k=0
    while [ $k -lt 80 ]; do printf 'ping %s\nsleep 250\n' "$ping_ms"; k=$((k + 1)); done
} > "$T/longping.script"
rm -f "$T/ph4/ping-go"
script "$T/ph4" < "$T/longping.script"
P4=$PR
i=0; until [ -e "$T/ph4/ping-go" ]; do i=$((i + 1)); [ "$i" -lt $TRIES ] || fail "long: the other phone did not start"; sleep 0.05; done
B1=$LLAST
{
    printf 'send {"type":"sync","session":"%s","seq":%s}\n' "$LS" "$LMID"
    printf 'expect {"type":"sync","session":"%s","seq":%s,\n' "$LS" "$LTOP"
    printf 'send {"type":"sync","session":"%s","seq":-1}\n' "$LS"
    printf 'expect {"type":"sync","session":"%s","seq":%s,\n' "$LS" "$LTOP"
    for k in 1 2 3 4 5; do
        printf 'send {"type":"fetch","session":"%s","key":"k-long-fetch-0000%s","payload":{"before":%s,"limit":20}}\n' "$LS" "$k" "$B1"
        B1=$((B1 - 20))
        printf 'expect {"type":"fetch","session":"%s","seq":%s,"key":"k-long-fetch-0000%s","payload":{"done":true,"more":true}}\n' "$LS" "$B1" "$k"
    done
    printf 'mark long-done\n'
} > "$T/long.script"
script "$T/ph1" < "$T/long.script"
P1=$PR
done_ok $P4 "long: the other phone"
late=$(grep -c '^late pong$' "$T/ph4.run" || true)
slowest=$(sed -n 's/^pong \([0-9]*\) ms$/\1/p' "$T/ph4.run" | sort -n | tail -1)
[ "$late" = 0 ] || fail "long: $late of the other phone's 80 pings waited over ${ping_ms} ms (slowest answered $slowest ms)"
[ "$(grep -c '^pong [0-9]* ms$' "$T/ph4.run")" = 80 ] || fail "long: pongs: $(grep -c '^pong' "$T/ph4.run")"
done_ok $P1 "long: earlier pages"
# Each page is the 20 entries before the last: no entry at or past its before, none twice.
B1=$LLAST
for k in 1 2 3 4 5; do
    seqs=$(grep -F '"key":"k-long-fetch-0000'"$k"'"' "$T/ph1.run" | grep -F '{"type":"event"' | sed -n 's/.*"seq":\([0-9]*\),.*/\1/p' | sort -un)
    [ "$(printf '%s\n' "$seqs" | wc -l | tr -d ' ')" = 20 ] || fail "long: page $k has $(printf '%s\n' "$seqs" | wc -l) entries"
    [ "$(printf '%s\n' "$seqs" | head -1)" = $((B1 - 20)) ] && [ "$(printf '%s\n' "$seqs" | tail -1)" = $((B1 - 1)) ] ||
        fail "long: page $k is $(printf '%s\n' "$seqs" | head -1)..$(printf '%s\n' "$seqs" | tail -1), not before $B1"
    B1=$((B1 - 20))
done
grep -F '"key":"k-long-fetch-00001"' "$T/ph1.run" | grep -qF '"type":"agent_end"' || fail "long: a whole request's end is not on its page"
ctl "slow?0"
# A larger limit is held to 200 entries; a page that reaches the first entry says there is no more.
script "$T/ph1" <<EOS
send {"type":"fetch","session":"$LS","key":"k-long-fetch-big001","payload":{"before":$LLAST,"limit":1000}}
expect {"type":"fetch","session":"$LS","seq":$((LLAST - 200)),"key":"k-long-fetch-big001","payload":{"done":true,"more":true}}
send {"type":"fetch","session":"$LS","key":"k-long-fetch-first1","payload":{"before":$((LMIN + 15)),"limit":200}}
expect {"type":"fetch","session":"$LS","seq":$LMIN,"key":"k-long-fetch-first1","payload":{"done":true,"more":false}}
send {"type":"fetch","session":"$LS","key":"k-long-fetch-bad001","payload":{"after":3,"to":9}}
expect {"type":"error","key":"k-long-fetch-bad001","payload":{"code":"not_available"
send {"type":"fetch","session":"$LS","payload":{"before":$LLAST,"limit":20}}
expect {"type":"error","payload":{"code":"bad_message"
EOS
done_ok $PR "long: limits"
[ "$(grep -F '"key":"k-long-fetch-big001"' "$T/ph1.run" | grep -F '{"type":"event"' | sed -n 's/.*"seq":\([0-9]*\),.*/\1/p' | sort -u | wc -l | tr -d ' ')" = 200 ] ||
    fail "long: a limit of 1000 was not held to 200"
grep -F '"key":"k-long-fetch-first1"' "$T/ph1.run" | grep -qF '"type":"agent_start"' || fail "long: the first request's start is not on the first page"
grep -F '"seq":' "$T/ph1.run" | grep -F '{"type":"event"' | grep -vF '"key":"' | grep -qF '"long-' &&
    fail "long: a fetch without a key was answered with events"
# A page is held to about 2 MiB as well: entries of 200 KB go about ten a page, the rest the next.
"$SQLITE3" "$LONG" "BEGIN;
  INSERT INTO pic_session(id, created_ms, updated_ms) VALUES('l0002', 1, 1);
  INSERT INTO pic_submission(id, request_key, content, status, session_id)
    SELECT 500 + value, 'wide-' || value, 'wide ' || value, 'answered', 'l0002' FROM generate_series(1, 3);
  INSERT INTO pic_entry(submission_id, kind, body) SELECT 501 + (value - 1) / 10, 'assistant',
    json_array(json_object('type', 'text', 'text', value || hex(zeroblob(100000)))) FROM generate_series(1, 30);
  COMMIT" || fail "long: wide rows"
LW="$LONG/l0002"
WEND=$(($(lseq "SELECT max(seq) FROM pic_entry") + 1))
script "$T/ph1" <<EOS
send {"type":"fetch","session":"$LW","key":"k-long-fetch-wide01","payload":{"before":$WEND,"limit":200}}
expect "key":"k-long-fetch-wide01","payload":{"done":true,"more":true}}
EOS
done_ok $PR "long: wide entries"
wseqs=$(grep -F '"key":"k-long-fetch-wide01"' "$T/ph1.run" | grep -F '{"type":"event"' | sed -n 's/.*"seq":\([0-9]*\),.*/\1/p' | sort -un)
wn=$(printf '%s\n' "$wseqs" | wc -l | tr -d ' ')
wbytes=$(grep -F '"key":"k-long-fetch-wide01"' "$T/ph1.run" | wc -c | tr -d ' ')
[ "$wn" -ge 5 ] && [ "$wn" -lt 30 ] || fail "long: a page of 200 KB entries held $wn of them"
[ "$wbytes" -le 2621440 ] || fail "long: a page of 200 KB entries came to $wbytes bytes"
grep -qF '{"type":"fetch","session":"'"$LW"'","seq":'"$(printf '%s\n' "$wseqs" | head -1)"',"key":"k-long-fetch-wide01"' "$T/ph1.run" ||
    fail "long: the wide page's end does not name its first entry"
# A pong is not queued behind the page on its way to the same phone: over a slow link (512 KB a
# second here, the page about 2 MB), a ping sent once the page has begun is answered before it ends.
ctl "slow?524288"
script "$T/ph1" <<EOS
send {"type":"fetch","session":"$LW","key":"k-long-fetch-wide02","payload":{"before":$WEND,"limit":200}}
expect "key":"k-long-fetch-wide02"
send {"type":"ping"}
expect {"type":"pong"}
expect "key":"k-long-fetch-wide02","payload":{"done":true,"more":true}}
EOS
done_ok $PR "long: a ping during a page"
ctl "slow?0"
pl=$(grep -n '^<- {"type":"pong"}' "$T/ph1.run" | tail -1 | cut -d: -f1)
el=$(grep -n '"key":"k-long-fetch-wide02","payload":{"done":true' "$T/ph1.run" | tail -1 | cut -d: -f1)
[ -n "$pl" ] && [ -n "$el" ] && [ "$pl" -lt "$el" ] || fail "long: the pong waited for the page (pong at line $pl, the page's end at $el)"
before=$(head -n "$pl" "$T/ph1.run" | grep -cF '"key":"k-long-fetch-wide02"' || true)
printf 'PASS: a ping during a long page to the same phone is answered before the page ends (after %s of its messages)\n' "$before"
# No poster thread would start (a dev build's seam): pic remote says so and posts on its loop.
kill "$RP"
gone "$RP"
nr=$((nr + 1))
RO="$T/remote$nr.out"
PIC_TEST_RC_NO_POSTER=1 "$PIC" remote > "$RO" 2> "$T/remote$nr.err" &
RP=$!
bg $RP
await "$RO" 'pic remote: connected'
script "$T/ph1" <<EOS
send {"type":"ping"}
expect {"type":"pong"}
send {"type":"fetch","session":"$LS","key":"k-long-fetch-nopost","payload":{"before":$LLAST,"limit":5}}
expect "key":"k-long-fetch-nopost","payload":{"done":true,"more":true}}
EOS
done_ok $PR "long: no poster"
[ "$(grep -c 'no poster thread would start; posting to the relay on the loop' "$RO")" = 1 ] ||
    fail "long: no poster: not said once: $(cat "$RO")"
printf 'PASS: paging back 5,000 entries: each earlier page at most 200 entries before the phone'"'"'s first, ended with whether more is left, about 2 MiB at most, never without its key; with no poster, posted on the loop; another phone answered within a second throughout (slowest %s ms)\n' "$slowest"