arkteto 0.4.1
Transactional runtime kernel with context-scoped DI for FastAPI and ARQ
License: MIT
Requires Python: >=3.10

# ARKTETO

**Distributed Application Kernel for Python**

ARKTETO is an **execution runtime and dependency orchestration kernel** for Python that brings
**NestJS-style modular architecture, dependency injection, and execution isolation** to async Python applications.

It is designed for **FastAPI, ARQ, background workers, and distributed workflows**, turning your codebase into a **deterministic, scalable, and concurrency-safe execution engine**.

---

## What ARKTETO Solves

| Problem                      | Traditional Stack | ARKTETO           |
| ---------------------------- | ----------------- | ----------------- |
| Circular imports             | Common            | Impossible        |
| Global mutable state         | Unsafe            | Impossible        |
| Leaking DB sessions          | Common            | Impossible        |
| Singleton services           | Dangerous         | Explicit & Scoped |
| Job orchestration            | Ad-hoc            | Native            |
| Execution isolation          | Partial           | Guaranteed        |
| Async concurrency safety     | Hard              | Built-in          |
| Multi-tenant modular systems | Complex           | Native            |
| Deterministic workflows      | Rare              | Native            |

---

## Core Concepts

| Component            | Responsibility                           |
| -------------------- | ---------------------------------------- |
| `ContextVar Runtime` | Isolates execution state per request/job |
| `Container`          | Dependency Injection kernel with scopes  |
| `Scope`              | `SINGLETON` or `TRANSIENT` lifetimes     |
| `BaseProvider`       | Module boundary & dependency exports     |
| `BaseRepository`     | Transaction-scoped data access           |
| `BaseService`        | Stateless business logic                 |
| `BaseJob`            | Distributed workflow execution           |
| `JobMiddleware`      | Execution hooks (before / after / error) |
| `bootstrap()`        | Runtime context initializer              |

---

## Installation

```bash
pip install arkteto
```

---

## Bootstrapping the Runtime

ARKTETO **must always be bootstrapped using a context manager**.
This guarantees **automatic cleanup**, **no context leakage**, and **safe concurrency**.

---

### HTTP (FastAPI)

```python
from arkteto import bootstrap

@app.middleware("http")
async def arkteto_middleware(request, call_next):
    async with db_session() as session:
        with bootstrap(
            db_session=session,
            providers=ALL_PROVIDERS
        ):
            return await call_next(request)
```

✔ Each request gets:

* its own container
* its own DB session
* isolated execution context

---

### Background Jobs (ARQ)

```python
from arkteto import bootstrap

async def on_job_start(ctx):
    bootstrap_context = bootstrap(
        queue=ctx,
        providers=ALL_PROVIDERS
    )
    ctx["arkteto"] = bootstrap_context

class WorkerSettings:
    on_startup = on_job_start
```

Inside jobs, ARKTETO guarantees:

* isolated container per job execution
* safe access to queue and database
* deterministic job chaining

---

## Modules & Providers

Providers define **module boundaries** and **explicit exports**.

```python
from arkteto import BaseProvider

class CompanyProvider(BaseProvider):
    repositories = [CompanyRepository]
    services = [CompanyService]
    jobs = [SyncCompanyJob]
```

Providers:

* register dependencies into the container
* define service scopes
* prevent accidental coupling

---

## Repositories (Transaction-Scoped)

```python
from arkteto import BaseRepository

class CompanyRepository(BaseRepository):
    async def get(self, company_id):
        return await self.session.get(Company, company_id)
```

✔ All repositories:

* share the same DB session within the execution
* are automatically isolated per request/job
* never leak across concurrent executions

---

## Services (Resolved via Container)

Services are **not instantiated directly**.

```python
from arkteto import BaseService

class CompanyService(BaseService):
    def __init__(self, repo: CompanyRepository):
        self.repo = repo

    async def sync(self, company_id):
        ...
```

Usage:

```python
from arkteto import resolve

service = resolve(CompanyService)
```

✔ No globals
✔ No manual wiring
✔ No hidden magic
✔ Fully testable

---

## Jobs (Distributed Workflows)

Jobs represent **deterministic execution units**.

```python
from arkteto import BaseJob

class SyncCompanyJob(BaseJob):
    async def handle(self, company_id):
        service = self.container.resolve(CompanyService)
        await service.sync(company_id)
```

Inside a job you can safely enqueue other jobs:

```python
await self.queue.enqueue_job(
    FetchFinanceJob.dispatch,
    company_id
)
```

---

## Job Middlewares

Jobs support **immutable, class-level middlewares**.

```python
from arkteto import JobMiddleware

class TracingMiddleware(JobMiddleware):
    async def before(self, job):
        print("starting job")

    async def after(self, job):
        print("job finished")

class SyncCompanyJob(BaseJob):
    middlewares = (TracingMiddleware(),)

    async def handle(self, company_id):
        ...
```

Middlewares are:

* immutable
* thread-safe
* execution-order deterministic

---

## Job Registration & Workers

Jobs are registered explicitly and safely.

```python
SyncCompanyJob.as_function()
```

Expose them to ARQ:

```python
from arkteto.arq import get_worker_functions

functions = get_worker_functions()
```

✔ Thread-safe
✔ Idempotent
✔ No duplicate registrations

---

## Execution Guarantees

ARKTETO guarantees:

* ✔ Per-execution isolation
* ✔ Safe async concurrency
* ✔ Deterministic dependency resolution
* ✔ Scoped lifetimes (singleton vs transient)
* ✔ No global mutable state
* ✔ No context leakage
* ✔ Idempotent job registration
* ✔ Transaction consistency
* ✔ Multi-tenant readiness
* ✔ Replay & compensation ready

---

## Mental Model

```text
Request / Job
     ↓
bootstrap()
     ↓
ContextVar Runtime
     ↓
Container (Scoped)
     ↓
Services → Repositories
     ↓
DB / Queue
```

ARKTETO is **not a framework**.
It is a **runtime kernel** you embed into your system.

---

## What You’ve Built

> **A Distributed Application Kernel**
>
> Comparable to NestJS, Spring, and Temporal —
> but async-native, Pythonic, and designed for real concurrency.

---

## License

MIT