Merge pull request '逐条审计 arXiv 类别完整性及来源证据' (#10) from codex/arxiv-tag-audit into main
Metadata integrity checks / metadata (push) Successful in 28s

Reviewed-on: #10
This commit was merged in pull request #10.
This commit is contained in:
2026-11-06 16:15:09 +00:00
4 changed files with 296 additions and 0 deletions
+143
View File
@@ -0,0 +1,143 @@
"""Compare every arXiv record's category evidence with retained source metadata."""
import argparse
from collections import defaultdict
from contextlib import closing
import fcntl
import json
from pathlib import Path
import sqlite3
from paper_atlas.db.submissions import timestamp
def save(path, state):
part = path.with_suffix('.part')
part.write_text(json.dumps(state, ensure_ascii=False, indent=2) + '\n')
part.replace(path)
def audit(db, out, repair_report=None, batch_size=500):
db, out = Path(db).resolve(), Path(out).resolve()
if not db.is_file():
raise ValueError('Existing database required')
if not 1 <= batch_size <= 500:
raise ValueError('Batch size must be between 1 and 500')
if out == db or repair_report and out == Path(repair_report).resolve():
raise ValueError('Audit output must preserve its inputs')
out.parent.mkdir(parents=True, exist_ok=True)
with Path(str(db) + '.maintenance.lock').open('a') as maintenance, Path(str(out) + '.lock').open('a') as output_lock:
# A partial repair is not a useful full-category audit. This also keeps
# cooperating maintenance writers out for the entire read-only snapshot.
fcntl.flock(maintenance, fcntl.LOCK_SH | fcntl.LOCK_NB)
fcntl.flock(output_lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
if out.exists():
raise ValueError('Audit report exists; select a new output path')
with closing(sqlite3.connect(db.as_uri() + '?mode=ro', uri=True)) as c:
c.execute('PRAGMA cache_size=-32768')
c.execute('BEGIN')
source = c.execute("SELECT id FROM sources WHERE name='arxiv'").fetchone()
if source is None:
raise ValueError('No imported arXiv source')
total, maximum = c.execute('SELECT count(*),COALESCE(max(id),0) FROM source_records WHERE source_id=?', source).fetchone()
if not total:
raise ValueError('No imported arXiv records')
scope = {'db': str(db), 'source_id': source[0], 'source_record_count': total,
'maximum_source_record_id': maximum}
if repair_report:
repair = json.loads(Path(repair_report).read_text())
if repair.get('status') != 'complete' or repair.get('records_refreshed') != total:
raise ValueError('Category repair has not completed this source inventory')
if any(repair.get(key) != value for key, value in scope.items()):
raise ValueError('Repair report belongs to a different source inventory')
state = {**scope, 'started_at': timestamp(), 'status': 'running', 'records_checked': 0,
'last_record_id': 0, 'expected_evidence': 0, 'actual_evidence': 0,
'records_with_mismatches': 0, 'missing_evidence': 0, 'unexpected_evidence': 0,
'legacy_evidence': 0, 'examples': [], 'repair_report': str(Path(repair_report).resolve()) if repair_report else None}
save(out, state)
try:
while True:
# The (source_id,external_id) index orders by external ID,
# so choosing it sorts the entire source again per batch.
# This fixed ID interval must use the integer primary key.
records = c.execute('''SELECT id,external_id,paper_id,metadata_json FROM source_records NOT INDEXED
WHERE source_id=? AND id>? AND id<=? ORDER BY id LIMIT ?''',
(source[0], state['last_record_id'], maximum, batch_size)).fetchall()
if not records:
break
ids = [row[0] for row in records]
actual = defaultdict(set)
for record, paper, category, evidence in c.execute('''SELECT pt.source_record_id,pt.paper_id,t.value,pt.evidence_key
FROM paper_tags pt JOIN tags t ON t.id=pt.tag_id WHERE t.namespace='arxiv:category'
AND pt.source_record_id IN (''' + ','.join('?' for _ in ids) + ')', ids):
actual[record].add((category, paper, evidence))
state['legacy_evidence'] += evidence == 'arxiv:categories'
for record, external, paper, payload in records:
metadata = json.loads(payload)
if not isinstance(metadata, dict):
raise ValueError('arXiv source metadata must be an object')
categories = metadata.get('categories')
if categories is None:
categories = ''
if not isinstance(categories, str):
raise ValueError('arXiv source categories must be text')
evidence_key = f'arxiv:record:{record}:tags'
expected = {(category, paper, evidence_key) for category in categories.split()}
found = actual[record]
missing, unexpected = expected - found, found - expected
state['expected_evidence'] += len(expected)
state['actual_evidence'] += len(found)
state['missing_evidence'] += len(missing)
state['unexpected_evidence'] += len(unexpected)
if missing or unexpected:
state['records_with_mismatches'] += 1
if len(state['examples']) < 20:
state['examples'].append({'record_id': record, 'external_id': external,
'paper_id': paper, 'missing': sorted(missing), 'unexpected': sorted(unexpected)})
state['records_checked'] += 1
state['last_record_id'] = ids[-1]
if state['records_checked'] % 10000 < len(records):
save(out, state)
print(json.dumps({k: state[k] for k in ('status', 'records_checked', 'source_record_count', 'records_with_mismatches')}), flush=True)
if state['records_checked'] != total:
raise ValueError('Audited record count differs from the fixed source inventory')
# Every category row must also have an arXiv source-record owner.
# The full namespace total catches orphan and wrong-source evidence
# that cannot appear in the per-record traversal above.
all_evidence = c.execute("SELECT count(*) FROM paper_tags pt JOIN tags t ON t.id=pt.tag_id WHERE t.namespace='arxiv:category'").fetchone()[0]
unscoped = all_evidence - state['actual_evidence']
if unscoped < 0:
raise ValueError('Category evidence totals are inconsistent')
state.update(namespace_evidence=all_evidence, evidence_without_arxiv_record=unscoped)
if unscoped:
state['unscoped_examples'] = [dict(zip(('paper_id', 'category', 'source_record_id', 'evidence_key'), row))
for row in c.execute('''SELECT pt.paper_id,t.value,pt.source_record_id,pt.evidence_key
FROM paper_tags pt JOIN tags t ON t.id=pt.tag_id
LEFT JOIN source_records r ON r.id=pt.source_record_id
WHERE t.namespace='arxiv:category' AND (r.source_id IS NULL OR r.source_id<>?) LIMIT 20''', source)]
passed = not state['records_with_mismatches'] and not unscoped
state.update(status='passed' if passed else 'failed', finished_at=timestamp(),
note='Full per-record category, canonical paper and evidence-key equality. '
'Read-only; not a global paper deduplication or full database-integrity audit.')
save(out, state)
except BaseException as error:
state.update(status='error', error=str(error), finished_at=timestamp())
save(out, state)
raise
print(json.dumps(state), flush=True)
return state
def main(argv=None, *, prog=None):
parser = argparse.ArgumentParser(prog=prog)
parser.add_argument('--db', required=True)
parser.add_argument('--out', required=True)
parser.add_argument('--repair-report')
parser.add_argument('--batch-size', type=int, default=500)
args = parser.parse_args(argv)
result = audit(args.db, args.out, args.repair_report, args.batch_size)
if result['status'] != 'passed':
raise SystemExit('arXiv category evidence audit failed; inspect the report')
if __name__ == '__main__':
main()
+1
View File
@@ -31,6 +31,7 @@ COMMANDS = {
('audit','iclr'): ('paper_atlas.audits.iclr', {}, '核对 ICLR 快照与同届官方程序'),
('audit','iclr-legacy'): ('paper_atlas.audits.iclr_legacy', {}, '独立核验 ICLR 2020 旧目录投稿身份'),
('audit','arxiv'): ('paper_atlas.audits.arxiv', {}, '核验 arXiv 原始编号、重复行与 ZIP 完整性'),
('audit','arxiv-tags'): ('paper_atlas.audits.arxiv_tags', {}, '逐记录核验 arXiv 类别及出处完整性'),
('audit','public-openreview'): ('paper_atlas.audits.public_openreview', {}, '核对公开负面决定与已有投稿历史'),
}