File size: 20,641 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
"""Authenticate opt-in measurements of an unchanged, saved generated scene.

refresh_measurements(config, generated_manifest_path, output_dir, *, source_root,
                     timeout_s) returns a retained result.json receipt. A runner
is an argv list in config.measurement_refresh.command; the literal tokens
{manifest}, {scene}, {output}, {source_root}, {requirements} are substituted
without a shell. The latter names the retained original task/priors JSON.
Its JSON output must use rhg.measured-refresh.v1 and bind exact manifest and
saved-scene bytes with manifest_sha256 and scene_sha256. Evidence can contain
sparse task/priors patches or repeat unchanged requirement fields.

Only measured_supports surface region/height/source pins and approach width/pins,
and priors surface/footprint bounds/source pins can change. Placement anchors,
candidate IDs, dimensions, limits, reservations and motifs remain requirements.
source_sha256 pins the entity asset_sha256 when available, otherwise the scene;
the envelope ALWAYS pins the scene. Old measurement fields are removed before
merging, so partial evidence cannot inherit a previous pose's measurements.

passed certifies fresh, complete measurement evidence, including evidence of
infeasible geometry. It never certifies task feasibility or native physics.
Absent runners and incomplete measurements return pending with passed=False.
"""
from __future__ import annotations

import copy
import hashlib
import json
import math
from pathlib import Path
import time

if __package__:
    from . import process_control
    from .spatial_priors import evaluate_priors
    from .task_precheck import evaluate_task
else:
    import process_control
    from spatial_priors import evaluate_priors
    from task_precheck import evaluate_task


__all__ = ['refresh_measurements']
_SURFACE = {'region', 'height_m', 'source_sha256', 'source_scene_sha256'}
_APPROACH = {'approach_clearance_width_m', 'approach_source_sha256',
             'approach_scene_sha256', 'source_sha256', 'source_scene_sha256'}
_BOUNDS = {'bounds_xy_m', 'source_sha256', 'source_scene_sha256'}


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


def _canonical(value):
    return json.dumps(value, sort_keys=True, separators=(',', ':'), allow_nan=False)


def _pairs(items):
    result = {}
    for key, value in items:
        if key in result:
            raise ValueError('Duplicate JSON field: ' + key)
        result[key] = value
    return result


def load_json(path):
    def invalid(value):
        raise ValueError('Nonfinite JSON number: ' + value)
    value = json.loads(Path(path).read_bytes(), object_pairs_hook=_pairs, parse_constant=invalid)
    _canonical(value)  # Includes numeric overflow such as 1e999.
    return value


def _save(path, value):
    with Path(path).open('x', encoding='utf-8') as stream:
        stream.write(json.dumps(value, indent=2, sort_keys=True, allow_nan=False) + '\n')


def _positive(value, label):
    if type(value) not in (int, float) or not math.isfinite(value) or value <= 0:
        raise ValueError(label + ' must be finite and positive')
    return float(value)


def _index(rows, label):
    if not isinstance(rows, list):
        raise ValueError(label + ' must be a list')
    indexed = {}
    for row in rows:
        if not isinstance(row, dict):
            raise ValueError(label + ' must contain objects')
        identifier = row.get('entity_id')
        if not isinstance(identifier, str) or not identifier.strip() or identifier in indexed:
            raise ValueError(label + ' requires unique, nonempty entity_id values')
        indexed[identifier] = row
    return indexed


def _protected(original, patch, mutable, label):
    if not isinstance(original, dict) or not isinstance(patch, dict):
        raise ValueError(label + ' must be an object')
    for key, value in patch.items():
        if key not in mutable and (key not in original or
                                    _canonical(value) != _canonical(original[key])):
            raise ValueError('Protected requirement changed: ' + label + '.' + key)


def _without_evidence(config):
    result = {key: copy.deepcopy(config[key]) for key in ('task', 'priors') if key in config}
    task = result.get('task')
    if isinstance(task, dict):
        for row in task.get('measured_supports', []):
            if isinstance(row, dict):
                for key in _APPROACH:
                    row.pop(key, None)
                if isinstance(row.get('surface'), dict):
                    for key in _SURFACE:
                        row['surface'].pop(key, None)
    priors = result.get('priors')
    if isinstance(priors, dict):
        for field in ('surfaces', 'footprints'):
            for row in priors.get(field, []):
                if isinstance(row, dict):
                    for key in _BOUNDS:
                        row.pop(key, None)
    return result


