Switch to PostgreSQL: pg data layer, CI-provisioned database, data rebuilt from sources
Deploy / deploy (push) Failing after 9m27s
Deploy / deploy (push) Failing after 9m27s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FbMbJPadPzVwvt9rU9GBNo
This commit is contained in:
+62
-23
@@ -1,51 +1,86 @@
|
||||
#!/bin/sh
|
||||
# Permanent deploy on the ces-control host: /opt/llm-survey/releases/<sha>, `current` symlink,
|
||||
# systemd unit `llm-survey`. Port is never 3000 or 18131 (taken).
|
||||
# Permanent deploy on the ces-control host, fully driven by CI:
|
||||
# 1. install + provision PostgreSQL (apt, systemd; role/db created once, password generated once)
|
||||
# 2. fetch raw sources (cached), build the staging SQLite with the Python scripts
|
||||
# 3. build the site, load the data into Postgres (schema "next" -> swapped in as "live")
|
||||
# 4. switch /opt/llm-survey/current, (re)start systemd unit `llm-survey`, health-check
|
||||
# Port is never 3000 or 18131 (taken).
|
||||
set -eu
|
||||
SHA="${1:?usage: deploy.sh <git-sha>}"
|
||||
APP=llm-survey
|
||||
ROOT=/opt/$APP
|
||||
ENVF=/etc/$APP/db.env
|
||||
PORT="${APP_PORT:-18231}"
|
||||
DB=llm_survey
|
||||
case "$PORT" in 3000|18131) echo "refusing reserved port $PORT" >&2; exit 1;; esac
|
||||
|
||||
command -v node >/dev/null || { echo "node is not installed on this host" >&2; exit 1; }
|
||||
for c in node python3 git curl bash; do command -v $c >/dev/null || { echo "$c is not installed on this host" >&2; exit 1; }; done
|
||||
node -e 'process.exit(+process.versions.node.split(".")[0] >= 18 ? 0 : 1)' || { echo "need node >= 18" >&2; exit 1; }
|
||||
|
||||
# ---- 1. PostgreSQL --------------------------------------------------------------------
|
||||
if ! command -v psql >/dev/null || ! [ -d /usr/lib/postgresql ]; then
|
||||
echo "installing postgresql"
|
||||
export DEBIAN_FRONTEND=noninteractive
|
||||
apt-get update -qq && apt-get install -y -qq postgresql postgresql-contrib
|
||||
fi
|
||||
systemctl enable --now postgresql >/dev/null 2>&1 || true
|
||||
i=0; until su postgres -c "pg_isready -q" 2>/dev/null || [ $i -ge 30 ]; do i=$((i+1)); sleep 2; done
|
||||
su postgres -c "pg_isready -q" || { echo "postgresql did not become ready" >&2; exit 1; }
|
||||
PGPORT=$(su postgres -c "psql -tAc 'show port'")
|
||||
psql_admin() { su postgres -c "psql -v ON_ERROR_STOP=1 -qtA $*"; }
|
||||
|
||||
mkdir -p "$(dirname "$ENVF")"; chmod 755 "$(dirname "$ENVF")"
|
||||
if [ ! -s "$ENVF" ]; then
|
||||
PW=$(head -c 64 /dev/urandom | base64 | tr -dc 'A-Za-z0-9' | head -c 28)
|
||||
umask 077
|
||||
printf 'DATABASE_URL=postgres://%s:%s@127.0.0.1:%s/%s\n' "$DB" "$PW" "$PGPORT" "$DB" > "$ENVF"
|
||||
fi
|
||||
PW=$(sed -E 's#^DATABASE_URL=postgres://[^:]+:([^@]+)@.*#\1#' "$ENVF")
|
||||
# keep the role password and the env file in sync; create role/db only when missing
|
||||
if [ "$(psql_admin "-c \"select 1 from pg_roles where rolname='$DB'\"")" = 1 ]; then
|
||||
psql_admin "-c \"alter role $DB with login password '$PW'\"" >/dev/null
|
||||
else
|
||||
psql_admin "-c \"create role $DB login password '$PW'\"" >/dev/null
|
||||
fi
|
||||
[ "$(psql_admin "-c \"select 1 from pg_database where datname='$DB'\"")" = 1 ] || psql_admin "-c \"create database $DB owner $DB\"" >/dev/null
|
||||
chmod 600 "$ENVF"
|
||||
set -a; . "$ENVF"; set +a
|
||||
PGPASSWORD=$PW psql -h 127.0.0.1 -p "$PGPORT" -U "$DB" -d "$DB" -qtAc 'select 1' >/dev/null || { echo "cannot log in to postgres as $DB" >&2; exit 1; }
|
||||
|
||||
# port must be free, or held by our own service
|
||||
if ss -ltnH "sport = :$PORT" | grep -q . && ! systemctl is-active --quiet "$APP"; then
|
||||
echo "port $PORT is in use by another process" >&2; exit 1
|
||||
fi
|
||||
|
||||
# ---- 2. release dir + data build ------------------------------------------------------
|
||||
REL="$ROOT/releases/$SHA"
|
||||
mkdir -p "$ROOT/releases"
|
||||
mkdir -p "$ROOT/releases" "$ROOT/cache/raw"
|
||||
rm -rf "$REL"; mkdir -p "$REL"
|
||||
tar --exclude=.git --exclude=node_modules --exclude=.next -cf - . | tar -xf - -C "$REL"
|
||||
cd "$REL"
|
||||
# data/papers.db is not in git: fetch it (checksum-verified) from the Gitea package registry.
|
||||
VER=$(cat data/DB_VERSION); PARTS=$(cat data/DB_PARTS)
|
||||
CACHE="$ROOT/data/$VER"
|
||||
if [ ! -s "$CACHE/papers.db" ]; then
|
||||
mkdir -p "$CACHE"; rm -f "$CACHE"/part.* "$CACHE/papers.db.tmp"
|
||||
URL="${GITHUB_SERVER_URL:-https://gitea.entroia.com}/api/packages/claude-bot/generic/llm-survey-data/$VER"
|
||||
i=0; while [ "$i" -lt "$PARTS" ]; do
|
||||
n=$(printf 'part.%02d' "$i"); curl -fsS --retry 3 -o "$CACHE/$n" "$URL/$n"; i=$((i+1))
|
||||
done
|
||||
cat "$CACHE"/part.* | gunzip > "$CACHE/papers.db.tmp"
|
||||
[ "$(sha256sum "$CACHE/papers.db.tmp" | cut -d' ' -f1)" = "$VER" ] || { echo "papers.db checksum mismatch" >&2; exit 1; }
|
||||
mv "$CACHE/papers.db.tmp" "$CACHE/papers.db"; rm -f "$CACHE"/part.*
|
||||
fi
|
||||
mkdir -p data && cp "$CACHE/papers.db" data/papers.db
|
||||
mkdir -p build data
|
||||
ln -sfn "$ROOT/cache/raw" data/raw # raw downloads survive between releases
|
||||
[ -d data/raw/acl-anthology ] && git -C data/raw/acl-anthology pull --ff-only -q || true
|
||||
bash scripts/fetch_data.sh
|
||||
python3 scripts/ingest.py --raw data/raw --out build/papers.db
|
||||
python3 scripts/build_worktypes.py --db build/papers.db
|
||||
|
||||
# ---- 3. site build + load into Postgres ----------------------------------------------
|
||||
npm ci --no-audit --no-fund
|
||||
npm run build
|
||||
node -e 'const D=require("better-sqlite3");const d=new D("data/papers.db",{readonly:true});console.log("papers:",d.prepare("select count(*) c from papers").get().c)'
|
||||
node scripts/load-pg.js --sqlite build/papers.db
|
||||
rm -rf build
|
||||
|
||||
# ---- 4. switch + restart --------------------------------------------------------------
|
||||
ln -sfn "$REL" "$ROOT/current.new" && mv -T "$ROOT/current.new" "$ROOT/current"
|
||||
cat > /etc/systemd/system/$APP.service <<UNIT
|
||||
[Unit]
|
||||
Description=LLM research survey (Next.js)
|
||||
After=network.target
|
||||
Description=LLM research survey (Next.js + PostgreSQL)
|
||||
After=network.target postgresql.service
|
||||
Wants=postgresql.service
|
||||
[Service]
|
||||
WorkingDirectory=$ROOT/current
|
||||
EnvironmentFile=$ENVF
|
||||
Environment=NODE_ENV=production PORT=$PORT
|
||||
ExecStart=$(command -v node) node_modules/next/dist/bin/next start -p $PORT -H 0.0.0.0
|
||||
Restart=always
|
||||
@@ -56,8 +91,12 @@ UNIT
|
||||
systemctl daemon-reload
|
||||
systemctl enable "$APP" >/dev/null 2>&1
|
||||
systemctl restart "$APP"
|
||||
ok=0
|
||||
for i in 1 2 3 4 5 6 7 8 9 10; do
|
||||
curl -fsS -o /dev/null "http://127.0.0.1:$PORT/" && { echo "healthy on :$PORT ($SHA)"; ok=1; break; }; sleep 2
|
||||
if curl -fsS -o /dev/null "http://127.0.0.1:$PORT/" && curl -fsS -o /dev/null "http://127.0.0.1:$PORT/papers?q=agent"; then ok=1; break; fi
|
||||
sleep 2
|
||||
done
|
||||
[ "${ok:-0}" = 1 ] || { journalctl -u "$APP" -n 40 --no-pager; exit 1; }
|
||||
[ "$ok" = 1 ] || { journalctl -u "$APP" -n 60 --no-pager; exit 1; }
|
||||
echo "healthy on :$PORT ($SHA); postgres on :$PGPORT db=$DB"
|
||||
echo "public ip: $(curl -fsS -m 5 https://api.ipify.org 2>/dev/null || echo unknown)"
|
||||
ls -1dt "$ROOT"/releases/* | tail -n +4 | xargs -r rm -rf
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
#!/usr/bin/env node
|
||||
// Load the SQLite staging database (built by ingest.py + build_worktypes.py) into PostgreSQL.
|
||||
// Builds schema "next", verifies row counts, then swaps it in as schema "live" in one transaction.
|
||||
// usage: DATABASE_URL=postgres://... node scripts/load-pg.js --sqlite build/papers.db
|
||||
const { Client } = require('pg');
|
||||
const Database = require('better-sqlite3');
|
||||
|
||||
const arg = (n, d) => { const i = process.argv.indexOf('--' + n); return i > 0 ? process.argv[i + 1] : d; };
|
||||
const sqliteFile = arg('sqlite', 'build/papers.db');
|
||||
if (!process.env.DATABASE_URL) { console.error('DATABASE_URL is not set'); process.exit(1); }
|
||||
|
||||
const DDL = `
|
||||
CREATE TABLE conferences(slug text PRIMARY KEY, name text, short text, year integer, kind text, start_date text, end_date text, location text, url text, papers_source text);
|
||||
CREATE TABLE papers(id integer PRIMARY KEY, conf text NOT NULL REFERENCES conferences(slug), track text, award text, ext_id text, title text NOT NULL, abstract text, authors text, keywords text, tldr text, url text, pdf_url text, primary_area text, is_llm integer DEFAULT 0, search tsvector, UNIQUE(conf, ext_id));
|
||||
CREATE TABLE taxonomy(id text PRIMARY KEY, parent text, label text, depth integer, sort integer);
|
||||
CREATE TABLE paper_taxonomy(paper_id integer NOT NULL REFERENCES papers(id), node_id text NOT NULL REFERENCES taxonomy(id), score double precision, is_primary integer, PRIMARY KEY(paper_id, node_id));
|
||||
CREATE TABLE areas(id text PRIMARY KEY, label text, kind text, sort integer);
|
||||
CREATE TABLE roles(id text PRIMARY KEY, label text, descr text, fixes text, varies text, pattern text, sort integer);
|
||||
CREATE TABLE work_types(id text PRIMARY KEY, area text REFERENCES areas(id), role text REFERENCES roles(id), n_papers integer, n_llm_labeled integer);
|
||||
CREATE TABLE benchmarks(id integer PRIMARY KEY, key text UNIQUE, name text, n_papers integer, n_new integer);
|
||||
CREATE TABLE paper_benchmarks(paper_id integer, bench_id integer, purpose text, is_new integer, source text, PRIMARY KEY(paper_id, bench_id));
|
||||
CREATE TABLE paper_meta(paper_id integer PRIMARY KEY, summary text, fixes text, varies text, workflow text, in_agent_scope integer, label_source text);
|
||||
CREATE TABLE paper_work_types(paper_id integer NOT NULL, type_id text NOT NULL, why text, source text, PRIMARY KEY(paper_id, type_id));
|
||||
CREATE TABLE results(id integer PRIMARY KEY, paper_id integer, bench_id integer, system text, base_model text, setting text, metric text, score double precision, unit text);
|
||||
CREATE TABLE type_notes(type_id text PRIMARY KEY, why_same text, workflow text, bench_summary text, narrative text);
|
||||
CREATE TABLE type_reviews(type_id text PRIMARY KEY, json text);
|
||||
`;
|
||||
const INDEXES = `
|
||||
CREATE INDEX idx_papers_conf ON papers(conf);
|
||||
CREATE INDEX idx_papers_search ON papers USING gin(search);
|
||||
CREATE INDEX idx_pt_node ON paper_taxonomy(node_id);
|
||||
CREATE INDEX idx_pb_bench ON paper_benchmarks(bench_id);
|
||||
CREATE INDEX idx_pwt_type ON paper_work_types(type_id);
|
||||
CREATE INDEX idx_res_bench ON results(bench_id);
|
||||
`;
|
||||
// parents first (foreign keys)
|
||||
const TABLES = ['conferences', 'taxonomy', 'areas', 'roles', 'benchmarks', 'papers', 'paper_taxonomy', 'work_types', 'paper_benchmarks',
|
||||
'paper_meta', 'paper_work_types', 'results', 'type_notes', 'type_reviews'];
|
||||
|
||||
(async () => {
|
||||
const lite = new Database(sqliteFile, { readonly: true, fileMustExist: true });
|
||||
const pg = new Client({ connectionString: process.env.DATABASE_URL });
|
||||
await pg.connect();
|
||||
try {
|
||||
await pg.query('DROP SCHEMA IF EXISTS next CASCADE; CREATE SCHEMA next; SET search_path = next');
|
||||
await pg.query(DDL);
|
||||
for (const t of TABLES) {
|
||||
const cols = lite.prepare(`PRAGMA table_info(${t})`).all().map((c) => c.name);
|
||||
const rows = lite.prepare(`SELECT ${cols.map((c) => `"${c}"`).join(',')} FROM ${t}`).raw().all();
|
||||
const per = Math.max(1, Math.floor(30000 / cols.length));
|
||||
for (let i = 0; i < rows.length; i += per) {
|
||||
const chunk = rows.slice(i, i + per);
|
||||
const ph = chunk.map((_, r) => '(' + cols.map((_, c) => `$${r * cols.length + c + 1}`).join(',') + ')').join(',');
|
||||
await pg.query(`INSERT INTO ${t} (${cols.map((c) => `"${c}"`).join(',')}) VALUES ${ph}`, chunk.flat());
|
||||
}
|
||||
const n = (await pg.query(`SELECT COUNT(*)::int AS n FROM ${t}`)).rows[0].n;
|
||||
if (n !== rows.length) throw new Error(`${t}: loaded ${n} of ${rows.length} rows`);
|
||||
console.log(`${t.padEnd(18)} ${n}`);
|
||||
}
|
||||
await pg.query(`UPDATE papers SET search =
|
||||
setweight(to_tsvector('english', coalesce(title,'')), 'A') ||
|
||||
setweight(to_tsvector('english', coalesce(keywords,'')), 'B') ||
|
||||
setweight(to_tsvector('english', coalesce(abstract,'')), 'C') ||
|
||||
setweight(to_tsvector('simple', coalesce(authors,'')), 'D')`);
|
||||
await pg.query(INDEXES);
|
||||
await pg.query('ANALYZE');
|
||||
const papers = (await pg.query('SELECT COUNT(*)::int AS n FROM papers')).rows[0].n;
|
||||
if (papers < 1000) throw new Error(`refusing to publish: only ${papers} papers`);
|
||||
await pg.query('BEGIN');
|
||||
await pg.query('DROP SCHEMA IF EXISTS live CASCADE');
|
||||
await pg.query('ALTER SCHEMA next RENAME TO live');
|
||||
await pg.query('COMMIT');
|
||||
console.log(`published schema live (${papers} papers)`);
|
||||
} catch (e) {
|
||||
await pg.query('ROLLBACK').catch(() => {});
|
||||
console.error('load failed:', e.message);
|
||||
process.exitCode = 1;
|
||||
} finally {
|
||||
await pg.end();
|
||||
lite.close();
|
||||
}
|
||||
})();
|
||||
Reference in New Issue
Block a user