from __future__ import annotations
import argparse
import concurrent.futures
import json
import math
import threading
import time
import urllib.error
import urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from typing import Any
import omega_cognitive_kernel_python as ok
class RateLimitedUpstream:
def __init__(self) -> None:
self._lock = threading.Lock()
self._inflight = 0
self.capacity = 4
self.base_latency_s = 0.015
self.overload_latency_s = 0.055
upstream = self
class Handler(BaseHTTPRequestHandler):
def do_GET(self) -> None: with upstream._lock:
upstream._inflight += 1
current = upstream._inflight
cap = upstream.capacity
try:
if current > cap:
time.sleep(upstream.overload_latency_s)
self.send_response(429)
self.send_header("Retry-After", "0.05")
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(b'{"error":"rate_limited"}')
else:
time.sleep(upstream.base_latency_s)
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(b'{"ok":true}')
finally:
with upstream._lock:
upstream._inflight -= 1
def log_message(self, format: str, *args: Any) -> None: return
self._server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
self.port = self._server.server_address[1]
self._thread = threading.Thread(target=self._server.serve_forever, daemon=True)
self._thread.start()
@property
def url(self) -> str:
return f"http://127.0.0.1:{self.port}/v1/tool"
def close(self) -> None:
self._server.shutdown()
self._server.server_close()
def percentile(values: list[float], pct: float) -> float:
if not values:
return 0.0
ordered = sorted(values)
idx = min(len(ordered) - 1, max(0, math.ceil(pct * len(ordered)) - 1))
return ordered[idx]
def send_one_request(url: str, retry_backoff_ms: float) -> tuple[int, float, int]:
t0 = time.perf_counter()
throttles = 0
for attempt in range(2):
try:
with urllib.request.urlopen(url, timeout=2.0) as resp:
resp.read()
elapsed_ms = (time.perf_counter() - t0) * 1000.0
return resp.status, elapsed_ms, throttles
except urllib.error.HTTPError as exc:
exc.read()
if exc.code == 429:
throttles += 1
if attempt == 0:
time.sleep(retry_backoff_ms / 1000.0)
continue
elapsed_ms = (time.perf_counter() - t0) * 1000.0
return exc.code, elapsed_ms, throttles
return 429, (time.perf_counter() - t0) * 1000.0, throttles
def capacity_for_round(round_idx: int) -> int:
if round_idx <= 6:
return 4
if round_idx <= 16:
return 2
return 3
def candidate_for_observation(
current: dict[str, float],
throttle_rate: float,
p95_ms: float,
clean_streak: int,
) -> dict[str, float] | None:
conc = current["max_concurrency"]
backoff = current["retry_backoff_ms"]
if throttle_rate >= 0.15 or p95_ms >= 60.0:
next_conc = max(1.0, conc - 1.0)
next_backoff = min(80.0, backoff + 15.0)
if next_conc != conc or next_backoff != backoff:
return {"max_concurrency": next_conc, "retry_backoff_ms": next_backoff}
elif clean_streak >= 3 and throttle_rate == 0.0 and p95_ms < 35.0 and conc < 4.0:
next_conc = min(4.0, conc + 1.0)
next_backoff = max(40.0, backoff - 10.0)
if next_conc != conc or next_backoff != backoff:
return {"max_concurrency": next_conc, "retry_backoff_ms": next_backoff}
return None
def run_arm(arm: str, rounds: int = 24, batch_size: int = 8) -> dict[str, Any]:
baseline = {"max_concurrency": 4.0, "retry_backoff_ms": 40.0}
host_params = dict(baseline)
upstream = RateLimitedUpstream()
total_ok = 0
total_final_429 = 0
total_429_events = 0
latencies_ms: list[float] = []
proposals_emitted = 0
proposals_settled = 0
applied_ids: set[str] = set()
clean_streak = 0
ctx = (
ok.AdaptiveSession.open_active(baseline)
if arm == "active"
else ok.AdaptiveSession.open_shadow(baseline)
)
try:
with ctx as session:
for r in range(1, rounds + 1):
upstream.capacity = capacity_for_round(r)
workers = max(1, int(round(host_params["max_concurrency"])))
backoff_ms = float(host_params["retry_backoff_ms"])
round_latencies: list[float] = []
round_429_events = 0
round_ok = 0
with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as pool:
futures = [
pool.submit(send_one_request, upstream.url, backoff_ms)
for _ in range(batch_size)
]
for fut in concurrent.futures.as_completed(futures):
status, elapsed_ms, throttles = fut.result()
round_latencies.append(elapsed_ms)
round_429_events += throttles
if status == 200:
round_ok += 1
elif status == 429:
total_final_429 += 1
total_ok += round_ok
total_429_events += round_429_events
latencies_ms.extend(round_latencies)
throttle_rate = round_429_events / max(1, batch_size)
round_p95 = percentile(round_latencies, 0.95)
clean_streak = clean_streak + 1 if round_429_events == 0 else 0
candidate = candidate_for_observation(
host_params, throttle_rate, round_p95, clean_streak
)
if candidate is None:
continue
resp = json.loads(
session.propose(
request_id=f"{arm}-req-{r}",
proposal_id=f"{arm}-prop-{r}",
request_digest=f"{arm}-digest-{r}-cap{upstream.capacity}",
requested_mode=arm,
candidate_params=candidate,
)
)
decision = resp["decision"]
if decision in ("active_proposal", "shadow_proposal"):
proposals_emitted += 1
if arm == "active" and decision == "active_proposal":
pid = resp["proposal_id"]
if pid not in applied_ids:
host_params = dict(resp["candidate_snapshot"]["params"])
applied_ids.add(pid)
session.acknowledge_applied(
proposal_id=pid,
execution_id=f"{arm}-exec-{r}",
applied_params=host_params,
)
probe_workers = max(1, int(round(host_params["max_concurrency"])))
probe_backoff = float(host_params["retry_backoff_ms"])
probe_429 = 0
with concurrent.futures.ThreadPoolExecutor(max_workers=probe_workers) as pool:
for fut in concurrent.futures.as_completed(
[pool.submit(send_one_request, upstream.url, probe_backoff) for _ in range(4)]
):
_, _, t_cnt = fut.result()
probe_429 += t_cnt
probe_rate = probe_429 / 4.0
reward = max(-1.0, min(1.0, 1.0 - probe_rate - 0.5 * max(0.0, probe_rate - throttle_rate)))
fb = json.loads(
session.feedback_completed(
feedback_id=f"{arm}-fb-{r}",
proposal_id=pid,
execution_id=f"{arm}-exec-{r}",
reward=reward,
error_delta=max(0.0, probe_rate),
risk_delta=max(0.0, probe_rate - throttle_rate),
)
)
if fb.get("state") == "settled":
proposals_settled += 1
recovery = json.loads(session.recommend_recovery(baseline))
finally:
upstream.close()
total_requests = rounds * batch_size
return {
"arm": arm,
"rounds": rounds,
"total_requests": total_requests,
"http_200_count": total_ok,
"http_200_rate": round(total_ok / total_requests, 4),
"final_429_count": total_final_429,
"total_429_events": total_429_events,
"throttle_event_rate": round(total_429_events / total_requests, 4),
"p50_latency_ms": round(percentile(latencies_ms, 0.50), 2),
"p95_latency_ms": round(percentile(latencies_ms, 0.95), 2),
"proposals_emitted": proposals_emitted,
"proposals_settled": proposals_settled,
"final_params": host_params,
"recovery_next_version": recovery.get("next_candidate_version"),
"recovery_params": recovery.get("recovery_params"),
}
def main() -> None:
parser = argparse.ArgumentParser(description="HTTP 429 guardrail Shadow vs Active demo")
parser.add_argument("--json", action="store_true", help="Emit JSON summary")
args = parser.parse_args()
shadow = run_arm("shadow")
active = run_arm("active")
summary = {
"workload": "local_http_429_regime_shift_4_to_2_to_3",
"shadow": shadow,
"active": active,
"delta": {
"http_200_rate_gain": round(active["http_200_rate"] - shadow["http_200_rate"], 4),
"throttle_event_reduction": shadow["total_429_events"] - active["total_429_events"],
"p95_latency_ms_change": round(active["p95_latency_ms"] - shadow["p95_latency_ms"], 2),
},
}
if args.json:
print(json.dumps(summary, indent=2))
return
print("HTTP 429 Guardrail Comparison (Capacity 4 -> 2 -> 3, 24 rounds x 8 reqs = 192 reqs/arm)")
print("-" * 86)
print(f"{'Arm':<10} {'HTTP 200':>10} {'Final 429':>10} {'429 Events':>11} {'P50 (ms)':>10} {'P95 (ms)':>10} {'Settled':>9}")
for row in (shadow, active):
print(
f"{row['arm']:<10} "
f"{row['http_200_rate']*100:>9.1f}% "
f"{row['final_429_count']:>10d} "
f"{row['total_429_events']:>11d} "
f"{row['p50_latency_ms']:>10.1f} "
f"{row['p95_latency_ms']:>10.1f} "
f"{row['proposals_settled']:>9d}"
)
print("-" * 86)
print(
f"Active vs Shadow: 429 events reduced by {summary['delta']['throttle_event_reduction']}, "
f"P95 latency delta {summary['delta']['p95_latency_ms_change']:+.1f} ms"
)
if __name__ == "__main__":
main()