contractgate 0.3.0__tar.gz → 0.3.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.
Files changed (27) hide show
  1. {contractgate-0.3.0 → contractgate-0.3.2}/CHANGELOG.md +20 -0
  2. {contractgate-0.3.0 → contractgate-0.3.2}/PKG-INFO +1 -1
  3. {contractgate-0.3.0 → contractgate-0.3.2}/pyproject.toml +1 -1
  4. contractgate-0.3.2/src/contractgate/_version.py +1 -0
  5. {contractgate-0.3.0 → contractgate-0.3.2}/src/contractgate/llm.py +62 -41
  6. {contractgate-0.3.0 → contractgate-0.3.2}/src/contractgate/models.py +6 -4
  7. {contractgate-0.3.0 → contractgate-0.3.2}/tests/test_llm_gate.py +42 -12
  8. contractgate-0.3.0/src/contractgate/_version.py +0 -1
  9. {contractgate-0.3.0 → contractgate-0.3.2}/.gitignore +0 -0
  10. {contractgate-0.3.0 → contractgate-0.3.2}/LICENSE +0 -0
  11. {contractgate-0.3.0 → contractgate-0.3.2}/README.md +0 -0
  12. {contractgate-0.3.0 → contractgate-0.3.2}/src/contractgate/__init__.py +0 -0
  13. {contractgate-0.3.0 → contractgate-0.3.2}/src/contractgate/_transport.py +0 -0
  14. {contractgate-0.3.0 → contractgate-0.3.2}/src/contractgate/async_client.py +0 -0
  15. {contractgate-0.3.0 → contractgate-0.3.2}/src/contractgate/client.py +0 -0
  16. {contractgate-0.3.0 → contractgate-0.3.2}/src/contractgate/contract.py +0 -0
  17. {contractgate-0.3.0 → contractgate-0.3.2}/src/contractgate/exceptions.py +0 -0
  18. {contractgate-0.3.0 → contractgate-0.3.2}/src/contractgate/validator.py +0 -0
  19. {contractgate-0.3.0 → contractgate-0.3.2}/tests/__init__.py +0 -0
  20. {contractgate-0.3.0 → contractgate-0.3.2}/tests/conftest.py +0 -0
  21. {contractgate-0.3.0 → contractgate-0.3.2}/tests/fixtures/contracts/compliance_mode.yaml +0 -0
  22. {contractgate-0.3.0 → contractgate-0.3.2}/tests/fixtures/contracts/user_events.yaml +0 -0
  23. {contractgate-0.3.0 → contractgate-0.3.2}/tests/fixtures/contracts/with_transform.yaml +0 -0
  24. {contractgate-0.3.0 → contractgate-0.3.2}/tests/test_client_async.py +0 -0
  25. {contractgate-0.3.0 → contractgate-0.3.2}/tests/test_client_sync.py +0 -0
  26. {contractgate-0.3.0 → contractgate-0.3.2}/tests/test_contract_parse.py +0 -0
  27. {contractgate-0.3.0 → contractgate-0.3.2}/tests/test_validator.py +0 -0
@@ -2,6 +2,26 @@
2
2
 
3
3
  All notable changes to the `contractgate` Python SDK.
4
4
 
5
+ ## 0.3.2 — 2026-10-13
6
+
7
+ - `LLMGate` / `AsyncLLMGate`: `llm` is now optional. `validate_only()` never
8
+ calls a provider, so it no longer needs a dummy client; `completion()` and
9
+ `message()` raise `ValueError` when no `llm` is bound.
10
+
11
+ ## 0.3.1 — 2026-10-13
12
+
13
+ Fixes from end-to-end testing against production. No API changes.
14
+
15
+ - Fix: `LLMGate(contract_id="<name>")` crashed with `KeyError: 'created_at'`.
16
+ `GET /contracts` returns summary rows without timestamps;
17
+ `ContractResponse.created_at` / `updated_at` are now optional.
18
+ - Fix: a rejected LLM output now returns `LLMGateResult(ok=False, violations=[...])`
19
+ instead of raising `ValidationFailedError`. The gateway answers 422 when every
20
+ event fails, which is always true for a gate's single-event batch, so
21
+ `validate_only` and the `auto_repair` loop never saw the violations. A 422
22
+ without an egress body (e.g. a deprecated version pin) is still raised.
23
+ - Default `base_url` is `https://api.datacontractgate.com` (was the dashboard host).
24
+
5
25
  ## 0.3.0 — 2026-10-11
