File size: 4,042 Bytes
870b85a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
"""Read sealed candidate metadata and compare selected native source records."""
import hashlib
import json
import math
from pathlib import Path
import sqlite3


IDENTITY = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]


def digest(path):
    sha = hashlib.sha256()
    with Path(path).open('rb') as stream:
        for block in iter(lambda: stream.read(1024 * 1024), b''):
            sha.update(block)
    return sha.hexdigest()


def load_pools(paths, requested_ids):
    """Read existing v2 SQLite pools in read-only mode, binding pool/receipt bytes.

    This consumes the latest source's candidates.candidate_json schema. Full
    importer, annotation and Blender qualification remain the native pipeline's
    responsibility; this helper establishes only selected source identity/size.
    """
    records, hashes = {}, {}
    for raw_path in paths:
        path = Path(raw_path).resolve()
        journals = [Path(str(path) + suffix) for suffix in ('-wal', '-journal')]
        if any(journal.exists() for journal in journals):
            raise ValueError('Prepared pool has an unsealed SQLite journal')
        receipt_path = path.with_suffix('.receipt.json')
        receipt = json.loads(receipt_path.read_text())
        hashes[str(path)] = digest(path)
        hashes[str(receipt_path)] = digest(receipt_path)
        if (receipt.get('schema') != 'rhg.prepared_asset_pool.v2'
                or receipt.get('sha256') != hashes[str(path)]):
            raise ValueError('Prepared candidate pool differs from its sealed receipt')
        with sqlite3.connect(path.as_uri() + '?mode=ro&immutable=1', uri=True) as db:
            for (raw,) in db.execute('SELECT candidate_json FROM candidates'):
                row = json.loads(raw)
                json.dumps(row, allow_nan=False)
                if row['asset_id'] in requested_ids:
                    records.setdefault(row['asset_id'], []).append(row)
        if (digest(path) != hashes[str(path)] or digest(receipt_path) != hashes[str(receipt_path)]
                or any(journal.exists() for journal in journals)):
            raise ValueError('Sealed prepared pool changed during reading')
    return records, hashes


def check_candidate(entity, candidates):
    """Compare native fields and actual source bytes; return diagnostics/hashes."""
    dimensions = entity.get('dimensions_m')
    valid_dimensions = (isinstance(dimensions, list) and len(dimensions) == 3
        and all(type(v) in (int, float) and math.isfinite(v) and v > 0 for v in dimensions))
    scale = entity.get('uniform_scale', 1)
    raw_scale = entity.get('scale', 1)
    matches = []
    raw_scale_native = (type(raw_scale) in (int, float) and raw_scale == 1
                       or isinstance(raw_scale, list) and len(raw_scale) == 3
                       and all(type(v) in (int, float) and v == 1 for v in raw_scale))
    if valid_dimensions and type(scale) in (int, float) and scale == 1 and raw_scale_native:
        for row in candidates:
            if (row.get('dimensions_m') == dimensions
                    and entity.get('source_dimensions_m') == dimensions
                    and entity.get('canonical_transform', IDENTITY) == row.get('canonical_transform', IDENTITY)
                    and all(entity.get(key) == row.get(key) and row.get(key)
                            for key in ('asset_sha256', 'runtime_sha256', 'canonical_path', 'runtime_path'))):
                matches.append(row)
    for row in matches:
        sources = {}
        for path_key, hash_key in (('canonical_path', 'asset_sha256'), ('runtime_path', 'runtime_sha256')):
            path = Path(row[path_key])
            if not path.is_file() or digest(path) != row[hash_key]:
                break
            sources[str(path)] = row[hash_key]
        else:
            return [], sources
    return [dict(code='native_candidate_contract_unverified', entity_ids=[entity['entity_id']],
                 message='Selected dimensions/transform/source bytes do not match a sealed native candidate')], {}