Metadata-Version: 2.4
Name: runprint
Version: 0.1.14
Summary: Run anything. Capture everything needed to reproduce it.
Author: Runprint Contributors
License-Expression: Apache-2.0
Project-URL: Homepage, https://github.com/minhquang0407/Runprint
Project-URL: Repository, https://github.com/minhquang0407/Runprint
Project-URL: Issues, https://github.com/minhquang0407/Runprint/issues
Keywords: reproducibility,research,ml,experiment-tracking,provenance
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Science/Research
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: click>=8.0.0
Requires-Dist: rich>=12.0.0
Requires-Dist: pydantic>=2.0.0
Provides-Extra: dev
Requires-Dist: pytest>=7.0.0; extra == "dev"
Dynamic: license-file

<p align="center">
  <img src="assets/runprint-icon.png" width="108" alt="Runprint Icon" />
</p>

<h1 align="center">Runprint (<code>qr</code>)</h1>

<p align="center">
  <strong>Production-Grade, Local-First Experiment &amp; Reproducibility Platform for AI &amp; Scientific Research</strong><br />
  <em>"Run anything. Capture everything needed to reproduce it."</em>
</p>

<p align="center">
  <a href="https://opensource.org/licenses/Apache-2.0"><img src="https://img.shields.io/badge/License-Apache%202.0-blue.svg" alt="License: Apache-2.0" /></a>
  <a href="https://www.python.org/downloads/"><img src="https://img.shields.io/badge/python-3.9+-blue.svg" alt="Python 3.9+" /></a>
  <a href="https://pypi.org/project/runprint/"><img src="https://img.shields.io/pypi/v/runprint.svg" alt="PyPI version" /></a>
  <a href="TESTING.md"><img src="https://img.shields.io/badge/tests-129%20passed-success.svg" alt="Tests: 129 passed" /></a>
  <a href="https://pypi.org/project/runprint/"><img src="https://img.shields.io/badge/platform-Linux%20%7C%20macOS%20%7C%20Windows-lightgrey.svg" alt="Platform" /></a>
</p>

Runprint (`qr`) is an ultra-lightweight, zero-telemetry reproducibility tracker and experiment supervisor for Machine Learning and computational science. It runs seamlessly **outside your code** (as an invisible CLI supervisor) or **inside your code** (via a clean, IDE-friendly Python SDK).

<p align="center">
  <img width="960" alt="Runprint Hub UI" src="https://github.com/user-attachments/assets/bf395319-4e7c-46ca-badf-f47ad6a1633a" />
</p>

All manifests, uncommitted code diffs, logs, metrics, hardware specs, and environment locks are preserved in a clean `.qr/` folder inside your workspace. **No cloud accounts, no external databases, no telemetry.**

```text
                        qr run -- <command>
                                │
                                ▼
                    ┌───────────────────────┐
                    │     Runprint (qr)     │
                    └───────────┬───────────┘
                                │
             ┌──────────────────┼──────────────────┐
             ▼                  ▼                  ▼
      Git State & Diff     Dependencies        Hardware & OS
        (uncommitted)      (AST + Lock)        (CPU, GPU, RAM)
             │                  │                  │
             └──────────────────┼──────────────────┘
                                ▼
              .qr/runs/QR-YYMMDD-HHMM-[Base62]-v1/
                                │
           ┌────────────────────┼────────────────────┐
           ▼                    ▼                    ▼
      manifest.json       metrics.jsonl        stdout / stderr
      config.json         artifacts.json       git.diff patch
                                │
                                ▼
                     Local SQLite & Lineage
                                │
             ┌──────────────────┼──────────────────┐
             ▼                  ▼                  ▼
           qr ui             qr diff            qr rerun
       (Live Web Hub)    (Side-by-Side)   (--reproduce / worktree)
```

---

## 📑 Table of Contents