6
26
 
7
27
  RFC-094. Adds the `contractgate.llm` submodule for LLM output
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: contractgate
3
- Version: 0.3.0
3
+ Version: 0.3.2
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
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "contractgate"
7
- version = "0.3.0"
7
+ version = "0.3.2"
8
8
  description = "Python SDK for DataContractGate — high-performance semantic contract enforcement gateway."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.9"
@@ -0,0 +1 @@
1
+ __version__ = "0.3.2"
@@ -26,7 +26,7 @@ from typing import Any, Awaitable, Callable, Dict, List, Optional
26
26
 
27
27
  from contractgate.async_client import AsyncClient
28
28
  from contractgate.client import Client
29
- from contractgate.exceptions import ContractGateError
29
+ from contractgate.exceptions import ContractGateError, ValidationFailedError
30
30
  from contractgate.models import ContractResponse, EgressResponse, Violation
31
31
 
32
32
  _UUID_RE = re.compile(
@@ -291,6 +291,31 @@ def _result_from_egress(
291
291
  )
292
292
 
293
293
 
294
+ def _egress_from_rejection(err: ValidationFailedError) -> EgressResponse:
295
+ """Turn a 422 egress rejection back into an ``EgressResponse``.
296
+
297
+ The gateway answers 422 when every event in the batch fails, which is
298
+ always the case for a gate's single-event batch. The body is still a full
299
+ egress response with per-field violations, so a failed validation is a
300
+ result (``ok=False``), not an exception. Any other 422 (e.g. a deprecated
301
+ version pin) has no ``outcomes`` and is re-raised.
302
+ """
303
+ body = err.body
304
+ if isinstance(body, dict) and "outcomes" in body and "failed" in body:
305
+ return EgressResponse.from_dict(body)
306
+ raise err
307
+
308
+
309
+ def _require_llm(llm: Any) -> None:
310
+ """``llm`` is only needed to call a provider; ``validate_only`` works without it."""
311
+ if llm is None:
312
+ raise ValueError(
313
+ "completion() and message() need an `llm` client (OpenAI / Anthropic / "
314
+ "Ollama / vLLM). Example: LLMGate(..., llm=OpenAI()). "
315
+ "validate_only() works without one."
316
+ )
317
+
318
+
294
319
  def _append_user_message(messages: List[Dict[str, Any]], hint: str) -> List[Dict[str, Any]]:
295
320
  return list(messages) + [{"role": "user", "content": hint}]
296
321
 
@@ -314,19 +339,14 @@ class LLMGate:
314
339
  *,
315
340
  api_key: str,
316
341
  contract_id: str,
317
- llm: Any,
318
- base_url: str = "https://app.datacontractgate.com",
342
+ llm: Any = None,
343
+ base_url: str = "https://api.datacontractgate.com",
319
344
  version: Optional[str] = None,
320
345
  disposition: Optional[str] = None,
321
346
  max_retries: int = _DEFAULT_MAX_RETRIES,
322
347
  repair_prompt: Optional[Callable[[List[Violation]], str]] = None,
323
348
  client: Optional[Client] = None,
324
349
  ) -> None:
325
- if llm is None:
326
- raise ValueError(
327
- "LLMGate requires an `llm` client (OpenAI / Anthropic / "
328
- "Ollama / vLLM). Example: LLMGate(..., llm=OpenAI())"
329
- )
330
350
  self._llm = llm
331
351
  self._contract_id = contract_id
332
352
  self._resolved: Dict[str, str] = {}
@@ -368,6 +388,7 @@ class LLMGate:
368
388
  Works unchanged for vLLM and OpenAI-compatible Ollama endpoints.
