Metadata-Version: 2.4
Name: pymapreduce-core
Version: 0.1.13
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

# ⚡ MapReduce Distributed Framework

<p align="center">
  <img src="docs/architecture.png" alt="MapReduce Distributed Framework Architecture" width="850"/>
</p>

<p align="center">
  <a href="#-key-features"><img src="https://img.shields.io/badge/Rust-2021_Edition-orange.svg?style=flat-square&logo=rust" alt="Rust Edition"/></a>
  <a href="#-python-sdk-pymapreduce"><img src="https://img.shields.io/badge/Python-3.8%2B-blue.svg?style=flat-square&logo=python" alt="Python Version"/></a>
  <a href="#-fault-tolerance--disaster-recovery"><img src="https://img.shields.io/badge/Fault_Tolerance-WAL%20%2B%20Snapshots-success.svg?style=flat-square" alt="Fault Tolerance"/></a>
  <a href="#-pluggable-scheduler"><img src="https://img.shields.io/badge/Scheduler-5_Strategies-blueviolet.svg?style=flat-square" alt="Scheduler"/></a>
  <a href="#-license"><img src="https://img.shields.io/badge/License-MIT%2FApache--2.0-green.svg?style=flat-square" alt="License"/></a>
</p>

A next-generation, high-performance, fault-tolerant distributed computing framework written in **Rust** with native **Python bindings (`pymapreduce`)**. Inspired by modern distributed systems like **Ray** and **Apache Spark**, this framework unifies **Stateless Task Execution (Map/Reduce)** and **Stateful Actor Computing** over a zero-copy, event-driven tiered storage architecture.

---

## 🌟 Key Features

| Feature | Description |
| :--- | :--- |
| 🧠 **Global Control Store (GCS)** | Centralized metadata registry tracking nodes, task lifecycles, network bandwidth EWMA, and active actors with $O(1)$ load tracking. |
| 🎭 **Stateful Actor & Self-Protection** | Dedicated per-actor mailboxes and deterministic affinity routing with automated Idle TTL, Global LRU quota eviction, Lazy Re-creation, and explicit teardown (`pymapreduce.kill`). |
| 🎛️ **Pluggable Scheduling Engine** | Dynamic scheduling with 5 pluggable strategies: `RoundRobin`, `WeightedCapacity`, `LeastLoad`, `LocalityFirst`, and `Adaptive` with $O(1)$ stateful load tracking. |
| 📦 **Tiered Object Store** | 2-tier intelligent storage (Hot RAM tier with Redis-style LRU eviction spilling to Warm disk tier) supporting large object handles (`ObjectRef`). |
| ⚡ **Pub/Sub Event-Driven Resolution** | Reactive `Notify` synchronization eliminating polling loops and saving network bandwidth during inter-task dependency resolution. |
| 🛡️ **Two-Phase Crash Recovery** | Write-Ahead Logging (WAL) paired with periodic atomic snapshots for sub-millisecond state recovery during unexpected crashes. |
| 💓 **Circuit-Breaker Health Monitor** | Periodic worker heartbeat polling with snooze-tolerance, automatic task re-queueing (priority 0), and actor mailbox draining. |
| 🚀 **Shared Memory `runtime_env` & Excludes** | Automated project code packaging with `.gitignore` and default excludes, single-flight extraction to `/dev/shm`, and 3-tier automatic lifecycle self-cleaning. |
| 🐍 **Seamless Python SDK (`pymapreduce`)** | Ray-like syntax (`@pymapreduce.remote`, `ObjectRef`, `async/await`) powered by PyO3, Tokio, and multi-process IPC isolating Python's GIL. |

---

## 🏗️ System Architecture

The framework is structured into three cooperating planes: the **Client/Driver Plane**, the **Control Plane (HeadNode)**, and the **Execution Plane (WorkerNodes)**:

