diff --git a/OFF_DataQuality/.gitignore b/OFF_DataQuality/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..57a303904aa225f7dec64a334508e17c9efa91b0 --- /dev/null +++ b/OFF_DataQuality/.gitignore @@ -0,0 +1,23 @@ +# Python cache/artifacts +__pycache__/ +*.py[cod] +*.pyo +*.pyd +.pytest_cache/ + +# Local environments +.venv/ +venv/ + +# Local data artifacts & databases (do not commit) +*.db +openfoodfacts-products.jsonl +config/secret_key +config/logs/ +results/tmp_engine_runs/ + +# OS/editor +.DS_Store +Thumbs.db +.vscode/ +.idea/ diff --git a/OFF_DataQuality/README.md b/OFF_DataQuality/README.md new file mode 100644 index 0000000000000000000000000000000000000000..6c40763bfd634a8a4c953a731246711604bf16d3 --- /dev/null +++ b/OFF_DataQuality/README.md @@ -0,0 +1,206 @@ +# OFF_DataQuality: Perl-to-Python Data Quality Migration & Benchmarking Framework + +## Overview + +**OFF_DataQuality** is an end-to-end framework designed to modernize legacy data quality validation logic for **Open Food Facts (OFF)**. + +Historically, Open Food Facts relied on legacy **Perl (`.pl`)** scripts to enforce quality controls across millions of food products—ranging from energy unit conversions (kcal vs. kJ) and macro-nutrient balance checks (sugars, fats, carbohydrates) to jurisdiction-specific allergen and packaging compliance regulations. + +This project provides an automated pipeline for: +1. **Extracting** relational, threshold, and logic conditions from legacy Perl scripts. +2. **Migrating** rules into modern **Python** validation logic using LLMs (Groq / GPT-oss-120b) with deterministic fallback templates and semantic guardrail verification. +3. **Generating Declarative Targets** for **dbt-core** (DuckDB SQL tests) and **SodaCL** (Soda data quality contracts). +4. **Benchmarking Parity** across legacy Perl outputs vs. Python, dbt, and Soda execution engines with conservative statistical confidence scoring (95% Wilson bounds & Beta posteriors). +5. **Interactive Dashboarding** to inspect side-by-side rule performance, win distributions by complexity (simple, medium, intricate), and legal traceability metadata. + +--- + +## Core Architecture & Workflow + +```mermaid +flowchart TD + A[Legacy Perl Rules .pl] --> B[Perl Logic Extractor] + B --> C{Migration Engine} + C -->|LLM / Groq GPT-oss-120b| D[Python Rules] + C -->|Declarative Generator| E[dbt DuckDB SQL Tests] + C -->|Declarative Generator| F[SodaCL YAML Contracts] + D --> G[Semantic Guardrails Verification] + E --> H[DuckDB Parity Execution] + F --> H + G --> H + H --> I[Statistical Confidence & Parity Validator] + I --> J[Streamlit Comparison Dashboard] +``` + +--- + +## Key Features + +### 1. Automated Perl Rule Extraction & Translation +- **Perl Extractor (`extractor/perl_logic_extractor.py`)**: Parses legacy `.pl` condition files to isolate numeric bounds, relational field constraints, and tag generation logic. +- **LLM Converter (`migration/llm_converter.py`)**: Translates extracted rules into executable Python functions via LLM API calls with 2-stage runtime and semantic contract validation. +- **Deterministic Fallback**: If LLM API access is unavailable or semantic checks fail, the system falls back to deterministic rule templates. + +### 2. Multi-Engine Declarative Pilot (`dbt` & `SodaCL`) +- **dbt Target**: Automatically generates dbt SQL test models and `count_violations` macros backed by DuckDB. +- **SodaCL Target**: Automatically generates SodaCL contract YAML files for automated data quality scanning. + +### 3. Statistical Parity & Confidence Scoring +Rule confidence is computed conservatively to prevent inflation on sparse evidence: +$$ ext{overall\_confidence} = ext{llm\_confidence} imes ext{parity\_ci\_lower\_95} imes ext{evidence\_ci\_lower\_95}$$ +Where `parity_ci_lower_95` uses the **Wilson score interval** and `evidence_ci_lower_95` uses a **Beta posterior credible bound** on positive violation matches. + +### 4. Jurisdiction Profile Layers +- **`global`**: Generic Open Food Facts nutrient consistency and boundary rules. +- **`canada`**: Phase-1 Canadian regulatory proxy rules (e.g., Front-of-Package (FOP) symbols, bilingual label indicators, allergen statements) with legal citations, source URLs, and review metadata. +- **`hybrid`**: Unified execution across both global and Canadian rule sets. + +### 5. Interactive Streamlit Dashboard +An interactive UI (`dashboard/app.py`) presenting per-rule accuracy, side-by-side code/SQL comparisons, engine recommendations, and legal traceability metadata. + +--- + +## Repository Structure + +```text +OFF_DataQuality/ +├── README.md # Project documentation and execution guide +├── requirements.txt # Core dependencies (duckdb, streamlit, pandas, openai, dbt, soda) +├── pytest.ini # Test configuration +├── inspect_duckdb.py # Utility script for inspecting DuckDB tables +├── config/ +│ ├── hypercorn.toml # Server configuration +│ └── custom-covers/ # Custom asset configuration directories +├── dashboard/ +│ └── app.py # Interactive Streamlit parity comparison dashboard +├── data/ +│ ├── load_dataset.py # Streamed product dataset loader (real OFF JSONL / sample) +│ └── sample_products.jsonl # 400 sample OFF product records for out-of-the-box execution +├── declarative/ +│ └── check_runners.py # Declarative dbt & Soda check generation & execution +├── duckdb_utils/ +│ └── create_tables.py # In-memory DuckDB table creation & schema setup +├── extractor/ +│ └── perl_logic_extractor.py # Legacy Perl script logic parser +├── llm-test/ +│ └── test_groq.py # Verification script for Groq API integration +├── migration/ +│ └── llm_converter.py # LLM translation pipeline with semantic guardrails +├── perl_checks/ +│ ├── legacy_checks.py # Simulated & file-based legacy Perl rule runner +│ └── rules/ # 19 legacy Perl validation rules (.pl) +├── python_checks/ +│ └── generated_checks.py # Auto-generated Python quality check routines +├── results/ +│ ├── engine_comparison.json # Pre-computed benchmark comparison report +│ ├── migration_results.json # Migration execution output +│ └── declarative_runtime/ # Generated dbt & Soda test models and contracts +├── rulepacks/ +│ └── registry.py # Global, Canada, and Hybrid rule-pack registry +├── tests/ # Comprehensive pytest suite +└── validation/ + ├── parity_validator.py # End-to-end parity validation pipeline + ├── engine_comparison.py # Multi-engine comparative benchmark suite + └── verification.py # Semantic and runtime verification contracts +``` + +--- + +## Security & Publishing Norms + +- **No Hardcoded Credentials**: API keys (such as `GROQ_API_KEY`) are read strictly from environment variables. +- **Sanitized Configurations**: Local secret keys, temporary logs, and local SQLite/DuckDB binary database files are excluded. +- **Reproducible Sample Dataset**: Includes 400 sample product records (`data/sample_products.jsonl`) so the entire pipeline can be benchmarked offline out-of-the-box. + +--- + +## Quick Start + +### 1. Installation + +Clone the repository and install dependencies: + +```bash +git clone https://huggingface.co/datasets/offCanada/Final_Deliverables +cd Final_Deliverables/OFF_DataQuality +pip install -r requirements.txt +``` + +### 2. Run Parity Validator Pipeline + +Run parity validation on sample products using the default Python target: + +```bash +python -m validation.parity_validator --size 300 --seed 17 +``` + +Run with declarative targets (`dbt` or `soda`): + +```bash +python -m validation.parity_validator --size 300 --execution-engine dbt +python -m validation.parity_validator --size 300 --execution-engine soda +``` + +Run using file-based Perl rule files: + +```bash +python -m validation.parity_validator --size 300 --perl-rules-dir perl_checks/rules +``` + +### 3. Run Multi-Engine Comparison Benchmark + +Execute a comparison experiment across Python, dbt, and Soda engines: + +```bash +python -m validation.engine_comparison --size 300 --mode off --llm-provider groq +``` + +Run with specific rule profiles: + +```bash +python -m validation.engine_comparison --size 300 --profile global +python -m validation.engine_comparison --size 300 --profile canada +python -m validation.engine_comparison --size 300 --profile hybrid +``` + +### 4. Launch the Streamlit Dashboard + +Explore benchmark metrics, engine recommendations, and rule details interactively: + +```bash +streamlit run dashboard/app.py +``` + +### 5. Running with Groq LLM Integration (Optional) + +To enable real LLM translation via Groq: + +```powershell +# Windows PowerShell +$env:GROQ_API_KEY="your_groq_api_key_here" +``` + +```bash +# Bash / Linux / macOS +export GROQ_API_KEY="your_groq_api_key_here" +``` + +Then run with Groq provider: + +```bash +python -m validation.parity_validator --size 300 --llm-provider groq --llm-model openai/gpt-oss-120b +``` + +### 6. Automated Testing + +Run the test suite using `pytest`: + +```bash +pytest -q +``` + +--- + +## License & Attribution + +This project is part of the **Open Food Facts (Canada)** data quality modernization effort. All product sample data and rule definitions conform to Open Food Facts open-data specifications. diff --git a/OFF_DataQuality/config/hypercorn.toml b/OFF_DataQuality/config/hypercorn.toml new file mode 100644 index 0000000000000000000000000000000000000000..98d1c62876ab3214c1607026228a555f3713fbd9 --- /dev/null +++ b/OFF_DataQuality/config/hypercorn.toml @@ -0,0 +1,9 @@ +# http1 & http2 binding +bind = ["0.0.0.0:9810"] +# http3 quick binding +quick_bind = ["0.0.0.0:9810"] +# http path prefix for codex +root_path = "" +# This can be a number or "auto" for Codex to guess a good value. +# https://github.com/ajslater/codex#bulk-database-updates-fail +max_import_batch_size = "auto" diff --git a/OFF_DataQuality/dashboard/app.py b/OFF_DataQuality/dashboard/app.py new file mode 100644 index 0000000000000000000000000000000000000000..5229f14ddb938e53d991ed46442ad2ecb14eed9c --- /dev/null +++ b/OFF_DataQuality/dashboard/app.py @@ -0,0 +1,787 @@ +"""Streamlit dashboard for cross-engine migration comparison.""" +from __future__ import annotations + +import html +import json +import os +import sys +from pathlib import Path +from typing import Dict, List, Mapping + +import pandas as pd +import plotly.express as px +import plotly.graph_objects as go +import streamlit as st + +PROJECT_ROOT = Path(__file__).resolve().parent.parent +if str(PROJECT_ROOT) not in sys.path: + sys.path.insert(0, str(PROJECT_ROOT)) + +from rulepacks.registry import DEFAULT_PROFILE, SUPPORTED_PROFILES +from validation.engine_comparison import COMPARISON_PATH, run_engine_comparison + +DEFAULT_SOURCE_JSONL = PROJECT_ROOT / "openfoodfacts-products.jsonl" +ENGINE_COLORS = { + "python": "#2563eb", + "dbt": "#f97316", + "soda": "#10b981", +} + + +def load_report() -> dict: + if not COMPARISON_PATH.exists(): + return {} + with COMPARISON_PATH.open("r", encoding="utf-8") as handle: + return json.load(handle) + + +def _inject_theme() -> None: + st.markdown( + """ + + """, + unsafe_allow_html=True, + ) + + +def _to_pct(value: object) -> float: + try: + return round(float(value) * 100, 2) + except (TypeError, ValueError): + return 0.0 + + +def _render_stat_chip(label: str, value: object) -> None: + st.markdown( + ( + "
Compare Python (LLM), dbt, and Soda migrations for every rule, side-by-side.
+.*?)```", text, re.DOTALL | re.IGNORECASE)
+ if match:
+ return match.group("code").strip()
+ return text.strip()
+
+
+def _validate_generated_code(code: str, function_name: str) -> None:
+ namespace: Dict[str, object] = {}
+ exec(code, {}, namespace)
+ fn = namespace.get(function_name)
+ if not callable(fn):
+ raise ValueError(f"Generated code does not define callable `{function_name}`.")
+ # Basic runtime contract checks to avoid unsafe generated code.
+ probe_products = [
+ {},
+ {
+ "energy_kj": None,
+ "energy_kj_computed": None,
+ "energy_kcal": 100.0,
+ "fat": None,
+ "saturated_fat": None,
+ "carbohydrates": None,
+ "sugars": None,
+ "language_code": None,
+ "ingredients_text_present": None,
+ "contains_statement_present": None,
+ "allergen_evidence_present": None,
+ "fop_threshold_exceeded": None,
+ "fop_symbol_present": None,
+ "fop_exempt_proxy": None,
+ "product_is_prepackaged_proxy": None,
+ },
+ {
+ "energy_kj": 100.0,
+ "energy_kj_computed": 100.0,
+ "energy_kcal": 10.0,
+ "fat": 10.0,
+ "saturated_fat": 2.0,
+ "carbohydrates": 15.0,
+ "sugars": 5.0,
+ "language_code": "en",
+ "ingredients_text_present": 1,
+ "contains_statement_present": 0,
+ "allergen_evidence_present": 0,
+ "fop_threshold_exceeded": 0,
+ "fop_symbol_present": 0,
+ "fop_exempt_proxy": 0,
+ "product_is_prepackaged_proxy": 1,
+ },
+ ]
+ for product in probe_products:
+ try:
+ result = fn(product)
+ except Exception as exc: # noqa: BLE001 - intentional hard guard for generated code
+ raise ValueError(f"Generated function raised {exc.__class__.__name__}: {exc}") from exc
+ if result is not None and not isinstance(result, str):
+ raise ValueError("Generated function must return str or None.")
+
+
+def _comparison_truth_pairs(operator_token: str) -> tuple[tuple[float, float], tuple[float, float]]:
+ pairs = {
+ ">": ((2.0, 1.0), (1.0, 2.0)),
+ "<": ((1.0, 2.0), (2.0, 1.0)),
+ ">=": ((2.0, 2.0), (1.0, 2.0)),
+ "<=": ((2.0, 2.0), (3.0, 2.0)),
+ "==": ((2.0, 2.0), (2.0, 3.0)),
+ "!=": ((2.0, 3.0), (2.0, 2.0)),
+ }
+ if operator_token not in pairs:
+ raise ValueError(f"Unsupported comparison operator: {operator_token}")
+ return pairs[operator_token]
+
+
+def _threshold_truth_values(operator_token: str, threshold: float) -> tuple[float, float]:
+ if operator_token == ">":
+ return threshold + 1.0, threshold
+ if operator_token == "<":
+ return threshold - 1.0, threshold
+ if operator_token == ">=":
+ return threshold, threshold - 1.0
+ if operator_token == "<=":
+ return threshold, threshold + 1.0
+ if operator_token == "==":
+ return threshold, threshold + 1.0
+ if operator_token == "!=":
+ return threshold + 1.0, threshold
+ raise ValueError(f"Unsupported threshold operator: {operator_token}")
+
+
+def _semantic_test_cases(rule: Dict[str, object]) -> List[tuple[Dict[str, object], str | None, str]]:
+ condition_type = str(rule.get("condition_type"))
+ tag = str(rule["tag"])
+
+ if condition_type == "field_comparison":
+ left = str(rule["left_operand"])
+ right = str(rule["right_operand"])
+ operator_token = str(rule["operator"])
+ true_pair, false_pair = _comparison_truth_pairs(operator_token)
+ return [
+ ({left: true_pair[0], right: true_pair[1]}, tag, "comparison_true"),
+ ({left: false_pair[0], right: false_pair[1]}, None, "comparison_false"),
+ ({left: None, right: true_pair[1]}, None, "comparison_missing_left"),
+ ({left: true_pair[0], right: None}, None, "comparison_missing_right"),
+ ({left: "nan_text", right: true_pair[1]}, None, "comparison_non_numeric_left"),
+ ]
+
+ if condition_type == "field_threshold":
+ left = str(rule["left_operand"])
+ operator_token = str(rule["operator"])
+ threshold = float(rule["right_operand"])
+ true_value, false_value = _threshold_truth_values(operator_token, threshold)
+ return [
+ ({left: true_value}, tag, "threshold_true"),
+ ({left: false_value}, None, "threshold_false"),
+ ({left: None}, None, "threshold_missing"),
+ ({left: "nan_text"}, None, "threshold_non_numeric"),
+ ]
+
+ if condition_type == "missing_field":
+ field = str(rule["left_operand"])
+ return [
+ ({field: None}, tag, "missing_none"),
+ ({field: ""}, tag, "missing_empty_string"),
+ ({field: " "}, tag, "missing_whitespace"),
+ ({field: "en"}, None, "missing_present"),
+ ]
+
+ if condition_type == "scaled_field_comparison":
+ left = str(rule["left_operand"])
+ right = str(rule["right_operand"])
+ operator_token = str(rule["operator"])
+ factor = float(rule["scale_factor"])
+ true_right = 10.0
+ scaled = true_right * factor
+ if operator_token == ">":
+ true_left, false_left = scaled + 1.0, scaled - 1.0
+ elif operator_token == ">=":
+ true_left, false_left = scaled, scaled - 1.0
+ elif operator_token == "<":
+ true_left, false_left = scaled - 1.0, scaled + 1.0
+ elif operator_token == "<=":
+ true_left, false_left = scaled, scaled + 1.0
+ elif operator_token == "==":
+ true_left, false_left = scaled, scaled + 1.0
+ elif operator_token == "!=":
+ true_left, false_left = scaled + 1.0, scaled
+ else:
+ raise ValueError(f"Unsupported scaled comparison operator: {operator_token}")
+ return [
+ ({left: true_left, right: true_right}, tag, "scaled_true"),
+ ({left: false_left, right: true_right}, None, "scaled_false"),
+ ({left: None, right: true_right}, None, "scaled_missing_left"),
+ ({left: true_left, right: None}, None, "scaled_missing_right"),
+ ({left: "nan_text", right: true_right}, None, "scaled_non_numeric"),
+ ]
+
+ if condition_type == "affine_field_comparison":
+ left = str(rule["left_operand"])
+ right = str(rule["right_operand"])
+ operator_token = str(rule["operator"])
+ factor = float(rule["scale_factor"])
+ offset = float(rule["offset"])
+ true_right = 10.0
+ target = (factor * true_right) + offset
+ if operator_token == ">":
+ true_left, false_left = target + 1.0, target - 1.0
+ elif operator_token == ">=":
+ true_left, false_left = target, target - 1.0
+ elif operator_token == "<":
+ true_left, false_left = target - 1.0, target + 1.0
+ elif operator_token == "<=":
+ true_left, false_left = target, target + 1.0
+ elif operator_token == "==":
+ true_left, false_left = target, target + 1.0
+ elif operator_token == "!=":
+ true_left, false_left = target + 1.0, target
+ else:
+ raise ValueError(f"Unsupported affine comparison operator: {operator_token}")
+ return [
+ ({left: true_left, right: true_right}, tag, "affine_true"),
+ ({left: false_left, right: true_right}, None, "affine_false"),
+ ({left: None, right: true_right}, None, "affine_missing_left"),
+ ({left: true_left, right: None}, None, "affine_missing_right"),
+ ({left: "nan_text", right: true_right}, None, "affine_non_numeric"),
+ ]
+
+ if condition_type == "sum_fields_comparison":
+ left_operands = list(rule.get("left_operands", []))
+ if len(left_operands) != 2:
+ raise ValueError("sum_fields_comparison rule must define two left operands.")
+ left_a = str(left_operands[0])
+ left_b = str(left_operands[1])
+ right = str(rule["right_operand"])
+ operator_token = str(rule["operator"])
+ right_offset = float(rule["right_offset"])
+ right_value = 20.0
+ target = right_value + right_offset
+ if operator_token == ">":
+ true_sum, false_sum = target + 1.0, target - 1.0
+ elif operator_token == ">=":
+ true_sum, false_sum = target, target - 1.0
+ elif operator_token == "<":
+ true_sum, false_sum = target - 1.0, target + 1.0
+ elif operator_token == "<=":
+ true_sum, false_sum = target, target + 1.0
+ elif operator_token == "==":
+ true_sum, false_sum = target, target + 1.0
+ elif operator_token == "!=":
+ true_sum, false_sum = target + 1.0, target
+ else:
+ raise ValueError(f"Unsupported sum comparison operator: {operator_token}")
+
+ true_a = true_sum / 2.0
+ true_b = true_sum - true_a
+ false_a = false_sum / 2.0
+ false_b = false_sum - false_a
+ return [
+ ({left_a: true_a, left_b: true_b, right: right_value}, tag, "sum_true"),
+ ({left_a: false_a, left_b: false_b, right: right_value}, None, "sum_false"),
+ ({left_a: None, left_b: true_b, right: right_value}, None, "sum_missing_left_a"),
+ ({left_a: true_a, left_b: None, right: right_value}, None, "sum_missing_left_b"),
+ ({left_a: true_a, left_b: true_b, right: None}, None, "sum_missing_right"),
+ ]
+
+ if condition_type == "compound_threshold_and":
+ clauses = list(rule.get("clauses", []))
+ if not clauses:
+ raise ValueError("compound_threshold_and rule must define clauses.")
+ true_product: Dict[str, object] = {}
+ false_product: Dict[str, object] = {}
+ missing_product: Dict[str, object] = {}
+ for idx, clause in enumerate(clauses):
+ field = str(clause["left_operand"])
+ operator_token = str(clause["operator"])
+ threshold = float(clause["right_operand"])
+ true_value, false_value = _threshold_truth_values(operator_token, threshold)
+ true_product[field] = true_value
+ false_product[field] = true_value
+ missing_product[field] = true_value
+ if idx == 0:
+ false_product[field] = false_value
+ missing_product[field] = None
+ return [
+ (true_product, tag, "compound_true"),
+ (false_product, None, "compound_false"),
+ (missing_product, None, "compound_missing"),
+ ]
+
+ raise ValueError(f"Unsupported condition type for semantic checks: {condition_type}")
+
+
+def _validate_generated_semantics(code: str, function_name: str, rule: Dict[str, object]) -> None:
+ namespace: Dict[str, object] = {}
+ exec(code, {}, namespace)
+ fn = namespace.get(function_name)
+ if not callable(fn):
+ raise ValueError(f"Generated code does not define callable `{function_name}`.")
+
+ for product, expected, case_name in _semantic_test_cases(rule):
+ try:
+ result = fn(product)
+ except Exception as exc: # noqa: BLE001
+ raise ValueError(f"Semantic test `{case_name}` raised {exc.__class__.__name__}: {exc}") from exc
+ if result != expected:
+ raise ValueError(
+ f"Semantic test `{case_name}` failed: expected {expected!r}, got {result!r}."
+ )
+
+
+def _normalize_function_name(code: str, function_name: str) -> str:
+ """Rename the first generated function to the expected runtime name."""
+ match = re.search(r"def\s+(?P[a-zA-Z_]\w*)\s*\(", code)
+ if not match:
+ return code
+ found_name = match.group("name")
+ if found_name == function_name:
+ return code
+ start, end = match.span("name")
+ return code[:start] + function_name + code[end:]
+
+
+def _build_llm_prompt(rule: Dict[str, object], function_name: str) -> str:
+ rule_payload = {
+ "rule_name": rule["rule_name"],
+ "tag": rule["tag"],
+ "condition_type": rule["condition_type"],
+ "condition": rule.get("condition"),
+ "duckdb_condition": rule.get("duckdb_condition"),
+ "left_operand": rule.get("left_operand"),
+ "left_operands": rule.get("left_operands"),
+ "operator": rule.get("operator"),
+ "right_operand": rule.get("right_operand"),
+ "scale_factor": rule.get("scale_factor"),
+ "offset": rule.get("offset"),
+ "right_offset": rule.get("right_offset"),
+ "clauses": rule.get("clauses"),
+ "complexity": rule.get("complexity"),
+ }
+ examples: List[Dict[str, object]] = []
+ for product, expected, case_name in _semantic_test_cases(rule):
+ examples.append({"case": case_name, "input": product, "expected": expected})
+ return (
+ "Generate one Python function for a data-quality rule.\n"
+ f"Function name must be exactly: {function_name}\n"
+ "Input: product (dict)\n"
+ "Output: return the rule tag string if the VIOLATION condition is TRUE; else return None.\n"
+ "Important: do NOT invert the condition.\n"
+ "Important: return only Python code, no markdown, no explanation.\n"
+ "Behavior requirements:\n"
+ "- field_comparison and field_threshold rules: if value is missing/non-numeric, return None.\n"
+ '- missing_field rule: None, empty string "", or whitespace-only string => return tag.\n'
+ "- Otherwise return None.\n"
+ f"Rule JSON: {json.dumps(rule_payload)}\n"
+ f"Validation examples (must pass): {json.dumps(examples)}"
+ )
+
+
+def _build_llm_repair_prompt(
+ rule: Dict[str, object],
+ function_name: str,
+ previous_code: str,
+ error_message: str,
+) -> str:
+ return (
+ "Your previous function failed validator checks.\n"
+ f"Validation error: {error_message}\n"
+ "Fix the function so all examples pass.\n"
+ "Return only corrected Python code.\n"
+ f"Previous code:\n{previous_code}\n\n"
+ f"{_build_llm_prompt(rule, function_name)}"
+ )
+
+
+def _call_groq(
+ rule: Dict[str, object],
+ function_name: str,
+ model: str,
+ prompt: str | None = None,
+) -> str:
+ api_key = os.getenv("GROQ_API_KEY")
+ if not api_key:
+ raise RuntimeError("GROQ_API_KEY is not set.")
+
+ try:
+ from openai import OpenAI
+ except Exception as exc: # noqa: BLE001
+ raise RuntimeError("openai package is required for Groq provider.") from exc
+
+ endpoint = os.getenv("GROQ_ENDPOINT", "https://api.groq.com/openai/v1")
+ client = OpenAI(api_key=api_key, base_url=endpoint)
+ response = client.chat.completions.create(
+ model=model,
+ messages=[
+ {"role": "system", "content": "You are a strict Python code generator for data quality rules."},
+ {"role": "user", "content": prompt or _build_llm_prompt(rule, function_name)},
+ ],
+ temperature=0.0,
+ )
+ content = response.choices[0].message.content
+ if not isinstance(content, str):
+ content = str(content)
+ return _extract_code_block(content)
+
+
+def convert_rule_to_python(
+ rule: Dict[str, object],
+ provider: str = "groq",
+ model: str | None = None,
+) -> ConversionResult:
+ """Convert one structured rule to Python code and confidence metadata."""
+ function_name = f"check_{_safe_identifier(str(rule['rule_name']))}"
+ confidence = _confidence_for_rule(rule)
+ provider_used = provider
+
+ if provider == "groq":
+ strict_llm = os.getenv("LLM_STRICT", "0").strip().lower() in {"1", "true", "yes", "on"}
+ chosen_model = model or os.getenv("GROQ_MODEL", "openai/gpt-oss-120b")
+ first_attempt_code = ""
+ try:
+ python_code = _call_groq(rule, function_name=function_name, model=chosen_model)
+ first_attempt_code = python_code
+ python_code = _normalize_function_name(python_code, function_name=function_name)
+ _validate_generated_code(python_code, function_name=function_name)
+ _validate_generated_semantics(python_code, function_name=function_name, rule=rule)
+ notes = f"Converted via Groq ({chosen_model})."
+ confidence = min(0.99, confidence + 0.01)
+ except (
+ RuntimeError,
+ ValueError,
+ TypeError,
+ json.JSONDecodeError,
+ TimeoutError,
+ ) as exc:
+ repair_exc: Exception | None = None
+ try:
+ repair_prompt = _build_llm_repair_prompt(
+ rule=rule,
+ function_name=function_name,
+ previous_code=first_attempt_code or "# no usable code returned in first attempt",
+ error_message=f"{exc.__class__.__name__}: {exc}",
+ )
+ python_code = _call_groq(
+ rule,
+ function_name=function_name,
+ model=chosen_model,
+ prompt=repair_prompt,
+ )
+ python_code = _normalize_function_name(python_code, function_name=function_name)
+ _validate_generated_code(python_code, function_name=function_name)
+ _validate_generated_semantics(python_code, function_name=function_name, rule=rule)
+ notes = f"Converted via Groq ({chosen_model}) after repair pass."
+ confidence = min(0.99, confidence + 0.005)
+ except (
+ RuntimeError,
+ ValueError,
+ TypeError,
+ json.JSONDecodeError,
+ TimeoutError,
+ ) as second_exc:
+ repair_exc = second_exc
+
+ if repair_exc is not None:
+ if strict_llm:
+ raise RuntimeError(
+ f"Groq conversion failed and LLM_STRICT=1 is enabled. "
+ f"First error: {exc.__class__.__name__}: {exc} | "
+ f"Repair error: {repair_exc.__class__.__name__}: {repair_exc}"
+ ) from repair_exc
+ python_code = _build_python_code(rule, function_name=function_name)
+ _validate_generated_code(python_code, function_name=function_name)
+ _validate_generated_semantics(python_code, function_name=function_name, rule=rule)
+ notes = (
+ f"Groq conversion failed after retry "
+ f"(first: {exc.__class__.__name__}: {exc}; "
+ f"retry: {repair_exc.__class__.__name__}: {repair_exc}). "
+ "Fell back to deterministic converter."
+ )
+ provider_used = "simulated_fallback"
+ confidence = max(0.70, confidence - 0.05)
+ else:
+ if provider not in {"simulated", "simulated_fallback"}:
+ provider_used = "simulated_fallback"
+ python_code = _build_python_code(rule, function_name=function_name)
+ _validate_generated_code(python_code, function_name=function_name)
+ _validate_generated_semantics(python_code, function_name=function_name, rule=rule)
+ notes = f"Converted {rule['condition_type']} rule using deterministic template."
+
+ return ConversionResult(
+ rule_name=str(rule["rule_name"]),
+ function_name=function_name,
+ python_code=python_code,
+ llm_confidence=confidence,
+ conversion_notes=notes,
+ provider=provider_used,
+ )
+
+
+def _build_counterexample_repair_prompt(
+ rule: Dict[str, object],
+ function_name: str,
+ previous_code: str,
+ counterexamples: Sequence[Dict[str, object]],
+) -> str:
+ limited = list(counterexamples)[:5]
+ return (
+ "Your previous code fails equivalence against legacy Perl behavior.\n"
+ "Fix the function using these concrete failing examples.\n"
+ "Return only Python code.\n"
+ f"Function name must remain: {function_name}\n"
+ f"Counterexamples: {json.dumps(limited)}\n"
+ f"Previous code:\n{previous_code}\n\n"
+ f"{_build_llm_prompt(rule, function_name)}"
+ )
+
+
+def repair_conversion_with_counterexamples(
+ rule: Dict[str, object],
+ converted_rule: Dict[str, object],
+ counterexamples: Sequence[Dict[str, object]],
+ provider: str = "groq",
+ model: str | None = None,
+) -> Dict[str, object]:
+ """Attempt counterexample-driven repair for an already converted rule."""
+ if provider != "groq":
+ return dict(converted_rule)
+ if not counterexamples:
+ return dict(converted_rule)
+
+ function_name = str(converted_rule["function_name"])
+ previous_code = str(converted_rule["python_code"])
+ chosen_model = model or os.getenv("GROQ_MODEL", "openai/gpt-oss-120b")
+ repair_prompt = _build_counterexample_repair_prompt(
+ rule=rule,
+ function_name=function_name,
+ previous_code=previous_code,
+ counterexamples=counterexamples,
+ )
+ repaired_code = _call_groq(rule, function_name=function_name, model=chosen_model, prompt=repair_prompt)
+ repaired_code = _normalize_function_name(repaired_code, function_name=function_name)
+ _validate_generated_code(repaired_code, function_name=function_name)
+ _validate_generated_semantics(repaired_code, function_name=function_name, rule=rule)
+
+ repaired = dict(converted_rule)
+ repaired["python_code"] = repaired_code
+ repaired["provider"] = "groq"
+ repaired["llm_confidence"] = min(0.99, float(converted_rule.get("llm_confidence", 0.9)) + 0.01)
+ repaired["conversion_notes"] = (
+ f"{converted_rule.get('conversion_notes', '')} "
+ "Counterexample-driven Groq repair applied."
+ ).strip()
+ return repaired
+
+
+def convert_rules(
+ rules: Sequence[Dict[str, object]],
+ provider: str = "groq",
+ model: str | None = None,
+) -> List[Dict[str, object]]:
+ """Batch convert structured rules to generated Python snippets."""
+ return [asdict(convert_rule_to_python(rule, provider=provider, model=model)) for rule in rules]
diff --git a/OFF_DataQuality/perl_checks/__init__.py b/OFF_DataQuality/perl_checks/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/OFF_DataQuality/perl_checks/legacy_checks.py b/OFF_DataQuality/perl_checks/legacy_checks.py
new file mode 100644
index 0000000000000000000000000000000000000000..059f2cd7236d65b7a34d9dcfbab2dc831676c621
--- /dev/null
+++ b/OFF_DataQuality/perl_checks/legacy_checks.py
@@ -0,0 +1,590 @@
+"""Simulated legacy Perl checks for migration parity testing."""
+from __future__ import annotations
+
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Callable, Dict, List, Mapping, Sequence, Set
+
+Product = Mapping[str, object]
+
+
+@dataclass(frozen=True)
+class LegacyRule:
+ rule_name: str
+ tag: str
+ severity: str
+ condition: str
+ duckdb_condition: str
+ complexity: str
+ declarative_friendly: bool
+ perl_logic: str
+ evaluator: Callable[[Product], bool]
+
+
+def _to_float(value: object) -> float | None:
+ if value is None:
+ return None
+ try:
+ return float(value)
+ except (TypeError, ValueError):
+ return None
+
+
+def _greater_than(left_value: object, right_value: object) -> bool:
+ left = _to_float(left_value)
+ right = _to_float(right_value)
+ return left is not None and right is not None and left > right
+
+
+def _greater_than_plus_offset(left_value: object, right_value: object, offset: float) -> bool:
+ left = _to_float(left_value)
+ right = _to_float(right_value)
+ return left is not None and right is not None and left > (right + offset)
+
+
+def _affine_compare(
+ left_value: object,
+ right_value: object,
+ operator: str,
+ factor: float,
+ offset: float,
+) -> bool:
+ left = _to_float(left_value)
+ right = _to_float(right_value)
+ if left is None or right is None:
+ return False
+ target = (factor * right) + offset
+ if operator == ">":
+ return left > target
+ if operator == "<":
+ return left < target
+ if operator == ">=":
+ return left >= target
+ if operator == "<=":
+ return left <= target
+ if operator == "==":
+ return left == target
+ if operator == "!=":
+ return left != target
+ return False
+
+
+def _sum_compare(
+ left_a: object,
+ left_b: object,
+ operator: str,
+ right: object,
+ right_offset: float,
+) -> bool:
+ left_a_num = _to_float(left_a)
+ left_b_num = _to_float(left_b)
+ right_num = _to_float(right)
+ if left_a_num is None or left_b_num is None or right_num is None:
+ return False
+ left_sum = left_a_num + left_b_num
+ right_value = right_num + right_offset
+ if operator == ">":
+ return left_sum > right_value
+ if operator == "<":
+ return left_sum < right_value
+ if operator == ">=":
+ return left_sum >= right_value
+ if operator == "<=":
+ return left_sum <= right_value
+ if operator == "==":
+ return left_sum == right_value
+ if operator == "!=":
+ return left_sum != right_value
+ return False
+
+
+def _is_missing(value: object) -> bool:
+ return value is None or str(value).strip() == ""
+
+
+def _compare_values(left_value: object, operator: str, right_value: object) -> bool:
+ left = _to_float(left_value)
+ right = _to_float(right_value)
+ if left is None or right is None:
+ return False
+ if operator == ">":
+ return left > right
+ if operator == "<":
+ return left < right
+ if operator == ">=":
+ return left >= right
+ if operator == "<=":
+ return left <= right
+ if operator == "==":
+ return left == right
+ if operator == "!=":
+ return left != right
+ return False
+
+
+LEGACY_RULES: List[LegacyRule] = [
+ LegacyRule(
+ rule_name="energy_kcal_vs_kj",
+ tag="energy-value-in-kcal-greater-than-in-kj",
+ severity="error",
+ condition="energy_kcal > energy_kj",
+ duckdb_condition="energy_kcal > energy_kj",
+ complexity="simple",
+ declarative_friendly=True,
+ perl_logic="""
+# RULE_NAME: energy_kcal_vs_kj
+# SEVERITY: error
+# COMPLEXITY: simple
+# DECLARATIVE_FRIENDLY: yes
+if ($energy_kcal > $energy_kj) {
+ push @{$product_ref->{$data_quality_tags}}, "energy-value-in-kcal-greater-than-in-kj";
+}
+""".strip(),
+ evaluator=lambda product: _greater_than(product.get("energy_kcal"), product.get("energy_kj")),
+ ),
+ LegacyRule(
+ rule_name="energy_kj_mismatch_low",
+ tag="energy-value-in-kcal-does-not-match-value-in-kj-low",
+ severity="error",
+ condition="energy_kj < (3.7 * energy_kcal - 2)",
+ duckdb_condition="energy_kj < (3.7 * energy_kcal - 2)",
+ complexity="intricate",
+ declarative_friendly=False,
+ perl_logic="""
+# RULE_NAME: energy_kj_mismatch_low
+# SEVERITY: error
+# COMPLEXITY: intricate
+# DECLARATIVE_FRIENDLY: no
+if ($energy_kj < (3.7 * $energy_kcal - 2)) {
+ push @{$product_ref->{$data_quality_tags}}, "energy-value-in-kcal-does-not-match-value-in-kj-low";
+}
+""".strip(),
+ evaluator=lambda product: _affine_compare(
+ product.get("energy_kj"),
+ product.get("energy_kcal"),
+ operator="<",
+ factor=3.7,
+ offset=-2.0,
+ ),
+ ),
+ LegacyRule(
+ rule_name="energy_kj_mismatch_high",
+ tag="energy-value-in-kcal-does-not-match-value-in-kj-high",
+ severity="error",
+ condition="energy_kj > (4.7 * energy_kcal + 2)",
+ duckdb_condition="energy_kj > (4.7 * energy_kcal + 2)",
+ complexity="intricate",
+ declarative_friendly=False,
+ perl_logic="""
+# RULE_NAME: energy_kj_mismatch_high
+# SEVERITY: error
+# COMPLEXITY: intricate
+# DECLARATIVE_FRIENDLY: no
+if ($energy_kj > (4.7 * $energy_kcal + 2)) {
+ push @{$product_ref->{$data_quality_tags}}, "energy-value-in-kcal-does-not-match-value-in-kj-high";
+}
+""".strip(),
+ evaluator=lambda product: _affine_compare(
+ product.get("energy_kj"),
+ product.get("energy_kcal"),
+ operator=">",
+ factor=4.7,
+ offset=2.0,
+ ),
+ ),
+ LegacyRule(
+ rule_name="energy_kj_over_3911",
+ tag="value-over-3911-energy",
+ severity="error",
+ condition="energy_kj > 3911",
+ duckdb_condition="energy_kj > 3911",
+ complexity="simple",
+ declarative_friendly=True,
+ perl_logic="""
+# RULE_NAME: energy_kj_over_3911
+# SEVERITY: error
+# COMPLEXITY: simple
+# DECLARATIVE_FRIENDLY: yes
+if ($energy_kj > 3911) {
+ push @{$product_ref->{$data_quality_tags}}, "value-over-3911-energy";
+}
+""".strip(),
+ evaluator=lambda product: _greater_than(product.get("energy_kj"), 3911),
+ ),
+ LegacyRule(
+ rule_name="energy_kj_computed_mismatch_low",
+ tag="energy-value-in-kj-does-not-match-value-computed-from-other-nutrients-low",
+ severity="error",
+ condition="energy_kj_computed < (0.7 * energy_kj - 5)",
+ duckdb_condition="energy_kj_computed < (0.7 * energy_kj - 5)",
+ complexity="intricate",
+ declarative_friendly=False,
+ perl_logic="""
+# RULE_NAME: energy_kj_computed_mismatch_low
+# SEVERITY: error
+# COMPLEXITY: intricate
+# DECLARATIVE_FRIENDLY: no
+if ($energy_kj_computed < (0.7 * $energy_kj - 5)) {
+ push @{$product_ref->{$data_quality_tags}}, "energy-value-in-kj-does-not-match-value-computed-from-other-nutrients-low";
+}
+""".strip(),
+ evaluator=lambda product: _affine_compare(
+ product.get("energy_kj_computed"),
+ product.get("energy_kj"),
+ operator="<",
+ factor=0.7,
+ offset=-5.0,
+ ),
+ ),
+ LegacyRule(
+ rule_name="energy_kj_computed_mismatch_high",
+ tag="energy-value-in-kj-does-not-match-value-computed-from-other-nutrients-high",
+ severity="error",
+ condition="energy_kj_computed > (1.3 * energy_kj + 5)",
+ duckdb_condition="energy_kj_computed > (1.3 * energy_kj + 5)",
+ complexity="intricate",
+ declarative_friendly=False,
+ perl_logic="""
+# RULE_NAME: energy_kj_computed_mismatch_high
+# SEVERITY: error
+# COMPLEXITY: intricate
+# DECLARATIVE_FRIENDLY: no
+if ($energy_kj_computed > (1.3 * $energy_kj + 5)) {
+ push @{$product_ref->{$data_quality_tags}}, "energy-value-in-kj-does-not-match-value-computed-from-other-nutrients-high";
+}
+""".strip(),
+ evaluator=lambda product: _affine_compare(
+ product.get("energy_kj_computed"),
+ product.get("energy_kj"),
+ operator=">",
+ factor=1.3,
+ offset=5.0,
+ ),
+ ),
+ LegacyRule(
+ rule_name="saturated_fat_vs_fat",
+ tag="saturated-fat-greater-than-fat",
+ severity="error",
+ condition="saturated_fat > (1 * fat + 0.001)",
+ duckdb_condition="saturated_fat > (1 * fat + 0.001)",
+ complexity="simple",
+ declarative_friendly=True,
+ perl_logic="""
+# RULE_NAME: saturated_fat_vs_fat
+# SEVERITY: error
+# COMPLEXITY: simple
+# DECLARATIVE_FRIENDLY: yes
+if ($saturated_fat > (1 * $fat + 0.001)) {
+ push @{$product_ref->{$data_quality_tags}}, "saturated-fat-greater-than-fat";
+}
+""".strip(),
+ evaluator=lambda product: _greater_than_plus_offset(product.get("saturated_fat"), product.get("fat"), 0.001),
+ ),
+ LegacyRule(
+ rule_name="sugars_plus_starch_vs_carbohydrates",
+ tag="sugars-plus-starch-greater-than-carbohydrates",
+ severity="error",
+ condition="(sugars + starch) > (carbohydrates + 0.001)",
+ duckdb_condition="(sugars + starch) > (carbohydrates + 0.001)",
+ complexity="medium",
+ declarative_friendly=True,
+ perl_logic="""
+# RULE_NAME: sugars_plus_starch_vs_carbohydrates
+# SEVERITY: error
+# COMPLEXITY: medium
+# DECLARATIVE_FRIENDLY: yes
+if (($sugars + $starch) > ($carbohydrates + 0.001)) {
+ push @{$product_ref->{$data_quality_tags}}, "sugars-plus-starch-greater-than-carbohydrates";
+}
+""".strip(),
+ evaluator=lambda product: _sum_compare(
+ product.get("sugars"),
+ product.get("starch"),
+ operator=">",
+ right=product.get("carbohydrates"),
+ right_offset=0.001,
+ ),
+ ),
+ LegacyRule(
+ rule_name="fat_over_105g",
+ tag="fat-value-over-105g",
+ severity="warning",
+ condition="fat > 105",
+ duckdb_condition="fat > 105",
+ complexity="simple",
+ declarative_friendly=True,
+ perl_logic="""
+# RULE_NAME: fat_over_105g
+# SEVERITY: warning
+# COMPLEXITY: simple
+# DECLARATIVE_FRIENDLY: yes
+if ($fat > 105) {
+ push @{$product_ref->{$data_quality_tags}}, "fat-value-over-105g";
+}
+""".strip(),
+ evaluator=lambda product: _greater_than(product.get("fat"), 105),
+ ),
+ LegacyRule(
+ rule_name="saturated_fat_over_105g",
+ tag="saturated-fat-value-over-105g",
+ severity="warning",
+ condition="saturated_fat > 105",
+ duckdb_condition="saturated_fat > 105",
+ complexity="simple",
+ declarative_friendly=True,
+ perl_logic="""
+# RULE_NAME: saturated_fat_over_105g
+# SEVERITY: warning
+# COMPLEXITY: simple
+# DECLARATIVE_FRIENDLY: yes
+if ($saturated_fat > 105) {
+ push @{$product_ref->{$data_quality_tags}}, "saturated-fat-value-over-105g";
+}
+""".strip(),
+ evaluator=lambda product: _greater_than(product.get("saturated_fat"), 105),
+ ),
+ LegacyRule(
+ rule_name="carbohydrates_over_105g",
+ tag="carbohydrates-value-over-105g",
+ severity="warning",
+ condition="carbohydrates > 105",
+ duckdb_condition="carbohydrates > 105",
+ complexity="simple",
+ declarative_friendly=True,
+ perl_logic="""
+# RULE_NAME: carbohydrates_over_105g
+# SEVERITY: warning
+# COMPLEXITY: simple
+# DECLARATIVE_FRIENDLY: yes
+if ($carbohydrates > 105) {
+ push @{$product_ref->{$data_quality_tags}}, "carbohydrates-value-over-105g";
+}
+""".strip(),
+ evaluator=lambda product: _greater_than(product.get("carbohydrates"), 105),
+ ),
+ LegacyRule(
+ rule_name="sugars_over_105g",
+ tag="sugars-value-over-105g",
+ severity="warning",
+ condition="sugars > 105",
+ duckdb_condition="sugars > 105",
+ complexity="simple",
+ declarative_friendly=True,
+ perl_logic="""
+# RULE_NAME: sugars_over_105g
+# SEVERITY: warning
+# COMPLEXITY: simple
+# DECLARATIVE_FRIENDLY: yes
+if ($sugars > 105) {
+ push @{$product_ref->{$data_quality_tags}}, "sugars-value-over-105g";
+}
+""".strip(),
+ evaluator=lambda product: _greater_than(product.get("sugars"), 105),
+ ),
+ LegacyRule(
+ rule_name="main_language_code_missing",
+ tag="main-language-code-missing",
+ severity="bug",
+ condition="missing(lc)",
+ duckdb_condition="lc IS NULL OR TRIM(lc) = ''",
+ complexity="simple",
+ declarative_friendly=True,
+ perl_logic="""
+# RULE_NAME: main_language_code_missing
+# SEVERITY: bug
+# COMPLEXITY: simple
+# DECLARATIVE_FRIENDLY: yes
+if (!defined $lc || $lc eq "") {
+ push @{$product_ref->{$data_quality_tags}}, "main-language-code-missing";
+}
+""".strip(),
+ evaluator=lambda product: _is_missing(product.get("lc")),
+ ),
+ LegacyRule(
+ rule_name="main_language_missing",
+ tag="main-language-missing",
+ severity="bug",
+ condition="missing(lang)",
+ duckdb_condition="lang IS NULL OR TRIM(lang) = ''",
+ complexity="simple",
+ declarative_friendly=True,
+ perl_logic="""
+# RULE_NAME: main_language_missing
+# SEVERITY: bug
+# COMPLEXITY: simple
+# DECLARATIVE_FRIENDLY: yes
+if (!defined $lang || $lang eq "") {
+ push @{$product_ref->{$data_quality_tags}}, "main-language-missing";
+}
+ """.strip(),
+ evaluator=lambda product: _is_missing(product.get("lang")),
+ ),
+ LegacyRule(
+ rule_name="ca_allergen_evidence_missing_ingredients_text",
+ tag="ca-allergen-evidence-but-missing-ingredients-text",
+ severity="warning",
+ condition="allergen_evidence_present > 0 && ingredients_text_present == 0",
+ duckdb_condition="allergen_evidence_present > 0 AND ingredients_text_present == 0",
+ complexity="medium",
+ declarative_friendly=True,
+ perl_logic="""
+# RULE_NAME: ca_allergen_evidence_missing_ingredients_text
+# SEVERITY: warning
+# COMPLEXITY: medium
+# DECLARATIVE_FRIENDLY: yes
+if (($allergen_evidence_present > 0) && ($ingredients_text_present == 0)) {
+ push @{$product_ref->{$data_quality_tags}}, "ca-allergen-evidence-but-missing-ingredients-text";
+}
+""".strip(),
+ evaluator=lambda product: (
+ _compare_values(product.get("allergen_evidence_present"), ">", 0)
+ and _compare_values(product.get("ingredients_text_present"), "==", 0)
+ ),
+ ),
+ LegacyRule(
+ rule_name="ca_contains_statement_without_allergen_evidence",
+ tag="ca-contains-statement-without-allergen-evidence",
+ severity="warning",
+ condition="contains_statement_present > 0 && allergen_evidence_present == 0",
+ duckdb_condition="contains_statement_present > 0 AND allergen_evidence_present == 0",
+ complexity="medium",
+ declarative_friendly=True,
+ perl_logic="""
+# RULE_NAME: ca_contains_statement_without_allergen_evidence
+# SEVERITY: warning
+# COMPLEXITY: medium
+# DECLARATIVE_FRIENDLY: yes
+if (($contains_statement_present > 0) && ($allergen_evidence_present == 0)) {
+ push @{$product_ref->{$data_quality_tags}}, "ca-contains-statement-without-allergen-evidence";
+}
+""".strip(),
+ evaluator=lambda product: (
+ _compare_values(product.get("contains_statement_present"), ">", 0)
+ and _compare_values(product.get("allergen_evidence_present"), "==", 0)
+ ),
+ ),
+ LegacyRule(
+ rule_name="ca_fop_required_but_symbol_missing",
+ tag="ca-fop-required-but-symbol-missing",
+ severity="error",
+ condition="fop_threshold_exceeded > 0 && fop_symbol_present == 0 && fop_exempt_proxy == 0 && product_is_prepackaged_proxy > 0",
+ duckdb_condition=(
+ "fop_threshold_exceeded > 0 AND fop_symbol_present == 0 "
+ "AND fop_exempt_proxy == 0 AND product_is_prepackaged_proxy > 0"
+ ),
+ complexity="medium",
+ declarative_friendly=True,
+ perl_logic="""
+# RULE_NAME: ca_fop_required_but_symbol_missing
+# SEVERITY: error
+# COMPLEXITY: medium
+# DECLARATIVE_FRIENDLY: yes
+if (($fop_threshold_exceeded > 0) && ($fop_symbol_present == 0) && ($fop_exempt_proxy == 0) && ($product_is_prepackaged_proxy > 0)) {
+ push @{$product_ref->{$data_quality_tags}}, "ca-fop-required-but-symbol-missing";
+}
+""".strip(),
+ evaluator=lambda product: (
+ _compare_values(product.get("fop_threshold_exceeded"), ">", 0)
+ and _compare_values(product.get("fop_symbol_present"), "==", 0)
+ and _compare_values(product.get("fop_exempt_proxy"), "==", 0)
+ and _compare_values(product.get("product_is_prepackaged_proxy"), ">", 0)
+ ),
+ ),
+ LegacyRule(
+ rule_name="ca_fop_symbol_present_but_not_required",
+ tag="ca-fop-symbol-present-but-not-required",
+ severity="warning",
+ condition="fop_symbol_present > 0 && fop_threshold_exceeded == 0 && fop_exempt_proxy == 0 && product_is_prepackaged_proxy > 0",
+ duckdb_condition=(
+ "fop_symbol_present > 0 AND fop_threshold_exceeded == 0 "
+ "AND fop_exempt_proxy == 0 AND product_is_prepackaged_proxy > 0"
+ ),
+ complexity="medium",
+ declarative_friendly=True,
+ perl_logic="""
+# RULE_NAME: ca_fop_symbol_present_but_not_required
+# SEVERITY: warning
+# COMPLEXITY: medium
+# DECLARATIVE_FRIENDLY: yes
+if (($fop_symbol_present > 0) && ($fop_threshold_exceeded == 0) && ($fop_exempt_proxy == 0) && ($product_is_prepackaged_proxy > 0)) {
+ push @{$product_ref->{$data_quality_tags}}, "ca-fop-symbol-present-but-not-required";
+}
+""".strip(),
+ evaluator=lambda product: (
+ _compare_values(product.get("fop_symbol_present"), ">", 0)
+ and _compare_values(product.get("fop_threshold_exceeded"), "==", 0)
+ and _compare_values(product.get("fop_exempt_proxy"), "==", 0)
+ and _compare_values(product.get("product_is_prepackaged_proxy"), ">", 0)
+ ),
+ ),
+ LegacyRule(
+ rule_name="ca_fop_symbol_present_on_exempt_product",
+ tag="ca-fop-symbol-present-on-exempt-product",
+ severity="warning",
+ condition="fop_symbol_present > 0 && fop_exempt_proxy > 0 && product_is_prepackaged_proxy > 0",
+ duckdb_condition="fop_symbol_present > 0 AND fop_exempt_proxy > 0 AND product_is_prepackaged_proxy > 0",
+ complexity="medium",
+ declarative_friendly=True,
+ perl_logic="""
+# RULE_NAME: ca_fop_symbol_present_on_exempt_product
+# SEVERITY: warning
+# COMPLEXITY: medium
+# DECLARATIVE_FRIENDLY: yes
+if (($fop_symbol_present > 0) && ($fop_exempt_proxy > 0) && ($product_is_prepackaged_proxy > 0)) {
+ push @{$product_ref->{$data_quality_tags}}, "ca-fop-symbol-present-on-exempt-product";
+}
+""".strip(),
+ evaluator=lambda product: (
+ _compare_values(product.get("fop_symbol_present"), ">", 0)
+ and _compare_values(product.get("fop_exempt_proxy"), ">", 0)
+ and _compare_values(product.get("product_is_prepackaged_proxy"), ">", 0)
+ ),
+ ),
+]
+
+
+RULE_FILES_DIR = Path(__file__).resolve().parent / "rules"
+
+
+def load_rule_snippets_from_directory(rules_dir: Path = RULE_FILES_DIR) -> List[str]:
+ snippets: List[str] = []
+ for file_path in sorted(rules_dir.glob("*.pl")):
+ content = file_path.read_text(encoding="utf-8").lstrip("\ufeff").strip()
+ if content:
+ snippets.append(content)
+ if not snippets:
+ raise ValueError(f"No Perl rule files found in {rules_dir}")
+ return snippets
+
+
+def get_perl_rule_snippets(
+ rules: Sequence[LegacyRule] = LEGACY_RULES,
+ rules_dir: Path | None = None,
+) -> List[str]:
+ if rules_dir is not None:
+ return load_rule_snippets_from_directory(Path(rules_dir))
+ return [rule.perl_logic for rule in rules]
+
+
+def get_legacy_rule_map(rules: Sequence[LegacyRule] = LEGACY_RULES) -> Dict[str, LegacyRule]:
+ return {rule.rule_name: rule for rule in rules}
+
+
+def run_perl_checks(products: Sequence[Product], rules: Sequence[LegacyRule] = LEGACY_RULES) -> Dict[str, Dict[str, object]]:
+ """Run simulated Perl checks and return per-product and per-rule outputs."""
+ per_product_tags: Dict[str, List[str]] = {}
+ per_rule_products: Dict[str, Set[str]] = {rule.rule_name: set() for rule in rules}
+
+ for product in products:
+ product_id = str(product.get("product_id"))
+ emitted_tags: List[str] = []
+ for rule in rules:
+ if rule.evaluator(product):
+ emitted_tags.append(rule.tag)
+ per_rule_products[rule.rule_name].add(product_id)
+ per_product_tags[product_id] = emitted_tags
+
+ return {
+ "per_product": per_product_tags,
+ "per_rule": {name: sorted(ids) for name, ids in per_rule_products.items()},
+ }
diff --git a/OFF_DataQuality/perl_checks/rules/01_energy_kcal_vs_kj.pl b/OFF_DataQuality/perl_checks/rules/01_energy_kcal_vs_kj.pl
new file mode 100644
index 0000000000000000000000000000000000000000..a0ec6d4c22855e036d34612303db49766aa4139a
--- /dev/null
+++ b/OFF_DataQuality/perl_checks/rules/01_energy_kcal_vs_kj.pl
@@ -0,0 +1,7 @@
+# RULE_NAME: energy_kcal_vs_kj
+# SEVERITY: error
+# COMPLEXITY: simple
+# DECLARATIVE_FRIENDLY: yes
+if ($energy_kcal > $energy_kj) {
+ push @{$product_ref->{$data_quality_tags}}, "energy-value-in-kcal-greater-than-in-kj";
+}
diff --git a/OFF_DataQuality/perl_checks/rules/02_energy_kj_mismatch_low.pl b/OFF_DataQuality/perl_checks/rules/02_energy_kj_mismatch_low.pl
new file mode 100644
index 0000000000000000000000000000000000000000..0478bf90922140b69a599d25c42869e3c2293dad
--- /dev/null
+++ b/OFF_DataQuality/perl_checks/rules/02_energy_kj_mismatch_low.pl
@@ -0,0 +1,7 @@
+# RULE_NAME: energy_kj_mismatch_low
+# SEVERITY: error
+# COMPLEXITY: intricate
+# DECLARATIVE_FRIENDLY: no
+if ($energy_kj < (3.7 * $energy_kcal - 2)) {
+ push @{$product_ref->{$data_quality_tags}}, "energy-value-in-kcal-does-not-match-value-in-kj-low";
+}
diff --git a/OFF_DataQuality/perl_checks/rules/03_energy_kj_mismatch_high.pl b/OFF_DataQuality/perl_checks/rules/03_energy_kj_mismatch_high.pl
new file mode 100644
index 0000000000000000000000000000000000000000..dc9daf4f0e4f8bffcda48bd4802ed9d3371576f5
--- /dev/null
+++ b/OFF_DataQuality/perl_checks/rules/03_energy_kj_mismatch_high.pl
@@ -0,0 +1,7 @@
+# RULE_NAME: energy_kj_mismatch_high
+# SEVERITY: error
+# COMPLEXITY: intricate
+# DECLARATIVE_FRIENDLY: no
+if ($energy_kj > (4.7 * $energy_kcal + 2)) {
+ push @{$product_ref->{$data_quality_tags}}, "energy-value-in-kcal-does-not-match-value-in-kj-high";
+}
diff --git a/OFF_DataQuality/perl_checks/rules/04_energy_kj_over_3911.pl b/OFF_DataQuality/perl_checks/rules/04_energy_kj_over_3911.pl
new file mode 100644
index 0000000000000000000000000000000000000000..aa6609cfe0c30349222422baa9993866b2cb3901
--- /dev/null
+++ b/OFF_DataQuality/perl_checks/rules/04_energy_kj_over_3911.pl
@@ -0,0 +1,7 @@
+# RULE_NAME: energy_kj_over_3911
+# SEVERITY: error
+# COMPLEXITY: simple
+# DECLARATIVE_FRIENDLY: yes
+if ($energy_kj > 3911) {
+ push @{$product_ref->{$data_quality_tags}}, "value-over-3911-energy";
+}
diff --git a/OFF_DataQuality/perl_checks/rules/05_saturated_fat_vs_fat.pl b/OFF_DataQuality/perl_checks/rules/05_saturated_fat_vs_fat.pl
new file mode 100644
index 0000000000000000000000000000000000000000..2efa63513c0d483173a6cba3024386faa0978169
--- /dev/null
+++ b/OFF_DataQuality/perl_checks/rules/05_saturated_fat_vs_fat.pl
@@ -0,0 +1,7 @@
+# RULE_NAME: saturated_fat_vs_fat
+# SEVERITY: error
+# COMPLEXITY: simple
+# DECLARATIVE_FRIENDLY: yes
+if ($saturated_fat > (1 * $fat + 0.001)) {
+ push @{$product_ref->{$data_quality_tags}}, "saturated-fat-greater-than-fat";
+}
diff --git a/OFF_DataQuality/perl_checks/rules/06_sugars_plus_starch_vs_carbohydrates.pl b/OFF_DataQuality/perl_checks/rules/06_sugars_plus_starch_vs_carbohydrates.pl
new file mode 100644
index 0000000000000000000000000000000000000000..d330a70f295c7a687e8d9cf5d0ecd1c32972fe49
--- /dev/null
+++ b/OFF_DataQuality/perl_checks/rules/06_sugars_plus_starch_vs_carbohydrates.pl
@@ -0,0 +1,7 @@
+# RULE_NAME: sugars_plus_starch_vs_carbohydrates
+# SEVERITY: error
+# COMPLEXITY: medium
+# DECLARATIVE_FRIENDLY: yes
+if (($sugars + $starch) > ($carbohydrates + 0.001)) {
+ push @{$product_ref->{$data_quality_tags}}, "sugars-plus-starch-greater-than-carbohydrates";
+}
diff --git a/OFF_DataQuality/perl_checks/rules/07_fat_over_105g.pl b/OFF_DataQuality/perl_checks/rules/07_fat_over_105g.pl
new file mode 100644
index 0000000000000000000000000000000000000000..20d32756c658a90b98b54dad43e7224902737977
--- /dev/null
+++ b/OFF_DataQuality/perl_checks/rules/07_fat_over_105g.pl
@@ -0,0 +1,7 @@
+# RULE_NAME: fat_over_105g
+# SEVERITY: warning
+# COMPLEXITY: simple
+# DECLARATIVE_FRIENDLY: yes
+if ($fat > 105) {
+ push @{$product_ref->{$data_quality_tags}}, "fat-value-over-105g";
+}
diff --git a/OFF_DataQuality/perl_checks/rules/08_saturated_fat_over_105g.pl b/OFF_DataQuality/perl_checks/rules/08_saturated_fat_over_105g.pl
new file mode 100644
index 0000000000000000000000000000000000000000..7d556ee7a51bd0b4fd431be2c974ed1b16446f5f
--- /dev/null
+++ b/OFF_DataQuality/perl_checks/rules/08_saturated_fat_over_105g.pl
@@ -0,0 +1,7 @@
+# RULE_NAME: saturated_fat_over_105g
+# SEVERITY: warning
+# COMPLEXITY: simple
+# DECLARATIVE_FRIENDLY: yes
+if ($saturated_fat > 105) {
+ push @{$product_ref->{$data_quality_tags}}, "saturated-fat-value-over-105g";
+}
diff --git a/OFF_DataQuality/perl_checks/rules/09_carbohydrates_over_105g.pl b/OFF_DataQuality/perl_checks/rules/09_carbohydrates_over_105g.pl
new file mode 100644
index 0000000000000000000000000000000000000000..d6eb7860a01c6c0d18979af964c221d08e6365d1
--- /dev/null
+++ b/OFF_DataQuality/perl_checks/rules/09_carbohydrates_over_105g.pl
@@ -0,0 +1,7 @@
+# RULE_NAME: carbohydrates_over_105g
+# SEVERITY: warning
+# COMPLEXITY: simple
+# DECLARATIVE_FRIENDLY: yes
+if ($carbohydrates > 105) {
+ push @{$product_ref->{$data_quality_tags}}, "carbohydrates-value-over-105g";
+}
diff --git a/OFF_DataQuality/perl_checks/rules/10_sugars_over_105g.pl b/OFF_DataQuality/perl_checks/rules/10_sugars_over_105g.pl
new file mode 100644
index 0000000000000000000000000000000000000000..4839ef5b4f1f3b904caef45abfcf4f9a39c4abce
--- /dev/null
+++ b/OFF_DataQuality/perl_checks/rules/10_sugars_over_105g.pl
@@ -0,0 +1,7 @@
+# RULE_NAME: sugars_over_105g
+# SEVERITY: warning
+# COMPLEXITY: simple
+# DECLARATIVE_FRIENDLY: yes
+if ($sugars > 105) {
+ push @{$product_ref->{$data_quality_tags}}, "sugars-value-over-105g";
+}
diff --git a/OFF_DataQuality/perl_checks/rules/11_main_language_code_missing.pl b/OFF_DataQuality/perl_checks/rules/11_main_language_code_missing.pl
new file mode 100644
index 0000000000000000000000000000000000000000..5f53d1b6d65f01f4efe61dd288ec8f65766f382d
--- /dev/null
+++ b/OFF_DataQuality/perl_checks/rules/11_main_language_code_missing.pl
@@ -0,0 +1,7 @@
+# RULE_NAME: main_language_code_missing
+# SEVERITY: bug
+# COMPLEXITY: simple
+# DECLARATIVE_FRIENDLY: yes
+if (!defined $lc || $lc eq "") {
+ push @{$product_ref->{$data_quality_tags}}, "main-language-code-missing";
+}
diff --git a/OFF_DataQuality/perl_checks/rules/12_main_language_missing.pl b/OFF_DataQuality/perl_checks/rules/12_main_language_missing.pl
new file mode 100644
index 0000000000000000000000000000000000000000..bc720aa612352115b1575fce56786caa4fd1e2e9
--- /dev/null
+++ b/OFF_DataQuality/perl_checks/rules/12_main_language_missing.pl
@@ -0,0 +1,7 @@
+# RULE_NAME: main_language_missing
+# SEVERITY: bug
+# COMPLEXITY: simple
+# DECLARATIVE_FRIENDLY: yes
+if (!defined $lang || $lang eq "") {
+ push @{$product_ref->{$data_quality_tags}}, "main-language-missing";
+}
diff --git a/OFF_DataQuality/perl_checks/rules/13_energy_kj_computed_mismatch_low.pl b/OFF_DataQuality/perl_checks/rules/13_energy_kj_computed_mismatch_low.pl
new file mode 100644
index 0000000000000000000000000000000000000000..a576d43befed2205cf764bffe23998fd9907c112
--- /dev/null
+++ b/OFF_DataQuality/perl_checks/rules/13_energy_kj_computed_mismatch_low.pl
@@ -0,0 +1,7 @@
+# RULE_NAME: energy_kj_computed_mismatch_low
+# SEVERITY: error
+# COMPLEXITY: intricate
+# DECLARATIVE_FRIENDLY: no
+if ($energy_kj_computed < (0.7 * $energy_kj - 5)) {
+ push @{$product_ref->{$data_quality_tags}}, "energy-value-in-kj-does-not-match-value-computed-from-other-nutrients-low";
+}
diff --git a/OFF_DataQuality/perl_checks/rules/14_energy_kj_computed_mismatch_high.pl b/OFF_DataQuality/perl_checks/rules/14_energy_kj_computed_mismatch_high.pl
new file mode 100644
index 0000000000000000000000000000000000000000..972ddc46428d08954e02f929c38eb7cd2655ec26
--- /dev/null
+++ b/OFF_DataQuality/perl_checks/rules/14_energy_kj_computed_mismatch_high.pl
@@ -0,0 +1,7 @@
+# RULE_NAME: energy_kj_computed_mismatch_high
+# SEVERITY: error
+# COMPLEXITY: intricate
+# DECLARATIVE_FRIENDLY: no
+if ($energy_kj_computed > (1.3 * $energy_kj + 5)) {
+ push @{$product_ref->{$data_quality_tags}}, "energy-value-in-kj-does-not-match-value-computed-from-other-nutrients-high";
+}
diff --git a/OFF_DataQuality/perl_checks/rules/15_ca_allergen_evidence_missing_ingredients_text.pl b/OFF_DataQuality/perl_checks/rules/15_ca_allergen_evidence_missing_ingredients_text.pl
new file mode 100644
index 0000000000000000000000000000000000000000..79ef17d6ece4644b4542a31b840ac057b3e47857
--- /dev/null
+++ b/OFF_DataQuality/perl_checks/rules/15_ca_allergen_evidence_missing_ingredients_text.pl
@@ -0,0 +1,7 @@
+# RULE_NAME: ca_allergen_evidence_missing_ingredients_text
+# SEVERITY: warning
+# COMPLEXITY: medium
+# DECLARATIVE_FRIENDLY: yes
+if (($allergen_evidence_present > 0) && ($ingredients_text_present == 0)) {
+ push @{$product_ref->{$data_quality_tags}}, "ca-allergen-evidence-but-missing-ingredients-text";
+}
diff --git a/OFF_DataQuality/perl_checks/rules/16_ca_contains_statement_without_allergen_evidence.pl b/OFF_DataQuality/perl_checks/rules/16_ca_contains_statement_without_allergen_evidence.pl
new file mode 100644
index 0000000000000000000000000000000000000000..d47e484541d6ae8e54d06b3c716b530bf60722f0
--- /dev/null
+++ b/OFF_DataQuality/perl_checks/rules/16_ca_contains_statement_without_allergen_evidence.pl
@@ -0,0 +1,7 @@
+# RULE_NAME: ca_contains_statement_without_allergen_evidence
+# SEVERITY: warning
+# COMPLEXITY: medium
+# DECLARATIVE_FRIENDLY: yes
+if (($contains_statement_present > 0) && ($allergen_evidence_present == 0)) {
+ push @{$product_ref->{$data_quality_tags}}, "ca-contains-statement-without-allergen-evidence";
+}
diff --git a/OFF_DataQuality/perl_checks/rules/17_ca_fop_required_but_symbol_missing.pl b/OFF_DataQuality/perl_checks/rules/17_ca_fop_required_but_symbol_missing.pl
new file mode 100644
index 0000000000000000000000000000000000000000..1fd04fb83af7d97a62c63d75d4bb0620fe66deaf
--- /dev/null
+++ b/OFF_DataQuality/perl_checks/rules/17_ca_fop_required_but_symbol_missing.pl
@@ -0,0 +1,7 @@
+# RULE_NAME: ca_fop_required_but_symbol_missing
+# SEVERITY: error
+# COMPLEXITY: medium
+# DECLARATIVE_FRIENDLY: yes
+if (($fop_threshold_exceeded > 0) && ($fop_symbol_present == 0) && ($fop_exempt_proxy == 0) && ($product_is_prepackaged_proxy > 0)) {
+ push @{$product_ref->{$data_quality_tags}}, "ca-fop-required-but-symbol-missing";
+}
diff --git a/OFF_DataQuality/perl_checks/rules/18_ca_fop_symbol_present_but_not_required.pl b/OFF_DataQuality/perl_checks/rules/18_ca_fop_symbol_present_but_not_required.pl
new file mode 100644
index 0000000000000000000000000000000000000000..40f858fd914b6f6b5741b7c638089dd301d94ffd
--- /dev/null
+++ b/OFF_DataQuality/perl_checks/rules/18_ca_fop_symbol_present_but_not_required.pl
@@ -0,0 +1,7 @@
+# RULE_NAME: ca_fop_symbol_present_but_not_required
+# SEVERITY: warning
+# COMPLEXITY: medium
+# DECLARATIVE_FRIENDLY: yes
+if (($fop_symbol_present > 0) && ($fop_threshold_exceeded == 0) && ($fop_exempt_proxy == 0) && ($product_is_prepackaged_proxy > 0)) {
+ push @{$product_ref->{$data_quality_tags}}, "ca-fop-symbol-present-but-not-required";
+}
diff --git a/OFF_DataQuality/perl_checks/rules/19_ca_fop_symbol_present_on_exempt_product.pl b/OFF_DataQuality/perl_checks/rules/19_ca_fop_symbol_present_on_exempt_product.pl
new file mode 100644
index 0000000000000000000000000000000000000000..c82dd93e7443e60279c450a1e6c115dded487640
--- /dev/null
+++ b/OFF_DataQuality/perl_checks/rules/19_ca_fop_symbol_present_on_exempt_product.pl
@@ -0,0 +1,7 @@
+# RULE_NAME: ca_fop_symbol_present_on_exempt_product
+# SEVERITY: warning
+# COMPLEXITY: medium
+# DECLARATIVE_FRIENDLY: yes
+if (($fop_symbol_present > 0) && ($fop_exempt_proxy > 0) && ($product_is_prepackaged_proxy > 0)) {
+ push @{$product_ref->{$data_quality_tags}}, "ca-fop-symbol-present-on-exempt-product";
+}
diff --git a/OFF_DataQuality/pytest.ini b/OFF_DataQuality/pytest.ini
new file mode 100644
index 0000000000000000000000000000000000000000..53bfcf9276d71c928071856de4249bbd657a2470
--- /dev/null
+++ b/OFF_DataQuality/pytest.ini
@@ -0,0 +1,2 @@
+[pytest]
+testpaths = tests
diff --git a/OFF_DataQuality/python_checks/__init__.py b/OFF_DataQuality/python_checks/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/OFF_DataQuality/python_checks/generated_checks.py b/OFF_DataQuality/python_checks/generated_checks.py
new file mode 100644
index 0000000000000000000000000000000000000000..85be184f32e147832520dc3852cafe56f0267d72
--- /dev/null
+++ b/OFF_DataQuality/python_checks/generated_checks.py
@@ -0,0 +1,36 @@
+"""Runtime compiler for generated Python checks."""
+from __future__ import annotations
+
+from typing import Callable, Dict, List, Tuple
+
+
+def compile_generated_checks(
+ converted_rules: List[Dict[str, object]],
+) -> Tuple[Dict[str, Callable[[Dict[str, object]], object]], Dict[str, Dict[str, object]]]:
+ """Compile generated Python snippets into callable checks."""
+ checks: Dict[str, Callable[[Dict[str, object]], object]] = {}
+ metadata: Dict[str, Dict[str, object]] = {}
+
+ for converted in converted_rules:
+ function_name = str(converted["function_name"])
+ rule_name = str(converted["rule_name"])
+ code = str(converted["python_code"])
+
+ namespace: Dict[str, object] = {}
+ exec(code, {}, namespace)
+ check_fn = namespace[function_name]
+ checks[rule_name] = check_fn
+ metadata[rule_name] = {
+ "function_name": function_name,
+ "python_code": code,
+ "llm_confidence": float(converted["llm_confidence"]),
+ "conversion_notes": converted["conversion_notes"],
+ "provider": converted.get("provider", "unknown"),
+ }
+ return checks, metadata
+
+
+def render_generated_module(metadata: Dict[str, Dict[str, object]]) -> str:
+ """Return a readable module-like rendering of generated checks."""
+ code_blocks = [str(info["python_code"]).rstrip() for info in metadata.values()]
+ return "\n\n".join(code_blocks) + "\n"
diff --git a/OFF_DataQuality/requirements.txt b/OFF_DataQuality/requirements.txt
new file mode 100644
index 0000000000000000000000000000000000000000..f10e5f75793655f674438ca575ffdcc63bf23201
--- /dev/null
+++ b/OFF_DataQuality/requirements.txt
@@ -0,0 +1,8 @@
+duckdb
+streamlit
+pandas
+openai
+pytest
+plotly
+dbt-duckdb
+soda-duckdb
diff --git a/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/dbt_project.yml b/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/dbt_project.yml
new file mode 100644
index 0000000000000000000000000000000000000000..298a835daac9169ef49a0c2c9ec0805acb39bb87
--- /dev/null
+++ b/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/dbt_project.yml
@@ -0,0 +1,6 @@
+name: off_quality_declarative
+version: '1.0'
+config-version: 2
+profile: off_quality_duckdb
+model-paths: ['models']
+test-paths: ['tests']
diff --git a/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/macros/count_violations.sql b/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/macros/count_violations.sql
new file mode 100644
index 0000000000000000000000000000000000000000..b2f5860e30680cd91ea4d3cb7a30a3aa06aeadb1
--- /dev/null
+++ b/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/macros/count_violations.sql
@@ -0,0 +1,12 @@
+{% macro count_violations(condition_sql) %}
+ {% set q %}
+ select count(*) as violation_count
+ from {{ source('off_source', 'nutrition_table') }}
+ where {{ condition_sql }}
+ {% endset %}
+ {% set t = run_query(q) %}
+ {% if execute %}
+ {% set c = t.columns[0].values()[0] %}
+ {% do log('VIOLATION_COUNT=' ~ c, info=True) %}
+ {% endif %}
+{% endmacro %}
diff --git a/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/models/sources.yml b/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/models/sources.yml
new file mode 100644
index 0000000000000000000000000000000000000000..2257ae92ba3422631b5dad7eb6b2bb5d8ae8d22e
--- /dev/null
+++ b/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/models/sources.yml
@@ -0,0 +1,6 @@
+version: 2
+sources:
+ - name: off_source
+ schema: main
+ tables:
+ - name: nutrition_table
diff --git a/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/profiles.yml b/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/profiles.yml
new file mode 100644
index 0000000000000000000000000000000000000000..671409d1df80f793c1356e269083428aedfa8030
--- /dev/null
+++ b/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/profiles.yml
@@ -0,0 +1,8 @@
+off_quality_duckdb:
+ target: dev
+ outputs:
+ dev:
+ type: duckdb
+ path: 'results/declarative_runtime/dbt/dbt_runtime.db'
+ schema: main
+ threads: 1
diff --git a/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/tests/ca_allergen_evidence_missing_ingredients_text.sql b/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/tests/ca_allergen_evidence_missing_ingredients_text.sql
new file mode 100644
index 0000000000000000000000000000000000000000..5cba65e89f6db7703a9e0ad372581da55a6eef26
--- /dev/null
+++ b/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/tests/ca_allergen_evidence_missing_ingredients_text.sql
@@ -0,0 +1,3 @@
+SELECT product_id
+FROM {{ source('off_source', 'nutrition_table') }}
+WHERE allergen_evidence_present > 0.0 AND ingredients_text_present == 0.0
diff --git a/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/tests/ca_contains_statement_without_allergen_evidence.sql b/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/tests/ca_contains_statement_without_allergen_evidence.sql
new file mode 100644
index 0000000000000000000000000000000000000000..f1bbfced480baca63044d9b1e8dd8df3ddcbc32d
--- /dev/null
+++ b/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/tests/ca_contains_statement_without_allergen_evidence.sql
@@ -0,0 +1,3 @@
+SELECT product_id
+FROM {{ source('off_source', 'nutrition_table') }}
+WHERE contains_statement_present > 0.0 AND allergen_evidence_present == 0.0
diff --git a/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/tests/ca_fop_required_but_symbol_missing.sql b/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/tests/ca_fop_required_but_symbol_missing.sql
new file mode 100644
index 0000000000000000000000000000000000000000..54a383000949f62d7a8e51b9638bce352e78158b
--- /dev/null
+++ b/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/tests/ca_fop_required_but_symbol_missing.sql
@@ -0,0 +1,3 @@
+SELECT product_id
+FROM {{ source('off_source', 'nutrition_table') }}
+WHERE fop_threshold_exceeded > 0.0 AND fop_symbol_present == 0.0 AND fop_exempt_proxy == 0.0 AND product_is_prepackaged_proxy > 0.0
diff --git a/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/tests/ca_fop_symbol_present_but_not_required.sql b/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/tests/ca_fop_symbol_present_but_not_required.sql
new file mode 100644
index 0000000000000000000000000000000000000000..73875a8ab4bd3a5b60c4d8a6b21f77480e43c791
--- /dev/null
+++ b/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/tests/ca_fop_symbol_present_but_not_required.sql
@@ -0,0 +1,3 @@
+SELECT product_id
+FROM {{ source('off_source', 'nutrition_table') }}
+WHERE fop_symbol_present > 0.0 AND fop_threshold_exceeded == 0.0 AND fop_exempt_proxy == 0.0 AND product_is_prepackaged_proxy > 0.0
diff --git a/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/tests/ca_fop_symbol_present_on_exempt_product.sql b/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/tests/ca_fop_symbol_present_on_exempt_product.sql
new file mode 100644
index 0000000000000000000000000000000000000000..ede059e6c0d080f918d675f407995bbc6bf0da2b
--- /dev/null
+++ b/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/tests/ca_fop_symbol_present_on_exempt_product.sql
@@ -0,0 +1,3 @@
+SELECT product_id
+FROM {{ source('off_source', 'nutrition_table') }}
+WHERE fop_symbol_present > 0.0 AND fop_exempt_proxy > 0.0 AND product_is_prepackaged_proxy > 0.0
diff --git a/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/tests/carbohydrates_over_105g.sql b/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/tests/carbohydrates_over_105g.sql
new file mode 100644
index 0000000000000000000000000000000000000000..f674900f480f0b5bb5ac7282084555a66e3a420a
--- /dev/null
+++ b/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/tests/carbohydrates_over_105g.sql
@@ -0,0 +1,3 @@
+SELECT product_id
+FROM {{ source('off_source', 'nutrition_table') }}
+WHERE carbohydrates > 105
diff --git a/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/tests/energy_kcal_vs_kj.sql b/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/tests/energy_kcal_vs_kj.sql
new file mode 100644
index 0000000000000000000000000000000000000000..bb6de3c4fa58c30006d2d0fc04b3c4fad22601b8
--- /dev/null
+++ b/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/tests/energy_kcal_vs_kj.sql
@@ -0,0 +1,3 @@
+SELECT product_id
+FROM {{ source('off_source', 'nutrition_table') }}
+WHERE energy_kcal > energy_kj
diff --git a/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/tests/energy_kj_computed_mismatch_high.sql b/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/tests/energy_kj_computed_mismatch_high.sql
new file mode 100644
index 0000000000000000000000000000000000000000..f8441a685c40801367b2648c26c093481edd3b8d
--- /dev/null
+++ b/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/tests/energy_kj_computed_mismatch_high.sql
@@ -0,0 +1,3 @@
+SELECT product_id
+FROM {{ source('off_source', 'nutrition_table') }}
+WHERE energy_kj_computed > (1.3 * energy_kj + 5.0)
diff --git a/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/tests/energy_kj_computed_mismatch_low.sql b/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/tests/energy_kj_computed_mismatch_low.sql
new file mode 100644
index 0000000000000000000000000000000000000000..22467e455417d26dd6eac5f5b3a7861f5147a951
--- /dev/null
+++ b/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/tests/energy_kj_computed_mismatch_low.sql
@@ -0,0 +1,3 @@
+SELECT product_id
+FROM {{ source('off_source', 'nutrition_table') }}
+WHERE energy_kj_computed < (0.7 * energy_kj - 5.0)
diff --git a/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/tests/energy_kj_mismatch_high.sql b/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/tests/energy_kj_mismatch_high.sql
new file mode 100644
index 0000000000000000000000000000000000000000..040af1ce76762014a8178e74220750b594a5b82b
--- /dev/null
+++ b/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/tests/energy_kj_mismatch_high.sql
@@ -0,0 +1,3 @@
+SELECT product_id
+FROM {{ source('off_source', 'nutrition_table') }}
+WHERE energy_kj > (4.7 * energy_kcal + 2.0)
diff --git a/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/tests/energy_kj_mismatch_low.sql b/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/tests/energy_kj_mismatch_low.sql
new file mode 100644
index 0000000000000000000000000000000000000000..b5ffd498bfb159be98afb6dcc4a6afa0b4f0fb04
--- /dev/null
+++ b/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/tests/energy_kj_mismatch_low.sql
@@ -0,0 +1,3 @@
+SELECT product_id
+FROM {{ source('off_source', 'nutrition_table') }}
+WHERE energy_kj < (3.7 * energy_kcal - 2.0)
diff --git a/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/tests/energy_kj_over_3911.sql b/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/tests/energy_kj_over_3911.sql
new file mode 100644
index 0000000000000000000000000000000000000000..edb9969136f8213e57ca3e9a552285eec334a5b9
--- /dev/null
+++ b/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/tests/energy_kj_over_3911.sql
@@ -0,0 +1,3 @@
+SELECT product_id
+FROM {{ source('off_source', 'nutrition_table') }}
+WHERE energy_kj > 3911
diff --git a/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/tests/fat_over_105g.sql b/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/tests/fat_over_105g.sql
new file mode 100644
index 0000000000000000000000000000000000000000..df23a2b562b92785ae9280e8d2dafbf8efe97fb9
--- /dev/null
+++ b/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/tests/fat_over_105g.sql
@@ -0,0 +1,3 @@
+SELECT product_id
+FROM {{ source('off_source', 'nutrition_table') }}
+WHERE fat > 105
diff --git a/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/tests/main_language_code_missing.sql b/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/tests/main_language_code_missing.sql
new file mode 100644
index 0000000000000000000000000000000000000000..be4cd787a3b310e7cac47965864d59d957071050
--- /dev/null
+++ b/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/tests/main_language_code_missing.sql
@@ -0,0 +1,3 @@
+SELECT product_id
+FROM {{ source('off_source', 'nutrition_table') }}
+WHERE lc IS NULL OR TRIM(lc) = ''
diff --git a/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/tests/main_language_missing.sql b/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/tests/main_language_missing.sql
new file mode 100644
index 0000000000000000000000000000000000000000..b92c5c22b7a5f219f859d2c38548c1828b87ec2c
--- /dev/null
+++ b/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/tests/main_language_missing.sql
@@ -0,0 +1,3 @@
+SELECT product_id
+FROM {{ source('off_source', 'nutrition_table') }}
+WHERE lang IS NULL OR TRIM(lang) = ''
diff --git a/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/tests/saturated_fat_over_105g.sql b/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/tests/saturated_fat_over_105g.sql
new file mode 100644
index 0000000000000000000000000000000000000000..4c5bd8a6b1670fe861db743f4fbfbf11b73f7986
--- /dev/null
+++ b/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/tests/saturated_fat_over_105g.sql
@@ -0,0 +1,3 @@
+SELECT product_id
+FROM {{ source('off_source', 'nutrition_table') }}
+WHERE saturated_fat > 105
diff --git a/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/tests/saturated_fat_vs_fat.sql b/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/tests/saturated_fat_vs_fat.sql
new file mode 100644
index 0000000000000000000000000000000000000000..728306ddde0fbce6be6ad92a3d91012b946c4e80
--- /dev/null
+++ b/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/tests/saturated_fat_vs_fat.sql
@@ -0,0 +1,3 @@
+SELECT product_id
+FROM {{ source('off_source', 'nutrition_table') }}
+WHERE saturated_fat > (1.0 * fat + 0.001)
diff --git a/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/tests/sugars_over_105g.sql b/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/tests/sugars_over_105g.sql
new file mode 100644
index 0000000000000000000000000000000000000000..3c821e0c07aca8d835c051b2116e886d14f16a87
--- /dev/null
+++ b/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/tests/sugars_over_105g.sql
@@ -0,0 +1,3 @@
+SELECT product_id
+FROM {{ source('off_source', 'nutrition_table') }}
+WHERE sugars > 105
diff --git a/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/tests/sugars_plus_starch_vs_carbohydrates.sql b/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/tests/sugars_plus_starch_vs_carbohydrates.sql
new file mode 100644
index 0000000000000000000000000000000000000000..13936a538534e6b04ecb8cfb1480f7acc2ec8aca
--- /dev/null
+++ b/OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/tests/sugars_plus_starch_vs_carbohydrates.sql
@@ -0,0 +1,3 @@
+SELECT product_id
+FROM {{ source('off_source', 'nutrition_table') }}
+WHERE (sugars + starch) > (carbohydrates + 0.001)
diff --git a/OFF_DataQuality/results/declarative_runtime/soda/soda/contracts/ca_allergen_evidence_missing_ingredients_text.yml b/OFF_DataQuality/results/declarative_runtime/soda/soda/contracts/ca_allergen_evidence_missing_ingredients_text.yml
new file mode 100644
index 0000000000000000000000000000000000000000..8b2e70f35a0d83ec161c2cb0a4853ec9fdb647f0
--- /dev/null
+++ b/OFF_DataQuality/results/declarative_runtime/soda/soda/contracts/ca_allergen_evidence_missing_ingredients_text.yml
@@ -0,0 +1,27 @@
+dataset: off_quality/main/nutrition_table
+columns:
+ - name: product_id
+ - name: energy_kj
+ - name: energy_kj_computed
+ - name: energy_kcal
+ - name: fat
+ - name: saturated_fat
+ - name: carbohydrates
+ - name: sugars
+ - name: starch
+ - name: sodium
+ - name: ingredients_text
+ - name: ingredients_text_present
+ - name: contains_statement_present
+ - name: allergen_evidence_present
+ - name: fop_threshold_exceeded
+ - name: fop_symbol_present
+ - name: fop_exempt_proxy
+ - name: product_is_prepackaged_proxy
+ - name: lc
+ - name: lang
+ - name: language_code
+checks:
+ - failed_rows:
+ name: ca_allergen_evidence_missing_ingredients_text
+ expression: allergen_evidence_present > 0.0 AND ingredients_text_present == 0.0
diff --git a/OFF_DataQuality/results/declarative_runtime/soda/soda/contracts/ca_contains_statement_without_allergen_evidence.yml b/OFF_DataQuality/results/declarative_runtime/soda/soda/contracts/ca_contains_statement_without_allergen_evidence.yml
new file mode 100644
index 0000000000000000000000000000000000000000..40f3ee627c0d08c9591b3622492e01f8176f3251
--- /dev/null
+++ b/OFF_DataQuality/results/declarative_runtime/soda/soda/contracts/ca_contains_statement_without_allergen_evidence.yml
@@ -0,0 +1,27 @@
+dataset: off_quality/main/nutrition_table
+columns:
+ - name: product_id
+ - name: energy_kj
+ - name: energy_kj_computed
+ - name: energy_kcal
+ - name: fat
+ - name: saturated_fat
+ - name: carbohydrates
+ - name: sugars
+ - name: starch
+ - name: sodium
+ - name: ingredients_text
+ - name: ingredients_text_present
+ - name: contains_statement_present
+ - name: allergen_evidence_present
+ - name: fop_threshold_exceeded
+ - name: fop_symbol_present
+ - name: fop_exempt_proxy
+ - name: product_is_prepackaged_proxy
+ - name: lc
+ - name: lang
+ - name: language_code
+checks:
+ - failed_rows:
+ name: ca_contains_statement_without_allergen_evidence
+ expression: contains_statement_present > 0.0 AND allergen_evidence_present == 0.0
diff --git a/OFF_DataQuality/results/declarative_runtime/soda/soda/contracts/ca_fop_required_but_symbol_missing.yml b/OFF_DataQuality/results/declarative_runtime/soda/soda/contracts/ca_fop_required_but_symbol_missing.yml
new file mode 100644
index 0000000000000000000000000000000000000000..d49c55b6db065bb7827cf477ea562f62813c046a
--- /dev/null
+++ b/OFF_DataQuality/results/declarative_runtime/soda/soda/contracts/ca_fop_required_but_symbol_missing.yml
@@ -0,0 +1,27 @@
+dataset: off_quality/main/nutrition_table
+columns:
+ - name: product_id
+ - name: energy_kj
+ - name: energy_kj_computed
+ - name: energy_kcal
+ - name: fat
+ - name: saturated_fat
+ - name: carbohydrates
+ - name: sugars
+ - name: starch
+ - name: sodium
+ - name: ingredients_text
+ - name: ingredients_text_present
+ - name: contains_statement_present
+ - name: allergen_evidence_present
+ - name: fop_threshold_exceeded
+ - name: fop_symbol_present
+ - name: fop_exempt_proxy
+ - name: product_is_prepackaged_proxy
+ - name: lc
+ - name: lang
+ - name: language_code
+checks:
+ - failed_rows:
+ name: ca_fop_required_but_symbol_missing
+ expression: fop_threshold_exceeded > 0.0 AND fop_symbol_present == 0.0 AND fop_exempt_proxy == 0.0 AND product_is_prepackaged_proxy > 0.0
diff --git a/OFF_DataQuality/results/declarative_runtime/soda/soda/contracts/ca_fop_symbol_present_but_not_required.yml b/OFF_DataQuality/results/declarative_runtime/soda/soda/contracts/ca_fop_symbol_present_but_not_required.yml
new file mode 100644
index 0000000000000000000000000000000000000000..0085cd01e318557a23e4a04e8304c2fc00b66aeb
--- /dev/null
+++ b/OFF_DataQuality/results/declarative_runtime/soda/soda/contracts/ca_fop_symbol_present_but_not_required.yml
@@ -0,0 +1,27 @@
+dataset: off_quality/main/nutrition_table
+columns:
+ - name: product_id
+ - name: energy_kj
+ - name: energy_kj_computed
+ - name: energy_kcal
+ - name: fat
+ - name: saturated_fat
+ - name: carbohydrates
+ - name: sugars
+ - name: starch
+ - name: sodium
+ - name: ingredients_text
+ - name: ingredients_text_present
+ - name: contains_statement_present
+ - name: allergen_evidence_present
+ - name: fop_threshold_exceeded
+ - name: fop_symbol_present
+ - name: fop_exempt_proxy
+ - name: product_is_prepackaged_proxy
+ - name: lc
+ - name: lang
+ - name: language_code
+checks:
+ - failed_rows:
+ name: ca_fop_symbol_present_but_not_required
+ expression: fop_symbol_present > 0.0 AND fop_threshold_exceeded == 0.0 AND fop_exempt_proxy == 0.0 AND product_is_prepackaged_proxy > 0.0
diff --git a/OFF_DataQuality/results/declarative_runtime/soda/soda/contracts/ca_fop_symbol_present_on_exempt_product.yml b/OFF_DataQuality/results/declarative_runtime/soda/soda/contracts/ca_fop_symbol_present_on_exempt_product.yml
new file mode 100644
index 0000000000000000000000000000000000000000..491c8f7e26b4c8fe13f73bd3bd6abcc64ecc45f4
--- /dev/null
+++ b/OFF_DataQuality/results/declarative_runtime/soda/soda/contracts/ca_fop_symbol_present_on_exempt_product.yml
@@ -0,0 +1,27 @@
+dataset: off_quality/main/nutrition_table
+columns:
+ - name: product_id
+ - name: energy_kj
+ - name: energy_kj_computed
+ - name: energy_kcal
+ - name: fat
+ - name: saturated_fat
+ - name: carbohydrates
+ - name: sugars
+ - name: starch
+ - name: sodium
+ - name: ingredients_text
+ - name: ingredients_text_present
+ - name: contains_statement_present
+ - name: allergen_evidence_present
+ - name: fop_threshold_exceeded
+ - name: fop_symbol_present
+ - name: fop_exempt_proxy
+ - name: product_is_prepackaged_proxy
+ - name: lc
+ - name: lang
+ - name: language_code
+checks:
+ - failed_rows:
+ name: ca_fop_symbol_present_on_exempt_product
+ expression: fop_symbol_present > 0.0 AND fop_exempt_proxy > 0.0 AND product_is_prepackaged_proxy > 0.0
diff --git a/OFF_DataQuality/results/declarative_runtime/soda/soda/contracts/carbohydrates_over_105g.yml b/OFF_DataQuality/results/declarative_runtime/soda/soda/contracts/carbohydrates_over_105g.yml
new file mode 100644
index 0000000000000000000000000000000000000000..4245ad87e0773553d5ef335d737499e5e195994e
--- /dev/null
+++ b/OFF_DataQuality/results/declarative_runtime/soda/soda/contracts/carbohydrates_over_105g.yml
@@ -0,0 +1,27 @@
+dataset: off_quality/main/nutrition_table
+columns:
+ - name: product_id
+ - name: energy_kj
+ - name: energy_kj_computed
+ - name: energy_kcal
+ - name: fat
+ - name: saturated_fat
+ - name: carbohydrates
+ - name: sugars
+ - name: starch
+ - name: sodium
+ - name: ingredients_text
+ - name: ingredients_text_present
+ - name: contains_statement_present
+ - name: allergen_evidence_present
+ - name: fop_threshold_exceeded
+ - name: fop_symbol_present
+ - name: fop_exempt_proxy
+ - name: product_is_prepackaged_proxy
+ - name: lc
+ - name: lang
+ - name: language_code
+checks:
+ - failed_rows:
+ name: carbohydrates_over_105g
+ expression: carbohydrates > 105
diff --git a/OFF_DataQuality/results/declarative_runtime/soda/soda/contracts/energy_kcal_vs_kj.yml b/OFF_DataQuality/results/declarative_runtime/soda/soda/contracts/energy_kcal_vs_kj.yml
new file mode 100644
index 0000000000000000000000000000000000000000..884145f4cb5a38ebd44751151fc45af999ca5343
--- /dev/null
+++ b/OFF_DataQuality/results/declarative_runtime/soda/soda/contracts/energy_kcal_vs_kj.yml
@@ -0,0 +1,27 @@
+dataset: off_quality/main/nutrition_table
+columns:
+ - name: product_id
+ - name: energy_kj
+ - name: energy_kj_computed
+ - name: energy_kcal
+ - name: fat
+ - name: saturated_fat
+ - name: carbohydrates
+ - name: sugars
+ - name: starch
+ - name: sodium
+ - name: ingredients_text
+ - name: ingredients_text_present
+ - name: contains_statement_present
+ - name: allergen_evidence_present
+ - name: fop_threshold_exceeded
+ - name: fop_symbol_present
+ - name: fop_exempt_proxy
+ - name: product_is_prepackaged_proxy
+ - name: lc
+ - name: lang
+ - name: language_code
+checks:
+ - failed_rows:
+ name: energy_kcal_vs_kj
+ expression: energy_kcal > energy_kj
diff --git a/OFF_DataQuality/results/declarative_runtime/soda/soda/contracts/energy_kj_computed_mismatch_high.yml b/OFF_DataQuality/results/declarative_runtime/soda/soda/contracts/energy_kj_computed_mismatch_high.yml
new file mode 100644
index 0000000000000000000000000000000000000000..f4cc61285b3d879fe694a4e1b73a34624f47f857
--- /dev/null
+++ b/OFF_DataQuality/results/declarative_runtime/soda/soda/contracts/energy_kj_computed_mismatch_high.yml
@@ -0,0 +1,27 @@
+dataset: off_quality/main/nutrition_table
+columns:
+ - name: product_id
+ - name: energy_kj
+ - name: energy_kj_computed
+ - name: energy_kcal
+ - name: fat
+ - name: saturated_fat
+ - name: carbohydrates
+ - name: sugars
+ - name: starch
+ - name: sodium
+ - name: ingredients_text
+ - name: ingredients_text_present
+ - name: contains_statement_present
+ - name: allergen_evidence_present
+ - name: fop_threshold_exceeded
+ - name: fop_symbol_present
+ - name: fop_exempt_proxy
+ - name: product_is_prepackaged_proxy
+ - name: lc
+ - name: lang
+ - name: language_code
+checks:
+ - failed_rows:
+ name: energy_kj_computed_mismatch_high
+ expression: energy_kj_computed > (1.3 * energy_kj + 5.0)
diff --git a/OFF_DataQuality/results/declarative_runtime/soda/soda/contracts/energy_kj_computed_mismatch_low.yml b/OFF_DataQuality/results/declarative_runtime/soda/soda/contracts/energy_kj_computed_mismatch_low.yml
new file mode 100644
index 0000000000000000000000000000000000000000..eefe9fd1bdaec604d20b12bff9482fddb86de826
--- /dev/null
+++ b/OFF_DataQuality/results/declarative_runtime/soda/soda/contracts/energy_kj_computed_mismatch_low.yml
@@ -0,0 +1,27 @@
+dataset: off_quality/main/nutrition_table
+columns:
+ - name: product_id
+ - name: energy_kj
+ - name: energy_kj_computed
+ - name: energy_kcal
+ - name: fat
+ - name: saturated_fat
+ - name: carbohydrates
+ - name: sugars
+ - name: starch
+ - name: sodium
+ - name: ingredients_text
+ - name: ingredients_text_present
+ - name: contains_statement_present
+ - name: allergen_evidence_present
+ - name: fop_threshold_exceeded
+ - name: fop_symbol_present
+ - name: fop_exempt_proxy
+ - name: product_is_prepackaged_proxy
+ - name: lc
+ - name: lang
+ - name: language_code
+checks:
+ - failed_rows:
+ name: energy_kj_computed_mismatch_low
+ expression: energy_kj_computed < (0.7 * energy_kj - 5.0)
diff --git a/OFF_DataQuality/results/declarative_runtime/soda/soda/contracts/energy_kj_mismatch_high.yml b/OFF_DataQuality/results/declarative_runtime/soda/soda/contracts/energy_kj_mismatch_high.yml
new file mode 100644
index 0000000000000000000000000000000000000000..1093ce93be2e685910fe0a9b34cf0c1057e50310
--- /dev/null
+++ b/OFF_DataQuality/results/declarative_runtime/soda/soda/contracts/energy_kj_mismatch_high.yml
@@ -0,0 +1,27 @@
+dataset: off_quality/main/nutrition_table
+columns:
+ - name: product_id
+ - name: energy_kj
+ - name: energy_kj_computed
+ - name: energy_kcal
+ - name: fat
+ - name: saturated_fat
+ - name: carbohydrates
+ - name: sugars
+ - name: starch
+ - name: sodium
+ - name: ingredients_text
+ - name: ingredients_text_present
+ - name: contains_statement_present
+ - name: allergen_evidence_present
+ - name: fop_threshold_exceeded
+ - name: fop_symbol_present
+ - name: fop_exempt_proxy
+ - name: product_is_prepackaged_proxy
+ - name: lc
+ - name: lang
+ - name: language_code
+checks:
+ - failed_rows:
+ name: energy_kj_mismatch_high
+ expression: energy_kj > (4.7 * energy_kcal + 2.0)
diff --git a/OFF_DataQuality/results/declarative_runtime/soda/soda/contracts/energy_kj_mismatch_low.yml b/OFF_DataQuality/results/declarative_runtime/soda/soda/contracts/energy_kj_mismatch_low.yml
new file mode 100644
index 0000000000000000000000000000000000000000..bf94b05e21945b82e70f19a06d24419e5f7fabf4
--- /dev/null
+++ b/OFF_DataQuality/results/declarative_runtime/soda/soda/contracts/energy_kj_mismatch_low.yml
@@ -0,0 +1,27 @@
+dataset: off_quality/main/nutrition_table
+columns:
+ - name: product_id
+ - name: energy_kj
+ - name: energy_kj_computed
+ - name: energy_kcal
+ - name: fat
+ - name: saturated_fat
+ - name: carbohydrates
+ - name: sugars
+ - name: starch
+ - name: sodium
+ - name: ingredients_text
+ - name: ingredients_text_present
+ - name: contains_statement_present
+ - name: allergen_evidence_present
+ - name: fop_threshold_exceeded
+ - name: fop_symbol_present
+ - name: fop_exempt_proxy
+ - name: product_is_prepackaged_proxy
+ - name: lc
+ - name: lang
+ - name: language_code
+checks:
+ - failed_rows:
+ name: energy_kj_mismatch_low
+ expression: energy_kj < (3.7 * energy_kcal - 2.0)
diff --git a/OFF_DataQuality/results/declarative_runtime/soda/soda/contracts/energy_kj_over_3911.yml b/OFF_DataQuality/results/declarative_runtime/soda/soda/contracts/energy_kj_over_3911.yml
new file mode 100644
index 0000000000000000000000000000000000000000..04f6dd1e9535b56d1510f2fd40cc9855a64cf1ca
--- /dev/null
+++ b/OFF_DataQuality/results/declarative_runtime/soda/soda/contracts/energy_kj_over_3911.yml
@@ -0,0 +1,27 @@
+dataset: off_quality/main/nutrition_table
+columns:
+ - name: product_id
+ - name: energy_kj
+ - name: energy_kj_computed
+ - name: energy_kcal
+ - name: fat
+ - name: saturated_fat
+ - name: carbohydrates
+ - name: sugars
+ - name: starch
+ - name: sodium
+ - name: ingredients_text
+ - name: ingredients_text_present
+ - name: contains_statement_present
+ - name: allergen_evidence_present
+ - name: fop_threshold_exceeded
+ - name: fop_symbol_present
+ - name: fop_exempt_proxy
+ - name: product_is_prepackaged_proxy
+ - name: lc
+ - name: lang
+ - name: language_code
+checks:
+ - failed_rows:
+ name: energy_kj_over_3911
+ expression: energy_kj > 3911
diff --git a/OFF_DataQuality/results/declarative_runtime/soda/soda/contracts/fat_over_105g.yml b/OFF_DataQuality/results/declarative_runtime/soda/soda/contracts/fat_over_105g.yml
new file mode 100644
index 0000000000000000000000000000000000000000..e39e19ea374830ca8a5c997bc05e273f3683cf02
--- /dev/null
+++ b/OFF_DataQuality/results/declarative_runtime/soda/soda/contracts/fat_over_105g.yml
@@ -0,0 +1,27 @@
+dataset: off_quality/main/nutrition_table
+columns:
+ - name: product_id
+ - name: energy_kj
+ - name: energy_kj_computed
+ - name: energy_kcal
+ - name: fat
+ - name: saturated_fat
+ - name: carbohydrates
+ - name: sugars
+ - name: starch
+ - name: sodium
+ - name: ingredients_text
+ - name: ingredients_text_present
+ - name: contains_statement_present
+ - name: allergen_evidence_present
+ - name: fop_threshold_exceeded
+ - name: fop_symbol_present
+ - name: fop_exempt_proxy
+ - name: product_is_prepackaged_proxy
+ - name: lc
+ - name: lang
+ - name: language_code
+checks:
+ - failed_rows:
+ name: fat_over_105g
+ expression: fat > 105
diff --git a/OFF_DataQuality/results/declarative_runtime/soda/soda/contracts/main_language_code_missing.yml b/OFF_DataQuality/results/declarative_runtime/soda/soda/contracts/main_language_code_missing.yml
new file mode 100644
index 0000000000000000000000000000000000000000..a5fbd9d53adccfb8551875efa0d139326a2aa9ae
--- /dev/null
+++ b/OFF_DataQuality/results/declarative_runtime/soda/soda/contracts/main_language_code_missing.yml
@@ -0,0 +1,27 @@
+dataset: off_quality/main/nutrition_table
+columns:
+ - name: product_id
+ - name: energy_kj
+ - name: energy_kj_computed
+ - name: energy_kcal
+ - name: fat
+ - name: saturated_fat
+ - name: carbohydrates
+ - name: sugars
+ - name: starch
+ - name: sodium
+ - name: ingredients_text
+ - name: ingredients_text_present
+ - name: contains_statement_present
+ - name: allergen_evidence_present
+ - name: fop_threshold_exceeded
+ - name: fop_symbol_present
+ - name: fop_exempt_proxy
+ - name: product_is_prepackaged_proxy
+ - name: lc
+ - name: lang
+ - name: language_code
+checks:
+ - failed_rows:
+ name: main_language_code_missing
+ expression: lc IS NULL OR TRIM(lc) = ''
diff --git a/OFF_DataQuality/results/declarative_runtime/soda/soda/contracts/main_language_missing.yml b/OFF_DataQuality/results/declarative_runtime/soda/soda/contracts/main_language_missing.yml
new file mode 100644
index 0000000000000000000000000000000000000000..6b74857b8e43cffd35e1a3c1077853d0db0cd746
--- /dev/null
+++ b/OFF_DataQuality/results/declarative_runtime/soda/soda/contracts/main_language_missing.yml
@@ -0,0 +1,27 @@
+dataset: off_quality/main/nutrition_table
+columns:
+ - name: product_id
+ - name: energy_kj
+ - name: energy_kj_computed
+ - name: energy_kcal
+ - name: fat
+ - name: saturated_fat
+ - name: carbohydrates
+ - name: sugars
+ - name: starch
+ - name: sodium
+ - name: ingredients_text
+ - name: ingredients_text_present
+ - name: contains_statement_present
+ - name: allergen_evidence_present
+ - name: fop_threshold_exceeded
+ - name: fop_symbol_present
+ - name: fop_exempt_proxy
+ - name: product_is_prepackaged_proxy
+ - name: lc
+ - name: lang
+ - name: language_code
+checks:
+ - failed_rows:
+ name: main_language_missing
+ expression: lang IS NULL OR TRIM(lang) = ''
diff --git a/OFF_DataQuality/results/declarative_runtime/soda/soda/contracts/saturated_fat_over_105g.yml b/OFF_DataQuality/results/declarative_runtime/soda/soda/contracts/saturated_fat_over_105g.yml
new file mode 100644
index 0000000000000000000000000000000000000000..5231c27a2b77079c42cf399f43abeb98fadddff7
--- /dev/null
+++ b/OFF_DataQuality/results/declarative_runtime/soda/soda/contracts/saturated_fat_over_105g.yml
@@ -0,0 +1,27 @@
+dataset: off_quality/main/nutrition_table
+columns:
+ - name: product_id
+ - name: energy_kj
+ - name: energy_kj_computed
+ - name: energy_kcal
+ - name: fat
+ - name: saturated_fat
+ - name: carbohydrates
+ - name: sugars
+ - name: starch
+ - name: sodium
+ - name: ingredients_text
+ - name: ingredients_text_present
+ - name: contains_statement_present
+ - name: allergen_evidence_present
+ - name: fop_threshold_exceeded
+ - name: fop_symbol_present
+ - name: fop_exempt_proxy
+ - name: product_is_prepackaged_proxy
+ - name: lc
+ - name: lang
+ - name: language_code
+checks:
+ - failed_rows:
+ name: saturated_fat_over_105g
+ expression: saturated_fat > 105
diff --git a/OFF_DataQuality/results/declarative_runtime/soda/soda/contracts/saturated_fat_vs_fat.yml b/OFF_DataQuality/results/declarative_runtime/soda/soda/contracts/saturated_fat_vs_fat.yml
new file mode 100644
index 0000000000000000000000000000000000000000..006010b2631a40cacf4213fcb654e928d3f885ca
--- /dev/null
+++ b/OFF_DataQuality/results/declarative_runtime/soda/soda/contracts/saturated_fat_vs_fat.yml
@@ -0,0 +1,27 @@
+dataset: off_quality/main/nutrition_table
+columns:
+ - name: product_id
+ - name: energy_kj
+ - name: energy_kj_computed
+ - name: energy_kcal
+ - name: fat
+ - name: saturated_fat
+ - name: carbohydrates
+ - name: sugars
+ - name: starch
+ - name: sodium
+ - name: ingredients_text
+ - name: ingredients_text_present
+ - name: contains_statement_present
+ - name: allergen_evidence_present
+ - name: fop_threshold_exceeded
+ - name: fop_symbol_present
+ - name: fop_exempt_proxy
+ - name: product_is_prepackaged_proxy
+ - name: lc
+ - name: lang
+ - name: language_code
+checks:
+ - failed_rows:
+ name: saturated_fat_vs_fat
+ expression: saturated_fat > (1.0 * fat + 0.001)
diff --git a/OFF_DataQuality/results/declarative_runtime/soda/soda/contracts/sugars_over_105g.yml b/OFF_DataQuality/results/declarative_runtime/soda/soda/contracts/sugars_over_105g.yml
new file mode 100644
index 0000000000000000000000000000000000000000..0c4f23f7f5702d18dd502ae0afe5fcc0de0b6983
--- /dev/null
+++ b/OFF_DataQuality/results/declarative_runtime/soda/soda/contracts/sugars_over_105g.yml
@@ -0,0 +1,27 @@
+dataset: off_quality/main/nutrition_table
+columns:
+ - name: product_id
+ - name: energy_kj
+ - name: energy_kj_computed
+ - name: energy_kcal
+ - name: fat
+ - name: saturated_fat
+ - name: carbohydrates
+ - name: sugars
+ - name: starch
+ - name: sodium
+ - name: ingredients_text
+ - name: ingredients_text_present
+ - name: contains_statement_present
+ - name: allergen_evidence_present
+ - name: fop_threshold_exceeded
+ - name: fop_symbol_present
+ - name: fop_exempt_proxy
+ - name: product_is_prepackaged_proxy
+ - name: lc
+ - name: lang
+ - name: language_code
+checks:
+ - failed_rows:
+ name: sugars_over_105g
+ expression: sugars > 105
diff --git a/OFF_DataQuality/results/declarative_runtime/soda/soda/contracts/sugars_plus_starch_vs_carbohydrates.yml b/OFF_DataQuality/results/declarative_runtime/soda/soda/contracts/sugars_plus_starch_vs_carbohydrates.yml
new file mode 100644
index 0000000000000000000000000000000000000000..122bedd8ec354f14556d80690dcb68a137ef6826
--- /dev/null
+++ b/OFF_DataQuality/results/declarative_runtime/soda/soda/contracts/sugars_plus_starch_vs_carbohydrates.yml
@@ -0,0 +1,27 @@
+dataset: off_quality/main/nutrition_table
+columns:
+ - name: product_id
+ - name: energy_kj
+ - name: energy_kj_computed
+ - name: energy_kcal
+ - name: fat
+ - name: saturated_fat
+ - name: carbohydrates
+ - name: sugars
+ - name: starch
+ - name: sodium
+ - name: ingredients_text
+ - name: ingredients_text_present
+ - name: contains_statement_present
+ - name: allergen_evidence_present
+ - name: fop_threshold_exceeded
+ - name: fop_symbol_present
+ - name: fop_exempt_proxy
+ - name: product_is_prepackaged_proxy
+ - name: lc
+ - name: lang
+ - name: language_code
+checks:
+ - failed_rows:
+ name: sugars_plus_starch_vs_carbohydrates
+ expression: (sugars + starch) > (carbohydrates + 0.001)
diff --git a/OFF_DataQuality/results/declarative_runtime/soda/soda/data_source.yml b/OFF_DataQuality/results/declarative_runtime/soda/soda/data_source.yml
new file mode 100644
index 0000000000000000000000000000000000000000..cfb1fa860bd4343d474fde86c9c8fdd38f04461f
--- /dev/null
+++ b/OFF_DataQuality/results/declarative_runtime/soda/soda/data_source.yml
@@ -0,0 +1,5 @@
+type: duckdb
+name: off_quality
+connection:
+ database: C:/dev/OFF_DataQuality_Prototype/results/declarative_runtime/soda/soda_runtime.db
+ schema: main
diff --git a/OFF_DataQuality/results/declarative_runtime/soda/soda_cloud/contracts/ca_allergen_evidence_missing_ingredients_text.yml b/OFF_DataQuality/results/declarative_runtime/soda/soda_cloud/contracts/ca_allergen_evidence_missing_ingredients_text.yml
new file mode 100644
index 0000000000000000000000000000000000000000..8b2e70f35a0d83ec161c2cb0a4853ec9fdb647f0
--- /dev/null
+++ b/OFF_DataQuality/results/declarative_runtime/soda/soda_cloud/contracts/ca_allergen_evidence_missing_ingredients_text.yml
@@ -0,0 +1,27 @@
+dataset: off_quality/main/nutrition_table
+columns:
+ - name: product_id
+ - name: energy_kj
+ - name: energy_kj_computed
+ - name: energy_kcal
+ - name: fat
+ - name: saturated_fat
+ - name: carbohydrates
+ - name: sugars
+ - name: starch
+ - name: sodium
+ - name: ingredients_text
+ - name: ingredients_text_present
+ - name: contains_statement_present
+ - name: allergen_evidence_present
+ - name: fop_threshold_exceeded
+ - name: fop_symbol_present
+ - name: fop_exempt_proxy
+ - name: product_is_prepackaged_proxy
+ - name: lc
+ - name: lang
+ - name: language_code
+checks:
+ - failed_rows:
+ name: ca_allergen_evidence_missing_ingredients_text
+ expression: allergen_evidence_present > 0.0 AND ingredients_text_present == 0.0
diff --git a/OFF_DataQuality/results/declarative_runtime/soda/soda_cloud/contracts/ca_contains_statement_without_allergen_evidence.yml b/OFF_DataQuality/results/declarative_runtime/soda/soda_cloud/contracts/ca_contains_statement_without_allergen_evidence.yml
new file mode 100644
index 0000000000000000000000000000000000000000..40f3ee627c0d08c9591b3622492e01f8176f3251
--- /dev/null
+++ b/OFF_DataQuality/results/declarative_runtime/soda/soda_cloud/contracts/ca_contains_statement_without_allergen_evidence.yml
@@ -0,0 +1,27 @@
+dataset: off_quality/main/nutrition_table
+columns:
+ - name: product_id
+ - name: energy_kj
+ - name: energy_kj_computed
+ - name: energy_kcal
+ - name: fat
+ - name: saturated_fat
+ - name: carbohydrates
+ - name: sugars
+ - name: starch
+ - name: sodium
+ - name: ingredients_text
+ - name: ingredients_text_present
+ - name: contains_statement_present
+ - name: allergen_evidence_present
+ - name: fop_threshold_exceeded
+ - name: fop_symbol_present
+ - name: fop_exempt_proxy
+ - name: product_is_prepackaged_proxy
+ - name: lc
+ - name: lang
+ - name: language_code
+checks:
+ - failed_rows:
+ name: ca_contains_statement_without_allergen_evidence
+ expression: contains_statement_present > 0.0 AND allergen_evidence_present == 0.0
diff --git a/OFF_DataQuality/results/declarative_runtime/soda/soda_cloud/contracts/ca_fop_required_but_symbol_missing.yml b/OFF_DataQuality/results/declarative_runtime/soda/soda_cloud/contracts/ca_fop_required_but_symbol_missing.yml
new file mode 100644
index 0000000000000000000000000000000000000000..d49c55b6db065bb7827cf477ea562f62813c046a
--- /dev/null
+++ b/OFF_DataQuality/results/declarative_runtime/soda/soda_cloud/contracts/ca_fop_required_but_symbol_missing.yml
@@ -0,0 +1,27 @@
+dataset: off_quality/main/nutrition_table
+columns:
+ - name: product_id
+ - name: energy_kj
+ - name: energy_kj_computed
+ - name: energy_kcal
+ - name: fat
+ - name: saturated_fat
+ - name: carbohydrates
+ - name: sugars
+ - name: starch
+ - name: sodium
+ - name: ingredients_text
+ - name: ingredients_text_present
+ - name: contains_statement_present
+ - name: allergen_evidence_present
+ - name: fop_threshold_exceeded
+ - name: fop_symbol_present
+ - name: fop_exempt_proxy
+ - name: product_is_prepackaged_proxy
+ - name: lc
+ - name: lang
+ - name: language_code
+checks:
+ - failed_rows:
+ name: ca_fop_required_but_symbol_missing
+ expression: fop_threshold_exceeded > 0.0 AND fop_symbol_present == 0.0 AND fop_exempt_proxy == 0.0 AND product_is_prepackaged_proxy > 0.0
diff --git a/OFF_DataQuality/results/declarative_runtime/soda/soda_cloud/contracts/ca_fop_symbol_present_but_not_required.yml b/OFF_DataQuality/results/declarative_runtime/soda/soda_cloud/contracts/ca_fop_symbol_present_but_not_required.yml
new file mode 100644
index 0000000000000000000000000000000000000000..0085cd01e318557a23e4a04e8304c2fc00b66aeb
--- /dev/null
+++ b/OFF_DataQuality/results/declarative_runtime/soda/soda_cloud/contracts/ca_fop_symbol_present_but_not_required.yml
@@ -0,0 +1,27 @@
+dataset: off_quality/main/nutrition_table
+columns:
+ - name: product_id
+ - name: energy_kj
+ - name: energy_kj_computed
+ - name: energy_kcal
+ - name: fat
+ - name: saturated_fat
+ - name: carbohydrates
+ - name: sugars
+ - name: starch
+ - name: sodium
+ - name: ingredients_text
+ - name: ingredients_text_present
+ - name: contains_statement_present
+ - name: allergen_evidence_present
+ - name: fop_threshold_exceeded
+ - name: fop_symbol_present
+ - name: fop_exempt_proxy
+ - name: product_is_prepackaged_proxy
+ - name: lc
+ - name: lang
+ - name: language_code
+checks:
+ - failed_rows:
+ name: ca_fop_symbol_present_but_not_required
+ expression: fop_symbol_present > 0.0 AND fop_threshold_exceeded == 0.0 AND fop_exempt_proxy == 0.0 AND product_is_prepackaged_proxy > 0.0
diff --git a/OFF_DataQuality/results/declarative_runtime/soda/soda_cloud/contracts/ca_fop_symbol_present_on_exempt_product.yml b/OFF_DataQuality/results/declarative_runtime/soda/soda_cloud/contracts/ca_fop_symbol_present_on_exempt_product.yml
new file mode 100644
index 0000000000000000000000000000000000000000..491c8f7e26b4c8fe13f73bd3bd6abcc64ecc45f4
--- /dev/null
+++ b/OFF_DataQuality/results/declarative_runtime/soda/soda_cloud/contracts/ca_fop_symbol_present_on_exempt_product.yml
@@ -0,0 +1,27 @@
+dataset: off_quality/main/nutrition_table
+columns:
+ - name: product_id
+ - name: energy_kj
+ - name: energy_kj_computed
+ - name: energy_kcal
+ - name: fat
+ - name: saturated_fat
+ - name: carbohydrates
+ - name: sugars
+ - name: starch
+ - name: sodium
+ - name: ingredients_text
+ - name: ingredients_text_present
+ - name: contains_statement_present
+ - name: allergen_evidence_present
+ - name: fop_threshold_exceeded
+ - name: fop_symbol_present
+ - name: fop_exempt_proxy
+ - name: product_is_prepackaged_proxy
+ - name: lc
+ - name: lang
+ - name: language_code
+checks:
+ - failed_rows:
+ name: ca_fop_symbol_present_on_exempt_product
+ expression: fop_symbol_present > 0.0 AND fop_exempt_proxy > 0.0 AND product_is_prepackaged_proxy > 0.0
diff --git a/OFF_DataQuality/results/declarative_runtime/soda/soda_cloud/contracts/carbohydrates_over_105g.yml b/OFF_DataQuality/results/declarative_runtime/soda/soda_cloud/contracts/carbohydrates_over_105g.yml
new file mode 100644
index 0000000000000000000000000000000000000000..4245ad87e0773553d5ef335d737499e5e195994e
--- /dev/null
+++ b/OFF_DataQuality/results/declarative_runtime/soda/soda_cloud/contracts/carbohydrates_over_105g.yml
@@ -0,0 +1,27 @@
+dataset: off_quality/main/nutrition_table
+columns:
+ - name: product_id
+ - name: energy_kj
+ - name: energy_kj_computed
+ - name: energy_kcal
+ - name: fat
+ - name: saturated_fat
+ - name: carbohydrates
+ - name: sugars
+ - name: starch
+ - name: sodium
+ - name: ingredients_text
+ - name: ingredients_text_present
+ - name: contains_statement_present
+ - name: allergen_evidence_present
+ - name: fop_threshold_exceeded
+ - name: fop_symbol_present
+ - name: fop_exempt_proxy
+ - name: product_is_prepackaged_proxy
+ - name: lc
+ - name: lang
+ - name: language_code
+checks:
+ - failed_rows:
+ name: carbohydrates_over_105g
+ expression: carbohydrates > 105
diff --git a/OFF_DataQuality/results/declarative_runtime/soda/soda_cloud/contracts/energy_kcal_vs_kj.yml b/OFF_DataQuality/results/declarative_runtime/soda/soda_cloud/contracts/energy_kcal_vs_kj.yml
new file mode 100644
index 0000000000000000000000000000000000000000..884145f4cb5a38ebd44751151fc45af999ca5343
--- /dev/null
+++ b/OFF_DataQuality/results/declarative_runtime/soda/soda_cloud/contracts/energy_kcal_vs_kj.yml
@@ -0,0 +1,27 @@
+dataset: off_quality/main/nutrition_table
+columns:
+ - name: product_id
+ - name: energy_kj
+ - name: energy_kj_computed
+ - name: energy_kcal
+ - name: fat
+ - name: saturated_fat
+ - name: carbohydrates
+ - name: sugars
+ - name: starch
+ - name: sodium
+ - name: ingredients_text
+ - name: ingredients_text_present
+ - name: contains_statement_present
+ - name: allergen_evidence_present
+ - name: fop_threshold_exceeded
+ - name: fop_symbol_present
+ - name: fop_exempt_proxy
+ - name: product_is_prepackaged_proxy
+ - name: lc
+ - name: lang
+ - name: language_code
+checks:
+ - failed_rows:
+ name: energy_kcal_vs_kj
+ expression: energy_kcal > energy_kj
diff --git a/OFF_DataQuality/results/declarative_runtime/soda/soda_cloud/contracts/energy_kj_computed_mismatch_high.yml b/OFF_DataQuality/results/declarative_runtime/soda/soda_cloud/contracts/energy_kj_computed_mismatch_high.yml
new file mode 100644
index 0000000000000000000000000000000000000000..f4cc61285b3d879fe694a4e1b73a34624f47f857
--- /dev/null
+++ b/OFF_DataQuality/results/declarative_runtime/soda/soda_cloud/contracts/energy_kj_computed_mismatch_high.yml
@@ -0,0 +1,27 @@
+dataset: off_quality/main/nutrition_table
+columns:
+ - name: product_id
+ - name: energy_kj
+ - name: energy_kj_computed
+ - name: energy_kcal
+ - name: fat
+ - name: saturated_fat
+ - name: carbohydrates
+ - name: sugars
+ - name: starch
+ - name: sodium
+ - name: ingredients_text
+ - name: ingredients_text_present
+ - name: contains_statement_present
+ - name: allergen_evidence_present
+ - name: fop_threshold_exceeded
+ - name: fop_symbol_present
+ - name: fop_exempt_proxy
+ - name: product_is_prepackaged_proxy
+ - name: lc
+ - name: lang
+ - name: language_code
+checks:
+ - failed_rows:
+ name: energy_kj_computed_mismatch_high
+ expression: energy_kj_computed > (1.3 * energy_kj + 5.0)
diff --git a/OFF_DataQuality/results/declarative_runtime/soda/soda_cloud/contracts/energy_kj_computed_mismatch_low.yml b/OFF_DataQuality/results/declarative_runtime/soda/soda_cloud/contracts/energy_kj_computed_mismatch_low.yml
new file mode 100644
index 0000000000000000000000000000000000000000..eefe9fd1bdaec604d20b12bff9482fddb86de826
--- /dev/null
+++ b/OFF_DataQuality/results/declarative_runtime/soda/soda_cloud/contracts/energy_kj_computed_mismatch_low.yml
@@ -0,0 +1,27 @@
+dataset: off_quality/main/nutrition_table
+columns:
+ - name: product_id
+ - name: energy_kj
+ - name: energy_kj_computed
+ - name: energy_kcal
+ - name: fat
+ - name: saturated_fat
+ - name: carbohydrates
+ - name: sugars
+ - name: starch
+ - name: sodium
+ - name: ingredients_text
+ - name: ingredients_text_present
+ - name: contains_statement_present
+ - name: allergen_evidence_present
+ - name: fop_threshold_exceeded
+ - name: fop_symbol_present
+ - name: fop_exempt_proxy
+ - name: product_is_prepackaged_proxy
+ - name: lc
+ - name: lang
+ - name: language_code
+checks:
+ - failed_rows:
+ name: energy_kj_computed_mismatch_low
+ expression: energy_kj_computed < (0.7 * energy_kj - 5.0)
diff --git a/OFF_DataQuality/results/declarative_runtime/soda/soda_cloud/contracts/energy_kj_mismatch_high.yml b/OFF_DataQuality/results/declarative_runtime/soda/soda_cloud/contracts/energy_kj_mismatch_high.yml
new file mode 100644
index 0000000000000000000000000000000000000000..1093ce93be2e685910fe0a9b34cf0c1057e50310
--- /dev/null
+++ b/OFF_DataQuality/results/declarative_runtime/soda/soda_cloud/contracts/energy_kj_mismatch_high.yml
@@ -0,0 +1,27 @@
+dataset: off_quality/main/nutrition_table
+columns:
+ - name: product_id
+ - name: energy_kj
+ - name: energy_kj_computed
+ - name: energy_kcal
+ - name: fat
+ - name: saturated_fat
+ - name: carbohydrates
+ - name: sugars
+ - name: starch
+ - name: sodium
+ - name: ingredients_text
+ - name: ingredients_text_present
+ - name: contains_statement_present
+ - name: allergen_evidence_present
+ - name: fop_threshold_exceeded
+ - name: fop_symbol_present
+ - name: fop_exempt_proxy
+ - name: product_is_prepackaged_proxy
+ - name: lc
+ - name: lang
+ - name: language_code
+checks:
+ - failed_rows:
+ name: energy_kj_mismatch_high
+ expression: energy_kj > (4.7 * energy_kcal + 2.0)
diff --git a/OFF_DataQuality/results/declarative_runtime/soda/soda_cloud/contracts/energy_kj_mismatch_low.yml b/OFF_DataQuality/results/declarative_runtime/soda/soda_cloud/contracts/energy_kj_mismatch_low.yml
new file mode 100644
index 0000000000000000000000000000000000000000..bf94b05e21945b82e70f19a06d24419e5f7fabf4
--- /dev/null
+++ b/OFF_DataQuality/results/declarative_runtime/soda/soda_cloud/contracts/energy_kj_mismatch_low.yml
@@ -0,0 +1,27 @@
+dataset: off_quality/main/nutrition_table
+columns:
+ - name: product_id
+ - name: energy_kj
+ - name: energy_kj_computed
+ - name: energy_kcal
+ - name: fat
+ - name: saturated_fat
+ - name: carbohydrates
+ - name: sugars
+ - name: starch
+ - name: sodium
+ - name: ingredients_text
+ - name: ingredients_text_present
+ - name: contains_statement_present
+ - name: allergen_evidence_present
+ - name: fop_threshold_exceeded
+ - name: fop_symbol_present
+ - name: fop_exempt_proxy
+ - name: product_is_prepackaged_proxy
+ - name: lc
+ - name: lang
+ - name: language_code
+checks:
+ - failed_rows:
+ name: energy_kj_mismatch_low
+ expression: energy_kj < (3.7 * energy_kcal - 2.0)
diff --git a/OFF_DataQuality/results/declarative_runtime/soda/soda_cloud/contracts/energy_kj_over_3911.yml b/OFF_DataQuality/results/declarative_runtime/soda/soda_cloud/contracts/energy_kj_over_3911.yml
new file mode 100644
index 0000000000000000000000000000000000000000..04f6dd1e9535b56d1510f2fd40cc9855a64cf1ca
--- /dev/null
+++ b/OFF_DataQuality/results/declarative_runtime/soda/soda_cloud/contracts/energy_kj_over_3911.yml
@@ -0,0 +1,27 @@
+dataset: off_quality/main/nutrition_table
+columns:
+ - name: product_id
+ - name: energy_kj
+ - name: energy_kj_computed
+ - name: energy_kcal
+ - name: fat
+ - name: saturated_fat
+ - name: carbohydrates
+ - name: sugars
+ - name: starch
+ - name: sodium
+ - name: ingredients_text
+ - name: ingredients_text_present
+ - name: contains_statement_present
+ - name: allergen_evidence_present
+ - name: fop_threshold_exceeded
+ - name: fop_symbol_present
+ - name: fop_exempt_proxy
+ - name: product_is_prepackaged_proxy
+ - name: lc
+ - name: lang
+ - name: language_code
+checks:
+ - failed_rows:
+ name: energy_kj_over_3911
+ expression: energy_kj > 3911
diff --git a/OFF_DataQuality/results/declarative_runtime/soda/soda_cloud/contracts/fat_over_105g.yml b/OFF_DataQuality/results/declarative_runtime/soda/soda_cloud/contracts/fat_over_105g.yml
new file mode 100644
index 0000000000000000000000000000000000000000..e39e19ea374830ca8a5c997bc05e273f3683cf02
--- /dev/null
+++ b/OFF_DataQuality/results/declarative_runtime/soda/soda_cloud/contracts/fat_over_105g.yml
@@ -0,0 +1,27 @@
+dataset: off_quality/main/nutrition_table
+columns:
+ - name: product_id
+ - name: energy_kj
+ - name: energy_kj_computed
+ - name: energy_kcal
+ - name: fat
+ - name: saturated_fat
+ - name: carbohydrates
+ - name: sugars
+ - name: starch
+ - name: sodium
+ - name: ingredients_text
+ - name: ingredients_text_present
+ - name: contains_statement_present
+ - name: allergen_evidence_present
+ - name: fop_threshold_exceeded
+ - name: fop_symbol_present
+ - name: fop_exempt_proxy
+ - name: product_is_prepackaged_proxy
+ - name: lc
+ - name: lang
+ - name: language_code
+checks:
+ - failed_rows:
+ name: fat_over_105g
+ expression: fat > 105
diff --git a/OFF_DataQuality/results/declarative_runtime/soda/soda_cloud/contracts/main_language_code_missing.yml b/OFF_DataQuality/results/declarative_runtime/soda/soda_cloud/contracts/main_language_code_missing.yml
new file mode 100644
index 0000000000000000000000000000000000000000..a5fbd9d53adccfb8551875efa0d139326a2aa9ae
--- /dev/null
+++ b/OFF_DataQuality/results/declarative_runtime/soda/soda_cloud/contracts/main_language_code_missing.yml
@@ -0,0 +1,27 @@
+dataset: off_quality/main/nutrition_table
+columns:
+ - name: product_id
+ - name: energy_kj
+ - name: energy_kj_computed
+ - name: energy_kcal
+ - name: fat
+ - name: saturated_fat
+ - name: carbohydrates
+ - name: sugars
+ - name: starch
+ - name: sodium
+ - name: ingredients_text
+ - name: ingredients_text_present
+ - name: contains_statement_present
+ - name: allergen_evidence_present
+ - name: fop_threshold_exceeded
+ - name: fop_symbol_present
+ - name: fop_exempt_proxy
+ - name: product_is_prepackaged_proxy
+ - name: lc
+ - name: lang
+ - name: language_code
+checks:
+ - failed_rows:
+ name: main_language_code_missing
+ expression: lc IS NULL OR TRIM(lc) = ''
diff --git a/OFF_DataQuality/results/declarative_runtime/soda/soda_cloud/contracts/main_language_missing.yml b/OFF_DataQuality/results/declarative_runtime/soda/soda_cloud/contracts/main_language_missing.yml
new file mode 100644
index 0000000000000000000000000000000000000000..6b74857b8e43cffd35e1a3c1077853d0db0cd746
--- /dev/null
+++ b/OFF_DataQuality/results/declarative_runtime/soda/soda_cloud/contracts/main_language_missing.yml
@@ -0,0 +1,27 @@
+dataset: off_quality/main/nutrition_table
+columns:
+ - name: product_id
+ - name: energy_kj
+ - name: energy_kj_computed
+ - name: energy_kcal
+ - name: fat
+ - name: saturated_fat
+ - name: carbohydrates
+ - name: sugars
+ - name: starch
+ - name: sodium
+ - name: ingredients_text
+ - name: ingredients_text_present
+ - name: contains_statement_present
+ - name: allergen_evidence_present
+ - name: fop_threshold_exceeded
+ - name: fop_symbol_present
+ - name: fop_exempt_proxy
+ - name: product_is_prepackaged_proxy
+ - name: lc
+ - name: lang
+ - name: language_code
+checks:
+ - failed_rows:
+ name: main_language_missing
+ expression: lang IS NULL OR TRIM(lang) = ''
diff --git a/OFF_DataQuality/results/declarative_runtime/soda/soda_cloud/contracts/saturated_fat_over_105g.yml b/OFF_DataQuality/results/declarative_runtime/soda/soda_cloud/contracts/saturated_fat_over_105g.yml
new file mode 100644
index 0000000000000000000000000000000000000000..5231c27a2b77079c42cf399f43abeb98fadddff7
--- /dev/null
+++ b/OFF_DataQuality/results/declarative_runtime/soda/soda_cloud/contracts/saturated_fat_over_105g.yml
@@ -0,0 +1,27 @@
+dataset: off_quality/main/nutrition_table
+columns:
+ - name: product_id
+ - name: energy_kj
+ - name: energy_kj_computed
+ - name: energy_kcal
+ - name: fat
+ - name: saturated_fat
+ - name: carbohydrates
+ - name: sugars
+ - name: starch
+ - name: sodium
+ - name: ingredients_text
+ - name: ingredients_text_present
+ - name: contains_statement_present
+ - name: allergen_evidence_present
+ - name: fop_threshold_exceeded
+ - name: fop_symbol_present
+ - name: fop_exempt_proxy
+ - name: product_is_prepackaged_proxy
+ - name: lc
+ - name: lang
+ - name: language_code
+checks:
+ - failed_rows:
+ name: saturated_fat_over_105g
+ expression: saturated_fat > 105
diff --git a/OFF_DataQuality/results/declarative_runtime/soda/soda_cloud/contracts/saturated_fat_vs_fat.yml b/OFF_DataQuality/results/declarative_runtime/soda/soda_cloud/contracts/saturated_fat_vs_fat.yml
new file mode 100644
index 0000000000000000000000000000000000000000..006010b2631a40cacf4213fcb654e928d3f885ca
--- /dev/null
+++ b/OFF_DataQuality/results/declarative_runtime/soda/soda_cloud/contracts/saturated_fat_vs_fat.yml
@@ -0,0 +1,27 @@
+dataset: off_quality/main/nutrition_table
+columns:
+ - name: product_id
+ - name: energy_kj
+ - name: energy_kj_computed
+ - name: energy_kcal
+ - name: fat
+ - name: saturated_fat
+ - name: carbohydrates
+ - name: sugars
+ - name: starch
+ - name: sodium
+ - name: ingredients_text
+ - name: ingredients_text_present
+ - name: contains_statement_present
+ - name: allergen_evidence_present
+ - name: fop_threshold_exceeded
+ - name: fop_symbol_present
+ - name: fop_exempt_proxy
+ - name: product_is_prepackaged_proxy
+ - name: lc
+ - name: lang
+ - name: language_code
+checks:
+ - failed_rows:
+ name: saturated_fat_vs_fat
+ expression: saturated_fat > (1.0 * fat + 0.001)
diff --git a/OFF_DataQuality/results/declarative_runtime/soda/soda_cloud/contracts/sugars_over_105g.yml b/OFF_DataQuality/results/declarative_runtime/soda/soda_cloud/contracts/sugars_over_105g.yml
new file mode 100644
index 0000000000000000000000000000000000000000..0c4f23f7f5702d18dd502ae0afe5fcc0de0b6983
--- /dev/null
+++ b/OFF_DataQuality/results/declarative_runtime/soda/soda_cloud/contracts/sugars_over_105g.yml
@@ -0,0 +1,27 @@
+dataset: off_quality/main/nutrition_table
+columns:
+ - name: product_id
+ - name: energy_kj
+ - name: energy_kj_computed
+ - name: energy_kcal
+ - name: fat
+ - name: saturated_fat
+ - name: carbohydrates
+ - name: sugars
+ - name: starch
+ - name: sodium
+ - name: ingredients_text
+ - name: ingredients_text_present
+ - name: contains_statement_present
+ - name: allergen_evidence_present
+ - name: fop_threshold_exceeded
+ - name: fop_symbol_present
+ - name: fop_exempt_proxy
+ - name: product_is_prepackaged_proxy
+ - name: lc
+ - name: lang
+ - name: language_code
+checks:
+ - failed_rows:
+ name: sugars_over_105g
+ expression: sugars > 105
diff --git a/OFF_DataQuality/results/declarative_runtime/soda/soda_cloud/contracts/sugars_plus_starch_vs_carbohydrates.yml b/OFF_DataQuality/results/declarative_runtime/soda/soda_cloud/contracts/sugars_plus_starch_vs_carbohydrates.yml
new file mode 100644
index 0000000000000000000000000000000000000000..122bedd8ec354f14556d80690dcb68a137ef6826
--- /dev/null
+++ b/OFF_DataQuality/results/declarative_runtime/soda/soda_cloud/contracts/sugars_plus_starch_vs_carbohydrates.yml
@@ -0,0 +1,27 @@
+dataset: off_quality/main/nutrition_table
+columns:
+ - name: product_id
+ - name: energy_kj
+ - name: energy_kj_computed
+ - name: energy_kcal
+ - name: fat
+ - name: saturated_fat
+ - name: carbohydrates
+ - name: sugars
+ - name: starch
+ - name: sodium
+ - name: ingredients_text
+ - name: ingredients_text_present
+ - name: contains_statement_present
+ - name: allergen_evidence_present
+ - name: fop_threshold_exceeded
+ - name: fop_symbol_present
+ - name: fop_exempt_proxy
+ - name: product_is_prepackaged_proxy
+ - name: lc
+ - name: lang
+ - name: language_code
+checks:
+ - failed_rows:
+ name: sugars_plus_starch_vs_carbohydrates
+ expression: (sugars + starch) > (carbohydrates + 0.001)
diff --git a/OFF_DataQuality/results/declarative_runtime/soda/soda_cloud/data_source.yml b/OFF_DataQuality/results/declarative_runtime/soda/soda_cloud/data_source.yml
new file mode 100644
index 0000000000000000000000000000000000000000..589d1eea166af9267b347fcdd681173867240197
--- /dev/null
+++ b/OFF_DataQuality/results/declarative_runtime/soda/soda_cloud/data_source.yml
@@ -0,0 +1,5 @@
+type: duckdb
+name: off_quality
+connection:
+ database: C:/dev/OFF_DataQuality_Prototype/results/declarative_runtime/soda/soda_cloud_runtime.db
+ schema: main
diff --git a/OFF_DataQuality/results/declarative_runtime/soda/soda_cloud/soda_cloud.yml b/OFF_DataQuality/results/declarative_runtime/soda/soda_cloud/soda_cloud.yml
new file mode 100644
index 0000000000000000000000000000000000000000..eccdcab464096519d4964d6cb42204dc321cdb5c
--- /dev/null
+++ b/OFF_DataQuality/results/declarative_runtime/soda/soda_cloud/soda_cloud.yml
@@ -0,0 +1,4 @@
+soda_cloud:
+ host: cloud.us.soda.io
+ api_key_id: 500b32e7-7f6e-48d9-99b6-6baf7d493827
+ api_key_secret: YhYpBOl2CcnATIhcR9hiz0ftitPJmR66MLEsgPdfkCeOCzdCRsI-gQ
diff --git a/OFF_DataQuality/results/engine_comparison.json b/OFF_DataQuality/results/engine_comparison.json
new file mode 100644
index 0000000000000000000000000000000000000000..eaa316068bd6e0d750b585b467366624d3cf44b5
--- /dev/null
+++ b/OFF_DataQuality/results/engine_comparison.json
@@ -0,0 +1,2427 @@
+{
+ "generated_at_utc": "2026-03-20T02:16:51.454190+00:00",
+ "comparison_fingerprint": {
+ "comparison_run_id": "comparison_20260320T021651454190p0000_802895b4",
+ "comparison_sha256": "5e38ef21823aded9830415be43d4189df6c1b7facaa3942d11746129d5cbec94",
+ "engine_run_ids": {
+ "python": "parity_20260320T020923217791p0000_522963ec",
+ "dbt": "parity_20260320T021319241433p0000_babb0a3c",
+ "soda": "parity_20260320T021651369626p0000_93e7e9a5"
+ },
+ "dataset_fingerprint_sha256_by_engine": {
+ "python": "edc06c70fc61d470398d05743822716e42722100fe4f1dcb721aff4895aabd76",
+ "dbt": "edc06c70fc61d470398d05743822716e42722100fe4f1dcb721aff4895aabd76",
+ "soda": "edc06c70fc61d470398d05743822716e42722100fe4f1dcb721aff4895aabd76"
+ },
+ "rulepack_fingerprint_sha256_by_engine": {
+ "python": "ceec8ffe16d3fc6fd32744c834c7a34068b108a398f12c9abf86da0f5a390149",
+ "dbt": "ceec8ffe16d3fc6fd32744c834c7a34068b108a398f12c9abf86da0f5a390149",
+ "soda": "ceec8ffe16d3fc6fd32744c834c7a34068b108a398f12c9abf86da0f5a390149"
+ },
+ "dataset_fingerprint_consistent": true,
+ "rulepack_fingerprint_consistent": true,
+ "dataset_fingerprint_sha256": "edc06c70fc61d470398d05743822716e42722100fe4f1dcb721aff4895aabd76",
+ "rulepack_fingerprint_sha256": "ceec8ffe16d3fc6fd32744c834c7a34068b108a398f12c9abf86da0f5a390149",
+ "code_commit": "fdda1c042a421a0dd81a90c7ca692dccb4915106",
+ "code_commits_by_engine": {
+ "python": "fdda1c042a421a0dd81a90c7ca692dccb4915106",
+ "dbt": "fdda1c042a421a0dd81a90c7ca692dccb4915106",
+ "soda": "fdda1c042a421a0dd81a90c7ca692dccb4915106"
+ }
+ },
+ "comparison_method": {
+ "best_engine_ranking": "Prefer MATCH status, then fewer mismatches, then higher effective_confidence. effective_confidence = overall_confidence * provider_factor.",
+ "decision_score": "decision_score = effective_confidence + architecture_bonus(declarative for simple rules / python for complex rules) - mismatch_penalty - review_penalty.",
+ "hybrid_tie_break": "If python and best declarative engine are close (within 0.20 effective confidence): prefer declarative for declarative-friendly rules, prefer python for non-declarative rules.",
+ "declarative_tie_break": "When dbt and soda are exactly tied on status/mismatches/scores for a rule, use a stable hash of rule_name to select dbt or soda explicitly.",
+ "provider_factor_notes": {
+ "python_real_llm": 1.0,
+ "python_simulated_fallback": 0.55,
+ "dbt_sql_fallback": 0.85,
+ "soda_cloud": 1.0,
+ "soda_sql_fallback": 0.85
+ }
+ },
+ "dataset": {
+ "jsonl_path": "C:\\dev\\OFF_DataQuality_Prototype\\data\\sample_products.jsonl",
+ "duckdb_path": "C:\\dev\\OFF_DataQuality_Prototype\\off_quality.db",
+ "products_tested": 400,
+ "source_jsonl": "C:\\dev\\OFF_DataQuality_Prototype\\openfoodfacts-products.jsonl",
+ "perl_rules_source": "inline_legacy_rules",
+ "execution_engine": "python",
+ "soda_mode": "cloud",
+ "profile": "hybrid",
+ "profile_rule_count": 19,
+ "dataset_fingerprint_sha256": "edc06c70fc61d470398d05743822716e42722100fe4f1dcb721aff4895aabd76",
+ "rulepack_fingerprint_sha256": "ceec8ffe16d3fc6fd32744c834c7a34068b108a398f12c9abf86da0f5a390149"
+ },
+ "engines": [
+ "python",
+ "dbt",
+ "soda"
+ ],
+ "engine_run_fingerprints": {
+ "python": {
+ "run_id": "parity_20260320T020923217791p0000_522963ec",
+ "generated_at_utc": "2026-03-20T02:09:23.217791+00:00",
+ "execution_engine": "python",
+ "soda_mode": "cloud",
+ "llm_provider": "groq",
+ "llm_model": "openai/gpt-oss-120b",
+ "code_commit": "fdda1c042a421a0dd81a90c7ca692dccb4915106",
+ "dataset_fingerprint": {
+ "source_mode": "off_jsonl",
+ "source_jsonl": "C:\\dev\\OFF_DataQuality_Prototype\\openfoodfacts-products.jsonl",
+ "requested_size": 400,
+ "products_tested": 400,
+ "seed": null,
+ "product_id_first": "0000101209159",
+ "product_id_last": "0008295663177",
+ "sha256": "edc06c70fc61d470398d05743822716e42722100fe4f1dcb721aff4895aabd76"
+ },
+ "rulepack_fingerprint": {
+ "profile": "hybrid",
+ "rule_count": 19,
+ "rule_names_sha256": "c39c2b95539ad714a422b372ca37457381efad3eab0ab3cf6183fb84e78799b2",
+ "rule_ir_sha256": "ceec8ffe16d3fc6fd32744c834c7a34068b108a398f12c9abf86da0f5a390149"
+ }
+ },
+ "dbt": {
+ "run_id": "parity_20260320T021319241433p0000_babb0a3c",
+ "generated_at_utc": "2026-03-20T02:13:19.241433+00:00",
+ "execution_engine": "dbt",
+ "soda_mode": "cloud",
+ "llm_provider": "groq",
+ "llm_model": "openai/gpt-oss-120b",
+ "code_commit": "fdda1c042a421a0dd81a90c7ca692dccb4915106",
+ "dataset_fingerprint": {
+ "source_mode": "off_jsonl",
+ "source_jsonl": "C:\\dev\\OFF_DataQuality_Prototype\\openfoodfacts-products.jsonl",
+ "requested_size": 400,
+ "products_tested": 400,
+ "seed": null,
+ "product_id_first": "0000101209159",
+ "product_id_last": "0008295663177",
+ "sha256": "edc06c70fc61d470398d05743822716e42722100fe4f1dcb721aff4895aabd76"
+ },
+ "rulepack_fingerprint": {
+ "profile": "hybrid",
+ "rule_count": 19,
+ "rule_names_sha256": "c39c2b95539ad714a422b372ca37457381efad3eab0ab3cf6183fb84e78799b2",
+ "rule_ir_sha256": "ceec8ffe16d3fc6fd32744c834c7a34068b108a398f12c9abf86da0f5a390149"
+ }
+ },
+ "soda": {
+ "run_id": "parity_20260320T021651369626p0000_93e7e9a5",
+ "generated_at_utc": "2026-03-20T02:16:51.369626+00:00",
+ "execution_engine": "soda",
+ "soda_mode": "cloud",
+ "llm_provider": "groq",
+ "llm_model": "openai/gpt-oss-120b",
+ "code_commit": "fdda1c042a421a0dd81a90c7ca692dccb4915106",
+ "dataset_fingerprint": {
+ "source_mode": "off_jsonl",
+ "source_jsonl": "C:\\dev\\OFF_DataQuality_Prototype\\openfoodfacts-products.jsonl",
+ "requested_size": 400,
+ "products_tested": 400,
+ "seed": null,
+ "product_id_first": "0000101209159",
+ "product_id_last": "0008295663177",
+ "sha256": "edc06c70fc61d470398d05743822716e42722100fe4f1dcb721aff4895aabd76"
+ },
+ "rulepack_fingerprint": {
+ "profile": "hybrid",
+ "rule_count": 19,
+ "rule_names_sha256": "c39c2b95539ad714a422b372ca37457381efad3eab0ab3cf6183fb84e78799b2",
+ "rule_ir_sha256": "ceec8ffe16d3fc6fd32744c834c7a34068b108a398f12c9abf86da0f5a390149"
+ }
+ }
+ },
+ "per_engine_summary": {
+ "python": {
+ "rules": 19,
+ "passed": 19,
+ "avg_overall_confidence": 0.2826,
+ "avg_effective_confidence": 0.2826,
+ "avg_parity_ci_lower": 0.9905,
+ "avg_equivalence_rate": 1.0,
+ "avg_mutation_score": 0.6053,
+ "fallback_rules": 0,
+ "real_llm_rules": 19,
+ "real_llm_rate": 1.0,
+ "repairs_applied": 0
+ },
+ "dbt": {
+ "rules": 19,
+ "passed": 19,
+ "avg_overall_confidence": 0.2946,
+ "avg_effective_confidence": 0.2946,
+ "avg_parity_ci_lower": 0.9905,
+ "avg_equivalence_rate": 1.0,
+ "avg_mutation_score": 1.0,
+ "fallback_rules": 0
+ },
+ "soda": {
+ "rules": 19,
+ "passed": 19,
+ "avg_overall_confidence": 0.2946,
+ "avg_effective_confidence": 0.2946,
+ "avg_parity_ci_lower": 0.9905,
+ "avg_equivalence_rate": 1.0,
+ "avg_mutation_score": 1.0,
+ "fallback_rules": 0
+ }
+ },
+ "per_complexity_summary": {
+ "simple": {
+ "rules": 9,
+ "python_wins": 0,
+ "dbt_wins": 5,
+ "soda_wins": 4,
+ "avg_best_effective_confidence": 0.4464
+ },
+ "medium": {
+ "rules": 6,
+ "python_wins": 0,
+ "dbt_wins": 4,
+ "soda_wins": 2,
+ "avg_best_effective_confidence": 0.2306
+ },
+ "intricate": {
+ "rules": 4,
+ "python_wins": 4,
+ "dbt_wins": 0,
+ "soda_wins": 0,
+ "avg_best_effective_confidence": 0.0446
+ }
+ },
+ "rule_comparison": [
+ {
+ "rule_name": "ca_allergen_evidence_missing_ingredients_text",
+ "tag": "ca-allergen-evidence-but-missing-ingredients-text",
+ "severity": "warning",
+ "condition": "allergen_evidence_present > 0.0 && ingredients_text_present == 0.0",
+ "jurisdiction": "ca",
+ "profile_tags": [
+ "canada",
+ "hybrid"
+ ],
+ "regulatory_type": "statutory_proxy",
+ "legal_citation": "FDR B.01.010.1(2); FDR B.01.010.3",
+ "source_url": "https://laws-lois.justice.gc.ca/eng/regulations/C.R.C.,_c._870/section-B.01.010.1.html",
+ "effective_date": "2012-08-04",
+ "review_status": "draft",
+ "reviewer": "pending-mentor-review",
+ "required_fields": [
+ "allergen_evidence_present",
+ "ingredients_text_present",
+ "ingredients_text"
+ ],
+ "exemption_logic": "Proxy check: flags records with allergen evidence but no ingredient text present.",
+ "rule_notes": "Phase-1 Canada allergen rule using OFF-available proxy fields.",
+ "rule_ir_hash": "89636a09e83b",
+ "condition_type": "compound_threshold_and",
+ "complexity": "medium",
+ "declarative_friendly": true,
+ "products_tested": 400,
+ "best_engine": "soda",
+ "selection_reason": "hybrid-close-declarative:explicit-hash-tie-break-odd->soda",
+ "declarative_tie_break_applied": true,
+ "recommendation": "Declarative-friendly rule; prefer dbt/soda for readability and operations.",
+ "engines": {
+ "python": {
+ "status": "MATCH",
+ "mismatches": 0,
+ "parity_ci_lower": 0.9905,
+ "overall_confidence": 0.2015,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_cases": 2,
+ "mutation_score": 1.0,
+ "mutation_total": 0,
+ "mutation_killed": 0,
+ "verification_score": 1.0,
+ "counterexample_repair_applied": false,
+ "equivalence_counterexamples": [],
+ "effective_confidence": 0.2015,
+ "provider_factor": 1.0,
+ "real_llm_used": true,
+ "decision_score": 0.3015,
+ "conversion_provider": "groq",
+ "conversion_notes": "Converted via Groq (openai/gpt-oss-120b).",
+ "execution_mode": "",
+ "cloud_connected": false,
+ "cloud_scan_id": "",
+ "cloud_scan_url": "",
+ "conversion_artifact": "def check_ca_allergen_evidence_missing_ingredients_text(product):\n \"\"\"\n Returns the rule tag if allergen evidence is present (>0) while ingredients text is missing (==0).\n Returns None otherwise or if required fields are missing/non-numeric.\n \"\"\"\n tag = \"ca-allergen-evidence-but-missing-ingredients-text\"\n\n allergen_val = product.get(\"allergen_evidence_present\")\n ingredients_val = product.get(\"ingredients_text_present\")\n\n # If either value is missing or not a number, do not flag a violation\n if allergen_val is None or ingredients_val is None:\n return None\n if not isinstance(allergen_val, (int, float)) or not isinstance(ingredients_val, (int, float)):\n return None\n\n if allergen_val > 0.0 and ingredients_val == 0.0:\n return tag\n return None",
+ "conversion_lines": 19,
+ "failed_test_cases": []
+ },
+ "dbt": {
+ "status": "MATCH",
+ "mismatches": 0,
+ "parity_ci_lower": 0.9905,
+ "overall_confidence": 0.2193,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_cases": 0,
+ "mutation_score": 1.0,
+ "mutation_total": 0,
+ "mutation_killed": 0,
+ "verification_score": 1.0,
+ "counterexample_repair_applied": false,
+ "equivalence_counterexamples": [],
+ "effective_confidence": 0.2193,
+ "provider_factor": 1.0,
+ "real_llm_used": null,
+ "decision_score": 0.2543,
+ "conversion_provider": "dbt_core",
+ "conversion_notes": "dbt tests executed through dbt-core. Command: dbt debug + dbt run-operation count_violations (per-rule x19) --project-dir C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\dbt\\dbt_project --profiles-dir C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\dbt\\dbt_project | Success: True | Return code: 0",
+ "execution_mode": "local",
+ "cloud_connected": false,
+ "cloud_scan_id": "",
+ "cloud_scan_url": "",
+ "conversion_artifact": "SELECT product_id\nFROM {{ source('off_source', 'nutrition_table') }}\nWHERE allergen_evidence_present > 0.0 AND ingredients_text_present == 0.0",
+ "conversion_lines": 3,
+ "failed_test_cases": []
+ },
+ "soda": {
+ "status": "MATCH",
+ "mismatches": 0,
+ "parity_ci_lower": 0.9905,
+ "overall_confidence": 0.2193,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_cases": 0,
+ "mutation_score": 1.0,
+ "mutation_total": 0,
+ "mutation_killed": 0,
+ "verification_score": 1.0,
+ "counterexample_repair_applied": false,
+ "equivalence_counterexamples": [],
+ "effective_confidence": 0.2193,
+ "provider_factor": 1.0,
+ "real_llm_used": null,
+ "decision_score": 0.2543,
+ "conversion_provider": "soda_cloud",
+ "conversion_notes": "Soda Cloud scan executed successfully. Command: soda contract verify (per-rule x19) -ds C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\soda\\soda_cloud\\data_source.yml -sc C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\soda\\soda_cloud\\soda_cloud.yml -p | Success: True | Return code: 0",
+ "execution_mode": "cloud",
+ "cloud_connected": true,
+ "cloud_scan_id": "",
+ "cloud_scan_url": "https://cloud.us.soda.io/o/c9e7e376-1da2-49c5-93cb-78c6d95273ee/datasets/5e60cafe-18fc-4d01-8390-0057b49d7765",
+ "conversion_artifact": " - failed_rows:\n name: ca_allergen_evidence_missing_ingredients_text\n expression: allergen_evidence_present > 0.0 AND ingredients_text_present == 0.0",
+ "conversion_lines": 3,
+ "failed_test_cases": []
+ }
+ }
+ },
+ {
+ "rule_name": "ca_contains_statement_without_allergen_evidence",
+ "tag": "ca-contains-statement-without-allergen-evidence",
+ "severity": "warning",
+ "condition": "contains_statement_present > 0.0 && allergen_evidence_present == 0.0",
+ "jurisdiction": "ca",
+ "profile_tags": [
+ "canada",
+ "hybrid"
+ ],
+ "regulatory_type": "statutory_proxy",
+ "legal_citation": "FDR B.01.010.3(1)(b), (2)",
+ "source_url": "https://laws-lois.justice.gc.ca/eng/regulations/C.R.C.,_c._870/section-B.01.010.3.html",
+ "effective_date": "2012-08-04",
+ "review_status": "draft",
+ "reviewer": "pending-mentor-review",
+ "required_fields": [
+ "contains_statement_present",
+ "allergen_evidence_present"
+ ],
+ "exemption_logic": "Proxy check: 'contains' proxy without allergen evidence proxy.",
+ "rule_notes": "Phase-1 Canada allergen consistency rule.",
+ "rule_ir_hash": "224946da0a1f",
+ "condition_type": "compound_threshold_and",
+ "complexity": "medium",
+ "declarative_friendly": true,
+ "products_tested": 400,
+ "best_engine": "dbt",
+ "selection_reason": "hybrid-close-declarative:explicit-hash-tie-break-even->dbt",
+ "declarative_tie_break_applied": true,
+ "recommendation": "Declarative-friendly rule; prefer dbt/soda for readability and operations.",
+ "engines": {
+ "python": {
+ "status": "MATCH",
+ "mismatches": 0,
+ "parity_ci_lower": 0.9905,
+ "overall_confidence": 0.0451,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_cases": 2,
+ "mutation_score": 1.0,
+ "mutation_total": 0,
+ "mutation_killed": 0,
+ "verification_score": 1.0,
+ "counterexample_repair_applied": false,
+ "equivalence_counterexamples": [],
+ "effective_confidence": 0.0451,
+ "provider_factor": 1.0,
+ "real_llm_used": true,
+ "decision_score": 0.1451,
+ "conversion_provider": "groq",
+ "conversion_notes": "Converted via Groq (openai/gpt-oss-120b).",
+ "execution_mode": "",
+ "cloud_connected": false,
+ "cloud_scan_id": "",
+ "cloud_scan_url": "",
+ "conversion_artifact": "def check_ca_contains_statement_without_allergen_evidence(product: dict):\n tag = \"ca-contains-statement-without-allergen-evidence\"\n cs = product.get(\"contains_statement_present\")\n ae = product.get(\"allergen_evidence_present\")\n # If either value is missing or not numeric, do not flag\n if cs is None or ae is None:\n return None\n if not isinstance(cs, (int, float)) or not isinstance(ae, (int, float)):\n return None\n if cs > 0.0 and ae == 0.0:\n return tag\n return None",
+ "conversion_lines": 12,
+ "failed_test_cases": []
+ },
+ "dbt": {
+ "status": "MATCH",
+ "mismatches": 0,
+ "parity_ci_lower": 0.9905,
+ "overall_confidence": 0.049,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_cases": 0,
+ "mutation_score": 1.0,
+ "mutation_total": 0,
+ "mutation_killed": 0,
+ "verification_score": 1.0,
+ "counterexample_repair_applied": false,
+ "equivalence_counterexamples": [],
+ "effective_confidence": 0.049,
+ "provider_factor": 1.0,
+ "real_llm_used": null,
+ "decision_score": 0.084,
+ "conversion_provider": "dbt_core",
+ "conversion_notes": "dbt tests executed through dbt-core. Command: dbt debug + dbt run-operation count_violations (per-rule x19) --project-dir C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\dbt\\dbt_project --profiles-dir C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\dbt\\dbt_project | Success: True | Return code: 0",
+ "execution_mode": "local",
+ "cloud_connected": false,
+ "cloud_scan_id": "",
+ "cloud_scan_url": "",
+ "conversion_artifact": "SELECT product_id\nFROM {{ source('off_source', 'nutrition_table') }}\nWHERE contains_statement_present > 0.0 AND allergen_evidence_present == 0.0",
+ "conversion_lines": 3,
+ "failed_test_cases": []
+ },
+ "soda": {
+ "status": "MATCH",
+ "mismatches": 0,
+ "parity_ci_lower": 0.9905,
+ "overall_confidence": 0.049,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_cases": 0,
+ "mutation_score": 1.0,
+ "mutation_total": 0,
+ "mutation_killed": 0,
+ "verification_score": 1.0,
+ "counterexample_repair_applied": false,
+ "equivalence_counterexamples": [],
+ "effective_confidence": 0.049,
+ "provider_factor": 1.0,
+ "real_llm_used": null,
+ "decision_score": 0.084,
+ "conversion_provider": "soda_cloud",
+ "conversion_notes": "Soda Cloud scan executed successfully. Command: soda contract verify (per-rule x19) -ds C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\soda\\soda_cloud\\data_source.yml -sc C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\soda\\soda_cloud\\soda_cloud.yml -p | Success: True | Return code: 0",
+ "execution_mode": "cloud",
+ "cloud_connected": true,
+ "cloud_scan_id": "",
+ "cloud_scan_url": "https://cloud.us.soda.io/o/c9e7e376-1da2-49c5-93cb-78c6d95273ee/datasets/5e60cafe-18fc-4d01-8390-0057b49d7765",
+ "conversion_artifact": " - failed_rows:\n name: ca_contains_statement_without_allergen_evidence\n expression: contains_statement_present > 0.0 AND allergen_evidence_present == 0.0",
+ "conversion_lines": 3,
+ "failed_test_cases": []
+ }
+ }
+ },
+ {
+ "rule_name": "ca_fop_required_but_symbol_missing",
+ "tag": "ca-fop-required-but-symbol-missing",
+ "severity": "error",
+ "condition": "fop_threshold_exceeded > 0.0 && fop_symbol_present == 0.0 && fop_exempt_proxy == 0.0 && product_is_prepackaged_proxy > 0.0",
+ "jurisdiction": "ca",
+ "profile_tags": [
+ "canada",
+ "hybrid"
+ ],
+ "regulatory_type": "statutory_proxy",
+ "legal_citation": "FDR B.01.350(1)",
+ "source_url": "https://laws-lois.justice.gc.ca/eng/regulations/C.R.C.,_c._870/section-B.01.350.html",
+ "effective_date": "2026-01-01",
+ "review_status": "draft",
+ "reviewer": "pending-mentor-review",
+ "required_fields": [
+ "fop_threshold_exceeded",
+ "fop_symbol_present",
+ "fop_exempt_proxy",
+ "product_is_prepackaged_proxy"
+ ],
+ "exemption_logic": "Applies only when proxy not exempt and prepackaged proxy is true.",
+ "rule_notes": "Phase-1 Canada FOP threshold-vs-symbol proxy.",
+ "rule_ir_hash": "6a505be71205",
+ "condition_type": "compound_threshold_and",
+ "complexity": "medium",
+ "declarative_friendly": true,
+ "products_tested": 400,
+ "best_engine": "dbt",
+ "selection_reason": "hybrid-close-declarative:explicit-hash-tie-break-even->dbt",
+ "declarative_tie_break_applied": true,
+ "recommendation": "Declarative-friendly rule; prefer dbt/soda for readability and operations.",
+ "engines": {
+ "python": {
+ "status": "MATCH",
+ "mismatches": 0,
+ "parity_ci_lower": 0.9905,
+ "overall_confidence": 0.8902,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_cases": 2,
+ "mutation_score": 1.0,
+ "mutation_total": 0,
+ "mutation_killed": 0,
+ "verification_score": 1.0,
+ "counterexample_repair_applied": false,
+ "equivalence_counterexamples": [],
+ "effective_confidence": 0.8902,
+ "provider_factor": 1.0,
+ "real_llm_used": true,
+ "decision_score": 0.9902,
+ "conversion_provider": "groq",
+ "conversion_notes": "Converted via Groq (openai/gpt-oss-120b).",
+ "execution_mode": "",
+ "cloud_connected": false,
+ "cloud_scan_id": "",
+ "cloud_scan_url": "",
+ "conversion_artifact": "def check_ca_fop_required_but_symbol_missing(product):\n \"\"\"\n Returns the rule tag \"ca-fop-required-but-symbol-missing\" if the compound condition is met,\n otherwise returns None.\n \"\"\"\n # Extract required fields\n fop_threshold_exceeded = product.get(\"fop_threshold_exceeded\")\n fop_symbol_present = product.get(\"fop_symbol_present\")\n fop_exempt_proxy = product.get(\"fop_exempt_proxy\")\n product_is_prepackaged_proxy = product.get(\"product_is_prepackaged_proxy\")\n\n # If any required field is missing or not a number, do not flag a violation\n for value in (\n fop_threshold_exceeded,\n fop_symbol_present,\n fop_exempt_proxy,\n product_is_prepackaged_proxy,\n ):\n if value is None:\n return None\n if not isinstance(value, (int, float)):\n return None\n\n # Evaluate the compound condition\n if (\n fop_threshold_exceeded > 0.0\n and fop_symbol_present == 0.0\n and fop_exempt_proxy == 0.0\n and product_is_prepackaged_proxy > 0.0\n ):\n return \"ca-fop-required-but-symbol-missing\"\n\n return None",
+ "conversion_lines": 33,
+ "failed_test_cases": []
+ },
+ "dbt": {
+ "status": "MATCH",
+ "mismatches": 0,
+ "parity_ci_lower": 0.9905,
+ "overall_confidence": 0.9684,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_cases": 0,
+ "mutation_score": 1.0,
+ "mutation_total": 0,
+ "mutation_killed": 0,
+ "verification_score": 1.0,
+ "counterexample_repair_applied": false,
+ "equivalence_counterexamples": [],
+ "effective_confidence": 0.9684,
+ "provider_factor": 1.0,
+ "real_llm_used": null,
+ "decision_score": 1.0034,
+ "conversion_provider": "dbt_core",
+ "conversion_notes": "dbt tests executed through dbt-core. Command: dbt debug + dbt run-operation count_violations (per-rule x19) --project-dir C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\dbt\\dbt_project --profiles-dir C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\dbt\\dbt_project | Success: True | Return code: 0",
+ "execution_mode": "local",
+ "cloud_connected": false,
+ "cloud_scan_id": "",
+ "cloud_scan_url": "",
+ "conversion_artifact": "SELECT product_id\nFROM {{ source('off_source', 'nutrition_table') }}\nWHERE fop_threshold_exceeded > 0.0 AND fop_symbol_present == 0.0 AND fop_exempt_proxy == 0.0 AND product_is_prepackaged_proxy > 0.0",
+ "conversion_lines": 3,
+ "failed_test_cases": []
+ },
+ "soda": {
+ "status": "MATCH",
+ "mismatches": 0,
+ "parity_ci_lower": 0.9905,
+ "overall_confidence": 0.9684,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_cases": 0,
+ "mutation_score": 1.0,
+ "mutation_total": 0,
+ "mutation_killed": 0,
+ "verification_score": 1.0,
+ "counterexample_repair_applied": false,
+ "equivalence_counterexamples": [],
+ "effective_confidence": 0.9684,
+ "provider_factor": 1.0,
+ "real_llm_used": null,
+ "decision_score": 1.0034,
+ "conversion_provider": "soda_cloud",
+ "conversion_notes": "Soda Cloud scan executed successfully. Command: soda contract verify (per-rule x19) -ds C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\soda\\soda_cloud\\data_source.yml -sc C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\soda\\soda_cloud\\soda_cloud.yml -p | Success: True | Return code: 0",
+ "execution_mode": "cloud",
+ "cloud_connected": true,
+ "cloud_scan_id": "",
+ "cloud_scan_url": "https://cloud.us.soda.io/o/c9e7e376-1da2-49c5-93cb-78c6d95273ee/datasets/5e60cafe-18fc-4d01-8390-0057b49d7765",
+ "conversion_artifact": " - failed_rows:\n name: ca_fop_required_but_symbol_missing\n expression: fop_threshold_exceeded > 0.0 AND fop_symbol_present == 0.0 AND fop_exempt_proxy == 0.0 AND product_is_prepackaged_proxy > 0.0",
+ "conversion_lines": 3,
+ "failed_test_cases": []
+ }
+ }
+ },
+ {
+ "rule_name": "ca_fop_symbol_present_but_not_required",
+ "tag": "ca-fop-symbol-present-but-not-required",
+ "severity": "warning",
+ "condition": "fop_symbol_present > 0.0 && fop_threshold_exceeded == 0.0 && fop_exempt_proxy == 0.0 && product_is_prepackaged_proxy > 0.0",
+ "jurisdiction": "ca",
+ "profile_tags": [
+ "canada",
+ "hybrid"
+ ],
+ "regulatory_type": "guidance_proxy",
+ "legal_citation": "FDR B.01.350; CFIA FOP guidance",
+ "source_url": "https://inspection.canada.ca/en/food-labels/labelling/industry/nutrition-labelling/fop-nutrition-symbol",
+ "effective_date": "2026-01-01",
+ "review_status": "draft",
+ "reviewer": "pending-mentor-review",
+ "required_fields": [
+ "fop_threshold_exceeded",
+ "fop_symbol_present",
+ "fop_exempt_proxy",
+ "product_is_prepackaged_proxy"
+ ],
+ "exemption_logic": "Proxy warning for symbol present when threshold proxy not exceeded and not exempt.",
+ "rule_notes": "Phase-1 Canada FOP over-labelling consistency rule.",
+ "rule_ir_hash": "4d20f5612a17",
+ "condition_type": "compound_threshold_and",
+ "complexity": "medium",
+ "declarative_friendly": true,
+ "products_tested": 400,
+ "best_engine": "dbt",
+ "selection_reason": "hybrid-close-declarative:explicit-hash-tie-break-even->dbt",
+ "declarative_tie_break_applied": true,
+ "recommendation": "Declarative-friendly rule; prefer dbt/soda for readability and operations.",
+ "engines": {
+ "python": {
+ "status": "MATCH",
+ "mismatches": 0,
+ "parity_ci_lower": 0.9905,
+ "overall_confidence": 0.0451,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_cases": 2,
+ "mutation_score": 1.0,
+ "mutation_total": 0,
+ "mutation_killed": 0,
+ "verification_score": 1.0,
+ "counterexample_repair_applied": false,
+ "equivalence_counterexamples": [],
+ "effective_confidence": 0.0451,
+ "provider_factor": 1.0,
+ "real_llm_used": true,
+ "decision_score": 0.1451,
+ "conversion_provider": "groq",
+ "conversion_notes": "Converted via Groq (openai/gpt-oss-120b).",
+ "execution_mode": "",
+ "cloud_connected": false,
+ "cloud_scan_id": "",
+ "cloud_scan_url": "",
+ "conversion_artifact": "def check_ca_fop_symbol_present_but_not_required(product: dict):\n tag = \"ca-fop-symbol-present-but-not-required\"\n # Required fields\n fields = [\"fop_symbol_present\", \"fop_threshold_exceeded\", \"fop_exempt_proxy\", \"product_is_prepackaged_proxy\"]\n values = {}\n for f in fields:\n v = product.get(f, None)\n # Missing field rule: None, empty, whitespace -> violation (but not applicable for this rule type)\n if v is None:\n return None\n # Non-numeric check for field_comparison/threshold rules\n if not isinstance(v, (int, float)):\n return None\n values[f] = v\n if (values[\"fop_symbol_present\"] > 0.0 and\n values[\"fop_threshold_exceeded\"] == 0.0 and\n values[\"fop_exempt_proxy\"] == 0.0 and\n values[\"product_is_prepackaged_proxy\"] > 0.0):\n return tag\n return None",
+ "conversion_lines": 20,
+ "failed_test_cases": []
+ },
+ "dbt": {
+ "status": "MATCH",
+ "mismatches": 0,
+ "parity_ci_lower": 0.9905,
+ "overall_confidence": 0.049,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_cases": 0,
+ "mutation_score": 1.0,
+ "mutation_total": 0,
+ "mutation_killed": 0,
+ "verification_score": 1.0,
+ "counterexample_repair_applied": false,
+ "equivalence_counterexamples": [],
+ "effective_confidence": 0.049,
+ "provider_factor": 1.0,
+ "real_llm_used": null,
+ "decision_score": 0.084,
+ "conversion_provider": "dbt_core",
+ "conversion_notes": "dbt tests executed through dbt-core. Command: dbt debug + dbt run-operation count_violations (per-rule x19) --project-dir C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\dbt\\dbt_project --profiles-dir C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\dbt\\dbt_project | Success: True | Return code: 0",
+ "execution_mode": "local",
+ "cloud_connected": false,
+ "cloud_scan_id": "",
+ "cloud_scan_url": "",
+ "conversion_artifact": "SELECT product_id\nFROM {{ source('off_source', 'nutrition_table') }}\nWHERE fop_symbol_present > 0.0 AND fop_threshold_exceeded == 0.0 AND fop_exempt_proxy == 0.0 AND product_is_prepackaged_proxy > 0.0",
+ "conversion_lines": 3,
+ "failed_test_cases": []
+ },
+ "soda": {
+ "status": "MATCH",
+ "mismatches": 0,
+ "parity_ci_lower": 0.9905,
+ "overall_confidence": 0.049,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_cases": 0,
+ "mutation_score": 1.0,
+ "mutation_total": 0,
+ "mutation_killed": 0,
+ "verification_score": 1.0,
+ "counterexample_repair_applied": false,
+ "equivalence_counterexamples": [],
+ "effective_confidence": 0.049,
+ "provider_factor": 1.0,
+ "real_llm_used": null,
+ "decision_score": 0.084,
+ "conversion_provider": "soda_cloud",
+ "conversion_notes": "Soda Cloud scan executed successfully. Command: soda contract verify (per-rule x19) -ds C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\soda\\soda_cloud\\data_source.yml -sc C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\soda\\soda_cloud\\soda_cloud.yml -p | Success: True | Return code: 0",
+ "execution_mode": "cloud",
+ "cloud_connected": true,
+ "cloud_scan_id": "",
+ "cloud_scan_url": "https://cloud.us.soda.io/o/c9e7e376-1da2-49c5-93cb-78c6d95273ee/datasets/5e60cafe-18fc-4d01-8390-0057b49d7765",
+ "conversion_artifact": " - failed_rows:\n name: ca_fop_symbol_present_but_not_required\n expression: fop_symbol_present > 0.0 AND fop_threshold_exceeded == 0.0 AND fop_exempt_proxy == 0.0 AND product_is_prepackaged_proxy > 0.0",
+ "conversion_lines": 3,
+ "failed_test_cases": []
+ }
+ }
+ },
+ {
+ "rule_name": "ca_fop_symbol_present_on_exempt_product",
+ "tag": "ca-fop-symbol-present-on-exempt-product",
+ "severity": "warning",
+ "condition": "fop_symbol_present > 0.0 && fop_exempt_proxy > 0.0 && product_is_prepackaged_proxy > 0.0",
+ "jurisdiction": "ca",
+ "profile_tags": [
+ "canada",
+ "hybrid"
+ ],
+ "regulatory_type": "guidance_proxy",
+ "legal_citation": "FDR B.01.350(5)-(15)",
+ "source_url": "https://laws-lois.justice.gc.ca/eng/regulations/C.R.C.,_c._870/section-B.01.350.html",
+ "effective_date": "2026-01-01",
+ "review_status": "draft",
+ "reviewer": "pending-mentor-review",
+ "required_fields": [
+ "fop_symbol_present",
+ "fop_exempt_proxy",
+ "product_is_prepackaged_proxy"
+ ],
+ "exemption_logic": "Proxy warning on symbol presence for exempt categories.",
+ "rule_notes": "Phase-1 Canada FOP exemption consistency rule.",
+ "rule_ir_hash": "4e274edaa3ca",
+ "condition_type": "compound_threshold_and",
+ "complexity": "medium",
+ "declarative_friendly": true,
+ "products_tested": 400,
+ "best_engine": "soda",
+ "selection_reason": "hybrid-close-declarative:explicit-hash-tie-break-odd->soda",
+ "declarative_tie_break_applied": true,
+ "recommendation": "Declarative-friendly rule; prefer dbt/soda for readability and operations.",
+ "engines": {
+ "python": {
+ "status": "MATCH",
+ "mismatches": 0,
+ "parity_ci_lower": 0.9905,
+ "overall_confidence": 0.0451,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_cases": 2,
+ "mutation_score": 1.0,
+ "mutation_total": 0,
+ "mutation_killed": 0,
+ "verification_score": 1.0,
+ "counterexample_repair_applied": false,
+ "equivalence_counterexamples": [],
+ "effective_confidence": 0.0451,
+ "provider_factor": 1.0,
+ "real_llm_used": true,
+ "decision_score": 0.1451,
+ "conversion_provider": "groq",
+ "conversion_notes": "Converted via Groq (openai/gpt-oss-120b).",
+ "execution_mode": "",
+ "cloud_connected": false,
+ "cloud_scan_id": "",
+ "cloud_scan_url": "",
+ "conversion_artifact": "def check_ca_fop_symbol_present_on_exempt_product(product: dict):\n \"\"\"\n Returns the rule tag if the product violates the rule:\n fop_symbol_present > 0.0 && fop_exempt_proxy > 0.0 && product_is_prepackaged_proxy > 0.0\n Otherwise returns None.\n \"\"\"\n tag = \"ca-fop-symbol-present-on-exempt-product\"\n\n # Helper to validate numeric fields\n def _is_valid_number(value):\n return isinstance(value, (int, float)) and not isinstance(value, bool)\n\n fop_symbol_present = product.get(\"fop_symbol_present\")\n fop_exempt_proxy = product.get(\"fop_exempt_proxy\")\n product_is_prepackaged_proxy = product.get(\"product_is_prepackaged_proxy\")\n\n # If any required field is missing or not numeric, rule does not apply\n if not (_is_valid_number(fop_symbol_present) and\n _is_valid_number(fop_exempt_proxy) and\n _is_valid_number(product_is_prepackaged_proxy)):\n return None\n\n if (fop_symbol_present > 0.0 and\n fop_exempt_proxy > 0.0 and\n product_is_prepackaged_proxy > 0.0):\n return tag\n\n return None",
+ "conversion_lines": 28,
+ "failed_test_cases": []
+ },
+ "dbt": {
+ "status": "MATCH",
+ "mismatches": 0,
+ "parity_ci_lower": 0.9905,
+ "overall_confidence": 0.049,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_cases": 0,
+ "mutation_score": 1.0,
+ "mutation_total": 0,
+ "mutation_killed": 0,
+ "verification_score": 1.0,
+ "counterexample_repair_applied": false,
+ "equivalence_counterexamples": [],
+ "effective_confidence": 0.049,
+ "provider_factor": 1.0,
+ "real_llm_used": null,
+ "decision_score": 0.084,
+ "conversion_provider": "dbt_core",
+ "conversion_notes": "dbt tests executed through dbt-core. Command: dbt debug + dbt run-operation count_violations (per-rule x19) --project-dir C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\dbt\\dbt_project --profiles-dir C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\dbt\\dbt_project | Success: True | Return code: 0",
+ "execution_mode": "local",
+ "cloud_connected": false,
+ "cloud_scan_id": "",
+ "cloud_scan_url": "",
+ "conversion_artifact": "SELECT product_id\nFROM {{ source('off_source', 'nutrition_table') }}\nWHERE fop_symbol_present > 0.0 AND fop_exempt_proxy > 0.0 AND product_is_prepackaged_proxy > 0.0",
+ "conversion_lines": 3,
+ "failed_test_cases": []
+ },
+ "soda": {
+ "status": "MATCH",
+ "mismatches": 0,
+ "parity_ci_lower": 0.9905,
+ "overall_confidence": 0.049,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_cases": 0,
+ "mutation_score": 1.0,
+ "mutation_total": 0,
+ "mutation_killed": 0,
+ "verification_score": 1.0,
+ "counterexample_repair_applied": false,
+ "equivalence_counterexamples": [],
+ "effective_confidence": 0.049,
+ "provider_factor": 1.0,
+ "real_llm_used": null,
+ "decision_score": 0.084,
+ "conversion_provider": "soda_cloud",
+ "conversion_notes": "Soda Cloud scan executed successfully. Command: soda contract verify (per-rule x19) -ds C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\soda\\soda_cloud\\data_source.yml -sc C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\soda\\soda_cloud\\soda_cloud.yml -p | Success: True | Return code: 0",
+ "execution_mode": "cloud",
+ "cloud_connected": true,
+ "cloud_scan_id": "",
+ "cloud_scan_url": "https://cloud.us.soda.io/o/c9e7e376-1da2-49c5-93cb-78c6d95273ee/datasets/5e60cafe-18fc-4d01-8390-0057b49d7765",
+ "conversion_artifact": " - failed_rows:\n name: ca_fop_symbol_present_on_exempt_product\n expression: fop_symbol_present > 0.0 AND fop_exempt_proxy > 0.0 AND product_is_prepackaged_proxy > 0.0",
+ "conversion_lines": 3,
+ "failed_test_cases": []
+ }
+ }
+ },
+ {
+ "rule_name": "carbohydrates_over_105g",
+ "tag": "carbohydrates-value-over-105g",
+ "severity": "warning",
+ "condition": "carbohydrates > 105",
+ "jurisdiction": "global",
+ "profile_tags": [
+ "global",
+ "hybrid"
+ ],
+ "regulatory_type": "off_internal",
+ "legal_citation": "",
+ "source_url": "",
+ "effective_date": "",
+ "review_status": "reviewed",
+ "reviewer": "prototype",
+ "required_fields": [],
+ "exemption_logic": "none",
+ "rule_notes": "OFF-derived global rule: carbohydrates_over_105g",
+ "rule_ir_hash": "7261087f016d",
+ "condition_type": "field_threshold",
+ "complexity": "simple",
+ "declarative_friendly": true,
+ "products_tested": 400,
+ "best_engine": "soda",
+ "selection_reason": "hybrid-close-declarative:explicit-hash-tie-break-odd->soda",
+ "declarative_tie_break_applied": true,
+ "recommendation": "Declarative-friendly rule; prefer dbt/soda for readability and operations.",
+ "engines": {
+ "python": {
+ "status": "MATCH",
+ "mismatches": 0,
+ "parity_ci_lower": 0.9905,
+ "overall_confidence": 0.9181,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_cases": 22,
+ "mutation_score": 1.0,
+ "mutation_total": 1,
+ "mutation_killed": 1,
+ "verification_score": 1.0,
+ "counterexample_repair_applied": false,
+ "equivalence_counterexamples": [],
+ "effective_confidence": 0.9181,
+ "provider_factor": 1.0,
+ "real_llm_used": true,
+ "decision_score": 1.0181,
+ "conversion_provider": "groq",
+ "conversion_notes": "Converted via Groq (openai/gpt-oss-120b).",
+ "execution_mode": "",
+ "cloud_connected": false,
+ "cloud_scan_id": "",
+ "cloud_scan_url": "",
+ "conversion_artifact": "def check_carbohydrates_over_105g(product: dict):\n \"\"\"\n Returns the tag 'carbohydrates-value-over-105g' if the product's\n 'carbohydrates' field is numeric and greater than 105.\n Otherwise returns None.\n \"\"\"\n tag = \"carbohydrates-value-over-105g\"\n value = product.get(\"carbohydrates\", None)\n\n # If the value is missing or not a number, do not flag a violation\n if value is None or not isinstance(value, (int, float)):\n return None\n\n # Check the threshold condition\n if value > 105:\n return tag\n\n return None",
+ "conversion_lines": 18,
+ "failed_test_cases": []
+ },
+ "dbt": {
+ "status": "MATCH",
+ "mismatches": 0,
+ "parity_ci_lower": 0.9905,
+ "overall_confidence": 0.9371,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_cases": 0,
+ "mutation_score": 1.0,
+ "mutation_total": 0,
+ "mutation_killed": 0,
+ "verification_score": 1.0,
+ "counterexample_repair_applied": false,
+ "equivalence_counterexamples": [],
+ "effective_confidence": 0.9371,
+ "provider_factor": 1.0,
+ "real_llm_used": null,
+ "decision_score": 0.9721,
+ "conversion_provider": "dbt_core",
+ "conversion_notes": "dbt tests executed through dbt-core. Command: dbt debug + dbt run-operation count_violations (per-rule x19) --project-dir C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\dbt\\dbt_project --profiles-dir C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\dbt\\dbt_project | Success: True | Return code: 0",
+ "execution_mode": "local",
+ "cloud_connected": false,
+ "cloud_scan_id": "",
+ "cloud_scan_url": "",
+ "conversion_artifact": "SELECT product_id\nFROM {{ source('off_source', 'nutrition_table') }}\nWHERE carbohydrates > 105",
+ "conversion_lines": 3,
+ "failed_test_cases": []
+ },
+ "soda": {
+ "status": "MATCH",
+ "mismatches": 0,
+ "parity_ci_lower": 0.9905,
+ "overall_confidence": 0.9371,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_cases": 0,
+ "mutation_score": 1.0,
+ "mutation_total": 0,
+ "mutation_killed": 0,
+ "verification_score": 1.0,
+ "counterexample_repair_applied": false,
+ "equivalence_counterexamples": [],
+ "effective_confidence": 0.9371,
+ "provider_factor": 1.0,
+ "real_llm_used": null,
+ "decision_score": 0.9721,
+ "conversion_provider": "soda_cloud",
+ "conversion_notes": "Soda Cloud scan executed successfully. Command: soda contract verify (per-rule x19) -ds C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\soda\\soda_cloud\\data_source.yml -sc C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\soda\\soda_cloud\\soda_cloud.yml -p | Success: True | Return code: 0",
+ "execution_mode": "cloud",
+ "cloud_connected": true,
+ "cloud_scan_id": "",
+ "cloud_scan_url": "https://cloud.us.soda.io/o/c9e7e376-1da2-49c5-93cb-78c6d95273ee/datasets/5e60cafe-18fc-4d01-8390-0057b49d7765",
+ "conversion_artifact": " - failed_rows:\n name: carbohydrates_over_105g\n expression: carbohydrates > 105",
+ "conversion_lines": 3,
+ "failed_test_cases": []
+ }
+ }
+ },
+ {
+ "rule_name": "energy_kcal_vs_kj",
+ "tag": "energy-value-in-kcal-greater-than-in-kj",
+ "severity": "error",
+ "condition": "energy_kcal > energy_kj",
+ "jurisdiction": "global",
+ "profile_tags": [
+ "global",
+ "hybrid"
+ ],
+ "regulatory_type": "off_internal",
+ "legal_citation": "",
+ "source_url": "",
+ "effective_date": "",
+ "review_status": "reviewed",
+ "reviewer": "prototype",
+ "required_fields": [],
+ "exemption_logic": "none",
+ "rule_notes": "OFF-derived global rule: energy_kcal_vs_kj",
+ "rule_ir_hash": "413d25898535",
+ "condition_type": "field_comparison",
+ "complexity": "simple",
+ "declarative_friendly": true,
+ "products_tested": 400,
+ "best_engine": "soda",
+ "selection_reason": "hybrid-close-declarative:explicit-hash-tie-break-odd->soda",
+ "declarative_tie_break_applied": true,
+ "recommendation": "Declarative-friendly rule; prefer dbt/soda for readability and operations.",
+ "engines": {
+ "python": {
+ "status": "MATCH",
+ "mismatches": 0,
+ "parity_ci_lower": 0.9905,
+ "overall_confidence": 0.049,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_cases": 23,
+ "mutation_score": 0.0,
+ "mutation_total": 1,
+ "mutation_killed": 0,
+ "verification_score": 0.0,
+ "counterexample_repair_applied": false,
+ "equivalence_counterexamples": [],
+ "effective_confidence": 0.049,
+ "provider_factor": 1.0,
+ "real_llm_used": true,
+ "decision_score": 0.099,
+ "conversion_provider": "groq",
+ "conversion_notes": "Converted via Groq (openai/gpt-oss-120b).",
+ "execution_mode": "",
+ "cloud_connected": false,
+ "cloud_scan_id": "",
+ "cloud_scan_url": "",
+ "conversion_artifact": "def check_energy_kcal_vs_kj(product):\n \"\"\"\n Returns the rule tag if energy_kcal > energy_kj.\n Returns None if any value is missing, None, empty/whitespace string, or non-numeric.\n \"\"\"\n tag = \"energy-value-in-kcal-greater-than-in-kj\"\n left = product.get(\"energy_kcal\")\n right = product.get(\"energy_kj\")\n\n # Missing or None values\n if left is None or right is None:\n return None\n\n # Empty or whitespace-only strings are considered missing for this rule\n if isinstance(left, str) and left.strip() == \"\":\n return None\n if isinstance(right, str) and right.strip() == \"\":\n return None\n\n # Non-numeric values\n if not isinstance(left, (int, float)):\n return None\n if not isinstance(right, (int, float)):\n return None\n\n if left > right:\n return tag\n return None",
+ "conversion_lines": 28,
+ "failed_test_cases": []
+ },
+ "dbt": {
+ "status": "MATCH",
+ "mismatches": 0,
+ "parity_ci_lower": 0.9905,
+ "overall_confidence": 0.049,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_cases": 0,
+ "mutation_score": 1.0,
+ "mutation_total": 0,
+ "mutation_killed": 0,
+ "verification_score": 1.0,
+ "counterexample_repair_applied": false,
+ "equivalence_counterexamples": [],
+ "effective_confidence": 0.049,
+ "provider_factor": 1.0,
+ "real_llm_used": null,
+ "decision_score": 0.084,
+ "conversion_provider": "dbt_core",
+ "conversion_notes": "dbt tests executed through dbt-core. Command: dbt debug + dbt run-operation count_violations (per-rule x19) --project-dir C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\dbt\\dbt_project --profiles-dir C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\dbt\\dbt_project | Success: True | Return code: 0",
+ "execution_mode": "local",
+ "cloud_connected": false,
+ "cloud_scan_id": "",
+ "cloud_scan_url": "",
+ "conversion_artifact": "SELECT product_id\nFROM {{ source('off_source', 'nutrition_table') }}\nWHERE energy_kcal > energy_kj",
+ "conversion_lines": 3,
+ "failed_test_cases": []
+ },
+ "soda": {
+ "status": "MATCH",
+ "mismatches": 0,
+ "parity_ci_lower": 0.9905,
+ "overall_confidence": 0.049,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_cases": 0,
+ "mutation_score": 1.0,
+ "mutation_total": 0,
+ "mutation_killed": 0,
+ "verification_score": 1.0,
+ "counterexample_repair_applied": false,
+ "equivalence_counterexamples": [],
+ "effective_confidence": 0.049,
+ "provider_factor": 1.0,
+ "real_llm_used": null,
+ "decision_score": 0.084,
+ "conversion_provider": "soda_cloud",
+ "conversion_notes": "Soda Cloud scan executed successfully. Command: soda contract verify (per-rule x19) -ds C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\soda\\soda_cloud\\data_source.yml -sc C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\soda\\soda_cloud\\soda_cloud.yml -p | Success: True | Return code: 0",
+ "execution_mode": "cloud",
+ "cloud_connected": true,
+ "cloud_scan_id": "",
+ "cloud_scan_url": "https://cloud.us.soda.io/o/c9e7e376-1da2-49c5-93cb-78c6d95273ee/datasets/5e60cafe-18fc-4d01-8390-0057b49d7765",
+ "conversion_artifact": " - failed_rows:\n name: energy_kcal_vs_kj\n expression: energy_kcal > energy_kj",
+ "conversion_lines": 3,
+ "failed_test_cases": []
+ }
+ }
+ },
+ {
+ "rule_name": "energy_kj_computed_mismatch_high",
+ "tag": "energy-value-in-kj-does-not-match-value-computed-from-other-nutrients-high",
+ "severity": "error",
+ "condition": "energy_kj_computed > (1.3 * energy_kj + 5.0)",
+ "jurisdiction": "global",
+ "profile_tags": [
+ "global",
+ "hybrid"
+ ],
+ "regulatory_type": "off_internal",
+ "legal_citation": "",
+ "source_url": "",
+ "effective_date": "",
+ "review_status": "reviewed",
+ "reviewer": "prototype",
+ "required_fields": [],
+ "exemption_logic": "none",
+ "rule_notes": "OFF-derived global rule: energy_kj_computed_mismatch_high",
+ "rule_ir_hash": "ac2e3831ada8",
+ "condition_type": "affine_field_comparison",
+ "complexity": "intricate",
+ "declarative_friendly": false,
+ "products_tested": 400,
+ "best_engine": "python",
+ "selection_reason": "hybrid-close-procedural:prefer-python",
+ "declarative_tie_break_applied": false,
+ "recommendation": "Procedural preference: rule is intricate (affine_field_comparison). Python migration is preferred under current evidence.",
+ "engines": {
+ "python": {
+ "status": "MATCH",
+ "mismatches": 0,
+ "parity_ci_lower": 0.9905,
+ "overall_confidence": 0.0446,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_cases": 22,
+ "mutation_score": 0.0,
+ "mutation_total": 3,
+ "mutation_killed": 0,
+ "verification_score": 0.0,
+ "counterexample_repair_applied": false,
+ "equivalence_counterexamples": [],
+ "effective_confidence": 0.0446,
+ "provider_factor": 1.0,
+ "real_llm_used": true,
+ "decision_score": 0.1296,
+ "conversion_provider": "groq",
+ "conversion_notes": "Converted via Groq (openai/gpt-oss-120b).",
+ "execution_mode": "",
+ "cloud_connected": false,
+ "cloud_scan_id": "",
+ "cloud_scan_url": "",
+ "conversion_artifact": "def check_energy_kj_computed_mismatch_high(product):\n \"\"\"\n Returns the rule tag if energy_kj_computed > (1.3 * energy_kj + 5.0),\n otherwise returns None. Missing or non\u2011numeric values also yield None.\n \"\"\"\n tag = \"energy-value-in-kj-does-not-match-value-computed-from-other-nutrients-high\"\n left = product.get(\"energy_kj_computed\")\n right = product.get(\"energy_kj\")\n\n # Missing values\n if left is None or right is None:\n return None\n\n # Non\u2011numeric values (exclude bool which is subclass of int)\n if isinstance(left, bool) or isinstance(right, bool):\n return None\n if not isinstance(left, (int, float)) or not isinstance(right, (int, float)):\n return None\n\n # Apply affine comparison\n if left > (1.3 * right + 5.0):\n return tag\n return None",
+ "conversion_lines": 23,
+ "failed_test_cases": []
+ },
+ "dbt": {
+ "status": "MATCH",
+ "mismatches": 0,
+ "parity_ci_lower": 0.9905,
+ "overall_confidence": 0.049,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_cases": 0,
+ "mutation_score": 1.0,
+ "mutation_total": 0,
+ "mutation_killed": 0,
+ "verification_score": 1.0,
+ "counterexample_repair_applied": false,
+ "equivalence_counterexamples": [],
+ "effective_confidence": 0.049,
+ "provider_factor": 1.0,
+ "real_llm_used": null,
+ "decision_score": 0.049,
+ "conversion_provider": "dbt_core",
+ "conversion_notes": "dbt tests executed through dbt-core. Command: dbt debug + dbt run-operation count_violations (per-rule x19) --project-dir C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\dbt\\dbt_project --profiles-dir C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\dbt\\dbt_project | Success: True | Return code: 0",
+ "execution_mode": "local",
+ "cloud_connected": false,
+ "cloud_scan_id": "",
+ "cloud_scan_url": "",
+ "conversion_artifact": "SELECT product_id\nFROM {{ source('off_source', 'nutrition_table') }}\nWHERE energy_kj_computed > (1.3 * energy_kj + 5.0)",
+ "conversion_lines": 3,
+ "failed_test_cases": []
+ },
+ "soda": {
+ "status": "MATCH",
+ "mismatches": 0,
+ "parity_ci_lower": 0.9905,
+ "overall_confidence": 0.049,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_cases": 0,
+ "mutation_score": 1.0,
+ "mutation_total": 0,
+ "mutation_killed": 0,
+ "verification_score": 1.0,
+ "counterexample_repair_applied": false,
+ "equivalence_counterexamples": [],
+ "effective_confidence": 0.049,
+ "provider_factor": 1.0,
+ "real_llm_used": null,
+ "decision_score": 0.049,
+ "conversion_provider": "soda_cloud",
+ "conversion_notes": "Soda Cloud scan executed successfully. Command: soda contract verify (per-rule x19) -ds C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\soda\\soda_cloud\\data_source.yml -sc C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\soda\\soda_cloud\\soda_cloud.yml -p | Success: True | Return code: 0",
+ "execution_mode": "cloud",
+ "cloud_connected": true,
+ "cloud_scan_id": "",
+ "cloud_scan_url": "https://cloud.us.soda.io/o/c9e7e376-1da2-49c5-93cb-78c6d95273ee/datasets/5e60cafe-18fc-4d01-8390-0057b49d7765",
+ "conversion_artifact": " - failed_rows:\n name: energy_kj_computed_mismatch_high\n expression: energy_kj_computed > (1.3 * energy_kj + 5.0)",
+ "conversion_lines": 3,
+ "failed_test_cases": []
+ }
+ }
+ },
+ {
+ "rule_name": "energy_kj_computed_mismatch_low",
+ "tag": "energy-value-in-kj-does-not-match-value-computed-from-other-nutrients-low",
+ "severity": "error",
+ "condition": "energy_kj_computed < (0.7 * energy_kj - 5.0)",
+ "jurisdiction": "global",
+ "profile_tags": [
+ "global",
+ "hybrid"
+ ],
+ "regulatory_type": "off_internal",
+ "legal_citation": "",
+ "source_url": "",
+ "effective_date": "",
+ "review_status": "reviewed",
+ "reviewer": "prototype",
+ "required_fields": [],
+ "exemption_logic": "none",
+ "rule_notes": "OFF-derived global rule: energy_kj_computed_mismatch_low",
+ "rule_ir_hash": "2845fdb42a7e",
+ "condition_type": "affine_field_comparison",
+ "complexity": "intricate",
+ "declarative_friendly": false,
+ "products_tested": 400,
+ "best_engine": "python",
+ "selection_reason": "hybrid-close-procedural:prefer-python",
+ "declarative_tie_break_applied": false,
+ "recommendation": "Procedural preference: rule is intricate (affine_field_comparison). Python migration is preferred under current evidence.",
+ "engines": {
+ "python": {
+ "status": "MATCH",
+ "mismatches": 0,
+ "parity_ci_lower": 0.9905,
+ "overall_confidence": 0.0446,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_cases": 22,
+ "mutation_score": 1.0,
+ "mutation_total": 2,
+ "mutation_killed": 2,
+ "verification_score": 1.0,
+ "counterexample_repair_applied": false,
+ "equivalence_counterexamples": [],
+ "effective_confidence": 0.0446,
+ "provider_factor": 1.0,
+ "real_llm_used": true,
+ "decision_score": 0.1796,
+ "conversion_provider": "groq",
+ "conversion_notes": "Converted via Groq (openai/gpt-oss-120b).",
+ "execution_mode": "",
+ "cloud_connected": false,
+ "cloud_scan_id": "",
+ "cloud_scan_url": "",
+ "conversion_artifact": "def check_energy_kj_computed_mismatch_low(product):\n tag = \"energy-value-in-kj-does-not-match-value-computed-from-other-nutrients-low\"\n # missing_field rule for the whole input\n if product is None or (isinstance(product, str) and product.strip() == \"\"):\n return tag\n if not isinstance(product, dict):\n return None\n left = product.get(\"energy_kj_computed\")\n right = product.get(\"energy_kj\")\n # field_comparison rule: missing or non-numeric values yield None\n if left is None or right is None:\n return None\n try:\n left_val = float(left)\n right_val = float(right)\n except (TypeError, ValueError):\n return None\n if left_val < (0.7 * right_val - 5.0):\n return tag\n return None",
+ "conversion_lines": 20,
+ "failed_test_cases": []
+ },
+ "dbt": {
+ "status": "MATCH",
+ "mismatches": 0,
+ "parity_ci_lower": 0.9905,
+ "overall_confidence": 0.049,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_cases": 0,
+ "mutation_score": 1.0,
+ "mutation_total": 0,
+ "mutation_killed": 0,
+ "verification_score": 1.0,
+ "counterexample_repair_applied": false,
+ "equivalence_counterexamples": [],
+ "effective_confidence": 0.049,
+ "provider_factor": 1.0,
+ "real_llm_used": null,
+ "decision_score": 0.049,
+ "conversion_provider": "dbt_core",
+ "conversion_notes": "dbt tests executed through dbt-core. Command: dbt debug + dbt run-operation count_violations (per-rule x19) --project-dir C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\dbt\\dbt_project --profiles-dir C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\dbt\\dbt_project | Success: True | Return code: 0",
+ "execution_mode": "local",
+ "cloud_connected": false,
+ "cloud_scan_id": "",
+ "cloud_scan_url": "",
+ "conversion_artifact": "SELECT product_id\nFROM {{ source('off_source', 'nutrition_table') }}\nWHERE energy_kj_computed < (0.7 * energy_kj - 5.0)",
+ "conversion_lines": 3,
+ "failed_test_cases": []
+ },
+ "soda": {
+ "status": "MATCH",
+ "mismatches": 0,
+ "parity_ci_lower": 0.9905,
+ "overall_confidence": 0.049,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_cases": 0,
+ "mutation_score": 1.0,
+ "mutation_total": 0,
+ "mutation_killed": 0,
+ "verification_score": 1.0,
+ "counterexample_repair_applied": false,
+ "equivalence_counterexamples": [],
+ "effective_confidence": 0.049,
+ "provider_factor": 1.0,
+ "real_llm_used": null,
+ "decision_score": 0.049,
+ "conversion_provider": "soda_cloud",
+ "conversion_notes": "Soda Cloud scan executed successfully. Command: soda contract verify (per-rule x19) -ds C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\soda\\soda_cloud\\data_source.yml -sc C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\soda\\soda_cloud\\soda_cloud.yml -p | Success: True | Return code: 0",
+ "execution_mode": "cloud",
+ "cloud_connected": true,
+ "cloud_scan_id": "",
+ "cloud_scan_url": "https://cloud.us.soda.io/o/c9e7e376-1da2-49c5-93cb-78c6d95273ee/datasets/5e60cafe-18fc-4d01-8390-0057b49d7765",
+ "conversion_artifact": " - failed_rows:\n name: energy_kj_computed_mismatch_low\n expression: energy_kj_computed < (0.7 * energy_kj - 5.0)",
+ "conversion_lines": 3,
+ "failed_test_cases": []
+ }
+ }
+ },
+ {
+ "rule_name": "energy_kj_mismatch_high",
+ "tag": "energy-value-in-kcal-does-not-match-value-in-kj-high",
+ "severity": "error",
+ "condition": "energy_kj > (4.7 * energy_kcal + 2.0)",
+ "jurisdiction": "global",
+ "profile_tags": [
+ "global",
+ "hybrid"
+ ],
+ "regulatory_type": "off_internal",
+ "legal_citation": "",
+ "source_url": "",
+ "effective_date": "",
+ "review_status": "reviewed",
+ "reviewer": "prototype",
+ "required_fields": [],
+ "exemption_logic": "none",
+ "rule_notes": "OFF-derived global rule: energy_kj_mismatch_high",
+ "rule_ir_hash": "13c3c72ed774",
+ "condition_type": "affine_field_comparison",
+ "complexity": "intricate",
+ "declarative_friendly": false,
+ "products_tested": 400,
+ "best_engine": "python",
+ "selection_reason": "hybrid-close-procedural:prefer-python",
+ "declarative_tie_break_applied": false,
+ "recommendation": "Procedural preference: rule is intricate (affine_field_comparison). Python migration is preferred under current evidence.",
+ "engines": {
+ "python": {
+ "status": "MATCH",
+ "mismatches": 0,
+ "parity_ci_lower": 0.9905,
+ "overall_confidence": 0.0446,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_cases": 22,
+ "mutation_score": 0.0,
+ "mutation_total": 3,
+ "mutation_killed": 0,
+ "verification_score": 0.0,
+ "counterexample_repair_applied": false,
+ "equivalence_counterexamples": [],
+ "effective_confidence": 0.0446,
+ "provider_factor": 1.0,
+ "real_llm_used": true,
+ "decision_score": 0.1296,
+ "conversion_provider": "groq",
+ "conversion_notes": "Converted via Groq (openai/gpt-oss-120b).",
+ "execution_mode": "",
+ "cloud_connected": false,
+ "cloud_scan_id": "",
+ "cloud_scan_url": "",
+ "conversion_artifact": "def check_energy_kj_mismatch_high(product):\n \"\"\"\n Returns the rule tag if energy_kj > (4.7 * energy_kcal + 2.0), otherwise None.\n Missing or non-numeric values result in None.\n \"\"\"\n tag = \"energy-value-in-kcal-does-not-match-value-in-kj-high\"\n left = product.get(\"energy_kj\")\n right = product.get(\"energy_kcal\")\n\n # Missing values\n if left is None or right is None:\n return None\n\n # Non-numeric values\n if not isinstance(left, (int, float)) or not isinstance(right, (int, float)):\n return None\n\n if left > (4.7 * right + 2.0):\n return tag\n return None",
+ "conversion_lines": 20,
+ "failed_test_cases": []
+ },
+ "dbt": {
+ "status": "MATCH",
+ "mismatches": 0,
+ "parity_ci_lower": 0.9905,
+ "overall_confidence": 0.049,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_cases": 0,
+ "mutation_score": 1.0,
+ "mutation_total": 0,
+ "mutation_killed": 0,
+ "verification_score": 1.0,
+ "counterexample_repair_applied": false,
+ "equivalence_counterexamples": [],
+ "effective_confidence": 0.049,
+ "provider_factor": 1.0,
+ "real_llm_used": null,
+ "decision_score": 0.049,
+ "conversion_provider": "dbt_core",
+ "conversion_notes": "dbt tests executed through dbt-core. Command: dbt debug + dbt run-operation count_violations (per-rule x19) --project-dir C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\dbt\\dbt_project --profiles-dir C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\dbt\\dbt_project | Success: True | Return code: 0",
+ "execution_mode": "local",
+ "cloud_connected": false,
+ "cloud_scan_id": "",
+ "cloud_scan_url": "",
+ "conversion_artifact": "SELECT product_id\nFROM {{ source('off_source', 'nutrition_table') }}\nWHERE energy_kj > (4.7 * energy_kcal + 2.0)",
+ "conversion_lines": 3,
+ "failed_test_cases": []
+ },
+ "soda": {
+ "status": "MATCH",
+ "mismatches": 0,
+ "parity_ci_lower": 0.9905,
+ "overall_confidence": 0.049,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_cases": 0,
+ "mutation_score": 1.0,
+ "mutation_total": 0,
+ "mutation_killed": 0,
+ "verification_score": 1.0,
+ "counterexample_repair_applied": false,
+ "equivalence_counterexamples": [],
+ "effective_confidence": 0.049,
+ "provider_factor": 1.0,
+ "real_llm_used": null,
+ "decision_score": 0.049,
+ "conversion_provider": "soda_cloud",
+ "conversion_notes": "Soda Cloud scan executed successfully. Command: soda contract verify (per-rule x19) -ds C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\soda\\soda_cloud\\data_source.yml -sc C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\soda\\soda_cloud\\soda_cloud.yml -p | Success: True | Return code: 0",
+ "execution_mode": "cloud",
+ "cloud_connected": true,
+ "cloud_scan_id": "",
+ "cloud_scan_url": "https://cloud.us.soda.io/o/c9e7e376-1da2-49c5-93cb-78c6d95273ee/datasets/5e60cafe-18fc-4d01-8390-0057b49d7765",
+ "conversion_artifact": " - failed_rows:\n name: energy_kj_mismatch_high\n expression: energy_kj > (4.7 * energy_kcal + 2.0)",
+ "conversion_lines": 3,
+ "failed_test_cases": []
+ }
+ }
+ },
+ {
+ "rule_name": "energy_kj_mismatch_low",
+ "tag": "energy-value-in-kcal-does-not-match-value-in-kj-low",
+ "severity": "error",
+ "condition": "energy_kj < (3.7 * energy_kcal - 2.0)",
+ "jurisdiction": "global",
+ "profile_tags": [
+ "global",
+ "hybrid"
+ ],
+ "regulatory_type": "off_internal",
+ "legal_citation": "",
+ "source_url": "",
+ "effective_date": "",
+ "review_status": "reviewed",
+ "reviewer": "prototype",
+ "required_fields": [],
+ "exemption_logic": "none",
+ "rule_notes": "OFF-derived global rule: energy_kj_mismatch_low",
+ "rule_ir_hash": "5a7e9e033cc8",
+ "condition_type": "affine_field_comparison",
+ "complexity": "intricate",
+ "declarative_friendly": false,
+ "products_tested": 400,
+ "best_engine": "python",
+ "selection_reason": "hybrid-close-procedural:prefer-python",
+ "declarative_tie_break_applied": false,
+ "recommendation": "Procedural preference: rule is intricate (affine_field_comparison). Python migration is preferred under current evidence.",
+ "engines": {
+ "python": {
+ "status": "MATCH",
+ "mismatches": 0,
+ "parity_ci_lower": 0.9905,
+ "overall_confidence": 0.0446,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_cases": 22,
+ "mutation_score": 0.5,
+ "mutation_total": 2,
+ "mutation_killed": 1,
+ "verification_score": 0.5,
+ "counterexample_repair_applied": false,
+ "equivalence_counterexamples": [],
+ "effective_confidence": 0.0446,
+ "provider_factor": 1.0,
+ "real_llm_used": true,
+ "decision_score": 0.1546,
+ "conversion_provider": "groq",
+ "conversion_notes": "Converted via Groq (openai/gpt-oss-120b).",
+ "execution_mode": "",
+ "cloud_connected": false,
+ "cloud_scan_id": "",
+ "cloud_scan_url": "",
+ "conversion_artifact": "def check_energy_kj_mismatch_low(product):\n \"\"\"\n Returns the rule tag if energy_kj is less than (3.7 * energy_kcal - 2.0).\n Returns None for missing or non-numeric values or when the condition is false.\n \"\"\"\n tag = \"energy-value-in-kcal-does-not-match-value-in-kj-low\"\n left = product.get(\"energy_kj\")\n right = product.get(\"energy_kcal\")\n\n # Missing values\n if left is None or right is None:\n return None\n\n # Convert to float, treat conversion failures as non-numeric\n try:\n left_val = float(left)\n right_val = float(right)\n except (TypeError, ValueError):\n return None\n\n # Apply affine comparison\n if left_val < (3.7 * right_val - 2.0):\n return tag\n return None",
+ "conversion_lines": 24,
+ "failed_test_cases": []
+ },
+ "dbt": {
+ "status": "MATCH",
+ "mismatches": 0,
+ "parity_ci_lower": 0.9905,
+ "overall_confidence": 0.049,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_cases": 0,
+ "mutation_score": 1.0,
+ "mutation_total": 0,
+ "mutation_killed": 0,
+ "verification_score": 1.0,
+ "counterexample_repair_applied": false,
+ "equivalence_counterexamples": [],
+ "effective_confidence": 0.049,
+ "provider_factor": 1.0,
+ "real_llm_used": null,
+ "decision_score": 0.049,
+ "conversion_provider": "dbt_core",
+ "conversion_notes": "dbt tests executed through dbt-core. Command: dbt debug + dbt run-operation count_violations (per-rule x19) --project-dir C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\dbt\\dbt_project --profiles-dir C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\dbt\\dbt_project | Success: True | Return code: 0",
+ "execution_mode": "local",
+ "cloud_connected": false,
+ "cloud_scan_id": "",
+ "cloud_scan_url": "",
+ "conversion_artifact": "SELECT product_id\nFROM {{ source('off_source', 'nutrition_table') }}\nWHERE energy_kj < (3.7 * energy_kcal - 2.0)",
+ "conversion_lines": 3,
+ "failed_test_cases": []
+ },
+ "soda": {
+ "status": "MATCH",
+ "mismatches": 0,
+ "parity_ci_lower": 0.9905,
+ "overall_confidence": 0.049,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_cases": 0,
+ "mutation_score": 1.0,
+ "mutation_total": 0,
+ "mutation_killed": 0,
+ "verification_score": 1.0,
+ "counterexample_repair_applied": false,
+ "equivalence_counterexamples": [],
+ "effective_confidence": 0.049,
+ "provider_factor": 1.0,
+ "real_llm_used": null,
+ "decision_score": 0.049,
+ "conversion_provider": "soda_cloud",
+ "conversion_notes": "Soda Cloud scan executed successfully. Command: soda contract verify (per-rule x19) -ds C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\soda\\soda_cloud\\data_source.yml -sc C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\soda\\soda_cloud\\soda_cloud.yml -p | Success: True | Return code: 0",
+ "execution_mode": "cloud",
+ "cloud_connected": true,
+ "cloud_scan_id": "",
+ "cloud_scan_url": "https://cloud.us.soda.io/o/c9e7e376-1da2-49c5-93cb-78c6d95273ee/datasets/5e60cafe-18fc-4d01-8390-0057b49d7765",
+ "conversion_artifact": " - failed_rows:\n name: energy_kj_mismatch_low\n expression: energy_kj < (3.7 * energy_kcal - 2.0)",
+ "conversion_lines": 3,
+ "failed_test_cases": []
+ }
+ }
+ },
+ {
+ "rule_name": "energy_kj_over_3911",
+ "tag": "value-over-3911-energy",
+ "severity": "error",
+ "condition": "energy_kj > 3911",
+ "jurisdiction": "global",
+ "profile_tags": [
+ "global",
+ "hybrid"
+ ],
+ "regulatory_type": "off_internal",
+ "legal_citation": "",
+ "source_url": "",
+ "effective_date": "",
+ "review_status": "reviewed",
+ "reviewer": "prototype",
+ "required_fields": [],
+ "exemption_logic": "none",
+ "rule_notes": "OFF-derived global rule: energy_kj_over_3911",
+ "rule_ir_hash": "abd124f391c9",
+ "condition_type": "field_threshold",
+ "complexity": "simple",
+ "declarative_friendly": true,
+ "products_tested": 400,
+ "best_engine": "soda",
+ "selection_reason": "hybrid-close-declarative:explicit-hash-tie-break-odd->soda",
+ "declarative_tie_break_applied": true,
+ "recommendation": "Declarative-friendly rule; prefer dbt/soda for readability and operations.",
+ "engines": {
+ "python": {
+ "status": "MATCH",
+ "mismatches": 0,
+ "parity_ci_lower": 0.9905,
+ "overall_confidence": 0.8599,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_cases": 22,
+ "mutation_score": 0.0,
+ "mutation_total": 1,
+ "mutation_killed": 0,
+ "verification_score": 0.0,
+ "counterexample_repair_applied": false,
+ "equivalence_counterexamples": [],
+ "effective_confidence": 0.8599,
+ "provider_factor": 1.0,
+ "real_llm_used": true,
+ "decision_score": 0.9099,
+ "conversion_provider": "groq",
+ "conversion_notes": "Converted via Groq (openai/gpt-oss-120b).",
+ "execution_mode": "",
+ "cloud_connected": false,
+ "cloud_scan_id": "",
+ "cloud_scan_url": "",
+ "conversion_artifact": "def check_energy_kj_over_3911(product):\n \"\"\"\n Returns the tag 'value-over-3911-energy' if product['energy_kj'] > 3911.\n Returns None for missing, None, empty, whitespace-only, or non-numeric values.\n \"\"\"\n tag = \"value-over-3911-energy\"\n value = product.get(\"energy_kj\", None)\n\n # Missing or None\n if value is None:\n return None\n\n # Empty or whitespace-only strings (treated as missing for this rule)\n if isinstance(value, str) and value.strip() == \"\":\n return None\n\n # Non-numeric values\n if not isinstance(value, (int, float)) or isinstance(value, bool):\n return None\n\n # Apply threshold condition\n if value > 3911:\n return tag\n return None",
+ "conversion_lines": 24,
+ "failed_test_cases": []
+ },
+ "dbt": {
+ "status": "MATCH",
+ "mismatches": 0,
+ "parity_ci_lower": 0.9905,
+ "overall_confidence": 0.8776,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_cases": 0,
+ "mutation_score": 1.0,
+ "mutation_total": 0,
+ "mutation_killed": 0,
+ "verification_score": 1.0,
+ "counterexample_repair_applied": false,
+ "equivalence_counterexamples": [],
+ "effective_confidence": 0.8776,
+ "provider_factor": 1.0,
+ "real_llm_used": null,
+ "decision_score": 0.9126,
+ "conversion_provider": "dbt_core",
+ "conversion_notes": "dbt tests executed through dbt-core. Command: dbt debug + dbt run-operation count_violations (per-rule x19) --project-dir C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\dbt\\dbt_project --profiles-dir C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\dbt\\dbt_project | Success: True | Return code: 0",
+ "execution_mode": "local",
+ "cloud_connected": false,
+ "cloud_scan_id": "",
+ "cloud_scan_url": "",
+ "conversion_artifact": "SELECT product_id\nFROM {{ source('off_source', 'nutrition_table') }}\nWHERE energy_kj > 3911",
+ "conversion_lines": 3,
+ "failed_test_cases": []
+ },
+ "soda": {
+ "status": "MATCH",
+ "mismatches": 0,
+ "parity_ci_lower": 0.9905,
+ "overall_confidence": 0.8776,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_cases": 0,
+ "mutation_score": 1.0,
+ "mutation_total": 0,
+ "mutation_killed": 0,
+ "verification_score": 1.0,
+ "counterexample_repair_applied": false,
+ "equivalence_counterexamples": [],
+ "effective_confidence": 0.8776,
+ "provider_factor": 1.0,
+ "real_llm_used": null,
+ "decision_score": 0.9126,
+ "conversion_provider": "soda_cloud",
+ "conversion_notes": "Soda Cloud scan executed successfully. Command: soda contract verify (per-rule x19) -ds C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\soda\\soda_cloud\\data_source.yml -sc C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\soda\\soda_cloud\\soda_cloud.yml -p | Success: True | Return code: 0",
+ "execution_mode": "cloud",
+ "cloud_connected": true,
+ "cloud_scan_id": "",
+ "cloud_scan_url": "https://cloud.us.soda.io/o/c9e7e376-1da2-49c5-93cb-78c6d95273ee/datasets/5e60cafe-18fc-4d01-8390-0057b49d7765",
+ "conversion_artifact": " - failed_rows:\n name: energy_kj_over_3911\n expression: energy_kj > 3911",
+ "conversion_lines": 3,
+ "failed_test_cases": []
+ }
+ }
+ },
+ {
+ "rule_name": "fat_over_105g",
+ "tag": "fat-value-over-105g",
+ "severity": "warning",
+ "condition": "fat > 105",
+ "jurisdiction": "global",
+ "profile_tags": [
+ "global",
+ "hybrid"
+ ],
+ "regulatory_type": "off_internal",
+ "legal_citation": "",
+ "source_url": "",
+ "effective_date": "",
+ "review_status": "reviewed",
+ "reviewer": "prototype",
+ "required_fields": [],
+ "exemption_logic": "none",
+ "rule_notes": "OFF-derived global rule: fat_over_105g",
+ "rule_ir_hash": "c6f7c59ce9c9",
+ "condition_type": "field_threshold",
+ "complexity": "simple",
+ "declarative_friendly": true,
+ "products_tested": 400,
+ "best_engine": "dbt",
+ "selection_reason": "hybrid-close-declarative:explicit-hash-tie-break-even->dbt",
+ "declarative_tie_break_applied": true,
+ "recommendation": "Declarative-friendly rule; prefer dbt/soda for readability and operations.",
+ "engines": {
+ "python": {
+ "status": "MATCH",
+ "mismatches": 0,
+ "parity_ci_lower": 0.9905,
+ "overall_confidence": 0.6888,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_cases": 22,
+ "mutation_score": 1.0,
+ "mutation_total": 1,
+ "mutation_killed": 1,
+ "verification_score": 1.0,
+ "counterexample_repair_applied": false,
+ "equivalence_counterexamples": [],
+ "effective_confidence": 0.6888,
+ "provider_factor": 1.0,
+ "real_llm_used": true,
+ "decision_score": 0.7888,
+ "conversion_provider": "groq",
+ "conversion_notes": "Converted via Groq (openai/gpt-oss-120b).",
+ "execution_mode": "",
+ "cloud_connected": false,
+ "cloud_scan_id": "",
+ "cloud_scan_url": "",
+ "conversion_artifact": "def check_fat_over_105g(product):\n \"\"\"\n Returns the tag 'fat-value-over-105g' if the product's 'fat' field\n exceeds 105. Returns None for missing, empty, whitespace-only,\n or non-numeric values, or when the condition is not met.\n \"\"\"\n tag = \"fat-value-over-105g\"\n value = product.get(\"fat\")\n\n # Missing field or None\n if value is None:\n return None\n\n # Non-numeric values (including strings, bools, etc.)\n if not isinstance(value, (int, float)):\n return None\n\n # Apply the threshold condition\n if value > 105:\n return tag\n\n return None",
+ "conversion_lines": 22,
+ "failed_test_cases": []
+ },
+ "dbt": {
+ "status": "MATCH",
+ "mismatches": 0,
+ "parity_ci_lower": 0.9905,
+ "overall_confidence": 0.703,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_cases": 0,
+ "mutation_score": 1.0,
+ "mutation_total": 0,
+ "mutation_killed": 0,
+ "verification_score": 1.0,
+ "counterexample_repair_applied": false,
+ "equivalence_counterexamples": [],
+ "effective_confidence": 0.703,
+ "provider_factor": 1.0,
+ "real_llm_used": null,
+ "decision_score": 0.738,
+ "conversion_provider": "dbt_core",
+ "conversion_notes": "dbt tests executed through dbt-core. Command: dbt debug + dbt run-operation count_violations (per-rule x19) --project-dir C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\dbt\\dbt_project --profiles-dir C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\dbt\\dbt_project | Success: True | Return code: 0",
+ "execution_mode": "local",
+ "cloud_connected": false,
+ "cloud_scan_id": "",
+ "cloud_scan_url": "",
+ "conversion_artifact": "SELECT product_id\nFROM {{ source('off_source', 'nutrition_table') }}\nWHERE fat > 105",
+ "conversion_lines": 3,
+ "failed_test_cases": []
+ },
+ "soda": {
+ "status": "MATCH",
+ "mismatches": 0,
+ "parity_ci_lower": 0.9905,
+ "overall_confidence": 0.703,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_cases": 0,
+ "mutation_score": 1.0,
+ "mutation_total": 0,
+ "mutation_killed": 0,
+ "verification_score": 1.0,
+ "counterexample_repair_applied": false,
+ "equivalence_counterexamples": [],
+ "effective_confidence": 0.703,
+ "provider_factor": 1.0,
+ "real_llm_used": null,
+ "decision_score": 0.738,
+ "conversion_provider": "soda_cloud",
+ "conversion_notes": "Soda Cloud scan executed successfully. Command: soda contract verify (per-rule x19) -ds C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\soda\\soda_cloud\\data_source.yml -sc C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\soda\\soda_cloud\\soda_cloud.yml -p | Success: True | Return code: 0",
+ "execution_mode": "cloud",
+ "cloud_connected": true,
+ "cloud_scan_id": "",
+ "cloud_scan_url": "https://cloud.us.soda.io/o/c9e7e376-1da2-49c5-93cb-78c6d95273ee/datasets/5e60cafe-18fc-4d01-8390-0057b49d7765",
+ "conversion_artifact": " - failed_rows:\n name: fat_over_105g\n expression: fat > 105",
+ "conversion_lines": 3,
+ "failed_test_cases": []
+ }
+ }
+ },
+ {
+ "rule_name": "main_language_code_missing",
+ "tag": "main-language-code-missing",
+ "severity": "bug",
+ "condition": "missing(lc)",
+ "jurisdiction": "ca",
+ "profile_tags": [
+ "canada",
+ "hybrid"
+ ],
+ "regulatory_type": "statutory",
+ "legal_citation": "SFCR 206(1); FDR B.01.012(2)",
+ "source_url": "https://laws-lois.justice.gc.ca/eng/regulations/SOR-2018-108/section-206.html",
+ "effective_date": "2019-01-15",
+ "review_status": "draft",
+ "reviewer": "pending-mentor-review",
+ "required_fields": [
+ "lc",
+ "lang",
+ "language_code"
+ ],
+ "exemption_logic": "Not all products require bilingual labels; this prototype uses a conservative language-presence proxy.",
+ "rule_notes": "Canada pack: proxy check for missing primary language code in label metadata.",
+ "rule_ir_hash": "d6c3ad98509c",
+ "condition_type": "missing_field",
+ "complexity": "simple",
+ "declarative_friendly": true,
+ "products_tested": 400,
+ "best_engine": "dbt",
+ "selection_reason": "hybrid-close-declarative:explicit-hash-tie-break-even->dbt",
+ "declarative_tie_break_applied": true,
+ "recommendation": "Declarative-friendly rule; prefer dbt/soda for readability and operations.",
+ "engines": {
+ "python": {
+ "status": "MATCH",
+ "mismatches": 0,
+ "parity_ci_lower": 0.9905,
+ "overall_confidence": 0.0466,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_cases": 5,
+ "mutation_score": 1.0,
+ "mutation_total": 0,
+ "mutation_killed": 0,
+ "verification_score": 1.0,
+ "counterexample_repair_applied": false,
+ "equivalence_counterexamples": [],
+ "effective_confidence": 0.0466,
+ "provider_factor": 1.0,
+ "real_llm_used": true,
+ "decision_score": 0.1466,
+ "conversion_provider": "groq",
+ "conversion_notes": "Converted via Groq (openai/gpt-oss-120b).",
+ "execution_mode": "",
+ "cloud_connected": false,
+ "cloud_scan_id": "",
+ "cloud_scan_url": "",
+ "conversion_artifact": "def check_main_language_code_missing(product: dict) -> str | None:\n \"\"\"\n Returns the tag 'main-language-code-missing' if the 'lc' field is missing,\n None, empty, or contains only whitespace. Otherwise returns None.\n \"\"\"\n tag = \"main-language-code-missing\"\n lc = product.get(\"lc\")\n if lc is None:\n return tag\n if isinstance(lc, str) and lc.strip() == \"\":\n return tag\n return None",
+ "conversion_lines": 12,
+ "failed_test_cases": []
+ },
+ "dbt": {
+ "status": "MATCH",
+ "mismatches": 0,
+ "parity_ci_lower": 0.9905,
+ "overall_confidence": 0.049,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_cases": 0,
+ "mutation_score": 1.0,
+ "mutation_total": 0,
+ "mutation_killed": 0,
+ "verification_score": 1.0,
+ "counterexample_repair_applied": false,
+ "equivalence_counterexamples": [],
+ "effective_confidence": 0.049,
+ "provider_factor": 1.0,
+ "real_llm_used": null,
+ "decision_score": 0.084,
+ "conversion_provider": "dbt_core",
+ "conversion_notes": "dbt tests executed through dbt-core. Command: dbt debug + dbt run-operation count_violations (per-rule x19) --project-dir C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\dbt\\dbt_project --profiles-dir C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\dbt\\dbt_project | Success: True | Return code: 0",
+ "execution_mode": "local",
+ "cloud_connected": false,
+ "cloud_scan_id": "",
+ "cloud_scan_url": "",
+ "conversion_artifact": "SELECT product_id\nFROM {{ source('off_source', 'nutrition_table') }}\nWHERE lc IS NULL OR TRIM(lc) = ''",
+ "conversion_lines": 3,
+ "failed_test_cases": []
+ },
+ "soda": {
+ "status": "MATCH",
+ "mismatches": 0,
+ "parity_ci_lower": 0.9905,
+ "overall_confidence": 0.049,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_cases": 0,
+ "mutation_score": 1.0,
+ "mutation_total": 0,
+ "mutation_killed": 0,
+ "verification_score": 1.0,
+ "counterexample_repair_applied": false,
+ "equivalence_counterexamples": [],
+ "effective_confidence": 0.049,
+ "provider_factor": 1.0,
+ "real_llm_used": null,
+ "decision_score": 0.084,
+ "conversion_provider": "soda_cloud",
+ "conversion_notes": "Soda Cloud scan executed successfully. Command: soda contract verify (per-rule x19) -ds C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\soda\\soda_cloud\\data_source.yml -sc C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\soda\\soda_cloud\\soda_cloud.yml -p | Success: True | Return code: 0",
+ "execution_mode": "cloud",
+ "cloud_connected": true,
+ "cloud_scan_id": "",
+ "cloud_scan_url": "https://cloud.us.soda.io/o/c9e7e376-1da2-49c5-93cb-78c6d95273ee/datasets/5e60cafe-18fc-4d01-8390-0057b49d7765",
+ "conversion_artifact": " - failed_rows:\n name: main_language_code_missing\n expression: lc IS NULL OR TRIM(lc) = ''",
+ "conversion_lines": 3,
+ "failed_test_cases": []
+ }
+ }
+ },
+ {
+ "rule_name": "main_language_missing",
+ "tag": "main-language-missing",
+ "severity": "bug",
+ "condition": "missing(lang)",
+ "jurisdiction": "ca",
+ "profile_tags": [
+ "canada",
+ "hybrid"
+ ],
+ "regulatory_type": "statutory",
+ "legal_citation": "SFCR 206(1); FDR B.01.012(2)",
+ "source_url": "https://laws-lois.justice.gc.ca/eng/regulations/C.R.C.,_c._870/section-B.01.012.html",
+ "effective_date": "2019-01-15",
+ "review_status": "draft",
+ "reviewer": "pending-mentor-review",
+ "required_fields": [
+ "lang",
+ "language_code",
+ "lc"
+ ],
+ "exemption_logic": "Prototype proxy only; legal exemptions by product class must be modeled before strict enforcement.",
+ "rule_notes": "Canada pack: proxy check for missing primary language value.",
+ "rule_ir_hash": "342123898ecb",
+ "condition_type": "missing_field",
+ "complexity": "simple",
+ "declarative_friendly": true,
+ "products_tested": 400,
+ "best_engine": "dbt",
+ "selection_reason": "hybrid-close-declarative:explicit-hash-tie-break-even->dbt",
+ "declarative_tie_break_applied": true,
+ "recommendation": "Declarative-friendly rule; prefer dbt/soda for readability and operations.",
+ "engines": {
+ "python": {
+ "status": "MATCH",
+ "mismatches": 0,
+ "parity_ci_lower": 0.9905,
+ "overall_confidence": 0.0466,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_cases": 5,
+ "mutation_score": 1.0,
+ "mutation_total": 0,
+ "mutation_killed": 0,
+ "verification_score": 1.0,
+ "counterexample_repair_applied": false,
+ "equivalence_counterexamples": [],
+ "effective_confidence": 0.0466,
+ "provider_factor": 1.0,
+ "real_llm_used": true,
+ "decision_score": 0.1466,
+ "conversion_provider": "groq",
+ "conversion_notes": "Converted via Groq (openai/gpt-oss-120b).",
+ "execution_mode": "",
+ "cloud_connected": false,
+ "cloud_scan_id": "",
+ "cloud_scan_url": "",
+ "conversion_artifact": "def check_main_language_missing(product):\n \"\"\"\n Checks if the 'lang' field is missing (None, empty, or whitespace-only).\n Returns the rule tag 'main-language-missing' if the condition is met, otherwise None.\n \"\"\"\n tag = \"main-language-missing\"\n value = product.get(\"lang\")\n if value is None:\n return tag\n if isinstance(value, str) and value.strip() == \"\":\n return tag\n return None",
+ "conversion_lines": 12,
+ "failed_test_cases": []
+ },
+ "dbt": {
+ "status": "MATCH",
+ "mismatches": 0,
+ "parity_ci_lower": 0.9905,
+ "overall_confidence": 0.049,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_cases": 0,
+ "mutation_score": 1.0,
+ "mutation_total": 0,
+ "mutation_killed": 0,
+ "verification_score": 1.0,
+ "counterexample_repair_applied": false,
+ "equivalence_counterexamples": [],
+ "effective_confidence": 0.049,
+ "provider_factor": 1.0,
+ "real_llm_used": null,
+ "decision_score": 0.084,
+ "conversion_provider": "dbt_core",
+ "conversion_notes": "dbt tests executed through dbt-core. Command: dbt debug + dbt run-operation count_violations (per-rule x19) --project-dir C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\dbt\\dbt_project --profiles-dir C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\dbt\\dbt_project | Success: True | Return code: 0",
+ "execution_mode": "local",
+ "cloud_connected": false,
+ "cloud_scan_id": "",
+ "cloud_scan_url": "",
+ "conversion_artifact": "SELECT product_id\nFROM {{ source('off_source', 'nutrition_table') }}\nWHERE lang IS NULL OR TRIM(lang) = ''",
+ "conversion_lines": 3,
+ "failed_test_cases": []
+ },
+ "soda": {
+ "status": "MATCH",
+ "mismatches": 0,
+ "parity_ci_lower": 0.9905,
+ "overall_confidence": 0.049,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_cases": 0,
+ "mutation_score": 1.0,
+ "mutation_total": 0,
+ "mutation_killed": 0,
+ "verification_score": 1.0,
+ "counterexample_repair_applied": false,
+ "equivalence_counterexamples": [],
+ "effective_confidence": 0.049,
+ "provider_factor": 1.0,
+ "real_llm_used": null,
+ "decision_score": 0.084,
+ "conversion_provider": "soda_cloud",
+ "conversion_notes": "Soda Cloud scan executed successfully. Command: soda contract verify (per-rule x19) -ds C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\soda\\soda_cloud\\data_source.yml -sc C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\soda\\soda_cloud\\soda_cloud.yml -p | Success: True | Return code: 0",
+ "execution_mode": "cloud",
+ "cloud_connected": true,
+ "cloud_scan_id": "",
+ "cloud_scan_url": "https://cloud.us.soda.io/o/c9e7e376-1da2-49c5-93cb-78c6d95273ee/datasets/5e60cafe-18fc-4d01-8390-0057b49d7765",
+ "conversion_artifact": " - failed_rows:\n name: main_language_missing\n expression: lang IS NULL OR TRIM(lang) = ''",
+ "conversion_lines": 3,
+ "failed_test_cases": []
+ }
+ }
+ },
+ {
+ "rule_name": "saturated_fat_over_105g",
+ "tag": "saturated-fat-value-over-105g",
+ "severity": "warning",
+ "condition": "saturated_fat > 105",
+ "jurisdiction": "global",
+ "profile_tags": [
+ "global",
+ "hybrid"
+ ],
+ "regulatory_type": "off_internal",
+ "legal_citation": "",
+ "source_url": "",
+ "effective_date": "",
+ "review_status": "reviewed",
+ "reviewer": "prototype",
+ "required_fields": [],
+ "exemption_logic": "none",
+ "rule_notes": "OFF-derived global rule: saturated_fat_over_105g",
+ "rule_ir_hash": "aafe1ceddbf5",
+ "condition_type": "field_threshold",
+ "complexity": "simple",
+ "declarative_friendly": true,
+ "products_tested": 400,
+ "best_engine": "soda",
+ "selection_reason": "hybrid-close-declarative:explicit-hash-tie-break-odd->soda",
+ "declarative_tie_break_applied": true,
+ "recommendation": "Declarative-friendly rule; prefer dbt/soda for readability and operations.",
+ "engines": {
+ "python": {
+ "status": "MATCH",
+ "mismatches": 0,
+ "parity_ci_lower": 0.9905,
+ "overall_confidence": 0.2148,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_cases": 22,
+ "mutation_score": 0.0,
+ "mutation_total": 1,
+ "mutation_killed": 0,
+ "verification_score": 0.0,
+ "counterexample_repair_applied": false,
+ "equivalence_counterexamples": [],
+ "effective_confidence": 0.2148,
+ "provider_factor": 1.0,
+ "real_llm_used": true,
+ "decision_score": 0.2648,
+ "conversion_provider": "groq",
+ "conversion_notes": "Converted via Groq (openai/gpt-oss-120b).",
+ "execution_mode": "",
+ "cloud_connected": false,
+ "cloud_scan_id": "",
+ "cloud_scan_url": "",
+ "conversion_artifact": "def check_saturated_fat_over_105g(product):\n \"\"\"\n Returns the tag \"saturated-fat-value-over-105g\" if product['saturated_fat'] > 105.\n Returns None if the field is missing, None, non\u2011numeric, or the condition is false.\n \"\"\"\n value = product.get(\"saturated_fat\")\n if value is None:\n return None\n\n # Determine if value is numeric\n if isinstance(value, (int, float)):\n num = float(value)\n else:\n try:\n num = float(value)\n except Exception:\n return None\n\n if num > 105:\n return \"saturated-fat-value-over-105g\"\n return None",
+ "conversion_lines": 21,
+ "failed_test_cases": []
+ },
+ "dbt": {
+ "status": "MATCH",
+ "mismatches": 0,
+ "parity_ci_lower": 0.9905,
+ "overall_confidence": 0.2193,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_cases": 0,
+ "mutation_score": 1.0,
+ "mutation_total": 0,
+ "mutation_killed": 0,
+ "verification_score": 1.0,
+ "counterexample_repair_applied": false,
+ "equivalence_counterexamples": [],
+ "effective_confidence": 0.2193,
+ "provider_factor": 1.0,
+ "real_llm_used": null,
+ "decision_score": 0.2543,
+ "conversion_provider": "dbt_core",
+ "conversion_notes": "dbt tests executed through dbt-core. Command: dbt debug + dbt run-operation count_violations (per-rule x19) --project-dir C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\dbt\\dbt_project --profiles-dir C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\dbt\\dbt_project | Success: True | Return code: 0",
+ "execution_mode": "local",
+ "cloud_connected": false,
+ "cloud_scan_id": "",
+ "cloud_scan_url": "",
+ "conversion_artifact": "SELECT product_id\nFROM {{ source('off_source', 'nutrition_table') }}\nWHERE saturated_fat > 105",
+ "conversion_lines": 3,
+ "failed_test_cases": []
+ },
+ "soda": {
+ "status": "MATCH",
+ "mismatches": 0,
+ "parity_ci_lower": 0.9905,
+ "overall_confidence": 0.2193,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_cases": 0,
+ "mutation_score": 1.0,
+ "mutation_total": 0,
+ "mutation_killed": 0,
+ "verification_score": 1.0,
+ "counterexample_repair_applied": false,
+ "equivalence_counterexamples": [],
+ "effective_confidence": 0.2193,
+ "provider_factor": 1.0,
+ "real_llm_used": null,
+ "decision_score": 0.2543,
+ "conversion_provider": "soda_cloud",
+ "conversion_notes": "Soda Cloud scan executed successfully. Command: soda contract verify (per-rule x19) -ds C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\soda\\soda_cloud\\data_source.yml -sc C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\soda\\soda_cloud\\soda_cloud.yml -p | Success: True | Return code: 0",
+ "execution_mode": "cloud",
+ "cloud_connected": true,
+ "cloud_scan_id": "",
+ "cloud_scan_url": "https://cloud.us.soda.io/o/c9e7e376-1da2-49c5-93cb-78c6d95273ee/datasets/5e60cafe-18fc-4d01-8390-0057b49d7765",
+ "conversion_artifact": " - failed_rows:\n name: saturated_fat_over_105g\n expression: saturated_fat > 105",
+ "conversion_lines": 3,
+ "failed_test_cases": []
+ }
+ }
+ },
+ {
+ "rule_name": "saturated_fat_vs_fat",
+ "tag": "saturated-fat-greater-than-fat",
+ "severity": "error",
+ "condition": "saturated_fat > (1.0 * fat + 0.001)",
+ "jurisdiction": "global",
+ "profile_tags": [
+ "global",
+ "hybrid"
+ ],
+ "regulatory_type": "off_internal",
+ "legal_citation": "",
+ "source_url": "",
+ "effective_date": "",
+ "review_status": "reviewed",
+ "reviewer": "prototype",
+ "required_fields": [],
+ "exemption_logic": "none",
+ "rule_notes": "OFF-derived global rule: saturated_fat_vs_fat",
+ "rule_ir_hash": "3b10c7bc2547",
+ "condition_type": "affine_field_comparison",
+ "complexity": "simple",
+ "declarative_friendly": true,
+ "products_tested": 400,
+ "best_engine": "dbt",
+ "selection_reason": "hybrid-close-declarative:explicit-hash-tie-break-even->dbt",
+ "declarative_tie_break_applied": true,
+ "recommendation": "Declarative-friendly rule; prefer dbt/soda for readability and operations.",
+ "engines": {
+ "python": {
+ "status": "MATCH",
+ "mismatches": 0,
+ "parity_ci_lower": 0.9905,
+ "overall_confidence": 0.1993,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_cases": 22,
+ "mutation_score": 0.0,
+ "mutation_total": 3,
+ "mutation_killed": 0,
+ "verification_score": 0.0,
+ "counterexample_repair_applied": false,
+ "equivalence_counterexamples": [],
+ "effective_confidence": 0.1993,
+ "provider_factor": 1.0,
+ "real_llm_used": true,
+ "decision_score": 0.2493,
+ "conversion_provider": "groq",
+ "conversion_notes": "Converted via Groq (openai/gpt-oss-120b).",
+ "execution_mode": "",
+ "cloud_connected": false,
+ "cloud_scan_id": "",
+ "cloud_scan_url": "",
+ "conversion_artifact": "def check_saturated_fat_vs_fat(product: dict):\n tag = \"saturated-fat-greater-than-fat\"\n left = product.get(\"saturated_fat\")\n right = product.get(\"fat\")\n # Missing or empty values\n if left is None or right is None:\n return None\n if isinstance(left, str) and left.strip() == \"\":\n return None\n if isinstance(right, str) and right.strip() == \"\":\n return None\n # Convert to numeric\n try:\n left_val = float(left)\n right_val = float(right)\n except (TypeError, ValueError):\n return None\n # Affine comparison: saturated_fat > (1.0 * fat + 0.001)\n if left_val > (1.0 * right_val + 0.001):\n return tag\n return None",
+ "conversion_lines": 21,
+ "failed_test_cases": []
+ },
+ "dbt": {
+ "status": "MATCH",
+ "mismatches": 0,
+ "parity_ci_lower": 0.9905,
+ "overall_confidence": 0.2193,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_cases": 0,
+ "mutation_score": 1.0,
+ "mutation_total": 0,
+ "mutation_killed": 0,
+ "verification_score": 1.0,
+ "counterexample_repair_applied": false,
+ "equivalence_counterexamples": [],
+ "effective_confidence": 0.2193,
+ "provider_factor": 1.0,
+ "real_llm_used": null,
+ "decision_score": 0.2543,
+ "conversion_provider": "dbt_core",
+ "conversion_notes": "dbt tests executed through dbt-core. Command: dbt debug + dbt run-operation count_violations (per-rule x19) --project-dir C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\dbt\\dbt_project --profiles-dir C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\dbt\\dbt_project | Success: True | Return code: 0",
+ "execution_mode": "local",
+ "cloud_connected": false,
+ "cloud_scan_id": "",
+ "cloud_scan_url": "",
+ "conversion_artifact": "SELECT product_id\nFROM {{ source('off_source', 'nutrition_table') }}\nWHERE saturated_fat > (1.0 * fat + 0.001)",
+ "conversion_lines": 3,
+ "failed_test_cases": []
+ },
+ "soda": {
+ "status": "MATCH",
+ "mismatches": 0,
+ "parity_ci_lower": 0.9905,
+ "overall_confidence": 0.2193,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_cases": 0,
+ "mutation_score": 1.0,
+ "mutation_total": 0,
+ "mutation_killed": 0,
+ "verification_score": 1.0,
+ "counterexample_repair_applied": false,
+ "equivalence_counterexamples": [],
+ "effective_confidence": 0.2193,
+ "provider_factor": 1.0,
+ "real_llm_used": null,
+ "decision_score": 0.2543,
+ "conversion_provider": "soda_cloud",
+ "conversion_notes": "Soda Cloud scan executed successfully. Command: soda contract verify (per-rule x19) -ds C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\soda\\soda_cloud\\data_source.yml -sc C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\soda\\soda_cloud\\soda_cloud.yml -p | Success: True | Return code: 0",
+ "execution_mode": "cloud",
+ "cloud_connected": true,
+ "cloud_scan_id": "",
+ "cloud_scan_url": "https://cloud.us.soda.io/o/c9e7e376-1da2-49c5-93cb-78c6d95273ee/datasets/5e60cafe-18fc-4d01-8390-0057b49d7765",
+ "conversion_artifact": " - failed_rows:\n name: saturated_fat_vs_fat\n expression: saturated_fat > (1.0 * fat + 0.001)",
+ "conversion_lines": 3,
+ "failed_test_cases": []
+ }
+ }
+ },
+ {
+ "rule_name": "sugars_over_105g",
+ "tag": "sugars-value-over-105g",
+ "severity": "warning",
+ "condition": "sugars > 105",
+ "jurisdiction": "global",
+ "profile_tags": [
+ "global",
+ "hybrid"
+ ],
+ "regulatory_type": "off_internal",
+ "legal_citation": "",
+ "source_url": "",
+ "effective_date": "",
+ "review_status": "reviewed",
+ "reviewer": "prototype",
+ "required_fields": [],
+ "exemption_logic": "none",
+ "rule_notes": "OFF-derived global rule: sugars_over_105g",
+ "rule_ir_hash": "f4924feaa2f8",
+ "condition_type": "field_threshold",
+ "complexity": "simple",
+ "declarative_friendly": true,
+ "products_tested": 400,
+ "best_engine": "dbt",
+ "selection_reason": "hybrid-close-declarative:explicit-hash-tie-break-even->dbt",
+ "declarative_tie_break_applied": true,
+ "recommendation": "Declarative-friendly rule; prefer dbt/soda for readability and operations.",
+ "engines": {
+ "python": {
+ "status": "MATCH",
+ "mismatches": 0,
+ "parity_ci_lower": 0.9905,
+ "overall_confidence": 0.8961,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_cases": 22,
+ "mutation_score": 1.0,
+ "mutation_total": 1,
+ "mutation_killed": 1,
+ "verification_score": 1.0,
+ "counterexample_repair_applied": false,
+ "equivalence_counterexamples": [],
+ "effective_confidence": 0.8961,
+ "provider_factor": 1.0,
+ "real_llm_used": true,
+ "decision_score": 0.9961,
+ "conversion_provider": "groq",
+ "conversion_notes": "Converted via Groq (openai/gpt-oss-120b).",
+ "execution_mode": "",
+ "cloud_connected": false,
+ "cloud_scan_id": "",
+ "cloud_scan_url": "",
+ "conversion_artifact": "def check_sugars_over_105g(product):\n \"\"\"\n Returns the tag 'sugars-value-over-105g' if the product's 'sugars' field\n exceeds 105. Returns None for missing, non-numeric, or non\u2011violating values.\n \"\"\"\n tag = \"sugars-value-over-105g\"\n value = product.get(\"sugars\")\n\n # Missing or None -> no violation\n if value is None:\n return None\n\n # Attempt to interpret numeric values\n try:\n numeric_value = float(value)\n except (TypeError, ValueError):\n return None\n\n # Apply threshold condition\n if numeric_value > 105:\n return tag\n\n return None",
+ "conversion_lines": 23,
+ "failed_test_cases": []
+ },
+ "dbt": {
+ "status": "MATCH",
+ "mismatches": 0,
+ "parity_ci_lower": 0.9905,
+ "overall_confidence": 0.9146,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_cases": 0,
+ "mutation_score": 1.0,
+ "mutation_total": 0,
+ "mutation_killed": 0,
+ "verification_score": 1.0,
+ "counterexample_repair_applied": false,
+ "equivalence_counterexamples": [],
+ "effective_confidence": 0.9146,
+ "provider_factor": 1.0,
+ "real_llm_used": null,
+ "decision_score": 0.9496,
+ "conversion_provider": "dbt_core",
+ "conversion_notes": "dbt tests executed through dbt-core. Command: dbt debug + dbt run-operation count_violations (per-rule x19) --project-dir C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\dbt\\dbt_project --profiles-dir C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\dbt\\dbt_project | Success: True | Return code: 0",
+ "execution_mode": "local",
+ "cloud_connected": false,
+ "cloud_scan_id": "",
+ "cloud_scan_url": "",
+ "conversion_artifact": "SELECT product_id\nFROM {{ source('off_source', 'nutrition_table') }}\nWHERE sugars > 105",
+ "conversion_lines": 3,
+ "failed_test_cases": []
+ },
+ "soda": {
+ "status": "MATCH",
+ "mismatches": 0,
+ "parity_ci_lower": 0.9905,
+ "overall_confidence": 0.9146,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_cases": 0,
+ "mutation_score": 1.0,
+ "mutation_total": 0,
+ "mutation_killed": 0,
+ "verification_score": 1.0,
+ "counterexample_repair_applied": false,
+ "equivalence_counterexamples": [],
+ "effective_confidence": 0.9146,
+ "provider_factor": 1.0,
+ "real_llm_used": null,
+ "decision_score": 0.9496,
+ "conversion_provider": "soda_cloud",
+ "conversion_notes": "Soda Cloud scan executed successfully. Command: soda contract verify (per-rule x19) -ds C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\soda\\soda_cloud\\data_source.yml -sc C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\soda\\soda_cloud\\soda_cloud.yml -p | Success: True | Return code: 0",
+ "execution_mode": "cloud",
+ "cloud_connected": true,
+ "cloud_scan_id": "",
+ "cloud_scan_url": "https://cloud.us.soda.io/o/c9e7e376-1da2-49c5-93cb-78c6d95273ee/datasets/5e60cafe-18fc-4d01-8390-0057b49d7765",
+ "conversion_artifact": " - failed_rows:\n name: sugars_over_105g\n expression: sugars > 105",
+ "conversion_lines": 3,
+ "failed_test_cases": []
+ }
+ }
+ },
+ {
+ "rule_name": "sugars_plus_starch_vs_carbohydrates",
+ "tag": "sugars-plus-starch-greater-than-carbohydrates",
+ "severity": "error",
+ "condition": "(sugars + starch) > (carbohydrates + 0.001)",
+ "jurisdiction": "global",
+ "profile_tags": [
+ "global",
+ "hybrid"
+ ],
+ "regulatory_type": "off_internal",
+ "legal_citation": "",
+ "source_url": "",
+ "effective_date": "",
+ "review_status": "reviewed",
+ "reviewer": "prototype",
+ "required_fields": [],
+ "exemption_logic": "none",
+ "rule_notes": "OFF-derived global rule: sugars_plus_starch_vs_carbohydrates",
+ "rule_ir_hash": "7160c946ab45",
+ "condition_type": "sum_fields_comparison",
+ "complexity": "medium",
+ "declarative_friendly": true,
+ "products_tested": 400,
+ "best_engine": "dbt",
+ "selection_reason": "hybrid-close-declarative:explicit-hash-tie-break-even->dbt",
+ "declarative_tie_break_applied": true,
+ "recommendation": "Declarative-friendly rule; prefer dbt/soda for readability and operations.",
+ "engines": {
+ "python": {
+ "status": "MATCH",
+ "mismatches": 0,
+ "parity_ci_lower": 0.9905,
+ "overall_confidence": 0.0456,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_cases": 22,
+ "mutation_score": 0.0,
+ "mutation_total": 1,
+ "mutation_killed": 0,
+ "verification_score": 0.0,
+ "counterexample_repair_applied": false,
+ "equivalence_counterexamples": [],
+ "effective_confidence": 0.0456,
+ "provider_factor": 1.0,
+ "real_llm_used": true,
+ "decision_score": 0.0956,
+ "conversion_provider": "groq",
+ "conversion_notes": "Converted via Groq (openai/gpt-oss-120b).",
+ "execution_mode": "",
+ "cloud_connected": false,
+ "cloud_scan_id": "",
+ "cloud_scan_url": "",
+ "conversion_artifact": "def check_sugars_plus_starch_vs_carbohydrates(product):\n \"\"\"\n Returns the rule tag if (sugars + starch) > (carbohydrates + 0.001).\n Returns None if any required field is missing, non\u2011numeric, or the condition is false.\n \"\"\"\n tag = \"sugars-plus-starch-greater-than-carbohydrates\"\n # Helper to determine if a value is numeric (int or float, but not bool)\n def _is_numeric(v):\n return isinstance(v, (int, float)) and not isinstance(v, bool)\n\n sugars = product.get(\"sugars\")\n starch = product.get(\"starch\")\n carbohydrates = product.get(\"carbohydrates\")\n\n # Missing or non\u2011numeric values cause the rule to be ignored\n if not (_is_numeric(sugars) and _is_numeric(starch) and _is_numeric(carbohydrates)):\n return None\n\n if (sugars + starch) > (carbohydrates + 0.001):\n return tag\n return None",
+ "conversion_lines": 21,
+ "failed_test_cases": []
+ },
+ "dbt": {
+ "status": "MATCH",
+ "mismatches": 0,
+ "parity_ci_lower": 0.9905,
+ "overall_confidence": 0.049,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_cases": 0,
+ "mutation_score": 1.0,
+ "mutation_total": 0,
+ "mutation_killed": 0,
+ "verification_score": 1.0,
+ "counterexample_repair_applied": false,
+ "equivalence_counterexamples": [],
+ "effective_confidence": 0.049,
+ "provider_factor": 1.0,
+ "real_llm_used": null,
+ "decision_score": 0.084,
+ "conversion_provider": "dbt_core",
+ "conversion_notes": "dbt tests executed through dbt-core. Command: dbt debug + dbt run-operation count_violations (per-rule x19) --project-dir C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\dbt\\dbt_project --profiles-dir C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\dbt\\dbt_project | Success: True | Return code: 0",
+ "execution_mode": "local",
+ "cloud_connected": false,
+ "cloud_scan_id": "",
+ "cloud_scan_url": "",
+ "conversion_artifact": "SELECT product_id\nFROM {{ source('off_source', 'nutrition_table') }}\nWHERE (sugars + starch) > (carbohydrates + 0.001)",
+ "conversion_lines": 3,
+ "failed_test_cases": []
+ },
+ "soda": {
+ "status": "MATCH",
+ "mismatches": 0,
+ "parity_ci_lower": 0.9905,
+ "overall_confidence": 0.049,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_cases": 0,
+ "mutation_score": 1.0,
+ "mutation_total": 0,
+ "mutation_killed": 0,
+ "verification_score": 1.0,
+ "counterexample_repair_applied": false,
+ "equivalence_counterexamples": [],
+ "effective_confidence": 0.049,
+ "provider_factor": 1.0,
+ "real_llm_used": null,
+ "decision_score": 0.084,
+ "conversion_provider": "soda_cloud",
+ "conversion_notes": "Soda Cloud scan executed successfully. Command: soda contract verify (per-rule x19) -ds C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\soda\\soda_cloud\\data_source.yml -sc C:\\dev\\OFF_DataQuality_Prototype\\results\\declarative_runtime\\soda\\soda_cloud\\soda_cloud.yml -p | Success: True | Return code: 0",
+ "execution_mode": "cloud",
+ "cloud_connected": true,
+ "cloud_scan_id": "",
+ "cloud_scan_url": "https://cloud.us.soda.io/o/c9e7e376-1da2-49c5-93cb-78c6d95273ee/datasets/5e60cafe-18fc-4d01-8390-0057b49d7765",
+ "conversion_artifact": " - failed_rows:\n name: sugars_plus_starch_vs_carbohydrates\n expression: (sugars + starch) > (carbohydrates + 0.001)",
+ "conversion_lines": 3,
+ "failed_test_cases": []
+ }
+ }
+ }
+ ],
+ "run_config": {
+ "llm_provider": "groq",
+ "llm_model": "openai/gpt-oss-120b",
+ "require_real_llm": true,
+ "groq_api_key_set": true,
+ "profile": "hybrid",
+ "dataset_size": 400,
+ "seed": 17,
+ "mode": "off",
+ "source_jsonl": "C:\\dev\\OFF_DataQuality_Prototype\\openfoodfacts-products.jsonl",
+ "soda_mode": "cloud",
+ "soda_cloud_credentials_set": true
+ }
+}
\ No newline at end of file
diff --git a/OFF_DataQuality/results/migration_results.json b/OFF_DataQuality/results/migration_results.json
new file mode 100644
index 0000000000000000000000000000000000000000..8ca07dabe3b19185152c3e4b713aac1c97ace7f9
--- /dev/null
+++ b/OFF_DataQuality/results/migration_results.json
@@ -0,0 +1,1183 @@
+{
+ "generated_at_utc": "2026-03-19T04:59:26.835204+00:00",
+ "run_fingerprint": {
+ "run_id": "parity_20260319T045926835204p0000_27542d2d",
+ "generated_at_utc": "2026-03-19T04:59:26.835204+00:00",
+ "execution_engine": "soda",
+ "soda_mode": "cloud",
+ "llm_provider": "simulated",
+ "llm_model": "",
+ "code_commit": "028c181854202a3ea75c2d4fbd380afcb2385249",
+ "dataset_fingerprint": {
+ "source_mode": "off_jsonl",
+ "source_jsonl": "C:\\Users\\Administrator\\Downloads\\off_quality_migration_prototype\\openfoodfacts-products.jsonl",
+ "requested_size": 20,
+ "products_tested": 20,
+ "seed": null,
+ "product_id_first": "0000101209159",
+ "product_id_last": "0000141013129",
+ "sha256": "c562e5de6e6cfd70e0e5332d54454c472ad0815a03be0152f6c1aaf6135b8c4b"
+ },
+ "rulepack_fingerprint": {
+ "profile": "global",
+ "rule_count": 12,
+ "rule_names_sha256": "2f2262fc9912fd4287ba7153b63ef2bc845a9129b1e185da528fa69ecaf05c07",
+ "rule_ir_sha256": "8b85ff9de926d2326112dcccd87b1ca3f4c060ae830d9d921f7148f1e6465c42"
+ }
+ },
+ "dataset": {
+ "jsonl_path": "C:\\Users\\Administrator\\Downloads\\off_quality_migration_prototype\\data\\sample_products.jsonl",
+ "duckdb_path": "C:\\Users\\Administrator\\Downloads\\off_quality_migration_prototype\\off_quality.db",
+ "products_tested": 20,
+ "source_jsonl": "C:\\Users\\Administrator\\Downloads\\off_quality_migration_prototype\\openfoodfacts-products.jsonl",
+ "perl_rules_source": "inline_legacy_rules",
+ "execution_engine": "soda",
+ "soda_mode": "cloud",
+ "profile": "global",
+ "profile_rule_count": 12,
+ "dataset_fingerprint_sha256": "c562e5de6e6cfd70e0e5332d54454c472ad0815a03be0152f6c1aaf6135b8c4b",
+ "rulepack_fingerprint_sha256": "8b85ff9de926d2326112dcccd87b1ca3f4c060ae830d9d921f7148f1e6465c42"
+ },
+ "migration_summary": {
+ "total_rules": 12,
+ "passed_rules": 12,
+ "rules_needing_review": 0,
+ "average_overall_confidence": 0.0609
+ },
+ "rule_results": [
+ {
+ "rule_name": "energy_kcal_vs_kj",
+ "tag": "energy-value-in-kcal-greater-than-in-kj",
+ "severity": "error",
+ "condition": "energy_kcal > energy_kj",
+ "jurisdiction": "global",
+ "profile_tags": [
+ "global",
+ "hybrid"
+ ],
+ "regulatory_type": "off_internal",
+ "legal_citation": "",
+ "source_url": "",
+ "effective_date": "",
+ "review_status": "reviewed",
+ "reviewer": "prototype",
+ "required_fields": [],
+ "exemption_logic": "none",
+ "rule_notes": "OFF-derived global rule: energy_kcal_vs_kj",
+ "rule_ir": {
+ "version": "1.0",
+ "rule_name": "energy_kcal_vs_kj",
+ "condition_type": "field_comparison",
+ "severity": "error",
+ "tag": "energy-value-in-kcal-greater-than-in-kj",
+ "left_operand": "energy_kcal",
+ "operator": ">",
+ "right_operand": "energy_kj"
+ },
+ "rule_ir_hash": "413d25898535",
+ "condition_type": "field_comparison",
+ "complexity": "simple",
+ "declarative_friendly": true,
+ "products_tested": 20,
+ "perl_errors": 0,
+ "python_errors": 0,
+ "supporting_violations": 0,
+ "positive_matches": 0,
+ "positive_agreement": 0.5,
+ "positive_coverage": 0.0,
+ "parity_ci_lower": 0.8389,
+ "parity_ci_upper": 1.0,
+ "coverage_ci_lower": 0.0,
+ "coverage_ci_upper": 0.1611,
+ "evidence_alpha": 1.0,
+ "evidence_beta": 1.0,
+ "evidence_posterior_mean": 0.5,
+ "evidence_ci_lower": 0.05,
+ "evidence_ci_upper": 0.95,
+ "evidence_factor": 0.05,
+ "matches": 20,
+ "mismatches": 0,
+ "confidence": 1.0,
+ "llm_confidence": 0.92,
+ "overall_confidence": 0.0386,
+ "overall_method": "llm_confidence * parity_ci_lower_95 * evidence_ci_lower_95_beta_posterior",
+ "status": "MATCH",
+ "duckdb_query": "SELECT * FROM nutrition_table WHERE energy_kcal > energy_kj",
+ "duckdb_errors": 0,
+ "duckdb_condition": "energy_kcal > energy_kj",
+ "duckdb_example_rows": [],
+ "equivalence_cases": 0,
+ "equivalence_matches": 0,
+ "equivalence_mismatches": 0,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_counterexamples": [],
+ "mutation_total": 0,
+ "mutation_killed": 0,
+ "mutation_survived": 0,
+ "mutation_score": 1.0,
+ "mutation_survived_mutants": [],
+ "verification_score": 1.0,
+ "counterexample_repair_attempted": false,
+ "counterexample_repair_applied": false,
+ "counterexample_repair_error": "",
+ "mismatch_product_ids": [],
+ "failed_test_cases": [],
+ "perl_logic": "# RULE_NAME: energy_kcal_vs_kj\n# SEVERITY: error\n# COMPLEXITY: simple\n# DECLARATIVE_FRIENDLY: yes\nif ($energy_kcal > $energy_kj) {\n push @{$product_ref->{$data_quality_tags}}, \"energy-value-in-kcal-greater-than-in-kj\";\n}",
+ "python_conversion": " - failed_rows:\n name: energy_kcal_vs_kj\n expression: energy_kcal > energy_kj",
+ "conversion_notes": "Soda Cloud unavailable/failed; used SQL-equivalent declarative parity (fast fallback). Command: soda contract verify (per-rule x12) -ds C:\\Users\\Administrator\\Downloads\\off_quality_migration_prototype\\results\\declarative_runtime\\soda\\soda_cloud\\data_source.yml -sc C:\\Users\\Administrator\\Downloads\\off_quality_migration_prototype\\results\\declarative_runtime\\soda\\soda_cloud\\soda_cloud.yml -p | Success: True | Return code: 0",
+ "conversion_provider": "soda_core_sql_fallback",
+ "conversion_execution_mode": "cloud_sql_fallback",
+ "conversion_cloud_connected": false,
+ "conversion_cloud_scan_id": "",
+ "conversion_cloud_scan_url": "https://cloud.us.soda.io/o/c9e7e376-1da2-49c5-93cb-78c6d95273ee/datasets/5e60cafe-18fc-4d01-8390-0057b49d7765"
+ },
+ {
+ "rule_name": "energy_kj_mismatch_low",
+ "tag": "energy-value-in-kcal-does-not-match-value-in-kj-low",
+ "severity": "error",
+ "condition": "energy_kj < (3.7 * energy_kcal - 2.0)",
+ "jurisdiction": "global",
+ "profile_tags": [
+ "global",
+ "hybrid"
+ ],
+ "regulatory_type": "off_internal",
+ "legal_citation": "",
+ "source_url": "",
+ "effective_date": "",
+ "review_status": "reviewed",
+ "reviewer": "prototype",
+ "required_fields": [],
+ "exemption_logic": "none",
+ "rule_notes": "OFF-derived global rule: energy_kj_mismatch_low",
+ "rule_ir": {
+ "version": "1.0",
+ "rule_name": "energy_kj_mismatch_low",
+ "condition_type": "affine_field_comparison",
+ "severity": "error",
+ "tag": "energy-value-in-kcal-does-not-match-value-in-kj-low",
+ "left_operand": "energy_kj",
+ "operator": "<",
+ "right_operand": "energy_kcal",
+ "scale_factor": 3.7,
+ "offset": -2.0
+ },
+ "rule_ir_hash": "5a7e9e033cc8",
+ "condition_type": "affine_field_comparison",
+ "complexity": "intricate",
+ "declarative_friendly": false,
+ "products_tested": 20,
+ "perl_errors": 0,
+ "python_errors": 0,
+ "supporting_violations": 0,
+ "positive_matches": 0,
+ "positive_agreement": 0.5,
+ "positive_coverage": 0.0,
+ "parity_ci_lower": 0.8389,
+ "parity_ci_upper": 1.0,
+ "coverage_ci_lower": 0.0,
+ "coverage_ci_upper": 0.1611,
+ "evidence_alpha": 1.0,
+ "evidence_beta": 1.0,
+ "evidence_posterior_mean": 0.5,
+ "evidence_ci_lower": 0.05,
+ "evidence_ci_upper": 0.95,
+ "evidence_factor": 0.05,
+ "matches": 20,
+ "mismatches": 0,
+ "confidence": 1.0,
+ "llm_confidence": 0.92,
+ "overall_confidence": 0.0386,
+ "overall_method": "llm_confidence * parity_ci_lower_95 * evidence_ci_lower_95_beta_posterior",
+ "status": "MATCH",
+ "duckdb_query": "SELECT * FROM nutrition_table WHERE energy_kj < (3.7 * energy_kcal - 2.0)",
+ "duckdb_errors": 0,
+ "duckdb_condition": "energy_kj < (3.7 * energy_kcal - 2.0)",
+ "duckdb_example_rows": [],
+ "equivalence_cases": 0,
+ "equivalence_matches": 0,
+ "equivalence_mismatches": 0,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_counterexamples": [],
+ "mutation_total": 0,
+ "mutation_killed": 0,
+ "mutation_survived": 0,
+ "mutation_score": 1.0,
+ "mutation_survived_mutants": [],
+ "verification_score": 1.0,
+ "counterexample_repair_attempted": false,
+ "counterexample_repair_applied": false,
+ "counterexample_repair_error": "",
+ "mismatch_product_ids": [],
+ "failed_test_cases": [],
+ "perl_logic": "# RULE_NAME: energy_kj_mismatch_low\n# SEVERITY: error\n# COMPLEXITY: intricate\n# DECLARATIVE_FRIENDLY: no\nif ($energy_kj < (3.7 * $energy_kcal - 2)) {\n push @{$product_ref->{$data_quality_tags}}, \"energy-value-in-kcal-does-not-match-value-in-kj-low\";\n}",
+ "python_conversion": " - failed_rows:\n name: energy_kj_mismatch_low\n expression: energy_kj < (3.7 * energy_kcal - 2.0)",
+ "conversion_notes": "Soda Cloud unavailable/failed; used SQL-equivalent declarative parity (fast fallback). Command: soda contract verify (per-rule x12) -ds C:\\Users\\Administrator\\Downloads\\off_quality_migration_prototype\\results\\declarative_runtime\\soda\\soda_cloud\\data_source.yml -sc C:\\Users\\Administrator\\Downloads\\off_quality_migration_prototype\\results\\declarative_runtime\\soda\\soda_cloud\\soda_cloud.yml -p | Success: True | Return code: 0",
+ "conversion_provider": "soda_core_sql_fallback",
+ "conversion_execution_mode": "cloud_sql_fallback",
+ "conversion_cloud_connected": false,
+ "conversion_cloud_scan_id": "",
+ "conversion_cloud_scan_url": "https://cloud.us.soda.io/o/c9e7e376-1da2-49c5-93cb-78c6d95273ee/datasets/5e60cafe-18fc-4d01-8390-0057b49d7765"
+ },
+ {
+ "rule_name": "energy_kj_mismatch_high",
+ "tag": "energy-value-in-kcal-does-not-match-value-in-kj-high",
+ "severity": "error",
+ "condition": "energy_kj > (4.7 * energy_kcal + 2.0)",
+ "jurisdiction": "global",
+ "profile_tags": [
+ "global",
+ "hybrid"
+ ],
+ "regulatory_type": "off_internal",
+ "legal_citation": "",
+ "source_url": "",
+ "effective_date": "",
+ "review_status": "reviewed",
+ "reviewer": "prototype",
+ "required_fields": [],
+ "exemption_logic": "none",
+ "rule_notes": "OFF-derived global rule: energy_kj_mismatch_high",
+ "rule_ir": {
+ "version": "1.0",
+ "rule_name": "energy_kj_mismatch_high",
+ "condition_type": "affine_field_comparison",
+ "severity": "error",
+ "tag": "energy-value-in-kcal-does-not-match-value-in-kj-high",
+ "left_operand": "energy_kj",
+ "operator": ">",
+ "right_operand": "energy_kcal",
+ "scale_factor": 4.7,
+ "offset": 2.0
+ },
+ "rule_ir_hash": "13c3c72ed774",
+ "condition_type": "affine_field_comparison",
+ "complexity": "intricate",
+ "declarative_friendly": false,
+ "products_tested": 20,
+ "perl_errors": 0,
+ "python_errors": 0,
+ "supporting_violations": 0,
+ "positive_matches": 0,
+ "positive_agreement": 0.5,
+ "positive_coverage": 0.0,
+ "parity_ci_lower": 0.8389,
+ "parity_ci_upper": 1.0,
+ "coverage_ci_lower": 0.0,
+ "coverage_ci_upper": 0.1611,
+ "evidence_alpha": 1.0,
+ "evidence_beta": 1.0,
+ "evidence_posterior_mean": 0.5,
+ "evidence_ci_lower": 0.05,
+ "evidence_ci_upper": 0.95,
+ "evidence_factor": 0.05,
+ "matches": 20,
+ "mismatches": 0,
+ "confidence": 1.0,
+ "llm_confidence": 0.92,
+ "overall_confidence": 0.0386,
+ "overall_method": "llm_confidence * parity_ci_lower_95 * evidence_ci_lower_95_beta_posterior",
+ "status": "MATCH",
+ "duckdb_query": "SELECT * FROM nutrition_table WHERE energy_kj > (4.7 * energy_kcal + 2.0)",
+ "duckdb_errors": 0,
+ "duckdb_condition": "energy_kj > (4.7 * energy_kcal + 2.0)",
+ "duckdb_example_rows": [],
+ "equivalence_cases": 0,
+ "equivalence_matches": 0,
+ "equivalence_mismatches": 0,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_counterexamples": [],
+ "mutation_total": 0,
+ "mutation_killed": 0,
+ "mutation_survived": 0,
+ "mutation_score": 1.0,
+ "mutation_survived_mutants": [],
+ "verification_score": 1.0,
+ "counterexample_repair_attempted": false,
+ "counterexample_repair_applied": false,
+ "counterexample_repair_error": "",
+ "mismatch_product_ids": [],
+ "failed_test_cases": [],
+ "perl_logic": "# RULE_NAME: energy_kj_mismatch_high\n# SEVERITY: error\n# COMPLEXITY: intricate\n# DECLARATIVE_FRIENDLY: no\nif ($energy_kj > (4.7 * $energy_kcal + 2)) {\n push @{$product_ref->{$data_quality_tags}}, \"energy-value-in-kcal-does-not-match-value-in-kj-high\";\n}",
+ "python_conversion": " - failed_rows:\n name: energy_kj_mismatch_high\n expression: energy_kj > (4.7 * energy_kcal + 2.0)",
+ "conversion_notes": "Soda Cloud unavailable/failed; used SQL-equivalent declarative parity (fast fallback). Command: soda contract verify (per-rule x12) -ds C:\\Users\\Administrator\\Downloads\\off_quality_migration_prototype\\results\\declarative_runtime\\soda\\soda_cloud\\data_source.yml -sc C:\\Users\\Administrator\\Downloads\\off_quality_migration_prototype\\results\\declarative_runtime\\soda\\soda_cloud\\soda_cloud.yml -p | Success: True | Return code: 0",
+ "conversion_provider": "soda_core_sql_fallback",
+ "conversion_execution_mode": "cloud_sql_fallback",
+ "conversion_cloud_connected": false,
+ "conversion_cloud_scan_id": "",
+ "conversion_cloud_scan_url": "https://cloud.us.soda.io/o/c9e7e376-1da2-49c5-93cb-78c6d95273ee/datasets/5e60cafe-18fc-4d01-8390-0057b49d7765"
+ },
+ {
+ "rule_name": "energy_kj_over_3911",
+ "tag": "value-over-3911-energy",
+ "severity": "error",
+ "condition": "energy_kj > 3911",
+ "jurisdiction": "global",
+ "profile_tags": [
+ "global",
+ "hybrid"
+ ],
+ "regulatory_type": "off_internal",
+ "legal_citation": "",
+ "source_url": "",
+ "effective_date": "",
+ "review_status": "reviewed",
+ "reviewer": "prototype",
+ "required_fields": [],
+ "exemption_logic": "none",
+ "rule_notes": "OFF-derived global rule: energy_kj_over_3911",
+ "rule_ir": {
+ "version": "1.0",
+ "rule_name": "energy_kj_over_3911",
+ "condition_type": "field_threshold",
+ "severity": "error",
+ "tag": "value-over-3911-energy",
+ "left_operand": "energy_kj",
+ "operator": ">",
+ "right_operand": 3911.0
+ },
+ "rule_ir_hash": "abd124f391c9",
+ "condition_type": "field_threshold",
+ "complexity": "simple",
+ "declarative_friendly": true,
+ "products_tested": 20,
+ "perl_errors": 1,
+ "python_errors": 1,
+ "supporting_violations": 1,
+ "positive_matches": 1,
+ "positive_agreement": 1.0,
+ "positive_coverage": 0.05,
+ "parity_ci_lower": 0.8389,
+ "parity_ci_upper": 1.0,
+ "coverage_ci_lower": 0.0089,
+ "coverage_ci_upper": 0.2361,
+ "evidence_alpha": 2.0,
+ "evidence_beta": 1.0,
+ "evidence_posterior_mean": 0.6667,
+ "evidence_ci_lower": 0.2236,
+ "evidence_ci_upper": 0.9747,
+ "evidence_factor": 0.2236,
+ "matches": 20,
+ "mismatches": 0,
+ "confidence": 1.0,
+ "llm_confidence": 0.92,
+ "overall_confidence": 0.1726,
+ "overall_method": "llm_confidence * parity_ci_lower_95 * evidence_ci_lower_95_beta_posterior",
+ "status": "MATCH",
+ "duckdb_query": "SELECT * FROM nutrition_table WHERE energy_kj > 3911",
+ "duckdb_errors": 1,
+ "duckdb_condition": "energy_kj > 3911",
+ "duckdb_example_rows": [
+ {
+ "product_id": "0000111301201",
+ "energy_kj": 19200.0,
+ "energy_kj_computed": NaN,
+ "energy_kcal": 4590.0,
+ "fat": 510.0,
+ "saturated_fat": 76.4,
+ "carbohydrates": 0.0,
+ "sugars": 0.0,
+ "starch": NaN,
+ "sodium": 5.1,
+ "ingredients_text": "CANOLA OIL, WATER, PALM OIL, PALM KERNEL OIL, SALT, WHEY POWDER (MILK), VEGETABLE MONO AND DIGLYCERIDES, SOYBEAN LECITHIN, POTASSIUM SORBATE (PRESERVATIVE), CITRIC ACID, ARTIFICIAL FLAVOR, VITAMIN E (DL-ALPHA-TOCOPHEROL ACETATE), VITAMIN A PALMITATE, BETA CAROTENE & VITAMIN D3.",
+ "ingredients_text_present": 1,
+ "contains_statement_present": 1,
+ "allergen_evidence_present": 1,
+ "fop_threshold_exceeded": 1,
+ "fop_symbol_present": 0,
+ "fop_exempt_proxy": 0,
+ "product_is_prepackaged_proxy": 1,
+ "lc": "en",
+ "lang": "en",
+ "language_code": "en"
+ }
+ ],
+ "equivalence_cases": 0,
+ "equivalence_matches": 0,
+ "equivalence_mismatches": 0,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_counterexamples": [],
+ "mutation_total": 0,
+ "mutation_killed": 0,
+ "mutation_survived": 0,
+ "mutation_score": 1.0,
+ "mutation_survived_mutants": [],
+ "verification_score": 1.0,
+ "counterexample_repair_attempted": false,
+ "counterexample_repair_applied": false,
+ "counterexample_repair_error": "",
+ "mismatch_product_ids": [],
+ "failed_test_cases": [],
+ "perl_logic": "# RULE_NAME: energy_kj_over_3911\n# SEVERITY: error\n# COMPLEXITY: simple\n# DECLARATIVE_FRIENDLY: yes\nif ($energy_kj > 3911) {\n push @{$product_ref->{$data_quality_tags}}, \"value-over-3911-energy\";\n}",
+ "python_conversion": " - failed_rows:\n name: energy_kj_over_3911\n expression: energy_kj > 3911",
+ "conversion_notes": "Soda Cloud unavailable/failed; used SQL-equivalent declarative parity (fast fallback). Command: soda contract verify (per-rule x12) -ds C:\\Users\\Administrator\\Downloads\\off_quality_migration_prototype\\results\\declarative_runtime\\soda\\soda_cloud\\data_source.yml -sc C:\\Users\\Administrator\\Downloads\\off_quality_migration_prototype\\results\\declarative_runtime\\soda\\soda_cloud\\soda_cloud.yml -p | Success: True | Return code: 0",
+ "conversion_provider": "soda_core_sql_fallback",
+ "conversion_execution_mode": "cloud_sql_fallback",
+ "conversion_cloud_connected": false,
+ "conversion_cloud_scan_id": "",
+ "conversion_cloud_scan_url": "https://cloud.us.soda.io/o/c9e7e376-1da2-49c5-93cb-78c6d95273ee/datasets/5e60cafe-18fc-4d01-8390-0057b49d7765"
+ },
+ {
+ "rule_name": "energy_kj_computed_mismatch_low",
+ "tag": "energy-value-in-kj-does-not-match-value-computed-from-other-nutrients-low",
+ "severity": "error",
+ "condition": "energy_kj_computed < (0.7 * energy_kj - 5.0)",
+ "jurisdiction": "global",
+ "profile_tags": [
+ "global",
+ "hybrid"
+ ],
+ "regulatory_type": "off_internal",
+ "legal_citation": "",
+ "source_url": "",
+ "effective_date": "",
+ "review_status": "reviewed",
+ "reviewer": "prototype",
+ "required_fields": [],
+ "exemption_logic": "none",
+ "rule_notes": "OFF-derived global rule: energy_kj_computed_mismatch_low",
+ "rule_ir": {
+ "version": "1.0",
+ "rule_name": "energy_kj_computed_mismatch_low",
+ "condition_type": "affine_field_comparison",
+ "severity": "error",
+ "tag": "energy-value-in-kj-does-not-match-value-computed-from-other-nutrients-low",
+ "left_operand": "energy_kj_computed",
+ "operator": "<",
+ "right_operand": "energy_kj",
+ "scale_factor": 0.7,
+ "offset": -5.0
+ },
+ "rule_ir_hash": "2845fdb42a7e",
+ "condition_type": "affine_field_comparison",
+ "complexity": "intricate",
+ "declarative_friendly": false,
+ "products_tested": 20,
+ "perl_errors": 0,
+ "python_errors": 0,
+ "supporting_violations": 0,
+ "positive_matches": 0,
+ "positive_agreement": 0.5,
+ "positive_coverage": 0.0,
+ "parity_ci_lower": 0.8389,
+ "parity_ci_upper": 1.0,
+ "coverage_ci_lower": 0.0,
+ "coverage_ci_upper": 0.1611,
+ "evidence_alpha": 1.0,
+ "evidence_beta": 1.0,
+ "evidence_posterior_mean": 0.5,
+ "evidence_ci_lower": 0.05,
+ "evidence_ci_upper": 0.95,
+ "evidence_factor": 0.05,
+ "matches": 20,
+ "mismatches": 0,
+ "confidence": 1.0,
+ "llm_confidence": 0.92,
+ "overall_confidence": 0.0386,
+ "overall_method": "llm_confidence * parity_ci_lower_95 * evidence_ci_lower_95_beta_posterior",
+ "status": "MATCH",
+ "duckdb_query": "SELECT * FROM nutrition_table WHERE energy_kj_computed < (0.7 * energy_kj - 5.0)",
+ "duckdb_errors": 0,
+ "duckdb_condition": "energy_kj_computed < (0.7 * energy_kj - 5.0)",
+ "duckdb_example_rows": [],
+ "equivalence_cases": 0,
+ "equivalence_matches": 0,
+ "equivalence_mismatches": 0,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_counterexamples": [],
+ "mutation_total": 0,
+ "mutation_killed": 0,
+ "mutation_survived": 0,
+ "mutation_score": 1.0,
+ "mutation_survived_mutants": [],
+ "verification_score": 1.0,
+ "counterexample_repair_attempted": false,
+ "counterexample_repair_applied": false,
+ "counterexample_repair_error": "",
+ "mismatch_product_ids": [],
+ "failed_test_cases": [],
+ "perl_logic": "# RULE_NAME: energy_kj_computed_mismatch_low\n# SEVERITY: error\n# COMPLEXITY: intricate\n# DECLARATIVE_FRIENDLY: no\nif ($energy_kj_computed < (0.7 * $energy_kj - 5)) {\n push @{$product_ref->{$data_quality_tags}}, \"energy-value-in-kj-does-not-match-value-computed-from-other-nutrients-low\";\n}",
+ "python_conversion": " - failed_rows:\n name: energy_kj_computed_mismatch_low\n expression: energy_kj_computed < (0.7 * energy_kj - 5.0)",
+ "conversion_notes": "Soda Cloud unavailable/failed; used SQL-equivalent declarative parity (fast fallback). Command: soda contract verify (per-rule x12) -ds C:\\Users\\Administrator\\Downloads\\off_quality_migration_prototype\\results\\declarative_runtime\\soda\\soda_cloud\\data_source.yml -sc C:\\Users\\Administrator\\Downloads\\off_quality_migration_prototype\\results\\declarative_runtime\\soda\\soda_cloud\\soda_cloud.yml -p | Success: True | Return code: 0",
+ "conversion_provider": "soda_core_sql_fallback",
+ "conversion_execution_mode": "cloud_sql_fallback",
+ "conversion_cloud_connected": false,
+ "conversion_cloud_scan_id": "",
+ "conversion_cloud_scan_url": "https://cloud.us.soda.io/o/c9e7e376-1da2-49c5-93cb-78c6d95273ee/datasets/5e60cafe-18fc-4d01-8390-0057b49d7765"
+ },
+ {
+ "rule_name": "energy_kj_computed_mismatch_high",
+ "tag": "energy-value-in-kj-does-not-match-value-computed-from-other-nutrients-high",
+ "severity": "error",
+ "condition": "energy_kj_computed > (1.3 * energy_kj + 5.0)",
+ "jurisdiction": "global",
+ "profile_tags": [
+ "global",
+ "hybrid"
+ ],
+ "regulatory_type": "off_internal",
+ "legal_citation": "",
+ "source_url": "",
+ "effective_date": "",
+ "review_status": "reviewed",
+ "reviewer": "prototype",
+ "required_fields": [],
+ "exemption_logic": "none",
+ "rule_notes": "OFF-derived global rule: energy_kj_computed_mismatch_high",
+ "rule_ir": {
+ "version": "1.0",
+ "rule_name": "energy_kj_computed_mismatch_high",
+ "condition_type": "affine_field_comparison",
+ "severity": "error",
+ "tag": "energy-value-in-kj-does-not-match-value-computed-from-other-nutrients-high",
+ "left_operand": "energy_kj_computed",
+ "operator": ">",
+ "right_operand": "energy_kj",
+ "scale_factor": 1.3,
+ "offset": 5.0
+ },
+ "rule_ir_hash": "ac2e3831ada8",
+ "condition_type": "affine_field_comparison",
+ "complexity": "intricate",
+ "declarative_friendly": false,
+ "products_tested": 20,
+ "perl_errors": 0,
+ "python_errors": 0,
+ "supporting_violations": 0,
+ "positive_matches": 0,
+ "positive_agreement": 0.5,
+ "positive_coverage": 0.0,
+ "parity_ci_lower": 0.8389,
+ "parity_ci_upper": 1.0,
+ "coverage_ci_lower": 0.0,
+ "coverage_ci_upper": 0.1611,
+ "evidence_alpha": 1.0,
+ "evidence_beta": 1.0,
+ "evidence_posterior_mean": 0.5,
+ "evidence_ci_lower": 0.05,
+ "evidence_ci_upper": 0.95,
+ "evidence_factor": 0.05,
+ "matches": 20,
+ "mismatches": 0,
+ "confidence": 1.0,
+ "llm_confidence": 0.92,
+ "overall_confidence": 0.0386,
+ "overall_method": "llm_confidence * parity_ci_lower_95 * evidence_ci_lower_95_beta_posterior",
+ "status": "MATCH",
+ "duckdb_query": "SELECT * FROM nutrition_table WHERE energy_kj_computed > (1.3 * energy_kj + 5.0)",
+ "duckdb_errors": 0,
+ "duckdb_condition": "energy_kj_computed > (1.3 * energy_kj + 5.0)",
+ "duckdb_example_rows": [],
+ "equivalence_cases": 0,
+ "equivalence_matches": 0,
+ "equivalence_mismatches": 0,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_counterexamples": [],
+ "mutation_total": 0,
+ "mutation_killed": 0,
+ "mutation_survived": 0,
+ "mutation_score": 1.0,
+ "mutation_survived_mutants": [],
+ "verification_score": 1.0,
+ "counterexample_repair_attempted": false,
+ "counterexample_repair_applied": false,
+ "counterexample_repair_error": "",
+ "mismatch_product_ids": [],
+ "failed_test_cases": [],
+ "perl_logic": "# RULE_NAME: energy_kj_computed_mismatch_high\n# SEVERITY: error\n# COMPLEXITY: intricate\n# DECLARATIVE_FRIENDLY: no\nif ($energy_kj_computed > (1.3 * $energy_kj + 5)) {\n push @{$product_ref->{$data_quality_tags}}, \"energy-value-in-kj-does-not-match-value-computed-from-other-nutrients-high\";\n}",
+ "python_conversion": " - failed_rows:\n name: energy_kj_computed_mismatch_high\n expression: energy_kj_computed > (1.3 * energy_kj + 5.0)",
+ "conversion_notes": "Soda Cloud unavailable/failed; used SQL-equivalent declarative parity (fast fallback). Command: soda contract verify (per-rule x12) -ds C:\\Users\\Administrator\\Downloads\\off_quality_migration_prototype\\results\\declarative_runtime\\soda\\soda_cloud\\data_source.yml -sc C:\\Users\\Administrator\\Downloads\\off_quality_migration_prototype\\results\\declarative_runtime\\soda\\soda_cloud\\soda_cloud.yml -p | Success: True | Return code: 0",
+ "conversion_provider": "soda_core_sql_fallback",
+ "conversion_execution_mode": "cloud_sql_fallback",
+ "conversion_cloud_connected": false,
+ "conversion_cloud_scan_id": "",
+ "conversion_cloud_scan_url": "https://cloud.us.soda.io/o/c9e7e376-1da2-49c5-93cb-78c6d95273ee/datasets/5e60cafe-18fc-4d01-8390-0057b49d7765"
+ },
+ {
+ "rule_name": "saturated_fat_vs_fat",
+ "tag": "saturated-fat-greater-than-fat",
+ "severity": "error",
+ "condition": "saturated_fat > (1.0 * fat + 0.001)",
+ "jurisdiction": "global",
+ "profile_tags": [
+ "global",
+ "hybrid"
+ ],
+ "regulatory_type": "off_internal",
+ "legal_citation": "",
+ "source_url": "",
+ "effective_date": "",
+ "review_status": "reviewed",
+ "reviewer": "prototype",
+ "required_fields": [],
+ "exemption_logic": "none",
+ "rule_notes": "OFF-derived global rule: saturated_fat_vs_fat",
+ "rule_ir": {
+ "version": "1.0",
+ "rule_name": "saturated_fat_vs_fat",
+ "condition_type": "affine_field_comparison",
+ "severity": "error",
+ "tag": "saturated-fat-greater-than-fat",
+ "left_operand": "saturated_fat",
+ "operator": ">",
+ "right_operand": "fat",
+ "scale_factor": 1.0,
+ "offset": 0.001
+ },
+ "rule_ir_hash": "3b10c7bc2547",
+ "condition_type": "affine_field_comparison",
+ "complexity": "simple",
+ "declarative_friendly": true,
+ "products_tested": 20,
+ "perl_errors": 0,
+ "python_errors": 0,
+ "supporting_violations": 0,
+ "positive_matches": 0,
+ "positive_agreement": 0.5,
+ "positive_coverage": 0.0,
+ "parity_ci_lower": 0.8389,
+ "parity_ci_upper": 1.0,
+ "coverage_ci_lower": 0.0,
+ "coverage_ci_upper": 0.1611,
+ "evidence_alpha": 1.0,
+ "evidence_beta": 1.0,
+ "evidence_posterior_mean": 0.5,
+ "evidence_ci_lower": 0.05,
+ "evidence_ci_upper": 0.95,
+ "evidence_factor": 0.05,
+ "matches": 20,
+ "mismatches": 0,
+ "confidence": 1.0,
+ "llm_confidence": 0.92,
+ "overall_confidence": 0.0386,
+ "overall_method": "llm_confidence * parity_ci_lower_95 * evidence_ci_lower_95_beta_posterior",
+ "status": "MATCH",
+ "duckdb_query": "SELECT * FROM nutrition_table WHERE saturated_fat > (1.0 * fat + 0.001)",
+ "duckdb_errors": 0,
+ "duckdb_condition": "saturated_fat > (1.0 * fat + 0.001)",
+ "duckdb_example_rows": [],
+ "equivalence_cases": 0,
+ "equivalence_matches": 0,
+ "equivalence_mismatches": 0,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_counterexamples": [],
+ "mutation_total": 0,
+ "mutation_killed": 0,
+ "mutation_survived": 0,
+ "mutation_score": 1.0,
+ "mutation_survived_mutants": [],
+ "verification_score": 1.0,
+ "counterexample_repair_attempted": false,
+ "counterexample_repair_applied": false,
+ "counterexample_repair_error": "",
+ "mismatch_product_ids": [],
+ "failed_test_cases": [],
+ "perl_logic": "# RULE_NAME: saturated_fat_vs_fat\n# SEVERITY: error\n# COMPLEXITY: simple\n# DECLARATIVE_FRIENDLY: yes\nif ($saturated_fat > (1 * $fat + 0.001)) {\n push @{$product_ref->{$data_quality_tags}}, \"saturated-fat-greater-than-fat\";\n}",
+ "python_conversion": " - failed_rows:\n name: saturated_fat_vs_fat\n expression: saturated_fat > (1.0 * fat + 0.001)",
+ "conversion_notes": "Soda Cloud unavailable/failed; used SQL-equivalent declarative parity (fast fallback). Command: soda contract verify (per-rule x12) -ds C:\\Users\\Administrator\\Downloads\\off_quality_migration_prototype\\results\\declarative_runtime\\soda\\soda_cloud\\data_source.yml -sc C:\\Users\\Administrator\\Downloads\\off_quality_migration_prototype\\results\\declarative_runtime\\soda\\soda_cloud\\soda_cloud.yml -p | Success: True | Return code: 0",
+ "conversion_provider": "soda_core_sql_fallback",
+ "conversion_execution_mode": "cloud_sql_fallback",
+ "conversion_cloud_connected": false,
+ "conversion_cloud_scan_id": "",
+ "conversion_cloud_scan_url": "https://cloud.us.soda.io/o/c9e7e376-1da2-49c5-93cb-78c6d95273ee/datasets/5e60cafe-18fc-4d01-8390-0057b49d7765"
+ },
+ {
+ "rule_name": "sugars_plus_starch_vs_carbohydrates",
+ "tag": "sugars-plus-starch-greater-than-carbohydrates",
+ "severity": "error",
+ "condition": "(sugars + starch) > (carbohydrates + 0.001)",
+ "jurisdiction": "global",
+ "profile_tags": [
+ "global",
+ "hybrid"
+ ],
+ "regulatory_type": "off_internal",
+ "legal_citation": "",
+ "source_url": "",
+ "effective_date": "",
+ "review_status": "reviewed",
+ "reviewer": "prototype",
+ "required_fields": [],
+ "exemption_logic": "none",
+ "rule_notes": "OFF-derived global rule: sugars_plus_starch_vs_carbohydrates",
+ "rule_ir": {
+ "version": "1.0",
+ "rule_name": "sugars_plus_starch_vs_carbohydrates",
+ "condition_type": "sum_fields_comparison",
+ "severity": "error",
+ "tag": "sugars-plus-starch-greater-than-carbohydrates",
+ "operator": ">",
+ "right_operand": "carbohydrates",
+ "left_operands": [
+ "sugars",
+ "starch"
+ ],
+ "right_offset": 0.001
+ },
+ "rule_ir_hash": "7160c946ab45",
+ "condition_type": "sum_fields_comparison",
+ "complexity": "medium",
+ "declarative_friendly": true,
+ "products_tested": 20,
+ "perl_errors": 0,
+ "python_errors": 0,
+ "supporting_violations": 0,
+ "positive_matches": 0,
+ "positive_agreement": 0.5,
+ "positive_coverage": 0.0,
+ "parity_ci_lower": 0.8389,
+ "parity_ci_upper": 1.0,
+ "coverage_ci_lower": 0.0,
+ "coverage_ci_upper": 0.1611,
+ "evidence_alpha": 1.0,
+ "evidence_beta": 1.0,
+ "evidence_posterior_mean": 0.5,
+ "evidence_ci_lower": 0.05,
+ "evidence_ci_upper": 0.95,
+ "evidence_factor": 0.05,
+ "matches": 20,
+ "mismatches": 0,
+ "confidence": 1.0,
+ "llm_confidence": 0.92,
+ "overall_confidence": 0.0386,
+ "overall_method": "llm_confidence * parity_ci_lower_95 * evidence_ci_lower_95_beta_posterior",
+ "status": "MATCH",
+ "duckdb_query": "SELECT * FROM nutrition_table WHERE (sugars + starch) > (carbohydrates + 0.001)",
+ "duckdb_errors": 0,
+ "duckdb_condition": "(sugars + starch) > (carbohydrates + 0.001)",
+ "duckdb_example_rows": [],
+ "equivalence_cases": 0,
+ "equivalence_matches": 0,
+ "equivalence_mismatches": 0,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_counterexamples": [],
+ "mutation_total": 0,
+ "mutation_killed": 0,
+ "mutation_survived": 0,
+ "mutation_score": 1.0,
+ "mutation_survived_mutants": [],
+ "verification_score": 1.0,
+ "counterexample_repair_attempted": false,
+ "counterexample_repair_applied": false,
+ "counterexample_repair_error": "",
+ "mismatch_product_ids": [],
+ "failed_test_cases": [],
+ "perl_logic": "# RULE_NAME: sugars_plus_starch_vs_carbohydrates\n# SEVERITY: error\n# COMPLEXITY: medium\n# DECLARATIVE_FRIENDLY: yes\nif (($sugars + $starch) > ($carbohydrates + 0.001)) {\n push @{$product_ref->{$data_quality_tags}}, \"sugars-plus-starch-greater-than-carbohydrates\";\n}",
+ "python_conversion": " - failed_rows:\n name: sugars_plus_starch_vs_carbohydrates\n expression: (sugars + starch) > (carbohydrates + 0.001)",
+ "conversion_notes": "Soda Cloud unavailable/failed; used SQL-equivalent declarative parity (fast fallback). Command: soda contract verify (per-rule x12) -ds C:\\Users\\Administrator\\Downloads\\off_quality_migration_prototype\\results\\declarative_runtime\\soda\\soda_cloud\\data_source.yml -sc C:\\Users\\Administrator\\Downloads\\off_quality_migration_prototype\\results\\declarative_runtime\\soda\\soda_cloud\\soda_cloud.yml -p | Success: True | Return code: 0",
+ "conversion_provider": "soda_core_sql_fallback",
+ "conversion_execution_mode": "cloud_sql_fallback",
+ "conversion_cloud_connected": false,
+ "conversion_cloud_scan_id": "",
+ "conversion_cloud_scan_url": "https://cloud.us.soda.io/o/c9e7e376-1da2-49c5-93cb-78c6d95273ee/datasets/5e60cafe-18fc-4d01-8390-0057b49d7765"
+ },
+ {
+ "rule_name": "fat_over_105g",
+ "tag": "fat-value-over-105g",
+ "severity": "warning",
+ "condition": "fat > 105",
+ "jurisdiction": "global",
+ "profile_tags": [
+ "global",
+ "hybrid"
+ ],
+ "regulatory_type": "off_internal",
+ "legal_citation": "",
+ "source_url": "",
+ "effective_date": "",
+ "review_status": "reviewed",
+ "reviewer": "prototype",
+ "required_fields": [],
+ "exemption_logic": "none",
+ "rule_notes": "OFF-derived global rule: fat_over_105g",
+ "rule_ir": {
+ "version": "1.0",
+ "rule_name": "fat_over_105g",
+ "condition_type": "field_threshold",
+ "severity": "warning",
+ "tag": "fat-value-over-105g",
+ "left_operand": "fat",
+ "operator": ">",
+ "right_operand": 105.0
+ },
+ "rule_ir_hash": "c6f7c59ce9c9",
+ "condition_type": "field_threshold",
+ "complexity": "simple",
+ "declarative_friendly": true,
+ "products_tested": 20,
+ "perl_errors": 1,
+ "python_errors": 1,
+ "supporting_violations": 1,
+ "positive_matches": 1,
+ "positive_agreement": 1.0,
+ "positive_coverage": 0.05,
+ "parity_ci_lower": 0.8389,
+ "parity_ci_upper": 1.0,
+ "coverage_ci_lower": 0.0089,
+ "coverage_ci_upper": 0.2361,
+ "evidence_alpha": 2.0,
+ "evidence_beta": 1.0,
+ "evidence_posterior_mean": 0.6667,
+ "evidence_ci_lower": 0.2236,
+ "evidence_ci_upper": 0.9747,
+ "evidence_factor": 0.2236,
+ "matches": 20,
+ "mismatches": 0,
+ "confidence": 1.0,
+ "llm_confidence": 0.92,
+ "overall_confidence": 0.1726,
+ "overall_method": "llm_confidence * parity_ci_lower_95 * evidence_ci_lower_95_beta_posterior",
+ "status": "MATCH",
+ "duckdb_query": "SELECT * FROM nutrition_table WHERE fat > 105",
+ "duckdb_errors": 1,
+ "duckdb_condition": "fat > 105",
+ "duckdb_example_rows": [
+ {
+ "product_id": "0000111301201",
+ "energy_kj": 19200.0,
+ "energy_kj_computed": NaN,
+ "energy_kcal": 4590.0,
+ "fat": 510.0,
+ "saturated_fat": 76.4,
+ "carbohydrates": 0.0,
+ "sugars": 0.0,
+ "starch": NaN,
+ "sodium": 5.1,
+ "ingredients_text": "CANOLA OIL, WATER, PALM OIL, PALM KERNEL OIL, SALT, WHEY POWDER (MILK), VEGETABLE MONO AND DIGLYCERIDES, SOYBEAN LECITHIN, POTASSIUM SORBATE (PRESERVATIVE), CITRIC ACID, ARTIFICIAL FLAVOR, VITAMIN E (DL-ALPHA-TOCOPHEROL ACETATE), VITAMIN A PALMITATE, BETA CAROTENE & VITAMIN D3.",
+ "ingredients_text_present": 1,
+ "contains_statement_present": 1,
+ "allergen_evidence_present": 1,
+ "fop_threshold_exceeded": 1,
+ "fop_symbol_present": 0,
+ "fop_exempt_proxy": 0,
+ "product_is_prepackaged_proxy": 1,
+ "lc": "en",
+ "lang": "en",
+ "language_code": "en"
+ }
+ ],
+ "equivalence_cases": 0,
+ "equivalence_matches": 0,
+ "equivalence_mismatches": 0,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_counterexamples": [],
+ "mutation_total": 0,
+ "mutation_killed": 0,
+ "mutation_survived": 0,
+ "mutation_score": 1.0,
+ "mutation_survived_mutants": [],
+ "verification_score": 1.0,
+ "counterexample_repair_attempted": false,
+ "counterexample_repair_applied": false,
+ "counterexample_repair_error": "",
+ "mismatch_product_ids": [],
+ "failed_test_cases": [],
+ "perl_logic": "# RULE_NAME: fat_over_105g\n# SEVERITY: warning\n# COMPLEXITY: simple\n# DECLARATIVE_FRIENDLY: yes\nif ($fat > 105) {\n push @{$product_ref->{$data_quality_tags}}, \"fat-value-over-105g\";\n}",
+ "python_conversion": " - failed_rows:\n name: fat_over_105g\n expression: fat > 105",
+ "conversion_notes": "Soda Cloud unavailable/failed; used SQL-equivalent declarative parity (fast fallback). Command: soda contract verify (per-rule x12) -ds C:\\Users\\Administrator\\Downloads\\off_quality_migration_prototype\\results\\declarative_runtime\\soda\\soda_cloud\\data_source.yml -sc C:\\Users\\Administrator\\Downloads\\off_quality_migration_prototype\\results\\declarative_runtime\\soda\\soda_cloud\\soda_cloud.yml -p | Success: True | Return code: 0",
+ "conversion_provider": "soda_core_sql_fallback",
+ "conversion_execution_mode": "cloud_sql_fallback",
+ "conversion_cloud_connected": false,
+ "conversion_cloud_scan_id": "",
+ "conversion_cloud_scan_url": "https://cloud.us.soda.io/o/c9e7e376-1da2-49c5-93cb-78c6d95273ee/datasets/5e60cafe-18fc-4d01-8390-0057b49d7765"
+ },
+ {
+ "rule_name": "saturated_fat_over_105g",
+ "tag": "saturated-fat-value-over-105g",
+ "severity": "warning",
+ "condition": "saturated_fat > 105",
+ "jurisdiction": "global",
+ "profile_tags": [
+ "global",
+ "hybrid"
+ ],
+ "regulatory_type": "off_internal",
+ "legal_citation": "",
+ "source_url": "",
+ "effective_date": "",
+ "review_status": "reviewed",
+ "reviewer": "prototype",
+ "required_fields": [],
+ "exemption_logic": "none",
+ "rule_notes": "OFF-derived global rule: saturated_fat_over_105g",
+ "rule_ir": {
+ "version": "1.0",
+ "rule_name": "saturated_fat_over_105g",
+ "condition_type": "field_threshold",
+ "severity": "warning",
+ "tag": "saturated-fat-value-over-105g",
+ "left_operand": "saturated_fat",
+ "operator": ">",
+ "right_operand": 105.0
+ },
+ "rule_ir_hash": "aafe1ceddbf5",
+ "condition_type": "field_threshold",
+ "complexity": "simple",
+ "declarative_friendly": true,
+ "products_tested": 20,
+ "perl_errors": 0,
+ "python_errors": 0,
+ "supporting_violations": 0,
+ "positive_matches": 0,
+ "positive_agreement": 0.5,
+ "positive_coverage": 0.0,
+ "parity_ci_lower": 0.8389,
+ "parity_ci_upper": 1.0,
+ "coverage_ci_lower": 0.0,
+ "coverage_ci_upper": 0.1611,
+ "evidence_alpha": 1.0,
+ "evidence_beta": 1.0,
+ "evidence_posterior_mean": 0.5,
+ "evidence_ci_lower": 0.05,
+ "evidence_ci_upper": 0.95,
+ "evidence_factor": 0.05,
+ "matches": 20,
+ "mismatches": 0,
+ "confidence": 1.0,
+ "llm_confidence": 0.92,
+ "overall_confidence": 0.0386,
+ "overall_method": "llm_confidence * parity_ci_lower_95 * evidence_ci_lower_95_beta_posterior",
+ "status": "MATCH",
+ "duckdb_query": "SELECT * FROM nutrition_table WHERE saturated_fat > 105",
+ "duckdb_errors": 0,
+ "duckdb_condition": "saturated_fat > 105",
+ "duckdb_example_rows": [],
+ "equivalence_cases": 0,
+ "equivalence_matches": 0,
+ "equivalence_mismatches": 0,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_counterexamples": [],
+ "mutation_total": 0,
+ "mutation_killed": 0,
+ "mutation_survived": 0,
+ "mutation_score": 1.0,
+ "mutation_survived_mutants": [],
+ "verification_score": 1.0,
+ "counterexample_repair_attempted": false,
+ "counterexample_repair_applied": false,
+ "counterexample_repair_error": "",
+ "mismatch_product_ids": [],
+ "failed_test_cases": [],
+ "perl_logic": "# RULE_NAME: saturated_fat_over_105g\n# SEVERITY: warning\n# COMPLEXITY: simple\n# DECLARATIVE_FRIENDLY: yes\nif ($saturated_fat > 105) {\n push @{$product_ref->{$data_quality_tags}}, \"saturated-fat-value-over-105g\";\n}",
+ "python_conversion": " - failed_rows:\n name: saturated_fat_over_105g\n expression: saturated_fat > 105",
+ "conversion_notes": "Soda Cloud unavailable/failed; used SQL-equivalent declarative parity (fast fallback). Command: soda contract verify (per-rule x12) -ds C:\\Users\\Administrator\\Downloads\\off_quality_migration_prototype\\results\\declarative_runtime\\soda\\soda_cloud\\data_source.yml -sc C:\\Users\\Administrator\\Downloads\\off_quality_migration_prototype\\results\\declarative_runtime\\soda\\soda_cloud\\soda_cloud.yml -p | Success: True | Return code: 0",
+ "conversion_provider": "soda_core_sql_fallback",
+ "conversion_execution_mode": "cloud_sql_fallback",
+ "conversion_cloud_connected": false,
+ "conversion_cloud_scan_id": "",
+ "conversion_cloud_scan_url": "https://cloud.us.soda.io/o/c9e7e376-1da2-49c5-93cb-78c6d95273ee/datasets/5e60cafe-18fc-4d01-8390-0057b49d7765"
+ },
+ {
+ "rule_name": "carbohydrates_over_105g",
+ "tag": "carbohydrates-value-over-105g",
+ "severity": "warning",
+ "condition": "carbohydrates > 105",
+ "jurisdiction": "global",
+ "profile_tags": [
+ "global",
+ "hybrid"
+ ],
+ "regulatory_type": "off_internal",
+ "legal_citation": "",
+ "source_url": "",
+ "effective_date": "",
+ "review_status": "reviewed",
+ "reviewer": "prototype",
+ "required_fields": [],
+ "exemption_logic": "none",
+ "rule_notes": "OFF-derived global rule: carbohydrates_over_105g",
+ "rule_ir": {
+ "version": "1.0",
+ "rule_name": "carbohydrates_over_105g",
+ "condition_type": "field_threshold",
+ "severity": "warning",
+ "tag": "carbohydrates-value-over-105g",
+ "left_operand": "carbohydrates",
+ "operator": ">",
+ "right_operand": 105.0
+ },
+ "rule_ir_hash": "7261087f016d",
+ "condition_type": "field_threshold",
+ "complexity": "simple",
+ "declarative_friendly": true,
+ "products_tested": 20,
+ "perl_errors": 0,
+ "python_errors": 0,
+ "supporting_violations": 0,
+ "positive_matches": 0,
+ "positive_agreement": 0.5,
+ "positive_coverage": 0.0,
+ "parity_ci_lower": 0.8389,
+ "parity_ci_upper": 1.0,
+ "coverage_ci_lower": 0.0,
+ "coverage_ci_upper": 0.1611,
+ "evidence_alpha": 1.0,
+ "evidence_beta": 1.0,
+ "evidence_posterior_mean": 0.5,
+ "evidence_ci_lower": 0.05,
+ "evidence_ci_upper": 0.95,
+ "evidence_factor": 0.05,
+ "matches": 20,
+ "mismatches": 0,
+ "confidence": 1.0,
+ "llm_confidence": 0.92,
+ "overall_confidence": 0.0386,
+ "overall_method": "llm_confidence * parity_ci_lower_95 * evidence_ci_lower_95_beta_posterior",
+ "status": "MATCH",
+ "duckdb_query": "SELECT * FROM nutrition_table WHERE carbohydrates > 105",
+ "duckdb_errors": 0,
+ "duckdb_condition": "carbohydrates > 105",
+ "duckdb_example_rows": [],
+ "equivalence_cases": 0,
+ "equivalence_matches": 0,
+ "equivalence_mismatches": 0,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_counterexamples": [],
+ "mutation_total": 0,
+ "mutation_killed": 0,
+ "mutation_survived": 0,
+ "mutation_score": 1.0,
+ "mutation_survived_mutants": [],
+ "verification_score": 1.0,
+ "counterexample_repair_attempted": false,
+ "counterexample_repair_applied": false,
+ "counterexample_repair_error": "",
+ "mismatch_product_ids": [],
+ "failed_test_cases": [],
+ "perl_logic": "# RULE_NAME: carbohydrates_over_105g\n# SEVERITY: warning\n# COMPLEXITY: simple\n# DECLARATIVE_FRIENDLY: yes\nif ($carbohydrates > 105) {\n push @{$product_ref->{$data_quality_tags}}, \"carbohydrates-value-over-105g\";\n}",
+ "python_conversion": " - failed_rows:\n name: carbohydrates_over_105g\n expression: carbohydrates > 105",
+ "conversion_notes": "Soda Cloud unavailable/failed; used SQL-equivalent declarative parity (fast fallback). Command: soda contract verify (per-rule x12) -ds C:\\Users\\Administrator\\Downloads\\off_quality_migration_prototype\\results\\declarative_runtime\\soda\\soda_cloud\\data_source.yml -sc C:\\Users\\Administrator\\Downloads\\off_quality_migration_prototype\\results\\declarative_runtime\\soda\\soda_cloud\\soda_cloud.yml -p | Success: True | Return code: 0",
+ "conversion_provider": "soda_core_sql_fallback",
+ "conversion_execution_mode": "cloud_sql_fallback",
+ "conversion_cloud_connected": false,
+ "conversion_cloud_scan_id": "",
+ "conversion_cloud_scan_url": "https://cloud.us.soda.io/o/c9e7e376-1da2-49c5-93cb-78c6d95273ee/datasets/5e60cafe-18fc-4d01-8390-0057b49d7765"
+ },
+ {
+ "rule_name": "sugars_over_105g",
+ "tag": "sugars-value-over-105g",
+ "severity": "warning",
+ "condition": "sugars > 105",
+ "jurisdiction": "global",
+ "profile_tags": [
+ "global",
+ "hybrid"
+ ],
+ "regulatory_type": "off_internal",
+ "legal_citation": "",
+ "source_url": "",
+ "effective_date": "",
+ "review_status": "reviewed",
+ "reviewer": "prototype",
+ "required_fields": [],
+ "exemption_logic": "none",
+ "rule_notes": "OFF-derived global rule: sugars_over_105g",
+ "rule_ir": {
+ "version": "1.0",
+ "rule_name": "sugars_over_105g",
+ "condition_type": "field_threshold",
+ "severity": "warning",
+ "tag": "sugars-value-over-105g",
+ "left_operand": "sugars",
+ "operator": ">",
+ "right_operand": 105.0
+ },
+ "rule_ir_hash": "f4924feaa2f8",
+ "condition_type": "field_threshold",
+ "complexity": "simple",
+ "declarative_friendly": true,
+ "products_tested": 20,
+ "perl_errors": 0,
+ "python_errors": 0,
+ "supporting_violations": 0,
+ "positive_matches": 0,
+ "positive_agreement": 0.5,
+ "positive_coverage": 0.0,
+ "parity_ci_lower": 0.8389,
+ "parity_ci_upper": 1.0,
+ "coverage_ci_lower": 0.0,
+ "coverage_ci_upper": 0.1611,
+ "evidence_alpha": 1.0,
+ "evidence_beta": 1.0,
+ "evidence_posterior_mean": 0.5,
+ "evidence_ci_lower": 0.05,
+ "evidence_ci_upper": 0.95,
+ "evidence_factor": 0.05,
+ "matches": 20,
+ "mismatches": 0,
+ "confidence": 1.0,
+ "llm_confidence": 0.92,
+ "overall_confidence": 0.0386,
+ "overall_method": "llm_confidence * parity_ci_lower_95 * evidence_ci_lower_95_beta_posterior",
+ "status": "MATCH",
+ "duckdb_query": "SELECT * FROM nutrition_table WHERE sugars > 105",
+ "duckdb_errors": 0,
+ "duckdb_condition": "sugars > 105",
+ "duckdb_example_rows": [],
+ "equivalence_cases": 0,
+ "equivalence_matches": 0,
+ "equivalence_mismatches": 0,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "equivalence_counterexamples": [],
+ "mutation_total": 0,
+ "mutation_killed": 0,
+ "mutation_survived": 0,
+ "mutation_score": 1.0,
+ "mutation_survived_mutants": [],
+ "verification_score": 1.0,
+ "counterexample_repair_attempted": false,
+ "counterexample_repair_applied": false,
+ "counterexample_repair_error": "",
+ "mismatch_product_ids": [],
+ "failed_test_cases": [],
+ "perl_logic": "# RULE_NAME: sugars_over_105g\n# SEVERITY: warning\n# COMPLEXITY: simple\n# DECLARATIVE_FRIENDLY: yes\nif ($sugars > 105) {\n push @{$product_ref->{$data_quality_tags}}, \"sugars-value-over-105g\";\n}",
+ "python_conversion": " - failed_rows:\n name: sugars_over_105g\n expression: sugars > 105",
+ "conversion_notes": "Soda Cloud unavailable/failed; used SQL-equivalent declarative parity (fast fallback). Command: soda contract verify (per-rule x12) -ds C:\\Users\\Administrator\\Downloads\\off_quality_migration_prototype\\results\\declarative_runtime\\soda\\soda_cloud\\data_source.yml -sc C:\\Users\\Administrator\\Downloads\\off_quality_migration_prototype\\results\\declarative_runtime\\soda\\soda_cloud\\soda_cloud.yml -p | Success: True | Return code: 0",
+ "conversion_provider": "soda_core_sql_fallback",
+ "conversion_execution_mode": "cloud_sql_fallback",
+ "conversion_cloud_connected": false,
+ "conversion_cloud_scan_id": "",
+ "conversion_cloud_scan_url": "https://cloud.us.soda.io/o/c9e7e376-1da2-49c5-93cb-78c6d95273ee/datasets/5e60cafe-18fc-4d01-8390-0057b49d7765"
+ }
+ ],
+ "declarative_engine_run": {
+ "command": "soda contract verify (per-rule x12) -ds C:\\Users\\Administrator\\Downloads\\off_quality_migration_prototype\\results\\declarative_runtime\\soda\\soda_cloud\\data_source.yml -sc C:\\Users\\Administrator\\Downloads\\off_quality_migration_prototype\\results\\declarative_runtime\\soda\\soda_cloud\\soda_cloud.yml -p",
+ "executed": true,
+ "success": true,
+ "return_code": 0,
+ "stdout_tail": "\nergy_kj_over_3911\\\\n expression: energy_kj > 3911\\\\n\\\",\\n \\\"token\\\": \\\"****\\\"\\n}\",\n \"timestamp\": \"2026-03-19T04:58:35+00:00\",\n \"index\": 27,\n \"thread\": 6576\n },\n {\n \"level\": \"debug\",\n \"message\": \"\\ud83d\\udc4c Soda Cloud command upload_contract_file OK | X-Soda-Trace-Id:5687728576962414806\",\n \"timestamp\": \"2026-03-19T04:58:36+00:00\",\n \"index\": 28,\n \"thread\": 6576\n }\n ],\n \"sourceOwner\": \"soda-core\",\n \"contract\": {\n \"fileId\": \"55051482-c315-4894-bfae-1d3a9a712e34\",\n \"metadata\": {\n \"source\": {\n \"type\": \"local\",\n \"filePath\": \"C:\\\\Users\\\\Administrator\\\\Downloads\\\\off_quality_migration_prototype\\\\results\\\\declarative_runtime\\\\soda\\\\soda_cloud\\\\contracts\\\\energy_kj_over_3911.yml\"\n }\n }\n },\n \"postProcessingStages\": [],\n \"resultsIngestionMode\": \"full\",\n \"type\": \"sodaCoreInsertScanResults\",\n \"token\": \"****\"\n}\n\ud83d\udc4c Soda Cloud command send_contract_verification_results OK | X-Soda-Trace-Id:3497840797341852655\n\ud83d\udc4c Results sent to Soda Cloud\nTo view the dataset on Soda Cloud, see https://cloud.us.soda.io/o/c9e7e376-1da2-49c5-93cb-78c6d95273ee/datasets/5e60cafe-18fc-4d01-8390-0057b49d7765\nExiting with code 1",
+ "stderr_tail": "",
+ "mode": "cloud_sql_fallback",
+ "real_execution": false,
+ "cloud_connected": false,
+ "cloud_scan_id": "",
+ "cloud_scan_url": "https://cloud.us.soda.io/o/c9e7e376-1da2-49c5-93cb-78c6d95273ee/datasets/5e60cafe-18fc-4d01-8390-0057b49d7765",
+ "cloud_config_source": "C:\\Users\\Administrator\\Downloads\\off_quality_migration_prototype\\sc_config.yml",
+ "failed_rules": [
+ "energy_kcal_vs_kj",
+ "energy_kj_mismatch_low",
+ "energy_kj_mismatch_high",
+ "energy_kj_over_3911",
+ "energy_kj_computed_mismatch_low",
+ "energy_kj_computed_mismatch_high",
+ "saturated_fat_vs_fat",
+ "sugars_plus_starch_vs_carbohydrates",
+ "fat_over_105g",
+ "saturated_fat_over_105g",
+ "carbohydrates_over_105g",
+ "sugars_over_105g"
+ ]
+ }
+}
\ No newline at end of file
diff --git a/OFF_DataQuality/rulepacks/__init__.py b/OFF_DataQuality/rulepacks/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..fb0010857ed4de3a7c1dc110cfe5a25755a4f324
--- /dev/null
+++ b/OFF_DataQuality/rulepacks/__init__.py
@@ -0,0 +1,2 @@
+"""Rule-pack and profile helpers for migration pipeline."""
+
diff --git a/OFF_DataQuality/rulepacks/registry.py b/OFF_DataQuality/rulepacks/registry.py
new file mode 100644
index 0000000000000000000000000000000000000000..04414e4af976261c6c038b988592fa4c7ec20cbf
--- /dev/null
+++ b/OFF_DataQuality/rulepacks/registry.py
@@ -0,0 +1,208 @@
+"""Rule-pack registry for profile-aware migration runs.
+
+Profiles:
+- global: OFF-derived generic checks.
+- canada: Canada-focused checks with official-source traceability metadata.
+- hybrid: union of global + canada (default for backward compatibility).
+"""
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Dict, Iterable, List, Mapping, Sequence
+
+DEFAULT_PROFILE = "hybrid"
+SUPPORTED_PROFILES = ("global", "canada", "hybrid")
+
+CANADA_RULES = (
+ "main_language_code_missing",
+ "main_language_missing",
+ "ca_allergen_evidence_missing_ingredients_text",
+ "ca_contains_statement_without_allergen_evidence",
+ "ca_fop_required_but_symbol_missing",
+ "ca_fop_symbol_present_but_not_required",
+ "ca_fop_symbol_present_on_exempt_product",
+)
+
+
+@dataclass(frozen=True)
+class RuleProfileMetadata:
+ jurisdiction: str
+ profile_tags: List[str]
+ regulatory_type: str
+ legal_citation: str
+ source_url: str
+ effective_date: str
+ review_status: str
+ reviewer: str
+ required_fields: List[str]
+ exemption_logic: str
+ notes: str
+
+
+def _default_metadata(rule_name: str) -> RuleProfileMetadata:
+ return RuleProfileMetadata(
+ jurisdiction="global",
+ profile_tags=["global", "hybrid"],
+ regulatory_type="off_internal",
+ legal_citation="",
+ source_url="",
+ effective_date="",
+ review_status="reviewed",
+ reviewer="prototype",
+ required_fields=[],
+ exemption_logic="none",
+ notes=f"OFF-derived global rule: {rule_name}",
+ )
+
+
+RULE_PROFILE_METADATA: Dict[str, RuleProfileMetadata] = {
+ "main_language_code_missing": RuleProfileMetadata(
+ jurisdiction="ca",
+ profile_tags=["canada", "hybrid"],
+ regulatory_type="statutory",
+ legal_citation="SFCR 206(1); FDR B.01.012(2)",
+ source_url="https://laws-lois.justice.gc.ca/eng/regulations/SOR-2018-108/section-206.html",
+ effective_date="2019-01-15",
+ review_status="draft",
+ reviewer="pending-mentor-review",
+ required_fields=["lc", "lang", "language_code"],
+ exemption_logic="Not all products require bilingual labels; this prototype uses a conservative language-presence proxy.",
+ notes="Canada pack: proxy check for missing primary language code in label metadata.",
+ ),
+ "main_language_missing": RuleProfileMetadata(
+ jurisdiction="ca",
+ profile_tags=["canada", "hybrid"],
+ regulatory_type="statutory",
+ legal_citation="SFCR 206(1); FDR B.01.012(2)",
+ source_url="https://laws-lois.justice.gc.ca/eng/regulations/C.R.C.,_c._870/section-B.01.012.html",
+ effective_date="2019-01-15",
+ review_status="draft",
+ reviewer="pending-mentor-review",
+ required_fields=["lang", "language_code", "lc"],
+ exemption_logic="Prototype proxy only; legal exemptions by product class must be modeled before strict enforcement.",
+ notes="Canada pack: proxy check for missing primary language value.",
+ ),
+ "ca_allergen_evidence_missing_ingredients_text": RuleProfileMetadata(
+ jurisdiction="ca",
+ profile_tags=["canada", "hybrid"],
+ regulatory_type="statutory_proxy",
+ legal_citation="FDR B.01.010.1(2); FDR B.01.010.3",
+ source_url="https://laws-lois.justice.gc.ca/eng/regulations/C.R.C.,_c._870/section-B.01.010.1.html",
+ effective_date="2012-08-04",
+ review_status="draft",
+ reviewer="pending-mentor-review",
+ required_fields=["allergen_evidence_present", "ingredients_text_present", "ingredients_text"],
+ exemption_logic="Proxy check: flags records with allergen evidence but no ingredient text present.",
+ notes="Phase-1 Canada allergen rule using OFF-available proxy fields.",
+ ),
+ "ca_contains_statement_without_allergen_evidence": RuleProfileMetadata(
+ jurisdiction="ca",
+ profile_tags=["canada", "hybrid"],
+ regulatory_type="statutory_proxy",
+ legal_citation="FDR B.01.010.3(1)(b), (2)",
+ source_url="https://laws-lois.justice.gc.ca/eng/regulations/C.R.C.,_c._870/section-B.01.010.3.html",
+ effective_date="2012-08-04",
+ review_status="draft",
+ reviewer="pending-mentor-review",
+ required_fields=["contains_statement_present", "allergen_evidence_present"],
+ exemption_logic="Proxy check: 'contains' proxy without allergen evidence proxy.",
+ notes="Phase-1 Canada allergen consistency rule.",
+ ),
+ "ca_fop_required_but_symbol_missing": RuleProfileMetadata(
+ jurisdiction="ca",
+ profile_tags=["canada", "hybrid"],
+ regulatory_type="statutory_proxy",
+ legal_citation="FDR B.01.350(1)",
+ source_url="https://laws-lois.justice.gc.ca/eng/regulations/C.R.C.,_c._870/section-B.01.350.html",
+ effective_date="2026-01-01",
+ review_status="draft",
+ reviewer="pending-mentor-review",
+ required_fields=[
+ "fop_threshold_exceeded",
+ "fop_symbol_present",
+ "fop_exempt_proxy",
+ "product_is_prepackaged_proxy",
+ ],
+ exemption_logic="Applies only when proxy not exempt and prepackaged proxy is true.",
+ notes="Phase-1 Canada FOP threshold-vs-symbol proxy.",
+ ),
+ "ca_fop_symbol_present_but_not_required": RuleProfileMetadata(
+ jurisdiction="ca",
+ profile_tags=["canada", "hybrid"],
+ regulatory_type="guidance_proxy",
+ legal_citation="FDR B.01.350; CFIA FOP guidance",
+ source_url="https://inspection.canada.ca/en/food-labels/labelling/industry/nutrition-labelling/fop-nutrition-symbol",
+ effective_date="2026-01-01",
+ review_status="draft",
+ reviewer="pending-mentor-review",
+ required_fields=[
+ "fop_threshold_exceeded",
+ "fop_symbol_present",
+ "fop_exempt_proxy",
+ "product_is_prepackaged_proxy",
+ ],
+ exemption_logic="Proxy warning for symbol present when threshold proxy not exceeded and not exempt.",
+ notes="Phase-1 Canada FOP over-labelling consistency rule.",
+ ),
+ "ca_fop_symbol_present_on_exempt_product": RuleProfileMetadata(
+ jurisdiction="ca",
+ profile_tags=["canada", "hybrid"],
+ regulatory_type="guidance_proxy",
+ legal_citation="FDR B.01.350(5)-(15)",
+ source_url="https://laws-lois.justice.gc.ca/eng/regulations/C.R.C.,_c._870/section-B.01.350.html",
+ effective_date="2026-01-01",
+ review_status="draft",
+ reviewer="pending-mentor-review",
+ required_fields=["fop_symbol_present", "fop_exempt_proxy", "product_is_prepackaged_proxy"],
+ exemption_logic="Proxy warning on symbol presence for exempt categories.",
+ notes="Phase-1 Canada FOP exemption consistency rule.",
+ ),
+}
+
+
+def _build_profile_rule_names(all_rule_names: Iterable[str]) -> Dict[str, List[str]]:
+ names = list(all_rule_names)
+ canada_set = set(CANADA_RULES)
+ global_rules = [name for name in names if name not in canada_set]
+ canada_rules = [name for name in names if name in canada_set]
+ hybrid_rules = names
+ return {
+ "global": global_rules,
+ "canada": canada_rules,
+ "hybrid": hybrid_rules,
+ }
+
+
+def validate_profile(profile: str) -> str:
+ normalized = profile.strip().lower()
+ if normalized not in SUPPORTED_PROFILES:
+ raise ValueError(f"Unsupported profile `{profile}`. Supported: {', '.join(SUPPORTED_PROFILES)}")
+ return normalized
+
+
+def get_profile_rule_names(profile: str, all_rule_names: Sequence[str]) -> List[str]:
+ normalized = validate_profile(profile)
+ profile_map = _build_profile_rule_names(all_rule_names)
+ return list(profile_map[normalized])
+
+
+def attach_profile_metadata(rules: Sequence[Mapping[str, object]], profile: str) -> List[Dict[str, object]]:
+ validate_profile(profile)
+ out: List[Dict[str, object]] = []
+ for rule in rules:
+ rule_name = str(rule.get("rule_name", ""))
+ meta = RULE_PROFILE_METADATA.get(rule_name, _default_metadata(rule_name))
+ row = dict(rule)
+ row["jurisdiction"] = meta.jurisdiction
+ row["profile_tags"] = list(meta.profile_tags)
+ row["regulatory_type"] = meta.regulatory_type
+ row["legal_citation"] = meta.legal_citation
+ row["source_url"] = meta.source_url
+ row["effective_date"] = meta.effective_date
+ row["review_status"] = meta.review_status
+ row["reviewer"] = meta.reviewer
+ row["required_fields"] = list(meta.required_fields)
+ row["exemption_logic"] = meta.exemption_logic
+ row["rule_notes"] = meta.notes
+ out.append(row)
+ return out
diff --git a/OFF_DataQuality/tests/test_declarative_runner.py b/OFF_DataQuality/tests/test_declarative_runner.py
new file mode 100644
index 0000000000000000000000000000000000000000..a78f8f38730faec8829796e951ef7a6b547f15d0
--- /dev/null
+++ b/OFF_DataQuality/tests/test_declarative_runner.py
@@ -0,0 +1,35 @@
+from pathlib import Path
+
+from data.load_dataset import create_and_load_dataset
+from declarative import check_runners
+from extractor.perl_logic_extractor import extract_rules
+from perl_checks.legacy_checks import LEGACY_RULES, get_perl_rule_snippets
+
+
+def _run_engine(engine: str, tmp_path: Path, monkeypatch) -> None:
+ monkeypatch.setattr(check_runners.shutil, "which", lambda _: None)
+ db_path = tmp_path / f"{engine}_checks.db"
+ products = create_and_load_dataset(size=120, seed=17, db_path=db_path, source_jsonl=None)
+ rules = extract_rules(get_perl_rule_snippets(LEGACY_RULES))
+
+ result = check_runners.run_declarative_checks(
+ rules=rules,
+ products=products,
+ db_path=db_path,
+ engine=engine,
+ )
+
+ assert set(result["per_rule"].keys()) == {rule["rule_name"] for rule in rules}
+ assert set(result["conversion_metadata"].keys()) == {rule["rule_name"] for rule in rules}
+ first_rule = rules[0]["rule_name"]
+ provider = result["conversion_metadata"][first_rule]["provider"]
+ assert provider.endswith("_sql_fallback")
+
+
+def test_declarative_dbt_runner_smoke(tmp_path, monkeypatch) -> None:
+ _run_engine("dbt", tmp_path=tmp_path, monkeypatch=monkeypatch)
+
+
+def test_declarative_soda_runner_smoke(tmp_path, monkeypatch) -> None:
+ _run_engine("soda", tmp_path=tmp_path, monkeypatch=monkeypatch)
+
diff --git a/OFF_DataQuality/tests/test_deterministic_converter.py b/OFF_DataQuality/tests/test_deterministic_converter.py
new file mode 100644
index 0000000000000000000000000000000000000000..5342dbcf258dd586f2c458323353014e27fd81a1
--- /dev/null
+++ b/OFF_DataQuality/tests/test_deterministic_converter.py
@@ -0,0 +1,84 @@
+from extractor.perl_logic_extractor import extract_rules
+from migration.llm_converter import convert_rules
+from perl_checks.legacy_checks import LEGACY_RULES, get_perl_rule_snippets
+from python_checks.generated_checks import compile_generated_checks
+
+
+def test_deterministic_conversion_behaves_like_expected_templates() -> None:
+ structured_rules = extract_rules(get_perl_rule_snippets(LEGACY_RULES))
+ converted_rules = convert_rules(structured_rules, provider="simulated")
+ checks, metadata = compile_generated_checks(converted_rules)
+
+ energy_tag = checks["energy_kcal_vs_kj"]({"energy_kcal": 200.0, "energy_kj": 100.0})
+ assert energy_tag == "energy-value-in-kcal-greater-than-in-kj"
+ assert checks["energy_kcal_vs_kj"]({"energy_kcal": 50.0, "energy_kj": 100.0}) is None
+
+ sugars_tag = checks["sugars_over_105g"]({"sugars": 106.0})
+ assert sugars_tag == "sugars-value-over-105g"
+ assert checks["sugars_over_105g"]({"sugars": 104.9}) is None
+
+ low_energy_tag = checks["energy_kj_mismatch_low"]({"energy_kj": 300.0, "energy_kcal": 100.0})
+ assert low_energy_tag == "energy-value-in-kcal-does-not-match-value-in-kj-low"
+ assert checks["energy_kj_mismatch_low"]({"energy_kj": 380.0, "energy_kcal": 100.0}) is None
+
+ high_energy_tag = checks["energy_kj_mismatch_high"]({"energy_kj": 500.0, "energy_kcal": 100.0})
+ assert high_energy_tag == "energy-value-in-kcal-does-not-match-value-in-kj-high"
+ assert checks["energy_kj_mismatch_high"]({"energy_kj": 450.0, "energy_kcal": 100.0}) is None
+
+ computed_low_tag = checks["energy_kj_computed_mismatch_low"]({"energy_kj_computed": 60.0, "energy_kj": 100.0})
+ assert computed_low_tag == "energy-value-in-kj-does-not-match-value-computed-from-other-nutrients-low"
+ assert checks["energy_kj_computed_mismatch_low"]({"energy_kj_computed": 80.0, "energy_kj": 100.0}) is None
+
+ computed_high_tag = checks["energy_kj_computed_mismatch_high"]({"energy_kj_computed": 150.0, "energy_kj": 100.0})
+ assert computed_high_tag == "energy-value-in-kj-does-not-match-value-computed-from-other-nutrients-high"
+ assert checks["energy_kj_computed_mismatch_high"]({"energy_kj_computed": 130.0, "energy_kj": 100.0}) is None
+
+ sugar_starch_tag = checks["sugars_plus_starch_vs_carbohydrates"](
+ {"sugars": 12.0, "starch": 8.2, "carbohydrates": 20.0}
+ )
+ assert sugar_starch_tag == "sugars-plus-starch-greater-than-carbohydrates"
+ assert (
+ checks["sugars_plus_starch_vs_carbohydrates"]({"sugars": 8.0, "starch": 6.0, "carbohydrates": 20.0}) is None
+ )
+
+ missing_lc_tag = checks["main_language_code_missing"]({"lc": " "})
+ assert missing_lc_tag == "main-language-code-missing"
+ assert checks["main_language_code_missing"]({"lc": "en"}) is None
+
+ missing_lang_tag = checks["main_language_missing"]({"lang": ""})
+ assert missing_lang_tag == "main-language-missing"
+ assert checks["main_language_missing"]({"lang": "en"}) is None
+
+ ca_allergen_tag = checks["ca_allergen_evidence_missing_ingredients_text"](
+ {"allergen_evidence_present": 1, "ingredients_text_present": 0}
+ )
+ assert ca_allergen_tag == "ca-allergen-evidence-but-missing-ingredients-text"
+ assert (
+ checks["ca_allergen_evidence_missing_ingredients_text"](
+ {"allergen_evidence_present": 1, "ingredients_text_present": 1}
+ )
+ is None
+ )
+
+ ca_fop_missing_tag = checks["ca_fop_required_but_symbol_missing"](
+ {
+ "fop_threshold_exceeded": 1,
+ "fop_symbol_present": 0,
+ "fop_exempt_proxy": 0,
+ "product_is_prepackaged_proxy": 1,
+ }
+ )
+ assert ca_fop_missing_tag == "ca-fop-required-but-symbol-missing"
+ assert (
+ checks["ca_fop_required_but_symbol_missing"](
+ {
+ "fop_threshold_exceeded": 1,
+ "fop_symbol_present": 1,
+ "fop_exempt_proxy": 0,
+ "product_is_prepackaged_proxy": 1,
+ }
+ )
+ is None
+ )
+
+ assert metadata["energy_kcal_vs_kj"]["provider"] == "simulated"
diff --git a/OFF_DataQuality/tests/test_engine_comparison.py b/OFF_DataQuality/tests/test_engine_comparison.py
new file mode 100644
index 0000000000000000000000000000000000000000..0f40f18f1c848b42bacc143cafadd4f69824439a
--- /dev/null
+++ b/OFF_DataQuality/tests/test_engine_comparison.py
@@ -0,0 +1,42 @@
+import json
+
+from validation.engine_comparison import ENGINES, run_engine_comparison
+
+
+def test_engine_comparison_smoke(tmp_path) -> None:
+ results_path = tmp_path / "engine_comparison.json"
+ db_path = tmp_path / "engine_compare.db"
+
+ report = run_engine_comparison(
+ dataset_size=100,
+ seed=17,
+ source_jsonl=None,
+ use_default_off_source=False,
+ llm_provider="simulated",
+ llm_model=None,
+ perl_rules_dir=None,
+ db_path=db_path,
+ results_path=results_path,
+ )
+
+ assert results_path.exists()
+ parsed = json.loads(results_path.read_text(encoding="utf-8"))
+ assert parsed["engines"] == list(ENGINES)
+ assert set(parsed["per_engine_summary"].keys()) == set(ENGINES)
+ assert len(parsed["rule_comparison"]) > 0
+ assert "comparison_method" in parsed
+ assert "run_config" in parsed
+ assert "per_complexity_summary" in parsed
+ assert parsed["run_config"]["soda_mode"] == "local"
+ assert "comparison_fingerprint" in parsed
+ assert "engine_run_fingerprints" in parsed
+ assert parsed["comparison_fingerprint"]["dataset_fingerprint_consistent"] is True
+ assert parsed["comparison_fingerprint"]["rulepack_fingerprint_consistent"] is True
+ first_rule = parsed["rule_comparison"][0]
+ assert set(first_rule["engines"].keys()) == set(ENGINES)
+ assert "best_engine" in first_rule
+ assert "recommendation" in first_rule
+ assert "complexity" in first_rule
+ assert "effective_confidence" in first_rule["engines"]["python"]
+ assert "provider_factor" in first_rule["engines"]["python"]
+ assert report["engines"] == list(ENGINES)
diff --git a/OFF_DataQuality/tests/test_extractor.py b/OFF_DataQuality/tests/test_extractor.py
new file mode 100644
index 0000000000000000000000000000000000000000..3c1131f4962e847893180fd403ac4e7a8514c6cb
--- /dev/null
+++ b/OFF_DataQuality/tests/test_extractor.py
@@ -0,0 +1,54 @@
+from pathlib import Path
+
+from extractor.perl_logic_extractor import extract_rules
+from perl_checks.legacy_checks import RULE_FILES_DIR, load_rule_snippets_from_directory
+
+
+def test_extract_rules_from_perl_files() -> None:
+ snippets = load_rule_snippets_from_directory(RULE_FILES_DIR)
+ rules = extract_rules(snippets)
+
+ assert len(rules) >= 19
+ names = {rule["rule_name"] for rule in rules}
+ assert "energy_kcal_vs_kj" in names
+ assert "main_language_code_missing" in names
+ assert "energy_kj_mismatch_low" in names
+ assert "energy_kj_computed_mismatch_low" in names
+ assert "energy_kj_computed_mismatch_high" in names
+ assert "sugars_plus_starch_vs_carbohydrates" in names
+ assert "ca_fop_required_but_symbol_missing" in names
+ assert "ca_contains_statement_without_allergen_evidence" in names
+
+ missing_rule = next(rule for rule in rules if rule["rule_name"] == "main_language_code_missing")
+ assert missing_rule["condition_type"] == "missing_field"
+ assert missing_rule["duckdb_condition"] == "lc IS NULL OR TRIM(lc) = ''"
+ assert "rule_ir" in missing_rule
+ assert len(str(missing_rule.get("rule_ir_hash", ""))) == 12
+
+ affine_rule = next(rule for rule in rules if rule["rule_name"] == "energy_kj_mismatch_low")
+ assert affine_rule["condition_type"] == "affine_field_comparison"
+ assert affine_rule["complexity"] == "intricate"
+ assert affine_rule["declarative_friendly"] is False
+ assert affine_rule["scale_factor"] == 3.7
+ assert affine_rule["offset"] == -2.0
+
+ sum_rule = next(rule for rule in rules if rule["rule_name"] == "sugars_plus_starch_vs_carbohydrates")
+ assert sum_rule["condition_type"] == "sum_fields_comparison"
+ assert sum_rule["left_operands"] == ["sugars", "starch"]
+ assert sum_rule["right_operand"] == "carbohydrates"
+
+ computed_rule = next(rule for rule in rules if rule["rule_name"] == "energy_kj_computed_mismatch_low")
+ assert computed_rule["condition_type"] == "affine_field_comparison"
+ assert computed_rule["left_operand"] == "energy_kj_computed"
+ assert computed_rule["right_operand"] == "energy_kj"
+ assert computed_rule["scale_factor"] == 0.7
+ assert computed_rule["offset"] == -5.0
+
+ ca_fop_rule = next(rule for rule in rules if rule["rule_name"] == "ca_fop_required_but_symbol_missing")
+ assert ca_fop_rule["condition_type"] == "compound_threshold_and"
+ assert ca_fop_rule["complexity"] == "medium"
+
+
+def test_perl_rule_files_are_present() -> None:
+ rule_files = sorted(Path(RULE_FILES_DIR).glob("*.pl"))
+ assert len(rule_files) >= 8
diff --git a/OFF_DataQuality/tests/test_parity_smoke.py b/OFF_DataQuality/tests/test_parity_smoke.py
new file mode 100644
index 0000000000000000000000000000000000000000..b1acd9e274edad43f41fa65f3ac08b4fefa4f9bb
--- /dev/null
+++ b/OFF_DataQuality/tests/test_parity_smoke.py
@@ -0,0 +1,35 @@
+from pathlib import Path
+
+import validation.parity_validator as parity_validator
+from perl_checks.legacy_checks import load_rule_snippets_from_directory
+
+
+def test_parity_pipeline_smoke_simulated(tmp_path, monkeypatch) -> None:
+ monkeypatch.setattr(parity_validator, "DEFAULT_OFF_JSONL", tmp_path / "missing_off_source.jsonl")
+ results_path = tmp_path / "migration_results.json"
+ perl_rules_dir = Path(__file__).resolve().parent.parent / "perl_checks" / "rules"
+
+ payload = parity_validator.run_pipeline(
+ dataset_size=100,
+ seed=17,
+ results_path=results_path,
+ source_jsonl=None,
+ use_default_off_source=False,
+ db_path=tmp_path / "off_quality_test.db",
+ llm_provider="simulated",
+ perl_rules_dir=perl_rules_dir,
+ )
+
+ summary = payload["migration_summary"]
+ expected_rules = len(load_rule_snippets_from_directory(perl_rules_dir))
+ assert results_path.exists()
+ assert summary["total_rules"] == expected_rules
+ assert summary["passed_rules"] == expected_rules
+ assert summary["rules_needing_review"] == 0
+ assert "run_fingerprint" in payload
+ assert payload["run_fingerprint"]["dataset_fingerprint"]["sha256"]
+ assert payload["run_fingerprint"]["rulepack_fingerprint"]["rule_ir_sha256"]
+ first_rule = payload["rule_results"][0]
+ assert "parity_ci_lower" in first_rule
+ assert "evidence_ci_lower" in first_rule
+ assert "overall_method" in first_rule
diff --git a/OFF_DataQuality/tests/test_profiles.py b/OFF_DataQuality/tests/test_profiles.py
new file mode 100644
index 0000000000000000000000000000000000000000..4a207397af02dad401c7a85c16385d0f8033a4ff
--- /dev/null
+++ b/OFF_DataQuality/tests/test_profiles.py
@@ -0,0 +1,47 @@
+from pathlib import Path
+
+from rulepacks.registry import DEFAULT_PROFILE, SUPPORTED_PROFILES, get_profile_rule_names, validate_profile
+from validation.parity_validator import run_pipeline
+
+
+def test_profile_registry_basics() -> None:
+ assert DEFAULT_PROFILE in SUPPORTED_PROFILES
+ assert validate_profile("HYBRID") == "hybrid"
+ rule_names = [
+ "energy_kcal_vs_kj",
+ "main_language_code_missing",
+ "main_language_missing",
+ "ca_fop_required_but_symbol_missing",
+ ]
+ assert get_profile_rule_names("global", rule_names) == ["energy_kcal_vs_kj"]
+ assert get_profile_rule_names("canada", rule_names) == [
+ "main_language_code_missing",
+ "main_language_missing",
+ "ca_fop_required_but_symbol_missing",
+ ]
+ assert get_profile_rule_names("hybrid", rule_names) == rule_names
+
+
+def test_canada_profile_pipeline_subset(tmp_path, monkeypatch) -> None:
+ import validation.parity_validator as parity_validator
+
+ monkeypatch.setattr(parity_validator, "DEFAULT_OFF_JSONL", tmp_path / "missing_off_source.jsonl")
+ payload = run_pipeline(
+ dataset_size=120,
+ seed=17,
+ results_path=tmp_path / "migration_results_canada.json",
+ source_jsonl=None,
+ use_default_off_source=False,
+ db_path=tmp_path / "off_quality_canada.db",
+ llm_provider="simulated",
+ perl_rules_dir=Path(__file__).resolve().parent.parent / "perl_checks" / "rules",
+ execution_engine="python",
+ profile="canada",
+ )
+
+ assert payload["dataset"]["profile"] == "canada"
+ assert payload["migration_summary"]["total_rules"] == 7
+ jurisdictions = {row["jurisdiction"] for row in payload["rule_results"]}
+ assert jurisdictions == {"ca"}
+ citations = [str(row.get("legal_citation", "")) for row in payload["rule_results"]]
+ assert all(citation != "" for citation in citations)
diff --git a/OFF_DataQuality/tests/test_verification.py b/OFF_DataQuality/tests/test_verification.py
new file mode 100644
index 0000000000000000000000000000000000000000..76c08dee07540cb917eb4af15d536adaec24d7ff
--- /dev/null
+++ b/OFF_DataQuality/tests/test_verification.py
@@ -0,0 +1,27 @@
+from extractor.perl_logic_extractor import extract_rules
+from migration.llm_converter import convert_rules
+from perl_checks.legacy_checks import LEGACY_RULES, get_legacy_rule_map, get_perl_rule_snippets
+from python_checks.generated_checks import compile_generated_checks
+from validation.verification import run_rule_verification
+
+
+def test_rule_verification_for_deterministic_conversion() -> None:
+ structured_rules = extract_rules(get_perl_rule_snippets(LEGACY_RULES))
+ converted_rules = convert_rules(structured_rules, provider="simulated")
+ checks, metadata = compile_generated_checks(converted_rules)
+ legacy_map = get_legacy_rule_map(LEGACY_RULES)
+
+ rule = next(rule for rule in structured_rules if rule["rule_name"] == "energy_kcal_vs_kj")
+ verification = run_rule_verification(
+ rule=rule,
+ perl_evaluator=legacy_map["energy_kcal_vs_kj"].evaluator,
+ check_fn=checks["energy_kcal_vs_kj"],
+ python_code=str(metadata["energy_kcal_vs_kj"]["python_code"]),
+ function_name=str(metadata["energy_kcal_vs_kj"]["function_name"]),
+ seed=17,
+ )
+
+ assert verification["equivalence_mismatches"] == 0
+ assert verification["equivalence_status"] == "PASS"
+ assert verification["mutation_total"] >= 1
+ assert 0.0 <= float(verification["mutation_score"]) <= 1.0
diff --git a/OFF_DataQuality/validation/__init__.py b/OFF_DataQuality/validation/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/OFF_DataQuality/validation/engine_comparison.py b/OFF_DataQuality/validation/engine_comparison.py
new file mode 100644
index 0000000000000000000000000000000000000000..e205726f319f6914a06a9167532c460a8698af01
--- /dev/null
+++ b/OFF_DataQuality/validation/engine_comparison.py
@@ -0,0 +1,695 @@
+"""Compare python/dbt/soda execution engines against the same Perl baseline."""
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+import os
+from datetime import datetime, timezone
+from pathlib import Path
+from statistics import mean
+from typing import Dict, Iterable, List, Mapping, Sequence, Tuple
+from uuid import uuid4
+
+from data.load_dataset import DB_PATH, DEFAULT_OFF_JSONL
+from rulepacks.registry import DEFAULT_PROFILE, SUPPORTED_PROFILES
+from validation.parity_validator import RESULT_PATH, run_pipeline
+
+COMPARISON_PATH = Path(__file__).resolve().parent.parent / "results" / "engine_comparison.json"
+ENGINES = ("python", "dbt", "soda")
+
+
+def _line_count(text: object) -> int:
+ snippet = str(text or "").strip("\n")
+ if not snippet:
+ return 0
+ return len(snippet.splitlines())
+
+
+def _comparison_fingerprint_payload(
+ engine_payloads: Mapping[str, Mapping[str, object]],
+ generated_at_utc: str,
+) -> Dict[str, object]:
+ engine_run_ids: Dict[str, str] = {}
+ dataset_hashes: Dict[str, str] = {}
+ rulepack_hashes: Dict[str, str] = {}
+ commits: Dict[str, str] = {}
+
+ for engine, payload in engine_payloads.items():
+ run_fp = payload.get("run_fingerprint", {})
+ engine_run_ids[engine] = str(run_fp.get("run_id", ""))
+ commits[engine] = str(run_fp.get("code_commit", "unknown"))
+ dataset_fp = run_fp.get("dataset_fingerprint", {})
+ rulepack_fp = run_fp.get("rulepack_fingerprint", {})
+ dataset_hashes[engine] = str(dataset_fp.get("sha256", ""))
+ rulepack_hashes[engine] = str(rulepack_fp.get("rule_ir_sha256", ""))
+
+ dataset_unique = sorted({value for value in dataset_hashes.values() if value})
+ rulepack_unique = sorted({value for value in rulepack_hashes.values() if value})
+ commit_unique = sorted({value for value in commits.values() if value and value != "unknown"})
+
+ safe_timestamp = generated_at_utc.replace(":", "").replace("-", "").replace(".", "").replace("+", "p")
+ comparison_run_id = f"comparison_{safe_timestamp}_{uuid4().hex[:8]}"
+ comparison_sha_input = {
+ "engine_run_ids": engine_run_ids,
+ "dataset_hashes": dataset_hashes,
+ "rulepack_hashes": rulepack_hashes,
+ "generated_at_utc": generated_at_utc,
+ }
+ comparison_sha = hashlib.sha256(
+ json.dumps(comparison_sha_input, sort_keys=True, default=str, separators=(",", ":")).encode("utf-8")
+ ).hexdigest()
+
+ return {
+ "comparison_run_id": comparison_run_id,
+ "comparison_sha256": comparison_sha,
+ "engine_run_ids": engine_run_ids,
+ "dataset_fingerprint_sha256_by_engine": dataset_hashes,
+ "rulepack_fingerprint_sha256_by_engine": rulepack_hashes,
+ "dataset_fingerprint_consistent": len(dataset_unique) <= 1,
+ "rulepack_fingerprint_consistent": len(rulepack_unique) <= 1,
+ "dataset_fingerprint_sha256": dataset_unique[0] if dataset_unique else "",
+ "rulepack_fingerprint_sha256": rulepack_unique[0] if rulepack_unique else "",
+ "code_commit": commit_unique[0] if len(commit_unique) == 1 else "mixed_or_unknown",
+ "code_commits_by_engine": commits,
+ }
+
+
+def _is_fallback_provider(provider: str) -> bool:
+ return "fallback" in provider.lower()
+
+
+def _python_provider_is_real_llm(provider: str) -> bool:
+ normalized = provider.strip().lower()
+ return normalized in {"groq"}
+
+
+def _provider_factor(engine: str, provider: str) -> float:
+ normalized = provider.strip().lower()
+ if engine == "python":
+ if normalized == "groq":
+ return 1.0
+ if normalized == "simulated_fallback":
+ return 0.55
+ return 0.75
+ if engine == "dbt":
+ if normalized == "dbt_core":
+ return 1.0
+ if normalized == "dbt_core_sql_fallback":
+ return 0.85
+ return 0.9
+ if engine == "soda":
+ if normalized == "soda_cloud":
+ return 1.0
+ if normalized == "soda_core":
+ return 1.0
+ if normalized == "soda_core_sql_fallback":
+ return 0.85
+ return 0.9
+ return 0.8
+
+
+def _effective_confidence(engine: str, row: Mapping[str, object]) -> float:
+ overall = float(row.get("overall_confidence", 0.0))
+ provider = str(row.get("conversion_provider", "unknown"))
+ return overall * _provider_factor(engine, provider)
+
+
+def _is_declarative_friendly(condition: str) -> bool:
+ text = condition.strip().lower()
+ if not text:
+ return False
+ if text.startswith("missing("):
+ return True
+ return any(op in text for op in (">", "<", ">=", "<=", "==", "!="))
+
+
+def _decision_score(engine: str, row: Mapping[str, object], declarative_friendly: bool) -> float:
+ score = _effective_confidence(engine, row)
+ status = str(row.get("status", "REVIEW"))
+ mismatches = int(row.get("mismatches", 0))
+ equivalence_rate = float(row.get("equivalence_match_rate", 1.0))
+ mutation_score = float(row.get("mutation_score", 1.0))
+
+ if status != "MATCH":
+ score -= 0.25
+ score -= mismatches * 1.0
+ if engine == "python":
+ score += 0.05 * equivalence_rate
+ score += 0.05 * mutation_score
+ if str(row.get("equivalence_status", "PASS")) != "PASS":
+ score -= 0.10
+
+ if declarative_friendly and engine in {"dbt", "soda"}:
+ score += 0.035
+ if (not declarative_friendly) and engine == "python":
+ score += 0.035
+ return score
+
+
+def _status_rank(row: Mapping[str, object]) -> int:
+ return 1 if str(row.get("status", "REVIEW")) == "MATCH" else 0
+
+
+def _declarative_tie_break(
+ rule_name: str,
+ declarative_friendly: bool,
+ dbt_row: Mapping[str, object],
+ soda_row: Mapping[str, object],
+) -> Tuple[str, str, bool]:
+ """Pick best declarative engine with an explicit, balanced tie-break."""
+ dbt_score = _decision_score("dbt", dbt_row, declarative_friendly)
+ soda_score = _decision_score("soda", soda_row, declarative_friendly)
+ dbt_effective = _effective_confidence("dbt", dbt_row)
+ soda_effective = _effective_confidence("soda", soda_row)
+ dbt_overall = float(dbt_row.get("overall_confidence", 0.0))
+ soda_overall = float(soda_row.get("overall_confidence", 0.0))
+ dbt_mismatches = int(dbt_row.get("mismatches", 0))
+ soda_mismatches = int(soda_row.get("mismatches", 0))
+ dbt_status = _status_rank(dbt_row)
+ soda_status = _status_rank(soda_row)
+
+ # Primary deterministic comparison.
+ dbt_tuple = (dbt_status, -dbt_mismatches, dbt_score, dbt_effective, dbt_overall)
+ soda_tuple = (soda_status, -soda_mismatches, soda_score, soda_effective, soda_overall)
+ if dbt_tuple != soda_tuple:
+ if dbt_tuple > soda_tuple:
+ return "dbt", "declarative-rank:dbt>soda", False
+ return "soda", "declarative-rank:soda>dbt", False
+
+ # Explicit tie case: keep correctness identical, distribute ties fairly.
+ # Stable rule-name hash parity avoids always preferring dbt.
+ hash_int = int(hashlib.sha1(rule_name.encode("utf-8")).hexdigest(), 16)
+ chosen = "dbt" if hash_int % 2 == 0 else "soda"
+ reason = "explicit-hash-tie-break-even->dbt" if chosen == "dbt" else "explicit-hash-tie-break-odd->soda"
+ return chosen, reason, True
+
+
+def _engine_summary(engine: str, payload: Mapping[str, object]) -> Dict[str, object]:
+ rule_results = list(payload.get("rule_results", []))
+ if not rule_results:
+ empty = {
+ "rules": 0,
+ "passed": 0,
+ "avg_overall_confidence": 0.0,
+ "avg_effective_confidence": 0.0,
+ "avg_parity_ci_lower": 0.0,
+ "fallback_rules": 0,
+ "avg_equivalence_rate": 0.0,
+ "avg_mutation_score": 0.0,
+ }
+ if engine == "python":
+ empty["real_llm_rules"] = 0
+ empty["real_llm_rate"] = 0.0
+ empty["repairs_applied"] = 0
+ return empty
+
+ summary = {
+ "rules": len(rule_results),
+ "passed": sum(1 for row in rule_results if row.get("status") == "MATCH"),
+ "avg_overall_confidence": round(mean(float(row.get("overall_confidence", 0.0)) for row in rule_results), 4),
+ "avg_effective_confidence": round(mean(_effective_confidence(engine, row) for row in rule_results), 4),
+ "avg_parity_ci_lower": round(mean(float(row.get("parity_ci_lower", 0.0)) for row in rule_results), 4),
+ "avg_equivalence_rate": round(mean(float(row.get("equivalence_match_rate", 1.0)) for row in rule_results), 4),
+ "avg_mutation_score": round(mean(float(row.get("mutation_score", 1.0)) for row in rule_results), 4),
+ "fallback_rules": sum(
+ 1 for row in rule_results if _is_fallback_provider(str(row.get("conversion_provider", "")))
+ ),
+ }
+ if engine == "python":
+ real_llm_rules = sum(
+ 1 for row in rule_results if _python_provider_is_real_llm(str(row.get("conversion_provider", "")))
+ )
+ summary["real_llm_rules"] = real_llm_rules
+ summary["real_llm_rate"] = round(real_llm_rules / len(rule_results), 4)
+ summary["repairs_applied"] = sum(1 for row in rule_results if bool(row.get("counterexample_repair_applied")))
+ return summary
+
+
+def _best_engine_for_rule(per_engine_rows: Mapping[str, Mapping[str, object]]) -> Tuple[str, str, bool]:
+ candidate_rows: List[Tuple[str, Mapping[str, object]]] = [(engine, row) for engine, row in per_engine_rows.items()]
+ reference_row = next(iter(per_engine_rows.values()))
+ if reference_row.get("declarative_friendly") is None:
+ declarative_friendly = _is_declarative_friendly(str(reference_row.get("condition", "")))
+ else:
+ declarative_friendly = bool(reference_row.get("declarative_friendly"))
+ ranked = sorted(
+ candidate_rows,
+ key=lambda item: (
+ _decision_score(item[0], item[1], declarative_friendly),
+ _effective_confidence(item[0], item[1]),
+ float(item[1].get("overall_confidence", 0.0)),
+ ),
+ reverse=True,
+ )
+
+ rows = {engine: row for engine, row in candidate_rows}
+ python_row = rows.get("python", {})
+ python_match = str(python_row.get("status", "")) == "MATCH"
+ python_effective = _effective_confidence("python", python_row) if python_row else 0.0
+
+ dbt_row = rows.get("dbt", {})
+ soda_row = rows.get("soda", {})
+ declarative_best_engine = None
+ declarative_best_effective = 0.0
+ declarative_reason = "declarative-unavailable"
+ declarative_tie_applied = False
+ if dbt_row and soda_row:
+ declarative_best_engine, declarative_reason, declarative_tie_applied = _declarative_tie_break(
+ rule_name=str(reference_row.get("rule_name", "")),
+ declarative_friendly=declarative_friendly,
+ dbt_row=dbt_row,
+ soda_row=soda_row,
+ )
+ declarative_best_effective = _effective_confidence(declarative_best_engine, rows[declarative_best_engine])
+ elif dbt_row:
+ declarative_best_engine = "dbt"
+ declarative_best_effective = _effective_confidence("dbt", dbt_row)
+ declarative_reason = "only-dbt-available"
+ elif soda_row:
+ declarative_best_engine = "soda"
+ declarative_best_effective = _effective_confidence("soda", soda_row)
+ declarative_reason = "only-soda-available"
+
+ declarative_candidates = [
+ (engine, row)
+ for engine, row in candidate_rows
+ if engine in {"dbt", "soda"} and str(row.get("status", "")) == "MATCH"
+ ]
+ if declarative_candidates and declarative_best_engine is None:
+ declarative_best_engine, declarative_best_row = max(
+ declarative_candidates,
+ key=lambda item: _effective_confidence(item[0], item[1]),
+ )
+ declarative_best_effective = _effective_confidence(declarative_best_engine, declarative_best_row)
+ declarative_reason = "fallback-declarative-selection"
+
+ closeness_threshold = 0.20
+ if declarative_friendly and python_match and declarative_best_engine is not None:
+ if abs(python_effective - declarative_best_effective) <= closeness_threshold:
+ return (
+ declarative_best_engine,
+ f"hybrid-close-declarative:{declarative_reason}",
+ declarative_tie_applied,
+ )
+ if (not declarative_friendly) and python_match and declarative_best_engine is not None:
+ if abs(python_effective - declarative_best_effective) <= closeness_threshold:
+ return "python", "hybrid-close-procedural:prefer-python", False
+
+ top_engine = ranked[0][0]
+ if top_engine in {"dbt", "soda"} and declarative_tie_applied and declarative_best_engine in {"dbt", "soda"}:
+ return declarative_best_engine, f"explicit-declarative-tie:{declarative_reason}", True
+ return top_engine, "top-decision-score", False
+
+
+def _rule_recommendation(rule_row: Mapping[str, object], best_engine: str) -> str:
+ mismatches = int(rule_row.get("mismatches", 0))
+ condition = str(rule_row.get("condition", ""))
+ condition_type = str(rule_row.get("condition_type", ""))
+ complexity = str(rule_row.get("complexity", "unknown"))
+ equivalence_status = str(rule_row.get("equivalence_status", "PASS"))
+ if rule_row.get("declarative_friendly") is None:
+ declarative_friendly = _is_declarative_friendly(condition)
+ else:
+ declarative_friendly = bool(rule_row.get("declarative_friendly"))
+ provider = str(rule_row.get("conversion_provider", ""))
+ if mismatches > 0:
+ return "Needs manual review; parity mismatches exist."
+ if _is_fallback_provider(provider):
+ return (
+ f"{best_engine} currently wins, but provider is fallback. "
+ "Enable real engine execution to confirm this choice."
+ )
+ if best_engine == "python" and equivalence_status != "PASS":
+ return "Python rule failed equivalence checks; inspect counterexamples before accepting."
+ if best_engine in {"dbt", "soda"} and declarative_friendly:
+ return "Declarative-friendly rule; prefer dbt/soda for readability and operations."
+ if best_engine == "python" and "fallback" in provider.lower():
+ return "Use python path with caution; conversion fell back and needs prompt/model tuning."
+ if best_engine == "python" and complexity in {"medium", "intricate"}:
+ return (
+ f"Procedural preference: rule is {complexity} ({condition_type}). "
+ "Python migration is preferred under current evidence."
+ )
+ if best_engine == "python":
+ return "Keep procedural Python migration path for this rule."
+ return f"Prefer {best_engine} for this rule under current evidence."
+
+
+def _build_complexity_summary(rule_comparison: Sequence[Mapping[str, object]]) -> Dict[str, Dict[str, object]]:
+ summary: Dict[str, Dict[str, object]] = {}
+ for tier in ("simple", "medium", "intricate", "unknown"):
+ tier_rows = [row for row in rule_comparison if str(row.get("complexity", "unknown")) == tier]
+ if not tier_rows:
+ continue
+ wins = {"python": 0, "dbt": 0, "soda": 0}
+ for row in tier_rows:
+ wins[str(row.get("best_engine", "python"))] += 1
+ summary[tier] = {
+ "rules": len(tier_rows),
+ "python_wins": wins["python"],
+ "dbt_wins": wins["dbt"],
+ "soda_wins": wins["soda"],
+ "avg_best_effective_confidence": round(
+ mean(
+ float(row.get("engines", {}).get(str(row.get("best_engine")), {}).get("effective_confidence", 0.0))
+ for row in tier_rows
+ ),
+ 4,
+ ),
+ }
+ return summary
+
+
+def _build_rule_comparison(engine_payloads: Mapping[str, Mapping[str, object]]) -> List[Dict[str, object]]:
+ rows_by_engine_and_rule: Dict[str, Dict[str, Mapping[str, object]]] = {}
+ for engine, payload in engine_payloads.items():
+ row_map: Dict[str, Mapping[str, object]] = {}
+ for row in payload.get("rule_results", []):
+ row_map[str(row["rule_name"])] = row
+ rows_by_engine_and_rule[engine] = row_map
+
+ rule_names = sorted(set().union(*(set(m.keys()) for m in rows_by_engine_and_rule.values())))
+ results: List[Dict[str, object]] = []
+
+ for rule_name in rule_names:
+ per_engine: Dict[str, Mapping[str, object]] = {
+ engine: rows_by_engine_and_rule[engine][rule_name]
+ for engine in ENGINES
+ if rule_name in rows_by_engine_and_rule[engine]
+ }
+ if not per_engine:
+ continue
+ best_engine, selection_reason, tie_break_applied = _best_engine_for_rule(per_engine)
+ reference = next(iter(per_engine.values()))
+
+ rule_out: Dict[str, object] = {
+ "rule_name": rule_name,
+ "tag": reference.get("tag"),
+ "severity": reference.get("severity"),
+ "condition": reference.get("condition"),
+ "jurisdiction": reference.get("jurisdiction", "global"),
+ "profile_tags": list(reference.get("profile_tags", [])),
+ "regulatory_type": reference.get("regulatory_type", ""),
+ "legal_citation": reference.get("legal_citation", ""),
+ "source_url": reference.get("source_url", ""),
+ "effective_date": reference.get("effective_date", ""),
+ "review_status": reference.get("review_status", ""),
+ "reviewer": reference.get("reviewer", ""),
+ "required_fields": list(reference.get("required_fields", [])),
+ "exemption_logic": reference.get("exemption_logic", ""),
+ "rule_notes": reference.get("rule_notes", ""),
+ "rule_ir_hash": reference.get("rule_ir_hash"),
+ "condition_type": reference.get("condition_type", "unknown"),
+ "complexity": reference.get("complexity", "unknown"),
+ "declarative_friendly": (
+ _is_declarative_friendly(str(reference.get("condition", "")))
+ if reference.get("declarative_friendly") is None
+ else bool(reference.get("declarative_friendly"))
+ ),
+ "products_tested": reference.get("products_tested"),
+ "best_engine": best_engine,
+ "selection_reason": selection_reason,
+ "declarative_tie_break_applied": tie_break_applied,
+ "recommendation": _rule_recommendation(per_engine[best_engine], best_engine),
+ "engines": {},
+ }
+ for engine, row in per_engine.items():
+ conversion_text = row.get("python_conversion", "")
+ provider = str(row.get("conversion_provider", "unknown"))
+ provider_factor = _provider_factor(engine, provider)
+ effective = _effective_confidence(engine, row)
+ rule_out["engines"][engine] = {
+ "status": row.get("status"),
+ "mismatches": row.get("mismatches"),
+ "parity_ci_lower": row.get("parity_ci_lower"),
+ "overall_confidence": row.get("overall_confidence"),
+ "equivalence_match_rate": row.get("equivalence_match_rate", 1.0),
+ "equivalence_status": row.get("equivalence_status", "PASS"),
+ "equivalence_cases": row.get("equivalence_cases", 0),
+ "mutation_score": row.get("mutation_score", 1.0),
+ "mutation_total": row.get("mutation_total", 0),
+ "mutation_killed": row.get("mutation_killed", 0),
+ "verification_score": row.get("verification_score", 1.0),
+ "counterexample_repair_applied": row.get("counterexample_repair_applied", False),
+ "equivalence_counterexamples": row.get("equivalence_counterexamples", []),
+ "effective_confidence": round(effective, 4),
+ "provider_factor": round(provider_factor, 4),
+ "real_llm_used": _python_provider_is_real_llm(provider) if engine == "python" else None,
+ "decision_score": round(_decision_score(engine, row, rule_out["declarative_friendly"]), 4),
+ "conversion_provider": provider,
+ "conversion_notes": row.get("conversion_notes", ""),
+ "execution_mode": row.get("conversion_execution_mode", ""),
+ "cloud_connected": bool(row.get("conversion_cloud_connected", False)),
+ "cloud_scan_id": row.get("conversion_cloud_scan_id", ""),
+ "cloud_scan_url": row.get("conversion_cloud_scan_url", ""),
+ "conversion_artifact": conversion_text,
+ "conversion_lines": _line_count(conversion_text),
+ "failed_test_cases": row.get("failed_test_cases", []),
+ }
+ results.append(rule_out)
+ return results
+
+
+def _run_for_engines(
+ dataset_size: int,
+ seed: int,
+ source_jsonl: Path | None,
+ use_default_off_source: bool,
+ llm_provider: str,
+ llm_model: str | None,
+ perl_rules_dir: Path | None,
+ db_path: Path,
+ profile: str,
+ soda_mode: str,
+) -> Dict[str, Dict[str, object]]:
+ engine_payloads: Dict[str, Dict[str, object]] = {}
+ temp_results_dir = RESULT_PATH.parent / "tmp_engine_runs"
+ temp_results_dir.mkdir(parents=True, exist_ok=True)
+
+ for engine in ENGINES:
+ engine_results_path = temp_results_dir / f"migration_results_{engine}.json"
+ payload = run_pipeline(
+ dataset_size=dataset_size,
+ seed=seed,
+ results_path=engine_results_path,
+ source_jsonl=source_jsonl,
+ use_default_off_source=use_default_off_source,
+ db_path=db_path,
+ llm_provider=llm_provider,
+ llm_model=llm_model,
+ perl_rules_dir=perl_rules_dir,
+ execution_engine=engine,
+ soda_mode=soda_mode,
+ profile=profile,
+ )
+ engine_payloads[engine] = payload
+ return engine_payloads
+
+
+def run_engine_comparison(
+ dataset_size: int = 300,
+ seed: int = 17,
+ source_jsonl: Path | None = None,
+ use_default_off_source: bool = True,
+ llm_provider: str = "groq",
+ llm_model: str | None = None,
+ perl_rules_dir: Path | None = None,
+ db_path: Path = DB_PATH,
+ results_path: Path = COMPARISON_PATH,
+ require_real_llm: bool = False,
+ profile: str = DEFAULT_PROFILE,
+ soda_mode: str = "local",
+) -> Dict[str, object]:
+ """Run all engines and emit a rule-by-rule comparison report."""
+ engine_payloads = _run_for_engines(
+ dataset_size=dataset_size,
+ seed=seed,
+ source_jsonl=source_jsonl,
+ use_default_off_source=use_default_off_source,
+ llm_provider=llm_provider,
+ llm_model=llm_model,
+ perl_rules_dir=perl_rules_dir,
+ db_path=db_path,
+ profile=profile,
+ soda_mode=soda_mode,
+ )
+ if require_real_llm:
+ python_rows = list(engine_payloads.get("python", {}).get("rule_results", []))
+ non_llm_rules = [
+ str(row.get("rule_name"))
+ for row in python_rows
+ if not _python_provider_is_real_llm(str(row.get("conversion_provider", "")))
+ ]
+ if non_llm_rules:
+ raise RuntimeError(
+ "Real LLM mode is enabled, but python engine used fallback/non-LLM providers "
+ f"for rules: {', '.join(non_llm_rules)}. "
+ "Set GROQ_API_KEY and verify model access."
+ )
+
+ dataset_meta = engine_payloads["python"].get("dataset", {})
+ per_engine_summary = {engine: _engine_summary(engine, payload) for engine, payload in engine_payloads.items()}
+ rule_comparison = _build_rule_comparison(engine_payloads)
+ complexity_summary = _build_complexity_summary(rule_comparison)
+ generated_at_utc = datetime.now(timezone.utc).isoformat()
+ comparison_fingerprint = _comparison_fingerprint_payload(
+ engine_payloads=engine_payloads,
+ generated_at_utc=generated_at_utc,
+ )
+
+ report = {
+ "generated_at_utc": generated_at_utc,
+ "comparison_fingerprint": comparison_fingerprint,
+ "comparison_method": {
+ "best_engine_ranking": (
+ "Prefer MATCH status, then fewer mismatches, then higher effective_confidence. "
+ "effective_confidence = overall_confidence * provider_factor."
+ ),
+ "decision_score": (
+ "decision_score = effective_confidence "
+ "+ architecture_bonus(declarative for simple rules / python for complex rules) "
+ "- mismatch_penalty - review_penalty."
+ ),
+ "hybrid_tie_break": (
+ "If python and best declarative engine are close (within 0.20 effective confidence): "
+ "prefer declarative for declarative-friendly rules, prefer python for non-declarative rules."
+ ),
+ "declarative_tie_break": (
+ "When dbt and soda are exactly tied on status/mismatches/scores for a rule, "
+ "use a stable hash of rule_name to select dbt or soda explicitly."
+ ),
+ "provider_factor_notes": {
+ "python_real_llm": 1.0,
+ "python_simulated_fallback": 0.55,
+ "dbt_sql_fallback": 0.85,
+ "soda_cloud": 1.0,
+ "soda_sql_fallback": 0.85,
+ },
+ },
+ "dataset": dataset_meta,
+ "engines": list(ENGINES),
+ "engine_run_fingerprints": {
+ engine: payload.get("run_fingerprint", {})
+ for engine, payload in engine_payloads.items()
+ },
+ "per_engine_summary": per_engine_summary,
+ "per_complexity_summary": complexity_summary,
+ "rule_comparison": rule_comparison,
+ "run_config": {
+ "llm_provider": llm_provider,
+ "llm_model": llm_model,
+ "require_real_llm": require_real_llm,
+ "groq_api_key_set": bool(os.getenv("GROQ_API_KEY")),
+ "profile": profile,
+ "dataset_size": dataset_size,
+ "seed": seed,
+ "mode": "off" if use_default_off_source else "synthetic",
+ "source_jsonl": str(source_jsonl) if source_jsonl else "",
+ "soda_mode": soda_mode,
+ "soda_cloud_credentials_set": bool(
+ os.getenv("SODA_CLOUD_API_KEY_ID")
+ and os.getenv("SODA_CLOUD_API_KEY_SECRET")
+ and os.getenv("SODA_CLOUD_HOST")
+ ),
+ },
+ }
+
+ results_path.parent.mkdir(parents=True, exist_ok=True)
+ with results_path.open("w", encoding="utf-8") as handle:
+ json.dump(report, handle, indent=2)
+ return report
+
+
+def parse_args() -> argparse.Namespace:
+ parser = argparse.ArgumentParser(description="Compare python/dbt/soda engines for rule migration parity.")
+ parser.add_argument("--size", type=int, default=300, help="Number of products to test.")
+ parser.add_argument("--seed", type=int, default=17, help="Seed for synthetic mode.")
+ parser.add_argument(
+ "--mode",
+ choices=["off", "synthetic"],
+ default="off" if DEFAULT_OFF_JSONL.exists() else "synthetic",
+ help="Dataset source mode: off (JSONL) or synthetic.",
+ )
+ parser.add_argument(
+ "--source-jsonl",
+ type=Path,
+ default=DEFAULT_OFF_JSONL if DEFAULT_OFF_JSONL.exists() else None,
+ help="OFF JSONL path (used when --mode off).",
+ )
+ parser.add_argument(
+ "--llm-provider",
+ choices=["simulated", "groq"],
+ default="groq",
+ help="LLM provider for python execution engine.",
+ )
+ parser.add_argument("--llm-model", default=None, help="Optional model override for selected LLM provider.")
+ parser.add_argument("--perl-rules-dir", type=Path, default=None, help="Optional directory of .pl snippets.")
+ parser.add_argument(
+ "--profile",
+ choices=list(SUPPORTED_PROFILES),
+ default=DEFAULT_PROFILE,
+ help="Rule-pack profile to compare: global, canada, or hybrid.",
+ )
+ parser.add_argument("--results-path", type=Path, default=COMPARISON_PATH, help="Output comparison JSON path.")
+ parser.add_argument(
+ "--require-real-llm",
+ action="store_true",
+ help="Fail if python engine did not use real LLM providers (no simulated fallback allowed).",
+ )
+ parser.add_argument(
+ "--soda-mode",
+ choices=["local", "cloud"],
+ default="local",
+ help="Soda execution mode for soda engine runs.",
+ )
+ return parser.parse_args()
+
+
+def main() -> None:
+ args = parse_args()
+ use_off_mode = args.mode == "off"
+ source_jsonl = args.source_jsonl if use_off_mode else None
+
+ report = run_engine_comparison(
+ dataset_size=args.size,
+ seed=args.seed,
+ source_jsonl=source_jsonl,
+ use_default_off_source=use_off_mode,
+ llm_provider=args.llm_provider,
+ llm_model=args.llm_model,
+ perl_rules_dir=args.perl_rules_dir,
+ results_path=args.results_path,
+ require_real_llm=args.require_real_llm,
+ profile=args.profile,
+ soda_mode=args.soda_mode,
+ )
+ print(f"Engines compared: {', '.join(report['engines'])}")
+ for engine, summary in report["per_engine_summary"].items():
+ print(
+ f"{engine}: passed {summary['passed']}/{summary['rules']}, "
+ f"avg_overall={summary['avg_overall_confidence']:.2%}, "
+ f"avg_effective={summary['avg_effective_confidence']:.2%}, "
+ f"fallback_rules={summary['fallback_rules']}"
+ )
+ if report.get("run_config"):
+ print(
+ "LLM key status: "
+ f"GROQ_API_KEY={report['run_config']['groq_api_key_set']}"
+ )
+ if report.get("dataset"):
+ print(f"Profile: {report['dataset'].get('profile', DEFAULT_PROFILE)}")
+ print(f"Soda mode: {args.soda_mode}")
+ if report.get("comparison_fingerprint"):
+ fingerprint = report["comparison_fingerprint"]
+ print(f"Comparison run ID: {fingerprint.get('comparison_run_id', 'n/a')}")
+ print(
+ "Fingerprints: "
+ f"dataset={str(fingerprint.get('dataset_fingerprint_sha256', ''))[:16]} | "
+ f"rulepack={str(fingerprint.get('rulepack_fingerprint_sha256', ''))[:16]}"
+ )
+ print(f"Comparison written to: {args.results_path}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/OFF_DataQuality/validation/parity_validator.py b/OFF_DataQuality/validation/parity_validator.py
new file mode 100644
index 0000000000000000000000000000000000000000..79533e7d627ec3418664aa9f38d8687234b48227
--- /dev/null
+++ b/OFF_DataQuality/validation/parity_validator.py
@@ -0,0 +1,706 @@
+"""Back-to-back validation engine for Perl-to-Python rule migration."""
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+import math
+import subprocess
+from datetime import datetime, timezone
+from pathlib import Path
+from statistics import mean
+from typing import Dict, List, Mapping, Sequence, Set
+from uuid import uuid4
+
+from declarative.check_runners import run_declarative_checks
+from data.load_dataset import (
+ DB_PATH,
+ DEFAULT_OFF_JSONL,
+ SAMPLE_FILE,
+ create_and_load_dataset,
+)
+from duckdb_utils.create_tables import count_violations, sample_violations
+from extractor.perl_logic_extractor import extract_rules
+from migration.llm_converter import convert_rules, repair_conversion_with_counterexamples
+from perl_checks.legacy_checks import LEGACY_RULES, get_legacy_rule_map, get_perl_rule_snippets, run_perl_checks
+from python_checks.generated_checks import compile_generated_checks
+from rulepacks.registry import DEFAULT_PROFILE, SUPPORTED_PROFILES, attach_profile_metadata, get_profile_rule_names, validate_profile
+from validation.verification import run_rule_verification
+
+RESULT_PATH = Path(__file__).resolve().parent.parent / "results" / "migration_results.json"
+TABLE_NAME = "nutrition_table"
+
+
+def _sha256_text(text: str) -> str:
+ return hashlib.sha256(text.encode("utf-8")).hexdigest()
+
+
+def _sha256_json(payload: object) -> str:
+ normalized = json.dumps(payload, sort_keys=True, default=str, separators=(",", ":"))
+ return _sha256_text(normalized)
+
+
+def _resolve_git_commit() -> str:
+ try:
+ completed = subprocess.run(
+ ["git", "rev-parse", "HEAD"],
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ check=False,
+ timeout=5,
+ )
+ if completed.returncode == 0:
+ value = (completed.stdout or "").strip()
+ if value:
+ return value
+ except Exception:
+ pass
+ return "unknown"
+
+
+def _dataset_fingerprint_payload(
+ products: Sequence[Mapping[str, object]],
+ source_path: Path | None,
+ dataset_size: int,
+ seed: int,
+) -> Dict[str, object]:
+ normalized_products = [
+ {key: product.get(key) for key in sorted(product.keys())}
+ for product in sorted(products, key=lambda row: str(row.get("product_id", "")))
+ ]
+ product_ids = [str(product.get("product_id", "")) for product in normalized_products if product.get("product_id")]
+ source_mode = "off_jsonl" if source_path else "synthetic"
+ payload = {
+ "source_mode": source_mode,
+ "source_jsonl": str(source_path) if source_path else "synthetic",
+ "requested_size": int(dataset_size),
+ "products_tested": len(normalized_products),
+ "seed": int(seed) if source_mode == "synthetic" else None,
+ "product_id_first": product_ids[0] if product_ids else None,
+ "product_id_last": product_ids[-1] if product_ids else None,
+ "sha256": _sha256_json(normalized_products),
+ }
+ return payload
+
+
+def _rulepack_fingerprint_payload(structured_rules: Sequence[Mapping[str, object]], profile_name: str) -> Dict[str, object]:
+ rule_names = sorted(str(rule.get("rule_name", "")) for rule in structured_rules)
+ ir_hashes = sorted(str(rule.get("rule_ir_hash", "")) for rule in structured_rules)
+ payload = {
+ "profile": profile_name,
+ "rule_count": len(structured_rules),
+ "rule_names_sha256": _sha256_json(rule_names),
+ "rule_ir_sha256": _sha256_json(ir_hashes),
+ }
+ return payload
+
+
+def _wilson_interval(successes: int, trials: int, z: float = 1.96) -> tuple[float, float]:
+ """Return two-sided Wilson score interval for a binomial proportion."""
+ if trials <= 0:
+ return 0.0, 1.0
+ p = successes / trials
+ z2 = z * z
+ denom = 1.0 + (z2 / trials)
+ center = (p + (z2 / (2.0 * trials))) / denom
+ margin = (z * (((p * (1.0 - p)) + (z2 / (4.0 * trials))) / trials) ** 0.5) / denom
+ lower = max(0.0, center - margin)
+ upper = min(1.0, center + margin)
+ return lower, upper
+
+
+def _beta_continued_fraction(a: float, b: float, x: float, max_iter: int = 400, eps: float = 3e-12) -> float:
+ """Continued fraction helper for incomplete beta evaluation."""
+ qab = a + b
+ qap = a + 1.0
+ qam = a - 1.0
+ c = 1.0
+ d = 1.0 - (qab * x / qap)
+ if abs(d) < 1e-30:
+ d = 1e-30
+ d = 1.0 / d
+ h = d
+
+ for m in range(1, max_iter + 1):
+ m2 = 2 * m
+ aa = (m * (b - m) * x) / ((qam + m2) * (a + m2))
+ d = 1.0 + aa * d
+ if abs(d) < 1e-30:
+ d = 1e-30
+ c = 1.0 + aa / c
+ if abs(c) < 1e-30:
+ c = 1e-30
+ d = 1.0 / d
+ h *= d * c
+
+ aa = (-(a + m) * (qab + m) * x) / ((a + m2) * (qap + m2))
+ d = 1.0 + aa * d
+ if abs(d) < 1e-30:
+ d = 1e-30
+ c = 1.0 + aa / c
+ if abs(c) < 1e-30:
+ c = 1e-30
+ d = 1.0 / d
+ delta = d * c
+ h *= delta
+ if abs(delta - 1.0) < eps:
+ break
+
+ return h
+
+
+def _regularized_incomplete_beta(a: float, b: float, x: float) -> float:
+ """Regularized incomplete beta I_x(a,b) in [0,1]."""
+ if x <= 0.0:
+ return 0.0
+ if x >= 1.0:
+ return 1.0
+
+ bt = math.exp(
+ math.lgamma(a + b)
+ - math.lgamma(a)
+ - math.lgamma(b)
+ + a * math.log(x)
+ + b * math.log(1.0 - x)
+ )
+
+ if x < (a + 1.0) / (a + b + 2.0):
+ return bt * _beta_continued_fraction(a, b, x) / a
+ return 1.0 - (bt * _beta_continued_fraction(b, a, 1.0 - x) / b)
+
+
+def _beta_ppf(probability: float, alpha: float, beta: float, tol: float = 1e-7, max_iter: int = 200) -> float:
+ """Inverse CDF for Beta(alpha, beta) using monotonic bisection."""
+ p = min(1.0, max(0.0, probability))
+ lo = 0.0
+ hi = 1.0
+ for _ in range(max_iter):
+ mid = (lo + hi) / 2.0
+ cdf_mid = _regularized_incomplete_beta(alpha, beta, mid)
+ if abs(cdf_mid - p) < tol:
+ return mid
+ if cdf_mid < p:
+ lo = mid
+ else:
+ hi = mid
+ return (lo + hi) / 2.0
+
+
+def _run_python_checks(
+ products: Sequence[Mapping[str, object]],
+ structured_rules: Sequence[Dict[str, object]],
+ python_checks: Dict[str, object],
+) -> Dict[str, Dict[str, object]]:
+ rule_names = [str(rule["rule_name"]) for rule in structured_rules]
+ per_rule_products: Dict[str, Set[str]] = {rule_name: set() for rule_name in rule_names}
+ per_product_tags: Dict[str, List[str]] = {}
+
+ for product in products:
+ product_id = str(product.get("product_id"))
+ tags: List[str] = []
+ for rule in structured_rules:
+ rule_name = str(rule["rule_name"])
+ check_fn = python_checks[rule_name]
+ tag = check_fn(product)
+ if tag:
+ tags.append(str(tag))
+ per_rule_products[rule_name].add(product_id)
+ per_product_tags[product_id] = tags
+
+ return {
+ "per_product": per_product_tags,
+ "per_rule": {name: sorted(ids) for name, ids in per_rule_products.items()},
+ }
+
+
+def _run_python_verification(
+ structured_rules: Sequence[Dict[str, object]],
+ python_checks: Mapping[str, object],
+ conversion_metadata: Mapping[str, Mapping[str, object]],
+ seed: int,
+ legacy_rules: Sequence[object],
+) -> Dict[str, Dict[str, object]]:
+ legacy_map = get_legacy_rule_map(legacy_rules)
+ verification_by_rule: Dict[str, Dict[str, object]] = {}
+ for rule in structured_rules:
+ rule_name = str(rule["rule_name"])
+ legacy_rule = legacy_map.get(rule_name)
+ if legacy_rule is None:
+ verification_by_rule[rule_name] = {
+ "equivalence_cases": 0,
+ "equivalence_matches": 0,
+ "equivalence_mismatches": 0,
+ "equivalence_match_rate": 1.0,
+ "equivalence_status": "PASS",
+ "counterexamples": [],
+ "mutation_total": 0,
+ "mutation_killed": 0,
+ "mutation_survived": 0,
+ "mutation_score": 1.0,
+ "mutation_survived_mutants": [],
+ "verification_score": 1.0,
+ }
+ continue
+ verification_by_rule[rule_name] = run_rule_verification(
+ rule=rule,
+ perl_evaluator=legacy_rule.evaluator,
+ check_fn=python_checks[rule_name],
+ python_code=str(conversion_metadata[rule_name]["python_code"]),
+ function_name=str(conversion_metadata[rule_name]["function_name"]),
+ seed=seed,
+ )
+ return verification_by_rule
+
+
+def _build_failed_case_rows(
+ mismatch_ids: Sequence[str],
+ product_map: Dict[str, Mapping[str, object]],
+ perl_ids: Set[str],
+ python_ids: Set[str],
+ limit: int = 10,
+) -> List[Dict[str, object]]:
+ rows: List[Dict[str, object]] = []
+ for product_id in mismatch_ids[:limit]:
+ product = dict(product_map[product_id])
+ rows.append(
+ {
+ "product_id": product_id,
+ "perl_triggered": product_id in perl_ids,
+ "python_triggered": product_id in python_ids,
+ "energy_kj": product.get("energy_kj"),
+ "energy_kj_computed": product.get("energy_kj_computed"),
+ "energy_kcal": product.get("energy_kcal"),
+ "fat": product.get("fat"),
+ "saturated_fat": product.get("saturated_fat"),
+ "carbohydrates": product.get("carbohydrates"),
+ "sugars": product.get("sugars"),
+ "starch": product.get("starch"),
+ "sodium": product.get("sodium"),
+ "ingredients_text_present": product.get("ingredients_text_present"),
+ "contains_statement_present": product.get("contains_statement_present"),
+ "allergen_evidence_present": product.get("allergen_evidence_present"),
+ "fop_threshold_exceeded": product.get("fop_threshold_exceeded"),
+ "fop_symbol_present": product.get("fop_symbol_present"),
+ "fop_exempt_proxy": product.get("fop_exempt_proxy"),
+ "product_is_prepackaged_proxy": product.get("product_is_prepackaged_proxy"),
+ "lc": product.get("lc"),
+ "lang": product.get("lang"),
+ "language_code": product.get("language_code"),
+ }
+ )
+ return rows
+
+
+def _compute_rule_result(
+ rule: Dict[str, object],
+ perl_rule_products: Sequence[str],
+ python_rule_products: Sequence[str],
+ product_map: Dict[str, Mapping[str, object]],
+ conversion_meta: Dict[str, object],
+ verification_meta: Mapping[str, object] | None = None,
+ db_path: Path = DB_PATH,
+) -> Dict[str, object]:
+ product_ids = set(product_map)
+ perl_ids = set(perl_rule_products)
+ python_ids = set(python_rule_products)
+ supporting_ids = perl_ids | python_ids
+
+ matching_products = {
+ product_id
+ for product_id in product_ids
+ if (product_id in perl_ids) == (product_id in python_ids)
+ }
+ mismatch_ids = sorted(product_ids - matching_products)
+ total_tests = len(product_ids)
+ supporting_violations = len(supporting_ids)
+ positive_matches = len(perl_ids & python_ids)
+ positive_coverage = (supporting_violations / total_tests) if total_tests else 0.0
+
+ parity_confidence = (len(matching_products) / total_tests) if total_tests else 1.0
+ parity_ci_lower, parity_ci_upper = _wilson_interval(len(matching_products), total_tests)
+ coverage_ci_lower, coverage_ci_upper = _wilson_interval(supporting_violations, total_tests)
+ positive_agreement = (positive_matches / supporting_violations) if supporting_violations else 0.5
+ evidence_alpha = positive_matches + 1.0
+ evidence_beta = (supporting_violations - positive_matches) + 1.0
+ # Posterior mean for reference.
+ evidence_posterior_mean = evidence_alpha / (evidence_alpha + evidence_beta)
+ # Conservative 95% lower credible bound.
+ evidence_ci_lower = _beta_ppf(0.05, evidence_alpha, evidence_beta)
+ evidence_ci_upper = _beta_ppf(0.95, evidence_alpha, evidence_beta)
+ llm_confidence = float(conversion_meta["llm_confidence"])
+ overall_confidence = llm_confidence * parity_ci_lower * evidence_ci_lower
+ status = "MATCH" if not mismatch_ids else "REVIEW"
+
+ duckdb_condition = str(rule["duckdb_condition"])
+ duckdb_error_count = count_violations(duckdb_condition, db_path=db_path)
+ duckdb_examples = sample_violations(duckdb_condition, limit=5, db_path=db_path)
+ verification = dict(verification_meta or {})
+
+ return {
+ "rule_name": rule["rule_name"],
+ "tag": rule["tag"],
+ "severity": rule["severity"],
+ "condition": rule["condition"],
+ "jurisdiction": rule.get("jurisdiction", "global"),
+ "profile_tags": list(rule.get("profile_tags", [])),
+ "regulatory_type": rule.get("regulatory_type", ""),
+ "legal_citation": rule.get("legal_citation", ""),
+ "source_url": rule.get("source_url", ""),
+ "effective_date": rule.get("effective_date", ""),
+ "review_status": rule.get("review_status", ""),
+ "reviewer": rule.get("reviewer", ""),
+ "required_fields": list(rule.get("required_fields", [])),
+ "exemption_logic": rule.get("exemption_logic", ""),
+ "rule_notes": rule.get("rule_notes", ""),
+ "rule_ir": rule.get("rule_ir"),
+ "rule_ir_hash": rule.get("rule_ir_hash"),
+ "condition_type": rule.get("condition_type", "unknown"),
+ "complexity": rule.get("complexity", "unknown"),
+ "declarative_friendly": rule.get("declarative_friendly"),
+ "products_tested": total_tests,
+ "perl_errors": len(perl_ids),
+ "python_errors": len(python_ids),
+ "supporting_violations": supporting_violations,
+ "positive_matches": positive_matches,
+ "positive_agreement": round(positive_agreement, 4),
+ "positive_coverage": round(positive_coverage, 4),
+ "parity_ci_lower": round(parity_ci_lower, 4),
+ "parity_ci_upper": round(parity_ci_upper, 4),
+ "coverage_ci_lower": round(coverage_ci_lower, 4),
+ "coverage_ci_upper": round(coverage_ci_upper, 4),
+ "evidence_alpha": round(evidence_alpha, 4),
+ "evidence_beta": round(evidence_beta, 4),
+ "evidence_posterior_mean": round(evidence_posterior_mean, 4),
+ "evidence_ci_lower": round(evidence_ci_lower, 4),
+ "evidence_ci_upper": round(evidence_ci_upper, 4),
+ # Back-compat alias for old dashboards/scripts.
+ "evidence_factor": round(evidence_ci_lower, 4),
+ "matches": len(matching_products),
+ "mismatches": len(mismatch_ids),
+ "confidence": round(parity_confidence, 4),
+ "llm_confidence": round(llm_confidence, 4),
+ "overall_confidence": round(overall_confidence, 4),
+ "overall_method": "llm_confidence * parity_ci_lower_95 * evidence_ci_lower_95_beta_posterior",
+ "status": status,
+ "duckdb_query": f"SELECT * FROM {TABLE_NAME} WHERE {duckdb_condition}",
+ "duckdb_errors": duckdb_error_count,
+ "duckdb_condition": duckdb_condition,
+ "duckdb_example_rows": duckdb_examples,
+ "equivalence_cases": int(verification.get("equivalence_cases", 0)),
+ "equivalence_matches": int(verification.get("equivalence_matches", 0)),
+ "equivalence_mismatches": int(verification.get("equivalence_mismatches", 0)),
+ "equivalence_match_rate": round(float(verification.get("equivalence_match_rate", 1.0)), 4),
+ "equivalence_status": verification.get("equivalence_status", "PASS"),
+ "equivalence_counterexamples": list(verification.get("counterexamples", [])),
+ "mutation_total": int(verification.get("mutation_total", 0)),
+ "mutation_killed": int(verification.get("mutation_killed", 0)),
+ "mutation_survived": int(verification.get("mutation_survived", 0)),
+ "mutation_score": round(float(verification.get("mutation_score", 1.0)), 4),
+ "mutation_survived_mutants": list(verification.get("mutation_survived_mutants", [])),
+ "verification_score": round(float(verification.get("verification_score", 1.0)), 4),
+ "counterexample_repair_attempted": bool(verification.get("counterexample_repair_attempted", False)),
+ "counterexample_repair_applied": bool(verification.get("counterexample_repair_applied", False)),
+ "counterexample_repair_error": str(verification.get("counterexample_repair_error", "")),
+ "mismatch_product_ids": mismatch_ids,
+ "failed_test_cases": _build_failed_case_rows(
+ mismatch_ids=mismatch_ids,
+ product_map=product_map,
+ perl_ids=perl_ids,
+ python_ids=python_ids,
+ limit=10,
+ ),
+ "perl_logic": rule["perl_logic"],
+ "python_conversion": conversion_meta["python_code"],
+ "conversion_notes": conversion_meta["conversion_notes"],
+ "conversion_provider": conversion_meta.get("provider", "unknown"),
+ "conversion_execution_mode": conversion_meta.get("execution_mode", ""),
+ "conversion_cloud_connected": bool(conversion_meta.get("cloud_connected", False)),
+ "conversion_cloud_scan_id": conversion_meta.get("cloud_scan_id", ""),
+ "conversion_cloud_scan_url": conversion_meta.get("cloud_scan_url", ""),
+ }
+
+
+def run_pipeline(
+ dataset_size: int = 300,
+ seed: int = 17,
+ results_path: Path = RESULT_PATH,
+ source_jsonl: Path | None = None,
+ use_default_off_source: bool = True,
+ db_path: Path = DB_PATH,
+ llm_provider: str = "groq",
+ llm_model: str | None = None,
+ perl_rules_dir: Path | None = None,
+ execution_engine: str = "python",
+ soda_mode: str = "local",
+ profile: str = DEFAULT_PROFILE,
+) -> Dict[str, object]:
+ """Run the full migration prototype pipeline and persist JSON results."""
+ if execution_engine not in {"python", "dbt", "soda"}:
+ raise ValueError("execution_engine must be one of: python, dbt, soda")
+
+ profile_name = validate_profile(profile)
+ selected_rule_names = set(get_profile_rule_names(profile_name, [rule.rule_name for rule in LEGACY_RULES]))
+ selected_legacy_rules = [rule for rule in LEGACY_RULES if rule.rule_name in selected_rule_names]
+ if not selected_legacy_rules:
+ raise ValueError(f"No legacy rules selected for profile `{profile_name}`.")
+
+ source_path = source_jsonl
+ if source_path is None and use_default_off_source and DEFAULT_OFF_JSONL.exists():
+ source_path = DEFAULT_OFF_JSONL
+
+ products = create_and_load_dataset(size=dataset_size, seed=seed, db_path=db_path, source_jsonl=source_path)
+ product_map = {str(product["product_id"]): product for product in products}
+
+ perl_output = run_perl_checks(products, selected_legacy_rules)
+ if perl_rules_dir is None:
+ structured_rules_raw = extract_rules(get_perl_rule_snippets(selected_legacy_rules, rules_dir=None))
+ else:
+ all_structured = extract_rules(get_perl_rule_snippets(LEGACY_RULES, rules_dir=perl_rules_dir))
+ structured_rules_raw = [rule for rule in all_structured if str(rule["rule_name"]) in selected_rule_names]
+ structured_rules = attach_profile_metadata(structured_rules_raw, profile=profile_name)
+ if not structured_rules:
+ raise ValueError(f"No structured rules extracted for profile `{profile_name}`.")
+
+ engine_run: Dict[str, object] | None = None
+ verification_by_rule: Dict[str, Dict[str, object]] = {}
+
+ if execution_engine == "python":
+ converted_rules = convert_rules(structured_rules, provider=llm_provider, model=llm_model)
+ converted_by_name = {str(item["rule_name"]): dict(item) for item in converted_rules}
+ repair_flags: Dict[str, Dict[str, object]] = {
+ str(rule["rule_name"]): {
+ "counterexample_repair_attempted": False,
+ "counterexample_repair_applied": False,
+ "counterexample_repair_error": "",
+ }
+ for rule in structured_rules
+ }
+
+ python_checks, conversion_metadata = compile_generated_checks(
+ [converted_by_name[str(rule["rule_name"])] for rule in structured_rules]
+ )
+ initial_verification = _run_python_verification(
+ structured_rules=structured_rules,
+ python_checks=python_checks,
+ conversion_metadata=conversion_metadata,
+ seed=seed,
+ legacy_rules=selected_legacy_rules,
+ )
+
+ if llm_provider == "groq":
+ for rule in structured_rules:
+ rule_name = str(rule["rule_name"])
+ verification = initial_verification.get(rule_name, {})
+ provider = str(conversion_metadata[rule_name].get("provider", ""))
+ if provider != "groq":
+ continue
+ if int(verification.get("equivalence_mismatches", 0)) <= 0:
+ continue
+
+ repair_flags[rule_name]["counterexample_repair_attempted"] = True
+ try:
+ repaired = repair_conversion_with_counterexamples(
+ rule=rule,
+ converted_rule=converted_by_name[rule_name],
+ counterexamples=list(verification.get("counterexamples", [])),
+ provider=llm_provider,
+ model=llm_model,
+ )
+ if str(repaired.get("python_code", "")) != str(converted_by_name[rule_name].get("python_code", "")):
+ converted_by_name[rule_name] = repaired
+ repair_flags[rule_name]["counterexample_repair_applied"] = True
+ except Exception as exc: # noqa: BLE001
+ repair_flags[rule_name]["counterexample_repair_error"] = f"{exc.__class__.__name__}: {exc}"
+
+ python_checks, conversion_metadata = compile_generated_checks(
+ [converted_by_name[str(rule["rule_name"])] for rule in structured_rules]
+ )
+ verification_by_rule = _run_python_verification(
+ structured_rules=structured_rules,
+ python_checks=python_checks,
+ conversion_metadata=conversion_metadata,
+ seed=seed,
+ legacy_rules=selected_legacy_rules,
+ )
+ for rule in structured_rules:
+ rule_name = str(rule["rule_name"])
+ verification_by_rule.setdefault(rule_name, {}).update(repair_flags.get(rule_name, {}))
+
+ candidate_output = _run_python_checks(products, structured_rules, python_checks)
+ else:
+ declarative_result = run_declarative_checks(
+ rules=structured_rules,
+ products=products,
+ db_path=db_path,
+ engine=execution_engine,
+ soda_mode=soda_mode,
+ )
+ candidate_output = {
+ "per_product": declarative_result["per_product"],
+ "per_rule": declarative_result["per_rule"],
+ }
+ conversion_metadata = declarative_result["conversion_metadata"]
+ engine_run = declarative_result["engine_run"]
+
+ rule_results: List[Dict[str, object]] = []
+ for rule in structured_rules:
+ rule_name = str(rule["rule_name"])
+ rule_result = _compute_rule_result(
+ rule=rule,
+ perl_rule_products=perl_output["per_rule"][rule_name],
+ python_rule_products=candidate_output["per_rule"][rule_name],
+ product_map=product_map,
+ conversion_meta=conversion_metadata[rule_name],
+ verification_meta=verification_by_rule.get(rule_name),
+ db_path=db_path,
+ )
+ rule_results.append(rule_result)
+
+ passed_rules = sum(1 for row in rule_results if row["status"] == "MATCH")
+ total_rules = len(rule_results)
+ avg_confidence = mean([row["overall_confidence"] for row in rule_results]) if rule_results else 0.0
+ generated_at_utc = datetime.now(timezone.utc).isoformat()
+ dataset_fingerprint = _dataset_fingerprint_payload(
+ products=products,
+ source_path=source_path,
+ dataset_size=dataset_size,
+ seed=seed,
+ )
+ rulepack_fingerprint = _rulepack_fingerprint_payload(structured_rules=structured_rules, profile_name=profile_name)
+ safe_timestamp = (
+ generated_at_utc.replace(":", "").replace("-", "").replace(".", "").replace("+", "p")
+ )
+ run_id = f"parity_{safe_timestamp}_{uuid4().hex[:8]}"
+ git_commit = _resolve_git_commit()
+
+ result_payload: Dict[str, object] = {
+ "generated_at_utc": generated_at_utc,
+ "run_fingerprint": {
+ "run_id": run_id,
+ "generated_at_utc": generated_at_utc,
+ "execution_engine": execution_engine,
+ "soda_mode": soda_mode,
+ "llm_provider": llm_provider,
+ "llm_model": llm_model or "",
+ "code_commit": git_commit,
+ "dataset_fingerprint": dataset_fingerprint,
+ "rulepack_fingerprint": rulepack_fingerprint,
+ },
+ "dataset": {
+ "jsonl_path": str(SAMPLE_FILE),
+ "duckdb_path": str(db_path),
+ "products_tested": len(products),
+ "source_jsonl": str(source_path) if source_path else "synthetic",
+ "perl_rules_source": str(perl_rules_dir) if perl_rules_dir else "inline_legacy_rules",
+ "execution_engine": execution_engine,
+ "soda_mode": soda_mode,
+ "profile": profile_name,
+ "profile_rule_count": len(structured_rules),
+ "dataset_fingerprint_sha256": dataset_fingerprint["sha256"],
+ "rulepack_fingerprint_sha256": rulepack_fingerprint["rule_ir_sha256"],
+ },
+ "migration_summary": {
+ "total_rules": total_rules,
+ "passed_rules": passed_rules,
+ "rules_needing_review": total_rules - passed_rules,
+ "average_overall_confidence": round(avg_confidence, 4),
+ },
+ "rule_results": rule_results,
+ }
+ if engine_run is not None:
+ result_payload["declarative_engine_run"] = engine_run
+
+ results_path.parent.mkdir(parents=True, exist_ok=True)
+ with results_path.open("w", encoding="utf-8") as handle:
+ json.dump(result_payload, handle, indent=2)
+ return result_payload
+
+
+def parse_args() -> argparse.Namespace:
+ parser = argparse.ArgumentParser(description="Run Perl/Python parity validation prototype.")
+ parser.add_argument("--size", type=int, default=300, help="Number of products to generate.")
+ parser.add_argument(
+ "--seed",
+ type=int,
+ default=17,
+ help="Random seed for synthetic data generation (ignored when --source-jsonl is set).",
+ )
+ parser.add_argument(
+ "--source-jsonl",
+ type=Path,
+ default=DEFAULT_OFF_JSONL if DEFAULT_OFF_JSONL.exists() else None,
+ help="OFF JSONL source path. Defaults to ./openfoodfacts-products.jsonl when present.",
+ )
+ parser.add_argument(
+ "--llm-provider",
+ choices=["simulated", "groq"],
+ default="groq",
+ help="Rule conversion provider.",
+ )
+ parser.add_argument(
+ "--llm-model",
+ default=None,
+ help="Optional model override (for selected LLM provider).",
+ )
+ parser.add_argument(
+ "--perl-rules-dir",
+ type=Path,
+ default=None,
+ help="Optional directory containing .pl rule snippets for extractor input.",
+ )
+ parser.add_argument(
+ "--execution-engine",
+ choices=["python", "dbt", "soda"],
+ default="python",
+ help="Check execution engine for parity target: python (LLM converted), dbt, or soda.",
+ )
+ parser.add_argument(
+ "--profile",
+ choices=list(SUPPORTED_PROFILES),
+ default=DEFAULT_PROFILE,
+ help="Rule-pack profile to execute: global, canada, or hybrid.",
+ )
+ parser.add_argument(
+ "--soda-mode",
+ choices=["local", "cloud"],
+ default="local",
+ help="Soda execution mode when --execution-engine soda: local or cloud.",
+ )
+ return parser.parse_args()
+
+
+def main() -> None:
+ args = parse_args()
+ results = run_pipeline(
+ dataset_size=args.size,
+ seed=args.seed,
+ source_jsonl=args.source_jsonl,
+ llm_provider=args.llm_provider,
+ llm_model=args.llm_model,
+ perl_rules_dir=args.perl_rules_dir,
+ execution_engine=args.execution_engine,
+ soda_mode=args.soda_mode,
+ profile=args.profile,
+ )
+ summary = results["migration_summary"]
+ print(f"Rules analyzed: {summary['total_rules']}")
+ print(f"Passed rules: {summary['passed_rules']}")
+ print(f"Rules needing review: {summary['rules_needing_review']}")
+ print(f"Dataset source: {results['dataset']['source_jsonl']}")
+ print(f"Execution engine: {results['dataset'].get('execution_engine', 'python')}")
+ if results["dataset"].get("execution_engine") == "soda":
+ print(f"Soda mode: {results['dataset'].get('soda_mode', 'local')}")
+ print(f"Profile: {results['dataset'].get('profile', DEFAULT_PROFILE)}")
+ print(f"Run ID: {results.get('run_fingerprint', {}).get('run_id', 'n/a')}")
+ print(
+ "Fingerprints: "
+ f"dataset={str(results.get('run_fingerprint', {}).get('dataset_fingerprint', {}).get('sha256', ''))[:16]} | "
+ f"rulepack={str(results.get('run_fingerprint', {}).get('rulepack_fingerprint', {}).get('rule_ir_sha256', ''))[:16]}"
+ )
+ print(f"Results written to: {RESULT_PATH}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/OFF_DataQuality/validation/verification.py b/OFF_DataQuality/validation/verification.py
new file mode 100644
index 0000000000000000000000000000000000000000..2c6b24ba11bac17d7cf31e4b8f135f8cdcb56f14
--- /dev/null
+++ b/OFF_DataQuality/validation/verification.py
@@ -0,0 +1,387 @@
+"""Verification utilities for migrated rule quality.
+
+This module adds:
+- rule-level equivalence checks (Perl evaluator vs generated check),
+- mutation testing for generated Python checks.
+"""
+from __future__ import annotations
+
+import json
+import random
+from typing import Callable, Dict, List, Mapping, Sequence
+
+
+def _to_float(value: object) -> float | None:
+ if value is None:
+ return None
+ try:
+ return float(value)
+ except (TypeError, ValueError):
+ return None
+
+
+def _comparison_pairs(operator: str) -> tuple[tuple[float, float], tuple[float, float]]:
+ pairs = {
+ ">": ((2.0, 1.0), (1.0, 2.0)),
+ "<": ((1.0, 2.0), (2.0, 1.0)),
+ ">=": ((2.0, 2.0), (1.0, 2.0)),
+ "<=": ((2.0, 2.0), (3.0, 2.0)),
+ "==": ((2.0, 2.0), (2.0, 3.0)),
+ "!=": ((2.0, 3.0), (2.0, 2.0)),
+ }
+ return pairs.get(operator, ((2.0, 1.0), (1.0, 2.0)))
+
+
+def _threshold_values(operator: str, threshold: float) -> tuple[float, float]:
+ if operator == ">":
+ return threshold + 1.0, threshold
+ if operator == "<":
+ return threshold - 1.0, threshold
+ if operator == ">=":
+ return threshold, threshold - 1.0
+ if operator == "<=":
+ return threshold, threshold + 1.0
+ if operator == "==":
+ return threshold, threshold + 1.0
+ if operator == "!=":
+ return threshold + 1.0, threshold
+ return threshold + 1.0, threshold
+
+
+def _dedupe_cases(cases: Sequence[Mapping[str, object]]) -> List[Dict[str, object]]:
+ deduped: List[Dict[str, object]] = []
+ seen: set[str] = set()
+ for case in cases:
+ payload = dict(case)
+ key = json.dumps(payload, sort_keys=True, default=str)
+ if key in seen:
+ continue
+ seen.add(key)
+ deduped.append(payload)
+ return deduped
+
+
+def generate_equivalence_cases(
+ rule: Mapping[str, object],
+ seed: int = 17,
+ random_cases: int = 18,
+) -> List[Dict[str, object]]:
+ rng = random.Random(seed + (sum(ord(ch) for ch in str(rule.get("rule_name", ""))) % 997))
+ condition_type = str(rule.get("condition_type", ""))
+ cases: List[Dict[str, object]] = []
+
+ if condition_type == "field_comparison":
+ left = str(rule.get("left_operand"))
+ right = str(rule.get("right_operand"))
+ operator = str(rule.get("operator"))
+ true_pair, false_pair = _comparison_pairs(operator)
+ cases.extend(
+ [
+ {left: true_pair[0], right: true_pair[1]},
+ {left: false_pair[0], right: false_pair[1]},
+ {left: true_pair[1], right: true_pair[1]},
+ {left: None, right: true_pair[1]},
+ {left: true_pair[0], right: None},
+ ]
+ )
+ for _ in range(random_cases):
+ cases.append({left: round(rng.uniform(-10, 200), 3), right: round(rng.uniform(-10, 200), 3)})
+
+ elif condition_type == "field_threshold":
+ left = str(rule.get("left_operand"))
+ operator = str(rule.get("operator"))
+ threshold = float(rule.get("right_operand", 0.0))
+ true_value, false_value = _threshold_values(operator, threshold)
+ cases.extend([{left: true_value}, {left: false_value}, {left: None}, {left: "nan_text"}])
+ for _ in range(random_cases):
+ cases.append({left: round(rng.uniform(threshold - 100, threshold + 100), 3)})
+
+ elif condition_type == "missing_field":
+ field = str(rule.get("left_operand"))
+ cases.extend(
+ [
+ {field: None},
+ {field: ""},
+ {field: " "},
+ {field: "en"},
+ {field: "xx"},
+ ]
+ )
+
+ elif condition_type == "scaled_field_comparison":
+ left = str(rule.get("left_operand"))
+ right = str(rule.get("right_operand"))
+ operator = str(rule.get("operator"))
+ factor = float(rule.get("scale_factor", 1.0))
+ right_value = 10.0
+ target = right_value * factor
+ true_value, false_value = _threshold_values(operator, target)
+ cases.extend(
+ [
+ {left: true_value, right: right_value},
+ {left: false_value, right: right_value},
+ {left: None, right: right_value},
+ {left: true_value, right: None},
+ ]
+ )
+ for _ in range(random_cases):
+ random_right = round(rng.uniform(0.1, 150), 3)
+ random_target = random_right * factor
+ delta = rng.uniform(-10, 10)
+ cases.append({left: round(random_target + delta, 3), right: random_right})
+
+ elif condition_type == "affine_field_comparison":
+ left = str(rule.get("left_operand"))
+ right = str(rule.get("right_operand"))
+ operator = str(rule.get("operator"))
+ factor = float(rule.get("scale_factor", 1.0))
+ offset = float(rule.get("offset", 0.0))
+ right_value = 10.0
+ target = (factor * right_value) + offset
+ true_value, false_value = _threshold_values(operator, target)
+ cases.extend(
+ [
+ {left: true_value, right: right_value},
+ {left: false_value, right: right_value},
+ {left: None, right: right_value},
+ {left: true_value, right: None},
+ ]
+ )
+ for _ in range(random_cases):
+ random_right = round(rng.uniform(0.1, 150), 3)
+ random_target = (factor * random_right) + offset
+ delta = rng.uniform(-10, 10)
+ cases.append({left: round(random_target + delta, 3), right: random_right})
+
+ elif condition_type == "sum_fields_comparison":
+ left_operands = list(rule.get("left_operands", []))
+ if len(left_operands) >= 2:
+ left_a = str(left_operands[0])
+ left_b = str(left_operands[1])
+ right = str(rule.get("right_operand"))
+ operator = str(rule.get("operator"))
+ right_offset = float(rule.get("right_offset", 0.0))
+ right_value = 20.0
+ target = right_value + right_offset
+ true_sum, false_sum = _threshold_values(operator, target)
+ cases.extend(
+ [
+ {left_a: true_sum / 2.0, left_b: true_sum / 2.0, right: right_value},
+ {left_a: false_sum / 2.0, left_b: false_sum / 2.0, right: right_value},
+ {left_a: None, left_b: 2.0, right: right_value},
+ {left_a: 2.0, left_b: None, right: right_value},
+ ]
+ )
+ for _ in range(random_cases):
+ random_right = round(rng.uniform(0.1, 120), 3)
+ random_target = random_right + right_offset
+ left_sum = random_target + rng.uniform(-20, 20)
+ left_part = round(rng.uniform(0, max(left_sum, 0.1)), 3)
+ cases.append(
+ {
+ left_a: left_part,
+ left_b: round(left_sum - left_part, 3),
+ right: random_right,
+ }
+ )
+
+ elif condition_type == "compound_threshold_and":
+ clauses = list(rule.get("clauses", []))
+ passing: Dict[str, object] = {}
+ failing: Dict[str, object] = {}
+ for idx, clause in enumerate(clauses):
+ field = str(clause.get("left_operand"))
+ operator = str(clause.get("operator"))
+ threshold = float(clause.get("right_operand", 0.0))
+ true_value, false_value = _threshold_values(operator, threshold)
+ passing[field] = true_value
+ failing[field] = true_value
+ if idx == 0:
+ failing[field] = false_value
+ if passing:
+ cases.append(passing)
+ if failing:
+ cases.append(failing)
+
+ return _dedupe_cases(cases)
+
+
+def evaluate_rule_equivalence(
+ rule: Mapping[str, object],
+ perl_evaluator: Callable[[Mapping[str, object]], bool],
+ check_fn: Callable[[Mapping[str, object]], object],
+ seed: int = 17,
+ cases: Sequence[Mapping[str, object]] | None = None,
+ max_counterexamples: int = 5,
+) -> Dict[str, object]:
+ sample_cases = list(cases) if cases is not None else generate_equivalence_cases(rule, seed=seed)
+ tag = str(rule.get("tag"))
+ matches = 0
+ mismatches = 0
+ counterexamples: List[Dict[str, object]] = []
+
+ for case in sample_cases:
+ product = dict(case)
+ expected = tag if bool(perl_evaluator(product)) else None
+ try:
+ actual = check_fn(product)
+ except Exception as exc: # noqa: BLE001
+ actual = f"EXCEPTION:{exc.__class__.__name__}"
+ if actual == expected:
+ matches += 1
+ else:
+ mismatches += 1
+ if len(counterexamples) < max_counterexamples:
+ counterexamples.append({"input": product, "expected": expected, "actual": actual})
+
+ total = len(sample_cases)
+ rate = (matches / total) if total else 1.0
+ return {
+ "equivalence_cases": total,
+ "equivalence_matches": matches,
+ "equivalence_mismatches": mismatches,
+ "equivalence_match_rate": round(rate, 4),
+ "equivalence_status": "PASS" if mismatches == 0 else "FAIL",
+ "counterexamples": counterexamples,
+ }
+
+
+def _mutate_once(code: str, old: str, new: str) -> str | None:
+ if old not in code:
+ return None
+ mutated = code.replace(old, new, 1)
+ if mutated == code:
+ return None
+ return mutated
+
+
+def build_mutants(rule: Mapping[str, object], python_code: str) -> List[Dict[str, object]]:
+ mutants: List[Dict[str, object]] = []
+ condition_type = str(rule.get("condition_type", ""))
+ operator = str(rule.get("operator", ""))
+ operator_swap = {">": ">=", "<": "<=", ">=": ">", "<=": "<", "==": "!=", "!=": "=="}
+ swapped = operator_swap.get(operator)
+ if swapped:
+ mutated = _mutate_once(python_code, f" {operator} ", f" {swapped} ")
+ if mutated is not None:
+ mutants.append({"name": f"operator_{operator}_to_{swapped}", "code": mutated})
+
+ if condition_type == "missing_field":
+ mutated = _mutate_once(python_code, 'or str(value).strip() == ""', 'and str(value).strip() == ""')
+ if mutated is not None:
+ mutants.append({"name": "missing_logic_or_to_and", "code": mutated})
+
+ if condition_type == "sum_fields_comparison":
+ mutated = _mutate_once(python_code, "left_sum = left_a_value + left_b_value", "left_sum = left_a_value - left_b_value")
+ if mutated is not None:
+ mutants.append({"name": "sum_to_difference", "code": mutated})
+
+ scale_factor = rule.get("scale_factor")
+ if isinstance(scale_factor, (int, float)):
+ old = str(float(scale_factor))
+ new = str(round(float(scale_factor) + 0.3, 6))
+ mutated = _mutate_once(python_code, old, new)
+ if mutated is not None:
+ mutants.append({"name": "scale_factor_perturbed", "code": mutated})
+
+ offset = rule.get("offset")
+ if isinstance(offset, (int, float)):
+ old = str(float(offset))
+ new = str(round(float(offset) + 1.0, 6))
+ mutated = _mutate_once(python_code, old, new)
+ if mutated is not None:
+ mutants.append({"name": "offset_perturbed", "code": mutated})
+
+ threshold = rule.get("right_operand")
+ if condition_type == "field_threshold" and isinstance(threshold, (int, float)):
+ old = str(float(threshold))
+ new = str(round(float(threshold) + 1.0, 6))
+ mutated = _mutate_once(python_code, old, new)
+ if mutated is not None:
+ mutants.append({"name": "threshold_perturbed", "code": mutated})
+
+ deduped: List[Dict[str, object]] = []
+ seen: set[str] = set()
+ for mutant in mutants:
+ code = str(mutant["code"])
+ if code in seen:
+ continue
+ seen.add(code)
+ deduped.append(mutant)
+ return deduped[:8]
+
+
+def evaluate_mutation_suite(
+ rule: Mapping[str, object],
+ perl_evaluator: Callable[[Mapping[str, object]], bool],
+ python_code: str,
+ function_name: str,
+ seed: int = 17,
+) -> Dict[str, object]:
+ cases = generate_equivalence_cases(rule, seed=seed)
+ mutants = build_mutants(rule, python_code)
+ total = 0
+ killed = 0
+ survived: List[str] = []
+
+ for mutant in mutants:
+ namespace: Dict[str, object] = {}
+ try:
+ exec(str(mutant["code"]), {}, namespace)
+ fn = namespace.get(function_name)
+ if not callable(fn):
+ continue
+ except Exception:
+ continue
+
+ total += 1
+ result = evaluate_rule_equivalence(
+ rule=rule,
+ perl_evaluator=perl_evaluator,
+ check_fn=fn,
+ seed=seed,
+ cases=cases,
+ max_counterexamples=1,
+ )
+ if int(result["equivalence_mismatches"]) > 0:
+ killed += 1
+ else:
+ survived.append(str(mutant["name"]))
+
+ score = (killed / total) if total else 1.0
+ return {
+ "mutation_total": total,
+ "mutation_killed": killed,
+ "mutation_survived": total - killed,
+ "mutation_score": round(score, 4),
+ "mutation_survived_mutants": survived,
+ }
+
+
+def run_rule_verification(
+ rule: Mapping[str, object],
+ perl_evaluator: Callable[[Mapping[str, object]], bool],
+ check_fn: Callable[[Mapping[str, object]], object],
+ python_code: str,
+ function_name: str,
+ seed: int = 17,
+) -> Dict[str, object]:
+ equivalence = evaluate_rule_equivalence(
+ rule=rule,
+ perl_evaluator=perl_evaluator,
+ check_fn=check_fn,
+ seed=seed,
+ )
+ mutation = evaluate_mutation_suite(
+ rule=rule,
+ perl_evaluator=perl_evaluator,
+ python_code=python_code,
+ function_name=function_name,
+ seed=seed,
+ )
+ verification_score = float(equivalence["equivalence_match_rate"]) * float(mutation["mutation_score"])
+ return {
+ **equivalence,
+ **mutation,
+ "verification_score": round(verification_score, 4),
+ }