import hashlib import json import os import fcntl import sqlite3 import tempfile import unittest from pathlib import Path from verify_corpus import ( InventoryError, database, insert_or_update_file, prefix_upper_bound, raw_file_rows, combined_source_hash, NORMALIZER_VERSION, safe_relative_path, validate_fragment_file, verify_corpus, ) class CorpusInventoryTests(unittest.TestCase): def setUp(self): self.temp = tempfile.TemporaryDirectory() self.base = Path(self.temp.name) self.raw = self.base / "raw" self.raw.mkdir() self._manifest() def tearDown(self): self.temp.cleanup() def _manifest(self): connection = sqlite3.connect(self.raw / "manifest.sqlite3") connection.executescript( "CREATE TABLE documents (code INTEGER PRIMARY KEY, source_sha256 TEXT, fetched_at TEXT);" "CREATE TABLE errors (code INTEGER PRIMARY KEY, message TEXT, failed_at TEXT);" ) connection.close() def _nonempty_corpus(self, normalizer_version=NORMALIZER_VERSION): document = self.raw / "documents/1" edition = document / "editions/2" edition.mkdir(parents=True) (document / "metadata.json").write_text('{"Code":"1"}\n', encoding="utf-8") (edition / "metadata.json").write_text('{"Code":"2"}\n', encoding="utf-8") html = edition / "ru.html" html.write_text("
Фрагмент
\n", encoding="utf-8") source_files = [] for path in sorted(document.rglob("*")): if path.is_file(): digest = hashlib.sha256(path.read_bytes()).hexdigest() source_files.append({"path": path.relative_to(self.raw).as_posix(), "sha256": digest}) source_sha = combined_source_hash(source_files) raw_manifest = sqlite3.connect(self.raw / "manifest.sqlite3") raw_manifest.execute("INSERT INTO documents VALUES (1, ?, 'now')", (source_sha,)) raw_manifest.commit() raw_manifest.close() normalized = self.base / "normalized" language = normalized / "documents/1/editions/2/ru" language.mkdir(parents=True) fragment_text = "Фрагмент" fragments = [{ "id": "document:1:edition:2:lang:ru:fragment:1", "document_code": "1", "edition_code": "2", "language": "ru", "position": 1, "text": fragment_text, "text_sha256": hashlib.sha256(fragment_text.encode("utf-8")).hexdigest(), "source_path": "documents/1/editions/2/ru.html", "source_sha256": next(item["sha256"] for item in source_files if item["path"].endswith("/ru.html")), }] (language / "fragments.json").write_text(json.dumps(fragments, ensure_ascii=False), encoding="utf-8") (language / "content.txt").write_text(fragment_text + "\n", encoding="utf-8") (language / "content.html").write_text("Фрагмент
\n", encoding="utf-8") document_json = { "schema_version": "1", "source_code": "1", "normalizer": {"version": normalizer_version}, "source": {"path": "documents/1", "files": source_files, "sha256": source_sha}, "editions": [{"source_code": "2"}], } (normalized / "documents/1/document.json").write_text(json.dumps(document_json), encoding="utf-8") edition_json = { "source_code": "2", "available_languages": ["ru"], "source": { "path": "documents/1/editions/2", "files": [item for item in source_files if item["path"].startswith("documents/1/editions/2/")], }, "images": [], } (normalized / "documents/1/editions/2/edition.json").write_text(json.dumps(edition_json), encoding="utf-8") normalized_manifest = sqlite3.connect(normalized / "manifest.sqlite3") normalized_manifest.execute( "CREATE TABLE documents (code TEXT PRIMARY KEY, source_sha256 TEXT, schema_version TEXT, normalizer_version TEXT, state TEXT)" ) normalized_manifest.execute( "INSERT INTO documents VALUES ('1', ?, '1', ?, 'success')", (source_sha, normalizer_version) ) normalized_manifest.commit() normalized_manifest.close() return normalized, source_sha def test_output_inside_source_is_rejected_without_creating_it(self): output = self.raw / "artifacts" before_mode = self.raw.stat().st_mode with self.assertRaisesRegex(InventoryError, "separate"): verify_corpus(self.raw, None, output) self.assertFalse(output.exists()) self.assertEqual(self.raw.stat().st_mode, before_mode) self.assertEqual({path.name for path in self.raw.iterdir()}, {"manifest.sqlite3"}) def test_symlink_output_is_rejected_without_changing_target(self): target = self.base / "target" target.mkdir(mode=0o755) link = self.base / "output-link" try: link.symlink_to(target, target_is_directory=True) except (NotImplementedError, OSError): self.skipTest("directory symlinks are unavailable") before_mode = target.stat().st_mode with self.assertRaisesRegex(InventoryError, "link or file"): verify_corpus(self.raw, None, link) self.assertEqual(target.stat().st_mode, before_mode) self.assertEqual(list(target.iterdir()), []) def test_public_existing_output_is_rejected_without_chmod(self): output = self.base / "public-output" output.mkdir(mode=0o755) output.chmod(0o755) before_mode = output.stat().st_mode with self.assertRaisesRegex(InventoryError, "must be private"): verify_corpus(self.raw, None, output) self.assertEqual(output.stat().st_mode, before_mode) self.assertEqual(list(output.iterdir()), []) def test_resume_rejects_symlink_inventory_without_touching_target(self): output = self.base / "artifacts" output.mkdir(mode=0o700) target = self.base / "do-not-touch.sqlite3" target.write_bytes(b"sentinel") link = output / "inventory.sqlite3" try: link.symlink_to(target) except (NotImplementedError, OSError): self.skipTest("file symlinks are unavailable") with self.assertRaisesRegex(InventoryError, "private regular file"): verify_corpus(self.raw, None, output, resume=True) self.assertEqual(target.read_bytes(), b"sentinel") def test_rejects_unsafe_cross_platform_relative_paths(self): for value in ("../outside", "C:\\outside", "folder\\file", "//server/share"): with self.subTest(value=value), self.assertRaises(InventoryError): safe_relative_path(value) def test_interrupted_inventory_resumes_and_detects_changed_input(self): payload = self.raw / "payload.txt" payload.write_text("before", encoding="utf-8") output = self.base / "artifacts" stopped = verify_corpus(self.raw, None, output, stop_after_entries=1) self.assertEqual(stopped["status"], "incomplete") resumed = verify_corpus(self.raw, None, output, resume=True) self.assertEqual(resumed["status"], "complete") self.assertEqual(resumed["input_changes"]["raw"]["added"], 1) payload.write_text("after", encoding="utf-8") changed = verify_corpus(self.raw, None, output, resume=True) self.assertEqual(changed["status"], "complete") self.assertEqual(changed["input_changes"]["raw"]["changed"], 1) rows = sqlite3.connect(output / "inventory.sqlite3").execute( "SELECT sha256 FROM files WHERE relative_path='payload.txt'" ).fetchone() self.assertEqual(rows[0], hashlib.sha256(b"after").hexdigest()) def test_large_filesystem_identity_values_are_stored_without_integer_overflow(self): connection = database(self.base / "identity.sqlite3") insert_or_update_file( connection, "run", "raw", "payload", 1, "a" * 64, (2**100, 2**120, 1, 2**110, 2**115, 1), {"raw": {"added": 0, "changed": 0}}, ) device, inode, mtime_ns, ctime_ns = connection.execute( "SELECT device,inode,mtime_ns,ctime_ns FROM files" ).fetchone() self.assertEqual((device, inode, mtime_ns, ctime_ns), tuple(map(str, (2**100, 2**120, 2**110, 2**115)))) connection.close() def test_document_prefix_uses_primary_key_range_and_excludes_neighbor_codes(self): connection = database(self.base / "paths.sqlite3") prefix = "documents/1/" upper = prefix_upper_bound(prefix) plan = connection.execute( "EXPLAIN QUERY PLAN SELECT relative_path FROM files WHERE root_id='raw' AND relative_path>=? AND relative_path", (prefix, upper), ).fetchone()[3] self.assertIn("USING COVERING INDEX sqlite_autoindex_files_1", plan) connection.executemany( "INSERT INTO files(root_id,relative_path,status,last_seen_run) VALUES('raw',?,'hashed','run')", [(f"documents/{code}/a",) for code in range(20000)] + [("documents/1x/a",)], ) self.assertEqual([item["path"] for item in raw_file_rows(connection, "1")], ["documents/1/a"]) connection.close() def test_inventory_rejects_a_concurrent_writer_and_records_verifier_hash(self): output = self.base / "artifacts" output.mkdir(mode=0o700) lock_path = output / ".inventory.lock" descriptor = os.open(lock_path, os.O_CREAT | os.O_RDWR, 0o600) try: fcntl.flock(descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB) with self.assertRaisesRegex(InventoryError, "another inventory run"): verify_corpus(self.raw, None, output) finally: os.close(descriptor) result = verify_corpus(self.raw, None, output) self.assertEqual(result["status"], "complete") self.assertRegex(result["verifier_sha256"], r"^[a-f0-9]{64}$") def test_removed_file_is_reported_on_resume(self): payload = self.raw / "payload.txt" payload.write_text("payload", encoding="utf-8") output = self.base / "artifacts" self.assertEqual(verify_corpus(self.raw, None, output)["status"], "complete") payload.unlink() result = verify_corpus(self.raw, None, output, resume=True) self.assertEqual(result["input_changes"]["raw"]["removed"], 1) self.assertIn("removed_file", {item["kind"] for item in result["finding_examples"]}) def test_added_file_is_reported_on_resume(self): output = self.base / "artifacts" self.assertEqual(verify_corpus(self.raw, None, output)["status"], "complete") (self.raw / "extra.txt").write_text("extra", encoding="utf-8") result = verify_corpus(self.raw, None, output, resume=True) self.assertEqual(result["input_changes"]["raw"]["added"], 1) def test_manifest_error_missing_document_and_extra_directory_are_reported(self): connection = sqlite3.connect(self.raw / "manifest.sqlite3") connection.execute("INSERT INTO documents VALUES (1, ?, 'now')", ("a" * 64,)) connection.execute("INSERT INTO errors VALUES (6, 'fetch failed', 'now')") connection.commit() connection.close() (self.raw / "documents" / "999").mkdir(parents=True) result = verify_corpus(self.raw, None, self.base / "artifacts") kinds = {finding["kind"] for finding in result["finding_examples"]} self.assertEqual(result["status"], "failed") self.assertIn("raw_manifest_error", kinds) self.assertIn("missing_raw_document_directory", kinds) self.assertIn("extra_raw_document_directory", kinds) def test_empty_raw_and_normalized_manifests_complete_successfully(self): normalized = self.base / "normalized" normalized.mkdir() connection = sqlite3.connect(normalized / "manifest.sqlite3") connection.execute( "CREATE TABLE documents (code TEXT PRIMARY KEY, source_sha256 TEXT, schema_version TEXT, normalizer_version TEXT, state TEXT)" ) connection.commit() connection.close() result = verify_corpus(self.raw, normalized, self.base / "artifacts") self.assertEqual(result["status"], "complete", result["finding_examples"]) self.assertEqual(result["manifest_summary"]["raw"]["documents"], 0) self.assertEqual(result["manifest_summary"]["normalized"]["documents"], 0) def test_nonempty_raw_and_normalized_manifests_cross_validate_fragment_sources(self): normalized, _ = self._nonempty_corpus() result = verify_corpus(self.raw, normalized, self.base / "artifacts") self.assertEqual(result["status"], "complete", result["finding_examples"]) self.assertEqual(result["manifest_summary"]["raw"]["documents"], 1) self.assertEqual(result["manifest_summary"]["normalized"]["fragments"], 1) def test_verifies_legacy_normalizer_1_0_0_manifest(self): normalized, _ = self._nonempty_corpus(normalizer_version="1.0.0") result = verify_corpus(self.raw, normalized, self.base / "artifacts") self.assertEqual(result["status"], "complete", result["finding_examples"]) self.assertNotIn( "normalizer_version_mismatch", {item["kind"] for item in result["finding_examples"]}, ) def test_rejects_unsupported_normalizer_version(self): normalized, _ = self._nonempty_corpus(normalizer_version="9.9.9") result = verify_corpus(self.raw, normalized, self.base / "artifacts") self.assertEqual(result["status"], "failed") self.assertIn( "normalizer_version_mismatch", {item["kind"] for item in result["finding_examples"]}, ) def test_raw_normalized_source_mismatch_is_reported(self): normalized, _ = self._nonempty_corpus() manifest = sqlite3.connect(normalized / "manifest.sqlite3") manifest.execute("UPDATE documents SET source_sha256=? WHERE code='1'", ("0" * 64,)) manifest.commit() manifest.close() result = verify_corpus(self.raw, normalized, self.base / "artifacts") kinds = {item["kind"] for item in result["finding_examples"]} self.assertEqual(result["status"], "failed") self.assertIn("normalized_source_hash_mismatch", kinds) self.assertIn("document_source_manifest_mismatch", kinds) def test_fragment_text_hash_mismatch_is_reported(self): normalized = self.base / "normalized" fragment_rel = "documents/1/editions/2/ru/fragments.json" fragment_path = normalized / fragment_rel fragment_path.parent.mkdir(parents=True) fragment = { "id": "document:1:edition:2:lang:ru:fragment:1", "document_code": "1", "edition_code": "2", "language": "ru", "position": 1, "text": "text", "text_sha256": "0" * 64, "source_path": "documents/1/source.txt", "source_sha256": "1" * 64, } fragment_path.write_text(json.dumps([fragment]), encoding="utf-8") content_path = fragment_path.with_name("content.txt") content_path.write_text("text\n", encoding="utf-8") connection = database(self.base / "test.sqlite3") content_digest = hashlib.sha256(b"text\n").hexdigest() connection.execute( "INSERT INTO files(root_id,relative_path,sha256,status,last_seen_run) VALUES('normalized',?,?, 'hashed','run')", (content_path.relative_to(normalized).as_posix(), content_digest), ) validate_fragment_file( connection, "run", normalized, fragment_path, fragment_rel, hashlib.sha256(fragment_path.read_bytes()).hexdigest(), {"documents/1/source.txt": "1" * 64}, ) kinds = {row[0] for row in connection.execute("SELECT kind FROM findings WHERE run_id='run'")} connection.close() self.assertIn("fragment_text_checksum_mismatch", kinds) if __name__ == "__main__": unittest.main()