```mermaid
graph TB
    subgraph Client["Driver Plane (Python SDK / Rust Client)"]
        Driver["Driver / Client App<br/>(@pymapreduce.remote)"]
    end

    subgraph Head["Control Plane (HeadNode)"]
        GCS[("Global Control Store (GCS)<br/>(Nodes, Tasks, Actors, Objects)")]
        Scheduler["Pluggable Dispatcher<br/>(Min-Heap Priority Queue & Actor Mailboxes)"]
        Monitor["Health Monitor & Heartbeat<br/>(Circuit-Breaker & Requeuing)"]
        WAL[("Write-Ahead Log (WAL)<br/>& Atomic Snapshot")]
        HeadStore[("Tiered Object Store<br/>(Pub/Sub Broker)")]
        
        Scheduler <-->|Query Load & Topology| GCS
        Monitor -->|Track Liveness & Evict Dead Nodes| GCS
        GCS -.->|Persist State Mutations| WAL
        HeadStore <-->|Catalog Location| GCS
    end

    subgraph Worker1["Execution Plane (Worker Node 1)"]
        W1_Core["Rust Worker Engine<br/>(Backpressure Semaphore)"]
        W1_Store[("Local Object Store<br/>(Hot RAM / Warm Disk)")]
        W1_Py["Python Daemon IPC<br/>(Task / Actor Runtime)"]
        
        W1_Core <-->|Spill / Read| W1_Store
        W1_Core <-->|Stdin / Stdout Frames| W1_Py
    end

    subgraph WorkerN["Execution Plane (Worker Node N)"]
        WN_Core["Rust Worker Engine<br/>(Backpressure Semaphore)"]
        WN_Store[("Local Object Store<br/>(Hot RAM / Warm Disk)")]
        WN_Py["Python Daemon IPC<br/>(Task / Actor Runtime)"]
        
        WN_Core <-->|Spill / Read| WN_Store
        WN_Core <-->|Stdin / Stdout Frames| WN_Py
    end

    Driver -->|1. Submit Job / Task Payload| Head
    Head -->|2. Dispatch Task with Priority| W1_Core
    Head -->|2. Dispatch Task with Priority| WN_Core
    W1_Core -->|3. Heartbeat / Task Success / ObjectId| Head
    WN_Core -->|3. Heartbeat / Task Success / ObjectId| Head
    W1_Store <..|4. P2P Object Transfer (Zero-Copy)| WN_Store
    Head ..->|5. Notify Result / ObjectRef| Driver
```

---

## 🚀 Quickstart

### 1. Installation

#### Rust Core Binary & Library
```bash
# Clone the repository
git clone https://github.com/xuandong/MapReduce.git
cd MapReduce

# Build the optimized release binary
cargo build --release
```

#### Python SDK (`pymapreduce`)
```bash
cd pymapreduce
python3 -m venv .venv
source .venv/bin/activate
pip install maturin
maturin develop --release
```

---

### 2. Running a Cluster

You can start the cluster either using the **Rust CLI** or the **Python CLI**:

#### Option A: Using the Rust CLI
```bash
# Terminal 1: Start the HeadNode
./target/release/mapreduce serve --port 7777 --strategy Adaptive

# Terminal 2: Start Worker 1 (auto-detects physical cores)
./target/release/mapreduce worker --head 127.0.0.1:7777

# Terminal 3: Start Worker 2 (limit to 4 cores)
./target/release/mapreduce worker --head 127.0.0.1:7777 --workers 4
```

#### Option B: Using the Python CLI
```bash
# Terminal 1: Start the HeadNode
mapreduce start --head --port 7777 --scheduler Adaptive

# Terminal 2: Start a Worker
mapreduce start --worker --head-addr 127.0.0.1:7777 --cpus 4
```

---

### 3. Python SDK (`pymapreduce`) Examples

#### A. Stateless Remote Functions
```python
import asyncio
import pymapreduce

# Decorate any standard Python function
@pymapreduce.remote
def process_data(chunk):
    return [x ** 2 for x in chunk]

async def main():
    # Initialize connection to the cluster
    driver = await pymapreduce.DriverWrapper.init("127.0.0.1:7777")

    # Launch distributed tasks concurrently
    data_chunks = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    futures = [process_data.remote(chunk) for chunk in data_chunks]

    results = await asyncio.gather(*futures)
    print("Distributed Results:", results)

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

#### B. Stateful Actors
```python
import asyncio
import pymapreduce

@pymapreduce.remote
class ParameterServer:
    def __init__(self, init_val=0):
        self.weights = init_val

    def update(self, delta):
        self.weights += delta
        return self.weights

    def get_weights(self):
        return self.weights

async def main():
    await pymapreduce.DriverWrapper.init("127.0.0.1:7777")

    # Instantiate Actor on a dedicated worker
    ps = await ParameterServer.remote(init_val=10)

    # Actor calls are sequentially processed in the actor's mailbox
    await ps.update.remote(5)
    await ps.update.remote(2)
    final_weights = await ps.get_weights.remote()

    print("Final Model Weights:", final_weights) # Output: 17

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

