Metadata-Version: 2.5
Name: corobots-async-sdk
Version: 1.1.0
Summary: asyncio Python SDK for CoRobots — client and step worker, GIL-free on free-threaded CPython
Project-URL: Homepage, https://github.com/coredgeio/corobots
Project-URL: Repository, https://github.com/coredgeio/corobots
Project-URL: Issues, https://github.com/coredgeio/corobots/issues
Author-email: "Coredge.io" <ashok@coredge.io>
License: Apache-2.0
Keywords: asyncio,free-threading,grpc,orchestration,saga,workflow
Classifier: Development Status :: 4 - Beta
Classifier: Framework :: AsyncIO
Classifier: Framework :: FastAPI
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
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: Programming Language :: Python :: Free Threading :: 2 - Beta
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: System :: Distributed Computing
Requires-Python: >=3.9
Requires-Dist: connectrpc<0.13,>=0.12; python_version >= '3.11'
Requires-Dist: grpcio>=1.74; python_version < '3.11'
Requires-Dist: httpx>=0.27
Requires-Dist: protobuf>=6.31.1
Requires-Dist: pydantic>=2.0
Requires-Dist: pyyaml>=6.0
Provides-Extra: dev
Requires-Dist: fastapi>=0.110; extra == 'dev'
Requires-Dist: grpcio>=1.74; extra == 'dev'
Requires-Dist: pytest-cov>=5.0; extra == 'dev'
Requires-Dist: pytest-httpx>=0.30; extra == 'dev'
Requires-Dist: pytest>=8.0; extra == 'dev'
Requires-Dist: uvicorn>=0.29; extra == 'dev'
Provides-Extra: fastapi
Requires-Dist: fastapi>=0.110; extra == 'fastapi'
Provides-Extra: grpcio
Requires-Dist: grpcio>=1.74; extra == 'grpcio'
Description-Content-Type: text/markdown

# corobots-async-sdk

