Viewing files at commit 290f11640be1Commit detailsView latest

Browse files
tests/test_oak_sqlite_reader.py 351 lines · 18.9 KB · python
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.2')
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_head_commit_row_not_found_is_unavailable(self):
145
        with self.database() as db:
146
            db.execute("UPDATE metadata SET value=? WHERE key='head'", ('a' * 64,))
147
        self.assert_unavailable(self.read(), 'commit row not found')
148
149
    def test_newer_schema_migration_is_unavailable(self):
150
        with self.database() as db:
151
            db.execute("INSERT INTO schema_migrations(version) VALUES ('9999_future_format')")
152
        self.assert_unavailable(self.read(), 'unrecognized Oak schema migration')
153
154
    def test_changed_blob_hash_convention_is_unavailable(self):
155
        # Simulate a future Oak hashing blobs differently: every stored blob's
156
        # bytes no longer hash to its key under blake3(raw).
157
        with self.database() as db:
158
            db.execute("UPDATE blobs SET content=CAST(content || X'00' AS BLOB), size=size+1 WHERE codec=0")
159
            for (object_hash, content) in db.execute('SELECT hash,content FROM blobs WHERE codec=1').fetchall():
160
                import zstandard
161
                raw = zstandard.ZstdDecompressor().decompress(content) + b'\x00'
162
                db.execute('UPDATE blobs SET content=?,size=? WHERE hash=?',
163
                           (zstandard.ZstdCompressor().compress(raw), len(raw), object_hash))
164
        self.assert_unavailable(self.read(), 'blob hash format unrecognized')
165
166
    def test_in_scope_blob_over_task_limit_is_reported_before_reader_bound(self):
167
        with self.database() as db:
168
            db.execute('UPDATE blobs SET size=? WHERE size=?', (40 * 1024 * 1024, len(b'committed payload\n')))
169
        result = subprocess.run([sys.executable, '-I', str(READER), str(self.repo), str(self.root / 'out'),
170
                                 '--max-blob-bytes', str(1024 * 1024), '--scope', 'payload.txt'], capture_output=True, text=True)
171
        self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
172
        self.assertEqual(json.loads(result.stdout)['oversized_paths'], ['payload.txt'])
173
174
    def test_unrecognized_schema_is_unavailable(self):
175
        with self.database() as db:
176
            db.execute('ALTER TABLE blobs RENAME COLUMN codec TO codec_v2')
177
        self.assert_unavailable(self.read(), 'unrecognized Oak storage schema')
178
179
    def test_hash_valid_traversal_is_rejected_without_external_write(self):
180
        self.install_tree([('blob', '../escaped', self.blob_hash(), 'regular')])
181
        self.assert_corrupt(self.read(), 'unsafe')
182
        self.assertFalse((self.root / 'escaped').exists())
183
184
    def test_case_colliding_paths_cannot_overwrite(self):
185
        probe = self.root / 'casecheck'
186
        probe.write_text('case')
187
        if not (self.root / 'CASECHECK').exists():
188
            self.skipTest('filesystem distinguishes case; no alias to test')
189
        h = self.blob_hash()
190
        self.install_tree([('blob', 'A', h, 'regular'), ('blob', 'a', h, 'regular')])
191
        result = self.read()
192
        # Reported (as Git fails the path set), never silently overwritten.
193
        self.assertEqual(result.returncode, 0, result.stdout)
194
        self.assertEqual(len(json.loads(result.stdout)['collision_paths']), 1)
195
196
    def test_symlink_mode_is_explicitly_unavailable(self):
197
        self.install_tree([('blob', 'link', self.blob_hash(), 'symlink')])
198
        result = self.read()
199
        self.assertEqual(result.returncode, 77, result.stdout)
200
        self.assertIn('unsupported tree entry', result.stdout)
201
        self.assertFalse((self.root / 'out/link').exists())
202
203
    def test_chunk_only_or_missing_complete_blob_is_unavailable(self):
204
        with self.database() as db:
205
            db.execute('DELETE FROM blobs')
206
        result = self.read()
207
        self.assertEqual(result.returncode, 77, result.stdout)
208
        self.assertIn('chunk-only', result.stdout)
209
210
    def test_active_wal_is_not_silently_ignored(self):
211
        db = sqlite3.connect(str(self.repo / '.oak/oak.db'))
212
        try:
213
            db.execute('PRAGMA journal_mode=WAL')
