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,620 @@
|
|
|
1
|
+
"""Reviewable schema and constraint inference for DataForge profiles."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
import math
|
|
8
|
+
import os
|
|
9
|
+
import re
|
|
10
|
+
import tempfile
|
|
11
|
+
from collections import Counter, defaultdict
|
|
12
|
+
from contextlib import suppress
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Literal
|
|
15
|
+
|
|
16
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
17
|
+
|
|
18
|
+
from dataforge.table import TableLike, column_names, column_values, row_count
|
|
19
|
+
from dataforge.transactions.log import sha256_bytes
|
|
20
|
+
from dataforge.verifier.schema import DomainBound, FunctionalDependency, Schema
|
|
21
|
+
|
|
22
|
+
ConstraintKind = Literal[
|
|
23
|
+
"column_type",
|
|
24
|
+
"domain_bound",
|
|
25
|
+
"regex",
|
|
26
|
+
"unique",
|
|
27
|
+
"functional_dependency",
|
|
28
|
+
]
|
|
29
|
+
ConstraintDecision = Literal["pending", "accepted", "rejected"]
|
|
30
|
+
CONSTRAINT_REVIEW_SCHEMA_VERSION: Literal["constraint_review_v1"] = "constraint_review_v1"
|
|
31
|
+
REPAIR_SUPPORTED_CONSTRAINT_KINDS = frozenset(
|
|
32
|
+
{"column_type", "domain_bound", "functional_dependency"}
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
_INT_RE = re.compile(r"^[+-]?\d+$")
|
|
36
|
+
_FLOAT_RE = re.compile(r"^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$")
|
|
37
|
+
_ISO_DATE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$")
|
|
38
|
+
_DIGITS_RE = re.compile(r"^\d+$")
|
|
39
|
+
_UPPER_CODE_RE = re.compile(r"^[A-Z0-9_-]+$")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class ConstraintCandidate(BaseModel):
|
|
43
|
+
"""One inferred constraint candidate that must be reviewed before adoption."""
|
|
44
|
+
|
|
45
|
+
kind: ConstraintKind
|
|
46
|
+
columns: tuple[str, ...] = Field(min_length=1)
|
|
47
|
+
dependent: str | None = None
|
|
48
|
+
inferred_type: str | None = None
|
|
49
|
+
pattern: str | None = None
|
|
50
|
+
min_value: float | None = None
|
|
51
|
+
max_value: float | None = None
|
|
52
|
+
confidence: float = Field(ge=0.0, le=1.0)
|
|
53
|
+
evidence: str = Field(min_length=1)
|
|
54
|
+
provenance: str = "profile_inference_v1"
|
|
55
|
+
|
|
56
|
+
model_config = ConfigDict(strict=True, extra="forbid", frozen=True)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class SchemaInferenceResult(BaseModel):
|
|
60
|
+
"""Reviewable schema inference result emitted by profile and benchmarks."""
|
|
61
|
+
|
|
62
|
+
columns: dict[str, str] = Field(default_factory=dict)
|
|
63
|
+
candidates: list[ConstraintCandidate] = Field(default_factory=list)
|
|
64
|
+
row_count: int = Field(ge=0)
|
|
65
|
+
|
|
66
|
+
model_config = ConfigDict(strict=True, extra="forbid", frozen=True)
|
|
67
|
+
|
|
68
|
+
def to_schema(self, *, include_inferred_constraints: bool = False) -> Schema:
|
|
69
|
+
"""Convert reviewed inference output into a verifier Schema."""
|
|
70
|
+
if not include_inferred_constraints:
|
|
71
|
+
return Schema(columns=dict(self.columns))
|
|
72
|
+
|
|
73
|
+
fds: list[FunctionalDependency] = []
|
|
74
|
+
bounds: list[DomainBound] = []
|
|
75
|
+
for candidate in self.candidates:
|
|
76
|
+
if (
|
|
77
|
+
candidate.kind == "functional_dependency"
|
|
78
|
+
and candidate.dependent is not None
|
|
79
|
+
and candidate.confidence >= 0.9
|
|
80
|
+
):
|
|
81
|
+
fds.append(
|
|
82
|
+
FunctionalDependency(
|
|
83
|
+
determinant=candidate.columns,
|
|
84
|
+
dependent=candidate.dependent,
|
|
85
|
+
)
|
|
86
|
+
)
|
|
87
|
+
elif candidate.kind == "domain_bound" and candidate.confidence >= 0.95:
|
|
88
|
+
bounds.append(
|
|
89
|
+
DomainBound(
|
|
90
|
+
column=candidate.columns[0],
|
|
91
|
+
min_value=candidate.min_value,
|
|
92
|
+
max_value=candidate.max_value,
|
|
93
|
+
)
|
|
94
|
+
)
|
|
95
|
+
return Schema(
|
|
96
|
+
columns=dict(self.columns),
|
|
97
|
+
functional_dependencies=tuple(fds),
|
|
98
|
+
domain_bounds=tuple(bounds),
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class ReviewedConstraintCandidate(BaseModel):
|
|
103
|
+
"""A profile-inferred candidate plus its explicit review decision."""
|
|
104
|
+
|
|
105
|
+
candidate_id: str = Field(pattern=r"^cnd-[0-9a-f]{16}$")
|
|
106
|
+
decision: ConstraintDecision = "pending"
|
|
107
|
+
candidate: ConstraintCandidate
|
|
108
|
+
review_note: str | None = None
|
|
109
|
+
|
|
110
|
+
model_config = ConfigDict(strict=True, extra="forbid", frozen=True)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
class ConstraintReviewArtifact(BaseModel):
|
|
114
|
+
"""Strict JSON artifact that records review decisions for inferred constraints."""
|
|
115
|
+
|
|
116
|
+
schema_version: Literal["constraint_review_v1"] = CONSTRAINT_REVIEW_SCHEMA_VERSION
|
|
117
|
+
source_path: str = Field(min_length=1)
|
|
118
|
+
source_sha256: str = Field(pattern=r"^[0-9a-f]{64}$")
|
|
119
|
+
row_count: int = Field(ge=0)
|
|
120
|
+
candidates: list[ReviewedConstraintCandidate] = Field(default_factory=list)
|
|
121
|
+
|
|
122
|
+
model_config = ConfigDict(strict=True, extra="forbid", frozen=True)
|
|
123
|
+
|
|
124
|
+
def accepted_candidates(self) -> list[ReviewedConstraintCandidate]:
|
|
125
|
+
"""Return candidates explicitly accepted by review."""
|
|
126
|
+
return [candidate for candidate in self.candidates if candidate.decision == "accepted"]
|
|
127
|
+
|
|
128
|
+
def to_schema(self) -> Schema:
|
|
129
|
+
"""Convert accepted repair-supported candidates into a verifier Schema."""
|
|
130
|
+
columns: dict[str, str] = {}
|
|
131
|
+
fds: list[FunctionalDependency] = []
|
|
132
|
+
bounds: list[DomainBound] = []
|
|
133
|
+
|
|
134
|
+
for reviewed in self.accepted_candidates():
|
|
135
|
+
candidate = reviewed.candidate
|
|
136
|
+
if candidate.kind == "column_type" and candidate.inferred_type is not None:
|
|
137
|
+
columns[candidate.columns[0]] = candidate.inferred_type
|
|
138
|
+
elif candidate.kind == "domain_bound":
|
|
139
|
+
bounds.append(
|
|
140
|
+
DomainBound(
|
|
141
|
+
column=candidate.columns[0],
|
|
142
|
+
min_value=candidate.min_value,
|
|
143
|
+
max_value=candidate.max_value,
|
|
144
|
+
)
|
|
145
|
+
)
|
|
146
|
+
elif candidate.kind == "functional_dependency" and candidate.dependent is not None:
|
|
147
|
+
fds.append(
|
|
148
|
+
FunctionalDependency(
|
|
149
|
+
determinant=candidate.columns,
|
|
150
|
+
dependent=candidate.dependent,
|
|
151
|
+
)
|
|
152
|
+
)
|
|
153
|
+
|
|
154
|
+
return Schema(
|
|
155
|
+
columns=columns,
|
|
156
|
+
functional_dependencies=tuple(fds),
|
|
157
|
+
domain_bounds=tuple(bounds),
|
|
158
|
+
)
|
|
159
|
+
|
|
160
|
+
def accepted_candidate_ids(self) -> list[str]:
|
|
161
|
+
"""Return accepted candidate ids that affect repair in v1."""
|
|
162
|
+
return [
|
|
163
|
+
reviewed.candidate_id
|
|
164
|
+
for reviewed in self.accepted_candidates()
|
|
165
|
+
if reviewed.candidate.kind in REPAIR_SUPPORTED_CONSTRAINT_KINDS
|
|
166
|
+
]
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
class ConstraintReviewError(ValueError):
|
|
170
|
+
"""Raised when a reviewed constraint artifact cannot be used safely."""
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _canonical_candidate_payload(candidate: ConstraintCandidate) -> str:
|
|
174
|
+
"""Return stable JSON used for candidate ids and deterministic artifacts."""
|
|
175
|
+
return json.dumps(
|
|
176
|
+
candidate.model_dump(mode="json"),
|
|
177
|
+
sort_keys=True,
|
|
178
|
+
separators=(",", ":"),
|
|
179
|
+
)
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def constraint_candidate_id(candidate: ConstraintCandidate) -> str:
|
|
183
|
+
"""Return the stable id for one inferred constraint candidate."""
|
|
184
|
+
digest = hashlib.sha256(_canonical_candidate_payload(candidate).encode("utf-8")).hexdigest()
|
|
185
|
+
return f"cnd-{digest[:16]}"
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def build_constraint_review_artifact(
|
|
189
|
+
inference: SchemaInferenceResult,
|
|
190
|
+
*,
|
|
191
|
+
source_path: Path,
|
|
192
|
+
source_sha256: str,
|
|
193
|
+
) -> ConstraintReviewArtifact:
|
|
194
|
+
"""Create a pending review artifact from a schema inference result."""
|
|
195
|
+
reviewed: list[ReviewedConstraintCandidate] = []
|
|
196
|
+
seen_ids: set[str] = set()
|
|
197
|
+
for candidate in inference.candidates:
|
|
198
|
+
candidate_id = constraint_candidate_id(candidate)
|
|
199
|
+
if candidate_id in seen_ids:
|
|
200
|
+
raise ConstraintReviewError(f"Duplicate inferred constraint id: {candidate_id}.")
|
|
201
|
+
seen_ids.add(candidate_id)
|
|
202
|
+
reviewed.append(
|
|
203
|
+
ReviewedConstraintCandidate(
|
|
204
|
+
candidate_id=candidate_id,
|
|
205
|
+
candidate=candidate,
|
|
206
|
+
)
|
|
207
|
+
)
|
|
208
|
+
return ConstraintReviewArtifact(
|
|
209
|
+
source_path=str(source_path),
|
|
210
|
+
source_sha256=source_sha256,
|
|
211
|
+
row_count=inference.row_count,
|
|
212
|
+
candidates=reviewed,
|
|
213
|
+
)
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def validate_constraint_review_artifact(artifact: ConstraintReviewArtifact) -> None:
|
|
217
|
+
"""Validate review-artifact integrity beyond the strict JSON schema."""
|
|
218
|
+
seen_ids: set[str] = set()
|
|
219
|
+
duplicate_ids: list[str] = []
|
|
220
|
+
mismatched_ids: list[str] = []
|
|
221
|
+
for reviewed in artifact.candidates:
|
|
222
|
+
if reviewed.candidate_id in seen_ids:
|
|
223
|
+
duplicate_ids.append(reviewed.candidate_id)
|
|
224
|
+
seen_ids.add(reviewed.candidate_id)
|
|
225
|
+
|
|
226
|
+
expected_id = constraint_candidate_id(reviewed.candidate)
|
|
227
|
+
if reviewed.candidate_id != expected_id:
|
|
228
|
+
mismatched_ids.append(f"{reviewed.candidate_id} should be {expected_id}")
|
|
229
|
+
|
|
230
|
+
errors: list[str] = []
|
|
231
|
+
if duplicate_ids:
|
|
232
|
+
errors.append("duplicate candidate ids: " + ", ".join(sorted(set(duplicate_ids))))
|
|
233
|
+
if mismatched_ids:
|
|
234
|
+
errors.append("candidate id payload mismatch: " + "; ".join(mismatched_ids))
|
|
235
|
+
if errors:
|
|
236
|
+
raise ConstraintReviewError("Invalid constraints artifact: " + "; ".join(errors))
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def load_constraint_review_artifact(path: Path) -> tuple[ConstraintReviewArtifact, str]:
|
|
240
|
+
"""Load a strict constraint review artifact and return it with its SHA-256."""
|
|
241
|
+
try:
|
|
242
|
+
payload = path.read_bytes()
|
|
243
|
+
except OSError as exc:
|
|
244
|
+
raise ConstraintReviewError(f"Could not read constraints file '{path}': {exc}") from exc
|
|
245
|
+
try:
|
|
246
|
+
artifact = ConstraintReviewArtifact.model_validate_json(payload)
|
|
247
|
+
except ValueError as exc:
|
|
248
|
+
raise ConstraintReviewError(f"Invalid constraints file '{path}': {exc}") from exc
|
|
249
|
+
validate_constraint_review_artifact(artifact)
|
|
250
|
+
return artifact, sha256_bytes(payload)
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def dump_constraint_review_artifact(artifact: ConstraintReviewArtifact) -> str:
|
|
254
|
+
"""Return deterministic, human-reviewable JSON for a constraint artifact."""
|
|
255
|
+
validate_constraint_review_artifact(artifact)
|
|
256
|
+
return json.dumps(artifact.model_dump(mode="json"), indent=2, sort_keys=True) + "\n"
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def update_constraint_review_artifact(
|
|
260
|
+
artifact: ConstraintReviewArtifact,
|
|
261
|
+
*,
|
|
262
|
+
accept_ids: list[str] | tuple[str, ...] = (),
|
|
263
|
+
reject_ids: list[str] | tuple[str, ...] = (),
|
|
264
|
+
pending_ids: list[str] | tuple[str, ...] = (),
|
|
265
|
+
notes: dict[str, str | None] | None = None,
|
|
266
|
+
) -> ConstraintReviewArtifact:
|
|
267
|
+
"""Return a reviewed artifact with explicit decision and note edits applied."""
|
|
268
|
+
validate_constraint_review_artifact(artifact)
|
|
269
|
+
notes = notes or {}
|
|
270
|
+
decisions: dict[str, ConstraintDecision] = {}
|
|
271
|
+
conflicts: set[str] = set()
|
|
272
|
+
for candidate_id in accept_ids:
|
|
273
|
+
if candidate_id in decisions:
|
|
274
|
+
conflicts.add(candidate_id)
|
|
275
|
+
decisions[candidate_id] = "accepted"
|
|
276
|
+
for candidate_id in reject_ids:
|
|
277
|
+
if candidate_id in decisions:
|
|
278
|
+
conflicts.add(candidate_id)
|
|
279
|
+
decisions[candidate_id] = "rejected"
|
|
280
|
+
for candidate_id in pending_ids:
|
|
281
|
+
if candidate_id in decisions:
|
|
282
|
+
conflicts.add(candidate_id)
|
|
283
|
+
decisions[candidate_id] = "pending"
|
|
284
|
+
if conflicts:
|
|
285
|
+
raise ConstraintReviewError(
|
|
286
|
+
"Candidate ids received conflicting review decisions: " + ", ".join(sorted(conflicts))
|
|
287
|
+
)
|
|
288
|
+
|
|
289
|
+
known_ids = {reviewed.candidate_id for reviewed in artifact.candidates}
|
|
290
|
+
unknown_ids = sorted((set(decisions) | set(notes)) - known_ids)
|
|
291
|
+
if unknown_ids:
|
|
292
|
+
raise ConstraintReviewError("Unknown candidate ids: " + ", ".join(unknown_ids))
|
|
293
|
+
|
|
294
|
+
updated_candidates: list[ReviewedConstraintCandidate] = []
|
|
295
|
+
for reviewed in artifact.candidates:
|
|
296
|
+
update: dict[str, object] = {}
|
|
297
|
+
if reviewed.candidate_id in decisions:
|
|
298
|
+
update["decision"] = decisions[reviewed.candidate_id]
|
|
299
|
+
if reviewed.candidate_id in notes:
|
|
300
|
+
note = notes[reviewed.candidate_id]
|
|
301
|
+
update["review_note"] = note if note else None
|
|
302
|
+
updated_candidates.append(reviewed.model_copy(update=update))
|
|
303
|
+
|
|
304
|
+
updated = artifact.model_copy(update={"candidates": updated_candidates})
|
|
305
|
+
validate_constraint_review_artifact(updated)
|
|
306
|
+
return updated
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def write_constraint_review_artifact_atomic(path: Path, artifact: ConstraintReviewArtifact) -> str:
|
|
310
|
+
"""Atomically rewrite a constraints artifact and return the written SHA-256."""
|
|
311
|
+
payload = dump_constraint_review_artifact(artifact).encode("utf-8")
|
|
312
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
313
|
+
fd, temp_name = tempfile.mkstemp(
|
|
314
|
+
prefix=f".{path.name}.",
|
|
315
|
+
suffix=".tmp",
|
|
316
|
+
dir=str(path.parent),
|
|
317
|
+
)
|
|
318
|
+
temp_path = Path(temp_name)
|
|
319
|
+
try:
|
|
320
|
+
with os.fdopen(fd, "wb") as handle:
|
|
321
|
+
handle.write(payload)
|
|
322
|
+
handle.flush()
|
|
323
|
+
os.fsync(handle.fileno())
|
|
324
|
+
os.replace(temp_path, path)
|
|
325
|
+
except Exception:
|
|
326
|
+
with suppress(OSError):
|
|
327
|
+
temp_path.unlink()
|
|
328
|
+
raise
|
|
329
|
+
return sha256_bytes(payload)
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
def merge_schema_with_reviewed_constraints(
|
|
333
|
+
base_schema: Schema | None,
|
|
334
|
+
artifact: ConstraintReviewArtifact | None,
|
|
335
|
+
*,
|
|
336
|
+
source_sha256: str,
|
|
337
|
+
) -> tuple[Schema | None, list[str]]:
|
|
338
|
+
"""Merge a declared schema with accepted reviewed constraints.
|
|
339
|
+
|
|
340
|
+
Pending and rejected candidates are ignored. Accepted regex and uniqueness
|
|
341
|
+
candidates stay recorded in the artifact but do not affect repair in v1.
|
|
342
|
+
"""
|
|
343
|
+
if artifact is None:
|
|
344
|
+
return base_schema, []
|
|
345
|
+
if artifact.source_sha256 != source_sha256:
|
|
346
|
+
raise ConstraintReviewError(
|
|
347
|
+
"Constraint review artifact source_sha256 does not match the CSV being repaired."
|
|
348
|
+
)
|
|
349
|
+
|
|
350
|
+
accepted_schema = artifact.to_schema()
|
|
351
|
+
accepted_ids = artifact.accepted_candidate_ids()
|
|
352
|
+
if not accepted_ids:
|
|
353
|
+
return base_schema, []
|
|
354
|
+
if base_schema is None:
|
|
355
|
+
return accepted_schema, accepted_ids
|
|
356
|
+
|
|
357
|
+
conflicts: list[str] = []
|
|
358
|
+
merged_columns = dict(base_schema.columns)
|
|
359
|
+
accepted_by_id = {
|
|
360
|
+
reviewed.candidate_id: reviewed
|
|
361
|
+
for reviewed in artifact.accepted_candidates()
|
|
362
|
+
if reviewed.candidate.kind in REPAIR_SUPPORTED_CONSTRAINT_KINDS
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
for candidate_id, reviewed in accepted_by_id.items():
|
|
366
|
+
candidate = reviewed.candidate
|
|
367
|
+
if candidate.kind != "column_type" or candidate.inferred_type is None:
|
|
368
|
+
continue
|
|
369
|
+
column = candidate.columns[0]
|
|
370
|
+
declared_type = merged_columns.get(column)
|
|
371
|
+
if declared_type is not None and declared_type != candidate.inferred_type:
|
|
372
|
+
conflicts.append(
|
|
373
|
+
f"{candidate_id}: column '{column}' declared as {declared_type!r} "
|
|
374
|
+
f"but accepted candidate infers {candidate.inferred_type!r}"
|
|
375
|
+
)
|
|
376
|
+
continue
|
|
377
|
+
merged_columns[column] = candidate.inferred_type
|
|
378
|
+
|
|
379
|
+
merged_fds = list(base_schema.functional_dependencies)
|
|
380
|
+
fd_keys = {(fd.determinant, fd.dependent) for fd in merged_fds}
|
|
381
|
+
for fd in accepted_schema.functional_dependencies:
|
|
382
|
+
fd_key = (fd.determinant, fd.dependent)
|
|
383
|
+
if fd_key not in fd_keys:
|
|
384
|
+
merged_fds.append(fd)
|
|
385
|
+
fd_keys.add(fd_key)
|
|
386
|
+
|
|
387
|
+
merged_bounds = list(base_schema.domain_bounds)
|
|
388
|
+
bound_keys = {
|
|
389
|
+
(
|
|
390
|
+
bound.column,
|
|
391
|
+
bound.min_value,
|
|
392
|
+
bound.max_value,
|
|
393
|
+
bound.inclusive_min,
|
|
394
|
+
bound.inclusive_max,
|
|
395
|
+
)
|
|
396
|
+
for bound in merged_bounds
|
|
397
|
+
}
|
|
398
|
+
bounds_by_column = {bound.column: bound for bound in base_schema.domain_bounds}
|
|
399
|
+
for candidate_id, reviewed in accepted_by_id.items():
|
|
400
|
+
candidate = reviewed.candidate
|
|
401
|
+
if candidate.kind != "domain_bound":
|
|
402
|
+
continue
|
|
403
|
+
accepted_bound = DomainBound(
|
|
404
|
+
column=candidate.columns[0],
|
|
405
|
+
min_value=candidate.min_value,
|
|
406
|
+
max_value=candidate.max_value,
|
|
407
|
+
)
|
|
408
|
+
declared_bound = bounds_by_column.get(accepted_bound.column)
|
|
409
|
+
if declared_bound is not None and declared_bound != accepted_bound:
|
|
410
|
+
conflicts.append(
|
|
411
|
+
f"{candidate_id}: domain bound for '{accepted_bound.column}' conflicts "
|
|
412
|
+
"with declared schema"
|
|
413
|
+
)
|
|
414
|
+
continue
|
|
415
|
+
bound_key = (
|
|
416
|
+
accepted_bound.column,
|
|
417
|
+
accepted_bound.min_value,
|
|
418
|
+
accepted_bound.max_value,
|
|
419
|
+
accepted_bound.inclusive_min,
|
|
420
|
+
accepted_bound.inclusive_max,
|
|
421
|
+
)
|
|
422
|
+
if bound_key not in bound_keys:
|
|
423
|
+
merged_bounds.append(accepted_bound)
|
|
424
|
+
bound_keys.add(bound_key)
|
|
425
|
+
|
|
426
|
+
if conflicts:
|
|
427
|
+
raise ConstraintReviewError(
|
|
428
|
+
"Accepted constraints conflict with the declared schema: " + "; ".join(conflicts)
|
|
429
|
+
)
|
|
430
|
+
|
|
431
|
+
return (
|
|
432
|
+
Schema(
|
|
433
|
+
columns=merged_columns,
|
|
434
|
+
functional_dependencies=tuple(merged_fds),
|
|
435
|
+
pii_columns=base_schema.pii_columns,
|
|
436
|
+
primary_key_columns=base_schema.primary_key_columns,
|
|
437
|
+
not_null_columns=base_schema.not_null_columns,
|
|
438
|
+
unique_columns=base_schema.unique_columns,
|
|
439
|
+
accepted_values=base_schema.accepted_values,
|
|
440
|
+
regex_constraints=base_schema.regex_constraints,
|
|
441
|
+
relationships=base_schema.relationships,
|
|
442
|
+
domain_bounds=tuple(merged_bounds),
|
|
443
|
+
aggregate_dependencies=base_schema.aggregate_dependencies,
|
|
444
|
+
),
|
|
445
|
+
accepted_ids,
|
|
446
|
+
)
|
|
447
|
+
|
|
448
|
+
|
|
449
|
+
def _non_empty(values: list[object]) -> list[str]:
|
|
450
|
+
"""Return non-empty string values."""
|
|
451
|
+
return [str(value).strip() for value in values if str(value).strip()]
|
|
452
|
+
|
|
453
|
+
|
|
454
|
+
def _try_float(value: str) -> float | None:
|
|
455
|
+
"""Parse a finite float or return None."""
|
|
456
|
+
try:
|
|
457
|
+
parsed = float(value)
|
|
458
|
+
except ValueError:
|
|
459
|
+
return None
|
|
460
|
+
return parsed if math.isfinite(parsed) else None
|
|
461
|
+
|
|
462
|
+
|
|
463
|
+
def _infer_column_type(values: list[str]) -> tuple[str, float, str]:
|
|
464
|
+
"""Infer a conservative verifier-compatible column type."""
|
|
465
|
+
if not values:
|
|
466
|
+
return "str", 0.0, "No non-empty values were available."
|
|
467
|
+
|
|
468
|
+
int_count = sum(1 for value in values if _INT_RE.fullmatch(value))
|
|
469
|
+
float_count = sum(1 for value in values if _FLOAT_RE.fullmatch(value))
|
|
470
|
+
date_count = sum(1 for value in values if _ISO_DATE_RE.fullmatch(value))
|
|
471
|
+
total = len(values)
|
|
472
|
+
|
|
473
|
+
if int_count / total >= 0.95:
|
|
474
|
+
return "int", round(int_count / total, 4), f"{int_count}/{total} values parse as integers."
|
|
475
|
+
if float_count / total >= 0.9:
|
|
476
|
+
return (
|
|
477
|
+
"float",
|
|
478
|
+
round(float_count / total, 4),
|
|
479
|
+
f"{float_count}/{total} values parse as floats.",
|
|
480
|
+
)
|
|
481
|
+
if date_count / total >= 0.9:
|
|
482
|
+
return (
|
|
483
|
+
"str",
|
|
484
|
+
round(date_count / total, 4),
|
|
485
|
+
f"{date_count}/{total} values look like ISO dates.",
|
|
486
|
+
)
|
|
487
|
+
return "str", 1.0, "Column is treated as string unless reviewed otherwise."
|
|
488
|
+
|
|
489
|
+
|
|
490
|
+
def _regex_candidate(column: str, values: list[str]) -> ConstraintCandidate | None:
|
|
491
|
+
"""Infer a simple regex candidate for consistent identifier-like columns."""
|
|
492
|
+
if not values:
|
|
493
|
+
return None
|
|
494
|
+
if all(_DIGITS_RE.fullmatch(value) for value in values):
|
|
495
|
+
lengths = sorted({len(value) for value in values})
|
|
496
|
+
pattern = rf"^\d{{{lengths[0]}}}$" if len(lengths) == 1 else r"^\d+$"
|
|
497
|
+
elif all(_UPPER_CODE_RE.fullmatch(value) for value in values):
|
|
498
|
+
pattern = r"^[A-Z0-9_-]+$"
|
|
499
|
+
else:
|
|
500
|
+
return None
|
|
501
|
+
return ConstraintCandidate(
|
|
502
|
+
kind="regex",
|
|
503
|
+
columns=(column,),
|
|
504
|
+
pattern=pattern,
|
|
505
|
+
confidence=1.0,
|
|
506
|
+
evidence=f"{len(values)} non-empty values matched {pattern}.",
|
|
507
|
+
)
|
|
508
|
+
|
|
509
|
+
|
|
510
|
+
def _domain_candidate(column: str, values: list[str]) -> ConstraintCandidate | None:
|
|
511
|
+
"""Infer a numeric min/max domain candidate."""
|
|
512
|
+
numeric = [_try_float(value) for value in values]
|
|
513
|
+
parsed = [value for value in numeric if value is not None]
|
|
514
|
+
if len(parsed) < 3 or len(parsed) != len(values):
|
|
515
|
+
return None
|
|
516
|
+
return ConstraintCandidate(
|
|
517
|
+
kind="domain_bound",
|
|
518
|
+
columns=(column,),
|
|
519
|
+
min_value=min(parsed),
|
|
520
|
+
max_value=max(parsed),
|
|
521
|
+
confidence=1.0,
|
|
522
|
+
evidence=f"{len(parsed)} values define the observed numeric range.",
|
|
523
|
+
)
|
|
524
|
+
|
|
525
|
+
|
|
526
|
+
def _unique_candidate(column: str, values: list[str]) -> ConstraintCandidate | None:
|
|
527
|
+
"""Infer a uniqueness candidate when every non-empty value is distinct."""
|
|
528
|
+
if len(values) < 3 or len(set(values)) != len(values):
|
|
529
|
+
return None
|
|
530
|
+
return ConstraintCandidate(
|
|
531
|
+
kind="unique",
|
|
532
|
+
columns=(column,),
|
|
533
|
+
confidence=1.0,
|
|
534
|
+
evidence=f"{len(values)} non-empty values are distinct.",
|
|
535
|
+
)
|
|
536
|
+
|
|
537
|
+
|
|
538
|
+
def _fd_candidates(table: TableLike, columns: list[str]) -> list[ConstraintCandidate]:
|
|
539
|
+
"""Infer single-column functional dependencies with violation tolerance."""
|
|
540
|
+
total_rows = row_count(table)
|
|
541
|
+
if total_rows < 5:
|
|
542
|
+
return []
|
|
543
|
+
|
|
544
|
+
values_by_column = {column: _non_empty(column_values(table, column)) for column in columns}
|
|
545
|
+
candidates: list[ConstraintCandidate] = []
|
|
546
|
+
for determinant in columns:
|
|
547
|
+
determinant_values = values_by_column[determinant]
|
|
548
|
+
if len(determinant_values) != total_rows:
|
|
549
|
+
continue
|
|
550
|
+
determinant_unique = len(set(determinant_values))
|
|
551
|
+
if determinant_unique < 2 or determinant_unique == total_rows:
|
|
552
|
+
continue
|
|
553
|
+
|
|
554
|
+
for dependent in columns:
|
|
555
|
+
if dependent == determinant:
|
|
556
|
+
continue
|
|
557
|
+
dependent_values = values_by_column[dependent]
|
|
558
|
+
if len(dependent_values) != total_rows:
|
|
559
|
+
continue
|
|
560
|
+
groups: dict[str, list[str]] = defaultdict(list)
|
|
561
|
+
for det_value, dep_value in zip(determinant_values, dependent_values, strict=True):
|
|
562
|
+
groups[det_value].append(dep_value)
|
|
563
|
+
|
|
564
|
+
violations = 0
|
|
565
|
+
for group_values in groups.values():
|
|
566
|
+
most_common = Counter(group_values).most_common(1)[0][1]
|
|
567
|
+
violations += len(group_values) - most_common
|
|
568
|
+
confidence = round(1.0 - (violations / total_rows), 4)
|
|
569
|
+
if confidence < 0.9:
|
|
570
|
+
continue
|
|
571
|
+
candidates.append(
|
|
572
|
+
ConstraintCandidate(
|
|
573
|
+
kind="functional_dependency",
|
|
574
|
+
columns=(determinant,),
|
|
575
|
+
dependent=dependent,
|
|
576
|
+
confidence=confidence,
|
|
577
|
+
evidence=(
|
|
578
|
+
f"{determinant} determined {dependent} in "
|
|
579
|
+
f"{total_rows - violations}/{total_rows} rows."
|
|
580
|
+
),
|
|
581
|
+
)
|
|
582
|
+
)
|
|
583
|
+
return candidates
|
|
584
|
+
|
|
585
|
+
|
|
586
|
+
def infer_schema(table: TableLike) -> SchemaInferenceResult:
|
|
587
|
+
"""Infer reviewable schema candidates from a table-like object."""
|
|
588
|
+
columns = column_names(table)
|
|
589
|
+
inferred_columns: dict[str, str] = {}
|
|
590
|
+
candidates: list[ConstraintCandidate] = []
|
|
591
|
+
|
|
592
|
+
for column in columns:
|
|
593
|
+
values = _non_empty(column_values(table, column))
|
|
594
|
+
inferred_type, confidence, evidence = _infer_column_type(values)
|
|
595
|
+
inferred_columns[column] = inferred_type
|
|
596
|
+
candidates.append(
|
|
597
|
+
ConstraintCandidate(
|
|
598
|
+
kind="column_type",
|
|
599
|
+
columns=(column,),
|
|
600
|
+
inferred_type=inferred_type,
|
|
601
|
+
confidence=confidence,
|
|
602
|
+
evidence=evidence,
|
|
603
|
+
)
|
|
604
|
+
)
|
|
605
|
+
regex_candidate = _regex_candidate(column, values)
|
|
606
|
+
if regex_candidate is not None:
|
|
607
|
+
candidates.append(regex_candidate)
|
|
608
|
+
domain_candidate = _domain_candidate(column, values)
|
|
609
|
+
if domain_candidate is not None:
|
|
610
|
+
candidates.append(domain_candidate)
|
|
611
|
+
unique_candidate = _unique_candidate(column, values)
|
|
612
|
+
if unique_candidate is not None:
|
|
613
|
+
candidates.append(unique_candidate)
|
|
614
|
+
|
|
615
|
+
candidates.extend(_fd_candidates(table, columns))
|
|
616
|
+
return SchemaInferenceResult(
|
|
617
|
+
columns=inferred_columns,
|
|
618
|
+
candidates=candidates,
|
|
619
|
+
row_count=row_count(table),
|
|
620
|
+
)
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"""Backend-neutral table-store and patch-plan API."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataforge.stores.base import (
|
|
6
|
+
StoreApplyReceipt,
|
|
7
|
+
StoreRevertReceipt,
|
|
8
|
+
TableStore,
|
|
9
|
+
TableStoreError,
|
|
10
|
+
)
|
|
11
|
+
from dataforge.stores.cloud import CloudWarehouseStore
|
|
12
|
+
from dataforge.stores.csv import CSVStore
|
|
13
|
+
from dataforge.stores.duckdb import DuckDBStore
|
|
14
|
+
from dataforge.stores.patch_plan import (
|
|
15
|
+
CostEstimate,
|
|
16
|
+
PatchOperation,
|
|
17
|
+
PatchPlan,
|
|
18
|
+
RowIdentity,
|
|
19
|
+
)
|
|
20
|
+
from dataforge.stores.registry import (
|
|
21
|
+
TableStoreSpec,
|
|
22
|
+
is_table_store_uri,
|
|
23
|
+
parse_table_store_uri,
|
|
24
|
+
store_from_uri,
|
|
25
|
+
)
|
|
26
|
+
from dataforge.stores.repair import TableStoreRepairResult, run_table_store_repair
|
|
27
|
+
|
|
28
|
+
__all__ = [
|
|
29
|
+
"CSVStore",
|
|
30
|
+
"CloudWarehouseStore",
|
|
31
|
+
"CostEstimate",
|
|
32
|
+
"DuckDBStore",
|
|
33
|
+
"PatchOperation",
|
|
34
|
+
"PatchPlan",
|
|
35
|
+
"RowIdentity",
|
|
36
|
+
"StoreApplyReceipt",
|
|
37
|
+
"StoreRevertReceipt",
|
|
38
|
+
"TableStore",
|
|
39
|
+
"TableStoreError",
|
|
40
|
+
"TableStoreRepairResult",
|
|
41
|
+
"TableStoreSpec",
|
|
42
|
+
"is_table_store_uri",
|
|
43
|
+
"parse_table_store_uri",
|
|
44
|
+
"run_table_store_repair",
|
|
45
|
+
"store_from_uri",
|
|
46
|
+
]
|