RoboHome / code /robohome /src /engine /tests /test_effective_request.py
RoboParty Release
Unify robohome source, assets and scenes delivery
3f15e9f
Raw History Blame
12.5 kB
import copy
import hashlib
import json
from pathlib import Path
import sqlite3
import sys
import tempfile
import unittest
from engine.run_chain import run_chain
from engine.search_bridge import compile_search_request
class EffectiveRequestTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
self.manifest = dict(floor_plan={'rooms': [{'room_id': 'living'}]}, entities=[
dict(entity_id='table', room_id='living', role='side_table',
asset_id='original', dimensions_m=[1, 1, .7])])
self.request = dict(schema='rhg.scene_request.v1', mode='pool',
task_kind='scene_generation', task_text='Fixture only.',
entities=copy.deepcopy(self.manifest['entities']),
furniture=[dict(entity_id='table', candidate_asset_ids=['original'])])
asset = self.root / 'fixture.asset'
asset.write_text('synthetic native source fixture')
sha = self.digest(asset)
self.record = dict(asset_id='backup', pool_candidate_key='backup-record',
dimensions_m=[1, 1, .7], canonical_path=str(asset),
runtime_path=str(asset), asset_sha256=sha, runtime_sha256=sha)
self.pool = self.root / 'pool.sqlite3'
with sqlite3.connect(self.pool) as db:
db.execute('CREATE TABLE candidates (candidate_json TEXT)')
db.execute('INSERT INTO candidates VALUES (?)', (json.dumps(self.record),))
self.write('pool.receipt.json', dict(schema='rhg.prepared_asset_pool.v2',
sha256=self.digest(self.pool)))
self.effective = compile_search_request(self.request, {}, self.manifest)
self.effective['furniture'][0].update(candidate_asset_ids=['backup'],
candidate_record_ids=['backup-record'])
self.receipt_changes = {}
self.write_receipt = True
self.runtime = None
@staticmethod
def digest(path):
return hashlib.sha256(path.read_bytes()).hexdigest()
def write(self, name, payload):
path = self.root / name
path.write_text(json.dumps(payload))
return path
def run_fixture(self):
self.write('manifest.json', self.manifest)
self.write('request.json', self.request)
generated = copy.deepcopy(self.manifest)
generated['entities'][0].update(self.record, source_dimensions_m=[1, 1, .7],
uniform_scale=1)
payload = self.write('payload.json', dict(
effective=self.effective, generated=generated, receipt_changes=self.receipt_changes,
write_receipt=self.write_receipt, pool=str(self.pool), pool_sha=self.digest(self.pool)))
body = '''import hashlib,json,pathlib,sys
out=pathlib.Path(sys.argv[1]); p=json.loads(pathlib.Path(sys.argv[2]).read_text())
request=out/'request.json'; original=json.loads(request.read_text()); effective=p['effective']
row=effective['furniture'][0]
receipt=dict(schema='rhg.eligible_candidate_request.v1',passed=True,
input_request=str(request),input_request_sha256=hashlib.sha256(request.read_bytes()).hexdigest(),
effective_request_sha256=hashlib.sha256(json.dumps(effective,sort_keys=True,separators=(',',':')).encode()).hexdigest(),
prepared_pools=[dict(path=p['pool'],sha256=p['pool_sha'])],entity_count=1,
entity_ids_preserved=True,task_and_relations_preserved=True,
entities=[dict(entity_id='table',original_asset_ids=original['furniture'][0]['candidate_asset_ids'],
eligible_asset_ids=row['candidate_asset_ids'],eligible_record_ids=row['candidate_record_ids'])])
receipt.update(p['receipt_changes'])
(out/'eligible_scene_request.json').write_text(json.dumps(effective))
if p['write_receipt']:
(out/'candidate_eligibility_report.json').write_text(json.dumps(receipt))
(out/'generated.json').write_text(json.dumps(p['generated']))
'''
config = dict(schema='rhg.frontier-chain-config.v1', manifest='manifest.json',
request='request.json', prepared_pools=['pool.sqlite3'], generation=dict(
command=[sys.executable, '-c', body, '{attempt_dir}', str(payload)],
manifest_output='generated.json', timeout_s=5))
if self.runtime is not None:
self.write('template.json', self.runtime)
config['generation']['runtime_template'] = 'template.json'
path = self.write('config.json', config)
return run_chain(path, self.root / 'output', execute=True)
def assert_rejected(self, error=None, *, diagnostic=None):
result = self.run_fixture()
self.assertEqual(result['status'], 'output_contract_failed', result)
self.assertFalse(result['output_contract_passed'])
self.assertNotEqual(error is None, diagnostic is None)
if error is not None:
self.assertEqual(result.get('error_type'), 'ValueError', result)
self.assertEqual(result.get('error'), error, result)
else:
self.assertNotIn('error', result)
review = json.loads((self.root / 'output/attempt_01/output_review.json').read_text())
self.assertIn(diagnostic, [row['code'] for row in review['diagnostics']])
def test_compatible_backup_from_prebound_pool_is_verified(self):
result = self.run_fixture()
self.assertEqual(result['status'], 'generation_completed_pending_native_validation', result)
self.assertTrue(result['output_contract_passed'])
self.assertTrue(result['inputs_unchanged'])
audit = json.loads((self.root / 'output/attempt_01/effective_request_review.json').read_text())
self.assertTrue(audit['passed'])
self.assertEqual(audit['added_asset_ids'], ['backup'])
def test_wrong_input_hash_is_rejected(self):
self.receipt_changes['input_request_sha256'] = '0' * 64
self.assert_rejected('Effective eligibility receipt does not bind this frozen request/output')
def test_wrong_input_path_is_rejected(self):
self.receipt_changes['input_request'] = str(self.root / 'request.json')
self.assert_rejected('Effective eligibility receipt does not bind this frozen request/output')
def test_failed_native_eligibility_is_rejected(self):
self.receipt_changes['passed'] = False
self.assert_rejected('Effective eligibility receipt does not bind this frozen request/output')
def test_wrong_effective_hash_is_rejected(self):
self.receipt_changes['effective_request_sha256'] = '0' * 64
self.assert_rejected('Effective eligibility receipt does not bind this frozen request/output')
def test_missing_eligibility_receipt_is_rejected(self):
self.write_receipt = False
self.assert_rejected('Effective request/receipt must both belong to this attempt')
def test_changed_task_is_rejected_even_with_matching_receipt(self):
self.effective['task_text'] = 'Unauthorized task'
self.assert_rejected('Effective request changed a protected field: task_text')
def test_changed_semantics_are_rejected_even_with_matching_receipt(self):
self.effective['entities'][0]['role'] = 'sofa'
self.assert_rejected('Effective request changed a protected field: entities')
def test_unknown_pool_is_rejected(self):
self.receipt_changes['prepared_pools'] = [dict(path='/unknown/pool', sha256='0' * 64)]
self.assert_rejected('Effective eligibility differs from the pre-bound prepared pools')
def test_unsealed_record_is_rejected(self):
self.effective['furniture'][0]['candidate_record_ids'] = ['unsealed-record']
self.assert_rejected('Effective eligibility contains an unsealed candidate: table')
def test_explicit_record_pin_cannot_be_widened(self):
self.request['furniture'][0]['candidate_record_ids'] = ['pinned-record']
self.effective['furniture'][0]['candidate_record_ids'] = ['backup-record']
self.assert_rejected('Effective eligibility widened explicit record pins: table')
def test_single_record_pin_cannot_be_bypassed(self):
for request in (self.request, self.effective):
request['furniture'][0]['record_id'] = 'pinned-record'
self.assert_rejected('Effective eligibility violated a hard record/source pin: table')
def test_matching_explicit_record_and_source_pins_are_accepted(self):
for request in (self.request, self.effective):
request['furniture'][0].update(record_id='backup-record',
candidate_record_ids=['backup-record'], source_sha256=self.record['asset_sha256'])
self.assertTrue(self.run_fixture()['output_contract_passed'])
def test_explicit_source_hash_cannot_be_bypassed(self):
for request in (self.request, self.effective):
request['furniture'][0]['source_sha256'] = '0' * 64
self.assert_rejected('Effective eligibility violated a hard record/source pin: table')
def test_changed_native_size_is_still_rejected(self):
self.record['dimensions_m'] = [2, 2, 2]
self.assert_rejected(diagnostic='native_candidate_contract_unverified')
def test_changed_source_bytes_are_still_rejected(self):
Path(self.record['runtime_path']).write_text('tampered')
self.assert_rejected(diagnostic='native_candidate_contract_unverified')
def test_locked_request_cannot_consume_pool_expansion(self):
self.request['mode'] = 'locked'
self.request['furniture'][0]['asset_id'] = 'original'
self.assert_rejected('Effective pool expansion is not allowed for a locked request')
def test_unknown_top_level_enrichment_is_rejected(self):
self.effective['unchecked_policy'] = 'accept_all'
self.assert_rejected('Effective request changed a protected field: unchecked_policy')
def test_runtime_support_evidence_enrichment_is_accepted(self):
source = self.write('measured_surface.json', dict(schema='synthetic.measured_surface'))
refs = [dict(path=str(source), sha256=self.digest(source))]
index = self.write('surfaces.json', dict(schema='rhg.prepared_support_surfaces.v1', sources=refs))
floor = self.write('floor.json', dict(schema='fixture.floor'))
self.runtime = dict(prepared_support_surfaces=str(index), prepared_floor_body_geometry=str(floor))
self.effective['support_surface_feedback'] = refs
self.effective['floor_body_geometry_index'] = dict(path=str(floor.resolve()), sha256=self.digest(floor))
result = self.run_fixture()
self.assertTrue(result['output_contract_passed'], result)
def test_unbound_support_enrichment_is_rejected(self):
self.effective['support_surface_feedback'] = [dict(path='/unknown', sha256='a' * 64)]
self.assert_rejected('Effective request changed a protected field: support_surface_feedback')
def test_effective_request_cannot_remove_compiled_search(self):
del self.effective['search']
self.assert_rejected('Effective request removed a caller field: search')
def test_effective_request_cannot_change_compiled_search_order(self):
self.effective['search']['functional_children_first'] = False
self.assert_rejected('Effective request changed a protected field: search')
def test_native_search_defaults_cannot_replace_explicit_caller_value(self):
self.request['search'] = dict(functional_children_first=True, max_nodes_per_room=17)
self.effective['search']['max_nodes_per_room'] = 80000
self.assert_rejected('Effective request changed a protected field: search')
def test_runtime_floor_enrichment_cannot_replace_explicit_caller_field(self):
caller = self.write('caller_floor.json', dict(schema='fixture.caller_floor'))
floor = self.write('runtime_floor.json', dict(schema='fixture.runtime_floor'))
self.request['floor_body_geometry_index'] = dict(path=str(caller.resolve()), sha256=self.digest(caller))
self.effective['floor_body_geometry_index'] = dict(path=str(floor.resolve()), sha256=self.digest(floor))
self.runtime = dict(prepared_floor_body_geometry=str(floor))
self.assert_rejected('Effective request changed a protected field: floor_body_geometry_index')
if __name__ == '__main__':
unittest.main()