Metadata-Version: 2.4
Name: pymapreduce-core
Version: 0.1.12
Classifier: Programming Language :: Rust
Classifier: Programming Language :: Python :: Implementation :: CPython
Classifier: Programming Language :: Python :: Implementation :: PyPy
Requires-Dist: cloudpickle>=3.0.0
Summary: A high-performance MapReduce framework in Rust with Python async/await bindings
Author: MapReduce Team
License: MIT
Requires-Python: >=3.8
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM

# PyMapReduce: Distributed Computing Engine for Python

<div align="center">

[![Version](https://img.shields.io/badge/version-0.1.10-blue.svg?style=flat-square)](https://pypi.org/project/pymapreduce-core/)
[![Python](https://img.shields.io/badge/python-3.8%2B-brightgreen.svg?style=flat-square)](https://www.python.org/)
[![Rust](https://img.shields.io/badge/rust-1.75%2B-orange.svg?style=flat-square)](https://www.rust-lang.org/)
[![PyO3](https://img.shields.io/badge/bindings-PyO3_0.20_abi3-red.svg?style=flat-square)](https://pyo3.rs/)
[![License](https://img.shields.io/badge/license-MIT-green.svg?style=flat-square)](LICENSE)

<p style="font-size: 1.1em; color: #555; max-width: 850px; margin: 15px auto;">
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.
</p>

</div>

---

## Table of Contents

- [1. Key Features](#1-key-features)
- [2. Installation](#2-installation)
- [3. Cluster Deployment Modes](#3-cluster-deployment-modes)
- [4. Task Scheduling Strategies](#4-task-scheduling-strategies)
- [5. Programming Guide](#5-programming-guide)
  - [5.1. Stateless Distributed Tasks](#51-stateless-distributed-tasks)
  - [5.2. Stateful Distributed Actors](#52-stateful-distributed-actors)
  - [5.3. Zero-Copy Shared Memory & Large Data](#53-zero-copy-shared-memory--large-data)
  - [5.4. Distributed Dataset API](#54-distributed-dataset-api)
  - [5.5. Dynamic Cluster Management & Graceful Drain](#55-dynamic-cluster-management--graceful-drain)
  - [5.6. Configurable Execution Timeouts](#56-configurable-execution-timeouts)
- [6. Command Line Interface (CLI)](#6-command-line-interface-cli)
- [7. Python API Reference](#7-python-api-reference)
- [8. Reliability & Disaster Recovery Guarantees](#8-reliability--disaster-recovery-guarantees)
- [9. License](#9-license)

---

## 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

### From PyPI (Recommended)

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

```bash
pip install pymapreduce-core
```

### Building from Source

```bash
# 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:

```python
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:

```bash
# 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:

```python
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

<table width="100%">
  <thead>
    <tr>
      <th width="22%">Strategy</th>
      <th width="28%">Python Enum / CLI Flag</th>
      <th width="50%">Description & Optimal Use Case</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><strong>Adaptive</strong><br><em>(Recommended)</em></td>
      <td><code>SchedulerStrategy.Adaptive</code><br><code>--scheduler Adaptive</code></td>
      <td>
        <strong>Dynamic multi-factor scheduling.</strong> 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.
      </td>
    </tr>
    <tr>
      <td><strong>LocalityFirst</strong></td>
      <td><code>SchedulerStrategy.LocalityFirst</code><br><code>--scheduler LocalityFirst</code></td>
      <td>
        <strong>Cache-aware scheduling.</strong> Prioritizes dispatching tasks to worker nodes that already hold required input <code>ObjectId</code> data in local RAM, eliminating unnecessary network transfers during MapReduce shuffle stages.
      </td>
    </tr>
    <tr>
      <td><strong>LeastLoad</strong></td>
      <td><code>SchedulerStrategy.LeastLoad</code><br><code>--scheduler LeastLoad</code></td>
      <td>
        <strong>Queue balance scheduling.</strong> 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.
      </td>
    </tr>
    <tr>
      <td><strong>WeightedCapacity</strong></td>
      <td><code>SchedulerStrategy.WeightedCapacity</code><br><code>--scheduler WeightedCapacity</code></td>
      <td>
        <strong>Hardware capacity weighting.</strong> Assigns tasks proportionally based on total physical CPU cores and RAM size reported by each worker node.
      </td>
    </tr>
    <tr>
      <td><strong>RoundRobin</strong></td>
      <td><code>SchedulerStrategy.RoundRobin</code><br><code>--scheduler RoundRobin</code></td>
      <td>
        <strong>Sequential rotation.</strong> Distributes tasks sequentially across all active workers. Best suited for benchmark baselines and uniform workloads.
      </td>
    </tr>
  </tbody>
</table>

### Strategy Selection Examples

**Programmatic initialization:**

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

**CLI initialization:**

```bash
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:

```python
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:

```python
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:

```python
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:

```python
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:

```python
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:

```python
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)

```bash
# 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

```bash
# 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

```bash
# 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

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

### Core Classes

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


