#!/usr/bin/env bash
# Smoke test for Nixl-based PD-sep migration (NVLink intra-node via UCX).
#
# Drops 2 vLLM kv_both NixlConnector instances on GPU 0,1 and runs
# smoke_test_migrate_cache.py against them with the kv_transfer_params
# format Nixl expects (only do_remote_decode on src; proxy must forward
# kv_transfer_params from src's response to dst).
#
# Since smoke_test_migrate_cache.py is currently hard-coded for Mooncake
# (transfer_id + remote_bootstrap_addr), we use a tiny Python in-line
# variant here that does the Nixl response-forward handshake directly.

set -uo pipefail

PROJ_DIR="${PROJ_DIR:-/home/admin/cpfs/wjh/agentic-kv}"
MODEL="${MODEL:-/home/admin/cpfs/wjh/models/Qwen/Qwen3-Coder-30B-A3B-Instruct}"
VENV="$PROJ_DIR/.venv/bin"
LOGS_DIR="${LOGS_DIR:-$PROJ_DIR/outputs/smoke_nixl_$(date +%Y%m%d_%H%M%S)}"
mkdir -p "$LOGS_DIR"

cleanup() {
    echo "[smoke-nixl] cleaning up vLLM..."
    pkill -9 -f "vllm serve" 2>/dev/null || true
    pkill -9 -f "EngineCore" 2>/dev/null || true
    sleep 2
}
trap cleanup EXIT
cleanup

echo "[smoke-nixl] starting 2 vLLM kv_both NixlConnector on GPU 0,1"
for i in 0 1; do
    port=$((8000 + i))
    nixl_port=$((5600 + i))
    master=$((29500 + i))
    PYTHONHASHSEED=42 \
    VLLM_NIXL_SIDE_CHANNEL_PORT=$nixl_port \
    CUDA_VISIBLE_DEVICES=$i \
    MASTER_PORT=$master \
    nohup "$VENV/vllm" serve "$MODEL" \
        --host 0.0.0.0 --port "$port" \
        --tensor-parallel-size 1 \
        --trust-remote-code --enable-prefix-caching \
        --dtype auto --gpu-memory-utilization 0.9 \
        --max-model-len 200000 \
        --kv-transfer-config '{"kv_connector":"NixlConnector","kv_role":"kv_both"}' \
        --enable-prompt-tokens-details \
        > "$LOGS_DIR/vllm_inst_${i}_gpu${i}.log" 2>&1 &
    disown
    sleep 2
done

echo "[smoke-nixl] waiting for health on 8000 and 8001 ..."
for port in 8000 8001; do
    tries=0
    while ! curl -sf "http://127.0.0.1:$port/health" >/dev/null 2>&1; do
        tries=$((tries+1))
        if [ $tries -gt 240 ]; then
            echo "[smoke-nixl] FATAL: $port not ready"; exit 1
        fi
        sleep 2
    done
    echo "  port=$port ready"
done

echo "[smoke-nixl] running smoke_nixl_migrate.py"
"$VENV/python" "$PROJ_DIR/microbench/connector_tax/cache_sweep/smoke_nixl_migrate.py" \
    --src-port 8000 --dst-port 8001 \
    ${EXTRA_SMOKE_ARGS:-} \
    2>&1 | tee "$LOGS_DIR/smoke_output.log"

ec=${PIPESTATUS[0]}
echo "[smoke-nixl] test exit=$ec, logs at $LOGS_DIR"
exit $ec
