Download fixed metadata snapshots with checksum and resume safeguards
Metadata integrity checks / metadata (push) Successful in 4s

This commit is contained in:
2026-11-06 13:29:30 +08:00
parent 396b7dbaf2
commit a7a0729df2
4 changed files with 212 additions and 0 deletions
+6
View File
@@ -3,8 +3,14 @@ __pycache__/
*.sqlite
*.sqlite-*
*.zip
*.gz
*.bz2
*.jsonl
*.part
*.part.json
*.download.lock
.env
.DS_Store
raw/
data/
collected/
+29
View File
@@ -127,6 +127,35 @@ python3 -B collect_peerread.py --cache /data/paper-index/raw/http-cache \
数据任务以一次性 systemd 服务运行:`paper-atlas-arxiv-import`、`paper-atlas-pmlr-collect`、`paper-atlas-peerread-collect`;`paper-atlas-pmlr-verify` 用于全索引复核,`paper-atlas-conference-merge` 用于单写入合并。它们不是定时任务。主库只允许一个写入进程;会议采集先写独立 JSONL,待 arXiv 主批次结束后再合并;也可以使用 `merge_conferences.py` 在保存断点处暂停本项目的 arXiv unit、顺序合并会议清单并恢复。该操作应作为独立的一次性 systemd 任务运行,避免 SSH 断开影响恢复;不能同时启动多个合并任务。运行日志位于 `/data/paper-index/*-import.log`、`/data/paper-index/*-collect.log`。任何服务启动成功都不等于批次已完成,需检查批次状态、清单与完整性结果。标签按来源刷新使用 `paper_tags_source_evidence` 索引,避免每条论文都扫描整张标签表。运行中的 arXiv 可以通过同一协调脚本的 `--schema-only` 模式在断点更新索引后恢复;此模式要求已有 arXiv unit 正在运行。
### 固定版本的补充元数据快照
`download_snapshot.py` 流式下载到 `.part`,核对完整 HTTP 响应、预期大小和可信来源发布的校验和后,才发布正式文件及 manifest。已存在的正式文件会先重新核验;错误校验和不会覆盖它。默认保留 8 GiB 空闲空间,同一输出只允许一个下载进程。
DBLP 官方月度快照用于补充出版目录和历史届次,元数据按 CC0 发布。固定版本可复现,不把每日变动下载链接当作同一快照:
```sh
python3 -B download_snapshot.py \
--url https://drops.dagstuhl.de/storage/artifacts/dblp/xml/2026/dblp-2026-11-01.xml.gz \
--md5 18ad5db59592406ec74289975c4b44cb \
--output /data/paper-index/raw/dblp-2026-11-01.xml.gz
```
[官方版本与校验值](https://doi.org/10.4230/dblp.xml.2026-11-01)。下载器另外计算 SHA-256,记录来源 URL、大小和核验时间。DBLP 没有提供的摘要不能编造,出版目录也不能作为拒稿证据。
公开 ICLR 投稿快照的固定 Release 供后续筛选投稿和明确决定;它是第三方保存的 OpenReview 历史副本,不等于最新官方全量数据:
```sh
python3 -B download_snapshot.py \
--url https://github.com/qhjqhj00/iclr-openreview-reviews/releases/download/v1.0/iclr.tar.bz2 \
--sha256 350071daf25ebf1aef854ee1d5dc3a81834e1c468917c82a4f78af5548de34fc \
--expected-bytes 512940722 \
--output /data/paper-index/raw/iclr-openreview-v1.0.tar.bz2
```
[快照来源与复现脚本](https://github.com/qhjqhj00/iclr-openreview-reviews)。原包包含评审回复;后续解析只筛选公开投稿的索引、标题、摘要、平台标签及带证据的明确决定,不提取评审正文、作者邮件或论文全文。必须核对原始 invitation、readers、签名及决定字段,不能根据评分或录用名单缺席推断拒稿。该解析适配尚在开发,下载成功不代表已经入库或核验覆盖。
下载异常后先检查对应进程或 CI 任务确已终止,再使用同一参数增加 `--resume`。只有断点身份一致且服务器实际返回正确 Range 响应才续传;不支持时保留断点并报错,不自动重下。正式文件与下载清单均放在仓库外,不提交大型来源包。
### COLM 与 NeurIPS 官方摘要
```sh
+106
View File
@@ -0,0 +1,106 @@
"""Checksum-verified streaming downloads; existing valid snapshots stay intact."""
import argparse
import fcntl
import hashlib
import json
from pathlib import Path
import re
import shutil
import time
from urllib.parse import urlsplit
import urllib.request
def digest_file(path):
sha=hashlib.sha256();md5=hashlib.md5(usedforsecurity=False);size=0
with path.open('rb') as stream:
while block:=stream.read(1024**2):
sha.update(block);md5.update(block);size+=len(block)
return {'sha256':sha.hexdigest(),'md5':md5.hexdigest(),'bytes':size}
def verify(actual,sha256,md5,expected_bytes):
if expected_bytes is not None and actual['bytes']!=expected_bytes:
raise ValueError('Snapshot size differs from trusted expected size')
if sha256 and actual['sha256']!=sha256:
raise ValueError('Snapshot SHA256 mismatch; partial file retained')
if md5 and actual['md5']!=md5:
raise ValueError('Snapshot MD5 mismatch; partial file retained')
def write_manifest(output,url,actual):
manifest={'status':'verified','file':str(output),'url':url,**actual,
'verified_at':time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime())}
metadata=Path(str(output)+'.manifest.json');stage=Path(str(metadata)+'.part')
stage.write_text(json.dumps(manifest,indent=2));stage.replace(metadata)
return manifest
def download(url,output,sha256=None,md5=None,expected_bytes=None,resume=False,min_free=8*1024**3):
parsed=urlsplit(url)
if parsed.scheme!='https' or not parsed.netloc or parsed.username or parsed.password:
raise ValueError('A public HTTPS URL without embedded credentials is required')
if not (sha256 or md5):raise ValueError('A trusted published checksum is required')
if expected_bytes is not None and expected_bytes<=0:raise ValueError('Expected byte count must be positive')
if min_free<0:raise ValueError('Disk reserve must not be negative')
for name,value,length in [('SHA256',sha256,64),('MD5',md5,32)]:
if value and not re.fullmatch('[0-9a-f]{'+str(length)+'}',value):raise ValueError('Invalid '+name)
output=Path(output);output.parent.mkdir(parents=True,exist_ok=True)
if output.is_symlink():raise ValueError('Refusing a symlink output')
intent={'url':url,'expected_sha256':sha256,'expected_md5':md5,'expected_bytes':expected_bytes}
with Path(str(output)+'.download.lock').open('a') as lock:
fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
if output.exists():
actual=digest_file(output);verify(actual,sha256,md5,expected_bytes)
if not Path(str(output)+'.manifest.json').exists():write_manifest(output,url,actual)
return {'status':'already_verified','file':str(output),**actual}
part=Path(str(output)+'.part');intent_path=Path(str(part)+'.json')
offset=0
if part.exists():
if not resume or not intent_path.is_file() or json.loads(intent_path.read_text())!=intent:
raise ValueError('Existing partial requires --resume and the same snapshot identity')
offset=part.stat().st_size
else:
intent_path.write_text(json.dumps(intent,indent=2))
remaining=max(0,(expected_bytes or 0)-offset)
if shutil.disk_usage(output.parent).free<min_free+remaining:
raise RuntimeError('Insufficient free space for snapshot and reserve')
if expected_bytes is None or offset!=expected_bytes:
headers={'User-Agent':'PaperAtlas/0.1 (public scholarly metadata research)'}
if offset:headers['Range']=f'bytes={offset}-'
with urllib.request.urlopen(urllib.request.Request(url,headers=headers),timeout=90) as response:
if offset:
content_range=response.headers.get('Content-Range','')
match=re.fullmatch(r'bytes (\d+)-(\d+)/(\d+)',content_range)
if response.status!=206 or not match or int(match[1])!=offset:
raise ValueError('Server did not honor resume range; partial retained')
total=int(match[3])
else:
if response.status!=200:raise ValueError('Expected a complete HTTP 200 response')
total=int(response.headers.get('Content-Length','0')) or expected_bytes
if expected_bytes is not None and total is not None and total!=expected_bytes:
raise ValueError('HTTP size differs from expected snapshot')
if total and shutil.disk_usage(output.parent).free<min_free+total-offset:
raise RuntimeError('Insufficient disk reserve for response')
written=offset;reported=offset
with part.open('ab' if part.exists() else 'xb') as target:
while block:=response.read(1024**2):
target.write(block);written+=len(block)
if total and written>total:raise ValueError('HTTP response exceeds advertised size')
if written-reported>=64*1024**2:
print(json.dumps({'status':'downloading','file':str(output),'bytes':written,'expected_bytes':total}),flush=True);reported=written
if shutil.disk_usage(output.parent).free<min_free:raise RuntimeError('Stopped at disk reserve')
if total and written!=total:raise ValueError('Incomplete HTTP response; partial retained')
actual=digest_file(part);verify(actual,sha256,md5,expected_bytes)
part.replace(output)
manifest=write_manifest(output,url,actual)
intent_path.unlink(missing_ok=True)
return manifest
if __name__=='__main__':
parser=argparse.ArgumentParser();parser.add_argument('--url',required=True);parser.add_argument('--output',required=True)
parser.add_argument('--sha256');parser.add_argument('--md5');parser.add_argument('--expected-bytes',type=int)
parser.add_argument('--resume',action='store_true');parser.add_argument('--min-free-gib',type=float,default=8)
args=parser.parse_args()
print(json.dumps(download(args.url,args.output,args.sha256,args.md5,args.expected_bytes,args.resume,int(args.min_free_gib*1024**3))),flush=True)
+71
View File
@@ -0,0 +1,71 @@
import hashlib
import io
import json
from pathlib import Path
import tempfile
import unittest
from unittest.mock import patch
from download_snapshot import download
class Response(io.BytesIO):
def __init__(self,body,status=200,headers=None):
super().__init__(body);self.status=status;self.headers=headers or {'Content-Length':str(len(body))}
class DownloadTests(unittest.TestCase):
def test_verified_download_is_reused_without_replacing_it(self):
body=b'public metadata';sha=hashlib.sha256(body).hexdigest()
with tempfile.TemporaryDirectory() as tmp:
path=Path(tmp)/'snapshot.gz'
with patch('download_snapshot.urllib.request.urlopen',return_value=Response(body)):
result=download('https://example.org/snapshot.gz',path,sha256=sha,expected_bytes=len(body),min_free=0)
self.assertEqual(result['status'],'verified')
with patch('download_snapshot.urllib.request.urlopen',side_effect=AssertionError('No network expected')):
reused=download('https://example.org/snapshot.gz',path,sha256=sha,min_free=0)
self.assertEqual(reused['status'],'already_verified')
self.assertEqual(json.loads(Path(str(path)+'.manifest.json').read_text())['sha256'],sha)
def test_bad_checksum_never_publishes_a_snapshot(self):
with tempfile.TemporaryDirectory() as tmp,patch('download_snapshot.urllib.request.urlopen',return_value=Response(b'wrong bytes')):
path=Path(tmp)/'snapshot.gz'
with self.assertRaisesRegex(ValueError,'SHA256 mismatch'):
download('https://example.org/snapshot.gz',path,sha256='0'*64,min_free=0)
self.assertFalse(path.exists());self.assertTrue(Path(str(path)+'.part').exists())
def test_resume_requires_the_same_identity_and_a_real_partial_response(self):
body=b'abcdef';sha=hashlib.sha256(body).hexdigest();url='https://example.org/snapshot.gz'
with tempfile.TemporaryDirectory() as tmp:
path=Path(tmp)/'snapshot.gz';part=Path(str(path)+'.part');part.write_bytes(body[:3])
Path(str(part)+'.json').write_text(json.dumps({'url':url,'expected_sha256':sha,'expected_md5':None,'expected_bytes':6}))
with self.assertRaisesRegex(ValueError,'same snapshot'):
download(url,path,sha256=sha,expected_bytes=6,min_free=0)
with patch('download_snapshot.urllib.request.urlopen',return_value=Response(body)):
with self.assertRaisesRegex(ValueError,'resume range'):
download(url,path,sha256=sha,expected_bytes=6,resume=True,min_free=0)
self.assertEqual(part.read_bytes(),b'abc')
with patch('download_snapshot.urllib.request.urlopen',return_value=Response(b'def',206,{'Content-Range':'bytes 3-5/6'})):
download(url,path,sha256=sha,expected_bytes=6,resume=True,min_free=0)
self.assertEqual(path.read_bytes(),body)
def test_wrong_http_length_is_rejected_before_writing(self):
with tempfile.TemporaryDirectory() as tmp,patch('download_snapshot.urllib.request.urlopen',return_value=Response(b'abc')):
path=Path(tmp)/'snapshot.gz'
with self.assertRaisesRegex(ValueError,'HTTP size'):
download('https://example.org/snapshot.gz',path,sha256='0'*64,expected_bytes=4,min_free=0)
self.assertFalse(path.exists());self.assertFalse(Path(str(path)+'.part').exists())
def test_empty_partial_and_missing_final_manifest_can_recover(self):
body=b'abc';sha=hashlib.sha256(body).hexdigest();url='https://example.org/snapshot.gz'
with tempfile.TemporaryDirectory() as tmp:
path=Path(tmp)/'snapshot.gz';part=Path(str(path)+'.part');part.write_bytes(b'')
Path(str(part)+'.json').write_text(json.dumps({'url':url,'expected_sha256':sha,'expected_md5':None,'expected_bytes':3}))
with patch('download_snapshot.urllib.request.urlopen',return_value=Response(body)):
download(url,path,sha256=sha,expected_bytes=3,resume=True,min_free=0)
metadata=Path(str(path)+'.manifest.json');metadata.unlink()
download(url,path,sha256=sha,expected_bytes=3,min_free=0)
self.assertEqual(json.loads(metadata.read_text())['sha256'],sha)
if __name__=='__main__':unittest.main()