Metadata-Version: 2.5
Name: fuzzymemo
Version: 0.4.1
Summary: Adaptive 4-layer numeric accelerator with Live Drift Auditing, Async Singleflight, Background CPU/RAM Governor, and Prometheus observability.
Project-URL: Homepage, https://github.com/ashutosh27272727/fuzzymemo
Project-URL: Documentation, https://github.com/ashutosh27272727/fuzzymemo/blob/main/INTEGRATION_GUIDE.md
Project-URL: Repository, https://github.com/ashutosh27272727/fuzzymemo
Project-URL: Issues, https://github.com/ashutosh27272727/fuzzymemo/issues
Author: Ashutosh
Maintainer: Ashutosh
License-Expression: MIT
License-File: LICENSE
Keywords: async,caching,fuzzy,interpolation,jit,load-shedding,memoization,numba,prometheus,quant
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Financial and Insurance Industry
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Mathematics
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: System :: Monitoring
Classifier: Typing :: Typed
Requires-Python: >=3.10
Provides-Extra: dev
Requires-Dist: pytest>=8.0; extra == 'dev'
Provides-Extra: jit
Requires-Dist: numba>=0.59; extra == 'jit'
Provides-Extra: monitor
Requires-Dist: psutil>=5.9; extra == 'monitor'
Description-Content-Type: text/markdown

# fuzzymemo

**Adaptive 4-Layer Numeric Accelerator & Load-Shedding Governor for Python.**

