Skip to main content

PyMapReduce: Distributed Computing Engine for Python

Version Python Rust PyO3 License

A high-performance, asynchronous distributed computing engine built with a Rust runtime and Python async/await bindings. PyMapReduce provides seamless distributed functions, stateful actors, in-memory zero-copy datasets, configurable scheduling strategies, and disaster recovery.


Table of Contents


1. Key Features

  • Asynchronous Distributed Tasks: Transform regular Python functions into distributed background jobs via the @pymapreduce.remote decorator.
  • Stateful Distributed Actors: Maintain in-memory class state across method calls with automatic failover and state resurrection if a worker node crashes.
  • Configurable Scheduling Strategies: Select between 5 specialized dispatching algorithms: Adaptive (EMA-based), Locality-First, Least-Load, Weighted-Capacity, or Round-Robin.
  • Zero-Copy Memory Transfers: Direct memory-mapped data sharing via /dev/shm for Pandas DataFrames, PyArrow Tables, and NumPy arrays without serialization overhead.
  • Dynamic Tiered ObjectStore: Memory allocation dynamically adjusts to 50% of host RAM via system metrics, with full LRU cache eviction and disk garbage collection.
  • Disaster Recovery (WAL): The HeadNode automatically checkpoints state and replays Write-Ahead Logs (WAL) upon restart. Drivers and workers automatically reconnect and reconcile in-flight jobs.
  • Dynamic Cluster Scaling: Programmatically attach workers or safely remove them using graceful draining without aborting running tasks.

2. Installation

PyMapReduce Core is packaged as a universal PyO3 Stable ABI wheel compatible with Python 3.8 and higher:

pip install pymapreduce-core

Building from Source

# Clone the repository
git clone https://github.com/xuandong/MapReduce.git
cd MapReduce/pymapreduce

# Create and activate a virtual environment
python3 -m venv .venv
source .venv/bin/activate

# Build and install locally
pip install maturin cloudpickle
maturin develop --release

3. Cluster Deployment Modes

Mode A: Embedded Cluster (Single-Node Development)

In embedded mode, pymapreduce.init() starts an in-process HeadNode coordinator and returns a connected Driver client:

import asyncio
import pymapreduce

async def main():
    # Start embedded coordinator on 127.0.0.1:7777
    driver = await pymapreduce.init(
        address="127.0.0.1:7777",
        scheduler=pymapreduce.SchedulerStrategy.Adaptive
    )

    # Launch a local worker node with 4 CPU cores
    await pymapreduce.connect_worker("127.0.0.1:7777", cpus=4)

if __name__ == "__main__":
    asyncio.run(main())

Mode B: Standalone Distributed Cluster (Multi-Node Production)

In standalone mode, cluster nodes run as dedicated daemon processes across different machines:

# On Master Node (192.168.1.10): Start HeadNode coordinator
mapreduce start --head --port 7777 --scheduler Adaptive

# On Worker Node 1 (192.168.1.20): Join cluster with 8 CPUs
mapreduce start --worker --head-addr 192.168.1.10:7777 --cpus 8

# On Worker Node 2 (192.168.1.21): Join cluster with 16 CPUs
mapreduce start --worker --head-addr 192.168.1.10:7777 --cpus 16

In your application code, connect directly to the existing HeadNode:

import asyncio
import pymapreduce

async def main():
    # Connect to the remote cluster coordinator
    driver = await pymapreduce.connect("192.168.1.10:7777")

if __name__ == "__main__":
    asyncio.run(main())

4. Task Scheduling Strategies

PyMapReduce provides 5 dispatching strategies to optimize workload distribution based on cluster topology and task characteristics.

Available Strategies

Strategy Python Enum / CLI Flag Description & Optimal Use Case
Adaptive
(Recommended)
SchedulerStrategy.Adaptive
--scheduler Adaptive
Dynamic multi-factor scheduling. Tracks real-time Exponential Moving Average (EMA) network bandwidth between nodes, current active CPU load, and in-memory data locality. Recommended for heterogeneous clusters and production environments.
LocalityFirst SchedulerStrategy.LocalityFirst
--scheduler LocalityFirst
Cache-aware scheduling. Prioritizes dispatching tasks to worker nodes that already hold required input ObjectId data in local RAM, eliminating unnecessary network transfers during MapReduce shuffle stages.
LeastLoad SchedulerStrategy.LeastLoad
--scheduler LeastLoad
Queue balance scheduling. Dispatches each incoming task to the worker currently executing the smallest number of active tasks. Ideal for homogeneous nodes running compute-heavy workloads of variable duration.
WeightedCapacity SchedulerStrategy.WeightedCapacity
--scheduler WeightedCapacity
Hardware capacity weighting. Assigns tasks proportionally based on total physical CPU cores and RAM size reported by each worker node.
RoundRobin SchedulerStrategy.RoundRobin
--scheduler RoundRobin
Sequential rotation. Distributes tasks sequentially across all active workers. Best suited for benchmark baselines and uniform workloads.

