From 6d158597791c73bfdcdda43ebfb1bb88cfc5dcbe Mon Sep 17 00:00:00 2001 From: Carlos Garcia Date: Fri, 24 Apr 2026 17:39:51 -0400 Subject: [PATCH] fix(setup.sh): detect stale DB volume, run Alembic migrations on startup - Before bringing up the stack, check if the agent-db volume exists but is missing the expected database (left from a previous broken run with wrong POSTGRES_DB). Offer to wipe and re-init automatically. - After docker compose up, wait for pg_isready then run `alembic upgrade head` inside the agent container so tables are created before the agent attempts to use them. - Restart agent-service after migrations so it connects to a fully initialized database on its first attempt. Co-Authored-By: Claude Sonnet 4.6 --- setup.sh | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/setup.sh b/setup.sh index d61e927..3dc1ddc 100644 --- a/setup.sh +++ b/setup.sh @@ -380,7 +380,47 @@ ask "Start the agent stack now? [Y/n]" read -rp " > " _START if [[ "${_START:-Y}" =~ ^[Yy] ]]; then cd "$SCRIPT_DIR" + + # If the DB volume exists but was initialized with a different POSTGRES_DB, + # the database won't exist inside it. Detect this and offer a clean wipe. + _VOL="$(docker volume ls -q --filter name=odoo-ai_agent-db-data 2>/dev/null | head -1)" + if [[ -n "$_VOL" ]]; then + # Spin up just the DB to check + docker compose up -d agent-db >/dev/null 2>&1 + sleep 3 + if ! docker exec activeblue-agent-db psql -U "$POSTGRES_USER" -lqt 2>/dev/null \ + | cut -d'|' -f1 | grep -qw "$POSTGRES_DB"; then + warn "DB volume exists but database '${POSTGRES_DB}' is missing (left from a previous broken run)" + ask " Wipe the agent-db volume and re-init? [Y/n]" + read -rp " > " _WIPE + if [[ "${_WIPE:-Y}" =~ ^[Yy] ]]; then + docker compose down -v + info " Volume wiped" + fi + fi + fi + docker compose up -d + info "Waiting for agent-db to be ready..." + for _i in $(seq 1 15); do + if docker exec activeblue-agent-db pg_isready -U "$POSTGRES_USER" -d "$POSTGRES_DB" \ + >/dev/null 2>&1; then + break + fi + sleep 2 + done + + # Run Alembic migrations so tables exist before the agent needs them + info "Running database migrations..." + if docker exec activeblue-agent \ + alembic -c agent_service/migrations/alembic.ini upgrade head 2>&1; then + info "Migrations applied" + else + warn "Migration command failed — tables may be missing. Check alembic output above." + fi + + # Restart agent so it picks up a healthy DB on its first connect attempt + docker compose restart agent-service echo "" info "Stack started. Tailing logs (Ctrl-C to stop):" echo ""