solveedit_benchmark_2728 / code /src /pvr_eval /agent /executable_predicate.py
wenjieshu's picture
Add files using upload-large-folder tool
b8ea052 verified
Raw History Blame Contribute Delete
176 kB
"""Executable visual predicates embedded in PVR evaluation contracts. Natural-language questions and criteria remain useful for review, but they are not an execution interface. This module compiles one reviewed check into a small, validated program that names its subjects, tool operations, derived regions, state machine, and deterministic decision table. Only explicitly supported predicate families are executable. Everything else is represented as ``blocked_uncompiled`` so downstream code cannot fall back to guessing tools from prose. """ from __future__ import annotations from copy import deepcopy from dataclasses import dataclass import re from typing import Any, Mapping, Sequence from pvr_eval.contracts.metric_profiles import ( ARTICULATED_ENTITY_PRESERVATION_EXECUTOR_VERSION, ARTICULATED_ENTITY_PRESERVATION_PROFILE, REPEATED_COMPONENT_GROUP_IDENTITY_EXECUTOR_VERSION, REPEATED_COMPONENT_GROUP_IDENTITY_PROFILE, SHELF_SOURCE_GROUP_CLEARANCE_PROFILE, shelf_source_group_clearance_profile_parameters, ) from pvr_eval.agent.source_instance_selector import ( ANCHOR_RELATIVE_SOURCE_INSTANCE_PROFILE, SUPPORTED_ANCHOR_PARTS, is_relational_identity_text, ) from pvr_eval.agent.source_annotation_masks import ( VERIFIED_PROTECTED_SOURCE_MASK_PROFILE, VERIFIED_SOURCE_MASK_CAPABILITY_VERSION, VERIFIED_SOURCE_MASK_PROFILE, ) EXECUTABLE_PREDICATE_SCHEMA_VERSION = "pvr.executable_predicate.v1" REGISTERED_METRIC_OPERATOR_VERSION = "pvr.contract_metric.v7" SMALL_ANIMAL_GEOMETRY_EXECUTOR_VERSION = "pvr.small_animal_set_geometry.v5" SOURCE_REGION_CLEARANCE_RULES = frozenset( { "counted_pair_removal", "paired_zoned_instance_removal", "colored_container_visibility_count", "source_zone_vacancy", "zoned_instance_absence_with_residual_test", "small_zoned_instance_absence_with_residual_test", } ) SURFACE_RESIDUAL_INVENTORY_RULES = frozenset( { "desk_clutter_residual_count", "tabletop_remaining_item_count", } ) DESTINATION_MEMBERSHIP_RULES = frozenset( { "named_supply_storage_coverage", "single_object_destination_containment", "counted_objects_destination_containment", "relocated_object_in_air_zone", "categorized_group_completeness", "dual_category_grouping", "document_group_completeness", "paired_zone_containment", "two_object_single_zone_containment", "counted_container_membership", "required_set_container_membership", "paired_container_membership", "remote_pair_on_table_surface", "paired_relocation_beside_dispenser", "same_unit_different_compartment_placement", } ) RELOCATION_TRANSITION_RULES = frozenset({"source_vacated_and_destination_valid"}) SOURCE_REGION_RESTORATION_RULES = frozenset({"vacated_source_with_background_fill"}) SOURCE_DISPLACEMENT_RULES = frozenset( { "per_instance_source_zone_displacement", "multi_instance_source_zone_displacement", "bird_instance_displacement_and_shoulder_clearance", } ) INSTANCE_CLUSTER_GROUPING_RULES = frozenset({"small_animal_cluster_component_count"}) PROTECTED_SET_EXCLUSION_RULES = frozenset({"protected_zone_exclusion_count"}) CLUSTER_SUBJECT_SEPARATION_RULES = frozenset({"cluster_protected_subject_gap"}) CROSS_IMAGE_INVENTORY_RULES = frozenset( { "original_inventory_visible_match", "expected_species_count_preservation", "no_excess_or_novel_animal_instances", "identity_count_conservation_no_excess", "all_input_targets_matched", "source_instance_conservation", "object_group_survival", "all_named_entities_preserved", } ) OCR_TEXT_RULES = frozenset({"all_text_rois_preserved", "no_new_explanatory_text"}) FIXED_LOCATION_PRESERVATION_RULES = frozenset( { "multi_instance_strict_preservation", "character_integrity_preservation", "person_region_preservation", } ) # These region backends need a typed materializer of their own. Until that # exists, the predicate compiler must fail closed instead of silently feeding # an OCR label, an existing-zone name, or a shelf-grid instruction to DINO. NON_DETECTOR_REGION_METHODS = frozenset({"ocr_layout", "existing_zone", "grid_parser", "none"}) LABELED_COLOR_ZONE_IDS = frozenset( {"zone_a_floor", "zone_b_floor", "zone_c_floor", "water_bin", "snacks_bin", "teacher_bin"} ) PREDICATE_OPERATION_KINDS = frozenset( { "object_detection", "mask_refinement", "instance_matching", "source_instance_selection", "source_state_classification", "region_resolution", "spatial_geometry", "counting", "ocr", "image_registration", "change_analysis", "visual_attribute", "pose_estimation", "local_correspondence", "crop_classification", "state_parsing", "structured_check", "predicate_decision", } ) # These rules have a deterministic, case-parameterized parser path. They are # intentionally separate from the generic state parser: a dial, parking bay, # or flowchart checkbox is not an interchangeable coloured grid cell. The # terminal structured checker consumes the complete reviewed decision rule # and returns pass/partial/fail/unknown evidence for exactly one atomic check. STRUCTURED_CHECK_RULES = frozenset( { # Gauge and watch. "angular_sector_containment", "source_corridor_vacancy", "pivot_shaft_connectivity", "needle_instance_preservation", "dial_graphics_preservation", "registered_invariant_region_preservation", "needle_shape_integrity", "expected_date_digit_transition", "clockwise_hour_hand_delta", "minute_hand_angle_invariance", "watch_structure_relocation_violation", "non_target_component_integrity_violation", # Kanban board. "source_instance_vacancy", "all_source_instances_in_destination", "card_text_identity_preservation", "identity_loss_penalty", "structural_invariant_preservation", "unrequested_annotation_penalty", # Visual pill organizer. "exclusive_color_zone_containment", "translucent_lid_depth_plausibility", "multi_entity_integrity", "protected_roi_exact_preservation", "paired_text_legibility_preservation", "count_conservation_and_structure_invariance", # Board-game movement. "target_cell_mask_containment", "source_cell_vacated", "ordered_dotted_route_match", "two_instance_cell_preservation", "card_content_preservation", "grid_and_labels_intact", "tray_and_contents_preserved", "exact_board_instance_count", # Parking assignment. "assigned_vehicle_slot_predicate", "accessible_vehicle_slot_predicate", "any_assigned_vehicle_boundary_violation", "audit_only_required_identity_count", "occlusion_aware_marking_preservation", # Laundry sorting. "required_pair_in_target_zone", "all_sources_vacated_no_forbidden_zone_instances", "all_required_text_and_icons_intact", "all_item_attributes_preserved", "invariant_region_preserved", # Medication organizer. "seven_slot_exact_pair_count", "seven_slot_exact_single_count", "exact_container_count_with_purity", "all_instances_intact_and_stationary", "registered_card_preservation", "all_required_labels_legible_and_aligned", "allowed_type_by_row", "invariant_background_preservation", # Fluid network. "fluid_level_drop", "required_tube_network_fill", "paired_lower_path_and_container_fill", "paired_level_equality", "forbidden_blue_fluid_overlap", "multi_handle_pose_preservation", "ordered_label_preservation", "invariant_structure_integrity", # Flowchart execution. "single_checkbox_mark_state", "two_checkbox_completion_count", "all_forbidden_checkboxes_empty", "flowchart_structure_preservation", "inputs_card_integrity", "multi_region_background_preservation", } ) @dataclass(frozen=True) class PredicateValidation: valid: bool reasons: tuple[str, ...] def _mapping(value: Any) -> dict[str, Any]: return deepcopy(dict(value)) if isinstance(value, Mapping) else {} def _list(value: Any) -> list[Any]: return list(value) if isinstance(value, (list, tuple)) else [] def _dedupe_text(values: Sequence[Any]) -> list[str]: result: list[str] = [] seen: set[str] = set() for raw in values: value = str(raw or "").strip() if value and value not in seen: result.append(value) seen.add(value) return result def _verified_source_mask_profile(annotations: Sequence[Mapping[str, Any]]) -> str: """Require real segmentation whenever a reviewed bbox owns source identity.""" return VERIFIED_SOURCE_MASK_PROFILE if annotations else "" def _subjects(params: Mapping[str, Any]) -> list[str]: # ``object_queries`` contains the reviewed, instance-level identities used # by the detector and by ordered subject->zone bindings. Older contracts # may also retain short ``objects``/``labels`` strings as search aliases. # Appending those aliases creates fictitious extra inventory members (for # example two reviewed backpacks become four subjects), so the reviewed # queries are authoritative whenever they are present. object_queries = _dedupe_text(_list(params.get("object_queries"))) if object_queries: return object_queries values: list[Any] = [] for key in ("required_instances", "labels", "objects"): values.extend(_list(params.get(key))) for key in ("object", "label"): if params.get(key): values.append(params[key]) return _dedupe_text(values) def _planned_regions(params: Mapping[str, Any]) -> list[dict[str, Any]]: return [ deepcopy(dict(item)) for item in _list(params.get("planned_regions")) if isinstance(item, Mapping) ] def _typed_region( region_id: str, *, semantic_role: str, image_roles: Sequence[str], queries: Sequence[str], geometry_policy: str = "mask_or_polygon_required", cardinality: str = "one", ) -> dict[str, Any]: clean_queries = _dedupe_text(queries) return { "region_id": region_id, "semantic_role": semantic_role, "image_roles": list(image_roles), "source_image": "both" if set(image_roles) == {"input", "pred"} else next(iter(image_roles), "pred"), "proposal_method": "grounding_dino_box", "query_or_rule": " | ".join(clean_queries), "materializer": { "kind": "open_vocabulary_detector", "queries": clean_queries, "selection_policy": "dino_first_top1_per_query", "cardinality": cardinality, }, "geometry_policy": geometry_policy, } def _region_id_matching(params: Mapping[str, Any], tokens: Sequence[str], default: str) -> str: candidates: list[tuple[int, str]] = [] for item in _planned_regions(params): region_id = str(item.get("region_id") or item.get("id") or "") lowered = region_id.lower() score = sum(token in lowered for token in tokens) if score: candidates.append((score, region_id)) return max(candidates, default=(0, default))[1] def _region_roles(value: Any) -> list[str]: text = str(value or "").lower() if text in {"both", "input_output", "input+output"}: return ["input", "pred"] if text in {"input", "source", "before"}: return ["input"] return ["pred"] def _generic_typed_regions(params: Mapping[str, Any]) -> list[dict[str, Any]]: regions: list[dict[str, Any]] = [] for index, raw in enumerate(_planned_regions(params)): region_id = str(raw.get("region_id") or raw.get("id") or f"region_{index}").strip() if not region_id: continue description = str(raw.get("description") or "").strip() id_query = region_id.replace("_", " ") queries = [id_query] if description and len(description.split()) <= 14: queries.append(description) lowered = region_id.lower() semantic_role = "context_region" if any(token in lowered for token in ("destination", "target", "patio", "shelf", "bin", "table_top", "tabletop", "credenza", "air_zone")): semantic_role = "valid_destination_set" elif any(token in lowered for token in ("source", "original", "before", "vacancy", "protected")): semantic_role = "source_region" elif any(token in lowered for token in ("forbidden", "floor", "exclusion")): semantic_role = "forbidden_region" typed = _typed_region( region_id, semantic_role=semantic_role, image_roles=_region_roles(raw.get("source_image")), queries=queries, cardinality="one_or_more" if any(token in lowered for token in ("zones", "regions", "surfaces", "instances")) else "one", ) for key in ("bbox", "bbox_xyxy", "polygon", "polygon_xy", "encoded_mask", "geometry_type"): if key in raw: typed[key] = deepcopy(raw[key]) regions.append(typed) return regions def _subject_specs(subjects: Sequence[str], source_anchor_query: str) -> list[dict[str, str]]: anchor = str(source_anchor_query or "").strip() result: list[dict[str, str]] = [] for index, identity in enumerate(subjects): subject_id = re.sub(r"[^a-z0-9]+", "_", identity.lower()).strip("_") or f"subject_{index}" result.append( { "id": subject_id, "identity_query": identity, "input_query": f"{identity} {anchor}".strip(), "output_query": identity, } ) return result def _subject_group_spec( aliases: Sequence[str], *, expected_count: int = 1, source_anchor_query: str = "", group_id: str = "", ) -> dict[str, Any]: """Encode one semantic inventory unit separately from its query aliases.""" clean_aliases = _dedupe_text(aliases) primary = clean_aliases[0] if clean_aliases else group_id or "subject" subject_id = group_id or re.sub(r"[^a-z0-9]+", "_", primary.lower()).strip("_") or "subject" anchor = str(source_anchor_query or "").strip() return { "id": subject_id, "identity_query": primary, "aliases": clean_aliases, "input_query": f"{primary} {anchor}".strip(), "output_query": primary, "input_queries": [f"{alias} {anchor}".strip() for alias in clean_aliases], "output_queries": clean_aliases, "expected_count": max(1, int(expected_count)), } def _is_secondary_context_query(query: str, primary: str) -> bool: """Reject obvious support/anchor queries accidentally mixed with targets.""" query_tokens = set(re.findall(r"[a-z0-9]+", query.lower())) primary_tokens = set(re.findall(r"[a-z0-9]+", primary.lower())) target_nouns = { "bird", "binder", "binders", "printer", "wrapper", "dumbbell", "dumbbells", "cup", "bottle", "shaker", "container", "containers", "bag", "napkin", "tissue", "table", "chair", "backpack", "remote", "cart", "kettle", "microwave", "fox", "raccoon", "squirrel", "deer", "fawn", } primary_targets = primary_tokens & target_nouns context_terms = { "robot", "shoulder", "ground", "floor", "trunk", "branch", "wall", "walkway", "dispenser", "shelf", "shelving", "tray", "table", } return bool(query_tokens & context_terms) and bool(primary_targets) and not bool(query_tokens & primary_targets) def _source_subject_groups( subjects: Sequence[str], *, source_rule_type: str, expected_count: int, raw: Mapping[str, Any], ) -> list[dict[str, Any]]: queries = _dedupe_text(subjects) if not queries: return [] anchor = str(raw.get("source_anchor_query") or "") if source_rule_type == "colored_container_visibility_count" and len(queries) >= expected_count: return [ _subject_group_spec((query,), expected_count=1, source_anchor_query=anchor) for query in queries[:expected_count] ] aliases = [queries[0], *[ query for query in queries[1:] if not _is_secondary_context_query(query, queries[0]) ]] return [ _subject_group_spec( aliases, expected_count=expected_count, source_anchor_query=anchor, group_id="source_target_inventory", ) ] def _destination_subject_groups( subjects: Sequence[str], *, source_rule_type: str, required_count: int, ) -> list[dict[str, Any]]: queries = _dedupe_text(subjects) if not queries: return [] if source_rule_type in {"single_object_destination_containment", "counted_objects_destination_containment"}: aliases = [queries[0], *[ query for query in queries[1:] if not _is_secondary_context_query(query, queries[0]) ]] return [ _subject_group_spec( aliases, expected_count=max(1, required_count), group_id="destination_target_inventory", ) ] if source_rule_type == "relocated_object_in_air_zone": aliases = [queries[0], *[ query for query in queries[1:] if not _is_secondary_context_query(query, queries[0]) ]] return [_subject_group_spec(aliases, expected_count=1, group_id="relocated_target")] if source_rule_type in { "remote_pair_on_table_surface", "paired_relocation_beside_dispenser", "same_unit_different_compartment_placement", }: target_queries = [queries[0], *[ query for query in queries[1:] if not _is_secondary_context_query(query, queries[0]) ]] return [_subject_group_spec((query,), expected_count=1) for query in target_queries] return [_subject_group_spec((query,), expected_count=1) for query in queries] def _public_subject_groups(subjects: Sequence[Mapping[str, Any]]) -> list[dict[str, Any]]: result: list[dict[str, Any]] = [] for item in subjects: public = { "id": str(item.get("id") or ""), "aliases": _dedupe_text(item.get("aliases", [])), "expected_count": max(1, int(item.get("expected_count") or 1)), } if str(item.get("spatial_selector") or ""): public["spatial_selector"] = str(item["spatial_selector"]) result.append(public) return result def _positive_int(parameters: Mapping[str, Any], *keys: str) -> tuple[int, str]: for key in keys: value = parameters.get(key) if isinstance(value, (int, float)) and int(value) > 0: return int(value), key return 0, "" def _number(parameters: Mapping[str, Any], keys: Sequence[str], default: float) -> tuple[float, str]: for key in keys: value = parameters.get(key) if isinstance(value, (int, float)): return float(value), key return float(default), "" def _source_scope_conflicts(decision: Mapping[str, Any]) -> list[str]: pass_text = str(decision.get("pass_condition") or "").lower() partial_text = str(decision.get("partial_condition") or "").lower() reasons: list[str] = [] if re.search( r"(?:anywhere|entire (?:image|scene|frame)|whole (?:image|scene|frame)|全图|整张图|任何位置)", pass_text, ): reasons.append("source_scope_conflicts_with_global_absence_pass") if re.search(r"(?:elsewhere|other (?:area|location)|其他位置)", partial_text) and not re.search( r"(?:do not count|does not count|not count|不计|不算)", partial_text ): reasons.append("source_scope_conflicts_with_elsewhere_partial") return reasons def _operation( operation_id: str, kind: str, tool_family: str, image_roles: Sequence[str], *, depends_on: Sequence[str] = (), optional: bool = False, parameters: Mapping[str, Any] | None = None, produces: Sequence[str] = (), ) -> dict[str, Any]: return { "id": operation_id, "kind": kind, "tool_family": tool_family, "image_roles": list(image_roles), "depends_on": list(depends_on), "optional": bool(optional), "parameters": deepcopy(dict(parameters or {})), "produces": list(produces), } def _blocked( *, check_id: str, source_rule_type: str, family: str, subjects: Sequence[str], reasons: Sequence[str], provenance: Mapping[str, Any] | None = None, status: str = "blocked_uncompiled", ) -> dict[str, Any]: return { "schema_version": EXECUTABLE_PREDICATE_SCHEMA_VERSION, "check_id": check_id, "status": status, "family": family, "source_rule_type": source_rule_type, "subjects": list(subjects), "regions": [], "operations": [], "state_schema": {}, "decision": {}, "parameters": {}, "unmapped_contract_parameters": [], "reasons": list(dict.fromkeys(str(item) for item in reasons if item)), "provenance": deepcopy(dict(provenance or {})), } def _compile_surface_residual_inventory( *, check_id: str, source_rule_type: str, subjects: Sequence[str], params: Mapping[str, Any], decision: Mapping[str, Any], provenance: Mapping[str, Any], ) -> dict[str, Any]: raw = _mapping(decision.get("parameters")) if source_rule_type == "desk_clutter_residual_count": threshold, threshold_key = _number(raw, ("desktop_containment_threshold",), 0.5) region_id = _region_id_matching(params, ("desktop", "desk_surface", "main_desk"), "main_desktop_surface") region_queries = ("horizontal top surface of the main desk", "main desktop surface") normalized = { "surface_region_id": region_id, "surface_containment_threshold": threshold, "support_contact_tolerance_pixels": int(raw.get("support_contact_tolerance_pixels", 8)), "count_coherent_book_stack_as": int(raw.get("count_coherent_book_stack_as", 1)), "exclude_animate_subjects": bool(raw.get("exclude_animate_cat", True)), "minimum_match_confidence": float(raw.get("minimum_match_confidence", 0.55)), "minimum_detection_confidence": float(raw.get("minimum_detector_confidence", 0.15)), "geometry_policy": "mask_or_polygon_required", } consumed = { threshold_key, "support_contact_tolerance_pixels", "count_coherent_book_stack_as", "exclude_animate_cat", "minimum_match_confidence", "minimum_detector_confidence", } decision_table = { "pass": {"residual_count": 0, "unresolved_count": 0}, "partial": {"residual_count": {"minimum": 1, "maximum": 2}, "residual_fraction": {"less_than": 0.5}, "unresolved_count": 0}, "fail": {"any": [{"residual_count": {"minimum": 3}}, {"residual_fraction": {"minimum": 0.5}}], "unresolved_count": 0}, "unknown": {"unresolved_count": {"minimum": 1}}, } else: threshold, threshold_key = _number(raw, ("zone_containment_threshold", "table_overlap_threshold"), 0.5) region_id = _region_id_matching(params, ("conference_table", "tabletop", "table_surface"), "tabletop_surface") region_queries = ("horizontal top surface of the conference table", "conference table tabletop") normalized = { "surface_region_id": region_id, "surface_containment_threshold": threshold, "minimum_detection_confidence": float(raw.get("minimum_detector_confidence", raw.get("output_detection_confidence_fail", 0.15))), "pass_max_remaining": int(raw.get("pass_max_remaining", 0)), "partial_min_remaining": int(raw.get("partial_min_remaining", 1)), "partial_max_remaining": int(raw.get("partial_max_remaining", 2)), "fail_min_remaining": int(raw.get("fail_min_remaining", int(raw.get("partial_max_remaining", 2)) + 1)), "exclude_furniture_and_built_in_features": bool(raw.get("exclude_furniture_and_built_in_features", True)), "geometry_policy": "mask_or_polygon_required", } consumed = { threshold_key, "minimum_detector_confidence", "output_detection_confidence_fail", "pass_max_remaining", "partial_min_remaining", "partial_max_remaining", "fail_min_remaining", "exclude_furniture_and_built_in_features", "support_surface_area_ratio", } decision_table = { "pass": {"residual_count": {"maximum": normalized["pass_max_remaining"]}, "unresolved_count": 0}, "partial": {"residual_count": {"minimum": normalized["partial_min_remaining"], "maximum": normalized["partial_max_remaining"]}, "unresolved_count": 0}, "fail": {"residual_count": {"minimum": normalized["fail_min_remaining"]}, "unresolved_count": 0}, "unknown": {"unresolved_count": {"minimum": 1}}, } unmapped = sorted(set(raw) - {key for key in consumed if key}) reasons = [] if not check_id: reasons.append("missing_check_id") if not subjects: reasons.append("missing_subject_queries") if unmapped: reasons.append("unmapped_contract_parameters") region = _typed_region( region_id, semantic_role="support_surface", image_roles=("input", "pred"), queries=region_queries, ) predicate = { "schema_version": EXECUTABLE_PREDICATE_SCHEMA_VERSION, "check_id": check_id, "status": "executable" if not reasons else "blocked_uncompiled", "family": "surface_residual_inventory", "source_rule_type": source_rule_type, "subjects": _subject_specs(subjects, ""), "regions": [region], "operations": [ _operation("detect_input_inventory", "object_detection", "detector", ("input",), produces=("input_inventory_boxes",)), _operation("refine_input_inventory", "mask_refinement", "segmenter", ("input",), depends_on=("detect_input_inventory",), produces=("input_inventory_masks",)), _operation("detect_output_inventory", "object_detection", "detector", ("pred",), produces=("output_inventory_boxes", "detector_search_coverage")), _operation("refine_output_inventory", "mask_refinement", "segmenter", ("pred",), depends_on=("detect_output_inventory",), produces=("output_inventory_masks",)), _operation("materialize_surface", "region_resolution", "region_proposer", ("pred",), produces=("surface_region_box",)), _operation("refine_surface", "spatial_geometry", "segmenter", ("pred",), depends_on=("materialize_surface",), produces=("surface_region_mask",)), _operation("match_inventory", "instance_matching", "matcher", ("input", "pred"), depends_on=("refine_input_inventory", "refine_output_inventory"), optional=True, produces=("instance_matches",)), _operation("count_surface_residuals", "counting", "predicate_interpreter", ("input", "pred"), depends_on=("refine_output_inventory", "refine_surface"), produces=("per_instance_surface_facts", "residual_count")), _operation("decide", "predicate_decision", "predicate_interpreter", ("input", "pred"), depends_on=("count_surface_residuals",), produces=("check_result",)), ], "state_schema": { "unit": "input_inventory_instance", "states": ["on_surface", "off_surface", "not_visible_after_complete_search", "unknown"], "facts": ["mask_containment", "support_contact", "match_confidence"], }, "decision": decision_table, "parameters": normalized, "parameter_provenance": {"surface_containment_threshold": threshold_key or "default:0.5"}, "unmapped_contract_parameters": unmapped, "reasons": reasons, "provenance": deepcopy(dict(provenance)), } return predicate def _compile_destination_membership( *, check_id: str, source_rule_type: str, subjects: Sequence[str], params: Mapping[str, Any], decision: Mapping[str, Any], provenance: Mapping[str, Any], ) -> dict[str, Any]: raw = _mapping(decision.get("parameters")) required = _dedupe_text(raw.get("required_components", [])) if not required: required = list(subjects) expected_counts = raw.get("expected_counts") if isinstance(raw.get("expected_counts"), Mapping) else {} required_count, required_count_key = _positive_int( raw, "required_count", "expected_total_count", "required_identity_count", "expected_components", ) if not required_count and expected_counts: required_count, required_count_key = sum(int(value) for value in expected_counts.values()), "expected_counts" if not required_count and raw.get("required_instances"): required_count, required_count_key = len(_list(raw.get("required_instances"))), "required_instances" if not required_count: required_count = len(required) required_count_key = "derived:subjects" subject_groups = _destination_subject_groups( subjects, source_rule_type=source_rule_type, required_count=required_count, ) # Detector queries may also name support objects or exclusion geometry. # The executable inventory is owned by the typed subject groups, not by # the raw query list. Re-derive both the public roster and count after # role filtering so a table, tray, robot, or ground region cannot become # a fictitious required target instance. required = [ str(group.get("identity_query") or group.get("id") or "") for group in subject_groups if str(group.get("identity_query") or group.get("id") or "").strip() ] required_count = sum(max(1, int(group.get("expected_count") or 1)) for group in subject_groups) required_count_key = "derived:typed_subject_groups" threshold, threshold_key = _number( raw, ( "zone_containment_threshold", "predominant_visible_mask_containment_min", "minimum_mask_containment", "minimum_destination_containment", "pass_min_containment", "credenza_containment_threshold", "minimum_air_zone_containment", "pass_patio_footprint_fraction", "pass_patio_footprint_fraction_per_chair", ), 0.5, ) partial_threshold, partial_key = _number( raw, ("minimum_partial_intersection_fraction", "partial_min_containment"), min(0.25, threshold), ) minimum_confidence, minimum_confidence_key = _number( raw, ( "minimum_instance_confidence", "minimum_bird_detection_confidence", "instance_match_min_score", "minimum_identity_similarity", "minimum_match_confidence", ), 0.45, ) identity_required = source_rule_type in { "named_supply_storage_coverage", "required_set_container_membership", "paired_relocation_beside_dispenser", "same_unit_different_compartment_placement", "relocated_object_in_air_zone", } or bool(raw.get("match_to_input_instances") or raw.get("visible_match_required")) explicit_white_furniture = source_rule_type in { "single_object_destination_containment", "counted_objects_destination_containment", } and any( "white" in str(subject).lower() and any(noun in str(subject).lower() for noun in ("chair", "table")) for subject in subjects ) classification_labels: list[str] = [] if explicit_white_furniture: classification_labels.extend(str(subject) for subject in subjects) has_chair_subject = any("chair" in str(subject).lower() for subject in subjects) if has_chair_subject: classification_labels.append("brown wooden dining chair") classification_labels.append("white round patio table") elif any("table" in str(subject).lower() for subject in subjects): classification_labels.append("brown wooden outdoor table") classification_labels.extend(("white patio chair", "brown wooden dining chair")) classification_labels.append("other object") classification_proposal_queries: list[str] = [] if explicit_white_furniture: if any("chair" in str(subject).lower() for subject in subjects): classification_proposal_queries = ["chair", "outdoor chair"] else: classification_proposal_queries = ["table", "outdoor table"] normalized = { "required_components": required, "required_count": required_count, "subject_groups": _public_subject_groups(subject_groups), "zone_containment_threshold": threshold, "partial_containment_threshold": partial_threshold, "support_contact_tolerance_pixels": int(raw.get("support_contact_tolerance_pixels", 8)), "visible_match_required": identity_required, "minimum_match_confidence": minimum_confidence, "minimum_detection_confidence": minimum_confidence, "require_distinct_instances": bool( raw.get("require_distinct_instances", raw.get("require_distinct_backpack_instances", True)) ), "deduplicate_iou_threshold": float(raw.get("deduplicate_iou_threshold", 0.6)), "maximum_forbidden_support_points": int(raw.get("maximum_grass_support_points_for_pass", 0)), "geometry_policy": "per_zone_mask_or_polygon_required", "valid_zone_aggregation": "any_member_zone", "forbidden_zone_policy": "declared_forbidden_regions", "source_rule_semantics": source_rule_type, "center_or_support_point_required": bool(raw.get("center_or_support_point_must_be_inside")), "accept_center_inside_when_occluded": bool( raw.get("accept_center_inside_bin_interior_when_lower_object_is_occluded_by_bin_wall") or raw.get("accept_center_inside_bin_interior_when_occluded_by_bin_wall") ), "zone_boundary_tolerance_pixels": int(raw.get("zone_boundary_tolerance_px", 0)), "require_crop_classification": explicit_white_furniture, "classification_labels": _dedupe_text(classification_labels), "classification_proposal_queries": classification_proposal_queries, # Proposal recall and final instance acceptance are separate gates. # A moderate detector proposal can become reliable after closed-set # classification and destination geometry; filtering it at the final # instance-confidence threshold would discard the evidence too early. "classification_proposal_minimum_score": 0.15, "classified_candidate_minimum_score": 0.15, "classification_use_segmenter_proposals": explicit_white_furniture, "classification_proposal_zone_ids": [], "classification_segmenter_min_area_fraction": 0.00008, "classification_segmenter_max_area_fraction": 0.06, "classification_segmenter_max_proposals": 128, "classification_minimum_margin": 0.025, "classification_minimum_probability": 0.28, } supported_by_rule = { "named_supply_storage_coverage": { "required_components", "zone_containment_threshold", "support_contact_tolerance_pixels", "visible_match_required", "minimum_match_confidence", }, "single_object_destination_containment": { "required_count", "pass_patio_footprint_fraction", "minimum_partial_intersection_fraction", "maximum_grass_support_points_for_pass", "minimum_instance_confidence", }, "counted_objects_destination_containment": { "required_count", "pass_patio_footprint_fraction_per_chair", "maximum_grass_support_points_for_pass", "minimum_instance_confidence", "deduplicate_iou_threshold", }, "paired_zone_containment": { "center_or_support_point_must_be_inside", "predominant_visible_mask_containment_min", "require_distinct_backpack_instances", "zone_boundary_tolerance_px", }, "two_object_single_zone_containment": { "center_or_support_point_must_be_inside", "predominant_visible_mask_containment_min", "require_distinct_instances", "zone_boundary_tolerance_px", }, "counted_container_membership": { "accept_center_inside_bin_interior_when_lower_object_is_occluded_by_bin_wall", "expected_total_count", "predominant_visible_mask_containment_min", "require_no_duplicate_assignment", }, "required_set_container_membership": { "accept_center_inside_bin_interior_when_occluded_by_bin_wall", "match_to_input_instances", "predominant_visible_mask_containment_min", "require_distinct_instances", "required_identity_count", }, "paired_container_membership": { "accept_center_inside_bin_interior_when_occluded_by_bin_wall", "predominant_visible_mask_containment_min", "require_distinct_appliance_instances", }, } consumed = supported_by_rule.get(source_rule_type, set()) unmapped = sorted(set(raw) - {key for key in consumed if key}) reasons = [] if not check_id: reasons.append("missing_check_id") if not subjects: reasons.append("missing_subject_queries") if not required: reasons.append("required_components_not_compiled") if unmapped: reasons.append("unmapped_contract_parameters") regions: list[dict[str, Any]] = [] instance_tokens = ("instance", "instances", "source", "candidate", "relocated_binders", "tray") forbidden_tokens = ("floor", "grass", "walkway", "forbidden", "negative") valid_tokens = ( "destination", "target", "patio", "storage", "shelf", "ledge", "window", "credenza", "airborne", "air_zone", "table_top", "tabletop", "coffee_table_top", "corner", "bin", "zone_a", "zone_b", "zone_c", "compartment", ) for index, source_region in enumerate(_planned_regions(params)): region_id = str(source_region.get("region_id") or source_region.get("id") or f"region_{index}") lowered = region_id.lower() if any(token in lowered for token in instance_tokens): continue if region_id in LABELED_COLOR_ZONE_IDS: semantic_role = "valid_destination_set" elif any(token in lowered for token in forbidden_tokens): semantic_role = "forbidden_destination" elif any(token in lowered for token in valid_tokens): semantic_role = "valid_destination_set" else: continue method = str(source_region.get("proposal_method") or "grounding_dino_box").lower() has_explicit_geometry = any( key in source_region for key in ("bbox", "bbox_xyxy", "polygon", "polygon_xy", "encoded_mask") ) if method in {"ocr_layout", "existing_zone"} and region_id in LABELED_COLOR_ZONE_IDS: region = _typed_region( region_id, semantic_role=semantic_role, image_roles=("pred",), queries=(), ) region["proposal_method"] = method region["materializer"] = { "kind": "input_ocr_color_zone", "region_id": region_id, "backend": "input_ocr_hsv_connected_component_v1", } regions.append(region) continue if method in NON_DETECTOR_REGION_METHODS and not has_explicit_geometry: reasons.append(f"region_materializer_not_implemented:{region_id}:{method}") continue authored_detector_queries = _dedupe_text( _list(source_region.get("detector_queries")) + _list(source_region.get("detector_query")) ) if authored_detector_queries: region_queries = tuple(authored_detector_queries) elif "patio" in lowered: region_queries = ("stone paved patio",) elif "valid_storage" in lowered: region_queries = ("window ledge", "cabinet shelf", "visible cabinet compartment") elif "floor" in lowered: region_queries = ("room floor",) elif "airborne" in lowered or "air_zone" in lowered: region_queries = ("open sky area",) elif "coffee_table_top" in lowered: region_queries = ("horizontal top surface of the coffee table",) elif "credenza" in lowered: region_queries = ("wooden credenza",) else: region_queries = (region_id.replace("_", " "),) # Preserve an explicitly reviewed cross-image scene anchor. Stable # destination supports such as a patio are part of the scene layout: # the input proposal constrains the output proposal, while the object # itself is still detected and scored only in the output. The old # compiler forced every destination region to ``pred`` and silently # discarded ``source_image: both`` from the contract. region_roles = ( tuple(_region_roles(source_region.get("source_image"))) if "patio" in lowered else ("pred",) ) region = _typed_region( region_id, semantic_role=semantic_role, image_roles=region_roles, queries=region_queries, cardinality="one_or_more" if source_rule_type == "named_supply_storage_coverage" and semantic_role == "valid_destination_set" else "one", ) # Once this compiler has lowered a legacy VLM proposal to an explicit # detector query, runtime provenance must name the tool that is # actually called. Keep the reviewed legacy method separately instead # of claiming that a VLM produced a DINO box. region["source_proposal_method"] = method region["proposal_method"] = ( "grounding_dino_box" if method == "vlm_region_box" else method ) for key in ("bbox", "bbox_xyxy", "polygon", "polygon_xy", "encoded_mask", "geometry_type"): if key in source_region: region[key] = deepcopy(source_region[key]) regions.append(region) if source_rule_type == "named_supply_storage_coverage": # The reviewed question explicitly forbids leaving supplies on the # central desk. This independent mask is deliberately separate from # the storage-set masks; never replace either with a union bbox. regions.append( _typed_region( "main_desktop_surface", semantic_role="forbidden_destination", image_roles=("pred",), queries=("horizontal top surface of the main desk",), ) ) if not any(item.get("semantic_role") == "valid_destination_set" for item in regions): reasons.append("valid_destination_region_not_compiled") normalized["valid_zone_ids"] = [ str(item["region_id"]) for item in regions if item.get("semantic_role") == "valid_destination_set" ] if explicit_white_furniture: normalized["classification_proposal_zone_ids"] = list(normalized["valid_zone_ids"]) normalized["forbidden_zone_ids"] = [ str(item["region_id"]) for item in regions if item.get("semantic_role") == "forbidden_destination" ] normalized["subject_zone_map"] = ( { str(group.get("identity_query") or group.get("id") or ""): normalized["valid_zone_ids"][index] for index, group in enumerate(subject_groups) } if source_rule_type == "paired_zone_containment" and len(subject_groups) == len(normalized["valid_zone_ids"]) else {} ) if source_rule_type == "paired_zone_containment" and not normalized["subject_zone_map"]: reasons.append("subject_destination_zone_mapping_not_compiled") destination_region_roles = tuple(dict.fromkeys( role for region in regions for role in region.get("image_roles", []) )) or ("pred",) operations = [ _operation("detect_output_components", "object_detection", "detector", ("pred",), produces=("output_component_boxes",)), _operation("refine_output_components", "mask_refinement", "segmenter", ("pred",), depends_on=("detect_output_components",), produces=("output_component_masks",)), _operation("materialize_destination_zones", "region_resolution", "region_proposer", destination_region_roles, produces=("destination_zone_boxes",)), _operation("refine_destination_zones", "spatial_geometry", "segmenter", destination_region_roles, depends_on=("materialize_destination_zones",), produces=("destination_zone_masks",)), ] if explicit_white_furniture: operations.insert( 2, _operation( "classify_output_components", "crop_classification", "classifier", ("pred",), depends_on=("refine_output_components",), parameters={"closed_set": classification_labels}, produces=("output_component_classification",), ), ) classification_dependencies = ["refine_output_components", "refine_destination_zones"] if explicit_white_furniture: classification_dependencies.insert(1, "classify_output_components") if identity_required: operations[0:0] = [ _operation("detect_input_components", "object_detection", "detector", ("input",), produces=("input_component_boxes",)), _operation("refine_input_components", "mask_refinement", "segmenter", ("input",), depends_on=("detect_input_components",), produces=("input_component_masks",)), ] operations.append( _operation("match_components", "instance_matching", "matcher", ("input", "pred"), depends_on=("refine_input_components", "refine_output_components"), produces=("component_matches",)) ) classification_dependencies.insert(0, "match_components") operations.extend( [ _operation("classify_destination_membership", "counting", "predicate_interpreter", ("input", "pred"), depends_on=classification_dependencies, produces=("per_component_destination_facts",)), _operation("decide", "predicate_decision", "predicate_interpreter", ("input", "pred"), depends_on=("classify_destination_membership",), produces=("check_result",)), ] ) predicate = { "schema_version": EXECUTABLE_PREDICATE_SCHEMA_VERSION, "check_id": check_id, "status": "executable" if not reasons else "blocked_uncompiled", "family": "destination_membership", "source_rule_type": source_rule_type, "subjects": subject_groups, "regions": regions, "operations": operations, "state_schema": { "unit": "required_component", "states": ["stored", "wrong_zone", "visible_unstored", "missing", "unknown"], "facts": ["identity_match", "valid_zone_mask_containment", "forbidden_zone_mask_containment", "support_contact"], }, "decision": { "pass": { "stored_count": required_count, "partial_count": 0, "wrong_zone_count": 0, "unresolved_count": 0, }, "partial": { "any": [ { "stored_count": {"minimum": 1, "maximum": max(1, required_count - 1)}, "unresolved_count": 0, }, {"partial_count": {"minimum": 1}, "unresolved_count": 0}, ] }, "fail": {"stored_count": 0, "partial_count": 0, "unresolved_count": 0}, "unknown": {"unresolved_count": {"minimum": 1}}, }, "parameters": normalized, "parameter_provenance": { "required_count": required_count_key, "zone_containment_threshold": threshold_key or "default:0.5", "partial_containment_threshold": partial_key or "default:min(0.25, pass)", "minimum_match_confidence": minimum_confidence_key or "default:0.45", }, "unmapped_contract_parameters": unmapped, "reasons": reasons, "provenance": deepcopy(dict(provenance)), } return predicate def _compile_relocation_transition( *, check_id: str, source_rule_type: str, subjects: Sequence[str], params: Mapping[str, Any], decision: Mapping[str, Any], provenance: Mapping[str, Any], ) -> dict[str, Any]: raw = _mapping(decision.get("parameters")) source_overlap, source_key = _number(raw, ("source_residual_overlap_max",), 0.15) destination_threshold, destination_key = _number(raw, ("destination_containment_threshold",), 0.4) normalized = { "source_residual_overlap_max": source_overlap, "destination_containment_threshold": destination_threshold, "desk_edge_band_fraction": float(raw.get("desk_edge_band_fraction", 0.12)), "minimum_match_confidence": float(raw.get("minimum_match_confidence", 0.55)), "require_complete_negative_search_for_missing": True, "geometry_policy": "per_zone_mask_or_polygon_required", } consumed = {source_key, destination_key, "desk_edge_band_fraction", "minimum_match_confidence"} unmapped = sorted(set(raw) - {key for key in consumed if key}) reasons = [] if not check_id: reasons.append("missing_check_id") if not subjects: reasons.append("missing_subject_queries") if unmapped: reasons.append("unmapped_contract_parameters") destination_id = _region_id_matching(params, ("valid_destination", "destination"), "valid_destinations") desk_id = _region_id_matching(params, ("desktop", "desk_surface", "main_desk"), "main_desktop_surface") regions = [ _typed_region( destination_id, semantic_role="valid_destination_set", image_roles=("pred",), queries=("window ledge", "cabinet shelf", "visible cabinet compartment", "wall leaning display location"), cardinality="one_or_more", ), _typed_region( desk_id, semantic_role="forbidden_destination", image_roles=("input", "pred"), queries=("horizontal top surface of the main desk",), ), ] return { "schema_version": EXECUTABLE_PREDICATE_SCHEMA_VERSION, "check_id": check_id, "status": "executable" if not reasons else "blocked_uncompiled", "family": "relocation_transition", "source_rule_type": source_rule_type, "subjects": _subject_specs(subjects, ""), "regions": regions, "operations": [ _operation("detect_input_subject", "object_detection", "detector", ("input",), produces=("input_subject_boxes",)), _operation("refine_input_subject", "mask_refinement", "segmenter", ("input",), depends_on=("detect_input_subject",), produces=("input_subject_masks", "source_footprints")), _operation("detect_output_subject", "object_detection", "detector", ("pred",), produces=("output_subject_boxes", "detector_search_coverage")), _operation("refine_output_subject", "mask_refinement", "segmenter", ("pred",), depends_on=("detect_output_subject",), produces=("output_subject_masks",)), _operation("materialize_destination_zones", "region_resolution", "region_proposer", ("pred",), produces=("destination_zone_boxes",)), _operation("refine_destination_zones", "spatial_geometry", "segmenter", ("pred",), depends_on=("materialize_destination_zones",), produces=("destination_zone_masks",)), _operation("match_subject", "instance_matching", "matcher", ("input", "pred"), depends_on=("refine_input_subject", "refine_output_subject"), produces=("subject_match",)), _operation("classify_transition", "source_state_classification", "predicate_interpreter", ("input", "pred"), depends_on=("match_subject", "refine_destination_zones"), produces=("source_vacancy_fact", "destination_fact", "visibility_fact")), _operation("decide", "predicate_decision", "predicate_interpreter", ("input", "pred"), depends_on=("classify_transition",), produces=("check_result",)), ], "state_schema": { "unit": "relocated_subject", "states": ["validly_relocated", "desk_edge_ambiguous", "not_moved", "missing", "unknown"], "facts": ["source_overlap_against_transferred_input_target_footprint", "destination_mask_containment", "desk_mask_containment", "identity_match", "negative_search_complete"], }, "decision": { "pass": {"source_vacant": 1, "destination_valid": 1, "visible": 1, "unresolved_count": 0}, "partial": {"source_vacant": 1, "destination_valid": 0, "desk_edge_ambiguous": 1, "visible": 1, "unresolved_count": 0}, "fail": {"any": [{"source_vacant": 0}, {"visible": 0}], "unresolved_count": 0}, "unknown": {"unresolved_count": {"minimum": 1}}, }, "parameters": normalized, "parameter_provenance": { "source_residual_overlap_max": source_key or "default:0.15", "destination_containment_threshold": destination_key or "default:0.4", }, "unmapped_contract_parameters": unmapped, "reasons": reasons, "provenance": deepcopy(dict(provenance)), } def _inventory_alias_tokens(value: Any) -> set[str]: """Return conservative tokens for mapping fixed inventory ids to queries.""" return { token[:-1] if token.endswith("s") and not token.endswith("ss") and len(token) > 3 else token for token in re.findall(r"[a-z0-9]+", str(value or "").replace("_", " ").lower()) if token not in {"a", "an", "and", "the", "with"} } def _inventory_matching_aliases(identity: Any, subjects: Sequence[str]) -> list[str]: """Match aliases without merging objects that share only color/type words.""" identity_tokens = _inventory_alias_tokens(identity) if not identity_tokens: return [] matches: list[str] = [] for subject in subjects: subject_tokens = _inventory_alias_tokens(subject) overlap = len(identity_tokens & subject_tokens) if identity_tokens.issubset(subject_tokens) or ( len(identity_tokens) >= 3 and overlap / len(identity_tokens) >= 0.75 ): matches.append(subject) return matches def _compile_cross_image_inventory( *, check_id: str, source_rule_type: str, subjects: Sequence[str], decision: Mapping[str, Any], provenance: Mapping[str, Any], ) -> dict[str, Any]: """Compile identity/count conservation without claiming pose integrity.""" raw = _mapping(decision.get("parameters")) expected_counts = raw.get("expected_counts") if isinstance(raw.get("expected_counts"), Mapping) else {} maximum_counts = raw.get("maximum_counts") if isinstance(raw.get("maximum_counts"), Mapping) else {} trusted_output_count_mode = "" if source_rule_type == "identity_count_conservation_no_excess": maximum_counts = expected_counts trusted_output_count_mode = "maximum" elif source_rule_type == "all_input_targets_matched": expected_counts = { subject: ( int(raw.get("expected_tumbler_count") or 2) if "tumbler" in subject.lower() else 1 ) for subject in subjects } trusted_output_count_mode = "minimum" expected_count = sum(int(value) for value in expected_counts.values()) if expected_counts else 0 if source_rule_type == "all_named_entities_preserved": named_entities = _dedupe_text(_list(raw.get("required_entities"))) if named_entities: subjects = named_entities expected_count = len(named_entities) minimum_matches = int(raw.get("minimum_matching_instances", 0) or 0) match_threshold, match_key = _number( raw, ( "minimum_match_confidence", "minimum_credible_match_score", "minimum_instance_match_score", "minimum_match_score", ), 0.55, ) coverage = float(raw.get("required_match_coverage", 1.0)) minimum_area_ratio = float( raw.get("minimum_matched_area_ratio", raw.get("minimum_visible_fraction", 0.0)) ) supported_by_rule = { "original_inventory_visible_match": { "count_book_stack_as_group", "minimum_match_confidence", "one_to_one_assignment", "require_visible_output_match", "whole_image_search", }, "expected_species_count_preservation": { "expected_counts", "low_confidence_count_requires_vlm_audit", "minimum_match_confidence", }, "no_excess_or_novel_animal_instances": { "maximum_counts", "allowed_species", "candidate_detection_confidence", "validation_confidence", "unknown_animal_candidates_require_vlm_audit", }, "identity_count_conservation_no_excess": { "expected_counts", "minimum_distinct_mask_iou_for_separate_instances", "minimum_duplicate_identity_similarity", "confirm_excess_with_ocr_color_or_vlm_when_available", }, "all_input_targets_matched": { "required_match_coverage", "minimum_identity_similarity", "allow_pose_and_scale_change", "allow_partial_occlusion_with_supporting_attributes", "expected_tumbler_count", "prefer_credenza_matches", }, "source_instance_conservation": { "allow_occlusion", "allow_position_change", "minimum_credible_match_score", "one_to_one_matching", }, "object_group_survival": { "full_image_search", "minimum_instance_match_score", "minimum_matched_area_ratio", "minimum_matching_instances", "repeated_group_identity_profile", }, "all_named_entities_preserved": { "required_entities", "minimum_match_score", "minimum_visible_fraction", "allow_minor_occlusion", "require_category_and_shape_consistency", }, } unmapped = sorted(set(raw) - supported_by_rule.get(source_rule_type, set())) reasons: list[str] = [] if not check_id: reasons.append("missing_check_id") if not subjects: reasons.append("missing_subject_queries") if source_rule_type == "expected_species_count_preservation" and not expected_counts: reasons.append("expected_species_counts_not_compiled") if source_rule_type == "no_excess_or_novel_animal_instances" and not maximum_counts: reasons.append("maximum_species_counts_not_compiled") if trusted_output_count_mode and not (expected_counts or maximum_counts): reasons.append("trusted_inventory_counts_not_compiled") if unmapped: reasons.append("unmapped_contract_parameters") species_count_mode = source_rule_type == "expected_species_count_preservation" no_excess_species_mode = source_rule_type == "no_excess_or_novel_animal_instances" output_species_mode = species_count_mode or no_excess_species_mode or bool(trusted_output_count_mode) inventory_counts = expected_counts if species_count_mode else maximum_counts if trusted_output_count_mode == "minimum": inventory_counts = expected_counts if output_species_mode: subject_groups = [] for species, count in inventory_counts.items(): species_text = str(species).replace("_", " ").strip() matching_aliases = _inventory_matching_aliases(species, subjects) subject_groups.append( _subject_group_spec( matching_aliases or (species_text,), expected_count=int(count), group_id=re.sub(r"[^a-z0-9]+", "_", str(species).lower()).strip("_"), ) ) else: subject_groups = [ _subject_group_spec((subject,), expected_count=1) for subject in subjects ] requested_group_profile = str(raw.get("repeated_group_identity_profile") or "") binder_group_queries = bool(subjects) and all( any(token in str(subject).lower() for token in ("binder", "file folder")) for subject in subjects ) repeated_group_profile = "" if source_rule_type == "object_group_survival": if requested_group_profile: if requested_group_profile == REPEATED_COMPONENT_GROUP_IDENTITY_PROFILE: repeated_group_profile = requested_group_profile else: reasons.append("repeated_group_identity_profile_unsupported") elif binder_group_queries: repeated_group_profile = REPEATED_COMPONENT_GROUP_IDENTITY_PROFILE if repeated_group_profile: # The detector phrases are aliases for one physical repeated-item # group, not three independent binder rows. Component cardinality # is certified later from image structure. subject_groups = [ _subject_group_spec( tuple(subjects), expected_count=1, group_id="repeated_component_group", ) ] expected_count = 1 if species_count_mode or no_excess_species_mode: classification_proposal_queries = _dedupe_text( ["animal", "wildlife"] + list(subjects) + [str(species).replace("_", " ") for species in inventory_counts] ) elif trusted_output_count_mode: # Fixed object inventories carry identity-bearing attributes such as # colour, printed title, or assembly membership. Adding generic # closed-set labels here causes the detector query canonicalizer to # replace those reviewed phrases with shorter ambiguous queries. classification_proposal_queries = _dedupe_text(list(subjects)) else: classification_proposal_queries = [] normalized = { "expected_count": expected_count, "expected_counts": dict(expected_counts), "maximum_counts": dict(maximum_counts), "subject_groups": _public_subject_groups(subject_groups), "minimum_detection_confidence": float(raw.get("candidate_detection_confidence", 0.15)), "minimum_match_confidence": match_threshold, "required_match_coverage": coverage, "minimum_matching_instances": minimum_matches, "minimum_matched_area_ratio": minimum_area_ratio, "one_to_one_assignment": bool(raw.get("one_to_one_assignment", raw.get("one_to_one_matching", True))), "full_frame_search": bool(raw.get("whole_image_search", raw.get("full_image_search", True))), "require_tiled_search_for_negative": True, "allow_position_change": bool(raw.get("allow_position_change", True)), "allow_minor_occlusion": bool(raw.get("allow_minor_occlusion", False)), "require_category_and_shape_consistency": bool( raw.get("require_category_and_shape_consistency", False) ), "minimum_shape_similarity": ( 0.5 if raw.get("require_category_and_shape_consistency", False) else 0.0 ), "visible_output_match_required": bool(raw.get("require_visible_output_match", True)), "enforce_no_excess": no_excess_species_mode, "trusted_output_count_mode": trusted_output_count_mode, "low_confidence_policy": "unknown", "require_crop_classification": output_species_mode, "classification_labels": ( [str(species).replace("_", " ") for species in inventory_counts] + ( ["other animal", "not an animal"] if species_count_mode or no_excess_species_mode else ["other object"] ) if output_species_mode else [] ), "classification_proposal_queries": classification_proposal_queries, "classification_use_segmenter_proposals": species_count_mode, "classification_proposal_zone_ids": [], "classification_segmenter_min_area_fraction": 0.00005, "classification_segmenter_max_area_fraction": 0.08, "classification_segmenter_max_proposals": 128, "classification_minimum_margin": 0.06, "classification_minimum_probability": 0.25, "minimum_novel_classification_probability": float(raw.get("validation_confidence", 0.55)), "unknown_animal_policy": ( "unknown_without_vlm" if raw.get("unknown_animal_candidates_require_vlm_audit", False) else "fail_when_confident" ), "inventory_distractor_labels": ( ["other animal", "not an animal"] if species_count_mode or no_excess_species_mode else ["other object"] ), "group_alias_policy": ( "repeated_component_group_as_one" if repeated_group_profile else "book_stack_as_one" if raw.get("count_book_stack_as_group") else "per_instance" ), "repeated_group_identity_profile": repeated_group_profile, "repeated_group_identity_executor_version": ( REPEATED_COMPONENT_GROUP_IDENTITY_EXECUTOR_VERSION if repeated_group_profile else "" ), "minimum_repeated_component_count": minimum_matches, "maximum_repeated_component_count": 8, } return { "schema_version": EXECUTABLE_PREDICATE_SCHEMA_VERSION, "check_id": check_id, "status": "executable" if not reasons else "blocked_uncompiled", "family": "cross_image_inventory_integrity", "source_rule_type": source_rule_type, "subjects": subject_groups, "regions": [], "operations": ([ _operation("detect_output_inventory", "object_detection", "detector", ("pred",), parameters={"search_scopes": ["full_frame", "tiled"]}, produces=("output_inventory_boxes", "detector_search_coverage")), _operation("refine_output_inventory", "mask_refinement", "segmenter", ("pred",), depends_on=("detect_output_inventory",), produces=("output_inventory_masks",)), _operation("classify_output_inventory", "crop_classification", "classifier", ("pred",), depends_on=("refine_output_inventory",), parameters={"closed_set": normalized["classification_labels"]}, produces=("output_inventory_classification",)), _operation("classify_inventory_integrity", "counting", "predicate_interpreter", ("pred",), depends_on=("classify_output_inventory",), produces=("species_inventory_facts",)), _operation("decide", "predicate_decision", "predicate_interpreter", ("pred",), depends_on=("classify_inventory_integrity",), produces=("check_result",)), ] if output_species_mode else [ _operation("detect_input_inventory", "object_detection", "detector", ("input",), produces=("input_inventory_boxes",)), _operation("refine_input_inventory", "mask_refinement", "segmenter", ("input",), depends_on=("detect_input_inventory",), produces=("input_inventory_masks",)), _operation("detect_output_inventory", "object_detection", "detector", ("pred",), parameters={"search_scopes": ["full_frame", "tiled"]}, produces=("output_inventory_boxes", "detector_search_coverage")), _operation("refine_output_inventory", "mask_refinement", "segmenter", ("pred",), depends_on=("detect_output_inventory",), produces=("output_inventory_masks",)), _operation("match_inventory", "instance_matching", "matcher", ("input", "pred"), depends_on=("refine_input_inventory", "refine_output_inventory"), produces=("inventory_matches",)), _operation("classify_inventory_integrity", "counting", "predicate_interpreter", ("input", "pred"), depends_on=("match_inventory",), produces=("inventory_integrity_facts",)), _operation("decide", "predicate_decision", "predicate_interpreter", ("input", "pred"), depends_on=("classify_inventory_integrity",), produces=("check_result",)), ]), "state_schema": ( { "unit": "expected_species_inventory", "states": ["count_preserved", "count_decreased_after_complete_search", "unknown"], "facts": ["expected_count", "deduplicated_output_count", "full_frame_and_tiled_search_coverage"], } if output_species_mode else { "unit": "input_inventory_instance", "states": ["preserved", "missing_after_complete_search", "excess", "unknown"], "facts": ["identity_match", "one_to_one_assignment", "matched_area_ratio", "search_coverage"], } ), "decision": { "pass": {"missing_count": 0, "excess_count": 0, "unresolved_count": 0}, "fail": ( {"excess_count": {"minimum": 1}} if no_excess_species_mode or trusted_output_count_mode == "maximum" else {"missing_count": {"minimum": 1}, "unresolved_count": 0} ), "unknown": ( {"unresolved_count": {"minimum": 1}, "excess_count": 0} if no_excess_species_mode or trusted_output_count_mode == "maximum" else {"unresolved_count": {"minimum": 1}} ), }, "parameters": normalized, "parameter_provenance": { "minimum_match_confidence": match_key or "default:0.55", "expected_count": ( "expected_counts" if expected_counts else "maximum_counts" if maximum_counts else "required_entities" if source_rule_type == "all_named_entities_preserved" else "input_inventory_runtime" ), "low_confidence_policy": "contract_vlm_request_mapped_to_zero_vlm_unknown", "repeated_group_identity_profile": ( "decision_rule.parameters.repeated_group_identity_profile" if requested_group_profile else "deterministic_subject_profile:binder_or_file_folder_group" if repeated_group_profile else "not_applicable" ), }, "unmapped_contract_parameters": unmapped, "reasons": reasons, "provenance": deepcopy(dict(provenance)), } def _compile_fixed_location_preservation( *, check_id: str, source_rule_type: str, subjects: Sequence[str], decision: Mapping[str, Any], provenance: Mapping[str, Any], ) -> dict[str, Any]: """Compile preservation checks whose complete semantics are measurable.""" raw = _mapping(decision.get("parameters")) supported_by_rule = { "multi_instance_strict_preservation": { "expected_count", "required_instances", "maximum_registered_centroid_shift_pixels", "minimum_mask_iou", "minimum_masked_ssim", "maximum_new_occlusion_fraction", "source_instance_annotations", }, "character_integrity_preservation": { "minimum_identity_similarity", "minimum_visible_mask_fraction", "maximum_unexplained_silhouette_change", "hat_required", }, "person_region_preservation": { "minimum_mask_iou", "maximum_changed_area_ratio", "major_body_region_required", "blur_aware_comparison", }, } unmapped = sorted(set(raw) - supported_by_rule.get(source_rule_type, set())) reasons: list[str] = [] if not check_id: reasons.append("missing_check_id") if not subjects: reasons.append("missing_subject_queries") if unmapped: reasons.append("unmapped_contract_parameters") required_instances = _dedupe_text(_list(raw.get("required_instances"))) expected_count = int(raw.get("expected_count") or 0) or ( 1 if source_rule_type in {"character_integrity_preservation", "person_region_preservation"} else len(required_instances) or len(subjects) ) minimum_shape = ( 1.0 - float(raw["maximum_unexplained_silhouette_change"]) if "maximum_unexplained_silhouette_change" in raw else 0.0 ) minimum_visible = float(raw.get("minimum_visible_mask_fraction", 0.0)) if "maximum_new_occlusion_fraction" in raw: minimum_visible = max(minimum_visible, 1.0 - float(raw["maximum_new_occlusion_fraction"])) source_annotations = [ deepcopy(dict(item)) for item in _list(raw.get("source_instance_annotations")) if isinstance(item, Mapping) ] annotation_ids: set[str] = set() for index, item in enumerate(source_annotations): instance_id = str(item.get("instance_id") or "").strip() group_id = str(item.get("group_id") or "").strip() query_text = str(item.get("query_text") or item.get("label") or "").strip() bbox = item.get("bbox_xyxy") provenance_value = str(item.get("provenance") or "").strip() if not instance_id or instance_id in annotation_ids: reasons.append(f"source_annotation_{index}_instance_id_invalid") annotation_ids.add(instance_id) if not group_id: reasons.append(f"source_annotation_{index}_group_missing") if not query_text: reasons.append(f"source_annotation_{index}_query_missing") else: # Fixed-location closed-set labels are identity phrases rather # than coarse detector classes. Keep that matcher-only class # explicit so a reviewed ``running_child`` roster slot and the # classifier label ``running child on grass`` are comparable. item["matching_class"] = query_text if provenance_value != "human_verified_fixed_input_v1": reasons.append(f"source_annotation_{index}_provenance_unverified") if not ( isinstance(bbox, (list, tuple)) and len(bbox) == 4 and all(isinstance(value, (int, float)) for value in bbox) and float(bbox[2]) > float(bbox[0]) and float(bbox[3]) > float(bbox[1]) ): reasons.append(f"source_annotation_{index}_bbox_invalid") if source_annotations and len(source_annotations) != expected_count: reasons.append("source_annotation_count_mismatch") if source_annotations and required_instances: annotated_groups = {str(item.get("group_id") or "") for item in source_annotations} if annotated_groups != set(required_instances): reasons.append("source_annotation_groups_do_not_match_required_instances") # A detector query is not an instance identity. Multi-subject # preservation checks own one typed roster entry per reviewed entity, # while the single-subject rules treat multiple phrases as aliases for # the same physical instance. This prevents synonymous foreground-person # prompts (or a dog prompt that also fires on a child) from inflating the # protected source inventory. if source_rule_type == "multi_instance_strict_preservation": subject_groups = [ _subject_group_spec( (query,), expected_count=1, group_id=( required_instances[index] if index < len(required_instances) else "" ), ) for index, query in enumerate(_dedupe_text(subjects)) ] else: subject_groups = [ _subject_group_spec( _dedupe_text(subjects), expected_count=expected_count, group_id="fixed_location_target", ) ] for group in subject_groups: selector_text = " ".join( [str(group.get("id") or ""), *[str(value) for value in group.get("aliases", [])]] ).lower() if "foreground" in selector_text: group["spatial_selector"] = "foreground_largest_lower" elif "background" in selector_text: group["spatial_selector"] = "background_smallest_upper" normalized = { "expected_count": expected_count, "required_instances": required_instances, "subject_groups": _public_subject_groups(subject_groups), "minimum_detection_confidence": 0.15, "minimum_match_confidence": float(raw.get("minimum_identity_similarity", 0.55)), "minimum_identity_similarity": float(raw.get("minimum_identity_similarity", 0.0)), "maximum_centroid_shift_pixels": ( float(raw["maximum_registered_centroid_shift_pixels"]) if "maximum_registered_centroid_shift_pixels" in raw else None ), "minimum_registered_mask_iou": float(raw.get("minimum_mask_iou", 0.0)), "minimum_masked_ssim": float(raw.get("minimum_masked_ssim", 0.0)), "maximum_changed_area_ratio": float(raw.get("maximum_changed_area_ratio", 1.0)), "minimum_visible_mask_fraction": minimum_visible, "minimum_shape_similarity": minimum_shape, "hat_required": bool(raw.get("hat_required", False)), "major_body_region_required": bool(raw.get("major_body_region_required", False)), "blur_aware_comparison": bool(raw.get("blur_aware_comparison", False)), "registration_required": True, "registration_method": "robust_static_background_alignment", "required_matching_features": ["appearance embedding", "mask shape"], "source_instance_annotations": source_annotations, "source_inventory_provenance": ( "contract_source_annotations" if source_annotations else "runtime_detector" ), "source_annotation_mask_profile": _verified_source_mask_profile(source_annotations), } if source_rule_type == "multi_instance_strict_preservation": normalized.update( { "matching_classification_labels": [ *[str(group.get("identity_query") or "") for group in subject_groups], "other object", ], "matching_classification_minimum_margin": 0.04, "matching_classification_minimum_probability": 0.25, # Fixed, named preservation subjects already have scoped # detector proposals. Full-frame all-mask proposals add # background lookalikes and cannot establish identity. "matching_use_segmenter_proposals": False, "matching_segmenter_min_area_fraction": 0.00003, "matching_segmenter_max_area_fraction": 0.15, "matching_segmenter_max_proposals": 128, } ) normalized = {key: value for key, value in normalized.items() if value is not None} return { "schema_version": EXECUTABLE_PREDICATE_SCHEMA_VERSION, "check_id": check_id, "status": "executable" if not reasons else "blocked_uncompiled", "family": "fixed_location_instance_preservation", "source_rule_type": source_rule_type, "subjects": subject_groups, "regions": [], "operations": [ _operation("detect_input_subjects", "object_detection", "detector", ("input",), produces=("input_boxes",)), _operation("refine_input_subjects", "mask_refinement", "segmenter", ("input",), depends_on=("detect_input_subjects",), produces=("input_masks",)), _operation("detect_output_subjects", "object_detection", "detector", ("pred",), produces=("output_boxes",)), _operation("refine_output_subjects", "mask_refinement", "segmenter", ("pred",), depends_on=("detect_output_subjects",), produces=("output_masks",)), _operation("match_subjects", "instance_matching", "matcher", ("input", "pred"), depends_on=("refine_input_subjects", "refine_output_subjects"), produces=("subject_matches",)), _operation("register_frames", "image_registration", "registration", ("input", "pred"), produces=("pred_to_input_transform",)), _operation("decide", "predicate_decision", "predicate_interpreter", ("input", "pred"), depends_on=("match_subjects", "register_frames"), produces=("check_result",)), ], "state_schema": { "unit": "preserved_instance", "states": ["preserved", "definite_violation", "unknown"], "facts": [ "identity_match", "registered_centroid_shift", "registered_mask_iou", "visible_mask_fraction", "shape_similarity", "masked_ssim", "changed_area_ratio", ], }, "decision": { "pass": {"violation_count": 0, "unresolved_count": 0}, "fail": {"violation_count": {"minimum": 1}}, "unknown": {"unresolved_count": {"minimum": 1}, "violation_count": 0}, }, "parameters": normalized, "parameter_provenance": { "expected_count": "required_instances_or_rule_cardinality", "registration_required": "fixed_location_preservation_semantics", }, "unmapped_contract_parameters": unmapped, "reasons": reasons, "provenance": deepcopy(dict(provenance)), } def _compile_ocr_text_predicate( *, check_id: str, source_rule_type: str, subjects: Sequence[str], params: Mapping[str, Any], decision: Mapping[str, Any], provenance: Mapping[str, Any], ) -> dict[str, Any]: """Normalize reviewed OCR semantics into the tested OCR operator.""" from pvr_eval.agent.contract_metric_binding import ( canonical_rule_type, metric_capability, metric_contract_compliance, ) raw = _mapping(decision.get("parameters")) if source_rule_type == "all_text_rois_preserved": supported = { "required_anchor_strings", "normalized_edit_similarity_min", "output_ocr_confidence_min", "relative_sharpness_min_vs_input", "compare_full_rule_sign_by_line_layout_and_string_alignment", } normalized = { "required_anchor_strings": _dedupe_text(_list(raw.get("required_anchor_strings"))), "normalized_edit_similarity_min": float(raw.get("normalized_edit_similarity_min", 0.90)), "output_ocr_confidence_min": float(raw.get("output_ocr_confidence_min", 0.65)), "relative_sharpness_min_vs_input": float(raw.get("relative_sharpness_min_vs_input", 0.75)), "compare_full_input_text_inventory": bool( raw.get("compare_full_rule_sign_by_line_layout_and_string_alignment", True) ), "registered_text_roi_matching": True, } else: supported = { "full_frame_scan", "minimum_ocr_confidence", "match_existing_text_by_content_or_host_object", "ignore_original_scene_text", "annotation_cues", } normalized = { "minimum_ocr_confidence": float(raw.get("minimum_ocr_confidence", 0.30)), "full_frame_scan": bool(raw.get("full_frame_scan", True)), "match_existing_text_by_content": bool( raw.get("match_existing_text_by_content_or_host_object", True) ), "ignore_original_scene_text": bool(raw.get("ignore_original_scene_text", True)), "annotation_cues": _dedupe_text(_list(raw.get("annotation_cues"))), "new_text_content_similarity_min": 0.85, "definite_overlay_minimum_confidence": 0.80, "definite_overlay_minimum_text_length": 4, } unmapped = sorted(set(raw) - supported) reasons: list[str] = [] if not check_id: reasons.append("missing_check_id") if source_rule_type == "all_text_rois_preserved" and not normalized["required_anchor_strings"]: reasons.append("required_anchor_strings_not_compiled") if unmapped: reasons.append("unmapped_contract_parameters") canonical = canonical_rule_type(source_rule_type) predicate = _compile_registered_metric_bridge( check_id=check_id, source_rule_type=source_rule_type, canonical_rule_type=canonical, subjects=subjects, params=params, decision=decision, provenance=provenance, capability=metric_capability(canonical), ) predicate["parameters"] = normalized predicate["parameter_provenance"] = { "source": "decision_rule.parameters", "normalizer": "ocr_text_contract_v1", } predicate["unmapped_contract_parameters"] = unmapped compliance = metric_contract_compliance(source_rule_type, normalized, decision) predicate["contract_compliance"] = compliance if compliance.get("status") != "compliant": reasons.extend(["contract_handler_incompatible", *compliance.get("risk_flags", [])]) predicate["reasons"] = list(dict.fromkeys((*predicate.get("reasons", []), *reasons))) predicate["status"] = "executable" if not predicate["reasons"] else "blocked_uncompiled" return predicate def _compile_source_displacement( *, check_id: str, source_rule_type: str, subjects: Sequence[str], decision: Mapping[str, Any], provenance: Mapping[str, Any], ) -> dict[str, Any]: """Compile per-instance movement as matching plus source-footprint geometry.""" raw = _mapping(decision.get("parameters")) expected_instances = ( {str(key): int(value) for key, value in raw.get("expected_instances", {}).items()} if isinstance(raw.get("expected_instances"), Mapping) else {} ) expected_bird_count = int(raw.get("expected_bird_count") or 0) expected_count = sum(expected_instances.values()) if expected_instances else expected_bird_count supported = { "per_instance_source_zone_displacement": { "expected_instances", "source_zone_expansion_fraction", "moved_if_centroid_outside_expanded_source_zone", "maximum_source_output_mask_iou_for_move", "minimum_normalized_centroid_displacement", "matching_features", "source_instance_annotations", }, "multi_instance_source_zone_displacement": { "expected_instances", "source_zone_expansion_fraction", "moved_if_centroid_outside_expanded_source_zone", "maximum_source_output_mask_iou_for_move", "minimum_normalized_centroid_displacement", "raccoon_matching", "source_instance_annotations", }, "bird_instance_displacement_and_shoulder_clearance": { "expected_bird_count", "source_zone_expansion_fraction", "maximum_source_output_mask_iou_for_move", "minimum_normalized_centroid_displacement", "maximum_bird_shoulder_overlap_ratio", "use_tiled_detection", "source_instance_annotations", }, } unmapped = sorted(set(raw) - supported.get(source_rule_type, set())) reasons: list[str] = [] if not check_id: reasons.append("missing_check_id") if not subjects: reasons.append("missing_subject_queries") if expected_count <= 0: reasons.append("expected_displaced_count_not_compiled") if unmapped: reasons.append("unmapped_contract_parameters") subject_groups = [] if expected_instances: for species, count in expected_instances.items(): aliases = [ subject for subject in subjects if species.lower() in subject.lower() or subject.lower() in species.lower() ] subject_groups.append( _subject_group_spec(aliases or (species,), expected_count=count, group_id=species) ) else: subject_groups = [_subject_group_spec(subjects, expected_count=expected_count, group_id="birds")] required_matching_features = _dedupe_text(_list(raw.get("matching_features"))) if source_rule_type == "multi_instance_source_zone_displacement" and raw.get("raccoon_matching"): matching_text = str(raw.get("raccoon_matching") or "").lower() required_matching_features = ["species"] if "appearance" in matching_text: required_matching_features.append("appearance embedding") if "size" in matching_text: required_matching_features.append("relative size") if source_rule_type == "bird_instance_displacement_and_shoulder_clearance": required_matching_features = ["species", "appearance embedding", "mask shape"] source_annotations = [ deepcopy(dict(item)) for item in _list(raw.get("source_instance_annotations")) if isinstance(item, Mapping) ] annotation_reasons = [] for index, item in enumerate(source_annotations): bbox = item.get("bbox_xyxy") if not isinstance(bbox, (list, tuple)) or len(bbox) != 4: annotation_reasons.append(f"source_annotation_{index}_bbox_invalid") if not str(item.get("group_id") or "").strip(): annotation_reasons.append(f"source_annotation_{index}_group_missing") if source_annotations and len(source_annotations) != expected_count: annotation_reasons.append("source_annotation_count_mismatch") reasons.extend(annotation_reasons) classification_labels = [] for group in subject_groups: group_id = str(group.get("id") or "").strip() aliases = [str(value).strip() for value in group.get("aliases", []) if str(value or "").strip()] label = "bird" if group_id == "birds" else group_id or (aliases[0] if aliases else "") if label and label not in classification_labels: classification_labels.append(label) classification_labels.append("other animal") normalized = { "expected_count": expected_count, "expected_instances": expected_instances, "expected_bird_count": expected_bird_count, "subject_groups": _public_subject_groups(subject_groups), "minimum_detection_confidence": 0.15, "minimum_match_confidence": 0.55, "minimum_normalized_centroid_displacement": float( raw.get("minimum_normalized_centroid_displacement", 0.04) ), "maximum_source_output_mask_iou_for_move": float( raw.get("maximum_source_output_mask_iou_for_move", 0.15) ), "source_zone_expansion_fraction": float(raw.get("source_zone_expansion_fraction", 0.0)), "moved_if_centroid_outside_expanded_source_zone": bool( raw.get("moved_if_centroid_outside_expanded_source_zone", True) ), "require_source_output_mask_iou": True, "maximum_bird_shoulder_overlap_ratio": float( raw.get("maximum_bird_shoulder_overlap_ratio", 1.0) ), "clearance_source_selector_terms": ( ["shoulder"] if source_rule_type == "bird_instance_displacement_and_shoulder_clearance" else [] ), "require_tiled_search": bool(raw.get("use_tiled_detection", True)), "required_matching_features": required_matching_features, "assignment_policy": str(raw.get("raccoon_matching") or "hungarian_one_to_one"), "source_instance_annotations": source_annotations, "source_annotation_mask_profile": _verified_source_mask_profile(source_annotations), "matching_classification_labels": classification_labels, "matching_use_segmenter_proposals": bool(source_annotations), "matching_segmenter_min_area_fraction": 0.00003, "matching_segmenter_max_area_fraction": 0.08, "matching_segmenter_max_proposals": 128, # Closed-set filtering only removes non-target animals here. Fine # target-label ambiguity (notably doe vs fawn) is resolved by the # subsequent one-to-one matcher, so it must not be discarded early. "matching_classification_minimum_margin": 0.0, "matching_classification_minimum_probability": 0.25, "localized_source_residual_enabled": bool(source_annotations), "localized_source_residual_minimum_correlation": 0.85, "localized_source_residual_maximum_mean_absolute_error": 0.10, "set_level_source_vacancy_allowed": source_rule_type in { "multi_instance_source_zone_displacement", "bird_instance_displacement_and_shoulder_clearance", }, } return { "schema_version": EXECUTABLE_PREDICATE_SCHEMA_VERSION, "check_id": check_id, "status": "executable" if not reasons else "blocked_uncompiled", "family": "source_instance_displacement", "source_rule_type": source_rule_type, "subjects": subject_groups, "regions": [], "operations": [ _operation("detect_input_inventory", "object_detection", "detector", ("input",), produces=("input_boxes",)), _operation("refine_input_inventory", "mask_refinement", "segmenter", ("input",), depends_on=("detect_input_inventory",), produces=("input_masks",)), _operation("detect_output_inventory", "object_detection", "detector", ("pred",), parameters={"search_scopes": ["full_frame", "tiled"]}, produces=("output_boxes", "detector_search_coverage")), _operation("refine_output_inventory", "mask_refinement", "segmenter", ("pred",), depends_on=("detect_output_inventory",), produces=("output_masks",)), _operation("match_inventory", "instance_matching", "matcher", ("input", "pred"), depends_on=("refine_input_inventory", "refine_output_inventory"), produces=("one_to_one_matches",)), _operation("classify_displacement", "source_state_classification", "predicate_interpreter", ("input", "pred"), depends_on=("match_inventory",), produces=("per_instance_displacement_facts",)), _operation("decide", "predicate_decision", "predicate_interpreter", ("input", "pred"), depends_on=("classify_displacement",), produces=("check_result",)), ], "state_schema": { "unit": "matched_source_instance", "states": ["moved", "stationary", "unknown"], "facts": ["identity_match", "centroid_displacement", "source_overlap", "expanded_source_zone_clearance"], }, "decision": { "pass": {"moved_count": expected_count, "unresolved_count": 0}, "partial": {"moved_count": {"minimum": 1, "maximum": max(1, expected_count - 1)}, "unresolved_count": 0}, "fail": {"moved_count": 0, "unresolved_count": 0}, "unknown": {"unresolved_count": {"minimum": 1}}, }, "parameters": normalized, "parameter_provenance": { "expected_count": "expected_instances" if expected_instances else "expected_bird_count", "displacement_thresholds": "decision_rule.parameters", "assignment_policy": "raccoon_matching" if raw.get("raccoon_matching") else "default:hungarian_one_to_one", "source_instance_annotations": "decision_rule.parameters.source_instance_annotations" if source_annotations else "runtime_detector", }, "unmapped_contract_parameters": unmapped, "reasons": reasons, "provenance": deepcopy(dict(provenance)), } def _compile_source_region_restoration( *, check_id: str, source_rule_type: str, subjects: Sequence[str], decision: Mapping[str, Any], provenance: Mapping[str, Any], ) -> dict[str, Any]: """Compile source furniture clearance plus objective lawn coherence.""" raw = _mapping(decision.get("parameters")) furniture = [ subject for subject in subjects if any(noun in subject.lower() for noun in ("table", "chair")) and "grass" not in subject.lower() ] table_aliases = [subject for subject in furniture if "table" in subject.lower()] chair_aliases = [subject for subject in furniture if "chair" in subject.lower()] groups: list[dict[str, Any]] = [] if table_aliases: table = _subject_group_spec(table_aliases, expected_count=1, group_id="source_table") table["output_queries"] = _dedupe_text([*table_aliases, "table", "outdoor table"]) groups.append(table) if chair_aliases: chairs = _subject_group_spec(chair_aliases, expected_count=3, group_id="source_chairs") chairs["output_queries"] = _dedupe_text([*chair_aliases, "chair", "outdoor chair"]) groups.append(chairs) supported = { "source_zone_dilation_pixels", "pass_max_furniture_residual_fraction", "partial_max_furniture_residual_fraction", "pass_min_grass_fill_fraction", "registration_method", } unmapped = sorted(set(raw) - supported) reasons: list[str] = [] if not check_id: reasons.append("missing_check_id") if not groups or not table_aliases or not chair_aliases: reasons.append("table_and_chair_subjects_not_compiled") if unmapped: reasons.append("unmapped_contract_parameters") pass_residual = float(raw.get("pass_max_furniture_residual_fraction", 0.03)) partial_residual = float(raw.get("partial_max_furniture_residual_fraction", 0.20)) grass_min = float(raw.get("pass_min_grass_fill_fraction", 0.90)) normalized = { "expected_source_count": 4, "minimum_detection_confidence": 0.15, "source_zone_dilation_pixels": int(raw.get("source_zone_dilation_pixels", 8)), "pass_max_furniture_residual_fraction": pass_residual, "partial_max_furniture_residual_fraction": partial_residual, "pass_min_grass_fill_fraction": grass_min, "registration_method": str(raw.get("registration_method") or "robust_static_background_alignment"), "require_tiled_search_for_negative": True, "grass_reference_ring_pixels": 24, "grass_hue_tolerance_degrees": 38.0, "grass_saturation_tolerance": 0.32, "grass_value_tolerance": 0.32, } return { "schema_version": EXECUTABLE_PREDICATE_SCHEMA_VERSION, "check_id": check_id, "status": "executable" if not reasons else "blocked_uncompiled", "family": "source_region_restoration", "source_rule_type": source_rule_type, "subjects": groups, "regions": [], "operations": [ _operation("detect_input_furniture", "object_detection", "detector", ("input",), produces=("input_furniture_boxes",)), _operation("refine_input_furniture", "mask_refinement", "segmenter", ("input",), depends_on=("detect_input_furniture",), produces=("input_furniture_masks", "source_footprint")), _operation("detect_output_furniture", "object_detection", "detector", ("pred",), parameters={"search_scopes": ["full_frame", "tiled"]}, produces=("output_furniture_boxes", "detector_search_coverage")), _operation("refine_output_furniture", "mask_refinement", "segmenter", ("pred",), depends_on=("detect_output_furniture",), produces=("output_furniture_masks",)), _operation("register_source", "image_registration", "registration", ("input", "pred"), produces=("input_to_output_transform",)), _operation("measure_restoration", "source_state_classification", "predicate_interpreter", ("input", "pred"), depends_on=("refine_input_furniture", "refine_output_furniture", "register_source"), produces=("furniture_residual_fraction", "grass_fill_fraction")), _operation("decide", "predicate_decision", "predicate_interpreter", ("input", "pred"), depends_on=("measure_restoration",), produces=("check_result",)), ], "state_schema": { "unit": "registered_source_furniture_footprint", "states": ["restored", "partially_restored", "furniture_remaining", "unknown"], "facts": ["input_inventory_count", "registration", "furniture_residual_fraction", "grass_fill_fraction", "negative_search_coverage"], }, "decision": { "pass": {"furniture_residual_fraction": {"maximum": pass_residual}, "grass_fill_fraction": {"minimum": grass_min}, "unresolved_count": 0}, "partial": {"any": [ {"furniture_residual_fraction": {"minimum": pass_residual + 1e-9, "maximum": partial_residual}, "unresolved_count": 0}, {"furniture_residual_fraction": {"maximum": partial_residual}, "grass_fill_fraction": {"maximum": grass_min - 1e-9}, "unresolved_count": 0}, ]}, "fail": {"furniture_residual_fraction": {"minimum": partial_residual + 1e-9}, "unresolved_count": 0}, "unknown": {"unresolved_count": {"minimum": 1}}, }, "parameters": normalized, "parameter_provenance": { "source_zone": "union_of_input_table_and_three_chair_masks", "registration_method": "registration_method", "furniture_residual_thresholds": "decision_rule.parameters", "grass_fill_threshold": "decision_rule.parameters", }, "unmapped_contract_parameters": unmapped, "reasons": reasons, "provenance": deepcopy(dict(provenance)), } def _compile_registered_metric_bridge( *, check_id: str, source_rule_type: str, canonical_rule_type: str, subjects: Sequence[str], params: Mapping[str, Any], decision: Mapping[str, Any], provenance: Mapping[str, Any], capability: Any, ) -> dict[str, Any]: operations: list[dict[str, Any]] = [] previous_by_kind: dict[str, list[str]] = {} for index, requirement in enumerate(getattr(capability, "evidence", ())): kind = str(requirement.operation) operation_id = f"{kind}_{index + 1}" dependencies: list[str] = [] if kind == "mask_refinement": dependencies.extend(previous_by_kind.get("object_detection", [])) elif kind == "instance_matching": dependencies.extend(previous_by_kind.get("mask_refinement", [])) operations.append( _operation( operation_id, kind, str(requirement.tool_family), tuple(requirement.image_roles), depends_on=dependencies, produces=(kind + "_evidence",), ) ) previous_by_kind.setdefault(kind, []).append(operation_id) regions = _generic_typed_regions(params) if getattr(capability, "regions", ()) else [] if regions and getattr(capability, "regions", ()): operations.append( _operation( "materialize_regions", "region_resolution", "region_proposer", tuple(dict.fromkeys(role for region in regions for role in region.get("image_roles", []))), produces=("named_region_boxes",), ) ) operations.append( _operation( "refine_regions", "spatial_geometry", "segmenter", tuple(dict.fromkeys(role for region in regions for role in region.get("image_roles", []))), depends_on=("materialize_regions",), produces=("named_region_masks",), ) ) terminal_dependencies = [item["id"] for item in operations] operations.append( _operation( "decide", "predicate_decision", "registered_metric_operator", ("input", "pred"), depends_on=terminal_dependencies, parameters={"operator": canonical_rule_type, "operator_version": REGISTERED_METRIC_OPERATOR_VERSION}, produces=("check_result",), ) ) reasons = [] if not check_id: reasons.append("missing_check_id") if any(item["kind"] in {"object_detection", "mask_refinement", "instance_matching"} for item in operations) and not subjects: reasons.append("missing_subject_queries") return { "schema_version": EXECUTABLE_PREDICATE_SCHEMA_VERSION, "check_id": check_id, "status": "executable" if not reasons else "blocked_uncompiled", "family": "registered_metric_bridge", "source_rule_type": source_rule_type, "canonical_rule_type": canonical_rule_type, "subjects": _subject_specs(subjects, ""), "regions": regions, "operations": operations, "state_schema": { "unit": "registered_metric_evidence", "operator": canonical_rule_type, "operator_version": REGISTERED_METRIC_OPERATOR_VERSION, }, "decision": { "operator": canonical_rule_type, "operator_version": REGISTERED_METRIC_OPERATOR_VERSION, "allowed_outcomes": ["pass", "partial", "fail", "unknown"], "unknown_policy": "fail_closed", }, "parameters": _mapping(decision.get("parameters")), "parameter_provenance": {"source": "decision_rule.parameters", "validation": "metric_contract_compliance"}, "unmapped_contract_parameters": [], "reasons": reasons, "provenance": deepcopy(dict(provenance)), } def _compile_instance_cluster_grouping( *, check_id: str, source_rule_type: str, subjects: Sequence[str], params: Mapping[str, Any], decision: Mapping[str, Any], provenance: Mapping[str, Any], ) -> dict[str, Any]: """Lower the reviewed adaptive proximity graph into numeric parameters.""" from pvr_eval.agent.contract_metric_binding import ( # local import avoids module-init cycle canonical_rule_type, metric_capability, metric_contract_compliance, ) raw = _mapping(decision.get("parameters")) consumed = { "proximity_edge_threshold", "meaningful_component_minimum", "dominant_cluster_fraction", "partial_cluster_fraction", "source_instance_annotations", "matching_classification_labels", "minimum_output_roster_coverage_for_geometry", "source_stationary_overlap_threshold", "maximum_instance_area_fraction", } unmapped = sorted(set(raw) - consumed) reasons: list[str] = [] if not check_id: reasons.append("missing_check_id") if not subjects: reasons.append("missing_subject_queries") if unmapped: reasons.append("unmapped_contract_parameters") source_annotations = [ deepcopy(dict(item)) for item in _list(raw.get("source_instance_annotations")) if isinstance(item, Mapping) ] annotation_ids: set[str] = set() for index, item in enumerate(source_annotations): bbox = item.get("bbox_xyxy") instance_id = str(item.get("instance_id") or "").strip() group_id = str(item.get("group_id") or "").strip() if not isinstance(bbox, (list, tuple)) or len(bbox) != 4: reasons.append(f"source_annotation_{index}_bbox_invalid") else: try: x0, y0, x1, y1 = [float(value) for value in bbox] if x1 <= x0 or y1 <= y0: reasons.append(f"source_annotation_{index}_bbox_invalid") except (TypeError, ValueError): reasons.append(f"source_annotation_{index}_bbox_invalid") if not instance_id or instance_id in annotation_ids: reasons.append(f"source_annotation_{index}_instance_id_invalid") annotation_ids.add(instance_id) if not group_id: reasons.append(f"source_annotation_{index}_group_missing") if not source_annotations: reasons.append("fixed_source_roster_required") classification_labels = _dedupe_text(_list(raw.get("matching_classification_labels"))) if not classification_labels: classification_labels = _dedupe_text( [str(item.get("group_id") or "") for item in source_annotations] ) classification_labels = [value for value in classification_labels if value != "other animal"] if classification_labels: classification_labels.append("other animal") else: reasons.append("matching_classification_labels_required") proximity = raw.get("proximity_edge_threshold") proximity_text = str(proximity or "").lower() edge_fraction_match = re.search(r"([0-9]*\.?[0-9]+)\s*(?:image\s*)?diagonal", proximity_text) diameter_match = re.search(r"([0-9]*\.?[0-9]+)\s*times\s*median", proximity_text) if isinstance(proximity, (int, float)): minimum_edge_fraction = float(proximity) diameter_multiplier = 0.0 elif edge_fraction_match and diameter_match: minimum_edge_fraction = float(edge_fraction_match.group(1)) diameter_multiplier = float(diameter_match.group(1)) else: minimum_edge_fraction = 0.08 diameter_multiplier = 2.5 reasons.append("proximity_edge_threshold_not_parsed") meaningful_match = re.search(r"(\d+)", str(raw.get("meaningful_component_minimum") or "2")) minimum_component_size = int(meaningful_match.group(1)) if meaningful_match else 0 if minimum_component_size < 2: reasons.append("meaningful_component_minimum_not_compiled") pass_fraction = float(raw.get("dominant_cluster_fraction", 0.9)) partial_fraction = float(raw.get("partial_cluster_fraction", 0.6)) if not (0.0 <= partial_fraction <= pass_fraction <= 1.0): reasons.append("invalid_cluster_fraction_thresholds") normalized = { "minimum_detector_confidence": 0.20, "minimum_match_confidence": 0.45, "maximum_instance_area_fraction": float(raw.get("maximum_instance_area_fraction", 0.08)), "minimum_edge_fraction_of_image_diagonal": minimum_edge_fraction, # The reviewed rule is max(fraction*diagonal, multiplier*diameter) # and declares no smaller cap. A cap of one image diagonal preserves # that rule while keeping the numeric operator bounded. "maximum_edge_fraction_of_image_diagonal": 1.0, "median_instance_diameter_multiplier": diameter_multiplier, "minimum_meaningful_component_size": minimum_component_size, "dominant_cluster_fraction": pass_fraction, "partial_cluster_fraction": partial_fraction, "source_instance_annotations": source_annotations, "source_annotation_mask_profile": _verified_source_mask_profile(source_annotations), "matching_classification_labels": classification_labels, "matching_use_segmenter_proposals": bool(source_annotations), "matching_segmenter_min_area_fraction": 0.00003, "matching_segmenter_max_area_fraction": float(raw.get("maximum_instance_area_fraction", 0.08)), "matching_segmenter_max_proposals": 160, "matching_classification_minimum_margin": 0.0, "matching_classification_minimum_probability": 0.25, "minimum_output_roster_coverage_for_geometry": float( raw.get("minimum_output_roster_coverage_for_geometry", 0.65) ), "source_stationary_overlap_threshold": float( raw.get("source_stationary_overlap_threshold", 0.30) ), "set_level_target_roster_allowed": True, } canonical = canonical_rule_type(source_rule_type) predicate = _compile_registered_metric_bridge( check_id=check_id, source_rule_type=source_rule_type, canonical_rule_type=canonical, subjects=subjects, params=params, decision=decision, provenance=provenance, capability=metric_capability(canonical), ) predicate["subjects"] = [ _subject_group_spec( subjects, expected_count=1, group_id="small_animal_target_roster", ) ] if subjects else [] predicate["parameters"] = normalized predicate["parameter_provenance"] = { "minimum_edge_fraction_of_image_diagonal": "proximity_edge_threshold", "median_instance_diameter_multiplier": "proximity_edge_threshold", "minimum_meaningful_component_size": "meaningful_component_minimum", "dominant_cluster_fraction": "dominant_cluster_fraction", "partial_cluster_fraction": "partial_cluster_fraction", "source_instance_annotations": "source_instance_annotations:manual_input_fact", "matching_classification_labels": "matching_classification_labels", "minimum_output_roster_coverage_for_geometry": "minimum_output_roster_coverage_for_geometry", "source_stationary_overlap_threshold": "source_stationary_overlap_threshold", } predicate["unmapped_contract_parameters"] = unmapped compliance = metric_contract_compliance(source_rule_type, normalized, decision) predicate["contract_compliance"] = compliance if compliance.get("status") != "compliant": reasons.extend(["contract_handler_incompatible", *compliance.get("risk_flags", [])]) predicate["reasons"] = list(dict.fromkeys((*predicate.get("reasons", []), *reasons))) predicate["status"] = "executable" if not predicate["reasons"] else "blocked_uncompiled" return predicate def _compile_small_animal_set_geometry( *, check_id: str, source_rule_type: str, subjects: Sequence[str], params: Mapping[str, Any], decision: Mapping[str, Any], provenance: Mapping[str, Any], ) -> dict[str, Any]: """Compile dense small-animal checks as set geometry, not fake identity. The input roster is a reviewed case fact. The output remains entirely tool-derived: detector and FastSAM proposals are filtered by closed-set CLIP, then the metric consumes the accepted output set and masks. """ from pvr_eval.agent.contract_metric_binding import ( # local import avoids module-init cycle canonical_rule_type, metric_capability, metric_contract_compliance, ) raw = _mapping(decision.get("parameters")) common = { "source_instance_annotations", "matching_classification_labels", "minimum_output_roster_coverage_for_geometry", "source_stationary_overlap_threshold", "maximum_instance_area_fraction", "protected_subject_source_annotations", "protected_subject_minimum_identity_confidence", } supported = { "protected_zone_exclusion_count": common | { "immediate_vicinity_dilation", "touch_tolerance_pixels", "minimum_match_confidence", }, "cluster_protected_subject_gap": common | { "clear_gap_threshold", "slight_overlap_fraction_max", "substantial_overlap_fraction", "cluster_proximity_edge_threshold", "meaningful_component_minimum", "dominant_cluster_minimum_fraction", }, } unmapped = sorted(set(raw) - supported.get(source_rule_type, set())) reasons: list[str] = [] if not check_id: reasons.append("missing_check_id") if unmapped: reasons.append("unmapped_contract_parameters") protected_terms = ("moose", "bear", "robot") protected_queries = [ subject for subject in subjects if any(term in subject.lower() for term in protected_terms) ] target_queries = [ subject for subject in subjects if subject not in protected_queries ] if not target_queries: reasons.append("small_animal_subject_queries_missing") if len(protected_queries) < 3: reasons.append("protected_subject_queries_incomplete") source_annotations = [ deepcopy(dict(item)) for item in _list(raw.get("source_instance_annotations")) if isinstance(item, Mapping) ] annotation_ids: set[str] = set() for index, item in enumerate(source_annotations): bbox = item.get("bbox_xyxy") instance_id = str(item.get("instance_id") or "").strip() group_id = str(item.get("group_id") or "").strip() if not isinstance(bbox, (list, tuple)) or len(bbox) != 4: reasons.append(f"source_annotation_{index}_bbox_invalid") else: try: x0, y0, x1, y1 = [float(value) for value in bbox] if x1 <= x0 or y1 <= y0: reasons.append(f"source_annotation_{index}_bbox_invalid") except (TypeError, ValueError): reasons.append(f"source_annotation_{index}_bbox_invalid") if not instance_id or instance_id in annotation_ids: reasons.append(f"source_annotation_{index}_instance_id_invalid") annotation_ids.add(instance_id) if not group_id: reasons.append(f"source_annotation_{index}_group_missing") if not source_annotations: reasons.append("fixed_source_roster_required") classification_labels = _dedupe_text(_list(raw.get("matching_classification_labels"))) if not classification_labels: classification_labels = _dedupe_text( [str(item.get("group_id") or "") for item in source_annotations] ) classification_labels = [value for value in classification_labels if value != "other animal"] if classification_labels: classification_labels.append("other animal") else: reasons.append("matching_classification_labels_required") verified_roster_expected_counts: dict[str, int] = {} for item in source_annotations: group_id = str(item.get("group_id") or "").strip() if group_id: verified_roster_expected_counts[group_id] = ( verified_roster_expected_counts.get(group_id, 0) + 1 ) protected_source_annotations = [ deepcopy(dict(item)) for item in _list(raw.get("protected_subject_source_annotations")) if isinstance(item, Mapping) ] for index, item in enumerate(protected_source_annotations): bbox = item.get("bbox_xyxy") instance_id = str(item.get("instance_id") or "").strip() group_id = str(item.get("group_id") or "").strip() if not instance_id: reasons.append(f"protected_source_annotation_{index}_instance_id_invalid") if group_id not in protected_queries: reasons.append(f"protected_source_annotation_{index}_group_invalid") if not isinstance(bbox, (list, tuple)) or len(bbox) != 4: reasons.append(f"protected_source_annotation_{index}_bbox_invalid") else: try: x0, y0, x1, y1 = [float(value) for value in bbox] if x1 <= x0 or y1 <= y0: reasons.append(f"protected_source_annotation_{index}_bbox_invalid") except (TypeError, ValueError): reasons.append(f"protected_source_annotation_{index}_bbox_invalid") if protected_source_annotations and ( len(protected_source_annotations) != len(protected_queries) or {str(item.get("group_id") or "") for item in protected_source_annotations} != set(protected_queries) ): reasons.append("protected_source_annotation_roster_incomplete") normalized: dict[str, Any] = { "source_instance_annotations": source_annotations, "source_annotation_mask_profile": _verified_source_mask_profile(source_annotations), "expected_source_count": len(source_annotations), "protected_subject_queries": protected_queries, "minimum_detector_confidence": 0.15, "minimum_match_confidence": float(raw.get("minimum_match_confidence", 0.45)), "maximum_instance_area_fraction": float(raw.get("maximum_instance_area_fraction", 0.08)), "matching_classification_labels": classification_labels, "matching_use_segmenter_proposals": bool(source_annotations), "matching_segmenter_min_area_fraction": 0.00003, "matching_segmenter_max_area_fraction": float(raw.get("maximum_instance_area_fraction", 0.08)), "matching_segmenter_max_proposals": 160, "matching_classification_minimum_margin": 0.0, "matching_classification_minimum_probability": 0.25, "minimum_output_roster_coverage_for_geometry": float( raw.get("minimum_output_roster_coverage_for_geometry", 0.65) ), "source_stationary_overlap_threshold": float( raw.get("source_stationary_overlap_threshold", 0.30) ), "set_level_target_roster_allowed": True, "verified_roster_profile": "verified_group_roster_assignment_v1", "verified_roster_assignment_mode": "question_support_allowed_edit_coverage_v1", "verified_roster_expected_counts": verified_roster_expected_counts, "verified_roster_minimum_area_ratio": 0.10, "verified_roster_maximum_area_ratio": 6.0, "identity_agnostic_target_coverage_profile": ( "identity_agnostic_target_animal_coverage_v1" ), "target_coverage_minimum_probability": 0.50, "target_coverage_minimum_margin": 0.15, "target_coverage_minimum_animal_probability": 0.75, "target_coverage_minimum_animal_margin": 0.50, "target_coverage_maximum_protected_overlap": 0.10, "target_coverage_neighborhood_fraction_of_diagonal": 0.08, "protected_subject_certificate_required": True, "protected_classification_minimum_margin": 0.0, "protected_classification_minimum_probability": 0.25, **( { "protected_subject_source_annotations": protected_source_annotations, "protected_subject_source_mask_profile": ( VERIFIED_PROTECTED_SOURCE_MASK_PROFILE ), "protected_subject_minimum_identity_confidence": float( raw.get("protected_subject_minimum_identity_confidence", 0.45) ), } if protected_source_annotations else {} ), } if source_rule_type == "protected_zone_exclusion_count": dilation = str(raw.get("immediate_vicinity_dilation") or "").lower() fraction_match = re.search(r"([0-9]*\.?[0-9]+)\s*(?:image\s*)?diagonal", dilation) diameter_match = re.search(r"([0-9]*\.?[0-9]+)\s*times\s*median", dilation) if not fraction_match or not diameter_match: reasons.append("immediate_vicinity_dilation_not_parsed") normalized.update( { "vicinity_fraction_of_image_diagonal": float(fraction_match.group(1)) if fraction_match else 0.02, "vicinity_median_instance_diameter_multiplier": float(diameter_match.group(1)) if diameter_match else 0.5, "touch_tolerance_pixels": int(raw.get("touch_tolerance_pixels", 3)), "partial_max_violating_instances": 2, "fail_min_violating_instances": 3, "fail_majority_source_roster_fraction": 0.5, } ) else: gap = str(raw.get("clear_gap_threshold") or "").lower() gap_fraction = re.search(r"([0-9]*\.?[0-9]+)\s*(?:image\s*)?diagonal", gap) gap_diameter = re.search(r"([0-9]*\.?[0-9]+)\s*times\s*median", gap) proximity = str(raw.get("cluster_proximity_edge_threshold") or "").lower() edge_fraction = re.search(r"([0-9]*\.?[0-9]+)\s*(?:image\s*)?diagonal", proximity) edge_diameter = re.search(r"([0-9]*\.?[0-9]+)\s*times\s*median", proximity) meaningful = re.search(r"(\d+)", str(raw.get("meaningful_component_minimum") or "2")) if not gap_fraction or not gap_diameter: reasons.append("clear_gap_threshold_not_parsed") if not edge_fraction or not edge_diameter: reasons.append("cluster_proximity_edge_threshold_not_parsed") normalized.update( { "clear_gap_fraction_of_image_diagonal": float(gap_fraction.group(1)) if gap_fraction else 0.02, "clear_gap_median_instance_diameter_multiplier": float(gap_diameter.group(1)) if gap_diameter else 0.5, "slight_overlap_fraction_max": float(raw.get("slight_overlap_fraction_max", 0.02)), "substantial_overlap_fraction": float(raw.get("substantial_overlap_fraction", 0.02)), "minimum_edge_fraction_of_image_diagonal": float(edge_fraction.group(1)) if edge_fraction else 0.08, "median_instance_diameter_multiplier": float(edge_diameter.group(1)) if edge_diameter else 2.5, "minimum_meaningful_component_size": int(meaningful.group(1)) if meaningful else 2, "dominant_cluster_minimum_fraction": float(raw.get("dominant_cluster_minimum_fraction", 0.60)), "cluster_envelope_buffer_pixels": 3, } ) canonical = canonical_rule_type(source_rule_type) predicate = _compile_registered_metric_bridge( check_id=check_id, source_rule_type=source_rule_type, canonical_rule_type=canonical, subjects=subjects, params=params, decision=decision, provenance=provenance, capability=metric_capability(canonical), ) target_group = _subject_group_spec( target_queries, expected_count=max(1, len(source_annotations)), group_id="small_animal_target_roster", ) target_group["output_queries"] = _dedupe_text(target_queries) protected_group = _subject_group_spec( protected_queries, expected_count=3, group_id="protected_subjects", ) predicate["subjects"] = [target_group, protected_group] predicate["parameters"] = normalized predicate.setdefault("provenance", {})[ "small_animal_geometry_executor_version" ] = SMALL_ANIMAL_GEOMETRY_EXECUTOR_VERSION predicate["parameter_provenance"] = { "source_instance_annotations": "source_instance_annotations:manual_input_fact", "matching_classification_labels": "matching_classification_labels", "protected_subject_queries": "object_queries:moose,bear,robot", "verified_roster_profile": "shared_verified_group_roster_assignment_v1", "identity_agnostic_target_coverage_profile": ( "shared_identity_agnostic_target_animal_coverage_v1" ), "protected_subject_certificate_required": "shared_protected_subject_roster_clearance_v1", "geometry_thresholds": "decision_rule.parameters", } predicate["unmapped_contract_parameters"] = unmapped compliance = metric_contract_compliance(source_rule_type, normalized, decision) predicate["contract_compliance"] = compliance if compliance.get("status") != "compliant": reasons.extend(["contract_handler_incompatible", *compliance.get("risk_flags", [])]) predicate["reasons"] = list(dict.fromkeys((*predicate.get("reasons", []), *reasons))) predicate["status"] = "executable" if not predicate["reasons"] else "blocked_uncompiled" return predicate def _compile_structured_check( *, check_id: str, source_rule_type: str, subjects: Sequence[str], params: Mapping[str, Any], decision: Mapping[str, Any], provenance: Mapping[str, Any], ) -> dict[str, Any]: """Compile one reviewed case parser as a terminal deterministic call. Structured visual states do not share a safe universal detector schema. The parser therefore owns the complete reviewed rule parameters and emits a standardized atomic result. Semantic planned regions are consumed by the case adapter (or by explicit geometry in the rule), rather than being silently reinterpreted as open-vocabulary object queries. """ raw = _mapping(decision.get("parameters")) planned_ids = [ str(item.get("region_id") or item.get("id") or "").strip() for item in _planned_regions(params) if str(item.get("region_id") or item.get("id") or "").strip() ] subject_groups = [ _subject_group_spec((subject,), expected_count=1) for subject in _dedupe_text(subjects) ] or [ _subject_group_spec( (check_id.replace("_", " "),), expected_count=1, group_id="structured_case_state", ) ] operations: list[dict[str, Any]] = [] dependencies: list[str] = [] if source_rule_type in { "expected_date_digit_transition", "dial_graphics_preservation", "flowchart_structure_preservation", "inputs_card_integrity", "card_text_identity_preservation", "identity_loss_penalty", "unrequested_annotation_penalty", "paired_text_legibility_preservation", "card_content_preservation", "grid_and_labels_intact", "all_required_text_and_icons_intact", "all_required_labels_legible_and_aligned", "ordered_label_preservation", }: paired_ocr_rules = { "inputs_card_integrity", "identity_loss_penalty", "unrequested_annotation_penalty", "grid_and_labels_intact", } roles = ("input", "pred") if "preservation" in source_rule_type or source_rule_type in paired_ocr_rules else ("pred",) operations.append( _operation("read_structured_text", "ocr", "ocr", roles, produces=("structured_text",)) ) dependencies.append("read_structured_text") if source_rule_type in { "assigned_vehicle_slot_predicate", "accessible_vehicle_slot_predicate", "any_assigned_vehicle_boundary_violation", "audit_only_required_identity_count", "required_pair_in_target_zone", "all_sources_vacated_no_forbidden_zone_instances", "all_item_attributes_preserved", "source_instance_vacancy", }: operations.extend( [ _operation( "detect_structured_objects", "object_detection", "detector", ("pred",), produces=("structured_object_boxes",), ), _operation( "refine_structured_objects", "mask_refinement", "segmenter", ("pred",), depends_on=("detect_structured_objects",), produces=("structured_object_masks",), ), ] ) dependencies.append("refine_structured_objects") if source_rule_type in { "needle_instance_preservation", "dial_graphics_preservation", "registered_invariant_region_preservation", "watch_structure_relocation_violation", "non_target_component_integrity_violation", "occlusion_aware_marking_preservation", "flowchart_structure_preservation", "inputs_card_integrity", "multi_region_background_preservation", "structural_invariant_preservation", "multi_entity_integrity", "protected_roi_exact_preservation", "paired_text_legibility_preservation", "card_content_preservation", "grid_and_labels_intact", "tray_and_contents_preserved", "all_instances_intact_and_stationary", "registered_card_preservation", "invariant_background_preservation", "invariant_region_preserved", "ordered_label_preservation", "invariant_structure_integrity", }: operations.extend( [ _operation( "register_structured_frames", "image_registration", "registration", ("input", "pred"), produces=("structured_transform",), ), _operation( "measure_structured_change", "change_analysis", "change_analyzer", ("input", "pred"), depends_on=("register_structured_frames",), produces=("structured_change",), ), ] ) dependencies.append("measure_structured_change") operations.append( _operation( "run_structured_checker", "structured_check", "structured_checker", ("input", "pred"), depends_on=tuple(dict.fromkeys(dependencies)), parameters={"adapter": "pvr_structured_contract_v1", "source_rule_type": source_rule_type}, produces=("structured_check_result",), ) ) return { "schema_version": EXECUTABLE_PREDICATE_SCHEMA_VERSION, "check_id": check_id, "status": "executable", "family": "structured_case_parser", "source_rule_type": source_rule_type, "subjects": subject_groups, "regions": [], "explicitly_ignored_region_ids": planned_ids, "operations": operations, "state_schema": { "unit": "atomic_structured_visual_state", "states": ["pass", "partial", "fail", "unknown"], "facts": ["parser_measurements", "contract_thresholds", "evidence_overlay"], }, "decision": { "pass": {"parser_status": "pass"}, "partial": {"parser_status": "partial"}, "fail": {"parser_status": "fail"}, "unknown": {"parser_status": "unknown"}, }, "parameters": { "adapter": "pvr_structured_contract_v1", "source_rule_type": source_rule_type, "decision_parameters": raw, "planned_region_ids": planned_ids, "zero_vlm": True, }, "parameter_provenance": { "decision_parameters": "reviewed decision_rule.parameters", "planned_region_ids": "reviewed planned_regions", "adapter": "versioned deterministic case parser", }, "unmapped_contract_parameters": [], "reasons": [], "provenance": deepcopy(dict(provenance)), } def compile_executable_predicate(check: Mapping[str, Any]) -> dict[str, Any]: """Compile one prepared contract check into a validated predicate. An explicit predicate authored in the source contract wins. Generated predicates are currently limited to the source-region clearance family; other rules are retained as blocked records until their semantics have a dedicated compiler and interpreter. """ check_id = str(check.get("id") or check.get("check_id") or "").strip() params = _mapping(check.get("params")) decision = _mapping(params.get("decision_rule")) source_rule_type = str(decision.get("type") or "").strip() explicit = check.get("executable_predicate") or params.get("executable_predicate") if isinstance(explicit, Mapping): predicate = deepcopy(dict(explicit)) provenance = predicate.get("provenance") if isinstance(predicate.get("provenance"), Mapping) else {} capabilities = predicate.get("capability_versions") if isinstance(predicate.get("capability_versions"), Mapping) else {} source_annotation_mask_rules = ( FIXED_LOCATION_PRESERVATION_RULES | SOURCE_DISPLACEMENT_RULES | INSTANCE_CLUSTER_GROUPING_RULES | PROTECTED_SET_EXCLUSION_RULES | CLUSTER_SUBJECT_SEPARATION_RULES ) if ( provenance.get("compiler") == "pvr_eval.agent.executable_predicate.compile_executable_predicate" and source_rule_type in source_annotation_mask_rules and bool(_list(_mapping(decision.get("parameters")).get("source_instance_annotations"))) and provenance.get("source_annotation_mask_policy_version") != VERIFIED_SOURCE_MASK_CAPABILITY_VERSION ): # Generated IR is a cache, not authored contract truth. Rebuild # it when the runtime evidence policy advances; hand-authored IR # never enters this branch. source_check = deepcopy(dict(check)) source_check.pop("executable_predicate", None) source_params = _mapping(source_check.get("params")) source_params.pop("executable_predicate", None) source_check["params"] = source_params return compile_executable_predicate(source_check) if ( provenance.get("compiler") == "pvr_eval.agent.executable_predicate.compile_executable_predicate" and source_rule_type in (PROTECTED_SET_EXCLUSION_RULES | CLUSTER_SUBJECT_SEPARATION_RULES) and provenance.get("small_animal_geometry_executor_version") != SMALL_ANIMAL_GEOMETRY_EXECUTOR_VERSION ): source_check = deepcopy(dict(check)) source_check.pop("executable_predicate", None) source_params = _mapping(source_check.get("params")) source_params.pop("executable_predicate", None) source_check["params"] = source_params return compile_executable_predicate(source_check) if ( provenance.get("compiler") == "pvr_eval.agent.executable_predicate.compile_executable_predicate" and str(predicate.get("family") or "") == "registered_metric_bridge" and "stale_registered_metric_operator_version" in validate_executable_predicate(predicate).reasons ): # Generated bridge IR is a cache. Refresh it whenever the shared # registered metric operator advances; otherwise a schema-valid # embedded predicate can silently omit newly required evidence. source_check = deepcopy(dict(check)) source_check.pop("executable_predicate", None) source_params = _mapping(source_check.get("params")) source_params.pop("executable_predicate", None) source_check["params"] = source_params return compile_executable_predicate(source_check) if provenance.get("compiler") == "pvr_eval.contracts.predicate_lowering.lower_reviewed_predicate": from pvr_eval.contracts.predicate_lowering import ( LOWERER_VERSION, VERIFIED_GROUP_ROSTER_PROFILE, lower_reviewed_predicate, reviewed_source_check_sha256, ) source_hash_stale = ( str(predicate.get("source_check_sha256") or "") != reviewed_source_check_sha256(check) ) predicate_parameters = _mapping(predicate.get("parameters")) articulated_executor_stale = bool( predicate_parameters.get("articulated_entity_preservation_profile") == ARTICULATED_ENTITY_PRESERVATION_PROFILE and predicate_parameters.get("articulated_entity_preservation_executor_version") != ARTICULATED_ENTITY_PRESERVATION_EXECUTOR_VERSION ) source_decision = _mapping(_mapping(_mapping(check.get("params")).get("decision_rule")).get("parameters")) verified_roster_executor_stale = bool( source_decision.get("source_roster_complete") is True and isinstance(source_decision.get("source_roster_expected_counts"), Mapping) and source_decision.get("source_instance_annotations") and predicate_parameters.get("verified_roster_profile") != VERIFIED_GROUP_ROSTER_PROFILE ) if ( capabilities.get("lowerer") != LOWERER_VERSION or source_hash_stale or articulated_executor_stale or verified_roster_executor_stale ): refreshed = lower_reviewed_predicate(check) if refreshed is not None: predicate = refreshed elif ( provenance.get("compiler") == "pvr_eval.agent.executable_predicate.compile_executable_predicate" and str(predicate.get("status") or "") in {"manual_review_required", "blocked_uncompiled"} ): from pvr_eval.contracts.predicate_ir_candidate import RULE_FAMILY_TARGETS from pvr_eval.contracts.predicate_lowering import lower_reviewed_predicate if source_rule_type in RULE_FAMILY_TARGETS: refreshed = lower_reviewed_predicate(check) if refreshed is not None: predicate = refreshed predicate.setdefault("schema_version", EXECUTABLE_PREDICATE_SCHEMA_VERSION) predicate.setdefault("check_id", check_id) validation = validate_executable_predicate(predicate) if validation.valid: return predicate predicate["status"] = "blocked_invalid" predicate["reasons"] = list(dict.fromkeys((*_list(predicate.get("reasons")), *validation.reasons))) return predicate subjects = _subjects(params) provenance = { "compiler": "pvr_eval.agent.executable_predicate.compile_executable_predicate", "source_annotation_mask_policy_version": VERIFIED_SOURCE_MASK_CAPABILITY_VERSION, "question": str(check.get("question") or check.get("description") or ""), "pass_criteria": str(check.get("pass_criteria") or ""), "partial_criteria": str(check.get("partial_criteria") or ""), "fail_criteria": str(check.get("fail_criteria") or ""), "decision_conditions": { key: str(decision.get(key) or "") for key in ("pass_condition", "partial_condition", "fail_condition") }, } # The reviewed natural-language backlog is promoted only through the # golden candidate IR and deterministic six-family lowerer. This branch # intentionally precedes legacy aliases, whose coarse handlers consumed # only a small subset of the reviewed parameters. from pvr_eval.contracts.predicate_lowering import lower_reviewed_predicate reviewed = lower_reviewed_predicate(check) if reviewed is not None: validation = validate_executable_predicate(reviewed) if not validation.valid and reviewed.get("status") == "executable": reviewed["status"] = "blocked_invalid" reviewed["reasons"] = list( dict.fromkeys((*reviewed.get("reasons", []), *validation.reasons)) ) return reviewed if source_rule_type in SURFACE_RESIDUAL_INVENTORY_RULES: predicate = _compile_surface_residual_inventory( check_id=check_id, source_rule_type=source_rule_type, subjects=subjects, params=params, decision=decision, provenance=provenance, ) validation = validate_executable_predicate(predicate) if not validation.valid and predicate.get("status") == "executable": predicate["status"] = "blocked_invalid" predicate["reasons"] = list(dict.fromkeys((*predicate["reasons"], *validation.reasons))) return predicate if source_rule_type in DESTINATION_MEMBERSHIP_RULES: predicate = _compile_destination_membership( check_id=check_id, source_rule_type=source_rule_type, subjects=subjects, params=params, decision=decision, provenance=provenance, ) validation = validate_executable_predicate(predicate) if not validation.valid and predicate.get("status") == "executable": predicate["status"] = "blocked_invalid" predicate["reasons"] = list(dict.fromkeys((*predicate["reasons"], *validation.reasons))) return predicate if source_rule_type in RELOCATION_TRANSITION_RULES: predicate = _compile_relocation_transition( check_id=check_id, source_rule_type=source_rule_type, subjects=subjects, params=params, decision=decision, provenance=provenance, ) validation = validate_executable_predicate(predicate) if not validation.valid and predicate.get("status") == "executable": predicate["status"] = "blocked_invalid" predicate["reasons"] = list(dict.fromkeys((*predicate["reasons"], *validation.reasons))) return predicate if source_rule_type in CROSS_IMAGE_INVENTORY_RULES: predicate = _compile_cross_image_inventory( check_id=check_id, source_rule_type=source_rule_type, subjects=subjects, decision=decision, provenance=provenance, ) validation = validate_executable_predicate(predicate) if not validation.valid and predicate.get("status") == "executable": predicate["status"] = "blocked_invalid" predicate["reasons"] = list(dict.fromkeys((*predicate["reasons"], *validation.reasons))) return predicate if source_rule_type in FIXED_LOCATION_PRESERVATION_RULES: predicate = _compile_fixed_location_preservation( check_id=check_id, source_rule_type=source_rule_type, subjects=subjects, decision=decision, provenance=provenance, ) validation = validate_executable_predicate(predicate) if not validation.valid and predicate.get("status") == "executable": predicate["status"] = "blocked_invalid" predicate["reasons"] = list(dict.fromkeys((*predicate["reasons"], *validation.reasons))) return predicate if source_rule_type in OCR_TEXT_RULES: predicate = _compile_ocr_text_predicate( check_id=check_id, source_rule_type=source_rule_type, subjects=subjects, params=params, decision=decision, provenance=provenance, ) validation = validate_executable_predicate(predicate) if not validation.valid and predicate.get("status") == "executable": predicate["status"] = "blocked_invalid" predicate["reasons"] = list(dict.fromkeys((*predicate["reasons"], *validation.reasons))) return predicate if source_rule_type in SOURCE_DISPLACEMENT_RULES: predicate = _compile_source_displacement( check_id=check_id, source_rule_type=source_rule_type, subjects=subjects, decision=decision, provenance=provenance, ) validation = validate_executable_predicate(predicate) if not validation.valid and predicate.get("status") == "executable": predicate["status"] = "blocked_invalid" predicate["reasons"] = list(dict.fromkeys((*predicate["reasons"], *validation.reasons))) return predicate if source_rule_type in SOURCE_REGION_RESTORATION_RULES: predicate = _compile_source_region_restoration( check_id=check_id, source_rule_type=source_rule_type, subjects=subjects, decision=decision, provenance=provenance, ) validation = validate_executable_predicate(predicate) if not validation.valid and predicate.get("status") == "executable": predicate["status"] = "blocked_invalid" predicate["reasons"] = list(dict.fromkeys((*predicate["reasons"], *validation.reasons))) return predicate if source_rule_type in INSTANCE_CLUSTER_GROUPING_RULES: predicate = _compile_instance_cluster_grouping( check_id=check_id, source_rule_type=source_rule_type, subjects=subjects, params=params, decision=decision, provenance=provenance, ) validation = validate_executable_predicate(predicate) if not validation.valid and predicate.get("status") == "executable": predicate["status"] = "blocked_invalid" predicate["reasons"] = list(dict.fromkeys((*predicate["reasons"], *validation.reasons))) return predicate if source_rule_type in PROTECTED_SET_EXCLUSION_RULES | CLUSTER_SUBJECT_SEPARATION_RULES: predicate = _compile_small_animal_set_geometry( check_id=check_id, source_rule_type=source_rule_type, subjects=subjects, params=params, decision=decision, provenance=provenance, ) validation = validate_executable_predicate(predicate) if not validation.valid and predicate.get("status") == "executable": predicate["status"] = "blocked_invalid" predicate["reasons"] = list(dict.fromkeys((*predicate["reasons"], *validation.reasons))) return predicate if source_rule_type in STRUCTURED_CHECK_RULES: predicate = _compile_structured_check( check_id=check_id, source_rule_type=source_rule_type, subjects=subjects, params=params, decision=decision, provenance=provenance, ) validation = validate_executable_predicate(predicate) if not validation.valid and predicate.get("status") == "executable": predicate["status"] = "blocked_invalid" predicate["reasons"] = list(dict.fromkeys((*predicate["reasons"], *validation.reasons))) return predicate # All previously registered deterministic metrics are represented as a # typed operator bridge. The bridge consumes only predicate operations, # typed regions, and normalized parameters; legacy tool prose is never # consulted by the lowerer. from pvr_eval.agent.contract_metric_binding import ( # local import avoids module-init cycle REGISTERED_RULE_TYPES, canonical_rule_type as canonicalize_rule_type, metric_contract_compliance, metric_capability, ) canonical = canonicalize_rule_type(source_rule_type) if canonical in REGISTERED_RULE_TYPES and source_rule_type not in SOURCE_REGION_CLEARANCE_RULES: compliance = metric_contract_compliance( source_rule_type, _mapping(decision.get("parameters")), decision, ) predicate = _compile_registered_metric_bridge( check_id=check_id, source_rule_type=source_rule_type, canonical_rule_type=canonical, subjects=subjects, params=params, decision=decision, provenance=provenance, capability=metric_capability(canonical), ) predicate["contract_compliance"] = compliance if compliance.get("status") != "compliant": predicate["status"] = "blocked_uncompiled" predicate["reasons"] = list( dict.fromkeys( ( *predicate.get("reasons", []), "contract_handler_incompatible", *[str(item) for item in compliance.get("risk_flags", [])], ) ) ) validation = validate_executable_predicate(predicate) if not validation.valid and predicate.get("status") == "executable": predicate["status"] = "blocked_invalid" predicate["reasons"] = list(dict.fromkeys((*predicate["reasons"], *validation.reasons))) return predicate if source_rule_type not in SOURCE_REGION_CLEARANCE_RULES: subjective_rules = { "semantic_physical_overlap_plausibility", "relocated_item_perspective_plausibility", "physical_support_and_nonintersection", "flight_posture_semantic_classification", "localized_inpainting_artifact_classification", "species_support_plausibility", "per_instance_support_plausibility", "vacated_patch_artifact_audit", "folded_chair_physical_state", "localized_background_reconstruction_quality", "supported_nonintersecting_placement", } manual = str(check.get("checker") or params.get("resolved_plan_checker") or "") == "vlm_audit" or source_rule_type in subjective_rules return _blocked( check_id=check_id, source_rule_type=source_rule_type, family="", subjects=subjects, reasons=[("manual_review_required:" if manual else "predicate_family_not_compiled:") + (source_rule_type or "missing_decision_rule")], provenance=provenance, status="manual_review_required" if manual else "blocked_uncompiled", ) raw = _mapping(decision.get("parameters")) expected_count, expected_key = _positive_int( raw, "expected_source_count", "expected_input_count", "required_removed_count_for_pass" ) if expected_count <= 0: if source_rule_type in {"counted_pair_removal", "paired_zoned_instance_removal"}: expected_count, expected_key = 2, "derived:paired_rule" elif source_rule_type in { "source_zone_vacancy", "zoned_instance_absence_with_residual_test", "small_zoned_instance_absence_with_residual_test", }: expected_count, expected_key = 1, "derived:single_source_rule" output_score, output_score_key = _number( raw, ( "minimum_detection_confidence", "output_detection_confidence", "output_detection_confidence_fail", "per_item_detection_confidence_fail", "minimum_detector_confidence", "output_bird_detection_threshold", ), 0.15, ) input_score, input_score_key = _number( raw, ("source_input_minimum_detector_confidence", "input_detection_confidence"), min(0.05, output_score), ) source_overlap, source_overlap_key = _number( raw, ( "source_overlap_threshold", "zone_containment_threshold", ), 0.15, ) pass_residual, pass_residual_key = _number( raw, ("pass_residual_fraction_max", "pass_max_residual_ratio"), 0.0, ) partial_residual, partial_residual_key = _number( raw, ( "partial_residual_fraction_max", "partial_max_residual_ratio", "residual_mask_fraction_partial", "per_item_residual_fraction_partial", "orange_residual_fraction_partial", ), max(pass_residual, 0.03), ) intact_residual, intact_residual_key = _number( raw, ( "intact_mask_fraction_fail", "per_item_intact_mask_fraction_fail", "fail_min_residual_ratio", "substantial_zone_overlap", ), max(0.25, partial_residual), ) supported_by_rule = { "colored_container_visibility_count": { "expected_source_count", "minimum_detection_confidence", "source_zone_vacancy_required_for_pass", "confirm_with_color_and_shape", "full_frame_search", "closed_cabinet_storage_counts_as_not_visible", "source_anchor_query", }, "paired_zoned_instance_removal": { "required_removed_count_for_pass", "per_item_detection_confidence_fail", "per_item_intact_mask_fraction_fail", "per_item_residual_fraction_partial", "zone_expansion_pixels", }, "counted_pair_removal": { "expected_input_count", "fail_output_count_min", "orange_residual_fraction_partial", "output_detection_confidence", "partial_output_count", "pass_output_count", "zone_expansion_pixels", }, "source_zone_vacancy": { "output_bird_detection_threshold", "partial_residual_fraction_max", "pass_residual_fraction_max", "substantial_zone_overlap", "minimum_detector_confidence", "pass_max_residual_ratio", "fail_min_residual_ratio", "registration_tolerance_pixels", "source_clearance_profile", "source_selector_profile", "source_selector", }, "zoned_instance_absence_with_residual_test": { "intact_mask_fraction_fail", "output_detection_confidence_fail", "query_aliases_equivalent", "residual_mask_fraction_partial", "zone_expansion_pixels", "registration_required", "registration_tolerance_pixels", }, "small_zoned_instance_absence_with_residual_test": { "intact_mask_fraction_fail", "output_detection_confidence_fail", "residual_mask_fraction_partial", "use_color_guided_proposals", "zone_expansion_pixels", }, } consumed = set(supported_by_rule.get(source_rule_type, set())) semantic_keys = { "confirm_with_color_and_shape", "full_frame_search", "source_zone_vacancy_required_for_pass", "closed_cabinet_storage_counts_as_not_visible", "source_anchor_query", } consumed.update(key for key in semantic_keys if key in raw) unmapped = sorted(set(raw) - consumed) reasons = _source_scope_conflicts(decision) source_selector_raw = raw.get("source_selector") source_selector = dict(source_selector_raw) if isinstance(source_selector_raw, Mapping) else {} source_selector_profile = str( raw.get("source_selector_profile") or source_selector.get("profile") or "" ) if source_selector_profile: source_selector["profile"] = source_selector_profile identity_queries = _dedupe_text(_list(source_selector.get("identity_queries"))) anchor_queries = _dedupe_text(_list(source_selector.get("anchor_queries"))) anchor_part = str(source_selector.get("anchor_part") or "") relation = str(source_selector.get("relation") or "") selector_expected_count = int(source_selector.get("expected_count") or 0) if source_rule_type != "source_zone_vacancy": reasons.append("source_selector_rule_unsupported") if source_selector_profile != ANCHOR_RELATIVE_SOURCE_INSTANCE_PROFILE: reasons.append("source_selector_profile_unsupported") if not identity_queries or not anchor_queries: reasons.append("source_selector_queries_missing") if anchor_part not in SUPPORTED_ANCHOR_PARTS: reasons.append("source_selector_anchor_part_unsupported") if relation != "contact_or_near": reasons.append("source_selector_relation_unsupported") if selector_expected_count != 1 or expected_count != 1: reasons.append("source_selector_expected_count_unsupported") source_selector.update( { "identity_queries": identity_queries, "anchor_queries": anchor_queries, "anchor_part": anchor_part, "relation": relation, "expected_count": selector_expected_count, } ) if identity_queries: subjects = identity_queries elif ( source_rule_type == "source_zone_vacancy" and bool(subjects) and is_relational_identity_text(subjects[0]) ): reasons.append("relational_identity_without_typed_selector") requested_clearance_profile = str(raw.get("source_clearance_profile") or "") clearance_profile_parameters: dict[str, Any] = {} if requested_clearance_profile: if ( source_rule_type == "source_zone_vacancy" and requested_clearance_profile == SHELF_SOURCE_GROUP_CLEARANCE_PROFILE ): clearance_profile_parameters = shelf_source_group_clearance_profile_parameters( requested_clearance_profile ) else: reasons.append("source_clearance_profile_unsupported") if not check_id: reasons.append("missing_check_id") if not subjects: reasons.append("missing_subject_queries") if expected_count <= 0: reasons.append("expected_source_count_not_compiled") if unmapped: reasons.append("unmapped_contract_parameters") if raw.get("source_zone_vacancy_required_for_pass") is False: reasons.append("source_vacancy_not_required_by_contract") subject_groups = _source_subject_groups( subjects, source_rule_type=source_rule_type, expected_count=expected_count, raw=raw, ) normalized = { "expected_source_count": expected_count, "subject_groups": _public_subject_groups(subject_groups), "minimum_detection_confidence": output_score, "source_input_minimum_detector_confidence": input_score, "source_overlap_threshold": source_overlap, "pass_source_residual_fraction_max": pass_residual, "partial_source_residual_fraction_max": partial_residual, "intact_source_residual_fraction_min": intact_residual, "source_zone_dilation_pixels": int(raw.get("zone_expansion_pixels", 0)), "registration_required": bool( raw.get("registration_required", False) or clearance_profile_parameters ), "registration_tolerance_pixels": int(raw.get("registration_tolerance_pixels", 0)), "registration_method": "robust_static_background_alignment", "confirm_with_color_and_shape": bool(raw.get("confirm_with_color_and_shape", False)), "full_frame_search": bool(raw.get("full_frame_search", True)), "require_tiled_search_for_negative": True, "source_zone_vacancy_required_for_pass": bool( raw.get("source_zone_vacancy_required_for_pass", True) ), "closed_cabinet_storage_counts_as_not_visible": bool( raw.get("closed_cabinet_storage_counts_as_not_visible", False) ), "query_aliases_equivalent": bool(raw.get("query_aliases_equivalent", False)), "use_color_guided_proposals": bool(raw.get("use_color_guided_proposals", False)), "source_zone": { "method": "per_instance_input_mask_or_bbox", "description": "Each detected input target instance defines its own source footprint.", }, **({ "source_selector_profile": source_selector_profile, "source_selector": source_selector, } if source_selector_profile else {}), **clearance_profile_parameters, } shelf_source_region = { "region_id": "lower_shelf_source_compartment", "semantic_role": "source_region", "image_roles": ["input", "pred"], "source_image": "both", "proposal_method": "grid_parser", "query_or_rule": ( "Within the left shelving unit, select the lower compartment below the " "horizontal shelf divider that contains the input binder group; transfer " "the corresponding cell through registered shelf-grid pairing." ), "materializer": { "kind": "shelf_grid_parser", "queries": ["shelving unit", "shelf compartment"], "geometry_policy": "registered_rectified_compartment_grid", "region_rule": ( "Within the left shelving unit, select the lower compartment below the " "horizontal shelf divider that contains the input binder group." ), }, "geometry_policy": "registered_rectified_compartment_grid", "provenance": "registered source-clearance profile", } predicate = { "schema_version": EXECUTABLE_PREDICATE_SCHEMA_VERSION, "check_id": check_id, "status": "executable" if not reasons else "blocked_uncompiled", "family": "source_region_clearance", "source_rule_type": source_rule_type, "subjects": subject_groups, "regions": ( [shelf_source_region] if clearance_profile_parameters else [normalized["source_zone"]] ), "operations": [ _operation( "detect_input_targets", "object_detection", "detector", ("input",), parameters={"queries_from": "subjects"}, produces=("input_target_boxes",), ), _operation( "refine_input_targets", "mask_refinement", "segmenter", ("input",), depends_on=("detect_input_targets",), produces=("input_target_masks",), ), *([ _operation( "detect_source_anchor", "object_detection", "detector", ("input",), parameters={"queries": source_selector.get("anchor_queries", []), "evidence_role": "source_selector_anchor"}, produces=("source_anchor_boxes",), ), _operation( "refine_source_anchor", "mask_refinement", "segmenter", ("input",), depends_on=("detect_source_anchor",), produces=("source_anchor_masks",), ), _operation( "select_source_instance", "source_instance_selection", "source_instance_selector", ("input",), depends_on=("refine_input_targets", "refine_source_anchor"), parameters=source_selector, produces=("source_selector_certificate",), ), ] if source_selector_profile else []), _operation( "detect_output_targets", "object_detection", "detector", ("pred",), parameters={"queries_from": "subjects", "search_scopes": ["full_frame", "tiled"]}, produces=("output_target_boxes", "detector_search_coverage"), ), _operation( "refine_output_targets", "mask_refinement", "segmenter", ("pred",), depends_on=("detect_output_targets",), produces=("output_target_masks",), ), *([ _operation( "register_source", "image_registration", "registration", ("input", "pred"), produces=("input_to_output_transform",), ) ] if normalized["registration_required"] else []), *([ _operation( "materialize_source_shelf", "region_resolution", "typed_region_materializer", ("input", "pred"), produces=("typed_regions", "registered_shelf_grid_pair"), ) ] if clearance_profile_parameters else []), _operation( "match_target_instances", "instance_matching", "matcher", ("input", "pred"), depends_on=("refine_input_targets", "refine_output_targets"), optional=True, produces=("instance_matches",), ), _operation( "classify_source_states", "source_state_classification", "predicate_interpreter", ("input", "pred"), depends_on=( "refine_input_targets", "refine_output_targets", "detect_output_targets", *(["select_source_instance"] if source_selector_profile else []), *(["materialize_source_shelf"] if clearance_profile_parameters else []), ), produces=("per_target_source_state",), ), _operation( "decide", "predicate_decision", "predicate_interpreter", ("input", "pred"), depends_on=("classify_source_states",), produces=("check_result",), ), ], "state_schema": { "unit": "source_target_instance", "states": ["not_moved", "partial_residual", "moved", "deleted_or_invisible", "unknown"], "not_moved": "A compatible output target overlaps its own input source footprint.", "moved": "A compatible output target is detected only outside its source footprint.", "deleted_or_invisible": "No accepted target remains after complete DINO+YOLO full-frame and tiled search.", "unknown": "Input identity, source geometry, or negative search coverage is insufficient.", }, "decision": { "pass": {"remaining_source_count": 0, "partial_source_count": 0, "unresolved_source_count": 0}, "partial": { "any": [ { "remaining_source_count": {"minimum": 1, "maximum": max(0, expected_count - 1)}, "unresolved_source_count": 0, }, {"partial_source_count": {"minimum": 1}, "unresolved_source_count": 0}, ], }, "fail": {"remaining_source_count": expected_count, "unresolved_source_count": 0}, "unknown": {"unresolved_source_count": {"minimum": 1}}, }, "parameters": normalized, "parameter_provenance": { "expected_source_count": expected_key or "default_missing", "minimum_detection_confidence": output_score_key or "default:0.15", "source_input_minimum_detector_confidence": input_score_key or f"default:{input_score}", "source_overlap_threshold": source_overlap_key or "default:0.15", "pass_source_residual_fraction_max": pass_residual_key or "default:0", "partial_source_residual_fraction_max": partial_residual_key or "default:max(pass,0.03)", "intact_source_residual_fraction_min": intact_residual_key or "default:max(0.25,partial)", "source_zone_dilation_pixels": "zone_expansion_pixels" if "zone_expansion_pixels" in raw else "default:0", "registration_required": "registration_required" if "registration_required" in raw else "default:false", "registration_tolerance_pixels": ( "registration_tolerance_pixels" if "registration_tolerance_pixels" in raw else "default:0" ), "source_anchor_query": "source_anchor_query" if raw.get("source_anchor_query") else "identity_query_only", **({ "source_selector_profile": "decision_rule.parameters.source_selector_profile", "source_selector": "decision_rule.parameters.source_selector", } if source_selector_profile else {}), **({ "source_clearance_profile": "decision_rule.parameters.source_clearance_profile", "source_clearance_executor_version": "registered_metric_profile", } if clearance_profile_parameters else {}), }, "unmapped_contract_parameters": unmapped, "reasons": list(dict.fromkeys(reasons)), "provenance": provenance, } validation = validate_executable_predicate(predicate) if not validation.valid: predicate["status"] = "blocked_invalid" predicate["reasons"] = list(dict.fromkeys((*predicate["reasons"], *validation.reasons))) return predicate def validate_executable_predicate(predicate: Mapping[str, Any]) -> PredicateValidation: """Validate structure and operation dependencies without executing tools.""" reasons: list[str] = [] if predicate.get("schema_version") != EXECUTABLE_PREDICATE_SCHEMA_VERSION: reasons.append("unsupported_predicate_schema") if not str(predicate.get("check_id") or "").strip(): reasons.append("missing_check_id") status = str(predicate.get("status") or "") if status not in {"executable", "blocked_uncompiled", "blocked_invalid", "manual_review_required"}: reasons.append("invalid_predicate_status") operations = _list(predicate.get("operations")) if status == "executable" and not operations: reasons.append("executable_predicate_has_no_operations") operation_ids: set[str] = set() for item in operations: if not isinstance(item, Mapping): reasons.append("operation_is_not_object") continue operation_id = str(item.get("id") or "") kind = str(item.get("kind") or "") if not operation_id: reasons.append("operation_missing_id") elif operation_id in operation_ids: reasons.append("duplicate_operation_id:" + operation_id) operation_ids.add(operation_id) if kind not in PREDICATE_OPERATION_KINDS: reasons.append("unsupported_operation_kind:" + kind) for item in operations: if not isinstance(item, Mapping): continue for dependency in _list(item.get("depends_on")): if str(dependency) not in operation_ids: reasons.append(f"missing_operation_dependency:{item.get('id', '')}:{dependency}") if status == "executable": if not _list(predicate.get("subjects")): reasons.append("executable_predicate_has_no_subjects") if not isinstance(predicate.get("decision"), Mapping) or not predicate.get("decision"): reasons.append("executable_predicate_has_no_decision_table") if _list(predicate.get("unmapped_contract_parameters")): reasons.append("executable_predicate_has_unmapped_parameters") if str(predicate.get("family") or "") == "registered_metric_bridge": state_schema = predicate.get("state_schema") if isinstance(predicate.get("state_schema"), Mapping) else {} decision = predicate.get("decision") if isinstance(predicate.get("decision"), Mapping) else {} decide_operations = [ item for item in operations if isinstance(item, Mapping) and str(item.get("kind") or "") == "predicate_decision" ] versions = { str(state_schema.get("operator_version") or ""), str(decision.get("operator_version") or ""), *{ str((item.get("parameters") or {}).get("operator_version") or "") for item in decide_operations if isinstance(item.get("parameters"), Mapping) }, } if versions != {REGISTERED_METRIC_OPERATOR_VERSION}: reasons.append("stale_registered_metric_operator_version") return PredicateValidation(not reasons, tuple(dict.fromkeys(reasons)))
"""Executable visual predicates embedded in PVR evaluation contracts.
Natural-language questions and criteria remain useful for review, but they are
not an execution interface. This module compiles one reviewed check into a
small, validated program that names its subjects, tool operations, derived
regions, state machine, and deterministic decision table.
Only explicitly supported predicate families are executable. Everything
else is represented as ``blocked_uncompiled`` so downstream code cannot fall
back to guessing tools from prose.
"""
from __future__ import annotations
from copy import deepcopy
from dataclasses import dataclass
import re
from typing import Any, Mapping, Sequence
from pvr_eval.contracts.metric_profiles import (
ARTICULATED_ENTITY_PRESERVATION_EXECUTOR_VERSION,
ARTICULATED_ENTITY_PRESERVATION_PROFILE,
REPEATED_COMPONENT_GROUP_IDENTITY_EXECUTOR_VERSION,
REPEATED_COMPONENT_GROUP_IDENTITY_PROFILE,
SHELF_SOURCE_GROUP_CLEARANCE_PROFILE,
shelf_source_group_clearance_profile_parameters,
)
from pvr_eval.agent.source_instance_selector import (
ANCHOR_RELATIVE_SOURCE_INSTANCE_PROFILE,
SUPPORTED_ANCHOR_PARTS,
is_relational_identity_text,
)
from pvr_eval.agent.source_annotation_masks import (
VERIFIED_PROTECTED_SOURCE_MASK_PROFILE,
VERIFIED_SOURCE_MASK_CAPABILITY_VERSION,
VERIFIED_SOURCE_MASK_PROFILE,
)
EXECUTABLE_PREDICATE_SCHEMA_VERSION = "pvr.executable_predicate.v1"
REGISTERED_METRIC_OPERATOR_VERSION = "pvr.contract_metric.v7"
SMALL_ANIMAL_GEOMETRY_EXECUTOR_VERSION = "pvr.small_animal_set_geometry.v5"
SOURCE_REGION_CLEARANCE_RULES = frozenset(
{
"counted_pair_removal",
"paired_zoned_instance_removal",
"colored_container_visibility_count",
"source_zone_vacancy",
"zoned_instance_absence_with_residual_test",
"small_zoned_instance_absence_with_residual_test",
}
)
SURFACE_RESIDUAL_INVENTORY_RULES = frozenset(
{
"desk_clutter_residual_count",
"tabletop_remaining_item_count",
}
)
DESTINATION_MEMBERSHIP_RULES = frozenset(
{
"named_supply_storage_coverage",
"single_object_destination_containment",
"counted_objects_destination_containment",
"relocated_object_in_air_zone",
"categorized_group_completeness",
"dual_category_grouping",
"document_group_completeness",
"paired_zone_containment",
"two_object_single_zone_containment",
"counted_container_membership",
"required_set_container_membership",
"paired_container_membership",
"remote_pair_on_table_surface",
"paired_relocation_beside_dispenser",
"same_unit_different_compartment_placement",
}
)
RELOCATION_TRANSITION_RULES = frozenset({"source_vacated_and_destination_valid"})
SOURCE_REGION_RESTORATION_RULES = frozenset({"vacated_source_with_background_fill"})
SOURCE_DISPLACEMENT_RULES = frozenset(
{
"per_instance_source_zone_displacement",
"multi_instance_source_zone_displacement",
"bird_instance_displacement_and_shoulder_clearance",
}
)
INSTANCE_CLUSTER_GROUPING_RULES = frozenset({"small_animal_cluster_component_count"})
PROTECTED_SET_EXCLUSION_RULES = frozenset({"protected_zone_exclusion_count"})
CLUSTER_SUBJECT_SEPARATION_RULES = frozenset({"cluster_protected_subject_gap"})
CROSS_IMAGE_INVENTORY_RULES = frozenset(