wenjieshu's picture
Add files using upload-large-folder tool
b8ea052 verified
Raw History Blame Contribute Delete
16.4 kB
"""Compile reviewed predicates into a small shared visual-change program.
The program is configuration, not a checker implementation. Cases select a
scope, typed deltas, shared executor names, and an optional VLM prompt profile.
Runtime code remains in the executor registry, so adding a case does not add a
new Python checker class.
"""
from __future__ import annotations
from copy import deepcopy
from typing import Any, Mapping
from pvr_eval.core.visual_change_types import DELTA_TYPES, SCOPE_KINDS, SCOPE_ROLES
CHANGE_SPEC_SCHEMA_VERSION = "pvr.visual_change_spec.v1"
SUPPORTED_CHANGE_FAMILIES = frozenset(
{
"fixed_location_entity_preservation",
"registered_invariant_region_preservation",
"relocated_entity_integrity",
"contract_family_all_of",
}
)
# Facts keep their contract-authored thresholds. This table only says which
# typed delta the measurement describes; it never invents a new threshold.
FACT_DELTA_TYPES: dict[str, str] = {
"centroid_shift_pixels": "position_changed",
"centroid_shift": "position_changed",
"centroid_shift_fraction_of_image_diagonal": "position_changed",
"bird_centroid_shift_fraction_of_diagonal": "position_changed",
"centroid_shift_max_fraction_of_chair_bbox_diagonal": "position_changed",
"centroid_shift_max_fraction_of_instance_bbox_diagonal": "position_changed",
"scale_change": "scale_changed",
"scale_change_ratio": "scale_changed",
"bbox_scale_ratio": "scale_changed",
"relative_scale_ratio_tolerance": "scale_changed",
"bird_area_change_ratio": "scale_changed",
"aspect_ratio_change": "shape_changed",
"registered_mask_iou": "shape_changed",
"mask_iou_after_registration": "shape_changed",
"robot_mask_iou": "shape_changed",
"door_mask_iou": "shape_changed",
"man_mask_iou": "shape_changed",
"boundary_iou": "shape_changed",
"tray_shape_iou": "shape_changed",
"severe_shape_deformation": "shape_changed",
"mask_shape_change_warning": "shape_changed",
"orientation_change": "pose_changed",
"orientation_change_degrees": "pose_changed",
"rotation_change_degrees": "pose_changed",
"appearance_embedding_similarity": "texture_changed",
"appearance_similarity": "texture_changed",
"appearance_similarity_warning": "texture_changed",
"bird_appearance_similarity": "texture_changed",
"instance_count": "count_changed",
"counts": "count_changed",
"magazine_count": "count_changed",
"required_original_bird_match_rate": "entity_missing",
"major_part_match_rate": "part_missing",
"changed_pixel_fraction": "unexplained_region_change",
"background_changed_fraction": "unexplained_region_change",
"unexplained_change_area_fraction": "unexplained_region_change",
"unexplained_change_ratio": "unexplained_region_change",
"invariant_change_ratio": "unexplained_region_change",
"coherent_invariant_change_fraction": "unexplained_region_change",
"invariant_region_ssim": "background_structure_changed",
"major_edge_retention": "background_structure_changed",
"structural_edge_retention": "background_structure_changed",
"vacated_site_hole_score": "inpainting_artifact",
"vacated_site_repeated_texture_score": "inpainting_artifact",
"vacated_site_texture_collapse_score": "inpainting_artifact",
}
_ENVIRONMENT_DELTAS = frozenset(
{"background_structure_changed", "inpainting_artifact", "unexplained_region_change"}
)
def _delta_bindings(predicate: Mapping[str, Any]) -> list[dict[str, Any]]:
"""Return every reviewed parameter clause backed by the delta ontology.
A clause may have been routed to ``semantic_vlm`` by an older compiler
simply because no deterministic producer existed at the time. The shared
change executor is itself a deterministic producer, so producer history
must not prevent it from satisfying a typed orientation/pose clause.
Obligation clauses are intentionally excluded: they are conclusions, not
measurements.
"""
rows: list[dict[str, Any]] = []
for binding in predicate.get("parameter_bindings", []):
if not isinstance(binding, Mapping) or binding.get("consumer") != "decision_clause":
continue
fact = str(binding.get("fact") or "")
delta_type = FACT_DELTA_TYPES.get(fact)
if not delta_type or fact.startswith("obligation:"):
continue
rows.append({**deepcopy(dict(binding)), "delta_type": delta_type})
return rows
def _operation_config(predicate: Mapping[str, Any]) -> dict[str, Any]:
return {
str(item.get("config_key") or ""): deepcopy(item.get("value"))
for item in predicate.get("parameter_bindings", [])
if isinstance(item, Mapping)
and item.get("consumer") == "operation_config"
and str(item.get("config_key") or "")
}
def _unmapped_parameter_clauses(predicate: Mapping[str, Any]) -> list[str]:
rows: list[str] = []
for binding in predicate.get("parameter_bindings", []):
if not isinstance(binding, Mapping) or binding.get("consumer") != "decision_clause":
continue
fact = str(binding.get("fact") or "")
if fact.startswith("obligation:"):
continue
if fact not in FACT_DELTA_TYPES:
rows.append(fact or str(binding.get("source_key") or "unnamed_clause"))
return list(dict.fromkeys(rows))
def _semantic_pass_is_compilable(predicate: Mapping[str, Any]) -> tuple[bool, list[str]]:
"""Certify only that the contract semantics fit the shared delta API.
This is not a runtime pass. The executor must still prove roster coverage
and resolve every requested delta. Requiring reviewed obligation text
prevents a synthetic/minimal predicate from silently claiming broad
preservation semantics.
"""
obligations = [
item for item in predicate.get("obligations", []) if isinstance(item, Mapping)
]
reasons = ["unmapped_parameter_clause:" + value for value in _unmapped_parameter_clauses(predicate)]
if not obligations:
reasons.append("reviewed_obligations_missing")
elif any(not str(item.get("source_text") or "").strip() for item in obligations):
reasons.append("reviewed_obligation_text_missing")
return not reasons, reasons
def _subject_roster(predicate: Mapping[str, Any]) -> list[dict[str, Any]]:
annotations = [
item
for item in (predicate.get("parameters") or {}).get("source_instance_annotations", [])
if isinstance(item, Mapping)
]
rows: list[dict[str, Any]] = []
for subject in predicate.get("subjects", []):
if not isinstance(subject, Mapping):
continue
identity = str(subject.get("identity_query") or "").strip()
aliases = list(dict.fromkeys(
str(value).strip()
for key in ("input_queries", "output_queries", "aliases")
for value in subject.get(key, [])
if str(value).strip()
))
if identity and identity not in aliases:
aliases.insert(0, identity)
matched_annotations = []
for annotation in annotations:
annotation_labels = [
str(annotation.get(key) or "").casefold()
for key in ("group_id", "label", "query_text", "semantic_class")
if str(annotation.get(key) or "").strip()
]
alias_values = [value.casefold() for value in aliases if value]
if len(predicate.get("subjects", [])) == 1 or any(
left == right or left in right or right in left
for left in annotation_labels for right in alias_values
):
matched_annotations.append(annotation)
rows.append(
{
"subject_id": str(subject.get("id") or ""),
"identity_query": identity,
"aliases": aliases,
"expected_count": subject.get("expected_count"),
"source_instance_ids": list(dict.fromkeys(
[str(value) for value in subject.get("source_instance_ids", []) if str(value)]
+ [
str(item.get("instance_id") or "")
for item in matched_annotations if str(item.get("instance_id") or "")
]
)),
"open_collection": identity.casefold().startswith(("all ", "every ", "each ")),
"provenance": str(subject.get("provenance") or ""),
}
)
return rows
def compile_change_spec(predicate: Mapping[str, Any]) -> dict[str, Any]:
"""Return an auditable shared-executor program for one predicate."""
family = str(predicate.get("family") or "")
if family not in SUPPORTED_CHANGE_FAMILIES:
return {}
bindings = _delta_bindings(predicate)
if not bindings:
return {}
check_id = str(predicate.get("check_id") or "")
target_families = {
str(value) for value in predicate.get("target_families", []) if str(value)
}
environment = family == "registered_invariant_region_preservation" or (
family == "contract_family_all_of"
and "registered_invariant_region_preservation" in target_families
and all(row["delta_type"] in _ENVIRONMENT_DELTAS for row in bindings)
)
relocated = family == "relocated_entity_integrity" or (
family == "contract_family_all_of" and "relocated_entity_integrity" in target_families
)
operation_config = _operation_config(predicate)
semantic_pass_complete, semantic_coverage_reasons = _semantic_pass_is_compilable(predicate)
if environment:
scope = {
"scope_id": f"{check_id}:protected_environment",
"kind": "region",
"role": "protected_environment",
"label": "question-scoped protected environment",
"source_check_ids": [check_id],
"metadata": {
"region_ids": [
str(item.get("region_id") or "")
for item in predicate.get("regions", [])
if isinstance(item, Mapping)
and str(item.get("semantic_role") or "") == "protected_region"
]
},
}
prompt_profile = "environment_change_audit_v1"
executors = ["registered_environment_change_v1"]
# The executor only reports ``changed`` after exclusion-aware
# registration and two independent major-damage cues agree.
violation_short_circuit_certified = True
semantic_pass_complete = False
semantic_coverage_reasons = ["environment_pass_requires_exclusion_aware_executor"]
else:
subject_roster = _subject_roster(predicate)
scope = {
"scope_id": f"{check_id}:entities",
"kind": "entity_set",
"role": "edit_target" if relocated else "protected_entity",
"label": "question-scoped entity set",
"source_check_ids": [check_id],
"metadata": {
"subject_ids": [
str(item.get("id") or "")
for item in predicate.get("subjects", []) if isinstance(item, Mapping)
],
"source_instance_ids": [
str(item.get("instance_id") or "")
for item in (predicate.get("parameters") or {}).get("source_instance_annotations", [])
if isinstance(item, Mapping)
],
"subjects": subject_roster,
"operation_config": operation_config,
},
}
prompt_profile = "relocated_entity_integrity_v1" if relocated else "entity_preservation_v1"
executors = ["stable_entity_geometry_v1"]
# This profile only triggers on large, independently corroborated
# matcher/bbox changes. Narrow threshold failures remain audit-only.
violation_short_circuit_certified = True
deltas = list(dict.fromkeys(str(row["delta_type"]) for row in bindings))
# Movement is intended for relocated targets. Position facts may support
# target completion elsewhere, but they are not a forbidden integrity
# change in this preservation program.
if relocated:
deltas = [value for value in deltas if value != "position_changed"]
count_config = any(
value is True and "count" in key.casefold()
for key, value in operation_config.items()
)
one_to_one_config = any(
value is True and "one_to_one" in key.casefold()
for key, value in operation_config.items()
)
if not environment and (count_config or one_to_one_config):
deltas.extend(["entity_missing", "count_changed"])
deltas = list(dict.fromkeys(deltas))
if not deltas:
return {}
return {
"schema_version": CHANGE_SPEC_SCHEMA_VERSION,
"scopes": [scope],
"queries": [
{
"check_id": check_id,
"scope_ids": [scope["scope_id"]],
"scope_roles": [],
"required_deltas": [],
"forbidden_deltas": deltas,
}
],
"bindings": bindings,
"executors": executors,
"violation_short_circuit_certified": violation_short_circuit_certified,
"semantic_pass_complete": semantic_pass_complete,
"semantic_coverage": {
"complete": semantic_pass_complete,
"reasons": semantic_coverage_reasons,
"basis": "reviewed_parameter_clauses_to_shared_delta_ontology_v1",
},
"fallback": {
"executor": "vlm_change_audit_v1",
"enabled": False,
"prompt_profile": prompt_profile,
},
"provenance": {
"compiler": "pvr_eval.contracts.change_spec.compile_change_spec",
"policy": "contract_facts_to_shared_typed_deltas_v1",
},
}
def validate_change_spec(value: Mapping[str, Any]) -> tuple[str, ...]:
reasons: list[str] = []
if value.get("schema_version") != CHANGE_SPEC_SCHEMA_VERSION:
reasons.append("unsupported_change_spec_schema")
scopes = value.get("scopes")
queries = value.get("queries")
executors = value.get("executors")
if not isinstance(scopes, list) or not scopes:
reasons.append("change_spec_has_no_scopes")
scopes = []
if not isinstance(queries, list) or not queries:
reasons.append("change_spec_has_no_queries")
queries = []
if not isinstance(executors, list) or not executors:
reasons.append("change_spec_has_no_executors")
scope_ids: set[str] = set()
for scope in scopes:
if not isinstance(scope, Mapping):
reasons.append("change_scope_is_not_object")
continue
scope_id = str(scope.get("scope_id") or "")
if not scope_id or scope_id in scope_ids:
reasons.append("change_scope_id_missing_or_duplicate")
scope_ids.add(scope_id)
if scope.get("kind") not in SCOPE_KINDS:
reasons.append("change_scope_kind_invalid:" + scope_id)
if scope.get("role") not in SCOPE_ROLES:
reasons.append("change_scope_role_invalid:" + scope_id)
for query in queries:
if not isinstance(query, Mapping):
reasons.append("change_query_is_not_object")
continue
referenced = {str(item) for item in query.get("scope_ids", [])}
if not referenced or not referenced.issubset(scope_ids):
reasons.append("change_query_scope_invalid:" + str(query.get("check_id") or ""))
deltas = set(query.get("required_deltas", [])) | set(query.get("forbidden_deltas", []))
invalid = sorted(str(item) for item in deltas if item not in DELTA_TYPES)
if not deltas or invalid:
reasons.append("change_query_delta_invalid:" + ",".join(invalid))
fallback = value.get("fallback")
if not isinstance(fallback, Mapping):
reasons.append("change_spec_fallback_missing")
elif fallback.get("enabled") not in {True, False}:
reasons.append("change_spec_fallback_enabled_invalid")
return tuple(dict.fromkeys(reasons))
__all__ = [
"CHANGE_SPEC_SCHEMA_VERSION",
"FACT_DELTA_TYPES",
"SUPPORTED_CHANGE_FAMILIES",
"compile_change_spec",
"validate_change_spec",
]