duroxide-python
Copilot instructions34 starsChanged 57 days agoMITView on GitHub
π¨ STOP: DO NOT git commit OR git push WITHOUT EXPLICIT USER PERMISSION π¨ Always ask before committing or pushing. Never assume. When making changes to this SDK, always check ../duroxide-node for symmetry: 1. Bug fixes: If you fix a bug here, apply the same fix in duroxide-node (and vice versa) 2. API parity: Every public API in one SDK must have an equivalent in the other (adjusted for language idioms β snake_case in Python, camelCase in JS) 3. Testβ¦
- Reads credentials
- Commits and pushes
In this repository3 other files it gives its agents.
The file
We split this copilot-instructions.md into the rules it gives an agent
6 rules. About 0 are common, 3 are distinctive, and 3 are very specific to this project.
β0
Common Β· estimate
Many files like this have a rule of this kind.
β3
Distinctive Β· estimate
This author's own choices. Worth a look.
3
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 9
When making changes to this SDK, always check ../duroxide-node for symmetry:
- Distinctive: line 10
Bug fixes: If you fix a bug here, apply the same fix in duroxide-node (and vice versa)
- Distinctive: line 11
API parity: Every public API in one SDK must have an equivalent in the other (adjusted for language idioms β snake_case in Python, β¦
- Distinctive: line 12
Test parity: Every test in one SDK must have a corresponding test in the other
- Very specific: line 150
To add a new task type: Add to both context.py AND types.rs, add execution in handlers.rs.
- Very specific: line 214
Use SqliteProvider.in_memory() only for SQLite smoketest
β βCommonβ is an estimate: at least 1 in 5 of the 1,644 Copilot instructions files we read have a rule of the same kind, not the same words. βVery specificβ is our guess from the words: it names a file, a command, a setting or the project itself.
Files
duroxide-python β Copilot Instructions
π¨ STOP: DO NOT
git commitORgit pushWITHOUT EXPLICIT USER PERMISSION π¨Always ask before committing or pushing. Never assume.
β οΈ SDK Symmetry β duroxide-python & duroxide-node MUST stay in sync
When making changes to this SDK, always check ../duroxide-node for symmetry:
- Bug fixes: If you fix a bug here, apply the same fix in duroxide-node (and vice versa)
- API parity: Every public API in one SDK must have an equivalent in the other (adjusted for language idioms β snake_case in Python, camelCase in JS)
- Test parity: Every test in one SDK must have a corresponding test in the other
- Feature parity: New duroxide features exposed in one SDK must be exposed in both
- Rust handler code (
src/handlers.rs): Both SDKs share the same interop architecture βexecute_task,make_select_future,make_join_futureshould be kept structurally identical
Project Overview
duroxide-python is a Python SDK for the duroxide durable execution runtime. It wraps the Rust duroxide library via PyO3/maturin, providing a generator-based API for writing deterministic, replayable workflows.
This is a thin binding layer β the replay engine, state management, providers, and observability live in the duroxide Rust crate (peer folder ../duroxide). This project only bridges Python β Rust.
Architecture
Python (generators) ββ PyO3 bridge ββ duroxide (Rust core)
β
tokio runtime (global)- Orchestrations: Python generators that
yieldscheduling commands (dicts) to Rust - Activities: Regular Python functions called by Rust via
block_in_place+Python::with_gil() - Providers: PostgreSQL (
duroxide-pg) or SQLite β configured at startup - Tracing: Delegates to Rust
tracingβ controlled byRUST_LOGenv var
Key Files
Rust Source (src/)
| File | Role |
lib.rs | PyO3 module entry, #[pyfunction] exports |
types.rs | ScheduledTask enum (PythonβRust protocol) |
handlers.rs | Core interop: orchestration loop, activity handler, execute_task, select/join |
runtime.rs | PyRuntime β global tokio runtime, start/shutdown |
client.rs | PyClient β all client methods with py.allow_threads() |
provider.rs | PySqliteProvider |
pg_provider.rs | PyPostgresProvider |
Python Source (python/duroxide/)
| File | Role |
__init__.py | Public API: SqliteProvider, PostgresProvider, Client, Runtime, decorators |
context.py | OrchestrationContext, ActivityContext (yield scheduling commands) |
driver.py | Generator driver: create_generator, next_step, dispose_generator |
Tests (tests/)
| File | Tests | Schema |
test_e2e.py | 27 | duroxide_python_e2e |
test_races.py | 7 | duroxide_python_races |
test_admin_api.py | 14 | duroxide_python_admin |
scenarios/test_toygres.py | 6 | duroxide_python_toygres |
Build & Test
cd duroxide-python
source .venv/bin/activate
# Build (ALWAYS use maturin, never bare cargo build)
maturin develop # debug build + install into venv
maturin develop --release # release build
# Lint
cargo clippy --all-targets # must pass with zero warnings
# Test (requires DATABASE_URL in .env for PG tests)
pytest -v # all 54 tests
pytest tests/test_e2e.py -v # e2e only
pytest -s # show Rust tracing output
# Logging
RUST_LOG=info pytest -s # see orchestration/activity tracesβ οΈ GIL Deadlock β The #1 Pitfall
Every Rust method that calls TOKIO_RT.block_on() MUST release the GIL first:
fn my_method(&self, py: Python<'_>, ...) -> PyResult<...> {
py.allow_threads(|| {
TOKIO_RT.block_on(async { ... })
.map_err(|e| format!("{e}"))
})
.map_err(PyRuntimeError::new_err)
}Without py.allow_threads(), Python holds the GIL while blocking on tokio. Orchestration handlers on tokio threads need the GIL β deadlock. See pyo3-interop skill for full details.
Interop Model
Orchestrations: Generator Protocol
Python generators yield scheduling commands as plain dicts. The Rust handler loop:
- Calls
create_generator(payload)β Python creates generator, callsgen.send(None)β first task - Loops:
execute_task()in Rust βnext_step(result)β Python callsgen.send(value)β next task - Generator returns (
StopIteration) β orchestration complete
Activities: Synchronous Call
Rust calls Python activity functions synchronously via block_in_place + Python::with_gil(). Activities are regular def functions (not generators, not async).
Tracing: Global Context Maps
static ORCHESTRATION_CTXS: LazyLock<Mutex<HashMap<String, OrchestrationContext>>>
static ACTIVITY_CTXS: LazyLock<Mutex<HashMap<String, ActivityContext>>>Python ctx.trace_info() β PyO3 function β looks up Rust context by key β delegates to ctx.trace().
Both maps are keyed by an atomic token that is new for every invocation (act-{n}, orch-{n}), never by instance_id: two replays of one instance can be alive in the same process, and each must only reach its own context. Rust passes the orchestration token in ctxInfo["_ctxToken"].
ScheduledTask Protocol
Python OrchestrationContext methods return dicts with a "type" key. Rust deserializes to ScheduledTask enum:
# Python side (context.py)
def schedule_activity(self, name, input):
return {"type": "activity", "name": name, "input": json.dumps(input)}// Rust side (types.rs)
#[derive(Deserialize)]
#[serde(tag = "type", rename_all = "camelCase")]
pub enum ScheduledTask {
Activity { name: String, input: String },
Timer { delay_ms: u64 },
// ... etc
}To add a new task type: Add to both context.py AND types.rs, add execution in handlers.rs.
Key Patterns
Error Handling Across py.allow_threads
PyErr is not Send. Map errors inside, convert outside:
py.allow_threads(|| {
TOKIO_RT.block_on(async { ... }).map_err(|e| format!("{e}"))
})
.map_err(PyRuntimeError::new_err)Provider Polymorphism
PyO3 doesn't support trait objects directly. Detect provider type in Python:
if getattr(provider, "_type", None) == "postgres":
self._native = PyRuntime.from_postgres(provider._native, options)
else:
self._native = PyRuntime.from_sqlite(provider._native, options)Activity Client Access
ctx.get_client() calls activity_get_client(token) PyO3 function β looks up ActivityContext in ACTIVITY_CTXS map β calls ctx.get_client() β wraps result as PyClient. Activities can use this to start orchestrations, raise events, etc.
Metrics Snapshot
runtime.metrics_snapshot() returns a dict with 17 counters (orch starts/completions/failures, activity results, dispatcher stats, provider errors). Returns None if observability is not enabled.
Observability Options
PyRuntimeOptions includes log_format, log_level, service_name, service_version which map to duroxide::ObservabilityConfig.
Non-Generator Orchestrations
driver.py handles functions that return without yielding (checked via isinstance(gen, types.GeneratorType)). These are treated as immediate completion.
PyO3 Object Mutability
#[pyclass(get_all)] fields are read-only from Python. Use Python wrapper objects (e.g., OrchestrationResult) instead of mutating PyO3 objects.
Determinism Rules
Orchestration code must be deterministic β same input + history = same sequence of yields:
| β Safe | β Breaks Replay |
yield ctx.utc_now() | time.time() |
yield ctx.new_guid() | uuid.uuid4() |
ctx.trace_info() | print() |
yield ctx.schedule_timer(ms) | time.sleep() |
| Pure computation | I/O, HTTP, DB, randomness |
Testing Conventions
- PostgreSQL tests use schema isolation (one schema per test file)
python-dotenvloadsDATABASE_URLfrom.envPyRuntimeOptions(dispatcher_poll_interval_ms=50)for fast test dispatchruntime.shutdown(100)β short timeout, it waits the full duration- Use
SqliteProvider.in_memory()only for SQLite smoketest worker_lock_timeout_ms=2000for tests needing fast cancellation detection
Dependencies
- Rust: duroxide (core), duroxide-pg (PG provider), sqlx, tokio, pyo3, tracing
- Python: maturin (build), pytest (test), python-dotenv (test config)
- Build:
maturin develop(notcargo build) β produces the.so/.dylibPython can import - Cargo dependencies: Release manifests must use crates.io versions for
duroxideandduroxide-pg; remove temporary local[patch.crates-io]sections or inlinepath =overrides before release validation.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

