contractgate 0.3.2__tar.gz → 0.4.0__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.
Files changed (27) hide show
  1. {contractgate-0.3.2 → contractgate-0.4.0}/CHANGELOG.md +12 -0
  2. {contractgate-0.3.2 → contractgate-0.4.0}/PKG-INFO +2 -2
  3. {contractgate-0.3.2 → contractgate-0.4.0}/README.md +1 -1
  4. {contractgate-0.3.2 → contractgate-0.4.0}/pyproject.toml +1 -1
  5. {contractgate-0.3.2 → contractgate-0.4.0}/src/contractgate/_transport.py +29 -10
  6. contractgate-0.4.0/src/contractgate/_version.py +1 -0
  7. {contractgate-0.3.2 → contractgate-0.4.0}/src/contractgate/async_client.py +7 -1
  8. {contractgate-0.3.2 → contractgate-0.4.0}/src/contractgate/client.py +15 -8
  9. {contractgate-0.3.2 → contractgate-0.4.0}/src/contractgate/models.py +6 -0
  10. {contractgate-0.3.2 → contractgate-0.4.0}/tests/test_client_async.py +19 -1
  11. {contractgate-0.3.2 → contractgate-0.4.0}/tests/test_client_sync.py +41 -6
  12. contractgate-0.3.2/src/contractgate/_version.py +0 -1
  13. {contractgate-0.3.2 → contractgate-0.4.0}/.gitignore +0 -0
  14. {contractgate-0.3.2 → contractgate-0.4.0}/LICENSE +0 -0
  15. {contractgate-0.3.2 → contractgate-0.4.0}/src/contractgate/__init__.py +0 -0
  16. {contractgate-0.3.2 → contractgate-0.4.0}/src/contractgate/contract.py +0 -0
  17. {contractgate-0.3.2 → contractgate-0.4.0}/src/contractgate/exceptions.py +0 -0
  18. {contractgate-0.3.2 → contractgate-0.4.0}/src/contractgate/llm.py +0 -0
  19. {contractgate-0.3.2 → contractgate-0.4.0}/src/contractgate/validator.py +0 -0
  20. {contractgate-0.3.2 → contractgate-0.4.0}/tests/__init__.py +0 -0
  21. {contractgate-0.3.2 → contractgate-0.4.0}/tests/conftest.py +0 -0
  22. {contractgate-0.3.2 → contractgate-0.4.0}/tests/fixtures/contracts/compliance_mode.yaml +0 -0
  23. {contractgate-0.3.2 → contractgate-0.4.0}/tests/fixtures/contracts/user_events.yaml +0 -0
  24. {contractgate-0.3.2 → contractgate-0.4.0}/tests/fixtures/contracts/with_transform.yaml +0 -0
  25. {contractgate-0.3.2 → contractgate-0.4.0}/tests/test_contract_parse.py +0 -0
  26. {contractgate-0.3.2 → contractgate-0.4.0}/tests/test_llm_gate.py +0 -0
  27. {contractgate-0.3.2 → contractgate-0.4.0}/tests/test_validator.py +0 -0
@@ -2,6 +2,18 @@
2
2
 
3
3
  All notable changes to the `contractgate` Python SDK.
4
4
 
5
+ ## 0.4.0 — 2026-10-13
6
+
7
+ - `ingest` now posts to `/v1/ingest/{contract_id}` (was the legacy
8
+ `/ingest`), so each result carries `index` and `quarantine_id`.
9
+ - **Behavior change:** a batch where every event fails, or a rejected
10
+ `atomic` batch, returns a `BatchIngestResponse` with per-event results and violations instead of
11
+ raising `ValidationFailedError` on the gateway's 422. Only a 422 without
12
+ per-event results (an idempotency conflict) still raises.
13
+ - `version` is sent as the `version` query parameter; the
14
+ `"<uuid>@<version>"` contract-id form is still accepted.
15
+ - `IngestEventResult` gains `index` and `quarantine_id` (optional, default `None`).
16
+
5
17
  ## 0.3.2 — 2026-10-13
