Add verified PostgreSQL migration and shared research queries
Metadata integrity checks / metadata (push) Successful in 46s

This commit is contained in:
2026-11-07 02:09:19 +08:00
parent 029e73cafe
commit a3b677bdf2
17 changed files with 748 additions and 14 deletions
+1
View File
@@ -0,0 +1 @@
"""PostgreSQL migration and read access for the paper index."""
+83
View File
@@ -0,0 +1,83 @@
"""Libpq service connections; credentials never belong in CLI arguments."""
from collections.abc import Mapping
import re
SEARCH_VECTOR = "to_tsvector('english'::regconfig,coalesce(title,'') || ' ' || coalesce(abstract,''))"
def driver():
try:
import psycopg
except ImportError as error:
raise RuntimeError('Install paper-atlas[postgres] on the approved remote runner') from error
return psycopg
def connect(service, *, readonly=False):
if not re.fullmatch(r'[A-Za-z0-9_-]+', service):
raise ValueError('Use a libpq service name, never a password or connection URL')
connection = driver().connect(service=service, connect_timeout=15, autocommit=True,
application_name='paper-atlas')
connection.execute("SET timezone='UTC'")
connection.execute("SET lock_timeout='5s'")
connection.execute("SET work_mem='2MB'")
connection.execute("SET maintenance_work_mem='16MB'")
connection.execute('SET max_parallel_workers_per_gather=0')
connection.execute('SET max_parallel_maintenance_workers=0')
if readonly:
connection.execute('BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY')
return connection
class Row(Mapping):
"""The small mapping/positional interface used by existing query output."""
def __init__(self, columns, values):
self.columns, self.values = columns, values
def __getitem__(self, key):
return self.values[key if isinstance(key, int) else self.columns.index(key)]
def __iter__(self):
return iter(self.columns)
def __len__(self):
return len(self.columns)
def row_factory(cursor):
columns = [column.name for column in cursor.description] if cursor.description else []
return lambda values: Row(columns, values)
class ReadConnection:
postgres = True
def __init__(self, service, schema=None):
if schema is not None and not re.fullmatch(r'[a-z][a-z0-9_]{0,35}', schema):
raise ValueError('Invalid schema name')
self.connection = connect(service, readonly=True)
from paper_atlas.postgres.schema import quote
if schema is not None:
self.connection.execute('SET LOCAL search_path TO ' + quote(schema) + ',pg_catalog')
self.connection.row_factory = row_factory
if not self.has_table('papers'):
self.close()
raise RuntimeError('PostgreSQL publication is not ready in the configured search_path')
def execute(self, query, params=()):
# All caller SQL is static; user values are always bound parameters.
if 'sqlite_master' in query:
match = re.search(r"name='([a-z_]+)'", query)
if not match or match[1] not in ('decision_sources', 'submission_sources', 'venue_aliases'):
raise ValueError('Unsupported legacy table lookup')
return self.connection.execute('''SELECT 1 FROM information_schema.tables
WHERE table_schema=current_schema() AND table_name=%s''',
(match[1],))
return self.connection.execute(query.replace('?', '%s'), params)
def has_table(self, name):
return bool(self.connection.execute('''SELECT 1 FROM information_schema.tables
WHERE table_schema=current_schema() AND table_name=%s''', (name,)).fetchone())
def close(self):
self.connection.close()
+232
View File
@@ -0,0 +1,232 @@
"""Resumable, unpublished COPY followed by complete ordered content verification."""
import argparse
from contextlib import closing
import fcntl
import hashlib
import json
from pathlib import Path
import re
import shutil
import sqlite3
import uuid
import zlib
from paper_atlas.db.submissions import timestamp
from paper_atlas.postgres.client import connect, SEARCH_VECTOR
from paper_atlas.postgres.schema import TABLES, inspect, fingerprint, quote, select_sql, table_sql
def digest_file(path):
digest = hashlib.sha256()
with path.open('rb') as stream:
while block := stream.read(8 * 1024 ** 2):
digest.update(block)
return digest.hexdigest()
def update_hash(digest, row):
# Raw JSON columns remain text: whitespace, escapes and source evidence survive.
data = json.dumps(tuple(row), ensure_ascii=False, separators=(',', ':')).encode()
digest.update(len(data).to_bytes(8, 'big')); digest.update(data)
def save(path, result):
path.parent.mkdir(parents=True, exist_ok=True)
part = path.with_suffix(path.suffix + '.part')
part.write_text(json.dumps(result, ensure_ascii=False, indent=2) + '\n')
part.replace(path)
def free_space(path, minimum):
if path and shutil.disk_usage(path).free < minimum * 1024 ** 3:
raise RuntimeError('Migration storage headroom fell below the configured minimum')
def qualify(schema, table):
return quote(schema) + '.' + quote(table)
def add_constraints(pg, stage, plan):
def constraint(table, name, clause):
exists = pg.execute('''SELECT 1 FROM pg_constraint co JOIN pg_class cl ON cl.oid=co.conrelid
JOIN pg_namespace ns ON ns.oid=cl.relnamespace WHERE ns.nspname=%s AND cl.relname=%s AND co.conname=%s''',
(stage, table, name)).fetchone()
if not exists:
pg.execute('ALTER TABLE ' + qualify(stage, table) + ' ADD CONSTRAINT ' + quote(name) + ' ' + clause)
for table, spec in plan.items():
constraint(table, table + '_pkey', 'PRIMARY KEY (' + ','.join(map(quote, spec['pk'])) + ')')
for number, index in enumerate(spec['indexes']):
if index['origin'] == 'u':
constraint(table, table + '_unique_' + str(number), 'UNIQUE (' + ','.join(quote(n) for n, desc in index['terms']) + ')')
else:
terms = ','.join(quote(n) + (' DESC' if desc else '') for n, desc in index['terms'])
pg.execute('CREATE ' + ('UNIQUE ' if index['unique'] else '') + 'INDEX IF NOT EXISTS ' +
quote(index['name']) + ' ON ' + qualify(stage, table) + '(' + terms + ')')
for table, spec in plan.items():
for number, fk in enumerate(spec['foreign_keys']):
clause = ('FOREIGN KEY (' + ','.join(map(quote, fk['columns'])) + ') REFERENCES ' +
qualify(stage, fk['table']) + '(' + ','.join(map(quote, fk['references'])) + ') NOT VALID')
constraint(table, table + '_fk_' + str(number), clause)
for number, check in enumerate(spec['checks']):
constraint(table, table + '_check_' + str(number), 'CHECK (' + check + ') NOT VALID')
constraints = pg.execute('''SELECT cl.relname,co.conname FROM pg_constraint co
JOIN pg_class cl ON cl.oid=co.conrelid JOIN pg_namespace ns ON ns.oid=cl.relnamespace
WHERE ns.nspname=%s AND NOT co.convalidated ORDER BY cl.relname,co.conname''', (stage,)).fetchall()
for table, name in constraints:
pg.execute('ALTER TABLE ' + qualify(stage, table) + ' VALIDATE CONSTRAINT ' + quote(name))
def sequences(pg, source, stage, plan):
old = dict(source.execute('SELECT name,seq FROM sqlite_sequence'))
history = {'papers': ('paper_merges', 'former_paper_id'),
'submissions': ('submission_merges', 'former_submission_id'),
'decisions': ('decision_merges', 'former_decision_id')}
result = {}
for table, spec in plan.items():
if spec['pk'] != ['id']:
continue
value = max(source.execute('SELECT coalesce(max(id),0) FROM ' + quote(table)).fetchone()[0], old.get(table, 0))
if table in history:
audit, column = history[table]
value = max(value, source.execute('SELECT coalesce(max(' + quote(column) + '),0) FROM ' + quote(audit)).fetchone()[0])
sequence = pg.execute('SELECT pg_get_serial_sequence(%s,%s)', (qualify(stage, table), 'id')).fetchone()[0]
pg.execute('SELECT setval(%s,%s,%s)', (sequence, max(value, 1), value > 0))
result[table] = value
return result
def migrate(db, service, out, *, schema='research', storage_path=None, min_free_gib=8):
if not re.fullmatch(r'[a-z][a-z0-9_]{0,35}', schema):
raise ValueError('Use a short lowercase target schema name')
db, out = Path(db).resolve(), Path(out).resolve()
if not db.is_file() or out == db:
raise ValueError('Existing source and a distinct report are required')
if out.exists() and json.loads(out.read_text()).get('status') == 'complete':
raise ValueError('Completed report must be preserved')
free_space(storage_path, min_free_gib)
control = schema + '_migration'
report = {'status': 'preflight', 'source': str(db), 'service': service, 'schema': schema,
'started_at': timestamp(), 'tables': {}, 'scope': 'All 21 business tables; FTS5 internals rebuilt as native PostgreSQL GIN.'}
with Path(str(db) + '.maintenance.lock').open('a') as lock:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
if Path(str(db) + '-wal').exists() and Path(str(db) + '-wal').stat().st_size:
raise ValueError('Freeze writers and checkpoint SQLite WAL before migrating')
with closing(sqlite3.connect(db.as_uri() + '?mode=ro', uri=True)) as source, closing(connect(service)) as pg:
source.execute('PRAGMA query_only=ON'); source.execute('PRAGMA cache_size=-16384'); source.execute('BEGIN')
plan = inspect(source)
stat = db.stat()
identity = {'file_sha256': digest_file(db), 'bytes': stat.st_size, 'mtime_ns': stat.st_mtime_ns,
'schema_sha256': fingerprint(plan)}
report['source_identity'] = identity
advisory = zlib.crc32(schema.encode()) & 0x7fffffff
if not pg.execute('SELECT pg_try_advisory_lock(%s,%s)', (615173, advisory)).fetchone()[0]:
raise RuntimeError('Another migration holds the target lock')
if pg.execute('SELECT 1 FROM pg_namespace WHERE nspname=%s', (schema,)).fetchone():
raise ValueError('Target schema already exists; published data will never be overwritten')
pg.execute('CREATE SCHEMA IF NOT EXISTS ' + quote(control))
pg.execute('CREATE TABLE IF NOT EXISTS ' + qualify(control, 'run') +
'(id INTEGER PRIMARY KEY CHECK(id=1), source_json TEXT NOT NULL, stage TEXT NOT NULL, status TEXT NOT NULL)')
pg.execute('CREATE TABLE IF NOT EXISTS ' + qualify(control, 'tables') +
'(name TEXT PRIMARY KEY, rows BIGINT NOT NULL, sha256 TEXT NOT NULL, verified BOOLEAN NOT NULL DEFAULT false)')
run = pg.execute('SELECT source_json,stage,status FROM ' + qualify(control, 'run') + ' WHERE id=1').fetchone()
if run:
if json.loads(run[0]) != identity or run[2] == 'complete':
raise ValueError('Resume requires the exact same unpublished SQLite snapshot')
stage = run[1]
else:
stage = schema + '_stage_' + uuid.uuid4().hex[:12]
with pg.transaction():
pg.execute('CREATE SCHEMA ' + quote(stage))
for table, spec in plan.items():
pg.execute(table_sql(stage, table, spec))
pg.execute('INSERT INTO ' + qualify(control, 'run') + ' VALUES(1,%s,%s,%s)',
(json.dumps(identity, sort_keys=True), stage, 'copying'))
report.update(status='copying', stage=stage); save(out, report)
try:
for table, spec in plan.items():
free_space(storage_path, min_free_gib)
previous = pg.execute('SELECT rows,sha256 FROM ' + qualify(control, 'tables') + ' WHERE name=%s', (table,)).fetchone()
if previous:
rows, digest = previous
else:
digest = hashlib.sha256(); rows = 0
with pg.transaction():
# Only this run's unpublished, incomplete table can be reset.
pg.execute('TRUNCATE ' + qualify(stage, table))
columns = ','.join(quote(c['name']) for c in spec['columns'])
with pg.cursor().copy('COPY ' + qualify(stage, table) + '(' + columns + ') FROM STDIN') as copy:
for row in source.execute(select_sql(None, table, spec)):
copy.write_row(row); update_hash(digest, row); rows += 1
if rows % 10000 == 0:
free_space(storage_path, min_free_gib)
if rows % 100000 == 0:
print(json.dumps({'stage': 'copying', 'table': table, 'rows': rows}), flush=True)
digest = digest.hexdigest()
pg.execute('INSERT INTO ' + qualify(control, 'tables') + '(name,rows,sha256) VALUES(%s,%s,%s)', (table, rows, digest))
report['tables'][table] = {'source_rows': rows, 'source_sha256': digest}
save(out, report)
print(json.dumps({'stage': 'copied', 'table': table, 'rows': rows}), flush=True)
report['status'] = 'validating_constraints'; save(out, report)
add_constraints(pg, stage, plan)
report['sequences'] = sequences(pg, source, stage, plan)
report['status'] = 'verifying_contents'; save(out, report)
for table, spec in plan.items():
digest = hashlib.sha256(); rows = 0
with pg.transaction(), pg.cursor(name='verify_' + table) as cursor:
cursor.itersize = 512
cursor.execute(select_sql(stage, table, spec))
for row in cursor:
update_hash(digest, row); rows += 1
entry = report['tables'][table]
entry.update(target_rows=rows, target_sha256=digest.hexdigest())
if rows != entry['source_rows'] or digest.hexdigest() != entry['source_sha256']:
raise ValueError('Complete content verification failed for ' + table)
pg.execute('UPDATE ' + qualify(control, 'tables') + ' SET verified=true WHERE name=%s', (table,))
save(out, report)
print(json.dumps({'stage': 'verified', 'table': table, 'rows': rows}), flush=True)
report['status'] = 'building_search_index'; save(out, report)
free_space(storage_path, min_free_gib)
pg.execute('CREATE INDEX IF NOT EXISTS papers_search_gin ON ' + qualify(stage, 'papers') + ' USING gin (' + SEARCH_VECTOR + ')')
search = pg.execute('''SELECT am.amname,i.indisvalid,i.indisready,t.relname
FROM pg_index i JOIN pg_class ix ON ix.oid=i.indexrelid
JOIN pg_class t ON t.oid=i.indrelid JOIN pg_namespace ns ON ns.oid=ix.relnamespace
JOIN pg_am am ON am.oid=ix.relam WHERE ns.nspname=%s AND ix.relname='papers_search_gin' ''', (stage,)).fetchone()
if search != ('gin', True, True, 'papers'):
raise ValueError('Native full-text index is not valid and ready')
for table in TABLES:
pg.execute('ANALYZE ' + qualify(stage, table))
invalid = pg.execute('''SELECT count(*) FROM pg_constraint co JOIN pg_class cl ON cl.oid=co.conrelid
JOIN pg_namespace ns ON ns.oid=cl.relnamespace WHERE ns.nspname=%s AND NOT co.convalidated''', (stage,)).fetchone()[0]
if invalid:
raise ValueError('Unvalidated constraints remain')
if (db.stat().st_size, db.stat().st_mtime_ns) != (identity['bytes'], identity['mtime_ns']):
raise ValueError('Source changed during migration')
if Path(str(db) + '-wal').exists() and Path(str(db) + '-wal').stat().st_size:
raise ValueError('A source writer committed during migration')
report.update(status='prepared', foreign_keys='all_validated', checks='all_validated', native_search_index=True)
save(out, report)
with pg.transaction():
pg.execute('ALTER SCHEMA ' + quote(stage) + ' RENAME TO ' + quote(schema))
pg.execute('UPDATE ' + qualify(control, 'run') + " SET status='complete' WHERE id=1")
report.update(status='complete', finished_at=timestamp())
save(out, report)
return report
except BaseException as error:
report.update(status='error', error_type=type(error).__name__, error=str(error), failed_at=timestamp())
save(out, report)
raise
def main(argv=None, *, prog=None):
parser = argparse.ArgumentParser(prog=prog)
parser.add_argument('--db', required=True, help='Frozen SQLite source')
parser.add_argument('--pg-service', required=True, help='Protected libpq service name')
parser.add_argument('--schema', default='research')
parser.add_argument('--out', required=True)
parser.add_argument('--storage-path', help='Target filesystem path for free-space checks')
parser.add_argument('--min-free-gib', type=float, default=8)
args = parser.parse_args(argv)
result = migrate(args.db, args.pg_service, args.out, schema=args.schema,
storage_path=args.storage_path, min_free_gib=args.min_free_gib)
print(json.dumps(result, ensure_ascii=False), flush=True)
+120
View File
@@ -0,0 +1,120 @@
"""Inspect the complete business schema; rebuild SQLite engine internals natively."""
import hashlib
import json
import re
TABLES = ('sources', 'papers', 'identifiers', 'source_records', 'venues', 'editions',
'venue_aliases', 'edition_sources', 'submissions', 'decisions',
'submission_sources', 'submission_identifiers', 'decision_sources',
'submission_merges', 'decision_merges', 'schema_migrations', 'tags',
'paper_tags', 'match_candidates', 'paper_merges', 'ingest_runs')
CHECKS = {
'venues': ["venue_type IN ('conference','journal','review_platform')"],
'edition_sources': ["status IN ('pending','running','complete','partial','blocked','unavailable','not_yet_published')"],
'decisions': ["status IN ('accepted','rejected','desk_rejected','withdrawn','under_review','unknown')"],
'match_candidates': ["status IN ('pending','merged','distinct')"],
}
TYPES = {'INTEGER': 'BIGINT', 'TEXT': 'TEXT COLLATE "C"', 'REAL': 'DOUBLE PRECISION'}
def checks_in(ddl):
result = []
for match in re.finditer(r'\bCHECK\s*\(', ddl, re.I):
start = position = match.end()
depth, quoted = 1, False
while position < len(ddl) and depth:
char = ddl[position]
if char == "'":
if quoted and position + 1 < len(ddl) and ddl[position + 1] == "'":
position += 2; continue
quoted = not quoted
elif not quoted:
depth += (char == '(') - (char == ')')
position += 1
if depth:
raise ValueError('Unclosed CHECK constraint')
result.append(ddl[start:position - 1])
return result
def normalize_check(expression):
# Normalize SQL layout/keywords, retaining case and spaces inside literals.
tokens = re.findall(r"'(?:[^']|'')*'|[^']+", expression)
return ''.join(token if token.startswith("'") else re.sub(r'\s+', '', token).lower() for token in tokens)
def quote(name):
return '"' + name.replace('"', '""') + '"'
def inspect(connection):
business = {name for schema, name, kind, *_ in connection.execute('PRAGMA table_list')
if schema == 'main' and kind == 'table' and not name.startswith('sqlite_')}
if business != set(TABLES):
raise ValueError('Unexpected business tables: ' + repr(sorted(business ^ set(TABLES))))
result = {}
for table in TABLES:
columns = [{'name': r[1], 'type': r[2].upper(), 'notnull': bool(r[3]),
'default': r[4], 'pk': r[5]}
for r in connection.execute('PRAGMA table_info(' + quote(table) + ')')]
if any(c['type'] not in TYPES for c in columns):
raise ValueError('Unsupported storage type in ' + table)
pk = [c['name'] for c in sorted(columns, key=lambda c: c['pk']) if c['pk']]
if not pk:
raise ValueError('A deterministic primary key is required for ' + table)
indexes = []
for row in connection.execute('PRAGMA index_list(' + quote(table) + ')'):
if row[3] == 'pk':
continue
if row[4]:
raise ValueError('Partial indexes require explicit migration support')
terms = [(r[2], bool(r[3]), r[4]) for r in connection.execute('PRAGMA index_xinfo(' + quote(row[1]) + ')') if r[5]]
if any(name is None or coll != 'BINARY' for name, desc, coll in terms):
raise ValueError('Unsupported expression or collation in ' + table)
indexes.append({'name': row[1], 'unique': bool(row[2]), 'origin': row[3],
'terms': [(name, desc) for name, desc, coll in terms]})
fks = {}
for row in connection.execute('PRAGMA foreign_key_list(' + quote(table) + ')'):
if row[5:7] != ('NO ACTION', 'NO ACTION'):
raise ValueError('Unsupported foreign key actions')
fk = fks.setdefault(row[0], {'table': row[2], 'columns': [], 'references': []})
fk['columns'].append(row[3]); fk['references'].append(row[4])
ddl = connection.execute("SELECT sql FROM sqlite_schema WHERE type='table' AND name=?", (table,)).fetchone()[0]
checks = CHECKS.get(table, [])
if sorted(map(normalize_check, checks_in(ddl))) != sorted(map(normalize_check, checks)):
raise ValueError('Unrecognized CHECK constraint in ' + table)
result[table] = {'columns': columns, 'pk': pk, 'indexes': indexes,
'foreign_keys': list(fks.values()), 'checks': checks}
return result
def fingerprint(plan):
return hashlib.sha256(json.dumps(plan, sort_keys=True, separators=(',', ':')).encode()).hexdigest()
def default_sql(value):
if value is None:
return ''
if value.upper() == 'CURRENT_TIMESTAMP':
return " DEFAULT to_char(CURRENT_TIMESTAMP AT TIME ZONE 'UTC','YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"
if re.fullmatch(r'-?\d+|\'(?:[^\']|\'\')*\'', value):
return ' DEFAULT ' + value
raise ValueError('Unsupported column default')
def table_sql(schema, table, spec):
columns = []
for column in spec['columns']:
generated = column['name'] == 'id' and spec['pk'] == ['id'] and column['type'] == 'INTEGER'
value = quote(column['name']) + ' ' + TYPES[column['type']]
value += ' GENERATED BY DEFAULT AS IDENTITY' if generated else default_sql(column['default'])
if column['notnull']:
value += ' NOT NULL'
columns.append(value)
return 'CREATE TABLE ' + quote(schema) + '.' + quote(table) + '(' + ','.join(columns) + ')'
def select_sql(schema, table, spec):
prefix = quote(schema) + '.' if schema else ''
return ('SELECT ' + ','.join(quote(c['name']) for c in spec['columns']) +
' FROM ' + prefix + quote(table) + ' ORDER BY ' + ','.join(quote(c) for c in spec['pk']))