Strategy Selection Examples

Programmatic initialization:

driver = await pymapreduce.init(
    address="127.0.0.1:7777",
    scheduler=pymapreduce.SchedulerStrategy.LocalityFirst
)

CLI initialization:

mapreduce start --head --port 7777 --scheduler LocalityFirst

5. Programming Guide

5.1. Stateless Distributed Tasks

Functions decorated with @pymapreduce.remote are executed asynchronously on remote worker nodes:

import asyncio
import pymapreduce

@pymapreduce.remote
def compute_factor(n: int) -> int:
    return sum(i * i for i in range(n))

async def main():
    driver = await pymapreduce.init()
    await pymapreduce.connect_worker("127.0.0.1:7777", cpus=4)

    # 1. Single remote execution
    future = compute_factor.remote(10_000)
    result = await future
    print(f"Single result: {result}")

    # 2. Parallel fan-out execution
    futures = [compute_factor.remote(x) for x in range(1_000, 10_000, 1_000)]
    results = await asyncio.gather(*futures)
    print(f"Parallel results: {results}")

if __name__ == "__main__":
    asyncio.run(main())

5.2. Stateful Distributed Actors

Classes decorated with @pymapreduce.remote become distributed actors. Their internal state resides on a designated worker node, and method calls are queued and processed in order:

import asyncio
import pymapreduce

@pymapreduce.remote
class ModelTrainingState:
    def __init__(self, learning_rate: float = 0.01):
        self.learning_rate = learning_rate
        self.iteration = 0
        self.loss = 1.0

    def step(self, gradient: float) -> float:
        self.iteration += 1
        self.loss -= self.learning_rate * gradient
        return self.loss

    def get_summary(self) -> dict:
        return {"iteration": self.iteration, "loss": self.loss}

async def main():
    driver = await pymapreduce.init()
    await pymapreduce.connect_worker("127.0.0.1:7777", cpus=4)

    # Instantiate Actor on cluster
    actor = await ModelTrainingState.remote(learning_rate=0.05)

    # Invoke actor methods remotely
    await actor.step.remote(0.8)
    await actor.step.remote(0.5)
    summary = await actor.get_summary.remote()

    print(f"Training summary: {summary}")

if __name__ == "__main__":
    asyncio.run(main())

5.3. Zero-Copy Shared Memory & Large Data

When functions return large DataFrames, NumPy arrays, or PyArrow tables, PyMapReduce writes them to shared memory (/dev/shm) and returns an ObjectRef. Passing this reference into subsequent tasks avoids network copies and serialization:

import asyncio
import pymapreduce
import pandas as pd
import numpy as np

@pymapreduce.remote
def generate_matrix(rows: int, cols: int) -> pd.DataFrame:
    # Large DataFrame stored in shared memory
    data = np.random.randn(rows, cols)
    return pd.DataFrame(data, columns=[f"col_{i}" for i in range(cols)])

@pymapreduce.remote
def compute_column_means(df: pd.DataFrame) -> dict:
    return df.mean().to_dict()

async def main():
    driver = await pymapreduce.init()
    await pymapreduce.connect_worker("127.0.0.1:7777", cpus=4)

    # generate_matrix returns an ObjectRef handle
    matrix_ref = await generate_matrix.remote(100_000, 50)
    print(f"Generated ObjectRef ID: {matrix_ref.object_id}")

    # Pass reference directly to the next task (zero serialization)
    means = await compute_column_means.remote(matrix_ref)
    print(f"Calculated means for {len(means)} columns")

if __name__ == "__main__":
    asyncio.run(main())

5.4. Distributed Dataset API

The Dataset API provides distributed collection abstractions for tabular and stream processing:

import asyncio
import pymapreduce

