diff --git a/.gitea/workflows/deploy.yml b/.gitea/workflows/deploy.yml index 7dbd579..8690f75 100644 --- a/.gitea/workflows/deploy.yml +++ b/.gitea/workflows/deploy.yml @@ -7,7 +7,7 @@ on: jobs: deploy: runs-on: ces-control - timeout-minutes: 30 + timeout-minutes: 60 steps: - name: Checkout run: | diff --git a/.gitignore b/.gitignore index a5750b1..d364572 100644 --- a/.gitignore +++ b/.gitignore @@ -9,3 +9,4 @@ __pycache__ *-journal *.lock data/papers.db +build diff --git a/components/LegacyTypeView.tsx b/components/LegacyTypeView.tsx index 9dd650b..6e01d8d 100644 --- a/components/LegacyTypeView.tsx +++ b/components/LegacyTypeView.tsx @@ -4,7 +4,7 @@ import { ScoreBars, ScoreScatter, TimelineBars } from './SvgCharts'; import { typeSlug } from '../lib/slug'; import type { getWorkType } from '../lib/worktypes'; -type Data = NonNullable>; +type Data = NonNullable>>; const sc = (d: string) => (d.length > 140 ? d.slice(0, 138) + '…' : d); export default function LegacyTypeView({ data, page, llm, slug }: { data: Data; page: number; llm: boolean; slug: string }) { diff --git a/data/DB_PARTS b/data/DB_PARTS deleted file mode 100644 index b4de394..0000000 --- a/data/DB_PARTS +++ /dev/null @@ -1 +0,0 @@ -11 diff --git a/data/DB_VERSION b/data/DB_VERSION deleted file mode 100644 index cb612a1..0000000 --- a/data/DB_VERSION +++ /dev/null @@ -1 +0,0 @@ -262b7919414f086e0d1ee353ff6404ce3660adae746f21a8e598ab8116d02f0b diff --git a/lib/db.ts b/lib/db.ts index 1b41422..d33eeba 100644 --- a/lib/db.ts +++ b/lib/db.ts @@ -1,13 +1,27 @@ -import Database from 'better-sqlite3'; -import path from 'path'; +import { Pool, types } from 'pg'; -let _db: Database.Database | null = null; +// COUNT()/SUM() come back as bigint (type 20) and numeric (1700): hand them to JS as numbers. +types.setTypeParser(20, (v) => parseInt(v, 10)); +types.setTypeParser(1700, (v) => parseFloat(v)); -/** Read-only handle on data/papers.db (built by scripts/ingest.py). */ -export function db(): Database.Database { - if (!_db) { - const file = process.env.PAPERS_DB ?? path.join(process.cwd(), 'data', 'papers.db'); - _db = new Database(file, { readonly: true, fileMustExist: true }); +const g = globalThis as unknown as { __pgPool?: Pool }; + +function pool(): Pool { + if (!g.__pgPool) { + if (!process.env.DATABASE_URL) throw new Error('DATABASE_URL is not set'); + // scripts/load-pg.js publishes each build as schema "live" + g.__pgPool = new Pool({ connectionString: process.env.DATABASE_URL, max: 8, options: '-c search_path=live' }); } - return _db; + return g.__pgPool; +} + +/** Run SQL written with `?` placeholders (rewritten to $1, $2, ...). */ +export async function query(sql: string, params: unknown[] = []): Promise { + let i = 0; + const text = sql.replace(/\?/g, () => `$${++i}`); + return (await pool().query(text, params as any[])).rows as T[]; +} + +export async function one(sql: string, params: unknown[] = []): Promise { + return (await query(sql, params))[0]; } diff --git a/lib/queries.ts b/lib/queries.ts index ce81341..e608eb3 100644 --- a/lib/queries.ts +++ b/lib/queries.ts @@ -1,24 +1,22 @@ -import { db } from './db'; +import { one, query } from './db'; import { Conference, PAGE_SIZE, Paper, PaperQuery, TaxNode } from './types'; -export function getConferences(): Conference[] { - return db() - .prepare( - `SELECT c.*, (SELECT COUNT(*) FROM papers p WHERE p.conf = c.slug) AS paper_count - FROM conferences c ORDER BY COALESCE(c.start_date, '9999'), c.short` - ) - .all() as Conference[]; +export async function getConferences(): Promise { + return query( + `SELECT c.*, (SELECT COUNT(*) FROM papers p WHERE p.conf = c.slug) AS paper_count + FROM conferences c ORDER BY COALESCE(c.start_date, '9999'), c.short` + ); } -export function getConference(slug: string): Conference | null { - return (getConferences().find((c) => c.slug === slug) ?? null) as Conference | null; +export async function getConference(slug: string): Promise { + return (await getConferences()).find((c) => c.slug === slug) ?? null; } -/** Turn free text into a safe FTS5 prefix query: each token quoted, last one prefix-matched. */ +/** Turn free text into a safe tsquery: letters/digits only, all terms ANDed, last one prefix-matched. */ function ftsQuery(q: string): string | null { - const toks = q.match(/[\p{L}\p{N}][\p{L}\p{N}\-]*/gu); + const toks = q.match(/[\p{L}\p{N}]+/gu); if (!toks) return null; - return toks.map((t, i) => `"${t.replace(/"/g, '')}"${i === toks.length - 1 ? '*' : ''}`).join(' '); + return toks.map((t, i) => `${t}${i === toks.length - 1 ? ':*' : ''}`).join(' & '); } interface Where { sql: string; params: unknown[]; fts: string | null } @@ -27,7 +25,7 @@ function buildWhere(q: Partial): Where { const parts: string[] = []; const params: unknown[] = []; const fts = q.q ? ftsQuery(q.q) : null; - if (fts) { parts.push('p.id IN (SELECT rowid FROM papers_fts WHERE papers_fts MATCH ?)'); params.push(fts); } + if (fts) { parts.push("p.search @@ to_tsquery('english', ?)"); params.push(fts); } if (q.conf) { parts.push('p.conf = ?'); params.push(q.conf); } if (q.track) { parts.push('p.track = ?'); params.push(q.track); } if (q.llm) parts.push('p.is_llm = 1'); @@ -38,57 +36,56 @@ function buildWhere(q: Partial): Where { return { sql: parts.length ? 'WHERE ' + parts.join(' AND ') : '', params, fts }; } -export function searchPapers(q: PaperQuery): { papers: (Paper & { topics: string[] })[]; total: number } { +export async function searchPapers(q: PaperQuery): Promise<{ papers: (Paper & { topics: string[] })[]; total: number }> { const w = buildWhere(q); - const total = (db().prepare(`SELECT COUNT(*) AS n FROM papers p ${w.sql}`).get(...w.params) as { n: number }).n; + const total = (await one<{ n: number }>(`SELECT COUNT(*) AS n FROM papers p ${w.sql}`, w.params))!.n; const ranked = q.sort === 'rank' && !!w.fts; - const order = q.sort === 'title' ? 'p.title COLLATE NOCASE' : ranked ? 'f.r' : 'p.conf, p.id'; - const join = ranked - ? 'JOIN (SELECT rowid, bm25(papers_fts) AS r FROM papers_fts WHERE papers_fts MATCH ?) f ON f.rowid = p.id' - : ''; - const sql = `SELECT p.*, c.short AS conf_short FROM papers p JOIN conferences c ON c.slug = p.conf ${join} ${w.sql} ORDER BY ${order} LIMIT ? OFFSET ?`; - const params = ranked ? [w.fts, ...w.params] : w.params; - const papers = db().prepare(sql).all(...params, PAGE_SIZE, (q.page - 1) * PAGE_SIZE) as Paper[]; - const topicStmt = db().prepare( - `SELECT t.label FROM paper_taxonomy pt JOIN taxonomy t ON t.id = pt.node_id WHERE pt.paper_id = ? ORDER BY pt.is_primary DESC, pt.score DESC` - ); + const order = q.sort === 'title' ? 'lower(p.title), p.id' : ranked ? "ts_rank(p.search, to_tsquery('english', ?)) DESC, p.id" : 'p.conf, p.id'; + const sql = `SELECT p.*, c.short AS conf_short FROM papers p JOIN conferences c ON c.slug = p.conf ${w.sql} ORDER BY ${order} LIMIT ? OFFSET ?`; + const params = ranked ? [...w.params, w.fts] : w.params; + const papers = await query(sql, [...params, PAGE_SIZE, (q.page - 1) * PAGE_SIZE]); + const topicRows = papers.length + ? await query<{ paper_id: number; label: string }>( + `SELECT pt.paper_id, t.label FROM paper_taxonomy pt JOIN taxonomy t ON t.id = pt.node_id WHERE pt.paper_id = ANY(?) ORDER BY pt.is_primary DESC, pt.score DESC`, + [papers.map((p) => p.id)] + ) + : []; + const topics = new Map(); + for (const r of topicRows) (topics.get(r.paper_id) ?? topics.set(r.paper_id, []).get(r.paper_id)!).push(r.label); return { total, - papers: papers.map((p) => ({ - ...p, - abstract: p.abstract ? p.abstract.slice(0, 420) : null, - topics: (topicStmt.all(p.id) as { label: string }[]).map((r) => r.label), - })), + papers: papers.map((p) => ({ ...p, abstract: p.abstract ? p.abstract.slice(0, 420) : null, topics: topics.get(p.id) ?? [] })), }; } -export function getPaper(id: number): (Paper & { topics: { id: string; label: string }[] }) | null { - const p = db().prepare(`SELECT p.*, c.short AS conf_short FROM papers p JOIN conferences c ON c.slug = p.conf WHERE p.id = ?`).get(id) as Paper | undefined; +export async function getPaper(id: number): Promise<(Paper & { topics: { id: string; label: string }[] }) | null> { + if (!Number.isInteger(id)) return null; + const p = await one(`SELECT p.*, c.short AS conf_short FROM papers p JOIN conferences c ON c.slug = p.conf WHERE p.id = ?`, [id]); if (!p) return null; - const topics = db() - .prepare(`SELECT t.id, t.label FROM paper_taxonomy pt JOIN taxonomy t ON t.id = pt.node_id WHERE pt.paper_id = ? ORDER BY pt.is_primary DESC`) - .all(id) as { id: string; label: string }[]; + const topics = await query<{ id: string; label: string }>( + `SELECT t.id, t.label FROM paper_taxonomy pt JOIN taxonomy t ON t.id = pt.node_id WHERE pt.paper_id = ? ORDER BY pt.is_primary DESC`, + [id] + ); return { ...p, topics }; } -export function getTracks(conf: string): string[] { - const sql = conf - ? `SELECT DISTINCT track FROM papers WHERE conf = ? ORDER BY track` - : `SELECT DISTINCT track FROM papers ORDER BY track`; - const rows = (conf ? db().prepare(sql).all(conf) : db().prepare(sql).all()) as { track: string }[]; +export async function getTracks(conf: string): Promise { + const rows = conf + ? await query<{ track: string }>(`SELECT DISTINCT track FROM papers WHERE conf = ? ORDER BY track`, [conf]) + : await query<{ track: string }>(`SELECT DISTINCT track FROM papers ORDER BY track`); return rows.map((r) => r.track).filter(Boolean); } /** Global taxonomy tree (spans all conferences) with distinct-paper counts per node. */ -export function getTaxonomyTree(opts: { llm?: boolean } = {}): TaxNode[] { - const nodes = db().prepare('SELECT id, parent, label, depth FROM taxonomy ORDER BY sort').all() as Omit[]; +export async function getTaxonomyTree(opts: { llm?: boolean } = {}): Promise { + const nodes = await query>('SELECT id, parent, label, depth FROM taxonomy ORDER BY sort'); const where = opts.llm ? 'WHERE p.is_llm = 1' : ''; - const leafRows = db() - .prepare(`SELECT pt.node_id AS id, COUNT(DISTINCT pt.paper_id) AS n FROM paper_taxonomy pt JOIN papers p ON p.id = pt.paper_id ${where} GROUP BY pt.node_id`) - .all() as { id: string; n: number }[]; - const topRows = db() - .prepare(`SELECT t.parent AS id, COUNT(DISTINCT pt.paper_id) AS n FROM paper_taxonomy pt JOIN taxonomy t ON t.id = pt.node_id JOIN papers p ON p.id = pt.paper_id ${where ? where + ' AND' : 'WHERE'} t.parent IS NOT NULL GROUP BY t.parent`) - .all() as { id: string; n: number }[]; + const leafRows = await query<{ id: string; n: number }>( + `SELECT pt.node_id AS id, COUNT(DISTINCT pt.paper_id) AS n FROM paper_taxonomy pt JOIN papers p ON p.id = pt.paper_id ${where} GROUP BY pt.node_id` + ); + const topRows = await query<{ id: string; n: number }>( + `SELECT t.parent AS id, COUNT(DISTINCT pt.paper_id) AS n FROM paper_taxonomy pt JOIN taxonomy t ON t.id = pt.node_id JOIN papers p ON p.id = pt.paper_id ${where ? where + ' AND' : 'WHERE'} t.parent IS NOT NULL GROUP BY t.parent` + ); const counts = new Map([...leafRows, ...topRows].map((r) => [r.id, r.n])); const byId = new Map(); nodes.forEach((n) => byId.set(n.id, { ...n, count: counts.get(n.id) ?? 0, children: [] })); @@ -98,35 +95,35 @@ export function getTaxonomyTree(opts: { llm?: boolean } = {}): TaxNode[] { } /** node id -> { conference slug -> paper count }, for leaves and their parents. */ -export function getNodeConfBreakdown(opts: { llm?: boolean } = {}): Record> { +export async function getNodeConfBreakdown(opts: { llm?: boolean } = {}): Promise>> { const where = opts.llm ? 'WHERE p.is_llm = 1' : ''; - const leaf = db() - .prepare(`SELECT pt.node_id AS id, p.conf AS conf, COUNT(DISTINCT pt.paper_id) AS n FROM paper_taxonomy pt JOIN papers p ON p.id = pt.paper_id ${where} GROUP BY pt.node_id, p.conf`) - .all() as { id: string; conf: string; n: number }[]; - const top = db() - .prepare(`SELECT t.parent AS id, p.conf AS conf, COUNT(DISTINCT pt.paper_id) AS n FROM paper_taxonomy pt JOIN taxonomy t ON t.id = pt.node_id JOIN papers p ON p.id = pt.paper_id ${where ? where + ' AND' : 'WHERE'} t.parent IS NOT NULL GROUP BY t.parent, p.conf`) - .all() as { id: string; conf: string; n: number }[]; + const leaf = await query<{ id: string; conf: string; n: number }>( + `SELECT pt.node_id AS id, p.conf AS conf, COUNT(DISTINCT pt.paper_id) AS n FROM paper_taxonomy pt JOIN papers p ON p.id = pt.paper_id ${where} GROUP BY pt.node_id, p.conf` + ); + const top = await query<{ id: string; conf: string; n: number }>( + `SELECT t.parent AS id, p.conf AS conf, COUNT(DISTINCT pt.paper_id) AS n FROM paper_taxonomy pt JOIN taxonomy t ON t.id = pt.node_id JOIN papers p ON p.id = pt.paper_id ${where ? where + ' AND' : 'WHERE'} t.parent IS NOT NULL GROUP BY t.parent, p.conf` + ); const out: Record> = {}; for (const r of [...leaf, ...top]) (out[r.id] ??= {})[r.conf] = r.n; return out; } /** Conference-tag counts for the current query, ignoring the conference filter itself. */ -export function getConfFacets(q: PaperQuery): Record { +export async function getConfFacets(q: PaperQuery): Promise> { const w = buildWhere({ ...q, conf: '' }); - const rows = db().prepare(`SELECT p.conf AS conf, COUNT(*) AS n FROM papers p ${w.sql} GROUP BY p.conf`).all(...w.params) as { conf: string; n: number }[]; + const rows = await query<{ conf: string; n: number }>(`SELECT p.conf AS conf, COUNT(*) AS n FROM papers p ${w.sql} GROUP BY p.conf`, w.params); return Object.fromEntries(rows.map((r) => [r.conf, r.n])); } -export function getTaxonomyLabel(id: string): string | null { - const r = db().prepare('SELECT label FROM taxonomy WHERE id = ?').get(id) as { label: string } | undefined; +export async function getTaxonomyLabel(id: string): Promise { + const r = await one<{ label: string }>('SELECT label FROM taxonomy WHERE id = ?', [id]); return r?.label ?? null; } -export function getStats() { - const d = db(); - return { - papers: (d.prepare('SELECT COUNT(*) AS n FROM papers').get() as { n: number }).n, - llm: (d.prepare('SELECT COUNT(*) AS n FROM papers WHERE is_llm = 1').get() as { n: number }).n, - }; +export async function getStats() { + const [a, b] = await Promise.all([ + one<{ n: number }>('SELECT COUNT(*) AS n FROM papers'), + one<{ n: number }>('SELECT COUNT(*) AS n FROM papers WHERE is_llm = 1'), + ]); + return { papers: a!.n, llm: b!.n }; } diff --git a/lib/reviews.ts b/lib/reviews.ts index 6907864..ed34b13 100644 --- a/lib/reviews.ts +++ b/lib/reviews.ts @@ -1,4 +1,4 @@ -import { db } from './db'; +import { one, query } from './db'; export interface Review { type_id: string; title: string; abstract: string; @@ -28,26 +28,30 @@ function citationOrder(r: Review): number[] { return seen; } -export function getReview(typeId: string) { +export async function getReview(typeId: string) { let row: { json: string } | undefined; - try { row = db().prepare('SELECT json FROM type_reviews WHERE type_id = ?').get(typeId) as { json: string } | undefined; } catch { return null; } + try { row = await one<{ json: string }>('SELECT json FROM type_reviews WHERE type_id = ?', [typeId]); } catch { return null; } if (!row) return null; const review = JSON.parse(row.json) as Review; const memberIds = review.papers.map((p) => p.id); const order = citationOrder(review).filter((id) => memberIds.includes(id)); const all = [...order, ...memberIds.filter((id) => !order.includes(id))]; - const stmt = db().prepare(`SELECT p.id, p.title, p.authors, c.short || ' 2026' AS venue, COALESCE(c.start_date,'2026-06-01') AS date, p.url FROM papers p JOIN conferences c ON c.slug = p.conf WHERE p.id = ?`); - const refs: RefMeta[] = all.map((id) => stmt.get(id) as RefMeta).filter(Boolean).map((r) => { + const found = all.length + ? await query(`SELECT p.id, p.title, p.authors, c.short || ' 2026' AS venue, COALESCE(c.start_date,'2026-06-01') AS date, p.url FROM papers p JOIN conferences c ON c.slug = p.conf WHERE p.id = ANY(?)`, [all]) + : []; + const byId = new Map(found.map((r) => [r.id, r])); + const refs: RefMeta[] = all.map((id) => byId.get(id)).filter((r): r is RefMeta => !!r).map((r) => { const a = (r.authors ?? '').split(', '); return { ...r, authors: a[0] ? a[0] + (a.length > 1 ? ' et al.' : '') : '' }; }); return { review, refs, citeNum: Object.fromEntries(all.map((id, i) => [id, i + 1])) as Record }; } -export function listReviews() { +export async function listReviews() { try { - return db().prepare(`SELECT r.type_id, json_extract(r.json,'$.title') AS title, json_extract(r.json,'$.abstract') AS abstract, w.n_llm_labeled AS n, w.area, w.role - FROM type_reviews r JOIN work_types w ON w.id = r.type_id ORDER BY w.area, w.n_llm_labeled DESC`).all() as { type_id: string; title: string; abstract: string; n: number; area: string; role: string }[]; + return await query<{ type_id: string; title: string; abstract: string; n: number; area: string; role: string }>( + `SELECT r.type_id, r.json::json->>'title' AS title, r.json::json->>'abstract' AS abstract, w.n_llm_labeled AS n, w.area, w.role + FROM type_reviews r JOIN work_types w ON w.id = r.type_id ORDER BY w.area, w.n_llm_labeled DESC`); } catch { return []; } } export { CITE }; diff --git a/lib/worktypes.ts b/lib/worktypes.ts index 52afa25..ce58a24 100644 --- a/lib/worktypes.ts +++ b/lib/worktypes.ts @@ -1,16 +1,17 @@ -import { db } from './db'; +import { one, query } from './db'; export interface Role { id: string; label: string; descr: string; fixes: string; varies: string; pattern: string; n: number } export interface Area { id: string; label: string; kind: 'agent' | 'general'; n: number } -export function getMatrix(opts: { src?: 'llm' | 'all' } = {}) { +export async function getMatrix(opts: { src?: 'llm' | 'all' } = {}) { const llmOnly = opts.src === 'llm'; - const roles = db().prepare(`SELECT r.*, (SELECT COUNT(*) FROM paper_work_types w WHERE substr(w.type_id, instr(w.type_id,'|')+1) = r.id ${llmOnly ? "AND w.source='llm'" : ''}) AS n FROM roles r ORDER BY sort`).all() as Role[]; - const areas = db().prepare(`SELECT a.*, (SELECT COUNT(*) FROM paper_work_types w WHERE substr(w.type_id,1,instr(w.type_id,'|')-1) = a.id ${llmOnly ? "AND w.source='llm'" : ''}) AS n FROM areas a ORDER BY sort`).all() as Area[]; - const cells = db() - .prepare(`SELECT type_id AS id, COUNT(*) AS n, SUM(source='llm') AS n_llm FROM paper_work_types GROUP BY type_id`) - .all() as { id: string; n: number; n_llm: number }[]; + const src = llmOnly ? "AND w.source='llm'" : ''; + const roles = await query(`SELECT r.*, (SELECT COUNT(*) FROM paper_work_types w WHERE split_part(w.type_id,'|',2) = r.id ${src}) AS n FROM roles r ORDER BY sort`); + const areas = await query(`SELECT a.*, (SELECT COUNT(*) FROM paper_work_types w WHERE split_part(w.type_id,'|',1) = a.id ${src}) AS n FROM areas a ORDER BY sort`); + const cells = await query<{ id: string; n: number; n_llm: number }>( + `SELECT type_id AS id, COUNT(*) AS n, SUM((source='llm')::int) AS n_llm FROM paper_work_types GROUP BY type_id` + ); return { roles, areas: areas.filter((a) => a.n > 0), cells: Object.fromEntries(cells.map((c) => [c.id, llmOnly ? c.n_llm : c.n])) as Record }; } @@ -22,71 +23,78 @@ export interface TypeMember { const j = (s: string | null): string[] => { try { return s ? (JSON.parse(s) as string[]) : []; } catch { return []; } }; const DATE = "COALESCE(c.start_date, '2026-06-01')"; -export function getWorkType(id: string, page: number, srcLlm: boolean) { - const d = db(); - const t = d.prepare(`SELECT * FROM work_types WHERE id = ?`).get(id) as { id: string; area: string; role: string; n_papers: number; n_llm_labeled: number } | undefined; +export async function getWorkType(id: string, page: number, srcLlm: boolean) { + const t = await one<{ id: string; area: string; role: string; n_papers: number; n_llm_labeled: number }>(`SELECT * FROM work_types WHERE id = ?`, [id]); if (!t) return null; - const area = d.prepare('SELECT * FROM areas WHERE id = ?').get(t.area) as Area; - const role = d.prepare('SELECT * FROM roles WHERE id = ?').get(t.role) as Role; + const area = (await one('SELECT * FROM areas WHERE id = ?', [t.area]))!; + const role = (await one('SELECT * FROM roles WHERE id = ?', [t.role]))!; const srcSql = srcLlm ? "AND pwt.source = 'llm'" : ''; const PAGE = 60; - const total = (d.prepare(`SELECT COUNT(*) AS n FROM paper_work_types pwt WHERE pwt.type_id = ? ${srcSql}`).get(id) as { n: number }).n; - const rows = d.prepare(` + const total = (await one<{ n: number }>(`SELECT COUNT(*) AS n FROM paper_work_types pwt WHERE pwt.type_id = ? ${srcSql}`, [id]))!.n; + const rows = await query & { fixes: string; varies: string; workflow: string }>(` SELECT p.id, p.title, p.authors, c.short AS conf_short, c.slug AS conf, ${DATE} AS date, p.track, pwt.why, pwt.source, pm.summary, pm.fixes, pm.varies, pm.workflow FROM paper_work_types pwt JOIN papers p ON p.id = pwt.paper_id JOIN conferences c ON c.slug = p.conf LEFT JOIN paper_meta pm ON pm.paper_id = p.id - WHERE pwt.type_id = ? ${srcSql} ORDER BY date, p.id LIMIT ? OFFSET ?`).all(id, PAGE, (page - 1) * PAGE) as (Omit & { fixes: string; varies: string; workflow: string })[]; + WHERE pwt.type_id = ? ${srcSql} ORDER BY date, p.id LIMIT ? OFFSET ?`, [id, PAGE, (page - 1) * PAGE]); const members: TypeMember[] = rows.map((r) => ({ ...r, fixes: j(r.fixes), varies: j(r.varies), workflow: j(r.workflow) })); - const timeline = d.prepare(` - SELECT c.short AS label, ${DATE} AS date, COUNT(*) AS n FROM paper_work_types pwt JOIN papers p ON p.id = pwt.paper_id JOIN conferences c ON c.slug = p.conf - WHERE pwt.type_id = ? ${srcSql} GROUP BY c.slug ORDER BY date`).all(id) as { label: string; date: string; n: number }[]; - const benchmarks = d.prepare(` - SELECT b.id, b.name, COUNT(DISTINCT pb.paper_id) AS n, SUM(pb.is_new) AS n_new, - (SELECT group_concat(purpose, ' | ') FROM (SELECT DISTINCT pb2.purpose AS purpose FROM paper_benchmarks pb2 JOIN paper_work_types w2 ON w2.paper_id = pb2.paper_id WHERE pb2.bench_id = b.id AND w2.type_id = ? AND pb2.purpose <> '' LIMIT 3)) AS purposes - FROM paper_benchmarks pb JOIN benchmarks b ON b.id = pb.bench_id JOIN paper_work_types pwt ON pwt.paper_id = pb.paper_id - WHERE pwt.type_id = ? GROUP BY b.id ORDER BY n DESC LIMIT 15`).all(id, id) as { id: number; name: string; n: number; n_new: number; purposes: string | null }[]; - const results = getResults({ typeId: id }); - const siblings = d.prepare(`SELECT w.id, w.role, w.n_papers, r.label, r.fixes, r.varies FROM work_types w JOIN roles r ON r.id = w.role WHERE w.area = ? ORDER BY w.n_papers DESC`).all(t.area) as { id: string; role: string; n_papers: number; label: string; fixes: string; varies: string }[]; - const sameRole = d.prepare(`SELECT w.id, w.n_papers, a.label FROM work_types w JOIN areas a ON a.id = w.area WHERE w.role = ? AND w.area <> ? AND a.kind = ? ORDER BY w.n_papers DESC LIMIT 8`).all(t.role, t.area, area.kind) as { id: string; n_papers: number; label: string }[]; - const note = d.prepare('SELECT * FROM type_notes WHERE type_id = ?').get(id) as { why_same: string; workflow: string; bench_summary: string; narrative: string } | undefined; + const [timeline, benchmarks, results, siblings, sameRole, note] = await Promise.all([ + query<{ label: string; date: string; n: number }>(` + SELECT c.short AS label, ${DATE} AS date, COUNT(*) AS n FROM paper_work_types pwt JOIN papers p ON p.id = pwt.paper_id JOIN conferences c ON c.slug = p.conf + WHERE pwt.type_id = ? ${srcSql} GROUP BY c.slug ORDER BY date`, [id]), + query<{ id: number; name: string; n: number; n_new: number; purposes: string | null }>(` + SELECT b.id, b.name, COUNT(DISTINCT pb.paper_id) AS n, SUM(pb.is_new) AS n_new, + (SELECT string_agg(s.purpose, ' | ') FROM (SELECT DISTINCT pb2.purpose AS purpose FROM paper_benchmarks pb2 JOIN paper_work_types w2 ON w2.paper_id = pb2.paper_id WHERE pb2.bench_id = b.id AND w2.type_id = ? AND pb2.purpose <> '' LIMIT 3) s) AS purposes + FROM paper_benchmarks pb JOIN benchmarks b ON b.id = pb.bench_id JOIN paper_work_types pwt ON pwt.paper_id = pb.paper_id + WHERE pwt.type_id = ? GROUP BY b.id ORDER BY n DESC LIMIT 15`, [id, id]), + getResults({ typeId: id }), + query<{ id: string; role: string; n_papers: number; label: string; fixes: string; varies: string }>(`SELECT w.id, w.role, w.n_papers, r.label, r.fixes, r.varies FROM work_types w JOIN roles r ON r.id = w.role WHERE w.area = ? ORDER BY w.n_papers DESC`, [t.area]), + query<{ id: string; n_papers: number; label: string }>(`SELECT w.id, w.n_papers, a.label FROM work_types w JOIN areas a ON a.id = w.area WHERE w.role = ? AND w.area <> ? AND a.kind = ? ORDER BY w.n_papers DESC LIMIT 8`, [t.role, t.area, area.kind]), + one<{ why_same: string; workflow: string; bench_summary: string; narrative: string }>('SELECT * FROM type_notes WHERE type_id = ?', [id]), + ]); const workflows = members.filter((m) => m.workflow.length).slice(0, 6).map((m) => ({ id: m.id, title: m.title, steps: m.workflow })); return { type: t, area, role, total, pageSize: PAGE, members, timeline, benchmarks, results, siblings, sameRole, note: note ? { ...note, workflow: j(note.workflow) } : null, workflows }; } export interface ResultRow { id: number; paper_id: number; title: string; system: string | null; base_model: string | null; setting: string | null; metric: string | null; score: number; unit: string | null; date: string; bench_id: number; bench: string; conf_short: string } -export function getResults(f: { typeId?: string; benchId?: number }): ResultRow[] { +export async function getResults(f: { typeId?: string; benchId?: number }): Promise { const where: string[] = []; const params: unknown[] = []; if (f.benchId) { where.push('r.bench_id = ?'); params.push(f.benchId); } if (f.typeId) { where.push('r.paper_id IN (SELECT paper_id FROM paper_work_types WHERE type_id = ?)'); params.push(f.typeId); } - return db().prepare(` + return query(` SELECT r.id, r.paper_id, p.title, r.system, r.base_model, r.setting, r.metric, r.score, r.unit, ${DATE} AS date, r.bench_id, b.name AS bench, c.short AS conf_short FROM results r JOIN papers p ON p.id = r.paper_id JOIN conferences c ON c.slug = p.conf JOIN benchmarks b ON b.id = r.bench_id - ${where.length ? 'WHERE ' + where.join(' AND ') : ''} ORDER BY date LIMIT 500`).all(...params) as ResultRow[]; + ${where.length ? 'WHERE ' + where.join(' AND ') : ''} ORDER BY date, r.id LIMIT 500`, params); } -export function getBenchmarks(minPapers = 2) { - return db().prepare(`SELECT id, name, n_papers, n_new, (SELECT COUNT(*) FROM results r WHERE r.bench_id = benchmarks.id) AS n_results FROM benchmarks WHERE n_papers >= ? ORDER BY n_papers DESC`).all(minPapers) as { id: number; name: string; n_papers: number; n_new: number; n_results: number }[]; +export async function getBenchmarks(minPapers = 2) { + return query<{ id: number; name: string; n_papers: number; n_new: number; n_results: number }>( + `SELECT id, name, n_papers, n_new, (SELECT COUNT(*) FROM results r WHERE r.bench_id = benchmarks.id) AS n_results FROM benchmarks WHERE n_papers >= ? ORDER BY n_papers DESC, id`, [minPapers]); } -export function getBenchmark(id: number) { - const d = db(); - const b = d.prepare('SELECT * FROM benchmarks WHERE id = ?').get(id) as { id: number; name: string; n_papers: number; n_new: number } | undefined; +export async function getBenchmark(id: number) { + if (!Number.isInteger(id)) return null; + const b = await one<{ id: number; name: string; n_papers: number; n_new: number }>('SELECT * FROM benchmarks WHERE id = ?', [id]); if (!b) return null; - const papers = d.prepare(` - SELECT p.id, p.title, c.short AS conf_short, ${DATE} AS date, pb.purpose, pb.is_new, pb.source, pm.summary, - (SELECT group_concat(w.type_id, ',') FROM paper_work_types w WHERE w.paper_id = p.id) AS types - FROM paper_benchmarks pb JOIN papers p ON p.id = pb.paper_id JOIN conferences c ON c.slug = p.conf LEFT JOIN paper_meta pm ON pm.paper_id = p.id - WHERE pb.bench_id = ? ORDER BY date, p.id LIMIT 300`).all(id) as { id: number; title: string; conf_short: string; date: string; purpose: string; is_new: number; source: string; summary: string | null; types: string | null }[]; - const byType = d.prepare(` - SELECT w.type_id AS id, COUNT(*) AS n FROM paper_benchmarks pb JOIN paper_work_types w ON w.paper_id = pb.paper_id WHERE pb.bench_id = ? GROUP BY w.type_id ORDER BY n DESC LIMIT 12`).all(id) as { id: string; n: number }[]; - return { bench: b, papers, byType, results: getResults({ benchId: id }) }; + const [papers, byType, results] = await Promise.all([ + query<{ id: number; title: string; conf_short: string; date: string; purpose: string; is_new: number; source: string; summary: string | null; types: string | null }>(` + SELECT p.id, p.title, c.short AS conf_short, ${DATE} AS date, pb.purpose, pb.is_new, pb.source, pm.summary, + (SELECT string_agg(w.type_id, ',') FROM paper_work_types w WHERE w.paper_id = p.id) AS types + FROM paper_benchmarks pb JOIN papers p ON p.id = pb.paper_id JOIN conferences c ON c.slug = p.conf LEFT JOIN paper_meta pm ON pm.paper_id = p.id + WHERE pb.bench_id = ? ORDER BY date, p.id LIMIT 300`, [id]), + query<{ id: string; n: number }>(` + SELECT w.type_id AS id, COUNT(*) AS n FROM paper_benchmarks pb JOIN paper_work_types w ON w.paper_id = pb.paper_id WHERE pb.bench_id = ? GROUP BY w.type_id ORDER BY n DESC, w.type_id LIMIT 12`, [id]), + getResults({ benchId: id }), + ]); + return { bench: b, papers, byType, results }; } -export function getPaperWork(paperId: number) { - const d = db(); - const types = d.prepare(`SELECT w.type_id AS id, w.why, w.source, a.label AS area_label, r.label AS role_label, r.fixes, r.varies FROM paper_work_types w - JOIN areas a ON a.id = substr(w.type_id,1,instr(w.type_id,'|')-1) JOIN roles r ON r.id = substr(w.type_id,instr(w.type_id,'|')+1) WHERE w.paper_id = ?`).all(paperId) as { id: string; why: string; source: string; area_label: string; role_label: string; fixes: string; varies: string }[]; - const meta = d.prepare('SELECT * FROM paper_meta WHERE paper_id = ?').get(paperId) as { summary: string; fixes: string; varies: string; workflow: string; label_source: string } | undefined; - const benchmarks = d.prepare(`SELECT b.id, b.name, pb.purpose, pb.is_new FROM paper_benchmarks pb JOIN benchmarks b ON b.id = pb.bench_id WHERE pb.paper_id = ?`).all(paperId) as { id: number; name: string; purpose: string; is_new: number }[]; +export async function getPaperWork(paperId: number) { + const [types, meta, benchmarks] = await Promise.all([ + query<{ id: string; why: string; source: string; area_label: string; role_label: string; fixes: string; varies: string }>( + `SELECT w.type_id AS id, w.why, w.source, a.label AS area_label, r.label AS role_label, r.fixes, r.varies FROM paper_work_types w + JOIN areas a ON a.id = split_part(w.type_id,'|',1) JOIN roles r ON r.id = split_part(w.type_id,'|',2) WHERE w.paper_id = ?`, [paperId]), + one<{ summary: string; fixes: string; varies: string; workflow: string; label_source: string }>('SELECT * FROM paper_meta WHERE paper_id = ?', [paperId]), + query<{ id: number; name: string; purpose: string; is_new: number }>(`SELECT b.id, b.name, pb.purpose, pb.is_new FROM paper_benchmarks pb JOIN benchmarks b ON b.id = pb.bench_id WHERE pb.paper_id = ?`, [paperId]), + ]); return { types, meta: meta ? { ...meta, fixes: j(meta.fixes), varies: j(meta.varies), workflow: j(meta.workflow) } : null, benchmarks }; } diff --git a/next.config.js b/next.config.js index fb111e9..3dd7ef1 100644 --- a/next.config.js +++ b/next.config.js @@ -1,5 +1,4 @@ /** @type {import('next').NextConfig} */ module.exports = { reactStrictMode: true, - experimental: { serverComponentsExternalPackages: ['better-sqlite3'] }, }; diff --git a/package-lock.json b/package-lock.json index e24ff76..c9e077d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -8,16 +8,18 @@ "name": "llm-general-survey-2026", "version": "0.1.0", "dependencies": { - "better-sqlite3": "^11.5.0", "next": "^14.2.15", + "pg": "^8.13.1", "react": "^18.3.1", "react-dom": "^18.3.1" }, "devDependencies": { "@types/better-sqlite3": "^7.6.11", "@types/node": "^22.7.0", + "@types/pg": "^8.11.10", "@types/react": "^18.3.11", "@types/react-dom": "^18.3.0", + "better-sqlite3": "^11.5.0", "typescript": "^5.6.2" } }, @@ -207,6 +209,18 @@ "undici-types": "~6.21.0" } }, + "node_modules/@types/pg": { + "version": "8.23.1", + "resolved": "https://registry.npmjs.org/@types/pg/-/pg-8.23.1.tgz", + "integrity": "sha512-fKVHpikPdg4GKks3JuLEhvwSyvwzF23hnabPy6DD8ljVbC7+6J5dQzdv4arV6jqq57djnMgs1HKBxX4P8aBI3A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*", + "pg-protocol": "*", + "pg-types": "^2.2.0" + } + }, "node_modules/@types/prop-types": { "version": "15.7.15", "resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.15.tgz", @@ -239,6 +253,7 @@ "version": "1.5.1", "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "dev": true, "funding": [ { "type": "github", @@ -259,6 +274,7 @@ "version": "11.10.0", "resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-11.10.0.tgz", "integrity": "sha512-EwhOpyXiOEL/lKzHz9AW1msWFNzGc/z+LzeB3/jnFJpxu+th2yqvzsSWas1v9jgs9+xiXJcD5A8CJxAG2TaghQ==", + "dev": true, "hasInstallScript": true, "license": "MIT", "dependencies": { @@ -270,6 +286,7 @@ "version": "1.5.0", "resolved": "https://registry.npmjs.org/bindings/-/bindings-1.5.0.tgz", "integrity": "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==", + "dev": true, "license": "MIT", "dependencies": { "file-uri-to-path": "1.0.0" @@ -279,6 +296,7 @@ "version": "4.1.0", "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz", "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==", + "dev": true, "license": "MIT", "dependencies": { "buffer": "^5.5.0", @@ -290,6 +308,7 @@ "version": "5.7.1", "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", + "dev": true, "funding": [ { "type": "github", @@ -345,6 +364,7 @@ "version": "1.1.4", "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz", "integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==", + "dev": true, "license": "ISC" }, "node_modules/client-only": { @@ -364,6 +384,7 @@ "version": "6.0.0", "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz", "integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==", + "dev": true, "license": "MIT", "dependencies": { "mimic-response": "^3.1.0" @@ -379,6 +400,7 @@ "version": "0.6.0", "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz", "integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==", + "dev": true, "license": "MIT", "engines": { "node": ">=4.0.0" @@ -388,6 +410,7 @@ "version": "2.1.2", "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "dev": true, "license": "Apache-2.0", "engines": { "node": ">=8" @@ -397,6 +420,7 @@ "version": "1.4.5", "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz", "integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==", + "dev": true, "license": "MIT", "dependencies": { "once": "^1.4.0" @@ -406,6 +430,7 @@ "version": "2.0.3", "resolved": "https://registry.npmjs.org/expand-template/-/expand-template-2.0.3.tgz", "integrity": "sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==", + "dev": true, "license": "(MIT OR WTFPL)", "engines": { "node": ">=6" @@ -415,18 +440,21 @@ "version": "1.0.0", "resolved": "https://registry.npmjs.org/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz", "integrity": "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==", + "dev": true, "license": "MIT" }, "node_modules/fs-constants": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz", "integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==", + "dev": true, "license": "MIT" }, "node_modules/github-from-package": { "version": "0.0.0", "resolved": "https://registry.npmjs.org/github-from-package/-/github-from-package-0.0.0.tgz", "integrity": "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==", + "dev": true, "license": "MIT" }, "node_modules/graceful-fs": { @@ -439,6 +467,7 @@ "version": "1.2.1", "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", + "dev": true, "funding": [ { "type": "github", @@ -459,12 +488,14 @@ "version": "2.0.4", "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "dev": true, "license": "ISC" }, "node_modules/ini": { "version": "1.3.8", "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz", "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==", + "dev": true, "license": "ISC" }, "node_modules/js-tokens": { @@ -489,6 +520,7 @@ "version": "3.1.0", "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz", "integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==", + "dev": true, "license": "MIT", "engines": { "node": ">=10" @@ -501,6 +533,7 @@ "version": "1.2.8", "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "dev": true, "license": "MIT", "funding": { "url": "https://github.com/sponsors/ljharb" @@ -510,6 +543,7 @@ "version": "0.5.3", "resolved": "https://registry.npmjs.org/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz", "integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==", + "dev": true, "license": "MIT" }, "node_modules/nanoid": { @@ -534,6 +568,7 @@ "version": "2.0.0", "resolved": "https://registry.npmjs.org/napi-build-utils/-/napi-build-utils-2.0.0.tgz", "integrity": "sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA==", + "dev": true, "license": "MIT" }, "node_modules/next": { @@ -590,6 +625,7 @@ "version": "3.99.0", "resolved": "https://registry.npmjs.org/node-abi/-/node-abi-3.99.0.tgz", "integrity": "sha512-lLdwkeg2XUVPTHqWjPltTxH81zbQNbUWC+AEb9ni50KjxkUzAAx1HGtMT21sbntzfUGfIphhcklvs3imJeqDXw==", + "dev": true, "license": "MIT", "dependencies": { "semver": "^7.3.5" @@ -602,11 +638,101 @@ "version": "1.4.0", "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "dev": true, "license": "ISC", "dependencies": { "wrappy": "1" } }, + "node_modules/pg": { + "version": "8.23.1", + "resolved": "https://registry.npmjs.org/pg/-/pg-8.23.1.tgz", + "integrity": "sha512-aL96AHANtWjPLDOLqnhx+ngp9+UK7ETEU8VJrDCGvsSSi/mGLcWYsS6Herg7lmaBJe4uwrfqsa7gTEFaSizDoQ==", + "license": "MIT", + "dependencies": { + "pg-connection-string": "^2.14.1", + "pg-pool": "^3.14.0", + "pg-protocol": "^1.16.1", + "pg-types": "2.2.0", + "pgpass": "1.0.5" + }, + "engines": { + "node": ">= 16.0.0" + }, + "optionalDependencies": { + "pg-cloudflare": "^1.4.1" + }, + "peerDependencies": { + "pg-native": ">=3.0.1" + }, + "peerDependenciesMeta": { + "pg-native": { + "optional": true + } + } + }, + "node_modules/pg-cloudflare": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/pg-cloudflare/-/pg-cloudflare-1.4.1.tgz", + "integrity": "sha512-6PQbsFWZcp9EmJEwy5cGQ2La+AMWpP46lgbb8X+U/XsHIUweYDNCpeuKck5RxL2MdVFi7krbbEi5nX4Zh7JhrQ==", + "license": "MIT", + "optional": true + }, + "node_modules/pg-connection-string": { + "version": "2.14.1", + "resolved": "https://registry.npmjs.org/pg-connection-string/-/pg-connection-string-2.14.1.tgz", + "integrity": "sha512-qR3kGNPBLpCNtz0evbKA0Y/MRFXwSSdT+pTJvYp/bXTcReZbvX1kzF0IyTc1QnxqF7AZbOeBhNL8R5mYQZV/MA==", + "license": "MIT" + }, + "node_modules/pg-int8": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/pg-int8/-/pg-int8-1.0.1.tgz", + "integrity": "sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==", + "license": "ISC", + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/pg-pool": { + "version": "3.14.0", + "resolved": "https://registry.npmjs.org/pg-pool/-/pg-pool-3.14.0.tgz", + "integrity": "sha512-gKtPkFdQPU3DksooVLi9LsjZxrsBUZIpa+7aVx+LV5pNh0KzP4Zleud2po+ConrxbuXGBJ6Hfer6hdgpIBpBaw==", + "license": "MIT", + "peerDependencies": { + "pg": ">=8.0" + } + }, + "node_modules/pg-protocol": { + "version": "1.16.1", + "resolved": "https://registry.npmjs.org/pg-protocol/-/pg-protocol-1.16.1.tgz", + "integrity": "sha512-p9VOFMiHB/ZbJATetbg+99PxssTVSQRnyuPSQ67mN1+1KBOjZaZ83ZQzltnxPhJwSsC3nwVjJ10DVJlerbFzLg==", + "license": "MIT" + }, + "node_modules/pg-types": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/pg-types/-/pg-types-2.2.0.tgz", + "integrity": "sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==", + "license": "MIT", + "dependencies": { + "pg-int8": "1.0.1", + "postgres-array": "~2.0.0", + "postgres-bytea": "~1.0.0", + "postgres-date": "~1.0.4", + "postgres-interval": "^1.1.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/pgpass": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/pgpass/-/pgpass-1.0.5.tgz", + "integrity": "sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug==", + "license": "MIT", + "dependencies": { + "split2": "^4.1.0" + } + }, "node_modules/picocolors": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", @@ -641,11 +767,51 @@ "node": "^10 || ^12 || >=14" } }, + "node_modules/postgres-array": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-2.0.0.tgz", + "integrity": "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA==", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/postgres-bytea": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/postgres-bytea/-/postgres-bytea-1.0.1.tgz", + "integrity": "sha512-5+5HqXnsZPE65IJZSMkZtURARZelel2oXUEO8rH83VS/hxH5vv1uHquPg5wZs8yMAfdv971IU+kcPUczi7NVBQ==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/postgres-date": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/postgres-date/-/postgres-date-1.0.7.tgz", + "integrity": "sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/postgres-interval": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/postgres-interval/-/postgres-interval-1.2.0.tgz", + "integrity": "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==", + "license": "MIT", + "dependencies": { + "xtend": "^4.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/prebuild-install": { "version": "7.1.3", "resolved": "https://registry.npmjs.org/prebuild-install/-/prebuild-install-7.1.3.tgz", "integrity": "sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug==", "deprecated": "No longer maintained. Please contact the author of the relevant native addon; alternatives are available.", + "dev": true, "license": "MIT", "dependencies": { "detect-libc": "^2.0.0", @@ -672,6 +838,7 @@ "version": "3.0.4", "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.4.tgz", "integrity": "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==", + "dev": true, "license": "MIT", "dependencies": { "end-of-stream": "^1.1.0", @@ -682,6 +849,7 @@ "version": "1.2.8", "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz", "integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==", + "dev": true, "license": "(BSD-2-Clause OR MIT OR Apache-2.0)", "dependencies": { "deep-extend": "^0.6.0", @@ -722,6 +890,7 @@ "version": "3.6.2", "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "dev": true, "license": "MIT", "dependencies": { "inherits": "^2.0.3", @@ -736,6 +905,7 @@ "version": "5.2.1", "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "dev": true, "funding": [ { "type": "github", @@ -765,6 +935,7 @@ "version": "7.8.5", "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "dev": true, "license": "ISC", "bin": { "semver": "bin/semver.js" @@ -777,6 +948,7 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/simple-concat/-/simple-concat-1.0.1.tgz", "integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==", + "dev": true, "funding": [ { "type": "github", @@ -797,6 +969,7 @@ "version": "4.0.1", "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-4.0.1.tgz", "integrity": "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==", + "dev": true, "funding": [ { "type": "github", @@ -827,6 +1000,15 @@ "node": ">=0.10.0" } }, + "node_modules/split2": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz", + "integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==", + "license": "ISC", + "engines": { + "node": ">= 10.x" + } + }, "node_modules/streamsearch": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-1.1.0.tgz", @@ -839,6 +1021,7 @@ "version": "1.3.0", "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "dev": true, "license": "MIT", "dependencies": { "safe-buffer": "~5.2.0" @@ -848,6 +1031,7 @@ "version": "2.0.1", "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", "integrity": "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==", + "dev": true, "license": "MIT", "engines": { "node": ">=0.10.0" @@ -880,6 +1064,7 @@ "version": "2.1.5", "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.5.tgz", "integrity": "sha512-OboTd8mmMhZDNPV+UjQcK9yKAatXu2aJ+r1w4im1Otd4M4fl2hwvdoXUxIYHFTHWK/3y3FarBP70v3vwmGlOxw==", + "dev": true, "license": "MIT", "dependencies": { "chownr": "^1.1.1", @@ -892,6 +1077,7 @@ "version": "2.2.0", "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz", "integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==", + "dev": true, "license": "MIT", "dependencies": { "bl": "^4.0.3", @@ -914,6 +1100,7 @@ "version": "0.6.0", "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", "integrity": "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==", + "dev": true, "license": "Apache-2.0", "dependencies": { "safe-buffer": "^5.0.1" @@ -947,13 +1134,24 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "dev": true, "license": "MIT" }, "node_modules/wrappy": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "dev": true, "license": "ISC" + }, + "node_modules/xtend": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", + "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==", + "license": "MIT", + "engines": { + "node": ">=0.4" + } } } } diff --git a/package.json b/package.json index 09a7178..f196ffc 100644 --- a/package.json +++ b/package.json @@ -4,23 +4,26 @@ "private": true, "scripts": { "data:fetch": "bash scripts/fetch_data.sh", - "data:build": "python3 scripts/ingest.py", + "data:build": "python3 scripts/ingest.py --out build/papers.db && python3 scripts/build_worktypes.py --db build/papers.db", "dev": "next dev", "build": "next build", "start": "next start", - "typecheck": "tsc --noEmit" + "typecheck": "tsc --noEmit", + "data:load": "node scripts/load-pg.js --sqlite build/papers.db" }, "dependencies": { - "better-sqlite3": "^11.5.0", "next": "^14.2.15", + "pg": "^8.13.1", "react": "^18.3.1", "react-dom": "^18.3.1" }, "devDependencies": { "@types/better-sqlite3": "^7.6.11", "@types/node": "^22.7.0", + "@types/pg": "^8.11.10", "@types/react": "^18.3.11", "@types/react-dom": "^18.3.0", + "better-sqlite3": "^11.5.0", "typescript": "^5.6.2" } } diff --git a/pages/benchmarks/[id].tsx b/pages/benchmarks/[id].tsx index 426f4d5..dcede2b 100644 --- a/pages/benchmarks/[id].tsx +++ b/pages/benchmarks/[id].tsx @@ -5,9 +5,9 @@ import { ScoreBars, ScoreScatter } from '../../components/SvgCharts'; import { getBenchmark } from '../../lib/worktypes'; import { typeSlug } from '../../lib/slug'; -type Data = NonNullable>; +type Data = NonNullable>>; export const getServerSideProps: GetServerSideProps<{ data: Data }> = async ({ params }) => { - const data = getBenchmark(Number(params?.id)); + const data = await getBenchmark(Number(params?.id)); return data ? { props: { data } } : { notFound: true }; }; diff --git a/pages/benchmarks/index.tsx b/pages/benchmarks/index.tsx index 834edb0..8173628 100644 --- a/pages/benchmarks/index.tsx +++ b/pages/benchmarks/index.tsx @@ -3,8 +3,8 @@ import Link from 'next/link'; import Layout from '../../components/Layout'; import { getBenchmarks } from '../../lib/worktypes'; -interface Props { rows: ReturnType } -export const getServerSideProps: GetServerSideProps = async () => ({ props: { rows: getBenchmarks(2) } }); +interface Props { rows: Awaited> } +export const getServerSideProps: GetServerSideProps = async () => ({ props: { rows: await getBenchmarks(2) } }); export default function Benchmarks({ rows }: Props) { return ( diff --git a/pages/conferences/[slug].tsx b/pages/conferences/[slug].tsx index eb6c197..a2163d6 100644 --- a/pages/conferences/[slug].tsx +++ b/pages/conferences/[slug].tsx @@ -7,11 +7,11 @@ import { Conference } from '../../lib/types'; interface Props { conf: Conference; tops: { id: string; label: string; n: number }[]; tracks: string[] } export const getServerSideProps: GetServerSideProps = async ({ params }) => { - const conf = getConference(String(params?.slug)); + const conf = await getConference(String(params?.slug)); if (!conf) return { notFound: true }; - const bd = getNodeConfBreakdown(); - const tops = getTaxonomyTree().map((t) => ({ id: t.id, label: t.label, n: bd[t.id]?.[conf.slug] ?? 0 })).filter((t) => t.n > 0); - return { props: { conf, tops, tracks: getTracks(conf.slug) } }; + const [bd, tree, tracks] = await Promise.all([getNodeConfBreakdown(), getTaxonomyTree(), getTracks(conf.slug)]); + const tops = tree.map((t) => ({ id: t.id, label: t.label, n: bd[t.id]?.[conf.slug] ?? 0 })).filter((t) => t.n > 0); + return { props: { conf, tops, tracks } }; }; export default function ConferencePage({ conf, tops, tracks }: Props) { diff --git a/pages/index.tsx b/pages/index.tsx index 19fdf31..23bc05b 100644 --- a/pages/index.tsx +++ b/pages/index.tsx @@ -11,14 +11,17 @@ interface Props { today: string; } -export const getServerSideProps: GetServerSideProps = async () => ({ - props: { - conferences: getConferences(), - stats: getStats(), - topics: getTaxonomyTree({ llm: true }).filter((t) => t.id !== 'other'), - today: new Date().toISOString().slice(0, 10), - }, -}); +export const getServerSideProps: GetServerSideProps = async () => { + const [conferences, stats, tree] = await Promise.all([getConferences(), getStats(), getTaxonomyTree({ llm: true })]); + return { + props: { + conferences, + stats, + topics: tree.filter((t) => t.id !== 'other'), + today: new Date().toISOString().slice(0, 10), + }, + }; +}; const fmt = (c: Conference) => c.start_date ? `${c.start_date}${c.end_date ? ' → ' + c.end_date.slice(5) : ''}` : '—'; diff --git a/pages/papers/[id].tsx b/pages/papers/[id].tsx index f448ed1..a19f0eb 100644 --- a/pages/papers/[id].tsx +++ b/pages/papers/[id].tsx @@ -6,11 +6,11 @@ import { getPaperWork } from '../../lib/worktypes'; import { typeSlug } from '../../lib/slug'; import { Paper } from '../../lib/types'; -type Props = { paper: Paper & { topics: { id: string; label: string }[] }; work: ReturnType }; +type Props = { paper: Paper & { topics: { id: string; label: string }[] }; work: Awaited> }; export const getServerSideProps: GetServerSideProps = async ({ params }) => { - const paper = getPaper(Number(params?.id)); - return paper ? { props: { paper, work: getPaperWork(paper.id) } } : { notFound: true }; + const paper = await getPaper(Number(params?.id)); + return paper ? { props: { paper, work: await getPaperWork(paper.id) } } : { notFound: true }; }; export default function PaperPage({ paper: p, work }: Props) { diff --git a/pages/papers/index.tsx b/pages/papers/index.tsx index 8a91113..47931d6 100644 --- a/pages/papers/index.tsx +++ b/pages/papers/index.tsx @@ -20,17 +20,24 @@ interface Props { export const getServerSideProps: GetServerSideProps = async ({ query: raw }) => { const query = parsePaperQuery(raw); - const { papers, total } = searchPapers(query); + const [{ papers, total }, conferences, tracks, tree, facets, nodeLabel] = await Promise.all([ + searchPapers(query), + getConferences(), + getTracks(query.conf), + getTaxonomyTree({ llm: query.llm }), + getConfFacets(query), + query.node ? getTaxonomyLabel(query.node) : Promise.resolve(null), + ]); return { props: { query, papers, total, - conferences: getConferences().filter((c) => c.paper_count > 0), - tracks: getTracks(query.conf), - tree: getTaxonomyTree({ llm: query.llm }), - facets: getConfFacets(query), - nodeLabel: query.node ? getTaxonomyLabel(query.node) : null, + conferences: conferences.filter((c) => c.paper_count > 0), + tracks, + tree, + facets, + nodeLabel, }, }; }; diff --git a/pages/taxonomy.tsx b/pages/taxonomy.tsx index 91e2810..cf9ac9b 100644 --- a/pages/taxonomy.tsx +++ b/pages/taxonomy.tsx @@ -14,12 +14,13 @@ interface Props { export const getServerSideProps: GetServerSideProps = async ({ query }) => { const llm = query.llm === '1'; + const [tree, breakdown, confs] = await Promise.all([getTaxonomyTree({ llm }), getNodeConfBreakdown({ llm }), getConferences()]); return { props: { - tree: getTaxonomyTree({ llm }), + tree, llm, - breakdown: getNodeConfBreakdown({ llm }), - confLabel: Object.fromEntries(getConferences().map((c) => [c.slug, c.short])), + breakdown, + confLabel: Object.fromEntries(confs.map((c) => [c.slug, c.short])), }, }; }; diff --git a/pages/work-types/[slug].tsx b/pages/work-types/[slug].tsx index 7c9d893..e270b29 100644 --- a/pages/work-types/[slug].tsx +++ b/pages/work-types/[slug].tsx @@ -9,8 +9,8 @@ import { getReview } from '../../lib/reviews'; import { typeIdFromSlug, typeSlug } from '../../lib/slug'; import { getWorkType } from '../../lib/worktypes'; -type Data = NonNullable>; -type Rev = NonNullable>; +type Data = NonNullable>>; +type Rev = NonNullable>>; interface Props { data: Data; rev: Rev | null; page: number; llm: boolean; slug: string } export const getServerSideProps: GetServerSideProps = async ({ params, query }) => { @@ -18,9 +18,9 @@ export const getServerSideProps: GetServerSideProps = async ({ params, qu const page = Math.max(1, parseInt(String(query.page ?? '1'), 10) || 1); const llm = query.src === 'llm'; const id = typeIdFromSlug(slug); - const data = getWorkType(id, page, llm); + const data = await getWorkType(id, page, llm); if (!data) return { notFound: true }; - return { props: { data, rev: query.view === 'data' ? null : getReview(id), page, llm, slug } }; + return { props: { data, rev: query.view === 'data' ? null : await getReview(id), page, llm, slug } }; }; export default function WorkTypePage(props: Props) { diff --git a/pages/work-types/index.tsx b/pages/work-types/index.tsx index ab4e6fd..fa2db29 100644 --- a/pages/work-types/index.tsx +++ b/pages/work-types/index.tsx @@ -5,11 +5,11 @@ import { Area, Role, getMatrix } from '../../lib/worktypes'; import { typeSlug } from '../../lib/slug'; import { listReviews } from '../../lib/reviews'; -interface Props { roles: Role[]; areas: Area[]; cells: Record; src: 'llm' | 'all'; reviews: ReturnType } +interface Props { roles: Role[]; areas: Area[]; cells: Record; src: 'llm' | 'all'; reviews: Awaited> } export const getServerSideProps: GetServerSideProps = async ({ query }) => { const src = query.src === 'llm' ? 'llm' : 'all'; - return { props: { ...getMatrix({ src }), src, reviews: listReviews() } }; + return { props: { ...(await getMatrix({ src })), src, reviews: await listReviews() } }; }; export default function WorkTypes({ roles, areas, cells, src, reviews }: Props) { diff --git a/scripts/deploy.sh b/scripts/deploy.sh index 7ad2b80..2922b7a 100644 --- a/scripts/deploy.sh +++ b/scripts/deploy.sh @@ -1,51 +1,86 @@ #!/bin/sh -# Permanent deploy on the ces-control host: /opt/llm-survey/releases/, `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 }" 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 </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 diff --git a/scripts/load-pg.js b/scripts/load-pg.js new file mode 100644 index 0000000..21020cd --- /dev/null +++ b/scripts/load-pg.js @@ -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(); + } +})();