A state-machine based orchestrator for long-running AI and other jobs.
pip install holarchy==1.0.0.post1 Copy PIP instructions
Holarchy is a high-performance, state-machine based orchestrator for long-running AI workflows and distributed tasks. It serves as the core of a Holarchical Logic Network (HLN), coordinating Holons (workers) via the RXON protocol.
This document serves as a comprehensive guide for developers looking to build pipelines (blueprints) and embed the Orchestrator into their applications.
Holarchy decouples process orchestration from distributed computational execution across three primary components:
Under the Holarchical Logic Network (HLN) architecture, orchestrators handle workflow state management while workers provide standardized execution wrappers. Through recursive composition, an orchestrator instance can execute behind a worker interface, enabling nested multi-tier hierarchical clusters.
pip install holarchy Install with Redis support (recommended for production):
pip install "holarchy[redis]" Install with history storage support (SQLite, PostgreSQL):
pip install "holarchy[history]" Install with telemetry support (OpenTelemetry):
pip install "holarchy[telemetry]" Install with S3 support (Payload Offloading):
pip install "holarchy[s3]" Install all dependencies, including for testing:
pip install "holarchy[all,test]" Job Statuses Holarchy jobs move through various states:
Holarchy is built with deep observability in mind using the OpenTelemetry standard. It provides:
To enable telemetry support during installation:
pip install "holarchy[telemetry]" See the Observability Guide for configuration details.
You can easily integrate and run the orchestrator engine within your own application.
# my_app.py from asyncio import Event, run from dataclasses import dataclass from holarchy import Blueprint, OrchestratorEngine from holarchy.config import Config from holarchy.context import ActionFactory from holarchy.fsm import State, StatesGroup from holarchy.storage import MemoryStorage @dataclass class OrderInput: order_id: int amount: float class OrderFlow(StatesGroup): start = State() finalize = State() storage = MemoryStorage() config = Config() config.CLIENT_TOKEN = "my-secret-client-token" config.GLOBAL_WORKER_TOKEN = "my-secret-worker-token" bp = Blueprint(name="order_pipeline", api_version="v1", api_endpoint="/jobs/order") @bp.start(OrderFlow.start) async def process_start(data: OrderInput, actions: ActionFactory) -> State: """The initial state for each new job.""" print(f"Order #{data.order_id} received, amount: {data.amount}") return OrderFlow.finalize @bp.end(OrderFlow.finalize) async def process_finalize(context) -> dict[str, str]: """The final state. The pipeline ends here.""" print(f"Job {context.job_id} | Complete.") return {"status": "completed"} engine = OrchestratorEngine(storage, config) engine.register_blueprint(bp) async def main() -> None: await engine.start() try: await Event().wait() finally: await engine.stop() if __name__ == "__main__": try: run(main()) except KeyboardInterrupt: print("\nStopping server.") Engine Lifecycle: run() vs. start() The OrchestratorEngine offers two ways to start the server:
engine.run(): This is a simple, blocking method. It's useful for dedicated scripts where the orchestrator is the only major component. It handles starting and stopping the server for you. You should not use this inside an async def function that is part of a larger application, as it can conflict with the event loop.
await engine.start() and await engine.stop(): These are the non-blocking methods for integrating the engine into a larger asyncio application.
State handlers are the core of your workflow logic. Holarchy provides a powerful dependency injection system to make writing handlers clean and efficient.
Instead of receiving a single, large context object, your handler can ask for exactly what it needs as function arguments. The engine will automatically provide them.
Tip: In v1.0.0, use declarative @bp.start(State), @bp.step(State, condition=...), and @bp.end(State). The legacy @bp.handler(state_name) decorator remains fully supported for backward compatibility.
Holarchy v1.0.0 replaces monolithic state blobs with 5 cleanly partitioned storage zones:
(Clean Slate Architecture: Zero legacy aliases or backward compatibility bridges; the 5 storage zones are the sole canonical memory model).
The following arguments can be injected by name, type, or decorator:
This is the recommended modern way to write handlers:
@bp.step(OrderFlow.process) async def publish_video( job_id: str, output_path: str, # Injected by name or from preceding steps ctx: Context, ): print(f"Job {job_id}: Publishing video at {output_path}.") ctx.actions.go_to(OrderFlow.complete) Available arguments for injection:
Holarchy is engineered for high-load environments with thousands of concurrent workers.
Pass conditions directly to @bp.step() (or @bp.handler()) to create conditional logic branches. Conditions are declarative FastF expressions from the fast-magic-filter library, resolving through the 4-tier StepScope cascade (current scope $\rightarrow$ input $\rightarrow$ steps).
from holarchy import Blueprint, Context, F, State, StatesGroup class Flow(StatesGroup): decision = State() urgent_processing = State() priority_lane = State() normal_processing = State() # Direct property matching on input payload via StepScope @bp.step(Flow.decision, condition=F.type == "urgent") async def handle_urgent(ctx: Context): ctx.actions.go_to(Flow.urgent_processing) # Compound condition with logical AND @bp.step(Flow.decision, condition=(F.priority >= 8) & (F.active == True)) async def handle_priority(ctx: Context): ctx.actions.go_to(Flow.priority_lane) # Fallback step if no prior condition matches @bp.step(Flow.decision) async def handle_default(ctx: Context): ctx.actions.go_to(Flow.normal_processing) Supported condition syntax:
Note: Missing attributes and None intermediate values are handled safely — they return False instead of raising AttributeError. This is a deliberate improvement over magic-filter.
This is the primary function for delegating work. The orchestrator will queue the task and wait for a worker to pick it up and return a result.
@bp.step async def transcode_video(input: dict, actions: ActionFactory): actions.dispatch_task( task_type="video_transcoding", params={"input_path": input.get("path")}, # Define the next step based on the worker's response status transitions={ "success": "publish_video", "failure": "transcoding_failed", "needs_review": "manual_review", # Example of a custom status }, ) If the worker returns a status not listed in transitions, the job will automatically transition to a failed state.
Run multiple tasks simultaneously and gather their results. Isolated branch state prevents race conditions when multiple branches report results simultaneously.
# 1. Fan-out: Dispatch multiple tasks to be aggregated into a single state @bp.step async def process_files(input: dict, actions: ActionFactory): tasks_to_dispatch = [{"task_type": "file_analysis", "params": {"file": file}} for file in input.get("files", [])] # Use dispatch_parallel to send all tasks at once. # All successful tasks will implicitly lead to the 'aggregate_into' state. actions.dispatch_parallel(tasks=tasks_to_dispatch, aggregate_into="aggregate_results") # 2. Fan-in: Collect results using the @aggregator decorator @bp.aggregator async def aggregate_results(aggregation_results, steps, actions): # This handler will only execute AFTER ALL tasks # dispatched by dispatch_parallel are complete. # aggregation_results is a dictionary of {task_id: result_dict} summary = [res.get("data") for res in aggregation_results.values()] steps["summary"] = summary actions.go_to("processing_complete") 4. Dependency Injection (DataStore) Provide handlers with access to external resources (like a cache or DB client).
from redis.asyncio import Redis # 1. Initialize and register your DataStore redis_client = Redis(decode_responses=True) bp = Blueprint("blueprint_with_datastore", data_stores={"cache": redis_client}) # 2. Use it in a handler via dependency injection @bp.step async def get_from_cache(data_stores): # Access the redis_client by the name "cache" user_data = await data_stores.cache.get("user:123") print(f"User from cache: {user_data}") 5. Native Scheduler Holarchy includes a built-in distributed scheduler. It allows you to trigger blueprints periodically (interval, daily, weekly, monthly) without external tools like cron.
# schedules.toml example [nightly_backup] blueprint = "backup_flow" daily_at = "02:00" dispatch_timeout = 60 # Fail if no worker picks it up within 1 minute 6. Webhook Notifications The orchestrator can send asynchronous notifications to an external system when a job completes, fails, or is quarantined. This eliminates the need for clients to constantly poll the API for status updates.
Orchestrator provides first-class support for handling large files via S3-compatible storage, powered by the high-performance obstore library (Rust bindings).
@bp.step async def process_data(task_files, actions): # Streaming download of a large file local_path = await task_files.download("large_dataset.csv") # ... process data ... # Upload results await task_files.write_json("results.json", {"status": "done"}) actions.go_to("finished") API Groups & Versioning All external API endpoints are strictly versioned and prefixed with /api/v1/.
POST /api/v1/jobs/my_flow { "input": { "video_url": "..." }, "webhook_url": "https://my-app.com/webhooks/holarchy", "dispatch_timeout": 30, "result_timeout": 120 } Example Webhook Payload:
{ "event": "job_finished", "job_id": "123e4567-e89b-12d3-a456-426614174000", "status": "finished", "result": { "output_path": "/videos/result.mp4" }, "error": null } Production Configuration The orchestrator's behavior can be configured through environment variables. Additionally, any configuration parameter loaded from environment variables can be programmatically overridden in your application code after the Config object has been initialized.
Important: The system employs strict validation for configuration files (clients.toml, workers.toml) at startup.
For detailed specifications and examples, please refer to the Configuration Guide.
The orchestrator handles failures based on the error.code field in a worker's response.
Multiple Orchestrator instances can run behind a load balancer.
POST /api/v1/jobs/my_flow { "input": {"input_val": 42}, "policy": { "allowed_skills": ["data_extractor", "pdf_generator"] }, "max_transitions": 50 } Custom Middleware Example (MiddlewareChain): from holarchy.middleware import BaseMiddleware class AuditLogMiddleware(BaseMiddleware): async def process_outbound_task(self, context, task_payload): task_payload["audit_tag"] = "monitored" return task_payload engine.middleware_chain.add(AuditLogMiddleware()) D-DNA Crypto-Audit Verification Example (holarchy.cli.audit): from holarchy.cli.audit import verify_d_dna_integrity is_valid, error = verify_d_dna_integrity(job_history_events, audit_salt="my_secret_salt") if not is_valid: print(f"History tampering detected: {error}") Deterministic Replay CLI (holarchy replay evaluate): Evaluate historical advisory execution receipts offline against updated blueprint routing logic to catch decision drift before production deployment:
# Evaluate historical execution receipts holarchy replay evaluate --app my_module:bp --cases .holarchy/replay/cases.jsonl # Enforce zero drift in CI pipelines (exits with code 1 if drift detected) holarchy replay evaluate --app my_module:bp --cases .holarchy/replay/cases.jsonl --strict Rate Limiting Granular, context-aware Redis-based rate limiter (Heartbeats: 120/min, Polling: 60/min, General: 100/min).
Note: Workers receive a standard Retry-After header on block to manage smart backoff strategies.
Automatic loading from BLUEPRINTS_DIR. Scans, imports, and registers .py files on startup.
Disable public API with ENABLE_CLIENT_API="false" to only accept tasks via RXON from parent holons.
pip install -e ../rxon pip install -e ".[all,test]" Running Tests pytest tests/ Interactive API Documentation Available at /_public/docs. Features dynamic blueprint documentation and interactive testing.
orchestrator state-machine workflow distributed ai llm rxon hln
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
None of the files in this release were uploaded with provenance metadata.
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.




