rmi-backend/app/_archive/legacy_2026_07/ab_testing.py
cryptorugmunch 628c1d2a10
Some checks failed
CI / build (push) Failing after 3s
refactor(rmi-backend,audit): mount Wave 3 + archive 136 dead-code files (P2.3)
PHASE 2.3 (AUDIT-2026-Q3.md):

Task 1 — Wire-in Wave 3 (1 router mounted, 2 deferred):
  - app.routers.unified_scanner_router mounted at /api/v2/scanner/* (2 routes:
    POST /api/v2/scanner/token/scan, POST /api/v2/scanner/wallet/scan).
    Refactored prefix from /api/v2 -> /api/v2/scanner to avoid future conflicts
    with the v1 /api/v1/scanner/ stub.
  - app.routers.unified_wallet_scanner DEFERRED (no router APIRouter attribute;
    library module consumed by unified_scanner_router via get_wallet_scanner()).
  - app.routers.admin_extensions DEFERRED (DORMANT per audit; 25 routes at
    /api/v1/admin/* would shadow /api/v1/admin/alerts_webhook).

Task 2 — Archive 136 dead-code files to app/_archive/legacy_2026_07/:
  - 73 routers in app/routers/ (reach graph showed zero reach into mount.py).
  - 63 flat app/*.py (domain modules never imported by live code).
  - 1 file RESTORED post-archive: app/routers/x402_bridge_health.py (caught by
    tests/unit/test_bridge_health.py which directly imports it; reach graph
    considered tests/ only as transitive reach — to be patched in next cycle).

Forced-LIVE (NOT archived per user directive):
  - app/ai_pipeline_v3.py  (3 importers in audit window, importers themselves DEAD)
  - app/splade_bm25.py       (LIVE via app.rag_service)
  - app/wallet_manager_v2.py (LIVE via x402_enforcement, x402_tools, sweep_all, sweep_now)
  - app/crypto_embeddings.py (NOT in audit ARCHIVE list; heavy import graph)

Verification (forward-import closure from mount.py + main.py + factory.py + lifespan.py):
  - imports = 348 app.* modules
  - reached = 194 files reachable from roots
  - archive set = audit_dead (186) - reached - forced_live (4) - test_live (1) = 136
  - Net delta: 136 files moved, 44,932 LOC reduction, 293->295 active routes (+2 from Wave 3)

pyproject.toml updates:
  - setuptools.packages.find: added exclude for app._archive*
  - ruff.extend-exclude: added "app/_archive/"
  - mypy.exclude: added "app/_archive/"

Smoke test: pytest tests/ — 817 passed, 3 pre-existing failures unchanged
(0 new failures; 0 routes lost; all 4 forced-LIVE files still importable).

Restoration: git mv app/_archive/legacy_2026_07/<name>.py <original-path>
and add the import to app/mount.py ROUTER_MODULES.

Refs: AUDIT-2026-Q3.md /home/dev/pry/rmi-final-deadcode-2026-07-06.md
2026-07-06 20:52:31 +02:00

154 lines
5.1 KiB
Python

"""A/B Testing Framework - split traffic, measure accuracy, auto-promote winners."""
import hashlib
from datetime import UTC, datetime
from fastapi import APIRouter, Query
router = APIRouter(prefix="/api/v1/ab-testing", tags=["ab-testing"])
_experiments: dict[str, dict] = {}
_results: dict[str, list] = {}
@router.post("/experiment")
async def create_experiment(
name: str,
variants: str = Query(..., description="Comma-separated variant names, e.g. 'prompt_v1,prompt_v2'"),
traffic_split: str = Query("50,50", description="Traffic split percentages"),
metric: str = Query("accuracy", description="Metric to evaluate"),
):
"""Create a new A/B test experiment."""
variant_list = [v.strip() for v in variants.split(",")]
split_list = [int(s.strip()) for s in traffic_split.split(",")]
if len(variant_list) != len(split_list):
return {"error": "Variants and splits must have same length"}
if sum(split_list) != 100:
return {"error": "Traffic splits must sum to 100"}
exp_id = hashlib.md5(name.encode()).hexdigest()[:8]
_experiments[exp_id] = {
"id": exp_id,
"name": name,
"variants": variant_list,
"traffic_split": split_list,
"metric": metric,
"created_at": datetime.now(UTC).isoformat(),
"status": "active",
}
_results[exp_id] = []
return _experiments[exp_id]
@router.get("/assign/{experiment_id}")
async def assign_variant(experiment_id: str, user_id: str = "anonymous"):
"""Assign a user to a variant deterministically (same user always gets same variant)."""
if experiment_id not in _experiments:
return {"variant": "control", "note": "Experiment not found"}
exp = _experiments[experiment_id]
# Deterministic assignment based on user_id hash
h = int(hashlib.md5(f"{experiment_id}:{user_id}".encode()).hexdigest(), 16)
bucket = h % 100
cumulative = 0
for variant, split in zip(exp["variants"], exp["traffic_split"], strict=False):
cumulative += split
if bucket < cumulative:
return {"experiment": experiment_id, "variant": variant, "user": user_id}
return {"experiment": experiment_id, "variant": exp["variants"][-1], "user": user_id}
@router.post("/record/{experiment_id}")
async def record_result(experiment_id: str, variant: str, correct: bool = False):
"""Record a result for an A/B test variant."""
if experiment_id not in _experiments:
return {"error": "Experiment not found"}
_results[experiment_id].append(
{
"variant": variant,
"correct": correct,
"timestamp": datetime.now(UTC).isoformat(),
}
)
# Check if we have enough data to declare a winner (30+ samples per variant)
results = _results[experiment_id]
variant_counts = {}
variant_correct = {}
for r in results:
v = r["variant"]
variant_counts[v] = variant_counts.get(v, 0) + 1
if r["correct"]:
variant_correct[v] = variant_correct.get(v, 0) + 1
# Check if all variants have enough samples
min_samples = 30
all_ready = all(count >= min_samples for count in variant_counts.values())
if all_ready:
scores = {v: variant_correct.get(v, 0) / variant_counts[v] for v in variant_counts}
best = max(scores, key=scores.get)
worst = min(scores, key=scores.get)
improvement = scores[best] - scores[worst]
result = {
"experiment": experiment_id,
"status": "complete" if improvement > 0.05 else "inconclusive",
"winner": best if improvement > 0.05 else None,
"scores": {v: round(s, 3) for v, s in scores.items()},
"samples": variant_counts,
"confidence": round(improvement * 100, 1),
}
if improvement > 0.05:
_experiments[experiment_id]["status"] = "complete"
_experiments[experiment_id]["winner"] = best
return result
return {
"experiment": experiment_id,
"status": "collecting",
"samples": variant_counts,
"min_needed": min_samples,
}
@router.get("/experiments")
async def list_experiments():
return {
"experiments": list(_experiments.values()),
"active": sum(1 for e in _experiments.values() if e["status"] == "active"),
}
@router.get("/experiment/{experiment_id}")
async def get_experiment(experiment_id: str):
if experiment_id not in _experiments:
return {"error": "Experiment not found"}
exp = _experiments[experiment_id]
results = _results.get(experiment_id, [])
return {
**exp,
"total_trials": len(results),
"results": _summarize_results(results, exp["variants"]),
}
def _summarize_results(results: list, variants: list) -> dict:
counts = dict.fromkeys(variants, 0)
correct = dict.fromkeys(variants, 0)
for r in results:
v = r["variant"]
if v in counts:
counts[v] += 1
if r["correct"]:
correct[v] += 1
return {
v: {"trials": counts[v], "correct": correct[v], "accuracy": round(correct[v] / max(counts[v], 1), 3)}
for v in variants
}