Metadata-Version: 2.4
Name: sagaz
Version: 2.5.0
Summary: Production-ready Saga pattern with DAG support
License-Expression: MIT
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: aiofiles>=25.1.0
Requires-Dist: click>=8.1.0
Requires-Dist: python-dotenv>=1.0.0
Requires-Dist: python-statemachine<4,>=3.2.0
Requires-Dist: rich>=13.0.0
Requires-Dist: simple-term-menu>=1.6.0
Requires-Dist: PyYAML>=6.0.0
Provides-Extra: storage
Requires-Dist: asyncpg>=0.30.0; extra == "storage"
Requires-Dist: redis>=7.0.0; extra == "storage"
Provides-Extra: demo
Requires-Dist: testcontainers[postgres,redis]>=4.14.2; extra == "demo"
Provides-Extra: integration-tests
Requires-Dist: testcontainers[kafka,postgres,rabbitmq,redis]>=4.13.0; extra == "integration-tests"
Requires-Dist: aioboto3>=12.0.0; extra == "integration-tests"
Requires-Dist: zstandard>=0.22.0; extra == "integration-tests"
Provides-Extra: redis
Requires-Dist: redis>=7.1.0; extra == "redis"
Provides-Extra: sqlite
Requires-Dist: aiosqlite>=0.19.0; extra == "sqlite"
Provides-Extra: postgres
Requires-Dist: asyncpg>=0.31.0; extra == "postgres"
Provides-Extra: kafka
Requires-Dist: aiokafka>=0.12.0; extra == "kafka"
Provides-Extra: rabbitmq
Requires-Dist: aio-pika>=9.0.0; extra == "rabbitmq"
Provides-Extra: tracing
Requires-Dist: opentelemetry-api>=1.45.1; extra == "tracing"
Requires-Dist: opentelemetry-exporter-otlp-proto-grpc>=1.39.1; extra == "tracing"
Requires-Dist: opentelemetry-sdk>=1.39.1; extra == "tracing"
Provides-Extra: prometheus
Requires-Dist: prometheus-client>=0.23.1; extra == "prometheus"
Provides-Extra: analytics
Requires-Dist: duckdb>=1.0.0; extra == "analytics"
Requires-Dist: sqldim<2.1,>=2.0.1; extra == "analytics"
Requires-Dist: narwhals>=1.0.0; extra == "analytics"
Provides-Extra: visualization
Requires-Dist: fastapi>=0.100.0; extra == "visualization"
Requires-Dist: uvicorn[standard]>=0.23.0; extra == "visualization"
Requires-Dist: sse-starlette>=1.0.0; extra == "visualization"
Provides-Extra: monitor
Requires-Dist: sagaz[visualization]; extra == "monitor"
Provides-Extra: gradio
Requires-Dist: gradio>=5.25.0; extra == "gradio"
Provides-Extra: schema-registry
Requires-Dist: confluent-kafka[avro,json,schemaregistry]>=2.10.0; extra == "schema-registry"
Provides-Extra: aws
Requires-Dist: aioboto3>=12.0.0; extra == "aws"
Requires-Dist: zstandard>=0.22.0; extra == "aws"
Provides-Extra: iceberg
Requires-Dist: pyiceberg[pyarrow,sql-postgres,sql-sqlite]>=0.9.0; extra == "iceberg"
Requires-Dist: duckdb>=1.0.0; extra == "iceberg"
Requires-Dist: prometheus-client>=0.20.0; extra == "iceberg"
Provides-Extra: fluss
Requires-Dist: pyfluss>=1.0.0; python_version < "3.13" and extra == "fluss"
Requires-Dist: pyarrow>=15.0.0; extra == "fluss"
Provides-Extra: cdc
Requires-Dist: psycopg2-binary>=2.9.9; extra == "cdc"
Requires-Dist: aiokafka>=0.12.0; extra == "cdc"
Requires-Dist: httpx>=0.28.1; extra == "cdc"
Provides-Extra: encryption
Requires-Dist: cryptography>=46.0.7; extra == "encryption"
Provides-Extra: compression
Requires-Dist: zstandard>=0.22.0; extra == "compression"
Dynamic: license-file

