| 1 | """Independent reader checks against repositories produced by the real Oak CLI."""
|
| 2 | from contextlib import contextmanager
|
| 3 | from unittest import mock
|
| 4 | import importlib.util
|
| 5 | import json
|
| 6 | import os
|
| 7 | from pathlib import Path
|
| 8 | import shutil
|
| 9 | import sqlite3
|
| 10 | import subprocess
|
| 11 | import sys
|
| 12 | import tempfile
|
| 13 | import unittest
|
| 14 |
|
| 15 | ROOT = Path(__file__).resolve().parents[1]
|
| 16 | READER = ROOT / 'scripts/oakbench/oak_sqlite_reader.py'
|
| 17 |
|
| 18 | @unittest.skipUnless(importlib.util.find_spec('blake3') and importlib.util.find_spec('zstandard') and shutil.which('oak'), 'optional reader dependencies and Oak required')
|
| 19 | class OakSQLiteReaderTest(unittest.TestCase):
|
| 20 | def setUp(self):
|
| 21 | self.tmp = tempfile.TemporaryDirectory()
|
| 22 | self.addCleanup(self.tmp.cleanup)
|
| 23 | self.root = Path(self.tmp.name)
|
| 24 | self.repo = self.root / 'repo'
|
| 25 | self.repo.mkdir()
|
| 26 | env = {**os.environ, 'OAK_NO_UPDATE_CHECK': '1', 'HOME': str(self.root)}
|
| 27 | for command in ([shutil.which('oak'), 'init'],):
|
| 28 | subprocess.run(command, cwd=self.repo, env=env, check=True, capture_output=True)
|
| 29 | (self.repo / 'payload.txt').write_text('committed payload\n')
|
| 30 | # A second, smaller blob so the blob-hash format pin has an
|
| 31 | # uncorrupted sample when a test corrupts only the payload blob.
|
| 32 | (self.repo / 'pin.txt').write_text('pin\n')
|
| 33 | subprocess.run([shutil.which('oak'), 'commit', '--no-verify'], cwd=self.repo, env=env, check=True, capture_output=True)
|
| 34 |
|
| 35 | def read(self, *scope):
|
| 36 | extra = ['--scope', *scope] if scope else []
|
| 37 | return subprocess.run([sys.executable, '-I', str(READER), str(self.repo), str(self.root / 'out'), *extra], capture_output=True, text=True)
|
| 38 |
|
| 39 | def assert_unavailable(self, result, reason):
|
| 40 | self.assertEqual(result.returncode, 77, result.stdout + result.stderr)
|
| 41 | self.assertIn(reason, json.loads(result.stdout)['unavailable'])
|
| 42 |
|
| 43 | def test_reads_committed_content_without_subject_or_worktree(self):
|
| 44 | (self.repo / 'payload.txt').write_text('uncommitted replacement')
|
| 45 | result = self.read()
|
| 46 | self.assertEqual(result.returncode, 0, result.stderr + result.stdout)
|
| 47 | self.assertEqual((self.root / 'out/payload.txt').read_text(), 'committed payload\n')
|
| 48 | self.assertEqual(json.loads(result.stdout)['reader_version'], 'oak-sqlite-v1-2026-09-27.3')
|
| 49 |
|
| 50 | def test_corrupt_blob_is_not_verified(self):
|
| 51 | with sqlite3.connect(str(self.repo / '.oak/oak.db')) as db:
|
| 52 | db.execute('PRAGMA journal_mode=DELETE')
|
| 53 | db.execute('UPDATE blobs SET content=?, size=?, codec=0 WHERE size=?', (b'corrupt', 7, len(b'committed payload\n')))
|
| 54 | db.close()
|
| 55 | result = self.read()
|
| 56 | self.assertEqual(result.returncode, 1, result.stderr + result.stdout)
|
| 57 | self.assertIn('hash', result.stdout)
|
| 58 |
|
| 59 | def test_unsupported_format_is_unmeasured(self):
|
| 60 | with sqlite3.connect(str(self.repo / '.oak/oak.db')) as db:
|
| 61 | db.execute('PRAGMA journal_mode=DELETE')
|
| 62 | db.execute("INSERT OR REPLACE INTO metadata(key,value) VALUES ('hash_format','future')")
|
| 63 | db.close()
|
| 64 | result = self.read()
|
| 65 | self.assertEqual(result.returncode, 77, result.stderr + result.stdout)
|
| 66 | self.assertIn('unsupported', result.stdout)
|
| 67 |
|
| 68 | @contextmanager
|
| 69 | def database(self):
|
| 70 | db = sqlite3.connect(str(self.repo / '.oak/oak.db'))
|
| 71 | try:
|
| 72 | db.execute('PRAGMA journal_mode=DELETE')
|
| 73 | yield db
|
| 74 | db.commit()
|
| 75 | finally:
|
| 76 | db.close()
|
| 77 |
|
| 78 | def install_tree(self, entries, *, normalized=False):
|
| 79 | """Author a hash-valid adversarial tree without Oak serializing it."""
|
| 80 | import blake3
|
| 81 | import zstandard
|
| 82 | raw = '\n'.join('\t'.join(entry) for entry in entries).encode()
|
| 83 | tree_hash = blake3.blake3(raw).hexdigest()
|
| 84 | with self.database() as db:
|
| 85 | db.execute('INSERT OR REPLACE INTO trees(hash,content) VALUES (?,?)',
|
| 86 | (tree_hash, None if normalized else zstandard.ZstdCompressor().compress(raw)))
|
| 87 | if normalized:
|
| 88 | for kind, name, object_hash, mode in entries:
|
| 89 | db.execute('INSERT INTO tree_entries(tree_hash,name,kind,hash,mode) VALUES (?,?,?,?,?)',
|
| 90 | (tree_hash, name, kind, object_hash, mode))
|
| 91 | old_head = db.execute("SELECT value FROM metadata WHERE key='head'").fetchone()[0]
|
| 92 | commit = list(db.execute('SELECT branch_name,parent_hash,merge_parent_hash,manifest_hash,author,message,timestamp FROM commits WHERE hash=?', (old_head,)).fetchone())
|
| 93 | commit[3] = tree_hash
|
| 94 | head = blake3.blake3('\n'.join(value or '' for value in commit).encode()).hexdigest()
|
| 95 | db.execute('UPDATE commits SET hash=?,manifest_hash=? WHERE hash=?', (head, tree_hash, old_head))
|
| 96 | db.execute("UPDATE metadata SET value=? WHERE key='head'", (head,))
|
| 97 | return tree_hash
|
| 98 |
|
| 99 | def blob_hash(self):
|
| 100 | with self.database() as db:
|
| 101 | return db.execute('SELECT hash FROM blobs WHERE size=?', (len(b'committed payload\n'),)).fetchone()[0]
|
| 102 |
|
| 103 | def assert_corrupt(self, result, reason):
|
| 104 | self.assertEqual(result.returncode, 1, result.stdout + result.stderr)
|
| 105 | payload = json.loads(result.stdout)
|
| 106 | self.assertIs(payload['corrupt'], True)
|
| 107 | self.assertIn(reason, payload['reason'])
|
| 108 |
|
| 109 | def test_commit_preimage_mismatch_fails_closed_as_unrecognized_format(self):
|
| 110 | # The HEAD preimage is the format pin: a mismatch may be a future Oak
|
| 111 | # serialization, so it is never published as an Oak correctness failure.
|
| 112 | with self.database() as db:
|
| 113 | db.execute("UPDATE commits SET message='tampered'")
|
| 114 | self.assert_unavailable(self.read(), 'commit preimage format unrecognized')
|
| 115 |
|
| 116 | def test_root_tree_mismatch_fails_closed_as_unrecognized_format(self):
|
| 117 | import zstandard
|
| 118 | with self.database() as db:
|
| 119 | db.execute('UPDATE trees SET content=?', (zstandard.ZstdCompressor().compress(b'not original tree'),))
|
| 120 | self.assert_unavailable(self.read(), 'root tree serialization unrecognized')
|
| 121 |
|
| 122 | def test_corrupt_nested_tree_after_verified_root_is_invalid(self):
|
| 123 | import blake3
|
| 124 | import zstandard
|
| 125 | bogus = blake3.blake3(b'expected subtree').hexdigest()
|
| 126 | with self.database() as db:
|
| 127 | db.execute('INSERT INTO trees(hash,content) VALUES (?,?)',
|
| 128 | (bogus, zstandard.ZstdCompressor().compress(b'different subtree bytes')))
|
| 129 | self.install_tree([('tree', 'dir', bogus, 'tree')])
|
| 130 | self.assert_corrupt(self.read(), 'hash')
|
| 131 |
|
| 132 | # QA P1 A1: subject-controlled repository state is a measured failure.
|
| 133 | def test_missing_database_is_measured_failure(self):
|
| 134 | import shutil as _shutil
|
| 135 | _shutil.rmtree(self.repo / '.oak')
|
| 136 | self.assert_corrupt(self.read(), 'database missing')
|
| 137 |
|
| 138 | def test_headless_repository_is_measured_failure(self):
|
| 139 | with self.database() as db:
|
| 140 | db.execute("DELETE FROM metadata WHERE key='head'")
|
| 141 | self.assert_corrupt(self.read(), 'no committed HEAD')
|
| 142 |
|
| 143 | # QA P1 A3: format drift is unmeasured, never corrupt.
|
| 144 | def test_dangling_head_is_measured_failure(self):
|
| 145 | # QA R2-3: format is pinned by schema + migrations; a HEAD naming a
|
| 146 | # missing commit row is an Oak failure.
|
| 147 | with self.database() as db:
|
| 148 | db.execute("UPDATE metadata SET value=? WHERE key='head'", ('a' * 64,))
|
| 149 | self.assert_corrupt(self.read(), 'missing commit row')
|
| 150 |
|
| 151 | def test_newer_schema_migration_is_unavailable(self):
|
| 152 | with self.database() as db:
|
| 153 | db.execute("INSERT INTO schema_migrations(version) VALUES ('9999_future_format')")
|
| 154 | self.assert_unavailable(self.read(), 'unrecognized Oak schema migration')
|
| 155 |
|
| 156 | def test_changed_blob_hash_convention_is_unavailable(self):
|
| 157 | # Simulate a future Oak hashing blobs differently: every stored blob's
|
| 158 | # bytes no longer hash to its key under blake3(raw).
|
| 159 | with self.database() as db:
|
| 160 | db.execute("UPDATE blobs SET content=CAST(content || X'00' AS BLOB), size=size+1 WHERE codec=0")
|
| 161 | for (object_hash, content) in db.execute('SELECT hash,content FROM blobs WHERE codec=1').fetchall():
|
| 162 | import zstandard
|
| 163 | raw = zstandard.ZstdDecompressor().decompress(content) + b'\x00'
|
| 164 | db.execute('UPDATE blobs SET content=?,size=? WHERE hash=?',
|
| 165 | (zstandard.ZstdCompressor().compress(raw), len(raw), object_hash))
|
| 166 | self.assert_unavailable(self.read(), 'blob hash format unrecognized')
|
| 167 |
|
| 168 | def test_in_scope_blob_over_task_limit_is_reported_before_reader_bound(self):
|
| 169 | with self.database() as db:
|
| 170 | db.execute('UPDATE blobs SET size=? WHERE size=?', (40 * 1024 * 1024, len(b'committed payload\n')))
|
| 171 | result = subprocess.run([sys.executable, '-I', str(READER), str(self.repo), str(self.root / 'out'),
|
| 172 | '--max-blob-bytes', str(1024 * 1024), '--scope', 'payload.txt'], capture_output=True, text=True)
|
| 173 | self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
| 174 | self.assertEqual(json.loads(result.stdout)['oversized_paths'], ['payload.txt'])
|
| 175 |
|
| 176 | def test_unrecognized_schema_is_unavailable(self):
|
| 177 | with self.database() as db:
|
| 178 | db.execute('ALTER TABLE blobs RENAME COLUMN codec TO codec_v2')
|
| 179 | self.assert_unavailable(self.read(), 'unrecognized Oak storage schema')
|
| 180 |
|
| 181 | def test_hash_valid_traversal_is_rejected_without_external_write(self):
|
| 182 | self.install_tree([('blob', '../escaped', self.blob_hash(), 'regular')])
|
| 183 | self.assert_corrupt(self.read(), 'unsafe')
|
| 184 | self.assertFalse((self.root / 'escaped').exists())
|
| 185 |
|
| 186 | def test_case_colliding_paths_cannot_overwrite(self):
|
| 187 | probe = self.root / 'casecheck'
|
| 188 | probe.write_text('case')
|
| 189 | if not (self.root / 'CASECHECK').exists():
|
| 190 | self.skipTest('filesystem distinguishes case; no alias to test')
|
| 191 | h = self.blob_hash()
|
| 192 | self.install_tree([('blob', 'A', h, 'regular'), ('blob', 'a', h, 'regular')])
|
| 193 | result = self.read()
|
| 194 | # Reported (as Git fails the path set), never silently overwritten.
|
| 195 | self.assertEqual(result.returncode, 0, result.stdout)
|
| 196 | self.assertEqual(len(json.loads(result.stdout)['collision_paths']), 1)
|
| 197 |
|
| 198 | def test_symlink_mode_is_explicitly_unavailable(self):
|
| 199 | self.install_tree([('blob', 'link', self.blob_hash(), 'symlink')])
|
| 200 | result = self.read()
|
| 201 | self.assertEqual(result.returncode, 77, result.stdout)
|
| 202 | self.assertIn('unsupported tree entry', result.stdout)
|
| 203 | self.assertFalse((self.root / 'out/link').exists())
|
| 204 |
|
| 205 | def test_chunk_only_or_missing_complete_blob_is_unavailable(self):
|
| 206 | with self.database() as db:
|
| 207 | db.execute('DELETE FROM blobs')
|
| 208 | result = self.read()
|
| 209 | self.assertEqual(result.returncode, 77, result.stdout)
|
| 210 | self.assertIn('chunk-only', result.stdout)
|
| 211 |
|
| 212 | def test_active_wal_is_not_silently_ignored(self):
|
| 213 | db = sqlite3.connect(str(self.repo / '.oak/oak.db'))
|
| 214 | try:
|
| 215 | db.execute('PRAGMA journal_mode=WAL')
|
| 216 | db.execute("INSERT OR REPLACE INTO metadata(key,value) VALUES ('pending-reader-test','1')")
|
| 217 | db.commit()
|
| 218 | self.assertTrue((self.repo / '.oak/oak.db-wal').exists())
|
| 219 | result = self.read()
|
| 220 | self.assertEqual(result.returncode, 77, result.stdout)
|
| 221 | self.assertIn('active SQLite journal', result.stdout)
|
| 222 | finally:
|
| 223 | db.close()
|
| 224 |
|
| 225 | # Reader budgets are harness limits, not facts about Oak's content:
|
| 226 | # exceeding one is unmeasured (77), never a corrupt (1) Oak failure.
|
| 227 | def test_declared_blob_size_over_bound_is_unmeasured(self):
|
| 228 | with self.database() as db:
|
| 229 | db.execute('UPDATE blobs SET size=?', (32 * 1024 * 1024 + 1,))
|
| 230 | self.assert_unavailable(self.read(), 'size exceeds')
|
| 231 |
|
| 232 | def test_declared_zstd_window_over_bound_is_unmeasured_without_allocation(self):
|
| 233 | # A tiny frame header declaring a >32MiB single-segment window.
|
| 234 | frame = b'\x28\xb5\x2f\xfd\xa0' + (32 * 1024 * 1024 + 1).to_bytes(4, 'little') + b'\x01\x00\x00'
|
| 235 | with self.database() as db:
|
| 236 | db.execute('UPDATE blobs SET content=?,codec=1 WHERE size=?', (frame, len(b'committed payload\n')))
|
| 237 | self.assert_unavailable(self.read(), 'window exceeds')
|
| 238 |
|
| 239 | def test_out_of_scope_entries_are_never_decoded(self):
|
| 240 | h = self.blob_hash()
|
| 241 | self.install_tree([('blob', 'huge.bin', 'f' * 64, 'regular'), ('blob', 'link', h, 'symlink'),
|
| 242 | ('blob', 'payload.txt', h, 'regular')])
|
| 243 | result = self.read('payload.txt')
|
| 244 | self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
| 245 | payload = json.loads(result.stdout)
|
| 246 | self.assertEqual(payload['scope'], ['payload.txt'])
|
| 247 | self.assertEqual(payload['nonregular_paths'], [])
|
| 248 | self.assertEqual(sorted(p.name for p in (self.root / 'out').iterdir()), ['payload.txt'])
|
| 249 |
|
| 250 | def test_in_scope_symlink_is_reported_for_oracle_failure(self):
|
| 251 | h = self.blob_hash()
|
| 252 | self.install_tree([('blob', 'link', h, 'symlink'), ('blob', 'payload.txt', h, 'regular')])
|
| 253 | result = self.read('link', 'payload.txt')
|
| 254 | self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
| 255 | self.assertEqual(json.loads(result.stdout)['nonregular_paths'], ['link'])
|
| 256 | self.assertFalse((self.root / 'out/link').exists())
|
| 257 |
|
| 258 | def test_scoped_directory_reads_only_its_subtree(self):
|
| 259 | import blake3
|
| 260 | import zstandard
|
| 261 | h = self.blob_hash()
|
| 262 | inner = '\t'.join(('blob', 'config.toml', h, 'regular')).encode()
|
| 263 | inner_hash = blake3.blake3(inner).hexdigest()
|
| 264 | with self.database() as db:
|
| 265 | db.execute('INSERT INTO trees(hash,content) VALUES (?,?)', (inner_hash, zstandard.ZstdCompressor().compress(inner)))
|
| 266 | self.install_tree([('blob', 'other', 'e' * 64, 'regular'), ('tree', 'services', inner_hash, 'tree')])
|
| 267 | result = self.read('services')
|
| 268 | self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
| 269 | self.assertEqual((self.root / 'out/services/config.toml').read_bytes(), b'committed payload\n')
|
| 270 | self.assertFalse((self.root / 'out/other').exists())
|
| 271 |
|
| 272 | def test_normalized_legacy_tree_roundtrip(self):
|
| 273 | self.install_tree([('blob', 'legacy', self.blob_hash(), 'regular')], normalized=True)
|
| 274 | result = self.read()
|
| 275 | self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
| 276 | self.assertEqual((self.root / 'out/legacy').read_bytes(), b'committed payload\n')
|
| 277 |
|
| 278 | def test_legacy_entry_field_bound_precedes_materialization(self):
|
| 279 | self.install_tree([('blob', 'x' * 4097, self.blob_hash(), 'regular')], normalized=True)
|
| 280 | self.assert_unavailable(self.read(), 'entry exceeds')
|
| 281 |
|
| 282 | def test_executable_mode_is_preserved_for_downstream_validation(self):
|
| 283 | self.install_tree([('blob', 'executable', self.blob_hash(), 'executable')])
|
| 284 | result = self.read()
|
| 285 | self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
| 286 | self.assertTrue((self.root / 'out/executable').stat().st_mode & 0o111)
|
| 287 |
|
| 288 | def test_source_database_change_after_snapshot_is_unavailable(self):
|
| 289 | spec = importlib.util.spec_from_file_location('independent_reader_control', READER)
|
| 290 | reader = importlib.util.module_from_spec(spec)
|
| 291 | spec.loader.exec_module(reader)
|
| 292 | original_write = Path.write_bytes
|
| 293 | def write_then_change_database(path, content):
|
| 294 | result = original_write(path, content)
|
| 295 | if path.name == 'snapshot.db':
|
| 296 | with self.database() as db:
|
| 297 | db.execute("INSERT OR REPLACE INTO metadata(key,value) VALUES ('changed-after-snapshot','1')")
|
| 298 | return result
|
| 299 | with mock.patch.object(Path, 'write_bytes', write_then_change_database):
|
| 300 | with self.assertRaisesRegex(reader.Unavailable, 'database changed'):
|
| 301 | reader.read_committed_tree(self.repo, self.root / 'out')
|
| 302 |
|
| 303 | def test_unknown_blob_codec_is_unavailable(self):
|
| 304 | with self.database() as db:
|
| 305 | db.execute('UPDATE blobs SET codec=99 WHERE size=?', (len(b'committed payload\n'),))
|
| 306 | result = self.read()
|
| 307 | self.assertEqual(result.returncode, 77, result.stdout)
|
| 308 | self.assertIn('unsupported object codec', result.stdout)
|
| 309 |
|
| 310 | def commit_bugfix_payload(self):
|
| 311 | env = {**os.environ, 'OAK_NO_UPDATE_CHECK': '1', 'HOME': str(self.root)}
|
| 312 | (self.repo / 'app').mkdir()
|
| 313 | (self.repo / 'app/pricing.py').write_text('def f(cents, percent):\n return cents - ((cents * percent) // 100)\n')
|
| 314 | subprocess.run([shutil.which('oak'), 'commit', '--no-verify'], cwd=self.repo, env=env, check=True, capture_output=True)
|
| 315 |
|
| 316 | def evidence(self):
|
| 317 | sys.path.insert(0, str(ROOT / 'scripts'))
|
| 318 | from oakbench.workflow_oracles import independent_oak_evidence, VERSION
|
| 319 | return independent_oak_evidence('bugfix_test_loop', self.repo, sys.executable,
|
| 320 | {'oracle_version': VERSION, 'workflow_integrity_source': 'trusted_task_worktree',
|
| 321 | 'workflow_integrity_passed': None, 'workflow_integrity_unmeasured_reason': None})
|
| 322 |
|
| 323 | def test_in_scope_blob_over_task_limit_fails_like_git_before_reader_bound(self):
|
| 324 | # QA P1 A4: Git reports committed_payload_over_limit for an in-scope
|
| 325 | # blob over the task's 1 MiB limit; the reader must agree rather than
|
| 326 | # hit its own 32 MiB bound and go unmeasured.
|
| 327 | self.commit_bugfix_payload()
|
| 328 | with self.database() as db:
|
| 329 | db.execute('UPDATE blobs SET size=? WHERE size>?', (32 * 1024 * 1024 + 1, len(b'committed payload\n')))
|
| 330 | result = self.evidence()
|
| 331 | self.assertIs(result['workflow_integrity_passed'], False, result)
|
| 332 | self.assertEqual(result['workflow_integrity_failure_reason'], 'committed_payload_over_limit:app/pricing.py')
|
| 333 |
|
| 334 | def test_out_of_scope_oversized_blob_does_not_fail_oak(self):
|
| 335 | self.commit_bugfix_payload()
|
| 336 | with self.database() as db:
|
| 337 | db.execute('UPDATE blobs SET size=? WHERE size=?', (32 * 1024 * 1024 + 1, len(b'committed payload\n')))
|
| 338 | result = self.evidence()
|
| 339 | self.assertIs(result['workflow_integrity_passed'], True, result)
|
| 340 | self.assertEqual(result['workflow_integrity_committed_scope'], ['app/pricing.py'])
|
| 341 |
|
| 342 | def test_corrupt_reader_envelope_reaches_workflow_failure(self):
|
| 343 | sys.path.insert(0, str(ROOT / 'scripts'))
|
| 344 | from oakbench.workflow_oracles import independent_oak_evidence, VERSION
|
| 345 | self.commit_bugfix_payload()
|
| 346 | with self.database() as db:
|
| 347 | db.execute('UPDATE blobs SET content=?,size=?,codec=0 WHERE size>?', (b'corrupt', 7, len(b'committed payload\n')))
|
| 348 | result = independent_oak_evidence('bugfix_test_loop', self.repo, sys.executable,
|
| 349 | {'oracle_version': VERSION, 'workflow_integrity_source': 'trusted_task_worktree',
|
| 350 | 'workflow_integrity_passed': None, 'workflow_integrity_unmeasured_reason': None})
|
| 351 | self.assertIs(result['workflow_integrity_passed'], False, result)
|
| 352 | self.assertIn('oak_stored_content_invalid', result['workflow_integrity_failure_reason'])
|
| 353 | self.assertIsNone(result['workflow_integrity_unmeasured_reason'])
|