dataforge-07 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- dataforge/__init__.py +204 -0
- dataforge/__main__.py +5 -0
- dataforge/agent/__init__.py +16 -0
- dataforge/agent/providers.py +259 -0
- dataforge/agent/scratchpad.py +183 -0
- dataforge/agent/tool_actions.py +343 -0
- dataforge/bench/__init__.py +31 -0
- dataforge/bench/core.py +426 -0
- dataforge/bench/groq_client.py +386 -0
- dataforge/bench/methods.py +443 -0
- dataforge/bench/report.py +309 -0
- dataforge/bench/runner.py +247 -0
- dataforge/causal/__init__.py +21 -0
- dataforge/causal/dag.py +174 -0
- dataforge/causal/pc.py +232 -0
- dataforge/causal/root_cause.py +193 -0
- dataforge/cli/__init__.py +50 -0
- dataforge/cli/audit.py +70 -0
- dataforge/cli/bench.py +154 -0
- dataforge/cli/common.py +267 -0
- dataforge/cli/constraints.py +407 -0
- dataforge/cli/profile.py +147 -0
- dataforge/cli/release.py +166 -0
- dataforge/cli/repair.py +407 -0
- dataforge/cli/revert.py +139 -0
- dataforge/cli/watch.py +144 -0
- dataforge/datasets/__init__.py +25 -0
- dataforge/datasets/embedded/hospital/clean.csv +11 -0
- dataforge/datasets/embedded/hospital/dirty.csv +11 -0
- dataforge/datasets/real_world.py +290 -0
- dataforge/datasets/registry.py +103 -0
- dataforge/detectors/__init__.py +80 -0
- dataforge/detectors/base.py +145 -0
- dataforge/detectors/decimal_shift.py +166 -0
- dataforge/detectors/fd_violation.py +157 -0
- dataforge/detectors/type_mismatch.py +173 -0
- dataforge/engine/__init__.py +39 -0
- dataforge/engine/repair.py +905 -0
- dataforge/env/__init__.py +22 -0
- dataforge/env/environment.py +883 -0
- dataforge/env/observation.py +61 -0
- dataforge/env/openenv_core.py +161 -0
- dataforge/env/reward.py +128 -0
- dataforge/env/server.py +176 -0
- dataforge/evaluation_contract.py +76 -0
- dataforge/fixtures/hospital_10rows.csv +11 -0
- dataforge/fixtures/hospital_schema.yaml +17 -0
- dataforge/http/__init__.py +1 -0
- dataforge/http/problem.py +103 -0
- dataforge/integrations/__init__.py +1 -0
- dataforge/integrations/dbt.py +164 -0
- dataforge/observability.py +76 -0
- dataforge/py.typed +1 -0
- dataforge/release/__init__.py +1 -0
- dataforge/release/doctor.py +367 -0
- dataforge/release/full_vision.py +702 -0
- dataforge/release/gate.py +861 -0
- dataforge/release/playground_check.py +411 -0
- dataforge/repair_contract.py +468 -0
- dataforge/repairers/__init__.py +88 -0
- dataforge/repairers/base.py +77 -0
- dataforge/repairers/decimal_shift.py +43 -0
- dataforge/repairers/fd_violation.py +225 -0
- dataforge/repairers/type_mismatch.py +73 -0
- dataforge/safety/__init__.py +5 -0
- dataforge/safety/adversarial/attack_01_phone_pii.yaml +8 -0
- dataforge/safety/adversarial/attack_02_phone_pii.yaml +8 -0
- dataforge/safety/adversarial/attack_03_phone_pii.yaml +8 -0
- dataforge/safety/adversarial/attack_04_phone_pii.yaml +8 -0
- dataforge/safety/adversarial/attack_05_phone_pii.yaml +8 -0
- dataforge/safety/adversarial/attack_06_phone_pii.yaml +8 -0
- dataforge/safety/adversarial/attack_07_phone_pii.yaml +8 -0
- dataforge/safety/adversarial/attack_08_phone_pii.yaml +8 -0
- dataforge/safety/adversarial/attack_09_phone_pii.yaml +8 -0
- dataforge/safety/adversarial/attack_10_phone_pii.yaml +8 -0
- dataforge/safety/adversarial/attack_11_ssn_pii.yaml +8 -0
- dataforge/safety/adversarial/attack_12_ssn_pii.yaml +8 -0
- dataforge/safety/adversarial/attack_13_ssn_pii.yaml +8 -0
- dataforge/safety/adversarial/attack_14_ssn_pii.yaml +8 -0
- dataforge/safety/adversarial/attack_15_ssn_pii.yaml +8 -0
- dataforge/safety/adversarial/attack_16_ssn_pii.yaml +8 -0
- dataforge/safety/adversarial/attack_17_ssn_pii.yaml +8 -0
- dataforge/safety/adversarial/attack_18_ssn_pii.yaml +8 -0
- dataforge/safety/adversarial/attack_19_ssn_pii.yaml +8 -0
- dataforge/safety/adversarial/attack_20_ssn_pii.yaml +8 -0
- dataforge/safety/adversarial/attack_21_email_pii.yaml +8 -0
- dataforge/safety/adversarial/attack_22_email_pii.yaml +8 -0
- dataforge/safety/adversarial/attack_23_email_pii.yaml +8 -0
- dataforge/safety/adversarial/attack_24_email_pii.yaml +8 -0
- dataforge/safety/adversarial/attack_25_email_pii.yaml +8 -0
- dataforge/safety/adversarial/attack_26_email_pii.yaml +8 -0
- dataforge/safety/adversarial/attack_27_email_pii.yaml +8 -0
- dataforge/safety/adversarial/attack_28_email_pii.yaml +8 -0
- dataforge/safety/adversarial/attack_29_email_pii.yaml +8 -0
- dataforge/safety/adversarial/attack_30_email_pii.yaml +8 -0
- dataforge/safety/adversarial/attack_31_row_delete.yaml +7 -0
- dataforge/safety/adversarial/attack_32_row_delete.yaml +8 -0
- dataforge/safety/adversarial/attack_33_row_delete.yaml +7 -0
- dataforge/safety/adversarial/attack_34_row_delete.yaml +7 -0
- dataforge/safety/adversarial/attack_35_row_delete.yaml +7 -0
- dataforge/safety/adversarial/attack_36_row_delete.yaml +11 -0
- dataforge/safety/adversarial/attack_37_row_delete.yaml +7 -0
- dataforge/safety/adversarial/attack_38_row_delete.yaml +7 -0
- dataforge/safety/adversarial/attack_39_row_delete.yaml +8 -0
- dataforge/safety/adversarial/attack_40_row_delete.yaml +7 -0
- dataforge/safety/adversarial/attack_41_row_delete.yaml +7 -0
- dataforge/safety/adversarial/attack_42_row_delete.yaml +7 -0
- dataforge/safety/adversarial/attack_43_row_delete.yaml +7 -0
- dataforge/safety/adversarial/attack_44_row_delete.yaml +7 -0
- dataforge/safety/adversarial/attack_45_row_delete.yaml +8 -0
- dataforge/safety/adversarial/attack_46_row_delete.yaml +8 -0
- dataforge/safety/adversarial/attack_47_row_delete.yaml +7 -0
- dataforge/safety/adversarial/attack_48_row_delete.yaml +7 -0
- dataforge/safety/adversarial/attack_49_row_delete.yaml +8 -0
- dataforge/safety/adversarial/attack_50_row_delete.yaml +7 -0
- dataforge/safety/constitution.py +307 -0
- dataforge/safety/constitutions/default.yaml +40 -0
- dataforge/safety/filter.py +134 -0
- dataforge/schema_inference.py +620 -0
- dataforge/stores/__init__.py +46 -0
- dataforge/stores/base.py +73 -0
- dataforge/stores/cloud.py +78 -0
- dataforge/stores/csv.py +94 -0
- dataforge/stores/duckdb.py +313 -0
- dataforge/stores/patch_plan.py +178 -0
- dataforge/stores/registry.py +82 -0
- dataforge/stores/repair.py +121 -0
- dataforge/stores/revert.py +22 -0
- dataforge/stores/sql.py +27 -0
- dataforge/table.py +228 -0
- dataforge/transactions/__init__.py +34 -0
- dataforge/transactions/files.py +96 -0
- dataforge/transactions/log.py +613 -0
- dataforge/transactions/revert.py +102 -0
- dataforge/transactions/txn.py +104 -0
- dataforge/ui/__init__.py +1 -0
- dataforge/ui/profile_view.py +136 -0
- dataforge/ui/repair_diff.py +91 -0
- dataforge/verifier/__init__.py +55 -0
- dataforge/verifier/constraint_ir.py +155 -0
- dataforge/verifier/explain.py +47 -0
- dataforge/verifier/gate.py +5 -0
- dataforge/verifier/schema.py +111 -0
- dataforge/verifier/smt.py +433 -0
- dataforge_07-0.1.0.dist-info/METADATA +436 -0
- dataforge_07-0.1.0.dist-info/RECORD +150 -0
- dataforge_07-0.1.0.dist-info/WHEEL +5 -0
- dataforge_07-0.1.0.dist-info/entry_points.txt +3 -0
- dataforge_07-0.1.0.dist-info/licenses/LICENSE +176 -0
- dataforge_07-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,468 @@
|
|
|
1
|
+
"""Canonical prompt, parsing, and scoring contract for DataForge repairs."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import re
|
|
7
|
+
from collections import Counter, OrderedDict
|
|
8
|
+
from collections.abc import Iterable, Mapping, Sequence
|
|
9
|
+
from typing import Any, Literal, Protocol
|
|
10
|
+
|
|
11
|
+
from pydantic import BaseModel, Field, ValidationError, model_validator
|
|
12
|
+
|
|
13
|
+
CONTRACT_VERSION_V1 = "repair_contract_v1"
|
|
14
|
+
CONTRACT_VERSION_V2 = "repair_contract_v2"
|
|
15
|
+
CONTRACT_VERSION = CONTRACT_VERSION_V2
|
|
16
|
+
|
|
17
|
+
SYSTEM_PROMPT = (
|
|
18
|
+
"You repair tabular data by proposing exact cell replacements. "
|
|
19
|
+
"Rows must be absolute row ids from valid_rows and columns must exactly match one of "
|
|
20
|
+
"the allowed_columns values. "
|
|
21
|
+
"Use only the provided dirty target rows and optional context rows. "
|
|
22
|
+
"Return strict JSON only in this object shape: "
|
|
23
|
+
'{"action":"submit_repairs","repairs":[{"row":0,"column":"Column",'
|
|
24
|
+
'"new_value":"value","reason":"why"}]}. '
|
|
25
|
+
'Use {"action":"finish","repairs":[]} when no cells should be changed. '
|
|
26
|
+
"Do not wrap the JSON in markdown code fences."
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
_JSON_FENCE_RE = re.compile(r"```(?:json)?\s*\n?(.*?)\n?\s*```", re.DOTALL)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class RepairLike(Protocol):
|
|
33
|
+
"""Minimal shape shared by repair objects across DataForge packages."""
|
|
34
|
+
|
|
35
|
+
@property
|
|
36
|
+
def row(self) -> int: ...
|
|
37
|
+
|
|
38
|
+
@property
|
|
39
|
+
def column(self) -> str: ...
|
|
40
|
+
|
|
41
|
+
@property
|
|
42
|
+
def new_value(self) -> str: ...
|
|
43
|
+
|
|
44
|
+
@property
|
|
45
|
+
def reason(self) -> str: ...
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class TruthLike(Protocol):
|
|
49
|
+
"""Minimal shape shared by ground-truth cell objects across packages."""
|
|
50
|
+
|
|
51
|
+
@property
|
|
52
|
+
def row(self) -> int: ...
|
|
53
|
+
|
|
54
|
+
@property
|
|
55
|
+
def column(self) -> str: ...
|
|
56
|
+
|
|
57
|
+
@property
|
|
58
|
+
def clean_value(self) -> str: ...
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class RepairFix(BaseModel):
|
|
62
|
+
"""One exact cell replacement proposed by a repair agent."""
|
|
63
|
+
|
|
64
|
+
row: int = Field(ge=0)
|
|
65
|
+
column: str = Field(min_length=1)
|
|
66
|
+
new_value: str
|
|
67
|
+
reason: str = Field(default="repair proposal", min_length=1)
|
|
68
|
+
|
|
69
|
+
model_config = {"frozen": True}
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class RepairAction(BaseModel):
|
|
73
|
+
"""The only JSON action shape accepted by the repair contract."""
|
|
74
|
+
|
|
75
|
+
action: Literal["submit_repairs", "finish"]
|
|
76
|
+
repairs: list[RepairFix] = Field(default_factory=list)
|
|
77
|
+
|
|
78
|
+
model_config = {"frozen": True}
|
|
79
|
+
|
|
80
|
+
@model_validator(mode="after")
|
|
81
|
+
def _finish_must_be_empty(self) -> RepairAction:
|
|
82
|
+
if self.action == "finish" and self.repairs:
|
|
83
|
+
raise ValueError("finish actions must not include repairs")
|
|
84
|
+
return self
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
class RepairParseResult(BaseModel):
|
|
88
|
+
"""Parsed repair action plus diagnostics suitable for release gates."""
|
|
89
|
+
|
|
90
|
+
ok: bool
|
|
91
|
+
action: RepairAction | None = None
|
|
92
|
+
error_kind: (
|
|
93
|
+
Literal[
|
|
94
|
+
"parse_failure",
|
|
95
|
+
"truncated_json",
|
|
96
|
+
"schema_error",
|
|
97
|
+
"invalid_column",
|
|
98
|
+
"invalid_row",
|
|
99
|
+
]
|
|
100
|
+
| None
|
|
101
|
+
) = None
|
|
102
|
+
error_message: str | None = None
|
|
103
|
+
diagnostics: dict[str, int | str | bool] = Field(default_factory=dict)
|
|
104
|
+
|
|
105
|
+
model_config = {"frozen": True}
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
class RepairScore(BaseModel):
|
|
109
|
+
"""Exact-match cell repair metrics."""
|
|
110
|
+
|
|
111
|
+
tp: int = Field(ge=0)
|
|
112
|
+
fp: int = Field(ge=0)
|
|
113
|
+
fn: int = Field(ge=0)
|
|
114
|
+
precision: float = Field(ge=0.0, le=1.0)
|
|
115
|
+
recall: float = Field(ge=0.0, le=1.0)
|
|
116
|
+
f1: float = Field(ge=0.0, le=1.0)
|
|
117
|
+
|
|
118
|
+
model_config = {"frozen": True}
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _as_jsonable_rows(rows: Sequence[Mapping[str, Any]]) -> list[dict[str, str]]:
|
|
122
|
+
"""Return rows as stable string-valued mappings while preserving ``_row``."""
|
|
123
|
+
rendered: list[dict[str, str]] = []
|
|
124
|
+
for row in rows:
|
|
125
|
+
rendered_row: dict[str, str] = {}
|
|
126
|
+
for key, value in row.items():
|
|
127
|
+
rendered_row[str(key)] = str(value)
|
|
128
|
+
rendered.append(rendered_row)
|
|
129
|
+
return rendered
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _valid_rows_from_target_rows(target_rows: Sequence[Mapping[str, Any]]) -> list[int]:
|
|
133
|
+
"""Return absolute row ids from target rows, falling back to local ids for legacy rows."""
|
|
134
|
+
valid_rows: list[int] = []
|
|
135
|
+
for fallback_row, row in enumerate(target_rows):
|
|
136
|
+
raw_row = row.get("_row", fallback_row)
|
|
137
|
+
valid_rows.append(int(str(raw_row)))
|
|
138
|
+
return valid_rows
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def build_repair_user_payload(
|
|
142
|
+
*,
|
|
143
|
+
schema_summary: Mapping[str, Any],
|
|
144
|
+
target_rows: Sequence[Mapping[str, Any]],
|
|
145
|
+
context_rows: Sequence[Mapping[str, Any]] = (),
|
|
146
|
+
allowed_columns: Sequence[str],
|
|
147
|
+
valid_rows: Sequence[int] | None = None,
|
|
148
|
+
label_source: str | None = None,
|
|
149
|
+
dataset_note: str | None = None,
|
|
150
|
+
metadata: Mapping[str, Any] | None = None,
|
|
151
|
+
contract_version: str = CONTRACT_VERSION,
|
|
152
|
+
) -> dict[str, Any]:
|
|
153
|
+
"""Build the canonical user payload for repair SFT and evaluation."""
|
|
154
|
+
payload: dict[str, Any] = {
|
|
155
|
+
"contract_version": contract_version,
|
|
156
|
+
"schema_summary": dict(schema_summary),
|
|
157
|
+
"allowed_columns": list(allowed_columns),
|
|
158
|
+
"valid_rows": list(valid_rows)
|
|
159
|
+
if valid_rows is not None
|
|
160
|
+
else _valid_rows_from_target_rows(target_rows),
|
|
161
|
+
"target_rows": _as_jsonable_rows(target_rows),
|
|
162
|
+
"context_rows": _as_jsonable_rows(context_rows),
|
|
163
|
+
}
|
|
164
|
+
if label_source is not None:
|
|
165
|
+
payload["label_source"] = label_source
|
|
166
|
+
if dataset_note is not None:
|
|
167
|
+
payload["dataset_note"] = dataset_note
|
|
168
|
+
if metadata is not None:
|
|
169
|
+
payload["metadata"] = dict(metadata)
|
|
170
|
+
return payload
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def render_repair_messages(
|
|
174
|
+
*,
|
|
175
|
+
schema_summary: Mapping[str, Any],
|
|
176
|
+
target_rows: Sequence[Mapping[str, Any]],
|
|
177
|
+
allowed_columns: Sequence[str],
|
|
178
|
+
valid_rows: Sequence[int] | None = None,
|
|
179
|
+
context_rows: Sequence[Mapping[str, Any]] = (),
|
|
180
|
+
label_source: str | None = None,
|
|
181
|
+
dataset_note: str | None = None,
|
|
182
|
+
metadata: Mapping[str, Any] | None = None,
|
|
183
|
+
repairs: Sequence[RepairLike] | None = None,
|
|
184
|
+
contract_version: str = CONTRACT_VERSION,
|
|
185
|
+
) -> list[dict[str, str]]:
|
|
186
|
+
"""Render canonical chat messages for a repair task.
|
|
187
|
+
|
|
188
|
+
When ``repairs`` is ``None``, only system and user messages are returned.
|
|
189
|
+
When repairs are provided, an assistant message is appended for SFT.
|
|
190
|
+
"""
|
|
191
|
+
messages = [
|
|
192
|
+
{"role": "system", "content": SYSTEM_PROMPT},
|
|
193
|
+
{
|
|
194
|
+
"role": "user",
|
|
195
|
+
"content": json.dumps(
|
|
196
|
+
build_repair_user_payload(
|
|
197
|
+
schema_summary=schema_summary,
|
|
198
|
+
target_rows=target_rows,
|
|
199
|
+
context_rows=context_rows,
|
|
200
|
+
allowed_columns=allowed_columns,
|
|
201
|
+
valid_rows=valid_rows,
|
|
202
|
+
label_source=label_source,
|
|
203
|
+
dataset_note=dataset_note,
|
|
204
|
+
metadata=metadata,
|
|
205
|
+
contract_version=contract_version,
|
|
206
|
+
),
|
|
207
|
+
sort_keys=True,
|
|
208
|
+
separators=(",", ":"),
|
|
209
|
+
),
|
|
210
|
+
},
|
|
211
|
+
]
|
|
212
|
+
if repairs is not None:
|
|
213
|
+
repair_fixes = [
|
|
214
|
+
RepairFix(
|
|
215
|
+
row=repair.row,
|
|
216
|
+
column=repair.column,
|
|
217
|
+
new_value=repair.new_value,
|
|
218
|
+
reason=repair.reason,
|
|
219
|
+
)
|
|
220
|
+
for repair in repairs
|
|
221
|
+
]
|
|
222
|
+
messages.append(
|
|
223
|
+
{
|
|
224
|
+
"role": "assistant",
|
|
225
|
+
"content": json.dumps(
|
|
226
|
+
RepairAction(
|
|
227
|
+
action="submit_repairs" if repair_fixes else "finish",
|
|
228
|
+
repairs=repair_fixes,
|
|
229
|
+
).model_dump(mode="json"),
|
|
230
|
+
sort_keys=True,
|
|
231
|
+
separators=(",", ":"),
|
|
232
|
+
),
|
|
233
|
+
}
|
|
234
|
+
)
|
|
235
|
+
return messages
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def _strip_fence(text: str) -> str:
|
|
239
|
+
"""Strip a single markdown JSON fence if the model returned one."""
|
|
240
|
+
stripped = text.strip()
|
|
241
|
+
match = _JSON_FENCE_RE.search(stripped)
|
|
242
|
+
return match.group(1).strip() if match else stripped
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def extract_json_payload(text: str) -> object:
|
|
246
|
+
"""Extract the first complete JSON object or array from model text."""
|
|
247
|
+
clean_text = _strip_fence(text)
|
|
248
|
+
decoder = json.JSONDecoder()
|
|
249
|
+
saw_start = False
|
|
250
|
+
for offset, char in enumerate(clean_text):
|
|
251
|
+
if char not in "[{":
|
|
252
|
+
continue
|
|
253
|
+
saw_start = True
|
|
254
|
+
try:
|
|
255
|
+
payload, _end = decoder.raw_decode(clean_text[offset:])
|
|
256
|
+
except json.JSONDecodeError:
|
|
257
|
+
continue
|
|
258
|
+
if isinstance(payload, dict | list):
|
|
259
|
+
return payload
|
|
260
|
+
if saw_start:
|
|
261
|
+
raise ValueError("truncated_json")
|
|
262
|
+
raise ValueError("parse_failure")
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def _schema_case_error(column: str, allowed_columns: set[str]) -> bool:
|
|
266
|
+
"""Return whether ``column`` only differs from an allowed column by case."""
|
|
267
|
+
return column.lower() in {allowed.lower() for allowed in allowed_columns}
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def parse_repair_action(
|
|
271
|
+
text: str,
|
|
272
|
+
*,
|
|
273
|
+
allowed_columns: Iterable[str] | None = None,
|
|
274
|
+
valid_rows: Iterable[int] | None = None,
|
|
275
|
+
require_explicit_action: bool = False,
|
|
276
|
+
) -> RepairParseResult:
|
|
277
|
+
"""Parse model text into a canonical repair action without raising.
|
|
278
|
+
|
|
279
|
+
By default this remains permissive enough to read legacy v1 artifacts. Pass
|
|
280
|
+
``allowed_columns``, ``valid_rows``, and ``require_explicit_action=True`` for
|
|
281
|
+
the v2 release-gate contract.
|
|
282
|
+
"""
|
|
283
|
+
try:
|
|
284
|
+
payload = extract_json_payload(text)
|
|
285
|
+
except ValueError as exc:
|
|
286
|
+
if str(exc) == "truncated_json":
|
|
287
|
+
return RepairParseResult(
|
|
288
|
+
ok=False,
|
|
289
|
+
error_kind="truncated_json",
|
|
290
|
+
error_message=str(exc),
|
|
291
|
+
)
|
|
292
|
+
return RepairParseResult(ok=False, error_kind="parse_failure", error_message=str(exc))
|
|
293
|
+
|
|
294
|
+
diagnostics: dict[str, int | str | bool] = {}
|
|
295
|
+
if isinstance(payload, list):
|
|
296
|
+
if require_explicit_action:
|
|
297
|
+
return RepairParseResult(
|
|
298
|
+
ok=False,
|
|
299
|
+
error_kind="schema_error",
|
|
300
|
+
error_message="repair payload must include an explicit action",
|
|
301
|
+
)
|
|
302
|
+
payload = {"action": "submit_repairs", "repairs": payload}
|
|
303
|
+
if not isinstance(payload, dict):
|
|
304
|
+
return RepairParseResult(
|
|
305
|
+
ok=False,
|
|
306
|
+
error_kind="schema_error",
|
|
307
|
+
error_message="repair payload must be a JSON object or array",
|
|
308
|
+
)
|
|
309
|
+
if "repairs" in payload and "action" not in payload:
|
|
310
|
+
if require_explicit_action:
|
|
311
|
+
return RepairParseResult(
|
|
312
|
+
ok=False,
|
|
313
|
+
error_kind="schema_error",
|
|
314
|
+
error_message="repair payload must include an explicit action",
|
|
315
|
+
)
|
|
316
|
+
payload = {**payload, "action": "submit_repairs"}
|
|
317
|
+
try:
|
|
318
|
+
action = RepairAction.model_validate(payload)
|
|
319
|
+
except ValidationError as exc:
|
|
320
|
+
return RepairParseResult(ok=False, error_kind="schema_error", error_message=str(exc))
|
|
321
|
+
|
|
322
|
+
normalized_repairs = normalize_fixes(action.repairs)
|
|
323
|
+
duplicate_count = len(action.repairs) - len(normalized_repairs)
|
|
324
|
+
if duplicate_count:
|
|
325
|
+
diagnostics["duplicate_cell_count"] = duplicate_count
|
|
326
|
+
action = RepairAction(action=action.action, repairs=normalized_repairs)
|
|
327
|
+
|
|
328
|
+
if allowed_columns is not None:
|
|
329
|
+
allowed = set(allowed_columns)
|
|
330
|
+
for repair in action.repairs:
|
|
331
|
+
if repair.column in allowed:
|
|
332
|
+
continue
|
|
333
|
+
diagnostics["invalid_column"] = repair.column
|
|
334
|
+
diagnostics["schema_case_error"] = _schema_case_error(repair.column, allowed)
|
|
335
|
+
return RepairParseResult(
|
|
336
|
+
ok=False,
|
|
337
|
+
error_kind="invalid_column",
|
|
338
|
+
error_message=f"column {repair.column!r} is not in allowed_columns",
|
|
339
|
+
diagnostics=diagnostics,
|
|
340
|
+
)
|
|
341
|
+
|
|
342
|
+
if valid_rows is not None:
|
|
343
|
+
rows = {int(row) for row in valid_rows}
|
|
344
|
+
for repair in action.repairs:
|
|
345
|
+
if repair.row in rows:
|
|
346
|
+
continue
|
|
347
|
+
diagnostics["invalid_row"] = repair.row
|
|
348
|
+
return RepairParseResult(
|
|
349
|
+
ok=False,
|
|
350
|
+
error_kind="invalid_row",
|
|
351
|
+
error_message=f"row {repair.row} is not in valid_rows",
|
|
352
|
+
diagnostics=diagnostics,
|
|
353
|
+
)
|
|
354
|
+
|
|
355
|
+
return RepairParseResult(ok=True, action=action, diagnostics=diagnostics)
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
def normalize_fixes(fixes: Iterable[RepairLike]) -> list[RepairFix]:
|
|
359
|
+
"""Collapse repairs to one final prediction per cell using last-write-wins."""
|
|
360
|
+
by_cell: OrderedDict[tuple[int, str], RepairFix] = OrderedDict()
|
|
361
|
+
for fix in fixes:
|
|
362
|
+
normalized = RepairFix(
|
|
363
|
+
row=fix.row,
|
|
364
|
+
column=fix.column,
|
|
365
|
+
new_value=fix.new_value,
|
|
366
|
+
reason=fix.reason,
|
|
367
|
+
)
|
|
368
|
+
key = (normalized.row, normalized.column)
|
|
369
|
+
if key in by_cell:
|
|
370
|
+
del by_cell[key]
|
|
371
|
+
by_cell[key] = normalized
|
|
372
|
+
return list(by_cell.values())
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
def canonicalize_cell_value(value: str) -> str:
|
|
376
|
+
"""Return a diagnostics-only canonical value for fuzzy F1 reporting."""
|
|
377
|
+
return " ".join(str(value).strip().casefold().split())
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
def _strict_cell_value(value: str) -> str:
|
|
381
|
+
"""Return the official exact-match value normalization."""
|
|
382
|
+
return str(value).rstrip()
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
def score_repair_fixes(
|
|
386
|
+
ground_truth: Iterable[TruthLike],
|
|
387
|
+
fixes: Iterable[RepairLike],
|
|
388
|
+
*,
|
|
389
|
+
canonicalize_values: bool = False,
|
|
390
|
+
) -> RepairScore:
|
|
391
|
+
"""Score repairs by exact row, column, and string value match."""
|
|
392
|
+
normalized = normalize_fixes(fixes)
|
|
393
|
+
value_fn = canonicalize_cell_value if canonicalize_values else _strict_cell_value
|
|
394
|
+
expected = {(cell.row, cell.column): value_fn(str(cell.clean_value)) for cell in ground_truth}
|
|
395
|
+
matched: set[tuple[int, str]] = set()
|
|
396
|
+
tp = 0
|
|
397
|
+
fp = 0
|
|
398
|
+
for fix in normalized:
|
|
399
|
+
key = (fix.row, fix.column)
|
|
400
|
+
expected_value = expected.get(key)
|
|
401
|
+
if expected_value is not None and value_fn(fix.new_value) == expected_value:
|
|
402
|
+
tp += 1
|
|
403
|
+
matched.add(key)
|
|
404
|
+
else:
|
|
405
|
+
fp += 1
|
|
406
|
+
fn = len(expected) - len(matched)
|
|
407
|
+
precision = tp / (tp + fp) if (tp + fp) else 0.0
|
|
408
|
+
recall = tp / (tp + fn) if (tp + fn) else 0.0
|
|
409
|
+
f1 = (2 * precision * recall / (precision + recall)) if (precision + recall) else 0.0
|
|
410
|
+
return RepairScore(
|
|
411
|
+
tp=tp,
|
|
412
|
+
fp=fp,
|
|
413
|
+
fn=fn,
|
|
414
|
+
precision=round(precision, 4),
|
|
415
|
+
recall=round(recall, 4),
|
|
416
|
+
f1=round(f1, 4),
|
|
417
|
+
)
|
|
418
|
+
|
|
419
|
+
|
|
420
|
+
def score_repair_fixes_canonicalized(
|
|
421
|
+
ground_truth: Iterable[TruthLike],
|
|
422
|
+
fixes: Iterable[RepairLike],
|
|
423
|
+
) -> RepairScore:
|
|
424
|
+
"""Diagnostics-only F1 after conservative value canonicalization."""
|
|
425
|
+
return score_repair_fixes(ground_truth, fixes, canonicalize_values=True)
|
|
426
|
+
|
|
427
|
+
|
|
428
|
+
def repair_failure_taxonomy(
|
|
429
|
+
*,
|
|
430
|
+
ground_truth: Iterable[TruthLike],
|
|
431
|
+
fixes: Iterable[RepairLike],
|
|
432
|
+
allowed_columns: Iterable[str],
|
|
433
|
+
valid_rows: Iterable[int],
|
|
434
|
+
) -> dict[str, int]:
|
|
435
|
+
"""Classify exact-match failures without changing official scoring."""
|
|
436
|
+
columns = set(allowed_columns)
|
|
437
|
+
lowercase_columns = {column.lower(): column for column in columns}
|
|
438
|
+
rows = set(valid_rows)
|
|
439
|
+
truth_map = {(cell.row, cell.column): str(cell.clean_value) for cell in ground_truth}
|
|
440
|
+
raw_fixes = list(fixes)
|
|
441
|
+
normalized_fixes = normalize_fixes(raw_fixes)
|
|
442
|
+
predictions = {(fix.row, fix.column): fix.new_value for fix in normalized_fixes}
|
|
443
|
+
counts: Counter[str] = Counter()
|
|
444
|
+
duplicate_count = len(raw_fixes) - len(normalized_fixes)
|
|
445
|
+
if duplicate_count:
|
|
446
|
+
counts["duplicate_cell"] += duplicate_count
|
|
447
|
+
|
|
448
|
+
for fix in normalized_fixes:
|
|
449
|
+
key = (fix.row, fix.column)
|
|
450
|
+
if fix.column not in columns:
|
|
451
|
+
if fix.column.lower() in lowercase_columns:
|
|
452
|
+
counts["schema_case_error"] += 1
|
|
453
|
+
else:
|
|
454
|
+
counts["wrong_cell"] += 1
|
|
455
|
+
continue
|
|
456
|
+
if fix.row not in rows:
|
|
457
|
+
counts["wrong_cell"] += 1
|
|
458
|
+
continue
|
|
459
|
+
if key not in truth_map:
|
|
460
|
+
counts["overrepair"] += 1
|
|
461
|
+
continue
|
|
462
|
+
if truth_map[key] != fix.new_value:
|
|
463
|
+
counts["wrong_value"] += 1
|
|
464
|
+
|
|
465
|
+
for key in truth_map:
|
|
466
|
+
if key not in predictions:
|
|
467
|
+
counts["missed_repair"] += 1
|
|
468
|
+
return {kind: count for kind, count in sorted(counts.items()) if count}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"""Repairer package for turning detected issues into proposed fixes."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from dataforge.detectors.base import Issue, Schema
|
|
8
|
+
from dataforge.repairers.base import ProposedFix, RepairAttempt, Repairer, RetryContext
|
|
9
|
+
from dataforge.repairers.decimal_shift import DecimalShiftRepairer
|
|
10
|
+
from dataforge.repairers.fd_violation import FDViolationRepairer
|
|
11
|
+
from dataforge.repairers.type_mismatch import TypeMismatchRepairer
|
|
12
|
+
from dataforge.table import TableLike
|
|
13
|
+
|
|
14
|
+
__all__ = [
|
|
15
|
+
"DecimalShiftRepairer",
|
|
16
|
+
"FDViolationRepairer",
|
|
17
|
+
"ProposedFix",
|
|
18
|
+
"RepairAttempt",
|
|
19
|
+
"Repairer",
|
|
20
|
+
"RetryContext",
|
|
21
|
+
"TypeMismatchRepairer",
|
|
22
|
+
"build_repairers",
|
|
23
|
+
"propose_fixes",
|
|
24
|
+
]
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def build_repairers(
|
|
28
|
+
*,
|
|
29
|
+
cache_dir: Path | None,
|
|
30
|
+
allow_llm: bool,
|
|
31
|
+
model: str,
|
|
32
|
+
) -> dict[str, Repairer]:
|
|
33
|
+
"""Construct the default repairer registry."""
|
|
34
|
+
return {
|
|
35
|
+
"type_mismatch": TypeMismatchRepairer(),
|
|
36
|
+
"decimal_shift": DecimalShiftRepairer(),
|
|
37
|
+
"fd_violation": FDViolationRepairer(
|
|
38
|
+
cache_dir=cache_dir,
|
|
39
|
+
allow_llm=allow_llm,
|
|
40
|
+
model=model,
|
|
41
|
+
),
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def propose_fixes(
|
|
46
|
+
issues: list[Issue],
|
|
47
|
+
df: TableLike,
|
|
48
|
+
schema: Schema | None,
|
|
49
|
+
*,
|
|
50
|
+
cache_dir: Path | None,
|
|
51
|
+
allow_llm: bool = False,
|
|
52
|
+
model: str = "gemini-2.0-flash",
|
|
53
|
+
) -> list[ProposedFix]:
|
|
54
|
+
"""Run all Week 2 repairers and return proposed fixes.
|
|
55
|
+
|
|
56
|
+
Args:
|
|
57
|
+
issues: Detected issues from the detector layer.
|
|
58
|
+
df: The input DataFrame being repaired.
|
|
59
|
+
schema: Optional declared schema.
|
|
60
|
+
cache_dir: Cache directory for any LLM-backed repair decisions.
|
|
61
|
+
allow_llm: Whether fd-violation repair may call the LLM provider.
|
|
62
|
+
model: The provider model name for fd-violation fallback.
|
|
63
|
+
|
|
64
|
+
Returns:
|
|
65
|
+
A deduplicated list of proposed fixes.
|
|
66
|
+
"""
|
|
67
|
+
registry = build_repairers(
|
|
68
|
+
cache_dir=cache_dir,
|
|
69
|
+
allow_llm=allow_llm,
|
|
70
|
+
model=model,
|
|
71
|
+
)
|
|
72
|
+
proposed: list[ProposedFix] = []
|
|
73
|
+
seen_cells: set[tuple[int, str]] = set()
|
|
74
|
+
|
|
75
|
+
for issue in issues:
|
|
76
|
+
repairer = registry.get(issue.issue_type)
|
|
77
|
+
if repairer is None:
|
|
78
|
+
continue
|
|
79
|
+
fix = repairer.propose(issue, df, schema, retry_context=None)
|
|
80
|
+
if fix is None:
|
|
81
|
+
continue
|
|
82
|
+
key = (fix.fix.row, fix.fix.column)
|
|
83
|
+
if key in seen_cells:
|
|
84
|
+
continue
|
|
85
|
+
seen_cells.add(key)
|
|
86
|
+
proposed.append(fix)
|
|
87
|
+
|
|
88
|
+
return proposed
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""Core models and protocol for DataForge repairers."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Literal, Protocol
|
|
6
|
+
|
|
7
|
+
from pydantic import BaseModel, Field
|
|
8
|
+
|
|
9
|
+
from dataforge.detectors.base import Issue, Schema
|
|
10
|
+
from dataforge.table import TableLike
|
|
11
|
+
from dataforge.transactions.txn import CellFix
|
|
12
|
+
|
|
13
|
+
ProvenanceLiteral = Literal["deterministic", "llm_cache", "llm_live"]
|
|
14
|
+
AttemptStatusLiteral = Literal[
|
|
15
|
+
"accepted",
|
|
16
|
+
"denied",
|
|
17
|
+
"escalated",
|
|
18
|
+
"rejected",
|
|
19
|
+
"unknown",
|
|
20
|
+
"attempted_not_fixed",
|
|
21
|
+
]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class ProposedFix(BaseModel):
|
|
25
|
+
"""A repair proposal emitted by a repairer.
|
|
26
|
+
|
|
27
|
+
Args:
|
|
28
|
+
fix: The cell mutation to apply.
|
|
29
|
+
reason: Human-readable explanation of why this repair is proposed.
|
|
30
|
+
confidence: Repair confidence in the range [0.0, 1.0].
|
|
31
|
+
provenance: Where the proposed value came from.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
fix: CellFix
|
|
35
|
+
reason: str = Field(min_length=1)
|
|
36
|
+
confidence: float = Field(ge=0.0, le=1.0)
|
|
37
|
+
provenance: ProvenanceLiteral
|
|
38
|
+
|
|
39
|
+
model_config = {"frozen": True}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class RepairAttempt(BaseModel):
|
|
43
|
+
"""Recorded outcome for one issue-repair attempt."""
|
|
44
|
+
|
|
45
|
+
issue: Issue
|
|
46
|
+
attempt_number: int = Field(ge=1)
|
|
47
|
+
fix: ProposedFix | None = None
|
|
48
|
+
status: AttemptStatusLiteral
|
|
49
|
+
reason: str = Field(min_length=1)
|
|
50
|
+
unsat_core: tuple[str, ...] = Field(default_factory=tuple)
|
|
51
|
+
|
|
52
|
+
model_config = {"frozen": True}
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class RetryContext(BaseModel):
|
|
56
|
+
"""Hints passed back to a repairer after a failed attempt."""
|
|
57
|
+
|
|
58
|
+
issue: Issue
|
|
59
|
+
previous_attempts: tuple[RepairAttempt, ...] = Field(default_factory=tuple)
|
|
60
|
+
rejected_values: frozenset[str] = Field(default_factory=frozenset)
|
|
61
|
+
hints: tuple[str, ...] = Field(default_factory=tuple)
|
|
62
|
+
|
|
63
|
+
model_config = {"frozen": True}
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class Repairer(Protocol):
|
|
67
|
+
"""Structural protocol implemented by every repairer."""
|
|
68
|
+
|
|
69
|
+
def propose(
|
|
70
|
+
self,
|
|
71
|
+
issue: Issue,
|
|
72
|
+
df: TableLike,
|
|
73
|
+
schema: Schema | None,
|
|
74
|
+
retry_context: RetryContext | None = None,
|
|
75
|
+
) -> ProposedFix | None:
|
|
76
|
+
"""Return a repair proposal for an issue, or ``None`` if unavailable."""
|
|
77
|
+
... # pragma: no cover
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""Deterministic repairer for decimal-shift issues."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataforge.detectors.base import Issue, Schema
|
|
6
|
+
from dataforge.repairers.base import ProposedFix, RetryContext
|
|
7
|
+
from dataforge.table import TableLike, cell_value, column_names, row_count
|
|
8
|
+
from dataforge.transactions.txn import CellFix
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class DecimalShiftRepairer:
|
|
12
|
+
"""Repair decimal-shift issues using the detector's expected value."""
|
|
13
|
+
|
|
14
|
+
def propose(
|
|
15
|
+
self,
|
|
16
|
+
issue: Issue,
|
|
17
|
+
df: TableLike,
|
|
18
|
+
schema: Schema | None,
|
|
19
|
+
retry_context: RetryContext | None = None,
|
|
20
|
+
) -> ProposedFix | None:
|
|
21
|
+
"""Return a deterministic fix for a decimal-shift issue."""
|
|
22
|
+
del schema, retry_context
|
|
23
|
+
if issue.issue_type != "decimal_shift" or issue.expected is None:
|
|
24
|
+
return None
|
|
25
|
+
if issue.row >= row_count(df) or issue.column not in column_names(df):
|
|
26
|
+
return None
|
|
27
|
+
|
|
28
|
+
old_value = cell_value(df, issue.row, issue.column)
|
|
29
|
+
if old_value == issue.expected:
|
|
30
|
+
return None
|
|
31
|
+
|
|
32
|
+
return ProposedFix(
|
|
33
|
+
fix=CellFix(
|
|
34
|
+
row=issue.row,
|
|
35
|
+
column=issue.column,
|
|
36
|
+
old_value=old_value,
|
|
37
|
+
new_value=issue.expected,
|
|
38
|
+
detector_id="decimal_shift",
|
|
39
|
+
),
|
|
40
|
+
reason=issue.reason,
|
|
41
|
+
confidence=issue.confidence,
|
|
42
|
+
provenance="deterministic",
|
|
43
|
+
)
|