Skip to main content

Runtime contract reliability SDK for AI system components.

Project description

StateGuard

Runtime contract reliability SDK for AI system components.

CI License: Apache 2.0 Python 3.11+

StateGuard automatically detects and repairs runtime contract failures between AI system components — preventing schema drift, field renames, and type mismatches from crashing your AI workflows.

Why StateGuard?

LLM tool calls and agent pipelines are wired together by convention, not by a compiler. A model returns temp_celsius when your schema expects temperature, or "31.5" where you need a float — and without a repair layer, that's an unhandled exception in production. StateGuard sits between the LLM's output and your typed schema, detects the drift, and repairs it automatically wherever it can safely infer the fix — falling back to a clear, structured failure when it can't.

from stateguard import ContractGuard
from pydantic import BaseModel

class Weather(BaseModel):
    temperature: float
    humidity: int

guard = ContractGuard.with_pydantic()

# Tool returned the wrong field name — StateGuard repairs it automatically.
result = guard.repair(Weather, {"temp_celsius": 31.5, "humidity": 80})
# result.status        → RepairStatus.SUCCESS
# result.repaired_output → {"temperature": 31.5, "humidity": 80}

Installation

Requirements: Python 3.11+. No runtime dependencies for the core package; pydantic>=2.0,<3.0 if you install the pydantic extra.

pip install "sguard[pydantic]"

The brackets must be quoted — on zsh and many Linux shells, an unquoted pip install sguard[pydantic] is interpreted as a glob pattern and fails with no matches found. The quoted form works in zsh, bash, PowerShell, and cmd.exe alike.

The core package (pip install sguard) has zero runtime dependencies. Pydantic is an optional extra — the only adapter currently shipped.

Command-line interface

Validate and repair a JSON payload against a contract without writing any Python:

# Against a Pydantic model
stateguard check --model mypackage.models:Weather --payload payload.json

# Against a plain JSON schema (no pydantic required)
stateguard check --schema contract.json --payload payload.json

# Machine-readable output, for piping into other tools
stateguard check --schema contract.json --payload payload.json --json

Exit codes: 0 = success/already valid, 1 = partially repaired, 2 = failed (or a usage error). Run stateguard check --help for the full flag reference, including --strict, --max-attempts, and --confidence-threshold.

Repair history (optional)

Keep a local, append-only audit trail of every repair StateGuard performs:

from stateguard import ContractGuard
from stateguard.logging import RepairHistoryRecorder

guard = ContractGuard.with_pydantic(history=RepairHistoryRecorder())
# Appends one JSON line per repair to ~/.stateguard/repairs.jsonl by default.
# Fully optional, fully local — no network calls, no external services.

Architecture

A framework-agnostic core engine with zero external runtime dependencies. Pydantic is the first supported adapter; future adapters (LangChain, LangGraph, JSON Schema) can be added without modifying the engine.

User Code
    │
    ▼
ContractGuard          ← orchestrator (guard.py)
    │
    ├── IContractAdapter  ← PydanticAdapter, DictContractAdapter, ...
    │       │
    │       └── ContractSpec  ← normalised, framework-agnostic contract
    │
    └── RepairEngine      ← core; zero external deps
            │
            ├── ContractValidator
            ├── StrategyRegistry
            └── Strategies: ExactAlias, FuzzyRename, TypeCoerce, DefaultFill

Limitations

  • Nesting depth: repairs are officially validated up to 3 levels of nesting (root.address.country.code). Deeper structures generally work but aren't part of the tested/supported surface.
  • Cross-branch fuzzy matching: FuzzyFieldMatchStrategy scores candidates by full dotted-path similarity, not parent-scope. In adversarial cases with similar field and branch names, this can block a valid repair (StateGuard's safe failure mode) rather than guess wrong.
  • No JSON Schema adapter yet — the CLI's --schema format is a StateGuard-proprietary equivalent, not real JSON Schema.

See M9_AUDIT.md for the full production-readiness audit, performance characteristics, and recommended next steps.

Benchmarks

A correctness benchmark suite in benchmarks/ covers alias repair, fuzzy renames, type coercion, default-fill, nested structures, and known-unrecoverable cases:

python benchmarks/runner.py --verbose

Development

# Install with all dev dependencies
pip install -e ".[pydantic,dev]"

# Run isolation tests first (must always pass)
pytest tests/isolation/ -v

# Run full test suite
pytest tests/ --cov=stateguard

# Type check
mypy src/

# Lint
ruff check src/ tests/

See CHANGELOG.md for release history.

License

Apache License 2.0 — see LICENSE.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

sguard-0.1.0.tar.gz (151.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

sguard-0.1.0-py3-none-any.whl (81.3 kB view details)

Uploaded Python 3

File details

Details for the file sguard-0.1.0.tar.gz.

File metadata

  • Download URL: sguard-0.1.0.tar.gz
  • Upload date:
  • Size: 151.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.6

File hashes

Hashes for sguard-0.1.0.tar.gz
Algorithm Hash digest
SHA256 0ea129c7b1d0d434bd3dc991de477166c0bcb61d618a0148f642ba20ad03eac2
MD5 9dea2d6f8124287b2b6420e12c26c887
BLAKE2b-256 5e26a2eaa497f8b215d62151d70c6e525ec02a78a932b0b797604577005674f6

See more details on using hashes here.

File details

Details for the file sguard-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: sguard-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 81.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.6

File hashes

Hashes for sguard-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 5edf10b34f4a3e465142a184ad12f1e185965046793e583d9da9584ee64b9ca6
MD5 da9d4324b40874a386007a2d01d0a36c
BLAKE2b-256 2bd0bc57176140be518c72bac8949821f582171b0d7f378ec8c7577a134900a4

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page