diff --git a/docs/decisions/ADR-002-sync-async-strategy.md b/docs/decisions/ADR-002-sync-async-strategy.md new file mode 100644 index 0000000..a0c7e33 --- /dev/null +++ b/docs/decisions/ADR-002-sync-async-strategy.md @@ -0,0 +1,125 @@ +# ADR-002: Sync/Async Strategy + +**Status:** Accepted +**Date:** 2026-12-01 + +## Context + +The SDK must expose both synchronous and asynchronous clients. Python's async/await model requires fundamentally different call sites (`await` vs direct call), different context managers (`async with` vs `with`), and different HTTP clients (`httpx2.AsyncClient` vs `httpx2.Client`). The challenge is providing both surfaces without excessive duplication or type-safety compromises. + +Five approaches were evaluated against the project's constraints (pyright strict, mypy strict, zero `Any` in public API). + +## Alternatives + +### 1. Async-only with `asyncio.run()` sync wrapper + +Implement everything as async, wrap in `asyncio.run()` for the sync surface. + +| Factor | Assessment | +|---|---| +| Code duplication | Zero | +| Event loop conflicts | Fatal: fails when called inside an existing event loop (Jupyter, Django async views, nested frameworks). `asyncio.run()` raises `RuntimeError` if a loop is already running | +| Performance | Sync callers pay async overhead (event loop creation per call) | +| Type safety | Single set of overloads works | + +**Rejected.** Event loop conflicts make this unsuitable for a general-purpose SDK. + +### 2. Build-time code generation + +Generate both sync and async clients from a shared definition using a build-time code generator. + +| Factor | Assessment | +|---|---| +| Code duplication | Zero in source; generated output is duplicated | +| Maintenance | Requires maintaining the generator and the definition format | +| Type safety | Depends on generator quality | + +**Rejected.** A bespoke generator for a single-language SDK with 54 endpoints inverts the complexity equation: the generator itself (templates, definition format, output validation) becomes the maintenance burden, and the generated output still requires the same strict type-checking pipeline as hand-written code. Code generation pays off at scale (hundreds of endpoints, multiple language targets); at this scale, visible duplication is cheaper to maintain and easier to reason about than a template layer. + +### 3. Shared abstract base with sync/async subclasses + +Define an abstract `BaseResource` with method signatures, subclass for sync and async implementations. + +| Factor | Assessment | +|---|---| +| Code duplication | Reduced (shared signatures), but implementations still differ (`await` vs direct call) | +| Type safety | Problematic: abstract methods cannot express both `async def` and `def` with the same signature under pyright strict. `Protocol` with `__call__` overloads adds complexity without eliminating duplication | + +**Rejected.** The type system does not cleanly express a method that is sometimes async and sometimes sync. The workarounds (Protocol, Union returns, cast) weaken the type safety that is a project goal. + +### 4. Single class with `_async` suffixed methods + +One client class exposes both `method()` (sync) and `method_async()` (async) with a pluggable HTTP backend. + +| Factor | Assessment | +|---|---| +| Code duplication | Low: method bodies differ by `await` and suffix | +| API ergonomics | Unusual: `_async` suffixes are non-standard Python. Callers must remember two method names per operation. No `async with client:` idiom | +| Type safety | Good for individual methods, but mixed sync/async on one class complicates type stubs and IDE completion | + +**Rejected.** The `_async` suffix convention is non-idiomatic in the Python async ecosystem. Separate classes are the established convention for dual sync/async libraries, which is what Python developers expect. The suffix approach also prevents `async with AsyncClient()` context manager patterns. + +### 5. Parallel separate classes (chosen) + +Write separate `BaseClient`/`AsyncBaseClient` and separate `SyncAPIResource`/`AsyncAPIResource` with the same method names and signatures (minus `async`/`await`). + +| Factor | Assessment | +|---|---| +| Code duplication | Moderate: each resource file contains a sync class and an async class with structurally identical methods | +| Maintenance | Adding an endpoint means adding it in both classes. Risk: drift between sync and async. Mitigated by tests that verify both surfaces have identical method sets | +| Type safety | Full: each class has its own overloads, no casts, no Union escapes, pyright strict + mypy strict clean | + +## Decision + +**Use parallel separate classes for sync and async surfaces.** + +### Architecture + +``` +_base_client.py + BaseClient (httpx2.Client, sync _request with retry) + AsyncBaseClient (httpx2.AsyncClient, async _request with retry) + SyncAPIResource (3 overloads for typed/None/RAW returns) + AsyncAPIResource (3 async overloads, identical signatures) + +_client.py Client(BaseClient) -> 9 @cached_property resources +_async_client.py AsyncClient(AsyncBaseClient) -> 9 @cached_property resources + +resources/ + tasks.py Tasks(SyncAPIResource) + AsyncTasks(AsyncAPIResource) + runs.py Runs(SyncAPIResource) + AsyncRuns(AsyncAPIResource) + ... (same pattern for all 9 domains) +``` + +### What is shared vs duplicated + +| Layer | Shared | Duplicated (sync/async pair) | +|---|---|---| +| Configuration | `DEFAULT_BASE_URL`, `DEFAULT_TIMEOUT`, `DEFAULT_MAX_RETRIES`, error mapping, retry logic module (`_retry.py`) | Constructor, `_request`, context manager, `close` | +| Resource base | `_SentinelType`, `RAW` sentinel, `_ModelT` TypeVar | `SyncAPIResource._request` (3 overloads + impl), `AsyncAPIResource._request` (3 overloads + impl) | +| Resource clients | Pydantic models, filter param builders, URL paths, error handling | Method bodies (sync vs `await`) | +| Streaming | SSE parser (`SSEDecoder`, `ServerSentEvent`) | `Stream[T]`/`AsyncStream[T]`, `ChannelClient`/`AsyncChannelClient` | + +The duplication is concentrated in the method bodies, where the only difference is `await` and the HTTP client type. The business logic (URL construction, parameter building, model deserialization) is identical. + +### Drift prevention + +Every resource has parallel sync and async test modules (e.g., `test_resources_tasks.py` and `test_async_resources_tasks.py`) that verify the same operations with the same parameters and return types. As of this writing, 394 tests cover both surfaces across all 54 operations. + +## Consequences + +### Positive + +- Full type safety with zero casts or Protocol workarounds. pyright strict and mypy strict pass with zero errors. +- Consumers get natural Python idioms: `with Client()` for sync, `async with AsyncClient()` for async. +- No event loop conflicts. Sync client works in Jupyter, Django sync views, scripts. Async client works in async frameworks. +- Uses the established Python convention for dual sync/async libraries: separate classes with matching method signatures and clean type separation. + +### Negative + +- Each new endpoint requires writing the method body twice (sync and async). For a typical resource method, this is 5 to 15 lines of near-identical code per method. +- Risk of sync/async drift. Mitigated by: paired tests, code review, and the structural simplicity of the method bodies (most are a single `_request` call with the same arguments). + +### Deferred + +- If the SDK grows beyond ~100 endpoints, a lightweight code generator that produces both sync and async classes from a method table could eliminate the duplication. At the current scale (54 operations), the async surface adds ~800 lines across resource files and ~270 lines in the base client, for ~1,070 lines of structural duplication. This is manageable for hand maintenance; at Tier 3 scale (~85 operations) it may warrant revisiting. diff --git a/docs/decisions/ADR-003-schema-driven-generation.md b/docs/decisions/ADR-003-schema-driven-generation.md index 3dac3c8..88b495f 100644 --- a/docs/decisions/ADR-003-schema-driven-generation.md +++ b/docs/decisions/ADR-003-schema-driven-generation.md @@ -13,7 +13,7 @@ Three approaches were evaluated: 2. **Custom generation script** (read YAML, emit Python directly) 3. **Manual translation** (hand-write every model from the spec) -Model SDK repos (anthropic-sdk-python, openai-python, stripe-python) all use proprietary generators (Stainless, Codegen) unavailable to us. All three follow a "generate then hand-tune" pattern: generated types live in a types directory, hand-written code lives separately. +Production Python SDKs commonly follow a "generate then hand-tune" pattern: generated types live in a types directory, hand-written code lives separately. ## Decision @@ -48,7 +48,7 @@ datamodel-code-generator v0.102.0 was tested against our pinned spec (`spec/v3-o - Add `__all__` to each module - Add re-exports in `src/triggerdev/types/__init__.py` -Hand-tuned models are committed to version control as source code, not regenerated at build time. This matches model repo practice (anthropic-sdk-python commits `src/anthropic/types/`) and ensures reproducible installs without build-time dependencies. +Hand-tuned models are committed to version control as source code, not regenerated at build time. This ensures reproducible installs without build-time dependencies. 4. **Verify.** Run pyright strict, mypy strict, and ruff against the tuned models. All must pass with zero errors. @@ -78,7 +78,7 @@ scripts/ - Mechanical schema translation is automated (2,981 lines of model code from one command). - Type checker compliance is guaranteed at generation time (0 errors from both pyright and mypy). - Reproducible: any developer can re-generate from the pinned spec. -- Matches the "generate then hand-tune" pattern used by model SDK repos. +- Matches the established "generate then hand-tune" pattern for typed SDKs. ### Negative