#### C. Embedded Single-Node Mode (Zero Configuration)
If you are developing locally or testing in a notebook, you don't even need to start standalone processes manually:
```python
import asyncio
import pymapreduce

async def main():
    # Automatically spawns background HeadNode & local Workers
    driver = await pymapreduce.DriverWrapper.init()
    asyncio.ensure_future(pymapreduce.start_worker("127.0.0.1:7777", 4))
    await asyncio.sleep(2) # Give worker a moment to connect

    # Run jobs directly
    # ...
```

---

## ⚙️ Scheduling Strategies

The framework offers five built-in scheduling strategies configured via `--strategy <STRATEGY>`:

| Strategy | Selection Algorithm | Best Used For |
| :--- | :--- | :--- |
| `RoundRobin` | Strict circular allocation across active nodes. | Homogeneous tasks and uniform node capacities. |
| `WeightedCapacity` | $\text{Score} = \frac{\text{CPUs} + \text{RAM (GB)}}{\text{Load} + 1}$. Directs tasks to higher-spec nodes. | Heterogeneous clusters with varying node specs. |
| `LeastLoad` | Assigns to the worker with the lowest in-flight task count. | Variable-duration compute-heavy workloads. |
| `LocalityFirst` | Matches task cache requirements with local worker storage. | Large dataset transformations minimizing network IO. |
| `Adaptive` | Dynamically prioritizes local cache, then fallback to least load + task stealing. | General-purpose mixed workloads. |

---

## 📂 Repository Structure

```
MapReduce/
├── src/                          # Core Rust engine (crate: mapreduce)
│   ├── cluster/
│   │   ├── head.rs               # HeadNode event loop, connection management & RPC
│   │   ├── worker.rs             # WorkerNode execution loop & back-pressure semaphore
│   │   └── handle.rs             # Cluster handle
│   ├── gcs/
│   │   ├── state.rs              # GcsState schema (Jobs, Nodes, Tasks, Actors, Objects)
│   │   └── store.rs              # Thread-safe Gcs wrapper with RwLock & EWMA calculations
│   ├── scheduler/
│   │   ├── queue.rs              # TaskQueue (Min-Heap Priority Queue + Actor Mailboxes)
│   │   ├── dispatcher.rs         # Dispatcher bridge
│   │   └── strategy.rs           # 5 Pluggable Scheduling Strategies
│   ├── fault/
│   │   ├── monitor.rs            # HealthMonitor with Circuit-Breaker & failure handling
│   │   └── wal.rs                # WriteAheadLog (WAL) append, replay & truncation
│   ├── object_store/
│   │   ├── store.rs              # Tiered ObjectStore (Hot RAM LRU spill to Warm Disk)
│   │   └── tier.rs               # Storage tier policy (Hot vs Warm)
│   ├── protocol/
│   │   ├── message.rs            # Binary Message enum catalog
│   │   └── codec.rs              # LengthDelimitedCodec framer (up to 70MB frames)
│   └── driver/
│       ├── mod.rs                # Driver TCP client & asynchronous command dispatcher
│       └── config.rs             # JobConfig, TaskInput definitions
│
├── pymapreduce/                  # Python SDK & PyO3 C-Extension
│   ├── src/
│   │   ├── lib.rs                # PyO3 bindings, @remote decorator, Actor runtime
│   │   └── ipc.rs                # IPC Subprocess manager with length-prefixed protocol
│   └── python/pymapreduce/
│       ├── __init__.py           # Package exports
│       ├── daemon.py             # Python worker worker-daemon
│       └── cli.py                # Python CLI (mapreduce start ...)
│
├── testing/                      # Integration benchmarks & AutoML test suites
│   ├── app.py                    # Distributed AutoML grid-search pipeline
│   └── run_iris.py               # Benchmark execution script
└── DEVELOPER_GUIDE.md            # In-depth architectural & developer guide
```

---

## 🧪 Testing & Verification

Run the entire test suite including unit tests and integration tests:

```bash
# Run unit tests across the Rust workspace
cargo test --all-targets

# Validate Python bindings build
cargo check --manifest-path pymapreduce/Cargo.toml

# Run AutoML integration benchmark
cd testing
python run_iris.py
```

---

## 📜 License

This project is licensed under the MIT License / Apache-2.0. Feel free to use and contribute!

