contractgate 0.4.0__tar.gz → 0.4.2__tar.gz
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.
- {contractgate-0.4.0 → contractgate-0.4.2}/.gitignore +6 -1
- {contractgate-0.4.0 → contractgate-0.4.2}/CHANGELOG.md +48 -0
- {contractgate-0.4.0 → contractgate-0.4.2}/PKG-INFO +7 -2
- {contractgate-0.4.0 → contractgate-0.4.2}/README.md +5 -0
- {contractgate-0.4.0 → contractgate-0.4.2}/pyproject.toml +7 -2
- {contractgate-0.4.0 → contractgate-0.4.2}/src/contractgate/__init__.py +2 -0
- contractgate-0.4.2/src/contractgate/__main__.py +6 -0
- {contractgate-0.4.0 → contractgate-0.4.2}/src/contractgate/_transport.py +54 -0
- contractgate-0.4.2/src/contractgate/_version.py +1 -0
- {contractgate-0.4.0 → contractgate-0.4.2}/src/contractgate/async_client.py +39 -0
- contractgate-0.4.2/src/contractgate/cli.py +280 -0
- {contractgate-0.4.0 → contractgate-0.4.2}/src/contractgate/client.py +39 -0
- contractgate-0.4.2/src/contractgate/contract.py +811 -0
- {contractgate-0.4.0 → contractgate-0.4.2}/src/contractgate/exceptions.py +10 -0
- {contractgate-0.4.0 → contractgate-0.4.2}/src/contractgate/llm.py +155 -7
- {contractgate-0.4.0 → contractgate-0.4.2}/src/contractgate/models.py +33 -0
- contractgate-0.4.2/src/contractgate/provenance.py +275 -0
- contractgate-0.4.2/src/contractgate/validator.py +995 -0
- contractgate-0.4.2/tests/fixtures/contracts/odcs_full_example.yaml +362 -0
- contractgate-0.4.2/tests/fixtures/contracts/odcs_minimal.yaml +24 -0
- contractgate-0.4.2/tests/test_cli_review.py +28 -0
- contractgate-0.4.2/tests/test_cli_synth.py +199 -0
- {contractgate-0.4.0 → contractgate-0.4.2}/tests/test_client_sync.py +44 -0
- {contractgate-0.4.0 → contractgate-0.4.2}/tests/test_contract_parse.py +42 -0
- {contractgate-0.4.0 → contractgate-0.4.2}/tests/test_llm_gate.py +7 -3
- contractgate-0.4.2/tests/test_llm_provenance.py +385 -0
- contractgate-0.4.2/tests/test_odcs_input.py +81 -0
- contractgate-0.4.2/tests/test_parity_rfc118.py +82 -0
- {contractgate-0.4.0 → contractgate-0.4.2}/tests/test_validator.py +194 -0
- contractgate-0.4.0/src/contractgate/_version.py +0 -1
- contractgate-0.4.0/src/contractgate/contract.py +0 -426
- contractgate-0.4.0/src/contractgate/validator.py +0 -395
- {contractgate-0.4.0 → contractgate-0.4.2}/LICENSE +0 -0
- {contractgate-0.4.0 → contractgate-0.4.2}/tests/__init__.py +0 -0
- {contractgate-0.4.0 → contractgate-0.4.2}/tests/conftest.py +0 -0
- {contractgate-0.4.0 → contractgate-0.4.2}/tests/fixtures/contracts/compliance_mode.yaml +0 -0
- {contractgate-0.4.0 → contractgate-0.4.2}/tests/fixtures/contracts/user_events.yaml +0 -0
- {contractgate-0.4.0 → contractgate-0.4.2}/tests/fixtures/contracts/with_transform.yaml +0 -0
- {contractgate-0.4.0 → contractgate-0.4.2}/tests/test_client_async.py +0 -0
|
@@ -9,6 +9,7 @@ confluent-connector/*.zip.asc
|
|
|
9
9
|
# Environment
|
|
10
10
|
.env
|
|
11
11
|
.env.local
|
|
12
|
+
.selfhost/
|
|
12
13
|
|
|
13
14
|
# Node / Next.js
|
|
14
15
|
mcp/node_modules/
|
|
@@ -76,7 +77,7 @@ supabase/.temp/
|
|
|
76
77
|
docs/marketing/drafts/
|
|
77
78
|
!docs/marketing/drafts/README.md
|
|
78
79
|
|
|
79
|
-
#
|
|
80
|
+
# AI assistant hunter outbox (drafts, never sent)
|
|
80
81
|
.bot-outbox/
|
|
81
82
|
|
|
82
83
|
# Claude Code screenshot attachments (local scratch folder, never project files)
|
|
@@ -85,3 +86,7 @@ docs/marketing/drafts/
|
|
|
85
86
|
# npm auth tokens
|
|
86
87
|
.npmrc
|
|
87
88
|
*.mcpb
|
|
89
|
+
|
|
90
|
+
# Local-only output (kept out of the public repo)
|
|
91
|
+
ops/dogfood/findings/runs/
|
|
92
|
+
docs/marketing/
|
|
@@ -2,6 +2,54 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to the `contractgate` Python SDK.
|
|
4
4
|
|
|
5
|
+
## 0.4.2 (unreleased, not yet published)
|
|
6
|
+
|
|
7
|
+
- New `contractgate-py synth` command (also `python -m contractgate synth`) that
|
|
8
|
+
calls the gateway's `POST /contracts/synth` (RFC-117, RFC-118). Takes a
|
|
9
|
+
contract file or `--contract-id` / `--version`, plus `--rows`,
|
|
10
|
+
`--invalid`, `--seed`, `--anchor` (RFC 3339 time for freshness rules),
|
|
11
|
+
`--envelope` and `--format json|csv`. The key comes from `--api-key` or
|
|
12
|
+
`CONTRACTGATE_API_KEY`; the URL from `--base-url` or
|
|
13
|
+
`CONTRACTGATE_BASE_URL`. Exit 1 names an unsatisfiable rule.
|
|
14
|
+
- `Client.synth(...)` / `AsyncClient.synth(...)` for the same endpoint.
|
|
15
|
+
- The console script is `contractgate-py`, not `contractgate`, so it never
|
|
16
|
+
shadows the Rust `contractgate` binary when both are installed.
|
|
17
|
+
- The local validator (`Contract.compile()` / `validate`) now enforces
|
|
18
|
+
`cross_field:` rules (including per-item `lines[].qty` paths), quality
|
|
19
|
+
`completeness` and `freshness` rules, patterns inside array items, and
|
|
20
|
+
`null_as_absent`, and counts string lengths in UTF-8 bytes. Results match
|
|
21
|
+
the gateway on the shared parity corpus (`tests/fixtures/parity/rfc118.json`).
|
|
22
|
+
`validate(..., now=...)` pins the clock for freshness.
|
|
23
|
+
- `Cargo.toml` and `mcp/` are at 0.4.2 too, so a `v0.4.2` tag passes the
|
|
24
|
+
release version checks.
|
|
25
|
+
- Fix: repair hints no longer create two user messages in a row. When the
|
|
26
|
+
conversation ends with a user turn, `LLMGate` / `AsyncLLMGate` fold the
|
|
27
|
+
hint into that turn (string content or an extra text content part), so
|
|
28
|
+
roles keep alternating. Chat templates such as Gemma's rejected the old
|
|
29
|
+
shape with "Conversation roles must alternate".
|
|
30
|
+
- `LLMGate` / `AsyncLLMGate` check repaired output for invented values.
|
|
31
|
+
After a repair attempt passes the contract, identifier and amount fields
|
|
32
|
+
whose value does not occur in the source text are set to `null` (or left
|
|
33
|
+
out, if the contract rejects `null`) and the payload is validated again.
|
|
34
|
+
If the contract still fails, the attempt fails with the new client-side
|
|
35
|
+
violation kind `provenance_violation` and the model is re-prompted while
|
|
36
|
+
retries remain. On by default; configure with
|
|
37
|
+
`provenance=ProvenanceCheck(...)` or turn off with `provenance=False`.
|
|
38
|
+
`completion` / `message` accept `source_text=` (default: the user
|
|
39
|
+
messages). Findings are on `LLMGateResult.provenance`. The package
|
|
40
|
+
version stays 0.4.1.
|
|
41
|
+
- The local validator enforces `format: email`, `uuid`, and `uri` / `url`
|
|
42
|
+
with the same rules as the Rust engine. Unknown format names still pass.
|
|
43
|
+
The package version stays 0.4.1: a release tag must match both
|
|
44
|
+
`Cargo.toml` and `pyproject.toml`, and this fix does not ship on its own.
|
|
45
|
+
- `type: date` and `type: timestamp` parse and validate with the same rules
|
|
46
|
+
as the Rust engine (`YYYY-MM-DD` calendar dates, RFC 3339 date-times,
|
|
47
|
+
including offsets and leap days). The package version stays 0.4.1.
|
|
48
|
+
|
|
49
|
+
## 0.4.1 — 2026-10-28
|
|
50
|
+
|
|
51
|
+
Version alignment with DataContractGate 0.4.1. No SDK API changes.
|
|
52
|
+
|
|
5
53
|
## 0.4.0 — 2026-10-13
|
|
6
54
|
|
|
7
55
|
- `ingest` now posts to `/v1/ingest/{contract_id}` (was the legacy
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: contractgate
|
|
3
|
-
Version: 0.4.
|
|
4
|
-
Summary: Python SDK for DataContractGate
|
|
3
|
+
Version: 0.4.2
|
|
4
|
+
Summary: Python SDK for DataContractGate: high-performance semantic contract enforcement gateway.
|
|
5
5
|
Project-URL: Homepage, https://datacontractgate.com
|
|
6
6
|
Project-URL: Source, https://github.com/nightmoose/contractgate
|
|
7
7
|
Author: NightMoose, Inc.
|
|
@@ -119,6 +119,11 @@ config if contracts live elsewhere.
|
|
|
119
119
|
|
|
120
120
|
## Caveats
|
|
121
121
|
|
|
122
|
+
- **Local validator enforces `format: email`, `uuid`, and `uri`/`url`**
|
|
123
|
+
the same way the Rust engine does. Any other `format` name is metadata
|
|
124
|
+
and passes. `type: date` is a real `YYYY-MM-DD` calendar date and
|
|
125
|
+
`type: timestamp` is an RFC 3339 date-time, matching the Rust engine
|
|
126
|
+
(timezone offsets, leap days, and the same rejections).
|
|
122
127
|
- **Local validator does not run RFC-004 PII transforms** (`mask`,
|
|
123
128
|
`hash`, `drop`, `redact`). The per-contract salt is server-side
|
|
124
129
|
only. The gateway is the single source of truth for the
|
|
@@ -89,6 +89,11 @@ config if contracts live elsewhere.
|
|
|
89
89
|
|
|
90
90
|
## Caveats
|
|
91
91
|
|
|
92
|
+
- **Local validator enforces `format: email`, `uuid`, and `uri`/`url`**
|
|
93
|
+
the same way the Rust engine does. Any other `format` name is metadata
|
|
94
|
+
and passes. `type: date` is a real `YYYY-MM-DD` calendar date and
|
|
95
|
+
`type: timestamp` is an RFC 3339 date-time, matching the Rust engine
|
|
96
|
+
(timezone offsets, leap days, and the same rejections).
|
|
92
97
|
- **Local validator does not run RFC-004 PII transforms** (`mask`,
|
|
93
98
|
`hash`, `drop`, `redact`). The per-contract salt is server-side
|
|
94
99
|
only. The gateway is the single source of truth for the
|
|
@@ -4,8 +4,8 @@ build-backend = "hatchling.build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "contractgate"
|
|
7
|
-
version = "0.4.
|
|
8
|
-
description = "Python SDK for DataContractGate
|
|
7
|
+
version = "0.4.2"
|
|
8
|
+
description = "Python SDK for DataContractGate: high-performance semantic contract enforcement gateway."
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.9"
|
|
11
11
|
license = { text = "MIT" }
|
|
@@ -36,6 +36,11 @@ dev = [
|
|
|
36
36
|
"ruff>=0.5",
|
|
37
37
|
]
|
|
38
38
|
|
|
39
|
+
[project.scripts]
|
|
40
|
+
# Not "contractgate": that name belongs to the Rust CLI binary. Also runs as
|
|
41
|
+
# `python -m contractgate`.
|
|
42
|
+
contractgate-py = "contractgate.cli:main_exit"
|
|
43
|
+
|
|
39
44
|
[project.urls]
|
|
40
45
|
Homepage = "https://datacontractgate.com"
|
|
41
46
|
Source = "https://github.com/nightmoose/contractgate"
|
|
@@ -52,6 +52,7 @@ from contractgate.exceptions import (
|
|
|
52
52
|
ContractGateError,
|
|
53
53
|
HTTPError,
|
|
54
54
|
NotFoundError,
|
|
55
|
+
PlanRequiredError,
|
|
55
56
|
ServerError,
|
|
56
57
|
ValidationFailedError,
|
|
57
58
|
)
|
|
@@ -106,6 +107,7 @@ __all__ = [
|
|
|
106
107
|
"NotFoundError",
|
|
107
108
|
"ConflictError",
|
|
108
109
|
"ValidationFailedError",
|
|
110
|
+
"PlanRequiredError",
|
|
109
111
|
"ServerError",
|
|
110
112
|
"ConnectionError",
|
|
111
113
|
"ContractCompileError",
|
|
@@ -83,6 +83,7 @@ def build_ingest_request(
|
|
|
83
83
|
version: Optional[str] = None,
|
|
84
84
|
dry_run: bool = False,
|
|
85
85
|
atomic: bool = False,
|
|
86
|
+
on_fail: Optional[str] = None,
|
|
86
87
|
timeout: Optional[float] = None,
|
|
87
88
|
) -> RequestSpec:
|
|
88
89
|
"""Build a POST to ``/v1/ingest/{contract_id}``.
|
|
@@ -109,6 +110,8 @@ def build_ingest_request(
|
|
|
109
110
|
params["dry_run"] = "true"
|
|
110
111
|
if atomic:
|
|
111
112
|
params["atomic"] = "true"
|
|
113
|
+
if on_fail is not None:
|
|
114
|
+
params["on_fail"] = on_fail
|
|
112
115
|
return RequestSpec(
|
|
113
116
|
method="POST",
|
|
114
117
|
url=cfg.url(path),
|
|
@@ -127,6 +130,7 @@ def build_egress_request(
|
|
|
127
130
|
version: Optional[str] = None,
|
|
128
131
|
disposition: Optional[str] = None,
|
|
129
132
|
dry_run: bool = False,
|
|
133
|
+
on_fail: Optional[str] = None,
|
|
130
134
|
timeout: Optional[float] = None,
|
|
131
135
|
) -> RequestSpec:
|
|
132
136
|
"""Build a POST to ``/egress/{contract_id}``."""
|
|
@@ -138,6 +142,8 @@ def build_egress_request(
|
|
|
138
142
|
params["dry_run"] = "true"
|
|
139
143
|
if disposition is not None:
|
|
140
144
|
params["disposition"] = disposition
|
|
145
|
+
if on_fail is not None:
|
|
146
|
+
params["on_fail"] = on_fail
|
|
141
147
|
return RequestSpec(
|
|
142
148
|
method="POST",
|
|
143
149
|
url=cfg.url(f"/egress/{contract_id}"),
|
|
@@ -281,6 +287,54 @@ def build_playground_request(
|
|
|
281
287
|
)
|
|
282
288
|
|
|
283
289
|
|
|
290
|
+
def build_synth_request(
|
|
291
|
+
cfg: TransportConfig,
|
|
292
|
+
body: Dict[str, Any],
|
|
293
|
+
*,
|
|
294
|
+
timeout: Optional[float] = None,
|
|
295
|
+
) -> RequestSpec:
|
|
296
|
+
return RequestSpec(
|
|
297
|
+
method="POST",
|
|
298
|
+
url=cfg.url("/contracts/synth"),
|
|
299
|
+
headers=cfg.headers({"Content-Type": "application/json"}),
|
|
300
|
+
params=None,
|
|
301
|
+
json_body=body,
|
|
302
|
+
timeout=timeout if timeout is not None else cfg.timeout,
|
|
303
|
+
)
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def synth_body(
|
|
307
|
+
*,
|
|
308
|
+
yaml_content: Optional[str] = None,
|
|
309
|
+
contract_id: Optional[str] = None,
|
|
310
|
+
version: Optional[str] = None,
|
|
311
|
+
rows: int = 100,
|
|
312
|
+
mode: str = "valid",
|
|
313
|
+
seed: Optional[int] = None,
|
|
314
|
+
anchor_time: Optional[str] = None,
|
|
315
|
+
envelope: bool = False,
|
|
316
|
+
) -> Dict[str, Any]:
|
|
317
|
+
"""Request body for ``POST /contracts/synth`` (RFC-117, RFC-118)."""
|
|
318
|
+
if (yaml_content is None) == (contract_id is None):
|
|
319
|
+
raise ValueError("pass exactly one of yaml_content or contract_id")
|
|
320
|
+
if mode not in ("valid", "invalid"):
|
|
321
|
+
raise ValueError("mode must be 'valid' or 'invalid'")
|
|
322
|
+
body: Dict[str, Any] = {"rows": rows, "mode": mode}
|
|
323
|
+
if yaml_content is not None:
|
|
324
|
+
body["yaml_content"] = yaml_content
|
|
325
|
+
if contract_id is not None:
|
|
326
|
+
body["contract_id"] = contract_id
|
|
327
|
+
if version is not None:
|
|
328
|
+
body["version"] = version
|
|
329
|
+
if seed is not None:
|
|
330
|
+
body["seed"] = seed
|
|
331
|
+
if anchor_time is not None:
|
|
332
|
+
body["anchor_time"] = anchor_time
|
|
333
|
+
if envelope:
|
|
334
|
+
body["envelope"] = True
|
|
335
|
+
return body
|
|
336
|
+
|
|
337
|
+
|
|
284
338
|
# ---------------------------------------------------------------------------
|
|
285
339
|
# Response decoding
|
|
286
340
|
# ---------------------------------------------------------------------------
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.4.2"
|
|
@@ -76,6 +76,7 @@ class AsyncClient:
|
|
|
76
76
|
version: Optional[str] = None,
|
|
77
77
|
dry_run: bool = False,
|
|
78
78
|
atomic: bool = False,
|
|
79
|
+
on_fail: Optional[str] = None,
|
|
79
80
|
timeout: Optional[float] = None,
|
|
80
81
|
) -> BatchIngestResponse:
|
|
81
82
|
spec = _t.build_ingest_request(
|
|
@@ -85,6 +86,7 @@ class AsyncClient:
|
|
|
85
86
|
version=version,
|
|
86
87
|
dry_run=dry_run,
|
|
87
88
|
atomic=atomic,
|
|
89
|
+
on_fail=on_fail,
|
|
88
90
|
timeout=timeout,
|
|
89
91
|
)
|
|
90
92
|
try:
|
|
@@ -103,6 +105,7 @@ class AsyncClient:
|
|
|
103
105
|
version: Optional[str] = None,
|
|
104
106
|
disposition: Optional[str] = None,
|
|
105
107
|
dry_run: bool = False,
|
|
108
|
+
on_fail: Optional[str] = None,
|
|
106
109
|
timeout: Optional[float] = None,
|
|
107
110
|
) -> EgressResponse:
|
|
108
111
|
"""Validate an outbound payload via ``POST /egress/{contract_id}``.
|
|
@@ -117,6 +120,7 @@ class AsyncClient:
|
|
|
117
120
|
version=version,
|
|
118
121
|
disposition=disposition,
|
|
119
122
|
dry_run=dry_run,
|
|
123
|
+
on_fail=on_fail,
|
|
120
124
|
timeout=timeout,
|
|
121
125
|
)
|
|
122
126
|
_, body = await self._dispatch(spec)
|
|
@@ -220,6 +224,41 @@ class AsyncClient:
|
|
|
220
224
|
_, body = await self._dispatch(spec)
|
|
221
225
|
return body
|
|
222
226
|
|
|
227
|
+
async def synth(
|
|
228
|
+
self,
|
|
229
|
+
*,
|
|
230
|
+
yaml_content: Optional[str] = None,
|
|
231
|
+
contract_id: Optional[str] = None,
|
|
232
|
+
version: Optional[str] = None,
|
|
233
|
+
rows: int = 100,
|
|
234
|
+
mode: str = "valid",
|
|
235
|
+
seed: Optional[int] = None,
|
|
236
|
+
anchor_time: Optional[str] = None,
|
|
237
|
+
envelope: bool = False,
|
|
238
|
+
timeout: Optional[float] = None,
|
|
239
|
+
) -> Any:
|
|
240
|
+
"""Generate synthetic rows from a contract (``POST /contracts/synth``).
|
|
241
|
+
|
|
242
|
+
Pass ``yaml_content`` or ``contract_id`` (plus optional ``version``).
|
|
243
|
+
``mode="invalid"`` returns rows that each break exactly one rule,
|
|
244
|
+
labeled with it. ``seed`` plus ``anchor_time`` (RFC 3339) make the
|
|
245
|
+
output repeat exactly. ``envelope=True`` adds ``envelope_payload``.
|
|
246
|
+
Returns the raw JSON response.
|
|
247
|
+
"""
|
|
248
|
+
body = _t.synth_body(
|
|
249
|
+
yaml_content=yaml_content,
|
|
250
|
+
contract_id=contract_id,
|
|
251
|
+
version=version,
|
|
252
|
+
rows=rows,
|
|
253
|
+
mode=mode,
|
|
254
|
+
seed=seed,
|
|
255
|
+
anchor_time=anchor_time,
|
|
256
|
+
envelope=envelope,
|
|
257
|
+
)
|
|
258
|
+
spec = _t.build_synth_request(self._cfg, body, timeout=timeout)
|
|
259
|
+
_, resp = await self._dispatch(spec)
|
|
260
|
+
return resp
|
|
261
|
+
|
|
223
262
|
# ------------------------------------------------------------------
|
|
224
263
|
# Internals
|
|
225
264
|
# ------------------------------------------------------------------
|
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
"""``contractgate-py`` command line (Python SDK).
|
|
2
|
+
|
|
3
|
+
Installed as the ``contractgate-py`` console script and also runnable as
|
|
4
|
+
``python -m contractgate``. It is deliberately not called ``contractgate``:
|
|
5
|
+
that name belongs to the Rust CLI binary, and both can sit on one PATH.
|
|
6
|
+
|
|
7
|
+
Subcommands:
|
|
8
|
+
|
|
9
|
+
contractgate-py synth CONTRACT.yaml --rows 100 [--invalid] [--seed N]
|
|
10
|
+
[--anchor 2026-01-01T00:00:00Z] [--envelope] [--format json|csv] [-o FILE]
|
|
11
|
+
contractgate-py synth --contract-id UUID [--version 1.2.0] ...
|
|
12
|
+
contractgate-py review FILE.csv [--out DIR] [--name NAME]
|
|
13
|
+
|
|
14
|
+
``synth`` calls the gateway's ``POST /contracts/synth`` (RFC-117, RFC-118).
|
|
15
|
+
Rows come only from the contract's rules; no stored data is read.
|
|
16
|
+
|
|
17
|
+
``review`` shells out to the Rust ``contractgate review`` CLI (the binary
|
|
18
|
+
must be on PATH) and writes a Readiness Review report from a CSV.
|
|
19
|
+
|
|
20
|
+
The API key comes from ``--api-key`` or ``CONTRACTGATE_API_KEY``; the
|
|
21
|
+
gateway URL from ``--base-url`` or ``CONTRACTGATE_BASE_URL``.
|
|
22
|
+
|
|
23
|
+
Exit codes:
|
|
24
|
+
0 rows written
|
|
25
|
+
1 a contract rule cannot be satisfied (the error names the rule)
|
|
26
|
+
2 bad arguments, unreadable contract, or any other API error
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
from __future__ import annotations
|
|
30
|
+
|
|
31
|
+
import argparse
|
|
32
|
+
import csv
|
|
33
|
+
import io
|
|
34
|
+
import json
|
|
35
|
+
import os
|
|
36
|
+
import shutil
|
|
37
|
+
import subprocess
|
|
38
|
+
import sys
|
|
39
|
+
from typing import Any, Dict, List, Optional, Sequence, Tuple
|
|
40
|
+
|
|
41
|
+
import httpx
|
|
42
|
+
|
|
43
|
+
from contractgate._version import __version__
|
|
44
|
+
from contractgate.client import Client
|
|
45
|
+
from contractgate.exceptions import ContractGateError, HTTPError
|
|
46
|
+
|
|
47
|
+
DEFAULT_BASE_URL = "https://api.datacontractgate.com"
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _parser() -> argparse.ArgumentParser:
|
|
51
|
+
p = argparse.ArgumentParser(
|
|
52
|
+
prog="contractgate-py",
|
|
53
|
+
description="DataContractGate command line (Python SDK).",
|
|
54
|
+
)
|
|
55
|
+
p.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
|
|
56
|
+
sub = p.add_subparsers(dest="command", required=True)
|
|
57
|
+
|
|
58
|
+
s = sub.add_parser(
|
|
59
|
+
"synth",
|
|
60
|
+
help="Generate synthetic rows from a contract's rules via the API.",
|
|
61
|
+
description="Generate synthetic rows from a contract's rules via the API.",
|
|
62
|
+
)
|
|
63
|
+
s.add_argument("contract", nargs="?", help="Path to a contract YAML file.")
|
|
64
|
+
s.add_argument("--contract-id", help="A stored contract in your org (instead of a file).")
|
|
65
|
+
s.add_argument("--version", dest="contract_version", help="Version of --contract-id.")
|
|
66
|
+
s.add_argument("--rows", type=int, default=100, help="1 to 10000 (default 100).")
|
|
67
|
+
s.add_argument(
|
|
68
|
+
"--invalid",
|
|
69
|
+
action="store_true",
|
|
70
|
+
help="Rows that each break exactly one rule, labeled with it.",
|
|
71
|
+
)
|
|
72
|
+
s.add_argument("--seed", type=int, help="Seed for repeatable output.")
|
|
73
|
+
s.add_argument(
|
|
74
|
+
"--anchor",
|
|
75
|
+
metavar="RFC3339",
|
|
76
|
+
help="Time freshness rules are measured from (default now). "
|
|
77
|
+
"Set it with --seed for output that repeats exactly.",
|
|
78
|
+
)
|
|
79
|
+
s.add_argument(
|
|
80
|
+
"--envelope",
|
|
81
|
+
action="store_true",
|
|
82
|
+
help="Wrap rows in the contract's envelope (JSON only).",
|
|
83
|
+
)
|
|
84
|
+
s.add_argument("--format", choices=["json", "csv"], default="json")
|
|
85
|
+
s.add_argument("-o", "--out", metavar="FILE", help="Write here instead of stdout.")
|
|
86
|
+
s.add_argument("--api-key", help="API key (default: $CONTRACTGATE_API_KEY).")
|
|
87
|
+
s.add_argument(
|
|
88
|
+
"--base-url",
|
|
89
|
+
help=f"Gateway URL (default: $CONTRACTGATE_BASE_URL or {DEFAULT_BASE_URL}).",
|
|
90
|
+
)
|
|
91
|
+
s.add_argument("--timeout", type=float, default=120.0, help="Seconds (default 120).")
|
|
92
|
+
|
|
93
|
+
r = sub.add_parser(
|
|
94
|
+
"review",
|
|
95
|
+
help="Infer a draft contract from a CSV and write a Readiness Review report.",
|
|
96
|
+
description=(
|
|
97
|
+
"Thin wrapper around the Rust `contractgate review` CLI. "
|
|
98
|
+
"The Rust binary must be on PATH. It infers a draft contract, "
|
|
99
|
+
"validates every row, and writes contract.yaml, report.html, "
|
|
100
|
+
"and rejected.csv."
|
|
101
|
+
),
|
|
102
|
+
)
|
|
103
|
+
r.add_argument("file", help="Path to the CSV file.")
|
|
104
|
+
r.add_argument("-o", "--out", help="Output directory.")
|
|
105
|
+
r.add_argument("--name", help="Name for the inferred contract.")
|
|
106
|
+
return p
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _flatten(value: Any, prefix: str, out: List[Tuple[str, str]]) -> None:
|
|
110
|
+
"""Nested objects become dot-path columns; arrays are JSON text.
|
|
111
|
+
|
|
112
|
+
Matches the Rust CLI's CSV layout.
|
|
113
|
+
"""
|
|
114
|
+
if isinstance(value, dict) and (value or not prefix):
|
|
115
|
+
for k, v in value.items():
|
|
116
|
+
_flatten(v, f"{prefix}.{k}" if prefix else k, out)
|
|
117
|
+
return
|
|
118
|
+
if value is None:
|
|
119
|
+
cell = ""
|
|
120
|
+
elif isinstance(value, bool):
|
|
121
|
+
cell = "true" if value else "false"
|
|
122
|
+
elif isinstance(value, str):
|
|
123
|
+
cell = value
|
|
124
|
+
elif isinstance(value, (list, dict)):
|
|
125
|
+
cell = json.dumps(value, separators=(",", ":"))
|
|
126
|
+
else:
|
|
127
|
+
cell = json.dumps(value)
|
|
128
|
+
out.append((prefix, cell))
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def to_csv(body: Dict[str, Any]) -> str:
|
|
132
|
+
rows: List[List[Tuple[str, str]]] = []
|
|
133
|
+
for r in body.get("rows") or []:
|
|
134
|
+
cells: List[Tuple[str, str]] = []
|
|
135
|
+
if body.get("mode") == "invalid":
|
|
136
|
+
_flatten(r.get("record"), "", cells)
|
|
137
|
+
br = r.get("broken_rule") or {}
|
|
138
|
+
cells.append(("_broken_field", str(br.get("field", ""))))
|
|
139
|
+
cells.append(("_broken_rule", str(br.get("rule", ""))))
|
|
140
|
+
else:
|
|
141
|
+
_flatten(r, "", cells)
|
|
142
|
+
rows.append(cells)
|
|
143
|
+
header: List[str] = []
|
|
144
|
+
for cells in rows:
|
|
145
|
+
for k, _ in cells:
|
|
146
|
+
if k not in header:
|
|
147
|
+
header.append(k)
|
|
148
|
+
buf = io.StringIO()
|
|
149
|
+
w = csv.writer(buf, lineterminator="\n")
|
|
150
|
+
w.writerow(header)
|
|
151
|
+
for cells in rows:
|
|
152
|
+
d = dict(cells)
|
|
153
|
+
w.writerow([d.get(h, "") for h in header])
|
|
154
|
+
return buf.getvalue()
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _render(body: Dict[str, Any], args: argparse.Namespace) -> str:
|
|
158
|
+
if args.format == "csv":
|
|
159
|
+
return to_csv(body)
|
|
160
|
+
if args.envelope:
|
|
161
|
+
payload = body.get("envelope_payload")
|
|
162
|
+
if args.invalid:
|
|
163
|
+
labels = [r.get("broken_rule") for r in body.get("rows") or []]
|
|
164
|
+
out: Any = {"payload": payload, "labels": labels}
|
|
165
|
+
else:
|
|
166
|
+
out = payload
|
|
167
|
+
else:
|
|
168
|
+
out = body.get("rows")
|
|
169
|
+
return json.dumps(out, indent=2) + "\n"
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _synth(args: argparse.Namespace, transport: Optional[httpx.BaseTransport]) -> int:
|
|
173
|
+
if (args.contract is None) == (args.contract_id is None):
|
|
174
|
+
print("error: pass a contract file or --contract-id (not both)", file=sys.stderr)
|
|
175
|
+
return 2
|
|
176
|
+
if args.envelope and args.format == "csv":
|
|
177
|
+
print("error: --envelope needs --format json", file=sys.stderr)
|
|
178
|
+
return 2
|
|
179
|
+
yaml_content = None
|
|
180
|
+
if args.contract is not None:
|
|
181
|
+
try:
|
|
182
|
+
with open(args.contract, encoding="utf-8") as f:
|
|
183
|
+
yaml_content = f.read()
|
|
184
|
+
except OSError as e:
|
|
185
|
+
print(f"error: cannot read {args.contract}: {e}", file=sys.stderr)
|
|
186
|
+
return 2
|
|
187
|
+
api_key = args.api_key or os.environ.get("CONTRACTGATE_API_KEY")
|
|
188
|
+
base_url = args.base_url or os.environ.get("CONTRACTGATE_BASE_URL") or DEFAULT_BASE_URL
|
|
189
|
+
try:
|
|
190
|
+
with Client(
|
|
191
|
+
base_url=base_url, api_key=api_key, timeout=args.timeout, transport=transport
|
|
192
|
+
) as cg:
|
|
193
|
+
body = cg.synth(
|
|
194
|
+
yaml_content=yaml_content,
|
|
195
|
+
contract_id=args.contract_id,
|
|
196
|
+
version=args.contract_version,
|
|
197
|
+
rows=args.rows,
|
|
198
|
+
mode="invalid" if args.invalid else "valid",
|
|
199
|
+
seed=args.seed,
|
|
200
|
+
anchor_time=args.anchor,
|
|
201
|
+
envelope=args.envelope,
|
|
202
|
+
)
|
|
203
|
+
except HTTPError as e:
|
|
204
|
+
b = e.body if isinstance(e.body, dict) else {}
|
|
205
|
+
if b.get("error") == "unsatisfiable_rule":
|
|
206
|
+
field = f" on '{b['field']}'" if b.get("field") else ""
|
|
207
|
+
print(f"error: rule '{b.get('rule')}'{field}: {b.get('message')}", file=sys.stderr)
|
|
208
|
+
return 1
|
|
209
|
+
detail = b.get("message") or b.get("error") or str(e)
|
|
210
|
+
print(f"error: HTTP {e.status}: {detail}", file=sys.stderr)
|
|
211
|
+
return 2
|
|
212
|
+
except (ContractGateError, ValueError) as e:
|
|
213
|
+
print(f"error: {e}", file=sys.stderr)
|
|
214
|
+
return 2
|
|
215
|
+
|
|
216
|
+
if args.seed is None:
|
|
217
|
+
print(f"seed: {body.get('seed')}", file=sys.stderr)
|
|
218
|
+
for s in body.get("skipped_rules") or []:
|
|
219
|
+
print(
|
|
220
|
+
f"note: no row breaks the {s.get('rule')} rule on '{s.get('field')}': "
|
|
221
|
+
f"{s.get('reason')}",
|
|
222
|
+
file=sys.stderr,
|
|
223
|
+
)
|
|
224
|
+
text = _render(body, args)
|
|
225
|
+
if args.out:
|
|
226
|
+
with open(args.out, "w", encoding="utf-8", newline="") as f:
|
|
227
|
+
f.write(text)
|
|
228
|
+
else:
|
|
229
|
+
sys.stdout.write(text)
|
|
230
|
+
return 0
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def _review(args: argparse.Namespace) -> int:
|
|
235
|
+
"""Shell out to the Rust ``contractgate review`` CLI.
|
|
236
|
+
|
|
237
|
+
Inference and the HTML report live in the Rust binary. This wrapper
|
|
238
|
+
exists so ``contractgate-py review`` works when both CLIs are installed.
|
|
239
|
+
"""
|
|
240
|
+
rust = shutil.which("contractgate")
|
|
241
|
+
if not rust:
|
|
242
|
+
sys.stderr.write(
|
|
243
|
+
"error: `contractgate` (the Rust CLI) was not found on PATH. "
|
|
244
|
+
"Build it with `cargo build --release --bin contractgate` and "
|
|
245
|
+
"put target/release on PATH, then re-run.\n"
|
|
246
|
+
)
|
|
247
|
+
return 2
|
|
248
|
+
cmd = [rust, "review", args.file]
|
|
249
|
+
if args.out:
|
|
250
|
+
cmd.extend(["--out", args.out])
|
|
251
|
+
if args.name:
|
|
252
|
+
cmd.extend(["--name", args.name])
|
|
253
|
+
try:
|
|
254
|
+
proc = subprocess.run(cmd, check=False)
|
|
255
|
+
except OSError as e:
|
|
256
|
+
sys.stderr.write(f"error: running {rust}: {e}\n")
|
|
257
|
+
return 2
|
|
258
|
+
return proc.returncode
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def main(
|
|
262
|
+
argv: Optional[Sequence[str]] = None,
|
|
263
|
+
*,
|
|
264
|
+
transport: Optional[httpx.BaseTransport] = None,
|
|
265
|
+
) -> int:
|
|
266
|
+
"""Entry point. ``transport`` lets tests swap in ``httpx.MockTransport``."""
|
|
267
|
+
args = _parser().parse_args(argv)
|
|
268
|
+
if args.command == "synth":
|
|
269
|
+
return _synth(args, transport)
|
|
270
|
+
if args.command == "review":
|
|
271
|
+
return _review(args)
|
|
272
|
+
return 2 # pragma: no cover - argparse enforces a subcommand
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def main_exit() -> None: # pragma: no cover - console script shim
|
|
276
|
+
sys.exit(main())
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
if __name__ == "__main__": # pragma: no cover
|
|
280
|
+
main_exit()
|
|
@@ -82,6 +82,7 @@ class Client:
|
|
|
82
82
|
version: Optional[str] = None,
|
|
83
83
|
dry_run: bool = False,
|
|
84
84
|
atomic: bool = False,
|
|
85
|
+
on_fail: Optional[str] = None,
|
|
85
86
|
timeout: Optional[float] = None,
|
|
86
87
|
) -> BatchIngestResponse:
|
|
87
88
|
"""Validate + persist a batch via ``POST /v1/ingest/{contract_id}``.
|
|
@@ -102,6 +103,7 @@ class Client:
|
|
|
102
103
|
version=version,
|
|
103
104
|
dry_run=dry_run,
|
|
104
105
|
atomic=atomic,
|
|
106
|
+
on_fail=on_fail,
|
|
105
107
|
timeout=timeout,
|
|
106
108
|
)
|
|
107
109
|
try:
|
|
@@ -120,6 +122,7 @@ class Client:
|
|
|
120
122
|
version: Optional[str] = None,
|
|
121
123
|
disposition: Optional[str] = None,
|
|
122
124
|
dry_run: bool = False,
|
|
125
|
+
on_fail: Optional[str] = None,
|
|
123
126
|
timeout: Optional[float] = None,
|
|
124
127
|
) -> EgressResponse:
|
|
125
128
|
"""Validate an outbound payload via ``POST /egress/{contract_id}``.
|
|
@@ -134,6 +137,7 @@ class Client:
|
|
|
134
137
|
version=version,
|
|
135
138
|
disposition=disposition,
|
|
136
139
|
dry_run=dry_run,
|
|
140
|
+
on_fail=on_fail,
|
|
137
141
|
timeout=timeout,
|
|
138
142
|
)
|
|
139
143
|
_, body = self._dispatch(spec)
|
|
@@ -250,6 +254,41 @@ class Client:
|
|
|
250
254
|
_, body = self._dispatch(spec)
|
|
251
255
|
return body
|
|
252
256
|
|
|
257
|
+
def synth(
|
|
258
|
+
self,
|
|
259
|
+
*,
|
|
260
|
+
yaml_content: Optional[str] = None,
|
|
261
|
+
contract_id: Optional[str] = None,
|
|
262
|
+
version: Optional[str] = None,
|
|
263
|
+
rows: int = 100,
|
|
264
|
+
mode: str = "valid",
|
|
265
|
+
seed: Optional[int] = None,
|
|
266
|
+
anchor_time: Optional[str] = None,
|
|
267
|
+
envelope: bool = False,
|
|
268
|
+
timeout: Optional[float] = None,
|
|
269
|
+
) -> Any:
|
|
270
|
+
"""Generate synthetic rows from a contract (``POST /contracts/synth``).
|
|
271
|
+
|
|
272
|
+
Pass ``yaml_content`` or ``contract_id`` (plus optional ``version``).
|
|
273
|
+
``mode="invalid"`` returns rows that each break exactly one rule,
|
|
274
|
+
labeled with it. ``seed`` plus ``anchor_time`` (RFC 3339) make the
|
|
275
|
+
output repeat exactly. ``envelope=True`` adds ``envelope_payload``.
|
|
276
|
+
Returns the raw JSON response.
|
|
277
|
+
"""
|
|
278
|
+
body = _t.synth_body(
|
|
279
|
+
yaml_content=yaml_content,
|
|
280
|
+
contract_id=contract_id,
|
|
281
|
+
version=version,
|
|
282
|
+
rows=rows,
|
|
283
|
+
mode=mode,
|
|
284
|
+
seed=seed,
|
|
285
|
+
anchor_time=anchor_time,
|
|
286
|
+
envelope=envelope,
|
|
287
|
+
)
|
|
288
|
+
spec = _t.build_synth_request(self._cfg, body, timeout=timeout)
|
|
289
|
+
_, resp = self._dispatch(spec)
|
|
290
|
+
return resp
|
|
291
|
+
|
|
253
292
|
# ------------------------------------------------------------------
|
|
254
293
|
# Internals
|
|
255
294
|
# ------------------------------------------------------------------
|