def _source(record, entity, scene_sha, label):
    if 'source_scene_sha256' in record and record['source_scene_sha256'] != scene_sha:
        raise ValueError('Stale scene source pin: ' + label)
    if 'source_sha256' not in record:
        return False
    expected = entity.get('asset_sha256') or scene_sha
    value = record['source_sha256']
    if (not isinstance(expected, str) or len(expected) != 64 or
            any(c not in '0123456789abcdefABCDEF' for c in expected) or
            not isinstance(value, str) or value.lower() != expected.lower()):
        raise ValueError('Stale or invalid source_sha256: ' + label)
    return True


def _rectangle(value):
    if (not isinstance(value, list) or len(value) != 4 or
            any(type(v) not in (int, float) or not math.isfinite(v) for v in value) or
            not value[0] < value[2] or not value[1] < value[3]):
        raise ValueError('Measured bounds require a positive finite XY rectangle')


def _merge(config, evidence, manifest, scene_sha):
    result = _without_evidence(config)
    missing = []
    entities = _index(manifest.get('entities'), 'manifest.entities')
    for section in ('task', 'priors'):
        if section not in config or config[section] is None:
            if section in evidence and evidence[section] not in (None, {}):
                raise ValueError('Unrequested evidence section: ' + section)
            continue
        original, patch = config[section], evidence.get(section, {})
        mutable = {'measured_supports'} if section == 'task' else {'surfaces', 'footprints'}
        _protected(original, patch, mutable, section)
        if section == 'task':
            old = _index(original.get('measured_supports', []), 'task.measured_supports')
            rows = _index(patch.get('measured_supports', []), 'evidence.measured_supports')
            wanted = list(dict.fromkeys(original.get('support_entity_ids', []) + list(old)))
            if set(rows) - set(wanted) or set(wanted) - set(entities):
                raise ValueError('Measurement changed task support candidates')
            merged_rows = []
            for identifier in wanted:
                previous = old.get(identifier, {'entity_id': identifier})
                update = rows.get(identifier, {})
                _protected(previous, update, _APPROACH | {'surface'}, 'measured_supports')
                row = next((r for r in result[section].get('measured_supports', [])
                            if r['entity_id'] == identifier), {'entity_id': identifier})
                surface_patch = update.get('surface', {})
                _protected(previous.get('surface', {}), surface_patch, _SURFACE, 'surface')
                row.setdefault('surface', {}).update(copy.deepcopy(surface_patch))
                row.update({key: copy.deepcopy(value) for key, value in update.items()
                            if key in _APPROACH})
                surface = row['surface']
                source_ok = _source(surface_patch, entities[identifier], scene_sha, identifier)
                if not source_ok or not {'region', 'height_m', 'xy_m'} <= surface.keys():
                    missing.append('task.surface:' + identifier)
                for key in ('source_scene_sha256', 'approach_scene_sha256'):
                    if key in update and update[key] != scene_sha:
                        raise ValueError('Stale approach/scene source pin')
                if 'source_sha256' in update:
                    _source(update, entities[identifier], scene_sha, identifier)
                if 'approach_clearance_width_m' in update:
                    pin = update.get('approach_source_sha256', update.get('source_sha256'))
                    if pin is not None:
                        _source({'source_sha256': pin}, entities[identifier], scene_sha, identifier)
                    if pin is None:
                        missing.append('task.approach_source:' + identifier)
                elif 'minimum_approach_width_m' in original:
                    missing.append('task.approach:' + identifier)
                merged_rows.append(row)
            result[section]['measured_supports'] = merged_rows
            audit = evaluate_task(manifest, result[section])
            if audit['status'] == 'insufficient_evidence':
                missing.append('task.required_measurements')
        else:
            reserved = {r['support_entity_id'] for r in original.get('reservations', [])}
            for field in ('surfaces', 'footprints'):
                old = _index(original.get(field, []), 'priors.' + field)
                expected = dict(old)
                if field == 'surfaces':
                    for identifier in reserved:
                        expected.setdefault(identifier, {'entity_id': identifier})
                else:
                    for identifier, entity in entities.items():
                        parents = {entity[k] for k in ('supported_by_entity_id',
                                   'support_entity_id', 'parent_entity_id') if entity.get(k) is not None}
                        if len(parents) == 1 and next(iter(parents)) in reserved:
                            expected.setdefault(identifier, dict(entity_id=identifier,
                                support_entity_id=next(iter(parents))))
                rows = _index(patch.get(field, []), 'evidence.' + field)
                if set(rows) - set(expected) or set(expected) - set(entities):
                    raise ValueError('Measurement changed prior entity domain')
                merged_rows = []
                for identifier, previous in expected.items():
                    update = rows.get(identifier, {})
                    _protected(previous, update, _BOUNDS, 'priors.' + field)
                    row = {k: copy.deepcopy(v) for k, v in previous.items() if k not in _BOUNDS}
                    row.update({k: copy.deepcopy(v) for k, v in update.items() if k in _BOUNDS})
                    if 'bounds_xy_m' in update:
                        _rectangle(update['bounds_xy_m'])
                    source_ok = _source(update, entities[identifier], scene_sha, identifier)
                    if not source_ok or 'bounds_xy_m' not in update:
                        missing.append('priors.' + field + ':' + identifier)
                    merged_rows.append(row)
                if field in original or merged_rows:
                    result[section][field] = merged_rows
            audit = evaluate_priors(manifest, result[section])
            if audit['status'] == 'insufficient_evidence':
                missing.append('priors.required_measurements')
    return result, missing