[![Python 3.10+](https://img.shields.io/badge/python-3.10%2B-blue.svg)](https://www.python.org/downloads/)
[![Version 0.4.0](https://img.shields.io/badge/version-0.4.0-brightgreen.svg)](#)
[![License: MIT](https://img.shields.io/badge/license-MIT-yellow.svg)](https://github.com/ashutosh27272727/fuzzymemo/blob/main/LICENSE)

Standard memoization (`functools.lru_cache`) fails on continuous floating-point streams because minor market or sensor jitter causes near-zero hit rates. Meanwhile, OS-level CPU throttling freezes or stalls overloaded VMs rather than degrading gracefully.

`fuzzymemo` solves both problems with a single `@auto_turbo` decorator: it auto-calibrates on your hardware, stacks quantized axial interpolation with runtime Numba JIT compilation, sheds CPU/RAM load gracefully during VM spikes, and exposes Prometheus and JSON telemetry out of the box.

---

## The 4-Layer Architecture

1. **Layer 1 — Adaptive Auto-Router (`turbo.py`)**
   Profiles your host CPU on the first call to compare compiled kernel latency against a warm cache lookup. If the kernel is already faster than $1.15\times$ the lookup cost, it locks into `BYPASS` mode (zero lookup tax, zero approximation error). When caching wins, it monitors sliding-window hit rates—automatically bypassing random "chaos storms" and probing back when inputs re-cluster.
2. **Layer 2 — Fuzzy Memoizer v4 (`core.py`)**
   Compiles a zero-loop fast-path wrapper at decoration time with $O(1)$ bounded LRU eviction, `NaN`/`Inf` safety bypasses, optional TTL, thread safety, and **axial linear interpolation** ($D + 1$ neighbor lookups) to reduce quantization error by orders of magnitude.
3. **Layer 3 — Micro-Superoptimizer (`superopt.py`)**
   Races pure Python against compiled Numba `@njit` variants (`njit_strict`, `njit_fastmath`, `njit_fastmath_np`), validates numerical accuracy against the Python baseline, and locks in the fastest binary. Falls back cleanly to pure Python when Numba is not installed.
4. **Layer 4 — Background CPU & RAM Pressure Governor (`governor.py`)**
   Polls host utilization via `psutil` or `os.getloadavg()` in an optional background daemon thread (zero hot-path syscalls) with hysteresis:
   * **`NORMAL` (< 70% CPU):** Tight tolerances with axial linear interpolation.
   * **`ELEVATED` (70%–85% CPU):** Flat nearest-bucket lookups ($1$ lookup vs. $D + 1$).
   * **`CRITICAL` ($\ge$ 85% CPU, Brownout):** Widens tolerances by `critical_tolerance_mult` (default $3\times$) and doubles TTL to drive hit rates toward 99%+ and shed compute before the VM stalls.
   * **`RAM PRESSURE` ($\ge$ 85% RAM):** Clears the primary cache and routes to a compact `maxsize // 4` tier to prevent OOM kills.

---

## Production Features (v0.4.0)

* **Live Drift Auditing:** Shadow-samples 1 out of every `drift_sample_rate` hits against the exact kernel; if error exceeds `max_error`, tolerances automatically halve ($0.5\times$) and cache tiers rebuild.
* **Native `async`/`await` with Singleflight Coalescing:** Decorate `async def` coroutines directly. Concurrent callers hitting the same quantized bucket share a single in-flight `asyncio.Future`, preventing cache stampedes.
* **Multi-Process Shared VM State:** Point multiple Python services or workers at a shared `shared_state_path` so a CPU spike triggers coordinated load-shedding across the entire VM.
* **Zero-Dependency Observability:** Call `.prometheus_metrics()` or `.json_status()` directly on any decorated function.

---

## Verified Benchmarks

Measured on an 8-logical-CPU Windows 11 host (Python 3.11.9, Numba + `psutil`, 19/19 tests passing):

| Workload | Blind Python | `@auto_turbo` | Speedup | Auto-Calibrated Strategy |
| :--- | ---: | ---: | ---: | :--- |
| **Live BTC/USDT Stream** (232 ticks) | `66.70 ms` | **`1.62 ms`** | **`41.1x`** | `njit_strict` + Fuzzy v4 (`CACHED`) |
| **Robotics 3D IK** (20k frames) | `0.7232 s` | **`0.0472 s`** | **`15.3x`** | `njit_fastmath_np` (`BYPASS`) |
| **3-Regime Stress Test** (30k ticks) | `1.8904 s` | **`0.1840 s`** | **`10.3x`** | `njit_strict` + Fuzzy v4 + Chaos Bypass |
| **Geo-Delivery Surge API** (20k reqs) | `0.5156 s` | **`0.0931 s`** | **`5.5x`** | `njit_fastmath_np` + Fuzzy v4 (`CACHED`) |
| **Trivial Formula Guard** (20k calls) | `0.0019 s` | `0.0039 s` | `0.5x` | `python` (`BYPASS` guard — refused cache) |

**v0.4.0 Concurrency & Load-Shedding Verification:**
* **Async Singleflight (400 concurrent `asyncio.gather` calls):** Hit rate jumped from `0.0%` to **`90.5%`** (38 actual runs, 362 coalesced).
* **Live CPU Spike (`multiprocessing`):** Caught `88.8%` host CPU spike and transitioned `NORMAL -> CRITICAL -> NORMAL` automatically.
* **Live Drift Auditing:** Audited 24 shadow samples and auto-tightened tolerances 3 times when error crossed `max_error`.

---

## Installation

```bash
# Core zero-dependency package
pip install fuzzymemo

# Recommended: with Numba JIT superoptimizer and psutil CPU/RAM governor
pip install "fuzzymemo[jit,monitor]"
```

---

## Quickstart

### 1. Synchronous Compute Kernel (Full 4-Layer Stack)

```python
import math
from fuzzymemo import auto_turbo

@auto_turbo(
    tolerances=(0.25, None, 0.001, 0.005),  # None = exact match (e.g., strike)
    maxsize=4096,
    interpolate=True,
    use_superopt=True,
    enable_governor=True,
    background_governor=True,
    elevated_cpu_pct=70.0,
    critical_cpu_pct=85.0,
    ram_critical_pct=85.0,
    shared_state_path="/tmp/fuzzymemo_pressure.state",
    drift_sample_rate=500,
    max_error=0.01,
)
def price_option(spot, strike, t_expiry, vol):
    val = (spot - strike) * 0.01 + vol * math.sqrt(t_expiry)
    for _ in range(200):
        val = math.sin(val) + math.cos(val * 0.5)
    return val

result = price_option(59120.40, 59000.0, 0.082, 0.55)

# Inspect stats or export telemetry
print(price_option.turbo_info())
print(price_option.prometheus_metrics("price_option"))
print(price_option.json_status(event="heartbeat"))
```

### 2. Native Async with Singleflight Coalescing

```python
import asyncio
from fuzzymemo import auto_turbo

@auto_turbo(tolerances=(0.25, 0.01), maxsize=2048, background_governor=True)
async def fetch_and_score(price: float, vol: float) -> float:
    await asyncio.sleep(0.01)  # Simulated async work
    return price * vol * 0.15
```

---

## Documentation

* See **[INTEGRATION_GUIDE.md](https://github.com/ashutosh27272727/fuzzymemo/blob/main/INTEGRATION_GUIDE.md)** for full production wiring templates (FastAPI + `/metrics`, WebSockets, multi-tenant Linux VMs with `systemd`, and tuning playbooks).
* See **[fuzzy_memoizer_guide.pdf](https://github.com/ashutosh27272727/fuzzymemo/blob/main/fuzzy_memoizer_guide.pdf)** for the architectural whitepaper and detailed benchmark tables.

## License

MIT License — Copyright (c) 2026 Ashutosh. See [LICENSE](https://github.com/ashutosh27272727/fuzzymemo/blob/main/LICENSE) for details.