369
389
  """
370
390
  self._reject_stream_kwarg(provider_kwargs)
391
+ _require_llm(self._llm)
371
392
 
372
393
  def call(current: List[Dict[str, Any]]) -> Any:
373
394
  return self._llm.chat.completions.create(
@@ -387,6 +408,7 @@ class LLMGate:
387
408
  ) -> LLMGateResult:
388
409
  """Anthropic-protocol wrapper. Calls ``llm.messages.create``."""
389
410
  self._reject_stream_kwarg(provider_kwargs)
411
+ _require_llm(self._llm)
390
412
 
391
413
  def call(current: List[Dict[str, Any]]) -> Any:
392
414
  return self._llm.messages.create(
@@ -407,6 +429,18 @@ class LLMGate:
407
429
  )
408
430
  return self._resolved[contract_id]
409
431
 
432
+ def _egress(self, payload: Dict[str, Any], *, dry_run: bool = False) -> EgressResponse:
433
+ try:
434
+ return self._client.egress(
435
+ contract_id=self._resolve(self._contract_id),
436
+ events=[payload],
437
+ version=self._version,
438
+ disposition=self._disposition,
439
+ dry_run=dry_run,
440
+ )
441
+ except ValidationFailedError as err:
442
+ return _egress_from_rejection(err)
443
+
410
444
  def validate_only(
411
445
  self,
412
446
  response: Any,
@@ -415,13 +449,7 @@ class LLMGate:
415
449
  ) -> LLMGateResult:
416
450
  """Validate a response the caller already produced."""
417
451
  payload = extract_json(response)
418
- egress = self._client.egress(
419
- contract_id=self._resolve(self._contract_id),
420
- events=[payload],
421
- version=self._version,
422
- disposition=self._disposition,
423
- dry_run=dry_run,
424
- )
452
+ egress = self._egress(payload, dry_run=dry_run)
425
453
  return _result_from_egress(egress, raw_response=response, attempts=1)
426
454
 
427
455
  def mask_prompt(
@@ -479,12 +507,7 @@ class LLMGate:
479
507
  hints.append(hint)
480
508
  current = _append_user_message(current, hint)
481
509
  continue
482
- egress = self._client.egress(
483
- contract_id=self._resolve(self._contract_id),
484
- events=[payload],
485
- version=self._version,
486
- disposition=self._disposition,
487
- )
510
+ egress = self._egress(payload)
488
511
  last = _result_from_egress(egress, raw_response=resp, attempts=attempt, hints=hints)
489
512
  if egress.failed == 0 or not auto_repair or attempt >= total_attempts:
490
513
  return last
@@ -508,19 +531,14 @@ class AsyncLLMGate:
508
531
  *,
509
532
  api_key: str,
510
533
  contract_id: str,
511
- llm: Any,
512
- base_url: str = "https://app.datacontractgate.com",
534
+ llm: Any = None,
535
+ base_url: str = "https://api.datacontractgate.com",
513
536
  version: Optional[str] = None,
514
537
  disposition: Optional[str] = None,
515
538
  max_retries: int = _DEFAULT_MAX_RETRIES,
516
539
  repair_prompt: Optional[Callable[[List[Violation]], str]] = None,
517
540
  client: Optional[AsyncClient] = None,
518
541
  ) -> None:
519
- if llm is None:
520
- raise ValueError(
521
- "AsyncLLMGate requires an `llm` client. Example: "
522
- "AsyncLLMGate(..., llm=AsyncOpenAI())"
523
- )
524
542
  self._llm = llm
525
543
  self._contract_id = contract_id
526
544
  self._resolved: Dict[str, str] = {}
@@ -554,6 +572,7 @@ class AsyncLLMGate:
554
572
  **provider_kwargs: Any,
555
573
  ) -> LLMGateResult:
556
574
  LLMGate._reject_stream_kwarg(provider_kwargs)
575
+ _require_llm(self._llm)
557
576
 
558
577
  async def call(current: List[Dict[str, Any]]) -> Any:
559
578
  return await self._llm.chat.completions.create(
@@ -572,6 +591,7 @@ class AsyncLLMGate:
572
591
  **provider_kwargs: Any,
573
592
  ) -> LLMGateResult:
574
593
  LLMGate._reject_stream_kwarg(provider_kwargs)
594
+ _require_llm(self._llm)
575
595
 
576
596
  async def call(current: List[Dict[str, Any]]) -> Any:
577
597
  return await self._llm.messages.create(
@@ -592,6 +612,18 @@ class AsyncLLMGate:
592
612
  )
593
613
  return self._resolved[contract_id]
594
614
 
615
+ async def _egress(self, payload: Dict[str, Any], *, dry_run: bool = False) -> EgressResponse:
616
+ try:
617
+ return await self._client.egress(
618
+ contract_id=await self._resolve(self._contract_id),
619
+ events=[payload],
620
+ version=self._version,
621
+ disposition=self._disposition,
622
+ dry_run=dry_run,
623
+ )
624
+ except ValidationFailedError as err:
625
+ return _egress_from_rejection(err)
626
+
595
627
  async def validate_only(
596
628
  self,
597
629
  response: Any,
@@ -599,13 +631,7 @@ class AsyncLLMGate:
599
631
  dry_run: bool = False,
600
632
  ) -> LLMGateResult:
601
633
  payload = extract_json(response)
602
- egress = await self._client.egress(
603
- contract_id=await self._resolve(self._contract_id),
604
- events=[payload],
605
- version=self._version,
606
- disposition=self._disposition,
607
- dry_run=dry_run,
608
- )
634
+ egress = await self._egress(payload, dry_run=dry_run)
609
635
  return _result_from_egress(egress, raw_response=response, attempts=1)
610
636
 
611
637
  async def mask_prompt(
@@ -649,12 +675,7 @@ class AsyncLLMGate:
649
675
  hints.append(hint)
650
676
  current = _append_user_message(current, hint)
651
677
  continue
652
- egress = await self._client.egress(
653
- contract_id=await self._resolve(self._contract_id),
654
- events=[payload],
655
- version=self._version,
656
- disposition=self._disposition,
657
- )
678
+ egress = await self._egress(payload)
658
679
  last = _result_from_egress(egress, raw_response=resp, attempts=attempt, hints=hints)
659
680
  if egress.failed == 0 or not auto_repair or attempt >= total_attempts:
660
681
  return last
@@ -193,8 +193,10 @@ class ContractResponse:
193
193
  name: str
194
194
  description: Optional[str]
195
195
  multi_stable_resolution: str
196
- created_at: str
197
- updated_at: str
196
+ # ``GET /contracts`` returns summary rows without timestamps; only the
197
+ # single-contract endpoints include them.
198
+ created_at: Optional[str]
199
+ updated_at: Optional[str]
198
200
  version_count: int
199
201
  latest_stable_version: Optional[str]
200
202
 
@@ -205,8 +207,8 @@ class ContractResponse:
205
207
  name=raw["name"],
206
208
  description=raw.get("description"),
207
209
  multi_stable_resolution=raw.get("multi_stable_resolution", "strict"),
208
- created_at=raw["created_at"],
209
- updated_at=raw["updated_at"],
210
+ created_at=raw.get("created_at"),
211
+ updated_at=raw.get("updated_at"),
210
212
  version_count=int(raw.get("version_count", 0)),
211
213
  latest_stable_version=raw.get("latest_stable_version"),
212
214
  )
@@ -137,6 +137,13 @@ def _fail_egress_body(payload: Dict[str, Any]) -> Dict[str, Any]:
137
137
  }
138
138
 
139
139
 
140
+ def _egress_status(body: Dict[str, Any]) -> int:
141
+ """Status the gateway really sends: 422 when every event failed."""
142
+ if body.get("failed", 0) > 0 and body.get("passed", 0) == 0:
143
+ return 422
144
+ return 207 if body.get("failed", 0) > 0 else 200
145
+
146
+
140
147
  def _ingest_body_with_transform(transformed: Dict[str, Any]) -> Dict[str, Any]:
141
148
  return {
142
149
  "total": 1,
@@ -248,9 +255,18 @@ def test_extract_json_streaming_rejected():
248
255
  # ---------------------------------------------------------------------------
249
256
 
250
257
 
251
- def test_llmgate_requires_llm():
252
- with pytest.raises(ValueError, match="requires an `llm` client"):
253
- LLMGate(api_key="k", contract_id="11111111-1111-4111-8111-111111111111", llm=None)
258
+ def test_llm_is_optional_for_validate_only():
259
+ payload = {"user_id": "alice"}
260
+ gate = LLMGate(
261
+ api_key="k",
262
+ contract_id="11111111-1111-4111-8111-111111111111",
263
+ client=_client_with_egress(_ok_egress_body(payload)),
264
+ )
265
+ assert gate.validate_only(payload).ok is True
266
+ with pytest.raises(ValueError, match="need an `llm` client"):
267
+ gate.completion(model="m", messages=[])
268
+ with pytest.raises(ValueError, match="need an `llm` client"):
269
+ gate.message(model="m", messages=[])
254
270
 
255
271
 
256
272
  def test_llmgate_max_retries_above_cap_warns_and_clamps():
@@ -273,7 +289,7 @@ def test_llmgate_negative_max_retries_clamps_to_zero():
273
289
 
274
290
  def _client_with_egress(response_body: Dict[str, Any]) -> Client:
275
291
  def handler(request: httpx.Request) -> httpx.Response:
276
- return httpx.Response(200, json=response_body)
292
+ return httpx.Response(_egress_status(response_body), json=response_body)
277
293
 
278
294
  return Client(
279
295
  base_url="https://gw",
@@ -305,6 +321,18 @@ def test_validate_only_failure_returns_sanitized_result():
305
321
  assert result.violations[0].kind == ViolationKind.RANGE_VIOLATION
306
322
 
307
323
 
324
+ def test_non_egress_422_is_still_raised():
325
+ from contractgate import ValidationFailedError
326
+
327
+ def handler(request: httpx.Request) -> httpx.Response:
328
+ return httpx.Response(422, json={"error": "version 1.0 is deprecated"})
329
+
330
+ client = Client(base_url="https://gw", api_key="k", transport=httpx.MockTransport(handler))
331
+ gate = LLMGate(api_key="k", contract_id="11111111-1111-4111-8111-111111111111", llm=MagicMock(), client=client)
332
+ with pytest.raises(ValidationFailedError):
333
+ gate.validate_only({"user_id": "a"})
334
+
335
+
308
336
  def test_validate_only_asserts_request_shape():
309
337
  captured: Dict[str, Any] = {}
310
338
 
@@ -375,7 +403,7 @@ class _ToggleTransport(httpx.MockTransport):
375
403
  def _handler(self, request: httpx.Request) -> httpx.Response:
376
404
  self.hits += 1
377
405
  body = next(self._bodies)
378
- return httpx.Response(200, json=body)
406
+ return httpx.Response(_egress_status(body), json=body)
379
407
 
380
408
 
381
409
  def test_completion_auto_repair_passes_on_second_try():
@@ -541,9 +569,11 @@ async def test_async_llmgate_validate_only_happy_path():
541
569
 
542
570
 
543
571
  @pytest.mark.asyncio
544
- async def test_async_llmgate_requires_llm():
545
- with pytest.raises(ValueError, match="requires an `llm` client"):
546
- AsyncLLMGate(api_key="k", contract_id="11111111-1111-4111-8111-111111111111", llm=None)
572
+ async def test_async_llm_is_optional_until_completion():
573
+ gate = AsyncLLMGate(api_key="k", contract_id="11111111-1111-4111-8111-111111111111")
574
+ with pytest.raises(ValueError, match="need an `llm` client"):
575
+ await gate.completion(model="m", messages=[])
576
+ await gate.aclose()
547
577
 
548
578
 
549
579
  # ---------------------------------------------------------------------------
@@ -570,14 +600,14 @@ def test_result_is_dataclass_with_expected_fields():
570
600
 
571
601
  def _contract_row(cid: str, name: str) -> Dict[str, Any]:
572
602
  return {
603
+ # The real ``GET /contracts`` summary row (src/contract.rs
604
+ # ContractSummary): no description or timestamps.
573
605
  "id": cid,
574
606
  "name": name,
575
- "description": None,
576
607
  "multi_stable_resolution": "strict",
577
- "created_at": "2026-10-12T00:00:00Z",
578
- "updated_at": "2026-10-12T00:00:00Z",
579
- "version_count": 1,
580
608
  "latest_stable_version": "1.0.0",
609
+ "version_count": 1,
610
+ "store_event_payloads": False,
581
611
  }
582
612
 
583
613
 
@@ -1 +0,0 @@
1
- __version__ = "0.3.0"
File without changes
File without changes
File without changes