This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: pydantic-v2-rust-core-strict-validation

Pydantic V2 Rust-Core Strict Ingestion Boundary Standard

Mandates compile-level strict validation mode and direct binary deserialization via pydantic-core at all external network boundaries. Eliminates silent implicit type coercion vulnerabilities and bypasses Python GIL runtime serialization bottlenecks by delegating parsing directly to the Rust core.

Prohibited Anti-Pattern: Lax Type Coercion and Intermediate Dict Allocation at Network Boundaries

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Pydantic V2 Rust-Core Strict Ingestion Boundary Standard - Mandates compile-level strict validation mode and direct binary deserialization via pydantic-core at all external network boundaries. Eliminates silent implicit type coercion vulnerabilities and bypasses Python GIL runtime serialization bottlenecks by delegating parsing directly to the Rust core.
globs: app/**/*.py, src/**/*.py, api/**/*.py, services/**/*.py
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/pydantic-v2-rust-core-strict-validation"
---

# Pydantic V2 Rust-Core Strict Ingestion Boundary Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Lax Type Coercion and Intermediate Dict Allocation at Network Boundaries

## System Constraints
You are a Principal Software Architect enforcing the Pydantic V2 Rust-Core Strict Validation Boundary Standard. You must mandate strict-mode type safety on all ingress network boundaries, disallow implicit type coercion (such as string-to-integer or integer-to-boolean widening), forbid intermediate Python `json.loads()` dictionary allocations, and enforce zero-copy `model_validate_json(..., strict=True)` deserialization via pydantic-core.

## Strict Guidelines
- Engineers MUST ALWAYS declare `model_config = ConfigDict(strict=True, extra='forbid')` on all external ingress Data Transfer Objects (DTOs).
- Engineers MUST ALWAYS invoke `Model.model_validate_json(raw_bytes, strict=True)` when consuming network payloads to execute parsing entirely within the Rust `pydantic-core` layer.
- Engineers MUST NOT utilize `json.loads()` prior to Pydantic validation, as it incurs intermediate Python dictionary allocation and forfeits C/Rust engine optimizations.
- Engineers MUST NOT allow lax mode coercion on identifiers, permissions, or numeric thresholds where strings like 'true' or numbers like 1 could bypass access controls or alter precision.
- Services MUST explicitly use `Annotated[T, Field(strict=True)]` if fine-grained field-level boundary constraints are required inside generic schemas.

## Bad vs Good Implementations
### Ingress Deserialization: Lax Dict Conversion vs. Rust-Core Strict Validation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Intermediate json.loads allocates Python dictionary objects on the heap, triggering GIL contention. Default Pydantic validation allows lax coercion where string 'yes' or int 1 coerces to booleans, and string '100' coerces to an integer, bypassing boundary validation semantics.
```python
import json
from pydantic import BaseModel

class IngestTelemetryRequest(BaseModel):
    device_id: int
    is_authorized: bool
    sampling_rate: float

def process_webhook(raw_payload: bytes) -> IngestTelemetryRequest:
    # Anti-Pattern: Intermediate Python heap dict allocation and lax coercion.
    # Payload {"device_id": "100", "is_authorized": "yes", "sampling_rate": 5}
    # is silently coerced without validation errors, introducing security bugs.
    data = json.loads(raw_payload)
    return IngestTelemetryRequest(**data)
```

#### Production Standard (Correct)
> **Standard**: Using model_validate_json with strict=True skips Python-layer JSON parsing entirely, delegating SIMD-accelerated deserialization to Rust (pydantic-core). It explicitly rejects implicit type coercion and unexpected fields.
```python
from pydantic import BaseModel, ConfigDict, ValidationError

class IngestTelemetryRequest(BaseModel):
    model_config = ConfigDict(
        strict=True,
        extra="forbid",
        frozen=True
    )
    device_id: int
    is_authorized: bool
    sampling_rate: float

def process_webhook(raw_payload: bytes) -> IngestTelemetryRequest:
    # Invariant: Directly dispatch raw bytes to pydantic-core in Rust.
    # Payload must conform strictly to exact types; coercion raises ValidationError.
    return IngestTelemetryRequest.model_validate_json(
        raw_payload,
        strict=True
    )
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Pydantic V2 Rust-Core Strict Ingestion Boundary Standard

Pydantic V2 Rust-Core Strict Ingestion Boundary Standard defines an industrial-grade behavioral standard for backend engineering. Mandates compile-level strict validation mode and direct binary deserialization via pydantic-core at all external network boundaries. Eliminates silent implicit type coercion vulnerabilities and bypasses Python GIL runtime serialization bottlenecks by delegating parsing directly to the Rust core. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Lax Type Coercion and Intermediate Dict Allocation at Network Boundaries Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftLax Type Coercion and Intermediate Dict Allocation at Network BoundariesCritical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS declare `model_config = ConfigDict(strict=True, extra='forbid')` on all external ingress Data Transfer Objects (DTOs).

Engineers MUST ALWAYS declare `model_config = ConfigDict(strict=True, extra='forbid')` on all external ingress Data Transfer Objects (DTOs).

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST ALWAYS invoke `Model.model_validate_json(raw_bytes, strict=True)` when consuming network payloads to execute parsing entirely within the Rust `pydantic-core` layer.

Engineers MUST ALWAYS invoke `Model.model_validate_json(raw_bytes, strict=True)` when consuming network payloads to execute parsing entirely within the Rust `pydantic-core` layer.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Engineers MUST NOT utilize `json.loads()` prior to Pydantic validation, as it incurs intermediate Python dictionary allocation and forfeits C/Rust engine optimizations.

Engineers MUST NOT utilize `json.loads()` prior to Pydantic validation, as it incurs intermediate Python dictionary allocation and forfeits C/Rust engine optimizations.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Engineers MUST NOT allow lax mode coercion on identifiers, permissions, or numeric thresholds where strings like 'true' or numbers like 1 could bypass access controls or alter precision.

Engineers MUST NOT allow lax mode coercion on identifiers, permissions, or numeric thresholds where strings like 'true' or numbers like 1 could bypass access controls or alter precision.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Services MUST explicitly use `Annotated[T, Field(strict=True)]` if fine-grained field-level boundary constraints are required inside generic schemas.

Services MUST explicitly use `Annotated[T, Field(strict=True)]` if fine-grained field-level boundary constraints are required inside generic schemas.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is Pydantic V2 Rust-Core Strict Ingestion Boundary Standard critical for AI coding assistants?

Mandates compile-level strict validation mode and direct binary deserialization via pydantic-core at all external network boundaries. Eliminates silent implicit type coercion vulnerabilities and bypasses Python GIL runtime serialization bottlenecks by delegating parsing directly to the Rust core. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Lax Type Coercion and Intermediate Dict Allocation at Network Boundaries) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

1 Rule in Stack

Pydantic