"""Exact maximum-distribution and percentile calculations for hypothetical independent and perfectly shared latencies; no production-service measurements.
Run with Python 3.10+; standard library only. Writes results.json in the current directory.
"""
import math

worker_slow_probability = 0.01
mean_ms = 10.0
target = 0.99

def independent_p99(workers):
    component_cdf = target ** (1.0 / workers)
    latency = -mean_ms * math.log1p(-component_cdf)
    recovered = (1.0 - math.exp(-latency / mean_ms)) ** workers
    assert abs(recovered - target) < 1e-10
    return latency, component_cdf

shared_p99 = -mean_ms * math.log1p(-target)
for workers in [1, 10, 100, 1000]:
    any_slow = 1.0 - (1.0 - worker_slow_probability) ** workers
    latency, component_cdf = independent_p99(workers)
    print(f"n={workers:4d} independent_any_slow={any_slow:.6f} "
          f"shared_any_slow={worker_slow_probability:.6f}")
    print(f"  exponential_p99_ms: independent={latency:.3f} "
          f"shared={shared_p99:.3f}; required_component_CDF={component_cdf:.8f}")

single, _ = independent_p99(1)
assert abs(single - shared_p99) < 1e-12
print("CDF inversion and n=1 checks: passed")

# Extended experiment: deterministic parameter sweep and invariants.
sweep=[]
for rho in [0.,.25,.5,.75,1.]:
    for workers in [1,2,5,10,20,50,100,200,500,1000]:
        slow=rho*.01+(1-rho)*(1-.99**workers)
        # Mixture: with probability rho use one common latency, otherwise independent workers.
        lo,hi=0.,1000.
        for _ in range(100):
            mid=(lo+hi)/2;f=1-math.exp(-mid/10)
            cdf=rho*f+(1-rho)*f**workers
            if cdf<.99:lo=mid
            else:hi=mid
        p99=(lo+hi)/2;f=1-math.exp(-p99/10)
        assert abs(rho*f+(1-rho)*f**workers-.99)<1e-10
        sweep.append(dict(shared_mixture_weight=rho,workers=workers,any_slow_probability=slow,p99_ms=p99))
data=dict(dependence_sweep=sweep,worker_slow_probability=.01,mean_worker_latency_ms=10,
          mixture_definition='With probability rho all workers share one latency draw; otherwise all draws are independent. Marginals are unchanged.')
print('50 mixture cases inverted by bisection; each reconstructed service CDF equals 0.99 within 1e−10.')

import json
from pathlib import Path
Path("results.json").write_text(json.dumps(data,indent=2,allow_nan=False)+"\n",encoding="utf-8")