214
            db.execute("INSERT OR REPLACE INTO metadata(key,value) VALUES ('pending-reader-test','1')")
215
            db.commit()
216
            self.assertTrue((self.repo / '.oak/oak.db-wal').exists())
217
            result = self.read()
218
            self.assertEqual(result.returncode, 77, result.stdout)
219
            self.assertIn('active SQLite journal', result.stdout)
220
        finally:
221
            db.close()
222
223
    # Reader budgets are harness limits, not facts about Oak's content:
224
    # exceeding one is unmeasured (77), never a corrupt (1) Oak failure.
225
    def test_declared_blob_size_over_bound_is_unmeasured(self):
226
        with self.database() as db:
227
            db.execute('UPDATE blobs SET size=?', (32 * 1024 * 1024 + 1,))
228
        self.assert_unavailable(self.read(), 'size exceeds')
229
230
    def test_declared_zstd_window_over_bound_is_unmeasured_without_allocation(self):
231
        # A tiny frame header declaring a >32MiB single-segment window.
232
        frame = b'\x28\xb5\x2f\xfd\xa0' + (32 * 1024 * 1024 + 1).to_bytes(4, 'little') + b'\x01\x00\x00'
233
        with self.database() as db:
234
            db.execute('UPDATE blobs SET content=?,codec=1 WHERE size=?', (frame, len(b'committed payload\n')))
235
        self.assert_unavailable(self.read(), 'window exceeds')
236
237
    def test_out_of_scope_entries_are_never_decoded(self):
238
        h = self.blob_hash()
239
        self.install_tree([('blob', 'huge.bin', 'f' * 64, 'regular'), ('blob', 'link', h, 'symlink'),
240
                           ('blob', 'payload.txt', h, 'regular')])
241
        result = self.read('payload.txt')
242
        self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
243
        payload = json.loads(result.stdout)
244
        self.assertEqual(payload['scope'], ['payload.txt'])
245
        self.assertEqual(payload['nonregular_paths'], [])
246
        self.assertEqual(sorted(p.name for p in (self.root / 'out').iterdir()), ['payload.txt'])
247
248
    def test_in_scope_symlink_is_reported_for_oracle_failure(self):
249
        h = self.blob_hash()
250
        self.install_tree([('blob', 'link', h, 'symlink'), ('blob', 'payload.txt', h, 'regular')])
251
        result = self.read('link', 'payload.txt')
252
        self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
253
        self.assertEqual(json.loads(result.stdout)['nonregular_paths'], ['link'])
254
        self.assertFalse((self.root / 'out/link').exists())
255
256
    def test_scoped_directory_reads_only_its_subtree(self):
257
        import blake3
258
        import zstandard
259
        h = self.blob_hash()
260
        inner = '\t'.join(('blob', 'config.toml', h, 'regular')).encode()
261
        inner_hash = blake3.blake3(inner).hexdigest()
262
        with self.database() as db:
263
            db.execute('INSERT INTO trees(hash,content) VALUES (?,?)', (inner_hash, zstandard.ZstdCompressor().compress(inner)))
264
        self.install_tree([('blob', 'other', 'e' * 64, 'regular'), ('tree', 'services', inner_hash, 'tree')])
265
        result = self.read('services')
266
        self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
267
        self.assertEqual((self.root / 'out/services/config.toml').read_bytes(), b'committed payload\n')
268
        self.assertFalse((self.root / 'out/other').exists())
269
270
    def test_normalized_legacy_tree_roundtrip(self):
271
        self.install_tree([('blob', 'legacy', self.blob_hash(), 'regular')], normalized=True)
272
        result = self.read()
273
        self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
274
        self.assertEqual((self.root / 'out/legacy').read_bytes(), b'committed payload\n')
275
276
    def test_legacy_entry_field_bound_precedes_materialization(self):
277
        self.install_tree([('blob', 'x' * 4097, self.blob_hash(), 'regular')], normalized=True)
278
        self.assert_unavailable(self.read(), 'entry exceeds')
279
280
    def test_executable_mode_is_preserved_for_downstream_validation(self):
281
        self.install_tree([('blob', 'executable', self.blob_hash(), 'executable')])
282
        result = self.read()
283
        self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
284
        self.assertTrue((self.root / 'out/executable').stat().st_mode & 0o111)
285
286
    def test_source_database_change_after_snapshot_is_unavailable(self):