asyncio Python SDK for [CoRobots](https://github.com/coredgeio/corobots): an
engine client (`AsyncCorobotsClient`) and a step worker (`AsyncWorkerClient`)
whose calls never block the event loop, and which run **without the GIL on
free-threaded CPython** (`python3.14t`).

It is the asyncio counterpart of [`corobots-sdk`](../python/README.md), as its
own package: same models, workflow builder, schedules, messaging and step
semantics, and the same wire protocol to the engine. It never needs grpcio,
which has no free-threaded build and re-enables the GIL when imported.

```bash
pip install corobots-async-sdk            # every supported Python, python3.14t included
pip install "corobots-async-sdk[fastapi]" # + FastAPI integration
pip install "corobots-async-sdk[grpcio]"  # optional: grpcio's grpc.aio on 3.11+ too
```

```python
import corobots_async_sdk
```

Use one SDK per process: `corobots-sdk` for blocking code, this one for
asyncio services and free-threaded workers. They talk to the same engine and
can run side by side in one system.

## Python versions and the GIL

| You run | gRPC library installed and used | GIL |
|---|---|---|
| Python 3.9 – 3.10 | grpcio (`grpc.aio`) | on (normal) |
| Python 3.11 – 3.14 (regular build) | connectrpc (gRPC protocol over HTTP/2); grpcio's `grpc.aio` if you add `[grpcio]` | on (normal) |
| Python 3.14t+ (free-threaded) | connectrpc; grpcio is never installed or imported | **off** |

`pip install corobots-async-sdk` picks the right dependencies per version
(connectrpc needs Python 3.11+). On free-threaded CPython nothing else is
needed: check with `python -VV` (it says `free-threading build`) and
`python -c "import sys; print(sys._is_gil_enabled())"` (prints `False`).

The library behind the gRPC calls is chosen by `transport=` on both classes:

| `transport=` | gRPC library |
|---|---|
| `"auto"` (default) | grpcio's `grpc.aio` where it is importable on a GIL build; connectrpc otherwise (always on free-threaded CPython) |
| `"grpcio"` | always `grpc.aio` (needs grpcio) |
| `"connect"` | always connectrpc (Python 3.11+) |

Both send the same requests and the same service token, and support the same
TLS options (`tls`, `ca_file`, client certificate, `server_name`). One
difference: on connectrpc every failed RPC raises `EngineError`, while
grpcio raises a raw `grpc.RpcError` from the non-schedule RPCs (as
`corobots_sdk.CorobotsClient` does). `EngineError.grpc_status` holds the
status name (`"PERMISSION_DENIED"`) on both; `EngineError.grpc_code` is the
`grpc.StatusCode` wherever grpcio is loaded, and None on free-threaded
CPython. With connectrpc, `engine_grpc` must be `host:port` (no `dns:///` or
`unix:` targets).

What to know on free-threaded CPython:

- **Your other dependencies must be free-threading-ready too.** Importing a
  C extension that does not support free-threading re-enables the GIL;
  Python prints a `RuntimeWarning` saying so. Run with
  `python -W error::RuntimeWarning` to turn that into an error, or check
  `sys._is_gil_enabled()` at startup.
- **Do not force the GIL off** with `PYTHON_GIL=0` to load a library that is
  not ready for it (grpcio included): that is unsupported and can crash.
- Tested on 3.14t; 3.13t has not been tested.

## Engine client

`AsyncCorobotsClient` has the same constructor arguments, methods, results
and `EngineError`s as `corobots_sdk.CorobotsClient`, each method a
coroutine. HTTP goes through `httpx.AsyncClient`; gRPC through the transport
above.

```python
import asyncio
from corobots_async_sdk import AsyncCorobotsClient

async def main():
    async with AsyncCorobotsClient(
        "http://engine:50051", engine_grpc="engine:50052",
        api_token="crp_...", project_id="proj-123", service_token="crsvc_...",
    ) as client:
        runs = await asyncio.gather(
            *(client.start_workflow("provision", {"region": r}) for r in ("us-east-1", "eu-west-1"))
        )
        detail = await client.get_execution(runs[0].workflow_id)
        await client.publish_message("approval", "order-42", {"approved": True})

asyncio.run(main())
```

A client belongs to the event loop it is first used on (the gRPC channel
opens lazily on the first gRPC call). Close it with `async with` or
`await client.close()`, and create a new one per loop.

The methods are those of `corobots_sdk.CorobotsClient` — workflows,
executions, schedules over REST and gRPC, triggers, messages and signals,
audit events; see that README for what each does.

## Step worker

`AsyncWorkerClient` registers step functions with the engine, holds the step
stream the engine pushes tasks down, and heartbeats — on the running event
loop. It never listens for the engine: the only network requirement is that
it can reach the engine's registration address.

```python
import asyncio
import httpx
from corobots_async_sdk import AsyncWorkerClient, RetryableError

worker = AsyncWorkerClient("my-svc", "corobots:50052", service_token="crsvc_...")
http = httpx.AsyncClient()            # one client, shared by every invocation

@worker.step("fetchThing", default_timeout="30s", max_retries=3)
async def fetch_thing(inputs, log, **_):          # runs on the worker's event loop
    resp = await http.get(f"https://api.example/things/{inputs['id']}")
    if resp.status_code == 503:
        raise RetryableError("upstream busy")     # engine retries per policy
    log("INFO", "fetched", status=resp.status_code)
    return resp.json()

@worker.step("crunch")
def crunch(inputs, **_):                           # runs on the worker's thread pool
    return {"sum": sum(range(int(inputs["n"])))}  # JSON numbers arrive as floats

async def main():
    async with worker:                 # or: await worker.start() ... await worker.stop()
        await asyncio.Event().wait()

asyncio.run(main())
```

Steps declare only the keyword arguments they need — `inputs`,
`workflow_id`, `workflow_name`, `step_name`, `is_compensation`,
`retry_count`, and the optional `log`, `auth`, `scope_path`, `cancel`,
`delivery_count` and `secrets` — exactly as with `corobots_sdk.WorkerClient`.
Pydantic input/output models, `RetryableError`, secret masking, the
stdlib-logging tee, `StepRouter`, and workflow and schedule registration at
`start()` work the same way too.

| | `async def` steps | `def` steps |
|---|---|---|
| Run on | the worker's event loop | the worker's thread pool (`max_workers`) |
| Sharing loop-bound resources (`httpx.AsyncClient`, ...) across invocations | yes | — |
| A blocking call | stalls the loop and the step stream: don't | fine |
| On cancel or timeout | the `cancel` event is set **and** the coroutine is cancelled (`asyncio.CancelledError` inside the step) | the `cancel` event is set; the step stops if it checks it |
| On free-threaded CPython | — | run truly in parallel |

A step's log frames not yet on the stream are capped at 256; beyond that
they are dropped and one `step app-log buffer overflow` warning precedes the
result. An `async def` step that logs heavily should yield (`await`) between
log calls.

On free-threaded CPython `def` steps are not serialised by the GIL. Measured
with 8 CPU-bound pure-Python steps on 11 cores: 0.11s on 3.14t, 0.65s on
3.14 with the GIL.

Useful constructor arguments: `wait_for_engine_s=30` retries registration
with backoff at startup, `max_inflight` caps how many tasks the engine may
push at once (0 = engine default), `tee_logging=False` stops streaming stdlib
logging to the engine. Introspection: `worker.worker_id`, `worker.is_running`,
`worker.attached`, `worker.active_executions`, `worker.transport`,
`worker.step_metadata()`. `AsyncWorkerClient.from_settings(WorkerSettings.from_env())`
reads the `COROBOTS_*` environment like `corobots-sdk`.

### FastAPI

```python
from fastapi import FastAPI
from corobots_async_sdk.contrib.fastapi import worker_lifespan, worker_router

app = FastAPI(lifespan=worker_lifespan(worker))   # or lifespan=worker.lifespan
app.include_router(worker_router(worker))          # GET /corobots/healthz, /corobots/steps
```

A failed start (engine down, a rejected workflow) raises from the lifespan
and leaves nothing running.

## Development

```bash
pip install -e ".[dev]"
make test              # unit + offline integration (FakeEngine)
make test-e2e          # real engine + MongoDB, see tests/e2e/conftest.py
```

The models, workflow builder, schemas, messaging, secrets and protobuf
messages are kept byte-identical to `corobots-sdk`'s (only the package name
differs); `tests/test_shared_with_corobots_sdk.py` fails when they drift.
Change them in `sdks/python` first, then copy them here.

### Releasing

1. Bump `version` in `pyproject.toml` and add a `## [X.Y.Z]` entry to `CHANGELOG.md`.
2. `git tag sdks/python-async/vX.Y.Z && git push origin sdks/python-async/vX.Y.Z`, then create a
   GitHub release from that tag; `.github/workflows/sdk-python-async-publish.yml` builds and
   uploads to PyPI.
