SanjayH9305 commited on
Commit
ba71465
·
verified ·
1 Parent(s): 120ff8c

Add OFF_DataQuality project with sanitized code and enriched README

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. OFF_DataQuality/.gitignore +23 -0
  2. OFF_DataQuality/README.md +206 -0
  3. OFF_DataQuality/config/hypercorn.toml +9 -0
  4. OFF_DataQuality/dashboard/app.py +787 -0
  5. OFF_DataQuality/data/__init__.py +0 -0
  6. OFF_DataQuality/data/load_dataset.py +494 -0
  7. OFF_DataQuality/data/sample_products.jsonl +0 -0
  8. OFF_DataQuality/declarative/__init__.py +2 -0
  9. OFF_DataQuality/declarative/check_runners.py +742 -0
  10. OFF_DataQuality/duckdb_utils/__init__.py +0 -0
  11. OFF_DataQuality/duckdb_utils/create_tables.py +116 -0
  12. OFF_DataQuality/extractor/__init__.py +0 -0
  13. OFF_DataQuality/extractor/perl_logic_extractor.py +316 -0
  14. OFF_DataQuality/inspect_duckdb.py +6 -0
  15. OFF_DataQuality/llm-test/test_groq.py +26 -0
  16. OFF_DataQuality/migration/__init__.py +0 -0
  17. OFF_DataQuality/migration/llm_converter.py +714 -0
  18. OFF_DataQuality/perl_checks/__init__.py +0 -0
  19. OFF_DataQuality/perl_checks/legacy_checks.py +590 -0
  20. OFF_DataQuality/perl_checks/rules/01_energy_kcal_vs_kj.pl +7 -0
  21. OFF_DataQuality/perl_checks/rules/02_energy_kj_mismatch_low.pl +7 -0
  22. OFF_DataQuality/perl_checks/rules/03_energy_kj_mismatch_high.pl +7 -0
  23. OFF_DataQuality/perl_checks/rules/04_energy_kj_over_3911.pl +7 -0
  24. OFF_DataQuality/perl_checks/rules/05_saturated_fat_vs_fat.pl +7 -0
  25. OFF_DataQuality/perl_checks/rules/06_sugars_plus_starch_vs_carbohydrates.pl +7 -0
  26. OFF_DataQuality/perl_checks/rules/07_fat_over_105g.pl +7 -0
  27. OFF_DataQuality/perl_checks/rules/08_saturated_fat_over_105g.pl +7 -0
  28. OFF_DataQuality/perl_checks/rules/09_carbohydrates_over_105g.pl +7 -0
  29. OFF_DataQuality/perl_checks/rules/10_sugars_over_105g.pl +7 -0
  30. OFF_DataQuality/perl_checks/rules/11_main_language_code_missing.pl +7 -0
  31. OFF_DataQuality/perl_checks/rules/12_main_language_missing.pl +7 -0
  32. OFF_DataQuality/perl_checks/rules/13_energy_kj_computed_mismatch_low.pl +7 -0
  33. OFF_DataQuality/perl_checks/rules/14_energy_kj_computed_mismatch_high.pl +7 -0
  34. OFF_DataQuality/perl_checks/rules/15_ca_allergen_evidence_missing_ingredients_text.pl +7 -0
  35. OFF_DataQuality/perl_checks/rules/16_ca_contains_statement_without_allergen_evidence.pl +7 -0
  36. OFF_DataQuality/perl_checks/rules/17_ca_fop_required_but_symbol_missing.pl +7 -0
  37. OFF_DataQuality/perl_checks/rules/18_ca_fop_symbol_present_but_not_required.pl +7 -0
  38. OFF_DataQuality/perl_checks/rules/19_ca_fop_symbol_present_on_exempt_product.pl +7 -0
  39. OFF_DataQuality/pytest.ini +2 -0
  40. OFF_DataQuality/python_checks/__init__.py +0 -0
  41. OFF_DataQuality/python_checks/generated_checks.py +36 -0
  42. OFF_DataQuality/requirements.txt +8 -0
  43. OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/dbt_project.yml +6 -0
  44. OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/macros/count_violations.sql +12 -0
  45. OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/models/sources.yml +6 -0
  46. OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/profiles.yml +8 -0
  47. OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/tests/ca_allergen_evidence_missing_ingredients_text.sql +3 -0
  48. OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/tests/ca_contains_statement_without_allergen_evidence.sql +3 -0
  49. OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/tests/ca_fop_required_but_symbol_missing.sql +3 -0
  50. OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/tests/ca_fop_symbol_present_but_not_required.sql +3 -0