287
        spec = importlib.util.spec_from_file_location('independent_reader_control', READER)
288
        reader = importlib.util.module_from_spec(spec)
289
        spec.loader.exec_module(reader)
290
        original_write = Path.write_bytes
291
        def write_then_change_database(path, content):
292
            result = original_write(path, content)
293
            if path.name == 'snapshot.db':
294
                with self.database() as db:
295
                    db.execute("INSERT OR REPLACE INTO metadata(key,value) VALUES ('changed-after-snapshot','1')")
296
            return result
297
        with mock.patch.object(Path, 'write_bytes', write_then_change_database):
298
            with self.assertRaisesRegex(reader.Unavailable, 'database changed'):
299
                reader.read_committed_tree(self.repo, self.root / 'out')
300
301
    def test_unknown_blob_codec_is_unavailable(self):
302
        with self.database() as db:
303
            db.execute('UPDATE blobs SET codec=99 WHERE size=?', (len(b'committed payload\n'),))
304
        result = self.read()
305
        self.assertEqual(result.returncode, 77, result.stdout)
306
        self.assertIn('unsupported object codec', result.stdout)
307
308
    def commit_bugfix_payload(self):
309
        env = {**os.environ, 'OAK_NO_UPDATE_CHECK': '1', 'HOME': str(self.root)}
310
        (self.repo / 'app').mkdir()
311
        (self.repo / 'app/pricing.py').write_text('def f(cents, percent):\n    return cents - ((cents * percent) // 100)\n')
312
        subprocess.run([shutil.which('oak'), 'commit', '--no-verify'], cwd=self.repo, env=env, check=True, capture_output=True)
313
314
    def evidence(self):
315
        sys.path.insert(0, str(ROOT / 'scripts'))
316
        from oakbench.workflow_oracles import independent_oak_evidence, VERSION
317
        return independent_oak_evidence('bugfix_test_loop', self.repo, sys.executable,
318
            {'oracle_version': VERSION, 'workflow_integrity_source': 'trusted_task_worktree',
319
             'workflow_integrity_passed': None, 'workflow_integrity_unmeasured_reason': None})
320
321
    def test_in_scope_blob_over_task_limit_fails_like_git_before_reader_bound(self):
322
        # QA P1 A4: Git reports committed_payload_over_limit for an in-scope
323
        # blob over the task's 1 MiB limit; the reader must agree rather than
324
        # hit its own 32 MiB bound and go unmeasured.
325
        self.commit_bugfix_payload()
326
        with self.database() as db:
327
            db.execute('UPDATE blobs SET size=? WHERE size>?', (32 * 1024 * 1024 + 1, len(b'committed payload\n')))
328
        result = self.evidence()
329
        self.assertIs(result['workflow_integrity_passed'], False, result)
330
        self.assertEqual(result['workflow_integrity_failure_reason'], 'committed_payload_over_limit:app/pricing.py')
331
332
    def test_out_of_scope_oversized_blob_does_not_fail_oak(self):
333
        self.commit_bugfix_payload()
334
        with self.database() as db:
335
            db.execute('UPDATE blobs SET size=? WHERE size=?', (32 * 1024 * 1024 + 1, len(b'committed payload\n')))
336
        result = self.evidence()
337
        self.assertIs(result['workflow_integrity_passed'], True, result)
338
        self.assertEqual(result['workflow_integrity_committed_scope'], ['app/pricing.py'])
339
340
    def test_corrupt_reader_envelope_reaches_workflow_failure(self):
341
        sys.path.insert(0, str(ROOT / 'scripts'))
342
        from oakbench.workflow_oracles import independent_oak_evidence, VERSION
343
        self.commit_bugfix_payload()
344
        with self.database() as db:
345
            db.execute('UPDATE blobs SET content=?,size=?,codec=0 WHERE size>?', (b'corrupt', 7, len(b'committed payload\n')))
346
        result = independent_oak_evidence('bugfix_test_loop', self.repo, sys.executable,
347
            {'oracle_version': VERSION, 'workflow_integrity_source': 'trusted_task_worktree',
348
             'workflow_integrity_passed': None, 'workflow_integrity_unmeasured_reason': None})
349
        self.assertIs(result['workflow_integrity_passed'], False, result)
350
        self.assertIn('oak_stored_content_invalid', result['workflow_integrity_failure_reason'])
351
        self.assertIsNone(result['workflow_integrity_unmeasured_reason'])