Files
NODEDC_MISSION_CORE/simulation/urban-plan-research/topdown/reconcile_objects.py
T
DCCONSTRUCTIONS 69dc566665 feat(research): preserve urban geometry pipelines and qualification suites
Preserve offline geometry, marking, replay and evaluation pipelines with source manifests and synthetic tests. Research qualification does not activate these methods as production navigation.
2026-10-29 09:10:00 +03:00

87 lines
5.7 KiB
Python

"""Non-destructive map reconciliation, strictly after independent verification.
This is map-state assembly, never an inference input. A missing proposal is
not evidence that a confirmed object disappeared. Unmatched old features are
preserved byte-for-byte as JSON values; they do not count as freshly recovered.
"""
import copy
import hashlib
import json
import shapely
from shapely.geometry import shape
from preservation import compare
from component_conflicts import symbol_replacements, FRAGMENT_POLICY
def reconcile(base_bytes,result_bytes,verification):
base=json.loads(base_bytes);proposed=json.loads(result_bytes)
digest=hashlib.sha256(result_bytes).hexdigest()
features=proposed['features'];ids=[f['id'] for f in features]
if len(set(ids))!=len(ids):raise ValueError('Duplicate proposal identity')
if not (verification.get('passed') is True and verification.get('original_pixels_remeasured') is True
and verification.get('immutable_presets') is True and verification.get('source_registry_verified') is True
and verification.get('source_result_sha256')==digest and verification.get('accepted')==len(features)
and sorted(v['id'] for v in verification.get('checks',[]))==sorted(ids)):
raise ValueError('Independent verification does not bind these proposal bytes')
prior=base['features'];old_ids=[f['id'] for f in prior]
if len(set(old_ids))!=len(old_ids):raise ValueError('Duplicate base identity')
arrows=[f for f in prior if 'arrow' in f['properties'].get('subtype','')]
matches=compare(dict(features=arrows),proposed)
old={f['id']:f for f in arrows};new={f['id']:f for f in features}
output=copy.deepcopy(base);positions={f['id']:i for i,f in enumerate(output['features'])}
replaced=[];added=[];unresolved=[];used=set();upgraded=[];absorbed=set()
for pair in matches['pairs']:
before=old[pair['reference_id']];after=new[pair['result_id']]
# A proposal must not replace manual/authoritative map state. Such a
# conflict needs its own review, independently of numeric fit quality.
if before['properties'].get('authority')!='observation-only':
unresolved.append(dict(proposal=after['id'],reason='protected-existing-authority'));used.add(after['id']);continue
merged=copy.deepcopy(after);merged['id']=before['id']
for key in ['authority','route_permission','review_status']:
if key in before['properties']:merged['properties'][key]=copy.deepcopy(before['properties'][key])
output['features'][positions[before['id']]]=merged
replaced.append(dict(existing=before['id'],proposal=after['id'],identity_iou=pair['iou']))
used.add(after['id'])
for feature in features:
if feature['id'] in used:continue
q=shapely.force_2d(shape(feature['geometry']))
current=output['features']
fragments=symbol_replacements(q,feature['properties']['subtype'],current)
if fragments is None:
unresolved.append(dict(proposal=feature['id'],reason='existing-marking-conflict'));continue
if any(f['properties'].get('authority')!='observation-only' or
f['properties'].get('review_status') not in [None,'unreviewed'] for f in fragments):
unresolved.append(dict(proposal=feature['id'],reason='protected-existing-fragment'));continue
if fragments:
# The existing fragment identity becomes the complete object. All
# original records remain in provenance; extra fragments become
# explicit aliases, never silently removed independent objects.
fragments=sorted(fragments,key=lambda f:f['id'])
identity=fragments[0]['id'];merged=copy.deepcopy(feature);merged['id']=identity
for key in ['authority','route_permission','review_status']:
if key in fragments[0]['properties']:merged['properties'][key]=copy.deepcopy(fragments[0]['properties'][key])
merged['properties']['absorbed_fragments']=copy.deepcopy(fragments)
fragment_ids={f['id'] for f in fragments}
output['features']=[merged if f['id']==identity else f for f in current
if f['id']==identity or f['id'] not in fragment_ids]
absorbed.update(fragment_ids)
upgraded.append(dict(existing=identity,proposal=feature['id'],fragment_ids=sorted(fragment_ids),
retired_aliases=sorted(fragment_ids-{identity}),policy=FRAGMENT_POLICY,
previous_records=copy.deepcopy(fragments)))
positions={f['id']:i for i,f in enumerate(output['features'])}
continue
if feature['id'] in positions:raise ValueError('Proposal collides with unrelated existing ID')
output['features'].append(copy.deepcopy(feature));added.append(feature['id'])
replaced_ids={r['existing'] for r in replaced}
retained=[f['id'] for f in arrows if f['id'] not in replaced_ids]
actual={f['id']:f for f in output['features']}
for f in prior:
if f['id'] not in replaced_ids|absorbed and actual.get(f['id'])!=f:raise AssertionError('Untouched object changed')
if not set(old_ids)-absorbed<=actual.keys():raise AssertionError('Existing object lost')
ledger=dict(base_sha256=hashlib.sha256(base_bytes).hexdigest(),proposal_sha256=digest,
input_objects=len(prior),output_objects=len(actual),freshly_verified=len(features),
replaced=replaced,added=added,fragment_upgrades=upgraded,retained_previous_arrow_geometry=retained,conflicts=unresolved,
deleted=[],other_objects_unchanged=True,prior_map_seen_by_inference=False,
fresh_recovery_must_be_measured_separately=True,published=False)
return output,ledger