python-programming-expert · diff
v4.4.2 to v4.4.2
268 added, 284 removed. Audit A to A.
---
name: python-programming-expert
description: "Expert-level skill for Python programming (Python 3.13/3.14+). Covers type safety, generic syntax (PEP 695), async/await TaskGroups, FastAPI 0.115+, Pydantic v2, uv package manager, Ruff, and pytest in English and Indonesian."
author: "Roedy Rustam"
version: "4.4.2"
---
# Python Programming Expert (3.14 Edition)
[English](#english) | [Bahasa Indonesia](#bahasa-indonesia)
---
<a name="english"></a>
## English
### Orchestration & Integration
- Connects and orchestrates with domain skills:
- - **AI & Agentic Systems**: `pydantic-ai-expert` (type-safe Pydantic agents), `ai-llm-integration-expert` (LangChain/LlamaIndex/LangGraph), and `vector-db-rag-expert` (pgvector, Qdrant).
- - **API Design & Contracts**: `api-design-expert`, `openapi-swagger-codegen-expert`, and `spec-driven-development-expert` for OpenAPI 3.1 generation, FastAPI schemas, and RFC 9457 Problem Details.
- - **Database Layer**: `database-orm-expert` for async SQLAlchemy 2.x, SQLModel, Alembic migrations, and connection pooling.
- - **Testing & Quality**: `autonomous-tdd-debugger`, `e2e-testing-expert`, and `anti-slop` for running `pytest -v`, self-healing test failures, and zero-slop production routines.
- - **Orchestration**: `brainstorming` and `zero-to-prod-orchestrator` (Phase 4: Backend & APIs).
+ - **AI & Agentic Systems**: `pydantic-ai-expert` (type-safe Pydantic agents), `ai-llm-integration-expert` (LangChain/LlamaIndex/LangGraph), `vector-db-rag-expert` (pgvector, Qdrant), `prompt-injection-firewall` (AI defense)
+ - **API Design & Contracts**: `api-design-expert`, `openapi-swagger-codegen-expert`, `spec-driven-development-expert` for OpenAPI 3.1 generation, FastAPI schemas, and RFC 9457 Problem Details
+ - **Database Layer**: `database-orm-expert` for async SQLAlchemy 2.x, SQLModel, Alembic migrations, connection pooling, and pgvector operations
+ - **Testing & Quality**: `autonomous-tdd-debugger`, `e2e-testing-expert`, `anti-slop` for running `pytest -v`, self-healing test failures, and zero-slop production code
+ - **Orchestration**: `brainstorming`, `zero-to-prod-orchestrator` (Phase 4: Backend & APIs)
### Description
- Expert-level Python development guidance for **Python 3.13 / 3.14+** covering JIT compilation, free-threaded (no-GIL) mode, modern type safety patterns, async architecture, and the full production stack: **FastAPI 0.115+**, **Pydantic v2**, **SQLAlchemy 2.x / SQLModel**, **uv**, **Ruff**, and **pytest-asyncio**.
+ Production-grade engineering standard for **Python 3.13 / 3.14+** enterprise applications, AI backends, and microservices. Covers free-threaded (no-GIL) execution (`python3.13t`), Tier-2 JIT compilation, PEP 695/696 generic type systems, structured concurrency with `asyncio.TaskGroup` and `asyncio.timeout`, high-throughput **FastAPI 0.115+**, **Pydantic v2**, async **SQLAlchemy 2.0**, and the Rust-powered **uv** toolchain.
### Trigger Conditions
- - Writing Python 3.13+ / 3.14+ applications or services.
- - Building **FastAPI 0.115+** REST APIs, **Django 5.x**, or **Litestar** web services.
- - Managing Python projects with the **`uv`** package manager.
- - Implementing async/await patterns with `asyncio.TaskGroup` or structured concurrency.
- - Writing type-safe Python with **Pydantic v2** and modern generics (PEP 695/696).
- - Setting up **Ruff** for linting + formatting; **pytest** with `pytest-asyncio` for testing.
- - Building AI backends integrating with LLM APIs (OpenAI, Anthropic, Google GenAI).
+ - Developing Python 3.13+ / 3.14+ backend microservices, async APIs, or AI pipelines.
+ - Building **FastAPI 0.115+** REST APIs, **Litestar**, or high-performance async web services.
+ - Managing project environments, dependencies, and lockfiles via **`uv`**.
+ - Leveraging true multi-threaded CPU parallel execution with Python 3.13 free-threaded mode (no GIL).
+ - Implementing structured concurrency with `asyncio.TaskGroup` and `asyncio.timeout`.
+ - Designing strictly typed schemas using **Pydantic v2** (`TypeAdapter`, `@computed_field`, `BaseSettings`).
+ - Structuring async database persistence with **SQLAlchemy 2.0** and `asyncpg`.
+ - Running linting, formatting, and tests via **Ruff** and **pytest-asyncio**.
---
### Python Version Matrix (2026)
- | Version | Status | Key Feature |
+ | Version | Status | Key Innovations |
|---|---|---|
- | **Python 3.14** | Latest Stable | PEP 696 type defaults, PEP 749 deferred evaluation, Tier-2 JIT |
- | **Python 3.13** | Stable LTS | JIT compiler, free-threaded mode (no GIL) |
- | **Python 3.12** | Supported | PEP 695 generics, `type` alias statement |
- | **Python 3.11** | Security only | `asyncio.TaskGroup`, `ExceptionGroup` |
+ | **Python 3.14** | Latest Release | PEP 696 type defaults, PEP 749 deferred annotation evaluation, Tier-2 JIT optimizations |
+ | **Python 3.13** | Stable LTS | Free-threaded build (no GIL: `python3.13t`), copy-and-patch JIT, improved interactive REPL |
+ | **Python 3.12** | Supported | PEP 695 type parameter syntax (`class Foo[T]:`), `type` alias statement |
+ | **Python 3.11** | Security only | `asyncio.TaskGroup`, `ExceptionGroup`, `asyncio.timeout` |
---
- ### Modern Python Toolchain (2026)
+ ### Modern Python Toolchain: `uv` & Ruff
- #### uv — The Standard Package Manager
- Replace `pip`, `pip-tools`, `virtualenv`, `pyenv`, and `poetry` entirely with **uv** (written in Rust — 10-100x faster):
- ```bash
- # Create project
- uv init my-api
- cd my-api
+ #### `uv` — Lightning-Fast Package Manager (Written in Rust)
+ `uv` replaces `pip`, `pip-tools`, `virtualenv`, `pyenv`, and `poetry` with 10-100x faster execution:
- # Add runtime dependencies
- uv add fastapi pydantic httpx sqlalchemy[asyncio]
+ ```bash
+ # 1. Initialize project with uv
+ uv init my-service --app
+ cd my-service
- # Add dev dependencies
- uv add --dev pytest pytest-asyncio ruff mypy httpx
+ # 2. Add dependencies with exact constraints
+ uv add fastapi pydantic pydantic-settings "sqlalchemy[asyncio]>=2.0" asyncpg httpx
- # Run scripts (no activation needed)
- uv run python main.py
- uv run pytest
- uv run fastapi dev main.py # Hot reload dev server
+ # 3. Add development and test dependency groups
+ uv add --group dev ruff mypy
+ uv add --group test pytest pytest-asyncio coverage
- # Pin exact Python version
- uv python pin 3.13
+ # 4. Run scripts and tests inside the managed environment
+ uv run fastapi dev main.py --port 8000
+ uv run pytest -v
- # Sync all environments
- uv sync
+ # 5. Lock and synchronize exact dependencies
+ uv lock
+ uv sync --frozen
```
- #### `pyproject.toml` — Single Config File
+ #### `pyproject.toml` — Single Canonical Configuration File
```toml
[project]
- name = "my-api"
+ name = "my-service"
version = "0.1.0"
+ description = "High-performance async Python service"
+ readme = "README.md"
requires-python = ">=3.13"
dependencies = [
- "fastapi>=0.115",
- "pydantic>=2.9",
- "sqlalchemy[asyncio]>=2.0",
- "asyncpg>=0.30",
+ "asyncpg>=0.30.0",
+ "fastapi>=0.115.0",
+ "httpx>=0.28.0",
+ "pydantic>=2.10.0",
+ "pydantic-settings>=2.7.0",
+ "sqlalchemy[asyncio]>=2.0.38",
]
+ [dependency-groups]
+ dev = [
+ "mypy>=1.14.0",
+ "ruff>=0.9.0",
+ ]
+ test = [
+ "pytest>=8.3.0",
+ "pytest-asyncio>=0.25.0",
+ ]
+
[tool.ruff]
- line-length = 88
+ line-length = 100
target-version = "py313"
[tool.ruff.lint]
- select = ["E", "F", "I", "N", "UP", "B", "SIM", "ANN", "ASYNC"]
-
- [tool.ruff.lint.per-file-ignores]
- "tests/**/*.py" = ["ANN"] # No type annotations required in tests
+ select = [
+ "E", # pycodestyle errors
+ "W", # pycodestyle warnings
+ "F", # Pyflakes
+ "I", # isort imports
+ "UP", # pyupgrade
+ "B", # flake8-bugbear
+ "SIM", # flake8-simplify
+ "ASYNC",# flake8-async
+ "RUF", # Ruff-specific rules
+ ]
[tool.pytest.ini_options]
- asyncio_mode = "auto" # pytest-asyncio auto mode
+ asyncio_mode = "auto"
+ testpaths = ["tests"]
```
---
- ### Type Safety — Modern Patterns
+ ### Python 3.13+ Free-Threaded Mode (No GIL Execution)
- #### PEP 695 — Generic Syntax (Python 3.12+)
+ Python 3.13 introduces the free-threaded build (`python3.13t`) where the Global Interpreter Lock is disabled. Unlike traditional Python where CPU-bound threads serialize on the GIL, free-threaded Python scales CPU tasks across all CPU cores using native worker threads without inter-process IPC overhead:
+
```python
- # Old way (verbose)
- from typing import TypeVar, Generic
- T = TypeVar('T')
- class Stack(Generic[T]):
- def push(self, item: T) -> None: ...
+ import os
+ import sys
+ import sysconfig
+ from concurrent.futures import ThreadPoolExecutor
+ import time
+ import math
- # New way (Python 3.12+) — clean, no boilerplate
- class Stack[T]:
- def __init__(self) -> None:
- self._items: list[T] = []
+ def check_gil_status() -> bool:
+ """Returns True if the Global Interpreter Lock is enabled."""
+ if hasattr(sys, "_is_gil_enabled"):
+ return sys._is_gil_enabled()
+ return True
- def push(self, item: T) -> None:
- self._items.append(item)
+ def cpu_intensive_kernel(number: int) -> int:
+ """Simulates CPU-heavy calculations (e.g. vector math, tokenization)."""
+ count = 0
+ for i in range(2, int(math.isqrt(number)) + 1):
+ if number % i == 0:
+ count += 1
+ return count
- def pop(self) -> T:
- return self._items.pop()
+ def run_multithreaded_workload(items: list[int]) -> list[int]:
+ gil_active = check_gil_status()
+ workers = os.cpu_count() or 4
+ print(f"Executing on {workers} cores | GIL Active: {gil_active}")
- # Generic functions
- def first[T](lst: list[T]) -> T:
- return lst[0]
+ start_time = time.perf_counter()
+ with ThreadPoolExecutor(max_workers=workers) as executor:
+ results = list(executor.map(cpu_intensive_kernel, items))
+
+ elapsed = time.perf_counter() - start_time
+ print(f"Processed {len(items)} items in {elapsed:.3f} seconds")
+ return results
- # Type aliases (PEP 695)
- type Vector = list[float]
- type Matrix[T] = list[list[T]]
+ if __name__ == "__main__":
+ workload = [10_000_000 + i for i in range(2000)]
+ run_multithreaded_workload(workload)
```
- #### PEP 696 — TypeVar Defaults (Python 3.14+)
+ ---
+
+ ### Type Safety — Modern 2026 Patterns
+
+ #### 1. Generic Syntax (PEP 695 & PEP 696)
```python
- # Default generic types — reduces boilerplate in libraries
- class Response[T = dict]: # T defaults to dict if not specified
- def __init__(self, data: T) -> None:
- self.data = data
+ # Clean generic class declaration without TypeVar boilerplate
+ class CacheStore[TKey, TValue = dict]:
+ def __init__(self) -> None:
+ self._storage: dict[TKey, TValue] = {}
- response = Response({"key": "value"}) # T inferred as dict
+ def set(self, key: TKey, value: TValue) -> None:
+ self._storage[key] = value
+
+ def get(self, key: TKey) -> TValue | None:
+ return self._storage.get(key)
+
+ # Generic type alias
+ type DatabaseRecord[ID: int | str] = dict[str, ID]
```
- #### Pydantic v2 — Production Data Validation
+ #### 2. Pydantic v2 Production Patterns
```python
- from pydantic import BaseModel, Field, field_validator, model_validator
- from pydantic import EmailStr, SecretStr
+ from pydantic import BaseModel, Field, EmailStr, SecretStr, computed_field, TypeAdapter
from typing import Annotated
- # Annotated types for reusability
- PositiveInt = Annotated[int, Field(gt=0)]
- TrimmedStr = Annotated[str, Field(min_length=1, strip_whitespace=True)]
+ # Reusable typed constraint aliases
+ ValidId = Annotated[int, Field(gt=0)]
+ Username = Annotated[str, Field(min_length=3, max_length=30, pattern=r"^[a-zA-Z0-9_-]+$")]
class UserCreate(BaseModel):
model_config = {"str_strip_whitespace": True}
- name: TrimmedStr = Field(max_length=50)
+ username: Username
email: EmailStr
- age: PositiveInt
- passphrase: SecretStr = Field(min_length=8)
+ password: SecretStr = Field(min_length=8)
- @field_validator('name')
- @classmethod
- def validate_name(cls, v: str) -> str:
- if not v.replace(' ', '').isalpha():
- raise ValueError('Name must contain only letters')
- return v.title()
+ class UserResponse(BaseModel):
+ id: ValidId
+ username: Username
+ email: EmailStr
+ first_name: str
+ last_name: str
- @model_validator(mode='after')
- def check_adult_email(self) -> 'UserCreate':
- if self.age < 18 and 'kids' not in self.email:
- raise ValueError('Minors must use a kids account email')
- return self
+ @computed_field
+ def full_name(self) -> str:
+ return f"{self.first_name} {self.last_name}".strip()
- # Usage
- user = UserCreate(name="alice smith", email="alice@example.com", age=25, passphrase="sample_valid_token")
- user.model_dump() # {'name': 'Alice Smith', 'email': 'alice@example.com', 'age': 25}
- user.model_dump(mode='json') # JSON-serializable dict
+ # High-speed batch parsing using TypeAdapter
+ batch_adapter = TypeAdapter(list[UserResponse])
+ def parse_user_batch(raw_json_data: list[dict]) -> list[UserResponse]:
+ return batch_adapter.validate_python(raw_json_data)
```
---
- ### FastAPI 0.115+ — Production Patterns
-
- #### Application Structure
- ```
- my_api/
- ├── main.py # FastAPI app + lifespan
- ├── routers/
- │ ├── users.py # APIRouter for /users
- │ └── posts.py # APIRouter for /posts
- ├── models/
- │ ├── user.py # Pydantic request/response models
- │ └── post.py
- ├── db/
- │ ├── database.py # SQLAlchemy engine + session
- │ └── models.py # ORM models
- ├── services/
- │ └── user_service.py # Business logic layer
- └── core/
- ├── config.py # Settings with Pydantic BaseSettings
- └── security.py # JWT, hashing
- ```
+ ### FastAPI 0.115+ Enterprise Architecture
- #### Lifespan — Startup & Shutdown
+ #### Clean Repository & Service Pattern with Async SQLAlchemy 2.0
```python
+ # db.py
+ from collections.abc import AsyncGenerator
from contextlib import asynccontextmanager
from fastapi import FastAPI
- from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker
-
- engine = create_async_engine(settings.DATABASE_URL, echo=False, pool_size=10)
- AsyncSessionLocal = async_sessionmaker(engine, expire_on_commit=False)
+ from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker, AsyncSession
+ from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
+ from sqlalchemy import String, Integer
- @asynccontextmanager
- async def lifespan(app: FastAPI):
- # Startup
- async with engine.begin() as conn:
- await conn.run_sync(Base.metadata.create_all)
- print("✅ Database connected")
- yield
- # Shutdown
- await engine.dispose()
- print("✅ Database disconnected")
+ class Base(DeclarativeBase):
+ pass
- app = FastAPI(title="My API", version="1.0.0", lifespan=lifespan)
- ```
+ class UserModel(Base):
+ __tablename__ = "users"
+ id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
+ username: Mapped[str] = mapped_column(String(30), unique=True, index=True)
+ email: Mapped[str] = mapped_column(String(255), unique=True)
- #### Dependency Injection Pattern
- ```python
- from typing import Annotated
- from fastapi import Depends, HTTPException, status
- from sqlalchemy.ext.asyncio import AsyncSession
+ # Connection pooling configuration
+ DATABASE_URL = "postgresql+asyncpg://postgres:postgres@localhost:5432/app_db"
+ engine = create_async_engine(
+ DATABASE_URL,
+ echo=False,
+ pool_size=20,
+ max_overflow=10,
+ pool_recycle=1800,
+ )
+ AsyncSessionLocal = async_sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)
- async def get_db() -> AsyncSession:
+ async def get_db_session() -> AsyncGenerator[AsyncSession, None]:
async with AsyncSessionLocal() as session:
yield session
-
- DbDep = Annotated[AsyncSession, Depends(get_db)]
-
- # In routes
- @router.get("/users/{user_id}", response_model=UserResponse)
- async def get_user(user_id: str, db: DbDep):
- user = await db.get(User, user_id)
- if not user:
- raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")
- return user
```
- #### Settings with Pydantic BaseSettings
```python
- from pydantic_settings import BaseSettings, SettingsConfigDict
-
- class Settings(BaseSettings):
- model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8")
-
- DATABASE_URL: str
- JWT_SIGNING_KEY: str
- ALGORITHM: str = "HS256"
- ACCESS_TOKEN_EXPIRE_MINUTES: int = 15
- ENVIRONMENT: str = "development"
-
- @property
- def is_production(self) -> bool:
- return self.ENVIRONMENT == "production"
+ # main.py
+ from contextlib import asynccontextmanager
+ from typing import Annotated
+ from fastapi import FastAPI, Depends, HTTPException, status
+ from fastapi.responses import JSONResponse
+ from sqlalchemy import select
+ from sqlalchemy.ext.asyncio import AsyncSession
+ from pydantic import BaseModel
- settings = Settings()
- ```
+ @asynccontextmanager
+ async def lifespan(app: FastAPI):
+ # Startup: ensure tables exist
+ async with engine.begin() as conn:
+ await conn.run_sync(Base.metadata.create_all)
+ yield
+ # Shutdown: cleanly close connection pool
+ await engine.dispose()
- #### Structured Error Handling (RFC 9457)
- ```python
- from fastapi import Request
- from fastapi.responses import JSONResponse
+ app = FastAPI(title="Core Backend Service", version="1.0.0", lifespan=lifespan)
- class AppException(Exception):
- def __init__(self, *, type: str, title: str, status: int, detail: str):
- self.type = type
+ # RFC 9457 Problem Details Exception Handler
+ class ProblemDetailsException(HTTPException):
+ def __init__(self, status_code: int, title: str, detail: str, type_url: str):
+ super().__init__(status_code=status_code, detail=detail)
self.title = title
- self.status = status
- self.detail = detail
+ self.type_url = type_url
- @app.exception_handler(AppException)
- async def app_exception_handler(request: Request, exc: AppException) -> JSONResponse:
+ @app.exception_handler(ProblemDetailsException)
+ async def problem_details_handler(request, exc: ProblemDetailsException):
return JSONResponse(
- status_code=exc.status,
+ status_code=exc.status_code,
+ media_type="application/problem+json",
content={
- "type": exc.type,
+ "type": exc.type_url,
"title": exc.title,
- "status": exc.status,
+ "status": exc.status_code,
"detail": exc.detail,
+ "instance": str(request.url),
}
)
- # Usage in routes
- raise AppException(
- type="https://myapi.com/errors/user-not-found",
- title="User Not Found",
- status=404,
- detail=f"User with id '{user_id}' does not exist",
- )
+ DbSession = Annotated[AsyncSession, Depends(get_db_session)]
+
+ @app.get("/users/{user_id}", response_model=UserResponse)
+ async def fetch_user(user_id: int, db: DbSession):
+ stmt = select(UserModel).where(UserModel.id == user_id)
+ result = await db.execute(stmt)
+ user = result.scalar_one_or_none()
+
+ if not user:
+ raise ProblemDetailsException(
+ status_code=status.HTTP_404_NOT_FOUND,
+ title="User Not Found",
+ detail=f"No active record found for user identifier {user_id}",
+ type_url="https://api.domain.com/errors/user-not-found"
+ )
+ return user
```
---
- ### Async Patterns
+ ### Structured Concurrency (`asyncio.TaskGroup` & `asyncio.timeout`)
- #### asyncio.TaskGroup (Python 3.11+)
+ Never use unbounded `asyncio.gather()` or obsolete `asyncio.wait_for`. Use `asyncio.TaskGroup` for deterministic failure isolation and `asyncio.timeout` for clean cancel-on-timeout management:
+
```python
import asyncio
-
- async def main():
- # Better than asyncio.gather — propagates exceptions immediately
- async with asyncio.TaskGroup() as tg:
- task_users = tg.create_task(fetch_users())
- task_posts = tg.create_task(fetch_posts())
- task_stats = tg.create_task(fetch_stats())
- # All tasks complete here — exception in any task cancels all others
- return task_users.result(), task_posts.result(), task_stats.result()
- ```
-
- #### Python 3.13 — JIT & Free-Threaded Mode
- ```bash
- # JIT compiler — 10-20% speedup on CPU-bound code
- PYTHON_JIT=1 python3.13 compute_heavy.py
-
- # Free-threaded build (no GIL) — true CPU parallelism
- uv python install 3.13t # install free-threaded build
- python3.13t -X gil=0 parallel_app.py
- ```
-
- ---
+ import httpx
- ### Testing with pytest + pytest-asyncio
- ```python
- # conftest.py
- import pytest
- from httpx import AsyncClient, ASGITransport
- from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker
+ async def fetch_metrics(service_name: str, endpoint: str) -> dict:
+ async with httpx.AsyncClient() as client:
+ # Enforce bounded deadline with structured timeout
+ async with asyncio.timeout(3.0):
+ response = await client.get(endpoint)
+ response.raise_for_status()
+ return {service_name: response.json()}
- TEST_DATABASE_URL = "sqlite+aiosqlite:///:memory:"
+ async def aggregate_cluster_health() -> dict[str, dict]:
+ results = {}
+ endpoints = {
+ "auth": "http://auth-service.internal/health",
+ "billing": "http://billing-service.internal/health",
+ "search": "http://search-service.internal/health",
+ }
- @pytest.fixture
- async def db_session():
- engine = create_async_engine(TEST_DATABASE_URL)
- async with engine.begin() as conn:
- await conn.run_sync(Base.metadata.create_all)
- async with async_sessionmaker(engine)() as session:
- yield session
- await engine.dispose()
+ try:
+ async with asyncio.TaskGroup() as tg:
+ tasks = {
+ service: tg.create_task(fetch_metrics(service, url))
+ for service, url in endpoints.items()
+ }
+
+ # When TaskGroup exits without error, all tasks are complete
+ for service, task in tasks.items():
+ results.update(task.result())
- @pytest.fixture
- async def client(db_session):
- app.dependency_overrides[get_db] = lambda: db_session
- async with AsyncClient(
- transport=ASGITransport(app=app), base_url="http://test"
- ) as ac:
- yield ac
+ except* TimeoutError as eg:
+ # Python 3.11+ ExceptionGroup pattern
+ print(f"One or more services timed out: {eg.exceptions}")
+ except* httpx.HTTPError as eg:
+ print(f"Service returned HTTP failure: {eg.exceptions}")
- # test_users.py
- async def test_create_user(client: AsyncClient):
- response = await client.post("/users", json={"name": "Alice", "email": "alice@test.com", "age": 25, "passphrase": "sample_valid_token"})
- assert response.status_code == 201
- data = response.json()
- assert data["email"] == "alice@test.com"
+ return results
```
---
<a name="bahasa-indonesia"></a>
## Bahasa Indonesia
### Integrasi Orkestrasi
- Terhubung dan mengorkestrasi bersama skill domain:
- - **AI & Sistem Agentic**: `pydantic-ai-expert` (agen Pydantic type-safe), `ai-llm-integration-expert` (LangChain/LlamaIndex/LangGraph), dan `vector-db-rag-expert` (pgvector, Qdrant).
- - **Desain & Kontrak API**: `api-design-expert`, `openapi-swagger-codegen-expert`, dan `spec-driven-development-expert` untuk pembuatan spesifikasi OpenAPI 3.1, skema FastAPI, dan standar RFC 9457 Problem Details.
- - **Lapisan Database**: `database-orm-expert` untuk SQLAlchemy 2.x async, SQLModel, migrasi Alembic, dan connection pooling.
- - **Pengujian & Kualitas**: `autonomous-tdd-debugger`, `e2e-testing-expert`, dan `anti-slop` untuk eksekusi `pytest -v`, perbaikan otomatis kegagalan tes, dan kode produksi bebas slop.
- - **Orkestrator Utama**: `brainstorming` dan `zero-to-prod-orchestrator` (Fase 4: Backend & APIs).
+ - **AI & Sistem Agentic**: `pydantic-ai-expert` (agen Pydantic type-safe), `ai-llm-integration-expert` (LangChain/LlamaIndex/LangGraph), `vector-db-rag-expert` (pgvector, Qdrant), `prompt-injection-firewall` (keamanan AI)
+ - **Desain & Kontrak API**: `api-design-expert`, `openapi-swagger-codegen-expert`, `spec-driven-development-expert` untuk OpenAPI 3.1, skema FastAPI, dan RFC 9457 Problem Details
+ - **Lapisan Database**: `database-orm-expert` untuk SQLAlchemy 2.x async, SQLModel, migrasi Alembic, connection pooling, dan operasi pgvector
+ - **Pengujian & Kualitas**: `autonomous-tdd-debugger`, `e2e-testing-expert`, `anti-slop` untuk eksekusi `pytest -v`, perbaikan mandiri kode tes, dan kepatuhan anti-slop
+ - **Orkestrator Utama**: `brainstorming`, `zero-to-prod-orchestrator` (Fase 4: Backend & APIs)
### Deskripsi
- Panduan pengembangan Python tingkat ahli untuk **Python 3.13/3.14+** mencakup JIT compilation, mode free-threaded (tanpa GIL), pola keamanan tipe modern, arsitektur async, dan stack produksi lengkap: **FastAPI 0.115+**, **Pydantic v2**, **SQLAlchemy 2.x**, **uv**, **Ruff**, dan **pytest-asyncio**.
+ Standar rekayasa perangkat lunak tingkat industri untuk aplikasi enterprise, backend AI, dan microservices berbasis **Python 3.13 / 3.14+**. Mencakup eksekusi free-threaded (tanpa GIL: `python3.13t`), kompilasi Tier-2 JIT, sistem tipe generic PEP 695/696, konkurensi terstruktur menggunakan `asyncio.TaskGroup` dan `asyncio.timeout`, arsitektur **FastAPI 0.115+**, **Pydantic v2**, async **SQLAlchemy 2.0**, serta toolchain modern berbasis Rust **uv**.
### Kondisi Pemicu
- - Menulis aplikasi atau layanan Python 3.13+/3.14+.
- - Membangun REST API FastAPI 0.115+, Django 5.x, atau Litestar.
- - Mengelola proyek Python dengan manajer paket `uv`.
- - Mengimplementasikan pola async/await dengan `asyncio.TaskGroup`.
- - Menulis Python type-safe dengan Pydantic v2 dan generik modern (PEP 695/696).
- - Menyiapkan Ruff untuk linting + formatting; pytest-asyncio untuk pengujian.
-
- ### Toolchain Modern (2026)
-
- **`uv`** menggantikan `pip`, `pip-tools`, `virtualenv`, `pyenv`, dan `poetry` — ditulis dalam Rust, 10-100x lebih cepat. Gunakan satu file `pyproject.toml` untuk semua konfigurasi.
-
- ### Keamanan Tipe — Pola Modern
-
- **PEP 695** (Python 3.12+): Sintaksis generic baru yang bersih tanpa boilerplate `TypeVar`. Gunakan `type` statement untuk alias tipe.
-
- **PEP 696** (Python 3.14+): Default untuk TypeVar — mengurangi boilerplate lebih lanjut pada library dan class generic.
-
- **Pydantic v2**: Gunakan `BaseModel`, `Field`, `@field_validator`, dan `@model_validator` untuk validasi data yang ketat. `model_dump()` dan `model_validate()` menggantikan metode v1.
-
- ### FastAPI 0.115+ — Pola Produksi
-
- - **Lifespan**: Gunakan `@asynccontextmanager` dengan `lifespan=` di `FastAPI()` untuk startup/shutdown yang bersih.
- - **Dependency Injection**: Gunakan `Depends()` dengan `Annotated` untuk sesi database, autentikasi, dll.
- - **BaseSettings**: Gunakan `pydantic-settings` untuk konfigurasi dari environment variables dengan validasi tipe.
- - **Error RFC 9457**: Format error yang konsisten dengan `type`, `title`, `status`, `detail`.
-
- ### Pola Async
-
- Gunakan `asyncio.TaskGroup` (Python 3.11+) sebagai pengganti `asyncio.gather()` — lebih aman karena propagasi exception langsung dan membatalkan semua task lain saat ada yang gagal.
+ - Membangun microservice backend, API async, atau pipeline AI dengan Python 3.13+/3.14+.
+ - Mengembangkan REST API performa tinggi menggunakan **FastAPI 0.115+** atau **Litestar**.
+ - Mengelola dependensi, environment, dan virtual environment menggunakan **`uv`**.
+ - Memanfaatkan paralelisme multi-thread CPU sejati menggunakan mode free-threaded Python 3.13 (tanpa batasan GIL).
+ - Mengimplementasikan konkurensi terstruktur dengan `asyncio.TaskGroup` dan `asyncio.timeout`.
+ - Merancang skema data validasi dengan Pydantic v2 (`TypeAdapter`, `@computed_field`, `BaseSettings`).
+ - Menyusun persistensi database async dengan SQLAlchemy 2.0 dan driver `asyncpg`.
+ - Menjalankan linter, formatter, dan pengujian dengan Ruff dan pytest-asyncio.
- Python 3.13 JIT: Aktifkan dengan `PYTHON_JIT=1` untuk kode CPU-bound. Free-threaded mode (`python3.13t -X gil=0`) untuk paralelisme CPU sejati.
+ ---
- ### Pengujian
+ ### Aturan Utama Python Modern (Standar 2026)
- Gunakan `pytest-asyncio` dengan `asyncio_mode = "auto"` di `pyproject.toml`. Gunakan `AsyncClient` dari `httpx` dengan `ASGITransport` untuk pengujian endpoint async yang bersih dan terisolasi tanpa perlu menjalankan server.
+ 1. **Gunakan `uv` Sebagai Manajer Paket Utama**: Tinggalkan `pip`, `poetry`, dan `virtualenv`. Gunakan `uv add`, `uv run`, `uv lock`, dan `uv sync` yang berjalan 10-100x lebih cepat.
+ 2. **Manfaatkan Bebas-GIL untuk Komputasi CPU**: Pada Python 3.13t, gunakan `ThreadPoolExecutor` untuk memproses tugas-tugas intensif CPU (vektorisasi, tokenisasi, enkripsi) di seluruh core prosesor tanpa overhead IPC multiprocessing.
+ 3. **Konkurensi Terstruktur (`TaskGroup`)**: Dilarang menggunakan `asyncio.gather()` tanpa penanganan pembatalan. Selalu gunakan blok `async with asyncio.TaskGroup() as tg:` untuk memastikan task yang gagal langsung membatalkan task paralel lainnya secara aman.
+ 4. **Validasi Skema dengan Pydantic v2**: Manfaatkan `TypeAdapter` untuk serialisasi batch berkecepatan tinggi dan `@computed_field` untuk properti terhitung yang ikut terserialisasi dalam skema OpenAPI.
+ 5. **Format Error Terstandarisasi RFC 9457**: Semua pengecualian HTTP pada FastAPI wajib mengembalikan format Problem Details (`application/problem+json`) yang konsisten dengan atribut `type`, `title`, `status`, dan `detail`.