def refresh_measurements(config, generated_manifest_path, output_dir, *, source_root,
                         timeout_s) -> dict:
    """Run a configured measurement command within the caller's remaining budget."""
    started = time.monotonic()
    output = Path(output_dir).resolve()
    result = dict(schema='rhg.measurement-refresh-result.v1', status='pending', passed=False,
                  evidence_manifest_sha256=None, input_sha256={}, artifact_sha256={},
                  command=None, receipt_path=None, inputs_unchanged=True,
                  physical_qualified=False, native_preflight_queried=False,
                  whole_task_acceptance=False)
    writable = False
    try:
        if not isinstance(config, dict):
            raise ValueError('config must be an object')
        _canonical(config)
        result.update(_without_evidence(config))
        output.mkdir(parents=True, exist_ok=True)
        if any(output.iterdir()):
            raise ValueError('Measurement output directory must be new or empty')
        writable = True
        budget = _positive(timeout_s, 'timeout_s')
        runner = config.get('measurement_refresh')
        if runner is None or runner == {}:
            result['pending_fields'] = ['measurement_refresh.command']
        else:
            if not isinstance(runner, dict):
                raise ValueError('measurement_refresh must be an object')
            command = runner.get('command')
            if command is None:
                result['pending_fields'] = ['measurement_refresh.command']
            else:
                if (not isinstance(command, list) or not command or
                        any(not isinstance(arg, str) or not arg for arg in command)):
                    raise ValueError('measurement_refresh.command must be nonempty argv tokens')
                if 'timeout_s' in runner:
                    budget = min(budget, _positive(runner['timeout_s'], 'measurement_refresh.timeout_s'))
                deadline = started + budget
                manifest_path = Path(generated_manifest_path).resolve(strict=True)
                manifest_sha = file_sha256(manifest_path)
                result['input_sha256'][str(manifest_path)] = manifest_sha
                manifest = load_json(manifest_path)
                generation = config.get('generation', {})
                scene_name = generation.get('scene_output')
                if scene_name is None:
                    identifier = manifest.get('scene_id')
                    if (not isinstance(identifier, str) or not identifier or
                            Path(identifier).name != identifier or identifier in ('.', '..')):
                        raise ValueError('Manifest needs scene_id or generation.scene_output')
                    scene_name = identifier + '.blend'
                if not isinstance(scene_name, str) or not scene_name:
                    raise ValueError('generation.scene_output must be a saved file path')
                scene = (manifest_path.parent / scene_name).resolve(strict=True)
                if scene == manifest_path or not scene.is_file():
                    raise ValueError('Saved scene is missing or aliases the manifest')
                scene_sha = file_sha256(scene)
                result['input_sha256'][str(scene)] = scene_sha
                source = Path(source_root).resolve(strict=True)
                request = output / 'measurement_request.json'
                _save(request, {key: config[key] for key in ('task', 'priors') if key in config})
                result['input_sha256'][str(request)] = file_sha256(request)
                target = output / 'evidence.json'
                tokens = {'{manifest}': str(manifest_path), '{scene}': str(scene),
                          '{output}': str(target), '{source_root}': str(source),
                          '{requirements}': str(request)}
                expanded = []
                for argument in command:
                    for token, value in tokens.items():
                        argument = argument.replace(token, value)
                    expanded.append(argument)
                for index, argument in enumerate(expanded):
                    path = Path(argument)
                    if path.is_absolute() and path.is_file() and (index == 0 or path.suffix == '.py'):
                        sha = file_sha256(path)
                        # Keep the invoked path too: a symlink can be retargeted.
                        result['input_sha256'][str(path)] = sha
                        result['input_sha256'][str(path.resolve())] = sha
                remaining = deadline - time.monotonic()
                if remaining <= 0:
                    raise TimeoutError('Measurement deadline exhausted before command launch')
                result['command'] = expanded
                receipt = process_control.execute_command(expanded, source, output / 'measurement.log', remaining)
                receipt_path = output / 'command_receipt.json'
                _save(receipt_path, receipt)
                result['receipt_path'] = str(receipt_path)
                if (receipt.get('exit_code') != 0 or receipt.get('timed_out') is not False or
                        receipt.get('cleanup_passed') is not True):
                    raise ValueError('Measurement command failed, timed out, or cleanup failed')
                if time.monotonic() > deadline:
                    raise TimeoutError('Measurement command exceeded remaining deadline')
                evidence = load_json(target)
                if (not isinstance(evidence, dict) or evidence.get('schema') != 'rhg.measured-refresh.v1' or
                        evidence.get('manifest_sha256') != manifest_sha or
                        evidence.get('scene_sha256') != scene_sha):
                    raise ValueError('Stale or malformed measurement evidence binding')
                if any(evidence.get(k) is True for k in ('physical_qualified', 'whole_task_acceptance')):
                    raise ValueError('Measurement evidence cannot certify native acceptance')
                extra_pins = evidence.get('input_sha256', {})
                if not isinstance(extra_pins, dict):
                    raise ValueError('Evidence input_sha256 must be a path/hash mapping')
                for name, expected in extra_pins.items():
                    path = Path(name)
                    if (not path.is_absolute() or not path.is_file() or
                            not isinstance(expected, str) or file_sha256(path) != expected or
                            (str(path.resolve()) in result['input_sha256'] and
                             result['input_sha256'][str(path.resolve())] != expected)):
                        raise ValueError('Stale or conflicting measurement input pin: ' + name)
                    result['input_sha256'][str(path.resolve())] = expected
                merged, missing = _merge(config, evidence, manifest, scene_sha)
                if time.monotonic() > deadline:
                    raise TimeoutError('Measurement validation exceeded remaining deadline')
                result.update(merged)
                result['evidence_path'] = str(target)
                result['evidence_manifest_sha256'] = manifest_sha
                if missing or evidence.get('status') == 'pending' or evidence.get('passed') is False:
                    result['pending_fields'] = missing or evidence.get('pending_fields', ['runner.pending'])
                else:
                    if evidence.get('status', 'measured') not in ('measured', 'refreshed', 'complete'):
                        raise ValueError('Unsupported measurement evidence status')
                    result.update(status='refreshed', passed=True)
    except Exception as error:
        result.update(status='failed', passed=False, evidence_manifest_sha256=None,
                      error_type=type(error).__name__, error=str(error))
    finally:
        try:
            result['inputs_unchanged'] = all(Path(path).is_file() and file_sha256(path) == sha
                                             for path, sha in result['input_sha256'].items())
        except OSError:
            result['inputs_unchanged'] = False
        if not result['inputs_unchanged']:
            result.update(status='failed', passed=False, evidence_manifest_sha256=None,
                          error='Measurement input changed during command or validation')
        result['elapsed_s'] = round(time.monotonic() - started, 3)
        if writable:
            result['artifact_sha256'] = {str(path): file_sha256(path)
                for path in sorted(output.rglob('*')) if path.is_file() and not path.is_symlink()}
            result['result_path'] = str(output / 'result.json')
            _save(output / 'result.json', result)
    return result