# Sagaz - Production-Ready Saga Pattern for Python

[![codecov](https://codecov.io/gh/brunolnetto/sagaz/branch/main/graph/badge.svg)](https://codecov.io/gh/brunolnetto/sagaz)
[![Tests](https://github.com/brunolnetto/sagaz/actions/workflows/test-gates.yml/badge.svg?branch=main)](https://github.com/brunolnetto/sagaz/actions/workflows/test-gates.yml)
[![Python](https://img.shields.io/badge/python-3.11+-blue.svg)](https://www.python.org/)
[![License](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/brunolnetto/sagaz/blob/main/LICENSE)
[![PyPI](https://img.shields.io/pypi/v/sagaz.svg)](https://pypi.org/project/sagaz/)

**Enterprise-grade distributed transaction orchestration with exactly-once semantics.**

---

## Features

### Core Saga Pattern
- **Sequential & Parallel (DAG) execution** - Optimize throughput with dependency graphs
- **Automatic compensation** - Rollback on failures with transaction safety
- **Three failure strategies** - FAIL_FAST, WAIT_ALL, FAIL_FAST_WITH_GRACE
- **Retry logic** - Exponential backoff with configurable limits
- **Timeout protection** - Per-step and global timeouts
- **Idempotency support** - Safe retries and recovery

### Transactional Outbox Pattern
- **Exactly-once delivery** - Transactional event publishing
- **Optimistic sending** - 10x latency improvement (<10ms)
- **Consumer inbox** - Exactly-once processing guarantee
- **Multiple brokers** - Redis Streams, Kafka, RabbitMQ, or in-memory
- **Dead letter queue** - Automatic failure handling
- **Worker auto-scaling** - Kubernetes HPA support

### Configuration & Developer Experience
- **Unified SagaConfig** - Single config for storage, broker, observability
- **Environment variables** - 12-factor app support via `SagaConfig.from_env()`
- **Mermaid diagrams** - `saga.to_mermaid()` for flowchart visualization
- **Connected graph validation** - Enforces single connected component in DAG sagas
- **Global configuration** - Configure once, all sagas inherit
- **Type-safe instances** - Real storage/broker instances, not brittle strings

### Choreography & Event-Driven Sagas
- **Choreographed sagas** - Participants react to events on a bus, with compensation requests and reports
- **Guarantees** - Idempotent delivery, tombstones for late events, deadlines, durable participant state
- **Tracker** - Status of every choreographed transaction, with stalled-transaction detection

### Unified Saga Log
- **One OLTP model** - Orchestrated and choreographed sagas in the same append-only log, shareable between services
- **Atomic publication** - Choreography state and events written together, delivered through the outbox
- **Per-participant write policies** - PostgreSQL row-level security per tenant and per service role
- **Event sourcing** - Rebuild any saga from its events, with snapshots and replay

### Multi-Tenancy & Multi-Region
- **Tenant isolation** - Tenant scope on every store, with PostgreSQL row-level security
- **Multi-region routing** - Step affinity, data residency, and same-jurisdiction failover

### Analytics
- **Embedded pipeline** - DuckDB reports over the saga log (`sagaz[analytics]`), served by `sagaz monitor`
- **Streaming and history** - Export the log to Apache Fluss, tiered to Apache Iceberg (`sagaz[fluss]`)
- **Flink SQL reports** - `sagaz analytics flink-sql` over the Iceberg history
- **Prometheus metrics** - Flow summary from Iceberg (`sagaz[iceberg]`), with a Grafana dashboard

### Storage Backends
- **SQLite** - File-based persistence for local development and smaller deployments
- **PostgreSQL** - Production-grade with ACID guarantees
- **Redis** - High-performance storage backend
- **In-Memory** - Testing and development

### Monitoring & Operations
- **Prometheus metrics** - 40+ metrics exposed
- **OpenTelemetry tracing** - Distributed tracing support
- **Structured logging** - JSON logs with correlation IDs
- **Grafana dashboard** - Ready-to-import JSON template
- **Change data capture** - Outbox relay through PostgreSQL logical replication or Debezium
- **Kubernetes manifests** - Production-ready deployment
- **Health checks** - Liveness and readiness probes
- **Chaos engineering tests** - 12 resilience tests validating production readiness

---

## Installation

```bash
# Core library (includes the CLI)
pip install sagaz

# With SQLite persistence
pip install "sagaz[sqlite]"

# With PostgreSQL support
pip install "sagaz[postgres]"

# With Redis support
pip install "sagaz[redis]"

# With both PostgreSQL and Redis storage adapters
pip install "sagaz[storage]"

# With Kafka broker
pip install "sagaz[kafka]"

# Analytics: embedded (DuckDB), Fluss export, Iceberg metrics
pip install "sagaz[analytics]" "sagaz[fluss]" "sagaz[iceberg]"

# Change data capture (PostgreSQL logical replication, Debezium)
pip install "sagaz[cdc]"
```

### CLI Deployment Scenarios

The CLI is included in the core package; use it for your deployment scenario:

```bash
# Local development (Docker Compose)
sagaz init --local
sagaz dev

# Self-hosted/on-premise servers
sagaz init --selfhost

# Kubernetes (cloud-native)  
sagaz init --k8s

# Hybrid (local DB + cloud broker)
sagaz init --hybrid

# Run benchmarks
sagaz benchmark
sagaz benchmark --profile stress
```

### CLI Examples Browser

Explore and run built-in examples directly from the CLI:

```bash
# List all available examples
sagaz examples list

# Filter by industry (display or folder name)
sagaz examples list --domain consumer_goods
sagaz examples list --domain "Banking & Financial Services"

# Run a specific example
sagaz examples run retail_ecommerce/commerce/order_processing
sagaz examples run consumer_goods/product/product_recall

# Interactive selection menu
sagaz examples select
sagaz examples select --category ml
```

**Available Categories:**
- `ecommerce` - Order processing workflows
- `fintech` - Payment & trading systems  
- `healthcare` - Patient onboarding
- `integrations` - FastAPI, Flask, Django integration examples (requires `uv pip install uvicorn werkzeug asgiref`)
- `iot` - Device orchestration, smart grid
- `logistics` - Drone delivery
- `ml` - Training pipelines, federated learning
- `monitoring` - Metrics and observability
- `travel` - Booking systems

---

## Quick Start

`sagaz.Saga` (`from sagaz import Saga`) is the class to use. It supports two usage modes;
you choose one approach per saga, since mixing is not allowed. A failed `run()` raises
`SagaFailedError` (see the [quickstart](https://github.com/brunolnetto/sagaz/blob/main/docs/quickstart.md#3-when-a-saga-fails)).

### Mode 1: Declarative (Decorators)

Best for sagas defined as classes with clear step methods:

```python
from sagaz import Saga, action, compensate

class OrderSaga(Saga):
    saga_name = "order-processing"
    
    @action("reserve_inventory")
    async def reserve_inventory(self, ctx):
        inventory_id = await inventory_service.reserve(ctx["order_id"])
        return {"inventory_id": inventory_id}
    
    @compensate("reserve_inventory")
    async def release_inventory(self, ctx):
        await inventory_service.release(ctx["inventory_id"])
    
    @action("charge_payment", depends_on=["reserve_inventory"])
    async def charge_payment(self, ctx):
        return await payment_service.charge(ctx["amount"])

# Execute saga
saga = OrderSaga()
result = await saga.run({"order_id": "123", "amount": 99.99})
```

### Mode 2: Imperative (add_step)

Best for dynamic sagas or when steps are defined at runtime:

```python
from sagaz import Saga

# Create saga and add steps programmatically
saga = Saga(name="order-processing")

# Method chaining for fluent API
saga.add_step("validate", validate_order)
saga.add_step("reserve", reserve_inventory, release_inventory, depends_on=["validate"])
saga.add_step("charge", charge_payment, refund_payment, depends_on=["reserve"])
saga.add_step("ship", ship_order, depends_on=["charge"])

# Execute
result = await saga.run({"order_id": "123", "amount": 99.99})
```

> **Note:** You cannot mix both approaches. Once you use decorators, `add_step()` will raise an error, and vice versa.

> **Which `Saga`?** Use `sagaz.Saga`. Another class, `sagaz.core.saga.Saga`
> (`await add_step(...)`, `execute()` returning a `SagaResult`), is the engine behind
> snapshot replay (`SagaReplay`) and `SagaOrchestrator`. Use it only for those; it will be
> merged into `sagaz.Saga`. Its `add_step` also accepts `sagaz.Saga`'s parameter names
> (`depends_on`, `timeout_seconds`).

### Transactional Outbox + Optimistic Sending

```python
from sagaz.core.outbox import OptimisticPublisher, OutboxWorker
from sagaz.core.storage.backends.postgresql import PostgreSQLOutboxStorage
from sagaz.core.outbox import KafkaBroker

# Setup
storage = PostgreSQLOutboxStorage("postgresql://localhost/db")
broker = KafkaBroker(bootstrap_servers="localhost:9092")
publisher = OptimisticPublisher(storage, broker, enabled=True)

# Publish event transactionally
async with db.transaction():
    await saga_storage.save(saga)
    await outbox_storage.insert(event)
    # Transaction committed

# Immediate publish (< 10ms)
await publisher.publish_after_commit(event)
# Falls back to worker if fails
```

### Consumer Inbox (Exactly-Once)

```python
from sagaz.core.outbox import ConsumerInbox

inbox = ConsumerInbox(storage, consumer_name="order-service")

async def process_order(payload: dict):
    order = await create_order(payload)
    return {"order_id": order.id}

# Exactly-once processing - duplicates automatically skipped
result = await inbox.process_idempotent(
    event_id=msg.headers['message_id'],
    source_topic=msg.topic,
    event_type="OrderCreated",
    payload=msg.value,
    handler=process_order
)
```

### Unified Configuration

```python
from sagaz import SagaConfig, configure, create_storage_manager  

# NEW: Unified StorageManager (recommended)
# Manages connection pooling for both saga and outbox storage
manager = create_storage_manager("postgresql://localhost/db")
await manager.initialize()

config = SagaConfig(
    storage_manager=manager,
    broker=KafkaBroker(bootstrap_servers="localhost:9092"),
    metrics=True,
)
configure(config)

# OR: Traditional separate configuration
config = SagaConfig(
    storage=PostgreSQLSagaStorage("postgresql://localhost/db"),
    broker=KafkaBroker(...),
    metrics=True,
)
configure(config)

# Or from environment variables (12-factor app)
config = SagaConfig.from_env()  # Reads SAGAZ_STORAGE_URL, etc.
```

### Mermaid Diagram Visualization

```python
from sagaz import Saga, action, compensate

class OrderSaga(Saga):
    saga_name = "order"
    
    @action("reserve")
    async def reserve(self, ctx): return {}
    
    @compensate("reserve")
    async def release(self, ctx): pass
    
    @action("charge", depends_on=["reserve"])
    async def charge(self, ctx): return {}
    
    @compensate("charge")
    async def refund(self, ctx): pass

saga = OrderSaga()

# Generate Mermaid diagram with state markers
print(saga.to_mermaid())

# Visualize specific execution from storage
diagram = await saga.to_mermaid_with_execution(
    saga_id="abc-123",
    storage=PostgreSQLSagaStorage(...)
)
```

**Output:** State machine diagram with START/SUCCESS/ROLLED_BACK markers, color-coded paths (green=success, amber=compensation, red=failure), and execution trail highlighting.

---

## Kubernetes Deployment

```bash
# One-command deployment
kubectl create namespace sagaz
kubectl apply -f k8s/

# Deployed components:
# - PostgreSQL StatefulSet (20Gi persistent storage)
# - Outbox Worker Deployment (3-10 replicas with HPA)
# - Prometheus ServiceMonitor + 8 Alert Rules
# - Database Migration Job
```

**Features:**
- Auto-scaling based on pending events
- Zero-downtime rolling updates
- Built-in health checks
- Production security (non-root, read-only fs)
- Complete monitoring stack

See [`sagaz/deployment/resources/k8s/README.md`](https://github.com/brunolnetto/sagaz/blob/main/sagaz/deployment/resources/k8s/README.md) for the detailed deployment guide.

---

## Monitoring

### Prometheus Metrics

```python
# Saga metrics
saga_execution_total{status}
saga_execution_duration_seconds
saga_step_duration_seconds{step_name}

# Outbox metrics
outbox_pending_events_total
outbox_published_events_total
outbox_optimistic_send_success_total
consumer_inbox_duplicates_total
```

### Grafana Dashboard

Ready-to-import dashboards:

- **Sagas and outbox:** [`main-dashboard.json`](https://github.com/brunolnetto/sagaz/blob/main/sagaz/deployment/resources/k8s/monitoring/dashboards/main-dashboard.json) and [`outbox-dashboard.json`](https://github.com/brunolnetto/sagaz/blob/main/sagaz/deployment/resources/k8s/monitoring/dashboards/outbox-dashboard.json).
- **Saga flows from the Iceberg history:** ["Sagaz - Saga Flows"](https://github.com/brunolnetto/sagaz/blob/main/sagaz/deployment/resources/local/lakehouse/grafana/dashboards/sagaz-flows.json).

### Grafana Alerts

- **OutboxHighLag** - >5000 pending events for 10min
- **OutboxWorkerDown** - No workers running
- **OutboxHighErrorRate** - >1% publish failures
- **OptimisticSendHighFailureRate** - >10% optimistic failures

---

## Chaos Engineering

Production readiness validated through deliberate failure injection.

The library includes comprehensive chaos engineering tests that verify system resilience:

### Test Categories

- **Worker Crash Recovery** - Workers can recover from crashes, no data loss
- **Database Connection Loss** - Graceful handling of DB failures with retry
- **Broker Downtime** - Messages not lost when broker unavailable
- **Network Partitions** - No duplicate processing under split-brain
- **Concurrent Failures** - System recovers from multiple simultaneous failures
- **Data Consistency** - Exactly-once guarantees maintained under chaos

### Run Chaos Tests

```bash
# Run all chaos engineering tests
pytest tests/integration/test_chaos_engineering.py -v -m chaos

# Test specific failure scenario
pytest tests/integration/test_chaos_engineering.py::TestWorkerCrashRecovery -v
```

**Key Findings:**
- No data loss even with 30% random failure rate
- Exactly-once processing with 5 concurrent workers
- Graceful handling of 50 events under extreme load
- Automatic recovery with exponential backoff

See [ADR-017](https://github.com/brunolnetto/sagaz/blob/main/docs/architecture/adr/adr-017-chaos-engineering.md) for the chaos engineering design.

---

## Documentation

| Topic | Link |
|-------|------|
| **Documentation Home** | [docs/README.md](https://github.com/brunolnetto/sagaz/blob/main/docs/README.md) |
| **Configuration Guide** | [docs/guides/configuration.md](https://github.com/brunolnetto/sagaz/blob/main/docs/guides/configuration.md) |
| **DAG Pattern** | [docs/architecture/deep-dives/compensation-graph-deep-dive.md](https://github.com/brunolnetto/sagaz/blob/main/docs/architecture/deep-dives/compensation-graph-deep-dive.md) |
| **Optimistic Sending** | [docs/patterns/optimistic-sending.md](https://github.com/brunolnetto/sagaz/blob/main/docs/patterns/optimistic-sending.md) |
| **Consumer Inbox** | [docs/patterns/consumer-inbox.md](https://github.com/brunolnetto/sagaz/blob/main/docs/patterns/consumer-inbox.md) |
| **Unified Saga Log** | [docs/guides/unified-saga-log.md](https://github.com/brunolnetto/sagaz/blob/main/docs/guides/unified-saga-log.md) |
| **Event Sourcing** | [docs/guides/event-sourcing.md](https://github.com/brunolnetto/sagaz/blob/main/docs/guides/event-sourcing.md) |
| **Multi-Tenancy** | [docs/guides/multi-tenancy.md](https://github.com/brunolnetto/sagaz/blob/main/docs/guides/multi-tenancy.md) |
| **Multi-Region** | [docs/guides/multi-region.md](https://github.com/brunolnetto/sagaz/blob/main/docs/guides/multi-region.md) |
| **Fluss & Iceberg Analytics** | [docs/monitoring/fluss-iceberg-analytics.md](https://github.com/brunolnetto/sagaz/blob/main/docs/monitoring/fluss-iceberg-analytics.md) |
| **Kubernetes Deploy** | [sagaz/deployment/resources/k8s/README.md](https://github.com/brunolnetto/sagaz/blob/main/sagaz/deployment/resources/k8s/README.md) |
| **Observability Reference** | [docs/monitoring/OBSERVABILITY_REFERENCE.md](https://github.com/brunolnetto/sagaz/blob/main/docs/monitoring/OBSERVABILITY_REFERENCE.md) |
| **Architecture Decisions** | [docs/architecture/adr/README.md](https://github.com/brunolnetto/sagaz/blob/main/docs/architecture/adr/README.md) |
| **Changelog** | [docs/development/changelog.md](https://github.com/brunolnetto/sagaz/blob/main/docs/development/changelog.md) |

---

## Performance

| Operation | Latency | Notes |
|-----------|---------|-------|
| Saga execution | ~50ms | Baseline |
| Outbox polling | ~100ms | Baseline |
| Optimistic publish | <10ms | 10x faster |
| Inbox dedup check | <1ms | Sub-millisecond |

**Tested on:**
- PostgreSQL 16
- Kafka 3.x
- 4 CPU cores, 8GB RAM

---

## Production Stats

- **98% unit test coverage** (4,800+ passing tests), plus integration, chaos and lakehouse end-to-end suites
- **Type-safe** - Full type hints, checked with mypy
- **Small core** - Integrations are optional extras
- **Well-documented** - Comprehensive examples
- **Battle-tested** - Production-ready
- **Kubernetes-native** - Cloud-ready deployment
- **Mermaid visualization** - Auto-generated saga diagrams

---

## Development

```bash
# Clone repository
git clone https://github.com/brunolnetto/sagaz.git
cd sagaz

# Install dependencies (using uv)
uv sync --all-extras

# Run tests
uv run pytest

# With coverage
uv run pytest --cov=sagaz --cov-report=html
```

---

## License

MIT License - see [LICENSE](https://github.com/brunolnetto/sagaz/blob/main/LICENSE) file for details.

---

## Project Status

**Current Version**: 2.5.0 (November 2026)

**Recent releases:**
- **v2.5.0** - Security and typing: signed external context storage, dependencies without known advisories, CI gates on mypy, bandit, pip-audit and coverage, every function annotated, and three outbox and CLI bugs the types exposed. Two breaking changes; see the changelog.
- **v2.4.0** - Developer experience: retries, durability and a run-once saga id that keep their promises, one failure contract (`SagaFailedError`), a 1 MB package, documentation that runs, and a feature × mode matrix.
- **v2.3.0** - StateChart step charts with pivot/taint states and compensation re-entry, a CDC reader for the saga log export, a Gradio asset monitor and a schema registry for saga events.
- **v2.2.0** - Streaming and historical analytics on the saga log. The log is exported to Apache Fluss and tiered to Apache Iceberg, with Flink SQL reports, Prometheus metrics and a Grafana dashboard.
- **v2.1.0** - Unified saga log: one OLTP model for orchestrated and choreographed sagas, with atomic choreography publication and analytics over both coordination styles.
- **v2.0.0** - Event sourcing and multi-region routing with data residency.
- **v1.10.0** - Event-driven choreography with delivery guarantees.

See the [changelog](https://github.com/brunolnetto/sagaz/blob/main/docs/development/changelog.md) for every release and the [release plan](https://github.com/brunolnetto/sagaz/blob/main/docs/planning/release-plan.md) for what comes next.
