catopt-graph-graph-calculus.../core/contract_registry.py

43 lines
1.8 KiB
Python

from __future__ import annotations
from typing import Any, Dict, Optional
class ContractRegistry:
"""Lightweight, in-memory, versioned contract registry for MVP tests.
- Contracts are registered by name and version.
- Each contract has a schema (dict) describing LocalProblem/SharedVariables/etc.
- Exposes simple get_contract(name, version), register_contract(...), and conformance checks.
- Exposes list_versions(name) to mirror test expectations.
"""
def __init__(self) -> None:
self._store: Dict[str, Dict[str, Dict[str, Any]]] = {}
def register_contract(self, name: str, version: str, schema: Dict[str, Any]) -> None:
"""Register or update a contract schema for a given name/version."""
# Store a shallow copy to avoid accidental external mutation
self._store.setdefault(name, {})[version] = dict(schema)
def get_contract(self, name: str, version: str) -> Optional[Dict[str, Any]]:
return self._store.get(name, {}).get(version)
def list_versions(self, name: str) -> list[str]:
return sorted(list(self._store.get(name, {}).keys()))
def conformance_check(self, name: str, version: str, adapter_data: Dict[str, Any]) -> bool:
"""Check if adapter_data satisfies the contract's required_fields.
Returns True if all required_fields (defined in schema) are present in adapter_data.
If no contract or required_fields are defined, returns False to be safe.
"""
contract = self.get_contract(name, version)
if contract is None:
return False
required = contract.get("required_fields") or []
if not isinstance(required, (list, tuple)):
return False
return all(field in adapter_data for field in required)