#!/bin/sh set -e # Ensure storage + credentials dirs exist (Render's persistent disk is empty on # first boot; local docker-run may not have created them either). mkdir -p "${LIGHTING_MVP_STORAGE_ROOT:-/tmp/lighting-mvp-runtime}" mkdir -p "${LIGHTING_MVP_CLAUDE_CONFIG_DIR:-/app/claude-config}" # Run alembic migrations before the app starts so schema is always current. # # Gotcha: the Neon DB was originally created without alembic tracking, so the # alembic_version table is empty but the core tables (jobs, files, ...) exist. # In that state `alembic upgrade head` fails on the very first migration with # "relation jobs already exists" and never applies later additive migrations # (like new columns). To recover, we stamp the DB to the last pre-drift # revision if we detect that case, then run upgrade head. # # SQLite carve-out: the migrations use Postgres-specific operations (JSONB, # index-after-create, NULLS LAST) that don't apply cleanly on SQLite. For # SQLite mode (handover/evaluation default), skip alembic and rely on # Base.metadata.create_all in the app's lifespan to build the schema from # the current ORM. The Postgres path is the source-of-truth for migrations. DB_URL="${LIGHTING_MVP_DATABASE_URL:-}" if [ -z "$DB_URL" ] || echo "$DB_URL" | grep -q "^sqlite"; then echo "Using SQLite (no migrations needed; lifespan create_all will build schema)." elif [ -f "/app/alembic.ini" ]; then echo "Running alembic migrations..." python - <<'PYEOF' || echo "Alembic bootstrap check failed (continuing)" # One-off recovery: the Neon DB was created without alembic tracking, and the # previous Dockerfile swallowed alembic errors with `|| continuing`. Result: # some additive migrations were partially applied and the version table is # out of sync with reality. Rather than trying to pick the correct stamp # point, apply any missing schema changes idempotently, then stamp to head. from sqlalchemy import create_engine, text, inspect from app.core.settings import get_settings HEAD_REVISION = "20260428_0002" url = get_settings().database_url.replace("+aiosqlite", "") eng = create_engine(url) with eng.connect() as conn: insp = inspect(conn) has_jobs = insp.has_table("jobs") has_version = insp.has_table("alembic_version") version_row = None if has_version: row = conn.execute(text("SELECT version_num FROM alembic_version LIMIT 1")).fetchone() version_row = row[0] if row else None print(f"[bootstrap] has_jobs={has_jobs} has_version={has_version} version={version_row}") if not has_jobs: # Fresh DB — let alembic run normally. print("[bootstrap] no jobs table; letting alembic run from scratch") else: # Existing DB: idempotently add any missing schema, then stamp to head. def col_exists(table, col): if not insp.has_table(table): return False return any(c["name"] == col for c in insp.get_columns(table)) # 20260408_0001 — benchmark_deviations if not insp.has_table("benchmark_deviations"): print("[bootstrap] creating benchmark_deviations") conn.execute(text(""" CREATE TABLE benchmark_deviations ( deviation_id VARCHAR PRIMARY KEY, run_id VARCHAR, item_id VARCHAR, kind VARCHAR, details JSONB, created_at TIMESTAMP WITH TIME ZONE DEFAULT now() ) """)) # 20260416_0001 — pipeline_runs if not insp.has_table("pipeline_runs"): print("[bootstrap] creating pipeline_runs (minimal schema)") conn.execute(text(""" CREATE TABLE pipeline_runs ( run_id VARCHAR PRIMARY KEY, job_id VARCHAR, job_name VARCHAR, config_version VARCHAR, source_filenames JSONB, status VARCHAR, current_stage VARCHAR, created_at TIMESTAMP WITH TIME ZONE, started_at TIMESTAMP WITH TIME ZONE, completed_at TIMESTAMP WITH TIME ZONE, heartbeat_at TIMESTAMP WITH TIME ZONE, cancel_requested BOOLEAN DEFAULT false, error_code VARCHAR, error_message TEXT, matched_count INTEGER, unmatched_count INTEGER, total_items INTEGER, worker_id VARCHAR ) """)) # 20260417_0001 — uploaded_files.content bytea if not col_exists("uploaded_files", "content"): print("[bootstrap] adding uploaded_files.content BYTEA") conn.execute(text("ALTER TABLE uploaded_files ADD COLUMN IF NOT EXISTS content BYTEA")) conn.execute(text("ALTER TABLE uploaded_files ALTER COLUMN storage_key DROP NOT NULL")) # 20260526_0001 — uploaded_files.source_url for SharePoint/etc provenance if not col_exists("uploaded_files", "source_url"): print("[bootstrap] adding uploaded_files.source_url TEXT") conn.execute(text("ALTER TABLE uploaded_files ADD COLUMN IF NOT EXISTS source_url TEXT")) # 20260417_0002 — system_secrets if not insp.has_table("system_secrets"): print("[bootstrap] creating system_secrets") conn.execute(text(""" CREATE TABLE system_secrets ( name VARCHAR PRIMARY KEY, value TEXT, updated_at TIMESTAMP WITH TIME ZONE DEFAULT now() ) """)) # 20260422_0001 — new outcome counts if not col_exists("pipeline_runs", "no_offer_count"): print("[bootstrap] adding pipeline_runs.no_offer_count") conn.execute(text("ALTER TABLE pipeline_runs ADD COLUMN IF NOT EXISTS no_offer_count INTEGER")) if not col_exists("pipeline_runs", "out_of_scope_count"): print("[bootstrap] adding pipeline_runs.out_of_scope_count") conn.execute(text("ALTER TABLE pipeline_runs ADD COLUMN IF NOT EXISTS out_of_scope_count INTEGER")) # 20260424_0001 — functional_substitute_count column if not col_exists("pipeline_runs", "functional_substitute_count"): print("[bootstrap] adding pipeline_runs.functional_substitute_count") conn.execute(text("ALTER TABLE pipeline_runs ADD COLUMN IF NOT EXISTS functional_substitute_count INTEGER")) # 20260428_0001 — pipeline_runs.run_instructions if not col_exists("pipeline_runs", "run_instructions"): print("[bootstrap] adding pipeline_runs.run_instructions") conn.execute(text("ALTER TABLE pipeline_runs ADD COLUMN IF NOT EXISTS run_instructions TEXT")) # 20260428_0002 — pipeline_runs.queue_priority if not col_exists("pipeline_runs", "queue_priority"): print("[bootstrap] adding pipeline_runs.queue_priority") conn.execute(text("ALTER TABLE pipeline_runs ADD COLUMN IF NOT EXISTS queue_priority INTEGER")) # 20260424_0002 — cost + token tracking columns for col_name, col_type in ( ("total_cost_usd", "DOUBLE PRECISION"), ("total_input_tokens", "BIGINT"), ("total_output_tokens", "BIGINT"), ("total_cache_read_tokens", "BIGINT"), ("total_cache_creation_tokens", "BIGINT"), ("total_claude_calls", "INTEGER"), ): if not col_exists("pipeline_runs", col_name): print(f"[bootstrap] adding pipeline_runs.{col_name}") conn.execute(text(f"ALTER TABLE pipeline_runs ADD COLUMN IF NOT EXISTS {col_name} {col_type}")) # feedback table: align with current ORM. The table was originally # created via NeonBase.metadata.create_all on app startup with an older # schema, so any column added later needs idempotent backfill here. if insp.has_table("feedback"): if not col_exists("feedback", "job_name"): print("[bootstrap] adding feedback.job_name") conn.execute(text("ALTER TABLE feedback ADD COLUMN IF NOT EXISTS job_name TEXT")) if not col_exists("feedback", "source_filenames"): print("[bootstrap] adding feedback.source_filenames") conn.execute(text("ALTER TABLE feedback ADD COLUMN IF NOT EXISTS source_filenames JSONB")) # 20260427_0001 — run_id + candidates_snapshot if not col_exists("feedback", "run_id"): print("[bootstrap] adding feedback.run_id") conn.execute(text("ALTER TABLE feedback ADD COLUMN IF NOT EXISTS run_id VARCHAR(36)")) conn.execute(text("CREATE INDEX IF NOT EXISTS ix_feedback_run_id ON feedback(run_id)")) if not col_exists("feedback", "candidates_snapshot"): print("[bootstrap] adding feedback.candidates_snapshot") conn.execute(text("ALTER TABLE feedback ADD COLUMN IF NOT EXISTS candidates_snapshot JSONB")) # 20260423_0001 — pipeline_run_diagnostics table if not insp.has_table("pipeline_run_diagnostics"): print("[bootstrap] creating pipeline_run_diagnostics") conn.execute(text(""" CREATE TABLE pipeline_run_diagnostics ( run_id VARCHAR(36) PRIMARY KEY REFERENCES pipeline_runs(run_id), job_id VARCHAR(36) NOT NULL REFERENCES jobs(job_id), timings_json JSONB, hardware_info_json JSONB, activity_jsonl TEXT, metrics_jsonl TEXT, errs_json JSONB, created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now() ) """)) conn.execute(text("CREATE INDEX ix_pipeline_run_diagnostics_job_id ON pipeline_run_diagnostics(job_id)")) # Stamp to head so future alembic upgrades are no-ops. if not has_version: conn.execute(text("CREATE TABLE IF NOT EXISTS alembic_version (version_num VARCHAR(32) NOT NULL PRIMARY KEY)")) if version_row != HEAD_REVISION: print(f"[bootstrap] stamping alembic_version to {HEAD_REVISION}") conn.execute(text("DELETE FROM alembic_version")) conn.execute(text("INSERT INTO alembic_version (version_num) VALUES (:v)"), {"v": HEAD_REVISION}) conn.commit() PYEOF alembic -c /app/alembic.ini upgrade head || echo "Alembic upgrade failed (continuing)" fi exec uvicorn app.main:app --host 0.0.0.0 --port "${PORT:-7860}"