"""Offline recovery, filtering, and content-integrity tests.""" from contextlib import closing import gzip import hashlib import io from pathlib import Path import tempfile import threading from types import SimpleNamespace import unittest import pyarrow as pa import pyarrow.parquet as pq from stackgo.scripts import download_stack_v2_contents as downloader class FakeS3: def __init__(self, bodies): self.bodies = bodies self.calls = [] def get_object(self, Bucket, Key): self.calls.append(Key) return {'Body': io.BytesIO(gzip.compress(self.bodies[Key.split('/')[-1]]))} class ContentsTest(unittest.TestCase): def test_prepare_accepts_strict_star_range(self): with tempfile.TemporaryDirectory() as temporary: root = Path(temporary) blob = hashlib.sha1(b'body').hexdigest() files = [dict(blob_id=blob, length_bytes=4, path='src/a.py')] source = root / 'source.parquet' pq.write_table(pa.Table.from_pylist([ dict(repo_name=str(stars), star_events_count=stars, revision_id=str(stars), files=files) for stars in (1, 2, 9, 10, 11, None) ]), source) target = root / 'shard' self.assertTrue(downloader.prepare( source, target, threading.Event(), min_stars_exclusive=1, max_stars_exclusive=11, )) self.assertEqual( [row['repo_name'] for row in pq.read_table(target / 'repositories.parquet').to_pylist()], ['2', '9', '10'], ) def test_strict_filter_full_metadata_and_crash_recovery(self): with tempfile.TemporaryDirectory() as temporary: root = Path(temporary) bodies = {hashlib.sha1(b'hello').hexdigest(): b'hello', hashlib.sha1(b'world').hexdigest(): b'world'} files = [dict(blob_id=blob, length_bytes=len(body) + number, path=f'src/{number}.py', detected_licenses=['MIT'], src_encoding='utf-8') for number, (blob, body) in enumerate(bodies.items())] source = root / 'source.parquet' pq.write_table(pa.Table.from_pylist([ dict(repo_name='excluded', star_events_count=10, revision_id='a', files=files), dict(repo_name='included', star_events_count=11, revision_id='b', files=files + files[:1]), dict(repo_name='unknown', star_events_count=None, revision_id='c', files=files), ]), source) target = root / 'shard' stop = threading.Event() self.assertTrue(downloader.prepare(source, target, stop)) metadata = pq.read_table(target / 'repositories.parquet').to_pylist() self.assertEqual(len(metadata), 1) self.assertEqual(metadata[0]['files'], files + files[:1]) args = SimpleNamespace(workers=2, shard_files=2, shard_mib=1) s3 = FakeS3(bodies) with closing(downloader.state(target / 'queue.sqlite3')) as db: with db: db.execute("UPDATE blobs SET status='fetching'") # Simulate atomic Parquet publication followed by a crash before DB acknowledgement. content_dir = target / 'contents' content_dir.mkdir() blob, body = next(iter(bodies.items())) pq.write_table(pa.Table.from_pylist([dict(blob_id=blob, content=body, length_bytes=len(body))], schema=downloader.BODY_SCHEMA), content_dir / 'recovered.parquet') count = downloader.download(db, target, s3, args, stop, None) self.assertEqual(count, 1) self.assertEqual(len(s3.calls), 1) self.assertEqual(db.execute("SELECT count(*) FROM blobs WHERE status='done'").fetchone()[0], 2) self.assertEqual(downloader.download(db, target, s3, args, stop, None), 0) recovered = pq.read_table(content_dir).to_pylist() self.assertEqual({row['blob_id']: row['content'] for row in recovered}, bodies) self.assertFalse(next(row for row in recovered if row['blob_id'] != blob)['length_matches_index']) def test_corrupt_content_rejected(self): blob = hashlib.sha1(b'right').hexdigest() with self.assertRaisesRegex(ValueError, 'SHA1Mismatch'): downloader.fetch(FakeS3({blob: b'wrong'}), blob, 5) self.assertEqual(downloader.fetch(FakeS3({blob: b'right'}), blob, 1), b'right') def test_transient_failure_survives_restart_and_attempt_limit(self): class Unreachable: def get_object(self, **kwargs): raise TimeoutError('offline') with tempfile.TemporaryDirectory() as temporary: root = Path(temporary) body = b'retry me' blob = hashlib.sha1(body).hexdigest() args = SimpleNamespace(workers=2, shard_files=2, shard_mib=1) stop = threading.Event() with closing(downloader.state(root / 'queue.sqlite3')) as db: with db: db.execute('INSERT INTO blobs(blob_id,length_bytes) VALUES (?,?)', (blob, len(body))) self.assertEqual(downloader.download(db, root, Unreachable(), args, stop, 1), 1) self.assertEqual(db.execute('SELECT status,attempts FROM blobs').fetchone(), ('error', 1)) with closing(downloader.state(root / 'queue.sqlite3')) as db: with db: db.execute('UPDATE blobs SET retry_at=0') self.assertEqual(downloader.download(db, root, FakeS3({blob: body}), args, stop, 1), 1) self.assertEqual(db.execute('SELECT status FROM blobs').fetchone()[0], 'done') if __name__ == '__main__': unittest.main()