async def main():
    driver = await pymapreduce.init()
    await pymapreduce.connect_worker("127.0.0.1:7777", cpus=4)

    # 1. Create a distributed dataset from local items or files
    ds = pymapreduce.from_items(range(1, 100_001), num_partitions=8)

    # 2. Lazy transformation pipeline
    processed_ds = (
        ds.map(lambda x: x * 2)
          .filter(lambda x: x % 4 == 0)
          .persist(pymapreduce.StorageLevel.MEMORY_ONLY)
    )

    # 3. Aggregations and conversions
    total = await processed_ds.count()
    first_five = await processed_ds.take(5)
    print(f"Total count: {total}, First 5 items: {first_five}")

    # 4. Convert directly to Pandas or PyArrow
    df = await processed_ds.to_pandas()
    print(f"Converted DataFrame shape: {df.shape}")

if __name__ == "__main__":
    asyncio.run(main())

5.5. Dynamic Cluster Management & Graceful Drain

Scale your cluster up and down programmatically:

import asyncio
import pymapreduce

async def main():
    driver = await pymapreduce.connect("127.0.0.1:7777")

    # 1. Scale Out: Add a worker node dynamically
    worker = await pymapreduce.connect_worker(
        head_addr="127.0.0.1:7777",
        cpus=8,
        idle_timeout=15  # Idle process cleanup in minutes
    )
    print("Worker registered to cluster")

    # 2. Scale In: Graceful drain (finishes current tasks before disconnecting)
    await worker.disconnect(graceful=True)
    print("Worker drained and retired cleanly")

if __name__ == "__main__":
    asyncio.run(main())

5.6. Configurable Execution Timeouts

Prevent stalled jobs by configuring execution timeouts:

import asyncio
import pymapreduce

async def main():
    driver = await pymapreduce.init()
    await pymapreduce.connect_worker("127.0.0.1:7777", cpus=4)

    # Configure a 30-second watchdog timeout for the job
    config = pymapreduce.JobConfig("AnalyticsJob", max_time=30)
    
    # Add tasks to config
    # ...
    
    results = await driver.submit(config)

6. Command Line Interface (CLI)

The mapreduce CLI manages nodes and script execution.

Starting the Coordinator (HeadNode)

# Start HeadNode with default Adaptive scheduler on port 7777
mapreduce start --head --port 7777 --scheduler Adaptive

# Start HeadNode with LocalityFirst scheduler and custom WAL directory
mapreduce start --head --port 8888 --scheduler LocalityFirst --wal-path /var/log/mapreduce/wal.log

Starting Worker Nodes

# Join a worker node with 8 CPU cores
mapreduce start --worker --head-addr 127.0.0.1:7777 --cpus 8

# Join a worker node with custom listener port and 10-minute idle process timeout
mapreduce start --worker --head-addr 192.168.1.10:7777 --cpus 16 --listener-port 9999 --idle-timeout 10

Submitting Standalone Scripts

# Submit a script with a 300-second execution timeout
mapreduce submit pipeline.py --head-addr 127.0.0.1:7777 --max-time 300

7. Python API Reference

Core Functions

Function Parameters Description
pymapreduce.init(...) address: str = "127.0.0.1:7777"
scheduler: Optional[SchedulerStrategy] = None
Starts an embedded in-process HeadNode coordinator and returns a connected Driver instance.
pymapreduce.connect(...) head_node: str
workers: Optional[List[str]] = None
Connects to an existing remote cluster coordinator.
pymapreduce.connect_worker(...) head_addr: str
cpus: Optional[int] = None
idle_timeout: int = 0
listener_addr: Optional[str] = None
Launches a background Worker node connected to the HeadNode and returns a WorkerHandle.
@pymapreduce.remote func_or_class Decorator that converts a standard Python function into a distributed task or a class into a stateful actor.

Core Classes

Class Method / Signature Description
WorkerHandle disconnect(graceful: bool = True) Initiates graceful draining on the worker node, finishes in-flight tasks, and disconnects.
JobConfig __init__(name: str, max_time: Optional[int] = None) Initializes a job configuration with an optional watchdog timeout in seconds.
JobConfig add_task(task: TaskInput) Appends a TaskInput instance to the job specification.
Driver get_job_status(job_id: str) Queries the real-time progress (completed_tasks, total_tasks) for a running job.
ObjectRef pin() / unpin() Locks an object in the in-memory ObjectStore to prevent LRU eviction.
Dataset map(fn) / filter(fn) / flat_map(fn) Transforms partitions asynchronously across the cluster.
Dataset to_pandas() / to_arrow() Collects and concatenates distributed partitions into a single Pandas DataFrame or PyArrow Table.

