Datasets:
File size: 10,363 Bytes
e1ced61 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 | """Six-step AST canonicalization and the canonical program hash (``docs/02`` §7.2).
Two programs are *semantically equivalent* iff their canonical ASTs hash equal.
``canonical_program_sha256`` is the integrity anchor reused by the C2 dual-compile
exact-match (``canonical_program_exact_match``) and the executor (P3):
1. resolve entity names → stable IDs (via the world's label→id map);
2. numeric literal normalize (exact rational; expression → SymPy canonical);
3. commutative operand sort (per-DSL commutative ops, sorted by canonical JSON);
4. alias operator expand (per-DSL alias → canonical op name);
5. redundant cast/remove (per-DSL no-op identity casts collapse to their arg);
6. topological node ordering (children canonicalized before parents, so a
parent's commutative sort is over already-canonical operands).
Step 6 is structural in the recursion: each child is canonicalized before its
parent, and the parent's commutative sort keys on the canonical (post-alias) op.
The numbered order is the spec's conceptual order; alias-expansion is applied
before the commutative sort so sort keys on the *canonical* operator, which is
the operator commutativity is defined on.
"""
from __future__ import annotations
from collections.abc import Mapping
from dataclasses import dataclass
from fractions import Fraction
from typing import Any
from ..hashing import canonical_json, canonical_json_hash
from ..sources.base import World
from .ast import LITERAL, REF, AstNode, Dsl, Program, canonical_number_str, parse_number
# Per-DSL canonicalization profile (loaded lazily to avoid a circular import:
# the dsl modules import this module to compute the canonical hash).
@dataclass(frozen=True)
class DslProfile:
"""Per-DSL canonicalization knobs."""
commutative_ops: frozenset[str]
aliases: Mapping[str, str]
identity_casts: frozenset[str]
def profile(dsl: Dsl) -> DslProfile:
"""Load the canonicalization profile for one DSL (lazy import)."""
if dsl == "plotqa_dsl_v1":
from . import plotdsl
return DslProfile(plotdsl.COMMUTATIVE_OPS, plotdsl.ALIASES, plotdsl.IDENTITY_CASTS)
if dsl == "geometry_dsl_v1":
from . import geometrydsl
return DslProfile(
geometrydsl.COMMUTATIVE_OPS, geometrydsl.ALIASES, geometrydsl.IDENTITY_CASTS
)
if dsl == "table_dsl_v1":
from . import tabledsl
return DslProfile(tabledsl.COMMUTATIVE_OPS, tabledsl.ALIASES, tabledsl.IDENTITY_CASTS)
if dsl == "clevr_dsl_v1":
from . import clevrdsl
return DslProfile(clevrdsl.COMMUTATIVE_OPS, clevrdsl.ALIASES, clevrdsl.IDENTITY_CASTS)
raise ValueError(f"unknown DSL {dsl!r}")
# --- world resolution (step 1) ---------------------------------------------
def entity_ids(world: World | None) -> set[str]:
"""All stable entity ids declared by a world (``plot_world_v1`` / ``geometry_world_v1``)."""
if not world:
return set()
ids: set[str] = set()
for series in world.get("series", []) or []:
if isinstance(series, Mapping) and series.get("id"):
ids.add(str(series["id"]))
for point in series.get("points", []) or [] if isinstance(series, Mapping) else []:
if isinstance(point, Mapping) and point.get("id"):
ids.add(str(point["id"]))
for entity in world.get("entities", []) or []:
if isinstance(entity, Mapping) and entity.get("id"):
ids.add(str(entity["id"]))
for obj in world.get("objects", []) or []:
if isinstance(obj, Mapping) and obj.get("id"):
ids.add(str(obj["id"]))
return ids
def entity_aliases(world: World | None) -> dict[str, str]:
"""Label → stable-id map for entity-name resolution (``docs/02`` §7.2 step 1).
A plot series label resolves to its ``series:`` id; a geometry entity has no
human label separate from its id, so it maps to itself. A referent that is
already a stable id passes through unchanged.
"""
if not world:
return {}
aliases: dict[str, str] = {}
for series in world.get("series", []) or []:
if isinstance(series, Mapping) and series.get("id"):
sid = str(series["id"])
aliases[sid] = sid
label = series.get("label")
if isinstance(label, str) and label:
aliases[label] = sid
for entity in world.get("entities", []) or []:
if isinstance(entity, Mapping) and entity.get("id"):
eid = str(entity["id"])
aliases[eid] = eid
for obj in world.get("objects", []) or []:
if isinstance(obj, Mapping) and obj.get("id"):
oid = str(obj["id"])
aliases[oid] = oid
return aliases
def resolve_ref_id(node: AstNode, aliases: Mapping[str, str]) -> AstNode:
"""Step 1: replace a REF label with its stable id when a mapping exists."""
if not node.is_ref():
return node
raw = node.ref_id()
resolved = aliases.get(raw, raw)
if resolved == raw:
return node
return AstNode(op=REF, args=(resolved,), return_type=node.return_type)
# --- literal normalization (step 2) ----------------------------------------
def canonical_expression(expr: str) -> str:
"""Canonical SymPy form of an expression literal (``docs/02`` §3.3).
``sympy.expand`` + the default printer yields a term-ordered canonical string
so ``"1 + x"`` and ``"x + 1"`` collapse. SymPy is imported lazily; if it is
unavailable the literal is left untouched (P2 plot programs never need it).
"""
try:
import sympy
except ImportError: # pragma: no cover - sympy is pinned in requirements
return expr
try:
expanded = sympy.expand(sympy.sympify(expr))
except Exception: # noqa: BLE001 - sympify raises varied types on bad input
return expr
return str(sympy.sstr(expanded))
def normalize_literal(node: AstNode) -> AstNode:
"""Step 2: re-canonicalize a LITERAL's value (numeric exact / expression SymPy)."""
if not node.is_literal() or not node.args:
return node
value = node.args[0]
if node.return_type in ("number", "integer") and isinstance(value, str):
return AstNode(
op=LITERAL,
args=(canonical_number_str(parse_number(value)),),
return_type=node.return_type,
)
if node.return_type == "expression" and isinstance(value, str):
return AstNode(
op=LITERAL, args=(canonical_expression(value),), return_type=node.return_type
)
return node
# --- canonicalize ----------------------------------------------------------
def canonicalize(node: AstNode, *, dsl: Dsl, world: World | None = None) -> AstNode:
"""Apply the §7.2 six steps to ``node`` and return a new canonical :class:`AstNode`."""
prof = profile(dsl)
aliases = entity_aliases(world)
def canon(n: AstNode) -> AstNode:
# Step 1: resolve entity references.
n = resolve_ref_id(n, aliases)
# Leaves: step 2 only.
if n.is_ref():
return n
if n.is_literal():
return normalize_literal(n)
# Compound: canonicalize children first (step 6 — topological ordering).
canon_args = tuple(_canonicalize_arg(a, canon) for a in n.args)
# Step 4: alias operator expand (before sort so sort keys on the canonical op).
op = prof.aliases.get(n.op, n.op)
# Step 5: redundant cast/remove — a single-arg identity cast collapses.
if (
op in prof.identity_casts
and len(canon_args) == 1
and isinstance(canon_args[0], AstNode)
):
return canon_args[0]
# Step 3: commutative operand sort over canonical child JSON.
if op in prof.commutative_ops:
canon_args = _sort_commutative(canon_args)
return AstNode(op=op, args=canon_args, return_type=n.return_type)
return canon(node)
def _canonicalize_arg(arg: Any, canon: Any) -> Any:
"""Canonicalize a sub-node; pass bare atomic field keys through untouched."""
if isinstance(arg, AstNode):
return canon(arg)
return arg
def _sort_commutative(args: tuple[Any, ...]) -> tuple[Any, ...]:
"""Sort commutative operands by their canonical-JSON serialization (stable)."""
return tuple(sorted(args, key=_arg_sort_key))
def _arg_sort_key(arg: Any) -> str:
if isinstance(arg, AstNode):
return canonical_json(arg.to_ast_node_dict())
if isinstance(arg, bool):
return canonical_json(arg)
if isinstance(arg, int):
return canonical_json(arg)
if isinstance(arg, Fraction):
return canonical_number_str(arg)
if isinstance(arg, str):
return canonical_json(arg)
return canonical_json(str(arg))
# --- canonical program hash ------------------------------------------------
def canonical_program_sha256(program: Program, *, world: World | None = None) -> str:
"""SHA-256 of the canonical program AST (+ referent selector).
The hash input is the canonical-JSON of::
{"program": <canonical astNode>, "referent_selector": <canonical astNode | null>}
This is the exact-match key for ``canonical_program_exact_match`` (P4) and the
program fingerprint reused by the executor (P3). Equivalent programs hash
equal; non-equivalent programs hash differently.
"""
canon_program = canonicalize(program.program, dsl=program.dsl, world=world)
referent: dict[str, Any] | None = None
if program.referent_selector is not None:
canon_ref = canonicalize(program.referent_selector, dsl=program.dsl, world=world)
referent = canon_ref.to_ast_node_dict()
return canonical_json_hash(
{"program": canon_program.to_ast_node_dict(), "referent_selector": referent}
)
def programs_equivalent(a: Program, b: Program, *, world: World | None = None) -> bool:
"""True iff two programs share a canonical program hash (§7.2 canonical match)."""
return canonical_program_sha256(a, world=world) == canonical_program_sha256(b, world=world)
__all__ = [
"DslProfile",
"canonical_expression",
"canonical_program_sha256",
"canonicalize",
"entity_aliases",
"entity_ids",
"profile",
"programs_equivalent",
"resolve_ref_id",
]
|