A task management system for complex distributed orchestration
Project description
Pynenc
A task management system for complex distributed orchestration
Documentation: https://docs.pynenc.org
Source Code: https://github.com/pynenc/pynenc
Pynenc addresses the complex challenges of task management in distributed environments, offering a robust solution for developers looking to efficiently orchestrate asynchronous tasks across multiple systems. By combining intuitive configuration with advanced features like automatic task prioritization, Pynenc empowers developers to build scalable and reliable distributed applications with ease.
🆕 What's New in v0.2.3
- Invocation status state machine diagram:
pynenc status rendergenerates a text or SVG view of the state machine directly frompynenc.invocation.status. The SVG is committed underdocs/_static/and embedded in the README, the docs landing page, and the invocation status guide. A pre-commit hook keeps it aligned with the implementation - CLI app auto-discovery: when the current directory contains a single Python file with a
Pynenc()instance,pynenc runner startandpynenc monitorno longer require--app. Use--apponly when more than one app is available or when running from another directory - Dropped
PENDING -> FAILEDtransition: cycle-control is deprecated and the status unnecessary - Hardened multi-thread shutdown: worker SIGTERM handlers ignore repeated signals so a second termination cannot re-enter shutdown logging
See the Changelog for the complete list of changes.
Key Features
-
Modular Plugin Architecture: Pynenc is built with modularity at its core, supporting various backend implementations through a plugin system:
- Memory Backend: Built-in development/testing mode for local execution (single-host only)
- SQLite Backend: Built-in backend for testing on a single host (compatible with any runner sharing the same database file)
- Redis Plugin (
pynenc-redis): Production-ready distributed task management - MongoDB Plugin (
pynenc-mongodb): Document-based storage with full feature support - RabbitMQ Plugin (
pynenc-rabbitmq): Message queue-based broker for distributed task orchestration
The plugin system allows easy extension with additional databases, message queues, and services, enabling customization for different operational needs and environments.
-
Intuitive Orchestration: Simplifies the setup and management of tasks in distributed systems, focusing on usability and practicality.
-
Flexible Configuration with
PynencBuilder: A fluent builder interface allows users to configure apps programmatically with method chaining. Backend plugins automatically extend the builder with their own methods:from pynenc.builder import PynencBuilder # Production setup with Redis (requires pynenc-redis plugin) app = ( PynencBuilder() .app_id("my_app") .redis(url="redis://localhost:6379") # Plugin-provided method .multi_thread_runner(min_threads=2, max_threads=8) .logging_level("info") .build() ) # Development/testing setup (no plugins required) app = PynencBuilder().app_id("my_app").memory().dev_mode().build()
-
Invocation Status State Machine: Type-safe, declarative status management with:
- Ownership tracking for invocations across distributed runners
- Automatic recovery of stuck PENDING and RUNNING invocations
- Runner heartbeat monitoring to detect inactive runners
- Comprehensive state transitions with validation
-
Configurable Concurrency Management: Pynenc offers versatile concurrency control mechanisms at various levels:
- Task-Level Concurrency: Ensures only one instance of a specific task is in a running state at any given time.
- Argument-Level Concurrency: Limits concurrent execution based on the arguments of the task, allowing only one task with a unique set of arguments to be running or pending.
- Key Argument-Level Concurrency: Pick a subset of arguments (e.g.
key_arguments=("account_id",)) and serialise only invocations that share that key — perfect for per-tenant external API calls. Different keys still run fully in parallel. See theconcurrency_demosample for a runnable FastAPI-based walkthrough.
This structured approach to concurrency management in Pynenc allows for precise control over task execution, ensuring efficient handling of tasks without overloading the system and adhering to specified constraints.
-
Real-Time Monitoring with Pynmon: Built-in web-based monitoring interface featuring:
- SVG-based timeline visualization of invocations and state transitions
- Runner health monitoring with heartbeat tracking
- Workflow visualization with parent-child relationships
- Task details with execution history and context
- HTMX-powered real-time updates
-
Comprehensive Trigger System: Enables declarative task scheduling and event-driven workflows:
- Diverse Trigger Conditions: Schedule tasks using cron expressions, react to events, task status changes, results, or exceptions.
- Flexible Argument Handling:
- ArgumentProvider: Dynamically generate arguments for triggered tasks from the context of the condition (static values or using custom functions).
- ArgumentFilter: Filter task execution based on original task arguments (exact match dictionary or custom validation function).
- ResultFilter: Conditionally trigger tasks based on specific result values of the preceding task.
- Event Payload Filtering: Selectively process events based on payload content.
- Composable Conditions: Combine multiple conditions with AND/OR logic for complex triggering rules.
-
Advanced Workflow System: Sophisticated task orchestration with deterministic execution and state management:
- Deterministic Execution: All non-deterministic operations (random numbers, UUIDs, timestamps) are made deterministic for perfect replay.
- Workflow Identity: Unique workflow contexts with parent-child relationships and inheritance.
- State Persistence: Automatic key-value storage for workflow data with failure recovery capabilities.
- Task Integration: Integration with existing Pynenc tasks using
force_new_workflowdecorator option. - Failure Recovery: Workflows can resume from exact points of failure with identical replay behavior.
-
Core Services & Automatic Recovery: Built-in recovery tasks automatically detect and re-queue stuck invocations:
- Pending Recovery: Invocations stuck in
PENDINGbeyond a configurable timeout are re-routed through the broker. - Running Recovery: Invocations owned by runners that stopped sending heartbeats are detected and re-queued.
- Atomic Service Scheduling: A time-slot distribution algorithm ensures only one runner executes global services (trigger evaluation, recovery) per cycle, preventing race conditions in multi-runner deployments.
- Pending Recovery: Invocations stuck in
-
Automatic Task Prioritization: The broker prioritizes tasks by counting how many other tasks depend on them. The task blocking the most others is selected first.
-
Automatic Task Pausing: Tasks waiting for dependencies are paused, freeing their runner slots. Higher-priority tasks (those with more dependents waiting) run instead, preventing thread-pool exhaustion and deadlocks.
-
Incremental Migration with
@app.direct_task: For codebases adopting pynenc gradually, the@app.direct_taskdecorator preserves the calling contract of a regular Python function — the caller waits, gets back the value, exception handling is unchanged. Combined withPYNENC__DEV_MODE_FORCE_SYNC_TASKS=True, decorated functions run inline during development; remove the variable in production to distribute to workers. No call site has to be rewritten.@app.direct_task def analyze(data: str) -> dict: return expensive_computation(data) result = analyze(my_data) # returns the value directly — no Invocation
See the direct_task_demo sample and the usage guide for the migration pattern in detail.
Installation
Installing Pynenc is a simple process. The core package provides the framework, and you'll need to install backend plugins separately:
Core (supports Python 3.11+)
pip install pynenc
Backend Plugins
Choose the backend that fits your needs:
Redis Backend (recommended for production):
pip install pynenc-redis
MongoDB Backend:
pip install pynenc-mongodb
RabbitMQ Backend:
pip install pynenc-rabbitmq
Optional Features
Include the monitoring web app:
pip install pynenc[monitor]
Complete Installation Examples
For a Redis-based setup with monitoring:
pip install pynenc pynenc-redis pynenc[monitor]
For a MongoDB-based setup:
pip install pynenc pynenc-mongodb
For a RabbitMQ-based setup:
pip install pynenc pynenc-rabbitmq
For development/testing (memory or SQLite backend only):
pip install pynenc
This modular approach allows you to install only the components you need, keeping your dependencies minimal and focused.
For more detailed instructions and advanced installation options, please refer to the Pynenc Documentation.
Quick Start Example
To get started with Pynenc, here's a simple example that demonstrates the creation of a distributed task for adding two numbers. Follow these steps to quickly set up a basic task and execute it.
-
Define a Task: Create a file named
tasks.pyand define a simple addition task:from pynenc import Pynenc app = Pynenc() @app.task def add(x: int, y: int) -> int: add.logger.info(f"{add.task_id=} Adding {x} + {y}") return x + y @app.direct_task def direct_add(x: int, y: int) -> int: return x + y
-
Start Your Runner or Run Synchronously:
Before executing the task, decide if you want to run it asynchronously with a runner or synchronously for testing or development purposes.
-
Asynchronously: Start a runner in a separate terminal or script:
pynenc runner start
The CLI auto-discovers the app when the current directory contains exactly one importable file with a
Pynenc()instance. If your project has multiple apps, select one explicitly:pynenc --app tasks.app runner start
Check for the basic_redis_example (requires
pynenc-redisplugin)- Synchronously:
For test or local demonstration, to try synchronous execution, you can set the environment variable
PYNENC__DEV_MODE_FORCE_SYNC_TASKS=Trueto force tasks to run in the same thread.
-
-
Execute the Task:
# Standard task (returns invocation) result = add(1, 2).result # 3 # Direct task (returns result directly) direct_result = direct_add(1, 2) # 3
Using the Trigger System
Here's an example of creating and using triggers:
from pynenc import Pynenc
from datetime import datetime
app = Pynenc()
@app.task
def process_data(data: dict) -> dict:
return {"processed": data, "timestamp": datetime.now().isoformat()}
@app.task
def notify_admin(result: dict, urgency: str = "normal") -> None:
print(f"Admin notification ({urgency}): {result}")
# Create a trigger that runs when process_data completes successfully
trigger = app.trigger.on_success(process_data).run(notify_admin)
# Create a trigger with argument filtering - only trigger when data contains 'urgent'
trigger_urgent = (app.trigger
.on_success(process_data)
.with_argument_filter(lambda args: args.get('data', {}).get('priority') == 'urgent')
.run(notify_admin, argument_provider=lambda ctx: [ctx.result, "high"])
)
# Create a cron-based scheduled task
scheduled_task = (app.trigger
.on_cron("*/30 * * * *") # Every 30 minutes
.run(process_data, argument_provider={"data": {"source": "scheduled"}})
)
For a complete guide on how to set up and run pynenc, visit our samples library.
Monitoring with Pynmon
Pynenc includes Pynmon, a built-in web-based monitoring interface that provides real-time visibility into your distributed task execution — no external tooling required.
Execution Timeline
See exactly what ran across every runner and worker, at every moment. Status transitions are color-coded with connections between parent and child invocations. Click any invocation to inspect its full status history and the runner context that executed it.
Family Tree & Invocation Details
Navigate the full hierarchy of task calls as an interactive graph. Selecting a node cross-highlights it on the timeline, and vice versa — making it trivial to understand both the logical structure and the physical execution of complex workflows.
Log Explorer
Paste your Pynenc log lines and the Log Explorer augments them with full context — parsing runner contexts, invocation IDs, and task references, resolving each to its detail page. It generates a mini-timeline of all invocations mentioned in the logs and highlights runners and workers with direct links.
Starting the Monitor
The monitor requires a Pynenc app defined in your codebase:
pynenc monitor --host 127.0.0.1 --port 8000
If more than one app is available, specify the one to inspect:
pynenc --app your_app_module monitor --host 127.0.0.1 --port 8000
Then open http://127.0.0.1:8000 in your browser to access the dashboard.
Installing the Monitor
The monitoring web app is an optional feature:
pip install pynenc[monitor]
Requirements
- Python 3.11+
- Core package: No external infrastructure needed — includes memory and SQLite backends for development and testing
- Production: Install a backend plugin (
pynenc-redis,pynenc-mongodb, orpynenc-rabbitmq) and ensure the corresponding service is running
The plugin architecture lets you swap backends without changing application code.
Contributing
Contributions are welcome! See CONTRIBUTING.md for development setup, testing instructions, and pull request guidelines.
Community & Support
- GitHub Issues — Bug reports and feature requests
- GitHub Discussions — Questions, ideas, and general conversation
- Documentation — Guides, API reference, and configuration details
- Samples Repository — Working examples for common use cases
License
Pynenc is released under the MIT License.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file pynenc-0.2.3.tar.gz.
File metadata
- Download URL: pynenc-0.2.3.tar.gz
- Upload date:
- Size: 4.1 MB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: uv/0.11.12 {"installer":{"name":"uv","version":"0.11.12","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
99c660f67c2a0494af8ddc9102e1415e428ddb074c454e7b3e4707475e1d52dc
|
|
| MD5 |
ab4b727079d74accbd4f60799955854d
|
|
| BLAKE2b-256 |
d7f5ccaedc042f6a73aa80c0b98055be76d81d72c508b34a12f2b68a6b523b75
|
File details
Details for the file pynenc-0.2.3-py3-none-any.whl.
File metadata
- Download URL: pynenc-0.2.3-py3-none-any.whl
- Upload date:
- Size: 993.4 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: uv/0.11.12 {"installer":{"name":"uv","version":"0.11.12","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
ceacdc91c278f54c5bf86b16bd232615d2c7ebdf6f3bec40ab8cac167a44b454
|
|
| MD5 |
f45ad63244444833cb96f39e4c31807f
|
|
| BLAKE2b-256 |
7fdc8062d5e039395811cebf7b0c5868ce864a84da0548ee372ba53b285cd993
|