6
18
 
7
19
  - `LLMGate` / `AsyncLLMGate`: `llm` is now optional. `validate_only()` never
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: contractgate
3
- Version: 0.3.2
3
+ Version: 0.4.0
4
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
@@ -48,7 +48,7 @@ Python 3.9+. Runtime deps: `httpx`, `PyYAML`.
48
48
  ```python
49
49
  from contractgate import Client
50
50
 
51
- cg = Client(base_url="https://gw.example.com", api_key="cg_live_...")
51
+ cg = Client(base_url="https://api.datacontractgate.com", api_key="cg_live_...")
52
52
 
53
53
  result = cg.ingest(
54
54
  contract_id="11111111-1111-1111-1111-111111111111",
@@ -18,7 +18,7 @@ Python 3.9+. Runtime deps: `httpx`, `PyYAML`.
18
18
  ```python
19
19
  from contractgate import Client
20
20
 
21
- cg = Client(base_url="https://gw.example.com", api_key="cg_live_...")
21
+ cg = Client(base_url="https://api.datacontractgate.com", api_key="cg_live_...")
22
22
 
23
23
  result = cg.ingest(
24
24
  contract_id="11111111-1111-1111-1111-111111111111",
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "contractgate"
7
- version = "0.3.2"
7
+ version = "0.4.0"
8
8
  description = "Python SDK for DataContractGate — high-performance semantic contract enforcement gateway."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.9"
@@ -85,22 +85,26 @@ def build_ingest_request(
85
85
  atomic: bool = False,
86
86
  timeout: Optional[float] = None,
87
87
  ) -> RequestSpec:
88
- """Build a POST to ``/ingest/{contract_id}[@version]``.
88
+ """Build a POST to ``/v1/ingest/{contract_id}``.
89
89
 
90
90
  ``events`` may be a single dict (the gateway treats a non-array
91
91
  body as a one-event batch) or a list. ``version`` becomes the
92
- ``X-Contract-Version`` header so the gateway can resolve to a
93
- specific pin (header > path-suffix > default-stable, per RFC-002).
92
+ ``version`` query parameter, the pin form ``/v1/ingest`` accepts.
93
+ The older ``contract_id="<uuid>@<version>"`` form is still accepted
94
+ and converted; an explicit ``version`` wins.
95
+
96
+ ``/v1/ingest`` (unlike the legacy ``/ingest``) returns each result's
97
+ ``index`` and ``quarantine_id``.
94
98
  """
95
- path = f"/ingest/{contract_id}"
99
+ if "@" in contract_id:
100
+ contract_id, _, suffix = contract_id.partition("@")
101
+ if version is None and suffix:
102
+ version = suffix
103
+ path = f"/v1/ingest/{contract_id}"
96
104
  extra_headers: Dict[str, str] = {}
97
- if version is not None:
98
- # Header takes precedence over path-suffix per RFC-002. We use
99
- # the header form by default — clients that need the @version
100
- # path form for environments that strip headers can pass
101
- # ``contract_id="<uuid>@<version>"`` and leave ``version=None``.
102
- extra_headers["X-Contract-Version"] = version
103
105
  params: Dict[str, Any] = {}
106
+ if version is not None:
107
+ params["version"] = version
104
108
  if dry_run:
105
109
  params["dry_run"] = "true"
106
110
  if atomic:
@@ -307,3 +311,18 @@ def expect_list(body: Any) -> List[Any]:
307
311
  if isinstance(body, list):
308
312
  return body
309
313
  raise ValueError(f"expected list response, got {type(body).__name__}")
314
+
315
+
316
+ def ingest_body_from_rejection(err: Exception) -> Optional[Dict[str, Any]]:
317
+ """Return the batch body carried by a 422 ingest rejection, if any.
318
+
319
+ ``/v1/ingest`` answers 422 when every event fails or an atomic batch is
320
+ rejected, but the body is still a full batch response with per-event
321
+ results, so ``ingest`` returns it instead of raising. Other 422s (an
322
+ idempotency conflict, a deprecated version pin) carry no ``results``
323
+ and keep raising.
324
+ """
325
+ body = getattr(err, "body", None)
326
+ if isinstance(body, dict) and isinstance(body.get("results"), list) and "failed" in body:
327
+ return body
328
+ return None
@@ -0,0 +1 @@
1
+ __version__ = "0.4.0"
@@ -19,6 +19,7 @@ import httpx
19
19
 
20
20
  from contractgate import _transport as _t
21
21
  from contractgate.exceptions import ConnectionError as _ConnectionError
22
+ from contractgate.exceptions import ValidationFailedError
22
23
  from contractgate.models import (
23
24
  AuditEntry,
24
25
  BatchIngestResponse,
@@ -86,7 +87,12 @@ class AsyncClient:
86
87
  atomic=atomic,
87
88
  timeout=timeout,
88
89
  )
89
- _, body = await self._dispatch(spec)
90
+ try:
91
+ _, body = await self._dispatch(spec)
92
+ except ValidationFailedError as err:
93
+ body = _t.ingest_body_from_rejection(err)
94
+ if body is None:
95
+ raise
90
96
  return BatchIngestResponse.from_dict(body)
91
97
 
92
98
  async def egress(
@@ -13,6 +13,7 @@ import httpx
13
13
 
14
14
  from contractgate import _transport as _t
15
15
  from contractgate.exceptions import ConnectionError as _ConnectionError
16
+ from contractgate.exceptions import ValidationFailedError
16
17
  from contractgate.models import (
17
18
  AuditEntry,
18
19
  BatchIngestResponse,
@@ -29,7 +30,7 @@ class Client:
29
30
 
30
31
  Construct with the gateway's ``base_url`` and your API key:
31
32
 
32
- cg = Client(base_url="https://gw.example.com", api_key="cg_live_...")
33
+ cg = Client(base_url="https://api.datacontractgate.com", api_key="cg_live_...")
33
34
 
34
35
  The client owns an ``httpx.Client`` for connection pooling. Close
35
36
  it explicitly with :py:meth:`close` or use as a context manager.
@@ -83,15 +84,16 @@ class Client:
83
84
  atomic: bool = False,
84
85
  timeout: Optional[float] = None,
85
86
  ) -> BatchIngestResponse:
86
- """Validate + persist a batch via ``POST /ingest/{contract_id}``.
87
+ """Validate + persist a batch via ``POST /v1/ingest/{contract_id}``.
87
88
 
88
89
  ``events`` may be a single dict or a list of dicts. ``version``
89
- pins to a specific contract version via the
90
- ``X-Contract-Version`` header (RFC-002).
90
+ pins to a specific contract version.
91
91
 
92
- Per-event failures in a 207 Multi-Status response do NOT
93
- raise — they appear in ``response.results``. Whole-batch
94
- rejections (422) raise ``ValidationFailedError``.
92
+ Failed events never raise: whether some (207) or all (422) fail,
93
+ or an ``atomic`` batch is rejected, they appear in
94
+ ``response.results`` with their violations, ``index`` and
95
+ ``quarantine_id``. Only a 422 without per-event results (an
96
+ idempotency conflict) raises ``ValidationFailedError``.
95
97
  """
96
98
  spec = _t.build_ingest_request(
97
99
  self._cfg,
@@ -102,7 +104,12 @@ class Client:
102
104
  atomic=atomic,
103
105
  timeout=timeout,
104
106
  )
105
- _, body = self._dispatch(spec)
107
+ try:
108
+ _, body = self._dispatch(spec)
109
+ except ValidationFailedError as err:
110
+ body = _t.ingest_body_from_rejection(err)
111
+ if body is None:
112
+ raise
106
113
  return BatchIngestResponse.from_dict(body)
107
114
 
108
115
  def egress(
@@ -87,6 +87,10 @@ class IngestEventResult:
87
87
  forwarded: bool
88
88
  contract_version: str
89
89
  transformed_event: Any
90
+ # Position in the submitted batch, and the quarantine row for a stored
91
+ # failure (``None`` for passes, dry runs and atomic rejections).
92
+ index: Optional[int] = None
93
+ quarantine_id: Optional[str] = None
90
94
 
91
95
  @classmethod
92
96
  def from_dict(cls, raw: Dict[str, Any]) -> "IngestEventResult":
@@ -97,6 +101,8 @@ class IngestEventResult:
97
101
  forwarded=bool(raw.get("forwarded", False)),
98
102
  contract_version=raw["contract_version"],
99
103
  transformed_event=raw.get("transformed_event"),
104
+ index=raw.get("index"),
105
+ quarantine_id=raw.get("quarantine_id"),
100
106
  )
101
107
 
102
108
 
@@ -60,7 +60,7 @@ async def test_async_ingest_basic():
60
60
  r = await cg.ingest(contract_id="abc", events=[{"user_id": "x"}])
61
61
 
62
62
  assert r.passed == 1
63
- assert "/ingest/abc" in captured["url"]
63
+ assert "/v1/ingest/abc" in captured["url"]
64
64
  assert captured["body"] == [{"user_id": "x"}]
65
65
 
66
66
 
@@ -84,6 +84,24 @@ async def test_async_error_mapping(status: int, exc: type):
84
84
  await cg.ingest(contract_id="abc", events=[{}])
85
85
 
86
86
 
87
+ async def test_async_ingest_all_failed_422_returns_results():
88
+ body = _ok_body()
89
+ body.update(passed=0, failed=1)
90
+ body["results"][0].update(
91
+ index=0,
92
+ passed=False,
93
+ quarantine_id="00000000-0000-4000-8000-000000000000",
94
+ violations=[{"field": "amount", "message": "below min", "kind": "range_violation"}],
95
+ )
96
+ transport = httpx.MockTransport(lambda r: httpx.Response(422, json=body))
97
+ async with AsyncClient(base_url="https://gw", api_key="k", transport=transport) as cg:
98
+ r = await cg.ingest(contract_id="abc", events=[{}])
99
+ assert r.failed == 1
100
+ assert r.results[0].index == 0
101
+ assert r.results[0].quarantine_id == "00000000-0000-4000-8000-000000000000"
102
+ assert r.results[0].violations[0].field == "amount"
103
+
104
+
87
105
  async def test_async_context_manager_closes_underlying_client():
88
106
  transport = httpx.MockTransport(lambda r: httpx.Response(200, json=_ok_body()))
89
107
  cg = AsyncClient(base_url="https://gw", api_key="k", transport=transport)
@@ -27,6 +27,7 @@ from contractgate.exceptions import ConnectionError as _CGConnError
27
27
 
28
28
 
29
29
  def _ok_ingest_body(passed: int = 1, failed: int = 0) -> Dict[str, Any]:
30
+ """The real ``/v1/ingest`` shape, including ``index`` and ``quarantine_id``."""
30
31
  return {
31
32
  "total": passed + failed,
32
33
  "passed": passed,
@@ -37,17 +38,20 @@ def _ok_ingest_body(passed: int = 1, failed: int = 0) -> Dict[str, Any]:
37
38
  "version_pin_source": "default_stable",
38
39
  "results": [
39
40
  {
41
+ "index": i,
40
42
  "passed": True,
41
43
  "violations": [],
42
44
  "validation_us": 42,
43
45
  "forwarded": True,
44
46
  "contract_version": "1.0",
47
+ "quarantine_id": None,
45
48
  "transformed_event": {"user_id": "x"},
46
49
  }
47
- for _ in range(passed)
50
+ for i in range(passed)
48
51
  ]
49
52
  + [
50
53
  {
54
+ "index": passed + i,
51
55
  "passed": False,
52
56
  "violations": [
53
57
  {"field": "user_id", "message": "bad", "kind": "pattern_mismatch"}
@@ -55,9 +59,10 @@ def _ok_ingest_body(passed: int = 1, failed: int = 0) -> Dict[str, Any]:
55
59
  "validation_us": 12,
56
60
  "forwarded": False,
57
61
  "contract_version": "1.0",
62
+ "quarantine_id": f"00000000-0000-4000-8000-00000000000{i}",
58
63
  "transformed_event": {"user_id": "BAD!"},
59
64
  }
60
- for _ in range(failed)
65
+ for i in range(failed)
61
66
  ],
62
67
  }
63
68
 
@@ -88,7 +93,7 @@ def test_ingest_posts_to_correct_path_with_headers():
88
93
  events=[{"user_id": "alice"}],
89
94
  )
90
95
 
91
- assert "/ingest/11111111-1111-1111-1111-111111111111" in captured["url"]
96
+ assert "/v1/ingest/11111111-1111-1111-1111-111111111111" in captured["url"]
92
97
  assert captured["headers"]["x-api-key"] == "cg_live_test"
93
98
  assert captured["headers"]["x-org-id"] == "org-uuid"
94
99
  assert captured["headers"]["user-agent"].startswith("contractgate-python/")
@@ -97,11 +102,11 @@ def test_ingest_posts_to_correct_path_with_headers():
97
102
  assert r.results[0].forwarded is True
98
103
 
99
104
 
100
- def test_ingest_version_kwarg_becomes_header():
105
+ def test_ingest_version_kwarg_becomes_query_param():
101
106
  captured: Dict[str, Any] = {}
102
107
 
103
108
  def handler(request: httpx.Request) -> httpx.Response:
104
- captured["headers"] = dict(request.headers)
109
+ captured["url"] = request.url
105
110
  return httpx.Response(200, json=_ok_ingest_body(passed=1))
106
111
 
107
112
  with Client(
@@ -111,7 +116,22 @@ def test_ingest_version_kwarg_becomes_header():
111
116
  ) as cg:
112
117
  cg.ingest(contract_id="abc", events=[{}], version="2.5")
113
118
 
114
- assert captured["headers"]["x-contract-version"] == "2.5"
119
+ assert captured["url"].path == "/v1/ingest/abc"
120
+ assert captured["url"].params["version"] == "2.5"
121
+
122
+
123
+ def test_ingest_at_version_suffix_becomes_query_param():
124
+ captured: Dict[str, Any] = {}
125
+
126
+ def handler(request: httpx.Request) -> httpx.Response:
127
+ captured["url"] = request.url
128
+ return httpx.Response(200, json=_ok_ingest_body(passed=1))
129
+
130
+ with Client(base_url="https://gw", api_key="k", transport=httpx.MockTransport(handler)) as cg:
131
+ cg.ingest(contract_id="abc@1.2.0", events=[{}])
132
+
133
+ assert captured["url"].path == "/v1/ingest/abc"
134
+ assert captured["url"].params["version"] == "1.2.0"
115
135
 
116
136
 
117
137
  def test_ingest_dry_run_and_atomic_become_query_params():
@@ -142,6 +162,21 @@ def test_ingest_207_does_not_raise():
142
162
  assert any(not e.passed for e in r.results)
143
163
 
144
164
 
165
+ def test_ingest_all_failed_422_returns_results():
166
+ """Every event failing is a 422, but still a result with violations."""
167
+
168
+ def handler(request: httpx.Request) -> httpx.Response:
169
+ return httpx.Response(422, json=_ok_ingest_body(passed=0, failed=2))
170
+
171
+ with Client(base_url="https://gw", api_key="k", transport=httpx.MockTransport(handler)) as cg:
172
+ r = cg.ingest(contract_id="abc", events=[{}, {}])
173
+
174
+ assert (r.passed, r.failed) == (0, 2)
175
+ assert [e.index for e in r.results] == [0, 1]
176
+ assert r.results[0].violations[0].field == "user_id"
177
+ assert r.results[1].quarantine_id == "00000000-0000-4000-8000-000000000001"
178
+
179
+
145
180
  # ---------------------------------------------------------------------------
146
181
  # Error mapping
147
182
  # ---------------------------------------------------------------------------
@@ -1 +0,0 @@
1
- __version__ = "0.3.2"
File without changes
File without changes