OFF_DataQuality/.gitignore ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Python cache/artifacts
2
+ __pycache__/
3
+ *.py[cod]
4
+ *.pyo
5
+ *.pyd
6
+ .pytest_cache/
7
+
8
+ # Local environments
9
+ .venv/
10
+ venv/
11
+
12
+ # Local data artifacts & databases (do not commit)
13
+ *.db
14
+ openfoodfacts-products.jsonl
15
+ config/secret_key
16
+ config/logs/
17
+ results/tmp_engine_runs/
18
+
19
+ # OS/editor
20
+ .DS_Store
21
+ Thumbs.db
22
+ .vscode/
23
+ .idea/
OFF_DataQuality/README.md ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # OFF_DataQuality: Perl-to-Python Data Quality Migration & Benchmarking Framework
2
+
3
+ ## Overview
4
+
5
+ **OFF_DataQuality** is an end-to-end framework designed to modernize legacy data quality validation logic for **Open Food Facts (OFF)**.
6
+
7
+ 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.
8
+
9
+ This project provides an automated pipeline for:
10
+ 1. **Extracting** relational, threshold, and logic conditions from legacy Perl scripts.
11
+ 2. **Migrating** rules into modern **Python** validation logic using LLMs (Groq / GPT-oss-120b) with deterministic fallback templates and semantic guardrail verification.
12
+ 3. **Generating Declarative Targets** for **dbt-core** (DuckDB SQL tests) and **SodaCL** (Soda data quality contracts).
13
+ 4. **Benchmarking Parity** across legacy Perl outputs vs. Python, dbt, and Soda execution engines with conservative statistical confidence scoring (95% Wilson bounds & Beta posteriors).
14
+ 5. **Interactive Dashboarding** to inspect side-by-side rule performance, win distributions by complexity (simple, medium, intricate), and legal traceability metadata.
15
+
16
+ ---
17
+
18
+ ## Core Architecture & Workflow
19
+
20
+ ```mermaid
21
+ flowchart TD
22
+ A[Legacy Perl Rules .pl] --> B[Perl Logic Extractor]
23
+ B --> C{Migration Engine}
24
+ C -->|LLM / Groq GPT-oss-120b| D[Python Rules]
25
+ C -->|Declarative Generator| E[dbt DuckDB SQL Tests]
26
+ C -->|Declarative Generator| F[SodaCL YAML Contracts]
27
+ D --> G[Semantic Guardrails Verification]
28
+ E --> H[DuckDB Parity Execution]
29
+ F --> H
30
+ G --> H
31
+ H --> I[Statistical Confidence & Parity Validator]
32
+ I --> J[Streamlit Comparison Dashboard]
33
+ ```
34
+
35
+ ---
36
+
37
+ ## Key Features
38
+
39
+ ### 1. Automated Perl Rule Extraction & Translation
40
+ - **Perl Extractor (`extractor/perl_logic_extractor.py`)**: Parses legacy `.pl` condition files to isolate numeric bounds, relational field constraints, and tag generation logic.
41
+ - **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.
42
+ - **Deterministic Fallback**: If LLM API access is unavailable or semantic checks fail, the system falls back to deterministic rule templates.
43
+
44
+ ### 2. Multi-Engine Declarative Pilot (`dbt` & `SodaCL`)
45
+ - **dbt Target**: Automatically generates dbt SQL test models and `count_violations` macros backed by DuckDB.
46
+ - **SodaCL Target**: Automatically generates SodaCL contract YAML files for automated data quality scanning.
47
+
48
+ ### 3. Statistical Parity & Confidence Scoring
49
+ Rule confidence is computed conservatively to prevent inflation on sparse evidence:
50
+ $$ ext{overall\_confidence} = ext{llm\_confidence} imes ext{parity\_ci\_lower\_95} imes ext{evidence\_ci\_lower\_95}$$
51
+ 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.
52
+
53
+ ### 4. Jurisdiction Profile Layers
54
+ - **`global`**: Generic Open Food Facts nutrient consistency and boundary rules.
55
+ - **`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.
56
+ - **`hybrid`**: Unified execution across both global and Canadian rule sets.
57
+
58
+ ### 5. Interactive Streamlit Dashboard
59
+ An interactive UI (`dashboard/app.py`) presenting per-rule accuracy, side-by-side code/SQL comparisons, engine recommendations, and legal traceability metadata.
60
+
61
+ ---
62
+
63
+ ## Repository Structure
64
+
65
+ ```text
66
+ OFF_DataQuality/
67
+ ├── README.md # Project documentation and execution guide
68
+ ├── requirements.txt # Core dependencies (duckdb, streamlit, pandas, openai, dbt, soda)
69
+ ├── pytest.ini # Test configuration
70
+ ├── inspect_duckdb.py # Utility script for inspecting DuckDB tables
71
+ ├── config/
72
+ │ ├── hypercorn.toml # Server configuration
73
+ │ └── custom-covers/ # Custom asset configuration directories
74
+ ├── dashboard/
75
+ │ └── app.py # Interactive Streamlit parity comparison dashboard
76
+ ├── data/
77
+ │ ├── load_dataset.py # Streamed product dataset loader (real OFF JSONL / sample)
78
+ │ └── sample_products.jsonl # 400 sample OFF product records for out-of-the-box execution
79
+ ├── declarative/
80
+ │ └── check_runners.py # Declarative dbt & Soda check generation & execution
81
+ ├── duckdb_utils/
82
+ │ └── create_tables.py # In-memory DuckDB table creation & schema setup
83
+ ├── extractor/
84
+ │ └── perl_logic_extractor.py # Legacy Perl script logic parser
85
+ ├── llm-test/
86
+ │ └── test_groq.py # Verification script for Groq API integration
87
+ ├── migration/
88
+ │ └── llm_converter.py # LLM translation pipeline with semantic guardrails
89
+ ├── perl_checks/
90
+ │ ├── legacy_checks.py # Simulated & file-based legacy Perl rule runner
91
+ │ └── rules/ # 19 legacy Perl validation rules (.pl)
92
+ ├── python_checks/
93
+ │ └── generated_checks.py # Auto-generated Python quality check routines
94
+ ├── results/
95
+ │ ├── engine_comparison.json # Pre-computed benchmark comparison report
96
+ │ ├── migration_results.json # Migration execution output
97
+ │ └── declarative_runtime/ # Generated dbt & Soda test models and contracts
98
+ ├── rulepacks/
99
+ │ └── registry.py # Global, Canada, and Hybrid rule-pack registry
100
+ ├── tests/ # Comprehensive pytest suite
101
+ └── validation/
102
+ ├── parity_validator.py # End-to-end parity validation pipeline
103
+ ├── engine_comparison.py # Multi-engine comparative benchmark suite
104
+ └── verification.py # Semantic and runtime verification contracts
105
+ ```
106
+
107
+ ---
108
+
109
+ ## Security & Publishing Norms
110
+
111
+ - **No Hardcoded Credentials**: API keys (such as `GROQ_API_KEY`) are read strictly from environment variables.
112
+ - **Sanitized Configurations**: Local secret keys, temporary logs, and local SQLite/DuckDB binary database files are excluded.
113
+ - **Reproducible Sample Dataset**: Includes 400 sample product records (`data/sample_products.jsonl`) so the entire pipeline can be benchmarked offline out-of-the-box.
114
+
115
+ ---
116
+
117
+ ## Quick Start
118
+
119
+ ### 1. Installation
120
+
121
+ Clone the repository and install dependencies:
122
+
123
+ ```bash
124
+ git clone https://huggingface.co/datasets/offCanada/Final_Deliverables
125
+ cd Final_Deliverables/OFF_DataQuality
126
+ pip install -r requirements.txt
127
+ ```
128
+
129
+ ### 2. Run Parity Validator Pipeline
130
+
131
+ Run parity validation on sample products using the default Python target:
132
+
133
+ ```bash
134
+ python -m validation.parity_validator --size 300 --seed 17
135
+ ```
136
+
137
+ Run with declarative targets (`dbt` or `soda`):
138
+
139
+ ```bash
140
+ python -m validation.parity_validator --size 300 --execution-engine dbt
141
+ python -m validation.parity_validator --size 300 --execution-engine soda
142
+ ```
143
+
144
+ Run using file-based Perl rule files:
145
+
146
+ ```bash
147
+ python -m validation.parity_validator --size 300 --perl-rules-dir perl_checks/rules
148
+ ```
149
+
150
+ ### 3. Run Multi-Engine Comparison Benchmark
151
+
152
+ Execute a comparison experiment across Python, dbt, and Soda engines:
153
+
154
+ ```bash
155
+ python -m validation.engine_comparison --size 300 --mode off --llm-provider groq
156
+ ```
157
+
158
+ Run with specific rule profiles:
159
+
160
+ ```bash
161
+ python -m validation.engine_comparison --size 300 --profile global
162
+ python -m validation.engine_comparison --size 300 --profile canada
163
+ python -m validation.engine_comparison --size 300 --profile hybrid
164
+ ```
165
+
166
+ ### 4. Launch the Streamlit Dashboard
167
+
168
+ Explore benchmark metrics, engine recommendations, and rule details interactively:
169
+
170
+ ```bash
171
+ streamlit run dashboard/app.py
172
+ ```
173
+
174
+ ### 5. Running with Groq LLM Integration (Optional)
175
+
176
+ To enable real LLM translation via Groq:
177
+
178
+ ```powershell
179
+ # Windows PowerShell
180
+ $env:GROQ_API_KEY="your_groq_api_key_here"
181
+ ```
182
+
183
+ ```bash
184
+ # Bash / Linux / macOS
185
+ export GROQ_API_KEY="your_groq_api_key_here"
186
+ ```
187
+
188
+ Then run with Groq provider:
189
+
190
+ ```bash
191
+ python -m validation.parity_validator --size 300 --llm-provider groq --llm-model openai/gpt-oss-120b
192
+ ```
193
+
194
+ ### 6. Automated Testing
195
+
196
+ Run the test suite using `pytest`:
197
+
198
+ ```bash
199
+ pytest -q
200
+ ```
201
+
202
+ ---
203
+
204
+ ## License & Attribution
205
+
206
+ 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.
OFF_DataQuality/config/hypercorn.toml ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # http1 & http2 binding
2
+ bind = ["0.0.0.0:9810"]
3
+ # http3 quick binding
4
+ quick_bind = ["0.0.0.0:9810"]
5
+ # http path prefix for codex
6
+ root_path = ""
7
+ # This can be a number or "auto" for Codex to guess a good value.
8
+ # https://github.com/ajslater/codex#bulk-database-updates-fail
9
+ max_import_batch_size = "auto"
OFF_DataQuality/dashboard/app.py ADDED
@@ -0,0 +1,787 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Streamlit dashboard for cross-engine migration comparison."""
2
+ from __future__ import annotations
3
+
4
+ import html
5
+ import json
6
+ import os
7
+ import sys
8
+ from pathlib import Path
9
+ from typing import Dict, List, Mapping
10
+
11
+ import pandas as pd
12
+ import plotly.express as px
13
+ import plotly.graph_objects as go
14
+ import streamlit as st
15
+
16
+ PROJECT_ROOT = Path(__file__).resolve().parent.parent
17
+ if str(PROJECT_ROOT) not in sys.path:
18
+ sys.path.insert(0, str(PROJECT_ROOT))
19
+
20
+ from rulepacks.registry import DEFAULT_PROFILE, SUPPORTED_PROFILES
21
+ from validation.engine_comparison import COMPARISON_PATH, run_engine_comparison
22
+
23
+ DEFAULT_SOURCE_JSONL = PROJECT_ROOT / "openfoodfacts-products.jsonl"
24
+ ENGINE_COLORS = {
25
+ "python": "#2563eb",
26
+ "dbt": "#f97316",
27
+ "soda": "#10b981",
28
+ }
29
+
30
+
31
+ def load_report() -> dict:
32
+ if not COMPARISON_PATH.exists():
33
+ return {}
34
+ with COMPARISON_PATH.open("r", encoding="utf-8") as handle:
35
+ return json.load(handle)
36
+
37
+
38
+ def _inject_theme() -> None:
39
+ st.markdown(
40
+ """
41
+ <style>
42
+ @import url('https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@400;600;700&family=IBM+Plex+Mono:wght@400;500&display=swap');
43
+ @import url('https://fonts.googleapis.com/css2?family=Material+Symbols+Rounded:opsz,wght,FILL,GRAD@20..48,400,0,0');
44
+ html, body, [class*="st-"], [class*="css"] {
45
+ font-family: "Space Grotesk", sans-serif;
46
+ }
47
+ [class^="material-symbols"], [class*=" material-symbols"] {
48
+ font-family: "Material Symbols Rounded" !important;
49
+ font-weight: normal;
50
+ font-style: normal;
51
+ font-size: 1rem;
52
+ line-height: 1;
53
+ letter-spacing: normal;
54
+ text-transform: none;
55
+ display: inline-block;
56
+ white-space: nowrap;
57
+ word-wrap: normal;
58
+ direction: ltr;
59
+ -webkit-font-smoothing: antialiased;
60
+ }
61
+ .block-container {
62
+ max-width: 1260px;
63
+ padding-top: 1.15rem;
64
+ padding-bottom: 2rem;
65
+ }
66
+ [data-testid="stMetric"] {
67
+ background: linear-gradient(120deg, #f8fafc 0%, #ecfeff 100%);
68
+ border: 1px solid #dbeafe;
69
+ border-radius: 14px;
70
+ padding: 0.6rem 0.8rem;
71
+ min-height: 118px;
72
+ }
73
+ [data-testid="stMetricLabel"] > div {
74
+ white-space: normal !important;
75
+ line-height: 1.15;
76
+ }
77
+ [data-testid="stMetricValue"] > div {
78
+ line-height: 1.15;
79
+ }
80
+ .stat-chip {
81
+ border-radius: 16px;
82
+ border: 1px solid #dbeafe;
83
+ background: linear-gradient(135deg, #f8fafc 0%, #ecfeff 100%);
84
+ padding: 0.8rem 0.95rem;
85
+ min-height: 112px;
86
+ display: flex;
87
+ flex-direction: column;
88
+ justify-content: space-between;
89
+ overflow: hidden;
90
+ box-shadow: 0 4px 12px rgba(15, 23, 42, 0.06);
91
+ }
92
+ .stat-chip .label {
93
+ color: #475569;
94
+ font-size: 0.76rem;
95
+ line-height: 1.1rem;
96
+ font-weight: 600;
97
+ text-transform: uppercase;
98
+ letter-spacing: 0.04em;
99
+ word-break: normal;
100
+ overflow-wrap: break-word;
101
+ }
102
+ .stat-chip .value {
103
+ color: #0f172a;
104
+ font-size: 1.28rem;
105
+ font-weight: 700;
106
+ line-height: 1.4rem;
107
+ margin-top: 0.5rem;
108
+ white-space: normal;
109
+ word-break: break-word;
110
+ }
111
+ .hero {
112
+ border-radius: 16px;
113
+ border: 1px solid #cbd5e1;
114
+ background: radial-gradient(circle at 10% 20%, #f0fdfa 0%, #eff6ff 45%, #fff7ed 100%);
115
+ padding: 1rem 1.2rem;
116
+ margin-bottom: 1.1rem;
117
+ }
118
+ .hero h1 {
119
+ margin: 0;
120
+ color: #0b1324;
121
+ font-size: 1.38rem;
122
+ letter-spacing: -0.01em;
123
+ }
124
+ .hero p {
125
+ margin: 0.3rem 0 0 0;
126
+ color: #334155;
127
+ font-size: 0.95rem;
128
+ }
129
+ .explain-chip {
130
+ border-radius: 14px;
131
+ border: 1px solid #bfdbfe;
132
+ background: linear-gradient(135deg, #eff6ff 0%, #f0f9ff 100%);
133
+ padding: 0.8rem 0.95rem;
134
+ margin: 0.6rem 0 0.9rem 0;
135
+ box-shadow: 0 4px 12px rgba(15, 23, 42, 0.05);
136
+ }
137
+ .explain-chip .title {
138
+ color: #1e3a8a;
139
+ font-size: 0.88rem;
140
+ line-height: 1.2rem;
141
+ font-weight: 700;
142
+ margin-bottom: 0.35rem;
143
+ text-transform: uppercase;
144
+ letter-spacing: 0.03em;
145
+ }
146
+ .explain-chip ul {
147
+ margin: 0.1rem 0 0 1rem;
148
+ padding: 0;
149
+ }
150
+ .explain-chip li {
151
+ color: #1e293b;
152
+ font-size: 0.92rem;
153
+ line-height: 1.35rem;
154
+ margin: 0.2rem 0;
155
+ }
156
+ [data-testid="stExpander"] > details > summary {
157
+ display: flex;
158
+ align-items: center;
159
+ gap: 0.5rem;
160
+ line-height: 1.25;
161
+ }
162
+ [data-testid="stExpander"] > details > summary p {
163
+ margin: 0 !important;
164
+ line-height: 1.25 !important;
165
+ }
166
+ [data-testid="stExpander"] > details > summary svg {
167
+ flex-shrink: 0;
168
+ margin-top: 0 !important;
169
+ }
170
+ </style>
171
+ """,
172
+ unsafe_allow_html=True,
173
+ )
174
+
175
+
176
+ def _to_pct(value: object) -> float:
177
+ try:
178
+ return round(float(value) * 100, 2)
179
+ except (TypeError, ValueError):
180
+ return 0.0
181
+
182
+
183
+ def _render_stat_chip(label: str, value: object) -> None:
184
+ st.markdown(
185
+ (
186
+ "<div class='stat-chip'>"
187
+ f"<div class='label'>{label}</div>"
188
+ f"<div class='value'>{value}</div>"
189
+ "</div>"
190
+ ),
191
+ unsafe_allow_html=True,
192
+ )
193
+
194
+
195
+ def _render_explain_chip(title: str, lines: List[str]) -> None:
196
+ safe_items = "".join(f"<li>{html.escape(line)}</li>" for line in lines if line)
197
+ st.markdown(
198
+ (
199
+ "<div class='explain-chip'>"
200
+ f"<div class='title'>{html.escape(title)}</div>"
201
+ f"<ul>{safe_items}</ul>"
202
+ "</div>"
203
+ ),
204
+ unsafe_allow_html=True,
205
+ )
206
+
207
+
208
+ def _engine_summary_frame(per_engine_summary: Mapping[str, Mapping[str, object]]) -> pd.DataFrame:
209
+ rows: List[Dict[str, object]] = []
210
+ for engine in ("python", "dbt", "soda"):
211
+ summary = per_engine_summary.get(engine, {})
212
+ rows.append(
213
+ {
214
+ "engine": engine.upper(),
215
+ "rules": int(summary.get("rules", 0)),
216
+ "passed": int(summary.get("passed", 0)),
217
+ "avg_overall_confidence_pct": _to_pct(summary.get("avg_overall_confidence", 0.0)),
218
+ "avg_effective_confidence_pct": _to_pct(summary.get("avg_effective_confidence", 0.0)),
219
+ "avg_parity_ci_low_pct": _to_pct(summary.get("avg_parity_ci_lower", 0.0)),
220
+ "avg_equivalence_rate_pct": _to_pct(summary.get("avg_equivalence_rate", 0.0)),
221
+ "avg_mutation_score_pct": _to_pct(summary.get("avg_mutation_score", 0.0)),
222
+ "fallback_rules": int(summary.get("fallback_rules", 0)),
223
+ "real_llm_rules": int(summary.get("real_llm_rules", 0)) if engine == "python" else None,
224
+ "real_llm_rate_pct": _to_pct(summary.get("real_llm_rate", 0.0)) if engine == "python" else None,
225
+ "repairs_applied": int(summary.get("repairs_applied", 0)) if engine == "python" else None,
226
+ }
227
+ )
228
+ return pd.DataFrame(rows)
229
+
230
+
231
+ def _rule_frame(rule_comparison: List[Mapping[str, object]]) -> pd.DataFrame:
232
+ rows: List[Dict[str, object]] = []
233
+ for item in rule_comparison:
234
+ engines = item.get("engines", {})
235
+ py = engines.get("python", {})
236
+ dbt = engines.get("dbt", {})
237
+ soda = engines.get("soda", {})
238
+ best_engine = str(item.get("best_engine", "python"))
239
+
240
+ effective_confidences = {
241
+ "python": float(py.get("effective_confidence", py.get("overall_confidence", 0.0))),
242
+ "dbt": float(dbt.get("effective_confidence", dbt.get("overall_confidence", 0.0))),
243
+ "soda": float(soda.get("effective_confidence", soda.get("overall_confidence", 0.0))),
244
+ }
245
+ sorted_conf = sorted(effective_confidences.values(), reverse=True)
246
+ margin = sorted_conf[0] - sorted_conf[1] if len(sorted_conf) > 1 else sorted_conf[0]
247
+ decision_scores = {
248
+ "python": float(py.get("decision_score", effective_confidences["python"])),
249
+ "dbt": float(dbt.get("decision_score", effective_confidences["dbt"])),
250
+ "soda": float(soda.get("decision_score", effective_confidences["soda"])),
251
+ }
252
+ sorted_scores = sorted(decision_scores.values(), reverse=True)
253
+ score_margin = sorted_scores[0] - sorted_scores[1] if len(sorted_scores) > 1 else sorted_scores[0]
254
+
255
+ rows.append(
256
+ {
257
+ "rule_name": item.get("rule_name", ""),
258
+ "severity": item.get("severity", ""),
259
+ "condition": item.get("condition", ""),
260
+ "condition_type": item.get("condition_type", "unknown"),
261
+ "complexity": item.get("complexity", "unknown"),
262
+ "declarative_friendly": bool(item.get("declarative_friendly", False)),
263
+ "jurisdiction": str(item.get("jurisdiction", "global")),
264
+ "regulatory_type": str(item.get("regulatory_type", "")),
265
+ "legal_citation": str(item.get("legal_citation", "")),
266
+ "review_status": str(item.get("review_status", "")),
267
+ "products_tested": int(item.get("products_tested", 0)),
268
+ "best_engine": best_engine,
269
+ "best_effective_pct": _to_pct(effective_confidences.get(best_engine, 0.0)),
270
+ "effective_margin_pct": round(margin * 100, 2),
271
+ "best_decision_score": round(decision_scores.get(best_engine, 0.0), 4),
272
+ "decision_margin": round(score_margin, 4),
273
+ "python_status": py.get("status", "n/a"),
274
+ "dbt_status": dbt.get("status", "n/a"),
275
+ "soda_status": soda.get("status", "n/a"),
276
+ "python_effective_pct": _to_pct(py.get("effective_confidence", py.get("overall_confidence", 0.0))),
277
+ "dbt_effective_pct": _to_pct(dbt.get("effective_confidence", dbt.get("overall_confidence", 0.0))),
278
+ "soda_effective_pct": _to_pct(soda.get("effective_confidence", soda.get("overall_confidence", 0.0))),
279
+ "python_decision_score": round(decision_scores["python"], 4),
280
+ "dbt_decision_score": round(decision_scores["dbt"], 4),
281
+ "soda_decision_score": round(decision_scores["soda"], 4),
282
+ "python_overall_pct": _to_pct(py.get("overall_confidence", 0.0)),
283
+ "dbt_overall_pct": _to_pct(dbt.get("overall_confidence", 0.0)),
284
+ "soda_overall_pct": _to_pct(soda.get("overall_confidence", 0.0)),
285
+ "python_equivalence_pct": _to_pct(py.get("equivalence_match_rate", 1.0)),
286
+ "python_mutation_pct": _to_pct(py.get("mutation_score", 1.0)),
287
+ "python_verification_pct": _to_pct(py.get("verification_score", 1.0)),
288
+ "python_repair_applied": bool(py.get("counterexample_repair_applied", False)),
289
+ "python_mismatches": int(py.get("mismatches", 0)),
290
+ "dbt_mismatches": int(dbt.get("mismatches", 0)),
291
+ "soda_mismatches": int(soda.get("mismatches", 0)),
292
+ "python_real_llm": bool(py.get("real_llm_used", False)),
293
+ "python_provider": py.get("conversion_provider", ""),
294
+ "dbt_provider": dbt.get("conversion_provider", ""),
295
+ "soda_provider": soda.get("conversion_provider", ""),
296
+ "selection_reason": item.get("selection_reason", ""),
297
+ "declarative_tie_break_applied": bool(item.get("declarative_tie_break_applied", False)),
298
+ "recommendation": item.get("recommendation", ""),
299
+ }
300
+ )
301
+ frame = pd.DataFrame(rows)
302
+ if frame.empty:
303
+ return frame
304
+ return frame.sort_values(by=["best_effective_pct", "rule_name"], ascending=[False, True]).reset_index(drop=True)
305
+
306
+
307
+ def _build_effective_chart(frame: pd.DataFrame) -> go.Figure:
308
+ chart = frame[["rule_name", "python_effective_pct", "dbt_effective_pct", "soda_effective_pct"]].copy()
309
+ chart = chart.melt(id_vars=["rule_name"], var_name="engine", value_name="effective_pct")
310
+ chart["engine"] = chart["engine"].str.replace("_effective_pct", "", regex=False).str.upper()
311
+ fig = px.bar(
312
+ chart,
313
+ x="rule_name",
314
+ y="effective_pct",
315
+ color="engine",
316
+ barmode="group",
317
+ color_discrete_map={"PYTHON": ENGINE_COLORS["python"], "DBT": ENGINE_COLORS["dbt"], "SODA": ENGINE_COLORS["soda"]},
318
+ )
319
+ fig.update_layout(
320
+ height=460,
321
+ margin=dict(l=20, r=20, t=30, b=80),
322
+ xaxis=dict(title=None, tickangle=-30),
323
+ yaxis=dict(title="Effective confidence (%)", range=[0, 100]),
324
+ legend=dict(orientation="h", y=1.08, x=0),
325
+ plot_bgcolor="#ffffff",
326
+ paper_bgcolor="#ffffff",
327
+ )
328
+ return fig
329
+
330
+
331
+ def _build_best_engine_chart(frame: pd.DataFrame) -> go.Figure:
332
+ dist = frame["best_engine"].value_counts().rename_axis("engine").reset_index(name="rules")
333
+ fig = px.pie(
334
+ dist,
335
+ names="engine",
336
+ values="rules",
337
+ hole=0.58,
338
+ color="engine",
339
+ color_discrete_map=ENGINE_COLORS,
340
+ )
341
+ fig.update_layout(height=420, margin=dict(l=5, r=5, t=10, b=10), legend=dict(orientation="h", y=-0.1, x=0))
342
+ fig.update_traces(textinfo="label+value")
343
+ return fig
344
+
345
+
346
+ def _complexity_summary_frame(per_complexity_summary: Mapping[str, Mapping[str, object]]) -> pd.DataFrame:
347
+ rows: List[Dict[str, object]] = []
348
+ for tier in ("simple", "medium", "intricate", "unknown"):
349
+ info = per_complexity_summary.get(tier)
350
+ if not info:
351
+ continue
352
+ rows.append(
353
+ {
354
+ "complexity": tier,
355
+ "rules": int(info.get("rules", 0)),
356
+ "python_wins": int(info.get("python_wins", 0)),
357
+ "dbt_wins": int(info.get("dbt_wins", 0)),
358
+ "soda_wins": int(info.get("soda_wins", 0)),
359
+ "avg_best_effective_pct": _to_pct(info.get("avg_best_effective_confidence", 0.0)),
360
+ }
361
+ )
362
+ return pd.DataFrame(rows)
363
+
364
+
365
+ def _engine_detail_frame(selected_rule: Mapping[str, object]) -> pd.DataFrame:
366
+ rows: List[Dict[str, object]] = []
367
+ engines = selected_rule.get("engines", {})
368
+ for engine in ("python", "dbt", "soda"):
369
+ row = engines.get(engine, {})
370
+ rows.append(
371
+ {
372
+ "engine": engine.upper(),
373
+ "status": row.get("status", "n/a"),
374
+ "overall_confidence_pct": _to_pct(row.get("overall_confidence", 0.0)),
375
+ "effective_confidence_pct": _to_pct(row.get("effective_confidence", row.get("overall_confidence", 0.0))),
376
+ "decision_score": float(row.get("decision_score", row.get("effective_confidence", 0.0))),
377
+ "parity_ci_low_pct": _to_pct(row.get("parity_ci_lower", 0.0)),
378
+ "equivalence_pct": _to_pct(row.get("equivalence_match_rate", 1.0)),
379
+ "mutation_pct": _to_pct(row.get("mutation_score", 1.0)),
380
+ "verification_pct": _to_pct(row.get("verification_score", 1.0)),
381
+ "mismatches": int(row.get("mismatches", 0)),
382
+ "provider_factor_pct": _to_pct(row.get("provider_factor", 0.0)),
383
+ "provider": row.get("conversion_provider", ""),
384
+ "execution_mode": row.get("execution_mode", ""),
385
+ "cloud_connected": bool(row.get("cloud_connected", False)),
386
+ "cloud_scan_id": row.get("cloud_scan_id", ""),
387
+ "cloud_scan_url": row.get("cloud_scan_url", ""),
388
+ "real_llm_used": bool(row.get("real_llm_used")) if engine == "python" else None,
389
+ "repair_applied": bool(row.get("counterexample_repair_applied", False)) if engine == "python" else None,
390
+ "artifact_lines": int(row.get("conversion_lines", 0)),
391
+ }
392
+ )
393
+ return pd.DataFrame(rows)
394
+
395
+
396
+ def _engine_artifact(selected_rule: Mapping[str, object], engine: str) -> str:
397
+ return str(selected_rule.get("engines", {}).get(engine, {}).get("conversion_artifact", "")).strip()
398
+
399
+
400
+ def _engine_failed_cases(selected_rule: Mapping[str, object], engine: str) -> List[Mapping[str, object]]:
401
+ return list(selected_rule.get("engines", {}).get(engine, {}).get("failed_test_cases", []))
402
+
403
+
404
+ def _engine_equivalence_counterexamples(selected_rule: Mapping[str, object], engine: str) -> List[Mapping[str, object]]:
405
+ return list(selected_rule.get("engines", {}).get(engine, {}).get("equivalence_counterexamples", []))
406
+
407
+
408
+ def main() -> None:
409
+ st.set_page_config(page_title="OFF Migration Comparison Dashboard", layout="wide")
410
+ _inject_theme()
411
+ st.markdown(
412
+ """
413
+ <div class="hero">
414
+ <h1>Open Food Facts Migration Comparison Dashboard</h1>
415
+ <p>Compare Python (LLM), dbt, and Soda migrations for every rule, side-by-side.</p>
416
+ </div>
417
+ """,
418
+ unsafe_allow_html=True,
419
+ )
420
+
421
+ with st.sidebar:
422
+ st.subheader("Comparison Run")
423
+ size = st.slider("Dataset size", min_value=100, max_value=500, value=300, step=25)
424
+ default_mode = "OFF JSONL" if DEFAULT_SOURCE_JSONL.exists() else "Synthetic"
425
+ dataset_mode = st.radio("Dataset mode", options=["OFF JSONL", "Synthetic"], index=0 if default_mode == "OFF JSONL" else 1)
426
+ use_off_source = dataset_mode == "OFF JSONL"
427
+ seed = st.number_input("Seed (synthetic mode)", min_value=1, max_value=99999, value=17, disabled=use_off_source)
428
+ source_jsonl_text = st.text_input("Source JSONL path", value=str(DEFAULT_SOURCE_JSONL), disabled=not use_off_source)
429
+ perl_rules_dir_text = st.text_input("Perl rules directory (optional)", value="")
430
+ llm_provider = "groq"
431
+ st.caption("Python engine uses Groq for LLM conversion in this dashboard.")
432
+ llm_model = st.text_input("LLM model override", value="openai/gpt-oss-120b")
433
+ soda_mode = st.selectbox(
434
+ "Soda mode",
435
+ options=["local", "cloud"],
436
+ index=0,
437
+ help="Use `cloud` to attempt Soda Cloud scan publishing; falls back to local if unavailable.",
438
+ )
439
+ profile = st.selectbox("Rule profile", options=list(SUPPORTED_PROFILES), index=list(SUPPORTED_PROFILES).index(DEFAULT_PROFILE))
440
+ has_groq_key = bool(os.getenv("GROQ_API_KEY"))
441
+ if not has_groq_key:
442
+ st.warning("GROQ_API_KEY is not set. Python engine will fall back unless key is provided.")
443
+
444
+ if st.button("Run Full Comparison"):
445
+ try:
446
+ if not has_groq_key:
447
+ raise RuntimeError("GROQ_API_KEY is required. Set it before running the comparison.")
448
+ with st.spinner("Running Python + dbt + Soda comparison..."):
449
+ run_engine_comparison(
450
+ dataset_size=int(size),
451
+ seed=int(seed),
452
+ source_jsonl=Path(source_jsonl_text) if use_off_source else None,
453
+ use_default_off_source=use_off_source,
454
+ llm_provider=llm_provider,
455
+ llm_model=llm_model.strip() or None,
456
+ perl_rules_dir=Path(perl_rules_dir_text) if perl_rules_dir_text.strip() else None,
457
+ results_path=COMPARISON_PATH,
458
+ require_real_llm=True,
459
+ profile=profile,
460
+ soda_mode=soda_mode,
461
+ )
462
+ st.success("Comparison completed.")
463
+ except Exception as exc: # noqa: BLE001
464
+ st.error(str(exc))
465
+
466
+ payload = load_report()
467
+ if not payload:
468
+ st.info("No comparison report found yet. Click 'Run Full Comparison' in the sidebar.")
469
+ return
470
+
471
+ dataset = payload.get("dataset", {})
472
+ rule_comparison = list(payload.get("rule_comparison", []))
473
+ engine_summary = payload.get("per_engine_summary", {})
474
+ complexity_summary = payload.get("per_complexity_summary", {})
475
+ run_config = payload.get("run_config", {})
476
+ comparison_method = payload.get("comparison_method", {})
477
+ comparison_fingerprint = payload.get("comparison_fingerprint", {})
478
+ frame = _rule_frame(rule_comparison)
479
+ if frame.empty:
480
+ st.warning("Comparison report has no rule rows.")
481
+ return
482
+
483
+ python_wins = int((frame["best_engine"] == "python").sum())
484
+ dbt_wins = int((frame["best_engine"] == "dbt").sum())
485
+ soda_wins = int((frame["best_engine"] == "soda").sum())
486
+ avg_best = frame["best_effective_pct"].mean()
487
+ canada_rules = int((frame["jurisdiction"] == "ca").sum()) if "jurisdiction" in frame.columns else 0
488
+
489
+ k1, k2, k3 = st.columns(3, gap="large")
490
+ with k1:
491
+ _render_stat_chip("Rules compared", len(frame))
492
+ with k2:
493
+ _render_stat_chip("Python wins", python_wins)
494
+ with k3:
495
+ _render_stat_chip("dbt wins", dbt_wins)
496
+ k4, k5, k6 = st.columns(3, gap="large")
497
+ with k4:
498
+ _render_stat_chip("Soda wins", soda_wins)
499
+ with k5:
500
+ _render_stat_chip("Avg best effective %", f"{avg_best:.2f}%")
501
+ with k6:
502
+ _render_stat_chip("Canada rules", canada_rules)
503
+
504
+ st.caption(f"Generated at: {payload.get('generated_at_utc', 'n/a')}")
505
+ st.caption(f"Dataset size: {dataset.get('products_tested', 'n/a')}")
506
+ st.caption(f"Dataset source: {dataset.get('source_jsonl', 'n/a')}")
507
+ st.caption(f"Profile: {dataset.get('profile', DEFAULT_PROFILE)}")
508
+ st.caption(
509
+ "Confidence context: we compare engines using effective confidence "
510
+ "(overall confidence x provider factor), with status and mismatches prioritized."
511
+ )
512
+ if run_config:
513
+ st.caption(
514
+ f"LLM provider={run_config.get('llm_provider', 'n/a')} | "
515
+ f"GROQ key set={run_config.get('groq_api_key_set')} | "
516
+ f"Require real LLM={run_config.get('require_real_llm')} | "
517
+ f"Run profile={run_config.get('profile', DEFAULT_PROFILE)} | "
518
+ f"Soda mode={run_config.get('soda_mode', 'local')} | "
519
+ f"Soda Cloud creds set={run_config.get('soda_cloud_credentials_set', False)}"
520
+ )
521
+ if comparison_fingerprint:
522
+ st.caption(
523
+ f"Comparison run ID: {comparison_fingerprint.get('comparison_run_id', 'n/a')} | "
524
+ f"Run SHA: {str(comparison_fingerprint.get('comparison_sha256', ''))[:12]}"
525
+ )
526
+ st.caption(
527
+ f"Dataset fingerprint: {str(comparison_fingerprint.get('dataset_fingerprint_sha256', ''))[:16]} | "
528
+ f"Rulepack fingerprint: {str(comparison_fingerprint.get('rulepack_fingerprint_sha256', ''))[:16]} | "
529
+ f"Commit: {str(comparison_fingerprint.get('code_commit', 'unknown'))[:12]}"
530
+ )
531
+ st.caption(
532
+ f"Cross-engine consistency -> "
533
+ f"dataset={comparison_fingerprint.get('dataset_fingerprint_consistent', False)} | "
534
+ f"rulepack={comparison_fingerprint.get('rulepack_fingerprint_consistent', False)}"
535
+ )
536
+ selection_lines: List[str] = [
537
+ str(
538
+ comparison_method.get(
539
+ "best_engine_ranking",
540
+ "Prefer MATCH status, then fewer mismatches, then higher effective confidence.",
541
+ )
542
+ )
543
+ ]
544
+ if comparison_method.get("hybrid_tie_break"):
545
+ selection_lines.append(str(comparison_method["hybrid_tie_break"]))
546
+ if comparison_method.get("declarative_tie_break"):
547
+ selection_lines.append(str(comparison_method["declarative_tie_break"]))
548
+ _render_explain_chip("How Best Migration Is Chosen", selection_lines)
549
+
550
+ st.subheader("Engine Summary")
551
+ summary_frame = _engine_summary_frame(engine_summary)
552
+ st.dataframe(
553
+ summary_frame,
554
+ use_container_width=True,
555
+ hide_index=True,
556
+ column_config={
557
+ "engine": st.column_config.TextColumn("Engine"),
558
+ "rules": st.column_config.NumberColumn("Rules", format="%d"),
559
+ "passed": st.column_config.NumberColumn("Passed", format="%d"),
560
+ "avg_overall_confidence_pct": st.column_config.NumberColumn("Avg overall %", format="%.2f"),
561
+ "avg_effective_confidence_pct": st.column_config.NumberColumn("Avg effective %", format="%.2f"),
562
+ "avg_parity_ci_low_pct": st.column_config.NumberColumn("Avg parity CI low %", format="%.2f"),
563
+ "avg_equivalence_rate_pct": st.column_config.NumberColumn("Avg equivalence %", format="%.2f"),
564
+ "avg_mutation_score_pct": st.column_config.NumberColumn("Avg mutation %", format="%.2f"),
565
+ "fallback_rules": st.column_config.NumberColumn("Fallback rules", format="%d"),
566
+ "real_llm_rules": st.column_config.NumberColumn("Real LLM rules", format="%d"),
567
+ "real_llm_rate_pct": st.column_config.NumberColumn("Real LLM rate %", format="%.2f"),
568
+ "repairs_applied": st.column_config.NumberColumn("Repairs applied", format="%d"),
569
+ },
570
+ )
571
+
572
+ complexity_frame = _complexity_summary_frame(complexity_summary)
573
+ if not complexity_frame.empty:
574
+ st.subheader("Mixed-Complexity Benchmark Summary")
575
+ st.dataframe(
576
+ complexity_frame,
577
+ use_container_width=True,
578
+ hide_index=True,
579
+ column_config={
580
+ "complexity": st.column_config.TextColumn("Complexity tier"),
581
+ "rules": st.column_config.NumberColumn("Rules", format="%d"),
582
+ "python_wins": st.column_config.NumberColumn("Python wins", format="%d"),
583
+ "dbt_wins": st.column_config.NumberColumn("dbt wins", format="%d"),
584
+ "soda_wins": st.column_config.NumberColumn("Soda wins", format="%d"),
585
+ "avg_best_effective_pct": st.column_config.NumberColumn("Avg best effective %", format="%.2f"),
586
+ },
587
+ )
588
+
589
+ left, right = st.columns([0.72, 0.28], gap="large")
590
+ with left:
591
+ st.subheader("Effective Confidence by Rule and Engine")
592
+ st.plotly_chart(_build_effective_chart(frame), use_container_width=True)
593
+ with right:
594
+ st.subheader("Best Engine Distribution")
595
+ st.plotly_chart(_build_best_engine_chart(frame), use_container_width=True)
596
+
597
+ st.subheader("Rule Validation Table (Comparison View)")
598
+ show_advanced = st.checkbox("Show advanced metrics", value=False)
599
+ show_providers = st.checkbox("Show provider columns", value=False)
600
+ jurisdictions = sorted(frame["jurisdiction"].dropna().unique().tolist())
601
+ selected_jurisdictions = st.multiselect("Filter jurisdiction", options=jurisdictions, default=jurisdictions)
602
+ table_frame = frame[frame["jurisdiction"].isin(selected_jurisdictions)] if selected_jurisdictions else frame
603
+ columns = [
604
+ "rule_name",
605
+ "jurisdiction",
606
+ "regulatory_type",
607
+ "review_status",
608
+ "legal_citation",
609
+ "complexity",
610
+ "condition_type",
611
+ "severity",
612
+ "best_engine",
613
+ "best_effective_pct",
614
+ "decision_margin",
615
+ "recommendation",
616
+ ]
617
+ if show_advanced:
618
+ columns.extend(
619
+ [
620
+ "best_decision_score",
621
+ "effective_margin_pct",
622
+ "python_effective_pct",
623
+ "dbt_effective_pct",
624
+ "soda_effective_pct",
625
+ "python_equivalence_pct",
626
+ "python_mutation_pct",
627
+ "python_verification_pct",
628
+ "python_repair_applied",
629
+ "python_mismatches",
630
+ "dbt_mismatches",
631
+ "soda_mismatches",
632
+ "python_real_llm",
633
+ "declarative_tie_break_applied",
634
+ "selection_reason",
635
+ ]
636
+ )
637
+ if show_providers:
638
+ columns.extend(["python_provider", "dbt_provider", "soda_provider"])
639
+ st.dataframe(
640
+ table_frame[columns],
641
+ use_container_width=True,
642
+ hide_index=True,
643
+ column_config={
644
+ "rule_name": st.column_config.TextColumn("Rule"),
645
+ "jurisdiction": st.column_config.TextColumn("Jurisdiction"),
646
+ "regulatory_type": st.column_config.TextColumn("Regulatory type"),
647
+ "review_status": st.column_config.TextColumn("Review status"),
648
+ "legal_citation": st.column_config.TextColumn("Legal citation"),
649
+ "complexity": st.column_config.TextColumn("Complexity"),
650
+ "condition_type": st.column_config.TextColumn("Condition type"),
651
+ "severity": st.column_config.TextColumn("Severity"),
652
+ "best_engine": st.column_config.TextColumn("Best migration"),
653
+ "best_effective_pct": st.column_config.NumberColumn("Best effective %", format="%.2f"),
654
+ "best_decision_score": st.column_config.NumberColumn("Best decision score", format="%.4f"),
655
+ "effective_margin_pct": st.column_config.NumberColumn("Win margin %", format="%.2f"),
656
+ "decision_margin": st.column_config.NumberColumn("Score margin", format="%.4f"),
657
+ "python_effective_pct": st.column_config.NumberColumn("Python effective %", format="%.2f"),
658
+ "dbt_effective_pct": st.column_config.NumberColumn("dbt effective %", format="%.2f"),
659
+ "soda_effective_pct": st.column_config.NumberColumn("Soda effective %", format="%.2f"),
660
+ "python_equivalence_pct": st.column_config.NumberColumn("Python equiv %", format="%.2f"),
661
+ "python_mutation_pct": st.column_config.NumberColumn("Python mutation %", format="%.2f"),
662
+ "python_verification_pct": st.column_config.NumberColumn("Python verify %", format="%.2f"),
663
+ "python_repair_applied": st.column_config.CheckboxColumn("Repair applied"),
664
+ "python_mismatches": st.column_config.NumberColumn("Python mismatches", format="%d"),
665
+ "dbt_mismatches": st.column_config.NumberColumn("dbt mismatches", format="%d"),
666
+ "soda_mismatches": st.column_config.NumberColumn("Soda mismatches", format="%d"),
667
+ "python_real_llm": st.column_config.CheckboxColumn("Python real LLM"),
668
+ "declarative_tie_break_applied": st.column_config.CheckboxColumn("dbt/soda tie-break"),
669
+ "selection_reason": st.column_config.TextColumn("Selection reason"),
670
+ "recommendation": st.column_config.TextColumn("Recommendation"),
671
+ "python_provider": st.column_config.TextColumn("Python provider"),
672
+ "dbt_provider": st.column_config.TextColumn("dbt provider"),
673
+ "soda_provider": st.column_config.TextColumn("Soda provider"),
674
+ },
675
+ )
676
+
677
+ st.subheader("Rule Detail")
678
+ rule_names = [row.get("rule_name", "") for row in rule_comparison]
679
+ selected_rule_name = st.selectbox("Select rule", rule_names)
680
+ selected_rule = next(row for row in rule_comparison if row.get("rule_name") == selected_rule_name)
681
+
682
+ d1, d2, d3 = st.columns(3, gap="large")
683
+ with d1:
684
+ _render_stat_chip("Best migration", str(selected_rule.get("best_engine", "n/a")).upper())
685
+ with d2:
686
+ _render_stat_chip("Severity", str(selected_rule.get("severity", "n/a")))
687
+ with d3:
688
+ _render_stat_chip("Products tested", int(selected_rule.get("products_tested", 0)))
689
+ best_engine = str(selected_rule.get("best_engine", "python"))
690
+ best_effective = selected_rule.get("engines", {}).get(best_engine, {}).get("effective_confidence", 0.0)
691
+ detail_row = frame.loc[frame["rule_name"] == selected_rule_name].iloc[0]
692
+ d4, d5 = st.columns(2, gap="large")
693
+ with d4:
694
+ _render_stat_chip("Best effective %", f"{_to_pct(best_effective):.2f}")
695
+ with d5:
696
+ _render_stat_chip("Decision margin", f"{float(detail_row['decision_margin']):.4f}")
697
+
698
+ st.caption(f"Condition: {selected_rule.get('condition', 'n/a')}")
699
+ st.caption(f"Rule IR hash: {selected_rule.get('rule_ir_hash', 'n/a')}")
700
+ st.caption(f"Condition type: {selected_rule.get('condition_type', 'n/a')}")
701
+ st.caption(f"Complexity tier: {selected_rule.get('complexity', 'n/a')}")
702
+ st.caption(f"Declarative friendly: {selected_rule.get('declarative_friendly', 'n/a')}")
703
+ st.caption(f"Jurisdiction: {selected_rule.get('jurisdiction', 'global')}")
704
+ st.caption(f"Regulatory type: {selected_rule.get('regulatory_type', 'n/a')}")
705
+ st.caption(f"Legal citation: {selected_rule.get('legal_citation', 'n/a')}")
706
+ source_url = str(selected_rule.get("source_url", "")).strip()
707
+ if source_url:
708
+ st.markdown(f"Source URL: [{source_url}]({source_url})")
709
+ else:
710
+ st.caption("Source URL: n/a")
711
+ st.caption(f"Effective date: {selected_rule.get('effective_date', 'n/a')}")
712
+ st.caption(f"Review status: {selected_rule.get('review_status', 'n/a')}")
713
+ st.caption(f"Reviewer: {selected_rule.get('reviewer', 'n/a')}")
714
+ st.caption(f"Exemption logic: {selected_rule.get('exemption_logic', 'n/a')}")
715
+ st.caption(f"Selection reason: {selected_rule.get('selection_reason', 'n/a')}")
716
+ st.caption(f"dbt/soda explicit tie-break applied: {selected_rule.get('declarative_tie_break_applied', False)}")
717
+ st.caption(f"Recommendation: {selected_rule.get('recommendation', 'n/a')}")
718
+ soda_meta = selected_rule.get("engines", {}).get("soda", {})
719
+ st.caption(
720
+ "Soda execution: "
721
+ f"mode={soda_meta.get('execution_mode', 'n/a')} | "
722
+ f"cloud_connected={soda_meta.get('cloud_connected', False)} | "
723
+ f"scan_id={soda_meta.get('cloud_scan_id', '') or 'n/a'}"
724
+ )
725
+ soda_scan_url = str(soda_meta.get("cloud_scan_url", "")).strip()
726
+ if soda_scan_url:
727
+ st.markdown(f"Soda Cloud scan URL: [{soda_scan_url}]({soda_scan_url})")
728
+
729
+ st.markdown("**Engine metrics for selected rule**")
730
+ st.dataframe(
731
+ _engine_detail_frame(selected_rule),
732
+ use_container_width=True,
733
+ hide_index=True,
734
+ column_config={
735
+ "engine": st.column_config.TextColumn("Engine"),
736
+ "status": st.column_config.TextColumn("Status"),
737
+ "overall_confidence_pct": st.column_config.NumberColumn("Overall %", format="%.2f"),
738
+ "effective_confidence_pct": st.column_config.NumberColumn("Effective %", format="%.2f"),
739
+ "decision_score": st.column_config.NumberColumn("Decision score", format="%.4f"),
740
+ "parity_ci_low_pct": st.column_config.NumberColumn("Parity CI low %", format="%.2f"),
741
+ "equivalence_pct": st.column_config.NumberColumn("Equivalence %", format="%.2f"),
742
+ "mutation_pct": st.column_config.NumberColumn("Mutation %", format="%.2f"),
743
+ "verification_pct": st.column_config.NumberColumn("Verification %", format="%.2f"),
744
+ "mismatches": st.column_config.NumberColumn("Mismatches", format="%d"),
745
+ "provider_factor_pct": st.column_config.NumberColumn("Provider factor %", format="%.2f"),
746
+ "provider": st.column_config.TextColumn("Provider"),
747
+ "execution_mode": st.column_config.TextColumn("Execution mode"),
748
+ "cloud_connected": st.column_config.CheckboxColumn("Cloud connected"),
749
+ "cloud_scan_id": st.column_config.TextColumn("Cloud scan ID"),
750
+ "cloud_scan_url": st.column_config.TextColumn("Cloud scan URL"),
751
+ "real_llm_used": st.column_config.CheckboxColumn("Real LLM used"),
752
+ "repair_applied": st.column_config.CheckboxColumn("Repair applied"),
753
+ "artifact_lines": st.column_config.NumberColumn("Artifact lines", format="%d"),
754
+ },
755
+ )
756
+
757
+ st.markdown("**All three migration artifacts for this rule**")
758
+ c1, c2, c3 = st.columns(3, gap="large")
759
+ with c1:
760
+ st.markdown("`PYTHON`")
761
+ st.code(_engine_artifact(selected_rule, "python"), language="python")
762
+ with c2:
763
+ st.markdown("`DBT`")
764
+ st.code(_engine_artifact(selected_rule, "dbt"), language="sql")
765
+ with c3:
766
+ st.markdown("`SODA`")
767
+ st.code(_engine_artifact(selected_rule, "soda"), language="yaml")
768
+
769
+ st.markdown("**Python Equivalence Counterexamples**")
770
+ python_counterexamples = _engine_equivalence_counterexamples(selected_rule, "python")
771
+ if python_counterexamples:
772
+ st.dataframe(pd.DataFrame(python_counterexamples), use_container_width=True, hide_index=True)
773
+ else:
774
+ st.success("No Python equivalence counterexamples.")
775
+
776
+ st.markdown("**Parity mismatch samples by engine**")
777
+ for engine, title in [("python", "Python"), ("dbt", "dbt"), ("soda", "Soda")]:
778
+ st.markdown(f"`{title}`")
779
+ failed_cases = _engine_failed_cases(selected_rule, engine)
780
+ if failed_cases:
781
+ st.dataframe(pd.DataFrame(failed_cases), use_container_width=True, hide_index=True)
782
+ else:
783
+ st.success(f"No mismatches for {title}.")
784
+
785
+
786
+ if __name__ == "__main__":
787
+ main()
OFF_DataQuality/data/__init__.py ADDED
File without changes
OFF_DataQuality/data/load_dataset.py ADDED
@@ -0,0 +1,494 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Dataset utilities for the migration prototype.
2
+
3
+ This module creates a reduced Open Food Facts-like JSONL dataset and loads
4
+ it into DuckDB for downstream parity validation.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import argparse
9
+ import json
10
+ import random
11
+ from dataclasses import dataclass
12
+ from pathlib import Path
13
+ from typing import Dict, Iterable, List, Mapping
14
+
15
+ PROJECT_ROOT = Path(__file__).resolve().parent.parent
16
+ DB_PATH = PROJECT_ROOT / "off_quality.db"
17
+ SAMPLE_FILE = Path(__file__).resolve().parent / "sample_products.jsonl"
18
+ DEFAULT_OFF_JSONL = PROJECT_ROOT / "openfoodfacts-products.jsonl"
19
+
20
+ CORE_FIELDS = [
21
+ "product_id",
22
+ "energy_kj",
23
+ "energy_kj_computed",
24
+ "energy_kcal",
25
+ "fat",
26
+ "saturated_fat",
27
+ "carbohydrates",
28
+ "sugars",
29
+ "starch",
30
+ "sodium",
31
+ "ingredients_text",
32
+ "ingredients_text_present",
33
+ "contains_statement_present",
34
+ "allergen_evidence_present",
35
+ "fop_threshold_exceeded",
36
+ "fop_symbol_present",
37
+ "fop_exempt_proxy",
38
+ "product_is_prepackaged_proxy",
39
+ ]
40
+
41
+ # Additional fields used for OFF language-related checks.
42
+ OPTIONAL_FIELDS = ["lc", "lang", "language_code"]
43
+
44
+
45
+ def _to_int_flag(value: bool) -> int:
46
+ return 1 if value else 0
47
+
48
+
49
+ def _compute_fop_threshold_exceeded(sugars: object, saturated_fat: object, sodium: object) -> int:
50
+ """Proxy Front-of-Pack trigger for prototype experiments.
51
+
52
+ This is intentionally a simplified threshold model to exercise migration
53
+ architecture and should not be interpreted as full legal implementation.
54
+ """
55
+ sugars_val = _to_float(sugars) or 0.0
56
+ sat_fat_val = _to_float(saturated_fat) or 0.0
57
+ sodium_val = _to_float(sodium) or 0.0
58
+ return _to_int_flag((sugars_val >= 15.0) or (sat_fat_val >= 6.0) or (sodium_val >= 0.6))
59
+
60
+
61
+ @dataclass(frozen=True)
62
+ class DatasetConfig:
63
+ """Configuration for synthetic dataset generation."""
64
+
65
+ size: int = 300
66
+ seed: int = 17
67
+ output_path: Path = SAMPLE_FILE
68
+
69
+
70
+ def _maybe(probability: float, rng: random.Random) -> bool:
71
+ return rng.random() < probability
72
+
73
+
74
+ def _to_float(value: object) -> float | None:
75
+ if value is None:
76
+ return None
77
+ if isinstance(value, bool):
78
+ return None
79
+ if isinstance(value, (int, float)):
80
+ return float(value)
81
+ if isinstance(value, str):
82
+ text = value.strip()
83
+ if not text:
84
+ return None
85
+ try:
86
+ return float(text)
87
+ except ValueError:
88
+ return None
89
+ return None
90
+
91
+
92
+ def _first_number(*values: object) -> float | None:
93
+ for value in values:
94
+ parsed = _to_float(value)
95
+ if parsed is not None:
96
+ return parsed
97
+ return None
98
+
99
+
100
+ def _apply_deterministic_synthetic_scenarios(index: int, product: Dict[str, object], rng: random.Random) -> None:
101
+ """Inject deterministic rule-violation scenarios for synthetic datasets.
102
+
103
+ This keeps synthetic runs visually informative in the dashboard by ensuring
104
+ each rule receives recurring, known-positive examples.
105
+ """
106
+ bucket = index % 21
107
+
108
+ if bucket == 1:
109
+ # energy_kcal > energy_kj
110
+ energy_kj = float(product["energy_kj"])
111
+ product["energy_kcal"] = round(energy_kj + rng.uniform(1.0, 50.0), 1)
112
+ elif bucket == 2:
113
+ # energy_kj < (3.7 * energy_kcal - 2)
114
+ energy_kcal = round(rng.uniform(80.0, 320.0), 1)
115
+ product["energy_kcal"] = energy_kcal
116
+ product["energy_kj"] = round((3.7 * energy_kcal) - rng.uniform(3.0, 30.0), 1)
117
+ elif bucket == 3:
118
+ # energy_kj > (4.7 * energy_kcal + 2)
119
+ energy_kcal = round(rng.uniform(80.0, 320.0), 1)
120
+ product["energy_kcal"] = energy_kcal
121
+ product["energy_kj"] = round((4.7 * energy_kcal) + rng.uniform(3.0, 30.0), 1)
122
+ elif bucket == 4:
123
+ # energy_kj > 3911
124
+ product["energy_kj"] = round(rng.uniform(3912.0, 5200.0), 1)
125
+ elif bucket == 5:
126
+ # saturated_fat > (fat + 0.001)
127
+ fat = round(rng.uniform(10.0, 80.0), 3)
128
+ product["fat"] = fat
129
+ product["saturated_fat"] = round(fat + rng.uniform(0.01, 9.0), 3)
130
+ elif bucket == 6:
131
+ # sugars + starch > carbohydrates + 0.001
132
+ carbs = round(rng.uniform(10.0, 90.0), 3)
133
+ sugars = round(rng.uniform(3.0, 60.0), 3)
134
+ starch = round(max((carbs - sugars) + rng.uniform(0.01, 6.0), 0.0), 3)
135
+ product["carbohydrates"] = carbs
136
+ product["sugars"] = sugars
137
+ product["starch"] = starch
138
+ elif bucket == 7:
139
+ # fat > 105
140
+ product["fat"] = round(rng.uniform(106.0, 135.0), 1)
141
+ elif bucket == 8:
142
+ # saturated_fat > 105
143
+ product["saturated_fat"] = round(rng.uniform(106.0, 135.0), 1)
144
+ elif bucket == 9:
145
+ # carbohydrates > 105
146
+ product["carbohydrates"] = round(rng.uniform(106.0, 140.0), 1)
147
+ elif bucket == 10:
148
+ # sugars > 105
149
+ product["sugars"] = round(rng.uniform(106.0, 140.0), 1)
150
+ elif bucket == 11:
151
+ # missing lc
152
+ product["lc"] = ""
153
+ product["language_code"] = ""
154
+ elif bucket == 12:
155
+ # missing lang
156
+ product["lang"] = ""
157
+ if product.get("lc"):
158
+ product["language_code"] = str(product["lc"])
159
+ else:
160
+ product["language_code"] = ""
161
+ elif bucket == 13:
162
+ # energy_kj_computed < (0.7 * energy_kj - 5)
163
+ energy_kj = float(product["energy_kj"])
164
+ product["energy_kj_computed"] = round((0.7 * energy_kj) - rng.uniform(6.0, 25.0), 1)
165
+ elif bucket == 14:
166
+ # energy_kj_computed > (1.3 * energy_kj + 5)
167
+ energy_kj = float(product["energy_kj"])
168
+ product["energy_kj_computed"] = round((1.3 * energy_kj) + rng.uniform(6.0, 25.0), 1)
169
+ elif bucket == 15:
170
+ # Allergen evidence present but ingredients text missing.
171
+ product["allergen_evidence_present"] = 1
172
+ product["contains_statement_present"] = 1
173
+ product["ingredients_text"] = ""
174
+ product["ingredients_text_present"] = 0
175
+ elif bucket == 16:
176
+ # Contains statement present without allergen evidence.
177
+ product["contains_statement_present"] = 1
178
+ product["allergen_evidence_present"] = 0
179
+ product["ingredients_text"] = "Contains: milk, soy."
180
+ product["ingredients_text_present"] = 1
181
+ elif bucket == 17:
182
+ # FOP required but symbol missing.
183
+ product["fop_threshold_exceeded"] = 1
184
+ product["fop_symbol_present"] = 0
185
+ product["fop_exempt_proxy"] = 0
186
+ product["product_is_prepackaged_proxy"] = 1
187
+ elif bucket == 18:
188
+ # FOP symbol present but threshold not exceeded (and not exempt).
189
+ product["fop_threshold_exceeded"] = 0
190
+ product["fop_symbol_present"] = 1
191
+ product["fop_exempt_proxy"] = 0
192
+ product["product_is_prepackaged_proxy"] = 1
193
+ elif bucket == 19:
194
+ # FOP symbol present on exempt product (proxy inconsistency).
195
+ product["fop_threshold_exceeded"] = 1
196
+ product["fop_symbol_present"] = 1
197
+ product["fop_exempt_proxy"] = 1
198
+ product["product_is_prepackaged_proxy"] = 1
199
+ elif bucket == 20:
200
+ # Not prepackaged proxy case (used to suppress FOP obligations).
201
+ product["product_is_prepackaged_proxy"] = 0
202
+ product["fop_symbol_present"] = 0
203
+
204
+
205
+ def generate_product(index: int, rng: random.Random) -> Dict[str, object]:
206
+ """Generate a single product with occasional quality rule violations."""
207
+ energy_kj = rng.randint(50, 4800)
208
+ energy_kcal = int(round(energy_kj / 4.184))
209
+
210
+ fat = round(rng.uniform(0.0, 100.0), 1)
211
+ saturated_fat = round(rng.uniform(0.0, fat), 1)
212
+ carbohydrates = round(rng.uniform(0.0, 100.0), 1)
213
+ sugars = round(rng.uniform(0.0, carbohydrates), 1)
214
+ starch = round(rng.uniform(0.0, max(carbohydrates - sugars, 0.0)), 1)
215
+ sodium = round(rng.uniform(0.0, 1.5), 3)
216
+
217
+ if _maybe(0.10, rng):
218
+ energy_kcal = energy_kj + rng.randint(1, 100)
219
+ if _maybe(0.07, rng):
220
+ energy_kj = round((3.7 * energy_kcal) - rng.uniform(3.0, 30.0), 1)
221
+ if _maybe(0.07, rng):
222
+ energy_kj = round((4.7 * energy_kcal) + rng.uniform(3.0, 30.0), 1)
223
+ if _maybe(0.08, rng):
224
+ saturated_fat = round(fat + rng.uniform(0.1, 20.0), 1)
225
+ if _maybe(0.07, rng):
226
+ starch = round(max((carbohydrates - sugars) + rng.uniform(0.01, 6.0), 0.0), 1)
227
+
228
+ energy_kj_computed = round(float(energy_kj) * rng.uniform(0.92, 1.08), 1)
229
+ if _maybe(0.06, rng):
230
+ energy_kj_computed = round((0.65 * float(energy_kj)) - rng.uniform(1.0, 8.0), 1)
231
+ if _maybe(0.06, rng):
232
+ energy_kj_computed = round((1.35 * float(energy_kj)) + rng.uniform(1.0, 8.0), 1)
233
+
234
+ product: Dict[str, object] = {
235
+ "product_id": f"{index:013d}",
236
+ "energy_kj": energy_kj,
237
+ "energy_kj_computed": energy_kj_computed,
238
+ "energy_kcal": energy_kcal,
239
+ "fat": fat,
240
+ "saturated_fat": saturated_fat,
241
+ "carbohydrates": carbohydrates,
242
+ "sugars": sugars,
243
+ "starch": starch,
244
+ "sodium": sodium,
245
+ }
246
+
247
+ for nutrient in ("fat", "saturated_fat", "carbohydrates", "sugars"):
248
+ if _maybe(0.08, rng):
249
+ product[nutrient] = round(rng.uniform(106.0, 140.0), 1)
250
+
251
+ language_code = rng.choices(
252
+ ["en", "fr", "es", "de", "it", "", None],
253
+ weights=[0.55, 0.1, 0.08, 0.06, 0.06, 0.08, 0.07],
254
+ k=1,
255
+ )[0]
256
+ lang_value = rng.choices(
257
+ ["en", "fr", "es", "de", "it", "xx", "", None],
258
+ weights=[0.5, 0.1, 0.08, 0.06, 0.06, 0.03, 0.09, 0.08],
259
+ k=1,
260
+ )[0]
261
+ product["lc"] = language_code
262
+ product["lang"] = lang_value
263
+ product["language_code"] = language_code or lang_value
264
+ ingredients_text = rng.choices(
265
+ [
266
+ "Sugar, milk powder, cocoa butter.",
267
+ "Water, apple juice concentrate.",
268
+ "Ingredients: wheat flour, salt, yeast.",
269
+ "",
270
+ None,
271
+ ],
272
+ weights=[0.30, 0.22, 0.22, 0.16, 0.10],
273
+ k=1,
274
+ )[0]
275
+ product["ingredients_text"] = ingredients_text if ingredients_text is not None else ""
276
+ product["ingredients_text_present"] = _to_int_flag(str(product["ingredients_text"]).strip() != "")
277
+
278
+ # Prototype proxies for Canadian allergen/FOP checks.
279
+ contains_statement_present = _maybe(0.22, rng)
280
+ allergen_evidence_present = contains_statement_present or _maybe(0.15, rng)
281
+ fop_threshold_exceeded = _compute_fop_threshold_exceeded(product.get("sugars"), product.get("saturated_fat"), product.get("sodium"))
282
+ fop_exempt_proxy = _to_int_flag(_maybe(0.10, rng))
283
+ product_is_prepackaged_proxy = _to_int_flag(not _maybe(0.05, rng))
284
+ fop_symbol_present = _to_int_flag(
285
+ (fop_threshold_exceeded == 1 and _maybe(0.78, rng))
286
+ or (fop_threshold_exceeded == 0 and _maybe(0.10, rng))
287
+ )
288
+
289
+ product["contains_statement_present"] = _to_int_flag(contains_statement_present)
290
+ product["allergen_evidence_present"] = _to_int_flag(allergen_evidence_present)
291
+ product["fop_threshold_exceeded"] = int(fop_threshold_exceeded)
292
+ product["fop_symbol_present"] = int(fop_symbol_present)
293
+ product["fop_exempt_proxy"] = int(fop_exempt_proxy)
294
+ product["product_is_prepackaged_proxy"] = int(product_is_prepackaged_proxy)
295
+ _apply_deterministic_synthetic_scenarios(index=index, product=product, rng=rng)
296
+ return product
297
+
298
+
299
+ def generate_products(config: DatasetConfig) -> List[Dict[str, object]]:
300
+ """Generate ``config.size`` synthetic products."""
301
+ rng = random.Random(config.seed)
302
+ return [generate_product(i, rng) for i in range(1, config.size + 1)]
303
+
304
+
305
+ def extract_product_from_off_record(record: Mapping[str, object]) -> Dict[str, object] | None:
306
+ """Extract prototype fields from one Open Food Facts product object."""
307
+ product_id = str(record.get("code") or record.get("_id") or record.get("id") or "").strip()
308
+ if not product_id:
309
+ return None
310
+
311
+ nutriments = record.get("nutriments")
312
+ if not isinstance(nutriments, Mapping):
313
+ nutriments = {}
314
+
315
+ energy_kj = _first_number(
316
+ nutriments.get("energy-kj_100g"),
317
+ nutriments.get("energy-kj"),
318
+ nutriments.get("energy_100g"),
319
+ nutriments.get("energy"),
320
+ )
321
+ energy_kcal = _first_number(
322
+ nutriments.get("energy-kcal_100g"),
323
+ nutriments.get("energy-kcal"),
324
+ nutriments.get("energy-kcal_value"),
325
+ nutriments.get("energy-kcal_value_computed"),
326
+ )
327
+ energy_kj_computed = _first_number(
328
+ nutriments.get("energy-kj_value_computed"),
329
+ nutriments.get("energy-kj_value-computed"),
330
+ nutriments.get("energy-kj_computed"),
331
+ )
332
+ fat = _first_number(nutriments.get("fat_100g"), nutriments.get("fat"))
333
+ saturated_fat = _first_number(nutriments.get("saturated-fat_100g"), nutriments.get("saturated-fat"))
334
+ carbohydrates = _first_number(nutriments.get("carbohydrates_100g"), nutriments.get("carbohydrates"))
335
+ sugars = _first_number(nutriments.get("sugars_100g"), nutriments.get("sugars"))
336
+ starch = _first_number(nutriments.get("starch_100g"), nutriments.get("starch"))
337
+ sodium = _first_number(nutriments.get("sodium_100g"), nutriments.get("sodium"))
338
+ if sodium is None:
339
+ salt_value = _first_number(nutriments.get("salt_100g"), nutriments.get("salt"))
340
+ if salt_value is not None:
341
+ sodium = round(float(salt_value) * 0.393, 4)
342
+ lc = record.get("lc")
343
+ lang = record.get("lang")
344
+ language_code = lc or lang
345
+ ingredients_text = str(record.get("ingredients_text") or "").strip()
346
+
347
+ allergens_tags = record.get("allergens_tags")
348
+ allergens_list = allergens_tags if isinstance(allergens_tags, list) else []
349
+ contains_statement_present = bool(record.get("allergens")) or bool(record.get("traces")) or bool(allergens_list)
350
+ allergen_evidence_present = contains_statement_present or bool(record.get("allergens_from_ingredients"))
351
+
352
+ labels_tags = record.get("labels_tags")
353
+ labels_list = labels_tags if isinstance(labels_tags, list) else []
354
+ labels_text = " ".join(str(item).lower() for item in labels_list)
355
+ fop_symbol_present = (
356
+ ("high-in-sugars" in labels_text)
357
+ or ("high-in-sodium" in labels_text)
358
+ or ("high-in-saturated-fat" in labels_text)
359
+ )
360
+
361
+ categories_tags = record.get("categories_tags")
362
+ categories_list = categories_tags if isinstance(categories_tags, list) else []
363
+ categories_text = " ".join(str(item).lower() for item in categories_list)
364
+ fop_exempt_proxy = ("en:waters" in categories_text) or ("en:unflavoured-waters" in categories_text)
365
+ product_is_prepackaged_proxy = True
366
+ fop_threshold_exceeded = _compute_fop_threshold_exceeded(sugars, saturated_fat, sodium)
367
+
368
+ return {
369
+ "product_id": product_id,
370
+ "energy_kj": energy_kj,
371
+ "energy_kj_computed": energy_kj_computed,
372
+ "energy_kcal": energy_kcal,
373
+ "fat": fat,
374
+ "saturated_fat": saturated_fat,
375
+ "carbohydrates": carbohydrates,
376
+ "sugars": sugars,
377
+ "starch": starch,
378
+ "sodium": sodium,
379
+ "ingredients_text": ingredients_text,
380
+ "ingredients_text_present": _to_int_flag(ingredients_text != ""),
381
+ "contains_statement_present": _to_int_flag(contains_statement_present),
382
+ "allergen_evidence_present": _to_int_flag(allergen_evidence_present),
383
+ "fop_threshold_exceeded": int(fop_threshold_exceeded),
384
+ "fop_symbol_present": _to_int_flag(fop_symbol_present),
385
+ "fop_exempt_proxy": _to_int_flag(fop_exempt_proxy),
386
+ "product_is_prepackaged_proxy": _to_int_flag(product_is_prepackaged_proxy),
387
+ "lc": lc,
388
+ "lang": lang,
389
+ "language_code": language_code,
390
+ }
391
+
392
+
393
+ def extract_products_from_off_jsonl(source_path: Path, max_products: int = 300) -> List[Dict[str, object]]:
394
+ """Stream OFF JSONL and extract up to ``max_products`` normalized records."""
395
+ products: List[Dict[str, object]] = []
396
+ with source_path.open("r", encoding="utf-8", errors="ignore") as handle:
397
+ for line in handle:
398
+ if len(products) >= max_products:
399
+ break
400
+ if not line.strip():
401
+ continue
402
+ try:
403
+ record = json.loads(line)
404
+ except json.JSONDecodeError:
405
+ continue
406
+ if not isinstance(record, Mapping):
407
+ continue
408
+ extracted = extract_product_from_off_record(record)
409
+ if extracted is not None:
410
+ products.append(extracted)
411
+
412
+ if not products:
413
+ raise ValueError(f"No usable products extracted from {source_path}")
414
+ return products
415
+
416
+
417
+ def write_products_jsonl(products: Iterable[Dict[str, object]], output_path: Path) -> None:
418
+ """Persist product records to JSONL."""
419
+ output_path.parent.mkdir(parents=True, exist_ok=True)
420
+ with output_path.open("w", encoding="utf-8") as handle:
421
+ for record in products:
422
+ handle.write(json.dumps(record) + "\n")
423
+
424
+
425
+ def read_products_jsonl(path: Path = SAMPLE_FILE) -> List[Dict[str, object]]:
426
+ """Read products from JSONL into a list."""
427
+ records: List[Dict[str, object]] = []
428
+ with path.open("r", encoding="utf-8") as handle:
429
+ for line in handle:
430
+ if line.strip():
431
+ records.append(json.loads(line))
432
+ return records
433
+
434
+
435
+ def create_and_load_dataset(
436
+ size: int = 300,
437
+ seed: int = 17,
438
+ output_path: Path = SAMPLE_FILE,
439
+ db_path: Path = DB_PATH,
440
+ source_jsonl: Path | None = None,
441
+ ) -> List[Dict[str, object]]:
442
+ """Build dataset records and load them into DuckDB.
443
+
444
+ Notes:
445
+ - ``seed`` is used only for synthetic generation.
446
+ - When ``source_jsonl`` is provided, records are streamed from that file and
447
+ ``seed`` has no effect.
448
+ """
449
+ if source_jsonl is not None:
450
+ products = extract_products_from_off_jsonl(Path(source_jsonl), max_products=size)
451
+ else:
452
+ config = DatasetConfig(size=size, seed=seed, output_path=output_path)
453
+ products = generate_products(config)
454
+ write_products_jsonl(products, output_path)
455
+
456
+ # Local import avoids module cycles between data and duckdb layers.
457
+ from duckdb_utils.create_tables import load_jsonl_to_duckdb, recreate_nutrition_table
458
+
459
+ recreate_nutrition_table(db_path=db_path)
460
+ load_jsonl_to_duckdb(jsonl_path=output_path, db_path=db_path)
461
+ return products
462
+
463
+
464
+ def parse_args() -> argparse.Namespace:
465
+ parser = argparse.ArgumentParser(description="Generate and load prototype dataset.")
466
+ parser.add_argument("--size", type=int, default=300, help="Number of products (100-500 recommended).")
467
+ parser.add_argument(
468
+ "--seed",
469
+ type=int,
470
+ default=17,
471
+ help="Random seed for synthetic data reproducibility (ignored when --source-jsonl is set).",
472
+ )
473
+ parser.add_argument(
474
+ "--source-jsonl",
475
+ type=Path,
476
+ default=None,
477
+ help="Path to OFF JSONL source file (if omitted, synthetic data is generated).",
478
+ )
479
+ return parser.parse_args()
480
+
481
+
482
+ def main() -> None:
483
+ args = parse_args()
484
+ products = create_and_load_dataset(size=args.size, seed=args.seed, source_jsonl=args.source_jsonl)
485
+ print(f"Generated {len(products)} records at {SAMPLE_FILE}")
486
+ if args.source_jsonl:
487
+ print(f"Source dataset: {Path(args.source_jsonl).resolve()}")
488
+ else:
489
+ print("Source dataset: synthetic generator")
490
+ print(f"Loaded dataset into {DB_PATH}")
491
+
492
+
493
+ if __name__ == "__main__":
494
+ main()
OFF_DataQuality/data/sample_products.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
OFF_DataQuality/declarative/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ """Declarative check execution helpers (dbt-core / soda-core prototypes)."""
2
+
OFF_DataQuality/declarative/check_runners.py ADDED
@@ -0,0 +1,742 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Declarative check runners for dbt-core and soda-core pilots.
2
+
3
+ These runners are intentionally lightweight:
4
+ - They always compute violating product IDs from DuckDB SQL conditions
5
+ (deterministic parity baseline).
6
+ - They optionally execute dbt/soda commands to prove declarative integration.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ import re
12
+ import shutil
13
+ import subprocess
14
+ from pathlib import Path
15
+ from typing import Dict, List, Mapping, Sequence
16
+
17
+ import duckdb
18
+
19
+ from duckdb_utils.create_tables import TABLE_NAME
20
+
21
+ PROJECT_ROOT = Path(__file__).resolve().parent.parent
22
+ RUNTIME_DIR = PROJECT_ROOT / "results" / "declarative_runtime"
23
+ OUTPUT_TAIL_CHARS = 4000
24
+
25
+
26
+ def _sql_for_rule(rule: Mapping[str, object]) -> str:
27
+ condition = str(rule["duckdb_condition"])
28
+ return f"SELECT product_id FROM {TABLE_NAME} WHERE {condition}"
29
+
30
+
31
+ def _query_rule_product_ids(rule: Mapping[str, object], db_path: Path) -> List[str]:
32
+ query = _sql_for_rule(rule)
33
+ with duckdb.connect(db_path.as_posix()) as con:
34
+ rows = con.execute(query).fetchall()
35
+ return sorted(str(row[0]) for row in rows)
36
+
37
+
38
+ def _build_per_product_tags(
39
+ rules: Sequence[Mapping[str, object]],
40
+ per_rule_ids: Dict[str, List[str]],
41
+ products: Sequence[Mapping[str, object]],
42
+ ) -> Dict[str, List[str]]:
43
+ per_product_tags: Dict[str, List[str]] = {str(product.get("product_id")): [] for product in products}
44
+ for rule in rules:
45
+ rule_name = str(rule["rule_name"])
46
+ tag = str(rule["tag"])
47
+ for product_id in per_rule_ids[rule_name]:
48
+ if product_id in per_product_tags:
49
+ per_product_tags[product_id].append(tag)
50
+ return per_product_tags
51
+
52
+
53
+ def _run_command(command: List[str], cwd: Path, env: Mapping[str, str] | None = None) -> Dict[str, object]:
54
+ try:
55
+ full_env = os.environ.copy()
56
+ if env:
57
+ full_env.update(env)
58
+ completed = subprocess.run(
59
+ command,
60
+ cwd=cwd,
61
+ env=full_env,
62
+ capture_output=True,
63
+ text=True,
64
+ encoding="utf-8",
65
+ errors="replace",
66
+ check=False,
67
+ timeout=180,
68
+ )
69
+ stdout = completed.stdout or ""
70
+ stderr = completed.stderr or ""
71
+ return {
72
+ "command": " ".join(command),
73
+ "executed": True,
74
+ "success": completed.returncode == 0,
75
+ "return_code": completed.returncode,
76
+ "stdout_tail": stdout[-OUTPUT_TAIL_CHARS:],
77
+ "stderr_tail": stderr[-OUTPUT_TAIL_CHARS:],
78
+ }
79
+ except FileNotFoundError:
80
+ return {
81
+ "command": " ".join(command),
82
+ "executed": False,
83
+ "success": False,
84
+ "return_code": None,
85
+ "stdout_tail": "",
86
+ "stderr_tail": f"Command not found: {command[0]}",
87
+ }
88
+ except subprocess.TimeoutExpired as exc:
89
+ return {
90
+ "command": " ".join(command),
91
+ "executed": True,
92
+ "success": False,
93
+ "return_code": None,
94
+ "stdout_tail": (exc.stdout or "")[-OUTPUT_TAIL_CHARS:] if exc.stdout else "",
95
+ "stderr_tail": (exc.stderr or "")[-OUTPUT_TAIL_CHARS:] if exc.stderr else "Command timed out.",
96
+ }
97
+
98
+
99
+ def _soda_cloud_credentials() -> Dict[str, str] | None:
100
+ api_key_id = os.getenv("SODA_CLOUD_API_KEY_ID", "").strip()
101
+ api_key_secret = os.getenv("SODA_CLOUD_API_KEY_SECRET", "").strip()
102
+ host = os.getenv("SODA_CLOUD_HOST", "").strip()
103
+ if not (api_key_id and api_key_secret and host):
104
+ return None
105
+ return {
106
+ "api_key_id": api_key_id,
107
+ "api_key_secret": api_key_secret,
108
+ "host": host,
109
+ }
110
+
111
+
112
+ def _extract_cloud_scan_metadata(stdout_tail: str, stderr_tail: str) -> Dict[str, str]:
113
+ text = f"{stdout_tail}\n{stderr_tail}"
114
+ scan_id = ""
115
+ scan_url = ""
116
+
117
+ scan_match = re.search(r"(?:scan[\s_-]?id)\s*[:=]\s*([a-zA-Z0-9\-]+)", text, flags=re.IGNORECASE)
118
+ if scan_match:
119
+ scan_id = scan_match.group(1).strip()
120
+
121
+ url_match = re.search(r"(https?://[^\s]+)", text)
122
+ if url_match:
123
+ scan_url = url_match.group(1).strip().rstrip(".,)")
124
+
125
+ return {
126
+ "scan_id": scan_id,
127
+ "scan_url": scan_url,
128
+ }
129
+
130
+
131
+ def _write_soda_data_source_config(config_path: Path, data_source_name: str, runtime_db_path: Path) -> None:
132
+ config_path.write_text(
133
+ "\n".join(
134
+ [
135
+ "type: duckdb",
136
+ f"name: {data_source_name}",
137
+ "connection:",
138
+ f" database: {runtime_db_path.as_posix()}",
139
+ " schema: main",
140
+ ]
141
+ )
142
+ + "\n",
143
+ encoding="utf-8",
144
+ )
145
+
146
+
147
+ def _resolve_soda_cloud_config(target_path: Path) -> tuple[Path | None, str]:
148
+ explicit_path = os.getenv("SODA_CLOUD_CONFIG_PATH", "").strip()
149
+ candidate_paths = []
150
+ if explicit_path:
151
+ candidate_paths.append(Path(explicit_path).expanduser())
152
+ candidate_paths.append(PROJECT_ROOT / "sc_config.yml")
153
+
154
+ for candidate in candidate_paths:
155
+ if candidate.is_file():
156
+ shutil.copyfile(candidate, target_path)
157
+ return target_path, str(candidate)
158
+
159
+ credentials = _soda_cloud_credentials()
160
+ if credentials is None:
161
+ return None, ""
162
+
163
+ target_path.write_text(
164
+ "\n".join(
165
+ [
166
+ "soda_cloud:",
167
+ f" host: {credentials['host']}",
168
+ f" api_key_id: {credentials['api_key_id']}",
169
+ f" api_key_secret: {credentials['api_key_secret']}",
170
+ ]
171
+ )
172
+ + "\n",
173
+ encoding="utf-8",
174
+ )
175
+ return target_path, "env"
176
+
177
+
178
+ def _prepare_dbt_project(rules: Sequence[Mapping[str, object]], db_path: Path, root_dir: Path) -> Dict[str, object]:
179
+ project_dir = root_dir / "dbt_project"
180
+ tests_dir = project_dir / "tests"
181
+ models_dir = project_dir / "models"
182
+ macros_dir = project_dir / "macros"
183
+ runtime_db_path = root_dir / "dbt_runtime.db"
184
+ tests_dir.mkdir(parents=True, exist_ok=True)
185
+ models_dir.mkdir(parents=True, exist_ok=True)
186
+ macros_dir.mkdir(parents=True, exist_ok=True)
187
+ shutil.copyfile(db_path, runtime_db_path)
188
+
189
+ (project_dir / "dbt_project.yml").write_text(
190
+ "\n".join(
191
+ [
192
+ "name: off_quality_declarative",
193
+ "version: '1.0'",
194
+ "config-version: 2",
195
+ "profile: off_quality_duckdb",
196
+ "model-paths: ['models']",
197
+ "test-paths: ['tests']",
198
+ ]
199
+ )
200
+ + "\n",
201
+ encoding="utf-8",
202
+ )
203
+
204
+ (project_dir / "profiles.yml").write_text(
205
+ "\n".join(
206
+ [
207
+ "off_quality_duckdb:",
208
+ " target: dev",
209
+ " outputs:",
210
+ " dev:",
211
+ " type: duckdb",
212
+ f" path: '{runtime_db_path.as_posix()}'",
213
+ " schema: main",
214
+ " threads: 1",
215
+ ]
216
+ )
217
+ + "\n",
218
+ encoding="utf-8",
219
+ )
220
+
221
+ (models_dir / "sources.yml").write_text(
222
+ "\n".join(
223
+ [
224
+ "version: 2",
225
+ "sources:",
226
+ " - name: off_source",
227
+ " schema: main",
228
+ " tables:",
229
+ " - name: nutrition_table",
230
+ ]
231
+ )
232
+ + "\n",
233
+ encoding="utf-8",
234
+ )
235
+
236
+ test_sql_by_rule: Dict[str, str] = {}
237
+ for rule in rules:
238
+ rule_name = str(rule["rule_name"])
239
+ condition = str(rule["duckdb_condition"])
240
+ sql = (
241
+ "SELECT product_id\n"
242
+ "FROM {{ source('off_source', 'nutrition_table') }}\n"
243
+ f"WHERE {condition}"
244
+ )
245
+ test_sql_by_rule[rule_name] = sql
246
+ (tests_dir / f"{rule_name}.sql").write_text(sql + "\n", encoding="utf-8")
247
+
248
+ # dbt test command uses multiprocessing in this environment and fails with WinError 5.
249
+ # Use run-operation to execute each rule query in real dbt runtime instead.
250
+ (macros_dir / "count_violations.sql").write_text(
251
+ "\n".join(
252
+ [
253
+ "{% macro count_violations(condition_sql) %}",
254
+ " {% set q %}",
255
+ " select count(*) as violation_count",
256
+ " from {{ source('off_source', 'nutrition_table') }}",
257
+ " where {{ condition_sql }}",
258
+ " {% endset %}",
259
+ " {% set t = run_query(q) %}",
260
+ " {% if execute %}",
261
+ " {% set c = t.columns[0].values()[0] %}",
262
+ " {% do log('VIOLATION_COUNT=' ~ c, info=True) %}",
263
+ " {% endif %}",
264
+ "{% endmacro %}",
265
+ ]
266
+ )
267
+ + "\n",
268
+ encoding="utf-8",
269
+ )
270
+
271
+ dbt_cmd = shutil.which("dbt")
272
+ if not dbt_cmd:
273
+ return {
274
+ "run": {
275
+ "command": "dbt test --project-dir ... --profiles-dir ...",
276
+ "executed": False,
277
+ "success": False,
278
+ "return_code": None,
279
+ "stdout_tail": "",
280
+ "stderr_tail": "dbt CLI not found. Install dbt-duckdb.",
281
+ },
282
+ "test_sql_by_rule": test_sql_by_rule,
283
+ }
284
+
285
+ debug_info = _run_command(
286
+ [dbt_cmd, "debug", "--project-dir", str(project_dir), "--profiles-dir", str(project_dir)],
287
+ cwd=project_dir,
288
+ )
289
+ per_rule_runs: Dict[str, Dict[str, object]] = {}
290
+ for rule in rules:
291
+ rule_name = str(rule["rule_name"])
292
+ condition = str(rule["duckdb_condition"])
293
+ args_yaml = f"{{condition_sql: {condition!r}}}"
294
+ per_rule_runs[rule_name] = _run_command(
295
+ [
296
+ dbt_cmd,
297
+ "run-operation",
298
+ "count_violations",
299
+ "--project-dir",
300
+ str(project_dir),
301
+ "--profiles-dir",
302
+ str(project_dir),
303
+ "--args",
304
+ args_yaml,
305
+ ],
306
+ cwd=project_dir,
307
+ )
308
+
309
+ all_executed = bool(debug_info.get("executed")) and all(bool(run.get("executed")) for run in per_rule_runs.values())
310
+ all_success_codes = (
311
+ debug_info.get("return_code") == 0 and all(run.get("return_code") == 0 for run in per_rule_runs.values())
312
+ )
313
+ failing_rules = [rule_name for rule_name, run in per_rule_runs.items() if run.get("return_code") != 0]
314
+ summary_stdout, summary_stderr = _summarize_soda_runs(per_rule_runs)
315
+
316
+ run_info = {
317
+ "command": (
318
+ f"dbt debug + dbt run-operation count_violations "
319
+ f"(per-rule x{len(per_rule_runs)}) --project-dir {project_dir} --profiles-dir {project_dir}"
320
+ ),
321
+ "executed": all_executed,
322
+ "success": all_success_codes,
323
+ "return_code": 0 if all_success_codes else 2,
324
+ "stdout_tail": summary_stdout,
325
+ "stderr_tail": summary_stderr,
326
+ "real_execution": all_success_codes,
327
+ "failed_rules": failing_rules,
328
+ }
329
+ return {"run": run_info, "test_sql_by_rule": test_sql_by_rule}
330
+
331
+
332
+ def _prepare_soda_cloud_scan(
333
+ rules: Sequence[Mapping[str, object]],
334
+ db_path: Path,
335
+ root_dir: Path,
336
+ ) -> Dict[str, object]:
337
+ soda_dir = root_dir / "soda_cloud"
338
+ soda_dir.mkdir(parents=True, exist_ok=True)
339
+ runtime_db_path = root_dir / "soda_cloud_runtime.db"
340
+ shutil.copyfile(db_path, runtime_db_path)
341
+
342
+ data_source_name = "off_quality"
343
+ config_path = soda_dir / "data_source.yml"
344
+ soda_cloud_config_path = soda_dir / "soda_cloud.yml"
345
+ contracts_dir = soda_dir / "contracts"
346
+ contracts_dir.mkdir(parents=True, exist_ok=True)
347
+
348
+ check_yaml_by_rule: Dict[str, str] = {}
349
+ soda_cloud_config, cloud_config_source = _resolve_soda_cloud_config(soda_cloud_config_path)
350
+ if soda_cloud_config is None:
351
+ return {
352
+ "run": {
353
+ "command": "soda contract verify -c <contract.yml> -ds data_source.yml -sc soda_cloud.yml -p",
354
+ "executed": False,
355
+ "success": False,
356
+ "return_code": None,
357
+ "stdout_tail": "",
358
+ "stderr_tail": (
359
+ "Soda Cloud config missing. Provide sc_config.yml, set SODA_CLOUD_CONFIG_PATH, "
360
+ "or set SODA_CLOUD_API_KEY_ID, SODA_CLOUD_API_KEY_SECRET, SODA_CLOUD_HOST."
361
+ ),
362
+ "mode": "cloud",
363
+ "cloud_connected": False,
364
+ "cloud_scan_id": "",
365
+ "cloud_scan_url": "",
366
+ "real_execution": False,
367
+ "failed_rules": [str(rule["rule_name"]) for rule in rules],
368
+ },
369
+ "check_yaml_by_rule": check_yaml_by_rule,
370
+ }
371
+
372
+ _write_soda_data_source_config(config_path=config_path, data_source_name=data_source_name, runtime_db_path=runtime_db_path)
373
+
374
+ soda_cmd = shutil.which("soda")
375
+ if not soda_cmd:
376
+ return {
377
+ "run": {
378
+ "command": (
379
+ f"soda contract verify -c <contract.yml> -ds {config_path} "
380
+ f"-sc {soda_cloud_config_path} -p"
381
+ ),
382
+ "executed": False,
383
+ "success": False,
384
+ "return_code": None,
385
+ "stdout_tail": "",
386
+ "stderr_tail": "soda CLI not found. Install soda-duckdb.",
387
+ "mode": "cloud",
388
+ "cloud_connected": False,
389
+ "cloud_scan_id": "",
390
+ "cloud_scan_url": "",
391
+ "real_execution": False,
392
+ "failed_rules": [str(rule["rule_name"]) for rule in rules],
393
+ },
394
+ "check_yaml_by_rule": check_yaml_by_rule,
395
+ }
396
+
397
+ with duckdb.connect(db_path.as_posix()) as con:
398
+ columns = [str(row[1]) for row in con.execute(f"PRAGMA table_info('{TABLE_NAME}')").fetchall()]
399
+
400
+ soda_env = {
401
+ "OTEL_SDK_DISABLED": "true",
402
+ "PYTHONUTF8": "1",
403
+ "PYTHONIOENCODING": "utf-8",
404
+ }
405
+ per_rule_runs: Dict[str, Dict[str, object]] = {}
406
+ first_cloud_meta = {"scan_id": "", "scan_url": ""}
407
+ for rule in rules:
408
+ rule_name = str(rule["rule_name"])
409
+ condition = str(rule["duckdb_condition"])
410
+ check_block = (
411
+ f" - failed_rows:\n"
412
+ f" name: {rule_name}\n"
413
+ f" expression: {condition}\n"
414
+ )
415
+ check_yaml_by_rule[rule_name] = check_block.rstrip("\n")
416
+
417
+ contract_lines: List[str] = [
418
+ f"dataset: {data_source_name}/main/{TABLE_NAME}",
419
+ "columns:",
420
+ ]
421
+ for column in columns:
422
+ contract_lines.append(f" - name: {column}")
423
+ contract_lines.extend(["checks:", check_block.rstrip("\n")])
424
+
425
+ contract_path = contracts_dir / f"{rule_name}.yml"
426
+ contract_path.write_text("\n".join(contract_lines) + "\n", encoding="utf-8")
427
+
428
+ run = _run_command(
429
+ [
430
+ soda_cmd,
431
+ "contract",
432
+ "verify",
433
+ "-c",
434
+ str(contract_path),
435
+ "-ds",
436
+ str(config_path),
437
+ "-sc",
438
+ str(soda_cloud_config),
439
+ "-p",
440
+ "-v",
441
+ ],
442
+ cwd=soda_dir,
443
+ env=soda_env,
444
+ )
445
+ per_rule_runs[rule_name] = run
446
+ cloud_meta = _extract_cloud_scan_metadata(
447
+ stdout_tail=str(run.get("stdout_tail", "")),
448
+ stderr_tail=str(run.get("stderr_tail", "")),
449
+ )
450
+ if not first_cloud_meta["scan_id"] and cloud_meta["scan_id"]:
451
+ first_cloud_meta["scan_id"] = cloud_meta["scan_id"]
452
+ if not first_cloud_meta["scan_url"] and cloud_meta["scan_url"]:
453
+ first_cloud_meta["scan_url"] = cloud_meta["scan_url"]
454
+
455
+ all_executed = all(bool(run.get("executed")) for run in per_rule_runs.values())
456
+ all_success_codes = all(run.get("return_code") in {0, 1} for run in per_rule_runs.values())
457
+ all_real = all(_soda_run_is_real(run) for run in per_rule_runs.values())
458
+ all_published = all(_soda_cloud_publish_succeeded(run) for run in per_rule_runs.values())
459
+ failing_rules = [
460
+ rule_name
461
+ for rule_name, run in per_rule_runs.items()
462
+ if not (_soda_run_is_real(run) and _soda_cloud_publish_succeeded(run))
463
+ ]
464
+
465
+ summary_stdout, summary_stderr = _summarize_soda_runs(per_rule_runs)
466
+
467
+ run_info = {
468
+ "command": (
469
+ f"soda contract verify (per-rule x{len(per_rule_runs)}) -ds {config_path} "
470
+ f"-sc {soda_cloud_config} -p"
471
+ ),
472
+ "executed": all_executed,
473
+ "success": all_success_codes,
474
+ "return_code": 0 if all_success_codes else 3,
475
+ "stdout_tail": summary_stdout,
476
+ "stderr_tail": summary_stderr,
477
+ "mode": "cloud",
478
+ "real_execution": all_real,
479
+ "cloud_connected": all_published,
480
+ "cloud_scan_id": first_cloud_meta["scan_id"],
481
+ "cloud_scan_url": first_cloud_meta["scan_url"],
482
+ "cloud_config_source": cloud_config_source,
483
+ "failed_rules": failing_rules,
484
+ }
485
+ return {"run": run_info, "check_yaml_by_rule": check_yaml_by_rule}
486
+
487
+
488
+ def _prepare_soda_contract(rules: Sequence[Mapping[str, object]], db_path: Path, root_dir: Path) -> Dict[str, object]:
489
+ soda_dir = root_dir / "soda"
490
+ soda_dir.mkdir(parents=True, exist_ok=True)
491
+ data_source_name = "off_quality"
492
+ runtime_db_path = root_dir / "soda_runtime.db"
493
+ config_path = soda_dir / "data_source.yml"
494
+ contracts_dir = soda_dir / "contracts"
495
+ contracts_dir.mkdir(parents=True, exist_ok=True)
496
+ shutil.copyfile(db_path, runtime_db_path)
497
+
498
+ _write_soda_data_source_config(config_path=config_path, data_source_name=data_source_name, runtime_db_path=runtime_db_path)
499
+
500
+ with duckdb.connect(db_path.as_posix()) as con:
501
+ columns = [str(row[1]) for row in con.execute(f"PRAGMA table_info('{TABLE_NAME}')").fetchall()]
502
+
503
+ check_yaml_by_rule: Dict[str, str] = {}
504
+ soda_cmd = shutil.which("soda")
505
+ if not soda_cmd:
506
+ return {
507
+ "run": {
508
+ "command": f"soda contract verify -c <contract.yml> -ds {config_path}",
509
+ "executed": False,
510
+ "success": False,
511
+ "return_code": None,
512
+ "stdout_tail": "",
513
+ "stderr_tail": "soda CLI not found. Install soda-duckdb.",
514
+ },
515
+ "check_yaml_by_rule": check_yaml_by_rule,
516
+ }
517
+
518
+ soda_env = {
519
+ # Avoid blocked telemetry calls and Windows cp1252 console issues with emoji output.
520
+ "OTEL_SDK_DISABLED": "true",
521
+ "PYTHONUTF8": "1",
522
+ "PYTHONIOENCODING": "utf-8",
523
+ }
524
+ per_rule_runs: Dict[str, Dict[str, object]] = {}
525
+ for rule in rules:
526
+ rule_name = str(rule["rule_name"])
527
+ condition = str(rule["duckdb_condition"])
528
+ check_block = (
529
+ f" - failed_rows:\n"
530
+ f" name: {rule_name}\n"
531
+ f" expression: {condition}\n"
532
+ )
533
+ check_yaml_by_rule[rule_name] = check_block.rstrip("\n")
534
+
535
+ contract_lines: List[str] = [
536
+ f"dataset: {data_source_name}/main/{TABLE_NAME}",
537
+ "columns:",
538
+ ]
539
+ for column in columns:
540
+ contract_lines.append(f" - name: {column}")
541
+ contract_lines.extend(["checks:", check_block.rstrip("\n")])
542
+
543
+ contract_path = contracts_dir / f"{rule_name}.yml"
544
+ contract_path.write_text("\n".join(contract_lines) + "\n", encoding="utf-8")
545
+
546
+ per_rule_runs[rule_name] = _run_command(
547
+ [soda_cmd, "contract", "verify", "-c", str(contract_path), "-ds", str(config_path)],
548
+ cwd=soda_dir,
549
+ env=soda_env,
550
+ )
551
+
552
+ all_executed = all(bool(run.get("executed")) for run in per_rule_runs.values())
553
+ all_success_codes = all(run.get("return_code") in {0, 1} for run in per_rule_runs.values())
554
+ all_real = all(_soda_run_is_real(run) for run in per_rule_runs.values())
555
+ failing_rules = [rule_name for rule_name, run in per_rule_runs.items() if not _soda_run_is_real(run)]
556
+
557
+ summary_stdout = "\n".join(
558
+ f"{rule_name}: rc={run.get('return_code')}, success={run.get('success')}"
559
+ for rule_name, run in per_rule_runs.items()
560
+ )[-1200:]
561
+ summary_stderr = "\n".join(
562
+ f"{rule_name}: {str(run.get('stderr_tail', '')).strip()}"
563
+ for rule_name, run in per_rule_runs.items()
564
+ if str(run.get("stderr_tail", "")).strip()
565
+ )[-1200:]
566
+
567
+ run_info = {
568
+ "command": f"soda contract verify (per-rule x{len(per_rule_runs)}) -ds {config_path}",
569
+ "executed": all_executed,
570
+ "success": all_success_codes,
571
+ "return_code": 0 if all_success_codes else 3,
572
+ "stdout_tail": summary_stdout,
573
+ "stderr_tail": summary_stderr,
574
+ "mode": "local",
575
+ "real_execution": all_real,
576
+ "cloud_connected": False,
577
+ "cloud_scan_id": "",
578
+ "cloud_scan_url": "",
579
+ "failed_rules": failing_rules,
580
+ }
581
+ return {"run": run_info, "check_yaml_by_rule": check_yaml_by_rule}
582
+
583
+
584
+ def _dbt_run_is_real(run_info: Mapping[str, object]) -> bool:
585
+ if "real_execution" in run_info:
586
+ return bool(run_info.get("real_execution"))
587
+ if not bool(run_info.get("executed")):
588
+ return False
589
+ return run_info.get("return_code") in {0, 1}
590
+
591
+
592
+ def _soda_run_is_real(run_info: Mapping[str, object]) -> bool:
593
+ if not bool(run_info.get("executed")):
594
+ return False
595
+ output = f"{run_info.get('stdout_tail', '')}\n{run_info.get('stderr_tail', '')}".lower()
596
+ if "soda v3 commands are not supported" in output:
597
+ return False
598
+ if "contract results for" in output:
599
+ return True
600
+ if run_info.get("return_code") in {0, 1}:
601
+ return True
602
+ return bool(run_info.get("success"))
603
+
604
+
605
+ def _soda_cloud_publish_succeeded(run_info: Mapping[str, object]) -> bool:
606
+ if not bool(run_info.get("executed")):
607
+ return False
608
+ output = f"{run_info.get('stdout_tail', '')}\n{run_info.get('stderr_tail', '')}".lower()
609
+ if "results sent to soda cloud" in output:
610
+ return True
611
+ if "to view the dataset on soda cloud" in output:
612
+ return True
613
+ if "cloud.soda.io/o/" in output:
614
+ return True
615
+ return False
616
+
617
+
618
+ def _summarize_soda_runs(per_rule_runs: Mapping[str, Mapping[str, object]]) -> tuple[str, str]:
619
+ summary_stdout = "\n".join(
620
+ f"{rule_name}: rc={run.get('return_code')}, success={run.get('success')}"
621
+ for rule_name, run in per_rule_runs.items()
622
+ )
623
+ summary_stderr = "\n".join(
624
+ f"{rule_name}: {str(run.get('stderr_tail', '')).strip()}"
625
+ for rule_name, run in per_rule_runs.items()
626
+ if str(run.get("stderr_tail", "")).strip()
627
+ )
628
+
629
+ for rule_name, run in per_rule_runs.items():
630
+ if not _soda_run_is_real(run):
631
+ failing_stdout = str(run.get("stdout_tail", "")).strip()
632
+ failing_stderr = str(run.get("stderr_tail", "")).strip()
633
+ if failing_stdout:
634
+ summary_stdout = f"{summary_stdout}\n\nFirst failing rule: {rule_name}\n{failing_stdout}"
635
+ if failing_stderr:
636
+ summary_stderr = f"{summary_stderr}\n\nFirst failing rule: {rule_name}\n{failing_stderr}"
637
+ break
638
+
639
+ return summary_stdout[-1200:], summary_stderr[-1200:]
640
+
641
+
642
+ def run_declarative_checks(
643
+ rules: Sequence[Mapping[str, object]],
644
+ products: Sequence[Mapping[str, object]],
645
+ db_path: Path,
646
+ engine: str,
647
+ soda_mode: str = "local",
648
+ ) -> Dict[str, object]:
649
+ """Run declarative checks and return parity-compatible output payload."""
650
+ if engine not in {"dbt", "soda"}:
651
+ raise ValueError(f"Unsupported declarative engine: {engine}")
652
+ if soda_mode not in {"local", "cloud"}:
653
+ raise ValueError("soda_mode must be one of: local, cloud")
654
+
655
+ runtime_root = RUNTIME_DIR / engine
656
+ runtime_root.mkdir(parents=True, exist_ok=True)
657
+
658
+ per_rule_ids: Dict[str, List[str]] = {}
659
+ for rule in rules:
660
+ per_rule_ids[str(rule["rule_name"])] = _query_rule_product_ids(rule, db_path=db_path)
661
+
662
+ per_product_tags = _build_per_product_tags(rules=rules, per_rule_ids=per_rule_ids, products=products)
663
+
664
+ if engine == "dbt":
665
+ artifact = _prepare_dbt_project(rules=rules, db_path=db_path, root_dir=runtime_root)
666
+ run_info = artifact["run"]
667
+ snippets = artifact["test_sql_by_rule"]
668
+ is_real = _dbt_run_is_real(run_info)
669
+ provider = "dbt_core" if is_real else "dbt_core_sql_fallback"
670
+ confidence = 0.99 if is_real else 0.92
671
+ note_prefix = (
672
+ "dbt tests executed through dbt-core."
673
+ if is_real
674
+ else "dbt execution unavailable/failed; used SQL-equivalent declarative parity."
675
+ )
676
+ else:
677
+ if soda_mode == "cloud":
678
+ cloud_artifact = _prepare_soda_cloud_scan(rules=rules, db_path=db_path, root_dir=runtime_root)
679
+ cloud_run = cloud_artifact["run"]
680
+ snippets = cloud_artifact["check_yaml_by_rule"]
681
+ cloud_ok = bool(cloud_run.get("cloud_connected")) and bool(cloud_run.get("real_execution"))
682
+ if cloud_ok:
683
+ run_info = cloud_run
684
+ is_real = True
685
+ provider = "soda_cloud"
686
+ confidence = 0.99
687
+ note_prefix = "Soda Cloud scan executed successfully."
688
+ else:
689
+ run_info = dict(cloud_run)
690
+ run_info.update(
691
+ {
692
+ "mode": "cloud_sql_fallback",
693
+ "real_execution": False,
694
+ "cloud_connected": bool(cloud_run.get("cloud_connected", False)),
695
+ "cloud_scan_id": str(cloud_run.get("cloud_scan_id", "")),
696
+ "cloud_scan_url": str(cloud_run.get("cloud_scan_url", "")),
697
+ "failed_rules": [str(rule["rule_name"]) for rule in rules],
698
+ }
699
+ )
700
+ is_real = False
701
+ provider = "soda_core_sql_fallback"
702
+ confidence = 0.92
703
+ note_prefix = "Soda Cloud unavailable/failed; used SQL-equivalent declarative parity (fast fallback)."
704
+ else:
705
+ artifact = _prepare_soda_contract(rules=rules, db_path=db_path, root_dir=runtime_root)
706
+ run_info = artifact["run"]
707
+ snippets = artifact["check_yaml_by_rule"]
708
+ is_real = bool(run_info.get("real_execution")) or _soda_run_is_real(run_info)
709
+ provider = "soda_core" if is_real else "soda_core_sql_fallback"
710
+ confidence = 0.99 if is_real else 0.92
711
+ note_prefix = (
712
+ "Soda contract verification executed through soda-core."
713
+ if is_real
714
+ else "Soda execution unavailable/failed; used SQL-equivalent declarative parity."
715
+ )
716
+
717
+ conversion_metadata: Dict[str, Dict[str, object]] = {}
718
+ for rule in rules:
719
+ rule_name = str(rule["rule_name"])
720
+ conversion_metadata[rule_name] = {
721
+ "function_name": f"{engine}_{rule_name}",
722
+ "python_code": snippets.get(rule_name, _sql_for_rule(rule)),
723
+ "llm_confidence": confidence,
724
+ "conversion_notes": (
725
+ f"{note_prefix} "
726
+ f"Command: {run_info['command']} | "
727
+ f"Success: {run_info['success']} | "
728
+ f"Return code: {run_info['return_code']}"
729
+ ),
730
+ "provider": provider,
731
+ "execution_mode": str(run_info.get("mode", "local")),
732
+ "cloud_connected": bool(run_info.get("cloud_connected", False)),
733
+ "cloud_scan_id": str(run_info.get("cloud_scan_id", "")),
734
+ "cloud_scan_url": str(run_info.get("cloud_scan_url", "")),
735
+ }
736
+
737
+ return {
738
+ "per_product": per_product_tags,
739
+ "per_rule": per_rule_ids,
740
+ "conversion_metadata": conversion_metadata,
741
+ "engine_run": run_info,
742
+ }
OFF_DataQuality/duckdb_utils/__init__.py ADDED
File without changes
OFF_DataQuality/duckdb_utils/create_tables.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """DuckDB helpers for the migration prototype."""
2
+ from __future__ import annotations
3
+
4
+ from pathlib import Path
5
+ from typing import Dict, List
6
+
7
+ import duckdb
8
+
9
+ DB_PATH = Path(__file__).resolve().parent.parent / "off_quality.db"
10
+ TABLE_NAME = "nutrition_table"
11
+
12
+ SCHEMA_SQL = f"""
13
+ CREATE TABLE IF NOT EXISTS {TABLE_NAME} (
14
+ product_id TEXT,
15
+ energy_kj DOUBLE,
16
+ energy_kj_computed DOUBLE,
17
+ energy_kcal DOUBLE,
18
+ fat DOUBLE,
19
+ saturated_fat DOUBLE,
20
+ carbohydrates DOUBLE,
21
+ sugars DOUBLE,
22
+ starch DOUBLE,
23
+ sodium DOUBLE,
24
+ ingredients_text TEXT,
25
+ ingredients_text_present INTEGER,
26
+ contains_statement_present INTEGER,
27
+ allergen_evidence_present INTEGER,
28
+ fop_threshold_exceeded INTEGER,
29
+ fop_symbol_present INTEGER,
30
+ fop_exempt_proxy INTEGER,
31
+ product_is_prepackaged_proxy INTEGER,
32
+ lc TEXT,
33
+ lang TEXT,
34
+ language_code TEXT
35
+ )
36
+ """
37
+
38
+
39
+ def connect(db_path: Path = DB_PATH) -> duckdb.DuckDBPyConnection:
40
+ return duckdb.connect(db_path.as_posix())
41
+
42
+
43
+ def recreate_nutrition_table(db_path: Path = DB_PATH) -> None:
44
+ """Drop and recreate the main table for deterministic runs."""
45
+ with connect(db_path) as con:
46
+ con.execute(f"DROP TABLE IF EXISTS {TABLE_NAME}")
47
+ con.execute(SCHEMA_SQL)
48
+
49
+
50
+ def load_jsonl_to_duckdb(jsonl_path: Path, db_path: Path = DB_PATH) -> None:
51
+ """Load JSONL records into DuckDB."""
52
+ with connect(db_path) as con:
53
+ con.execute(
54
+ f"""
55
+ INSERT INTO {TABLE_NAME}
56
+ SELECT
57
+ product_id,
58
+ energy_kj,
59
+ energy_kj_computed,
60
+ energy_kcal,
61
+ fat,
62
+ saturated_fat,
63
+ carbohydrates,
64
+ sugars,
65
+ starch,
66
+ sodium,
67
+ ingredients_text,
68
+ ingredients_text_present,
69
+ contains_statement_present,
70
+ allergen_evidence_present,
71
+ fop_threshold_exceeded,
72
+ fop_symbol_present,
73
+ fop_exempt_proxy,
74
+ product_is_prepackaged_proxy,
75
+ lc,
76
+ lang,
77
+ language_code
78
+ FROM read_json_auto(?)
79
+ """,
80
+ [jsonl_path.as_posix()],
81
+ )
82
+
83
+
84
+ def fetch_products(db_path: Path = DB_PATH) -> List[Dict[str, object]]:
85
+ """Read all products from DuckDB as dictionaries."""
86
+ with connect(db_path) as con:
87
+ rows = con.execute(f"SELECT * FROM {TABLE_NAME}").fetchdf()
88
+ return rows.to_dict("records")
89
+
90
+
91
+ def count_rows(db_path: Path = DB_PATH) -> int:
92
+ with connect(db_path) as con:
93
+ value = con.execute(f"SELECT COUNT(*) FROM {TABLE_NAME}").fetchone()
94
+ return int(value[0] if value else 0)
95
+
96
+
97
+ def count_violations(condition_sql: str, db_path: Path = DB_PATH) -> int:
98
+ """Count records matching a rule condition."""
99
+ query = f"SELECT COUNT(*) FROM {TABLE_NAME} WHERE {condition_sql}"
100
+ with connect(db_path) as con:
101
+ value = con.execute(query).fetchone()
102
+ return int(value[0] if value else 0)
103
+
104
+
105
+ def sample_violations(condition_sql: str, limit: int = 5, db_path: Path = DB_PATH) -> List[Dict[str, object]]:
106
+ """Return sample violating records for dashboard drilldown."""
107
+ query = f"""
108
+ SELECT *
109
+ FROM {TABLE_NAME}
110
+ WHERE {condition_sql}
111
+ ORDER BY product_id
112
+ LIMIT {int(limit)}
113
+ """
114
+ with connect(db_path) as con:
115
+ rows = con.execute(query).fetchdf()
116
+ return rows.to_dict("records")
OFF_DataQuality/extractor/__init__.py ADDED
File without changes
OFF_DataQuality/extractor/perl_logic_extractor.py ADDED
@@ -0,0 +1,316 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Perl logic extractor for converting legacy checks into structured rules."""
2
+ from __future__ import annotations
3
+
4
+ import hashlib
5
+ import json
6
+ import re
7
+ from typing import Dict, Iterable, List, Mapping, Sequence
8
+
9
+ RULE_NAME_RE = re.compile(r"#\s*RULE_NAME:\s*(?P<value>[a-zA-Z0-9_]+)")
10
+ SEVERITY_RE = re.compile(r"#\s*SEVERITY:\s*(?P<value>[a-zA-Z0-9_]+)")
11
+ COMPLEXITY_RE = re.compile(r"#\s*COMPLEXITY:\s*(?P<value>[a-zA-Z0-9_]+)")
12
+ DECLARATIVE_RE = re.compile(r"#\s*DECLARATIVE_FRIENDLY:\s*(?P<value>[a-zA-Z0-9_]+)")
13
+ TAG_RE = re.compile(r'"(?P<tag>[a-z0-9\-]+)"\s*;')
14
+
15
+ VAR_COMPARE_RE = re.compile(
16
+ r"if\s*\(\s*\$(?P<left>[a-zA-Z_]\w*)\s*(?P<op>>=|<=|>|<|==|!=)\s*\$(?P<right>[a-zA-Z_]\w*)\s*\)",
17
+ re.DOTALL,
18
+ )
19
+ VALUE_COMPARE_RE = re.compile(
20
+ r"if\s*\(\s*\$(?P<left>[a-zA-Z_]\w*)\s*(?P<op>>=|<=|>|<|==|!=)\s*(?P<right>\d+(?:\.\d+)?)\s*\)",
21
+ re.DOTALL,
22
+ )
23
+ MISSING_FIELD_RE = re.compile(
24
+ r'if\s*\(\s*!defined\s+\$(?P<field>[a-zA-Z_]\w*)\s*\|\|\s*\$(?P=field)\s+eq\s+""\s*\)',
25
+ re.DOTALL,
26
+ )
27
+ SCALED_FIELD_COMPARE_RE = re.compile(
28
+ r"if\s*\(\s*\$(?P<left>[a-zA-Z_]\w*)\s*(?P<op>>=|<=|>|<|==|!=)\s*\(\s*\$(?P<right>[a-zA-Z_]\w*)\s*\*\s*(?P<factor>\d+(?:\.\d+)?)\s*\)\s*\)",
29
+ re.DOTALL,
30
+ )
31
+ AFFINE_FIELD_COMPARE_RE = re.compile(
32
+ r"if\s*\(\s*\$(?P<left>[a-zA-Z_]\w*)\s*(?P<op>>=|<=|>|<|==|!=)\s*\(\s*(?P<factor>\d+(?:\.\d+)?)\s*\*\s*\$(?P<right>[a-zA-Z_]\w*)\s*(?P<sign>[+-])\s*(?P<offset>\d+(?:\.\d+)?)\s*\)\s*\)",
33
+ re.DOTALL,
34
+ )
35
+ SUM_FIELDS_COMPARE_RE = re.compile(
36
+ r"if\s*\(\s*\(\s*\$(?P<left_a>[a-zA-Z_]\w*)\s*\+\s*\$(?P<left_b>[a-zA-Z_]\w*)\s*\)\s*(?P<op>>=|<=|>|<|==|!=)\s*\(\s*\$(?P<right>[a-zA-Z_]\w*)\s*(?P<sign>[+-])\s*(?P<offset>\d+(?:\.\d+)?)\s*\)\s*\)",
37
+ re.DOTALL,
38
+ )
39
+ IF_CONDITION_RE = re.compile(r"if\s*\(\s*(?P<condition>.*?)\s*\)\s*\{", re.DOTALL)
40
+ THRESHOLD_CLAUSE_RE = re.compile(
41
+ r"^\s*\(?\s*\$(?P<left>[a-zA-Z_]\w*)\s*(?P<op>>=|<=|>|<|==|!=)\s*(?P<right>\d+(?:\.\d+)?)\s*\)?\s*$"
42
+ )
43
+
44
+
45
+ def _extract_named_value(pattern: re.Pattern[str], text: str, default: str) -> str:
46
+ match = pattern.search(text)
47
+ if not match:
48
+ return default
49
+ return match.group("value").strip()
50
+
51
+
52
+ def _extract_tag(perl_logic: str) -> str:
53
+ match = TAG_RE.search(perl_logic)
54
+ if not match:
55
+ raise ValueError(f"Unable to extract tag from Perl logic:\n{perl_logic}")
56
+ return match.group("tag")
57
+
58
+
59
+ def _default_rule_name(tag: str) -> str:
60
+ return tag.replace("-", "_")
61
+
62
+
63
+ def _parse_declarative_flag(value: str) -> bool:
64
+ return value.strip().lower() in {"yes", "true", "1", "y"}
65
+
66
+
67
+ def _default_complexity(condition_type: str) -> str:
68
+ if condition_type in {"field_comparison", "field_threshold", "missing_field"}:
69
+ return "simple"
70
+ if condition_type == "compound_threshold_and":
71
+ return "medium"
72
+ if condition_type == "sum_fields_comparison":
73
+ return "medium"
74
+ if condition_type == "affine_field_comparison":
75
+ return "intricate"
76
+ return "intricate"
77
+
78
+
79
+ def _build_rule_ir(rule: Mapping[str, object]) -> Dict[str, object]:
80
+ condition_type = str(rule.get("condition_type", "unknown"))
81
+ ir: Dict[str, object] = {
82
+ "version": "1.0",
83
+ "rule_name": rule.get("rule_name"),
84
+ "condition_type": condition_type,
85
+ "severity": rule.get("severity"),
86
+ "tag": rule.get("tag"),
87
+ }
88
+ if condition_type in {"field_comparison", "field_threshold", "missing_field", "scaled_field_comparison", "affine_field_comparison"}:
89
+ ir["left_operand"] = rule.get("left_operand")
90
+ if condition_type in {"field_comparison", "field_threshold", "scaled_field_comparison", "affine_field_comparison", "sum_fields_comparison"}:
91
+ ir["operator"] = rule.get("operator")
92
+ if condition_type in {"field_comparison", "field_threshold", "scaled_field_comparison", "affine_field_comparison", "sum_fields_comparison"}:
93
+ ir["right_operand"] = rule.get("right_operand")
94
+ if condition_type == "sum_fields_comparison":
95
+ ir["left_operands"] = rule.get("left_operands")
96
+ ir["right_offset"] = rule.get("right_offset")
97
+ if condition_type == "scaled_field_comparison":
98
+ ir["scale_factor"] = rule.get("scale_factor")
99
+ if condition_type == "affine_field_comparison":
100
+ ir["scale_factor"] = rule.get("scale_factor")
101
+ ir["offset"] = rule.get("offset")
102
+ if condition_type == "compound_threshold_and":
103
+ ir["clauses"] = rule.get("clauses")
104
+ return ir
105
+
106
+
107
+ def _attach_rule_ir(rule: Dict[str, object]) -> Dict[str, object]:
108
+ ir = _build_rule_ir(rule)
109
+ ir_json = json.dumps(ir, sort_keys=True, default=str)
110
+ rule["rule_ir"] = ir
111
+ rule["rule_ir_hash"] = hashlib.sha1(ir_json.encode("utf-8")).hexdigest()[:12]
112
+ return rule
113
+
114
+
115
+ def extract_rule(perl_logic: str) -> Dict[str, object]:
116
+ """Extract one structured rule from a Perl snippet."""
117
+ perl_logic = perl_logic.lstrip("\ufeff").strip()
118
+ tag = _extract_tag(perl_logic)
119
+ rule_name = _extract_named_value(RULE_NAME_RE, perl_logic, _default_rule_name(tag))
120
+ severity = _extract_named_value(SEVERITY_RE, perl_logic, "error")
121
+ complexity_meta = _extract_named_value(COMPLEXITY_RE, perl_logic, "")
122
+ declarative_meta = _extract_named_value(DECLARATIVE_RE, perl_logic, "")
123
+ declarative_friendly = _parse_declarative_flag(declarative_meta) if declarative_meta else None
124
+
125
+ missing_match = MISSING_FIELD_RE.search(perl_logic)
126
+ if missing_match:
127
+ field = missing_match.group("field")
128
+ return {
129
+ "rule_name": rule_name,
130
+ "condition": f"missing({field})",
131
+ "duckdb_condition": f"{field} IS NULL OR TRIM({field}) = ''",
132
+ "condition_type": "missing_field",
133
+ "left_operand": field,
134
+ "operator": "missing",
135
+ "right_operand": None,
136
+ "complexity": complexity_meta or _default_complexity("missing_field"),
137
+ "declarative_friendly": True if declarative_friendly is None else declarative_friendly,
138
+ "tag": tag,
139
+ "severity": severity,
140
+ "perl_logic": perl_logic.strip(),
141
+ }
142
+
143
+ scaled_match = SCALED_FIELD_COMPARE_RE.search(perl_logic)
144
+ if scaled_match:
145
+ left = scaled_match.group("left")
146
+ operator = scaled_match.group("op")
147
+ right = scaled_match.group("right")
148
+ factor = float(scaled_match.group("factor"))
149
+ condition = f"{left} {operator} ({right} * {factor})"
150
+ return {
151
+ "rule_name": rule_name,
152
+ "condition": condition,
153
+ "duckdb_condition": f"{left} {operator} ({right} * {factor})",
154
+ "condition_type": "scaled_field_comparison",
155
+ "left_operand": left,
156
+ "operator": operator,
157
+ "right_operand": right,
158
+ "scale_factor": factor,
159
+ "complexity": complexity_meta or _default_complexity("scaled_field_comparison"),
160
+ "declarative_friendly": False if declarative_friendly is None else declarative_friendly,
161
+ "tag": tag,
162
+ "severity": severity,
163
+ "perl_logic": perl_logic.strip(),
164
+ }
165
+
166
+ affine_match = AFFINE_FIELD_COMPARE_RE.search(perl_logic)
167
+ if affine_match:
168
+ left = affine_match.group("left")
169
+ operator = affine_match.group("op")
170
+ right = affine_match.group("right")
171
+ factor = float(affine_match.group("factor"))
172
+ offset = float(affine_match.group("offset"))
173
+ if affine_match.group("sign") == "-":
174
+ offset *= -1.0
175
+ offset_sign = "+" if offset >= 0 else "-"
176
+ offset_abs = abs(offset)
177
+ condition = f"{left} {operator} ({factor} * {right} {offset_sign} {offset_abs})"
178
+ return {
179
+ "rule_name": rule_name,
180
+ "condition": condition,
181
+ "duckdb_condition": condition,
182
+ "condition_type": "affine_field_comparison",
183
+ "left_operand": left,
184
+ "operator": operator,
185
+ "right_operand": right,
186
+ "scale_factor": factor,
187
+ "offset": offset,
188
+ "complexity": complexity_meta or _default_complexity("affine_field_comparison"),
189
+ "declarative_friendly": False if declarative_friendly is None else declarative_friendly,
190
+ "tag": tag,
191
+ "severity": severity,
192
+ "perl_logic": perl_logic.strip(),
193
+ }
194
+
195
+ sum_match = SUM_FIELDS_COMPARE_RE.search(perl_logic)
196
+ if sum_match:
197
+ left_a = sum_match.group("left_a")
198
+ left_b = sum_match.group("left_b")
199
+ operator = sum_match.group("op")
200
+ right = sum_match.group("right")
201
+ offset = float(sum_match.group("offset"))
202
+ if sum_match.group("sign") == "-":
203
+ offset *= -1.0
204
+ offset_sign = "+" if offset >= 0 else "-"
205
+ offset_abs = abs(offset)
206
+ condition = f"({left_a} + {left_b}) {operator} ({right} {offset_sign} {offset_abs})"
207
+ return {
208
+ "rule_name": rule_name,
209
+ "condition": condition,
210
+ "duckdb_condition": condition,
211
+ "condition_type": "sum_fields_comparison",
212
+ "left_operands": [left_a, left_b],
213
+ "operator": operator,
214
+ "right_operand": right,
215
+ "right_offset": offset,
216
+ "left_operand": None,
217
+ "complexity": complexity_meta or _default_complexity("sum_fields_comparison"),
218
+ "declarative_friendly": True if declarative_friendly is None else declarative_friendly,
219
+ "tag": tag,
220
+ "severity": severity,
221
+ "perl_logic": perl_logic.strip(),
222
+ }
223
+
224
+ if "&&" in perl_logic:
225
+ condition_match = IF_CONDITION_RE.search(perl_logic)
226
+ if condition_match:
227
+ condition_body = condition_match.group("condition").strip()
228
+ clauses: List[Dict[str, object]] = []
229
+ for part in [token.strip() for token in condition_body.split("&&")]:
230
+ clause_match = THRESHOLD_CLAUSE_RE.match(part)
231
+ if not clause_match:
232
+ clauses = []
233
+ break
234
+ clauses.append(
235
+ {
236
+ "left_operand": clause_match.group("left"),
237
+ "operator": clause_match.group("op"),
238
+ "right_operand": float(clause_match.group("right")),
239
+ }
240
+ )
241
+ if clauses:
242
+ duckdb_condition = " AND ".join(
243
+ f"{clause['left_operand']} {clause['operator']} {clause['right_operand']}" for clause in clauses
244
+ )
245
+ condition = " && ".join(
246
+ f"{clause['left_operand']} {clause['operator']} {clause['right_operand']}" for clause in clauses
247
+ )
248
+ return {
249
+ "rule_name": rule_name,
250
+ "condition": condition,
251
+ "duckdb_condition": duckdb_condition,
252
+ "condition_type": "compound_threshold_and",
253
+ "clauses": clauses,
254
+ "left_operand": None,
255
+ "operator": "&&",
256
+ "right_operand": None,
257
+ "complexity": complexity_meta or _default_complexity("compound_threshold_and"),
258
+ "declarative_friendly": True if declarative_friendly is None else declarative_friendly,
259
+ "tag": tag,
260
+ "severity": severity,
261
+ "perl_logic": perl_logic.strip(),
262
+ }
263
+
264
+ var_match = VAR_COMPARE_RE.search(perl_logic)
265
+ if var_match:
266
+ left = var_match.group("left")
267
+ operator = var_match.group("op")
268
+ right = var_match.group("right")
269
+ condition = f"{left} {operator} {right}"
270
+ return {
271
+ "rule_name": rule_name,
272
+ "condition": condition,
273
+ "duckdb_condition": condition,
274
+ "condition_type": "field_comparison",
275
+ "left_operand": left,
276
+ "operator": operator,
277
+ "right_operand": right,
278
+ "complexity": complexity_meta or _default_complexity("field_comparison"),
279
+ "declarative_friendly": True if declarative_friendly is None else declarative_friendly,
280
+ "tag": tag,
281
+ "severity": severity,
282
+ "perl_logic": perl_logic.strip(),
283
+ }
284
+
285
+ value_match = VALUE_COMPARE_RE.search(perl_logic)
286
+ if value_match:
287
+ left = value_match.group("left")
288
+ operator = value_match.group("op")
289
+ right = value_match.group("right")
290
+ condition = f"{left} {operator} {right}"
291
+ return {
292
+ "rule_name": rule_name,
293
+ "condition": condition,
294
+ "duckdb_condition": condition,
295
+ "condition_type": "field_threshold",
296
+ "left_operand": left,
297
+ "operator": operator,
298
+ "right_operand": float(right),
299
+ "complexity": complexity_meta or _default_complexity("field_threshold"),
300
+ "declarative_friendly": True if declarative_friendly is None else declarative_friendly,
301
+ "tag": tag,
302
+ "severity": severity,
303
+ "perl_logic": perl_logic.strip(),
304
+ }
305
+
306
+ raise ValueError(f"Unsupported Perl condition format:\n{perl_logic}")
307
+
308
+
309
+ def extract_rules(perl_snippets: Sequence[str] | str) -> List[Dict[str, object]]:
310
+ """Extract structured rules from Perl snippets."""
311
+ snippets: Iterable[str]
312
+ if isinstance(perl_snippets, str):
313
+ snippets = [chunk.strip() for chunk in perl_snippets.split("\n\n") if chunk.strip()]
314
+ else:
315
+ snippets = perl_snippets
316
+ return [_attach_rule_ir(extract_rule(snippet)) for snippet in snippets]
OFF_DataQuality/inspect_duckdb.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ import duckdb
2
+
3
+ print('module', duckdb)
4
+ print('attrs', dir(duckdb))
5
+ print('has_connect', 'connect' in dir(duckdb))
6
+ print('location', getattr(duckdb, '__file__', None))
OFF_DataQuality/llm-test/test_groq.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ from openai import OpenAI
4
+
5
+
6
+ def main() -> None:
7
+ api_key = os.getenv("GROQ_API_KEY")
8
+ if not api_key:
9
+ raise RuntimeError("GROQ_API_KEY is not set. Set it in your shell before running.")
10
+
11
+ client = OpenAI(
12
+ api_key=api_key,
13
+ base_url="https://api.groq.com/openai/v1",
14
+ )
15
+
16
+ response = client.chat.completions.create(
17
+ model="openai/gpt-oss-120b",
18
+ messages=[{"role": "user", "content": "Explain quantum tunnelling in one paragraph"}],
19
+ temperature=0.7,
20
+ max_tokens=500,
21
+ )
22
+ print(response.choices[0].message.content)
23
+
24
+
25
+ if __name__ == "__main__":
26
+ main()
OFF_DataQuality/migration/__init__.py ADDED
File without changes
OFF_DataQuality/migration/llm_converter.py ADDED
@@ -0,0 +1,714 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """LLM-style conversion from structured rules to Python check code."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import os
6
+ import re
7
+ from dataclasses import asdict, dataclass
8
+ from typing import Dict, List, Sequence
9
+
10
+
11
+ @dataclass(frozen=True)
12
+ class ConversionResult:
13
+ rule_name: str
14
+ function_name: str
15
+ python_code: str
16
+ llm_confidence: float
17
+ conversion_notes: str
18
+ provider: str
19
+
20
+
21
+ def _safe_identifier(name: str) -> str:
22
+ sanitized = re.sub(r"[^a-zA-Z0-9_]", "_", name).strip("_")
23
+ if not sanitized:
24
+ sanitized = "generated_rule"
25
+ if sanitized[0].isdigit():
26
+ sanitized = f"rule_{sanitized}"
27
+ return sanitized
28
+
29
+
30
+ def _python_literal(value: object) -> str:
31
+ if isinstance(value, str):
32
+ return repr(value)
33
+ if isinstance(value, (int, float)):
34
+ return str(value)
35
+ if value is None:
36
+ return "None"
37
+ return repr(str(value))
38
+
39
+
40
+ def _confidence_for_rule(rule: Dict[str, object]) -> float:
41
+ condition_type = str(rule.get("condition_type", ""))
42
+ if condition_type == "field_comparison":
43
+ return 0.98
44
+ if condition_type == "field_threshold":
45
+ return 0.96
46
+ if condition_type == "missing_field":
47
+ return 0.93
48
+ if condition_type == "sum_fields_comparison":
49
+ return 0.91
50
+ if condition_type == "compound_threshold_and":
51
+ return 0.90
52
+ if condition_type == "affine_field_comparison":
53
+ return 0.89
54
+ if condition_type == "scaled_field_comparison":
55
+ return 0.88
56
+ return 0.80
57
+
58
+
59
+ def _build_python_code(rule: Dict[str, object], function_name: str) -> str:
60
+ tag_literal = _python_literal(rule["tag"])
61
+ condition_type = str(rule.get("condition_type"))
62
+
63
+ if condition_type == "field_comparison":
64
+ left = str(rule["left_operand"])
65
+ right = str(rule["right_operand"])
66
+ operator = str(rule["operator"])
67
+ return f"""def {function_name}(product):
68
+ left_raw = product.get({left!r})
69
+ right_raw = product.get({right!r})
70
+ try:
71
+ left_value = float(left_raw)
72
+ right_value = float(right_raw)
73
+ except (TypeError, ValueError):
74
+ return None
75
+ if left_value {operator} right_value:
76
+ return {tag_literal}
77
+ return None
78
+ """
79
+
80
+ if condition_type == "field_threshold":
81
+ left = str(rule["left_operand"])
82
+ operator = str(rule["operator"])
83
+ right_literal = _python_literal(rule["right_operand"])
84
+ return f"""def {function_name}(product):
85
+ left_raw = product.get({left!r})
86
+ try:
87
+ left_value = float(left_raw)
88
+ except (TypeError, ValueError):
89
+ return None
90
+ if left_value {operator} {right_literal}:
91
+ return {tag_literal}
92
+ return None
93
+ """
94
+
95
+ if condition_type == "missing_field":
96
+ field = str(rule["left_operand"])
97
+ return f"""def {function_name}(product):
98
+ value = product.get({field!r})
99
+ if value is None or str(value).strip() == "":
100
+ return {tag_literal}
101
+ return None
102
+ """
103
+
104
+ if condition_type == "scaled_field_comparison":
105
+ left = str(rule["left_operand"])
106
+ right = str(rule["right_operand"])
107
+ operator = str(rule["operator"])
108
+ factor = float(rule["scale_factor"])
109
+ return f"""def {function_name}(product):
110
+ left_raw = product.get({left!r})
111
+ right_raw = product.get({right!r})
112
+ try:
113
+ left_value = float(left_raw)
114
+ right_value = float(right_raw)
115
+ except (TypeError, ValueError):
116
+ return None
117
+ scaled_value = right_value * {factor}
118
+ if left_value {operator} scaled_value:
119
+ return {tag_literal}
120
+ return None
121
+ """
122
+
123
+ if condition_type == "compound_threshold_and":
124
+ clauses = list(rule.get("clauses", []))
125
+ lines = [
126
+ f"def {function_name}(product):",
127
+ " try:",
128
+ ]
129
+ for idx, clause in enumerate(clauses):
130
+ field = str(clause["left_operand"])
131
+ lines.append(f" value_{idx} = float(product.get({field!r}))")
132
+ lines.append(" except (TypeError, ValueError):")
133
+ lines.append(" return None")
134
+ checks: List[str] = []
135
+ for idx, clause in enumerate(clauses):
136
+ operator = str(clause["operator"])
137
+ threshold = float(clause["right_operand"])
138
+ checks.append(f"(value_{idx} {operator} {threshold})")
139
+ joined = " and ".join(checks) if checks else "False"
140
+ lines.append(f" if {joined}:")
141
+ lines.append(f" return {tag_literal}")
142
+ lines.append(" return None")
143
+ return "\n".join(lines) + "\n"
144
+
145
+ if condition_type == "affine_field_comparison":
146
+ left = str(rule["left_operand"])
147
+ right = str(rule["right_operand"])
148
+ operator = str(rule["operator"])
149
+ factor = float(rule["scale_factor"])
150
+ offset = float(rule["offset"])
151
+ return f"""def {function_name}(product):
152
+ left_raw = product.get({left!r})
153
+ right_raw = product.get({right!r})
154
+ try:
155
+ left_value = float(left_raw)
156
+ right_value = float(right_raw)
157
+ except (TypeError, ValueError):
158
+ return None
159
+ target = ({factor} * right_value) + ({offset})
160
+ if left_value {operator} target:
161
+ return {tag_literal}
162
+ return None
163
+ """
164
+
165
+ if condition_type == "sum_fields_comparison":
166
+ left_operands = list(rule.get("left_operands", []))
167
+ if len(left_operands) != 2:
168
+ raise ValueError("sum_fields_comparison requires exactly two left_operands.")
169
+ left_a = str(left_operands[0])
170
+ left_b = str(left_operands[1])
171
+ right = str(rule["right_operand"])
172
+ operator = str(rule["operator"])
173
+ right_offset = float(rule["right_offset"])
174
+ return f"""def {function_name}(product):
175
+ left_a_raw = product.get({left_a!r})
176
+ left_b_raw = product.get({left_b!r})
177
+ right_raw = product.get({right!r})
178
+ try:
179
+ left_a_value = float(left_a_raw)
180
+ left_b_value = float(left_b_raw)
181
+ right_value = float(right_raw)
182
+ except (TypeError, ValueError):
183
+ return None
184
+ left_sum = left_a_value + left_b_value
185
+ right_target = right_value + ({right_offset})
186
+ if left_sum {operator} right_target:
187
+ return {tag_literal}
188
+ return None
189
+ """
190
+
191
+ raise ValueError(f"Unsupported condition type: {condition_type}")
192
+
193
+
194
+ def _extract_code_block(text: str) -> str:
195
+ match = re.search(r"```(?:python)?\s*(?P<code>.*?)```", text, re.DOTALL | re.IGNORECASE)
196
+ if match:
197
+ return match.group("code").strip()
198
+ return text.strip()
199
+
200
+
201
+ def _validate_generated_code(code: str, function_name: str) -> None:
202
+ namespace: Dict[str, object] = {}
203
+ exec(code, {}, namespace)
204
+ fn = namespace.get(function_name)
205
+ if not callable(fn):
206
+ raise ValueError(f"Generated code does not define callable `{function_name}`.")
207
+ # Basic runtime contract checks to avoid unsafe generated code.
208
+ probe_products = [
209
+ {},
210
+ {
211
+ "energy_kj": None,
212
+ "energy_kj_computed": None,
213
+ "energy_kcal": 100.0,
214
+ "fat": None,
215
+ "saturated_fat": None,
216
+ "carbohydrates": None,
217
+ "sugars": None,
218
+ "language_code": None,
219
+ "ingredients_text_present": None,
220
+ "contains_statement_present": None,
221
+ "allergen_evidence_present": None,
222
+ "fop_threshold_exceeded": None,
223
+ "fop_symbol_present": None,
224
+ "fop_exempt_proxy": None,
225
+ "product_is_prepackaged_proxy": None,
226
+ },
227
+ {
228
+ "energy_kj": 100.0,
229
+ "energy_kj_computed": 100.0,
230
+ "energy_kcal": 10.0,
231
+ "fat": 10.0,
232
+ "saturated_fat": 2.0,
233
+ "carbohydrates": 15.0,
234
+ "sugars": 5.0,
235
+ "language_code": "en",
236
+ "ingredients_text_present": 1,
237
+ "contains_statement_present": 0,
238
+ "allergen_evidence_present": 0,
239
+ "fop_threshold_exceeded": 0,
240
+ "fop_symbol_present": 0,
241
+ "fop_exempt_proxy": 0,
242
+ "product_is_prepackaged_proxy": 1,
243
+ },
244
+ ]
245
+ for product in probe_products:
246
+ try:
247
+ result = fn(product)
248
+ except Exception as exc: # noqa: BLE001 - intentional hard guard for generated code
249
+ raise ValueError(f"Generated function raised {exc.__class__.__name__}: {exc}") from exc
250
+ if result is not None and not isinstance(result, str):
251
+ raise ValueError("Generated function must return str or None.")
252
+
253
+
254
+ def _comparison_truth_pairs(operator_token: str) -> tuple[tuple[float, float], tuple[float, float]]:
255
+ pairs = {
256
+ ">": ((2.0, 1.0), (1.0, 2.0)),
257
+ "<": ((1.0, 2.0), (2.0, 1.0)),
258
+ ">=": ((2.0, 2.0), (1.0, 2.0)),
259
+ "<=": ((2.0, 2.0), (3.0, 2.0)),
260
+ "==": ((2.0, 2.0), (2.0, 3.0)),
261
+ "!=": ((2.0, 3.0), (2.0, 2.0)),
262
+ }
263
+ if operator_token not in pairs:
264
+ raise ValueError(f"Unsupported comparison operator: {operator_token}")
265
+ return pairs[operator_token]
266
+
267
+
268
+ def _threshold_truth_values(operator_token: str, threshold: float) -> tuple[float, float]:
269
+ if operator_token == ">":
270
+ return threshold + 1.0, threshold
271
+ if operator_token == "<":
272
+ return threshold - 1.0, threshold
273
+ if operator_token == ">=":
274
+ return threshold, threshold - 1.0
275
+ if operator_token == "<=":
276
+ return threshold, threshold + 1.0
277
+ if operator_token == "==":
278
+ return threshold, threshold + 1.0
279
+ if operator_token == "!=":
280
+ return threshold + 1.0, threshold
281
+ raise ValueError(f"Unsupported threshold operator: {operator_token}")
282
+
283
+
284
+ def _semantic_test_cases(rule: Dict[str, object]) -> List[tuple[Dict[str, object], str | None, str]]:
285
+ condition_type = str(rule.get("condition_type"))
286
+ tag = str(rule["tag"])
287
+
288
+ if condition_type == "field_comparison":
289
+ left = str(rule["left_operand"])
290
+ right = str(rule["right_operand"])
291
+ operator_token = str(rule["operator"])
292
+ true_pair, false_pair = _comparison_truth_pairs(operator_token)
293
+ return [
294
+ ({left: true_pair[0], right: true_pair[1]}, tag, "comparison_true"),
295
+ ({left: false_pair[0], right: false_pair[1]}, None, "comparison_false"),
296
+ ({left: None, right: true_pair[1]}, None, "comparison_missing_left"),
297
+ ({left: true_pair[0], right: None}, None, "comparison_missing_right"),
298
+ ({left: "nan_text", right: true_pair[1]}, None, "comparison_non_numeric_left"),
299
+ ]
300
+
301
+ if condition_type == "field_threshold":
302
+ left = str(rule["left_operand"])
303
+ operator_token = str(rule["operator"])
304
+ threshold = float(rule["right_operand"])
305
+ true_value, false_value = _threshold_truth_values(operator_token, threshold)
306
+ return [
307
+ ({left: true_value}, tag, "threshold_true"),
308
+ ({left: false_value}, None, "threshold_false"),
309
+ ({left: None}, None, "threshold_missing"),
310
+ ({left: "nan_text"}, None, "threshold_non_numeric"),
311
+ ]
312
+
313
+ if condition_type == "missing_field":
314
+ field = str(rule["left_operand"])
315
+ return [
316
+ ({field: None}, tag, "missing_none"),
317
+ ({field: ""}, tag, "missing_empty_string"),
318
+ ({field: " "}, tag, "missing_whitespace"),
319
+ ({field: "en"}, None, "missing_present"),
320
+ ]
321
+
322
+ if condition_type == "scaled_field_comparison":
323
+ left = str(rule["left_operand"])
324
+ right = str(rule["right_operand"])
325
+ operator_token = str(rule["operator"])
326
+ factor = float(rule["scale_factor"])
327
+ true_right = 10.0
328
+ scaled = true_right * factor
329
+ if operator_token == ">":
330
+ true_left, false_left = scaled + 1.0, scaled - 1.0
331
+ elif operator_token == ">=":
332
+ true_left, false_left = scaled, scaled - 1.0
333
+ elif operator_token == "<":
334
+ true_left, false_left = scaled - 1.0, scaled + 1.0
335
+ elif operator_token == "<=":
336
+ true_left, false_left = scaled, scaled + 1.0
337
+ elif operator_token == "==":
338
+ true_left, false_left = scaled, scaled + 1.0
339
+ elif operator_token == "!=":
340
+ true_left, false_left = scaled + 1.0, scaled
341
+ else:
342
+ raise ValueError(f"Unsupported scaled comparison operator: {operator_token}")
343
+ return [
344
+ ({left: true_left, right: true_right}, tag, "scaled_true"),
345
+ ({left: false_left, right: true_right}, None, "scaled_false"),
346
+ ({left: None, right: true_right}, None, "scaled_missing_left"),
347
+ ({left: true_left, right: None}, None, "scaled_missing_right"),
348
+ ({left: "nan_text", right: true_right}, None, "scaled_non_numeric"),
349
+ ]
350
+
351
+ if condition_type == "affine_field_comparison":
352
+ left = str(rule["left_operand"])
353
+ right = str(rule["right_operand"])
354
+ operator_token = str(rule["operator"])
355
+ factor = float(rule["scale_factor"])
356
+ offset = float(rule["offset"])
357
+ true_right = 10.0
358
+ target = (factor * true_right) + offset
359
+ if operator_token == ">":
360
+ true_left, false_left = target + 1.0, target - 1.0
361
+ elif operator_token == ">=":
362
+ true_left, false_left = target, target - 1.0
363
+ elif operator_token == "<":
364
+ true_left, false_left = target - 1.0, target + 1.0
365
+ elif operator_token == "<=":
366
+ true_left, false_left = target, target + 1.0
367
+ elif operator_token == "==":
368
+ true_left, false_left = target, target + 1.0
369
+ elif operator_token == "!=":
370
+ true_left, false_left = target + 1.0, target
371
+ else:
372
+ raise ValueError(f"Unsupported affine comparison operator: {operator_token}")
373
+ return [
374
+ ({left: true_left, right: true_right}, tag, "affine_true"),
375
+ ({left: false_left, right: true_right}, None, "affine_false"),
376
+ ({left: None, right: true_right}, None, "affine_missing_left"),
377
+ ({left: true_left, right: None}, None, "affine_missing_right"),
378
+ ({left: "nan_text", right: true_right}, None, "affine_non_numeric"),
379
+ ]
380
+
381
+ if condition_type == "sum_fields_comparison":
382
+ left_operands = list(rule.get("left_operands", []))
383
+ if len(left_operands) != 2:
384
+ raise ValueError("sum_fields_comparison rule must define two left operands.")
385
+ left_a = str(left_operands[0])
386
+ left_b = str(left_operands[1])
387
+ right = str(rule["right_operand"])
388
+ operator_token = str(rule["operator"])
389
+ right_offset = float(rule["right_offset"])
390
+ right_value = 20.0
391
+ target = right_value + right_offset
392
+ if operator_token == ">":
393
+ true_sum, false_sum = target + 1.0, target - 1.0
394
+ elif operator_token == ">=":
395
+ true_sum, false_sum = target, target - 1.0
396
+ elif operator_token == "<":
397
+ true_sum, false_sum = target - 1.0, target + 1.0
398
+ elif operator_token == "<=":
399
+ true_sum, false_sum = target, target + 1.0
400
+ elif operator_token == "==":
401
+ true_sum, false_sum = target, target + 1.0
402
+ elif operator_token == "!=":
403
+ true_sum, false_sum = target + 1.0, target
404
+ else:
405
+ raise ValueError(f"Unsupported sum comparison operator: {operator_token}")
406
+
407
+ true_a = true_sum / 2.0
408
+ true_b = true_sum - true_a
409
+ false_a = false_sum / 2.0
410
+ false_b = false_sum - false_a
411
+ return [
412
+ ({left_a: true_a, left_b: true_b, right: right_value}, tag, "sum_true"),
413
+ ({left_a: false_a, left_b: false_b, right: right_value}, None, "sum_false"),
414
+ ({left_a: None, left_b: true_b, right: right_value}, None, "sum_missing_left_a"),
415
+ ({left_a: true_a, left_b: None, right: right_value}, None, "sum_missing_left_b"),
416
+ ({left_a: true_a, left_b: true_b, right: None}, None, "sum_missing_right"),
417
+ ]
418
+
419
+ if condition_type == "compound_threshold_and":
420
+ clauses = list(rule.get("clauses", []))
421
+ if not clauses:
422
+ raise ValueError("compound_threshold_and rule must define clauses.")
423
+ true_product: Dict[str, object] = {}
424
+ false_product: Dict[str, object] = {}
425
+ missing_product: Dict[str, object] = {}
426
+ for idx, clause in enumerate(clauses):
427
+ field = str(clause["left_operand"])
428
+ operator_token = str(clause["operator"])
429
+ threshold = float(clause["right_operand"])
430
+ true_value, false_value = _threshold_truth_values(operator_token, threshold)
431
+ true_product[field] = true_value
432
+ false_product[field] = true_value
433
+ missing_product[field] = true_value
434
+ if idx == 0:
435
+ false_product[field] = false_value
436
+ missing_product[field] = None
437
+ return [
438
+ (true_product, tag, "compound_true"),
439
+ (false_product, None, "compound_false"),
440
+ (missing_product, None, "compound_missing"),
441
+ ]
442
+
443
+ raise ValueError(f"Unsupported condition type for semantic checks: {condition_type}")
444
+
445
+
446
+ def _validate_generated_semantics(code: str, function_name: str, rule: Dict[str, object]) -> None:
447
+ namespace: Dict[str, object] = {}
448
+ exec(code, {}, namespace)
449
+ fn = namespace.get(function_name)
450
+ if not callable(fn):
451
+ raise ValueError(f"Generated code does not define callable `{function_name}`.")
452
+
453
+ for product, expected, case_name in _semantic_test_cases(rule):
454
+ try:
455
+ result = fn(product)
456
+ except Exception as exc: # noqa: BLE001
457
+ raise ValueError(f"Semantic test `{case_name}` raised {exc.__class__.__name__}: {exc}") from exc
458
+ if result != expected:
459
+ raise ValueError(
460
+ f"Semantic test `{case_name}` failed: expected {expected!r}, got {result!r}."
461
+ )
462
+
463
+
464
+ def _normalize_function_name(code: str, function_name: str) -> str:
465
+ """Rename the first generated function to the expected runtime name."""
466
+ match = re.search(r"def\s+(?P<name>[a-zA-Z_]\w*)\s*\(", code)
467
+ if not match:
468
+ return code
469
+ found_name = match.group("name")
470
+ if found_name == function_name:
471
+ return code
472
+ start, end = match.span("name")
473
+ return code[:start] + function_name + code[end:]
474
+
475
+
476
+ def _build_llm_prompt(rule: Dict[str, object], function_name: str) -> str:
477
+ rule_payload = {
478
+ "rule_name": rule["rule_name"],
479
+ "tag": rule["tag"],
480
+ "condition_type": rule["condition_type"],
481
+ "condition": rule.get("condition"),
482
+ "duckdb_condition": rule.get("duckdb_condition"),
483
+ "left_operand": rule.get("left_operand"),
484
+ "left_operands": rule.get("left_operands"),
485
+ "operator": rule.get("operator"),
486
+ "right_operand": rule.get("right_operand"),
487
+ "scale_factor": rule.get("scale_factor"),
488
+ "offset": rule.get("offset"),
489
+ "right_offset": rule.get("right_offset"),
490
+ "clauses": rule.get("clauses"),
491
+ "complexity": rule.get("complexity"),
492
+ }
493
+ examples: List[Dict[str, object]] = []
494
+ for product, expected, case_name in _semantic_test_cases(rule):
495
+ examples.append({"case": case_name, "input": product, "expected": expected})
496
+ return (
497
+ "Generate one Python function for a data-quality rule.\n"
498
+ f"Function name must be exactly: {function_name}\n"
499
+ "Input: product (dict)\n"
500
+ "Output: return the rule tag string if the VIOLATION condition is TRUE; else return None.\n"
501
+ "Important: do NOT invert the condition.\n"
502
+ "Important: return only Python code, no markdown, no explanation.\n"
503
+ "Behavior requirements:\n"
504
+ "- field_comparison and field_threshold rules: if value is missing/non-numeric, return None.\n"
505
+ '- missing_field rule: None, empty string "", or whitespace-only string => return tag.\n'
506
+ "- Otherwise return None.\n"
507
+ f"Rule JSON: {json.dumps(rule_payload)}\n"
508
+ f"Validation examples (must pass): {json.dumps(examples)}"
509
+ )
510
+
511
+
512
+ def _build_llm_repair_prompt(
513
+ rule: Dict[str, object],
514
+ function_name: str,
515
+ previous_code: str,
516
+ error_message: str,
517
+ ) -> str:
518
+ return (
519
+ "Your previous function failed validator checks.\n"
520
+ f"Validation error: {error_message}\n"
521
+ "Fix the function so all examples pass.\n"
522
+ "Return only corrected Python code.\n"
523
+ f"Previous code:\n{previous_code}\n\n"
524
+ f"{_build_llm_prompt(rule, function_name)}"
525
+ )
526
+
527
+
528
+ def _call_groq(
529
+ rule: Dict[str, object],
530
+ function_name: str,
531
+ model: str,
532
+ prompt: str | None = None,
533
+ ) -> str:
534
+ api_key = os.getenv("GROQ_API_KEY")
535
+ if not api_key:
536
+ raise RuntimeError("GROQ_API_KEY is not set.")
537
+
538
+ try:
539
+ from openai import OpenAI
540
+ except Exception as exc: # noqa: BLE001
541
+ raise RuntimeError("openai package is required for Groq provider.") from exc
542
+
543
+ endpoint = os.getenv("GROQ_ENDPOINT", "https://api.groq.com/openai/v1")
544
+ client = OpenAI(api_key=api_key, base_url=endpoint)
545
+ response = client.chat.completions.create(
546
+ model=model,
547
+ messages=[
548
+ {"role": "system", "content": "You are a strict Python code generator for data quality rules."},
549
+ {"role": "user", "content": prompt or _build_llm_prompt(rule, function_name)},
550
+ ],
551
+ temperature=0.0,
552
+ )
553
+ content = response.choices[0].message.content
554
+ if not isinstance(content, str):
555
+ content = str(content)
556
+ return _extract_code_block(content)
557
+
558
+
559
+ def convert_rule_to_python(
560
+ rule: Dict[str, object],
561
+ provider: str = "groq",
562
+ model: str | None = None,
563
+ ) -> ConversionResult:
564
+ """Convert one structured rule to Python code and confidence metadata."""
565
+ function_name = f"check_{_safe_identifier(str(rule['rule_name']))}"
566
+ confidence = _confidence_for_rule(rule)
567
+ provider_used = provider
568
+
569
+ if provider == "groq":
570
+ strict_llm = os.getenv("LLM_STRICT", "0").strip().lower() in {"1", "true", "yes", "on"}
571
+ chosen_model = model or os.getenv("GROQ_MODEL", "openai/gpt-oss-120b")
572
+ first_attempt_code = ""
573
+ try:
574
+ python_code = _call_groq(rule, function_name=function_name, model=chosen_model)
575
+ first_attempt_code = python_code
576
+ python_code = _normalize_function_name(python_code, function_name=function_name)
577
+ _validate_generated_code(python_code, function_name=function_name)
578
+ _validate_generated_semantics(python_code, function_name=function_name, rule=rule)
579
+ notes = f"Converted via Groq ({chosen_model})."
580
+ confidence = min(0.99, confidence + 0.01)
581
+ except (
582
+ RuntimeError,
583
+ ValueError,
584
+ TypeError,
585
+ json.JSONDecodeError,
586
+ TimeoutError,
587
+ ) as exc:
588
+ repair_exc: Exception | None = None
589
+ try:
590
+ repair_prompt = _build_llm_repair_prompt(
591
+ rule=rule,
592
+ function_name=function_name,
593
+ previous_code=first_attempt_code or "# no usable code returned in first attempt",
594
+ error_message=f"{exc.__class__.__name__}: {exc}",
595
+ )
596
+ python_code = _call_groq(
597
+ rule,
598
+ function_name=function_name,
599
+ model=chosen_model,
600
+ prompt=repair_prompt,
601
+ )
602
+ python_code = _normalize_function_name(python_code, function_name=function_name)
603
+ _validate_generated_code(python_code, function_name=function_name)
604
+ _validate_generated_semantics(python_code, function_name=function_name, rule=rule)
605
+ notes = f"Converted via Groq ({chosen_model}) after repair pass."
606
+ confidence = min(0.99, confidence + 0.005)
607
+ except (
608
+ RuntimeError,
609
+ ValueError,
610
+ TypeError,
611
+ json.JSONDecodeError,
612
+ TimeoutError,
613
+ ) as second_exc:
614
+ repair_exc = second_exc
615
+
616
+ if repair_exc is not None:
617
+ if strict_llm:
618
+ raise RuntimeError(
619
+ f"Groq conversion failed and LLM_STRICT=1 is enabled. "
620
+ f"First error: {exc.__class__.__name__}: {exc} | "
621
+ f"Repair error: {repair_exc.__class__.__name__}: {repair_exc}"
622
+ ) from repair_exc
623
+ python_code = _build_python_code(rule, function_name=function_name)
624
+ _validate_generated_code(python_code, function_name=function_name)
625
+ _validate_generated_semantics(python_code, function_name=function_name, rule=rule)
626
+ notes = (
627
+ f"Groq conversion failed after retry "
628
+ f"(first: {exc.__class__.__name__}: {exc}; "
629
+ f"retry: {repair_exc.__class__.__name__}: {repair_exc}). "
630
+ "Fell back to deterministic converter."
631
+ )
632
+ provider_used = "simulated_fallback"
633
+ confidence = max(0.70, confidence - 0.05)
634
+ else:
635
+ if provider not in {"simulated", "simulated_fallback"}:
636
+ provider_used = "simulated_fallback"
637
+ python_code = _build_python_code(rule, function_name=function_name)
638
+ _validate_generated_code(python_code, function_name=function_name)
639
+ _validate_generated_semantics(python_code, function_name=function_name, rule=rule)
640
+ notes = f"Converted {rule['condition_type']} rule using deterministic template."
641
+
642
+ return ConversionResult(
643
+ rule_name=str(rule["rule_name"]),
644
+ function_name=function_name,
645
+ python_code=python_code,
646
+ llm_confidence=confidence,
647
+ conversion_notes=notes,
648
+ provider=provider_used,
649
+ )
650
+
651
+
652
+ def _build_counterexample_repair_prompt(
653
+ rule: Dict[str, object],
654
+ function_name: str,
655
+ previous_code: str,
656
+ counterexamples: Sequence[Dict[str, object]],
657
+ ) -> str:
658
+ limited = list(counterexamples)[:5]
659
+ return (
660
+ "Your previous code fails equivalence against legacy Perl behavior.\n"
661
+ "Fix the function using these concrete failing examples.\n"
662
+ "Return only Python code.\n"
663
+ f"Function name must remain: {function_name}\n"
664
+ f"Counterexamples: {json.dumps(limited)}\n"
665
+ f"Previous code:\n{previous_code}\n\n"
666
+ f"{_build_llm_prompt(rule, function_name)}"
667
+ )
668
+
669
+
670
+ def repair_conversion_with_counterexamples(
671
+ rule: Dict[str, object],
672
+ converted_rule: Dict[str, object],
673
+ counterexamples: Sequence[Dict[str, object]],
674
+ provider: str = "groq",
675
+ model: str | None = None,
676
+ ) -> Dict[str, object]:
677
+ """Attempt counterexample-driven repair for an already converted rule."""
678
+ if provider != "groq":
679
+ return dict(converted_rule)
680
+ if not counterexamples:
681
+ return dict(converted_rule)
682
+
683
+ function_name = str(converted_rule["function_name"])
684
+ previous_code = str(converted_rule["python_code"])
685
+ chosen_model = model or os.getenv("GROQ_MODEL", "openai/gpt-oss-120b")
686
+ repair_prompt = _build_counterexample_repair_prompt(
687
+ rule=rule,
688
+ function_name=function_name,
689
+ previous_code=previous_code,
690
+ counterexamples=counterexamples,
691
+ )
692
+ repaired_code = _call_groq(rule, function_name=function_name, model=chosen_model, prompt=repair_prompt)
693
+ repaired_code = _normalize_function_name(repaired_code, function_name=function_name)
694
+ _validate_generated_code(repaired_code, function_name=function_name)
695
+ _validate_generated_semantics(repaired_code, function_name=function_name, rule=rule)
696
+
697
+ repaired = dict(converted_rule)
698
+ repaired["python_code"] = repaired_code
699
+ repaired["provider"] = "groq"
700
+ repaired["llm_confidence"] = min(0.99, float(converted_rule.get("llm_confidence", 0.9)) + 0.01)
701
+ repaired["conversion_notes"] = (
702
+ f"{converted_rule.get('conversion_notes', '')} "
703
+ "Counterexample-driven Groq repair applied."
704
+ ).strip()
705
+ return repaired
706
+
707
+
708
+ def convert_rules(
709
+ rules: Sequence[Dict[str, object]],
710
+ provider: str = "groq",
711
+ model: str | None = None,
712
+ ) -> List[Dict[str, object]]:
713
+ """Batch convert structured rules to generated Python snippets."""
714
+ return [asdict(convert_rule_to_python(rule, provider=provider, model=model)) for rule in rules]
OFF_DataQuality/perl_checks/__init__.py ADDED
File without changes
OFF_DataQuality/perl_checks/legacy_checks.py ADDED
@@ -0,0 +1,590 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Simulated legacy Perl checks for migration parity testing."""
2
+ from __future__ import annotations
3
+
4
+ from dataclasses import dataclass
5
+ from pathlib import Path
6
+ from typing import Callable, Dict, List, Mapping, Sequence, Set
7
+
8
+ Product = Mapping[str, object]
9
+
10
+
11
+ @dataclass(frozen=True)
12
+ class LegacyRule:
13
+ rule_name: str
14
+ tag: str
15
+ severity: str
16
+ condition: str
17
+ duckdb_condition: str
18
+ complexity: str
19
+ declarative_friendly: bool
20
+ perl_logic: str
21
+ evaluator: Callable[[Product], bool]
22
+
23
+
24
+ def _to_float(value: object) -> float | None:
25
+ if value is None:
26
+ return None
27
+ try:
28
+ return float(value)
29
+ except (TypeError, ValueError):
30
+ return None
31
+
32
+
33
+ def _greater_than(left_value: object, right_value: object) -> bool:
34
+ left = _to_float(left_value)
35
+ right = _to_float(right_value)
36
+ return left is not None and right is not None and left > right
37
+
38
+
39
+ def _greater_than_plus_offset(left_value: object, right_value: object, offset: float) -> bool:
40
+ left = _to_float(left_value)
41
+ right = _to_float(right_value)
42
+ return left is not None and right is not None and left > (right + offset)
43
+
44
+
45
+ def _affine_compare(
46
+ left_value: object,
47
+ right_value: object,
48
+ operator: str,
49
+ factor: float,
50
+ offset: float,
51
+ ) -> bool:
52
+ left = _to_float(left_value)
53
+ right = _to_float(right_value)
54
+ if left is None or right is None:
55
+ return False
56
+ target = (factor * right) + offset
57
+ if operator == ">":
58
+ return left > target
59
+ if operator == "<":
60
+ return left < target
61
+ if operator == ">=":
62
+ return left >= target
63
+ if operator == "<=":
64
+ return left <= target
65
+ if operator == "==":
66
+ return left == target
67
+ if operator == "!=":
68
+ return left != target
69
+ return False
70
+
71
+
72
+ def _sum_compare(
73
+ left_a: object,
74
+ left_b: object,
75
+ operator: str,
76
+ right: object,
77
+ right_offset: float,
78
+ ) -> bool:
79
+ left_a_num = _to_float(left_a)
80
+ left_b_num = _to_float(left_b)
81
+ right_num = _to_float(right)
82
+ if left_a_num is None or left_b_num is None or right_num is None:
83
+ return False
84
+ left_sum = left_a_num + left_b_num
85
+ right_value = right_num + right_offset
86
+ if operator == ">":
87
+ return left_sum > right_value
88
+ if operator == "<":
89
+ return left_sum < right_value
90
+ if operator == ">=":
91
+ return left_sum >= right_value
92
+ if operator == "<=":
93
+ return left_sum <= right_value
94
+ if operator == "==":
95
+ return left_sum == right_value
96
+ if operator == "!=":
97
+ return left_sum != right_value
98
+ return False
99
+
100
+
101
+ def _is_missing(value: object) -> bool:
102
+ return value is None or str(value).strip() == ""
103
+
104
+
105
+ def _compare_values(left_value: object, operator: str, right_value: object) -> bool:
106
+ left = _to_float(left_value)
107
+ right = _to_float(right_value)
108
+ if left is None or right is None:
109
+ return False
110
+ if operator == ">":
111
+ return left > right
112
+ if operator == "<":
113
+ return left < right
114
+ if operator == ">=":
115
+ return left >= right
116
+ if operator == "<=":
117
+ return left <= right
118
+ if operator == "==":
119
+ return left == right
120
+ if operator == "!=":
121
+ return left != right
122
+ return False
123
+
124
+
125
+ LEGACY_RULES: List[LegacyRule] = [
126
+ LegacyRule(
127
+ rule_name="energy_kcal_vs_kj",
128
+ tag="energy-value-in-kcal-greater-than-in-kj",
129
+ severity="error",
130
+ condition="energy_kcal > energy_kj",
131
+ duckdb_condition="energy_kcal > energy_kj",
132
+ complexity="simple",
133
+ declarative_friendly=True,
134
+ perl_logic="""
135
+ # RULE_NAME: energy_kcal_vs_kj
136
+ # SEVERITY: error
137
+ # COMPLEXITY: simple
138
+ # DECLARATIVE_FRIENDLY: yes
139
+ if ($energy_kcal > $energy_kj) {
140
+ push @{$product_ref->{$data_quality_tags}}, "energy-value-in-kcal-greater-than-in-kj";
141
+ }
142
+ """.strip(),
143
+ evaluator=lambda product: _greater_than(product.get("energy_kcal"), product.get("energy_kj")),
144
+ ),
145
+ LegacyRule(
146
+ rule_name="energy_kj_mismatch_low",
147
+ tag="energy-value-in-kcal-does-not-match-value-in-kj-low",
148
+ severity="error",
149
+ condition="energy_kj < (3.7 * energy_kcal - 2)",
150
+ duckdb_condition="energy_kj < (3.7 * energy_kcal - 2)",
151
+ complexity="intricate",
152
+ declarative_friendly=False,
153
+ perl_logic="""
154
+ # RULE_NAME: energy_kj_mismatch_low
155
+ # SEVERITY: error
156
+ # COMPLEXITY: intricate
157
+ # DECLARATIVE_FRIENDLY: no
158
+ if ($energy_kj < (3.7 * $energy_kcal - 2)) {
159
+ push @{$product_ref->{$data_quality_tags}}, "energy-value-in-kcal-does-not-match-value-in-kj-low";
160
+ }
161
+ """.strip(),
162
+ evaluator=lambda product: _affine_compare(
163
+ product.get("energy_kj"),
164
+ product.get("energy_kcal"),
165
+ operator="<",
166
+ factor=3.7,
167
+ offset=-2.0,
168
+ ),
169
+ ),
170
+ LegacyRule(
171
+ rule_name="energy_kj_mismatch_high",
172
+ tag="energy-value-in-kcal-does-not-match-value-in-kj-high",
173
+ severity="error",
174
+ condition="energy_kj > (4.7 * energy_kcal + 2)",
175
+ duckdb_condition="energy_kj > (4.7 * energy_kcal + 2)",
176
+ complexity="intricate",
177
+ declarative_friendly=False,
178
+ perl_logic="""
179
+ # RULE_NAME: energy_kj_mismatch_high
180
+ # SEVERITY: error
181
+ # COMPLEXITY: intricate
182
+ # DECLARATIVE_FRIENDLY: no
183
+ if ($energy_kj > (4.7 * $energy_kcal + 2)) {
184
+ push @{$product_ref->{$data_quality_tags}}, "energy-value-in-kcal-does-not-match-value-in-kj-high";
185
+ }
186
+ """.strip(),
187
+ evaluator=lambda product: _affine_compare(
188
+ product.get("energy_kj"),
189
+ product.get("energy_kcal"),
190
+ operator=">",
191
+ factor=4.7,
192
+ offset=2.0,
193
+ ),
194
+ ),
195
+ LegacyRule(
196
+ rule_name="energy_kj_over_3911",
197
+ tag="value-over-3911-energy",
198
+ severity="error",
199
+ condition="energy_kj > 3911",
200
+ duckdb_condition="energy_kj > 3911",
201
+ complexity="simple",
202
+ declarative_friendly=True,
203
+ perl_logic="""
204
+ # RULE_NAME: energy_kj_over_3911
205
+ # SEVERITY: error
206
+ # COMPLEXITY: simple
207
+ # DECLARATIVE_FRIENDLY: yes
208
+ if ($energy_kj > 3911) {
209
+ push @{$product_ref->{$data_quality_tags}}, "value-over-3911-energy";
210
+ }
211
+ """.strip(),
212
+ evaluator=lambda product: _greater_than(product.get("energy_kj"), 3911),
213
+ ),
214
+ LegacyRule(
215
+ rule_name="energy_kj_computed_mismatch_low",
216
+ tag="energy-value-in-kj-does-not-match-value-computed-from-other-nutrients-low",
217
+ severity="error",
218
+ condition="energy_kj_computed < (0.7 * energy_kj - 5)",
219
+ duckdb_condition="energy_kj_computed < (0.7 * energy_kj - 5)",
220
+ complexity="intricate",
221
+ declarative_friendly=False,
222
+ perl_logic="""
223
+ # RULE_NAME: energy_kj_computed_mismatch_low
224
+ # SEVERITY: error
225
+ # COMPLEXITY: intricate
226
+ # DECLARATIVE_FRIENDLY: no
227
+ if ($energy_kj_computed < (0.7 * $energy_kj - 5)) {
228
+ push @{$product_ref->{$data_quality_tags}}, "energy-value-in-kj-does-not-match-value-computed-from-other-nutrients-low";
229
+ }
230
+ """.strip(),
231
+ evaluator=lambda product: _affine_compare(
232
+ product.get("energy_kj_computed"),
233
+ product.get("energy_kj"),
234
+ operator="<",
235
+ factor=0.7,
236
+ offset=-5.0,
237
+ ),
238
+ ),
239
+ LegacyRule(
240
+ rule_name="energy_kj_computed_mismatch_high",
241
+ tag="energy-value-in-kj-does-not-match-value-computed-from-other-nutrients-high",
242
+ severity="error",
243
+ condition="energy_kj_computed > (1.3 * energy_kj + 5)",
244
+ duckdb_condition="energy_kj_computed > (1.3 * energy_kj + 5)",
245
+ complexity="intricate",
246
+ declarative_friendly=False,
247
+ perl_logic="""
248
+ # RULE_NAME: energy_kj_computed_mismatch_high
249
+ # SEVERITY: error
250
+ # COMPLEXITY: intricate
251
+ # DECLARATIVE_FRIENDLY: no
252
+ if ($energy_kj_computed > (1.3 * $energy_kj + 5)) {
253
+ push @{$product_ref->{$data_quality_tags}}, "energy-value-in-kj-does-not-match-value-computed-from-other-nutrients-high";
254
+ }
255
+ """.strip(),
256
+ evaluator=lambda product: _affine_compare(
257
+ product.get("energy_kj_computed"),
258
+ product.get("energy_kj"),
259
+ operator=">",
260
+ factor=1.3,
261
+ offset=5.0,
262
+ ),
263
+ ),
264
+ LegacyRule(
265
+ rule_name="saturated_fat_vs_fat",
266
+ tag="saturated-fat-greater-than-fat",
267
+ severity="error",
268
+ condition="saturated_fat > (1 * fat + 0.001)",
269
+ duckdb_condition="saturated_fat > (1 * fat + 0.001)",
270
+ complexity="simple",
271
+ declarative_friendly=True,
272
+ perl_logic="""
273
+ # RULE_NAME: saturated_fat_vs_fat
274
+ # SEVERITY: error
275
+ # COMPLEXITY: simple
276
+ # DECLARATIVE_FRIENDLY: yes
277
+ if ($saturated_fat > (1 * $fat + 0.001)) {
278
+ push @{$product_ref->{$data_quality_tags}}, "saturated-fat-greater-than-fat";
279
+ }
280
+ """.strip(),
281
+ evaluator=lambda product: _greater_than_plus_offset(product.get("saturated_fat"), product.get("fat"), 0.001),
282
+ ),
283
+ LegacyRule(
284
+ rule_name="sugars_plus_starch_vs_carbohydrates",
285
+ tag="sugars-plus-starch-greater-than-carbohydrates",
286
+ severity="error",
287
+ condition="(sugars + starch) > (carbohydrates + 0.001)",
288
+ duckdb_condition="(sugars + starch) > (carbohydrates + 0.001)",
289
+ complexity="medium",
290
+ declarative_friendly=True,
291
+ perl_logic="""
292
+ # RULE_NAME: sugars_plus_starch_vs_carbohydrates
293
+ # SEVERITY: error
294
+ # COMPLEXITY: medium
295
+ # DECLARATIVE_FRIENDLY: yes
296
+ if (($sugars + $starch) > ($carbohydrates + 0.001)) {
297
+ push @{$product_ref->{$data_quality_tags}}, "sugars-plus-starch-greater-than-carbohydrates";
298
+ }
299
+ """.strip(),
300
+ evaluator=lambda product: _sum_compare(
301
+ product.get("sugars"),
302
+ product.get("starch"),
303
+ operator=">",
304
+ right=product.get("carbohydrates"),
305
+ right_offset=0.001,
306
+ ),
307
+ ),
308
+ LegacyRule(
309
+ rule_name="fat_over_105g",
310
+ tag="fat-value-over-105g",
311
+ severity="warning",
312
+ condition="fat > 105",
313
+ duckdb_condition="fat > 105",
314
+ complexity="simple",
315
+ declarative_friendly=True,
316
+ perl_logic="""
317
+ # RULE_NAME: fat_over_105g
318
+ # SEVERITY: warning
319
+ # COMPLEXITY: simple
320
+ # DECLARATIVE_FRIENDLY: yes
321
+ if ($fat > 105) {
322
+ push @{$product_ref->{$data_quality_tags}}, "fat-value-over-105g";
323
+ }
324
+ """.strip(),
325
+ evaluator=lambda product: _greater_than(product.get("fat"), 105),
326
+ ),
327
+ LegacyRule(
328
+ rule_name="saturated_fat_over_105g",
329
+ tag="saturated-fat-value-over-105g",
330
+ severity="warning",
331
+ condition="saturated_fat > 105",
332
+ duckdb_condition="saturated_fat > 105",
333
+ complexity="simple",
334
+ declarative_friendly=True,
335
+ perl_logic="""
336
+ # RULE_NAME: saturated_fat_over_105g
337
+ # SEVERITY: warning
338
+ # COMPLEXITY: simple
339
+ # DECLARATIVE_FRIENDLY: yes
340
+ if ($saturated_fat > 105) {
341
+ push @{$product_ref->{$data_quality_tags}}, "saturated-fat-value-over-105g";
342
+ }
343
+ """.strip(),
344
+ evaluator=lambda product: _greater_than(product.get("saturated_fat"), 105),
345
+ ),
346
+ LegacyRule(
347
+ rule_name="carbohydrates_over_105g",
348
+ tag="carbohydrates-value-over-105g",
349
+ severity="warning",
350
+ condition="carbohydrates > 105",
351
+ duckdb_condition="carbohydrates > 105",
352
+ complexity="simple",
353
+ declarative_friendly=True,
354
+ perl_logic="""
355
+ # RULE_NAME: carbohydrates_over_105g
356
+ # SEVERITY: warning
357
+ # COMPLEXITY: simple
358
+ # DECLARATIVE_FRIENDLY: yes
359
+ if ($carbohydrates > 105) {
360
+ push @{$product_ref->{$data_quality_tags}}, "carbohydrates-value-over-105g";
361
+ }
362
+ """.strip(),
363
+ evaluator=lambda product: _greater_than(product.get("carbohydrates"), 105),
364
+ ),
365
+ LegacyRule(
366
+ rule_name="sugars_over_105g",
367
+ tag="sugars-value-over-105g",
368
+ severity="warning",
369
+ condition="sugars > 105",
370
+ duckdb_condition="sugars > 105",
371
+ complexity="simple",
372
+ declarative_friendly=True,
373
+ perl_logic="""
374
+ # RULE_NAME: sugars_over_105g
375
+ # SEVERITY: warning
376
+ # COMPLEXITY: simple
377
+ # DECLARATIVE_FRIENDLY: yes
378
+ if ($sugars > 105) {
379
+ push @{$product_ref->{$data_quality_tags}}, "sugars-value-over-105g";
380
+ }
381
+ """.strip(),
382
+ evaluator=lambda product: _greater_than(product.get("sugars"), 105),
383
+ ),
384
+ LegacyRule(
385
+ rule_name="main_language_code_missing",
386
+ tag="main-language-code-missing",
387
+ severity="bug",
388
+ condition="missing(lc)",
389
+ duckdb_condition="lc IS NULL OR TRIM(lc) = ''",
390
+ complexity="simple",
391
+ declarative_friendly=True,
392
+ perl_logic="""
393
+ # RULE_NAME: main_language_code_missing
394
+ # SEVERITY: bug
395
+ # COMPLEXITY: simple
396
+ # DECLARATIVE_FRIENDLY: yes
397
+ if (!defined $lc || $lc eq "") {
398
+ push @{$product_ref->{$data_quality_tags}}, "main-language-code-missing";
399
+ }
400
+ """.strip(),
401
+ evaluator=lambda product: _is_missing(product.get("lc")),
402
+ ),
403
+ LegacyRule(
404
+ rule_name="main_language_missing",
405
+ tag="main-language-missing",
406
+ severity="bug",
407
+ condition="missing(lang)",
408
+ duckdb_condition="lang IS NULL OR TRIM(lang) = ''",
409
+ complexity="simple",
410
+ declarative_friendly=True,
411
+ perl_logic="""
412
+ # RULE_NAME: main_language_missing
413
+ # SEVERITY: bug
414
+ # COMPLEXITY: simple
415
+ # DECLARATIVE_FRIENDLY: yes
416
+ if (!defined $lang || $lang eq "") {
417
+ push @{$product_ref->{$data_quality_tags}}, "main-language-missing";
418
+ }
419
+ """.strip(),
420
+ evaluator=lambda product: _is_missing(product.get("lang")),
421
+ ),
422
+ LegacyRule(
423
+ rule_name="ca_allergen_evidence_missing_ingredients_text",
424
+ tag="ca-allergen-evidence-but-missing-ingredients-text",
425
+ severity="warning",
426
+ condition="allergen_evidence_present > 0 && ingredients_text_present == 0",
427
+ duckdb_condition="allergen_evidence_present > 0 AND ingredients_text_present == 0",
428
+ complexity="medium",
429
+ declarative_friendly=True,
430
+ perl_logic="""
431
+ # RULE_NAME: ca_allergen_evidence_missing_ingredients_text
432
+ # SEVERITY: warning
433
+ # COMPLEXITY: medium
434
+ # DECLARATIVE_FRIENDLY: yes
435
+ if (($allergen_evidence_present > 0) && ($ingredients_text_present == 0)) {
436
+ push @{$product_ref->{$data_quality_tags}}, "ca-allergen-evidence-but-missing-ingredients-text";
437
+ }
438
+ """.strip(),
439
+ evaluator=lambda product: (
440
+ _compare_values(product.get("allergen_evidence_present"), ">", 0)
441
+ and _compare_values(product.get("ingredients_text_present"), "==", 0)
442
+ ),
443
+ ),
444
+ LegacyRule(
445
+ rule_name="ca_contains_statement_without_allergen_evidence",
446
+ tag="ca-contains-statement-without-allergen-evidence",
447
+ severity="warning",
448
+ condition="contains_statement_present > 0 && allergen_evidence_present == 0",
449
+ duckdb_condition="contains_statement_present > 0 AND allergen_evidence_present == 0",
450
+ complexity="medium",
451
+ declarative_friendly=True,
452
+ perl_logic="""
453
+ # RULE_NAME: ca_contains_statement_without_allergen_evidence
454
+ # SEVERITY: warning
455
+ # COMPLEXITY: medium
456
+ # DECLARATIVE_FRIENDLY: yes
457
+ if (($contains_statement_present > 0) && ($allergen_evidence_present == 0)) {
458
+ push @{$product_ref->{$data_quality_tags}}, "ca-contains-statement-without-allergen-evidence";
459
+ }
460
+ """.strip(),
461
+ evaluator=lambda product: (
462
+ _compare_values(product.get("contains_statement_present"), ">", 0)
463
+ and _compare_values(product.get("allergen_evidence_present"), "==", 0)
464
+ ),
465
+ ),
466
+ LegacyRule(
467
+ rule_name="ca_fop_required_but_symbol_missing",
468
+ tag="ca-fop-required-but-symbol-missing",
469
+ severity="error",
470
+ condition="fop_threshold_exceeded > 0 && fop_symbol_present == 0 && fop_exempt_proxy == 0 && product_is_prepackaged_proxy > 0",
471
+ duckdb_condition=(
472
+ "fop_threshold_exceeded > 0 AND fop_symbol_present == 0 "
473
+ "AND fop_exempt_proxy == 0 AND product_is_prepackaged_proxy > 0"
474
+ ),
475
+ complexity="medium",
476
+ declarative_friendly=True,
477
+ perl_logic="""
478
+ # RULE_NAME: ca_fop_required_but_symbol_missing
479
+ # SEVERITY: error
480
+ # COMPLEXITY: medium
481
+ # DECLARATIVE_FRIENDLY: yes
482
+ if (($fop_threshold_exceeded > 0) && ($fop_symbol_present == 0) && ($fop_exempt_proxy == 0) && ($product_is_prepackaged_proxy > 0)) {
483
+ push @{$product_ref->{$data_quality_tags}}, "ca-fop-required-but-symbol-missing";
484
+ }
485
+ """.strip(),
486
+ evaluator=lambda product: (
487
+ _compare_values(product.get("fop_threshold_exceeded"), ">", 0)
488
+ and _compare_values(product.get("fop_symbol_present"), "==", 0)
489
+ and _compare_values(product.get("fop_exempt_proxy"), "==", 0)
490
+ and _compare_values(product.get("product_is_prepackaged_proxy"), ">", 0)
491
+ ),
492
+ ),
493
+ LegacyRule(
494
+ rule_name="ca_fop_symbol_present_but_not_required",
495
+ tag="ca-fop-symbol-present-but-not-required",
496
+ severity="warning",
497
+ condition="fop_symbol_present > 0 && fop_threshold_exceeded == 0 && fop_exempt_proxy == 0 && product_is_prepackaged_proxy > 0",
498
+ duckdb_condition=(
499
+ "fop_symbol_present > 0 AND fop_threshold_exceeded == 0 "
500
+ "AND fop_exempt_proxy == 0 AND product_is_prepackaged_proxy > 0"
501
+ ),
502
+ complexity="medium",
503
+ declarative_friendly=True,
504
+ perl_logic="""
505
+ # RULE_NAME: ca_fop_symbol_present_but_not_required
506
+ # SEVERITY: warning
507
+ # COMPLEXITY: medium
508
+ # DECLARATIVE_FRIENDLY: yes
509
+ if (($fop_symbol_present > 0) && ($fop_threshold_exceeded == 0) && ($fop_exempt_proxy == 0) && ($product_is_prepackaged_proxy > 0)) {
510
+ push @{$product_ref->{$data_quality_tags}}, "ca-fop-symbol-present-but-not-required";
511
+ }
512
+ """.strip(),
513
+ evaluator=lambda product: (
514
+ _compare_values(product.get("fop_symbol_present"), ">", 0)
515
+ and _compare_values(product.get("fop_threshold_exceeded"), "==", 0)
516
+ and _compare_values(product.get("fop_exempt_proxy"), "==", 0)
517
+ and _compare_values(product.get("product_is_prepackaged_proxy"), ">", 0)
518
+ ),
519
+ ),
520
+ LegacyRule(
521
+ rule_name="ca_fop_symbol_present_on_exempt_product",
522
+ tag="ca-fop-symbol-present-on-exempt-product",
523
+ severity="warning",
524
+ condition="fop_symbol_present > 0 && fop_exempt_proxy > 0 && product_is_prepackaged_proxy > 0",
525
+ duckdb_condition="fop_symbol_present > 0 AND fop_exempt_proxy > 0 AND product_is_prepackaged_proxy > 0",
526
+ complexity="medium",
527
+ declarative_friendly=True,
528
+ perl_logic="""
529
+ # RULE_NAME: ca_fop_symbol_present_on_exempt_product
530
+ # SEVERITY: warning
531
+ # COMPLEXITY: medium
532
+ # DECLARATIVE_FRIENDLY: yes
533
+ if (($fop_symbol_present > 0) && ($fop_exempt_proxy > 0) && ($product_is_prepackaged_proxy > 0)) {
534
+ push @{$product_ref->{$data_quality_tags}}, "ca-fop-symbol-present-on-exempt-product";
535
+ }
536
+ """.strip(),
537
+ evaluator=lambda product: (
538
+ _compare_values(product.get("fop_symbol_present"), ">", 0)
539
+ and _compare_values(product.get("fop_exempt_proxy"), ">", 0)
540
+ and _compare_values(product.get("product_is_prepackaged_proxy"), ">", 0)
541
+ ),
542
+ ),
543
+ ]
544
+
545
+
546
+ RULE_FILES_DIR = Path(__file__).resolve().parent / "rules"
547
+
548
+
549
+ def load_rule_snippets_from_directory(rules_dir: Path = RULE_FILES_DIR) -> List[str]:
550
+ snippets: List[str] = []
551
+ for file_path in sorted(rules_dir.glob("*.pl")):
552
+ content = file_path.read_text(encoding="utf-8").lstrip("\ufeff").strip()
553
+ if content:
554
+ snippets.append(content)
555
+ if not snippets:
556
+ raise ValueError(f"No Perl rule files found in {rules_dir}")
557
+ return snippets
558
+
559
+
560
+ def get_perl_rule_snippets(
561
+ rules: Sequence[LegacyRule] = LEGACY_RULES,
562
+ rules_dir: Path | None = None,
563
+ ) -> List[str]:
564
+ if rules_dir is not None:
565
+ return load_rule_snippets_from_directory(Path(rules_dir))
566
+ return [rule.perl_logic for rule in rules]
567
+
568
+
569
+ def get_legacy_rule_map(rules: Sequence[LegacyRule] = LEGACY_RULES) -> Dict[str, LegacyRule]:
570
+ return {rule.rule_name: rule for rule in rules}
571
+
572
+
573
+ def run_perl_checks(products: Sequence[Product], rules: Sequence[LegacyRule] = LEGACY_RULES) -> Dict[str, Dict[str, object]]:
574
+ """Run simulated Perl checks and return per-product and per-rule outputs."""
575
+ per_product_tags: Dict[str, List[str]] = {}
576
+ per_rule_products: Dict[str, Set[str]] = {rule.rule_name: set() for rule in rules}
577
+
578
+ for product in products:
579
+ product_id = str(product.get("product_id"))
580
+ emitted_tags: List[str] = []
581
+ for rule in rules:
582
+ if rule.evaluator(product):
583
+ emitted_tags.append(rule.tag)
584
+ per_rule_products[rule.rule_name].add(product_id)
585
+ per_product_tags[product_id] = emitted_tags
586
+
587
+ return {
588
+ "per_product": per_product_tags,
589
+ "per_rule": {name: sorted(ids) for name, ids in per_rule_products.items()},
590
+ }
OFF_DataQuality/perl_checks/rules/01_energy_kcal_vs_kj.pl ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # RULE_NAME: energy_kcal_vs_kj
2
+ # SEVERITY: error
3
+ # COMPLEXITY: simple
4
+ # DECLARATIVE_FRIENDLY: yes
5
+ if ($energy_kcal > $energy_kj) {
6
+ push @{$product_ref->{$data_quality_tags}}, "energy-value-in-kcal-greater-than-in-kj";
7
+ }
OFF_DataQuality/perl_checks/rules/02_energy_kj_mismatch_low.pl ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # RULE_NAME: energy_kj_mismatch_low
2
+ # SEVERITY: error
3
+ # COMPLEXITY: intricate
4
+ # DECLARATIVE_FRIENDLY: no
5
+ if ($energy_kj < (3.7 * $energy_kcal - 2)) {
6
+ push @{$product_ref->{$data_quality_tags}}, "energy-value-in-kcal-does-not-match-value-in-kj-low";
7
+ }
OFF_DataQuality/perl_checks/rules/03_energy_kj_mismatch_high.pl ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # RULE_NAME: energy_kj_mismatch_high
2
+ # SEVERITY: error
3
+ # COMPLEXITY: intricate
4
+ # DECLARATIVE_FRIENDLY: no
5
+ if ($energy_kj > (4.7 * $energy_kcal + 2)) {
6
+ push @{$product_ref->{$data_quality_tags}}, "energy-value-in-kcal-does-not-match-value-in-kj-high";
7
+ }
OFF_DataQuality/perl_checks/rules/04_energy_kj_over_3911.pl ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # RULE_NAME: energy_kj_over_3911
2
+ # SEVERITY: error
3
+ # COMPLEXITY: simple
4
+ # DECLARATIVE_FRIENDLY: yes
5
+ if ($energy_kj > 3911) {
6
+ push @{$product_ref->{$data_quality_tags}}, "value-over-3911-energy";
7
+ }
OFF_DataQuality/perl_checks/rules/05_saturated_fat_vs_fat.pl ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # RULE_NAME: saturated_fat_vs_fat
2
+ # SEVERITY: error
3
+ # COMPLEXITY: simple
4
+ # DECLARATIVE_FRIENDLY: yes
5
+ if ($saturated_fat > (1 * $fat + 0.001)) {
6
+ push @{$product_ref->{$data_quality_tags}}, "saturated-fat-greater-than-fat";
7
+ }
OFF_DataQuality/perl_checks/rules/06_sugars_plus_starch_vs_carbohydrates.pl ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # RULE_NAME: sugars_plus_starch_vs_carbohydrates
2
+ # SEVERITY: error
3
+ # COMPLEXITY: medium
4
+ # DECLARATIVE_FRIENDLY: yes
5
+ if (($sugars + $starch) > ($carbohydrates + 0.001)) {
6
+ push @{$product_ref->{$data_quality_tags}}, "sugars-plus-starch-greater-than-carbohydrates";
7
+ }
OFF_DataQuality/perl_checks/rules/07_fat_over_105g.pl ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # RULE_NAME: fat_over_105g
2
+ # SEVERITY: warning
3
+ # COMPLEXITY: simple
4
+ # DECLARATIVE_FRIENDLY: yes
5
+ if ($fat > 105) {
6
+ push @{$product_ref->{$data_quality_tags}}, "fat-value-over-105g";
7
+ }
OFF_DataQuality/perl_checks/rules/08_saturated_fat_over_105g.pl ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # RULE_NAME: saturated_fat_over_105g
2
+ # SEVERITY: warning
3
+ # COMPLEXITY: simple
4
+ # DECLARATIVE_FRIENDLY: yes
5
+ if ($saturated_fat > 105) {
6
+ push @{$product_ref->{$data_quality_tags}}, "saturated-fat-value-over-105g";
7
+ }
OFF_DataQuality/perl_checks/rules/09_carbohydrates_over_105g.pl ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # RULE_NAME: carbohydrates_over_105g
2
+ # SEVERITY: warning
3
+ # COMPLEXITY: simple
4
+ # DECLARATIVE_FRIENDLY: yes
5
+ if ($carbohydrates > 105) {
6
+ push @{$product_ref->{$data_quality_tags}}, "carbohydrates-value-over-105g";
7
+ }
OFF_DataQuality/perl_checks/rules/10_sugars_over_105g.pl ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # RULE_NAME: sugars_over_105g
2
+ # SEVERITY: warning
3
+ # COMPLEXITY: simple
4
+ # DECLARATIVE_FRIENDLY: yes
5
+ if ($sugars > 105) {
6
+ push @{$product_ref->{$data_quality_tags}}, "sugars-value-over-105g";
7
+ }
OFF_DataQuality/perl_checks/rules/11_main_language_code_missing.pl ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # RULE_NAME: main_language_code_missing
2
+ # SEVERITY: bug
3
+ # COMPLEXITY: simple
4
+ # DECLARATIVE_FRIENDLY: yes
5
+ if (!defined $lc || $lc eq "") {
6
+ push @{$product_ref->{$data_quality_tags}}, "main-language-code-missing";
7
+ }
OFF_DataQuality/perl_checks/rules/12_main_language_missing.pl ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # RULE_NAME: main_language_missing
2
+ # SEVERITY: bug
3
+ # COMPLEXITY: simple
4
+ # DECLARATIVE_FRIENDLY: yes
5
+ if (!defined $lang || $lang eq "") {
6
+ push @{$product_ref->{$data_quality_tags}}, "main-language-missing";
7
+ }
OFF_DataQuality/perl_checks/rules/13_energy_kj_computed_mismatch_low.pl ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # RULE_NAME: energy_kj_computed_mismatch_low
2
+ # SEVERITY: error
3
+ # COMPLEXITY: intricate
4
+ # DECLARATIVE_FRIENDLY: no
5
+ if ($energy_kj_computed < (0.7 * $energy_kj - 5)) {
6
+ push @{$product_ref->{$data_quality_tags}}, "energy-value-in-kj-does-not-match-value-computed-from-other-nutrients-low";
7
+ }
OFF_DataQuality/perl_checks/rules/14_energy_kj_computed_mismatch_high.pl ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # RULE_NAME: energy_kj_computed_mismatch_high
2
+ # SEVERITY: error
3
+ # COMPLEXITY: intricate
4
+ # DECLARATIVE_FRIENDLY: no
5
+ if ($energy_kj_computed > (1.3 * $energy_kj + 5)) {
6
+ push @{$product_ref->{$data_quality_tags}}, "energy-value-in-kj-does-not-match-value-computed-from-other-nutrients-high";
7
+ }
OFF_DataQuality/perl_checks/rules/15_ca_allergen_evidence_missing_ingredients_text.pl ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # RULE_NAME: ca_allergen_evidence_missing_ingredients_text
2
+ # SEVERITY: warning
3
+ # COMPLEXITY: medium
4
+ # DECLARATIVE_FRIENDLY: yes
5
+ if (($allergen_evidence_present > 0) && ($ingredients_text_present == 0)) {
6
+ push @{$product_ref->{$data_quality_tags}}, "ca-allergen-evidence-but-missing-ingredients-text";
7
+ }
OFF_DataQuality/perl_checks/rules/16_ca_contains_statement_without_allergen_evidence.pl ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # RULE_NAME: ca_contains_statement_without_allergen_evidence
2
+ # SEVERITY: warning
3
+ # COMPLEXITY: medium
4
+ # DECLARATIVE_FRIENDLY: yes
5
+ if (($contains_statement_present > 0) && ($allergen_evidence_present == 0)) {
6
+ push @{$product_ref->{$data_quality_tags}}, "ca-contains-statement-without-allergen-evidence";
7
+ }
OFF_DataQuality/perl_checks/rules/17_ca_fop_required_but_symbol_missing.pl ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # RULE_NAME: ca_fop_required_but_symbol_missing
2
+ # SEVERITY: error
3
+ # COMPLEXITY: medium
4
+ # DECLARATIVE_FRIENDLY: yes
5
+ if (($fop_threshold_exceeded > 0) && ($fop_symbol_present == 0) && ($fop_exempt_proxy == 0) && ($product_is_prepackaged_proxy > 0)) {
6
+ push @{$product_ref->{$data_quality_tags}}, "ca-fop-required-but-symbol-missing";
7
+ }
OFF_DataQuality/perl_checks/rules/18_ca_fop_symbol_present_but_not_required.pl ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # RULE_NAME: ca_fop_symbol_present_but_not_required
2
+ # SEVERITY: warning
3
+ # COMPLEXITY: medium
4
+ # DECLARATIVE_FRIENDLY: yes
5
+ if (($fop_symbol_present > 0) && ($fop_threshold_exceeded == 0) && ($fop_exempt_proxy == 0) && ($product_is_prepackaged_proxy > 0)) {
6
+ push @{$product_ref->{$data_quality_tags}}, "ca-fop-symbol-present-but-not-required";
7
+ }
OFF_DataQuality/perl_checks/rules/19_ca_fop_symbol_present_on_exempt_product.pl ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # RULE_NAME: ca_fop_symbol_present_on_exempt_product
2
+ # SEVERITY: warning
3
+ # COMPLEXITY: medium
4
+ # DECLARATIVE_FRIENDLY: yes
5
+ if (($fop_symbol_present > 0) && ($fop_exempt_proxy > 0) && ($product_is_prepackaged_proxy > 0)) {
6
+ push @{$product_ref->{$data_quality_tags}}, "ca-fop-symbol-present-on-exempt-product";
7
+ }
OFF_DataQuality/pytest.ini ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ [pytest]
2
+ testpaths = tests
OFF_DataQuality/python_checks/__init__.py ADDED
File without changes
OFF_DataQuality/python_checks/generated_checks.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Runtime compiler for generated Python checks."""
2
+ from __future__ import annotations
3
+
4
+ from typing import Callable, Dict, List, Tuple
5
+
6
+
7
+ def compile_generated_checks(
8
+ converted_rules: List[Dict[str, object]],
9
+ ) -> Tuple[Dict[str, Callable[[Dict[str, object]], object]], Dict[str, Dict[str, object]]]:
10
+ """Compile generated Python snippets into callable checks."""
11
+ checks: Dict[str, Callable[[Dict[str, object]], object]] = {}
12
+ metadata: Dict[str, Dict[str, object]] = {}
13
+
14
+ for converted in converted_rules:
15
+ function_name = str(converted["function_name"])
16
+ rule_name = str(converted["rule_name"])
17
+ code = str(converted["python_code"])
18
+
19
+ namespace: Dict[str, object] = {}
20
+ exec(code, {}, namespace)
21
+ check_fn = namespace[function_name]
22
+ checks[rule_name] = check_fn
23
+ metadata[rule_name] = {
24
+ "function_name": function_name,
25
+ "python_code": code,
26
+ "llm_confidence": float(converted["llm_confidence"]),
27
+ "conversion_notes": converted["conversion_notes"],
28
+ "provider": converted.get("provider", "unknown"),
29
+ }
30
+ return checks, metadata
31
+
32
+
33
+ def render_generated_module(metadata: Dict[str, Dict[str, object]]) -> str:
34
+ """Return a readable module-like rendering of generated checks."""
35
+ code_blocks = [str(info["python_code"]).rstrip() for info in metadata.values()]
36
+ return "\n\n".join(code_blocks) + "\n"
OFF_DataQuality/requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ duckdb
2
+ streamlit
3
+ pandas
4
+ openai
5
+ pytest
6
+ plotly
7
+ dbt-duckdb
8
+ soda-duckdb
OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/dbt_project.yml ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ name: off_quality_declarative
2
+ version: '1.0'
3
+ config-version: 2
4
+ profile: off_quality_duckdb
5
+ model-paths: ['models']
6
+ test-paths: ['tests']
OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/macros/count_violations.sql ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% macro count_violations(condition_sql) %}
2
+ {% set q %}
3
+ select count(*) as violation_count
4
+ from {{ source('off_source', 'nutrition_table') }}
5
+ where {{ condition_sql }}
6
+ {% endset %}
7
+ {% set t = run_query(q) %}
8
+ {% if execute %}
9
+ {% set c = t.columns[0].values()[0] %}
10
+ {% do log('VIOLATION_COUNT=' ~ c, info=True) %}
11
+ {% endif %}
12
+ {% endmacro %}
OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/models/sources.yml ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ version: 2
2
+ sources:
3
+ - name: off_source
4
+ schema: main
5
+ tables:
6
+ - name: nutrition_table
OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/profiles.yml ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ off_quality_duckdb:
2
+ target: dev
3
+ outputs:
4
+ dev:
5
+ type: duckdb
6
+ path: 'results/declarative_runtime/dbt/dbt_runtime.db'
7
+ schema: main
8
+ threads: 1
OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/tests/ca_allergen_evidence_missing_ingredients_text.sql ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ SELECT product_id
2
+ FROM {{ source('off_source', 'nutrition_table') }}
3
+ WHERE allergen_evidence_present > 0.0 AND ingredients_text_present == 0.0
OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/tests/ca_contains_statement_without_allergen_evidence.sql ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ SELECT product_id
2
+ FROM {{ source('off_source', 'nutrition_table') }}
3
+ WHERE contains_statement_present > 0.0 AND allergen_evidence_present == 0.0
OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/tests/ca_fop_required_but_symbol_missing.sql ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ SELECT product_id
2
+ FROM {{ source('off_source', 'nutrition_table') }}
3
+ 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
OFF_DataQuality/results/declarative_runtime/dbt/dbt_project/tests/ca_fop_symbol_present_but_not_required.sql ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ SELECT product_id
2
+ FROM {{ source('off_source', 'nutrition_table') }}
3
+ 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