Metadata-Version: 2.4
Name: spanwire
Version: 0.1.0
Summary: Zero-dependency micro-tracing, distributed context propagation & breadcrumb telemetry engine for Python.
Author-email: Hamidreza <h4midrezam@gmail.com>
License-Expression: MIT
Project-URL: Homepage, https://github.com/mrhamidrezam/spanwire
Project-URL: Repository, https://github.com/mrhamidrezam/spanwire
Project-URL: Issues, https://github.com/mrhamidrezam/spanwire/issues
Keywords: tracing,distributed-tracing,opentelemetry,w3c,traceparent,baggage,breadcrumbs,telemetry,contextvars,zero-dependency,async
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: System :: Monitoring
Classifier: Topic :: System :: Logging
Classifier: Typing :: Typed
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Dynamic: license-file

<div align="center">

# ⚡ spanwire

**Zero-dependency micro-tracing, distributed context propagation & breadcrumb telemetry engine for Python.**

[![PyPI Version](https://img.shields.io/pypi/v/spanwire.svg?color=blue)](https://pypi.org/project/spanwire/)
[![Python Versions](https://img.shields.io/pypi/pyversions/spanwire.svg)](https://pypi.org/project/spanwire/)
[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](https://opensource.org/licenses/MIT)
[![CI](https://github.com/mrhamidrezam/spanwire/actions/workflows/ci.yml/badge.svg)](https://github.com/mrhamidrezam/spanwire/actions/workflows/ci.yml)
[![Typing: Typed](https://img.shields.io/badge/typing-typed-purple.svg)](https://peps.python.org/pep-0561/)
[![Dependencies: Zero](https://img.shields.io/badge/dependencies-0-brightgreen.svg)](#)

</div>

---

## 💡 Why spanwire?

Standard distributed tracing solutions (like OpenTelemetry SDK) pull in dozens of heavy transitive dependencies, incur noticeable startup delays, and add architectural bloat to lightweight microservices, CLI utilities, serverless functions (AWS Lambda, Cloud Run), and async LLM pipelines.

**spanwire** delivers enterprise-grade distributed telemetry and error context trails with **zero external dependencies**, utilizing pure Python standard library primitives (`contextvars`, `dataclasses`, `time`, `secrets`).

- **100% W3C Trace Context & Baggage Standard**: Interoperable with Datadog, Jaeger, Grafana Tempo, AWS X-Ray, and OpenTelemetry collectors.
- **Flawless Context Propagation**: Works out of the box across `asyncio` coroutines, background tasks, and OS threads without context leakage.
- **In-Memory Breadcrumb Trail**: Maintains an efficient circular ring-buffer of recent operational milestones, automatically attached when errors or exceptions occur.
- **Multiple Exporters**: ANSI-colorized CLI console, NDJSON/JSONLines for log aggregators (Vector, Fluentd, Promtail), or in-memory collectors for unit testing.
- **Deterministic Sampling**: Ratio-based trace hashing guarantees synchronized sampling decisions across distributed microservice boundaries.

---

## 📐 Architecture & Flow

```mermaid
sequenceDiagram
    autonumber
    participant Client as API Gateway (Service A)
    participant Wire as W3C HTTP Headers
    participant Worker as Downstream Worker (Service B)
    participant Exporter as Telemetry Exporter

    Client->>Client: Start Span ("checkout.process")
    Client->>Client: Record Breadcrumb ("User tier: VIP")
    Client->>Wire: Inject W3C traceparent & baggage headers
    Wire->>Worker: Forward HTTP Request
    Worker->>Worker: Extract W3C Context (inherits trace_id)
    Worker->>Worker: Execute child span ("db.persist_order")
    Worker-->>Exporter: Export child span ([OK] 12.4ms)
    Client-->>Exporter: Export parent span ([OK] 45.1ms)
```

---

## 🚀 Installation

```bash
pip install spanwire
```

*Requires Python 3.10 or higher. No third-party dependencies required.*

---

## ⚡ Quick Start

### 1. Basic Spans and Console Export

```python
import time
from spanwire import Tracer, ConsoleExporter

tracer = Tracer(
    service_name="payment-service",
    exporter=ConsoleExporter(colored=True)
)

tracer.add_breadcrumb("Validating customer cart", category="cart")

with tracer.span("process_payment", attributes={"order.id": "ord_1042", "amount": 89.00}) as span:
    time.sleep(0.02)
    
    # Nested child span
    with tracer.span("stripe.charge") as child:
        time.sleep(0.03)
        child.set_attribute("charge.id", "ch_abc123")
        tracer.add_breadcrumb("Payment captured via webhook", category="billing")
```

Console Output:
```text
⚡ [OK] stripe.charge (30.12ms) [trace=63d3791c.. span=ff0dba3fa8e11f3c parent=97bc44600e80142d]
   ↳ attributes: service.name='payment-service', charge.id='ch_abc123'
   ↳ breadcrumbs (2):
     - [INFO] cart: Validating customer cart
     - [INFO] billing: Payment captured via webhook
⚡ [OK] process_payment (50.84ms) [trace=63d3791c.. span=97bc44600e80142d]
   ↳ attributes: service.name='payment-service', order.id='ord_1042', amount=89.0
```

---

### 2. Distributed Tracing over HTTP (W3C Traceparent & Baggage)

```python
import requests
from spanwire import Tracer, set_baggage_item

tracer = Tracer(service_name="gateway")

# Set user context in baggage
set_baggage_item("user_id", "u_8841")

with tracer.span("http_outgoing_call") as span:
    # 1. Inject W3C headers into outbound HTTP request
    headers = {}
    tracer.inject_headers(headers)
    # headers contains:
    # 'traceparent': '00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01'
    # 'baggage': 'user_id=u_8841'

    # requests.get("https://worker.internal/api/tasks", headers=headers)
```

On the receiving downstream service:

```python
from spanwire import Tracer

worker_tracer = Tracer(service_name="worker")

def handle_incoming_request(incoming_headers: dict):
    # Extract parent context & baggage from headers
    parent_ctx, baggage, _ = worker_tracer.extract_headers(incoming_headers)

    # Continue the distributed trace seamlessly
    with worker_tracer.span("worker.handle_job", parent_context=parent_ctx) as span:
        print(f"Propagated trace_id: {span.context.trace_id}")
        print(f"Parent span_id:      {span.parent_span_id}")
        print(f"User ID from baggage: {baggage.get('user_id')}")
```

---

### 3. Asynchronous Function Decoration & LLM Agent Pipeline

```python
import asyncio
from spanwire import Tracer, ConsoleExporter

tracer = Tracer(service_name="llm-orchestrator", exporter=ConsoleExporter())

@tracer.trace(name="llm.generate_plan")
async def generate_plan(prompt: str) -> list[str]:
    tracer.add_breadcrumb(f"Generating plan for: {prompt[:30]}", category="llm")
    await asyncio.sleep(0.05)
    return ["search_db", "render_markdown"]

async def main():
    with tracer.span("orchestrate_query"):
        plan = await generate_plan("Summarize latest server telemetry")

asyncio.run(main())
```

---

## 🛠️ Exporters

| Exporter | Description | Best Suited For |
|---|---|---|
| `ConsoleExporter` | Formatted CLI output with ANSI colors, durations, and breadcrumb trails | Development, debugging, CLI tools |
| `JsonLinesExporter` | Newline-delimited JSON (NDJSON) output to file or stdout | Vector, Promtail, Datadog Agent, CloudWatch |
| `InMemoryExporter` | Stores finished spans in a thread-safe list | Pytest unit assertions, custom telemetry queues |
| `CallbackExporter` | Invokes custom callback function on each completed span | Custom event emission, Webhooks |

---

## 🎯 Samplers

- **`AlwaysOnSampler()`**: Traces 100% of operations (default).
- **`AlwaysOffSampler()`**: Disables tracing overhead completely.
- **`RatioSampler(ratio=0.1)`**: Probabilistically samples `10%` of traces using deterministic hashing on `trace_id`.
- **`ParentBasedSampler(root=...)`**: Respects the upstream service's sampling flag, with fallback to root sampler.

---

## 🧪 Running Unit Tests

```bash
python -m pytest tests -v
```

All 33 unit tests execute in ~0.15s with zero external test plugins.

---

## 📜 License

MIT License © 2026 Hamidreza Moghaddam Kohi. See [LICENSE](LICENSE) for details.