- [⚡ Why Runprint?](#-why-runprint)
- [💡 Real-World Use Case: 3-Minute Walkthrough](#-real-world-use-case-3-minute-walkthrough)
- [📦 Installation](#-installation)
- [🚀 Quickstart in 60 Seconds](#-quickstart-in-60-seconds)
- [🎯 The Two Ways to Use Runprint](#-the-two-ways-to-use-runprint)
  - [Way 1: Zero-Code CLI Wrapper](#way-1-zero-code-cli-wrapper-terminal-first)
  - [Way 2: In-Code Python SDK](#way-2-in-code-python-sdk-ide--script-first)
- [🌐 Interactive Web UI Hub (`qr ui`)](#-interactive-web-ui-hub-qr-ui)
- [🧬 Hybrid Run ID Architecture](#-hybrid-run-id-architecture)
- [🛠️ CLI Command Cheatsheet](#️-cli-command-cheatsheet)
  - [JSON output for agents and scripts](#json-output-for-agents-and-scripts)
- [🐍 Python SDK Method Reference](#-python-sdk-method-reference)
- [🔬 Core Concepts & Restorability Score](#-core-concepts--restorability-score)
- [📂 Storage Layout](#-storage-layout)
- [🛡️ Quality Assurance & Security](#-quality-assurance--security)
- [📄 License](#-license)

---

## ⚡ Why Runprint?

| Pain Point in ML & Research | How Runprint (`qr`) Solves It |
| :--- | :--- |
| **"Which code generated this checkpoint?"** | Automatically snapshots Git commit, branch, and **uncommitted working tree diffs** (`git.diff`) into the run folder without modifying Git index. |
| **"Training crashed with CUDA/OOM, but script reported exit=0"** | **Intelligent Anomaly Scanner**: Tail-inspects execution logs for swallowed CUDA fatal errors, OOMs, and launch timeouts wrapped in `try...except`, auto-overriding false `completed` runs to `failed`. |
| **"The environment broke after 2 weeks"** | Analyzes direct AST imports (`direct-packages.txt`) + captures complete environment lock (`pip-freeze.txt`). |
| **"Cloud MLOps tools are too heavy / require server setup"** | 100% local-first, self-contained inside `.qr/`. Zero cloud, zero Docker daemon requirement, zero telemetry. |
| **"Run ID collisions when running on Kaggle/Colab/Slurm"** | Hybrid 26-character Run ID: `QR-YYMMDD-HHMM-[8 Base62 Entropy]-vN` with multi-layered container entropy harvesting. |
| **"Can you reproduce this paper/experiment exactly?"** | `qr rerun <id> --reproduce` automatically recreates the exact git commit, applies diffs in a temporary worktree, and runs in a restored virtualenv. |

---

## 💡 Real-World Use Case: 3-Minute Walkthrough

Here is how a real ML workflow unfolds with Runprint from day-to-day hacking to 1-click reproduction:

### Scenario
You are fine-tuning a PyTorch ResNet model on `train.py`. You made quick uncommitted code tweaks in VS Code, adjusted learning rate to `1e-4`, added CosineAnnealing, and want to know how it performs.

### Step 1: Run your script (Zero Code Modification)
No need to commit Git, no need to push to any server:
```bash
qr run --tag fine-tune -- python train.py --lr 0.0001 --batch-size 32
```
`qr` instantly prints:
```text
[!] Working tree contains uncommitted changes. Snapshotting diff:
  - train.py
  - configs/model.yaml

Run QR-261008-1230-7x9mK2pA-v1 [fine-tune] started (12:30:15)
Epoch 1/10 | loss: 0.421 | val_acc: 0.884
...
Epoch 10/10 | loss: 0.112 | val_acc: 0.952
Run completed: exit=0, duration=42.1s, restorability=95/100 (HIGHLY_RESTORABLE)
```

### Step 2: Track metrics & checkpoints with Python SDK *(Optional)*
In `train.py`, add a few lines to stream metrics and register checkpoints:
```python
import qr

# Log config and streaming epoch metrics
qr.log_config({"lr": 0.0001, "batch_size": 32, "model": "resnet50"})

for epoch in range(10):
    loss, val_acc = train_one_epoch()
    qr.metric({"loss": loss, "val_acc": val_acc}, epoch=epoch)

# Register checkpoint with auto-checksum
qr.artifact("checkpoints/best.pt", kind="weights")
```

### Step 3: Explore & compare in Web UI
Launch the built-in UI:
```bash
qr ui
```
- Open `http://127.0.0.1:8765` to inspect live SVG metric curves.
- View **Sister Runs** (runs with same code but different learning rates).
- Click **[ Compare ]** to see parameter deltas side-by-side.

### Step 4: The Nightmare Scenario Solved: 1-Click Reproduction
**Three weeks later**: Your Git repo is on a different branch, your code was edited, packages were updated, but a reviewer or colleague asks:
> *"Can you reproduce the exact output from run `QR-261008-1230-7x9mK2pA-v1`?"*

Simply run:
```bash
qr rerun QR-261008-1230-7x9mK2pA-v1 --reproduce
```
Runprint automatically:
1. Clones the exact historical Git commit into a clean, isolated temporary worktree.
2. Applies the uncommitted `git.diff` captured from that day.
3. Automatically restores the exact Python virtual environment from `.qr/runs/<run_id>/environment/pip-freeze.txt`.
4. Executes the training command and outputs `QR-261008-1230-7x9mK2pA-v2`!

---

## 📦 Installation

```bash
# Recommended from PyPI
pip install runprint

# Or install latest from GitHub
pip install git+https://github.com/minhquang0407/Runprint.git
```
*(Both `qr` and `runprint` commands are registered globally. You can also run `python -m qr`).*

---

## 🚀 Quickstart in 60 Seconds

```bash
# 1. Initialize Runprint in your project repository
qr init

# 2. Run any command (Bash, Python, C++, etc.)
qr run -- python train.py --epochs 10

# 3. Launch the Web UI Hub
qr ui
```

---

## 🎯 The Two Ways to Use Runprint

Runprint offers two complementary execution models depending on whether you prefer terminal commands or IDE-centric scripts.

### Way 1: Zero-Code CLI Wrapper (Terminal-First)
**Zero lines of code changed.** Runprint supervises the process from the outside:
```bash
# Basic run
qr run -- python train.py

# With tags and notes
qr run --tag baseline --notes "Testing AdamW optimizer" -- python train.py

# List recent runs
qr list

# Compare two runs side-by-side
qr diff QR-261008-1230-7x9mK2pA-v1 QR-261008-1245-3kL8wQ9Z-v1
```

### Way 2: In-Code Python SDK (IDE & Script-First)
If you run code using the **Run / Debug** button in VS Code, PyCharm, or Jupyter without a terminal wrapper, place `qr.init()` at the top of your script:

```python
import qr

def main():
    # 1. Initialize at the very start (auto-creates run & streams logs to Web UI)
    qr.init(tag="cifar10_baseline", params={"lr": 0.001, "batch_size": 32})
    
    # 2. Declare input datasets (auto SHA-256 fingerprinting)
    qr.input_dataset("cifar10", "data/cifar10")
    
    # 3. Real-time metric streaming (fsynced safely, zero data loss on OOM/crash)
    for epoch in range(10):
        # ... your training step ...
        qr.log({"loss": 0.24, "val_acc": 0.945}, epoch=epoch)
        
    # 4. Register outputs (models, figures, weights)
    qr.artifact("checkpoints/model.pt", kind="weights")

if __name__ == "__main__":
    main()
```

> **Universal Logger**: `qr.log()` automatically infers types (`dict` ➔ metric, `str` ➔ note). You can also pass explicit types: `qr.log({"lr": 1e-3}, type="config")` or `qr.log("model.pt", type="artifact")`.

---

## 🌐 Interactive Web UI Hub (`qr ui`)

Launch the local dashboard anytime with `qr ui`:

```bash
# Default (port 8765, opens browser automatically)
qr ui

# Custom port or headless mode
qr ui --port 9000 --no-browser
```

### What You Get in the UI:
- **Hierarchical DAG & Tree View**: Group runs by `Script Entrypoint` ➔ `Git Commit` ➔ `Sister Runs & Versions`.
- **Live SSE Terminal Streaming**: Real-time terminal log viewer (`stdout`/`stderr`) with search & auto-scroll.
- **Dynamic Metric Charts**: Interactive SVG loss & accuracy curves with Min/Max/Latest summary cards.
- **Sister Runs & Lineage**: Detects hyperparameter sweeps sharing the same code base and enables 1-click side-by-side diffing.
- **Deep Hardware & OS Diagnostics**: Inspect CPU cores/cache, RAM bus speed (MHz/MTs) per slot, GPU VRAM & compute capabilities, plus 1-Click Markdown Paper Exporter.
- **GUI Script Launcher (`+ New Run`)**: AST automatically parses script CLI arguments into interactive forms with provenance duplicate warnings.

---

## 🧬 Hybrid Run ID Architecture

Runprint uses a deterministic, human-readable, time-sortable **Hybrid Run ID**:

$$\mathbf{QR\text{-}YYMMDD\text{-}HHMM\text{-}[Entropy\_Base62]\text{-}vN}$$

- **Format**: `QR-261008-1230-7x9mK2pA-v1` (exactly 26 characters).
- **Human-Readable & Time-Sortable**: `YYMMDD-HHMM` indicates execution timestamp at a glance and sorts naturally via ASCII.
- **Collision-Proof Distributed Entropy**: 8 Base62 characters ($62^8 \approx 2.18 \times 10^{14}$ states) generated via BLAKE2b from multi-tier container metadata (`KAGGLE_CONTAINER_NAME`, `COLAB_GPU`, `SLURM_JOB_ID`, PID, OS CSPRNG, nanosecond clock). Multi-node runs will **never collide**.
- **Lineage Tracking**: Reruns automatically increment linear versions (`-v1` ➔ `-v2` ➔ `-v3`).
- **Shorthand Resolution**: `qr rerun QR-261008-1230-7x9mK2pA` automatically finds the latest version and creates the next.

---

## 🛠️ CLI Command Cheatsheet

| Command | Purpose | Example |
| :--- | :--- | :--- |
| `qr init` | Initialize `.qr/` workspace in repo | `qr init` |
| `qr run` | Execute command & snapshot state (with CUDA anomaly scanner) | `qr run --tag exp1 -- python train.py` |
| `qr ui` | Launch local Web UI Dashboard | `qr ui --port 8765` |
| `qr list` | List experiment history & status | `qr list --limit 10 --tag baseline` |
| `qr show` | Display run manifest, audit score & failure diagnosis | `qr show QR-261008-1230-7x9mK2pA-v1` |
| `qr rerun` | 1-Click reproduction in isolated worktree | `qr rerun <run_id> --reproduce` |
| `qr diff` | Side-by-side compare parameters & metrics | `qr diff <run_id_1> <run_id_2>` |
| `qr env` | Inspect environment drift & cached venvs | `qr env diff <run_id>` / `qr env clean --all` |
| `qr doctor` | Audit execution integrity & auto-repair orphaned/swallowed-error runs | `qr doctor --fix` |
| `qr sync` | Rebuild SQLite index or import from remote | `qr sync --from /path/to/backup/.qr/runs` |

### JSON output for agents and scripts

```bash
qr show <run_id> --json
qr diff <baseline_run_id> <current_run_id> --json
```

Both commands write one JSON object to stdout with `schema_version: 1`. A missing
project or unreadable run returns a nonzero exit code and a message on stderr.
The JSON commands only read saved run data and can inspect older manifests.

- `show` reports the saved `status`, the wrapped process's `exit_code`, the
  restorability score, and local paths to available logs. A run may be `failed`
  with `exit_code: 0` if Runprint detected a fatal signature in its logs.
  `error_evidence` contains a matched log excerpt and a line hint when available.
  Treat it as evidence for investigation. Line hints can be approximate.
- `diff` uses the first run as `baseline` and the second as `current`. Individual
  comparisons report `changed`, `unchanged`, or `unknown` when either value is
  unavailable. Package changes come from the two saved dependency snapshots.
  Dataset fingerprints are compared by name and split. An empty dataset list
  means no dataset was recorded in either run. Equal commits or fingerprints
  describe the saved evidence and do not guarantee an identical run.

---

## 🐍 Python SDK Method Reference

| Method | Shorthand | What It Does |
| :--- | :--- | :--- |
| `qr.init(tag=..., params=...)` | `qr.activate()` | Initializes experiment run at script start (for IDE runs) |
| `qr.log(data, type=...)` | — | Smart universal logging dispatcher |
| `qr.log_metric(dict, epoch, step)` | `qr.metric()` | Records numerical metrics with adaptive rate-limiting fsync |
| `qr.log_config(dict)` | `qr.params()` | Logs hyperparameter configuration |
| `qr.log_dataset(name, uri)` | `qr.dataset()`, `qr.input_dataset()` | Registers dataset with auto streaming SHA-256 |
| `qr.log_artifact(path, kind)` | `qr.artifact()` | Registers model checkpoints or output files |
| `qr.log_note(text)` | `qr.note()` | Appends timestamped research observation |
| `qr.seed(seed, deterministic=True)` | — | Enforces seed across Python, NumPy, PyTorch & cuDNN |
| `qr.is_main_process()` | — | Returns `True` on Rank 0 in PyTorch DDP / distributed training |
| `with qr.timer("name"):` | — | Measures execution duration of a code block |
| `with qr.run() as run:` | — | Context manager for hyperparameter sweeps / trials |

---

## 🔬 Core Concepts & Restorability Score

### 0–100 Restorability Score Rubric
Every run receives a machine-checked reproducibility audit score:

| Pillar | Points | What It Checks |
| :--- | :---: | :--- |
| **Source Code** | **35 pts** | Valid Git commit (+10), clean tree or uncommitted diff patch (+15), untracked source files archived (+10) |
| **Environment** | **35 pts** | Pinned Python version (+10), package lockfile recorded (+15), zero non-standard local dependencies (+10) |
| **Data & Inputs** | **30 pts** | Pure compute (+30), OR declared datasets (+10) with verified SHA-256 fingerprints (+20) |

- **90 – 100**: `HIGHLY_RESTORABLE` 🟢
- **70 – 89**: `PARTIALLY_RESTORABLE` 🟡
- **< 70**: `LOW_RESTORABILITY` 🔴

---

## 📂 Storage Layout

Everything is kept transparently inside `.qr/` in your repository:

```text
my-project/
├── train.py
├── configs/
├── .git/
└── .qr/
    ├── project.json                 # Project configuration
    ├── index.sqlite                 # Fast local SQLite cache (WAL mode, auto-synced)
    ├── envs/                        # Cached virtualenvs for reproduction
    ├── worktrees/                   # Temporary git checkouts for isolated reruns
    └── runs/
        └── QR-261008-1230-7x9mK2pA-v1/
            ├── manifest.json        # Machine-readable provenance manifest
            ├── config.json          # Parsed hyperparameters & config
            ├── git.diff             # Complete uncommitted diff patch
            ├── stdout.log           # Full stdout stream
            ├── stderr.log           # Full stderr stream
            ├── metrics.jsonl        # Streaming metric records with timestamps
            ├── artifacts.json       # Registered artifacts & SHA-256 checksums
            ├── notes.jsonl          # Timestamped experiment notes
            └── environment/
                ├── direct-packages.txt   # Core packages imported by script (AST)
                └── pip-freeze.txt        # Full environment freeze (100% lock)
```

---

## 🛡️ Quality Assurance & Security

- **119 Automated Tests (100% Pass Rate)**: Comprehensive test suite validating process supervision, Git dirty diffing, AST import resolution, container entropy generation, and isolated worktree reproduction. See [TESTING.md](TESTING.md).
- **100% Air-Gapped & Offline**: Zero network calls, zero telemetry, zero data exfiltration. Fully compliant with enterprise air-gapped environments. See [SECURITY.md](SECURITY.md).

---

## 📄 License

Licensed under the [Apache License, Version 2.0](LICENSE).