8. Reliability & Disaster Recovery Guarantees

  • HeadNode Disaster Recovery & WAL Replay: If the HeadNode restarts, it restores cluster state from 5-minute periodic snapshots and Write-Ahead Logs (WAL). Connected Drivers automatically perform auto-reconnect retries over a 30-second backoff schedule (1s -> 2s -> 4s -> 6s -> 8s -> 9s) and re-attach to active running jobs without losing progress.
  • Worker Multi-Task Continuous Execution & Isolation: When communication with the HeadNode is temporarily severed, Worker nodes do not freeze or crash. Instead, workers continue computing all assigned in-flight tasks across all allocated CPU cores to completion.
  • Per-Task Reconciliation & Automatic Memory Reclamation:
    • Each completed task enters an automated 30-second retry window ([1, 2, 4, 6, 8, 9] seconds) to push its execution result to the HeadNode.
    • If the HeadNode reconnects within this window, the worker performs instant state reconciliation, flushes all buffered task results, and immediately frees internal buffers.
    • If the HeadNode remains unreachable after 30 seconds for a given task, the worker cleans up intermediate results from RAM and ObjectStore to prevent memory leaks. The worker continues executing all other assigned in-flight tasks to completion before entering an idle sleep state to await new commands.
  • Worker Crash & Lineage Recomputation: When a worker node abruptly disconnects, active tasks are reassigned to healthy workers. Lost intermediate shuffle data is automatically reconstructed by re-executing upstream parent tasks in the lineage graph.
  • Stateful Actor Failover & Resurrection: Stateful actors residing on failed worker nodes are automatically recreated and resumed on surviving nodes without dropping queued mailbox calls.
  • Dynamic Hot-Tier ObjectStore & LRU Eviction: ObjectStore memory limits are dynamically tuned to 50% of available host RAM using system metrics, backed by LRU spillover to disk and automated reference-counted garbage collection.
  • Process Hygiene: Python worker daemons are bound to the parent Rust runtime via Linux PR_SET_PDEATHSIG, ensuring child processes terminate automatically if the parent process exits.

9. License

PyMapReduce is licensed under the MIT License.

Metadata

Release files for pymapreduce-core 0.1.12

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pymapreduce-core 0.1.12
File Size Uploaded Provenance Actions
pymapreduce_core-0.1.12.tar.gz 331.8 kB Without provenance Details for pymapreduce_core-0.1.12.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for pymapreduce-core 0.1.12
File Interpreter ABI Platform Actions
pymapreduce_core-0.1.12-cp38-abi3-manylinux_2_28_x86_64.whl CPython 3.8 abi3 Linux glibc 2.28+ x86-64 Details for pymapreduce_core-0.1.12-cp38-abi3-manylinux_2_28_x86_64.whl

Total release size: 1.8 MB

Release files / pymapreduce_core-0.1.12.tar.gz

Download URL pymapreduce_core-0.1.12.tar.gz
Size 331.8 kB
Tags Source
SHA-256 checksum
How to use checksums
00a3c8817db6ec1d23eaa8255bb9429388fb6aea4380d5d2a27bb4b078cadbc6
BLAKE2b-256 checksum
How to use checksums
a4b86b21739687b7276489e9ea67f7a705bdf7b8646c5d4136373f6388790e12
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.3

Release files / pymapreduce_core-0.1.12-cp38-abi3-manylinux_2_28_x86_64.whl

Download URL pymapreduce_core-0.1.12-cp38-abi3-manylinux_2_28_x86_64.whl
Size 1.5 MB
Tags CPython 3.8 Linux glibc 2.28+ x86-64 abi3
SHA-256 checksum
How to use checksums
823d854b0875885890fe32efa403ac7b7a89396b5ab2c429c5a4bf6d162a1feb
BLAKE2b-256 checksum
How to use checksums
3c6715767780a25dca9fd40229c846fb608c195e2b9b796d4dbefeac3752db27
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.3

Security for pymapreduce-core 0.1.12

Provenance

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.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

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.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page