interplane.Get Omega
Read in your language

aien-sovereign-core-mv

AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.

Brought by drakestapleton

branch main Branches Tags History

aien-sovereign-core-mv / scripts / own30b-pkv-lib.sh

274 lines · 12218 bytes Raw Blame History
1# SPDX-License-Identifier: Apache-2.0
2# Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16# Shared helpers of the persistent KV chip scripts (sc#507 #508 #509). Sourced, never run.
17# CHIP-ONLY callers: own30b-pkv-chip-check.sh, own30b-pkv-bench.sh, own30b-pkv-ops-check.sh.
18#
19# Rules every caller inherits:
20# - refuses while the live server on :18091 answers (no override: two omega processes on
21# the chip at once is UNKNOWN territory), and refuses an occupied port (PKV_CHECK_PORT,
22# default 18098; never 18091, 18092 or 18095, which belong to other services);
23# - starts its own aien-serve-http only on 127.0.0.1:$PORT, stops only the PID it started;
24# - key: atlas-vault entry AIEN_KV_STORE_KEY by default (`atlas-vault run AIEN_KV_STORE_KEY
25# --`, the key never passes through this shell), or PKV_CHECK_EPHEMERAL_KEY=1 for a
26# throwaway key held only in this shell and the child's environment; never printed or saved;
27# - evidence: raw files in the evidence dir, a summary, SHA256SUMS over every file.
28# shellcheck shell=bash disable=SC2034 # DRY, fail, SERVER_JOB, ... are read by the callers
29
30PKV_LIVE_PORT=18091
31MODEL=${OWN30B_MODEL_DIR:-$HOME/models/qwen3-30b-a3b-instruct-2507-fp8}
32PORT=${PKV_CHECK_PORT:-18098}
33PKV_RESERVED_PORTS="18091 18092 18095" # live 30B, spark-mail, spark-cockpit
34pkv_port_reserved() { case " $PKV_RESERVED_PORTS " in *" $1 "*) return 0 ;; esac; return 1; }
35base="http://127.0.0.1:$PORT"
36DRY=0
37SERVER_JOB=
38
39pkv_usage_args() { # <script> "$@": sets dir BIN DRY
40 local me=$1
41 shift
42 if [ "${1:-}" = --dry-run ]; then
43 DRY=1
44 shift
45 fi
46 if [ $# -ne 2 ]; then
47 echo "usage: $me [--dry-run] <evidence-dir> <aien-serve-http binary>" >&2
48 exit 64
49 fi
50 dir=$1 BIN=$2
51}
52
53pkv_live_up() { curl -s -m 2 "http://127.0.0.1:$PKV_LIVE_PORT/health" >/dev/null 2>&1; }
54pkv_port_busy() { ss -Hltn "sport = :$PORT" | grep -q . || curl -s -m 2 "$base/health" >/dev/null 2>&1; }
55
56# Prerequisites shared by every script. Prints one line per check; returns non-zero on a hard miss.
57# pkv_prereqs <needs-key 0|1>
58pkv_prereqs() {
59 local bad=0 t
60 for t in curl jq awk ss sha256sum setsid od; do
61 if command -v "$t" >/dev/null; then echo " ok tool $t"; else echo " MISS tool $t"; bad=1; fi
62 done
63 if [ -n "${AIEN_SERVE_HTTP_BEARER_TOKEN:-}" ]; then echo " ok HTTP bearer credential configured"; else echo " MISS AIEN_SERVE_HTTP_BEARER_TOKEN"; bad=1; fi
64 if [ -x "$BIN" ]; then
65 echo " ok binary $BIN (sha256 $(sha256sum "$BIN" | cut -c1-16)...)"
66 else
67 echo " MISS binary $BIN (not an executable file)"
68 bad=1
69 fi
70 if [ -f "$MODEL/config.json" ]; then echo " ok model $MODEL"; else echo " MISS model $MODEL/config.json"; bad=1; fi
71 if pkv_live_up; then
72 echo " STOP live server on :$PKV_LIVE_PORT answers: the real run would refuse (pause it first)"
73 bad=1
74 else
75 echo " ok :$PKV_LIVE_PORT does not answer"
76 fi
77 if pkv_port_reserved "$PORT"; then echo " STOP :$PORT belongs to another service (reserved: $PKV_RESERVED_PORTS)"; bad=1; elif pkv_port_busy; then echo " STOP something listens on :$PORT (pick a free PKV_CHECK_PORT)"; bad=1; else echo " ok :$PORT is free"; fi
78 if [ "${1:-1}" = 1 ]; then
79 if [ "${PKV_CHECK_EPHEMERAL_KEY:-0}" = 1 ]; then
80 echo " ok key: ephemeral (PKV_CHECK_EPHEMERAL_KEY=1, lives only in this run)"
81 elif ! command -v atlas-vault >/dev/null; then
82 echo " MISS atlas-vault (or set PKV_CHECK_EPHEMERAL_KEY=1)"
83 bad=1
84 elif atlas-vault list 2>/dev/null | grep -qx AIEN_KV_STORE_KEY; then
85 echo " ok key: atlas-vault entry AIEN_KV_STORE_KEY exists (listed only, not read)"
86 else
87 echo " MISS atlas-vault entry AIEN_KV_STORE_KEY (or set PKV_CHECK_EPHEMERAL_KEY=1)"
88 bad=1
89 fi
90 fi
91 local avail
92 avail=$(df -Pk /tmp | awk 'NR==2 {print int($4/1048576)}')
93 echo " info /tmp free: ${avail} GiB on $(df -P /tmp | awk 'NR==2 {print $1}')"
94 return $bad
95}
96
97# The real run: refuse, then make the private work dir and the key. Sets work PIDF KEY.
98pkv_begin() {
99 if pkv_live_up; then
100 echo "refusing: the live server on :$PKV_LIVE_PORT is up (pause it first)" >&2
101 exit 2
102 fi
103 if pkv_port_reserved "$PORT"; then
104 echo "refusing: :$PORT belongs to another service (reserved: $PKV_RESERVED_PORTS)" >&2
105 exit 2
106 fi
107 if pkv_port_busy; then
108 echo "refusing: something already listens on :$PORT (18095 is spark-cockpit; pick a free PKV_CHECK_PORT)" >&2
109 exit 2
110 fi
111 [ -x "$BIN" ] || { echo "no executable binary at $BIN" >&2; exit 2; }
112 mkdir -p "$dir"
113 work=$(mktemp -d /tmp/pkv-chip.XXXXXX)
114 chmod 700 "$work"
115 PIDF="$work/server.pid"
116 trap 'stop_server || PKV_LEAK=1; rm -rf "$work"; pkv_trap_status' EXIT
117 KEY=
118 if [ "${PKV_CHECK_EPHEMERAL_KEY:-0}" = 1 ]; then
119 KEY=$(head -c 32 /dev/urandom | od -An -tx1 | tr -d ' \n')
120 fi
121 {
122 echo "binary $BIN sha256 $(sha256sum "$BIN" | cut -d' ' -f1)"
123 echo "model $MODEL port $PORT key-mode $([ -n "$KEY" ] && echo ephemeral || echo atlas-vault)"
124 echo "started $(date -u +%FT%TZ) host $(hostname)"
125 } >"$dir/run-info.txt"
126}
127
128# The name the server answers to (it refuses any other model name).
129SERVED_MODEL=${PKV_SERVED_MODEL:-qwen3-30b-a3b-instruct-2507}
130
131server_pid() { [ -f "$PIDF" ] && cat "$PIDF"; }
132
133# Fails (returns 1) if anything still owns our port after a stop: never start the next server
134# beside a leftover one (two 30 GB loads on the chip). Mid-run the callers' set -e stops the run;
135# the EXIT trap records it and carries on with its cleanup (an exit inside the trap would end the
136# trap there and leave the other server and the work dir behind, sc#523).
137port_released() {
138 for _ in $(seq 1 50); do ss -Hltn "sport = :$PORT" | grep -q . || return 0; sleep 0.2; done
139 echo "something still listens on :$PORT after the stop; stopping the run" >&2
140 return 1
141}
142
143# The last step of every EXIT trap: a stop that left the port held (PKV_LEAK=1) fails the run,
144# after every other cleanup step has run.
145pkv_trap_status() { [ -z "${PKV_LEAK:-}" ] || exit 1; }
146
147# Stops our server: SIGTERM (graceful drain, #509), SIGKILL after PKV_STOP_WAIT_S (default 120).
148stop_server() {
149 [ -n "${PIDF:-}" ] && [ -f "$PIDF" ] || return 0
150 local p
151 p=$(cat "$PIDF")
152 if [ -n "$p" ] && [ "$(ps -o comm= -p "$p" 2>/dev/null || true)" = aien-serve-http ]; then
153 kill "$p"
154 for _ in $(seq 1 $((${PKV_STOP_WAIT_S:-120} * 10))); do kill -0 "$p" 2>/dev/null || break; sleep 0.1; done
155 if kill -0 "$p" 2>/dev/null; then
156 echo "server $p ignored SIGTERM for ${PKV_STOP_WAIT_S:-120} s: SIGKILL" >&2
157 kill -9 "$p" 2>/dev/null || true
158 fi
159 fi
160 rm -f "$PIDF"
161 port_released
162}
163
164# kill -9 our server now (the interrupted-write case).
165kill9_server() {
166 local p
167 p=$(cat "$PIDF")
168 if [ -n "$p" ] && [ "$(ps -o comm= -p "$p" 2>/dev/null || true)" = aien-serve-http ]; then
169 kill -9 "$p"
170 for _ in $(seq 1 100); do kill -0 "$p" 2>/dev/null || break; sleep 0.1; done
171 fi
172 rm -f "$PIDF"
173 port_released
174}
175
176# start_server <log-name> <store-dir | - (unset) | nokey:<dir> | badkey:<dir> | foreignkey:<dir>> [flags...]
177# Sets SERVER_JOB (the background job, for `wait`); the server PID is in $PIDF.
178# Extra environment for the child: PKV_SERVER_ENV="A=1 B=2" (no spaces inside values).
179start_server() {
180 local name=$1 store=$2
181 shift 2
182 local log="$dir/$name.log"
183 local cmd="echo \$\$ > '$PIDF'; exec '$BIN' --engine omega --model-dir '$MODEL' --port $PORT $*"
184 local -a extra=()
185 # shellcheck disable=SC2206
186 [ -n "${PKV_SERVER_ENV:-}" ] && extra=($PKV_SERVER_ENV)
187 case $store in
188 -) setsid env -u AIEN_KV_STORE_DIR -u AIEN_KV_STORE_KEY "${extra[@]}" sh -c "$cmd" >"$log" 2>&1 </dev/null & ;;
189 nokey:*) setsid env -u AIEN_KV_STORE_KEY AIEN_KV_STORE_DIR="${store#nokey:}" "${extra[@]}" sh -c "$cmd" >"$log" 2>&1 </dev/null & ;;
190 badkey:*) setsid env AIEN_KV_STORE_DIR="${store#badkey:}" AIEN_KV_STORE_KEY=not-a-key "${extra[@]}" sh -c "$cmd" >"$log" 2>&1 </dev/null & ;;
191 foreignkey:*)
192 # A valid key that is not the store's: a store written by someone else.
193 setsid env AIEN_KV_STORE_DIR="${store#foreignkey:}" AIEN_KV_STORE_KEY="$(head -c 32 /dev/urandom | od -An -tx1 | tr -d ' \n')" "${extra[@]}" sh -c "$cmd" >"$log" 2>&1 </dev/null &
194 ;;
195 *)
196 if [ -n "${KEY:-}" ]; then
197 setsid env AIEN_KV_STORE_DIR="$store" AIEN_KV_STORE_KEY="$KEY" "${extra[@]}" sh -c "$cmd" >"$log" 2>&1 </dev/null &
198 else
199 setsid atlas-vault run AIEN_KV_STORE_KEY -- env AIEN_KV_STORE_DIR="$store" "${extra[@]}" sh -c "$cmd" >"$log" 2>&1 </dev/null &
200 fi
201 ;;
202 esac
203 SERVER_JOB=$!
204 for _ in $(seq 1 "${PKV_START_WAIT_S:-600}"); do
205 grep -q "serving \|load failed\|bind failed" "$log" 2>/dev/null && break
206 sleep 1
207 done
208 grep -q "serving " "$log" || { echo "server $name did not start; see $log" >&2; exit 1; }
209 # The PID file can hold a wrapper, not the server: atlas-vault re-wraps the command in its own
210 # `sh -c "..."`, which expands $$ to the wrapper. Record the process that owns our port.
211 local lp
212 lp=$(ss -Hltnp "sport = :$PORT" | grep -o 'pid=[0-9]*' | head -1 | cut -d= -f2)
213 if [ -z "$lp" ] || [ "$(ps -o comm= -p "$lp" 2>/dev/null || true)" != aien-serve-http ]; then
214 echo "server $name: no aien-serve-http owns :$PORT" >&2
215 exit 1
216 fi
217 echo "$lp" >"$PIDF"
218 grep "persistent KV" "$log" || true
219}
220
221health() { curl -s -m 10 "$base/health" >"$dir/$1-health.json"; cat "$dir/$1-health.json"; }
222pk() { jq -r ".persistent_kv.$2" "$dir/$1-health.json"; }
223
224# The same greedy two-turn conversation as #507.
225SYS="You are the OWN-30B assistant on the AIEN Spark. Answer briefly."
226for i in $(seq 1 40); do SYS="$SYS Rule $i: keep answers short, never invent facts, say UNKNOWN when unsure."; done
227Q1="Name three uses of a torque wrench."
228Q2="Which of those matters most on a bicycle, and why?"
229m1=$(jq -n --arg s "$SYS" --arg q "$Q1" '[{role:"system",content:$s},{role:"user",content:$q}]')
230turn2_msgs() { jq -n --argjson m "$m1" --arg a "$1" --arg q "${2:-$Q2}" '$m + [{role:"assistant",content:$a},{role:"user",content:$q}]'; }
231
232chat() { # <out-name> <messages-json>: prints the content
233 jq -n --arg model "$SERVED_MODEL" --argjson m "$2" '{model:$model, messages:$m, max_tokens:64, temperature:0, seed:1, stream:false}' |
234 curl -s -m 600 "$base/v1/chat/completions" -H "Authorization: Bearer $AIEN_SERVE_HTTP_BEARER_TOKEN" -H 'content-type: application/json' -d @- >"$dir/$1.json"
235 local c
236 c=$(jq -r '.choices[0].message.content // empty' "$dir/$1.json" 2>/dev/null)
237 if [ -z "$c" ]; then
238 echo "chat $1: no reply ($(head -c 200 "$dir/$1.json")); stopping the run" >&2
239 exit 1
240 fi
241 printf '%s\n' "$c"
242}
243
244wait_parks() { # until parked_chunks is a number > 0 and unchanged for 3 s
245 local last=-1 now
246 for _ in $(seq 1 60); do
247 now=$(curl -s -m 5 "$base/health" | jq -r '.persistent_kv.parked_chunks' 2>/dev/null || true)
248 # A failed request, null or a missing counter is not a count (sc#523): never settled.
249 case $now in '' | *[!0-9]*) now=-1 ;; esac
250 [ "$now" -gt 0 ] && [ "$now" = "$last" ] && return 0
251 last=$now
252 sleep 3
253 done
254 echo "parks did not settle" >&2
255 exit 1
256}
257
258fail=0
259# Empty or null on either side is a FAIL: two failed requests must never compare equal.
260check() { if [ -n "$2" ] && [ "$2" != null ] && [ "$2" = "$3" ]; then echo "PASS $1"; else echo "FAIL $1 ($2 != $3)"; fail=1; fi; }
261
262pkv_seal() { # writes SHA256SUMS over every evidence file
263 local sums
264 sums=$(cd "$dir" && find . -type f ! -name SHA256SUMS -print0 | sort -z | xargs -0 sha256sum)
265 printf '%s\n' "$sums" >"$dir/SHA256SUMS"
266}
267
268flip_byte() { # <file>: XOR 0x40 into the middle byte, in place
269 local f=$1 sz off b
270 sz=$(stat -c %s "$f")
271 off=$((sz / 2))
272 b=$(dd if="$f" bs=1 skip=$off count=1 2>/dev/null | od -An -tu1 | tr -d ' ')
273 printf '%b' "\\$(printf '%03o' $(((b ^ 64) & 255)))" | dd of="$f" bs=1 seek=$off count=1 conv=notrunc 2>/dev/null
274}